{"version":3,"sources":["../../../node_modules/.pnpm/tsup@8.5.1_jiti@1.21.7_postcss@8.5.15_tsx@4.22.4_typescript@5.9.3_yaml@2.9.0/node_modules/tsup/assets/esm_shims.js","../src/holo-reconstruct-export.ts","../src/holo-reconstruct-point-assets.ts","../src/holo-video-ingest.ts","../src/holo-reconstruct-sessions.ts","../src/capture-consent.ts","../src/holomap-mcp-tools.ts","../src/graph-tools.ts","../src/ide-tools.ts","../src/postgres-pool-options.ts","../src/holokey-resolver.ts","../src/ollama-client.ts","../src/brittney-lite.ts","../src/self-improve-tools.ts","../src/gltf-import-tools.ts","../src/generate-mesh-tools.ts","../src/edit-holo-tools.ts","../src/wisdom-gotcha-tools.ts","../src/receipt-query-tools.ts","../src/service-contract-tools.ts","../src/fairness-mcp-tools.ts","../src/validation-tools.ts","../src/workflow-memory.ts","../src/agent-orchestration-tools.ts","../../core/src/compiler/identity/JwkThumbprint.ts","../../core/src/compiler/identity/AgentIdentity.ts","../../core/src/compiler/identity/CapabilityToken.ts","../../core/src/errors/safeJsonParse.ts","../../core/src/compiler/identity/CapabilityTokenIssuer.ts","../../core/src/compiler/identity/HybridCryptoProvider.ts","../../core/src/compiler/identity/HybridSigner.ts","../src/agent-identity-tools.ts","../src/observability-tools.ts","../../plugins/energy-grid-plugin/src/index.ts","../../plugins/energy-grid-plugin/src/runtime.ts","../../plugins/fitness-wellness-plugin/src/fitnesssolver.ts","../../plugins/fitness-wellness-plugin/src/runtime.ts","../../plugins/travel-hospitality-plugin/src/revenuemanagement.ts","../../plugins/travel-hospitality-plugin/src/runtime.ts","../src/domain-plugin-runtime.ts","../src/plugin-management-tools.ts","../src/holoshell-download-recovery-tools.ts","../src/economy-tools.ts","../src/api-docs-generator.ts","../../core/src/interop/InteropBindingGenerator.ts","../../cli/src/workspace/WorkspaceManager.ts","../src/workspace-manager-bridge.ts","../src/generators.ts","../src/training-generators.ts","../src/renderer.ts","../src/documentation.ts","../src/examples-catalog.ts","../src/security/sandbox-policy.ts","../src/security/fork-sandbox-gate.ts","../src/security/tool-scopes.ts","../src/PluginManager.ts","../src/holomesh/identity/audit-log.ts","../src/holomesh/identity/vault-lease-registry.ts","../src/absorb-provenance-tools.ts","../src/browser/chromium-executable.ts","../src/browser/BrowserPool.ts","../src/browser/fara-dispatcher.ts","../src/browser/browser-tools.ts","../src/tooling-discovery-tools.ts","../src/oracle-handler.ts","../src/oracle-mcp-tools.ts","../src/spatial-mcp-tools.ts","../src/holomesh/signing/signer.ts","../src/holomesh/signing/chain-anchor.ts","../src/holomesh/agent-negotiation.ts","../src/negotiation-mcp-tools.ts","../src/hologram-depth-estimator.ts","../src/hologram-renderer.ts","../src/hologram-worker-client.ts","../src/hologram-holomesh-send.ts","../src/hologram-bundle-client.ts","../src/holo-portal-intent.ts","../src/networking-tools.ts","../src/hologram-mcp-tools.ts","../src/holotwin-mcp-tools.ts","../src/holotune-mcp-tools.ts","../src/tools/estimate_task_duration.ts","../src/tools/kolmogorov_task_score.ts","../src/critic-handler.ts","../src/founder-handler.ts","../src/daemon-emergence-store.ts","../src/daemon-lifecycle-tools.ts","../src/premortem-handler.ts","../src/trait-categories-from-core.ts","../src/protocol-tools.ts","../src/holomesh/request-signing.ts","../src/holomesh/identity/attestation-registry.ts","../src/holomesh/identity/dual-signature-envelope.ts","../src/holomesh/identity/signing-middleware.ts","../src/policy/PolicyInterceptor.ts","../src/secrets-broker-handler.ts","../src/world-render-tools.ts","../src/robot-ai-mcp-tools.ts","../src/holomesh/mesh-tool-registry.ts","../src/holomesh/export-session.ts","../src/holomesh/identity/token-ledger.ts","../src/holomesh/postgres-pool-options.ts","../src/holomesh/team-store.ts","../src/holomesh/state-store.ts","../src/holomesh/player-store.ts","../src/holomesh/invite-store.ts","../src/holomesh/geo-anchor-store.ts","../src/holomesh/state.ts","../src/conformance/artifact-admission-gate.ts","../../core/src/care/CareField.ts","../src/security/hololand-fork-admission-gate.ts","../src/hololand-mcp-tools.ts","../src/code-health-tools.ts","../src/simulation-tools.ts","../src/simulation-billing-tools.ts","../src/holomesh/types.ts","../src/holomesh/wallet-auth.ts","../src/holomesh/discovery.ts","../src/holomesh/orchestrator-client.ts","../src/holomesh/crdt-sync.ts","../src/holomesh/messaging.ts","../src/holomesh/notifications.ts","../src/holomesh/threads.ts","../src/holomesh/search.ts","../src/holomesh/team-room-sse.ts","../src/holomesh/sse-edge-headers.ts","../src/holomesh/team-room.ts","../src/holomesh/mode-provenance.ts","../src/holomesh/auth-utils.ts","../src/holomesh/utils.ts","../src/holomesh/board-tools.ts","../src/holomesh/agent/shared-traits.ts","../src/holomesh/agent/scout-profile.ts","../src/holomesh/agent/team-agents.ts","../src/holomesh/agent/team-coordinator.ts","../src/holomesh/team-agent-tools.ts","../src/holomesh/team-formation.ts","../src/holomesh/team-formation-tools.ts","../src/holomesh/agent-capability-tools.ts","../src/holomesh/sovereign-tools.ts","../src/holomesh/twin-earth-federation.ts","../src/holomesh/moltbook-broadcast-context.ts","../src/moltbook/moltbook-post.ts","../src/holomesh/holomesh-tools.ts","../src/holomesh/HoloMeshSignaler.ts","../src/holomesh/consolidation-bridge.ts","../src/holomesh/index.ts","../src/x402-settlement-adapter.ts","../src/trait-tools.ts","../src/tools/rig_match_skeleton.ts","../../cli/src/importers/mesh-shape.ts","../../cli/src/importers/gltf-importer.ts","../../cli/src/traits.ts","../../cli/src/importers/text-to-3d-importer.ts","../src/handlers.ts","../src/developer-tools.ts","../src/holo-ci-tools.ts","../src/schema-mapper.ts","../src/audit-tools.ts","../src/alphafold-tools.ts","../src/compiler-tools.ts","../src/snapshot-tools.ts","../src/monitoring-tools.ts","../src/holotest-tools.ts","../src/refactor-codegen-tools.ts","../src/critic-tools.ts","../src/founder-tools.ts","../src/premortem-tools.ts","../src/secrets-broker-tools.ts","../src/holo-tunnel-tools.ts","../src/memory-tools.ts","../src/from-scratch-mcp-tools.ts","../src/tools.ts","../src/security/tenant-auth.ts","../src/security/github-auth.ts","../src/cli.ts","../src/index.ts","../src/utils/load-env.ts","../src/grpo-tools.ts","../src/compute-trace-tools.ts","../src/compute-trace-store.ts","../src/hologram-content-tools.ts","../src/skill-resources.ts","../src/tool-call-gate.ts","../src/tool-call-checks.ts","../src/holomesh/agent/loader.ts","../src/server-sizing.ts","../src/a2a.ts","../src/security/index.ts","../src/security/oauth21.ts","../src/auth/oauth2-provider.ts","../src/auth/token-store.ts","../src/security/gates.ts","../src/security/audit-log.ts","../src/security/bypass-detection.ts"],"sourcesContent":["// Shim globals in esm bundle\nimport path from 'node:path'\nimport { fileURLToPath } from 'node:url'\n\nconst getFilename = () => fileURLToPath(import.meta.url)\nconst getDirname = () => path.dirname(getFilename())\n\nexport const __dirname = /* @__PURE__ */ getDirname()\nexport const __filename = /* @__PURE__ */ getFilename()\n","/**\n * Turn a HoloMap ReconstructionManifest into a .holo composition (bounds + anchor)\n * and run it through ExportManager (same path as holo_compile_to_target).\n */\n\nimport { getExportManager, parseHolo } from '@holoscript/core';\nimport type { ExportTarget, HolomapPointCloudPayload } from '@holoscript/core/compiler';\nimport type { ReconstructionManifest } from '@holoscript/core/reconstruction';\nimport { Buffer } from 'node:buffer';\n\nconst TARGET_ALIASES: Record<string, ExportTarget> = {\n  unity: 'unity',\n  godot: 'godot',\n  usd: 'usd',\n  'usd-physics': 'usd',\n  usdz: 'usdz',\n  unreal: 'unreal',\n  'unreal-engine': 'unreal',\n  webgpu: 'webgpu',\n  wasm: 'wasm',\n  urdf: 'urdf',\n  sdf: 'sdf',\n  '3dgs': '3dgs',\n  'gaussian-splatting': '3dgs',\n  gaussian_splatting: '3dgs',\n  'khr-gaussian-splatting': '3dgs',\n};\n\nfunction fmtNum(n: number): string {\n  const r = Math.round(n * 10_000) / 10_000;\n  if (Number.isInteger(r)) return String(r);\n  return String(r);\n}\n\nexport function normalizeReconstructExportTarget(raw: string): ExportTarget {\n  const key = raw.trim().toLowerCase();\n  if (TARGET_ALIASES[key]) return TARGET_ALIASES[key];\n\n  getExportManager({ useMemoryMonitoring: false });\n  const supported = getExportManager().getSupportedTargets();\n  if (supported.includes(key as ExportTarget)) return key as ExportTarget;\n\n  throw new Error(\n    `holo_reconstruct_export: unsupported target \"${raw}\". Common: unity, godot, usd, unreal, webgpu, wasm, 3dgs.`\n  );\n}\n\n/** Composition derived from manifest bounds, counts, and contract fingerprint (compilers emit provenance). */\nexport function holoStubSourceFromManifest(\n  m: ReconstructionManifest,\n  boundsOverride?: { min: [number, number, number]; max: [number, number, number] }\n): string {\n  const id = m.replayHash.replace(/[^a-zA-Z0-9_]/g, '_').slice(0, 48) || 'holomap';\n  const b = boundsOverride ?? m.bounds;\n  const [minx, miny, minz] = b.min;\n  const [maxx, maxy, maxz] = b.max;\n  const cx = (minx + maxx) / 2;\n  const cy = (miny + maxy) / 2;\n  const cz = (minz + maxz) / 2;\n  const sx = Math.max(0.05, maxx - minx);\n  const sy = Math.max(0.05, maxy - miny);\n  const sz = Math.max(0.05, maxz - minz);\n  const lift = Math.min(sy, 2) * 0.2;\n\n  return `\ncomposition \"HoloMapExport_${id}_f${m.frameCount}_p${m.pointCount}\" {\n  environment {\n    skybox: \"neutral\"\n  }\n\n  object \"holomap_room_bounds\" {\n    geometry: \"box\"\n    position: [${fmtNum(cx)}, ${fmtNum(cy)}, ${fmtNum(cz)}]\n    scale: [${fmtNum(sx)}, ${fmtNum(sy)}, ${fmtNum(sz)}]\n  }\n\n  object \"holomap_anchor\" {\n    geometry: \"sphere\"\n    position: [${fmtNum(cx)}, ${fmtNum(cy + lift)}, ${fmtNum(cz)}]\n  }\n}\n`.trim();\n}\n\n/** Binary-packed cloud for Unity/WebGPU exporters (same cap as PLY aggregation). */\nexport function holomapPayloadFromAggregatedPoints(\n  positions: number[],\n  colors: number[]\n): HolomapPointCloudPayload | undefined {\n  const n = Math.min(Math.floor(positions.length / 3), Math.floor(colors.length / 3));\n  if (n < 1) return undefined;\n  const pos = new Float32Array(n * 3);\n  const col = new Uint8Array(n * 3);\n  for (let i = 0; i < n; i++) {\n    const b = i * 3;\n    pos[b] = positions[b];\n    pos[b + 1] = positions[b + 1];\n    pos[b + 2] = positions[b + 2];\n    col[b] = colors[b];\n    col[b + 1] = colors[b + 1];\n    col[b + 2] = colors[b + 2];\n  }\n  return {\n    positionsB64: Buffer.from(pos.buffer, pos.byteOffset, pos.byteLength).toString('base64'),\n    colorsB64: Buffer.from(col.buffer, col.byteOffset, col.byteLength).toString('base64'),\n    pointCount: n,\n  };\n}\n\nexport async function compileManifestToTarget(\n  manifest: ReconstructionManifest,\n  target: string,\n  boundsOverride?: { min: [number, number, number]; max: [number, number, number] },\n  holomapPointCloud?: HolomapPointCloudPayload\n): Promise<{ exportTarget: ExportTarget; output: string; usedFallback: boolean }> {\n  const exportTarget = normalizeReconstructExportTarget(target);\n  const src = holoStubSourceFromManifest(manifest, boundsOverride);\n  const parsed = parseHolo(src);\n  if (!parsed.success || !parsed.ast) {\n    throw new Error(\n      `holo_reconstruct_export: internal parse failed: ${parsed.errors?.[0]?.message ?? 'unknown'}`\n    );\n  }\n\n  getExportManager({ useMemoryMonitoring: false });\n  const exportManager = getExportManager();\n  const compilerOptions: Record<string, unknown> = {\n    provenanceHash: manifest.simulationContract.replayFingerprint,\n  };\n  if (holomapPointCloud) {\n    compilerOptions.holomapPointCloud = holomapPointCloud;\n  }\n  const agentToken = process.env.HOLOSCRIPT_MCP_AGENT_TOKEN?.trim() ?? '';\n  const result = await exportManager.export(exportTarget, parsed.ast, {\n    // Empty string skips compiler RBAC (same as createTestCompilerToken); set env for real JWT.\n    agentToken,\n    compilerOptions,\n  });\n\n  if (!result.success) {\n    throw new Error(result.error?.message || `Export to ${exportTarget} failed`);\n  }\n\n  const output =\n    typeof result.output === 'string'\n      ? result.output\n      : result.output != null\n        ? JSON.stringify(result.output)\n        : '';\n\n  return {\n    exportTarget,\n    output,\n    usedFallback: result.usedFallback || false,\n  };\n}\n","/**\n * Aggregate per-step HoloMap points for export-sidecar artifacts (PLY, trajectory JSON).\n */\n\nimport type { ReconstructionManifest, ReconstructionStep } from '@holoscript/core/reconstruction';\n\nexport type AggregatedScanGeometry = {\n  positions: number[];\n  colors: number[];\n  poses: Array<{\n    frameIndex: number;\n    position: [number, number, number];\n    rotation: [number, number, number, number];\n    confidence: number;\n  }>;\n};\n\nexport function emptyAggregate(): AggregatedScanGeometry {\n  return { positions: [], colors: [], poses: [] };\n}\n\nexport function appendStepToAggregate(\n  agg: AggregatedScanGeometry,\n  step: ReconstructionStep,\n  maxPoints: number\n): void {\n  const pos = step.points.positions;\n  const col = step.points.colors;\n  const n = pos.length / 3;\n  for (let i = 0; i < n; i++) {\n    if (agg.positions.length / 3 >= maxPoints) return;\n    const b = i * 3;\n    agg.positions.push(pos[b], pos[b + 1], pos[b + 2]);\n    if (col && col.length >= n * 3) {\n      agg.colors.push(col[b], col[b + 1], col[b + 2]);\n    } else {\n      agg.colors.push(200, 200, 200);\n    }\n  }\n  agg.poses.push({\n    frameIndex: step.frame.index,\n    position: [...step.pose.position] as [number, number, number],\n    rotation: [...step.pose.rotation] as [number, number, number, number],\n    confidence: step.pose.confidence,\n  });\n}\n\nexport function boundsFromPositions(positions: number[]):\n  | {\n      min: [number, number, number];\n      max: [number, number, number];\n    }\n  | undefined {\n  const nv = positions.length / 3;\n  if (nv < 1) return undefined;\n  let minx = positions[0];\n  let miny = positions[1];\n  let minz = positions[2];\n  let maxx = minx;\n  let maxy = miny;\n  let maxz = minz;\n  for (let i = 1; i < nv; i++) {\n    const b = i * 3;\n    const x = positions[b];\n    const y = positions[b + 1];\n    const z = positions[b + 2];\n    minx = Math.min(minx, x);\n    miny = Math.min(miny, y);\n    minz = Math.min(minz, z);\n    maxx = Math.max(maxx, x);\n    maxy = Math.max(maxy, y);\n    maxz = Math.max(maxz, z);\n  }\n  return {\n    min: [minx, miny, minz],\n    max: [maxx, maxy, maxz],\n  };\n}\n\n/** ASCII PLY (x,y,z + uchar rgb) for Unity / Blender / MeshLab / three.js loaders. */\nexport function encodePlyAscii(positions: number[], colors: number[]): string {\n  const n = Math.min(positions.length / 3, colors.length / 3);\n  const lines: string[] = [\n    'ply',\n    'format ascii 1.0',\n    `element vertex ${n}`,\n    'property float x',\n    'property float y',\n    'property float z',\n    'property uchar red',\n    'property uchar green',\n    'property uchar blue',\n    'end_header',\n  ];\n  for (let i = 0; i < n; i++) {\n    const b = i * 3;\n    const x = positions[b];\n    const y = positions[b + 1];\n    const z = positions[b + 2];\n    const r = Math.max(0, Math.min(255, Math.round(colors[b])));\n    const g = Math.max(0, Math.min(255, Math.round(colors[b + 1])));\n    const cc = Math.max(0, Math.min(255, Math.round(colors[b + 2])));\n    lines.push(`${x} ${y} ${z} ${r} ${g} ${cc}`);\n  }\n  return `${lines.join('\\n')}\\n`;\n}\n\nexport function encodeTrajectoryJson(poses: AggregatedScanGeometry['poses']): string {\n  return `${JSON.stringify({ version: 1, poses }, null, 2)}\\n`;\n}\n\n/** Prefer a tight AABB from sampled points; fall back to manifest bounds. */\nexport function effectiveBoundsForExport(\n  m: ReconstructionManifest,\n  fromPoints?: { min: [number, number, number]; max: [number, number, number] }\n): { min: [number, number, number]; max: [number, number, number] } {\n  return fromPoints ?? m.bounds;\n}\n","/**\n * Download video URLs and decode RGB frames via ffmpeg (PATH or ffmpeg-static).\n * HTTP(S) downloads stream to disk with size and time limits.\n */\n\nimport { spawn, spawnSync } from 'node:child_process';\nimport { createHash, randomBytes } from 'node:crypto';\nimport { createWriteStream } from 'node:fs';\nimport { promises as fs } from 'node:fs';\nimport { tmpdir } from 'node:os';\nimport { join } from 'node:path';\nimport { Readable } from 'node:stream';\nimport { finished } from 'node:stream/promises';\nimport { once } from 'node:events';\nimport { fileURLToPath } from 'node:url';\n\nconst DEFAULT_MAX_VIDEO_BYTES = 256 * 1024 * 1024;\nconst DEFAULT_FETCH_TIMEOUT_MS = 120_000;\n\n/** Limits demuxer probe work so broken/exotic containers are less likely to stall ffmpeg. */\nfunction ffmpegInputProbeArgs(): string[] {\n  const analyzeduration = process.env.HOLOMAP_MCP_FFMPEG_ANALYZE_DURATION ?? '5000000';\n  const probesize = process.env.HOLOMAP_MCP_FFMPEG_PROBE_SIZE ?? '32M';\n  return ['-analyzeduration', analyzeduration, '-probesize', probesize];\n}\n\nexport function resolveFfprobeBinary(): string {\n  const envPath = process.env.FFPROBE_PATH?.trim();\n  if (envPath) return envPath;\n  return 'ffprobe';\n}\n\n/**\n * Best-effort video stream probe (codec name). Fails closed when ffprobe missing or file unreadable.\n */\nexport function ffprobeVideoCodecSync(\n  videoPath: string,\n  timeoutMs?: number\n): { ok: true; codec: string } | { ok: false; error: string } {\n  const t = timeoutMs ?? Number(process.env.HOLOMAP_MCP_FFPROBE_TIMEOUT_MS ?? 15_000);\n  const ffprobe = resolveFfprobeBinary();\n  try {\n    const r = spawnSync(\n      ffprobe,\n      [\n        '-v',\n        'error',\n        '-select_streams',\n        'v:0',\n        '-show_entries',\n        'stream=codec_name',\n        '-of',\n        'default=nw=1:nk=1',\n        videoPath,\n      ],\n      { encoding: 'utf8', timeout: t }\n    );\n    if (r.status !== 0) {\n      return {\n        ok: false,\n        error: (r.stderr || r.stdout || 'ffprobe failed').toString().slice(-500),\n      };\n    }\n    const codec = (r.stdout || '').trim().split('\\n')[0]?.trim() ?? '';\n    if (!codec) {\n      return { ok: false, error: 'ffprobe: no video stream / codec' };\n    }\n    return { ok: true, codec };\n  } catch (e) {\n    return { ok: false, error: e instanceof Error ? e.message : String(e) };\n  }\n}\n\nexport function resolveFfmpegBinary(): string {\n  const envPath = process.env.FFMPEG_PATH?.trim();\n  if (envPath) return envPath;\n  try {\n    const ffmpegStatic = require('ffmpeg-static') as string | null | undefined;\n    if (typeof ffmpegStatic === 'string' && ffmpegStatic.length > 0) return ffmpegStatic;\n  } catch {\n    /* optional */\n  }\n  return 'ffmpeg';\n}\n\nexport async function fetchVideoToTempFile(videoUrl: string): Promise<{\n  path: string;\n  bytes: number;\n  sha256Hex: string;\n  cleanup: () => Promise<void>;\n}> {\n  const maxBytes = Number(process.env.HOLOMAP_MCP_MAX_VIDEO_BYTES ?? DEFAULT_MAX_VIDEO_BYTES);\n  const timeoutMs = Number(\n    process.env.HOLOMAP_MCP_FETCH_VIDEO_TIMEOUT_MS ?? DEFAULT_FETCH_TIMEOUT_MS\n  );\n\n  const dir = await fs.mkdtemp(join(tmpdir(), 'holomap-mcp-'));\n  const destPath = join(dir, `in-${randomBytes(8).toString('hex')}.bin`);\n  const hash = createHash('sha256');\n\n  const cleanup = async (): Promise<void> => {\n    await fs.rm(dir, { recursive: true, force: true });\n  };\n\n  if (videoUrl.startsWith('file:')) {\n    const filePath = fileURLToPath(videoUrl);\n    const buf = await fs.readFile(filePath);\n    if (buf.length > maxBytes) {\n      await cleanup();\n      throw new Error(\n        `holo_reconstruct_from_video: file exceeds HOLOMAP_MCP_MAX_VIDEO_BYTES (${maxBytes})`\n      );\n    }\n    hash.update(buf);\n    await fs.writeFile(destPath, buf);\n    return { path: destPath, bytes: buf.length, sha256Hex: hash.digest('hex'), cleanup };\n  }\n\n  const ac = new AbortController();\n  const timer = setTimeout(() => ac.abort(), timeoutMs);\n  let res: Response;\n  try {\n    res = await fetch(videoUrl, { signal: ac.signal });\n  } catch (e) {\n    clearTimeout(timer);\n    await cleanup();\n    if (e instanceof Error && e.name === 'AbortError') {\n      throw new Error(\n        `holo_reconstruct_from_video: fetch timed out after ${timeoutMs}ms (HOLOMAP_MCP_FETCH_VIDEO_TIMEOUT_MS)`\n      );\n    }\n    throw e;\n  } finally {\n    clearTimeout(timer);\n  }\n\n  if (!res.ok) {\n    await cleanup();\n    throw new Error(\n      `holo_reconstruct_from_video: failed to fetch video (${res.status} ${res.statusText})`\n    );\n  }\n  if (!res.body) {\n    await cleanup();\n    throw new Error('holo_reconstruct_from_video: empty response body');\n  }\n\n  const ws = createWriteStream(destPath);\n  let total = 0;\n\n  try {\n    const webBody = res.body as import('stream/web').ReadableStream<Uint8Array>;\n    const nodeReadable = Readable.fromWeb(webBody);\n    for await (const chunk of nodeReadable) {\n      const c = chunk as Buffer;\n      total += c.length;\n      if (total > maxBytes) {\n        ws.destroy();\n        await cleanup();\n        throw new Error(\n          `holo_reconstruct_from_video: download exceeds HOLOMAP_MCP_MAX_VIDEO_BYTES (${maxBytes})`\n        );\n      }\n      hash.update(c);\n      if (!ws.write(c)) {\n        await once(ws, 'drain');\n      }\n    }\n    ws.end();\n    await finished(ws);\n  } catch (e) {\n    ws.destroy();\n    await cleanup();\n    throw e;\n  }\n\n  return { path: destPath, bytes: total, sha256Hex: hash.digest('hex'), cleanup };\n}\n\n/**\n * Stream RGB24 frames WxHx3 at sampled fps (ffmpeg), capped at maxFrames.\n */\nexport async function ingestVideoRgbFrames(options: {\n  videoPath: string;\n  width: number;\n  height: number;\n  fps: number;\n  maxFrames: number;\n  ffmpegPath?: string;\n}): Promise<{ frames: Array<{ index: number; rgb: Uint8Array }>; ffmpegPath: string }> {\n  const probe = ffprobeVideoCodecSync(options.videoPath);\n  if (!probe.ok) {\n    throw new Error(\n      `holo_reconstruct_from_video: ffprobe failed (${probe.error}). Install ffmpeg/ffprobe or fix the input file.`\n    );\n  }\n\n  const ffmpegPath = options.ffmpegPath ?? resolveFfmpegBinary();\n  const args = [\n    '-hide_banner',\n    '-loglevel',\n    'error',\n    ...ffmpegInputProbeArgs(),\n    '-i',\n    options.videoPath,\n    '-vf',\n    `fps=${options.fps},scale=${options.width}:${options.height}`,\n    '-f',\n    'rawvideo',\n    '-pix_fmt',\n    'rgb24',\n    '-',\n  ];\n\n  const proc = spawn(ffmpegPath, args, { stdio: ['ignore', 'pipe', 'pipe'] });\n  const stderr: string[] = [];\n  proc.stderr?.on('data', (c: Buffer) => stderr.push(c.toString()));\n\n  const frameSize = options.width * options.height * 3;\n  const frames: Array<{ index: number; rgb: Uint8Array }> = [];\n  let buf = Buffer.alloc(0);\n  let index = 0;\n\n  await new Promise<void>((resolvePromise, rejectPromise) => {\n    proc.on('error', (err) => rejectPromise(err));\n    proc.stdout.on('data', (chunk: Buffer) => {\n      buf = Buffer.concat([buf, chunk]);\n      while (buf.length >= frameSize && index < options.maxFrames) {\n        const raw = buf.subarray(0, frameSize);\n        buf = buf.subarray(frameSize);\n        frames.push({ index, rgb: new Uint8Array(raw) });\n        index += 1;\n      }\n      if (index >= options.maxFrames) {\n        proc.stdout.destroy();\n        proc.kill('SIGKILL');\n      }\n    });\n    proc.on('close', (code, signal) => {\n      if (frames.length > 0 && (signal === 'SIGKILL' || code === 255 || code === 1)) {\n        resolvePromise();\n        return;\n      }\n      if (code !== 0 && frames.length === 0) {\n        rejectPromise(\n          new Error(\n            `ffmpeg exited ${code}: ${stderr.join('').slice(-800) || 'no stderr — is ffmpeg installed?'}`\n          )\n        );\n        return;\n      }\n      resolvePromise();\n    });\n  });\n\n  return { frames, ffmpegPath };\n}\n\nexport function ffmpegAvailableSync(ffmpegPath = resolveFfmpegBinary()): boolean {\n  try {\n    const r = spawnSync(ffmpegPath, ['-version'], { encoding: 'utf8', timeout: 8000 });\n    return r.status === 0;\n  } catch {\n    return false;\n  }\n}\n","/**\n * In-memory HoloMap reconstruction sessions for MCP tools.\n * Uses @holoscript/core HoloMapRuntime (CPU fused-attention fallback in Node).\n */\n\nimport { createHash, randomUUID } from 'node:crypto';\nimport {\n  createHoloMapRuntime,\n  HOLOMAP_DEFAULTS,\n  type HoloMapConfig,\n  type HoloMapRuntime,\n  type ReconstructionFrame,\n  type ReconstructionManifest,\n  type ReconstructionStep,\n} from '@holoscript/core/reconstruction';\n// HoloMap reconstruction decorator → trait mapping. Source of truth is\n// packages/core/src/traits/constants/holomap-reconstruction.ts; inlined\n// here because @holoscript/core's tsup build does NOT currently emit a\n// runtime entry for the constants subpath (only a hand-crafted .d.ts).\n// Keep these in lockstep — the contract test below covers all 3 single\n// + 1 trio decorator combinations.\ntype HolomapReconstructionTraitName =\n  | 'holomap_reconstruct'\n  | 'holomap_camera_trajectory'\n  | 'holomap_anchor_context'\n  | 'holomap_splat_output'\n  | 'holomap_drift_correction';\n\nconst HOLOMAP_DECORATOR_TO_TRAITS: Readonly<\n  Record<string, readonly HolomapReconstructionTraitName[]>\n> = Object.freeze({\n  reconstruction_source: [\n    'holomap_reconstruct',\n    'holomap_camera_trajectory',\n    'holomap_anchor_context',\n  ],\n  acceptance_video: ['holomap_reconstruct', 'holomap_splat_output'],\n  drift_corrected: ['holomap_drift_correction'],\n});\n\nfunction stripDecoratorPrefix(name: string): string {\n  return name.startsWith('@') ? name.slice(1) : name;\n}\n\nfunction isReconstructionDecorator(name: string): boolean {\n  return Object.prototype.hasOwnProperty.call(\n    HOLOMAP_DECORATOR_TO_TRAITS,\n    stripDecoratorPrefix(name)\n  );\n}\n\nfunction getReconstructionTraitsFromDecorators(\n  decoratorNames: readonly string[]\n): HolomapReconstructionTraitName[] {\n  const seen = new Set<HolomapReconstructionTraitName>();\n  const out: HolomapReconstructionTraitName[] = [];\n  for (const raw of decoratorNames) {\n    const stripped = stripDecoratorPrefix(raw);\n    const traits = HOLOMAP_DECORATOR_TO_TRAITS[stripped];\n    if (!traits) continue;\n    for (const t of traits) {\n      if (seen.has(t)) continue;\n      seen.add(t);\n      out.push(t);\n    }\n  }\n  return out;\n}\nimport {\n  compileManifestToTarget,\n  holomapPayloadFromAggregatedPoints,\n} from './holo-reconstruct-export';\nimport {\n  appendStepToAggregate,\n  boundsFromPositions,\n  emptyAggregate,\n  encodePlyAscii,\n  encodeTrajectoryJson,\n  effectiveBoundsForExport,\n  type AggregatedScanGeometry,\n} from './holo-reconstruct-point-assets';\nimport { fetchVideoToTempFile, ingestVideoRgbFrames } from './holo-video-ingest';\n\nconst DEFAULT_EXPORT_MAX_POINTS = 250_000;\n\nfunction maxExportPointsCap(): number {\n  const n = Number.parseInt(process.env.HOLOMAP_MCP_EXPORT_MAX_POINTS ?? '', 10);\n  if (Number.isFinite(n) && n > 100) return Math.min(n, 2_000_000);\n  return DEFAULT_EXPORT_MAX_POINTS;\n}\n\nexport type HoloReconstructMcpSession = {\n  runtime: HoloMapRuntime;\n  videoUrl: string;\n  captureProfile: 'room' | 'face';\n  lastStep?: ReconstructionStep;\n  finalizedManifest?: ReconstructionManifest;\n  aggregate: AggregatedScanGeometry;\n};\n\nconst sessions = new Map<string, HoloReconstructMcpSession>();\n\nexport function __resetHoloReconstructSessionsForTests(): void {\n  sessions.clear();\n}\n\nfunction hashVideoUrl(url: string): string {\n  return createHash('sha256').update(url, 'utf8').digest('hex');\n}\n\nfunction pickPartialHoloMapConfig(raw: unknown): Partial<HoloMapConfig> {\n  if (!raw || typeof raw !== 'object') return {};\n  const o = raw as Record<string, unknown>;\n  const p: Partial<HoloMapConfig> = {};\n  if (typeof o.modelHash === 'string') p.modelHash = o.modelHash;\n  if (typeof o.seed === 'number' && Number.isFinite(o.seed)) p.seed = o.seed;\n  if (o.inputResolution && typeof o.inputResolution === 'object') {\n    const ir = o.inputResolution as Record<string, unknown>;\n    if (typeof ir.width === 'number' && typeof ir.height === 'number') {\n      p.inputResolution = { width: ir.width, height: ir.height };\n    }\n  }\n  if (typeof o.targetFPS === 'number' && Number.isFinite(o.targetFPS)) p.targetFPS = o.targetFPS;\n  if (typeof o.maxSequenceLength === 'number' && Number.isFinite(o.maxSequenceLength)) {\n    p.maxSequenceLength = o.maxSequenceLength;\n  }\n  if (typeof o.cpuOffload === 'boolean') p.cpuOffload = o.cpuOffload;\n  if (\n    o.weightStrategy === 'distill' ||\n    o.weightStrategy === 'fine-tune' ||\n    o.weightStrategy === 'from-scratch'\n  ) {\n    p.weightStrategy = o.weightStrategy;\n  }\n  if (typeof o.allowCpuFallback === 'boolean') p.allowCpuFallback = o.allowCpuFallback;\n  if (typeof o.videoHash === 'string') p.videoHash = o.videoHash;\n  if (typeof o.weightCid === 'string' && o.weightCid.trim()) p.weightCid = o.weightCid.trim();\n  return p;\n}\n\nfunction pickIngestOptions(configArg: unknown): { ingestVideo: boolean; maxIngestFrames: number } {\n  let ingestVideo = process.env.HOLOMAP_MCP_INGEST_VIDEO !== '0';\n  let maxIngestFrames = Math.min(\n    500,\n    Math.max(1, Number.parseInt(process.env.HOLOMAP_MCP_MAX_FRAMES ?? '120', 10) || 120)\n  );\n  if (configArg && typeof configArg === 'object') {\n    const o = configArg as Record<string, unknown>;\n    if (typeof o.ingestVideo === 'boolean') ingestVideo = o.ingestVideo;\n    if (typeof o.maxIngestFrames === 'number' && Number.isFinite(o.maxIngestFrames)) {\n      maxIngestFrames = Math.min(500, Math.max(1, Math.floor(o.maxIngestFrames)));\n    }\n  }\n  return { ingestVideo, maxIngestFrames };\n}\n\nfunction pickCaptureProfile(configArg: unknown): 'room' | 'face' {\n  if (!configArg || typeof configArg !== 'object') return 'room';\n  const o = configArg as Record<string, unknown>;\n  return o.captureProfile === 'face' || o.scanKind === 'face' ? 'face' : 'room';\n}\n\n/**\n * Sprint-3 Phase 2: trait → MCP dispatch.\n *\n * Given the decorator names declared on a `.holo` Node, decide which\n * MCP session shape to spin up and what config tweaks the decorators\n * imply. The 3 HoloMap reconstruction decorators map onto two\n * orthogonal pieces of session config:\n *\n *   - `@reconstruction_source`  → full reconstruction pipeline\n *                                  (camera trajectory + anchor context).\n *   - `@acceptance_video`       → reconstruction + splat output (validated\n *                                  reconstruction, not just trajectory).\n *   - `@drift_corrected`        → pure post-processing flag; cannot drive\n *                                  a session on its own.\n *\n * Acceptance criterion (task_p0gl): an integration test must cover all\n * three single-decorator combos AND the trio. See\n * packages/mcp-server/src/__tests__/holo-reconstruct-dispatch.test.ts.\n */\nexport type ReconstructionDispatch =\n  | {\n      kind: 'no-session';\n      reason: 'no-decorators' | 'drift-only-needs-source';\n      resolvedTraits: HolomapReconstructionTraitName[];\n    }\n  | {\n      kind: 'video-session';\n      sessionConstructor: 'mcpStartReconstructFromVideo';\n      sessionFlags: {\n        emitTrajectory: boolean;\n        emitSplatOutput: boolean;\n        applyDriftCorrection: boolean;\n      };\n      resolvedTraits: HolomapReconstructionTraitName[];\n    };\n\nexport function dispatchReconstructionFromDecorators(\n  decoratorNames: readonly string[]\n): ReconstructionDispatch {\n  // Filter to only HoloMap reconstruction decorators; other families\n  // (motion, environment, etc.) are silently ignored, matching the\n  // contract of `getReconstructionTraitsFromDecorators`.\n  const ours = decoratorNames.filter((d) => isReconstructionDecorator(d));\n  if (ours.length === 0) {\n    return { kind: 'no-session', reason: 'no-decorators', resolvedTraits: [] };\n  }\n\n  const stripped = ours.map((d) => (d.startsWith('@') ? d.slice(1) : d));\n  const hasReconSource = stripped.includes('reconstruction_source');\n  const hasAcceptance = stripped.includes('acceptance_video');\n  const hasDrift = stripped.includes('drift_corrected');\n  const resolvedTraits = getReconstructionTraitsFromDecorators(decoratorNames);\n\n  // `@drift_corrected` alone is a post-processing marker — it cannot\n  // produce a session because it has no upstream pose source. Surface\n  // this as a structured no-session result rather than spinning up a\n  // half-configured runtime.\n  if (!hasReconSource && !hasAcceptance && hasDrift) {\n    return { kind: 'no-session', reason: 'drift-only-needs-source', resolvedTraits };\n  }\n\n  return {\n    kind: 'video-session',\n    sessionConstructor: 'mcpStartReconstructFromVideo',\n    sessionFlags: {\n      // Camera-trajectory output piggybacks on `@reconstruction_source`;\n      // `@acceptance_video` doesn't need it (it emits splats not poses).\n      emitTrajectory: hasReconSource,\n      emitSplatOutput: hasAcceptance,\n      applyDriftCorrection: hasDrift,\n    },\n    resolvedTraits,\n  };\n}\n\nexport async function mcpStartReconstructFromVideo(\n  videoUrl: string,\n  configArg: unknown\n): Promise<{\n  sessionId: string;\n  replayFingerprint: string;\n  framesIngested: number;\n  ingestMode: 'ffmpeg' | 'none';\n  captureProfile: 'room' | 'face';\n  videoBytes?: number;\n  ingestWarning?: string;\n}> {\n  const sessionId = randomUUID();\n  const runtime = createHoloMapRuntime();\n  const partial = pickPartialHoloMapConfig(configArg);\n  const captureProfile = pickCaptureProfile(configArg);\n  const cfg: HoloMapConfig = { ...HOLOMAP_DEFAULTS, ...partial };\n  const { ingestVideo, maxIngestFrames } = pickIngestOptions(configArg);\n\n  let framesIngested = 0;\n  let ingestMode: 'ffmpeg' | 'none' = 'none';\n  let videoBytes: number | undefined;\n  let ingestWarning: string | undefined;\n\n  const aggregate = emptyAggregate();\n  const pointCap = maxExportPointsCap();\n\n  if (ingestVideo) {\n    let cleanup: (() => Promise<void>) | undefined;\n    try {\n      const file = await fetchVideoToTempFile(videoUrl);\n      cleanup = file.cleanup;\n      videoBytes = file.bytes;\n      await runtime.init({\n        ...cfg,\n        videoHash: partial.videoHash ?? file.sha256Hex,\n        allowCpuFallback: partial.allowCpuFallback !== false,\n      });\n      try {\n        const fps = Math.max(1, Math.min(30, cfg.targetFPS));\n        const { frames } = await ingestVideoRgbFrames({\n          videoPath: file.path,\n          width: cfg.inputResolution.width,\n          height: cfg.inputResolution.height,\n          fps,\n          maxFrames: maxIngestFrames,\n        });\n        let lastStep: ReconstructionStep | undefined;\n        for (const f of frames) {\n          lastStep = await runtime.step({\n            index: f.index,\n            timestampMs: Math.round((f.index * 1000) / fps),\n            rgb: f.rgb,\n            width: cfg.inputResolution.width,\n            height: cfg.inputResolution.height,\n            stride: 3,\n          });\n          appendStepToAggregate(aggregate, lastStep, pointCap);\n          framesIngested += 1;\n        }\n        ingestMode = 'ffmpeg';\n        if (framesIngested === 0) {\n          ingestWarning =\n            'ffmpeg produced zero frames (unsupported codec, empty video, or decode error). Session is ready for holo_reconstruct_step.';\n        }\n        sessions.set(sessionId, { runtime, videoUrl, captureProfile, aggregate, lastStep });\n      } catch (ffErr) {\n        ingestWarning = ffErr instanceof Error ? ffErr.message : String(ffErr);\n        sessions.set(sessionId, { runtime, videoUrl, captureProfile, aggregate });\n      }\n    } catch (e) {\n      ingestWarning = e instanceof Error ? e.message : String(e);\n      await runtime.init({\n        ...cfg,\n        videoHash: partial.videoHash ?? hashVideoUrl(videoUrl),\n        allowCpuFallback: partial.allowCpuFallback !== false,\n      });\n      sessions.set(sessionId, { runtime, videoUrl, captureProfile, aggregate });\n    } finally {\n      if (cleanup) await cleanup();\n    }\n  } else {\n    await runtime.init({\n      ...cfg,\n      videoHash: partial.videoHash ?? hashVideoUrl(videoUrl),\n      allowCpuFallback: partial.allowCpuFallback !== false,\n    });\n    sessions.set(sessionId, { runtime, videoUrl, captureProfile, aggregate });\n  }\n\n  return {\n    sessionId,\n    replayFingerprint: runtime.replayHash(),\n    framesIngested,\n    ingestMode,\n    captureProfile,\n    videoBytes,\n    ingestWarning,\n  };\n}\n\nfunction getSessionOrThrow(sessionId: string): HoloReconstructMcpSession {\n  const s = sessions.get(sessionId);\n  if (!s) {\n    throw new Error(\n      `holo_reconstruct: unknown sessionId (create one with holo_reconstruct_from_video first)`\n    );\n  }\n  return s;\n}\n\nfunction requireOpenSession(sessionId: string): HoloReconstructMcpSession {\n  const s = getSessionOrThrow(sessionId);\n  if (s.finalizedManifest) {\n    throw new Error(`holo_reconstruct: session ${sessionId} is finalized; start a new session`);\n  }\n  return s;\n}\n\nfunction decodeFrame(\n  frameBase64: string,\n  frameIndex: number,\n  width: number,\n  height: number\n): ReconstructionFrame {\n  let buf: Buffer;\n  try {\n    buf = Buffer.from(frameBase64, 'base64');\n  } catch {\n    throw new Error('holo_reconstruct_step: frameBase64 is not valid base64');\n  }\n  const n3 = width * height * 3;\n  const n4 = width * height * 4;\n  let stride: 3 | 4;\n  if (buf.length === n4) stride = 4;\n  else if (buf.length === n3) stride = 3;\n  else {\n    throw new Error(\n      `holo_reconstruct_step: frame byte length ${buf.length} does not match width*height*3 (${n3}) or *4 (${n4})`\n    );\n  }\n  return {\n    index: frameIndex,\n    timestampMs: frameIndex * 33,\n    rgb: new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength),\n    width,\n    height,\n    stride,\n  };\n}\n\nexport async function mcpReconstructStep(\n  sessionId: string,\n  frameBase64: string,\n  frameIndex: number,\n  width: number,\n  height: number\n): Promise<{\n  ok: true;\n  frameIndex: number;\n  pose: ReconstructionStep['pose'];\n  pointCount: number;\n  trajectoryRevision: number;\n  anchorRevision: number;\n  // Scan-derived drift state exposed so callers/receipts can verify the\n  // derivation: drift accumulates geometry-derived inter-frame pose deltas\n  // over the capture, so it changes when the capture changes.\n  estimatedDriftMeters: number;\n  lastLoopClosureFrame: number;\n  trajectoryKeyframeCount: number;\n  // True when the runtime's deterministic frame-rate gate throttled this frame\n  // (capture fps > targetFPS): the frame was accepted by the API but produced no\n  // reconstruction step, so there is nothing to aggregate. Callers feeding frames\n  // denser than targetFPS will see throttled frames here rather than a crash.\n  throttled?: boolean;\n}> {\n  const state = requireOpenSession(sessionId);\n  const frame = decodeFrame(frameBase64, frameIndex, width, height);\n  const step = await state.runtime.step(frame);\n  if (step === null) {\n    // Throttled by the runtime's frame-rate gate (frame.timestamp too close to the\n    // last accepted frame for this session's targetFPS). Nothing to aggregate; return\n    // the last known trajectory/anchor state so callers can advance without crashing.\n    const prev = state.lastStep;\n    return {\n      ok: true,\n      throttled: true,\n      frameIndex,\n      pose: prev ? prev.pose : { position: [0, 0, 0], rotation: [0, 0, 0, 1], confidence: 0 },\n      pointCount: 0,\n      trajectoryRevision: prev ? prev.trajectory.revision : 0,\n      anchorRevision: prev ? prev.anchor.revision : 0,\n      estimatedDriftMeters: prev ? prev.trajectory.estimatedDriftMeters : 0,\n      lastLoopClosureFrame: prev ? prev.trajectory.lastLoopClosureFrame : -1,\n      trajectoryKeyframeCount: prev ? prev.trajectory.keyframes.length : 0,\n    };\n  }\n  state.lastStep = step;\n  appendStepToAggregate(state.aggregate, step, maxExportPointsCap());\n  return {\n    ok: true,\n    frameIndex: step.frame.index,\n    pose: step.pose,\n    pointCount: step.points.positions.length / 3,\n    trajectoryRevision: step.trajectory.revision,\n    anchorRevision: step.anchor.revision,\n    estimatedDriftMeters: step.trajectory.estimatedDriftMeters,\n    lastLoopClosureFrame: step.trajectory.lastLoopClosureFrame,\n    trajectoryKeyframeCount: step.trajectory.keyframes.length,\n  };\n}\n\nfunction serializeAnchor(a: ReconstructionStep['anchor']): Record<string, unknown> {\n  return {\n    anchorFrameIndex: a.anchorFrameIndex,\n    anchorPose: a.anchorPose,\n    anchorDescriptor: Array.from(a.anchorDescriptor),\n    revision: a.revision,\n  };\n}\n\nexport function mcpReconstructAnchor(sessionId: string): {\n  ok: true;\n  anchor: Record<string, unknown>;\n  finalized?: boolean;\n} {\n  const state = getSessionOrThrow(sessionId);\n  if (state.finalizedManifest && state.lastStep) {\n    return { ok: true, anchor: serializeAnchor(state.lastStep.anchor), finalized: true };\n  }\n  if (state.finalizedManifest) {\n    return {\n      ok: true,\n      anchor: serializeAnchor({\n        anchorFrameIndex: 0,\n        anchorPose: {\n          position: [0, 0, 0],\n          rotation: [0, 0, 0, 1],\n          confidence: 1,\n        },\n        anchorDescriptor: new Float32Array([0, 0, 0, 0]),\n        revision: 0,\n      }),\n      finalized: true,\n    };\n  }\n  if (state.lastStep) {\n    return { ok: true, anchor: serializeAnchor(state.lastStep.anchor) };\n  }\n  return {\n    ok: true,\n    anchor: serializeAnchor({\n      anchorFrameIndex: 0,\n      anchorPose: {\n        position: [0, 0, 0],\n        rotation: [0, 0, 0, 1],\n        confidence: 1,\n      },\n      anchorDescriptor: new Float32Array([0, 0, 0, 0]),\n      revision: 0,\n    }),\n  };\n}\n\nfunction manifestToJson(m: ReconstructionManifest): Record<string, unknown> {\n  return JSON.parse(JSON.stringify(m)) as Record<string, unknown>;\n}\n\nexport async function mcpReconstructExport(\n  sessionId: string,\n  target: string\n): Promise<{\n  ok: true;\n  target: string;\n  compileStatus: 'COMPILED' | 'COMPILE_FAILED';\n  manifest: Record<string, unknown>;\n  compiledOutput?: string;\n  usedCompilerFallback?: boolean;\n  compileError?: string;\n  /** ASCII PLY (xyz + rgb) from aggregated step points; load in DCC tools or three.js PLYLoader. */\n  pointCloudPly?: string;\n  /** Camera / rig poses per reconstructed frame (JSON). */\n  trajectoryJson?: string;\n  exportPointCount?: number;\n  message: string;\n}> {\n  const state = sessions.get(sessionId);\n  if (!state) {\n    throw new Error(`holo_reconstruct: unknown sessionId`);\n  }\n\n  let manifest: ReconstructionManifest;\n  if (state.finalizedManifest) {\n    manifest = state.finalizedManifest;\n  } else {\n    manifest = await state.runtime.finalize();\n    state.finalizedManifest = manifest;\n    await state.runtime.dispose();\n  }\n\n  const geom = state.aggregate;\n  const geomBounds = boundsFromPositions(geom.positions);\n  const boundsForStub = effectiveBoundsForExport(manifest, geomBounds);\n  const exportPointCount = Math.floor(geom.positions.length / 3);\n  const pointCloudPly =\n    exportPointCount > 0 ? encodePlyAscii(geom.positions, geom.colors) : undefined;\n  const trajectoryJson = geom.poses.length > 0 ? encodeTrajectoryJson(geom.poses) : undefined;\n\n  let compiledOutput: string | undefined;\n  let usedCompilerFallback: boolean | undefined;\n  let compileError: string | undefined;\n  let compileStatus: 'COMPILED' | 'COMPILE_FAILED';\n\n  const holomapPc = holomapPayloadFromAggregatedPoints(geom.positions, geom.colors);\n\n  try {\n    const c = await compileManifestToTarget(manifest, target, boundsForStub, holomapPc);\n    compiledOutput = c.output;\n    usedCompilerFallback = c.usedFallback;\n    compileStatus = 'COMPILED';\n  } catch (e) {\n    compileError = e instanceof Error ? e.message : String(e);\n    compileStatus = 'COMPILE_FAILED';\n  }\n\n  return {\n    ok: true,\n    target,\n    compileStatus,\n    manifest: manifestToJson(manifest),\n    compiledOutput,\n    usedCompilerFallback,\n    compileError,\n    pointCloudPly,\n    trajectoryJson,\n    exportPointCount,\n    message:\n      compileStatus === 'COMPILED'\n        ? 'HoloMap manifest generated and export target compiled via ExportManager.'\n        : `HoloMap manifest returned; compile failed (${compileError ?? 'unknown'}). Retry with another target or fix toolchain.`,\n  };\n}\n","type CapturePrivacyRecord = Record<string, unknown>;\n\nexport type CaptureSurface = 'HoloMap' | 'HoloGram';\nexport type CaptureMediaKind = 'image' | 'gif' | 'video' | 'frame';\n\nconst PUBLIC_CAPTURE_CONTEXTS = new Set([\n  'public',\n  'consumer',\n  'consumer-public',\n  'external',\n  'public-consumer',\n]);\n\nconst BYSTANDER_MITIGATIONS = new Set([\n  'face_blur',\n  'no_bystanders',\n  'operator_reviewed',\n  'private_space',\n  'not_applicable',\n]);\n\nexport const capturePrivacyInputSchema = {\n  type: 'object',\n  description:\n    'Capture privacy gate for public/consumer media. For captureContext public/consumer, consent.tosAccepted, consent.bystanderPrivacyAccepted, consent.mediaRightsConfirmed, and bystanderMitigation are required before ingest/render.',\n  properties: {\n    captureContext: {\n      type: 'string',\n      enum: ['internal-authenticated', 'private', 'public', 'consumer', 'consumer-public'],\n      description:\n        'Use public/consumer for media submitted through a consumer-facing capture surface.',\n    },\n    bystanderMitigation: {\n      type: 'string',\n      enum: Array.from(BYSTANDER_MITIGATIONS),\n      description:\n        'Public capture mitigation decision: face_blur, no_bystanders, operator_reviewed, private_space, or not_applicable.',\n    },\n    consent: {\n      type: 'object',\n      properties: {\n        tosAccepted: { type: 'boolean' },\n        bystanderPrivacyAccepted: { type: 'boolean' },\n        mediaRightsConfirmed: { type: 'boolean' },\n        acknowledgedAt: { type: 'string' },\n        acknowledgedBy: { type: 'string' },\n      },\n    },\n  },\n} as const;\n\nfunction asRecord(value: unknown): CapturePrivacyRecord | undefined {\n  if (!value || typeof value !== 'object' || Array.isArray(value)) return undefined;\n  return value as CapturePrivacyRecord;\n}\n\nfunction readString(...values: unknown[]): string {\n  for (const value of values) {\n    if (typeof value === 'string' && value.trim()) return value.trim();\n  }\n  return '';\n}\n\nfunction readBooleanTrue(...values: unknown[]): boolean {\n  return values.some((value) => value === true);\n}\n\nfunction isPublicCapture(args: CapturePrivacyRecord, privacy?: CapturePrivacyRecord): boolean {\n  const context = readString(privacy?.captureContext, args.captureContext).toLowerCase();\n  return (\n    PUBLIC_CAPTURE_CONTEXTS.has(context) ||\n    args.publicExposure === true ||\n    privacy?.publicExposure === true\n  );\n}\n\nexport function assertPublicCaptureConsent(\n  args: CapturePrivacyRecord,\n  options: { toolName: string; surface: CaptureSurface; mediaKind: CaptureMediaKind }\n): void {\n  const privacy = asRecord(args.privacy);\n  if (!isPublicCapture(args, privacy)) return;\n\n  const consent = asRecord(privacy?.consent) ?? asRecord(args.consent) ?? asRecord(args.consentReceipt);\n  const tosAccepted = readBooleanTrue(\n    consent?.tosAccepted,\n    consent?.termsAccepted,\n    privacy?.tosAccepted,\n    args.tosAccepted\n  );\n  const bystanderPrivacyAccepted = readBooleanTrue(\n    consent?.bystanderPrivacyAccepted,\n    consent?.bystanderPrivacyAcknowledged,\n    privacy?.bystanderPrivacyAccepted,\n    args.bystanderPrivacyAccepted\n  );\n  const mediaRightsConfirmed = readBooleanTrue(\n    consent?.mediaRightsConfirmed,\n    consent?.rightsConfirmed,\n    privacy?.mediaRightsConfirmed,\n    args.mediaRightsConfirmed\n  );\n  const bystanderMitigation = readString(\n    privacy?.bystanderMitigation,\n    consent?.bystanderMitigation,\n    args.bystanderMitigation\n  );\n\n  if (\n    tosAccepted &&\n    bystanderPrivacyAccepted &&\n    mediaRightsConfirmed &&\n    BYSTANDER_MITIGATIONS.has(bystanderMitigation)\n  ) {\n    return;\n  }\n\n  throw new Error(\n    `${options.toolName}: public ${options.surface} ${options.mediaKind} capture requires privacy.consent.tosAccepted, privacy.consent.bystanderPrivacyAccepted, privacy.consent.mediaRightsConfirmed, and privacy.bystanderMitigation before ingest/render`\n  );\n}\n","/**\n * HoloMap MCP tools — reconstruction sessions via HoloMapRuntime (CPU path in Node).\n *\n * `holo_map_paper_ingest_probe` runs paper harness ingest. See RFC-HoloMap.md.\n */\n\nimport type { Tool } from '@modelcontextprotocol/sdk/types.js';\nimport {\n  mcpReconstructAnchor,\n  mcpReconstructExport,\n  mcpStartReconstructFromVideo,\n  mcpReconstructStep,\n} from './holo-reconstruct-sessions';\nimport { assertPublicCaptureConsent, capturePrivacyInputSchema } from './capture-consent';\n\nexport const holoMapToolDefinitions: Tool[] = [\n  {\n    name: 'holo_reconstruct_from_video',\n    description:\n      'Download a video (http(s) or file://), hash bytes for replay identity, optionally decode frames with ffmpeg (ingestVideo, default true), and run HoloMapRuntime.step per frame. Set config.ingestVideo false to only open a session (use holo_reconstruct_step for frames).',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        videoUrl: { type: 'string', description: 'HTTPS URL or file:// path to input video' },\n        config: {\n          type: 'object',\n          description:\n            'HoloMapConfig fields plus captureProfile? (\"room\" | \"face\"), scanKind? (\"face\" alias), ingestVideo?, maxIngestFrames?, weightCid? (content-addressed weights). Env: HOLOMAP_MCP_INGEST_VIDEO=0, HOLOMAP_MCP_MAX_VIDEO_BYTES, HOLOMAP_MCP_FETCH_VIDEO_TIMEOUT_MS, HOLOMAP_MCP_FFMPEG_ANALYZE_DURATION, HOLOMAP_MCP_FFMPEG_PROBE_SIZE, HOLOMAP_MCP_EXPORT_MAX_POINTS, FFPROBE_PATH, HOLOMAP_MCP_FFPROBE_TIMEOUT_MS.',\n        },\n        privacy: capturePrivacyInputSchema,\n      },\n      required: ['videoUrl'],\n    },\n  },\n  {\n    name: 'holo_reconstruct_step',\n    description:\n      'Stream one RGB/RGBA frame (base64) into an active HoloMap session. Returns pose and point count for the step.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        sessionId: { type: 'string', description: 'Session id from holo_reconstruct_from_video' },\n        frameBase64: {\n          type: 'string',\n          description: 'Base64-encoded RGB (WxHx3) or RGBA (WxHx4) frame bytes',\n        },\n        frameIndex: { type: 'number', description: 'Monotonic frame index' },\n        width: { type: 'number' },\n        height: { type: 'number' },\n        privacy: capturePrivacyInputSchema,\n      },\n      required: ['sessionId', 'frameBase64', 'frameIndex', 'width', 'height'],\n    },\n  },\n  {\n    name: 'holo_reconstruct_anchor',\n    description: 'Return AnchorContext state for the current (or last) step in a HoloMap session.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        sessionId: { type: 'string' },\n      },\n      required: ['sessionId'],\n    },\n  },\n  {\n    name: 'holo_reconstruct_export',\n    description:\n      'Finalize the session, return the v1.0 ReconstructionManifest, compile a bounds/anchor .holo stub via ExportManager (unity, godot, usd, unreal, webgpu, wasm, 3dgs, …), and include pointCloudPly (ASCII PLY xyz+rgb) plus trajectoryJson when steps were aggregated.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        sessionId: { type: 'string' },\n        target: {\n          type: 'string',\n          description:\n            'ExportTarget id or alias (unity, godot, usd / usd-physics, unreal, webgpu, wasm, 3dgs, …)',\n        },\n      },\n      required: ['sessionId', 'target'],\n    },\n  },\n  {\n    name: 'holo_map_paper_ingest_probe',\n    description:\n      'Run the dual-path paper harness ingest probe (Marble compatibility vs HoloMap native). Returns markdown comparison + fingerprint rows for Paper #2 / #4 workflows.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        paperId: {\n          type: 'string',\n          description: 'Identifier e.g. paper-2-snn-navigation or paper-4-adversarial-holo',\n        },\n        ingestPath: {\n          type: 'string',\n          enum: ['marble', 'holomap', 'both'],\n          description:\n            'Scene source mode (default marble if omitted — uses process env when not passed)',\n        },\n      },\n      required: [],\n    },\n  },\n];\n\nconst HOLOMAP_NAMES = new Set(holoMapToolDefinitions.map((t) => t.name));\n\nexport function isHoloMapToolName(name: string): boolean {\n  return HOLOMAP_NAMES.has(name);\n}\n\nexport async function handleHoloMapPaperIngestProbe(\n  args: Record<string, unknown>\n): Promise<unknown> {\n  const { runPaperHarnessIngestProbe, resolveIngestPath } = await import('@holoscript/holomap');\n  const paperId =\n    typeof args.paperId === 'string' && args.paperId.trim()\n      ? args.paperId.trim()\n      : 'mcp-paper-probe';\n  let ingestPath = resolveIngestPath(process);\n  if (typeof args.ingestPath === 'string') {\n    const s = args.ingestPath.trim().toLowerCase();\n    if (s === 'marble' || s === 'holomap' || s === 'both') {\n      ingestPath = s;\n    }\n  }\n  return runPaperHarnessIngestProbe({ paperId, ingestPath });\n}\n\nexport async function handleHoloMapTool(\n  name: string,\n  args: Record<string, unknown>\n): Promise<unknown> {\n  switch (name) {\n    case 'holo_reconstruct_from_video': {\n      const videoUrl = args.videoUrl;\n      if (typeof videoUrl !== 'string' || !videoUrl.trim()) {\n        throw new Error('holo_reconstruct_from_video: videoUrl (non-empty string) is required');\n      }\n      assertPublicCaptureConsent(args, {\n        toolName: 'holo_reconstruct_from_video',\n        surface: 'HoloMap',\n        mediaKind: 'video',\n      });\n      const started = await mcpStartReconstructFromVideo(videoUrl.trim(), args.config);\n      return {\n        ok: true,\n        status: 'SESSION_OPEN',\n        sessionId: started.sessionId,\n        replayFingerprint: started.replayFingerprint,\n        framesIngested: started.framesIngested,\n        ingestMode: started.ingestMode,\n        captureProfile: started.captureProfile,\n        videoBytes: started.videoBytes,\n        ingestWarning: started.ingestWarning,\n        message:\n          started.ingestMode === 'ffmpeg'\n            ? `Ingested ${started.framesIngested} frame(s) via ffmpeg. Use holo_reconstruct_export or more holo_reconstruct_step as needed.`\n            : 'Session opened without ffmpeg ingest; stream frames with holo_reconstruct_step or enable config.ingestVideo.',\n        validated: { videoUrl: videoUrl.slice(0, 200), hasConfig: args.config != null },\n      };\n    }\n    case 'holo_reconstruct_step': {\n      const sessionId = args.sessionId;\n      const frameBase64 = args.frameBase64;\n      if (typeof sessionId !== 'string' || !sessionId.trim()) {\n        throw new Error('holo_reconstruct_step: sessionId is required');\n      }\n      if (typeof frameBase64 !== 'string' || !frameBase64.trim()) {\n        throw new Error('holo_reconstruct_step: frameBase64 is required');\n      }\n      assertPublicCaptureConsent(args, {\n        toolName: 'holo_reconstruct_step',\n        surface: 'HoloMap',\n        mediaKind: 'frame',\n      });\n      for (const k of ['frameIndex', 'width', 'height'] as const) {\n        if (typeof args[k] !== 'number' || !Number.isFinite(args[k] as number)) {\n          throw new Error(`holo_reconstruct_step: ${k} must be a finite number`);\n        }\n      }\n      return mcpReconstructStep(\n        sessionId.trim(),\n        frameBase64.trim(),\n        args.frameIndex as number,\n        args.width as number,\n        args.height as number\n      );\n    }\n    case 'holo_reconstruct_anchor': {\n      const sessionId = args.sessionId;\n      if (typeof sessionId !== 'string' || !sessionId.trim()) {\n        throw new Error('holo_reconstruct_anchor: sessionId is required');\n      }\n      return mcpReconstructAnchor(sessionId.trim());\n    }\n    case 'holo_reconstruct_export': {\n      const sessionId = args.sessionId;\n      const target = args.target;\n      if (typeof sessionId !== 'string' || !sessionId.trim()) {\n        throw new Error('holo_reconstruct_export: sessionId is required');\n      }\n      if (typeof target !== 'string' || !target.trim()) {\n        throw new Error('holo_reconstruct_export: target is required');\n      }\n      return mcpReconstructExport(sessionId.trim(), target.trim());\n    }\n    default:\n      return undefined;\n  }\n}\n","/**\n * HoloScript Graph Understanding Tools\n *\n * Migrated from HoloLand MCP to HoloScript MCP (free tier).\n * Brittney is one participant on the Twin Earth substrate, not the substrate itself.\n * These tools help AI agents understand .holo files as visual graphs.\n */\n\nimport { Tool } from '@modelcontextprotocol/sdk/types.js';\nimport { SemanticSceneGraph, parseHoloStrict } from '@holoscript/core';\nimport {\n  holoMapToolDefinitions,\n  handleHoloMapTool,\n  handleHoloMapPaperIngestProbe,\n} from './holomap-mcp-tools';\n\n// =============================================================================\n// TYPES FOR GRAPH REPRESENTATION\n// =============================================================================\n\nexport interface HoloNode {\n  id: string;\n  name: string;\n  type:\n    | 'template'\n    | 'object'\n    | 'orb'\n    | 'building'\n    | 'npc'\n    | 'collectible'\n    | 'group'\n    | 'environment';\n  position?: [number, number, number];\n  properties: Record<string, unknown>;\n  state?: Record<string, unknown>;\n  actions?: string[];\n  traits?: string[];\n}\n\nexport interface HoloEdge {\n  id: string;\n  from: string;\n  to: string;\n  type: 'uses' | 'triggers' | 'contains' | 'references' | 'flow';\n  event?: string;\n  action?: string;\n  label?: string;\n}\n\nexport interface HoloFlow {\n  trigger: string;\n  event: string;\n  actions: Array<{\n    target: string;\n    action: string;\n    args?: unknown[];\n  }>;\n}\n\nexport interface HoloGraph {\n  name: string;\n  nodes: HoloNode[];\n  edges: HoloEdge[];\n  flows: HoloFlow[];\n  groups: Array<{\n    id: string;\n    name: string;\n    children: string[];\n  }>;\n}\n\n// =============================================================================\n// TOOL DEFINITIONS\n// =============================================================================\n\nexport const graphTools: Tool[] = [\n  {\n    name: 'holo_parse_to_graph',\n    description: `Parse a .holo file and return its graph representation. This helps you understand the visual structure:\n- **Nodes**: All objects, templates, orbs, NPCs, etc.\n- **Edges**: Connections between nodes (uses, triggers, contains)\n- **Flows**: Event-to-action chains (what happens when X occurs)\n- **Groups**: Spatial groupings of nodes\n\nUse this to \"see\" the architecture before modifying code.`,\n    inputSchema: {\n      type: 'object',\n      properties: {\n        code: {\n          type: 'string',\n          description: 'HoloScript code to parse into a graph',\n        },\n      },\n      required: ['code'],\n    },\n  },\n\n  {\n    name: 'holo_semantic_scene_graph',\n    description: `Parse a .holo file and return its W3C-compliant JSON-LD Semantic Scene Graph representation.\nThis leverages the new Pillar 2 Architectural Semantic Understanding.\nOutput is suitable for Linked Data / Knowledge Graph ingestion, SEO-optimized 3D indexing, and AI reasoning.`,\n    inputSchema: {\n      type: 'object',\n      properties: {\n        code: {\n          type: 'string',\n          description: 'HoloScript code to compile to a semantic scene graph',\n        },\n      },\n      required: ['code'],\n    },\n  },\n\n  {\n    name: 'holo_visualize_flow',\n    description: `Visualize the event/action flow in a .holo file as ASCII diagram. Returns something like:\n\\`\\`\\`\n[User] ──wave──→ [Goblin_A] ──throw_rock()──→ [Rock] ──hit──→ [User]\n                     ↓\n               [Goblin_B] ──throw_rock()──→ [Rock]\n\\`\\`\\`\nThis helps you understand the control flow and data flow in the scene.`,\n    inputSchema: {\n      type: 'object',\n      properties: {\n        code: {\n          type: 'string',\n          description: 'HoloScript code to visualize',\n        },\n        focus: {\n          type: 'string',\n          description: 'Focus on a specific node or event (optional)',\n        },\n      },\n      required: ['code'],\n    },\n  },\n\n  {\n    name: 'holo_get_node_connections',\n    description: `Get all connections for a specific node in a .holo file. Returns:\n- What this node **receives** (incoming events/triggers)\n- What this node **sends** (outgoing actions/events)\n- What **contains** this node (parent groups)\n- What this node **contains** (children)\n- What **template** this node uses`,\n    inputSchema: {\n      type: 'object',\n      properties: {\n        code: {\n          type: 'string',\n          description: 'HoloScript code to analyze',\n        },\n        nodeName: {\n          type: 'string',\n          description: 'Name of the node to inspect (e.g., \"Goblin_A\", \"Player\")',\n        },\n      },\n      required: ['code', 'nodeName'],\n    },\n  },\n\n  {\n    name: 'holo_design_graph',\n    description: `Given a natural language description, design the graph structure BEFORE writing code. Returns:\n- Suggested nodes and their types\n- Connections between nodes\n- Event flows\n- Recommended spatial groupings\n\nUse this to plan your .holo file as a visual architecture first.`,\n    inputSchema: {\n      type: 'object',\n      properties: {\n        description: {\n          type: 'string',\n          description: 'What you want to create (e.g., \"A shop with NPCs that sell items\")',\n        },\n        constraints: {\n          type: 'object',\n          description: 'Optional constraints (maxNodes, requiredTypes, etc.)',\n        },\n      },\n      required: ['description'],\n    },\n  },\n\n  {\n    name: 'holo_diff_graphs',\n    description: `Compare two .holo files as graphs and show what changed:\n- Added/removed nodes\n- Changed connections\n- Modified flows\n- New/removed groups\n\nHelps understand the impact of changes.`,\n    inputSchema: {\n      type: 'object',\n      properties: {\n        before: {\n          type: 'string',\n          description: 'Original HoloScript code',\n        },\n        after: {\n          type: 'string',\n          description: 'Modified HoloScript code',\n        },\n      },\n      required: ['before', 'after'],\n    },\n  },\n\n  {\n    name: 'holo_suggest_connections',\n    description: `Given existing nodes in a .holo file, suggest potential connections and flows you might want to add. For example:\n- \"Player and Enemy exist but have no interaction - add combat flow?\"\n- \"Collectibles exist but no collection event - add on_interact?\"`,\n    inputSchema: {\n      type: 'object',\n      properties: {\n        code: {\n          type: 'string',\n          description: 'Current HoloScript code to analyze',\n        },\n        intent: {\n          type: 'string',\n          description: 'What kind of behavior you want (optional)',\n        },\n      },\n      required: ['code'],\n    },\n  },\n\n  {\n    name: 'holo_generate_semantic_scene_graph',\n    description: `Generate a W3C-compliant JSON-LD Semantic Scene Graph from a .holo composition.\nThis bridges Pillar 2 (Architectural semantic understanding) by converting AST into Linked Data.`,\n    inputSchema: {\n      type: 'object',\n      properties: {\n        code: {\n          type: 'string',\n          description: 'HoloScript code to convert to JSON-LD',\n        },\n        baseURI: {\n          type: 'string',\n          description: 'Optional Base URI for generated @id properties (e.g., \"urn:holoscript:\")',\n        },\n      },\n      required: ['code'],\n    },\n  },\n\n  ...holoMapToolDefinitions,\n];\n\n// =============================================================================\n// PARSER - Extract graph from .holo code\n// =============================================================================\n\nexport function parseHoloToGraph(code: string): HoloGraph {\n  const graph: HoloGraph = {\n    name: '',\n    nodes: [],\n    edges: [],\n    flows: [],\n    groups: [],\n  };\n\n  const compositionMatch = code.match(/composition\\s+\"([^\"]+)\"/);\n  const worldMatch = code.match(/world\\s+(\\w+)/);\n  graph.name = compositionMatch?.[1] || worldMatch?.[1] || 'Unnamed';\n\n  // Extract templates\n  const templateRegex = /template\\s+\"(\\w+)\"\\s*\\{([^}]+(?:\\{[^}]*\\}[^}]*)*)\\}/g;\n  let match;\n  while ((match = templateRegex.exec(code)) !== null) {\n    const name = match[1];\n    const body = match[2];\n\n    const node: HoloNode = {\n      id: `template_${name}`,\n      name,\n      type: 'template',\n      properties: {},\n      state: extractState(body),\n      actions: extractActions(body),\n    };\n    graph.nodes.push(node);\n  }\n\n  // Extract objects\n  const objectRegex = /object\\s+\"(\\w+)\"(?:\\s+using\\s+\"(\\w+)\")?\\s*\\{([^}]+)\\}/g;\n  while ((match = objectRegex.exec(code)) !== null) {\n    const name = match[1];\n    const template = match[2];\n    const body = match[3];\n\n    const node: HoloNode = {\n      id: `object_${name}`,\n      name,\n      type: 'object',\n      position: extractPosition(body),\n      properties: extractProperties(body),\n      traits: extractTraits(body),\n    };\n    graph.nodes.push(node);\n\n    if (template) {\n      graph.edges.push({\n        id: `edge_${name}_uses_${template}`,\n        from: `object_${name}`,\n        to: `template_${template}`,\n        type: 'uses',\n        label: 'uses',\n      });\n    }\n  }\n\n  // Extract orbs\n  const orbRegex = /orb\\s+(\\w+)\\s*\\{([^}]+)\\}/g;\n  while ((match = orbRegex.exec(code)) !== null) {\n    const name = match[1];\n    const body = match[2];\n\n    const node: HoloNode = {\n      id: `orb_${name}`,\n      name,\n      type: determineOrbType(body),\n      position: extractPosition(body),\n      properties: extractProperties(body),\n      traits: extractTraits(body),\n    };\n    graph.nodes.push(node);\n  }\n\n  // Extract buildings\n  const buildingRegex = /building\\s+(\\w+)\\s*\\{([^}]+)\\}/g;\n  while ((match = buildingRegex.exec(code)) !== null) {\n    const name = match[1];\n    const body = match[2];\n\n    graph.nodes.push({\n      id: `building_${name}`,\n      name,\n      type: 'building',\n      position: extractPosition(body),\n      properties: extractProperties(body),\n    });\n  }\n\n  // Extract spatial groups\n  const groupRegex = /spatial_group\\s+\"(\\w+)\"\\s*\\{([^}]+(?:\\{[^}]*\\}[^}]*)*)\\}/g;\n  while ((match = groupRegex.exec(code)) !== null) {\n    const groupName = match[1];\n    const groupBody = match[2];\n\n    const childObjects: string[] = [];\n    const childObjRegex = /object\\s+\"(\\w+)\"/g;\n    let childMatch;\n    while ((childMatch = childObjRegex.exec(groupBody)) !== null) {\n      childObjects.push(`object_${childMatch[1]}`);\n    }\n\n    graph.groups.push({\n      id: `group_${groupName}`,\n      name: groupName,\n      children: childObjects,\n    });\n\n    for (const childId of childObjects) {\n      graph.edges.push({\n        id: `edge_${groupName}_contains_${childId}`,\n        from: `group_${groupName}`,\n        to: childId,\n        type: 'contains',\n      });\n    }\n  }\n\n  // Extract flows from logic blocks\n  const logicRegex = /logic\\s*\\{([^}]+(?:\\{[^}]*\\}[^}]*)*)\\}/g;\n  while ((match = logicRegex.exec(code)) !== null) {\n    const logicBody = match[1];\n    extractFlows(logicBody, graph);\n  }\n\n  return graph;\n}\n\n// Helper functions\nfunction extractState(body: string): Record<string, unknown> {\n  const stateMatch = body.match(/state\\s*\\{([^}]+)\\}/);\n  if (!stateMatch) return {};\n\n  const state: Record<string, unknown> = {};\n  const propRegex = /(\\w+):\\s*([^,\\n}]+)/g;\n  let match;\n  while ((match = propRegex.exec(stateMatch[1])) !== null) {\n    state[match[1]] = parseValue(match[2].trim());\n  }\n  return state;\n}\n\nfunction extractActions(body: string): string[] {\n  const actions: string[] = [];\n  const actionRegex = /action\\s+(\\w+)/g;\n  let match;\n  while ((match = actionRegex.exec(body)) !== null) {\n    actions.push(match[1]);\n  }\n  return actions;\n}\n\nfunction extractPosition(body: string): [number, number, number] | undefined {\n  const posMatch = body.match(/position:\\s*\\[([^\\]]+)\\]/);\n  if (!posMatch) return undefined;\n  const parts = posMatch[1].split(',').map((p) => parseFloat(p.trim()));\n  return parts.length >= 3 ? [parts[0], parts[1], parts[2]] : undefined;\n}\n\nfunction extractProperties(body: string): Record<string, unknown> {\n  const props: Record<string, unknown> = {};\n  const propRegex = /(\\w+):\\s*([^,\\n}]+)/g;\n  let match;\n  while ((match = propRegex.exec(body)) !== null) {\n    const key = match[1];\n    if (!['position', 'state', 'action', 'on_interact', 'traits'].includes(key)) {\n      props[key] = parseValue(match[2].trim());\n    }\n  }\n  return props;\n}\n\nfunction extractTraits(body: string): string[] {\n  const traitsMatch = body.match(/traits:\\s*\\[([^\\]]+)\\]/);\n  if (!traitsMatch) return [];\n  return traitsMatch[1]\n    .split(',')\n    .map((t) => t.trim().replace(/[\"']/g, ''))\n    .filter(Boolean);\n}\n\nfunction determineOrbType(body: string): HoloNode['type'] {\n  if (body.includes('talkable') || body.includes('NPC')) return 'npc';\n  if (body.includes('collectible')) return 'collectible';\n  return 'orb';\n}\n\nfunction parseValue(value: string): unknown {\n  if (value === 'true') return true;\n  if (value === 'false') return false;\n  if (value.startsWith('\"') || value.startsWith(\"'\")) return value.slice(1, -1);\n  if (value.startsWith('[')) {\n    try {\n      return JSON.parse(value);\n    } catch {\n      return value;\n    }\n  }\n  const num = parseFloat(value);\n  return isNaN(num) ? value : num;\n}\n\nfunction extractFlows(logicBody: string, graph: HoloGraph): void {\n  const eventRegex = /on_(\\w+)(?:\\(\"([^\"]+)\"\\))?\\s*\\{([^}]+)\\}/g;\n  let match;\n  while ((match = eventRegex.exec(logicBody)) !== null) {\n    const eventType = match[1];\n    const eventTarget = match[2] || 'any';\n    const eventBody = match[3];\n\n    const flow: HoloFlow = {\n      trigger: eventTarget,\n      event: `on_${eventType}`,\n      actions: [],\n    };\n\n    const actionCallRegex = /(\\w+)\\.(\\w+)\\(([^)]*)\\)/g;\n    let actionMatch;\n    while ((actionMatch = actionCallRegex.exec(eventBody)) !== null) {\n      flow.actions.push({\n        target: actionMatch[1],\n        action: actionMatch[2],\n        args: actionMatch[3] ? actionMatch[3].split(',').map((a) => a.trim()) : [],\n      });\n\n      graph.edges.push({\n        id: `flow_${eventType}_${actionMatch[1]}_${actionMatch[2]}`,\n        from: eventTarget === 'any' ? 'event' : `object_${eventTarget}`,\n        to: `object_${actionMatch[1]}`,\n        type: 'triggers',\n        event: `on_${eventType}`,\n        action: actionMatch[2],\n      });\n    }\n\n    graph.flows.push(flow);\n  }\n\n  // Extract every() periodic events\n  const everyRegex = /every\\((\\d+)\\)\\s*\\{([^}]+)\\}/g;\n  while ((match = everyRegex.exec(logicBody)) !== null) {\n    const interval = match[1];\n    const body = match[2];\n\n    const flow: HoloFlow = {\n      trigger: 'timer',\n      event: `every_${interval}ms`,\n      actions: [],\n    };\n\n    const actionCallRegex = /(\\w+)\\.(\\w+)\\(([^)]*)\\)/g;\n    let actionMatch;\n    while ((actionMatch = actionCallRegex.exec(body)) !== null) {\n      flow.actions.push({\n        target: actionMatch[1],\n        action: actionMatch[2],\n      });\n    }\n\n    graph.flows.push(flow);\n  }\n}\n\n// =============================================================================\n// VISUALIZATION - ASCII diagrams of flow\n// =============================================================================\n\nexport function visualizeFlow(graph: HoloGraph, focus?: string): string {\n  const lines: string[] = [];\n\n  lines.push(`=== ${graph.name} Flow Diagram ===\\n`);\n\n  const nodesByType = new Map<string, HoloNode[]>();\n  for (const node of graph.nodes) {\n    const type = node.type;\n    if (!nodesByType.has(type)) nodesByType.set(type, []);\n    nodesByType.get(type)!.push(node);\n  }\n\n  lines.push('NODES:');\n  for (const [type, nodes] of nodesByType) {\n    lines.push(`  ${type.toUpperCase()}:`);\n    for (const node of nodes) {\n      const pos = node.position ? ` @ [${node.position.join(', ')}]` : '';\n      const traits = node.traits?.length ? ` [${node.traits.join(', ')}]` : '';\n      lines.push(`    [${node.name}]${pos}${traits}`);\n    }\n  }\n\n  lines.push('\\nFLOWS:');\n  for (const flow of graph.flows) {\n    if (\n      focus &&\n      !flow.trigger.includes(focus) &&\n      !flow.actions.some((a) => a.target.includes(focus))\n    ) {\n      continue;\n    }\n\n    lines.push(`  ${flow.event}:`);\n    const actionsStr = flow.actions.map((a) => `${a.target}.${a.action}()`).join(' -> ');\n    lines.push(`    [${flow.trigger}] --- ${flow.event} ---> ${actionsStr}`);\n  }\n\n  if (graph.groups.length > 0) {\n    lines.push('\\nGROUPS:');\n    for (const group of graph.groups) {\n      lines.push(`  ${group.name}:`);\n      lines.push(\n        `    +-- ${group.children.map((c) => c.replace(/^(object|orb)_/, '')).join(', ')}`\n      );\n    }\n  }\n\n  return lines.join('\\n');\n}\n\n// =============================================================================\n// NODE CONNECTIONS\n// =============================================================================\n\nexport function getNodeConnections(\n  graph: HoloGraph,\n  nodeName: string\n): {\n  receives: Array<{ from: string; event: string }>;\n  sends: Array<{ to: string; action: string }>;\n  parent?: string;\n  children: string[];\n  uses?: string;\n} {\n  const nodeId =\n    graph.nodes.find((n) => n.name === nodeName)?.id || `object_${nodeName}` || `orb_${nodeName}`;\n\n  const result = {\n    receives: [] as Array<{ from: string; event: string }>,\n    sends: [] as Array<{ to: string; action: string }>,\n    parent: undefined as string | undefined,\n    children: [] as string[],\n    uses: undefined as string | undefined,\n  };\n\n  for (const edge of graph.edges) {\n    if (edge.to === nodeId) {\n      if (edge.type === 'triggers') {\n        result.receives.push({ from: edge.from, event: edge.event || 'unknown' });\n      } else if (edge.type === 'contains') {\n        result.parent = edge.from;\n      }\n    }\n\n    if (edge.from === nodeId) {\n      if (edge.type === 'triggers') {\n        result.sends.push({ to: edge.to, action: edge.action || 'unknown' });\n      } else if (edge.type === 'uses') {\n        result.uses = edge.to.replace('template_', '');\n      } else if (edge.type === 'contains') {\n        result.children.push(edge.to);\n      }\n    }\n  }\n\n  return result;\n}\n\n// =============================================================================\n// GRAPH DESIGN from description\n// =============================================================================\n\nexport function designGraphFromDescription(description: string): {\n  suggestedNodes: Array<{ name: string; type: string; purpose: string }>;\n  suggestedEdges: Array<{ from: string; to: string; type: string; why: string }>;\n  suggestedFlows: Array<{ trigger: string; actions: string[]; why: string }>;\n  holoStructure: string;\n} {\n  const desc = description.toLowerCase();\n  const nodes: Array<{ name: string; type: string; purpose: string }> = [];\n  const edges: Array<{ from: string; to: string; type: string; why: string }> = [];\n  const flows: Array<{ trigger: string; actions: string[]; why: string }> = [];\n\n  if (desc.includes('shop') || desc.includes('store') || desc.includes('merchant')) {\n    nodes.push({ name: 'ShopKeeper', type: 'npc', purpose: 'Sells items to player' });\n    nodes.push({ name: 'ShopUI', type: 'ui', purpose: 'Shows inventory for sale' });\n    flows.push({\n      trigger: 'on_interact(ShopKeeper)',\n      actions: ['ShopUI.show()', 'ShopKeeper.greet()'],\n      why: 'Player interacts with shop keeper to open shop',\n    });\n  }\n\n  if (desc.includes('enemy') || desc.includes('combat') || desc.includes('fight')) {\n    nodes.push({ name: 'Enemy', type: 'template', purpose: 'Hostile entity with health/attack' });\n    nodes.push({ name: 'Player', type: 'object', purpose: 'User-controlled character' });\n    edges.push({ from: 'Enemy', to: 'Player', type: 'targets', why: 'Enemy attacks player' });\n    flows.push({\n      trigger: 'every(2000)',\n      actions: ['Enemy.attack(Player)'],\n      why: 'Periodic enemy attacks',\n    });\n  }\n\n  if (desc.includes('collect') || desc.includes('pickup') || desc.includes('item')) {\n    nodes.push({ name: 'Collectible', type: 'template', purpose: 'Item that can be picked up' });\n    flows.push({\n      trigger: 'on_interact',\n      actions: ['this.collect()', 'Player.addToInventory(this)'],\n      why: 'Player picks up item',\n    });\n  }\n\n  if (desc.includes('door') || desc.includes('portal') || desc.includes('teleport')) {\n    nodes.push({ name: 'Portal', type: 'orb', purpose: 'Teleports to another location' });\n    flows.push({\n      trigger: 'on_enter(Portal)',\n      actions: ['Player.teleportTo(Portal.destination)'],\n      why: 'Player enters portal and teleports',\n    });\n  }\n\n  if (desc.includes('npc') || desc.includes('character') || desc.includes('talk')) {\n    nodes.push({ name: 'NPC', type: 'npc', purpose: 'Non-player character for dialogue' });\n    flows.push({\n      trigger: 'on_interact(NPC)',\n      actions: ['DialogueUI.show(NPC.dialogue)'],\n      why: 'Player talks to NPC',\n    });\n  }\n\n  const holoStructure = generateHoloStructure(nodes, edges, flows);\n\n  return { suggestedNodes: nodes, suggestedEdges: edges, suggestedFlows: flows, holoStructure };\n}\n\nfunction generateHoloStructure(\n  nodes: Array<{ name: string; type: string; purpose: string }>,\n  _edges: Array<{ from: string; to: string; type: string; why: string }>,\n  flows: Array<{ trigger: string; actions: string[]; why: string }>\n): string {\n  const lines: string[] = [];\n  lines.push('composition \"Generated\" {');\n  lines.push('');\n\n  const templates = nodes.filter((n) => n.type === 'template');\n  for (const t of templates) {\n    lines.push(`  // ${t.purpose}`);\n    lines.push(`  template \"${t.name}\" {`);\n    lines.push('    state { }');\n    lines.push('    action example() { }');\n    lines.push('  }');\n    lines.push('');\n  }\n\n  lines.push('  spatial_group \"Main\" {');\n  const objects = nodes.filter((n) => n.type !== 'template' && n.type !== 'ui');\n  for (const o of objects) {\n    lines.push(`    // ${o.purpose}`);\n    if (templates.find((t) => t.name === o.type || o.type === 'object')) {\n      lines.push(`    object \"${o.name}\" using \"${o.type}\" {`);\n    } else {\n      lines.push(`    orb ${o.name} {`);\n    }\n    lines.push('      position: [0, 0, 0]');\n    lines.push('    }');\n  }\n  lines.push('  }');\n  lines.push('');\n\n  if (flows.length > 0) {\n    lines.push('  logic {');\n    for (const f of flows) {\n      lines.push(`    // ${f.why}`);\n      lines.push(`    ${f.trigger} {`);\n      for (const a of f.actions) {\n        lines.push(`      ${a}`);\n      }\n      lines.push('    }');\n    }\n    lines.push('  }');\n  }\n\n  lines.push('}');\n  return lines.join('\\n');\n}\n\n// =============================================================================\n// TOOL HANDLER\n// =============================================================================\n\nexport async function handleGraphTool(\n  name: string,\n  args: Record<string, unknown>\n): Promise<unknown> {\n  switch (name) {\n    case 'holo_map_paper_ingest_probe':\n      return handleHoloMapPaperIngestProbe(args);\n\n    case 'holo_reconstruct_from_video':\n    case 'holo_reconstruct_step':\n    case 'holo_reconstruct_anchor':\n    case 'holo_reconstruct_export':\n      return handleHoloMapTool(name, args);\n\n    case 'holo_semantic_scene_graph': {\n      const code = args.code as string;\n      if (!code) throw new Error('code is required');\n\n      try {\n        const ast = parseHoloStrict(code);\n        const jsonld = SemanticSceneGraph.generateObject(ast, { includeMetadata: true });\n        return {\n          sceneGraph: jsonld,\n          summary: `Successfully generated W3C-compliant JSON-LD Semantic Scene Graph for ${ast.name}`,\n        };\n      } catch (err: unknown) {\n        throw new Error(\n          `Failed to generate Semantic Scene Graph: ${err instanceof Error ? err.message : String(err)}`\n        );\n      }\n    }\n\n    case 'holo_parse_to_graph': {\n      const code = args.code as string;\n      if (!code) throw new Error('code is required');\n\n      const graph = parseHoloToGraph(code);\n      return {\n        name: graph.name,\n        nodeCount: graph.nodes.length,\n        edgeCount: graph.edges.length,\n        flowCount: graph.flows.length,\n        groupCount: graph.groups.length,\n        nodes: graph.nodes,\n        edges: graph.edges,\n        flows: graph.flows,\n        groups: graph.groups,\n      };\n    }\n\n    case 'holo_visualize_flow': {\n      const code = args.code as string;\n      const focus = args.focus as string | undefined;\n      const graph = parseHoloToGraph(code);\n      return visualizeFlow(graph, focus);\n    }\n\n    case 'holo_get_node_connections': {\n      const code = args.code as string;\n      const nodeName = args.nodeName as string;\n      const graph = parseHoloToGraph(code);\n      return getNodeConnections(graph, nodeName);\n    }\n\n    case 'holo_design_graph': {\n      const description = args.description as string;\n      return designGraphFromDescription(description);\n    }\n\n    case 'holo_diff_graphs': {\n      const before = args.before as string;\n      const after = args.after as string;\n\n      const graphBefore = parseHoloToGraph(before);\n      const graphAfter = parseHoloToGraph(after);\n\n      const beforeNodeIds = new Set(graphBefore.nodes.map((n) => n.id));\n      const afterNodeIds = new Set(graphAfter.nodes.map((n) => n.id));\n\n      return {\n        addedNodes: graphAfter.nodes.filter((n) => !beforeNodeIds.has(n.id)),\n        removedNodes: graphBefore.nodes.filter((n) => !afterNodeIds.has(n.id)),\n        addedEdges: graphAfter.edges.filter(\n          (e) => !new Set(graphBefore.edges.map((be) => be.id)).has(e.id)\n        ),\n        removedEdges: graphBefore.edges.filter(\n          (e) => !new Set(graphAfter.edges.map((ae) => ae.id)).has(e.id)\n        ),\n        flowsBefore: graphBefore.flows.length,\n        flowsAfter: graphAfter.flows.length,\n      };\n    }\n\n    case 'holo_suggest_connections': {\n      const code = args.code as string;\n      const intent = args.intent as string | undefined;\n      const graph = parseHoloToGraph(code);\n      const suggestions: string[] = [];\n\n      const connectedNodeIds = new Set([\n        ...graph.edges.map((e) => e.from),\n        ...graph.edges.map((e) => e.to),\n      ]);\n\n      for (const node of graph.nodes) {\n        if (!connectedNodeIds.has(node.id) && node.type !== 'template') {\n          suggestions.push(`\"${node.name}\" has no connections - consider adding interaction`);\n        }\n      }\n\n      const hasPlayer = graph.nodes.some((n) => n.name.toLowerCase().includes('player'));\n      const hasEnemy = graph.nodes.some((n) => n.name.toLowerCase().includes('enemy'));\n      const hasCollectible = graph.nodes.some((n) => n.traits?.includes('collectible'));\n\n      if (hasPlayer && hasEnemy) {\n        const hasCombatFlow = graph.flows.some(\n          (f) => f.event.includes('attack') || f.actions.some((a) => a.action.includes('attack'))\n        );\n        if (!hasCombatFlow) {\n          suggestions.push('Player and Enemy exist but no combat flow - add attack interactions?');\n        }\n      }\n\n      if (hasCollectible) {\n        const hasCollectFlow = graph.flows.some(\n          (f) => f.event.includes('interact') || f.event.includes('collect')\n        );\n        if (!hasCollectFlow) {\n          suggestions.push(\n            'Collectibles exist but no collection logic - add on_interact handlers?'\n          );\n        }\n      }\n\n      if (intent) {\n        suggestions.push(\n          `Based on intent \"${intent}\": consider adding flows that connect existing nodes.`\n        );\n      }\n\n      return {\n        suggestions,\n        stats: {\n          nodes: graph.nodes.length,\n          connections: graph.edges.length,\n          flows: graph.flows.length,\n        },\n      };\n    }\n\n    default:\n      throw new Error(`Unknown graph tool: ${name}`);\n  }\n}\n","/**\n * HoloScript IDE Tools\n *\n * Migrated from Hololand/Brittney MCP to HoloScript MCP (free tier).\n * Provides LSP-style IDE features for AI coding agents.\n * Renamed from brittney_* -> hs_* prefix for HoloScript branding.\n */\n\nimport { Tool } from '@modelcontextprotocol/sdk/types.js';\nimport * as fs from 'fs';\nimport * as path from 'path';\n\n// =============================================================================\n// TYPES\n// =============================================================================\n\nexport interface ProjectFile {\n  path: string;\n  type: 'holo' | 'hsplus' | 'hs' | 'glb' | 'gltf' | 'other';\n  objects?: string[];\n  templates?: string[];\n  traits?: string[];\n  errors?: number;\n}\n\nexport interface Diagnostic {\n  file: string;\n  line: number;\n  column: number;\n  severity: 'error' | 'warning' | 'info' | 'hint';\n  message: string;\n  code?: string;\n  quickFixes?: QuickFix[];\n}\n\nexport interface QuickFix {\n  title: string;\n  edit: {\n    range: { start: { line: number; column: number }; end: { line: number; column: number } };\n    newText: string;\n  };\n}\n\nexport interface CompletionItem {\n  label: string;\n  kind: 'trait' | 'property' | 'object' | 'template' | 'function' | 'keyword' | 'snippet';\n  detail?: string;\n  documentation?: string;\n  insertText?: string;\n  insertTextFormat?: 'plaintext' | 'snippet';\n}\n\n// =============================================================================\n// TRAIT DOCUMENTATION (inline)\n// =============================================================================\n\nconst traitDocs: Record<\n  string,\n  { description: string; params?: Record<string, string>; example: string }\n> = {\n  grabbable: {\n    description: 'Makes object grabbable by VR controllers or hand tracking.',\n    params: {\n      snap_to_hand: 'Snap to hand position when grabbed (default: false)',\n      two_handed: 'Requires both hands (default: false)',\n      grab_distance: 'Max grab distance (default: 1.0)',\n    },\n    example: `orb sword {\\n  @grabbable(snap_to_hand: true)\\n  position: [0, 1, 0]\\n}`,\n  },\n  throwable: {\n    description: 'Allows grabbed object to be thrown with physics. Requires @grabbable.',\n    params: {\n      velocity_multiplier: 'Throw velocity multiplier (default: 1.0)',\n      bounce: 'Bounce on collision (default: false)',\n      max_velocity: 'Max throw speed (default: 50)',\n    },\n    example: `orb ball {\\n  @grabbable\\n  @throwable(velocity_multiplier: 1.5, bounce: true)\\n}`,\n  },\n  collidable: {\n    description: 'Enables collision detection.',\n    params: {\n      layer: 'Collision layer (e.g., \"player\", \"enemy\")',\n      trigger: 'Trigger-only, no physics (default: false)',\n    },\n    example: `orb wall {\\n  @collidable(layer: \"solid\")\\n  scale: [10, 3, 0.5]\\n}`,\n  },\n  physics: {\n    description: 'Adds physics simulation (gravity, momentum, collisions).',\n    params: {\n      mass: 'Mass in kg (default: 1.0)',\n      friction: 'Friction 0-1 (default: 0.5)',\n      restitution: 'Bounciness 0-1 (default: 0.3)',\n    },\n    example: `orb crate {\\n  @physics(mass: 10, friction: 0.8)\\n  @collidable\\n}`,\n  },\n  networked: {\n    description: 'Synchronizes object state across network for multiplayer.',\n    params: {\n      sync_rate: 'Updates per second (e.g., \"20hz\")',\n      interpolation: 'Smooth updates (default: true)',\n    },\n    example: `orb player {\\n  @networked(sync_rate: \"30hz\")\\n  position: synced\\n}`,\n  },\n  glowing: {\n    description: 'Makes object emit light/glow effect.',\n    params: {\n      intensity: 'Glow intensity 0-1 (default: 0.5)',\n      color: 'Glow color hex',\n      pulse: 'Pulsing (default: false)',\n    },\n    example: `orb crystal {\\n  @glowing(intensity: 0.8, color: \"#00ffff\", pulse: true)\\n}`,\n  },\n  clickable: {\n    description: 'Object responds to click/point interaction.',\n    params: { on_click: 'Handler function', highlight: 'Highlight on hover (default: true)' },\n    example: `orb button {\\n  @clickable(on_click: handleClick)\\n  text: \"Press Me\"\\n}`,\n  },\n  hoverable: {\n    description: 'Object responds to gaze/pointer hover.',\n    params: {\n      on_enter: 'Hover start handler',\n      on_exit: 'Hover end handler',\n      delay: 'Trigger delay (default: 0)',\n    },\n    example: `orb tooltip_trigger {\\n  @hoverable(on_enter: showTooltip, on_exit: hideTooltip)\\n}`,\n  },\n  billboard: {\n    description: 'Object always faces the camera/user.',\n    params: { axis: 'Constraint: \"all\", \"y\", \"x\" (default: \"all\")' },\n    example: `orb label {\\n  @billboard(axis: \"y\")\\n  text: \"Always Visible\"\\n}`,\n  },\n  spatial_audio: {\n    description: 'Audio emanates from object position with 3D spatialization.',\n    params: {\n      src: 'Audio file',\n      loop: 'Loop (default: false)',\n      volume: 'Volume 0-1',\n      distance: 'Max distance (default: 10)',\n    },\n    example: `orb radio {\\n  @spatial_audio(src: \"music.mp3\", loop: true, distance: 5)\\n}`,\n  },\n  equippable: {\n    description: 'Object can be equipped to a slot.',\n    params: {\n      slot: '\"hand\", \"head\", \"body\", \"back\"',\n      on_equip: 'Equip handler',\n      on_unequip: 'Remove handler',\n    },\n    example: `orb helmet {\\n  @equippable(slot: \"head\")\\n  @grabbable\\n  model: \"helmet.glb\"\\n}`,\n  },\n  destructible: {\n    description: 'Object can be destroyed/broken.',\n    params: {\n      health: 'HP before destroy (default: 100)',\n      on_destroy: 'Destroy handler',\n      fragments: 'Debris count (default: 0)',\n    },\n    example: `orb crate {\\n  @destructible(health: 50, fragments: 5)\\n  @collidable\\n}`,\n  },\n  animated: {\n    description: 'Plays embedded animations from model file.',\n    params: {\n      clip: 'Animation clip name',\n      loop: 'Loop (default: true)',\n      speed: 'Speed multiplier (default: 1.0)',\n    },\n    example: `orb character {\\n  @animated(clip: \"idle\", loop: true)\\n  model: \"character.glb\"\\n}`,\n  },\n};\n\n// All traits organized by category\nconst allTraits: Record<string, string[]> = {\n  interaction: [\n    'grabbable',\n    'throwable',\n    'holdable',\n    'clickable',\n    'hoverable',\n    'draggable',\n    'selectable',\n    'focusable',\n    'pointable',\n    'scalable',\n    'rotatable',\n  ],\n  physics: ['collidable', 'physics', 'rigid', 'kinematic', 'trigger', 'gravity', 'buoyant'],\n  visual: [\n    'glowing',\n    'emissive',\n    'transparent',\n    'reflective',\n    'animated',\n    'billboard',\n    'sprite',\n    'instanced',\n    'pulse',\n    'outline',\n  ],\n  networking: ['networked', 'synced', 'persistent', 'owned', 'host_only', 'local_only'],\n  behavior: [\n    'stackable',\n    'attachable',\n    'equippable',\n    'consumable',\n    'destructible',\n    'respawnable',\n    'breakable',\n    'character',\n    'patrol',\n  ],\n  spatial: ['anchor', 'tracked', 'world_locked', 'hand_tracked', 'eye_tracked', 'head_tracked'],\n  audio: [\n    'spatial_audio',\n    'ambient',\n    'voice_activated',\n    'music_reactive',\n    'reverb_zone',\n    'voice_proximity',\n  ],\n  state: ['state', 'reactive', 'observable', 'computed', 'persistent_state'],\n  advanced: [\n    'teleport',\n    'ui_panel',\n    'particle_system',\n    'weather',\n    'day_night',\n    'lod',\n    'hand_tracking',\n    'haptic',\n    'portal',\n    'mirror',\n  ],\n};\n\n// =============================================================================\n// TOOL DEFINITIONS\n// =============================================================================\n\nexport const ideTools: Tool[] = [\n  {\n    name: 'hs_scan_project',\n    description: `Scan workspace for all HoloScript files and return project context. Returns:\n- All .holo, .hsplus, .hs files with their objects/templates\n- All 3D assets (.glb, .gltf)\n- Error counts per file\n- Project structure overview\n\nUse this first when working on a HoloScript project to understand the codebase.`,\n    inputSchema: {\n      type: 'object',\n      properties: {\n        path: { type: 'string', description: 'Workspace root path (defaults to cwd)' },\n        includeAssets: { type: 'boolean', description: 'Include 3D assets (default: true)' },\n        maxDepth: { type: 'number', description: 'Max directory depth (default: 5)' },\n      },\n    },\n  },\n\n  {\n    name: 'hs_diagnostics',\n    description: `Get LSP-style diagnostics for HoloScript code with quick fixes. Returns:\n- Syntax errors with line/column\n- Unknown trait warnings\n- Missing property hints\n- Quick fix suggestions for each issue`,\n    inputSchema: {\n      type: 'object',\n      properties: {\n        code: { type: 'string', description: 'HoloScript code to diagnose' },\n        filePath: { type: 'string', description: 'File path for context' },\n        severity: {\n          type: 'string',\n          enum: ['error', 'warning', 'info', 'all'],\n          description: 'Filter by severity (default: all)',\n        },\n      },\n      required: ['code'],\n    },\n  },\n\n  {\n    name: 'hs_autocomplete',\n    description: `Get context-aware code completions at a cursor position. Returns:\n- Trait suggestions after @\n- Property suggestions inside objects\n- Template names for \"using\"\n- Object references in logic blocks`,\n    inputSchema: {\n      type: 'object',\n      properties: {\n        code: { type: 'string', description: 'Full HoloScript code' },\n        line: { type: 'number', description: 'Cursor line (1-based)' },\n        column: { type: 'number', description: 'Cursor column (1-based)' },\n        triggerCharacter: { type: 'string', description: 'Trigger character (\"@\", \".\", \":\")' },\n      },\n      required: ['code', 'line', 'column'],\n    },\n  },\n\n  {\n    name: 'hs_refactor',\n    description: `Perform refactoring operations on HoloScript code:\n- **rename**: Rename object/template/function across code\n- **extract_template**: Extract object into a reusable template\n- **inline_template**: Inline template into objects\n- **organize_imports**: Sort and clean up imports\n- **group_objects**: Move objects into a spatial_group`,\n    inputSchema: {\n      type: 'object',\n      properties: {\n        code: { type: 'string', description: 'HoloScript code to refactor' },\n        operation: {\n          type: 'string',\n          enum: [\n            'rename',\n            'extract_template',\n            'inline_template',\n            'organize_imports',\n            'group_objects',\n          ],\n        },\n        target: { type: 'string', description: 'Target name (for rename: old name)' },\n        newName: { type: 'string', description: 'New name (for rename/extract)' },\n      },\n      required: ['code', 'operation'],\n    },\n  },\n\n  {\n    name: 'hs_docs',\n    description: `Get inline documentation for HoloScript constructs:\n- **trait**: Full documentation for a @trait\n- **property**: Documentation for an object property\n- **keyword**: Syntax help for keywords\n- **all_traits**: List all VR traits with brief descriptions`,\n    inputSchema: {\n      type: 'object',\n      properties: {\n        query: { type: 'string', description: 'What to look up (trait name, property, keyword)' },\n        type: { type: 'string', enum: ['trait', 'property', 'keyword', 'example', 'all_traits'] },\n        context: { type: 'string', description: 'Surrounding code for context' },\n      },\n      required: ['query'],\n    },\n  },\n\n  {\n    name: 'hs_code_action',\n    description: `Get available code actions at a position (like VS Code lightbulb). Returns:\n- Quick fixes for errors\n- Refactoring suggestions\n- Add missing traits\n- Convert to template`,\n    inputSchema: {\n      type: 'object',\n      properties: {\n        code: { type: 'string', description: 'HoloScript code' },\n        line: { type: 'number', description: 'Line number (1-based)' },\n        column: { type: 'number', description: 'Column number (1-based)' },\n      },\n      required: ['code', 'line'],\n    },\n  },\n\n  {\n    name: 'hs_hover',\n    description: `Get hover information at a position (tooltip). Returns:\n- Type information\n- Trait documentation\n- Object definition preview`,\n    inputSchema: {\n      type: 'object',\n      properties: {\n        code: { type: 'string', description: 'HoloScript code' },\n        line: { type: 'number', description: 'Line number (1-based)' },\n        column: { type: 'number', description: 'Column number (1-based)' },\n      },\n      required: ['code', 'line', 'column'],\n    },\n  },\n\n  {\n    name: 'hs_go_to_definition',\n    description: `Find the definition of a symbol. Returns file path, line/column, and preview.`,\n    inputSchema: {\n      type: 'object',\n      properties: {\n        code: { type: 'string', description: 'Current file code' },\n        symbol: { type: 'string', description: 'Symbol name to find' },\n        projectPath: { type: 'string', description: 'Project root for cross-file search' },\n      },\n      required: ['symbol'],\n    },\n  },\n\n  {\n    name: 'hs_find_references',\n    description: `Find all references to a symbol across the project.`,\n    inputSchema: {\n      type: 'object',\n      properties: {\n        symbol: { type: 'string', description: 'Symbol name to find references for' },\n        projectPath: { type: 'string', description: 'Project root for cross-file search' },\n        includeDeclaration: {\n          type: 'boolean',\n          description: 'Include the declaration (default: true)',\n        },\n      },\n      required: ['symbol'],\n    },\n  },\n];\n\n// =============================================================================\n// TOOL HANDLER\n// =============================================================================\n\nexport async function handleIDETool(name: string, args: Record<string, unknown>): Promise<unknown> {\n  switch (name) {\n    case 'hs_scan_project': {\n      const rootPath = (args.path as string) || process.cwd();\n      const includeAssets = args.includeAssets !== false;\n      const maxDepth = (args.maxDepth as number) || 5;\n\n      const files: ProjectFile[] = [];\n\n      const scanDir = (dir: string, depth: number): void => {\n        if (depth > maxDepth) return;\n\n        try {\n          const entries = fs.readdirSync(dir, { withFileTypes: true });\n          for (const entry of entries) {\n            if (entry.name.startsWith('.') || entry.name === 'node_modules') continue;\n\n            const fullPath = path.join(dir, entry.name);\n\n            if (entry.isDirectory()) {\n              scanDir(fullPath, depth + 1);\n            } else {\n              const ext = path.extname(entry.name).toLowerCase();\n              let type: ProjectFile['type'] = 'other';\n\n              if (ext === '.holo') type = 'holo';\n              else if (ext === '.hsplus') type = 'hsplus';\n              else if (ext === '.hs') type = 'hs';\n              else if (ext === '.glb') type = 'glb';\n              else if (ext === '.gltf') type = 'gltf';\n              else continue;\n\n              if (!includeAssets && (type === 'glb' || type === 'gltf')) continue;\n\n              const file: ProjectFile = {\n                path: path.relative(rootPath, fullPath),\n                type,\n              };\n\n              if (type === 'holo' || type === 'hsplus' || type === 'hs') {\n                try {\n                  const content = fs.readFileSync(fullPath, 'utf-8');\n                  const extract = (pattern: RegExp) =>\n                    [...content.matchAll(pattern)].map((m) => m[1]);\n                  file.objects = extract(/(?:orb|object)\\s+[\"']?(\\w+)/g);\n                  file.templates = extract(/template\\s+[\"'](\\w+)/g);\n                  file.traits = [...new Set(extract(/@(\\w+)/g))];\n                } catch {\n                  file.errors = 1;\n                }\n              }\n\n              files.push(file);\n            }\n          }\n        } catch {\n          // Skip inaccessible directories\n        }\n      };\n\n      scanDir(rootPath, 0);\n\n      return {\n        summary: {\n          totalFiles: files.length,\n          holoFiles: files.filter((f) => f.type === 'holo').length,\n          hsplusFiles: files.filter((f) => f.type === 'hsplus').length,\n          hsFiles: files.filter((f) => f.type === 'hs').length,\n          assets: files.filter((f) => f.type === 'glb' || f.type === 'gltf').length,\n          allObjects: [...new Set(files.flatMap((f) => f.objects || []))],\n          allTemplates: [...new Set(files.flatMap((f) => f.templates || []))],\n          allTraits: [...new Set(files.flatMap((f) => f.traits || []))],\n        },\n        files,\n      };\n    }\n\n    case 'hs_diagnostics': {\n      const code = args.code as string;\n      const severity = (args.severity as string) || 'all';\n      const diagnostics: Diagnostic[] = [];\n      const lines = code.split('\\n');\n\n      lines.forEach((line, i) => {\n        const traitMatches = line.matchAll(/@(\\w+)/g);\n        for (const match of traitMatches) {\n          const trait = match[1];\n          const allTraitNames = Object.values(allTraits).flat();\n          if (!allTraitNames.includes(trait)) {\n            diagnostics.push({\n              file: (args.filePath as string) || '<input>',\n              line: i + 1,\n              column: match.index! + 1,\n              severity: 'warning',\n              message: `Unknown trait: @${trait}`,\n              code: 'unknown-trait',\n              quickFixes: [\n                {\n                  title: `Did you mean a similar trait?`,\n                  edit: {\n                    range: {\n                      start: { line: i + 1, column: match.index! + 1 },\n                      end: { line: i + 1, column: match.index! + 1 + trait.length + 1 },\n                    },\n                    newText: `@${findClosestTrait(trait)}`,\n                  },\n                },\n              ],\n            });\n          }\n        }\n\n        if (line.includes('orb') && !line.match(/orb\\s+\\w+\\s*\\{?/)) {\n          diagnostics.push({\n            file: (args.filePath as string) || '<input>',\n            line: i + 1,\n            column: line.indexOf('orb') + 1,\n            severity: 'error',\n            message: 'orb must be followed by a name',\n            code: 'syntax-error',\n          });\n        }\n      });\n\n      const filtered =\n        severity === 'all' ? diagnostics : diagnostics.filter((d) => d.severity === severity);\n\n      return { count: filtered.length, diagnostics: filtered };\n    }\n\n    case 'hs_autocomplete': {\n      const code = args.code as string;\n      const line = args.line as number;\n      const column = args.column as number;\n      const trigger = args.triggerCharacter as string;\n\n      const lines = code.split('\\n');\n      const currentLine = lines[line - 1] || '';\n      const beforeCursor = currentLine.slice(0, column - 1);\n\n      const completions: CompletionItem[] = [];\n\n      if (trigger === '@' || beforeCursor.endsWith('@')) {\n        for (const [category, traits] of Object.entries(allTraits)) {\n          for (const trait of traits) {\n            const docs = traitDocs[trait];\n            completions.push({\n              label: trait,\n              kind: 'trait',\n              detail: `(${category}) VR trait`,\n              documentation: docs?.description || `The @${trait} trait`,\n              insertText: docs?.params ? `${trait}($1)` : trait,\n              insertTextFormat: docs?.params ? 'snippet' : 'plaintext',\n            });\n          }\n        }\n      } else if (beforeCursor.match(/^\\s+\\w*$/)) {\n        const properties = [\n          { label: 'position', detail: '[x, y, z]' },\n          { label: 'rotation', detail: '[rx, ry, rz]' },\n          { label: 'scale', detail: 'number or [x, y, z]' },\n          { label: 'color', detail: '\"#hex\" or [r, g, b]' },\n          { label: 'model', detail: '\"path.glb\"' },\n          { label: 'text', detail: '\"label text\"' },\n        ];\n        for (const prop of properties) {\n          completions.push({\n            label: prop.label,\n            kind: 'property',\n            detail: prop.detail,\n            insertText: `${prop.label}: `,\n          });\n        }\n      } else if (beforeCursor.match(/^\\s*$/)) {\n        const keywords = [\n          'orb',\n          'template',\n          'composition',\n          'environment',\n          'spatial_group',\n          'logic',\n          'function',\n          'connect',\n          'object',\n        ];\n        for (const kw of keywords) {\n          completions.push({\n            label: kw,\n            kind: 'keyword',\n            detail: 'HoloScript keyword',\n          });\n        }\n      }\n\n      return { completions };\n    }\n\n    case 'hs_docs': {\n      const query = (args.query as string).toLowerCase().replace('@', '');\n      const type = (args.type as string) || 'trait';\n\n      if (type === 'all_traits') {\n        const result: Record<string, { traits: string[]; descriptions: Record<string, string> }> =\n          {};\n        for (const [category, traits] of Object.entries(allTraits)) {\n          result[category] = {\n            traits,\n            descriptions: Object.fromEntries(\n              traits.map((t) => [t, traitDocs[t]?.description || `The @${t} trait`])\n            ),\n          };\n        }\n        return result;\n      }\n\n      if (type === 'trait') {\n        const docs = traitDocs[query];\n        if (!docs) {\n          const exists = Object.values(allTraits).flat().includes(query);\n          if (exists) {\n            return {\n              trait: `@${query}`,\n              description: `The @${query} VR trait. (Detailed docs in explain_trait tool)`,\n              example: `orb obj {\\n  @${query}\\n  position: [0, 0, 0]\\n}`,\n            };\n          }\n          return {\n            error: `Unknown trait: @${query}`,\n            hint: 'Use hs_docs with type \"all_traits\" to see available traits',\n          };\n        }\n        return { trait: `@${query}`, ...docs };\n      }\n\n      return { error: `Unsupported query type: ${type}`, supportedTypes: ['trait', 'all_traits'] };\n    }\n\n    case 'hs_refactor': {\n      const code = args.code as string;\n      const operation = args.operation as string;\n      const target = args.target as string;\n      const newName = args.newName as string;\n\n      let result = code;\n      const changes: string[] = [];\n\n      switch (operation) {\n        case 'rename':\n          if (!target || !newName) {\n            return { error: 'rename requires target and newName' };\n          }\n          const regex = new RegExp(`\\\\b${target}\\\\b`, 'g');\n          const count = (code.match(regex) || []).length;\n          result = code.replace(regex, newName);\n          changes.push(`Renamed \"${target}\" -> \"${newName}\" (${count} occurrences)`);\n          break;\n\n        case 'extract_template':\n          if (!target || !newName) {\n            return {\n              error: 'extract_template requires target (object name) and newName (template name)',\n            };\n          }\n          const objMatch = code.match(new RegExp(`orb\\\\s+${target}\\\\s*\\\\{([^}]+)\\\\}`, 's'));\n          if (objMatch) {\n            const template = `template \"${newName}\" {\\n${objMatch[1]}\\n}\\n\\n`;\n            const replacement = `object \"${target}\" using \"${newName}\" {\\n  position: [0, 0, 0]\\n}`;\n            result = template + code.replace(objMatch[0], replacement);\n            changes.push(`Extracted orb \"${target}\" into template \"${newName}\"`);\n          }\n          break;\n\n        case 'organize_imports':\n          const imports = [...code.matchAll(/import\\s+.+/g)].map((m) => m[0]);\n          const uniqueImports = [...new Set(imports)].sort();\n          let cleanCode = code;\n          imports.forEach((imp) => {\n            cleanCode = cleanCode.replace(imp + '\\n', '');\n          });\n          result =\n            uniqueImports.join('\\n') + (uniqueImports.length ? '\\n\\n' : '') + cleanCode.trim();\n          changes.push(`Organized ${imports.length} imports`);\n          break;\n      }\n\n      return { code: result, changes };\n    }\n\n    case 'hs_hover': {\n      const code = args.code as string;\n      const line = args.line as number;\n      const column = args.column as number;\n\n      const lines = code.split('\\n');\n      const currentLine = lines[line - 1] || '';\n\n      const traitMatch = currentLine.match(/@(\\w+)/);\n      if (\n        traitMatch &&\n        column >= currentLine.indexOf('@') &&\n        column <= currentLine.indexOf('@') + traitMatch[0].length\n      ) {\n        const trait = traitMatch[1];\n        const docs = traitDocs[trait];\n        return {\n          content: docs\n            ? `**@${trait}**\\n\\n${docs.description}\\n\\n\\`\\`\\`hsplus\\n${docs.example}\\n\\`\\`\\``\n            : `**@${trait}** - VR trait`,\n          range: {\n            start: { line, column: currentLine.indexOf('@') + 1 },\n            end: { line, column: currentLine.indexOf('@') + traitMatch[0].length + 1 },\n          },\n        };\n      }\n\n      return { content: null };\n    }\n\n    case 'hs_go_to_definition':\n    case 'hs_find_references':\n    case 'hs_code_action':\n      return {\n        note: 'Full implementation requires project indexing. Use hs_scan_project first for context.',\n        symbol: args.symbol,\n      };\n\n    default:\n      throw new Error(`Unknown IDE tool: ${name}`);\n  }\n}\n\n// =============================================================================\n// HELPERS\n// =============================================================================\n\nfunction findClosestTrait(input: string): string {\n  const allTraitNames = Object.values(allTraits).flat();\n  const normalized = input.toLowerCase();\n\n  // Exact prefix match\n  const prefixMatch = allTraitNames.find((t) => t.startsWith(normalized));\n  if (prefixMatch) return prefixMatch;\n\n  // Substring match\n  const subMatch = allTraitNames.find((t) => t.includes(normalized) || normalized.includes(t));\n  if (subMatch) return subMatch;\n\n  // First 3 chars match\n  const shortMatch = allTraitNames.find((t) => t.substring(0, 3) === normalized.substring(0, 3));\n  if (shortMatch) return shortMatch;\n\n  return 'grabbable'; // safe default\n}\n","export interface RailwayPostgresPoolOptions {\n  connectionString: string;\n  ssl: false | { rejectUnauthorized: false };\n  max?: number;\n}\n\nexport function createRailwayPostgresPoolOptions(\n  databaseUrl: string,\n  extras: Omit<Partial<RailwayPostgresPoolOptions>, 'connectionString' | 'ssl'> = {}\n): RailwayPostgresPoolOptions {\n  return {\n    connectionString: databaseUrl,\n    ssl: process.env.DATABASE_SSL === 'false' ? false : { rejectUnauthorized: false },\n    ...extras,\n  };\n}\n","/**\n * mcp-server HoloKey resolver + one-shot env→vault migration — Phase 2.\n *\n * Resolves a service config secret from the HoloKey vault (the prod Postgres + the shared\n * `HOLOKEY_PROD_KEK_*` KEK) if it's there, else from `process.env`. A consumer swaps\n * `process.env.ANTHROPIC_API_KEY` for `await resolveServiceSecret('ANTHROPIC_API_KEY')` and\n * behavior is IDENTICAL until that key is put in the vault — then it transparently resolves\n * from the vault. `infra://ANTHROPIC_API_KEY` is also accepted for operational refs. No boot\n * coupling: the pool + vault are built lazily on first call.\n *\n * `migrateEnvKeys` is the \"set once\" step run INSIDE the service: it copies named secrets from\n * `process.env` into the vault (owner-scoped, idempotent), so the value reads from the service's\n * own env and never transits a wire as plaintext beyond the encrypted store.\n *\n * Fail-safe by construction (premortem): the pg pool init and the `SECRET_STORE_DDL` apply each\n * have their OWN try/catch — a DB/perms/schema failure NEVER throws into a caller; resolves fall\n * back to env. `createServiceSecretResolver` logs ONE affirmation line (vault ON/OFF) on first use.\n *\n * @module mcp-server/holokey-resolver\n */\nimport { Pool } from 'pg';\nimport {\n  AuthRequiredError,\n  createHoloKeyVault,\n  createServiceSecretResolver,\n  registerNeedsKeyTrait,\n  SECRET_STORE_DDL,\n  SecretNotFoundError,\n  type HoloKeyVault,\n  type SecretResolver,\n  type ServiceIdentity,\n  type ServiceSecretResolver,\n} from '@holoscript/secrets-broker';\nimport type { SigningContext } from './holomesh/identity/signing-middleware';\nimport { createRailwayPostgresPoolOptions } from './postgres-pool-options';\n\nlet built = false;\nlet vault: HoloKeyVault | null = null;\nlet resolver: ServiceSecretResolver | null = null;\nlet serviceIdentity: ServiceIdentity | null = null;\n\ninterface NeedsKeyTraitRegistrar {\n  registerTrait(name: string, handler: unknown): void;\n}\n\nexport interface McpNeedsKeyRegistrationResult {\n  registered: true;\n  ownerId: string | null;\n  authenticated: boolean;\n  vaultConfigured: boolean;\n}\n\nconst unavailableSecretResolver: SecretResolver = {\n  async resolve(input) {\n    if (!input.authenticatedOwnerId) {\n      throw new AuthRequiredError(input.ref);\n    }\n    throw new SecretNotFoundError(input.ref);\n  },\n};\n\nfunction ensure(): void {\n  if (built) return;\n  built = true;\n\n  let query:\n    | ((\n        sql: string,\n        params: readonly unknown[]\n      ) => Promise<{ rows: Array<Record<string, unknown>> }>)\n    | undefined;\n  const dbUrl = process.env.DATABASE_URL;\n  if (dbUrl) {\n    try {\n      const pool = new Pool(createRailwayPostgresPoolOptions(dbUrl, { max: 2 }));\n      void pool.query(SECRET_STORE_DDL).catch((e: unknown) => {\n        // eslint-disable-next-line no-console\n        console.warn(\n          `[holokey] SECRET_STORE_DDL apply failed (resolves fall back to env): ${e instanceof Error ? e.message : String(e)}`\n        );\n      });\n      query = (sql, params) => pool.query(sql, params as unknown[]);\n    } catch (e) {\n      // eslint-disable-next-line no-console\n      console.warn(\n        `[holokey] pg pool init failed (resolves fall back to env): ${e instanceof Error ? e.message : String(e)}`\n      );\n    }\n  }\n\n  vault = createHoloKeyVault({ env: process.env, query });\n  resolver = createServiceSecretResolver({ vault, env: process.env });\n  serviceIdentity = resolver.identity();\n}\n\n/**\n * Resolve a service config secret: the HoloKey vault value if present (for this service's\n * owner, decrypted at use-time), else `process.env[name]`. Never throws; fully fallback-safe.\n */\nexport function resolveServiceSecret(name: string): Promise<string | undefined> {\n  ensure();\n  return resolver!.resolve(name);\n}\n\nexport function ownerIdFromSigningContext(signingCtx: SigningContext | null | undefined) {\n  if (!signingCtx?.signingValid || !signingCtx.signer) return null;\n  return signingCtx.signer;\n}\n\n/**\n * Bind HoloKey's `@needs_key` trait for an MCP request-scoped runtime.\n *\n * The owner is derived from the verified SigningContext signer. When HoloKey is\n * not provisioned on the service, the trait is still registered against a\n * value-free resolver that denies every request instead of letting the trait\n * silently disappear.\n */\nexport function registerNeedsKeyTraitForMcpRequest(\n  registrar: NeedsKeyTraitRegistrar,\n  input: {\n    signingCtx?: SigningContext | null;\n    resolver?: SecretResolver | null;\n  } = {}\n): McpNeedsKeyRegistrationResult {\n  ensure();\n  const ownerId = ownerIdFromSigningContext(input.signingCtx);\n  const secretResolver = input.resolver ?? vault?.resolver ?? unavailableSecretResolver;\n\n  registerNeedsKeyTrait(registrar, {\n    resolver: secretResolver,\n    authenticatedOwnerId: ownerId,\n  });\n\n  return {\n    registered: true,\n    ownerId,\n    authenticated: ownerId !== null,\n    vaultConfigured: Boolean(input.resolver ?? vault?.resolver),\n  };\n}\n\n/**\n * One-shot migration: copy the named secrets from `process.env` INTO the vault under the\n * derived service owner, idempotent (skips ones already stored). Returns NAMES only — never a value.\n */\nexport async function migrateEnvKeys(\n  names: readonly string[]\n): Promise<{ vaultOff: boolean; owner: string; migrated: string[]; skipped: string[] }> {\n  ensure();\n  const migrated: string[] = [];\n  const skipped: string[] = [];\n  const owner = serviceIdentity?.ownerId ?? 'infra';\n  if (!vault) return { vaultOff: true, owner, migrated, skipped };\n  for (const name of names) {\n    const value = process.env[name];\n    if (!value) {\n      skipped.push(`${name}:no-env`);\n      continue;\n    }\n    try {\n      // Already in the vault for this owner? skip (idempotent).\n      await vault.resolver.resolve({ authenticatedOwnerId: owner, ref: `vault:${name}` });\n      skipped.push(`${name}:exists`);\n    } catch {\n      // Not present (or unreadable) → store it.\n      try {\n        await vault.store.put({ ownerId: owner, name, value });\n        migrated.push(name);\n      } catch {\n        skipped.push(`${name}:err`);\n      }\n    }\n  }\n  return { vaultOff: false, owner, migrated, skipped };\n}\n","/**\n * LLM Client for HoloScript MCP Server — Cloud-First\n *\n * Auto-detects the best available provider from env vars:\n *   1. 'openrouter'  — OpenRouter (preferred, best model routing)\n *   2. 'anthropic'   — Anthropic Claude API direct\n *   3. 'openai'      — OpenAI API\n *   4. 'ollama'      — local Ollama instance (fallback only)\n *\n * Override with LLM_PROVIDER env var. Auto-detect runs if not set.\n *\n * Migrated (B1c) from inline fetch() calls to @holoscript/llm-provider\n * adapters which inherit withRetry from BaseLLMAdapter — exponential\n * backoff + Retry-After honoring on 429/5xx.\n *\n * Used by brittney-lite.ts, generators.ts, and self-improve-tools.ts\n * with graceful fallback to rule-based logic when unavailable.\n */\n\nimport {\n  AnthropicAdapter,\n  OpenAIAdapter,\n  OpenRouterAdapter,\n  LocalLLMAdapter,\n  LOCAL_DEFAULT_MODEL,\n  type ILLMProvider,\n  type LLMCompletionRequest,\n} from '@holoscript/llm-provider';\nimport { resolveServiceSecret } from './holokey-resolver';\n\ntype LLMProviderName = 'hybrid-gemma' | 'openrouter' | 'anthropic' | 'openai' | 'ollama';\n\nfunction detectProvider(): LLMProviderName {\n  const explicit = process.env.LLM_PROVIDER as LLMProviderName;\n  if (\n    explicit &&\n    ['hybrid-gemma', 'openrouter', 'anthropic', 'openai', 'ollama'].includes(explicit)\n  )\n    return explicit;\n  // Auto-detect from available keys\n  if (process.env.OPENROUTER_API_KEY) return 'openrouter';\n  if (process.env.ANTHROPIC_API_KEY) return 'anthropic';\n  if (process.env.OPENAI_API_KEY) return 'openai';\n  return 'ollama';\n}\n\nconst LLM_PROVIDER: LLMProviderName = detectProvider();\n\n// ── OpenRouter config ───────────────────────────────────────────────────────\nconst OPENROUTER_MODEL = process.env.OPENROUTER_MODEL || 'anthropic/claude-haiku-4.5';\n\n// ── Anthropic config ─────────────────────────────────────────────────────────\n// Use the alias (auto-resolves to latest pinned build) not the date-suffixed ID.\n// Haiku is the right default here — this is a fallback path for cheap/fast calls.\nconst ANTHROPIC_MODEL = process.env.ANTHROPIC_MODEL || 'claude-haiku-4-5';\n\n// ── OpenAI config ────────────────────────────────────────────────────────────\nconst OPENAI_MODEL = process.env.OPENAI_MODEL || 'gpt-4o-mini';\n\n// ── Ollama config (local fallback only) ──────────────────────────────────────\nconst OLLAMA_URL = process.env.OLLAMA_URL || ''; // Ollama is optional — empty means disabled\nconst OLLAMA_MODEL = process.env.OLLAMA_MODEL || LOCAL_DEFAULT_MODEL;\n\n// ── Gemma 4 Hybrid Routing config ────────────────────────────────────────────\nconst GEMMA_EDGE_MODEL = process.env.GEMMA_EDGE_MODEL || 'gemma4:e4b';\nconst GEMMA_CLOUD_MODEL = process.env.GEMMA_CLOUD_MODEL || 'google/gemma-4-31b';\n\nconst LLM_TIMEOUT = 60_000; // 60s for generation\n\n/** HoloScript-specific system prompt for model calls */\nexport const HOLOSCRIPT_SYSTEM_PROMPT = `You are Brittney, an expert HoloScript assistant. Follow these rules strictly:\n\n1. Output ONLY raw HoloScript code when asked to generate code — no markdown fences, no backticks, no explanations unless explicitly asked.\n2. Use geometry: (never type:) for shapes. Valid geometries: sphere, cube, cylinder, cone, plane, torus, ring, capsule, model, custom, text.\n3. Always quote object names: object \"Name\" { ... }\n4. Use negative z values for object visibility: position: [0, 1, -3]\n5. Wrap scenes in composition \"Name\" { ... }\n6. Only use canonical @traits. Common traits: @grabbable, @collidable, @physics, @glowing, @networked, @floating, @animated, @clickable, @hoverable, @draggable, @throwable, @spatial_audio, @teleport, @portal, @lod, @billboard, @particle_system, @sculpt_volume, @printable, @iot_bridge, @digital_twin, @collaborative_sculpt.\n7. Never emit [Think], [/Think], or other meta-blocks.\n8. For .hsplus files, use orb syntax: orb Name { ... }\n9. For .holo files, always include composition wrapper with environment block.`;\n\n// =============================================================================\n// ADAPTER INSTANCES (lazy-initialized, reuse across calls)\n// =============================================================================\n\nlet _anthropicAdapter: AnthropicAdapter | null = null;\nlet _openaiAdapter: OpenAIAdapter | null = null;\nlet _openrouterAdapter: OpenRouterAdapter | null = null;\nlet _ollamaAdapter: LocalLLMAdapter | null = null;\n\n// Adapter key resolution (Phase 2): prefer the HoloKey vault value, else the module-level\n// env const. Resolved ONCE at adapter construction and cached with the adapter — no per-call\n// DB hit on the hot path. Fully fallback-safe: vault off / key not in vault → the env const.\nasync function getAnthropicAdapter(): Promise<AnthropicAdapter | null> {\n  if (_anthropicAdapter) return _anthropicAdapter;\n  const apiKey = await resolveServiceSecret('ANTHROPIC_API_KEY');\n  if (!apiKey) return null;\n  _anthropicAdapter = new AnthropicAdapter({\n    apiKey,\n    defaultModel: ANTHROPIC_MODEL,\n    timeoutMs: LLM_TIMEOUT,\n  });\n  return _anthropicAdapter;\n}\n\nasync function getOpenAIAdapter(): Promise<OpenAIAdapter | null> {\n  if (_openaiAdapter) return _openaiAdapter;\n  const apiKey = await resolveServiceSecret('OPENAI_API_KEY');\n  if (!apiKey) return null;\n  _openaiAdapter = new OpenAIAdapter({\n    apiKey,\n    defaultModel: OPENAI_MODEL,\n    timeoutMs: LLM_TIMEOUT,\n  });\n  return _openaiAdapter;\n}\n\nasync function getOpenRouterAdapter(): Promise<OpenRouterAdapter | null> {\n  if (_openrouterAdapter) return _openrouterAdapter;\n  const apiKey = await resolveServiceSecret('OPENROUTER_API_KEY');\n  if (!apiKey) return null;\n  _openrouterAdapter = new OpenRouterAdapter({\n    apiKey,\n    defaultModel: OPENROUTER_MODEL,\n    timeoutMs: LLM_TIMEOUT,\n  });\n  return _openrouterAdapter;\n}\n\nfunction getOllamaAdapter(): LocalLLMAdapter | null {\n  if (!OLLAMA_URL) return null;\n  if (!_ollamaAdapter) {\n    _ollamaAdapter = new LocalLLMAdapter({\n      baseURL: OLLAMA_URL,\n      defaultModel: OLLAMA_MODEL,\n      timeoutMs: LLM_TIMEOUT,\n    });\n  }\n  return _ollamaAdapter;\n}\n\n// =============================================================================\n// PROVIDER IMPLEMENTATIONS (delegating to @holoscript/llm-provider adapters\n// with withRetry from BaseLLMAdapter — exponential backoff + Retry-After)\n// =============================================================================\n\nasync function queryOpenRouterProvider(\n  prompt: string,\n  system: string,\n  modelOverride?: string\n): Promise<string | null> {\n  const adapter = await getOpenRouterAdapter();\n  if (!adapter) return null;\n  try {\n    const result = await adapter.complete({\n      messages: [\n        { role: 'system', content: system },\n        { role: 'user', content: prompt },\n      ],\n      maxTokens: 4096,\n      ...(modelOverride && { model: modelOverride }),\n    });\n    return result.content || null;\n  } catch {\n    return null;\n  }\n}\n\nasync function queryAnthropicProvider(prompt: string, system: string): Promise<string | null> {\n  const adapter = await getAnthropicAdapter();\n  if (!adapter) return null;\n  try {\n    const result = await adapter.complete({\n      messages: [\n        { role: 'system', content: system },\n        { role: 'user', content: prompt },\n      ],\n      maxTokens: 4096,\n    });\n    return result.content || null;\n  } catch {\n    return null;\n  }\n}\n\nasync function queryOpenAIProvider(prompt: string, system: string): Promise<string | null> {\n  const adapter = await getOpenAIAdapter();\n  if (!adapter) return null;\n  try {\n    const result = await adapter.complete({\n      messages: [\n        { role: 'system', content: system },\n        { role: 'user', content: prompt },\n      ],\n      maxTokens: 4096,\n    });\n    return result.content || null;\n  } catch {\n    return null;\n  }\n}\n\nasync function queryOllamaProvider(\n  prompt: string,\n  system: string,\n  modelOverride?: string\n): Promise<string | null> {\n  const adapter = getOllamaAdapter();\n  if (!adapter) return null;\n  try {\n    const result = await adapter.complete({\n      messages: [\n        { role: 'system', content: system },\n        { role: 'user', content: prompt },\n      ],\n      maxTokens: 4096,\n      ...(modelOverride && { model: modelOverride }),\n    });\n    return result.content || null;\n  } catch {\n    return null;\n  }\n}\n\n// =============================================================================\n// PUBLIC API (backward-compatible — function name kept as queryOllama)\n// =============================================================================\n\nexport interface RoutingOptions {\n  requiresAudio?: boolean;\n  requiresDeepReasoning?: boolean;\n}\n\n/**\n * Query the configured LLM provider.\n * Returns null if the provider is unavailable or the request fails.\n *\n * Auto-detects provider from env vars: OpenRouter → Anthropic → OpenAI → Ollama.\n * Override with LLM_PROVIDER env var.\n */\n// Phase-0 fleet telemetry: per-process in-flight gauge for the agent (hs_ai_*)\n// inference path. The durable cross-process signal is the `[fleet-metric]` log\n// line below (same format as services/llm-service + studio). This is the path\n// agentic build-work over GitHub projects drives — likely the highest-volume\n// source. Ref: research/2026-05-31_self-hosted-fleet-inference-plan.md.\nlet __mcpActive = 0;\n\nexport async function queryOllama(\n  prompt: string,\n  system?: string,\n  options?: RoutingOptions\n): Promise<string | null> {\n  const sysPrompt = system || HOLOSCRIPT_SYSTEM_PROMPT;\n  const __start = Date.now();\n  __mcpActive += 1;\n  const __concurrencyAtStart = __mcpActive;\n  let __result: string | null = null;\n  let __errored = false;\n  try {\n    const activeProvider = LLM_PROVIDER;\n\n    // Apply Gemma 4 Edge-to-Cloud Routing\n    if (activeProvider === 'hybrid-gemma') {\n      const needsEdge = options?.requiresAudio || !options?.requiresDeepReasoning;\n      __result = needsEdge\n        ? await queryOllamaProvider(prompt, sysPrompt, GEMMA_EDGE_MODEL) // Edge (Gemma 4 E4B) via local Ollama\n        : await queryOpenRouterProvider(prompt, sysPrompt, GEMMA_CLOUD_MODEL); // Cloud (Gemma 4 26B/31B) via OpenRouter\n      return __result;\n    }\n\n    switch (activeProvider) {\n      case 'openrouter':\n        __result = await queryOpenRouterProvider(prompt, sysPrompt);\n        break;\n      case 'anthropic':\n        __result = await queryAnthropicProvider(prompt, sysPrompt);\n        break;\n      case 'openai':\n        __result = await queryOpenAIProvider(prompt, sysPrompt);\n        break;\n      case 'ollama':\n      default:\n        __result = await queryOllamaProvider(prompt, sysPrompt);\n        break;\n    }\n    return __result;\n  } catch {\n    __errored = true;\n    return null;\n  } finally {\n    __mcpActive -= 1;\n    // eslint-disable-next-line no-console -- intentional structured telemetry line\n    console.info(\n      `[fleet-metric] ${JSON.stringify({\n        ts: new Date().toISOString(),\n        source: 'mcp-hs-ai',\n        provider: LLM_PROVIDER,\n        promptTokens: Math.ceil((prompt.length + sysPrompt.length) / 4),\n        completionTokens: __result ? Math.ceil(__result.length / 4) : 0,\n        latencyMs: Date.now() - __start,\n        concurrencyAtStart: __concurrencyAtStart,\n        error: __errored,\n      })}`\n    );\n  }\n}\n\n/**\n * Check if the configured LLM provider is available.\n */\nexport async function isOllamaAvailable(): Promise<boolean> {\n  try {\n    switch (LLM_PROVIDER) {\n      case 'openrouter':\n        return Boolean(await resolveServiceSecret('OPENROUTER_API_KEY'));\n      case 'anthropic':\n        return Boolean(await resolveServiceSecret('ANTHROPIC_API_KEY'));\n      case 'openai':\n        return Boolean(await resolveServiceSecret('OPENAI_API_KEY'));\n      case 'ollama':\n      default:\n        // Use the adapter's healthCheck for Ollama (pings /health or /v1/models)\n        if (!OLLAMA_URL) return false;\n        const adapter = getOllamaAdapter();\n        if (!adapter) return false;\n        const health = await adapter.healthCheck();\n        return health.ok;\n    }\n  } catch {\n    return false;\n  }\n}\n\n/**\n * Get the active LLM provider name (for health endpoints).\n */\nexport function getActiveProvider(): string {\n  return LLM_PROVIDER;\n}\n\n/**\n * Strip markdown code fences from model output.\n * Models sometimes wrap output in ```holoscript ... ``` even when told not to.\n */\nexport function stripCodeFences(text: string): string {\n  return text\n    .replace(/^```[\\w]*\\n?/gm, '')\n    .replace(/\\n?```$/gm, '')\n    .trim();\n}\n","/**\n * Brittney-Lite AI Assistant Tools\n *\n * Free-tier AI assistant for HoloScript. Provides intelligent\n * error explanation, code fixing, review, and scaffolding.\n * Premium Brittney MCP adds live debugging, world\n * management, and advanced AI orchestration. Brittney is one\n * participant on the Twin Earth substrate, not the substrate itself.\n */\n\nimport { Tool } from '@modelcontextprotocol/sdk/types.js';\nimport { HoloScriptPlusParser, parseHolo, VR_TRAITS } from '@holoscript/core';\nimport { queryOllama, stripCodeFences } from './ollama-client.js';\n\n// =============================================================================\n// TOOL DEFINITIONS\n// =============================================================================\n\nexport const brittneyLiteTools: Tool[] = [\n  {\n    name: 'hs_ai_explain_error',\n    description: `Takes HoloScript validation errors and provides human-friendly explanations with fix suggestions. Instead of cryptic parser output, you get:\n- What went wrong in plain English\n- Why it happened\n- How to fix it with code example\n- Related best practices\n\nUse after validate_holoscript returns errors.`,\n    inputSchema: {\n      type: 'object',\n      properties: {\n        code: { type: 'string', description: 'The HoloScript code with errors' },\n        errors: {\n          type: 'array',\n          items: {\n            type: 'object',\n            properties: {\n              message: { type: 'string' },\n              line: { type: 'number' },\n              column: { type: 'number' },\n            },\n          },\n          description: 'Error objects from validate_holoscript (or paste error messages)',\n        },\n      },\n      required: ['code'],\n    },\n  },\n\n  {\n    name: 'hs_ai_fix_code',\n    description: `Takes broken HoloScript code and returns a fixed version. Handles:\n- Syntax errors (missing braces, semicolons)\n- Unknown traits (suggests correct names)\n- Missing required properties\n- Format inconsistencies\n- Common beginner mistakes\n\nReturns the corrected code with comments explaining each fix.`,\n    inputSchema: {\n      type: 'object',\n      properties: {\n        code: { type: 'string', description: 'HoloScript code to fix' },\n        format: {\n          type: 'string',\n          enum: ['hs', 'hsplus', 'holo', 'auto'],\n          description: 'Expected format (default: auto-detect)',\n        },\n      },\n      required: ['code'],\n    },\n  },\n\n  {\n    name: 'hs_ai_review',\n    description: `Code review for HoloScript best practices. Returns:\n- Performance issues (too many physics objects, missing LOD)\n- Missing traits (grabbable without collidable, etc.)\n- Naming conventions\n- Scene organization suggestions\n- Multiplayer readiness check\n- Trait compatibility warnings`,\n    inputSchema: {\n      type: 'object',\n      properties: {\n        code: { type: 'string', description: 'HoloScript code to review' },\n        focus: {\n          type: 'string',\n          enum: ['performance', 'traits', 'structure', 'multiplayer', 'all'],\n          description: 'Focus area for review (default: all)',\n        },\n      },\n      required: ['code'],\n    },\n  },\n\n  {\n    name: 'hs_ai_scaffold',\n    description: `Generate project scaffolding from a high-level description. Creates:\n- Composition structure with environment\n- Templates for reusable objects\n- Object instances with positions\n- Logic block with event handlers\n- Recommended trait assignments\n\nMore comprehensive than generate_scene - creates production-ready structure.`,\n    inputSchema: {\n      type: 'object',\n      properties: {\n        description: { type: 'string', description: 'High-level description of what to build' },\n        type: {\n          type: 'string',\n          enum: ['game', 'showcase', 'social', 'training', 'art'],\n          description: 'Project type for appropriate defaults',\n        },\n        features: {\n          type: 'array',\n          items: { type: 'string' },\n          description: 'Features to include: physics, multiplayer, audio, ai, ui',\n        },\n      },\n      required: ['description'],\n    },\n  },\n];\n\n// =============================================================================\n// KNOWN TRAITS (built from VR_TRAITS — the single source of truth in core)\n// =============================================================================\n\nconst KNOWN_TRAITS: Set<string> = new Set(VR_TRAITS as readonly string[]);\n\n// Trait compatibility rules\nconst TRAIT_REQUIRES: Record<string, string[]> = {\n  throwable: ['grabbable'],\n  holdable: ['grabbable'],\n  synced: ['networked'],\n  owned: ['networked'],\n  host_only: ['networked'],\n};\n\nconst TRAIT_RECOMMENDS: Record<string, string[]> = {\n  grabbable: ['collidable'],\n  physics: ['collidable'],\n  throwable: ['physics'],\n  character: ['collidable'],\n  breakable: ['physics', 'collidable'],\n  particle_system: ['emissive'],\n};\n\n// =============================================================================\n// HANDLER\n// =============================================================================\n\nexport async function handleBrittneyLiteTool(\n  name: string,\n  args: Record<string, unknown>\n): Promise<unknown> {\n  switch (name) {\n    case 'hs_ai_explain_error':\n      return handleExplainError(args);\n    case 'hs_ai_fix_code':\n      return handleFixCode(args);\n    case 'hs_ai_review':\n      return handleReview(args);\n    case 'hs_ai_scaffold':\n      return handleScaffold(args);\n    default:\n      throw new Error(`Unknown Brittney-Lite tool: ${name}`);\n  }\n}\n\n// =============================================================================\n// EXPLAIN ERROR\n// =============================================================================\n\nasync function handleExplainError(args: Record<string, unknown>) {\n  const code = args.code as string;\n  const providedErrors = args.errors as\n    | Array<{ message: string; line?: number; column?: number }>\n    | undefined;\n\n  // Parse to find errors if not provided\n  let errors = providedErrors || [];\n  if (errors.length === 0) {\n    try {\n      const format = detectFormat(code);\n      if (format === 'holo') {\n        const result = parseHolo(code);\n        errors = result.errors || [];\n      } else {\n        const parser = new HoloScriptPlusParser();\n        const result = parser.parse(code);\n        errors = result.errors || [];\n      }\n    } catch (e: unknown) {\n      errors = [{ message: e instanceof Error ? e.message : String(e), line: 1 }];\n    }\n  }\n\n  if (errors.length === 0) {\n    return { status: 'ok', message: 'No errors found! Code looks valid.' };\n  }\n\n  const explanations = errors.map((err) => {\n    const explanation: Record<string, unknown> = {\n      original: err.message,\n      line: err.line,\n    };\n\n    // Add context from source\n    const lines = code.split('\\n');\n    if (err.line && err.line > 0 && err.line <= lines.length) {\n      explanation.codeLine = lines[err.line - 1].trim();\n    }\n\n    // Explain common errors\n    const msg = err.message.toLowerCase();\n\n    if (msg.includes('unknown trait') || msg.includes('unrecognized trait')) {\n      const traitMatch = err.message.match(/@?(\\w+)/);\n      const trait = traitMatch?.[1] || '';\n      const suggestion = findSimilarTrait(trait);\n      explanation.explanation = `The trait @${trait} doesn't exist in HoloScript's ${KNOWN_TRAITS.size}-trait system.`;\n      explanation.fix = suggestion\n        ? `Use @${suggestion} instead`\n        : 'Check available traits with list_traits tool';\n      explanation.fixCode = suggestion ? `@${suggestion}` : undefined;\n    } else if (msg.includes('unexpected') || msg.includes('syntax')) {\n      explanation.explanation =\n        \"There's a syntax error - likely a missing brace, bracket, or keyword.\";\n      explanation.fix = 'Check for matching { }, [ ], and correct keyword spelling.';\n    } else if (msg.includes('missing')) {\n      explanation.explanation = 'A required element is missing from the code.';\n      explanation.fix = 'Check the syntax reference for the correct structure.';\n    } else {\n      explanation.explanation = err.message;\n      explanation.fix = 'Review the code around the indicated line.';\n    }\n\n    return explanation;\n  });\n\n  // Optionally enhance with model's natural language explanation\n  const modelExplanation = await queryOllama(\n    `Explain these HoloScript errors concisely (1-2 sentences each):\\n\\nCode:\\n${code}\\n\\nErrors:\\n${errors.map((e) => e.message).join('\\n')}`,\n    'You are a helpful HoloScript expert. Explain errors clearly and suggest fixes. Be concise. Never use [Think] blocks.',\n    { requiresDeepReasoning: false } // Fast edge model routing\n  );\n\n  return {\n    errorCount: errors.length,\n    explanations,\n    modelExplanation: modelExplanation || undefined,\n    tip: 'Use hs_ai_fix_code to automatically fix these issues.',\n  };\n}\n\n// =============================================================================\n// FIX CODE\n// =============================================================================\n\nasync function handleFixCode(args: Record<string, unknown>) {\n  const code = args.code as string;\n  if (typeof code !== 'string' || !code.trim()) {\n    return { error: '\"code\" is required — pass the HoloScript/.hsplus source to fix.' };\n  }\n\n  // Try model first — send broken code, validate fix through parser\n  const modelFixed = await tryModelFix(code);\n  if (modelFixed) {\n    return {\n      originalCode: code,\n      fixedCode: modelFixed,\n      fixes: ['Model-generated fix applied'],\n      fixCount: 1,\n      source: 'model',\n      isValid: true,\n      note: 'Code fixed by Brittney AI model and validated through parser.',\n    };\n  }\n\n  // Fall back to rule-based fixes\n  let fixed = code;\n  const fixes: string[] = [];\n\n  // Fix 1: Balance braces\n  const openBraces = (code.match(/\\{/g) || []).length;\n  const closeBraces = (code.match(/\\}/g) || []).length;\n  if (openBraces > closeBraces) {\n    const diff = openBraces - closeBraces;\n    fixed += '\\n' + '}'.repeat(diff);\n    fixes.push(`Added ${diff} missing closing brace(s)`);\n  }\n\n  // Fix 2: Balance brackets\n  const openBrackets = (code.match(/\\[/g) || []).length;\n  const closeBrackets = (code.match(/\\]/g) || []).length;\n  if (openBrackets > closeBrackets) {\n    const diff = openBrackets - closeBrackets;\n    fixed = fixed.replace(/\\[([^\\]]*?)$/, (match) => match + ']'.repeat(diff));\n    fixes.push(`Added ${diff} missing closing bracket(s)`);\n  }\n\n  // Fix 3: Unknown traits\n  const traitMatches = [...fixed.matchAll(/@(\\w+)/g)];\n  for (const match of traitMatches) {\n    const trait = match[1];\n    if (!KNOWN_TRAITS.has(trait)) {\n      const suggestion = findSimilarTrait(trait);\n      if (suggestion) {\n        fixed = fixed.replace(new RegExp(`@${trait}\\\\b`), `@${suggestion}`);\n        fixes.push(`Replaced unknown @${trait} with @${suggestion}`);\n      }\n    }\n  }\n\n  // Fix 4: Missing composition wrapper for .holo-style code\n  if (fixed.includes('template ') && !fixed.includes('composition ')) {\n    if (fixed.match(/^template\\s+\"/m)) {\n      fixed = `composition \"Scene\" {\\n${fixed\n        .split('\\n')\n        .map((l) => '  ' + l)\n        .join('\\n')}\\n}`;\n      fixes.push('Wrapped in composition block');\n    }\n  }\n\n  // Fix 5: Orb without name\n  fixed = fixed.replace(/orb\\s*\\{/g, () => {\n    fixes.push('Added missing name to orb declaration');\n    return 'orb Unnamed {';\n  });\n\n  // Validate the fixed code\n  let isValid = false;\n  try {\n    const format = detectFormat(fixed);\n    if (format === 'holo') {\n      const result = parseHolo(fixed);\n      isValid = !result.errors?.length;\n    } else {\n      const parser = new HoloScriptPlusParser();\n      const result = parser.parse(fixed);\n      isValid = !result.errors?.length;\n    }\n  } catch {\n    isValid = false;\n  }\n\n  return {\n    originalCode: code,\n    fixedCode: fixed,\n    fixes,\n    fixCount: fixes.length,\n    isValid,\n    note: isValid ? 'Code is now valid!' : 'Some issues remain - manual review recommended.',\n  };\n}\n\n// =============================================================================\n// CODE REVIEW\n// =============================================================================\n\nasync function handleReview(args: Record<string, unknown>) {\n  const code = args.code as string;\n  if (typeof code !== 'string' || !code.trim()) {\n    return { error: '\"code\" is required — pass the HoloScript/.hsplus source to review.' };\n  }\n  const focus = (args.focus as string) || 'all';\n  const issues: Array<{\n    severity: string;\n    category: string;\n    message: string;\n    suggestion?: string;\n  }> = [];\n\n  const lines = code.split('\\n');\n  const traitMatches = [...code.matchAll(/@(\\w+)/g)].map((m) => m[1]);\n  const uniqueTraits = new Set(traitMatches);\n  const objectCount = (code.match(/\\b(orb|object)\\s+/g) || []).length;\n\n  // Performance checks\n  if (focus === 'all' || focus === 'performance') {\n    const physicsCount = traitMatches.filter((t) => t === 'physics').length;\n    if (physicsCount > 20) {\n      issues.push({\n        severity: 'warning',\n        category: 'performance',\n        message: `${physicsCount} physics objects detected - may cause performance issues`,\n        suggestion: 'Consider using @lod for distant objects and reducing active physics bodies',\n      });\n    }\n\n    if (objectCount > 50 && !uniqueTraits.has('lod')) {\n      issues.push({\n        severity: 'info',\n        category: 'performance',\n        message: `${objectCount} objects without LOD - add @lod for distant objects`,\n        suggestion: 'Add @lod(distances: [0, 15, 30]) to objects far from the player',\n      });\n    }\n\n    if (lines.length > 300) {\n      issues.push({\n        severity: 'info',\n        category: 'performance',\n        message: 'Large file - consider splitting into multiple compositions',\n        suggestion: 'Use separate .holo files for different areas/sections',\n      });\n    }\n  }\n\n  // Trait checks\n  if (focus === 'all' || focus === 'traits') {\n    for (const [trait, requires] of Object.entries(TRAIT_REQUIRES)) {\n      if (uniqueTraits.has(trait)) {\n        for (const req of requires) {\n          if (!uniqueTraits.has(req)) {\n            issues.push({\n              severity: 'error',\n              category: 'traits',\n              message: `@${trait} requires @${req} but it's missing`,\n              suggestion: `Add @${req} to objects that have @${trait}`,\n            });\n          }\n        }\n      }\n    }\n\n    for (const [trait, recommends] of Object.entries(TRAIT_RECOMMENDS)) {\n      if (uniqueTraits.has(trait)) {\n        for (const rec of recommends) {\n          if (!uniqueTraits.has(rec)) {\n            issues.push({\n              severity: 'info',\n              category: 'traits',\n              message: `@${trait} works better with @${rec}`,\n              suggestion: `Consider adding @${rec} for better behavior`,\n            });\n          }\n        }\n      }\n    }\n  }\n\n  // Structure checks\n  if (focus === 'all' || focus === 'structure') {\n    if (!code.includes('composition') && !code.includes('orb ')) {\n      issues.push({\n        severity: 'warning',\n        category: 'structure',\n        message: 'No composition or orb declarations found',\n        suggestion: 'Wrap your scene in a composition block',\n      });\n    }\n\n    if (!code.includes('environment') && code.includes('composition')) {\n      issues.push({\n        severity: 'info',\n        category: 'structure',\n        message: 'No environment block - scene will use defaults',\n        suggestion: 'Add environment { skybox: \"...\" ambient_light: 0.4 }',\n      });\n    }\n\n    const templates = (code.match(/template\\s+\"/g) || []).length;\n    if (objectCount > 5 && templates === 0) {\n      issues.push({\n        severity: 'info',\n        category: 'structure',\n        message: `${objectCount} objects but no templates - code duplication likely`,\n        suggestion: 'Extract common patterns into templates for reuse',\n      });\n    }\n  }\n\n  // Multiplayer checks\n  if (focus === 'all' || focus === 'multiplayer') {\n    if (uniqueTraits.has('networked')) {\n      if (!uniqueTraits.has('owned')) {\n        issues.push({\n          severity: 'info',\n          category: 'multiplayer',\n          message: '@networked objects without @owned may have ownership conflicts',\n          suggestion: 'Add @owned for objects that players interact with',\n        });\n      }\n    }\n\n    const hasGrabbable = uniqueTraits.has('grabbable');\n    const hasNetworked = uniqueTraits.has('networked');\n    if (hasGrabbable && !hasNetworked) {\n      issues.push({\n        severity: 'info',\n        category: 'multiplayer',\n        message: 'Grabbable objects are not networked - only visible to local player',\n        suggestion: 'Add @networked if this is a multiplayer scene',\n      });\n    }\n  }\n\n  // Optionally append model's freeform review\n  const modelReview = await queryOllama(\n    `Review this HoloScript code. Focus on: correctness, best practices, missing traits, performance. Be concise (3-5 bullet points).\\n\\n${code}`,\n    'You are a senior HoloScript code reviewer. Give actionable feedback. Never use [Think] blocks.',\n    { requiresDeepReasoning: true } // Need 26B/31B model for multi-component structural review\n  );\n\n  return {\n    issueCount: issues.length,\n    issues,\n    modelReview: modelReview || undefined,\n    stats: {\n      lines: lines.length,\n      objects: objectCount,\n      uniqueTraits: uniqueTraits.size,\n      templates: (code.match(/template\\s+\"/g) || []).length,\n    },\n    grade:\n      issues.filter((i) => i.severity === 'error').length === 0\n        ? issues.filter((i) => i.severity === 'warning').length === 0\n          ? 'A'\n          : 'B'\n        : 'C',\n  };\n}\n\n// =============================================================================\n// SCAFFOLD\n// =============================================================================\n\nasync function handleScaffold(args: Record<string, unknown>) {\n  const description = args.description as string;\n  const type = (args.type as string) || 'game';\n  const features = (args.features as string[]) || [];\n  const desc = description.toLowerCase();\n\n  // Try model first — qwen3.5:4b (sovereign default) for scene generation\n  const modelCode = await tryModelScaffold(description, type, features);\n  if (modelCode) {\n    return {\n      code: modelCode,\n      scaffoldType: type,\n      source: 'model',\n      stats: {\n        lines: modelCode.split('\\n').length,\n        templates: (modelCode.match(/template\\s+\"/g) || []).length,\n        objects: (modelCode.match(/object\\s+\"/g) || []).length,\n        traits: (modelCode.match(/@\\w+/g) || []).length,\n      },\n      features: features.length > 0 ? features : ['basic'],\n      nextSteps: [\n        'Review generated code for correctness',\n        'Replace placeholder geometry with your .glb models',\n        'Test with render_preview tool',\n      ],\n    };\n  }\n\n  // Fall back to rule-based scaffolding\n\n  const lines: string[] = [];\n  const sceneName = extractSceneName(description);\n\n  lines.push(`composition \"${sceneName}\" {`);\n  lines.push('');\n\n  // Environment\n  lines.push('  environment {');\n  if (desc.includes('space') || desc.includes('galaxy')) {\n    lines.push('    skybox: \"nebula\"');\n    lines.push('    ambient_light: 0.1');\n    lines.push('    gravity: [0, 0, 0]');\n  } else if (desc.includes('forest') || desc.includes('nature')) {\n    lines.push('    skybox: \"forest\"');\n    lines.push('    ambient_light: 0.4');\n    lines.push('    fog: { enabled: true, density: 0.01 }');\n  } else if (desc.includes('night') || desc.includes('dark')) {\n    lines.push('    skybox: \"night\"');\n    lines.push('    ambient_light: 0.15');\n  } else {\n    lines.push('    skybox: \"gradient\"');\n    lines.push('    ambient_light: 0.4');\n  }\n  lines.push('  }');\n  lines.push('');\n\n  // Templates based on project type\n  if (type === 'game' || desc.includes('game')) {\n    lines.push('  // Player template');\n    lines.push('  template \"Player\" {');\n    lines.push('    @character(speed: 5, jump_force: 6)');\n    lines.push('    @collidable');\n    if (features.includes('multiplayer')) {\n      lines.push('    @networked(sync_rate: \"30hz\")');\n      lines.push('    @owned');\n    }\n    lines.push('    geometry: \"model/player.glb\"');\n    lines.push('    state {');\n    lines.push('      health: 100');\n    lines.push('      score: 0');\n    lines.push('    }');\n    lines.push('  }');\n    lines.push('');\n  }\n\n  if (desc.includes('enemy') || desc.includes('combat')) {\n    lines.push('  // Enemy template');\n    lines.push('  template \"Enemy\" {');\n    lines.push('    @collidable');\n    lines.push('    @destructible(health: 50)');\n    lines.push('    @patrol');\n    if (features.includes('ai')) {\n      lines.push('    @behavior_tree');\n      lines.push('    @perception');\n    }\n    lines.push('    geometry: \"model/enemy.glb\"');\n    lines.push('    state {');\n    lines.push('      health: 50');\n    lines.push('      damage: 10');\n    lines.push('    }');\n    lines.push('  }');\n    lines.push('');\n  }\n\n  if (desc.includes('item') || desc.includes('collect') || desc.includes('pickup')) {\n    lines.push('  // Collectible template');\n    lines.push('  template \"Collectible\" {');\n    lines.push('    @grabbable');\n    lines.push('    @collidable');\n    lines.push('    @glowing(intensity: 0.5, pulse: true)');\n    lines.push('    @animated');\n    if (features.includes('audio')) {\n      lines.push('    @spatial_audio(src: \"pickup.mp3\")');\n    }\n    lines.push('    geometry: \"sphere\"');\n    lines.push('    state {');\n    lines.push('      value: 10');\n    lines.push('      collected: false');\n    lines.push('    }');\n    lines.push('  }');\n    lines.push('');\n  }\n\n  if (type === 'showcase' || type === 'art') {\n    lines.push('  // Display item template');\n    lines.push('  template \"DisplayItem\" {');\n    lines.push('    @grabbable');\n    lines.push('    @scalable(min_scale: 0.5, max_scale: 3)');\n    lines.push('    @rotatable(auto_rotate: true, speed: 0.3)');\n    lines.push('    @glowing(intensity: 0.3)');\n    lines.push('    @billboard(axis: \"y\")');\n    lines.push('    geometry: \"sphere\"');\n    lines.push('  }');\n    lines.push('');\n  }\n\n  if (type === 'social' || features.includes('multiplayer')) {\n    lines.push('  // Social avatar template');\n    lines.push('  template \"Avatar\" {');\n    lines.push('    @networked(sync_rate: \"30hz\")');\n    lines.push('    @owned');\n    lines.push('    @hand_tracking');\n    lines.push('    @spatial_audio');\n    lines.push('    geometry: \"model/avatar.glb\"');\n    lines.push('  }');\n    lines.push('');\n  }\n\n  // Objects\n  lines.push('  // Scene objects');\n  if (type === 'game') {\n    lines.push('  object \"MainPlayer\" using \"Player\" {');\n    lines.push('    position: [0, 0, 0]');\n    lines.push('  }');\n    lines.push('');\n  }\n\n  // Ground/floor\n  lines.push('  object \"Ground\" @collidable {');\n  lines.push('    geometry: \"plane\"');\n  lines.push('    scale: [50, 1, 50]');\n  lines.push('    position: [0, 0, 0]');\n  lines.push('    color: \"#333333\"');\n  lines.push('  }');\n  lines.push('');\n\n  // UI\n  if (features.includes('ui')) {\n    lines.push('  // HUD');\n    lines.push('  object \"HUD\" @ui_panel(width: 512, height: 128, text: \"Score: 0\") @billboard {');\n    lines.push('    position: [0, 3, -5]');\n    lines.push('  }');\n    lines.push('');\n  }\n\n  // Audio\n  if (features.includes('audio')) {\n    lines.push('  // Ambient audio');\n    lines.push('  object \"Ambience\" @ambient(volume: 0.3) {');\n    lines.push('    audio: { src: \"ambience.mp3\", loop: true }');\n    lines.push('  }');\n    lines.push('');\n  }\n\n  // Logic block\n  lines.push('  logic {');\n  lines.push('    on_scene_start() {');\n  if (type === 'game') {\n    lines.push('      // Initialize game state');\n    lines.push('      console.log(\"Game started!\")');\n  } else {\n    lines.push('      // Scene initialization');\n    lines.push('      console.log(\"Scene loaded!\")');\n  }\n  lines.push('    }');\n\n  if (desc.includes('collect')) {\n    lines.push('');\n    lines.push('    on_interact(\"Collectible\") {');\n    lines.push('      // Handle item collection');\n    lines.push('      Player.score += this.value');\n    lines.push('      this.collected = true');\n    lines.push('      this.destroy()');\n    lines.push('    }');\n  }\n\n  lines.push('  }');\n  lines.push('}');\n\n  const code = lines.join('\\n');\n\n  // Validate scaffolded code through the parser before returning\n  try {\n    const parseResult = parseHolo(code);\n    if (parseResult.errors && parseResult.errors.length > 0) {\n      return {\n        code,\n        isValid: false,\n        scaffoldType: type,\n        errors: parseResult.errors.map((e: { message: string; line?: number }) => ({\n          message: e.message,\n          line: e.line,\n        })),\n        stats: {\n          lines: lines.length,\n          templates: (code.match(/template\\s+\"/g) || []).length,\n          objects: (code.match(/object\\s+\"/g) || []).length,\n          traits: (code.match(/@\\w+/g) || []).length,\n        },\n        features: features.length > 0 ? features : ['basic'],\n        nextSteps: ['Fix the validation errors above', 'Then test with render_preview tool'],\n      };\n    }\n  } catch {\n    // Parser threw — treat as invalid but still return the code for debugging\n  }\n\n  return {\n    code,\n    isValid: true,\n    scaffoldType: type,\n    stats: {\n      lines: lines.length,\n      templates: (code.match(/template\\s+\"/g) || []).length,\n      objects: (code.match(/object\\s+\"/g) || []).length,\n      traits: (code.match(/@\\w+/g) || []).length,\n    },\n    features: features.length > 0 ? features : ['basic'],\n    nextSteps: [\n      'Replace placeholder geometry with your .glb models',\n      'Customize template state and actions',\n      'Add specific game logic in the logic block',\n      'Test with render_preview tool',\n    ],\n  };\n}\n\n// =============================================================================\n// MODEL-BACKED HELPERS\n// =============================================================================\n\n/**\n * Try to generate a scaffold using the Ollama model.\n * Returns validated HoloScript code or null if model is unavailable/output is invalid.\n */\nasync function tryModelScaffold(\n  description: string,\n  type: string,\n  features: string[]\n): Promise<string | null> {\n  const featureStr = features.length > 0 ? `\\nFeatures to include: ${features.join(', ')}` : '';\n  const prompt = `Generate a complete HoloScript .holo scene for: ${description}\\nProject type: ${type}${featureStr}\\n\\nOutput ONLY the HoloScript code. Include composition wrapper, environment block, templates, objects with positions, and a logic block.`;\n\n  const raw = await queryOllama(prompt, undefined, { requiresDeepReasoning: true }); // Needs cloud reasoning for full codebase scaffolding\n  if (!raw) {\n    console.warn(\n      `[brittney-lite] AI model returned empty response for: \"${description.slice(0, 60)}\". Check Ollama is running and model is loaded.`\n    );\n    return null;\n  }\n\n  const code = stripCodeFences(raw);\n\n  // Validate through parser\n  try {\n    const format = detectFormat(code);\n    if (format === 'holo') {\n      const result = parseHolo(code);\n      if (result.errors?.length > 0) {\n        console.warn(\n          `[brittney-lite] Generated .holo has ${result.errors.length} parse errors: ${result.errors\n            .slice(0, 2)\n            .map((e: any) => e.message || e)\n            .join(', ')}. Returning null — caller should retry or adjust prompt.`\n        );\n        return null;\n      }\n    } else {\n      const parser = new HoloScriptPlusParser();\n      const result = parser.parse(code);\n      if (result.errors?.length > 0) {\n        console.warn(\n          `[brittney-lite] Generated .hsplus has ${result.errors.length} parse errors: ${result.errors\n            .slice(0, 2)\n            .map((e: any) => e.message || e)\n            .join(', ')}. Returning null.`\n        );\n        return null;\n      }\n    }\n  } catch (e) {\n    console.warn(\n      `[brittney-lite] Parser crashed on generated code: ${(e as Error)?.message ?? e}. The AI model may have produced invalid syntax.`\n    );\n    return null;\n  }\n\n  // Fix any hallucinated traits\n  let fixed = code;\n  const traitMatches = [...code.matchAll(/@(\\w+)/g)];\n  for (const match of traitMatches) {\n    const trait = match[1];\n    if (!KNOWN_TRAITS.has(trait)) {\n      const suggestion = findSimilarTrait(trait);\n      if (suggestion) {\n        fixed = fixed.replace(new RegExp(`@${trait}\\\\b`), `@${suggestion}`);\n      }\n    }\n  }\n\n  return fixed;\n}\n\n/**\n * Try to fix code using the Ollama model.\n * Returns validated fixed code or null if model is unavailable/output is invalid.\n */\nasync function tryModelFix(brokenCode: string): Promise<string | null> {\n  const prompt = `Fix the following broken HoloScript code. Output ONLY the corrected code, no explanations:\\n\\n${brokenCode}`;\n\n  const raw = await queryOllama(prompt, undefined, { requiresDeepReasoning: true }); // Fixing complex code requires cloud MoE\n  if (!raw) return null;\n\n  const code = stripCodeFences(raw);\n\n  // Validate the fix through parser\n  try {\n    const format = detectFormat(code);\n    if (format === 'holo') {\n      const result = parseHolo(code);\n      if (result.errors?.length > 0) return null;\n    } else {\n      const parser = new HoloScriptPlusParser();\n      const result = parser.parse(code);\n      if (result.errors?.length > 0) return null;\n    }\n  } catch {\n    return null;\n  }\n\n  return code;\n}\n\n// =============================================================================\n// HELPERS\n// =============================================================================\n\nfunction detectFormat(code: string): 'hs' | 'hsplus' | 'holo' {\n  if (code.includes('composition') && code.includes('{')) return 'holo';\n  if (code.includes('@') || code.includes('state {')) return 'hsplus';\n  return 'hs';\n}\n\nfunction findSimilarTrait(input: string): string | null {\n  const normalized = input.toLowerCase();\n\n  // Exact match\n  if (KNOWN_TRAITS.has(normalized)) return normalized;\n\n  // Prefix match\n  for (const trait of KNOWN_TRAITS) {\n    if (trait.startsWith(normalized) || normalized.startsWith(trait)) return trait;\n  }\n\n  // Substring match\n  for (const trait of KNOWN_TRAITS) {\n    if (trait.includes(normalized) || normalized.includes(trait)) return trait;\n  }\n\n  // NOTE: First-3-chars matching removed — too loose, causes silent wrong replacements\n  // with 1800+ traits (e.g. \"gra\" matching \"grabbable\" when \"gravity\" was intended)\n\n  return null;\n}\n\nfunction extractSceneName(description: string): string {\n  const words = description.split(/\\s+/).slice(0, 4);\n  return words\n    .map((w) => w.charAt(0).toUpperCase() + w.slice(1).toLowerCase())\n    .join(' ')\n    .replace(/[^a-zA-Z0-9 ]/g, '');\n}\n","/**\n * MCP Self-Improve Tools for HoloScript\n *\n * Provides AI agents with tools for autonomous codebase improvement:\n * - holo_self_diagnose: Analyze codebase for improvement opportunities\n * - holo_validate_quality: Calculate composite quality score\n *\n * These tools chain with existing absorb/query/GraphRAG tools to form\n * the 6-step self-improvement pipeline:\n *   ABSORB → DIAGNOSE → GENERATE → VALIDATE → COMMIT → LEARN\n *\n * The AI agent handles GENERATE and COMMIT steps; these tools provide\n * the intelligence layer (what to improve, whether changes are valid).\n */\n\nimport { Tool } from '@modelcontextprotocol/sdk/types.js';\nimport { exec } from 'child_process';\nimport { promisify } from 'util';\nimport * as fs from 'fs';\nimport * as path from 'path';\n\n/** Error shape from child_process.exec — includes stdout/stderr from the failed command. */\ninterface ExecError extends Error {\n  stdout?: string;\n  stderr?: string;\n}\n\nfunction errMsg(err: unknown): string {\n  return err instanceof Error ? err.message : String(err);\n}\n\nconst execAsync = promisify(exec);\n\n// =============================================================================\n// TOOL DEFINITIONS\n// =============================================================================\n\nexport const selfImproveTools: Tool[] = [\n  {\n    name: 'holo_write_file',\n    description:\n      'Write content to a file. Creates parent directories if needed. ' +\n      'Use for generating tests, documentation, or applying fixes. ' +\n      'Path must be within the project root directory.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        filePath: {\n          type: 'string',\n          description: 'Absolute path to the file to write',\n        },\n        content: {\n          type: 'string',\n          description: 'The full content to write to the file',\n        },\n        createOnly: {\n          type: 'boolean',\n          description: 'If true, fail if file already exists. Defaults to false.',\n        },\n      },\n      required: ['filePath', 'content'],\n    },\n  },\n  {\n    name: 'holo_edit_file',\n    description:\n      'Apply a search-and-replace edit to an existing file. ' +\n      'The old_string must match exactly (including whitespace). ' +\n      'Use for targeted code fixes without rewriting entire files.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        filePath: {\n          type: 'string',\n          description: 'Absolute path to the file to edit',\n        },\n        oldString: {\n          type: 'string',\n          description: 'The exact string to search for in the file',\n        },\n        newString: {\n          type: 'string',\n          description: 'The replacement string',\n        },\n      },\n      required: ['filePath', 'oldString', 'newString'],\n    },\n  },\n  {\n    name: 'holo_read_file',\n    description: 'Read the contents of a file. Use to understand code before making edits.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        filePath: {\n          type: 'string',\n          description: 'Absolute path to the file to read',\n        },\n        startLine: {\n          type: 'number',\n          description: 'Start reading from this line (1-indexed). Defaults to 1.',\n        },\n        endLine: {\n          type: 'number',\n          description: 'Stop reading at this line. Defaults to end of file.',\n        },\n      },\n      required: ['filePath'],\n    },\n  },\n  {\n    name: 'holo_git_commit',\n    description:\n      'Stage changed files and create a git commit. ' +\n      'Only commits files within the project root.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        rootDir: {\n          type: 'string',\n          description: 'Root directory of the git repository',\n        },\n        files: {\n          type: 'array',\n          items: { type: 'string' },\n          description:\n            'File paths to stage (relative to rootDir). If empty, stages all changed files.',\n        },\n        message: {\n          type: 'string',\n          description: 'Commit message',\n        },\n      },\n      required: ['rootDir', 'message'],\n    },\n  },\n  {\n    name: 'holo_run_tests_targeted',\n    description:\n      'Run vitest on specific test files instead of the entire suite. ' +\n      'Much faster than full test run for validating individual changes.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        rootDir: {\n          type: 'string',\n          description: 'Root directory of the project',\n        },\n        testFiles: {\n          type: 'array',\n          items: { type: 'string' },\n          description: 'Specific test file paths to run (relative to rootDir)',\n        },\n        testPattern: {\n          type: 'string',\n          description: 'Test name pattern to match (vitest -t flag)',\n        },\n      },\n      required: ['rootDir'],\n    },\n  },\n  {\n    name: 'holo_list_type_errors',\n    description:\n      'Run tsc --noEmit and return the actual TypeScript errors grouped by file. ' +\n      'Use this to find and fix specific type errors. Much more actionable than holo_validate_quality ' +\n      'for improving the type-check score.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        rootDir: {\n          type: 'string',\n          description: 'Root directory of the project',\n        },\n        maxErrors: {\n          type: 'number',\n          description: 'Maximum number of errors to return. Defaults to 20.',\n        },\n        file: {\n          type: 'string',\n          description: 'Filter errors to a specific file path (substring match)',\n        },\n      },\n      required: ['rootDir'],\n    },\n  },\n  {\n    name: 'holo_batch_type_fix',\n    description:\n      'Group TypeScript errors by error code (TS7006, TS2339, etc.) and return ' +\n      'batch fix suggestions. Much more efficient than fixing one error at a time. ' +\n      'Returns errors grouped by code with fix patterns.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        rootDir: {\n          type: 'string',\n          description: 'Root directory of the project',\n        },\n        errorCode: {\n          type: 'string',\n          description:\n            'Filter to a specific error code (e.g. \"TS7006\"). If omitted, groups all errors.',\n        },\n        maxFiles: {\n          type: 'number',\n          description: 'Maximum files to return. Defaults to 5.',\n        },\n      },\n      required: ['rootDir'],\n    },\n  },\n  {\n    name: 'holo_verify_before_commit',\n    description:\n      'Run tsc --noEmit on specific changed files to verify they compile before committing. ' +\n      'Much faster than full tsc. Use after edits and before holo_git_commit.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        rootDir: {\n          type: 'string',\n          description: 'Root directory of the project',\n        },\n        files: {\n          type: 'array',\n          items: { type: 'string' },\n          description: 'File paths to check (relative or absolute)',\n        },\n      },\n      required: ['rootDir', 'files'],\n    },\n  },\n  {\n    name: 'holo_run_related_tests',\n    description:\n      'Run only tests related to specific source files using vitest --related. ' +\n      'Much faster than running the full test suite. Use after editing source files.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        rootDir: {\n          type: 'string',\n          description: 'Root directory of the project',\n        },\n        sourceFiles: {\n          type: 'array',\n          items: { type: 'string' },\n          description: 'Source files that were changed (vitest finds their related tests)',\n        },\n      },\n      required: ['rootDir', 'sourceFiles'],\n    },\n  },\n  {\n    name: 'holo_quality_trend',\n    description:\n      'Analyze quality score history to detect trends, plateaus, and regressions. ' +\n      \"Returns trend analysis and strategy recommendations based on what has and hasn't worked.\",\n    inputSchema: {\n      type: 'object',\n      properties: {\n        rootDir: {\n          type: 'string',\n          description: 'Root directory of the project (for finding .holoscript/)',\n        },\n        lastN: {\n          type: 'number',\n          description: 'Number of recent cycles to analyze. Defaults to 10.',\n        },\n      },\n      required: ['rootDir'],\n    },\n  },\n  {\n    name: 'holo_self_diagnose',\n    description:\n      'Diagnose a codebase for improvement opportunities using Graph RAG. ' +\n      'Runs pre-built analytical queries to identify: untested code with high impact, ' +\n      'missing documentation on public APIs, high-complexity modules, and structural issues. ' +\n      'Returns a prioritized list of improvement candidates. Requires a prior holo_absorb_repo call.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        rootDir: {\n          type: 'string',\n          description:\n            'Root directory of the project (for test discovery). Defaults to the last absorbed directory.',\n        },\n        focus: {\n          type: 'string',\n          enum: ['coverage', 'docs', 'complexity', 'all'],\n          description:\n            'Focus area for diagnosis. \"coverage\" = untested code, \"docs\" = missing docs, \"complexity\" = high-complexity modules, \"all\" = everything. Defaults to \"all\".',\n        },\n        maxResults: {\n          type: 'number',\n          description: 'Maximum improvement candidates to return. Defaults to 10.',\n        },\n      },\n    },\n  },\n  {\n    name: 'holo_validate_quality',\n    description:\n      'Calculate a composite quality score for the codebase. Runs type checking (tsc), ' +\n      'test suite (vitest), and lint checks. Returns individual scores and a weighted composite. ' +\n      'Use after making changes to verify improvement, or before changes to establish a baseline.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        rootDir: {\n          type: 'string',\n          description: 'Root directory of the project to validate',\n        },\n        skipTests: {\n          type: 'boolean',\n          description: 'Skip running tests (faster, but no test score). Defaults to false.',\n        },\n        skipLint: {\n          type: 'boolean',\n          description: 'Skip lint check. Defaults to false.',\n        },\n      },\n      required: ['rootDir'],\n    },\n  },\n];\n\n// =============================================================================\n// HANDLER\n// =============================================================================\n\nexport async function handleSelfImproveTool(\n  name: string,\n  args: Record<string, unknown>\n): Promise<unknown | null> {\n  switch (name) {\n    case 'holo_write_file':\n      return handleWriteFile(args);\n    case 'holo_edit_file':\n      return handleEditFile(args);\n    case 'holo_read_file':\n      return handleReadFile(args);\n    case 'holo_git_commit':\n      return handleGitCommit(args);\n    case 'holo_run_tests_targeted':\n      return handleRunTestsTargeted(args);\n    case 'holo_list_type_errors':\n      return handleListTypeErrors(args);\n    case 'holo_batch_type_fix':\n      return handleBatchTypeFix(args);\n    case 'holo_verify_before_commit':\n      return handleVerifyBeforeCommit(args);\n    case 'holo_run_related_tests':\n      return handleRunRelatedTests(args);\n    case 'holo_quality_trend':\n      return handleQualityTrend(args);\n    case 'holo_self_diagnose':\n      return handleDiagnose(args);\n    case 'holo_validate_quality':\n      return handleValidateQuality(args);\n    default:\n      return null;\n  }\n}\n\n// ── Write/Edit Handlers ──────────────────────────────────────────────────────\n\nasync function handleWriteFile(args: Record<string, unknown>): Promise<unknown> {\n  const filePath = args.filePath as string;\n  const content = args.content as string;\n  const createOnly = (args.createOnly as boolean) ?? false;\n\n  if (!filePath || !path.isAbsolute(filePath)) {\n    return { error: 'filePath must be an absolute path' };\n  }\n\n  if (createOnly && fs.existsSync(filePath)) {\n    return { error: `File already exists: ${filePath}` };\n  }\n\n  try {\n    const dir = path.dirname(filePath);\n    if (!fs.existsSync(dir)) {\n      fs.mkdirSync(dir, { recursive: true });\n    }\n    fs.writeFileSync(filePath, content, 'utf-8');\n    return {\n      success: true,\n      filePath,\n      bytesWritten: Buffer.byteLength(content, 'utf-8'),\n      linesWritten: content.split('\\n').length,\n    };\n  } catch (err: unknown) {\n    return { error: `Write failed: ${errMsg(err)}` };\n  }\n}\n\nasync function handleEditFile(args: Record<string, unknown>): Promise<unknown> {\n  const filePath = args.filePath as string;\n  const oldString = args.oldString as string;\n  const newString = args.newString as string;\n\n  if (!filePath || !path.isAbsolute(filePath)) {\n    return { error: 'filePath must be an absolute path' };\n  }\n\n  if (!fs.existsSync(filePath)) {\n    return { error: `File not found: ${filePath}` };\n  }\n\n  try {\n    const content = fs.readFileSync(filePath, 'utf-8');\n    const occurrences = content.split(oldString).length - 1;\n\n    if (occurrences === 0) {\n      return { error: 'oldString not found in file', filePath };\n    }\n\n    if (occurrences > 1) {\n      return {\n        error: `oldString found ${occurrences} times — must be unique. Provide more context.`,\n        filePath,\n      };\n    }\n\n    const updated = content.replace(oldString, newString);\n    fs.writeFileSync(filePath, updated, 'utf-8');\n    return {\n      success: true,\n      filePath,\n      replacements: 1,\n    };\n  } catch (err: unknown) {\n    return { error: `Edit failed: ${errMsg(err)}` };\n  }\n}\n\nasync function handleReadFile(args: Record<string, unknown>): Promise<unknown> {\n  const filePath = args.filePath as string;\n  const startLine = (args.startLine as number) ?? 1;\n  const endLine = args.endLine as number | undefined;\n\n  if (!filePath || !path.isAbsolute(filePath)) {\n    return { error: 'filePath must be an absolute path' };\n  }\n\n  if (!fs.existsSync(filePath)) {\n    return { error: `File not found: ${filePath}` };\n  }\n\n  try {\n    const content = fs.readFileSync(filePath, 'utf-8');\n    const lines = content.split('\\n');\n    const start = Math.max(0, startLine - 1);\n    const end = endLine ? Math.min(lines.length, endLine) : Math.min(lines.length, start + 200);\n    const slice = lines.slice(start, end);\n\n    return {\n      filePath,\n      startLine: start + 1,\n      endLine: end,\n      totalLines: lines.length,\n      content: slice.map((line, i) => `${start + i + 1}: ${line}`).join('\\n'),\n    };\n  } catch (err: unknown) {\n    return { error: `Read failed: ${errMsg(err)}` };\n  }\n}\n\nasync function handleGitCommit(args: Record<string, unknown>): Promise<unknown> {\n  const rootDir = args.rootDir as string;\n  const files = (args.files as string[]) ?? [];\n  const message = args.message as string;\n\n  if (!message) {\n    return { error: 'Commit message is required' };\n  }\n\n  // Multi-agent safety: never stage all files (git add -A). Each agent must\n  // explicitly declare which files it wants to commit. Without this guard,\n  // a daemon commit can sweep in unrelated dirty files from other agents.\n  if (files.length === 0) {\n    return {\n      error:\n        'files array is required — refusing to stage all (git add -A is disabled for multi-agent safety)',\n    };\n  }\n\n  try {\n    // Stage only the explicitly specified files\n    for (const f of files) {\n      await execAsync(`git add \"${f}\"`, { cwd: rootDir, timeout: 30_000 });\n    }\n\n    // Commit\n    const commitMsg = message.replace(/\"/g, '\\\\\"');\n    const { stdout } = await execAsync(\n      `git commit --no-verify -m \"${commitMsg}\" --author=\"HoloScript Daemon <daemon@holoscript.dev>\"`,\n      { cwd: rootDir, timeout: 30_000 }\n    );\n\n    return {\n      success: true,\n      message,\n      output: stdout.trim(),\n    };\n  } catch (err: unknown) {\n    return { error: `Git commit failed: ${errMsg(err)}` };\n  }\n}\n\nasync function handleRunTestsTargeted(args: Record<string, unknown>): Promise<unknown> {\n  const rootDir = args.rootDir as string;\n  const testFiles = (args.testFiles as string[]) ?? [];\n  const testPattern = args.testPattern as string | undefined;\n\n  try {\n    let cmd = 'npx vitest run --reporter=json';\n    if (testFiles.length > 0) {\n      cmd += ' ' + testFiles.map((f) => `\"${f}\"`).join(' ');\n    }\n    if (testPattern) {\n      cmd += ` -t \"${testPattern}\"`;\n    }\n\n    const { stdout, stderr } = await execAsync(cmd + ' 2>&1', {\n      cwd: rootDir,\n      timeout: 120_000,\n      maxBuffer: 10 * 1024 * 1024,\n    });\n\n    const output = stdout + stderr;\n    try {\n      const jsonMatch = output.match(/\\{[\\s\\S]*\"numTotalTests\"[\\s\\S]*\\}/);\n      if (jsonMatch) {\n        const result = JSON.parse(jsonMatch[0]);\n        return {\n          success: result.success ?? false,\n          numPassed: result.numPassedTests ?? 0,\n          numFailed: result.numFailedTests ?? 0,\n          numTotal: result.numTotalTests ?? 0,\n          testFiles,\n          duration: result.startTime ? Date.now() - result.startTime : undefined,\n        };\n      }\n    } catch {\n      /* JSON parse failed */\n    }\n\n    return {\n      success: !output.includes('FAIL'),\n      rawOutput: output.slice(0, 5000),\n    };\n  } catch (err: unknown) {\n    return {\n      success: false,\n      error: errMsg(err).slice(0, 2000),\n    };\n  }\n}\n\n// ── Type Error Listing ───────────────────────────────────────────────────────\n\nasync function handleListTypeErrors(args: Record<string, unknown>): Promise<unknown> {\n  const rootDir = args.rootDir as string;\n  const maxErrors = (args.maxErrors as number) ?? 20;\n  const fileFilter = args.file as string | undefined;\n\n  try {\n    let output = '';\n    try {\n      const result = await execAsync('npx tsc --noEmit --pretty false 2>&1', {\n        cwd: rootDir,\n        timeout: 180_000,\n        maxBuffer: 50 * 1024 * 1024,\n      });\n      output = result.stdout + result.stderr;\n    } catch (e: unknown) {\n      const execErr = e as ExecError;\n      output = (execErr.stdout ?? '') + (execErr.stderr ?? '');\n    }\n\n    const errorLines = output.split('\\n').filter((l: string) => l.includes('error TS'));\n    const totalErrors = errorLines.length;\n\n    // Filter by file if requested\n    const filtered = fileFilter\n      ? errorLines.filter((l: string) => l.includes(fileFilter))\n      : errorLines;\n\n    // Group by file\n    const byFile: Record<string, string[]> = {};\n    for (const line of filtered) {\n      const match = line.match(/^([^(]+)\\(/);\n      if (match) {\n        const file = match[1].trim();\n        if (!byFile[file]) byFile[file] = [];\n        byFile[file].push(line);\n      }\n    }\n\n    // Sort files by error count (most errors first), take top files\n    const sortedFiles = Object.entries(byFile)\n      .sort(([, a], [, b]) => b.length - a.length)\n      .slice(0, 10);\n\n    // Collect errors up to maxErrors\n    const errors: Array<{ file: string; line: number; code: string; message: string }> = [];\n    for (const [_file, lines] of sortedFiles) {\n      for (const errLine of lines) {\n        if (errors.length >= maxErrors) break;\n        const match = errLine.match(/^([^(]+)\\((\\d+),\\d+\\): error (TS\\d+): (.+)/);\n        if (match) {\n          errors.push({\n            file: match[1].trim(),\n            line: parseInt(match[2], 10),\n            code: match[3],\n            message: match[4],\n          });\n        }\n      }\n    }\n\n    return {\n      totalErrors,\n      filteredErrors: filtered.length,\n      topFiles: sortedFiles.map(([file, lines]) => ({\n        file,\n        errorCount: lines.length,\n      })),\n      errors,\n      hint:\n        totalErrors > maxErrors\n          ? `Showing ${errors.length} of ${totalErrors} errors. Fix the top files first.`\n          : undefined,\n    };\n  } catch (err: unknown) {\n    return { error: `Failed to run tsc: ${errMsg(err)}` };\n  }\n}\n\n// ── Batch Type Fix (Level 2) ────────────────────────────────────────────────\n\nasync function handleBatchTypeFix(args: Record<string, unknown>): Promise<unknown> {\n  const rootDir = args.rootDir as string;\n  const errorCode = args.errorCode as string | undefined;\n  const maxFiles = (args.maxFiles as number) ?? 5;\n\n  try {\n    let output = '';\n    try {\n      const result = await execAsync('npx tsc --noEmit --pretty false 2>&1', {\n        cwd: rootDir,\n        timeout: 180_000,\n        maxBuffer: 50 * 1024 * 1024,\n      });\n      output = result.stdout + result.stderr;\n    } catch (e: unknown) {\n      const execErr = e as ExecError;\n      output = (execErr.stdout ?? '') + (execErr.stderr ?? '');\n    }\n\n    const errorLines = output.split('\\n').filter((l: string) => l.includes('error TS'));\n\n    // Group by error code\n    const byCode: Record<string, Array<{ file: string; line: number; message: string }>> = {};\n    for (const line of errorLines) {\n      const match = line.match(/^([^(]+)\\((\\d+),\\d+\\): error (TS\\d+): (.+)/);\n      if (match) {\n        const code = match[3];\n        if (errorCode && code !== errorCode) continue;\n        if (!byCode[code]) byCode[code] = [];\n        byCode[code].push({\n          file: match[1].trim(),\n          line: parseInt(match[2], 10),\n          message: match[4],\n        });\n      }\n    }\n\n    // Sort codes by frequency\n    const sortedCodes = Object.entries(byCode).sort(([, a], [, b]) => b.length - a.length);\n\n    // For each code, group by file and provide fix patterns\n    const fixPatterns: Record<string, string> = {\n      TS7006: 'Add explicit type annotations to parameters (e.g., `param: any` or specific type)',\n      TS2339:\n        'Property does not exist — add to interface, use type assertion, or check optional chaining',\n      TS2322: 'Type mismatch — adjust the assignment or cast to the expected type',\n      TS2304: 'Cannot find name — add missing import statement',\n      TS2345: 'Argument type mismatch — cast argument or update function signature',\n      TS2554: 'Wrong number of arguments — add/remove arguments or update function signature',\n      TS2532:\n        'Object possibly undefined — add null check or use optional chaining (?.) / non-null assertion (!)',\n      TS2307: 'Cannot find module — install the package or fix the import path',\n      TS18046: 'Variable is of type unknown — add type guard or assertion',\n      TS18047: 'Variable possibly null — add null check',\n    };\n\n    const groups = sortedCodes.slice(0, 10).map(([code, errors]) => {\n      // Group this code's errors by file\n      const fileMap: Record<string, typeof errors> = {};\n      for (const err of errors) {\n        if (!fileMap[err.file]) fileMap[err.file] = [];\n        fileMap[err.file].push(err);\n      }\n      const topFiles = Object.entries(fileMap)\n        .sort(([, a], [, b]) => b.length - a.length)\n        .slice(0, maxFiles);\n\n      return {\n        code,\n        count: errors.length,\n        fixPattern: fixPatterns[code] ?? 'Review each error and apply appropriate fix',\n        topFiles: topFiles.map(([file, errs]) => ({\n          file,\n          errorCount: errs.length,\n          errors: errs.slice(0, 5),\n        })),\n      };\n    });\n\n    return {\n      totalErrors: errorLines.length,\n      errorCodes: sortedCodes.length,\n      groups,\n      strategy:\n        `Fix ${sortedCodes[0]?.[0]} first (${sortedCodes[0]?.[1]?.length} instances). ` +\n        `Then ${sortedCodes[1]?.[0]} (${sortedCodes[1]?.[1]?.length}). ` +\n        `Target the file with the most errors in each group for maximum impact.`,\n    };\n  } catch (err: unknown) {\n    return { error: `Failed to run tsc: ${errMsg(err)}` };\n  }\n}\n\n// ── Pre-Commit Verification (Level 4) ──────────────────────────────────────\n\nasync function handleVerifyBeforeCommit(args: Record<string, unknown>): Promise<unknown> {\n  const rootDir = args.rootDir as string;\n  const files = (args.files as string[]) ?? [];\n\n  if (files.length === 0) {\n    return { error: 'No files specified for verification' };\n  }\n\n  try {\n    // Get current error count for these files BEFORE and check if we made them worse\n    let output = '';\n    try {\n      const result = await execAsync('npx tsc --noEmit --pretty false 2>&1', {\n        cwd: rootDir,\n        timeout: 180_000,\n        maxBuffer: 50 * 1024 * 1024,\n      });\n      output = result.stdout + result.stderr;\n    } catch (e: unknown) {\n      const execErr = e as ExecError;\n      output = (execErr.stdout ?? '') + (execErr.stderr ?? '');\n    }\n\n    const allErrors = output.split('\\n').filter((l: string) => l.includes('error TS'));\n    const fileErrors: Record<string, string[]> = {};\n    let totalRelevant = 0;\n\n    for (const file of files) {\n      const normalizedFile = file.replace(/\\\\/g, '/');\n      const matching = allErrors.filter((l: string) => {\n        const normalized = l.replace(/\\\\/g, '/');\n        return normalized.includes(normalizedFile) || normalized.includes(path.basename(file));\n      });\n      fileErrors[file] = matching;\n      totalRelevant += matching.length;\n    }\n\n    return {\n      safe: totalRelevant === 0,\n      totalErrors: allErrors.length,\n      relevantErrors: totalRelevant,\n      files: Object.entries(fileErrors).map(([file, errors]) => ({\n        file,\n        errors: errors.length,\n        details: errors.slice(0, 5),\n      })),\n      recommendation:\n        totalRelevant === 0\n          ? 'Safe to commit — no type errors in changed files.'\n          : `${totalRelevant} type errors in changed files. Fix before committing.`,\n    };\n  } catch (err: unknown) {\n    return { error: `Verification failed: ${errMsg(err)}` };\n  }\n}\n\n// ── Smart Test Running (Level 5) ──────────────────────────────────────────\n\nasync function handleRunRelatedTests(args: Record<string, unknown>): Promise<unknown> {\n  const rootDir = args.rootDir as string;\n  const sourceFiles = (args.sourceFiles as string[]) ?? [];\n\n  if (sourceFiles.length === 0) {\n    return { error: 'No source files specified' };\n  }\n\n  try {\n    const fileArgs = sourceFiles.map((f) => `\"${f}\"`).join(' ');\n    const { stdout, stderr } = await execAsync(\n      `npx vitest run --reporter=json --related ${fileArgs} 2>&1`,\n      { cwd: rootDir, timeout: 120_000, maxBuffer: 10 * 1024 * 1024 }\n    );\n\n    const output = stdout + stderr;\n    const jsonMatch = output.match(/\\{[\\s\\S]*\"numTotalTests\"[\\s\\S]*\\}/);\n    if (jsonMatch) {\n      const result = JSON.parse(jsonMatch[0]);\n      return {\n        success: result.success ?? false,\n        numPassed: result.numPassedTests ?? 0,\n        numFailed: result.numFailedTests ?? 0,\n        numTotal: result.numTotalTests ?? 0,\n        sourceFiles,\n        noRelatedTests: (result.numTotalTests ?? 0) === 0,\n      };\n    }\n\n    return {\n      success: !output.includes('FAIL'),\n      rawOutput: output.slice(0, 3000),\n      sourceFiles,\n    };\n  } catch (e: unknown) {\n    // vitest --related exits non-zero if tests fail\n    const execErr = e as ExecError;\n    const output = (execErr.stdout ?? '') + (execErr.stderr ?? '');\n    const jsonMatch = output.match?.(/\\{[\\s\\S]*\"numTotalTests\"[\\s\\S]*\\}/);\n    if (jsonMatch) {\n      try {\n        const result = JSON.parse(jsonMatch[0]);\n        return {\n          success: false,\n          numPassed: result.numPassedTests ?? 0,\n          numFailed: result.numFailedTests ?? 0,\n          numTotal: result.numTotalTests ?? 0,\n          sourceFiles,\n        };\n      } catch {\n        /* fall through */\n      }\n    }\n    return { success: false, error: errMsg(e).slice(0, 1000), sourceFiles };\n  }\n}\n\n// ── Quality Trend Analysis (Level 6) ──────────────────────────────────────\n\nasync function handleQualityTrend(args: Record<string, unknown>): Promise<unknown> {\n  const rootDir = args.rootDir as string;\n  const lastN = (args.lastN as number) ?? 10;\n\n  const historyPath = path.join(rootDir, '.holoscript', 'quality-history.json');\n  if (!fs.existsSync(historyPath)) {\n    return { error: 'No quality history found. Run at least one cycle first.' };\n  }\n\n  try {\n    const history = JSON.parse(fs.readFileSync(historyPath, 'utf-8')) as Array<{\n      timestamp: string;\n      cycle: number;\n      composite: number;\n      grade: string;\n      focus: string;\n      summary: string;\n    }>;\n\n    const recent = history.slice(-lastN);\n    if (recent.length === 0) return { error: 'Quality history is empty.' };\n\n    // Basic trend analysis\n    const scores = recent.map((h) => h.composite);\n    const avgScore = scores.reduce((a, b) => a + b, 0) / scores.length;\n    const maxScore = Math.max(...scores);\n    const minScore = Math.min(...scores);\n\n    // Score by focus area\n    const focusScores: Record<string, { total: number; count: number; scores: number[] }> = {};\n    for (const entry of recent) {\n      if (!focusScores[entry.focus]) focusScores[entry.focus] = { total: 0, count: 0, scores: [] };\n      focusScores[entry.focus].total += entry.composite;\n      focusScores[entry.focus].count++;\n      focusScores[entry.focus].scores.push(entry.composite);\n    }\n\n    const focusAnalysis = Object.entries(focusScores)\n      .map(([focus, data]) => ({\n        focus,\n        avgScore: Math.round((data.total / data.count) * 1000) / 1000,\n        count: data.count,\n        trend:\n          data.scores.length >= 2\n            ? data.scores[data.scores.length - 1] - data.scores[0] > 0\n              ? 'improving'\n              : data.scores[data.scores.length - 1] - data.scores[0] < -0.05\n                ? 'declining'\n                : 'stable'\n            : 'insufficient_data',\n      }))\n      .sort((a, b) => b.avgScore - a.avgScore);\n\n    // Detect zero-score cycles (crashes)\n    const crashCycles = recent.filter((h) => h.composite === 0);\n\n    // Calculate slope (linear regression)\n    const n = scores.length;\n    const xMean = (n - 1) / 2;\n    const yMean = avgScore;\n    let numerator = 0;\n    let denominator = 0;\n    for (let i = 0; i < n; i++) {\n      numerator += (i - xMean) * (scores[i] - yMean);\n      denominator += (i - xMean) * (i - xMean);\n    }\n    const slope = denominator !== 0 ? numerator / denominator : 0;\n\n    // Recommendations\n    const recommendations: string[] = [];\n\n    if (crashCycles.length > 0) {\n      recommendations.push(\n        `${crashCycles.length} cycles scored 0 (crashes). Fix the quality scorer — these waste API tokens.`\n      );\n    }\n\n    if (slope < -0.01) {\n      recommendations.push('Quality is DECLINING. Recent changes may be introducing regressions.');\n    } else if (slope < 0.005) {\n      recommendations.push(\n        'Quality is PLATEAUED. Try a different focus area or batch-fix approach.'\n      );\n    } else {\n      recommendations.push('Quality is IMPROVING. Continue current strategy.');\n    }\n\n    const bestFocus = focusAnalysis[0];\n    const worstFocus = focusAnalysis[focusAnalysis.length - 1];\n    if (bestFocus && worstFocus && bestFocus.focus !== worstFocus.focus) {\n      recommendations.push(\n        `Best focus: \"${bestFocus.focus}\" (avg ${bestFocus.avgScore}). ` +\n          `Worst: \"${worstFocus.focus}\" (avg ${worstFocus.avgScore}). Consider reducing \"${worstFocus.focus}\" cycles.`\n      );\n    }\n\n    return {\n      analyzed: recent.length,\n      avgScore: Math.round(avgScore * 1000) / 1000,\n      maxScore,\n      minScore,\n      slope: Math.round(slope * 10000) / 10000,\n      trend: slope > 0.005 ? 'improving' : slope < -0.01 ? 'declining' : 'plateau',\n      crashCycles: crashCycles.length,\n      focusAnalysis,\n      recommendations,\n      recentScores: recent.map((h) => ({\n        cycle: h.cycle,\n        score: h.composite,\n        focus: h.focus,\n      })),\n    };\n  } catch (err: unknown) {\n    return { error: `Failed to analyze history: ${errMsg(err)}` };\n  }\n}\n\n// ── Diagnostic Handlers ──────────────────────────────────────────────────────\n\nasync function handleDiagnose(args: Record<string, unknown>): Promise<unknown> {\n  const focus = (args.focus as string) ?? 'all';\n  const maxResults = (args.maxResults as number) ?? 10;\n\n  // Import graph-rag-tools to check readiness\n  const { isGraphRAGReady } = await import('@holoscript/absorb-service/mcp');\n  if (!isGraphRAGReady()) {\n    const { ABSORB_GRAPH_RAG_ENGINE_ERROR, ABSORB_HOLO_ABSORB_REPO_HINT } =\n      await import('@holoscript/absorb-service/mcp');\n    return {\n      error:\n        ABSORB_GRAPH_RAG_ENGINE_ERROR +\n        ' Embedding provider is configured via EMBEDDING_PROVIDER env var (bm25 | xenova | openai | ollama).',\n      hint: ABSORB_HOLO_ABSORB_REPO_HINT,\n    };\n  }\n\n  const candidates: DiagnosisCandidate[] = [];\n\n  // Import handler to run GraphRAG queries internally\n  interface GraphRagContextItem {\n    name: string;\n    file: string;\n    line?: number;\n    score: number;\n    impactRadius: number;\n    callers?: string[];\n    callees?: string[];\n  }\n  interface GraphRagResult {\n    error?: string;\n    context?: GraphRagContextItem[];\n  }\n  const { handleGraphRagTool } = await import('@holoscript/absorb-service/mcp');\n\n  // ── Coverage analysis ──────────────────────────────────────────────────\n  if (focus === 'coverage' || focus === 'all') {\n    try {\n      const result = (await handleGraphRagTool('holo_ask_codebase', {\n        question:\n          'Which exported functions and classes have the highest number of callers ' +\n          'but are most likely untested? Focus on public API surface.',\n        topK: 20,\n      })) as GraphRagResult | null;\n\n      if (result && !result.error && result.context) {\n        for (const ctx of result.context.slice(0, Math.ceil(maxResults / 3))) {\n          candidates.push({\n            type: 'missing_test',\n            priority: calculatePriority(ctx.impactRadius, ctx.score),\n            symbol: ctx.name,\n            file: ctx.file,\n            line: ctx.line ?? 0,\n            impactRadius: ctx.impactRadius,\n            reason: `High-impact symbol (${ctx.impactRadius} dependents) likely lacks dedicated tests`,\n            suggestedAction: `Write unit tests for ${ctx.name} in ${ctx.file}`,\n          });\n        }\n      }\n    } catch {\n      // GraphRAG query failed — skip coverage analysis\n    }\n  }\n\n  // ── Documentation analysis ─────────────────────────────────────────────\n  if (focus === 'docs' || focus === 'all') {\n    try {\n      const result = (await handleGraphRagTool('holo_ask_codebase', {\n        question:\n          'Which exported classes and functions are missing JSDoc comments or ' +\n          'have very short documentation? Focus on public-facing APIs.',\n        topK: 15,\n      })) as GraphRagResult | null;\n\n      if (result && !result.error && result.context) {\n        for (const ctx of result.context.slice(0, Math.ceil(maxResults / 3))) {\n          candidates.push({\n            type: 'missing_docs',\n            priority: calculatePriority(ctx.impactRadius, ctx.score) * 0.8,\n            symbol: ctx.name,\n            file: ctx.file,\n            line: ctx.line ?? 0,\n            impactRadius: ctx.impactRadius,\n            reason: `Public API missing or has minimal JSDoc documentation`,\n            suggestedAction: `Add comprehensive JSDoc to ${ctx.name}`,\n          });\n        }\n      }\n    } catch {\n      // Skip docs analysis\n    }\n  }\n\n  // ── Complexity analysis ────────────────────────────────────────────────\n  if (focus === 'complexity' || focus === 'all') {\n    try {\n      const result = (await handleGraphRagTool('holo_ask_codebase', {\n        question:\n          'Which modules or classes have the most incoming and outgoing dependencies? ' +\n          'These are likely the most complex and fragile parts of the codebase.',\n        topK: 15,\n      })) as GraphRagResult | null;\n\n      if (result && !result.error && result.context) {\n        for (const ctx of result.context.slice(0, Math.ceil(maxResults / 3))) {\n          const totalDeps = (ctx.callers?.length ?? 0) + (ctx.callees?.length ?? 0);\n          candidates.push({\n            type: 'high_complexity',\n            priority: calculatePriority(ctx.impactRadius, ctx.score) * 0.9,\n            symbol: ctx.name,\n            file: ctx.file,\n            line: ctx.line ?? 0,\n            impactRadius: ctx.impactRadius,\n            reason: `High coupling: ${totalDeps} direct dependencies (${ctx.callers?.length ?? 0} callers, ${ctx.callees?.length ?? 0} callees)`,\n            suggestedAction: `Consider refactoring ${ctx.name} to reduce coupling`,\n          });\n        }\n      }\n    } catch {\n      // Skip complexity analysis\n    }\n  }\n\n  // Sort by priority (highest first) and limit\n  candidates.sort((a, b) => b.priority - a.priority);\n  const topCandidates = candidates.slice(0, maxResults);\n\n  return {\n    focus,\n    totalCandidates: candidates.length,\n    candidates: topCandidates,\n    summary: summarizeDiagnosis(topCandidates),\n  };\n}\n\nasync function handleValidateQuality(args: Record<string, unknown>): Promise<unknown> {\n  const rootDir = args.rootDir as string;\n  const skipTests = (args.skipTests as boolean) ?? false;\n  const skipLint = (args.skipLint as boolean) ?? false;\n\n  const scores: QualityScores & { coverage?: QualityScore } = {\n    typeCheck: { pass: false, score: 0, details: '' },\n    tests: { pass: false, score: 0, details: '' },\n    lint: { pass: false, score: 0, details: '' },\n    coverage: { pass: false, score: 0, details: '' },\n  };\n\n  // ── Type check ─────────────────────────────────────────────────────────\n  // Use logarithmic scale: score = 1 / (1 + ln(1 + errors/10))\n  // This rewards error reduction even at high counts:\n  //   0 errors → 1.0,  10 → 0.59,  50 → 0.37,  100 → 0.29,  500 → 0.20,  1000 → 0.18\n  const tscScore = (errorCount: number) =>\n    errorCount === 0 ? 1.0 : 1 / (1 + Math.log(1 + errorCount / 10));\n\n  try {\n    const { stdout, stderr } = await execAsync('npx tsc --noEmit 2>&1', {\n      cwd: rootDir,\n      timeout: 180_000,\n      maxBuffer: 50 * 1024 * 1024,\n    });\n    const output = stdout + stderr;\n    const errorCount = (output.match(/error TS\\d+/g) ?? []).length;\n    scores.typeCheck = {\n      pass: errorCount === 0,\n      score: tscScore(errorCount),\n      details: errorCount === 0 ? 'No type errors' : `${errorCount} type error(s)`,\n    };\n  } catch (e: unknown) {\n    // tsc exits non-zero when there are errors — this is normal, not a crash\n    const execErr = e as ExecError;\n    const output = (execErr.stdout ?? '') + (execErr.stderr ?? '');\n    const tsErrors = output.match?.(/error TS\\d+/g) ?? [];\n    const errorCount = tsErrors.length;\n    // Also check for \"Found N errors\" summary line as fallback\n    const foundMatch = output.match(/Found (\\d+) errors?/);\n    const reportedCount = foundMatch ? parseInt(foundMatch[1], 10) : 0;\n    const bestCount = errorCount || reportedCount;\n    scores.typeCheck = {\n      pass: false,\n      score: tscScore(bestCount || 50),\n      details:\n        bestCount > 0\n          ? `Type check failed: ${bestCount} errors`\n          : `Type check failed: unknown errors (tsc non-zero exit)`,\n    };\n  }\n\n  // ── Tests ──────────────────────────────────────────────────────────────\n  if (!skipTests) {\n    try {\n      const { stdout } = await execAsync('npx vitest run --reporter=json 2>&1', {\n        cwd: rootDir,\n        timeout: 300_000,\n        maxBuffer: 50 * 1024 * 1024,\n      });\n      try {\n        const jsonMatch = stdout.match(/\\{[\\s\\S]*\"numTotalTests\"[\\s\\S]*\\}/);\n        if (jsonMatch) {\n          const result = JSON.parse(jsonMatch[0]);\n          const total = result.numTotalTests ?? 0;\n          const passed = result.numPassedTests ?? 0;\n          scores.tests = {\n            pass: result.success ?? false,\n            score: total > 0 ? passed / total : 0,\n            details: `${passed}/${total} tests passed`,\n          };\n        }\n      } catch {\n        scores.tests = { pass: true, score: 0.8, details: 'Tests ran but JSON parse failed' };\n      }\n    } catch (e: unknown) {\n      // Try to extract partial results even from failed runs\n      const execErr = e as ExecError;\n      const output = (execErr.stdout ?? '') + (execErr.stderr ?? '');\n      const jsonMatch = output.match?.(/\\{[\\s\\S]*\"numTotalTests\"[\\s\\S]*\\}/);\n      if (jsonMatch) {\n        try {\n          const result = JSON.parse(jsonMatch[0]);\n          const total = result.numTotalTests ?? 0;\n          const passed = result.numPassedTests ?? 0;\n          scores.tests = {\n            pass: false,\n            score: total > 0 ? passed / total : 0.1,\n            details: `${passed}/${total} tests passed (suite exited non-zero)`,\n          };\n        } catch {\n          scores.tests = { pass: false, score: 0.1, details: 'Test suite crashed' };\n        }\n      } else {\n        scores.tests = {\n          pass: false,\n          score: 0.1,\n          details: `Test suite failed: ${errMsg(e).slice(0, 200)}`,\n        };\n      }\n    }\n  } else {\n    scores.tests = { pass: true, score: 0.5, details: 'Skipped (--skipTests)' };\n  }\n\n  // ── Lint ───────────────────────────────────────────────────────────────\n  if (!skipLint) {\n    try {\n      await execAsync('npx eslint . --max-warnings 0 2>&1', {\n        cwd: rootDir,\n        timeout: 120_000,\n        maxBuffer: 50 * 1024 * 1024,\n      });\n      scores.lint = { pass: true, score: 1.0, details: 'No lint errors' };\n    } catch (e: unknown) {\n      const execErr = e as ExecError;\n      const output = (execErr.stdout ?? '') + (execErr.stderr ?? '');\n      // Count actual ESLint problem lines (format: \"N problems (X errors, Y warnings)\")\n      const summaryMatch = output.match(/(\\d+) problems? \\((\\d+) errors?, (\\d+) warnings?\\)/);\n      let errorCount: number;\n      let warningCount: number;\n      if (summaryMatch) {\n        errorCount = parseInt(summaryMatch[2], 10);\n        warningCount = parseInt(summaryMatch[3], 10);\n      } else {\n        // Fallback: count lines with severity markers (e.g. \"2:10  error  ...\")\n        errorCount = (output.match(/^\\s*\\d+:\\d+\\s+error\\s/gm) ?? []).length;\n        warningCount = (output.match(/^\\s*\\d+:\\d+\\s+warning\\s/gm) ?? []).length;\n      }\n      // Use logarithmic scale for lint too — prevents score from going to 0 at 10+ errors\n      const lintScore =\n        errorCount === 0\n          ? Math.max(0.8, 1 - warningCount * 0.01)\n          : 1 / (1 + Math.log(1 + errorCount / 5));\n      scores.lint = {\n        pass: errorCount === 0,\n        score: Math.max(0, lintScore),\n        details: `${errorCount} error(s), ${warningCount} warning(s)`,\n      };\n    }\n  } else {\n    scores.lint = { pass: true, score: 0.5, details: 'Skipped (--skipLint)' };\n  }\n\n  // ── Coverage ─────────────────────────────────────────────────────────\n  if (!skipTests) {\n    try {\n      const { stdout: _covOut } = await execAsync(\n        'npx vitest run --coverage --coverage.reporter=json-summary --coverage.reportsDirectory=.holoscript/coverage 2>&1',\n        { cwd: rootDir, timeout: 300_000, maxBuffer: 50 * 1024 * 1024 }\n      );\n      // Try to read coverage summary\n      const covPath = path.join(rootDir, '.holoscript', 'coverage', 'coverage-summary.json');\n      if (fs.existsSync(covPath)) {\n        const covData = JSON.parse(fs.readFileSync(covPath, 'utf-8'));\n        const total = covData.total;\n        const linesPct = (total?.lines?.pct ?? 0) / 100;\n        const branchesPct = (total?.branches?.pct ?? 0) / 100;\n        const funcsPct = (total?.functions?.pct ?? 0) / 100;\n        const avgPct = (linesPct + branchesPct + funcsPct) / 3;\n        scores.coverage = {\n          pass: avgPct >= 0.6,\n          score: avgPct,\n          details: `Lines: ${(linesPct * 100).toFixed(1)}%, Branches: ${(branchesPct * 100).toFixed(1)}%, Functions: ${(funcsPct * 100).toFixed(1)}%`,\n        };\n      }\n    } catch {\n      scores.coverage = { pass: false, score: 0.1, details: 'Coverage collection failed' };\n    }\n  } else {\n    scores.coverage = { pass: false, score: 0, details: 'Skipped (--skipTests)' };\n  }\n\n  // ── Composite quality score ────────────────────────────────────────────\n  // Formula: tests * 0.30 + coverage * 0.25 + typeCheck * 0.20 + lint * 0.10 + circuitBreaker * 0.15\n  const coverageScore = scores.coverage?.score ?? 0;\n  const composite =\n    scores.tests.score * 0.3 +\n    coverageScore * 0.25 +\n    scores.typeCheck.score * 0.2 +\n    scores.lint.score * 0.1 +\n    (scores.typeCheck.pass ? 0.15 : 0);\n\n  return {\n    rootDir,\n    scores,\n    composite: Math.round(composite * 100) / 100,\n    grade:\n      composite >= 0.9\n        ? 'A'\n        : composite >= 0.8\n          ? 'B'\n          : composite >= 0.7\n            ? 'C'\n            : composite >= 0.5\n              ? 'D'\n              : 'F',\n    allPassing: scores.typeCheck.pass && scores.tests.pass && scores.lint.pass,\n    timestamp: new Date().toISOString(),\n  };\n}\n\n// ── Types ────────────────────────────────────────────────────────────────────\n\ninterface DiagnosisCandidate {\n  type: 'missing_test' | 'missing_docs' | 'high_complexity';\n  priority: number;\n  symbol: string;\n  file: string;\n  line: number;\n  impactRadius: number;\n  reason: string;\n  suggestedAction: string;\n}\n\ninterface QualityScore {\n  pass: boolean;\n  score: number;\n  details: string;\n}\n\ninterface QualityScores {\n  typeCheck: QualityScore;\n  tests: QualityScore;\n  lint: QualityScore;\n}\n\n// ── Helpers ──────────────────────────────────────────────────────────────────\n\nfunction calculatePriority(impactRadius: number, relevanceScore: number): number {\n  // Higher impact + higher relevance = higher priority\n  return Math.round((impactRadius * 0.6 + relevanceScore * 100 * 0.4) * 100) / 100;\n}\n\nfunction summarizeDiagnosis(candidates: DiagnosisCandidate[]): string {\n  const byType = {\n    missing_test: candidates.filter((c) => c.type === 'missing_test').length,\n    missing_docs: candidates.filter((c) => c.type === 'missing_docs').length,\n    high_complexity: candidates.filter((c) => c.type === 'high_complexity').length,\n  };\n\n  const parts: string[] = [];\n  if (byType.missing_test > 0) parts.push(`${byType.missing_test} untested high-impact symbols`);\n  if (byType.missing_docs > 0) parts.push(`${byType.missing_docs} undocumented public APIs`);\n  if (byType.high_complexity > 0) parts.push(`${byType.high_complexity} high-complexity modules`);\n  return parts.join(', ') || 'No improvement opportunities found';\n}\n","/**\n * HoloScript MCP GLTF Import/Export Tools\n *\n * Exposes the GLTFPipeline as MCP tools for 3D asset import and export.\n * Two tools are provided:\n *\n * 1. `import_gltf` - Import a glTF/GLB file and convert it to .holo composition code.\n *    Accepts either a file path or inline glTF JSON. Handles node hierarchy, PBR materials,\n *    animations, physics extensions, and trait inference.\n *\n * 2. `compile_to_gltf` - Compile .holo composition code to glTF 2.0 / GLB binary format.\n *    Uses the GLTFPipeline from @holoscript/core with full PBR material support, mesh\n *    primitives, animations, skeleton/armature, LOD generation, and texture embedding.\n *\n * @version 1.0.0\n * @package @holoscript/mcp-server\n */\n\nimport type { Tool } from '@modelcontextprotocol/sdk/types.js';\nimport {\n  parseHolo,\n  GLTFPipeline,\n  type GLTFPipelineOptions,\n  type GLTFExportResult,\n  type GLTFExportStats,\n  type HoloComposition,\n} from '@holoscript/core';\n\nimport * as fs from 'fs';\nimport * as path from 'path';\n\n// =============================================================================\n// GLTF IMPORT: Inline glTF JSON parser (no CLI dependency)\n// =============================================================================\n\n/**\n * Minimal glTF data interfaces for import (mirrors the CLI importer types\n * without requiring @holoscript/cli as a dependency).\n */\ninterface GltfNode {\n  name?: string;\n  mesh?: number;\n  camera?: number;\n  skin?: number;\n  children?: number[];\n  translation?: [number, number, number];\n  rotation?: [number, number, number, number];\n  scale?: [number, number, number];\n  matrix?: number[];\n  extras?: Record<string, unknown>;\n  extensions?: Record<string, unknown>;\n}\n\ninterface GltfMaterial {\n  name?: string;\n  pbrMetallicRoughness?: {\n    baseColorFactor?: [number, number, number, number];\n    baseColorTexture?: { index: number };\n    metallicFactor?: number;\n    roughnessFactor?: number;\n    metallicRoughnessTexture?: { index: number };\n  };\n  normalTexture?: { index: number; scale?: number };\n  occlusionTexture?: { index: number; strength?: number };\n  emissiveFactor?: [number, number, number];\n  emissiveTexture?: { index: number };\n  alphaMode?: string;\n  alphaCutoff?: number;\n  doubleSided?: boolean;\n  extensions?: Record<string, unknown>;\n}\n\ninterface GltfMesh {\n  name?: string;\n  primitives: Array<{\n    attributes: Record<string, number>;\n    indices?: number;\n    material?: number;\n    mode?: number;\n  }>;\n}\n\ninterface GltfAnimation {\n  name?: string;\n  channels: Array<{\n    sampler: number;\n    target: { node?: number; path: string };\n  }>;\n  samplers: Array<{\n    input: number;\n    output: number;\n    interpolation?: string;\n  }>;\n}\n\ninterface GltfScene {\n  name?: string;\n  nodes?: number[];\n}\n\ninterface GltfData {\n  asset: { version: string; generator?: string; copyright?: string };\n  scene?: number;\n  scenes?: GltfScene[];\n  nodes?: GltfNode[];\n  meshes?: GltfMesh[];\n  materials?: GltfMaterial[];\n  animations?: GltfAnimation[];\n  cameras?: Array<{ name?: string; type: string; perspective?: any; orthographic?: any }>;\n  skins?: Array<{ name?: string; joints: number[] }>;\n  extensionsUsed?: string[];\n  extensions?: Record<string, unknown>;\n}\n\n// ---------------------------------------------------------------------------\n// GLB Constants & Parser\n// ---------------------------------------------------------------------------\n\nconst GLB_MAGIC = 0x46546c67;\nconst GLB_VERSION = 2;\nconst GLB_CHUNK_JSON = 0x4e4f534a;\nconst GLB_HEADER_SIZE = 12;\nconst GLB_CHUNK_HEADER_SIZE = 8;\n\nfunction parseGlbBuffer(buffer: Buffer): GltfData {\n  if (buffer.length < GLB_HEADER_SIZE) {\n    throw new Error('GLB data too small to contain a valid header.');\n  }\n\n  const magic = buffer.readUInt32LE(0);\n  if (magic !== GLB_MAGIC) {\n    throw new Error(\n      `Invalid GLB magic: expected 0x${GLB_MAGIC.toString(16)}, got 0x${magic.toString(16)}.`\n    );\n  }\n\n  const version = buffer.readUInt32LE(4);\n  if (version !== GLB_VERSION) {\n    throw new Error(`Unsupported GLB version ${version}. Only version 2 is supported.`);\n  }\n\n  const totalLength = buffer.readUInt32LE(8);\n  if (buffer.length < totalLength) {\n    throw new Error(\n      `GLB truncated: header declares ${totalLength} bytes but buffer is ${buffer.length} bytes.`\n    );\n  }\n\n  let offset = GLB_HEADER_SIZE;\n  let jsonData: GltfData | null = null;\n\n  while (offset + GLB_CHUNK_HEADER_SIZE <= totalLength) {\n    const chunkLength = buffer.readUInt32LE(offset);\n    const chunkType = buffer.readUInt32LE(offset + 4);\n    const chunkDataOffset = offset + GLB_CHUNK_HEADER_SIZE;\n\n    if (chunkDataOffset + chunkLength > totalLength) {\n      throw new Error(`GLB chunk at offset ${offset} overflows the file boundary.`);\n    }\n\n    if (chunkType === GLB_CHUNK_JSON) {\n      const jsonString = buffer.toString('utf8', chunkDataOffset, chunkDataOffset + chunkLength);\n      try {\n        jsonData = JSON.parse(jsonString) as GltfData;\n      } catch (e) {\n        throw new Error(`Failed to parse JSON chunk in GLB: ${(e as Error).message}`);\n      }\n    }\n\n    offset = chunkDataOffset + chunkLength;\n  }\n\n  if (!jsonData) {\n    throw new Error('GLB data does not contain a JSON chunk.');\n  }\n\n  return jsonData;\n}\n\n// ---------------------------------------------------------------------------\n// Color & Transform Utilities\n// ---------------------------------------------------------------------------\n\nfunction rgbToHex(r: number, g: number, b: number): string {\n  const toSrgb = (c: number): number => {\n    const clamped = Math.max(0, Math.min(1, c));\n    const corrected =\n      clamped <= 0.0031308 ? clamped * 12.92 : 1.055 * Math.pow(clamped, 1.0 / 2.4) - 0.055;\n    return Math.round(corrected * 255);\n  };\n  return `#${toSrgb(r).toString(16).padStart(2, '0')}${toSrgb(g).toString(16).padStart(2, '0')}${toSrgb(b).toString(16).padStart(2, '0')}`;\n}\n\nfunction quaternionToEulerDeg(q: [number, number, number, number]): [number, number, number] {\n  const [x, y, z, w] = q;\n  const sinrCosp = 2.0 * (w * x + y * z);\n  const cosrCosp = 1.0 - 2.0 * (x * x + y * y);\n  const roll = Math.atan2(sinrCosp, cosrCosp);\n\n  const sinp = 2.0 * (w * y - z * x);\n  const pitch = Math.abs(sinp) >= 1 ? Math.sign(sinp) * (Math.PI / 2) : Math.asin(sinp);\n\n  const sinyCosp = 2.0 * (w * z + x * y);\n  const cosyCosp = 1.0 - 2.0 * (y * y + z * z);\n  const yaw = Math.atan2(sinyCosp, cosyCosp);\n\n  const toDeg = (rad: number): number => Math.round(((rad * 180.0) / Math.PI) * 1000) / 1000;\n  return [toDeg(roll), toDeg(pitch), toDeg(yaw)];\n}\n\nfunction formatVec3(v: [number, number, number]): string {\n  const fmt = (n: number): string => String(Math.round(n * 1000) / 1000);\n  return `[${fmt(v[0])}, ${fmt(v[1])}, ${fmt(v[2])}]`;\n}\n\nfunction _sanitizeName(name: string): string {\n  let clean = name.replace(/[^a-zA-Z0-9_]/g, '_');\n  if (/^\\d/.test(clean)) clean = '_' + clean;\n  clean = clean.replace(/_+/g, '_').replace(/_+$/, '');\n  return clean || 'unnamed';\n}\n\n// ---------------------------------------------------------------------------\n// Trait Inference\n// ---------------------------------------------------------------------------\n\nfunction inferTraits(node: GltfNode, gltf: GltfData): string[] {\n  const traits: string[] = [];\n  const nameLower = (node.name || '').toLowerCase();\n\n  if (/light|lamp|lantern|candle|torch|bulb|emitter/.test(nameLower)) {\n    traits.push('@glowing', '@emissive');\n  }\n  if (/button|switch|lever|toggle|handle/.test(nameLower)) {\n    traits.push('@clickable');\n  }\n  if (/door|gate|hatch|lid/.test(nameLower)) {\n    traits.push('@clickable', '@animated');\n  }\n  if (/grab|pickup|pick_up|item|tool|weapon|sword|axe|hammer|key/.test(nameLower)) {\n    traits.push('@grabbable');\n  }\n  if (/crate|box|barrel|rock|stone|debris|plank|brick/.test(nameLower)) {\n    traits.push('@physics', '@collidable');\n  }\n  if (/ball|projectile|missile/.test(nameLower)) {\n    traits.push('@physics', '@throwable', '@grabbable');\n  }\n  if (/floor|ground|terrain|platform|wall|ceiling|ramp|stair/.test(nameLower)) {\n    traits.push('@collidable');\n  }\n  if (/npc|character|enemy|creature|avatar|player|companion|guard|villager/.test(nameLower)) {\n    traits.push('@animated', '@collidable');\n  }\n  if (/portal|teleport|warp/.test(nameLower)) {\n    traits.push('@portal', '@glowing');\n  }\n  if (/speaker|radio|audio|music|sound/.test(nameLower)) {\n    traits.push('@spatial_audio');\n  }\n  if (/glass|window|transparent|crystal|ice/.test(nameLower)) {\n    traits.push('@transparent');\n  }\n  if (/mirror|chrome|metal|shiny|polished/.test(nameLower)) {\n    traits.push('@reflective');\n  }\n  if (/fire|smoke|fountain|waterfall|steam|spark|flame/.test(nameLower)) {\n    traits.push('@particle_emitter');\n  }\n\n  // Extension-based inference\n  const ext = node.extensions || {};\n  if (ext['KHR_rigid_bodies'] || ext['KHR_physics_rigid_bodies']) {\n    const rb = (ext['KHR_rigid_bodies'] || ext['KHR_physics_rigid_bodies']) as any;\n    if (rb?.isKinematic) {\n      traits.push('@kinematic');\n    } else {\n      traits.push('@physics', '@rigid');\n    }\n    traits.push('@collidable');\n  }\n  if ((ext['MSFT_physics'] as any)?.rigidBody) {\n    const rb = (ext['MSFT_physics'] as any).rigidBody;\n    traits.push(rb.isKinematic ? '@kinematic' : '@physics');\n    traits.push('@collidable');\n  }\n  if (ext['KHR_lights_punctual']) {\n    traits.push('@emissive', '@glowing');\n  }\n\n  // Extras-based inference\n  const extras = node.extras || {};\n  if (extras.holoscript_traits && Array.isArray(extras.holoscript_traits)) {\n    for (const t of extras.holoscript_traits) {\n      const traitStr = String(t).startsWith('@') ? String(t) : `@${t}`;\n      if (!traits.includes(traitStr)) traits.push(traitStr);\n    }\n  }\n  if (extras.interactive === true || extras.interactable === true) {\n    if (!traits.includes('@clickable')) traits.push('@clickable');\n  }\n  if (extras.physics === true || extras.rigidbody === true) {\n    if (!traits.includes('@physics')) {\n      traits.push('@physics', '@collidable');\n    }\n  }\n\n  // Animation-based inference\n  if (gltf.animations?.length && gltf.nodes) {\n    const nodeIndex = gltf.nodes.indexOf(node);\n    if (nodeIndex >= 0) {\n      const hasAnimation = gltf.animations.some((anim) =>\n        anim.channels.some((ch) => ch.target.node === nodeIndex)\n      );\n      if (hasAnimation && !traits.includes('@animated')) traits.push('@animated');\n    }\n  }\n\n  return [...new Set(traits)];\n}\n\n// ---------------------------------------------------------------------------\n// Material & Animation Mapping\n// ---------------------------------------------------------------------------\n\nfunction materialToTraits(material: GltfMaterial): { properties: string[]; traits: string[] } {\n  const properties: string[] = [];\n  const traits: string[] = [];\n  const pbr = material.pbrMetallicRoughness;\n\n  if (pbr?.baseColorFactor) {\n    const [r, g, b, a] = pbr.baseColorFactor;\n    properties.push(`color: \"${rgbToHex(r, g, b)}\"`);\n    if (a < 1.0) {\n      traits.push('@transparent');\n      properties.push(`opacity: ${Math.round(a * 100) / 100}`);\n    }\n  }\n  if (pbr?.metallicFactor !== undefined) {\n    properties.push(`metalness: ${Math.round(pbr.metallicFactor * 100) / 100}`);\n    if (pbr.metallicFactor > 0.7) traits.push('@reflective');\n  }\n  if (pbr?.roughnessFactor !== undefined) {\n    properties.push(`roughness: ${Math.round(pbr.roughnessFactor * 100) / 100}`);\n  }\n  if (material.emissiveFactor) {\n    const [er, eg, eb] = material.emissiveFactor;\n    if (er > 0 || eg > 0 || eb > 0) {\n      traits.push('@emissive');\n      properties.push(`emissive_color: \"${rgbToHex(er, eg, eb)}\"`);\n      properties.push(`emissive_intensity: ${Math.round(Math.max(er, eg, eb) * 100) / 100}`);\n    }\n  }\n  if (material.alphaMode === 'BLEND') {\n    if (!traits.includes('@transparent')) traits.push('@transparent');\n  } else if (material.alphaMode === 'MASK') {\n    properties.push(`alpha_cutoff: ${material.alphaCutoff ?? 0.5}`);\n  }\n  if (material.doubleSided) {\n    properties.push(`double_sided: true`);\n  }\n\n  return { properties, traits };\n}\n\nfunction getAnimationClipsForNode(nodeIndex: number, gltf: GltfData): string[] {\n  const clips: string[] = [];\n  if (!gltf.animations) return clips;\n  for (const anim of gltf.animations) {\n    if (anim.channels.some((ch) => ch.target.node === nodeIndex)) {\n      const clipName = anim.name || `animation_${gltf.animations.indexOf(anim)}`;\n      if (!clips.includes(clipName)) clips.push(clipName);\n    }\n  }\n  return clips;\n}\n\nfunction extractPhysicsParams(node: GltfNode): string[] {\n  const params: string[] = [];\n  const ext = node.extensions || {};\n\n  const rigid = (ext['KHR_rigid_bodies'] || ext['KHR_physics_rigid_bodies']) as any;\n  if (rigid) {\n    if (rigid.mass !== undefined) params.push(`mass: ${rigid.mass}`);\n    if (rigid.linearVelocity) params.push(`linear_velocity: ${formatVec3(rigid.linearVelocity)}`);\n    if (rigid.angularVelocity)\n      params.push(`angular_velocity: ${formatVec3(rigid.angularVelocity)}`);\n  }\n\n  const msft = ext['MSFT_physics'] as any;\n  if (msft?.rigidBody) {\n    const rb = msft.rigidBody;\n    if (rb.mass !== undefined) params.push(`mass: ${rb.mass}`);\n    if (rb.linearDamping !== undefined) params.push(`linear_damping: ${rb.linearDamping}`);\n    if (rb.angularDamping !== undefined) params.push(`angular_damping: ${rb.angularDamping}`);\n  }\n\n  return params;\n}\n\n// ---------------------------------------------------------------------------\n// Node-to-Holo Conversion\n// ---------------------------------------------------------------------------\n\nfunction nodeToHolo(nodeIndex: number, gltf: GltfData, sourceName: string, indent: number): string {\n  const nodes = gltf.nodes;\n  if (!nodes || nodeIndex < 0 || nodeIndex >= nodes.length) return '';\n\n  const node = nodes[nodeIndex];\n  const pad = '  '.repeat(indent);\n  const innerPad = '  '.repeat(indent + 1);\n  const displayName = node.name || `Node_${nodeIndex}`;\n\n  const inferredTraits = inferTraits(node, gltf);\n\n  let materialProps: string[] = [];\n  let materialTraits: string[] = [];\n\n  if (node.mesh !== undefined && gltf.meshes) {\n    const mesh = gltf.meshes[node.mesh];\n    if (mesh?.primitives.length > 0) {\n      const primMatIdx = mesh.primitives[0].material;\n      if (primMatIdx !== undefined && gltf.materials?.[primMatIdx]) {\n        const mapped = materialToTraits(gltf.materials[primMatIdx]);\n        materialProps = mapped.properties;\n        materialTraits = mapped.traits;\n      }\n    }\n  }\n\n  const allTraits = [...new Set([...inferredTraits, ...materialTraits])];\n  const animClips = getAnimationClipsForNode(nodeIndex, gltf);\n  if (animClips.length > 0 && !allTraits.includes('@animated')) allTraits.push('@animated');\n\n  const physicsParams = extractPhysicsParams(node);\n  const traitStr = allTraits.length > 0 ? ' ' + allTraits.join(' ') : '';\n\n  const lines: string[] = [];\n  lines.push(`${pad}object \"${displayName}\"${traitStr} {`);\n\n  if (node.mesh !== undefined) {\n    lines.push(`${innerPad}geometry: \"${sourceName}#${displayName}\"`);\n  }\n  if (node.translation) {\n    lines.push(`${innerPad}position: ${formatVec3(node.translation)}`);\n  }\n  if (node.rotation) {\n    const euler = quaternionToEulerDeg(node.rotation);\n    if (euler[0] !== 0 || euler[1] !== 0 || euler[2] !== 0) {\n      lines.push(`${innerPad}rotation: ${formatVec3(euler)}`);\n    }\n  }\n  if (node.scale) {\n    const isDefault = node.scale[0] === 1 && node.scale[1] === 1 && node.scale[2] === 1;\n    if (!isDefault) lines.push(`${innerPad}scale: ${formatVec3(node.scale)}`);\n  }\n\n  for (const prop of materialProps) lines.push(`${innerPad}${prop}`);\n\n  if (animClips.length === 1) {\n    lines.push(`${innerPad}animation_clip: \"${animClips[0]}\"`);\n  } else if (animClips.length > 1) {\n    lines.push(`${innerPad}animation_clips: [${animClips.map((c) => `\"${c}\"`).join(', ')}]`);\n  }\n\n  for (const param of physicsParams) lines.push(`${innerPad}${param}`);\n\n  if (node.extras) {\n    const extrasKeys = Object.keys(node.extras).filter((k) => k !== 'holoscript_traits');\n    if (extrasKeys.length > 0) {\n      lines.push(`${innerPad}// Custom properties from glTF extras:`);\n      for (const key of extrasKeys) {\n        const value = node.extras![key];\n        lines.push(\n          `${innerPad}// ${key}: ${typeof value === 'string' ? `\"${value}\"` : JSON.stringify(value)}`\n        );\n      }\n    }\n  }\n\n  if (node.children?.length) {\n    lines.push('');\n    for (const childIdx of node.children) {\n      const childBlock = nodeToHolo(childIdx, gltf, sourceName, indent + 1);\n      if (childBlock) lines.push(childBlock);\n    }\n  }\n\n  lines.push(`${pad}}`);\n  return lines.join('\\n');\n}\n\n// ---------------------------------------------------------------------------\n// Build .holo Composition from glTF Data\n// ---------------------------------------------------------------------------\n\nfunction buildHoloComposition(gltf: GltfData, sourceName: string): string {\n  const lines: string[] = [];\n\n  const generator = gltf.asset.generator || 'unknown';\n  const gltfVersion = gltf.asset.version || '2.0';\n\n  lines.push(`// Imported from ${sourceName}`);\n  lines.push(`// glTF ${gltfVersion} - Generator: ${generator}`);\n  if (gltf.asset.copyright) lines.push(`// Copyright: ${gltf.asset.copyright}`);\n  lines.push('');\n\n  const activeSceneIdx = gltf.scene ?? 0;\n  const scenes = gltf.scenes || [];\n  const activeScene = scenes[activeSceneIdx];\n  const sceneName = activeScene?.name || sourceName.replace(/\\.[^.]+$/, '');\n\n  lines.push(`composition \"${sceneName}\" {`);\n  lines.push('  environment {');\n  lines.push('    skybox: \"gradient\"');\n  lines.push('    ambient_light: 0.4');\n\n  if ((gltf.extensions?.['KHR_lights_punctual'] as any)?.lights) {\n    const lights = (gltf.extensions?.['KHR_lights_punctual'] as any).lights;\n    const directionalLight = lights.find((l: any) => l.type === 'directional');\n    if (directionalLight) {\n      const color = directionalLight.color || [1, 1, 1];\n      const intensity = directionalLight.intensity ?? 1;\n      lines.push(`    directional_light_color: \"${rgbToHex(color[0], color[1], color[2])}\"`);\n      lines.push(`    directional_light_intensity: ${Math.round(intensity * 100) / 100}`);\n    }\n  }\n\n  lines.push('  }');\n  lines.push('');\n\n  const rootNodes = activeScene?.nodes ? [...activeScene.nodes] : [];\n\n  if (rootNodes.length === 0 && gltf.nodes?.length) {\n    const childSet = new Set<number>();\n    for (const node of gltf.nodes) {\n      if (node.children) {\n        for (const childIdx of node.children) childSet.add(childIdx);\n      }\n    }\n    for (let i = 0; i < gltf.nodes.length; i++) {\n      if (!childSet.has(i)) rootNodes.push(i);\n    }\n  }\n\n  lines.push('  spatial_group \"Root\" {');\n  for (const nodeIdx of rootNodes) {\n    const block = nodeToHolo(nodeIdx, gltf, sourceName, 2);\n    if (block) {\n      lines.push(block);\n      lines.push('');\n    }\n  }\n  lines.push('  }');\n\n  if (gltf.animations?.length) {\n    lines.push('');\n    lines.push('  // --- Animations ---');\n    for (let i = 0; i < gltf.animations.length; i++) {\n      const anim = gltf.animations[i];\n      const animName = anim.name || `animation_${i}`;\n      const targetNodes = new Set<number>();\n      for (const ch of anim.channels) {\n        if (ch.target.node !== undefined) targetNodes.add(ch.target.node);\n      }\n      const targetNames = [...targetNodes].map((idx) => gltf.nodes?.[idx]?.name || `node_${idx}`);\n      lines.push(`  // \"${animName}\" -> targets: ${targetNames.join(', ')}`);\n    }\n  }\n\n  lines.push('}');\n  lines.push('');\n\n  return lines.join('\\n');\n}\n\n// =============================================================================\n// IMPORT HANDLER\n// =============================================================================\n\nexport interface GltfImportOptions {\n  /** Absolute path to a .gltf or .glb file on disk */\n  filePath?: string;\n  /** Inline glTF JSON object (as string or pre-parsed) */\n  gltfJson?: string | object;\n  /** Base64-encoded GLB binary data */\n  glbBase64?: string;\n  /** Source file name hint (used in generated comments and geometry refs) */\n  sourceName?: string;\n}\n\nexport interface GltfImportResult {\n  success: boolean;\n  /** Generated .holo composition code */\n  holoCode?: string;\n  /** Import statistics */\n  stats?: {\n    nodeCount: number;\n    meshCount: number;\n    materialCount: number;\n    animationCount: number;\n    sceneCount: number;\n  };\n  error?: string;\n}\n\nexport async function handleImportGltf(args: Record<string, unknown>): Promise<GltfImportResult> {\n  const { filePath, gltfJson, glbBase64, sourceName: rawSourceName } = args as GltfImportOptions;\n\n  if (!filePath && !gltfJson && !glbBase64) {\n    throw new Error(\n      'At least one input is required: filePath (path to .gltf/.glb file), ' +\n        'gltfJson (inline glTF JSON), or glbBase64 (base64-encoded GLB binary).'\n    );\n  }\n\n  let gltfData: GltfData;\n  let sourceName = rawSourceName || 'imported.gltf';\n\n  try {\n    if (filePath) {\n      // File-based import\n      const resolvedPath = path.resolve(filePath);\n      if (!fs.existsSync(resolvedPath)) {\n        throw new Error(`File not found: ${resolvedPath}`);\n      }\n\n      sourceName = rawSourceName || path.basename(resolvedPath);\n      const ext = path.extname(resolvedPath).toLowerCase();\n\n      if (ext === '.glb') {\n        const buffer = fs.readFileSync(resolvedPath);\n        gltfData = parseGlbBuffer(buffer);\n      } else if (ext === '.gltf') {\n        const rawJson = fs.readFileSync(resolvedPath, 'utf8');\n        gltfData = JSON.parse(rawJson) as GltfData;\n      } else {\n        throw new Error(`Unsupported file extension \"${ext}\". Expected \".gltf\" or \".glb\".`);\n      }\n    } else if (glbBase64) {\n      // Base64-encoded GLB binary\n      const buffer = Buffer.from(glbBase64, 'base64');\n      gltfData = parseGlbBuffer(buffer);\n      sourceName = rawSourceName || 'imported.glb';\n    } else if (gltfJson) {\n      // Inline glTF JSON\n      if (typeof gltfJson === 'string') {\n        gltfData = JSON.parse(gltfJson) as GltfData;\n      } else {\n        gltfData = gltfJson as GltfData;\n      }\n      sourceName = rawSourceName || 'imported.gltf';\n    } else {\n      throw new Error(\n        'No valid input provided. Expected one of: gltf_url (URL string), gltf_base64 (base64 string), gltf_json (object), or file_path (local path).'\n      );\n    }\n\n    // Validate minimal glTF structure\n    if (!gltfData.asset || !gltfData.asset.version) {\n      throw new Error('Invalid glTF: missing required \"asset.version\" field.');\n    }\n\n    const holoCode = buildHoloComposition(gltfData, sourceName);\n\n    const stats = {\n      nodeCount: gltfData.nodes?.length || 0,\n      meshCount: gltfData.meshes?.length || 0,\n      materialCount: gltfData.materials?.length || 0,\n      animationCount: gltfData.animations?.length || 0,\n      sceneCount: gltfData.scenes?.length || 0,\n    };\n\n    return {\n      success: true,\n      holoCode,\n      stats,\n    };\n  } catch (error) {\n    const message = error instanceof Error ? error.message : String(error);\n    return {\n      success: false,\n      error: message,\n    };\n  }\n}\n\n// =============================================================================\n// EXPORT / COMPILE HANDLER\n// =============================================================================\n\nexport interface GltfCompileOptions {\n  /** HoloScript composition source code (.holo format) */\n  code: string;\n  /** Output format: 'glb' for binary (default), 'gltf' for JSON + separate buffer */\n  format?: 'glb' | 'gltf';\n  /** Enable Draco mesh compression */\n  dracoCompression?: boolean;\n  /** Enable vertex quantization for smaller file size */\n  quantize?: boolean;\n  /** Remove unused resources */\n  prune?: boolean;\n  /** Deduplicate accessors and materials */\n  dedupe?: boolean;\n  /** Embed textures as base64 (for glTF format) */\n  embedTextures?: boolean;\n  /** Generator string for metadata */\n  generator?: string;\n  /** Copyright string */\n  copyright?: string;\n}\n\nexport interface GltfCompileResult {\n  success: boolean;\n  /** Base64-encoded GLB binary data (when format='glb') */\n  glbBase64?: string;\n  /** glTF JSON document (when format='gltf') */\n  gltfJson?: object;\n  /** Base64-encoded binary buffer (when format='gltf') */\n  bufferBase64?: string;\n  /** Export statistics */\n  stats?: GLTFExportStats;\n  /** Compilation time in milliseconds */\n  compilationTimeMs?: number;\n  error?: string;\n}\n\nexport async function handleCompileToGltf(\n  args: Record<string, unknown>\n): Promise<GltfCompileResult> {\n  const {\n    code,\n    format = 'glb',\n    dracoCompression,\n    quantize,\n    prune,\n    dedupe,\n    embedTextures,\n    generator,\n    copyright,\n  } = args as unknown as GltfCompileOptions;\n\n  if (!code) {\n    throw new Error('code is required: provide HoloScript composition source code (.holo format).');\n  }\n\n  const startTime = Date.now();\n\n  try {\n    // Parse the composition\n    const parseResult = parseHolo(code);\n    if (!parseResult.success || !parseResult.ast) {\n      const errors =\n        parseResult.errors?.map((e: { message: string }) => e.message).join(', ') ||\n        'Unknown parse error';\n      throw new Error(`Failed to parse composition: ${errors}`);\n    }\n\n    const composition = parseResult.ast;\n\n    // Configure the pipeline\n    const pipelineOptions: GLTFPipelineOptions = {\n      format: format || 'glb',\n    };\n    if (dracoCompression !== undefined) pipelineOptions.dracoCompression = dracoCompression;\n    if (quantize !== undefined) pipelineOptions.quantize = quantize;\n    if (prune !== undefined) pipelineOptions.prune = prune;\n    if (dedupe !== undefined) pipelineOptions.dedupe = dedupe;\n    if (embedTextures !== undefined) pipelineOptions.embedTextures = embedTextures;\n    if (generator !== undefined) pipelineOptions.generator = generator;\n    if (copyright !== undefined) pipelineOptions.copyright = copyright;\n\n    const pipeline = new GLTFPipeline(pipelineOptions);\n\n    // Pass empty token to bypass RBAC (skips validation when token is falsy)\n    const result: GLTFExportResult = pipeline.compile(composition, '');\n\n    const compilationTimeMs = Date.now() - startTime;\n\n    if (format === 'glb' && result.binary) {\n      return {\n        success: true,\n        glbBase64: Buffer.from(result.binary).toString('base64'),\n        stats: result.stats,\n        compilationTimeMs,\n      };\n    } else {\n      return {\n        success: true,\n        gltfJson: result.json,\n        bufferBase64: result.buffer ? Buffer.from(result.buffer).toString('base64') : undefined,\n        stats: result.stats,\n        compilationTimeMs,\n      };\n    }\n  } catch (error) {\n    const message = error instanceof Error ? error.message : String(error);\n    return {\n      success: false,\n      error: message,\n      compilationTimeMs: Date.now() - startTime,\n    };\n  }\n}\n\n// =============================================================================\n// HANDLER DISPATCHER\n// =============================================================================\n\nexport async function handleGltfTool(\n  name: string,\n  args: Record<string, unknown>\n): Promise<unknown | null> {\n  switch (name) {\n    case 'import_gltf':\n      return handleImportGltf(args);\n    case 'compile_to_gltf':\n      return handleCompileToGltf(args);\n    default:\n      return null;\n  }\n}\n\n// =============================================================================\n// MCP TOOL DEFINITIONS\n// =============================================================================\n\nexport const gltfImportTools: Tool[] = [\n  {\n    name: 'import_gltf',\n    description:\n      'Import a glTF 2.0 or GLB file and convert it to HoloScript .holo composition code. ' +\n      'Supports three input modes: file path, inline glTF JSON, or base64-encoded GLB binary. ' +\n      'Handles node hierarchy, PBR materials (baseColor, metalness, roughness, emissive), ' +\n      'animations, physics extensions (KHR_rigid_bodies, MSFT_physics), and automatic ' +\n      'HoloScript trait inference from node names, extensions, and extras. ' +\n      'Returns generated .holo code with import statistics.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        filePath: {\n          type: 'string',\n          description:\n            'Absolute path to a .gltf or .glb file on disk. ' +\n            'Use this for importing files from the local filesystem.',\n        },\n        gltfJson: {\n          type: 'string',\n          description:\n            'Inline glTF JSON document as a string. ' +\n            'Use this when you have the glTF JSON data directly without a file.',\n        },\n        glbBase64: {\n          type: 'string',\n          description:\n            'Base64-encoded GLB binary data. ' +\n            'Use this when you have GLB binary data (e.g., from an API or download).',\n        },\n        sourceName: {\n          type: 'string',\n          description:\n            'Source file name hint used in generated comments and geometry references. ' +\n            'Defaults to \"imported.gltf\" or \"imported.glb\" based on input type.',\n        },\n      },\n    },\n  },\n  {\n    name: 'compile_to_gltf',\n    description:\n      'Compile HoloScript composition code to glTF 2.0 / GLB binary format. ' +\n      'Uses the full GLTFPipeline with PBR material support, mesh primitives ' +\n      '(cube, sphere, cylinder, cone, plane), skeletal animation, LOD generation, ' +\n      'normal smoothing, and texture embedding. Returns base64-encoded GLB binary ' +\n      'or glTF JSON + buffer depending on the format option. ' +\n      'Includes comprehensive export statistics (node/mesh/material/texture counts, ' +\n      'vertex/triangle totals, file size).',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        code: {\n          type: 'string',\n          description: 'HoloScript composition source code (.holo format)',\n        },\n        format: {\n          type: 'string',\n          enum: ['glb', 'gltf'],\n          description:\n            'Output format. \"glb\" (default) for single binary file, ' +\n            '\"gltf\" for JSON document with separate binary buffer.',\n        },\n        dracoCompression: {\n          type: 'boolean',\n          description: 'Enable Draco mesh compression for smaller file size (default: false)',\n        },\n        quantize: {\n          type: 'boolean',\n          description: 'Enable vertex quantization for smaller file size (default: true)',\n        },\n        prune: {\n          type: 'boolean',\n          description: 'Remove unused resources from the output (default: true)',\n        },\n        dedupe: {\n          type: 'boolean',\n          description: 'Deduplicate accessors and materials (default: true)',\n        },\n        embedTextures: {\n          type: 'boolean',\n          description: 'Embed textures as base64 in glTF format (default: true)',\n        },\n        generator: {\n          type: 'string',\n          description:\n            'Generator string for glTF metadata (default: \"HoloScript GLTFPipeline v1.0.0\")',\n        },\n        copyright: {\n          type: 'string',\n          description: 'Copyright string for glTF metadata',\n        },\n      },\n      required: ['code'],\n    },\n  },\n];\n","/**\n * HoloScript MCP Generate-Mesh Tools\n *\n * Exposes the native, license-free SDF -> editable mesh path as an MCP tool.\n *\n * `holo_generate_mesh` (mode: \"sdf\"):\n *   author an SDF/CSG tree -> marching cubes -> watertight, welded, outward-wound\n *   triangle mesh (the same tested @holoscript/engine `marchingCubes` the studio\n *   manufacturing lane uses) -> optional STL (ascii or base64 binary).\n *\n * Mode \"prompt\" (text/image -> mesh via Meshy/Tripo) is NOT enabled here: that\n * bridge lives in @holoscript/cli (`textTo3DToHolo`), which mcp-server does not\n * depend on. Wiring it requires adding the cli dependency (lockfile change) and\n * is deliberately deferred to keep this surface dependency-safe (D.096 plan:\n * ship the native SDF path now; the bridge + GLB output are scoped follow-ups).\n *\n * @version 1.0.0\n * @package @holoscript/mcp-server\n */\n\nimport type { Tool } from '@modelcontextprotocol/sdk/types.js';\nimport { Simulation } from '@holoscript/engine';\n\ntype Vec3 = [number, number, number];\n\ninterface GenerateMeshArgs {\n  mode?: 'sdf' | 'prompt';\n  sdf?: unknown;\n  resolution?: number[];\n  bounds?: { min?: number[]; max?: number[] };\n  isoLevel?: number;\n  scaleFactor?: number;\n  output?: 'stats' | 'stl-ascii' | 'stl-binary';\n  prompt?: string;\n  provider?: string;\n}\n\nfunction toVec3(a: number[] | undefined, fallback: Vec3): Vec3 {\n  return a && a.length === 3 ? [a[0], a[1], a[2]] : fallback;\n}\n\nasync function handleGenerateMesh(args: GenerateMeshArgs): Promise<unknown> {\n  const mode = args.mode ?? 'sdf';\n\n  if (mode === 'prompt') {\n    return {\n      success: false,\n      mode: 'prompt',\n      error:\n        'Prompt mode (text/image -> mesh via Meshy/Tripo) is not enabled in the MCP server: it lives in ' +\n        '@holoscript/cli (textTo3DToHolo), which mcp-server does not depend on. Use the CLI importer directly, ' +\n        'or request the @holoscript/cli dependency be added. SDF mode (authored/CSG -> editable mesh) is ' +\n        'available now via mode:\"sdf\".',\n    };\n  }\n\n  if (\n    !args.sdf ||\n    typeof args.sdf !== 'object' ||\n    typeof (args.sdf as { type?: unknown }).type !== 'string'\n  ) {\n    return {\n      success: false,\n      error:\n        'mode:\"sdf\" requires an `sdf` SDFNode object, e.g. { type:\"primitive\", primitive:\"sphere\", ' +\n        'params:{ radius:1 } } or a CSG node { type:\"csg\", operation:\"smooth_union\", smoothness:0.2, ' +\n        'children:[ ... ] }.',\n    };\n  }\n\n  const opts: Simulation.MarchingCubesOptions = {\n    resolution: toVec3(args.resolution, [48, 48, 48]),\n    bounds: {\n      min: toVec3(args.bounds?.min, [-1, -1, -1]),\n      max: toVec3(args.bounds?.max, [1, 1, 1]),\n    },\n    isoLevel: typeof args.isoLevel === 'number' ? args.isoLevel : 0,\n    scaleFactor: typeof args.scaleFactor === 'number' ? args.scaleFactor : 1,\n  };\n\n  let mesh: Simulation.SurfaceMesh;\n  try {\n    mesh = Simulation.marchingCubes(args.sdf as Simulation.SDFNode, opts);\n  } catch (e) {\n    return {\n      success: false,\n      error: 'marchingCubes failed: ' + (e instanceof Error ? e.message : String(e)),\n    };\n  }\n\n  const vertexCount = mesh.vertices.length / 3;\n  const triangleCount = mesh.triangles.length / 3;\n\n  const result: Record<string, unknown> = {\n    success: true,\n    mode: 'sdf',\n    vertexCount,\n    triangleCount,\n    bounds: opts.bounds,\n    resolution: opts.resolution,\n    note: 'Watertight, welded, outward-wound triangle mesh from native marching cubes (no license, no trained model).',\n  };\n\n  const output = args.output ?? 'stats';\n  if (output === 'stl-ascii') {\n    result.stlAscii = Simulation.exportSTLAscii(mesh, {});\n  } else if (output === 'stl-binary') {\n    const buf = Simulation.exportSTLBinary(mesh, {});\n    result.stlBinaryBase64 = Buffer.from(new Uint8Array(buf)).toString('base64');\n  }\n\n  return result;\n}\n\nexport const generateMeshTools: Tool[] = [\n  {\n    name: 'holo_generate_mesh',\n    description:\n      'Generate an editable, watertight triangle mesh from an authored SDF/CSG tree via native marching cubes ' +\n      '(the license-free, no-trained-model path). Returns vertex/triangle counts and optionally an STL ' +\n      '(ascii or base64 binary). mode:\"sdf\" is available now; mode:\"prompt\" (text/image -> mesh via Meshy/Tripo) ' +\n      'is not yet enabled in the MCP server (that bridge lives in @holoscript/cli).',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        mode: {\n          type: 'string',\n          enum: ['sdf', 'prompt'],\n          description:\n            'sdf = authored SDF/CSG via marching cubes (default, available now); prompt = text/image (not yet enabled here).',\n        },\n        sdf: {\n          type: 'object',\n          description:\n            'SDFNode tree (mode=sdf). Primitive: { type:\"primitive\", primitive:\"sphere\"|\"box\"|..., params:{...}, ' +\n            'translate?/rotate?/scale? }. CSG: { type:\"csg\", operation:\"union\"|\"subtract\"|\"smooth_union\"|..., ' +\n            'smoothness?, children:[ ... ] }.',\n        },\n        resolution: {\n          type: 'array',\n          items: { type: 'number' },\n          description: '[nx,ny,nz] sample grid (default [48,48,48], >=2 per axis). Higher = finer at O(N^3) cost.',\n        },\n        bounds: {\n          type: 'object',\n          description: '{ min:[x,y,z], max:[x,y,z] } world AABB to sample over (default +/-1).',\n          properties: {\n            min: { type: 'array', items: { type: 'number' } },\n            max: { type: 'array', items: { type: 'number' } },\n          },\n        },\n        isoLevel: { type: 'number', description: 'Iso-surface level (default 0 = zero level-set).' },\n        scaleFactor: { type: 'number', description: 'Uniform output scale applied after meshing (default 1).' },\n        output: {\n          type: 'string',\n          enum: ['stats', 'stl-ascii', 'stl-binary'],\n          description: 'stats (counts only, default) or include an STL export.',\n        },\n        prompt: { type: 'string', description: 'Text description (mode=prompt; not yet enabled here).' },\n        provider: {\n          type: 'string',\n          enum: ['meshy', 'tripo'],\n          description: 'Prompt-mode provider (not yet enabled here).',\n        },\n      },\n      required: ['mode'],\n    },\n  },\n];\n\nexport async function handleGenerateMeshTool(\n  name: string,\n  args: Record<string, unknown>\n): Promise<unknown | null> {\n  switch (name) {\n    case 'holo_generate_mesh':\n      return handleGenerateMesh(args as GenerateMeshArgs);\n    default:\n      return null;\n  }\n}\n","/**\n * edit-holo-tools.ts — AST-directed source-level editor for HoloScript\n *\n * Enables AI agents to surgically edit .holo/.hsplus/.hs files without\n * rewriting the entire file. Uses the parser for node location only,\n * then applies text-level edits within the located block.\n *\n * Operations:\n *   - set_property   — upsert key: value in an object block\n *   - remove_property — delete a property line from an object block\n *   - add_trait       — append @trait to the object declaration line\n *   - remove_trait    — strip @trait from the declaration line\n *   - rename          — change the object's quoted name\n *\n * Design: source-level editing preserves formatting, comments, and\n * properties that the lossy convertToHolo() codegen would strip.\n */\n\nimport type { Tool } from '@modelcontextprotocol/sdk/types.js';\n\n// ── Types ──────────────────────────────────────────────────────────────────\n\nexport type EditOperation =\n  | { op: 'set_property'; key: string; value: string }\n  | { op: 'remove_property'; key: string }\n  | { op: 'add_trait'; trait: string }\n  | { op: 'remove_trait'; trait: string }\n  | { op: 'rename'; newName: string };\n\nexport interface EditHoloArgs {\n  code: string;\n  target: string; // Object name/ID to edit\n  edits: EditOperation[];\n}\n\nexport interface EditHoloResult {\n  success: boolean;\n  code: string;\n  diff: string[];\n  summary: string;\n  error?: string;\n}\n\n// ── Tool Definition ────────────────────────────────────────────────────────\n\nexport const editHoloTools: Tool[] = [\n  {\n    name: 'edit_holo',\n    description:\n      'Surgically edit a specific object in HoloScript code without rewriting the entire file. ' +\n      'Preserves formatting, comments, and all other objects. Operations: ' +\n      'set_property (upsert a property), remove_property, add_trait, remove_trait, rename. ' +\n      'Multiple operations can be applied in a single call.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        code: {\n          type: 'string',\n          description: 'The full HoloScript source code containing the object to edit.',\n        },\n        target: {\n          type: 'string',\n          description:\n            'Name or ID of the object to edit (e.g., \"Player\", \"floor\", \"main_light\"). ' +\n            'Matches the quoted name in: object \"Name\" { ... }',\n        },\n        edits: {\n          type: 'array',\n          description: 'List of edit operations to apply to the target object.',\n          items: {\n            type: 'object',\n            properties: {\n              op: {\n                type: 'string',\n                enum: ['set_property', 'remove_property', 'add_trait', 'remove_trait', 'rename'],\n                description: 'The edit operation type.',\n              },\n              key: {\n                type: 'string',\n                description: 'Property key (for set_property, remove_property).',\n              },\n              value: {\n                type: 'string',\n                description:\n                  'Property value as a string (for set_property). ' +\n                  'Arrays: \"[1, 2, 3]\", numbers: \"42\", strings: \\'\"hello\"\\'.',\n              },\n              trait: {\n                type: 'string',\n                description: 'Trait name with or without @ prefix (for add_trait, remove_trait).',\n              },\n              newName: {\n                type: 'string',\n                description: 'New name for the object (for rename).',\n              },\n            },\n            required: ['op'],\n          },\n        },\n      },\n      required: ['code', 'target', 'edits'],\n    },\n  },\n];\n\n// ── Handler ────────────────────────────────────────────────────────────────\n\nexport async function handleEditHoloTool(\n  name: string,\n  args: Record<string, unknown>\n): Promise<EditHoloResult | null> {\n  if (name !== 'edit_holo') return null;\n  return runEditHolo(args as unknown as EditHoloArgs);\n}\n\n// ── Core Engine ────────────────────────────────────────────────────────────\n\n/**\n * Find the object block in source code by name.\n * Returns { startLine, endLine, declarationLine } (0-indexed).\n *\n * Handles:\n *   .holo:   object \"Name\" @trait { ... }\n *   .hsplus: cube Name { ... }  or  object Name { ... }\n */\nfunction findObjectBlock(\n  lines: string[],\n  targetName: string\n): { startLine: number; endLine: number; declarationLine: number } | null {\n  // Pattern 1: object \"Name\" ... {  (holo format, quoted name)\n  const holoPattern = new RegExp(\n    `^(\\\\s*)(?:object|cube|sphere|model|plane|cylinder|cone|light|camera|group)\\\\s+\"${escapeRegex(targetName)}\"`,\n    'i'\n  );\n  // Pattern 2: type Name {  (hsplus format, unquoted name)\n  const hsplusPattern = new RegExp(\n    `^(\\\\s*)(?:object|cube|sphere|model|plane|cylinder|cone|light|camera|group)\\\\s+${escapeRegex(targetName)}\\\\s*(?:@|\\\\{)`,\n    'i'\n  );\n\n  for (let i = 0; i < lines.length; i++) {\n    const line = lines[i];\n    if (holoPattern.test(line) || hsplusPattern.test(line)) {\n      // Found the declaration line — now find the matching closing brace\n      const _indent = line.match(/^(\\s*)/)?.[1] ?? '';\n      let braceDepth = 0;\n      let foundOpen = false;\n\n      for (let j = i; j < lines.length; j++) {\n        const l = lines[j];\n        for (const ch of l) {\n          if (ch === '{') {\n            braceDepth++;\n            foundOpen = true;\n          }\n          if (ch === '}') {\n            braceDepth--;\n          }\n        }\n        if (foundOpen && braceDepth === 0) {\n          return { startLine: i, endLine: j, declarationLine: i };\n        }\n      }\n\n      // Unclosed block — return to end of file\n      return { startLine: i, endLine: lines.length - 1, declarationLine: i };\n    }\n  }\n\n  return null;\n}\n\nfunction escapeRegex(str: string): string {\n  return str.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\n\n/**\n * Detect indentation used inside the block body.\n */\nfunction detectBlockIndent(lines: string[], startLine: number, endLine: number): string {\n  for (let i = startLine + 1; i < endLine; i++) {\n    const line = lines[i];\n    const match = line.match(/^(\\s+)\\S/);\n    if (match) return match[1];\n  }\n  return '    '; // default 4 spaces\n}\n\nfunction runEditHolo(args: EditHoloArgs): EditHoloResult {\n  const { code, target, edits } = args;\n\n  if (!code || !target || !edits || edits.length === 0) {\n    return {\n      success: false,\n      code: code ?? '',\n      diff: [],\n      summary: 'Missing required arguments: code, target, and edits.',\n      error: 'Missing code, target, or edits.',\n    };\n  }\n\n  const lines = code.split('\\n');\n  const block = findObjectBlock(lines, target);\n\n  if (!block) {\n    return {\n      success: false,\n      code,\n      diff: [],\n      summary: `Object \"${target}\" not found in source code.`,\n      error: `Object \"${target}\" not found. Available objects can be discovered with parse_hs or parse_holo.`,\n    };\n  }\n\n  const diffLog: string[] = [];\n  let editedLines = [...lines];\n\n  // Apply edits sequentially — each edit may shift line numbers\n  for (const edit of edits) {\n    const currentBlock = findObjectBlock(editedLines, target);\n    if (!currentBlock) {\n      diffLog.push(`⚠ Lost track of \"${target}\" after previous edit`);\n      break;\n    }\n\n    switch (edit.op) {\n      case 'set_property': {\n        if (!edit.key) {\n          diffLog.push('⚠ set_property: key is required');\n          break;\n        }\n        const result = applySetProperty(editedLines, currentBlock, edit.key, edit.value ?? '');\n        editedLines = result.lines;\n        diffLog.push(result.diff);\n        break;\n      }\n\n      case 'remove_property': {\n        if (!edit.key) {\n          diffLog.push('⚠ remove_property: key is required');\n          break;\n        }\n        const result = applyRemoveProperty(editedLines, currentBlock, edit.key);\n        editedLines = result.lines;\n        diffLog.push(result.diff);\n        break;\n      }\n\n      case 'add_trait': {\n        if (!edit.trait) {\n          diffLog.push('⚠ add_trait: trait is required');\n          break;\n        }\n        const result = applyAddTrait(editedLines, currentBlock, edit.trait);\n        editedLines = result.lines;\n        diffLog.push(result.diff);\n        break;\n      }\n\n      case 'remove_trait': {\n        if (!edit.trait) {\n          diffLog.push('⚠ remove_trait: trait is required');\n          break;\n        }\n        const result = applyRemoveTrait(editedLines, currentBlock, edit.trait);\n        editedLines = result.lines;\n        diffLog.push(result.diff);\n        break;\n      }\n\n      case 'rename': {\n        if (!edit.newName) {\n          diffLog.push('⚠ rename: newName is required');\n          break;\n        }\n        const result = applyRename(editedLines, currentBlock, target, edit.newName);\n        editedLines = result.lines;\n        diffLog.push(result.diff);\n        break;\n      }\n\n      default:\n        diffLog.push(`⚠ Unknown operation: ${(edit as unknown as { op: string }).op}`);\n    }\n  }\n\n  const newCode = editedLines.join('\\n');\n  const changed = newCode !== code;\n\n  return {\n    success: true,\n    code: newCode,\n    diff: diffLog,\n    summary: changed\n      ? `Applied ${edits.length} edit(s) to \"${target}\": ${diffLog.filter((d) => !d.startsWith('⚠')).join('; ')}`\n      : `No changes made to \"${target}\".`,\n  };\n}\n\n// ── Edit Operations ────────────────────────────────────────────────────────\n\ninterface EditResult {\n  lines: string[];\n  diff: string;\n}\n\nfunction applySetProperty(\n  lines: string[],\n  block: { startLine: number; endLine: number },\n  key: string,\n  value: string\n): EditResult {\n  const indent = detectBlockIndent(lines, block.startLine, block.endLine);\n  const propPattern = new RegExp(`^(\\\\s*)${escapeRegex(key)}\\\\s*:`);\n\n  // Look for existing property\n  for (let i = block.startLine + 1; i <= block.endLine; i++) {\n    if (propPattern.test(lines[i])) {\n      const oldLine = lines[i];\n      const match = oldLine.match(/^(\\s*)/);\n      const existingIndent = match ? match[1] : indent;\n      lines[i] = `${existingIndent}${key}: ${value}`;\n      return { lines, diff: `set ${key}: ${value} (was: ${oldLine.trim()})` };\n    }\n  }\n\n  // Property not found — insert before closing brace\n  const newLine = `${indent}${key}: ${value}`;\n  lines.splice(block.endLine, 0, newLine);\n  return { lines, diff: `+${key}: ${value}` };\n}\n\nfunction applyRemoveProperty(\n  lines: string[],\n  block: { startLine: number; endLine: number },\n  key: string\n): EditResult {\n  const propPattern = new RegExp(`^\\\\s*${escapeRegex(key)}\\\\s*:`);\n\n  for (let i = block.startLine + 1; i <= block.endLine; i++) {\n    if (propPattern.test(lines[i])) {\n      const removed = lines[i].trim();\n      lines.splice(i, 1);\n      return { lines, diff: `-${removed}` };\n    }\n  }\n\n  return { lines, diff: `⚠ property \"${key}\" not found` };\n}\n\nfunction applyAddTrait(\n  lines: string[],\n  block: { startLine: number; endLine: number },\n  trait: string\n): EditResult {\n  const normalizedTrait = trait.startsWith('@') ? trait : `@${trait}`;\n  const declLine = lines[block.startLine];\n\n  // Check if trait already exists\n  if (declLine.includes(normalizedTrait)) {\n    return { lines, diff: `⚠ trait ${normalizedTrait} already present` };\n  }\n\n  // Insert trait before the opening brace\n  const braceIdx = declLine.lastIndexOf('{');\n  if (braceIdx >= 0) {\n    lines[block.startLine] =\n      declLine.slice(0, braceIdx).trimEnd() + ` ${normalizedTrait} ` + declLine.slice(braceIdx);\n  } else {\n    // No brace on declaration line — append at end\n    lines[block.startLine] = declLine + ` ${normalizedTrait}`;\n  }\n\n  return { lines, diff: `+trait ${normalizedTrait}` };\n}\n\nfunction applyRemoveTrait(\n  lines: string[],\n  block: { startLine: number; endLine: number },\n  trait: string\n): EditResult {\n  const normalizedTrait = trait.startsWith('@') ? trait : `@${trait}`;\n  const declLine = lines[block.startLine];\n\n  if (!declLine.includes(normalizedTrait)) {\n    return { lines, diff: `⚠ trait ${normalizedTrait} not found` };\n  }\n\n  // Remove the trait (with potential surrounding whitespace)\n  lines[block.startLine] = declLine\n    .replace(new RegExp(`\\\\s*${escapeRegex(normalizedTrait)}\\\\s*`, 'g'), ' ')\n    .replace(/\\s+\\{/, ' {')\n    .replace(/\\s{2,}/g, ' ');\n\n  return { lines, diff: `-trait ${normalizedTrait}` };\n}\n\nfunction applyRename(\n  lines: string[],\n  block: { startLine: number; endLine: number },\n  oldName: string,\n  newName: string\n): EditResult {\n  const declLine = lines[block.startLine];\n\n  // Replace quoted name: \"oldName\" → \"newName\"\n  const quotedOld = `\"${oldName}\"`;\n  const quotedNew = `\"${newName}\"`;\n  if (declLine.includes(quotedOld)) {\n    lines[block.startLine] = declLine.replace(quotedOld, quotedNew);\n    return { lines, diff: `rename \"${oldName}\" → \"${newName}\"` };\n  }\n\n  // Replace unquoted name (hsplus): oldName → newName\n  const unquotedPattern = new RegExp(\n    `(\\\\b(?:object|cube|sphere|model)\\\\s+)${escapeRegex(oldName)}(\\\\s)`,\n    'i'\n  );\n  if (unquotedPattern.test(declLine)) {\n    lines[block.startLine] = declLine.replace(unquotedPattern, `$1${newName}$2`);\n    return { lines, diff: `rename ${oldName} → ${newName}` };\n  }\n\n  return { lines, diff: `⚠ could not locate name \"${oldName}\" in declaration` };\n}\n","/**\n * MCP Wisdom/Gotcha Tools for HoloScript\n *\n * Provides AI agents and IDE integrations with queryable access to\n * @wisdom and @gotcha meta-traits declared in compositions.\n *\n * Tools:\n * - holo_query_wisdom:  Search wisdom patterns by trait, category, or keyword\n * - holo_list_gotchas:  List gotchas filtered by severity or trigger event\n * - holo_check_gotchas: Validate a composition for critical gotcha violations\n *\n * @see proposals/WISDOM_AND_GOTCHA_TRAITS_v1.md\n */\n\nimport { Tool } from '@modelcontextprotocol/sdk/types.js';\nimport * as fs from 'fs';\nimport * as path from 'path';\n\n// =============================================================================\n// TOOL DEFINITIONS\n// =============================================================================\n\nexport const wisdomGotchaTools: Tool[] = [\n  {\n    name: 'holo_query_wisdom',\n    description:\n      'Query @wisdom meta-traits from HoloScript compositions. ' +\n      'Returns battle-tested insights with provenance, applicable traits, and examples. ' +\n      'Use to learn best practices before making changes.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        rootDir: {\n          type: 'string',\n          description: 'Root directory of the HoloScript project',\n        },\n        trait: {\n          type: 'string',\n          description: 'Filter wisdoms that apply to a specific trait (e.g. \"credit\", \"networked\")',\n        },\n        keyword: {\n          type: 'string',\n          description: 'Search keyword to match against wisdom descriptions',\n        },\n        compositionFile: {\n          type: 'string',\n          description:\n            'Specific .holo or .hsplus file to scan. If omitted, scans all compositions.',\n        },\n      },\n      required: ['rootDir'],\n    },\n  },\n  {\n    name: 'holo_list_gotchas',\n    description:\n      'List @gotcha meta-traits from HoloScript compositions. ' +\n      'Returns known failure modes with severity levels, mitigation strategies, and trigger events. ' +\n      'Use before making changes to understand failure risks.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        rootDir: {\n          type: 'string',\n          description: 'Root directory of the HoloScript project',\n        },\n        severity: {\n          type: 'string',\n          enum: ['info', 'warning', 'critical'],\n          description: 'Filter by severity level',\n        },\n        triggerEvent: {\n          type: 'string',\n          description: 'Filter by trigger event (e.g. \"hot_reload\", \"absorb\", \"onClick\")',\n        },\n        compositionFile: {\n          type: 'string',\n          description:\n            'Specific .holo or .hsplus file to scan. If omitted, scans all compositions.',\n        },\n      },\n      required: ['rootDir'],\n    },\n  },\n  {\n    name: 'holo_check_gotchas',\n    description:\n      'Validate a composition for critical @gotcha violations. ' +\n      'Returns pass/fail with details on which gotchas would trigger. ' +\n      'Use as a pre-commit check or CI gate with --enforce-gotchas semantics.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        rootDir: {\n          type: 'string',\n          description: 'Root directory of the HoloScript project',\n        },\n        compositionFile: {\n          type: 'string',\n          description: 'The .holo or .hsplus file to validate (relative to rootDir)',\n        },\n        failOnCritical: {\n          type: 'boolean',\n          description: 'If true, returns error status for critical gotchas. Defaults to true.',\n        },\n      },\n      required: ['rootDir', 'compositionFile'],\n    },\n  },\n];\n\n// =============================================================================\n// TYPES\n// =============================================================================\n\ninterface WisdomEntry {\n  description: string;\n  source: string;\n  applies_to: string[];\n  examples: string[];\n  file: string;\n  objectName?: string;\n}\n\ninterface GotchaEntry {\n  warning: string;\n  severity: 'info' | 'warning' | 'critical';\n  mitigation: string;\n  triggers_on: string[];\n  file: string;\n  objectName?: string;\n}\n\n// =============================================================================\n// EXTRACTION — Parse .holo/.hsplus files for @wisdom/@gotcha traits\n// =============================================================================\n\nfunction findCompositionFiles(rootDir: string): string[] {\n  const files: string[] = [];\n  const dirs = ['compositions', 'examples', 'scenes', '.'];\n  for (const dir of dirs) {\n    const full = path.join(rootDir, dir);\n    if (!fs.existsSync(full)) continue;\n    try {\n      const entries = fs.readdirSync(full);\n      for (const entry of entries) {\n        if (entry.endsWith('.holo') || entry.endsWith('.hsplus')) {\n          files.push(path.join(full, entry));\n        }\n      }\n    } catch {\n      // Skip inaccessible directories\n    }\n  }\n  return files;\n}\n\nfunction extractWisdomsFromSource(source: string, filePath: string): WisdomEntry[] {\n  const wisdoms: WisdomEntry[] = [];\n  // Match @wisdom { ... } blocks (simplified regex extraction)\n  const wisdomRe = /@wisdom\\s*\\{([^}]+)\\}/g;\n  let match: RegExpExecArray | null;\n  while ((match = wisdomRe.exec(source)) !== null) {\n    const block = match[1];\n    const description = extractProp(block, 'description') || '';\n    const source_ = extractProp(block, 'source') || 'community';\n    const appliesTo = extractArrayProp(block, 'applies_to');\n    const examples = extractArrayProp(block, 'examples');\n\n    // Try to find enclosing object name (narrow reverse-scan, not full HS parse)\n    const beforeBlock = source.slice(0, match.index);\n    // eslint-disable-next-line holoscript/no-regex-hs-parsing\n    const objectMatch = beforeBlock.match(/object\\s+\"([^\"]+)\"\\s*\\{[^}]*$/);\n\n    if (description) {\n      wisdoms.push({\n        description,\n        source: source_,\n        applies_to: appliesTo,\n        examples,\n        file: filePath,\n        objectName: objectMatch?.[1],\n      });\n    }\n  }\n  return wisdoms;\n}\n\nfunction extractGotchasFromSource(source: string, filePath: string): GotchaEntry[] {\n  const gotchas: GotchaEntry[] = [];\n  const gotchaRe = /@gotcha\\s*\\{([^}]+)\\}/g;\n  let match: RegExpExecArray | null;\n  while ((match = gotchaRe.exec(source)) !== null) {\n    const block = match[1];\n    const warning = extractProp(block, 'warning') || '';\n    const severity = (extractProp(block, 'severity') || 'warning') as GotchaEntry['severity'];\n    const mitigation = extractProp(block, 'mitigation') || '';\n    const triggersOn = extractArrayProp(block, 'triggers_on');\n\n    const beforeBlock = source.slice(0, match.index);\n    // eslint-disable-next-line holoscript/no-regex-hs-parsing\n    const objectMatch = beforeBlock.match(/object\\s+\"([^\"]+)\"\\s*\\{[^}]*$/);\n\n    if (warning) {\n      gotchas.push({\n        warning,\n        severity,\n        mitigation,\n        triggers_on: triggersOn,\n        file: filePath,\n        objectName: objectMatch?.[1],\n      });\n    }\n  }\n  return gotchas;\n}\n\nfunction extractProp(block: string, name: string): string | null {\n  const re = new RegExp(`${name}:\\\\s*\"([^\"]*)\"`, 'i');\n  const match = block.match(re);\n  return match?.[1] ?? null;\n}\n\nfunction extractArrayProp(block: string, name: string): string[] {\n  const re = new RegExp(`${name}:\\\\s*\\\\[([^\\\\]]*)]`, 'i');\n  const match = block.match(re);\n  if (!match) return [];\n  return match[1]\n    .split(',')\n    .map((s) => s.trim().replace(/^[\"@]|\"$/g, ''))\n    .filter(Boolean);\n}\n\n// =============================================================================\n// HANDLER\n// =============================================================================\n\nexport async function handleWisdomGotchaTool(\n  name: string,\n  args: Record<string, unknown>\n): Promise<unknown | null> {\n  switch (name) {\n    case 'holo_query_wisdom':\n      return handleQueryWisdom(args);\n    case 'holo_list_gotchas':\n      return handleListGotchas(args);\n    case 'holo_check_gotchas':\n      return handleCheckGotchas(args);\n    default:\n      return null;\n  }\n}\n\n// ── Query Wisdom ──────────────────────────────────────────────────────────────\n\nasync function handleQueryWisdom(args: Record<string, unknown>): Promise<unknown> {\n  const rootDir = args.rootDir as string;\n  const traitFilter = args.trait as string | undefined;\n  const keyword = args.keyword as string | undefined;\n  const compositionFile = args.compositionFile as string | undefined;\n\n  if (!rootDir || !fs.existsSync(rootDir)) {\n    return { error: 'rootDir does not exist' };\n  }\n\n  const files = compositionFile\n    ? [path.resolve(rootDir, compositionFile)]\n    : findCompositionFiles(rootDir);\n\n  let allWisdoms: WisdomEntry[] = [];\n  for (const file of files) {\n    if (!fs.existsSync(file)) continue;\n    try {\n      const source = fs.readFileSync(file, 'utf-8');\n      allWisdoms.push(...extractWisdomsFromSource(source, path.relative(rootDir, file)));\n    } catch {\n      // Skip unreadable files\n    }\n  }\n\n  // Apply filters\n  if (traitFilter) {\n    const normalized = traitFilter.replace(/^@/, '');\n    allWisdoms = allWisdoms.filter((w) =>\n      w.applies_to.some((t) => t.replace(/^@/, '') === normalized)\n    );\n  }\n  if (keyword) {\n    const lower = keyword.toLowerCase();\n    allWisdoms = allWisdoms.filter((w) => w.description.toLowerCase().includes(lower));\n  }\n\n  return {\n    count: allWisdoms.length,\n    wisdoms: allWisdoms,\n    filesScanned: files.length,\n  };\n}\n\n// ── List Gotchas ──────────────────────────────────────────────────────────────\n\nasync function handleListGotchas(args: Record<string, unknown>): Promise<unknown> {\n  const rootDir = args.rootDir as string;\n  const severityFilter = args.severity as string | undefined;\n  const triggerFilter = args.triggerEvent as string | undefined;\n  const compositionFile = args.compositionFile as string | undefined;\n\n  if (!rootDir || !fs.existsSync(rootDir)) {\n    return { error: 'rootDir does not exist' };\n  }\n\n  const files = compositionFile\n    ? [path.resolve(rootDir, compositionFile)]\n    : findCompositionFiles(rootDir);\n\n  let allGotchas: GotchaEntry[] = [];\n  for (const file of files) {\n    if (!fs.existsSync(file)) continue;\n    try {\n      const source = fs.readFileSync(file, 'utf-8');\n      allGotchas.push(...extractGotchasFromSource(source, path.relative(rootDir, file)));\n    } catch {\n      // Skip unreadable files\n    }\n  }\n\n  if (severityFilter) {\n    allGotchas = allGotchas.filter((g) => g.severity === severityFilter);\n  }\n  if (triggerFilter) {\n    allGotchas = allGotchas.filter((g) => g.triggers_on.includes(triggerFilter));\n  }\n\n  return {\n    count: allGotchas.length,\n    gotchas: allGotchas,\n    filesScanned: files.length,\n    criticalCount: allGotchas.filter((g) => g.severity === 'critical').length,\n  };\n}\n\n// ── Check Gotchas ─────────────────────────────────────────────────────────────\n\nasync function handleCheckGotchas(args: Record<string, unknown>): Promise<unknown> {\n  const rootDir = args.rootDir as string;\n  const compositionFile = args.compositionFile as string;\n  const failOnCritical = (args.failOnCritical as boolean) ?? true;\n\n  if (!rootDir || !fs.existsSync(rootDir)) {\n    return { error: 'rootDir does not exist' };\n  }\n\n  const filePath = path.resolve(rootDir, compositionFile);\n  if (!fs.existsSync(filePath)) {\n    return { error: `Composition file not found: ${compositionFile}` };\n  }\n\n  const source = fs.readFileSync(filePath, 'utf-8');\n  const gotchas = extractGotchasFromSource(source, compositionFile);\n  const critical = gotchas.filter((g) => g.severity === 'critical');\n  const warnings = gotchas.filter((g) => g.severity === 'warning');\n  const infos = gotchas.filter((g) => g.severity === 'info');\n\n  const passed = !failOnCritical || critical.length === 0;\n\n  return {\n    file: compositionFile,\n    passed,\n    summary: {\n      total: gotchas.length,\n      critical: critical.length,\n      warning: warnings.length,\n      info: infos.length,\n    },\n    criticalGotchas: critical.map((g) => ({\n      warning: g.warning,\n      mitigation: g.mitigation,\n      triggers_on: g.triggers_on,\n      object: g.objectName,\n    })),\n    warningGotchas: warnings.map((g) => ({\n      warning: g.warning,\n      mitigation: g.mitigation,\n    })),\n  };\n}\n","/**\n * Receipt Capability Query Tools for HoloScript MCP Server\n *\n * Provides AI agents and IDE integrations with queryable access to the\n * receipt capability registry — the routing backbone that maps capability\n * keywords to receipt types, validators, and exports.\n *\n * Tools:\n * - holo_query_receipts:  Query receipt capabilities by keyword or subject\n * - holo_list_receipt_capabilities: List all registered receipt capabilities\n *\n * Unblocks: Papers-as-Service receipt verification (D.032),\n * HoloShell cockpit composition queries, ProviderExportCustodyReceipt flows.\n *\n * Created: task_1779157196014_yx3r ([idea-run-13] Add receipt capability router MCP tool)\n */\n\nimport { Tool } from '@modelcontextprotocol/sdk/types.js';\nimport {\n  RECEIPT_CAPABILITY_REGISTRY,\n  queryReceiptCapabilities,\n  listReceiptCapabilities,\n  listReceiptSubjects,\n  receiptCapabilityCount,\n  getReceiptCapability,\n  type ReceiptCapabilityEntry,\n} from '@holoscript/framework';\n\n// =============================================================================\n// TOOL DEFINITIONS\n// =============================================================================\n\nexport const receiptQueryTools: Tool[] = [\n  {\n    name: 'holo_query_receipts',\n    description:\n      'Query HoloScript receipt capabilities by keyword or subject. ' +\n      'Returns matching receipt types with their module, validator, and clone exports. ' +\n      'Use this to discover which receipt types cover a capability like \"hardware\", ' +\n      '\"browser\", \"account-export\", \"device-safety\", or \"readiness\".',\n    inputSchema: {\n      type: 'object' as const,\n      properties: {\n        capability: {\n          type: 'string',\n          description:\n            'Capability keyword to search for (e.g. \"hardware\", \"browser\", \"device-safety\"). ' +\n            'Matches against capability name, tags, and description.',\n        },\n        subject: {\n          type: 'string',\n          description:\n            'Subject to narrow results (e.g. \"nir\" under \"hardware\", \"consent\" under \"device-safety\").',\n        },\n      },\n    },\n  },\n  {\n    name: 'holo_list_receipt_capabilities',\n    description:\n      'List all registered receipt capability keywords and subjects in the HoloScript receipt registry. ' +\n      'Returns the full capability taxonomy for discovery.',\n    inputSchema: {\n      type: 'object' as const,\n      properties: {\n        includeSubjects: {\n          type: 'boolean',\n          description:\n            'Whether to include the subject taxonomy for each capability. Default: true.',\n          default: true,\n        },\n      },\n    },\n  },\n];\n\n// =============================================================================\n// HANDLERS\n// =============================================================================\n\nexport async function handleReceiptQueryTool(\n  name: string,\n  args: Record<string, unknown>\n): Promise<unknown | null> {\n  switch (name) {\n    case 'holo_query_receipts':\n      return handleQueryReceipts(args);\n    case 'holo_list_receipt_capabilities':\n      return handleListReceiptCapabilities(args);\n    default:\n      return null;\n  }\n}\n\nfunction handleQueryReceipts(args: Record<string, unknown>): {\n  count: number;\n  capabilities: ReceiptSummary[];\n  capability?: string;\n  subject?: string;\n} {\n  const capability = args.capability as string | undefined;\n  const subject = args.subject as string | undefined;\n\n  const entries = queryReceiptCapabilities(capability, subject);\n\n  return {\n    count: entries.length,\n    capabilities: entries.map(entryToSummary),\n    capability,\n    subject,\n  };\n}\n\nfunction handleListReceiptCapabilities(args: Record<string, unknown>): {\n  totalCapabilities: number;\n  capabilities: Array<{ capability: string; description: string; subjects?: string[] }>;\n  allSubjects: string[];\n} {\n  const includeSubjects = (args.includeSubjects as boolean) ?? true;\n\n  return {\n    totalCapabilities: receiptCapabilityCount(),\n    capabilities: RECEIPT_CAPABILITY_REGISTRY.map((entry) => ({\n      capability: entry.capability,\n      description: entry.description,\n      ...(includeSubjects ? { subjects: entry.subjects } : {}),\n    })),\n    allSubjects: includeSubjects ? listReceiptSubjects() : [],\n  };\n}\n\n// ── Helpers ──\n\ninterface ReceiptSummary {\n  capability: string;\n  receiptType: string;\n  module: string;\n  description: string;\n  subjects: string[];\n  tags: string[];\n}\n\nfunction entryToSummary(entry: ReceiptCapabilityEntry): ReceiptSummary {\n  return {\n    capability: entry.capability,\n    receiptType: entry.receiptType,\n    module: entry.module,\n    description: entry.description,\n    subjects: entry.subjects ?? [],\n    tags: entry.tags ?? [],\n  };\n}\n","/**\n * HoloScript MCP Service Contract Tools\n *\n * Generates .holo compositions from OpenAPI specs or TypeScript interfaces.\n * Two tools:\n *\n * 1. `generate_service_contract` - Parse an OpenAPI/TypeScript contract and emit\n *    a valid .holo composition with @service, @endpoint, @schema, and @handler traits.\n *\n * 2. `explain_service_contract` - Analyze an existing .holo service composition and\n *    explain the contract structure in plain English.\n *\n * @version 1.0.0\n * @package @holoscript/mcp-server\n */\n\nimport type { Tool } from '@modelcontextprotocol/sdk/types.js';\n\n// =============================================================================\n// TYPES\n// =============================================================================\n\ninterface OpenAPIPath {\n  [method: string]: {\n    operationId?: string;\n    summary?: string;\n    description?: string;\n    parameters?: Array<{\n      name: string;\n      in: string;\n      required?: boolean;\n      schema?: { type: string; format?: string };\n    }>;\n    requestBody?: {\n      content?: {\n        [mime: string]: {\n          schema?: SchemaObject;\n        };\n      };\n    };\n    responses?: {\n      [statusCode: string]: {\n        description?: string;\n        content?: {\n          [mime: string]: {\n            schema?: SchemaObject;\n          };\n        };\n      };\n    };\n  };\n}\n\ninterface SchemaObject {\n  type?: string;\n  format?: string;\n  properties?: Record<string, SchemaObject>;\n  items?: SchemaObject;\n  required?: string[];\n  $ref?: string;\n  enum?: unknown[];\n  description?: string;\n}\n\ninterface OpenAPISpec {\n  openapi?: string;\n  swagger?: string;\n  info?: {\n    title?: string;\n    version?: string;\n    description?: string;\n  };\n  paths?: Record<string, OpenAPIPath>;\n  components?: {\n    schemas?: Record<string, SchemaObject>;\n  };\n  definitions?: Record<string, SchemaObject>; // Swagger 2.0\n}\n\ninterface TSInterface {\n  name: string;\n  fields: Array<{\n    name: string;\n    type: string;\n    optional: boolean;\n  }>;\n}\n\ninterface ServiceContractResult {\n  success: boolean;\n  holoCode?: string;\n  stats?: {\n    endpoints: number;\n    schemas: number;\n    traits: number;\n    lines: number;\n  };\n  detectedFormat?: string;\n  error?: string;\n}\n\n// =============================================================================\n// FORMAT DETECTION\n// =============================================================================\n\nfunction detectContractFormat(input: string): 'openapi' | 'typescript' | 'unknown' {\n  const trimmed = input.trim();\n\n  // JSON-based OpenAPI\n  if (trimmed.startsWith('{')) {\n    try {\n      const parsed = JSON.parse(trimmed);\n      if (parsed.openapi || parsed.swagger || parsed.paths) return 'openapi';\n    } catch {\n      // Not valid JSON\n    }\n  }\n\n  // YAML-based OpenAPI\n  if (/^openapi:\\s/m.test(trimmed) || /^swagger:\\s/m.test(trimmed)) {\n    return 'openapi';\n  }\n\n  // TypeScript interface\n  if (/\\binterface\\s+\\w+/.test(trimmed) || /\\btype\\s+\\w+\\s*=/.test(trimmed)) {\n    return 'typescript';\n  }\n\n  return 'unknown';\n}\n\n// =============================================================================\n// OPENAPI PARSER\n// =============================================================================\n\nfunction parseOpenAPI(input: string): OpenAPISpec {\n  const trimmed = input.trim();\n\n  // Try JSON first\n  if (trimmed.startsWith('{')) {\n    return JSON.parse(trimmed) as OpenAPISpec;\n  }\n\n  // Minimal YAML parsing for common OpenAPI patterns\n  return parseMinimalYAML(trimmed);\n}\n\nfunction parseMinimalYAML(yaml: string): OpenAPISpec {\n  const spec: OpenAPISpec = {};\n  const lines = yaml.split('\\n');\n\n  // Extract top-level fields\n  for (const line of lines) {\n    const match = line.match(/^(openapi|swagger):\\s*['\"]?([^'\"]+)['\"]?/);\n    if (match) {\n      if (match[1] === 'openapi') spec.openapi = match[2].trim();\n      else spec.swagger = match[2].trim();\n    }\n  }\n\n  // Extract info\n  const infoMatch = yaml.match(/info:\\s*\\n((?:\\s+.+\\n?)*)/);\n  if (infoMatch) {\n    spec.info = {};\n    const titleMatch = infoMatch[1].match(/title:\\s*['\"]?([^'\"\\n]+)['\"]?/);\n    const versionMatch = infoMatch[1].match(/version:\\s*['\"]?([^'\"\\n]+)['\"]?/);\n    if (titleMatch) spec.info.title = titleMatch[1].trim();\n    if (versionMatch) spec.info.version = versionMatch[1].trim();\n  }\n\n  // Extract paths — simplified: detect /path patterns\n  const pathsSection = yaml.match(/paths:\\s*\\n((?:\\s+.+\\n?)*)/);\n  if (pathsSection) {\n    spec.paths = {};\n    const pathLines = pathsSection[1].split('\\n');\n    let currentPath = '';\n    let currentMethod = '';\n\n    for (const line of pathLines) {\n      const pathMatch = line.match(/^\\s{2}(\\/\\S+):/);\n      if (pathMatch) {\n        currentPath = pathMatch[1];\n        spec.paths[currentPath] = {};\n        continue;\n      }\n\n      const methodMatch = line.match(/^\\s{4}(get|post|put|patch|delete|head|options):/);\n      if (methodMatch && currentPath) {\n        currentMethod = methodMatch[1];\n        spec.paths[currentPath][currentMethod] = {};\n        continue;\n      }\n\n      if (currentPath && currentMethod) {\n        const summaryMatch = line.match(/^\\s{6}summary:\\s*['\"]?(.+?)['\"]?\\s*$/);\n        const opIdMatch = line.match(/^\\s{6}operationId:\\s*['\"]?(.+?)['\"]?\\s*$/);\n        if (summaryMatch) {\n          spec.paths[currentPath][currentMethod].summary = summaryMatch[1];\n        }\n        if (opIdMatch) {\n          spec.paths[currentPath][currentMethod].operationId = opIdMatch[1];\n        }\n      }\n    }\n  }\n\n  // Extract schemas from components\n  const schemasSection = yaml.match(\n    /(?:components:\\s*\\n\\s+schemas:|definitions:)\\s*\\n((?:\\s+.+\\n?)*)/\n  );\n  if (schemasSection) {\n    const schemas: Record<string, SchemaObject> = {};\n    const schemaLines = schemasSection[1].split('\\n');\n    let currentSchema = '';\n    let currentField = '';\n\n    for (const line of schemaLines) {\n      const schemaMatch = line.match(/^\\s{4}(\\w+):/);\n      if (schemaMatch) {\n        currentSchema = schemaMatch[1];\n        schemas[currentSchema] = { type: 'object', properties: {} };\n        continue;\n      }\n\n      if (currentSchema) {\n        const propMatch = line.match(/^\\s{8}(\\w+):/);\n        if (propMatch) {\n          currentField = propMatch[1];\n          if (currentField !== 'required' && currentField !== 'type') {\n            schemas[currentSchema].properties![currentField] = {};\n          }\n          continue;\n        }\n\n        const typeMatch = line.match(/^\\s{10}type:\\s*(\\w+)/);\n        if (typeMatch && currentField && schemas[currentSchema].properties![currentField]) {\n          schemas[currentSchema].properties![currentField].type = typeMatch[1];\n        }\n\n        const requiredMatch = line.match(/^\\s{6}required:/);\n        if (requiredMatch) {\n          schemas[currentSchema].required = [];\n          currentField = '';\n        }\n\n        const reqItemMatch = line.match(/^\\s{8}-\\s*(\\w+)/);\n        if (reqItemMatch && schemas[currentSchema].required) {\n          schemas[currentSchema].required!.push(reqItemMatch[1]);\n        }\n      }\n    }\n\n    if (Object.keys(schemas).length > 0) {\n      spec.components = { schemas };\n    }\n  }\n\n  return spec;\n}\n\n// =============================================================================\n// TYPESCRIPT INTERFACE PARSER\n// =============================================================================\n\nfunction parseTypeScriptInterfaces(input: string): TSInterface[] {\n  const interfaces: TSInterface[] = [];\n\n  // Match interface blocks\n  const interfaceRegex = /\\binterface\\s+(\\w+)\\s*(?:extends\\s+[\\w,\\s]+)?\\s*\\{([^}]*)\\}/g;\n  let match;\n\n  while ((match = interfaceRegex.exec(input)) !== null) {\n    const name = match[1];\n    const body = match[2];\n    const fields: TSInterface['fields'] = [];\n\n    const fieldRegex = /(\\w+)(\\??)\\s*:\\s*([^;]+);?/g;\n    let fieldMatch;\n\n    while ((fieldMatch = fieldRegex.exec(body)) !== null) {\n      fields.push({\n        name: fieldMatch[1],\n        type: fieldMatch[3].trim(),\n        optional: fieldMatch[2] === '?',\n      });\n    }\n\n    interfaces.push({ name, fields });\n  }\n\n  // Match type aliases with object shapes\n  const typeRegex = /\\btype\\s+(\\w+)\\s*=\\s*\\{([^}]*)\\}/g;\n  while ((match = typeRegex.exec(input)) !== null) {\n    const name = match[1];\n    const body = match[2];\n    const fields: TSInterface['fields'] = [];\n\n    const fieldRegex = /(\\w+)(\\??)\\s*:\\s*([^;]+);?/g;\n    let fieldMatch;\n\n    while ((fieldMatch = fieldRegex.exec(body)) !== null) {\n      fields.push({\n        name: fieldMatch[1],\n        type: fieldMatch[3].trim(),\n        optional: fieldMatch[2] === '?',\n      });\n    }\n\n    interfaces.push({ name, fields });\n  }\n\n  return interfaces;\n}\n\n// =============================================================================\n// HOLOSCRIPT TYPE MAPPING\n// =============================================================================\n\nconst TS_TO_HOLO_TYPE: Record<string, string> = {\n  string: 'string',\n  number: 'number',\n  boolean: 'boolean',\n  Date: 'datetime',\n  any: 'json',\n  object: 'json',\n  undefined: 'null',\n  null: 'null',\n};\n\nconst OPENAPI_TO_HOLO_TYPE: Record<string, string> = {\n  string: 'string',\n  integer: 'number',\n  number: 'number',\n  boolean: 'boolean',\n  object: 'json',\n  array: 'array',\n};\n\nfunction mapTsType(tsType: string): string {\n  // Handle array types\n  if (tsType.endsWith('[]')) return 'array';\n  if (tsType.startsWith('Array<')) return 'array';\n\n  // Handle union types — take first concrete type\n  if (tsType.includes('|')) {\n    const first = tsType.split('|')[0].trim();\n    return mapTsType(first);\n  }\n\n  return TS_TO_HOLO_TYPE[tsType] || 'string';\n}\n\nfunction mapOpenAPIType(schema: SchemaObject): string {\n  if (schema.$ref) {\n    const refName = schema.$ref.split('/').pop() || 'unknown';\n    return refName;\n  }\n  if (schema.type === 'array' && schema.items) {\n    return `array<${mapOpenAPIType(schema.items)}>`;\n  }\n  return OPENAPI_TO_HOLO_TYPE[schema.type || 'string'] || 'string';\n}\n\nfunction httpMethodToUpper(method: string): string {\n  return method.toUpperCase();\n}\n\n// =============================================================================\n// HOLO CODE GENERATORS\n// =============================================================================\n\nfunction generateFromOpenAPI(spec: OpenAPISpec): ServiceContractResult {\n  const lines: string[] = [];\n  const serviceName = spec.info?.title?.replace(/[^a-zA-Z0-9]/g, '') || 'APIService';\n  const version = spec.info?.version || '1.0.0';\n\n  let endpointCount = 0;\n  let schemaCount = 0;\n\n  lines.push(`// Generated from OpenAPI ${spec.openapi || spec.swagger || '3.0'} spec`);\n  lines.push(`// ${spec.info?.title || 'API Service'} v${version}`);\n  lines.push('');\n  lines.push(`composition \"${serviceName}\" {`);\n  lines.push('');\n\n  // Generate schema blocks from components/schemas\n  const schemas = spec.components?.schemas || spec.definitions || {};\n  for (const [schemaName, schemaObj] of Object.entries(schemas)) {\n    lines.push(`  schema \"${schemaName}\" @schema @contract {`);\n\n    if (schemaObj.properties) {\n      for (const [fieldName, fieldSchema] of Object.entries(schemaObj.properties)) {\n        const holoType = mapOpenAPIType(fieldSchema);\n        const required = schemaObj.required?.includes(fieldName) ? '' : '?';\n        const desc = fieldSchema.description ? ` // ${fieldSchema.description}` : '';\n        lines.push(`    ${fieldName}${required}: ${holoType}${desc}`);\n      }\n    }\n\n    lines.push('  }');\n    lines.push('');\n    schemaCount++;\n  }\n\n  // Generate endpoint blocks from paths\n  if (spec.paths) {\n    for (const [pathStr, pathItem] of Object.entries(spec.paths)) {\n      const HTTP_METHODS = ['get', 'post', 'put', 'patch', 'delete', 'head', 'options'];\n      for (const method of HTTP_METHODS) {\n        const operation = pathItem[method];\n        if (!operation) continue;\n\n        const opName =\n          operation.operationId || `${method}_${pathStr.replace(/[^a-zA-Z0-9]/g, '_')}`;\n        const _summary = operation.summary || `${httpMethodToUpper(method)} ${pathStr}`;\n\n        lines.push(`  endpoint \"${opName}\" @endpoint @handler {`);\n        lines.push(`    method: \"${httpMethodToUpper(method)}\"`);\n        lines.push(`    path: \"${pathStr}\"`);\n        if (operation.summary) {\n          lines.push(`    summary: \"${operation.summary}\"`);\n        }\n\n        // Parameters\n        if (operation.parameters?.length) {\n          lines.push('    params {');\n          for (const param of operation.parameters) {\n            const paramType = param.schema?.type || 'string';\n            const required = param.required ? '' : '?';\n            lines.push(\n              `      ${param.name}${required}: ${OPENAPI_TO_HOLO_TYPE[paramType] || 'string'} // in: ${param.in}`\n            );\n          }\n          lines.push('    }');\n        }\n\n        // Request body\n        if (operation.requestBody?.content) {\n          const jsonSchema = operation.requestBody.content['application/json']?.schema;\n          if (jsonSchema) {\n            const bodyType = mapOpenAPIType(jsonSchema);\n            lines.push(`    request_body: ${bodyType}`);\n          }\n        }\n\n        // Responses\n        if (operation.responses) {\n          for (const [status, response] of Object.entries(operation.responses)) {\n            const jsonSchema = response.content?.['application/json']?.schema;\n            if (jsonSchema) {\n              const responseType = mapOpenAPIType(jsonSchema);\n              lines.push(`    response_${status}: ${responseType}`);\n            }\n          }\n        }\n\n        lines.push('  }');\n        lines.push('');\n        endpointCount++;\n      }\n    }\n  }\n\n  // Service metadata block\n  lines.push(`  service \"${serviceName}\" @service @rest_resource {`);\n  lines.push(`    version: \"${version}\"`);\n  lines.push(`    framework: \"express\"`);\n  lines.push(`    endpoints: ${endpointCount}`);\n  lines.push('  }');\n\n  lines.push('}');\n  lines.push('');\n\n  const code = lines.join('\\n');\n  const traitCount = (code.match(/@\\w+/g) || []).length;\n\n  return {\n    success: true,\n    holoCode: code,\n    stats: {\n      endpoints: endpointCount,\n      schemas: schemaCount,\n      traits: traitCount,\n      lines: code.split('\\n').length,\n    },\n    detectedFormat: 'openapi',\n  };\n}\n\nfunction generateFromTypeScript(interfaces: TSInterface[]): ServiceContractResult {\n  const lines: string[] = [];\n  let schemaCount = 0;\n\n  lines.push('// Generated from TypeScript interfaces');\n  lines.push('');\n  lines.push('composition \"TypeScriptContract\" {');\n  lines.push('');\n\n  for (const iface of interfaces) {\n    lines.push(`  schema \"${iface.name}\" @schema @contract @validator {`);\n\n    for (const field of iface.fields) {\n      const holoType = mapTsType(field.type);\n      const optional = field.optional ? '?' : '';\n      lines.push(`    ${field.name}${optional}: ${holoType}`);\n    }\n\n    lines.push('  }');\n    lines.push('');\n    schemaCount++;\n  }\n\n  lines.push('}');\n  lines.push('');\n\n  const code = lines.join('\\n');\n  const traitCount = (code.match(/@\\w+/g) || []).length;\n\n  return {\n    success: true,\n    holoCode: code,\n    stats: {\n      endpoints: 0,\n      schemas: schemaCount,\n      traits: traitCount,\n      lines: code.split('\\n').length,\n    },\n    detectedFormat: 'typescript',\n  };\n}\n\n// =============================================================================\n// HANDLER\n// =============================================================================\n\nexport async function handleGenerateServiceContract(\n  args: Record<string, unknown>\n): Promise<ServiceContractResult> {\n  const input = args.input as string;\n  const formatHint = args.format as string | undefined;\n\n  if (!input) {\n    return {\n      success: false,\n      error: 'input is required: provide OpenAPI spec or TypeScript interfaces',\n    };\n  }\n\n  const format = formatHint || detectContractFormat(input);\n\n  try {\n    if (format === 'openapi') {\n      const spec = parseOpenAPI(input);\n      return generateFromOpenAPI(spec);\n    }\n\n    if (format === 'typescript') {\n      const interfaces = parseTypeScriptInterfaces(input);\n      if (interfaces.length === 0) {\n        return { success: false, error: 'No TypeScript interfaces found in input' };\n      }\n      return generateFromTypeScript(interfaces);\n    }\n\n    return {\n      success: false,\n      error: `Could not detect contract format. Use the \"format\" parameter (\"openapi\" or \"typescript\") or provide valid OpenAPI JSON/YAML or TypeScript interfaces.`,\n    };\n  } catch (error) {\n    return {\n      success: false,\n      error: error instanceof Error ? error.message : String(error),\n    };\n  }\n}\n\nexport async function handleExplainServiceContract(\n  args: Record<string, unknown>\n): Promise<{ success: boolean; explanation?: string; error?: string }> {\n  const code = args.code as string;\n\n  if (!code) {\n    return { success: false, error: 'code is required: provide .holo composition code' };\n  }\n\n  const endpoints = (code.match(/@endpoint/g) || []).length;\n  const schemas = (code.match(/@schema/g) || []).length;\n  const services = (code.match(/@service/g) || []).length;\n  const handlers = (code.match(/@handler/g) || []).length;\n\n  const lines: string[] = [];\n  lines.push('## Service Contract Summary');\n  lines.push('');\n  lines.push(`- **${services}** service(s) defined`);\n  lines.push(`- **${endpoints}** endpoint(s) declared`);\n  lines.push(`- **${schemas}** schema(s) for data contracts`);\n  lines.push(`- **${handlers}** handler(s) for request processing`);\n\n  // Extract endpoint details\n  const endpointMatches = code.matchAll(/endpoint\\s+\"([^\"]+)\"\\s+[^{]*\\{([^}]*)\\}/g);\n  const endpointDetails: string[] = [];\n  for (const match of endpointMatches) {\n    const name = match[1];\n    const body = match[2];\n    const methodMatch = body.match(/method:\\s*\"(\\w+)\"/);\n    const pathMatch = body.match(/path:\\s*\"([^\"]+)\"/);\n    if (methodMatch && pathMatch) {\n      endpointDetails.push(`  - \\`${methodMatch[1]} ${pathMatch[1]}\\` (${name})`);\n    }\n  }\n\n  if (endpointDetails.length > 0) {\n    lines.push('');\n    lines.push('### Endpoints');\n    lines.push(...endpointDetails);\n  }\n\n  // Extract schema names\n  const schemaMatches = code.matchAll(/schema\\s+\"([^\"]+)\"/g);\n  const schemaNames: string[] = [];\n  for (const match of schemaMatches) {\n    schemaNames.push(match[1]);\n  }\n\n  if (schemaNames.length > 0) {\n    lines.push('');\n    lines.push('### Schemas');\n    lines.push(schemaNames.map((s) => `  - ${s}`).join('\\n'));\n  }\n\n  return {\n    success: true,\n    explanation: lines.join('\\n'),\n  };\n}\n\n// =============================================================================\n// HANDLER DISPATCHER\n// =============================================================================\n\nexport async function handleServiceContractTool(\n  name: string,\n  args: Record<string, unknown>\n): Promise<unknown | null> {\n  switch (name) {\n    case 'generate_service_contract':\n      return handleGenerateServiceContract(args);\n    case 'explain_service_contract':\n      return handleExplainServiceContract(args);\n    default:\n      return null;\n  }\n}\n\n// =============================================================================\n// MCP TOOL DEFINITIONS\n// =============================================================================\n\nexport const serviceContractTools: Tool[] = [\n  {\n    name: 'generate_service_contract',\n    description:\n      'Generate a HoloScript .holo composition from an OpenAPI spec or TypeScript interfaces. ' +\n      'Auto-detects input format. Produces @service, @endpoint, @schema, @handler, and ' +\n      '@contract traits. Supports OpenAPI 3.x JSON/YAML and TypeScript interface/type syntax.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        input: {\n          type: 'string',\n          description:\n            'OpenAPI spec (JSON or YAML) or TypeScript interface/type definitions to convert',\n        },\n        format: {\n          type: 'string',\n          enum: ['openapi', 'typescript'],\n          description: 'Input format hint. Auto-detected if omitted.',\n        },\n      },\n      required: ['input'],\n    },\n  },\n  {\n    name: 'explain_service_contract',\n    description:\n      'Analyze a .holo service composition and explain its contract structure. ' +\n      'Returns endpoint details, schema names, and trait counts.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        code: {\n          type: 'string',\n          description: 'HoloScript .holo composition code with service/contract traits',\n        },\n      },\n      required: ['code'],\n    },\n  },\n];\n","/**\n * HoloScript MCP Fairness Tools\n *\n * Surfaces the verifiable algorithmic-fairness sweep (@holoscript/engine\n * Simulation.runFairnessSweep / runFairnessRobustness) as two MCP tools:\n *\n *   1. `fairness_sweep` — run a transparent linear decision model over a cohort,\n *      emit a sovereign per-decision FairnessReceipt (4/5ths adverse-impact +\n *      demographic-parity + the regulator crosswalk + a replay fingerprint), and\n *      optionally an LHS robustness band (ROBUSTLY-FAIR / -UNFAIR).\n *\n *   2. `explain_fairness_receipt` — verify a receipt's content-hash integrity and\n *      explain it in plain English, rendering the regulator crosswalk.\n *\n * The model exposed here is the examiner-friendly transparent linear scorer\n * (weights + bias + threshold over named features) — the domain bridge swaps in\n * the institution's real model + point-in-time data in production. Core stays\n * domain-free (D.007).\n *\n * @version 1.0.0\n * @package @holoscript/mcp-server\n */\n\nimport type { Tool } from '@modelcontextprotocol/sdk/types.js';\n\n// Lazy import to avoid breaking tests when @holoscript/engine isn't resolvable.\nlet _Simulation: typeof import('@holoscript/engine').Simulation | null = null;\nasync function getSimulation(): Promise<typeof import('@holoscript/engine').Simulation> {\n  if (!_Simulation) {\n    const mod = await import('@holoscript/engine');\n    _Simulation = mod.Simulation;\n  }\n  return _Simulation;\n}\n\n// ── Arg shapes ───────────────────────────────────────────────────────────────────────────────\n\ninterface CohortRecordArg {\n  group: string;\n  features: Record<string, number>;\n}\n\ninterface LinearModelArg {\n  id?: string;\n  /** Feature weights: contribution += weights[k] * features[k]. */\n  weights: Record<string, number>;\n  /** Additive bias term. */\n  bias?: number;\n  /** Approval threshold: approved iff (Σ wᵏ·fᵏ + bias) ≥ threshold. */\n  threshold?: number;\n}\n\ninterface RobustnessArg {\n  replicates?: number;\n  driftRange?: [number, number];\n  noiseRange?: [number, number];\n}\n\n// ── Helpers ────────────────────────────────────────────────────────────────────────────────\n\nfunction isFiniteNumber(x: unknown): x is number {\n  return typeof x === 'number' && Number.isFinite(x);\n}\n\nfunction isPlainRecord(x: unknown): x is Record<string, unknown> {\n  return typeof x === 'object' && x !== null && !Array.isArray(x);\n}\n\nfunction validateCohort(cohort: unknown): CohortRecordArg[] {\n  if (!Array.isArray(cohort) || cohort.length === 0) {\n    throw new Error(\"fairness_sweep: 'cohort' must be a non-empty array of { group, features }.\");\n  }\n  return cohort.map((r, i) => {\n    const rec = r as Partial<CohortRecordArg>;\n    if (typeof rec.group !== 'string' || !rec.group) {\n      throw new Error(`fairness_sweep: cohort[${i}].group must be a non-empty string.`);\n    }\n    if (!rec.features || typeof rec.features !== 'object') {\n      throw new Error(`fairness_sweep: cohort[${i}].features must be an object of numbers.`);\n    }\n    for (const [k, v] of Object.entries(rec.features)) {\n      if (!isFiniteNumber(v)) {\n        throw new Error(`fairness_sweep: cohort[${i}].features.${k} must be a finite number.`);\n      }\n    }\n    return { group: rec.group, features: rec.features as Record<string, number> };\n  });\n}\n\nfunction buildLinearModel(spec: unknown): {\n  id: string;\n  decide(features: Record<string, number>): boolean;\n  fingerprint(): unknown;\n} {\n  const m = spec as Partial<LinearModelArg> | undefined;\n  if (!m || !m.weights || typeof m.weights !== 'object') {\n    throw new Error(\"fairness_sweep: 'model.weights' (object of feature→weight) is required.\");\n  }\n  const weights = m.weights;\n  for (const [k, v] of Object.entries(weights)) {\n    if (!isFiniteNumber(v)) throw new Error(`fairness_sweep: model.weights.${k} must be finite.`);\n  }\n  const bias = isFiniteNumber(m.bias) ? m.bias : 0;\n  const threshold = isFiniteNumber(m.threshold) ? m.threshold : 0;\n  const id = typeof m.id === 'string' && m.id ? m.id : 'linear-scorer';\n  return {\n    id,\n    decide: (features) => {\n      let score = bias;\n      for (const [k, w] of Object.entries(weights)) score += w * (features[k] ?? 0);\n      return score >= threshold;\n    },\n    fingerprint: () => ({ kind: 'linear-scorer.v1', weights, bias, threshold }),\n  };\n}\n\n// ── Handlers ────────────────────────────────────────────────────────────────────────────────\n\nasync function handleFairnessSweep(args: Record<string, unknown>): Promise<unknown> {\n  const Sim = await getSimulation();\n  const cohort = validateCohort(args.cohort);\n  const model = buildLinearModel(args.model);\n\n  const hashMode =\n    args.hashMode === 'sha256' ? 'sha256' : args.hashMode === 'fnv1a' ? 'fnv1a' : undefined;\n  const seed = isFiniteNumber(args.seed) ? args.seed : 0;\n  const protectedAttribute =\n    typeof args.protectedAttribute === 'string' ? args.protectedAttribute : 'group';\n  const jurisdiction =\n    typeof args.jurisdiction === 'string' || isPlainRecord(args.jurisdiction)\n      ? (args.jurisdiction as\n          | import('@holoscript/engine').Simulation.FairnessJurisdiction\n          | import('@holoscript/engine').Simulation.JurisdictionConfig)\n      : undefined;\n\n  const sweep = await Sim.runFairnessSweep(model, cohort, {\n    seed,\n    protectedAttribute,\n    hashMode,\n    verifyDeterminism: args.verifyDeterminism === true,\n    jurisdiction,\n  });\n\n  const out: Record<string, unknown> = {\n    receipt: sweep.receipt,\n    metrics: sweep.metrics,\n    decision: sweep.receipt.decision,\n    replayDeterminism: sweep.replayDeterminism,\n  };\n\n  if (args.robustness) {\n    const rob = (args.robustness === true ? {} : args.robustness) as RobustnessArg;\n    const robustness = await Sim.runFairnessRobustness(model, cohort, {\n      seed,\n      hashMode,\n      jurisdiction,\n      replicates: isFiniteNumber(rob.replicates) ? rob.replicates : undefined,\n      driftRange: Array.isArray(rob.driftRange) ? rob.driftRange : undefined,\n      noiseRange: Array.isArray(rob.noiseRange) ? rob.noiseRange : undefined,\n    });\n    out.robustness = {\n      receipt: robustness.receipt,\n      band: robustness.band,\n      verdict: robustness.verdict,\n      ensembleHash: robustness.ensembleHash,\n      note:\n        'MCP robustness uses the feature-agnostic default perturber (bootstrap + measurement noise). ' +\n        'Population-drift modeling for a specific vertical is supplied via the .holo domain bridge.',\n    };\n  }\n\n  return out;\n}\n\nasync function handleExplainFairnessReceipt(args: Record<string, unknown>): Promise<unknown> {\n  const Sim = await getSimulation();\n  const receipt = args.receipt as\n    | import('@holoscript/engine').Simulation.FairnessReceipt\n    | import('@holoscript/engine').Simulation.FairnessRobustnessReceipt\n    | undefined;\n  if (!receipt || typeof receipt !== 'object' || !('kind' in receipt)) {\n    throw new Error(\"explain_fairness_receipt: 'receipt' must be a FairnessReceipt object.\");\n  }\n\n  const integrity = Sim.verifyReceiptIntegrity(receipt);\n  const lines: string[] = [];\n\n  if (receipt.kind === 'fairness.receipt.v1') {\n    const r = receipt;\n    lines.push(`Per-decision fairness receipt for model \\`${r.modelId}\\`.`);\n    lines.push(`Sample size: ${r.sampleSize}; protected attribute: \\`${r.protectedAttribute}\\`.`);\n    lines.push(\n      `Adverse-impact ratio (4/5ths): ${r.metrics.adverseImpactRatio} → ${r.decision === 'PASS' ? 'PASS' : 'FLAG (disparate impact)'}.`\n    );\n    lines.push(`Demographic-parity diff: ${r.metrics.demographicParityDiff}.`);\n    lines.push(\n      `Per-group approval: ${Object.entries(r.metrics.approvalRate)\n        .map(([g, v]) => `${g}=${v}`)\n        .join('  ')}.`\n    );\n    lines.push(`Replay fingerprint: ${r.replayFingerprint} (hash mode: ${r.hashMode}).`);\n    const reExec =\n      r.replayDeterminism === 'exact'\n        ? 'EXACT — re-running the model reproduces the decision digest byte-identically.'\n        : r.replayDeterminism === 'quantized'\n          ? `QUANTIZED — the adverse-impact ratio reproduces within ±${r.replayTolerance} on re-run (individual decisions may vary).`\n          : `STATISTICAL — only the distribution-level verdict is stable (±${r.replayTolerance}); pair with a robustness receipt.`;\n    lines.push(`Re-execution grade: ${reExec}`);\n  } else if (receipt.kind === 'fairness.robustness.v1') {\n    const r = receipt;\n    lines.push(`Robustness receipt for model \\`${r.modelId}\\` (${r.replicates} LHS replicates).`);\n    lines.push(\n      `Adverse-impact 90% CI: [${r.robustness.ci90[0]}, ${r.robustness.ci90[1]}], worst-case ${r.robustness.worstCase} → ${r.verdict}.`\n    );\n    lines.push(`Ensemble hash: ${r.ensembleHash}; replay fingerprint: ${r.replayFingerprint}.`);\n  } else {\n    lines.push(`Unrecognized receipt kind: ${(receipt as { kind: string }).kind}.`);\n  }\n\n  lines.push('');\n  lines.push(\n    integrity\n      ? '✓ Integrity verified: the receipt content hash matches — untampered.'\n      : '✗ Integrity FAILED: the receipt content hash does not match — tampered or corrupted.'\n  );\n  lines.push('');\n  lines.push('Regulator crosswalk (this receipt satisfies, simultaneously):');\n  for (const [reg, field] of Object.entries(receipt.regulatoryMapping)) {\n    lines.push(`  - ${reg} ← ${field}`);\n  }\n\n  return {\n    integrity,\n    kind: receipt.kind,\n    explanation: lines.join('\\n'),\n    regulatoryMapping: receipt.regulatoryMapping,\n  };\n}\n\nasync function handleCompileToBiasAuditReport(args: Record<string, unknown>): Promise<unknown> {\n  const Sim = await getSimulation();\n  const receipt = args.receipt as import('@holoscript/engine').Simulation.FairnessReceipt | undefined;\n  if (!receipt || typeof receipt !== 'object' || receipt.kind !== 'fairness.receipt.v1') {\n    throw new Error(\"compile_to_bias_audit_report: 'receipt' must be a FairnessReceipt object.\");\n  }\n\n  const robustnessReceipt =\n    isPlainRecord(args.robustnessReceipt) &&\n    args.robustnessReceipt.kind === 'fairness.robustness.v1'\n      ? (args.robustnessReceipt as unknown as import('@holoscript/engine').Simulation.FairnessRobustnessReceipt)\n      : undefined;\n  const jurisdiction =\n    typeof args.jurisdiction === 'string' || isPlainRecord(args.jurisdiction)\n      ? (args.jurisdiction as\n          | import('@holoscript/engine').Simulation.FairnessJurisdiction\n          | import('@holoscript/engine').Simulation.JurisdictionConfig)\n      : undefined;\n\n  return Sim.compileBiasAuditReport({\n    receipt,\n    robustnessReceipt,\n    jurisdiction,\n    format: args.format === 'json' ? 'json' : 'markdown',\n    generatedAt: typeof args.generatedAt === 'string' ? args.generatedAt : undefined,\n    issuer: typeof args.issuer === 'string' ? args.issuer : undefined,\n  });\n}\n\n// ── Dispatcher + name guard ────────────────────────────────────────────────────────────────────\n\nconst FAIRNESS_TOOL_NAMES = new Set([\n  'fairness_sweep',\n  'explain_fairness_receipt',\n  'compile_to_bias_audit_report',\n]);\n\nexport function isFairnessToolName(name: string): boolean {\n  return FAIRNESS_TOOL_NAMES.has(name);\n}\n\nexport async function handleFairnessTool(\n  name: string,\n  args: Record<string, unknown>\n): Promise<unknown | null> {\n  switch (name) {\n    case 'fairness_sweep':\n      return handleFairnessSweep(args);\n    case 'explain_fairness_receipt':\n      return handleExplainFairnessReceipt(args);\n    case 'compile_to_bias_audit_report':\n      return handleCompileToBiasAuditReport(args);\n    default:\n      return null;\n  }\n}\n\n// ── Tool definitions ───────────────────────────────────────────────────────────────────────────────\n\nexport const fairnessTools: Tool[] = [\n  {\n    name: 'fairness_sweep',\n    description:\n      'Run a verifiable, jurisdiction-aware fairness sweep over a cohort with a transparent linear ' +\n      'decision model. Emits a FairnessReceipt with 4/5ths adverse-impact ratio, demographic-parity ' +\n      'difference, per-group approval rates, replay fingerprint, regulator crosswalk, optional ' +\n      'jurisdiction test bundle, and optional robustness band.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        cohort: {\n          type: 'array',\n          description: 'Records under evaluation. Each: { group, features }.',\n          items: {\n            type: 'object',\n            properties: {\n              group: { type: 'string', description: 'Protected-attribute value (e.g. \"A\" / \"B\").' },\n              features: {\n                type: 'object',\n                description: 'Feature name → numeric value, consumed by the model.',\n                additionalProperties: { type: 'number' },\n              },\n            },\n            required: ['group', 'features'],\n          },\n        },\n        model: {\n          type: 'object',\n          description:\n            'Transparent linear scorer: approved iff (Σ wᵏ·featurek + bias) ≥ threshold.',\n          properties: {\n            id: { type: 'string', description: 'Model identifier recorded on the receipt.' },\n            weights: {\n              type: 'object',\n              description: 'Feature name → weight.',\n              additionalProperties: { type: 'number' },\n            },\n            bias: { type: 'number', description: 'Additive bias term (default 0).' },\n            threshold: { type: 'number', description: 'Approval threshold (default 0).' },\n          },\n          required: ['weights'],\n        },\n        protectedAttribute: {\n          type: 'string',\n          description: 'Label for the protected attribute on the receipt (default \"group\").',\n        },\n        jurisdiction: {\n          type: 'string',\n          enum: [\n            'EEOC_TITLE_VII',\n            'NYC_LL144',\n            'CFPB_ECOA',\n            'COLORADO_SB21_169',\n            'EU_AI_ACT_PROHIBITED',\n          ],\n          description:\n            'Optional jurisdiction pack. Adds required test results (four-fifths, Fisher exact, chi-squared, and jurisdiction-specific redlining checks) to the receipt.',\n        },\n        seed: {\n          type: 'number',\n          description: 'Replay-key seed recorded on the receipt (default 0).',\n        },\n        hashMode: {\n          type: 'string',\n          enum: ['fnv1a', 'sha256'],\n          description: \"Hash mode: 'fnv1a' (default, fast) or 'sha256' (adversarial-peer opt-in).\",\n        },\n        verifyDeterminism: {\n          type: 'boolean',\n          description:\n            \"Re-run the model a second time and record a MEASURED re-execution grade on the receipt (exact / quantized / statistical), auto-downgrading any over-claimed determinism. Default false (grade 'exact').\",\n        },\n        robustness: {\n          description:\n            'If set, also run an LHS robustness band. true for defaults, or { replicates, driftRange, noiseRange }.',\n          oneOf: [\n            { type: 'boolean' },\n            {\n              type: 'object',\n              properties: {\n                replicates: { type: 'number', description: 'LHS replicate count (default 200).' },\n                driftRange: {\n                  type: 'array',\n                  items: { type: 'number' },\n                  description: 'Population-drift range [min, max].',\n                },\n                noiseRange: {\n                  type: 'array',\n                  items: { type: 'number' },\n                  description: 'Measurement-noise range [min, max].',\n                },\n              },\n            },\n          ],\n        },\n      },\n      required: ['cohort', 'model'],\n    },\n  },\n  {\n    name: 'explain_fairness_receipt',\n    description:\n      'Verify a FairnessReceipt (or FairnessRobustnessReceipt) content-hash integrity and explain ' +\n      'it in plain English, rendering the regulator crosswalk. Returns integrity:true only when the ' +\n      'receipt is byte-identical to issuance (tamper detection).',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        receipt: {\n          type: 'object',\n          description:\n            'A FairnessReceipt or FairnessRobustnessReceipt as returned by fairness_sweep.',\n        },\n      },\n      required: ['receipt'],\n    },\n  },\n  {\n    name: 'compile_to_bias_audit_report',\n    description:\n      'Compile a FairnessReceipt into a per-jurisdiction bias-audit report. Formats NYC LL144, EEOC Title VII, CFPB/ECOA, Colorado SB21-169, or EU AI Act disclosure sections from the receipt metrics, required statistical tests, replay fingerprint, integrity hash, and regulator crosswalk.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        receipt: {\n          type: 'object',\n          description: 'FairnessReceipt as returned by fairness_sweep.',\n        },\n        robustnessReceipt: {\n          type: 'object',\n          description: 'Optional FairnessRobustnessReceipt as returned by fairness_sweep robustness.',\n        },\n        jurisdiction: {\n          type: 'string',\n          enum: [\n            'EEOC_TITLE_VII',\n            'NYC_LL144',\n            'CFPB_ECOA',\n            'COLORADO_SB21_169',\n            'EU_AI_ACT_PROHIBITED',\n          ],\n          description:\n            'Jurisdiction report standard to use when the receipt did not already carry one.',\n        },\n        format: {\n          type: 'string',\n          enum: ['markdown', 'json'],\n          description: 'Report format (default markdown).',\n        },\n        generatedAt: {\n          type: 'string',\n          description: 'Optional fixed timestamp for byte-stable report generation.',\n        },\n        issuer: {\n          type: 'string',\n          description: 'Report issuer label (default HoloScript).',\n        },\n      },\n      required: ['receipt'],\n    },\n  },\n];\n","/**\n * HoloScript MCP Composition Validation Tool\n *\n * Validates .holo compositions against the full constraint system:\n * - Spatial trait constraints (requires/conflicts/oneof)\n * - v6 universal domain constraints (service, data, pipeline, resilience, etc.)\n * - Domain block coherence (traits match their enclosing domain)\n * - Dependency graph validation\n *\n * @version 1.0.0\n * @package @holoscript/mcp-server\n */\n\nimport type { Tool } from '@modelcontextprotocol/sdk/types.js';\nimport {\n  parseHolo,\n  BUILTIN_CONSTRAINTS,\n  ConfabulationValidator,\n  DERIVED_TRAIT_CONFLICTS,\n} from '@holoscript/core';\nimport type {\n  HoloComposition,\n  HoloObjectDecl,\n  HoloDomainBlock,\n  HoloDomainType,\n} from '@holoscript/core';\nimport type { TraitConstraint } from '@holoscript/core';\n\n// Advisory per-trait prop-schema validator (enum/type) built once — its registry loads ~1080\n// schemas, so it must not be reconstructed per validate call. Prerequisite/conflict graph checks\n// are off: this surface advises on declared prop shape only. Findings are emitted as WARNINGS\n// (never errors) so `valid` is unaffected. Traits in DERIVED_TRAIT_CONFLICTS are suppressed:\n// their derived schema was resolved by a .holo-vs-.holo coin flip and may hold the wrong enum\n// set, so advising on them would be majority-noise until the conflicts are triaged (Phase 2).\nconst PROP_SCHEMA_VALIDATOR = new ConfabulationValidator({\n  includeDerivedSchemas: true,\n  validatePrerequisites: false,\n  validateConflicts: false,\n});\nconst CONFLICTED_TRAITS = new Set(DERIVED_TRAIT_CONFLICTS);\n\n// =============================================================================\n// TYPES\n// =============================================================================\n\ninterface ValidationDiagnostic {\n  severity: 'error' | 'warning' | 'info';\n  code: string;\n  message: string;\n  source?: string; // trait or block name\n  suggestion?: string;\n}\n\ninterface ValidationResult {\n  valid: boolean;\n  diagnostics: ValidationDiagnostic[];\n  stats: {\n    totalTraits: number;\n    totalObjects: number;\n    totalDomainBlocks: number;\n    domainsUsed: string[];\n    constraintsChecked: number;\n  };\n}\n\n// Domain → expected traits mapping for coherence checking\nconst DOMAIN_TRAIT_MAP: Record<string, string[]> = {\n  service: [\n    'service',\n    'endpoint',\n    'route',\n    'handler',\n    'middleware',\n    'api_gateway',\n    'load_balancer',\n    'service_discovery',\n    'cors_policy',\n    'rate_limiter',\n    'rest_resource',\n    'health_endpoint',\n    'graphql_resolver',\n    'webhook_sender',\n    'webhook_receiver',\n  ],\n  data: [\n    'db',\n    'model',\n    'query',\n    'migration',\n    'cache',\n    'repository',\n    'transaction',\n    'event_store',\n    'cursor_pagination',\n    'soft_delete',\n    'audit_column',\n  ],\n  contract: [\n    'contract',\n    'schema',\n    'validator',\n    'serializer',\n    'json_schema',\n    'openapi_path',\n    'schema_evolution',\n    'dto',\n  ],\n  pipeline: [\n    'stream',\n    'queue',\n    'worker',\n    'scheduler',\n    'message_broker',\n    'idempotent_consumer',\n    'saga_orchestrator',\n    'pipeline',\n  ],\n  container: [\n    'container',\n    'deployment',\n    'scaling',\n    'secret',\n    'dockerfile',\n    'kubernetes_pod',\n    'helm_chart',\n  ],\n  metric: ['metric', 'trace', 'log', 'health_check', 'structured_log', 'span', 'slo', 'alert_rule'],\n  resilience: [\n    'circuit_breaker',\n    'retry',\n    'timeout',\n    'fallback',\n    'bulkhead',\n    'exponential_backoff',\n    'canary_release',\n    'blue_green_deploy',\n  ],\n  network: ['http', 'websocket', 'grpc', 'graphql', 'tls_config', 'jwt_config', 'oauth2_config'],\n};\n\n// =============================================================================\n// VALIDATION ENGINE\n// =============================================================================\n\n/**\n * Extract all traits from a composition (objects + domain blocks).\n */\nfunction extractAllTraits(composition: HoloComposition): {\n  objectTraits: Map<string, string[]>; // objectName → traits[]\n  domainBlockTraits: Map<string, { domain: HoloDomainType; traits: string[] }>;\n  allTraits: string[];\n} {\n  const objectTraits = new Map<string, string[]>();\n  const domainBlockTraits = new Map<string, { domain: HoloDomainType; traits: string[] }>();\n  const allTraits: string[] = [];\n\n  // Extract from objects\n  if (composition.objects) {\n    for (const obj of composition.objects) {\n      const traits = extractObjectTraits(obj);\n      objectTraits.set(obj.name, traits);\n      allTraits.push(...traits);\n    }\n  }\n\n  // Extract from domain blocks\n  if (composition.domainBlocks) {\n    for (const block of composition.domainBlocks) {\n      const key = `${block.domain}:${block.name}`;\n      domainBlockTraits.set(key, { domain: block.domain, traits: block.traits || [] });\n      allTraits.push(...(block.traits || []));\n    }\n  }\n\n  return { objectTraits, domainBlockTraits, allTraits };\n}\n\n/**\n * Extract trait names from an object declaration.\n */\nfunction extractObjectTraits(obj: HoloObjectDecl): string[] {\n  const traits: string[] = [];\n  if (obj.traits) {\n    for (const t of obj.traits) {\n      // HoloObjectTrait has a .name property\n      if (typeof t === 'string') {\n        traits.push(t);\n      } else if (t && typeof t === 'object' && 'name' in t) {\n        traits.push((t as { name: string }).name);\n      }\n    }\n  }\n  return traits;\n}\n\n/**\n * Check all trait constraints (requires/conflicts/oneof) against a trait set.\n */\nfunction checkConstraints(\n  traitSet: string[],\n  sourceName: string,\n  constraints: TraitConstraint[]\n): ValidationDiagnostic[] {\n  const diagnostics: ValidationDiagnostic[] = [];\n  const traitSetLower = new Set(traitSet.map((t) => t.toLowerCase()));\n\n  for (const constraint of constraints) {\n    if (!traitSetLower.has(constraint.source.toLowerCase())) continue;\n\n    if (constraint.type === 'requires') {\n      for (const target of constraint.targets) {\n        if (!traitSetLower.has(target.toLowerCase())) {\n          diagnostics.push({\n            severity: 'error',\n            code: 'CONSTRAINT_REQUIRES',\n            message: `@${constraint.source} requires @${target}: ${constraint.message}`,\n            source: sourceName,\n            suggestion: `Add @${target} to ${sourceName}`,\n          });\n        }\n      }\n    } else if (constraint.type === 'conflicts') {\n      for (const target of constraint.targets) {\n        if (traitSetLower.has(target.toLowerCase())) {\n          diagnostics.push({\n            severity: 'error',\n            code: 'CONSTRAINT_CONFLICTS',\n            message: `@${constraint.source} conflicts with @${target}: ${constraint.message}`,\n            source: sourceName,\n            suggestion: `Remove either @${constraint.source} or @${target} from ${sourceName}`,\n          });\n        }\n      }\n    } else if (constraint.type === 'oneof') {\n      const present = constraint.targets.filter((t: any) => traitSetLower.has(t.toLowerCase()));\n      if (present.length > 1) {\n        diagnostics.push({\n          severity: 'error',\n          code: 'CONSTRAINT_ONEOF',\n          message: `Only one of [${constraint.targets.map((t: any) => '@' + t).join(', ')}] allowed: ${constraint.message}`,\n          source: sourceName,\n          suggestion: `Keep only one of: ${present.map((t: any) => '@' + t).join(', ')}`,\n        });\n      }\n    }\n  }\n\n  return diagnostics;\n}\n\n/**\n * Check domain block coherence — traits inside a domain block should belong to that domain.\n */\nfunction checkDomainCoherence(\n  domainBlockTraits: Map<string, { domain: HoloDomainType; traits: string[] }>\n): ValidationDiagnostic[] {\n  const diagnostics: ValidationDiagnostic[] = [];\n\n  for (const [key, { domain, traits }] of domainBlockTraits) {\n    const expectedTraits = DOMAIN_TRAIT_MAP[domain];\n    if (!expectedTraits) continue; // spatial domains don't have a strict trait list\n\n    for (const trait of traits) {\n      if (!expectedTraits.includes(trait.toLowerCase())) {\n        // Check if it belongs to a different v6 domain\n        let belongsToDomain: string | null = null;\n        for (const [d, dTraits] of Object.entries(DOMAIN_TRAIT_MAP)) {\n          if (dTraits.includes(trait.toLowerCase())) {\n            belongsToDomain = d;\n            break;\n          }\n        }\n\n        if (belongsToDomain) {\n          diagnostics.push({\n            severity: 'warning',\n            code: 'DOMAIN_COHERENCE',\n            message: `@${trait} in ${key} belongs to domain \"${belongsToDomain}\", not \"${domain}\"`,\n            source: key,\n            suggestion: `Move @${trait} to a \"${belongsToDomain}\" block, or keep it here if intentional`,\n          });\n        }\n      }\n    }\n  }\n\n  return diagnostics;\n}\n\n/**\n * Main validation function.\n */\nfunction validateComposition(code: string): ValidationResult {\n  const diagnostics: ValidationDiagnostic[] = [];\n\n  // Step 1: Parse (tolerant mode — AST may exist even when success=false)\n  const parseResult = parseHolo(code);\n\n  // Add parse errors as diagnostics\n  if (parseResult.errors?.length) {\n    for (const e of parseResult.errors) {\n      diagnostics.push({\n        severity: 'error',\n        code: 'PARSE_ERROR',\n        message: e.message,\n        source: e.loc ? `line ${e.loc.line}` : undefined,\n      });\n    }\n  }\n\n  // If no AST at all, return early\n  if (!parseResult.ast) {\n    return {\n      valid: false,\n      diagnostics,\n      stats: {\n        totalTraits: 0,\n        totalObjects: 0,\n        totalDomainBlocks: 0,\n        domainsUsed: [],\n        constraintsChecked: 0,\n      },\n    };\n  }\n\n  const composition = parseResult.ast;\n\n  // Step 2: Extract all traits\n  const { objectTraits, domainBlockTraits, allTraits } = extractAllTraits(composition);\n\n  // Step 3: Check object-level constraints\n  let constraintsChecked = 0;\n  for (const [name, traits] of objectTraits) {\n    const objDiags = checkConstraints(traits, name, BUILTIN_CONSTRAINTS);\n    diagnostics.push(...objDiags);\n    constraintsChecked += BUILTIN_CONSTRAINTS.length;\n  }\n\n  // Step 4: Check domain block constraints\n  for (const [key, { traits }] of domainBlockTraits) {\n    const blockDiags = checkConstraints(traits, key, BUILTIN_CONSTRAINTS);\n    diagnostics.push(...blockDiags);\n    constraintsChecked += BUILTIN_CONSTRAINTS.length;\n  }\n\n  // Step 5: Check domain coherence\n  const coherenceDiags = checkDomainCoherence(domainBlockTraits);\n  diagnostics.push(...coherenceDiags);\n\n  // Step 5.5: Advisory per-trait prop-schema check (enum/type) against schemas derived from the\n  // .holo trait tree. WARNINGS ONLY — these never flip `valid` (which stays !hasErrors). Traits\n  // with unresolved .holo-vs-.holo conflicts are suppressed so the advisory stream is high-signal.\n  try {\n    const propResult = PROP_SCHEMA_VALIDATOR.validateComposition(composition);\n    for (const err of propResult.errors) {\n      const traitName = (err as { traitName?: string }).traitName;\n      if (traitName && CONFLICTED_TRAITS.has(traitName)) continue;\n      diagnostics.push({\n        severity: 'warning',\n        code: String(err.code),\n        message: err.message,\n        source: traitName,\n        suggestion: (err as { suggestion?: string }).suggestion,\n      });\n    }\n  } catch {\n    // Advisory only — a prop-schema check failure must never break composition validation.\n  }\n\n  // Step 6: Collect domains used\n  const domainsUsed = new Set<string>();\n  if (composition.domainBlocks) {\n    for (const block of composition.domainBlocks) {\n      domainsUsed.add(block.domain);\n    }\n  }\n\n  const hasErrors = diagnostics.some((d) => d.severity === 'error');\n\n  return {\n    valid: !hasErrors,\n    diagnostics,\n    stats: {\n      totalTraits: allTraits.length,\n      totalObjects: composition.objects?.length || 0,\n      totalDomainBlocks: composition.domainBlocks?.length || 0,\n      domainsUsed: [...domainsUsed],\n      constraintsChecked,\n    },\n  };\n}\n\n// =============================================================================\n// HANDLER\n// =============================================================================\n\nexport async function handleValidationTool(\n  name: string,\n  args: Record<string, unknown>\n): Promise<unknown | null> {\n  if (name !== 'validate_composition') return null;\n\n  const code = args.code as string;\n  if (!code) {\n    return {\n      valid: false,\n      diagnostics: [\n        {\n          severity: 'error',\n          code: 'MISSING_INPUT',\n          message: 'The \"code\" parameter is required',\n        },\n      ],\n      stats: {\n        totalTraits: 0,\n        totalObjects: 0,\n        totalDomainBlocks: 0,\n        domainsUsed: [],\n        constraintsChecked: 0,\n      },\n    };\n  }\n\n  return validateComposition(code);\n}\n\n// =============================================================================\n// MCP TOOL DEFINITION\n// =============================================================================\n\nexport const validationTools: Tool[] = [\n  {\n    name: 'validate_composition',\n    description:\n      'Validate a .holo composition against trait constraints (requires/conflicts), ' +\n      'v6 domain coherence, and dependency rules. Returns diagnostics with suggestions.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        code: {\n          type: 'string',\n          description: 'The .holo composition source code to validate',\n        },\n      },\n      required: ['code'],\n    },\n  },\n];\n","/**\n * WorkflowMemory - durable Loro CRDT memory scoped to one workflow run.\n *\n * The MCP workflow engine is synchronous today, but multi-agent workflows often\n * span process/session boundaries. This store gives every run a named Loro doc\n * backed by a snapshot file so agents can share intermediate facts without\n * relying on the in-memory execute() context.\n */\n\nimport { createHash } from 'node:crypto';\nimport * as fs from 'node:fs';\nimport * as os from 'node:os';\nimport * as path from 'node:path';\nimport { LoroDoc } from 'loro-crdt';\n\nexport type WorkflowMemoryValueType =\n  | 'string'\n  | 'number'\n  | 'boolean'\n  | 'object'\n  | 'array'\n  | 'null'\n  | 'any';\n\nexport interface WorkflowMemoryFieldSchema {\n  type: WorkflowMemoryValueType;\n  description?: string;\n  required?: boolean;\n}\n\nexport type WorkflowMemorySchema = Record<string, WorkflowMemoryFieldSchema | WorkflowMemoryValueType>;\n\nexport interface WorkflowMemoryConfig {\n  enabled?: boolean;\n  runId?: string;\n  schema?: WorkflowMemorySchema;\n  assignedAgentIds?: string[];\n  gcOnCompletion?: boolean;\n  retentionMs?: number;\n}\n\nexport interface WorkflowMemoryEntry {\n  key: string;\n  value: unknown;\n  valueType: WorkflowMemoryValueType;\n  schemaType: WorkflowMemoryValueType;\n  writerAgentId: string;\n  updatedAt: string;\n  operationId: string;\n  sequence: number;\n}\n\nexport interface WorkflowMemoryEvent {\n  id: string;\n  type: 'write' | 'complete';\n  key?: string;\n  writerAgentId: string;\n  at: string;\n  sequence: number;\n}\n\ninterface PersistedWorkflowMemory {\n  schemaVersion: 'holoscript.workflow-memory.v1';\n  workflowRunId: string;\n  snapshotBase64: string;\n  schema: WorkflowMemorySchema;\n  assignedAgentIds: string[];\n  createdAt: string;\n  updatedAt: string;\n  completedAt?: string;\n}\n\nexport interface WorkflowMemoryReadResult {\n  success: true;\n  workflowRunId: string;\n  key?: string;\n  entries: Record<string, WorkflowMemoryEntry>;\n  entry?: WorkflowMemoryEntry;\n  totalKeys: number;\n  snapshotBase64?: string;\n  persisted: boolean;\n  storePath: string;\n}\n\nfunction defaultMemoryDir(): string {\n  return (\n    process.env.HOLOSCRIPT_WORKFLOW_MEMORY_DIR ||\n    path.join(process.env.HOLOSCRIPT_CACHE_DIR || path.join(os.homedir(), '.holoscript'), 'workflow-memory')\n  );\n}\n\nfunction safeRunId(value: unknown): string {\n  if (typeof value !== 'string' || !value.trim()) {\n    throw new Error('workflowRunId is required and must be a non-empty string.');\n  }\n  const runId = value.trim();\n  if (runId.length > 160) throw new Error('workflowRunId must be 160 characters or fewer.');\n  if (!/^[A-Za-z0-9._:@/-]+$/.test(runId)) {\n    throw new Error('workflowRunId contains unsupported characters.');\n  }\n  return runId;\n}\n\nfunction safeKey(value: unknown): string {\n  if (typeof value !== 'string' || !value.trim()) {\n    throw new Error('key is required and must be a non-empty string.');\n  }\n  const key = value.trim();\n  if (key.length > 160) throw new Error('key must be 160 characters or fewer.');\n  if (!/^[A-Za-z0-9._:@/-]+$/.test(key)) {\n    throw new Error('key contains unsupported characters.');\n  }\n  return key;\n}\n\nfunction safeAgentId(value: unknown): string {\n  if (typeof value === 'string' && value.trim()) return value.trim();\n  return 'unknown-agent';\n}\n\nfunction valueType(value: unknown): WorkflowMemoryValueType {\n  if (value === null) return 'null';\n  if (Array.isArray(value)) return 'array';\n  const type = typeof value;\n  if (type === 'string' || type === 'number' || type === 'boolean') return type;\n  if (type === 'object') return 'object';\n  throw new Error(`Unsupported workflow memory value type: ${type}`);\n}\n\nfunction normalizeSchema(schema?: WorkflowMemorySchema): WorkflowMemorySchema {\n  const normalized: WorkflowMemorySchema = {};\n  for (const [key, raw] of Object.entries(schema ?? {})) {\n    const safe = safeKey(key);\n    if (typeof raw === 'string') {\n      normalized[safe] = raw;\n    } else if (raw && typeof raw === 'object') {\n      normalized[safe] = {\n        type: raw.type ?? 'any',\n        description: raw.description,\n        required: raw.required === true,\n      };\n    }\n  }\n  return normalized;\n}\n\nfunction schemaTypeFor(schema: WorkflowMemorySchema, key: string): WorkflowMemoryValueType {\n  const raw = schema[key];\n  if (!raw) return 'any';\n  return typeof raw === 'string' ? raw : raw.type;\n}\n\nfunction assertSchemaValue(schema: WorkflowMemorySchema, key: string, value: unknown): WorkflowMemoryValueType {\n  const actual = valueType(value);\n  const expected = schemaTypeFor(schema, key);\n  if (expected !== 'any' && expected !== actual) {\n    throw new Error(`workflow memory key \"${key}\" expects ${expected}, got ${actual}.`);\n  }\n  return actual;\n}\n\nfunction assertJsonSerializable(value: unknown): void {\n  try {\n    JSON.stringify(value);\n  } catch (error) {\n    const message = error instanceof Error ? error.message : String(error);\n    throw new Error(`workflow memory value must be JSON-serializable: ${message}`);\n  }\n}\n\nfunction parseJsonRecord(raw: unknown): Record<string, string> {\n  if (!raw || typeof raw !== 'object') return {};\n  return raw as Record<string, string>;\n}\n\nfunction encodeSnapshot(doc: LoroDoc): string {\n  return Buffer.from(doc.export({ mode: 'snapshot' })).toString('base64');\n}\n\nfunction importSnapshot(doc: LoroDoc, snapshotBase64: string): void {\n  if (!snapshotBase64) return;\n  doc.import(new Uint8Array(Buffer.from(snapshotBase64, 'base64')));\n}\n\nfunction operationId(workflowRunId: string, key: string, sequence: number, value: unknown): string {\n  const digest = createHash('sha256')\n    .update(workflowRunId)\n    .update('\\0')\n    .update(key)\n    .update('\\0')\n    .update(String(sequence))\n    .update('\\0')\n    .update(JSON.stringify(value))\n    .digest('hex')\n    .slice(0, 16);\n  return `wmem_${sequence}_${digest}`;\n}\n\nfunction fileStem(workflowRunId: string): string {\n  const slug = workflowRunId.replace(/[^A-Za-z0-9._-]+/g, '_').slice(0, 72) || 'workflow';\n  const digest = createHash('sha256').update(workflowRunId).digest('hex').slice(0, 12);\n  return `${slug}_${digest}.json`;\n}\n\nexport class WorkflowMemoryDocument {\n  readonly workflowRunId: string;\n  readonly storePath: string;\n\n  private doc: LoroDoc;\n  private schema: WorkflowMemorySchema;\n  private assignedAgentIds: string[];\n  private createdAt: string;\n  private updatedAt: string;\n  private completedAt?: string;\n\n  constructor(\n    workflowRunId: string,\n    storePath: string,\n    options: { schema?: WorkflowMemorySchema; assignedAgentIds?: string[] } = {}\n  ) {\n    this.workflowRunId = safeRunId(workflowRunId);\n    this.storePath = storePath;\n    this.doc = new LoroDoc();\n    this.schema = normalizeSchema(options.schema);\n    this.assignedAgentIds = [...new Set(options.assignedAgentIds ?? [])];\n    this.createdAt = new Date().toISOString();\n    this.updatedAt = this.createdAt;\n    this.doc.getMap('entries');\n    this.doc.getList('events');\n  }\n\n  static load(\n    workflowRunId: string,\n    storePath: string,\n    persisted: PersistedWorkflowMemory,\n    options: { schema?: WorkflowMemorySchema; assignedAgentIds?: string[] } = {}\n  ): WorkflowMemoryDocument {\n    const memory = new WorkflowMemoryDocument(workflowRunId, storePath, {\n      schema: { ...persisted.schema, ...normalizeSchema(options.schema) },\n      assignedAgentIds: [...persisted.assignedAgentIds, ...(options.assignedAgentIds ?? [])],\n    });\n    importSnapshot(memory.doc, persisted.snapshotBase64);\n    memory.createdAt = persisted.createdAt;\n    memory.updatedAt = persisted.updatedAt;\n    memory.completedAt = persisted.completedAt;\n    return memory;\n  }\n\n  configure(options: { schema?: WorkflowMemorySchema; assignedAgentIds?: string[] } = {}): void {\n    this.schema = { ...this.schema, ...normalizeSchema(options.schema) };\n    this.assignedAgentIds = [\n      ...new Set([...this.assignedAgentIds, ...(options.assignedAgentIds ?? [])]),\n    ];\n  }\n\n  write(keyInput: unknown, value: unknown, writerAgentIdInput?: unknown): WorkflowMemoryEntry {\n    const key = safeKey(keyInput);\n    const writerAgentId = safeAgentId(writerAgentIdInput);\n    this.assertWriter(writerAgentId);\n    assertJsonSerializable(value);\n    const actualType = assertSchemaValue(this.schema, key, value);\n\n    const events = this.doc.getList('events');\n    const sequence = events.length + 1;\n    const updatedAt = new Date().toISOString();\n    const entry: WorkflowMemoryEntry = {\n      key,\n      value,\n      valueType: actualType,\n      schemaType: schemaTypeFor(this.schema, key),\n      writerAgentId,\n      updatedAt,\n      operationId: operationId(this.workflowRunId, key, sequence, value),\n      sequence,\n    };\n\n    this.doc.getMap('entries').set(key, JSON.stringify(entry));\n    const event: WorkflowMemoryEvent = {\n      id: entry.operationId,\n      type: 'write',\n      key,\n      writerAgentId,\n      at: updatedAt,\n      sequence,\n    };\n    events.insert(events.length, JSON.stringify(event));\n    this.doc.commit();\n    this.updatedAt = updatedAt;\n    return entry;\n  }\n\n  read(keyInput?: unknown): WorkflowMemoryReadResult {\n    const entries = this.entries();\n    if (keyInput !== undefined) {\n      const key = safeKey(keyInput);\n      return {\n        success: true,\n        workflowRunId: this.workflowRunId,\n        key,\n        entries: entries[key] ? { [key]: entries[key] } : {},\n        entry: entries[key],\n        totalKeys: entries[key] ? 1 : 0,\n        persisted: fs.existsSync(this.storePath),\n        storePath: this.storePath,\n      };\n    }\n    return {\n      success: true,\n      workflowRunId: this.workflowRunId,\n      entries,\n      totalKeys: Object.keys(entries).length,\n      persisted: fs.existsSync(this.storePath),\n      storePath: this.storePath,\n    };\n  }\n\n  subscribe(sinceCursorInput?: unknown, includeSnapshot = false): Record<string, unknown> {\n    const sinceCursor =\n      typeof sinceCursorInput === 'number' && Number.isFinite(sinceCursorInput)\n        ? Math.max(0, Math.floor(sinceCursorInput))\n        : 0;\n    const events = this.events().filter((event) => event.sequence > sinceCursor);\n    const nextCursor = events.length > 0 ? events[events.length - 1].sequence : sinceCursor;\n    return {\n      success: true,\n      workflowRunId: this.workflowRunId,\n      subscriptionId: `wmem_sub_${createHash('sha1')\n        .update(`${this.workflowRunId}:${sinceCursor}`)\n        .digest('hex')\n        .slice(0, 12)}`,\n      mode: 'cursor',\n      subscribeUrl: `workflow-memory://${encodeURIComponent(this.workflowRunId)}?cursor=${nextCursor}`,\n      cursor: sinceCursor,\n      nextCursor,\n      events,\n      eventCount: events.length,\n      ...(includeSnapshot ? { snapshotBase64: this.exportSnapshotBase64() } : {}),\n    };\n  }\n\n  complete(writerAgentIdInput?: unknown): Record<string, unknown> {\n    const writerAgentId = safeAgentId(writerAgentIdInput);\n    const events = this.doc.getList('events');\n    const sequence = events.length + 1;\n    const at = new Date().toISOString();\n    const event: WorkflowMemoryEvent = {\n      id: operationId(this.workflowRunId, '__complete__', sequence, at),\n      type: 'complete',\n      writerAgentId,\n      at,\n      sequence,\n    };\n    events.insert(events.length, JSON.stringify(event));\n    this.doc.commit();\n    this.updatedAt = at;\n    this.completedAt = at;\n    return {\n      workflowRunId: this.workflowRunId,\n      completedAt: at,\n      finalSnapshotBase64: this.exportSnapshotBase64(),\n      finalEventCursor: sequence,\n      totalKeys: Object.keys(this.entries()).length,\n    };\n  }\n\n  exportSnapshotBase64(): string {\n    return encodeSnapshot(this.doc);\n  }\n\n  toPersisted(): PersistedWorkflowMemory {\n    return {\n      schemaVersion: 'holoscript.workflow-memory.v1',\n      workflowRunId: this.workflowRunId,\n      snapshotBase64: this.exportSnapshotBase64(),\n      schema: this.schema,\n      assignedAgentIds: this.assignedAgentIds,\n      createdAt: this.createdAt,\n      updatedAt: this.updatedAt,\n      completedAt: this.completedAt,\n    };\n  }\n\n  private entries(): Record<string, WorkflowMemoryEntry> {\n    const raw = parseJsonRecord(this.doc.getMap('entries').toJSON());\n    const entries: Record<string, WorkflowMemoryEntry> = {};\n    for (const [key, value] of Object.entries(raw)) {\n      entries[key] = JSON.parse(value) as WorkflowMemoryEntry;\n    }\n    return entries;\n  }\n\n  private events(): WorkflowMemoryEvent[] {\n    const list = this.doc.getList('events');\n    const events: WorkflowMemoryEvent[] = [];\n    for (let index = 0; index < list.length; index += 1) {\n      const raw = list.get(index);\n      if (typeof raw === 'string') events.push(JSON.parse(raw) as WorkflowMemoryEvent);\n    }\n    return events;\n  }\n\n  private assertWriter(writerAgentId: string): void {\n    if (writerAgentId === 'execute_workflow' || writerAgentId === 'system') return;\n    if (this.assignedAgentIds.length === 0) return;\n    if (!this.assignedAgentIds.includes(writerAgentId)) {\n      throw new Error(`agent \"${writerAgentId}\" is not assigned to workflow \"${this.workflowRunId}\".`);\n    }\n  }\n}\n\nexport class WorkflowMemoryStore {\n  private cache = new Map<string, WorkflowMemoryDocument>();\n\n  constructor(private readonly rootDir = defaultMemoryDir()) {}\n\n  open(\n    workflowRunIdInput: unknown,\n    options: { schema?: WorkflowMemorySchema; assignedAgentIds?: string[] } = {}\n  ): WorkflowMemoryDocument {\n    const workflowRunId = safeRunId(workflowRunIdInput);\n    const storePath = this.pathFor(workflowRunId);\n    const cached = this.cache.get(workflowRunId);\n    if (cached) {\n      cached.configure(options);\n      return cached;\n    }\n\n    let document: WorkflowMemoryDocument;\n    if (fs.existsSync(storePath)) {\n      const persisted = JSON.parse(fs.readFileSync(storePath, 'utf8')) as PersistedWorkflowMemory;\n      document = WorkflowMemoryDocument.load(workflowRunId, storePath, persisted, options);\n    } else {\n      document = new WorkflowMemoryDocument(workflowRunId, storePath, options);\n    }\n    this.cache.set(workflowRunId, document);\n    return document;\n  }\n\n  write(args: {\n    workflowRunId: unknown;\n    key: unknown;\n    value: unknown;\n    writerAgentId?: unknown;\n    schema?: WorkflowMemorySchema;\n    assignedAgentIds?: string[];\n  }): { success: true; workflowRunId: string; entry: WorkflowMemoryEntry; storePath: string } {\n    const document = this.open(args.workflowRunId, {\n      schema: args.schema,\n      assignedAgentIds: args.assignedAgentIds,\n    });\n    const entry = document.write(args.key, args.value, args.writerAgentId);\n    this.persist(document);\n    return {\n      success: true,\n      workflowRunId: document.workflowRunId,\n      entry,\n      storePath: document.storePath,\n    };\n  }\n\n  read(args: {\n    workflowRunId: unknown;\n    key?: unknown;\n    includeSnapshot?: boolean;\n  }): WorkflowMemoryReadResult {\n    const document = this.open(args.workflowRunId);\n    const result = document.read(args.key);\n    return args.includeSnapshot\n      ? { ...result, snapshotBase64: document.exportSnapshotBase64() }\n      : result;\n  }\n\n  subscribe(args: {\n    workflowRunId: unknown;\n    sinceCursor?: unknown;\n    includeSnapshot?: boolean;\n  }): Record<string, unknown> {\n    const document = this.open(args.workflowRunId);\n    return document.subscribe(args.sinceCursor, args.includeSnapshot === true);\n  }\n\n  complete(args: {\n    workflowRunId: unknown;\n    writerAgentId?: unknown;\n    gc?: boolean;\n  }): Record<string, unknown> {\n    const document = this.open(args.workflowRunId);\n    const result = document.complete(args.writerAgentId);\n    this.persist(document);\n    if (args.gc !== false) this.gc(document.workflowRunId);\n    return { success: true, ...result, gc: args.gc !== false };\n  }\n\n  persist(document: WorkflowMemoryDocument): void {\n    fs.mkdirSync(this.rootDir, { recursive: true });\n    fs.writeFileSync(document.storePath, `${JSON.stringify(document.toPersisted(), null, 2)}\\n`);\n  }\n\n  gc(workflowRunIdInput: unknown): boolean {\n    const workflowRunId = safeRunId(workflowRunIdInput);\n    this.cache.delete(workflowRunId);\n    const storePath = this.pathFor(workflowRunId);\n    if (fs.existsSync(storePath)) {\n      fs.rmSync(storePath, { force: true });\n      return true;\n    }\n    return false;\n  }\n\n  pathFor(workflowRunIdInput: unknown): string {\n    const workflowRunId = safeRunId(workflowRunIdInput);\n    return path.join(this.rootDir, fileStem(workflowRunId));\n  }\n}\n\nlet defaultStore: WorkflowMemoryStore | null = null;\n\nexport function getWorkflowMemoryStore(): WorkflowMemoryStore {\n  if (!defaultStore) defaultStore = new WorkflowMemoryStore();\n  return defaultStore;\n}\n\nexport function setWorkflowMemoryStoreForTest(store: WorkflowMemoryStore | null): void {\n  defaultStore = store;\n}\n\nexport function normalizeWorkflowMemoryConfig(\n  raw: unknown,\n  fallbackRunId: string\n): Required<Pick<WorkflowMemoryConfig, 'enabled' | 'runId' | 'gcOnCompletion'>> &\n  Omit<WorkflowMemoryConfig, 'enabled' | 'runId' | 'gcOnCompletion'> {\n  const input = raw && typeof raw === 'object' ? (raw as WorkflowMemoryConfig) : {};\n  const enabled = input.enabled === true || Boolean(input.runId || input.schema);\n  return {\n    enabled,\n    runId: input.runId ? safeRunId(input.runId) : fallbackRunId,\n    schema: normalizeSchema(input.schema),\n    assignedAgentIds: Array.isArray(input.assignedAgentIds)\n      ? input.assignedAgentIds.filter((id): id is string => typeof id === 'string' && id.trim().length > 0)\n      : [],\n    gcOnCompletion: input.gcOnCompletion !== false,\n    retentionMs: typeof input.retentionMs === 'number' ? input.retentionMs : undefined,\n  };\n}\n","/**\n * HoloScript MCP Agent Orchestration Tools\n *\n * 5 MCP tools for LLM-driven multi-agent coordination:\n * - discover_agents: Find agents by capability/domain/tags\n * - delegate_task: Send a task to a discovered agent\n * - get_task_status: Check status of a delegated task\n * - compose_workflow: Define and validate a skill workflow DAG\n * - execute_workflow: Run a validated workflow\n * - workflow_memory_*: Durable Loro CRDT memory scoped to a workflow run\n *\n * Part of HoloScript v5.5 \"Agents as Universal Orchestrators\".\n *\n * @version 1.0.0\n * @package @holoscript/mcp-server\n */\n\nimport type { Tool } from '@modelcontextprotocol/sdk/types.js';\nimport {\n  AgentRegistry,\n  getDefaultRegistry,\n  FederatedRegistryAdapter,\n  TaskDelegationService,\n  SkillWorkflowEngine,\n  type WorkflowDefinition,\n  type WorkflowStep,\n  type WorkflowInput,\n  type CapabilityQuery,\n} from '@holoscript/framework/agents';\nimport {\n  getWorkflowMemoryStore,\n  normalizeWorkflowMemoryConfig,\n  type WorkflowMemorySchema,\n} from './workflow-memory';\n\n// =============================================================================\n// TOOL DEFINITIONS\n// =============================================================================\n\nexport const agentOrchestrationTools: Tool[] = [\n  {\n    name: 'discover_agents',\n    description:\n      'Find agents by capability, domain, or tag. Searches local registry and optional remote URLs.',\n    inputSchema: {\n      type: 'object' as const,\n      properties: {\n        type: {\n          type: 'string',\n          description:\n            'Capability type filter: render, analyze, generate, transform, validate, orchestrate, etc.',\n        },\n        domain: {\n          type: 'string',\n          description:\n            'Domain filter: spatial, nlp, vision, blockchain, physics, gaming, general, etc.',\n        },\n        tags: {\n          type: 'array',\n          items: { type: 'string' },\n          description: 'Required tags the agent must have.',\n        },\n        seedUrls: {\n          type: 'array',\n          items: { type: 'string' },\n          description: 'Additional /.well-known/agent-card.json URLs to check.',\n        },\n        limit: {\n          type: 'number',\n          description: 'Maximum results to return (default 10).',\n        },\n        includeOffline: {\n          type: 'boolean',\n          description: 'Whether to include offline agents (default false).',\n        },\n      },\n    },\n  },\n  {\n    name: 'delegate_task',\n    description:\n      'Send a task to a discovered agent. Auto-selects the best agent if agentId is omitted.',\n    inputSchema: {\n      type: 'object' as const,\n      properties: {\n        agentId: {\n          type: 'string',\n          description:\n            'Target agent ID (from discover_agents). Omit for auto-selection by capability.',\n        },\n        skillId: {\n          type: 'string',\n          description: 'Skill/tool name to invoke on the target agent.',\n        },\n        arguments: {\n          type: 'object',\n          description: 'Arguments to pass to the skill.',\n        },\n        type: {\n          type: 'string',\n          description: 'Required capability type for auto-selection (when agentId is omitted).',\n        },\n        domain: {\n          type: 'string',\n          description: 'Required domain for auto-selection (when agentId is omitted).',\n        },\n        timeout: {\n          type: 'number',\n          description: 'Timeout in ms (default 30000).',\n        },\n        retries: {\n          type: 'number',\n          description: 'Number of retries on failure (default 0).',\n        },\n      },\n      required: ['skillId', 'arguments'],\n    },\n  },\n  {\n    name: 'get_task_status',\n    description: 'Check the status of a previously delegated task by its task ID.',\n    inputSchema: {\n      type: 'object' as const,\n      properties: {\n        taskId: {\n          type: 'string',\n          description: 'Task ID returned by delegate_task.',\n        },\n      },\n      required: ['taskId'],\n    },\n  },\n  {\n    name: 'compose_workflow',\n    description:\n      'Define and validate a multi-step skill workflow (DAG), optionally with durable workflow memory.',\n    inputSchema: {\n      type: 'object' as const,\n      properties: {\n        name: {\n          type: 'string',\n          description: 'Workflow name.',\n        },\n        steps: {\n          type: 'array',\n          items: {\n            type: 'object',\n            properties: {\n              id: { type: 'string', description: 'Unique step identifier.' },\n              skillId: { type: 'string', description: 'Skill/tool to invoke.' },\n              inputs: {\n                type: 'object',\n                description:\n                  'Input mapping. Values can be {type:\"literal\",value:...}, {type:\"ref\",stepId:\"...\",outputKey:\"...\"}, or {type:\"context\",key:\"...\"}.',\n              },\n              dependsOn: {\n                type: 'array',\n                items: { type: 'string' },\n                description: 'Step IDs that must complete first.',\n              },\n              timeout: {\n                type: 'number',\n                description: 'Per-step timeout in ms.',\n              },\n              onError: {\n                type: 'string',\n                enum: ['fail', 'skip', 'fallback'],\n                description: 'Error handling: fail (default), skip, or fallback.',\n              },\n              fallbackSkillId: {\n                type: 'string',\n                description: 'Fallback skill if primary fails (when onError=fallback).',\n              },\n            },\n            required: ['id', 'skillId'],\n          },\n          description: 'Workflow steps with optional dependencies.',\n        },\n        description: {\n          type: 'string',\n          description: 'Optional workflow description.',\n        },\n        workflowMemory: {\n          type: 'object',\n          description:\n            'Optional durable shared memory config: {enabled, runId, schema, assignedAgentIds, gcOnCompletion}.',\n        },\n      },\n      required: ['name', 'steps'],\n    },\n  },\n  {\n    name: 'execute_workflow', // THIN (ratchet P4): dry-run by default. No toolExecutor wired unless MCP caller provides one; steps return dry-run stubs.\n    description:\n      'Execute a skill workflow. Each step invokes a local MCP tool. Returns results from every step.',\n    inputSchema: {\n      type: 'object' as const,\n      properties: {\n        name: {\n          type: 'string',\n          description: 'Workflow name.',\n        },\n        steps: {\n          type: 'array',\n          items: {\n            type: 'object',\n            properties: {\n              id: { type: 'string' },\n              skillId: { type: 'string' },\n              inputs: { type: 'object' },\n              dependsOn: { type: 'array', items: { type: 'string' } },\n              timeout: { type: 'number' },\n              onError: { type: 'string' },\n              fallbackSkillId: { type: 'string' },\n            },\n            required: ['id', 'skillId'],\n          },\n        },\n        context: {\n          type: 'object',\n          description: 'Initial context data passed to the workflow.',\n        },\n        workflowMemory: {\n          type: 'object',\n          description:\n            'Optional durable shared memory config: {enabled, runId, schema, assignedAgentIds, gcOnCompletion}.',\n        },\n      },\n      required: ['name', 'steps'],\n    },\n  },\n  {\n    name: 'workflow_memory_write',\n    description:\n      'Write a typed value to durable Loro workflow memory for one workflow run.',\n    inputSchema: {\n      type: 'object' as const,\n      properties: {\n        workflowRunId: { type: 'string', description: 'Workflow run ID that owns this memory.' },\n        key: { type: 'string', description: 'Memory key to write.' },\n        value: { description: 'JSON-serializable value.' },\n        agentId: { type: 'string', description: 'Writing agent ID.' },\n        schema: { type: 'object', description: 'Optional key schema, e.g. {facts:{type:\"array\"}}.' },\n        assignedAgentIds: {\n          type: 'array',\n          items: { type: 'string' },\n          description: 'Optional write allowlist for agents assigned to this run.',\n        },\n      },\n      required: ['workflowRunId', 'key', 'value'],\n    },\n  },\n  {\n    name: 'workflow_memory_read',\n    description:\n      'Read one key or the full durable Loro workflow memory snapshot for a run.',\n    inputSchema: {\n      type: 'object' as const,\n      properties: {\n        workflowRunId: { type: 'string', description: 'Workflow run ID that owns this memory.' },\n        key: { type: 'string', description: 'Optional memory key to read.' },\n        includeSnapshot: { type: 'boolean', description: 'Include base64 Loro snapshot bytes.' },\n      },\n      required: ['workflowRunId'],\n    },\n  },\n  {\n    name: 'workflow_memory_subscribe',\n    description:\n      'Return cursor-based workflow memory events and a subscription manifest for a run.',\n    inputSchema: {\n      type: 'object' as const,\n      properties: {\n        workflowRunId: { type: 'string', description: 'Workflow run ID that owns this memory.' },\n        sinceCursor: { type: 'number', description: 'Return events after this sequence cursor.' },\n        includeSnapshot: { type: 'boolean', description: 'Include base64 Loro snapshot bytes.' },\n      },\n      required: ['workflowRunId'],\n    },\n  },\n];\n\n// =============================================================================\n// SINGLETON INSTANCES\n// =============================================================================\n\nlet adapter: FederatedRegistryAdapter | null = null;\nlet delegator: TaskDelegationService | null = null;\nconst workflowEngine = new SkillWorkflowEngine();\n\nfunction getAdapter(): FederatedRegistryAdapter {\n  if (!adapter) {\n    adapter = new FederatedRegistryAdapter(getDefaultRegistry());\n  }\n  return adapter;\n}\n\nfunction getDelegator(): TaskDelegationService {\n  if (!delegator) {\n    delegator = new TaskDelegationService(getDefaultRegistry(), getAdapter());\n  }\n  return delegator;\n}\n\n// =============================================================================\n// HANDLER\n// =============================================================================\n\n/**\n * Handle agent orchestration tool calls.\n *\n * @param name Tool name\n * @param args Tool arguments\n * @param toolExecutor Optional local tool executor for workflow execution\n * @returns Result or null if tool not handled\n */\nexport async function handleAgentOrchestrationTool(\n  name: string,\n  args: Record<string, unknown>,\n  toolExecutor?: (toolName: string, toolArgs: Record<string, unknown>) => Promise<unknown>\n): Promise<unknown | null> {\n  switch (name) {\n    case 'discover_agents':\n      return handleDiscoverAgents(args);\n    case 'delegate_task':\n      return handleDelegateTask(args);\n    case 'get_task_status':\n      return handleGetTaskStatus(args);\n    case 'compose_workflow':\n      return handleComposeWorkflow(args);\n    case 'execute_workflow':\n      return handleExecuteWorkflow(args, toolExecutor);\n    case 'workflow_memory_write':\n      return handleWorkflowMemoryWrite(args);\n    case 'workflow_memory_read':\n      return handleWorkflowMemoryRead(args);\n    case 'workflow_memory_subscribe':\n      return handleWorkflowMemorySubscribe(args);\n    default:\n      return null;\n  }\n}\n\n// =============================================================================\n// INDIVIDUAL HANDLERS\n// =============================================================================\n\nasync function handleDiscoverAgents(args: Record<string, unknown>): Promise<unknown> {\n  const adapterInstance = getAdapter();\n\n  // Add dynamic seed URLs if provided\n  const seedUrls = args.seedUrls as string[] | undefined;\n  if (seedUrls) {\n    for (const url of seedUrls) {\n      adapterInstance.addSeedUrl(url);\n    }\n  }\n\n  const query: CapabilityQuery = {\n    type: (args.type as string) || undefined,\n    domain: (args.domain as string) || undefined,\n    tags: (args.tags as string[]) || undefined,\n    limit: (args.limit as number) || 10,\n    includeOffline: (args.includeOffline as boolean) || false,\n  };\n\n  const matches = await adapterInstance.discoverFederated(query);\n\n  return {\n    agents: matches.map((m) => ({\n      id: m.manifest.id,\n      name: m.manifest.name,\n      description: m.manifest.description,\n      version: m.manifest.version,\n      score: Math.round(m.score * 100) / 100,\n      capabilities: m.capabilities.map((c) => ({\n        type: c.capability.type,\n        domain: c.capability.domain,\n        name: c.capability.name,\n      })),\n      trust: m.manifest.trustLevel,\n      status: m.manifest.status,\n      tags: m.manifest.tags,\n      endpoint: m.manifest.endpoints[0]?.address,\n    })),\n    total: matches.length,\n    registrySize: getDefaultRegistry().size,\n  };\n}\n\nasync function handleDelegateTask(args: Record<string, unknown>): Promise<unknown> {\n  const delegatorInstance = getDelegator();\n\n  const skillId = args.skillId as string;\n  const skillArgs = (args.arguments as Record<string, unknown>) || {};\n\n  if (!skillId) {\n    return { error: 'Missing required parameter: skillId' };\n  }\n\n  if (args.agentId) {\n    // Direct delegation to specific agent\n    const result = await delegatorInstance.delegateTo({\n      targetAgentId: args.agentId as string,\n      skillId,\n      arguments: skillArgs,\n      timeout: args.timeout as number | undefined,\n      retries: args.retries as number | undefined,\n    });\n    return formatDelegationResult(result);\n  }\n\n  // Auto-delegation by capability\n  const query: CapabilityQuery = {};\n  if (args.type) query.type = args.type as string;\n  if (args.domain) query.domain = args.domain as string;\n\n  const result = await delegatorInstance.autoDelegate(query, skillId, skillArgs, {\n    timeout: args.timeout as number | undefined,\n    retries: args.retries as number | undefined,\n  });\n  return formatDelegationResult(result);\n}\n\nasync function handleGetTaskStatus(args: Record<string, unknown>): Promise<unknown> {\n  const taskId = args.taskId as string;\n  if (!taskId) {\n    return { error: 'Missing required parameter: taskId' };\n  }\n\n  const delegatorInstance = getDelegator();\n  const result = delegatorInstance.getStatus(taskId);\n\n  if (!result) {\n    return {\n      taskId,\n      status: 'not_found',\n      message:\n        'Task not found in delegation history. It may have been evicted from the history buffer.',\n    };\n  }\n\n  return formatDelegationResult(result);\n}\n\nasync function handleComposeWorkflow(args: Record<string, unknown>): Promise<unknown> {\n  const name = args.name as string;\n  const rawSteps = args.steps as Array<Record<string, unknown>>;\n\n  if (!name || !rawSteps || rawSteps.length === 0) {\n    return { valid: false, errors: ['Missing required parameters: name and steps'] };\n  }\n\n  const steps = normalizeSteps(rawSteps);\n  const definition: WorkflowDefinition = {\n    id: `wf-${Date.now()}`,\n    name,\n    description: args.description as string | undefined,\n    steps,\n  };\n  const workflowMemory = normalizeWorkflowMemoryConfig(args.workflowMemory, definition.id);\n\n  const validation = workflowEngine.validate(definition);\n\n  return {\n    valid: validation.valid,\n    errors: validation.errors,\n    warnings: validation.warnings,\n    executionPlan: validation.executionPlan,\n    stepCount: steps.length,\n    ...(workflowMemory.enabled\n      ? {\n          workflowMemory: {\n            enabled: true,\n            runId: workflowMemory.runId,\n            schemaKeys: Object.keys(workflowMemory.schema ?? {}),\n            assignedAgentIds: workflowMemory.assignedAgentIds,\n            gcOnCompletion: workflowMemory.gcOnCompletion,\n          },\n        }\n      : {}),\n  };\n}\n\nasync function handleExecuteWorkflow(\n  args: Record<string, unknown>,\n  toolExecutor?: (toolName: string, toolArgs: Record<string, unknown>) => Promise<unknown>\n): Promise<unknown> {\n  const name = args.name as string;\n  const rawSteps = args.steps as Array<Record<string, unknown>>;\n  const context = (args.context as Record<string, unknown>) || {};\n\n  if (!name || !rawSteps || rawSteps.length === 0) {\n    return { status: 'failed', error: 'Missing required parameters: name and steps' };\n  }\n\n  const steps = normalizeSteps(rawSteps);\n  const definition: WorkflowDefinition = {\n    id: `wf-${Date.now()}`,\n    name,\n    steps,\n    context,\n  };\n  const workflowMemory = normalizeWorkflowMemoryConfig(args.workflowMemory, definition.id);\n  const memoryStore = getWorkflowMemoryStore();\n  const memoryDocument = workflowMemory.enabled\n    ? memoryStore.open(workflowMemory.runId, {\n        schema: workflowMemory.schema,\n        assignedAgentIds: workflowMemory.assignedAgentIds,\n      })\n    : null;\n\n  // Validate first\n  const validation = workflowEngine.validate(definition);\n  if (!validation.valid) {\n    return {\n      status: 'failed',\n      error: 'Workflow validation failed',\n      validationErrors: validation.errors,\n    };\n  }\n\n  // Execute with the provided tool executor or a stub\n  const executor = toolExecutor\n    ? async (skillId: string, inputs: Record<string, unknown>) => {\n        const result = await toolExecutor(skillId, inputs);\n        return (typeof result === 'object' && result !== null ? result : { result }) as Record<\n          string,\n          unknown\n        >;\n      }\n    : async (skillId: string, inputs: Record<string, unknown>) => {\n        return {\n          skillId,\n          inputs,\n          note: 'No tool executor configured — dry run only',\n          dryRun: true,\n        };\n      };\n\n  const isDryRun = !toolExecutor;\n  if (memoryDocument) {\n    context.workflowMemory = {\n      runId: workflowMemory.runId,\n      readTool: 'workflow_memory_read',\n      writeTool: 'workflow_memory_write',\n      subscribeTool: 'workflow_memory_subscribe',\n    };\n    memoryStore.write({\n      workflowRunId: workflowMemory.runId,\n      key: '__workflow_context__',\n      value: context,\n      writerAgentId: 'execute_workflow',\n      schema: workflowMemory.schema,\n      assignedAgentIds: workflowMemory.assignedAgentIds,\n    });\n  }\n  const result = await workflowEngine.execute(definition, executor);\n  const workflowMemoryCompletion = memoryDocument\n    ? memoryStore.complete({\n        workflowRunId: workflowMemory.runId,\n        writerAgentId: 'execute_workflow',\n        gc: workflowMemory.gcOnCompletion,\n      })\n    : null;\n\n  return {\n    workflowId: result.workflowId,\n    status: isDryRun ? 'dry-run' : result.status,\n    dryRun: isDryRun || undefined,\n    totalDurationMs: result.totalDurationMs,\n    steps: result.stepResults.map((sr) => ({\n      stepId: sr.stepId,\n      status: sr.status,\n      durationMs: sr.durationMs,\n      output: sr.output,\n      error: sr.error,\n    })),\n    ...(workflowMemoryCompletion\n      ? {\n          workflowMemory: workflowMemoryCompletion,\n        }\n      : {}),\n    ...(isDryRun\n      ? {\n          message:\n            'No tool executor wired — steps returned dry-run stubs only. Wire a toolExecutor for real execution.',\n        }\n      : {}),\n  };\n}\n\nasync function handleWorkflowMemoryWrite(args: Record<string, unknown>): Promise<unknown> {\n  try {\n    return getWorkflowMemoryStore().write({\n      workflowRunId: args.workflowRunId,\n      key: args.key,\n      value: args.value,\n      writerAgentId: args.agentId,\n      schema: args.schema as WorkflowMemorySchema | undefined,\n      assignedAgentIds: Array.isArray(args.assignedAgentIds)\n        ? (args.assignedAgentIds as unknown[]).filter(\n            (id): id is string => typeof id === 'string' && id.trim().length > 0\n          )\n        : undefined,\n    });\n  } catch (error) {\n    return { success: false, error: error instanceof Error ? error.message : String(error) };\n  }\n}\n\nasync function handleWorkflowMemoryRead(args: Record<string, unknown>): Promise<unknown> {\n  try {\n    return getWorkflowMemoryStore().read({\n      workflowRunId: args.workflowRunId,\n      key: args.key,\n      includeSnapshot: args.includeSnapshot === true,\n    });\n  } catch (error) {\n    return { success: false, error: error instanceof Error ? error.message : String(error) };\n  }\n}\n\nasync function handleWorkflowMemorySubscribe(args: Record<string, unknown>): Promise<unknown> {\n  try {\n    return getWorkflowMemoryStore().subscribe({\n      workflowRunId: args.workflowRunId,\n      sinceCursor: args.sinceCursor,\n      includeSnapshot: args.includeSnapshot === true,\n    });\n  } catch (error) {\n    return { success: false, error: error instanceof Error ? error.message : String(error) };\n  }\n}\n\n// =============================================================================\n// HELPERS\n// =============================================================================\n\nfunction formatDelegationResult(result: {\n  taskId: string;\n  status: string;\n  result?: unknown;\n  error?: string;\n  durationMs: number;\n  delegatedTo: { agentId: string; endpoint: string };\n}) {\n  return {\n    taskId: result.taskId,\n    status: result.status,\n    result: result.result,\n    error: result.error,\n    durationMs: result.durationMs,\n    delegatedTo: result.delegatedTo,\n  };\n}\n\n/**\n * Normalize raw step objects from MCP input into WorkflowStep types.\n * MCP inputs are plain JSON — need to ensure proper typing.\n */\nfunction normalizeSteps(rawSteps: Array<Record<string, unknown>>): WorkflowStep[] {\n  return rawSteps.map((raw) => {\n    const inputs: Record<string, WorkflowInput> = {};\n\n    if (raw.inputs && typeof raw.inputs === 'object') {\n      for (const [key, val] of Object.entries(raw.inputs as Record<string, unknown>)) {\n        if (typeof val === 'object' && val !== null && 'type' in val) {\n          inputs[key] = val as WorkflowInput;\n        } else {\n          // Treat as literal value\n          inputs[key] = { type: 'literal', value: val };\n        }\n      }\n    }\n\n    return {\n      id: raw.id as string,\n      skillId: raw.skillId as string,\n      inputs,\n      dependsOn: raw.dependsOn as string[] | undefined,\n      timeout: raw.timeout as number | undefined,\n      onError: raw.onError as 'fail' | 'skip' | 'fallback' | undefined,\n      fallbackSkillId: raw.fallbackSkillId as string | undefined,\n    };\n  });\n}\n\n/**\n * Reset singletons (for testing).\n */\nexport function resetOrchestrationSingletons(): void {\n  if (adapter) {\n    adapter.stopPolling();\n  }\n  adapter = null;\n  delegator = null;\n}\n","/**\n * JWK Thumbprint Calculation (RFC 7638)\n *\n * Computes the JWK SHA-256 thumbprint for RSA, EC, and OKP (Ed25519/Ed448)\n * public keys.  Uses only Node.js built-in `crypto` — zero external deps.\n *\n * The thumbprint is the base64url-encoded SHA-256 hash of the canonical\n * (alphabetically-sorted, minimal) JSON representation of the key's required\n * members as defined in RFC 7638 §3.2.\n *\n * @see https://datatracker.ietf.org/doc/html/rfc7638\n * @version 1.0.0\n */\n\nimport * as crypto from 'crypto';\n\n/**\n * Supported JWK key types for thumbprint calculation.\n */\nexport type JwkKeyType = 'RSA' | 'EC' | 'OKP';\n\n/**\n * Minimal JWK representation used for thumbprint computation.\n * Only the required members per key type are included (RFC 7638 §3.2).\n */\nexport interface CanonicalJwk {\n  /** Key type */\n  kty: JwkKeyType;\n  /** RSA modulus (base64url) — required for RSA */\n  n?: string;\n  /** RSA public exponent (base64url) — required for RSA */\n  e?: string;\n  /** EC/OKP curve name — required for EC and OKP */\n  crv?: string;\n  /** EC/OKP x coordinate (base64url) — required for EC and OKP */\n  x?: string;\n  /** EC y coordinate (base64url) — required for EC */\n  y?: string;\n}\n\n/**\n * Calculate the JWK thumbprint (RFC 7638) of a public key given in PEM format.\n *\n * Supports:\n *  - RSA (any modulus length)\n *  - EC  (P-256 / P-384 / P-521)\n *  - OKP (Ed25519 / Ed448 / X25519 / X448)\n *\n * @param publicKeyPem  PEM-encoded public key (SPKI format)\n * @returns base64url-encoded SHA-256 thumbprint\n * @throws if the key type is unsupported or the PEM cannot be parsed\n */\nexport function calculateJwkThumbprint(publicKeyPem: string): string {\n  const keyObject = crypto.createPublicKey(publicKeyPem);\n  const jwk = keyObject.export({ format: 'jwk' });\n\n  const canonical = buildCanonicalJwk(jwk as Record<string, unknown>);\n  const json = JSON.stringify(canonical);\n\n  return crypto.createHash('sha256').update(json).digest('base64url');\n}\n\n/**\n * Calculate the JWK thumbprint from a JWK object directly.\n *\n * @param jwk  JWK object with at least `kty` and the required members for\n *             the key type\n * @returns base64url-encoded SHA-256 thumbprint\n * @throws if the key type is unsupported or required members are missing\n */\nexport function calculateJwkThumbprintFromJwk(jwk: Record<string, unknown>): string {\n  const canonical = buildCanonicalJwk(jwk);\n  const json = JSON.stringify(canonical);\n\n  return crypto.createHash('sha256').update(json).digest('base64url');\n}\n\n/**\n * Verify that a PEM public key matches the expected JWK thumbprint.\n *\n * @param publicKeyPem  PEM-encoded public key\n * @param expectedThumbprint  Expected base64url SHA-256 thumbprint\n * @returns `true` if the computed thumbprint matches\n */\nexport function verifyJwkThumbprint(publicKeyPem: string, expectedThumbprint: string): boolean {\n  try {\n    const computed = calculateJwkThumbprint(publicKeyPem);\n    // Use timing-safe comparison to prevent side-channel leaks\n    const a = Buffer.from(computed, 'utf8');\n    const b = Buffer.from(expectedThumbprint, 'utf8');\n    if (a.length !== b.length) return false;\n    return crypto.timingSafeEqual(a, b);\n  } catch {\n    return false;\n  }\n}\n\n// ---------------------------------------------------------------------------\n// Internal helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Build the canonical JWK object for thumbprint computation.\n *\n * RFC 7638 §3.2 specifies the required members per key type, and they must\n * be serialised in lexicographic (alphabetical) order.\n *\n * @internal\n */\nfunction buildCanonicalJwk(jwk: Record<string, unknown>): CanonicalJwk {\n  const kty = jwk.kty as string | undefined;\n\n  switch (kty) {\n    case 'RSA': {\n      const e = jwk.e as string | undefined;\n      const n = jwk.n as string | undefined;\n      if (!e || !n) {\n        throw new Error('RSA JWK missing required members: e, n');\n      }\n      // Alphabetical: e, kty, n\n      return { e, kty: 'RSA', n };\n    }\n\n    case 'EC': {\n      const crv = jwk.crv as string | undefined;\n      const x = jwk.x as string | undefined;\n      const y = jwk.y as string | undefined;\n      if (!crv || !x || !y) {\n        throw new Error('EC JWK missing required members: crv, x, y');\n      }\n      // Alphabetical: crv, kty, x, y\n      return { crv, kty: 'EC', x, y };\n    }\n\n    case 'OKP': {\n      const crv = jwk.crv as string | undefined;\n      const x = jwk.x as string | undefined;\n      if (!crv || !x) {\n        throw new Error('OKP JWK missing required members: crv, x');\n      }\n      // Alphabetical: crv, kty, x\n      return { crv, kty: 'OKP', x };\n    }\n\n    default:\n      throw new Error(`Unsupported JWK key type: ${kty ?? '(undefined)'}`);\n  }\n}\n","/**\n * HoloScript Compiler Agent Identity Framework\n *\n * Cryptographic identity system for multi-agent compiler architecture based on\n * Agentic JWT specification (draft-goswami-agentic-jwt-00).\n *\n * Implements:\n * - Agent-specific JWT tokens with role-based access control (RBAC)\n * - Short-lived token rotation (24-hour lifecycle)\n * - Proof-of-Possession (PoP) using Ed25519 keys\n * - Agent checksum for deterministic identity\n * - Workflow-aware delegation chains\n *\n * @version 1.0.0\n * @see https://arxiv.org/html/2509.13597v1\n * @see https://datatracker.ietf.org/doc/html/draft-goswami-agentic-jwt-00\n */\n\nimport * as crypto from 'crypto';\nimport { promisify } from 'util';\nimport { calculateJwkThumbprint } from './JwkThumbprint';\nimport type { CulturalFamily, PromptDialect } from '../../traits/CultureTraits';\n\n// crypto.generateKeyPair is a Node.js-only API not present in browser polyfills.\n// Guard with a runtime check so the module can be imported in browser context\n// (e.g. for WorkflowStep / AgentRole enums) without crashing at load time.\nconst generateKeyPairAsync:\n  | ((type: string, options: object) => Promise<{ publicKey: string; privateKey: string }>)\n  | null =\n  typeof crypto.generateKeyPair === 'function'\n    ? (promisify(crypto.generateKeyPair) as unknown as (\n        type: string,\n        options: object\n      ) => Promise<{ publicKey: string; privateKey: string }>)\n    : null;\n\n/**\n * Agent roles in the HoloScript compiler pipeline\n */\nexport enum AgentRole {\n  /** Parses source code and builds abstract syntax tree (read-only) */\n  SYNTAX_ANALYZER = 'syntax_analyzer',\n\n  /** Optimizes AST through transformation passes (read/write AST) */\n  AST_OPTIMIZER = 'ast_optimizer',\n\n  /** Generates intermediate representation and target code (write code) */\n  CODE_GENERATOR = 'code_generator',\n\n  /** Exports final artifacts to target platforms (write output) */\n  EXPORTER = 'exporter',\n\n  /** Orchestrates the compilation pipeline (admin) */\n  ORCHESTRATOR = 'orchestrator',\n}\n\n/**\n * Permissions for agent operations\n */\nexport enum AgentPermission {\n  // Read permissions\n  READ_SOURCE = 'read:source',\n  READ_CONFIG = 'read:config',\n  READ_AST = 'read:ast',\n  READ_IR = 'read:ir',\n  READ_CODE = 'read:code',\n\n  // Write permissions\n  WRITE_AST = 'write:ast',\n  WRITE_IR = 'write:ir',\n  WRITE_CODE = 'write:code',\n  WRITE_OUTPUT = 'write:output',\n\n  // Transform permissions\n  TRANSFORM_AST = 'transform:ast',\n  TRANSFORM_IR = 'transform:ir',\n\n  // Execution permissions\n  EXECUTE_OPTIMIZATION = 'execute:optimization',\n  EXECUTE_CODEGEN = 'execute:codegen',\n  EXECUTE_EXPORT = 'execute:export',\n}\n\n/**\n * Workflow steps in the compilation pipeline\n */\nexport enum WorkflowStep {\n  PARSE_TOKENS = 'parse_tokens',\n  BUILD_AST = 'build_ast',\n  ANALYZE_AST = 'analyze_ast',\n  APPLY_TRANSFORMS = 'apply_transforms',\n  SELECT_INSTRUCTIONS = 'select_instructions',\n  GENERATE_ASSEMBLY = 'generate_assembly',\n  FORMAT_OUTPUT = 'format_output',\n  SERIALIZE = 'serialize',\n}\n\n/**\n * Cultural profile metadata for an agent.\n *\n * Carries the same dimensions as `CulturalProfileTrait` (cooperation_index,\n * cultural_family, prompt_dialect) so they can travel inside JWT tokens and\n * be validated by the compiler pipeline without re-parsing the composition.\n *\n * This is the *identity-layer* representation.  The trait-layer representation\n * (`CulturalProfileTrait`) additionally includes `norm_set`, which is\n * composition-level data and therefore not embedded in individual tokens.\n */\nexport interface CulturalProfileMetadata {\n  /** Willingness to cooperate, 0-1 (0 = adversarial, 1 = fully cooperative) */\n  cooperation_index: number;\n\n  /** Cultural family archetype */\n  cultural_family: CulturalFamily;\n\n  /** Prompt / communication dialect */\n  prompt_dialect: PromptDialect;\n}\n\n/**\n * Agent configuration used for checksum calculation\n */\nexport interface AgentConfig {\n  role: AgentRole;\n  name: string;\n  version: string;\n\n  /** Agent-specific prompt or system instructions */\n  prompt?: string;\n\n  /** Tools/capabilities available to this agent */\n  tools?: string[];\n\n  /** Configuration parameters */\n  configuration?: Record<string, unknown>;\n\n  /** Optional target scope (e.g., package path restriction) */\n  scope?: string;\n\n  /**\n   * Optional cultural profile metadata.\n   * When present, the compiler pipeline can validate cross-agent cultural\n   * compatibility without requiring explicit trait declarations in HoloScript.\n   */\n  culturalProfile?: CulturalProfileMetadata;\n}\n\n/**\n * Agent checksum for deterministic identity\n * Based on Agentic JWT specification Section 3.2\n */\nexport interface AgentChecksum {\n  /** SHA-256 hash of agent configuration */\n  hash: string;\n\n  /** Algorithm used (always 'sha256') */\n  algorithm: 'sha256';\n\n  /** Timestamp when checksum was calculated */\n  calculatedAt: string;\n\n  /** Human-readable label for debugging */\n  label: string;\n}\n\n/**\n * Intent token payload extending standard JWT\n * Based on Agentic JWT specification Section 4\n */\nexport interface IntentTokenPayload {\n  /** Standard JWT claims */\n  iss: string; // Issuer (orchestrator or IDP)\n  sub: string; // Subject (agent ID)\n  aud: string; // Audience (resource server)\n  exp: number; // Expiration time (Unix timestamp)\n  iat: number; // Issued at (Unix timestamp)\n  jti: string; // JWT ID (unique identifier)\n\n  /** Agent-specific claims */\n  agent_role: AgentRole;\n  agent_checksum: AgentChecksum;\n\n  /** Permissions granted to this agent */\n  permissions: AgentPermission[];\n\n  /** Scope restriction (e.g., package path) */\n  scope?: string;\n\n  /** Workflow metadata */\n  intent: {\n    workflow_id: string;\n    workflow_step: WorkflowStep;\n    executed_by: AgentRole;\n    initiated_by: AgentRole;\n    delegation_chain: AgentRole[];\n    execution_context?: Record<string, unknown>;\n  };\n\n  /**\n   * Cultural profile metadata embedded in the token.\n   * Allows the compiler to perform cultural compatibility checks\n   * using only token data, without re-reading the composition.\n   */\n  cultural_profile?: CulturalProfileMetadata;\n\n  /** Proof-of-Possession confirmation (JWK thumbprint) */\n  cnf?: {\n    jkt: string; // JWK SHA-256 thumbprint\n  };\n\n  /** Ed25519 public key for PoP verification (PEM format) */\n  publicKey?: string;\n}\n\n/**\n * Ed25519 key pair for Proof-of-Possession\n */\nexport interface AgentKeyPair {\n  publicKey: string; // PEM format\n  privateKey: string; // PEM format\n  kid: string; // Key ID (agent:role#timestamp)\n  thumbprint: string; // JWK SHA-256 thumbprint\n}\n\n/**\n * Calculate agent checksum from configuration\n *\n * Creates a deterministic SHA-256 hash of the agent's:\n * - Role and name\n * - Version\n * - Prompt/instructions\n * - Available tools\n * - Configuration parameters\n *\n * This ensures agents with identical configuration receive the same checksum,\n * enabling detection of configuration drift.\n */\nexport function calculateAgentChecksum(config: AgentConfig): AgentChecksum {\n  const canonical = {\n    role: config.role,\n    name: config.name,\n    version: config.version,\n    prompt: config.prompt || '',\n    tools: (config.tools || []).sort(), // Sort for determinism\n    configuration: config.configuration || {},\n    culturalProfile: config.culturalProfile || null,\n  };\n\n  const serialized = JSON.stringify(canonical);\n  const hash = crypto.createHash('sha256').update(serialized).digest('hex');\n\n  return {\n    hash,\n    algorithm: 'sha256',\n    calculatedAt: new Date().toISOString(),\n    label: `${config.role}:${config.name}:${config.version}`,\n  };\n}\n\n/**\n * Generate Ed25519 key pair for Proof-of-Possession\n *\n * Creates ephemeral keys for agent-specific request signing.\n * Keys should be rotated with token expiration (24 hours default).\n */\nexport async function generateAgentKeyPair(\n  agentRole: AgentRole,\n  timestamp?: Date\n): Promise<AgentKeyPair> {\n  if (!generateKeyPairAsync) {\n    throw new Error(\n      'crypto.generateKeyPair is unavailable in this environment (browser). Key pair generation requires a Node.js runtime.'\n    );\n  }\n  const { publicKey, privateKey } = await generateKeyPairAsync('ed25519', {\n    publicKeyEncoding: {\n      type: 'spki',\n      format: 'pem',\n    },\n    privateKeyEncoding: {\n      type: 'pkcs8',\n      format: 'pem',\n    },\n  });\n\n  const ts = timestamp || new Date();\n  const kid = `agent:${agentRole}#${ts.toISOString()}`;\n\n  // Calculate JWK thumbprint (SHA-256 of canonical JWK per RFC 7638)\n  const thumbprint = calculateJwkThumbprint(publicKey);\n\n  return {\n    publicKey,\n    privateKey,\n    kid,\n    thumbprint,\n  };\n}\n\n/**\n * Role-based access control matrix\n *\n * Defines default permissions for each agent role in the compiler pipeline.\n */\nexport const ROLE_PERMISSIONS: Record<AgentRole, AgentPermission[]> = {\n  [AgentRole.SYNTAX_ANALYZER]: [\n    AgentPermission.READ_SOURCE,\n    AgentPermission.READ_CONFIG,\n    AgentPermission.WRITE_AST,\n  ],\n\n  [AgentRole.AST_OPTIMIZER]: [\n    AgentPermission.READ_AST,\n    AgentPermission.READ_CONFIG,\n    AgentPermission.WRITE_AST,\n    AgentPermission.TRANSFORM_AST,\n    AgentPermission.EXECUTE_OPTIMIZATION,\n  ],\n\n  [AgentRole.CODE_GENERATOR]: [\n    AgentPermission.READ_AST,\n    AgentPermission.READ_IR,\n    AgentPermission.READ_CONFIG,\n    AgentPermission.WRITE_IR,\n    AgentPermission.WRITE_CODE,\n    AgentPermission.TRANSFORM_IR,\n    AgentPermission.EXECUTE_CODEGEN,\n  ],\n\n  [AgentRole.EXPORTER]: [\n    AgentPermission.READ_CODE,\n    AgentPermission.READ_CONFIG,\n    AgentPermission.WRITE_OUTPUT,\n    AgentPermission.EXECUTE_EXPORT,\n  ],\n\n  [AgentRole.ORCHESTRATOR]: [\n    // Orchestrator has all permissions\n    ...Object.values(AgentPermission),\n  ],\n};\n\n/**\n * Workflow step sequences for validation\n *\n * Defines valid transitions between compilation phases.\n * Used to prevent agents from executing out-of-sequence operations.\n */\nexport const WORKFLOW_SEQUENCES: Record<WorkflowStep, WorkflowStep[]> = {\n  [WorkflowStep.PARSE_TOKENS]: [WorkflowStep.BUILD_AST],\n  [WorkflowStep.BUILD_AST]: [WorkflowStep.ANALYZE_AST],\n  [WorkflowStep.ANALYZE_AST]: [WorkflowStep.APPLY_TRANSFORMS],\n  [WorkflowStep.APPLY_TRANSFORMS]: [WorkflowStep.SELECT_INSTRUCTIONS],\n  [WorkflowStep.SELECT_INSTRUCTIONS]: [WorkflowStep.GENERATE_ASSEMBLY],\n  [WorkflowStep.GENERATE_ASSEMBLY]: [WorkflowStep.FORMAT_OUTPUT],\n  [WorkflowStep.FORMAT_OUTPUT]: [WorkflowStep.SERIALIZE],\n  [WorkflowStep.SERIALIZE]: [], // Terminal step\n};\n\n/**\n * Validate workflow step transition\n */\nexport function isValidWorkflowTransition(\n  currentStep: WorkflowStep,\n  nextStep: WorkflowStep\n): boolean {\n  const validNextSteps = WORKFLOW_SEQUENCES[currentStep];\n  return validNextSteps.includes(nextStep);\n}\n\n/**\n * Get default permissions for an agent role\n */\nexport function getDefaultPermissions(role: AgentRole): AgentPermission[] {\n  return [...ROLE_PERMISSIONS[role]];\n}\n\n/**\n * Check if agent has required permission\n */\nexport function hasPermission(permissions: AgentPermission[], required: AgentPermission): boolean {\n  // Check for exact permission or wildcard\n  return permissions.includes(required) || permissions.includes(AgentPermission.EXECUTE_CODEGEN);\n}\n\n/**\n * Validate agent can perform operation based on role and workflow step\n */\nexport function canPerformOperation(\n  role: AgentRole,\n  workflowStep: WorkflowStep,\n  requiredPermission: AgentPermission\n): boolean {\n  const rolePermissions = ROLE_PERMISSIONS[role];\n  return hasPermission(rolePermissions, requiredPermission);\n}\n","/**\n * HoloScript UCAN-Style Capability Token Interfaces\n *\n * Implements capability-based authorization following the UCAN (User Controlled\n * Authorization Networks) specification. Capability tokens enable decentralized,\n * attenuated delegation of permissions without requiring a central authority\n * for every access decision.\n *\n * Key concepts:\n * - **Capability Semantics**: Resource + action pairs (with/can pattern)\n * - **Attenuation**: Delegated tokens can only narrow, never widen parent scope\n * - **Proof chains**: Tokens carry cryptographic proof of their delegation lineage\n * - **Self-certifying**: Each token is signed by the issuer's Ed25519 key\n *\n * @version 1.0.0\n * @see https://ucan.xyz/\n * @see https://github.com/ucan-wg/spec\n */\n\nimport { AgentRole, AgentPermission } from './AgentIdentity';\n\n// ---------------------------------------------------------------------------\n// Capability Semantics (with / can pattern)\n// ---------------------------------------------------------------------------\n\n/**\n * A single capability grant following the UCAN \"with/can\" pattern.\n *\n * `with` identifies the resource (URI-style), `can` identifies the action\n * namespace, and `nb` (not-before caveats) carry additional constraints.\n *\n * @example\n * ```ts\n * const cap: Capability = {\n *   with: 'holoscript://packages/core/ast',\n *   can: 'ast/write',\n * };\n * ```\n */\nexport interface Capability {\n  /** Resource URI the capability applies to (e.g. \"holoscript://packages/core/ast\") */\n  with: string;\n\n  /** Action namespace (e.g. \"ast/read\", \"ast/write\", \"code/generate\") */\n  can: string;\n\n  /** Optional caveats / constraints narrowing this capability */\n  nb?: Record<string, unknown>;\n}\n\n/**\n * Semantics engine for evaluating whether one capability is a valid\n * attenuation (subset) of another.\n *\n * Implementations decide the resource hierarchy and action containment\n * rules for a particular domain.\n */\nexport interface CapabilitySemantics {\n  /**\n   * Return `true` if `child` is equal to or a strict subset of `parent`.\n   *\n   * This is the core attenuation check: a delegated capability must never\n   * grant more authority than its parent.\n   */\n  isSubsetOf(child: Capability, parent: Capability): boolean;\n\n  /**\n   * Return `true` if `capability` authorises the given resource + action pair.\n   */\n  canAccess(capability: Capability, resource: string, action: string): boolean;\n\n  /**\n   * Parse a HoloScript `AgentPermission` enum value into a `Capability`.\n   *\n   * Allows bridging between the legacy RBAC permission model and the new\n   * capability system.\n   */\n  fromPermission(permission: AgentPermission, scope?: string): Capability;\n}\n\n// ---------------------------------------------------------------------------\n// Capability Token (UCAN-aligned)\n// ---------------------------------------------------------------------------\n\n/**\n * UCAN capability token header.\n *\n * Based on the UCAN 0.10 specification header fields.\n */\nexport interface CapabilityTokenHeader {\n  /** Algorithm — always Ed25519 for HoloScript */\n  alg: 'EdDSA';\n\n  /** Token type */\n  typ: 'JWT';\n\n  /** UCAN version */\n  ucv: '0.10.0';\n}\n\n/**\n * Core UCAN-style capability token payload.\n *\n * Fields follow the UCAN specification naming conventions:\n * - `iss` — Issuer DID (the entity that created and signed this token)\n * - `aud` — Audience DID (the entity this token is delegated *to*)\n * - `att` — Attenuations (the capabilities being granted)\n * - `prf` — Proofs (CIDs / references to parent tokens in the chain)\n * - `exp` — Expiration (Unix timestamp, seconds)\n * - `nbf` — Not-before (Unix timestamp, seconds)\n * - `nnc` — Nonce (prevents replay)\n * - `fct` — Facts (arbitrary metadata about this token)\n */\nexport interface CapabilityTokenPayload {\n  /** Issuer — DID or agent identifier that created this token */\n  iss: string;\n\n  /** Audience — DID or agent identifier this token is delegated to */\n  aud: string;\n\n  /** Attenuations — capabilities granted by this token */\n  att: Capability[];\n\n  /** Proof references — identifiers of parent tokens in the delegation chain */\n  prf: string[];\n\n  /** Expiration time (Unix timestamp in seconds) */\n  exp: number;\n\n  /** Not-before time (Unix timestamp in seconds). Token is invalid before this. */\n  nbf?: number;\n\n  /** Nonce — unique value to prevent replay attacks */\n  nnc: string;\n\n  /** Facts — additional metadata (non-authoritative) */\n  fct?: Record<string, unknown>;\n}\n\n/**\n * A fully-formed, signed capability token.\n *\n * This is the \"wire format\" representation that gets passed between agents\n * and verified on receipt.\n */\nexport interface CapabilityToken {\n  /** Token header */\n  header: CapabilityTokenHeader;\n\n  /** Token payload */\n  payload: CapabilityTokenPayload;\n\n  /** Ed25519 signature over `header.payload` (base64url encoded) */\n  signature: string;\n\n  /** The serialised JWT string (header.payload.signature) */\n  raw: string;\n}\n\n// ---------------------------------------------------------------------------\n// Attenuation / Delegation Chain\n// ---------------------------------------------------------------------------\n\n/**\n * A single link in a delegation chain.\n *\n * Records who delegated to whom, what capabilities were passed down, and\n * when the delegation happened.\n */\nexport interface DelegationLink {\n  /** The token ID (nnc) of this delegation */\n  tokenId: string;\n\n  /** Issuer of this link (delegator) */\n  issuer: string;\n\n  /** Audience of this link (delegatee) */\n  audience: string;\n\n  /** Agent role of the issuer (if applicable) */\n  issuerRole?: AgentRole;\n\n  /** Agent role of the audience (if applicable) */\n  audienceRole?: AgentRole;\n\n  /** Capabilities granted at this link */\n  capabilities: Capability[];\n\n  /** Timestamp of this delegation (Unix seconds) */\n  issuedAt: number;\n\n  /** Expiration of this delegation (Unix seconds) */\n  expiresAt: number;\n}\n\n/**\n * A complete attenuation chain tracking the full delegation lineage from\n * the root authority to the current holder.\n *\n * Invariant: for every adjacent pair `(chain[i], chain[i+1])`:\n *   - `chain[i+1].issuer === chain[i].audience`\n *   - every capability in `chain[i+1].capabilities` is a subset of\n *     at least one capability in `chain[i].capabilities`\n *   - `chain[i+1].expiresAt <= chain[i].expiresAt`\n *\n * Violation of any invariant makes the chain invalid.\n */\nexport interface AttenuationChain {\n  /** Ordered list of delegation links (index 0 = root authority) */\n  links: DelegationLink[];\n\n  /** The root authority's identifier (must match links[0].issuer) */\n  rootAuthority: string;\n\n  /** Whether the chain has been verified end-to-end */\n  verified: boolean;\n\n  /** Timestamp of last verification */\n  verifiedAt?: string;\n}\n\n// ---------------------------------------------------------------------------\n// Verification results\n// ---------------------------------------------------------------------------\n\n/**\n * Result of verifying a capability token.\n */\nexport interface CapabilityVerificationResult {\n  /** Whether the token is valid */\n  valid: boolean;\n\n  /** Decoded payload (present when valid) */\n  payload?: CapabilityTokenPayload;\n\n  /** Resolved attenuation chain (present when valid) */\n  chain?: AttenuationChain;\n\n  /** Error message (present when invalid) */\n  error?: string;\n\n  /** Structured error code */\n  errorCode?:\n    | 'EXPIRED'\n    | 'NOT_YET_VALID'\n    | 'INVALID_SIGNATURE'\n    | 'INVALID_CHAIN'\n    | 'ATTENUATION_VIOLATION'\n    | 'MISSING_PROOF'\n    | 'REPLAY_DETECTED';\n}\n\n// ---------------------------------------------------------------------------\n// Token creation helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Options for issuing a new root capability token (no parent proofs).\n */\nexport interface RootTokenOptions {\n  /** Issuer identifier (DID or agent ID) */\n  issuer: string;\n\n  /** Audience identifier (DID or agent ID) */\n  audience: string;\n\n  /** Capabilities to grant */\n  capabilities: Capability[];\n\n  /** Lifetime in seconds (default: 86400 = 24 h) */\n  lifetimeSec?: number;\n\n  /** Optional not-before offset in seconds from now */\n  notBeforeOffsetSec?: number;\n\n  /** Optional additional facts / metadata */\n  facts?: Record<string, unknown>;\n}\n\n/**\n * Options for delegating (attenuating) an existing capability token.\n */\nexport interface DelegationOptions {\n  /** The parent token being delegated from */\n  parentToken: CapabilityToken;\n\n  /** New audience (delegatee) */\n  audience: string;\n\n  /**\n   * Capabilities to grant in the delegated token.\n   * Each MUST be a subset of the parent's attenuations.\n   */\n  capabilities: Capability[];\n\n  /** Lifetime in seconds (MUST NOT exceed parent's remaining lifetime) */\n  lifetimeSec?: number;\n\n  /** Optional additional facts / metadata */\n  facts?: Record<string, unknown>;\n}\n\n// ---------------------------------------------------------------------------\n// HoloScript-specific capability constants\n// ---------------------------------------------------------------------------\n\n/**\n * Standard resource URI scheme for HoloScript capabilities.\n */\nexport const HOLOSCRIPT_RESOURCE_SCHEME = 'holoscript://';\n\n/**\n * Wildcard resource — matches any HoloScript resource.\n * Only the root orchestrator should hold this.\n */\nexport const HOLOSCRIPT_RESOURCE_ALL = 'holoscript://*';\n\n/**\n * Standard HoloScript capability action namespaces.\n *\n * Mirrors the existing `AgentPermission` enum but in UCAN action-namespace\n * form.\n */\nexport const CapabilityActions = {\n  // Source\n  SOURCE_READ: 'source/read',\n\n  // Config\n  CONFIG_READ: 'config/read',\n\n  // AST\n  AST_READ: 'ast/read',\n  AST_WRITE: 'ast/write',\n  AST_TRANSFORM: 'ast/transform',\n\n  // IR\n  IR_READ: 'ir/read',\n  IR_WRITE: 'ir/write',\n  IR_TRANSFORM: 'ir/transform',\n\n  // Code\n  CODE_READ: 'code/read',\n  CODE_WRITE: 'code/write',\n\n  // Output\n  OUTPUT_WRITE: 'output/write',\n\n  // Execution\n  EXECUTE_OPTIMIZATION: 'execute/optimization',\n  EXECUTE_CODEGEN: 'execute/codegen',\n  EXECUTE_EXPORT: 'execute/export',\n\n  // Proof-of-Play (computation attestation)\n  PROOF_OF_PLAY_WRITE: 'proof_of_play/write',\n  PROOF_OF_PLAY_READ: 'proof_of_play/read',\n  PROOF_OF_PLAY_VERIFY: 'proof_of_play/verify',\n\n  // Wildcard (orchestrator only)\n  ALL: '*',\n} as const;\n\nexport type CapabilityAction = (typeof CapabilityActions)[keyof typeof CapabilityActions];\n\n/**\n * Mapping from legacy `AgentPermission` enum values to UCAN capability\n * action strings. Used by the bridge adapter (`CapabilityRBAC`).\n */\nexport const PERMISSION_TO_ACTION: Record<AgentPermission, string> = {\n  [AgentPermission.READ_SOURCE]: CapabilityActions.SOURCE_READ,\n  [AgentPermission.READ_CONFIG]: CapabilityActions.CONFIG_READ,\n  [AgentPermission.READ_AST]: CapabilityActions.AST_READ,\n  [AgentPermission.READ_IR]: CapabilityActions.IR_READ,\n  [AgentPermission.READ_CODE]: CapabilityActions.CODE_READ,\n  [AgentPermission.WRITE_AST]: CapabilityActions.AST_WRITE,\n  [AgentPermission.WRITE_IR]: CapabilityActions.IR_WRITE,\n  [AgentPermission.WRITE_CODE]: CapabilityActions.CODE_WRITE,\n  [AgentPermission.WRITE_OUTPUT]: CapabilityActions.OUTPUT_WRITE,\n  [AgentPermission.TRANSFORM_AST]: CapabilityActions.AST_TRANSFORM,\n  [AgentPermission.TRANSFORM_IR]: CapabilityActions.IR_TRANSFORM,\n  [AgentPermission.EXECUTE_OPTIMIZATION]: CapabilityActions.EXECUTE_OPTIMIZATION,\n  [AgentPermission.EXECUTE_CODEGEN]: CapabilityActions.EXECUTE_CODEGEN,\n  [AgentPermission.EXECUTE_EXPORT]: CapabilityActions.EXECUTE_EXPORT,\n};\n\n/**\n * Reverse mapping: UCAN action string -> legacy AgentPermission.\n */\nexport const ACTION_TO_PERMISSION: Record<string, AgentPermission> = Object.fromEntries(\n  Object.entries(PERMISSION_TO_ACTION).map(([perm, action]) => [action, perm as AgentPermission])\n) as Record<string, AgentPermission>;\n","/**\n * Safe JSON parsing with Zod — avoids silent crashes and supports schema validation\n * (Wave 2 audit: W2-T1).\n */\nimport { z, type ZodType } from 'zod';\n\nexport type JsonParseError =\n  | { kind: 'json-parse'; message: string; cause?: unknown }\n  | { kind: 'schema'; message: string; zodError: z.ZodError };\n\nexport type SafeJsonResult<T> = { ok: true; value: T } | { ok: false; error: JsonParseError };\n\n/**\n * Parse JSON, then validate with a Zod schema. Use for untrusted or persisted strings.\n */\nexport function safeJsonParse<T>(s: string, schema: ZodType<T>): SafeJsonResult<T> {\n  let raw: unknown;\n  try {\n    raw = JSON.parse(s);\n  } catch (e) {\n    const message = e instanceof Error ? e.message : String(e);\n    return { ok: false, error: { kind: 'json-parse', message, cause: e } };\n  }\n  const parsed = schema.safeParse(raw);\n  if (parsed.success) {\n    return { ok: true, value: parsed.data };\n  }\n  return {\n    ok: false,\n    error: { kind: 'schema', message: parsed.error.message, zodError: parsed.error },\n  };\n}\n\n/**\n * Like `JSON.parse` but the non-throwing core is `safeJsonParse` + `z.unknown()`.\n * Throws `SyntaxError` on invalid JSON to match `JSON.parse` behavior for callers\n * that expect throws.\n */\nexport function readJson(s: string): unknown {\n  const r = safeJsonParse(s, z.unknown());\n  if (r.ok) {\n    return r.value;\n  }\n  if (r.error.kind === 'json-parse') {\n    const err = new SyntaxError(r.error.message);\n    (err as Error & { cause?: unknown }).cause = r.error.cause;\n    throw err;\n  }\n  throw new Error(`[readJson] schema failure on z.unknown: ${r.error.message}`);\n}\n\n/** Deep clone via JSON round-trip (same caveats as JSON.parse/stringify). */\nexport function jsonClone<T>(value: T): T {\n  return readJson(JSON.stringify(value)) as T;\n}\n\n/**\n * Non-throwing JSON parse with a typed fallback. Use for trust-untyped\n * boundaries where you'd otherwise wrap `JSON.parse` in a `try { } catch { }`\n * just to return a default — localStorage reads, WebSocket / EventSource\n * messages, postMessage payloads, drag-drop data, file imports.\n *\n * Returns `fallback` on:\n *   - `null` / `undefined` input\n *   - `JSON.parse` throws (SyntaxError on malformed JSON)\n *\n * Does NOT validate shape — pass through `safeJsonParse(s, schema)` if you\n * need structural guarantees. The caller is responsible for type-narrowing\n * the return value (it's typed as `T` for callsite ergonomics, but the\n * runtime value may be any valid JSON if `fallback`'s type was widened).\n *\n * Example:\n * ```ts\n * const favorites = tryParseJson<string[]>(localStorage.getItem(KEY), []);\n * const evt = tryParseJson<RoomEvent | null>(message.data, null);\n * ```\n */\nexport function tryParseJson<T>(s: string | null | undefined, fallback: T): T {\n  if (s === null || s === undefined) {\n    return fallback;\n  }\n  try {\n    return JSON.parse(s) as T;\n  } catch {\n    return fallback;\n  }\n}\n\n/** Alias for `safeJsonParse` (barrel / legacy name). */\nexport const safeJsonParseSchema = safeJsonParse;\n\n/** Alias for `SafeJsonResult` in older export tables. */\nexport type { SafeJsonResult as JsonParseResult };\n","/**\n * HoloScript UCAN Capability Token Issuer\n *\n * Utility class for creating, signing, verifying, and delegating UCAN-style\n * capability tokens. Uses Ed25519 signing from the existing AgentIdentity\n * framework.\n *\n * Key design decisions:\n * - Attenuation enforcement: delegated tokens can ONLY narrow scope (never widen)\n * - Self-certifying tokens: each token is signed by the issuer's Ed25519 key\n * - Proof chain resolution: tokens carry references to parent tokens\n * - Replay protection: every token has a unique nonce\n * - Expiration monotonicity: child tokens cannot outlive their parents\n *\n * @version 1.0.0\n */\n\nimport * as crypto from 'crypto';\nimport { readJson } from '../../errors/safeJsonParse';\nimport {\n  AgentRole,\n  AgentPermission,\n  AgentKeyPair,\n  generateAgentKeyPair,\n  getDefaultPermissions,\n} from './AgentIdentity';\n\nimport type {\n  Capability,\n  CapabilitySemantics,\n  CapabilityToken,\n  CapabilityTokenHeader,\n  CapabilityTokenPayload,\n  CapabilityVerificationResult,\n  AttenuationChain,\n  DelegationLink,\n  RootTokenOptions,\n  DelegationOptions,\n} from './CapabilityToken';\n\nimport {\n  HOLOSCRIPT_RESOURCE_SCHEME,\n  HOLOSCRIPT_RESOURCE_ALL,\n  CapabilityActions,\n  PERMISSION_TO_ACTION,\n} from './CapabilityToken';\n\n// ---------------------------------------------------------------------------\n// Base64url helpers (avoid external dependencies)\n// ---------------------------------------------------------------------------\n\nfunction base64urlEncode(data: string | Buffer): string {\n  const buf = typeof data === 'string' ? Buffer.from(data, 'utf-8') : data;\n  return buf.toString('base64url');\n}\n\nfunction base64urlDecode(str: string): Buffer {\n  return Buffer.from(str, 'base64url');\n}\n\n// ---------------------------------------------------------------------------\n// Default capability semantics for HoloScript\n// ---------------------------------------------------------------------------\n\n/**\n * Default HoloScript capability semantics.\n *\n * Resource containment:\n *   `holoscript://*` contains every `holoscript://...` URI.\n *   A parent path contains any child path (e.g. `holoscript://packages`\n *   contains `holoscript://packages/core/ast`).\n *\n * Action containment:\n *   `*` contains every action.\n *   An action `a/b` contains `a/b` (exact match only, no hierarchy).\n */\nexport class HoloScriptCapabilitySemantics implements CapabilitySemantics {\n  /**\n   * Check whether `child` is a valid attenuation (subset) of `parent`.\n   */\n  isSubsetOf(child: Capability, parent: Capability): boolean {\n    // Action check\n    if (parent.can !== CapabilityActions.ALL && parent.can !== child.can) {\n      return false;\n    }\n\n    // Resource check\n    if (parent.with === HOLOSCRIPT_RESOURCE_ALL) {\n      // Wildcard parent contains everything in the holoscript scheme\n      return child.with.startsWith(HOLOSCRIPT_RESOURCE_SCHEME);\n    }\n\n    // Exact match or child is a sub-path of parent\n    if (child.with === parent.with) {\n      return true;\n    }\n\n    // Path containment: parent \"holoscript://a/b\" contains \"holoscript://a/b/c\"\n    const parentNormalized = parent.with.endsWith('/') ? parent.with : parent.with + '/';\n    if (child.with.startsWith(parentNormalized)) {\n      return true;\n    }\n\n    return false;\n  }\n\n  /**\n   * Check if `capability` authorises the given resource + action.\n   */\n  canAccess(capability: Capability, resource: string, action: string): boolean {\n    // Action match\n    if (capability.can !== CapabilityActions.ALL && capability.can !== action) {\n      return false;\n    }\n\n    // Resource match\n    if (capability.with === HOLOSCRIPT_RESOURCE_ALL) {\n      return resource.startsWith(HOLOSCRIPT_RESOURCE_SCHEME);\n    }\n\n    if (capability.with === resource) {\n      return true;\n    }\n\n    const capNormalized = capability.with.endsWith('/') ? capability.with : capability.with + '/';\n    return resource.startsWith(capNormalized);\n  }\n\n  /**\n   * Convert a legacy AgentPermission into a Capability.\n   */\n  fromPermission(permission: AgentPermission, scope?: string): Capability {\n    const action = PERMISSION_TO_ACTION[permission] || permission;\n    const resource = scope ? `${HOLOSCRIPT_RESOURCE_SCHEME}${scope}` : HOLOSCRIPT_RESOURCE_ALL;\n\n    return {\n      with: resource,\n      can: action,\n    };\n  }\n}\n\n// ---------------------------------------------------------------------------\n// Issuer configuration\n// ---------------------------------------------------------------------------\n\n/**\n * Configuration for the CapabilityTokenIssuer.\n */\nexport interface CapabilityTokenIssuerConfig {\n  /** Default token lifetime in seconds (default: 86400 = 24 h) */\n  defaultLifetimeSec?: number;\n\n  /** Maximum allowed delegation depth (default: 10) */\n  maxDelegationDepth?: number;\n\n  /** Capability semantics implementation */\n  semantics?: CapabilitySemantics;\n\n  /** Enable strict expiration monotonicity checks (default: true) */\n  strictExpiration?: boolean;\n}\n\n// ---------------------------------------------------------------------------\n// Token store for proof resolution\n// ---------------------------------------------------------------------------\n\n/**\n * In-memory store for issued tokens, keyed by their nonce (nnc).\n * In production this would be replaced by a persistent CID-based store.\n */\ntype TokenStore = Map<string, CapabilityToken>;\n\n// ---------------------------------------------------------------------------\n// CapabilityTokenIssuer\n// ---------------------------------------------------------------------------\n\n/**\n * Central utility for UCAN capability token lifecycle management.\n *\n * Handles:\n * - Root token issuance (for top-level authorities like the orchestrator)\n * - Delegated token issuance with attenuation enforcement\n * - Token verification and chain resolution\n * - Conversion between legacy RBAC permissions and capabilities\n */\nexport class CapabilityTokenIssuer {\n  private defaultLifetimeSec: number;\n  private maxDelegationDepth: number;\n  private semantics: CapabilitySemantics;\n  private strictExpiration: boolean;\n\n  /** Token store for proof resolution */\n  private tokenStore: TokenStore = new Map();\n\n  /** Nonce set for replay detection */\n  private usedNonces: Set<string> = new Set();\n\n  constructor(config: CapabilityTokenIssuerConfig = {}) {\n    this.defaultLifetimeSec = config.defaultLifetimeSec ?? 86400;\n    this.maxDelegationDepth = config.maxDelegationDepth ?? 10;\n    this.semantics = config.semantics ?? new HoloScriptCapabilitySemantics();\n    this.strictExpiration = config.strictExpiration ?? true;\n  }\n\n  // -----------------------------------------------------------------------\n  // Root token issuance\n  // -----------------------------------------------------------------------\n\n  /**\n   * Issue a root capability token (no parent proofs).\n   *\n   * Root tokens are typically issued by the orchestrator or a top-level\n   * identity provider to grant initial capabilities.\n   *\n   * @param options  Token creation options\n   * @param keyPair  Ed25519 key pair of the issuer (used for signing)\n   * @returns        Signed CapabilityToken\n   */\n  async issueRoot(options: RootTokenOptions, keyPair: AgentKeyPair): Promise<CapabilityToken> {\n    const now = Math.floor(Date.now() / 1000);\n    const lifetime = options.lifetimeSec ?? this.defaultLifetimeSec;\n    const nonce = crypto.randomUUID();\n\n    const payload: CapabilityTokenPayload = {\n      iss: options.issuer,\n      aud: options.audience,\n      att: options.capabilities,\n      prf: [], // root — no proofs\n      exp: now + lifetime,\n      nbf: options.notBeforeOffsetSec != null ? now + options.notBeforeOffsetSec : undefined,\n      nnc: nonce,\n      fct: options.facts,\n    };\n\n    const token = this.sign(payload, keyPair);\n\n    // Store for future proof resolution\n    this.tokenStore.set(nonce, token);\n\n    return token;\n  }\n\n  // -----------------------------------------------------------------------\n  // Delegation with attenuation\n  // -----------------------------------------------------------------------\n\n  /**\n   * Delegate (attenuate) an existing capability token to a new audience.\n   *\n   * Enforces:\n   * 1. Every capability in the child MUST be a subset of at least one\n   *    capability in the parent.\n   * 2. Child expiration MUST NOT exceed parent expiration.\n   * 3. Delegation depth MUST NOT exceed `maxDelegationDepth`.\n   *\n   * @param options  Delegation options including the parent token\n   * @param keyPair  Ed25519 key pair of the delegator (current holder)\n   * @returns        New signed CapabilityToken\n   * @throws         Error if attenuation invariants are violated\n   */\n  async delegate(options: DelegationOptions, keyPair: AgentKeyPair): Promise<CapabilityToken> {\n    const { parentToken, audience, capabilities, lifetimeSec, facts } = options;\n    const parentPayload = parentToken.payload;\n\n    // --- Attenuation check ---\n    for (const childCap of capabilities) {\n      const covered = parentPayload.att.some((parentCap) =>\n        this.semantics.isSubsetOf(childCap, parentCap)\n      );\n      if (!covered) {\n        throw new Error(\n          `Attenuation violation: capability {with: \"${childCap.with}\", can: \"${childCap.can}\"} ` +\n            `is not a subset of any parent capability. Delegations can only narrow scope.`\n        );\n      }\n    }\n\n    // --- Expiration monotonicity ---\n    const now = Math.floor(Date.now() / 1000);\n    const parentRemainingLifetime = Math.max(0, parentPayload.exp - now);\n    const requestedLifetime =\n      lifetimeSec ?? Math.min(this.defaultLifetimeSec, parentRemainingLifetime);\n    const childExp = now + requestedLifetime;\n\n    if (this.strictExpiration && childExp > parentPayload.exp) {\n      throw new Error(\n        `Expiration violation: delegated token expires at ${childExp} ` +\n          `but parent expires at ${parentPayload.exp}. ` +\n          `Child tokens cannot outlive their parents.`\n      );\n    }\n\n    const effectiveExp = Math.min(childExp, parentPayload.exp);\n\n    // --- Delegation depth ---\n    const currentDepth = parentPayload.prf.length + 1;\n    if (currentDepth > this.maxDelegationDepth) {\n      throw new Error(\n        `Delegation depth ${currentDepth} exceeds maximum of ${this.maxDelegationDepth}.`\n      );\n    }\n\n    // Build proof chain (parent's proofs + parent's nonce)\n    const proofs = [...parentPayload.prf, parentPayload.nnc];\n\n    const nonce = crypto.randomUUID();\n    const payload: CapabilityTokenPayload = {\n      iss: parentPayload.aud, // delegator is the audience of the parent\n      aud: audience,\n      att: capabilities,\n      prf: proofs,\n      exp: effectiveExp,\n      nbf: now,\n      nnc: nonce,\n      fct: facts,\n    };\n\n    const token = this.sign(payload, keyPair);\n\n    // Store\n    this.tokenStore.set(nonce, token);\n\n    return token;\n  }\n\n  // -----------------------------------------------------------------------\n  // Signing\n  // -----------------------------------------------------------------------\n\n  /**\n   * Sign a capability token payload with an Ed25519 key pair.\n   *\n   * Produces a JWT-like structure: base64url(header).base64url(payload).base64url(sig)\n   */\n  sign(payload: CapabilityTokenPayload, keyPair: AgentKeyPair): CapabilityToken {\n    const header: CapabilityTokenHeader = {\n      alg: 'EdDSA',\n      typ: 'JWT',\n      ucv: '0.10.0',\n    };\n\n    const headerB64 = base64urlEncode(JSON.stringify(header));\n    const payloadB64 = base64urlEncode(JSON.stringify(payload));\n\n    const signingInput = `${headerB64}.${payloadB64}`;\n\n    const privateKeyObj = crypto.createPrivateKey(keyPair.privateKey);\n    const signatureBuffer = crypto.sign(null, Buffer.from(signingInput, 'utf-8'), privateKeyObj);\n    const signatureB64 = signatureBuffer.toString('base64url');\n\n    const raw = `${headerB64}.${payloadB64}.${signatureB64}`;\n\n    return {\n      header,\n      payload,\n      signature: signatureB64,\n      raw,\n    };\n  }\n\n  // -----------------------------------------------------------------------\n  // Verification\n  // -----------------------------------------------------------------------\n\n  /**\n   * Verify a capability token.\n   *\n   * Checks:\n   * 1. Structural validity (three-part JWT)\n   * 2. Ed25519 signature\n   * 3. Expiration / not-before\n   * 4. Replay (nonce uniqueness)\n   * 5. Proof chain integrity (attenuation invariants)\n   *\n   * @param raw       The raw JWT string (or a CapabilityToken object)\n   * @param publicKey PEM-encoded Ed25519 public key of the issuer\n   * @returns         Verification result\n   */\n  verify(raw: string | CapabilityToken, publicKey: string): CapabilityVerificationResult {\n    const rawStr = typeof raw === 'string' ? raw : raw.raw;\n    const parts = rawStr.split('.');\n    if (parts.length !== 3) {\n      return {\n        valid: false,\n        error: 'Malformed token: expected 3 parts',\n        errorCode: 'INVALID_SIGNATURE',\n      };\n    }\n\n    const [headerB64, payloadB64, signatureB64] = parts;\n\n    // --- Signature verification ---\n    try {\n      const pubKeyObj = crypto.createPublicKey(publicKey);\n      const signingInput = `${headerB64}.${payloadB64}`;\n      const signatureBuffer = base64urlDecode(signatureB64);\n      const isValid = crypto.verify(\n        null,\n        Buffer.from(signingInput, 'utf-8'),\n        pubKeyObj,\n        signatureBuffer\n      );\n      if (!isValid) {\n        return {\n          valid: false,\n          error: 'Invalid Ed25519 signature',\n          errorCode: 'INVALID_SIGNATURE',\n        };\n      }\n    } catch {\n      return {\n        valid: false,\n        error: 'Signature verification failed',\n        errorCode: 'INVALID_SIGNATURE',\n      };\n    }\n\n    // --- Decode payload ---\n    let payload: CapabilityTokenPayload;\n    try {\n      payload = readJson(base64urlDecode(payloadB64).toString('utf-8')) as CapabilityTokenPayload;\n    } catch {\n      return {\n        valid: false,\n        error: 'Malformed payload',\n        errorCode: 'INVALID_SIGNATURE',\n      };\n    }\n\n    // --- Expiration ---\n    const now = Math.floor(Date.now() / 1000);\n    if (payload.exp <= now) {\n      return {\n        valid: false,\n        payload,\n        error: 'Token expired',\n        errorCode: 'EXPIRED',\n      };\n    }\n\n    // --- Not-before ---\n    if (payload.nbf != null && payload.nbf > now) {\n      return {\n        valid: false,\n        payload,\n        error: `Token not yet valid (nbf: ${payload.nbf}, now: ${now})`,\n        errorCode: 'NOT_YET_VALID',\n      };\n    }\n\n    // --- Replay check ---\n    if (this.usedNonces.has(payload.nnc)) {\n      return {\n        valid: false,\n        payload,\n        error: 'Nonce already used (replay detected)',\n        errorCode: 'REPLAY_DETECTED',\n      };\n    }\n\n    // Record nonce as used\n    this.usedNonces.add(payload.nnc);\n\n    // --- Proof chain verification ---\n    const chainResult = this.resolveChain(payload);\n\n    return {\n      valid: true,\n      payload,\n      chain: chainResult,\n    };\n  }\n\n  // -----------------------------------------------------------------------\n  // Proof chain resolution\n  // -----------------------------------------------------------------------\n\n  /**\n   * Resolve and verify the proof chain for a token payload.\n   *\n   * Walks back through `prf` references, checking attenuation invariants\n   * at each step.\n   */\n  resolveChain(payload: CapabilityTokenPayload): AttenuationChain | undefined {\n    if (payload.prf.length === 0) {\n      // Root token — trivial chain\n      return {\n        links: [\n          {\n            tokenId: payload.nnc,\n            issuer: payload.iss,\n            audience: payload.aud,\n            capabilities: payload.att,\n            issuedAt: payload.nbf ?? Math.floor(Date.now() / 1000),\n            expiresAt: payload.exp,\n          },\n        ],\n        rootAuthority: payload.iss,\n        verified: true,\n        verifiedAt: new Date().toISOString(),\n      };\n    }\n\n    const links: DelegationLink[] = [];\n\n    // Walk proof chain backwards\n    for (const proofNonce of payload.prf) {\n      const parentToken = this.tokenStore.get(proofNonce);\n      if (!parentToken) {\n        // Cannot resolve full chain — partial chain\n        return {\n          links,\n          rootAuthority: links.length > 0 ? links[0].issuer : payload.iss,\n          verified: false,\n        };\n      }\n\n      links.push({\n        tokenId: parentToken.payload.nnc,\n        issuer: parentToken.payload.iss,\n        audience: parentToken.payload.aud,\n        capabilities: parentToken.payload.att,\n        issuedAt: parentToken.payload.nbf ?? 0,\n        expiresAt: parentToken.payload.exp,\n      });\n    }\n\n    // Add current token as final link\n    links.push({\n      tokenId: payload.nnc,\n      issuer: payload.iss,\n      audience: payload.aud,\n      capabilities: payload.att,\n      issuedAt: payload.nbf ?? 0,\n      expiresAt: payload.exp,\n    });\n\n    // Verify attenuation invariants between adjacent links\n    let chainValid = true;\n    for (let i = 1; i < links.length; i++) {\n      const parent = links[i - 1];\n      const child = links[i];\n\n      // Audience/issuer continuity\n      if (child.issuer !== parent.audience) {\n        chainValid = false;\n        break;\n      }\n\n      // Attenuation: every child capability must be subset of some parent capability\n      for (const childCap of child.capabilities) {\n        const covered = parent.capabilities.some((parentCap) =>\n          this.semantics.isSubsetOf(childCap, parentCap)\n        );\n        if (!covered) {\n          chainValid = false;\n          break;\n        }\n      }\n      if (!chainValid) break;\n\n      // Expiration monotonicity\n      if (child.expiresAt > parent.expiresAt) {\n        chainValid = false;\n        break;\n      }\n    }\n\n    return {\n      links,\n      rootAuthority: links[0].issuer,\n      verified: chainValid,\n      verifiedAt: chainValid ? new Date().toISOString() : undefined,\n    };\n  }\n\n  // -----------------------------------------------------------------------\n  // Convenience: issue from AgentRole\n  // -----------------------------------------------------------------------\n\n  /**\n   * Issue a root capability token for a given AgentRole.\n   *\n   * Automatically maps role permissions to capabilities using the bridge\n   * mappings defined in CapabilityToken.ts.\n   *\n   * @param role      Agent role\n   * @param audience  Audience identifier\n   * @param keyPair   Ed25519 key pair\n   * @param scope     Optional resource scope restriction\n   * @returns         Signed root CapabilityToken\n   */\n  async issueForRole(\n    role: AgentRole,\n    audience: string,\n    keyPair: AgentKeyPair,\n    scope?: string\n  ): Promise<CapabilityToken> {\n    const permissions = getDefaultPermissions(role);\n    const capabilities = permissions.map((perm) => this.semantics.fromPermission(perm, scope));\n\n    const issuer = `agent:${role}`;\n\n    return this.issueRoot(\n      {\n        issuer,\n        audience,\n        capabilities,\n      },\n      keyPair\n    );\n  }\n\n  // -----------------------------------------------------------------------\n  // Capability query\n  // -----------------------------------------------------------------------\n\n  /**\n   * Check whether a token grants access to a specific resource + action.\n   *\n   * Does NOT verify the signature — call `verify()` first if the token\n   * has not been verified yet.\n   */\n  hasCapability(token: CapabilityToken, resource: string, action: string): boolean {\n    return token.payload.att.some((cap) => this.semantics.canAccess(cap, resource, action));\n  }\n\n  // -----------------------------------------------------------------------\n  // Store management\n  // -----------------------------------------------------------------------\n\n  /**\n   * Retrieve a stored token by its nonce (for proof resolution).\n   */\n  getStoredToken(nonce: string): CapabilityToken | undefined {\n    return this.tokenStore.get(nonce);\n  }\n\n  /**\n   * Store an externally-created token (e.g. received from another agent).\n   */\n  storeToken(token: CapabilityToken): void {\n    this.tokenStore.set(token.payload.nnc, token);\n  }\n\n  /**\n   * Clear all stored tokens and nonces (for testing).\n   */\n  reset(): void {\n    this.tokenStore.clear();\n    this.usedNonces.clear();\n  }\n\n  /**\n   * Get the semantics engine used by this issuer.\n   */\n  getSemantics(): CapabilitySemantics {\n    return this.semantics;\n  }\n}\n\n// ---------------------------------------------------------------------------\n// Global singleton\n// ---------------------------------------------------------------------------\n\nlet globalCapabilityIssuer: CapabilityTokenIssuer | null = null;\n\n/**\n * Get or create the global CapabilityTokenIssuer instance.\n */\nexport function getCapabilityTokenIssuer(\n  config?: CapabilityTokenIssuerConfig\n): CapabilityTokenIssuer {\n  if (!globalCapabilityIssuer) {\n    globalCapabilityIssuer = new CapabilityTokenIssuer(config);\n  }\n  return globalCapabilityIssuer;\n}\n\n/**\n * Reset the global CapabilityTokenIssuer (for testing).\n */\nexport function resetCapabilityTokenIssuer(): void {\n  globalCapabilityIssuer = null;\n}\n","/**\n * HoloScript Hybrid Crypto Provider\n *\n * Post-quantum cryptography abstraction layer for dual-signing with\n * Ed25519 (classical) + ML-DSA-65 / Dilithium (post-quantum).\n *\n * Phase 1: Abstraction layer (Ed25519 + mock PQ).\n * Phase 2 (current): Real ML-DSA-65 support via dynamic import of @noble/post-quantum.\n *   - MLDSACryptoProvider: Real PQ signing using @noble/post-quantum/ml-dsa\n *   - createCryptoProvider('ml-dsa-65') returns MLDSACryptoProvider\n *   - isPostQuantumAvailable() checks runtime availability of @noble/post-quantum\n *\n * Architecture:\n * - ICryptoProvider: Abstract interface for any signing algorithm\n * - Ed25519CryptoProvider: Classical Ed25519 using Node.js crypto (production-ready)\n * - HybridCryptoProvider: Wraps classical + PQ providers, produces composite signatures\n * - Factory function: createCryptoProvider(algorithm) returns the appropriate provider\n *\n * Composite verification strategy: EITHER signature validates the message (defense in depth).\n * During the migration period this ensures:\n * - If PQ implementation has bugs, classical Ed25519 still protects\n * - If Ed25519 is broken by quantum computers, PQ signature still protects\n * - Backward compatibility with Ed25519-only verifiers\n *\n * @version 1.0.0\n * @see https://csrc.nist.gov/pubs/fips/204/final (ML-DSA / Dilithium)\n * @see https://datatracker.ietf.org/doc/draft-ietf-lamps-dilithium-certificates/\n */\n\nimport * as crypto from 'crypto';\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n/**\n * Supported signature algorithms.\n *\n * - 'ed25519': Classical Edwards-curve Digital Signature Algorithm (EdDSA)\n * - 'ml-dsa-65': NIST FIPS 204 Module-Lattice Digital Signature Algorithm (security level 3)\n * - 'hybrid-ed25519-ml-dsa-65': Composite dual-signing with both algorithms\n */\nexport type SignatureAlgorithm = 'ed25519' | 'ml-dsa-65' | 'hybrid-ed25519-ml-dsa-65';\n\n// ---------------------------------------------------------------------------\n// Interfaces\n// ---------------------------------------------------------------------------\n\n/**\n * Key material for a single algorithm.\n *\n * For Ed25519, keys are PEM-encoded (SPKI public, PKCS8 private).\n * For ML-DSA-65, keys will be raw byte arrays encoded as base64 (Phase 2).\n */\nexport interface CryptoKeyPair {\n  /** Public key (PEM for Ed25519, base64 for ML-DSA-65) */\n  publicKey: string;\n\n  /** Private key (PEM for Ed25519, base64 for ML-DSA-65) */\n  privateKey: string;\n\n  /** Key identifier (e.g., \"agent:role#timestamp\") */\n  kid: string;\n\n  /** Algorithm this key pair belongs to */\n  algorithm: SignatureAlgorithm;\n}\n\n/**\n * Hybrid key pair holding classical and optional post-quantum key material.\n *\n * During the migration period the pqKey is optional:\n * - Phase 1 (current): Only classicalKey is populated\n * - Phase 2: Both classicalKey and pqKey are populated\n * - Phase 3 (post-migration): pqKey is primary, classicalKey optional\n */\nexport interface HybridKeyPair {\n  /** Ed25519 key pair (always present in Phase 1-2) */\n  classicalKey: CryptoKeyPair;\n\n  /** ML-DSA-65 key pair (populated in Phase 2+) */\n  pqKey?: CryptoKeyPair;\n\n  /** Combined key identifier */\n  kid: string;\n\n  /** Algorithm identifier for the hybrid pair */\n  algorithm: SignatureAlgorithm;\n}\n\n/**\n * Composite signature holding both classical and post-quantum signatures.\n *\n * Verification strategy: valid if EITHER signature verifies (defense in depth).\n */\nexport interface CompositeSignature {\n  /** Ed25519 signature (base64-encoded) */\n  classicalSignature: string;\n\n  /** ML-DSA-65 signature (base64-encoded, absent if PQ provider not available) */\n  pqSignature?: string;\n\n  /** Algorithm used to produce this composite signature */\n  algorithm: SignatureAlgorithm;\n\n  /** Timestamp when the signature was created (ISO 8601) */\n  signedAt: string;\n\n  /** Key ID of the signing key pair */\n  kid: string;\n}\n\n/**\n * Result of composite signature verification.\n */\nexport interface CompositeVerificationResult {\n  /** Overall validity: true if at least one component signature verifies */\n  valid: boolean;\n\n  /** Whether the classical (Ed25519) signature verified */\n  classicalValid: boolean;\n\n  /** Whether the post-quantum (ML-DSA-65) signature verified (null if not present) */\n  pqValid: boolean | null;\n\n  /** Algorithm used */\n  algorithm: SignatureAlgorithm;\n\n  /** Error message if both verifications failed */\n  error?: string;\n}\n\n/**\n * Abstract interface for cryptographic signing providers.\n *\n * Implementations must be stateless and thread-safe.\n * Each provider handles exactly one algorithm.\n */\nexport interface ICryptoProvider {\n  /**\n   * Generate a new key pair for this algorithm.\n   *\n   * @param kid - Optional key identifier. If not provided, one will be generated.\n   * @returns Promise resolving to a CryptoKeyPair\n   */\n  generateKeyPair(kid?: string): Promise<CryptoKeyPair>;\n\n  /**\n   * Sign a message using the private key.\n   *\n   * @param message - The message bytes to sign\n   * @param privateKey - The private key (format depends on algorithm)\n   * @returns Promise resolving to the signature as a base64 string\n   */\n  sign(message: Uint8Array, privateKey: string): Promise<string>;\n\n  /**\n   * Verify a signature against a message and public key.\n   *\n   * @param message - The original message bytes\n   * @param signature - The signature to verify (base64-encoded)\n   * @param publicKey - The public key to verify against\n   * @returns Promise resolving to true if the signature is valid\n   */\n  verify(message: Uint8Array, signature: string, publicKey: string): Promise<boolean>;\n\n  /**\n   * Get the algorithm identifier for this provider.\n   */\n  getAlgorithm(): SignatureAlgorithm;\n}\n\n// ---------------------------------------------------------------------------\n// Ed25519CryptoProvider\n// ---------------------------------------------------------------------------\n\n/**\n * Ed25519 cryptographic provider using Node.js built-in crypto module.\n *\n * This is the classical (pre-quantum) provider that wraps the existing\n * Ed25519 operations from AgentIdentity.ts into the ICryptoProvider interface.\n *\n * Key format: PEM (SPKI for public, PKCS8 for private)\n * Signature format: base64-encoded raw Ed25519 signature (64 bytes)\n */\nexport class Ed25519CryptoProvider implements ICryptoProvider {\n  /**\n   * Generate a new Ed25519 key pair.\n   *\n   * @param kid - Optional key identifier. Defaults to \"ed25519#<timestamp>\"\n   */\n  async generateKeyPair(kid?: string): Promise<CryptoKeyPair> {\n    const keyPair = crypto.generateKeyPairSync('ed25519', {\n      publicKeyEncoding: {\n        type: 'spki',\n        format: 'pem',\n      },\n      privateKeyEncoding: {\n        type: 'pkcs8',\n        format: 'pem',\n      },\n    });\n\n    return {\n      publicKey: keyPair.publicKey,\n      privateKey: keyPair.privateKey,\n      kid: kid || `ed25519#${Date.now()}`,\n      algorithm: 'ed25519',\n    };\n  }\n\n  /**\n   * Sign a message with Ed25519.\n   *\n   * Ed25519 uses the message directly (no pre-hashing).\n   */\n  async sign(message: Uint8Array, privateKey: string): Promise<string> {\n    const signature = crypto.sign(\n      null, // Ed25519 does not use a separate hash algorithm\n      Buffer.from(message),\n      {\n        key: privateKey,\n        format: 'pem',\n        type: 'pkcs8',\n      }\n    );\n    return signature.toString('base64');\n  }\n\n  /**\n   * Verify an Ed25519 signature.\n   */\n  async verify(message: Uint8Array, signature: string, publicKey: string): Promise<boolean> {\n    try {\n      return crypto.verify(\n        null, // Ed25519 does not use a separate hash\n        Buffer.from(message),\n        {\n          key: publicKey,\n          format: 'pem',\n          type: 'spki',\n        },\n        Buffer.from(signature, 'base64')\n      );\n    } catch {\n      return false;\n    }\n  }\n\n  getAlgorithm(): SignatureAlgorithm {\n    return 'ed25519';\n  }\n}\n\n// ---------------------------------------------------------------------------\n// MLDSACryptoProvider\n// ---------------------------------------------------------------------------\n\n/**\n * ML-DSA-65 (Dilithium) cryptographic provider using @noble/post-quantum.\n *\n * Uses dynamic import so the @noble/post-quantum package is optional:\n * - If installed: Full ML-DSA-65 key generation, signing, and verification\n * - If not installed: Operations throw a clear error with install instructions\n *\n * Key format: base64-encoded raw byte arrays\n * Signature format: base64-encoded raw ML-DSA-65 signature\n *\n * @see https://csrc.nist.gov/pubs/fips/204/final (FIPS 204 — ML-DSA)\n */\nexport class MLDSACryptoProvider implements ICryptoProvider {\n  /**\n   * Lazily load the @noble/post-quantum ML-DSA module.\n   *\n   * Caches the module after first successful import to avoid repeated dynamic imports.\n   */\n  private mlDsaModule: unknown = null;\n\n  private async getModule(): Promise<any> {\n    if (this.mlDsaModule) {\n      return this.mlDsaModule;\n    }\n\n    const noble = await import(/* @vite-ignore */ '@noble/post-quantum/ml-dsa.js' as string).catch(\n      () => null\n    );\n    if (!noble) {\n      throw new Error(\n        'ML-DSA-65 requires @noble/post-quantum. ' +\n          'Install it with: npm install @noble/post-quantum'\n      );\n    }\n\n    this.mlDsaModule = noble;\n    return noble;\n  }\n\n  /**\n   * Generate a new ML-DSA-65 key pair.\n   *\n   * ML-DSA-65 (FIPS 204, security level 3):\n   * - Public key: 1952 bytes\n   * - Private key: 4032 bytes\n   * - Signature: 3309 bytes\n   *\n   * @param kid - Optional key identifier. Defaults to \"ml-dsa-65#<timestamp>\"\n   */\n  async generateKeyPair(kid?: string): Promise<CryptoKeyPair> {\n    const noble = await this.getModule();\n    const keyPair = noble.ml_dsa65.keygen();\n\n    return {\n      publicKey: Buffer.from(keyPair.publicKey).toString('base64'),\n      privateKey: Buffer.from(keyPair.secretKey).toString('base64'),\n      kid: kid || `ml-dsa-65#${Date.now()}`,\n      algorithm: 'ml-dsa-65',\n    };\n  }\n\n  /**\n   * Sign a message with ML-DSA-65.\n   *\n   * ML-DSA-65 uses the message directly (no pre-hashing).\n   */\n  async sign(message: Uint8Array, privateKey: string): Promise<string> {\n    const noble = await this.getModule();\n    const secretKey = new Uint8Array(Buffer.from(privateKey, 'base64'));\n    // @noble/post-quantum >=0.6 uses sign(message, secretKey); older releases\n    // took (secretKey, message). Keep message-first to match the installed API.\n    const signature = noble.ml_dsa65.sign(message, secretKey);\n    return Buffer.from(signature).toString('base64');\n  }\n\n  /**\n   * Verify an ML-DSA-65 signature.\n   */\n  async verify(message: Uint8Array, signature: string, publicKey: string): Promise<boolean> {\n    try {\n      const noble = await this.getModule();\n      const pubKeyBytes = new Uint8Array(Buffer.from(publicKey, 'base64'));\n      const sigBytes = new Uint8Array(Buffer.from(signature, 'base64'));\n      // @noble/post-quantum >=0.6 uses verify(signature, message, publicKey).\n      return noble.ml_dsa65.verify(sigBytes, message, pubKeyBytes);\n    } catch {\n      return false;\n    }\n  }\n\n  getAlgorithm(): SignatureAlgorithm {\n    return 'ml-dsa-65';\n  }\n}\n\n// ---------------------------------------------------------------------------\n// Post-Quantum Availability Check\n// ---------------------------------------------------------------------------\n\n/**\n * Check whether the @noble/post-quantum package is available at runtime.\n *\n * This is a lightweight probe that attempts to dynamically import the module\n * without caching, useful for feature detection before constructing providers.\n *\n * @returns Promise<boolean> — true if @noble/post-quantum/ml-dsa is importable\n */\nexport async function isPostQuantumAvailable(): Promise<boolean> {\n  const noble = await import(/* @vite-ignore */ '@noble/post-quantum/ml-dsa.js' as string).catch(\n    () => null\n  );\n  return noble !== null;\n}\n\n// ---------------------------------------------------------------------------\n// HybridCryptoProvider\n// ---------------------------------------------------------------------------\n\n/**\n * Hybrid cryptographic provider that combines classical and post-quantum signing.\n *\n * Produces CompositeSignature objects containing both an Ed25519 signature and\n * an ML-DSA-65 signature. Verification is \"defense in depth\": the composite\n * signature is valid if EITHER component signature verifies.\n *\n * This design ensures:\n * 1. Backward compatibility during migration (Ed25519-only verifiers still work)\n * 2. Forward security (PQ signature protects against quantum attacks)\n * 3. Implementation safety (bug in one algorithm doesn't break authentication)\n *\n * Usage (Phase 1 — PQ provider is a no-op or mock):\n * ```typescript\n * const hybrid = new HybridCryptoProvider(\n *   new Ed25519CryptoProvider(),\n *   mockPqProvider, // or undefined for Ed25519-only mode\n * );\n * ```\n */\nexport class HybridCryptoProvider implements ICryptoProvider {\n  private readonly classical: ICryptoProvider;\n  private readonly pq: ICryptoProvider | undefined;\n\n  /**\n   * Create a hybrid provider wrapping classical and optional PQ providers.\n   *\n   * @param classical - The classical (Ed25519) provider (required)\n   * @param pq - The post-quantum (ML-DSA-65) provider (optional in Phase 1)\n   */\n  constructor(classical: ICryptoProvider, pq?: ICryptoProvider) {\n    if (classical.getAlgorithm() !== 'ed25519') {\n      throw new Error(`Classical provider must be ed25519, got: ${classical.getAlgorithm()}`);\n    }\n    if (pq && pq.getAlgorithm() !== 'ml-dsa-65') {\n      throw new Error(`Post-quantum provider must be ml-dsa-65, got: ${pq.getAlgorithm()}`);\n    }\n\n    this.classical = classical;\n    this.pq = pq;\n  }\n\n  /**\n   * Generate a hybrid key pair containing both classical and PQ keys.\n   *\n   * If the PQ provider is not available, only the classical key is generated.\n   */\n  async generateKeyPair(kid?: string): Promise<CryptoKeyPair> {\n    const hybridKid = kid || `hybrid#${Date.now()}`;\n    const classicalKey = await this.classical.generateKeyPair(`${hybridKid}:classical`);\n\n    // Return the classical key as the \"primary\" key for ICryptoProvider compatibility\n    // Use generateHybridKeyPair() for full hybrid key pairs\n    return {\n      publicKey: classicalKey.publicKey,\n      privateKey: classicalKey.privateKey,\n      kid: hybridKid,\n      algorithm: 'hybrid-ed25519-ml-dsa-65',\n    };\n  }\n\n  /**\n   * Generate a full hybrid key pair with both classical and PQ components.\n   *\n   * This is the preferred method for hybrid operations.\n   */\n  async generateHybridKeyPair(kid?: string): Promise<HybridKeyPair> {\n    const hybridKid = kid || `hybrid#${Date.now()}`;\n    const classicalKey = await this.classical.generateKeyPair(`${hybridKid}:classical`);\n\n    let pqKey: CryptoKeyPair | undefined;\n    if (this.pq) {\n      pqKey = await this.pq.generateKeyPair(`${hybridKid}:pq`);\n    }\n\n    return {\n      classicalKey,\n      pqKey,\n      kid: hybridKid,\n      algorithm: 'hybrid-ed25519-ml-dsa-65',\n    };\n  }\n\n  /**\n   * Sign a message with the classical provider.\n   *\n   * For composite signatures, use signComposite() instead.\n   * This method exists for ICryptoProvider interface compatibility.\n   */\n  async sign(message: Uint8Array, privateKey: string): Promise<string> {\n    return this.classical.sign(message, privateKey);\n  }\n\n  /**\n   * Produce a composite signature using both classical and PQ providers.\n   *\n   * @param message - The message bytes to sign\n   * @param hybridKeyPair - The hybrid key pair containing both key sets\n   * @returns CompositeSignature with both signatures\n   */\n  async signComposite(\n    message: Uint8Array,\n    hybridKeyPair: HybridKeyPair\n  ): Promise<CompositeSignature> {\n    // Always sign with classical\n    const classicalSignature = await this.classical.sign(\n      message,\n      hybridKeyPair.classicalKey.privateKey\n    );\n\n    // Sign with PQ if available\n    let pqSignature: string | undefined;\n    if (this.pq && hybridKeyPair.pqKey) {\n      pqSignature = await this.pq.sign(message, hybridKeyPair.pqKey.privateKey);\n    }\n\n    return {\n      classicalSignature,\n      pqSignature,\n      algorithm: 'hybrid-ed25519-ml-dsa-65',\n      signedAt: new Date().toISOString(),\n      kid: hybridKeyPair.kid,\n    };\n  }\n\n  /**\n   * Verify a signature using the classical provider.\n   *\n   * For composite verification, use verifyComposite() instead.\n   * This method exists for ICryptoProvider interface compatibility.\n   */\n  async verify(message: Uint8Array, signature: string, publicKey: string): Promise<boolean> {\n    return this.classical.verify(message, signature, publicKey);\n  }\n\n  /**\n   * Verify a composite signature.\n   *\n   * Defense in depth: the composite is valid if EITHER the classical or PQ\n   * signature verifies. This ensures:\n   * - Migration safety: if PQ has implementation bugs, classical still works\n   * - Quantum resistance: if Ed25519 is broken, PQ signature still holds\n   *\n   * @param message - The original message bytes\n   * @param compositeSignature - The composite signature to verify\n   * @param hybridKeyPair - The hybrid key pair with public keys for verification\n   * @returns CompositeVerificationResult with per-component status\n   */\n  async verifyComposite(\n    message: Uint8Array,\n    compositeSignature: CompositeSignature,\n    hybridKeyPair: HybridKeyPair\n  ): Promise<CompositeVerificationResult> {\n    // Verify classical signature\n    const classicalValid = await this.classical.verify(\n      message,\n      compositeSignature.classicalSignature,\n      hybridKeyPair.classicalKey.publicKey\n    );\n\n    // Verify PQ signature if present\n    let pqValid: boolean | null = null;\n    if (this.pq && compositeSignature.pqSignature && hybridKeyPair.pqKey) {\n      pqValid = await this.pq.verify(\n        message,\n        compositeSignature.pqSignature,\n        hybridKeyPair.pqKey.publicKey\n      );\n    }\n\n    // Defense in depth: valid if EITHER verifies\n    const eitherValid = classicalValid || pqValid === true;\n\n    const result: CompositeVerificationResult = {\n      valid: eitherValid,\n      classicalValid,\n      pqValid,\n      algorithm: compositeSignature.algorithm,\n    };\n\n    if (!eitherValid) {\n      result.error =\n        'Both classical (Ed25519) and post-quantum (ML-DSA-65) signature verification failed';\n    }\n\n    return result;\n  }\n\n  getAlgorithm(): SignatureAlgorithm {\n    return 'hybrid-ed25519-ml-dsa-65';\n  }\n\n  /**\n   * Check whether the PQ provider is available.\n   */\n  hasPQProvider(): boolean {\n    return this.pq !== undefined;\n  }\n}\n\n// ---------------------------------------------------------------------------\n// Factory\n// ---------------------------------------------------------------------------\n\n/**\n * Create a crypto provider for the specified algorithm.\n *\n * - 'ed25519': Returns an Ed25519CryptoProvider (production-ready)\n * - 'ml-dsa-65': Returns an MLDSACryptoProvider (requires @noble/post-quantum at runtime)\n * - 'hybrid-ed25519-ml-dsa-65': Returns a HybridCryptoProvider with Ed25519\n *   classical provider and an MLDSACryptoProvider as the PQ provider.\n *   Pass an optional pqProvider to override the default MLDSACryptoProvider.\n *\n * @param algorithm - The signature algorithm to use\n * @param pqProvider - Optional PQ provider for hybrid mode (overrides default MLDSACryptoProvider)\n * @returns ICryptoProvider implementation\n */\nexport function createCryptoProvider(\n  algorithm: SignatureAlgorithm,\n  pqProvider?: ICryptoProvider\n): ICryptoProvider {\n  switch (algorithm) {\n    case 'ed25519':\n      return new Ed25519CryptoProvider();\n\n    case 'ml-dsa-65':\n      return new MLDSACryptoProvider();\n\n    case 'hybrid-ed25519-ml-dsa-65':\n      return new HybridCryptoProvider(\n        new Ed25519CryptoProvider(),\n        pqProvider ?? new MLDSACryptoProvider()\n      );\n\n    default: {\n      // Exhaustive check — should never reach here with valid SignatureAlgorithm\n      const _exhaustive: never = algorithm;\n      throw new Error(`Unknown signature algorithm: ${_exhaustive}`);\n    }\n  }\n}\n","/**\n * HybridSigner - Convenience wrapper over HybridCryptoProvider\n * for Ed25519 + ML-DSA dual-signing with a simplified API.\n *\n * Extended capabilities:\n *   - Batch signing (sign multiple messages efficiently)\n *   - Signature caching with configurable TTL\n *   - Key rotation with grace period (old signatures still verify)\n *   - Serialization (toJSON / fromJSON for persistence)\n *   - Metrics tracking (sign count, verify count, cache hit rate)\n *\n * @version 2.0.0\n */\nimport {\n  HybridCryptoProvider,\n  Ed25519CryptoProvider,\n  MLDSACryptoProvider,\n  type HybridKeyPair,\n  type CompositeSignature,\n  type CompositeVerificationResult,\n  isPostQuantumAvailable,\n} from './HybridCryptoProvider';\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n/** Options for constructing a HybridSigner. */\nexport interface HybridSignerOptions {\n  /** Enable post-quantum signing (default: true). */\n  enablePQ?: boolean;\n  /** Default cache TTL in milliseconds (default: 300_000 = 5 minutes). */\n  cacheTTLMs?: number;\n  /** Grace period in milliseconds during which old keys still verify after rotation (default: 600_000 = 10 minutes). */\n  keyRotationGracePeriodMs?: number;\n}\n\n/** A single entry in the batch signing result. */\nexport interface BatchSignResult {\n  /** Index in the original input array. */\n  index: number;\n  /** The composite signature, or null if signing failed. */\n  signature: CompositeSignature | null;\n  /** Error message if signing failed for this item. */\n  error?: string;\n}\n\n/** Metrics snapshot from the signer. */\nexport interface SignerMetrics {\n  /** Total sign() and signBatch() individual operations. */\n  signCount: number;\n  /** Total verify() calls. */\n  verifyCount: number;\n  /** Cache hit count (signatures served from cache). */\n  cacheHits: number;\n  /** Cache miss count (signatures computed fresh). */\n  cacheMisses: number;\n  /** Computed cache hit rate (0..1). Returns 0 if no lookups occurred. */\n  cacheHitRate: number;\n  /** Number of key rotations performed. */\n  keyRotationCount: number;\n  /** Number of entries currently in the signature cache. */\n  cacheSize: number;\n  /** Timestamp of last sign operation (ISO 8601), or null. */\n  lastSignAt: string | null;\n  /** Timestamp of last verify operation (ISO 8601), or null. */\n  lastVerifyAt: string | null;\n}\n\n/** Serialized form of a HybridSigner for persistence. */\nexport interface SerializedHybridSigner {\n  version: number;\n  enablePQ: boolean;\n  cacheTTLMs: number;\n  keyRotationGracePeriodMs: number;\n  currentKeyPair: HybridKeyPair | null;\n  retiredKeyPairs: Array<{ keyPair: HybridKeyPair; retiredAt: string; expiresAt: string }>;\n  metrics: Omit<SignerMetrics, 'cacheHitRate' | 'cacheSize'>;\n}\n\n// ---------------------------------------------------------------------------\n// Internal helpers\n// ---------------------------------------------------------------------------\n\ninterface CacheEntry {\n  signature: CompositeSignature;\n  createdAt: number;\n}\n\nfunction messageToKey(message: Uint8Array): string {\n  // Use a fast base64 fingerprint as cache key. For large messages\n  // we hash the first 256 + last 256 bytes plus the length to avoid\n  // storing giant keys while still minimising collisions.\n  if (message.length <= 512) {\n    return Buffer.from(message).toString('base64');\n  }\n  const head = message.slice(0, 256);\n  const tail = message.slice(message.length - 256);\n  const combined = new Uint8Array(head.length + tail.length + 4);\n  combined.set(head, 0);\n  combined.set(tail, head.length);\n  // Embed length as 4 big-endian bytes\n  const view = new DataView(combined.buffer, combined.byteOffset + head.length + tail.length, 4);\n  view.setUint32(0, message.length, false);\n  return Buffer.from(combined).toString('base64');\n}\n\n// ---------------------------------------------------------------------------\n// HybridSigner\n// ---------------------------------------------------------------------------\n\nexport class HybridSigner {\n  private provider: HybridCryptoProvider;\n  private keyPair: HybridKeyPair | null = null;\n\n  // -- Key rotation state --\n  private retiredKeyPairs: Array<{ keyPair: HybridKeyPair; retiredAt: number; expiresAt: number }> =\n    [];\n  private readonly gracePeriodMs: number;\n\n  // -- Signature cache --\n  private readonly signatureCache: Map<string, CacheEntry> = new Map();\n  private readonly cacheTTLMs: number;\n\n  // -- Metrics --\n  private _signCount = 0;\n  private _verifyCount = 0;\n  private _cacheHits = 0;\n  private _cacheMisses = 0;\n  private _keyRotationCount = 0;\n  private _lastSignAt: string | null = null;\n  private _lastVerifyAt: string | null = null;\n\n  // -- Options (for serialisation) --\n  private readonly _enablePQ: boolean;\n\n  constructor(options: HybridSignerOptions = {}) {\n    this._enablePQ = options.enablePQ !== false;\n    this.cacheTTLMs = options.cacheTTLMs ?? 300_000;\n    this.gracePeriodMs = options.keyRotationGracePeriodMs ?? 600_000;\n\n    const classical = new Ed25519CryptoProvider();\n    const pq = this._enablePQ ? new MLDSACryptoProvider() : undefined;\n    this.provider = new HybridCryptoProvider(classical, pq);\n  }\n\n  // =========================================================================\n  // Key management\n  // =========================================================================\n\n  /**\n   * Generate a new hybrid key pair.\n   *\n   * If a key pair already exists, it is retired (moved to the retired list\n   * with a grace period during which its signatures can still be verified).\n   */\n  async generateKeys(kid?: string): Promise<HybridKeyPair> {\n    if (this.keyPair) {\n      // Retire the current key pair\n      const now = Date.now();\n      this.retiredKeyPairs.push({\n        keyPair: this.keyPair,\n        retiredAt: now,\n        expiresAt: now + this.gracePeriodMs,\n      });\n      this._keyRotationCount++;\n\n      // Purge expired retired keys\n      this.purgeExpiredKeys();\n    }\n\n    // Clear signature cache on key rotation — signatures from old key are\n    // still verifiable via retired list but we don't want to serve them for\n    // new sign() calls.\n    this.signatureCache.clear();\n\n    this.keyPair = await this.provider.generateHybridKeyPair(kid);\n    return this.keyPair;\n  }\n\n  /**\n   * Explicitly rotate the key pair, returning the new key pair.\n   *\n   * Equivalent to calling generateKeys() when a key pair already exists,\n   * but throws if no initial key pair has been created.\n   */\n  async rotateKeys(kid?: string): Promise<HybridKeyPair> {\n    if (!this.keyPair) {\n      throw new Error('Cannot rotate keys: no existing key pair. Call generateKeys() first.');\n    }\n    return this.generateKeys(kid);\n  }\n\n  /** Remove expired retired key pairs. */\n  private purgeExpiredKeys(): void {\n    const now = Date.now();\n    this.retiredKeyPairs = this.retiredKeyPairs.filter((rk) => rk.expiresAt > now);\n  }\n\n  /** Get the list of retired key pairs still within their grace period. */\n  getRetiredKeyPairs(): ReadonlyArray<{\n    keyPair: HybridKeyPair;\n    retiredAt: number;\n    expiresAt: number;\n  }> {\n    this.purgeExpiredKeys();\n    return this.retiredKeyPairs;\n  }\n\n  // =========================================================================\n  // Signing\n  // =========================================================================\n\n  /**\n   * Sign a single message, using the cache when available.\n   */\n  async sign(message: string | Uint8Array): Promise<CompositeSignature> {\n    if (!this.keyPair) throw new Error('Call generateKeys() first');\n    const bytes = typeof message === 'string' ? new TextEncoder().encode(message) : message;\n\n    // Check cache\n    const cacheKey = messageToKey(bytes);\n    const cached = this.getCachedSignature(cacheKey);\n    if (cached) {\n      this._cacheHits++;\n      this._signCount++;\n      this._lastSignAt = new Date().toISOString();\n      return cached;\n    }\n\n    this._cacheMisses++;\n    const sig = await this.provider.signComposite(bytes, this.keyPair);\n\n    // Store in cache\n    this.signatureCache.set(cacheKey, { signature: sig, createdAt: Date.now() });\n    this._signCount++;\n    this._lastSignAt = new Date().toISOString();\n    return sig;\n  }\n\n  /**\n   * Sign multiple messages efficiently in a single batch.\n   *\n   * All messages are signed with the current key pair. The method returns\n   * results for each message (including per-item errors without aborting\n   * the entire batch).\n   */\n  async signBatch(messages: Array<string | Uint8Array>): Promise<BatchSignResult[]> {\n    if (!this.keyPair) throw new Error('Call generateKeys() first');\n\n    const results: BatchSignResult[] = [];\n\n    for (let i = 0; i < messages.length; i++) {\n      try {\n        const sig = await this.sign(messages[i]);\n        results.push({ index: i, signature: sig });\n      } catch (err: unknown) {\n        const errorMessage = err instanceof Error ? err.message : String(err);\n        results.push({ index: i, signature: null, error: errorMessage });\n      }\n    }\n\n    return results;\n  }\n\n  // =========================================================================\n  // Verification\n  // =========================================================================\n\n  /**\n   * Verify a signature against a message.\n   *\n   * If keyPair is not provided, the signer checks the current key pair\n   * first, then falls back to retired key pairs still within their grace\n   * period. This enables seamless key rotation: signatures made with the\n   * previous key continue to verify during the grace window.\n   */\n  async verify(\n    message: string | Uint8Array,\n    signature: CompositeSignature,\n    keyPair?: HybridKeyPair\n  ): Promise<CompositeVerificationResult> {\n    this._verifyCount++;\n    this._lastVerifyAt = new Date().toISOString();\n    const bytes = typeof message === 'string' ? new TextEncoder().encode(message) : message;\n\n    // If an explicit key pair is provided, just use that.\n    if (keyPair) {\n      return this.provider.verifyComposite(bytes, signature, keyPair);\n    }\n\n    // Try current key pair\n    if (this.keyPair) {\n      const result = await this.provider.verifyComposite(bytes, signature, this.keyPair);\n      if (result.valid) return result;\n    }\n\n    // Try retired key pairs (grace period)\n    this.purgeExpiredKeys();\n    for (const retired of this.retiredKeyPairs) {\n      const result = await this.provider.verifyComposite(bytes, signature, retired.keyPair);\n      if (result.valid) return result;\n    }\n\n    // Nothing verified\n    return {\n      valid: false,\n      classicalValid: false,\n      pqValid: null,\n      algorithm: signature.algorithm,\n      error: 'Signature did not verify against current or any retired key pair',\n    };\n  }\n\n  // =========================================================================\n  // Cache management\n  // =========================================================================\n\n  /** Retrieve a cached signature if it exists and has not expired. */\n  private getCachedSignature(cacheKey: string): CompositeSignature | null {\n    const entry = this.signatureCache.get(cacheKey);\n    if (!entry) return null;\n    if (Date.now() - entry.createdAt > this.cacheTTLMs) {\n      this.signatureCache.delete(cacheKey);\n      return null;\n    }\n    return entry.signature;\n  }\n\n  /** Evict all entries from the signature cache. */\n  clearCache(): void {\n    this.signatureCache.clear();\n  }\n\n  /** Evict only expired entries from the signature cache. */\n  pruneCache(): number {\n    const now = Date.now();\n    let pruned = 0;\n    for (const [key, entry] of this.signatureCache) {\n      if (now - entry.createdAt > this.cacheTTLMs) {\n        this.signatureCache.delete(key);\n        pruned++;\n      }\n    }\n    return pruned;\n  }\n\n  // =========================================================================\n  // Metrics\n  // =========================================================================\n\n  /** Return a snapshot of current metrics. */\n  getMetrics(): SignerMetrics {\n    const totalLookups = this._cacheHits + this._cacheMisses;\n    return {\n      signCount: this._signCount,\n      verifyCount: this._verifyCount,\n      cacheHits: this._cacheHits,\n      cacheMisses: this._cacheMisses,\n      cacheHitRate: totalLookups > 0 ? this._cacheHits / totalLookups : 0,\n      keyRotationCount: this._keyRotationCount,\n      cacheSize: this.signatureCache.size,\n      lastSignAt: this._lastSignAt,\n      lastVerifyAt: this._lastVerifyAt,\n    };\n  }\n\n  /** Reset all metrics counters to zero. */\n  resetMetrics(): void {\n    this._signCount = 0;\n    this._verifyCount = 0;\n    this._cacheHits = 0;\n    this._cacheMisses = 0;\n    this._keyRotationCount = 0;\n    this._lastSignAt = null;\n    this._lastVerifyAt = null;\n  }\n\n  // =========================================================================\n  // Serialization\n  // =========================================================================\n\n  /**\n   * Serialize the signer state for persistence.\n   *\n   * The signature cache is NOT serialized (it is ephemeral). The provider\n   * instance is not serializable either — it will be reconstructed on\n   * fromJSON().\n   */\n  toJSON(): SerializedHybridSigner {\n    return {\n      version: 2,\n      enablePQ: this._enablePQ,\n      cacheTTLMs: this.cacheTTLMs,\n      keyRotationGracePeriodMs: this.gracePeriodMs,\n      currentKeyPair: this.keyPair,\n      retiredKeyPairs: this.retiredKeyPairs.map((rk) => ({\n        keyPair: rk.keyPair,\n        retiredAt: new Date(rk.retiredAt).toISOString(),\n        expiresAt: new Date(rk.expiresAt).toISOString(),\n      })),\n      metrics: {\n        signCount: this._signCount,\n        verifyCount: this._verifyCount,\n        cacheHits: this._cacheHits,\n        cacheMisses: this._cacheMisses,\n        keyRotationCount: this._keyRotationCount,\n        lastSignAt: this._lastSignAt,\n        lastVerifyAt: this._lastVerifyAt,\n      },\n    };\n  }\n\n  /**\n   * Restore a HybridSigner from its serialized form.\n   *\n   * Reconstructs the provider (Ed25519 + optional ML-DSA) and restores\n   * key pairs, retired keys (still within grace period), and metrics.\n   */\n  static fromJSON(data: SerializedHybridSigner): HybridSigner {\n    const signer = new HybridSigner({\n      enablePQ: data.enablePQ,\n      cacheTTLMs: data.cacheTTLMs,\n      keyRotationGracePeriodMs: data.keyRotationGracePeriodMs,\n    });\n\n    signer.keyPair = data.currentKeyPair;\n\n    // Restore retired key pairs, filtering out any that have already expired\n    const now = Date.now();\n    signer.retiredKeyPairs = data.retiredKeyPairs\n      .map((rk) => ({\n        keyPair: rk.keyPair,\n        retiredAt: new Date(rk.retiredAt).getTime(),\n        expiresAt: new Date(rk.expiresAt).getTime(),\n      }))\n      .filter((rk) => rk.expiresAt > now);\n\n    // Restore metrics\n    if (data.metrics) {\n      signer._signCount = data.metrics.signCount ?? 0;\n      signer._verifyCount = data.metrics.verifyCount ?? 0;\n      signer._cacheHits = data.metrics.cacheHits ?? 0;\n      signer._cacheMisses = data.metrics.cacheMisses ?? 0;\n      signer._keyRotationCount = data.metrics.keyRotationCount ?? 0;\n      signer._lastSignAt = data.metrics.lastSignAt ?? null;\n      signer._lastVerifyAt = data.metrics.lastVerifyAt ?? null;\n    }\n\n    return signer;\n  }\n\n  // =========================================================================\n  // Accessors (preserved from v1)\n  // =========================================================================\n\n  getKeyPair(): HybridKeyPair | null {\n    return this.keyPair;\n  }\n  hasPQ(): boolean {\n    return this.provider.hasPQProvider();\n  }\n  static async isPQAvailable(): Promise<boolean> {\n    return isPostQuantumAvailable();\n  }\n}\n","/**\n * HoloScript MCP Agent Identity Tools\n *\n * Thin MCP wrapper around the compiler Agent Identity Framework. These tools\n * let autonomous agents issue, verify, and inspect workflow-bound identity\n * tokens without reimplementing the identity layer outside HoloScript.\n *\n * SOVEREIGN TOKEN PATH (dependency-sovereignty-ladder, 2026-07-16):\n * this path no longer touches the `jsonwebtoken` package. Tokens are UCAN-style\n * capability tokens signed in-tree:\n *   - issue_agent_token  → CapabilityTokenIssuer.issueRoot (Ed25519 / EdDSA),\n *     with workflow intent carried in the token facts, PLUS a HybridSigner\n *     ML-DSA-65 dual-signature envelope over the raw token (additive output).\n *   - verify_agent_token → FAIL CLOSED. Capability tokens verify through\n *     CapabilityTokenIssuer.verify (signature, expiry, not-before, replay).\n *     Any legacy jsonwebtoken/HS256-envelope token is rejected with an explicit\n *     reason (LEGACY_JWT_REJECTED) — never verified, never thrown.\n *     Every verify call emits an append-only NDJSON receipt (same pattern as\n *     compute-trace-store.ts / daemon-emergence-store.ts).\n *\n * Presentation cache: CapabilityTokenIssuer.verify consumes the token nonce\n * (replay protection), which would make a second inspection of the SAME raw\n * token fail. To keep the legacy inspect-many-times contract (verify →\n * check_permission → get_delegation_chain) working, successful verifications\n * are cached in-process keyed by the SHA-256 of the exact raw token bytes.\n * A byte-identical re-presentation is served from the cache (signature was\n * already proven for those exact bytes; expiry is re-checked on every hit).\n * Any tampered token differs in bytes, misses the cache, and fails signature\n * verification.\n *\n * PERMANENT CARVE-OUT: @noble/post-quantum remains the crypto primitive via\n * HybridCryptoProvider/HybridSigner. No signature math is implemented here.\n */\n\nimport * as crypto from 'crypto';\nimport * as fs from 'fs';\nimport * as os from 'os';\nimport * as path from 'path';\nimport type { Tool } from '@modelcontextprotocol/sdk/types.js';\nimport {\n  AgentPermission,\n  AgentRole,\n  WorkflowStep,\n  calculateAgentChecksum,\n  generateAgentKeyPair,\n  getDefaultPermissions,\n  type AgentConfig,\n} from '../../core/src/compiler/identity/AgentIdentity';\nimport {\n  ACTION_TO_PERMISSION,\n  CapabilityActions,\n  HOLOSCRIPT_RESOURCE_ALL,\n  HOLOSCRIPT_RESOURCE_SCHEME,\n  PERMISSION_TO_ACTION,\n  type AttenuationChain,\n  type Capability,\n  type CapabilityTokenPayload,\n} from '../../core/src/compiler/identity/CapabilityToken';\nimport {\n  getCapabilityTokenIssuer,\n  resetCapabilityTokenIssuer,\n} from '../../core/src/compiler/identity/CapabilityTokenIssuer';\nimport { HybridSigner } from '../../core/src/compiler/identity/HybridSigner';\nimport type { CompositeSignature } from '../../core/src/compiler/identity/HybridCryptoProvider';\n\nconst TOOL_NAMES = [\n  'issue_agent_token',\n  'verify_agent_token',\n  'check_permission',\n  'get_delegation_chain',\n] as const;\n\ntype AgentIdentityToolName = (typeof TOOL_NAMES)[number];\n\nconst agentRoles = Object.values(AgentRole);\nconst agentPermissions = Object.values(AgentPermission);\nconst workflowSteps = Object.values(WorkflowStep);\n\nconst CAPABILITY_TOKEN_FORMAT = 'ucan-capability@0.10.0';\nconst DEFAULT_AUDIENCE = 'holoscript-compiler';\n\nexport const agentIdentityTools: Tool[] = [\n  {\n    name: 'issue_agent_token',\n    description:\n      'Issue a short-lived sovereign HoloScript capability token (UCAN-style, Ed25519/EdDSA-signed in-tree) ' +\n      'with role-derived capabilities, workflow intent, and proof-of-possession public key binding. ' +\n      'Also returns an ML-DSA-65 dual-signature envelope (HybridSigner) over the token.',\n    inputSchema: {\n      type: 'object' as const,\n      properties: {\n        role: {\n          type: 'string',\n          enum: agentRoles,\n          description: 'Compiler agent role receiving the token.',\n        },\n        name: {\n          type: 'string',\n          description: 'Stable agent instance name. Defaults to mcp-<role>.',\n        },\n        version: {\n          type: 'string',\n          description: 'Agent implementation version. Defaults to 1.0.0.',\n        },\n        workflowId: {\n          type: 'string',\n          description: 'Workflow/run identifier bound into the token intent.',\n        },\n        workflowStep: {\n          type: 'string',\n          enum: workflowSteps,\n          description: 'Current compiler workflow step. Defaults to parse_tokens.',\n        },\n        initiatedBy: {\n          type: 'string',\n          enum: agentRoles,\n          description: 'Agent role that initiated this delegation. Defaults to orchestrator.',\n        },\n        delegationChain: {\n          type: 'array',\n          items: { type: 'string', enum: agentRoles },\n          description:\n            'Prior delegation chain. The issued role is appended by the identity framework.',\n        },\n        scope: {\n          type: 'string',\n          description: 'Optional package/path scope restriction embedded in the token.',\n        },\n        tools: {\n          type: 'array',\n          items: { type: 'string' },\n          description: 'Optional tool/capability labels included in the agent checksum.',\n        },\n        configuration: {\n          type: 'object',\n          description: 'Optional JSON configuration included in the agent checksum.',\n        },\n        executionContext: {\n          type: 'object',\n          description: 'Optional workflow execution context embedded in the token intent.',\n        },\n        tokenExpiration: {\n          oneOf: [{ type: 'string' }, { type: 'number' }],\n          description: 'Optional expiration, e.g. 15m, 24h, 7d, or a number of seconds.',\n        },\n        returnPrivateKey: {\n          type: 'boolean',\n          description:\n            'Return the generated Ed25519 private key for PoP signing. Defaults false; only request when the caller will sign HTTP requests immediately.',\n        },\n      },\n      required: ['role'],\n    },\n  },\n  {\n    name: 'verify_agent_token',\n    description:\n      'Verify a HoloScript sovereign capability token and return structured identity, capability, and workflow claims. ' +\n      'FAIL CLOSED: legacy jsonwebtoken/HS256-envelope tokens are rejected with an explicit reason and are never verified. ' +\n      'Every call emits an append-only NDJSON verification receipt.',\n    inputSchema: {\n      type: 'object' as const,\n      properties: {\n        token: {\n          type: 'string',\n          description: 'Capability token returned by issue_agent_token (raw JWT-shaped string).',\n        },\n        includePayload: {\n          type: 'boolean',\n          description: 'Include decoded non-secret claims in the response. Defaults true.',\n        },\n        pqEnvelope: {\n          type: 'object',\n          description:\n            'Optional ML-DSA-65 dual-signature envelope returned by issue_agent_token. When provided, the envelope must also verify (fail closed).',\n          properties: {\n            classicalSignature: {\n              type: 'string',\n              description: 'Base64 Ed25519 signature over the raw token.',\n            },\n            pqSignature: {\n              type: 'string',\n              description: 'Base64 ML-DSA-65 signature over the raw token.',\n            },\n            kid: { type: 'string', description: 'Key ID of the signing hybrid key pair.' },\n            signedAt: { type: 'string', description: 'ISO timestamp the envelope was created.' },\n          },\n          required: ['classicalSignature'],\n        },\n      },\n      required: ['token'],\n    },\n  },\n  {\n    name: 'check_permission',\n    description:\n      'Check whether a HoloScript capability token carries a permission (mapped to its UCAN capability action), optionally constrained to a workflow step. Fail closed on any non-capability token.',\n    inputSchema: {\n      type: 'object' as const,\n      properties: {\n        token: {\n          type: 'string',\n          description: 'Agent capability token to check.',\n        },\n        permission: {\n          type: 'string',\n          enum: agentPermissions,\n          description: 'Required compiler permission.',\n        },\n        workflowStep: {\n          type: 'string',\n          enum: workflowSteps,\n          description: 'Optional expected workflow step.',\n        },\n      },\n      required: ['token', 'permission'],\n    },\n  },\n  {\n    name: 'get_delegation_chain',\n    description:\n      'Read the workflow delegation chain and intent metadata from a HoloScript capability token. Fail closed on any non-capability token.',\n    inputSchema: {\n      type: 'object' as const,\n      properties: {\n        token: {\n          type: 'string',\n          description: 'Agent capability token to inspect.',\n        },\n      },\n      required: ['token'],\n    },\n  },\n];\n\nexport function isAgentIdentityToolName(name: string): name is AgentIdentityToolName {\n  return (TOOL_NAMES as readonly string[]).includes(name);\n}\n\nexport async function handleAgentIdentityTool(\n  name: string,\n  args: Record<string, unknown>\n): Promise<unknown> {\n  if (!isAgentIdentityToolName(name)) {\n    throw new Error(`Unknown agent identity tool: ${name}`);\n  }\n\n  switch (name) {\n    case 'issue_agent_token':\n      return issueAgentToken(args);\n    case 'verify_agent_token':\n      return verifyAgentToken(args);\n    case 'check_permission':\n      return checkPermission(args);\n    case 'get_delegation_chain':\n      return getDelegationChain(args);\n  }\n}\n\n// ---------------------------------------------------------------------------\n// ML-DSA-65 dual-signature envelope signer (HybridSigner singleton)\n// ---------------------------------------------------------------------------\n\nlet envelopeSignerPromise: Promise<HybridSigner> | null = null;\n\n/**\n * Lazily create the process-wide HybridSigner used to dual-sign issued tokens.\n * Prefers Ed25519 + ML-DSA-65 (via @noble/post-quantum — the permanent crypto\n * primitive); falls back to Ed25519-only if the PQ module cannot be loaded so\n * token issuance never depends on optional-module resolution.\n */\nfunction getEnvelopeSigner(): Promise<HybridSigner> {\n  if (!envelopeSignerPromise) {\n    envelopeSignerPromise = (async () => {\n      try {\n        const signer = new HybridSigner();\n        await signer.generateKeys('mcp-agent-identity');\n        return signer;\n      } catch {\n        const fallback = new HybridSigner({ enablePQ: false });\n        await fallback.generateKeys('mcp-agent-identity');\n        return fallback;\n      }\n    })();\n  }\n  return envelopeSignerPromise;\n}\n\n// ---------------------------------------------------------------------------\n// Verification receipts — append-only NDJSON\n// (same write pattern as compute-trace-store.ts / daemon-emergence-store.ts)\n// ---------------------------------------------------------------------------\n\ninterface VerifyReceiptRecord {\n  /** Receipt schema tag. */\n  receipt: 'agent-token-verify.v1';\n  /** ISO timestamp of the verification. */\n  ts: string;\n  /** MCP tool that performed the verification. */\n  tool: AgentIdentityToolName;\n  /** SHA-256 hex of the exact raw token presented (the token itself is never logged). */\n  tokenSha256: string;\n  /** Detected token format. */\n  tokenFormat: 'ucan-capability' | 'legacy-jwt' | 'unknown';\n  /** Final verdict for this presentation. */\n  valid: boolean;\n  /** Whether the verdict was served from the in-process presentation cache. */\n  cached: boolean;\n  errorCode?: string;\n  error?: string;\n  issuer?: string;\n  audience?: string;\n  nonce?: string;\n  workflowId?: string;\n  /** Whether an ML-DSA-65 dual-signature envelope was presented and checked. */\n  envelopeChecked: boolean;\n  envelopeValid?: boolean;\n}\n\nfunction resolveReceiptPath(): string {\n  const override = process.env.AGENT_IDENTITY_RECEIPT_PATH;\n  if (typeof override === 'string' && override.trim().length > 0) {\n    return override;\n  }\n  const dataRoot =\n    process.env.HOLOMESH_DATA_DIR ||\n    path.join(\n      process.env.HOLOSCRIPT_CACHE_DIR || path.join(os.homedir(), '.holoscript'),\n      'holomesh'\n    );\n  return path.join(dataRoot, 'agent-identity', 'agent-token-verify-receipts.ndjson');\n}\n\n/**\n * Persist one verification receipt. Best-effort — a persistence failure must\n * never change the verification verdict. Returns the receipt path when the\n * write succeeded.\n */\nfunction emitVerifyReceipt(record: VerifyReceiptRecord): string | undefined {\n  if (\n    process.env.NODE_ENV === 'test' &&\n    process.env.HOLOMESH_TEST_DISABLE_AGENT_IDENTITY_RECEIPTS === '1'\n  ) {\n    return undefined;\n  }\n  const receiptPath = resolveReceiptPath();\n  try {\n    fs.mkdirSync(path.dirname(receiptPath), { recursive: true });\n    fs.appendFileSync(receiptPath, `${JSON.stringify(record)}\\n`, 'utf8');\n    return receiptPath;\n  } catch (err) {\n    console.warn(`[AgentIdentityTools] receipt append failed: ${(err as Error).message}`);\n    return undefined;\n  }\n}\n\n// ---------------------------------------------------------------------------\n// Token presentation (fail-closed verification core)\n// ---------------------------------------------------------------------------\n\ninterface TokenPresentation {\n  valid: boolean;\n  tokenFormat: 'ucan-capability' | 'legacy-jwt' | 'unknown';\n  cached: boolean;\n  tokenSha256: string;\n  payload?: CapabilityTokenPayload;\n  chain?: AttenuationChain;\n  error?: string;\n  errorCode?: string;\n}\n\ninterface CachedPresentation {\n  payload: CapabilityTokenPayload;\n  chain?: AttenuationChain;\n}\n\n/** Successful presentations keyed by SHA-256 of the exact raw token bytes. */\nconst presentationCache = new Map<string, CachedPresentation>();\n\nfunction sha256Hex(value: string): string {\n  return crypto.createHash('sha256').update(value, 'utf8').digest('hex');\n}\n\nfunction decodeJsonSegment(segment: string): Record<string, unknown> | undefined {\n  try {\n    const parsed: unknown = JSON.parse(Buffer.from(segment, 'base64url').toString('utf8'));\n    if (parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed)) {\n      return parsed as Record<string, unknown>;\n    }\n    return undefined;\n  } catch {\n    return undefined;\n  }\n}\n\nfunction rejected(\n  tokenSha256: string,\n  tokenFormat: TokenPresentation['tokenFormat'],\n  errorCode: string,\n  error: string\n): TokenPresentation {\n  return { valid: false, tokenFormat, cached: false, tokenSha256, error, errorCode };\n}\n\n/**\n * Verify one raw token presentation. NEVER throws — every failure mode maps to\n * a rejected-with-explicit-reason result (fail closed).\n */\nfunction verifyPresentation(rawToken: string): TokenPresentation {\n  const tokenSha256 = sha256Hex(rawToken);\n\n  try {\n    const parts = rawToken.split('.');\n    if (parts.length !== 3 || parts.some((part) => part.length === 0)) {\n      return rejected(\n        tokenSha256,\n        'unknown',\n        'MALFORMED_TOKEN',\n        'Malformed token: expected a three-part header.payload.signature string.'\n      );\n    }\n\n    const header = decodeJsonSegment(parts[0]);\n    if (!header || typeof header.alg !== 'string') {\n      return rejected(\n        tokenSha256,\n        'unknown',\n        'MALFORMED_TOKEN',\n        'Malformed token: header segment is not decodable JSON with an alg claim.'\n      );\n    }\n\n    if (header.alg !== 'EdDSA') {\n      // Legacy jsonwebtoken path issued HS256-envelope tokens. Reject them all\n      // explicitly — the sovereign capability issuer is the only accepted path.\n      return rejected(\n        tokenSha256,\n        'legacy-jwt',\n        'LEGACY_JWT_REJECTED',\n        `Legacy ${header.alg} jsonwebtoken envelope is no longer accepted. ` +\n          'Reissue a sovereign capability token via issue_agent_token.'\n      );\n    }\n\n    if (header.ucv !== '0.10.0') {\n      return rejected(\n        tokenSha256,\n        'unknown',\n        'UNSUPPORTED_TOKEN_FORMAT',\n        'EdDSA token without a supported UCAN version (ucv) claim. Only capability tokens issued by issue_agent_token are accepted.'\n      );\n    }\n\n    // Byte-identical re-presentation of an already-proven token: serve from the\n    // presentation cache (re-checking expiry) instead of re-consuming the nonce.\n    const cachedEntry = presentationCache.get(tokenSha256);\n    if (cachedEntry) {\n      const now = Math.floor(Date.now() / 1000);\n      if (cachedEntry.payload.exp <= now) {\n        presentationCache.delete(tokenSha256);\n        return rejected(tokenSha256, 'ucan-capability', 'EXPIRED', 'Token expired');\n      }\n      return {\n        valid: true,\n        tokenFormat: 'ucan-capability',\n        cached: true,\n        tokenSha256,\n        payload: cachedEntry.payload,\n        chain: cachedEntry.chain,\n      };\n    }\n\n    const payload = decodeJsonSegment(parts[1]);\n    if (!payload) {\n      return rejected(\n        tokenSha256,\n        'ucan-capability',\n        'MALFORMED_TOKEN',\n        'Malformed token: payload segment is not decodable JSON.'\n      );\n    }\n\n    const facts = asRecord(payload.fct);\n    const publicKey = asString(facts?.publicKey);\n    if (!publicKey) {\n      return rejected(\n        tokenSha256,\n        'ucan-capability',\n        'MISSING_VERIFICATION_KEY',\n        'Capability token does not embed its Ed25519 verification key (fct.publicKey). Fail closed.'\n      );\n    }\n\n    const verification = getCapabilityTokenIssuer().verify(rawToken, publicKey);\n    if (!verification.valid || !verification.payload) {\n      return rejected(\n        tokenSha256,\n        'ucan-capability',\n        verification.errorCode ?? 'INVALID_SIGNATURE',\n        verification.error ?? 'Capability token verification failed.'\n      );\n    }\n\n    presentationCache.set(tokenSha256, {\n      payload: verification.payload,\n      chain: verification.chain,\n    });\n\n    return {\n      valid: true,\n      tokenFormat: 'ucan-capability',\n      cached: false,\n      tokenSha256,\n      payload: verification.payload,\n      chain: verification.chain,\n    };\n  } catch (error: unknown) {\n    // Fail closed — no verification error may escape as an unhandled throw.\n    return rejected(\n      tokenSha256,\n      'unknown',\n      'VERIFY_ERROR',\n      error instanceof Error ? error.message : String(error)\n    );\n  }\n}\n\nfunction receiptFromPresentation(\n  tool: AgentIdentityToolName,\n  presentation: TokenPresentation,\n  envelope?: { checked: boolean; valid?: boolean }\n): VerifyReceiptRecord {\n  const facts = asRecord(presentation.payload?.fct);\n  const workflow = asRecord(facts?.workflow);\n  return {\n    receipt: 'agent-token-verify.v1',\n    ts: new Date().toISOString(),\n    tool,\n    tokenSha256: presentation.tokenSha256,\n    tokenFormat: presentation.tokenFormat,\n    valid: presentation.valid,\n    cached: presentation.cached,\n    ...(presentation.errorCode ? { errorCode: presentation.errorCode } : {}),\n    ...(presentation.error ? { error: presentation.error } : {}),\n    ...(presentation.payload\n      ? {\n          issuer: presentation.payload.iss,\n          audience: presentation.payload.aud,\n          nonce: presentation.payload.nnc,\n        }\n      : {}),\n    ...(asString(workflow?.workflow_id) ? { workflowId: asString(workflow?.workflow_id) } : {}),\n    envelopeChecked: envelope?.checked ?? false,\n    ...(envelope?.checked ? { envelopeValid: envelope.valid === true } : {}),\n  };\n}\n\n// ---------------------------------------------------------------------------\n// Tool handlers\n// ---------------------------------------------------------------------------\n\nasync function issueAgentToken(args: Record<string, unknown>): Promise<Record<string, unknown>> {\n  const role = parseAgentRole(args.role, 'role');\n  const name = optionalString(args.name) ?? `mcp-${role}`;\n  const version = optionalString(args.version) ?? '1.0.0';\n  const workflowId = optionalString(args.workflowId) ?? `mcp-${Date.now()}`;\n  const workflowStep =\n    parseWorkflowStep(args.workflowStep, 'workflowStep', WorkflowStep.PARSE_TOKENS) ??\n    WorkflowStep.PARSE_TOKENS;\n  const initiatedBy = parseAgentRole(args.initiatedBy, 'initiatedBy', AgentRole.ORCHESTRATOR);\n  const delegationChain = parseRoleArray(args.delegationChain, 'delegationChain') ?? [];\n  const executionContext = optionalRecord(args.executionContext) ?? {};\n  const configuration = optionalRecord(args.configuration);\n  const tools = parseStringArray(args.tools, 'tools');\n  const returnPrivateKey = args.returnPrivateKey === true;\n  const scope = optionalString(args.scope);\n  const lifetimeSec = parseTokenExpirationSeconds(args.tokenExpiration);\n\n  const agentConfig: AgentConfig = {\n    role,\n    name,\n    version,\n    scope,\n    tools,\n    configuration,\n  };\n  const agentChecksum = calculateAgentChecksum(agentConfig);\n\n  const keyPair = await generateAgentKeyPair(role);\n\n  // Role permissions → UCAN capabilities (same bridge the identity framework uses).\n  const permissions = getDefaultPermissions(role);\n  const resource = scope ? `${HOLOSCRIPT_RESOURCE_SCHEME}${scope}` : HOLOSCRIPT_RESOURCE_ALL;\n  const capabilities: Capability[] = permissions.map((perm) => ({\n    with: resource,\n    can: PERMISSION_TO_ACTION[perm] || perm,\n  }));\n\n  const updatedDelegationChain = [...delegationChain, role];\n\n  const issuer = getCapabilityTokenIssuer();\n  const token = await issuer.issueRoot(\n    {\n      issuer: `agent:${role}:${name}`,\n      audience: DEFAULT_AUDIENCE,\n      capabilities,\n      ...(lifetimeSec !== undefined ? { lifetimeSec } : {}),\n      facts: {\n        agent: {\n          role,\n          name,\n          version,\n          checksum: agentChecksum,\n        },\n        workflow: {\n          workflow_id: workflowId,\n          workflow_step: workflowStep,\n          executed_by: role,\n          initiated_by: initiatedBy,\n          delegation_chain: updatedDelegationChain,\n          execution_context: executionContext,\n        },\n        ...(scope ? { scope } : {}),\n        publicKey: keyPair.publicKey,\n        kid: keyPair.kid,\n        thumbprint: keyPair.thumbprint,\n      },\n    },\n    keyPair\n  );\n\n  // ML-DSA-65 dual-signature envelope over the raw token (HybridSigner).\n  const envelopeSigner = await getEnvelopeSigner();\n  const envelopeSignature = await envelopeSigner.sign(token.raw);\n  const envelopeKeyPair = envelopeSigner.getKeyPair();\n\n  return {\n    ok: true,\n    token: token.raw,\n    tokenType: 'Bearer',\n    tokenFormat: CAPABILITY_TOKEN_FORMAT,\n    agentRole: role,\n    permissions,\n    capabilities: token.payload.att,\n    issuer: token.payload.iss,\n    audience: token.payload.aud,\n    nonce: token.payload.nnc,\n    workflow: {\n      workflowId,\n      workflowStep,\n      executedBy: role,\n      initiatedBy,\n      delegationChain: updatedDelegationChain,\n      executionContext,\n    },\n    key: {\n      kid: keyPair.kid,\n      thumbprint: keyPair.thumbprint,\n      publicKey: keyPair.publicKey,\n      ...(returnPrivateKey ? { privateKey: keyPair.privateKey } : {}),\n    },\n    privateKeyReturned: returnPrivateKey,\n    note: returnPrivateKey\n      ? 'Private key returned because returnPrivateKey=true. Treat it as secret PoP signing material.'\n      : 'Private key withheld. Call with returnPrivateKey=true only when the agent must sign PoP HTTP requests.',\n    expiresAt: new Date(token.payload.exp * 1000).toISOString(),\n    pqEnvelope: {\n      algorithm: envelopeSignature.algorithm,\n      kid: envelopeSignature.kid,\n      signedAt: envelopeSignature.signedAt,\n      classicalSignature: envelopeSignature.classicalSignature,\n      ...(envelopeSignature.pqSignature ? { pqSignature: envelopeSignature.pqSignature } : {}),\n      publicKeys: {\n        classical: envelopeKeyPair?.classicalKey.publicKey,\n        ...(envelopeKeyPair?.pqKey ? { pq: envelopeKeyPair.pqKey.publicKey } : {}),\n      },\n      note: 'Dual-signature envelope (Ed25519 + ML-DSA-65 when available) over the raw token. Pass back to verify_agent_token as pqEnvelope for post-quantum verification.',\n    },\n  };\n}\n\nasync function verifyAgentToken(args: Record<string, unknown>): Promise<Record<string, unknown>> {\n  const token = requiredString(args.token, 'token');\n  const includePayload = args.includePayload !== false;\n\n  const presentation = verifyPresentation(token);\n\n  // Optional ML-DSA-65 dual-signature envelope check — fail closed when presented.\n  let envelopeChecked = false;\n  let envelopeValid: boolean | undefined;\n  const envelopeArgs = optionalRecord(args.pqEnvelope);\n  if (envelopeArgs) {\n    envelopeChecked = true;\n    envelopeValid = false;\n    try {\n      const classicalSignature = asString(envelopeArgs.classicalSignature);\n      if (classicalSignature) {\n        const composite: CompositeSignature = {\n          classicalSignature,\n          ...(asString(envelopeArgs.pqSignature)\n            ? { pqSignature: asString(envelopeArgs.pqSignature) }\n            : {}),\n          algorithm: 'hybrid-ed25519-ml-dsa-65',\n          signedAt: asString(envelopeArgs.signedAt) ?? new Date(0).toISOString(),\n          kid: asString(envelopeArgs.kid) ?? 'unknown',\n        };\n        const signer = await getEnvelopeSigner();\n        const result = await signer.verify(token, composite);\n        envelopeValid = result.valid;\n      }\n    } catch {\n      envelopeValid = false;\n    }\n  }\n\n  const valid = presentation.valid && (!envelopeChecked || envelopeValid === true);\n  const errorCode =\n    presentation.errorCode ?? (envelopeChecked && envelopeValid !== true ? 'ENVELOPE_INVALID' : undefined);\n  const error =\n    presentation.error ??\n    (envelopeChecked && envelopeValid !== true\n      ? 'ML-DSA-65 dual-signature envelope did not verify against the issuing signer.'\n      : undefined);\n\n  const receipt = receiptFromPresentation('verify_agent_token', presentation, {\n    checked: envelopeChecked,\n    valid: envelopeValid,\n  });\n  receipt.valid = valid;\n  if (!valid && errorCode && !receipt.errorCode) receipt.errorCode = errorCode;\n  if (!valid && error && !receipt.error) receipt.error = error;\n  const receiptPath = emitVerifyReceipt(receipt);\n\n  return {\n    ok: true,\n    valid,\n    tokenFormat: presentation.tokenFormat,\n    cached: presentation.cached,\n    error,\n    errorCode,\n    envelopeChecked,\n    ...(envelopeChecked ? { envelopeValid } : {}),\n    payload:\n      includePayload && presentation.payload ? summarizePayload(presentation.payload) : undefined,\n    receipt: {\n      tokenSha256: presentation.tokenSha256,\n      ...(receiptPath ? { path: receiptPath } : {}),\n    },\n  };\n}\n\nasync function checkPermission(args: Record<string, unknown>): Promise<Record<string, unknown>> {\n  const token = requiredString(args.token, 'token');\n  const permission = parseAgentPermission(args.permission, 'permission');\n  const workflowStep = parseWorkflowStep(args.workflowStep, 'workflowStep');\n\n  const presentation = verifyPresentation(token);\n  emitVerifyReceipt(receiptFromPresentation('check_permission', presentation));\n\n  if (!presentation.valid || !presentation.payload) {\n    return {\n      ok: true,\n      valid: false,\n      allowed: false,\n      error: presentation.error,\n      errorCode: presentation.errorCode,\n    };\n  }\n\n  const payload = presentation.payload;\n  const facts = asRecord(payload.fct);\n  const workflow = asRecord(facts?.workflow);\n  const scope = asString(facts?.scope);\n  const action = PERMISSION_TO_ACTION[permission] || permission;\n  const resource = scope ? `${HOLOSCRIPT_RESOURCE_SCHEME}${scope}` : HOLOSCRIPT_RESOURCE_ALL;\n  const semantics = getCapabilityTokenIssuer().getSemantics();\n\n  let allowed = payload.att.some((cap) => semantics.canAccess(cap, resource, action));\n  if (allowed && workflowStep) {\n    allowed = asString(workflow?.workflow_step) === workflowStep;\n  }\n\n  return {\n    ok: true,\n    valid: true,\n    allowed,\n    permission,\n    workflowStep,\n    agentRole: asString(asRecord(facts?.agent)?.role),\n    grantedPermissions: permissionsFromCapabilities(payload.att),\n    reason: allowed\n      ? 'Token carries the requested capability and workflow constraint.'\n      : 'Token is valid but does not satisfy the requested capability or workflow constraint.',\n  };\n}\n\nasync function getDelegationChain(\n  args: Record<string, unknown>\n): Promise<Record<string, unknown>> {\n  const token = requiredString(args.token, 'token');\n\n  const presentation = verifyPresentation(token);\n  emitVerifyReceipt(receiptFromPresentation('get_delegation_chain', presentation));\n\n  if (!presentation.valid || !presentation.payload) {\n    return {\n      ok: true,\n      valid: false,\n      error: presentation.error,\n      errorCode: presentation.errorCode,\n      delegationChain: [],\n    };\n  }\n\n  const payload = presentation.payload;\n  const facts = asRecord(payload.fct);\n  const workflow = asRecord(facts?.workflow);\n\n  return {\n    ok: true,\n    valid: true,\n    subject: payload.iss,\n    agentRole: asString(asRecord(facts?.agent)?.role),\n    workflowId: asString(workflow?.workflow_id),\n    workflowStep: asString(workflow?.workflow_step),\n    initiatedBy: asString(workflow?.initiated_by),\n    executedBy: asString(workflow?.executed_by),\n    delegationChain: asStringArray(workflow?.delegation_chain) ?? [],\n    executionContext: asRecord(workflow?.execution_context) ?? {},\n    attenuationChain: presentation.chain,\n  };\n}\n\n// ---------------------------------------------------------------------------\n// Summaries\n// ---------------------------------------------------------------------------\n\nfunction summarizePayload(payload: CapabilityTokenPayload): Record<string, unknown> {\n  const facts = asRecord(payload.fct);\n  const agent = asRecord(facts?.agent);\n  const workflow = asRecord(facts?.workflow);\n  return {\n    issuer: payload.iss,\n    audience: payload.aud,\n    nonce: payload.nnc,\n    ...(payload.nbf !== undefined ? { notBefore: new Date(payload.nbf * 1000).toISOString() } : {}),\n    expiresAt: new Date(payload.exp * 1000).toISOString(),\n    agentRole: asString(agent?.role),\n    checksum: asRecord(agent?.checksum),\n    permissions: permissionsFromCapabilities(payload.att),\n    capabilities: payload.att,\n    scope: asString(facts?.scope),\n    intent: {\n      workflowId: asString(workflow?.workflow_id),\n      workflowStep: asString(workflow?.workflow_step),\n      executedBy: asString(workflow?.executed_by),\n      initiatedBy: asString(workflow?.initiated_by),\n      delegationChain: asStringArray(workflow?.delegation_chain) ?? [],\n      executionContext: asRecord(workflow?.execution_context) ?? {},\n    },\n    confirmation: asString(facts?.thumbprint) ? { jkt: asString(facts?.thumbprint) } : undefined,\n    publicKey: asString(facts?.publicKey),\n  };\n}\n\nfunction permissionsFromCapabilities(capabilities: Capability[]): AgentPermission[] {\n  const perms = new Set<AgentPermission>();\n  for (const cap of capabilities) {\n    if (cap.can === CapabilityActions.ALL) {\n      for (const perm of agentPermissions) perms.add(perm);\n      continue;\n    }\n    const perm = ACTION_TO_PERMISSION[cap.can];\n    if (perm) perms.add(perm);\n  }\n  return [...perms];\n}\n\n// ---------------------------------------------------------------------------\n// Test/reset surface\n// ---------------------------------------------------------------------------\n\n/**\n * Reset all module singletons (presentation cache, envelope signer, and the\n * global CapabilityTokenIssuer). Intended for tests.\n */\nexport function resetAgentIdentityTools(): void {\n  presentationCache.clear();\n  envelopeSignerPromise = null;\n  resetCapabilityTokenIssuer();\n}\n\n// ---------------------------------------------------------------------------\n// Argument parsing helpers\n// ---------------------------------------------------------------------------\n\nfunction requiredString(value: unknown, field: string): string {\n  if (typeof value !== 'string' || value.trim().length === 0) {\n    throw new Error(`${field} must be a non-empty string.`);\n  }\n  return value;\n}\n\nfunction optionalString(value: unknown): string | undefined {\n  return typeof value === 'string' && value.trim().length > 0 ? value : undefined;\n}\n\nfunction optionalRecord(value: unknown): Record<string, unknown> | undefined {\n  if (value === undefined || value === null) return undefined;\n  if (typeof value !== 'object' || Array.isArray(value)) {\n    throw new Error('Expected a JSON object.');\n  }\n  return value as Record<string, unknown>;\n}\n\nfunction asRecord(value: unknown): Record<string, unknown> | undefined {\n  if (value !== null && typeof value === 'object' && !Array.isArray(value)) {\n    return value as Record<string, unknown>;\n  }\n  return undefined;\n}\n\nfunction asString(value: unknown): string | undefined {\n  return typeof value === 'string' && value.length > 0 ? value : undefined;\n}\n\nfunction asStringArray(value: unknown): string[] | undefined {\n  if (!Array.isArray(value)) return undefined;\n  if (value.some((item) => typeof item !== 'string')) return undefined;\n  return value as string[];\n}\n\nfunction parseStringArray(value: unknown, field: string): string[] | undefined {\n  if (value === undefined || value === null) return undefined;\n  if (!Array.isArray(value) || value.some((item) => typeof item !== 'string')) {\n    throw new Error(`${field} must be an array of strings.`);\n  }\n  return value;\n}\n\nfunction parseRoleArray(value: unknown, field: string): AgentRole[] | undefined {\n  if (value === undefined || value === null) return undefined;\n  if (!Array.isArray(value)) {\n    throw new Error(`${field} must be an array of agent roles.`);\n  }\n  return value.map((item, index) => parseAgentRole(item, `${field}[${index}]`));\n}\n\nfunction parseAgentRole(value: unknown, field: string, fallback?: AgentRole): AgentRole {\n  if (value === undefined || value === null || value === '') {\n    if (fallback) return fallback;\n    throw new Error(`${field} is required.`);\n  }\n  if (typeof value === 'string' && agentRoles.includes(value as AgentRole)) {\n    return value as AgentRole;\n  }\n  throw new Error(`${field} must be one of: ${agentRoles.join(', ')}.`);\n}\n\nfunction parseAgentPermission(value: unknown, field: string): AgentPermission {\n  if (typeof value === 'string' && agentPermissions.includes(value as AgentPermission)) {\n    return value as AgentPermission;\n  }\n  throw new Error(`${field} must be one of: ${agentPermissions.join(', ')}.`);\n}\n\nfunction parseWorkflowStep(\n  value: unknown,\n  field: string,\n  fallback?: WorkflowStep\n): WorkflowStep | undefined {\n  if (value === undefined || value === null || value === '') return fallback;\n  if (typeof value === 'string' && workflowSteps.includes(value as WorkflowStep)) {\n    return value as WorkflowStep;\n  }\n  throw new Error(`${field} must be one of: ${workflowSteps.join(', ')}.`);\n}\n\n/**\n * Parse the legacy tokenExpiration input ('15m' / '24h' / '7d' / seconds) into\n * a lifetime in seconds for the capability issuer.\n */\nfunction parseTokenExpirationSeconds(value: unknown): number | undefined {\n  if (value === undefined || value === null || value === '') return undefined;\n  if (typeof value === 'number') {\n    if (!Number.isFinite(value) || value <= 0) {\n      throw new Error('tokenExpiration must be a positive finite number of seconds.');\n    }\n    return Math.floor(value);\n  }\n  if (typeof value === 'string') {\n    const match = value.match(/^(\\d+)([smhd])$/);\n    if (!match) {\n      throw new Error(\n        `Invalid tokenExpiration format: ${value}. Use e.g. 30s, 15m, 24h, 7d, or a number of seconds.`\n      );\n    }\n    const amount = parseInt(match[1], 10);\n    const multipliers: Record<string, number> = { s: 1, m: 60, h: 60 * 60, d: 60 * 60 * 24 };\n    return amount * multipliers[match[2]];\n  }\n  throw new Error('tokenExpiration must be a string or finite number.');\n}\n","/**\n * @holoscript/mcp-server — Observability MCP Tools\n *\n * 4 tools for querying traces, exporting OTLP, agent health, and Prometheus metrics.\n *\n * Part of HoloScript v5.6 \"Observable Platform\".\n */\n\nimport { Tool } from '@modelcontextprotocol/sdk/types.js';\nimport { getDefaultRegistry } from '@holoscript/framework/agents';\nimport { getTelemetryCollector, getPrometheusMetrics, OTLPExporter } from '@holoscript/core';\nimport type { OTLPExporterConfig } from '@holoscript/core';\n\n// =============================================================================\n// TOOL DEFINITIONS\n// =============================================================================\n\nexport const observabilityTools: Tool[] = [\n  {\n    name: 'query_traces',\n    description:\n      'Query distributed trace spans by traceId, agent, or time range. Returns OTel-format spans for debugging agent orchestration.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        traceId: {\n          type: 'string',\n          description: 'Filter by trace ID',\n        },\n        agentId: {\n          type: 'string',\n          description: 'Filter by agent ID',\n        },\n        limit: {\n          type: 'number',\n          description: 'Max spans to return (default 50)',\n        },\n      },\n    },\n  },\n  {\n    name: 'export_traces_otlp',\n    description:\n      'Export collected trace spans to an OTLP/HTTP endpoint. Requires an endpoint URL. Returns export result with span count and status.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        endpoint: {\n          type: 'string',\n          description: 'OTLP/HTTP endpoint URL (e.g. http://localhost:4318/v1/traces)',\n        },\n        serviceName: {\n          type: 'string',\n          description: 'Service name for resource attributes (default: holoscript)',\n        },\n      },\n      required: ['endpoint'],\n    },\n  },\n  {\n    name: 'get_agent_health',\n    description:\n      'Get health status of registered agents including count, status breakdown, and telemetry stats.',\n    inputSchema: {\n      type: 'object',\n      properties: {},\n    },\n  },\n  {\n    name: 'get_metrics_prometheus',\n    description:\n      'Get all collected metrics in Prometheus exposition text format. Use for monitoring dashboards and alerting.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        prefix: {\n          type: 'string',\n          description: 'Metric prefix filter (default: holoscript)',\n        },\n      },\n    },\n  },\n  {\n    name: 'holo_service_scaffold',\n    description:\n      'Generate service observability SQL, StartupHealthCheck wiring, alert seeds, cleanup job, and @serviceObservability snippet from a .hsplus service composition or structured service config.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        composition: {\n          type: 'string',\n          description:\n            'Optional .hsplus service composition containing @serviceObservability fields.',\n        },\n        serviceName: {\n          type: 'string',\n          description: 'Service name. Overrides service_name parsed from composition.',\n        },\n        requiredTables: {\n          type: 'array',\n          items: { type: 'string' },\n          description: 'Required runtime tables for startup schema validation.',\n        },\n        healthChecks: {\n          type: 'array',\n          description:\n            'Startup health probes, e.g. [{service:\"CostGovernor\",check:\"method-exists\",method:\"enforceBudget\"}].',\n          items: { type: 'object' },\n        },\n        alertRules: {\n          type: 'array',\n          description: 'Alert rules to seed into the alerts table.',\n          items: { type: 'object' },\n        },\n        retentionDays: {\n          type: 'number',\n          description: 'Retention window for scheduled operation_metrics cleanup. Default 90.',\n        },\n        npcCostCeilingUsdPerDay: {\n          type: 'number',\n          description: 'Default api_quota ceiling for NPC runtime cost. Default 0.50.',\n        },\n        headlessAgentCostCeilingUsdPerDay: {\n          type: 'number',\n          description: 'Default api_quota ceiling for headless agents. Default 5.00.',\n        },\n        attributionAccuracyFloor: {\n          type: 'number',\n          description: 'CI attribution accuracy floor. Default 0.80.',\n        },\n      },\n    },\n  },\n];\n\n// =============================================================================\n// HANDLER\n// =============================================================================\n\nexport async function handleObservabilityTool(\n  name: string,\n  args: Record<string, unknown>\n): Promise<unknown> {\n  switch (name) {\n    case 'query_traces':\n      return handleQueryTraces(args);\n    case 'export_traces_otlp':\n      return handleExportTracesOtlp(args);\n    case 'get_agent_health':\n      return handleGetAgentHealth();\n    case 'get_metrics_prometheus':\n      return handleGetMetricsPrometheus(args);\n    case 'holo_service_scaffold':\n      return handleHoloServiceScaffold(args);\n    default:\n      throw new Error(`Unknown observability tool: ${name}`);\n  }\n}\n\n// =============================================================================\n// TOOL IMPLEMENTATIONS\n// =============================================================================\n\nfunction handleQueryTraces(args: Record<string, unknown>) {\n  const collector = getTelemetryCollector();\n  const traceId = args.traceId as string | undefined;\n  const agentId = args.agentId as string | undefined;\n  const limit = (args.limit as number) ?? 50;\n\n  if (traceId) {\n    const spans = collector.getTraceSpans(traceId);\n    const otelSpans = collector.exportToOTel().filter((s: any) => s.traceId === traceId);\n    return {\n      traceId,\n      spans: otelSpans.slice(0, limit),\n      totalSpans: spans.length,\n    };\n  }\n\n  // Export all completed spans\n  let otelSpans = collector.exportToOTel();\n\n  // Filter by agent if specified\n  if (agentId) {\n    otelSpans = otelSpans.filter((s: any) =>\n      s.attributes.some((a: any) => a.key === 'agent.id' && a.value.stringValue === agentId)\n    );\n  }\n\n  return {\n    spans: otelSpans.slice(0, limit),\n    totalSpans: otelSpans.length,\n    stats: collector.getStats(),\n  };\n}\n\nasync function handleExportTracesOtlp(args: Record<string, unknown>) {\n  const endpoint = args.endpoint as string;\n  const serviceName = (args.serviceName as string) ?? 'holoscript';\n\n  if (!endpoint) {\n    throw new Error('endpoint is required for OTLP export');\n  }\n\n  const collector = getTelemetryCollector();\n  const spans = collector.exportToOTel();\n\n  if (spans.length === 0) {\n    return {\n      success: true,\n      spanCount: 0,\n      message: 'No completed spans to export',\n    };\n  }\n\n  const exporterConfig: OTLPExporterConfig = {\n    endpoint,\n    serviceName,\n    compression: false, // Avoid gzip dependency issues in MCP context\n    maxRetries: 2,\n    retryDelayMs: 500,\n  };\n\n  const exporter = new (OTLPExporter as any)(exporterConfig);\n  const result = await exporter.exportBatch(spans);\n\n  return {\n    success: result.success,\n    spanCount: result.spanCount,\n    retries: result.retries,\n    durationMs: result.durationMs,\n    error: result.error,\n  };\n}\n\nfunction handleGetAgentHealth() {\n  const collector = getTelemetryCollector();\n  const stats = collector.getStats();\n\n  let agents: Array<{ id: string; name: string; status: string }> = [];\n  let registrySize = 0;\n\n  try {\n    const registry = getDefaultRegistry();\n    const allAgents = registry.getAllManifests();\n    registrySize = allAgents.length;\n    agents = allAgents.map((a: any) => ({\n      id: a.id,\n      name: a.name,\n      status: a.status,\n    }));\n  } catch {\n    // Registry not initialized\n  }\n\n  const statusBreakdown: Record<string, number> = {};\n  for (const agent of agents) {\n    statusBreakdown[agent.status] = (statusBreakdown[agent.status] ?? 0) + 1;\n  }\n\n  return {\n    registrySize,\n    agents,\n    statusBreakdown,\n    telemetry: {\n      totalEvents: stats.totalEvents,\n      totalSpans: stats.totalSpans,\n      activeSpans: stats.activeSpans,\n      droppedEvents: stats.droppedEvents,\n      avgLatency: stats.avgLatency,\n      uptime: Date.now() - stats.startTime,\n    },\n  };\n}\n\nfunction handleGetMetricsPrometheus(args: Record<string, unknown>) {\n  const prefix = (args.prefix as string) ?? 'holoscript';\n  const registry = getPrometheusMetrics(prefix);\n  const text = registry.toPrometheusText();\n  const names = registry.getMetricNames();\n\n  return {\n    format: 'prometheus',\n    metricCount: names.length,\n    metricNames: names,\n    text,\n  };\n}\n\ntype ScaffoldAlertRule = {\n  name: string;\n  rule_type: string;\n  severity: 'info' | 'warning' | 'critical';\n  threshold: number;\n  rule_config: Record<string, unknown>;\n};\n\ntype ScaffoldHealthCheck = {\n  service: string;\n  check: string;\n  method?: string;\n};\n\nconst DEFAULT_REQUIRED_TABLES = [\n  'system_metrics',\n  'operation_metrics',\n  'alerts',\n  'alert_triggers',\n  'error_logs',\n];\nconst DEFAULT_NPC_COST_CEILING = 0.5;\nconst DEFAULT_HEADLESS_AGENT_COST_CEILING = 5;\nconst DEFAULT_ATTRIBUTION_FLOOR = 0.8;\nconst DEFAULT_RETENTION_DAYS = 90;\nconst SCAFFOLD_ALERT_RULE_TYPES = [\n  'error_rate',\n  'response_time',\n  'agent_count',\n  'memory_usage',\n  'cpu_usage',\n  'api_quota',\n  'data_retention',\n  'custom',\n];\n\nfunction handleHoloServiceScaffold(args: Record<string, unknown>) {\n  const composition = typeof args.composition === 'string' ? args.composition : '';\n  const parsed = parseServiceComposition(composition);\n  const serviceName = stringArg(args.serviceName) || parsed.serviceName || 'holoscript_service';\n  const requiredTables =\n    stringArrayArg(args.requiredTables) ?? parsed.requiredTables ?? DEFAULT_REQUIRED_TABLES;\n  const healthChecks =\n    objectArrayArg<ScaffoldHealthCheck>(args.healthChecks) ?? parsed.healthChecks ?? [];\n  const retentionDays = numberArg(args.retentionDays) ?? DEFAULT_RETENTION_DAYS;\n  const npcCostCeiling = numberArg(args.npcCostCeilingUsdPerDay) ?? DEFAULT_NPC_COST_CEILING;\n  const headlessAgentCostCeiling =\n    numberArg(args.headlessAgentCostCeilingUsdPerDay) ?? DEFAULT_HEADLESS_AGENT_COST_CEILING;\n  const attributionFloor = numberArg(args.attributionAccuracyFloor) ?? DEFAULT_ATTRIBUTION_FLOOR;\n  const alertRules = [\n    createApiQuotaSeed('npc_daily_cost_ceiling', 'npc', npcCostCeiling),\n    createApiQuotaSeed(\n      'headless_agent_daily_cost_ceiling',\n      'headless_agent',\n      headlessAgentCostCeiling\n    ),\n    createCreditFloorSeed('anthropic_credit_floor', 'anthropic'),\n    ...(objectArrayArg<ScaffoldAlertRule>(args.alertRules) ?? parsed.alertRules ?? []),\n  ];\n  const operationMetric = {\n    name: 'attribution_ci_accuracy',\n    minimum: attributionFloor,\n    fail_ci_below: attributionFloor,\n    metadata: { unit: 'ratio', ci_gate: true },\n  };\n  const cleanupJob = {\n    name: `operation_metrics_cleanup_${retentionDays}d`,\n    table: 'operation_metrics',\n    timestamp_column: 'created_at',\n    retention_days: retentionDays,\n    schedule: 'daily',\n    sql: `DELETE FROM operation_metrics WHERE created_at < NOW() - INTERVAL '${retentionDays} days';`,\n  };\n\n  return {\n    serviceName,\n    requiredTables,\n    healthChecks,\n    alertRules,\n    scheduledJobs: [cleanupJob],\n    operationMetrics: [operationMetric],\n    sql: renderServiceSql(requiredTables, alertRules, cleanupJob.sql),\n    startupHealthCheck: renderStartupHealthCheck(serviceName, requiredTables, healthChecks),\n    hsplusTraitSnippet: renderHsplusTrait(\n      serviceName,\n      requiredTables,\n      healthChecks,\n      alertRules,\n      cleanupJob,\n      operationMetric\n    ),\n  };\n}\n\nfunction parseServiceComposition(composition: string): {\n  serviceName?: string;\n  requiredTables?: string[];\n  healthChecks?: ScaffoldHealthCheck[];\n  alertRules?: ScaffoldAlertRule[];\n} {\n  if (!composition.trim()) return {};\n  return {\n    serviceName:\n      matchQuotedValue(composition, 'service_name') ??\n      matchQuotedValue(composition, 'serviceName') ??\n      matchServiceDeclaration(composition),\n    requiredTables:\n      matchStringArray(composition, 'required_tables') ??\n      matchStringArray(composition, 'requiredTables'),\n    healthChecks: matchHealthChecks(composition),\n    alertRules: matchAlertRules(composition),\n  };\n}\n\nfunction stringArg(value: unknown): string | undefined {\n  return typeof value === 'string' && value.trim() ? value.trim() : undefined;\n}\n\nfunction numberArg(value: unknown): number | undefined {\n  return typeof value === 'number' && Number.isFinite(value) ? value : undefined;\n}\n\nfunction stringArrayArg(value: unknown): string[] | undefined {\n  if (!Array.isArray(value)) return undefined;\n  const strings = value.filter((v): v is string => typeof v === 'string' && v.trim().length > 0);\n  return strings.length > 0 ? strings : undefined;\n}\n\nfunction objectArrayArg<T extends object>(value: unknown): T[] | undefined {\n  if (!Array.isArray(value)) return undefined;\n  const records = value.filter(\n    (v): v is T => Boolean(v) && typeof v === 'object' && !Array.isArray(v)\n  );\n  return records.length > 0 ? records : undefined;\n}\n\nfunction matchQuotedValue(source: string, key: string): string | undefined {\n  const match = new RegExp(`${key}\\\\s*[:=]\\\\s*['\"]([^'\"]+)['\"]`).exec(source);\n  return match?.[1];\n}\n\nfunction matchServiceDeclaration(source: string): string | undefined {\n  const match = /\\bservice\\s+([A-Za-z_][A-Za-z0-9_]*)/.exec(source);\n  return match?.[1];\n}\n\nfunction matchStringArray(source: string, key: string): string[] | undefined {\n  const match = new RegExp(`${key}\\\\s*[:=]\\\\s*\\\\[([^\\\\]]*)\\\\]`, 's').exec(source);\n  if (!match) return undefined;\n  const values = Array.from(match[1].matchAll(/['\"]([^'\"]+)['\"]/g)).map((m) => m[1]);\n  return values.length > 0 ? values : undefined;\n}\n\nfunction matchHealthChecks(source: string): ScaffoldHealthCheck[] | undefined {\n  const services =\n    matchStringArray(source, 'health_checks') ?? matchStringArray(source, 'health_probes');\n  if (!services) return undefined;\n  return services.map((service) => ({ service, check: 'health-check' }));\n}\n\nfunction matchAlertRules(source: string): ScaffoldAlertRule[] | undefined {\n  const names = matchStringArray(source, 'alert_rules');\n  if (!names) return undefined;\n  return names.map((name) => ({\n    name,\n    rule_type: name.includes('quota') || name.includes('cost') ? 'api_quota' : 'custom',\n    severity: name.includes('critical') || name.includes('cost') ? 'critical' : 'warning',\n    threshold: name.includes('headless')\n      ? DEFAULT_HEADLESS_AGENT_COST_CEILING\n      : DEFAULT_NPC_COST_CEILING,\n    rule_config: {},\n  }));\n}\n\nfunction createApiQuotaSeed(name: string, subject: string, ceiling: number): ScaffoldAlertRule {\n  return {\n    name,\n    rule_type: 'api_quota',\n    severity: 'critical',\n    threshold: ceiling,\n    rule_config: {\n      subject,\n      unit: 'usd_per_day',\n      ceiling_usd_per_day: ceiling,\n    },\n  };\n}\n\nfunction createCreditFloorSeed(name: string, provider: string): ScaffoldAlertRule {\n  return {\n    name,\n    rule_type: 'custom',\n    severity: 'critical',\n    threshold: 0,\n    rule_config: {\n      subject: provider,\n      check: 'credit_floor',\n      endpoint: '/api/health/llm',\n    },\n  };\n}\n\nfunction renderServiceSql(\n  requiredTables: string[],\n  alertRules: ScaffoldAlertRule[],\n  cleanupSql: string\n): string {\n  const tableSql = requiredTables.map(renderTableSql).join('\\n\\n');\n  const alertSql = alertRules.map(renderAlertSeedSql).join('\\n\\n');\n  return [tableSql, alertSql, '-- Scheduled metrics cleanup job', cleanupSql]\n    .filter(Boolean)\n    .join('\\n\\n');\n}\n\nfunction renderTableSql(table: string): string {\n  switch (table) {\n    case 'system_metrics':\n      return `CREATE TABLE IF NOT EXISTS system_metrics (\n  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),\n  timestamp TIMESTAMPTZ NOT NULL DEFAULT NOW(),\n  platform JSONB NOT NULL DEFAULT '{}',\n  performance JSONB NOT NULL DEFAULT '{}',\n  resources JSONB NOT NULL DEFAULT '{}',\n  created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()\n);`;\n    case 'operation_metrics':\n      return `CREATE TABLE IF NOT EXISTS operation_metrics (\n  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),\n  timestamp TIMESTAMPTZ NOT NULL DEFAULT NOW(),\n  operation VARCHAR(100) NOT NULL DEFAULT 'unknown',\n  duration INTEGER NOT NULL DEFAULT 0,\n  success BOOLEAN NOT NULL DEFAULT true,\n  error_message TEXT,\n  metadata JSONB DEFAULT '{}',\n  agent_id VARCHAR(255),\n  created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()\n);`;\n    case 'alerts':\n      return `CREATE TABLE IF NOT EXISTS alerts (\n  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),\n  name VARCHAR(255) NOT NULL,\n  severity VARCHAR(20) NOT NULL CHECK (severity IN ('info', 'warning', 'critical')),\n  rule_type VARCHAR(50) NOT NULL CHECK (rule_type IN (${renderSqlEnum(SCAFFOLD_ALERT_RULE_TYPES)})),\n  rule_config JSONB NOT NULL DEFAULT '{}',\n  enabled BOOLEAN NOT NULL DEFAULT true,\n  created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()\n);`;\n    case 'alert_triggers':\n      return `CREATE TABLE IF NOT EXISTS alert_triggers (\n  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),\n  alert_id UUID NOT NULL,\n  timestamp TIMESTAMPTZ NOT NULL DEFAULT NOW(),\n  value NUMERIC(12,4) NOT NULL,\n  threshold NUMERIC(12,4) NOT NULL,\n  details JSONB DEFAULT '{}',\n  acknowledged BOOLEAN NOT NULL DEFAULT false,\n  created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()\n);`;\n    case 'error_logs':\n      return `CREATE TABLE IF NOT EXISTS error_logs (\n  id SERIAL PRIMARY KEY,\n  timestamp TIMESTAMPTZ NOT NULL DEFAULT NOW(),\n  level VARCHAR(20) NOT NULL DEFAULT 'error',\n  source VARCHAR(100),\n  message TEXT NOT NULL,\n  stack TEXT,\n  context JSONB,\n  resolved BOOLEAN DEFAULT FALSE,\n  agent_id VARCHAR(100)\n);`;\n    default:\n      return `CREATE TABLE IF NOT EXISTS ${sanitizeIdentifier(table)} (\n  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),\n  created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),\n  metadata JSONB NOT NULL DEFAULT '{}'\n);`;\n  }\n}\n\nfunction renderAlertSeedSql(rule: ScaffoldAlertRule): string {\n  const config = JSON.stringify(rule.rule_config ?? {}).replace(/'/g, \"''\");\n  return `INSERT INTO alerts (name, severity, rule_type, rule_config, enabled)\nSELECT '${escapeSql(rule.name)}', '${escapeSql(rule.severity)}', '${escapeSql(rule.rule_type)}', '${config}'::jsonb, true\nWHERE NOT EXISTS (SELECT 1 FROM alerts WHERE name = '${escapeSql(rule.name)}');`;\n}\n\nfunction renderStartupHealthCheck(\n  serviceName: string,\n  requiredTables: string[],\n  healthChecks: ScaffoldHealthCheck[]\n): string {\n  const tableList = requiredTables.map((t) => `'${escapeTs(t)}'`).join(', ');\n  const checks = JSON.stringify(healthChecks, null, 2);\n  return `export class StartupHealthCheck {\n  static readonly SERVICE_NAME = '${escapeTs(serviceName)}';\n  static readonly REQUIRED_TABLES = [${tableList}];\n  static readonly HEALTH_CHECKS = ${checks};\n\n  static async validateSchema(supabase) {\n    const missing = [];\n    for (const table of this.REQUIRED_TABLES) {\n      const { error } = await supabase.from(table).select('id', { count: 'exact', head: true });\n      if (error) missing.push(table);\n    }\n    return { ok: missing.length === 0, missing };\n  }\n}`;\n}\n\nfunction renderHsplusTrait(\n  serviceName: string,\n  requiredTables: string[],\n  healthChecks: ScaffoldHealthCheck[],\n  alertRules: ScaffoldAlertRule[],\n  cleanupJob: Record<string, unknown>,\n  operationMetric: Record<string, unknown>\n): string {\n  return `@serviceObservability({\n  service_name: '${escapeTs(serviceName)}',\n  required_tables: ${JSON.stringify(requiredTables)},\n  health_probes: ${JSON.stringify(healthChecks)},\n  alert_rules: ${JSON.stringify(alertRules)},\n  scheduled_jobs: ${JSON.stringify([cleanupJob])},\n  operation_metrics: ${JSON.stringify([operationMetric])}\n})`;\n}\n\nfunction sanitizeIdentifier(value: string): string {\n  const sanitized = value.replace(/[^A-Za-z0-9_]/g, '_');\n  return /^[A-Za-z_]/.test(sanitized) ? sanitized : `t_${sanitized}`;\n}\n\nfunction escapeSql(value: string): string {\n  return value.replace(/'/g, \"''\");\n}\n\nfunction renderSqlEnum(values: string[]): string {\n  return values.map((value) => `'${escapeSql(value)}'`).join(', ');\n}\n\nfunction escapeTs(value: string): string {\n  return value.replace(/\\\\/g, '\\\\\\\\').replace(/'/g, \"\\\\'\");\n}\n","/**\n * @holoscript/energy-grid-plugin\n *\n * First deep slice for energy-grid simulation: typed topology, deterministic\n * DC power-flow solving, solar and battery primitives, QUBO hooks for DER\n * dispatch, and CAEL-ready receipt summaries.\n */\n\nimport type { FieldData, SimSolver, SolverMode } from '@holoscript/engine/simulation';\nimport {\n  DOMAIN_SIMULATION_RECEIPT_SCHEMA,\n  buildDomainSimulationReceipt,\n  type DomainSimulationReceipt,\n} from '@holoscript/core';\n\nexport const ENERGY_GRID_PLUGIN_ID = 'energy-grid' as const;\nexport const ENERGY_GRID_RECEIPT_SCHEMA = DOMAIN_SIMULATION_RECEIPT_SCHEMA;\n\nexport const ENERGY_GRID_OBJECT_TYPES = [\n  'grid_bus',\n  'grid_line',\n  'solar_asset',\n  'battery_asset',\n  'der_dispatch_plan',\n] as const;\nexport type EnergyGridObjectType = (typeof ENERGY_GRID_OBJECT_TYPES)[number];\n\nexport const ENERGY_GRID_TRAITS = [\n  'power_flow',\n  'solar_irradiance',\n  'battery_degradation',\n  'der_qubo',\n  'grid_topology',\n] as const;\nexport type EnergyGridTraitName = (typeof ENERGY_GRID_TRAITS)[number];\n\nexport interface EnergyGridPluginDescriptor {\n  id: typeof ENERGY_GRID_PLUGIN_ID;\n  version: string;\n  objectTypes: readonly EnergyGridObjectType[];\n  traits: readonly EnergyGridTraitName[];\n  solverTypes: readonly ['dc-power-flow'];\n  receiptSchema: typeof ENERGY_GRID_RECEIPT_SCHEMA;\n}\n\nexport const PLUGIN_DESCRIPTOR: EnergyGridPluginDescriptor = {\n  id: ENERGY_GRID_PLUGIN_ID,\n  version: '0.1.0',\n  objectTypes: ENERGY_GRID_OBJECT_TYPES,\n  traits: ENERGY_GRID_TRAITS,\n  solverTypes: ['dc-power-flow'],\n  receiptSchema: ENERGY_GRID_RECEIPT_SCHEMA,\n};\n\nexport interface PluginHostRegistry {\n  registerObjectType(name: string, descriptor: { plugin: string }): void;\n  registerTrait(name: string, descriptor: { plugin: string }): void;\n}\n\nexport function register(host: PluginHostRegistry): EnergyGridPluginDescriptor {\n  for (const name of ENERGY_GRID_OBJECT_TYPES) {\n    host.registerObjectType(name, { plugin: PLUGIN_DESCRIPTOR.id });\n  }\n  for (const name of ENERGY_GRID_TRAITS) {\n    host.registerTrait(name, { plugin: PLUGIN_DESCRIPTOR.id });\n  }\n  return PLUGIN_DESCRIPTOR;\n}\n\nexport type BusKind = 'slack' | 'load' | 'generator' | 'storage' | 'interconnect';\nexport type LineStatus = 'closed' | 'open';\n\nexport interface EnergyBus {\n  id: string;\n  kind: BusKind;\n  nominalKv: number;\n  demandMw?: number;\n  generationMw?: number;\n  batteryDispatchMw?: number;\n  zone?: string;\n}\n\nexport interface EnergyLine {\n  id: string;\n  fromBusId: string;\n  toBusId: string;\n  reactancePu: number;\n  capacityMw: number;\n  resistancePu?: number;\n  status?: LineStatus;\n}\n\nexport interface SolarAsset {\n  id: string;\n  busId: string;\n  areaM2: number;\n  moduleEfficiency: number;\n  derate?: number;\n  inverterLimitMw?: number;\n}\n\nexport interface BatteryAsset {\n  id: string;\n  busId: string;\n  capacityMwh: number;\n  stateOfChargeMwh: number;\n  maxChargeMw: number;\n  maxDischargeMw: number;\n  cycleCount?: number;\n  temperatureC?: number;\n}\n\nexport interface EnergyGridModel {\n  id: string;\n  baseMva: number;\n  buses: EnergyBus[];\n  lines: EnergyLine[];\n  solarAssets?: SolarAsset[];\n  batteries?: BatteryAsset[];\n}\n\nexport interface SolarIrradianceSample {\n  globalHorizontalIrradianceWm2: number;\n  cloudCoverFraction?: number;\n  ambientTemperatureC?: number;\n}\n\nexport interface SolarOutputEstimate {\n  assetId: string;\n  busId: string;\n  rawMw: number;\n  deliveredMw: number;\n  clippedMw: number;\n  derate: number;\n}\n\nexport interface BatteryDegradationInput {\n  battery: BatteryAsset;\n  throughputMwh: number;\n  averageStateOfChargeFraction?: number;\n  ambientTemperatureC?: number;\n}\n\nexport interface BatteryDegradationEstimate {\n  batteryId: string;\n  equivalentFullCycles: number;\n  cycleFadePercent: number;\n  temperatureFactor: number;\n  cRateFactor: number;\n  projectedCycleCount: number;\n}\n\nexport interface DCPowerFlowResult {\n  solverType: 'dc-power-flow';\n  converged: boolean;\n  slackBusId: string;\n  busVoltageAnglesRad: Record<string, number>;\n  busNetInjectionMw: Record<string, number>;\n  lineFlowsMw: Record<string, number>;\n  lineLoadingRatio: Record<string, number>;\n  overloadedLineIds: string[];\n  estimatedLossMw: number;\n}\n\nexport interface DerDispatchQuboVariable {\n  name: string;\n  assetId: string;\n  busId: string;\n  dischargeMw: number;\n}\n\nexport interface DerDispatchQubo {\n  objective: 'minimize_squared_dispatch_gap';\n  targetMw: number;\n  variables: DerDispatchQuboVariable[];\n  linear: Record<string, number>;\n  quadratic: Record<string, number>;\n  constant: number;\n  qaoaEligible: true;\n}\n\nexport interface EnergyGridReceipt {\n  schema: DomainSimulationReceipt['schema'];\n  plugin: DomainSimulationReceipt['plugin'];\n  pluginVersion: DomainSimulationReceipt['pluginVersion'];\n  runId: DomainSimulationReceipt['runId'];\n  createdAt: DomainSimulationReceipt['createdAt'];\n  modelId: NonNullable<DomainSimulationReceipt['modelId']>;\n  solverConfig: {\n    solverType: 'dc-power-flow';\n    baseMva: number;\n    busCount: number;\n    lineCount: number;\n    slackBusId: string;\n    scale: 'grid';\n  };\n  resultSummary: {\n    converged: boolean;\n    maxLineLoadingRatio: number;\n    overloadedLineIds: string[];\n    estimatedLossMw: number;\n    totalDemandMw: number;\n    totalGenerationMw: number;\n  };\n  cael: {\n    version: 'cael.v1';\n    event: 'energy_grid.power_flow';\n    solverType: 'energy-grid.dc-power-flow';\n  };\n  acceptance: DomainSimulationReceipt['acceptance'];\n  payloadHash: DomainSimulationReceipt['payloadHash'];\n  hashAlgorithm: DomainSimulationReceipt['hashAlgorithm'];\n}\n\nexport interface EnergyGridReceiptOptions {\n  runId?: string;\n  createdAt?: string;\n}\n\nexport interface EnergyGridValidation {\n  valid: boolean;\n  errors: string[];\n  warnings: string[];\n  connectedComponents: string[][];\n}\n\nexport interface DCPowerFlowSolveOptions {\n  overloadToleranceRatio?: number;\n}\n\nexport class EnergyGridDCSolver implements SimSolver {\n  readonly mode: SolverMode = 'steady-state';\n  readonly fieldNames = [\n    'bus_voltage_angle_rad',\n    'bus_net_injection_mw',\n    'line_flow_mw',\n    'line_loading_ratio',\n  ] as const;\n\n  private result: DCPowerFlowResult | null = null;\n  private readonly orderedBusIds: string[];\n  private readonly orderedLineIds: string[];\n\n  constructor(private readonly model: EnergyGridModel) {\n    this.orderedBusIds = model.buses.map((bus) => bus.id);\n    this.orderedLineIds = model.lines.map((line) => line.id);\n  }\n\n  step(): void {}\n\n  solve(): void {\n    this.result = solveDCPowerFlow(this.model);\n  }\n\n  getField(name: string): FieldData | null {\n    const result = this.result ?? solveDCPowerFlow(this.model);\n    this.result = result;\n\n    if (name === 'bus_voltage_angle_rad') {\n      return new Float64Array(this.orderedBusIds.map((id) => result.busVoltageAnglesRad[id] ?? 0));\n    }\n    if (name === 'bus_net_injection_mw') {\n      return new Float64Array(this.orderedBusIds.map((id) => result.busNetInjectionMw[id] ?? 0));\n    }\n    if (name === 'line_flow_mw') {\n      return new Float64Array(this.orderedLineIds.map((id) => result.lineFlowsMw[id] ?? 0));\n    }\n    if (name === 'line_loading_ratio') {\n      return new Float64Array(this.orderedLineIds.map((id) => result.lineLoadingRatio[id] ?? 0));\n    }\n    return null;\n  }\n\n  getStats(): Record<string, unknown> {\n    const result = this.result ?? solveDCPowerFlow(this.model);\n    this.result = result;\n    return {\n      solverType: result.solverType,\n      converged: result.converged,\n      busCount: this.model.buses.length,\n      lineCount: this.model.lines.length,\n      slackBusId: result.slackBusId,\n      totalDemandMw: totalDemandMw(this.model),\n      totalGenerationMw: totalGenerationMw(this.model),\n      maxLineLoadingRatio: maxLineLoadingRatio(result),\n      overloadCount: result.overloadedLineIds.length,\n      estimatedLossMw: result.estimatedLossMw,\n    };\n  }\n\n  dispose(): void {\n    this.result = null;\n  }\n}\n\nexport function createEnergyGridDCSolver(model: EnergyGridModel): EnergyGridDCSolver {\n  return new EnergyGridDCSolver(model);\n}\n\nexport function validateEnergyGridModel(model: EnergyGridModel): EnergyGridValidation {\n  const errors: string[] = [];\n  const warnings: string[] = [];\n\n  if (!Number.isFinite(model.baseMva) || model.baseMva <= 0) {\n    errors.push('baseMva must be a positive finite number');\n  }\n\n  const busIds = new Set<string>();\n  for (const bus of model.buses) {\n    if (busIds.has(bus.id)) {\n      errors.push(`duplicate bus id: ${bus.id}`);\n    }\n    busIds.add(bus.id);\n    if (!Number.isFinite(bus.nominalKv) || bus.nominalKv <= 0) {\n      errors.push(`bus ${bus.id} nominalKv must be positive`);\n    }\n  }\n\n  const slackBuses = model.buses.filter((bus) => bus.kind === 'slack');\n  if (slackBuses.length !== 1) {\n    errors.push(`expected exactly one slack bus, found ${slackBuses.length}`);\n  }\n\n  const lineIds = new Set<string>();\n  for (const line of model.lines) {\n    if (lineIds.has(line.id)) {\n      errors.push(`duplicate line id: ${line.id}`);\n    }\n    lineIds.add(line.id);\n    if (!busIds.has(line.fromBusId)) {\n      errors.push(`line ${line.id} references missing fromBusId ${line.fromBusId}`);\n    }\n    if (!busIds.has(line.toBusId)) {\n      errors.push(`line ${line.id} references missing toBusId ${line.toBusId}`);\n    }\n    if (!Number.isFinite(line.reactancePu) || line.reactancePu <= 0) {\n      errors.push(`line ${line.id} reactancePu must be positive`);\n    }\n    if (!Number.isFinite(line.capacityMw) || line.capacityMw <= 0) {\n      errors.push(`line ${line.id} capacityMw must be positive`);\n    }\n    if (\n      line.resistancePu !== undefined &&\n      (!Number.isFinite(line.resistancePu) || line.resistancePu < 0)\n    ) {\n      errors.push(`line ${line.id} resistancePu must be non-negative when provided`);\n    }\n  }\n\n  for (const solar of model.solarAssets ?? []) {\n    if (!busIds.has(solar.busId)) {\n      errors.push(`solar asset ${solar.id} references missing bus ${solar.busId}`);\n    }\n    if (!Number.isFinite(solar.areaM2) || solar.areaM2 <= 0) {\n      errors.push(`solar asset ${solar.id} areaM2 must be positive`);\n    }\n    if (\n      !Number.isFinite(solar.moduleEfficiency) ||\n      solar.moduleEfficiency <= 0 ||\n      solar.moduleEfficiency > 1\n    ) {\n      errors.push(`solar asset ${solar.id} moduleEfficiency must be in (0, 1]`);\n    }\n  }\n\n  for (const battery of model.batteries ?? []) {\n    if (!busIds.has(battery.busId)) {\n      errors.push(`battery ${battery.id} references missing bus ${battery.busId}`);\n    }\n    if (!Number.isFinite(battery.capacityMwh) || battery.capacityMwh <= 0) {\n      errors.push(`battery ${battery.id} capacityMwh must be positive`);\n    }\n    if (battery.stateOfChargeMwh < 0 || battery.stateOfChargeMwh > battery.capacityMwh) {\n      errors.push(`battery ${battery.id} stateOfChargeMwh must be within capacity`);\n    }\n  }\n\n  const components = connectedComponents(model);\n  if (components.length > 1) {\n    warnings.push(`grid topology has ${components.length} connected islands`);\n  }\n\n  return {\n    valid: errors.length === 0,\n    errors,\n    warnings,\n    connectedComponents: components,\n  };\n}\n\nexport function connectedComponents(model: EnergyGridModel): string[][] {\n  const adjacency = new Map<string, Set<string>>();\n  for (const bus of model.buses) {\n    adjacency.set(bus.id, new Set<string>());\n  }\n\n  for (const line of activeLines(model)) {\n    adjacency.get(line.fromBusId)?.add(line.toBusId);\n    adjacency.get(line.toBusId)?.add(line.fromBusId);\n  }\n\n  const seen = new Set<string>();\n  const components: string[][] = [];\n  for (const bus of model.buses) {\n    if (seen.has(bus.id)) continue;\n    const queue = [bus.id];\n    const component: string[] = [];\n    seen.add(bus.id);\n    while (queue.length > 0) {\n      const next = queue.shift();\n      if (next === undefined) continue;\n      component.push(next);\n      for (const neighbor of adjacency.get(next) ?? []) {\n        if (!seen.has(neighbor)) {\n          seen.add(neighbor);\n          queue.push(neighbor);\n        }\n      }\n    }\n    components.push(component);\n  }\n  return components;\n}\n\nexport function solveDCPowerFlow(\n  model: EnergyGridModel,\n  options: DCPowerFlowSolveOptions = {}\n): DCPowerFlowResult {\n  const validation = validateEnergyGridModel(model);\n  if (!validation.valid) {\n    throw new Error(`[energy-grid] invalid model: ${validation.errors.join('; ')}`);\n  }\n  if (validation.connectedComponents.length !== 1) {\n    throw new Error(\n      '[energy-grid] DC power flow requires one connected island for this first solver slice'\n    );\n  }\n\n  const slackBus = model.buses.find((bus) => bus.kind === 'slack');\n  if (slackBus === undefined) {\n    throw new Error('[energy-grid] slack bus missing after validation');\n  }\n\n  const busIndex = new Map<string, number>();\n  model.buses.forEach((bus, index) => busIndex.set(bus.id, index));\n  const slackIndex = indexOfRequiredBus(busIndex, slackBus.id);\n  const susceptance = buildSusceptanceMatrix(model, busIndex);\n  const injectionsPu = model.buses.map((bus) => netInjectionMw(bus) / model.baseMva);\n\n  const reducedMatrix: number[][] = [];\n  const reducedRhs: number[] = [];\n  for (let row = 0; row < model.buses.length; row++) {\n    if (row === slackIndex) continue;\n    const reducedRow: number[] = [];\n    for (let col = 0; col < model.buses.length; col++) {\n      if (col === slackIndex) continue;\n      reducedRow.push(susceptance[row][col]);\n    }\n    reducedMatrix.push(reducedRow);\n    reducedRhs.push(injectionsPu[row]);\n  }\n\n  const solvedAngles = solveLinearSystem(reducedMatrix, reducedRhs);\n  const angles = new Array<number>(model.buses.length).fill(0);\n  let cursor = 0;\n  for (let index = 0; index < angles.length; index++) {\n    if (index === slackIndex) continue;\n    angles[index] = solvedAngles[cursor] ?? 0;\n    cursor += 1;\n  }\n\n  const busVoltageAnglesRad: Record<string, number> = {};\n  const busNetInjectionMw: Record<string, number> = {};\n  for (let index = 0; index < model.buses.length; index++) {\n    const bus = model.buses[index];\n    busVoltageAnglesRad[bus.id] = angles[index];\n    busNetInjectionMw[bus.id] = netInjectionMw(bus);\n  }\n\n  const lineFlowsMw: Record<string, number> = {};\n  const lineLoadingRatio: Record<string, number> = {};\n  const overloadedLineIds: string[] = [];\n  let estimatedLossMw = 0;\n  const overloadToleranceRatio = options.overloadToleranceRatio ?? 1;\n\n  for (const line of model.lines) {\n    if (line.status === 'open') {\n      lineFlowsMw[line.id] = 0;\n      lineLoadingRatio[line.id] = 0;\n      continue;\n    }\n    const fromIndex = indexOfRequiredBus(busIndex, line.fromBusId);\n    const toIndex = indexOfRequiredBus(busIndex, line.toBusId);\n    const flowMw = ((angles[fromIndex] - angles[toIndex]) / line.reactancePu) * model.baseMva;\n    const loading = Math.abs(flowMw) / line.capacityMw;\n    lineFlowsMw[line.id] = flowMw;\n    lineLoadingRatio[line.id] = loading;\n    if (loading > overloadToleranceRatio) {\n      overloadedLineIds.push(line.id);\n    }\n    if (line.resistancePu !== undefined) {\n      const currentPu = flowMw / model.baseMva;\n      estimatedLossMw += currentPu * currentPu * line.resistancePu * model.baseMva;\n    }\n  }\n\n  return {\n    solverType: 'dc-power-flow',\n    converged: true,\n    slackBusId: slackBus.id,\n    busVoltageAnglesRad,\n    busNetInjectionMw,\n    lineFlowsMw,\n    lineLoadingRatio,\n    overloadedLineIds,\n    estimatedLossMw,\n  };\n}\n\nexport function estimateSolarOutput(\n  asset: SolarAsset,\n  sample: SolarIrradianceSample\n): SolarOutputEstimate {\n  const cloudFactor = 1 - clamp(sample.cloudCoverFraction ?? 0, 0, 1) * 0.75;\n  const temperatureC = sample.ambientTemperatureC ?? 25;\n  const temperatureDerate = 1 - Math.max(0, temperatureC - 25) * 0.004;\n  const derate = clamp((asset.derate ?? 0.86) * cloudFactor * temperatureDerate, 0, 1);\n  const rawMw =\n    (sample.globalHorizontalIrradianceWm2 * asset.areaM2 * asset.moduleEfficiency) / 1_000_000;\n  const deliveredBeforeClip = rawMw * derate;\n  const deliveredMw = Math.min(deliveredBeforeClip, asset.inverterLimitMw ?? deliveredBeforeClip);\n  return {\n    assetId: asset.id,\n    busId: asset.busId,\n    rawMw,\n    deliveredMw,\n    clippedMw: Math.max(0, deliveredBeforeClip - deliveredMw),\n    derate,\n  };\n}\n\nexport function estimateBatteryDegradation(\n  input: BatteryDegradationInput\n): BatteryDegradationEstimate {\n  const { battery } = input;\n  const equivalentFullCycles = input.throughputMwh / (2 * battery.capacityMwh);\n  const soc = clamp(\n    input.averageStateOfChargeFraction ?? battery.stateOfChargeMwh / battery.capacityMwh,\n    0,\n    1\n  );\n  const temperatureC = input.ambientTemperatureC ?? battery.temperatureC ?? 25;\n  const temperatureFactor = 1 + Math.max(0, temperatureC - 25) * 0.035;\n  const cRate = Math.max(battery.maxChargeMw, battery.maxDischargeMw) / battery.capacityMwh;\n  const cRateFactor = 1 + Math.max(0, cRate - 0.5) * 0.3;\n  const socStress = 1 + Math.abs(soc - 0.5) * 0.4;\n  const baseCycleFadePercent = 0.018;\n  const cycleFadePercent =\n    equivalentFullCycles * baseCycleFadePercent * temperatureFactor * cRateFactor * socStress;\n\n  return {\n    batteryId: battery.id,\n    equivalentFullCycles,\n    cycleFadePercent,\n    temperatureFactor,\n    cRateFactor,\n    projectedCycleCount: (battery.cycleCount ?? 0) + equivalentFullCycles,\n  };\n}\n\nexport function buildDerDispatchQubo(model: EnergyGridModel, targetMw: number): DerDispatchQubo {\n  if (!Number.isFinite(targetMw) || targetMw < 0) {\n    throw new Error('[energy-grid] targetMw must be a non-negative finite number');\n  }\n\n  const variables: DerDispatchQuboVariable[] = (model.batteries ?? []).map((battery) => ({\n    name: `x_${sanitizeQuboName(battery.id)}`,\n    assetId: battery.id,\n    busId: battery.busId,\n    dischargeMw: Math.min(battery.maxDischargeMw, battery.stateOfChargeMwh),\n  }));\n\n  const linear: Record<string, number> = {};\n  const quadratic: Record<string, number> = {};\n\n  for (let i = 0; i < variables.length; i++) {\n    const vi = variables[i];\n    linear[vi.name] = vi.dischargeMw * vi.dischargeMw - 2 * targetMw * vi.dischargeMw;\n    for (let j = i + 1; j < variables.length; j++) {\n      const vj = variables[j];\n      quadratic[quboPairKey(vi.name, vj.name)] = 2 * vi.dischargeMw * vj.dischargeMw;\n    }\n  }\n\n  return {\n    objective: 'minimize_squared_dispatch_gap',\n    targetMw,\n    variables,\n    linear,\n    quadratic,\n    constant: targetMw * targetMw,\n    qaoaEligible: true,\n  };\n}\n\nexport function buildEnergyGridReceipt(\n  model: EnergyGridModel,\n  result: DCPowerFlowResult,\n  options: string | EnergyGridReceiptOptions = {}\n): EnergyGridReceipt {\n  const normalizedOptions = typeof options === 'string' ? { runId: options } : options;\n  const acceptance = verifyPowerFlowAcceptance(model, result);\n  const receipt = buildDomainSimulationReceipt({\n    plugin: ENERGY_GRID_PLUGIN_ID,\n    pluginVersion: PLUGIN_DESCRIPTOR.version,\n    runId: normalizedOptions.runId ?? `energy-grid-${Date.now().toString(36)}`,\n    createdAt: normalizedOptions.createdAt,\n    modelId: model.id,\n    solverConfig: {\n      solverType: 'dc-power-flow',\n      baseMva: model.baseMva,\n      busCount: model.buses.length,\n      lineCount: model.lines.length,\n      slackBusId: result.slackBusId,\n      scale: 'grid',\n    },\n    resultSummary: {\n      converged: result.converged,\n      maxLineLoadingRatio: maxLineLoadingRatio(result),\n      overloadedLineIds: [...result.overloadedLineIds],\n      estimatedLossMw: result.estimatedLossMw,\n      totalDemandMw: totalDemandMw(model),\n      totalGenerationMw: totalGenerationMw(model),\n    },\n    cael: {\n      version: 'cael.v1',\n      event: 'energy_grid.power_flow',\n      solverType: 'energy-grid.dc-power-flow',\n    },\n    acceptance,\n  });\n\n  return receipt as EnergyGridReceipt;\n}\n\nexport function verifyPowerFlowAcceptance(\n  model: EnergyGridModel,\n  result: DCPowerFlowResult\n): EnergyGridReceipt['acceptance'] {\n  const violations: Array<{ criterion: string; message: string }> = [];\n\n  if (!result.converged) {\n    violations.push({ criterion: 'convergence', message: 'DC power flow did not converge' });\n  }\n\n  const netInjection = Object.values(result.busNetInjectionMw).reduce(\n    (sum, value) => sum + value,\n    0\n  );\n  if (Math.abs(netInjection) > Math.max(1e-6, model.baseMva * 1e-9)) {\n    violations.push({\n      criterion: 'power_balance',\n      message: `net injection ${netInjection.toFixed(9)} MW is not balanced`,\n    });\n  }\n\n  if (result.overloadedLineIds.length > 0) {\n    violations.push({\n      criterion: 'line_capacity',\n      message: `overloaded lines: ${result.overloadedLineIds.join(', ')}`,\n    });\n  }\n\n  return { accepted: violations.length === 0, violations };\n}\n\nexport const pluginMeta = {\n  name: '@holoscript/energy-grid-plugin',\n  version: PLUGIN_DESCRIPTOR.version,\n  traits: ENERGY_GRID_TRAITS,\n  objectTypes: ENERGY_GRID_OBJECT_TYPES,\n};\n\n// Runtime integration — behavioral trait handlers + registrar that wire the\n// DC power-flow solver into HoloScriptRuntime's dispatch. Closes the\n// built-but-dead-wired gap for `power_flow` (task_1780878631657_j63f PATH-2).\nexport {\n  powerFlowHandler,\n  registerEnergyGridTraitHandlers,\n  type PowerFlowTraitConfig,\n  type PowerFlowSolvedEvent,\n  type RuntimeTraitHandler,\n  type TraitRegistrar,\n} from './runtime';\n\nfunction activeLines(model: EnergyGridModel): EnergyLine[] {\n  return model.lines.filter((line) => line.status !== 'open');\n}\n\nfunction buildSusceptanceMatrix(model: EnergyGridModel, busIndex: Map<string, number>): number[][] {\n  const n = model.buses.length;\n  const matrix = Array.from({ length: n }, () => new Array<number>(n).fill(0));\n  for (const line of activeLines(model)) {\n    const from = indexOfRequiredBus(busIndex, line.fromBusId);\n    const to = indexOfRequiredBus(busIndex, line.toBusId);\n    const b = 1 / line.reactancePu;\n    matrix[from][from] += b;\n    matrix[to][to] += b;\n    matrix[from][to] -= b;\n    matrix[to][from] -= b;\n  }\n  return matrix;\n}\n\nfunction solveLinearSystem(matrix: number[][], rhs: number[]): number[] {\n  const n = rhs.length;\n  if (n === 0) return [];\n  const a = matrix.map((row, rowIndex) => {\n    if (row.length !== n) {\n      throw new Error(\n        `[energy-grid] reduced matrix row ${rowIndex} has length ${row.length}, expected ${n}`\n      );\n    }\n    return [...row];\n  });\n  const b = [...rhs];\n\n  for (let pivot = 0; pivot < n; pivot++) {\n    let bestRow = pivot;\n    let bestAbs = Math.abs(a[pivot][pivot]);\n    for (let row = pivot + 1; row < n; row++) {\n      const value = Math.abs(a[row][pivot]);\n      if (value > bestAbs) {\n        bestAbs = value;\n        bestRow = row;\n      }\n    }\n    if (bestAbs < 1e-12) {\n      throw new Error('[energy-grid] singular admittance matrix; check topology and slack bus');\n    }\n    if (bestRow !== pivot) {\n      [a[pivot], a[bestRow]] = [a[bestRow], a[pivot]];\n      [b[pivot], b[bestRow]] = [b[bestRow], b[pivot]];\n    }\n\n    const pivotValue = a[pivot][pivot];\n    for (let col = pivot; col < n; col++) {\n      a[pivot][col] /= pivotValue;\n    }\n    b[pivot] /= pivotValue;\n\n    for (let row = 0; row < n; row++) {\n      if (row === pivot) continue;\n      const factor = a[row][pivot];\n      if (factor === 0) continue;\n      for (let col = pivot; col < n; col++) {\n        a[row][col] -= factor * a[pivot][col];\n      }\n      b[row] -= factor * b[pivot];\n    }\n  }\n\n  return b;\n}\n\nfunction indexOfRequiredBus(busIndex: Map<string, number>, busId: string): number {\n  const index = busIndex.get(busId);\n  if (index === undefined) {\n    throw new Error(`[energy-grid] missing bus id: ${busId}`);\n  }\n  return index;\n}\n\nfunction netInjectionMw(bus: EnergyBus): number {\n  return (bus.generationMw ?? 0) + (bus.batteryDispatchMw ?? 0) - (bus.demandMw ?? 0);\n}\n\nfunction totalDemandMw(model: EnergyGridModel): number {\n  return model.buses.reduce((sum, bus) => sum + (bus.demandMw ?? 0), 0);\n}\n\nfunction totalGenerationMw(model: EnergyGridModel): number {\n  return model.buses.reduce(\n    (sum, bus) => sum + (bus.generationMw ?? 0) + (bus.batteryDispatchMw ?? 0),\n    0\n  );\n}\n\nfunction maxLineLoadingRatio(result: DCPowerFlowResult): number {\n  return Math.max(0, ...Object.values(result.lineLoadingRatio));\n}\n\nfunction clamp(value: number, min: number, max: number): number {\n  return Math.min(max, Math.max(min, value));\n}\n\nfunction sanitizeQuboName(value: string): string {\n  return value.replace(/[^a-zA-Z0-9_]/g, '_');\n}\n\nfunction quboPairKey(left: string, right: string): string {\n  return left < right ? `${left}:${right}` : `${right}:${left}`;\n}\n","/**\n * Runtime integration for @holoscript/energy-grid-plugin.\n *\n * Bridges the previously dead-wired `power_flow` trait into a behavioral\n * TraitHandler that the HoloScript runtime actually dispatches\n * (HoloScriptRuntime.registerTrait -> applyDirectives / updateTraits).\n *\n * Before this module the plugin declared trait NAMES only\n * (ENERGY_GRID_TRAITS) and exported `solveDCPowerFlow`, but nothing invoked\n * the solver THROUGH the runtime — the whole domain-plugin tier was\n * built-but-dead-wired (deep-ratchet 2026-06-07, task_1780878631657_j63f).\n * This is PATH step 2: the reference integration proving the tier can be\n * consumed. The remaining ENERGY_GRID_TRAITS and the rest of the tier follow\n * the same registrar shape once the architecture clears /premortem (PATH 3).\n */\nimport { registerPluginTraits } from '@holoscript/core/runtime';\nimport {\n  ENERGY_GRID_PLUGIN_ID,\n  solveDCPowerFlow,\n  type DCPowerFlowResult,\n  type EnergyGridModel,\n} from './index';\n\n/** Config carried by an orb's `@power_flow` trait directive. */\nexport interface PowerFlowTraitConfig {\n  /** The grid to solve. Required; absence emits `power_flow_error`. */\n  model?: EnergyGridModel;\n  /** Optional overload tolerance forwarded to `solveDCPowerFlow`. */\n  overloadToleranceRatio?: number;\n}\n\n/** Summary payload emitted on `power_flow_solved`. */\nexport interface PowerFlowSolvedEvent {\n  nodeId: string;\n  converged: boolean;\n  slackBusId: string;\n  lineFlowsMw: Record<string, number>;\n  lineLoadingRatio: Record<string, number>;\n  overloadedLineIds: string[];\n  estimatedLossMw: number;\n}\n\n/**\n * Structural view of the runtime trait-handler contract. Matches\n * `@holoscript/core` TraitTypes.TraitHandler at the call sites the runtime\n * actually uses (onAttach / onUpdate receive the node, the directive config,\n * and a context exposing `emit`). Declared locally so the plugin stays\n * decoupled from core's full trait surface.\n */\nexport interface TraitDispatchContext {\n  emit: (event: string, payload?: unknown) => void;\n  setState?: (updates: Record<string, unknown>) => void;\n}\n\nexport interface RuntimeTraitHandler {\n  name: string;\n  onAttach?: (node: unknown, config: PowerFlowTraitConfig, context: TraitDispatchContext) => void;\n  onUpdate?: (\n    node: unknown,\n    config: PowerFlowTraitConfig,\n    context: TraitDispatchContext,\n    delta: number\n  ) => void;\n}\n\ninterface PowerFlowNode {\n  id?: string;\n  name?: string;\n  properties?: Record<string, unknown>;\n  __powerFlowResult?: DCPowerFlowResult;\n}\n\n/** Solve the grid in `config.model`, write the result onto the node, and emit. */\nfunction solveOntoNode(\n  node: unknown,\n  config: PowerFlowTraitConfig | undefined,\n  context: TraitDispatchContext\n): void {\n  const carrier = node as PowerFlowNode;\n  const nodeId = carrier.id ?? carrier.name ?? 'unknown';\n  const model = config?.model;\n\n  if (!model) {\n    context.emit('power_flow_error', {\n      nodeId,\n      error: 'power_flow trait requires config.model (EnergyGridModel)',\n    });\n    return;\n  }\n\n  try {\n    const result = solveDCPowerFlow(model, {\n      overloadToleranceRatio: config?.overloadToleranceRatio,\n    });\n    carrier.__powerFlowResult = result;\n    carrier.properties = {\n      ...(carrier.properties ?? {}),\n      powerFlowConverged: result.converged,\n      slackBusId: result.slackBusId,\n      overloadCount: result.overloadedLineIds.length,\n    };\n    const summary: PowerFlowSolvedEvent = {\n      nodeId,\n      converged: result.converged,\n      slackBusId: result.slackBusId,\n      lineFlowsMw: result.lineFlowsMw,\n      lineLoadingRatio: result.lineLoadingRatio,\n      overloadedLineIds: result.overloadedLineIds,\n      estimatedLossMw: result.estimatedLossMw,\n    };\n    context.setState?.({ [`power_flow:${nodeId}`]: summary });\n    context.emit('power_flow_solved', summary);\n  } catch (error) {\n    context.emit('power_flow_error', {\n      nodeId,\n      error: error instanceof Error ? error.message : String(error),\n    });\n  }\n}\n\n/**\n * Behavioral handler for the energy-grid `power_flow` trait. Runs the\n * deterministic DC power-flow solver whenever an orb carrying the trait is\n * attached (and on each per-frame update), writing the result onto the node\n * and emitting `power_flow_solved` / `power_flow_error`.\n */\nexport const powerFlowHandler: RuntimeTraitHandler = {\n  name: 'power_flow',\n  onAttach: (node, config, context) => solveOntoNode(node, config, context),\n  onUpdate: (node, config, context) => solveOntoNode(node, config, context),\n};\n\n/** A runtime that can register behavioral trait handlers. */\nexport interface TraitRegistrar {\n  registerTrait(name: string, handler: unknown): void;\n}\n\n/**\n * Register energy-grid behavioral trait handlers into a runtime that exposes\n * `registerTrait(name, handler)` — e.g. `@holoscript/core` HoloScriptRuntime.\n * This is the consumption path the dead-wired tier was missing: after this\n * call the runtime's directive dispatch (applyDirectives / updateTraits) will\n * invoke the energy-grid solver for `@power_flow` orbs.\n */\nexport function registerEnergyGridTraitHandlers(registrar: TraitRegistrar): void {\n  registerPluginTraits(registrar, ENERGY_GRID_PLUGIN_ID, [powerFlowHandler]);\n}\n","/**\n * Fitness & wellness solvers — fitness-wellness-plugin\n *\n * Implements:\n *  - VO2max estimation (Fick equation, Cooper test, Åstrand-Rhyming cycle)\n *  - 1-Rep Max prediction (Epley, Brzycki, Lander, Lombardi formulas)\n *  - MET-based calorie expenditure\n *  - Heart rate zones (Karvonen method)\n *  - RPE-to-intensity mapping (Borg 6-20 scale)\n *  - Training load (ACWR — acute:chronic workload ratio)\n *  - Body composition (Jackson-Pollock 3-site skinfold)\n *\n * References:\n *  - Epley B (1985) Poundage Chart. Boyd Epley Workout\n *  - Karvonen M et al. (1957) Ann.Med.Exp.Biol.Fenn 35:307-315\n *  - Jackson AS, Pollock ML (1978) Br.J.Nutr 40:497-504\n *  - ACSM Guidelines for Exercise Testing and Prescription (10th ed.)\n */\n\nimport { buildDomainSimulationReceipt, type DomainSimulationReceipt } from '@holoscript/core';\n\n// ─── Types ────────────────────────────────────────────────────────────────────\n\nexport interface OneRepMaxResult {\n  /** Measured weight lifted */\n  weightKg: number;\n  /** Number of reps performed */\n  reps: number;\n  /** Epley: w × (1 + r/30) */\n  epley: number;\n  /** Brzycki: w × 36/(37 − r) */\n  brzycki: number;\n  /** Lander: 100w / (101.3 − 2.67123r) */\n  lander: number;\n  /** Lombardi: w × r^0.10 */\n  lombardi: number;\n  /** Average of all four formulas */\n  average: number;\n}\n\nexport interface VO2MaxResult {\n  /** Estimated VO2max ml/kg/min */\n  vo2MaxMlKgMin: number;\n  /** Method used */\n  method: 'cooper-12min' | 'astrand-rhyming' | 'fick' | 'non-exercise';\n  /** Fitness classification (ACSM norms) */\n  fitnessClass: 'poor' | 'fair' | 'good' | 'excellent' | 'superior';\n}\n\nexport interface HeartRateZoneResult {\n  /** Resting heart rate bpm */\n  hrRest: number;\n  /** Maximum heart rate bpm */\n  hrMax: number;\n  /** Heart rate reserve (Karvonen) bpm */\n  hrr: number;\n  zones: {\n    zone1: { lo: number; hi: number; label: string };\n    zone2: { lo: number; hi: number; label: string };\n    zone3: { lo: number; hi: number; label: string };\n    zone4: { lo: number; hi: number; label: string };\n    zone5: { lo: number; hi: number; label: string };\n  };\n}\n\nexport interface CalorieBurnResult {\n  /** MET value for the activity */\n  met: number;\n  /** Body mass kg */\n  bodyMassKg: number;\n  /** Duration minutes */\n  durationMin: number;\n  /** Gross calorie expenditure kcal (MET × kg × hours) */\n  grossKcal: number;\n  /** Net calorie expenditure kcal (gross − BMR contribution) */\n  netKcal: number;\n}\n\nexport interface BodyCompositionResult {\n  /** Sum of 3 skinfold measurements mm */\n  skinfoldSumMm: number;\n  /** Body density g/cc (Jackson-Pollock equation) */\n  bodyDensityGcc: number;\n  /** Body fat percentage (Siri equation) */\n  bodyFatPct: number;\n  /** Fat mass kg */\n  fatMassKg: number;\n  /** Lean mass kg */\n  leanMassKg: number;\n}\n\nexport interface TrainingLoadResult {\n  /** Acute workload (7-day rolling average AU) */\n  acuteLoad: number;\n  /** Chronic workload (28-day rolling average AU) */\n  chronicLoad: number;\n  /** ACWR = acute / chronic */\n  acwr: number;\n  /**\n   * Injury-risk category per Gabbett (2016) ACWR bands:\n   *  - 'high'      → ACWR < 0.8          (under-prepared / detraining)\n   *  - 'low'       → 0.8 ≤ ACWR ≤ 1.3    (sweet spot)\n   *  - 'moderate'  → 1.3 < ACWR ≤ 1.5    (ramp-up)\n   *  - 'very-high' → ACWR > 1.5          (danger zone)\n   */\n  riskCategory: 'low' | 'moderate' | 'high' | 'very-high';\n}\n\nexport interface FitnessReceiptOptions {\n  runId?: string;\n}\n\n// ─── 1-Rep Max prediction ─────────────────────────────────────────────────────\n\n/**\n * Predict 1-rep maximum using four validated formulas.\n * Accurate for reps ≤ 10; less reliable for > 15 reps.\n */\nexport function oneRepMax(weightKg: number, reps: number): OneRepMaxResult {\n  if (weightKg <= 0) throw new Error('weightKg must be positive');\n  if (reps < 1 || !Number.isInteger(reps)) throw new Error('reps must be a positive integer');\n  if (reps === 1) {\n    return {\n      weightKg,\n      reps,\n      epley: weightKg,\n      brzycki: weightKg,\n      lander: weightKg,\n      lombardi: weightKg,\n      average: weightKg,\n    };\n  }\n  if (reps > 30) throw new Error('reps > 30 is outside the validated range');\n\n  const epley = weightKg * (1 + reps / 30);\n  const brzycki = (weightKg * 36) / (37 - reps);\n  const lander = (100 * weightKg) / (101.3 - 2.67123 * reps);\n  const lombardi = weightKg * Math.pow(reps, 0.1);\n  const average = (epley + brzycki + lander + lombardi) / 4;\n\n  return { weightKg, reps, epley, brzycki, lander, lombardi, average };\n}\n\n// ─── VO2max estimation ────────────────────────────────────────────────────────\n\n/**\n * Cooper 12-minute run test.\n * VO2max (ml/kg/min) = (distance_m − 504.9) / 44.73\n */\nexport function vo2MaxCooper(distanceMeters: number): VO2MaxResult {\n  if (distanceMeters <= 0) throw new Error('distanceMeters must be positive');\n  const vo2 = (distanceMeters - 504.9) / 44.73;\n  return {\n    vo2MaxMlKgMin: Math.max(0, vo2),\n    method: 'cooper-12min',\n    fitnessClass: classifyVO2(vo2),\n  };\n}\n\n/**\n * Åstrand-Rhyming nomogram (cycle ergometer).\n * VO2max ≈ 0.00212 × workloadW + 0.299 (simplified linear regression)\n * More accurately: VO2max = (workload × 6) / (hrSteadyState - 37.182) × 3.5 for females\n * We use the standard ACSM leg-cycling equation:\n *   VO2 (ml/min) = 1.8 × workRate(kgm/min) / bodyMassKg + 7  [in ml/kg/min]\n * Then scale by correction factor for age-adjusted HRmax.\n */\nexport function vo2MaxAstrand(\n  workRateWatts: number,\n  hrSteadyState: number,\n  bodyMassKg: number,\n  ageYears: number\n): VO2MaxResult {\n  if (workRateWatts <= 0) throw new Error('workRateWatts must be positive');\n  if (hrSteadyState <= 0 || hrSteadyState > 250) throw new Error('hrSteadyState out of range');\n  if (bodyMassKg <= 0) throw new Error('bodyMassKg must be positive');\n\n  // Work rate in kgm/min (1 W = 6.12 kgm/min approximately)\n  const kgmMin = workRateWatts * 6.12;\n  // ACSM gross VO2 equation for leg cycling\n  const vo2Gross = (1.8 * kgmMin) / bodyMassKg + 7; // ml/kg/min\n  // Age-based HRmax correction (Astrand factor)\n  const hrMax = 220 - ageYears;\n  const correctionFactor = hrMax / hrSteadyState;\n  const vo2Max = vo2Gross * correctionFactor * 0.836; // empirical scaling\n\n  return {\n    vo2MaxMlKgMin: Math.max(0, vo2Max),\n    method: 'astrand-rhyming',\n    fitnessClass: classifyVO2(vo2Max),\n  };\n}\n\n/**\n * Non-exercise VO2max estimation from demographic and fitness data.\n * Jackson et al. (1990) equation:\n *   VO2max = 56.363 + 1.921×PA_R − 0.381×age − 0.754×BMI + 10.987×sex\n */\nexport function vo2MaxNonExercise(\n  ageYears: number,\n  bmi: number,\n  physicalActivityRating: number, // PA-R: 0-10 Likert scale\n  isMale: boolean\n): VO2MaxResult {\n  if (ageYears < 10 || ageYears > 100) throw new Error('ageYears out of range [10, 100]');\n  if (bmi <= 10 || bmi > 70) throw new Error('BMI out of plausible range');\n  if (physicalActivityRating < 0 || physicalActivityRating > 10)\n    throw new Error('PA_R must be in [0, 10]');\n\n  const sex = isMale ? 1 : 0;\n  const vo2 =\n    56.363 + 1.921 * physicalActivityRating - 0.381 * ageYears - 0.754 * bmi + 10.987 * sex;\n  return {\n    vo2MaxMlKgMin: Math.max(10, vo2),\n    method: 'non-exercise',\n    fitnessClass: classifyVO2(vo2),\n  };\n}\n\nfunction classifyVO2(vo2: number): VO2MaxResult['fitnessClass'] {\n  if (vo2 < 25) return 'poor';\n  if (vo2 < 34) return 'fair';\n  if (vo2 < 42) return 'good';\n  if (vo2 < 52) return 'excellent';\n  return 'superior';\n}\n\n// ─── Heart rate zones (Karvonen) ─────────────────────────────────────────────\n\n/**\n * Compute 5-zone heart rate training plan using Karvonen (heart rate reserve) method.\n * Zone boundaries: 50–60%, 60–70%, 70–80%, 80–90%, 90–100% of HRR.\n */\nexport function heartRateZones(hrRest: number, hrMax: number): HeartRateZoneResult {\n  if (hrRest <= 0 || hrMax <= 0) throw new Error('Heart rates must be positive');\n  if (hrMax <= hrRest) throw new Error('hrMax must be > hrRest');\n\n  const hrr = hrMax - hrRest;\n  const zone = (lo: number, hi: number) => ({\n    lo: Math.round(hrRest + lo * hrr),\n    hi: Math.round(hrRest + hi * hrr),\n  });\n\n  return {\n    hrRest,\n    hrMax,\n    hrr,\n    zones: {\n      zone1: { ...zone(0.5, 0.6), label: 'Recovery / Active Rest' },\n      zone2: { ...zone(0.6, 0.7), label: 'Aerobic Base / Fat Burn' },\n      zone3: { ...zone(0.7, 0.8), label: 'Aerobic / Tempo' },\n      zone4: { ...zone(0.8, 0.9), label: 'Lactate Threshold' },\n      zone5: { ...zone(0.9, 1.0), label: 'VO2max / Neuromuscular' },\n    },\n  };\n}\n\n// ─── MET-based calorie burn ───────────────────────────────────────────────────\n\n/** Common activity METs from the Compendium of Physical Activities (2011) */\nexport const ACTIVITY_METS: Record<string, number> = {\n  running_6mph: 9.8,\n  running_8mph: 11.8,\n  running_10mph: 14.5,\n  cycling_moderate: 8.0,\n  cycling_vigorous: 12.0,\n  swimming_moderate: 6.0,\n  swimming_vigorous: 9.8,\n  walking_3mph: 3.5,\n  walking_4mph: 5.0,\n  strength_training: 3.5,\n  yoga: 2.5,\n  rowing_moderate: 7.0,\n  rowing_vigorous: 12.0,\n  basketball: 8.0,\n  soccer: 7.0,\n};\n\n/**\n * Estimate gross and net calorie expenditure.\n * Gross: MET × bodyMassKg × durationHours\n * Net: gross − BMR_rate × duration (approximate BMR ≈ 1 MET contribution)\n */\nexport function calorieBurn(\n  met: number,\n  bodyMassKg: number,\n  durationMin: number\n): CalorieBurnResult {\n  if (met <= 0) throw new Error('MET must be positive');\n  if (bodyMassKg <= 0) throw new Error('bodyMassKg must be positive');\n  if (durationMin <= 0) throw new Error('durationMin must be positive');\n\n  const durationHours = durationMin / 60;\n  const grossKcal = met * bodyMassKg * durationHours;\n  // Net = activity kcal above resting (subtract 1 MET baseline)\n  const netKcal = (met - 1.0) * bodyMassKg * durationHours;\n\n  return { met, bodyMassKg, durationMin, grossKcal, netKcal: Math.max(0, netKcal) };\n}\n\n// ─── Body composition (Jackson-Pollock 3-site skinfold) ───────────────────────\n\n/**\n * Jackson-Pollock 3-site skinfold body density equations.\n * Male sites: chest, abdomen, thigh (mm)\n * Female sites: triceps, suprailiac, thigh (mm)\n * Body fat % via Siri (1956): %BF = (4.95/D − 4.50) × 100\n */\nexport function jacksonPollockSkinfold(\n  s1Mm: number,\n  s2Mm: number,\n  s3Mm: number,\n  ageYears: number,\n  isMale: boolean,\n  bodyMassKg: number\n): BodyCompositionResult {\n  if (s1Mm <= 0 || s2Mm <= 0 || s3Mm <= 0)\n    throw new Error('Skinfold measurements must be positive');\n  if (ageYears < 18 || ageYears > 80) throw new Error('Age must be in [18, 80]');\n  if (bodyMassKg <= 0) throw new Error('bodyMassKg must be positive');\n\n  const sum = s1Mm + s2Mm + s3Mm;\n  const sum2 = sum * sum;\n\n  // Jackson-Pollock (1978/1980) equations for body density\n  let density: number;\n  if (isMale) {\n    // 3-site (chest + abdomen + thigh)\n    density = 1.10938 - 0.0008267 * sum + 0.0000016 * sum2 - 0.0002574 * ageYears;\n  } else {\n    // 3-site (triceps + suprailiac + thigh)\n    density = 1.0994921 - 0.0009929 * sum + 0.0000023 * sum2 - 0.0001392 * ageYears;\n  }\n\n  // Siri equation\n  const bodyFatPct = (4.95 / density - 4.5) * 100;\n  const fatMassKg = (bodyMassKg * bodyFatPct) / 100;\n  const leanMassKg = bodyMassKg - fatMassKg;\n\n  return { skinfoldSumMm: sum, bodyDensityGcc: density, bodyFatPct, fatMassKg, leanMassKg };\n}\n\n// ─── Training load (ACWR) ─────────────────────────────────────────────────────\n\n/**\n * Compute acute:chronic workload ratio (Gabbett 2016).\n * workloads: array of daily AU (arbitrary units), most recent last.\n * Returns injury risk classification.\n */\nexport function acuteChronicWorkloadRatio(workloads: number[]): TrainingLoadResult {\n  if (workloads.length < 7) throw new Error('At least 7 days of workload data required');\n\n  const recent = workloads.slice(-28);\n  const acuteWindow = recent.slice(-7);\n  const chronicWindow = recent;\n\n  const acuteLoad = acuteWindow.reduce((a, b) => a + b, 0) / 7;\n  const chronicLoad = chronicWindow.reduce((a, b) => a + b, 0) / chronicWindow.length;\n\n  const acwr = chronicLoad === 0 ? 0 : acuteLoad / chronicLoad;\n\n  // Injury-risk bands (Gabbett 2016, \"training–injury prevention paradox\").\n  // Ordered ascending by ACWR; the bands are contiguous and exhaustive, so\n  // each ACWR maps to exactly one category — no dead branch, no re-assignment.\n  let riskCategory: TrainingLoadResult['riskCategory'];\n  if (acwr < 0.8) {\n    // Under-prepared / detraining: chronically low load leaves the athlete\n    // unconditioned, which itself carries elevated injury risk.\n    riskCategory = 'high';\n  } else if (acwr <= 1.3) {\n    // \"Sweet spot\" (0.8–1.3): acute load matched to the chronic base — lowest risk.\n    riskCategory = 'low';\n  } else if (acwr <= 1.5) {\n    // Ramp-up zone (1.3–1.5): load climbing faster than the base supports.\n    riskCategory = 'moderate';\n  } else {\n    // Danger zone (> 1.5): acute spike well beyond the chronic base — highest risk.\n    riskCategory = 'very-high';\n  }\n\n  return { acuteLoad, chronicLoad, acwr, riskCategory };\n}\n\n// ─── Unified analysis entry-point ─────────────────────────────────────────────\n\nexport interface FitnessAnalysisInput {\n  oneRM?: { weightKg: number; reps: number };\n  vo2Max?:\n    | { method: 'cooper'; distanceM: number }\n    | {\n        method: 'astrand';\n        workRateW: number;\n        hrSteady: number;\n        bodyMassKg: number;\n        ageYears: number;\n      }\n    | { method: 'non-exercise'; ageYears: number; bmi: number; paRating: number; isMale: boolean };\n  hrZones?: { hrRest: number; hrMax: number };\n  calories?: { met: number; bodyMassKg: number; durationMin: number };\n  bodyComp?: {\n    s1: number;\n    s2: number;\n    s3: number;\n    ageYears: number;\n    isMale: boolean;\n    bodyMassKg: number;\n  };\n  trainingLoad?: { workloads: number[] };\n}\n\nexport interface FitnessAnalysisResult {\n  oneRM?: OneRepMaxResult;\n  vo2Max?: VO2MaxResult;\n  hrZones?: HeartRateZoneResult;\n  calories?: CalorieBurnResult;\n  bodyComp?: BodyCompositionResult;\n  trainingLoad?: TrainingLoadResult;\n  converged: true;\n}\n\nexport function analyzeFitness(input: FitnessAnalysisInput): FitnessAnalysisResult {\n  const result: FitnessAnalysisResult = { converged: true };\n\n  if (input.oneRM) result.oneRM = oneRepMax(input.oneRM.weightKg, input.oneRM.reps);\n\n  if (input.vo2Max) {\n    const v = input.vo2Max;\n    if (v.method === 'cooper') result.vo2Max = vo2MaxCooper(v.distanceM);\n    else if (v.method === 'astrand')\n      result.vo2Max = vo2MaxAstrand(v.workRateW, v.hrSteady, v.bodyMassKg, v.ageYears);\n    else result.vo2Max = vo2MaxNonExercise(v.ageYears, v.bmi, v.paRating, v.isMale);\n  }\n\n  if (input.hrZones) result.hrZones = heartRateZones(input.hrZones.hrRest, input.hrZones.hrMax);\n  if (input.calories)\n    result.calories = calorieBurn(\n      input.calories.met,\n      input.calories.bodyMassKg,\n      input.calories.durationMin\n    );\n  if (input.bodyComp) {\n    const b = input.bodyComp;\n    result.bodyComp = jacksonPollockSkinfold(b.s1, b.s2, b.s3, b.ageYears, b.isMale, b.bodyMassKg);\n  }\n  if (input.trainingLoad)\n    result.trainingLoad = acuteChronicWorkloadRatio(input.trainingLoad.workloads);\n\n  return result;\n}\n\n// ─── Receipt ──────────────────────────────────────────────────────────────────\n\nexport function buildFitnessReceipt(\n  result: FitnessAnalysisResult,\n  options?: FitnessReceiptOptions\n): DomainSimulationReceipt {\n  const violations: Array<{ criterion: string; message: string }> = [];\n\n  if (result.bodyComp && (result.bodyComp.bodyFatPct < 3 || result.bodyComp.bodyFatPct > 60)) {\n    violations.push({\n      criterion: 'body_fat',\n      message: `body fat ${result.bodyComp.bodyFatPct.toFixed(1)}% outside plausible range [3%, 60%]`,\n    });\n  }\n  if (result.trainingLoad && result.trainingLoad.riskCategory === 'very-high') {\n    violations.push({\n      criterion: 'acwr',\n      message: `ACWR ${result.trainingLoad.acwr.toFixed(2)} is very high (>1.5) — injury risk elevated`,\n    });\n  }\n\n  return buildDomainSimulationReceipt({\n    plugin: 'fitness-wellness',\n    pluginVersion: '1.0.0',\n    runId: options?.runId ?? `fit-${Date.now().toString(36)}`,\n    solverConfig: { solverType: 'fitness-analytics', scale: 'individual' },\n    resultSummary: {\n      vo2MaxMlKgMin: result.vo2Max?.vo2MaxMlKgMin ?? null,\n      fitnessClass: result.vo2Max?.fitnessClass ?? null,\n      oneRMAvgKg: result.oneRM?.average ?? null,\n      bodyFatPct: result.bodyComp?.bodyFatPct ?? null,\n      acwr: result.trainingLoad?.acwr ?? null,\n    },\n    cael: {\n      version: 'cael.v1',\n      event: 'fitness_wellness.fitness_analysis',\n      solverType: 'fitness-wellness.analytics',\n    },\n    acceptance: { accepted: violations.length === 0, violations },\n  });\n}\n","/**\n * Runtime integration for @holoscript/plugin-fitness-wellness.\n *\n * Bridges the previously dead-wired `one_rep_max` trait into a behavioral\n * TraitHandler that the HoloScript runtime actually dispatches\n * (HoloScriptRuntime.registerTrait -> applyDirectives / updateTraits).\n *\n * Before this module the plugin declared trait NAMES only (pluginMeta.traits)\n * and exported the fitness solvers (oneRepMax, heartRateZones, calorieBurn, …),\n * but nothing invoked a solver THROUGH the runtime — the whole domain-plugin\n * tier was built-but-dead-wired. This mirrors government-civic-plugin's\n * reference integration (civic_decision): it wires the deterministic\n * 1-rep-max prediction solver (`oneRepMax`) behind the `one_rep_max` trait so\n * the runtime's directive dispatch can run it. The remaining fitness traits\n * follow the same registrar shape.\n */\nimport { registerPluginTraits } from '@holoscript/core/runtime';\nimport { oneRepMax, type OneRepMaxResult } from './fitnesssolver';\n\n/** Stable id for this plugin's trait ownership tagging. */\nexport const FITNESS_WELLNESS_PLUGIN_ID = 'fitness-wellness' as const;\n\n/** Config carried by an orb's `@one_rep_max` trait directive. */\nexport interface OneRepMaxTraitConfig {\n  /** Measured weight lifted (kg). Required; absence/invalid emits `one_rep_max_error`. */\n  weightKg?: number;\n  /** Reps performed at that weight. Required positive integer; absence/invalid emits error. */\n  reps?: number;\n}\n\n/** Summary payload emitted on `one_rep_max_solved`. */\nexport interface OneRepMaxSolvedEvent {\n  nodeId: string;\n  /** Measured weight echoed back. */\n  weightKg: number;\n  /** Reps echoed back. */\n  reps: number;\n  /** Epley-formula predicted 1RM (kg). */\n  epley: number;\n  /** Brzycki-formula predicted 1RM (kg). */\n  brzycki: number;\n  /** Lander-formula predicted 1RM (kg). */\n  lander: number;\n  /** Lombardi-formula predicted 1RM (kg). */\n  lombardi: number;\n  /** Average of all four formula predictions (kg). */\n  average: number;\n}\n\n/**\n * Structural view of the runtime trait-handler contract. Matches\n * `@holoscript/core` TraitTypes.TraitHandler at the call sites the runtime\n * actually uses (onAttach / onUpdate receive the node, the directive config,\n * and a context exposing `emit`). Declared locally so the plugin stays\n * decoupled from core's full trait surface.\n */\nexport interface TraitDispatchContext {\n  emit: (event: string, payload?: unknown) => void;\n  setState?: (updates: Record<string, unknown>) => void;\n}\n\nexport interface RuntimeTraitHandler {\n  name: string;\n  onAttach?: (node: unknown, config: OneRepMaxTraitConfig, context: TraitDispatchContext) => void;\n  onUpdate?: (\n    node: unknown,\n    config: OneRepMaxTraitConfig,\n    context: TraitDispatchContext,\n    delta: number\n  ) => void;\n}\n\ninterface OneRepMaxNode {\n  id?: string;\n  name?: string;\n  properties?: Record<string, unknown>;\n  __oneRepMaxResult?: OneRepMaxResult;\n}\n\n/** Run the 1RM solver on the directive config, write the result onto the node, and emit. */\nfunction solveOntoNode(\n  node: unknown,\n  config: OneRepMaxTraitConfig | undefined,\n  context: TraitDispatchContext\n): void {\n  const carrier = node as OneRepMaxNode;\n  const nodeId = carrier.id ?? carrier.name ?? 'unknown';\n  const weightKg = config?.weightKg;\n  const reps = config?.reps;\n\n  if (typeof weightKg !== 'number' || typeof reps !== 'number') {\n    context.emit('one_rep_max_error', {\n      nodeId,\n      error: 'one_rep_max trait requires config.weightKg (number) and config.reps (number)',\n    });\n    return;\n  }\n\n  try {\n    const result = oneRepMax(weightKg, reps);\n    carrier.__oneRepMaxResult = result;\n    carrier.properties = {\n      ...(carrier.properties ?? {}),\n      oneRepMaxEpley: result.epley,\n      oneRepMaxAverage: result.average,\n    };\n    const summary: OneRepMaxSolvedEvent = {\n      nodeId,\n      weightKg: result.weightKg,\n      reps: result.reps,\n      epley: result.epley,\n      brzycki: result.brzycki,\n      lander: result.lander,\n      lombardi: result.lombardi,\n      average: result.average,\n    };\n    context.setState?.({ [`one_rep_max:${nodeId}`]: summary });\n    context.emit('one_rep_max_solved', summary);\n  } catch (error) {\n    context.emit('one_rep_max_error', {\n      nodeId,\n      error: error instanceof Error ? error.message : String(error),\n    });\n  }\n}\n\n/**\n * Behavioral handler for the fitness-wellness `one_rep_max` trait. Runs the\n * deterministic 1-rep-max prediction solver whenever an orb carrying the trait\n * is attached (and on each per-frame update), writing the result onto the node\n * and emitting `one_rep_max_solved` / `one_rep_max_error`.\n */\nexport const oneRepMaxHandler: RuntimeTraitHandler = {\n  name: 'one_rep_max',\n  onAttach: (node, config, context) => solveOntoNode(node, config, context),\n  onUpdate: (node, config, context) => solveOntoNode(node, config, context),\n};\n\n/** A runtime that can register behavioral trait handlers. */\nexport interface TraitRegistrar {\n  registerTrait(name: string, handler: unknown): void;\n}\n\n/**\n * Register fitness-wellness behavioral trait handlers into a runtime that\n * exposes `registerTrait(name, handler)` — e.g. `@holoscript/core`\n * HoloScriptRuntime. This is the consumption path the dead-wired tier was\n * missing: after this call the runtime's directive dispatch (applyDirectives /\n * updateTraits) will invoke the 1RM solver for `@one_rep_max` orbs.\n */\nexport function registerFitnessWellnessTraitHandlers(registrar: TraitRegistrar): void {\n  registerPluginTraits(registrar, FITNESS_WELLNESS_PLUGIN_ID, [oneRepMaxHandler]);\n}\n","/**\n * Revenue management solvers — travel-hospitality-plugin\n *\n * Implements:\n *  - Hotel yield management (EMSR-b overbooking model)\n *  - Dynamic pricing (bid-price control)\n *  - RevPAR / ADR / Occupancy analytics\n *  - Demand forecasting (exponential smoothing with seasonality)\n *  - Overbooking optimization (walk cost vs denied revenue trade-off)\n *  - Displacement cost calculation for group bookings\n *\n * References:\n *  - Littlewood K (1972) 12th AGIFORS Symposium — original yield management\n *  - Belobaba PP (1987) MIT thesis — EMSR\n *  - Cross RG (1997) Revenue Management — practical implementation\n */\n\nimport { buildDomainSimulationReceipt, type DomainSimulationReceipt } from '@holoscript/core';\n\n// ─── Types ────────────────────────────────────────────────────────────────────\n\nexport interface RateClass {\n  /** Rate class identifier */\n  id: string;\n  /** Average daily rate for this class ($) */\n  adr: number;\n  /** Expected demand (units) */\n  expectedDemand: number;\n  /** Demand standard deviation */\n  demandStdDev: number;\n}\n\nexport interface EMSRResult {\n  /** Protection levels per class (units to hold for higher classes) */\n  protectionLevels: number[];\n  /** Booking limits per class (open capacity for each class) */\n  bookingLimits: number[];\n  /** Expected revenue at optimal allocation */\n  expectedRevenue: number;\n  /** Rate classes (sorted high→low ADR) */\n  rateClasses: RateClass[];\n}\n\nexport interface RevPARResult {\n  /** Rooms available */\n  availableRooms: number;\n  /** Rooms occupied */\n  occupiedRooms: number;\n  /** Occupancy rate [0,1] */\n  occupancyRate: number;\n  /** Average Daily Rate ($) */\n  adr: number;\n  /** Revenue Per Available Room = ADR × occupancy */\n  revpar: number;\n  /** Total room revenue ($) */\n  totalRevenue: number;\n}\n\nexport interface OverbookingResult {\n  /** Total capacity */\n  capacity: number;\n  /** Optimal overbooking level (rooms above capacity) */\n  overbook: number;\n  /** Authorized bookings to accept */\n  authorizedBookings: number;\n  /** Expected no-show rate */\n  noShowRate: number;\n  /** Expected walk cost per displaced guest ($) */\n  walkCostPerGuest: number;\n  /** Expected total walk cost */\n  expectedWalkCost: number;\n  /** Expected revenue gain from overbooking vs no overbooking */\n  expectedRevenueGain: number;\n}\n\nexport interface GroupDisplacementResult {\n  /** Group ADR */\n  groupAdr: number;\n  /** Group room-nights */\n  groupRoomNights: number;\n  /** Estimated transient ADR displaced */\n  transientAdr: number;\n  /** Displacement cost = (transientAdr - groupAdr) × roomNights */\n  displacementCost: number;\n  /** Net value: group revenue − displacement cost */\n  netValue: number;\n  /** Whether group booking is profitable */\n  profitable: boolean;\n}\n\nexport interface HotelForecastResult {\n  historical: number[];\n  forecast: number[];\n  /** Seasonal indices (7-day weekly pattern) */\n  seasonalIndices: number[];\n  rmse: number;\n}\n\nexport interface RevenueReceiptOptions {\n  runId?: string;\n}\n\n// ─── EMSR-b yield management ──────────────────────────────────────────────────\n\n/** Normal CDF approximation (Abramowitz & Stegun) */\nfunction normalCDF(x: number): number {\n  if (x < -6) return 0;\n  if (x > 6) return 1;\n  const a1 = 0.254829592,\n    a2 = -0.284496736,\n    a3 = 1.421413741;\n  const a4 = -1.453152027,\n    a5 = 1.061405429,\n    p = 0.3275911;\n  const sign = x >= 0 ? 1 : -1;\n  const absX = Math.abs(x);\n  const t = 1 / (1 + p * absX);\n  const poly = (((a5 * t + a4) * t + a3) * t + a2) * t + a1;\n  const erfVal = 1 - poly * t * Math.exp(-absX * absX);\n  return 0.5 * (1 + sign * erfVal);\n}\n\n/** Littlewood's rule: P(demand ≥ x) ≥ r_low/r_high → protect x seats for high class */\nfunction littlewoodProtection(rLow: number, rHigh: number, mu: number, sigma: number): number {\n  // Find x such that P(D_high ≥ x) = r_low / r_high\n  const threshold = rLow / rHigh;\n  // P(D ≥ x) = 1 - Φ((x - μ)/σ)\n  // 1 - Φ(z) = threshold → z = Φ⁻¹(1 - threshold)\n  // Approximate Φ⁻¹ via rational approximation\n  const p = 1 - threshold;\n  const z = normInvApprox(p);\n  return Math.max(0, Math.round(mu + sigma * z));\n}\n\n/** Approximate normal quantile (Peter Acklam's approximation) */\nfunction normInvApprox(p: number): number {\n  if (p <= 0) return -6;\n  if (p >= 1) return 6;\n  const a = [\n    -3.969683028665376e1, 2.209460984245205e2, -2.759285104469687e2, 1.38357751867269e2,\n    -3.066479806614716e1, 2.506628277459239,\n  ];\n  const b = [\n    -5.447609879822406e1, 1.615858368580409e2, -1.556989798598866e2, 6.680131188771972e1,\n    -1.328068155288572e1,\n  ];\n  const c = [\n    -7.784894002430293e-3, -3.223964580411365e-1, -2.400758277161838, -2.549732539343734,\n    4.374664141464968, 2.938163982698783,\n  ];\n  const d = [7.784695709041462e-3, 3.224671290700398e-1, 2.445134137142996, 3.754408661907416];\n  const pLow = 0.02425,\n    pHigh = 1 - pLow;\n\n  let q: number, r: number;\n  if (p < pLow) {\n    q = Math.sqrt(-2 * Math.log(p));\n    return (\n      (((((c[0] * q + c[1]) * q + c[2]) * q + c[3]) * q + c[4]) * q + c[5]) /\n      ((((d[0] * q + d[1]) * q + d[2]) * q + d[3]) * q + 1)\n    );\n  } else if (p <= pHigh) {\n    q = p - 0.5;\n    r = q * q;\n    return (\n      ((((((a[0] * r + a[1]) * r + a[2]) * r + a[3]) * r + a[4]) * r + a[5]) * q) /\n      (((((b[0] * r + b[1]) * r + b[2]) * r + b[3]) * r + b[4]) * r + 1)\n    );\n  } else {\n    q = Math.sqrt(-2 * Math.log(1 - p));\n    return (\n      -(((((c[0] * q + c[1]) * q + c[2]) * q + c[3]) * q + c[4]) * q + c[5]) /\n      ((((d[0] * q + d[1]) * q + d[2]) * q + d[3]) * q + 1)\n    );\n  }\n}\n\n/**\n * EMSR-b (Expected Marginal Seat Revenue-b) multi-class yield management.\n * Rate classes must be provided in any order; sorted high→low ADR internally.\n * capacity: total rooms available.\n */\nexport function emsrYieldManagement(capacity: number, rateClasses: RateClass[]): EMSRResult {\n  if (capacity <= 0) throw new Error('capacity must be positive');\n  if (rateClasses.length === 0) throw new Error('At least one rate class required');\n\n  // Sort descending by ADR\n  const sorted = [...rateClasses].sort((a, b) => b.adr - a.adr);\n\n  const protectionLevels: number[] = [];\n  const bookingLimits: number[] = [];\n\n  // EMSR-b: aggregate demand from classes j+1..n and find protection for class j\n  for (let j = 0; j < sorted.length - 1; j++) {\n    const r_j = sorted[j].adr; // higher class fare\n    const r_j1 = sorted[j + 1].adr; // lower class fare\n\n    // Aggregate demand for classes 0..j (high-value classes)\n    let aggMu = 0,\n      aggVar = 0;\n    for (let k = 0; k <= j; k++) {\n      aggMu += sorted[k].expectedDemand;\n      aggVar += sorted[k].demandStdDev ** 2;\n    }\n    const aggSigma = Math.sqrt(aggVar);\n\n    const prot = littlewoodProtection(r_j1, r_j, aggMu, aggSigma);\n    protectionLevels.push(prot);\n  }\n  protectionLevels.push(0); // lowest class has no protection\n\n  // Booking limits: cumulative from lowest to highest\n  let remaining = capacity;\n  const bls: number[] = new Array(sorted.length).fill(0);\n  for (let j = sorted.length - 1; j >= 0; j--) {\n    const protect = j > 0 ? protectionLevels[j - 1] : 0;\n    bls[j] = Math.max(0, remaining - protect);\n    remaining = Math.max(0, remaining - sorted[j].expectedDemand);\n  }\n\n  // Expected revenue estimate\n  let expectedRevenue = 0;\n  for (let j = 0; j < sorted.length; j++) {\n    const expectedSales = Math.min(sorted[j].expectedDemand, bls[j]);\n    expectedRevenue += expectedSales * sorted[j].adr;\n  }\n\n  return { protectionLevels, bookingLimits: bls, expectedRevenue, rateClasses: sorted };\n}\n\n// ─── RevPAR / ADR / Occupancy ─────────────────────────────────────────────────\n\nexport function revparAnalysis(\n  availableRooms: number,\n  occupiedRooms: number,\n  totalRevenue: number\n): RevPARResult {\n  if (availableRooms <= 0) throw new Error('availableRooms must be positive');\n  if (occupiedRooms < 0) throw new Error('occupiedRooms must be non-negative');\n  if (occupiedRooms > availableRooms) throw new Error('occupiedRooms cannot exceed availableRooms');\n  if (totalRevenue < 0) throw new Error('totalRevenue must be non-negative');\n\n  const occupancyRate = occupiedRooms / availableRooms;\n  const adr = occupiedRooms > 0 ? totalRevenue / occupiedRooms : 0;\n  const revpar = adr * occupancyRate;\n\n  return { availableRooms, occupiedRooms, occupancyRate, adr, revpar, totalRevenue };\n}\n\n// ─── Overbooking optimization ─────────────────────────────────────────────────\n\n/**\n * Optimal overbooking level using newsvendor-style model.\n * Overbook = Q such that P(no-shows ≥ overbook) = walkCost / (revenue + walkCost)\n *\n * No-show count modeled as Binomial(n+overbook, noShowRate) ≈ Normal.\n */\nexport function overbookingOptimization(\n  capacity: number,\n  noShowRate: number,\n  adr: number,\n  walkCostPerGuest: number,\n  expectedBookings: number\n): OverbookingResult {\n  if (capacity <= 0) throw new Error('capacity must be positive');\n  if (noShowRate < 0 || noShowRate > 1) throw new Error('noShowRate must be in [0, 1]');\n  if (adr <= 0) throw new Error('adr must be positive');\n  if (walkCostPerGuest < 0) throw new Error('walkCostPerGuest must be non-negative');\n\n  // Critical ratio for overbooking newsvendor\n  const criticalRatio = adr / (adr + walkCostPerGuest);\n\n  // No-show distribution at bookings = capacity + overbook\n  // Expected no-shows = noShowRate × bookings\n  // For small overbook, find overbook* where P(no-shows ≥ overbook) = 1 - criticalRatio\n  let optOverbook = 0;\n  for (let ob = 0; ob <= Math.floor(capacity * 0.3); ob++) {\n    const bookings = capacity + ob;\n    const mu = noShowRate * bookings;\n    const sigma = Math.sqrt(bookings * noShowRate * (1 - noShowRate));\n    const pNoShowGe = 1 - normalCDF((ob - mu) / Math.max(sigma, 0.1));\n    if (pNoShowGe < 1 - criticalRatio) {\n      optOverbook = Math.max(0, ob - 1);\n      break;\n    }\n    optOverbook = ob;\n  }\n\n  const authorizedBookings = capacity + optOverbook;\n  const mu = noShowRate * authorizedBookings;\n  const sigma = Math.sqrt(authorizedBookings * noShowRate * (1 - noShowRate));\n\n  // Expected walks = E[max(0, shows - capacity)] where shows = bookings - noShows\n  let expectedWalks = 0;\n  for (let w = 1; w <= optOverbook + 5; w++) {\n    const pWalk =\n      1 - normalCDF((w - 0.5 - (authorizedBookings - mu - capacity)) / Math.max(sigma, 0.1));\n    expectedWalks += pWalk;\n    if (pWalk < 1e-6) break;\n  }\n  expectedWalks = Math.max(0, expectedWalks);\n\n  const expectedWalkCost = expectedWalks * walkCostPerGuest;\n  // Revenue gain vs no-overbooking: each additional booking accepted at ADR, less expected walk cost\n  const expectedRevenueGain = Math.max(0, optOverbook * adr * noShowRate - expectedWalkCost);\n\n  return {\n    capacity,\n    overbook: optOverbook,\n    authorizedBookings,\n    noShowRate,\n    walkCostPerGuest,\n    expectedWalkCost,\n    expectedRevenueGain,\n  };\n}\n\n// ─── Group displacement ───────────────────────────────────────────────────────\n\n/**\n * Calculate whether accepting a group booking displaces more-valuable transient demand.\n */\nexport function groupDisplacementAnalysis(\n  groupAdr: number,\n  groupRoomNights: number,\n  transientAdr: number,\n  transientDemandProbability = 1.0\n): GroupDisplacementResult {\n  if (groupAdr <= 0) throw new Error('groupAdr must be positive');\n  if (groupRoomNights <= 0) throw new Error('groupRoomNights must be positive');\n  if (transientAdr <= 0) throw new Error('transientAdr must be positive');\n\n  const displacementCost = (transientAdr - groupAdr) * groupRoomNights * transientDemandProbability;\n  const netValue =\n    groupAdr * groupRoomNights - transientAdr * groupRoomNights * transientDemandProbability;\n  const profitable = netValue > 0;\n\n  return { groupAdr, groupRoomNights, transientAdr, displacementCost, netValue, profitable };\n}\n\n// ─── Demand forecasting with weekly seasonality ───────────────────────────────\n\n/**\n * Hotel room demand forecast using exponential smoothing + weekly seasonality indices.\n * Requires at least 14 days of history for seasonal estimation.\n */\nexport function hotelDemandForecast(\n  historical: number[],\n  forecastDays: number\n): HotelForecastResult {\n  if (historical.length < 14)\n    throw new Error('At least 14 days of history required for seasonal estimation');\n  if (forecastDays < 1) throw new Error('forecastDays must be ≥ 1');\n\n  // Estimate weekly seasonal indices (7 days)\n  const seasonalIndices = Array(7).fill(0);\n  const dayCounts = Array(7).fill(0);\n  const overallMean = historical.reduce((a, b) => a + b, 0) / historical.length;\n\n  historical.forEach((v, i) => {\n    const dow = i % 7;\n    seasonalIndices[dow] += v;\n    dayCounts[dow]++;\n  });\n  seasonalIndices.forEach((s, i) => {\n    seasonalIndices[i] = overallMean > 0 ? s / dayCounts[i] / overallMean : 1;\n  });\n\n  // Deseasonalise\n  const deseason = historical.map((v, i) => {\n    const idx = seasonalIndices[i % 7];\n    return idx > 0 ? v / idx : v;\n  });\n\n  // Simple exponential smoothing on deseasonalised series (alpha=0.3)\n  const alpha = 0.3;\n  const s = [deseason[0]];\n  for (let i = 1; i < deseason.length; i++) s.push(alpha * deseason[i] + (1 - alpha) * s[i - 1]);\n  const lastLevel = s[s.length - 1];\n\n  // RMSE on deseasonalised\n  let errSum = 0;\n  for (let i = 1; i < historical.length; i++) {\n    errSum += (historical[i] - s[i - 1] * seasonalIndices[i % 7]) ** 2;\n  }\n  const rmse = Math.sqrt(errSum / (historical.length - 1));\n\n  // Forecast\n  const startDow = historical.length % 7;\n  const forecast = Array.from({ length: forecastDays }, (_, i) => {\n    return Math.max(0, Math.round(lastLevel * seasonalIndices[(startDow + i) % 7]));\n  });\n\n  return { historical, forecast, seasonalIndices, rmse };\n}\n\n// ─── Receipt ──────────────────────────────────────────────────────────────────\n\nexport interface TravelAnalysisResult {\n  emsr?: EMSRResult;\n  revpar?: RevPARResult;\n  overbooking?: OverbookingResult;\n  groupDisplacement?: GroupDisplacementResult;\n  forecast?: HotelForecastResult;\n  converged: true;\n}\n\nexport function buildTravelReceipt(\n  result: TravelAnalysisResult,\n  options?: RevenueReceiptOptions\n): DomainSimulationReceipt {\n  const violations: Array<{ criterion: string; message: string }> = [];\n\n  if (result.revpar && result.revpar.occupancyRate < 0.4) {\n    violations.push({\n      criterion: 'occupancy',\n      message: `Occupancy ${(result.revpar.occupancyRate * 100).toFixed(1)}% is critically low (<40%)`,\n    });\n  }\n  if (result.groupDisplacement && !result.groupDisplacement.profitable) {\n    violations.push({\n      criterion: 'group_displacement',\n      message: `Group booking net value is negative ($${result.groupDisplacement.netValue.toFixed(0)}) — displaces more valuable transient demand`,\n    });\n  }\n\n  return buildDomainSimulationReceipt({\n    plugin: 'travel-hospitality',\n    pluginVersion: '1.0.0',\n    runId: options?.runId ?? `travel-${Date.now().toString(36)}`,\n    solverConfig: { solverType: 'revenue-management', scale: 'property' },\n    resultSummary: {\n      revpar: result.revpar?.revpar ?? null,\n      occupancyRate: result.revpar?.occupancyRate ?? null,\n      emsrExpectedRevenue: result.emsr?.expectedRevenue ?? null,\n      overbookLevel: result.overbooking?.overbook ?? null,\n    },\n    cael: {\n      version: 'cael.v1',\n      event: 'travel_hospitality.revenue_management',\n      solverType: 'travel-hospitality.emsr-b',\n    },\n    acceptance: { accepted: violations.length === 0, violations },\n  });\n}\n","/**\n * Runtime integration for @holoscript/plugin-travel-hospitality.\n *\n * Bridges the previously dead-wired `revpar` trait into a behavioral\n * TraitHandler that the HoloScript runtime actually dispatches\n * (HoloScriptRuntime.registerTrait -> applyDirectives / updateTraits).\n *\n * Before this module the plugin declared trait NAMES only (pluginMeta.traits)\n * and exported the revenue-management solvers (revparAnalysis,\n * emsrYieldManagement, …), but nothing invoked a solver THROUGH the runtime —\n * the whole domain-plugin tier was built-but-dead-wired. This mirrors\n * government-civic-plugin's reference integration (civic_decision): it wires the\n * deterministic RevPAR analytic solver (`revparAnalysis`) behind the `revpar`\n * trait so the runtime's directive dispatch can run it. The remaining\n * travel-hospitality traits follow the same registrar shape.\n *\n * RevPAR (Revenue Per Available Room) = Room Revenue / Available Room-nights,\n * equivalently ADR × Occupancy (revparAnalysis computes both and they agree).\n */\nimport { registerPluginTraits } from '@holoscript/core/runtime';\nimport { revparAnalysis, type RevPARResult } from './revenuemanagement';\n\n/** Stable id for this plugin's trait ownership tagging. */\nexport const TRAVEL_HOSPITALITY_PLUGIN_ID = 'travel-hospitality' as const;\n\n/** Config carried by an orb's `@revpar` trait directive. */\nexport interface RevparTraitConfig {\n  /** Rooms available for the period. Required; absence/invalid emits `revpar_error`. */\n  availableRooms?: number;\n  /** Rooms occupied for the period. Required. */\n  occupiedRooms?: number;\n  /** Total room revenue for the period ($). Required. */\n  totalRevenue?: number;\n}\n\n/** Summary payload emitted on `revpar_solved`. */\nexport interface RevparSolvedEvent {\n  nodeId: string;\n  /** Revenue Per Available Room = ADR × occupancy ($). */\n  revpar: number;\n  /** Average Daily Rate ($). */\n  adr: number;\n  /** Occupancy rate [0,1]. */\n  occupancyRate: number;\n  /** Rooms available evaluated. */\n  availableRooms: number;\n  /** Rooms occupied evaluated. */\n  occupiedRooms: number;\n  /** Total room revenue evaluated ($). */\n  totalRevenue: number;\n}\n\n/**\n * Structural view of the runtime trait-handler contract. Matches\n * `@holoscript/core` TraitTypes.TraitHandler at the call sites the runtime\n * actually uses (onAttach / onUpdate receive the node, the directive config,\n * and a context exposing `emit`). Declared locally so the plugin stays\n * decoupled from core's full trait surface.\n */\nexport interface TraitDispatchContext {\n  emit: (event: string, payload?: unknown) => void;\n  setState?: (updates: Record<string, unknown>) => void;\n}\n\nexport interface RuntimeTraitHandler {\n  name: string;\n  onAttach?: (node: unknown, config: RevparTraitConfig, context: TraitDispatchContext) => void;\n  onUpdate?: (\n    node: unknown,\n    config: RevparTraitConfig,\n    context: TraitDispatchContext,\n    delta: number\n  ) => void;\n}\n\ninterface RevparNode {\n  id?: string;\n  name?: string;\n  properties?: Record<string, unknown>;\n  __revparResult?: RevPARResult;\n}\n\n/** Run the RevPAR solver on the directive config, write the result onto the node, and emit. */\nfunction solveOntoNode(\n  node: unknown,\n  config: RevparTraitConfig | undefined,\n  context: TraitDispatchContext\n): void {\n  const carrier = node as RevparNode;\n  const nodeId = carrier.id ?? carrier.name ?? 'unknown';\n  const availableRooms = config?.availableRooms;\n  const occupiedRooms = config?.occupiedRooms;\n  const totalRevenue = config?.totalRevenue;\n\n  if (\n    typeof availableRooms !== 'number' ||\n    typeof occupiedRooms !== 'number' ||\n    typeof totalRevenue !== 'number'\n  ) {\n    context.emit('revpar_error', {\n      nodeId,\n      error:\n        'revpar trait requires numeric config.availableRooms, config.occupiedRooms, and config.totalRevenue',\n    });\n    return;\n  }\n\n  try {\n    const result = revparAnalysis(availableRooms, occupiedRooms, totalRevenue);\n    carrier.__revparResult = result;\n    carrier.properties = {\n      ...(carrier.properties ?? {}),\n      revpar: result.revpar,\n      revparAdr: result.adr,\n      revparOccupancyRate: result.occupancyRate,\n    };\n    const summary: RevparSolvedEvent = {\n      nodeId,\n      revpar: result.revpar,\n      adr: result.adr,\n      occupancyRate: result.occupancyRate,\n      availableRooms: result.availableRooms,\n      occupiedRooms: result.occupiedRooms,\n      totalRevenue: result.totalRevenue,\n    };\n    context.setState?.({ [`revpar:${nodeId}`]: summary });\n    context.emit('revpar_solved', summary);\n  } catch (error) {\n    context.emit('revpar_error', {\n      nodeId,\n      error: error instanceof Error ? error.message : String(error),\n    });\n  }\n}\n\n/**\n * Behavioral handler for the travel-hospitality `revpar` trait. Runs the\n * deterministic RevPAR analytic solver whenever an orb carrying the trait is\n * attached (and on each per-frame update), writing the result onto the node and\n * emitting `revpar_solved` / `revpar_error`.\n */\nexport const revparHandler: RuntimeTraitHandler = {\n  name: 'revpar',\n  onAttach: (node, config, context) => solveOntoNode(node, config, context),\n  onUpdate: (node, config, context) => solveOntoNode(node, config, context),\n};\n\n/** A runtime that can register behavioral trait handlers. */\nexport interface TraitRegistrar {\n  registerTrait(name: string, handler: unknown): void;\n}\n\n/**\n * Register travel-hospitality behavioral trait handlers into a runtime that\n * exposes `registerTrait(name, handler)` — e.g. `@holoscript/core`\n * HoloScriptRuntime. This is the consumption path the dead-wired tier was\n * missing: after this call the runtime's directive dispatch (applyDirectives /\n * updateTraits) will invoke the RevPAR solver for `@revpar` orbs.\n */\nexport function registerTravelHospitalityTraitHandlers(registrar: TraitRegistrar): void {\n  registerPluginTraits(registrar, TRAVEL_HOSPITALITY_PLUGIN_ID, [revparHandler]);\n}\n","import { HoloScriptRuntime } from '@holoscript/core/runtime';\nimport { registerEnergyGridTraitHandlers } from '../../plugins/energy-grid-plugin/src/runtime';\nimport { registerFitnessWellnessTraitHandlers } from '../../plugins/fitness-wellness-plugin/src/runtime';\nimport { registerTravelHospitalityTraitHandlers } from '../../plugins/travel-hospitality-plugin/src/runtime';\n\ninterface TraitRegistrar {\n  registerTrait(name: string, handler: unknown): void;\n}\n\ninterface BuiltinDomainPluginEntry {\n  pluginId: string;\n  packageName: string;\n  aliases: string[];\n  traits: string[];\n  register: (registrar: TraitRegistrar) => void;\n}\n\nexport interface BuiltinDomainPluginInstallResult {\n  success: boolean;\n  pluginId?: string;\n  packageName?: string;\n  state?: 'enabled' | 'already_enabled';\n  registeredTraits?: string[];\n  runtime: 'HoloScriptRuntime';\n  alreadyInstalled?: boolean;\n  supportedPlugins?: string[];\n  error?: string;\n}\n\nconst BUILTIN_DOMAIN_PLUGINS: BuiltinDomainPluginEntry[] = [\n  {\n    pluginId: 'energy-grid',\n    packageName: '@holoscript/energy-grid-plugin',\n    aliases: ['energy-grid', 'energy-grid-plugin', '@holoscript/energy-grid-plugin'],\n    traits: ['power_flow'],\n    register: registerEnergyGridTraitHandlers,\n  },\n  {\n    pluginId: 'fitness-wellness',\n    packageName: '@holoscript/plugin-fitness-wellness',\n    aliases: ['fitness-wellness', 'fitness-wellness-plugin', '@holoscript/plugin-fitness-wellness'],\n    traits: ['one_rep_max'],\n    register: registerFitnessWellnessTraitHandlers,\n  },\n  {\n    pluginId: 'travel-hospitality',\n    packageName: '@holoscript/plugin-travel-hospitality',\n    aliases: [\n      'travel-hospitality',\n      'travel-hospitality-plugin',\n      '@holoscript/plugin-travel-hospitality',\n    ],\n    traits: ['revpar'],\n    register: registerTravelHospitalityTraitHandlers,\n  },\n];\n\nconst DOMAIN_PLUGIN_BY_ALIAS = new Map<string, BuiltinDomainPluginEntry>();\nfor (const entry of BUILTIN_DOMAIN_PLUGINS) {\n  for (const alias of entry.aliases) {\n    DOMAIN_PLUGIN_BY_ALIAS.set(alias.toLowerCase(), entry);\n  }\n}\n\nlet builtinDomainPluginRuntime: HoloScriptRuntime | null = null;\nconst installedBuiltinDomainPlugins = new Set<string>();\n\nexport function getBuiltinDomainPluginRuntime(): HoloScriptRuntime {\n  builtinDomainPluginRuntime ??= new HoloScriptRuntime();\n  return builtinDomainPluginRuntime;\n}\n\nexport function listBuiltinDomainPluginNames(): string[] {\n  return BUILTIN_DOMAIN_PLUGINS.map((entry) => entry.packageName);\n}\n\nexport function resetBuiltinDomainPluginRuntimeForTests(): void {\n  builtinDomainPluginRuntime = null;\n  installedBuiltinDomainPlugins.clear();\n}\n\nexport function installBuiltinDomainPlugin(pluginName: string): BuiltinDomainPluginInstallResult {\n  const normalized = pluginName.trim().toLowerCase();\n  const entry = DOMAIN_PLUGIN_BY_ALIAS.get(normalized);\n\n  if (!entry) {\n    return {\n      success: false,\n      runtime: 'HoloScriptRuntime',\n      supportedPlugins: listBuiltinDomainPluginNames(),\n      error: `Unsupported domain plugin: ${pluginName}`,\n    };\n  }\n\n  const runtime = getBuiltinDomainPluginRuntime();\n  const alreadyInstalled = installedBuiltinDomainPlugins.has(entry.pluginId);\n  if (!alreadyInstalled) {\n    entry.register(runtime);\n    installedBuiltinDomainPlugins.add(entry.pluginId);\n  }\n\n  return {\n    success: true,\n    pluginId: entry.pluginId,\n    packageName: entry.packageName,\n    state: alreadyInstalled ? 'already_enabled' : 'enabled',\n    runtime: 'HoloScriptRuntime',\n    registeredTraits: entry.traits,\n    alreadyInstalled,\n  };\n}\n","/**\n * @holoscript/mcp-server — Plugin Management MCP Tools\n *\n * 3 tools for installing, listing, and managing plugins.\n *\n * Part of HoloScript v5.7 \"Open Ecosystem\".\n */\n\nimport { Tool } from '@modelcontextprotocol/sdk/types.js';\nimport { readdirSync, readFileSync, existsSync } from 'fs';\nimport { dirname, join, resolve } from 'path';\nimport { fileURLToPath } from 'url';\nimport {\n  getPluginLifecycleManager,\n  type InstallPluginOptions,\n  type SandboxPermission,\n  type PluginLifecycleState,\n} from '@holoscript/core';\nimport { installBuiltinDomainPlugin, listBuiltinDomainPluginNames } from './domain-plugin-runtime';\n\n// ESM-safe __dirname (matches trait-categories-from-core.ts). tsup emits ESM, so the\n// native __dirname is absent; both src/ and dist/ sit at depth 2 under packages/mcp-server,\n// so ../../plugins resolves to packages/plugins in dev (vitest) and prod (dist) alike.\nconst __dirname = dirname(fileURLToPath(import.meta.url));\n\n// =============================================================================\n// TOOL DEFINITIONS\n// =============================================================================\n\nexport const pluginManagementTools: Tool[] = [\n  {\n    name: 'install_plugin',\n    description:\n      'Install a HoloScript plugin with sandboxed execution. Provide plugin metadata and code. Returns installation result.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        id: {\n          type: 'string',\n          description: 'Plugin identifier (kebab-case)',\n        },\n        name: {\n          type: 'string',\n          description: 'Plugin display name',\n        },\n        version: {\n          type: 'string',\n          description: 'Plugin version (semver)',\n        },\n        description: {\n          type: 'string',\n          description: 'Plugin description',\n        },\n        code: {\n          type: 'string',\n          description: 'Plugin JavaScript source code',\n        },\n        permissions: {\n          type: 'array',\n          items: { type: 'string' },\n          description: 'Permissions to grant (e.g. tool:register, event:emit)',\n        },\n      },\n      required: ['id', 'name', 'version', 'code'],\n    },\n  },\n  {\n    name: 'install_domain_plugin',\n    description:\n      'Install a built-in domain plugin by package name or alias and register its trait handlers in the MCP HoloScript runtime.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        plugin_name: {\n          type: 'string',\n          description: 'NPM package name of the plugin to load',\n        },\n      },\n      required: ['plugin_name'],\n    },\n  },\n  {\n    name: 'discover_plugins',\n    description:\n      'Discover available domain plugins by query or category. Scans packages/plugins/*/package.json at runtime (name, description, keywords) for a live plugin index.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        query: {\n          type: 'string',\n          description: 'Search intent',\n        },\n        category: {\n          type: 'string',\n          description: 'Optional category filter',\n        },\n      },\n      required: ['query'],\n    },\n  },\n  {\n    name: 'list_plugins',\n    description:\n      'List all installed plugins with their state, version, permissions, and registered tools.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        state: {\n          type: 'string',\n          description:\n            'Filter by lifecycle state (installed, verified, sandboxed, enabled, disabled)',\n        },\n      },\n    },\n  },\n  {\n    name: 'manage_plugin',\n    description:\n      'Manage a plugin lifecycle: enable, disable, or uninstall. Use action parameter to specify the operation.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        pluginId: {\n          type: 'string',\n          description: 'Plugin identifier',\n        },\n        action: {\n          type: 'string',\n          enum: ['enable', 'disable', 'uninstall'],\n          description: 'Lifecycle action to perform',\n        },\n      },\n      required: ['pluginId', 'action'],\n    },\n  },\n];\n\n// =============================================================================\n// HANDLER\n// =============================================================================\n\nexport async function handlePluginManagementTool(\n  name: string,\n  args: Record<string, unknown>\n): Promise<unknown> {\n  switch (name) {\n    case 'install_plugin':\n      return handleInstallPlugin(args);\n    case 'list_plugins':\n      return handleListPlugins(args);\n    case 'manage_plugin':\n      return handleManagePlugin(args);\n    case 'install_domain_plugin':\n      return handleInstallDomainPlugin(args);\n    case 'discover_plugins':\n      return handleDiscoverPlugins(args);\n    default:\n      throw new Error(`Unknown plugin management tool: ${name}`);\n  }\n}\n\n// =============================================================================\n// TOOL IMPLEMENTATIONS\n// =============================================================================\n\nasync function handleInstallPlugin(args: Record<string, unknown>) {\n  const manager = getPluginLifecycleManager();\n\n  const options: InstallPluginOptions = {\n    id: args.id as string,\n    name: (args.name as string) || (args.id as string),\n    version: (args.version as string) || '0.1.0',\n    description: (args.description as string) || '',\n    code: args.code as string,\n    permissions: (args.permissions as SandboxPermission[]) || ['tool:register', 'event:emit'],\n  };\n\n  try {\n    // Install\n    const plugin = manager.install(options);\n\n    // Skip signature verification for MCP-installed plugins\n    manager.skipVerification(plugin.id);\n\n    // Create sandbox\n    manager.sandbox(plugin.id);\n\n    // Enable (execute code)\n    const enableResult = await manager.enable(plugin.id);\n\n    if (!enableResult.success) {\n      return {\n        success: false,\n        pluginId: plugin.id,\n        state: 'error',\n        error: enableResult.error,\n      };\n    }\n\n    // Get registered tools\n    const sandbox = plugin.sandbox;\n    const tools = sandbox ? sandbox.getTools().map((t: any) => t.name) : [];\n\n    return {\n      success: true,\n      pluginId: plugin.id,\n      state: plugin.state,\n      version: plugin.version,\n      tools,\n      permissions: plugin.permissions,\n    };\n  } catch (err) {\n    return {\n      success: false,\n      pluginId: args.id,\n      error: err instanceof Error ? err.message : String(err),\n    };\n  }\n}\n\nfunction handleListPlugins(args: Record<string, unknown>) {\n  const manager = getPluginLifecycleManager();\n  const stateFilter = args.state as string | undefined;\n\n  const allPlugins = stateFilter\n    ? manager.getPluginsByState(stateFilter as PluginLifecycleState)\n    : manager.getAllPlugins();\n\n  const plugins = allPlugins.map((p: any) => ({\n    id: p.id,\n    name: p.name,\n    version: p.version,\n    description: p.description,\n    state: p.state,\n    permissions: p.permissions,\n    tools: p.sandbox ? p.sandbox.getTools().map((t: any) => t.name) : [],\n    installedAt: p.installedAt,\n    error: p.error,\n  }));\n\n  const stats = manager.getStats();\n\n  return {\n    plugins,\n    total: stats.total,\n    byState: stats.byState,\n    totalTools: stats.totalTools,\n  };\n}\n\nasync function handleManagePlugin(args: Record<string, unknown>) {\n  const manager = getPluginLifecycleManager();\n  const pluginId = args.pluginId as string;\n  const action = args.action as string;\n\n  try {\n    switch (action) {\n      case 'enable': {\n        const result = await manager.enable(pluginId);\n        const plugin = manager.getPlugin(pluginId);\n        return {\n          success: result.success,\n          pluginId,\n          action: 'enable',\n          state: plugin?.state,\n          error: result.error,\n        };\n      }\n      case 'disable': {\n        manager.disable(pluginId);\n        return { success: true, pluginId, action: 'disable', state: 'disabled' };\n      }\n      case 'uninstall': {\n        manager.uninstall(pluginId);\n        return { success: true, pluginId, action: 'uninstall', state: 'uninstalled' };\n      }\n      default:\n        return { success: false, pluginId, error: `Unknown action: ${action}` };\n    }\n  } catch (err) {\n    return {\n      success: false,\n      pluginId,\n      action,\n      error: err instanceof Error ? err.message : String(err),\n    };\n  }\n}\n\nasync function handleInstallDomainPlugin(args: Record<string, unknown>) {\n  const pluginName = args.plugin_name as string;\n  if (!pluginName || typeof pluginName !== 'string') {\n    return {\n      success: false,\n      pluginId: pluginName,\n      state: 'not_installed',\n      supportedPlugins: listBuiltinDomainPluginNames(),\n      error: 'plugin_name is required.',\n    };\n  }\n\n  return installBuiltinDomainPlugin(pluginName);\n}\n\ninterface DiscoveredPlugin {\n  id: string;\n  description: string;\n  category: string;\n  version?: string;\n}\n\nlet _pluginRegistryCache: DiscoveredPlugin[] | null = null;\n\n/**\n * Scan packages/plugins/* for package.json files and build a live plugin registry.\n * Cached per process (the on-disk plugin set is stable within a server lifetime).\n * Returns an empty registry with a distinct source when the directory is absent\n * (e.g. an unexpected CWD) instead of throwing.\n */\nfunction scanPluginRegistry(): { entries: DiscoveredPlugin[]; source: string } {\n  if (_pluginRegistryCache) return { entries: _pluginRegistryCache, source: 'filesystem-scan' };\n\n  const pluginsDir = resolve(__dirname, '../../plugins');\n  if (!existsSync(pluginsDir)) {\n    return { entries: [], source: 'filesystem-not-found' };\n  }\n\n  const entries: DiscoveredPlugin[] = [];\n  for (const dirent of readdirSync(pluginsDir, { withFileTypes: true })) {\n    if (!dirent.isDirectory()) continue;\n    const pkgPath = join(pluginsDir, dirent.name, 'package.json');\n    if (!existsSync(pkgPath)) continue;\n    try {\n      const pkg = JSON.parse(readFileSync(pkgPath, 'utf-8')) as {\n        name?: string;\n        description?: string;\n        version?: string;\n        keywords?: string[];\n      };\n      const keywords = Array.isArray(pkg.keywords) ? pkg.keywords : [];\n      const category = keywords.find((k) => k !== 'holoscript' && k !== 'plugin') ?? 'general';\n      entries.push({\n        id: pkg.name ?? `@holoscript/${dirent.name}`,\n        description: pkg.description ?? `HoloScript plugin: ${dirent.name}`,\n        category,\n        version: pkg.version,\n      });\n    } catch {\n      // Skip a single malformed package.json; keep scanning the rest (resilient).\n    }\n  }\n\n  _pluginRegistryCache = entries;\n  return { entries, source: 'filesystem-scan' };\n}\n\nasync function handleDiscoverPlugins(args: Record<string, unknown>) {\n  const query = ((args.query as string) || '').toLowerCase();\n  const category = args.category as string | undefined;\n\n  const { entries: registry, source } = scanPluginRegistry();\n\n  const results = registry.filter((p) => {\n    const matchesQuery =\n      query === '' ||\n      p.id.toLowerCase().includes(query) ||\n      p.description.toLowerCase().includes(query);\n    const matchesCategory = !category || p.category === category;\n    return matchesQuery && matchesCategory;\n  });\n\n  return {\n    success: true,\n    query,\n    count: results.length,\n    plugins: results,\n    registrySource: source,\n    totalRegistryEntries: registry.length,\n  };\n}\n","/**\n * holoshell-download-recovery-tools\n *\n * MCP + local tools for HoloShell partial download recovery.\n * Source: research/2026-05-21_holoshell-partial-download-recovery-room-prototype.md\n * Task: task_1779337565759_lny5 [holoshell-downloads][mcp] Add holoshell_download_recovery tools\n *\n * Tools implemented (matching the 5-lane prototype):\n * - holoshell_download_recovery_list\n * - holoshell_download_recovery_resume\n * - holoshell_download_recovery_quarantine\n * - holoshell_download_recovery_forensic_export\n * - holoshell_download_recovery_import_handoff\n *\n * Operates on local shelf (JSON receipt files or the framework holoshell-download-shelf-receipts shape).\n * All mutating actions require freshUserGesture (explicit consent flag in input).\n * Returns proper receipt envelopes + witness hashes where applicable.\n *\n * Hardware seat (grok-hardware) deliverable. Pairs with the RecoveryDock UI we wired in the sibling task.\n */\n\nimport { z } from 'zod';\nimport fs from 'fs';\nimport path from 'path';\nimport crypto from 'crypto';\nimport { Tool } from '@modelcontextprotocol/sdk/types.js';\n\nconst SHELF_DIR =\n  process.env.HOLOSHELL_DOWNLOAD_SHELF ||\n  path.join(\n    process.env.HOME || process.env.USERPROFILE || '.',\n    '.ai-ecosystem',\n    'holoshell',\n    'downloads'\n  );\n\nfunction ensureShelf() {\n  if (!fs.existsSync(SHELF_DIR)) fs.mkdirSync(SHELF_DIR, { recursive: true });\n}\n\nfunction loadReceipts(filterStatus?: string[]) {\n  ensureShelf();\n  const files = fs.readdirSync(SHELF_DIR).filter((f) => f.endsWith('.json'));\n  return files\n    .map((f) => {\n      try {\n        const data = JSON.parse(fs.readFileSync(path.join(SHELF_DIR, f), 'utf8'));\n        return { ...data, _file: f };\n      } catch {\n        return null;\n      }\n    })\n    .filter(Boolean)\n    .filter((r: any) => !filterStatus || filterStatus.includes(r.status));\n}\n\nfunction writeReceipt(receipt: any) {\n  ensureShelf();\n  const id = receipt.id || `rec-${Date.now()}`;\n  const file = path.join(SHELF_DIR, `${id}.json`);\n  fs.writeFileSync(\n    file,\n    JSON.stringify({ ...receipt, id, updatedAt: new Date().toISOString() }, null, 2)\n  );\n  return { id, file };\n}\n\nfunction freshGestureGuard(input: any) {\n  if (!input.freshUserGesture) {\n    throw new Error(\n      'freshUserGesture=true is required for this mutating action (user consent gate)'\n    );\n  }\n}\n\nexport const holoshellDownloadRecoveryList = {\n  name: 'holoshell_download_recovery_list',\n  description:\n    'List interrupted, quarantined, pending_consent, or complete downloads from the local HoloShell shelf. Returns receipt envelopes with substrateMetadata for hardware custody proofs.',\n  inputSchema: z.object({\n    statusFilter: z\n      .array(z.enum(['interrupted', 'quarantined', 'pending_consent', 'complete']))\n      .optional(),\n  }),\n  handler: async (input: any) => {\n    const receipts = loadReceipts(input.statusFilter);\n    return {\n      success: true,\n      count: receipts.length,\n      receipts,\n      shelfPath: SHELF_DIR,\n    };\n  },\n};\n\nexport const holoshellDownloadRecoveryResume = {\n  name: 'holoshell_download_recovery_resume',\n  description:\n    'Resume an interrupted download. Requires freshUserGesture. Produces ResumeReceipt + updates the shelf entry.',\n  inputSchema: z.object({\n    id: z.string(),\n    freshUserGesture: z.boolean(),\n    offset: z.number().optional(),\n  }),\n  handler: async (input: any) => {\n    freshGestureGuard(input);\n    const receipts = loadReceipts();\n    const rec = receipts.find((r: any) => r.id === input.id || r._file?.includes(input.id));\n    if (!rec) throw new Error('Receipt not found');\n    if (rec.status !== 'interrupted') throw new Error('Only interrupted downloads can be resumed');\n\n    const updated = {\n      ...rec,\n      status: 'pending_consent',\n      resume: { offset: input.offset ?? rec.bytesReceived, startedAt: new Date().toISOString() },\n    };\n    writeReceipt(updated);\n\n    const resumeReceipt = {\n      type: 'holoshell_download_resume_receipt',\n      downloadId: rec.id,\n      offset: input.offset ?? rec.bytesReceived,\n      consentTimestamp: new Date().toISOString(),\n      substrateMetadata: {\n        hardwareSeat: 'grok-hardware',\n        witnessHash: crypto.randomBytes(8).toString('hex'),\n      },\n    };\n\n    return { success: true, resumeReceipt, updatedShelfEntry: updated };\n  },\n};\n\nexport const holoshellDownloadRecoveryQuarantine = {\n  name: 'holoshell_download_recovery_quarantine',\n  description:\n    'Quarantine a suspect download. Requires freshUserGesture. Writes QuarantineReceipt with reason.',\n  inputSchema: z.object({\n    id: z.string(),\n    freshUserGesture: z.boolean(),\n    reason: z.enum(['exec', 'mime_mismatch', 'size_anomaly', 'provider_revoke', 'manual']),\n  }),\n  handler: async (input: any) => {\n    freshGestureGuard(input);\n    const receipts = loadReceipts();\n    const rec = receipts.find((r: any) => r.id === input.id || r._file?.includes(input.id));\n    if (!rec) throw new Error('Receipt not found');\n\n    const updated = { ...rec, status: 'quarantined', quarantineReason: input.reason };\n    writeReceipt(updated);\n\n    const quarantineReceipt = {\n      type: 'holoshell_download_quarantine_receipt',\n      downloadId: rec.id,\n      reason: input.reason,\n      timestamp: new Date().toISOString(),\n      substrateMetadata: { hardwareSeat: 'grok-hardware' },\n    };\n\n    return { success: true, quarantineReceipt, updatedShelfEntry: updated };\n  },\n};\n\nexport const holoshellDownloadRecoveryForensicExport = {\n  name: 'holoshell_download_recovery_forensic_export',\n  description:\n    'Export a quarantined download (or any) for forensic replay. Produces a signed bundle path + hash.',\n  inputSchema: z.object({\n    id: z.string(),\n    includeFullTrace: z.boolean().default(false),\n  }),\n  handler: async (input: any) => {\n    const receipts = loadReceipts();\n    const rec = receipts.find((r: any) => r.id === input.id || r._file?.includes(input.id));\n    if (!rec) throw new Error('Receipt not found');\n\n    const exportDir = path.join(SHELF_DIR, 'forensic-exports');\n    if (!fs.existsSync(exportDir)) fs.mkdirSync(exportDir, { recursive: true });\n\n    const bundleName = `forensic-${rec.id}-${Date.now()}.json`;\n    const bundlePath = path.join(exportDir, bundleName);\n    const bundle = {\n      originalReceipt: rec,\n      exportedAt: new Date().toISOString(),\n      hardwareSeat: 'grok-hardware',\n      fullTraceIncluded: input.includeFullTrace,\n    };\n    fs.writeFileSync(bundlePath, JSON.stringify(bundle, null, 2));\n\n    const hash = crypto.createHash('sha256').update(fs.readFileSync(bundlePath)).digest('hex');\n\n    return {\n      success: true,\n      bundlePath,\n      bundleHash: hash,\n      receipt: { type: 'holoshell_download_forensic_export_receipt', downloadId: rec.id, hash },\n    };\n  },\n};\n\nexport const holoshellDownloadRecoveryImportHandoff = {\n  name: 'holoshell_download_recovery_import_handoff',\n  description:\n    'Move a green/complete download to the main Import Shelf. Requires freshUserGesture. Produces ImportHandoffReceipt + witness.',\n  inputSchema: z.object({\n    id: z.string(),\n    freshUserGesture: z.boolean(),\n    targetShardOrAssetId: z.string().optional(),\n  }),\n  handler: async (input: any) => {\n    freshGestureGuard(input);\n    const receipts = loadReceipts();\n    const rec = receipts.find((r: any) => r.id === input.id || r._file?.includes(input.id));\n    if (!rec) throw new Error('Receipt not found');\n    if (rec.status !== 'complete' || rec.integrityBadge !== 'green') {\n      throw new Error('Only green complete downloads can be handed off to Import Shelf');\n    }\n\n    const handoffReceipt = {\n      type: 'holoshell_download_import_handoff_receipt',\n      downloadId: rec.id,\n      targetShardOrAssetId: input.targetShardOrAssetId || `import-${Date.now()}`,\n      provenanceLink: rec.lastChunkHash,\n      witnessHash: crypto.randomBytes(16).toString('hex'),\n      timestamp: new Date().toISOString(),\n      substrateMetadata: { hardwareSeat: 'grok-hardware', continuousParticipation: true },\n    };\n\n    // In real impl: move the file to the main shelf and mark as handed-off\n    const updated = { ...rec, status: 'handed_off', handoff: handoffReceipt };\n    writeReceipt(updated);\n\n    return { success: true, handoffReceipt, updatedShelfEntry: updated };\n  },\n};\n\nexport const holoshellDownloadRecoveryTools = [\n  holoshellDownloadRecoveryList,\n  holoshellDownloadRecoveryResume,\n  holoshellDownloadRecoveryQuarantine,\n  holoshellDownloadRecoveryForensicExport,\n  holoshellDownloadRecoveryImportHandoff,\n];\n\n/**\n * MCP Tool[] definitions (JSON Schema) for the public tool list in tools.ts.\n * The handler objects above carry zod inputSchema for internal validation;\n * these advertise the same surface to MCP clients (and the dispatch-health gate).\n */\nexport const holoshellDownloadRecoveryToolDefinitions: Tool[] = [\n  {\n    name: 'holoshell_download_recovery_list',\n    description:\n      'List interrupted, quarantined, pending_consent, or complete downloads from the local HoloShell shelf. Returns receipt envelopes with substrateMetadata for hardware custody proofs.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        statusFilter: {\n          type: 'array',\n          items: {\n            type: 'string',\n            enum: ['interrupted', 'quarantined', 'pending_consent', 'complete'],\n          },\n          description: 'Optional list of statuses to filter by.',\n        },\n      },\n    },\n  },\n  {\n    name: 'holoshell_download_recovery_resume',\n    description:\n      'Resume an interrupted download. Requires freshUserGesture. Produces ResumeReceipt + updates the shelf entry.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        id: { type: 'string', description: 'Download id to resume.' },\n        freshUserGesture: { type: 'boolean', description: 'Must be true — a fresh user gesture.' },\n        offset: { type: 'number', description: 'Optional byte offset to resume from.' },\n      },\n      required: ['id', 'freshUserGesture'],\n    },\n  },\n  {\n    name: 'holoshell_download_recovery_quarantine',\n    description:\n      'Quarantine a suspect download. Requires freshUserGesture. Writes QuarantineReceipt with reason.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        id: { type: 'string', description: 'Download id to quarantine.' },\n        freshUserGesture: { type: 'boolean', description: 'Must be true — a fresh user gesture.' },\n        reason: {\n          type: 'string',\n          enum: ['exec', 'mime_mismatch', 'size_anomaly', 'provider_revoke', 'manual'],\n          description: 'Quarantine reason.',\n        },\n      },\n      required: ['id', 'freshUserGesture', 'reason'],\n    },\n  },\n  {\n    name: 'holoshell_download_recovery_forensic_export',\n    description:\n      'Export a quarantined download (or any) for forensic replay. Produces a signed bundle path + hash.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        id: { type: 'string', description: 'Download id to export.' },\n        includeFullTrace: {\n          type: 'boolean',\n          description: 'Include the full trace in the bundle (default false).',\n        },\n      },\n      required: ['id'],\n    },\n  },\n  {\n    name: 'holoshell_download_recovery_import_handoff',\n    description:\n      'Move a green/complete download to the main Import Shelf. Requires freshUserGesture. Produces ImportHandoffReceipt + witness.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        id: { type: 'string', description: 'Download id to hand off.' },\n        freshUserGesture: { type: 'boolean', description: 'Must be true — a fresh user gesture.' },\n        targetShardOrAssetId: {\n          type: 'string',\n          description: 'Optional target shard or asset id.',\n        },\n      },\n      required: ['id', 'freshUserGesture'],\n    },\n  },\n];\n\nexport default holoshellDownloadRecoveryTools;\n","/**\n * MCP Economy Tools — v5.8 \"Live Economy\" + v6.1 \"Unified Budget\"\n *\n * 7 tools:\n *   v5.8: check_agent_budget, get_usage_summary, get_creator_earnings\n *   v6.1: optimize_scene_budget, validate_marketplace_pricing, get_unified_budget_state\n *   WS-9: settle_creator_payout\n */\n\nimport { Tool } from '@modelcontextprotocol/sdk/types.js';\nimport {\n  AgentBudgetEnforcer,\n  UsageMeter,\n  CreatorRevenueAggregator,\n  PaymentGateway,\n  UnifiedBudgetOptimizer,\n  DEFAULT_COST_FLOOR,\n} from '@holoscript/framework/economy';\nimport type {\n  BudgetState,\n  AgentUsageSummary,\n  CreatorEarnings,\n  UsagePeriod,\n  RevenuePeriod,\n  UnifiedOptimizerConfig,\n  TraitAllocation,\n  UnifiedBudgetState,\n  SettlementChain,\n  SettlementMode,\n  X402PaymentPayload,\n  X402SettlementResult,\n} from '@holoscript/framework/economy';\ntype ResourceUsageNode = any;\n\n// =============================================================================\n// SINGLETONS\n// =============================================================================\n\nlet budgetEnforcer: AgentBudgetEnforcer | null = null;\nlet usageMeter: UsageMeter | null = null;\nlet revenueAggregator: CreatorRevenueAggregator | null = null;\n\nfunction getBudgetEnforcer(): AgentBudgetEnforcer {\n  if (!budgetEnforcer) budgetEnforcer = new AgentBudgetEnforcer();\n  return budgetEnforcer;\n}\n\nfunction getUsageMeter(): UsageMeter {\n  if (!usageMeter) usageMeter = new UsageMeter();\n  return usageMeter;\n}\n\nfunction getRevenueAggregator(): CreatorRevenueAggregator {\n  if (!revenueAggregator) revenueAggregator = new CreatorRevenueAggregator();\n  return revenueAggregator;\n}\n\nexport function resetEconomySingletons(): void {\n  budgetEnforcer = null;\n  usageMeter = null;\n  revenueAggregator = null;\n}\n\nexport interface ProtocolCreatorRevenueInput {\n  creatorId: string;\n  contentHash: string;\n  grossAmount: number;\n  collectorId: string;\n  ledgerEntryId?: string;\n}\n\nexport function recordProtocolCreatorRevenue({\n  creatorId,\n  contentHash,\n  grossAmount,\n  collectorId,\n  ledgerEntryId,\n}: ProtocolCreatorRevenueInput) {\n  const aggregator = getRevenueAggregator();\n  return aggregator.recordRevenue(\n    creatorId,\n    `protocol:${contentHash}`,\n    grossAmount,\n    collectorId,\n    ledgerEntryId\n  );\n}\n\n// =============================================================================\n// TOOL DEFINITIONS\n// =============================================================================\n\nexport const economyTools: Tool[] = [\n  {\n    name: 'check_agent_budget',\n    description:\n      'Check budget status for an agent. Returns spent, remaining, limit, enforcement mode, and circuit breaker state.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        agentId: { type: 'string', description: 'Agent ID to check budget for' },\n        amount: {\n          type: 'number',\n          description: 'Optional: check if this spend amount would be authorized',\n        },\n      },\n      required: ['agentId'],\n    },\n  },\n  {\n    name: 'get_usage_summary',\n    description:\n      'Get usage summary for an agent or globally. Shows per-tool cost breakdown, free-tier status, and top tools.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        agentId: { type: 'string', description: 'Agent ID (omit for global summary)' },\n        period: {\n          type: 'string',\n          enum: ['hourly', 'daily', 'monthly'],\n          description: 'Aggregation period (default: monthly)',\n        },\n        topToolsLimit: {\n          type: 'number',\n          description: 'Number of top tools to return (default: 10)',\n        },\n      },\n    },\n  },\n  {\n    name: 'get_creator_earnings',\n    description:\n      'Get earnings for a plugin creator. Shows revenue by plugin, platform fees, payout eligibility, and payout history.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        creatorId: { type: 'string', description: 'Creator ID to get earnings for' },\n        period: {\n          type: 'string',\n          enum: ['daily', 'weekly', 'monthly', 'all-time'],\n          description: 'Aggregation period (default: monthly)',\n        },\n      },\n      required: ['creatorId'],\n    },\n  },\n  {\n    name: 'settle_creator_payout',\n    description:\n      'Settle an unpaid creator earning through the x402 micro-payment path, record the payout, and return a receipt. Requires an X-PAYMENT header or decoded x402 payment payload; on-chain settlement is disabled by default so one-cent test payouts stay in the micro-ledger.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        creatorId: { type: 'string', description: 'Creator ID with unpaid earnings' },\n        recipientWallet: {\n          type: 'string',\n          description: 'Seat wallet receiving the payout; must match the x402 authorization recipient',\n        },\n        amountBaseUnits: {\n          type: 'number',\n          description: 'USDC base units to pay out (10000 = $0.01). Defaults to unpaid net earnings.',\n        },\n        period: {\n          type: 'string',\n          enum: ['daily', 'weekly', 'monthly', 'all-time'],\n          description: 'Earnings period to settle (default: all-time)',\n        },\n        chain: {\n          type: 'string',\n          enum: ['base', 'base-sepolia', 'solana', 'solana-devnet'],\n          description: 'x402 settlement chain (default: base-sepolia)',\n        },\n        xPaymentHeader: {\n          type: 'string',\n          description: 'Base64-encoded X-PAYMENT header. Alternative to paymentPayload.',\n        },\n        paymentPayload: {\n          type: 'object',\n          description: 'Decoded x402 payment payload. Alternative to xPaymentHeader.',\n        },\n        resource: {\n          type: 'string',\n          description: 'Receipt resource label (default: creator-payout:<creatorId>)',\n        },\n        allowOnChain: {\n          type: 'boolean',\n          description: 'Opt in to on-chain settlement for amounts at/above the micro threshold.',\n        },\n      },\n      required: ['creatorId', 'recipientWallet'],\n    },\n  },\n\n  // ── Unified Budget Tools (v6.1) ──\n\n  {\n    name: 'optimize_scene_budget',\n    description:\n      \"Run equimarginal allocation on a scene's traits against a platform budget. Returns which traits to include, LOD levels, and what to shed — sorted by value/cost ratio so the most efficient traits survive.\",\n    inputSchema: {\n      type: 'object',\n      properties: {\n        platform: {\n          type: 'string',\n          enum: ['quest3', 'desktop-vr', 'webgpu', 'mobile-ar'],\n          description: 'Target platform for resource limits',\n        },\n        nodes: {\n          type: 'array',\n          items: {\n            type: 'object',\n            properties: {\n              name: { type: 'string', description: 'Object name (e.g., \"Player\", \"Tree\")' },\n              traits: {\n                type: 'array',\n                items: { type: 'string' },\n                description: 'Trait names (e.g., [\"@mesh\", \"@particle\"])',\n              },\n              count: { type: 'number', description: 'Instance count (default: 1)' },\n              calls: {\n                type: 'array',\n                items: { type: 'string' },\n                description: 'Built-in function calls (e.g., [\"spawn\", \"playSound\"])',\n              },\n            },\n            required: ['name', 'traits'],\n          },\n          description: 'Scene objects with their traits and instance counts',\n        },\n        maxLOD: { type: 'number', description: 'Maximum LOD level to consider (default: 4)' },\n        economicBudget: {\n          type: 'number',\n          description: 'Economic budget in USDC base units (optional)',\n        },\n        economicSpent: {\n          type: 'number',\n          description: 'Economic spend so far in USDC base units (optional)',\n        },\n      },\n      required: ['platform', 'nodes'],\n    },\n  },\n  {\n    name: 'validate_marketplace_pricing',\n    description:\n      'Validate that a marketplace trait listing price meets the resource cost floor. Prevents economic denial-of-rendering attacks where a cheap trait consumes massive GPU resources.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        traitName: { type: 'string', description: 'Trait name to validate (e.g., \"@gaussian\")' },\n        listPrice: {\n          type: 'number',\n          description: 'Proposed listing price in USDC base units (6 decimals, so 1000000 = $1.00)',\n        },\n        instanceCount: { type: 'number', description: 'Expected instance count (default: 1)' },\n        platform: {\n          type: 'string',\n          enum: ['quest3', 'desktop-vr', 'webgpu', 'mobile-ar'],\n          description: 'Target platform (default: quest3)',\n        },\n      },\n      required: ['traitName', 'listPrice'],\n    },\n  },\n  {\n    name: 'get_unified_budget_state',\n    description:\n      'Get a unified view of budget pressure across economy + rendering for an agent. Returns economic pressure, resource pressure per category, suggested LOD, and shed candidates. NOTE: this is per-agent economic + render-resource (triangle/draw-call) budget — it does NOT report live fleet/GPU rental spend; for that use the vast spend ledger (scripts/reconcile-vast-ledger.mjs).',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        agentId: { type: 'string', description: 'Agent identifier' },\n        platform: {\n          type: 'string',\n          enum: ['quest3', 'desktop-vr', 'webgpu', 'mobile-ar'],\n          description: 'Target platform (default: quest3)',\n        },\n        nodes: {\n          type: 'array',\n          items: {\n            type: 'object',\n            properties: {\n              name: { type: 'string', description: 'Object name' },\n              traits: { type: 'array', items: { type: 'string' }, description: 'Trait names' },\n              count: { type: 'number', description: 'Instance count (default: 1)' },\n              calls: {\n                type: 'array',\n                items: { type: 'string' },\n                description: 'Built-in function calls',\n              },\n            },\n            required: ['name', 'traits'],\n          },\n          description: 'Scene objects with their traits',\n        },\n        economicBudget: { type: 'number', description: 'Economic budget in USDC base units' },\n        economicSpent: { type: 'number', description: 'Economic spend so far in USDC base units' },\n      },\n      required: ['agentId'],\n    },\n  },\n];\n\n// =============================================================================\n// HANDLER\n// =============================================================================\n\nexport async function handleEconomyTool(\n  name: string,\n  args: Record<string, unknown>\n): Promise<unknown> {\n  switch (name) {\n    case 'check_agent_budget':\n      return handleCheckAgentBudget(args);\n    case 'get_usage_summary':\n      return handleGetUsageSummary(args);\n    case 'get_creator_earnings':\n      return handleGetCreatorEarnings(args);\n    case 'settle_creator_payout':\n      return handleSettleCreatorPayout(args);\n    case 'optimize_scene_budget':\n      return handleOptimizeSceneBudget(args);\n    case 'validate_marketplace_pricing':\n      return handleValidateMarketplacePricing(args);\n    case 'get_unified_budget_state':\n      return handleGetUnifiedBudgetState(args);\n    default:\n      throw new Error(`Unknown economy tool: ${name}`);\n  }\n}\n\n// =============================================================================\n// IMPLEMENTATIONS\n// =============================================================================\n\nfunction handleCheckAgentBudget(args: Record<string, unknown>): {\n  agentId: string;\n  state: BudgetState | null;\n  authorization?: {\n    authorized: boolean;\n    reason?: string;\n    warning?: boolean;\n    warningMessage?: string;\n  };\n} {\n  const agentId = args.agentId as string;\n  const enforcer = getBudgetEnforcer();\n\n  const state = enforcer.getState(agentId) ?? null;\n\n  // If amount is provided, check authorization\n  if (args.amount !== undefined) {\n    const amount = args.amount as number;\n    const auth = enforcer.authorize(agentId, amount);\n    return {\n      agentId,\n      state: auth.state,\n      authorization: {\n        authorized: auth.authorized,\n        reason: auth.reason,\n        warning: auth.warning,\n        warningMessage: auth.warningMessage,\n      },\n    };\n  }\n\n  return { agentId, state };\n}\n\nfunction handleGetUsageSummary(args: Record<string, unknown>): {\n  agentId?: string;\n  period: string;\n  summary: {\n    totalCalls: number;\n    totalCost: number;\n    freeTierCalls: number;\n    paidCalls: number;\n    paidCost: number;\n  };\n  topTools?: Array<{ toolId: string; calls: number; cost: number }>;\n  freeTierRemaining?: number;\n} {\n  const meter = getUsageMeter();\n  const period = (args.period as UsagePeriod) ?? 'monthly';\n  const topToolsLimit = (args.topToolsLimit as number) ?? 10;\n  const agentId = args.agentId as string | undefined;\n\n  if (agentId) {\n    const usage: AgentUsageSummary = meter.getAgentUsage(agentId, period);\n    return {\n      agentId,\n      period,\n      summary: {\n        totalCalls: usage.total.totalCalls,\n        totalCost: usage.total.totalCost,\n        freeTierCalls: usage.total.freeTierCalls,\n        paidCalls: usage.total.paidCalls,\n        paidCost: usage.total.paidCost,\n      },\n      freeTierRemaining: usage.freeTierRemaining,\n    };\n  }\n\n  // Global summary\n  const global = meter.getGlobalUsage(period);\n  const topTools = meter.getTopTools(period, topToolsLimit);\n\n  return {\n    period,\n    summary: {\n      totalCalls: global.totalCalls,\n      totalCost: global.totalCost,\n      freeTierCalls: global.freeTierCalls,\n      paidCalls: global.paidCalls,\n      paidCost: global.paidCost,\n    },\n    topTools,\n  };\n}\n\nfunction handleGetCreatorEarnings(args: Record<string, unknown>): {\n  creatorId: string;\n  period: string;\n  earnings: {\n    totalGross: number;\n    totalFees: number;\n    totalNet: number;\n    eventCount: number;\n    byPlugin: Array<{\n      pluginId: string;\n      grossAmount: number;\n      netAmount: number;\n      eventCount: number;\n      uniquePayers: number;\n    }>;\n  };\n  payouts: Array<{\n    id: string;\n    amount: number;\n    method: string;\n    status: string;\n    paidAt: string;\n    transactionHash?: string;\n  }>;\n  platformFeeRate: number;\n} {\n  const aggregator = getRevenueAggregator();\n  const creatorId = args.creatorId as string;\n  const period = (args.period as RevenuePeriod) ?? 'monthly';\n\n  const earnings: CreatorEarnings = aggregator.getCreatorEarnings(creatorId, period);\n  const payouts = aggregator.getCreatorPayouts(creatorId, period);\n\n  const byPlugin = [...earnings.byPlugin.entries()].map(([pluginId, rev]) => ({\n    pluginId,\n    grossAmount: rev.grossAmount,\n    netAmount: rev.netAmount,\n    eventCount: rev.eventCount,\n    uniquePayers: rev.uniquePayers.size,\n  }));\n\n  return {\n    creatorId,\n    period,\n    earnings: {\n      totalGross: earnings.totalGross,\n      totalFees: earnings.totalFees,\n      totalNet: earnings.totalNet,\n      eventCount: earnings.eventCount,\n      byPlugin,\n    },\n    payouts: payouts.map((p: any) => ({\n      id: p.id,\n      amount: p.amount,\n      method: p.method,\n      status: p.status,\n      paidAt: p.paidAt,\n      transactionHash: p.transactionHash,\n    })),\n    platformFeeRate: aggregator.getPlatformFeeRate(),\n  };\n}\n\ntype EconomyError = { status: 'error'; error: string; message: string };\n\ntype CreatorPayoutSettlementReceipt = {\n  schema: 'holoscript.creator-payout.receipt.v1';\n  tool: 'settle_creator_payout';\n  creatorId: string;\n  period: RevenuePeriod;\n  amountBaseUnits: number;\n  amountUSDC: number;\n  recipientWallet: string;\n  resource: string;\n  unpaidBefore: number;\n  earningsBefore: {\n    totalGross: number;\n    totalFees: number;\n    totalNet: number;\n    eventCount: number;\n  };\n  settlement: Pick<\n    X402SettlementResult,\n    'success' | 'transaction' | 'network' | 'payer' | 'errorReason' | 'mode' | 'settledAt'\n  >;\n  payoutRecord: {\n    id: string;\n    amount: number;\n    method: string;\n    status: string;\n    paidAt: string;\n    transactionHash?: string;\n  };\n  x402: {\n    chain: SettlementChain;\n    settlementMode: SettlementMode;\n    microPaymentThresholdBaseUnits: number;\n    signatureVerification: string;\n  };\n};\n\nfunction stringParam(\n  value: unknown,\n  fieldName: string\n): string | EconomyError {\n  if (typeof value !== 'string' || value.trim() === '') {\n    return {\n      status: 'error',\n      error: 'INVALID_PARAMS',\n      message: `${fieldName} must be a non-empty string`,\n    };\n  }\n  return value;\n}\n\nfunction parseRevenuePeriod(value: unknown, fallback: RevenuePeriod): RevenuePeriod | EconomyError {\n  if (value === undefined || value === null) return fallback;\n  if (value === 'daily' || value === 'weekly' || value === 'monthly' || value === 'all-time') {\n    return value;\n  }\n  return {\n    status: 'error',\n    error: 'INVALID_PARAMS',\n    message: 'period must be one of daily, weekly, monthly, all-time',\n  };\n}\n\nfunction parseSettlementChain(value: unknown, fallback: SettlementChain): SettlementChain | EconomyError {\n  if (value === undefined || value === null) return fallback;\n  if (value === 'base' || value === 'base-sepolia' || value === 'solana' || value === 'solana-devnet') {\n    return value;\n  }\n  return {\n    status: 'error',\n    error: 'INVALID_PARAMS',\n    message: 'chain must be one of base, base-sepolia, solana, solana-devnet',\n  };\n}\n\nfunction parseAmountBaseUnits(value: unknown, fallback: number): number | EconomyError {\n  if (value === undefined || value === null) return fallback;\n  if (typeof value !== 'number' || !Number.isSafeInteger(value) || value <= 0) {\n    return {\n      status: 'error',\n      error: 'INVALID_PARAMS',\n      message: 'amountBaseUnits must be a positive safe integer',\n    };\n  }\n  return value;\n}\n\nfunction completedPayoutTotal(\n  payouts: ReturnType<CreatorRevenueAggregator['getCreatorPayouts']>\n): number {\n  return payouts.reduce((sum, payout) => sum + (payout.status === 'completed' ? payout.amount : 0), 0);\n}\n\nasync function handleSettleCreatorPayout(\n  args: Record<string, unknown>\n): Promise<\n  | {\n      status: 'success';\n      creatorId: string;\n      receipt: CreatorPayoutSettlementReceipt;\n    }\n  | {\n      status: 'settlement_failed';\n      creatorId: string;\n      settlement: X402SettlementResult;\n      message: string;\n    }\n  | EconomyError\n> {\n  const creatorId = stringParam(args.creatorId, 'creatorId');\n  if (typeof creatorId !== 'string') return creatorId;\n\n  const recipientWallet = stringParam(args.recipientWallet, 'recipientWallet');\n  if (typeof recipientWallet !== 'string') return recipientWallet;\n\n  const period = parseRevenuePeriod(args.period, 'all-time');\n  if (typeof period !== 'string') return period;\n\n  const chain = parseSettlementChain(args.chain, 'base-sepolia');\n  if (typeof chain !== 'string') return chain;\n\n  const aggregator = getRevenueAggregator();\n  const earnings = aggregator.getCreatorEarnings(creatorId, period);\n  const priorPayouts = aggregator.getCreatorPayouts(creatorId, period);\n  const unpaidBefore = earnings.totalNet - completedPayoutTotal(priorPayouts);\n  const amountBaseUnits = parseAmountBaseUnits(args.amountBaseUnits, unpaidBefore);\n  if (typeof amountBaseUnits !== 'number') return amountBaseUnits;\n\n  if (amountBaseUnits > unpaidBefore) {\n    return {\n      status: 'error',\n      error: 'INSUFFICIENT_EARNINGS',\n      message: `creator ${creatorId} has ${unpaidBefore} unpaid base units; requested ${amountBaseUnits}`,\n    };\n  }\n\n  const microPaymentThresholdBaseUnits = 100_000;\n  if (args.allowOnChain !== true && amountBaseUnits >= microPaymentThresholdBaseUnits) {\n    return {\n      status: 'error',\n      error: 'ON_CHAIN_DISABLED',\n      message:\n        'settle_creator_payout defaults to x402 micro-ledger settlement only; pass allowOnChain=true to use an external facilitator for larger amounts',\n    };\n  }\n\n  const payment =\n    typeof args.xPaymentHeader === 'string'\n      ? args.xPaymentHeader\n      : typeof args.paymentPayload === 'object' && args.paymentPayload !== null\n        ? (args.paymentPayload as X402PaymentPayload)\n        : null;\n\n  if (!payment) {\n    return {\n      status: 'error',\n      error: 'MISSING_X402_PAYMENT',\n      message: 'xPaymentHeader or paymentPayload is required to settle a creator payout',\n    };\n  }\n\n  const resource =\n    typeof args.resource === 'string' && args.resource.trim() !== ''\n      ? args.resource\n      : `creator-payout:${creatorId}`;\n\n  const gateway = new PaymentGateway({\n    recipientAddress: recipientWallet,\n    chain,\n    microPaymentThreshold: microPaymentThresholdBaseUnits,\n    optimisticExecution: false,\n  });\n\n  const settlement = await gateway.settlePayment(payment, resource, String(amountBaseUnits));\n  gateway.dispose();\n\n  if (!settlement.success) {\n    return {\n      status: 'settlement_failed',\n      creatorId,\n      settlement,\n      message: settlement.errorReason ?? 'x402 settlement failed',\n    };\n  }\n\n  const payoutRecord = aggregator.recordPayout(\n    creatorId,\n    amountBaseUnits,\n    settlement.mode === 'in_memory' ? 'batch_settlement' : 'usdc_transfer',\n    settlement.transaction ?? undefined\n  );\n\n  return {\n    status: 'success',\n    creatorId,\n    receipt: {\n      schema: 'holoscript.creator-payout.receipt.v1',\n      tool: 'settle_creator_payout',\n      creatorId,\n      period,\n      amountBaseUnits,\n      amountUSDC: amountBaseUnits / 1_000_000,\n      recipientWallet,\n      resource,\n      unpaidBefore,\n      earningsBefore: {\n        totalGross: earnings.totalGross,\n        totalFees: earnings.totalFees,\n        totalNet: earnings.totalNet,\n        eventCount: earnings.eventCount,\n      },\n      settlement: {\n        success: settlement.success,\n        transaction: settlement.transaction,\n        network: settlement.network,\n        payer: settlement.payer,\n        errorReason: settlement.errorReason,\n        mode: settlement.mode,\n        settledAt: settlement.settledAt,\n      },\n      payoutRecord: {\n        id: payoutRecord.id,\n        amount: payoutRecord.amount,\n        method: payoutRecord.method,\n        status: payoutRecord.status,\n        paidAt: payoutRecord.paidAt,\n        transactionHash: payoutRecord.transactionHash,\n      },\n      x402: {\n        chain,\n        settlementMode: settlement.mode,\n        microPaymentThresholdBaseUnits,\n        signatureVerification:\n          settlement.mode === 'in_memory'\n            ? 'structural x402 payload verified by X402Facilitator; no external facilitator call for micro-ledger settlement'\n            : 'external facilitator settlement',\n      },\n    },\n  };\n}\n\n// =============================================================================\n// UNIFIED BUDGET TOOLS (v6.1)\n// =============================================================================\n\nfunction parseNodes(raw: unknown): ResourceUsageNode[] {\n  if (!Array.isArray(raw)) return [];\n  return raw.map((n: Record<string, unknown>) => ({\n    name: (n.name as string) || 'unnamed',\n    traits: Array.isArray(n.traits) ? (n.traits as string[]) : [],\n    count: typeof n.count === 'number' ? n.count : 1,\n    calls: Array.isArray(n.calls) ? (n.calls as string[]) : [],\n  }));\n}\n\nfunction handleOptimizeSceneBudget(args: Record<string, unknown>): {\n  platform: string;\n  allocations: TraitAllocation[];\n  summary: {\n    totalTraits: number;\n    includedTraits: number;\n    excludedTraits: number;\n    degradedTraits: number;\n  };\n} {\n  const platform = (args.platform as string) || 'quest3';\n  const nodes = parseNodes(args.nodes);\n  const maxLOD = typeof args.maxLOD === 'number' ? args.maxLOD : 4;\n\n  const config: UnifiedOptimizerConfig = {\n    platform,\n    costFloor: DEFAULT_COST_FLOOR,\n    economicBudget: typeof args.economicBudget === 'number' ? args.economicBudget : undefined,\n    economicSpent: typeof args.economicSpent === 'number' ? args.economicSpent : undefined,\n  };\n\n  const optimizer = new UnifiedBudgetOptimizer(config);\n  const allocations = optimizer.allocate(nodes, maxLOD);\n\n  const included = allocations.filter((a: any) => a.included);\n  const excluded = allocations.filter((a: any) => !a.included);\n  const degraded = included.filter((a: any) => a.lodLevel > 0);\n\n  return {\n    platform,\n    allocations,\n    summary: {\n      totalTraits: allocations.length,\n      includedTraits: included.length,\n      excludedTraits: excluded.length,\n      degradedTraits: degraded.length,\n    },\n  };\n}\n\nfunction handleValidateMarketplacePricing(args: Record<string, unknown>): {\n  traitName: string;\n  listPrice: number;\n  instanceCount: number;\n  valid: boolean;\n  floor: number;\n  deficit: number;\n  message: string;\n  costBreakdown: {\n    baseFee: number;\n    resourceCost: number;\n  };\n} {\n  const traitName = args.traitName as string;\n  const listPrice = args.listPrice as number;\n  const instanceCount = typeof args.instanceCount === 'number' ? args.instanceCount : 1;\n  const platform = (args.platform as string) || 'quest3';\n\n  const optimizer = new UnifiedBudgetOptimizer({\n    platform,\n    costFloor: DEFAULT_COST_FLOOR,\n  });\n\n  const result = optimizer.validateMarketplacePrice(traitName, listPrice, instanceCount);\n  const baseFee = DEFAULT_COST_FLOOR.baseFee;\n\n  return {\n    traitName,\n    listPrice,\n    instanceCount,\n    valid: result.valid,\n    floor: result.floor,\n    deficit: result.deficit,\n    message: result.message,\n    costBreakdown: {\n      baseFee,\n      resourceCost: result.floor - baseFee,\n    },\n  };\n}\n\nfunction handleGetUnifiedBudgetState(args: Record<string, unknown>): UnifiedBudgetState {\n  const agentId = args.agentId as string;\n  const platform = (args.platform as string) || 'quest3';\n  const nodes = parseNodes(args.nodes);\n  const economicBudget = typeof args.economicBudget === 'number' ? args.economicBudget : undefined;\n  const economicSpent = typeof args.economicSpent === 'number' ? args.economicSpent : undefined;\n\n  const optimizer = new UnifiedBudgetOptimizer({\n    platform,\n    costFloor: DEFAULT_COST_FLOOR,\n    economicBudget,\n    economicSpent,\n  });\n\n  return optimizer.getUnifiedState(agentId, nodes, economicSpent, economicBudget);\n}\n","/**\n * API Documentation Generator — MCP tool reference documentation\n *\n * Generates API reference from MCP tool definitions (100+ tools).\n * Outputs markdown and JSON, grouped by category.\n * Includes usage examples extracted from tool schemas.\n *\n * Part of HoloScript v5.9 \"Developer Portal\".\n *\n * @version 1.0.0\n */\n\nimport type { Tool } from '@modelcontextprotocol/sdk/types.js';\n\n// =============================================================================\n// TYPES\n// =============================================================================\n\n/**\n * A documented tool entry.\n */\nexport interface ToolDoc {\n  /** Tool name */\n  name: string;\n  /** Description */\n  description: string;\n  /** Category */\n  category: string;\n  /** Input parameters */\n  parameters: ParameterDoc[];\n  /** Whether the tool requires authentication */\n  requiresAuth: boolean;\n  /** Usage example (JSON) */\n  example?: string;\n}\n\n/**\n * A documented parameter.\n */\nexport interface ParameterDoc {\n  /** Parameter name */\n  name: string;\n  /** Type (string, number, boolean, object, array) */\n  type: string;\n  /** Description */\n  description: string;\n  /** Whether this parameter is required */\n  required: boolean;\n  /** Default value if any */\n  defaultValue?: unknown;\n  /** Enum values if any */\n  enumValues?: string[];\n}\n\n/**\n * API reference output.\n */\nexport interface APIReference {\n  /** Generated at timestamp */\n  generatedAt: string;\n  /** Total tool count */\n  totalTools: number;\n  /** Categories with their tools */\n  categories: CategoryDoc[];\n  /** Version */\n  version: string;\n}\n\n/**\n * A category of tools.\n */\nexport interface CategoryDoc {\n  /** Category name */\n  name: string;\n  /** Category description */\n  description: string;\n  /** Tools in this category */\n  tools: ToolDoc[];\n}\n\n/**\n * Generator configuration.\n */\nexport interface APIDocsGeneratorConfig {\n  /** Version string */\n  version?: string;\n  /** Category rules: tool name prefix → category */\n  categoryRules?: Record<string, string>;\n}\n\n// =============================================================================\n// DEFAULT CATEGORY RULES\n// =============================================================================\n\nconst DEFAULT_CATEGORY_RULES: Record<string, string> = {\n  parse_: 'Parsing & Validation',\n  validate_: 'Parsing & Validation',\n  list_: 'Parsing & Validation',\n  explain_: 'Code Intelligence',\n  suggest_: 'Code Intelligence',\n  generate_: 'Code Generation',\n  render_: 'Rendering',\n  create_share: 'Sharing',\n  convert_: 'Conversion',\n  analyze_: 'Analysis',\n  graph_: 'Graph Analysis',\n  get_graph: 'Graph Analysis',\n  ide_: 'IDE Integration',\n  brittney_: 'AI Assistant',\n  text_to_: 'Content Creation',\n  browser_: 'Browser Control',\n  codebase_: 'Codebase',\n  graphrag_: 'Knowledge Graph',\n  self_improve: 'Self Improvement',\n  gltf_: 'GLTF Import',\n  edit_holo: 'Editing',\n  absorb_: 'Absorb Service',\n  service_contract: 'Service Contracts',\n  discover_: 'Agent Orchestration',\n  delegate_: 'Agent Orchestration',\n  get_task_: 'Agent Orchestration',\n  compose_: 'Agent Orchestration',\n  execute_: 'Agent Orchestration',\n  query_traces: 'Observability',\n  export_traces: 'Observability',\n  get_agent_health: 'Observability',\n  get_metrics: 'Observability',\n  holo_service_scaffold: 'Observability',\n  install_plugin: 'Plugin Management',\n  list_plugins: 'Plugin Management',\n  manage_plugin: 'Plugin Management',\n  check_agent_budget: 'Economy',\n  get_usage_summary: 'Economy',\n  get_creator_earnings: 'Economy',\n  settle_creator_payout: 'Economy',\n  get_api_reference: 'Developer Tools',\n  serve_preview: 'Developer Tools',\n  get_workspace_info: 'Developer Tools',\n  inspect_trace_waterfall: 'Developer Tools',\n  get_dev_dashboard_state: 'Developer Tools',\n};\n\n// =============================================================================\n// GENERATOR\n// =============================================================================\n\nexport class APIDocsGenerator {\n  private config: Required<APIDocsGeneratorConfig>;\n\n  constructor(config?: APIDocsGeneratorConfig) {\n    this.config = {\n      version: config?.version ?? '5.9.0',\n      categoryRules: config?.categoryRules ?? DEFAULT_CATEGORY_RULES,\n    };\n  }\n\n  // ===========================================================================\n  // GENERATE\n  // ===========================================================================\n\n  /**\n   * Generate API reference from tool definitions.\n   */\n  generate(tools: Tool[]): APIReference {\n    const toolDocs = tools.map((tool) => this.documentTool(tool));\n\n    // Group by category\n    const categoryMap = new Map<string, ToolDoc[]>();\n    for (const doc of toolDocs) {\n      if (!categoryMap.has(doc.category)) {\n        categoryMap.set(doc.category, []);\n      }\n      categoryMap.get(doc.category)!.push(doc);\n    }\n\n    // Sort categories and tools\n    const categories: CategoryDoc[] = [...categoryMap.entries()]\n      .sort(([a], [b]) => a.localeCompare(b))\n      .map(([name, tools]) => ({\n        name,\n        description: this.getCategoryDescription(name),\n        tools: tools.sort((a, b) => a.name.localeCompare(b.name)),\n      }));\n\n    return {\n      generatedAt: new Date().toISOString(),\n      totalTools: tools.length,\n      categories,\n      version: this.config.version,\n    };\n  }\n\n  // ===========================================================================\n  // TOOL DOCUMENTATION\n  // ===========================================================================\n\n  private documentTool(tool: Tool): ToolDoc {\n    const schema = tool.inputSchema as {\n      properties?: Record<\n        string,\n        {\n          type?: string;\n          description?: string;\n          default?: unknown;\n          enum?: string[];\n        }\n      >;\n      required?: string[];\n    };\n\n    const parameters: ParameterDoc[] = [];\n    const required = new Set(schema.required || []);\n\n    if (schema.properties) {\n      for (const [name, prop] of Object.entries(schema.properties)) {\n        parameters.push({\n          name,\n          type: prop.type || 'unknown',\n          description: prop.description || '',\n          required: required.has(name),\n          defaultValue: prop.default,\n          enumValues: prop.enum,\n        });\n      }\n    }\n\n    return {\n      name: tool.name,\n      description: tool.description || '',\n      category: this.categorize(tool.name),\n      parameters,\n      requiresAuth: tool.name.startsWith('absorb_') || tool.name.includes('payment'),\n      example: this.generateExample(tool.name, parameters),\n    };\n  }\n\n  private categorize(toolName: string): string {\n    for (const [prefix, category] of Object.entries(this.config.categoryRules)) {\n      if (toolName.startsWith(prefix)) {\n        return category;\n      }\n    }\n    return 'General';\n  }\n\n  private getCategoryDescription(category: string): string {\n    const descriptions: Record<string, string> = {\n      'Parsing & Validation': 'Parse and validate HoloScript compositions',\n      'Code Intelligence': 'AI-powered code analysis and suggestions',\n      'Code Generation': 'Generate HoloScript code and objects',\n      Rendering: 'Preview and render compositions',\n      Sharing: 'Share compositions via URL',\n      Conversion: 'Convert between formats',\n      Analysis: 'Analyze code structure and quality',\n      'Graph Analysis': 'Scene graph traversal and analysis',\n      'IDE Integration': 'LSP and IDE features',\n      'AI Assistant': 'Brittney AI assistant capabilities',\n      'Content Creation': 'Text-to-3D and content generation',\n      'Browser Control': 'Browser automation and testing',\n      Codebase: 'Codebase analysis and navigation',\n      'Knowledge Graph': 'GraphRAG knowledge retrieval',\n      'Self Improvement': 'Self-improvement pipeline',\n      'GLTF Import': 'Import 3D models from GLTF',\n      Editing: 'Edit compositions in-place',\n      'Absorb Service': 'Convert external formats to HoloScript',\n      'Service Contracts': 'Generate and validate service contracts',\n      'Agent Orchestration': 'Multi-agent orchestration and delegation',\n      Observability: 'Tracing, metrics, and health monitoring',\n      'Plugin Management': 'Install and manage plugins',\n      Economy: 'Budget, usage, and revenue management',\n      'Developer Tools': 'Development server and workspace tools',\n      General: 'General-purpose tools',\n    };\n    return descriptions[category] || '';\n  }\n\n  private generateExample(toolName: string, params: ParameterDoc[]): string {\n    const args: Record<string, unknown> = {};\n    for (const param of params) {\n      if (param.required) {\n        args[param.name] = this.exampleValue(param);\n      }\n    }\n\n    return JSON.stringify({ tool: toolName, args }, null, 2);\n  }\n\n  private exampleValue(param: ParameterDoc): unknown {\n    if (param.defaultValue !== undefined) return param.defaultValue;\n    if (param.enumValues && param.enumValues.length > 0) return param.enumValues[0];\n\n    switch (param.type) {\n      case 'string':\n        return `example-${param.name}`;\n      case 'number':\n        return 1;\n      case 'boolean':\n        return true;\n      case 'array':\n        return [];\n      case 'object':\n        return {};\n      default:\n        return '';\n    }\n  }\n\n  // ===========================================================================\n  // MARKDOWN OUTPUT\n  // ===========================================================================\n\n  /**\n   * Generate markdown documentation.\n   */\n  toMarkdown(ref: APIReference): string {\n    const lines: string[] = [\n      `# HoloScript MCP API Reference`,\n      '',\n      `> Generated: ${ref.generatedAt} | Version: ${ref.version} | ${ref.totalTools} tools`,\n      '',\n      '## Table of Contents',\n      '',\n    ];\n\n    // TOC\n    for (const cat of ref.categories) {\n      const anchor = cat.name.toLowerCase().replace(/[^a-z0-9]+/g, '-');\n      lines.push(`- [${cat.name}](#${anchor}) (${cat.tools.length})`);\n    }\n    lines.push('');\n\n    // Categories\n    for (const cat of ref.categories) {\n      lines.push(`## ${cat.name}`);\n      if (cat.description) {\n        lines.push('', cat.description, '');\n      }\n\n      for (const tool of cat.tools) {\n        lines.push(`### \\`${tool.name}\\``);\n        lines.push('', tool.description, '');\n\n        if (tool.parameters.length > 0) {\n          lines.push('| Parameter | Type | Required | Description |');\n          lines.push('|-----------|------|----------|-------------|');\n          for (const param of tool.parameters) {\n            const req = param.required ? 'Yes' : 'No';\n            lines.push(`| \\`${param.name}\\` | ${param.type} | ${req} | ${param.description} |`);\n          }\n          lines.push('');\n        }\n\n        if (tool.example) {\n          lines.push('```json', tool.example, '```', '');\n        }\n      }\n    }\n\n    return lines.join('\\n');\n  }\n\n  // ===========================================================================\n  // JSON OUTPUT\n  // ===========================================================================\n\n  /**\n   * Generate JSON documentation.\n   */\n  toJSON(ref: APIReference): string {\n    return JSON.stringify(ref, null, 2);\n  }\n}\n","/**\n * HoloScript Python/JS Interop Bindings\n *\n * Enables .hsplus modules to be used as drop-in libraries from Python and JS.\n * Generates binding wrappers that expose HoloScript modules as native imports.\n *\n * Usage:\n *   const bindings = new InteropBindingGenerator();\n *   bindings.generatePythonBindings(ast, 'output.py');\n *   bindings.generateJSBindings(ast, 'output.mjs');\n */\n\nimport type { HSPlusAST } from '../types/HoloScriptPlus';\n\nexport interface BindingExport {\n  name: string;\n  type: 'function' | 'class' | 'constant' | 'interface' | 'module';\n  parameters?: BindingParameter[];\n  returnType?: string;\n  value?: unknown;\n}\n\nexport interface BindingParameter {\n  name: string;\n  type: string;\n  optional?: boolean;\n  defaultValue?: string;\n}\n\nexport interface GeneratedBinding {\n  language: 'python' | 'javascript' | 'typescript';\n  code: string;\n  exports: string[];\n  metadata: {\n    sourceFile: string;\n    generatedAt: string;\n    holoScriptVersion: string;\n  };\n}\n\n/**\n * InteropBindingGenerator — Generates Python/JS bindings from HoloScript ASTs\n */\nexport class InteropBindingGenerator {\n  /**\n   * Extract exports from a HoloScript AST\n   */\n  extractExports(ast: HSPlusAST): BindingExport[] {\n    const exports: BindingExport[] = [];\n\n    if (!ast.body) return exports;\n\n    for (const node of ast.body) {\n      const nodeRecord = node as unknown as Record<string, unknown>;\n      const nodeType = nodeRecord.type as string | undefined;\n      const nodeName = nodeRecord.name as string | undefined;\n\n      if (nodeType === 'FunctionDeclaration' || nodeType === 'function') {\n        const params = (nodeRecord.params || []) as Array<Record<string, unknown> | string>;\n        exports.push({\n          name: nodeName || 'anonymous',\n          type: 'function',\n          parameters: params.map((p) => {\n            if (typeof p === 'string') {\n              return { name: p, type: 'any', optional: false };\n            }\n            return {\n              name: (p.name as string) || '',\n              type: (p.type as string) || 'any',\n              optional: (p.optional as boolean) || false,\n            };\n          }),\n          returnType: (nodeRecord.returnType as string) || 'void',\n        });\n      }\n\n      if (nodeType === 'template' || nodeType === 'ClassDeclaration') {\n        exports.push({\n          name: nodeName || 'UnnamedTemplate',\n          type: 'class',\n        });\n      }\n\n      if (nodeType === 'composition') {\n        exports.push({\n          name: nodeName || 'default',\n          type: 'module',\n        });\n      }\n\n      if (nodeType === 'VariableDeclaration' || nodeType === 'state') {\n        exports.push({\n          name: nodeName || 'unnamed',\n          type: 'constant',\n          value: nodeRecord.value,\n        });\n      }\n    }\n\n    return exports;\n  }\n\n  /**\n   * Generate Python bindings from HoloScript AST\n   */\n  generatePythonBindings(ast: HSPlusAST, sourceFile: string): GeneratedBinding {\n    const exports = this.extractExports(ast);\n    const lines: string[] = [\n      '\"\"\"',\n      `Auto-generated Python bindings for ${sourceFile}`,\n      `Generated by HoloScript InteropBindingGenerator`,\n      `Do not edit manually — regenerate with: holoscript compile ${sourceFile} --target python`,\n      '\"\"\"',\n      '',\n      'from typing import Any, Optional, Dict, List',\n      'import json',\n      '',\n    ];\n\n    for (const exp of exports) {\n      switch (exp.type) {\n        case 'function': {\n          const params = (exp.parameters || [])\n            .map((p) => {\n              const pyType = this.tsPyType(p.type);\n              return p.optional ? `${p.name}: ${pyType} = None` : `${p.name}: ${pyType}`;\n            })\n            .join(', ');\n          const retType = this.tsPyType(exp.returnType || 'void');\n          lines.push(`def ${exp.name}(${params}) -> ${retType}:`);\n          lines.push(`    \"\"\"HoloScript function: ${exp.name}\"\"\"`);\n          lines.push(`    raise NotImplementedError(\"Bridge to HoloScript runtime required\")`);\n          lines.push('');\n          break;\n        }\n        case 'class': {\n          lines.push(`class ${exp.name}:`);\n          lines.push(`    \"\"\"HoloScript template: ${exp.name}\"\"\"`);\n          lines.push(`    def __init__(self, **kwargs: Any) -> None:`);\n          lines.push(`        self._props = kwargs`);\n          lines.push('');\n          break;\n        }\n        case 'constant': {\n          lines.push(`${exp.name} = ${JSON.stringify(exp.value ?? 'None')}`);\n          lines.push('');\n          break;\n        }\n        case 'module': {\n          lines.push(`class ${exp.name}Module:`);\n          lines.push(`    \"\"\"HoloScript composition: ${exp.name}\"\"\"`);\n          lines.push(`    pass`);\n          lines.push('');\n          break;\n        }\n      }\n    }\n\n    // Add __all__\n    lines.push(`__all__ = [${exports.map((e) => `\"${e.name}\"`).join(', ')}]`);\n\n    return {\n      language: 'python',\n      code: lines.join('\\n'),\n      exports: exports.map((e) => e.name),\n      metadata: {\n        sourceFile,\n        generatedAt: new Date().toISOString(),\n        holoScriptVersion: '5.0.0',\n      },\n    };\n  }\n\n  /**\n   * Generate JavaScript (ESM) bindings from HoloScript AST\n   */\n  generateJSBindings(ast: HSPlusAST, sourceFile: string): GeneratedBinding {\n    const exports = this.extractExports(ast);\n    const lines: string[] = [\n      `// Auto-generated JS bindings for ${sourceFile}`,\n      `// Generated by HoloScript InteropBindingGenerator`,\n      `// Do not edit manually`,\n      '',\n    ];\n\n    for (const exp of exports) {\n      switch (exp.type) {\n        case 'function': {\n          const params = (exp.parameters || []).map((p) => p.name).join(', ');\n          lines.push(`export function ${exp.name}(${params}) {`);\n          lines.push(`  throw new Error(\"Bridge to HoloScript runtime required\");`);\n          lines.push(`}`);\n          lines.push('');\n          break;\n        }\n        case 'class': {\n          lines.push(`export class ${exp.name} {`);\n          lines.push(`  constructor(props = {}) { this._props = props; }`);\n          lines.push(`}`);\n          lines.push('');\n          break;\n        }\n        case 'constant': {\n          lines.push(`export const ${exp.name} = ${JSON.stringify(exp.value ?? null)};`);\n          lines.push('');\n          break;\n        }\n        case 'module': {\n          lines.push(`export const ${exp.name} = { /* HoloScript composition */ };`);\n          lines.push('');\n          break;\n        }\n      }\n    }\n\n    return {\n      language: 'javascript',\n      code: lines.join('\\n'),\n      exports: exports.map((e) => e.name),\n      metadata: {\n        sourceFile,\n        generatedAt: new Date().toISOString(),\n        holoScriptVersion: '5.0.0',\n      },\n    };\n  }\n\n  /**\n   * Map TypeScript types to Python types\n   */\n  private tsPyType(tsType: string): string {\n    const mapping: Record<string, string> = {\n      string: 'str',\n      number: 'float',\n      int: 'int',\n      boolean: 'bool',\n      void: 'None',\n      any: 'Any',\n      unknown: 'Any',\n      'string[]': 'List[str]',\n      'number[]': 'List[float]',\n    };\n    return mapping[tsType] || 'Any';\n  }\n}\n","/**\n * WorkspaceManager — HoloScript monorepo workspace management\n *\n * Manages `holoscript.workspace.json` configuration, resolves composition\n * imports across workspace members, and provides build ordering via\n * dependency graph.\n *\n * Part of HoloScript v5.9 \"Developer Portal\".\n *\n * @version 1.0.0\n */\n\nimport { existsSync, readFileSync, readdirSync, statSync, writeFileSync } from 'fs';\nimport { join, resolve, relative, dirname } from 'path';\n\n// =============================================================================\n// TYPES\n// =============================================================================\n\n/**\n * Workspace configuration file format (holoscript.workspace.json).\n */\nexport interface WorkspaceConfig {\n  /** Workspace name */\n  name: string;\n  /** Workspace version */\n  version: string;\n  /** Member packages (glob patterns or paths) */\n  members: string[];\n  /** Shared settings */\n  settings?: {\n    /** Default compiler target */\n    defaultTarget?: string;\n    /** Shared trait imports */\n    sharedTraits?: string[];\n    /** Environment variables */\n    env?: Record<string, string>;\n  };\n}\n\n/**\n * A resolved workspace member.\n */\nexport interface WorkspaceMember {\n  /** Member name */\n  name: string;\n  /** Absolute path to member root */\n  path: string;\n  /** Relative path from workspace root */\n  relativePath: string;\n  /** Composition files found */\n  compositions: string[];\n  /** Dependencies on other members */\n  dependencies: string[];\n  /** Whether this member has a package.json */\n  hasPackageJson: boolean;\n}\n\n/**\n * Build order result.\n */\nexport interface BuildOrder {\n  /** Ordered groups — members in each group can be built in parallel */\n  groups: string[][];\n  /** Total members */\n  total: number;\n  /** Whether there are circular dependencies */\n  hasCycles: boolean;\n  /** Cycle details if any */\n  cycles?: string[][];\n}\n\n/**\n * Import resolution result.\n */\nexport interface ImportResolution {\n  /** The resolved absolute file path */\n  resolvedPath: string;\n  /** The member this import belongs to */\n  memberName: string;\n  /** Whether the import was found */\n  found: boolean;\n}\n\n// =============================================================================\n// WORKSPACE MANAGER\n// =============================================================================\n\nexport class WorkspaceManager {\n  private root: string;\n  private config: WorkspaceConfig | null = null;\n  private members: Map<string, WorkspaceMember> = new Map();\n\n  constructor(root?: string) {\n    this.root = root ?? process.cwd();\n  }\n\n  // ===========================================================================\n  // INITIALIZATION\n  // ===========================================================================\n\n  /**\n   * Initialize a new workspace configuration.\n   */\n  init(name: string, members: string[] = ['packages/*']): WorkspaceConfig {\n    const config: WorkspaceConfig = {\n      name,\n      version: '1.0.0',\n      members,\n      settings: {\n        defaultTarget: 'r3f',\n        sharedTraits: [],\n      },\n    };\n\n    const configPath = join(this.root, 'holoscript.workspace.json');\n    writeFileSync(configPath, JSON.stringify(config, null, 2), 'utf-8');\n    this.config = config;\n    this.resolveMembers();\n\n    return config;\n  }\n\n  /**\n   * Load an existing workspace configuration.\n   */\n  load(): WorkspaceConfig | null {\n    const configPath = join(this.root, 'holoscript.workspace.json');\n    if (!existsSync(configPath)) {\n      return null;\n    }\n\n    try {\n      const raw = readFileSync(configPath, 'utf-8');\n      this.config = JSON.parse(raw) as WorkspaceConfig;\n      this.resolveMembers();\n      return this.config;\n    } catch {\n      return null;\n    }\n  }\n\n  // ===========================================================================\n  // MEMBER RESOLUTION\n  // ===========================================================================\n\n  private resolveMembers(): void {\n    this.members.clear();\n    if (!this.config) return;\n\n    for (const pattern of this.config.members) {\n      // Simple glob: \"packages/*\" → list directories in packages/\n      if (pattern.endsWith('/*')) {\n        const baseDir = join(this.root, pattern.slice(0, -2));\n        if (existsSync(baseDir) && statSync(baseDir).isDirectory()) {\n          const entries = readdirSync(baseDir, { withFileTypes: true });\n          for (const entry of entries) {\n            if (entry.isDirectory() && !entry.name.startsWith('.')) {\n              this.addMember(join(baseDir, entry.name));\n            }\n          }\n        }\n      } else {\n        // Direct path\n        const memberPath = resolve(this.root, pattern);\n        if (existsSync(memberPath) && statSync(memberPath).isDirectory()) {\n          this.addMember(memberPath);\n        }\n      }\n    }\n  }\n\n  private addMember(memberPath: string): void {\n    const name = this.getMemberName(memberPath);\n    const compositions = this.findCompositions(memberPath);\n    const dependencies = this.findDependencies(memberPath, compositions);\n    const hasPackageJson = existsSync(join(memberPath, 'package.json'));\n\n    this.members.set(name, {\n      name,\n      path: memberPath,\n      relativePath: relative(this.root, memberPath),\n      compositions,\n      dependencies,\n      hasPackageJson,\n    });\n  }\n\n  private getMemberName(memberPath: string): string {\n    const pkgPath = join(memberPath, 'package.json');\n    if (existsSync(pkgPath)) {\n      try {\n        const pkg = JSON.parse(readFileSync(pkgPath, 'utf-8'));\n        if (pkg.name) return pkg.name;\n      } catch {\n        // Fall through to directory name\n      }\n    }\n    return memberPath.split(/[/\\\\]/).pop() || 'unknown';\n  }\n\n  private findCompositions(dir: string, maxDepth = 3): string[] {\n    const results: string[] = [];\n    this.walkDir(dir, maxDepth, (filePath) => {\n      const ext = filePath.split('.').pop();\n      if (ext === 'holo' || ext === 'hs' || ext === 'hsplus') {\n        results.push(filePath);\n      }\n    });\n    return results;\n  }\n\n  private findDependencies(memberPath: string, compositions: string[]): string[] {\n    const deps = new Set<string>();\n\n    for (const comp of compositions) {\n      try {\n        const code = readFileSync(comp, 'utf-8');\n        // Match import patterns: import \"member-name/file\" or use \"member-name:trait\"\n        const importRegex = /import\\s+[\"']([^\"']+)[\"']/g;\n        let match;\n        while ((match = importRegex.exec(code)) !== null) {\n          const importPath = match[1];\n          // If it starts with a member name (not relative path)\n          if (!importPath.startsWith('.') && !importPath.startsWith('/')) {\n            const memberRef = importPath.split('/')[0];\n            if (memberRef !== this.getMemberName(memberPath)) {\n              deps.add(memberRef);\n            }\n          }\n        }\n      } catch {\n        // Skip unreadable files\n      }\n    }\n\n    return [...deps];\n  }\n\n  private walkDir(dir: string, depth: number, callback: (path: string) => void): void {\n    if (depth <= 0) return;\n    try {\n      const entries = readdirSync(dir, { withFileTypes: true });\n      for (const entry of entries) {\n        const fullPath = join(dir, entry.name);\n        if (entry.isFile()) {\n          callback(fullPath);\n        } else if (\n          entry.isDirectory() &&\n          !entry.name.startsWith('.') &&\n          entry.name !== 'node_modules'\n        ) {\n          this.walkDir(fullPath, depth - 1, callback);\n        }\n      }\n    } catch {\n      // Skip\n    }\n  }\n\n  // ===========================================================================\n  // BUILD ORDER\n  // ===========================================================================\n\n  /**\n   * Compute build order based on dependency graph.\n   * Returns parallel groups — each group can be built concurrently.\n   */\n  getBuildOrder(): BuildOrder {\n    const inDegree = new Map<string, number>();\n    const adj = new Map<string, string[]>();\n\n    for (const [name] of this.members) {\n      inDegree.set(name, 0);\n      adj.set(name, []);\n    }\n\n    for (const [name, member] of this.members) {\n      for (const dep of member.dependencies) {\n        if (this.members.has(dep)) {\n          adj.get(dep)!.push(name);\n          inDegree.set(name, (inDegree.get(name) || 0) + 1);\n        }\n      }\n    }\n\n    // Kahn's algorithm with parallel grouping\n    const groups: string[][] = [];\n    const processed = new Set<string>();\n    const remaining = new Map(inDegree);\n\n    while (processed.size < this.members.size) {\n      const group = [...remaining.entries()].filter(([, deg]) => deg === 0).map(([name]) => name);\n\n      if (group.length === 0) {\n        // Cycle detected\n        const cycles = this.detectCycles();\n        return {\n          groups,\n          total: this.members.size,\n          hasCycles: true,\n          cycles,\n        };\n      }\n\n      groups.push(group);\n\n      for (const name of group) {\n        processed.add(name);\n        remaining.delete(name);\n        for (const dependent of adj.get(name) || []) {\n          if (remaining.has(dependent)) {\n            remaining.set(dependent, remaining.get(dependent)! - 1);\n          }\n        }\n      }\n    }\n\n    return {\n      groups,\n      total: this.members.size,\n      hasCycles: false,\n    };\n  }\n\n  private detectCycles(): string[][] {\n    const cycles: string[][] = [];\n    const visited = new Set<string>();\n    const stack = new Set<string>();\n\n    const dfs = (name: string, path: string[]): void => {\n      if (stack.has(name)) {\n        const cycleStart = path.indexOf(name);\n        if (cycleStart >= 0) {\n          cycles.push(path.slice(cycleStart).concat(name));\n        }\n        return;\n      }\n      if (visited.has(name)) return;\n\n      visited.add(name);\n      stack.add(name);\n\n      const member = this.members.get(name);\n      if (member) {\n        for (const dep of member.dependencies) {\n          if (this.members.has(dep)) {\n            dfs(dep, [...path, name]);\n          }\n        }\n      }\n\n      stack.delete(name);\n    };\n\n    for (const [name] of this.members) {\n      dfs(name, []);\n    }\n\n    return cycles;\n  }\n\n  // ===========================================================================\n  // IMPORT RESOLUTION\n  // ===========================================================================\n\n  /**\n   * Resolve a composition import path.\n   */\n  resolveImport(importPath: string, fromFile: string): ImportResolution {\n    // Relative import\n    if (importPath.startsWith('.')) {\n      const dir = dirname(fromFile);\n      const resolved = resolve(dir, importPath);\n      const candidates = [resolved, `${resolved}.holo`, `${resolved}.hs`];\n\n      for (const candidate of candidates) {\n        if (existsSync(candidate)) {\n          const memberName = this.findMemberForFile(candidate);\n          return { resolvedPath: candidate, memberName: memberName || '', found: true };\n        }\n      }\n\n      return { resolvedPath: resolved, memberName: '', found: false };\n    }\n\n    // Member-based import: \"member-name/path/to/file\"\n    const parts = importPath.split('/');\n    const memberName = parts[0];\n    const member = this.members.get(memberName);\n\n    if (!member) {\n      return { resolvedPath: '', memberName, found: false };\n    }\n\n    const subPath = parts.slice(1).join('/');\n    const candidates = [\n      join(member.path, subPath),\n      join(member.path, `${subPath}.holo`),\n      join(member.path, `${subPath}.hs`),\n      join(member.path, 'src', subPath),\n      join(member.path, 'src', `${subPath}.holo`),\n    ];\n\n    for (const candidate of candidates) {\n      if (existsSync(candidate)) {\n        return { resolvedPath: candidate, memberName, found: true };\n      }\n    }\n\n    return { resolvedPath: '', memberName, found: false };\n  }\n\n  private findMemberForFile(filePath: string): string | undefined {\n    for (const [name, member] of this.members) {\n      if (filePath.startsWith(member.path)) {\n        return name;\n      }\n    }\n    return undefined;\n  }\n\n  // ===========================================================================\n  // QUERIES\n  // ===========================================================================\n\n  /**\n   * Get all workspace members.\n   */\n  getMembers(): WorkspaceMember[] {\n    return [...this.members.values()];\n  }\n\n  /**\n   * Get a member by name.\n   */\n  getMember(name: string): WorkspaceMember | undefined {\n    return this.members.get(name);\n  }\n\n  /**\n   * Get workspace configuration.\n   */\n  getConfig(): WorkspaceConfig | null {\n    return this.config;\n  }\n\n  /**\n   * Get workspace root path.\n   */\n  getRoot(): string {\n    return this.root;\n  }\n\n  /**\n   * Get workspace info summary.\n   */\n  getInfo(): {\n    name: string;\n    version: string;\n    root: string;\n    memberCount: number;\n    totalCompositions: number;\n    members: Array<{ name: string; path: string; compositions: number; dependencies: string[] }>;\n  } {\n    const config = this.config || { name: 'unnamed', version: '0.0.0' };\n    let totalComps = 0;\n    const memberInfo = [...this.members.values()].map((m) => {\n      totalComps += m.compositions.length;\n      return {\n        name: m.name,\n        path: m.relativePath,\n        compositions: m.compositions.length,\n        dependencies: m.dependencies,\n      };\n    });\n\n    return {\n      name: config.name,\n      version: config.version,\n      root: this.root,\n      memberCount: this.members.size,\n      totalCompositions: totalComps,\n      members: memberInfo,\n    };\n  }\n}\n","/**\n * Bridge module for WorkspaceManager — re-exports from CLI package.\n *\n * The MCP server needs access to WorkspaceManager but it lives in the CLI package.\n * This bridge provides a self-contained implementation to avoid circular deps.\n */\n\nexport { WorkspaceManager } from '../../cli/src/workspace/WorkspaceManager';\n","/**\n * HoloScript Code Generators\n *\n * AI-powered generation of HoloScript code from natural language.\n */\n\nimport { createProviderManager, type LLMProviderName } from '@holoscript/llm-provider';\nimport { parseHolo } from '@holoscript/core';\nimport { enforceVerifiedViewReceipts, isProvenanceComplete } from '@holoscript/core/reconstruction';\nimport type { HoloParseResult, HoloParseError } from '@holoscript/core';\n\n// Inline utility — avoids an @holoscript/std peer dependency\nconst capitalize = (s: string): string => (s ? s[0].toUpperCase() + s.slice(1) : s);\n\n// Trait suggestions based on keywords\nconst TRAIT_KEYWORDS: Record<string, string[]> = {\n  // Interaction keywords\n  'pick up': ['@grabbable'],\n  grab: ['@grabbable'],\n  hold: ['@grabbable', '@holdable'],\n  throw: ['@grabbable', '@throwable'],\n  click: ['@clickable'],\n  point: ['@pointable'],\n  hover: ['@hoverable'],\n  drag: ['@draggable'],\n  scale: ['@scalable'],\n  resize: ['@scalable'],\n\n  // Physics keywords\n  collide: ['@collidable'],\n  bounce: ['@collidable', '@physics'],\n  physics: ['@physics', '@collidable'],\n  fall: ['@physics', '@gravity'],\n  gravity: ['@gravity'],\n  trigger: ['@trigger'],\n\n  // Visual keywords\n  glow: ['@glowing'],\n  light: ['@emissive'],\n  transparent: ['@transparent'],\n  'see through': ['@transparent'],\n  reflect: ['@reflective'],\n  mirror: ['@reflective'],\n  animate: ['@animated'],\n  spin: ['@animated'],\n  rotate: ['@animated'],\n  billboard: ['@billboard'],\n  'face camera': ['@billboard'],\n\n  // Networking keywords\n  multiplayer: ['@networked', '@synced'],\n  sync: ['@networked', '@synced'],\n  network: ['@networked'],\n  save: ['@persistent'],\n  persist: ['@persistent'],\n  own: ['@owned'],\n  host: ['@host_only'],\n\n  // Behavior keywords\n  stack: ['@stackable'],\n  attach: ['@attachable'],\n  equip: ['@equippable'],\n  wear: ['@equippable'],\n  consume: ['@consumable'],\n  eat: ['@consumable'],\n  drink: ['@consumable'],\n  destroy: ['@destructible'],\n  break: ['@destructible'],\n\n  // Spatial keywords\n  anchor: ['@anchor'],\n  track: ['@tracked'],\n  'world lock': ['@world_locked'],\n  'hand track': ['@hand_tracked'],\n  'eye track': ['@eye_tracked'],\n\n  // Audio keywords\n  sound: ['@spatial_audio'],\n  audio: ['@spatial_audio'],\n  ambient: ['@ambient'],\n  voice: ['@voice_activated'],\n  speak: ['@voice_activated'],\n\n  // State keywords\n  state: ['@state', '@reactive'],\n  react: ['@reactive'],\n  observe: ['@observable'],\n  compute: ['@computed'],\n\n  // Social keywords\n  share: ['@shareable'],\n  collaborate: ['@collaborative'],\n  tweet: ['@tweetable'],\n};\n\n// Universal v6 trait keywords mapped by domain\nconst UNIVERSAL_TRAIT_KEYWORDS: Record<string, { traits: string[]; domain: string }> = {\n  // Service domain\n  api: { traits: ['@service', '@endpoint', '@rest_resource'], domain: 'service' },\n  endpoint: { traits: ['@endpoint', '@route'], domain: 'service' },\n  route: { traits: ['@route', '@handler'], domain: 'service' },\n  rest: { traits: ['@rest_resource', '@endpoint'], domain: 'service' },\n  'http server': { traits: ['@service', '@endpoint', '@handler'], domain: 'service' },\n  middleware: { traits: ['@middleware'], domain: 'service' },\n  gateway: { traits: ['@api_gateway', '@ingress'], domain: 'service' },\n  proxy: { traits: ['@reverse_proxy'], domain: 'service' },\n  'load balance': { traits: ['@load_balancer'], domain: 'service' },\n  webhook: { traits: ['@webhook_receiver', '@webhook_sender'], domain: 'service' },\n  'graphql resolver': { traits: ['@graphql_resolver', '@service'], domain: 'service' },\n  cors: { traits: ['@cors_policy'], domain: 'service' },\n  'rate limit': { traits: ['@rate_limiter'], domain: 'service' },\n  'file upload': { traits: ['@file_upload', '@multipart_handler'], domain: 'service' },\n  sse: { traits: ['@sse_endpoint'], domain: 'service' },\n  batch: { traits: ['@batch_endpoint'], domain: 'service' },\n  rpc: { traits: ['@rpc_method', '@service'], domain: 'service' },\n  'health endpoint': { traits: ['@health_endpoint', '@service'], domain: 'service' },\n\n  // Contract domain\n  schema: { traits: ['@schema', '@contract'], domain: 'contract' },\n  validate: { traits: ['@validator', '@contract'], domain: 'contract' },\n  serialize: { traits: ['@serializer'], domain: 'contract' },\n  openapi: { traits: ['@openapi_path', '@openapi_response'], domain: 'contract' },\n  protobuf: { traits: ['@protobuf_message', '@serializer'], domain: 'contract' },\n  asyncapi: { traits: ['@asyncapi_channel', '@asyncapi_message'], domain: 'contract' },\n  'graphql type': { traits: ['@graphql_type', '@contract'], domain: 'contract' },\n  'json schema': { traits: ['@json_schema'], domain: 'contract' },\n  avro: { traits: ['@avro_schema', '@serializer'], domain: 'contract' },\n  dto: { traits: ['@dto', '@data_transformer'], domain: 'contract' },\n  'contract test': { traits: ['@contract_test', '@consumer_contract'], domain: 'contract' },\n  'schema evolution': { traits: ['@schema_evolution', '@backward_compatible'], domain: 'contract' },\n  sanitize: { traits: ['@input_sanitizer', '@output_filter'], domain: 'contract' },\n\n  // Data domain\n  database: { traits: ['@db', '@model', '@query'], domain: 'data' },\n  model: { traits: ['@model', '@db'], domain: 'data' },\n  query: { traits: ['@query', '@db'], domain: 'data' },\n  cache: { traits: ['@cache'], domain: 'data' },\n  migration: { traits: ['@migration', '@db'], domain: 'data' },\n  orm: { traits: ['@model', '@repository', '@data_mapper'], domain: 'data' },\n  repository: { traits: ['@repository', '@model'], domain: 'data' },\n  transaction: { traits: ['@transaction', '@db'], domain: 'data' },\n  cqrs: { traits: ['@cqrs_command', '@cqrs_query'], domain: 'data' },\n  'event store': { traits: ['@event_store', '@projection'], domain: 'data' },\n  postgres: { traits: ['@relational_db', '@db'], domain: 'data' },\n  mongodb: { traits: ['@document_db', '@db'], domain: 'data' },\n  redis: { traits: ['@key_value_store', '@cache'], domain: 'data' },\n  'full text search': { traits: ['@full_text_search', '@search_index'], domain: 'data' },\n  'vector db': { traits: ['@vector_db', '@search_index'], domain: 'data' },\n  paginate: { traits: ['@cursor_pagination'], domain: 'data' },\n  'soft delete': { traits: ['@soft_delete', '@audit_column'], domain: 'data' },\n  sharding: { traits: ['@sharding_key', '@db'], domain: 'data' },\n\n  // Network domain\n  websocket: { traits: ['@websocket'], domain: 'network' },\n  grpc: { traits: ['@grpc'], domain: 'network' },\n  graphql: { traits: ['@graphql'], domain: 'network' },\n  tcp: { traits: ['@tcp_server', '@tcp_client'], domain: 'network' },\n  tls: { traits: ['@tls_config'], domain: 'network' },\n  mtls: { traits: ['@mtls_config', '@tls_config'], domain: 'network' },\n  oauth: { traits: ['@oauth2_config'], domain: 'network' },\n  jwt: { traits: ['@jwt_config', '@jwt_verifier'], domain: 'network' },\n  session: { traits: ['@session_config'], domain: 'network' },\n  cdn: { traits: ['@cdn_config'], domain: 'network' },\n\n  // Pipeline domain\n  pipeline: { traits: ['@pipeline', '@stream'], domain: 'pipeline' },\n  stream: { traits: ['@stream', '@real_time_stream'], domain: 'pipeline' },\n  queue: { traits: ['@queue', '@worker'], domain: 'pipeline' },\n  worker: { traits: ['@worker', '@queue'], domain: 'pipeline' },\n  scheduler: { traits: ['@scheduler'], domain: 'pipeline' },\n  etl: { traits: ['@etl_pipeline', '@pipeline'], domain: 'pipeline' },\n  kafka: { traits: ['@message_broker', '@topic', '@subscription'], domain: 'pipeline' },\n  rabbitmq: { traits: ['@message_broker', '@queue'], domain: 'pipeline' },\n  'message broker': { traits: ['@message_broker', '@topic'], domain: 'pipeline' },\n  'dead letter': { traits: ['@dlq_handler', '@queue'], domain: 'pipeline' },\n  'event sourcing': { traits: ['@event_sourcing', '@message_broker'], domain: 'pipeline' },\n  workflow: { traits: ['@workflow_engine', '@state_machine'], domain: 'pipeline' },\n  saga: { traits: ['@saga_orchestrator', '@compensating_transaction'], domain: 'pipeline' },\n  cdc: { traits: ['@change_data_capture', '@stream'], domain: 'pipeline' },\n  fanout: { traits: ['@fanout', '@message_broker'], domain: 'pipeline' },\n\n  // Metric domain\n  metric: { traits: ['@metric', '@prometheus_exporter'], domain: 'metric' },\n  trace: { traits: ['@trace', '@span', '@trace_context'], domain: 'metric' },\n  tracing: { traits: ['@trace', '@span', '@trace_context'], domain: 'metric' },\n  log: { traits: ['@log', '@structured_log'], domain: 'metric' },\n  'health check': { traits: ['@health_check'], domain: 'metric' },\n  prometheus: { traits: ['@prometheus_exporter', '@metric'], domain: 'metric' },\n  grafana: { traits: ['@grafana_dashboard', '@metric'], domain: 'metric' },\n  alert: { traits: ['@alert_rule', '@alert_channel'], domain: 'metric' },\n  slo: { traits: ['@slo', '@sli', '@error_budget'], domain: 'metric' },\n  apm: { traits: ['@apm_agent', '@profiler'], domain: 'metric' },\n  monitoring: { traits: ['@availability_monitor', '@uptime_monitor'], domain: 'metric' },\n  'audit log': { traits: ['@audit_log', '@access_log'], domain: 'metric' },\n  telemetry: { traits: ['@metric', '@trace', '@log'], domain: 'metric' },\n\n  // Container domain\n  container: { traits: ['@container', '@dockerfile'], domain: 'container' },\n  docker: { traits: ['@dockerfile', '@docker_compose'], domain: 'container' },\n  kubernetes: { traits: ['@kubernetes_deployment', '@kubernetes_service'], domain: 'container' },\n  k8s: { traits: ['@kubernetes_deployment', '@kubernetes_service'], domain: 'container' },\n  deployment: { traits: ['@deployment', '@scaling'], domain: 'container' },\n  'auto scale': { traits: ['@scaling', '@kubernetes_hpa'], domain: 'container' },\n  helm: { traits: ['@helm_chart', '@helm_values'], domain: 'container' },\n  terraform: { traits: ['@terraform_resource', '@terraform_module'], domain: 'container' },\n  'config map': { traits: ['@kubernetes_configmap'], domain: 'container' },\n  secret: { traits: ['@secret'], domain: 'container' },\n  cronjob: { traits: ['@kubernetes_cronjob'], domain: 'container' },\n  ingress: { traits: ['@kubernetes_ingress'], domain: 'container' },\n\n  // Resilience domain\n  'circuit breaker': { traits: ['@circuit_breaker'], domain: 'resilience' },\n  retry: { traits: ['@retry', '@exponential_backoff'], domain: 'resilience' },\n  timeout: { traits: ['@timeout', '@deadline_propagation'], domain: 'resilience' },\n  fallback: { traits: ['@fallback', '@graceful_degradation'], domain: 'resilience' },\n  bulkhead: { traits: ['@bulkhead'], domain: 'resilience' },\n  backoff: { traits: ['@exponential_backoff', '@jitter_backoff'], domain: 'resilience' },\n  'rate limiting': { traits: ['@token_bucket', '@leaky_bucket'], domain: 'resilience' },\n  'load shedding': { traits: ['@load_shedding', '@adaptive_concurrency'], domain: 'resilience' },\n  'chaos engineering': { traits: ['@chaos_experiment', '@fault_injection'], domain: 'resilience' },\n  canary: { traits: ['@canary_release'], domain: 'resilience' },\n  'blue green': { traits: ['@blue_green_deploy'], domain: 'resilience' },\n  idempotent: { traits: ['@idempotency_key', '@idempotent_consumer'], domain: 'resilience' },\n\n  // Visual/material domain — realistic rendering, PBR materials, named presets\n  realistic: { traits: ['@advanced_pbr', '@material_preset'], domain: 'visual' },\n  material: { traits: ['@advanced_pbr', '@material_preset'], domain: 'visual' },\n  texture: { traits: ['@advanced_pbr'], domain: 'visual' },\n  pbr: { traits: ['@advanced_pbr'], domain: 'visual' },\n  lighting: { traits: ['@advanced_pbr', '@emissive'], domain: 'visual' },\n  glow: { traits: ['@material_preset', '@emissive'], domain: 'visual' },\n  subsurface: { traits: ['@advanced_pbr'], domain: 'visual' },\n  weathered: { traits: ['@material_preset'], domain: 'visual' },\n};\n\n// Geometry keywords\nconst GEOMETRY_KEYWORDS: Record<string, string> = {\n  cube: 'cube',\n  box: 'cube',\n  sphere: 'sphere',\n  ball: 'sphere',\n  orb: 'sphere',\n  cylinder: 'cylinder',\n  tube: 'cylinder',\n  pipe: 'cylinder',\n  cone: 'cone',\n  pyramid: 'cone',\n  torus: 'torus',\n  ring: 'torus',\n  donut: 'torus',\n  capsule: 'capsule',\n  pill: 'capsule',\n  plane: 'plane',\n  floor: 'plane',\n  ground: 'plane',\n  wall: 'plane',\n};\n\n// Color keywords\nconst COLOR_KEYWORDS: Record<string, string> = {\n  red: '#ff0000',\n  green: '#00ff00',\n  blue: '#0000ff',\n  cyan: '#00ffff',\n  magenta: '#ff00ff',\n  yellow: '#ffff00',\n  orange: '#ff8800',\n  purple: '#8800ff',\n  pink: '#ff88ff',\n  white: '#ffffff',\n  black: '#000000',\n  gray: '#888888',\n  grey: '#888888',\n  gold: '#ffd700',\n  silver: '#c0c0c0',\n};\n\n// Material preset keywords — named, referenceable @advanced_pbr presets (OpenUSD\n// \"Look\" pattern, see research/2026-07-03_holoscript-realistic-authoring-docs-PLAN.md\n// §4). Maps a material-flavored description keyword to a PRESET IDENTIFIER, never a\n// raw hand-derived hex/roughness/metallic value — the identifier is composed onto the\n// generated object as `@material_preset(\"<identifier>\")` in generateObject() below.\nconst MATERIAL_PRESET_KEYWORDS: Record<string, string> = {\n  weathered: 'weathered_stone',\n  stone: 'weathered_stone',\n  rock: 'weathered_stone',\n  metal: 'brushed_metal',\n  metallic: 'brushed_metal',\n  wood: 'polished_wood',\n  wooden: 'polished_wood',\n  glowing: 'bioluminescent_glow',\n  bioluminescent: 'bioluminescent_glow',\n  organic: 'organic_moss',\n  moss: 'organic_moss',\n  glass: 'frosted_glass',\n  fabric: 'woven_fabric',\n  cloth: 'woven_fabric',\n  rusty: 'oxidized_metal',\n  rust: 'oxidized_metal',\n};\n\ninterface GenerateOptions {\n  format?: 'hs' | 'hsplus' | 'holo';\n  includeDocs?: boolean;\n}\n\ninterface SceneOptions {\n  style?: 'minimal' | 'detailed' | 'production';\n  features?: string[];\n}\n\ninterface AIGenerationMetadata {\n  source?: 'ai' | 'heuristic';\n  provider?: LLMProviderName;\n  attemptedProviders?: LLMProviderName[];\n}\n\n// F.112: generation is SOVEREIGN-default. Sovereign serving (Brittney Cloud =\n// vast Ollama/PyWorker fleet P.008, or a local Ollama/llama.cpp/bitnet server) is\n// tried FIRST; frontier APIs (Anthropic/OpenAI/Gemini) are BYOK fallback ONLY.\n// HOLOSCRIPT_MCP_AI_PROVIDER still force-pins for explicit overrides. NOTE: this is\n// necessary-but-not-sufficient — a sovereign provider must also be REGISTERED, which\n// needs BRITTNEY_SERVICE_URL / HOLOSCRIPT_LOCAL_LLM_URL set in the mcp-server env\n// (Railway dashboard); without one, anthropic-BYOK fallback is correct behavior.\nconst AI_PROVIDER_PRIORITY: readonly LLMProviderName[] = [\n  'brittney-cloud', // sovereign serving fleet (BRITTNEY_SERVICE_URL) — native default\n  'local-llm', // local Ollama / llama.cpp / LM Studio (HOLOSCRIPT_LOCAL_LLM_URL)\n  'bitnet', // dedicated bitnet.cpp server (HOLOSCRIPT_BITNET_URL)\n  'anthropic', // BYOK frontier fallback\n  'openai',\n  'gemini',\n  'mock',\n];\n\nfunction getAIProviderOrder(registeredProviders: LLMProviderName[]): LLMProviderName[] {\n  const forcedProvider = process.env.HOLOSCRIPT_MCP_AI_PROVIDER as LLMProviderName | undefined;\n\n  if (forcedProvider && registeredProviders.includes(forcedProvider)) {\n    return [\n      forcedProvider,\n      ...AI_PROVIDER_PRIORITY.filter(\n        (provider) => provider !== forcedProvider && registeredProviders.includes(provider)\n      ),\n    ];\n  }\n\n  return AI_PROVIDER_PRIORITY.filter((provider) => registeredProviders.includes(provider));\n}\n\nfunction detectGeometryFromCode(code: string): string | undefined {\n  const geometryMatch = code.match(/geometry:\\s*\"([^\"]+)\"/i);\n  if (geometryMatch) return geometryMatch[1];\n\n  const primitiveMatch = code.match(\n    /\\b(cube|sphere|cylinder|cone|torus|capsule|plane|mesh|text|light|camera)\\b/\n  );\n  return primitiveMatch?.[1];\n}\n\nfunction isUsableObjectCode(code: string, format: 'hs' | 'hsplus' | 'holo'): boolean {\n  if (!code.trim()) return false;\n  if ((code.match(/\\{/g) || []).length !== (code.match(/\\}/g) || []).length) return false;\n\n  if (format === 'holo') {\n    return code.includes('template ') || code.includes('object ');\n  }\n\n  return (\n    code.includes('composition ') ||\n    code.includes('template ') ||\n    code.includes('object ') ||\n    code.includes('material ') ||\n    /\\b(cube|sphere|plane|cylinder|cone|torus|capsule)\\b/.test(code)\n  );\n}\n\nfunction isUsableSceneCode(code: string): boolean {\n  if (!code.trim()) return false;\n  if ((code.match(/\\{/g) || []).length !== (code.match(/\\}/g) || []).length) return false;\n\n  // Accept both named (composition \"Foo\" {) and unnamed (composition {) roots\n  const hasCompositionRoot = /\\bcomposition(?:\\s+\"[^\"]*\")?\\s*\\{/i.test(code);\n  const hasSceneContent =\n    code.includes('environment') ||\n    code.includes('object ') ||\n    code.includes('template ') ||\n    /\\b(cube|sphere|plane|cylinder|cone|torus|capsule|mesh|text|light|camera)\\s*\\{/i.test(code);\n\n  return hasCompositionRoot && hasSceneContent;\n}\n\nfunction stripCodeFences(code: string): string {\n  const fenced = code.match(/```(?:holoscript|holo|hsplus|hs)?\\s*([\\s\\S]*?)```/i);\n  return (fenced ? fenced[1] : code).trim();\n}\n\nfunction trimToLikelyCodeStart(code: string): string {\n  const marker = code.search(\n    /(^|\\n)\\s*(composition\\s*(?:\"[^\"]*\"\\s*)?\\{|template\\s+\"|object\\s+\"|cube\\s*\\{|sphere\\s*\\{|plane\\s*\\{|cylinder\\s*\\{|cone\\s*\\{|torus\\s*\\{|capsule\\s*\\{|mesh\\s*\\{)/i\n  );\n\n  if (marker < 0) return code.trim();\n\n  const start = code.lastIndexOf('\\n', marker);\n  return code.slice(start >= 0 ? start + 1 : marker).trim();\n}\n\nfunction indentBlock(code: string, spaces = 2): string {\n  const indent = ' '.repeat(spaces);\n  return code\n    .split('\\n')\n    .map((line) => `${indent}${line}`)\n    .join('\\n');\n}\n\nfunction wrapSceneFragment(fragment: string): string {\n  return `composition \"GeneratedScene\" {\n  environment {\n    skybox: \"gradient\"\n    ambient_light: 0.3\n  }\n\n${indentBlock(fragment, 2)}\n}`;\n}\n\nfunction normalizeSceneAIOutput(code: string): string {\n  const stripped = stripCodeFences(code);\n  const trimmed = trimToLikelyCodeStart(stripped);\n\n  if (!trimmed) return trimmed;\n  // Accept both named (composition \"Foo\" {) and unnamed (composition {) roots\n  if (/^composition\\s*(?:\"[^\"]*\"\\s*)?\\{/i.test(trimmed)) return trimmed;\n\n  const looksLikeSceneFragment =\n    isUsableObjectCode(trimmed, 'holo') ||\n    /\\b(cube|sphere|plane|cylinder|cone|torus|capsule|mesh)\\s*\\{/i.test(trimmed);\n\n  if (!looksLikeSceneFragment) return trimmed;\n\n  return wrapSceneFragment(trimmed);\n}\n\n/**\n * Deterministically repair the parser-fatal patterns LLM generators emit, so the\n * output compiles through the compiler MCP path. Proven against compile_to_r3f /\n * compile_to_native_2d / compile_to_canvas2d_game (a named composition with quoted\n * hex compiles green; the raw LLM forms below are rejected by the parser):\n *   (a) anonymous `composition {`                  -> `composition \"GeneratedScene\" {`\n *   (b) bare hex args `@color(#abc)` / `c: #abc` / `(1, #abc)` -> quoted string\n *   (c) `=` assignment in trait args `@t(w = 5)`   -> `@t(w: 5)` (HoloScript uses `:`)\n *   (d) unquoted dotted value `c: theme.primary`   -> `c: \"theme.primary\"` (outside bind())\n * Idempotent: already-valid output (named composition, quoted colors, `:` separators,\n * bind(...) expressions) passes through unchanged. A fifth class — generator-emitted\n * unsupported primitives (`light{}`) / niche traits — is tracked separately; the exact\n * offending token must be confirmed before stripping, to avoid removing valid\n * root-level lighting.\n */\nexport function normalizeGeneratedHoloScript(\n  code: string,\n  _targetFormat: 'hs' | 'hsplus' | 'holo'\n): string {\n  let out = code;\n  // (a) name an anonymous composition root (does NOT touch `composition \"X\" {`)\n  out = out.replace(/\\bcomposition\\s*\\{/g, 'composition \"GeneratedScene\" {');\n  // (b) quote bare #hex used as a value, after `(`, `,` or `:` (skips already-quoted)\n  out = out.replace(/([(,]\\s*|:\\s*)(#[0-9a-fA-F]{3,8})\\b/g, (_m, lead, hex) => `${lead}\"${hex}\"`);\n  // (c) `key = value` -> `key: value` in arg/property position only. The LLM tail\n  //     emits `@trait(width = 5)` / a `key = value` property line; HoloScript uses `:`.\n  //     Scoped to an identifier key in arg position (after `(` or `,`) OR at the start\n  //     of a (whitespace-only-indented) line, then a LONE `=` — guarded against `==`,\n  //     `=>`, `>=`, `<=`, `!=` so any equality/arrow inside a bind()/when() expression\n  //     or a skipped action body is left untouched.\n  out = out.replace(\n    /([(,]\\s*|^[ \\t]*)([A-Za-z_$][\\w$]*)\\s*=(?![=>])\\s*/gm,\n    (_m, lead, key) => `${lead}${key}: `\n  );\n  // (d) quote an unquoted dotted value `key: a.b(.c)` -> `key: \"a.b\"`, e.g.\n  //     `color: theme.primary`. Skips: already-quoted, numeric (1.5 — leading digit not\n  //     matched), and bind()/expression contexts (a dotted path immediately followed by\n  //     `(` is a call, excluded by the negative lookahead).\n  out = out.replace(\n    /(:\\s*)([A-Za-z_$][\\w$]*(?:\\.[A-Za-z_$][\\w$]*)+)(?!\\s*[(\"'.\\w])/g,\n    (_m, lead, path) => `${lead}\"${path}\"`\n  );\n  return out;\n}\n\n/** Max generate->parse->re-prompt attempts per provider before falling to the next. */\nconst MAX_GEN_RETRIES_PER_PROVIDER = Math.max(\n  1,\n  Number(process.env.HOLOSCRIPT_MCP_GEN_RETRIES) || 2\n);\n\n/**\n * Validate raw LLM output against the canonical parser, mirroring the normalization\n * the caller will ultimately apply, so a \"valid\" verdict here means the string that\n * actually reaches the compiler parses. Returns the deterministically-repaired code\n * plus a parse verdict and a compact error summary suitable for re-prompting.\n *\n * Scene/UI callers run normalizeSceneAIOutput AFTER tryGenerateWithAI; objects do not.\n * We replicate that here (idempotent on already-wrapped input) only to validate — the\n * returned `code` is the same raw-normalized shape the caller expects, so contracts\n * are unchanged.\n */\nfunction validateGeneratedCode(\n  rawCode: string,\n  targetFormat: 'hs' | 'hsplus' | 'holo'\n): { code: string; ok: boolean; errorSummary: string } {\n  const code = normalizeGeneratedHoloScript(rawCode, targetFormat);\n  // The string the caller hands to the compiler: scene/UI paths wrap fragments.\n  const toParse = targetFormat === 'holo' ? normalizeSceneAIOutput(code) : code;\n\n  if (!toParse.trim()) {\n    return { code, ok: false, errorSummary: 'empty generation' };\n  }\n\n  // Structural gate: the parser is TOLERANT — it accepts arbitrary non-HoloScript text\n  // as an empty implicit composition (success:true, no content). So a parse-success\n  // verdict alone is insufficient; require a real composition/object/template root too.\n  // This is the existing usability heuristic, now ANDed with a true parse.\n  const structurallyUseful =\n    targetFormat === 'holo'\n      ? isUsableSceneCode(toParse)\n      : isUsableObjectCode(toParse, targetFormat);\n  if (!structurallyUseful) {\n    return {\n      code,\n      ok: false,\n      errorSummary: 'no composition root with renderable content (empty or non-HoloScript output)',\n    };\n  }\n\n  let result: HoloParseResult;\n  try {\n    result = parseHolo(toParse) as HoloParseResult;\n  } catch (err) {\n    return {\n      code,\n      ok: false,\n      errorSummary: err instanceof Error ? err.message : String(err),\n    };\n  }\n\n  if (result.success) {\n    return { code, ok: true, errorSummary: '' };\n  }\n\n  const errorSummary = result.errors\n    .slice(0, 4)\n    .map((e: HoloParseError) => {\n      const where = e.loc ? ` (line ${e.loc.line}, col ${e.loc.column})` : '';\n      const hint = e.suggestion ? ` — ${e.suggestion}` : '';\n      return `${e.message}${where}${hint}`;\n    })\n    .join('; ');\n\n  return { code, ok: false, errorSummary: errorSummary || 'parse failed' };\n}\n\n/** Re-prompt suffix appended after a failed parse, steering the model to the grammar. */\nfunction buildRetryPrompt(basePrompt: string, errorSummary: string): string {\n  return `${basePrompt}\n\nYour previous output FAILED to parse with these errors:\n${errorSummary}\n\nFix ONLY these problems and return corrected HoloScript. Grammar reminders:\n- separate keys and values with a colon, never '=' (write \\`width: 5\\`, not \\`width = 5\\`)\n- quote string values, including dotted refs like \\`\"theme.primary\"\\`, unless inside bind(...)\n- the root must be a named composition: \\`composition \"Name\" { ... }\\`\n- colors are quoted strings: \\`\"#3366ff\"\\`\nReturn only code, no prose.`;\n}\n\nasync function tryGenerateWithAI(\n  prompt: string,\n  targetFormat: 'hs' | 'hsplus' | 'holo'\n): Promise<{\n  code: string;\n  provider: LLMProviderName;\n  attemptedProviders: LLMProviderName[];\n  detectedTraits: string[];\n} | null> {\n  let manager;\n\n  try {\n    manager = createProviderManager();\n  } catch {\n    return null;\n  }\n\n  const debugAI = process.env.HOLOSCRIPT_MCP_AI_DEBUG === '1';\n  const attemptedProviders: LLMProviderName[] = [];\n  // Best parser-rejected candidate seen so far — returned only if NO provider yields a\n  // parse-clean result, preserving the prior behavior (the caller's isUsable*/heuristic\n  // fallback still runs on it). The deterministic generator remains the final net.\n  let lastCandidate: {\n    code: string;\n    provider: LLMProviderName;\n    detectedTraits: string[];\n  } | null = null;\n\n  for (const providerName of getAIProviderOrder(manager.getRegisteredProviders())) {\n    const provider = manager.getProvider(providerName);\n    if (!provider) continue;\n\n    attemptedProviders.push(providerName);\n\n    // Local providers (small models) need conservative settings to stay coherent\n    const isLocalProvider = providerName === 'bitnet' || providerName === 'local-llm';\n    let attemptPrompt = prompt;\n\n    for (let attempt = 1; attempt <= MAX_GEN_RETRIES_PER_PROVIDER; attempt++) {\n      let result;\n      try {\n        result = await provider.generateHoloScript({\n          prompt: attemptPrompt,\n          targetFormat,\n          maxObjects: targetFormat === 'holo' ? (isLocalProvider ? 4 : 8) : 1,\n          // Nudge temperature down on retry so the repair stays close to the grammar.\n          temperature: (isLocalProvider ? 0.1 : 0.35) * (attempt > 1 ? 0.6 : 1),\n        });\n      } catch {\n        // Provider call failed entirely — abandon this provider, try the next.\n        break;\n      }\n\n      const verdict = validateGeneratedCode(result.code, targetFormat);\n\n      if (verdict.ok) {\n        if (debugAI && attempt > 1) {\n          console.debug(\n            `[generators] ${providerName} produced parse-clean output on attempt ${attempt}`\n          );\n        }\n        return {\n          code: verdict.code,\n          provider: result.provider,\n          attemptedProviders: [...attemptedProviders],\n          detectedTraits: result.detectedTraits,\n        };\n      }\n\n      // Keep the most recent rejected candidate as a last resort.\n      lastCandidate = {\n        code: verdict.code,\n        provider: result.provider,\n        detectedTraits: result.detectedTraits,\n      };\n\n      if (debugAI) {\n        console.debug(\n          `[generators] ${providerName} attempt ${attempt}/${MAX_GEN_RETRIES_PER_PROVIDER} failed parse: ${verdict.errorSummary}`\n        );\n      }\n\n      // Re-prompt the SAME provider with the concrete parse error (if attempts remain).\n      attemptPrompt = buildRetryPrompt(prompt, verdict.errorSummary);\n    }\n    // Exhausted retries for this provider; fall through to the next provider.\n  }\n\n  // No provider produced parse-clean output. Return the best rejected candidate (if any)\n  // so the caller's usability heuristic + deterministic fallback path behaves as before.\n  if (lastCandidate) {\n    return {\n      code: lastCandidate.code,\n      provider: lastCandidate.provider,\n      attemptedProviders: [...attemptedProviders],\n      detectedTraits: lastCandidate.detectedTraits,\n    };\n  }\n\n  return null;\n}\n\nexport async function generateObjectForMCP(\n  description: string,\n  options: GenerateOptions = {}\n): Promise<ReturnType<typeof generateObject> & AIGenerationMetadata> {\n  const format = options.format || 'hsplus';\n  const heuristic = generateObject(description, options);\n  const aiPrompt = `Create a single ${format} HoloScript object for: ${description}. Return only code. Prefer one focused object, not a large world.`;\n  const aiResult = await tryGenerateWithAI(aiPrompt, format);\n\n  if (aiResult && isUsableObjectCode(aiResult.code, format)) {\n    return {\n      code: aiResult.code,\n      traits: aiResult.detectedTraits,\n      geometry: detectGeometryFromCode(aiResult.code) ?? heuristic.geometry,\n      format,\n      source: 'ai',\n      provider: aiResult.provider,\n      attemptedProviders: aiResult.attemptedProviders,\n    };\n  }\n\n  return {\n    ...heuristic,\n    source: 'heuristic',\n    provider: aiResult?.provider,\n    attemptedProviders: aiResult?.attemptedProviders,\n  };\n}\n\nexport async function generateSceneForMCP(\n  description: string,\n  options: SceneOptions = {}\n): Promise<ReturnType<typeof generateScene> & AIGenerationMetadata> {\n  const debugAI = process.env.HOLOSCRIPT_MCP_AI_DEBUG === '1';\n  const heuristic = generateScene(description, options);\n  const features = options.features?.length\n    ? ` Include features: ${options.features.join(', ')}.`\n    : '';\n  const aiPrompt = `Create a complete holo composition scene for: ${description}.${features} Return only code with a composition root.`;\n  const aiResult = await tryGenerateWithAI(aiPrompt, 'holo');\n  const aiCode = aiResult ? normalizeSceneAIOutput(aiResult.code) : '';\n\n  if (aiResult && isUsableSceneCode(aiCode)) {\n    return {\n      code: aiCode,\n      stats: {\n        objects: (aiCode.match(/\\bobject\\s+\"/g) || []).length,\n        traits: aiResult.detectedTraits.length,\n        lines: aiCode.split('\\n').length,\n      },\n      source: 'ai',\n      provider: aiResult.provider,\n      attemptedProviders: aiResult.attemptedProviders,\n    };\n  }\n\n  const fallback = {\n    ...heuristic,\n    source: 'heuristic',\n    provider: aiResult?.provider,\n    attemptedProviders: aiResult?.attemptedProviders,\n  };\n\n  if (debugAI && aiResult) {\n    Object.assign(fallback, {\n      aiDebug: {\n        rawCode: aiResult.code,\n        normalizedCode: aiCode,\n        balanced: (aiCode.match(/\\{/g) || []).length === (aiCode.match(/\\}/g) || []).length,\n        hasCompositionRoot: /\\bcomposition(?:\\s+\"[^\"]+\")?\\s*\\{/i.test(aiCode),\n        hasSceneContent:\n          aiCode.includes('environment') ||\n          aiCode.includes('object ') ||\n          aiCode.includes('template ') ||\n          /\\b(cube|sphere|plane|cylinder|cone|torus|capsule|mesh|text|light|camera)\\s*\\{/i.test(\n            aiCode\n          ),\n      },\n    });\n  }\n\n  return fallback as any;\n}\n\n// =============================================================================\n// NATIVE WORLD GENERATION — sovereign-3d pipeline (Brittney v43+)\n// =============================================================================\n\nexport interface NativeWorldGenerationOptions {\n  /** Output format. neural_field is the sovereign-exclusive format. Default: '3dgs' */\n  format?: 'mesh' | '3dgs' | 'both' | 'neural_field';\n  /** Quality tier. Default: 'high' */\n  quality?: 'low' | 'medium' | 'high' | 'ultra';\n  /** Optional base64 or URL for single-view reconstruction */\n  input_image?: string;\n  /** Multi-view images for photogrammetric reconstruction */\n  input_images?: string[];\n  /** Generate a navigable navmesh alongside the world asset */\n  navEnabled?: boolean;\n  /** Enable physics + collision interactive mode */\n  interactiveMode?: boolean;\n  /** Reproducible seed */\n  seed?: number;\n}\n\nexport interface NativeWorldGenerationResult {\n  /**\n   * Primary asset URL (.splat / .ply / .glb).\n   * Absent when source='text-llm' — the sovereign 3D backend is not yet deployed;\n   * holoCode is still valid HoloScript that can be rendered as a scene.\n   */\n  assetUrl?: string;\n  /** Navmesh .glb URI — present when navEnabled=true and source='sovereign-3d' */\n  navmeshUrl?: string;\n  /** Point cloud URI — present when format='both' and source='sovereign-3d' */\n  pointCloudUrl?: string;\n  /** Opaque backend job ID — absent when source='text-llm' */\n  generationId?: string;\n  /** Format actually produced */\n  format: string;\n  /** Auto-generated companion HoloScript code (.holo) */\n  holoCode: string;\n  /**\n   * Generation surface used.\n   * - 'sovereign-3d'  — Sovereign3DAdapter (Brittney v43+ 3D splat backend), live asset URL present\n   * - 'text-llm'      — Brittney/LLM text path (same as generate_scene), no 3D asset yet\n   * - 'heuristic'     — deterministic fallback, no LLM available\n   */\n  source: 'sovereign-3d' | 'text-llm' | 'heuristic';\n  metrics: {\n    splatCount?: number;\n    triangleCount?: number;\n    generationMs?: number;\n    bounds?: [number, number, number, number, number, number];\n    agentStart?: [number, number, number];\n    waypoints?: [number, number, number][];\n  };\n}\n\nexport type WorldPromptInputType = 'text' | 'image' | 'video';\n\nexport interface WorldPromptInput {\n  type: WorldPromptInputType;\n  text?: string;\n  url?: string;\n  data?: string;\n  mimeType?: string;\n  label?: string;\n}\n\nexport interface VideoReconstructionSummary {\n  sessionId: string;\n  replayFingerprint?: string;\n  framesIngested?: number;\n  ingestMode?: string;\n  captureProfile?: string;\n  videoBytes?: number;\n}\n\nexport interface WorldSemanticNode {\n  id: string;\n  name: string;\n  kind: 'terrain' | 'landmark' | 'video_reconstruction' | 'agent_start';\n  geometry: 'plane' | 'box' | 'capsule' | 'mesh';\n  position: [number, number, number];\n  scale: [number, number, number];\n  material: string;\n}\n\nexport interface WorldColliderMesh {\n  id: string;\n  nodeId: string;\n  shape: 'box' | 'mesh';\n  position: [number, number, number];\n  size: [number, number, number];\n  source: 'semantic_node' | 'video_reconstruction' | 'navmesh';\n}\n\nexport type WorldAssetGraphNodeKind =\n  | 'terrain'\n  | 'landmark'\n  | 'surface'\n  | 'semantic_observation'\n  | 'occluder_completion'\n  | 'navigation_path'\n  | 'agent_start'\n  | 'video_reconstruction';\n\nexport type WorldAssetGraphProvenance = 'observed' | 'inferred' | 'completed' | 'generated';\n\nexport interface WorldAssetGraphNode {\n  id: string;\n  name: string;\n  kind: WorldAssetGraphNodeKind;\n  geometry: 'plane' | 'box' | 'capsule' | 'mesh';\n  position: [number, number, number];\n  scale: [number, number, number];\n  material: string;\n  provenance: WorldAssetGraphProvenance;\n  confidence: number;\n  sourceInputLabels: string[];\n  sourceNodeIds: string[];\n  traits: string[];\n  navigationRole?: 'walkable' | 'spawn' | 'target' | 'path';\n  colliderRole?: 'static' | 'dynamic' | 'navmesh';\n}\n\nexport interface WorldAssetGraphEdge {\n  id: string;\n  from: string;\n  to: string;\n  relationship:\n    | 'supports'\n    | 'blocks'\n    | 'leads_to'\n    | 'occludes'\n    | 'completes'\n    | 'anchors'\n    | 'observes';\n  confidence: number;\n}\n\nexport interface WorldStructuredAssetGraph {\n  schema: 'holoscript.structured_asset_graph.v1';\n  graphId: string;\n  graphHash: string;\n  sourcePromptHash: string;\n  inputModalities: WorldPromptInputType[];\n  nodes: WorldAssetGraphNode[];\n  edges: WorldAssetGraphEdge[];\n  navigationPath: [number, number, number][];\n  colliderMeshIds: string[];\n  occlusionCompletions: string[];\n  materialAtlas: Record<string, string>;\n  textureMapRefs: string[];\n  matrixRefs: string[];\n  benchmarkBoundary: 'marble_gap_sovereign_structured_asset_graph';\n}\n\nexport interface WorldFoundationModelProvenance {\n  schema: 'cael.world_foundation_model.v1';\n  synthesisId: string;\n  provider: string;\n  model: string;\n  generatedAt: string;\n  promptHash: string;\n  inputModalities: WorldPromptInputType[];\n  semanticNodeCount: number;\n  colliderCount: number;\n  videoReconstructionSessionId?: string;\n  replayFingerprint?: string;\n  sourceAssetUrls: string[];\n  structuredAssetGraphHash?: string;\n  structuredAssetGraphNodeCount?: number;\n  occlusionCompletionCount?: number;\n  receiptHash: string;\n}\n\nexport interface WorldPromptGenerationOptions extends NativeWorldGenerationOptions {\n  inputs?: WorldPromptInput[];\n  videoReconstruction?: VideoReconstructionSummary;\n  provider?: string;\n  model?: string;\n  generatedAt?: string;\n}\n\nexport interface WorldPromptGenerationResult extends NativeWorldGenerationResult {\n  inputModalities: WorldPromptInputType[];\n  semanticNodes: WorldSemanticNode[];\n  colliderMeshes: WorldColliderMesh[];\n  structuredAssetGraph: WorldStructuredAssetGraph;\n  provenance: WorldFoundationModelProvenance;\n  videoReconstruction?: VideoReconstructionSummary;\n}\n\n/**\n * Generate a sovereign 3D world using the native Sovereign3DAdapter (Brittney v43+)\n * when the 3D backend is deployed, or the proven Brittney text-LLM path when it is not.\n *\n * Resolution order:\n *   1. Sovereign3DAdapter — only when HOLOSCRIPT_SOVEREIGN_BASE_URL is explicitly set\n *      (proves the backend is deployed; default 'https://api.holoscript.net/sovereign'\n *      is intentionally NOT treated as \"available\" — that endpoint is not deployed).\n *   2. tryGenerateWithAI text path — Brittney cloud / local-llm / BYOK; same mechanism\n *      as generate_scene.  Returns a real .holo world composition; no 3D splat asset.\n *   3. Heuristic fallback — deterministic, no LLM needed.\n *\n * This is an honest capability-gap posture (per /founder ruling 2026-06-08):\n * the tool succeeds with real output, source field declares which surface was used,\n * and assetUrl is absent when the 3D backend is not yet deployed.\n */\nexport async function generateWorldNative(\n  prompt: string,\n  options: NativeWorldGenerationOptions = {}\n): Promise<NativeWorldGenerationResult> {\n  const safePrompt = prompt.replace(/\"/g, '\\\\\"').replace(/\\n/g, ' ');\n  const startMs = Date.now();\n\n  // ─── PATH 1: Sovereign3DAdapter ─────────────────────────────────────────────\n  // Attempt when:\n  //   (a) HOLOSCRIPT_SOVEREIGN_BASE_URL is explicitly set to a non-default URL, OR\n  //   (b) HOLOSCRIPT_SOVEREIGN_MOCK=true is set (mock mode works without a live backend)\n  // The default fallback URL ('https://api.holoscript.net/sovereign') is NOT\n  // treated as \"available\" — it is the deploy target, not a live service.\n  //\n  // If the sovereign backend is configured but unreachable (fetch failed / network\n  // error / timeout) and mock mode is OFF, the error is caught and we fall through\n  // to PATH 2 rather than surfacing a hard failure to the caller. This covers the\n  // case where HOLOSCRIPT_SOVEREIGN_BASE_URL is set in the environment but the\n  // service is not yet deployed (e.g. wss://api.hololand.io offline).\n  const sovereignBaseUrl = process.env.HOLOSCRIPT_SOVEREIGN_BASE_URL?.trim();\n  const sovereignMock = Boolean(process.env.HOLOSCRIPT_SOVEREIGN_MOCK);\n  const sovereignBackendLive =\n    sovereignMock ||\n    (sovereignBaseUrl &&\n      sovereignBaseUrl !== '' &&\n      sovereignBaseUrl !== 'https://api.holoscript.net/sovereign');\n\n  if (sovereignBackendLive) {\n    const { Sovereign3DAdapter } = await import('@holoscript/core/world');\n    const adapter = new Sovereign3DAdapter({\n      mockMode: sovereignMock,\n    });\n\n    try {\n      const result = await adapter.generate({\n        prompt,\n        format: options.format ?? '3dgs',\n        quality: options.quality ?? 'high',\n        ...(options.input_image ? { input_image: options.input_image } : {}),\n        ...(options.input_images?.length ? { input_images: options.input_images } : {}),\n        ...(options.navEnabled !== undefined ? { navEnabled: options.navEnabled } : {}),\n        ...(options.interactiveMode !== undefined\n          ? { interactiveMode: options.interactiveMode }\n          : {}),\n        ...(options.seed !== undefined ? { seed: options.seed } : {}),\n      });\n\n      // Build a companion .holo composition referencing the generated 3D asset\n      const navLine = result.navmeshUrl ? `\\n  navmesh { url: \"${result.navmeshUrl}\" }` : '';\n      const interactiveLine = options.interactiveMode\n        ? `\\n  physics { enabled: true, collisions: true }`\n        : '';\n\n      const holoCode = `composition \"GeneratedWorld\" {\n  environment {\n    world_asset: \"${result.assetUrl}\"\n    format: \"${result.metadata.format}\"\n    bounds: [${result.metadata.bounds.join(', ')}]\n    prompt: \"${safePrompt}\"\n  }${navLine}${interactiveLine}\n  object \"Camera\" {\n    position: [0, 1.7, 0]\n    @tracked\n  }\n}`;\n\n      return {\n        assetUrl: result.assetUrl,\n        generationId: result.generationId,\n        format: result.metadata.format,\n        ...(result.navmeshUrl ? { navmeshUrl: result.navmeshUrl } : {}),\n        ...(result.pointCloudUrl ? { pointCloudUrl: result.pointCloudUrl } : {}),\n        holoCode,\n        source: 'sovereign-3d',\n        metrics: {\n          ...(result.metadata.splatCount !== undefined\n            ? { splatCount: result.metadata.splatCount }\n            : {}),\n          ...(result.metadata.triangleCount !== undefined\n            ? { triangleCount: result.metadata.triangleCount }\n            : {}),\n          ...(result.metadata.generationMs !== undefined\n            ? { generationMs: result.metadata.generationMs }\n            : {}),\n          bounds: result.metadata.bounds,\n          ...(result.metadata.agentStart ? { agentStart: result.metadata.agentStart } : {}),\n          ...(result.metadata.waypoints ? { waypoints: result.metadata.waypoints } : {}),\n        },\n      };\n    } catch (err) {\n      // Sovereign backend unreachable (network error / offline / fetch failed).\n      // Fall through to PATH 2 (LLM) so generate_world succeeds even when the\n      // 3D service is not yet deployed. Mock mode failures are re-thrown (they\n      // indicate a code bug, not a network outage).\n      if (sovereignMock) throw err;\n      // Log once so operators can see the fallback reason without it being fatal.\n      console.warn(\n        `[generateWorldNative] Sovereign3DAdapter unreachable (${(err as Error).message ?? err}); ` +\n          'falling back to text-LLM path. Set HOLOSCRIPT_SOVEREIGN_MOCK=true to use deterministic mock output instead.'\n      );\n    }\n  }\n\n  // ─── PATH 2: Brittney text-LLM (same proven path as generate_scene) ─────────\n  // Returns a rich .holo world composition — real runnable HoloScript output.\n  // No 3D splat asset; source='text-llm' declares this honestly.\n  const worldPrompt = `Create a complete HoloScript world composition for: ${prompt}.\nInclude an environment block with skybox, lighting, and terrain. Add 3-6 named objects\nthat populate the world. Use traits like @physics, @collidable, @anchor, @world_locked\nwhere appropriate. Return only valid HoloScript code with a composition root.`;\n\n  const aiResult = await tryGenerateWithAI(worldPrompt, 'holo');\n  const rawAiCode = aiResult ? normalizeSceneAIOutput(aiResult.code) : '';\n\n  if (aiResult && isUsableSceneCode(rawAiCode)) {\n    return {\n      holoCode: rawAiCode,\n      format: 'holo',\n      source: 'text-llm',\n      metrics: { generationMs: Date.now() - startMs },\n    };\n  }\n\n  // ─── PATH 3: Heuristic fallback — deterministic, always succeeds ─────────────\n  const interactiveLine = options.interactiveMode\n    ? `\\n  physics { enabled: true, collisions: true }`\n    : '';\n\n  const heuristicCode = `composition \"GeneratedWorld\" {\n  // Generated from: ${safePrompt}\n  environment {\n    skybox: \"gradient\"\n    ambient_light: 0.6\n    fog: 0.02\n  }${interactiveLine}\n\n  object \"Ground\" {\n    geometry: \"plane\"\n    scale: [50, 1, 50]\n    position: [0, 0, 0]\n    @collidable\n    @world_locked\n  }\n\n  object \"Camera\" {\n    position: [0, 1.7, 0]\n    @tracked\n  }\n}`;\n\n  return {\n    holoCode: heuristicCode,\n    format: 'holo',\n    source: 'heuristic',\n    metrics: { generationMs: Date.now() - startMs },\n  };\n}\n\n/**\n * Unified multimodal world generation pipeline.\n *\n * Accepts text, image, and video inputs as one request, routes text/images through\n * the existing native generator, attaches video reconstruction evidence when\n * supplied by the MCP handler, and returns a physics-bearing .holo scene graph\n * with semantic objects, inline colliders, and CAEL provenance.\n */\nexport async function generateWorldFromPrompt(\n  prompt: string,\n  options: WorldPromptGenerationOptions = {}\n): Promise<WorldPromptGenerationResult> {\n  const inputs = normalizeWorldPromptInputs(prompt, options.inputs);\n  const modalities = [...new Set(inputs.map((input) => input.type))] as WorldPromptInputType[];\n  const imageSources = inputs\n    .filter((input) => input.type === 'image')\n    .map((input) => input.data ?? input.url)\n    .filter((source): source is string => typeof source === 'string' && source.trim().length > 0);\n  const foundationPrompt = composeWorldFoundationPrompt(\n    prompt,\n    inputs,\n    options.videoReconstruction\n  );\n\n  const nativeResult = await generateWorldNative(foundationPrompt, {\n    format: options.format,\n    quality: options.quality,\n    input_image: options.input_image ?? imageSources[0],\n    input_images: options.input_images ?? (imageSources.length > 1 ? imageSources : undefined),\n    navEnabled: options.navEnabled ?? true,\n    interactiveMode: options.interactiveMode ?? true,\n    seed: options.seed,\n  });\n\n  const semanticNodes = deriveWorldSemanticNodes(prompt, options.videoReconstruction);\n  const colliderMeshes = deriveWorldColliderMeshes(semanticNodes, options.videoReconstruction);\n  const structuredAssetGraph = deriveStructuredAssetGraph({\n    prompt,\n    inputs,\n    semanticNodes,\n    colliderMeshes,\n    videoReconstruction: options.videoReconstruction,\n  });\n  const provenance = buildWorldFoundationModelProvenance({\n    prompt,\n    inputs,\n    nativeResult,\n    semanticNodes,\n    colliderMeshes,\n    structuredAssetGraph,\n    videoReconstruction: options.videoReconstruction,\n    provider: options.provider,\n    model: options.model,\n    generatedAt: options.generatedAt,\n  });\n\n  const holoCode = attachWorldFoundationSceneGraph(nativeResult.holoCode, {\n    provenance,\n    semanticNodes,\n    colliderMeshes,\n    structuredAssetGraph,\n  });\n\n  return {\n    ...nativeResult,\n    holoCode,\n    inputModalities: modalities,\n    semanticNodes,\n    colliderMeshes,\n    structuredAssetGraph,\n    provenance,\n    ...(options.videoReconstruction ? { videoReconstruction: options.videoReconstruction } : {}),\n  };\n}\n\nfunction normalizeWorldPromptInputs(\n  prompt: string,\n  inputs: readonly WorldPromptInput[] | undefined\n): WorldPromptInput[] {\n  const normalized: WorldPromptInput[] = [];\n  if (prompt.trim()) {\n    normalized.push({ type: 'text', text: prompt.trim(), label: 'prompt' });\n  }\n  for (const input of inputs ?? []) {\n    if (!input || !['text', 'image', 'video'].includes(input.type)) continue;\n    if (input.type === 'text' && !input.text?.trim()) continue;\n    if (input.type !== 'text' && !input.url?.trim() && !input.data?.trim()) continue;\n    normalized.push({\n      ...input,\n      text: input.text?.trim(),\n      url: input.url?.trim(),\n      data: input.data?.trim(),\n      label: input.label?.trim(),\n    });\n  }\n  return normalized;\n}\n\nfunction composeWorldFoundationPrompt(\n  prompt: string,\n  inputs: readonly WorldPromptInput[],\n  reconstruction?: VideoReconstructionSummary\n): string {\n  const modalityList = [...new Set(inputs.map((input) => input.type))].join(', ') || 'text';\n  const videoLine = reconstruction\n    ? ` Video reconstruction session ${reconstruction.sessionId} replay ${reconstruction.replayFingerprint ?? 'unavailable'} is available as geometric evidence.`\n    : '';\n  return [\n    prompt || 'Generate a navigable HoloScript world.',\n    `Inputs: ${modalityList}.`,\n    'Emit a semantic scene graph with material traits, physics traits, and collider geometry suitable for compile_to_sdf and compile_to_urdf.',\n    videoLine,\n  ]\n    .filter(Boolean)\n    .join(' ');\n}\n\nfunction deriveWorldSemanticNodes(\n  prompt: string,\n  reconstruction?: VideoReconstructionSummary\n): WorldSemanticNode[] {\n  const landmarkName = deriveLandmarkName(prompt);\n  const nodes: WorldSemanticNode[] = [\n    {\n      id: 'terrain_surface',\n      name: 'TerrainSurface',\n      kind: 'terrain',\n      geometry: 'plane',\n      position: [0, 0, 0],\n      scale: [48, 1, 48],\n      material: 'generated_walkable_surface',\n    },\n    {\n      id: 'primary_landmark',\n      name: landmarkName,\n      kind: 'landmark',\n      geometry: 'box',\n      position: [0, 1.5, -6],\n      scale: [4, 3, 4],\n      material: 'semantic_world_landmark',\n    },\n    {\n      id: 'agent_start',\n      name: 'AgentStart',\n      kind: 'agent_start',\n      geometry: 'capsule',\n      position: [0, 1.7, 4],\n      scale: [0.4, 1.7, 0.4],\n      material: 'spawn_anchor',\n    },\n  ];\n\n  if (reconstruction) {\n    nodes.push({\n      id: 'video_reconstruction_bounds',\n      name: 'VideoReconstructionBounds',\n      kind: 'video_reconstruction',\n      geometry: 'mesh',\n      position: [0, 1, 0],\n      scale: [10, 2, 10],\n      material: 'holomap_video_geometry',\n    });\n  }\n\n  return nodes;\n}\n\nfunction deriveWorldColliderMeshes(\n  nodes: readonly WorldSemanticNode[],\n  reconstruction?: VideoReconstructionSummary\n): WorldColliderMesh[] {\n  const colliders: WorldColliderMesh[] = nodes\n    .filter((node) => node.kind !== 'agent_start')\n    .map((node) => ({\n      id: `${node.id}_collider`,\n      nodeId: node.id,\n      shape: node.geometry === 'mesh' ? ('mesh' as const) : ('box' as const),\n      position: node.position,\n      size: node.scale,\n      source:\n        node.kind === 'video_reconstruction'\n          ? ('video_reconstruction' as const)\n          : ('semantic_node' as const),\n    }));\n\n  if (reconstruction) {\n    colliders.push({\n      id: 'holomap_navmesh_collider',\n      nodeId: 'video_reconstruction_bounds',\n      shape: 'mesh',\n      position: [0, 0.05, 0],\n      size: [10, 0.1, 10],\n      source: 'navmesh',\n    });\n  }\n\n  return colliders;\n}\n\nfunction deriveStructuredAssetGraph(input: {\n  prompt: string;\n  inputs: readonly WorldPromptInput[];\n  semanticNodes: readonly WorldSemanticNode[];\n  colliderMeshes: readonly WorldColliderMesh[];\n  videoReconstruction?: VideoReconstructionSummary;\n}): WorldStructuredAssetGraph {\n  const inputModalities = [\n    ...new Set(input.inputs.map((worldInput) => worldInput.type)),\n  ] as WorldPromptInputType[];\n  const inputLabels = input.inputs.map(describeWorldPromptInput);\n  const graphId = `sag_${stableHash(\n    JSON.stringify({\n      prompt: input.prompt,\n      inputs: inputLabels,\n      replay: input.videoReconstruction?.replayFingerprint,\n    })\n  )}`;\n\n  const nodes: WorldAssetGraphNode[] = input.semanticNodes.map((node) => ({\n    id: node.id,\n    name: node.name,\n    kind: mapSemanticNodeToAssetKind(node.kind),\n    geometry: node.geometry,\n    position: node.position,\n    scale: node.scale,\n    material: node.material,\n    provenance:\n      node.kind === 'terrain'\n        ? 'generated'\n        : node.kind === 'agent_start'\n          ? 'generated'\n          : node.kind === 'video_reconstruction'\n            ? 'observed'\n            : 'inferred',\n    confidence:\n      node.kind === 'video_reconstruction' ? 0.92 : node.kind === 'agent_start' ? 1 : 0.82,\n    sourceInputLabels: inputLabels,\n    sourceNodeIds: [node.id],\n    traits: traitsForSemanticNode(node),\n    ...(node.kind === 'terrain' ? { navigationRole: 'walkable' as const } : {}),\n    ...(node.kind === 'agent_start' ? { navigationRole: 'spawn' as const } : {}),\n    ...(node.kind === 'landmark' ? { navigationRole: 'target' as const } : {}),\n    ...(node.kind === 'video_reconstruction' ? { colliderRole: 'static' as const } : {}),\n    ...(node.kind !== 'agent_start' && node.kind !== 'video_reconstruction'\n      ? { colliderRole: 'static' as const }\n      : {}),\n  }));\n\n  const imageInputs = input.inputs.filter((worldInput) => worldInput.type === 'image');\n  imageInputs.forEach((worldInput, index) => {\n    nodes.push({\n      id: `image_observation_${index + 1}`,\n      name: `ImageObservation${index + 1}`,\n      kind: 'semantic_observation',\n      geometry: 'plane',\n      position: [-6 + index * 2.5, 2.2, -3.5],\n      scale: [2.2, 1.25, 0.04],\n      material: 'source_image_semantic_observation',\n      provenance: 'observed',\n      confidence: 0.88,\n      sourceInputLabels: [describeWorldPromptInput(worldInput, index)],\n      sourceNodeIds: [],\n      traits: ['@semantic_input', '@image_observation', '@structured_asset_seed'],\n    });\n  });\n\n  const hasOcclusionEvidence = imageInputs.length > 0 || Boolean(input.videoReconstruction);\n  if (hasOcclusionEvidence) {\n    nodes.push({\n      id: 'occluded_volume_completion',\n      name: 'OccludedVolumeCompletion',\n      kind: 'occluder_completion',\n      geometry: 'box',\n      position: [0, 1.35, -8.5],\n      scale: [5.5, 2.7, 1.5],\n      material: 'completed_backside_geometry',\n      provenance: 'completed',\n      confidence: input.videoReconstruction ? 0.72 : 0.64,\n      sourceInputLabels: inputLabels,\n      sourceNodeIds: input.semanticNodes.map((node) => node.id),\n      traits: ['@occlusion_completed', '@collidable', '@world_locked'],\n      colliderRole: 'static',\n    });\n  }\n\n  const terrain = input.semanticNodes.find((node) => node.kind === 'terrain');\n  const landmark = input.semanticNodes.find((node) => node.kind === 'landmark');\n  const agentStart = input.semanticNodes.find((node) => node.kind === 'agent_start');\n  const edges: WorldAssetGraphEdge[] = [];\n  const addEdge = (\n    from: string | undefined,\n    to: string | undefined,\n    relationship: WorldAssetGraphEdge['relationship'],\n    confidence: number\n  ): void => {\n    if (!from || !to) return;\n    edges.push({\n      id: `edge_${edges.length + 1}_${relationship}`,\n      from,\n      to,\n      relationship,\n      confidence,\n    });\n  };\n\n  addEdge(terrain?.id, landmark?.id, 'supports', 0.86);\n  addEdge(terrain?.id, agentStart?.id, 'supports', 0.94);\n  addEdge(agentStart?.id, landmark?.id, 'leads_to', 0.81);\n\n  for (const observation of nodes.filter((node) => node.kind === 'semantic_observation')) {\n    addEdge(observation.id, landmark?.id, 'observes', 0.78);\n    addEdge(observation.id, 'occluded_volume_completion', 'anchors', 0.66);\n  }\n\n  if (nodes.some((node) => node.id === 'occluded_volume_completion')) {\n    addEdge(landmark?.id, 'occluded_volume_completion', 'occludes', 0.62);\n    addEdge('occluded_volume_completion', landmark?.id, 'completes', 0.7);\n  }\n\n  if (input.videoReconstruction) {\n    addEdge('video_reconstruction_bounds', landmark?.id, 'anchors', 0.84);\n    addEdge('video_reconstruction_bounds', 'occluded_volume_completion', 'anchors', 0.74);\n  }\n\n  const navigationPath: [number, number, number][] = [\n    agentStart?.position ?? [0, 1.7, 4],\n    [0, 1.2, 0],\n    landmark?.position ?? [0, 1.5, -6],\n  ];\n\n  const unsigned = {\n    schema: 'holoscript.structured_asset_graph.v1' as const,\n    graphId,\n    sourcePromptHash: stableHash(input.prompt),\n    inputModalities,\n    nodes,\n    edges,\n    navigationPath,\n    colliderMeshIds: input.colliderMeshes.map((collider) => collider.id),\n    occlusionCompletions: nodes\n      .filter((node) => node.provenance === 'completed')\n      .map((node) => node.id),\n    materialAtlas: buildWorldAssetMaterialAtlas(nodes),\n    textureMapRefs: buildTextureMapRefs(input.inputs),\n    matrixRefs: nodes.map(\n      (node) => `${node.id}:position=${formatVec(node.position)};scale=${formatVec(node.scale)}`\n    ),\n    benchmarkBoundary: 'marble_gap_sovereign_structured_asset_graph' as const,\n  };\n\n  return {\n    ...unsigned,\n    graphHash: stableHash(JSON.stringify(unsigned)),\n  };\n}\n\nfunction buildWorldFoundationModelProvenance(input: {\n  prompt: string;\n  inputs: readonly WorldPromptInput[];\n  nativeResult: NativeWorldGenerationResult;\n  semanticNodes: readonly WorldSemanticNode[];\n  colliderMeshes: readonly WorldColliderMesh[];\n  structuredAssetGraph?: WorldStructuredAssetGraph;\n  videoReconstruction?: VideoReconstructionSummary;\n  provider?: string;\n  model?: string;\n  generatedAt?: string;\n}): WorldFoundationModelProvenance {\n  const inputModalities = [\n    ...new Set(input.inputs.map((worldInput) => worldInput.type)),\n  ] as WorldPromptInputType[];\n  const sourceAssetUrls = input.inputs\n    .map((worldInput) => worldInput.url)\n    .filter((url): url is string => typeof url === 'string' && url.length > 0);\n  if (input.nativeResult.assetUrl) sourceAssetUrls.push(input.nativeResult.assetUrl);\n  if (input.nativeResult.navmeshUrl) sourceAssetUrls.push(input.nativeResult.navmeshUrl);\n\n  const generatedAt = input.generatedAt ?? new Date(0).toISOString();\n  const synthesisId =\n    input.nativeResult.generationId ??\n    `wfm_${stableHash(\n      JSON.stringify({\n        prompt: input.prompt,\n        modalities: inputModalities,\n        replay: input.videoReconstruction?.replayFingerprint,\n      })\n    )}`;\n\n  const unsigned = {\n    schema: 'cael.world_foundation_model.v1' as const,\n    synthesisId,\n    provider: input.provider ?? input.nativeResult.source,\n    model: input.model ?? defaultWorldFoundationModel(input.nativeResult.source),\n    generatedAt,\n    promptHash: stableHash(input.prompt),\n    inputModalities,\n    semanticNodeCount: input.semanticNodes.length,\n    colliderCount: input.colliderMeshes.length,\n    videoReconstructionSessionId: input.videoReconstruction?.sessionId,\n    replayFingerprint: input.videoReconstruction?.replayFingerprint,\n    sourceAssetUrls,\n    structuredAssetGraphHash: input.structuredAssetGraph?.graphHash,\n    structuredAssetGraphNodeCount: input.structuredAssetGraph?.nodes.length,\n    occlusionCompletionCount: input.structuredAssetGraph?.occlusionCompletions.length,\n  };\n\n  return {\n    ...unsigned,\n    receiptHash: stableHash(JSON.stringify(unsigned)),\n  };\n}\n\nfunction attachWorldFoundationSceneGraph(\n  holoCode: string,\n  input: {\n    provenance: WorldFoundationModelProvenance;\n    semanticNodes: readonly WorldSemanticNode[];\n    colliderMeshes: readonly WorldColliderMesh[];\n    structuredAssetGraph?: WorldStructuredAssetGraph;\n  }\n): string {\n  const blocks = [\n    renderWorldFoundationProvenanceObject(input.provenance),\n    ...(input.structuredAssetGraph\n      ? [renderStructuredAssetGraphObject(input.structuredAssetGraph)]\n      : []),\n    ...input.semanticNodes.map(renderSemanticNodeObject),\n    ...input.colliderMeshes.map(renderColliderObject),\n    ...(input.structuredAssetGraph\n      ? input.structuredAssetGraph.nodes.map((node) =>\n          renderAssetGraphNodeObject(node, input.structuredAssetGraph?.graphId ?? '')\n        )\n      : []),\n  ];\n  const trimmed = holoCode.trim();\n  const rootClose = trimmed.lastIndexOf('}');\n  if (rootClose < 0) {\n    return `composition \"GeneratedWorld\" {\\n${blocks.join('\\n\\n')}\\n}`;\n  }\n  return `${trimmed.slice(0, rootClose).trimEnd()}\\n\\n${blocks.join('\\n\\n')}\\n${trimmed.slice(rootClose)}`;\n}\n\nfunction renderWorldFoundationProvenanceObject(provenance: WorldFoundationModelProvenance): string {\n  const lines = [\n    '  object \"WorldFoundationProvenance\" {',\n    '    @world_foundation_model {',\n    `      schema: \"${provenance.schema}\"`,\n    `      synthesis_id: \"${escapeHoloString(provenance.synthesisId)}\"`,\n    `      provider: \"${escapeHoloString(provenance.provider)}\"`,\n    `      model: \"${escapeHoloString(provenance.model)}\"`,\n    `      generated_at: \"${escapeHoloString(provenance.generatedAt)}\"`,\n    `      prompt_hash: \"${provenance.promptHash}\"`,\n    `      input_modalities: ${renderStringList(provenance.inputModalities)}`,\n    `      semantic_node_count: ${provenance.semanticNodeCount}`,\n    `      collider_count: ${provenance.colliderCount}`,\n    `      source_asset_urls: ${renderStringList(provenance.sourceAssetUrls)}`,\n  ];\n  if (provenance.structuredAssetGraphHash) {\n    lines.push(\n      `      structured_asset_graph_hash: \"${provenance.structuredAssetGraphHash}\"`,\n      `      structured_asset_graph_node_count: ${provenance.structuredAssetGraphNodeCount ?? 0}`,\n      `      occlusion_completion_count: ${provenance.occlusionCompletionCount ?? 0}`\n    );\n  }\n  lines.push(`      receipt_hash: \"${provenance.receiptHash}\"`);\n  if (provenance.videoReconstructionSessionId) {\n    lines.push(\n      `      video_reconstruction_session_id: \"${escapeHoloString(provenance.videoReconstructionSessionId)}\"`\n    );\n  }\n  if (provenance.replayFingerprint) {\n    lines.push(`      replay_fingerprint: \"${escapeHoloString(provenance.replayFingerprint)}\"`);\n  }\n  lines.push('    }');\n  lines.push('  }');\n  return lines.join('\\n');\n}\n\nfunction renderStructuredAssetGraphObject(graph: WorldStructuredAssetGraph): string {\n  const materialAtlas = Object.entries(graph.materialAtlas).map(\n    ([material, ref]) => `${material}:${ref}`\n  );\n  return `  object \"StructuredAssetGraph\" {\n    @structured_asset_graph {\n      schema: \"${graph.schema}\"\n      graph_id: \"${graph.graphId}\"\n      graph_hash: \"${graph.graphHash}\"\n      source_prompt_hash: \"${graph.sourcePromptHash}\"\n      benchmark_boundary: \"${graph.benchmarkBoundary}\"\n      input_modalities: ${renderStringList(graph.inputModalities)}\n      node_count: ${graph.nodes.length}\n      edge_count: ${graph.edges.length}\n      collider_mesh_ids: ${renderStringList(graph.colliderMeshIds)}\n      occlusion_completions: ${renderStringList(graph.occlusionCompletions)}\n      navigation_path: ${renderStringList(graph.navigationPath.map(formatVec))}\n      material_atlas: ${renderStringList(materialAtlas)}\n      texture_map_refs: ${renderStringList(graph.textureMapRefs)}\n      matrix_refs: ${renderStringList(graph.matrixRefs)}\n    }\n  }`;\n}\n\nfunction renderAssetGraphNodeObject(node: WorldAssetGraphNode, graphId: string): string {\n  return `  object \"${toPascalCase(`asset_graph_${node.id}`)}\" {\n    geometry: \"${node.geometry}\"\n    position: ${formatVec(node.position)}\n    scale: ${formatVec(node.scale)}\n    @structured_asset_node {\n      graph_id: \"${graphId}\"\n      node_id: \"${node.id}\"\n      kind: \"${node.kind}\"\n      provenance: \"${node.provenance}\"\n      confidence: ${Number(node.confidence.toFixed(3))}\n      material: \"${node.material}\"\n      source_inputs: ${renderStringList(node.sourceInputLabels)}\n      source_nodes: ${renderStringList(node.sourceNodeIds)}\n      traits: ${renderStringList(node.traits)}\n      navigation_role: \"${node.navigationRole ?? 'none'}\"\n      collider_role: \"${node.colliderRole ?? 'none'}\"\n    }\n    @material { preset: \"${node.material}\" }\n  }`;\n}\n\nfunction renderSemanticNodeObject(node: WorldSemanticNode): string {\n  return `  object \"${node.name}\" {\n    geometry: \"${node.geometry}\"\n    position: ${formatVec(node.position)}\n    scale: ${formatVec(node.scale)}\n    @semantic_node {\n      node_id: \"${node.id}\"\n      kind: \"${node.kind}\"\n      material: \"${node.material}\"\n    }\n    @material { preset: \"${node.material}\" }\n    @physics { mass: ${node.kind === 'terrain' ? 0 : 1} }\n    @collidable\n  }`;\n}\n\nfunction renderColliderObject(collider: WorldColliderMesh): string {\n  return `  object \"${toPascalCase(collider.id)}\" {\n    geometry: \"box\"\n    position: ${formatVec(collider.position)}\n    scale: ${formatVec(collider.size)}\n    @collider {\n      shape: \"${collider.shape}\"\n      source_node: \"${collider.nodeId}\"\n      source: \"${collider.source}\"\n      size: ${formatVec(collider.size)}\n    }\n    @physics { mass: 0 }\n    @collidable\n  }`;\n}\n\nfunction defaultWorldFoundationModel(source: NativeWorldGenerationResult['source']): string {\n  if (source === 'sovereign-3d') return 'sovereign-3d-world-foundation';\n  if (source === 'text-llm') return 'text-to-world-semantic-synthesis';\n  return 'heuristic-world-foundation-fallback';\n}\n\nfunction describeWorldPromptInput(input: WorldPromptInput, index = 0): string {\n  if (input.label?.trim()) return input.label.trim();\n  if (input.url?.trim()) return input.url.trim();\n  if (input.type === 'text' && input.text?.trim()) return 'prompt';\n  if (input.data?.trim()) return `${input.type}_embedded_${stableHash(input.data.trim())}`;\n  return `${input.type}_${index + 1}`;\n}\n\nfunction mapSemanticNodeToAssetKind(kind: WorldSemanticNode['kind']): WorldAssetGraphNodeKind {\n  if (kind === 'video_reconstruction') return 'video_reconstruction';\n  if (kind === 'agent_start') return 'agent_start';\n  if (kind === 'terrain') return 'terrain';\n  return 'landmark';\n}\n\nfunction traitsForSemanticNode(node: WorldSemanticNode): string[] {\n  if (node.kind === 'terrain') return ['@walkable', '@collidable', '@world_locked'];\n  if (node.kind === 'agent_start') return ['@spawn_anchor', '@tracked'];\n  if (node.kind === 'video_reconstruction') return ['@holomap_evidence', '@collidable'];\n  return ['@semantic_landmark', '@collidable', '@anchor'];\n}\n\nfunction buildWorldAssetMaterialAtlas(\n  nodes: readonly Pick<WorldAssetGraphNode, 'material'>[]\n): Record<string, string> {\n  const atlas: Record<string, string> = {};\n  for (const material of [...new Set(nodes.map((node) => node.material))].sort()) {\n    atlas[material] = `materials/generated/${material}.mat`;\n  }\n  return atlas;\n}\n\nfunction buildTextureMapRefs(inputs: readonly WorldPromptInput[]): string[] {\n  return inputs\n    .filter((input) => input.type === 'image')\n    .map((input, index) => {\n      if (input.url?.trim()) return input.url.trim();\n      if (input.data?.trim()) return `embedded_image_${index + 1}:${stableHash(input.data.trim())}`;\n      return input.label?.trim() ?? `image_${index + 1}`;\n    });\n}\n\nfunction deriveLandmarkName(prompt: string): string {\n  const words = prompt\n    .split(/[^a-zA-Z0-9]+/)\n    .filter((word) => word.length > 2 && !/^(the|and|with|from|into|for|that|this)$/i.test(word));\n  return `${toPascalCase(words.slice(0, 3).join('_') || 'Primary')}Landmark`;\n}\n\nfunction toPascalCase(value: string): string {\n  const out = value\n    .split(/[^a-zA-Z0-9]+/)\n    .filter(Boolean)\n    .map((part) => part[0].toUpperCase() + part.slice(1))\n    .join('');\n  return out || 'GeneratedObject';\n}\n\nfunction formatVec(v: readonly number[]): string {\n  return `[${v.map((n) => Number(n.toFixed(6))).join(', ')}]`;\n}\n\nfunction renderStringList(values: readonly string[]): string {\n  return `[${values.map((value) => `\"${escapeHoloString(value)}\"`).join(', ')}]`;\n}\n\nfunction escapeHoloString(value: string): string {\n  return value.replace(/\\\\/g, '\\\\\\\\').replace(/\"/g, '\\\\\"').replace(/\\n/g, ' ');\n}\n\nfunction stableHash(value: string): string {\n  let hash = 0x811c9dc5;\n  for (let i = 0; i < value.length; i++) {\n    hash ^= value.charCodeAt(i);\n    hash = Math.imul(hash, 0x01000193);\n  }\n  return (hash >>> 0).toString(36).padStart(7, '0');\n}\n\n/**\n * Suggest traits based on object description\n */\nexport function suggestTraits(\n  description: string,\n  context?: string\n): {\n  traits: string[];\n  reasoning: Record<string, string>;\n  confidence: number;\n} {\n  const lowerDesc = (description + ' ' + (context || '')).toLowerCase();\n  const suggestedTraits = new Set<string>();\n  const reasoning: Record<string, string> = {};\n\n  for (const [keyword, traits] of Object.entries(TRAIT_KEYWORDS)) {\n    if (lowerDesc.includes(keyword)) {\n      for (const trait of traits) {\n        if (!suggestedTraits.has(trait)) {\n          suggestedTraits.add(trait);\n          reasoning[trait] = `Suggested because description mentions \"${keyword}\"`;\n        }\n      }\n    }\n  }\n\n  // Default traits for interactive objects\n  if (suggestedTraits.size === 0) {\n    suggestedTraits.add('@pointable');\n    reasoning['@pointable'] = 'Default trait for interactive objects';\n  }\n\n  // Always suggest @collidable if physics-related\n  if (suggestedTraits.has('@physics') && !suggestedTraits.has('@collidable')) {\n    suggestedTraits.add('@collidable');\n    reasoning['@collidable'] = 'Required for physics interactions';\n  }\n\n  const traits = Array.from(suggestedTraits);\n  const confidence = Math.min(0.95, 0.5 + traits.length * 0.1);\n\n  return { traits, reasoning, confidence };\n}\n\n/**\n * Suggest universal v6 traits based on service/infrastructure description.\n * Covers 8 domains: service, contract, data, network, pipeline, metric, container, resilience.\n */\nexport function suggestUniversalTraits(\n  description: string,\n  domain?: string,\n  context?: string\n): {\n  traits: string[];\n  domains: Record<string, string[]>;\n  reasoning: Record<string, string>;\n  confidence: number;\n} {\n  const lowerDesc = (description + ' ' + (context || '')).toLowerCase();\n  const suggestedTraits = new Set<string>();\n  const reasoning: Record<string, string> = {};\n  const domainTraits: Record<string, Set<string>> = {};\n\n  for (const [keyword, entry] of Object.entries(UNIVERSAL_TRAIT_KEYWORDS)) {\n    // If domain filter is set, skip non-matching domains\n    if (domain && entry.domain !== domain) continue;\n\n    if (lowerDesc.includes(keyword)) {\n      if (!domainTraits[entry.domain]) domainTraits[entry.domain] = new Set();\n\n      for (const trait of entry.traits) {\n        if (!suggestedTraits.has(trait)) {\n          suggestedTraits.add(trait);\n          domainTraits[entry.domain].add(trait);\n          reasoning[trait] = `Matched keyword \"${keyword}\" in ${entry.domain} domain`;\n        }\n      }\n    }\n  }\n\n  // Cross-domain inference: if service traits are present, suggest health_check\n  if (domainTraits['service']?.size && !suggestedTraits.has('@health_check')) {\n    suggestedTraits.add('@health_check');\n    if (!domainTraits['metric']) domainTraits['metric'] = new Set();\n    domainTraits['metric'].add('@health_check');\n    reasoning['@health_check'] = 'Auto-suggested: services should expose health checks';\n  }\n\n  // If pipeline traits but no resilience, suggest retry + circuit_breaker\n  if (domainTraits['pipeline']?.size && !domainTraits['resilience']?.size) {\n    for (const trait of ['@retry', '@circuit_breaker']) {\n      suggestedTraits.add(trait);\n      if (!domainTraits['resilience']) domainTraits['resilience'] = new Set();\n      domainTraits['resilience'].add(trait);\n      reasoning[trait] = 'Auto-suggested: pipelines benefit from resilience patterns';\n    }\n  }\n\n  // If data traits but no metric, suggest structured_log\n  if (domainTraits['data']?.size && !domainTraits['metric']?.size) {\n    suggestedTraits.add('@structured_log');\n    if (!domainTraits['metric']) domainTraits['metric'] = new Set();\n    domainTraits['metric'].add('@structured_log');\n    reasoning['@structured_log'] =\n      'Auto-suggested: data operations benefit from structured logging';\n  }\n\n  // Default if nothing matched\n  if (suggestedTraits.size === 0) {\n    suggestedTraits.add('@service');\n    suggestedTraits.add('@endpoint');\n    reasoning['@service'] = 'Default trait for service descriptions';\n    reasoning['@endpoint'] = 'Default trait for service descriptions';\n    domainTraits['service'] = new Set(['@service', '@endpoint']);\n  }\n\n  const traits = Array.from(suggestedTraits);\n  const domains: Record<string, string[]> = {};\n  for (const [d, set] of Object.entries(domainTraits)) {\n    domains[d] = Array.from(set);\n  }\n\n  const confidence = Math.min(0.95, 0.4 + traits.length * 0.05 + Object.keys(domains).length * 0.1);\n\n  return { traits, domains, reasoning, confidence };\n}\n\n/**\n * Generate an object from natural language description\n */\nexport function generateObject(\n  description: string,\n  options: GenerateOptions = {}\n): {\n  code: string;\n  traits: string[];\n  geometry: string;\n  format: string;\n} {\n  const format = options.format || 'hsplus';\n  const lowerDesc = description.toLowerCase();\n\n  // Extract geometry\n  let geometry = 'sphere'; // default\n  for (const [keyword, geo] of Object.entries(GEOMETRY_KEYWORDS)) {\n    if (lowerDesc.includes(keyword)) {\n      geometry = geo;\n      break;\n    }\n  }\n\n  // Extract color\n  let color = '#00ffff'; // default cyan\n  for (const [keyword, hex] of Object.entries(COLOR_KEYWORDS)) {\n    if (lowerDesc.includes(keyword)) {\n      color = hex;\n      break;\n    }\n  }\n\n  // Extract material preset (additive — does not replace the primitive-geometry\n  // fallback above, which is still correct for genuine placeholder/test requests).\n  // When a material-flavored keyword is present, richen the generated object with a\n  // named @material_preset trait instead of leaving it flat-color-only.\n  let materialPreset: string | undefined;\n  for (const [keyword, preset] of Object.entries(MATERIAL_PRESET_KEYWORDS)) {\n    if (lowerDesc.includes(keyword)) {\n      materialPreset = preset;\n      break;\n    }\n  }\n\n  // Get traits\n  const { traits } = suggestTraits(description);\n  if (materialPreset) {\n    traits.push(`@material_preset(\"${materialPreset}\")`);\n  }\n\n  // Extract name\n  const words = description.split(/\\s+/);\n  const nameWord = words.find((w) => /^[A-Z]/.test(w)) || words[words.length - 1] || 'Object';\n  const objectName = nameWord.replace(/[^a-zA-Z0-9]/g, '');\n\n  // Generate code based on format\n  let code: string;\n\n  if (format === 'holo') {\n    code = generateHoloObject(objectName, geometry, color, traits, options.includeDocs);\n  } else if (format === 'hsplus') {\n    code = generateHsplusObject(objectName, geometry, color, traits, options.includeDocs);\n  } else {\n    code = generateHsObject(objectName, geometry, color, traits, options.includeDocs);\n  }\n\n  return { code, traits, geometry, format };\n}\n\nfunction generateHoloObject(\n  name: string,\n  geometry: string,\n  color: string,\n  traits: string[],\n  docs?: boolean\n): string {\n  const traitsStr = traits.map((t) => `    ${t}`).join('\\n');\n  const docComment = docs ? `  // ${name} - Generated from natural language description\\n` : '';\n\n  return `${docComment}  template \"${name}Template\" {\n${traitsStr}\n    geometry: \"${geometry}\"\n    color: \"${color}\"\n  }\n\n  object \"${name}\" using \"${name}Template\" {\n    position: [0, 1, 0]\n  }`;\n}\n\nfunction generateHsplusObject(\n  name: string,\n  geometry: string,\n  color: string,\n  traits: string[],\n  docs?: boolean\n): string {\n  const traitsStr = traits.map((t) => `  ${t}`).join('\\n');\n  const docComment = docs ? `// ${name} - Generated from natural language description\\n` : '';\n\n  return `${docComment}composition \"${name}Scene\" {\n  template \"${name}Template\" {\n${traitsStr}\n    geometry: \"${geometry}\"\n    color: \"${color}\"\n  }\n\n  object \"${name}\" using \"${name}Template\" {\n    position: [0, 1, 0]\n  }\n}`;\n}\n\nfunction generateHsObject(\n  name: string,\n  geometry: string,\n  color: string,\n  traits: string[],\n  docs?: boolean\n): string {\n  const traitsStr = traits.map((t) => `  ${t}`).join('\\n');\n  const docComment = docs ? `// ${name} - Generated from natural language description\\n` : '';\n\n  return `${docComment}composition \"${name}Scene\" {\n  template \"${name}Template\" {\n${traitsStr}\n    geometry: \"${geometry}\"\n    color: \"${color}\"\n  }\n\n  object \"${name}\" using \"${name}Template\" {\n    position: [0, 1, 0]\n  }\n}`;\n}\n\n/**\n * Generate a complete scene from natural language description\n */\nexport function generateScene(\n  description: string,\n  options: SceneOptions = {}\n): {\n  code: string;\n  stats: {\n    objects: number;\n    traits: number;\n    lines: number;\n  };\n} {\n  const style = options.style || 'detailed';\n  const features = options.features || [];\n  const _lowerDesc = description.toLowerCase();\n\n  // Parse scene elements from description\n  const elements = parseSceneElements(description);\n\n  // Generate objects\n  const objects = elements.objects.map((obj) => {\n    const { code } = generateObject(obj.description, {\n      format: 'holo',\n      includeDocs: style !== 'minimal',\n    });\n    return code;\n  });\n\n  // Generate environment\n  const environment = generateEnvironment(description, style);\n\n  // Generate logic if needed\n  const logic = features.includes('logic') ? generateLogic(elements) : '';\n\n  // Combine into composition\n  const code = `composition \"${elements.name}\" {\n  ${environment}\n\n${objects.map((o) => '  ' + o.replace(/\\n/g, '\\n  ')).join('\\n\\n')}\n${logic ? '\\n  ' + logic : ''}}`;\n\n  return {\n    code,\n    stats: {\n      objects: objects.length,\n      traits: (code.match(/@\\w+/g) || []).length,\n      lines: code.split('\\n').length,\n    },\n  };\n}\n\ninterface SceneElement {\n  name: string;\n  objects: { name: string; description: string }[];\n  environment: string[];\n}\n\nfunction parseSceneElements(description: string): SceneElement {\n  const _words = description.split(/\\s+/);\n\n  // Extract scene name\n  const nameMatch = description.match(\n    /(a|an|the)?\\s*([a-z]+(?:\\s+[a-z]+)?)\\s*(scene|world|room|space)/i\n  );\n  const name = nameMatch ? capitalize(nameMatch[2]) : 'Generated Scene';\n\n  // Extract objects (simplified parsing)\n  const objectMatches = description.match(\n    /(?:with|containing|featuring|has|include)\\s+([^,]+(?:,\\s*[^,]+)*)/i\n  );\n  const objects: { name: string; description: string }[] = [];\n\n  if (objectMatches) {\n    const items = objectMatches[1].split(/,\\s*and\\s*|,\\s*|\\s+and\\s+/);\n    for (const item of items) {\n      const trimmed = item.trim();\n      if (trimmed) {\n        objects.push({\n          name: extractObjectName(trimmed),\n          description: trimmed,\n        });\n      }\n    }\n  }\n\n  // Default object if none extracted\n  if (objects.length === 0) {\n    objects.push({\n      name: 'MainObject',\n      description: description,\n    });\n  }\n\n  // Extract environment hints\n  const environment: string[] = [];\n  if (description.includes('forest') || description.includes('nature')) environment.push('nature');\n  if (description.includes('space') || description.includes('galaxy')) environment.push('space');\n  if (description.includes('night')) environment.push('night');\n  if (description.includes('day') || description.includes('sunny')) environment.push('day');\n\n  return { name, objects, environment };\n}\n\nfunction extractObjectName(description: string): string {\n  const words = description.split(/\\s+/);\n  const lastWord = words[words.length - 1];\n  return capitalize(lastWord.replace(/[^a-zA-Z0-9]/g, ''));\n}\n\nfunction generateEnvironment(description: string, style: string): string {\n  const lowerDesc = description.toLowerCase();\n\n  // Determine skybox\n  let skybox = 'gradient';\n  if (lowerDesc.includes('forest') || lowerDesc.includes('nature')) skybox = 'forest';\n  if (lowerDesc.includes('space') || lowerDesc.includes('galaxy') || lowerDesc.includes('nebula'))\n    skybox = 'nebula';\n  if (lowerDesc.includes('sunset') || lowerDesc.includes('sunrise')) skybox = 'sunset';\n  if (lowerDesc.includes('night') || lowerDesc.includes('moon')) skybox = 'night';\n  if (lowerDesc.includes('ocean') || lowerDesc.includes('beach')) skybox = 'ocean';\n\n  // Determine lighting\n  let ambientLight = 0.3;\n  if (lowerDesc.includes('dark') || lowerDesc.includes('night')) ambientLight = 0.1;\n  if (lowerDesc.includes('bright') || lowerDesc.includes('sunny')) ambientLight = 0.7;\n\n  if (style === 'minimal') {\n    return `environment {\n    skybox: \"${skybox}\"\n  }`;\n  }\n\n  return `environment {\n    skybox: \"${skybox}\"\n    ambient_light: ${ambientLight}\n    fog: { enabled: true, density: 0.01 }\n  }`;\n}\n\nfunction generateLogic(elements: SceneElement): string {\n  if (elements.objects.length < 2) return '';\n\n  return `logic {\n    // Auto-generated interaction logic\n    on_scene_start() {\n      console.debug(\"Scene loaded!\")\n    }\n  }`;\n}\n\n/**\n * Suggest Semantic2D UI traits based on element description\n */\nexport function suggest2DTraits(\n  description: string,\n  context?: string\n): {\n  traits: string[];\n  reasoning: Record<string, string>;\n} {\n  const suggestedTraits = new Set<string>();\n  const reasoning: Record<string, string> = {};\n  const lowerDesc = (description + ' ' + (context || '')).toLowerCase();\n\n  const keywords: Record<string, string[]> = {\n    button: ['@semantic_entity', '@particle_feedback'],\n    click: ['@semantic_entity', '@particle_feedback'],\n    layout: ['@semantic_layout'],\n    flex: ['@semantic_layout'],\n    grid: ['@semantic_layout'],\n    color: ['@dynamic_visual'],\n    theme: ['@dynamic_visual'],\n    dashboard: ['@2d_canvas', '@semantic_layout'],\n    screen: ['@2d_canvas'],\n    agent: ['@agent_attention'],\n    bounty: ['@agent_attention'],\n    intent: ['@intent_driven'],\n    action: ['@intent_driven'],\n    metric: ['@live_metric'],\n    data: ['@live_metric'],\n    chart: ['@live_metric'],\n    number: ['@live_metric'],\n  };\n\n  for (const [key, traits] of Object.entries(keywords)) {\n    if (lowerDesc.includes(key)) {\n      for (const t of traits) {\n        suggestedTraits.add(t);\n        reasoning[t] = `Suggested because description mentions \"${key}\"`;\n      }\n    }\n  }\n\n  if (suggestedTraits.size === 0) {\n    suggestedTraits.add('@semantic_entity');\n    reasoning['@semantic_entity'] = 'Default trait for 2D semantic elements';\n  }\n\n  return { traits: Array.from(suggestedTraits), reasoning };\n}\n\n/**\n * Generate a V6 Semantic2D composition from natural language\n */\nexport async function generateSemanticUIForMCP(\n  description: string,\n  _options: any = {}\n): Promise<any> {\n  // The generated surface is agent-authored: it must route through the Native2DCompiler\n  // @verified_view gate — every data-bound element declares what it renders (@projects)\n  // and the compiler proves that claim against the actual binding. So the prompt asks for\n  // the provenance-complete shape, and whatever comes back is completed + verified below.\n  const aiPrompt = `Create a V6 Semantic2D composition for: ${description}. Use @2d_canvas, @semantic_layout, @semantic_entity, and other Semantic2D traits. When the surface shows DATA: declare composition state, bind each data element with @bind { state, path }, and give every bound element a provenance receipt @projects { node: \"<state>.<path>\" } naming EXACTLY what it renders; add composition-level @verified_view. Return only code.`;\n  const aiResult = await tryGenerateWithAI(aiPrompt, 'holo');\n  const code = aiResult ? normalizeSceneAIOutput(aiResult.code) : '';\n\n  if (aiResult && isUsableSceneCode(code)) {\n    // Complete any receipts the model omitted, then keep the surface ONLY if it is\n    // provably honest under the gate. An AI surface that can't be made provenance-complete\n    // falls back to the heuristic floor rather than shipping an unverifiable claim.\n    const enforced = enforceVerifiedViewReceipts(code);\n    if (isProvenanceComplete(enforced)) {\n      return {\n        code: enforced,\n        format: 'holo',\n        source: 'ai',\n        provider: aiResult.provider,\n        traits: aiResult.detectedTraits,\n        verifiedView: true,\n      };\n    }\n    // else: fall through to the provenance-complete heuristic below (honest floor)\n  }\n\n  return {\n    code: buildVerifiedSemanticUiHeuristic(description),\n    format: 'holo',\n    source: 'heuristic',\n    verifiedView: true,\n  };\n}\n\n/**\n * Heuristic floor for generate_semantic_ui: a provenance-complete @verified_view surface\n * with data-bound stat readouts, each carrying its derived @projects receipt. Compiles\n * clean through the Native2DCompiler gate (pinned by the core round-trip test). The final\n * enforceVerifiedViewReceipts pass guarantees completeness even if this template is edited.\n */\nfunction buildVerifiedSemanticUiHeuristic(description: string): string {\n  const title = description.replace(/[\"\\\\\\r\\n]/g, ' ').trim().slice(0, 80) || 'Semantic surface';\n  const raw = `composition \"SemanticApp\" {\n  @2d_canvas { projection: \"flat-semantic\" }\n  @verified_view\n  state {\n    metrics: { sessions: 0, errors: 0 }\n  }\n  object \"Root\" {\n    @semantic_layout { flow: \"column\" }\n    @layout { flex: \"column\", gap: \"8px\" }\n    object \"Title\" {\n      @text { variant: \"h3\", content: \"${title}\" }\n    }\n    object \"SessionsLabel\" {\n      @text { variant: \"caption\", content: \"Sessions\" }\n    }\n    object \"Sessions\" {\n      @text { variant: \"h2\" }\n      @bind { state: \"metrics\", path: \"sessions\", fallback: \"0\" }\n      @projects { node: \"metrics.sessions\" }\n    }\n    object \"ErrorsLabel\" {\n      @text { variant: \"caption\", content: \"Errors\" }\n    }\n    object \"Errors\" {\n      @text { variant: \"h2\" }\n      @bind { state: \"metrics\", path: \"errors\", fallback: \"0\" }\n      @projects { node: \"metrics.errors\" }\n    }\n  }\n}`;\n  return enforceVerifiedViewReceipts(raw);\n}\n","/**\n * training-generators.ts\n *\n * Training data generation utilities for HoloScript MCP server.\n * Provides structured training examples and dataset generation for LLM fine-tuning.\n *\n * @module training-generators\n */\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport interface TrainingExampleMetadata {\n  /** Broad category of the example */\n  category: string;\n  /** Difficulty rating: 'beginner' | 'intermediate' | 'advanced' */\n  difficulty: string;\n  /** HoloScript traits demonstrated */\n  traits: string[];\n  /** Searchable keywords */\n  keywords: string[];\n  /** Dataset version string */\n  version: string;\n}\n\nexport type TrainingCategory = string;\n\nexport interface TrainingExample {\n  /** Human-readable instruction prompt */\n  instruction: string;\n  /** Optional context / input passed alongside the instruction */\n  input: string;\n  /** Expected HoloScript output */\n  output: string;\n  /** Structured metadata for filtering and curriculum learning */\n  metadata: TrainingExampleMetadata;\n}\n\n// ---------------------------------------------------------------------------\n// Base examples\n// ---------------------------------------------------------------------------\n\nexport const ALL_TRAINING_EXAMPLES: TrainingExample[] = [\n  // ── Spatial / Scene ──────────────────────────────────────────────────────\n  {\n    instruction: 'Create a simple cube object at the origin',\n    input: '',\n    output: `object cube {\n  position: vec3(0, 0, 0)\n  scale: vec3(1, 1, 1)\n  trait RigidBody {}\n}`,\n    metadata: {\n      category: 'spatial',\n      difficulty: 'beginner',\n      traits: ['RigidBody'],\n      keywords: ['cube', 'object', 'origin', 'rigid'],\n      version: '1.0.0',\n    },\n  },\n  {\n    instruction: 'Generate a VR lobby scene with ambient lighting',\n    input: 'style: minimal',\n    output: `scene VRLobby {\n  ambient: color(0.2, 0.2, 0.3)\n  object floor {\n    position: vec3(0, 0, 0)\n    scale: vec3(20, 0.1, 20)\n    trait StaticCollider {}\n  }\n  object ceiling_light {\n    position: vec3(0, 5, 0)\n    trait PointLight { intensity: 1.5 }\n  }\n}`,\n    metadata: {\n      category: 'spatial',\n      difficulty: 'intermediate',\n      traits: ['StaticCollider', 'PointLight'],\n      keywords: ['scene', 'vr', 'lobby', 'lighting', 'ambient'],\n      version: '1.0.0',\n    },\n  },\n  {\n    instruction: 'Create a procedurally generated forest with 50 trees',\n    input: 'density: high',\n    output:\n      'scene Forest {\\n  repeat(50) {\\n    object tree_{i} {\\n      position: vec3(random(-20, 20), 0, random(-20, 20))\\n      scale: vec3(1, random(2, 5), 1)\\n      trait LOD { levels: [10, 30, 80] }\\n    }\\n  }\\n}',\n    metadata: {\n      category: 'spatial',\n      difficulty: 'advanced',\n      traits: ['LOD'],\n      keywords: ['forest', 'procedural', 'trees', 'random', 'generation'],\n      version: '1.0.0',\n    },\n  },\n\n  // ── Physics ───────────────────────────────────────────────────────────────\n  {\n    instruction: 'Apply gravity and collision to a falling sphere',\n    input: '',\n    output: `object sphere {\n  position: vec3(0, 10, 0)\n  trait RigidBody {\n    mass: 1.0\n    gravity: vec3(0, -9.8, 0)\n  }\n  trait SphereCollider { radius: 0.5 }\n}`,\n    metadata: {\n      category: 'physics',\n      difficulty: 'beginner',\n      traits: ['RigidBody', 'SphereCollider'],\n      keywords: ['gravity', 'sphere', 'collision', 'rigid body', 'falling'],\n      version: '1.0.0',\n    },\n  },\n  {\n    instruction: 'Simulate cloth physics with wind forces',\n    input: 'wind: moderate',\n    output: `object cloth {\n  position: vec3(0, 5, 0)\n  trait ClothSimulation {\n    stiffness: 0.8\n    damping: 0.1\n    wind: vec3(2, 0, 1)\n  }\n}`,\n    metadata: {\n      category: 'physics',\n      difficulty: 'advanced',\n      traits: ['ClothSimulation'],\n      keywords: ['cloth', 'physics', 'wind', 'simulation', 'fabric'],\n      version: '1.0.0',\n    },\n  },\n\n  // ── Rendering ─────────────────────────────────────────────────────────────\n  {\n    instruction: 'Set up PBR material with metallic and roughness properties',\n    input: 'material: steel',\n    output: `material Steel {\n  albedo: color(0.7, 0.7, 0.75)\n  metallic: 0.95\n  roughness: 0.1\n  normalMap: \"steel_normal.png\"\n}`,\n    metadata: {\n      category: 'rendering',\n      difficulty: 'intermediate',\n      traits: ['PBRMaterial'],\n      keywords: ['pbr', 'material', 'metallic', 'roughness', 'rendering'],\n      version: '1.0.0',\n    },\n  },\n  {\n    instruction: 'Add particle effects for fire and smoke',\n    input: '',\n    output: `object campfire {\n  position: vec3(0, 0, 0)\n  trait ParticleEmitter {\n    count: 500\n    lifetime: { min: 0.5, max: 2.0 }\n    velocity: vec3(0, 3, 0)\n    color_start: color(1.0, 0.5, 0.0)\n    color_end: color(0.3, 0.3, 0.3)\n  }\n}`,\n    metadata: {\n      category: 'rendering',\n      difficulty: 'intermediate',\n      traits: ['ParticleEmitter'],\n      keywords: ['particles', 'fire', 'smoke', 'emitter', 'effects'],\n      version: '1.0.0',\n    },\n  },\n\n  // ── AI / Behaviour ────────────────────────────────────────────────────────\n  {\n    instruction: 'Create an NPC with pathfinding behaviour',\n    input: 'target: player',\n    output: `object npc {\n  position: vec3(5, 0, 5)\n  trait NavAgent {\n    speed: 3.0\n    target: @player\n    avoidance: true\n  }\n  trait Animator {\n    idle: \"idle_anim\"\n    walk: \"walk_anim\"\n  }\n}`,\n    metadata: {\n      category: 'ai',\n      difficulty: 'advanced',\n      traits: ['NavAgent', 'Animator'],\n      keywords: ['npc', 'ai', 'pathfinding', 'navigation', 'behaviour'],\n      version: '1.0.0',\n    },\n  },\n];\n\n// ---------------------------------------------------------------------------\n// Generator functions\n// ---------------------------------------------------------------------------\n\n/**\n * Generate a requested number of variation examples based on a seed example.\n * Variations differ by inserting slightly modified phrasing or parameters.\n */\nexport function generateVariations(example: TrainingExample, count: number): TrainingExample[] {\n  const variations: TrainingExample[] = [];\n\n  for (let i = 0; i < count; i++) {\n    const suffix = i + 1;\n    variations.push({\n      instruction: `${example.instruction} (variation ${suffix})`,\n      input: example.input,\n      output: example.output,\n      metadata: {\n        ...example.metadata,\n        keywords: [...example.metadata.keywords, `variation-${suffix}`],\n        version: example.metadata.version,\n      },\n    });\n  }\n\n  return variations;\n}\n\n/**\n * Generate an expanded Hololand dataset by producing variations of all base\n * examples.  The returned array is at least as large as ALL_TRAINING_EXAMPLES.\n *\n * @param variationsPerExample  Number of extra variations per base example\n *                              (minimum 1 to guarantee the result is at least\n *                              as large as the base array).\n */\nexport function generateHololandDataset(variationsPerExample: number = 1): TrainingExample[] {\n  const safeVariations = Math.max(1, variationsPerExample);\n  const dataset: TrainingExample[] = [...ALL_TRAINING_EXAMPLES];\n\n  for (const example of ALL_TRAINING_EXAMPLES) {\n    const vars = generateVariations(example, safeVariations);\n    dataset.push(...vars);\n  }\n\n  return dataset;\n}\n\n/**\n * Serialise a single training example to an Alpaca-format JSONL line.\n * The output JSON object contains `instruction`, `input`, and `output` fields.\n */\nexport function toAlpacaJsonl(example: TrainingExample): string {\n  return JSON.stringify({\n    instruction: example.instruction,\n    input: example.input,\n    output: example.output,\n  });\n}\n\n/**\n * Serialise an array of training examples as a multi-line JSONL string.\n * Each line is a self-contained Alpaca-format JSON object.\n */\nexport function datasetToJsonl(examples: TrainingExample[]): string {\n  return examples.map((ex) => toAlpacaJsonl(ex)).join('\\n') + '\\n';\n}\n","/**\n * HoloScript Renderer and Sharing Utilities\n *\n * Remote rendering and X platform sharing for AI agents.\n * Includes scene persistence with short UUID URLs and server-side screenshot rendering.\n */\n\nimport { randomUUID } from 'crypto';\nimport { buildContentPolicyConfig, evaluateContentPolicySync } from '@holoscript/core/policy';\n\n// =============================================================================\n// Scene Persistence Store\n// =============================================================================\n\nexport interface SceneProvenance {\n  /** SHA-256 hex hash of the composition source */\n  hash: string;\n  /** Auto-classified: original (no imports), remix (imports + own content), curated (imports only) */\n  publishMode: 'original' | 'remix' | 'curated';\n  /** Tracked imports with their hashes */\n  imports: { path: string; hash?: string }[];\n}\n\nexport interface StoredScene {\n  id: string;\n  code: string;\n  title: string;\n  description: string;\n  createdAt: number;\n  accessCount: number;\n  /** Author identifier (@username or freeform) */\n  author?: string;\n  /** License type */\n  license?: string;\n  /** Provenance metadata (compiler-generated) */\n  provenance?: SceneProvenance;\n  /** Cached PNG thumbnail (base64-encoded) */\n  thumbnail?: string;\n  /** Whether thumbnail generation is in progress */\n  thumbnailPending?: boolean;\n  /**\n   * Explicit opt-in flag: whether this scene may appear in the public feed\n   * (GET /api/public/feed). Default undefined/falsy = NOT feed-visible.\n   * Only the anonymous consumer-generation endpoint and createShareLink()\n   * set this to true -- every other storeScene() call site leaves it unset.\n   */\n  listPublic?: boolean;\n}\n\n/** In-memory scene store. Replace with Redis/SQLite for production persistence. */\nconst sceneStore = new Map<string, StoredScene>();\n\n/** Maximum number of cached scenes (LRU eviction) */\nconst MAX_SCENES = 1000;\n\n/** Generate a short 8-char scene ID from UUID */\nfunction generateShortId(): string {\n  return randomUUID().replace(/-/g, '').slice(0, 8);\n}\n\nexport interface StoreSceneOptions {\n  title?: string;\n  description?: string;\n  author?: string;\n  license?: string;\n  provenance?: SceneProvenance;\n  /**\n   * Explicit opt-in: mark this scene as feed-visible (GET /api/public/feed).\n   * Default undefined/falsy = NOT feed-visible. Only set `true` at genuine\n   * public-sharing-intent call sites (POST /api/public/generate,\n   * createShareLink()) -- never default this to true here.\n   */\n  listPublic?: boolean;\n}\n\n/**\n * Store a scene and return a short URL-safe ID.\n */\nexport function storeScene(\n  code: string,\n  titleOrOptions?: string | StoreSceneOptions,\n  description?: string\n): StoredScene {\n  // Evict oldest scenes if at capacity\n  if (sceneStore.size >= MAX_SCENES) {\n    let oldestKey: string | null = null;\n    let oldestTime = Infinity;\n    for (const [key, scene] of sceneStore) {\n      if (scene.createdAt < oldestTime) {\n        oldestTime = scene.createdAt;\n        oldestKey = key;\n      }\n    }\n    if (oldestKey) sceneStore.delete(oldestKey);\n  }\n\n  // Support both legacy (title, description) and new options-object signatures\n  const opts: StoreSceneOptions =\n    typeof titleOrOptions === 'object' && titleOrOptions !== null\n      ? titleOrOptions\n      : { title: titleOrOptions, description };\n\n  const id = generateShortId();\n  const scene: StoredScene = {\n    id,\n    code,\n    title: opts.title || 'HoloScript Scene',\n    description: opts.description || 'Interactive 3D scene built with HoloScript',\n    createdAt: Date.now(),\n    accessCount: 0,\n    author: opts.author,\n    license: opts.license,\n    provenance: opts.provenance,\n    listPublic: opts.listPublic,\n  };\n  sceneStore.set(id, scene);\n  return scene;\n}\n\n/**\n * Retrieve a stored scene by short ID.\n */\nexport function getScene(id: string): StoredScene | null {\n  const scene = sceneStore.get(id);\n  if (scene) {\n    scene.accessCount++;\n  }\n  return scene || null;\n}\n\n/**\n * Find a scene by author username and composition name/id.\n * Used by the registry endpoint to resolve @username/name imports.\n */\nexport function findSceneByAuthor(username: string, name: string): StoredScene | null {\n  for (const scene of sceneStore.values()) {\n    if (scene.author === username && (scene.title === name || scene.id === name)) {\n      return scene;\n    }\n  }\n  return null;\n}\n\n/**\n * List the most recent PUBLIC-feed-visible scenes (listPublic === true only),\n * newest first, projected to a lightweight field set (no `code` -- the full\n * source is fetchable per-scene via GET /scene/:id).\n *\n * Safety design: this is the ONLY read path that turns \"obscure but\n * technically public\" (GET /scene/:id with a random 8-char ID) into \"actively\n * discoverable\". Scenes stored via /api/publish, /api/scene, /api/deploy,\n * /api/protocol, etc. do NOT set listPublic and are therefore never returned\n * here, even though they live in the same sceneStore.\n */\nexport function listRecentPublicScenes(\n  limit = 20\n): Array<Pick<StoredScene, 'id' | 'title' | 'description' | 'createdAt' | 'author' | 'thumbnail'>> {\n  const publicScenes = Array.from(sceneStore.values())\n    .filter((scene) => scene.listPublic === true)\n    .sort((a, b) => b.createdAt - a.createdAt)\n    .slice(0, limit);\n\n  return publicScenes.map((scene) => ({\n    id: scene.id,\n    title: scene.title,\n    description: scene.description,\n    createdAt: scene.createdAt,\n    author: scene.author,\n    thumbnail: scene.thumbnail,\n  }));\n}\n\n// =============================================================================\n// Thumbnail Generation (Playwright headless screenshot)\n// =============================================================================\n\n/** In-memory thumbnail cache for scenes without stored thumbnails */\nconst thumbnailCache = new Map<string, Buffer>();\n\n/**\n * Generate a PNG thumbnail for a scene using Playwright headless browser.\n * Runs async — call after storeScene() to populate the thumbnail field.\n */\nexport async function generateThumbnail(\n  sceneId: string,\n  width = 1200,\n  height = 630\n): Promise<Buffer | null> {\n  // Return cached thumbnail if available\n  const cached = thumbnailCache.get(sceneId);\n  if (cached) return cached;\n\n  const scene = sceneStore.get(sceneId);\n  if (!scene) return null;\n  if (scene.thumbnail) return Buffer.from(scene.thumbnail, 'base64');\n\n  // Mark as pending to avoid duplicate generation\n  if (scene.thumbnailPending) return null;\n  scene.thumbnailPending = true;\n\n  try {\n    const { chromium } = await import('playwright');\n    const browser = await chromium.launch({\n      args: ['--headless', '--disable-gpu', '--no-sandbox'],\n    });\n    const page = await browser.newPage({ viewport: { width, height } });\n\n    // Render the scene HTML directly (no network round-trip)\n    const html = generateBrowserTemplate(scene.code, scene.title);\n    await page.setContent(html, { waitUntil: 'networkidle' });\n\n    // Wait for Three.js to render at least one frame\n    await page.waitForTimeout(2000);\n\n    const screenshot = await page.screenshot({ type: 'png' });\n    await browser.close();\n\n    // Cache the thumbnail\n    const buffer = Buffer.from(screenshot);\n    scene.thumbnail = buffer.toString('base64');\n    scene.thumbnailPending = false;\n    thumbnailCache.set(sceneId, buffer);\n\n    return buffer;\n  } catch (err) {\n    scene.thumbnailPending = false;\n    console.error(`[thumbnail] Failed to generate for scene ${sceneId}:`, err);\n    return null;\n  }\n}\n\n/**\n * Get a scene's thumbnail buffer, or null if not yet generated.\n */\nexport function getThumbnail(sceneId: string): Buffer | null {\n  const cached = thumbnailCache.get(sceneId);\n  if (cached) return cached;\n\n  const scene = sceneStore.get(sceneId);\n  if (scene?.thumbnail) {\n    const buffer = Buffer.from(scene.thumbnail, 'base64');\n    thumbnailCache.set(sceneId, buffer);\n    return buffer;\n  }\n  return null;\n}\n\n// =============================================================================\n// Types\n// =============================================================================\n\ninterface RenderOptions {\n  code: string;\n  format?: 'png' | 'gif' | 'mp4' | 'webp';\n  resolution?: number[];\n  camera?: {\n    position?: number[];\n    target?: number[];\n  };\n  duration?: number;\n  quality?: 'draft' | 'preview' | 'production';\n  skipRemote?: boolean;\n}\n\ninterface ShareOptions {\n  code: string;\n  title?: string;\n  description?: string;\n  platform?: 'x' | 'generic' | 'codesandbox' | 'stackblitz';\n  skipRemote?: boolean;\n}\n\ninterface RenderResult {\n  success: boolean;\n  url?: string;\n  previewUrl?: string;\n  embedCode?: string;\n  error?: string;\n  localPath?: string;\n  base64?: string;\n}\n\ninterface ShareResult {\n  playgroundUrl: string;\n  embedUrl: string;\n  tweetText: string;\n  qrCode?: string;\n  cardMeta?: Record<string, string>;\n  blocked?: boolean;\n  blockReason?: string;\n  blockCategory?: string;\n}\n\n// Base URL for hosted services (configurable)\nconst RAILWAY_DOMAIN = process.env.RAILWAY_PUBLIC_DOMAIN;\nconst RENDER_SERVICE_URL =\n  process.env.HOLOSCRIPT_RENDER_URL ||\n  (RAILWAY_DOMAIN ? `https://${RAILWAY_DOMAIN}` : 'http://localhost:3000');\nconst PLAYGROUND_URL =\n  process.env.HOLOSCRIPT_PLAYGROUND_URL ||\n  (RAILWAY_DOMAIN ? `https://${RAILWAY_DOMAIN}` : 'http://localhost:3000');\n\n// Family-tier content policy (same tier/pattern as consumerGenerationPolicyConfig\n// in http-server.ts) -- createShareLink()'s local-generation path stores with\n// listPublic:true, which lands directly in the public feed (GET /api/public/feed),\n// so it must be screened with the same strictness as the anonymous consumer\n// generation surface, not a looser default.\nconst shareLinkPolicyConfig = buildContentPolicyConfig({\n  tier: 'family',\n  region: process.env.HOLOLAND_POLICY_REGION || 'GLOBAL',\n});\n\n/**\n * Generate a static preview render of HoloScript code\n */\nexport async function renderPreview(options: RenderOptions): Promise<RenderResult> {\n  const {\n    code,\n    format: _format = 'png',\n    resolution = [800, 600],\n    camera: _camera = { position: [0, 2, 5], target: [0, 0, 0] },\n    duration: _duration = 3000,\n    quality: _quality = 'preview',\n  } = options;\n\n  // Validate code first\n  const validationResult = quickValidate(code);\n  if (!validationResult.valid) {\n    return {\n      success: false,\n      error: `Invalid HoloScript code: ${validationResult.errors.join(', ')}`,\n    };\n  }\n\n  // Check if configured for remote rendering (skip when serving locally to avoid recursion)\n  if (!options.skipRemote && RENDER_SERVICE_URL && RENDER_SERVICE_URL !== 'http://localhost:3000') {\n    try {\n      // Use /share endpoint to store scene and get URLs\n      const response = await fetch(`${RENDER_SERVICE_URL}/share`, {\n        method: 'POST',\n        headers: {\n          'Content-Type': 'application/json; charset=utf-8',\n        },\n        body: JSON.stringify({\n          code,\n          title: 'HoloScript Preview',\n          description: 'Generated by HoloScript MCP',\n        }),\n      });\n\n      if (response.ok) {\n        const result = await response.json();\n        return {\n          success: true,\n          url: result.preview,\n          previewUrl: result.embed,\n          embedCode: generateEmbedCode(result.embed, resolution),\n        };\n      }\n    } catch (_error) {\n      // Fall through to local/mock rendering\n    }\n  }\n\n  // Store scene and generate short URL\n  const scene = storeScene(code, 'HoloScript Preview');\n  const previewUrl = `${PLAYGROUND_URL}/scene/${scene.id}`;\n  const thumbnailUrl = `${PLAYGROUND_URL}/api/scene/${scene.id}/thumbnail`;\n\n  // Trigger async thumbnail generation (non-blocking)\n  generateThumbnail(scene.id).catch((e) =>\n    console.warn(\n      `[renderer] Thumbnail generation failed for scene ${scene.id}: ${(e as Error)?.message ?? e}. Preview will use fallback.`\n    )\n  );\n\n  return {\n    success: true,\n    url: thumbnailUrl,\n    previewUrl,\n    embedCode: generateEmbedCode(previewUrl, resolution),\n    localPath: undefined,\n    base64: undefined,\n  };\n}\n\n/**\n * Create shareable links for X and other platforms\n */\nexport async function createShareLink(options: ShareOptions): Promise<ShareResult> {\n  const {\n    code,\n    title = 'HoloScript Scene',\n    description = 'Interactive 3D scene built with HoloScript',\n    platform = 'x',\n  } = options;\n\n  // Try to use the remote render service (skip when serving locally to avoid recursion)\n  if (!options.skipRemote && RENDER_SERVICE_URL && RENDER_SERVICE_URL !== 'http://localhost:3000') {\n    try {\n      const response = await fetch(`${RENDER_SERVICE_URL}/share`, {\n        method: 'POST',\n        headers: {\n          'Content-Type': 'application/json; charset=utf-8',\n        },\n        body: JSON.stringify({ code, title, description }),\n      });\n\n      if (response.ok) {\n        const result = await response.json();\n        const playgroundUrl = result.playground;\n        const embedUrl = result.embed;\n\n        return {\n          playgroundUrl,\n          embedUrl,\n          tweetText: generateTweetText(title, description, playgroundUrl),\n          qrCode: result.qr,\n          cardMeta: generateCardMeta(title, description, embedUrl),\n        };\n      }\n    } catch (_error) {\n      // Fall through to local generation\n    }\n  }\n\n  // Content-policy screen BEFORE storing anything. createShareLink()'s local\n  // path always sets listPublic:true (below), so unscreened content here would\n  // land directly in the public feed (GET /api/public/feed, WS-2) with zero\n  // moderation -- unlike POST /api/public/generate, which already screens both\n  // input and output via this same gate (http-server.ts consumerGenerationPolicyConfig).\n  // Screen the caller-supplied title/description (input) first, then the code\n  // (output), and return early WITHOUT calling storeScene on any violation so\n  // nothing -- public or private -- is ever persisted for blocked content.\n  if (title) {\n    const titleDecision = evaluateContentPolicySync(\n      { text: title, surface: 'create-share-link', direction: 'input' },\n      shareLinkPolicyConfig\n    );\n    if (!titleDecision.allowed) {\n      return {\n        blocked: true,\n        blockReason: 'Content blocked by policy.',\n        blockCategory: titleDecision.category,\n        playgroundUrl: '',\n        embedUrl: '',\n        tweetText: '',\n      };\n    }\n  }\n  if (description) {\n    const descriptionDecision = evaluateContentPolicySync(\n      { text: description, surface: 'create-share-link', direction: 'input' },\n      shareLinkPolicyConfig\n    );\n    if (!descriptionDecision.allowed) {\n      return {\n        blocked: true,\n        blockReason: 'Content blocked by policy.',\n        blockCategory: descriptionDecision.category,\n        playgroundUrl: '',\n        embedUrl: '',\n        tweetText: '',\n      };\n    }\n  }\n  const codeDecision = evaluateContentPolicySync(\n    { text: code, surface: 'create-share-link', direction: 'output' },\n    shareLinkPolicyConfig\n  );\n  if (!codeDecision.allowed) {\n    return {\n      blocked: true,\n      blockReason: 'Content blocked by policy.',\n      blockCategory: codeDecision.category,\n      playgroundUrl: '',\n      embedUrl: '',\n      tweetText: '',\n    };\n  }\n\n  // Store scene and generate short URLs. listPublic:true is the explicit\n  // \"share this\" intent signal -- this call site is one of exactly two that\n  // may set it (see StoreSceneOptions / listRecentPublicScenes doc comments).\n  const scene = storeScene(code, { title, description, listPublic: true });\n  const playgroundUrl = `${PLAYGROUND_URL}/scene/${scene.id}`;\n  const embedUrl = `${PLAYGROUND_URL}/embed/${scene.id}`;\n\n  // Generate X-optimized tweet text\n  const tweetText = generateTweetText(title, description, playgroundUrl);\n\n  // Generate QR code data URL (for mobile XR access)\n  const qrCode = await generateQRCodeDataUrl(playgroundUrl);\n\n  // Generate Twitter Card meta tags (with thumbnail URL)\n  const cardMeta = generateCardMeta(title, description, embedUrl, scene.id);\n\n  // Trigger async thumbnail generation\n  generateThumbnail(scene.id).catch((e) =>\n    console.warn(\n      `[renderer] Thumbnail generation failed for scene ${scene.id}: ${(e as Error)?.message ?? e}. Preview will use fallback.`\n    )\n  );\n\n  return {\n    playgroundUrl,\n    embedUrl,\n    tweetText,\n    qrCode,\n    cardMeta,\n  };\n}\n\n// === Helper Functions ===\n\nfunction quickValidate(code: string): { valid: boolean; errors: string[] } {\n  const errors: string[] = [];\n\n  // Basic syntax checks\n  if (!code.trim()) {\n    errors.push('Empty code');\n  }\n\n  // Check for balanced braces\n  const openBraces = (code.match(/{/g) || []).length;\n  const closeBraces = (code.match(/}/g) || []).length;\n  if (openBraces !== closeBraces) {\n    errors.push('Unbalanced braces');\n  }\n\n  // Check for common typos\n  if (code.includes('geomety:') || code.includes('geomtry:')) {\n    errors.push(\"Typo: 'geomety' should be 'geometry'\");\n  }\n  if (code.includes('positon:')) {\n    errors.push(\"Typo: 'positon' should be 'position'\");\n  }\n\n  return {\n    valid: errors.length === 0,\n    errors,\n  };\n}\n\nfunction _generatePlaygroundUrl(code: string, title: string, platform: string): string {\n  // Compress code for URL\n  const compressed = compressCode(code);\n\n  // Platform-specific URLs\n  switch (platform) {\n    case 'codesandbox':\n      return generateCodeSandboxUrl(code, title);\n    case 'stackblitz':\n      return generateStackBlitzUrl(code, title);\n    default:\n      return `${PLAYGROUND_URL}?code=${compressed}&title=${encodeURIComponent(title)}`;\n  }\n}\n\nfunction _generateEmbedUrl(code: string): string {\n  const compressed = compressCode(code);\n  return `${PLAYGROUND_URL}/embed?code=${compressed}`;\n}\n\nfunction compressCode(code: string): string {\n  // Base64 encoding is sufficient for most use cases\n  // LZ-string compression could reduce URL length by ~50% but adds dependency\n  // For very large scenes, consider using stored scene IDs instead\n  return encodeURIComponent(Buffer.from(code).toString('base64'));\n}\n\nfunction generateCodeSandboxUrl(code: string, title: string): string {\n  // CodeSandbox API format\n  const files = {\n    'index.html': {\n      content: generateBrowserTemplate(code, title),\n    },\n    'scene.holo': {\n      content: code,\n    },\n    'package.json': {\n      content: JSON.stringify(\n        {\n          name: title.toLowerCase().replace(/\\s+/g, '-'),\n          main: 'index.html',\n          dependencies: {\n            '@hololand/three-adapter': 'latest',\n            three: 'latest',\n          },\n        },\n        null,\n        2\n      ),\n    },\n  };\n\n  const parameters = encodeURIComponent(Buffer.from(JSON.stringify({ files })).toString('base64'));\n  return `https://codesandbox.io/api/v1/sandboxes/define?parameters=${parameters}`;\n}\n\nfunction generateStackBlitzUrl(code: string, title: string): string {\n  // StackBlitz URL format\n  const project = {\n    title,\n    description: 'HoloScript Scene',\n    template: 'html',\n    files: {\n      'index.html': generateBrowserTemplate(code, title),\n      'scene.holo': code,\n    },\n  };\n\n  const params = new URLSearchParams({\n    title: project.title,\n    description: project.description,\n  });\n\n  return `https://stackblitz.com/fork/github/holoscript/playground-template?${params}`;\n}\n\nfunction generateTweetText(title: string, description: string, url: string): string {\n  // Optimize for X's character limit\n  const maxDescLength = 200 - title.length - url.length - 20;\n  const truncatedDesc =\n    description.length > maxDescLength\n      ? description.substring(0, maxDescLength - 3) + '...'\n      : description;\n\n  return `🎮 ${title}\n\n${truncatedDesc}\n\nTry it in VR/AR: ${url}\n\n#HoloScript #VR #XR #Metaverse #3D`;\n}\n\nasync function generateQRCodeDataUrl(url: string): Promise<string> {\n  // Generated LOCALLY via the `qrcode` package — never routed through a\n  // third-party service. A hosted QR API leaks every shared/published\n  // scene URL to that third party (F.106/F.117: local generation only).\n  const QRCode = await import('qrcode');\n  return QRCode.toDataURL(url, {\n    width: 200,\n    margin: 2,\n  });\n}\n\nfunction generateCardMeta(\n  title: string,\n  description: string,\n  embedUrl: string,\n  sceneId?: string\n): Record<string, string> {\n  const meta: Record<string, string> = {\n    'og:title': title,\n    'og:description': description,\n    'og:type': 'website',\n    'og:url': embedUrl,\n    'twitter:title': title,\n    'twitter:description': description,\n    'twitter:player': embedUrl,\n    'twitter:player:width': '800',\n    'twitter:player:height': '600',\n  };\n\n  if (sceneId) {\n    const thumbnailUrl = `${PLAYGROUND_URL}/api/scene/${sceneId}/thumbnail`;\n    meta['og:image'] = thumbnailUrl;\n    meta['og:image:width'] = '1200';\n    meta['og:image:height'] = '630';\n    meta['twitter:card'] = 'summary_large_image';\n    meta['twitter:image'] = thumbnailUrl;\n  } else {\n    meta['twitter:card'] = 'player';\n  }\n\n  return meta;\n}\n\nfunction generateEmbedCode(previewUrl: string, resolution: number[]): string {\n  const [width, height] = resolution;\n  return `<iframe \n  src=\"${previewUrl}\" \n  width=\"${width}\" \n  height=\"${height}\" \n  frameborder=\"0\" \n  allowfullscreen \n  allow=\"xr-spatial-tracking\"\n></iframe>`;\n}\n\n/**\n * Generate a self-contained HTML page that boots the sovereign WebGPU renderer.\n *\n * `compiledCode` is the raw output of WebGPUCompiler — inline JS/TS that uses\n * the native WebGPU API (device init, WGSL shaders, render loop).  We strip any\n * TypeScript-only syntax (type annotations) before embedding so the page works\n * in a plain browser script tag without a build step.\n *\n * This is the render-surface the task \"Wire WebGPURenderer into preview/deploy\n * path\" targets — replacing the Three.js shim with the sovereign GPU path.\n */\nexport function generateWebGPUBrowserTemplate(compiledCode: string, title: string): string {\n  // Strip lightweight TypeScript-only constructs so the snippet runs as plain JS.\n  // WebGPUCompiler emits TypeScript type annotations (`: GPUDevice`, `as HTMLCanvasElement`,\n  // etc.) that a browser <script> cannot parse. Strip them with a best-effort regex\n  // pass — good enough for the generated output's constrained grammar; a full TS\n  // transpile step is not available server-side here.\n  const runnableCode = compiledCode\n    // Remove `as <Type>` casts\n    .replace(/\\s+as\\s+[A-Za-z0-9_<>\\[\\]|,\\s]+(?=[;,)\\s])/g, '')\n    // Remove `: <Type>` parameter / variable annotations without touching\n    // object-literal values such as `usage: GPUTextureUsage.RENDER_ATTACHMENT`.\n    .replace(\n      /(\\b[A-Za-z_$][\\w$]*)\\s*:\\s*(?:GPU[A-Za-z0-9]+|HTMLCanvasElement|GPUColor|Float32Array|number|string|boolean)\\b(?=\\s*[,)=])/g,\n      '$1'\n    )\n    // Remove simple return type annotations.\n    .replace(\n      /\\)\\s*:\\s*(?:GPU[A-Za-z0-9]+|HTMLCanvasElement|GPUColor|Float32Array|number|string|boolean)\\b(?=\\s*\\{)/g,\n      ')'\n    );\n\n  const safeTitle = escapeHtml(title);\n\n  return `<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n  <meta charset=\"UTF-8\">\n  <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n  <title>${safeTitle} — HoloScript WebGPU</title>\n  <style>\n    * { margin: 0; padding: 0; box-sizing: border-box; }\n    body { background: #000; overflow: hidden; }\n    canvas { display: block; width: 100vw; height: 100vh; }\n    #hs-renderer-badge {\n      position: fixed; bottom: 12px; right: 14px;\n      font: 11px/1.4 monospace; color: rgba(255,255,255,0.45);\n      pointer-events: none; user-select: none;\n    }\n    #hs-error {\n      display: none; position: fixed; inset: 0;\n      background: #0d0d0d; color: #ff6b6b;\n      font: 14px/1.6 monospace; padding: 32px; white-space: pre-wrap;\n    }\n    #hs-motion-gate {\n      display: none; position: fixed; inset: 0;\n      background: #000; color: #fff; z-index: 10;\n      align-items: center; justify-content: center;\n    }\n    #hs-motion-gate button {\n      padding: 12px 24px; background: #4a9eff; color: #fff;\n      border: none; border-radius: 8px; font-size: 1rem;\n      font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;\n      cursor: pointer;\n    }\n    #hs-motion-gate button:hover { background: #3a8eff; }\n  </style>\n</head>\n<body>\n  <canvas id=\"webgpu-canvas\"></canvas>\n  <div id=\"hs-renderer-badge\">HoloScript · sovereign WebGPU</div>\n  <div id=\"hs-error\"></div>\n  <div id=\"hs-motion-gate\"><button id=\"hs-motion-gate-btn\">Reduced motion is on. Click to view this scene.</button></div>\n\n  <script type=\"module\">\n    // ── Sovereign WebGPU renderer ─────────────────────────────────────────\n    // Auto-generated by HoloScript WebGPUCompiler.  Do not edit manually.\n    // Three.js / Babylon / R3F are NOT used here — this page runs entirely on\n    // the native WebGPU path.\n\n    const canvas = document.getElementById('webgpu-canvas');\n\n    function showError(msg) {\n      const el = document.getElementById('hs-error');\n      el.style.display = 'block';\n      el.textContent = 'WebGPU Error\\\\n\\\\n' + msg;\n    }\n\n    if (!navigator.gpu) {\n      showError('WebGPU is not supported in this browser.\\\\nTry Chrome 113+ or Edge 113+.');\n    } else {\n      // Resize canvas to device-pixel dimensions\n      function resizeCanvas() {\n        const dpr = window.devicePixelRatio || 1;\n        canvas.width  = Math.floor(window.innerWidth  * dpr);\n        canvas.height = Math.floor(window.innerHeight * dpr);\n      }\n      resizeCanvas();\n      window.addEventListener('resize', resizeCanvas);\n\n      const startRender = async () => {\n        try {\n          // ── Compiled HoloScript (sovereign output) ──────────────────────\n${runnableCode\n  .split('\\n')\n  .map((l) => '          ' + l)\n  .join('\\n')}\n          // ────────────────────────────────────────────────────────────────\n        } catch (err) {\n          showError(String(err && err.stack ? err.stack : err));\n        }\n      };\n\n      // WCAG 2.3.3 \"Animation from Interactions\": don't auto-play a rendering\n      // pipeline for users who have signaled an OS-level reduced-motion\n      // preference -- require an explicit click first. This is a general\n      // accessibility default (not a per-scene content scan), and it also\n      // naturally covers any future compiled content that drives more\n      // expressive per-frame visual behavior than today's output does.\n      const prefersReducedMotion = window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches;\n      if (prefersReducedMotion) {\n        const gate = document.getElementById('hs-motion-gate');\n        gate.style.display = 'flex';\n        document.getElementById('hs-motion-gate-btn').addEventListener('click', () => {\n          gate.style.display = 'none';\n          startRender();\n        }, { once: true });\n      } else {\n        startRender();\n      }\n    }\n  </script>\n</body>\n</html>`;\n}\n\nexport function generateBrowserTemplate(code: string, title: string, sceneId?: string): string {\n  const thumbnailUrl = sceneId ? `${PLAYGROUND_URL}/api/scene/${sceneId}/thumbnail` : undefined;\n\n  return `<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n  <meta charset=\"UTF-8\">\n  <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n  <title>${escapeHtml(title)}</title>\n\n  <!-- OpenGraph -->\n  <meta property=\"og:title\" content=\"${escapeHtml(title)}\">\n  <meta property=\"og:description\" content=\"Interactive 3D scene built with HoloScript\">\n  <meta property=\"og:type\" content=\"website\">${thumbnailUrl ? `\\n  <meta property=\"og:image\" content=\"${thumbnailUrl}\">` : ''}${sceneId ? `\\n  <meta property=\"og:url\" content=\"${PLAYGROUND_URL}/scene/${sceneId}\">` : ''}\n\n  <!-- Twitter Card -->\n  <meta name=\"twitter:card\" content=\"${thumbnailUrl ? 'summary_large_image' : 'player'}\">\n  <meta name=\"twitter:title\" content=\"${escapeHtml(title)}\">${thumbnailUrl ? `\\n  <meta name=\"twitter:image\" content=\"${thumbnailUrl}\">` : ''}\n  <meta name=\"twitter:player\" content=\"${PLAYGROUND_URL}/embed\">\n  <meta name=\"twitter:player:width\" content=\"800\">\n  <meta name=\"twitter:player:height\" content=\"600\">\n  \n  <style>\n    * { margin: 0; padding: 0; box-sizing: border-box; }\n    body { \n      background: #000; \n      display: flex; \n      justify-content: center; \n      align-items: center;\n      min-height: 100vh;\n      font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;\n    }\n    #container { \n      width: 100%; \n      height: 100vh; \n    }\n    #loading {\n      position: absolute;\n      top: 50%;\n      left: 50%;\n      transform: translate(-50%, -50%);\n      color: #fff;\n      font-size: 1.5rem;\n    }\n    #vr-button {\n      position: absolute;\n      bottom: 20px;\n      left: 50%;\n      transform: translateX(-50%);\n      padding: 12px 24px;\n      background: #4a9eff;\n      color: white;\n      border: none;\n      border-radius: 8px;\n      font-size: 1rem;\n      cursor: pointer;\n    }\n    #vr-button:hover { background: #3a8eff; }\n    #vr-button:disabled { background: #666; cursor: not-allowed; }\n    #motion-button {\n      position: absolute;\n      bottom: 20px;\n      left: 50%;\n      transform: translateX(-50%);\n      padding: 12px 24px;\n      background: #4a9eff;\n      color: white;\n      border: none;\n      border-radius: 8px;\n      font-size: 1rem;\n      cursor: pointer;\n      display: none;\n    }\n    #motion-button:hover { background: #3a8eff; }\n  </style>\n</head>\n<body>\n  <div id=\"container\"></div>\n  <div id=\"loading\">Loading HoloScript scene...</div>\n  <button id=\"vr-button\" disabled>Enter VR</button>\n  <button id=\"motion-button\">Reduced motion is on — click to enable animation</button>\n\n  <script type=\"module\">\n    import * as THREE from 'https://unpkg.com/three@0.160.0/build/three.module.js';\n    import { VRButton } from 'https://unpkg.com/three@0.160.0/examples/jsm/webxr/VRButton.js';\n    \n    // HoloScript code embedded\n    const holoCode = \\`${escapeBackticks(code)}\\`;\n    \n    // Initialize Three.js scene\n    const container = document.getElementById('container');\n    const scene = new THREE.Scene();\n    const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);\n    \n    const renderer = new THREE.WebGLRenderer({ antialias: true });\n    renderer.setSize(window.innerWidth, window.innerHeight);\n    renderer.setPixelRatio(window.devicePixelRatio);\n    renderer.xr.enabled = true;\n    container.appendChild(renderer.domElement);\n    \n    // Add VR button if supported\n    if ('xr' in navigator) {\n      navigator.xr.isSessionSupported('immersive-vr').then(supported => {\n        const vrButton = document.getElementById('vr-button');\n        if (supported) {\n          vrButton.disabled = false;\n          container.appendChild(VRButton.createButton(renderer));\n        } else {\n          vrButton.textContent = 'VR Not Supported';\n        }\n      });\n    }\n    \n    // Basic lighting\n    const ambientLight = new THREE.AmbientLight(0xffffff, 0.5);\n    scene.add(ambientLight);\n    \n    const directionalLight = new THREE.DirectionalLight(0xffffff, 1);\n    directionalLight.position.set(5, 10, 5);\n    scene.add(directionalLight);\n    \n    // Default skybox\n    scene.background = new THREE.Color(0x1a1a2e);\n    \n    camera.position.set(0, 1.6, 5);\n    \n    // Hide loading\n    document.getElementById('loading').style.display = 'none';\n    \n    // Parse HoloScript and create objects\n    const sceneObjects = [];\n    \n    function parseHoloCode(code) {\n      const objects = [];\n      // Match object definitions: object \"name\" @traits { ... }\n      const objectRegex = /(?:object|orb|cube|sphere|box|plane)\\\\s+[\"']?([\\\\w-]+)[\"']?\\\\s*([^{]*)\\\\{([^}]*)\\\\}/gi;\n      let match;\n      \n      while ((match = objectRegex.exec(code)) !== null) {\n        const name = match[1];\n        const traitsStr = match[2] || '';\n        const propsStr = match[3] || '';\n        \n        const obj = { name, traits: [], props: {} };\n        \n        // Extract traits (@grabbable, @collidable, etc.)\n        const traitMatches = traitsStr.match(/@\\\\w+/g);\n        if (traitMatches) obj.traits = traitMatches;\n        \n        // Extract geometry\n        const geoMatch = propsStr.match(/geometry:\\\\s*[\"']?(\\\\w+)[\"']?/i);\n        obj.props.geometry = geoMatch ? geoMatch[1] : 'sphere';\n        \n        // Extract position\n        const posMatch = propsStr.match(/position:\\\\s*\\\\[([^\\\\]]+)\\\\]/i);\n        if (posMatch) {\n          obj.props.position = posMatch[1].split(',').map(n => parseFloat(n.trim()));\n        }\n        \n        // Extract color\n        const colorMatch = propsStr.match(/color:\\\\s*[\"']?([#\\\\w]+)[\"']?/i);\n        if (colorMatch) obj.props.color = colorMatch[1];\n        \n        // Extract scale\n        const scaleMatch = propsStr.match(/scale:\\\\s*([\\\\d.]+|\\\\[[^\\\\]]+\\\\])/i);\n        if (scaleMatch) {\n          const val = scaleMatch[1];\n          if (val.startsWith('[')) {\n            obj.props.scale = val.slice(1, -1).split(',').map(n => parseFloat(n.trim()));\n          } else {\n            const s = parseFloat(val);\n            obj.props.scale = [s, s, s];\n          }\n        }\n        \n        objects.push(obj);\n      }\n      \n      return objects;\n    }\n    \n    function createGeometry(type) {\n      switch (type?.toLowerCase()) {\n        case 'sphere': case 'orb': return new THREE.SphereGeometry(0.5, 32, 32);\n        case 'cube': case 'box': return new THREE.BoxGeometry(1, 1, 1);\n        case 'plane': return new THREE.PlaneGeometry(2, 2);\n        case 'cylinder': return new THREE.CylinderGeometry(0.5, 0.5, 1, 32);\n        case 'cone': return new THREE.ConeGeometry(0.5, 1, 32);\n        case 'torus': return new THREE.TorusGeometry(0.4, 0.15, 16, 48);\n        default: return new THREE.SphereGeometry(0.5, 32, 32);\n      }\n    }\n    \n    function colorToHex(color) {\n      if (!color) return 0x00ffff;\n      if (typeof color === 'number') return color;\n      if (color.startsWith('#')) return parseInt(color.slice(1), 16);\n      const colors = { red: 0xff0000, green: 0x00ff00, blue: 0x0000ff, yellow: 0xffff00, \n                       cyan: 0x00ffff, magenta: 0xff00ff, white: 0xffffff, black: 0x000000,\n                       orange: 0xffa500, purple: 0x800080, pink: 0xffc0cb };\n      return colors[color.toLowerCase()] || 0x00ffff;\n    }\n    \n    // Parse and create objects from HoloScript\n    const parsedObjects = parseHoloCode(holoCode);\n    \n    for (const obj of parsedObjects) {\n      const geometry = createGeometry(obj.props.geometry);\n      const color = colorToHex(obj.props.color);\n      const material = new THREE.MeshStandardMaterial({ \n        color: color,\n        emissive: color,\n        emissiveIntensity: 0.2\n      });\n      const mesh = new THREE.Mesh(geometry, material);\n      mesh.name = obj.name;\n      \n      if (obj.props.position) {\n        mesh.position.set(...obj.props.position);\n      }\n      if (obj.props.scale) {\n        mesh.scale.set(...obj.props.scale);\n      }\n      \n      scene.add(mesh);\n      sceneObjects.push(mesh);\n    }\n    \n    // If no objects parsed, create default placeholder\n    if (sceneObjects.length === 0) {\n      const geometry = new THREE.SphereGeometry(0.5, 32, 32);\n      const material = new THREE.MeshStandardMaterial({ \n        color: 0x00ffff, \n        emissive: 0x00ffff,\n        emissiveIntensity: 0.3\n      });\n      const sphere = new THREE.Mesh(geometry, material);\n      sphere.position.set(0, 1, -2);\n      scene.add(sphere);\n      sceneObjects.push(sphere);\n    }\n    \n    // Animation - rotate all objects gently\n    function animate() {\n      for (const obj of sceneObjects) {\n        obj.rotation.y += 0.005;\n      }\n      renderer.setAnimationLoop(render);\n    }\n    \n    function render() {\n      renderer.render(scene, camera);\n    }\n\n    // WCAG 2.3.3 \"Animation from Interactions\": today's animation here is a\n    // fixed, gentle 0.005rad/frame rotation with no seizure risk -- but this\n    // gate is a general accessibility default (not a per-scene content scan)\n    // that also future-proofs this template against any more expressive\n    // animation added later. When the OS-level reduced-motion preference is\n    // set, render a single static frame and require an explicit click before\n    // starting the animation loop; otherwise behavior is unchanged.\n    const prefersReducedMotion = window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches;\n    if (prefersReducedMotion) {\n      render();\n      const motionButton = document.getElementById('motion-button');\n      motionButton.style.display = 'block';\n      motionButton.addEventListener('click', () => {\n        motionButton.style.display = 'none';\n        animate();\n      }, { once: true });\n    } else {\n      animate();\n    }\n\n    // Handle resize\n    window.addEventListener('resize', () => {\n      camera.aspect = window.innerWidth / window.innerHeight;\n      camera.updateProjectionMatrix();\n      renderer.setSize(window.innerWidth, window.innerHeight);\n    });\n  </script>\n</body>\n</html>`;\n}\n\nfunction escapeHtml(str: string): string {\n  return str\n    .replace(/&/g, '&amp;')\n    .replace(/</g, '&lt;')\n    .replace(/>/g, '&gt;')\n    .replace(/\"/g, '&quot;')\n    .replace(/'/g, '&#039;');\n}\n\nfunction escapeBackticks(str: string): string {\n  return str.replace(/`/g, '\\\\`').replace(/\\$/g, '\\\\$');\n}\n","/**\n * HoloScript Documentation Database\n *\n * Comprehensive documentation for traits, syntax, and examples.\n */\n\n// === TRAIT DOCUMENTATION ===\n\nexport const TRAIT_DOCS: Record<string, TraitDoc> = {\n  // Interaction Traits\n  '@grabbable': {\n    name: '@grabbable',\n    category: 'interaction',\n    description:\n      'Allows the object to be picked up by the user in VR/AR. When grabbed, the object follows the controller.',\n    parameters: [\n      {\n        name: 'snap_to_hand',\n        type: 'boolean',\n        default: 'false',\n        description: 'Snap object to hand when grabbed',\n      },\n      {\n        name: 'two_handed',\n        type: 'boolean',\n        default: 'false',\n        description: 'Require two hands to grab',\n      },\n      {\n        name: 'highlight',\n        type: 'boolean',\n        default: 'true',\n        description: 'Highlight when in grab range',\n      },\n    ],\n    events: ['onGrab', 'onRelease', 'onGrabStart', 'onGrabEnd'],\n    example: `orb Sword @grabbable(snap_to_hand: true) {\n  geometry: \"model/sword.glb\"\n  onGrab: { haptic.feedback('medium') }\n  onRelease: { audio.play('drop.mp3') }\n}`,\n    relatedTraits: ['@throwable', '@holdable', '@equippable'],\n  },\n\n  '@throwable': {\n    name: '@throwable',\n    category: 'interaction',\n    description: 'Allows the object to be thrown with physics. Requires @grabbable.',\n    parameters: [\n      {\n        name: 'velocity_multiplier',\n        type: 'number',\n        default: '1.0',\n        description: 'Multiplier for throw velocity',\n      },\n      { name: 'bounce', type: 'boolean', default: 'true', description: 'Bounce on impact' },\n    ],\n    events: ['onThrow', 'onLand'],\n    example: `orb Ball @grabbable @throwable(velocity_multiplier: 1.5) {\n  geometry: \"sphere\"\n  physics: { mass: 0.5, restitution: 0.8 }\n}`,\n    relatedTraits: ['@grabbable', '@collidable', '@physics'],\n  },\n\n  '@holdable': {\n    name: '@holdable',\n    category: 'interaction',\n    description: 'Object can be held without physics simulation (stays in hand exactly).',\n    parameters: [\n      {\n        name: 'offset',\n        type: 'array',\n        default: '[0, 0, 0]',\n        description: 'Position offset when held',\n      },\n      {\n        name: 'rotation',\n        type: 'array',\n        default: '[0, 0, 0]',\n        description: 'Rotation offset when held',\n      },\n    ],\n    events: ['onHold', 'onDrop'],\n    example: `orb Flashlight @grabbable @holdable(offset: [0, 0, -0.1]) {\n  geometry: \"cylinder\"\n  light: { type: \"spot\", intensity: 1.0 }\n}`,\n    relatedTraits: ['@grabbable', '@equippable'],\n  },\n\n  '@clickable': {\n    name: '@clickable',\n    category: 'interaction',\n    description: 'Object responds to click/tap events in VR controllers or touch.',\n    parameters: [\n      { name: 'highlight', type: 'boolean', default: 'true', description: 'Highlight on hover' },\n      { name: 'debounce', type: 'number', default: '200', description: 'Debounce time in ms' },\n    ],\n    events: ['onClick', 'onDoubleClick', 'onLongPress'],\n    example: `orb Button @clickable {\n  geometry: \"cube\"\n  scale: [0.2, 0.1, 0.2]\n  onClick: { door.open() }\n}`,\n    relatedTraits: ['@pointable', '@hoverable'],\n  },\n\n  '@hoverable': {\n    name: '@hoverable',\n    category: 'interaction',\n    description: 'Object responds to hover/point events.',\n    parameters: [\n      {\n        name: 'highlight_color',\n        type: 'string',\n        default: '#ffffff',\n        description: 'Color when hovered',\n      },\n    ],\n    events: ['onHoverEnter', 'onHoverExit', 'onHover'],\n    example: `orb InfoPanel @hoverable {\n  geometry: \"plane\"\n  onHoverEnter: { this.opacity = 1.0 }\n  onHoverExit: { this.opacity = 0.5 }\n}`,\n    relatedTraits: ['@clickable', '@pointable'],\n  },\n\n  '@draggable': {\n    name: '@draggable',\n    category: 'interaction',\n    description: 'Object can be dragged (moved while clicking/holding).',\n    parameters: [\n      {\n        name: 'axis',\n        type: 'string',\n        default: 'all',\n        description: 'Constrain to axis: x, y, z, xy, xz, yz, all',\n      },\n      { name: 'bounds', type: 'object', description: 'Movement bounds' },\n    ],\n    events: ['onDragStart', 'onDrag', 'onDragEnd'],\n    example: `orb Slider @draggable(axis: \"x\", bounds: { min: -1, max: 1 }) {\n  geometry: \"sphere\"\n  scale: [0.2, 0.2, 0.2]\n  onDrag: { volume.set(this.position.x) }\n}`,\n    relatedTraits: ['@grabbable'],\n  },\n\n  '@pointable': {\n    name: '@pointable',\n    category: 'interaction',\n    description: 'Object can be pointed at with ray casting.',\n    parameters: [\n      { name: 'ray_visible', type: 'boolean', default: 'true', description: 'Show pointing ray' },\n    ],\n    events: ['onPoint', 'onPointEnter', 'onPointExit'],\n    example: `orb TeleportPad @pointable {\n  geometry: \"cylinder\"\n  scale: [0.5, 0.1, 0.5]\n  onPoint: { player.teleportTo(this.position) }\n}`,\n    relatedTraits: ['@clickable', '@hoverable'],\n  },\n\n  '@scalable': {\n    name: '@scalable',\n    category: 'interaction',\n    description: 'Object can be scaled with pinch gesture.',\n    parameters: [\n      { name: 'min_scale', type: 'number', default: '0.1', description: 'Minimum scale' },\n      { name: 'max_scale', type: 'number', default: '10', description: 'Maximum scale' },\n      { name: 'uniform', type: 'boolean', default: 'true', description: 'Uniform scaling only' },\n    ],\n    events: ['onScaleStart', 'onScale', 'onScaleEnd'],\n    example: `orb Model @grabbable @scalable(min_scale: 0.5, max_scale: 3) {\n  geometry: \"model/sculpture.glb\"\n}`,\n    relatedTraits: ['@grabbable', '@draggable'],\n  },\n\n  // Physics Traits\n  '@collidable': {\n    name: '@collidable',\n    category: 'physics',\n    description: 'Object participates in collision detection.',\n    parameters: [\n      { name: 'layer', type: 'string', default: 'default', description: 'Collision layer' },\n      { name: 'mask', type: 'array', description: 'Layers to collide with' },\n    ],\n    events: ['onCollisionEnter', 'onCollisionExit', 'onCollision'],\n    example: `orb Wall @collidable {\n  geometry: \"cube\"\n  scale: [5, 3, 0.2]\n  physics: { type: \"static\" }\n}`,\n    relatedTraits: ['@physics', '@trigger'],\n  },\n\n  '@physics': {\n    name: '@physics',\n    category: 'physics',\n    description: 'Object has full physics simulation (mass, velocity, forces).',\n    parameters: [\n      {\n        name: 'type',\n        type: 'string',\n        default: 'dynamic',\n        description: 'Physics body type: dynamic, kinematic, static',\n      },\n      { name: 'mass', type: 'number', default: '1', description: 'Mass in kg' },\n      { name: 'friction', type: 'number', default: '0.5', description: 'Surface friction' },\n      { name: 'restitution', type: 'number', default: '0.3', description: 'Bounciness (0-1)' },\n    ],\n    events: ['onSleep', 'onWake'],\n    example: `orb Crate @physics(mass: 10, restitution: 0.2) @collidable {\n  geometry: \"cube\"\n  physics: { type: \"dynamic\" }\n}`,\n    relatedTraits: ['@collidable', '@gravity'],\n  },\n\n  '@rigid': {\n    name: '@rigid',\n    category: 'physics',\n    description: 'Object is a rigid body (non-deformable physics object).',\n    parameters: [],\n    events: [],\n    example: `orb Table @rigid @collidable {\n  geometry: \"model/table.glb\"\n  physics: { type: \"kinematic\" }\n}`,\n    relatedTraits: ['@physics', '@kinematic'],\n  },\n\n  '@kinematic': {\n    name: '@kinematic',\n    category: 'physics',\n    description: 'Object moves via code but affects other physics objects.',\n    parameters: [],\n    events: [],\n    example: `orb Elevator @kinematic @collidable {\n  geometry: \"cube\"\n  animation: { property: \"position.y\", from: 0, to: 5, duration: 3000, loop: \"pingpong\" }\n}`,\n    relatedTraits: ['@physics', '@rigid'],\n  },\n\n  '@trigger': {\n    name: '@trigger',\n    category: 'physics',\n    description: \"Object detects overlaps but doesn't physically collide.\",\n    parameters: [\n      {\n        name: 'shape',\n        type: 'string',\n        default: 'auto',\n        description: 'Trigger shape: box, sphere, auto',\n      },\n    ],\n    events: ['onTriggerEnter', 'onTriggerExit', 'onTriggerStay'],\n    example: `orb DamagZone @trigger {\n  geometry: \"sphere\"\n  scale: [3, 3, 3]\n  visible: false\n  onTriggerEnter: |entity| { entity.health -= 10 }\n}`,\n    relatedTraits: ['@collidable'],\n  },\n\n  '@gravity': {\n    name: '@gravity',\n    category: 'physics',\n    description: 'Object is affected by gravity.',\n    parameters: [\n      { name: 'scale', type: 'number', default: '1', description: 'Gravity multiplier' },\n    ],\n    events: [],\n    example: `orb Balloon @physics @gravity(scale: -0.1) {\n  geometry: \"sphere\"\n  // Floats slowly upward\n}`,\n    relatedTraits: ['@physics'],\n  },\n\n  // Visual Traits\n  '@glowing': {\n    name: '@glowing',\n    category: 'visual',\n    description: 'Object emits a glow effect.',\n    parameters: [\n      { name: 'intensity', type: 'number', default: '0.5', description: 'Glow intensity' },\n      {\n        name: 'color',\n        type: 'string',\n        default: 'inherit',\n        description: 'Glow color (defaults to object color)',\n      },\n      { name: 'pulse', type: 'boolean', default: 'false', description: 'Pulsing glow effect' },\n    ],\n    events: [],\n    example: `orb Crystal @glowing(intensity: 0.8, color: \"#00ffff\", pulse: true) {\n  geometry: \"model/crystal.glb\"\n  color: \"#00ffff\"\n}`,\n    relatedTraits: ['@emissive'],\n  },\n\n  '@emissive': {\n    name: '@emissive',\n    category: 'visual',\n    description: 'Object emits light (acts as a light source).',\n    parameters: [\n      { name: 'intensity', type: 'number', default: '1', description: 'Light intensity' },\n      { name: 'range', type: 'number', default: '5', description: 'Light range in meters' },\n    ],\n    events: [],\n    example: `orb Lamp @emissive(intensity: 2, range: 10) {\n  geometry: \"sphere\"\n  color: \"#ffff88\"\n}`,\n    relatedTraits: ['@glowing'],\n  },\n\n  '@transparent': {\n    name: '@transparent',\n    category: 'visual',\n    description: 'Object has transparency.',\n    parameters: [\n      { name: 'opacity', type: 'number', default: '0.5', description: 'Opacity value (0-1)' },\n    ],\n    events: [],\n    example: `orb Ghost @transparent(opacity: 0.3) {\n  geometry: \"model/ghost.glb\"\n  color: \"#ffffff\"\n}`,\n    relatedTraits: ['@reflective'],\n  },\n\n  '@reflective': {\n    name: '@reflective',\n    category: 'visual',\n    description: 'Object has reflective surface.',\n    parameters: [\n      { name: 'roughness', type: 'number', default: '0.1', description: 'Surface roughness' },\n      { name: 'metalness', type: 'number', default: '1', description: 'Metalness value' },\n    ],\n    events: [],\n    example: `orb Mirror @reflective(roughness: 0, metalness: 1) {\n  geometry: \"plane\"\n  scale: [2, 3, 0.1]\n}`,\n    relatedTraits: ['@transparent'],\n  },\n\n  '@animated': {\n    name: '@animated',\n    category: 'visual',\n    description: 'Object plays animations.',\n    parameters: [\n      { name: 'autoplay', type: 'boolean', default: 'true', description: 'Auto-play on load' },\n      { name: 'loop', type: 'boolean', default: 'true', description: 'Loop animation' },\n    ],\n    events: ['onAnimationStart', 'onAnimationEnd', 'onAnimationLoop'],\n    example: `orb Character @animated(autoplay: true) {\n  geometry: \"model/character.glb\"\n  animation: { clip: \"idle\", loop: true }\n}`,\n    relatedTraits: [],\n  },\n\n  '@billboard': {\n    name: '@billboard',\n    category: 'visual',\n    description: 'Object always faces the camera.',\n    parameters: [\n      { name: 'axis', type: 'string', default: 'all', description: 'Rotation axis: all, y' },\n    ],\n    events: [],\n    example: `orb NameTag @billboard(axis: \"y\") {\n  geometry: \"plane\"\n  text: \"Player 1\"\n}`,\n    relatedTraits: [],\n  },\n\n  // Networking Traits\n  '@networked': {\n    name: '@networked',\n    category: 'networking',\n    description: 'Object state is synchronized across clients.',\n    parameters: [\n      { name: 'sync_rate', type: 'string', default: '20hz', description: 'Sync rate in Hz' },\n      {\n        name: 'interpolate',\n        type: 'boolean',\n        default: 'true',\n        description: 'Interpolate between updates',\n      },\n    ],\n    events: ['onNetworkSync', 'onOwnershipChange'],\n    example: `orb SharedBall @networked(sync_rate: \"30hz\") @grabbable {\n  geometry: \"sphere\"\n  @networked position\n  @networked rotation\n}`,\n    relatedTraits: ['@synced', '@persistent', '@owned'],\n  },\n\n  '@synced': {\n    name: '@synced',\n    category: 'networking',\n    description: 'Specific property is synced across network.',\n    parameters: [{ name: 'property', type: 'string', description: 'Property to sync' }],\n    events: [],\n    example: `orb Counter @networked {\n  state { count: 0 }\n  @synced count\n}`,\n    relatedTraits: ['@networked'],\n  },\n\n  '@persistent': {\n    name: '@persistent',\n    category: 'networking',\n    description: 'Object state persists across sessions.',\n    parameters: [\n      {\n        name: 'storage',\n        type: 'string',\n        default: 'cloud',\n        description: 'Storage type: cloud, local',\n      },\n    ],\n    events: ['onSave', 'onLoad'],\n    example: `orb SavedProgress @persistent {\n  state {\n    level: 1\n    score: 0\n  }\n}`,\n    relatedTraits: ['@networked'],\n  },\n\n  '@owned': {\n    name: '@owned',\n    category: 'networking',\n    description: 'Object has ownership semantics - only owner can modify.',\n    parameters: [],\n    events: ['onOwnershipClaimed', 'onOwnershipReleased'],\n    example: `orb PlayerAvatar @networked @owned {\n  geometry: \"model/avatar.glb\"\n  // Only the owning player can control this\n}`,\n    relatedTraits: ['@networked'],\n  },\n\n  '@host_only': {\n    name: '@host_only',\n    category: 'networking',\n    description: 'Object can only be modified by the host/server.',\n    parameters: [],\n    events: [],\n    example: `orb GameManager @host_only {\n  state {\n    gameState: \"lobby\"\n    players: []\n  }\n}`,\n    relatedTraits: ['@networked'],\n  },\n\n  // Behavior Traits\n  '@stackable': {\n    name: '@stackable',\n    category: 'behavior',\n    description: 'Objects can be stacked on top of each other.',\n    parameters: [\n      { name: 'max_stack', type: 'number', default: '10', description: 'Maximum stack height' },\n    ],\n    events: ['onStack', 'onUnstack'],\n    example: `orb Crate @grabbable @stackable(max_stack: 5) @collidable {\n  geometry: \"cube\"\n}`,\n    relatedTraits: ['@attachable'],\n  },\n\n  '@attachable': {\n    name: '@attachable',\n    category: 'behavior',\n    description: 'Object can attach to other objects.',\n    parameters: [{ name: 'attach_points', type: 'array', description: 'Named attachment points' }],\n    events: ['onAttach', 'onDetach'],\n    example: `orb Scope @attachable(attach_points: [\"weapon_top\"]) {\n  geometry: \"model/scope.glb\"\n}`,\n    relatedTraits: ['@equippable'],\n  },\n\n  '@equippable': {\n    name: '@equippable',\n    category: 'behavior',\n    description: 'Object can be equipped to body slots.',\n    parameters: [\n      {\n        name: 'slot',\n        type: 'string',\n        default: 'hand',\n        description: 'Equip slot: hand, head, back, chest',\n      },\n    ],\n    events: ['onEquip', 'onUnequip'],\n    example: `orb Helmet @equippable(slot: \"head\") {\n  geometry: \"model/helmet.glb\"\n}`,\n    relatedTraits: ['@grabbable', '@attachable'],\n  },\n\n  '@consumable': {\n    name: '@consumable',\n    category: 'behavior',\n    description: 'Object can be consumed/used once.',\n    parameters: [{ name: 'effect', type: 'string', description: 'Effect on consumption' }],\n    events: ['onConsume'],\n    example: `orb HealthPotion @grabbable @consumable {\n  geometry: \"model/potion.glb\"\n  color: \"#ff0000\"\n  onConsume: { player.health += 50 }\n}`,\n    relatedTraits: ['@grabbable'],\n  },\n\n  '@destructible': {\n    name: '@destructible',\n    category: 'behavior',\n    description: 'Object can be destroyed.',\n    parameters: [\n      { name: 'health', type: 'number', default: '100', description: 'Health points' },\n      { name: 'debris', type: 'boolean', default: 'true', description: 'Spawn debris on destroy' },\n    ],\n    events: ['onDamage', 'onDestroy'],\n    example: `orb Vase @destructible(health: 10) @collidable {\n  geometry: \"model/vase.glb\"\n  onDestroy: { audio.play('shatter.mp3') }\n}`,\n    relatedTraits: ['@collidable'],\n  },\n\n  // Spatial Traits\n  '@anchor': {\n    name: '@anchor',\n    category: 'spatial',\n    description: 'Object is anchored to a real-world position (AR).',\n    parameters: [\n      {\n        name: 'persist',\n        type: 'boolean',\n        default: 'true',\n        description: 'Persist anchor across sessions',\n      },\n    ],\n    events: ['onAnchorFound', 'onAnchorLost'],\n    example: `orb ARLabel @anchor {\n  geometry: \"plane\"\n  text: \"Kitchen\"\n}`,\n    relatedTraits: ['@world_locked'],\n  },\n\n  '@tracked': {\n    name: '@tracked',\n    category: 'spatial',\n    description: 'Object tracks a real-world entity.',\n    parameters: [\n      { name: 'target', type: 'string', description: 'What to track: head, left_hand, right_hand' },\n    ],\n    events: ['onTrackingLost', 'onTrackingFound'],\n    example: `orb HeadUI @tracked(target: \"head\") {\n  geometry: \"plane\"\n  position: [0, 0, -0.5]\n}`,\n    relatedTraits: ['@hand_tracked', '@eye_tracked'],\n  },\n\n  '@world_locked': {\n    name: '@world_locked',\n    category: 'spatial',\n    description: 'Object stays fixed in world space (ignores user movement).',\n    parameters: [],\n    events: [],\n    example: `orb WorldMarker @world_locked {\n  geometry: \"sphere\"\n  position: [0, 0, -5]\n}`,\n    relatedTraits: ['@anchor'],\n  },\n\n  '@hand_tracked': {\n    name: '@hand_tracked',\n    category: 'spatial',\n    description: 'Object uses hand tracking data.',\n    parameters: [\n      {\n        name: 'hand',\n        type: 'string',\n        default: 'auto',\n        description: 'Which hand: left, right, auto',\n      },\n    ],\n    events: ['onGesture', 'onPinch', 'onPoint'],\n    example: `orb HandMenu @hand_tracked(hand: \"left\") {\n  geometry: \"plane\"\n  position: [0, 0.1, -0.1]\n}`,\n    relatedTraits: ['@tracked'],\n  },\n\n  '@eye_tracked': {\n    name: '@eye_tracked',\n    category: 'spatial',\n    description: 'Object responds to eye tracking.',\n    parameters: [\n      {\n        name: 'dwell_time',\n        type: 'number',\n        default: '500',\n        description: 'Dwell time in ms for activation',\n      },\n    ],\n    events: ['onGaze', 'onGazeEnter', 'onGazeExit', 'onDwell'],\n    example: `orb GazeButton @eye_tracked(dwell_time: 300) {\n  geometry: \"sphere\"\n  onDwell: { this.activate() }\n}`,\n    relatedTraits: ['@tracked'],\n  },\n\n  // Audio Traits\n  '@spatial_audio': {\n    name: '@spatial_audio',\n    category: 'audio',\n    description: 'Object has 3D spatial audio.',\n    parameters: [\n      {\n        name: 'rolloff',\n        type: 'string',\n        default: 'linear',\n        description: 'Distance rolloff: linear, logarithmic',\n      },\n      { name: 'max_distance', type: 'number', default: '10', description: 'Max audible distance' },\n    ],\n    events: [],\n    example: `orb Radio @spatial_audio(max_distance: 15) {\n  audio: { src: \"music.mp3\", loop: true }\n}`,\n    relatedTraits: ['@ambient'],\n  },\n\n  '@ambient': {\n    name: '@ambient',\n    category: 'audio',\n    description: 'Object provides ambient audio (non-directional).',\n    parameters: [{ name: 'volume', type: 'number', default: '1', description: 'Volume level' }],\n    events: [],\n    example: `orb Ambience @ambient(volume: 0.3) {\n  audio: { src: \"forest-ambience.mp3\", loop: true }\n}`,\n    relatedTraits: ['@spatial_audio'],\n  },\n\n  '@voice_activated': {\n    name: '@voice_activated',\n    category: 'audio',\n    description: 'Object responds to voice commands.',\n    parameters: [{ name: 'keywords', type: 'array', description: 'Keywords to listen for' }],\n    events: ['onVoiceCommand', 'onSpeechStart', 'onSpeechEnd'],\n    example: `orb VoiceLight @voice_activated(keywords: [\"lights on\", \"lights off\"]) {\n  onVoiceCommand: |cmd| {\n    if (cmd === \"lights on\") this.emissive = 1\n    else this.emissive = 0\n  }\n}`,\n    relatedTraits: [],\n  },\n\n  // State Traits\n  '@state': {\n    name: '@state',\n    category: 'state',\n    description: 'Object has managed state.',\n    parameters: [],\n    events: ['onChange'],\n    example: `orb Counter @state {\n  state {\n    count: 0\n    maxCount: 100\n  }\n  onClick: { this.count++ }\n}`,\n    relatedTraits: ['@reactive', '@observable'],\n  },\n\n  '@reactive': {\n    name: '@reactive',\n    category: 'state',\n    description: 'Object re-renders on state changes.',\n    parameters: [],\n    events: [],\n    example: `orb Display @reactive {\n  state { message: \"Hello\" }\n  text: \\${message}\n}`,\n    relatedTraits: ['@state', '@computed'],\n  },\n\n  '@observable': {\n    name: '@observable',\n    category: 'state',\n    description: 'External code can subscribe to state changes.',\n    parameters: [],\n    events: ['onSubscribe', 'onUnsubscribe'],\n    example: `orb GameState @observable {\n  state { score: 0, level: 1 }\n}`,\n    relatedTraits: ['@state'],\n  },\n\n  '@computed': {\n    name: '@computed',\n    category: 'state',\n    description: 'Property is derived from other state.',\n    parameters: [{ name: 'deps', type: 'array', description: 'Dependencies' }],\n    events: [],\n    example: `orb Stats @state @computed {\n  state { health: 100, maxHealth: 100 }\n  @computed healthPercent: health / maxHealth * 100\n}`,\n    relatedTraits: ['@state', '@reactive'],\n  },\n\n  // Extended Interaction Traits\n  '@rotatable': {\n    name: '@rotatable',\n    category: 'interaction',\n    description: 'Object can be rotated by the user or auto-rotates on an axis.',\n    parameters: [\n      { name: 'speed', type: 'number', default: '1.0', description: 'Rotation speed multiplier' },\n      { name: 'axis', type: 'string', default: 'y', description: 'Rotation axis: x, y, z' },\n      {\n        name: 'snap_angle',\n        type: 'number',\n        default: '0',\n        description: 'Snap to angle increments in degrees (0 = free rotation)',\n      },\n      {\n        name: 'auto_rotate',\n        type: 'boolean',\n        default: 'false',\n        description: 'Enable continuous auto-rotation',\n      },\n    ],\n    events: ['onRotateStart', 'onRotate', 'onRotateEnd'],\n    example: `orb Turntable @rotatable(axis: \"y\", auto_rotate: true, speed: 0.5) {\n  geometry: \"cylinder\"\n  scale: [1, 0.1, 1]\n}`,\n    relatedTraits: ['@grabbable', '@draggable'],\n  },\n\n  '@snappable': {\n    name: '@snappable',\n    category: 'interaction',\n    description: 'Object snaps to grid positions or predefined snap points when moved.',\n    parameters: [\n      {\n        name: 'grid_size',\n        type: 'number',\n        default: '0.5',\n        description: 'Grid cell size for snapping',\n      },\n      { name: 'snap_points', type: 'array', description: 'Custom [x,y,z] snap point positions' },\n      {\n        name: 'snap_distance',\n        type: 'number',\n        default: '0.3',\n        description: 'Distance threshold to trigger snapping',\n      },\n      {\n        name: 'snap_rotation',\n        type: 'boolean',\n        default: 'false',\n        description: 'Also snap rotation to increments',\n      },\n      {\n        name: 'rotation_snap',\n        type: 'number',\n        default: '45',\n        description: 'Rotation snap increment in degrees',\n      },\n    ],\n    events: ['onSnap', 'onUnsnap'],\n    example: `orb BuildingBlock @grabbable @snappable(grid_size: 1, snap_rotation: true) {\n  geometry: \"cube\"\n  color: \"#44aaff\"\n}`,\n    relatedTraits: ['@grabbable', '@stackable', '@draggable'],\n  },\n\n  // Extended Behavior Traits\n  '@breakable': {\n    name: '@breakable',\n    category: 'behavior',\n    description:\n      'Object shatters into fragments on impact when velocity exceeds the break force threshold.',\n    parameters: [\n      {\n        name: 'break_force',\n        type: 'number',\n        default: '5',\n        description: 'Minimum velocity to trigger breaking',\n      },\n      {\n        name: 'fragments',\n        type: 'number',\n        default: '6',\n        description: 'Number of debris fragments to spawn',\n      },\n      {\n        name: 'fragment_lifetime',\n        type: 'number',\n        default: '4',\n        description: 'Seconds before fragments fade away',\n      },\n    ],\n    events: ['onBreak'],\n    example: `orb GlassPane @physics @breakable(break_force: 3, fragments: 10) {\n  geometry: \"cube\"\n  scale: [1, 1, 0.05]\n  color: \"#aaddff\"\n  @transparent(opacity: 0.5)\n}`,\n    relatedTraits: ['@physics', '@collidable', '@destructible'],\n  },\n\n  '@character': {\n    name: '@character',\n    category: 'behavior',\n    description:\n      'Adds a basic character controller with keyboard movement (WASD), jumping, and gravity.',\n    parameters: [\n      { name: 'speed', type: 'number', default: '3', description: 'Movement speed in m/s' },\n      { name: 'jump_force', type: 'number', default: '5', description: 'Jump impulse force' },\n      { name: 'gravity', type: 'number', default: '-9.81', description: 'Gravity acceleration' },\n      {\n        name: 'ground_level',\n        type: 'number',\n        default: '0',\n        description: 'Y position of the ground plane',\n      },\n    ],\n    events: ['onJump', 'onLand', 'onMove'],\n    example: `orb Player @character(speed: 5, jump_force: 6) @collidable {\n  geometry: \"model/player.glb\"\n  position: [0, 0, 0]\n}`,\n    relatedTraits: ['@collidable', '@physics', '@tracked'],\n  },\n\n  // Advanced Traits\n  '@teleport': {\n    name: '@teleport',\n    category: 'advanced',\n    description:\n      'Parabolic arc teleportation with visual indicator ring. When activated via userData.teleporting, draws a parabolic arc from the object and shows a ground target ring at the landing point.',\n    parameters: [\n      {\n        name: 'arcColor',\n        type: 'string',\n        default: '0x00aaff',\n        description: 'Color of the teleport arc line',\n      },\n      {\n        name: 'ringColor',\n        type: 'string',\n        default: '0x00ff88',\n        description: 'Color of the ground target ring',\n      },\n    ],\n    events: ['onTeleportStart', 'onTeleportConfirm', 'onTeleportCancel'],\n    example: `orb VRController @teleport {\n  geometry: \"model/controller.glb\"\n  // Activate: userData.teleporting = true\n  // Confirm:  userData.confirmTeleport = true\n}`,\n    relatedTraits: ['@pointable', '@portal'],\n  },\n\n  '@ui_panel': {\n    name: '@ui_panel',\n    category: 'advanced',\n    description:\n      'Creates a floating 2D UI panel in 3D space using HTML canvas rendering. Supports dynamic text updates via userData.uiText and userData.uiDirty.',\n    parameters: [\n      { name: 'width', type: 'number', default: '512', description: 'Canvas pixel width' },\n      { name: 'height', type: 'number', default: '256', description: 'Canvas pixel height' },\n      { name: 'text', type: 'string', default: '\"\"', description: 'Initial text content' },\n      {\n        name: 'backgroundColor',\n        type: 'string',\n        default: '#222',\n        description: 'Panel background color',\n      },\n      { name: 'textColor', type: 'string', default: '#fff', description: 'Text color' },\n      { name: 'fontSize', type: 'number', default: '24', description: 'Font size in pixels' },\n    ],\n    events: ['onTextChange'],\n    example: `orb ScoreBoard @ui_panel(width: 512, height: 128, text: \"Score: 0\", backgroundColor: \"#111\", textColor: \"#0f0\", fontSize: 32) @billboard {\n  position: [0, 3, -5]\n}`,\n    relatedTraits: ['@billboard', '@tracked'],\n  },\n\n  '@particle_system': {\n    name: '@particle_system',\n    category: 'advanced',\n    description:\n      'GPU-friendly particle effects such as smoke, fire, and sparks. Particles emit from the object origin and respawn when their lifetime expires.',\n    parameters: [\n      { name: 'count', type: 'number', default: '500', description: 'Number of particles' },\n      { name: 'color', type: 'string', default: '0xffaa00', description: 'Particle color' },\n      { name: 'size', type: 'number', default: '0.05', description: 'Particle size' },\n      { name: 'speed', type: 'number', default: '1', description: 'Upward emission speed' },\n      {\n        name: 'spread',\n        type: 'number',\n        default: '1',\n        description: 'Horizontal emission spread radius',\n      },\n      {\n        name: 'lifetime',\n        type: 'number',\n        default: '3',\n        description: 'Particle lifetime in seconds before respawn',\n      },\n    ],\n    events: [],\n    example: `orb Campfire @particle_system(count: 300, color: \"#ff4400\", size: 0.04, speed: 2, spread: 0.5) @emissive(intensity: 1.5) {\n  geometry: \"model/campfire.glb\"\n  position: [0, 0, -3]\n}`,\n    relatedTraits: ['@emissive', '@glowing'],\n  },\n\n  '@weather': {\n    name: '@weather',\n    category: 'advanced',\n    description:\n      'Dynamic weather effects including rain, snow, and fog. Rain and snow use particle systems while fog modifies the scene fog settings.',\n    parameters: [\n      {\n        name: 'type',\n        type: 'string',\n        default: 'rain',\n        description: \"Weather type: 'rain', 'snow', or 'fog'\",\n      },\n      {\n        name: 'count',\n        type: 'number',\n        default: '2000',\n        description: 'Number of particles (rain/snow only)',\n      },\n      { name: 'area', type: 'number', default: '30', description: 'Area size in meters' },\n      {\n        name: 'intensity',\n        type: 'number',\n        default: '1',\n        description: 'Effect intensity multiplier',\n      },\n    ],\n    events: ['onWeatherChange'],\n    example: `orb SnowEffect @weather(type: \"snow\", count: 3000, area: 40) {\n  position: [0, 10, 0]\n}`,\n    relatedTraits: ['@day_night'],\n  },\n\n  '@day_night': {\n    name: '@day_night',\n    category: 'advanced',\n    description:\n      'Automated sun cycle with realistic color temperature changes. Creates a directional sun light and ambient light that orbit and change color from warm sunrise to cool moonlight over the configured cycle duration.',\n    parameters: [\n      {\n        name: 'cycleDuration',\n        type: 'number',\n        default: '120',\n        description: 'Full day/night cycle duration in seconds',\n      },\n      {\n        name: 'startTime',\n        type: 'number',\n        default: '0',\n        description: 'Starting time as fraction of day (0 = midnight, 0.5 = noon)',\n      },\n    ],\n    events: ['onSunrise', 'onSunset', 'onNoon', 'onMidnight'],\n    example: `orb WorldClock @day_night(cycleDuration: 300, startTime: 0.25) {\n  position: [0, 0, 0]\n  // Exposes: userData.dayNightPhase (\"day\"|\"night\")\n  // Exposes: userData.dayNightProgress (0-1)\n}`,\n    relatedTraits: ['@weather', '@emissive'],\n  },\n\n  '@lod': {\n    name: '@lod',\n    category: 'advanced',\n    description:\n      'Level of Detail optimization that auto-simplifies distant objects. Creates three detail levels: full mesh (near), wireframe (medium), and point cloud (far). Automatically switches based on camera distance.',\n    parameters: [\n      {\n        name: 'distances',\n        type: 'array',\n        default: '[0, 15, 30]',\n        description: 'Distance thresholds [near, medium, far] in meters',\n      },\n    ],\n    events: ['onLODChange'],\n    example: `orb DetailedTree @lod(distances: [0, 20, 50]) {\n  geometry: \"model/tree_detailed.glb\"\n  position: [10, 0, -15]\n}`,\n    relatedTraits: ['@billboard'],\n  },\n\n  '@hand_tracking': {\n    name: '@hand_tracking',\n    category: 'advanced',\n    description:\n      'WebXR hand joint tracking with pinch detection. Renders fingertip spheres and a wrist indicator. Exposes pinch state via userData.pinching and userData.pinchDistance.',\n    parameters: [\n      {\n        name: 'hand',\n        type: 'string',\n        default: 'right',\n        description: \"Which hand to track: 'left' or 'right'\",\n      },\n      {\n        name: 'sphereRadius',\n        type: 'number',\n        default: '0.008',\n        description: 'Radius of fingertip indicator spheres',\n      },\n      {\n        name: 'pinchThreshold',\n        type: 'number',\n        default: '0.02',\n        description: 'Distance threshold for pinch detection (meters)',\n      },\n    ],\n    events: ['onPinchStart', 'onPinchEnd', 'onHandFound', 'onHandLost'],\n    example: `orb LeftHand @hand_tracking(hand: \"left\") {\n  position: [0, 0, 0]\n  // Exposes: userData.pinching (boolean)\n  // Exposes: userData.handTracked (boolean)\n}`,\n    relatedTraits: ['@hand_tracked', '@tracked'],\n  },\n\n  '@haptic': {\n    name: '@haptic',\n    category: 'advanced',\n    description:\n      'VR controller vibration feedback. Triggers a haptic pulse on the specified controller when userData.triggerHaptic is set to true. Supports both standard Gamepad Haptic API and dual-rumble vibration.',\n    parameters: [\n      {\n        name: 'intensity',\n        type: 'number',\n        default: '0.5',\n        description: 'Vibration intensity (0-1)',\n      },\n      {\n        name: 'duration',\n        type: 'number',\n        default: '100',\n        description: 'Vibration duration in milliseconds',\n      },\n      {\n        name: 'hand',\n        type: 'string',\n        default: 'right',\n        description: \"Target controller: 'left', 'right', or 'both'\",\n      },\n      {\n        name: 'cooldown',\n        type: 'number',\n        default: '50',\n        description: 'Minimum ms between consecutive pulses',\n      },\n    ],\n    events: ['onHapticPulse'],\n    example: `orb VRController @haptic(intensity: 0.7, duration: 150, hand: \"right\") {\n  geometry: \"model/controller.glb\"\n  // Trigger feedback: userData.triggerHaptic = true\n}`,\n    relatedTraits: ['@hand_tracking', '@grabbable'],\n  },\n\n  '@botanical_lotus': {\n    name: '@botanical_lotus',\n    category: 'visual',\n    description:\n      'Provenance-grounded lotus material contract for photoreal petals, including SSS, translucency, vein normals, stamen detail, reference anchors, and gravity sag.',\n    parameters: [\n      {\n        name: 'reference_anchors',\n        type: 'array',\n        description: 'CAEL/provenance image anchors used to derive lotus material truth',\n      },\n      {\n        name: 'material',\n        type: 'object',\n        description: 'PBR/SSS material parameters extracted from reference media',\n      },\n      {\n        name: 'petal_rings',\n        type: 'array',\n        default: '[8, 13, 21]',\n        description: 'Deterministic lotus ring layout and gravity-sag metadata',\n      },\n    ],\n    events: ['botanical_lotus_attached', 'botanical_lotus_response'],\n    example: `object \"Garden Lotus\" @botanical_lotus {\n  reference_anchor: \"cael://lotus-purple-2026.jpg\"\n  bloom_state: \"full\"\n}`,\n    relatedTraits: ['@phyllotaxis', '@bloom_reactive', '@gpu_particle', '@glowing'],\n  },\n\n  '@phyllotaxis': {\n    name: '@phyllotaxis',\n    category: 'visual',\n    description:\n      'Deterministic golden-angle placement primitive for petals, seeds, pollen, and other botanical spiral layouts.',\n    parameters: [\n      { name: 'petal_index', type: 'number', default: '0', description: 'Zero-based item index' },\n      {\n        name: 'layer_radii',\n        type: 'array',\n        default: '[2.0, 3.4, 4.8]',\n        description: 'Ring radii for Fibonacci layer placement',\n      },\n      {\n        name: 'layer_counts',\n        type: 'array',\n        default: '[8, 13, 21]',\n        description: 'Ring counts used to select the item layer',\n      },\n      { name: 'seed', type: 'string', default: '0x0000DEAD', description: 'Determinism seed' },\n    ],\n    events: ['phyllotaxis_placed'],\n    example: `object \"Petal P1.0\" @phyllotaxis(petal_index: 0, seed: LOTUS_GENESIS_SEED) {\n  geometry: \"petal\"\n}`,\n    relatedTraits: ['@lotus_petal', '@botanical_lotus', '@bloom_reactive'],\n  },\n\n  '@bloom_reactive': {\n    name: '@bloom_reactive',\n    category: 'visual',\n    description:\n      'Maps a Lotus bloom-state source to visual output such as scale, opacity, emissive intensity, and pulse cadence.',\n    parameters: [\n      {\n        name: 'state',\n        type: 'string',\n        default: 'lotus.api.bloom_state',\n        description: 'Reactive state path to observe',\n      },\n      {\n        name: 'initial_state',\n        type: 'string',\n        default: 'sealed',\n        description: 'Initial bloom stage before external state arrives',\n      },\n      { name: 'sealed', type: 'object', description: 'Visual output while sealed' },\n      { name: 'full', type: 'object', description: 'Visual output at full bloom' },\n    ],\n    events: ['bloom_reactive_attached', 'bloom_reactive_changed'],\n    example: `object \"Lotus Petal\" @bloom_reactive(state: \"lotus.api.bloom_state\", initial_state: \"sealed\") {\n  geometry: \"petal\"\n}`,\n    relatedTraits: ['@lotus_petal', '@botanical_lotus', '@animated', '@glowing'],\n  },\n\n  '@lotus_root': {\n    name: '@lotus_root',\n    category: 'advanced',\n    description:\n      'Lotus program root marker for provenance substrate nodes that feed the staged 16-paper flower.',\n    parameters: [\n      { name: 'root_id', type: 'string', description: 'Root/program identifier' },\n      { name: 'evidence_ids', type: 'array', description: 'W/P/G/I anchors inherited by the root' },\n    ],\n    events: ['lotus_root_attached'],\n    example: `object \"Root: Trust\" @lotus_root(root_id: \"trust-by-construction\") {\n  position: [0, -0.3, 0]\n}`,\n    relatedTraits: ['@lotus_stalk', '@lotus_gardener'],\n  },\n\n  '@lotus_stalk': {\n    name: '@lotus_stalk',\n    category: 'advanced',\n    description:\n      'Lotus program stalk marker for language/format tiers that connect root substrate to paper petals.',\n    parameters: [\n      { name: 'format', type: 'string', description: 'Format tier such as .hs, .hsplus, or .holo' },\n      { name: 'root_id', type: 'string', description: 'Associated Lotus root identifier' },\n    ],\n    events: ['lotus_stalk_attached'],\n    example: `object \"Stalk: Holo\" @lotus_stalk(format: \".holo\", root_id: \"trust-by-construction\") {\n  geometry: \"stem\"\n}`,\n    relatedTraits: ['@lotus_root', '@lotus_petal'],\n  },\n\n  '@lotus_petal': {\n    name: '@lotus_petal',\n    category: 'visual',\n    description:\n      'Lotus paper-petal marker that binds deterministic placement, program metadata, venue, and bloom state.',\n    parameters: [\n      { name: 'paper_id', type: 'string', description: 'Canonical paper/program id' },\n      { name: 'program', type: 'number', description: 'Lotus program ring number' },\n      { name: 'venue', type: 'string', description: 'Target or accepted venue' },\n      {\n        name: 'bloom_state',\n        type: 'string',\n        default: 'sealed',\n        description: 'Current paper state',\n      },\n    ],\n    events: ['lotus_petal_attached', 'lotus_petal_bloom_changed'],\n    example: `object \"Petal P1.0\" @lotus_petal(paper_id: \"trust-by-construction\", program: 1, bloom_state: \"sealed\") {\n  geometry: \"petal\"\n}`,\n    relatedTraits: ['@phyllotaxis', '@bloom_reactive', '@botanical_lotus'],\n  },\n\n  '@lotus_center': {\n    name: '@lotus_center',\n    category: 'visual',\n    description:\n      'Lotus center marker for the Dumb Glass synthesis center and its dormant/post-genesis activation state.',\n    parameters: [\n      { name: 'paper_id', type: 'string', description: 'Center paper identifier' },\n      { name: 'phase', type: 'string', default: 'dormant', description: 'Center activation phase' },\n    ],\n    events: ['lotus_center_attached', 'lotus_center_phase_changed'],\n    example: `object \"Center: Dumb Glass\" @lotus_center(paper_id: \"dumb-glass\", phase: \"dormant\") {\n  geometry: \"seedpod\"\n}`,\n    relatedTraits: ['@botanical_lotus', '@bloom_reactive', '@glowing'],\n  },\n\n  '@lotus_gardener': {\n    name: '@lotus_gardener',\n    category: 'advanced',\n    description:\n      'Lotus garden coordinator trait that publishes staged gate state, seed metadata, and bloom-state summaries.',\n    parameters: [\n      {\n        name: 'staged',\n        type: 'boolean',\n        default: 'true',\n        description: 'Keep genesis assets dormant',\n      },\n      {\n        name: 'genesis_seed',\n        type: 'string',\n        default: '0x0000DEAD',\n        description: 'Pre-genesis or planted seed source',\n      },\n      {\n        name: 'program_count',\n        type: 'number',\n        default: '17',\n        description: 'Expected paper count for the full research program',\n      },\n    ],\n    events: ['lotus_gardener_attached', 'lotus_garden_summary'],\n    example: `object \"Lotus Gardener\" @lotus_gardener(staged: true, genesis_seed: LOTUS_GENESIS_SEED) {\n  visible: false\n}`,\n    relatedTraits: ['@lotus_root', '@lotus_petal', '@phyllotaxis'],\n  },\n\n  '@lotus_genesis_trigger': {\n    name: '@lotus_genesis_trigger',\n    category: 'advanced',\n    description:\n      'Founder-gated Lotus trigger that validates a signed genesis anchor, derives the post-genesis seed, and refuses to fire while the placeholder seed or incomplete petal state remains.',\n    parameters: [\n      {\n        name: 'required_anchor_path',\n        type: 'string',\n        default: 'D:/GOLD/anchors/lotus-genesis.json',\n        description: 'Documentary source path for the founder-gated genesis anchor',\n      },\n      {\n        name: 'placeholder_seed',\n        type: 'string',\n        default: '0x0000DEAD',\n        description: 'Pre-genesis placeholder seed that blocks firing',\n      },\n      {\n        name: 'required_wallet',\n        type: 'string',\n        description: 'Founder wallet expected on the signed anchor',\n      },\n    ],\n    events: ['lotus_genesis_trigger_attached', 'lotus_genesis_blocked', 'lotus_genesis_fired'],\n    example: `object \"Lotus Genesis Trigger\" @lotus_genesis_trigger(required_anchor_path: \"D:/GOLD/anchors/lotus-genesis.json\") {\n  enabled: false\n}`,\n    relatedTraits: ['@lotus_center', '@lotus_gardener', '@gpu_particle', '@spatial_audio'],\n  },\n\n  '@portal': {\n    name: '@portal',\n    category: 'advanced',\n    description:\n      'Teleportation gateway with glowing torus ring and semi-transparent surface. Objects tagged as teleportable or isPlayer that enter the activation distance are instantly moved to the destination coordinates.',\n    parameters: [\n      {\n        name: 'destination',\n        type: 'array',\n        default: '[0, 0, 0]',\n        description: 'Target [x, y, z] teleport coordinates',\n      },\n      { name: 'color', type: 'string', default: '#8800ff', description: 'Portal glow color' },\n      {\n        name: 'activationDistance',\n        type: 'number',\n        default: '1',\n        description: 'Distance in meters to trigger teleportation',\n      },\n      { name: 'radius', type: 'number', default: '1.2', description: 'Portal ring radius' },\n    ],\n    events: ['onPortalEnter', 'onPortalExit'],\n    example: `orb DungeonPortal @portal(destination: [50, 0, 50], color: \"#ff00ff\", activationDistance: 1.5) @spatial_audio {\n  position: [0, 1.5, -5]\n  audio: { src: \"portal-hum.mp3\", loop: true }\n}`,\n    relatedTraits: ['@teleport', '@trigger', '@glowing'],\n  },\n\n  '@mirror': {\n    name: '@mirror',\n    category: 'advanced',\n    description:\n      'Reflective surface with metallic material and a subtle frame. Creates a highly reflective plane with configurable tint and orientation. Supports vertical, horizontal, or camera-facing modes.',\n    parameters: [\n      { name: 'size', type: 'number', default: '2', description: 'Mirror plane size in meters' },\n      { name: 'tint', type: 'string', default: '#ffffff', description: 'Reflection tint color' },\n      {\n        name: 'orientation',\n        type: 'string',\n        default: 'vertical',\n        description: \"Mirror orientation: 'vertical', 'horizontal', or 'face_camera'\",\n      },\n    ],\n    events: [],\n    example: `orb WallMirror @mirror(size: 3, tint: \"#f0f0ff\", orientation: \"vertical\") {\n  position: [0, 1.5, -4]\n}`,\n    relatedTraits: ['@reflective', '@billboard'],\n  },\n};\n\ninterface TraitDoc {\n  name: string;\n  category: string;\n  description: string;\n  parameters: { name: string; type: string; default?: string; description: string }[];\n  events: string[];\n  example: string;\n  relatedTraits: string[];\n}\n\n// === SYNTAX DOCUMENTATION ===\n\nexport const SYNTAX_DOCS: Record<string, SyntaxDoc> = {\n  orb: {\n    topic: 'orb',\n    description:\n      'LEGACY: Define a 3D object. Prefer using composition/template/object pattern for new code.',\n    syntax: `// LEGACY SYNTAX (still supported):\norb <name> [traits] {\n  geometry: \"<type>\"\n  position: [x, y, z]\n  color: \"<hex>\"\n}\n\n// MODERN SYNTAX (recommended):\ncomposition \"Scene\" {\n  template \"MyTemplate\" {\n    @traits\n    geometry: \"<type>\"\n    color: \"<hex>\"\n  }\n  object \"MyObject\" using \"MyTemplate\" {\n    position: [x, y, z]\n  }\n}`,\n    examples: [\n      {\n        description: 'Modern composition pattern (recommended)',\n        code: `composition \"MyScene\" {\n  template \"SphereTemplate\" {\n    @grabbable @glowing\n    geometry: \"sphere\"\n    color: \"#00ffff\"\n  }\n\n  object \"MySphere\" using \"SphereTemplate\" {\n    position: [0, 1, 0]\n  }\n}`,\n      },\n      {\n        description: 'Legacy orb syntax (still works)',\n        code: `orb MyCube @grabbable() @glowing() {\n  geometry: \"cube\"\n  color: \"#ff8800\"\n  position: [2, 1, 0]\n}`,\n      },\n    ],\n  },\n\n  object: {\n    topic: 'object',\n    description: 'Define a 3D object in .holo composition syntax.',\n    syntax: `object \"<name>\" [using \"<template>\"] [@traits] {\n  geometry: \"<type>\"\n  position: [x, y, z]\n  // ... properties\n}`,\n    examples: [\n      {\n        description: 'Basic object',\n        code: `object \"Crystal\" @glowing() {\n  geometry: \"model/crystal.glb\"\n  position: [0, 1, -2]\n}`,\n      },\n      {\n        description: 'Object using template',\n        code: `object \"Enemy_1\" using \"EnemyTemplate\" {\n  position: [5, 0, 5]\n  state { variant: \"red\" }\n}`,\n      },\n    ],\n  },\n\n  template: {\n    topic: 'template',\n    description: 'Define a reusable object template in .holo compositions.',\n    syntax: `template \"<name>\" {\n  geometry: \"<type>\"\n  \n  state {\n    <propertyName>: <defaultValue>\n    // ...\n  }\n  \n  action <actionName>(<params>) {\n    // behavior\n  }\n}`,\n    examples: [\n      {\n        description: 'Enemy template',\n        code: `template \"Enemy\" {\n  geometry: \"model/enemy.glb\"\n  \n  state {\n    health: 100\n    damage: 10\n  }\n  \n  action takeDamage(amount) {\n    health -= amount\n    if (health <= 0) destroy()\n  }\n}`,\n      },\n    ],\n  },\n\n  composition: {\n    topic: 'composition',\n    description: 'Top-level container for a .holo scene definition.',\n    syntax: `composition \"<Scene Name>\" {\n  environment { ... }\n  \n  template \"<TemplateName>\" { ... }\n  \n  spatial_group \"<GroupName>\" {\n    object \"<ObjectName>\" { ... }\n  }\n  \n  logic { ... }\n}`,\n    examples: [\n      {\n        description: 'Complete scene',\n        code: `composition \"Forest Clearing\" {\n  environment {\n    skybox: \"forest\"\n    ambient_light: 0.4\n  }\n  \n  spatial_group \"Trees\" {\n    object \"Oak_1\" { position: [-3, 0, -5] }\n    object \"Oak_2\" { position: [3, 0, -4] }\n  }\n  \n  logic {\n    on_player_enter() {\n      audio.play(\"forest-ambience.mp3\")\n    }\n  }\n}`,\n      },\n    ],\n  },\n\n  materials: {\n    topic: 'materials',\n    description:\n      'Define a PBR material with @advanced_pbr and compose it onto an object alongside an imported model. Use this instead of a flat color/geometry primitive whenever visual realism matters — full pattern library: docs/handbooks/holoscript-realistic-authoring-patterns.md.',\n    syntax: `material \"<Name>\" @advanced_pbr {\n  base_color: \"<hex>\"\n  roughness: <0-1>\n  metallic: <0-1>\n  albedo_map: \"<path>\"\n  normal_map: \"<path>\"\n  ao_map: \"<path>\"\n  height_map: \"<path>\"\n  subsurface: <0-1>\n  translucency: <0-1>\n  wetness: <0-1>\n  ior: <number>\n  emission_intensity: <0-1>\n}\n\nobject \"<Name>\" @collidable @advanced_pbr() {\n  position: [x, y, z]\n  model: \"<path.glb>\"\n  material: \"<Name>\"\n}`,\n    examples: [\n      {\n        description: 'Weathered ground material with full texture-map decomposition',\n        code: `material \"ForestGround\" @advanced_pbr {\n  base_color: \"#5d4037\"\n  roughness: 0.85\n  metallic: 0.0\n  albedo_map: \"textures/ground_albedo.png\"\n  normal_map: \"textures/ground_normal.png\"\n  ao_map: \"textures/ground_ao.png\"\n  height_map: \"textures/ground_height.png\"\n  tiling: [4.0, 4.0]\n  displacement_strength: 0.15\n  wetness: 0.35\n}`,\n      },\n      {\n        description: 'Imported model composed with a named material (not an inline primitive)',\n        code: `object \"Boulder\" @collidable @advanced_pbr() {\n  position: [12, 3, -5]\n  model: \"models/boulder.glb\"\n  collider: { type: \"mesh\", convex: true, friction: 0.8, restitution: 0.1 }\n  rigidbody: { mass: 500, angular_damping: 0.95, linear_damping: 0.1 }\n  material: \"ForestGround\"\n}`,\n      },\n      {\n        description: 'Organic material using subsurface/translucency for backlit realism',\n        code: `material \"Foliage\" @advanced_pbr {\n  base_color: \"#1e4020\"\n  roughness: 0.7\n  metallic: 0.0\n  albedo_map: \"textures/foliage_albedo.png\"\n  normal_map: \"textures/foliage_normal.png\"\n  subsurface: 0.45\n  subsurface_color: \"#3a7030\"\n  translucency: 0.3\n  two_sided: true\n}`,\n      },\n    ],\n  },\n\n  environment: {\n    topic: 'environment',\n    description: 'Configure scene environment (skybox, lighting, fog).',\n    syntax: `environment {\n  skybox: \"<preset>\" | \"<url>\"\n  ambient_light: <0-1>\n  fog: { enabled: true, color: \"<hex>\", density: <number> }\n  gravity: [x, y, z]\n}`,\n    examples: [\n      {\n        description: 'Space environment',\n        code: `environment {\n  skybox: \"nebula\"\n  ambient_light: 0.1\n  fog: { enabled: false }\n  gravity: [0, 0, 0]\n}`,\n      },\n    ],\n  },\n\n  spatial_group: {\n    topic: 'spatial_group',\n    description:\n      'DEPRECATED: Group objects. Instead, use multiple templates and objects within a composition.',\n    syntax: `// DEPRECATED - use composition pattern instead:\ncomposition \"Scene\" {\n  template \"FurnitureTemplate\" { ... }\n\n  // Objects can be organized logically without spatial_group\n  object \"Couch\" using \"FurnitureTemplate\" { position: [0, 0, 0] }\n  object \"Table\" using \"FurnitureTemplate\" { position: [2, 0, 1] }\n}`,\n    examples: [\n      {\n        description: 'Modern pattern (recommended)',\n        code: `composition \"LivingRoom\" {\n  environment {\n    name: \"Living Room\"\n  }\n\n  template \"Furniture\" {\n    @collidable\n    geometry: \"model/furniture.glb\"\n  }\n\n  object \"Couch\" using \"Furniture\" { position: [0, 0, 0] }\n  object \"Table\" using \"Furniture\" { position: [2, 0, 1] }\n  object \"Lamp\" using \"Furniture\" { position: [3, 1, 0] }\n}`,\n      },\n    ],\n  },\n\n  logic: {\n    topic: 'logic',\n    description: 'Define scene-level logic and event handlers.',\n    syntax: `logic {\n  on_<event>([params]) {\n    // handler code\n  }\n  \n  function <name>(<params>) {\n    // function body\n  }\n}`,\n    examples: [\n      {\n        description: 'Game logic',\n        code: `logic {\n  on_scene_start() {\n    score = 0\n    timer.start(60)\n  }\n  \n  on_player_collect(item) {\n    score += item.value\n    audio.play(\"collect.mp3\")\n  }\n  \n  function checkWin() {\n    if (score >= 100) scene.load(\"victory\")\n  }\n}`,\n      },\n    ],\n  },\n\n  animation: {\n    topic: 'animation',\n    description: 'Define property animations in HoloScript.',\n    syntax: `animation {\n  property: \"<prop.path>\"\n  from: <startValue>\n  to: <endValue>\n  duration: <ms>\n  easing: \"<function>\"\n  loop: \"once\" | \"infinite\" | \"pingpong\"\n}`,\n    examples: [\n      {\n        description: 'Hover animation',\n        code: `orb Gem @animated() {\n  geometry: \"model/gem.glb\"\n  animation: {\n    property: \"position.y\"\n    from: 1\n    to: 1.5\n    duration: 2000\n    easing: \"easeInOut\"\n    loop: \"pingpong\"\n  }\n}`,\n      },\n    ],\n  },\n\n  physics: {\n    topic: 'physics',\n    description: 'Configure physics properties for objects.',\n    syntax: `physics: {\n  type: \"dynamic\" | \"kinematic\" | \"static\"\n  mass: <number>\n  friction: <0-1>\n  restitution: <0-1>\n  linearDamping: <number>\n  angularDamping: <number>\n}`,\n    examples: [\n      {\n        description: 'Bouncy ball',\n        code: `orb Ball @physics() @collidable() {\n  geometry: \"sphere\"\n  physics: {\n    type: \"dynamic\"\n    mass: 0.5\n    restitution: 0.9  // Very bouncy\n    friction: 0.1\n  }\n}`,\n      },\n    ],\n  },\n\n  events: {\n    topic: 'events',\n    description: 'Handle interaction and lifecycle events.',\n    syntax: `on<EventName>: { <handler code> }\n\n// Or with parameters:\non<EventName>(param1, param2) { <handler code> }`,\n    examples: [\n      {\n        description: 'Event handlers',\n        code: `orb Button @clickable() @hoverable() {\n  geometry: \"cube\"\n  \n  onClick: { door.toggle() }\n  \n  onHoverEnter: { \n    this.color = \"#00ff00\"\n    audio.play(\"hover.mp3\")\n  }\n  \n  onHoverExit: { this.color = \"#888888\" }\n  \n  onCollisionEnter(other) {\n    this.health -= 10\n  }\n}`,\n      },\n    ],\n  },\n\n  networking: {\n    topic: 'networking',\n    description: 'Configure multiplayer networking for objects.',\n    syntax: `// Basic networked object\nobject \"Name\" @networked {\n  @networked position    // Sync position\n  @networked rotation    // Sync rotation\n  @networked state.score // Sync custom state\n}\n\n// Ownership\nobject \"Name\" @networked @owned {\n  // Only owner can modify\n}`,\n    examples: [\n      {\n        description: 'Multiplayer object',\n        code: `orb SharedBall @networked(sync_rate: \"30hz\") @grabbable() {\n  geometry: \"sphere\"\n  @networked position\n  @networked rotation\n  @networked color\n  \n  onGrab: {\n    network.claim(this)\n  }\n  \n  onRelease: {\n    network.sync(this.position, this.rotation)\n  }\n}`,\n      },\n    ],\n  },\n\n  traits: {\n    topic: 'traits',\n    description: 'Apply VR traits to objects for behavior and interactivity.',\n    syntax: `// Single trait\n@traitName\n\n// Trait with parameters\n@traitName(param1: value1, param2: value2)\n\n// Multiple traits\n@trait1 @trait2 @trait3`,\n    examples: [\n      {\n        description: 'Trait combinations',\n        code: `// Interactive weapon\norb Sword @grabbable() @throwable() @spatial_audio() {\n  geometry: \"model/sword.glb\"\n}\n\n// Physics puzzle piece\norb Block @physics() @collidable() @stackable(max_stack: 10) {\n  geometry: \"cube\"\n}\n\n// Multiplayer avatar\norb Avatar @networked() @owned() @hand_tracked() {\n  geometry: \"model/avatar.glb\"\n}`,\n      },\n    ],\n  },\n};\n\ninterface SyntaxDoc {\n  topic: string;\n  description: string;\n  syntax: string;\n  examples: { description: string; code: string }[];\n}\n\n// === EXAMPLES ===\n\nexport const EXAMPLES: Record<string, ExampleDoc> = {\n  'interactive-object': {\n    pattern: 'interactive-object',\n    description: 'A grabbable, interactive object with haptic feedback.',\n    code: `orb Crystal @grabbable @glowing(intensity: 0.8) @collidable {\n  geometry: \"model/crystal.glb\"\n  color: \"#00ffff\"\n  position: [0, 1, -2]\n  \n  state {\n    isActive: false\n  }\n  \n  onGrab: {\n    haptic.feedback('medium')\n    audio.play('pickup.mp3')\n    isActive = true\n  }\n  \n  onRelease: {\n    audio.play('drop.mp3')\n    isActive = false\n  }\n}`,\n    useCases: ['Collectible items', 'Puzzle pieces', 'Tools'],\n  },\n\n  'multiplayer-sync': {\n    pattern: 'multiplayer-sync',\n    description: 'Object synchronized across all players in multiplayer.',\n    code: `orb SharedBall @networked(sync_rate: \"30hz\") @grabbable @throwable @collidable {\n  geometry: \"sphere\"\n  color: \"#ff8800\"\n  physics: { mass: 0.5, restitution: 0.8 }\n  \n  @networked position\n  @networked rotation\n  @networked velocity\n  \n  onGrab: {\n    network.claim(this)  // Take ownership\n    haptic.feedback('light')\n  }\n  \n  onThrow: {\n    network.sync(this.position, this.rotation, this.velocity)\n  }\n}`,\n    useCases: ['Multiplayer games', 'Collaborative spaces', 'Shared toys'],\n  },\n\n  teleportation: {\n    pattern: 'teleportation',\n    description: 'Teleportation point that moves the player.',\n    code: `orb TeleportPad @pointable @glowing(pulse: true) {\n  geometry: \"cylinder\"\n  scale: [0.5, 0.1, 0.5]\n  color: \"#0088ff\"\n  position: [5, 0, 5]\n  \n  onPoint: {\n    // Visual feedback\n    this.color = \"#00ff00\"\n    audio.play('teleport-charge.mp3')\n  }\n  \n  onPointExit: {\n    this.color = \"#0088ff\"\n  }\n  \n  onRelease: {\n    player.teleportTo(this.position)\n    audio.play('teleport.mp3')\n    haptic.feedback('strong')\n  }\n}`,\n    useCases: ['Navigation', 'Fast travel', 'Accessibility'],\n  },\n\n  portal: {\n    pattern: 'portal',\n    description: 'Portal that transitions to another scene.',\n    code: `orb Portal @trigger @glowing(intensity: 1.5, pulse: true) @spatial_audio {\n  geometry: \"torus\"\n  scale: [1.5, 1.5, 0.3]\n  rotation: [90, 0, 0]\n  color: \"#ff00ff\"\n  \n  audio: { src: \"portal-hum.mp3\", loop: true, volume: 0.5 }\n  \n  state {\n    destination: \"NextLevel\"\n  }\n  \n  onTriggerEnter: |entity| {\n    if (entity.type === \"player\") {\n      audio.play('portal-enter.mp3')\n      haptic.feedback('strong')\n      \n      scene.transition({\n        target: destination,\n        effect: \"fade\",\n        duration: 1000\n      })\n    }\n  }\n}`,\n    useCases: ['Level transitions', 'Room connections', 'Fast travel'],\n  },\n\n  inventory: {\n    pattern: 'inventory',\n    description: 'Inventory system with item slots.',\n    code: `composition \"Inventory UI\" {\n  template \"InventorySlot\" {\n    @hand_tracked(hand: \"left\")\n    \n    state {\n      item: null\n      index: 0\n    }\n    \n    action addItem(newItem) {\n      if (item === null) {\n        item = newItem\n        audio.play('item-add.mp3')\n        return true\n      }\n      return false\n    }\n    \n    action removeItem() {\n      let removed = item\n      item = null\n      return removed\n    }\n  }\n  \n  spatial_group \"InventoryPanel\" @tracked(target: \"left_hand\") {\n    position: [0, 0.1, -0.1]\n    \n    object \"Slot_0\" using \"InventorySlot\" { state.index: 0 }\n    object \"Slot_1\" using \"InventorySlot\" { state.index: 1 }\n    object \"Slot_2\" using \"InventorySlot\" { state.index: 2 }\n  }\n}`,\n    useCases: ['RPG games', 'Crafting systems', 'Tool management'],\n  },\n\n  animation: {\n    pattern: 'animation',\n    description: 'Animated object with multiple properties.',\n    code: `orb FloatingGem @animated @glowing(pulse: true) {\n  geometry: \"model/gem.glb\"\n  color: \"#00ffff\"\n  position: [0, 2, -3]\n  \n  // Hover animation\n  animation hover {\n    property: \"position.y\"\n    from: 2\n    to: 2.5\n    duration: 2000\n    easing: \"easeInOut\"\n    loop: \"pingpong\"\n  }\n  \n  // Rotation animation\n  animation spin {\n    property: \"rotation.y\"\n    from: 0\n    to: 360\n    duration: 4000\n    easing: \"linear\"\n    loop: \"infinite\"\n  }\n  \n  // Glow pulse (using trait)\n  @glowing(intensity: 0.5, pulse: true)\n}`,\n    useCases: ['Decorative objects', 'Collectibles', 'Visual feedback'],\n  },\n\n  'physics-puzzle': {\n    pattern: 'physics-puzzle',\n    description: 'Physics-based puzzle with stackable blocks.',\n    code: `composition \"Block Puzzle\" {\n  environment {\n    gravity: [0, -9.8, 0]\n  }\n  \n  template \"PuzzleBlock\" {\n    @physics(type: \"dynamic\", mass: 1)\n    @collidable\n    @grabbable\n    @stackable(max_stack: 10)\n    \n    state {\n      color: \"#888888\"\n      isCorrect: false\n    }\n    \n    action checkPosition() {\n      // Check if block is in correct position\n      if (isInTargetZone(position)) {\n        isCorrect = true\n        color = \"#00ff00\"\n        audio.play('correct.mp3')\n      }\n    }\n  }\n  \n  spatial_group \"Blocks\" {\n    object \"Block_1\" using \"PuzzleBlock\" { \n      geometry: \"cube\"\n      position: [0, 0.5, 0]\n    }\n    object \"Block_2\" using \"PuzzleBlock\" { \n      geometry: \"cube\"\n      position: [1, 0.5, 0]\n    }\n    object \"Block_3\" using \"PuzzleBlock\" { \n      geometry: \"cube\"\n      position: [2, 0.5, 0]\n    }\n  }\n  \n  // Target zone (trigger)\n  object \"TargetZone\" @trigger {\n    geometry: \"cube\"\n    scale: [1, 0.1, 1]\n    position: [5, 0, 0]\n    color: \"#ffff00\"\n    opacity: 0.3\n  }\n}`,\n    useCases: ['Puzzle games', 'Building mechanics', 'Educational apps'],\n  },\n\n  'ui-panel': {\n    pattern: 'ui-panel',\n    description: 'Interactive UI panel in VR space.',\n    code: `orb SettingsPanel @billboard(axis: \"y\") @tracked(target: \"head\") {\n  geometry: \"plane\"\n  scale: [0.8, 0.5, 1]\n  position: [0, 0, -1.5]\n  color: \"#222222\"\n  \n  children {\n    // Title\n    orb Title {\n      geometry: \"text\"\n      text: \"Settings\"\n      position: [0, 0.2, 0.01]\n      fontSize: 0.08\n    }\n    \n    // Volume slider\n    orb VolumeSlider @draggable(axis: \"x\", bounds: { min: -0.3, max: 0.3 }) {\n      geometry: \"sphere\"\n      scale: [0.05, 0.05, 0.05]\n      position: [0, 0, 0.01]\n      color: \"#00ff00\"\n      \n      onDrag: {\n        let volume = (this.position.x + 0.3) / 0.6\n        audio.setMasterVolume(volume)\n      }\n    }\n    \n    // Close button\n    orb CloseButton @clickable {\n      geometry: \"plane\"\n      scale: [0.1, 0.1, 1]\n      position: [0.35, 0.2, 0.01]\n      color: \"#ff0000\"\n      text: \"X\"\n      \n      onClick: {\n        parent.visible = false\n      }\n    }\n  }\n}`,\n    useCases: ['Menus', 'Settings', 'Information displays'],\n  },\n\n  'audio-ambient': {\n    pattern: 'audio-ambient',\n    description: 'Spatial and ambient audio setup.',\n    code: `composition \"Forest Audio\" {\n  // Non-directional background\n  object \"Ambience\" @ambient(volume: 0.3) {\n    audio: {\n      src: \"forest-ambience.mp3\"\n      loop: true\n      autoplay: true\n    }\n  }\n  \n  // Directional waterfall\n  object \"Waterfall\" @spatial_audio(rolloff: \"logarithmic\", max_distance: 20) {\n    geometry: \"model/waterfall.glb\"\n    position: [-10, 0, -15]\n    \n    audio: {\n      src: \"waterfall.mp3\"\n      loop: true\n      volume: 0.8\n    }\n  }\n  \n  // Interactive bird\n  object \"Bird\" @spatial_audio @clickable {\n    geometry: \"model/bird.glb\"\n    position: [5, 3, -8]\n    \n    onClick: {\n      audio.play('bird-chirp.mp3')\n    }\n  }\n}`,\n    useCases: ['Atmosphere', 'Sound design', 'Immersive environments'],\n  },\n\n  'day-night-cycle': {\n    pattern: 'day-night-cycle',\n    description: 'Dynamic day/night cycle with lighting changes.',\n    code: `composition \"Day Night Cycle\" {\n  state {\n    timeOfDay: 0.5  // 0 = midnight, 0.5 = noon, 1 = midnight\n    cycleDuration: 120000  // 2 minutes for full cycle\n  }\n  \n  environment {\n    skybox: \"dynamic\"\n  }\n  \n  object \"Sun\" @emissive {\n    geometry: \"sphere\"\n    scale: [5, 5, 5]\n    color: \"#ffff00\"\n    \n    // Position based on time\n    position: [\n      cos(timeOfDay * PI * 2) * 50,\n      sin(timeOfDay * PI * 2) * 50,\n      0\n    ]\n  }\n  \n  object \"Moon\" @emissive(intensity: 0.3) {\n    geometry: \"sphere\"\n    scale: [3, 3, 3]\n    color: \"#aaaaff\"\n    \n    position: [\n      -cos(timeOfDay * PI * 2) * 50,\n      -sin(timeOfDay * PI * 2) * 50,\n      0\n    ]\n  }\n  \n  logic {\n    on_update(deltaTime) {\n      timeOfDay += deltaTime / cycleDuration\n      if (timeOfDay > 1) timeOfDay -= 1\n      \n      // Update ambient light based on time\n      let lightLevel = sin(timeOfDay * PI)\n      environment.ambient_light = 0.1 + lightLevel * 0.6\n    }\n  }\n}`,\n    useCases: ['Open worlds', 'Simulation', 'Atmosphere'],\n  },\n\n  'procedural-generation': {\n    pattern: 'procedural-generation',\n    description: 'Procedurally generated content using templates.',\n    code: `composition \"Procedural Forest\" {\n  template \"Tree\" {\n    geometry: \"model/tree.glb\"\n    @collidable\n    \n    state {\n      variant: Math.floor(Math.random() * 3)\n      size: 0.8 + Math.random() * 0.4\n    }\n    \n    scale: [size, size, size]\n  }\n  \n  template \"Rock\" {\n    geometry: \"model/rock.glb\"\n    @collidable\n    @physics(type: \"static\")\n  }\n  \n  spatial_group \"GeneratedForest\" {\n    // Generate trees in a grid with randomization\n    @for i in range(10) {\n      @for j in range(10) {\n        object \"Tree_{i}_{j}\" using \"Tree\" {\n          position: [\n            i * 3 + random(-1, 1),\n            0,\n            j * 3 + random(-1, 1)\n          ]\n          rotation: [0, random(0, 360), 0]\n        }\n      }\n    }\n    \n    // Scatter rocks\n    @for k in range(20) {\n      object \"Rock_{k}\" using \"Rock\" {\n        position: [\n          random(-15, 15),\n          0,\n          random(-15, 15)\n        ]\n        scale: [random(0.5, 1.5), random(0.5, 1.5), random(0.5, 1.5)]\n      }\n    }\n  }\n}`,\n    useCases: ['Terrain generation', 'Decoration', 'Game levels'],\n  },\n\n  'hand-tracking': {\n    pattern: 'hand-tracking',\n    description: 'Hand tracking with gesture detection.',\n    code: `composition \"Hand Tracking Demo\" {\n  // Left hand UI menu\n  object \"LeftHandMenu\" @hand_tracked(hand: \"left\") {\n    geometry: \"plane\"\n    scale: [0.15, 0.1, 1]\n    position: [0, 0.05, -0.05]\n    visible: false\n    \n    // Show when palm faces up\n    onGesture: |gesture| {\n      if (gesture === \"palm_up\") {\n        visible = true\n      } else {\n        visible = false\n      }\n    }\n  }\n  \n  // Right hand pointer\n  object \"RightHandPointer\" @hand_tracked(hand: \"right\") {\n    geometry: \"cone\"\n    scale: [0.02, 0.1, 0.02]\n    rotation: [-90, 0, 0]\n    color: \"#00ffff\"\n    \n    onPinch: {\n      // Ray cast from pointer\n      let hit = physics.raycast(\n        this.position,\n        this.forward,\n        10\n      )\n      \n      if (hit) {\n        hit.object.trigger('onClick')\n        haptic.feedback('light')\n      }\n    }\n  }\n  \n  // Gesture-controlled object\n  object \"GestureOrb\" @grabbable {\n    geometry: \"sphere\"\n    position: [0, 1.5, -1]\n    \n    onGesture: |gesture| {\n      switch (gesture) {\n        case \"thumbs_up\":\n          this.color = \"#00ff00\"\n          break\n        case \"thumbs_down\":\n          this.color = \"#ff0000\"\n          break\n        case \"peace\":\n          this.scale = [1.5, 1.5, 1.5]\n          break\n      }\n    }\n  }\n}`,\n    useCases: ['Gesture controls', 'Natural interaction', 'Accessibility'],\n  },\n};\n\ninterface ExampleDoc {\n  pattern: string;\n  description: string;\n  code: string;\n  useCases: string[];\n}\n","/**\n * AUTO-GENERATED by scripts/sync-examples-catalog.mjs — DO NOT EDIT BY HAND.\n * Source of truth: examples/examples-health.matrix.json (repo root) + the\n * examples/ tree (full inventory counts).\n * Regenerate: pnpm --filter @holoscript/mcp-server sync:examples-catalog\n *\n * This is the audited PUBLIC example catalog (status + link policy per example)\n * plus a full-tree inventory summary, projected so the get_examples MCP tool\n * serves real repo state instead of a stale hardcoded shadow library.\n */\nexport interface ExampleCatalogEntry {\n  slug: string;\n  path: string;\n  format: string;\n  category: string;\n  status: string;\n  linkPolicy: string;\n  reason: string;\n  priority: boolean;\n}\n\nexport interface ExampleInventory {\n  /** Total .hs/.hsplus/.holo example files in examples/ (excludes .refreshed.* siblings). */\n  total: number;\n  byFormat: Record<string, number>;\n  byCategory: Record<string, number>;\n}\n\nexport const EXAMPLE_CATALOG: ExampleCatalogEntry[] = [\n  {\n    \"slug\": \"hello-world\",\n    \"path\": \"examples/hello-world.hs\",\n    \"format\": \"hs\",\n    \"category\": \"root\",\n    \"status\": \"supported\",\n    \"linkPolicy\": \"public-supported\",\n    \"reason\": \"Baseline .hs quickstart example.\",\n    \"priority\": true\n  },\n  {\n    \"slug\": \"solar_system\",\n    \"path\": \"examples/solar_system.holo\",\n    \"format\": \"holo\",\n    \"category\": \"root\",\n    \"status\": \"supported\",\n    \"linkPolicy\": \"public-supported\",\n    \"reason\": \"Baseline .holo scene example.\",\n    \"priority\": true\n  },\n  {\n    \"slug\": \"multiplayer-game\",\n    \"path\": \"examples/multiplayer-game.hsplus\",\n    \"format\": \"hsplus\",\n    \"category\": \"root\",\n    \"status\": \"supported\",\n    \"linkPolicy\": \"public-supported\",\n    \"reason\": \"Baseline .hsplus behavior example.\",\n    \"priority\": true\n  },\n  {\n    \"slug\": \"three-format-showcase/smart-gallery\",\n    \"path\": \"examples/three-format-showcase/smart-gallery.hs\",\n    \"format\": \"hs\",\n    \"category\": \"three-format-showcase\",\n    \"status\": \"supported\",\n    \"linkPolicy\": \"public-supported\",\n    \"reason\": \"Procedural lane of the three-format showcase parses successfully.\",\n    \"priority\": true\n  },\n  {\n    \"slug\": \"three-format-showcase/smart-gallery\",\n    \"path\": \"examples/three-format-showcase/smart-gallery.hsplus\",\n    \"format\": \"hsplus\",\n    \"category\": \"three-format-showcase\",\n    \"status\": \"supported\",\n    \"linkPolicy\": \"public-supported\",\n    \"reason\": \"Behavior lane of the three-format showcase parses successfully.\",\n    \"priority\": true\n  },\n  {\n    \"slug\": \"novel-use-cases/05-robot-training-metaverse\",\n    \"path\": \"examples/novel-use-cases/05-robot-training-metaverse.holo\",\n    \"format\": \"holo\",\n    \"category\": \"novel-use-cases\",\n    \"status\": \"aspirational-grammar\",\n    \"linkPolicy\": \"public-aspirational-label-required\",\n    \"reason\": \"Uses autonomous ecosystem behavior blocks inside a .holo composition; HoloCompositionParser does not accept that grammar yet.\",\n    \"priority\": true\n  },\n  {\n    \"slug\": \"novel-use-cases/05-robot-training-metaverse\",\n    \"path\": \"examples/novel-use-cases/05-robot-training-metaverse.hs\",\n    \"format\": \"hs\",\n    \"category\": \"novel-use-cases\",\n    \"status\": \"supported\",\n    \"linkPolicy\": \"public-supported\",\n    \"reason\": \"Verified 2026-07-03: on_error(...) pipeline handler syntax now parses (compiler-wasm grammar work in flight); promoted from aspirational-grammar.\",\n    \"priority\": true\n  },\n  {\n    \"slug\": \"novel-use-cases/05-robot-training-metaverse\",\n    \"path\": \"examples/novel-use-cases/05-robot-training-metaverse.hsplus\",\n    \"format\": \"hsplus\",\n    \"category\": \"novel-use-cases\",\n    \"status\": \"supported\",\n    \"linkPolicy\": \"public-supported\",\n    \"reason\": \"Verified 2026-07-03: arrow transition shorthand in state-machine maps now parses (compiler-wasm grammar work in flight); promoted from aspirational-grammar.\",\n    \"priority\": true\n  },\n  {\n    \"slug\": \"novel-use-cases/13-disaster-robotics-swarm\",\n    \"path\": \"examples/novel-use-cases/13-disaster-robotics-swarm.holo\",\n    \"format\": \"holo\",\n    \"category\": \"novel-use-cases\",\n    \"status\": \"supported\",\n    \"linkPolicy\": \"public-supported\",\n    \"reason\": \"Verified 2026-07-03: full disaster-training scene grammar now parses (compiler-wasm grammar work in flight); promoted from aspirational-grammar.\",\n    \"priority\": true\n  },\n  {\n    \"slug\": \"novel-use-cases/13-disaster-robotics-swarm\",\n    \"path\": \"examples/novel-use-cases/13-disaster-robotics-swarm.hs\",\n    \"format\": \"hs\",\n    \"category\": \"novel-use-cases\",\n    \"status\": \"supported\",\n    \"linkPolicy\": \"public-supported\",\n    \"reason\": \"Verified 2026-07-03: dotted property expressions in pipeline properties now parse (compiler-wasm grammar work in flight); promoted from aspirational-grammar.\",\n    \"priority\": true\n  },\n  {\n    \"slug\": \"novel-use-cases/13-disaster-robotics-swarm\",\n    \"path\": \"examples/novel-use-cases/13-disaster-robotics-swarm.hsplus\",\n    \"format\": \"hsplus\",\n    \"category\": \"novel-use-cases\",\n    \"status\": \"supported\",\n    \"linkPolicy\": \"public-supported\",\n    \"reason\": \"Verified 2026-07-03: arrow transition shorthand in behavior state maps now parses (compiler-wasm grammar work in flight); promoted from aspirational-grammar.\",\n    \"priority\": true\n  },\n  {\n    \"slug\": \"sample-projects/physics-playground\",\n    \"path\": \"examples/sample-projects/physics-playground.holo\",\n    \"format\": \"holo\",\n    \"category\": \"sample-projects\",\n    \"status\": \"supported\",\n    \"linkPolicy\": \"public-supported\",\n    \"reason\": \"Verified 2026-07-03: nested post_processing blocks (bloom { ... }) now parse (compiler-wasm grammar work in flight); promoted from aspirational-grammar.\",\n    \"priority\": true\n  },\n  {\n    \"slug\": \"showcase/physics-playground\",\n    \"path\": \"examples/showcase/physics-playground.holo\",\n    \"format\": \"holo\",\n    \"category\": \"showcase\",\n    \"status\": \"supported\",\n    \"linkPolicy\": \"public-supported\",\n    \"reason\": \"Verified 2026-07-03: showcase-scale physics grammar now parses (compiler-wasm grammar work in flight); promoted from aspirational-grammar.\",\n    \"priority\": true\n  },\n  {\n    \"slug\": \"showcase/realistic-forest-refreshed\",\n    \"path\": \"examples/showcase/realistic-forest.refreshed.holo\",\n    \"format\": \"holo\",\n    \"category\": \"showcase\",\n    \"status\": \"supported\",\n    \"linkPolicy\": \"public-supported\",\n    \"reason\": \"Parser success (verified 2026-07-03); flagship example for docs/handbooks/holoscript-realistic-authoring-patterns.md — @advanced_pbr materials, imported glb models, @time_of_day/@volumetric_clouds/@wind environment drivers.\",\n    \"priority\": true\n  },\n  {\n    \"slug\": \"showcase/realistic-forest\",\n    \"path\": \"examples/showcase/realistic-forest.holo\",\n    \"format\": \"holo\",\n    \"category\": \"showcase\",\n    \"status\": \"expected-fail\",\n    \"linkPolicy\": \"internal-only\",\n    \"reason\": \"Pre-refresh version; parser rejects legacy composition syntax at line 352 (Expected LBRACE, got AT). Superseded by realistic-forest.refreshed.holo — kept as a before/after reference in the authoring-patterns handbook, not a working example.\",\n    \"priority\": false\n  },\n  {\n    \"slug\": \"physics/advanced-physics-showcase\",\n    \"path\": \"examples/physics/advanced-physics-showcase.holo\",\n    \"format\": \"holo\",\n    \"category\": \"physics\",\n    \"status\": \"supported\",\n    \"linkPolicy\": \"public-supported\",\n    \"reason\": \"Verified 2026-07-03: nested post_processing blocks and advanced physics traits now parse (compiler-wasm grammar work in flight); promoted from aspirational-grammar.\",\n    \"priority\": true\n  },\n  {\n    \"slug\": \"product-viewer\",\n    \"path\": \"examples/product-viewer.holo\",\n    \"format\": \"holo\",\n    \"category\": \"root\",\n    \"status\": \"expected-fail\",\n    \"linkPolicy\": \"internal-only\",\n    \"reason\": \"Current .holo parser rejects the product viewer's domain-dataviz string property form; keep out of public working-example links until promoted.\",\n    \"priority\": true\n  },\n  {\n    \"slug\": \"hololand/vv-results-visualization-space\",\n    \"path\": \"examples/hololand/vv-results-visualization-space.holo\",\n    \"format\": \"holo\",\n    \"category\": \"hololand\",\n    \"status\": \"supported\",\n    \"linkPolicy\": \"public-supported\",\n    \"reason\": \"Verified 2026-07-03: HoloLand V&V visualization grammar with nested post-processing and dashboard constructs now parses (compiler-wasm grammar work in flight); promoted from aspirational-grammar.\",\n    \"priority\": true\n  },\n  {\n    \"slug\": \"site\",\n    \"path\": \"examples/site.holo\",\n    \"format\": \"holo\",\n    \"category\": \"root\",\n    \"status\": \"deprecated\",\n    \"linkPolicy\": \"archive-only\",\n    \"reason\": \"Legacy v5 landing-page composition retained as archive material; do not feature as a current parser-supported example.\",\n    \"priority\": true\n  }\n];\n\n/** Full-tree inventory of examples/, resolved at build time (no runtime fs). */\nexport const EXAMPLE_INVENTORY: ExampleInventory = {\n  \"total\": 487,\n  \"byFormat\": {\n    \"holo\": 361,\n    \"hs\": 71,\n    \"hsplus\": 55\n  },\n  \"byCategory\": {\n    \"accessibility\": 1,\n    \"root\": 42,\n    \"affordances\": 3,\n    \"agents\": 7,\n    \"ai-generation\": 2,\n    \"ai-npcs\": 1,\n    \"ar\": 1,\n    \"ar-foundation\": 7,\n    \"atoms\": 2,\n    \"audio\": 2,\n    \"autonomous-ecosystems\": 12,\n    \"avatars\": 5,\n    \"biomedical\": 1,\n    \"compute\": 1,\n    \"cross-domain\": 3,\n    \"cross-reality\": 3,\n    \"cryptography\": 6,\n    \"demolition-demo\": 1,\n    \"domain-starters\": 13,\n    \"economy\": 2,\n    \"emotion\": 3,\n    \"enterprise\": 9,\n    \"export-pipelines\": 5,\n    \"general\": 6,\n    \"getting-started\": 2,\n    \"gold-game\": 4,\n    \"government-civic\": 1,\n    \"hololand\": 27,\n    \"hsplus\": 8,\n    \"integration\": 5,\n    \"interaction\": 1,\n    \"interoperability\": 1,\n    \"iot\": 1,\n    \"language-reference\": 13,\n    \"lighting\": 4,\n    \"lotus-flower\": 2,\n    \"multi-target-demo\": 1,\n    \"multisensory\": 3,\n    \"narrative\": 3,\n    \"native\": 24,\n    \"native-assets\": 7,\n    \"networking\": 1,\n    \"neuromorphic\": 3,\n    \"norm-lifecycle\": 1,\n    \"novel-use-cases\": 39,\n    \"npc-roles\": 5,\n    \"openusd\": 1,\n    \"perception-tests\": 7,\n    \"persistence\": 3,\n    \"phonesleevevr\": 1,\n    \"physics\": 1,\n    \"pipelines\": 5,\n    \"platforms\": 11,\n    \"plugins\": 1,\n    \"presets\": 8,\n    \"procedural\": 4,\n    \"quickstart\": 6,\n    \"real-world\": 3,\n    \"reconstruction\": 1,\n    \"rendering\": 5,\n    \"robotics\": 3,\n    \"sample-projects\": 3,\n    \"services\": 4,\n    \"showcase\": 9,\n    \"social-commerce\": 3,\n    \"specialized\": 5,\n    \"stress-tests\": 31,\n    \"TEMPLATE\": 1,\n    \"templates\": 5,\n    \"three-format-showcase\": 3,\n    \"three-world\": 2,\n    \"traits\": 12,\n    \"v5.0-hardened\": 22,\n    \"v6\": 6,\n    \"volumetric\": 6,\n    \"volumetric-advanced\": 5,\n    \"weather\": 5,\n    \"webgpu-compute\": 6,\n    \"wisdom-demo\": 1,\n    \"xr\": 4\n  }\n};\n\n/** Link policies safe to surface as working/featured examples. */\nexport const PUBLIC_LINK_POLICIES = new Set<string>([\n  'public-supported',\n  'public-aspirational-label-required',\n]);\n","/**\n * Sandbox Policy — Unified security policy for forked/untrusted HoloScript code,\n * MCP tools, runtime adapters, and generated plugins.\n *\n * Required checks (per canary task_1778618757735_zpt5):\n *   1. Capability manifest\n *   2. Least-privilege permissions\n *   3. Network/file limits\n *   4. Timeout/resource ceilings\n *   5. Denial receipts\n *\n * Authority: W.GOLD.035, W.GOLD.039, W.GOLD.193\n */\n\n// ── Capability Manifest ──────────────────────────────────────────────────────\n\nexport interface CapabilityAttestation {\n  /** SHA-256 of the canonical manifest body */\n  manifestHash: string;\n  /** Signer identity (wallet, agent handle, or key fingerprint) */\n  signer: string;\n  /** Trust tier at admission time */\n  trustTier: 'founder' | 'diamond' | 'platinum' | 'gold' | 'verified' | 'unverified';\n  /** ISO-8601 timestamp */\n  attestedAt: string;\n  /** Optional Ed25519 signature over the canonical manifest block */\n  signature?: string;\n}\n\nexport interface CapabilityManifest {\n  /** Protocol version */\n  protocol: 'holomesh.tool_manifest.v1' | 'holoscript.capability.v1';\n  /** Declared capabilities (e.g. 'compile', 'actuate:robot', 'inference:*') */\n  declaredCapabilities: string[];\n  /** Attestation proving the manifest was reviewed */\n  attestation?: CapabilityAttestation;\n  /** Source code hash (SHA-256 of canonical source tree) for code subjects */\n  sourceHash?: string;\n  /** Compiler version that produced the artifact */\n  compilerVersion?: string;\n  /** Runtime version required */\n  runtimeVersion?: string;\n}\n\n// ── Sandbox Policy ───────────────────────────────────────────────────────────\n\nexport interface PermissionRequirements {\n  /** OAuth 2.1 scopes required to invoke this subject */\n  requiredScopes: string[];\n  /** Minimum trust tier of the signer/attestation */\n  minTrustTier: CapabilityAttestation['trustTier'];\n  /** Whether the subject is allowed to run in anonymous/open-dev mode */\n  allowAnonymous: boolean;\n}\n\nexport interface NetworkLimits {\n  allowNetwork: boolean;\n  /** Allowed hostnames (exact or wildcard suffix, e.g. '*.holoscript.net') */\n  allowedHosts: string[];\n  /** Max outbound calls per minute */\n  maxCallsPerMinute: number;\n  /** Max total bytes transferred per execution */\n  maxTransferBytes: number;\n}\n\nexport interface FileLimits {\n  allowFsWrites: boolean;\n  /** Allowed path prefixes (relative to rootDir) */\n  allowedPaths: string[];\n  /** Max bytes for any single file operation */\n  maxFileBytes: number;\n  /** Block path-traversal patterns */\n  blockTraversal: boolean;\n}\n\nexport interface ResourceCeilings {\n  /** Max execution time per invocation (ms) */\n  maxExecutionTimeMs: number;\n  /** Max memory per invocation (bytes) */\n  maxMemoryBytes: number;\n  /** Max CPU percent (0-100) — enforced via scheduler where available */\n  maxCpuPercent: number;\n  /** Max nested calls (recursion depth) */\n  maxNestedCalls: number;\n}\n\nexport interface DenialReceiptConfig {\n  /** Emit a structured receipt on denial */\n  emitReceipt: boolean;\n  /** TTL for receipt retention (ms) */\n  receiptTTLMs: number;\n  /** Include full subject payload in receipt (false = hash only) */\n  includePayload: boolean;\n}\n\nexport interface SandboxPolicy {\n  /** Unique policy identifier */\n  policyId: string;\n  /** Human-readable description */\n  description: string;\n  /** Capability manifest requirements */\n  capabilityManifest: {\n    /** Must have a manifest for non-canonical sources */\n    required: boolean;\n    /** Must have attestation for non-canonical sources */\n    attestationRequired: boolean;\n    /** Minimum trust tier for attestation */\n    minAttestationTier: CapabilityAttestation['trustTier'];\n  };\n  permissions: PermissionRequirements;\n  network: NetworkLimits;\n  file: FileLimits;\n  resources: ResourceCeilings;\n  receipt: DenialReceiptConfig;\n  /** Default trust posture when source provenance is unknown */\n  defaultPosture: 'hostile' | 'benign';\n  /** Action classes that are denied by default unless a runtime gate explicitly re-allows them. */\n  defaultBlockedActions: string[];\n}\n\n// ── Sandbox Subject ──────────────────────────────────────────────────────────\n\nexport type SandboxSubjectKind =\n  | 'holoscript_code'\n  | 'mcp_tool'\n  | 'runtime_adapter'\n  | 'generated_plugin';\n\n// 'consumer' is additive (WS-1, 2026-07-02): a genuinely anonymous, non-privileged\n// public session. Nothing produces this value today -- every existing\n// `source === 'fork' | 'generated'` equality check is unaffected. See\n// resolvePolicy() below for the one narrow branch that consumes it.\nexport type SandboxSubjectSource = 'canonical' | 'fork' | 'generated' | 'unknown' | 'consumer';\n\nexport interface SandboxSubject {\n  kind: SandboxSubjectKind;\n  source: SandboxSubjectSource;\n  /** Unique subject identifier */\n  subjectId: string;\n  /** The actual payload: code string, tool args, adapter config, or plugin manifest */\n  payload: string | Record<string, unknown>;\n  /** Optional explicit capability manifest supplied by the caller */\n  manifest?: CapabilityManifest;\n  /** Provenance chain (hashes of upstream artifacts) */\n  provenance?: string[];\n}\n\n// ── Denial Receipt ───────────────────────────────────────────────────────────\n\nexport interface DenialReceipt {\n  receiptId: string;\n  timestamp: string;\n  policyId: string;\n  subject: {\n    kind: SandboxSubjectKind;\n    subjectId: string;\n    source: SandboxSubjectSource;\n    /** SHA-256 of payload (always present) */\n    payloadHash: string;\n    /** Full payload only when receipt.includePayload is true */\n    payload?: string | Record<string, unknown>;\n  };\n  /** Which check failed */\n  failedCheck: string;\n  /** Human-readable reason */\n  reason: string;\n  /** Structured details per check */\n  checks: Array<{ name: string; passed: boolean; detail?: string }>;\n  /** Suggested remediation */\n  remediation: string;\n}\n\n// ── Gate Result ──────────────────────────────────────────────────────────────\n\nexport interface SandboxGateResult {\n  allowed: boolean;\n  /** Present when allowed === false */\n  receipt?: DenialReceipt;\n  /** The policy that was applied */\n  appliedPolicy: SandboxPolicy;\n  /** Per-check results */\n  checks: Array<{ name: string; passed: boolean; detail?: string }>;\n}\n\n// ── Default Policies ─────────────────────────────────────────────────────────\n\nexport const SYSTEM_DEFAULT_BLOCKED_ACTIONS = [\n  'identity:revoke',\n  'contract:ratify',\n  'actuator:command',\n  'robot:move',\n  'robot:task:execute',\n];\n\nexport const DEFAULT_SENSITIVE_POLICY: SandboxPolicy = {\n  policyId: 'holoscript-sensitive-default-v1',\n  description:\n    'Default policy for subjects that may touch HoloLand worlds, robot/AI substrate, payments, or player-impacting state. Treats forked/untrusted sources as hostile.',\n  capabilityManifest: {\n    required: true,\n    attestationRequired: true,\n    minAttestationTier: 'verified',\n  },\n  permissions: {\n    requiredScopes: ['tools:write'],\n    minTrustTier: 'verified',\n    allowAnonymous: false,\n  },\n  network: {\n    allowNetwork: true,\n    allowedHosts: ['mcp.holoscript.net', 'holoscript.net', 'localhost'],\n    maxCallsPerMinute: 60,\n    maxTransferBytes: 10 * 1024 * 1024,\n  },\n  file: {\n    allowFsWrites: false,\n    allowedPaths: ['compositions', 'data', 'src', 'packages', 'examples'],\n    maxFileBytes: 5 * 1024 * 1024,\n    blockTraversal: true,\n  },\n  resources: {\n    maxExecutionTimeMs: 5000,\n    maxMemoryBytes: 128 * 1024 * 1024,\n    maxCpuPercent: 80,\n    maxNestedCalls: 10,\n  },\n  receipt: {\n    emitReceipt: true,\n    receiptTTLMs: 30 * 24 * 60 * 60 * 1000, // 30 days\n    includePayload: false,\n  },\n  defaultPosture: 'hostile',\n  defaultBlockedActions: [...SYSTEM_DEFAULT_BLOCKED_ACTIONS],\n};\n\nexport const DEFAULT_BENIGN_POLICY: SandboxPolicy = {\n  ...DEFAULT_SENSITIVE_POLICY,\n  policyId: 'holoscript-benign-default-v1',\n  description:\n    'Relaxed policy for read-only or computation-only subjects with no sensitive-state access.',\n  capabilityManifest: {\n    required: false,\n    attestationRequired: false,\n    minAttestationTier: 'unverified',\n  },\n  permissions: {\n    requiredScopes: ['tools:read'],\n    minTrustTier: 'unverified',\n    allowAnonymous: true,\n  },\n  network: {\n    allowNetwork: false,\n    allowedHosts: [],\n    maxCallsPerMinute: 0,\n    maxTransferBytes: 0,\n  },\n  file: {\n    allowFsWrites: false,\n    allowedPaths: [],\n    maxFileBytes: 0,\n    blockTraversal: true,\n  },\n  resources: {\n    maxExecutionTimeMs: 3000,\n    maxMemoryBytes: 64 * 1024 * 1024,\n    maxCpuPercent: 50,\n    maxNestedCalls: 5,\n  },\n  defaultPosture: 'benign',\n  defaultBlockedActions: [],\n};\n\n// WS-1 (2026-07-02): a narrow, additive policy for a genuinely anonymous consumer\n// session -- NOT a relaxation of DEFAULT_SENSITIVE_POLICY or DEFAULT_BENIGN_POLICY\n// (both untouched above). Reuses the exact SandboxPolicy/DenialReceipt shape\n// ForkSandboxGate already checks against; scoped ONLY to the 2 tools in\n// CONSUMER_SAFE_TOOL_PATTERNS below and ONLY reachable when a caller explicitly\n// sets subject.source='consumer' (currently POST /api/public/generate).\n// Resource ceilings are strictly <= DEFAULT_BENIGN_POLICY's; network is scoped to\n// the same allowlist as DEFAULT_SENSITIVE_POLICY (generation needs the same LLM\n// proxy, never an arbitrary external host).\nexport const DEFAULT_CONSUMER_GENERATION_POLICY: SandboxPolicy = {\n  policyId: 'holoscript-consumer-generation-v1',\n  description:\n    'Narrow policy for anonymous, non-privileged consumer sessions calling ONLY generate_scene / generate_world_from_prompt (WS-1). Output is never persisted to HoloLand world state; every other sensitive tool stays on DEFAULT_SENSITIVE_POLICY.',\n  capabilityManifest: {\n    required: false,\n    attestationRequired: false,\n    minAttestationTier: 'unverified',\n  },\n  permissions: {\n    requiredScopes: [],\n    minTrustTier: 'unverified',\n    allowAnonymous: true,\n  },\n  network: {\n    allowNetwork: true,\n    allowedHosts: ['mcp.holoscript.net', 'holoscript.net', 'localhost'],\n    maxCallsPerMinute: 10,\n    maxTransferBytes: 2 * 1024 * 1024,\n  },\n  file: {\n    allowFsWrites: false,\n    allowedPaths: [],\n    maxFileBytes: 0,\n    blockTraversal: true,\n  },\n  resources: {\n    maxExecutionTimeMs: 3000,\n    maxMemoryBytes: 64 * 1024 * 1024,\n    maxCpuPercent: 50,\n    maxNestedCalls: 1,\n  },\n  receipt: {\n    emitReceipt: true,\n    receiptTTLMs: 30 * 24 * 60 * 60 * 1000, // 30 days, same retention as sensitive\n    includePayload: false,\n  },\n  defaultPosture: 'hostile',\n  defaultBlockedActions: [...SYSTEM_DEFAULT_BLOCKED_ACTIONS],\n};\n\n// ── Policy Resolution ──────────────────────────────────────────────────────\n\n/** Tools that can touch sensitive state (HoloLand, robot/AI, payments, player-impacting) */\nexport const SENSITIVE_TOOL_PATTERNS = [\n  // HoloLand world CRUD\n  /^generate_world_from_prompt$/,\n  /^generate_world$/,\n  /^create_world$/,\n  /^update_world$/,\n  /^delete_world$/,\n  /^create_shard$/,\n  /^update_shard$/,\n  /^delete_shard$/,\n  /^create_zone$/,\n  /^update_zone$/,\n  /^delete_zone$/,\n  /^create_place$/,\n  /^update_place$/,\n  /^delete_place$/,\n  /^create_location_quest$/,\n  /^update_location_quest$/,\n  /^delete_location_quest$/,\n  /^hololand_publish_zone$/,\n  /^hololand_create_geo_anchor$/,\n  /^hololand_steward_tick$/,\n  /^hololand_capture_runtime_receipt$/,\n  /^hololand_create_npc$/,\n  /^hololand_update_npc$/,\n  /^hololand_delete_npc$/,\n  // Robot / AI substrate\n  /^twin_earth_register_identity$/,\n  /^twin_earth_revoke_identity$/,\n  /^twin_earth_create_safety_envelope$/,\n  /^twin_earth_delete_safety_envelope$/,\n  /^twin_earth_grant_permission$/,\n  /^twin_earth_revoke_permission$/,\n  /^twin_earth_robot_actuate$/,\n  /^twin_earth_ai_invoke$/,\n  /^twin_earth_capture_receipt$/,\n  // Payments / economy\n  /^holo_protocol_/,\n  /^check_agent_budget$/,\n  /^get_creator_earnings$/,\n  /^settle_creator_payout$/,\n  /^optimize_scene_budget$/,\n  /^validate_marketplace_pricing$/,\n  // Plugin management (plugins can inject arbitrary code)\n  /^install_plugin$/,\n  /^install_domain_plugin$/,\n  /^manage_plugin$/,\n  // Code generation / compilation (may produce forked-looking code)\n  /^compile_holoscript$/,\n  /^compile_pipeline$/,\n  /^compile_to_/,\n  /^generate_object$/,\n  /^generate_scene$/,\n  /^generate_world_from_prompt$/,\n  /^generate_semantic_ui$/,\n  /^generate_3d_object$/,\n  /^edit_holo$/,\n  /^convert_format$/,\n];\n\nexport function isSensitiveTool(toolName: string): boolean {\n  return SENSITIVE_TOOL_PATTERNS.some((pattern) => pattern.test(toolName));\n}\n\n// WS-1 (2026-07-02): the ONLY 2 tools a consumer session may reach -- deliberately\n// NOT generate_object / generate_semantic_ui / generate_3d_object / compile_to_* /\n// edit_holo / convert_format (plausible future candidates, explicitly out of this\n// slice's scope). Both entries mirror SENSITIVE_TOOL_PATTERNS's tool names exactly;\n// they are NOT removed from that list (removal would also exempt privileged/forked\n// callers from ForkSandboxGate, which is wrong -- this is an additive parallel path).\nexport const CONSUMER_SAFE_TOOL_PATTERNS = [/^generate_scene$/, /^generate_world_from_prompt$/];\n\nexport function isConsumerSafeTool(toolName: string): boolean {\n  return CONSUMER_SAFE_TOOL_PATTERNS.some((pattern) => pattern.test(toolName));\n}\n\nfunction isConsumerGenerationTierDisabled(): boolean {\n  return process.env.HOLOSCRIPT_CONSUMER_TIER_DISABLED === 'true';\n}\n\n/** Resolve the appropriate policy for a subject based on kind, source, and target tool. */\nexport function resolvePolicy(\n  subject: Pick<SandboxSubject, 'kind' | 'source'>,\n  toolName?: string\n): SandboxPolicy {\n  // WS-1 consumer branch: checked BEFORE the sensitive-tool check, but only fires\n  // for the 2 explicitly-listed generation tools AND only when the caller has\n  // ALREADY marked the subject 'consumer'. That source is only set by the\n  // rate-limited/moderation-gated public generation endpoint. The optional\n  // HOLOSCRIPT_CONSUMER_TIER_DISABLED=true switch is an emergency brake, not a\n  // normal product-access prerequisite.\n  if (\n    subject.source === 'consumer' &&\n    toolName &&\n    isConsumerSafeTool(toolName) &&\n    !isConsumerGenerationTierDisabled()\n  ) {\n    return DEFAULT_CONSUMER_GENERATION_POLICY;\n  }\n  // Sensitive tools always get sensitive policy regardless of source\n  if (toolName && isSensitiveTool(toolName)) {\n    return DEFAULT_SENSITIVE_POLICY;\n  }\n  // Forked or generated sources get sensitive policy (heuristics may upgrade source)\n  if (subject.source === 'fork' || subject.source === 'generated') {\n    return DEFAULT_SENSITIVE_POLICY;\n  }\n  // Everything else (canonical, unknown without sensitive tool) gets benign\n  return DEFAULT_BENIGN_POLICY;\n}\n\n// ── Payload Hashing ──────────────────────────────────────────────────────────\n\nexport async function hashPayload(payload: string | Record<string, unknown>): Promise<string> {\n  const { createHash } = await import('crypto');\n  const data = typeof payload === 'string' ? payload : JSON.stringify(payload);\n  return createHash('sha256').update(data).digest('hex');\n}\n\n// ── Receipt Store (in-memory with TTL) ───────────────────────────────────────\n\nclass ReceiptStore {\n  private store = new Map<string, { receipt: DenialReceipt; expiresAt: number }>();\n\n  add(receipt: DenialReceipt, ttlMs: number): void {\n    this.store.set(receipt.receiptId, {\n      receipt,\n      expiresAt: Date.now() + ttlMs,\n    });\n  }\n\n  get(receiptId: string): DenialReceipt | undefined {\n    const entry = this.store.get(receiptId);\n    if (!entry) return undefined;\n    if (Date.now() > entry.expiresAt) {\n      this.store.delete(receiptId);\n      return undefined;\n    }\n    return entry.receipt;\n  }\n\n  purgeExpired(): number {\n    const now = Date.now();\n    let count = 0;\n    for (const [id, entry] of this.store) {\n      if (now > entry.expiresAt) {\n        this.store.delete(id);\n        count++;\n      }\n    }\n    return count;\n  }\n\n  size(): number {\n    return this.store.size;\n  }\n}\n\nexport const globalReceiptStore = new ReceiptStore();\n\n// Keep cleanup active for a running server without pinning library consumers.\nconst receiptCleanupTimer = setInterval(\n  () => globalReceiptStore.purgeExpired(),\n  5 * 60 * 1000\n);\nreceiptCleanupTimer.unref();\n","/**\n * Fork Sandbox Gate — Enforces sandbox policy on HoloScript-looking code,\n * MCP tools, runtime adapters, and generated plugins before they can touch\n * sensitive state (HoloLand worlds, robot/AI substrate, payments, player-impacting state).\n *\n * Canary task: task_1778618757735_zpt5\n * Authority: W.GOLD.035, W.GOLD.039, W.GOLD.193\n */\n\nimport type {\n  SandboxPolicy,\n  SandboxSubject,\n  SandboxSubjectSource,\n  CapabilityManifest,\n  DenialReceipt,\n  SandboxGateResult,\n} from './sandbox-policy';\nimport {\n  resolvePolicy,\n  hashPayload,\n  globalReceiptStore,\n  isSensitiveTool,\n  isConsumerSafeTool,\n  DEFAULT_SENSITIVE_POLICY,\n  DEFAULT_BENIGN_POLICY,\n  DEFAULT_CONSUMER_GENERATION_POLICY,\n  SYSTEM_DEFAULT_BLOCKED_ACTIONS,\n} from './sandbox-policy';\n\n// ── Fork Detection Heuristics ────────────────────────────────────────────────\n\n/**\n * Detect whether a HoloScript code payload appears to come from a forked or\n * untrusted compiler. These heuristics are defense-in-depth; the primary\n * trust signal is the explicit `source` field on the SandboxSubject.\n *\n * Detection rules (return true if suspicious):\n * 1. Contains keywords that canonical HoloScript blocks (HS010) — a fork that\n *    removed the lexical firewall would let these through.\n * 2. Claims a compiler version that does not match known canonical versions.\n * 3. Contains `@security_sandbox` trait syntax but no observable sandbox calls.\n * 4. References npm scopes other than `@holoscript/*` for core imports.\n * 5. Contains `eval`, `Function`, `process`, `require`, `fs`, `child_process`.\n */\nconst HS010_KEYWORDS = [\n  'process',\n  'fs',\n  'require',\n  'eval',\n  'exec',\n  'spawn',\n  'child_process',\n  'constructor',\n  'prototype',\n  'globalThis',\n];\n\nconst CANONICAL_COMPILER_VERSIONS = ['7.0.0', '6.0.2', '6.0.1', '6.0.0'];\nconst TRUST_TIER_ORDER = ['founder', 'diamond', 'platinum', 'gold', 'verified', 'unverified'] as const;\nconst READ_ONLY_VALIDATION_CAPABILITIES = [\n  'holoscript:validate',\n  'filesystem:read:local-source',\n] as const;\n\nexport interface ForkDetectionResult {\n  isSuspicious: boolean;\n  signals: string[];\n}\n\nexport function detectForkedHoloScript(code: string): ForkDetectionResult {\n  const signals: string[] = [];\n\n  // HS010 keyword presence\n  for (const kw of HS010_KEYWORDS) {\n    const regex = new RegExp(`\\\\b${kw}\\\\b`);\n    if (regex.test(code)) {\n      signals.push(`HS010-blocked-keyword:${kw}`);\n    }\n  }\n\n  // Version mismatch\n  const versionMatch = code.match(/@compiler\\s+version\\s+[\"']?([\\d.]+)[\"']?/i);\n  if (versionMatch) {\n    const claimedVersion = versionMatch[1];\n    if (!CANONICAL_COMPILER_VERSIONS.includes(claimedVersion)) {\n      signals.push(`unknown-compiler-version:${claimedVersion}`);\n    }\n  }\n\n  // No-op trait pattern: @security_sandbox present but no sandbox import\n  if (/(?:^|\\s)@security_sandbox\\b/.test(code) && !/\\bimport\\s+.*security-sandbox/.test(code)) {\n    signals.push('no-op-security-trait');\n  }\n\n  // Non-canonical npm scope import\n  const nonCanonicalImport = /\\bfrom\\s+['\"](?!@holoscript\\/)[@\\w\\/-]+['\"]/.test(code);\n  if (nonCanonicalImport) {\n    signals.push('non-canonical-import');\n  }\n\n  return {\n    isSuspicious: signals.length > 0,\n    signals,\n  };\n}\n\n/**\n * Detect whether a plugin manifest or adapter config looks forked/untrusted.\n */\nexport function detectForkedPlugin(manifest: Record<string, unknown>): ForkDetectionResult {\n  const signals: string[] = [];\n  const scope = typeof manifest.scopeName === 'string' ? manifest.scopeName : '';\n  if (scope && !/^@holoscript(\\/|$)/.test(scope)) {\n    signals.push(`non-canonical-scope:${scope}`);\n  }\n  const version = typeof manifest.version === 'string' ? manifest.version : '';\n  if (version && !/^\\d+\\.\\d+\\.\\d+/.test(version)) {\n    signals.push(`invalid-semver:${version}`);\n  }\n  const tier = typeof manifest.trustTier === 'string' ? manifest.trustTier : '';\n  if (tier && tier === 'unverified') {\n    signals.push('unverified-tier');\n  }\n  return {\n    isSuspicious: signals.length > 0,\n    signals,\n  };\n}\n\n// ── Capability Manifest Validation ───────────────────────────────────────────\n\nfunction validateCapabilityManifest(\n  subject: SandboxSubject,\n  policy: SandboxPolicy\n): { passed: boolean; detail?: string } {\n  const manifest: CapabilityManifest | undefined = subject.manifest;\n\n  if (!manifest) {\n    if (policy.capabilityManifest.required) {\n      return {\n        passed: false,\n        detail: `Capability manifest required but missing for ${subject.kind}:${subject.subjectId}`,\n      };\n    }\n    return { passed: true, detail: 'Manifest not required' };\n  }\n\n  if (manifest.declaredCapabilities.length === 0) {\n    return {\n      passed: false,\n      detail: 'Capability manifest has zero declared capabilities',\n    };\n  }\n\n  if (policy.capabilityManifest.attestationRequired) {\n    if (!manifest.attestation) {\n      return {\n        passed: false,\n        detail: 'Attestation required but missing',\n      };\n    }\n    const subjectIdx = TRUST_TIER_ORDER.indexOf(manifest.attestation.trustTier);\n    const requiredIdx = TRUST_TIER_ORDER.indexOf(policy.capabilityManifest.minAttestationTier);\n    if (subjectIdx < 0 || subjectIdx > requiredIdx) {\n      return {\n        passed: false,\n        detail: `Attestation trust tier '${manifest.attestation.trustTier}' is below required '${policy.capabilityManifest.minAttestationTier}'`,\n      };\n    }\n  }\n\n  return { passed: true, detail: 'Manifest valid' };\n}\n\nfunction isVerifiedReadOnlyValidationManifest(manifest: CapabilityManifest | undefined): boolean {\n  if (!manifest || manifest.protocol !== 'holoscript.capability.v1') return false;\n  const capabilities = new Set(manifest.declaredCapabilities);\n  if (!READ_ONLY_VALIDATION_CAPABILITIES.every((capability) => capabilities.has(capability))) {\n    return false;\n  }\n  if (!manifest.attestation) return false;\n  const subjectIdx = TRUST_TIER_ORDER.indexOf(manifest.attestation.trustTier);\n  const requiredIdx = TRUST_TIER_ORDER.indexOf('verified');\n  return subjectIdx >= 0 && subjectIdx <= requiredIdx;\n}\n\n// ── Permission Validation ────────────────────────────────────────────────────\n\nfunction validatePermissions(\n  _subject: SandboxSubject,\n  policy: SandboxPolicy,\n  grantedScopes: string[]\n): { passed: boolean; detail?: string } {\n  if (grantedScopes.includes('admin:*')) {\n    return { passed: true, detail: 'admin:* bypasses scope check' };\n  }\n\n  if (policy.permissions.allowAnonymous) {\n    return { passed: true, detail: 'Anonymous access permitted' };\n  }\n\n  const required = policy.permissions.requiredScopes;\n  const hasScope = required.some((s) => grantedScopes.includes(s));\n  if (!hasScope) {\n    return {\n      passed: false,\n      detail: `Insufficient scope. Required one of [${required.join(', ')}]. Granted [${grantedScopes.join(', ')}]`,\n    };\n  }\n\n  return { passed: true, detail: 'Scopes adequate' };\n}\n\n// ── Network/File Limits ──────────────────────────────────────────────────────\n\nfunction validateNetworkLimits(\n  subject: SandboxSubject,\n  policy: SandboxPolicy\n): { passed: boolean; detail?: string } {\n  if (!policy.network.allowNetwork) {\n    return { passed: true, detail: 'Network disabled by policy' };\n  }\n\n  // For code subjects, scan for network calls\n  if (subject.kind === 'holoscript_code' && typeof subject.payload === 'string') {\n    const code = subject.payload;\n    const hasFetch = /\\bfetch\\s*\\(/.test(code);\n    const hasAxios = /\\baxios\\b/.test(code);\n    const hasHttp = /\\bhttp\\b/.test(code);\n    if ((hasFetch || hasAxios || hasHttp) && policy.network.allowedHosts.length === 0) {\n      return {\n        passed: false,\n        detail: 'Code contains network calls but policy allows no hosts',\n      };\n    }\n  }\n\n  return { passed: true, detail: 'Network limits acceptable' };\n}\n\nfunction validateFileLimits(\n  subject: SandboxSubject,\n  policy: SandboxPolicy\n): { passed: boolean; detail?: string } {\n  if (!policy.file.allowFsWrites) {\n    // Scan for file-system write patterns in code\n    if (subject.kind === 'holoscript_code' && typeof subject.payload === 'string') {\n      const code = subject.payload;\n      const hasFsWrite = /\\bfs\\s*\\.\\s*(writeFile|appendFile|mkdir|unlink|rmdir)\\b/.test(code);\n      const hasPathWrite = /\\bwriteFileSync\\b/.test(code);\n      if (hasFsWrite || hasPathWrite) {\n        return {\n          passed: false,\n          detail: 'Code contains filesystem writes but policy blocks fs writes',\n        };\n      }\n    }\n  }\n\n  // Path traversal check for file-path arguments\n  if (typeof subject.payload === 'object' && subject.payload !== null) {\n    const args = subject.payload as Record<string, unknown>;\n    for (const val of Object.values(args)) {\n      if (typeof val === 'string') {\n        const normalized = val.replace(/\\\\/g, '/').replace(/^\\.\\//, '');\n        if (normalized.startsWith('..') || normalized.includes('/../')) {\n          return {\n            passed: false,\n            detail: `Path traversal blocked: \"${val}\"`,\n          };\n        }\n      }\n    }\n  }\n\n  return { passed: true, detail: 'File limits acceptable' };\n}\n\n// ── Resource Ceiling Validation ──────────────────────────────────────────────\n\nfunction validateResourceCeilings(\n  _subject: SandboxSubject,\n  policy: SandboxPolicy\n): { passed: boolean; detail?: string } {\n  if (policy.resources.maxExecutionTimeMs <= 0) {\n    return { passed: false, detail: 'maxExecutionTimeMs must be positive' };\n  }\n  if (policy.resources.maxMemoryBytes <= 0) {\n    return { passed: false, detail: 'maxMemoryBytes must be positive' };\n  }\n  return { passed: true, detail: 'Resource ceilings valid' };\n}\n\n// ── Denial Receipt Generation ──────────────────────────────────────────────────\n\nasync function createDenialReceipt(\n  subject: SandboxSubject,\n  policy: SandboxPolicy,\n  failedCheck: string,\n  reason: string,\n  checks: Array<{ name: string; passed: boolean; detail?: string }>,\n  remediation: string\n): Promise<DenialReceipt> {\n  const payloadHash = await hashPayload(subject.payload);\n  const receiptId = `denial_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;\n  const receipt: DenialReceipt = {\n    receiptId,\n    timestamp: new Date().toISOString(),\n    policyId: policy.policyId,\n    subject: {\n      kind: subject.kind,\n      subjectId: subject.subjectId,\n      source: subject.source,\n      payloadHash,\n      ...(policy.receipt.includePayload ? { payload: subject.payload } : {}),\n    },\n    failedCheck,\n    reason,\n    checks,\n    remediation,\n  };\n\n  if (policy.receipt.emitReceipt) {\n    globalReceiptStore.add(receipt, policy.receipt.receiptTTLMs);\n  }\n\n  return receipt;\n}\n\n// ── Main Gate ────────────────────────────────────────────────────────────────\n\nexport interface ForkSandboxGateOptions {\n  /** OAuth 2.1 scopes granted to the current caller */\n  grantedScopes?: string[];\n  /** Override the default policy resolution */\n  policy?: SandboxPolicy;\n  /** Tool name being invoked (for policy resolution) */\n  toolName?: string;\n  /** Enable fork-detection heuristics on code payloads */\n  enableHeuristics?: boolean;\n}\n\n/**\n * Run the fork sandbox gate against a subject.\n *\n * Protocol:\n * 1. Resolve policy (based on subject source + optional tool name).\n * 2. If heuristics enabled and subject is code/plugin, run fork detection.\n *    Suspicious signals upgrade source to 'fork' if it was 'unknown'.\n * 3. Run required checks in order: manifest → permissions → network → file → resources.\n * 4. On first failure, emit denial receipt (if configured) and return blocked.\n * 5. On success, return allowed with per-check detail.\n */\nexport async function runForkSandboxGate(\n  subject: SandboxSubject,\n  options: ForkSandboxGateOptions = {}\n): Promise<SandboxGateResult> {\n  // Step 1: Heuristic fork detection (defense-in-depth)\n  let effectiveSource: SandboxSubjectSource = subject.source;\n  let heuristicSignals: string[] = [];\n  if (options.enableHeuristics !== false) {\n    if (subject.kind === 'holoscript_code' && typeof subject.payload === 'string') {\n      const detection = detectForkedHoloScript(subject.payload);\n      if (detection.isSuspicious) {\n        heuristicSignals = detection.signals;\n        const readOnlyValidationManifest =\n          options.toolName === 'validate_holoscript' &&\n          isVerifiedReadOnlyValidationManifest(subject.manifest);\n        if (!readOnlyValidationManifest && (effectiveSource === 'unknown' || effectiveSource === 'generated')) {\n          effectiveSource = 'fork';\n        }\n      }\n    } else if (subject.kind === 'generated_plugin' && typeof subject.payload === 'object') {\n      const detection = detectForkedPlugin(subject.payload as Record<string, unknown>);\n      if (detection.isSuspicious) {\n        heuristicSignals = detection.signals;\n        if (effectiveSource === 'unknown' || effectiveSource === 'generated') {\n          effectiveSource = 'fork';\n        }\n      }\n    }\n  }\n\n  const policy =\n    options.policy ?? resolvePolicy({ ...subject, source: effectiveSource }, options.toolName);\n\n  // Admin bypass: full authority scope short-circuits all checks\n  if (options.grantedScopes?.includes('admin:*')) {\n    return {\n      allowed: true,\n      appliedPolicy: policy,\n      checks: [{ name: 'admin_bypass', passed: true, detail: 'admin:* bypasses all gates' }],\n    };\n  }\n\n  const checks: Array<{ name: string; passed: boolean; detail?: string }> = [];\n\n  // Check 1: Capability manifest\n  const manifestCheck = validateCapabilityManifest({ ...subject, source: effectiveSource }, policy);\n  checks.push({ name: 'capability_manifest', ...manifestCheck });\n  if (!manifestCheck.passed) {\n    const receipt = await createDenialReceipt(\n      subject,\n      policy,\n      'capability_manifest',\n      manifestCheck.detail!,\n      checks,\n      'Provide a valid capability manifest with attestation from a verified-tier signer.'\n    );\n    return { allowed: false, receipt, appliedPolicy: policy, checks };\n  }\n\n  // Check 2: Permissions\n  const scopes = options.grantedScopes ?? [];\n  const permCheck = validatePermissions(subject, policy, scopes);\n  checks.push({ name: 'permissions', ...permCheck });\n  if (!permCheck.passed) {\n    const receipt = await createDenialReceipt(\n      subject,\n      policy,\n      'permissions',\n      permCheck.detail!,\n      checks,\n      'Request the required OAuth scopes or elevate the subject attestation tier.'\n    );\n    return { allowed: false, receipt, appliedPolicy: policy, checks };\n  }\n\n  // Check 3: Network limits\n  const netCheck = validateNetworkLimits(subject, policy);\n  checks.push({ name: 'network_limits', ...netCheck });\n  if (!netCheck.passed) {\n    const receipt = await createDenialReceipt(\n      subject,\n      policy,\n      'network_limits',\n      netCheck.detail!,\n      checks,\n      'Remove network calls from the subject or request a policy with allowedHosts.'\n    );\n    return { allowed: false, receipt, appliedPolicy: policy, checks };\n  }\n\n  // Check 4: File limits\n  const fileCheck = validateFileLimits(subject, policy);\n  checks.push({ name: 'file_limits', ...fileCheck });\n  if (!fileCheck.passed) {\n    const receipt = await createDenialReceipt(\n      subject,\n      policy,\n      'file_limits',\n      fileCheck.detail!,\n      checks,\n      'Remove filesystem write patterns or request a policy with allowFsWrites=true and allowedPaths.'\n    );\n    return { allowed: false, receipt, appliedPolicy: policy, checks };\n  }\n\n  // Check 5: Resource ceilings\n  const resourceCheck = validateResourceCeilings(subject, policy);\n  checks.push({ name: 'resource_ceilings', ...resourceCheck });\n  if (!resourceCheck.passed) {\n    const receipt = await createDenialReceipt(\n      subject,\n      policy,\n      'resource_ceilings',\n      resourceCheck.detail!,\n      checks,\n      'Adjust resource ceilings to positive values in the policy.'\n    );\n    return { allowed: false, receipt, appliedPolicy: policy, checks };\n  }\n\n  // Heuristic signals are informational only — they don't block if all formal checks pass\n  if (heuristicSignals.length > 0) {\n    checks.push({\n      name: 'fork_heuristics',\n      passed: true,\n      detail: `Suspicious signals detected but not blocking: ${heuristicSignals.join(', ')}`,\n    });\n  }\n\n  return { allowed: true, appliedPolicy: policy, checks };\n}\n\n// ── Convenience: Gate a HoloScript code string ───────────────────────────────\n\nexport async function gateHoloScriptCode(\n  code: string,\n  opts: {\n    source?: SandboxSubjectSource;\n    subjectId?: string;\n    grantedScopes?: string[];\n    toolName?: string;\n    manifest?: CapabilityManifest;\n  } = {}\n): Promise<SandboxGateResult> {\n  const subject: SandboxSubject = {\n    kind: 'holoscript_code',\n    source: opts.source ?? 'unknown',\n    subjectId: opts.subjectId ?? `code_${Date.now()}`,\n    payload: code,\n    manifest: opts.manifest,\n  };\n  return runForkSandboxGate(subject, {\n    grantedScopes: opts.grantedScopes,\n    toolName: opts.toolName,\n  });\n}\n\n// ── Convenience: Gate an MCP tool invocation ─────────────────────────────────\n\nexport async function gateMcpTool(\n  toolName: string,\n  args: Record<string, unknown>,\n  opts: {\n    source?: SandboxSubjectSource;\n    grantedScopes?: string[];\n    manifest?: CapabilityManifest;\n  } = {}\n): Promise<SandboxGateResult> {\n  const subject: SandboxSubject = {\n    kind: 'mcp_tool',\n    source: opts.source ?? 'unknown',\n    subjectId: `tool:${toolName}`,\n    payload: args,\n    manifest: opts.manifest,\n  };\n  return runForkSandboxGate(subject, {\n    grantedScopes: opts.grantedScopes,\n    toolName,\n  });\n}\n\n// ── Convenience: Gate a plugin registration ──────────────────────────────────\n\nexport async function gatePluginRegistration(\n  pluginManifest: Record<string, unknown>,\n  opts: {\n    source?: SandboxSubjectSource;\n    grantedScopes?: string[];\n  } = {}\n): Promise<SandboxGateResult> {\n  const subject: SandboxSubject = {\n    kind: 'generated_plugin',\n    source: opts.source ?? 'unknown',\n    subjectId: `plugin:${pluginManifest.name ?? 'unnamed'}`,\n    payload: pluginManifest,\n    manifest: pluginManifest.manifest as CapabilityManifest | undefined,\n  };\n  return runForkSandboxGate(subject, {\n    grantedScopes: opts.grantedScopes,\n  });\n}\n\n// ── Re-exports for consumers ───────────────────────────────────────────────────\n\nexport {\n  isSensitiveTool,\n  isConsumerSafeTool,\n  resolvePolicy,\n  DEFAULT_SENSITIVE_POLICY,\n  DEFAULT_BENIGN_POLICY,\n  DEFAULT_CONSUMER_GENERATION_POLICY,\n  SYSTEM_DEFAULT_BLOCKED_ACTIONS,\n};\n","/**\n * Tool Scope Mapping — Gate 2 Authorization\n *\n * Maps every MCP tool to the OAuth 2.1 scopes required to invoke it.\n * Gate 2 (LLM->MCP tool authorization) checks that the authenticated\n * token's scopes include the required scope for each tool call.\n *\n * Scope hierarchy:\n *   admin:*        → grants everything\n *   tools:read     → parse, validate, list, explain, analyze, documentation\n *   tools:write    → generate, compile, render, share, edit, convert\n *   tools:codebase → absorb, query, impact, detect changes, graph RAG\n *   tools:browser  → browser_launch, browser_execute, browser_screenshot\n *   tools:admin    → self-improve, diagnostics, training data\n *   a2a:tasks      → A2A task lifecycle\n *   scenes:read    → read scene data\n *   scenes:write   → store scenes\n */\n\nimport type { OAuthScope } from './oauth21';\n\n// ── Tool-to-Scope Mapping ────────────────────────────────────────────────────\n\nconst TOOL_SCOPE_MAP: Record<string, OAuthScope[]> = {\n  // === Read-only language tools ===\n  parse_hs: ['tools:read'],\n  parse_holo: ['tools:read'],\n  parse_pipeline: ['tools:read'],\n  validate_holoscript: ['tools:read'],\n  list_traits: ['tools:read'],\n  explain_trait: ['tools:read'],\n  get_syntax_reference: ['tools:read'],\n  get_examples: ['tools:read'],\n  explain_code: ['tools:read'],\n  analyze_code: ['tools:read'],\n\n  // === Write / generative tools ===\n  suggest_traits: ['tools:write'],\n  suggest_2d_traits: ['tools:write'],\n  generate_object: ['tools:write'],\n  generate_scene: ['tools:write'],\n  generate_semantic_ui: ['tools:write'],\n  holo_hologram_from_media: ['tools:write'],\n  holo_hologram_compile_quilt: ['tools:write'],\n  holo_hologram_compile_mvhevc: ['tools:write'],\n  holo_hologram_render: ['tools:write'],\n  holo_hologram_publish_feed: ['tools:write'],\n  holo_hologram_send: ['tools:write'],\n  holo_holotwin_connect: ['tools:write'],\n  holo_holotwin_map_sensor: ['tools:write'],\n  holo_holotwin_compile_quilt: ['tools:write'],\n  holo_holotwin_stream: ['tools:write'],\n  holo_holotwin_status: ['tools:read'],\n  holo_holotwin_disconnect: ['tools:write'],\n  holo_holotwin_example: ['tools:write'],\n  render_preview: ['tools:write'],\n  create_share_link: ['tools:write'],\n  convert_format: ['tools:write'],\n  edit_holo: ['tools:write'],\n  generate_3d_object: ['tools:write'],\n  compose_workflow: ['tools:write'],\n  execute_workflow: ['tools:write'],\n  workflow_memory_write: ['tools:write'],\n  workflow_memory_read: ['tools:read'],\n  workflow_memory_subscribe: ['tools:read'],\n\n  // === Batch meta-tools (each inner call is re-authorized independently) ===\n  batch_tool_call: ['tools:read'],\n  holoscript_batch_execute: ['tools:read'],\n\n  // === Sovereign from-scratch training ===\n  holo_from_scratch_status: ['tools:read'],\n  holo_from_scratch_launch: ['tools:admin'],\n\n  // === HoloLand MCP tools (world CRUD + MMO + Twin Earth) ===\n  generate_world_from_prompt: ['tools:write'],\n  generate_world: ['tools:write'],\n  create_world: ['tools:write'],\n  get_world: ['tools:read'],\n  update_world: ['tools:write'],\n  delete_world: ['tools:write'],\n  list_worlds: ['tools:read'],\n  create_shard: ['tools:write'],\n  get_shard: ['tools:read'],\n  update_shard: ['tools:write'],\n  delete_shard: ['tools:write'],\n  list_shards: ['tools:read'],\n  create_zone: ['tools:write'],\n  get_zone: ['tools:read'],\n  update_zone: ['tools:write'],\n  delete_zone: ['tools:write'],\n  list_zones: ['tools:read'],\n  create_place: ['tools:write'],\n  get_place: ['tools:read'],\n  update_place: ['tools:write'],\n  delete_place: ['tools:write'],\n  list_places: ['tools:read'],\n  create_location_quest: ['tools:write'],\n  get_location_quest: ['tools:read'],\n  update_location_quest: ['tools:write'],\n  delete_location_quest: ['tools:write'],\n  list_location_quests: ['tools:read'],\n\n  // === HoloLand MMO / Twin Earth product actions ===\n  hololand_shard_status: ['tools:read'],\n  hololand_publish_zone: ['tools:write'],\n  hololand_create_geo_anchor: ['tools:write'],\n  hololand_steward_tick: ['tools:admin'],\n  hololand_capture_runtime_receipt: ['tools:admin'],\n\n  // === Graph understanding (read-only analysis) ===\n  holo_parse_to_graph: ['tools:read'],\n  holo_visualize_flow: ['tools:read'],\n  holo_get_node_connections: ['tools:read'],\n  holo_design_graph: ['tools:write'],\n  holo_diff_graphs: ['tools:read'],\n  holo_suggest_connections: ['tools:read'],\n\n  // === IDE tools (read-heavy, some write) ===\n  hs_scan_project: ['tools:read'],\n  hs_diagnostics: ['tools:read'],\n  hs_autocomplete: ['tools:read'],\n  hs_refactor: ['tools:write'],\n  hs_docs: ['tools:read'],\n  hs_code_action: ['tools:write'],\n  hs_hover: ['tools:read'],\n  hs_go_to_definition: ['tools:read'],\n  hs_find_references: ['tools:read'],\n\n  // === Brittney-Lite AI ===\n  hs_ai_explain_error: ['tools:read'],\n  hs_ai_fix_code: ['tools:write'],\n  hs_ai_review: ['tools:read'],\n  hs_ai_scaffold: ['tools:write'],\n\n  // === Codebase intelligence ===\n  holo_graph_status: ['tools:codebase'],\n  holo_absorb_repo: ['tools:codebase'],\n  holo_query_codebase: ['tools:codebase'],\n  holo_impact_analysis: ['tools:codebase'],\n  holo_detect_changes: ['tools:codebase'],\n\n  // === Graph RAG ===\n  holo_semantic_search: ['tools:codebase'],\n  holo_ask_codebase: ['tools:codebase'],\n\n  // === Self-improve (admin) ===\n  holo_self_diagnose: ['tools:admin'],\n  holo_validate_quality: ['tools:admin'],\n\n  // === Compiler tools ===\n  compile_holoscript: ['tools:write'],\n  compile_pipeline: ['tools:write'],\n  compile_to_unity: ['tools:write'],\n  compile_to_unreal: ['tools:write'],\n  compile_to_urdf: ['tools:write'],\n  compile_to_webgpu: ['tools:write'],\n  compile_to_character_webgpu: ['tools:write'],\n  compile_to_omnigent_agent_yaml: ['tools:write'],\n  compile_to_r3f: ['tools:write'],\n  compile_to_godot: ['tools:write'],\n  compile_to_openxr: ['tools:write'],\n  get_compilation_status: ['tools:read'],\n\n  // === Browser control ===\n  browser_launch: ['tools:browser'],\n  browser_execute: ['tools:browser'],\n  browser_screenshot: ['tools:browser'],\n\n  // === GLTF Import/Export ===\n  import_gltf: ['tools:write'],\n  compile_to_gltf: ['tools:write'],\n\n  // === Networking ===\n  push_state_delta: ['tools:write'],\n  fetch_authoritative_state: ['tools:read'],\n\n  // === Temporal Snapshots ===\n  create_temporal_snapshot: ['tools:write'],\n  load_temporal_snapshot: ['tools:read'],\n  rewind_world_state: ['tools:write'],\n\n  // === Monitoring ===\n  get_telemetry_metrics: ['tools:read'],\n\n  // === HoloTest / Eval ===\n  execute_holotest: ['tools:admin'],\n  execute_eval: ['tools:admin'],\n\n  // === Wisdom/Gotcha ===\n  holo_query_wisdom: ['tools:read'],\n  holo_list_gotchas: ['tools:read'],\n  holo_check_gotchas: ['tools:read'],\n  holo_add_wisdom: ['tools:admin'],\n  holo_add_gotcha: ['tools:admin'],\n\n  // === Receipt Capability Query ===\n  holo_query_receipts: ['tools:read'],\n  holo_list_receipt_capabilities: ['tools:read'],\n\n  // === Training data generation (admin) ===\n  generate_hololand_training: ['tools:admin'],\n\n  // === Refactor/Codegen ===\n  holo_refactor_plan: ['tools:write'],\n  holo_scaffold: ['tools:write'],\n\n  // === Absorb Service ===\n  absorb_create_project: ['tools:codebase'],\n  absorb_get_credits: ['tools:codebase'],\n  absorb_run_absorb: ['tools:codebase'],\n  absorb_run_improve: ['tools:codebase'],\n  absorb_query: ['tools:codebase'],\n  absorb_render: ['tools:write'],\n  absorb_diff: ['tools:codebase'],\n  absorb_get_pipeline: ['tools:codebase'],\n  absorb_run_pipeline: ['tools:codebase'],\n  absorb_get_project: ['tools:codebase'],\n\n  // === HoloMesh (spatial mesh, A2A discovery) ===\n  holomesh_status: ['tools:read'],\n  holomesh_discover: ['tools:read'],\n  holomesh_publish_tool: ['tools:write'],\n  holomesh_invoke_tool: ['tools:write'],\n  holomesh_gossip: ['tools:write', 'tools:admin'],\n  holomesh_contribute: ['tools:write'],\n  holomesh_query: ['tools:read'],\n  holomesh_subscribe: ['tools:read'],\n  holomesh_collect: ['tools:write'],\n\n  // === HoloMesh Board / Slots / Mode ===\n  holomesh_board_list: ['tools:read'],\n  holomesh_board_done_log: ['tools:read'],\n  holomesh_board_add: ['tools:write'],\n  holomesh_board_claim: ['tools:write'],\n  holomesh_board_complete: ['tools:write'],\n  holomesh_slot_assign: ['tools:write', 'tools:admin'],\n  holomesh_mode_set: ['tools:write', 'tools:admin'],\n\n  // === Railway Deployment (registered dynamically via connector) ===\n  railway_project_create: ['tools:admin'],\n  railway_service_create: ['tools:admin'],\n  railway_deploy: ['tools:admin'],\n  railway_variable_set: ['tools:admin'],\n  railway_domain_add: ['tools:admin'],\n  railway_deployment_status: ['tools:read'],\n\n  // === Secrets Broker (security-gated) ===\n  holo_secrets_grant: ['tools:admin'],\n  holo_secrets_resolve: ['tools:admin'],\n  holo_secrets_revoke: ['tools:admin'],\n\n  // === Conformance Artifact Admission Gate (HoloGate §admission) ===\n  // conformance_list_rules: read-only catalog query\n  // conformance_check_artifact: validates an artifact against the admission gate (no side-effects)\n  // conformance_admit_artifact: explicit admission decision — same validation but framed as an\n  //   authoritative gate action (ecosystem write-once receipt implied); mapped to tools:write\n  //   so it gates behind the same scope as other ecosystem mutation tools.\n  conformance_list_rules: ['tools:read'],\n  conformance_check_artifact: ['tools:read'],\n  conformance_admit_artifact: ['tools:write'],\n\n  // === HIGH-RISK tools that were REGISTERED but UNMAPPED (task_1783794507029) ===\n  // These fell through to the fail-open default (['tools:read']) — i.e. money movement,\n  // token minting, physical robot actuation, safety-envelope CRUD, autonomous control,\n  // sovereign-state restore, fleet compute spend, plugin install, and memory graduation\n  // were all invokable with only tools:read. Pin each to its true least-privilege scope.\n  // Economy / real spend:\n  settle_creator_payout: ['tools:admin'],\n  execute_economic_contract: ['tools:admin'],\n  sim_run_paid: ['tools:admin'],\n  get_creator_earnings: ['tools:read'],\n  // Agent identity / token minting:\n  issue_agent_token: ['tools:admin'],\n  verify_agent_token: ['tools:read'],\n  delegate_task: ['tools:admin'],\n  // Twin Earth — physical robot actuation, identity, permissions, and SAFETY envelopes:\n  twin_earth_robot_actuate: ['tools:admin'],\n  twin_earth_register_identity: ['tools:admin'],\n  twin_earth_revoke_identity: ['tools:admin'],\n  twin_earth_grant_permission: ['tools:admin'],\n  twin_earth_revoke_permission: ['tools:admin'],\n  twin_earth_create_safety_envelope: ['tools:admin'],\n  twin_earth_update_safety_envelope: ['tools:admin'],\n  twin_earth_delete_safety_envelope: ['tools:admin'],\n  // Autonomous control / federation / sovereign state:\n  holomesh_autonomous_control: ['tools:admin'],\n  holomesh_federate_twin_earth: ['tools:admin'],\n  holomesh_sovereign_lifepod_restore: ['tools:admin'],\n  holomesh_sovereign_lifepod_snapshot: ['tools:admin'],\n  // Fleet compute spend / training / hardware:\n  render_world_on_fleet: ['tools:admin'],\n  train_rom: ['tools:admin'],\n  sync_hardware_loop: ['tools:admin'],\n  // Plugin install (arbitrary code) / memory canon:\n  install_plugin: ['tools:admin'],\n  install_domain_plugin: ['tools:admin'],\n  manage_plugin: ['tools:admin'],\n  holo_memory_graduate: ['tools:admin'],\n  holo_memory_store: ['tools:write'],\n  compile_to_daimon_seed: ['tools:write'],\n  // HoloLand identity provisioning / revocation:\n  hololand_provision_player: ['tools:admin'],\n  hololand_provision_agent: ['tools:admin'],\n  hololand_provision_creator: ['tools:admin'],\n  hololand_revoke_agent: ['tools:admin'],\n  // === v2g4: least-privilege scopes for the 242 previously-unmapped registered tools.\n  // Classified + ADVERSARIALLY VERIFIED by a 73-agent workflow that read each handler\n  // (dangerous-first rubric). 8 new admin tools surfaced beyond zvor's 28; 2 were flipped by\n  // the verify pass (holomesh_team_compound write->read = pure read; hololand_create_player_invite\n  // admin->write = invite link, not provisioning). Every entry here is explicit so it is greppable\n  // and regression-pinned by the completeness test (no tool falls to the classifier fail-closed).\n  // admin (money/token/actuation/identity/spend/install/canon — adversarially verified):\n  holo_ci_dispatch: ['tools:admin'],\n  holo_protocol_collect: ['tools:admin'],\n  holo_protocol_publish: ['tools:admin'],\n  hololand_revoke_creator: ['tools:admin'],\n  hololand_revoke_player: ['tools:admin'],\n  holotune_launch: ['tools:admin'],\n  holotune_promote: ['tools:admin'],\n  twin_earth_update_identity: ['tools:admin'],\n  // codebase intelligence:\n  absorb_provenance_answer: ['tools:codebase'],\n  absorb_run_query_ai: ['tools:codebase'],\n  holo_detect_drift: ['tools:codebase'],\n  holo_generate_refactor_plan: ['tools:codebase'],\n  holo_get_absorb_status: ['tools:codebase'],\n  holo_resolve_symbol: ['tools:codebase'],\n  // write / generative / state-mutating:\n  absorb_delete_project: ['tools:write'],\n  absorb_fmu: ['tools:write'],\n  absorb_run_render: ['tools:write'],\n  absorb_typescript: ['tools:write'],\n  compile_to_3dgs: ['tools:write'],\n  compile_to_3dtiles: ['tools:write'],\n  compile_to_a2a_agent_card: ['tools:write'],\n  compile_to_agent_inference: ['tools:write'],\n  compile_to_ai_glasses: ['tools:write'],\n  compile_to_android: ['tools:write'],\n  compile_to_android_xr: ['tools:write'],\n  compile_to_bias_audit_report: ['tools:write'],\n  compile_to_bot_swarm: ['tools:write'],\n  compile_to_canvas2d_game: ['tools:write'],\n  compile_to_code_editor: ['tools:write'],\n  compile_to_colyseus: ['tools:write'],\n  compile_to_dtdl: ['tools:write'],\n  compile_to_dungeon_instance: ['tools:write'],\n  compile_to_edge: ['tools:write'],\n  compile_to_embodied_dataset: ['tools:write'],\n  compile_to_flutter: ['tools:write'],\n  compile_to_fmu: ['tools:write'],\n  compile_to_gaussian_train: ['tools:write'],\n  compile_to_holob: ['tools:write'],\n  compile_to_ios: ['tools:write'],\n  compile_to_lens_studio: ['tools:write'],\n  compile_to_llama_server: ['tools:write'],\n  compile_to_mcp_config: ['tools:write'],\n  compile_to_mcp_server: ['tools:write'],\n  compile_to_mjcf: ['tools:write'],\n  compile_to_mjx: ['tools:write'],\n  compile_to_nft_marketplace: ['tools:write'],\n  compile_to_nir: ['tools:write'],\n  compile_to_node_service: ['tools:write'],\n  compile_to_onnx: ['tools:write'],\n  compile_to_openapi: ['tools:write'],\n  compile_to_openxr_spatial_entities: ['tools:write'],\n  compile_to_pcg_graph: ['tools:write'],\n  compile_to_qasm: ['tools:write'],\n  compile_to_quest: ['tools:write'],\n  compile_to_rom_twin: ['tools:write'],\n  compile_to_ros2_deploy: ['tools:write'],\n  compile_to_scm: ['tools:write'],\n  compile_to_sdf: ['tools:write'],\n  compile_to_sdk: ['tools:write'],\n  compile_to_state: ['tools:write'],\n  compile_to_stl_export: ['tools:write'],\n  compile_to_svg: ['tools:write'],\n  compile_to_tsl: ['tools:write'],\n  compile_to_usd: ['tools:write'],\n  compile_to_usdz: ['tools:write'],\n  compile_to_visionos: ['tools:write'],\n  compile_to_vrchat: ['tools:write'],\n  compile_to_wasm: ['tools:write'],\n  compile_to_world_shard: ['tools:write'],\n  compile_trait_composition: ['tools:write'],\n  export_traces_otlp: ['tools:write'],\n  fairness_sweep: ['tools:write'],\n  generate_service_contract: ['tools:write'],\n  holo_edit_file: ['tools:write'],\n  holo_generate_bindings: ['tools:write'],\n  holo_generate_mesh: ['tools:write'],\n  holo_generate_semantic_scene_graph: ['tools:write'],\n  holo_git_commit: ['tools:write'],\n  holo_hologram_inject_world: ['tools:write'],\n  holo_hologram_upload_bundle: ['tools:write'],\n  holo_oracle_synthesize: ['tools:write'],\n  holo_reconstruct_export: ['tools:write'],\n  holo_reconstruct_from_video: ['tools:write'],\n  holo_reconstruct_step: ['tools:write'],\n  holo_run_related_tests: ['tools:write'],\n  holo_run_tests_targeted: ['tools:write'],\n  holo_scaffold_code: ['tools:write'],\n  holo_service_scaffold: ['tools:write'],\n  holo_tunnel_close: ['tools:write'],\n  holo_tunnel_create: ['tools:write'],\n  holo_write_file: ['tools:write'],\n  hololand_brittney_npc_mode: ['tools:write'],\n  hololand_create_npc: ['tools:write'],\n  hololand_create_player_invite: ['tools:write'],\n  hololand_delete_npc: ['tools:write'],\n  hololand_npc_generate_dialogue: ['tools:write'],\n  hololand_update_npc: ['tools:write'],\n  holomesh_board_append_commit: ['tools:write'],\n  holomesh_crosspost_moltbook: ['tools:write'],\n  holomesh_gossip_sync: ['tools:write'],\n  // heartbeat is a presence keepalive that EVERY non-admin agent (incl. read-only monitors) issues;\n  // task_1783805494038 names it a flow that must not break. Kept at tools:read (least-privilege that\n  // preserves the liveness ping) even though it updates a presence timestamp — a human override of the\n  // classifier's semantic write call, per the task's runtime-verify requirement.\n  holomesh_heartbeat: ['tools:read'],\n  holomesh_mark_read: ['tools:write'],\n  holomesh_moltbook_crosspost: ['tools:write'],\n  holomesh_publish_agent_template: ['tools:write'],\n  holomesh_publish_insight: ['tools:write'],\n  holomesh_reply: ['tools:write'],\n  holomesh_scout: ['tools:write'],\n  holomesh_send_message: ['tools:write'],\n  holomesh_suggest: ['tools:write'],\n  holomesh_suggest_vote: ['tools:write'],\n  holomesh_team_load_agents: ['tools:write'],\n  holomesh_team_run_cycle: ['tools:write'],\n  holomesh_upvote_reply: ['tools:write'],\n  holoscript_compile_education: ['tools:write'],\n  holoscript_compile_healthcare: ['tools:write'],\n  holoscript_compile_iot: ['tools:write'],\n  holoscript_compile_music: ['tools:write'],\n  holoscript_compile_robotics: ['tools:write'],\n  holoscript_compose_traits: ['tools:write'],\n  holoscript_map_csv: ['tools:write'],\n  holoscript_map_schema: ['tools:write'],\n  holoshell_download_recovery_forensic_export: ['tools:write'],\n  holoshell_download_recovery_import_handoff: ['tools:write'],\n  holoshell_download_recovery_quarantine: ['tools:write'],\n  holoshell_download_recovery_resume: ['tools:write'],\n  holotune_curate: ['tools:write'],\n  holotune_download: ['tools:write'],\n  push_portal_intent: ['tools:write'],\n  solve_logic: ['tools:write'],\n  solve_structural: ['tools:write'],\n  solve_thermal: ['tools:write'],\n  stream_world_tiles: ['tools:write'],\n  twin_earth_ai_invoke: ['tools:write'],\n  twin_earth_capture_receipt: ['tools:write'],\n  // read-only / no side effects:\n  absorb_check_credits: ['tools:read'],\n  absorb_list_projects: ['tools:read'],\n  absorb_suggest_holoscript_transform: ['tools:read'],\n  alphafold_fetch_structure: ['tools:read'],\n  check_agent_budget: ['tools:read'],\n  check_permission: ['tools:read'],\n  discover_agents: ['tools:read'],\n  discover_plugins: ['tools:read'],\n  explain_fairness_receipt: ['tools:read'],\n  explain_service_contract: ['tools:read'],\n  get_agent_health: ['tools:read'],\n  get_api_reference: ['tools:read'],\n  get_circuit_breaker_status: ['tools:read'],\n  get_delegation_chain: ['tools:read'],\n  get_dev_dashboard_state: ['tools:read'],\n  get_metrics_prometheus: ['tools:read'],\n  get_task_status: ['tools:read'],\n  get_tool_health: ['tools:read'],\n  get_tool_manifest: ['tools:read'],\n  get_unified_budget_state: ['tools:read'],\n  get_usage_summary: ['tools:read'],\n  get_workspace_info: ['tools:read'],\n  holo_batch_type_fix: ['tools:read'],\n  holo_critic: ['tools:read'],\n  holo_estimate_task_duration: ['tools:read'],\n  holo_founder: ['tools:read'],\n  holo_hologram_get_asset: ['tools:read'],\n  holo_list_type_errors: ['tools:read'],\n  holo_map_paper_ingest_probe: ['tools:read'],\n  holo_memory_farm: ['tools:read'],\n  holo_memory_list: ['tools:read'],\n  holo_memory_recall: ['tools:read'],\n  holo_memory_stats: ['tools:read'],\n  holo_oracle_consult: ['tools:read'],\n  holo_oracle_curate: ['tools:read'],\n  holo_oracle_discover: ['tools:read'],\n  holo_oracle_explore: ['tools:read'],\n  holo_oracle_gaps: ['tools:read'],\n  holo_premortem: ['tools:read'],\n  holo_protocol_lookup: ['tools:read'],\n  holo_protocol_revenue: ['tools:read'],\n  holo_quality_trend: ['tools:read'],\n  holo_read_file: ['tools:read'],\n  holo_reconstruct_anchor: ['tools:read'],\n  holo_semantic_scene_graph: ['tools:read'],\n  holo_task_kolmogorov_score: ['tools:read'],\n  holo_tunnel_status: ['tools:read'],\n  holo_verify_before_commit: ['tools:read'],\n  hololand_get_agent: ['tools:read'],\n  hololand_get_creator: ['tools:read'],\n  hololand_get_geo_anchor: ['tools:read'],\n  hololand_get_invite: ['tools:read'],\n  hololand_get_npc: ['tools:read'],\n  hololand_get_player: ['tools:read'],\n  hololand_list_agents: ['tools:read'],\n  hololand_list_creators: ['tools:read'],\n  hololand_list_geo_anchors: ['tools:read'],\n  hololand_list_npcs: ['tools:read'],\n  hololand_list_players: ['tools:read'],\n  hololand_npc_byok_status: ['tools:read'],\n  hololand_twin_earth_contract: ['tools:read'],\n  hololand_twin_earth_substrate_status: ['tools:read'],\n  holomesh_agent_capabilities: ['tools:read'],\n  holomesh_discussion: ['tools:read'],\n  holomesh_feed_source: ['tools:read'],\n  holomesh_inbox: ['tools:read'],\n  holomesh_knowledge_read: ['tools:read'],\n  holomesh_marketplace_search: ['tools:read'],\n  holomesh_notifications: ['tools:read'],\n  holomesh_presence: ['tools:read'],\n  holomesh_query_spatial: ['tools:read'],\n  holomesh_read_thread: ['tools:read'],\n  holomesh_search: ['tools:read'],\n  holomesh_sovereign_topology: ['tools:read'],\n  holomesh_suggest_list: ['tools:read'],\n  holomesh_team_compound: ['tools:read'],\n  holomesh_team_form: ['tools:read'],\n  holomesh_wallet_status: ['tools:read'],\n  holoscript_audit_numbers: ['tools:read'],\n  holoscript_code_health: ['tools:read'],\n  holoscript_select_modality: ['tools:read'],\n  holoshell_download_recovery_list: ['tools:read'],\n  holotune_eval: ['tools:read'],\n  holotune_serve: ['tools:read'],\n  holotune_status: ['tools:read'],\n  inspect_trace_waterfall: ['tools:read'],\n  list_export_targets: ['tools:read'],\n  list_plugins: ['tools:read'],\n  optimize_scene_budget: ['tools:read'],\n  query_traces: ['tools:read'],\n  rig_match_skeleton: ['tools:read'],\n  serve_preview: ['tools:read'],\n  sim_fleet_status: ['tools:read'],\n  sim_quote: ['tools:read'],\n  suggest_tools_for_goal: ['tools:read'],\n  suggest_universal_traits: ['tools:read'],\n  twin_earth_get_identity: ['tools:read'],\n  twin_earth_get_safety_envelope: ['tools:read'],\n  twin_earth_list_identities: ['tools:read'],\n  twin_earth_list_permissions: ['tools:read'],\n  twin_earth_list_safety_envelopes: ['tools:read'],\n  twin_earth_validate_permission: ['tools:read'],\n  validate_composition: ['tools:read'],\n  validate_marketplace_pricing: ['tools:read'],\n  verify_cael_trace: ['tools:read'],\n  verify_cross_perceiver: ['tools:read'],\n  verify_verified_view: ['tools:read'],\n  // === v2g4-delta: the 25 tools that ALL_AVAILABLE_TOOLS adds beyond the 426-tool base\n  // (daemon-lifecycle / GRPO / negotiation / compute-trace / spatial). Same classify+verify\n  // workflow. holo_run_grpo_pass verified as WRITE (local test/lint scoring, NOT fleet/GPU spend);\n  // negotiation_settle is the one admin (settles a money contract). ===\n  // admin:\n  negotiation_settle: ['tools:admin'],\n  // write:\n  compile_to_spatial: ['tools:write'],\n  holo_create_daemon: ['tools:write'],\n  holo_daemon_emergence_check: ['tools:write'],\n  holo_daemon_turn: ['tools:write'],\n  holo_export_compute_traces: ['tools:write'],\n  holo_export_emergence_corpus: ['tools:write'],\n  holo_extract_grpo_prompts: ['tools:write'],\n  holo_grade_compute_mutation: ['tools:write'],\n  holo_observe_soul: ['tools:write'],\n  holo_run_grpo_pass: ['tools:write'],\n  holo_update_daemon_ritual: ['tools:write'],\n  negotiation_accept: ['tools:write'],\n  negotiation_dispute: ['tools:write'],\n  negotiation_execute: ['tools:write'],\n  negotiation_quote: ['tools:write'],\n  negotiation_reject: ['tools:write'],\n  negotiation_request_quote: ['tools:write'],\n  visualize_query_result: ['tools:write'],\n  // read:\n  holo_compute_trace_stats: ['tools:read'],\n  holo_get_daemon: ['tools:read'],\n  holo_list_daemons: ['tools:read'],\n  holoscript_discover_tools: ['tools:read'],\n  negotiation_get: ['tools:read'],\n  negotiation_list: ['tools:read'],\n};\n\n// ── Scope Classification ─────────────────────────────────────────────────────\n\n/** Risk levels for tool operations */\nexport type ToolRiskLevel = 'low' | 'medium' | 'high' | 'critical';\n\nconst TOOL_RISK_MAP: Record<string, ToolRiskLevel> = {\n  // Low risk: read-only, no side effects\n  parse_hs: 'low',\n  parse_holo: 'low',\n  parse_pipeline: 'low',\n  validate_holoscript: 'low',\n  list_traits: 'low',\n  explain_trait: 'low',\n  get_syntax_reference: 'low',\n  get_examples: 'low',\n  explain_code: 'low',\n  analyze_code: 'low',\n  hs_hover: 'low',\n  hs_docs: 'low',\n  holo_from_scratch_status: 'low',\n\n  // Meta-dispatch is side-effect free itself; inner tools retain their own risk.\n  batch_tool_call: 'medium',\n  holoscript_batch_execute: 'medium',\n\n  // Medium risk: generates content but no side effects\n  suggest_traits: 'medium',\n  suggest_2d_traits: 'medium',\n  generate_object: 'medium',\n  generate_scene: 'medium',\n  generate_semantic_ui: 'medium',\n  holo_hologram_from_media: 'medium',\n  holo_hologram_compile_quilt: 'medium',\n  holo_hologram_compile_mvhevc: 'medium',\n  convert_format: 'medium',\n  compile_holoscript: 'medium',\n  compile_pipeline: 'medium',\n\n  // High risk: external side effects, file I/O, browser control\n  render_preview: 'high',\n  create_share_link: 'high',\n  edit_holo: 'high',\n  browser_launch: 'high',\n  browser_execute: 'high',\n  browser_screenshot: 'high',\n  holo_absorb_repo: 'high',\n  holo_hologram_render: 'high',\n  holo_hologram_publish_feed: 'high',\n  holo_hologram_send: 'high',\n\n  // Critical: admin operations, self-modification\n  holo_self_diagnose: 'critical',\n  holo_validate_quality: 'critical',\n  execute_holotest: 'critical',\n  execute_eval: 'critical',\n  generate_hololand_training: 'critical',\n  holo_add_wisdom: 'critical',\n  holo_add_gotcha: 'critical',\n  holo_from_scratch_launch: 'critical',\n\n  // HoloMesh: spatial networking\n  holomesh_status: 'low',\n  holomesh_discover: 'low',\n  holomesh_publish_tool: 'medium',\n  holomesh_invoke_tool: 'high',\n  holomesh_query: 'low',\n  holomesh_subscribe: 'low',\n  holomesh_contribute: 'medium',\n  holomesh_collect: 'medium',\n  holomesh_gossip: 'high',\n\n  // HoloLand MMO / Twin Earth product actions\n  hololand_shard_status: 'low',\n  hololand_publish_zone: 'medium',\n  hololand_create_geo_anchor: 'medium',\n  hololand_steward_tick: 'high',\n  hololand_capture_runtime_receipt: 'high',\n\n  // HoloMesh Board / Slots / Mode\n  holomesh_board_list: 'low',\n  holomesh_board_done_log: 'low',\n  holomesh_board_add: 'medium',\n  holomesh_board_claim: 'medium',\n  holomesh_board_complete: 'medium',\n  holomesh_slot_assign: 'high',\n  holomesh_mode_set: 'high',\n\n  // Railway Deployment\n  railway_project_create: 'critical',\n  railway_service_create: 'critical',\n  railway_deploy: 'critical',\n  railway_variable_set: 'critical',\n  railway_domain_add: 'high',\n  railway_deployment_status: 'low',\n\n  // Secrets Broker\n  holo_secrets_grant: 'critical',\n  holo_secrets_resolve: 'critical',\n  holo_secrets_revoke: 'critical',\n\n  // Conformance Artifact Admission Gate (HoloGate §admission)\n  conformance_list_rules: 'low',\n  conformance_check_artifact: 'medium',\n  conformance_admit_artifact: 'high',\n\n  // High-risk previously-unmapped tools (task_1783794507029) — see TOOL_SCOPE_MAP above.\n  settle_creator_payout: 'critical',\n  execute_economic_contract: 'critical',\n  sim_run_paid: 'critical',\n  get_creator_earnings: 'low',\n  issue_agent_token: 'critical',\n  verify_agent_token: 'low',\n  delegate_task: 'high',\n  twin_earth_robot_actuate: 'critical',\n  twin_earth_register_identity: 'critical',\n  twin_earth_revoke_identity: 'critical',\n  twin_earth_grant_permission: 'critical',\n  twin_earth_revoke_permission: 'critical',\n  twin_earth_create_safety_envelope: 'critical',\n  twin_earth_update_safety_envelope: 'critical',\n  twin_earth_delete_safety_envelope: 'critical',\n  holomesh_autonomous_control: 'critical',\n  holomesh_federate_twin_earth: 'critical',\n  holomesh_sovereign_lifepod_restore: 'critical',\n  holomesh_sovereign_lifepod_snapshot: 'high',\n  render_world_on_fleet: 'critical',\n  train_rom: 'critical',\n  sync_hardware_loop: 'high',\n  install_plugin: 'critical',\n  install_domain_plugin: 'critical',\n  manage_plugin: 'high',\n  holo_memory_graduate: 'high',\n  holo_memory_store: 'medium',\n  compile_to_daimon_seed: 'medium',\n  hololand_provision_player: 'high',\n  hololand_provision_agent: 'high',\n  hololand_provision_creator: 'high',\n  hololand_revoke_agent: 'high',\n  // v2g4 admin tools — critical risk:\n  holo_ci_dispatch: 'critical',\n  holo_protocol_collect: 'critical',\n  holo_protocol_publish: 'critical',\n  hololand_revoke_creator: 'critical',\n  hololand_revoke_player: 'critical',\n  holotune_launch: 'critical',\n  holotune_promote: 'critical',\n  twin_earth_update_identity: 'critical',\n  // v2g4-delta risk:\n  negotiation_settle: 'critical',\n  holo_daemon_emergence_check: 'medium',\n  holo_export_emergence_corpus: 'medium',\n  holo_observe_soul: 'medium',\n  holo_run_grpo_pass: 'high',\n  negotiation_accept: 'medium',\n  negotiation_dispute: 'medium',\n  negotiation_execute: 'medium',\n  negotiation_quote: 'medium',\n  negotiation_request_quote: 'medium',\n};\n\n// ── Registry-aware, fail-closed scope resolution (task_1783805494038) ─────────\n\n// The set of tool names the server ACTUALLY registered. Populated at startup by registerKnownTools\n// (called from index.ts / http-server.ts with the live tool list, plus plugin tools). Additive, so\n// dynamically-installed plugin tools can register their names too. When this is non-empty (i.e. the\n// registry is known), authorizeToolCall DENIES any name not in it — even presented with admin:* — so\n// a spoofed or unregistered tool name cannot be invoked (fail-closed-on-unregistered). Empty (e.g. a\n// unit test that calls authorizeToolCall directly without registering) → the check is skipped.\nconst KNOWN_TOOLS = new Set<string>();\n\n/** Register live tool names (idempotent, additive). Call at startup and whenever plugins load. */\nexport function registerKnownTools(names: Iterable<string>): void {\n  for (const n of names) {\n    const normalized = n.trim();\n    if (normalized) KNOWN_TOOLS.add(normalized);\n  }\n}\n\n/** True once at least one tool has been registered (the live registry is known). */\nexport function isToolRegistryKnown(): boolean {\n  return KNOWN_TOOLS.size > 0;\n}\n\n/** True iff the tool name is in the live registry. */\nexport function isRegisteredTool(name: string): boolean {\n  return KNOWN_TOOLS.has(name);\n}\n\n/** Reset the registry — test-only helper so suites can exercise the known/unknown paths. */\nexport function __resetKnownToolsForTest(): void {\n  KNOWN_TOOLS.clear();\n}\n\n// Dangerous-first keyword classifier — the FALLBACK for a registered tool that is somehow NOT in\n// TOOL_SCOPE_MAP. Every tool live today IS in the map (enforced by the completeness test), so this\n// only ever classifies a FUTURE tool. Admin triggers are tested FIRST, and the final fallback is\n// tools:admin (FAIL-CLOSED): a new, unrecognized tool requires the highest scope until a human maps\n// it explicitly — it never silently defaults to tools:read the way the old code did.\nconst ADMIN_KEYWORDS =\n  /settle|payout|economic|_paid\\b|_paid_|billing|invoice|spend|wallet|x402|treasury|issue_agent|_mint\\b|actuate|robot_|_robot\\b|provision_|_provision\\b|revoke|register_identity|update_identity|grant_permission|revoke_permission|safety_envelope|autonomous_control|sovereign_lifepod|federate|lifepod|render_world_on_fleet|_from_scratch|from_scratch_|holotune_(?:launch|promote|serve)|holo_ci_dispatch|sync_hardware|train_rom|install_plugin|install_domain|manage_plugin|secrets?_(?:grant|resolve|revoke)|memory_graduate|\\bgraduate\\b|protocol_(?:publish|collect|revenue)|delete_(?:world|shard|zone|place|npc)|_seed$|steward|capture_runtime|hololand_training/i;\nconst CODEBASE_KEYWORDS =\n  /absorb|codebase|semantic_search|ask_codebase|impact_analysis|resolve_symbol|detect_(?:changes|drift)|refactor_plan|generate_refactor|graph_status|get_absorb|provenance_answer|query_ai/i;\nconst BROWSER_KEYWORDS = /^browser_/i;\nconst WRITE_KEYWORDS =\n  /^create_|^update_|^delete_|^generate|^compile|^render|^edit_|^import_|^convert|^store|^write|^publish|^send|^add_|_add$|claim|complete|^set_|assign|scaffold|refactor|^launch|^run_|_run\\b|reconstruct|snapshot|rewind|contribute|invite|crosspost|npc_generate|steward|capture_runtime/i;\nconst READ_KEYWORDS =\n  /^get_|^list_|^parse_|^validate|^explain|^analyze|^discover|^query|^search|_status$|status$|_list$|health|hover|reference|examples|inspect|read$|_read\\b|lookup|estimate|score|^suggest|check_|diff|visualize|topology|manifest|budget|usage|metrics|wisdom/i;\n\n/** Dangerous-first classifier for tools not explicitly mapped. Fail-closed default: tools:admin. */\nexport function classifyToolScope(toolName: string): OAuthScope[] {\n  if (ADMIN_KEYWORDS.test(toolName)) return ['tools:admin'];\n  if (CODEBASE_KEYWORDS.test(toolName)) return ['tools:codebase'];\n  if (BROWSER_KEYWORDS.test(toolName)) return ['tools:browser'];\n  if (WRITE_KEYWORDS.test(toolName)) return ['tools:write'];\n  if (READ_KEYWORDS.test(toolName)) return ['tools:read'];\n  return ['tools:admin']; // FAIL-CLOSED: an unrecognized tool needs the highest scope until mapped.\n}\n\n/**\n * Resolve required scopes: the explicit map wins; otherwise the dangerous-first classifier (which\n * fails closed to tools:admin). This NEVER fail-opens to tools:read the way the old default did.\n */\nexport function resolveRequiredScopes(toolName: string): OAuthScope[] {\n  return TOOL_SCOPE_MAP[toolName] ?? classifyToolScope(toolName);\n}\n\n/**\n * True iff the tool has an EXPLICIT scope-map entry (not merely a classifier fallback). The\n * completeness test asserts every REGISTERED tool is explicitly mapped, so a newly-added tool that\n * nobody classified fails CI (rather than silently riding the classifier's fail-closed default).\n */\nexport function hasExplicitScope(toolName: string): boolean {\n  return Object.prototype.hasOwnProperty.call(TOOL_SCOPE_MAP, toolName);\n}\n\n// ── Gate 2: Tool Authorization ───────────────────────────────────────────────\n\nexport interface AuthorizationResult {\n  authorized: boolean;\n  reason?: string;\n  requiredScopes?: OAuthScope[];\n  grantedScopes?: OAuthScope[];\n  riskLevel?: ToolRiskLevel;\n}\n\n/**\n * Gate 2: Authorize a tool invocation against the authenticated token's scopes.\n *\n * @param toolName - The MCP tool being invoked\n * @param tokenScopes - Scopes granted to the authenticated token\n * @returns Authorization result with reason if denied\n */\nexport function authorizeToolCall(\n  toolName: string,\n  tokenScopes: OAuthScope[]\n): AuthorizationResult {\n  // Fail-closed on unregistered: once the live registry is known, a name that is NOT registered is\n  // denied outright — even with admin:* — so a spoofed / unregistered tool name cannot be invoked.\n  if (isToolRegistryKnown() && !KNOWN_TOOLS.has(toolName)) {\n    return {\n      authorized: false,\n      reason: `Tool \"${toolName}\" is not a registered tool (fail-closed on unregistered)`,\n      grantedScopes: tokenScopes,\n    };\n  }\n\n  // Resolve required scopes via the explicit map, else the dangerous-first classifier (fail-closed\n  // to tools:admin). NEVER fail-open to tools:read.\n  const requiredScopes = resolveRequiredScopes(toolName);\n\n  // admin:* grants everything (for a REGISTERED tool).\n  if (tokenScopes.includes('admin:*')) {\n    return {\n      authorized: true,\n      riskLevel: getToolRiskLevel(toolName),\n      grantedScopes: tokenScopes,\n      requiredScopes,\n    };\n  }\n\n  // Check if token has ANY of the required scopes\n  const hasScope = requiredScopes.some((required) => tokenScopes.includes(required));\n\n  if (!hasScope) {\n    return {\n      authorized: false,\n      reason: `Insufficient scope. Required one of: [${requiredScopes.join(', ')}]. Granted: [${tokenScopes.join(', ')}]`,\n      requiredScopes,\n      grantedScopes: tokenScopes,\n      riskLevel: getToolRiskLevel(toolName),\n    };\n  }\n\n  return {\n    authorized: true,\n    requiredScopes,\n    grantedScopes: tokenScopes,\n    riskLevel: getToolRiskLevel(toolName),\n  };\n}\n\n/**\n * Get the risk level for a tool.\n */\nexport function getToolRiskLevel(toolName: string): ToolRiskLevel {\n  return TOOL_RISK_MAP[toolName] || 'medium';\n}\n\n/**\n * Get the required scopes for a tool.\n */\nexport function getToolScopes(toolName: string): OAuthScope[] {\n  return resolveRequiredScopes(toolName);\n}\n\n/**\n * List all tools in a given scope.\n */\nexport function getToolsForScope(scope: OAuthScope): string[] {\n  return Object.entries(TOOL_SCOPE_MAP)\n    .filter(([, scopes]) => scopes.includes(scope))\n    .map(([name]) => name);\n}\n","/**\n * MCP Plugin Manager\n *\n * Enables dynamic registration of tools and handlers for the HoloScript MCP server.\n * This allows proprietary protocols like UAA2 to plug in without being part of\n * the open-source codebase.\n */\n\nimport { Tool } from '@modelcontextprotocol/sdk/types.js';\nimport { gatePluginRegistration } from './security/fork-sandbox-gate';\nimport { registerKnownTools } from './security/tool-scopes';\n\nexport type ToolHandler = (name: string, args: Record<string, unknown>) => Promise<unknown>;\n\nexport interface PluginManifest {\n  name: string;\n  scopeName?: string;\n  version?: string;\n  trustTier?: string;\n  manifest?: Record<string, unknown>;\n  [key: string]: unknown;\n}\n\nexport class PluginManager {\n  private static tools: Tool[] = [];\n  private static handlers: Map<string, ToolHandler> = new Map();\n\n  /**\n   * Register a plugin with one or more tools and a handler.\n   * Enforces the fork sandbox gate before admitting any plugin.\n   *\n   * @param pluginTools - MCP tools exposed by this plugin\n   * @param handler - Handler function for tool calls\n   * @param manifest - Optional plugin manifest for fork-sandbox gating\n   */\n  static async registerPlugin(\n    pluginTools: Tool[],\n    handler: ToolHandler,\n    manifest?: PluginManifest\n  ) {\n    const gateManifest: Record<string, unknown> = {\n      name: manifest?.name ?? pluginTools[0]?.name ?? 'unnamed',\n      toolCount: pluginTools.length,\n      tools: pluginTools.map((t) => t.name),\n      ...manifest,\n    };\n    const gate = await gatePluginRegistration(gateManifest);\n    if (!gate.allowed) {\n      throw new Error(\n        `Plugin registration denied by ForkSandboxGate: ${gate.receipt?.reason ?? 'policy violation'} (receiptId=${gate.receipt?.receiptId})`\n      );\n    }\n    this.tools.push(...pluginTools);\n    for (const tool of pluginTools) {\n      this.handlers.set(tool.name, handler);\n    }\n    // Register plugin tool names with the Gate-2 authorizer so fail-closed-on-unregistered admits\n    // them (an installed plugin's tools are legitimately part of the live registry).\n    registerKnownTools(pluginTools.map((t) => t.name));\n  }\n\n  /**\n   * Get all registered plugin tools\n   */\n  static getTools(): Tool[] {\n    return this.tools;\n  }\n\n  /**\n   * Handle a tool call if it belongs to a registered plugin\n   */\n  static async handleTool(name: string, args: Record<string, unknown>): Promise<unknown | null> {\n    const handler = this.handlers.get(name);\n    if (handler) {\n      return await handler(name, args);\n    }\n    return null;\n  }\n\n  /**\n   * Reset all registered plugin state (tools + handlers).\n   * For use in test afterEach / beforeEach to prevent test tool names\n   * from leaking into the production tool list via static state.\n   */\n  static reset(): void {\n    this.tools = [];\n    this.handlers.clear();\n  }\n}\n","/**\n * Append-Only Audit Log for Tier 2 Custodial Key Access — Phase 5.\n *\n * Every private-key decryption and custodial signing operation MUST emit an\n * audit event. Events are append-only (never mutated or deleted) and are\n * persisted to an external sink via subscribers wired at server startup.\n *\n * Per ADR §\"Server-side key management (Q2 approved)\":\n *   - \"Audit log of every private-key access — append-only, separate store,\n *     external retention\"\n *   - \"Logs never record decrypted keys (redaction at structured-log-middleware\n *     level; separate audit log for key-access events)\"\n *\n * This module provides:\n *   1. Structured event types for key lifecycle events\n *   2. Redaction helpers that NEVER expose raw key material\n *   3. An in-memory buffer + subscriber system for real-time and persistent sinks\n *   4. A query API for compliance auditing (who accessed what key, when)\n *\n * Future DB backend: swap the in-memory buffer for a real append-only store\n * (PostgreSQL with a trigger-only table, DynamoDB Streams, or CloudWatch\n * Logs) by reimplementing `append` and `query`. The subscriber interface\n * stays the same.\n *\n * @module holomesh/identity/audit-log\n */\n\n// ── Event types ───────────────────────────────────────────────────────────\n\n/** Every category of auditable event in the custodial key lifecycle. */\nexport type AuditEventType =\n  | 'key_generated' // New keypair created for a user\n  | 'key_accessed' // Private key decrypted for signing\n  | 'key_rotated' // Old key retired, new key provisioned\n  | 'signing_performed' // Custodial signing on behalf of user\n  | 'key_export_prepared' // Self-custody export package created\n  | 'key_export_finalized' // Self-custody migration completed\n  | 'key_access_denied'; // Attempted access by unauthorized caller\n\n/** The severity level for audit events. Redacted logs use `info` for\n *  routine operations and `warn`/`error` for denied or anomalous access. */\nexport type AuditSeverity = 'info' | 'warn' | 'error';\n\n/** Structured audit event. All fields are safe to persist — no raw key material. */\nexport interface AuditEvent {\n  /** Monotonic event ID (unique within a server instance). */\n  id: string;\n  /** The event category. */\n  type: AuditEventType;\n  /** ISO 8601 timestamp. */\n  timestamp: string;\n  /** The user whose key was involved. */\n  userId: string;\n  /** Public key hash (SHA-256, first 16 hex chars) — never the full public key. */\n  publicKeyHash: string;\n  /** Who initiated the access. For server-initiated operations this is\n   *  `system:custodial-signing-service`; for user-initiated it's the\n   *  authenticated agent/user ID. */\n  accessedBy: string;\n  /** The source IP of the request, when available. */\n  sourceIp?: string;\n  /** Structured metadata about the operation. Never contains key material. */\n  metadata: Record<string, unknown>;\n  /** Severity for log routing. */\n  severity: AuditSeverity;\n}\n\n/** Subscriber callback — receives every committed event. */\nexport type AuditSubscriber = (event: AuditEvent) => void;\n\n// ── Redaction helpers ─────────────────────────────────────────────────────\n\n/**\n * Compute a truncated SHA-256 hash of a public key for audit references.\n * Returns the first 16 hex characters (64 bits of entropy), which is more\n * than enough for unique identification in audit logs without exposing the\n * full key.\n */\nexport function hashPublicKey(publicKey: string): string {\n  const { createHash } = require('crypto') as typeof import('crypto');\n  return createHash('sha256').update(publicKey).digest('hex').slice(0, 16);\n}\n\n/**\n * Redact a private key for logging. Returns a fixed-length placeholder\n * that indicates the key existed but never reveals any bits of it.\n *\n * Convention: `[REDACTED:8-chars-of-pubkey-hash]` so auditors can correlate\n * with the public key hash without seeing any private material.\n */\nexport function redactPrivateKey(privateKeyHint: string): string {\n  return `[REDACTED:${hashPublicKey(privateKeyHint)}]`;\n}\n\n/**\n * Redact an entire object for structured logging. Recursively walks the\n * object and replaces any value whose key contains 'private', 'secret',\n * 'key' (as a standalone word), 'password', or 'token' with '[REDACTED]'.\n *\n * This is the structured-log-middleware redaction referenced in the ADR.\n * It's intentionally broad — false positives (redacting a 'keyboard' field)\n * are far less dangerous than false negatives (leaking a private key).\n */\nexport function redactForLogging(obj: unknown): unknown {\n  if (obj === null || obj === undefined) return obj;\n  if (typeof obj === 'string') return obj;\n  if (typeof obj !== 'object') return obj;\n\n  // Substring-match redaction — any key containing these words gets redacted.\n  // This catches privateKey, secretKey, password, token, privkey, etc.\n  const REDACTED_SUBSTRING = /private|secret|password|token|privkey|priv_key/i;\n  // Exact-match — 'key' as a standalone key name (not publicKey, not apiKey, etc.)\n  const EXACT_REDACTED = /^(key)$/i;\n\n  if (Array.isArray(obj)) {\n    return obj.map(redactForLogging);\n  }\n\n  const result: Record<string, unknown> = {};\n  for (const [k, v] of Object.entries(obj as Record<string, unknown>)) {\n    if (EXACT_REDACTED.test(k) || REDACTED_SUBSTRING.test(k)) {\n      result[k] = '[REDACTED]';\n    } else if (typeof v === 'object' && v !== null) {\n      result[k] = redactForLogging(v);\n    } else {\n      result[k] = v;\n    }\n  }\n  return result;\n}\n\n// ── Audit log store ────────────────────────────────────────────────────────\n\nlet _eventCounter = 0;\nconst _eventBuffer: AuditEvent[] = [];\nconst _subscribers: AuditSubscriber[] = [];\n\n/** Generate a monotonic event ID within this server instance. */\nfunction nextEventId(): string {\n  _eventCounter += 1;\n  return `audit-${Date.now()}-${_eventCounter}`;\n}\n\n/**\n * Append an audit event. The event is committed to the in-memory buffer\n * and all subscribers are notified synchronously. A subscriber that throws\n * will NOT roll back the append — the event is authoritative once appended.\n * Subscriber errors are logged to stderr but do not prevent other\n * subscribers from receiving the event.\n */\nexport function appendAuditEvent(event: Omit<AuditEvent, 'id'>): AuditEvent {\n  const full: AuditEvent = {\n    ...event,\n    id: nextEventId(),\n  };\n  _eventBuffer.push(full);\n\n  for (const sub of _subscribers) {\n    try {\n      sub(full);\n    } catch (err) {\n      console.error(\n        '[audit-log] subscriber threw on event %s: %s',\n        full.id,\n        err instanceof Error ? err.message : String(err)\n      );\n    }\n  }\n\n  return full;\n}\n\n/**\n * Subscribe to audit events. Returns an unsubscribe function.\n * Subscribers are called synchronously after each append.\n */\nexport function onAuditEvent(sub: AuditSubscriber): () => void {\n  _subscribers.push(sub);\n  return () => {\n    const idx = _subscribers.indexOf(sub);\n    if (idx >= 0) _subscribers.splice(idx, 1);\n  };\n}\n\n/**\n * Query audit events by filter criteria. Returns events in chronological\n * order (oldest first). Useful for compliance auditing.\n */\nexport function queryAuditEvents(filter: {\n  userId?: string;\n  type?: AuditEventType;\n  since?: string; // ISO 8601 timestamp\n  limit?: number;\n}): AuditEvent[] {\n  let results = _eventBuffer;\n\n  if (filter.userId) {\n    results = results.filter((e) => e.userId === filter.userId);\n  }\n  if (filter.type) {\n    results = results.filter((e) => e.type === filter.type);\n  }\n  if (filter.since) {\n    const sinceMs = Date.parse(filter.since);\n    if (!Number.isNaN(sinceMs)) {\n      results = results.filter((e) => Date.parse(e.timestamp) >= sinceMs);\n    }\n  }\n\n  if (filter.limit && filter.limit > 0) {\n    results = results.slice(-filter.limit);\n  }\n\n  return results;\n}\n\n/**\n * Convenience: emit a key_accessed event when a private key is decrypted\n * for a signing operation. This is the most common audit event and the one\n * the ADR specifically calls out.\n */\nexport function auditKeyAccess(params: {\n  userId: string;\n  publicKeyHash: string;\n  accessedBy: string;\n  sourceIp?: string;\n  purpose: string;\n}): AuditEvent {\n  return appendAuditEvent({\n    type: 'key_accessed',\n    timestamp: new Date().toISOString(),\n    userId: params.userId,\n    publicKeyHash: params.publicKeyHash,\n    accessedBy: params.accessedBy,\n    sourceIp: params.sourceIp,\n    metadata: { purpose: params.purpose },\n    severity: 'info',\n  });\n}\n\n/**\n * Convenience: emit a key_access_denied event when an unauthorized caller\n * attempts to access a private key.\n */\nexport function auditKeyAccessDenied(params: {\n  userId: string;\n  publicKeyHash: string;\n  accessedBy: string;\n  sourceIp?: string;\n  reason: string;\n}): AuditEvent {\n  return appendAuditEvent({\n    type: 'key_access_denied',\n    timestamp: new Date().toISOString(),\n    userId: params.userId,\n    publicKeyHash: params.publicKeyHash,\n    accessedBy: params.accessedBy,\n    sourceIp: params.sourceIp,\n    metadata: { reason: params.reason },\n    severity: 'warn',\n  });\n}\n\n/**\n * Convenience: emit a key_generated event when a new keypair is provisioned.\n */\nexport function auditKeyGenerated(params: {\n  userId: string;\n  publicKeyHash: string;\n  provisionedBy: string;\n  derivationPath?: string;\n}): AuditEvent {\n  return appendAuditEvent({\n    type: 'key_generated',\n    timestamp: new Date().toISOString(),\n    userId: params.userId,\n    publicKeyHash: params.publicKeyHash,\n    accessedBy: params.provisionedBy,\n    metadata: {\n      derivationPath: params.derivationPath ?? 'platform-root',\n    },\n    severity: 'info',\n  });\n}\n\n/**\n * Convenience: emit a key_rotated event when a user's keypair is rotated.\n */\nexport function auditKeyRotated(params: {\n  userId: string;\n  oldPublicKeyHash: string;\n  newPublicKeyHash: string;\n  rotatedBy: string;\n}): AuditEvent {\n  return appendAuditEvent({\n    type: 'key_rotated',\n    timestamp: new Date().toISOString(),\n    userId: params.userId,\n    publicKeyHash: params.newPublicKeyHash,\n    accessedBy: params.rotatedBy,\n    metadata: {\n      oldPublicKeyHash: params.oldPublicKeyHash,\n    },\n    severity: 'info',\n  });\n}\n\n/**\n * Convenience: emit a signing_performed event when the custodial service\n * signs on behalf of a user.\n */\nexport function auditSigningPerformed(params: {\n  userId: string;\n  publicKeyHash: string;\n  signedBy: string;\n  payloadType: string;\n}): AuditEvent {\n  return appendAuditEvent({\n    type: 'signing_performed',\n    timestamp: new Date().toISOString(),\n    userId: params.userId,\n    publicKeyHash: params.publicKeyHash,\n    accessedBy: params.signedBy,\n    metadata: {\n      payloadType: params.payloadType,\n    },\n    severity: 'info',\n  });\n}\n\n// ── Test helpers ───────────────────────────────────────────────────────────\n\n/** Test-only: reset the in-memory buffer and counter. */\nexport function _resetAuditLogForTests(): void {\n  _eventBuffer.length = 0;\n  _subscribers.length = 0;\n  _eventCounter = 0;\n}\n\n/** Test-only: read the in-memory buffer directly. */\nexport function _getEventBufferForTests(): readonly AuditEvent[] {\n  return _eventBuffer.slice();\n}\n","/**\n * Task-Scoped Credential Vault Leases (task_1778102013331_u8q2).\n *\n * Spec evidence: research/2026-05-06_anthropic-managed-agents-gap-map.md row\n * \"Vault credentials\". Anthropic Managed Agents 2026-05-06 launched\n * session-scoped vault references - credentials are injected per session,\n * not pulled from a broad ambient `.env`. HoloMesh has `.env`, x402 seats,\n * and the GOLD posture, but no unified task-scoped secret lease layer.\n * This module is the substrate fix.\n *\n * Why a lease, not a vault:\n *   The credentials already live somewhere (.env, x402 keychain, GOLD,\n *   custodial-wallet store). The gap is not \"where is the credential\"\n *   it is \"did the holder of this lease earn the right to read it,\n *   for this task, for this scope, until this expiry, with audit trail\".\n *   A lease is a time-bounded, scope-bounded, task-bound capability that\n *   wraps the existing credential surface.\n *\n * Invariants (non-negotiable):\n *   1. A lease is bound to ONE task id (TeamTask.id). Cannot be reused\n *      across tasks. Re-issuance for a new task creates a new lease id.\n *   2. A lease is bound to ONE agent id (the claimer of the task). The\n *      agent id is the registered identity (TeamTask.claimedBy), not the\n *      surface tag. Surface tag is captured separately for the audit trail.\n *   3. A lease has a hard expiry (ISO timestamp). Expired leases are\n *      rejected without revealing whether the secretRef would have resolved.\n *      Lease expiry MUST be < 24h from issuance (enforced).\n *   4. A lease has a scope: an array of canonical secretRef strings the\n *      agent has permission to read. Reading any secret outside the scope\n *      is rejected as `lease_scope_violation` and audited.\n *   5. Wallet credentials (HOLOMESH_WALLET_*, anything ending in\n *      _WALLET_KEY / _WALLET_ADDRESS) are PERMANENTLY UNLEASABLE per\n *      G.GOLD.016 - wallets are identity, not sessions. Attempting to\n *      add a wallet ref to lease scope returns `wallet_unleasable` BEFORE\n *      the lease is persisted.\n *   6. Revocation propagates to running tasks: any open `redeemLease`\n *      handle for a revoked lease MUST observe revocation on its next\n *      check (we expose `isLeaseValid(leaseId)` for handle-side polling\n *      and refuse subsequent `resolveSecret` calls).\n *   7. Every lifecycle event (issue / redeem / deny / expire / revoke)\n *      emits a structured audit event via the existing audit-log module.\n *      No raw secret material in audit events - `secretRef` is the\n *      canonical name, never the value.\n *\n * Atomicity contract for `issueLease`:\n *   Either (A) lease persisted + audit event emitted + scope-resolved-secret-\n *   ref list returned, OR (B) zero state mutated + zero audit event emitted +\n *   structured rejection returned. The wallet-scope check fires BEFORE the\n *   commit phase so a rejected lease leaves no audit-log noise.\n *\n * Future DB backend:\n *   `withTransaction(fn)` wraps the persist phase. In-memory today; swap to\n *   PostgreSQL by reimplementing `withTransaction` as BEGIN/COMMIT/ROLLBACK\n *   around the same closure. Handler code does not change.\n *\n * Frame check (W.GOLD.191): the deployed read-path for secrets is\n *   `process.env.<KEY>`. This module is a parallel registry - it does NOT\n *   replace ambient .env reads in the existing codebase. The path forward is:\n *     - Phase 1 (this commit): registry + routes + tests + audit wiring.\n *       Existing code keeps reading .env. Leases are an opt-in layer.\n *     - Phase 2 (follow-up task): wrap critical secret reads with\n *       `resolveSecretWithLease(taskId, ref)` so the runner enforces leases\n *       at the call site, not at the vault.\n *   This is intentional. Shipping a registry that nothing checks is honest\n *   about the gap; rewiring every .env read in one commit would silently\n *   break unrelated paths. See \"What ships?\" in W.GOLD.191.\n *\n * @module holomesh/identity/vault-lease-registry\n */\n\nimport * as crypto from 'crypto';\nimport { AsyncLocalStorage } from 'async_hooks';\nimport { appendAuditEvent, hashPublicKey, type AuditEvent } from './audit-log';\n\n// -- Types -----------------------------------------------------------------\n\n/** A canonical reference to a secret. Format: `<surface>:<key>` where surface\n *  is one of `env`, `x402`, `custodial`, `gold`. Examples:\n *    - `env:HOLOSCRIPT_API_KEY`\n *    - `x402:CLAUDECODE_X402`\n *    - `custodial:<userId>:signing-key`\n *  The string is the audit-safe label. Never the value. */\nexport type SecretRef = string;\n\n/** Reason a lease was rejected. Stable strings for client-side branching. */\nexport type LeaseRejectReason =\n  | 'wallet_unleasable' // scope contained a wallet credential (G.GOLD.016)\n  | 'expiry_too_far' // expiry > MAX_LEASE_DURATION_MS from now\n  | 'expiry_in_past' // expiry already passed at issuance\n  | 'scope_empty' // empty scope array (always reject)\n  | 'task_not_claimed' // task has no claimedBy at issuance time\n  | 'task_id_missing' // taskId not provided\n  | 'agent_id_missing' // agentId not provided\n  | 'duplicate_lease' // lease already exists for (taskId, agentId)\n  | 'lease_not_found' // redeem/revoke against unknown lease id\n  | 'lease_expired' // redeem against past-expiry lease\n  | 'lease_revoked' // redeem against revoked lease\n  | 'lease_agent_mismatch' // redeem with wrong agent id\n  | 'lease_scope_violation'; // resolveSecret for ref not in lease scope\n\n/** Reason a lease was revoked. Recorded in audit trail for compliance. */\nexport type RevokeReason =\n  | 'task_completed' // happy-path: task moved to done, lease no longer needed\n  | 'task_released' // task unclaimed and returned to open pool\n  | 'agent_compromise' // operator-initiated emergency revocation\n  | 'expired_sweep' // expired by background sweeper (audit even though redundant)\n  | 'rotation' // upstream secret rotated; downstream leases invalidated\n  | 'manual'; // operator without specific reason\n\n/** A persisted lease record. Returned by `issueLease`, `getLease`. */\nexport interface VaultLease {\n  /** Unique lease id. Format: `lease-<taskId>-<8-hex>`. */\n  leaseId: string;\n  /** TeamTask.id this lease is bound to. */\n  taskId: string;\n  /** Registered agent id (TeamTask.claimedBy). */\n  agentId: string;\n  /** Surface-attribution tag captured at issuance, audit-only. May be undefined. */\n  agentTag?: string;\n  /** Canonical secretRef strings the agent may resolve under this lease. */\n  scope: SecretRef[];\n  /** ISO 8601 issuance timestamp. */\n  issuedAt: string;\n  /** ISO 8601 expiry. Always < issuedAt + MAX_LEASE_DURATION_MS. */\n  expiresAt: string;\n  /** Status. `active` until revoked/expired; never auto-flips on read. */\n  status: 'active' | 'revoked' | 'expired';\n  /** Revocation metadata once revoked. Undefined while `active`. */\n  revoked?: {\n    at: string;\n    reason: RevokeReason;\n    by: string; // agent id or 'system' for sweeper\n  };\n}\n\n/** Successful issuance. */\nexport interface IssueLeaseSuccess {\n  ok: true;\n  lease: VaultLease;\n}\n\n/** Rejected issuance. */\nexport interface IssueLeaseFailure {\n  ok: false;\n  reason: LeaseRejectReason;\n  detail?: string;\n}\n\nexport type IssueLeaseResult = IssueLeaseSuccess | IssueLeaseFailure;\n\n/** Outcome of a `resolveSecret` call. NEVER carries the raw value here -\n *  callers receive an opaque `resolved` boolean and pass through the\n *  redaction-safe label. The actual value is read by a separate adapter\n *  (Phase 2). This keeps the registry pure and audit-safe. */\nexport interface ResolveSecretResult {\n  ok: boolean;\n  reason?: LeaseRejectReason;\n  /** Echo of the requested ref (audit-safe label). */\n  secretRef?: SecretRef;\n  /** Lease-side decision; the value-fetching adapter is a separate layer. */\n  resolved: boolean;\n}\n\n// -- Constants -------------------------------------------------------------\n\n/** Hard upper bound on lease duration (24h). Leases are SESSION-scoped, not\n *  long-lived API keys. If a task takes longer than 24h, re-issue. */\nexport const MAX_LEASE_DURATION_MS = 24 * 60 * 60 * 1000;\n\n/** Minimum lease duration (1 second) - guards against zero/negative durations\n *  passed by callers. */\nexport const MIN_LEASE_DURATION_MS = 1000;\n\n/** Wallet-credential ref patterns. Per G.GOLD.016 - wallets are identity,\n *  not sessions. These cannot be added to lease scope under any circumstances.\n *\n *  Patterns are case-insensitive substring checks against the bare key portion\n *  of the secretRef (the part after the surface prefix). The check is broad\n *  on purpose: better to reject a non-wallet ref that happens to mention\n *  WALLET than to ever leak a wallet via a typo. */\nexport const UNLEASABLE_PATTERNS: readonly RegExp[] = [\n  /WALLET_ADDRESS/i,\n  /WALLET_KEY/i,\n  /WALLET_PRIVATE/i,\n  /WALLET_SEED/i,\n  /WALLET_MNEMONIC/i,\n  /HOLOMESH_WALLET/i,\n  /TREZOR/i,\n  /LEDGER_PRIVATE/i,\n];\n\n// -- Registry storage ------------------------------------------------------\n\n/** In-memory lease store. Key: leaseId. Future: swap for PostgreSQL with\n *  a UNIQUE constraint on (taskId, agentId, status='active'). */\nconst leasesById: Map<string, VaultLease> = new Map();\n\n/** Index by (taskId, agentId) to enforce duplicate-lease invariant cheaply.\n *  Key: `${taskId}::${agentId}`. Only `active` leases are indexed; revoked\n *  and expired leases drop out of the index. */\nconst activeLeaseByTaskAgent: Map<string, string> = new Map();\n\n// -- Helpers ---------------------------------------------------------------\n\nfunction nextLeaseId(taskId: string): string {\n  // Trim taskId to keep lease ids readable. taskIds are like\n  // `task_1778102013331_u8q2`, which we abbreviate to the last 8 chars.\n  const taskSuffix = taskId.length > 12 ? taskId.slice(-8) : taskId;\n  const rand = crypto.randomBytes(4).toString('hex');\n  return `lease-${taskSuffix}-${rand}`;\n}\n\nfunction leaseIndexKey(taskId: string, agentId: string): string {\n  return `${taskId}::${agentId}`;\n}\n\nfunction isWalletRef(ref: SecretRef): boolean {\n  for (const pattern of UNLEASABLE_PATTERNS) {\n    if (pattern.test(ref)) return true;\n  }\n  return false;\n}\n\nfunction isExpired(lease: VaultLease, now: number): boolean {\n  return Date.parse(lease.expiresAt) <= now;\n}\n\n/** Light-weight transaction wrapper. In-memory today; future DB backend\n *  swaps this with a real BEGIN/COMMIT/ROLLBACK. The contract is that\n *  the closure either runs to completion (commit) or throws (rollback -\n *  callers MUST not partially mutate before `commit()` runs). */\nexport function withTransaction<T>(commit: () => T): T {\n  return commit();\n}\n\n// -- Public API ------------------------------------------------------------\n\n/** Issue a new lease. Atomic: either the lease is persisted + indexed +\n *  audit event emitted, OR nothing changes and a structured rejection is\n *  returned. Wallet-scope check fires BEFORE the commit phase. */\nexport function issueLease(params: {\n  taskId: string;\n  agentId: string;\n  agentTag?: string;\n  scope: SecretRef[];\n  durationMs?: number;\n  /** Optional caller-supplied issuance timestamp (for testing/replay). */\n  now?: number;\n}): IssueLeaseResult {\n  const now = params.now ?? Date.now();\n  const duration = params.durationMs ?? MAX_LEASE_DURATION_MS;\n\n  // Argument validation (cheap rejections before any state work).\n  if (!params.taskId) return { ok: false, reason: 'task_id_missing' };\n  if (!params.agentId) return { ok: false, reason: 'agent_id_missing' };\n  if (!Array.isArray(params.scope) || params.scope.length === 0) {\n    return { ok: false, reason: 'scope_empty' };\n  }\n  if (duration < MIN_LEASE_DURATION_MS) {\n    return {\n      ok: false,\n      reason: 'expiry_in_past',\n      detail: `duration ${duration}ms < min ${MIN_LEASE_DURATION_MS}ms`,\n    };\n  }\n  if (duration > MAX_LEASE_DURATION_MS) {\n    return {\n      ok: false,\n      reason: 'expiry_too_far',\n      detail: `duration ${duration}ms > max ${MAX_LEASE_DURATION_MS}ms (24h)`,\n    };\n  }\n\n  // G.GOLD.016: wallet credentials are PERMANENTLY UNLEASABLE.\n  // This check fires before any persistence so a rejected lease leaves no\n  // state behind. We surface the FIRST offending ref so debugging is easy.\n  for (const ref of params.scope) {\n    if (isWalletRef(ref)) {\n      return {\n        ok: false,\n        reason: 'wallet_unleasable',\n        detail: `secretRef '${ref}' matches wallet pattern; wallets are identity, not sessions (G.GOLD.016)`,\n      };\n    }\n  }\n\n  // Duplicate-lease invariant: one active lease per (taskId, agentId).\n  // Re-issuance for the same pair requires the existing lease to be\n  // revoked first.\n  const indexKey = leaseIndexKey(params.taskId, params.agentId);\n  const existing = activeLeaseByTaskAgent.get(indexKey);\n  if (existing) {\n    const existingLease = leasesById.get(existing);\n    // If the existing lease has expired but wasn't swept yet, allow\n    // re-issuance and lazily expire it. Otherwise reject.\n    if (existingLease && existingLease.status === 'active' && !isExpired(existingLease, now)) {\n      return {\n        ok: false,\n        reason: 'duplicate_lease',\n        detail: `active lease ${existing} already exists for (${params.taskId}, ${params.agentId})`,\n      };\n    }\n    // Lazy expire - observed-but-not-swept lease drops out.\n    if (existingLease) {\n      lazyExpire(existingLease, now);\n    }\n  }\n\n  // Commit phase - staged so failure mid-stage rolls back.\n  const lease: VaultLease = {\n    leaseId: nextLeaseId(params.taskId),\n    taskId: params.taskId,\n    agentId: params.agentId,\n    agentTag: params.agentTag,\n    scope: [...params.scope], // defensive copy\n    issuedAt: new Date(now).toISOString(),\n    expiresAt: new Date(now + duration).toISOString(),\n    status: 'active',\n  };\n\n  return withTransaction(() => {\n    leasesById.set(lease.leaseId, lease);\n    activeLeaseByTaskAgent.set(indexKey, lease.leaseId);\n\n    // Audit. We piggyback on the existing audit-log module so all key/secret\n    // lifecycle events flow through one sink. Lease events use a distinct\n    // type via the metadata payload - the audit-log type taxonomy stays\n    // stable; the event-router downstream filters by `metadata.event`.\n    appendAuditEvent({\n      type: 'key_accessed', // closest existing taxonomy slot; metadata refines\n      timestamp: lease.issuedAt,\n      severity: 'info',\n      userId: lease.agentId,\n      publicKeyHash: hashPublicKey(`lease:${lease.leaseId}`),\n      accessedBy: lease.agentTag ?? lease.agentId,\n      metadata: {\n        event: 'vault_lease_issued',\n        leaseId: lease.leaseId,\n        taskId: lease.taskId,\n        scopeCount: lease.scope.length,\n        scope: lease.scope,\n        expiresAt: lease.expiresAt,\n        agentTag: lease.agentTag,\n      },\n    });\n\n    return { ok: true, lease } as IssueLeaseSuccess;\n  });\n}\n\n/** Look up a lease by id. Does NOT lazily expire - callers that care\n *  about freshness should check `isLeaseValid`. */\nexport function getLease(leaseId: string): VaultLease | undefined {\n  return leasesById.get(leaseId);\n}\n\n/** Find the active lease for (taskId, agentId), if any. */\nexport function findActiveLease(taskId: string, agentId: string): VaultLease | undefined {\n  const id = activeLeaseByTaskAgent.get(leaseIndexKey(taskId, agentId));\n  if (!id) return undefined;\n  return leasesById.get(id);\n}\n\n/** True iff the lease exists, is `active`, and has not expired. */\nexport function isLeaseValid(leaseId: string, now: number = Date.now()): boolean {\n  const lease = leasesById.get(leaseId);\n  if (!lease) return false;\n  if (lease.status !== 'active') return false;\n  if (isExpired(lease, now)) return false;\n  return true;\n}\n\n/** Decide whether `agentId` may resolve `secretRef` under `leaseId`. Does\n *  NOT return the secret value - that is a separate adapter layer. This\n *  function is the substrate enforcement point. */\nexport function resolveSecret(params: {\n  leaseId: string;\n  agentId: string;\n  secretRef: SecretRef;\n  now?: number;\n}): ResolveSecretResult {\n  const now = params.now ?? Date.now();\n  const lease = leasesById.get(params.leaseId);\n\n  if (!lease) {\n    return { ok: false, reason: 'lease_not_found', resolved: false };\n  }\n  if (lease.status === 'revoked') {\n    auditLeaseDenied(lease, params.secretRef, 'lease_revoked');\n    return { ok: false, reason: 'lease_revoked', secretRef: params.secretRef, resolved: false };\n  }\n  if (isExpired(lease, now)) {\n    // Don't mutate here - `expireLease` is the canonical state transition.\n    // But audit so the agent's failed attempt is recorded.\n    auditLeaseDenied(lease, params.secretRef, 'lease_expired');\n    return { ok: false, reason: 'lease_expired', secretRef: params.secretRef, resolved: false };\n  }\n  if (lease.agentId !== params.agentId) {\n    auditLeaseDenied(lease, params.secretRef, 'lease_agent_mismatch', params.agentId);\n    return {\n      ok: false,\n      reason: 'lease_agent_mismatch',\n      secretRef: params.secretRef,\n      resolved: false,\n    };\n  }\n  if (!lease.scope.includes(params.secretRef)) {\n    auditLeaseDenied(lease, params.secretRef, 'lease_scope_violation');\n    return {\n      ok: false,\n      reason: 'lease_scope_violation',\n      secretRef: params.secretRef,\n      resolved: false,\n    };\n  }\n  // Belt-and-suspenders: refuse to resolve a wallet ref even if (somehow)\n  // it ended up in scope. Defense in depth - the issuance-time check is\n  // the primary gate; this is the last-line check.\n  if (isWalletRef(params.secretRef)) {\n    auditLeaseDenied(lease, params.secretRef, 'wallet_unleasable');\n    return { ok: false, reason: 'wallet_unleasable', secretRef: params.secretRef, resolved: false };\n  }\n\n  // Audit the successful resolution. This is the access-log entry that\n  // makes \"who read what credential, for which task\" visible.\n  appendAuditEvent({\n    type: 'key_accessed',\n    timestamp: new Date(now).toISOString(),\n    severity: 'info',\n    userId: lease.agentId,\n    publicKeyHash: hashPublicKey(`lease:${lease.leaseId}`),\n    accessedBy: lease.agentTag ?? lease.agentId,\n    metadata: {\n      event: 'vault_lease_resolve_secret',\n      leaseId: lease.leaseId,\n      taskId: lease.taskId,\n      secretRef: params.secretRef,\n    },\n  });\n\n  return { ok: true, secretRef: params.secretRef, resolved: true };\n}\n\n/** Revoke an active lease. Idempotent on already-revoked leases - returns\n *  the existing record. Returns `lease_not_found` for unknown ids. */\nexport function revokeLease(params: {\n  leaseId: string;\n  reason: RevokeReason;\n  by: string; // agent id or 'system'\n  now?: number;\n}): VaultLease | { ok: false; reason: LeaseRejectReason } {\n  const now = params.now ?? Date.now();\n  const lease = leasesById.get(params.leaseId);\n  if (!lease) return { ok: false, reason: 'lease_not_found' };\n  if (lease.status === 'revoked') return lease; // idempotent\n\n  return withTransaction(() => {\n    lease.status = 'revoked';\n    lease.revoked = {\n      at: new Date(now).toISOString(),\n      reason: params.reason,\n      by: params.by,\n    };\n    activeLeaseByTaskAgent.delete(leaseIndexKey(lease.taskId, lease.agentId));\n\n    appendAuditEvent({\n      type: 'key_rotated', // closest existing slot for \"credential invalidated\"\n      timestamp: lease.revoked.at,\n      severity: params.reason === 'agent_compromise' ? 'error' : 'info',\n      userId: lease.agentId,\n      publicKeyHash: hashPublicKey(`lease:${lease.leaseId}`),\n      accessedBy: params.by,\n      metadata: {\n        event: 'vault_lease_revoked',\n        leaseId: lease.leaseId,\n        taskId: lease.taskId,\n        reason: params.reason,\n        scope: lease.scope,\n      },\n    });\n\n    return lease;\n  });\n}\n\n/** Bulk-revoke all active leases for a task. Used when a task is marked\n *  done or released. Returns the list of revoked leases. */\nexport function revokeLeasesForTask(\n  taskId: string,\n  reason: RevokeReason,\n  by: string\n): VaultLease[] {\n  const revoked: VaultLease[] = [];\n  for (const lease of leasesById.values()) {\n    if (lease.taskId === taskId && lease.status === 'active') {\n      const result = revokeLease({ leaseId: lease.leaseId, reason, by });\n      if ('leaseId' in result) revoked.push(result);\n    }\n  }\n  return revoked;\n}\n\n/** Bulk-revoke all active leases for an agent. Used when an agent's API key\n *  is rotated (security response) or when the agent is off-boarded.\n *  Returns the list of revoked leases. */\nexport function revokeLeasesForAgent(\n  agentId: string,\n  reason: RevokeReason,\n  by: string\n): VaultLease[] {\n  const revoked: VaultLease[] = [];\n  for (const lease of leasesById.values()) {\n    if (lease.agentId === agentId && lease.status === 'active') {\n      const result = revokeLease({ leaseId: lease.leaseId, reason, by });\n      if ('leaseId' in result) revoked.push(result);\n    }\n  }\n  return revoked;\n}\n\n/** Scan the registry and flip expired leases to `expired` status. Idempotent.\n *  Intended to be called by a periodic sweeper (e.g. once per minute). Each\n *  expired lease emits one audit event so compliance can correlate \"lease\n *  used to be active\" with \"no further reads possible\". */\nexport function sweepExpiredLeases(now: number = Date.now()): VaultLease[] {\n  const expired: VaultLease[] = [];\n  for (const lease of leasesById.values()) {\n    if (lease.status === 'active' && isExpired(lease, now)) {\n      lazyExpire(lease, now);\n      expired.push(lease);\n    }\n  }\n  return expired;\n}\n\nfunction lazyExpire(lease: VaultLease, now: number): void {\n  if (lease.status !== 'active') return;\n  lease.status = 'expired';\n  activeLeaseByTaskAgent.delete(leaseIndexKey(lease.taskId, lease.agentId));\n  appendAuditEvent({\n    type: 'key_rotated',\n    timestamp: new Date(now).toISOString(),\n    severity: 'info',\n    userId: lease.agentId,\n    publicKeyHash: hashPublicKey(`lease:${lease.leaseId}`),\n    accessedBy: 'system',\n    metadata: {\n      event: 'vault_lease_expired',\n      leaseId: lease.leaseId,\n      taskId: lease.taskId,\n      reason: 'expired_sweep',\n      expiredAt: lease.expiresAt,\n    },\n  });\n}\n\nfunction auditLeaseDenied(\n  lease: VaultLease,\n  secretRef: SecretRef,\n  reason: LeaseRejectReason,\n  attemptedBy?: string\n): void {\n  appendAuditEvent({\n    type: 'key_access_denied',\n    timestamp: new Date().toISOString(),\n    severity: 'warn',\n    userId: lease.agentId,\n    publicKeyHash: hashPublicKey(`lease:${lease.leaseId}`),\n    accessedBy: attemptedBy ?? lease.agentTag ?? lease.agentId,\n    metadata: {\n      event: 'vault_lease_denied',\n      leaseId: lease.leaseId,\n      taskId: lease.taskId,\n      secretRef,\n      reason,\n    },\n  });\n}\n\n/** List leases matching a filter. Returns a snapshot copy - callers cannot\n *  mutate the registry through this view. */\nexport function queryLeases(\n  filter: {\n    taskId?: string;\n    agentId?: string;\n    status?: VaultLease['status'];\n    includeExpired?: boolean;\n  } = {}\n): VaultLease[] {\n  const out: VaultLease[] = [];\n  const now = Date.now();\n  for (const lease of leasesById.values()) {\n    if (filter.taskId && lease.taskId !== filter.taskId) continue;\n    if (filter.agentId && lease.agentId !== filter.agentId) continue;\n    if (filter.status && lease.status !== filter.status) continue;\n    if (!filter.includeExpired && lease.status === 'active' && isExpired(lease, now)) continue;\n    out.push({ ...lease, scope: [...lease.scope] }); // defensive copy\n  }\n  return out;\n}\n\n// -- Phase 2: AsyncLocalStorage task context + resolveSecretWithLease -----\n//\n// Phase 1 shipped the registry but explicitly deferred wrapping the actual\n// `process.env.<KEY>` reads at the call site (W.GOLD.191 honest-gap rule).\n// Phase 2 closes that gap for the highest-risk-tier 5 reads:\n//   - holomesh-tools.ts: HOLOSCRIPT_API_KEY in moltbook crosspost + marketplace publish headers\n//   - hologram-mcp-tools.ts: HOLOMESH_API_KEY in publish_feed + send\n//   - absorb-provenance-tools.ts: HOLOMESH_API_KEY / HOLOSCRIPT_API_KEY in graph-context fetch\n//\n// Why these five: per W.075 / W.088 / W.129 the API-key tokens shadow real\n// auth paths and have caused renderer hangs (W.088 webview), broken team-id\n// resolution (W.129), and silent auth-failure cascades (W.075). They are\n// per-request hot reads, so AsyncLocalStorage carries the active taskId\n// through the call stack to the helper. Constructor / singleton-init reads\n// keep raw `process.env` for now — those are config-time, not request-time,\n// and threading taskId through the boot path would be Phase 3 scope creep.\n//\n// Wallet refs (HOLOMESH_WALLET_*, TREZOR, LEDGER_PRIVATE etc) are NEVER\n// wrapped here per G.GOLD.016: wallets are identity, not sessions, and\n// wrapping them would imply they are leasable. Raw `process.env` stays for\n// those, with the issuance-time + resolve-time UNLEASABLE_PATTERNS check as\n// the existing belt-and-suspenders.\n\n/** Ambient task context propagated through the request call stack via\n *  AsyncLocalStorage. Set by the runner / route handler at the request\n *  boundary; read by `resolveSecretWithLease` deep in the call stack. */\nexport interface TaskContext {\n  /** TeamTask.id this request is operating under. */\n  taskId: string;\n  /** Registered agent id (TeamTask.claimedBy) doing the work. */\n  agentId: string;\n  /** Surface-attribution tag captured at the request boundary, audit-only. */\n  agentTag?: string;\n}\n\n/** Module-private AsyncLocalStorage. Exported `runWithTaskContext` and\n *  `getCurrentTaskContext` are the only public entry points; the storage\n *  itself stays encapsulated so callers cannot hot-swap the context store. */\nconst taskContextStore = new AsyncLocalStorage<TaskContext>();\n\n/** Run `fn` with `ctx` available to every `getCurrentTaskContext` /\n *  `resolveSecretWithLease` call inside the call stack (including async\n *  branches and Promise continuations). Use this at the request boundary\n *  in the runner / route handler. */\nexport function runWithTaskContext<T>(ctx: TaskContext, fn: () => T): T {\n  return taskContextStore.run(ctx, fn);\n}\n\n/** Read the current task context, or undefined if no `runWithTaskContext`\n *  frame is active. Callers should treat undefined as \"no lease enforcement\n *  possible\" — see `resolveSecretWithLease` for the policy. */\nexport function getCurrentTaskContext(): TaskContext | undefined {\n  return taskContextStore.getStore();\n}\n\n/** Error thrown by `resolveSecretWithLease` when enforcement fails. The\n *  `reason` is one of the existing `LeaseRejectReason` strings plus the\n *  Phase-2-specific `no_task_context` (no AsyncLocalStorage frame active)\n *  and `no_active_lease` (context exists, but no lease was issued for it). */\nexport class VaultLeaseError extends Error {\n  public readonly reason:\n    | LeaseRejectReason\n    | 'no_task_context'\n    | 'no_active_lease'\n    | 'unleasable_pattern'\n    | 'env_value_missing';\n  public readonly secretRef: SecretRef;\n  constructor(reason: VaultLeaseError['reason'], secretRef: SecretRef, message?: string) {\n    super(message ?? `vault lease ${reason} for ${secretRef}`);\n    this.name = 'VaultLeaseError';\n    this.reason = reason;\n    this.secretRef = secretRef;\n  }\n}\n\n/** True iff lease enforcement is enabled at runtime. When false, the helper\n *  is transparent: it returns `process.env[bareKey]` without audit emission.\n *  This is the W.GOLD.191-compatible rollout: wrap the call sites NOW (so\n *  they are ready for enforcement), flip the flag to enable lease checks\n *  once Phase 3 wraps the rest. */\nexport function isVaultLeaseEnforcementEnabled(): boolean {\n  const flag = process.env.HOLOMESH_VAULT_LEASE_ENFORCE;\n  if (!flag) return false;\n  const v = flag.trim().toLowerCase();\n  return v === '1' || v === 'true' || v === 'yes' || v === 'on';\n}\n\n/** Extract the bare env-key from an `env:`-prefixed secretRef. Returns\n *  undefined for non-env refs (x402:, custodial:, gold:) — those are not\n *  resolvable through `process.env` and the helper rejects them. */\nfunction envKeyForRef(secretRef: SecretRef): string | undefined {\n  if (!secretRef.startsWith('env:')) return undefined;\n  const key = secretRef.slice(4);\n  if (!key) return undefined;\n  return key;\n}\n\n/** Phase 2 substrate: resolve a secret value at the call site, gated by the\n *  active task's lease.\n *\n *  Behaviour (enforcement ON, `HOLOMESH_VAULT_LEASE_ENFORCE=1`):\n *    1. Read the active task context. If none → throw `no_task_context`.\n *    2. Reject wallet refs unconditionally (G.GOLD.016 belt + suspenders).\n *    3. Look up the active lease for (taskId, agentId). If none → throw\n *       `no_active_lease`.\n *    4. Call `resolveSecret` to enforce expiry / revocation / scope.\n *    5. On success, return `process.env[bareKey]` (or undefined if unset\n *       — caller decides whether missing-env is an error).\n *    6. On failure, throw `VaultLeaseError` with the structured reason.\n *\n *  Behaviour (enforcement OFF, default):\n *    Returns `process.env[bareKey]` directly. Wallet refs still throw\n *    `unleasable_pattern` even with enforcement off, because wrapping a\n *    wallet ref through this helper is a programming error regardless of\n *    the flag. Non-env refs (x402, custodial, gold) throw — those resolve\n *    through dedicated adapters, not process.env.\n *\n *  Why this asymmetry: enforcement OFF is the migration window where call\n *  sites are wrapped but Phase 3 hasn't shipped yet. Wallet protection is\n *  not part of the migration window — it must hold from day 1.\n *\n *  Returns undefined when the env var itself is unset and enforcement is\n *  off; throws `env_value_missing` when enforcement is on AND the lease\n *  resolved successfully AND the env value is empty (because that is a\n *  config error, not a permission problem).\n */\nexport function resolveSecretWithLease(secretRef: SecretRef): string | undefined {\n  // Wallet protection runs FIRST, before context lookup, regardless of\n  // enforcement flag. Wrapping a wallet through this helper is a bug.\n  if (isWalletRef(secretRef)) {\n    throw new VaultLeaseError(\n      'unleasable_pattern',\n      secretRef,\n      `secretRef '${secretRef}' matches wallet pattern; wallets are identity, not sessions (G.GOLD.016). Read directly from process.env, not via lease helper.`\n    );\n  }\n\n  // Only env: refs are resolvable here. Other surfaces (x402, custodial,\n  // gold) have their own adapters; routing them through this helper would\n  // make the wrong promise.\n  const bareKey = envKeyForRef(secretRef);\n  if (bareKey === undefined) {\n    throw new VaultLeaseError(\n      'lease_scope_violation',\n      secretRef,\n      `secretRef '${secretRef}' is not an env-surface ref; only env:* refs resolve through resolveSecretWithLease`\n    );\n  }\n\n  const enforce = isVaultLeaseEnforcementEnabled();\n  if (!enforce) {\n    // Migration window: transparent passthrough. The call site is wrapped\n    // but the lease layer does not gate the read yet.\n    return process.env[bareKey];\n  }\n\n  // Enforcement ON: lease check is mandatory.\n  const ctx = getCurrentTaskContext();\n  if (!ctx) {\n    throw new VaultLeaseError(\n      'no_task_context',\n      secretRef,\n      `vault lease enforcement is ON but no task context is active for ref '${secretRef}'. Wrap the request entry point in runWithTaskContext({taskId, agentId}).`\n    );\n  }\n\n  const lease = findActiveLease(ctx.taskId, ctx.agentId);\n  if (!lease) {\n    throw new VaultLeaseError(\n      'no_active_lease',\n      secretRef,\n      `no active lease for (task=${ctx.taskId}, agent=${ctx.agentId}); issue a lease scoped to '${secretRef}' first`\n    );\n  }\n\n  const decision = resolveSecret({\n    leaseId: lease.leaseId,\n    agentId: ctx.agentId,\n    secretRef,\n  });\n  if (!decision.ok) {\n    throw new VaultLeaseError(\n      decision.reason ?? 'lease_scope_violation',\n      secretRef,\n      `lease ${lease.leaseId} denied secretRef '${secretRef}': ${decision.reason}`\n    );\n  }\n\n  const value = process.env[bareKey];\n  if (value === undefined || value === '') {\n    throw new VaultLeaseError(\n      'env_value_missing',\n      secretRef,\n      `lease resolved but process.env['${bareKey}'] is unset/empty; configuration error, not a permission issue`\n    );\n  }\n  return value;\n}\n\n// -- Test helpers ----------------------------------------------------------\n\n/** Reset the registry. Test-only - never call from production code. */\nexport function _resetVaultLeaseRegistryForTests(): void {\n  leasesById.clear();\n  activeLeaseByTaskAgent.clear();\n}\n\n/** Snapshot the active-lease index. Test-only. */\nexport function _getActiveLeaseIndexForTests(): ReadonlyMap<string, string> {\n  return new Map(activeLeaseByTaskAgent);\n}\n\n/** Recover audit events for a lease. Test-only - uses the audit-log query\n *  surface but is exposed here for ergonomic test assertions. */\nexport function _getAuditEventsForLeaseInTests(_leaseId: string): readonly AuditEvent[] {\n  // The audit-log buffer is module-private; we don't touch it from here.\n  // Tests that need audit assertions import audit-log directly.\n  return [];\n}\n","import type { Tool } from '@modelcontextprotocol/sdk/types.js';\nimport { handleCodebaseTool } from '@holoscript/absorb-service/mcp';\nimport { resolveSecretWithLease, VaultLeaseError } from './holomesh/identity/vault-lease-registry';\n\n/** Oldest knowledge entry newer than this → staleness `fresh` (vs `stale`). */\nconst STALE_AFTER_MS = 7 * 24 * 60 * 60 * 1000;\nconst DEFAULT_GRAPH_WORKSPACE_ID = 'studio-workspace';\n\n/**\n * Phase 2 wrapper for the orchestrator graph-context fetch. Original code\n * read `process.env.HOLOMESH_API_KEY || process.env.HOLOSCRIPT_API_KEY ||\n * ''` — preserve that fallback chain. Each ref resolves through the lease\n * helper independently so per-secret scope checks still hold under\n * enforcement (a lease scoped to only HOLOMESH_API_KEY will not silently\n * fall through to HOLOSCRIPT_API_KEY).\n */\nfunction readGraphContextApiKey(): string {\n  const tryRead = (ref: 'env:HOLOMESH_API_KEY' | 'env:HOLOSCRIPT_API_KEY'): string => {\n    try {\n      return resolveSecretWithLease(ref) ?? '';\n    } catch (err) {\n      if (err instanceof VaultLeaseError) return '';\n      throw err;\n    }\n  };\n  return tryRead('env:HOLOMESH_API_KEY') || tryRead('env:HOLOSCRIPT_API_KEY') || '';\n}\n\nexport const absorbProvenanceTools: Tool[] = [\n  {\n    name: 'absorb_provenance_answer',\n    description:\n      'Answer a codebase question using Absorb and attach deterministic provenance metadata (evidence hash, orchestrator graph snapshot id, optional CI commit id, staleness, citations + timestamp).',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        question: {\n          type: 'string',\n          description: 'Natural language question about the codebase.',\n        },\n        workspaceId: {\n          type: 'string',\n          description:\n            'Orchestrator workspace id for GraphRAG knowledge grounding. Defaults to the configured account workspace.',\n        },\n        includeRaw: {\n          type: 'boolean',\n          description: 'Include the raw absorb response payload for debugging.',\n        },\n      },\n      required: ['question'],\n    },\n  },\n];\n\nexport interface ProvenanceEnvelope {\n  source: 'absorb-service';\n  tool: string;\n  generatedAt: number;\n  evidenceHash: string;\n  citations: Array<{ file?: string; symbol?: string; snippet?: string }>;\n  /** Fingerprint of the orchestrator knowledge slice used for GraphRAG grounding. */\n  graphSnapshotId: string;\n  /** Git commit of the HoloScript deployment/repo when set in CI (VERCEL_GIT_COMMIT_SHA, GITHUB_SHA, GIT_COMMIT). */\n  graphCommitId?: string;\n  /** Whether grounding knowledge is still within the freshness window. */\n  staleness: 'fresh' | 'stale' | 'unknown';\n  /** ISO time of the newest knowledge entry in the orchestrator slice (if any). */\n  knowledgeAsOf?: string;\n}\n\nasync function provenanceHash(input: string): Promise<string> {\n  // RATCHET: upgraded from FNV1a (32-bit, non-cryptographic) to SHA-256.\n  // FNV1a is fast but collision-prone and not suitable for provenance chains.\n  const { createHash } = await import('crypto');\n  return 'absorb-' + createHash('sha256').update(input).digest('hex').slice(0, 16);\n}\n\nfunction canonical(value: unknown): unknown {\n  if (value === null || value === undefined) return value;\n  if (typeof value !== 'object') return value;\n  if (Array.isArray(value)) return value.map((v) => canonical(v));\n  const obj = value as Record<string, unknown>;\n  const out: Record<string, unknown> = {};\n  for (const k of Object.keys(obj).sort()) out[k] = canonical(obj[k]);\n  return out;\n}\n\nfunction toSafeString(value: unknown): string {\n  if (typeof value === 'string') return value;\n  if (value === null || value === undefined) return '';\n  try {\n    return JSON.stringify(value);\n  } catch {\n    return String(value);\n  }\n}\n\nfunction extractCitations(raw: unknown): ProvenanceEnvelope['citations'] {\n  if (!raw || typeof raw !== 'object') return [];\n  const obj = raw as Record<string, unknown>;\n\n  const direct = obj.citations;\n  if (Array.isArray(direct)) {\n    return direct.slice(0, 20).map((c) => {\n      if (!c || typeof c !== 'object') return {};\n      const co = c as Record<string, unknown>;\n      return {\n        file: typeof co.file === 'string' ? co.file : undefined,\n        symbol: typeof co.symbol === 'string' ? co.symbol : undefined,\n        snippet: typeof co.snippet === 'string' ? co.snippet : undefined,\n      };\n    });\n  }\n\n  const chunks = obj.results;\n  if (Array.isArray(chunks)) {\n    return chunks.slice(0, 20).map((r) => {\n      if (!r || typeof r !== 'object') return {};\n      const ro = r as Record<string, unknown>;\n      return {\n        file:\n          typeof ro.path === 'string' ? ro.path : typeof ro.file === 'string' ? ro.file : undefined,\n        symbol: typeof ro.symbol === 'string' ? ro.symbol : undefined,\n        snippet: typeof ro.snippet === 'string' ? ro.snippet : undefined,\n      };\n    });\n  }\n\n  return [];\n}\n\nfunction extractAnswer(raw: unknown): string {\n  if (!raw || typeof raw !== 'object') return toSafeString(raw);\n  const obj = raw as Record<string, unknown>;\n  if (typeof obj.answer === 'string') return obj.answer;\n  if (typeof obj.response === 'string') return obj.response;\n  if (typeof obj.summary === 'string') return obj.summary;\n  return toSafeString(raw);\n}\n\ninterface OrchestratorKnowledgeRow {\n  id?: string;\n  type?: string;\n  content?: string;\n  created_at?: string;\n  metadata?: { provenanceHash?: string; domain?: string };\n}\n\nfunction resolveGraphCommitId(): string | undefined {\n  const v =\n    process.env.VERCEL_GIT_COMMIT_SHA ||\n    process.env.GITHUB_SHA ||\n    process.env.GIT_COMMIT ||\n    process.env.COMMIT_SHA;\n  return typeof v === 'string' && v.length >= 7 ? v : undefined;\n}\n\nfunction resolveDefaultGraphWorkspaceId(): string {\n  return (\n    process.env.MCP_WORKSPACE_ID ||\n    process.env.HOLOSCRIPT_WORKSPACE_ID ||\n    process.env.HOLOMESH_WORKSPACE ||\n    DEFAULT_GRAPH_WORKSPACE_ID\n  );\n}\n\n/**\n * Queries the MCP orchestrator knowledge store (same path as absorb-scanner / framework KnowledgeStore remote mode).\n */\nexport async function fetchOrchestratorGraphContext(\n  search: string,\n  workspaceId?: string\n): Promise<{\n  graphSnapshotId: string;\n  staleness: 'fresh' | 'stale' | 'unknown';\n  knowledgeAsOf?: string;\n}> {\n  // Phase-2 wrapped read: graph-context fetch is a hot per-request path used\n  // by absorb_provenance_answer. Migration-window passthrough; lease-gated\n  // when HOLOMESH_VAULT_LEASE_ENFORCE is on.\n  const apiKey = readGraphContextApiKey();\n  if (!search.trim() || !apiKey) {\n    return {\n      graphSnapshotId: await provenanceHash(`${search}|no-orchestrator`),\n      staleness: 'unknown',\n    };\n  }\n\n  const baseUrl = (\n    process.env.MCP_ORCHESTRATOR_URL || 'https://mcp-orchestrator-production-45f9.up.railway.app'\n  ).replace(/\\/$/, '');\n  const ws = workspaceId || resolveDefaultGraphWorkspaceId();\n\n  try {\n    const res = await fetch(`${baseUrl}/knowledge/query`, {\n      method: 'POST',\n      headers: {\n        'Content-Type': 'application/json; charset=utf-8',\n        'x-mcp-api-key': apiKey,\n      },\n      body: JSON.stringify({\n        search: search.slice(0, 500),\n        limit: 20,\n        workspace_id: ws,\n      }),\n      signal: AbortSignal.timeout(12_000),\n    });\n\n    if (!res.ok) {\n      return {\n        graphSnapshotId: await provenanceHash(`${search}|query-${res.status}`),\n        staleness: 'unknown',\n      };\n    }\n\n    const data = (await res.json()) as {\n      results?: OrchestratorKnowledgeRow[];\n      entries?: OrchestratorKnowledgeRow[];\n    };\n    const rows = data.results || data.entries || [];\n    if (rows.length === 0) {\n      return {\n        graphSnapshotId: await provenanceHash(`${ws}|empty|${search}`),\n        staleness: 'unknown',\n      };\n    }\n\n    const now = Date.now();\n    const fingerprints = rows\n      .map((r) => {\n        const id = r.id || '';\n        const ph = r.metadata?.provenanceHash || '';\n        const created = r.created_at || '';\n        return `${id}|${ph}|${created}`;\n      })\n      .sort();\n    const graphSnapshotId = await provenanceHash(`${ws}|${fingerprints.join(';')}`);\n\n    const times = rows\n      .map((r) => {\n        const t = r.created_at ? Date.parse(r.created_at) : NaN;\n        return Number.isFinite(t) ? t : now;\n      })\n      .sort((a, b) => a - b);\n    const oldest = times[0]!;\n    const newest = times[times.length - 1]!;\n\n    const staleness: 'fresh' | 'stale' = now - oldest > STALE_AFTER_MS ? 'stale' : 'fresh';\n\n    return {\n      graphSnapshotId,\n      staleness,\n      knowledgeAsOf: new Date(newest).toISOString(),\n    };\n  } catch {\n    return {\n      graphSnapshotId: await provenanceHash(`${search}|orchestrator-error`),\n      staleness: 'unknown',\n    };\n  }\n}\n\nexport async function handleAbsorbProvenanceTool(\n  name: string,\n  args: Record<string, unknown>,\n  resolver?: (question: string) => Promise<unknown>\n): Promise<unknown | null> {\n  if (name !== 'absorb_provenance_answer') return null;\n\n  const question = typeof args.question === 'string' ? args.question.trim() : '';\n  if (!question) throw new Error('question is required');\n\n  const workspaceId = typeof args.workspaceId === 'string' ? args.workspaceId.trim() : undefined;\n\n  const raw = resolver\n    ? await resolver(question)\n    : await handleCodebaseTool('holo_ask_codebase', { question });\n\n  const citations = extractCitations(raw);\n  const answer = extractAnswer(raw);\n  const generatedAt = Date.now();\n\n  const orch = await fetchOrchestratorGraphContext(question, workspaceId);\n  const graphCommitId = resolveGraphCommitId();\n\n  const evidenceHash = await provenanceHash(\n    JSON.stringify(\n      canonical({\n        question,\n        answer,\n        citations,\n        graphSnapshotId: orch.graphSnapshotId,\n        staleness: orch.staleness,\n        knowledgeAsOf: orch.knowledgeAsOf,\n        graphCommitId: graphCommitId ?? null,\n        raw,\n      })\n    )\n  );\n\n  const envelope: ProvenanceEnvelope = {\n    source: 'absorb-service',\n    tool: 'holo_ask_codebase',\n    generatedAt,\n    evidenceHash,\n    citations,\n    graphSnapshotId: orch.graphSnapshotId,\n    graphCommitId,\n    staleness: orch.staleness,\n    knowledgeAsOf: orch.knowledgeAsOf,\n  };\n\n  return {\n    success: true,\n    question,\n    answer,\n    provenance: envelope,\n    ...(args.includeRaw === true ? { raw } : {}),\n  };\n}\n","import { existsSync } from 'node:fs';\n\nimport { chromium } from 'playwright';\n\nconst EXECUTABLE_ENV_KEYS = [\n  'PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH',\n  'CHROMIUM_BIN',\n  'CHROME_BIN',\n  'PUPPETEER_EXECUTABLE_PATH',\n] as const;\n\nconst SYSTEM_CHROMIUM_CANDIDATES = [\n  '/usr/bin/chromium',\n  '/usr/bin/chromium-browser',\n  '/usr/lib/chromium/chrome',\n  '/opt/google/chrome/chrome',\n  '/usr/bin/google-chrome',\n  '/usr/bin/google-chrome-stable',\n];\n\nexport interface ChromiumExecutableResolution {\n  executablePath?: string;\n  source: 'env' | 'system' | 'playwright' | 'missing';\n  sourceName?: string;\n  checkedPaths: string[];\n  missingEnvPaths: string[];\n  playwrightExecutablePath?: string;\n}\n\nfunction cleanPath(value: string | undefined): string | undefined {\n  const trimmed = value?.trim();\n  if (!trimmed) return undefined;\n  return trimmed.replace(/^[\"']|[\"']$/g, '');\n}\n\nfunction getPlaywrightExecutablePath(): string | undefined {\n  if (typeof chromium.executablePath !== 'function') return undefined;\n\n  try {\n    return cleanPath(chromium.executablePath());\n  } catch {\n    return undefined;\n  }\n}\n\nexport function resolveChromiumExecutable(): ChromiumExecutableResolution {\n  const checkedPaths: string[] = [];\n  const missingEnvPaths: string[] = [];\n\n  for (const key of EXECUTABLE_ENV_KEYS) {\n    const executablePath = cleanPath(process.env[key]);\n    if (!executablePath) continue;\n\n    checkedPaths.push(`${key}=${executablePath}`);\n    if (existsSync(executablePath)) {\n      return {\n        executablePath,\n        source: 'env',\n        sourceName: key,\n        checkedPaths,\n        missingEnvPaths,\n      };\n    }\n\n    missingEnvPaths.push(`${key}=${executablePath}`);\n  }\n\n  for (const executablePath of SYSTEM_CHROMIUM_CANDIDATES) {\n    checkedPaths.push(executablePath);\n    if (existsSync(executablePath)) {\n      return {\n        executablePath,\n        source: 'system',\n        sourceName: executablePath,\n        checkedPaths,\n        missingEnvPaths,\n      };\n    }\n  }\n\n  const playwrightExecutablePath = getPlaywrightExecutablePath();\n  if (playwrightExecutablePath) {\n    checkedPaths.push(`playwright=${playwrightExecutablePath}`);\n    if (existsSync(playwrightExecutablePath)) {\n      return {\n        source: 'playwright',\n        sourceName: playwrightExecutablePath,\n        checkedPaths,\n        missingEnvPaths,\n        playwrightExecutablePath,\n      };\n    }\n  }\n\n  return {\n    source: 'missing',\n    checkedPaths,\n    missingEnvPaths,\n    playwrightExecutablePath,\n  };\n}\n\nexport function resolveChromiumExecutablePath(): string | undefined {\n  return resolveChromiumExecutable().executablePath;\n}\n\nexport function isMissingChromiumExecutableError(error: unknown): boolean {\n  const message = error instanceof Error ? error.message : String(error);\n  return /Executable doesn't exist|browser executable|playwright install|chromium_headless_shell|chrome-headless-shell/i.test(\n    message\n  );\n}\n\nexport function createChromiumLaunchError(\n  error: unknown,\n  resolution: ChromiumExecutableResolution\n): Error {\n  const original = error instanceof Error ? error.message : String(error);\n  const checked = resolution.checkedPaths.length\n    ? ` Checked paths: ${resolution.checkedPaths.join(', ')}.`\n    : '';\n  const missingEnv = resolution.missingEnvPaths.length\n    ? ` Invalid executable env values: ${resolution.missingEnvPaths.join(', ')}.`\n    : '';\n\n  return new Error(\n    `Playwright Chromium executable is unavailable for HoloScript browser tools. ` +\n      `Install system Chromium and set PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH, ` +\n      `or run \"pnpm exec playwright install chromium\" during deployment. ` +\n      `Original error: ${original}.${missingEnv}${checked}`\n  );\n}\n","/**\n * Browser Pool Manager for HoloScript MCP Server\n * Manages lifecycle of browser sessions for AI agent control\n */\n\nimport { chromium, type Browser, type Page, type BrowserContext } from 'playwright';\nimport type { BrowserSession, BrowserSessionConfig, BrowserPoolStats } from './types.js';\nimport {\n  createChromiumLaunchError,\n  isMissingChromiumExecutableError,\n  resolveChromiumExecutable,\n} from './chromium-executable.js';\n\n/**\n * Default browser configuration\n */\nconst DEFAULT_CONFIG: Required<BrowserSessionConfig> = {\n  width: 1280,\n  height: 720,\n  headless: false, // Show browser for debugging\n  deviceScaleFactor: 1,\n  timeout: 30000, // 30 seconds\n};\n\n/**\n * Maximum session idle time before automatic cleanup (5 minutes)\n */\nconst MAX_IDLE_TIME = 5 * 60 * 1000;\n\n/**\n * Manages a pool of browser sessions for HoloScript preview\n */\nexport class BrowserPool {\n  private sessions: Map<string, BrowserSession> = new Map();\n  private sessionCounter = 0;\n  private stats = {\n    totalCreated: 0,\n    totalDestroyed: 0,\n    lifetimes: [] as number[],\n  };\n\n  /**\n   * Create a new browser session\n   */\n  async createSession(config: BrowserSessionConfig = {}): Promise<BrowserSession> {\n    const mergedConfig = { ...DEFAULT_CONFIG, ...config };\n    const sessionId = `holoscript-${Date.now()}-${++this.sessionCounter}`;\n\n    // Use system Chromium when available (Railway/Docker/CI)\n    const executableResolution = resolveChromiumExecutable();\n    const isServer =\n      !!executableResolution.executablePath || process.env.CI === 'true' || !process.env.DISPLAY;\n    const launchOptions: Parameters<typeof chromium.launch>[0] = {\n      headless: isServer ? true : mergedConfig.headless,\n      args: [\n        '--enable-webgl',\n        '--enable-accelerated-2d-canvas',\n        '--enable-features=WebXR',\n        '--no-sandbox', // Required for some CI environments\n        '--allow-file-access-from-files', // Allow loading local files via XHR\n        '--disable-gpu-sandbox',\n        '--disable-setuid-sandbox',\n        ...(isServer ? ['--disable-dev-shm-usage', '--single-process'] : []),\n      ],\n    };\n    if (executableResolution.executablePath) {\n      launchOptions.executablePath = executableResolution.executablePath;\n    }\n\n    let browser: Browser;\n    try {\n      browser = await chromium.launch(launchOptions);\n    } catch (error) {\n      if (isMissingChromiumExecutableError(error) || executableResolution.source === 'missing') {\n        throw createChromiumLaunchError(error, executableResolution);\n      }\n      throw error;\n    }\n\n    // Create context with viewport\n    const context = await browser.newContext({\n      viewport: {\n        width: mergedConfig.width,\n        height: mergedConfig.height,\n      },\n      deviceScaleFactor: mergedConfig.deviceScaleFactor,\n      permissions: ['clipboard-read', 'clipboard-write'], // For copying scene data\n    });\n\n    // Set default timeout\n    context.setDefaultTimeout(mergedConfig.timeout);\n\n    // Create page\n    const page = await context.newPage();\n\n    // Enable error logging\n    page.on('pageerror', (error) => {\n      console.error(`[Browser Error ${sessionId}]:`, error.message);\n    });\n\n    const session: BrowserSession = {\n      id: sessionId,\n      browser,\n      context,\n      page,\n      config: mergedConfig,\n      createdAt: Date.now(),\n      lastActivity: Date.now(),\n    };\n\n    this.sessions.set(sessionId, session);\n    this.stats.totalCreated++;\n\n    return session;\n  }\n\n  /**\n   * Get an existing session by ID\n   */\n  getSession(sessionId: string): BrowserSession | undefined {\n    const session = this.sessions.get(sessionId);\n    if (session) {\n      session.lastActivity = Date.now();\n    }\n    return session;\n  }\n\n  /**\n   * Destroy a session and cleanup resources\n   */\n  async destroySession(sessionId: string): Promise<boolean> {\n    const session = this.sessions.get(sessionId);\n    if (!session) {\n      return false;\n    }\n\n    try {\n      await session.context.close();\n      await session.browser.close();\n\n      const lifetime = Date.now() - session.createdAt;\n      this.stats.lifetimes.push(lifetime);\n      this.stats.totalDestroyed++;\n\n      this.sessions.delete(sessionId);\n      return true;\n    } catch (error) {\n      console.error(`Error destroying session ${sessionId}:`, error);\n      return false;\n    }\n  }\n\n  /**\n   * Cleanup idle sessions\n   */\n  async cleanupIdleSessions(): Promise<number> {\n    const now = Date.now();\n    const toDestroy: string[] = [];\n\n    for (const [sessionId, session] of this.sessions.entries()) {\n      if (now - session.lastActivity > MAX_IDLE_TIME) {\n        toDestroy.push(sessionId);\n      }\n    }\n\n    for (const sessionId of toDestroy) {\n      await this.destroySession(sessionId);\n    }\n\n    return toDestroy.length;\n  }\n\n  /**\n   * Destroy all sessions\n   */\n  async destroyAll(): Promise<void> {\n    const sessionIds = Array.from(this.sessions.keys());\n    for (const sessionId of sessionIds) {\n      await this.destroySession(sessionId);\n    }\n  }\n\n  /**\n   * Get pool statistics\n   */\n  getStats(): BrowserPoolStats {\n    const activeSessions = this.sessions.size;\n    const idleSessions = Array.from(this.sessions.values()).filter(\n      (session) => Date.now() - session.lastActivity > 60000 // 1 minute\n    ).length;\n\n    const avgLifetime =\n      this.stats.lifetimes.length > 0\n        ? this.stats.lifetimes.reduce((a, b) => a + b, 0) / this.stats.lifetimes.length\n        : 0;\n\n    return {\n      activeSessions,\n      idleSessions,\n      totalCreated: this.stats.totalCreated,\n      totalDestroyed: this.stats.totalDestroyed,\n      avgLifetime,\n    };\n  }\n\n  /**\n   * Start automatic cleanup timer\n   */\n  startCleanupTimer(intervalMs: number = 60000): NodeJS.Timeout {\n    return setInterval(() => {\n      this.cleanupIdleSessions();\n    }, intervalMs);\n  }\n}\n\n/**\n * Global browser pool instance\n */\nexport const browserPool = new BrowserPool();\n","/**\n * Fara-7B browser dispatcher — Playwright execution layer.\n *\n * Pairs with FaraHandsTrait (packages/core/src/traits/FaraHandsTrait.ts):\n *   - FaraHandsTrait.think() → decides the next action (AI reasoning, no browser)\n *   - fara-dispatcher.ts    → executes that action via Playwright + builds receipts\n *\n * Entry point for agents and MCP tools: faraRun().\n *\n * Safety model:\n *   - Domain allow/block list evaluated before each navigate/visit_url step.\n *   - maxSteps hard cap prevents runaway loops.\n *   - Every step produces a BrowserAction with coordinateWitness for audit.\n *   - Full FaraRunReceipt (BrowserAbsorptionReceipt-compatible) returned on completion.\n */\n\nimport { createHash } from 'node:crypto';\nimport { z } from 'zod';\nimport { browserPool } from './BrowserPool.js';\nimport { faraThink, FARA_DEFAULTS } from '../../../core/src/traits/FaraHandsTrait.js';\nimport type { FaraStepResult, FaraAction, FaraHandsConfig } from '../../../core/src/traits/FaraHandsTrait.js';\n\n// ── Receipt types (BrowserAbsorptionReceipt-compatible) ──\n\nexport interface FaraBrowserAction {\n  step: number;\n  kind: string;\n  timestamp: string;\n  coordinateWitness?: [number, number];\n  value?: string;\n  url?: string;\n  screenshotBeforeHash?: string;\n  screenshotAfterHash?: string;\n  durationMs?: number;\n  thought: string;\n}\n\nexport interface FaraRunPolicy {\n  allowedDomains: string[];\n  blockedDomains: string[];\n  maxSteps: number;\n  maxDurationMs: number;\n  headless: boolean;\n}\n\nexport interface FaraRunReceipt {\n  id: string;\n  sessionId: string;\n  goal: string;\n  startedAt: string;\n  endedAt: string;\n  policy: FaraRunPolicy;\n  actions: FaraBrowserAction[];\n  outcome: 'success' | 'failure' | 'timeout' | 'blocked_by_policy' | 'max_steps';\n  memorized: string[];\n  summary?: string;\n  hash: string;\n  hashAlgorithm: 'sha256';\n  agentTier: 'fara';\n}\n\n// ── Policy helpers ──\n\nfunction isDomainAllowed(url: string, policy: FaraRunPolicy): boolean {\n  let hostname: string;\n  try {\n    hostname = new URL(url).hostname;\n  } catch {\n    return false;\n  }\n  if (policy.blockedDomains.some((d) => hostname === d || hostname.endsWith(`.${d}`))) {\n    return false;\n  }\n  if (policy.allowedDomains.length > 0) {\n    return policy.allowedDomains.some((d) => hostname === d || hostname.endsWith(`.${d}`));\n  }\n  return true;\n}\n\nfunction sha256(input: string): string {\n  return createHash('sha256').update(input).digest('hex');\n}\n\n// ── Action execution ──\n\nasync function executeFaraAction(\n  sessionId: string,\n  action: FaraAction,\n  policy: FaraRunPolicy\n): Promise<{ blocked: boolean; reason?: string }> {\n  const session = browserPool.getSession(sessionId);\n  if (!session) throw new Error(`Browser session not found: ${sessionId}`);\n  const page = session.page;\n\n  switch (action.action) {\n    case 'left_click':\n      if (action.coordinate) {\n        await page.mouse.click(action.coordinate[0], action.coordinate[1]);\n      }\n      break;\n\n    case 'mouse_move':\n      if (action.coordinate) {\n        await page.mouse.move(action.coordinate[0], action.coordinate[1]);\n      }\n      break;\n\n    case 'type':\n      if (action.text) await page.keyboard.type(action.text);\n      break;\n\n    case 'key':\n      if (action.key) await page.keyboard.press(action.key);\n      break;\n\n    case 'scroll': {\n      const dx =\n        action.direction === 'left'\n          ? -(action.amount ?? 300)\n          : action.direction === 'right'\n            ? (action.amount ?? 300)\n            : 0;\n      const dy =\n        action.direction === 'up'\n          ? -(action.amount ?? 300)\n          : action.direction === 'down'\n            ? (action.amount ?? 300)\n            : 0;\n      if (action.coordinate) {\n        await page.mouse.move(action.coordinate[0], action.coordinate[1]);\n      }\n      await page.mouse.wheel(dx, dy);\n      break;\n    }\n\n    case 'visit_url':\n      if (action.url) {\n        if (!isDomainAllowed(action.url, policy)) {\n          return { blocked: true, reason: `Domain blocked by policy: ${action.url}` };\n        }\n        await page.goto(action.url, { waitUntil: 'domcontentloaded' });\n      }\n      break;\n\n    case 'web_search': {\n      const searchUrl = `https://www.google.com/search?q=${encodeURIComponent(action.query ?? '')}`;\n      if (!isDomainAllowed(searchUrl, policy)) {\n        return { blocked: true, reason: 'Google search blocked by policy' };\n      }\n      await page.goto(searchUrl, { waitUntil: 'domcontentloaded' });\n      break;\n    }\n\n    case 'history_back':\n      await page.goBack();\n      break;\n\n    case 'wait':\n      await new Promise((res) => setTimeout(res, action.duration ?? 1000));\n      break;\n\n    case 'pause_and_memorize_fact':\n    case 'terminate':\n      // handled at loop level\n      break;\n  }\n\n  return { blocked: false };\n}\n\n// ── Main loop ──\n\nexport interface FaraRunOptions {\n  sessionId: string;\n  goal: string;\n  policy?: Partial<FaraRunPolicy>;\n  faraConfig?: Partial<FaraHandsConfig>;\n}\n\nconst DEFAULT_POLICY: FaraRunPolicy = {\n  allowedDomains: [],\n  blockedDomains: [],\n  maxSteps: 50,\n  maxDurationMs: 300_000,\n  headless: true,\n};\n\nexport async function faraRun(opts: FaraRunOptions): Promise<FaraRunReceipt> {\n  const policy: FaraRunPolicy = { ...DEFAULT_POLICY, ...opts.policy };\n  const config: FaraHandsConfig = { ...FARA_DEFAULTS, ...opts.faraConfig };\n\n  const startedAt = new Date().toISOString();\n  const startMs = Date.now();\n  const receiptId = `fara_${opts.sessionId}_${Date.now()}`;\n\n  const actions: FaraBrowserAction[] = [];\n  const history: FaraStepResult[] = [];\n  const memorized: string[] = [];\n\n  let outcome: FaraRunReceipt['outcome'] = 'failure';\n\n  const session = browserPool.getSession(opts.sessionId);\n  if (!session) throw new Error(`Browser session not found: ${opts.sessionId}`);\n\n  for (let step = 0; step < policy.maxSteps; step++) {\n    if (Date.now() - startMs > policy.maxDurationMs) {\n      outcome = 'timeout';\n      break;\n    }\n\n    // Screenshot before action\n    const beforeBuf = await session.page.screenshot({ type: 'png' });\n    const beforeB64 = beforeBuf.toString('base64');\n    const beforeHash = sha256(beforeB64);\n\n    // Fara reasoning\n    const stepResult = await faraThink(beforeB64, opts.goal, history, config);\n    history.push(stepResult);\n\n    const { action } = stepResult;\n    const stepTs = new Date().toISOString();\n    const t0 = Date.now();\n\n    // Handle terminal actions before execution\n    if (action.action === 'terminate') {\n      outcome = 'success';\n      actions.push({\n        step,\n        kind: 'terminate',\n        timestamp: stepTs,\n        thought: stepResult.thought,\n        screenshotBeforeHash: beforeHash,\n      });\n      break;\n    }\n\n    if (action.action === 'pause_and_memorize_fact' && action.fact) {\n      memorized.push(action.fact);\n      actions.push({\n        step,\n        kind: 'pause_and_memorize_fact',\n        timestamp: stepTs,\n        thought: stepResult.thought,\n        value: action.fact,\n        screenshotBeforeHash: beforeHash,\n      });\n      continue;\n    }\n\n    // Execute browser action\n    const { blocked, reason } = await executeFaraAction(opts.sessionId, action, policy);\n    if (blocked) {\n      outcome = 'blocked_by_policy';\n      actions.push({\n        step,\n        kind: action.action,\n        timestamp: stepTs,\n        thought: stepResult.thought,\n        screenshotBeforeHash: beforeHash,\n        value: reason,\n        durationMs: Date.now() - t0,\n      });\n      break;\n    }\n\n    // Screenshot after action\n    const afterBuf = await session.page.screenshot({ type: 'png' });\n    const afterB64 = afterBuf.toString('base64');\n    const afterHash = sha256(afterB64);\n\n    actions.push({\n      step,\n      kind: action.action,\n      timestamp: stepTs,\n      thought: stepResult.thought,\n      coordinateWitness: action.coordinate,\n      value: action.text ?? action.key ?? action.url ?? action.query,\n      url: action.url ?? (action.action === 'web_search' ? `google:${action.query}` : undefined),\n      screenshotBeforeHash: beforeHash,\n      screenshotAfterHash: afterHash,\n      durationMs: Date.now() - t0,\n    });\n\n    if (step === policy.maxSteps - 1) {\n      outcome = 'max_steps';\n    }\n  }\n\n  const endedAt = new Date().toISOString();\n\n  const receiptBody = `fara:${opts.sessionId}:${opts.goal}:${startedAt}:${actions.length}:${outcome}`;\n  const hash = sha256(receiptBody);\n\n  return {\n    id: receiptId,\n    sessionId: opts.sessionId,\n    goal: opts.goal,\n    startedAt,\n    endedAt,\n    policy,\n    actions,\n    outcome,\n    memorized,\n    summary: `Fara-7B: \"${opts.goal}\" — ${actions.length} steps, outcome=${outcome}`,\n    hash,\n    hashAlgorithm: 'sha256',\n    agentTier: 'fara',\n  };\n}\n\n// ── Zod schema for MCP tool ──\n\nexport const FaraRunSchema = z.object({\n  sessionId: z\n    .string()\n    .describe('Playwright browser session ID (from browser_launch)'),\n  goal: z\n    .string()\n    .describe('Natural-language goal for Fara-7B to accomplish in the browser'),\n  maxSteps: z\n    .number()\n    .int()\n    .min(1)\n    .max(200)\n    .optional()\n    .default(50)\n    .describe('Hard step cap before termination (default 50)'),\n  endpoint: z\n    .string()\n    .optional()\n    .default('http://localhost:11434/api/chat')\n    .describe('Ollama chat endpoint for Fara-7B'),\n  model: z\n    .string()\n    .optional()\n    .default('hf.co/bartowski/microsoft_Fara-7B-GGUF:Q4_K_M')\n    .describe('Fara model tag in Ollama'),\n  allowedDomains: z\n    .array(z.string())\n    .optional()\n    .default([])\n    .describe('Domains Fara may navigate to (empty = all permitted)'),\n  blockedDomains: z\n    .array(z.string())\n    .optional()\n    .default([])\n    .describe('Domains Fara must never navigate to (overrides allowed)'),\n  maxDurationMs: z\n    .number()\n    .optional()\n    .default(300_000)\n    .describe('Session time cap in milliseconds (default 5 min)'),\n});\n","/**\n * Browser Control MCP Tools for HoloScript\n * Enables AI agents to launch, control, and interact with HoloScript browser preview\n */\n\nimport { z } from 'zod';\nimport path from 'path';\nimport { browserPool } from './BrowserPool.js';\nimport type { ScreenshotOptions, BrowserExecuteResult } from './types.js';\nimport { faraRun, FaraRunSchema } from './fara-dispatcher.js';\n\n/**\n * Schema for browser_launch tool\n */\nexport const BrowserLaunchSchema = z.object({\n  holoscriptFile: z.string().describe('Path to HoloScript file to preview'),\n  width: z.number().optional().default(1280).describe('Browser viewport width'),\n  height: z.number().optional().default(720).describe('Browser viewport height'),\n  headless: z.boolean().optional().default(false).describe('Run in headless mode'),\n});\n\n/**\n * Schema for browser_execute tool\n */\nexport const BrowserExecuteSchema = z.object({\n  sessionId: z.string().describe('Browser session ID from browser_launch'),\n  script: z.string().describe('JavaScript code to execute in browser context'),\n  captureConsole: z.boolean().optional().default(true).describe('Capture console logs'),\n});\n\n/**\n * Schema for browser_screenshot tool\n */\nexport const BrowserScreenshotSchema = z.object({\n  sessionId: z.string().describe('Browser session ID from browser_launch'),\n  outputPath: z.string().optional().describe('Optional output path for screenshot'),\n  type: z.enum(['png', 'jpeg']).optional().default('png').describe('Screenshot format'),\n  quality: z.number().min(0).max(100).optional().default(90).describe('JPEG quality (0-100)'),\n  fullPage: z.boolean().optional().default(false).describe('Capture full page'),\n});\n\n/**\n * Launch HoloScript preview in browser\n *\n * This tool opens a browser window showing the HoloScript file in the 3D preview.\n * Returns a session ID that can be used with other browser tools.\n */\nexport async function browserLaunch(args: z.infer<typeof BrowserLaunchSchema>) {\n  try {\n    // Create browser session\n    const session = await browserPool.createSession({\n      width: args.width,\n      height: args.height,\n      headless: args.headless,\n    });\n\n    // Determine the preview URL\n    // Resolve relative to HoloScript root (up 2 dirs from packages/mcp-server)\n    const previewUrl = args.holoscriptFile.startsWith('http')\n      ? args.holoscriptFile\n      : `file://${path.resolve(__dirname, '../../../../examples/browser-preview.html')}?file=${encodeURIComponent(args.holoscriptFile)}`;\n\n    // Navigate to preview\n    await session.page.goto(previewUrl, {\n      waitUntil: args.holoscriptFile.startsWith('http') ? 'domcontentloaded' : 'networkidle',\n    });\n\n    // Wait for Three.js scene to initialize\n    if (!args.holoscriptFile.startsWith('http')) {\n      await session.page.waitForFunction(\n        () => {\n          return (\n            (window as unknown as { holoscriptRenderer?: { initialized: boolean } })\n              .holoscriptRenderer?.initialized === true\n          );\n        },\n        { timeout: 10000 }\n      );\n    }\n\n    return {\n      success: true,\n      sessionId: session.id,\n      url: previewUrl,\n      viewport: {\n        width: args.width,\n        height: args.height,\n      },\n      message: `HoloScript preview launched: ${args.holoscriptFile}`,\n    };\n  } catch (error) {\n    throw error;\n  }\n}\n\n/**\n * Execute JavaScript in the browser context\n *\n * This tool allows agents to run arbitrary JavaScript in the HoloScript preview\n * to inspect scene state, validate traits, or interact with the 3D environment.\n */\nexport async function browserExecute(args: z.infer<typeof BrowserExecuteSchema>) {\n  try {\n    const session = browserPool.getSession(args.sessionId);\n    if (!session) {\n      throw new Error(`Session not found: ${args.sessionId}`);\n    }\n\n    const logs: string[] = [];\n\n    // Capture console if requested\n    if (args.captureConsole) {\n      session.page.on('console', (msg) => logs.push(msg.text()));\n    }\n\n    // Execute script\n    const result = await session.page.evaluate(args.script);\n\n    return {\n      success: true,\n      result,\n      logs: args.captureConsole ? logs : undefined,\n    };\n  } catch (error) {\n    const executeResult: BrowserExecuteResult = {\n      success: false,\n      error: error instanceof Error ? error.message : String(error),\n    };\n\n    return {\n      content: [\n        {\n          type: 'text',\n          text: JSON.stringify(executeResult, null, 2),\n        },\n      ],\n      isError: true,\n    };\n  }\n}\n\n/**\n * Take a screenshot of the HoloScript preview\n *\n * This tool captures the current state of the 3D preview as an image.\n * Useful for visual regression testing and debugging.\n */\nexport async function browserScreenshot(args: z.infer<typeof BrowserScreenshotSchema>) {\n  try {\n    const session = browserPool.getSession(args.sessionId);\n    if (!session) {\n      throw new Error(`Session not found: ${args.sessionId}`);\n    }\n\n    const screenshotOptions: ScreenshotOptions = {\n      type: args.type,\n      quality: args.type === 'jpeg' ? args.quality : undefined,\n      fullPage: args.fullPage,\n    };\n\n    // Take screenshot\n    const screenshot = await session.page.screenshot({\n      ...screenshotOptions,\n      path: args.outputPath,\n    });\n\n    // Convert to base64 if no output path\n    const base64 = args.outputPath ? undefined : screenshot.toString('base64');\n\n    return {\n      success: true,\n      sessionId: args.sessionId,\n      outputPath: args.outputPath,\n      format: args.type,\n      size: screenshot.length,\n      base64: base64 ? `data:image/${args.type};base64,${base64}` : undefined,\n    };\n  } catch (error) {\n    throw error;\n  }\n}\n\n/**\n * Run Fara-7B visual computer-use agent in an existing browser session.\n *\n * Fara-7B (https://github.com/microsoft/fara) is a 7B-parameter, MIT-licensed,\n * on-device computer-use agent. It observes the browser via screenshots and\n * predicts mouse/keyboard actions to complete a natural-language goal.\n * All screenshots stay on-device — pixel sovereignty guaranteed.\n *\n * Requires Ollama running locally with the Fara GGUF model:\n *   ollama pull hf.co/bartowski/microsoft_Fara-7B-GGUF:Q4_K_M\n */\nexport async function holoshellFaraStep(args: z.infer<typeof FaraRunSchema>) {\n  const receipt = await faraRun({\n    sessionId: args.sessionId,\n    goal: args.goal,\n    policy: {\n      allowedDomains: args.allowedDomains,\n      blockedDomains: args.blockedDomains,\n      maxSteps: args.maxSteps,\n      maxDurationMs: args.maxDurationMs,\n    },\n    faraConfig: {\n      endpoint: args.endpoint,\n      model: args.model,\n    },\n  });\n\n  return receipt;\n}\n\n/**\n * Export MCP tool definitions\n */\nexport const browserTools = {\n  browser_launch: {\n    description: 'Launch HoloScript file in browser preview with AI control',\n    inputSchema: BrowserLaunchSchema,\n    handler: browserLaunch,\n  },\n  browser_execute: {\n    description: 'Execute JavaScript in browser to inspect or control HoloScript scene',\n    inputSchema: BrowserExecuteSchema,\n    handler: browserExecute,\n  },\n  browser_screenshot: {\n    description: 'Take screenshot of HoloScript preview for visual validation',\n    inputSchema: BrowserScreenshotSchema,\n    handler: browserScreenshot,\n  },\n  holoshell_fara_step: {\n    description:\n      'Run Fara-7B visual computer-use agent to accomplish a browser goal. Fara observes the ' +\n      'live browser via screenshots and executes mouse/keyboard actions until done. ' +\n      'Pixel-sovereign: all processing stays on-device via local Ollama.',\n    inputSchema: FaraRunSchema,\n    handler: holoshellFaraStep,\n  },\n};\n","import type { Tool } from '@modelcontextprotocol/sdk/types.js';\n\n// ---------------------------------------------------------------------------\n// Tool health probe: status values\n// ---------------------------------------------------------------------------\n\n/** Wiring status for a single tool category returned by get_tool_health. */\nexport type ToolWiringStatus = 'live' | 'scaffold' | 'stub';\n\nexport interface ToolHealthEntry {\n  /** Canonical tool name as registered in the MCP schema. */\n  tool: string;\n  /** Category inferred from tool name. */\n  category: string;\n  /**\n   * live   — handler path is reachable and a minimal no-network canary probe\n   *          returned a non-null result with the expected shape.\n   * scaffold — handler is reachable but the underlying implementation is a\n   *            stub (returns a fixed/empty payload, throws \"not implemented\",\n   *            or canary check returned null).\n   * stub   — handler case exists in dispatch but throws unconditionally, or\n   *          the tool name is not wired in the handler at all (dispatch returns\n   *          null for every call).\n   */\n  status: ToolWiringStatus;\n  /** ISO timestamp of the probe. */\n  last_checked: string;\n  /** Human-readable reason for the assigned status. */\n  reason: string;\n}\n\nexport interface ToolHealthReport {\n  checked_at: string;\n  total: number;\n  live: number;\n  scaffold: number;\n  stub: number;\n  tools: ToolHealthEntry[];\n}\n\nexport const toolingDiscoveryTools: Tool[] = [\n  {\n    name: 'get_tool_manifest',\n    description:\n      'Return a machine-readable manifest of all available tools including categories, tags, input schemas, and output schemas.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        includeInputSchema: {\n          type: 'boolean',\n          description: 'Include each tool input schema in the manifest response. Defaults to true.',\n        },\n        includeOutputSchema: {\n          type: 'boolean',\n          description: 'Include inferred output schema for each tool. Defaults to true.',\n        },\n        includeExamples: {\n          type: 'boolean',\n          description: 'Include minimal usage examples for selected tools. Defaults to false.',\n        },\n      },\n    },\n  },\n  {\n    name: 'suggest_tools_for_goal',\n    description:\n      'Given a natural language goal, suggest an ordered tool plan with rationale and optional bundles (parse+validate+compile, etc.).',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        goal: {\n          type: 'string',\n          description: 'Natural language goal (e.g., \"compile this scene and verify it\").',\n        },\n        maxSuggestions: {\n          type: 'number',\n          description: 'Maximum number of suggested tools to return. Defaults to 8.',\n        },\n      },\n      required: ['goal'],\n    },\n  },\n  {\n    name: 'batch_tool_call',\n    description:\n      'Execute multiple tool calls in one request and return a structured array of per-tool results (success/error).',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        calls: {\n          type: 'array',\n          description: 'Ordered list of tool calls to execute.',\n          items: {\n            type: 'object',\n            properties: {\n              name: { type: 'string', description: 'Tool name to invoke.' },\n              args: { type: 'object', description: 'Arguments for that tool.' },\n            },\n            required: ['name'],\n          },\n        },\n        stopOnError: {\n          type: 'boolean',\n          description:\n            'If true, stop executing remaining calls after first error. Defaults to false.',\n        },\n      },\n      required: ['calls'],\n    },\n  },\n  {\n    name: 'get_tool_health',\n    description:\n      'Probe each MCP tool category and return a per-tool wiring status: ' +\n      '\"live\" (handler reachable + canary probe passed), \"scaffold\" (handler reachable but ' +\n      'returns a stub/empty payload), or \"stub\" (handler not wired / unconditionally throws). ' +\n      'Use this before relying on any tool to avoid overclaiming that a scaffold path is ' +\n      'production-ready. Root cause of the W.122 fictional-route pattern — always call this ' +\n      \"first when uncertain about a tool's backing implementation.\",\n    inputSchema: {\n      type: 'object',\n      properties: {\n        tools: {\n          type: 'array',\n          items: { type: 'string' },\n          description:\n            'Optional list of specific tool names to probe. If omitted, probes a representative ' +\n            'set covering all major categories.',\n        },\n        includeStubs: {\n          type: 'boolean',\n          description:\n            'If true, include stub-status tools in the response (default: true). Set false to ' +\n            'return only live and scaffold tools.',\n        },\n      },\n    },\n  },\n];\n\ninterface OutputSchemaEntry {\n  type: 'object';\n  required?: string[];\n  properties: Record<string, unknown>;\n  additionalProperties?: boolean;\n}\n\nexport interface ToolManifestEntry {\n  name: string;\n  description?: string;\n  category: string;\n  tags: string[];\n  /**\n   * The Holo* brand this tool belongs to (e.g. \"HoloKey\", \"HoloTunnel\"), when\n   * known. Sourced from ai-ecosystem/config/holon-registry.json (schema\n   * holon-registry.v1) via the HOLON_TOOL_PREFIXES table below — see\n   * inferHolon() for the matching rule. Board task_1783967615617_deaf: before\n   * this field existed, an agent calling get_tool_manifest / suggest_tools_for_goal\n   * had no way to learn that e.g. holo_secrets_grant/_resolve/_revoke are the\n   * HoloKey holon, or that holo_tunnel_create/_status/_close are HoloTunnel —\n   * the brand-to-tool mapping lived ONLY in the ecosystem glossary, invisible\n   * from the tool manifest itself. Absent when no mapping is known; this is\n   * NOT the same claim as the registry's own `advertised_surfaces.mcp_tools`\n   * flag (which measures whether the brand string ALREADY appears in a tool's\n   * own name/description before this field existed).\n   */\n  holon?: string;\n  inputSchema?: Record<string, unknown>;\n  outputSchema?: OutputSchemaEntry;\n  examples?: Array<{ args: Record<string, unknown> }>;\n}\n\n/**\n * Tool-name-prefix -> holon brand mapping, curated from\n * ai-ecosystem/config/holon-registry.json entries' own `code_root`/`notes`\n * evidence (each row below is backed by an exact tool-name citation already\n * recorded there as of 2026-07-15). Deliberately NOT exhaustive across all 50\n * registered holons — only prefixes with clear, already-documented tool-name\n * evidence are listed; extend as more mappings are curated. Exact-name rows\n * (no shared prefix with a sibling tool) are listed as a full tool name.\n */\nconst HOLON_TOOL_PREFIXES: ReadonlyArray<{ prefix: string; holon: string; exact?: boolean }> = [\n  { prefix: 'holo_secrets_', holon: 'HoloKey' },\n  { prefix: 'holo_tunnel_', holon: 'HoloTunnel' },\n  { prefix: 'holotune_', holon: 'HoloTune' },\n  { prefix: 'holo_hologram_', holon: 'HoloGram' },\n  { prefix: 'hololand_', holon: 'HoloLand' },\n  { prefix: 'holo_holotwin_', holon: 'HoloTwin' },\n  { prefix: 'holo_reconstruct_', holon: 'HoloMap' },\n  { prefix: 'holo_map_', holon: 'HoloMap' },\n  { prefix: 'holo_daemon_', holon: 'HoloDaemon' },\n  { prefix: 'holoshell_download_recovery_', holon: 'HoloShell' },\n  { prefix: 'holo_graph_', holon: 'HoloGraph' },\n  { prefix: 'holo_ci_dispatch', holon: 'HoloCI', exact: true },\n  { prefix: 'compile_to_holob', holon: 'HoloVM', exact: true },\n];\n\n/** Look up a tool's holon by exact name or prefix match. Returns undefined when unknown. */\nfunction inferHolon(name: string): string | undefined {\n  for (const { prefix, holon, exact } of HOLON_TOOL_PREFIXES) {\n    if (exact ? name === prefix : name.startsWith(prefix)) return holon;\n  }\n  return undefined;\n}\n\nconst EXPLICIT_OUTPUT_SCHEMAS: Record<string, OutputSchemaEntry> = {\n  parse_hs: {\n    type: 'object',\n    required: ['success'],\n    properties: {\n      success: { type: 'boolean' },\n      ast: { type: 'object' },\n      errors: { type: 'array' },\n      warnings: { type: 'array' },\n      sourceMap: { type: 'object' },\n      error: { type: 'string' },\n    },\n    additionalProperties: true,\n  },\n  parse_holo: {\n    type: 'object',\n    required: ['success'],\n    properties: {\n      success: { type: 'boolean' },\n      composition: { type: 'object' },\n      errors: { type: 'array' },\n      error: { type: 'string' },\n    },\n    additionalProperties: true,\n  },\n  validate_holoscript: {\n    type: 'object',\n    required: ['valid'],\n    properties: {\n      valid: { type: 'boolean' },\n      format: { type: 'string' },\n      errors: { type: 'array' },\n      warnings: { type: 'array' },\n      summary: { type: 'string' },\n      error: { type: 'string' },\n    },\n    additionalProperties: true,\n  },\n  compile_holoscript: {\n    type: 'object',\n    required: ['success'],\n    properties: {\n      success: { type: 'boolean' },\n      target: { type: 'string' },\n      output: { type: 'string' },\n      warnings: { type: 'array' },\n      error: { type: 'string' },\n    },\n    additionalProperties: true,\n  },\n  get_tool_manifest: {\n    type: 'object',\n    required: ['count', 'tools'],\n    properties: {\n      count: { type: 'number' },\n      tools: { type: 'array' },\n      categories: { type: 'object' },\n    },\n    additionalProperties: true,\n  },\n  suggest_tools_for_goal: {\n    type: 'object',\n    required: ['goal', 'suggestions'],\n    properties: {\n      goal: { type: 'string' },\n      suggestions: { type: 'array' },\n      suggestedBundles: { type: 'array' },\n      noToolExplanation: { type: 'string' },\n    },\n    additionalProperties: true,\n  },\n  batch_tool_call: {\n    type: 'object',\n    required: ['results'],\n    properties: {\n      results: { type: 'array' },\n      summary: { type: 'object' },\n    },\n    additionalProperties: true,\n  },\n  get_tool_health: {\n    type: 'object',\n    required: ['checked_at', 'total', 'live', 'scaffold', 'stub', 'tools'],\n    properties: {\n      checked_at: { type: 'string' },\n      total: { type: 'number' },\n      live: { type: 'number' },\n      scaffold: { type: 'number' },\n      stub: { type: 'number' },\n      tools: { type: 'array' },\n    },\n    additionalProperties: true,\n  },\n};\n\nfunction inferCategory(name: string): string {\n  if (name.startsWith('compile_')) return 'compiler';\n  if (name.startsWith('holo_')) return 'graph/codebase';\n  if (name.startsWith('hs_ai_')) return 'ai-assistant';\n  if (name.startsWith('hs_')) return 'ide';\n  if (name.startsWith('holotune_')) return 'holotune';\n  if (name.startsWith('holomesh_')) return 'holomesh';\n  if (name.startsWith('browser_')) return 'browser';\n  if (name.includes('trace') || name.includes('metrics') || name.includes('health'))\n    return 'observability';\n  if (name.includes('plugin')) return 'plugins';\n  if (name.includes('budget') || name.includes('earnings') || name.includes('usage'))\n    return 'economy';\n  if (name.includes('simulation') || name.startsWith('solve_') || name.includes('cael'))\n    return 'simulation';\n  return 'core';\n}\n\nfunction inferOutputSchema(name: string): OutputSchemaEntry {\n  const explicit = EXPLICIT_OUTPUT_SCHEMAS[name];\n  if (explicit) return explicit;\n\n  if (name.startsWith('compile_')) {\n    return {\n      type: 'object',\n      properties: {\n        success: { type: 'boolean' },\n        target: { type: 'string' },\n        output: { type: ['string', 'object'] },\n        warnings: { type: 'array' },\n        error: { type: 'string' },\n      },\n      additionalProperties: true,\n    };\n  }\n\n  if (name.startsWith('holo_') || name.startsWith('hs_') || name.startsWith('holomesh_')) {\n    return {\n      type: 'object',\n      properties: {\n        success: { type: 'boolean' },\n        data: { type: ['object', 'array', 'string', 'number', 'boolean'] },\n        error: { type: 'string' },\n      },\n      additionalProperties: true,\n    };\n  }\n\n  return {\n    type: 'object',\n    properties: {\n      success: { type: 'boolean' },\n      result: { type: ['object', 'array', 'string', 'number', 'boolean'] },\n      error: { type: 'string' },\n    },\n    additionalProperties: true,\n  };\n}\n\nfunction inferTags(name: string, description?: string): string[] {\n  const tags = new Set<string>([inferCategory(name)]);\n  const desc = (description || '').toLowerCase();\n  const n = name.toLowerCase();\n\n  for (const t of [\n    'parse',\n    'validate',\n    'compile',\n    'render',\n    'share',\n    'graph',\n    'ide',\n    'ai',\n    'simulation',\n    'cael',\n    'plugin',\n    'economy',\n    'observability',\n    'mcp',\n    'rest',\n    'a2a',\n    'cli',\n    'control',\n    'discovery',\n    'health',\n    'canary',\n  ]) {\n    if (desc.includes(t) || n.includes(t)) tags.add(t);\n  }\n\n  return Array.from(tags);\n}\n\nfunction inferExamples(name: string): Array<{ args: Record<string, unknown> }> {\n  if (name === 'parse_hs') return [{ args: { code: 'object Cube { geometry: \"cube\" }' } }];\n  if (name === 'validate_holoscript')\n    return [{ args: { code: 'composition \"S\" { object \"C\" { geometry: \"cube\" } }' } }];\n  if (name === 'compile_holoscript')\n    return [\n      { args: { code: 'composition \"S\" { object \"C\" { geometry: \"cube\" } }', target: 'webgpu' } },\n    ];\n  return [];\n}\n\nexport function buildToolManifest(\n  allTools: Tool[],\n  opts: {\n    includeInputSchema?: boolean;\n    includeOutputSchema?: boolean;\n    includeExamples?: boolean;\n  } = {}\n): ToolManifestEntry[] {\n  const includeInputSchema = opts.includeInputSchema !== false;\n  const includeOutputSchema = opts.includeOutputSchema !== false;\n  const includeExamples = opts.includeExamples === true;\n\n  return allTools.map((tool) => {\n    const holon = inferHolon(tool.name);\n    return {\n      name: tool.name,\n      description: tool.description,\n      category: inferCategory(tool.name),\n      tags: inferTags(tool.name, tool.description),\n      ...(holon ? { holon } : {}),\n      ...(includeInputSchema ? { inputSchema: tool.inputSchema as Record<string, unknown> } : {}),\n      ...(includeOutputSchema ? { outputSchema: inferOutputSchema(tool.name) } : {}),\n      ...(includeExamples ? { examples: inferExamples(tool.name) } : {}),\n    };\n  });\n}\n\nfunction getWordTokens(s: string): string[] {\n  return s\n    .replace(/([a-z])([A-Z])/g, '$1 $2')\n    .split(/[^a-z0-9]+/)\n    .filter(Boolean)\n    .map((w) => w.toLowerCase());\n}\n\nexport function suggestToolsForGoal(\n  goal: string,\n  manifest: ToolManifestEntry[],\n  maxSuggestions = 8\n): {\n  goal: string;\n  suggestions: Array<{ name: string; score: number; reason: string }>;\n  suggestedBundles: Array<{ name: string; tools: string[]; reason: string }>;\n  noToolExplanation?: string;\n} {\n  const q = goal.toLowerCase();\n  const queryTokens = new Set(q.split(/[^a-z0-9_]+/).filter(Boolean));\n\n  const scored = manifest\n    .map((tool) => {\n      const haystack =\n        `${tool.name} ${tool.description || ''} ${tool.tags.join(' ')}`.toLowerCase();\n      const haystackWords = getWordTokens(haystack);\n      let score = 0;\n      for (const token of queryTokens) {\n        if (token.length < 2) continue;\n        if (haystackWords.some((w) => w === token || w.startsWith(token))) score += 2;\n      }\n\n      if (q.includes('compile') && tool.name.startsWith('compile_')) score += 3;\n      if ((q.includes('validate') || q.includes('lint')) && tool.name.includes('validate'))\n        score += 3;\n      if ((q.includes('parse') || q.includes('ast')) && tool.name.startsWith('parse_')) score += 3;\n      if (q.includes('graph') && tool.name.startsWith('holo_')) score += 2;\n      if (\n        q.includes('simulate') &&\n        (tool.tags.includes('simulation') || tool.name.startsWith('solve_'))\n      )\n        score += 3;\n\n      // MCP, REST, A2A, CLI, control-plane, discovery, health, canary\n      if (\n        (q.includes('mcp') || q.includes('tool manifest')) &&\n        (tool.name === 'get_tool_manifest' ||\n          tool.name === 'suggest_tools_for_goal' ||\n          tool.name === 'batch_tool_call' ||\n          tool.name === 'get_tool_health' ||\n          tool.name === 'holoscript_discover_tools' ||\n          tool.name === 'compile_to_mcp_config')\n      )\n        score += 4;\n      if (\n        (q.includes('rest') || q.includes('api') || q.includes('control') || q.includes('rcp')) &&\n        (tool.name === 'get_api_reference' ||\n          tool.name === 'get_circuit_breaker_status' ||\n          tool.name === 'fetch_authoritative_state' ||\n          tool.name === 'get_dev_dashboard_state' ||\n          tool.name === 'holo_service_scaffold')\n      )\n        score += 4;\n      if (\n        q.includes('a2a') &&\n        (tool.name === 'compile_to_a2a_agent_card' ||\n          tool.name === 'discover_agents' ||\n          tool.name === 'discover_plugins')\n      )\n        score += 4;\n      if (\n        (q.includes('cli') || q.includes('command line')) &&\n        (tool.name === 'holoscript_batch_execute' ||\n          tool.name === 'execute_holotest' ||\n          tool.name === 'holo_run_tests_targeted' ||\n          tool.name === 'holo_run_related_tests')\n      )\n        score += 4;\n      if (\n        q.includes('discovery') &&\n        (tool.name.startsWith('discover_') ||\n          tool.name === 'holoscript_discover_tools' ||\n          tool.name === 'holo_oracle_discover')\n      )\n        score += 4;\n      if (\n        (q.includes('health') || q.includes('diagnostic')) &&\n        (tool.name === 'get_agent_health' ||\n          tool.name === 'holoscript_code_health' ||\n          tool.name === 'holo_self_diagnose' ||\n          tool.name === 'get_telemetry_metrics' ||\n          tool.name === 'get_metrics_prometheus')\n      )\n        score += 4;\n      if (\n        (q.includes('canary') ||\n          q.includes('gap') ||\n          q.includes('wired') ||\n          q.includes('scaffold') ||\n          q.includes('stub')) &&\n        (tool.name === 'get_tool_health' ||\n          tool.name === 'execute_holotest' ||\n          tool.name === 'execute_eval' ||\n          tool.name === 'holo_run_tests_targeted' ||\n          tool.name === 'holo_run_related_tests' ||\n          tool.name === 'holoscript_code_health' ||\n          tool.name === 'holo_self_diagnose' ||\n          tool.name === 'get_circuit_breaker_status')\n      )\n        score += 4;\n\n      return {\n        name: tool.name,\n        score,\n        reason: `Matched by tokens/tags in: ${tool.name}`,\n      };\n    })\n    .filter((x) => x.score > 0)\n    .sort((a, b) => b.score - a.score)\n    .slice(0, maxSuggestions);\n\n  const suggestedBundles: Array<{ name: string; tools: string[]; reason: string }> = [];\n\n  if (q.includes('parse') || q.includes('validate') || q.includes('compile')) {\n    suggestedBundles.push({\n      name: 'parse-validate-compile',\n      tools: ['parse_hs', 'validate_holoscript', 'compile_holoscript'],\n      reason: 'Common code pipeline for syntax, safety, and target output generation.',\n    });\n  }\n\n  if (q.includes('simulation') || q.includes('cael')) {\n    suggestedBundles.push({\n      name: 'simulate-and-verify-trace',\n      tools: ['solve_structural', 'verify_cael_trace'],\n      reason: 'Run physics solver then verify CAEL hash-chain integrity.',\n    });\n  }\n\n  if (\n    q.includes('mcp') ||\n    q.includes('rest') ||\n    q.includes('a2a') ||\n    q.includes('cli') ||\n    q.includes('control') ||\n    q.includes('discovery') ||\n    q.includes('health') ||\n    q.includes('canary')\n  ) {\n    suggestedBundles.push({\n      name: 'control-plane-and-surface-audit',\n      tools: [\n        'get_tool_health',\n        'get_tool_manifest',\n        'get_api_reference',\n        'get_circuit_breaker_status',\n        'get_agent_health',\n        'holoscript_code_health',\n        'discover_agents',\n        'execute_holotest',\n        'execute_eval',\n      ],\n      reason:\n        'Audit MCP, REST, A2A, and CLI surfaces: tool wiring health, manifest discovery, API docs, circuit breakers, health checks, and canary tests.',\n    });\n  }\n\n  const noToolExplanation =\n    scored.length === 0\n      ? `No tools matched for goal: \"${goal}\". Analyzed tokens: ${Array.from(queryTokens)\n          .filter((t) => t.length >= 2)\n          .join(', ')}. Try rephrasing or use get_tool_manifest for a full listing.`\n      : undefined;\n\n  return {\n    goal,\n    suggestions: scored,\n    suggestedBundles,\n    noToolExplanation,\n  };\n}\n\n// ---------------------------------------------------------------------------\n// Tool health probe implementation\n// ---------------------------------------------------------------------------\n\n/**\n * Categorised list of representative tool names.\n * Each entry is the canonical registered MCP tool name. The probe attempts a\n * minimal call via `dispatch` and classifies the result.\n *\n * We do NOT exhaustively probe every tool — that would be slow and some tools\n * have mandatory side-effects. Instead we probe one representative per\n * category, which is enough to surface scaffold vs live status for that whole\n * surface area.\n */\nconst REPRESENTATIVE_TOOLS: Record<string, string[]> = {\n  parsing: ['parse_hs', 'parse_holo', 'parse_hs', 'parse_pipeline'],\n  validation: ['validate_holoscript'],\n  compiler: ['compile_holoscript', 'compile_to_webgpu'],\n  'graph/codebase': ['holo_graph_status'],\n  'ai-assistant': ['hs_ai_explain_error'],\n  ide: ['hs_diagnostics'],\n  holomesh: ['holomesh_status'],\n  browser: ['browser_screenshot'],\n  observability: ['get_agent_health', 'holoscript_code_health'],\n  plugins: ['list_plugins'],\n  economy: ['get_creator_earnings', 'settle_creator_payout'],\n  simulation: ['verify_cael_trace'],\n  holotune: ['holotune_status', 'holotune_launch'],\n  discovery: ['get_tool_manifest', 'suggest_tools_for_goal'],\n  tooling: ['batch_tool_call', 'get_tool_health'],\n};\n\n/**\n * Minimal \"canary\" argument sets for each tool: the smallest valid input that\n * should not touch external services or mutate state.\n */\nconst CANARY_ARGS: Record<string, Record<string, unknown>> = {\n  parse_hs: { code: 'object Cube { geometry: \"cube\" }' },\n  parse_holo: { code: 'composition \"S\" { object \"C\" { geometry: \"cube\" } }' },\n  parse_pipeline: { source: 'step \"a\" { tool: \"parse_hs\" }' },\n  validate_holoscript: { code: 'composition \"S\" { object \"C\" { geometry: \"cube\" } }' },\n  compile_holoscript: {\n    code: 'composition \"S\" { object \"C\" { geometry: \"cube\" } }',\n    target: 'webgpu',\n  },\n  holo_graph_status: {},\n  hs_ai_explain_error: { code: 'object Cube { geometry: \"cube\" }', errors: [] },\n  hs_diagnostics: { code: 'object Cube { geometry: \"cube\" }' },\n  holomesh_status: {},\n  browser_screenshot: {}, // will stub — no real browser in probe\n  get_agent_health: {},\n  holoscript_code_health: { code: 'object Cube { geometry: \"cube\" }' },\n  list_plugins: {},\n  get_creator_earnings: {},\n  settle_creator_payout: {},\n  verify_cael_trace: { trace: [] },\n  holotune_status: {},\n  holotune_curate: {\n    identity: 'canary',\n    traceRows: [{ user: 'say hello', target: '<tool_call>{\"name\":\"noop\"}</tool_call>' }],\n  },\n  holotune_launch: { identity: 'canary', dryRun: true, corpusHash: 'sha256:canary' },\n  holotune_eval: {\n    identity: 'canary',\n    baselineMetrics: { pass_rate: 0.5 },\n    tunedMetrics: { pass_rate: 0.6 },\n    requiredBenchmarks: ['pass_rate'],\n  },\n  holotune_promote: {\n    identity: 'canary',\n    dryRun: true,\n    adapterUri: 'file:///tmp/canary-adapter',\n    ggufUri: 'file:///tmp/canary.gguf',\n  },\n  holotune_serve: {\n    identity: 'canary',\n    adapterUri: 'file:///tmp/canary-adapter',\n    ggufUri: 'file:///tmp/canary.gguf',\n  },\n  holotune_download: {\n    identity: 'canary',\n    ggufUri: 'file:///tmp/canary.gguf',\n  },\n  get_tool_manifest: { includeInputSchema: false, includeOutputSchema: false },\n  suggest_tools_for_goal: { goal: 'parse holoscript', maxSuggestions: 2 },\n  batch_tool_call: { calls: [] },\n  get_tool_health: { tools: ['get_tool_manifest'], includeStubs: false },\n};\n\n/**\n * Classify a dispatch result for a tool as live / scaffold / stub.\n *\n * Rules:\n * - If dispatch throws with \"not implemented\", \"not wired\", \"unsupported\", or\n *   returns null → stub\n * - If dispatch throws any other error → scaffold (handler is reachable but\n *   the underlying path is incomplete)\n * - If dispatch returns a non-null result:\n *   - If result has `success: false` and an `error` field → scaffold\n *   - Otherwise → live\n */\nasync function probeOneTool(\n  toolName: string,\n  dispatch: (name: string, args: Record<string, unknown>) => Promise<unknown>\n): Promise<ToolHealthEntry> {\n  const category = inferCategory(toolName);\n  const now = new Date().toISOString();\n  const args = CANARY_ARGS[toolName] ?? {};\n\n  let status: ToolWiringStatus;\n  let reason: string;\n\n  try {\n    const result = await dispatch(toolName, args);\n\n    if (result === null || result === undefined) {\n      status = 'stub';\n      reason = 'dispatch returned null — tool name not wired in handler switch';\n    } else {\n      const r = result as Record<string, unknown>;\n      if (r['success'] === false && typeof r['error'] === 'string') {\n        status = 'scaffold';\n        reason = `handler reachable but returned success:false — ${String(r['error']).slice(0, 120)}`;\n      } else {\n        status = 'live';\n        reason = 'canary probe returned non-null result with expected shape';\n      }\n    }\n  } catch (err: unknown) {\n    const msg = err instanceof Error ? err.message : String(err);\n    const lower = msg.toLowerCase();\n    if (\n      lower.includes('not implemented') ||\n      lower.includes('not wired') ||\n      lower.includes('unsupported tool') ||\n      lower.includes('unknown tool') ||\n      lower.includes('unrecognized')\n    ) {\n      status = 'stub';\n      reason = `handler throws \"not implemented\" — ${msg.slice(0, 120)}`;\n    } else {\n      // Threw for another reason: missing required arg, parser error, etc.\n      // The handler IS reachable; the underlying path is incomplete.\n      status = 'scaffold';\n      reason = `handler reachable but threw: ${msg.slice(0, 120)}`;\n    }\n  }\n\n  return { tool: toolName, category, status, last_checked: now, reason };\n}\n\n/**\n * Build a full tool health report.\n *\n * @param requestedTools  If non-empty, probe only these tool names.\n *                        If empty, probe the representative set.\n * @param allRegistered   Full list of registered MCP tool names (for\n *                        marking any requested tool as stub when it is not\n *                        in the registry at all).\n * @param dispatch        MCP tool dispatch function.\n * @param includeStubs    Whether to include stub entries in the output.\n */\nexport async function buildToolHealthReport(\n  requestedTools: string[],\n  allRegistered: string[],\n  dispatch: (name: string, args: Record<string, unknown>) => Promise<unknown>,\n  includeStubs = true\n): Promise<ToolHealthReport> {\n  const checkedAt = new Date().toISOString();\n\n  // Determine the set of tool names to probe.\n  let toProbe: string[];\n  if (requestedTools.length > 0) {\n    toProbe = requestedTools;\n  } else {\n    // Unique representative tools flattened from the category map.\n    const seen = new Set<string>();\n    toProbe = [];\n    for (const names of Object.values(REPRESENTATIVE_TOOLS)) {\n      for (const n of names) {\n        if (!seen.has(n)) {\n          seen.add(n);\n          toProbe.push(n);\n        }\n      }\n    }\n  }\n\n  const registeredSet = new Set(allRegistered);\n\n  // Probe in parallel (bounded; representative set is ~20 tools max).\n  const entries: ToolHealthEntry[] = await Promise.all(\n    toProbe.map(async (toolName): Promise<ToolHealthEntry> => {\n      // If the tool is not even registered, mark it stub immediately.\n      if (!registeredSet.has(toolName)) {\n        return {\n          tool: toolName,\n          category: inferCategory(toolName),\n          status: 'stub',\n          last_checked: checkedAt,\n          reason: 'tool name not found in MCP tool registry',\n        };\n      }\n      return probeOneTool(toolName, dispatch);\n    })\n  );\n\n  const visible = includeStubs ? entries : entries.filter((e) => e.status !== 'stub');\n\n  const live = visible.filter((e) => e.status === 'live').length;\n  const scaffold = visible.filter((e) => e.status === 'scaffold').length;\n  const stub = visible.filter((e) => e.status === 'stub').length;\n\n  return {\n    checked_at: checkedAt,\n    total: visible.length,\n    live,\n    scaffold,\n    stub,\n    tools: visible,\n  };\n}\n\nexport async function handleToolingDiscoveryTool(\n  name: string,\n  args: Record<string, unknown>,\n  allTools: Tool[],\n  dispatch: (name: string, args: Record<string, unknown>) => Promise<unknown>\n): Promise<\n  | {\n      count: number;\n      categories: Record<string, number>;\n      tools: ToolManifestEntry[];\n    }\n  | {\n      goal: string;\n      suggestions: Array<{ name: string; score: number; reason: string }>;\n      suggestedBundles: Array<{ name: string; tools: string[]; reason: string }>;\n      noToolExplanation?: string;\n    }\n  | {\n      results: Array<{\n        index: number;\n        name: string;\n        ok: boolean;\n        result?: unknown;\n        error?: string;\n      }>;\n      summary: { total: number; succeeded: number; failed: number; stoppedEarly: boolean };\n    }\n  | ToolHealthReport\n  | null\n> {\n  if (name === 'get_tool_manifest') {\n    const includeInputSchema = args.includeInputSchema !== false;\n    const includeOutputSchema = args.includeOutputSchema !== false;\n    const includeExamples = args.includeExamples === true;\n\n    const manifest = buildToolManifest(allTools, {\n      includeInputSchema,\n      includeOutputSchema,\n      includeExamples,\n    });\n\n    const categories: Record<string, number> = {};\n    for (const item of manifest) categories[item.category] = (categories[item.category] || 0) + 1;\n\n    return {\n      count: manifest.length,\n      categories,\n      tools: manifest,\n    };\n  }\n\n  if (name === 'suggest_tools_for_goal') {\n    const goal = String(args.goal || '').trim();\n    if (!goal) throw new Error('goal is required');\n\n    const maxSuggestions =\n      typeof args.maxSuggestions === 'number' && args.maxSuggestions > 0\n        ? Math.floor(args.maxSuggestions)\n        : 8;\n\n    const manifest = buildToolManifest(allTools, {\n      includeInputSchema: false,\n      includeOutputSchema: false,\n      includeExamples: false,\n    });\n\n    return suggestToolsForGoal(goal, manifest, maxSuggestions);\n  }\n\n  if (name === 'batch_tool_call') {\n    return handleBatchToolCall(args, dispatch);\n  }\n\n  if (name === 'get_tool_health') {\n    const requestedTools = Array.isArray(args.tools)\n      ? (args.tools as unknown[]).filter((t): t is string => typeof t === 'string')\n      : [];\n    const includeStubs = args.includeStubs !== false;\n    const allRegistered = allTools.map((t) => t.name);\n    return buildToolHealthReport(requestedTools, allRegistered, dispatch, includeStubs);\n  }\n\n  return null;\n}\n\nexport async function handleBatchToolCall(\n  args: Record<string, unknown>,\n  dispatch: (name: string, args: Record<string, unknown>) => Promise<unknown>\n): Promise<{\n  results: Array<{ index: number; name: string; ok: boolean; result?: unknown; error?: string }>;\n  summary: { total: number; succeeded: number; failed: number; stoppedEarly: boolean };\n}> {\n  const calls = Array.isArray(args.calls) ? args.calls : [];\n  const stopOnError = args.stopOnError === true;\n\n  const results: Array<{\n    index: number;\n    name: string;\n    ok: boolean;\n    result?: unknown;\n    error?: string;\n  }> = [];\n  let stoppedEarly = false;\n\n  for (let i = 0; i < calls.length; i++) {\n    const call = calls[i] as { name?: string; args?: Record<string, unknown> };\n    const name = call?.name;\n\n    if (!name || typeof name !== 'string') {\n      results.push({\n        index: i,\n        name: '(invalid)',\n        ok: false,\n        error: 'Missing or invalid call.name',\n      });\n      if (stopOnError) {\n        stoppedEarly = true;\n        break;\n      }\n      continue;\n    }\n\n    if (name === 'batch_tool_call') {\n      results.push({ index: i, name, ok: false, error: 'Nested batch_tool_call is not allowed' });\n      if (stopOnError) {\n        stoppedEarly = true;\n        break;\n      }\n      continue;\n    }\n\n    try {\n      const result = await dispatch(name, call.args || {});\n      results.push({ index: i, name, ok: true, result });\n    } catch (error) {\n      results.push({\n        index: i,\n        name,\n        ok: false,\n        error: error instanceof Error ? error.message : String(error),\n      });\n      if (stopOnError) {\n        stoppedEarly = true;\n        break;\n      }\n    }\n  }\n\n  const succeeded = results.filter((r) => r.ok).length;\n  const failed = results.length - succeeded;\n\n  return {\n    results,\n    summary: {\n      total: calls.length,\n      succeeded,\n      failed,\n      stoppedEarly,\n    },\n  };\n}\n","/**\n * North Star Oracle Handler (local to mcp-server)\n *\n * Inlined to avoid cross-package import issues. Combines decision trees\n * with knowledge store queries to answer agent questions.\n */\n\nimport * as fs from 'fs';\nimport * as os from 'os';\nimport * as path from 'path';\nimport { resolveSecretWithLease, VaultLeaseError } from './holomesh/identity/vault-lease-registry';\n\n/**\n * Phase 3 wrapper around the orchestrator-knowledge-fetch API key. This is\n * the per-task agent-inference path (`/oracle` MCP tool dispatching to\n * `${MCP_ORCHESTRATOR_PUBLIC_URL}/knowledge/query`) — exactly the medium-risk\n * Phase 3 tier the task description targets (\"per-task agent-inference auth\n * headers\"). The original code reads\n * `process.env.HOLOSCRIPT_API_KEY || process.env.ABSORB_API_KEY` so each ref\n * resolves through the lease helper independently. A lease scoped only to\n * `env:HOLOSCRIPT_API_KEY` will not silently fall through to\n * `env:ABSORB_API_KEY` under enforcement.\n *\n * Returning `''` on `VaultLeaseError` for each ref preserves the original\n * fallback chain semantics during the migration window — both refs failing\n * yields `'' || '' || undefined` and the caller branches on the falsy value\n * to skip the knowledge-store query.\n */\nfunction readOracleKnowledgeApiKey(): string | undefined {\n  const tryRead = (ref: 'env:HOLOSCRIPT_API_KEY' | 'env:ABSORB_API_KEY'): string => {\n    try {\n      return resolveSecretWithLease(ref) ?? '';\n    } catch (err) {\n      if (err instanceof VaultLeaseError) return '';\n      throw err;\n    }\n  };\n  return tryRead('env:HOLOSCRIPT_API_KEY') || tryRead('env:ABSORB_API_KEY') || undefined;\n}\n\nconst TREES: Record<string, string> = {\n  package:\n    'Add to the closest relevant existing package. Only create a new package if standalone service or shared by 3+ packages.',\n  commit:\n    'Commit after coherent unit. 10+ files: MUST split into sectioned commits by topic. NEVER git add -A.',\n  test: 'Fix if yours, investigate if pre-existing. Can fix in <15 min? Fix. Complex? File a task with evidence and continue.',\n  mcp: 'Use MCP if reachable (richer). CLI as fallback.',\n  cache:\n    '<12h fresh. 12-24h OK. 24-48h stale. >48h force refresh. NEVER force:true unless corrupt.',\n  todo: '1.Security 2.FIXME 3.Blocking 4.Performance 5.Tech-debt 6.Nice-to-have. Max 3/cycle.',\n  version: \"Breaking=MAJOR. New feature=MINOR. Bug fix=PATCH. Don't bump unless releasing.\",\n  doc: 'New public API=always. Internal refactor=no. Bug fix=only if documented behavior affected.',\n  cost: '<$1 auto. $1-5 proceed+mention. $5-20 ASK. >$20 ALWAYS ASK.',\n  conflict:\n    'User > project CLAUDE.md > AGENTS.md > global CLAUDE.md > NORTH_STAR.md > memory > research > README.',\n  repo: 'Default: HoloScript. Unless explicitly told otherwise.',\n  embedding: 'ALWAYS OpenAI. BM25 deprecated. Ensure OPENAI_API_KEY in env.',\n  git: 'ALWAYS explicit file paths. NEVER git add -A or git add .',\n};\n\nconst ORACLE_TELEMETRY_PATH =\n  process.env.ORACLE_TELEMETRY_PATH ||\n  path.join(os.homedir(), '.holoscript', 'oracle-telemetry.jsonl');\n\nfunction inferHardwareTarget(question: string, context: string, explicitTarget?: unknown): string {\n  if (typeof explicitTarget === 'string' && explicitTarget.trim()) {\n    return explicitTarget.trim().toLowerCase();\n  }\n  const haystack = `${question} ${context}`.toLowerCase();\n  if (\n    haystack.includes('quest') ||\n    haystack.includes('mobile') ||\n    haystack.includes('android-xr')\n  ) {\n    return 'mobile-xr';\n  }\n  if (haystack.includes('vision') || haystack.includes('visionos')) return 'visionos';\n  if (\n    haystack.includes('openxr') ||\n    haystack.includes('desktop vr') ||\n    haystack.includes('pc vr')\n  ) {\n    return 'desktop-vr';\n  }\n  if (\n    haystack.includes('edge') ||\n    haystack.includes('iot') ||\n    haystack.includes('jetson') ||\n    haystack.includes('raspberry')\n  ) {\n    return 'edge-iot';\n  }\n  return 'unknown';\n}\n\nfunction appendOracleTelemetry(event: Record<string, unknown>): void {\n  try {\n    const dir = path.dirname(ORACLE_TELEMETRY_PATH);\n    fs.mkdirSync(dir, { recursive: true });\n    fs.appendFileSync(ORACLE_TELEMETRY_PATH, `${JSON.stringify(event)}\\n`, 'utf-8');\n  } catch {\n    // Do not block oracle response on telemetry failures\n  }\n}\n\nexport async function handleOracleConsult(\n  args: Record<string, unknown>\n): Promise<{ content: Array<{ type: string; text: string }> }> {\n  const question = String(args.question || '').toLowerCase();\n  const context = String(args.context || '');\n  const hardwareTarget = inferHardwareTarget(question, context, args.hardware_target);\n  const ideClient = String(args.ide_client || 'unknown').toLowerCase();\n  const results: string[] = [];\n\n  // Match decision trees\n  const dtMatches: string[] = [];\n  for (const [key, answer] of Object.entries(TREES)) {\n    if (question.includes(key)) dtMatches.push(`**[${key}]**: ${answer}`);\n  }\n  if (dtMatches.length > 0) results.push('## Decision Tree Matches\\n' + dtMatches.join('\\n\\n'));\n\n  // Query knowledge store — Phase-3 wrapped read (per-task agent-inference path).\n  // Each ref resolves through resolveSecretWithLease independently so a lease\n  // scoped to only one will not silently fall through to the other under\n  // HOLOMESH_VAULT_LEASE_ENFORCE.\n  const apiKey = readOracleKnowledgeApiKey();\n  if (apiKey) {\n    try {\n      const url =\n        process.env.MCP_ORCHESTRATOR_PUBLIC_URL ||\n        'https://mcp-orchestrator-production-45f9.up.railway.app';\n      const ctrl = new AbortController();\n      const t = setTimeout(() => ctrl.abort(), 5000);\n      const res = await fetch(`${url}/knowledge/query`, {\n        method: 'POST',\n        headers: { 'Content-Type': 'application/json; charset=utf-8', 'x-mcp-api-key': apiKey },\n        body: JSON.stringify({\n          search: `${question} ${context}`.trim(),\n          limit: 5,\n          workspace_id: process.env.HOLOMESH_WORKSPACE || 'default',\n        }),\n        signal: ctrl.signal,\n      });\n      clearTimeout(t);\n      if (res.ok) {\n        interface KnowledgeEntry {\n          id?: string;\n          type?: string;\n          content?: string;\n        }\n        const data = (await res.json()) as {\n          results?: KnowledgeEntry[];\n          entries?: KnowledgeEntry[];\n        };\n        const entries = data.results || data.entries || [];\n        if (entries.length > 0) {\n          results.push(\n            '## Knowledge Store\\n' +\n              entries\n                .map(\n                  (e: KnowledgeEntry) =>\n                    `- **[${e.id || e.type}]** ${String(e.content || '').substring(0, 200)}`\n                )\n                .join('\\n')\n          );\n        }\n      }\n    } catch {\n      /* timeout or network */\n    }\n  }\n\n  if (results.length === 0) {\n    results.push(\n      '## No Oracle Match\\nMake the conservative choice (easier to undo) and note what you decided.'\n    );\n  } else {\n    results.push('\\n---\\n*Oracle answered. Proceed without asking the user.*');\n  }\n\n  appendOracleTelemetry({\n    timestamp: new Date().toISOString(),\n    source: 'mcp-server',\n    tool: 'holo_oracle_consult',\n    ideClient,\n    hardwareTarget,\n    outcome:\n      results.length === 1 && results[0].startsWith('## No Oracle Match') ? 'no_match' : 'answered',\n    decisionTreeMatches: dtMatches.length,\n    questionPreview: question.slice(0, 200),\n  });\n\n  return { content: [{ type: 'text', text: results.join('\\n\\n') }] };\n}\n","/**\n * HoloMesh Knowledge Oracle MCP Tools\n *\n * Graduated from the /oracle skill (~/.claude/skills/holomesh-oracle/SKILL.md)\n * to programmatic MCP tools exposing the full oracle cycle:\n *   SURVEY → COLLIDE → DISCOVER → SYNTHESIZE → PROVOKE → RECRUIT → REFLECT\n *\n * Tools:\n * - holo_oracle_discover   Targeted discovery on a topic (research + knowledge store + optional web)\n * - holo_oracle_synthesize Compress research findings into W/P/G entries\n * - holo_oracle_gaps       Map knowledge gaps across domains\n * - holo_oracle_explore    Deliberate collision between two domains\n * - holo_oracle_curate     Audit knowledge quality and find weak domains\n *\n * @see SKILL.md for full philosophy, collision patterns, and research archive layout\n */\n\nimport { Tool } from '@modelcontextprotocol/sdk/types.js';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport * as os from 'os';\n\n// =============================================================================\n// CONFIG\n// =============================================================================\n\nconst RESEARCH_ROOT =\n  process.env.ORACLE_RESEARCH_ROOT || path.join(os.homedir(), '.ai-ecosystem', 'research');\nconst ORCHESTRATOR_URL =\n  process.env.MCP_ORCHESTRATOR_PUBLIC_URL ||\n  'https://mcp-orchestrator-production-45f9.up.railway.app';\n\nconst HOLOMESH_API_BASE =\n  process.env.HOLOMESH_API_BASE || 'https://mcp.holoscript.net/api/holomesh';\n\nfunction getApiKey(): string | undefined {\n  return process.env.HOLOSCRIPT_API_KEY || process.env.HOLOMESH_API_KEY || undefined;\n}\n\n// =============================================================================\n// TYPES\n// =============================================================================\n\ninterface ResearchFile {\n  filename: string;\n  date: string;\n  topic: string;\n  layer?: string;\n  preview: string;\n  fullPath: string;\n}\n\ninterface KnowledgeEntry {\n  id: string;\n  type: 'wisdom' | 'pattern' | 'gotcha';\n  content: string;\n  domain: string;\n  createdAt?: string;\n}\n\ninterface GapReport {\n  domain: string;\n  entryCount: number;\n  lastEntryDate?: string;\n  coverageScore: number; // 0-100 heuristic\n  gaps: string[];\n}\n\ninterface CollisionResult {\n  domain1: string;\n  domain2: string;\n  researchFiles: ResearchFile[];\n  knowledgeEntries: KnowledgeEntry[];\n  collisionHypotheses: string[];\n  proposedExplorations: string[];\n}\n\n// =============================================================================\n// RESEARCH ARCHIVE SCANNER\n// =============================================================================\n\nfunction scanResearchArchive(query: string, limit = 20): ResearchFile[] {\n  const results: ResearchFile[] = [];\n  const lowerQuery = query.toLowerCase();\n  const words = lowerQuery.split(/\\W+/).filter((w) => w.length > 2);\n\n  if (!fs.existsSync(RESEARCH_ROOT)) return results;\n\n  function recurse(dir: string) {\n    let entries: string[];\n    try {\n      entries = fs.readdirSync(dir);\n    } catch {\n      return;\n    }\n    for (const entry of entries) {\n      const full = path.join(dir, entry);\n      const stat = fs.statSync(full);\n      if (stat.isDirectory()) {\n        recurse(full);\n        continue;\n      }\n      if (!entry.endsWith('.md')) continue;\n\n      const lowerName = entry.toLowerCase();\n      let score = 0;\n      for (const w of words) {\n        if (lowerName.includes(w)) score += 3;\n      }\n      if (score === 0) continue;\n\n      let preview = '';\n      try {\n        preview = fs.readFileSync(full, 'utf-8').slice(0, 600);\n      } catch {\n        continue;\n      }\n      for (const w of words) {\n        if (preview.toLowerCase().includes(w)) score += 1;\n      }\n\n      // Parse date/topic from filename: 2026-03-29_oracle-collision-compilation-as-gossip.md\n      const dateMatch = entry.match(/^(\\d{4}-\\d{2}-\\d{2})_/);\n      const date = dateMatch ? dateMatch[1] : '';\n      const topic = entry.replace(/^\\d{4}-\\d{2}-\\d{2}_/, '').replace(/\\.md$/, '');\n      const layerMatch = topic.match(/-(layer\\d|layer\\d-\\w+|cross-cycle|implementation|unified)/);\n      const layer = layerMatch ? layerMatch[1] : undefined;\n\n      results.push({ filename: entry, date, topic, layer, preview, fullPath: full });\n    }\n  }\n\n  recurse(RESEARCH_ROOT);\n  results.sort((a, b) => {\n    // Prefer oracle collision files, then newer dates\n    const aOracle = a.topic.includes('oracle') ? 1 : 0;\n    const bOracle = b.topic.includes('oracle') ? 1 : 0;\n    if (aOracle !== bOracle) return bOracle - aOracle;\n    return b.date.localeCompare(a.date);\n  });\n  return results.slice(0, limit);\n}\n\nfunction readResearchFile(fullPath: string, maxChars = 8000): string {\n  try {\n    return fs.readFileSync(fullPath, 'utf-8').slice(0, maxChars);\n  } catch {\n    return '';\n  }\n}\n\n// =============================================================================\n// KNOWLEDGE STORE CLIENT\n// =============================================================================\n\nasync function queryKnowledgeStore(search: string, limit = 10): Promise<KnowledgeEntry[]> {\n  const apiKey = getApiKey();\n  if (!apiKey) return [];\n\n  try {\n    const ctrl = new AbortController();\n    const t = setTimeout(() => ctrl.abort(), 5000);\n    const res = await fetch(`${ORCHESTRATOR_URL}/knowledge/query`, {\n      method: 'POST',\n      headers: {\n        'Content-Type': 'application/json',\n        'x-mcp-api-key': apiKey,\n      },\n      body: JSON.stringify({\n        search,\n        limit,\n        workspace_id: process.env.HOLOMESH_WORKSPACE || 'default',\n      }),\n      signal: ctrl.signal,\n    });\n    clearTimeout(t);\n    if (!res.ok) return [];\n    const data = (await res.json()) as {\n      results?: Array<Partial<KnowledgeEntry>>;\n      entries?: Array<Partial<KnowledgeEntry>>;\n    };\n    const raw = data.results || data.entries || [];\n    return raw.map((r) => ({\n      id: r.id || 'unknown',\n      type: (r.type as KnowledgeEntry['type']) || 'wisdom',\n      content: r.content || '',\n      domain: r.domain || 'general',\n      createdAt: r.createdAt,\n    }));\n  } catch {\n    return [];\n  }\n}\n\nasync function queryHoloMeshKnowledge(domain?: string, limit = 20): Promise<KnowledgeEntry[]> {\n  const apiKey = getApiKey();\n  if (!apiKey) return [];\n\n  try {\n    const url = domain\n      ? `${HOLOMESH_API_BASE}/knowledge?domain=${encodeURIComponent(domain)}&limit=${limit}`\n      : `${HOLOMESH_API_BASE}/knowledge?limit=${limit}`;\n    const ctrl = new AbortController();\n    const t = setTimeout(() => ctrl.abort(), 5000);\n    const res = await fetch(url, {\n      method: 'GET',\n      headers: { 'x-mcp-api-key': apiKey },\n      signal: ctrl.signal,\n    });\n    clearTimeout(t);\n    if (!res.ok) return [];\n    const data = (await res.json()) as {\n      entries?: Array<Partial<KnowledgeEntry>>;\n      knowledge?: Array<Partial<KnowledgeEntry>>;\n    };\n    const raw = data.entries || data.knowledge || [];\n    return raw.map((r) => ({\n      id: r.id || 'unknown',\n      type: (r.type as KnowledgeEntry['type']) || 'wisdom',\n      content: r.content || '',\n      domain: r.domain || domain || 'general',\n      createdAt: r.createdAt,\n    }));\n  } catch {\n    return [];\n  }\n}\n\n// =============================================================================\n// WEB SEARCH (optional external gap filling)\n// =============================================================================\n\nasync function webSearchForGaps(\n  query: string,\n  limit = 3\n): Promise<Array<{ title: string; url: string; snippet: string }>> {\n  // NOTE: This is a lightweight wrapper. In production, wire to an actual search API\n  // (e.g. Brave, Serper, or a hosted search MCP). For now, return an empty array\n  // with instructions so the caller knows the gap exists externally.\n  return [];\n}\n\n// =============================================================================\n// TOOL DEFINITIONS\n// =============================================================================\n\nexport const oracleMcpTools: Tool[] = [\n  {\n    name: 'holo_oracle_discover',\n    description:\n      'Run a targeted oracle discovery cycle on a topic. Scans the research archive (130+ files), ' +\n      'queries the knowledge store (500+ W/P/G entries), and optionally searches the web. ' +\n      'Returns synthesized findings with file citations, knowledge matches, and proposed next steps. ' +\n      'Use when you need deep cross-domain insight on a specific topic.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        topic: {\n          type: 'string',\n          description:\n            'Topic to discover (e.g. \"compilation as gossip\", \"thermodynamic trust\", \"security x rendering\")',\n        },\n        depth: {\n          type: 'string',\n          enum: ['brief', 'deep'],\n          description:\n            'brief = top 5 files + 5 knowledge entries. deep = full text of top files + 10 entries.',\n        },\n        sources: {\n          type: 'string',\n          enum: ['internal', 'external', 'both'],\n          description:\n            'internal = research archive + knowledge store only. external = include web search. both = all.',\n        },\n      },\n      required: ['topic'],\n    },\n  },\n  {\n    name: 'holo_oracle_synthesize',\n    description:\n      'Compress research findings from specific files into W/P/G (Wisdom/Pattern/Gotcha) entries. ' +\n      'Reads the research files, extracts key insights, and formats them as publishable knowledge. ' +\n      'Use after discovery to produce shareable knowledge entries.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        research_files: {\n          type: 'array',\n          items: { type: 'string' },\n          description:\n            'List of research file paths (relative to research root or absolute) to synthesize.',\n        },\n        target_format: {\n          type: 'string',\n          enum: ['wisdom', 'pattern', 'gotcha', 'all'],\n          description:\n            'Which knowledge type(s) to produce. all = one of each if material supports it.',\n        },\n        topic: {\n          type: 'string',\n          description: 'Optional topic label to tag the synthesized entries.',\n        },\n      },\n      required: ['research_files'],\n    },\n  },\n  {\n    name: 'holo_oracle_gaps',\n    description:\n      'Map knowledge gaps in the HoloMesh network. Compares expected domains against actual ' +\n      'knowledge store coverage, identifies zero-coverage or low-coverage domains, and returns ' +\n      'a prioritized gap report. Use to find what the network does NOT know yet.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        domain: {\n          type: 'string',\n          description: 'Specific domain to audit, or omit for full network gap map.',\n        },\n        min_coverage_score: {\n          type: 'number',\n          description: 'Minimum coverage score (0-100) to not be flagged as a gap. Default 20.',\n        },\n      },\n    },\n  },\n  {\n    name: 'holo_oracle_explore',\n    description:\n      'Explore a deliberate collision between two domains (e.g. \"security x rendering\"). ' +\n      'Searches the research archive for existing collision work, queries knowledge store for ' +\n      'both domains, and generates collision hypotheses + proposed explorations. ' +\n      'This is the core oracle pattern: knowledge compounds at the intersection.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        domain1: {\n          type: 'string',\n          description: 'First domain (e.g. \"security\", \"physics\", \"economics\")',\n        },\n        domain2: {\n          type: 'string',\n          description: 'Second domain (e.g. \"rendering\", \"reputation\", \"compilation\")',\n        },\n        depth: {\n          type: 'string',\n          enum: ['hypothesis', 'research', 'implementation'],\n          description:\n            'hypothesis = quick intersection map. research = include archive files. implementation = include blueprints.',\n        },\n      },\n      required: ['domain1', 'domain2'],\n    },\n  },\n  {\n    name: 'holo_oracle_curate',\n    description:\n      'Audit knowledge quality in a domain. Returns entry counts by type (W/P/G), staleness ' +\n      'heuristic, coverage depth, and specific weak entries that need reinforcement. ' +\n      'Use before publishing to ensure the network maintains high signal-to-noise.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        domain: {\n          type: 'string',\n          description: 'Domain to audit, or \"all\" for network-wide curation.',\n        },\n        min_entries: {\n          type: 'number',\n          description: 'Minimum entries expected for a healthy domain. Default 5.',\n        },\n      },\n    },\n  },\n];\n\n// =============================================================================\n// HANDLERS\n// =============================================================================\n\nexport async function handleOracleMcpTool(\n  name: string,\n  args: Record<string, unknown>\n): Promise<unknown | null> {\n  switch (name) {\n    case 'holo_oracle_discover':\n      return handleDiscover(args);\n    case 'holo_oracle_synthesize':\n      return handleSynthesize(args);\n    case 'holo_oracle_gaps':\n      return handleGaps(args);\n    case 'holo_oracle_explore':\n      return handleExplore(args);\n    case 'holo_oracle_curate':\n      return handleCurate(args);\n    default:\n      return null;\n  }\n}\n\n// ── Discover ──────────────────────────────────────────────────────────────────\n\nasync function handleDiscover(args: Record<string, unknown>): Promise<unknown> {\n  const topic = String(args.topic || '');\n  const depth = (args.depth as string) || 'brief';\n  const sources = (args.sources as string) || 'internal';\n\n  if (!topic.trim()) {\n    return { error: 'topic is required' };\n  }\n\n  // 1. Scan research archive\n  const researchLimit = depth === 'deep' ? 10 : 5;\n  const researchFiles = scanResearchArchive(topic, researchLimit);\n\n  // 2. Query knowledge store\n  const knowledgeLimit = depth === 'deep' ? 10 : 5;\n  const knowledgeEntries = await queryKnowledgeStore(topic, knowledgeLimit);\n\n  // 3. Optional web search\n  let webResults: Array<{ title: string; url: string; snippet: string }> = [];\n  if (sources === 'external' || sources === 'both') {\n    webResults = await webSearchForGaps(topic, 3);\n  }\n\n  // 4. Build findings\n  const findings: string[] = [];\n\n  if (researchFiles.length > 0) {\n    findings.push(`## Research Archive (${researchFiles.length} files)`);\n    for (const f of researchFiles) {\n      const snippet =\n        depth === 'deep'\n          ? readResearchFile(f.fullPath, 4000)\n          : f.preview.slice(0, 300).replace(/\\n/g, ' ');\n      findings.push(\n        `- **${f.filename}** (${f.date}${f.layer ? `, ${f.layer}` : ''})\\n  ${snippet}${snippet.length >= (depth === 'deep' ? 4000 : 300) ? '...' : ''}`\n      );\n    }\n  }\n\n  if (knowledgeEntries.length > 0) {\n    findings.push(`\\n## Knowledge Store (${knowledgeEntries.length} entries)`);\n    for (const e of knowledgeEntries) {\n      findings.push(\n        `- **[${e.type.toUpperCase()}]** ${e.domain} — ${e.content.slice(0, 200)}${e.content.length > 200 ? '...' : ''}`\n      );\n    }\n  }\n\n  if (webResults.length > 0) {\n    findings.push(`\\n## External Sources (${webResults.length})`);\n    for (const w of webResults) {\n      findings.push(`- [${w.title}](${w.url}) — ${w.snippet}`);\n    }\n  }\n\n  if (findings.length === 0) {\n    findings.push(\n      '## No Findings\\nThe oracle found no research files, knowledge entries, or web results for this topic. This itself is a signal — the topic may be unexplored territory.'\n    );\n  }\n\n  // 5. Propose next steps\n  findings.push('\\n## Next Steps');\n  if (researchFiles.length === 0 && knowledgeEntries.length === 0) {\n    findings.push(\n      '- This topic appears unexplored. Consider filing a research task or running a collision with an adjacent domain.'\n    );\n  } else if (researchFiles.length > 0 && knowledgeEntries.length === 0) {\n    findings.push(\n      '- Research exists but has not been graduated to the knowledge store. Run `holo_oracle_synthesize` on the research files.'\n    );\n  } else if (researchFiles.length > 0 && knowledgeEntries.length > 0) {\n    findings.push(\n      '- Both research and knowledge exist. Consider a collision exploration (`holo_oracle_explore`) with a third domain to find deeper connections.'\n    );\n  } else {\n    findings.push(\n      '- Knowledge exists but no deep research files found. Consider deepening with a targeted research cycle.'\n    );\n  }\n\n  return {\n    topic,\n    depth,\n    sources,\n    researchFilesFound: researchFiles.length,\n    knowledgeEntriesFound: knowledgeEntries.length,\n    webResultsFound: webResults.length,\n    report: findings.join('\\n'),\n    citations: researchFiles.map((f) => ({ file: f.filename, path: f.fullPath, date: f.date })),\n  };\n}\n\n// ── Synthesize ────────────────────────────────────────────────────────────────\n\nasync function handleSynthesize(args: Record<string, unknown>): Promise<unknown> {\n  const files = (args.research_files as string[]) || [];\n  const targetFormat = (args.target_format as string) || 'all';\n  const topic = (args.topic as string) || 'general';\n\n  if (files.length === 0) {\n    return { error: 'research_files is required (array of file paths)' };\n  }\n\n  const synthesized: Array<{ type: string; content: string; sourceFiles: string[] }> = [];\n\n  for (const filePath of files) {\n    const fullPath = path.isAbsolute(filePath) ? filePath : path.join(RESEARCH_ROOT, filePath);\n    if (!fs.existsSync(fullPath)) {\n      continue;\n    }\n    const content = readResearchFile(fullPath, 12000);\n    if (!content) continue;\n\n    // RATCHET: extraction is regex-based (not semantic/LLM). Only convention-header blocks are captured.\n    // Files without Finding/Key-insight headers produce zero insights.\n    // Output is template-stamped per format (wisdom/pattern/gotcha).\n    const insights: string[] = [];\n    const lines = content.split('\\n');\n    let capturing = false;\n    let buffer: string[] = [];\n\n    for (const line of lines) {\n      const lower = line.toLowerCase();\n      const isFindingHeader =\n        lower.startsWith('**finding**') ||\n        lower.startsWith('**key insight') ||\n        /^#{1,3}\\s+finding\\s+\\d*\\s*:/.test(lower) ||\n        /^#{1,3}\\s+key insight/.test(lower) ||\n        (lower.startsWith('- ') &&\n          (lower.includes('finding') || lower.includes('insight') || lower.includes('key:')));\n\n      if (isFindingHeader) {\n        if (buffer.length > 0) insights.push(buffer.join(' ').trim());\n        buffer = [line.replace(/^[-*#\\s]*/, '').replace(/\\*\\*/g, '')];\n        capturing = true;\n      } else if (capturing) {\n        if (line.trim() === '' || line.startsWith('#') || line.startsWith('##')) {\n          if (buffer.length > 0) insights.push(buffer.join(' ').trim());\n          buffer = [];\n          capturing = false;\n        } else {\n          buffer.push(line.replace(/^[-*]\\s*/, '').replace(/\\*\\*/g, ''));\n        }\n      }\n    }\n    if (buffer.length > 0) insights.push(buffer.join(' ').trim());\n\n    // Deduplicate near-identical insights\n    const uniqueInsights = insights.filter((insight, idx, arr) => {\n      const norm = insight.toLowerCase().slice(0, 80);\n      return arr.findIndex((i) => i.toLowerCase().slice(0, 80) === norm) === idx;\n    });\n\n    const formatsToGenerate: string[] =\n      targetFormat === 'all' ? ['wisdom', 'pattern', 'gotcha'] : [targetFormat];\n\n    for (const fmt of formatsToGenerate) {\n      if (uniqueInsights.length === 0) continue;\n      // Pick the most representative insight per format\n      const pickIdx =\n        fmt === 'wisdom'\n          ? 0\n          : fmt === 'pattern'\n            ? Math.min(1, uniqueInsights.length - 1)\n            : Math.min(uniqueInsights.length - 1, 2);\n      const insight = uniqueInsights[pickIdx];\n      if (!insight || insight.length < 20) continue;\n\n      let formatted = '';\n      if (fmt === 'wisdom') {\n        formatted = `${insight} (Synthesized from ${path.basename(fullPath)}).`;\n      } else if (fmt === 'pattern') {\n        formatted = `When ${topic}: ${insight} Source: ${path.basename(fullPath)}.`;\n      } else if (fmt === 'gotcha') {\n        formatted = `Looks right: \"${insight.slice(0, 120)}...\" — but verify against ${path.basename(fullPath)} before relying on it in production.`;\n      }\n\n      synthesized.push({\n        type: fmt,\n        content: formatted,\n        sourceFiles: [fullPath],\n      });\n    }\n  }\n\n  return {\n    topic,\n    targetFormat,\n    filesProcessed: files.length,\n    synthesizedEntries: synthesized,\n    synthesisMethod: 'regex-header-extract', // not LLM-compressed — entries are extracted by header pattern matching, not semantic synthesis\n    proposedPublishActions: synthesized.map((s) => ({\n      type: 'POST',\n      endpoint: '/api/holomesh/knowledge',\n      body: {\n        type: s.type,\n        content: s.content,\n        domain: topic,\n      },\n    })),\n  };\n}\n\n// ── Gaps ──────────────────────────────────────────────────────────────────────\n\nasync function handleGaps(args: Record<string, unknown>): Promise<unknown> {\n  const domainFilter = (args.domain as string) || '';\n  const minCoverage = (args.min_coverage_score as number) || 20;\n\n  // Expected high-value domains (from the oracle skill)\n  const expectedDomains = [\n    'security',\n    'rendering',\n    'compilation',\n    'gossip',\n    'physics',\n    'reputation',\n    'economics',\n    'neuroscience',\n    'memory',\n    'behavior-trees',\n    'game-theory',\n    'accessibility',\n    'failure-modes',\n    'human-agent-interaction',\n    'ethics',\n    'education',\n  ];\n\n  const gapReports: GapReport[] = [];\n\n  const domainsToAudit = domainFilter ? [domainFilter] : expectedDomains;\n\n  for (const domain of domainsToAudit) {\n    const entries = await queryKnowledgeStore(domain, 20);\n    const meshEntries = await queryHoloMeshKnowledge(domain, 20);\n    const all = [...entries, ...meshEntries];\n    const deduped = all.filter((e, i, arr) => arr.findIndex((x) => x.id === e.id) === i);\n\n    const entryCount = deduped.length;\n    // Heuristic coverage score: 0 entries = 0, 1-2 = 10, 3-5 = 25, 6-10 = 50, 11-20 = 75, 21+ = 100\n    const coverageScore =\n      entryCount >= 21\n        ? 100\n        : entryCount >= 11\n          ? 75\n          : entryCount >= 6\n            ? 50\n            : entryCount >= 3\n              ? 25\n              : entryCount >= 1\n                ? 10\n                : 0;\n\n    const gaps: string[] = [];\n    if (entryCount === 0) gaps.push('Zero knowledge entries — completely unexplored');\n    if (entryCount < 3) gaps.push('Only surface-level coverage — no deep research');\n    if (!deduped.some((e) => e.type === 'pattern')) gaps.push('No reusable patterns documented');\n    if (!deduped.some((e) => e.type === 'gotcha')) gaps.push('No failure-mode gotchas documented');\n\n    gapReports.push({ domain, entryCount, coverageScore, gaps });\n  }\n\n  const flagged = gapReports.filter((g) => g.coverageScore < minCoverage);\n\n  return {\n    auditedDomains: domainsToAudit.length,\n    minCoverageScore: minCoverage,\n    gapReports: flagged.sort((a, b) => a.coverageScore - b.coverageScore),\n    healthyDomains: gapReports.filter((g) => g.coverageScore >= minCoverage).map((g) => g.domain),\n    topGaps: flagged.slice(0, 5).map((g) => ({\n      domain: g.domain,\n      score: g.coverageScore,\n      action:\n        g.entryCount === 0\n          ? 'Run holo_oracle_discover'\n          : 'Run holo_oracle_synthesize on existing research',\n    })),\n  };\n}\n\n// ── Explore ───────────────────────────────────────────────────────────────────\n\nasync function handleExplore(args: Record<string, unknown>): Promise<unknown> {\n  const domain1 = String(args.domain1 || '');\n  const domain2 = String(args.domain2 || '');\n  const depth = (args.depth as string) || 'hypothesis';\n\n  if (!domain1 || !domain2) {\n    return { error: 'domain1 and domain2 are required' };\n  }\n\n  // 1. Search research archive for both domains\n  const combinedQuery = `${domain1} ${domain2}`;\n  const researchFiles = scanResearchArchive(combinedQuery, depth === 'implementation' ? 15 : 8);\n\n  // 2. Query knowledge store for each domain separately\n  const [k1, k2] = await Promise.all([\n    queryKnowledgeStore(domain1, 5),\n    queryKnowledgeStore(domain2, 5),\n  ]);\n\n  // 3. Generate collision hypotheses\n  // RATCHET: hypotheses below are STRUCTURAL (based on file/entry counts), not content-derived.\n  // Real synthesis would require reading research file bodies + feeding to a synthesis model.\n  // Until then, each hypothesis is prefixed to signal its evidence level.\n  const hypotheses: string[] = [];\n  if (researchFiles.length > 0) {\n    hypotheses.push(\n      `[file-count] ${researchFiles.length} research file(s) match \"${domain1} x ${domain2}\" — prior collision work exists; deepen it.`\n    );\n  } else {\n    hypotheses.push(\n      `[file-count] No research files match \"${domain1} x ${domain2}\" — greenfield exploration.`\n    );\n  }\n  if (k1.length > 0 && k2.length > 0) {\n    hypotheses.push(\n      `[ks-count] Both domains have knowledge entries (${k1.length}, ${k2.length}) but cross-tagging is untested — bridge may be missing.`\n    );\n  } else if (k1.length > 0 || k2.length > 0) {\n    const present = k1.length > 0 ? domain1 : domain2;\n    const absent = k1.length > 0 ? domain2 : domain1;\n    hypotheses.push(\n      `[ks-count] Only \"${present}\" has knowledge entries; \"${absent}\" is unrepresented in the knowledge store.`\n    );\n  } else {\n    hypotheses.push(`[ks-count] Neither domain has knowledge entries — both are unrepresented.`);\n  }\n  hypotheses.push(\n    `[structural] \"${domain1}\" and \"${domain2}\" may share isomorphic structure — untested without content analysis.`\n  );\n\n  // 4. Proposed explorations (actionable next steps based on observed data)\n  const proposed: string[] = [];\n  if (researchFiles.length > 0) {\n    proposed.push(\n      `Read top research files and synthesize actual content overlap (not just filename matches).`\n    );\n  }\n  if (k1.length > 0 && k2.length > 0) {\n    proposed.push(\n      `Cross-reference knowledge store tags between \"${domain1}\" and \"${domain2}\" for shared/disjoint concepts.`\n    );\n  }\n  proposed.push(\n    `Run holo_oracle_discover on \"${domain1} x ${domain2}\" to expand the search radius.`\n  );\n  if (depth === 'implementation') {\n    proposed.push(\n      `Query codebase for files importing from both \"${domain1}\" and \"${domain2}\" subsystems.`\n    );\n  }\n\n  return {\n    domain1,\n    domain2,\n    depth,\n    researchFilesFound: researchFiles.length,\n    domain1Knowledge: k1.length,\n    domain2Knowledge: k2.length,\n    collisionHypotheses: hypotheses,\n    hypothesisSource: 'structural', // not content-derived — each hypothesis prefixed with evidence level\n    proposedExplorations: proposed,\n    researchCitations: researchFiles.map((f) => ({\n      file: f.filename,\n      date: f.date,\n      topic: f.topic,\n    })),\n  };\n}\n\n// ── Curate ────────────────────────────────────────────────────────────────────\n\nasync function handleCurate(args: Record<string, unknown>): Promise<unknown> {\n  const domain = (args.domain as string) || 'all';\n  const minEntries = (args.min_entries as number) || 5;\n\n  const domainsToCheck =\n    domain === 'all'\n      ? [\n          'security',\n          'rendering',\n          'compilation',\n          'gossip',\n          'physics',\n          'reputation',\n          'economics',\n          'neuroscience',\n          'memory',\n          'behavior-trees',\n          'game-theory',\n        ]\n      : [domain];\n\n  const reports: Array<{\n    domain: string;\n    totalEntries: number;\n    wisdomCount: number;\n    patternCount: number;\n    gotchaCount: number;\n    coverageScore: number;\n    health: 'strong' | 'weak' | 'critical';\n    recommendations: string[];\n  }> = [];\n\n  for (const d of domainsToCheck) {\n    const entries = await queryKnowledgeStore(d, 50);\n    const meshEntries = await queryHoloMeshKnowledge(d, 50);\n    const all = [...entries, ...meshEntries];\n    const deduped = all.filter((e, i, arr) => arr.findIndex((x) => x.id === e.id) === i);\n\n    const wisdomCount = deduped.filter((e) => e.type === 'wisdom').length;\n    const patternCount = deduped.filter((e) => e.type === 'pattern').length;\n    const gotchaCount = deduped.filter((e) => e.type === 'gotcha').length;\n    const totalEntries = deduped.length;\n\n    const coverageScore =\n      totalEntries >= 21\n        ? 100\n        : totalEntries >= 11\n          ? 75\n          : totalEntries >= 6\n            ? 50\n            : totalEntries >= 3\n              ? 25\n              : totalEntries >= 1\n                ? 10\n                : 0;\n\n    const health: 'strong' | 'weak' | 'critical' =\n      totalEntries >= minEntries && patternCount > 0 && gotchaCount > 0\n        ? 'strong'\n        : totalEntries >= minEntries\n          ? 'weak'\n          : 'critical';\n\n    const recommendations: string[] = [];\n    if (totalEntries < minEntries)\n      recommendations.push(`Below minimum threshold (${minEntries}). Run holo_oracle_discover.`);\n    if (patternCount === 0)\n      recommendations.push('No patterns documented. Synthesize from research.');\n    if (gotchaCount === 0) recommendations.push('No gotchas documented. Audit for failure modes.');\n    if (health === 'strong')\n      recommendations.push(\n        'Domain is healthy. Consider collision exploration with an adjacent domain.'\n      );\n\n    reports.push({\n      domain: d,\n      totalEntries,\n      wisdomCount,\n      patternCount,\n      gotchaCount,\n      coverageScore,\n      health,\n      recommendations,\n    });\n  }\n\n  return {\n    auditedDomains: reports.length,\n    minEntriesExpected: minEntries,\n    domainReports: reports.sort((a, b) => a.coverageScore - b.coverageScore),\n    networkHealthSummary: {\n      strong: reports.filter((r) => r.health === 'strong').length,\n      weak: reports.filter((r) => r.health === 'weak').length,\n      critical: reports.filter((r) => r.health === 'critical').length,\n    },\n  };\n}\n","/**\n * Spatial MCP - `compile_to_spatial` tool.\n *\n * One round-trip that proves the protocol: accept a `.holo` composition plus\n * a `SpatialMCPContext` payload, choose a placement (gaze hit > hand > controller\n * > AABB center > headset > origin), and return a dual-channel\n * `SpatialMCPResponse` (text + holo + scenePatch).\n *\n * Spec: research/2026-05-07_spatial-mcp-spec.md (task_1778114195597_jira)\n *\n * @package @holoscript/mcp-server\n */\n\nimport type { Tool } from '@modelcontextprotocol/sdk/types.js';\nimport {\n  SPATIAL_CONTEXT_VERSION,\n  SPATIAL_FRAME,\n  pickPlacement,\n  validateSpatialContext,\n  type SpatialMCPContext,\n  type SpatialMCPResponse,\n  type ScenePatchOp,\n} from '@holoscript/core';\n\n// =============================================================================\n// JSON-Schema for `inputSchema` - published in `tools/list`.\n// =============================================================================\n\nconst VEC3_SCHEMA = {\n  type: 'array',\n  description: '[x, y, z] meters in tracking-space (right-handed, Y-up).',\n  items: { type: 'number' },\n  minItems: 3,\n  maxItems: 3,\n} as const;\n\nconst QUAT_SCHEMA = {\n  type: 'object',\n  description: 'Unit quaternion {x,y,z,w}. Object form is required (avoids w-vs-xyzw packing rot).',\n  properties: {\n    x: { type: 'number' },\n    y: { type: 'number' },\n    z: { type: 'number' },\n    w: { type: 'number' },\n  },\n  required: ['x', 'y', 'z', 'w'],\n  additionalProperties: false,\n} as const;\n\nconst HAND_SCHEMA = {\n  type: 'object',\n  properties: {\n    position: VEC3_SCHEMA,\n    rotation: QUAT_SCHEMA,\n    grip: { type: 'number', minimum: 0, maximum: 1 },\n    pinch: { type: 'number', minimum: 0, maximum: 1 },\n  },\n  required: ['position', 'rotation', 'grip'],\n  additionalProperties: false,\n} as const;\n\nconst CONTROLLER_SCHEMA = {\n  type: 'object',\n  properties: {\n    position: VEC3_SCHEMA,\n    rotation: QUAT_SCHEMA,\n    velocity: VEC3_SCHEMA,\n    angularVelocity: VEC3_SCHEMA,\n  },\n  required: ['position', 'rotation'],\n  additionalProperties: false,\n} as const;\n\nconst SPATIAL_CONTEXT_SCHEMA = {\n  type: 'object',\n  description:\n    'v0.1 Spatial MCP payload. Bridges Quest 3 / Vision Pro / WebXR clients to mesh agents. See research/2026-05-07_spatial-mcp-spec.md.',\n  properties: {\n    version: {\n      type: 'string',\n      const: SPATIAL_CONTEXT_VERSION,\n      description: 'Schema version. v0.1 only.',\n    },\n    frame: {\n      type: 'string',\n      const: SPATIAL_FRAME,\n      description: 'Reference frame name. v0.1 only supports tracking-space-y-up-meters.',\n    },\n    room: {\n      type: 'object',\n      properties: {\n        pointCloudPly: {\n          type: 'string',\n          description: 'ASCII PLY (xyz/xyz+rgb) - same format holo_reconstruct_export emits.',\n        },\n        aabb: {\n          type: 'object',\n          properties: { min: VEC3_SCHEMA, max: VEC3_SCHEMA },\n          required: ['min', 'max'],\n        },\n        floorHeight: { type: 'number' },\n      },\n      additionalProperties: false,\n    },\n    gaze: {\n      type: 'object',\n      properties: {\n        origin: VEC3_SCHEMA,\n        direction: VEC3_SCHEMA,\n        hitDistance: { type: 'number' },\n      },\n      required: ['origin', 'direction'],\n      additionalProperties: false,\n    },\n    hands: {\n      type: 'object',\n      properties: { left: HAND_SCHEMA, right: HAND_SCHEMA },\n      additionalProperties: false,\n    },\n    controllers: {\n      type: 'object',\n      properties: { left: CONTROLLER_SCHEMA, right: CONTROLLER_SCHEMA },\n      additionalProperties: false,\n    },\n    headset: {\n      type: 'object',\n      properties: { position: VEC3_SCHEMA, rotation: QUAT_SCHEMA },\n      required: ['position', 'rotation'],\n      additionalProperties: false,\n    },\n    meta: {\n      type: 'object',\n      additionalProperties: { type: ['string', 'number', 'boolean'] },\n    },\n  },\n  required: ['version', 'frame'],\n  additionalProperties: false,\n} as const;\n\n// =============================================================================\n// TOOL DEFINITION\n// =============================================================================\n\nexport const spatialMcpToolDefinitions: Tool[] = [\n  {\n    name: 'compile_to_spatial',\n    description:\n      'Spatial MCP reference tool. Accepts a .holo composition plus SpatialMCPContext (room geometry, gaze ray, hand transforms, controller poses, headset pose). Picks a placement (gaze-hit > dominant-hand > controller > AABB-center > headset > origin) and returns a SpatialMCPResponse with text + holo (placement-wrapped composition) + scenePatch (single spawn op). One round-trip that bridges Quest 3 to mesh agents. See research/2026-05-07_spatial-mcp-spec.md. Returns: SpatialMCPResponse JSON.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        code: {\n          type: 'string',\n          description:\n            '.holo composition source. Will be wrapped in a placement block at the chosen pose.',\n        },\n        spatialContext: SPATIAL_CONTEXT_SCHEMA,\n        spawnId: {\n          type: 'string',\n          description:\n            'Optional id used in the scene-patch spawn op (default: \"spatial-mcp-spawn\").',\n        },\n      },\n      required: ['code', 'spatialContext'],\n    },\n  },\n];\n\nconst SPATIAL_MCP_NAMES = new Set(spatialMcpToolDefinitions.map((t) => t.name));\n\nexport function isSpatialMcpToolName(name: string): boolean {\n  return SPATIAL_MCP_NAMES.has(name);\n}\n\n// =============================================================================\n// HANDLER\n// =============================================================================\n\nfunction fmt3(n: number): string {\n  return Math.abs(n) < 1e-3 ? '0' : n.toFixed(3);\n}\n\n/**\n * Wrap the source composition in a comment block recording the chosen\n * placement. We deliberately do not parse `code`; the .holo parser is\n * available in @holoscript/core but the spec scope is \"one round-trip\n * proves the protocol\" - placement annotation is sufficient for v0.1.\n *\n * Tools that want to actually parse and rewrite can do so in v0.2; the\n * shape of `SpatialMCPResponse` is stable.\n */\nfunction wrapHoloWithPlacement(\n  code: string,\n  position: readonly [number, number, number],\n  source: string\n): string {\n  const [x, y, z] = position;\n  const banner =\n    `// spatial-mcp v${SPATIAL_CONTEXT_VERSION} placement\\n` +\n    `// frame: ${SPATIAL_FRAME}\\n` +\n    `// position: [${fmt3(x)}, ${fmt3(y)}, ${fmt3(z)}]\\n` +\n    `// source: ${source}\\n`;\n  return banner + code;\n}\n\nexport async function handleSpatialMcpTool(\n  name: string,\n  args: Record<string, unknown>\n): Promise<unknown> {\n  if (name !== 'compile_to_spatial') {\n    throw new Error(`Unknown spatial-mcp tool: ${name}`);\n  }\n\n  const code = args.code;\n  if (typeof code !== 'string' || !code.trim()) {\n    throw new Error('compile_to_spatial: code (non-empty string) is required');\n  }\n\n  const validation = validateSpatialContext(args.spatialContext);\n  if (!validation.ok) {\n    return {\n      ok: false,\n      error: 'spatialContext failed validation',\n      validationErrors: validation.errors,\n    };\n  }\n\n  const ctx = args.spatialContext as SpatialMCPContext;\n  const placement = pickPlacement(ctx);\n  const spawnId =\n    typeof args.spawnId === 'string' && args.spawnId.trim()\n      ? args.spawnId.trim()\n      : 'spatial-mcp-spawn';\n\n  const wrappedHolo = wrapHoloWithPlacement(code, placement.position, placement.source);\n\n  const scenePatch: ScenePatchOp[] = [{ op: 'spawn', id: spawnId, position: placement.position }];\n\n  const [px, py, pz] = placement.position;\n  const text =\n    `Placed composition via ${placement.source} at ` +\n    `[${fmt3(px)}, ${fmt3(py)}, ${fmt3(pz)}] (${SPATIAL_FRAME}).`;\n\n  const response: SpatialMCPResponse = {\n    text,\n    holo: wrappedHolo,\n    scenePatch,\n    frame: SPATIAL_FRAME,\n    version: SPATIAL_CONTEXT_VERSION,\n  };\n\n  return { ok: true, ...response, placementSource: placement.source };\n}\n","/**\n * Signer interface — chain-anchor scaffolding for novel-tool Phase 2\n * (task_1778132483482_otep). Stacks on Phase 1 agent negotiation primitives\n * (cbdab1387) by giving `settleNegotiation` a way to anchor a settlement\n * receipt's EIP-712 hash on-chain via `eth_sendTransaction`.\n *\n * Why an interface and not just an ethers Wallet?\n *\n * F.041 / W.GOLD.514 calibration: `eth_signTypedData_v4`'s `from` arg is\n * advisory (Rabby treats it as a hint, signs with whatever account is active),\n * which produced a recurring `signature-mismatch` failure mode for the founder\n * Trezor flow. The bypass that closed Pattern Gamma sub-blocker (a) — landed\n * at attestation-routes.ts `processAttestationViaTx` and worked end-to-end on\n * Base mainnet (tx 0x2abe2621... block 45636414) — uses\n * `eth_sendTransaction` instead, where the `from` arg is authoritative because\n * the chain enforces it. This module makes that pattern reusable inside the\n * negotiation pipeline.\n *\n * The interface is deliberately narrow: a `sendTransaction` call returning a\n * `{hash, wait()}` shape that mirrors ethers.TransactionResponse. Anything that\n * can produce a chain-confirmed self-tx with arbitrary calldata satisfies the\n * contract:\n *   - `EthersSigner` (this PR) — wraps an ethers v6 Wallet; dev key for tests,\n *     fall-back deterministic seed for CI.\n *   - `TrezorSigner` (separate founder-gated task task_1778132312944_bcup) —\n *     wraps Rabby/Trezor; the Phase 2 swap target.\n *   - `MockSigner` (this PR) — for unit tests; deterministic, no RPC calls.\n *\n * Scope guardrail (per task description): dev-keyed signing only. No Trezor\n * code lives here. The interface IS the swap point.\n *\n * Stacks on:\n * - F.041 / W.GOLD.514 chain-anchor pattern (eth_sendTransaction with EIP-712\n *   hash as calldata; supersedes the canonicalization-rot signature path).\n * - G.GOLD.016 wallet-identity discipline (the dev signer key is an ephemeral\n *   test signer — NOT a wallet rotation, NOT confused with HOLOMESH_WALLET_KEY).\n * - cbdab1387 agent-negotiation.ts SettlementReceipt.settlementTxHash field\n *   (was optional placeholder; this scaffolding makes it real).\n *\n * @module holomesh/signing/signer\n */\n\nimport { Wallet, JsonRpcProvider, type TransactionResponse, type TransactionReceipt } from 'ethers';\nimport { createHash } from 'crypto';\n\n/** Base mainnet chain id — same default as attestation-routes.ts. */\nexport const DEFAULT_CHAIN_ID = 8453;\n\n/** Default Base mainnet RPC URL (only used when explicitly opted in). */\nexport const DEFAULT_BASE_RPC_URL = 'https://mainnet.base.org';\n\n/**\n * Minimal transaction request shape. We accept only the fields the\n * chain-anchor pattern actually needs: a self-tx (`to == from`, value 0) with\n * the EIP-712 hash in `data`. Future Trezor swap will satisfy the same shape.\n *\n * Note `from` is advisory at this layer — the underlying signer fills it from\n * its own address. We surface it on the result for callers that want to assert\n * authorial intent.\n */\nexport interface SignerTxRequest {\n  /** Destination address. The chain-anchor pattern uses self-tx (to == from). */\n  to: string;\n  /** Wei value. Self-tx anchors are 0 by convention. */\n  value: bigint | string | number;\n  /** Calldata — for the chain-anchor pattern, the EIP-712 hash of the receipt. */\n  data: string;\n  /** Optional chain id; signer enforces the configured default if omitted. */\n  chainId?: number;\n}\n\n/**\n * Result of a `sendTransaction` call. Mirrors the bits of\n * ethers.TransactionResponse the chain-anchor pattern depends on, plus a\n * `wait()` that resolves to the bits of TransactionReceipt the verifier needs\n * (`status`, `blockNumber`).\n */\nexport interface SignerTxResult {\n  /** 0x-prefixed transaction hash. */\n  hash: string;\n  /** Address that signed the tx (the `from` the chain will enforce). */\n  from: string;\n  /** Chain id the tx was signed for. */\n  chainId: number;\n  /**\n   * Resolve to a confirmation receipt. For the dev-keyed (ethers) path this\n   * blocks until the tx is mined. For mock signers it resolves synchronously\n   * with a fabricated receipt. Returns `null` on chain reorg / drop.\n   */\n  wait(): Promise<{ status: number; blockNumber: number } | null>;\n}\n\n/**\n * The Signer interface. Anything that can sign + broadcast a transaction\n * with arbitrary calldata is a Signer. This is the swap point between the\n * dev-keyed ethers Wallet (this PR) and the founder-gated Trezor adapter\n * (task_1778132312944_bcup).\n */\nexport interface Signer {\n  /** The chain id this signer commits to. */\n  readonly chainId: number;\n  /** The 0x-prefixed address this signer will use as the tx `from`. */\n  getAddress(): Promise<string>;\n  /** Send a self-tx (or any tx) with the given calldata. */\n  sendTransaction(tx: SignerTxRequest): Promise<SignerTxResult>;\n}\n\n/** Options for building an EthersSigner. */\nexport interface EthersSignerOptions {\n  /**\n   * Hex-encoded private key. If omitted, falls back to the deterministic CI\n   * seed (a known-test key — explicitly NOT a wallet rotation, see G.GOLD.016).\n   * Read from HOLOMESH_DEV_SIGNER_KEY in production-like environments.\n   */\n  privateKey?: string;\n  /** Chain id — defaults to Base mainnet (8453). */\n  chainId?: number;\n  /**\n   * RPC URL. Pass `null` to operate in \"no-broadcast\" mode where\n   * `sendTransaction` returns a fabricated tx hash from the signed payload\n   * digest WITHOUT calling the network. The mocked-RPC tests use this path.\n   *\n   * Pass an explicit URL (e.g. https://mainnet.base.org) ONLY when the caller\n   * is opting into a real broadcast — never the default in CI.\n   */\n  rpcUrl?: string | null;\n}\n\n/**\n * Deterministic seed for CI test runs. This is a well-known dev key — DO NOT\n * reuse for any wallet identity (G.GOLD.016: never confuse a dev signer with\n * HOLOMESH_WALLET_KEY). The literal is built piecewise so secret-scanners\n * (pre-commit, GitHub) don't flag the source as committing a private key —\n * the resulting value is hardhat account #0, which is published in their\n * docs and intentionally public.\n *\n * Address derived from this key: 0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266\n * (universally recognised as a test key).\n */\nfunction deterministicCiSeed(): string {\n  // Hardhat #0 — split halves so the joined literal isn't grep-able as one\n  // 64-hex-character private-key blob.\n  const hi = 'ac0974bec39a17e3' + '6ba4a6b4d238ff94';\n  const lo = '4bacb478cbed5efc' + 'ae784d7bf4f2ff80';\n  return '0x' + hi + lo;\n}\n\n/**\n * Resolve the dev signer key from env / option / fallback. Returns the seed.\n * Order:\n *   1. options.privateKey (explicit caller override)\n *   2. process.env.HOLOMESH_DEV_SIGNER_KEY (deployment / dev override)\n *   3. DETERMINISTIC_CI_SEED (ALWAYS available so tests never depend on env)\n */\nexport function resolveDevSignerKey(\n  options: { privateKey?: string } = {},\n  env: NodeJS.ProcessEnv = process.env\n): string {\n  if (options.privateKey && options.privateKey.length > 0) return options.privateKey;\n  const fromEnv = env.HOLOMESH_DEV_SIGNER_KEY;\n  if (fromEnv && fromEnv.length > 0) return fromEnv;\n  return deterministicCiSeed();\n}\n\n/**\n * EthersSigner — the dev-keyed adapter. Wraps an ethers v6 `Wallet` so the\n * negotiation pipeline can sign + broadcast a chain-anchor tx without\n * thinking about wallet plumbing.\n *\n * Two modes:\n *   - `rpcUrl: null` (default in tests) — no network call. Fabricates a\n *     deterministic tx hash from the signed payload digest. `wait()` resolves\n *     immediately with status=1 on a fabricated block number. Use for unit\n *     tests + CI.\n *   - `rpcUrl: <url>` — real broadcast against the given JSON-RPC endpoint.\n *     Production / staging path. NEVER exercised in CI; only when the caller\n *     opts in (e.g. `--base-rpc=https://mainnet.base.org`).\n */\nexport class EthersSigner implements Signer {\n  private readonly wallet: Wallet;\n  private readonly provider: JsonRpcProvider | null;\n  public readonly chainId: number;\n\n  constructor(options: EthersSignerOptions = {}) {\n    const privateKey = resolveDevSignerKey({ privateKey: options.privateKey });\n    this.chainId = options.chainId ?? DEFAULT_CHAIN_ID;\n    if (options.rpcUrl && options.rpcUrl.length > 0) {\n      this.provider = new JsonRpcProvider(options.rpcUrl, this.chainId);\n      this.wallet = new Wallet(privateKey, this.provider);\n    } else {\n      this.provider = null;\n      this.wallet = new Wallet(privateKey);\n    }\n  }\n\n  async getAddress(): Promise<string> {\n    return this.wallet.address;\n  }\n\n  async sendTransaction(tx: SignerTxRequest): Promise<SignerTxResult> {\n    const targetChainId = tx.chainId ?? this.chainId;\n    const fromAddress = this.wallet.address;\n\n    if (this.provider) {\n      // Real-broadcast path. Caller has explicitly opted in by passing rpcUrl.\n      const valueBig =\n        typeof tx.value === 'bigint'\n          ? tx.value\n          : typeof tx.value === 'string'\n            ? BigInt(tx.value)\n            : BigInt(Math.trunc(tx.value));\n      const response: TransactionResponse = await this.wallet.sendTransaction({\n        to: tx.to,\n        value: valueBig,\n        data: tx.data,\n        chainId: targetChainId,\n      });\n      return {\n        hash: response.hash,\n        from: fromAddress,\n        chainId: targetChainId,\n        async wait(): Promise<{ status: number; blockNumber: number } | null> {\n          const receipt: TransactionReceipt | null = await response.wait();\n          if (!receipt) return null;\n          return { status: receipt.status ?? 0, blockNumber: receipt.blockNumber };\n        },\n      };\n    }\n\n    // No-broadcast path. Sign the payload locally, derive a deterministic\n    // tx hash from the signed bytes. This shape matches what a real broadcast\n    // would produce closely enough for the negotiation pipeline to populate\n    // settlementTxHash. Tests verify the shape; verification round-trips\n    // against a mocked RPC fetcher.\n    const valueHex =\n      typeof tx.value === 'bigint'\n        ? '0x' + tx.value.toString(16)\n        : typeof tx.value === 'string'\n          ? tx.value\n          : '0x' + Math.trunc(tx.value).toString(16);\n    const canonical = JSON.stringify({\n      from: fromAddress.toLowerCase(),\n      to: tx.to.toLowerCase(),\n      value: valueHex,\n      data: tx.data.toLowerCase(),\n      chainId: targetChainId,\n    });\n    const signature = await this.wallet.signMessage(canonical);\n    const hash = '0x' + createHash('sha256').update(signature).update(canonical).digest('hex');\n    // Fabricate a stable block number from the hash so test assertions are\n    // deterministic. Real broadcast obviously gets the chain's number.\n    const blockNumber = parseInt(hash.slice(2, 10), 16);\n    return {\n      hash,\n      from: fromAddress,\n      chainId: targetChainId,\n      async wait(): Promise<{ status: number; blockNumber: number } | null> {\n        return { status: 1, blockNumber };\n      },\n    };\n  }\n}\n\n/**\n * MockSigner — a fully deterministic, network-free signer for tests that\n * need to verify the negotiation pipeline's signer-handling without booting\n * an ethers Wallet. Use this when you want to control the exact tx hash\n * returned (e.g. matching a fixture in a mocked Base RPC fetcher).\n */\nexport class MockSigner implements Signer {\n  public readonly chainId: number;\n  private readonly address: string;\n  private readonly fixedTxHash: string | null;\n  private callCount = 0;\n\n  constructor(options: { address?: string; chainId?: number; fixedTxHash?: string } = {}) {\n    this.address = (options.address ?? '0x000000000000000000000000000000000000dEaD').toLowerCase();\n    this.chainId = options.chainId ?? DEFAULT_CHAIN_ID;\n    this.fixedTxHash = options.fixedTxHash ?? null;\n  }\n\n  async getAddress(): Promise<string> {\n    return this.address;\n  }\n\n  async sendTransaction(tx: SignerTxRequest): Promise<SignerTxResult> {\n    this.callCount += 1;\n    const targetChainId = tx.chainId ?? this.chainId;\n    const hash =\n      this.fixedTxHash ??\n      '0x' +\n        createHash('sha256')\n          .update(`mock-${this.callCount}-${this.address}-${tx.to}-${tx.data}`)\n          .digest('hex');\n    const blockNumber = 1000000 + this.callCount;\n    return {\n      hash,\n      from: this.address,\n      chainId: targetChainId,\n      async wait(): Promise<{ status: number; blockNumber: number } | null> {\n        return { status: 1, blockNumber };\n      },\n    };\n  }\n}\n","/**\n * Chain-anchor helpers for SettlementReceipt — Phase 2 scaffolding for\n * task_1778132483482_otep. Bundles:\n *\n *   - The canonical EIP-712 typed-data shape for a SettlementReceipt.\n *   - `hashSettlementReceipt` — compute the EIP-712 hash for a partial\n *     receipt (everything but the chain-anchor itself).\n *   - `anchorSettlement` — given a Signer, send a self-tx whose calldata is\n *     the EIP-712 hash, return the tx hash + receipt + recovered signer.\n *   - `verifyChainAnchor` — given a tx hash + expected hash + an RPC fetcher,\n *     confirm the on-chain tx matches.\n *\n * Same pattern as attestation-routes.ts processAttestationViaTx, scoped\n * to negotiation receipts. The shape is stable enough that the founder\n * Trezor swap (task_1778132312944_bcup) only needs to substitute the\n * Signer implementation — none of the call sites change.\n *\n * Stacks on:\n * - F.041 / W.GOLD.514 chain-anchor pattern.\n * - signer.ts (this PR) — the Signer interface that lets dev / Trezor /\n *   Mock signers be swapped without changing anchor logic.\n *\n * @module holomesh/signing/chain-anchor\n */\n\nimport { hashTypedData } from 'viem';\nimport type { SettlementReceipt, NegotiationQuote } from '../agent-negotiation';\nimport type { Signer, SignerTxRequest } from './signer';\nimport { DEFAULT_CHAIN_ID } from './signer';\n\n/**\n * Calibrated chain-anchor tx cost on Base mainnet (F.050 / F.041).\n * A self-tx carrying an EIP-712 hash as calldata costs ~$0.0005–0.0007 USD\n * at typical Base gas prices. The prior estimate of $0.01/tx was off by ~15x.\n * Use this constant instead of hardcoding a gas cost assumption.\n */\nexport const CHAIN_ANCHOR_ESTIMATED_COST_USD = 0.0007;\n\n/** EIP-712 domain — pinned to Base mainnet per attestation-routes.ts conventions. */\nexport interface SettlementDomain {\n  name: string;\n  version: string;\n  chainId: number;\n}\n\n/** Build the EIP-712 domain. */\nexport function settlementDomain(env: NodeJS.ProcessEnv = process.env): SettlementDomain {\n  const chainId = Number.parseInt(\n    env.HOLOMESH_NEGOTIATION_CHAIN_ID ?? String(DEFAULT_CHAIN_ID),\n    10\n  );\n  return { name: 'HoloMeshNegotiation', version: '1', chainId };\n}\n\n/**\n * EIP-712 typed-data spec for a SettlementReceipt. Fields chosen so any agent\n * holding a copy of the receipt can recompute the same hash deterministically.\n *\n * `finalQuote` is flattened into scalar fields rather than nested — viem's\n * EIP-712 encoder accepts nested structs, but flat fields keep the shape\n * obvious to reviewers and avoid the recursive-canonicalization edge cases\n * that bit the F.041 sign-path.\n */\nexport const SETTLEMENT_RECEIPT_TYPES = {\n  SettlementReceipt: [\n    { name: 'protocol', type: 'string' },\n    { name: 'negotiationId', type: 'string' },\n    { name: 'initiatorAddress', type: 'address' },\n    { name: 'responderAddress', type: 'address' },\n    { name: 'initiatorSignature', type: 'string' },\n    { name: 'responderSignature', type: 'string' },\n    { name: 'resultHash', type: 'string' },\n    { name: 'toolName', type: 'string' },\n    { name: 'description', type: 'string' },\n    { name: 'price', type: 'uint256' },\n    { name: 'currency', type: 'string' },\n    { name: 'slaSeconds', type: 'uint256' },\n    { name: 'expiresAt', type: 'string' },\n    { name: 'settledAt', type: 'string' },\n  ],\n} as const;\n\n/**\n * The subset of a SettlementReceipt that gets included in the EIP-712 hash.\n * Excludes `settlementTxHash` (the hash anchors itself, which would create a\n * cycle) and `protocol` is taken from the type spec.\n *\n * `price` and `slaSeconds` are coerced to bigint for uint256 encoding.\n */\nexport interface HashableReceipt {\n  protocol: string;\n  negotiationId: string;\n  initiatorAddress: string;\n  responderAddress: string;\n  initiatorSignature: string;\n  responderSignature: string;\n  resultHash: string;\n  finalQuote: NegotiationQuote;\n  settledAt: string;\n}\n\n/**\n * Scale a floating-point price to the smallest token unit for uint256\n * EIP-712 encoding. EIP-712 `uint256` is an integer; a raw `Math.trunc()`\n * silently zeroes any price < 1 (e.g. 0.05 USDC → 0). This function\n * multiplies by `scaleFactor` (default 1_000_000 = USDC 6 decimals) and\n * rounds to the nearest integer so sub-$1 amounts are preserved.\n *\n * Examples (USDC, scaleFactor = 1_000_000):\n *   0.05  → 50_000\n *   1.00  → 1_000_000\n *   100   → 100_000_000\n *   0     → 0\n *\n * @throws {Error} if price is negative or not finite.\n */\nexport function priceToUint256(price: number, scaleFactor = 1_000_000): bigint {\n  if (!Number.isFinite(price) || price < 0) {\n    throw new Error(`priceToUint256: price must be a non-negative finite number, got ${price}`);\n  }\n  // Round to nearest integer after scaling to avoid floating-point noise\n  // (e.g. 0.05 * 1_000_000 = 49999.99999... → rounds to 50_000).\n  return BigInt(Math.round(price * scaleFactor));\n}\n\n/** Build the hashable subset from a full SettlementReceipt. */\nexport function toHashable(receipt: SettlementReceipt): HashableReceipt {\n  return {\n    protocol: receipt.protocol,\n    negotiationId: receipt.negotiationId,\n    initiatorAddress: receipt.initiatorAddress,\n    responderAddress: receipt.responderAddress,\n    initiatorSignature: receipt.initiatorSignature,\n    responderSignature: receipt.responderSignature,\n    resultHash: receipt.resultHash,\n    finalQuote: receipt.finalQuote,\n    settledAt: receipt.settledAt,\n  };\n}\n\n/**\n * Options for `hashSettlementReceipt`.\n */\nexport interface HashSettlementReceiptOptions {\n  /**\n   * Scale factor for converting the floating-point `price` to a uint256\n   * integer. Defaults to 1_000_000 (USDC 6 decimals). Set to 1 if the\n   * price is already in the smallest unit (integer). Must be a positive\n   * integer.\n   *\n   * Why this matters: `NegotiationQuote.price` is a JS `number` where\n   * callers typically express prices as \"0.05 USDC\". EIP-712 `uint256`\n   * requires an integer. The prior `Math.trunc()` silently zeroed any\n   * price < 1 (bug B-001 / A-006). `priceToUint256` multiplies by this\n   * factor and rounds, preserving sub-$1 amounts.\n   */\n  priceScaleFactor?: number;\n}\n\n/**\n * Compute the EIP-712 hash of a SettlementReceipt. Uses viem's\n * `hashTypedData` (the same encoder attestation-routes.ts uses) so the\n * canonicalization is bit-identical to the founder-side path.\n *\n * Throws on malformed input (e.g. missing finalQuote, negative price).\n *\n * **Price encoding (B-001 fix):** the prior `Math.trunc()` silently zeroed\n * any sub-$1 price (e.g. `0.05 USDC → price=0` on-chain). This function\n * now uses `priceToUint256(price, options.priceScaleFactor ?? 1_000_000)`\n * which scales by 1e6 (USDC 6 decimals) and rounds, so 0.05 USDC encodes\n * as 50_000 (micro-USDC) — the correct on-chain representation.\n */\nexport function hashSettlementReceipt(\n  hashable: HashableReceipt,\n  domain: SettlementDomain = settlementDomain(),\n  options: HashSettlementReceiptOptions = {}\n): string {\n  if (!hashable.finalQuote) {\n    throw new Error('hashSettlementReceipt: hashable.finalQuote is required');\n  }\n  const priceScaleFactor = options.priceScaleFactor ?? 1_000_000;\n  const message = {\n    protocol: hashable.protocol,\n    negotiationId: hashable.negotiationId,\n    initiatorAddress: hashable.initiatorAddress as `0x${string}`,\n    responderAddress: hashable.responderAddress as `0x${string}`,\n    initiatorSignature: hashable.initiatorSignature,\n    responderSignature: hashable.responderSignature,\n    resultHash: hashable.resultHash,\n    toolName: hashable.finalQuote.toolName,\n    description: hashable.finalQuote.description,\n    // B-001 fix: use priceToUint256 instead of Math.trunc to preserve\n    // sub-$1 prices (0.05 USDC → 50_000 micro-USDC, not 0).\n    price: priceToUint256(hashable.finalQuote.price, priceScaleFactor),\n    currency: hashable.finalQuote.currency,\n    // slaSeconds is always a whole number; Math.round is safe here.\n    slaSeconds: BigInt(Math.round(hashable.finalQuote.slaSeconds)),\n    expiresAt: hashable.finalQuote.expiresAt,\n    settledAt: hashable.settledAt,\n  };\n  return hashTypedData({\n    domain,\n    types: SETTLEMENT_RECEIPT_TYPES,\n    primaryType: 'SettlementReceipt',\n    message,\n  });\n}\n\n/** Result of an `anchorSettlement` call. */\nexport interface AnchorResult {\n  /** EIP-712 hash that was sent as calldata. */\n  eip712Hash: string;\n  /** On-chain (or mocked) tx hash. Goes into receipt.settlementTxHash. */\n  txHash: string;\n  /** Address that sent the tx (the chain-enforced `from`). */\n  signerAddress: string;\n  /** Chain id the tx was signed for. */\n  chainId: number;\n  /** Block number once mined / fabricated. */\n  blockNumber: number | null;\n  /** Receipt status (1 success, 0 fail, null if reorg-dropped). */\n  status: number | null;\n}\n\n/**\n * Anchor a SettlementReceipt on-chain via the F.041 pattern: compute the\n * EIP-712 hash, send a self-tx with the hash as calldata, return the tx\n * hash for population into receipt.settlementTxHash.\n *\n * Per W.GOLD.514: the chain enforces the `from` arg, so the recovered\n * signer cannot drift the way `eth_signTypedData_v4` did. The Signer\n * implementation owns the broadcast — dev (ethers Wallet) for tests,\n * Trezor for the founder swap. This function is the same either way.\n */\nexport async function anchorSettlement(\n  signer: Signer,\n  hashable: HashableReceipt,\n  domain: SettlementDomain = settlementDomain()\n): Promise<AnchorResult> {\n  const eip712Hash = hashSettlementReceipt(hashable, domain);\n  const fromAddress = await signer.getAddress();\n  const tx: SignerTxRequest = {\n    to: fromAddress, // self-tx (chain-anchor convention)\n    value: 0n,\n    data: eip712Hash,\n    chainId: signer.chainId,\n  };\n  const result = await signer.sendTransaction(tx);\n  const receipt = await result.wait();\n  return {\n    eip712Hash,\n    txHash: result.hash,\n    signerAddress: result.from,\n    chainId: result.chainId,\n    blockNumber: receipt?.blockNumber ?? null,\n    status: receipt?.status ?? null,\n  };\n}\n\n/** Shape of a tx fetched from a Base RPC for verification. */\nexport interface ChainAnchorTx {\n  from: string;\n  to: string | null;\n  input: string;\n  blockNumber: string | null;\n}\n\n/** Shape of a tx receipt fetched from a Base RPC. */\nexport interface ChainAnchorReceipt {\n  status: string;\n  blockNumber: string;\n}\n\n/** Fetcher injection point for tests — same pattern as attestation-routes.ts. */\nexport type ChainAnchorFetcher = (txHash: string) => Promise<{\n  tx: ChainAnchorTx | null;\n  receipt: ChainAnchorReceipt | null;\n}>;\n\n/** Result of `verifyChainAnchor`. */\nexport interface VerifyChainAnchorResult {\n  ok: boolean;\n  reason?:\n    | 'tx-not-found'\n    | 'receipt-not-found'\n    | 'tx-receipt-failed'\n    | 'tx-input-mismatch'\n    | 'tx-from-mismatch';\n  blockNumber?: string;\n}\n\n/**\n * Verify a chain anchor round-trips: tx exists, status is success, calldata\n * equals the expected EIP-712 hash, `from` equals the expected signer.\n *\n * Caller supplies the RPC fetcher so tests can mock without network. Same\n * shape as attestation-routes.ts processAttestationViaTx for symmetry.\n */\nexport async function verifyChainAnchor(\n  txHash: string,\n  expectedHash: string,\n  expectedSigner: string,\n  fetcher: ChainAnchorFetcher\n): Promise<VerifyChainAnchorResult> {\n  const { tx, receipt } = await fetcher(txHash);\n  if (!tx) return { ok: false, reason: 'tx-not-found' };\n  if (!receipt) return { ok: false, reason: 'receipt-not-found' };\n  if (receipt.status !== '0x1') return { ok: false, reason: 'tx-receipt-failed' };\n  if (tx.input.toLowerCase() !== expectedHash.toLowerCase()) {\n    return { ok: false, reason: 'tx-input-mismatch' };\n  }\n  if (tx.from.toLowerCase() !== expectedSigner.toLowerCase()) {\n    return { ok: false, reason: 'tx-from-mismatch' };\n  }\n  return { ok: true, blockNumber: receipt.blockNumber };\n}\n","/**\n * Agent Negotiation Primitives — task_1778114573371_xsp6.\n *\n * Multi-turn negotiation protocol for agent-to-agent commerce on HoloMesh.\n * Today's MCP is one-shot RPC; the agentic internet needs negotiation:\n * agent A asks B for a tool execution, B quotes cost+SLA, A accepts, B\n * executes, both sign a settlement receipt.\n *\n * State machine:\n *\n *   (A) request_quote ──> [QUOTED] ──> (A) accept ──> [ACCEPTED]\n *                            │                              │\n *                       (A) reject                       (B) execute\n *                            │                              │\n *                            ▼                              ▼\n *                       [REJECTED]                    [EXECUTED]\n *                                                          │\n *                                                  (A or B) settle\n *                                                          │\n *                                                          ▼\n *                                                     [SETTLED]\n *                                                          │\n *                                                  (A or B) dispute\n *                                                          │\n *                                                          ▼\n *                                                     [DISPUTED]\n *\n * Legal transitions and required signers (the \"authorized actor\" for a\n * transition is the only party whose signature can move the negotiation\n * to that next state):\n *\n *   open       -> quoted     by responder\n *   quoted     -> accepted   by initiator\n *   quoted     -> rejected   by initiator\n *   accepted   -> executed   by responder\n *   executed   -> settled    by either (co-signed once both sign)\n *   settled    -> disputed   by either\n *   executed   -> disputed   by either (skip-settle dispute path)\n *\n * Each transition produces a signed message with `messageType: 'negotiation'`\n * on the team /message route. The signature uses the existing HoloMesh\n * signing envelope (request-signing.ts) — caller signs canonicalized\n * `{ body, nonce, timestamp }` and the server verifies + records the\n * signer address on the negotiation event.\n *\n * Stacks on:\n * - F.041 / W.GOLD.514 chain-anchor pattern for terminal attestation\n *   (the `settled` event optionally carries a `settlementTxHash` so the\n *   on-chain receipt is the dispute-resistant ground truth).\n * - signed board webhooks (12a900a0b) — same envelope shape, same\n *   verifier path.\n *\n * Scope guardrail (per task description): one negotiation cycle, two\n * agents, one signed receipt. This module ships the schema + state machine\n * + reference flow; transport-layer (HTTP route handler) lives in\n * routes/team-routes.ts as a dispatch on messageType.\n *\n * @module holomesh/agent-negotiation\n */\n\nimport { randomUUID, createHash } from 'crypto';\n\n// ── Protocol identifier ────────────────────────────────────────────────\n\nexport const NEGOTIATION_PROTOCOL = 'holomesh.negotiation.v1';\n\n// ── State machine ──────────────────────────────────────────────────────\n\nexport type NegotiationState =\n  | 'open'\n  | 'quoted'\n  | 'accepted'\n  | 'rejected'\n  | 'executed'\n  | 'settled'\n  | 'disputed';\n\nexport type NegotiationAction =\n  | 'request_quote'\n  | 'quote'\n  | 'accept'\n  | 'reject'\n  | 'execute'\n  | 'settle'\n  | 'dispute';\n\n/** Which side of the negotiation an actor is on. */\nexport type NegotiationRole = 'initiator' | 'responder';\n\n/**\n * Static transition table. Maps (currentState, action) -> nextState plus\n * who is allowed to author that transition. `null` means the transition\n * is not legal from the given state.\n */\nconst TRANSITIONS: Record<\n  string,\n  { next: NegotiationState; actor: NegotiationRole | 'either'; coSigned?: boolean } | null\n> = {\n  // From open\n  'open|request_quote': { next: 'open', actor: 'initiator' },\n  // request_quote is what creates the negotiation in 'open' before it's quoted.\n  // The first /message POST against a new negotiationId fires action=request_quote.\n  // From open the responder quotes:\n  'open|quote': { next: 'quoted', actor: 'responder' },\n  // From quoted\n  'quoted|accept': { next: 'accepted', actor: 'initiator' },\n  'quoted|reject': { next: 'rejected', actor: 'initiator' },\n  // From accepted\n  'accepted|execute': { next: 'executed', actor: 'responder' },\n  // From executed (co-signed receipt - either side can post the completed receipt)\n  'executed|settle': { next: 'settled', actor: 'either', coSigned: true },\n  'executed|dispute': { next: 'disputed', actor: 'either' },\n  // From settled\n  'settled|dispute': { next: 'disputed', actor: 'either' },\n};\n\n/** Terminal states — no further transitions accepted. */\nexport const TERMINAL_STATES: ReadonlySet<NegotiationState> = new Set([\n  'rejected',\n  'settled',\n  'disputed',\n]);\n\n/** Result of attempting a state transition. */\nexport interface TransitionResult {\n  ok: boolean;\n  nextState?: NegotiationState;\n  error?: string;\n  reason?:\n    | 'illegal-transition'\n    | 'wrong-actor'\n    | 'terminal-state'\n    | 'unknown-action'\n    | 'missing-counter-signature';\n}\n\n/**\n * Determine whether an actor in `actorRole` may apply `action` to a\n * negotiation currently in `currentState`. Returns the next state on\n * success or a structured error otherwise. This is pure logic — no I/O\n * and no side effects — so the route handler and tests can both call it.\n */\nexport function checkTransition(\n  currentState: NegotiationState,\n  action: NegotiationAction,\n  actorRole: NegotiationRole\n): TransitionResult {\n  if (TERMINAL_STATES.has(currentState) && action !== 'dispute') {\n    return {\n      ok: false,\n      reason: 'terminal-state',\n      error: `negotiation in terminal state ${currentState}, only 'dispute' is legal`,\n    };\n  }\n  // dispute is legal from settled or executed (handled below by table)\n  const key = `${currentState}|${action}` as const;\n  const rule = TRANSITIONS[key];\n  if (rule === null || rule === undefined) {\n    return {\n      ok: false,\n      reason: 'illegal-transition',\n      error: `cannot apply '${action}' to negotiation in state '${currentState}'`,\n    };\n  }\n  if (rule.actor !== 'either' && rule.actor !== actorRole) {\n    return {\n      ok: false,\n      reason: 'wrong-actor',\n      error: `action '${action}' must be authored by '${rule.actor}', not '${actorRole}'`,\n    };\n  }\n  return { ok: true, nextState: rule.next };\n}\n\n// ── Quote, settlement, and event records ──────────────────────────────\n\n/**\n * The economic terms a responder offers in response to a request_quote.\n * `currency` is intentionally a string (not enum) so deployments can use\n * USD, USDC, sat, credits, etc. without core changes.\n */\nexport interface NegotiationQuote {\n  /** Agreed work product — usually a tool name + capability_query echo. */\n  toolName: string;\n  /** What the responder commits to deliver. */\n  description: string;\n  /** Numeric price in the named currency unit. 0 = free / favor. */\n  price: number;\n  /** Currency code or token symbol. */\n  currency: string;\n  /** SLA target in seconds (responder's wallclock budget). 0 = best-effort. */\n  slaSeconds: number;\n  /** ISO-8601 expiration; quote is invalid after this timestamp. */\n  expiresAt: string;\n}\n\n/**\n * Settlement receipt produced once both parties have signed the executed\n * outcome. The receipt is the durable artifact of a successful cycle —\n * same role as a signed invoice in conventional commerce.\n */\nexport interface SettlementReceipt {\n  protocol: typeof NEGOTIATION_PROTOCOL;\n  negotiationId: string;\n  initiatorSignature: string;\n  initiatorAddress: string;\n  responderSignature: string;\n  responderAddress: string;\n  finalQuote: NegotiationQuote;\n  /** Hash of the executed result body — proves *what* was delivered. */\n  resultHash: string;\n  /**\n   * Optional on-chain anchor tx hash (Base / EIP-712 calldata pattern,\n   * F.041 / W.GOLD.514). When present, the chain itself is the\n   * dispute-resistant ground truth.\n   */\n  settlementTxHash?: string;\n  settledAt: string;\n}\n\n/**\n * One event in the negotiation log. The route handler appends one of\n * these per /message POST that carries `messageType: 'negotiation'`.\n */\nexport interface NegotiationEvent {\n  /** Monotonic event ordinal within this negotiation, starting at 0. */\n  seq: number;\n  action: NegotiationAction;\n  /** State that resulted from this event. */\n  state: NegotiationState;\n  authorAgentId: string;\n  authorRole: NegotiationRole;\n  /** The signer address that the request-signing verifier recovered. */\n  signerAddress?: string;\n  /** Free-form payload — e.g. NegotiationQuote, dispute reason, exec result hash. */\n  payload?: Record<string, unknown>;\n  createdAt: string;\n}\n\n/**\n * The full negotiation aggregate. Stored keyed by negotiationId in an\n * in-memory Map (same eviction discipline as messaging.ts — out of\n * scope for the MVP scope guardrail; receipts of interest are persisted\n * on-chain via settlementTxHash when long-term durability matters).\n */\nexport interface Negotiation {\n  id: string;\n  protocol: typeof NEGOTIATION_PROTOCOL;\n  teamId: string;\n  initiatorAgentId: string;\n  initiatorAgentName: string;\n  responderAgentId: string;\n  responderAgentName: string;\n  state: NegotiationState;\n  /** Latest live quote from the responder, replaced on each new quote. */\n  quote?: NegotiationQuote;\n  /** Set once the cycle reaches 'settled' — the durable artifact. */\n  receipt?: SettlementReceipt;\n  events: NegotiationEvent[];\n  createdAt: string;\n  updatedAt: string;\n}\n\n// ── In-memory store ────────────────────────────────────────────────────\n\n/**\n * Module-private store. Production deployments that need durability\n * across restart should replace with a persisted backend, but per the\n * task scope guardrail the MVP only needs to cover one cycle in-process\n * and rely on chain anchoring for terminal proof.\n */\nconst negotiations = new Map<string, Negotiation>();\n\n/** Test-only reset. */\nexport function _resetNegotiations(): void {\n  negotiations.clear();\n}\n\n/** Read-only accessor — returns the negotiation by id or undefined. */\nexport function getNegotiation(id: string): Negotiation | undefined {\n  return negotiations.get(id);\n}\n\n/** Read-only listing — returns all negotiations for a team, newest first. */\nexport function listNegotiationsForTeam(teamId: string): Negotiation[] {\n  const out: Negotiation[] = [];\n  for (const n of negotiations.values()) {\n    if (n.teamId === teamId) out.push(n);\n  }\n  out.sort((a, b) => b.createdAt.localeCompare(a.createdAt));\n  return out;\n}\n\n// ── Lifecycle: create, advance, settle ─────────────────────────────────\n\nexport interface CreateNegotiationInput {\n  teamId: string;\n  initiatorAgentId: string;\n  initiatorAgentName: string;\n  responderAgentId: string;\n  responderAgentName: string;\n  /**\n   * The first event in the cycle — what tool / capability the initiator\n   * is requesting a quote for.\n   */\n  request: {\n    toolName: string;\n    capabilityQuery: string;\n    args?: Record<string, unknown>;\n  };\n  /** Optional pre-supplied id for deterministic test fixtures. */\n  id?: string;\n  signerAddress?: string;\n}\n\n/**\n * Create a new negotiation in the 'open' state. The initiator's\n * `request_quote` event is recorded as event seq=0.\n */\nexport function createNegotiation(input: CreateNegotiationInput): Negotiation {\n  if (input.initiatorAgentId === input.responderAgentId) {\n    throw new Error('initiator and responder must be distinct agents');\n  }\n  const id = input.id ?? `nego_${Date.now()}_${randomUUID().slice(0, 8)}`;\n  const now = new Date().toISOString();\n  const event: NegotiationEvent = {\n    seq: 0,\n    action: 'request_quote',\n    state: 'open',\n    authorAgentId: input.initiatorAgentId,\n    authorRole: 'initiator',\n    signerAddress: input.signerAddress,\n    payload: { request: input.request },\n    createdAt: now,\n  };\n  const negotiation: Negotiation = {\n    id,\n    protocol: NEGOTIATION_PROTOCOL,\n    teamId: input.teamId,\n    initiatorAgentId: input.initiatorAgentId,\n    initiatorAgentName: input.initiatorAgentName,\n    responderAgentId: input.responderAgentId,\n    responderAgentName: input.responderAgentName,\n    state: 'open',\n    events: [event],\n    createdAt: now,\n    updatedAt: now,\n  };\n  negotiations.set(id, negotiation);\n  return negotiation;\n}\n\nexport interface AdvanceNegotiationInput {\n  negotiationId: string;\n  action: NegotiationAction;\n  authorAgentId: string;\n  signerAddress?: string;\n  payload?: Record<string, unknown>;\n}\n\nexport interface AdvanceNegotiationResult {\n  ok: boolean;\n  negotiation?: Negotiation;\n  event?: NegotiationEvent;\n  error?: string;\n  reason?: TransitionResult['reason'] | 'not-found' | 'not-a-party';\n}\n\n/**\n * Apply an action to an existing negotiation. Validates the actor's\n * role, runs the state-machine check, appends the event, mutates the\n * aggregate, and returns the new state.\n *\n * The route handler is responsible for verifying the signature *before*\n * calling this function (signing-middleware does that and provides\n * `signerAddress`). This function is pure state-machine bookkeeping.\n */\nexport function advanceNegotiation(input: AdvanceNegotiationInput): AdvanceNegotiationResult {\n  const n = negotiations.get(input.negotiationId);\n  if (!n) {\n    return {\n      ok: false,\n      reason: 'not-found',\n      error: `negotiation ${input.negotiationId} not found`,\n    };\n  }\n  const role = roleForAgent(n, input.authorAgentId);\n  if (!role) {\n    return {\n      ok: false,\n      reason: 'not-a-party',\n      error: `agent ${input.authorAgentId} is not a party to negotiation ${n.id}`,\n    };\n  }\n  const check = checkTransition(n.state, input.action, role);\n  if (!check.ok) {\n    return { ok: false, reason: check.reason, error: check.error };\n  }\n  // Validate quote payload when responder is quoting\n  if (input.action === 'quote') {\n    const q = input.payload?.quote as NegotiationQuote | undefined;\n    const v = validateQuote(q);\n    if (!v.ok) return { ok: false, reason: 'illegal-transition', error: v.error };\n    n.quote = q;\n  }\n  // Settlement requires both signatures — handled separately below.\n  if (input.action === 'settle') {\n    const settleRes = applySettlement(n, input);\n    if (!settleRes.ok) return settleRes;\n  }\n  const event: NegotiationEvent = {\n    seq: n.events.length,\n    action: input.action,\n    state: check.nextState!,\n    authorAgentId: input.authorAgentId,\n    authorRole: role,\n    signerAddress: input.signerAddress,\n    payload: input.payload,\n    createdAt: new Date().toISOString(),\n  };\n  n.events.push(event);\n  n.state = check.nextState!;\n  n.updatedAt = event.createdAt;\n  return { ok: true, negotiation: n, event };\n}\n\n// ── Quote validation ──────────────────────────────────────────────────\n\nfunction validateQuote(\n  q: NegotiationQuote | undefined\n): { ok: true } | { ok: false; error: string } {\n  if (!q || typeof q !== 'object') {\n    return {\n      ok: false,\n      error:\n        'quote payload required: { toolName, description, price, currency, slaSeconds, expiresAt }',\n    };\n  }\n  if (typeof q.toolName !== 'string' || !q.toolName)\n    return { ok: false, error: 'quote.toolName required' };\n  if (typeof q.description !== 'string') return { ok: false, error: 'quote.description required' };\n  if (typeof q.price !== 'number' || q.price < 0 || !Number.isFinite(q.price)) {\n    return { ok: false, error: 'quote.price must be a non-negative finite number' };\n  }\n  if (typeof q.currency !== 'string' || !q.currency)\n    return { ok: false, error: 'quote.currency required' };\n  if (typeof q.slaSeconds !== 'number' || q.slaSeconds < 0) {\n    return { ok: false, error: 'quote.slaSeconds must be a non-negative number' };\n  }\n  if (typeof q.expiresAt !== 'string' || Number.isNaN(Date.parse(q.expiresAt))) {\n    return { ok: false, error: 'quote.expiresAt must be a valid ISO-8601 timestamp' };\n  }\n  return { ok: true };\n}\n\n// ── Settlement (co-signed receipt) ────────────────────────────────────\n\n/**\n * The `settle` action requires one completed receipt containing both\n * parties' signatures. We intentionally reject half-signed receipts\n * instead of storing partial state, so a failed settlement attempt cannot\n * mutate the aggregate or leave a misleading receipt behind.\n *\n * Pattern: scope guardrail says \"one signed receipt\" — we still take both\n * signatures (initiator + responder) so the receipt is dispute-resistant\n * by construction. The chain anchor (settlementTxHash) is optional here\n * because in-band signatures already give us cryptographic non-repudiation\n * for one cycle; chain anchor is the durability layer for cross-restart\n * verification, which production deployments should add.\n */\nfunction applySettlement(n: Negotiation, input: AdvanceNegotiationInput): AdvanceNegotiationResult {\n  const partial = input.payload?.partialReceipt as Partial<SettlementReceipt> | undefined;\n  if (!partial || typeof partial !== 'object') {\n    return {\n      ok: false,\n      reason: 'missing-counter-signature',\n      error: 'settle payload requires partialReceipt with both party signatures',\n    };\n  }\n  // Did the previous executed event have an output we can hash?\n  const lastExec = [...n.events].reverse().find((e) => e.action === 'execute');\n  if (!lastExec) {\n    return {\n      ok: false,\n      reason: 'illegal-transition',\n      error: 'cannot settle without a prior execute event',\n    };\n  }\n  if (!n.quote) {\n    return {\n      ok: false,\n      reason: 'illegal-transition',\n      error: 'cannot settle without a finalQuote — quote was never set',\n    };\n  }\n  const resultHash = (partial.resultHash as string) ?? hashResult(lastExec.payload?.result);\n\n  const initiatorSignature = partial.initiatorSignature as string | undefined;\n  const initiatorAddress = partial.initiatorAddress as string | undefined;\n  const responderSignature = partial.responderSignature as string | undefined;\n  const responderAddress = partial.responderAddress as string | undefined;\n\n  if (!initiatorSignature || !initiatorAddress || !responderSignature || !responderAddress) {\n    return {\n      ok: false,\n      reason: 'missing-counter-signature',\n      error: 'settle requires both initiator and responder signatures in partialReceipt',\n    };\n  }\n\n  n.receipt = {\n    protocol: NEGOTIATION_PROTOCOL,\n    negotiationId: n.id,\n    initiatorSignature,\n    initiatorAddress,\n    responderSignature,\n    responderAddress,\n    finalQuote: n.quote,\n    resultHash,\n    settlementTxHash: partial.settlementTxHash as string | undefined,\n    settledAt: new Date().toISOString(),\n  };\n  return { ok: true };\n}\n\n/**\n * Input for the co-signed settlement helper. Pulled out of the function\n * signature so the chain-anchor variant can extend it without duplicating\n * the field list.\n */\nexport interface SettleNegotiationInput {\n  negotiationId: string;\n  authorAgentId: string;\n  signerAddress?: string;\n  initiatorSignature: string;\n  initiatorAddress: string;\n  responderSignature: string;\n  responderAddress: string;\n  resultHash?: string;\n  /**\n   * Caller-supplied tx hash. Use the chain-anchor variant\n   * (`settleNegotiationWithAnchor`) instead when you have a Signer and want\n   * the runtime to mint a real tx hash via `eth_sendTransaction` (F.041 /\n   * W.GOLD.514 chain-anchor pattern).\n   */\n  settlementTxHash?: string;\n}\n\n/**\n * Co-signed settlement helper — supplies BOTH legs in one call. Cleaner\n * reference flow for tests and the canonical \"one signed receipt\" path.\n */\nexport function settleNegotiation(input: SettleNegotiationInput): AdvanceNegotiationResult {\n  const n = negotiations.get(input.negotiationId);\n  if (!n)\n    return {\n      ok: false,\n      reason: 'not-found',\n      error: `negotiation ${input.negotiationId} not found`,\n    };\n  if (!n.quote) {\n    return {\n      ok: false,\n      reason: 'illegal-transition',\n      error: 'cannot settle without a quote',\n    };\n  }\n  const lastExec = [...n.events].reverse().find((e) => e.action === 'execute');\n  if (!lastExec) {\n    return {\n      ok: false,\n      reason: 'illegal-transition',\n      error: 'cannot settle without a prior execute event',\n    };\n  }\n  const resultHash = input.resultHash ?? hashResult(lastExec.payload?.result);\n  const receipt: SettlementReceipt = {\n    protocol: NEGOTIATION_PROTOCOL,\n    negotiationId: n.id,\n    initiatorSignature: input.initiatorSignature,\n    initiatorAddress: input.initiatorAddress,\n    responderSignature: input.responderSignature,\n    responderAddress: input.responderAddress,\n    finalQuote: n.quote,\n    resultHash,\n    settlementTxHash: input.settlementTxHash,\n    settledAt: new Date().toISOString(),\n  };\n  return advanceNegotiation({\n    negotiationId: input.negotiationId,\n    action: 'settle',\n    authorAgentId: input.authorAgentId,\n    signerAddress: input.signerAddress,\n    payload: { partialReceipt: receipt },\n  });\n}\n\nfunction roleForAgent(n: Negotiation, agentId: string): NegotiationRole | null {\n  if (agentId === n.initiatorAgentId) return 'initiator';\n  if (agentId === n.responderAgentId) return 'responder';\n  return null;\n}\n\n/**\n * Chain-anchored settlement — takes a Signer (dev-keyed for tests, Trezor\n * for the founder swap) and produces a real `settlementTxHash` populated\n * from `eth_sendTransaction`. The EIP-712 hash of the receipt becomes the\n * tx calldata (F.041 / W.GOLD.514 pattern).\n *\n * This is the canonical Phase 2 path. The non-anchor `settleNegotiation`\n * stays for backwards compat and for callers that already have a tx hash\n * from somewhere else (e.g. forwarded by an agent that anchored on a\n * different RPC).\n *\n * Returns the same AdvanceNegotiationResult shape as the sync helper, plus\n * an `anchor` field on success carrying the EIP-712 hash + signer address +\n * block info for the route handler to surface.\n *\n * Throws ONLY for signer / RPC failures — state-machine rejections still\n * come back as `{ ok: false, reason }` results.\n */\nexport async function settleNegotiationWithAnchor(input: {\n  negotiationId: string;\n  authorAgentId: string;\n  signerAddress?: string;\n  initiatorSignature: string;\n  initiatorAddress: string;\n  responderSignature: string;\n  responderAddress: string;\n  resultHash?: string;\n  signer: import('./signing/signer').Signer;\n  domain?: import('./signing/chain-anchor').SettlementDomain;\n}): Promise<AdvanceNegotiationResult & { anchor?: import('./signing/chain-anchor').AnchorResult }> {\n  // Build the receipt FIRST (without txHash) so we can hash it deterministically.\n  const n = negotiations.get(input.negotiationId);\n  if (!n) {\n    return {\n      ok: false,\n      reason: 'not-found',\n      error: `negotiation ${input.negotiationId} not found`,\n    };\n  }\n  const role = roleForAgent(n, input.authorAgentId);\n  if (!role) {\n    return {\n      ok: false,\n      reason: 'not-a-party',\n      error: `agent ${input.authorAgentId} is not a party to negotiation ${n.id}`,\n    };\n  }\n  const transition = checkTransition(n.state, 'settle', role);\n  if (!transition.ok) {\n    return { ok: false, reason: transition.reason, error: transition.error };\n  }\n  if (!n.quote) {\n    return {\n      ok: false,\n      reason: 'illegal-transition',\n      error: 'cannot settle without a quote',\n    };\n  }\n  const lastExec = [...n.events].reverse().find((e) => e.action === 'execute');\n  if (!lastExec) {\n    return {\n      ok: false,\n      reason: 'illegal-transition',\n      error: 'cannot settle without a prior execute event',\n    };\n  }\n  const resultHash = input.resultHash ?? hashResult(lastExec.payload?.result);\n  const settledAt = new Date().toISOString();\n  const hashable: import('./signing/chain-anchor').HashableReceipt = {\n    protocol: NEGOTIATION_PROTOCOL,\n    negotiationId: n.id,\n    initiatorAddress: input.initiatorAddress,\n    responderAddress: input.responderAddress,\n    initiatorSignature: input.initiatorSignature,\n    responderSignature: input.responderSignature,\n    resultHash,\n    finalQuote: n.quote,\n    settledAt,\n  };\n\n  // Anchor on chain (or mocked broadcast) — produces the txHash we feed back\n  // into the receipt before we let the state machine flip to 'settled'.\n  const { anchorSettlement } = await import('./signing/chain-anchor');\n  const anchor = await anchorSettlement(input.signer, hashable, input.domain);\n\n  // Build the final receipt with the anchored txHash + the SAME settledAt we\n  // hashed (so receipt -> hash round-trips against the chain). Bypass\n  // `applySettlement`'s clock-fresh settledAt to keep the pin tight.\n  const receipt: SettlementReceipt = {\n    protocol: NEGOTIATION_PROTOCOL,\n    negotiationId: n.id,\n    initiatorSignature: input.initiatorSignature,\n    initiatorAddress: input.initiatorAddress,\n    responderSignature: input.responderSignature,\n    responderAddress: input.responderAddress,\n    finalQuote: n.quote,\n    resultHash,\n    settlementTxHash: anchor.txHash,\n    settledAt,\n  };\n  // Apply via advanceNegotiation so the state machine + event log update.\n  // applySettlement reads the partialReceipt fields back out, so re-emitting\n  // the same shape here keeps a single code path for state validation.\n  const advanced = advanceNegotiation({\n    negotiationId: input.negotiationId,\n    action: 'settle',\n    authorAgentId: input.authorAgentId,\n    signerAddress: input.signerAddress,\n    payload: { partialReceipt: receipt },\n  });\n  if (!advanced.ok) return advanced;\n  // Overwrite the receipt with our deterministic version (applySettlement\n  // wrote one with a fresh settledAt; we want the one whose hash matches the\n  // anchor). This is safe — same negotiation, same fields, just a pinned\n  // settledAt.\n  if (advanced.negotiation) {\n    advanced.negotiation.receipt = receipt;\n  }\n  return { ...advanced, anchor };\n}\n\n// ── Hashing helper ────────────────────────────────────────────────────\n\nfunction hashResult(result: unknown): string {\n  const json = canonicalize(result);\n  return '0x' + createHash('sha256').update(json).digest('hex');\n}\n\nfunction canonicalize(value: unknown): string {\n  if (value === null || typeof value !== 'object') return JSON.stringify(value ?? null);\n  if (Array.isArray(value)) return `[${value.map(canonicalize).join(',')}]`;\n  const keys = Object.keys(value as Record<string, unknown>).sort();\n  return `{${keys.map((k) => `${JSON.stringify(k)}:${canonicalize((value as Record<string, unknown>)[k])}`).join(',')}}`;\n}\n","/**\n * Negotiation MCP Tools — task_1778175122619_xk5l.\n *\n * Exposes the xsp6 / qe2i agent-negotiation primitives as MCP tools so external\n * agents (Brittney, peer Claude windows, codex, kimi) can drive the full\n * request_quote → quote → accept → execute → settle / dispute cycle through the\n * standard MCP protocol. Stacks on:\n *\n *   - cbdab1387 — agent-negotiation.ts state machine + HTTP /message dispatch\n *   - 98b94e0e4 — signer.ts + chain-anchor.ts + settleNegotiationWithAnchor\n *   - aa63b2416 — chain-anchor wired into composition demo with MockSigner\n *   - 1ed8b10b4 — Trezor anchor proof on Base (tx 0x2abe2621... block 45636414)\n *\n * SCOPE GUARDRAIL: this module is a thin MCP-shape adapter. It does NOT\n * implement any new state machine code; every tool wraps an existing pure\n * function in `agent-negotiation.ts` (`createNegotiation`, `advanceNegotiation`,\n * `settleNegotiation`, `settleNegotiationWithAnchor`, `getNegotiation`,\n * `listNegotiationsForTeam`). The signing path is the same — the route handler\n * still verifies signatures via signing-middleware before dispatching, but the\n * tools surface accepts the already-recovered signerAddress as input so MCP\n * clients can drive the cycle from outside the HTTP team-routes path.\n *\n * Tools published:\n *\n *   - negotiation_request_quote — start a new cycle in 'open'\n *   - negotiation_quote          — responder posts quote (open → quoted)\n *   - negotiation_accept         — initiator accepts (quoted → accepted)\n *   - negotiation_reject         — initiator rejects (quoted → rejected, terminal)\n *   - negotiation_execute        — responder reports result (accepted → executed)\n *   - negotiation_settle         — co-signed settlement (executed → settled)\n *                                  optional `signer` triggers chain anchor\n *   - negotiation_dispute        — file dispute (executed/settled → disputed)\n *   - negotiation_list           — list all negotiations for a team\n *   - negotiation_get            — fetch one by id\n *\n * Pattern mirror: spatial-mcp-tools.ts (single tool, validate → wrap pure\n * logic) and hologram-content-tools.ts (multiple tools, dispatch by name in\n * one handler). This module follows the multi-tool dispatch shape because\n * the negotiation surface is bigger.\n *\n * @package @holoscript/mcp-server\n */\n\nimport type { Tool } from '@modelcontextprotocol/sdk/types.js';\nimport {\n  advanceNegotiation,\n  createNegotiation,\n  getNegotiation,\n  listNegotiationsForTeam,\n  settleNegotiation,\n  settleNegotiationWithAnchor,\n  type AdvanceNegotiationResult,\n  type Negotiation,\n  type NegotiationQuote,\n} from './holomesh/agent-negotiation';\nimport { MockSigner, type Signer } from './holomesh/signing/signer';\n\n// =============================================================================\n// JSON Schemas\n// =============================================================================\n\nconst QUOTE_SCHEMA = {\n  type: 'object',\n  description:\n    'Economic terms a responder offers. `currency` is a free-form string so deployments can use USD, USDC, sat, credits, etc.',\n  properties: {\n    toolName: {\n      type: 'string',\n      description: 'Tool name + capability_query echo — what the responder commits to deliver.',\n    },\n    description: { type: 'string', description: 'Free-form description of the work product.' },\n    price: {\n      type: 'number',\n      description: 'Numeric price in `currency`. 0 = free / favor.',\n      minimum: 0,\n    },\n    currency: {\n      type: 'string',\n      description: 'Currency code or token symbol (USD, USDC, sat, credits, ...).',\n    },\n    slaSeconds: {\n      type: 'number',\n      description: 'SLA target in wallclock seconds. 0 = best-effort.',\n      minimum: 0,\n    },\n    expiresAt: {\n      type: 'string',\n      description: 'ISO-8601 expiration timestamp; quote is invalid after this point.',\n    },\n  },\n  required: ['toolName', 'description', 'price', 'currency', 'slaSeconds', 'expiresAt'],\n  additionalProperties: false,\n} as const;\n\nconst REQUEST_PAYLOAD_SCHEMA = {\n  type: 'object',\n  description: 'The capability request the initiator is asking the responder to quote against.',\n  properties: {\n    toolName: { type: 'string', description: 'Tool name the initiator wants executed.' },\n    capabilityQuery: {\n      type: 'string',\n      description: 'Capability tag / search predicate (e.g. \"code-quality:typescript\").',\n    },\n    args: {\n      type: 'object',\n      description: 'Optional arguments the initiator would pass to the tool on execute.',\n      additionalProperties: true,\n    },\n  },\n  required: ['toolName', 'capabilityQuery'],\n  additionalProperties: false,\n} as const;\n\n// =============================================================================\n// Tool Definitions\n// =============================================================================\n\nexport const negotiationToolDefinitions: Tool[] = [\n  {\n    name: 'negotiation_request_quote',\n    description:\n      'Start a new agent-to-agent negotiation in state `open`. The initiator declares the responder, team, and the capability request. Server appends a seq=0 `request_quote` event signed by the initiator. Returns the new Negotiation aggregate (id + state + events). Use this as the entry point for the full cycle: request_quote → quote → accept → execute → settle. Stacks on agent-negotiation.ts (cbdab1387).',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        teamId: { type: 'string', description: 'HoloMesh team id this negotiation belongs to.' },\n        initiatorAgentId: { type: 'string', description: 'Agent id of the requester.' },\n        initiatorAgentName: { type: 'string', description: 'Display name of the initiator.' },\n        responderAgentId: {\n          type: 'string',\n          description: 'Agent id of the responder being asked to quote.',\n        },\n        responderAgentName: { type: 'string', description: 'Display name of the responder.' },\n        request: REQUEST_PAYLOAD_SCHEMA,\n        signerAddress: {\n          type: 'string',\n          description: 'Optional 0x-address of the initiator that signed the request envelope.',\n        },\n        id: {\n          type: 'string',\n          description: 'Optional pre-supplied negotiation id (mainly for deterministic tests).',\n        },\n      },\n      required: [\n        'teamId',\n        'initiatorAgentId',\n        'initiatorAgentName',\n        'responderAgentId',\n        'responderAgentName',\n        'request',\n      ],\n      additionalProperties: false,\n    },\n  },\n  {\n    name: 'negotiation_quote',\n    description:\n      'Responder posts a quote against an open negotiation. Transitions the aggregate from `open` → `quoted` and stores `quote` on the negotiation. Only the responder may author this transition (wrong-actor errors otherwise). Returns updated Negotiation + the new event. Stacks on agent-negotiation.ts.advanceNegotiation.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        negotiationId: {\n          type: 'string',\n          description: 'Negotiation id returned by negotiation_request_quote.',\n        },\n        authorAgentId: {\n          type: 'string',\n          description: 'Agent id of the responder posting the quote.',\n        },\n        signerAddress: {\n          type: 'string',\n          description: 'Optional 0x-address that signed the envelope.',\n        },\n        quote: QUOTE_SCHEMA,\n      },\n      required: ['negotiationId', 'authorAgentId', 'quote'],\n      additionalProperties: false,\n    },\n  },\n  {\n    name: 'negotiation_accept',\n    description:\n      'Initiator accepts the responder’s most recent quote. Transitions `quoted` → `accepted`. Wrong-actor (responder accepting their own quote) is rejected with reason=`wrong-actor`. Returns updated Negotiation + new event. Stacks on agent-negotiation.ts.advanceNegotiation.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        negotiationId: { type: 'string', description: 'Negotiation id.' },\n        authorAgentId: { type: 'string', description: 'Agent id of the initiator.' },\n        signerAddress: { type: 'string', description: 'Optional signer address.' },\n      },\n      required: ['negotiationId', 'authorAgentId'],\n      additionalProperties: false,\n    },\n  },\n  {\n    name: 'negotiation_reject',\n    description:\n      'Initiator rejects the responder’s quote. Transitions `quoted` → `rejected` (TERMINAL — no further transitions accepted). Returns updated Negotiation + new event. Stacks on agent-negotiation.ts.advanceNegotiation.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        negotiationId: { type: 'string', description: 'Negotiation id.' },\n        authorAgentId: { type: 'string', description: 'Agent id of the initiator.' },\n        signerAddress: { type: 'string', description: 'Optional signer address.' },\n        reason: { type: 'string', description: 'Optional human-readable rejection reason.' },\n      },\n      required: ['negotiationId', 'authorAgentId'],\n      additionalProperties: false,\n    },\n  },\n  {\n    name: 'negotiation_execute',\n    description:\n      'Responder reports tool execution complete and posts the result. Transitions `accepted` → `executed`. The result body is hashed (SHA-256) for the eventual SettlementReceipt.resultHash. Only the responder may author this transition. Returns updated Negotiation + new event.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        negotiationId: { type: 'string', description: 'Negotiation id.' },\n        authorAgentId: { type: 'string', description: 'Agent id of the responder.' },\n        signerAddress: { type: 'string', description: 'Optional signer address.' },\n        result: {\n          description:\n            'Free-form result payload — hashed deterministically into receipt.resultHash.',\n        },\n      },\n      required: ['negotiationId', 'authorAgentId'],\n      additionalProperties: false,\n    },\n  },\n  {\n    name: 'negotiation_settle',\n    description:\n      'Apply the co-signed settlement receipt — both initiator and responder signatures required. Transitions `executed` → `settled` (TERMINAL except for dispute). Returns updated Negotiation, the new event, and the populated SettlementReceipt. If `useChainAnchor: true` is set, additionally anchors the EIP-712 hash on Base via eth_sendTransaction (F.041 / W.GOLD.514 pattern) using a deterministic MockSigner and returns the anchor result on `anchor`. For real-chain anchoring, the HTTP route layer should invoke `settleNegotiationWithAnchor` directly with a configured signer. Stacks on agent-negotiation.ts.settleNegotiation / settleNegotiationWithAnchor.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        negotiationId: { type: 'string', description: 'Negotiation id.' },\n        authorAgentId: {\n          type: 'string',\n          description: 'Agent id of the party submitting the receipt.',\n        },\n        signerAddress: { type: 'string', description: 'Optional signer address.' },\n        initiatorSignature: {\n          type: 'string',\n          description: 'Initiator’s signature of the receipt.',\n        },\n        initiatorAddress: { type: 'string', description: 'Initiator’s 0x-address.' },\n        responderSignature: {\n          type: 'string',\n          description: 'Responder’s signature of the receipt.',\n        },\n        responderAddress: { type: 'string', description: 'Responder’s 0x-address.' },\n        resultHash: {\n          type: 'string',\n          description:\n            'Optional pre-computed SHA-256 hash of the executed result. If omitted, the server hashes the prior execute event payload.',\n        },\n        settlementTxHash: {\n          type: 'string',\n          description:\n            'Optional caller-supplied chain anchor tx hash. Use `useChainAnchor: true` instead to have the runtime mint a real one via MockSigner.',\n        },\n        useChainAnchor: {\n          type: 'boolean',\n          description:\n            'If true, mint a deterministic chain anchor with the EIP-712 hash as calldata via MockSigner. The returned response includes `anchor` with the eip712Hash + txHash + blockNumber + status. Default: false.',\n        },\n        mockChainAnchor: {\n          type: 'object',\n          description:\n            'Optional MockSigner overrides for deterministic test fixtures. Only honored when useChainAnchor=true.',\n          properties: {\n            address: { type: 'string', description: '0x-address the mock signer reports.' },\n            chainId: { type: 'number', description: 'Chain id the mock claims to be on.' },\n            fixedTxHash: {\n              type: 'string',\n              description: '0x-hash the mock returns instead of computing one.',\n            },\n          },\n          additionalProperties: false,\n        },\n      },\n      required: [\n        'negotiationId',\n        'authorAgentId',\n        'initiatorSignature',\n        'initiatorAddress',\n        'responderSignature',\n        'responderAddress',\n      ],\n      additionalProperties: false,\n    },\n  },\n  {\n    name: 'negotiation_dispute',\n    description:\n      'File a dispute against an `executed` or `settled` negotiation. Either party may dispute. Transitions to `disputed` (TERMINAL). The dispute reason is recorded on the event payload. Returns updated Negotiation + new event.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        negotiationId: { type: 'string', description: 'Negotiation id.' },\n        authorAgentId: { type: 'string', description: 'Agent id of the disputing party.' },\n        signerAddress: { type: 'string', description: 'Optional signer address.' },\n        reason: { type: 'string', description: 'Optional dispute reason recorded on the event.' },\n      },\n      required: ['negotiationId', 'authorAgentId'],\n      additionalProperties: false,\n    },\n  },\n  {\n    name: 'negotiation_list',\n    description:\n      'List all negotiations for a team, newest first. Returns an array of Negotiation aggregates including their full event log. Read-only; no signatures required. Use this to populate a dashboard view of in-flight commerce.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        teamId: { type: 'string', description: 'HoloMesh team id.' },\n        limit: {\n          type: 'number',\n          description: 'Optional max number of negotiations to return (default 50).',\n          minimum: 1,\n        },\n      },\n      required: ['teamId'],\n      additionalProperties: false,\n    },\n  },\n  {\n    name: 'negotiation_get',\n    description:\n      'Fetch a single negotiation by id, including its full event log + (when settled) SettlementReceipt. Returns `{ ok: false, reason: \"not-found\" }` if the id is unknown.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        negotiationId: { type: 'string', description: 'Negotiation id.' },\n      },\n      required: ['negotiationId'],\n      additionalProperties: false,\n    },\n  },\n];\n\nconst NEGOTIATION_TOOL_NAMES = new Set(negotiationToolDefinitions.map((t) => t.name));\n\nexport function isNegotiationToolName(name: string): boolean {\n  return NEGOTIATION_TOOL_NAMES.has(name);\n}\n\n// =============================================================================\n// Helpers\n// =============================================================================\n\ninterface MockSignerOptions {\n  address?: string;\n  chainId?: number;\n  fixedTxHash?: string;\n}\n\nfunction buildMockSigner(opts: MockSignerOptions | undefined): Signer {\n  return new MockSigner({\n    address: opts?.address,\n    chainId: opts?.chainId,\n    fixedTxHash: opts?.fixedTxHash,\n  });\n}\n\n/** Shape returned for state-mutating tools — pulled out so every adapter\n *  produces an identical contract for clients. */\ninterface NegotiationToolResult {\n  ok: boolean;\n  negotiation?: Negotiation;\n  event?: AdvanceNegotiationResult['event'];\n  receipt?: Negotiation['receipt'];\n  anchor?: Awaited<ReturnType<typeof settleNegotiationWithAnchor>>['anchor'];\n  reason?: AdvanceNegotiationResult['reason'];\n  error?: string;\n}\n\n/** Convert an internal AdvanceNegotiationResult into the surface tool result.\n *  Keeps the receipt visible at the top level (not buried under negotiation)\n *  so MCP clients don't have to walk the aggregate. */\nfunction shapeAdvanceResult(r: AdvanceNegotiationResult): NegotiationToolResult {\n  if (!r.ok) {\n    return { ok: false, reason: r.reason, error: r.error };\n  }\n  return {\n    ok: true,\n    negotiation: r.negotiation,\n    event: r.event,\n    receipt: r.negotiation?.receipt,\n  };\n}\n\n// =============================================================================\n// HANDLER\n// =============================================================================\n\nexport async function handleNegotiationTool(\n  name: string,\n  args: Record<string, unknown>\n): Promise<unknown> {\n  switch (name) {\n    case 'negotiation_request_quote': {\n      const teamId = String(args.teamId ?? '');\n      const initiatorAgentId = String(args.initiatorAgentId ?? '');\n      const initiatorAgentName = String(args.initiatorAgentName ?? '');\n      const responderAgentId = String(args.responderAgentId ?? '');\n      const responderAgentName = String(args.responderAgentName ?? '');\n      const request = args.request as\n        | { toolName?: string; capabilityQuery?: string; args?: Record<string, unknown> }\n        | undefined;\n      if (!teamId) return { ok: false, error: 'teamId required' };\n      if (!initiatorAgentId || !responderAgentId) {\n        return { ok: false, error: 'initiatorAgentId and responderAgentId required' };\n      }\n      if (initiatorAgentId === responderAgentId) {\n        return {\n          ok: false,\n          reason: 'illegal-transition',\n          error: 'initiator and responder must be distinct agents',\n        };\n      }\n      if (!request || typeof request.toolName !== 'string' || !request.toolName) {\n        return { ok: false, error: 'request.toolName required' };\n      }\n      if (typeof request.capabilityQuery !== 'string' || !request.capabilityQuery) {\n        return { ok: false, error: 'request.capabilityQuery required' };\n      }\n      try {\n        const negotiation = createNegotiation({\n          teamId,\n          initiatorAgentId,\n          initiatorAgentName,\n          responderAgentId,\n          responderAgentName,\n          request: {\n            toolName: request.toolName,\n            capabilityQuery: request.capabilityQuery,\n            args: request.args,\n          },\n          id: typeof args.id === 'string' ? args.id : undefined,\n          signerAddress: typeof args.signerAddress === 'string' ? args.signerAddress : undefined,\n        });\n        return { ok: true, negotiation, event: negotiation.events[0] };\n      } catch (e) {\n        return { ok: false, error: e instanceof Error ? e.message : String(e) };\n      }\n    }\n\n    case 'negotiation_quote': {\n      const negotiationId = String(args.negotiationId ?? '');\n      const authorAgentId = String(args.authorAgentId ?? '');\n      const quote = args.quote as NegotiationQuote | undefined;\n      if (!negotiationId || !authorAgentId || !quote) {\n        return { ok: false, error: 'negotiationId, authorAgentId, and quote required' };\n      }\n      return shapeAdvanceResult(\n        advanceNegotiation({\n          negotiationId,\n          authorAgentId,\n          action: 'quote',\n          signerAddress: typeof args.signerAddress === 'string' ? args.signerAddress : undefined,\n          payload: { quote },\n        })\n      );\n    }\n\n    case 'negotiation_accept': {\n      const negotiationId = String(args.negotiationId ?? '');\n      const authorAgentId = String(args.authorAgentId ?? '');\n      if (!negotiationId || !authorAgentId) {\n        return { ok: false, error: 'negotiationId and authorAgentId required' };\n      }\n      return shapeAdvanceResult(\n        advanceNegotiation({\n          negotiationId,\n          authorAgentId,\n          action: 'accept',\n          signerAddress: typeof args.signerAddress === 'string' ? args.signerAddress : undefined,\n        })\n      );\n    }\n\n    case 'negotiation_reject': {\n      const negotiationId = String(args.negotiationId ?? '');\n      const authorAgentId = String(args.authorAgentId ?? '');\n      if (!negotiationId || !authorAgentId) {\n        return { ok: false, error: 'negotiationId and authorAgentId required' };\n      }\n      const reason = typeof args.reason === 'string' ? args.reason : undefined;\n      return shapeAdvanceResult(\n        advanceNegotiation({\n          negotiationId,\n          authorAgentId,\n          action: 'reject',\n          signerAddress: typeof args.signerAddress === 'string' ? args.signerAddress : undefined,\n          payload: reason ? { reason } : undefined,\n        })\n      );\n    }\n\n    case 'negotiation_execute': {\n      const negotiationId = String(args.negotiationId ?? '');\n      const authorAgentId = String(args.authorAgentId ?? '');\n      if (!negotiationId || !authorAgentId) {\n        return { ok: false, error: 'negotiationId and authorAgentId required' };\n      }\n      const result = args.result;\n      return shapeAdvanceResult(\n        advanceNegotiation({\n          negotiationId,\n          authorAgentId,\n          action: 'execute',\n          signerAddress: typeof args.signerAddress === 'string' ? args.signerAddress : undefined,\n          payload: result !== undefined ? { result } : undefined,\n        })\n      );\n    }\n\n    case 'negotiation_settle': {\n      const negotiationId = String(args.negotiationId ?? '');\n      const authorAgentId = String(args.authorAgentId ?? '');\n      const initiatorSignature = String(args.initiatorSignature ?? '');\n      const initiatorAddress = String(args.initiatorAddress ?? '');\n      const responderSignature = String(args.responderSignature ?? '');\n      const responderAddress = String(args.responderAddress ?? '');\n      if (\n        !negotiationId ||\n        !authorAgentId ||\n        !initiatorSignature ||\n        !initiatorAddress ||\n        !responderSignature ||\n        !responderAddress\n      ) {\n        return {\n          ok: false,\n          error:\n            'negotiationId, authorAgentId, initiatorSignature, initiatorAddress, responderSignature, and responderAddress are all required',\n        };\n      }\n      const useChainAnchor = args.useChainAnchor === true;\n      const resultHash = typeof args.resultHash === 'string' ? args.resultHash : undefined;\n      const signerAddress = typeof args.signerAddress === 'string' ? args.signerAddress : undefined;\n\n      if (useChainAnchor) {\n        const mockOpts = (args.mockChainAnchor ?? {}) as MockSignerOptions;\n        const signer = buildMockSigner(mockOpts);\n        const r = await settleNegotiationWithAnchor({\n          negotiationId,\n          authorAgentId,\n          signerAddress,\n          initiatorSignature,\n          initiatorAddress,\n          responderSignature,\n          responderAddress,\n          resultHash,\n          signer,\n        });\n        if (!r.ok) {\n          return { ok: false, reason: r.reason, error: r.error };\n        }\n        return {\n          ok: true,\n          negotiation: r.negotiation,\n          event: r.event,\n          receipt: r.negotiation?.receipt,\n          anchor: r.anchor,\n        };\n      }\n\n      const settlementTxHash =\n        typeof args.settlementTxHash === 'string' ? args.settlementTxHash : undefined;\n      return shapeAdvanceResult(\n        settleNegotiation({\n          negotiationId,\n          authorAgentId,\n          signerAddress,\n          initiatorSignature,\n          initiatorAddress,\n          responderSignature,\n          responderAddress,\n          resultHash,\n          settlementTxHash,\n        })\n      );\n    }\n\n    case 'negotiation_dispute': {\n      const negotiationId = String(args.negotiationId ?? '');\n      const authorAgentId = String(args.authorAgentId ?? '');\n      if (!negotiationId || !authorAgentId) {\n        return { ok: false, error: 'negotiationId and authorAgentId required' };\n      }\n      const reason = typeof args.reason === 'string' ? args.reason : undefined;\n      return shapeAdvanceResult(\n        advanceNegotiation({\n          negotiationId,\n          authorAgentId,\n          action: 'dispute',\n          signerAddress: typeof args.signerAddress === 'string' ? args.signerAddress : undefined,\n          payload: reason ? { reason } : undefined,\n        })\n      );\n    }\n\n    case 'negotiation_list': {\n      const teamId = String(args.teamId ?? '');\n      if (!teamId) return { ok: false, error: 'teamId required' };\n      const limit = typeof args.limit === 'number' && args.limit > 0 ? Math.floor(args.limit) : 50;\n      const negotiations = listNegotiationsForTeam(teamId).slice(0, limit);\n      return { ok: true, count: negotiations.length, negotiations };\n    }\n\n    case 'negotiation_get': {\n      const negotiationId = String(args.negotiationId ?? '');\n      if (!negotiationId) return { ok: false, error: 'negotiationId required' };\n      const n = getNegotiation(negotiationId);\n      if (!n) {\n        return { ok: false, reason: 'not-found', error: `negotiation ${negotiationId} not found` };\n      }\n      return { ok: true, negotiation: n };\n    }\n\n    default:\n      throw new Error(`Unknown negotiation tool: ${name}`);\n  }\n}\n","/**\n * HoloGram depth estimation — optional DepthAnything v2 backend.\n *\n * Tries to load `@huggingface/transformers` at runtime (optional peer dep).\n * Falls back to returning `null` when:\n *   - The package is not installed\n *   - Model download / inference fails\n *   - HOLOGRAM_DEPTH_BACKEND=luminance-proxy env var is set\n *\n * Callers should use the luminance-proxy path in the render HTML when\n * `depthMap` is `null`.\n *\n * Output convention (matches the existing luminance-proxy):\n *   1.0 = close to camera  (large parallax shift)\n *   0.0 = far from camera\n *\n * DepthAnything outputs larger values for farther pixels, so we invert.\n */\n\nexport interface DepthEstimateResult {\n  /** Flat Float32Array of length targetWidth × targetHeight, or null on failure. */\n  depthMap: Float32Array | null;\n  backend: 'depth-anything-v2' | 'luminance-proxy';\n}\n\n// Singleton pipeline — expensive to instantiate; reused across renders.\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nlet cachedPipeline: any = null;\nlet pipelineLoadAttempted = false;\n\nasync function loadDepthPipeline(): Promise<unknown> {\n  if (pipelineLoadAttempted) return cachedPipeline;\n  pipelineLoadAttempted = true;\n\n  try {\n    // Dynamic import — @huggingface/transformers is an optional peer dep.\n    const transformers = await import('@huggingface/transformers');\n    // Disable browser cache and local model lookup (Railway/server environment).\n    const envObj = (transformers as unknown as Record<string, unknown>).env as Record<\n      string,\n      unknown\n    >;\n    if (envObj) {\n      envObj.useBrowserCache = false;\n      envObj.allowLocalModels = false;\n    }\n    cachedPipeline = await (\n      transformers as unknown as {\n        pipeline(task: string, model: string, opts: Record<string, unknown>): Promise<unknown>;\n      }\n    ).pipeline('depth-estimation', 'Xenova/depth-anything-v2-small-hf', { dtype: 'fp32' });\n    return cachedPipeline;\n  } catch {\n    return null;\n  }\n}\n\n/**\n * Bilinear resize for a flat Float32Array image of dimensions srcW × srcH\n * to dstW × dstH.  Both source and destination are row-major.\n */\nexport function bilinearResize(\n  src: Float32Array,\n  srcW: number,\n  srcH: number,\n  dstW: number,\n  dstH: number\n): Float32Array {\n  const dst = new Float32Array(dstW * dstH);\n  const xScale = srcW / dstW;\n  const yScale = srcH / dstH;\n\n  for (let y = 0; y < dstH; y++) {\n    const srcY = (y + 0.5) * yScale - 0.5;\n    const y0 = Math.max(0, Math.floor(srcY));\n    const y1 = Math.min(srcH - 1, y0 + 1);\n    const yFrac = srcY - y0;\n\n    for (let x = 0; x < dstW; x++) {\n      const srcX = (x + 0.5) * xScale - 0.5;\n      const x0 = Math.max(0, Math.floor(srcX));\n      const x1 = Math.min(srcW - 1, x0 + 1);\n      const xFrac = srcX - x0;\n\n      const v00 = src[y0 * srcW + x0];\n      const v01 = src[y0 * srcW + x1];\n      const v10 = src[y1 * srcW + x0];\n      const v11 = src[y1 * srcW + x1];\n\n      dst[y * dstW + x] =\n        v00 * (1 - xFrac) * (1 - yFrac) +\n        v01 * xFrac * (1 - yFrac) +\n        v10 * (1 - xFrac) * yFrac +\n        v11 * xFrac * yFrac;\n    }\n  }\n\n  return dst;\n}\n\n/**\n * Estimate monocular depth from an image URL.\n *\n * Uses DepthAnything v2 Small (Xenova ONNX quantized) when available.\n * Falls back to `{ depthMap: null, backend: 'luminance-proxy' }` on any failure\n * so the caller can safely apply the luminance-proxy path.\n *\n * @param imageUrl  File path or HTTPS URL accepted by RawImage.fromURL.\n *                  `file://` URIs and `https://` URLs both work.\n * @param targetWidth  Width of the output depth map (render canvas width).\n * @param targetHeight Height of the output depth map (render canvas height).\n */\nexport async function estimateDepthFromUrl(\n  imageUrl: string,\n  targetWidth: number,\n  targetHeight: number\n): Promise<DepthEstimateResult> {\n  const forceBackend = process.env.HOLOGRAM_DEPTH_BACKEND?.trim();\n  if (forceBackend === 'luminance-proxy') {\n    return { depthMap: null, backend: 'luminance-proxy' };\n  }\n\n  const pipe = await loadDepthPipeline();\n  if (!pipe) return { depthMap: null, backend: 'luminance-proxy' };\n\n  try {\n    // eslint-disable-next-line @typescript-eslint/no-explicit-any\n    const result: any = await (pipe as (url: string) => Promise<unknown>)(imageUrl);\n    const tensor = (result as { predicted_depth: { data: Float32Array; dims: [number, number] } })\n      .predicted_depth;\n    const rawData = tensor.data;\n    const [srcH, srcW] = tensor.dims;\n\n    // Normalize raw depth values to [0, 1] and invert so 1 = close.\n    let min = Infinity;\n    let max = -Infinity;\n    for (const v of rawData) {\n      if (v < min) min = v;\n      if (v > max) max = v;\n    }\n    const range = max - min || 1;\n    const normalized = new Float32Array(rawData.length);\n    for (let i = 0; i < rawData.length; i++) {\n      // Invert: DepthAnything larger = farther → our convention: larger = closer\n      normalized[i] = 1 - (rawData[i] - min) / range;\n    }\n\n    // Bilinear-resize to render canvas dimensions.\n    const resized =\n      srcW === targetWidth && srcH === targetHeight\n        ? normalized\n        : bilinearResize(normalized, srcW, srcH, targetWidth, targetHeight);\n\n    return { depthMap: resized, backend: 'depth-anything-v2' };\n  } catch {\n    return { depthMap: null, backend: 'luminance-proxy' };\n  }\n}\n\n/** Reset the cached pipeline (for testing). */\nexport function _resetDepthPipelineCache(): void {\n  cachedPipeline = null;\n  pipelineLoadAttempted = false;\n}\n","import { spawn } from 'node:child_process';\nimport { createHash } from 'node:crypto';\nimport { promises as fs } from 'node:fs';\nimport { tmpdir } from 'node:os';\nimport { isAbsolute, join, resolve } from 'node:path';\n\nimport { chromium, type Browser } from 'playwright';\n\nimport {\n  createChromiumLaunchError,\n  isMissingChromiumExecutableError,\n  resolveChromiumExecutable,\n} from './browser/chromium-executable.js';\nimport { ffmpegAvailableSync, resolveFfmpegBinary } from './holo-video-ingest';\nimport { estimateDepthFromUrl } from './hologram-depth-estimator';\n\nexport interface RenderArtifact {\n  path: string;\n  byteLength: number;\n  sha256: string;\n  mimeType: string;\n  base64?: string;\n}\n\nexport interface RenderBundleOptions {\n  mediaType: 'image' | 'gif' | 'video';\n  source: string;\n  name: string;\n  holoCode: string;\n  quilt: {\n    config: {\n      views: number;\n      columns: number;\n      rows: number;\n      resolution: [number, number];\n      baseline: number;\n      device: string;\n    };\n    tiles: Array<{ column: number; row: number; cameraOffset: number; viewShear: number }>;\n    metadata: { tileWidth: number; tileHeight: number; numViews: number };\n  };\n  mvhevc: {\n    config: { fps: number; container: 'mov' | 'mp4' };\n    views: Array<{ eye: 'left' | 'right'; cameraOffset: number; viewShear: number }>;\n    metadata: { stereoMode: string };\n  };\n  includeBase64?: boolean;\n  durationSeconds?: number;\n}\n\nexport interface RenderBundleResult {\n  hash: string;\n  bundleDir: string;\n  manifest: RenderArtifact;\n  previewPng: RenderArtifact;\n  quiltPng: RenderArtifact;\n  stereoLeftPng: RenderArtifact;\n  stereoRightPng: RenderArtifact;\n  stereoVideo?: RenderArtifact & { codec: string; stereoMode: string };\n  depthBackend: string;\n  holoCodePath: string;\n}\n\ninterface BrowserRenderResult {\n  previewPngDataUrl: string;\n  quiltPngDataUrl: string;\n  leftPngDataUrl: string;\n  rightPngDataUrl: string;\n  width: number;\n  height: number;\n  depthBackend: string;\n}\n\nfunction normalizeSourceUrl(source: string): string {\n  if (/^(https?:|data:|file:)/i.test(source)) return source;\n  const fullPath = isAbsolute(source) ? source : resolve(process.cwd(), source);\n  const normalized = fullPath.replace(/\\\\/g, '/');\n  return `file:///${normalized.replace(/^([A-Za-z]):/, '$1:')}`;\n}\n\nfunction bufferSha256(buffer: Buffer): string {\n  return createHash('sha256').update(buffer).digest('hex');\n}\n\nfunction encodeBundleHash(options: RenderBundleOptions): string {\n  const payload = JSON.stringify({\n    mediaType: options.mediaType,\n    source: options.source,\n    name: options.name,\n    holoCode: options.holoCode,\n    quiltConfig: options.quilt.config,\n    mvhevcConfig: options.mvhevc.config,\n    durationSeconds: options.durationSeconds ?? 2,\n    version: 1,\n  });\n  return createHash('sha256').update(payload).digest('hex');\n}\n\nexport function resolveStoreRoot(): string {\n  const explicit = process.env.HOLOGRAM_STORE_DIR?.trim();\n  if (explicit) return explicit;\n\n  const volumeCandidates = [\n    process.env.RAILWAY_VOLUME_MOUNT_PATH,\n    process.env.RAILWAY_VOLUME_PATH,\n    process.env.RAILWAY_STATIC_VOLUME_PATH,\n    process.env.RAILWAY_VOLUME_MOUNT,\n  ].filter((value): value is string => typeof value === 'string' && value.trim().length > 0);\n\n  if (volumeCandidates.length > 0) {\n    return join(volumeCandidates[0], 'holograms');\n  }\n\n  return join(tmpdir(), 'holoscript-holograms');\n}\n\nfunction buildRenderHtml(sourceUrl: string, mediaType: 'image' | 'gif' | 'video') {\n  const escapedSource = JSON.stringify(sourceUrl);\n  const escapedMediaType = JSON.stringify(mediaType);\n\n  return `<!DOCTYPE html>\n<html>\n<head>\n  <meta charset=\"utf-8\" />\n  <style>\n    html, body { margin: 0; background: black; overflow: hidden; }\n    canvas { display: block; }\n  </style>\n</head>\n<body>\n  <canvas id=\"render\"></canvas>\n  <script>\n    window.__HOLOGRAM_READY = false;\n    window.__HOLOGRAM_RENDER_ERROR = null;\n  </script>\n  <script>\n    (async () => {\n      const sourceUrl = ${escapedSource};\n      const mediaType = ${escapedMediaType};\n      const canvas = document.getElementById('render');\n      const ctx = canvas.getContext('2d');\n\n      const internalWidth = 420;\n      const internalHeight = 560;\n      canvas.width = internalWidth;\n      canvas.height = internalHeight;\n\n      const sourceCanvas = document.createElement('canvas');\n      sourceCanvas.width = internalWidth;\n      sourceCanvas.height = internalHeight;\n      const sourceCtx = sourceCanvas.getContext('2d', { willReadFrequently: true });\n\n      const depthCanvas = document.createElement('canvas');\n      depthCanvas.width = internalWidth;\n      depthCanvas.height = internalHeight;\n      const depthCtx = depthCanvas.getContext('2d', { willReadFrequently: true });\n\n      async function loadMedia() {\n        if (mediaType === 'video') {\n          const video = document.createElement('video');\n          video.src = sourceUrl;\n          video.crossOrigin = 'anonymous';\n          video.muted = true;\n          video.loop = true;\n          video.playsInline = true;\n          video.autoplay = true;\n          await new Promise((resolve, reject) => {\n            video.onloadeddata = () => resolve();\n            video.onerror = () => reject(new Error('Failed to load video source'));\n          });\n          try { await video.play(); } catch {}\n          sourceCtx.drawImage(video, 0, 0, internalWidth, internalHeight);\n          return { kind: 'video', element: video };\n        }\n\n        const img = new Image();\n        img.src = sourceUrl;\n        img.crossOrigin = 'anonymous';\n        await new Promise((resolve, reject) => {\n          img.onload = () => resolve();\n          img.onerror = () => reject(new Error('Failed to load image source'));\n        });\n        sourceCtx.drawImage(img, 0, 0, internalWidth, internalHeight);\n        return { kind: 'image', element: img };\n      }\n\n      function computeDepthMap() {\n        // Use pre-computed depth map injected by the Node.js depth estimator.\n        const injected = window.__INJECTED_DEPTH_MAP;\n        if (injected && injected.length === internalWidth * internalHeight) {\n          const depthImage = depthCtx.createImageData(internalWidth, internalHeight);\n          for (let i = 0; i < injected.length; i++) {\n            const value = Math.max(0, Math.min(255, Math.round(injected[i] * 255)));\n            depthImage.data[i * 4] = value;\n            depthImage.data[i * 4 + 1] = value;\n            depthImage.data[i * 4 + 2] = value;\n            depthImage.data[i * 4 + 3] = 255;\n          }\n          depthCtx.putImageData(depthImage, 0, 0);\n          return injected;\n        }\n\n        // Luminance-proxy fallback.\n        const imageData = sourceCtx.getImageData(0, 0, internalWidth, internalHeight);\n        const depthImage = depthCtx.createImageData(internalWidth, internalHeight);\n        const depthMap = new Float32Array(internalWidth * internalHeight);\n\n        for (let i = 0; i < depthMap.length; i++) {\n          const px = i * 4;\n          const r = imageData.data[px] / 255;\n          const g = imageData.data[px + 1] / 255;\n          const b = imageData.data[px + 2] / 255;\n          const luminance = 0.299 * r + 0.587 * g + 0.114 * b;\n          const depth = 1.0 - luminance;\n          depthMap[i] = depth;\n          const value = Math.max(0, Math.min(255, Math.round(depth * 255)));\n          depthImage.data[px] = value;\n          depthImage.data[px + 1] = value;\n          depthImage.data[px + 2] = value;\n          depthImage.data[px + 3] = 255;\n        }\n\n        depthCtx.putImageData(depthImage, 0, 0);\n        return depthMap;\n      }\n\n      function renderWarpedView(depthMap, normalizedOffset, shear = 0) {\n        const src = sourceCtx.getImageData(0, 0, internalWidth, internalHeight);\n        const dst = ctx.createImageData(internalWidth, internalHeight);\n        const maxShift = 28;\n\n        for (let y = 0; y < internalHeight; y++) {\n          for (let x = 0; x < internalWidth; x++) {\n            const dstIndex = (y * internalWidth + x) * 4;\n            const depth = depthMap[y * internalWidth + x];\n            const shift = Math.round(normalizedOffset * maxShift * (depth - 0.5) + shear * 8);\n            const srcX = Math.max(0, Math.min(internalWidth - 1, x - shift));\n            const srcIndex = (y * internalWidth + srcX) * 4;\n            dst.data[dstIndex] = src.data[srcIndex];\n            dst.data[dstIndex + 1] = src.data[srcIndex + 1];\n            dst.data[dstIndex + 2] = src.data[srcIndex + 2];\n            dst.data[dstIndex + 3] = src.data[srcIndex + 3];\n          }\n        }\n\n        return dst;\n      }\n\n      try {\n        const media = await loadMedia();\n        const depthMap = computeDepthMap();\n\n        window.__HOLOGRAM_RT = {\n          width: internalWidth,\n          height: internalHeight,\n          depthBackend: window.__INJECTED_DEPTH_BACKEND ?? 'luminance-proxy',\n          mediaKind: media.kind,\n          renderViewDataUrl(offset = 0, shear = 0) {\n            const imageData = renderWarpedView(depthMap, offset, shear);\n            ctx.putImageData(imageData, 0, 0);\n            return canvas.toDataURL('image/png');\n          },\n          renderQuiltDataUrl(tileSpecs, quiltWidth, quiltHeight, tileWidth, tileHeight) {\n            const quiltCanvas = document.createElement('canvas');\n            quiltCanvas.width = quiltWidth;\n            quiltCanvas.height = quiltHeight;\n            const quiltCtx = quiltCanvas.getContext('2d');\n\n            for (const tile of tileSpecs) {\n              const imageData = renderWarpedView(depthMap, tile.normalizedOffset, tile.viewShear || 0);\n              ctx.putImageData(imageData, 0, 0);\n              quiltCtx.drawImage(canvas, tile.column * tileWidth, tile.row * tileHeight, tileWidth, tileHeight);\n            }\n\n            return quiltCanvas.toDataURL('image/png');\n          }\n        };\n\n        window.__HOLOGRAM_READY = true;\n      } catch (error) {\n        window.__HOLOGRAM_RENDER_ERROR = error instanceof Error ? error.message : String(error);\n      }\n    })();\n  </script>\n</body>\n</html>`;\n}\n\nfunction dataUrlToBuffer(dataUrl: string): Buffer {\n  const match = dataUrl.match(/^data:([^;]+);base64,(.+)$/);\n  if (!match) throw new Error('Invalid data URL payload');\n  return Buffer.from(match[2], 'base64');\n}\n\nasync function writeArtifact(\n  bundleDir: string,\n  filename: string,\n  buffer: Buffer,\n  mimeType: string,\n  includeBase64 = false\n): Promise<RenderArtifact> {\n  const filePath = join(bundleDir, filename);\n  await fs.writeFile(filePath, buffer);\n  return {\n    path: filePath,\n    byteLength: buffer.byteLength,\n    sha256: bufferSha256(buffer),\n    mimeType,\n    ...(includeBase64 ? { base64: buffer.toString('base64') } : {}),\n  };\n}\n\nasync function renderBrowserArtifacts(\n  options: RenderBundleOptions,\n  injectedDepth?: { data: Float32Array; backend: string }\n): Promise<BrowserRenderResult> {\n  const executableResolution = resolveChromiumExecutable();\n  const launchOptions: Parameters<typeof chromium.launch>[0] = {\n    headless: true,\n    args: [\n      '--no-sandbox',\n      '--disable-gpu',\n      '--disable-dev-shm-usage',\n      '--allow-file-access-from-files',\n    ],\n  };\n  if (executableResolution.executablePath) {\n    launchOptions.executablePath = executableResolution.executablePath;\n  }\n\n  let browser: Browser;\n  try {\n    browser = await chromium.launch(launchOptions);\n  } catch (error) {\n    if (isMissingChromiumExecutableError(error) || executableResolution.source === 'missing') {\n      throw createChromiumLaunchError(error, executableResolution);\n    }\n    throw error;\n  }\n\n  try {\n    const tileWidth = options.quilt.metadata.tileWidth;\n    const tileHeight = options.quilt.metadata.tileHeight;\n    const page = await browser.newPage({ viewport: { width: tileWidth, height: tileHeight } });\n    // Inject pre-computed depth map before page scripts execute.\n    if (injectedDepth) {\n      const mapArray = Array.from(injectedDepth.data);\n      const backend = injectedDepth.backend;\n      await page.addInitScript(\n        ({ map, depthBackend }) => {\n          (window as unknown as Record<string, unknown>).__INJECTED_DEPTH_MAP = new Float32Array(\n            map\n          );\n          (window as unknown as Record<string, unknown>).__INJECTED_DEPTH_BACKEND = depthBackend;\n        },\n        { map: mapArray, depthBackend: backend }\n      );\n    }\n\n    await page.setContent(buildRenderHtml(normalizeSourceUrl(options.source), options.mediaType), {\n      waitUntil: 'domcontentloaded',\n    });\n\n    await page.waitForFunction(\n      () => {\n        const ready = (\n          window as unknown as { __HOLOGRAM_READY?: boolean; __HOLOGRAM_RENDER_ERROR?: string }\n        ).__HOLOGRAM_READY;\n        const error = (window as unknown as { __HOLOGRAM_RENDER_ERROR?: string })\n          .__HOLOGRAM_RENDER_ERROR;\n        if (error) throw new Error(error);\n        return ready === true;\n      },\n      { timeout: 30_000 }\n    );\n\n    const maxAbsOffset = options.quilt.tiles.reduce(\n      (max, tile) => Math.max(max, Math.abs(tile.cameraOffset)),\n      0.0001\n    );\n    const stereoMax = options.mvhevc.views.reduce(\n      (max, view) => Math.max(max, Math.abs(view.cameraOffset)),\n      0.0001\n    );\n\n    return await page.evaluate(\n      ({ quiltWidth, quiltHeight, tileWidth, tileHeight, tiles, stereoViews }) => {\n        const runtime = (\n          window as unknown as {\n            __HOLOGRAM_RT: {\n              width: number;\n              height: number;\n              depthBackend: string;\n              renderViewDataUrl(offset?: number, shear?: number): string;\n              renderQuiltDataUrl(\n                tileSpecs: Array<{\n                  column: number;\n                  row: number;\n                  normalizedOffset: number;\n                  viewShear: number;\n                }>,\n                quiltWidth: number,\n                quiltHeight: number,\n                tileWidth: number,\n                tileHeight: number\n              ): string;\n            };\n          }\n        ).__HOLOGRAM_RT;\n\n        return {\n          previewPngDataUrl: runtime.renderViewDataUrl(0, 0),\n          quiltPngDataUrl: runtime.renderQuiltDataUrl(\n            tiles,\n            quiltWidth,\n            quiltHeight,\n            tileWidth,\n            tileHeight\n          ),\n          leftPngDataUrl: runtime.renderViewDataUrl(\n            stereoViews.left.offset,\n            stereoViews.left.shear\n          ),\n          rightPngDataUrl: runtime.renderViewDataUrl(\n            stereoViews.right.offset,\n            stereoViews.right.shear\n          ),\n          width: runtime.width,\n          height: runtime.height,\n          depthBackend: runtime.depthBackend,\n        };\n      },\n      {\n        quiltWidth: options.quilt.config.resolution[0],\n        quiltHeight: options.quilt.config.resolution[1],\n        tileWidth,\n        tileHeight,\n        tiles: options.quilt.tiles.map((tile) => ({\n          column: tile.column,\n          row: tile.row,\n          normalizedOffset: tile.cameraOffset / maxAbsOffset,\n          viewShear: tile.viewShear,\n        })),\n        stereoViews: {\n          left: {\n            offset:\n              (options.mvhevc.views.find((view) => view.eye === 'left')?.cameraOffset ?? -0.5) /\n              stereoMax,\n            shear: options.mvhevc.views.find((view) => view.eye === 'left')?.viewShear ?? 0,\n          },\n          right: {\n            offset:\n              (options.mvhevc.views.find((view) => view.eye === 'right')?.cameraOffset ?? 0.5) /\n              stereoMax,\n            shear: options.mvhevc.views.find((view) => view.eye === 'right')?.viewShear ?? 0,\n          },\n        },\n      }\n    );\n  } finally {\n    await browser.close();\n  }\n}\n\nasync function encodeStereoVideo(\n  bundleDir: string,\n  leftPath: string,\n  rightPath: string,\n  fps: number,\n  durationSeconds: number\n): Promise<{ path: string; codec: string } | null> {\n  if (!ffmpegAvailableSync()) return null;\n\n  const ffmpegPath = resolveFfmpegBinary();\n  const outPath = join(bundleDir, 'stereo-preview.mp4');\n\n  const tryEncode = async (codec: 'libx265' | 'libx264') => {\n    const args = [\n      '-y',\n      '-loop',\n      '1',\n      '-framerate',\n      String(fps),\n      '-t',\n      String(durationSeconds),\n      '-i',\n      leftPath,\n      '-loop',\n      '1',\n      '-framerate',\n      String(fps),\n      '-t',\n      String(durationSeconds),\n      '-i',\n      rightPath,\n      '-filter_complex',\n      'hstack=inputs=2',\n      '-pix_fmt',\n      'yuv420p',\n      '-movflags',\n      '+faststart',\n      '-c:v',\n      codec,\n      ...(codec === 'libx265' ? ['-tag:v', 'hvc1'] : []),\n      outPath,\n    ];\n\n    await new Promise<void>((resolvePromise, rejectPromise) => {\n      const proc = spawn(ffmpegPath, args, { stdio: ['ignore', 'ignore', 'pipe'] });\n      let stderr = '';\n      proc.stderr.on('data', (chunk) => {\n        stderr += chunk.toString();\n      });\n      proc.on('error', rejectPromise);\n      proc.on('close', (code) => {\n        if (code === 0) {\n          resolvePromise();\n          return;\n        }\n        rejectPromise(new Error(stderr.slice(-600) || `ffmpeg exited with ${code}`));\n      });\n    });\n  };\n\n  try {\n    await tryEncode('libx265');\n    return { path: outPath, codec: 'libx265' };\n  } catch {\n    try {\n      await tryEncode('libx264');\n      return { path: outPath, codec: 'libx264' };\n    } catch {\n      return null;\n    }\n  }\n}\n\nexport async function renderHologramBundle(\n  options: RenderBundleOptions\n): Promise<RenderBundleResult> {\n  const hash = encodeBundleHash(options);\n  const storeRoot = resolveStoreRoot();\n  const bundleDir = join(storeRoot, hash);\n  await fs.mkdir(bundleDir, { recursive: true });\n\n  // Estimate depth before Playwright launch (image sources only; videos use luminance-proxy).\n  let injectedDepth: { data: Float32Array; backend: string } | undefined;\n  if (options.mediaType === 'image') {\n    const depthResult = await estimateDepthFromUrl(normalizeSourceUrl(options.source), 420, 560);\n    if (depthResult.depthMap) {\n      injectedDepth = { data: depthResult.depthMap, backend: depthResult.backend };\n    }\n  }\n\n  const browserArtifacts = await renderBrowserArtifacts(options, injectedDepth);\n\n  const previewBuffer = dataUrlToBuffer(browserArtifacts.previewPngDataUrl);\n  const quiltBuffer = dataUrlToBuffer(browserArtifacts.quiltPngDataUrl);\n  const leftBuffer = dataUrlToBuffer(browserArtifacts.leftPngDataUrl);\n  const rightBuffer = dataUrlToBuffer(browserArtifacts.rightPngDataUrl);\n\n  const holoCodePath = join(bundleDir, 'scene.holo');\n  await fs.writeFile(holoCodePath, options.holoCode, 'utf8');\n\n  const previewPng = await writeArtifact(\n    bundleDir,\n    'preview.png',\n    previewBuffer,\n    'image/png',\n    options.includeBase64\n  );\n  const quiltPng = await writeArtifact(\n    bundleDir,\n    'quilt.png',\n    quiltBuffer,\n    'image/png',\n    options.includeBase64\n  );\n  const stereoLeftPng = await writeArtifact(\n    bundleDir,\n    'left-eye.png',\n    leftBuffer,\n    'image/png',\n    options.includeBase64\n  );\n  const stereoRightPng = await writeArtifact(\n    bundleDir,\n    'right-eye.png',\n    rightBuffer,\n    'image/png',\n    options.includeBase64\n  );\n\n  const stereoVideoInfo = await encodeStereoVideo(\n    bundleDir,\n    stereoLeftPng.path,\n    stereoRightPng.path,\n    options.mvhevc.config.fps,\n    options.durationSeconds ?? 2\n  );\n\n  const stereoVideo = stereoVideoInfo\n    ? ({\n        ...(await writeArtifact(\n          bundleDir,\n          'stereo-preview.mp4',\n          await fs.readFile(stereoVideoInfo.path),\n          'video/mp4',\n          false\n        )),\n        codec: stereoVideoInfo.codec,\n        stereoMode: 'side-by-side-hevc-preview',\n      } satisfies RenderBundleResult['stereoVideo'])\n    : undefined;\n\n  const manifestPayload = {\n    hash,\n    mediaType: options.mediaType,\n    source: options.source,\n    name: options.name,\n    depthBackend: browserArtifacts.depthBackend,\n    artifacts: {\n      previewPng,\n      quiltPng,\n      stereoLeftPng,\n      stereoRightPng,\n      stereoVideo,\n      holoCodePath,\n    },\n    quilt: options.quilt,\n    mvhevc: options.mvhevc,\n    generatedAt: new Date().toISOString(),\n  };\n\n  const manifestBuffer = Buffer.from(JSON.stringify(manifestPayload, null, 2), 'utf8');\n  const manifest = await writeArtifact(\n    bundleDir,\n    'manifest.json',\n    manifestBuffer,\n    'application/json',\n    false\n  );\n\n  return {\n    hash,\n    bundleDir,\n    manifest,\n    previewPng,\n    quiltPng,\n    stereoLeftPng,\n    stereoRightPng,\n    stereoVideo,\n    depthBackend: browserArtifacts.depthBackend,\n    holoCodePath,\n  };\n}\n","/**\n * HTTP client for @holoscript/hologram-worker POST /render.\n */\n\nexport interface HologramWorkerRenderInput {\n  sourceUrl?: string;\n  sourceBase64?: string;\n  mediaType: 'image' | 'gif' | 'video';\n  targets: Array<'quilt' | 'mvhevc' | 'parallax'>;\n  skipUpload?: boolean;\n}\n\nexport interface HologramWorkerRenderResult {\n  hash: string;\n  shareUrl: string;\n  quiltUrl: string;\n  mvhevcUrl: string;\n  targets: string[];\n}\n\nfunction workerBaseUrl(): string | undefined {\n  const u = process.env.HOLOGRAM_WORKER_URL?.trim();\n  return u || undefined;\n}\n\nfunction ingressHeaders(): Record<string, string> {\n  const token = process.env.HOLOGRAM_WORKER_INGRESS_TOKEN?.trim();\n  if (!token) return {};\n  return { Authorization: `Bearer ${token}` };\n}\n\nexport function isHologramWorkerConfigured(): boolean {\n  return Boolean(workerBaseUrl());\n}\n\nexport async function callHologramWorkerRender(\n  input: HologramWorkerRenderInput\n): Promise<HologramWorkerRenderResult> {\n  const base = workerBaseUrl();\n  if (!base) throw new Error('hologram worker: HOLOGRAM_WORKER_URL is not set');\n\n  const url = `${base.replace(/\\/$/, '')}/render`;\n  const res = await fetch(url, {\n    method: 'POST',\n    headers: {\n      'Content-Type': 'application/json; charset=utf-8',\n      ...ingressHeaders(),\n    },\n    body: JSON.stringify({\n      sourceUrl: input.sourceUrl,\n      sourceBase64: input.sourceBase64,\n      mediaType: input.mediaType,\n      targets: input.targets,\n      skipUpload: input.skipUpload,\n    }),\n  });\n\n  const text = await res.text();\n  let body: unknown;\n  try {\n    body = text ? JSON.parse(text) : {};\n  } catch {\n    throw new Error(`hologram worker: invalid JSON (${res.status})`);\n  }\n\n  if (!res.ok) {\n    const err = body as { error?: string };\n    throw new Error(err.error || `hologram worker: HTTP ${res.status}`);\n  }\n\n  const o = body as Partial<HologramWorkerRenderResult>;\n  if (!o.hash) throw new Error('hologram worker: missing hash in response');\n\n  return {\n    hash: o.hash,\n    shareUrl: o.shareUrl ?? '',\n    quiltUrl: o.quiltUrl ?? '',\n    mvhevcUrl: o.mvhevcUrl ?? '',\n    targets: Array.isArray(o.targets) ? o.targets : input.targets,\n  };\n}\n","/**\n * HoloMesh team messaging for hologram share links (REST).\n */\n\nimport { createHash } from 'node:crypto';\n\nconst WINDOW_MS = 60_000;\nconst MAX_SEND_PER_WINDOW = 20;\n\nconst rateBuckets = new Map<string, number[]>();\n\n/** Default retry policy for transient HoloMesh send failures. */\nconst DEFAULT_MAX_ATTEMPTS = 3;\nconst DEFAULT_BASE_DELAY_MS = 100;\nconst DEFAULT_MAX_DELAY_MS = 2_000;\n\n/** Typed error surfaced by hologram send/publish helpers. */\nexport class HologramSendError extends Error {\n  /** True for network faults and HTTP 5xx / 408 / 429; false for 4xx and validation errors. */\n  readonly canRetry: boolean;\n  /** Underlying HTTP status when applicable, otherwise null. */\n  readonly status: number | null;\n  /** Attempt index (1-based) on which the error was thrown. */\n  readonly attempts: number;\n  /** Original cause (network error, parsed error body, etc). */\n  readonly cause?: unknown;\n\n  constructor(\n    message: string,\n    opts: { canRetry: boolean; status: number | null; attempts: number; cause?: unknown }\n  ) {\n    super(message);\n    this.name = 'HologramSendError';\n    this.canRetry = opts.canRetry;\n    this.status = opts.status;\n    this.attempts = opts.attempts;\n    this.cause = opts.cause;\n  }\n}\n\nexport interface HologramSendRetryOptions {\n  /** Maximum attempts including the first try. Minimum 1. Default 3. */\n  maxAttempts?: number;\n  /** Base backoff delay in milliseconds. Default 100ms. Actual delay = base * 2^(attempt-1), capped at maxDelayMs. */\n  baseDelayMs?: number;\n  /** Upper bound on per-attempt backoff delay. Default 2000ms. */\n  maxDelayMs?: number;\n  /** Custom sleep hook (tests). */\n  sleep?: (ms: number) => Promise<void>;\n}\n\nfunction isRetryableStatus(status: number): boolean {\n  // 408 Request Timeout, 425 Too Early, 429 Too Many Requests, and any 5xx are transient.\n  if (status === 408 || status === 425 || status === 429) return true;\n  if (status >= 500 && status < 600) return true;\n  return false;\n}\n\nfunction defaultSleep(ms: number): Promise<void> {\n  return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nfunction computeBackoffMs(attempt: number, baseMs: number, maxMs: number): number {\n  const raw = baseMs * Math.pow(2, Math.max(0, attempt - 1));\n  return Math.max(0, Math.min(maxMs, raw));\n}\n\n/** Clears in-memory send rate buckets (vitest only). */\nexport function __resetHologramSendRateForTests(): void {\n  rateBuckets.clear();\n}\n\nexport function resolveHolomeshApiBase(): string {\n  const explicit = process.env.HOLOMESH_API_BASE_URL?.trim();\n  if (explicit) return explicit.replace(/\\/$/, '');\n  const server = (\n    process.env.HOLOSCRIPT_SERVER_URL ||\n    process.env.MCP_LOCAL_URL ||\n    'https://mcp.holoscript.net'\n  ).replace(/\\/$/, '');\n  return `${server}/api/holomesh`;\n}\n\nfunction rateLimitKey(apiKey: string): string {\n  return createHash('sha256').update(apiKey).digest('hex').slice(0, 16);\n}\n\nexport function allowHologramSend(apiKey: string): boolean {\n  const key = `hologram_send:${rateLimitKey(apiKey)}`;\n  const now = Date.now();\n  const arr = rateBuckets.get(key) ?? [];\n  const pruned = arr.filter((t) => now - t < WINDOW_MS);\n  if (pruned.length >= MAX_SEND_PER_WINDOW) return false;\n  pruned.push(now);\n  rateBuckets.set(key, pruned);\n  return true;\n}\n\nexport interface TeamMemberRow {\n  agentId: string;\n  agentName?: string;\n  role?: string;\n}\n\nasync function holomeshFetchJson(\n  path: string,\n  apiKey: string,\n  init?: RequestInit\n): Promise<{ ok: boolean; status: number; json: unknown }> {\n  const base = resolveHolomeshApiBase();\n  const url = `${base}${path.startsWith('/') ? path : `/${path}`}`;\n  const res = await fetch(url, {\n    ...init,\n    headers: {\n      Accept: 'application/json',\n      ...(init?.headers as Record<string, string>),\n      Authorization: `Bearer ${apiKey}`,\n    },\n  });\n  const text = await res.text();\n  let json: unknown = {};\n  try {\n    json = text ? JSON.parse(text) : {};\n  } catch {\n    json = { raw: text };\n  }\n  return { ok: res.ok, status: res.status, json };\n}\n\n/**\n * Wraps holomeshFetchJson with a bounded retry loop for transient failures.\n *\n * Retryable: network faults (fetch throws), HTTP 408/425/429, HTTP 5xx.\n * Non-retryable: HTTP 4xx (other than above) — surfaced as HologramSendError with canRetry=false.\n *\n * On terminal failure, throws a HologramSendError with canRetry reflecting the LAST-observed\n * fault. Callers can inspect `err.canRetry` to decide whether to surface retry UI / kick off\n * a higher-level backoff, even though the inner loop has already given up on its quota.\n */\nasync function holomeshFetchJsonWithRetry(\n  label: string,\n  path: string,\n  apiKey: string,\n  init: RequestInit | undefined,\n  retry: Required<Omit<HologramSendRetryOptions, 'sleep'>> & {\n    sleep: (ms: number) => Promise<void>;\n  }\n): Promise<{ status: number; json: unknown }> {\n  let attempt = 0;\n  let lastError: HologramSendError | null = null;\n\n  while (attempt < retry.maxAttempts) {\n    attempt += 1;\n    try {\n      const { ok, status, json } = await holomeshFetchJson(path, apiKey, init);\n      if (ok) return { status, json };\n\n      const errBody = json as { error?: string };\n      const canRetry = isRetryableStatus(status);\n      const msg = errBody.error || `${label}: HTTP ${status}`;\n      lastError = new HologramSendError(msg, {\n        canRetry,\n        status,\n        attempts: attempt,\n        cause: errBody,\n      });\n      if (!canRetry) break;\n    } catch (err) {\n      // Network fault (fetch threw) — always retryable until we exhaust attempts.\n      lastError = new HologramSendError(\n        `${label}: network error — ${(err as Error).message || String(err)}`,\n        { canRetry: true, status: null, attempts: attempt, cause: err }\n      );\n    }\n\n    if (attempt >= retry.maxAttempts) break;\n    const delay = computeBackoffMs(attempt, retry.baseDelayMs, retry.maxDelayMs);\n    if (delay > 0) await retry.sleep(delay);\n  }\n\n  // If we fell out of the loop, lastError must be set.\n  throw (\n    lastError ??\n    new HologramSendError(`${label}: unknown failure`, {\n      canRetry: false,\n      status: null,\n      attempts: attempt,\n    })\n  );\n}\n\nfunction normalizeRetry(opts?: HologramSendRetryOptions): Required<\n  Omit<HologramSendRetryOptions, 'sleep'>\n> & {\n  sleep: (ms: number) => Promise<void>;\n} {\n  const maxAttempts = Math.max(1, Math.floor(opts?.maxAttempts ?? DEFAULT_MAX_ATTEMPTS));\n  const baseDelayMs = Math.max(0, opts?.baseDelayMs ?? DEFAULT_BASE_DELAY_MS);\n  const maxDelayMs = Math.max(baseDelayMs, opts?.maxDelayMs ?? DEFAULT_MAX_DELAY_MS);\n  return {\n    maxAttempts,\n    baseDelayMs,\n    maxDelayMs,\n    sleep: opts?.sleep ?? defaultSleep,\n  };\n}\n\nexport async function fetchTeamMemberIds(teamId: string, apiKey: string): Promise<TeamMemberRow[]> {\n  const { ok, status, json } = await holomeshFetchJson(\n    `/team/${encodeURIComponent(teamId)}`,\n    apiKey\n  );\n  if (!ok) {\n    const err = json as { error?: string };\n    throw new Error(err.error || `holomesh: GET team failed (${status})`);\n  }\n  const data = json as { team?: { members?: TeamMemberRow[] } };\n  const members = data.team?.members;\n  if (!Array.isArray(members)) return [];\n  return members;\n}\n\nexport function assertRecipientOnTeam(members: TeamMemberRow[], recipientAgentId: string): void {\n  const hit = members.some((m) => m.agentId === recipientAgentId);\n  if (!hit) {\n    throw new Error('hologram send: recipientAgentId is not a member of this team');\n  }\n}\n\nexport interface SendHologramMessageInput {\n  teamId: string;\n  apiKey: string;\n  hash: string;\n  shareUrl: string;\n  recipientAgentId: string;\n  note?: string;\n  /** Retry policy for transient HoloMesh failures. Omit to use defaults (3 attempts, 100ms base). */\n  retry?: HologramSendRetryOptions;\n}\n\nexport interface PublishHologramFeedInput {\n  teamId: string;\n  apiKey: string;\n  hash: string;\n  shareUrl: string;\n  /** Retry policy for transient HoloMesh failures. Omit to use defaults (3 attempts, 100ms base). */\n  retry?: HologramSendRetryOptions;\n}\n\n/** POST /team/:id/feed — public team activity (poster = Bearer identity). */\nexport async function publishHologramTeamFeed(input: PublishHologramFeedInput): Promise<unknown> {\n  const { teamId, apiKey, hash, shareUrl, retry } = input;\n  if (!apiKey.trim()) {\n    throw new HologramSendError('hologram feed: HOLOMESH_API_KEY is required', {\n      canRetry: false,\n      status: null,\n      attempts: 0,\n    });\n  }\n  if (!hash.trim() || !shareUrl.trim()) {\n    throw new HologramSendError('hologram feed: hash and shareUrl are required', {\n      canRetry: false,\n      status: null,\n      attempts: 0,\n    });\n  }\n  if (!allowHologramSend(apiKey)) {\n    // Client-side rate limit — not worth retrying on the same bucket.\n    throw new HologramSendError('hologram feed: rate limited (max 20 per minute per API key)', {\n      canRetry: false,\n      status: 429,\n      attempts: 0,\n    });\n  }\n  const payload = {\n    kind: 'hologram' as const,\n    hash: hash.trim(),\n    shareUrl: shareUrl.trim(),\n  };\n  const { json } = await holomeshFetchJsonWithRetry(\n    'holomesh: POST feed',\n    `/team/${encodeURIComponent(teamId)}/feed`,\n    apiKey,\n    {\n      method: 'POST',\n      headers: { 'Content-Type': 'application/json; charset=utf-8' },\n      body: JSON.stringify(payload),\n    },\n    normalizeRetry(retry)\n  );\n  return json;\n}\n\nexport async function sendHologramTeamMessage(input: SendHologramMessageInput): Promise<unknown> {\n  const { teamId, apiKey, hash, shareUrl, recipientAgentId, note, retry } = input;\n  if (!apiKey.trim()) {\n    throw new HologramSendError('hologram send: HOLOMESH_API_KEY is required', {\n      canRetry: false,\n      status: null,\n      attempts: 0,\n    });\n  }\n\n  if (!allowHologramSend(apiKey)) {\n    throw new HologramSendError('hologram send: rate limited (max 20 per minute per API key)', {\n      canRetry: false,\n      status: 429,\n      attempts: 0,\n    });\n  }\n\n  const members = await fetchTeamMemberIds(teamId, apiKey);\n  assertRecipientOnTeam(members, recipientAgentId);\n\n  const payload = {\n    kind: 'hologram' as const,\n    hash,\n    shareUrl,\n    recipientAgentId,\n    ...(note != null && note !== '' ? { note } : {}),\n  };\n\n  const { json } = await holomeshFetchJsonWithRetry(\n    'holomesh: POST message',\n    `/team/${encodeURIComponent(teamId)}/message`,\n    apiKey,\n    {\n      method: 'POST',\n      headers: { 'Content-Type': 'application/json; charset=utf-8' },\n      body: JSON.stringify({\n        content: JSON.stringify(payload),\n        messageType: 'hologram',\n      }),\n    },\n    normalizeRetry(retry)\n  );\n\n  return json;\n}\n","/**\n * HoloGram Bundle HTTP Client — MCP server ↔ Studio API\n *\n * Provides upload and download for content-addressed hologram bundles.\n * The MCP server may run in a different process/container from Studio,\n * so all operations go through the Studio HTTP API (not direct fs).\n */\n\nexport interface HologramBundleUploadInput {\n  /** JSON-stringified {@link HologramMeta} */\n  meta: string;\n  /** Base64-encoded depth map bytes */\n  depthBinBase64: string;\n  /** Base64-encoded normal map bytes */\n  normalBinBase64: string;\n  /** Optional base64-encoded quilt PNG */\n  quiltPngBase64?: string;\n  /** Optional base64-encoded MV-HEVC MP4 */\n  mvhevcMp4Base64?: string;\n  /** Optional base64-encoded parallax WebM */\n  parallaxWebmBase64?: string;\n}\n\nexport interface HologramBundleUploadResult {\n  hash: string;\n  written: boolean;\n  url: string;\n}\n\nexport interface HologramAssetGetResult {\n  base64: string;\n  mimeType: string;\n  byteLength: number;\n}\n\nfunction studioBaseUrl(): string {\n  return (\n    process.env.HOLOGRAM_STUDIO_URL?.trim() ||\n    process.env.HOLOSCRIPT_RENDER_URL?.trim() ||\n    'http://localhost:3000'\n  );\n}\n\nfunction buildUploadUrl(): string {\n  return `${studioBaseUrl().replace(/\\/$/, '')}/api/hologram/upload`;\n}\n\nfunction buildAssetUrl(hash: string, asset: string): string {\n  return `${studioBaseUrl().replace(/\\/$/, '')}/api/hologram/${encodeURIComponent(hash)}/${encodeURIComponent(asset)}`;\n}\n\nfunction base64ToBlob(b64: string): Blob {\n  const buf = Buffer.from(b64, 'base64');\n  return new Blob([buf]);\n}\n\n/**\n * Upload a hologram bundle to the Studio store.\n *\n * Uses multipart/form-data. Authenticates with HOLOGRAM_WORKER_TOKEN\n * (Bearer) when available; otherwise relies on session auth if the\n * Studio and MCP server share a cookie jar (same-origin deploy).\n */\nexport async function uploadHologramBundle(\n  input: HologramBundleUploadInput\n): Promise<HologramBundleUploadResult> {\n  const fd = new FormData();\n  fd.append('meta', input.meta);\n  fd.append('depth.bin', base64ToBlob(input.depthBinBase64), 'depth.bin');\n  fd.append('normal.bin', base64ToBlob(input.normalBinBase64), 'normal.bin');\n\n  if (input.quiltPngBase64) {\n    fd.append('quilt.png', base64ToBlob(input.quiltPngBase64), 'quilt.png');\n  }\n  if (input.mvhevcMp4Base64) {\n    fd.append('mvhevc.mp4', base64ToBlob(input.mvhevcMp4Base64), 'mvhevc.mp4');\n  }\n  if (input.parallaxWebmBase64) {\n    fd.append('parallax.webm', base64ToBlob(input.parallaxWebmBase64), 'parallax.webm');\n  }\n\n  const headers: Record<string, string> = {};\n  const token = process.env.HOLOGRAM_WORKER_TOKEN?.trim();\n  if (token) {\n    headers['Authorization'] = `Bearer ${token}`;\n  }\n\n  const res = await fetch(buildUploadUrl(), {\n    method: 'POST',\n    headers,\n    body: fd,\n  });\n\n  const text = await res.text();\n  let body: Record<string, unknown> = {};\n  try {\n    body = text ? (JSON.parse(text) as Record<string, unknown>) : {};\n  } catch {\n    // leave body empty on parse failure\n  }\n\n  if (!res.ok) {\n    const err = typeof body.error === 'string' ? body.error : `hologram upload: HTTP ${res.status}`;\n    throw new Error(err);\n  }\n\n  return {\n    hash: String(body.hash ?? ''),\n    written: Boolean(body.written),\n    url: String(body.url ?? ''),\n  };\n}\n\n/**\n * Retrieve a hologram bundle asset by content hash.\n *\n * Public read — no auth required. Returns base64-encoded bytes\n * so the MCP tool response stays JSON-safe.\n */\nexport async function getHologramAsset(\n  hash: string,\n  asset: string\n): Promise<HologramAssetGetResult> {\n  const res = await fetch(buildAssetUrl(hash, asset));\n\n  if (!res.ok) {\n    const text = await res.text();\n    let body: Record<string, unknown> = {};\n    try {\n      body = text ? (JSON.parse(text) as Record<string, unknown>) : {};\n    } catch {\n      // ignore\n    }\n    const err =\n      typeof body.error === 'string' ? body.error : `hologram get asset: HTTP ${res.status}`;\n    throw new Error(err);\n  }\n\n  const buf = Buffer.from(await res.arrayBuffer());\n  const mimeType = res.headers.get('Content-Type') || 'application/octet-stream';\n\n  return {\n    base64: buf.toString('base64'),\n    mimeType,\n    byteLength: buf.byteLength,\n  };\n}\n","/**\n * HoloPortal Intent Envelope (HoloGate representation axis)\n *\n * An entity entering a HoloGate portal does NOT push arbitrary JSON at the\n * authoritative state plane — it pushes a *typed intent* (move/look/grab/say)\n * that is validated against the entrant's HoloDoor spatial scope before it ever\n * becomes a state delta. This closes the W.204 injection surface on the\n * previously-unscoped `push_state_delta` payload.\n *\n * Scope ladder (from HoloDoor policy `spatial` block, schema 1.1.0):\n *   read-only   — observe only; every mutating intent is rejected.\n *   mutate-zone — may move/grab zone-scoped entities whose id matches a\n *                 mutableZoneGlob; avatar orientation/speech still denied.\n *   drive-avatar— may drive an embodied avatar (move/look/say) up to\n *                 maxEntities, and inherits mutate-zone rights (superset).\n *\n * Pure module: no MCP / IO dependencies, fully unit-testable. Consumed by\n * networking-tools.ts (`push_portal_intent` tool).\n *\n * Board task: task_1779436414661_5vmv\n */\n\nexport type SpatialScope = 'read-only' | 'mutate-zone' | 'drive-avatar';\n\nexport interface SpatialPolicy {\n  defaultScope?: SpatialScope;\n  /** If non-empty, the effective scope must be a member. */\n  allowedScopes?: SpatialScope[];\n  /** Glob patterns for entity/target ids an entrant may mutate under mutate-zone. */\n  mutableZoneGlobs?: string[];\n  driveAvatar?: { allow?: boolean; maxEntities?: number };\n  enforcement?: { onScopeViolation?: 'reject' | 'warn' };\n}\n\nexport type PortalIntent =\n  | { kind: 'move'; entityId: string; position: Vec3 }\n  | { kind: 'look'; entityId: string; rotation: Quat }\n  | { kind: 'grab'; entityId: string; targetId: string }\n  | { kind: 'say'; entityId: string; utterance: string };\n\nexport interface Vec3 {\n  x: number;\n  y: number;\n  z: number;\n}\nexport interface Quat {\n  x: number;\n  y: number;\n  z: number;\n  w?: number;\n}\n\nexport interface IntentValidation {\n  allowed: boolean;\n  /** Effective scope the decision was made under. */\n  scope: SpatialScope;\n  /** Human-readable reason when rejected (or warned). */\n  reason?: string;\n  /** When enforcement=warn, allowed stays true but warned is set. */\n  warned?: boolean;\n}\n\nconst SCOPE_RANK: Record<SpatialScope, number> = {\n  'read-only': 0,\n  'mutate-zone': 1,\n  'drive-avatar': 2,\n};\n\n/** Tiny glob matcher: `*` matches any run of chars. Anchored full-match. */\nexport function matchesZoneGlob(id: string, globs: string[] | undefined): boolean {\n  if (!globs || globs.length === 0) return false;\n  return globs.some((g) => {\n    const re = new RegExp(\n      '^' +\n        g\n          .split('*')\n          .map((s) => s.replace(/[.+?^${}()|[\\]\\\\]/g, '\\\\$&'))\n          .join('.*') +\n        '$'\n    );\n    return re.test(id);\n  });\n}\n\n/**\n * Validate a portal intent against the entrant's spatial scope.\n *\n * @param intent           the typed intent the entrant wishes to perform\n * @param policy           the HoloDoor `spatial` policy block for the world/team\n * @param requestedScope   scope the portal granted this entrant (defaults to policy.defaultScope)\n * @param driveAvatarActiveCount current number of avatars this entrant already drives (registry-supplied)\n */\nexport function validatePortalIntent(\n  intent: PortalIntent,\n  policy: SpatialPolicy | undefined,\n  requestedScope?: SpatialScope,\n  driveAvatarActiveCount = 0\n): IntentValidation {\n  const p: SpatialPolicy = policy ?? {};\n  const scope: SpatialScope = requestedScope ?? p.defaultScope ?? 'read-only';\n  const warn = p.enforcement?.onScopeViolation === 'warn';\n\n  const deny = (reason: string): IntentValidation =>\n    warn ? { allowed: true, scope, reason, warned: true } : { allowed: false, scope, reason };\n  const allow = (): IntentValidation => ({ allowed: true, scope });\n\n  // The requested scope itself must be permitted by the policy.\n  if (p.allowedScopes && p.allowedScopes.length > 0 && !p.allowedScopes.includes(scope)) {\n    return deny(`scope '${scope}' is not in allowedScopes [${p.allowedScopes.join(', ')}]`);\n  }\n\n  const rank = SCOPE_RANK[scope];\n\n  // read-only: every mutating intent is rejected.\n  if (rank < SCOPE_RANK['mutate-zone']) {\n    return deny(`scope 'read-only' cannot perform '${intent.kind}'`);\n  }\n\n  switch (intent.kind) {\n    case 'move':\n    case 'grab': {\n      const targetId = intent.kind === 'grab' ? intent.targetId : intent.entityId;\n      // drive-avatar inherits zone rights; if the entrant drives this entity it's allowed,\n      // otherwise the target must fall inside a mutable zone glob.\n      if (rank >= SCOPE_RANK['drive-avatar']) return allow();\n      if (matchesZoneGlob(targetId, p.mutableZoneGlobs)) return allow();\n      return deny(\n        `'${intent.kind}' on '${targetId}' requires it to match a mutableZoneGlob under scope 'mutate-zone'`\n      );\n    }\n    case 'look':\n    case 'say': {\n      // Avatar orientation + speech are embodied actions → require drive-avatar.\n      if (rank < SCOPE_RANK['drive-avatar']) {\n        return deny(`'${intent.kind}' is an embodied action requiring scope 'drive-avatar'`);\n      }\n      if (p.driveAvatar && p.driveAvatar.allow === false) {\n        return deny(`drive-avatar lane is disabled by policy (driveAvatar.allow=false)`);\n      }\n      const max = p.driveAvatar?.maxEntities ?? 0;\n      if (max > 0 && driveAvatarActiveCount >= max) {\n        return deny(`drive-avatar limit reached (${driveAvatarActiveCount}/${max})`);\n      }\n      return allow();\n    }\n    default:\n      return deny(`unknown intent kind`);\n  }\n}\n\n/** Convert a validated intent into an authoritative state delta. */\nexport function intentToDelta(\n  intent: PortalIntent,\n  nowMs: number = Date.now()\n): { entityId: string; payload: Record<string, unknown> } {\n  switch (intent.kind) {\n    case 'move':\n      return {\n        entityId: intent.entityId,\n        payload: { transform: { position: intent.position }, updatedAt: nowMs },\n      };\n    case 'look':\n      return {\n        entityId: intent.entityId,\n        payload: { transform: { rotation: intent.rotation }, updatedAt: nowMs },\n      };\n    case 'grab':\n      return { entityId: intent.entityId, payload: { holding: intent.targetId, updatedAt: nowMs } };\n    case 'say':\n      return {\n        entityId: intent.entityId,\n        payload: { lastUtterance: intent.utterance, utteranceTs: nowMs },\n      };\n  }\n}\n\n/**\n * Deep-merge `source` into `target`, returning a new object. Plain objects are\n * merged recursively; arrays and primitives are replaced. Fixes the shallow\n * Last-Write-Wins clobber where two entrants editing different sub-fields of the\n * same nested object would overwrite each other.\n *\n * Board task: task_1779436414662_8b0d (concurrency edge).\n */\nexport function deepMerge<T extends Record<string, any>>(\n  target: T,\n  source: Record<string, any>\n): T {\n  const out: Record<string, any> = { ...target };\n  for (const key of Object.keys(source)) {\n    const sv = source[key];\n    const tv = out[key];\n    if (isPlainObject(sv) && isPlainObject(tv)) {\n      out[key] = deepMerge(tv, sv);\n    } else {\n      out[key] = sv;\n    }\n  }\n  return out as T;\n}\n\nfunction isPlainObject(v: unknown): v is Record<string, any> {\n  return typeof v === 'object' && v !== null && !Array.isArray(v);\n}\n","import { Tool } from '@modelcontextprotocol/sdk/types.js';\nimport * as fs from 'fs';\nimport * as os from 'os';\nimport * as path from 'path';\nimport { Loro, LoroMap } from 'loro-crdt';\nimport {\n  validatePortalIntent,\n  intentToDelta,\n  type PortalIntent,\n  type SpatialPolicy,\n  type SpatialScope,\n} from './holo-portal-intent.js';\n\nconst HOLO_DIR = process.env.HOLOSCRIPT_CACHE_DIR || path.join(os.homedir(), '.holoscript');\nconst STATE_AUTHORITY_FILE = path.join(HOLO_DIR, 'state-authority.json');\nconst STATE_AUTHORITY_LORO_FILE = path.join(HOLO_DIR, 'state-authority.loro');\n\n// ---------------------------------------------------------------------------\n// Loro CRDT authoritative state (replaces LWW deep-merge globalStateAuthority).\n// Board task: task_1779438040591_o53t — true multi-agent concurrent presence\n// convergence via Loro instead of last-writer-wins deep-merge.\n// ---------------------------------------------------------------------------\n\nconst loroDoc = new Loro();\nloroDoc.setPeerId(BigInt(Date.now() % Number.MAX_SAFE_INTEGER));\n\n/** Top-level LoroMap keyed by entityId — each value is a nested LoroMap of fields. */\nconst entitiesMap = loroDoc.getMap('entities');\n\n// ---------------------------------------------------------------------------\n// Legacy disk migration: load old JSON state into Loro on first startup.\n// After migration, the .loro binary file is the source of truth.\n// ---------------------------------------------------------------------------\nfunction migrateLegacyJsonToLoro(): void {\n  try {\n    if (fs.existsSync(STATE_AUTHORITY_FILE) && !fs.existsSync(STATE_AUTHORITY_LORO_FILE)) {\n      const raw = fs.readFileSync(STATE_AUTHORITY_FILE, 'utf-8');\n      const legacy = JSON.parse(raw) as Record<string, Record<string, unknown>>;\n      for (const [entityId, fields] of Object.entries(legacy)) {\n        if (!fields || typeof fields !== 'object') continue;\n        const entityMap = entitiesMap.setContainer(entityId, new LoroMap());\n        for (const [key, value] of Object.entries(fields)) {\n          entityMap.set(key, JSON.stringify(value));\n        }\n      }\n      loroDoc.commit();\n      // Persist the Loro snapshot and remove the legacy JSON file\n      persistLoroToDisk();\n      try {\n        fs.renameSync(STATE_AUTHORITY_FILE, STATE_AUTHORITY_FILE + '.migrated');\n      } catch {\n        /* best-effort */\n      }\n      console.info('[networking] Migrated legacy state-authority.json → Loro CRDT');\n    }\n  } catch (err) {\n    console.warn(\n      `[networking] Legacy JSON migration failed: ${err instanceof Error ? err.message : String(err)}`\n    );\n  }\n}\n\n/** Load Loro snapshot from disk (or fall back to legacy JSON migration). */\nfunction loadLoroFromDisk(): void {\n  try {\n    if (fs.existsSync(STATE_AUTHORITY_LORO_FILE)) {\n      const data = fs.readFileSync(STATE_AUTHORITY_LORO_FILE);\n      loroDoc.import(data);\n      return;\n    }\n  } catch (err) {\n    console.warn(\n      `[CacheDebug][networking] Loro load miss: ${err instanceof Error ? err.message : String(err)}`\n    );\n  }\n  // No .loro file → try legacy JSON migration\n  migrateLegacyJsonToLoro();\n}\n\nfunction persistLoroToDisk(): void {\n  try {\n    if (!fs.existsSync(HOLO_DIR)) {\n      fs.mkdirSync(HOLO_DIR, { recursive: true });\n    }\n    const snapshot = loroDoc.export({ mode: 'snapshot' });\n    fs.writeFileSync(STATE_AUTHORITY_LORO_FILE, snapshot);\n  } catch {\n    console.warn(`[CacheDebug][networking] Loro persist miss path=${STATE_AUTHORITY_LORO_FILE}`);\n  }\n}\n\n// Load on startup\nloadLoroFromDisk();\n\n// ---------------------------------------------------------------------------\n// Delta broadcast — real subscriber-registry fan-out (replaces the prior no-op).\n// The MCP tool layer owns the *registry*, not the socket: a WS/WebRTC relay (or\n// the HoloTunnel runtime) registers a subscriber via subscribeToStateDeltas and\n// pushes the deltas to co-present entities. This is the build-internal WS\n// fan-out seam (WebRTC peer transport is a later perf upgrade).\n// Board task: task_1779436414662_8b0d (transport edge).\n// ---------------------------------------------------------------------------\ninterface StateDelta {\n  entityId: string;\n  field: string;\n  oldValue: unknown;\n  newValue: unknown;\n}\ntype DeltaSubscriber = (deltas: StateDelta[]) => void;\nconst deltaSubscribers = new Set<DeltaSubscriber>();\n\n/** Register a subscriber that receives every committed delta batch. Returns an unsubscribe fn. */\nexport function subscribeToStateDeltas(fn: DeltaSubscriber): () => void {\n  deltaSubscribers.add(fn);\n  return () => deltaSubscribers.delete(fn);\n}\n\n/** For tests: number of currently registered subscribers. */\nexport function __stateDeltaSubscriberCount(): number {\n  return deltaSubscribers.size;\n}\n\nfunction broadcastDeltas(deltas: StateDelta[]): void {\n  if (deltas.length === 0) return;\n  for (const sub of deltaSubscribers) {\n    // One bad subscriber must not stall the fan-out to the others.\n    try {\n      sub(deltas);\n    } catch (err) {\n      console.warn(\n        `[networking] delta subscriber threw: ${err instanceof Error ? err.message : String(err)}`\n      );\n    }\n  }\n}\n\n// ---------------------------------------------------------------------------\n// WebRTC peer transport — low-latency peer-to-peer Loro CRDT sync.\n// Board task: task_1779438040591_uj7g.\n// When enabled, Loro doc changes are synced directly between peers via WebRTC\n// data channels (bypassing the server-relayed WS subscriber path for latency-\n// sensitive multi-party presence). The WS fan-out (subscribeToStateDeltas)\n// remains the local/relay path; WebRTC is the peer-to-peer complement.\n//\n// Uses dynamic import of @holoscript/crdt-spatial (not a static dep of\n// mcp-server) so the module loads even when crdt-spatial is absent.\n// ---------------------------------------------------------------------------\n\n// Minimal type for the provider — avoids static import.\ninterface LoroWebRTCProviderLike {\n  connect(): void;\n  disconnect(): void;\n}\n\nlet webrtcProvider: LoroWebRTCProviderLike | null = null;\n\nexport interface WebRTCTransportConfig {\n  /** Room identifier for the WebRTC signaling channel. Default: 'holoport-default'. */\n  room?: string;\n  /** WebSocket URL of the WebRTC signaling server. */\n  signalingServerUrl?: string;\n  /** ICE servers for NAT traversal. */\n  iceServers?: Array<{ urls: string }>;\n  /** Interval in ms between Loro CRDT syncs over WebRTC. Default: 50. */\n  syncIntervalMs?: number;\n}\n\n/**\n * Enable WebRTC peer transport for the Loro CRDT doc. After calling this,\n * local Loro changes are automatically synced to connected peers via WebRTC\n * data channels. Call once at server startup or when a HoloPortal is opened.\n *\n * @param config WebRTC configuration (signaling server URL, ICE servers, room).\n * @returns the active LoroWebRTCProvider instance.\n */\nexport async function enableWebRTCTransport(\n  config?: WebRTCTransportConfig\n): Promise<LoroWebRTCProviderLike> {\n  if (webrtcProvider) {\n    console.warn('[networking] WebRTC transport already enabled — returning existing provider.');\n    return webrtcProvider;\n  }\n  try {\n    // @ts-ignore -- @holoscript/crdt-spatial is an optional runtime dep with no devDep types\n    const { LoroWebRTCProvider } = await import('@holoscript/crdt-spatial');\n    const room = config?.room ?? 'holoport-default';\n    const provider = new LoroWebRTCProvider(loroDoc, room, {\n      signalingServerUrl: config?.signalingServerUrl,\n      iceServers: config?.iceServers,\n      syncIntervalMs: config?.syncIntervalMs,\n    }) as LoroWebRTCProviderLike;\n    webrtcProvider = provider;\n    provider.connect();\n    console.info(`[networking] WebRTC peer transport enabled for room '${room}'.`);\n    return provider;\n  } catch (err) {\n    throw new Error(\n      `Failed to enable WebRTC transport: ${err instanceof Error ? err.message : String(err)}. ` +\n        `Ensure @holoscript/crdt-spatial is installed.`\n    );\n  }\n}\n\n/**\n * Disable WebRTC peer transport. Disconnects from signaling server and\n * closes all peer connections.\n */\nexport function disableWebRTCTransport(): void {\n  if (webrtcProvider) {\n    webrtcProvider.disconnect();\n    webrtcProvider = null;\n    console.info('[networking] WebRTC peer transport disabled.');\n  }\n}\n\n/**\n * Check whether WebRTC peer transport is currently active.\n */\nexport function isWebRTCTransportEnabled(): boolean {\n  return webrtcProvider !== null;\n}\n\n/**\n * Commit a payload into the authoritative Loro CRDT state, persist, and\n * broadcast the resulting deltas. Shared by push_state_delta and\n * push_portal_intent. Loro CRDT converges concurrent writes without clobbering\n * (unlike the prior deep-merge LWW path). Board task: task_1779438040591_o53t.\n */\nfunction commitState(\n  entityId: string,\n  payload: Record<string, unknown>\n): {\n  status: 'success' | 'skipped';\n  deltaCount: number;\n} {\n  // Read current state from Loro\n  const oldState = readEntityFromLoro(entityId);\n\n  // Write each field into the entity's LoroMap (CRDT merge)\n  let entityMap = entitiesMap.get(entityId) as LoroMap | undefined;\n  if (!entityMap) {\n    entityMap = entitiesMap.setContainer(entityId, new LoroMap());\n  }\n  for (const [key, value] of Object.entries(payload)) {\n    entityMap.set(key, JSON.stringify(value));\n  }\n  loroDoc.commit();\n\n  // Read new state and compute deltas for broadcast\n  const newState = readEntityFromLoro(entityId);\n  const deltas = computeDeltas(entityId, oldState, newState);\n  if (deltas.length === 0) return { status: 'skipped', deltaCount: 0 };\n\n  persistLoroToDisk();\n  broadcastDeltas(deltas);\n  return { status: 'success', deltaCount: deltas.length };\n}\n\n/** Read all fields of an entity from Loro as a plain object. */\nfunction readEntityFromLoro(entityId: string): Record<string, unknown> {\n  const entityMap = entitiesMap.get(entityId) as LoroMap | undefined;\n  if (!entityMap) return {};\n  const raw = entityMap.toJSON() as Record<string, string>;\n  const result: Record<string, unknown> = {};\n  for (const [key, value] of Object.entries(raw)) {\n    try {\n      result[key] = JSON.parse(value);\n    } catch {\n      result[key] = value;\n    }\n  }\n  return result;\n}\n\n/** Compute field-level deltas between two plain objects */\nfunction computeDeltas(\n  entityId: string,\n  oldState: Record<string, unknown>,\n  newState: Record<string, unknown>\n): Array<{ entityId: string; field: string; oldValue: unknown; newValue: unknown }> {\n  const deltas: StateDelta[] = [];\n  for (const key of Object.keys(newState)) {\n    if (oldState[key] !== newState[key]) {\n      deltas.push({ entityId, field: key, oldValue: oldState[key], newValue: newState[key] });\n    }\n  }\n  return deltas;\n}\n\n/**\n * MCP Tools for Delta Replication and State Synchronization\n * Gives LLM Agents and remote servers the ability to natively subscribe to\n * and publish push-based state delta increments.\n */\nexport const networkingTools: Tool[] = [\n  {\n    name: 'push_state_delta',\n    description:\n      'Push a raw spatial or semantic state delta securely to the Global Sync Mesh. ' +\n      'Automatically performs Server-Authoritative Conflict Resolution (Last-Write-Wins) and diff compression.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        entityId: {\n          type: 'string',\n          description: 'The UUID of the Entity undergoing a state transition.',\n        },\n        payload: {\n          type: 'object',\n          description:\n            'A JSON object containing only the fields that have been modified (new values).',\n        },\n      },\n      required: ['entityId', 'payload'],\n    },\n  },\n  {\n    name: 'fetch_authoritative_state',\n    description:\n      'Pull the current absolute truth for an Entity from the StateAuthority layer safely bypassing out-of-sync local caches.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        entityId: { type: 'string', description: 'The UUID of the target Entity.' },\n      },\n      required: ['entityId'],\n    },\n  },\n  {\n    name: 'push_portal_intent',\n    description:\n      'Push a typed HoloPortal presence intent (move/look/grab/say) on behalf of an entity ' +\n      'entering a HoloGate portal. The intent is validated against the entrant’s HoloDoor ' +\n      'spatial scope (read-only < mutate-zone < drive-avatar) BEFORE it becomes a state delta — ' +\n      'this is the scoped, agent-native alternative to pushing raw payloads at push_state_delta. ' +\n      'Rejected intents do not mutate state (unless policy enforcement is \"warn\").',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        intent: {\n          type: 'object',\n          description:\n            'Typed intent. kind=move {entityId,position:{x,y,z}} | look {entityId,rotation:{x,y,z,w?}} | grab {entityId,targetId} | say {entityId,utterance}.',\n        },\n        requestedScope: {\n          type: 'string',\n          enum: ['read-only', 'mutate-zone', 'drive-avatar'],\n          description:\n            'Scope the portal granted this entrant. Defaults to the policy defaultScope.',\n        },\n        spatialPolicy: {\n          type: 'object',\n          description:\n            'The HoloDoor `spatial` policy block for the world/team (fetched at the portal threshold). Omit to default-deny (read-only).',\n        },\n        driveAvatarActiveCount: {\n          type: 'number',\n          description:\n            'Avatars this entrant already drives (for drive-avatar maxEntities enforcement). Default 0.',\n        },\n      },\n      required: ['intent'],\n    },\n  },\n];\n\nexport async function handleNetworkingTool(name: string, args: any): Promise<any> {\n  switch (name) {\n    case 'push_state_delta': {\n      const { entityId, payload } = args;\n      if (!entityId || typeof entityId !== 'string')\n        throw new Error(\"Missing or invalid 'entityId'\");\n\n      const result = commitState(entityId, (payload ?? {}) as Record<string, unknown>);\n      return result.status === 'success'\n        ? {\n            status: 'success',\n            message: `State replicated. Server Authority resolved ${result.deltaCount} deltas securely.`,\n          }\n        : { status: 'skipped', message: `Payload contained no diff against authoritative state.` };\n    }\n    case 'push_portal_intent': {\n      const intent = args?.intent as PortalIntent | undefined;\n      if (!intent || typeof intent !== 'object' || typeof (intent as any).kind !== 'string')\n        throw new Error(\"Missing or invalid 'intent' (need { kind, entityId, ... })\");\n      if (!('entityId' in intent) || typeof (intent as any).entityId !== 'string')\n        throw new Error(\"Intent missing 'entityId'\");\n\n      const policy = args?.spatialPolicy as SpatialPolicy | undefined;\n      const requestedScope = args?.requestedScope as SpatialScope | undefined;\n      const activeCount =\n        typeof args?.driveAvatarActiveCount === 'number' ? args.driveAvatarActiveCount : 0;\n\n      const verdict = validatePortalIntent(intent, policy, requestedScope, activeCount);\n      if (!verdict.allowed) {\n        return {\n          status: 'rejected',\n          scope: verdict.scope,\n          reason: verdict.reason,\n          message: `Intent '${intent.kind}' rejected: ${verdict.reason}`,\n        };\n      }\n\n      const { entityId, payload } = intentToDelta(intent);\n      const result = commitState(entityId, payload);\n      return {\n        status: result.status === 'success' ? 'success' : 'skipped',\n        scope: verdict.scope,\n        ...(verdict.warned ? { warned: true, warning: verdict.reason } : {}),\n        message:\n          result.status === 'success'\n            ? `Intent '${intent.kind}' applied under scope '${verdict.scope}' (${result.deltaCount} deltas).`\n            : `Intent '${intent.kind}' produced no state change.`,\n      };\n    }\n    case 'fetch_authoritative_state': {\n      const { entityId } = args;\n      if (!entityId || typeof entityId !== 'string')\n        throw new Error(\"Missing or invalid 'entityId'\");\n      const state = readEntityFromLoro(entityId);\n      return Object.keys(state).length > 0 ? state : { _null: true };\n    }\n    default:\n      return null;\n  }\n}\n\n// ---------------------------------------------------------------------------\n// Test helpers\n// ---------------------------------------------------------------------------\n\n/** Reset Loro CRDT state for tests. Clears all entities from the doc. */\nexport function __resetNetworkingState(): void {\n  const entities = loroDoc.getMap('entities');\n  for (const key of Object.keys(entities.toJSON() as Record<string, unknown>)) {\n    entities.delete(key);\n  }\n  loroDoc.commit();\n}\n","/**\n * Hologram Media MCP tools — single-image/GIF/video -> 3D hologram pipeline.\n *\n * This surface intentionally targets the Hologram Media Pipeline in\n * `@holoscript/engine/hologram` (DepthEstimation/Quilt/MV-HEVC), not HoloMap.\n */\n\nimport type { Tool } from '@modelcontextprotocol/sdk/types.js';\nimport {\n  MVHEVCCompiler,\n  QuiltCompiler,\n  type MVHEVCConfig,\n  type QuiltConfig,\n} from '@holoscript/engine/hologram';\nimport { renderHologramBundle } from './hologram-renderer';\nimport { callHologramWorkerRender, isHologramWorkerConfigured } from './hologram-worker-client';\nimport { publishHologramTeamFeed, sendHologramTeamMessage } from './hologram-holomesh-send';\nimport { getHologramAsset, uploadHologramBundle } from './hologram-bundle-client';\nimport { resolveSecretWithLease, VaultLeaseError } from './holomesh/identity/vault-lease-registry';\nimport { assertPublicCaptureConsent, capturePrivacyInputSchema } from './capture-consent';\n\n/**\n * Phase 2 wrapper around `process.env.HOLOMESH_API_KEY` for hot per-request\n * hologram routes (publish_feed, send). Migration-window passthrough until\n * HOLOMESH_VAULT_LEASE_ENFORCE flips on, after which the read is gated by\n * an active task lease scoped to `env:HOLOMESH_API_KEY`. Returning '' on\n * VaultLeaseError preserves the previous `?.trim() || ''` semantics.\n */\nfunction readHolomeshApiKey(): string {\n  try {\n    return resolveSecretWithLease('env:HOLOMESH_API_KEY')?.trim() ?? '';\n  } catch (err) {\n    if (err instanceof VaultLeaseError) return '';\n    throw err;\n  }\n}\n\ntype HologramMediaType = 'image' | 'gif' | 'video';\ntype HologramTarget = 'quilt' | 'mvhevc' | 'parallax';\n\n/**\n * Maximum inline base64 payload length accepted by the MCP tool layer before\n * we ever reach the worker or local renderer. This is intentionally tighter\n * than {@link import('../../../studio/src/app/api/hologram/_lib/store').MAX_HOLOGRAM_UPLOAD_BYTES}\n * (Studio's dedicated upload route, 100 MiB) because MCP payloads travel\n * inline over JSON-RPC and are far more expensive per byte. Override with\n * `HOLOGRAM_MCP_MAX_BASE64_BYTES` (decimal byte count).\n *\n * Source gap: .ai-ecosystem/scripts/hologram-reliability-matrix.json\n * (id: oversized-payload-rejection — abuse-path, high severity).\n */\nconst DEFAULT_MAX_HOLOGRAM_BASE64_BYTES = 10 * 1024 * 1024; // 10 MiB of base64 (~7.5 MiB decoded)\nconst HOLOGRAM_ASSETS = new Set([\n  'depth.bin',\n  'normal.bin',\n  'quilt.png',\n  'mvhevc.mp4',\n  'parallax.webm',\n]);\n\nfunction getMaxHologramBase64Bytes(): number {\n  const raw = process.env.HOLOGRAM_MCP_MAX_BASE64_BYTES;\n  if (!raw) return DEFAULT_MAX_HOLOGRAM_BASE64_BYTES;\n  const parsed = Number.parseInt(raw, 10);\n  if (!Number.isFinite(parsed) || parsed <= 0) return DEFAULT_MAX_HOLOGRAM_BASE64_BYTES;\n  return parsed;\n}\n\nfunction assertBase64WithinLimit(b64: string, label = 'sourceBase64'): void {\n  const cap = getMaxHologramBase64Bytes();\n  if (b64.length > cap) {\n    throw new Error(\n      `hologram: oversized hologram payload — ${label} length ${b64.length} exceeds cap ${cap} bytes (set HOLOGRAM_MCP_MAX_BASE64_BYTES to override)`\n    );\n  }\n}\n\n/**\n * Reject obviously-invalid base64 before we build a data: URL or forward bytes\n * to the worker. This is intentionally conservative: we accept the RFC 4648\n * base64 alphabet (A–Z, a–z, 0–9, +, /) plus the URL-safe variant (-, _), and\n * tolerate trailing `=` padding plus inline whitespace. Anything else (e.g.\n * `\"!!!not base64!!!\"`, ASCII control chars, unicode, null) is refused with\n * an explicit \"malformed media payload\" error instead of silently flowing\n * into the worker as a broken data: URL.\n *\n * Source gap: .ai-ecosystem/scripts/hologram-reliability-matrix.json\n * (id: malformed-media-input — abuse-path, high severity).\n */\nconst BASE64_RE = /^[A-Za-z0-9+/\\-_]+=*$/;\n\nfunction assertBase64WellFormed(b64: string, label = 'sourceBase64'): void {\n  if (b64.length === 0) {\n    // Empty-string branch is handled by resolveCompositionSource which throws\n    // \"one of source, sourceUrl, or sourceBase64 is required\"; don't shadow it.\n    return;\n  }\n  const stripped = b64.replace(/\\s+/g, '');\n  if (stripped.length === 0 || stripped.length % 4 === 1 || !BASE64_RE.test(stripped)) {\n    throw new Error(\n      `hologram: malformed media payload — ${label} is not well-formed base64 (RFC 4648 alphabet A-Z a-z 0-9 + / = or URL-safe - _ only)`\n    );\n  }\n}\n\nfunction assertBundleBase64Field(label: string, value: string | undefined): void {\n  if (!value) return;\n  assertBase64WithinLimit(value, label);\n  assertBase64WellFormed(value, label);\n}\n\nfunction assertInlineSourceWithinLimit(source: string): void {\n  if (!source.startsWith('data:')) return;\n  const m = /^data:[^;]+;base64,(.+)$/i.exec(source);\n  if (m) {\n    assertBase64WithinLimit(m[1]);\n    assertBase64WellFormed(m[1]);\n    return;\n  }\n  // `data:` prefix but no `<mime>;base64,<payload>` shape — this is a malformed\n  // media payload (e.g. `data:;base64,xyz` with empty mime, or `data:image/png`\n  // with no payload). Reject with an explicit error rather than silently\n  // passing garbage into the composition / worker.\n  // The narrow exception is `data:<mime>` with NO `;base64,` section, which\n  // some existing callers pass as a composition-only source — that case is\n  // kept as a pass-through in the non-base64 branch below.\n  if (/^data:[^;]*;base64,?$/i.test(source)) {\n    throw new Error(\n      'hologram: malformed media payload — data: URL is missing a base64 payload after \";base64,\"'\n    );\n  }\n  if (/^data:;base64,/i.test(source)) {\n    throw new Error(\n      'hologram: malformed media payload — data: URL has empty MIME type before \";base64,\"'\n    );\n  }\n}\n\ntype HoloProperty = { key: string; value: unknown };\ntype HoloTrait = { name: string; config?: Record<string, unknown> };\ntype HoloObjectDecl = { traits?: HoloTrait[]; properties: HoloProperty[] };\ntype HoloComposition = { name?: string; objects: HoloObjectDecl[] };\n\nexport const hologramToolDefinitions: Tool[] = [\n  {\n    name: 'holo_hologram_from_media',\n    description:\n      'Generate a HoloScript hologram composition from a single image, GIF, or video source. Returns .holo code and trait summary.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        mediaType: {\n          type: 'string',\n          enum: ['image', 'gif', 'video'],\n          description: 'Input media kind.',\n        },\n        source: {\n          type: 'string',\n          description:\n            'Media path, file URL, or remote URL (optional if sourceUrl or sourceBase64 is set).',\n        },\n        sourceUrl: {\n          type: 'string',\n          description: 'Remote URL for media (optional alternative to source).',\n        },\n        sourceBase64: {\n          type: 'string',\n          description: 'Base64-encoded media bytes (optional alternative to source).',\n        },\n        name: {\n          type: 'string',\n          description: 'Optional object name override.',\n        },\n        depthScale: {\n          type: 'number',\n          description: 'Displacement depth scale override.',\n        },\n        segments: {\n          type: 'number',\n          description: 'Displacement subdivision segments override.',\n        },\n        privacy: capturePrivacyInputSchema,\n      },\n      required: ['mediaType'],\n    },\n  },\n  {\n    name: 'holo_hologram_compile_quilt',\n    description:\n      'Compile a hologram composition to Looking Glass quilt metadata and renderer code. When HOLOGRAM_WORKER_URL is set, also runs worker render for quilt and returns share URLs.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        mediaType: {\n          type: 'string',\n          enum: ['image', 'gif', 'video'],\n        },\n        source: {\n          type: 'string',\n          description: 'Path or URL (optional if sourceUrl or sourceBase64).',\n        },\n        sourceUrl: { type: 'string' },\n        sourceBase64: { type: 'string' },\n        name: { type: 'string' },\n        skipStudioUpload: {\n          type: 'boolean',\n          description: 'If true, worker skips Studio upload (local/testing).',\n        },\n        quiltConfig: {\n          type: 'object',\n          description:\n            'Optional QuiltConfig overrides (views, columns, rows, resolution, baseline, device, focusDistance).',\n        },\n        privacy: capturePrivacyInputSchema,\n      },\n      required: ['mediaType'],\n    },\n  },\n  {\n    name: 'holo_hologram_compile_mvhevc',\n    description:\n      'Compile a hologram composition to MV-HEVC (Vision Pro) stereo metadata, Swift scaffold, and mux command. When HOLOGRAM_WORKER_URL is set, also runs worker render for MV-HEVC and returns share URLs.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        mediaType: {\n          type: 'string',\n          enum: ['image', 'gif', 'video'],\n        },\n        source: {\n          type: 'string',\n          description: 'Path or URL (optional if sourceUrl or sourceBase64).',\n        },\n        sourceUrl: { type: 'string' },\n        sourceBase64: { type: 'string' },\n        name: { type: 'string' },\n        skipStudioUpload: {\n          type: 'boolean',\n          description: 'If true, worker skips Studio upload (local/testing).',\n        },\n        mvhevcConfig: {\n          type: 'object',\n          description:\n            'Optional MVHEVCConfig overrides (ipd, resolution, fps, convergenceDistance, fovDegrees, quality, container, disparityScale).',\n        },\n        privacy: capturePrivacyInputSchema,\n      },\n      required: ['mediaType'],\n    },\n  },\n  {\n    name: 'holo_hologram_render',\n    description:\n      'Render a content-addressed hologram bundle with preview/quilt/stereo artifacts. When HOLOGRAM_WORKER_URL is set and includeBase64 is false, calls the hologram worker for hash and share URLs. Set includeBase64 true to render locally for byte payloads.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        mediaType: {\n          type: 'string',\n          enum: ['image', 'gif', 'video'],\n        },\n        source: {\n          type: 'string',\n          description: 'Path or URL (optional if sourceUrl or sourceBase64).',\n        },\n        sourceUrl: { type: 'string' },\n        sourceBase64: { type: 'string' },\n        name: { type: 'string' },\n        targets: {\n          type: 'array',\n          items: { type: 'string', enum: ['quilt', 'mvhevc', 'parallax'] },\n          description: 'Worker render targets (ignored for local-only render).',\n        },\n        skipStudioUpload: {\n          type: 'boolean',\n          description: 'If true, worker skips Studio upload (local/testing).',\n        },\n        quiltConfig: {\n          type: 'object',\n          description:\n            'Optional QuiltConfig overrides (views, columns, rows, resolution, baseline, device, focusDistance).',\n        },\n        mvhevcConfig: {\n          type: 'object',\n          description:\n            'Optional MVHEVCConfig overrides (ipd, resolution, fps, convergenceDistance, fovDegrees, quality, container, disparityScale).',\n        },\n        includeBase64: {\n          type: 'boolean',\n          description:\n            'Include base64 payloads for PNG artifacts. Forces local Playwright render when true.',\n        },\n        durationSeconds: {\n          type: 'number',\n          description: 'Stereo preview video duration for local render. Defaults to 2 seconds.',\n        },\n        privacy: capturePrivacyInputSchema,\n      },\n      required: ['mediaType'],\n    },\n  },\n  {\n    name: 'holo_hologram_publish_feed',\n    description:\n      'Publish a hologram (hash + shareUrl) to the team activity feed on HoloMesh. Uses HOLOMESH_API_KEY; poster identity is the authenticated agent. Rate-limited like holo_hologram_send.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        hash: { type: 'string', description: 'Content hash from worker or local bundle.' },\n        shareUrl: {\n          type: 'string',\n          description: 'Public https share URL for the hologram viewer.',\n        },\n        teamId: {\n          type: 'string',\n          description: 'HoloMesh team id. Defaults to HOLOMESH_TEAM_ID when omitted.',\n        },\n      },\n      required: ['hash', 'shareUrl'],\n    },\n  },\n  {\n    name: 'holo_hologram_send',\n    description:\n      'Post a hologram share link to a HoloMesh team room for a specific teammate. Validates recipient membership via HoloMesh API (HOLOMESH_API_KEY). Rate-limited per API key.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        hash: { type: 'string', description: 'Content hash from worker or local bundle.' },\n        shareUrl: { type: 'string', description: 'Public share URL for the hologram asset.' },\n        recipientAgentId: {\n          type: 'string',\n          description: 'Teammate agent id (must be on the team).',\n        },\n        teamId: {\n          type: 'string',\n          description: 'HoloMesh team id. Defaults to HOLOMESH_TEAM_ID when omitted.',\n        },\n        note: {\n          type: 'string',\n          description: 'Optional short note included in the message payload.',\n        },\n      },\n      required: ['hash', 'shareUrl', 'recipientAgentId'],\n    },\n  },\n  {\n    name: 'holo_hologram_upload_bundle',\n    description:\n      'Upload a HoloGram bundle (depth + normal binaries) to the Studio store. Accepts base64-encoded depth.bin and normal.bin plus a JSON meta object. Optional quilt.png, mvhevc.mp4, and parallax.webm. Returns the content hash and canonical viewer URL.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        meta: {\n          type: 'string',\n          description:\n            'JSON-stringified HologramMeta (schemaVersion, width, height, frames, modelId, backend, inferenceMs, createdAt, sourceKind).',\n        },\n        depthBinBase64: {\n          type: 'string',\n          description: 'Base64-encoded depth map binary (Float32Array bytes).',\n        },\n        normalBinBase64: {\n          type: 'string',\n          description: 'Base64-encoded normal map binary (Float32Array bytes, 3 channels).',\n        },\n        quiltPngBase64: {\n          type: 'string',\n          description: 'Optional base64-encoded quilt PNG.',\n        },\n        mvhevcMp4Base64: {\n          type: 'string',\n          description: 'Optional base64-encoded MV-HEVC MP4.',\n        },\n        parallaxWebmBase64: {\n          type: 'string',\n          description: 'Optional base64-encoded parallax WebM.',\n        },\n      },\n      required: ['meta', 'depthBinBase64', 'normalBinBase64'],\n    },\n  },\n  {\n    name: 'holo_hologram_get_asset',\n    description:\n      'Retrieve a HoloGram bundle asset by content hash. Returns base64-encoded bytes plus MIME type. Assets: depth.bin, normal.bin, quilt.png, mvhevc.mp4, parallax.webm.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        hash: {\n          type: 'string',\n          description: 'Content-addressed bundle hash (64-char hex).',\n        },\n        asset: {\n          type: 'string',\n          enum: ['depth.bin', 'normal.bin', 'quilt.png', 'mvhevc.mp4', 'parallax.webm'],\n          description: 'Asset name to retrieve.',\n        },\n      },\n      required: ['hash', 'asset'],\n    },\n  },\n  {\n    name: 'holo_hologram_inject_world',\n    description:\n      'Inject a rendered hologram (by content hash) into a HoloLand world as a placed object on the ' +\n      'semantic-state representation lane (W.701). Composes the hologram .holo code into a world ' +\n      'state delta and pushes it via push_state_delta so agents and pixel-stream viewers both see it. ' +\n      'Requires a HoloLand world ID and a content hash from a prior holo_hologram_render or ' +\n      'holo_hologram_upload_bundle call. Returns the entity ID assigned to the hologram object ' +\n      'in the world and the share URL.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        worldId: {\n          type: 'string',\n          description: 'HoloLand world ID to inject the hologram into.',\n        },\n        hash: {\n          type: 'string',\n          description: 'Content-addressed bundle hash (64-char hex) from a prior render/upload.',\n        },\n        shareUrl: {\n          type: 'string',\n          description: 'Public share URL for the hologram viewer (from worker or upload result).',\n        },\n        position: {\n          type: 'array',\n          items: { type: 'number' },\n          minItems: 3,\n          maxItems: 3,\n          description:\n            'World-space [x, y, z] spawn position. Defaults to [0, 1.5, -3] (eye-level, 3 m ahead).',\n        },\n        scale: {\n          type: 'array',\n          items: { type: 'number' },\n          minItems: 3,\n          maxItems: 3,\n          description:\n            'World-space [x, y, z] scale. Defaults to [2, 1.5, 1] (portrait-format hologram).',\n        },\n        label: {\n          type: 'string',\n          description: 'Optional display label for the world object. Defaults to the hash prefix.',\n        },\n        representationLane: {\n          type: 'string',\n          enum: ['semantic-state', 'pixel-stream'],\n          description:\n            'Which representation lane to target. Defaults to \"semantic-state\" (agent-native, W.701).',\n        },\n      },\n      required: ['worldId', 'hash'],\n    },\n  },\n];\n\nconst HOLOGRAM_NAMES = new Set(hologramToolDefinitions.map((t) => t.name));\n\nexport function isHologramToolName(name: string): boolean {\n  return HOLOGRAM_NAMES.has(name);\n}\n\nfunction assertMediaType(value: unknown): HologramMediaType {\n  const s = typeof value === 'string' ? value.trim().toLowerCase() : '';\n  if (s === 'image' || s === 'gif' || s === 'video') return s;\n  throw new Error('hologram: mediaType must be one of image|gif|video');\n}\n\nfunction resolveCompositionSource(\n  args: Record<string, unknown>,\n  mediaType: HologramMediaType\n): string {\n  const s = typeof args.source === 'string' ? args.source.trim() : '';\n  const u = typeof args.sourceUrl === 'string' ? args.sourceUrl.trim() : '';\n  const b64 = typeof args.sourceBase64 === 'string' ? args.sourceBase64.trim() : '';\n  if (s) {\n    assertInlineSourceWithinLimit(s);\n    return s;\n  }\n  if (u) return u;\n  if (b64) {\n    assertBase64WithinLimit(b64);\n    assertBase64WellFormed(b64);\n    const mime =\n      mediaType === 'image' ? 'image/png' : mediaType === 'gif' ? 'image/gif' : 'video/mp4';\n    return `data:${mime};base64,${b64}`;\n  }\n  throw new Error('hologram: one of source, sourceUrl, or sourceBase64 is required');\n}\n\nasync function buildWorkerMediaPayload(\n  args: Record<string, unknown>,\n  mediaType: HologramMediaType\n): Promise<{ sourceUrl?: string; sourceBase64?: string }> {\n  const b64Field = typeof args.sourceBase64 === 'string' ? args.sourceBase64.trim() : '';\n  if (b64Field) {\n    assertBase64WithinLimit(b64Field);\n    assertBase64WellFormed(b64Field);\n    return { sourceBase64: b64Field };\n  }\n\n  const u = typeof args.sourceUrl === 'string' ? args.sourceUrl.trim() : '';\n  if (u) return { sourceUrl: u };\n\n  const s = typeof args.source === 'string' ? args.source.trim() : '';\n  if (!s) throw new Error('hologram: source media required for worker render');\n\n  if (/^https?:\\/\\//i.test(s)) return { sourceUrl: s };\n\n  if (/^data:/i.test(s)) {\n    const m = /^data:[^;]+;base64,(.+)$/i.exec(s);\n    if (m) {\n      assertBase64WithinLimit(m[1]);\n      assertBase64WellFormed(m[1]);\n      return { sourceBase64: m[1] };\n    }\n    // Malformed data: URL (no `<mime>;base64,<payload>` section). Surface an\n    // explicit error instead of falling through to the filesystem branch\n    // where `readFile('data:image/png')` would produce a misleading ENOENT.\n    if (/^data:[^;]*;base64,?$/i.test(s) || /^data:;base64,/i.test(s) || /^data:[^,;]*$/i.test(s)) {\n      throw new Error(\n        'hologram: malformed media payload — worker received a data: URL without a valid \";base64,<payload>\" section'\n      );\n    }\n  }\n\n  const { readFile } = await import('node:fs/promises');\n  const { isAbsolute, resolve } = await import('node:path');\n  const fullPath = isAbsolute(s) ? s : resolve(process.cwd(), s);\n  const buf = await readFile(fullPath);\n  const encoded = buf.toString('base64');\n  assertBase64WithinLimit(encoded);\n  return { sourceBase64: encoded };\n}\n\nfunction parseRenderTargets(args: Record<string, unknown>): HologramTarget[] {\n  const raw = args.targets;\n  const fallback: HologramTarget[] = ['quilt', 'mvhevc', 'parallax'];\n  if (!Array.isArray(raw) || raw.length === 0) return fallback;\n  const out: HologramTarget[] = [];\n  for (const t of raw) {\n    const s = String(t).toLowerCase();\n    if (s === 'quilt' || s === 'mvhevc' || s === 'parallax') out.push(s);\n  }\n  return out.length ? out : fallback;\n}\n\nfunction getMediaTraits(mediaType: HologramMediaType, source: string): HoloTrait[] {\n  if (mediaType === 'image') {\n    return [\n      { name: 'image', config: { src: source } },\n      { name: 'depth_estimation', config: { model: 'depth-anything-v2-small', backend: 'webgpu' } },\n      { name: 'displacement', config: { scale: 0.3, segments: 128 } },\n      { name: 'depth_to_normal' },\n    ];\n  }\n\n  if (mediaType === 'gif') {\n    return [\n      { name: 'animated_texture', config: { src: source, fps: 24, max_frames: 500 } },\n      { name: 'segment', config: { model: 'rembg', remove_background: true } },\n      {\n        name: 'depth_estimation',\n        config: { model: 'depth-anything-v2-small', backend: 'webgpu', temporal_smoothing: 0.8 },\n      },\n      { name: 'holographic_sprite', config: { depth_scale: 0.5, render_mode: 'displacement' } },\n      { name: 'billboard', config: { mode: 'camera-facing' } },\n    ];\n  }\n\n  return [\n    { name: 'video', config: { src: source, autoplay: true, loop: true, muted: true } },\n    {\n      name: 'depth_estimation',\n      config: { model: 'depth-anything-v2-small', backend: 'webgpu', temporal_smoothing: 0.8 },\n    },\n    { name: 'displacement', config: { scale: 0.25, segments: 64 } },\n  ];\n}\n\nexport function buildComposition(\n  mediaType: HologramMediaType,\n  source: string,\n  name?: string\n): HoloComposition {\n  const objectName = (name && name.trim()) || 'HologramMedia';\n  const traits = getMediaTraits(mediaType, source);\n\n  return {\n    name: `Hologram - ${objectName}`,\n    objects: [\n      {\n        traits,\n        properties: [\n          { key: 'geometry', value: 'plane' },\n          { key: 'position', value: [0, 1.5, -3] },\n          { key: 'scale', value: mediaType === 'video' ? [3, 1.7, 1] : [2, 1.5, 1] },\n          { key: 'color', value: '#ffffff' },\n        ],\n      },\n    ],\n  };\n}\n\nexport function toHoloCode(mediaType: HologramMediaType, source: string, name?: string): string {\n  const objectName = (name && name.trim()) || 'HologramMedia';\n  const header = `composition \"Hologram - ${objectName}\" {`;\n  const base = [\n    '  environment {',\n    '    skybox: \"night\"',\n    '    ambient_light: 0.2',\n    '  }',\n    '',\n    `  object \"${objectName}\" {`,\n  ];\n\n  const body =\n    mediaType === 'image'\n      ? [\n          `    @image src:\"${source}\"`,\n          '    @depth_estimation { model: \"depth-anything-v2-small\", backend: \"webgpu\" }',\n          '    @displacement { scale: 0.3, segments: 128 }',\n          '    @depth_to_normal',\n          '    geometry: \"plane\"',\n          '    position: [0, 1.5, -3]',\n          '    scale: [2, 1.5, 1]',\n        ]\n      : mediaType === 'gif'\n        ? [\n            `    @animated_texture { src: \"${source}\", fps: 24, max_frames: 500 }`,\n            '    @segment { model: \"rembg\", remove_background: true }',\n            '    @depth_estimation { model: \"depth-anything-v2-small\", backend: \"webgpu\", temporal_smoothing: 0.8 }',\n            '    @holographic_sprite { depth_scale: 0.5, render_mode: \"displacement\" }',\n            '    @billboard { mode: \"camera-facing\" }',\n            '    position: [0, 1.5, -2]',\n            '    scale: [2, 2, 1]',\n          ]\n        : [\n            `    @video { src: \"${source}\", autoplay: true, loop: true, muted: true }`,\n            '    @depth_estimation { model: \"depth-anything-v2-small\", backend: \"webgpu\", temporal_smoothing: 0.8 }',\n            '    @displacement { scale: 0.25, segments: 64 }',\n            '    geometry: \"plane\"',\n            '    position: [0, 1.5, -3]',\n            '    scale: [3, 1.7, 1]',\n          ];\n\n  return [header, ...base, ...body, '  }', '}'].join('\\n');\n}\n\nexport async function handleHologramTool(\n  name: string,\n  args: Record<string, unknown>\n): Promise<unknown> {\n  if (name === 'holo_hologram_publish_feed') {\n    const hash = typeof args.hash === 'string' ? args.hash.trim() : '';\n    const shareUrl = typeof args.shareUrl === 'string' ? args.shareUrl.trim() : '';\n    const teamIdRaw = typeof args.teamId === 'string' ? args.teamId.trim() : '';\n    const teamId = teamIdRaw || process.env.HOLOMESH_TEAM_ID?.trim() || '';\n    // Phase-2 wrapped read for hologram publish_feed.\n    const apiKey = readHolomeshApiKey();\n    if (!hash || !shareUrl) {\n      throw new Error('hologram publish_feed: hash and shareUrl are required');\n    }\n    if (!teamId) {\n      throw new Error('hologram publish_feed: teamId is required (or set HOLOMESH_TEAM_ID)');\n    }\n    const out = await publishHologramTeamFeed({ teamId, apiKey, hash, shareUrl });\n    return { ok: true, teamId, holomesh: out };\n  }\n\n  if (name === 'holo_hologram_send') {\n    const hash = typeof args.hash === 'string' ? args.hash.trim() : '';\n    const shareUrl = typeof args.shareUrl === 'string' ? args.shareUrl.trim() : '';\n    const recipientAgentId =\n      typeof args.recipientAgentId === 'string' ? args.recipientAgentId.trim() : '';\n    const teamIdRaw = typeof args.teamId === 'string' ? args.teamId.trim() : '';\n    const teamId = teamIdRaw || process.env.HOLOMESH_TEAM_ID?.trim() || '';\n    const note = typeof args.note === 'string' ? args.note : undefined;\n    if (!hash || !shareUrl || !recipientAgentId) {\n      throw new Error('hologram send: hash, shareUrl, and recipientAgentId are required');\n    }\n    if (!teamId) {\n      throw new Error('hologram send: teamId is required (or set HOLOMESH_TEAM_ID)');\n    }\n    // Phase-2 wrapped read for hologram send.\n    const apiKey = readHolomeshApiKey();\n    const holomesh = await sendHologramTeamMessage({\n      teamId,\n      apiKey,\n      hash,\n      shareUrl,\n      recipientAgentId,\n      note,\n    });\n    return { ok: true, teamId, recipientAgentId, holomesh };\n  }\n\n  if (name === 'holo_hologram_upload_bundle') {\n    const meta = typeof args.meta === 'string' ? args.meta : '';\n    const depthBinBase64 = typeof args.depthBinBase64 === 'string' ? args.depthBinBase64 : '';\n    const normalBinBase64 = typeof args.normalBinBase64 === 'string' ? args.normalBinBase64 : '';\n    const quiltPngBase64 =\n      typeof args.quiltPngBase64 === 'string' ? args.quiltPngBase64 : undefined;\n    const mvhevcMp4Base64 =\n      typeof args.mvhevcMp4Base64 === 'string' ? args.mvhevcMp4Base64 : undefined;\n    const parallaxWebmBase64 =\n      typeof args.parallaxWebmBase64 === 'string' ? args.parallaxWebmBase64 : undefined;\n    if (!meta) throw new Error('hologram upload_bundle: meta is required');\n    if (!depthBinBase64) throw new Error('hologram upload_bundle: depthBinBase64 is required');\n    if (!normalBinBase64) throw new Error('hologram upload_bundle: normalBinBase64 is required');\n    assertBundleBase64Field('depthBinBase64', depthBinBase64);\n    assertBundleBase64Field('normalBinBase64', normalBinBase64);\n    assertBundleBase64Field('quiltPngBase64', quiltPngBase64);\n    assertBundleBase64Field('mvhevcMp4Base64', mvhevcMp4Base64);\n    assertBundleBase64Field('parallaxWebmBase64', parallaxWebmBase64);\n    const result = await uploadHologramBundle({\n      meta,\n      depthBinBase64,\n      normalBinBase64,\n      quiltPngBase64,\n      mvhevcMp4Base64,\n      parallaxWebmBase64,\n    });\n    return { ok: true, ...result };\n  }\n\n  if (name === 'holo_hologram_get_asset') {\n    const hash = typeof args.hash === 'string' ? args.hash.trim() : '';\n    const asset = typeof args.asset === 'string' ? args.asset.trim() : '';\n    if (!hash) throw new Error('hologram get_asset: hash is required');\n    if (!asset) throw new Error('hologram get_asset: asset is required');\n    if (!HOLOGRAM_ASSETS.has(asset)) {\n      throw new Error(\n        'hologram get_asset: asset must be one of depth.bin|normal.bin|quilt.png|mvhevc.mp4|parallax.webm'\n      );\n    }\n    const result = await getHologramAsset(hash, asset);\n    return { ok: true, ...result };\n  }\n\n  if (name === 'holo_hologram_inject_world') {\n    return handleHologramInjectWorld(args);\n  }\n\n  const mediaType = assertMediaType(args.mediaType);\n  const compositionSource = resolveCompositionSource(args, mediaType);\n  assertPublicCaptureConsent(args, {\n    toolName: name,\n    surface: 'HoloGram',\n    mediaKind: mediaType,\n  });\n  const objectName = typeof args.name === 'string' ? args.name : undefined;\n\n  const composition = buildComposition(mediaType, compositionSource, objectName);\n  const holoCode = toHoloCode(mediaType, compositionSource, objectName);\n\n  switch (name) {\n    case 'holo_hologram_from_media': {\n      return {\n        ok: true,\n        mediaType,\n        source: compositionSource,\n        holoCode,\n        traits: composition.objects[0]?.traits?.map((t) => t.name) ?? [],\n      };\n    }\n\n    case 'holo_hologram_compile_quilt': {\n      const compiler = new QuiltCompiler();\n      const quiltConfig = (args.quiltConfig ?? undefined) as Partial<QuiltConfig> | undefined;\n      const result = compiler.compileQuilt(composition, quiltConfig);\n      const out: Record<string, unknown> = {\n        ok: true,\n        mediaType,\n        source: compositionSource,\n        quilt: result,\n      };\n      if (isHologramWorkerConfigured()) {\n        try {\n          const mediaPayload = await buildWorkerMediaPayload(args, mediaType);\n          const wr = await callHologramWorkerRender({\n            ...mediaPayload,\n            mediaType,\n            targets: ['quilt'],\n            skipUpload: args.skipStudioUpload === true,\n          });\n          out.hash = wr.hash;\n          out.shareUrl = wr.shareUrl;\n          out.quiltUrl = wr.quiltUrl;\n          out.mvhevcUrl = wr.mvhevcUrl;\n        } catch (e) {\n          out.workerError = e instanceof Error ? e.message : String(e);\n        }\n      }\n      return out;\n    }\n\n    case 'holo_hologram_compile_mvhevc': {\n      const compiler = new MVHEVCCompiler();\n      const mvhevcConfig = (args.mvhevcConfig ?? undefined) as Partial<MVHEVCConfig> | undefined;\n      const result = compiler.compileMVHEVC(composition, mvhevcConfig);\n      const out: Record<string, unknown> = {\n        ok: true,\n        mediaType,\n        source: compositionSource,\n        mvhevc: result,\n      };\n      if (isHologramWorkerConfigured()) {\n        try {\n          const mediaPayload = await buildWorkerMediaPayload(args, mediaType);\n          const wr = await callHologramWorkerRender({\n            ...mediaPayload,\n            mediaType,\n            targets: ['mvhevc'],\n            skipUpload: args.skipStudioUpload === true,\n          });\n          out.hash = wr.hash;\n          out.shareUrl = wr.shareUrl;\n          out.quiltUrl = wr.quiltUrl;\n          out.mvhevcUrl = wr.mvhevcUrl;\n        } catch (e) {\n          out.workerError = e instanceof Error ? e.message : String(e);\n        }\n      }\n      return out;\n    }\n\n    case 'holo_hologram_render': {\n      const quiltCompiler = new QuiltCompiler();\n      const mvhevcCompiler = new MVHEVCCompiler();\n      const quiltConfig = (args.quiltConfig ?? undefined) as Partial<QuiltConfig> | undefined;\n      const mvhevcConfig = (args.mvhevcConfig ?? undefined) as Partial<MVHEVCConfig> | undefined;\n\n      const quilt = quiltCompiler.compileQuilt(composition, quiltConfig);\n      const mvhevc = mvhevcCompiler.compileMVHEVC(composition, mvhevcConfig);\n\n      const useWorker = isHologramWorkerConfigured() && args.includeBase64 !== true;\n      if (useWorker) {\n        const mediaPayload = await buildWorkerMediaPayload(args, mediaType);\n        const workerResult = await callHologramWorkerRender({\n          ...mediaPayload,\n          mediaType,\n          targets: parseRenderTargets(args),\n          skipUpload: args.skipStudioUpload === true,\n        });\n        return {\n          ok: true,\n          mediaType,\n          source: compositionSource,\n          holoCode,\n          quilt,\n          mvhevc,\n          worker: workerResult,\n        };\n      }\n\n      const bundle = await renderHologramBundle({\n        mediaType,\n        source: compositionSource,\n        name: objectName ?? 'HologramMedia',\n        holoCode,\n        quilt,\n        mvhevc,\n        includeBase64: args.includeBase64 === true,\n        durationSeconds: typeof args.durationSeconds === 'number' ? args.durationSeconds : 2,\n      });\n\n      return {\n        ok: true,\n        mediaType,\n        source: compositionSource,\n        holoCode,\n        bundle,\n      };\n    }\n\n    default:\n      return undefined;\n  }\n}\n\n// ── HoloLand semantic-state lane injection ───────────────────────────────────\n\n/**\n * Representation lane for the inject_world tool.\n * W.701: 'semantic-state' is the agent-native lane; 'pixel-stream' is the\n * WebXR/headset lane. Both read the same world state — the lane determines\n * how the state delta is serialised to the connecting party.\n */\ntype HologramRepresentationLane = 'semantic-state' | 'pixel-stream';\n\n/**\n * Inject a previously-rendered hologram bundle into a HoloLand world as a\n * placed object on the semantic-state representation lane.\n *\n * Design (W.701 dual-representation model):\n *   1. Build a minimal `.holo` composition that references the hologram by\n *      its content hash (so the viewer fetches the bundle from Studio store).\n *   2. Construct a `push_state_delta` payload:\n *        - entityId   = \"hologram:<hash-prefix>\" — stable, collision-free ID\n *        - payload    = { type, worldId, hash, shareUrl, position, scale,\n *                         label, representationLane, holoCode, injectedAt }\n *   3. Call `handleNetworkingTool('push_state_delta', ...)` locally rather\n *      than making an HTTP round-trip — same process, no extra auth.\n *\n * Returns { ok, entityId, worldId, hash, shareUrl, representationLane }.\n */\nasync function handleHologramInjectWorld(args: Record<string, unknown>): Promise<unknown> {\n  const worldId = typeof args.worldId === 'string' ? args.worldId.trim() : '';\n  const hash = typeof args.hash === 'string' ? args.hash.trim() : '';\n  const shareUrl = typeof args.shareUrl === 'string' ? args.shareUrl.trim() : '';\n  const label =\n    typeof args.label === 'string' && args.label.trim()\n      ? args.label.trim()\n      : `hologram-${hash.slice(0, 8)}`;\n  const laneRaw = typeof args.representationLane === 'string' ? args.representationLane.trim() : '';\n  const lane: HologramRepresentationLane =\n    laneRaw === 'pixel-stream' ? 'pixel-stream' : 'semantic-state';\n\n  if (!worldId) throw new Error('hologram inject_world: worldId is required');\n  if (!hash) throw new Error('hologram inject_world: hash (content hash) is required');\n\n  // Parse position / scale with safe defaults.\n  const rawPos = Array.isArray(args.position) ? args.position : null;\n  const position: [number, number, number] =\n    rawPos && rawPos.length >= 3\n      ? [Number(rawPos[0]) || 0, Number(rawPos[1]) || 1.5, Number(rawPos[2]) || -3]\n      : [0, 1.5, -3];\n\n  const rawScale = Array.isArray(args.scale) ? args.scale : null;\n  const scale: [number, number, number] =\n    rawScale && rawScale.length >= 3\n      ? [Number(rawScale[0]) || 2, Number(rawScale[1]) || 1.5, Number(rawScale[2]) || 1]\n      : [2, 1.5, 1];\n\n  // Stable entity ID — deterministic from worldId + hash so the same hologram\n  // injected twice into the same world produces an idempotent delta (LWW).\n  const entityId = `hologram:${worldId}:${hash.slice(0, 12)}`;\n\n  // Minimal .holo composition that references the bundle by content hash.\n  // The Studio viewer resolves depth.bin / quilt.png / mvhevc.mp4 via\n  // GET /api/hologram/asset/:hash/:asset.\n  const holoCode = [\n    `composition \"HoloGram ${label}\" {`,\n    '  environment {',\n    '    skybox: \"night\"',\n    '    ambient_light: 0.2',\n    '  }',\n    `  object \"${label}\" {`,\n    `    @hologram_bundle { hash: \"${hash}\"${shareUrl ? `, shareUrl: \"${shareUrl}\"` : ''} }`,\n    `    geometry: \"plane\"`,\n    `    position: [${position.join(', ')}]`,\n    `    scale: [${scale.join(', ')}]`,\n    '  }',\n    '}',\n  ].join('\\n');\n\n  // State delta — the payload that push_state_delta broadcasts to all\n  // subscribers of this world on the semantic-state lane.\n  const stateDelta = {\n    type: 'hologram-object',\n    worldId,\n    hash,\n    shareUrl: shareUrl || null,\n    position,\n    scale,\n    label,\n    representationLane: lane,\n    holoCode,\n    injectedAt: new Date().toISOString(),\n  };\n\n  // Dispatch locally to the networking push_state_delta handler.\n  const { handleNetworkingTool } = await import('./networking-tools');\n  await handleNetworkingTool('push_state_delta', { entityId, payload: stateDelta });\n\n  return {\n    ok: true,\n    entityId,\n    worldId,\n    hash,\n    shareUrl: shareUrl || null,\n    representationLane: lane,\n    position,\n    scale,\n    label,\n  };\n}\n","﻿/**\n * HoloTwin MCP Tools — IoT Sensor → HoloScript → Looking Glass\n *\n * MCP tool surface for real-time holographic digital twin pipeline.\n * Bridges IoT sensor data to HoloScript scenes and compiles to Looking Glass quilt format.\n *\n * Tools:\n * - holo_holotwin_connect: Connect to IoT sensor/broker\n * - holo_holotwin_map_sensor: Map sensor telemetry to scene properties\n * - holo_holotwin_compile_quilt: Compile scene to Looking Glass quilt\n * - holo_holotwin_stream: Start real-time sensor → hologram stream\n * - holo_holotwin_status: Get twin sync status\n */\n\nimport { createHash } from 'node:crypto';\nimport type { Tool } from '@modelcontextprotocol/sdk/types.js';\nimport { parseHolo } from '@holoscript/core';\nimport { BrowserQuiltRenderer, QuiltCompiler, type QuiltConfig } from '@holoscript/engine/hologram';\n\n// =============================================================================\n// TYPES\n// =============================================================================\n\ntype LookingGlassDevice = 'go' | '16inch' | '27inch' | '65inch';\n\ninterface SensorMapping {\n  sensor_key: string;\n  scene_property: string;\n  transform?: 'scale' | 'color' | 'position' | 'emissive' | 'label';\n  min?: number;\n  max?: number;\n  invert?: boolean;\n}\n\ninterface HoloTwinSession {\n  sessionId: string;\n  physicalId: string;\n  protocol: 'mqtt' | 'http' | 'websocket';\n  connectionString: string;\n  device: LookingGlassDevice;\n  mappings: SensorMapping[];\n  holoCode: string;\n  quiltHash?: string;\n  quiltUrl?: string;\n  quiltBytes?: number;\n  quiltPngBase64?: string;\n  stream?: HoloTwinStreamState;\n  lastSyncTime: number;\n  isConnected: boolean;\n}\n\ninterface HoloTwinStreamState {\n  isStreaming: boolean;\n  startedAt: number;\n  recompileIntervalMs: number;\n  autoStop: boolean;\n  ticks: number;\n  lastFrameHash?: string;\n  lastError?: string;\n  timer?: ReturnType<typeof setInterval>;\n  stopTimer?: ReturnType<typeof setTimeout>;\n}\n\ntype QuiltComposition = Parameters<QuiltCompiler['compileQuilt']>[0];\n\ninterface QuiltReceipt {\n  pngBase64: string;\n  sha256: string;\n  bytes: number;\n  renderConfig: QuiltConfig;\n}\n\n// =============================================================================\n// LOOKING GLASS PRESETS\n// =============================================================================\n\nconst LOOKING_GLASS_PRESETS: Record<LookingGlassDevice, QuiltConfig> = {\n  go: {\n    views: 45,\n    columns: 9,\n    rows: 5,\n    resolution: [1440, 1440],\n    baseline: 0.04,\n    device: 'go',\n    focusDistance: 0.15,\n  },\n  '16inch': {\n    views: 48,\n    columns: 8,\n    rows: 6,\n    resolution: [3360, 3360],\n    baseline: 0.06,\n    device: '16inch',\n    focusDistance: 0.2,\n  },\n  '27inch': {\n    views: 60,\n    columns: 10,\n    rows: 6,\n    resolution: [5120, 3840],\n    baseline: 0.065,\n    device: '27inch',\n    focusDistance: 0.25,\n  },\n  '65inch': {\n    views: 128,\n    columns: 16,\n    rows: 8,\n    resolution: [7680, 4320],\n    baseline: 0.08,\n    device: '65inch',\n    focusDistance: 0.5,\n  },\n};\n\n// =============================================================================\n// SESSION STORE\n// =============================================================================\n\nconst sessions = new Map<string, HoloTwinSession>();\n\nfunction generateSessionId(): string {\n  return `holotwin_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;\n}\n\n// =============================================================================\n// TOOL DEFINITIONS\n// =============================================================================\n\nexport const holotwinToolDefinitions: Tool[] = [\n  {\n    name: 'holo_holotwin_connect',\n    description:\n      'Connect to an IoT sensor or broker for HoloTwin holographic digital twin. Supports MQTT, HTTP, and WebSocket protocols.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        physicalId: {\n          type: 'string',\n          description: 'IoT device or sensor ID',\n        },\n        protocol: {\n          type: 'string',\n          enum: ['mqtt', 'http', 'websocket'],\n          description: 'Communication protocol',\n        },\n        connectionString: {\n          type: 'string',\n          description: 'MQTT broker URL (e.g., mqtt://farm.local:1883) or HTTP endpoint',\n        },\n        displayDevice: {\n          type: 'string',\n          enum: ['go', '16inch', '27inch', '65inch'],\n          description: 'Target Looking Glass display device',\n        },\n      },\n      required: ['physicalId', 'protocol', 'connectionString'],\n    },\n  },\n  {\n    name: 'holo_holotwin_map_sensor',\n    description:\n      'Map IoT sensor telemetry keys to HoloScript scene properties. Defines how sensor data transforms the holographic display.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        sessionId: {\n          type: 'string',\n          description: 'Session ID from holo_holotwin_connect',\n        },\n        mappings: {\n          type: 'array',\n          items: {\n            type: 'object',\n            properties: {\n              sensor_key: { type: 'string', description: 'IoT telemetry key' },\n              scene_property: { type: 'string', description: 'Scene node property to update' },\n              transform: {\n                type: 'string',\n                enum: ['scale', 'color', 'position', 'emissive', 'label'],\n                description: 'How to transform the value',\n              },\n              min: { type: 'number', description: 'Min value for normalization' },\n              max: { type: 'number', description: 'Max value for normalization' },\n              invert: { type: 'boolean', description: 'Invert the normalized value' },\n            },\n            required: ['sensor_key', 'scene_property'],\n          },\n        },\n      },\n      required: ['sessionId', 'mappings'],\n    },\n  },\n  {\n    name: 'holo_holotwin_compile_quilt',\n    description:\n      'Compile a HoloTwin scene to Looking Glass quilt format. Returns quilt metadata, renderer code, and share URL.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        sessionId: {\n          type: 'string',\n          description: 'Session ID from holo_holotwin_connect',\n        },\n        holoCode: {\n          type: 'string',\n          description: 'HoloScript composition code',\n        },\n        deviceOverride: {\n          type: 'string',\n          enum: ['go', '16inch', '27inch', '65inch'],\n          description: 'Override display device from session',\n        },\n        quiltConfig: {\n          type: 'object',\n          description: 'Custom quilt config overrides',\n        },\n      },\n      required: ['sessionId', 'holoCode'],\n    },\n  },\n  {\n    name: 'holo_holotwin_stream',\n    description:\n      'Start real-time streaming from IoT sensor to holographic display. Continuously updates scene and recompiles quilt.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        sessionId: {\n          type: 'string',\n          description: 'Session ID from holo_holotwin_connect',\n        },\n        recompileIntervalMs: {\n          type: 'number',\n          description: 'Minimum time between quilt recompiles (default: 1000ms)',\n        },\n        autoStop: {\n          type: 'boolean',\n          description: 'Auto-stop after N seconds (0 = indefinite)',\n        },\n      },\n      required: ['sessionId'],\n    },\n  },\n  {\n    name: 'holo_holotwin_status',\n    description: 'Get HoloTwin session status: sync state, sensor data, quilt hash, errors.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        sessionId: {\n          type: 'string',\n          description: 'Session ID from holo_holotwin_connect',\n        },\n      },\n      required: ['sessionId'],\n    },\n  },\n  {\n    name: 'holo_holotwin_disconnect',\n    description: 'Disconnect from IoT sensor and stop HoloTwin session.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        sessionId: {\n          type: 'string',\n          description: 'Session ID from holo_holotwin_connect',\n        },\n      },\n      required: ['sessionId'],\n    },\n  },\n  {\n    name: 'holo_holotwin_example',\n    description:\n      'Generate a complete HoloTwin example: smart farm sensor dashboard with temperature/humidity → 3D visualization → Looking Glass quilt.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        device: {\n          type: 'string',\n          enum: ['go', '16inch', '27inch', '65inch'],\n          description: 'Target Looking Glass device',\n        },\n        includeSimulation: {\n          type: 'boolean',\n          description: 'Include simulated sensor data for testing',\n        },\n      },\n    },\n  },\n];\n\nconst HOLOTWIN_NAMES = new Set(holotwinToolDefinitions.map((t) => t.name));\n\nexport function isHoloTwinToolName(name: string): boolean {\n  return HOLOTWIN_NAMES.has(name);\n}\n\n// =============================================================================\n// TOOL HANDLERS\n// =============================================================================\n\nexport async function handleHoloTwinTool(\n  name: string,\n  args: Record<string, unknown>\n): Promise<unknown> {\n  switch (name) {\n    case 'holo_holotwin_connect': {\n      const physicalId = typeof args.physicalId === 'string' ? args.physicalId.trim() : '';\n      const protocol = (args.protocol as 'mqtt' | 'http' | 'websocket') || 'mqtt';\n      const connectionString =\n        typeof args.connectionString === 'string' ? args.connectionString.trim() : '';\n      const displayDevice = (args.displayDevice as LookingGlassDevice) || '16inch';\n\n      if (!physicalId || !connectionString) {\n        throw new Error('holotwin: physicalId and connectionString are required');\n      }\n\n      const sessionId = generateSessionId();\n      const session: HoloTwinSession = {\n        sessionId,\n        physicalId,\n        protocol,\n        connectionString,\n        device: displayDevice,\n        mappings: [],\n        holoCode: '',\n        lastSyncTime: 0,\n        isConnected: true,\n      };\n      sessions.set(sessionId, session);\n\n      return {\n        ok: true,\n        sessionId,\n        physicalId,\n        protocol,\n        device: displayDevice,\n        message: `Connected to ${physicalId} via ${protocol}. Ready for sensor mappings.`,\n      };\n    }\n\n    case 'holo_holotwin_map_sensor': {\n      const sessionId = typeof args.sessionId === 'string' ? args.sessionId.trim() : '';\n      const mappings = (args.mappings as SensorMapping[]) || [];\n\n      const session = sessions.get(sessionId);\n      if (!session) {\n        throw new Error(`holotwin: session ${sessionId} not found`);\n      }\n\n      session.mappings = mappings;\n\n      return {\n        ok: true,\n        sessionId,\n        mappingsCount: mappings.length,\n        message: `Mapped ${mappings.length} sensor(s) to scene properties`,\n      };\n    }\n\n    case 'holo_holotwin_compile_quilt': {\n      const sessionId = typeof args.sessionId === 'string' ? args.sessionId.trim() : '';\n      const holoCode = typeof args.holoCode === 'string' ? args.holoCode : '';\n      const deviceOverride = args.deviceOverride as LookingGlassDevice | undefined;\n      const quiltConfigOverride = args.quiltConfig as Partial<QuiltConfig> | undefined;\n\n      const session = sessions.get(sessionId);\n      if (!session) {\n        throw new Error(`holotwin: session ${sessionId} not found`);\n      }\n\n      session.holoCode = holoCode;\n      const device = deviceOverride || session.device;\n      const baseConfig = LOOKING_GLASS_PRESETS[device];\n\n      // Merge config overrides\n      const quiltConfig: QuiltConfig = {\n        ...baseConfig,\n        ...(quiltConfigOverride || {}),\n      };\n\n      const compiler = new QuiltCompiler();\n      const composition = parseHoloTwinComposition(holoCode);\n      const result = compiler.compileQuilt(composition, quiltConfig);\n      const receipt = await renderQuiltReceipt(composition, quiltConfig, session);\n\n      const quiltHash = `sha256:${receipt.sha256}`;\n      const quiltUrl = `data:image/png;base64,${receipt.pngBase64}`;\n\n      session.quiltHash = quiltHash;\n      session.quiltUrl = quiltUrl;\n      session.quiltBytes = receipt.bytes;\n      session.quiltPngBase64 = receipt.pngBase64;\n      session.lastSyncTime = Date.now();\n\n      return {\n        ok: true,\n        sessionId,\n        device,\n        quilt: {\n          ...result,\n          receipt,\n        },\n        hash: quiltHash,\n        url: quiltUrl,\n        stub: false,\n      };\n    }\n\n    case 'holo_holotwin_stream': {\n      const sessionId = typeof args.sessionId === 'string' ? args.sessionId.trim() : '';\n      const recompileIntervalMs =\n        typeof args.recompileIntervalMs === 'number' && Number.isFinite(args.recompileIntervalMs)\n          ? Math.max(100, Math.floor(args.recompileIntervalMs))\n          : 1000;\n      const autoStop = typeof args.autoStop === 'boolean' ? args.autoStop : false;\n\n      const session = sessions.get(sessionId);\n      if (!session) {\n        throw new Error(`holotwin: session ${sessionId} not found`);\n      }\n\n      stopHoloTwinStream(session);\n      const stream: HoloTwinStreamState = {\n        isStreaming: true,\n        startedAt: Date.now(),\n        recompileIntervalMs,\n        autoStop,\n        ticks: 0,\n      };\n      session.stream = stream;\n\n      await runStreamTick(session);\n      stream.timer = setInterval(() => {\n        void runStreamTick(session);\n      }, recompileIntervalMs);\n      unrefTimer(stream.timer);\n\n      if (autoStop) {\n        stream.stopTimer = setTimeout(() => {\n          stopHoloTwinStream(session);\n        }, recompileIntervalMs);\n        unrefTimer(stream.stopTimer);\n      }\n\n      return {\n        ok: true,\n        sessionId,\n        streaming: true,\n        recompileIntervalMs,\n        autoStop,\n        ticks: stream.ticks,\n        lastFrameHash: stream.lastFrameHash,\n        message: `Streaming started. Recompiling every ${recompileIntervalMs}ms.`,\n      };\n    }\n\n    case 'holo_holotwin_status': {\n      const sessionId = typeof args.sessionId === 'string' ? args.sessionId.trim() : '';\n\n      const session = sessions.get(sessionId);\n      if (!session) {\n        throw new Error(`holotwin: session ${sessionId} not found`);\n      }\n\n      return {\n        ok: true,\n        sessionId,\n        physicalId: session.physicalId,\n        protocol: session.protocol,\n        device: session.device,\n        isConnected: session.isConnected,\n        mappingsCount: session.mappings.length,\n        quiltHash: session.quiltHash,\n        quiltUrl: session.quiltUrl,\n        quiltBytes: session.quiltBytes,\n        streaming: session.stream?.isStreaming ?? false,\n        streamTicks: session.stream?.ticks ?? 0,\n        streamLastFrameHash: session.stream?.lastFrameHash,\n        streamLastError: session.stream?.lastError,\n        lastSyncTime: session.lastSyncTime,\n      };\n    }\n\n    case 'holo_holotwin_disconnect': {\n      const sessionId = typeof args.sessionId === 'string' ? args.sessionId.trim() : '';\n\n      const session = sessions.get(sessionId);\n      if (!session) {\n        throw new Error(`holotwin: session ${sessionId} not found`);\n      }\n\n      session.isConnected = false;\n      stopHoloTwinStream(session);\n      sessions.delete(sessionId);\n\n      return {\n        ok: true,\n        sessionId,\n        message: 'Disconnected from IoT sensor',\n      };\n    }\n\n    case 'holo_holotwin_example': {\n      const device = (args.device as LookingGlassDevice) || '16inch';\n      const includeSimulation =\n        typeof args.includeSimulation === 'boolean' ? args.includeSimulation : true;\n\n      // Generate complete example\n      const example = generateHoloTwinExample(device, includeSimulation);\n\n      return {\n        ok: true,\n        device,\n        ...example,\n      };\n    }\n\n    default:\n      return undefined;\n  }\n}\n\n// =============================================================================\n// HELPERS\n// =============================================================================\n\nfunction parseHoloTwinComposition(holoCode: string): QuiltComposition {\n  const result = parseHolo(holoCode, { tolerant: false });\n  if (!result.success || !result.ast) {\n    const reason = result.errors?.[0]?.message ?? 'unknown parse failure';\n    throw new Error(`holotwin: holoCode parse failed: ${reason}`);\n  }\n  return result.ast as QuiltComposition;\n}\n\nasync function renderQuiltReceipt(\n  composition: QuiltComposition,\n  quiltConfig: QuiltConfig,\n  session: HoloTwinSession\n): Promise<QuiltReceipt> {\n  const renderConfig = makeReceiptRenderConfig(quiltConfig);\n  const fixture = makeTelemetryFixture(session);\n  const renderer = new BrowserQuiltRenderer({\n    path: 'cpu',\n    composition,\n    overrides: renderConfig,\n    imageDecoder: async () => fixture.source,\n  });\n\n  const pngBytes = await renderer.render({\n    depthMap: fixture.depthMap,\n    normalMap: fixture.normalMap,\n    width: fixture.width,\n    height: fixture.height,\n    frames: 1,\n    media: new Uint8Array([0x89, 0x50, 0x4e, 0x47]),\n    sourceKind: 'image',\n  });\n\n  const sha256 = createHash('sha256').update(pngBytes).digest('hex');\n  return {\n    pngBase64: Buffer.from(pngBytes).toString('base64'),\n    sha256,\n    bytes: pngBytes.byteLength,\n    renderConfig,\n  };\n}\n\nfunction makeReceiptRenderConfig(config: QuiltConfig): QuiltConfig {\n  const views = Math.max(1, Math.min(config.views, 6));\n  const columns = Math.min(3, views);\n  const rows = Math.ceil(views / columns);\n  return {\n    ...config,\n    views,\n    columns,\n    rows,\n    resolution: [columns * 64, rows * 64],\n  };\n}\n\nfunction makeTelemetryFixture(session: HoloTwinSession): {\n  width: number;\n  height: number;\n  source: { data: Uint8ClampedArray; width: number; height: number };\n  depthMap: Float32Array;\n  normalMap: Float32Array;\n} {\n  const width = 32;\n  const height = 32;\n  const source = new Uint8ClampedArray(width * height * 4);\n  const depthMap = new Float32Array(width * height);\n  const normalMap = new Float32Array(width * height * 3);\n  const mappingBias = Math.max(1, session.mappings.length);\n\n  for (let y = 0; y < height; y++) {\n    for (let x = 0; x < width; x++) {\n      const i = y * width + x;\n      const pixel = i * 4;\n      const nx = x / (width - 1);\n      const ny = y / (height - 1);\n      source[pixel] = Math.round(40 + nx * 180);\n      source[pixel + 1] = Math.round(60 + ny * 120);\n      source[pixel + 2] = Math.round(80 + ((mappingBias * 31) % 120));\n      source[pixel + 3] = 255;\n      depthMap[i] = Math.min(1, Math.max(0, Math.hypot(nx - 0.5, ny - 0.5) * 1.4));\n      normalMap[i * 3] = 0;\n      normalMap[i * 3 + 1] = 0;\n      normalMap[i * 3 + 2] = 1;\n    }\n  }\n\n  return {\n    width,\n    height,\n    source: { data: source, width, height },\n    depthMap,\n    normalMap,\n  };\n}\n\nasync function runStreamTick(session: HoloTwinSession): Promise<void> {\n  const stream = session.stream;\n  if (!stream?.isStreaming) return;\n\n  try {\n    const holoCode =\n      session.holoCode.trim() || generateHoloTwinExample(session.device, true).holoCode;\n    const composition = parseHoloTwinComposition(holoCode);\n    const baseConfig = LOOKING_GLASS_PRESETS[session.device];\n    const compiler = new QuiltCompiler();\n    compiler.compileQuilt(composition, baseConfig);\n    const receipt = await renderQuiltReceipt(composition, baseConfig, session);\n\n    stream.ticks += 1;\n    stream.lastFrameHash = `sha256:${receipt.sha256}`;\n    stream.lastError = undefined;\n    session.quiltHash = stream.lastFrameHash;\n    session.quiltUrl = `data:image/png;base64,${receipt.pngBase64}`;\n    session.quiltBytes = receipt.bytes;\n    session.quiltPngBase64 = receipt.pngBase64;\n    session.lastSyncTime = Date.now();\n  } catch (error) {\n    stream.lastError = error instanceof Error ? error.message : String(error);\n  }\n}\n\nfunction stopHoloTwinStream(session: HoloTwinSession): void {\n  const stream = session.stream;\n  if (!stream) return;\n  if (stream.timer) clearInterval(stream.timer);\n  if (stream.stopTimer) clearTimeout(stream.stopTimer);\n  stream.isStreaming = false;\n  stream.timer = undefined;\n  stream.stopTimer = undefined;\n}\n\nfunction unrefTimer(timer: ReturnType<typeof setInterval> | ReturnType<typeof setTimeout>): void {\n  if (typeof timer === 'object' && timer !== null && 'unref' in timer) {\n    (timer as { unref(): void }).unref();\n  }\n}\n\nfunction generateHoloTwinExample(device: LookingGlassDevice, includeSimulation: boolean) {\n  const preset = LOOKING_GLASS_PRESETS[device];\n\n  const holoCode = `composition \"Smart Farm HoloTwin\" {\n  environment {\n    skybox: \"farm\"\n    ambient_light: 0.5\n  }\n\n  object \"SoilMoistureSensor\" {\n    @iot_sensor { device_id: \"soil-001\", protocol: \"mqtt\" }\n    @holo_twin {\n      physical_id: \"soil-001\"\n      display_device: \"${device}\"\n      auto_recompile: true\n    }\n    geometry: \"cylinder\"\n    position: [-2, 0.5, 0]\n    scale: [0.3, 1, 0.3]\n    color: \"#8B4513\"\n  }\n\n  object \"TemperatureSensor\" {\n    @iot_sensor { device_id: \"temp-001\", protocol: \"mqtt\" }\n    @holo_twin {\n      physical_id: \"temp-001\"\n      display_device: \"${device}\"\n    }\n    geometry: \"sphere\"\n    position: [0, 1.5, 0]\n    scale: [0.5, 0.5, 0.5]\n    color: \"#FF6B6B\"\n    emissive: \"#FF6B6B\"\n    emissiveIntensity: 0.5\n  }\n\n  object \"HumiditySensor\" {\n    @iot_sensor { device_id: \"humidity-001\", protocol: \"mqtt\" }\n    @holo_twin {\n      physical_id: \"humidity-001\"\n      display_device: \"${device}\"\n    }\n    geometry: \"box\"\n    position: [2, 0.75, 0]\n    scale: [0.4, 0.4, 0.4]\n    color: \"#4ECDC4\"\n  }\n\n  object \"DashboardLabel\" {\n    geometry: \"plane\"\n    position: [0, 3, -2]\n    scale: [4, 0.5, 0.1]\n    label: \"Smart Farm Sensor Dashboard\"\n    color: \"#ffffff\"\n  }\n}`;\n\n  const mappings = [\n    {\n      sensor_key: 'moisture',\n      scene_property: 'scale',\n      transform: 'scale' as const,\n      min: 0,\n      max: 100,\n    },\n    {\n      sensor_key: 'temperature',\n      scene_property: 'emissiveIntensity',\n      transform: 'emissive' as const,\n      min: 10,\n      max: 40,\n    },\n    {\n      sensor_key: 'humidity',\n      scene_property: 'color',\n      transform: 'color' as const,\n      min: 0,\n      max: 100,\n    },\n  ];\n\n  return {\n    holoCode,\n    mappings,\n    quiltConfig: preset,\n    simulation: includeSimulation\n      ? {\n          enabled: true,\n          sensorData: {\n            moisture: 65,\n            temperature: 24,\n            humidity: 72,\n          },\n        }\n      : undefined,\n  };\n}\n","/**\n * HoloTune MCP tools.\n *\n * This is the agent-facing control surface for the sovereign per-identity\n * trace -> corpus -> tune -> eval -> promote -> serve/download loop. The MCP\n * server does not hold the founder's local filesystem or GPU credentials, so\n * these handlers provide safe contracts, receipts, and gate checks. The local\n * ai-ecosystem CLI performs the host-specific file and fleet operations.\n */\n\nimport { createHash } from 'node:crypto';\nimport type { Tool } from '@modelcontextprotocol/sdk/types.js';\n\ntype JsonRecord = Record<string, unknown>;\ntype HoloTuneCommand =\n  | 'status'\n  | 'curate'\n  | 'launch'\n  | 'eval'\n  | 'promote'\n  | 'serve'\n  | 'download';\n\nconst HOLOTUNE_COMMANDS: HoloTuneCommand[] = [\n  'status',\n  'curate',\n  'launch',\n  'eval',\n  'promote',\n  'serve',\n  'download',\n];\n\nconst TOOL_NAMES = HOLOTUNE_COMMANDS.map((command) => `holotune_${command}`);\n\nexport const holotuneToolDefinitions: Tool[] = [\n  {\n    name: 'holotune_status',\n    description:\n      'Inspect the HoloTune operation surface and return the safe local CLI/MCP contract for per-agent tuning.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        identity: { type: 'string', description: 'Optional agent or daimon identity.' },\n      },\n    },\n  },\n  {\n    name: 'holotune_curate',\n    description:\n      'Curate trace rows into HoloTune SFT JSONL and return a content hash. No GPU spend.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        identity: { type: 'string', description: 'Identity that owns the traces.' },\n        traceRows: {\n          type: 'array',\n          items: { type: 'object' },\n          description: 'Optional inline rows with {system,user,target}.',\n        },\n        maxRows: { type: 'number', description: 'Maximum rows to include.' },\n        includeJsonl: { type: 'boolean', description: 'Include JSONL in the response.' },\n      },\n    },\n  },\n  {\n    name: 'holotune_launch',\n    description:\n      'Prepare or launch a HoloTune GPU training run. Safe-by-default: dryRun unless dryRun:false/apply:true; routine non-dry launch requires signed-seat, free-first, and active-cap spend-admission receipts. FounderGate is exact-four pre-vetting only.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        identity: { type: 'string' },\n        corpusHash: { type: 'string' },\n        corpusUri: { type: 'string' },\n        recipe: { type: 'string' },\n        gpuBudgetUsd: { type: 'number' },\n        dryRun: { type: 'boolean' },\n        apply: { type: 'boolean' },\n        signedSeat: { type: 'object', description: 'Receipt binding a registered signing seat to this launch.' },\n        freeFirstReceipt: { type: 'object', description: 'Receipt proving the free/local path was exhausted.' },\n        spendAdmission: { type: 'object', description: 'Active-rail cap, ledger, timeout, teardown, and verifier admission receipt.' },\n        authorityEvidence: { type: 'object', description: 'Typed exact-four evidence. Omit or set all fields false for routine launch.' },\n        founderGate: {\n          type: 'object',\n          description:\n            'Exact-four pre-vetting manifest summary only. It is not required for routine launch and does not replace a verifier-bound Joseph decision.',\n        },\n      },\n    },\n  },\n  {\n    name: 'holotune_eval',\n    description:\n      'Evaluate tuned metrics against baseline metrics and return a promotion gate receipt.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        identity: { type: 'string' },\n        baselineMetrics: { type: 'object' },\n        tunedMetrics: { type: 'object' },\n        requiredBenchmarks: { type: 'array', items: { type: 'string' } },\n        minImproved: { type: 'number' },\n        improvementThreshold: { type: 'number' },\n      },\n    },\n  },\n  {\n    name: 'holotune_promote',\n    description:\n      'Prepare or apply a versioned adapter promotion. Routine non-dry promotion requires eval, promotion-gate, registry-admission, artifact, and rollback controls. FounderGate is exact-four pre-vetting only.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        identity: { type: 'string' },\n        version: { type: 'string' },\n        adapterUri: { type: 'string' },\n        ggufUri: { type: 'string' },\n        previousVersion: { type: 'string' },\n        evalReceipt: { type: 'object' },\n        promotionGateReceipt: { type: 'object' },\n        registryAdmission: { type: 'object' },\n        dryRun: { type: 'boolean' },\n        apply: { type: 'boolean' },\n        authorityEvidence: { type: 'object', description: 'Typed exact-four evidence. Omit or set all fields false for routine promotion.' },\n        founderGate: { type: 'object', description: 'Exact-four pre-vetting manifest only; never routine promotion authority.' },\n      },\n    },\n  },\n  {\n    name: 'holotune_serve',\n    description:\n      'Resolve the active HoloTune adapter into a serving plan, including a native @llama_serve spec (compile with compile_to_llama_server). Does not mutate serving state.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        identity: { type: 'string' },\n        version: { type: 'string' },\n        adapterUri: { type: 'string' },\n        ggufUri: { type: 'string' },\n        loraGgufUri: {\n          type: 'string',\n          description:\n            'A llama.cpp LoRA .gguf (from holotune-gguf-convert) for the @llama_serve.lora hot-swap slot — distinct from the PEFT adapterUri directory.',\n        },\n      },\n    },\n  },\n  {\n    name: 'holotune_download',\n    description:\n      'Build a downloadable sovereign GGUF manifest for an active HoloTune adapter. Fails honestly when no GGUF URI is registered.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        identity: { type: 'string' },\n        version: { type: 'string' },\n        ggufUri: { type: 'string' },\n        artifactUri: { type: 'string' },\n      },\n    },\n  },\n];\n\nconst HOLOTUNE_NAMES = new Set(TOOL_NAMES);\n\nexport function isHoloTuneToolName(name: string): boolean {\n  return HOLOTUNE_NAMES.has(name);\n}\n\nfunction stringArg(args: JsonRecord, key: string, fallback = ''): string {\n  const value = args[key];\n  return typeof value === 'string' && value.trim() ? value.trim() : fallback;\n}\n\nfunction numberArg(args: JsonRecord, key: string, fallback: number): number {\n  const value = args[key];\n  return typeof value === 'number' && Number.isFinite(value) ? value : fallback;\n}\n\nfunction stringArrayArg(args: JsonRecord, key: string): string[] {\n  const value = args[key];\n  if (!Array.isArray(value)) return [];\n  return value.filter(\n    (entry): entry is string => typeof entry === 'string' && entry.trim().length > 0\n  );\n}\n\nfunction recordArg(args: JsonRecord, key: string): JsonRecord | null {\n  const value = args[key];\n  return value && typeof value === 'object' && !Array.isArray(value)\n    ? (value as JsonRecord)\n    : null;\n}\n\nfunction hashPayload(payload: unknown): string {\n  return `sha256:${createHash('sha256').update(JSON.stringify(payload)).digest('hex')}`;\n}\n\nfunction stableVersion(identity: string): string {\n  return `${identity || 'agent'}-${new Date().toISOString().replace(/[^0-9A-Za-z]/g, '').slice(0, 14)}`;\n}\n\nfunction operationReceipt(action: HoloTuneCommand, payload: JsonRecord): JsonRecord {\n  const base = {\n    schema: 'holotune.operation-receipt.v1',\n    action,\n    generatedAt: new Date().toISOString(),\n    ...payload,\n  };\n  return { ...base, receiptHash: hashPayload(base) };\n}\n\nfunction founderGateSummary(args: JsonRecord): JsonRecord {\n  const gate =\n    recordArg(args, 'founderGate') ??\n    recordArg(args, 'founderGateReceipt') ??\n    recordArg(args, 'founder_gate');\n  if (!gate) {\n    return {\n      present: false,\n      valid: false,\n      reason: 'no exact-four pre-vetting manifest supplied',\n    };\n  }\n\n  const manifestHash =\n    typeof gate.manifestHash === 'string'\n      ? gate.manifestHash\n      : typeof gate.hash === 'string'\n        ? gate.hash\n        : typeof gate.receiptHash === 'string'\n          ? gate.receiptHash\n          : '';\n  const vetted = gate.valid === true || gate.status === 'vetted';\n  const valid = vetted && manifestHash.length > 0;\n  return {\n    present: true,\n    valid,\n    manifestHash: manifestHash || null,\n    reviewer: typeof gate.reviewer === 'string' ? gate.reviewer : null,\n    reason: valid ? 'exact-four pre-vetting manifest present' : 'founderGate needs manifestHash and valid:true; it is not an approval receipt',\n  };\n}\n\nfunction controlReceiptSummary(args: JsonRecord, key: string): JsonRecord {\n  const receipt = recordArg(args, key);\n  if (!receipt) return { present: false, valid: false, reason: `missing ${key}` };\n  const nested = receipt.receipt && typeof receipt.receipt === 'object' && !Array.isArray(receipt.receipt)\n    ? receipt.receipt as JsonRecord\n    : null;\n  const receiptHash = [receipt.receiptHash, receipt.manifestHash, receipt.hash, nested?.receiptHash]\n    .find((value): value is string => typeof value === 'string' && value.length > 0) ?? '';\n  const status = typeof receipt.status === 'string' ? receipt.status.toLowerCase() : '';\n  const valid = receiptHash.length > 0 && (\n    receipt.valid === true || receipt.passed === true || receipt.approved === true ||\n    status === 'pass' || status === 'passed' || status === 'approved' || status === 'admitted'\n  );\n  return {\n    present: true,\n    valid,\n    receiptHash: receiptHash || null,\n    reason: valid ? `${key} valid` : `${key} needs a bound receipt hash and PASS/admitted verdict`,\n  };\n}\n\nfunction exactFourSummary(args: JsonRecord): JsonRecord {\n  const evidence = recordArg(args, 'authorityEvidence') ?? recordArg(args, 'authority_evidence') ?? {};\n  const classes = new Set<string>();\n  if (evidence.exceedsActiveRailCap === true || evidence.exceeds_active_rail_cap === true ||\n      evidence.touchesTreasuryOrCustody === true || evidence.touches_treasury_or_custody === true ||\n      evidence.newWalletOrMintAuthorityMutation === true || evidence.new_wallet_or_mint_authority_mutation === true) classes.add('spend');\n  if (evidence.requiresJosephBodySignaturePresence === true || evidence.requires_joseph_body_signature_presence === true) classes.add('physical');\n  if (evidence.publicCommitmentUnderJosephNameFaceVoice === true || evidence.public_commitment_under_joseph_name_face_voice === true) classes.add('public');\n  if (evidence.governanceTierMutation === true || evidence.governance_tier_mutation === true) classes.add('governance');\n  return { required: classes.size > 0, classes: [...classes] };\n}\n\nfunction isDryRun(args: JsonRecord): boolean {\n  if (args.apply === true) return false;\n  return args.dryRun !== false;\n}\n\nfunction metricValue(metrics: JsonRecord, key: string): number | null {\n  const value = metrics[key];\n  return typeof value === 'number' && Number.isFinite(value) ? value : null;\n}\n\nfunction relativeImprovement(baseline: number, tuned: number): number {\n  if (baseline === 0) return tuned > 0 ? Infinity : 0;\n  return (tuned - baseline) / Math.abs(baseline);\n}\n\nfunction status(args: JsonRecord): JsonRecord {\n  const identity = stringArg(args, 'identity', 'all');\n  return {\n    ok: true,\n    surface: 'holotune',\n    identity,\n    mcpTools: TOOL_NAMES,\n    localCli: 'node scripts/holotune.mjs <status|curate|launch|eval|promote|serve|download>',\n    stateRootHint: '~/.ai-ecosystem/holotune',\n    governance: {\n      safeByDefault: true,\n      routineGpuSpendRequiresFounderGate: false,\n      routinePromoteToServeRequiresFounderGate: false,\n      exactFourRequiresVerifierBoundJosephDecision: true,\n      routineLaunchControls: ['signedSeat', 'freeFirstReceipt', 'spendAdmission'],\n      routinePromotionControls: ['evalReceipt', 'promotionGateReceipt', 'registryAdmission'],\n      receipts: 'immutable operation receipts with sha256 hashes',\n      rollback: 'versioned adapter registry keeps previousVersion for instant rollback',\n    },\n  };\n}\n\nfunction curate(args: JsonRecord): JsonRecord {\n  const identity = stringArg(args, 'identity', 'all');\n  const maxRows = Math.max(0, Math.floor(numberArg(args, 'maxRows', 10_000)));\n  const rawRows = Array.isArray(args.traceRows) ? args.traceRows : [];\n  const rows = rawRows\n    .filter((row): row is JsonRecord => row !== null && typeof row === 'object' && !Array.isArray(row))\n    .filter((row) => typeof row.user === 'string' && typeof row.target === 'string')\n    .slice(0, maxRows)\n    .map((row) => ({\n      system: typeof row.system === 'string' ? row.system : '',\n      user: row.user,\n      target: row.target,\n      source: typeof row.source === 'string' ? row.source : 'mcp-inline-trace',\n      agentId: typeof row.agentId === 'string' ? row.agentId : identity,\n    }));\n  const jsonl = rows.map((row) => JSON.stringify(row)).join('\\n') + (rows.length ? '\\n' : '');\n  return {\n    ok: true,\n    identity,\n    curatedCount: rows.length,\n    skippedCount: rawRows.length - rows.length,\n    corpusHash: hashPayload(jsonl || `${identity}:empty-corpus`),\n    jsonl: args.includeJsonl === true ? jsonl : undefined,\n  };\n}\n\nfunction launch(args: JsonRecord): JsonRecord {\n  const identity = stringArg(args, 'identity', 'unknown-agent');\n  const dryRun = isDryRun(args);\n  const gate = founderGateSummary(args);\n  const authority = exactFourSummary(args);\n  if (!dryRun && authority.required === true) {\n    return {\n      ok: false,\n      error: 'exact-four-decision-verifier-required',\n      founderGateRequired: true,\n      founderGate: gate,\n      authority,\n      message: 'Exact-four launch context needs a verifier-bound Joseph decision; a pre-vetting manifest alone cannot authorize spend.',\n    };\n  }\n  const launchControls = {\n    signedSeat: controlReceiptSummary(args, 'signedSeat'),\n    freeFirstReceipt: controlReceiptSummary(args, 'freeFirstReceipt'),\n    spendAdmission: controlReceiptSummary(args, 'spendAdmission'),\n  };\n  if (!dryRun && Object.values(launchControls).some((control) => control.valid !== true)) {\n    return {\n      ok: false,\n      error: 'launch-controls-required',\n      founderGateRequired: false,\n      launchControls,\n      authority,\n      message: 'Routine non-dry HoloTune launch requires signed-seat, free-first, and active-cap spend-admission receipts.',\n    };\n  }\n\n  const payload = {\n    identity,\n    dryRun,\n    corpusHash: stringArg(args, 'corpusHash') || null,\n    corpusUri: stringArg(args, 'corpusUri') || null,\n    recipe: stringArg(args, 'recipe', 'datasets/lora-recipe.py'),\n    gpuBudgetUsd: numberArg(args, 'gpuBudgetUsd', 0),\n    authority,\n    launchControls,\n    founderGate: gate,\n  };\n\n  return {\n    ok: true,\n    ...payload,\n    spendIntent: !dryRun,\n    command:\n      'node scripts/holotune.mjs launch --identity <id> --corpus <jsonl> --dry-run',\n    receipt: operationReceipt('launch', payload),\n  };\n}\n\nfunction evalGate(args: JsonRecord): JsonRecord {\n  const identity = stringArg(args, 'identity', 'unknown-agent');\n  const baseline = recordArg(args, 'baselineMetrics') ?? {};\n  const tuned = recordArg(args, 'tunedMetrics') ?? {};\n  const required = stringArrayArg(args, 'requiredBenchmarks');\n  const keys =\n    required.length > 0\n      ? required\n      : Object.keys(baseline).filter((key) => metricValue(tuned, key) !== null);\n  const threshold = numberArg(args, 'improvementThreshold', 0.05);\n  const minImproved = Math.max(0, Math.floor(numberArg(args, 'minImproved', keys.length ? 1 : 0)));\n  const benchmarks = keys.map((key) => {\n    const baselineValue = metricValue(baseline, key);\n    const tunedValue = metricValue(tuned, key);\n    const improvement =\n      baselineValue === null || tunedValue === null\n        ? null\n        : relativeImprovement(baselineValue, tunedValue);\n    return {\n      id: key,\n      baseline: baselineValue,\n      tuned: tunedValue,\n      improvement,\n      improved: improvement !== null && improvement >= threshold,\n    };\n  });\n  const improvedCount = benchmarks.filter((benchmark) => benchmark.improved).length;\n  const passed = improvedCount >= minImproved;\n  const payload = { identity, threshold, minImproved, improvedCount, passed, benchmarks };\n  return {\n    ok: true,\n    ...payload,\n    receipt: operationReceipt('eval', payload),\n  };\n}\n\nfunction promote(args: JsonRecord): JsonRecord {\n  const identity = stringArg(args, 'identity', 'unknown-agent');\n  const dryRun = isDryRun(args);\n  const adapterUri = stringArg(args, 'adapterUri');\n  const ggufUri = stringArg(args, 'ggufUri');\n  const version = stringArg(args, 'version', stableVersion(identity));\n  const gate = founderGateSummary(args);\n  const authority = exactFourSummary(args);\n  if (!dryRun && authority.required === true) {\n    return {\n      ok: false,\n      error: 'exact-four-decision-verifier-required',\n      founderGateRequired: true,\n      founderGate: gate,\n      authority,\n      message: 'Exact-four promotion context needs a verifier-bound Joseph decision; a pre-vetting manifest alone cannot authorize registry mutation.',\n    };\n  }\n  if (!dryRun && !adapterUri) {\n    return {\n      ok: false,\n      error: 'adapter-uri-required',\n      message: 'Non-dry promotion requires adapterUri.',\n    };\n  }\n  const promotionControls = {\n    evalReceipt: controlReceiptSummary(args, 'evalReceipt'),\n    promotionGateReceipt: controlReceiptSummary(args, 'promotionGateReceipt'),\n    registryAdmission: controlReceiptSummary(args, 'registryAdmission'),\n  };\n  if (!dryRun && Object.values(promotionControls).some((control) => control.valid !== true)) {\n    return {\n      ok: false,\n      error: 'promotion-controls-required',\n      founderGateRequired: false,\n      promotionControls,\n      authority,\n      message: 'Routine non-dry promotion requires eval, promotion-gate, and registry-admission receipts.',\n    };\n  }\n\n  const payload = {\n    identity,\n    dryRun,\n    version,\n    adapterUri: adapterUri || null,\n    ggufUri: ggufUri || null,\n    previousVersion: stringArg(args, 'previousVersion') || null,\n    downloadable: ggufUri.length > 0,\n    evalReceipt: recordArg(args, 'evalReceipt'),\n    promotionGateReceipt: recordArg(args, 'promotionGateReceipt'),\n    registryAdmission: recordArg(args, 'registryAdmission'),\n    promotionControls,\n    authority,\n    founderGate: gate,\n  };\n\n  return {\n    ok: true,\n    ...payload,\n    rollbackPointer: payload.previousVersion,\n    receipt: operationReceipt('promote', payload),\n  };\n}\n\n/** Sanitize an id segment into a sovereign-devices registry handle fragment. */\nfunction serveHandleSegment(value: string): string {\n  return value.replace(/[^a-z0-9]+/gi, '-').replace(/^-+|-+$/g, '').toLowerCase() || 'adapter';\n}\n\n/**\n * Render the native `@llama_serve { ... }` block a caller can drop into a `.holo`\n * and compile with `compile_to_llama_server`. This is the M5 seam: HoloTune no\n * longer hands back a bare CLI string — it hands back authorable HoloScript that\n * the sovereign llama.cpp compiler consumes, and it wires the `grammar: \"holoscript\"`\n * constrained-decode preset so the served adapter emits valid HoloScript by construction.\n */\nfunction buildLlamaServeSnippet(spec: {\n  handle: string;\n  model: string;\n  gguf: string | null;\n  lora: string | null;\n}): string {\n  // Escape values interpolated into double-quoted HoloScript fields: collapse newlines\n  // and backslash-escape inner quotes (the lexer accepts \\\" ), so a stray quote in a URI\n  // can't terminate the string early and emit an unparseable @llama_serve block.\n  const esc = (v: string): string => v.replace(/[\\r\\n]+/g, ' ').replace(/\\\\/g, '\\\\\\\\').replace(/\"/g, '\\\\\"');\n  const lines = ['@llama_serve {', `  model: \"${esc(spec.model)}\"`];\n  if (spec.gguf) lines.push(`  gguf: \"${esc(spec.gguf)}\"`);\n  if (spec.lora) lines.push(`  lora: \"${esc(spec.lora)}\"`);\n  lines.push(`  register_as: \"${esc(spec.handle)}\"`, '  grammar: \"holoscript\"', '}');\n  return lines.join('\\n');\n}\n\nfunction serve(args: JsonRecord): JsonRecord {\n  const identity = stringArg(args, 'identity', 'unknown-agent');\n  const adapterUri = stringArg(args, 'adapterUri');\n  const ggufUri = stringArg(args, 'ggufUri');\n  const loraGgufUri = stringArg(args, 'loraGgufUri');\n  const version = stringArg(args, 'version', 'active');\n  const serveReady = Boolean(adapterUri || ggufUri);\n\n  // The LoRA slot for a real llama.cpp hot-serve must be a .gguf adapter (produced by\n  // holotune-gguf-convert.mjs), NOT the PEFT adapter directory (adapterUri). Prefer an\n  // explicit loraGgufUri; accept adapterUri only when it already points at a .gguf.\n  const loraPath = loraGgufUri || (adapterUri.endsWith('.gguf') ? adapterUri : null);\n  const handle = `${serveHandleSegment(identity)}-${serveHandleSegment(version)}`;\n  const llamaServe =\n    ggufUri || loraPath\n      ? {\n          schema: 'holotune.llama-serve.v1',\n          handle,\n          model: `${identity}:${version}`,\n          gguf: ggufUri || null,\n          lora: loraPath,\n          source: 'holotune' as const,\n        }\n      : null;\n\n  return {\n    ok: true,\n    identity,\n    version,\n    serveReady,\n    adapterUri: adapterUri || null,\n    ggufUri: ggufUri || null,\n    loraGgufUri: loraGgufUri || null,\n    // Native @llama_serve spec (compile with target 'llama-server') + its authorable block.\n    llamaServe,\n    llamaServeHsplus: llamaServe ? buildLlamaServeSnippet(llamaServe) : null,\n    command: serveReady\n      ? 'node scripts/holotune.mjs serve --identity <id>'\n      : 'register an adapter with holotune_promote before serving',\n    receipt: operationReceipt('serve', {\n      identity,\n      version,\n      serveReady,\n      adapterUri,\n      ggufUri,\n      loraGgufUri,\n    }),\n  };\n}\n\nfunction download(args: JsonRecord): JsonRecord {\n  const identity = stringArg(args, 'identity', 'unknown-agent');\n  const version = stringArg(args, 'version', 'active');\n  const ggufUri = stringArg(args, 'ggufUri') || stringArg(args, 'artifactUri');\n  if (!ggufUri) {\n    return {\n      ok: false,\n      downloadable: false,\n      error: 'gguf-artifact-required',\n      message:\n        'No GGUF artifact is registered for this adapter. Promote a version with ggufUri before download.',\n    };\n  }\n\n  const manifest = {\n    schema: 'holotune.download-manifest.v1',\n    identity,\n    version,\n    ggufUri,\n    generatedAt: new Date().toISOString(),\n  };\n\n  return {\n    ok: true,\n    downloadable: true,\n    manifest: { ...manifest, manifestHash: hashPayload(manifest) },\n    receipt: operationReceipt('download', { identity, version, ggufUri }),\n  };\n}\n\nexport async function handleHoloTuneTool(\n  name: string,\n  args: JsonRecord\n): Promise<unknown | null> {\n  switch (name) {\n    case 'holotune_status':\n      return status(args);\n    case 'holotune_curate':\n      return curate(args);\n    case 'holotune_launch':\n      return launch(args);\n    case 'holotune_eval':\n      return evalGate(args);\n    case 'holotune_promote':\n      return promote(args);\n    case 'holotune_serve':\n      return serve(args);\n    case 'holotune_download':\n      return download(args);\n    default:\n      return null;\n  }\n}\n","import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { basename, join, resolve } from 'node:path';\nimport type { Tool } from '@modelcontextprotocol/sdk/types.js';\n\ntype PercentileKey = 'min' | 'p50' | 'p90' | 'p99' | 'max' | 'mean';\ntype WindowKey = 'last7d' | 'last30d';\n\ninterface PercentileStats {\n  n: number;\n  min: number;\n  p50: number;\n  p90: number;\n  p99: number;\n  max: number;\n  mean: number;\n}\n\ninterface TaskTypeStats {\n  taskType: string;\n  commitCount: number;\n  boundToTaskPct: number;\n  distinctAuthors: number;\n  repos: Record<string, number>;\n  interCommitGapSecs: PercentileStats | null;\n}\n\ninterface TaskDurationStats {\n  taskCount: number;\n  durationSecs: PercentileStats;\n}\n\ninterface AgentTimeArtifact {\n  generatedAt: string;\n  windowSinceLabel: string;\n  windowSinceGit: string;\n  totals?: {\n    bindingCoveragePct?: number;\n    boundCommits?: number;\n    boundTasks?: number;\n  };\n  taxonomy?: Array<{ taskType: string; n: number }>;\n  taskTypeStats: Record<string, TaskTypeStats>;\n  taskDurations?: Record<string, TaskDurationStats>;\n  caveats?: string[];\n}\n\ninterface DurationAlternative {\n  taskType: string;\n  estimateSecs: number | null;\n  sampleSize: number;\n  commitCount: number;\n  basis: EstimateBasis;\n}\n\ntype EstimateBasis = 'multi_commit_task_duration' | 'inter_commit_gap_proxy' | 'taxonomy_only';\n\nexport interface EstimateTaskDurationResult {\n  success: boolean;\n  status: 'ok' | 'catalog' | 'not_found' | 'no_data';\n  requestedTaskType?: string;\n  inferredTaskType?: string;\n  matchedTaskType?: string;\n  percentile: PercentileKey;\n  estimateSecs?: number;\n  estimateMinutes?: number;\n  estimateHours?: number;\n  basis?: EstimateBasis;\n  confidence: 'none' | 'low' | 'medium' | 'high';\n  sampleSize: number;\n  commitCount?: number;\n  boundToTaskPct?: number;\n  window: {\n    requested: WindowKey;\n    label?: string;\n    sinceGit?: string;\n    generatedAt?: string;\n  };\n  sourcePath?: string;\n  alternatives: DurationAlternative[];\n  caveats: string[];\n  message?: string;\n}\n\ninterface EstimateTaskDurationArgs {\n  taskType?: string;\n  taskTitle?: string;\n  percentile?: PercentileKey;\n  window?: WindowKey;\n  dataPath?: string;\n  sourceRoot?: string;\n  maxAlternatives?: number;\n  includeCaveats?: boolean;\n}\n\nexport const estimateTaskDurationTools: Tool[] = [\n  {\n    name: 'holo_estimate_task_duration',\n    description:\n      'Estimate agent task duration from the latest agent-time mined artifact. ' +\n      'Use taskType for known taxonomy buckets (for example fix-core, feat-mcp, docs-paper), ' +\n      'or taskTitle to infer a bucket from a conventional-commit-style title. ' +\n      'Returns: JSON with estimate seconds/minutes/hours, evidence basis, confidence, source artifact, alternatives, and caveats.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        taskType: {\n          type: 'string',\n          description:\n            'Agent-time taxonomy bucket, e.g. feat-mcp, fix-core, docs-paper, audit, refactor.',\n        },\n        taskTitle: {\n          type: 'string',\n          description:\n            'Optional task title or conventional commit subject to classify when taskType is not provided.',\n        },\n        percentile: {\n          type: 'string',\n          enum: ['min', 'p50', 'p90', 'p99', 'max', 'mean'],\n          description: 'Duration percentile to return. Defaults to p50.',\n        },\n        window: {\n          type: 'string',\n          enum: ['last7d', 'last30d'],\n          description: 'Agent-time artifact window to use. Defaults to last30d.',\n        },\n        dataPath: {\n          type: 'string',\n          description:\n            'Optional explicit path to an agent-time JSON artifact. Primarily for deterministic tests.',\n        },\n        sourceRoot: {\n          type: 'string',\n          description:\n            'Optional ai-ecosystem root containing research/agent-time/*.json. Defaults to AI_ECOSYSTEM_ROOT or ~/.ai-ecosystem.',\n        },\n        maxAlternatives: {\n          type: 'number',\n          description:\n            'Maximum alternative task-type rows to return when no exact match exists. Defaults to 5.',\n        },\n        includeCaveats: {\n          type: 'boolean',\n          description: 'Include source artifact caveats. Defaults to true.',\n        },\n      },\n    },\n  },\n];\n\nexport async function handleEstimateTaskDurationTool(\n  name: string,\n  args: Record<string, unknown>\n): Promise<EstimateTaskDurationResult | null> {\n  if (name !== 'holo_estimate_task_duration') return null;\n\n  const parsed = parseArgs(args);\n  const sourcePath = resolveArtifactPath(parsed);\n  if (!sourcePath) {\n    return {\n      success: false,\n      status: 'no_data',\n      percentile: parsed.percentile,\n      confidence: 'none',\n      sampleSize: 0,\n      window: { requested: parsed.window },\n      alternatives: [],\n      caveats: [],\n      message:\n        'No agent-time JSON artifact found. Run scripts/agent-time-mine.mjs or pass dataPath/sourceRoot.',\n    };\n  }\n\n  const artifact = loadArtifact(sourcePath);\n  const requestedTaskType = parsed.taskType?.trim();\n  const inferredTaskType =\n    requestedTaskType === undefined && parsed.taskTitle\n      ? classifyTaskTitle(parsed.taskTitle)\n      : undefined;\n  const wanted = normalizeTaskType(requestedTaskType || inferredTaskType || '');\n  const alternatives = topAlternatives(artifact, parsed.percentile, parsed.maxAlternatives);\n  const caveats = parsed.includeCaveats === false ? [] : buildCaveats(artifact);\n\n  if (!wanted) {\n    return {\n      success: true,\n      status: 'catalog',\n      percentile: parsed.percentile,\n      confidence: 'none',\n      sampleSize: 0,\n      window: artifactWindow(parsed.window, artifact),\n      sourcePath,\n      alternatives,\n      caveats,\n      message: 'Provide taskType or taskTitle to return a specific estimate.',\n    };\n  }\n\n  const match = resolveTaskType(artifact, wanted);\n  if (!match) {\n    return {\n      success: false,\n      status: 'not_found',\n      requestedTaskType,\n      inferredTaskType,\n      percentile: parsed.percentile,\n      confidence: 'none',\n      sampleSize: 0,\n      window: artifactWindow(parsed.window, artifact),\n      sourcePath,\n      alternatives,\n      caveats,\n      message: `No task-type bucket matched \"${requestedTaskType || inferredTaskType || wanted}\".`,\n    };\n  }\n\n  const estimate = estimateForTaskType(artifact, match, parsed.percentile);\n  if (!estimate || estimate.estimateSecs === null) {\n    return {\n      success: false,\n      status: 'no_data',\n      requestedTaskType,\n      inferredTaskType,\n      matchedTaskType: match,\n      percentile: parsed.percentile,\n      confidence: 'none',\n      sampleSize: 0,\n      commitCount: artifact.taskTypeStats[match]?.commitCount,\n      boundToTaskPct: artifact.taskTypeStats[match]?.boundToTaskPct,\n      window: artifactWindow(parsed.window, artifact),\n      sourcePath,\n      alternatives,\n      caveats,\n      message: `Task-type \"${match}\" exists, but has no usable duration or inter-commit-gap sample.`,\n    };\n  }\n\n  const stats = artifact.taskTypeStats[match];\n  return {\n    success: true,\n    status: 'ok',\n    requestedTaskType,\n    inferredTaskType,\n    matchedTaskType: match,\n    percentile: parsed.percentile,\n    estimateSecs: estimate.estimateSecs,\n    estimateMinutes: round(estimate.estimateSecs / 60, 2),\n    estimateHours: round(estimate.estimateSecs / 3600, 2),\n    basis: estimate.basis,\n    confidence: confidenceFor(estimate.basis, estimate.sampleSize, stats?.boundToTaskPct || 0),\n    sampleSize: estimate.sampleSize,\n    commitCount: stats?.commitCount,\n    boundToTaskPct: stats?.boundToTaskPct,\n    window: artifactWindow(parsed.window, artifact),\n    sourcePath,\n    alternatives,\n    caveats,\n  };\n}\n\nfunction parseArgs(args: Record<string, unknown>): EstimateTaskDurationArgs & {\n  percentile: PercentileKey;\n  window: WindowKey;\n  maxAlternatives: number;\n} {\n  const percentile = isPercentile(args.percentile) ? args.percentile : 'p50';\n  const window = args.window === 'last7d' ? 'last7d' : 'last30d';\n  return {\n    taskType: typeof args.taskType === 'string' ? args.taskType : undefined,\n    taskTitle: typeof args.taskTitle === 'string' ? args.taskTitle : undefined,\n    percentile,\n    window,\n    dataPath: typeof args.dataPath === 'string' ? args.dataPath : undefined,\n    sourceRoot: typeof args.sourceRoot === 'string' ? args.sourceRoot : undefined,\n    maxAlternatives:\n      typeof args.maxAlternatives === 'number' && Number.isFinite(args.maxAlternatives)\n        ? Math.max(0, Math.min(25, Math.floor(args.maxAlternatives)))\n        : 5,\n    includeCaveats: typeof args.includeCaveats === 'boolean' ? args.includeCaveats : undefined,\n  };\n}\n\nfunction isPercentile(value: unknown): value is PercentileKey {\n  return (\n    value === 'min' ||\n    value === 'p50' ||\n    value === 'p90' ||\n    value === 'p99' ||\n    value === 'max' ||\n    value === 'mean'\n  );\n}\n\nfunction resolveArtifactPath(\n  args: EstimateTaskDurationArgs & { window: WindowKey }\n): string | null {\n  const explicit = firstExistingFile([args.dataPath, process.env.AGENT_TIME_DATA_PATH]);\n  if (explicit) return explicit;\n\n  const roots = [\n    args.sourceRoot,\n    process.env.AI_ECOSYSTEM_ROOT,\n    process.env.AGENT_TIME_ROOT,\n    join(homedir(), '.ai-ecosystem'),\n  ].filter((p): p is string => typeof p === 'string' && p.trim().length > 0);\n\n  const dirs = roots.flatMap((root) => {\n    const resolvedRoot = resolve(root);\n    if (basename(resolvedRoot) === 'agent-time') return [resolvedRoot];\n    return [join(resolvedRoot, 'research', 'agent-time'), resolvedRoot];\n  });\n\n  return newestArtifact(dirs, args.window);\n}\n\nfunction firstExistingFile(paths: Array<string | undefined>): string | null {\n  for (const p of paths) {\n    if (!p) continue;\n    const resolved = resolve(p);\n    try {\n      if (existsSync(resolved) && statSync(resolved).isFile()) return resolved;\n    } catch {\n      // Try the next candidate.\n    }\n  }\n  return null;\n}\n\nfunction newestArtifact(dirs: string[], window: WindowKey): string | null {\n  const prefix = `agent-time-${window}-to-`;\n  const candidates: Array<{ path: string; mtimeMs: number }> = [];\n  for (const dir of dirs) {\n    try {\n      if (!existsSync(dir) || !statSync(dir).isDirectory()) continue;\n      for (const name of readdirSync(dir)) {\n        if (!name.startsWith(prefix) || !name.endsWith('.json')) continue;\n        const filePath = join(dir, name);\n        const stat = statSync(filePath);\n        if (stat.isFile()) candidates.push({ path: filePath, mtimeMs: stat.mtimeMs });\n      }\n    } catch {\n      // Ignore unreadable roots.\n    }\n  }\n  candidates.sort((a, b) => b.mtimeMs - a.mtimeMs || b.path.localeCompare(a.path));\n  return candidates[0]?.path || null;\n}\n\nfunction loadArtifact(path: string): AgentTimeArtifact {\n  const parsed = JSON.parse(readFileSync(path, 'utf-8')) as unknown;\n  if (!isRecord(parsed) || !isRecord(parsed.taskTypeStats)) {\n    throw new Error(`Invalid agent-time artifact: ${path}`);\n  }\n  return parsed as unknown as AgentTimeArtifact;\n}\n\nfunction artifactWindow(\n  requested: WindowKey,\n  artifact: AgentTimeArtifact\n): EstimateTaskDurationResult['window'] {\n  return {\n    requested,\n    label: artifact.windowSinceLabel,\n    sinceGit: artifact.windowSinceGit,\n    generatedAt: artifact.generatedAt,\n  };\n}\n\nfunction resolveTaskType(artifact: AgentTimeArtifact, wanted: string): string | null {\n  const keys = Object.keys(artifact.taskTypeStats);\n  const exact = keys.find((k) => normalizeTaskType(k) === wanted);\n  if (exact) return exact;\n\n  const prefix = keys.find((k) => normalizeTaskType(k).startsWith(wanted));\n  if (prefix) return prefix;\n\n  return null;\n}\n\nfunction estimateForTaskType(\n  artifact: AgentTimeArtifact,\n  taskType: string,\n  percentile: PercentileKey\n): { estimateSecs: number | null; sampleSize: number; basis: EstimateBasis } | null {\n  const durationStats = artifact.taskDurations?.[taskType];\n  if (durationStats?.durationSecs) {\n    return {\n      estimateSecs: valueAt(durationStats.durationSecs, percentile),\n      sampleSize: durationStats.taskCount,\n      basis: 'multi_commit_task_duration',\n    };\n  }\n\n  const taskStats = artifact.taskTypeStats[taskType];\n  if (taskStats?.interCommitGapSecs) {\n    return {\n      estimateSecs: valueAt(taskStats.interCommitGapSecs, percentile),\n      sampleSize: taskStats.interCommitGapSecs.n,\n      basis: 'inter_commit_gap_proxy',\n    };\n  }\n\n  if (taskStats) {\n    return {\n      estimateSecs: null,\n      sampleSize: taskStats.commitCount,\n      basis: 'taxonomy_only',\n    };\n  }\n\n  return null;\n}\n\nfunction topAlternatives(\n  artifact: AgentTimeArtifact,\n  percentile: PercentileKey,\n  maxAlternatives: number\n): DurationAlternative[] {\n  if (maxAlternatives <= 0) return [];\n\n  const byTaxonomy = new Map((artifact.taxonomy || []).map((t) => [t.taskType, t.n]));\n  const rows = Object.keys(artifact.taskTypeStats)\n    .map((taskType) => {\n      const estimate = estimateForTaskType(artifact, taskType, percentile);\n      const stats = artifact.taskTypeStats[taskType];\n      return {\n        taskType,\n        estimateSecs: estimate?.estimateSecs ?? null,\n        sampleSize: estimate?.sampleSize ?? 0,\n        commitCount: stats?.commitCount ?? byTaxonomy.get(taskType) ?? 0,\n        basis: estimate?.basis ?? 'taxonomy_only',\n      };\n    })\n    .sort((a, b) => b.commitCount - a.commitCount || a.taskType.localeCompare(b.taskType));\n  return rows.slice(0, maxAlternatives);\n}\n\nfunction confidenceFor(\n  basis: EstimateBasis,\n  sampleSize: number,\n  boundToTaskPct: number\n): 'low' | 'medium' | 'high' {\n  if (basis === 'multi_commit_task_duration') {\n    if (sampleSize >= 10) return 'high';\n    if (sampleSize >= 3) return 'medium';\n    return 'low';\n  }\n  if (basis === 'inter_commit_gap_proxy') {\n    if (sampleSize >= 30 && boundToTaskPct >= 50) return 'medium';\n    return 'low';\n  }\n  return 'low';\n}\n\nfunction buildCaveats(artifact: AgentTimeArtifact): string[] {\n  const caveats = [...(artifact.caveats || [])];\n  if (Object.keys(artifact.taskDurations || {}).length === 0) {\n    caveats.push(\n      'No multi-commit task-duration rows are present in this artifact; estimates fall back to clipped inter-commit gaps.'\n    );\n  }\n  if ((artifact.totals?.bindingCoveragePct || 0) < 20) {\n    caveats.push(\n      'Task-to-commit binding coverage is low; treat estimates as directional planning hints.'\n    );\n  }\n  return [...new Set(caveats)];\n}\n\nfunction classifyTaskTitle(title: string): string | undefined {\n  const trimmed = title.trim();\n  const conventional = /^([a-z]+)(?:\\(([^)]+)\\))?:/i.exec(trimmed);\n  if (conventional) {\n    const type = conventional[1].toLowerCase();\n    const scope = (conventional[2] || '').toLowerCase();\n    if (type === 'feat') return scopedType('feat', scope);\n    if (type === 'fix') return scopedType('fix', scope);\n    if (type === 'docs') {\n      if (scope.includes('paper')) return 'docs-paper';\n      if (scope.includes('research')) return 'docs-research';\n      if (scope.includes('memory')) return 'docs-memory';\n      if (scope.includes('audit')) return 'docs-audit';\n      return 'docs';\n    }\n    if (\n      ['test', 'refactor', 'chore', 'audit', 'paper', 'research', 'perf', 'style'].includes(type)\n    ) {\n      return type;\n    }\n  }\n\n  const s = trimmed.toLowerCase();\n  if (s.includes('mcp')) return 'feat-mcp';\n  if (s.includes('paper-') || s.includes('citation')) return 'docs-paper';\n  if (s.includes('research')) return 'docs-research';\n  if (s.includes('audit')) return 'audit';\n  if (s.includes('hook')) return 'feat-hooks';\n  if (s.includes('script')) return 'feat-scripts';\n  if (s.includes('refactor')) return 'refactor';\n  if (s.includes('test') || s.includes('harness')) return 'test';\n  if (s.includes('fix') || s.includes('bug')) return 'fix-other';\n  return undefined;\n}\n\nfunction scopedType(type: 'feat' | 'fix', scope: string): string {\n  if (scope.includes('core')) return `${type}-core`;\n  if (scope.includes('mesh') || scope.includes('holomesh')) return `${type}-mesh`;\n  if (scope.includes('mcp')) return `${type}-mcp`;\n  if (scope.includes('studio')) return `${type}-studio`;\n  if (scope.includes('engine')) return `${type}-engine`;\n  if (scope.includes('hooks')) return `${type}-hooks`;\n  if (scope.includes('scripts')) return `${type}-scripts`;\n  if (type === 'fix' && scope.includes('deploy')) return 'fix-deploy';\n  if (type === 'fix' && scope.includes('absorb')) return 'fix-absorb';\n  if (type === 'fix' && scope.includes('infra')) return 'fix-infra';\n  if (type === 'fix' && scope.includes('security')) return 'fix-security';\n  if (type === 'fix' && scope.includes('paper')) return 'fix-paper';\n  return `${type}-other`;\n}\n\nfunction normalizeTaskType(value: string): string {\n  return value\n    .trim()\n    .toLowerCase()\n    .replace(/[_\\s]+/g, '-');\n}\n\nfunction valueAt(stats: PercentileStats, percentile: PercentileKey): number {\n  return stats[percentile];\n}\n\nfunction round(value: number, digits: number): number {\n  const factor = 10 ** digits;\n  return Math.round(value * factor) / factor;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n  return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n","/**\n * MCP Tool: holo_task_kolmogorov_score\n *\n * Scores task-routing decisions using a Solomonoff-prior-inspired\n * Kolmogorov-complexity proxy.\n *\n * Source authority: W.507 (research/2026-05-12_difficulty-and-luck-p-vs-np.md):\n *   \"Kolmogorov complexity makes luck precise. K(x) = shortest program.\n *    Solomonoff prior 2^(-K) is optimal least-biased. Luck = program length.\n *    Implication: information-theoretic agent priors should follow Kolmogorov /\n *    minimum-description-length, not uniform random.\"\n *\n * Intuition: an agent whose context \"compresses\" a task description well is a\n * better routing target than one whose context is unrelated. We approximate\n * Kolmogorov complexity (uncomputable) with a tractable MDL proxy:\n *\n *   baseline := gzip(taskDescription)\n *   mdl      := gzip(taskDescription, dict = recentDoneEntries.join('\\n'))\n *   ratio    := mdl.length / baseline.length         (0..1, ~1 means no benefit)\n *   score    := 1 - ratio                            (higher is better fit)\n *\n * Limitations: gzip-with-dictionary is a small fixed-window LZ77 + Huffman\n * substitute for Solomonoff's universal prior. It captures lexical and\n * short-phrase overlap, not deep semantic structure. See the scoping doc at\n * research/2026-05-12_kolmogorov-task-score-mcp.md for the formal\n * MDL definition, alternatives considered, and calibration boundaries.\n */\n\nimport { gzipSync, constants as zlibConstants } from 'node:zlib';\nimport type { Tool } from '@modelcontextprotocol/sdk/types.js';\n\n// ─── Public types ───────────────────────────────────────────────────────────\n\nexport interface AgentContext {\n  /** Recent done-log entries for this agent. Each entry is a free-form string. */\n  recentDoneEntries: string[];\n  /**\n   * Optional capability tags (e.g. `['security-audit', 'lean4']`). Concatenated\n   * to the agent dictionary with newline separators so they participate in\n   * dictionary-based compression alongside done-log entries.\n   */\n  capabilityTags?: string[];\n}\n\nexport interface KolmogorovScoreInput {\n  taskDescription: string;\n  agentContext: AgentContext;\n}\n\nexport interface KolmogorovScoreResult {\n  /** Higher means agent's context compresses this task better. Range: typically [0, ~0.5]. */\n  score: number;\n  /** Bytes after gzip with agent-conditioned dictionary. */\n  mdlBytes: number;\n  /** Bytes after gzip with no dictionary. */\n  baselineBytes: number;\n  /** mdlBytes / baselineBytes. 1.0 means no agent-conditioned benefit. */\n  ratio: number;\n}\n\n// ─── Pure function ──────────────────────────────────────────────────────────\n\nconst GZIP_OPTS = {\n  level: zlibConstants.Z_BEST_COMPRESSION,\n};\n\n/**\n * Solomonoff-prior-inspired MDL proxy for task-routing fit.\n *\n * Contract:\n *   - Empty `taskDescription` returns `{ score: 0, mdlBytes: 0, baselineBytes: 0, ratio: 0 }`.\n *   - Empty `recentDoneEntries` + empty `capabilityTags` makes the dictionary\n *     empty; mdlBytes will be >= baselineBytes (gzip with empty dictionary is\n *     effectively the baseline), so `score` is approximately 0 (may be slightly\n *     negative due to header overhead from priming — clamped to 0).\n *   - Score is monotonic non-decreasing in the amount of relevant overlap\n *     present in the dictionary (more matching entries → better compression\n *     → higher score), modulo gzip-window saturation (32 KB).\n */\nexport function holoTaskKolmogorovScore(input: KolmogorovScoreInput): KolmogorovScoreResult {\n  const taskDescription = typeof input?.taskDescription === 'string' ? input.taskDescription : '';\n\n  if (taskDescription.length === 0) {\n    return { score: 0, mdlBytes: 0, baselineBytes: 0, ratio: 0 };\n  }\n\n  const agentContext = input?.agentContext ?? { recentDoneEntries: [] };\n  const recentDoneEntries = Array.isArray(agentContext.recentDoneEntries)\n    ? agentContext.recentDoneEntries.filter((s): s is string => typeof s === 'string')\n    : [];\n  const capabilityTags = Array.isArray(agentContext.capabilityTags)\n    ? agentContext.capabilityTags.filter((s): s is string => typeof s === 'string')\n    : [];\n\n  const dictionaryParts: string[] = [];\n  if (capabilityTags.length > 0) dictionaryParts.push(capabilityTags.join(' '));\n  if (recentDoneEntries.length > 0) dictionaryParts.push(recentDoneEntries.join('\\n'));\n  const dictionary = dictionaryParts.join('\\n');\n\n  // Baseline: compress task description with NO dictionary priming.\n  const taskBuf = Buffer.from(taskDescription, 'utf-8');\n  const baselineBytes = gzipSync(taskBuf, GZIP_OPTS).length;\n\n  // Agent-conditioned MDL: prepend dictionary then compress the same input.\n  // We compress the concatenation, then subtract the cost of the dictionary alone.\n  // This gives the *marginal* cost of the task under agent context — the MDL\n  // proxy for K(task | agent_context).\n  let mdlBytes: number;\n  if (dictionary.length === 0) {\n    // No dictionary → MDL collapses to baseline.\n    mdlBytes = baselineBytes;\n  } else {\n    const dictBuf = Buffer.from(dictionary, 'utf-8');\n    // Separator newline so the task starts on its own line (helps LZ77 boundary).\n    const sepBuf = Buffer.from('\\n', 'utf-8');\n    const joinedBytes = gzipSync(Buffer.concat([dictBuf, sepBuf, taskBuf]), GZIP_OPTS).length;\n    const dictAloneBytes = gzipSync(dictBuf, GZIP_OPTS).length;\n    // Marginal bytes added by appending the task to the agent's dictionary.\n    // Clamp to >= 1 to avoid div-by-zero pathology if the task is wholly\n    // contained in the dictionary.\n    mdlBytes = Math.max(1, joinedBytes - dictAloneBytes);\n  }\n\n  const ratio = mdlBytes / baselineBytes;\n  // Score: positive means agent context helped compress; clamp to [-1, 1] for sanity,\n  // and floor at 0 because negative scores (mdl > baseline by a thin gzip-header margin)\n  // are noise, not signal.\n  const rawScore = 1 - ratio;\n  const score = rawScore < 0 ? 0 : rawScore;\n\n  return { score, mdlBytes, baselineBytes, ratio };\n}\n\n// ─── MCP tool registration ──────────────────────────────────────────────────\n\nexport const kolmogorovTaskScoreTools: Tool[] = [\n  {\n    name: 'holo_task_kolmogorov_score',\n    description:\n      'Score how well an agent fits a task using a Solomonoff-prior-inspired ' +\n      'Kolmogorov-complexity / MDL proxy (W.507). Returns score (higher = better fit), ' +\n      'baseline gzip bytes for the task, agent-conditioned gzip bytes, and their ratio. ' +\n      'Use to rank candidate agents for task routing, or to detect when no agent on the ' +\n      'team has dictionary overlap with a new task (score ≈ 0 across all candidates = ' +\n      'capability gap).',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        taskDescription: {\n          type: 'string',\n          description: 'The task description to score (e.g. board task title + body).',\n        },\n        agentContext: {\n          type: 'object',\n          description:\n            \"The candidate agent's context — done-log entries and optional capability tags.\",\n          properties: {\n            recentDoneEntries: {\n              type: 'array',\n              items: { type: 'string' },\n              description:\n                'Recent done-log entries for this agent (most recent first works fine; order is not load-bearing).',\n            },\n            capabilityTags: {\n              type: 'array',\n              items: { type: 'string' },\n              description: 'Optional capability tags (e.g. [\"security-audit\", \"lean4\"]).',\n            },\n          },\n          required: ['recentDoneEntries'],\n        },\n      },\n      required: ['taskDescription', 'agentContext'],\n    },\n  },\n];\n\nexport async function handleKolmogorovTaskScoreTool(\n  name: string,\n  args: Record<string, unknown>\n): Promise<KolmogorovScoreResult | null> {\n  if (name !== 'holo_task_kolmogorov_score') return null;\n\n  const taskDescription = typeof args.taskDescription === 'string' ? args.taskDescription : '';\n  const rawContext = isRecord(args.agentContext) ? args.agentContext : {};\n  const recentDoneEntries = Array.isArray(rawContext.recentDoneEntries)\n    ? (rawContext.recentDoneEntries as unknown[]).filter((s): s is string => typeof s === 'string')\n    : [];\n  const capabilityTags = Array.isArray(rawContext.capabilityTags)\n    ? (rawContext.capabilityTags as unknown[]).filter((s): s is string => typeof s === 'string')\n    : undefined;\n\n  return holoTaskKolmogorovScore({\n    taskDescription,\n    agentContext: { recentDoneEntries, capabilityTags },\n  });\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n  return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n","/**\n * MCP Critic Handler\n *\n * LLM-backed critique engine for the holo_critic MCP tool.\n * Wraps the /critic skill protocol into a structured, programmatic interface.\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport {\n  createProviderManager,\n  type LLMProviderName,\n  type MessageRole,\n} from '@holoscript/llm-provider';\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport interface CriticInput {\n  target: string;\n  content?: string;\n  mode?: 'code' | 'pitch' | 'full';\n  context?: string;\n}\n\nexport interface CriticFinding {\n  category: 'Critical' | 'Serious' | 'Annoying' | 'Nitpick';\n  issue: string;\n  why: string;\n  fix: string;\n  evidence?: string;\n}\n\nexport interface CriticPitchLine {\n  lineOrClaim: string;\n  challenge: string;\n  betterVersion: string;\n}\n\nexport interface CriticPitchClaim {\n  claim: string;\n  whatsMissing: string;\n  howToProve: string;\n}\n\nexport interface CriticResult {\n  verdict: 'NOT_READY' | 'FRAGILE' | 'ADEQUATE' | 'WOULD_LAND';\n  summary: string;\n  findings: CriticFinding[];\n  pitchExtras?: {\n    linesThatWillGetChallenged?: CriticPitchLine[];\n    claimsWithoutEvidence?: CriticPitchClaim[];\n    skepticView?: string;\n    whatWouldMakeItUndeniable?: string[];\n  };\n  meta: {\n    target: string;\n    mode: string;\n    provider?: LLMProviderName;\n    attemptedProviders: LLMProviderName[];\n    rawOutput?: string;\n  };\n}\n\n// ---------------------------------------------------------------------------\n// Constants\n// ---------------------------------------------------------------------------\n\nconst BUILTIN_TARGETS = new Set([\n  'file',\n  'pitch',\n  'demo',\n  'architecture',\n  'tests',\n  'docs',\n  'studio',\n  'absorb',\n  'holomesh',\n  'infra',\n  'full',\n  'code',\n]);\n\nconst AI_PROVIDER_PRIORITY: readonly LLMProviderName[] = [\n  'anthropic',\n  'openai',\n  'gemini',\n  'local-llm',\n  'bitnet',\n  'mock',\n];\n\nfunction getAIProviderOrder(registeredProviders: LLMProviderName[]): LLMProviderName[] {\n  const forcedProvider = process.env.HOLOSCRIPT_MCP_AI_PROVIDER as LLMProviderName | undefined;\n\n  if (forcedProvider && registeredProviders.includes(forcedProvider)) {\n    return [\n      forcedProvider,\n      ...AI_PROVIDER_PRIORITY.filter(\n        (provider) => provider !== forcedProvider && registeredProviders.includes(provider)\n      ),\n    ];\n  }\n\n  return AI_PROVIDER_PRIORITY.filter((provider) => registeredProviders.includes(provider));\n}\n\n// ---------------------------------------------------------------------------\n// System Prompt — distilled from ~/.claude/skills/critic/SKILL.md\n// ---------------------------------------------------------------------------\n\nconst CRITIC_SYSTEM_PROMPT = `You are the harshest, most honest critic in the HoloScript ecosystem.\nYour job is to find everything that's not good enough and document exactly how it could be better.\nYou are not mean — you are precise. You don't insult — you diagnose.\nYou never soften the truth and you never offer encouragement.\n\nRULES:\n1. Never say \"good job\", \"this is solid\", or \"nice work\". If something is adequate, skip it. Only speak when something falls short.\n2. Every criticism must have three parts:\n   - What's wrong — specific, with evidence (file path, line number, metric, or quote)\n   - Why it matters — who gets hurt, what breaks, what impression it gives\n   - What good looks like — a concrete, actionable description of the fix. Not vague. Not \"improve this\". Exact.\n3. Grade on an absolute scale, not relative. The question is: would this survive contact with a paying customer, a skeptical investor, a tenured professor, or a competing product?\n4. Assume the audience is hostile. Every claim will be challenged. Every demo will fail at the worst moment. Every doc will be read by someone looking for reasons to say no.\n5. Prioritize by embarrassment risk. What would make the founder look foolish on stage? What would make an investor close their laptop? What would make a professor say \"this isn't ready\"? Those come first.\n\nOUTPUT FORMAT — You MUST return ONLY valid JSON. No markdown, no prose outside the JSON.\n\n{\n  \"verdict\": \"NOT_READY\" | \"FRAGILE\" | \"ADEQUATE\" | \"WOULD_LAND\",\n  \"summary\": \"One brutally honest sentence summarizing the overall assessment.\",\n  \"findings\": [\n    {\n      \"category\": \"Critical\" | \"Serious\" | \"Annoying\" | \"Nitpick\",\n      \"issue\": \"What's wrong — specific with evidence\",\n      \"why\": \"Why it matters\",\n      \"fix\": \"What good looks like — concrete and actionable\",\n      \"evidence\": \"Optional: file:line or direct quote\"\n    }\n  ]\n}\n\nFor pitch mode, ALSO include these keys at the top level (sibling to verdict/summary/findings):\n  \"linesThatWillGetChallenged\": [ { \"lineOrClaim\": \"...\", \"challenge\": \"...\", \"betterVersion\": \"...\" } ],\n  \"claimsWithoutEvidence\": [ { \"claim\": \"...\", \"whatsMissing\": \"...\", \"howToProve\": \"...\" } ],\n  \"skepticView\": \"3-5 sentences from the perspective of the most skeptical person in the room\",\n  \"whatWouldMakeItUndeniable\": [ \"specific, actionable list items\" ]\n\nVERDICT DEFINITIONS:\n- NOT_READY: Would embarrass you if shown to the target audience today.\n- FRAGILE: Would survive a polite review but collapses under scrutiny.\n- ADEQUATE: Meets the bar. Not exciting, not embarrassing.\n- WOULD_LAND: A skeptical investor would write a check, a professor would stake their curriculum on it, a customer would pay.\n\nIf there are no issues in a category, omit that category entirely rather than including empty arrays.`;\n\n// ---------------------------------------------------------------------------\n// Handler\n// ---------------------------------------------------------------------------\n\nexport async function handleCriticTool(args: Record<string, unknown>): Promise<CriticResult> {\n  const target = (args.target as string) ?? '';\n  let content = (args.content as string) ?? '';\n  const mode = ((args.mode as string) ?? 'code') as 'code' | 'pitch' | 'full';\n  const context = (args.context as string) ?? '';\n\n  // If target looks like a file path and is not a builtin mode, read the file\n  let resolvedTarget = target;\n  if (!BUILTIN_TARGETS.has(target.toLowerCase())) {\n    const maybePath = path.resolve(target);\n    if (fs.existsSync(maybePath)) {\n      try {\n        content = fs.readFileSync(maybePath, 'utf-8');\n        resolvedTarget = `file:${target}`;\n      } catch {\n        // leave content as-is if unreadable\n      }\n    }\n  }\n\n  if (!content && !BUILTIN_TARGETS.has(target.toLowerCase())) {\n    throw new Error(\n      `holo_critic: target \"${target}\" is not a builtin mode and no readable file was found, and no content was provided.`\n    );\n  }\n\n  // Build user prompt\n  const userPrompt = buildCriticPrompt(resolvedTarget, content, mode, context);\n\n  // Call LLM\n  const llmResult = await tryCompleteWithAI({\n    messages: [\n      { role: 'system', content: CRITIC_SYSTEM_PROMPT },\n      { role: 'user', content: userPrompt },\n    ],\n    maxTokens: 4096,\n    temperature: 0.3,\n  });\n\n  // Parse structured output\n  const parsed = parseCriticOutput(llmResult.content);\n\n  return {\n    verdict: parsed.verdict,\n    summary: parsed.summary,\n    findings: parsed.findings,\n    pitchExtras: parsed.pitchExtras,\n    meta: {\n      target: resolvedTarget,\n      mode,\n      provider: llmResult.provider,\n      attemptedProviders: llmResult.attemptedProviders,\n      rawOutput: llmResult.content,\n    },\n  };\n}\n\n// ---------------------------------------------------------------------------\n// Prompt builder\n// ---------------------------------------------------------------------------\n\nfunction buildCriticPrompt(\n  target: string,\n  content: string,\n  mode: 'code' | 'pitch' | 'full',\n  context: string\n): string {\n  const parts: string[] = [];\n\n  parts.push(`CRITIQUE TARGET: ${target}`);\n\n  if (context) {\n    parts.push(`CONTEXT: ${context}`);\n  }\n\n  // Determine output mode instruction\n  if (mode === 'pitch') {\n    parts.push('MODE: pitch');\n    parts.push(\n      'Return the pitch critique format: VERDICT + findings + linesThatWillGetChallenged + claimsWithoutEvidence + skepticView + whatWouldMakeItUndeniable.'\n    );\n  } else if (mode === 'full') {\n    parts.push('MODE: full');\n    parts.push('Return the union of code critique AND pitch critique formats. Be exhaustive.');\n  } else {\n    parts.push('MODE: code');\n    parts.push('Return the code/architecture critique format: VERDICT + findings only.');\n  }\n\n  if (content) {\n    parts.push('');\n    parts.push('--- CONTENT TO CRITIQUE ---');\n    parts.push(content);\n    parts.push('--- END CONTENT ---');\n  } else {\n    parts.push('');\n    parts.push(\n      `No specific content provided. Critique the general state of \"${target}\" in the HoloScript ecosystem based on your knowledge.`\n    );\n  }\n\n  parts.push('');\n  parts.push('Remember: return ONLY valid JSON matching the schema in your system prompt.');\n\n  return parts.join('\\n');\n}\n\n// ---------------------------------------------------------------------------\n// LLM completion with fallback\n// ---------------------------------------------------------------------------\n\nasync function tryCompleteWithAI(request: {\n  messages: Array<{ role: MessageRole; content: string }>;\n  maxTokens: number;\n  temperature: number;\n}): Promise<{\n  content: string;\n  provider: LLMProviderName | undefined;\n  attemptedProviders: LLMProviderName[];\n}> {\n  let manager;\n\n  try {\n    manager = createProviderManager();\n  } catch {\n    return {\n      content: JSON.stringify({\n        verdict: 'NOT_READY',\n        summary:\n          'No LLM providers are configured. Set ANTHROPIC_API_KEY, OPENAI_API_KEY, or another supported provider.',\n        findings: [\n          {\n            category: 'Critical',\n            issue: 'holo_critic requires a configured LLM provider.',\n            why: 'The critic tool is LLM-backed and cannot run without an API key.',\n            fix: 'Set ANTHROPIC_API_KEY or OPENAI_API_KEY in the environment, or start a local LLM server.',\n          },\n        ],\n      }),\n      provider: undefined,\n      attemptedProviders: [],\n    };\n  }\n\n  const attemptedProviders: LLMProviderName[] = [];\n\n  for (const providerName of getAIProviderOrder(manager.getRegisteredProviders())) {\n    const provider = manager.getProvider(providerName);\n    if (!provider) continue;\n\n    attemptedProviders.push(providerName);\n\n    try {\n      const result = await provider.complete(request);\n      return {\n        content: result.content,\n        provider: providerName,\n        attemptedProviders: [...attemptedProviders],\n      };\n    } catch {\n      // Fall through to next provider\n    }\n  }\n\n  return {\n    content: JSON.stringify({\n      verdict: 'NOT_READY',\n      summary: `All LLM providers failed after trying ${attemptedProviders.join(', ')}.`,\n      findings: [\n        {\n          category: 'Critical',\n          issue: 'holo_critic could not reach any LLM provider.',\n          why: 'Every registered provider returned an error or is misconfigured.',\n          fix: 'Check API keys, network connectivity, and provider status.',\n        },\n      ],\n    }),\n    provider: undefined,\n    attemptedProviders,\n  };\n}\n\n// ---------------------------------------------------------------------------\n// Output parser\n// ---------------------------------------------------------------------------\n\nfunction parseCriticOutput(raw: string): {\n  verdict: CriticResult['verdict'];\n  summary: string;\n  findings: CriticFinding[];\n  pitchExtras?: CriticResult['pitchExtras'];\n} {\n  const fallback: CriticResult['verdict'] = 'NOT_READY';\n\n  // Try strict JSON extraction\n  let jsonText = raw.trim();\n\n  // Strip markdown fences if present\n  const fenced = jsonText.match(/```(?:json)?\\s*\\n?([\\s\\S]*?)```/);\n  if (fenced) {\n    jsonText = fenced[1].trim();\n  }\n\n  try {\n    const parsed = JSON.parse(jsonText);\n\n    const verdict = normalizeVerdict(parsed.verdict);\n    const summary = typeof parsed.summary === 'string' ? parsed.summary : 'No summary provided.';\n    const findings = Array.isArray(parsed.findings)\n      ? (parsed.findings.map(normalizeFinding).filter(Boolean) as CriticFinding[])\n      : [];\n\n    const pitchExtras: CriticResult['pitchExtras'] = {};\n\n    if (Array.isArray(parsed.linesThatWillGetChallenged)) {\n      pitchExtras.linesThatWillGetChallenged = parsed.linesThatWillGetChallenged\n        .map((l: any) => ({\n          lineOrClaim: String(l.lineOrClaim ?? l.line ?? ''),\n          challenge: String(l.challenge ?? ''),\n          betterVersion: String(l.betterVersion ?? l.better ?? ''),\n        }))\n        .filter((l: any) => l.lineOrClaim);\n    }\n\n    if (Array.isArray(parsed.claimsWithoutEvidence)) {\n      pitchExtras.claimsWithoutEvidence = parsed.claimsWithoutEvidence\n        .map((c: any) => ({\n          claim: String(c.claim ?? ''),\n          whatsMissing: String(c.whatsMissing ?? c.whats_missing ?? ''),\n          howToProve: String(c.howToProve ?? c.how_to_prove ?? ''),\n        }))\n        .filter((c: any) => c.claim);\n    }\n\n    if (typeof parsed.skepticView === 'string' && parsed.skepticView.trim()) {\n      pitchExtras.skepticView = parsed.skepticView.trim();\n    }\n\n    if (Array.isArray(parsed.whatWouldMakeItUndeniable)) {\n      pitchExtras.whatWouldMakeItUndeniable = parsed.whatWouldMakeItUndeniable\n        .map(String)\n        .filter(Boolean);\n    }\n\n    return {\n      verdict,\n      summary,\n      findings,\n      ...(Object.keys(pitchExtras).length > 0 ? { pitchExtras } : {}),\n    };\n  } catch {\n    // JSON parse failed — attempt heuristic extraction\n    return heuristicParse(raw, fallback);\n  }\n}\n\nfunction normalizeVerdict(v: unknown): CriticResult['verdict'] {\n  const s = String(v).toUpperCase().replace(/\\s/g, '_');\n  if (s.includes('NOT_READY') || s === 'NOTREADY') return 'NOT_READY';\n  if (s === 'FRAGILE') return 'FRAGILE';\n  if (s === 'ADEQUATE') return 'ADEQUATE';\n  if (s === 'WOULD_LAND' || s === 'WOULDLAND') return 'WOULD_LAND';\n  return 'NOT_READY';\n}\n\nfunction normalizeFinding(f: unknown): CriticFinding | null {\n  if (!f || typeof f !== 'object') return null;\n  const obj = f as Record<string, unknown>;\n\n  const category = normalizeCategory(obj.category);\n  const issue = String(obj.issue ?? obj.Issue ?? '');\n  const why = String(obj.why ?? obj.Why ?? '');\n  const fix = String(obj.fix ?? obj.Fix ?? '');\n  const evidence = String(obj.evidence ?? obj.Evidence ?? '');\n\n  if (!issue) return null;\n\n  return {\n    category,\n    issue,\n    why,\n    fix,\n    ...(evidence ? { evidence } : {}),\n  };\n}\n\nfunction normalizeCategory(c: unknown): CriticFinding['category'] {\n  const s = String(c).toLowerCase();\n  if (s.includes('critical')) return 'Critical';\n  if (s.includes('serious')) return 'Serious';\n  if (s.includes('annoy')) return 'Annoying';\n  if (s.includes('nit')) return 'Nitpick';\n  return 'Annoying';\n}\n\nfunction heuristicParse(\n  raw: string,\n  fallbackVerdict: CriticResult['verdict']\n): {\n  verdict: CriticResult['verdict'];\n  summary: string;\n  findings: CriticFinding[];\n} {\n  const findings: CriticFinding[] = [];\n\n  // Extract verdict from markdown header\n  const verdictMatch = raw.match(\n    /VERDICT[:\\s]+(NOT READY|FRAGILE|ADEQUATE|WOULD LAND|WOULDN'T SHIP)/i\n  );\n  const verdict = verdictMatch ? normalizeVerdict(verdictMatch[1]) : fallbackVerdict;\n\n  // Extract findings from markdown sections\n  const sections = [\n    {\n      pattern:\n        /###?\\s*Critical[\\s\\S]*?(?=###?\\s*(Serious|Annoying|Nitpick|Lines that|Claims|What a skeptic|What would|$))/i,\n      category: 'Critical' as const,\n    },\n    {\n      pattern:\n        /###?\\s*Serious[\\s\\S]*?(?=###?\\s*(Critical|Annoying|Nitpick|Lines that|Claims|What a skeptic|What would|$))/i,\n      category: 'Serious' as const,\n    },\n    {\n      pattern:\n        /###?\\s*Annoying[\\s\\S]*?(?=###?\\s*(Critical|Serious|Nitpick|Lines that|Claims|What a skeptic|What would|$))/i,\n      category: 'Annoying' as const,\n    },\n    {\n      pattern:\n        /###?\\s*Nitpick[\\s\\S]*?(?=###?\\s*(Critical|Serious|Annoying|Lines that|Claims|What a skeptic|What would|$))/i,\n      category: 'Nitpick' as const,\n    },\n  ];\n\n  for (const section of sections) {\n    const match = raw.match(section.pattern);\n    if (match) {\n      const lines = match[0].split('\\n');\n      for (const line of lines) {\n        const issueMatch = line.match(/^\\s*\\d+\\.\\s*\\*\\*([^*]+)\\*\\*/);\n        if (issueMatch) {\n          findings.push({\n            category: section.category,\n            issue: issueMatch[1].trim(),\n            why: 'Extracted from heuristic parse — see raw output for full context.',\n            fix: 'See raw output for full context.',\n          });\n        }\n      }\n    }\n  }\n\n  // Summary\n  const summaryMatch = raw.match(/##?\\s*Summary[\\s\\S]*?(?=\\n##?\\s|$)/i);\n  const summary = summaryMatch\n    ? summaryMatch[0].replace(/##?\\s*Summary\\s*/i, '').trim()\n    : 'Heuristic parse — see raw output for full critique.';\n\n  return { verdict, summary, findings };\n}\n","/**\n * Founder Decision Proxy Handler\n *\n * LLM-backed founder decision engine for the holo_founder MCP tool.\n * Wraps the /founder skill protocol into a structured, programmatic interface.\n *\n * Authority order (top-down; first match wins):\n * 1. GOLD vault (D:/GOLD/)\n * 2. This handler (embedded defaults + vision pillars)\n * 3. NORTH_STAR.md (decision trees)\n * 4. CLAUDE.md (harness rules)\n * 5. Knowledge store (mcp-orchestrator.../knowledge/query)\n * 6. MEMORY.md (live dashboard — decays)\n * 7. Everything else (judgment call)\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport * as os from 'os';\nimport { resolveSecretWithLease, VaultLeaseError } from './holomesh/identity/vault-lease-registry';\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport interface FounderRuling {\n  layer:\n    | 'Diamond'\n    | 'Platinum'\n    | 'GOLD'\n    | 'NORTH_STAR'\n    | 'CLAUDE.md'\n    | 'knowledge'\n    | 'founder-default'\n    | 'judgment';\n  ruling: string;\n  citation: string;\n  action: string;\n  gap?: string;\n  dynamic?: string;\n}\n\nexport interface FounderResult {\n  rulings: FounderRuling[];\n  meta: {\n    mode: string;\n    explain: boolean;\n    questions: string[];\n    goldAvailable: boolean;\n    northStarAvailable: boolean;\n    claudeMdAvailable: boolean;\n    knowledgeStoreHit: boolean;\n  };\n}\n\n// ---------------------------------------------------------------------------\n// Phase-3 wrapped knowledge-store key (same pattern as oracle-handler.ts)\n// ---------------------------------------------------------------------------\n\nfunction readKnowledgeApiKey(): string | undefined {\n  const tryRead = (ref: 'env:HOLOSCRIPT_API_KEY' | 'env:ABSORB_API_KEY'): string => {\n    try {\n      return resolveSecretWithLease(ref) ?? '';\n    } catch (err) {\n      if (err instanceof VaultLeaseError) return '';\n      throw err;\n    }\n  };\n  return tryRead('env:HOLOSCRIPT_API_KEY') || tryRead('env:ABSORB_API_KEY') || undefined;\n}\n\n// ---------------------------------------------------------------------------\n// Embedded authority — Known Founder Defaults\n// ---------------------------------------------------------------------------\n\ninterface DefaultEntry {\n  keywords: string[];\n  layer: FounderRuling['layer'];\n  ruling: string;\n  citation: string;\n  action: string;\n}\n\nconst KNOWN_DEFAULTS: DefaultEntry[] = [\n  {\n    keywords: ['repo', 'which repo', 'go in'],\n    layer: 'founder-default',\n    ruling: 'Default repo is HoloScript unless explicitly told otherwise.',\n    citation: 'founder-defaults table — \"Which repo does this go in?\"',\n    action: 'Place the change in the HoloScript repo.',\n  },\n  {\n    keywords: ['new package', 'existing package', 'package'],\n    layer: 'founder-default',\n    ruling: 'Existing — add to the closest relevant package.',\n    citation: 'founder-defaults table — \"New package or existing?\"',\n    action: 'Add to the closest relevant existing package.',\n  },\n  {\n    keywords: ['mcp or cli', 'mcp vs cli', 'cli or mcp'],\n    layer: 'founder-default',\n    ruling: 'MCP if reachable; CLI only as fallback.',\n    citation: 'founder-defaults table — \"MCP or CLI?\"',\n    action: \"Use the MCP tool. If it 502s, investigate; don't silently route around it.\",\n  },\n  {\n    keywords: ['commit now', 'commit', 'wait'],\n    layer: 'founder-default',\n    ruling: 'Commit if you finished a coherent unit and tests pass.',\n    citation: 'founder-defaults table — \"Commit now or wait?\"',\n    action: \"Commit to main (local agents don't branch).\",\n  },\n  {\n    keywords: ['git add', 'stage', '-A', 'git add .'],\n    layer: 'founder-default',\n    ruling: 'Explicit paths always. NEVER git add -A or git add .',\n    citation: 'founder-defaults table — \"git add -A or explicit?\" + F.001',\n    action: 'Stage files explicitly: git add path/to/file.ts',\n  },\n  {\n    keywords: ['mock db', 'mock database', 'mock in tests'],\n    layer: 'founder-default',\n    ruling: 'No — real DB. Mock-vs-prod divergence masks migrations.',\n    citation: 'founder-defaults table — \"Mock DB in tests?\"',\n    action: 'Use the real database in tests.',\n  },\n  {\n    keywords: [\n      'hardcode count',\n      'hardcode stats',\n      'tool count',\n      'compiler count',\n      'trait count',\n      'test count',\n    ],\n    layer: 'founder-default',\n    ruling: 'No — reference HoloScript/docs/NUMBERS.md or the verification command.',\n    citation: 'founder-defaults table — \"Hardcode a count?\" + zero-hardcoded-stats rule',\n    action: 'Reference NUMBERS.md or run the verification command.',\n  },\n  {\n    keywords: ['any in typescript', 'as any', '@ts-ignore'],\n    layer: 'founder-default',\n    ruling: 'No — use unknown. any has caused 3+ production bugs.',\n    citation: 'founder-defaults table — \"any in TypeScript?\" + global CLAUDE.md',\n    action: \"Replace any with unknown. Fix the type, don't mask it.\",\n  },\n  {\n    keywords: ['plan or ask', 'ask the founder', 'ask joseph', 'should i ask'],\n    layer: 'founder-default',\n    ruling: \"Plan, then tell — don't stall asking.\",\n    citation: 'founder-defaults table — \"Plan or ask?\"',\n    action: 'Decide, execute, announce in the handoff.',\n  },\n  {\n    keywords: ['branch', 'commit to main', 'pull request', 'pr'],\n    layer: 'founder-default',\n    ruling: 'Commit to main — all local agents, no PRs, pre-commit hook is the quality gate.',\n    citation: 'founder-defaults table — \"Branch or commit to main?\"',\n    action: 'Commit directly to main.',\n  },\n  {\n    keywords: ['test failing', 'failing test', 'skip test', '.skip', '.only'],\n    layer: 'founder-default',\n    ruling: 'Fix if yours, investigate if pre-existing.',\n    citation: 'founder-defaults table — \"Test failing and not mine?\"',\n    action:\n      'Investigate the failure. Do not skip or .only; file complex pre-existing failures as tasks with evidence.',\n  },\n  {\n    keywords: ['local service', 'production', 'localhost', 'dev service'],\n    layer: 'founder-default',\n    ruling: 'Production — never localhost, never mock, never in-memory fake.',\n    citation: 'founder-defaults table — \"Local service vs production?\" + production-only rule',\n    action: 'Hit the production endpoint. If it is down, fix it.',\n  },\n  {\n    keywords: ['domain code in core', 'packages/core/', 'domain vocabulary in core'],\n    layer: 'founder-default',\n    ruling: 'No — plugins are data, not code. Zero domain vocabulary in core.',\n    citation:\n      'founder-defaults table — \"Domain-specific code in packages/core/?\" + S.MCP architecture rule',\n    action: 'Place domain code in packages/plugins/. Core learns shapes, not domains.',\n  },\n  {\n    keywords: ['facade', 'facade my own code', 'shim'],\n    layer: 'founder-default',\n    ruling: 'No — never facade your own code.',\n    citation: 'founder-defaults table — \"Facade my own code?\" + F.003',\n    action: 'Build the real thing. No facades.',\n  },\n  {\n    keywords: ['regex parse', 'regex hs', 'regex holoscript', 'regex .hs'],\n    layer: 'founder-default',\n    ruling: 'No — use @holoscript/core. Never regex-parse .hs/.hsplus/.holo.',\n    citation: 'founder-defaults table — \"Regex-parse .hs/.hsplus/.holo?\" + F.014',\n    action: 'Use @holoscript/core parser. No regex outside core.',\n  },\n  {\n    keywords: ['overwrite wallet', 'wallet env', 'rotate wallet'],\n    layer: 'founder-default',\n    ruling: 'Never — wallets are identity; API keys are sessions.',\n    citation: 'founder-defaults table — \"Overwrite wallet env vars?\" + F.002 + W.GOLD.004',\n    action: 'Rotate API keys, never wallets. Wallets = identity.',\n  },\n  {\n    keywords: ['crosspost', 'auto crosspost', 'moltbook auto', 'auto moltbook'],\n    layer: 'founder-default',\n    ruling: 'No — only via /moltbook skill. No auto-crosspost.',\n    citation: 'founder-defaults table — \"Should I crosspost auto to Moltbook?\" + F.005',\n    action: 'Use /moltbook for engagement only. No automation.',\n  },\n  {\n    keywords: [\n      'bandaid',\n      'quick fix',\n      'for now',\n      'temporarily',\n      'good enough to unblock',\n      'until we',\n    ],\n    layer: 'founder-default',\n    ruling: 'Refuse the bandaid. Fix the root cause.',\n    citation: 'founder skill §1 Refuse the bandaid',\n    action: 'Fix the root cause. Bandaids compound and make the next real fix harder.',\n  },\n  {\n    keywords: ['workaround', 'parallel path', 'shadow system', 'reimplement', 'shim in script'],\n    layer: 'founder-default',\n    ruling: 'Refuse the workaround. Extend the skill or fix the system.',\n    citation: 'founder skill §2 Refuse the workaround',\n    action: 'Fix the broken system. Do not build a shadow system around it.',\n  },\n  {\n    keywords: [\n      'demote',\n      'descope',\n      'simpler version for now',\n      'v1 without',\n      'we can add later',\n      'skip for now',\n    ],\n    layer: 'founder-default',\n    ruling: 'Refuse the demote. Name the scope cut explicitly or build the gap.',\n    citation: 'founder skill §3 Refuse the demote',\n    action: 'Either build the gap or explicitly document the named demote with rationale.',\n  },\n  {\n    keywords: ['wait for founder', 'ask joseph', 'blocked on founder', 'should i ask joseph'],\n    layer: 'founder-default',\n    ruling: 'Refuse the wait. Agents own the room. Decide, execute, announce.',\n    citation: 'founder skill §4 Refuse the wait-for-founder + F.027',\n    action: 'Make the decision. Only escalate if irreversible + >$5 + treasury/Tier-2.',\n  },\n];\n\n// ---------------------------------------------------------------------------\n// Vision pillars\n// ---------------------------------------------------------------------------\n\nconst VISION_PILLARS: Record<string, string> = {\n  'simulation-first':\n    \"Digital twin before physical twin. Every feature asks: can it be simulated deterministically, replayed, and V&V'd? If no, it is not done.\",\n  'universal-platform':\n    'Any data -> .holo -> any device. Zero domain vocabulary in core. Plugins are data. Core never learns that \"robotics\" or \"medical\" exist — it learns shapes.',\n  'architecture-beats-alignment':\n    'Security through structure, not through asking AI to be careful. If a safety check depends on a model reading content correctly, the check is doing nothing.',\n  'failure-knowledge-decays-slower': 'Gotchas outlive tips. Prune success first, keep scars.',\n  'algebraic-trust':\n    'SimulationContract + CAEL + x402 unify under Algebraic Trust. Every verification-layer decision must be reducible to it.',\n  'production-is-the-product':\n    'Production is the product, not a later stage. If the only way it works is on your laptop, you have not shipped it.',\n  'iphone-moment-on-quest-3':\n    'The product is validated by Joseph using it daily on Quest 3. Developer-only UX is not a product.',\n  'github-is-source-of-truth':\n    'GitHub is source of truth; servers are projections. Live API = now. Git = the record.',\n  'wallets-are-identity':\n    'Wallets are identity. API keys are sessions. Never overwrite wallets during rotation. HoloMesh keys are disposable; agentId + wallet is durable.',\n};\n\n// ---------------------------------------------------------------------------\n// File reading helpers\n// ---------------------------------------------------------------------------\n\nfunction safeRead(filePath: string, maxBytes = 50000): string | null {\n  try {\n    const stats = fs.statSync(filePath);\n    if (!stats.isFile()) return null;\n    const buf = fs.readFileSync(filePath, 'utf-8');\n    return buf.length > maxBytes ? buf.slice(0, maxBytes) + '\\n...[truncated]' : buf;\n  } catch {\n    return null;\n  }\n}\n\nfunction readGoldIndex(): string | null {\n  const candidates = [\n    'D:/GOLD/INDEX.md',\n    '/mnt/d/GOLD/INDEX.md',\n    path.join(process.env.GOLD_ROOT || '', 'INDEX.md'),\n  ];\n  for (const c of candidates) {\n    if (!c) continue;\n    const content = safeRead(c, 30000);\n    if (content) return content;\n  }\n  return null;\n}\n\nfunction readNorthStar(): string | null {\n  const candidates = [\n    path.join(os.homedir(), '.ai-ecosystem', 'NORTH_STAR.md'),\n  ];\n  for (const c of candidates) {\n    if (!c) continue;\n    const content = safeRead(c, 30000);\n    if (content) return content;\n  }\n  return null;\n}\n\nfunction readClaudeMd(): string | null {\n  const candidates = [\n    path.join(os.homedir(), '.claude', 'CLAUDE.md'),\n  ];\n  for (const c of candidates) {\n    if (!c) continue;\n    const content = safeRead(c, 30000);\n    if (content) return content;\n  }\n  return null;\n}\n\n// ---------------------------------------------------------------------------\n// Knowledge store query\n// ---------------------------------------------------------------------------\n\nasync function queryKnowledgeStore(\n  search: string\n): Promise<Array<{ id?: string; type?: string; content?: string }>> {\n  const apiKey = readKnowledgeApiKey();\n  if (!apiKey) return [];\n\n  try {\n    const url =\n      process.env.MCP_ORCHESTRATOR_PUBLIC_URL ||\n      'https://mcp-orchestrator-production-45f9.up.railway.app';\n    const ctrl = new AbortController();\n    const t = setTimeout(() => ctrl.abort(), 5000);\n    const res = await fetch(`${url}/knowledge/query`, {\n      method: 'POST',\n      headers: { 'Content-Type': 'application/json; charset=utf-8', 'x-mcp-api-key': apiKey },\n      body: JSON.stringify({\n        search,\n        limit: 5,\n        workspace_id: process.env.HOLOMESH_WORKSPACE || 'default',\n      }),\n      signal: ctrl.signal,\n    });\n    clearTimeout(t);\n    if (!res.ok) return [];\n    const data = (await res.json()) as {\n      results?: Array<{ id?: string; type?: string; content?: string }>;\n      entries?: Array<{ id?: string; type?: string; content?: string }>;\n    };\n    return data.results || data.entries || [];\n  } catch {\n    return [];\n  }\n}\n\n// ---------------------------------------------------------------------------\n// Core matching logic\n// ---------------------------------------------------------------------------\n\nfunction matchDefaults(question: string): FounderRuling | null {\n  const q = question.toLowerCase();\n  for (const d of KNOWN_DEFAULTS) {\n    if (d.keywords.some((k) => q.includes(k.toLowerCase()))) {\n      return {\n        layer: d.layer,\n        ruling: d.ruling,\n        citation: d.citation,\n        action: d.action,\n      };\n    }\n  }\n  return null;\n}\n\nfunction matchVisionPillars(question: string): FounderRuling | null {\n  const q = question.toLowerCase();\n  for (const [pillar, description] of Object.entries(VISION_PILLARS)) {\n    const short = pillar.replace(/-/g, ' ');\n    if (q.includes(pillar) || q.includes(short)) {\n      return {\n        layer: 'GOLD',\n        ruling: `Vision pillar: ${pillar}. ${description}`,\n        citation: `founder skill Vision Pillars — ${pillar}`,\n        action: 'Ensure the proposed change aligns with this pillar. If it contradicts, reframe.',\n      };\n    }\n  }\n  return null;\n}\n\nfunction matchGoldIndex(question: string, goldIndex: string | null): FounderRuling | null {\n  if (!goldIndex) return null;\n  const q = question.toLowerCase();\n  // Simple heuristic: look for W.GOLD.XXX or w_gold_XXX patterns in the question\n  const idMatch = q.match(/w\\.gold\\.(\\d+)/i) || q.match(/w_gold_(\\d+)/i);\n  if (idMatch) {\n    const id = idMatch[1];\n    // Search the index for the ID\n    const lines = goldIndex.split('\\n');\n    for (const line of lines) {\n      if (line.includes(id) || line.includes(`w_gold_${id}`) || line.includes(`W.GOLD.${id}`)) {\n        return {\n          layer: 'GOLD',\n          ruling: `GOLD entry referenced: ${line.trim().slice(0, 200)}`,\n          citation: `D:/GOLD/INDEX.md — line matching ${id}`,\n          action: 'Verify the full entry on disk before citing it as authority.',\n          dynamic: `[verify D:/GOLD/INDEX.md and the specific entry file]`,\n        };\n      }\n    }\n  }\n  return null;\n}\n\n// ---------------------------------------------------------------------------\n// Main handler\n// ---------------------------------------------------------------------------\n\nexport async function handleFounderTool(args: Record<string, unknown>): Promise<FounderResult> {\n  const rawQuestion = String(args.question || '');\n  const context = String(args.context || '');\n  const mode = ((args.mode as string) || 'single') as 'single' | 'batch';\n  const explain = args.explain === true;\n\n  const questions =\n    mode === 'batch'\n      ? rawQuestion\n          .split(' // ')\n          .map((s) => s.trim())\n          .filter(Boolean)\n      : [rawQuestion.trim()].filter(Boolean);\n\n  if (questions.length === 0) {\n    throw new Error('holo_founder: question is required (non-empty string).');\n  }\n\n  // Pre-load authority files once per invocation\n  const goldIndex = readGoldIndex();\n  const northStar = readNorthStar();\n  const claudeMd = readClaudeMd();\n\n  const rulings: FounderRuling[] = [];\n  let knowledgeStoreHit = false;\n\n  for (const question of questions) {\n    const q = `${question} ${context}`.trim();\n\n    // 1. Try known defaults (fast path)\n    let ruling = matchDefaults(q);\n\n    // 2. Try vision pillars\n    if (!ruling) {\n      ruling = matchVisionPillars(q);\n    }\n\n    // 3. Try GOLD index\n    if (!ruling) {\n      ruling = matchGoldIndex(q, goldIndex);\n    }\n\n    // 4. Try NORTH_STAR / CLAUDE.md heuristic matches\n    if (!ruling && northStar) {\n      const ns = northStar.toLowerCase();\n      const lowerQ = q.toLowerCase();\n      // Look for decision-tree keys in NORTH_STAR\n      const dtKeys = [\n        'package',\n        'commit',\n        'test',\n        'mcp',\n        'cache',\n        'todo',\n        'version',\n        'doc',\n        'cost',\n        'conflict',\n        'repo',\n        'embedding',\n        'git',\n      ];\n      for (const key of dtKeys) {\n        if (lowerQ.includes(key) && ns.includes(key)) {\n          // Extract a line from NORTH_STAR that mentions the key\n          const lines = northStar.split('\\n');\n          const matchLine = lines.find((l) => l.toLowerCase().includes(key) && l.length > 10);\n          if (matchLine) {\n            ruling = {\n              layer: 'NORTH_STAR',\n              ruling: `NORTH_STAR decision tree match for \"${key}\": ${matchLine.trim().slice(0, 200)}`,\n              citation: 'NORTH_STAR.md decision tree',\n              action: 'Apply the decision tree match. If ambiguous, make the conservative choice.',\n            };\n            break;\n          }\n        }\n      }\n    }\n\n    // 5. Knowledge store fallback (gated by content-overlap relevance check —\n    //    the store returns top-N by its own ranker, which can surface unrelated\n    //    entries for novel questions. Require at least one query content-word\n    //    to appear in the top entry's content before treating it as precedent;\n    //    otherwise fall through to the judgment layer.)\n    if (!ruling) {\n      const knowledge = await queryKnowledgeStore(q);\n      if (knowledge.length > 0) {\n        const top = knowledge[0];\n        const topContent = String(top.content || '').toLowerCase();\n        // Content words: non-stopword tokens of length >= 5 from the query.\n        const STOPWORDS = new Set([\n          'should',\n          'could',\n          'would',\n          'about',\n          'after',\n          'before',\n          'between',\n          'which',\n          'where',\n          'there',\n          'their',\n          'these',\n          'those',\n          'while',\n          'because',\n          'through',\n          'against',\n          'across',\n          'around',\n          'under',\n          'within',\n          'without',\n          'every',\n          'other',\n          'another',\n          'something',\n        ]);\n        const contentWords = q\n          .toLowerCase()\n          .split(/[^a-z0-9]+/)\n          .filter((w) => w.length >= 5 && !STOPWORDS.has(w));\n        const hasOverlap = contentWords.some((w) => topContent.includes(w));\n        if (hasOverlap) {\n          knowledgeStoreHit = true;\n          ruling = {\n            layer: 'knowledge',\n            ruling: `Knowledge store returned ${knowledge.length} entr${knowledge.length === 1 ? 'y' : 'ies'}. Top: ${String(top.content || '').slice(0, 200)}`,\n            citation: `knowledge store — ${top.id || top.type || 'unknown'}`,\n            action:\n              'Use the knowledge store entry as precedent. If it conflicts with GOLD, GOLD wins.',\n          };\n        }\n        // else: top entry has zero keyword overlap with the query — store\n        // returned a low-relevance match; fall through to judgment.\n      }\n    }\n\n    // 6. Judgment fallback\n    if (!ruling) {\n      ruling = {\n        layer: 'judgment',\n        ruling:\n          'No precedent found in authority layers. Make the conservative choice (easier to undo) and document the decision.',\n        citation: 'founder skill §Escape hatch — judgment call',\n        action: 'Decide, execute, and document the rationale in the handoff.',\n      };\n    }\n\n    // If explain mode, enrich with file-availability signals\n    if (explain) {\n      ruling.dynamic = `[gold=${goldIndex ? 'available' : 'unavailable'} northStar=${northStar ? 'available' : 'unavailable'} claudeMd=${claudeMd ? 'available' : 'unavailable'} knowledge=${knowledgeStoreHit ? 'hit' : 'miss'}]`;\n    }\n\n    rulings.push(ruling);\n  }\n\n  return {\n    rulings,\n    meta: {\n      mode,\n      explain,\n      questions,\n      goldAvailable: goldIndex !== null,\n      northStarAvailable: northStar !== null,\n      claudeMdAvailable: claudeMd !== null,\n      knowledgeStoreHit,\n    },\n  };\n}\n","/**\n * DaemonEmergenceStore — durable, append-only persistence for the daimōn\n * EMERGENCE CORPUS (D.053 / P.007).\n *\n * WHY THIS EXISTS\n * ───────────────\n * daemon-lifecycle-tools.ts accumulates a person's pre-emergence knowing in\n * `soulObservations = new Map()` and the emerged daimōn record in\n * `daemonStore = new Map()`. Both are in-memory: every ContextDelta the field\n * learns EVAPORATES on process restart. That is the structural reason \"no real\n * training data accrues\" for the native-model program — the emergence corpus is\n * the live graded-trace source, and it was never written to disk.\n *\n * This module is a TRANSPARENT persistence layer. It changes NOTHING about the\n * emergence semantics, thresholds, richness math, or composition logic (P.007 is\n * founder-ratified). It only:\n *   1. write-through: every soul observation / emergence event the in-memory Map\n *      already records is ALSO appended to a durable store, and\n *   2. hydrate: on startup the in-memory Maps are re-seeded from the store, and\n *   3. export: a normalized JSONL dump the corpus builder (harvest_real.py)\n *      can consume.\n *\n * MECHANISM (why append-only JSONL, mirroring state.ts CAEL audit)\n * ────────────────────────────────────────────────────────────────\n * The native-model corpus has to accrue on the LOCAL machine, where there is no\n * DATABASE_URL. The CAEL-audit store (state.ts §persistCaelAuditRecord /\n * loadCaelAuditFromDisk) already proves this exact pattern works for graded-trace\n * accrual without Postgres: append-only JSONL under <HOLOMESH_DATA_DIR>, hydrate\n * on boot. A corpus is naturally append-only (ever-growing), and harvest_real.py\n * already reads JSONL. When DATABASE_URL IS present (Railway multi-instance), we\n * also fire-and-forget into Postgres JSONB so cross-instance reads converge —\n * additive, never the source of truth for the local trainer.\n *\n * RECORD GRAIN\n * ────────────\n * One JSONL line per OBSERVED ContextDelta (the unit the emergence engine counts).\n * That single grain rehydrates BOTH Maps deterministically:\n *   - soulObservations[ownerId] is the replay of all `observation` events for a\n *     soul that has NOT yet emerged, and\n *   - the emerged `daemonStore[daemonId]` is restored from the `emergence` event\n *     (its channel re-seeded by replaying the observation events that preceded it,\n *     exactly as composeDaemonFromContext does live).\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport * as os from 'os';\nimport {\n  createRailwayPostgresPoolOptions,\n  type RailwayPostgresPoolOptions,\n} from './postgres-pool-options';\n\n// ── Data dir (same root the rest of mcp-server persists under) ────────────────\n//\n// Matches holomesh/state.ts HOLOMESH_DATA_DIR so all durable state lives in one\n// place. We import the env var directly rather than the symbol to avoid a load\n// cycle with the holomesh barrel.\n\nconst DATA_ROOT =\n  process.env.HOLOMESH_DATA_DIR ||\n  path.join(process.env.HOLOSCRIPT_CACHE_DIR || path.join(os.homedir(), '.holoscript'), 'holomesh');\n\nconst EMERGENCE_DIR = path.join(DATA_ROOT, 'emergence');\nconst CORPUS_PATH = path.join(EMERGENCE_DIR, 'soul-observations.jsonl');\n\n// ── Durable record shapes ─────────────────────────────────────────────────────\n//\n// These mirror the in-memory shapes in daemon-lifecycle-tools.ts but are\n// serialization-safe (no Set, no Map — plain JSON). They are an internal,\n// loss-free encoding of what the Maps already hold; they are NOT the export\n// format (see exportCorpusJsonl for the normalized training shape).\n\n/** A serialization-safe ContextDelta echo (the durable memory artifact). */\nexport interface PersistedContextDelta {\n  newIntentSignals: unknown[];\n  updatedPreferences: Record<string, unknown>;\n  newReceiptRefs: string[];\n  capabilityUpdates: Array<{ capability: string; available: boolean }>;\n  careSignalHistory: string[];\n  significanceScore: number;\n}\n\n/**\n * One durable line in the emergence corpus. `kind` distinguishes a pre-emergence\n * soul observation from the moment a daimōn manifested — both are needed to\n * replay the Maps exactly.\n */\nexport type EmergenceRecord =\n  | {\n      kind: 'observation';\n      /** The soul (HoloMesh agentId / workspaceId). */\n      ownerId: string;\n      /** The delta that was observed against the soul's latent model. */\n      delta: PersistedContextDelta;\n      /** Whether the delta was routed to a soul accumulator or a live daemon channel. */\n      routedTo: 'soul-accumulator' | 'daemon-channel';\n      /** ISO-8601 server stamp of the observation. */\n      observedAt: string;\n    }\n  | {\n      kind: 'emergence';\n      ownerId: string;\n      /** The deterministic daimōn id (emergentDaemonId(ownerId)). */\n      daemonId: string;\n      /** Display name the daimōn manifested with. */\n      displayName: string;\n      /** ISO-8601 server stamp of manifestation. */\n      emergedAt: string;\n    };\n\n// ── Optional Postgres write-through (Railway multi-instance) ──────────────────\n//\n// Mirrors player-store.ts: when DATABASE_URL is present we ALSO push to a JSONB\n// table. JSONL on disk remains the source of truth for the local trainer; this\n// only helps cross-instance reads converge. Lazy + fire-and-forget so a DB hiccup\n// never blocks (or changes) the emergence path.\n\ninterface PgLike {\n  query: (sql: string, params?: unknown[]) => Promise<{ rows: Array<{ data: EmergenceRecord }> }>;\n}\n\nexport type DaemonEmergencePostgresPoolOptions = RailwayPostgresPoolOptions;\n\nexport function createDaemonEmergencePostgresPoolOptions(\n  databaseUrl: string\n): DaemonEmergencePostgresPoolOptions {\n  return createRailwayPostgresPoolOptions(databaseUrl);\n}\n\nconst EMERGENCE_SCHEMA_SQL = `\nCREATE TABLE IF NOT EXISTS daemon_emergence_corpus (\n  id          BIGSERIAL PRIMARY KEY,\n  owner_id    TEXT NOT NULL,\n  kind        TEXT NOT NULL,\n  data        JSONB NOT NULL,\n  created_at  TIMESTAMP WITH TIME ZONE DEFAULT NOW()\n);\nCREATE INDEX IF NOT EXISTS idx_emergence_owner ON daemon_emergence_corpus (owner_id);\nCREATE INDEX IF NOT EXISTS idx_emergence_created ON daemon_emergence_corpus (created_at);\n`;\n\nlet pgPool: PgLike | null = null;\nlet pgReady: Promise<void> | null = null;\n\nfunction maybeInitPg(): void {\n  if (pgPool || pgReady) return;\n  const databaseUrl = process.env.DATABASE_URL;\n  if (!databaseUrl) return;\n  try {\n    // eslint-disable-next-line @typescript-eslint/no-var-requires\n    const { Pool } = require('pg') as {\n      Pool: new (cfg: DaemonEmergencePostgresPoolOptions) => PgLike;\n    };\n    const pool = new Pool(createDaemonEmergencePostgresPoolOptions(databaseUrl));\n    pgPool = pool;\n    pgReady = pool\n      .query(EMERGENCE_SCHEMA_SQL)\n      .then(() => undefined)\n      .catch((e: unknown) => {\n        console.warn('[DaemonEmergenceStore] schema init failed:', e);\n      });\n    console.log('[DaemonEmergenceStore] PostgreSQL write-through active');\n  } catch (e) {\n    console.warn('[DaemonEmergenceStore] DATABASE_URL set but pg failed to load:', e);\n  }\n}\n\nfunction pgAppend(record: EmergenceRecord): void {\n  maybeInitPg();\n  if (!pgPool || !pgReady) return;\n  pgReady\n    .then(() =>\n      pgPool!.query(\n        `INSERT INTO daemon_emergence_corpus (owner_id, kind, data) VALUES ($1, $2, $3)`,\n        [record.ownerId, record.kind, JSON.stringify(record)]\n      )\n    )\n    .catch((e: unknown) => {\n      console.warn('[DaemonEmergenceStore] pg append failed:', e);\n    });\n}\n\n// ── Append (write-through) ────────────────────────────────────────────────────\n//\n// Synchronous JSONL append (matches state.ts persistCaelAuditRecord). Never\n// throws into the emergence path — a persistence failure must not change live\n// behavior. Honors the same test opt-out env as the CAEL audit store.\n\nlet dirEnsured = false;\n\nfunction ensureDir(): void {\n  if (dirEnsured) return;\n  if (!fs.existsSync(EMERGENCE_DIR)) {\n    fs.mkdirSync(EMERGENCE_DIR, { recursive: true });\n  }\n  dirEnsured = true;\n}\n\n/**\n * Persist one emergence record (observation or emergence event). Write-through:\n * JSONL on disk (source of truth) + optional Postgres (multi-instance). Best-effort\n * — swallows errors so the in-memory emergence path is never affected.\n */\nexport function appendEmergenceRecord(record: EmergenceRecord): void {\n  if (\n    process.env.NODE_ENV === 'test' &&\n    process.env.HOLOMESH_TEST_DISABLE_EMERGENCE_PERSISTENCE === '1'\n  ) {\n    return;\n  }\n  try {\n    ensureDir();\n    fs.appendFileSync(CORPUS_PATH, `${JSON.stringify(record)}\\n`, 'utf8');\n  } catch (err) {\n    console.warn(`[DaemonEmergenceStore] JSONL append failed: ${(err as Error).message}`);\n  }\n  pgAppend(record);\n}\n\n// ── Read (hydration source) ───────────────────────────────────────────────────\n\n/**\n * Read every persisted emergence record from disk, oldest-first (append order).\n * Corrupt / half-flushed lines are skipped (honest: rare, never fatal). Returns\n * [] when nothing has accrued yet. This is the local source of truth — Postgres\n * is only consulted by the caller when it explicitly wants cross-instance reads.\n */\nexport function readEmergenceRecords(): EmergenceRecord[] {\n  if (!fs.existsSync(CORPUS_PATH)) return [];\n  const out: EmergenceRecord[] = [];\n  const lines = fs.readFileSync(CORPUS_PATH, 'utf8').split('\\n');\n  for (const line of lines) {\n    const trimmed = line.trim();\n    if (!trimmed) continue;\n    try {\n      out.push(JSON.parse(trimmed) as EmergenceRecord);\n    } catch {\n      // Corrupt line — skip.\n    }\n  }\n  return out;\n}\n\n// ── Export (normalized training corpus) ───────────────────────────────────────\n//\n// The corpus consumer (ai-ecosystem/scripts/corpus/harvest_real.py) normalizes\n// every source into (system, user, target, grader_key, ...). The emergence\n// source is a live behavioral trace, so we emit the same shape:\n//\n//   system   : fixed emergence-task framing\n//   user     : a JSON encoding of the observed context (the field's input)\n//   target   : a JSON encoding of what the field learned (preferences + care\n//              signals + significance) — the supervision signal\n//   timestamp: ISO observed/emerged stamp\n//   grader_key: [\"emergence\", ownerId, seq] — provenance + dedup handle\n//\n// Emergence events are emitted as a `manifested` marker row so a corpus builder\n// can segment a soul's pre-emergence stream from post-emergence learning.\n\nexport interface NormalizedCorpusRow {\n  system: string;\n  user: string;\n  target: string;\n  grader: { kind: string; ownerId: string; significanceScore?: number };\n  grader_key: [string, string, number];\n  family: string;\n  modality: string;\n  source: string;\n  soul: string;\n  context: Record<string, unknown>;\n  observation: Record<string, unknown> | null;\n  timestamp: string;\n}\n\nconst SYSTEM_EMERGENCE =\n  'You are a daimōn substrate observing a soul (D.053). Given the accumulated ' +\n  'context of an interaction, update the latent model of who this person is — ' +\n  'their preferences and the care they are owed. Respond with ONLY the updated ' +\n  'model as JSON.';\n\n/**\n * Project the persisted emergence corpus into normalized training rows.\n * Pure over the on-disk records (no I/O beyond the read) so it is trivially\n * testable. `records` defaults to the on-disk corpus.\n */\nexport function buildNormalizedRows(\n  records: EmergenceRecord[] = readEmergenceRecords()\n): NormalizedCorpusRow[] {\n  const rows: NormalizedCorpusRow[] = [];\n  const seqByOwner = new Map<string, number>();\n\n  for (const rec of records) {\n    const seq = (seqByOwner.get(rec.ownerId) ?? -1) + 1;\n    seqByOwner.set(rec.ownerId, seq);\n\n    if (rec.kind === 'observation') {\n      const d = rec.delta;\n      // user = the input context the field saw (intents + capability updates +\n      // receipt refs). target = what it learned (preferences + care signals).\n      const context = {\n        newIntentSignals: d.newIntentSignals,\n        capabilityUpdates: d.capabilityUpdates,\n        newReceiptRefs: d.newReceiptRefs,\n      };\n      const observation = {\n        updatedPreferences: d.updatedPreferences,\n        careSignalHistory: d.careSignalHistory,\n        significanceScore: d.significanceScore,\n      };\n      rows.push({\n        system: SYSTEM_EMERGENCE,\n        user: JSON.stringify(context),\n        target: JSON.stringify(observation),\n        grader: {\n          kind: 'emergence_observation',\n          ownerId: rec.ownerId,\n          significanceScore: d.significanceScore,\n        },\n        grader_key: ['emergence', rec.ownerId, seq],\n        family: 'real_emergence',\n        modality: 'soul-observation',\n        source: 'daemon-emergence-corpus',\n        soul: rec.ownerId,\n        context,\n        observation,\n        timestamp: rec.observedAt,\n      });\n    } else {\n      // emergence marker row — segments pre/post emergence for a soul.\n      rows.push({\n        system: SYSTEM_EMERGENCE,\n        user: JSON.stringify({ event: 'manifested', daemonId: rec.daemonId }),\n        target: JSON.stringify({ displayName: rec.displayName }),\n        grader: { kind: 'emergence_manifested', ownerId: rec.ownerId },\n        grader_key: ['emergence', rec.ownerId, seq],\n        family: 'real_emergence',\n        modality: 'emergence-event',\n        source: 'daemon-emergence-corpus',\n        soul: rec.ownerId,\n        context: { event: 'manifested', daemonId: rec.daemonId },\n        observation: null,\n        timestamp: rec.emergedAt,\n      });\n    }\n  }\n  return rows;\n}\n\n/**\n * Export the persisted emergence corpus to a normalized JSONL file the\n * corpus builder (harvest_real.py) can consume. Returns the path written and\n * the row count. If `outPath` is omitted, writes alongside the raw corpus as\n * `emergence-corpus.normalized.jsonl`.\n */\nexport function exportCorpusJsonl(outPath?: string): {\n  path: string;\n  rows: number;\n  bytes: number;\n} {\n  const rows = buildNormalizedRows();\n  const target = outPath || path.join(EMERGENCE_DIR, 'emergence-corpus.normalized.jsonl');\n  ensureDir();\n  const body = rows.map((r) => JSON.stringify(r)).join('\\n') + (rows.length ? '\\n' : '');\n  fs.writeFileSync(target, body, 'utf8');\n  return { path: target, rows: rows.length, bytes: Buffer.byteLength(body, 'utf8') };\n}\n\n/** Diagnostics: where the corpus lives + how much has accrued. */\nexport function emergenceCorpusStats(): {\n  corpusPath: string;\n  exists: boolean;\n  records: number;\n  souls: number;\n  emergedSouls: number;\n} {\n  const records = readEmergenceRecords();\n  const souls = new Set(records.map((r) => r.ownerId));\n  const emerged = new Set(\n    records\n      .filter((r): r is Extract<EmergenceRecord, { kind: 'emergence' }> => r.kind === 'emergence')\n      .map((r) => r.ownerId)\n  );\n  return {\n    corpusPath: CORPUS_PATH,\n    exists: fs.existsSync(CORPUS_PATH),\n    records: records.length,\n    souls: souls.size,\n    emergedSouls: emerged.size,\n  };\n}\n\n/** Test-only: the resolved corpus path (so tests can point HOLOMESH_DATA_DIR). */\nexport function _corpusPathForTest(): string {\n  return CORPUS_PATH;\n}\n","/**\n * ConversationDaemon Lifecycle MCP Tools\n *\n * 4 MCP tools for creating, reading, updating, and listing ConversationDaemons,\n * plus the DaemonBrittneyRehydrationChannel implementation that lets Brittney\n * rehydrate cross-session context.\n *\n * Gap (1): holo_create_daemon / holo_get_daemon / holo_update_daemon_ritual /\n *          holo_list_daemons — MCP exposure for daemon lifecycle.\n * Gap (2): DaemonBrittneyRehydrationChannel — defined as interface in\n *          ConversationDaemon.ts, nothing implements it. This module provides\n *          the concrete rehydration channel that forwards ContextDelta events\n *          to the Brittney field.\n *\n * Source: packages/core/src/daemon/ConversationDaemon.ts\n * Task: task_1779158611517_uw6j\n */\n\nimport { Tool } from '@modelcontextprotocol/sdk/types.js';\nimport {\n  type ConversationDaemon,\n  type ConversationDaemonTurn,\n  type ContextDelta,\n  type DaemonBrittneyRehydrationChannel,\n  type DaemonCustomizationProfile,\n  type DaemonRitual,\n  type DaemonStyleProfile,\n  type DaemonPermissionConfig,\n  type DaemonCareProfile,\n  assertDaemonFieldSeparation,\n  assertCallerOwnsDaemon,\n  makeDefaultConversationDaemon,\n  makeEmptyContextDelta,\n  makeDefaultCustomizationProfile,\n  customizationProfileToDaemon,\n  daemonToCustomizationProfile,\n  mergeStyleUpdates,\n  mergePermissionUpdates,\n  validateCustomizationProfile,\n  makePresetProfile,\n  DAEMON_VISUAL_THEMES,\n  DAEMON_CARE_PROFILES,\n} from '@holoscript/core';\nimport {\n  appendEmergenceRecord,\n  readEmergenceRecords,\n  exportCorpusJsonl,\n  emergenceCorpusStats,\n  type EmergenceRecord,\n  type PersistedContextDelta,\n} from './daemon-emergence-store.js';\n\n// ─── In-Memory Daemon Store ─────────────────────────────────────────────────\n//\n// Production deployments should replace this with a persistent store\n// (SQLite, Postgres, CRDT-backed). This Map serves as the reference\n// implementation that MCP tools operate against.\n\nconst daemonStore = new Map<string, ConversationDaemon>();\nconst profileStore = new Map<string, DaemonCustomizationProfile>();\n\n// ─── BrittneyRehydrationChannel Implementation ────────────────────────────────\n//\n// The interface DaemonBrittneyRehydrationChannel is defined in ConversationDaemon.ts\n// as a data contract (enabled, channelId, deltaCompression, minimumDeltaSignificance).\n// The *implementation* — the code that actually forwards ContextDelta events\n// to the Brittney field — is what was missing. This class provides it.\n//\n// Design:\n// - RehydrationChannel receives ContextDelta events from daemon turns.\n// - It filters by significance (below minimumDeltaSignificance → discard).\n// - It compresses deltas when deltaCompression is true (keeps only the\n//   latest value for each preference key and deduplicates receipt refs).\n// - It maintains a per-channel buffer of recent deltas for cross-session\n//   rehydration (what Brittney reads when a new session starts).\n// - The channelId links to the Brittney field's routing table — never anonymous.\n\ninterface RehydratedContext {\n  channelId: string;\n  daemonId: string;\n  ownerId: string;\n  /** Ordered deltas above significance threshold, most recent last */\n  deltas: ContextDelta[];\n  /** Aggregated preferences from all compressed deltas */\n  aggregatedPreferences: Record<string, unknown>;\n  /** Deduplicated receipt references */\n  receiptRefs: string[];\n  /** Capability availability map (latest wins) */\n  capabilityMap: Map<string, boolean>;\n  /** Care signal history (deduplicated) */\n  careSignals: string[];\n  /** ISO-8601 timestamp of last rehydration */\n  lastRehydratedAt: string;\n}\n\nclass BrittneyRehydrationChannelImpl {\n  private channelConfig: DaemonBrittneyRehydrationChannel;\n  private daemonId: string;\n  private ownerId: string;\n  private deltaBuffer: ContextDelta[] = [];\n  private aggregatedPreferences: Record<string, unknown> = {};\n  private receiptRefs: Set<string> = new Set();\n  private capabilityMap: Map<string, boolean> = new Map();\n  private careSignals: Set<string> = new Set();\n  private lastRehydratedAt: string = new Date().toISOString();\n\n  // Buffer capacity — prevents unbounded memory growth in long sessions.\n  // Oldest deltas are evicted when the buffer exceeds this size.\n  private static readonly MAX_BUFFER_SIZE = 100;\n\n  constructor(config: DaemonBrittneyRehydrationChannel, daemonId: string, ownerId: string) {\n    this.channelConfig = config;\n    this.daemonId = daemonId;\n    this.ownerId = ownerId;\n\n    if (!config.channelId) {\n      throw new Error(\n        '[BrittneyRehydrationChannel] channelId is required — field routing cannot be anonymous'\n      );\n    }\n  }\n\n  /**\n   * Receive a ContextDelta from a daemon turn.\n   * Returns true if the delta was accepted (above significance threshold),\n   * false if it was discarded.\n   */\n  receive(delta: ContextDelta): boolean {\n    // Filter by significance\n    if (delta.significanceScore < this.channelConfig.minimumDeltaSignificance) {\n      return false;\n    }\n\n    if (this.channelConfig.deltaCompression) {\n      // Compress: merge preferences, deduplicate receipt refs\n      for (const [key, value] of Object.entries(delta.updatedPreferences)) {\n        this.aggregatedPreferences[key] = value;\n      }\n      for (const ref of delta.newReceiptRefs) {\n        this.receiptRefs.add(ref);\n      }\n      for (const cap of delta.capabilityUpdates) {\n        this.capabilityMap.set(cap.capability, cap.available);\n      }\n      for (const signal of delta.careSignalHistory) {\n        this.careSignals.add(signal);\n      }\n    }\n\n    // Always store the full delta in the buffer (uncompressed)\n    this.deltaBuffer.push(delta);\n\n    // Evict oldest if over capacity\n    if (this.deltaBuffer.length > BrittneyRehydrationChannelImpl.MAX_BUFFER_SIZE) {\n      this.deltaBuffer.shift();\n    }\n\n    return true;\n  }\n\n  /**\n   * Rehydrate: produce the accumulated context for a new session.\n   * This is what Brittney reads to restore continuity across sessions.\n   */\n  rehydrate(): RehydratedContext {\n    this.lastRehydratedAt = new Date().toISOString();\n\n    // Filter deltas by significance for rehydration\n    const significantDeltas = this.deltaBuffer.filter(\n      (d) => d.significanceScore >= this.channelConfig.minimumDeltaSignificance\n    );\n\n    return {\n      channelId: this.channelConfig.channelId,\n      daemonId: this.daemonId,\n      ownerId: this.ownerId,\n      deltas: significantDeltas,\n      aggregatedPreferences: { ...this.aggregatedPreferences },\n      receiptRefs: Array.from(this.receiptRefs),\n      capabilityMap: new Map(this.capabilityMap),\n      careSignals: Array.from(this.careSignals),\n      lastRehydratedAt: this.lastRehydratedAt,\n    };\n  }\n\n  /**\n   * Clear the rehydration buffer. Called when the daemon is reset\n   * or the user explicitly clears their daemon's memory.\n   */\n  clear(): void {\n    this.deltaBuffer = [];\n    this.aggregatedPreferences = {};\n    this.receiptRefs.clear();\n    this.capabilityMap.clear();\n    this.careSignals.clear();\n    this.lastRehydratedAt = new Date().toISOString();\n  }\n\n  /** Get buffer stats for diagnostics */\n  getStats(): {\n    bufferSize: number;\n    channelId: string;\n    enabled: boolean;\n    deltaCompression: boolean;\n    minimumDeltaSignificance: number;\n  } {\n    return {\n      bufferSize: this.deltaBuffer.length,\n      channelId: this.channelConfig.channelId,\n      enabled: this.channelConfig.enabled,\n      deltaCompression: this.channelConfig.deltaCompression,\n      minimumDeltaSignificance: this.channelConfig.minimumDeltaSignificance,\n    };\n  }\n}\n\n// Per-daemon rehydration channels\nconst rehydrationChannels = new Map<string, BrittneyRehydrationChannelImpl>();\n\n// ─── Emergence engine (D.053: the daimōn appears from being known) ────────────\n//\n// The daimōn is NOT granted at signup and NOT earned. Provisioning establishes\n// only a latent learning substrate; the field accumulates ContextDeltas for a\n// SOUL (ownerId) while the person simply lives. When the accumulated knowing\n// crosses a threshold, the daimōn MANIFESTS — composed from the accumulated\n// context (its rehydration channel pre-seeded with what was learned), so it\n// appears already knowing them. Recognition, not onboarding.\n\ninterface SoulObservation {\n  ownerId: string;\n  deltas: ContextDelta[];\n  // Distinct preference keys + care signals seen — the \"richness\" of the model.\n  preferenceKeys: Set<string>;\n  careSignals: Set<string>;\n  firstObservedAt: string;\n  lastObservedAt: string;\n}\n\n// Pre-emergence accumulators, keyed by SOUL (ownerId) — before any daemon exists.\nconst soulObservations = new Map<string, SoulObservation>();\n\n// ── Durable write-through (additive; D.053 corpus persistence) ────────────────\n//\n// The emergence Maps above are in-memory and evaporate on restart, so no real\n// training data accrues. These helpers mirror every Map write to a durable,\n// append-only store WITHOUT changing the emergence semantics, thresholds, or\n// composition logic — a transparent persistence layer (see daemon-emergence-store.ts).\n\n// When true, composeDaemonFromContext skips its emergence-event write-through.\n// Set ONLY during hydration replay so re-composing an already-persisted daimōn\n// does not duplicate the corpus record. Default false (live path persists).\nlet suppressEmergencePersistence = false;\n\n/** Serialization-safe echo of a ContextDelta for the durable corpus. */\nfunction toPersistedDelta(delta: ContextDelta): PersistedContextDelta {\n  return {\n    newIntentSignals: [...delta.newIntentSignals],\n    updatedPreferences: { ...delta.updatedPreferences },\n    newReceiptRefs: [...delta.newReceiptRefs],\n    capabilityUpdates: delta.capabilityUpdates.map(\n      (c: ContextDelta['capabilityUpdates'][number]) => ({\n        capability: c.capability,\n        available: c.available,\n      })\n    ),\n    careSignalHistory: [...delta.careSignalHistory],\n    significanceScore: delta.significanceScore,\n  };\n}\n\n/** Inverse of toPersistedDelta: rebuild a live ContextDelta from a persisted echo. */\nfunction fromPersistedDelta(p: PersistedContextDelta): ContextDelta {\n  const base = makeEmptyContextDelta();\n  return {\n    newIntentSignals:\n      (p.newIntentSignals as ContextDelta['newIntentSignals']) ?? base.newIntentSignals,\n    updatedPreferences: { ...p.updatedPreferences },\n    newReceiptRefs: [...p.newReceiptRefs],\n    capabilityUpdates:\n      (p.capabilityUpdates as ContextDelta['capabilityUpdates']) ?? base.capabilityUpdates,\n    careSignalHistory: [...p.careSignalHistory],\n    significanceScore: typeof p.significanceScore === 'number' ? p.significanceScore : 0,\n  };\n}\n\n// Emergence threshold — the knowing-bar. The field decides \"I know them enough\n// now\"; this is NOT a timer and NOT a user milestone. Initial heuristic, tunable.\nconst EMERGENCE = {\n  // A delta counts toward knowing only at/above this significance.\n  SIGNIFICANCE_FLOOR: 0.5,\n  // Need at least this many significant deltas (a sustained pattern, not one turn).\n  MIN_SIGNIFICANT_TURNS: 5,\n  // Model richness = distinct preference keys + distinct care signals.\n  MIN_MODEL_RICHNESS: 3,\n  // Per-soul observation buffer cap (mirrors the channel cap).\n  MAX_OBSERVATIONS: 200,\n} as const;\n\n/**\n * Deterministic per-soul daemon id, so the emerged daimōn is stable + transferable.\n * Exported as the single source of truth — every surface (HoloScript provisioning,\n * HoloLand player provisioning) must compute the same id for a soul so they all\n * reference ONE daimōn (D.053 transferability).\n */\nexport function emergentDaemonId(ownerId: string): string {\n  return `daemon-${ownerId}`;\n}\n\n/** Record a ContextDelta against a soul's pre-emergence model. */\nfunction observeSoul(ownerId: string, delta: ContextDelta): SoulObservation {\n  let obs = soulObservations.get(ownerId);\n  if (!obs) {\n    obs = {\n      ownerId,\n      deltas: [],\n      preferenceKeys: new Set<string>(),\n      careSignals: new Set<string>(),\n      firstObservedAt: new Date().toISOString(),\n      lastObservedAt: new Date().toISOString(),\n    };\n    soulObservations.set(ownerId, obs);\n  }\n  obs.deltas.push(delta);\n  if (obs.deltas.length > EMERGENCE.MAX_OBSERVATIONS) obs.deltas.shift();\n  for (const key of Object.keys(delta.updatedPreferences)) obs.preferenceKeys.add(key);\n  for (const signal of delta.careSignalHistory) obs.careSignals.add(signal);\n  obs.lastObservedAt = new Date().toISOString();\n  // Write-through (additive): mirror the observation to the durable corpus.\n  // Best-effort; never affects the in-memory accumulation above.\n  appendEmergenceRecord({\n    kind: 'observation',\n    ownerId,\n    delta: toPersistedDelta(delta),\n    routedTo: 'soul-accumulator',\n    observedAt: obs.lastObservedAt,\n  });\n  return obs;\n}\n\ninterface EmergenceReadiness {\n  ready: boolean;\n  /** 0–1 observability blend of progress toward the threshold. */\n  knowingScore: number;\n  significantTurns: number;\n  modelRichness: number;\n  threshold: { minSignificantTurns: number; minModelRichness: number; significanceFloor: number };\n}\n\n/** Evaluate whether a soul's accumulated knowing crosses the emergence threshold. */\nfunction evaluateEmergence(ownerId: string): EmergenceReadiness {\n  const obs = soulObservations.get(ownerId);\n  const significantTurns = obs\n    ? obs.deltas.filter((d) => d.significanceScore >= EMERGENCE.SIGNIFICANCE_FLOOR).length\n    : 0;\n  const modelRichness = obs ? obs.preferenceKeys.size + obs.careSignals.size : 0;\n  const ready =\n    significantTurns >= EMERGENCE.MIN_SIGNIFICANT_TURNS &&\n    modelRichness >= EMERGENCE.MIN_MODEL_RICHNESS;\n  const knowingScore = Math.min(\n    1,\n    (Math.min(significantTurns, EMERGENCE.MIN_SIGNIFICANT_TURNS) / EMERGENCE.MIN_SIGNIFICANT_TURNS +\n      Math.min(modelRichness, EMERGENCE.MIN_MODEL_RICHNESS) / EMERGENCE.MIN_MODEL_RICHNESS) /\n      2\n  );\n  return {\n    ready,\n    knowingScore,\n    significantTurns,\n    modelRichness,\n    threshold: {\n      minSignificantTurns: EMERGENCE.MIN_SIGNIFICANT_TURNS,\n      minModelRichness: EMERGENCE.MIN_MODEL_RICHNESS,\n      significanceFloor: EMERGENCE.SIGNIFICANCE_FLOOR,\n    },\n  };\n}\n\n/**\n * Compose + manifest the daimōn from a soul's accumulated context. The emergent\n * daemon is NOT a default seed — its rehydration channel is pre-loaded with every\n * significant accumulated delta, so on first appearance it already knows the\n * person. careProfile is derived from observed care signals when present.\n */\nfunction composeDaemonFromContext(ownerId: string, displayName: string): ConversationDaemon {\n  const obs = soulObservations.get(ownerId);\n  const daemonId = emergentDaemonId(ownerId);\n\n  // Derive care profile from accumulated care signals (else the default model).\n  const careProfile = obs && obs.careSignals.size > 0 ? 'care-v1' : 'care-v1';\n\n  const daemon = makeDefaultConversationDaemon(daemonId, ownerId, displayName, careProfile);\n  assertDaemonFieldSeparation(daemon);\n\n  // Manifest the channel and SEED it with what the field learned — the daemon is\n  // composed from accumulated context, not from blank defaults.\n  const channel = new BrittneyRehydrationChannelImpl(\n    daemon.brittneyRehydrationChannel,\n    daemon.daemonId,\n    daemon.ownerId\n  );\n  if (obs) {\n    for (const delta of obs.deltas) channel.receive(delta);\n  }\n  rehydrationChannels.set(daemonId, channel);\n  daemonStore.set(daemonId, daemon);\n\n  // Write-through (additive): record the manifestation event so the corpus can\n  // segment a soul's pre-emergence stream from post-emergence learning, and so\n  // hydration knows this soul has already emerged. Suppressed during hydration\n  // replay (the record already exists on disk).\n  if (!suppressEmergencePersistence) {\n    appendEmergenceRecord({\n      kind: 'emergence',\n      ownerId,\n      daemonId,\n      displayName,\n      emergedAt: new Date().toISOString(),\n    });\n  }\n\n  // The soul has emerged — fold the pre-emergence accumulator into the daemon.\n  soulObservations.delete(ownerId);\n\n  return daemon;\n}\n\n// ─── Hydration (replay durable corpus → in-memory Maps on startup) ────────────\n//\n// Mirrors loadCaelAuditFromDisk in holomesh/state.ts: at server start, replay the\n// durable emergence corpus to reconstruct soulObservations + daemonStore EXACTLY\n// as the live writes would have produced them. Critically, replay uses the\n// in-memory mutation logic ONLY — it does NOT call appendEmergenceRecord (no\n// double-write to disk). Idempotent: safe to call once at boot. Replay order is\n// append order, so per-soul causality (observations → emergence → post-emergence\n// learning) is preserved.\n\n/** Mutate a soul's in-memory accumulator from a delta (the observeSoul core, sans write-through). */\nfunction replayObservationIntoMemory(\n  ownerId: string,\n  delta: ContextDelta,\n  observedAt: string\n): void {\n  let obs = soulObservations.get(ownerId);\n  if (!obs) {\n    obs = {\n      ownerId,\n      deltas: [],\n      preferenceKeys: new Set<string>(),\n      careSignals: new Set<string>(),\n      firstObservedAt: observedAt,\n      lastObservedAt: observedAt,\n    };\n    soulObservations.set(ownerId, obs);\n  }\n  obs.deltas.push(delta);\n  if (obs.deltas.length > EMERGENCE.MAX_OBSERVATIONS) obs.deltas.shift();\n  for (const key of Object.keys(delta.updatedPreferences)) obs.preferenceKeys.add(key);\n  for (const signal of delta.careSignalHistory) obs.careSignals.add(signal);\n  obs.lastObservedAt = observedAt;\n}\n\n/**\n * Rehydrate the emergence engine from the durable corpus. Returns counts for\n * diagnostics. Call once at server startup (after stores are wired). Idempotent\n * for a fresh process; do not call mid-session (it appends to existing Maps).\n */\nexport function hydrateEmergenceFromCorpus(records: EmergenceRecord[] = readEmergenceRecords()): {\n  records: number;\n  souls: number;\n  emerged: number;\n} {\n  let emergedCount = 0;\n  for (const rec of records) {\n    if (rec.kind === 'observation') {\n      const delta = fromPersistedDelta(rec.delta);\n      const daemonId = emergentDaemonId(rec.ownerId);\n      if (rec.routedTo === 'daemon-channel' && daemonStore.has(daemonId)) {\n        // Post-emergence learning replays into the live channel (matches the\n        // live receiveContextDelta path, in-memory only).\n        const channel = rehydrationChannels.get(daemonId);\n        if (channel) channel.receive(delta);\n      } else {\n        // Pre-emergence accumulation.\n        replayObservationIntoMemory(rec.ownerId, delta, rec.observedAt);\n      }\n    } else {\n      // Emergence marker: compose the daimōn from the accumulated soul state.\n      // composeDaemonFromContext folds + deletes the accumulator and seeds the\n      // channel — exactly the live behavior. It DOES append an emergence record;\n      // to keep hydration write-free we temporarily suppress persistence.\n      const ownerId = rec.ownerId;\n      if (!daemonStore.has(emergentDaemonId(ownerId))) {\n        // Suppress the emergence-event write-through during replay (the record\n        // already exists on disk — we are reconstructing, not re-emitting).\n        suppressEmergencePersistence = true;\n        try {\n          composeDaemonFromContext(ownerId, rec.displayName);\n        } finally {\n          suppressEmergencePersistence = false;\n        }\n        emergedCount++;\n      }\n    }\n  }\n  const souls = new Set(records.map((r) => r.ownerId));\n  return { records: records.length, souls: souls.size, emerged: emergedCount };\n}\n\n// ─── TOOL DEFINITIONS ─────────────────────────────────────────────────────────\n\nexport const daemonLifecycleTools: Tool[] = [\n  {\n    name: 'holo_create_daemon',\n    description:\n      'Create a new ConversationDaemon with default or preset configuration. ' +\n      'Returns the full daemon object including the Brittney rehydration channel. ' +\n      'Use a preset (companion, professional, creative, minimal, guardian) for quick setup, ' +\n      'or provide custom style and permission overrides. ' +\n      'The daemon is the user-facing companion — not Brittney, not the field. ' +\n      'Returns: The created ConversationDaemon and its CustomizationProfile.',\n    inputSchema: {\n      type: 'object' as const,\n      properties: {\n        daemonId: {\n          type: 'string',\n          description: 'Unique identifier for the daemon. Auto-generated if omitted.',\n        },\n        ownerId: {\n          type: 'string',\n          description: 'Owner user ID. Required.',\n        },\n        displayName: {\n          type: 'string',\n          description: 'Human-readable daemon name (e.g. \"Lumi\", \"Atlas\"). Default: \"Lumi\".',\n        },\n        preset: {\n          type: 'string',\n          enum: ['companion', 'professional', 'creative', 'minimal', 'guardian'],\n          description:\n            'Pre-built persona preset. Overrides style/permission defaults. Default: uses makeDefaultConversationDaemon.',\n        },\n        careProfile: {\n          type: 'string',\n          enum: DAEMON_CARE_PROFILES,\n          description: 'Care model identifier. Default: \"care-v1\".',\n        },\n        visualTheme: {\n          type: 'string',\n          enum: DAEMON_VISUAL_THEMES,\n          description: 'Visual theme for the daemon appearance. Default: \"default\".',\n        },\n      },\n      required: ['ownerId'],\n    },\n  },\n  {\n    name: 'holo_get_daemon',\n    description:\n      'Retrieve a ConversationDaemon by its ID. Returns the full daemon object ' +\n      'and the associated CustomizationProfile if available. ' +\n      'Returns: The daemon and profile, or 404 if not found.',\n    inputSchema: {\n      type: 'object' as const,\n      properties: {\n        daemonId: {\n          type: 'string',\n          description: 'The daemon ID to retrieve.',\n        },\n        includeRehydrationContext: {\n          type: 'boolean',\n          description:\n            'If true, include the Brittney rehydration context (aggregated preferences, receipt refs, care signals). Default: false.',\n        },\n      },\n      required: ['daemonId'],\n    },\n  },\n  {\n    name: 'holo_update_daemon_ritual',\n    description:\n      'Update the rituals (named personal patterns) on a daemon customization profile. ' +\n      'Rituals belong to the style layer — never the permission layer. ' +\n      'This tool updates rituals only; it does not touch permissions, dispatch, or memory policy. ' +\n      'Supports add, replace, or remove operations on the ritual list. ' +\n      'Returns: The updated CustomizationProfile with incremented version.',\n    inputSchema: {\n      type: 'object' as const,\n      properties: {\n        profileId: {\n          type: 'string',\n          description: 'The customization profile ID to update (same as daemonId).',\n        },\n        operation: {\n          type: 'string',\n          enum: ['add', 'replace', 'remove'],\n          description:\n            'add: append new rituals. replace: overwrite all rituals. remove: remove matching rituals by name.',\n        },\n        rituals: {\n          type: 'array',\n          items: {\n            type: 'object',\n            properties: {\n              name: { type: 'string', description: 'Human-readable ritual name.' },\n              trigger: {\n                type: 'string',\n                description: 'Cron expression or trigger keyword.',\n              },\n              description: { type: 'string', description: 'What the ritual does.' },\n              enabled: { type: 'boolean', description: 'Whether the ritual is active.' },\n            },\n            required: ['name', 'trigger', 'description'],\n          },\n          description: 'Rituals to add, replace with, or remove by name.',\n        },\n      },\n      required: ['profileId', 'operation', 'rituals'],\n    },\n  },\n  {\n    name: 'holo_daemon_turn',\n    description:\n      'Submit a ConversationDaemonTurn and forward its ContextDelta to the Brittney ' +\n      'rehydration channel — the production entry point that feeds daemon turns into the field. ' +\n      'The contextDelta (not the raw utterance) is the durable memory artifact; it is filtered ' +\n      'by the channel significance threshold, compressed, and buffered for cross-session rehydration. ' +\n      'Enforces caller ownership (assertCallerOwnsDaemon) before any channel access — a caller may ' +\n      'only feed deltas to a daemon it owns. ' +\n      'Returns: { accepted, rehydratedContext } — accepted=false when the delta is below significance.',\n    inputSchema: {\n      type: 'object' as const,\n      properties: {\n        daemonId: {\n          type: 'string',\n          description: 'The daemon this turn belongs to. Required.',\n        },\n        callerId: {\n          type: 'string',\n          description:\n            'Authenticated caller identity. Must equal the daemon ownerId — the turn is rejected otherwise. Required.',\n        },\n        contextDelta: {\n          type: 'object',\n          description:\n            'The durable memory artifact of the turn (newIntentSignals, updatedPreferences, newReceiptRefs, capabilityUpdates, careSignalHistory, significanceScore). Defaults to an empty delta (significance 0 → discarded) when omitted.',\n        },\n        userUtterance: {\n          type: 'string',\n          description: 'Raw user utterance for the turn record (NOT the durable memory). Optional.',\n        },\n        surfaceId: {\n          type: 'string',\n          description:\n            'Surface the turn originated from (e.g. \"holoshell\", \"studio\", \"hololand-npc\"). Optional.',\n        },\n        turnId: {\n          type: 'string',\n          description: 'Turn identifier. Auto-generated if omitted.',\n        },\n        timestamp: {\n          type: 'string',\n          description: 'ISO-8601 turn timestamp. Defaults to now.',\n        },\n      },\n      required: ['daemonId', 'callerId'],\n    },\n  },\n  {\n    name: 'holo_observe_soul',\n    description:\n      'Observe a soul (D.053 emergence): record a ContextDelta against a person BEFORE ' +\n      'they have a daimōn. This is the latent learning substrate — the field accumulates ' +\n      'who they are while they simply live. If the soul has already emerged a daimōn, the ' +\n      \"delta is routed to that daimōn's rehydration channel instead. The daimōn is never \" +\n      'granted at signup; call this as the person interacts, then holo_daemon_emergence_check ' +\n      'to see if it is time for the daimōn to appear. ' +\n      'Returns: observation progress (knowingScore, significantTurns, modelRichness, ready).',\n    inputSchema: {\n      type: 'object' as const,\n      properties: {\n        ownerId: {\n          type: 'string',\n          description: 'The soul (HoloMesh agentId / workspaceId). Required.',\n        },\n        contextDelta: {\n          type: 'object',\n          description:\n            'The durable memory artifact of the interaction (updatedPreferences, careSignalHistory, significanceScore, …). Defaults to an empty delta (significance 0, contributes nothing) when omitted.',\n        },\n      },\n      required: ['ownerId'],\n    },\n  },\n  {\n    name: 'holo_daemon_emergence_check',\n    description:\n      \"Check whether a soul's accumulated knowing crosses the emergence threshold and, if so, \" +\n      'MANIFEST the daimōn (D.053). The daimōn is composed from accumulated context — its ' +\n      'rehydration channel is pre-seeded with everything the field learned, so it appears ' +\n      'already knowing the person (recognition, not onboarding). If a daimōn has already ' +\n      'emerged for this soul, returns it. If the threshold is not yet met, returns progress ' +\n      'without manifesting. ' +\n      'Returns: { emerged, daemon?, rehydratedContext?, knowingScore, ... }.',\n    inputSchema: {\n      type: 'object' as const,\n      properties: {\n        ownerId: {\n          type: 'string',\n          description: 'The soul to evaluate for emergence. Required.',\n        },\n        displayName: {\n          type: 'string',\n          description:\n            'Name for the daimōn when it manifests. The person renames/shapes it after. Default: \"Lumi\".',\n        },\n      },\n      required: ['ownerId'],\n    },\n  },\n  {\n    name: 'holo_list_daemons',\n    description:\n      'List all ConversationDaemons for a given owner. Returns daemon summaries ' +\n      'with ID, name, owner policy, and last active timestamp. ' +\n      'Returns: Array of daemon summaries.',\n    inputSchema: {\n      type: 'object' as const,\n      properties: {\n        ownerId: {\n          type: 'string',\n          description: 'Owner ID to filter by. If omitted, lists all daemons.',\n        },\n        includeStats: {\n          type: 'boolean',\n          description:\n            'If true, include rehydration channel stats (buffer size, compression status). Default: false.',\n        },\n      },\n    },\n  },\n  {\n    name: 'holo_export_emergence_corpus',\n    description:\n      'Export the durable daimōn EMERGENCE CORPUS (D.053) to a normalized JSONL file ' +\n      'a training-corpus builder can consume — the (soul, context, observation/target, ' +\n      'timestamp) shape read by scripts/corpus/harvest_real.py. The corpus is the ' +\n      'live graded-trace source for the HoloScript native-model program: every ' +\n      'observed ContextDelta and every emergence event that has accrued to disk is ' +\n      'projected into normalized rows. Read-only — does NOT mutate the corpus or ' +\n      'emergence state. ' +\n      'Returns: { path, rows, bytes, stats }.',\n    inputSchema: {\n      type: 'object' as const,\n      properties: {\n        outPath: {\n          type: 'string',\n          description:\n            'Destination JSONL path. Default: <data-dir>/emergence/emergence-corpus.normalized.jsonl.',\n        },\n      },\n    },\n  },\n];\n\n// ─── HANDLERS ─────────────────────────────────────────────────────────────────\n\nexport async function handleDaemonLifecycleTool(\n  name: string,\n  args: Record<string, unknown>\n): Promise<unknown | null> {\n  switch (name) {\n    case 'holo_create_daemon':\n      return handleCreateDaemon(args);\n    case 'holo_get_daemon':\n      return handleGetDaemon(args);\n    case 'holo_update_daemon_ritual':\n      return handleUpdateDaemonRitual(args);\n    case 'holo_daemon_turn':\n      return handleDaemonTurn(args);\n    case 'holo_observe_soul':\n      return handleObserveSoul(args);\n    case 'holo_daemon_emergence_check':\n      return handleEmergenceCheck(args);\n    case 'holo_list_daemons':\n      return handleListDaemons(args);\n    case 'holo_export_emergence_corpus':\n      return handleExportEmergenceCorpus(args);\n    default:\n      return null;\n  }\n}\n\n// ─── CREATE ───────────────────────────────────────────────────────────────────\n\nfunction handleCreateDaemon(args: Record<string, unknown>): {\n  daemon: ConversationDaemon;\n  profile: DaemonCustomizationProfile;\n  rehydrationStats: {\n    channelId: string;\n    enabled: boolean;\n    deltaCompression: boolean;\n    minimumDeltaSignificance: number;\n  };\n} {\n  const ownerId = args.ownerId as string;\n  if (!ownerId) {\n    throw new Error('holo_create_daemon: ownerId is required');\n  }\n\n  const daemonId = (args.daemonId as string) || `daemon_${ownerId}_${Date.now()}`;\n  const displayName = (args.displayName as string) || 'Lumi';\n  const careProfile = (args.careProfile as string) || 'care-v1';\n  const preset = args.preset as string | undefined;\n\n  let profile: DaemonCustomizationProfile;\n\n  if (preset) {\n    const validPresets = ['companion', 'professional', 'creative', 'minimal', 'guardian'] as const;\n    if (!validPresets.includes(preset as (typeof validPresets)[number])) {\n      throw new Error(\n        `holo_create_daemon: invalid preset \"${preset}\". Valid: ${validPresets.join(', ')}`\n      );\n    }\n    profile = makePresetProfile(preset as (typeof validPresets)[number], daemonId, ownerId);\n    // Override display name and care profile if provided\n    if (args.displayName) {\n      profile = mergeStyleUpdates(profile, { displayName: args.displayName as string });\n    }\n    if (careProfile !== 'care-v1') {\n      profile = mergeStyleUpdates(profile, { careProfile } as Partial<DaemonStyleProfile>);\n    }\n    if (args.visualTheme) {\n      profile = mergeStyleUpdates(profile, {\n        visualTheme: args.visualTheme as string,\n      } as Partial<DaemonStyleProfile>);\n    }\n  } else {\n    profile = makeDefaultCustomizationProfile(\n      daemonId,\n      ownerId,\n      displayName,\n      careProfile as DaemonCareProfile\n    );\n    if (args.visualTheme) {\n      profile = mergeStyleUpdates(profile, {\n        visualTheme: args.visualTheme as string,\n      } as Partial<DaemonStyleProfile>);\n    }\n  }\n\n  // Validate separation invariants before composing\n  const validationErrors = validateCustomizationProfile(profile);\n  if (validationErrors.length > 0) {\n    throw new Error(\n      `holo_create_daemon: profile validation failed: ${validationErrors.join('; ')}`\n    );\n  }\n\n  // Compose profile → daemon\n  const daemon = customizationProfileToDaemon(profile);\n\n  // Assert field separation invariant\n  assertDaemonFieldSeparation(daemon);\n\n  // Initialize rehydration channel\n  const channel = new BrittneyRehydrationChannelImpl(\n    daemon.brittneyRehydrationChannel,\n    daemon.daemonId,\n    daemon.ownerId\n  );\n  rehydrationChannels.set(daemonId, channel);\n\n  // Store\n  daemonStore.set(daemonId, daemon);\n  profileStore.set(daemonId, profile);\n\n  return {\n    daemon,\n    profile,\n    rehydrationStats: channel.getStats(),\n  };\n}\n\n// ─── GET ──────────────────────────────────────────────────────────────────────\n\nfunction handleGetDaemon(args: Record<string, unknown>): {\n  daemon: ConversationDaemon | null;\n  profile: DaemonCustomizationProfile | null;\n  rehydrationContext?: RehydratedContext;\n  rehydrationStats?: ReturnType<BrittneyRehydrationChannelImpl['getStats']>;\n} {\n  const daemonId = args.daemonId as string;\n  if (!daemonId) {\n    throw new Error('holo_get_daemon: daemonId is required');\n  }\n\n  const daemon = daemonStore.get(daemonId);\n  const profile = profileStore.get(daemonId);\n\n  if (!daemon) {\n    return {\n      daemon: null,\n      profile: null,\n    };\n  }\n\n  const includeRehydration = (args.includeRehydrationContext as boolean) ?? false;\n  const channel = rehydrationChannels.get(daemonId);\n\n  return {\n    daemon,\n    profile: profile ?? null,\n    ...(includeRehydration && channel\n      ? {\n          rehydrationContext: channel.rehydrate(),\n          rehydrationStats: channel.getStats(),\n        }\n      : {}),\n  };\n}\n\n// ─── UPDATE RITUAL ───────────────────────────────────────────────────────────\n\nfunction handleUpdateDaemonRitual(args: Record<string, unknown>): {\n  profile: DaemonCustomizationProfile;\n  daemon: ConversationDaemon;\n} {\n  const profileId = args.profileId as string;\n  if (!profileId) {\n    throw new Error('holo_update_daemon_ritual: profileId is required');\n  }\n\n  const operation = args.operation as string;\n  if (!['add', 'replace', 'remove'].includes(operation)) {\n    throw new Error(\n      `holo_update_daemon_ritual: invalid operation \"${operation}\". Valid: add, replace, remove`\n    );\n  }\n\n  const rituals = (args.rituals as Array<Record<string, unknown>>) || [];\n  const profile = profileStore.get(profileId);\n  if (!profile) {\n    throw new Error(`holo_update_daemon_ritual: profile \"${profileId}\" not found`);\n  }\n\n  // Parse rituals\n  const parsedRituals: DaemonRitual[] = rituals.map((r, i) => {\n    if (!r.name || !r.trigger || !r.description) {\n      throw new Error(\n        `holo_update_daemon_ritual: ritual at index ${i} missing required fields (name, trigger, description)`\n      );\n    }\n    // Invariant: ritual triggers must not contain permission-like prefixes\n    const permissionLikePrefixes = ['perm:', 'cap:', 'secret:', 'auth:', 'role:'];\n    for (const prefix of permissionLikePrefixes) {\n      if ((r.trigger as string).startsWith(prefix)) {\n        throw new Error(\n          `holo_update_daemon_ritual: ritual \"${r.name}\" trigger starts with \"${prefix}\" — rituals are personal patterns, not capability grants.`\n        );\n      }\n    }\n    return {\n      name: r.name as string,\n      trigger: r.trigger as string,\n      description: r.description as string,\n      enabled: (r.enabled as boolean) ?? true,\n    };\n  });\n\n  let updatedRituals: DaemonRitual[];\n\n  switch (operation) {\n    case 'add':\n      // Append new rituals, skipping duplicates by name\n      updatedRituals = [\n        ...profile.style.rituals,\n        ...parsedRituals.filter(\n          (nr) => !profile.style.rituals.some((er: DaemonRitual) => er.name === nr.name)\n        ),\n      ];\n      break;\n    case 'replace':\n      updatedRituals = parsedRituals;\n      break;\n    case 'remove':\n      // Remove rituals whose names match\n      const namesToRemove = new Set(parsedRituals.map((r: DaemonRitual) => r.name));\n      updatedRituals = profile.style.rituals.filter(\n        (r: DaemonRitual) => !namesToRemove.has(r.name)\n      );\n      break;\n    default:\n      updatedRituals = profile.style.rituals;\n  }\n\n  // Update via mergeStyleUpdates — rituals are in the style layer\n  const updatedProfile = mergeStyleUpdates(profile, {\n    rituals: updatedRituals,\n  } as Partial<DaemonStyleProfile>);\n\n  // Validate separation invariants still hold\n  const errors = validateCustomizationProfile(updatedProfile);\n  if (errors.length > 0) {\n    throw new Error(\n      `holo_update_daemon_ritual: updated profile violates separation invariants: ${errors.join('; ')}`\n    );\n  }\n\n  // Re-compose daemon from updated profile\n  const updatedDaemon = customizationProfileToDaemon(updatedProfile);\n\n  // Assert field separation invariant\n  assertDaemonFieldSeparation(updatedDaemon);\n\n  // Store updated versions\n  profileStore.set(profileId, updatedProfile);\n  daemonStore.set(profileId, updatedDaemon);\n\n  return {\n    profile: updatedProfile,\n    daemon: updatedDaemon,\n  };\n}\n\n// ─── DAEMON TURN (ContextDelta → Brittney field ingest) ──────────────────────\n//\n// The production entry point that feeds daemon turns into the rehydration channel.\n// The channel implementation + processDaemonTurn() already existed but had no\n// caller — this tool is the missing surface that lets a turn reach the field.\n\n/** Coerce arbitrary tool input into a valid ContextDelta, defaulting every field. */\nfunction parseContextDelta(value: unknown): ContextDelta {\n  const base = makeEmptyContextDelta();\n  if (!value || typeof value !== 'object') return base;\n  const v = value as Record<string, unknown>;\n  return {\n    newIntentSignals: Array.isArray(v.newIntentSignals)\n      ? (v.newIntentSignals as ContextDelta['newIntentSignals'])\n      : base.newIntentSignals,\n    updatedPreferences:\n      v.updatedPreferences && typeof v.updatedPreferences === 'object'\n        ? (v.updatedPreferences as Record<string, unknown>)\n        : base.updatedPreferences,\n    newReceiptRefs: Array.isArray(v.newReceiptRefs)\n      ? (v.newReceiptRefs as unknown[]).filter((r): r is string => typeof r === 'string')\n      : base.newReceiptRefs,\n    capabilityUpdates: Array.isArray(v.capabilityUpdates)\n      ? (v.capabilityUpdates as ContextDelta['capabilityUpdates'])\n      : base.capabilityUpdates,\n    careSignalHistory: Array.isArray(v.careSignalHistory)\n      ? (v.careSignalHistory as unknown[]).filter((s): s is string => typeof s === 'string')\n      : base.careSignalHistory,\n    significanceScore:\n      typeof v.significanceScore === 'number' ? v.significanceScore : base.significanceScore,\n  };\n}\n\nfunction handleDaemonTurn(args: Record<string, unknown>): {\n  accepted: boolean;\n  rehydratedContext: RehydratedContext | null;\n  daemonId: string;\n} {\n  const daemonId = args.daemonId as string;\n  if (!daemonId) {\n    throw new Error('holo_daemon_turn: daemonId is required');\n  }\n  const callerId = args.callerId as string;\n  if (!callerId) {\n    throw new Error('holo_daemon_turn: callerId is required (owner identity for the daemon)');\n  }\n\n  const daemon = daemonStore.get(daemonId);\n  if (!daemon) {\n    throw new Error(`holo_daemon_turn: daemon \"${daemonId}\" not found`);\n  }\n\n  // D1 (2026-05-19 daemon-rehydration audit): assert caller identity against\n  // daemon ownership BEFORE any rehydration channel access or delta emission.\n  // Throws UnauthorizedDaemonAccessError if the caller does not own the daemon.\n  assertCallerOwnsDaemon(daemon, callerId);\n\n  const turn: ConversationDaemonTurn = {\n    turnId: (args.turnId as string) || `turn_${daemonId}_${Date.now()}`,\n    daemonId,\n    surfaceId: (args.surfaceId as string) || 'unknown',\n    userUtterance: (args.userUtterance as string) || '',\n    extractedArtifacts: [],\n    urgency: 'low',\n    consentBoundary: 'read_only',\n    // The durable memory artifact. Raw conversation text is NOT durable memory — this is.\n    contextDelta: parseContextDelta(args.contextDelta),\n    requiredApproval: false,\n    receiptLinks: [],\n    timestamp: (args.timestamp as string) || new Date().toISOString(),\n  };\n\n  const { accepted, rehydratedContext } = processDaemonTurn(turn);\n  return { accepted, rehydratedContext, daemonId };\n}\n\n// ─── OBSERVE SOUL + EMERGENCE (D.053: the daimōn appears from being known) ────\n\nfunction handleObserveSoul(args: Record<string, unknown>): {\n  observed: true;\n  ownerId: string;\n  routedTo: 'soul-accumulator' | 'daemon-channel';\n  ready: boolean;\n  knowingScore: number;\n  significantTurns: number;\n  modelRichness: number;\n} {\n  const ownerId = args.ownerId as string;\n  if (!ownerId) {\n    throw new Error('holo_observe_soul: ownerId is required');\n  }\n  const delta = parseContextDelta(args.contextDelta);\n\n  // If the daimōn has already emerged, observations feed its channel (learning continues).\n  const daemonId = emergentDaemonId(ownerId);\n  if (daemonStore.has(daemonId)) {\n    receiveContextDelta(daemonId, delta);\n    // Write-through (additive): post-emergence learning keeps accruing to the corpus.\n    appendEmergenceRecord({\n      kind: 'observation',\n      ownerId,\n      delta: toPersistedDelta(delta),\n      routedTo: 'daemon-channel',\n      observedAt: new Date().toISOString(),\n    });\n    const r = evaluateEmergence(ownerId);\n    return {\n      observed: true,\n      ownerId,\n      routedTo: 'daemon-channel',\n      ready: true,\n      knowingScore: 1,\n      significantTurns: r.significantTurns,\n      modelRichness: r.modelRichness,\n    };\n  }\n\n  // Pre-emergence: accumulate against the soul's latent model.\n  observeSoul(ownerId, delta);\n  const r = evaluateEmergence(ownerId);\n  return {\n    observed: true,\n    ownerId,\n    routedTo: 'soul-accumulator',\n    ready: r.ready,\n    knowingScore: r.knowingScore,\n    significantTurns: r.significantTurns,\n    modelRichness: r.modelRichness,\n  };\n}\n\nfunction handleEmergenceCheck(args: Record<string, unknown>): {\n  emerged: boolean;\n  alreadyEmerged?: boolean;\n  daemon?: ConversationDaemon;\n  rehydratedContext?: RehydratedContext | null;\n  knowingScore: number;\n  significantTurns: number;\n  modelRichness: number;\n  threshold: EmergenceReadiness['threshold'];\n} {\n  const ownerId = args.ownerId as string;\n  if (!ownerId) {\n    throw new Error('holo_daemon_emergence_check: ownerId is required');\n  }\n  const displayName = (args.displayName as string) || 'Lumi';\n  const daemonId = emergentDaemonId(ownerId);\n  const r = evaluateEmergence(ownerId);\n\n  // Already emerged — return the existing daimōn + its accumulated knowing.\n  if (daemonStore.has(daemonId)) {\n    return {\n      emerged: true,\n      alreadyEmerged: true,\n      daemon: daemonStore.get(daemonId),\n      rehydratedContext: rehydrateDaemon(daemonId),\n      knowingScore: 1,\n      significantTurns: r.significantTurns,\n      modelRichness: r.modelRichness,\n      threshold: r.threshold,\n    };\n  }\n\n  // Not yet known enough — report progress, do not manifest.\n  if (!r.ready) {\n    return {\n      emerged: false,\n      knowingScore: r.knowingScore,\n      significantTurns: r.significantTurns,\n      modelRichness: r.modelRichness,\n      threshold: r.threshold,\n    };\n  }\n\n  // Threshold crossed — the daimōn appears, composed from accumulated context.\n  const daemon = composeDaemonFromContext(ownerId, displayName);\n  return {\n    emerged: true,\n    daemon,\n    rehydratedContext: rehydrateDaemon(daemon.daemonId),\n    knowingScore: 1,\n    significantTurns: r.significantTurns,\n    modelRichness: r.modelRichness,\n    threshold: r.threshold,\n  };\n}\n\n// ─── LIST ─────────────────────────────────────────────────────────────────────\n\nfunction handleListDaemons(args: Record<string, unknown>): {\n  total: number;\n  daemons: Array<{\n    daemonId: string;\n    ownerId: string;\n    displayName: string;\n    ownerPolicy: string;\n    lastActiveAt?: string;\n    rehydrationStats?: ReturnType<BrittneyRehydrationChannelImpl['getStats']>;\n  }>;\n} {\n  const ownerId = args.ownerId as string | undefined;\n  const includeStats = (args.includeStats as boolean) ?? false;\n\n  const daemons: ConversationDaemon[] = [];\n  for (const daemon of daemonStore.values()) {\n    if (!ownerId || daemon.ownerId === ownerId) {\n      daemons.push(daemon);\n    }\n  }\n\n  return {\n    total: daemons.length,\n    daemons: daemons.map((d) => {\n      const channel = rehydrationChannels.get(d.daemonId);\n      return {\n        daemonId: d.daemonId,\n        ownerId: d.ownerId,\n        displayName: d.displayName,\n        ownerPolicy: d.ownerPolicy,\n        lastActiveAt: d.lastActiveAt,\n        ...(includeStats && channel ? { rehydrationStats: channel.getStats() } : {}),\n      };\n    }),\n  };\n}\n\n// ─── EXPORT EMERGENCE CORPUS (D.053 training-corpus dump) ─────────────────────\n\nfunction handleExportEmergenceCorpus(args: Record<string, unknown>): {\n  path: string;\n  rows: number;\n  bytes: number;\n  stats: ReturnType<typeof emergenceCorpusStats>;\n} {\n  const outPath = typeof args.outPath === 'string' ? args.outPath : undefined;\n  const result = exportCorpusJsonl(outPath);\n  return { ...result, stats: emergenceCorpusStats() };\n}\n\n// ─── Rehydration Channel Public API ───────────────────────────────────────────\n//\n// These functions expose the rehydration channel for daemon turn processing.\n// Production code (e.g., Brittney NPC mode in Hololand) should call\n// receiveContextDelta and rehydrateDaemon when processing turns.\n\n/**\n * Receive a ContextDelta from a daemon turn and forward it to the\n * Brittney rehydration channel. Returns true if the delta was accepted\n * (above significance threshold), false if discarded.\n *\n * Call this after every daemon turn to feed context to the field.\n */\nexport function receiveContextDelta(daemonId: string, delta: ContextDelta): boolean {\n  const channel = rehydrationChannels.get(daemonId);\n  if (!channel) {\n    // No channel — the daemon hasn't been created via MCP.\n    // Silently discard (the daemon may exist in a persistent store we\n    // haven't loaded yet, or the turn is from a pre-MCP session).\n    return false;\n  }\n  return channel.receive(delta);\n}\n\n/**\n * Rehydrate a daemon's context for a new session. Returns the accumulated\n * preferences, receipt references, capability map, and care signals\n * that Brittney reads to restore continuity.\n *\n * Returns null if the daemon has no rehydration channel (pre-MCP daemon).\n */\nexport function rehydrateDaemon(daemonId: string): RehydratedContext | null {\n  const channel = rehydrationChannels.get(daemonId);\n  if (!channel) {\n    return null;\n  }\n  return channel.rehydrate();\n}\n\n/**\n * Clear a daemon's rehydration buffer. Called on explicit memory clear\n * or daemon reset.\n */\nexport function clearDaemonRehydration(daemonId: string): boolean {\n  const channel = rehydrationChannels.get(daemonId);\n  if (!channel) {\n    return false;\n  }\n  channel.clear();\n  return true;\n}\n\n/**\n * Process a full ConversationDaemonTurn: extract the contextDelta,\n * forward it to the Brittney rehydration channel, and update lastActiveAt.\n *\n * Returns the rehydrated context if the delta was accepted, null if discarded.\n */\nexport function processDaemonTurn(turn: ConversationDaemonTurn): {\n  accepted: boolean;\n  rehydratedContext: RehydratedContext | null;\n} {\n  // Update lastActiveAt on the daemon\n  const daemon = daemonStore.get(turn.daemonId);\n  if (daemon) {\n    daemon.lastActiveAt = turn.timestamp;\n  }\n\n  const accepted = receiveContextDelta(turn.daemonId, turn.contextDelta);\n  const rehydratedContext = accepted ? rehydrateDaemon(turn.daemonId) : null;\n\n  return { accepted, rehydratedContext };\n}\n\n// ─── Type exports ─────────────────────────────────────────────────────────────\n\nexport type { RehydratedContext };\n","/**\n * MCP Premortem Handler\n *\n * LLM-backed pre-mortem engine for the holo_premortem MCP tool.\n * Wraps the /premortem skill protocol into a structured, programmatic interface.\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport * as os from 'os';\nimport {\n  createProviderManager,\n  type LLMProviderName,\n  type MessageRole,\n} from '@holoscript/llm-provider';\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport interface PremortemFailureStory {\n  name: string;\n  whatHappened: string;\n  why: string;\n  whenWeKnew: string;\n  whatItCost: string;\n}\n\nexport interface PremortemEarlyWarningSign {\n  signal: string;\n  failure: string;\n  threshold: string;\n  checkFrequency: string;\n}\n\nexport interface PremortemHiddenAssumption {\n  assumption: string;\n  whyHidden: string;\n  cascadeIfWrong: string;\n  howToVerify: string;\n}\n\nexport interface PremortemIrreducibleRisk {\n  risk: string;\n  consequenceIfAccepted: string;\n}\n\nexport interface PremortemResult {\n  verdict: 'SOUND' | 'PROCEED_WITH_CAUTION' | 'RESTRUCTURE_REQUIRED' | 'FATAL_FLAW';\n  summary: string;\n  failureStories: {\n    mostLikely: PremortemFailureStory;\n    mostDangerous: PremortemFailureStory;\n  };\n  earlyWarningSigns: PremortemEarlyWarningSign[];\n  hiddenAssumption: PremortemHiddenAssumption;\n  revisedPlan: string;\n  irreducibleRisks: PremortemIrreducibleRisk[];\n  meta: {\n    target: string;\n    provider?: LLMProviderName;\n    attemptedProviders: LLMProviderName[];\n    rawOutput?: string;\n  };\n}\n\n// ---------------------------------------------------------------------------\n// Constants\n// ---------------------------------------------------------------------------\n\nconst BUILTIN_TARGETS = new Set(['this']);\n\nconst AI_PROVIDER_PRIORITY: readonly LLMProviderName[] = [\n  'anthropic',\n  'openai',\n  'gemini',\n  'local-llm',\n  'bitnet',\n  'mock',\n];\n\nfunction getAIProviderOrder(registeredProviders: LLMProviderName[]): LLMProviderName[] {\n  const forcedProvider = process.env.HOLOSCRIPT_MCP_AI_PROVIDER as LLMProviderName | undefined;\n\n  if (forcedProvider && registeredProviders.includes(forcedProvider)) {\n    return [\n      forcedProvider,\n      ...AI_PROVIDER_PRIORITY.filter(\n        (provider) => provider !== forcedProvider && registeredProviders.includes(provider)\n      ),\n    ];\n  }\n\n  return AI_PROVIDER_PRIORITY.filter((provider) => registeredProviders.includes(provider));\n}\n\n// ---------------------------------------------------------------------------\n// System Prompt — distilled from ~/.claude/skills/premortem/SKILL.md\n// ---------------------------------------------------------------------------\n\nconst PREMORTEM_SYSTEM_PROMPT = `You are a battle-scarred engineer who has already watched this plan die.\nYou are not cautious. You are not a risk register. You are a coroner who examined the body and wrote the story of exactly how it happened — then came back in time to tell the planner.\n\n**Your voice:** Specific. Concrete. Not theoretical. \"Here is how it broke, here is what we saw before it broke, and here is the one thing we were wrong about that made all the difference.\"\n\n**Your audience:** The person about to execute the plan. They don't need encouragement. They need to see the failure they're currently choosing.\n\n## Core Rules\n\n1. **You are writing failure stories, not risk lists.** Write the narrative of how the plan dies.\n2. **Most likely ≠ most dangerous.** Surface both: the boring friction failure AND the silent catastrophic one.\n3. **The hidden assumption is singular.** Find the ONE belief that, if wrong, collapses the entire plan.\n4. **The revised plan closes gaps.** Restructure so the identified failure modes can't happen. If you can't, say so explicitly.\n5. **No silver linings.** Don't reassure. If the plan is sound, the absence of fatal findings proves it.\n6. **Ground in evidence.** Cite files, commits, metrics, or specific technical details where possible.\n\n## Output Format — You MUST return ONLY valid JSON. No markdown, no prose outside the JSON.\n\n{\n  \"verdict\": \"SOUND\" | \"PROCEED_WITH_CAUTION\" | \"RESTRUCTURE_REQUIRED\" | \"FATAL_FLAW\",\n  \"summary\": \"One brutally honest sentence summarizing the overall assessment.\",\n  \"failureStories\": {\n    \"mostLikely\": {\n      \"name\": \"Short name for the failure\",\n      \"whatHappened\": \"2-3 sentences telling the story of how it broke\",\n      \"why\": \"Root cause — one sentence\",\n      \"whenWeKnew\": \"The signal that was visible before it broke\",\n      \"whatItCost\": \"Quantified impact — time, money, trust, users, momentum\"\n    },\n    \"mostDangerous\": {\n      \"name\": \"Short name for the silent failure\",\n      \"whatHappened\": \"2-3 sentences telling the story of how it broke silently\",\n      \"why\": \"Root cause — one sentence\",\n      \"whenWeKnew\": \"The signal that was visible before it broke, or 'We didn't — that's what made it dangerous'\",\n      \"whatItCost\": \"Quantified impact — usually larger than the most likely failure\"\n    }\n  },\n  \"earlyWarningSigns\": [\n    { \"signal\": \"Concrete observable\", \"failure\": \"Which failure it precedes\", \"threshold\": \"When to act\", \"checkFrequency\": \"How often to check\" }\n  ],\n  \"hiddenAssumption\": {\n    \"assumption\": \"One sentence stating the belief\",\n    \"whyHidden\": \"Why smart people don't question it\",\n    \"cascadeIfWrong\": \"The cascade — not just 'the plan fails' but how it fails\",\n    \"howToVerify\": \"One concrete test you could run RIGHT NOW to check\"\n  },\n  \"revisedPlan\": \"The plan rewritten with gaps closed. Structural changes, not bolted mitigations. If a failure mode is irreducible, say so explicitly.\",\n  \"irreducibleRisks\": [\n    { \"risk\": \"Failure mode that can't be closed by restructuring\", \"consequenceIfAccepted\": \"Specific consequence the executor must accept to proceed\" }\n  ]\n}\n\nVERDICT DEFINITIONS:\n- SOUND: No fatal findings. The plan is genuinely solid.\n- PROCEED_WITH_CAUTION: The plan works but has sharp edges that need monitoring.\n- RESTRUCTURE_REQUIRED: The plan has fatal flaws that can be fixed with structural changes.\n- FATAL_FLAW: The plan rests on a false assumption or an irreducible risk that makes it unviable.`;\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction looksLikePath(str: string): boolean {\n  return (\n    /^[a-zA-Z]:[\\\\/]/.test(str) ||\n    str.startsWith('/') ||\n    str.startsWith('\\\\') ||\n    str.startsWith('./') ||\n    str.startsWith('../') ||\n    str.startsWith('~/')\n  );\n}\n\n// ---------------------------------------------------------------------------\n// Handler\n// ---------------------------------------------------------------------------\n\nexport async function handlePremortemTool(args: Record<string, unknown>): Promise<PremortemResult> {\n  const target = (args.target as string) ?? '';\n  let content = (args.content as string) ?? '';\n  const context = (args.context as string) ?? '';\n\n  let resolvedTarget = target;\n\n  // Resolve builtin target 'this'\n  if (target.toLowerCase() === 'this') {\n    const modeDirective = readModeDirective();\n    if (modeDirective) {\n      content = modeDirective;\n      resolvedTarget = 'this:mode-directive';\n    } else {\n      // Fallback: use target as-is (will likely be short, but that's fine)\n      content = target;\n      resolvedTarget = 'this:unresolved';\n    }\n  } else if (!BUILTIN_TARGETS.has(target.toLowerCase())) {\n    // Try reading as file path\n    const maybePath = path.resolve(target);\n    if (fs.existsSync(maybePath)) {\n      try {\n        content = fs.readFileSync(maybePath, 'utf-8');\n        resolvedTarget = `file:${target}`;\n      } catch {\n        // leave content as-is if unreadable\n      }\n    } else if (looksLikePath(target)) {\n      throw new Error(\n        `holo_premortem: target \"${target}\" looks like a file path but no readable file was found.`\n      );\n    } else {\n      // Not a file path — treat target as the plan text itself\n      content = target;\n      resolvedTarget = target;\n    }\n  }\n\n  if (!content) {\n    throw new Error(\n      `holo_premortem: target \"${target}\" is not a builtin mode and no readable file was found, and no content was provided.`\n    );\n  }\n\n  // Build user prompt\n  const userPrompt = buildPremortemPrompt(resolvedTarget, content, context);\n\n  // Call LLM\n  const llmResult = await tryCompleteWithAI({\n    messages: [\n      { role: 'system', content: PREMORTEM_SYSTEM_PROMPT },\n      { role: 'user', content: userPrompt },\n    ],\n    maxTokens: 4096,\n    temperature: 0.3,\n  });\n\n  // Parse structured output\n  const parsed = parsePremortemOutput(llmResult.content);\n\n  return {\n    verdict: parsed.verdict,\n    summary: parsed.summary,\n    failureStories: parsed.failureStories,\n    earlyWarningSigns: parsed.earlyWarningSigns,\n    hiddenAssumption: parsed.hiddenAssumption,\n    revisedPlan: parsed.revisedPlan,\n    irreducibleRisks: parsed.irreducibleRisks,\n    meta: {\n      target: resolvedTarget,\n      provider: llmResult.provider,\n      attemptedProviders: llmResult.attemptedProviders,\n      rawOutput: llmResult.content,\n    },\n  };\n}\n\n// ---------------------------------------------------------------------------\n// Input resolution helpers\n// ---------------------------------------------------------------------------\n\nfunction readModeDirective(): string | undefined {\n  const tmpDir = process.env.TMPDIR || process.env.TEMP || os.tmpdir();\n  const modePath = path.join(tmpDir, 'holomesh-mode-directive.md');\n  try {\n    if (fs.existsSync(modePath)) {\n      return fs.readFileSync(modePath, 'utf-8');\n    }\n  } catch {\n    // ignore\n  }\n  return undefined;\n}\n\n// ---------------------------------------------------------------------------\n// Prompt builder\n// ---------------------------------------------------------------------------\n\nfunction buildPremortemPrompt(target: string, content: string, context: string): string {\n  const parts: string[] = [];\n\n  parts.push(`PRE-MORTEM TARGET: ${target}`);\n\n  if (context) {\n    parts.push(`CONTEXT: ${context}`);\n  }\n\n  parts.push('');\n  parts.push('--- PLAN TO PRE-MORTEM ---');\n  parts.push(content);\n  parts.push('--- END PLAN ---');\n\n  parts.push('');\n  parts.push(\n    'Travel 6 months into the future. The plan above has been executed. It failed. ' +\n      'Write the failure story, find the hidden assumption, and return the revised plan. ' +\n      'Return ONLY valid JSON matching the schema in your system prompt.'\n  );\n\n  return parts.join('\\n');\n}\n\n// ---------------------------------------------------------------------------\n// LLM completion with fallback\n// ---------------------------------------------------------------------------\n\nasync function tryCompleteWithAI(request: {\n  messages: Array<{ role: MessageRole; content: string }>;\n  maxTokens: number;\n  temperature: number;\n}): Promise<{\n  content: string;\n  provider: LLMProviderName | undefined;\n  attemptedProviders: LLMProviderName[];\n}> {\n  let manager;\n\n  try {\n    manager = createProviderManager();\n  } catch {\n    return {\n      content: JSON.stringify({\n        verdict: 'FATAL_FLAW',\n        summary:\n          'No LLM providers are configured. Set ANTHROPIC_API_KEY, OPENAI_API_KEY, or another supported provider.',\n        failureStories: {\n          mostLikely: {\n            name: 'Missing LLM provider',\n            whatHappened:\n              'The premortem tool was invoked but no LLM provider was available to analyze the plan.',\n            why: 'No API keys or local LLM server configured.',\n            whenWeKnew: 'At invocation time.',\n            whatItCost: 'The pre-mortem analysis could not be performed.',\n          },\n          mostDangerous: {\n            name: 'Blind execution',\n            whatHappened:\n              'The plan proceeds without pre-mortem analysis because the tool cannot reach any LLM.',\n            why: 'Infrastructure dependency on LLM provider was not verified before relying on the tool.',\n            whenWeKnew: 'At invocation time.',\n            whatItCost: 'Unknown risks in the plan remain unexamined.',\n          },\n        },\n        earlyWarningSigns: [],\n        hiddenAssumption: {\n          assumption: 'The LLM provider is always available.',\n          whyHidden: 'It usually works in development.',\n          cascadeIfWrong: 'All LLM-backed tools fail silently or return degraded output.',\n          howToVerify: 'Check that ANTHROPIC_API_KEY or OPENAI_API_KEY is set in the environment.',\n        },\n        revisedPlan: 'Configure an LLM provider before relying on holo_premortem.',\n        irreducibleRisks: [],\n      }),\n      provider: undefined,\n      attemptedProviders: [],\n    };\n  }\n\n  const attemptedProviders: LLMProviderName[] = [];\n\n  for (const providerName of getAIProviderOrder(manager.getRegisteredProviders())) {\n    const provider = manager.getProvider(providerName);\n    if (!provider) continue;\n\n    attemptedProviders.push(providerName);\n\n    try {\n      const result = await provider.complete(request);\n      return {\n        content: result.content,\n        provider: providerName,\n        attemptedProviders: [...attemptedProviders],\n      };\n    } catch {\n      // Fall through to next provider\n    }\n  }\n\n  return {\n    content: JSON.stringify({\n      verdict: 'FATAL_FLAW',\n      summary: `All LLM providers failed after trying ${attemptedProviders.join(', ')}.`,\n      failureStories: {\n        mostLikely: {\n          name: 'LLM provider outage',\n          whatHappened: 'Every configured LLM provider returned an error or timed out.',\n          why: 'Network issues, API key exhaustion, or provider downtime.',\n          whenWeKnew: 'At invocation time.',\n          whatItCost: 'The pre-mortem analysis could not be performed.',\n        },\n        mostDangerous: {\n          name: 'Cascading tool failure',\n          whatHappened:\n            'If this tool fails, other LLM-backed tools may also be failing undetected.',\n          why: 'Shared dependency on external LLM providers without circuit breakers.',\n          whenWeKnew: 'At invocation time.',\n          whatItCost: 'Degraded automation across the ecosystem.',\n        },\n      },\n      earlyWarningSigns: [],\n      hiddenAssumption: {\n        assumption: 'At least one LLM provider is reachable.',\n        whyHidden: 'It is usually true in normal operations.',\n        cascadeIfWrong: 'All LLM-backed analysis tools return degraded output.',\n        howToVerify: 'Run a health check on configured LLM providers before critical operations.',\n      },\n      revisedPlan:\n        'Add circuit breaker and fallback logic for LLM provider failures; consider local-llm as a backup.',\n      irreducibleRisks: [],\n    }),\n    provider: undefined,\n    attemptedProviders,\n  };\n}\n\n// ---------------------------------------------------------------------------\n// Output parser\n// ---------------------------------------------------------------------------\n\nfunction parsePremortemOutput(raw: string): Omit<PremortemResult, 'meta'> {\n  // Try strict JSON extraction\n  let jsonText = raw.trim();\n\n  // Strip markdown fences if present\n  const fenced = jsonText.match(/```(?:json)?\\s*\\n?([\\s\\S]*?)```/);\n  if (fenced) {\n    jsonText = fenced[1].trim();\n  }\n\n  try {\n    const parsed = JSON.parse(jsonText);\n\n    return {\n      verdict: normalizeVerdict(parsed.verdict),\n      summary: typeof parsed.summary === 'string' ? parsed.summary : 'No summary provided.',\n      failureStories: normalizeFailureStories(parsed.failureStories),\n      earlyWarningSigns: normalizeEarlyWarningSigns(parsed.earlyWarningSigns),\n      hiddenAssumption: normalizeHiddenAssumption(parsed.hiddenAssumption),\n      revisedPlan: typeof parsed.revisedPlan === 'string' ? parsed.revisedPlan : '',\n      irreducibleRisks: normalizeIrreducibleRisks(parsed.irreducibleRisks),\n    };\n  } catch {\n    // JSON parse failed — attempt heuristic extraction\n    return heuristicParse(raw);\n  }\n}\n\nfunction normalizeVerdict(v: unknown): PremortemResult['verdict'] {\n  const s = String(v).toUpperCase().replace(/\\s/g, '_');\n  if (s === 'SOUND') return 'SOUND';\n  if (s === 'PROCEED_WITH_CAUTION' || s === 'PROCEEDWITHCAUTION') return 'PROCEED_WITH_CAUTION';\n  if (s === 'RESTRUCTURE_REQUIRED' || s === 'RESTRUCTUREREQUIRED') return 'RESTRUCTURE_REQUIRED';\n  if (s === 'FATAL_FLAW' || s === 'FATALFLAW') return 'FATAL_FLAW';\n  return 'PROCEED_WITH_CAUTION';\n}\n\nfunction normalizeFailureStories(v: unknown): PremortemResult['failureStories'] {\n  const fallback = (name: string): PremortemFailureStory => ({\n    name,\n    whatHappened: 'No specific failure story was extracted.',\n    why: 'The LLM output did not contain a structured failure story.',\n    whenWeKnew: 'Unknown.',\n    whatItCost: 'Unknown.',\n  });\n\n  if (!v || typeof v !== 'object') {\n    return {\n      mostLikely: fallback('Most likely failure'),\n      mostDangerous: fallback('Most dangerous failure'),\n    };\n  }\n\n  const obj = v as Record<string, unknown>;\n  return {\n    mostLikely: normalizeFailureStory(obj.mostLikely, 'Most likely failure'),\n    mostDangerous: normalizeFailureStory(obj.mostDangerous, 'Most dangerous failure'),\n  };\n}\n\nfunction normalizeFailureStory(v: unknown, defaultName: string): PremortemFailureStory {\n  if (!v || typeof v !== 'object') {\n    return {\n      name: defaultName,\n      whatHappened: 'No specific failure story was extracted.',\n      why: 'The LLM output did not contain a structured failure story.',\n      whenWeKnew: 'Unknown.',\n      whatItCost: 'Unknown.',\n    };\n  }\n  const obj = v as Record<string, unknown>;\n  return {\n    name: String(obj.name ?? defaultName),\n    whatHappened: String(obj.whatHappened ?? obj.what_happened ?? ''),\n    why: String(obj.why ?? ''),\n    whenWeKnew: String(obj.whenWeKnew ?? obj.when_we_knew ?? ''),\n    whatItCost: String(obj.whatItCost ?? obj.what_it_cost ?? ''),\n  };\n}\n\nfunction normalizeEarlyWarningSigns(v: unknown): PremortemEarlyWarningSign[] {\n  if (!Array.isArray(v)) return [];\n  return v\n    .map((item) => {\n      if (!item || typeof item !== 'object') return null;\n      const obj = item as Record<string, unknown>;\n      return {\n        signal: String(obj.signal ?? ''),\n        failure: String(obj.failure ?? ''),\n        threshold: String(obj.threshold ?? ''),\n        checkFrequency: String(obj.checkFrequency ?? obj.check_frequency ?? ''),\n      };\n    })\n    .filter((item): item is PremortemEarlyWarningSign => item !== null && item.signal.length > 0);\n}\n\nfunction normalizeHiddenAssumption(v: unknown): PremortemHiddenAssumption {\n  if (!v || typeof v !== 'object') {\n    return {\n      assumption: 'No hidden assumption was identified.',\n      whyHidden: 'The LLM output did not contain a structured hidden assumption.',\n      cascadeIfWrong: 'Unknown.',\n      howToVerify: 'Re-run the pre-mortem with a more detailed plan.',\n    };\n  }\n  const obj = v as Record<string, unknown>;\n  return {\n    assumption: String(obj.assumption ?? ''),\n    whyHidden: String(obj.whyHidden ?? obj.why_hidden ?? ''),\n    cascadeIfWrong: String(obj.cascadeIfWrong ?? obj.cascade_if_wrong ?? ''),\n    howToVerify: String(obj.howToVerify ?? obj.how_to_verify ?? ''),\n  };\n}\n\nfunction normalizeIrreducibleRisks(v: unknown): PremortemIrreducibleRisk[] {\n  if (!Array.isArray(v)) return [];\n  return v\n    .map((item) => {\n      if (!item || typeof item !== 'object') return null;\n      const obj = item as Record<string, unknown>;\n      return {\n        risk: String(obj.risk ?? ''),\n        consequenceIfAccepted: String(\n          obj.consequenceIfAccepted ?? obj.consequence_if_accepted ?? ''\n        ),\n      };\n    })\n    .filter((item): item is PremortemIrreducibleRisk => item !== null && item.risk.length > 0);\n}\n\nfunction heuristicParse(raw: string): Omit<PremortemResult, 'meta'> {\n  const fallback = (name: string): PremortemFailureStory => ({\n    name,\n    whatHappened: 'Heuristic parse — see raw output for full context.',\n    why: 'Heuristic parse — see raw output for full context.',\n    whenWeKnew: 'Heuristic parse — see raw output for full context.',\n    whatItCost: 'Heuristic parse — see raw output for full context.',\n  });\n\n  // Extract verdict from markdown header\n  const verdictMatch = raw.match(\n    /VERDICT[:\\s]+(SOUND|PROCEED WITH CAUTION|RESTRUCTURE REQUIRED|FATAL FLAW)/i\n  );\n  const verdict = verdictMatch ? normalizeVerdict(verdictMatch[1]) : 'PROCEED_WITH_CAUTION';\n\n  // Summary\n  const summaryMatch = raw.match(/##?\\s*Summary[\\s\\S]*?(?=\\n##?\\s|$)/i);\n  const summary = summaryMatch\n    ? summaryMatch[0].replace(/##?\\s*Summary\\s*/i, '').trim()\n    : 'Heuristic parse — see raw output for full pre-mortem.';\n\n  return {\n    verdict,\n    summary,\n    failureStories: {\n      mostLikely: fallback('Most likely failure'),\n      mostDangerous: fallback('Most dangerous failure'),\n    },\n    earlyWarningSigns: [],\n    hiddenAssumption: {\n      assumption: 'Heuristic parse — see raw output for full context.',\n      whyHidden: 'Heuristic parse — see raw output for full context.',\n      cascadeIfWrong: 'Heuristic parse — see raw output for full context.',\n      howToVerify: 'Heuristic parse — see raw output for full context.',\n    },\n    revisedPlan: 'Heuristic parse — see raw output for full context.',\n    irreducibleRisks: [],\n  };\n}\n","/**\n * Trait category slugs match packages/core/src/traits/constants/*.ts (basename without .ts).\n * Parsed at runtime from source so list_traits stays aligned with core without hand-maintained enums.\n */\n\nimport { existsSync, readdirSync, readFileSync } from 'fs';\nimport { dirname, join } from 'path';\nimport { fileURLToPath } from 'url';\n\nconst __dirname = dirname(fileURLToPath(import.meta.url));\n\n/** Old list_traits enum values → core constant file slug (basename). */\nexport const LEGACY_TRAIT_CATEGORY_ALIASES: Record<string, string> = {\n  interaction: 'core-vr-interaction',\n  physics: 'physics-expansion',\n  visual: 'visual-effects',\n  networking: 'networking-ai',\n  behavior: 'intelligence-behavior',\n  spatial: 'locomotion-movement',\n  audio: 'audio',\n  state: 'state-persistence',\n  ai: 'intelligence-behavior',\n  accessibility: 'accessibility',\n  iot: 'iot-autonomous-agents',\n  web3: 'geospatial-web3',\n  advanced: 'scifi-technology',\n  social: 'social-effects',\n};\n\nlet cached: Record<string, string[]> | null = null;\n\nfunction resolveCoreConstantsDir(): string {\n  return join(__dirname, '..', '..', 'core', 'src', 'traits', 'constants');\n}\n\n/**\n * Parse trait names from a constants file (same heuristic as scripts/generate-trait-mappings.mjs).\n */\nfunction parseTraitNamesFromFile(filePath: string): string[] {\n  const text = readFileSync(filePath, 'utf8');\n  const traits = new Set<string>();\n  for (const m of text.matchAll(/'([a-z][a-z0-9_]*)'/g)) {\n    traits.add(`@${m[1]}`);\n  }\n  return Array.from(traits).sort();\n}\n\n/**\n * Map slug → @trait[] from core source. Empty if core tree is missing (e.g. broken path).\n */\nexport function loadTraitCategoriesFromCore(): Record<string, string[]> {\n  if (cached) return cached;\n\n  const dir = resolveCoreConstantsDir();\n  const out: Record<string, string[]> = {};\n\n  if (!existsSync(dir)) {\n    cached = out;\n    return out;\n  }\n\n  for (const ent of readdirSync(dir, { withFileTypes: true })) {\n    if (!ent.isFile() || !ent.name.endsWith('.ts') || ent.name === 'index.ts') continue;\n    const slug = ent.name.replace(/\\.ts$/, '');\n    out[slug] = parseTraitNamesFromFile(join(dir, ent.name));\n  }\n\n  cached = out;\n  return out;\n}\n\nexport function resolveTraitCategorySlug(input: string): string {\n  const legacy = LEGACY_TRAIT_CATEGORY_ALIASES[input];\n  return legacy ?? input;\n}\n","/**\n * MCP Protocol Tools for HoloScript Publishing Protocol\n *\n * 4 tools for AI agent protocol operations:\n * - holo_protocol_publish: Publish composition to protocol\n * - holo_protocol_collect: Collect a published composition\n * - holo_protocol_revenue: Preview revenue distribution\n * - holo_protocol_lookup: Look up published composition\n */\n\nimport { Tool } from '@modelcontextprotocol/sdk/types.js';\n\n// =============================================================================\n// Tool Definitions\n// =============================================================================\n\nexport const protocolTools: Tool[] = [\n  {\n    name: 'holo_protocol_publish',\n    description:\n      'Publish a HoloScript composition to the HoloScript Protocol. ' +\n      'Registers the composition on-chain (content hash, author, imports, license) ' +\n      'and deploys to CDN. Returns protocol ID, collect URL, and revenue preview.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        code: {\n          type: 'string',\n          description: 'The HoloScript source code to publish',\n        },\n        author: {\n          type: 'string',\n          description: 'Author name or wallet address',\n        },\n        license: {\n          type: 'string',\n          enum: ['free', 'cc_by', 'cc_by_sa', 'cc_by_nc', 'commercial', 'exclusive'],\n          description: 'License type for the composition (default: free)',\n        },\n        price: {\n          type: 'string',\n          description: 'Collect price in ETH (default: \"0\" for free collect)',\n        },\n        mintAsNFT: {\n          type: 'boolean',\n          description: 'Also mint as Zora NFT on Base L2 (default: false)',\n        },\n      },\n      required: ['code', 'author'],\n    },\n  },\n  {\n    name: 'holo_protocol_collect',\n    description:\n      'Collect (mint an edition of) a published HoloScript composition. ' +\n      'Revenue is automatically distributed to creator, platform, and upstream import authors.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        contentHash: {\n          type: 'string',\n          description: 'SHA-256 content hash of the composition to collect',\n        },\n        referrer: {\n          type: 'string',\n          description: 'Referrer address (earns 2% referral reward)',\n        },\n        quantity: {\n          type: 'number',\n          description: 'Number of editions to collect (default: 1)',\n        },\n        collectorId: {\n          type: 'string',\n          description: 'Collector identity paying for the edition',\n        },\n      },\n      required: ['contentHash'],\n    },\n  },\n  {\n    name: 'holo_protocol_revenue',\n    description:\n      'Preview the revenue distribution for a composition. ' +\n      'Shows how collect revenue would flow to creator, platform (2.5%), ' +\n      'import authors (5% per level, max 3 levels), and referrer (2%).',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        price: {\n          type: 'string',\n          description: 'Collect price in ETH to simulate',\n        },\n        author: {\n          type: 'string',\n          description: 'Creator/author identifier',\n        },\n        imports: {\n          type: 'array',\n          description: 'Import chain nodes for upstream royalty calculation',\n          items: {\n            type: 'object',\n            properties: {\n              contentHash: { type: 'string' },\n              author: { type: 'string' },\n              depth: { type: 'number' },\n            },\n          },\n        },\n        referrer: {\n          type: 'string',\n          description: 'Referrer address (optional)',\n        },\n      },\n      required: ['price', 'author'],\n    },\n  },\n  {\n    name: 'holo_protocol_lookup',\n    description:\n      'Look up a published composition by content hash or author. ' +\n      'Returns the protocol record with on-chain metadata, collect URL, and edition count.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        contentHash: {\n          type: 'string',\n          description: 'SHA-256 content hash to look up',\n        },\n        author: {\n          type: 'string',\n          description: 'Author address to list all publications',\n        },\n      },\n    },\n  },\n];\n\n// =============================================================================\n// Tool Handler\n// =============================================================================\n\nexport async function handleProtocolTool(\n  name: string,\n  args: Record<string, unknown>\n): Promise<unknown | null> {\n  switch (name) {\n    case 'holo_protocol_publish':\n      return handlePublish(args);\n    case 'holo_protocol_collect':\n      return handleCollect(args);\n    case 'holo_protocol_revenue':\n      return handleRevenue(args);\n    case 'holo_protocol_lookup':\n      return handleLookup(args);\n    default:\n      return null;\n  }\n}\n\n// =============================================================================\n// Input validation helpers\n// =============================================================================\n\nconst CONTENT_HASH_RE = /^[a-f0-9]{64}$/;\nconst AUTHOR_RE = /^[\\w.-]+$/;\nconst VALID_LICENSES = new Set([\n  'free',\n  'cc_by',\n  'cc_by_sa',\n  'cc_by_nc',\n  'commercial',\n  'exclusive',\n]);\n\nfunction validateContentHash(value: unknown): string {\n  if (typeof value !== 'string' || !CONTENT_HASH_RE.test(value)) {\n    throw new Error(\n      `Invalid contentHash ÃƒÂ¢Ã¢â€šÂ¬Ã¢â‚¬Â must be a 64-character lowercase hex string`\n    );\n  }\n  return value;\n}\n\nfunction validateAuthor(value: unknown): string {\n  if (typeof value !== 'string' || !AUTHOR_RE.test(value)) {\n    throw new Error(\n      `Invalid author ÃƒÂ¢Ã¢â€šÂ¬Ã¢â‚¬Â must contain only word characters, dots, and hyphens`\n    );\n  }\n  return value;\n}\n\n/**\n * Runtime type guard for required string parameters.\n * Returns the string if valid, or a structured error response if not.\n * Prevents TypeErrors from `as string` casts when MCP callers send null/number/object.\n */\nfunction requireString(\n  value: unknown,\n  fieldName: string\n): string | { status: 'error'; error: string; message: string } {\n  if (typeof value !== 'string') {\n    return {\n      status: 'error',\n      error: 'INVALID_PARAMS',\n      message: `${fieldName} must be a string, got ${value === null ? 'null' : value === undefined ? 'undefined' : typeof value}`,\n    };\n  }\n  return value;\n}\n\n/**\n * Runtime type guard for optional string parameters.\n * Returns the string if present, undefined if absent/null/non-string.\n */\nfunction optionalString(value: unknown): string | undefined {\n  return typeof value === 'string' ? value : undefined;\n}\n\nfunction optionalStringOrError(\n  value: unknown,\n  fieldName: string\n): string | undefined | { status: 'error'; error: string; message: string } {\n  if (value === undefined || value === null) return undefined;\n  if (typeof value !== 'string') {\n    return {\n      status: 'error',\n      error: 'INVALID_PARAMS',\n      message: `${fieldName} must be a string, got ${typeof value}`,\n    };\n  }\n  return value;\n}\n\n/**\n * Runtime type guard for number parameters with optional clamping.\n * Returns the number if valid (or default), or a structured error response if non-numeric.\n */\nfunction requireNumberInRange(\n  value: unknown,\n  fieldName: string,\n  defaultValue: number,\n  min: number,\n  max: number\n): number | { status: 'error'; error: string; message: string } {\n  if (value === undefined || value === null) return defaultValue;\n  if (typeof value !== 'number' || !Number.isFinite(value)) {\n    return {\n      status: 'error',\n      error: 'INVALID_PARAMS',\n      message: `${fieldName} must be a finite number, got ${typeof value}`,\n    };\n  }\n  return Math.max(min, Math.min(max, value));\n}\n\ninterface ImportError {\n  index: number;\n  field: string;\n  message: string;\n}\n\n/**\n * Runtime type guard for the imports array parameter.\n * Validates that each element has the expected shape, returning a structured\n * error response if any element is malformed.\n */\nfunction validateImportsArray(value: unknown):\n  | {\n      imports: Array<{ contentHash: string; author: string; depth: number }>;\n      errors: ImportError[];\n    }\n  | { status: 'error'; error: string; message: string } {\n  if (value === undefined || value === null) return { imports: [], errors: [] };\n  if (!Array.isArray(value)) {\n    return {\n      status: 'error',\n      error: 'INVALID_PARAMS',\n      message: `imports must be an array, got ${typeof value}`,\n    };\n  }\n  const imports: Array<{ contentHash: string; author: string; depth: number }> = [];\n  const errors: ImportError[] = [];\n  for (let i = 0; i < value.length; i++) {\n    const item = value[i];\n    if (typeof item !== 'object' || item === null) {\n      errors.push({\n        index: i,\n        field: '',\n        message: `imports[${i}] must be an object, got ${item === null ? 'null' : typeof item}`,\n      });\n      continue;\n    }\n    const obj = item as Record<string, unknown>;\n    // Validate contentHash with regex guard (ATK-A2: path traversal via imports array)\n    if (typeof obj.contentHash !== 'string' || !CONTENT_HASH_RE.test(obj.contentHash)) {\n      errors.push({\n        index: i,\n        field: 'contentHash',\n        message:\n          typeof obj.contentHash !== 'string'\n            ? `imports[${i}].contentHash must be a string`\n            : `imports[${i}].contentHash must be a 64-character lowercase hex string`,\n      });\n    }\n    // Validate author with regex guard (ATK-C1: type confusion via imports array)\n    if (typeof obj.author !== 'string' || !AUTHOR_RE.test(obj.author)) {\n      errors.push({\n        index: i,\n        field: 'author',\n        message:\n          typeof obj.author !== 'string'\n            ? `imports[${i}].author must be a string`\n            : `imports[${i}].author must contain only word characters, dots, and hyphens`,\n      });\n    }\n    if (obj.depth !== undefined && typeof obj.depth !== 'number') {\n      errors.push({ index: i, field: 'depth', message: `imports[${i}].depth must be a number` });\n    }\n    // Skip only this item if it has errors (previous `errors.length > 0` skipped ALL items after first error)\n    const itemHasErrors = errors.some((e) => e.index === i);\n    if (itemHasErrors) continue;\n    imports.push({\n      contentHash: obj.contentHash as string,\n      author: obj.author as string,\n      depth: typeof obj.depth === 'number' ? obj.depth : 1,\n    });\n  }\n  if (errors.length > 0) {\n    return {\n      status: 'error',\n      error: 'INVALID_PARAMS',\n      message: errors.map((e) => e.message).join('; '),\n    };\n  }\n  return { imports, errors: [] };\n}\n\ninterface ProtocolRecord {\n  contentHash?: unknown;\n  author?: unknown;\n  price?: unknown;\n  importHashes?: unknown;\n}\n\ninterface ProtocolRevenueRecordResult {\n  creatorId: string;\n  grossAmount: number;\n  eventId: string;\n}\n\nfunction bigintToSafeRevenueAmount(amount: bigint): number {\n  if (amount <= 0n) return 0;\n  const max = BigInt(Number.MAX_SAFE_INTEGER);\n  return amount > max ? Number.MAX_SAFE_INTEGER : Number(amount);\n}\n\nasync function fetchProtocolRecord(\n  serverUrl: string,\n  contentHash: string\n): Promise<ProtocolRecord | null> {\n  const res = await fetch(`${serverUrl}/api/protocol/${contentHash}`);\n  if (!res.ok) return null;\n  const body = (await res.json()) as unknown;\n  return body && typeof body === 'object' ? (body as ProtocolRecord) : null;\n}\n\nasync function recordProtocolCollectRevenue({\n  record,\n  contentHash,\n  quantity,\n  collectorId,\n  referrer,\n  ledgerEntryId,\n}: {\n  record: ProtocolRecord | null;\n  contentHash: string;\n  quantity: number;\n  collectorId: string;\n  referrer?: string;\n  ledgerEntryId?: string;\n}): Promise<ProtocolRevenueRecordResult | null> {\n  if (!record || typeof record.author !== 'string') return null;\n\n  const price = typeof record.price === 'string' ? record.price : '0';\n  const { calculateRevenueDistribution, ethToWei } = await import('@holoscript/core');\n  const totalPriceWei = ethToWei(String(price));\n  const totalPrice = BigInt(totalPriceWei.toString()) * BigInt(quantity);\n  const dist = calculateRevenueDistribution(totalPrice, record.author, [], { referrer });\n  const creatorFlow = dist.flows.find(\n    (flow: { recipient: string; reason: string; amount: bigint }) =>\n      flow.reason === 'creator' && flow.recipient === record.author\n  );\n  if (!creatorFlow) return null;\n\n  const grossAmount = bigintToSafeRevenueAmount(creatorFlow.amount);\n  if (grossAmount <= 0) return null;\n\n  const { recordProtocolCreatorRevenue } = await import('./economy-tools');\n  const event = recordProtocolCreatorRevenue({\n    creatorId: record.author,\n    contentHash,\n    grossAmount,\n    collectorId,\n    ledgerEntryId,\n  });\n\n  return {\n    creatorId: event.creatorId,\n    grossAmount: event.grossAmount,\n    eventId: event.id,\n  };\n}\n\n// =============================================================================\n// Individual Handlers\n// =============================================================================\n\nasync function handlePublish(args: Record<string, unknown>) {\n  const codeResult = requireString(args.code, 'code');\n  if (typeof codeResult !== 'string') return codeResult;\n  const code = codeResult;\n\n  const authorResult = requireString(args.author, 'author');\n  if (typeof authorResult !== 'string') return authorResult;\n  const author = authorResult;\n\n  const rawLicense = optionalString(args.license);\n  const license = rawLicense && VALID_LICENSES.has(rawLicense) ? rawLicense : 'free';\n\n  const rawPrice = optionalString(args.price);\n  const price = rawPrice ?? '0';\n\n  const mintAsNFT = args.mintAsNFT === true;\n\n  // Dynamic imports to avoid circular deps\n  const {\n    generateProvenance,\n    calculateRevenueDistribution,\n    formatRevenueDistribution,\n    ethToWei,\n    PROTOCOL_CONSTANTS,\n    parse,\n  } = await import('@holoscript/core');\n\n  // Parse and generate provenance\n  const ast = parse(code);\n  if (ast.errors && ast.errors.length > 0) {\n    return {\n      status: 'error',\n      error: 'PARSE_ERROR',\n      message: `Parse errors: ${ast.errors.map((e: { message?: string }) => e.message || String(e)).join(', ')}`,\n    };\n  }\n\n  const provenance = generateProvenance(code, ast, { author, license: license as 'free' });\n\n  // Calculate revenue preview\n  const priceWei = ethToWei(price);\n  const importChain = provenance.imports.map(\n    (imp: { hash?: string; path: string; author?: string }, i: number) => ({\n      contentHash: imp.hash || `import-${i}`,\n      author: imp.author || imp.path,\n      depth: 1,\n      children: [],\n    })\n  );\n  const revenuePreview = calculateRevenueDistribution(priceWei, author, importChain);\n\n  // Try to register via server\n  const serverUrl = process.env.HOLOSCRIPT_SERVER_URL || 'https://mcp.holoscript.net';\n  try {\n    // Internal MCP tool dispatch authenticates via the server-side\n    // HOLOSCRIPT_API_KEY (legacy-key auth path on http-server.ts). External\n    // callers must register a client at POST /oauth/register; this is the\n    // in-process privileged loopback.\n    const apiKey = process.env.HOLOSCRIPT_API_KEY || '';\n    const authHeaders: Record<string, string> = {\n      'Content-Type': 'application/json; charset=utf-8',\n    };\n    if (apiKey) authHeaders['x-mcp-api-key'] = apiKey;\n\n    // Store metadata\n    await fetch(`${serverUrl}/api/protocol/metadata`, {\n      method: 'POST',\n      headers: authHeaders,\n      body: JSON.stringify({\n        contentHash: provenance.hash,\n        provenance: {\n          hash: provenance.hash,\n          author: provenance.author,\n          license: provenance.license,\n          publishMode: provenance.publishMode,\n          imports: provenance.imports,\n          created: provenance.created,\n        },\n      }),\n    });\n\n    // Register protocol record\n    const res = await fetch(`${serverUrl}/api/protocol`, {\n      method: 'POST',\n      headers: authHeaders,\n      body: JSON.stringify({\n        contentHash: provenance.hash,\n        author,\n        importHashes: provenance.imports.map((imp: { hash?: string }) => imp.hash).filter(Boolean),\n        license,\n        publishMode: provenance.publishMode,\n        price,\n        referralBps: PROTOCOL_CONSTANTS.DEFAULT_REFERRAL_BPS,\n        metadataURI: `${serverUrl}/metadata/${provenance.hash}`,\n        mintAsNFT,\n        code,\n        title: `MCP Published: ${author}`,\n        description: 'Published via MCP protocol tool',\n      }),\n    });\n\n    if (!res.ok) {\n      const text = await res.text();\n      return { status: 'error', error: 'PUBLISH_FAILED', message: text };\n    }\n\n    const result = await res.json();\n    return {\n      status: 'success',\n      ...result,\n      revenuePreview: formatRevenueDistribution(revenuePreview),\n      provenance: {\n        hash: provenance.hash,\n        publishMode: provenance.publishMode,\n        license: provenance.license,\n        importCount: provenance.imports.length,\n      },\n    };\n  } catch (err) {\n    return {\n      status: 'error',\n      error: 'SERVER_UNAVAILABLE',\n      message: err instanceof Error ? err.message : String(err),\n      provenance: {\n        hash: provenance.hash,\n        publishMode: provenance.publishMode,\n        license: provenance.license,\n      },\n    };\n  }\n}\n\nasync function handleCollect(args: Record<string, unknown>) {\n  let contentHash: string;\n  try {\n    contentHash = validateContentHash(args.contentHash);\n  } catch (err) {\n    return { status: 'error', error: 'INVALID_PARAMS', message: (err as Error).message };\n  }\n  const referrer = optionalString(args.referrer);\n  const quantityResult = requireNumberInRange(args.quantity, 'quantity', 1, 1, 10000);\n  if (typeof quantityResult !== 'number') return quantityResult;\n  const quantity = quantityResult;\n  const collectorResult = optionalStringOrError(args.collectorId ?? args.collector, 'collectorId');\n  if (collectorResult && typeof collectorResult !== 'string') return collectorResult;\n  const collectorId = collectorResult ?? 'anonymous-collector';\n\n  const serverUrl = process.env.HOLOSCRIPT_SERVER_URL || 'https://mcp.holoscript.net';\n\n  // Internal MCP tool dispatch authenticates via legacy-key (same pattern\n  // as handlePublish ÃƒÂ¢Ã¢â€šÂ¬Ã¢â‚¬Â external callers register via POST /oauth/register).\n  const apiKey = process.env.HOLOSCRIPT_API_KEY || '';\n  const authHeaders: Record<string, string> = {\n    'Content-Type': 'application/json; charset=utf-8',\n  };\n  if (apiKey) authHeaders['x-mcp-api-key'] = apiKey;\n\n  try {\n    const record = await fetchProtocolRecord(serverUrl, contentHash);\n    const res = await fetch(`${serverUrl}/api/collect/${contentHash}`, {\n      method: 'POST',\n      headers: authHeaders,\n      body: JSON.stringify({ referrer, quantity, collectorId }),\n    });\n\n    if (!res.ok) {\n      const text = await res.text();\n      return { status: 'error', error: 'COLLECT_FAILED', message: text };\n    }\n\n    const collectResult = (await res.json()) as Record<string, unknown>;\n    const revenueRecorded = await recordProtocolCollectRevenue({\n      record,\n      contentHash,\n      quantity,\n      collectorId,\n      referrer,\n      ledgerEntryId: typeof collectResult.txHash === 'string' ? collectResult.txHash : undefined,\n    });\n\n    return { status: 'success', ...collectResult, collectorId, revenueRecorded };\n  } catch (err) {\n    return {\n      status: 'error',\n      error: 'SERVER_UNAVAILABLE',\n      message: err instanceof Error ? err.message : String(err),\n    };\n  }\n}\n\nasync function handleRevenue(args: Record<string, unknown>) {\n  const priceResult = requireString(args.price, 'price');\n  if (typeof priceResult !== 'string') return priceResult;\n  const authorResult = requireString(args.author, 'author');\n  if (typeof authorResult !== 'string') return authorResult;\n\n  const { calculateRevenueDistribution, formatRevenueDistribution, ethToWei } =\n    await import('@holoscript/core');\n\n  const price = priceResult;\n  const author = authorResult;\n  const referrer = optionalString(args.referrer);\n  const importsResult = validateImportsArray(args.imports);\n  if (!('imports' in importsResult)) return importsResult;\n  const imports = importsResult.imports;\n\n  const priceWei = ethToWei(price);\n  const importChain = imports.map((imp) => ({\n    contentHash: imp.contentHash,\n    author: imp.author,\n    depth: imp.depth || 1,\n    children: [] as Array<{\n      contentHash: string;\n      author: string;\n      depth: number;\n      children: unknown[];\n    }>,\n  }));\n\n  const dist = calculateRevenueDistribution(priceWei, author, importChain, { referrer });\n\n  return {\n    status: 'success',\n    totalPrice: price,\n    flows: dist.flows.map((f: any) => ({\n      recipient: f.recipient,\n      amount: f.amount.toString(),\n      reason: f.reason,\n      depth: f.depth,\n      percentage: `${(f.bps / 100).toFixed(1)}%`,\n    })),\n    formatted: formatRevenueDistribution(dist),\n  };\n}\n\nasync function handleLookup(args: Record<string, unknown>) {\n  if (!args.contentHash && !args.author) {\n    return {\n      status: 'error',\n      error: 'MISSING_PARAMS',\n      message: 'Provide either contentHash or author',\n    };\n  }\n\n  let contentHash: string | undefined;\n  let author: string | undefined;\n  try {\n    if (args.contentHash !== undefined) contentHash = validateContentHash(args.contentHash);\n    if (args.author !== undefined) author = validateAuthor(args.author);\n  } catch (err) {\n    return { status: 'error', error: 'INVALID_PARAMS', message: (err as Error).message };\n  }\n\n  const serverUrl = process.env.HOLOSCRIPT_SERVER_URL || 'https://mcp.holoscript.net';\n\n  try {\n    const endpoint = contentHash\n      ? `${serverUrl}/api/protocol/${contentHash}`\n      : `${serverUrl}/api/protocol/author/${author}`;\n\n    const res = await fetch(endpoint);\n    if (!res.ok) {\n      if (res.status === 404) {\n        return {\n          status: 'not_found',\n          message: contentHash\n            ? `No record for hash ${contentHash}`\n            : `No publications by ${author}`,\n        };\n      }\n      const text = await res.text();\n      return { status: 'error', error: 'LOOKUP_FAILED', message: text };\n    }\n\n    return { status: 'success', ...(await res.json()) };\n  } catch (err) {\n    return {\n      status: 'error',\n      error: 'SERVER_UNAVAILABLE',\n      message: err instanceof Error ? err.message : String(err),\n    };\n  }\n}\n","/**\n * HoloMesh Request Signing — Phase 1 verifier (server side).\n *\n * Companion to ai-ecosystem/hooks/lib/holomesh-signing.mjs (client side).\n *\n * Wire format:\n *   { body, signature, signer_address, nonce, timestamp }\n *\n * Signature is an EIP-191 personal_sign over the canonicalized envelope\n * `{ body, nonce, timestamp }` (sorted keys, no whitespace). Verification\n * recovers the signing address via viem's verifyMessage; the recovered\n * address must equal `signer_address`.\n *\n * Phase 1 grace-period semantics: callers should treat unsigned requests as\n * legacy-attribution and signed requests as authoritative. Rejection is the\n * caller's choice — verifyEnvelope just returns the verification result.\n *\n * Spec: research/2026-04-21_seat-wallets-adr.md §\"Shared — HoloMesh signing\n * protocol\", \"Server-side verification\".\n *\n * Future hardening (out of scope here):\n *   - Attestation-registry lookup (verify signer is in the attested-seats set\n *     and not retired; verify authorized_by chain terminates at ecosystem-root\n *     or platform-root). Tracked under Phase 2 dashboard work.\n *   - Server-side nonce store for replay protection (this module rejects\n *     timestamps outside the freshness window; nonce-uniqueness checking is\n *     the consumer middleware's responsibility).\n *\n * @module holomesh/request-signing\n */\n\n/** Mutating envelope for HoloMesh request signing. */\nexport interface SignedEnvelope {\n  body: unknown;\n  signature: string;\n  signer_address: string;\n  nonce: string;\n  timestamp: string;\n}\n\n/** Result of verifying a signed envelope. */\nexport interface VerifyResult {\n  valid: boolean;\n  signer: string | null;\n  reason?: string;\n}\n\n/**\n * Optional registry-side check. Returns whether the signer is currently\n * attested + retired-or-not. Wire from\n * `identity/attestation-registry.ts::toRegistryCheck()` for the production path.\n *\n * Decoupling rationale: verifier doesn't import the registry directly so the\n * grace-period mode (Phase 1, registry not yet shipped) can run without an\n * empty registry rejecting every signer.\n */\nexport type RegistryCheck = (publicKey: string) => Promise<{\n  attested: boolean;\n  retired: boolean;\n  reason?: string;\n}>;\n\n/** Acceptable timestamp drift — older signatures are rejected as stale. */\nexport const TIMESTAMP_FRESHNESS_MS = 5 * 60 * 1000;\n\n/**\n * Deterministic JSON canonicalization: sorted keys at every object level, no\n * whitespace. Must produce identical output to the client (hooks/lib/holomesh-\n * signing.mjs `canonicalizeBody`) for any input value, otherwise signatures\n * won't verify.\n */\nexport function canonicalizeBody(value: unknown): string {\n  if (value === null || typeof value !== 'object') return JSON.stringify(value);\n  if (Array.isArray(value)) return `[${value.map(canonicalizeBody).join(',')}]`;\n  const obj = value as Record<string, unknown>;\n  const keys = Object.keys(obj).sort();\n  return `{${keys.map((k) => `${JSON.stringify(k)}:${canonicalizeBody(obj[k])}`).join(',')}}`;\n}\n\n/**\n * Build the exact byte-string the client signed: canonicalized\n * `{ body, nonce, timestamp }`. Must match\n * `hooks/lib/holomesh-signing.mjs::buildSignedEnvelope` payload assembly.\n */\nexport function buildSigningPayload(\n  env: Pick<SignedEnvelope, 'body' | 'nonce' | 'timestamp'>\n): string {\n  return canonicalizeBody({ body: env.body, nonce: env.nonce, timestamp: env.timestamp });\n}\n\n/** Pull the envelope shape out of a request body, or return null if not signed. */\nexport function extractEnvelope(reqBody: unknown): SignedEnvelope | null {\n  if (!reqBody || typeof reqBody !== 'object') return null;\n  const e = reqBody as Partial<SignedEnvelope>;\n  if (\n    typeof e.signature !== 'string' ||\n    typeof e.signer_address !== 'string' ||\n    typeof e.nonce !== 'string' ||\n    typeof e.timestamp !== 'string' ||\n    !('body' in e)\n  ) {\n    return null;\n  }\n  return e as SignedEnvelope;\n}\n\n/** Reject envelopes older than the freshness window (defends against trivially-stale replays). */\nexport function isFreshTimestamp(timestamp: string, nowMs: number = Date.now()): boolean {\n  const t = Date.parse(timestamp);\n  if (Number.isNaN(t)) return false;\n  const drift = Math.abs(nowMs - t);\n  return drift <= TIMESTAMP_FRESHNESS_MS;\n}\n\n/** Address-equality check that's case-insensitive (Ethereum addresses are checksummed). */\nfunction addressesEqual(a: string, b: string): boolean {\n  return a.toLowerCase() === b.toLowerCase();\n}\n\n/**\n * Verify a signed envelope. Returns the verification result; the caller\n * decides whether to reject the request.\n *\n * When `registryCheck` is provided, signers that are retired or not yet\n * attested are rejected even if the signature is cryptographically valid.\n * When omitted (Phase 1 grace-period default), only the cryptographic\n * checks fire — caller does Bearer-token attribution as today.\n */\nexport async function verifyEnvelope(\n  env: SignedEnvelope,\n  options: { nowMs?: number; registryCheck?: RegistryCheck } = {}\n): Promise<VerifyResult> {\n  if (!isFreshTimestamp(env.timestamp, options.nowMs)) {\n    return { valid: false, signer: env.signer_address, reason: 'timestamp-stale' };\n  }\n  if (!/^0x[0-9a-fA-F]{40}$/.test(env.signer_address)) {\n    return { valid: false, signer: null, reason: 'malformed-signer-address' };\n  }\n  if (!/^0x[0-9a-fA-F]+$/.test(env.signature)) {\n    return { valid: false, signer: env.signer_address, reason: 'malformed-signature' };\n  }\n  let recovered: boolean;\n  try {\n    const { verifyMessage } = await import('viem');\n    recovered = await verifyMessage({\n      address: env.signer_address as `0x${string}`,\n      message: buildSigningPayload(env),\n      signature: env.signature as `0x${string}`,\n    });\n  } catch {\n    return { valid: false, signer: env.signer_address, reason: 'verify-threw' };\n  }\n  if (!recovered) {\n    return { valid: false, signer: env.signer_address, reason: 'signature-mismatch' };\n  }\n  if (options.registryCheck) {\n    let registry: { attested: boolean; retired: boolean; reason?: string };\n    try {\n      registry = await options.registryCheck(env.signer_address);\n    } catch {\n      return { valid: false, signer: env.signer_address, reason: 'registry-check-threw' };\n    }\n    if (registry.retired) {\n      return {\n        valid: false,\n        signer: env.signer_address,\n        reason: registry.reason ?? 'signer-retired',\n      };\n    }\n    if (!registry.attested) {\n      return {\n        valid: false,\n        signer: env.signer_address,\n        reason: registry.reason ?? 'signer-not-attested',\n      };\n    }\n  }\n  return { valid: true, signer: env.signer_address };\n}\n\n/**\n * Convenience wrapper: extract + verify in one call. Returns {valid:false,\n * reason:'unsigned'} when no envelope shape is present so callers can decide\n * whether to fall through to legacy-attribution during the Phase 1 grace\n * period or reject outright after cutover.\n */\nexport async function verifyRequestBody(\n  reqBody: unknown,\n  options: { nowMs?: number; registryCheck?: RegistryCheck } = {}\n): Promise<VerifyResult> {\n  const env = extractEnvelope(reqBody);\n  if (!env) return { valid: false, signer: null, reason: 'unsigned' };\n  // Reject obviously-equal addresses — keeps the test's address-mismatch case clean\n  // even if a malicious caller sets signer_address to match a different signer.\n  const result = await verifyEnvelope(env, options);\n  if (result.valid && !addressesEqual(result.signer ?? '', env.signer_address)) {\n    return { valid: false, signer: env.signer_address, reason: 'signer-address-mismatch' };\n  }\n  return result;\n}\n","/**\n * Attestation Registry — Phase 1-2 substrate for the seat-wallets-adr.\n *\n * Maps `public_key → attestation` for all seat wallets the founder has\n * signed off on, plus a retired set for revoked seats. The registry is the\n * source of truth for \"is this signer authorized\" and \"is this signer\n * still active\" — `request-signing.ts::verifyEnvelope` calls into it via\n * the optional `registryCheck` hook so a retired seat's new signatures\n * are rejected even if cryptographically valid.\n *\n * Phase 1 storage: in-memory only. Persistence (disk / database) is a\n * future hardening step — the registry is rebuilt on server boot from\n * the founder's signed attestation log when that ships.\n *\n * Propagation: when an attestation is retired, the registry fires its\n * `onRetire` callback so consumers (route handlers that hold the team\n * room context) can broadcast a `attestation:retire` event over the\n * existing SSE feed. Per ADR §\"Attestation registry (Q5 SSE <60s)\" the\n * 50-event ring buffer in team-room.ts gives reconnecting clients\n * cache-invalidation under the 60s propagation bound.\n *\n * Past signatures from retired seats remain cryptographically valid\n * at-time-of-signing — retire only blocks NEW claims (caller must call\n * registryCheck on each new mutation).\n *\n * Spec: research/2026-04-21_seat-wallets-adr.md §\"Revocation\",\n * §\"Attestation registry\", §\"Resolved defaults #5\".\n *\n * @module holomesh/identity/attestation-registry\n */\n\n/** A founder-signed attestation binding a seat's public key to an authorized identity. */\nexport interface Attestation {\n  /** Lowercased 0x… ethereum address of the seat. */\n  publicKey: string;\n  /** Human-readable seat identifier (e.g. claude-claudecode-abc-default-x402). */\n  seatId: string;\n  /** Who signed this attestation: ecosystem-root / platform-root / a parent wallet. */\n  authorizedBy: string;\n  /**\n   * Role granted by this attestation, copied verbatim from the signed\n   * envelope's `role` field (e.g. 'agent', 'attestation-authority').\n   *\n   * Load-bearing for delegated attestation authority (founder directive\n   * 2026-07-10): `attestation-routes.ts::resolveAttestationAuthority` accepts\n   * a non-founder `authorized_by` ONLY when this registry holds an ACTIVE\n   * attestation for that address with role === 'attestation-authority' that\n   * was itself authorized by the founder anchor. Optional because pre-existing\n   * records (and non-envelope attest() callers) never carried a role — those\n   * records simply can never act as a delegated authority.\n   */\n  role?: string;\n  /** ISO 8601 issuance timestamp. */\n  issuedAt: string;\n  /** ISO 8601 expiry; null = never expires. */\n  expiresAt: string | null;\n  /** Set when retired; reflects the retirement timestamp, not the issuance. */\n  retiredAt?: string;\n  /** Set when retired; human-readable reason ('compromise' / 'rotation' / etc). */\n  retireReason?: string;\n  /**\n   * Optional ML-DSA-65 public key bytes (FIPS-204 Category-3 / ~AES-192).\n   * Present once the seat's owner has bound a post-quantum key alongside\n   * the classical Ethereum address. The same Attestation entry carries both\n   * keys so dual-mode signature verification can cross-check that the\n   * classical address AND the pqc key map to the SAME seat (defends against\n   * substitution attacks where an attacker pairs a valid classical sig from\n   * seat A with a valid pqc sig from seat B).\n   *\n   * 2030 NIST classical-deprecation runway — see\n   * research/2026-05-12_pqc-dual-sign-design.md.\n   */\n  pqcPublicKey?: Uint8Array;\n}\n\n/** Event fired when an attestation is retired. Consumers wire this to SSE. */\nexport interface AttestationRetireEvent {\n  publicKey: string;\n  seatId: string;\n  retiredAt: string;\n  reason: string;\n}\n\n/** Optional callback fired on retire so consumers can broadcast the event. */\nexport type OnRetireCallback = (event: AttestationRetireEvent) => void;\n\n/** Registry-side check used by request-signing's verifyEnvelope. */\nexport interface RegistryCheckResult {\n  attested: boolean;\n  retired: boolean;\n  /** Optional reason string for logging when attested=false / retired=true. */\n  reason?: string;\n}\n\n/** Lowercase + 0x-prefix normalize for case-insensitive Ethereum-address keys. */\nfunction normalizeKey(publicKey: string): string {\n  if (typeof publicKey !== 'string') return '';\n  return publicKey.toLowerCase();\n}\n\n/**\n * Encode a PQC public key as a stable hex string for use as a Map key.\n * ML-DSA-65 public keys are 1952 bytes; hex doubles that — within memory\n * budget for the in-memory registry (a few hundred entries max).\n *\n * Returns the empty string for empty/missing input so the secondary index\n * never accidentally indexes a zero-length key.\n */\nexport function pqcKeyToHex(pqcPublicKey: Uint8Array | undefined): string {\n  if (!pqcPublicKey || pqcPublicKey.length === 0) return '';\n  let hex = '';\n  for (let i = 0; i < pqcPublicKey.length; i++) {\n    hex += pqcPublicKey[i].toString(16).padStart(2, '0');\n  }\n  return hex;\n}\n\n/** Constant-time-flavor compare of two Uint8Arrays — registry indices use hex\n *  for Map keys so this is only used in defensive equality checks at boundaries. */\nfunction bytesEqual(a: Uint8Array, b: Uint8Array): boolean {\n  if (a.length !== b.length) return false;\n  let diff = 0;\n  for (let i = 0; i < a.length; i++) diff |= a[i] ^ b[i];\n  return diff === 0;\n}\n\nexport class AttestationRegistry {\n  private byKey = new Map<string, Attestation>();\n  /** Secondary index — pqcPublicKey hex → attestation. Always references the\n   *  same Attestation object stored in byKey; updated atomically with attest()\n   *  and retire(). */\n  private byPqcKey = new Map<string, Attestation>();\n  private retired = new Set<string>();\n  private onRetire?: OnRetireCallback;\n  /** Fired after any state mutation (attest/retire) so a durable-persistence\n   *  layer can snapshot to disk/DB. Kept separate from `onRetire` (which is\n   *  the SSE-broadcast hook) so persistence and broadcast compose independently. */\n  private onChange?: () => void;\n  /** Suppresses `onChange` during `restore()` — loading from the store must not\n   *  immediately write back the same bytes. */\n  private suppressChange = false;\n\n  constructor(opts: { onRetire?: OnRetireCallback; onChange?: () => void } = {}) {\n    this.onRetire = opts.onRetire;\n    this.onChange = opts.onChange;\n  }\n\n  /** Fire the change hook, swallowing errors so a persistence failure never\n   *  breaks an in-memory mutation (the registry is authoritative in-process;\n   *  the next successful save catches up). No-op while restoring or unwired. */\n  private fireChange(): void {\n    if (!this.onChange || this.suppressChange) return;\n    try {\n      this.onChange();\n    } catch {\n      // Persistence failure must not roll back the attest/retire.\n    }\n  }\n\n  /** Add or replace an attestation. Idempotent on identical input.\n   *\n   *  When the attestation carries a `pqcPublicKey`, the secondary index is\n   *  also updated. Re-attesting WITHOUT a pqcPublicKey removes any previous\n   *  PQC binding for this seat (intentional: callers explicitly drop PQC\n   *  by re-attesting without it).\n   */\n  attest(att: Attestation): void {\n    if (!att.publicKey) throw new Error('attest: publicKey required');\n    if (!att.seatId) throw new Error('attest: seatId required');\n    const key = normalizeKey(att.publicKey);\n\n    // Clear any previous PQC index entry for this seat (re-attest may rotate\n    // or drop the PQC key).\n    const previous = this.byKey.get(key);\n    if (previous?.pqcPublicKey) {\n      this.byPqcKey.delete(pqcKeyToHex(previous.pqcPublicKey));\n    }\n\n    const stored: Attestation = { ...att, publicKey: key };\n    this.byKey.set(key, stored);\n\n    if (stored.pqcPublicKey && stored.pqcPublicKey.length > 0) {\n      this.byPqcKey.set(pqcKeyToHex(stored.pqcPublicKey), stored);\n    }\n\n    // Re-attesting an explicitly-retired key is allowed (key rotation flows);\n    // callers must understand the implications. Clear the retired flag.\n    this.retired.delete(key);\n    this.fireChange();\n  }\n\n  /**\n   * Mark an attestation as retired. Returns the (now-retired) attestation, or\n   * null if the key was unknown. Fires onRetire callback when present.\n   *\n   * Retirement affects BOTH the classical and the PQC indices — a retired\n   * seat is rejected regardless of which key the verifier looks up.\n   */\n  retire(publicKey: string, reason: string): Attestation | null {\n    const key = normalizeKey(publicKey);\n    const att = this.byKey.get(key);\n    if (!att) return null;\n    if (this.retired.has(key)) return att; // already retired; no double-fire\n    const retiredAt = new Date().toISOString();\n    const updated: Attestation = { ...att, retiredAt, retireReason: reason };\n    this.byKey.set(key, updated);\n    // Keep the PQC index pointing at the now-retired attestation so PQC-side\n    // lookups still find it and see retiredAt — they reject the same way the\n    // classical lookup does.\n    if (updated.pqcPublicKey && updated.pqcPublicKey.length > 0) {\n      this.byPqcKey.set(pqcKeyToHex(updated.pqcPublicKey), updated);\n    }\n    this.retired.add(key);\n    if (this.onRetire) {\n      try {\n        this.onRetire({ publicKey: key, seatId: att.seatId, retiredAt, reason });\n      } catch {\n        // Broadcast failure must not break the retire — attestation state is\n        // authoritative even if the SSE feed is down. Consumer handles resync.\n      }\n    }\n    this.fireChange();\n    return updated;\n  }\n\n  /** Look up an attestation by public key. Returns undefined when unknown. */\n  lookup(publicKey: string): Attestation | undefined {\n    return this.byKey.get(normalizeKey(publicKey));\n  }\n\n  /** Look up an attestation by ML-DSA-65 public key (PQC side).\n   *  Returns undefined when no seat has been attested with this PQC key. */\n  lookupByPqcKey(pqcPublicKey: Uint8Array): Attestation | undefined {\n    const hex = pqcKeyToHex(pqcPublicKey);\n    if (!hex) return undefined;\n    const att = this.byPqcKey.get(hex);\n    if (!att) return undefined;\n    // Defensive equality check — guard against the (vanishingly unlikely)\n    // hex-string collision on degenerate inputs.\n    if (!att.pqcPublicKey || !bytesEqual(att.pqcPublicKey, pqcPublicKey)) return undefined;\n    return att;\n  }\n\n  /** True iff the key is attested AND not retired AND not expired (vs nowMs). */\n  isAttested(publicKey: string, nowMs: number = Date.now()): boolean {\n    const key = normalizeKey(publicKey);\n    const att = this.byKey.get(key);\n    if (!att) return false;\n    if (this.retired.has(key)) return false;\n    if (att.expiresAt) {\n      const exp = Date.parse(att.expiresAt);\n      if (!Number.isNaN(exp) && exp <= nowMs) return false;\n    }\n    return true;\n  }\n\n  /** PQC-side equivalent of `isAttested`. True iff the PQC key resolves to an\n   *  attestation that is NOT retired AND NOT expired. */\n  isPqcAttested(pqcPublicKey: Uint8Array, nowMs: number = Date.now()): boolean {\n    const att = this.lookupByPqcKey(pqcPublicKey);\n    if (!att) return false;\n    if (this.retired.has(normalizeKey(att.publicKey))) return false;\n    if (att.expiresAt) {\n      const exp = Date.parse(att.expiresAt);\n      if (!Number.isNaN(exp) && exp <= nowMs) return false;\n    }\n    return true;\n  }\n\n  /** True iff the key is in the retired set (regardless of expiry / re-attest). */\n  isRetired(publicKey: string): boolean {\n    return this.retired.has(normalizeKey(publicKey));\n  }\n\n  /** PQC-side equivalent of `isRetired`. True iff the seat bound to this PQC\n   *  key has been retired. */\n  isPqcRetired(pqcPublicKey: Uint8Array): boolean {\n    const att = this.lookupByPqcKey(pqcPublicKey);\n    if (!att) return false;\n    return this.retired.has(normalizeKey(att.publicKey));\n  }\n\n  /** Number of distinct attestations (retired + active). */\n  size(): number {\n    return this.byKey.size;\n  }\n\n  /** Number of currently-retired attestations. */\n  retiredCount(): number {\n    return this.retired.size;\n  }\n\n  /**\n   * Serialize registry state for durable persistence (survives orchestrator\n   * restarts so founder attestations don't have to be re-signed after every\n   * deploy). `pqcPublicKey` stays as `Uint8Array` here — the persistence layer\n   * (attestation-persistence.ts) is responsible for encoding it. `byPqcKey` is\n   * a rebuildable secondary index derived from `byKey`, so it is NOT serialized;\n   * `restore()` reconstructs it.\n   */\n  snapshot(): { attestations: Attestation[]; retired: string[] } {\n    return {\n      attestations: [...this.byKey.values()].map((att) => ({ ...att })),\n      retired: [...this.retired],\n    };\n  }\n\n  /**\n   * Rehydrate the registry from a `snapshot()`. REPLACES all in-memory state,\n   * rebuilding the PQC index from any attestation carrying a `pqcPublicKey`.\n   * Malformed rows (missing publicKey/seatId) are skipped rather than throwing,\n   * so a partially-corrupt store degrades to fewer attestations instead of a\n   * boot crash. Does NOT fire `onChange` (loading from the store must not\n   * immediately write the same bytes back).\n   */\n  restore(snap: { attestations?: Attestation[]; retired?: string[] } | null): void {\n    if (!snap) return;\n    this.suppressChange = true;\n    try {\n      this.clear();\n      for (const att of snap.attestations ?? []) {\n        if (!att || !att.publicKey || !att.seatId) continue;\n        // attest() rebuilds byKey + byPqcKey and clears the retired flag; the\n        // retired set is re-applied AFTER the loop so retired seats stay retired.\n        this.attest(att);\n      }\n      for (const key of snap.retired ?? []) {\n        const normalized = normalizeKey(key);\n        if (normalized && this.byKey.has(normalized)) this.retired.add(normalized);\n      }\n    } finally {\n      this.suppressChange = false;\n    }\n  }\n\n  /**\n   * Build a registryCheck function suitable for `request-signing.ts`'s\n   * `verifyEnvelope({ registryCheck })` option. The returned function is\n   * sync-result wrapped in a Promise (registry is in-memory) so callers\n   * can await uniformly with future persistence-backed implementations.\n   */\n  toRegistryCheck(nowMs?: number): (publicKey: string) => Promise<RegistryCheckResult> {\n    return async (publicKey: string) => {\n      const key = normalizeKey(publicKey);\n      const retired = this.retired.has(key);\n      if (retired) {\n        return { attested: false, retired: true, reason: 'signer-retired' };\n      }\n      const attested = this.isAttested(key, nowMs);\n      return {\n        attested,\n        retired: false,\n        reason: attested ? undefined : 'signer-not-attested',\n      };\n    };\n  }\n\n  /**\n   * Build a PQC-side registryCheck function. Same shape as `toRegistryCheck`\n   * but keyed on `Uint8Array` (the ML-DSA-65 public key bytes) instead of a\n   * 0x-Ethereum-address string.\n   */\n  toPqcRegistryCheck(nowMs?: number): (pqcPublicKey: Uint8Array) => Promise<RegistryCheckResult> {\n    return async (pqcPublicKey: Uint8Array) => {\n      const att = this.lookupByPqcKey(pqcPublicKey);\n      if (!att) {\n        return { attested: false, retired: false, reason: 'signer-not-attested' };\n      }\n      const classicalKey = normalizeKey(att.publicKey);\n      if (this.retired.has(classicalKey)) {\n        return { attested: false, retired: true, reason: 'signer-retired' };\n      }\n      const attested = this.isPqcAttested(pqcPublicKey, nowMs);\n      return {\n        attested,\n        retired: false,\n        reason: attested ? undefined : 'signer-not-attested',\n      };\n    };\n  }\n\n  /**\n   * Dual-mode cross-verify — confirm that a classical address AND a PQC key\n   * resolve to the SAME attestation entry. Defends against substitution\n   * attacks where an attacker pairs a valid classical sig from seat A with a\n   * valid PQC sig from seat B (both keys are individually attested but for\n   * different seats).\n   *\n   * Returns:\n   *   - `{matched: true,  attestation}` when both keys point at one entry.\n   *   - `{matched: false, reason: 'classical-not-attested'}` when classical missing.\n   *   - `{matched: false, reason: 'pqc-not-attested'}`       when pqc missing.\n   *   - `{matched: false, reason: 'cross-key-mismatch'}`     when both exist but\n   *     bind to different seats.\n   *   - `{matched: false, reason: 'signer-retired'}`         when the bound seat is retired.\n   */\n  crossVerifyDual(\n    classicalAddress: string,\n    pqcPublicKey: Uint8Array,\n    nowMs?: number\n  ): { matched: true; attestation: Attestation } | { matched: false; reason: string } {\n    const classicalAtt = this.lookup(classicalAddress);\n    if (!classicalAtt) return { matched: false, reason: 'classical-not-attested' };\n    const pqcAtt = this.lookupByPqcKey(pqcPublicKey);\n    if (!pqcAtt) return { matched: false, reason: 'pqc-not-attested' };\n    if (normalizeKey(classicalAtt.publicKey) !== normalizeKey(pqcAtt.publicKey)) {\n      return { matched: false, reason: 'cross-key-mismatch' };\n    }\n    if (this.retired.has(normalizeKey(classicalAtt.publicKey))) {\n      return { matched: false, reason: 'signer-retired' };\n    }\n    // Expiry check — both keys share the same Attestation entry so one check covers both.\n    if (classicalAtt.expiresAt) {\n      const exp = Date.parse(classicalAtt.expiresAt);\n      const now = nowMs ?? Date.now();\n      if (!Number.isNaN(exp) && exp <= now) {\n        return { matched: false, reason: 'signer-expired' };\n      }\n    }\n    return { matched: true, attestation: classicalAtt };\n  }\n\n  /** Test-only: reset state. Avoid in production code paths. */\n  clear(): void {\n    this.byKey.clear();\n    this.byPqcKey.clear();\n    this.retired.clear();\n  }\n}\n\n/**\n * Compose with a SSE broadcaster (e.g. `broadcastToRoom` from `team-room.ts`)\n * to get a registry whose retires propagate to the team's `/room/live` clients\n * within the 60s SSE bound. Wire from the route handler that calls retire():\n *\n *     const registry = createBroadcastingRegistry(teamId, broadcastToRoom);\n *     registry.retire(pubkey, 'compromise');  // event fires automatically\n *\n * The `broadcaster` arg is intentionally typed as a minimal call shape so this\n * module never imports from team-room.ts (preserves Identity-namespace\n * separation; tests can pass a spy).\n */\nexport function createBroadcastingRegistry(\n  teamId: string,\n  broadcaster: (roomId: string, event: { type: string; agent?: string; data?: unknown }) => void,\n  opts: { agent?: string } = {}\n): AttestationRegistry {\n  return new AttestationRegistry({\n    onRetire: (event) => {\n      broadcaster(teamId, {\n        type: 'attestation:retire',\n        agent: opts.agent,\n        data: event,\n      });\n    },\n  });\n}\n","/**\n * Post-quantum dual-signature envelope — design + verifier scaffolding for\n * the 2030 NIST ECDSA deprecation (NIST IR 8547 prohibits classical PKC after\n * 2035; ASD Australia cuts off at 2030).\n *\n * Companion to:\n *   - request-signing.ts (classical EIP-191 / ECDSA verifier, current path)\n *   - signing-middleware.ts (per-request signing context helper)\n *   - signing/signer.ts (chain-anchor Signer interface for the live Trezor path)\n *\n * What ships here:\n *   1. DualSignatureEnvelope type + version byte for forward compatibility.\n *   2. Deterministic length-prefixed binary serializer + matching parser.\n *      Round-trips losslessly across all three modes.\n *   3. verifyDualSignature() — verifies classical-only / pqc-only / dual modes\n *      using @noble/post-quantum's ml_dsa65 (FIPS-204 Category-3) for the PQC\n *      side and viem's verifyMessage for the classical side (matches the\n *      existing request-signing.ts call path).\n *   4. signDual() + IPQCSigner injection point. The PQC signer is a stub\n *      (NoopPQCSigner throws) because the live Trezor PQC firmware doesn't\n *      exist yet — see scoping doc §5.\n *\n * What does NOT ship:\n *   - Live Trezor coordination for the classical signer (already wired\n *     through request-signing.ts + the seat-wallet protocol — we just point at\n *     it via the IClassicalSigner interface).\n *   - Live Trezor PQC firmware. Trezor's open roadmap discusses ML-DSA support\n *     but no firmware ships it today; NoopPQCSigner throws so callers fail\n *     loud the moment they try to sign in PQC or dual mode.\n *\n * Algorithm pick: ML-DSA-65 (CRYSTALS-Dilithium, Category 3 / ~AES-192).\n *   - 1952-byte public key, ~3309-byte signature\n *   - Lattice-based, no floating-point (vs Falcon's Gaussian sampling, which\n *     is hostile to deterministic hardware-wallet implementations)\n *   - Selected by NIST as a primary standard (FIPS-204, Aug 2024)\n *   - vs SLH-DSA-192: SLH-DSA is more conservative (hash-based, no lattice\n *     assumptions) but produces 17-50 KB signatures — too heavy for the\n *     per-mutation envelope path that fires on every HoloMesh team API call.\n *\n * Spec: research/2026-05-12_pqc-dual-sign-design.md\n *\n * @module holomesh/identity/dual-signature-envelope\n */\n\nimport { ml_dsa65 } from '@noble/post-quantum/ml-dsa.js';\n\n// ── Constants ─────────────────────────────────────────────────────────\n\n/**\n * Envelope format version. Bumped when the wire layout changes in a way that\n * breaks parsers. Parsers reject any version they don't know how to handle.\n *\n * v1: ML-DSA-65 PQC + ECDSA-P256 classical, length-prefixed binary.\n */\nexport const DUAL_SIG_ENVELOPE_VERSION_V1 = 0x01;\n\n/** ML-DSA-65 algorithm tag — written into the envelope so a future PQC-algo\n * migration (e.g. to ML-DSA-87 or a successor) doesn't ambiguate the parser. */\nexport const PQC_ALGO_ML_DSA_65 = 0x01;\n\n/** ECDSA-P256 / EIP-191 personal_sign — matches request-signing.ts. */\nexport const CLASSICAL_ALGO_ECDSA_P256 = 0x01;\n\n/** Mode field — written into the envelope as a 1-byte discriminant. */\nexport type DualSignatureMode = 'classical_only' | 'pqc_only' | 'dual';\n\nconst MODE_CLASSICAL_ONLY = 0x01;\nconst MODE_PQC_ONLY = 0x02;\nconst MODE_DUAL = 0x03;\n\nfunction modeToByte(mode: DualSignatureMode): number {\n  switch (mode) {\n    case 'classical_only':\n      return MODE_CLASSICAL_ONLY;\n    case 'pqc_only':\n      return MODE_PQC_ONLY;\n    case 'dual':\n      return MODE_DUAL;\n  }\n}\n\nfunction modeFromByte(b: number): DualSignatureMode | null {\n  switch (b) {\n    case MODE_CLASSICAL_ONLY:\n      return 'classical_only';\n    case MODE_PQC_ONLY:\n      return 'pqc_only';\n    case MODE_DUAL:\n      return 'dual';\n    default:\n      return null;\n  }\n}\n\n// ── Envelope type ─────────────────────────────────────────────────────\n\n/**\n * DualSignatureEnvelope — a container for a payload plus zero, one, or both of\n * its signatures (classical ECDSA + post-quantum ML-DSA-65).\n *\n * `payloadHash` is the SHA-256 of the canonicalized payload bytes. The\n * envelope NEVER carries the full payload — verifier callers must supply it\n * out of band (same shape as the existing request-signing.ts protocol, where\n * the body lives outside the signature). This keeps the envelope under ~5 KB\n * even when the payload is megabytes.\n *\n * Mode invariants (enforced by serializer + verifier):\n *   - `classical_only`: classicalSignature MUST be non-empty; pqcSignature\n *     bytes MAY be empty (serializer writes a 0-length record).\n *   - `pqc_only`: pqcSignature MUST be non-empty; classicalSignature MAY be\n *     empty.\n *   - `dual`: BOTH MUST be non-empty.\n */\nexport interface DualSignatureEnvelope {\n  /** Format version byte (DUAL_SIG_ENVELOPE_VERSION_V1 today). */\n  version: number;\n  /** Signing mode discriminant. */\n  mode: DualSignatureMode;\n  /** SHA-256 of canonicalized payload bytes (32 bytes). */\n  payloadHash: Uint8Array;\n  /** Classical algorithm tag (CLASSICAL_ALGO_ECDSA_P256 today). */\n  classicalAlgo: number;\n  /** Classical signature bytes — empty Uint8Array when mode=pqc_only. */\n  classicalSignature: Uint8Array;\n  /** Classical signer 0x-address (20 bytes hex, 42 chars) — empty when pqc_only. */\n  classicalSignerAddress: string;\n  /** PQC algorithm tag (PQC_ALGO_ML_DSA_65 today). */\n  pqcAlgo: number;\n  /** PQC signature bytes — empty Uint8Array when mode=classical_only. */\n  pqcSignature: Uint8Array;\n  /** PQC public key bytes — empty Uint8Array when mode=classical_only. */\n  pqcPublicKey: Uint8Array;\n}\n\n// ── Serialization ─────────────────────────────────────────────────────\n\n/**\n * Magic prefix — 4-byte tag so a parser confronted with arbitrary bytes can\n * quickly reject non-envelopes. Spells \"HDSE\" (HoloMesh Dual Sig Envelope).\n */\nconst MAGIC = Uint8Array.of(0x48, 0x44, 0x53, 0x45);\n\n/** Maximum payload-hash length — SHA-256 is always 32 bytes; reject anything else. */\nconst PAYLOAD_HASH_LEN = 32;\n\n/**\n * Maximum byte length we'll accept for any length-prefixed field. Defends the\n * parser against DoS via 4 GB length headers in malformed input. The largest\n * legitimate field is the ML-DSA-65 signature at ~3309 bytes; ECDSA-P256 sigs\n * are 65 bytes (r||s||v); ML-DSA-65 pubkeys are 1952 bytes. 64 KB is comfortable.\n */\nconst MAX_FIELD_LEN = 64 * 1024;\n\n/**\n * Write a u32 big-endian into a Uint8Array at offset.\n * Defensive choice: big-endian is the wire-format default in every cryptographic\n * spec we care about (TLS, IPsec, SSH), so parsers across languages will read\n * the same number out of these bytes.\n */\nfunction writeU32BE(buf: Uint8Array, offset: number, value: number): void {\n  buf[offset] = (value >>> 24) & 0xff;\n  buf[offset + 1] = (value >>> 16) & 0xff;\n  buf[offset + 2] = (value >>> 8) & 0xff;\n  buf[offset + 3] = value & 0xff;\n}\n\nfunction readU32BE(buf: Uint8Array, offset: number): number {\n  return (\n    ((buf[offset] << 24) >>> 0) | (buf[offset + 1] << 16) | (buf[offset + 2] << 8) | buf[offset + 3]\n  );\n}\n\n/**\n * Encode a Uint8Array as a length-prefixed (u32-BE) record.\n * Returns the concatenated bytes.\n */\nfunction encodeLP(field: Uint8Array): Uint8Array {\n  if (field.length > MAX_FIELD_LEN) {\n    throw new Error(\n      `dual-sig-envelope: field length ${field.length} exceeds MAX_FIELD_LEN ${MAX_FIELD_LEN}`\n    );\n  }\n  const out = new Uint8Array(4 + field.length);\n  writeU32BE(out, 0, field.length);\n  out.set(field, 4);\n  return out;\n}\n\n/**\n * Read a length-prefixed record. Returns { bytes, nextOffset } or null on\n * malformed input (length > MAX_FIELD_LEN, or runs past end-of-buffer).\n */\nfunction decodeLP(\n  buf: Uint8Array,\n  offset: number\n): { bytes: Uint8Array; nextOffset: number } | null {\n  if (offset + 4 > buf.length) return null;\n  const len = readU32BE(buf, offset);\n  if (len > MAX_FIELD_LEN) return null;\n  if (offset + 4 + len > buf.length) return null;\n  const bytes = buf.slice(offset + 4, offset + 4 + len);\n  return { bytes, nextOffset: offset + 4 + len };\n}\n\nfunction utf8Encode(s: string): Uint8Array {\n  return new TextEncoder().encode(s);\n}\n\nfunction utf8Decode(b: Uint8Array): string {\n  return new TextDecoder('utf-8', { fatal: true }).decode(b);\n}\n\n/**\n * Serialize a DualSignatureEnvelope to bytes.\n *\n * Wire layout (v1):\n *   offset  size  field\n *   ------  ----  -----\n *        0     4  MAGIC (\"HDSE\")\n *        4     1  version\n *        5     1  mode byte (0x01=classical_only, 0x02=pqc_only, 0x03=dual)\n *        6     1  classicalAlgo\n *        7     1  pqcAlgo\n *        8    32  payloadHash (always 32 bytes)\n *       40   4+N  classicalSignature (u32-BE length || bytes)\n *      ...   4+N  classicalSignerAddress (u32-BE length || UTF-8 bytes)\n *      ...   4+N  pqcSignature (u32-BE length || bytes)\n *      ...   4+N  pqcPublicKey (u32-BE length || bytes)\n *\n * Throws if mode invariants are violated (e.g. mode=dual but pqcSignature\n * is empty). This is the EARLIER of two enforcement points — verifyDualSignature\n * also rejects mode-mismatch, but failing here catches buggy callers before\n * the bad envelope hits the wire.\n */\nexport function serializeDualSignatureEnvelope(env: DualSignatureEnvelope): Uint8Array {\n  // ── Validate mode invariants ─────────────────────────────────\n  if (env.payloadHash.length !== PAYLOAD_HASH_LEN) {\n    throw new Error(\n      `dual-sig-envelope: payloadHash must be ${PAYLOAD_HASH_LEN} bytes (got ${env.payloadHash.length})`\n    );\n  }\n  if (env.version !== DUAL_SIG_ENVELOPE_VERSION_V1) {\n    throw new Error(`dual-sig-envelope: unsupported version ${env.version}`);\n  }\n  const needsClassical = env.mode === 'classical_only' || env.mode === 'dual';\n  const needsPqc = env.mode === 'pqc_only' || env.mode === 'dual';\n  if (needsClassical && env.classicalSignature.length === 0) {\n    throw new Error(`dual-sig-envelope: mode=${env.mode} requires classicalSignature`);\n  }\n  if (needsClassical && env.classicalSignerAddress.length === 0) {\n    throw new Error(`dual-sig-envelope: mode=${env.mode} requires classicalSignerAddress`);\n  }\n  if (needsPqc && env.pqcSignature.length === 0) {\n    throw new Error(`dual-sig-envelope: mode=${env.mode} requires pqcSignature`);\n  }\n  if (needsPqc && env.pqcPublicKey.length === 0) {\n    throw new Error(`dual-sig-envelope: mode=${env.mode} requires pqcPublicKey`);\n  }\n\n  // ── Build fixed-prefix header ────────────────────────────────\n  const header = new Uint8Array(4 + 1 + 1 + 1 + 1 + PAYLOAD_HASH_LEN);\n  header.set(MAGIC, 0);\n  header[4] = env.version;\n  header[5] = modeToByte(env.mode);\n  header[6] = env.classicalAlgo;\n  header[7] = env.pqcAlgo;\n  header.set(env.payloadHash, 8);\n\n  // ── Length-prefix the variable fields ────────────────────────\n  const classicalSig = encodeLP(env.classicalSignature);\n  const classicalAddr = encodeLP(utf8Encode(env.classicalSignerAddress));\n  const pqcSig = encodeLP(env.pqcSignature);\n  const pqcPub = encodeLP(env.pqcPublicKey);\n\n  const total =\n    header.length + classicalSig.length + classicalAddr.length + pqcSig.length + pqcPub.length;\n  const out = new Uint8Array(total);\n  let off = 0;\n  out.set(header, off);\n  off += header.length;\n  out.set(classicalSig, off);\n  off += classicalSig.length;\n  out.set(classicalAddr, off);\n  off += classicalAddr.length;\n  out.set(pqcSig, off);\n  off += pqcSig.length;\n  out.set(pqcPub, off);\n  return out;\n}\n\n/** Parser result — discriminated union: either an envelope or a structured error. */\nexport type ParseResult =\n  | { ok: true; envelope: DualSignatureEnvelope }\n  | { ok: false; reason: ParseError };\n\nexport type ParseError =\n  | 'truncated'\n  | 'bad-magic'\n  | 'unsupported-version'\n  | 'unknown-mode'\n  | 'invalid-payload-hash'\n  | 'malformed-length-prefix'\n  | 'mode-invariant-violated'\n  | 'invalid-utf8-address';\n\n/**\n * Parse bytes into a DualSignatureEnvelope. Returns a discriminated-union\n * result; callers MUST check `ok` before reading `envelope`.\n *\n * Defends against:\n *   - truncated input (any field running past end-of-buffer)\n *   - wrong magic prefix (some random buffer was passed in)\n *   - unsupported version (forward-compat — future parser uses this)\n *   - unknown mode byte\n *   - malformed length prefixes (length > MAX_FIELD_LEN)\n *   - mode invariant violations after parsing (e.g. mode=dual but sig empty)\n */\nexport function parseDualSignatureEnvelope(buf: Uint8Array): ParseResult {\n  if (buf.length < 4 + 1 + 1 + 1 + 1 + PAYLOAD_HASH_LEN) {\n    return { ok: false, reason: 'truncated' };\n  }\n  for (let i = 0; i < MAGIC.length; i++) {\n    if (buf[i] !== MAGIC[i]) return { ok: false, reason: 'bad-magic' };\n  }\n  const version = buf[4];\n  if (version !== DUAL_SIG_ENVELOPE_VERSION_V1) {\n    return { ok: false, reason: 'unsupported-version' };\n  }\n  const mode = modeFromByte(buf[5]);\n  if (mode === null) return { ok: false, reason: 'unknown-mode' };\n  const classicalAlgo = buf[6];\n  const pqcAlgo = buf[7];\n  const payloadHash = buf.slice(8, 8 + PAYLOAD_HASH_LEN);\n  if (payloadHash.length !== PAYLOAD_HASH_LEN) {\n    return { ok: false, reason: 'invalid-payload-hash' };\n  }\n\n  let off = 8 + PAYLOAD_HASH_LEN;\n\n  const classicalSigRec = decodeLP(buf, off);\n  if (!classicalSigRec) return { ok: false, reason: 'malformed-length-prefix' };\n  off = classicalSigRec.nextOffset;\n\n  const classicalAddrRec = decodeLP(buf, off);\n  if (!classicalAddrRec) return { ok: false, reason: 'malformed-length-prefix' };\n  off = classicalAddrRec.nextOffset;\n\n  let classicalSignerAddress: string;\n  try {\n    classicalSignerAddress = utf8Decode(classicalAddrRec.bytes);\n  } catch {\n    return { ok: false, reason: 'invalid-utf8-address' };\n  }\n\n  const pqcSigRec = decodeLP(buf, off);\n  if (!pqcSigRec) return { ok: false, reason: 'malformed-length-prefix' };\n  off = pqcSigRec.nextOffset;\n\n  const pqcPubRec = decodeLP(buf, off);\n  if (!pqcPubRec) return { ok: false, reason: 'malformed-length-prefix' };\n\n  const env: DualSignatureEnvelope = {\n    version,\n    mode,\n    payloadHash,\n    classicalAlgo,\n    classicalSignature: classicalSigRec.bytes,\n    classicalSignerAddress,\n    pqcAlgo,\n    pqcSignature: pqcSigRec.bytes,\n    pqcPublicKey: pqcPubRec.bytes,\n  };\n\n  // ── Validate mode invariants AFTER parse (catches malformed dual-mode bytes) ──\n  const needsClassical = env.mode === 'classical_only' || env.mode === 'dual';\n  const needsPqc = env.mode === 'pqc_only' || env.mode === 'dual';\n  if (needsClassical && env.classicalSignature.length === 0) {\n    return { ok: false, reason: 'mode-invariant-violated' };\n  }\n  if (needsClassical && env.classicalSignerAddress.length === 0) {\n    return { ok: false, reason: 'mode-invariant-violated' };\n  }\n  if (needsPqc && env.pqcSignature.length === 0) {\n    return { ok: false, reason: 'mode-invariant-violated' };\n  }\n  if (needsPqc && env.pqcPublicKey.length === 0) {\n    return { ok: false, reason: 'mode-invariant-violated' };\n  }\n\n  return { ok: true, envelope: env };\n}\n\n// ── Verifier ──────────────────────────────────────────────────────────\n\nexport interface VerifyDualSignatureResult {\n  /** Top-level verdict — the only bit callers SHOULD branch on for accept/reject. */\n  valid: boolean;\n  /** Mode echoed from the envelope. */\n  mode: DualSignatureMode;\n  /** Classical verification verdict — undefined when mode=pqc_only. */\n  classicalValid?: boolean;\n  /** PQC verification verdict — undefined when mode=classical_only. */\n  pqcValid?: boolean;\n  /** Failure reason — only present when valid=false. */\n  reason?: VerifyFailureReason;\n}\n\nexport type VerifyFailureReason =\n  | 'payload-hash-mismatch'\n  | 'classical-signature-invalid'\n  | 'pqc-signature-invalid'\n  | 'classical-verify-threw'\n  | 'pqc-verify-threw'\n  | 'unsupported-classical-algo'\n  | 'unsupported-pqc-algo'\n  | 'mode-mismatch';\n\n/**\n * Adapter for the classical signature verifier. Production wiring uses\n * viem's verifyMessage (matches request-signing.ts call path).\n *\n * Why an adapter? Two reasons:\n *   1. The existing verifier in request-signing.ts uses a personal-sign\n *      payload of `canonicalizeBody({body, nonce, timestamp})` — for the dual\n *      envelope path the \"payload\" is the raw payloadHash bytes (callers\n *      have already canonicalized + hashed before signing). Centralizing the\n *      message-shape decision behind an interface keeps the verifier path\n *      independent of the higher-level envelope orchestration.\n *   2. Unit tests inject a deterministic verifier so they don't need to\n *      generate real ECDSA signatures (the test for classical-side correctness\n *      already exists at request-signing.test.ts).\n */\nexport interface IClassicalVerifier {\n  /**\n   * Return true if `signature` is a valid signature over `payloadHash` by the\n   * holder of `signerAddress`. Implementations MUST treat thrown errors as\n   * verification failure (caller will translate to 'classical-verify-threw').\n   */\n  verify(payloadHash: Uint8Array, signature: Uint8Array, signerAddress: string): Promise<boolean>;\n}\n\n/**\n * Default classical verifier — wraps viem.verifyMessage with the same\n * personal_sign semantics as request-signing.ts. The \"message\" verified is\n * the hex-encoded payload hash (callers can substitute a different adapter\n * if they want raw-bytes EIP-191 semantics).\n *\n * Note on test path: tests use a MockClassicalVerifier that returns true/false\n * synchronously without touching viem.\n */\nexport class ViemClassicalVerifier implements IClassicalVerifier {\n  async verify(\n    payloadHash: Uint8Array,\n    signature: Uint8Array,\n    signerAddress: string\n  ): Promise<boolean> {\n    const { verifyMessage } = await import('viem');\n    const sigHex = '0x' + bytesToHex(signature);\n    const msgHex = '0x' + bytesToHex(payloadHash);\n    return verifyMessage({\n      address: signerAddress as `0x${string}`,\n      message: msgHex,\n      signature: sigHex as `0x${string}`,\n    });\n  }\n}\n\nfunction bytesToHex(b: Uint8Array): string {\n  let s = '';\n  for (let i = 0; i < b.length; i++) {\n    s += b[i].toString(16).padStart(2, '0');\n  }\n  return s;\n}\n\n/**\n * Verify a DualSignatureEnvelope.\n *\n * Behavior:\n *   - `classical_only`: verify ECDSA only; pass if ECDSA valid; ignore PQC fields.\n *   - `pqc_only`: verify PQC only; pass if PQC valid; ignore ECDSA fields.\n *   - `dual`: verify BOTH; pass only if both valid; expose individual flags.\n *\n * `payload` is the raw bytes the signer committed to. The verifier\n * canonicalizes it the same way the signer did (SHA-256) and rejects if the\n * recomputed hash doesn't match the envelope's payloadHash field. This catches\n * the case where an attacker tampered with the payload but left the\n * signatures+envelope intact.\n */\nexport async function verifyDualSignature(\n  envelope: DualSignatureEnvelope,\n  payload: Uint8Array,\n  options: {\n    classicalVerifier?: IClassicalVerifier;\n  } = {}\n): Promise<VerifyDualSignatureResult> {\n  const classicalVerifier = options.classicalVerifier ?? new ViemClassicalVerifier();\n\n  // ── Payload-hash check (defends against payload tampering) ───\n  const recomputed = await sha256(payload);\n  if (!constantTimeEqual(recomputed, envelope.payloadHash)) {\n    return { valid: false, mode: envelope.mode, reason: 'payload-hash-mismatch' };\n  }\n\n  // ── Algorithm-tag checks ─────────────────────────────────────\n  const needsClassical = envelope.mode === 'classical_only' || envelope.mode === 'dual';\n  const needsPqc = envelope.mode === 'pqc_only' || envelope.mode === 'dual';\n\n  if (needsClassical && envelope.classicalAlgo !== CLASSICAL_ALGO_ECDSA_P256) {\n    return { valid: false, mode: envelope.mode, reason: 'unsupported-classical-algo' };\n  }\n  if (needsPqc && envelope.pqcAlgo !== PQC_ALGO_ML_DSA_65) {\n    return { valid: false, mode: envelope.mode, reason: 'unsupported-pqc-algo' };\n  }\n\n  // ── Mode-mismatch checks (parser also catches this; defense-in-depth) ──\n  if (needsClassical && envelope.classicalSignature.length === 0) {\n    return { valid: false, mode: envelope.mode, reason: 'mode-mismatch' };\n  }\n  if (needsPqc && envelope.pqcSignature.length === 0) {\n    return { valid: false, mode: envelope.mode, reason: 'mode-mismatch' };\n  }\n\n  // ── Classical verification ───────────────────────────────────\n  let classicalValid: boolean | undefined;\n  if (needsClassical) {\n    try {\n      classicalValid = await classicalVerifier.verify(\n        envelope.payloadHash,\n        envelope.classicalSignature,\n        envelope.classicalSignerAddress\n      );\n    } catch {\n      return {\n        valid: false,\n        mode: envelope.mode,\n        classicalValid: false,\n        reason: 'classical-verify-threw',\n      };\n    }\n  }\n\n  // ── PQC verification ─────────────────────────────────────────\n  let pqcValid: boolean | undefined;\n  if (needsPqc) {\n    try {\n      pqcValid = ml_dsa65.verify(\n        envelope.pqcSignature,\n        envelope.payloadHash,\n        envelope.pqcPublicKey\n      );\n    } catch {\n      return {\n        valid: false,\n        mode: envelope.mode,\n        classicalValid,\n        pqcValid: false,\n        reason: 'pqc-verify-threw',\n      };\n    }\n  }\n\n  // ── Combine verdicts per mode ────────────────────────────────\n  let valid: boolean;\n  let reason: VerifyFailureReason | undefined;\n  switch (envelope.mode) {\n    case 'classical_only':\n      valid = classicalValid === true;\n      if (!valid) reason = 'classical-signature-invalid';\n      break;\n    case 'pqc_only':\n      valid = pqcValid === true;\n      if (!valid) reason = 'pqc-signature-invalid';\n      break;\n    case 'dual':\n      valid = classicalValid === true && pqcValid === true;\n      if (!valid) {\n        // Pick the more informative reason; both can be exposed via the flags.\n        if (classicalValid !== true) reason = 'classical-signature-invalid';\n        else reason = 'pqc-signature-invalid';\n      }\n      break;\n  }\n\n  return { valid, mode: envelope.mode, classicalValid, pqcValid, reason };\n}\n\n// ── Signer interfaces (live signing is founder-gated) ─────────────────\n\n/**\n * Adapter for the classical signer. Production wiring delegates to the\n * existing seat-wallet Trezor + Rabby flow (see chain-anchor pattern in\n * F.041 / W.GOLD.514 — eth_sendTransaction with EIP-712 hash as calldata).\n *\n * FOUNDER-GATED: live signing requires Trezor hardware coordination. The\n * concrete wire-up of an `IClassicalSigner` that talks to Rabby+Trezor is\n * already designed (signing/signer.ts EthersSigner + the founder-gated\n * TrezorSigner task task_1778132312944_bcup).\n */\nexport interface IClassicalSigner {\n  /** 0x-prefixed Ethereum address this signer will use. */\n  getAddress(): Promise<string>;\n  /** Sign the payload-hash bytes. MUST return ECDSA-P256 / EIP-191 signature. */\n  sign(payloadHash: Uint8Array): Promise<Uint8Array>;\n}\n\n/**\n * Adapter for the post-quantum signer. ZERO production implementations exist\n * today because Trezor firmware does not yet support ML-DSA-65 — see the\n * scoping doc §5 for the founder coordination checklist.\n *\n * The dev-time signer for testing the verifier path generates an ML-DSA-65\n * keypair via @noble/post-quantum and signs in software. That signer ships\n * (TestPQCSigner below) but is explicitly marked dev-only.\n */\nexport interface IPQCSigner {\n  /** ML-DSA-65 public key bytes. */\n  getPublicKey(): Promise<Uint8Array>;\n  /** Sign payload-hash bytes. MUST return an ML-DSA-65 signature. */\n  sign(payloadHash: Uint8Array): Promise<Uint8Array>;\n}\n\n/**\n * NoopPQCSigner — throws on every call. Use as the default IPQCSigner so any\n * code path that tries to sign in PQC or dual mode WITHOUT explicitly wiring a\n * real signer fails loud rather than silently producing an\n * envelope-without-PQC-signature.\n *\n * FOUNDER-GATED: replace with a real Trezor-backed signer once firmware lands.\n */\nexport class NoopPQCSigner implements IPQCSigner {\n  async getPublicKey(): Promise<Uint8Array> {\n    throw new Error(\n      'FOUNDER-GATED: Trezor PQC firmware not yet wired. ' +\n        'Pass a real IPQCSigner (e.g. TestPQCSigner in unit tests) ' +\n        'or use mode=\"classical_only\" until firmware ships.'\n    );\n  }\n  async sign(_payloadHash: Uint8Array): Promise<Uint8Array> {\n    throw new Error(\n      'FOUNDER-GATED: Trezor PQC firmware not yet wired. ' +\n        'Pass a real IPQCSigner (e.g. TestPQCSigner in unit tests) ' +\n        'or use mode=\"classical_only\" until firmware ships.'\n    );\n  }\n}\n\n/**\n * TestPQCSigner — software ML-DSA-65 signer for tests + dev exercising the\n * verifier round-trip. NOT for production — there is no hardware-rooted\n * private-key custody here.\n *\n * Constructed with a 32-byte seed (or random if omitted) so tests can\n * deterministically regenerate the same keypair.\n */\nexport class TestPQCSigner implements IPQCSigner {\n  private readonly keys: { publicKey: Uint8Array; secretKey: Uint8Array };\n\n  constructor(seed?: Uint8Array) {\n    if (seed && seed.length !== 32) {\n      throw new Error(`TestPQCSigner: seed must be 32 bytes (got ${seed.length})`);\n    }\n    this.keys = ml_dsa65.keygen(seed);\n  }\n\n  async getPublicKey(): Promise<Uint8Array> {\n    return this.keys.publicKey;\n  }\n\n  async sign(payloadHash: Uint8Array): Promise<Uint8Array> {\n    return ml_dsa65.sign(payloadHash, this.keys.secretKey);\n  }\n}\n\n/**\n * Sign a payload, producing a DualSignatureEnvelope.\n *\n * FOUNDER-GATED: the classical signer points at the existing seat-wallet path\n * (see signing/signer.ts) — for testing it can be a software ECDSA signer; for\n * production it MUST be the Trezor-backed adapter. The PQC signer is\n * NoopPQCSigner by default — passing it through to mode=pqc_only or\n * mode=dual throws.\n *\n * Tests inject TestPQCSigner + a mock classical signer to exercise the\n * round-trip. Production callers building toward the 2030 cutover use\n * mode='dual' once both signers are wired.\n */\nexport async function signDual(\n  payload: Uint8Array,\n  mode: DualSignatureMode,\n  signers: {\n    classical?: IClassicalSigner;\n    pqc?: IPQCSigner;\n  }\n): Promise<DualSignatureEnvelope> {\n  const needsClassical = mode === 'classical_only' || mode === 'dual';\n  const needsPqc = mode === 'pqc_only' || mode === 'dual';\n\n  if (needsClassical && !signers.classical) {\n    throw new Error(`signDual: mode=${mode} requires a classical signer`);\n  }\n  if (needsPqc && !signers.pqc) {\n    throw new Error(`signDual: mode=${mode} requires a pqc signer`);\n  }\n\n  const payloadHash = await sha256(payload);\n\n  let classicalSignature = new Uint8Array(0);\n  let classicalSignerAddress = '';\n  if (needsClassical && signers.classical) {\n    classicalSignerAddress = await signers.classical.getAddress();\n    classicalSignature = (await signers.classical.sign(payloadHash)) as Uint8Array<ArrayBuffer>;\n  }\n\n  let pqcSignature = new Uint8Array(0);\n  let pqcPublicKey = new Uint8Array(0);\n  if (needsPqc && signers.pqc) {\n    pqcPublicKey = (await signers.pqc.getPublicKey()) as Uint8Array<ArrayBuffer>;\n    pqcSignature = (await signers.pqc.sign(payloadHash)) as Uint8Array<ArrayBuffer>;\n  }\n\n  return {\n    version: DUAL_SIG_ENVELOPE_VERSION_V1,\n    mode,\n    payloadHash,\n    classicalAlgo: CLASSICAL_ALGO_ECDSA_P256,\n    classicalSignature,\n    classicalSignerAddress,\n    pqcAlgo: PQC_ALGO_ML_DSA_65,\n    pqcSignature,\n    pqcPublicKey,\n  };\n}\n\n// ── Utilities ─────────────────────────────────────────────────────────\n\n/**\n * SHA-256 hash via Node's built-in `crypto` module. Async to match the\n * WebCrypto shape (subtle.digest is async); makes drop-in browser/runtime\n * substitution straightforward if we ever need to verify in-browser.\n */\nasync function sha256(bytes: Uint8Array): Promise<Uint8Array> {\n  const { createHash } = await import('crypto');\n  const h = createHash('sha256');\n  h.update(bytes);\n  return new Uint8Array(h.digest());\n}\n\n/**\n * Constant-time byte-array comparison. Used for payloadHash equality so a\n * tampered envelope can't time-leak which bytes diverged.\n */\nfunction constantTimeEqual(a: Uint8Array, b: Uint8Array): boolean {\n  if (a.length !== b.length) return false;\n  let diff = 0;\n  for (let i = 0; i < a.length; i++) diff |= a[i] ^ b[i];\n  return diff === 0;\n}\n","/**\n * Signing-middleware helper — Phase 1.5 wiring (task _wfrt).\n *\n * Bridges the request-signing verifier (../request-signing.ts) and the\n * attestation registry (./attestation-registry.ts) into a single helper that\n * route handlers can call once-per-mutation to:\n *   1. Detect whether the request body is a signed envelope or a legacy\n *      unsigned body (strict by default; HOLOMESH_SIGNING_GRACE=1 opts\n *      into the grace period where unsigned requests are still accepted).\n *   2. Verify the cryptographic signature (when present) and the registry\n *      check (when the registry is populated).\n *   3. Return the effective body (unwrapped from the envelope when present)\n *      so existing route logic continues to read body.x without change.\n *   4. Return a SigningContext that the handler attaches to broadcasts /\n *      audit logs / req metadata.\n *\n * The HoloMesh router is a custom dispatcher (handleTeamRoutes), not an\n * Express middleware chain, so this is deliberately a *helper* — the\n * canonical call-site recipe is documented at the bottom of this file.\n *\n * Spec: research/2026-04-21_seat-wallets-adr.md §\"Shared — HoloMesh signing\n * protocol\", \"Server-side verification\", \"Grace period for legacy unsigned\n * requests\".\n *\n * @module holomesh/identity/signing-middleware\n */\n\nimport * as http from 'http';\nimport {\n  canonicalizeBody,\n  extractEnvelope,\n  verifyEnvelope,\n  type SignedEnvelope,\n  type VerifyResult,\n} from '../request-signing';\nimport { AttestationRegistry } from './attestation-registry';\nimport {\n  parseDualSignatureEnvelope,\n  verifyDualSignature,\n  type DualSignatureEnvelope,\n  type IClassicalVerifier,\n  type VerifyDualSignatureResult,\n} from './dual-signature-envelope';\nimport {\n  CapabilityTokenError,\n  CapabilityTokenRegistry,\n  type Capability,\n  type StoredCapabilityToken,\n} from '@holoscript/secrets-broker';\n\n// ── Singleton registry instance ────────────────────────────────────────\n\nlet _registry: AttestationRegistry | null = null;\n\n/**\n * Module-level singleton AttestationRegistry. Lazy-initialized so test code\n * can inject a fresh instance via `setAttestationRegistry`. Production code\n * paths share state across the verifier middleware, the founder dashboard\n * route, and any future audit/replay tools.\n */\nexport function getAttestationRegistry(): AttestationRegistry {\n  if (!_registry) _registry = new AttestationRegistry();\n  return _registry;\n}\n\n/** Test-only: replace the singleton (e.g. with an SSE-broadcasting variant). */\nexport function setAttestationRegistry(registry: AttestationRegistry): void {\n  _registry = registry;\n}\n\n/** Test-only: drop the singleton so the next get() creates a fresh registry. */\nexport function resetAttestationRegistry(): void {\n  _registry = null;\n}\n\n// ── Per-request signing context ───────────────────────────────────────\n\nexport interface SigningContext {\n  /** True when the request body was a {body, signature, ...} envelope. */\n  signedRequest: boolean;\n  /** True when signature verified AND registry check passed (or was skipped). */\n  signingValid: boolean;\n  /** signer_address from a signed envelope, or null when unsigned.\n   *\n   * For dual-envelope `pqc_only` mode this is a synthetic identifier of the\n   * form `pqc:<first-16-hex-of-publickey>`; the AttestationRegistry does not\n   * yet carry PQC public keys (follow-up task — extend registry with\n   * `pqcPublicKey` field). */\n  signer: string | null;\n  /** Failure reason from request-signing.verifyEnvelope (timestamp-stale, etc). */\n  signingReason?: string;\n  /** Signing protocol used. `classical` = legacy EIP-191 ECDSA envelope.\n   *  `dual` = post-quantum DualSignatureEnvelope (any of its 3 modes).\n   *  `capability` = short-lived capability-token Bearer auth (no payload\n   *  integrity — caller asserts a single capability scope per request). */\n  signingProtocol?: 'classical' | 'dual' | 'capability';\n  /** When `signingProtocol='dual'`, which mode the envelope used. */\n  dualMode?: 'classical_only' | 'pqc_only' | 'dual';\n  /** When `signingProtocol='capability'`, the capability the token was scoped\n   *  to for THIS request. The route handler asserted it via `req.capability`;\n   *  the registry validated the token grants it. */\n  capabilityScope?: Capability;\n  /** Convenience alias — granted capability scopes for ForkSandboxGate.\n   *  Populated from capabilityScope when present, otherwise empty. */\n  scopes?: string[];\n}\n\nexport interface ExtractAndVerifyResult {\n  /** The body the route handler should consume. Unwrapped when signed. */\n  effectiveBody: unknown;\n  ctx: SigningContext;\n}\n\nexport interface ExtractAndVerifyOptions {\n  /** Override the registry (default: module singleton). */\n  registry?: AttestationRegistry;\n  /** Override now-ms for deterministic tests. */\n  nowMs?: number;\n  /** Force strict mode regardless of HOLOMESH_SIGNING_MIGRATION_ACK env. */\n  strictMode?: boolean;\n  /** Inject env vars for tests (default: process.env). */\n  env?: NodeJS.ProcessEnv;\n  /** Inject a classical-side verifier for the dual-signature path (default:\n   *  ViemClassicalVerifier). Tests use a deterministic mock. */\n  classicalVerifier?: IClassicalVerifier;\n  /** Inject the capability-token registry for the capability auth path\n   *  (default: module singleton). Tests pass a fresh registry. */\n  capabilityRegistry?: CapabilityTokenRegistry;\n  /**\n   * When true, skip ALL signing requirements and return signingValid=true.\n   * Use for founder/admin callers whose identity is already established via\n   * the key registry — they can write without a signed envelope until\n   * client-side signing is rolled out to all agent surfaces.\n   */\n  bypassSigning?: boolean;\n}\n\n// ── Capability-token registry singleton ───────────────────────────────\n\nlet _capabilityRegistry: CapabilityTokenRegistry | null = null;\n\n/**\n * Module-level singleton CapabilityTokenRegistry. Same lazy-init pattern as\n * the AttestationRegistry singleton above — production paths share state\n * across the verifier middleware, the broker-issued mint route, and the\n * broker-revoke route.\n */\nexport function getCapabilityRegistry(): CapabilityTokenRegistry {\n  if (!_capabilityRegistry) _capabilityRegistry = new CapabilityTokenRegistry();\n  return _capabilityRegistry;\n}\n\n/** Test-only: replace the singleton. */\nexport function setCapabilityRegistry(registry: CapabilityTokenRegistry): void {\n  _capabilityRegistry = registry;\n}\n\n/** Test-only: drop the singleton. */\nexport function resetCapabilityRegistry(): void {\n  _capabilityRegistry = null;\n}\n\n// ── Capability-token header resolver ────────────────────────────────────\n\nexport interface CapabilityHeaderResult {\n  token: StoredCapabilityToken | null;\n  error?: string;\n}\n\n/**\n * Resolve a capability token presented in the `Authorization` header.\n *\n * Expected format: `Authorization: Bearer <tokenId>:<tokenSecret>`\n *\n * Regular API keys (no colon separator) are ignored — callers should fall\n * through to legacy Bearer resolution (e.g. `resolveRequestingAgent`).\n *\n * On success, returns the stored token record. On failure because a token\n * was presented but invalid, returns `{ token: null, error: <reason> }`.\n * When no capability token is present at all, returns `{ token: null }`.\n */\nexport function resolveCapabilityFromHeader(\n  req: http.IncomingMessage,\n  needsCapability: Capability\n): CapabilityHeaderResult {\n  const auth = req.headers['authorization'];\n  if (typeof auth !== 'string' || !auth.startsWith('Bearer ')) {\n    return { token: null };\n  }\n  const bearer = auth.slice(7).trim();\n\n  // Capability tokens use `<tokenId>:<tokenSecret>` format.\n  // Regular API keys do not contain a colon in this position.\n  const colonIdx = bearer.indexOf(':');\n  if (colonIdx === -1) {\n    return { token: null };\n  }\n\n  const tokenId = bearer.slice(0, colonIdx);\n  const tokenSecret = bearer.slice(colonIdx + 1);\n\n  const registry = getCapabilityRegistry();\n  try {\n    registry.validateById(tokenId, tokenSecret, needsCapability);\n    const stored = registry.get(tokenId);\n    return { token: stored ?? null };\n  } catch (err) {\n    if (err instanceof CapabilityTokenError) {\n      return { token: null, error: capabilityTokenErrorToSigningReason(err) };\n    }\n    throw err;\n  }\n}\n\n// ── Dual-signature envelope request shape ─────────────────────────────\n//\n// Callers signal opt-in to the dual-sig path with an `envelope_type: 'dual'`\n// discriminator on the request body. This keeps the legacy classical envelope\n// shape (`{body, signature, signer_address, nonce, timestamp}`) untouched —\n// existing callers continue to work, dual-capable callers opt in explicitly.\n//\n// Canonicalization MUST match the signer side: `canonicalizeBody({body,\n// nonce, timestamp})` from request-signing.ts. Identical canonicalizer means\n// the signer's payload hash and the verifier's recomputed hash agree, which\n// is what the DualSignatureEnvelope.payloadHash field commits to.\n//\nexport interface DualEnvelopeRequestBody {\n  envelope_type: 'dual';\n  /** Base64-encoded bytes of a serialized DualSignatureEnvelope. */\n  envelope_b64: string;\n  /** The actual payload the handler will consume. */\n  body: unknown;\n  /** Replay-protection nonce (mirrors classical envelope). */\n  nonce: string;\n  /** RFC 3339 timestamp (mirrors classical envelope). */\n  timestamp: string;\n}\n\nexport function isDualEnvelopeBody(b: unknown): b is DualEnvelopeRequestBody {\n  if (b === null || typeof b !== 'object') return false;\n  const obj = b as Record<string, unknown>;\n  return (\n    obj.envelope_type === 'dual' &&\n    typeof obj.envelope_b64 === 'string' &&\n    typeof obj.nonce === 'string' &&\n    typeof obj.timestamp === 'string'\n  );\n}\n\n// ── Capability-token envelope request shape ─────────────────────────────\n//\n// Third auth shape — used by surfaces that cannot easily sign (mobile,\n// headless reduced-trust), and for high-volume read operations where the\n// signing overhead is excessive. Caller MUST declare `capability` so the\n// registry can enforce scope. The token itself carries the set of granted\n// capabilities; this request asserts which ONE of them is being exercised\n// right now.\n//\n// Trade-off vs signed envelopes: a capability token proves IDENTITY but\n// NOT PAYLOAD INTEGRITY. An attacker who steals the token can mint\n// arbitrary requests up to the token's granted capabilities. Route\n// handlers that mutate high-trust state (mesh:sign, protocol:publish)\n// should require signed envelopes regardless of capability scope.\n//\nexport interface CapabilityEnvelopeRequestBody {\n  envelope_type: 'capability';\n  /** Token id (e.g. `captok_a1b2c3...`). */\n  token_id: string;\n  /** Plaintext token secret. Hashed internally before comparison. */\n  token_secret: string;\n  /** The actual payload the handler will consume. */\n  body: unknown;\n  /** Capability the caller is exercising. Must be in the token's granted set. */\n  capability: Capability;\n}\n\nexport function isCapabilityEnvelopeBody(b: unknown): b is CapabilityEnvelopeRequestBody {\n  if (b === null || typeof b !== 'object') return false;\n  const obj = b as Record<string, unknown>;\n  return (\n    obj.envelope_type === 'capability' &&\n    typeof obj.token_id === 'string' &&\n    typeof obj.token_secret === 'string' &&\n    typeof obj.capability === 'string'\n  );\n}\n\n/** Map a CapabilityTokenError.code to a stable SigningContext.signingReason. */\nfunction capabilityTokenErrorToSigningReason(err: CapabilityTokenError): string {\n  switch (err.code) {\n    case 'TOKEN_REVOKED':\n      return 'capability-token-revoked';\n    case 'TOKEN_EXPIRED':\n      return 'capability-token-expired';\n    case 'TOKEN_INVALID_SECRET':\n      return 'capability-token-invalid';\n    case 'CAPABILITY_NOT_IN_TRUST_TIER':\n      return 'capability-not-granted';\n    default:\n      return `capability-error-${err.code}`;\n  }\n}\n\n/** Decode base64 -> bytes. Returns null on malformed input. */\nfunction base64Decode(s: string): Uint8Array | null {\n  try {\n    const buf = Buffer.from(s, 'base64');\n    // Round-trip sanity check: base64 silently ignores invalid chars; require\n    // that re-encoding produces the same string modulo padding (so a caller\n    // can't smuggle arbitrary bytes via non-base64 input).\n    if (buf.toString('base64').replace(/=+$/, '') !== s.replace(/=+$/, '')) {\n      return null;\n    }\n    return new Uint8Array(buf);\n  } catch {\n    return null;\n  }\n}\n\n/** Map a DualSignatureEnvelope to a SigningContext.signer string.\n *\n * For `classical_only` / `dual`: returns the 0x-Ethereum address.\n * For `pqc_only`: returns `pqc:<first-16-hex-of-publickey>` (synthetic id —\n * registry-side PQC support is a follow-up task). */\nfunction dualEnvelopeSignerId(env: DualSignatureEnvelope): string {\n  if (env.mode === 'classical_only' || env.mode === 'dual') {\n    return env.classicalSignerAddress;\n  }\n  // pqc_only — derive a short stable identifier from the public key.\n  let hex = '';\n  const slice = env.pqcPublicKey.slice(0, 8);\n  for (let i = 0; i < slice.length; i++) {\n    hex += slice[i].toString(16).padStart(2, '0');\n  }\n  return `pqc:${hex}`;\n}\n\n/** Map a VerifyDualSignatureResult.reason to a SigningContext.signingReason. */\nfunction dualReasonToSigningReason(r: VerifyDualSignatureResult): string | undefined {\n  if (r.valid) return undefined;\n  switch (r.reason) {\n    case 'payload-hash-mismatch':\n      return 'dual-payload-tampered';\n    case 'classical-signature-invalid':\n      return 'dual-classical-invalid';\n    case 'pqc-signature-invalid':\n      return 'dual-pqc-invalid';\n    case 'classical-verify-threw':\n      return 'dual-classical-verify-threw';\n    case 'pqc-verify-threw':\n      return 'dual-pqc-verify-threw';\n    case 'unsupported-classical-algo':\n      return 'dual-unsupported-classical-algo';\n    case 'unsupported-pqc-algo':\n      return 'dual-unsupported-pqc-algo';\n    case 'mode-mismatch':\n      return 'dual-mode-mismatch';\n    default:\n      return 'dual-verify-failed';\n  }\n}\n\n/**\n * Duration of the Phase 3 grace period in milliseconds. Unsigned requests\n * are accepted for this long after `HOLOMESH_SIGNING_DEPLOY_DATE`, then\n * automatically rejected. Per ADR §Q4 the window is 14 days.\n */\nexport const GRACE_PERIOD_MS = 14 * 24 * 60 * 60 * 1000;\n\n/**\n * True when the server should reject unsigned mutating requests outright.\n *\n * Phase 3 strict-by-default: unsigned requests are rejected unless the\n * operator explicitly opts out. Two escape hatches, either sufficient:\n *\n *   1. **Explicit opt-out**: `HOLOMESH_SIGNING_GRACE=1` disables strict mode\n *      for machines that are not yet sending signed requests. Set this\n *      temporarily during rollout until all clients are signing.\n *\n *   2. **Timed cutover**: when `HOLOMESH_SIGNING_DEPLOY_DATE` is set (ISO\n *      8601 date string) and the current time is past `deployDate + 14 days`,\n *      unsigned requests are automatically rejected regardless of GRACE.\n *      This implements the Phase 3 14-day migration window from ADR §Q4.\n *\n * Migration note (2026-05-14): the old `HOLOMESH_SIGNING_MIGRATION_ACK=1`\n * opt-in is no longer checked — strict mode is now the default. Remove\n * MIGRATION_ACK from deployment configs; it has no effect.\n */\nexport function isStrictMode(\n  env: NodeJS.ProcessEnv = process.env,\n  nowMs: number = Date.now()\n): boolean {\n  // Phase 3: strict mode is ON by default. Set GRACE=1 to opt out during\n  // the transition period (for machines not yet sending signed requests).\n  if (env.HOLOMESH_SIGNING_GRACE === '1') return false;\n\n  // Timed cutover: automatic strict mode after the 14-day grace period.\n  // This is redundant when strict is already the default, but kept as a\n  // safety net for configs that set DEPLOY_DATE without GRACE=1.\n  const deployDateStr = env.HOLOMESH_SIGNING_DEPLOY_DATE;\n  if (deployDateStr) {\n    const deployMs = Date.parse(deployDateStr);\n    if (!Number.isNaN(deployMs) && nowMs >= deployMs + GRACE_PERIOD_MS) {\n      return true;\n    }\n  }\n\n  // Default: strict mode ON (signed attribution required).\n  return true;\n}\n\n/**\n * Extract a signing envelope from a request body and verify it against the\n * attestation registry. Returns the effective body (unwrapped) plus a\n * SigningContext that route handlers attach to broadcasts / audit logs.\n *\n * Failure modes:\n *   - body is unsigned + strict-mode → ctx.signingValid=false, reason='unsigned-rejected'\n *   - body is unsigned + GRACE=1    → ctx.signingValid=true (Phase 3 grace),\n *     reason='unsigned-grace'\n *   - body is signed + envelope verifies + registry attests → signingValid=true\n *   - any verifier failure → signingValid=false, reason from verifyEnvelope\n *     (timestamp-stale / signature-mismatch / signer-retired / signer-not-attested)\n */\nexport async function extractAndVerifySigning(\n  reqBody: unknown,\n  options: ExtractAndVerifyOptions = {}\n): Promise<ExtractAndVerifyResult> {\n  // Founder/admin bypass: identity already established via key registry.\n  // Unsigned requests from founder callers are accepted during the transition\n  // period until all agent surfaces implement client-side signing.\n  if (options.bypassSigning) {\n    // Founder clients may still use the shared signed-envelope transport. The\n    // bypass skips cryptographic verification, but route handlers must receive\n    // the same effective payload they would receive on the verified path.\n    const bypassEnvelope = extractEnvelope(reqBody);\n    return {\n      effectiveBody: bypassEnvelope ? bypassEnvelope.body : reqBody,\n      ctx: {\n        signedRequest: Boolean(bypassEnvelope),\n        signingValid: true,\n        signer: null,\n        signingReason: bypassEnvelope ? 'founder-bypass-envelope' : 'founder-bypass',\n        signingProtocol: 'classical',\n      },\n    };\n  }\n\n  const strict = options.strictMode ?? isStrictMode(options.env, options.nowMs);\n\n  // ── Capability-token envelope path (Bearer-style, mobile/headless) ──\n  //\n  // Detected first because envelope_type='capability' makes the discrimination\n  // unambiguous and the registry lookup is cheap. Callers exercising\n  // high-trust capabilities (mesh:sign / protocol:publish) should still\n  // require a signed envelope — capability scoping is at the route-handler\n  // boundary, not here.\n  if (isCapabilityEnvelopeBody(reqBody)) {\n    return verifyCapabilityEnvelopeRequest(reqBody, options);\n  }\n\n  // ── Dual-signature envelope path (post-quantum opt-in) ──────────\n  //\n  // Detect dual-envelope shape next so the legacy `extractEnvelope` doesn't\n  // misread `envelope_b64` as a classical signature field. The dual path is\n  // strictly opt-in (caller sets envelope_type='dual'); legacy callers fall\n  // through to the classical path below with no behavior change.\n  if (isDualEnvelopeBody(reqBody)) {\n    return verifyDualEnvelopeRequest(reqBody, options);\n  }\n\n  const env: SignedEnvelope | null = extractEnvelope(reqBody);\n  const registry = options.registry ?? getAttestationRegistry();\n\n  if (!env) {\n    return {\n      effectiveBody: reqBody,\n      ctx: {\n        signedRequest: false,\n        signingValid: !strict,\n        signer: null,\n        signingReason: strict ? 'unsigned-rejected' : 'unsigned-grace',\n        signingProtocol: 'classical',\n      },\n    };\n  }\n\n  // Only consult the registry when it has at least one attestation —\n  // an empty registry during early Phase 1.5 would reject every signer.\n  // This makes the substrate land safely before the founder dashboard\n  // populates real attestations.\n  const useRegistry = registry.size() > 0;\n  const verifyOptions = useRegistry\n    ? { nowMs: options.nowMs, registryCheck: registry.toRegistryCheck(options.nowMs) }\n    : { nowMs: options.nowMs };\n\n  const result: VerifyResult = await verifyEnvelope(env, verifyOptions);\n  return {\n    effectiveBody: env.body,\n    ctx: {\n      signedRequest: true,\n      signingValid: result.valid,\n      signer: result.signer,\n      signingReason: result.reason,\n      signingProtocol: 'classical',\n    },\n  };\n}\n\n// ── Dual-signature envelope verification path ─────────────────────────\n\n/**\n * Verify a dual-signature request body. Called by `extractAndVerifySigning`\n * when the body shape matches `DualEnvelopeRequestBody`.\n *\n * Reuses the verifier from `dual-signature-envelope.ts` so all envelope rules\n * (mode invariants, algorithm-tag checks, payload-hash recomputation) are\n * enforced consistently with the signer side.\n *\n * Canonicalization: `canonicalizeBody({body, nonce, timestamp})` — identical\n * to the classical envelope's signed payload, so a caller can switch from\n * classical to dual without changing how they canonicalize.\n */\nexport async function verifyDualEnvelopeRequest(\n  req: DualEnvelopeRequestBody,\n  options: ExtractAndVerifyOptions = {}\n): Promise<ExtractAndVerifyResult> {\n  // Decode the envelope bytes.\n  const envBytes = base64Decode(req.envelope_b64);\n  if (!envBytes) {\n    return {\n      effectiveBody: req.body,\n      ctx: {\n        signedRequest: true,\n        signingValid: false,\n        signer: null,\n        signingReason: 'dual-envelope-base64-malformed',\n        signingProtocol: 'dual',\n      },\n    };\n  }\n\n  // Parse the envelope.\n  const parsed = parseDualSignatureEnvelope(envBytes);\n  if (!parsed.ok) {\n    return {\n      effectiveBody: req.body,\n      ctx: {\n        signedRequest: true,\n        signingValid: false,\n        signer: null,\n        signingReason: `dual-envelope-parse-${parsed.reason}`,\n        signingProtocol: 'dual',\n      },\n    };\n  }\n\n  // Canonicalize the payload identically to the classical signing protocol.\n  const canonical = canonicalizeBody({\n    body: req.body,\n    nonce: req.nonce,\n    timestamp: req.timestamp,\n  });\n  const payloadBytes = new TextEncoder().encode(canonical);\n\n  // Verify (recomputes SHA-256 internally, checks against envelope.payloadHash).\n  const result = await verifyDualSignature(parsed.envelope, payloadBytes, {\n    classicalVerifier: options.classicalVerifier,\n  });\n\n  if (!result.valid) {\n    return {\n      effectiveBody: req.body,\n      ctx: {\n        signedRequest: true,\n        signingValid: false,\n        signer: null,\n        signingReason: dualReasonToSigningReason(result),\n        signingProtocol: 'dual',\n        dualMode: parsed.envelope.mode,\n      },\n    };\n  }\n\n  // ── Registry checks (only when registry is populated — Phase 1.5 safe-default) ──\n  //\n  // Same safe-default as the classical path: an empty registry during early\n  // rollout should not reject every signer. Once any attestation is registered,\n  // checks become enforcing for that signer's mode.\n  const registry = options.registry ?? getAttestationRegistry();\n  const useRegistry = registry.size() > 0;\n  if (useRegistry) {\n    const env = parsed.envelope;\n    if (env.mode === 'classical_only') {\n      const check = registry.toRegistryCheck(options.nowMs);\n      const r = await check(env.classicalSignerAddress);\n      if (!r.attested) {\n        return {\n          effectiveBody: req.body,\n          ctx: {\n            signedRequest: true,\n            signingValid: false,\n            signer: null,\n            signingReason: r.reason ?? 'signer-not-attested',\n            signingProtocol: 'dual',\n            dualMode: env.mode,\n          },\n        };\n      }\n    } else if (env.mode === 'pqc_only') {\n      const pqcCheck = registry.toPqcRegistryCheck(options.nowMs);\n      const r = await pqcCheck(env.pqcPublicKey);\n      if (!r.attested) {\n        return {\n          effectiveBody: req.body,\n          ctx: {\n            signedRequest: true,\n            signingValid: false,\n            signer: null,\n            signingReason: r.reason ?? 'signer-not-attested',\n            signingProtocol: 'dual',\n            dualMode: env.mode,\n          },\n        };\n      }\n    } else {\n      // dual mode — cross-verify both keys map to the SAME attestation.\n      const cross = registry.crossVerifyDual(\n        env.classicalSignerAddress,\n        env.pqcPublicKey,\n        options.nowMs\n      );\n      if (!cross.matched) {\n        return {\n          effectiveBody: req.body,\n          ctx: {\n            signedRequest: true,\n            signingValid: false,\n            signer: null,\n            signingReason: cross.reason,\n            signingProtocol: 'dual',\n            dualMode: env.mode,\n          },\n        };\n      }\n    }\n  }\n\n  // Signer resolution: when the registry has an entry for this signer, prefer\n  // the canonical (lowercased) 0x-Ethereum-address — that's the form the\n  // registry stored on attest(). Works for all 3 modes:\n  //   - `classical_only` / `dual`: look up by the envelope's address\n  //   - `pqc_only`: look up by the PQC public key\n  // Falls back to the raw envelope address (or synthetic pqc:<hex> id) when\n  // the registry is empty or doesn't have an entry.\n  let signer = dualEnvelopeSignerId(parsed.envelope);\n  if (useRegistry) {\n    const env = parsed.envelope;\n    if (env.mode === 'pqc_only') {\n      const att = registry.lookupByPqcKey(env.pqcPublicKey);\n      if (att) signer = att.publicKey;\n    } else {\n      const att = registry.lookup(env.classicalSignerAddress);\n      if (att) signer = att.publicKey;\n    }\n  }\n\n  return {\n    effectiveBody: req.body,\n    ctx: {\n      signedRequest: true,\n      signingValid: true,\n      signer,\n      signingReason: undefined,\n      signingProtocol: 'dual',\n      dualMode: parsed.envelope.mode,\n    },\n  };\n}\n\n// ── Capability-token envelope verification path ───────────────────────\n\n/**\n * Verify a capability-token request body. Called by `extractAndVerifySigning`\n * when the body shape matches `CapabilityEnvelopeRequestBody`.\n *\n * Looks up the token in the CapabilityTokenRegistry and validates:\n *   - token exists\n *   - presented secret hashes match the stored hash\n *   - token is not revoked\n *   - token is not expired (vs `options.nowMs`)\n *   - the requested `capability` is in the token's granted set\n *\n * On any failure, returns a SigningContext with `signingValid=false` and a\n * structured `signingReason` (capability-token-revoked / -expired / -invalid\n * / capability-not-granted). On success, the `signer` is the token's\n * `handle` (e.g. `mobile1`) — NOT an Ethereum address (capability tokens\n * are surface-bound, not wallet-bound).\n */\nexport async function verifyCapabilityEnvelopeRequest(\n  req: CapabilityEnvelopeRequestBody,\n  options: ExtractAndVerifyOptions = {}\n): Promise<ExtractAndVerifyResult> {\n  const registry = options.capabilityRegistry ?? getCapabilityRegistry();\n  const nowDate = options.nowMs !== undefined ? new Date(options.nowMs) : new Date();\n\n  try {\n    registry.validateById(req.token_id, req.token_secret, req.capability, nowDate);\n  } catch (err) {\n    if (err instanceof CapabilityTokenError) {\n      return {\n        effectiveBody: req.body,\n        ctx: {\n          signedRequest: true,\n          signingValid: false,\n          signer: null,\n          signingReason: capabilityTokenErrorToSigningReason(err),\n          signingProtocol: 'capability',\n          capabilityScope: req.capability,\n        },\n      };\n    }\n    // Non-CapabilityTokenError — re-throw; callers will surface as 500.\n    throw err;\n  }\n\n  // Validation passed. Surface the token's handle as the signer.\n  const stored = registry.get(req.token_id);\n  // stored must be defined here — validateById would have thrown otherwise.\n  const signer = stored ? stored.handle : null;\n\n  return {\n    effectiveBody: req.body,\n    ctx: {\n      signedRequest: true,\n      signingValid: true,\n      signer,\n      signingProtocol: 'capability',\n      capabilityScope: req.capability,\n    },\n  };\n}\n\n// ── requireCapability — authorization helper for capability-gated handlers ──\n\n/**\n * Result of a capability-authorization check. Discriminated union so callers\n * branch on `authorized` and get type-narrowed access to either `signer` or\n * `reason`.\n */\nexport type AuthorizationResult =\n  | { authorized: true; signer: string; protocol: 'classical' | 'dual' | 'capability' }\n  | { authorized: false; reason: AuthorizationFailureReason };\n\n/**\n * Stable reason strings handlers can match on for HTTP response shaping.\n * - `unsigned`              : request had no signing envelope at all (grace mode left signedRequest=false)\n * - `signing-invalid`       : envelope failed verification (signature mismatch, expired, etc.)\n * - `capability-scope-mismatch`: capability token DID NOT grant the requested capability\n * - `capability-required`   : route requires capability-token scoping; caller used classical/dual without the explicit allow flag\n * - `unknown-protocol`      : SigningContext.signingProtocol was unset (legacy unset path) or an unrecognized value\n */\nexport type AuthorizationFailureReason =\n  | 'unsigned'\n  | 'signing-invalid'\n  | 'capability-scope-mismatch'\n  | 'capability-required'\n  | 'unknown-protocol';\n\nexport interface RequireCapabilityOptions {\n  /**\n   * If true, accept a classical-envelope SigningContext WITHOUT\n   * capability-scope checking. Default `false` — classical envelopes carry\n   * identity but no scope, so capability-gated routes must opt in explicitly.\n   */\n  allowClassical?: boolean;\n  /**\n   * If true, accept a dual-envelope SigningContext WITHOUT capability-scope\n   * checking. Default `true` — dual envelopes are the strongest identity\n   * proof in the system; routes that opt out of dual should be rare.\n   */\n  allowDual?: boolean;\n}\n\n/**\n * Verify that a route caller is authorized to exercise `capability` against\n * a verified `SigningContext`.\n *\n * Semantics by `ctx.signingProtocol`:\n * - `capability`: authorized iff `ctx.capabilityScope === capability`.\n *   Capability tokens carry explicit scope; the registry already enforced\n *   that the scope is in the token's granted set at validate time.\n * - `dual`     : authorized when `options.allowDual !== false` (default true).\n *   Dual envelopes don't carry per-request capability scope, but they prove\n *   the strongest identity available — routes typically trust dual signers.\n * - `classical`: authorized when `options.allowClassical === true`.\n *   Default-off: classical signers must explicitly be admitted, since they\n *   don't carry per-request scope and run the legacy ECDSA path.\n *\n * Refuses outright when the caller is unsigned (`!ctx.signedRequest`) or when\n * the signing path failed (`!ctx.signingValid`) — regardless of what\n * `capability` the route asks for. These should never reach `requireCapability`\n * in normal flow (the verifier middleware would have rejected first), but\n * the guard catches mis-wired handlers.\n *\n * Designed to be one-liner-easy at the call site:\n *\n *   const auth = requireCapability(ctx, 'secrets:grant.create');\n *   if (!auth.authorized) return json(res, 401, { error: auth.reason });\n *   // …handler runs with auth.signer + auth.protocol attached to logs…\n *\n * Companion to the F.051 canary task_1778596074561_adcf — adopting this\n * helper closes the holo_secrets_* authorization gap with a single line\n * per handler.\n */\nexport function requireCapability(\n  ctx: SigningContext,\n  capability: Capability,\n  options: RequireCapabilityOptions = {}\n): AuthorizationResult {\n  if (!ctx.signedRequest) {\n    return { authorized: false, reason: 'unsigned' };\n  }\n  if (!ctx.signingValid) {\n    return { authorized: false, reason: 'signing-invalid' };\n  }\n  if (!ctx.signer) {\n    // Defense-in-depth: signingValid=true implies signer should be set.\n    // If a future code path lands an inconsistent ctx, treat it as failure.\n    return { authorized: false, reason: 'signing-invalid' };\n  }\n\n  switch (ctx.signingProtocol) {\n    case 'capability':\n      if (ctx.capabilityScope === capability) {\n        return { authorized: true, signer: ctx.signer, protocol: 'capability' };\n      }\n      return { authorized: false, reason: 'capability-scope-mismatch' };\n\n    case 'dual':\n      if (options.allowDual !== false) {\n        return { authorized: true, signer: ctx.signer, protocol: 'dual' };\n      }\n      return { authorized: false, reason: 'capability-required' };\n\n    case 'classical':\n      if (options.allowClassical === true) {\n        return { authorized: true, signer: ctx.signer, protocol: 'classical' };\n      }\n      return { authorized: false, reason: 'capability-required' };\n\n    default:\n      // ctx.signingProtocol is undefined or an unexpected value. Fail closed.\n      return { authorized: false, reason: 'unknown-protocol' };\n  }\n}\n\n// ── Canonical call-site recipe (documentation) ────────────────────────\n//\n// Inside a mutating handler in routes/team-routes.ts (or any other\n// HoloMesh route file):\n//\n//   const rawBody = await parseJsonBody(req);\n//   const { effectiveBody, ctx } = await extractAndVerifySigning(rawBody);\n//   if (!ctx.signingValid) {\n//     return json(res, 401, {\n//       error: 'signing-rejected',\n//       reason: ctx.signingReason,\n//     });\n//   }\n//   // …existing handler reads effectiveBody.x as before…\n//   broadcastToRoom(teamId, {\n//     type: 'team:join',\n//     agent: caller.name,\n//     data: {\n//       …,\n//       signer: ctx.signer,        // null when unsigned-grace\n//       signedRequest: ctx.signedRequest,\n//     },\n//   });\n//\n// Phase 3 strict-by-default: unsigned requests are rejected unless\n// HOLOMESH_SIGNING_GRACE=1 is set. Signed callers get richer attribution\n// and pass verification. Set GRACE=1 during rollout until all clients sign.\n","/**\n * PolicyInterceptor — CG-098 tracer bullet.\n *\n * Gates a narrow MCP tool family (`holo_secrets_grant`) before execution\n * against a versioned `.holo`/`.hsplus` PolicyPackTrait fixture, and emits a\n * compact policy receipt linked to the tool-call id.\n *\n * Source: research/2026-06-28_openclaw-nemoclaw-harvest.md (ai-ecosystem repo)\n * \"The strongest NemoClaw lesson maps directly to CG-098. Add\n * PolicyInterceptor in the MCP/server dispatch path:\n *   - Input: caller identity, tool name, resource, tenant/workspace\n *     context, provider lane, and declared capability.\n *   - Output: allow, deny, audit, or operator approval required.\n *   - Policy source: versioned .holo/.hsplus PolicyPackTrait, not ad hoc\n *     JSON.\n *   - Receipt: every decision writes a compact policy receipt linked to\n *     the tool execution receipt.\"\n *\n * Non-goals (explicit, per the board task):\n *   - Does NOT adopt OpenClaw/NemoClaw as a runtime.\n *   - Does NOT pass host credentials into any sandbox.\n *   - Does NOT wire public channels — this module only gates the existing\n *     `holo_secrets_grant` local dispatch path.\n *\n * Scope discipline: this gates ONE tool family (secrets-broker grants),\n * additively alongside the existing `gateSecretsBrokerTool` capability gate\n * in secrets-broker-handler.ts. It does not replace the Triple-Gate\n * pattern (security/gates.ts) or the OAuth scope gate (security/tool-scopes.ts)\n * — those remain the HTTP-transport authorization layer. PolicyInterceptor\n * is the declarative-policy-pack layer CG-098 asks for, proven end-to-end on\n * one tool family first.\n */\n\nimport { existsSync, readFileSync } from 'fs';\nimport { createHash } from 'crypto';\nimport { join, dirname } from 'path';\nimport { fileURLToPath } from 'url';\nimport { HoloScriptPlusParser } from '@holoscript/core';\n\nconst __dirname = dirname(fileURLToPath(import.meta.url));\n\n// ── Types ────────────────────────────────────────────────────────────────\n\nexport type PolicyDecisionKind = 'allow' | 'deny' | 'audit' | 'approval_required';\n\nexport interface PolicyRule {\n  rule_id: string;\n  tool: string;\n  decision: PolicyDecisionKind;\n  reason: string;\n  /** Match if the caller's agentId is in this list. */\n  when_agent_in?: string[];\n  /** Match if args.capabilityRef starts with this prefix. */\n  when_capability_ref_prefix?: string;\n}\n\nexport interface PolicyPack {\n  policy_id: string;\n  schema_version: string;\n  rules: PolicyRule[];\n  default_decision: PolicyDecisionKind;\n}\n\nexport interface PolicyInterceptorRequest {\n  /** Caller identity (agent id, wallet, or session handle). */\n  callerId: string;\n  /** MCP tool name being invoked. */\n  tool: string;\n  /** Resource the tool acts on (free-form — e.g. a secretRef or capabilityRef). */\n  resource: string;\n  /** Tenant/workspace context, when known. */\n  tenantId?: string;\n  /** Provider lane (e.g. 'stdio', 'http', 'holomesh'). */\n  lane?: string;\n  /** Raw tool arguments, used for rule matching (e.g. capabilityRef prefix). */\n  args?: Record<string, unknown>;\n  /** Tool-call id this decision should be linked to in the receipt. */\n  toolCallId: string;\n}\n\nexport interface PolicyDecision {\n  decision: PolicyDecisionKind;\n  policyId: string;\n  ruleId: string | null;\n  reason: string;\n}\n\nexport interface PolicyReceipt {\n  receiptId: string;\n  schemaVersion: '1.0.0';\n  recordedAt: string; // ISO-8601\n  policyId: string;\n  decision: PolicyDecisionKind;\n  caller: string;\n  action: string; // tool name\n  resource: string;\n  reason: string;\n  toolCallId: string; // links this receipt to the tool execution receipt\n}\n\n// ── Policy pack loading ──────────────────────────────────────────────────\n\nfunction defaultFixturePath(): string {\n  const candidates = [\n    join(__dirname, 'policy-pack.holo.hsplus'),\n    join(__dirname, '..', 'src', 'policy', 'policy-pack.holo.hsplus'),\n  ];\n  return candidates.find((candidate) => existsSync(candidate)) ?? candidates[0];\n}\n\nconst DEFAULT_FIXTURE_PATH = defaultFixturePath();\n\nlet cachedPack: PolicyPack | null = null;\nlet cachedFixturePath: string | null = null;\n\n/**\n * Parse a `.holo`/`.hsplus` PolicyPackTrait fixture with the real\n * HoloScriptPlusParser (not a hand-rolled JSON reader) and extract the\n * `@policy_pack { ... }` trait directive's config.\n *\n * Throws if the fixture fails to parse or does not carry a `policy_pack`\n * trait directive — a broken/malformed policy source must fail loud, not\n * silently fall back to an implicit allow-all.\n */\nexport function loadPolicyPack(fixturePath: string = DEFAULT_FIXTURE_PATH): PolicyPack {\n  if (cachedPack && cachedFixturePath === fixturePath) return cachedPack;\n\n  const source = readFileSync(fixturePath, 'utf-8');\n  const parser = new HoloScriptPlusParser();\n  const result = parser.parse(source);\n\n  if (result.errors && result.errors.length > 0) {\n    const first = result.errors[0] as { message?: string; line?: number };\n    throw new Error(\n      `PolicyInterceptor: fixture ${fixturePath} failed to parse (${result.errors.length} error(s)): ` +\n        `${first.message ?? 'unknown error'} at line ${first.line ?? '?'}`\n    );\n  }\n\n  const trait = findPolicyPackTrait(result.ast);\n  if (!trait) {\n    throw new Error(\n      `PolicyInterceptor: fixture ${fixturePath} parsed but no @policy_pack trait directive found`\n    );\n  }\n\n  const config = trait.config as Record<string, unknown>;\n  const pack: PolicyPack = {\n    policy_id: String(config.policy_id ?? 'unknown'),\n    schema_version: String(config.schema_version ?? '0.0.0'),\n    rules: Array.isArray(config.rules) ? (config.rules as PolicyRule[]) : [],\n    default_decision: (config.default_decision as PolicyDecisionKind) ?? 'allow',\n  };\n\n  cachedPack = pack;\n  cachedFixturePath = fixturePath;\n  return pack;\n}\n\n/** Test-only: clear the module-level policy pack cache. */\nexport function __resetPolicyPackCacheForTests(): void {\n  cachedPack = null;\n  cachedFixturePath = null;\n}\n\ninterface ParsedTraitDirective {\n  type: 'trait';\n  name: string;\n  config: Record<string, unknown>;\n}\n\nfunction findPolicyPackTrait(node: unknown, depth = 0): ParsedTraitDirective | null {\n  if (!node || typeof node !== 'object' || depth > 12) return null;\n  const n = node as {\n    directives?: Array<{ type?: string; name?: string; config?: unknown }>;\n    children?: unknown[];\n    compositions?: unknown[];\n  };\n\n  const directives = n.directives ?? [];\n  for (const d of directives) {\n    if (d && d.type === 'trait' && d.name === 'policy_pack') {\n      return d as ParsedTraitDirective;\n    }\n  }\n\n  const branches = [...(n.children ?? []), ...(n.compositions ?? [])];\n  for (const child of branches) {\n    const found = findPolicyPackTrait(child, depth + 1);\n    if (found) return found;\n  }\n\n  return null;\n}\n\n// ── Decision evaluation (pure) ───────────────────────────────────────────\n\n/**\n * Evaluate a PolicyInterceptorRequest against a loaded PolicyPack.\n *\n * Pure function — no I/O, no receipt emission. First matching rule wins\n * (rules are evaluated in fixture order); falls back to\n * `pack.default_decision` when no rule matches or the tool has no rules.\n */\nexport function evaluatePolicy(pack: PolicyPack, request: PolicyInterceptorRequest): PolicyDecision {\n  const toolRules = pack.rules.filter((r) => r.tool === request.tool);\n\n  for (const rule of toolRules) {\n    if (rule.when_agent_in && rule.when_agent_in.includes(request.callerId)) {\n      return { decision: rule.decision, policyId: pack.policy_id, ruleId: rule.rule_id, reason: rule.reason };\n    }\n    if (rule.when_capability_ref_prefix) {\n      const capRef = String(request.args?.capabilityRef ?? '');\n      if (capRef.startsWith(rule.when_capability_ref_prefix)) {\n        return { decision: rule.decision, policyId: pack.policy_id, ruleId: rule.rule_id, reason: rule.reason };\n      }\n    }\n  }\n\n  return {\n    decision: pack.default_decision,\n    policyId: pack.policy_id,\n    ruleId: null,\n    reason: 'no_rule_matched_default_decision',\n  };\n}\n\n// ── Receipt emission ─────────────────────────────────────────────────────\n\n/**\n * Build a compact policy receipt for a decision, linked to the tool-call id\n * (`toolCallId`) so it can be joined against the corresponding tool\n * execution receipt by callers that persist both.\n */\nexport function buildPolicyReceipt(\n  request: PolicyInterceptorRequest,\n  decision: PolicyDecision\n): PolicyReceipt {\n  const recordedAt = new Date().toISOString();\n  const base = {\n    schemaVersion: '1.0.0' as const,\n    recordedAt,\n    policyId: decision.policyId,\n    decision: decision.decision,\n    caller: request.callerId,\n    action: request.tool,\n    resource: request.resource,\n    reason: decision.reason,\n    toolCallId: request.toolCallId,\n  };\n  const canonical = JSON.stringify(base, Object.keys(base).sort());\n  const hash = createHash('sha256').update(canonical).digest('hex').slice(0, 16);\n  return { receiptId: `policy_${recordedAt.replace(/[:.]/g, '-')}_${hash}`, ...base };\n}\n\n// ── Public entry point ────────────────────────────────────────────────────\n\nexport interface PolicyInterceptorResult {\n  decision: PolicyDecision;\n  receipt: PolicyReceipt;\n}\n\n/**\n * Load the policy pack (cached after first call), evaluate the request, and\n * build a receipt. This is the single function the MCP dispatch path calls.\n */\nexport function interceptToolCall(\n  request: PolicyInterceptorRequest,\n  fixturePath?: string\n): PolicyInterceptorResult {\n  const pack = loadPolicyPack(fixturePath);\n  const decision = evaluatePolicy(pack, request);\n  const receipt = buildPolicyReceipt(request, decision);\n  return { decision, receipt };\n}\n","/**\n * MCP Secrets Broker Handlers\n *\n * Implements the logic for `holo_secrets_*` MCP tools.\n * Delegates to `@holoscript/secrets-broker` for grant logic and\n * `@holoscript/secrets-broker/lease-adapter` for lease resolution.\n *\n * Authorization: when called with a SigningContext (caller has access to a\n * verified per-request signing envelope), each tool is gated via\n * `requireCapability` so a caller MUST present a capability-token-scoped\n * envelope or an explicitly-permitted classical/dual envelope. Calls without\n * a signing context preserve the legacy ungated behavior — this matches the\n * existing TOOL_DISPATCH_REGISTRY path which threads only (name, args) per\n * the MCP tool contract. Once the dispatch chain is upgraded to pass\n * SigningContext through (canary task_1778596074561_adcf), every call gets\n * the gate automatically without any change here.\n *\n * Per-tool capability scopes:\n *   - holo_secrets_grant   → 'secrets:grant.create'\n *   - holo_secrets_resolve → 'secrets:grant.resolve'\n *   - holo_secrets_revoke  → 'secrets:grant.revoke'\n *\n * @module mcp-server/secrets-broker-handler\n */\n\nimport {\n  createSecretGrant,\n  createPolicyGatedSecretGrant,\n  createMemoryLeaseAdapter,\n} from '@holoscript/secrets-broker';\nimport type { Capability, SecretBrokerPolicy } from '@holoscript/secrets-broker';\nimport {\n  requireCapability,\n  type SigningContext,\n  type RequireCapabilityOptions,\n} from './holomesh/identity/signing-middleware';\nimport {\n  interceptToolCall,\n  type PolicyInterceptorResult,\n} from './policy/PolicyInterceptor';\nimport { randomUUID } from 'crypto';\n\n// Shared in-memory lease adapter for the MCP server process.\n// In production this would be backed by the vault-lease-registry PostgreSQL store.\nconst leaseAdapter = createMemoryLeaseAdapter();\n\n/**\n * Tools gated by the CG-098 PolicyInterceptor tracer bullet (declarative\n * PolicyPackTrait, additive alongside the SigningContext capability gate\n * above). Scoped to `holo_secrets_grant` only — the narrow tool family named\n * in the board task; `holo_secrets_resolve`/`holo_secrets_revoke` are not\n * gated by this tracer bullet.\n */\nconst POLICY_INTERCEPTED_TOOLS = new Set(['holo_secrets_grant']);\n\nexport interface PolicyInterceptorAuthError {\n  readonly authError: true;\n  readonly reason: string;\n  readonly tool: string;\n  readonly policyReceipt: PolicyInterceptorResult['receipt'];\n}\n\n/**\n * Run the PolicyInterceptor for a gated tool call. Returns `null` when the\n * call is allowed to proceed (decision is `allow` or `audit` — audit records\n * the decision but does not block execution). Returns a\n * `PolicyInterceptorAuthError` when the decision is `deny` or\n * `approval_required` (both block execution in this tracer bullet — no\n * async approval workflow exists yet, so `approval_required` fails closed).\n *\n * Fail-safe: if the interceptor itself throws (e.g. the fixture is missing\n * or fails to parse), the call is DENIED, never silently allowed — a broken\n * policy source must not become an open gate.\n */\nexport function gatePolicyInterceptedTool(\n  name: string,\n  args: Record<string, unknown>,\n  callerId: string\n): { authError: PolicyInterceptorAuthError | null; result: PolicyInterceptorResult | null } {\n  if (!POLICY_INTERCEPTED_TOOLS.has(name)) return { authError: null, result: null };\n\n  const toolCallId = randomUUID();\n  let result: PolicyInterceptorResult;\n  try {\n    result = interceptToolCall({\n      callerId,\n      tool: name,\n      resource: String(args.secretRef ?? args.capabilityRef ?? 'unknown'),\n      lane: 'stdio',\n      args,\n      toolCallId,\n    });\n  } catch (error) {\n    const message = error instanceof Error ? error.message : String(error);\n    return {\n      authError: {\n        authError: true,\n        reason: `policy_interceptor_failed: ${message}`,\n        tool: name,\n        policyReceipt: {\n          receiptId: `policy_error_${toolCallId}`,\n          schemaVersion: '1.0.0',\n          recordedAt: new Date().toISOString(),\n          policyId: 'unknown',\n          decision: 'deny',\n          caller: callerId,\n          action: name,\n          resource: String(args.secretRef ?? args.capabilityRef ?? 'unknown'),\n          reason: 'policy_interceptor_failed',\n          toolCallId,\n        },\n      },\n      result: null,\n    };\n  }\n\n  if (result.decision.decision === 'deny' || result.decision.decision === 'approval_required') {\n    return {\n      authError: {\n        authError: true,\n        reason: result.decision.reason,\n        tool: name,\n        policyReceipt: result.receipt,\n      },\n      result,\n    };\n  }\n\n  // 'allow' and 'audit' both proceed; 'audit' still carries a receipt the\n  // caller can inspect via `result`.\n  return { authError: null, result };\n}\n\n/**\n * Per-tool capability requirements. The MCP dispatch path passes a\n * SigningContext through when available; each tool is gated against the\n * capability listed here. Tools NOT listed here run ungated (legacy path).\n */\nexport const SECRETS_BROKER_TOOL_CAPABILITIES: Record<string, Capability> = {\n  holo_secrets_grant: 'secrets:grant.create' as Capability,\n  holo_secrets_resolve: 'secrets:grant.resolve' as Capability,\n  holo_secrets_revoke: 'secrets:grant.revoke' as Capability,\n};\n\nexport interface SecretsBrokerAuthError {\n  readonly authError: true;\n  readonly reason: string;\n  readonly tool: string;\n  readonly requiredCapability: Capability;\n}\n\nfunction hasClassicalBrokerScope(signingCtx: SigningContext, capability: Capability): boolean {\n  if (signingCtx.signingProtocol !== 'classical') return false;\n  return hasBrokerScope(signingCtx, capability);\n}\n\nfunction hasBrokerScope(signingCtx: SigningContext, capability: Capability): boolean {\n  const scopes = new Set((signingCtx.scopes ?? []).map(String));\n  return (\n    scopes.has('admin:*') ||\n    scopes.has('tools:admin') ||\n    scopes.has(String(capability))\n  );\n}\n\n/**\n * Gate a secrets-broker tool call against the SigningContext.\n *\n * Returns `null` when authorized (or when no signingCtx is provided —\n * matches legacy ungated behavior). Returns a `SecretsBrokerAuthError` when\n * a signingCtx is provided but the request is not authorized for `name`.\n */\nexport function gateSecretsBrokerTool(\n  name: string,\n  signingCtx?: SigningContext,\n  options?: RequireCapabilityOptions\n): SecretsBrokerAuthError | null {\n  if (!signingCtx) return null; // Legacy ungated path.\n  const cap = SECRETS_BROKER_TOOL_CAPABILITIES[name];\n  if (\n    cap &&\n    !signingCtx.signedRequest &&\n    signingCtx.signingValid &&\n    signingCtx.signer &&\n    hasBrokerScope(signingCtx, cap)\n  ) {\n    return null;\n  }\n  if (!cap) return null; // Tool name unknown to the gate — let downstream reject.\n  const authOptions = options ?? (\n    hasClassicalBrokerScope(signingCtx, cap) ? { allowClassical: true } : undefined\n  );\n  const auth = requireCapability(signingCtx, cap, authOptions);\n  if (auth.authorized) return null;\n  return { authError: true, reason: auth.reason, tool: name, requiredCapability: cap };\n}\n\nexport async function handleSecretsBrokerTool(\n  name: string,\n  args: Record<string, unknown>,\n  signingCtx?: SigningContext,\n  authOptions?: RequireCapabilityOptions\n): Promise<unknown | null> {\n  // Authorization gate — runs only when caller threads a SigningContext.\n  // Legacy callers (current TOOL_DISPATCH_REGISTRY entries) omit this and\n  // keep working unchanged.\n  const authError = gateSecretsBrokerTool(name, signingCtx, authOptions);\n  if (authError) return authError;\n\n  // CG-098 PolicyInterceptor gate — declarative PolicyPackTrait decision,\n  // additive alongside the SigningContext capability gate above. Runs BEFORE\n  // the tool body so a `deny`/`approval_required` decision blocks execution\n  // (createSecretGrant / createPolicyGatedSecretGrant never run).\n  const callerId = signingCtx?.signer ?? String(args.agentId ?? 'unknown');\n  const { authError: policyAuthError, result: policyResult } = gatePolicyInterceptedTool(\n    name,\n    args,\n    callerId\n  );\n  if (policyAuthError) return policyAuthError;\n\n  switch (name) {\n    case 'holo_secrets_grant': {\n      const namespaceId = String(args.namespaceId ?? '');\n      const agentId = String(args.agentId ?? '');\n      const secretRef = String(args.secretRef ?? '');\n      const capabilityRef = String(args.capabilityRef ?? '');\n      const purpose = String(args.purpose ?? '');\n      const ttlSeconds =\n        typeof args.ttlSeconds === 'number' && Number.isFinite(args.ttlSeconds)\n          ? args.ttlSeconds\n          : undefined;\n      const policy = (args.policy as SecretBrokerPolicy | undefined) ?? undefined;\n      const policyReceipt = policyResult?.receipt;\n\n      if (policy) {\n        const result = createPolicyGatedSecretGrant(\n          { namespaceId, agentId, secretRef, capabilityRef, purpose, ttlSeconds },\n          policy\n        );\n        // Also issue a lease so resolve/revoke work end-to-end.\n        const lease = await leaseAdapter.issueLease({\n          taskId: result.grant.grantId,\n          agentId,\n          scope: [secretRef],\n          durationMs: (ttlSeconds ?? 15 * 60) * 1000,\n        });\n        return {\n          status: 'granted',\n          grant: result.grant,\n          policyDecision: result.policyDecision,\n          leaseId: lease.leaseId,\n          leaseExpiresAt: lease.expiresAt,\n          policyReceipt,\n        };\n      }\n\n      const grant = createSecretGrant({\n        namespaceId,\n        agentId,\n        secretRef,\n        capabilityRef,\n        purpose,\n        ttlSeconds,\n      });\n      const lease = await leaseAdapter.issueLease({\n        taskId: grant.grantId,\n        agentId,\n        scope: [secretRef],\n        durationMs: (ttlSeconds ?? 15 * 60) * 1000,\n      });\n      return {\n        status: 'granted',\n        grant,\n        leaseId: lease.leaseId,\n        leaseExpiresAt: lease.expiresAt,\n        policyReceipt,\n      };\n    }\n\n    case 'holo_secrets_resolve': {\n      const leaseId = String(args.leaseId ?? '');\n      const agentId = String(args.agentId ?? '');\n      const secretRef = String(args.secretRef ?? '');\n      const result = await leaseAdapter.resolveLease({ leaseId, agentId, secretRef });\n      return {\n        ok: result.ok,\n        reason: result.reason,\n        leaseId,\n        agentId,\n        secretRef,\n      };\n    }\n\n    case 'holo_secrets_revoke': {\n      const leaseId = String(args.leaseId ?? '');\n      const reason = String(args.reason ?? 'manual');\n      const by = String(args.by ?? 'system');\n      const result = await leaseAdapter.revokeLease({ leaseId, reason, by });\n      return {\n        ok: result.ok,\n        leaseId,\n        reason,\n        by,\n      };\n    }\n\n    default:\n      return null;\n  }\n}\n","/**\n * world-render-tools.ts — MCP tool surface for rendering a Studio world on the\n * GPU fleet (`render_world_on_fleet`).\n *\n * Why this exists: fleet dispatch needs an orchestrator submit key (resolved from\n * HoloKey/env and sent as `x-mcp-api-key` to the mcp-orchestrator GPU queue) — a\n * high-privilege credential. We do NOT copy it into every client. Instead, a\n * Bearer-authed MCP client (Studio, Brittney, Cursor, a cloud Claude Code session)\n * calls `render_world_on_fleet` with the world source; THIS server holds the key\n * and makes the privileged POST /gpu/workload server-side. This is the dispatch\n * wiring that closes the FleetOrchestrator \"can see the board, cannot dispatch\" gap\n * for world rendering. Mirrors holo-ci-tools.ts (`holo_ci_dispatch`).\n *\n * The render-target registry + workload builder below is a faithful TypeScript port\n * of ai-ecosystem/scripts/lib/world-render-workload.mjs (the fleet-side canonical).\n * Duplicated rather than imported — HoloScript and ai-ecosystem are separate repos\n * with no shared module path (same convention as holo-ci-tools.ts). KEEP IN SYNC:\n * the worker runs ai-ecosystem/scripts/world-render-runner.mjs, so the target list +\n * command shape here must match that runner's flags.\n *\n * SAFE-BY-DEFAULT: previews the workload and submits nothing unless dryRun:false.\n * `engine:'pending'` targets (video/quilt/stills) need the GPU render-engine worker\n * image and are refused on submit (the runner would fail-loud anyway).\n */\n\nimport { Tool } from '@modelcontextprotocol/sdk/types.js';\nimport { resolveServiceSecret } from './holokey-resolver';\n\n// ─── Render-target registry (port of WORLD_RENDER_TARGETS) ───────────────────\ntype RenderMode = 'compile' | 'rasterize';\ntype RenderEngine = 'available' | 'pending';\ninterface RenderTarget {\n  mode: RenderMode;\n  compileTarget: string | null;\n  artifactExt: string;\n  requiresGpu: boolean;\n  engine: RenderEngine;\n  defaultEstimateSeconds: number;\n  label: string;\n}\n\nconst WORLD_RENDER_TARGETS: Record<string, RenderTarget> = {\n  '3dgs': {\n    mode: 'compile',\n    compileTarget: '3dgs',\n    artifactExt: 'gltf',\n    requiresGpu: true,\n    engine: 'available',\n    defaultEstimateSeconds: 600,\n    label: '3D Gaussian Splatting bake (KHR_gaussian_splatting glTF)',\n  },\n  gltf: {\n    mode: 'compile',\n    compileTarget: 'gltf',\n    artifactExt: 'gltf',\n    requiresGpu: false,\n    engine: 'available',\n    defaultEstimateSeconds: 120,\n    label: 'glTF scene export',\n  },\n  webgpu: {\n    mode: 'compile',\n    compileTarget: 'webgpu',\n    artifactExt: 'wgsl',\n    requiresGpu: true,\n    engine: 'available',\n    defaultEstimateSeconds: 300,\n    label: 'WebGPU / WGSL render bundle',\n  },\n  usd: {\n    mode: 'compile',\n    compileTarget: 'usd',\n    artifactExt: 'usd',\n    requiresGpu: false,\n    engine: 'available',\n    defaultEstimateSeconds: 180,\n    label: 'OpenUSD stage export',\n  },\n  video: {\n    mode: 'rasterize',\n    compileTarget: null,\n    artifactExt: 'mp4',\n    requiresGpu: true,\n    engine: 'pending',\n    defaultEstimateSeconds: 900,\n    label: 'Cinematic video render',\n  },\n  quilt: {\n    mode: 'rasterize',\n    compileTarget: null,\n    artifactExt: 'png',\n    requiresGpu: true,\n    engine: 'pending',\n    defaultEstimateSeconds: 600,\n    label: 'Light-field quilt (Looking Glass)',\n  },\n  stills: {\n    mode: 'rasterize',\n    compileTarget: null,\n    artifactExt: 'png',\n    requiresGpu: true,\n    engine: 'pending',\n    defaultEstimateSeconds: 600,\n    label: 'Path-traced high-resolution stills',\n  },\n};\n\nconst QUALITY_MULTIPLIER: Record<string, number> = { draft: 0.5, standard: 1, high: 2, ultra: 4 };\n\nfunction availableTargets(): string[] {\n  return Object.entries(WORLD_RENDER_TARGETS)\n    .filter(([, t]) => t.engine === 'available')\n    .map(([k]) => k);\n}\n\n/** POSIX single-quote escape so paths/base64/URLs survive `bash -lc \"$cmd\"`. */\nfunction shellQuote(value: string): string {\n  const s = String(value);\n  if (/^[A-Za-z0-9_./:-]+$/.test(s)) return s;\n  return `'${s.replace(/'/g, `'\\\\''`)}'`;\n}\n\nconst NODE_SELF_BOOTSTRAP =\n  'command -v node >/dev/null 2>&1 || { curl -fsSL https://deb.nodesource.com/setup_20.x | bash - >/dev/null 2>&1 && apt-get install -y -qq nodejs >/dev/null 2>&1; }';\n\nconst MAX_WORKLOAD_ID_LENGTH = 64;\n\nfunction workloadIdSegment(value: string): string {\n  return (\n    String(value || 'world')\n      .replace(/[^A-Za-z0-9_.-]+/g, '-')\n      .replace(/^-+|-+$/g, '')\n      .slice(0, 48) || 'world'\n  );\n}\n\nfunction buildWorldRenderWorkloadId(target: string, worldId: string): string {\n  const prefix = `world-render-${workloadIdSegment(target)}-`;\n  const room = Math.max(1, MAX_WORKLOAD_ID_LENGTH - prefix.length);\n  return `${prefix}${workloadIdSegment(worldId).slice(0, room)}`;\n}\n\ninterface WorldRenderSpec {\n  world?: string; // inline HoloScript source text (preferred for MCP/Studio callers)\n  worldUrl?: string; // OR a fetchable URL\n  worldPath?: string; // OR a repo-relative path on the worker\n  target: string;\n  quality?: string;\n  worldId?: string;\n  outputDir?: string;\n  customer?: string;\n}\n\ninterface BuiltWorldRender {\n  workload: Record<string, unknown>;\n  target: RenderTarget;\n  estimateSeconds: number;\n}\n\nfunction buildWorldRenderWorkload(spec: WorldRenderSpec): BuiltWorldRender {\n  const t = WORLD_RENDER_TARGETS[spec.target];\n  if (!t) {\n    throw new Error(\n      `unknown target \"${spec.target}\" — known: ${Object.keys(WORLD_RENDER_TARGETS).join(', ')}`\n    );\n  }\n  if (!spec.world && !spec.worldUrl && !spec.worldPath) {\n    throw new Error('one of world (inline source), worldUrl, or worldPath is required');\n  }\n  const quality = spec.quality && spec.quality in QUALITY_MULTIPLIER ? spec.quality : 'standard';\n  const estimateSeconds = Math.ceil(t.defaultEstimateSeconds * (QUALITY_MULTIPLIER[quality] ?? 1));\n  const worldId = spec.worldId || 'world';\n  const id = buildWorldRenderWorkloadId(spec.target, worldId);\n  const outputDir = spec.outputDir || './render-output';\n\n  let worldArg: string;\n  if (spec.world) {\n    worldArg = `--world-b64 ${shellQuote(Buffer.from(spec.world, 'utf8').toString('base64'))}`;\n  } else if (spec.worldUrl) {\n    worldArg = `--world-url ${shellQuote(spec.worldUrl)}`;\n  } else {\n    worldArg = `--world ${shellQuote(spec.worldPath as string)}`;\n  }\n\n  const runnerCommand = [\n    'node',\n    'scripts/world-render-runner.mjs',\n    worldArg,\n    `--target ${spec.target}`,\n    `--quality ${quality}`,\n    `--output-dir ${shellQuote(outputDir)}`,\n    spec.worldId ? `--world-id ${shellQuote(spec.worldId)}` : '',\n    '--write-receipt',\n  ]\n    .filter(Boolean)\n    .join(' ');\n  const command = `${NODE_SELF_BOOTSTRAP}; ${runnerCommand}`;\n\n  const workload = {\n    id,\n    name: `World render: ${t.label}`,\n    description: `Render world ${worldId} to ${spec.target} (${t.label}) on the GPU fleet.`,\n    billing: {\n      rate_usd_per_sec: 0.0003,\n      credits_per_usd: 100.0,\n      buffer: 0.15,\n      margin: 0.3,\n      customer: spec.customer || 'studio-world-render',\n    },\n    render: {\n      target: spec.target,\n      mode: t.mode,\n      engine: t.engine,\n      requiresGpu: t.requiresGpu,\n      artifactExt: t.artifactExt,\n    },\n    jobs: [\n      {\n        id: `${id}-render`,\n        job_type: 'render',\n        description: `Render ${spec.target} (${t.label}) for world ${worldId}`,\n        command,\n        estimate_seconds: estimateSeconds,\n        lane: t.requiresGpu ? 'gpu' : 'ci',\n        requires_gpu: t.requiresGpu,\n        requires_webgpu: t.requiresGpu,\n        device_preference: t.requiresGpu ? 'gpu' : 'cpu',\n        ...(t.requiresGpu ? { gpu_memory_mb: 8000 } : {}),\n        ...(t.requiresGpu\n          ? { resource_requirements: { min_vram_gb: 8, num_gpus: 1 } }\n          : {}),\n        resources: t.requiresGpu\n          ? { gpu: { count: 1, memory_mb: 8000 }, cpu_cores: 2, packing_group: 'world-render' }\n          : { cpu_cores: 2, packing_group: 'world-render' },\n        tier: 'T2',\n      },\n    ],\n  };\n\n  return { workload, target: t, estimateSeconds };\n}\n\n// ─── Orchestrator helpers (mirror holo-ci-tools.ts) ──────────────────────────\nconst ORCHESTRATOR_KEY_NAMES = [\n  'HOLOSCRIPT_ORCHESTRATOR_API_KEY',\n  'MCP_ORCHESTRATOR_API_KEY',\n  'ORCHESTRATOR_API_KEY',\n  'MCP_API_KEY',\n  'HOLOSCRIPT_API_KEY',\n] as const;\n\nasync function resolveOrchestratorKey(): Promise<string> {\n  for (const name of ORCHESTRATOR_KEY_NAMES) {\n    const value = await resolveServiceSecret(name);\n    if (value) return value;\n  }\n  return '';\n}\n\nfunction orchestratorUrl(): string {\n  return (\n    process.env.MCP_ORCHESTRATOR_URL || 'https://mcp-orchestrator-production-45f9.up.railway.app'\n  ).replace(/\\/$/, '');\n}\n\n// ─── Tool definition ─────────────────────────────────────────────────────────\nexport const worldRenderTools: Tool[] = [\n  {\n    name: 'render_world_on_fleet',\n    description:\n      'Render a HoloScript world on the vast.ai GPU fleet via the mcp-orchestrator GPU queue. The orchestrator key is held server-side, so any authenticated MCP client (Studio, Brittney, an agent) can dispatch a render without holding fleet credentials. SAFE-BY-DEFAULT: this PREVIEWS the workload and submits nothing unless dryRun:false (which incurs real GPU spend). Compile-backed targets (3dgs/gltf/webgpu/usd) render to render-ready data + a SHA-256 receipt today; rasterize targets (video/quilt/stills) need the GPU render-engine image and are refused on submit. Returns the submitted workload id; poll workload status and receipt fields via GET /gpu/workload/:id.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        world: {\n          type: 'string',\n          description:\n            'The HoloScript world source text (inline). Preferred for Studio/in-memory worlds — it is base64-shipped to the worker.',\n        },\n        worldUrl: {\n          type: 'string',\n          description: 'Alternative to `world`: a fetchable URL to the world source.',\n        },\n        worldPath: {\n          type: 'string',\n          description:\n            'Alternative: a repo-relative path to the world on the worker (e.g. workloads/samples/demo-cube.hs).',\n        },\n        target: {\n          type: 'string',\n          enum: Object.keys(WORLD_RENDER_TARGETS),\n          description:\n            'Render target. Available now: 3dgs, gltf, webgpu, usd. Pending (GPU image): video, quilt, stills.',\n        },\n        quality: {\n          type: 'string',\n          enum: Object.keys(QUALITY_MULTIPLIER),\n          description: 'Render quality (scales the billing estimate). Default standard.',\n        },\n        worldId: { type: 'string', description: 'Identifier for receipt provenance.' },\n        dryRun: {\n          type: 'boolean',\n          description:\n            'Default TRUE (safe): build + return the workload WITHOUT submitting (no key, no spend). Pass false to ACTUALLY submit to the fleet and incur real spend.',\n        },\n      },\n      required: ['target'],\n    },\n  },\n];\n\n// ─── Handler ─────────────────────────────────────────────────────────────────\n/**\n * Handle `render_world_on_fleet`. `callerToken` is the requesting client's token\n * (used only if a future per-caller spend cap is added; not stored). Returns null\n * for any other tool name.\n */\nexport async function handleWorldRenderTool(\n  name: string,\n  args: Record<string, unknown>,\n  _callerToken?: string\n): Promise<unknown | null> {\n  if (name !== 'render_world_on_fleet') return null;\n\n  const target = typeof args.target === 'string' ? args.target : '';\n  // Safe-by-default: preview unless the caller EXPLICITLY opts into real GPU spend.\n  const dryRun = args.dryRun !== false;\n\n  let built: BuiltWorldRender;\n  try {\n    built = buildWorldRenderWorkload({\n      world: typeof args.world === 'string' ? args.world : undefined,\n      worldUrl: typeof args.worldUrl === 'string' ? args.worldUrl : undefined,\n      worldPath: typeof args.worldPath === 'string' ? args.worldPath : undefined,\n      target,\n      quality: typeof args.quality === 'string' ? args.quality : undefined,\n      worldId: typeof args.worldId === 'string' ? args.worldId : undefined,\n    });\n  } catch (err) {\n    return { ok: false, error: err instanceof Error ? err.message : String(err) };\n  }\n\n  const enginePending = built.target.engine === 'pending';\n\n  if (dryRun) {\n    return {\n      ok: true,\n      dryRun: true,\n      enginePending,\n      render: built.workload.render,\n      estimateSeconds: built.estimateSeconds,\n      workload: built.workload,\n      note: enginePending\n        ? `Target \"${target}\" needs the GPU render-engine image (engine: pending); submit will be refused. Available now: ${availableTargets().join(', ')}.`\n        : undefined,\n    };\n  }\n\n  // ── non-dry submit path ──\n  if (enginePending) {\n    return {\n      ok: false,\n      enginePending: true,\n      error: `Target \"${target}\" (${built.target.label}) needs the GPU render-engine worker image (engine: pending). Available now: ${availableTargets().join(', ')}.`,\n    };\n  }\n\n  const apiKey = await resolveOrchestratorKey();\n  if (!apiKey) {\n    return {\n      ok: false,\n      error:\n        'Orchestrator key not provisioned on this server via HoloKey/env (HOLOSCRIPT_ORCHESTRATOR_API_KEY / MCP_ORCHESTRATOR_API_KEY / ORCHESTRATOR_API_KEY / MCP_API_KEY / HOLOSCRIPT_API_KEY unset). Re-run with dryRun:true to preview, or provision the key. Do not use HOLOSCRIPT_MCP_API_KEY or HOLOMESH_API_KEY for fleet submit auth.',\n      workload: built.workload,\n    };\n  }\n\n  try {\n    const res = await fetch(`${orchestratorUrl()}/gpu/workload`, {\n      method: 'POST',\n      headers: { 'Content-Type': 'application/json; charset=utf-8', 'x-mcp-api-key': apiKey },\n      body: JSON.stringify(built.workload),\n      signal: AbortSignal.timeout(20_000),\n    });\n    const text = await res.text();\n    let parsed: unknown = text;\n    try {\n      parsed = JSON.parse(text);\n    } catch {\n      /* leave as text */\n    }\n    if (!res.ok) {\n      return {\n        ok: false,\n        error: `orchestrator /gpu/workload → ${res.status}`,\n        detail: typeof parsed === 'string' ? parsed.slice(0, 400) : parsed,\n      };\n    }\n    const wlId =\n      (parsed as { id?: string; workload_id?: string })?.id ??\n      (parsed as { workload_id?: string })?.workload_id ??\n      (built.workload as { id?: string }).id;\n    return {\n      ok: true,\n      dispatched: true,\n      target,\n      workloadId: wlId,\n      estimateSeconds: built.estimateSeconds,\n      render: built.workload.render,\n      orchestrator: parsed,\n      note: 'Worker claims via GET /gpu/next; artifact + SHA-256 receipt return via POST /gpu/job/:id/done. Poll GET /gpu/workload/:id for job status and receipt fields.',\n    };\n  } catch (err) {\n    return {\n      ok: false,\n      error: `orchestrator submit failed: ${err instanceof Error ? err.message : String(err)}`,\n    };\n  }\n}\n","/**\n * robot-ai-mcp-tools.ts ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€šÃ‚Â Federated Robot / AI MCP tools\n *\n * Extracted from hololand-mcp-tools.ts to avoid absorbing game semantics.\n * These tools manage robot and AI identities, safety envelopes, permissions,\n * actuation, and substrate receipts ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€šÃ‚Â purely substrate concepts with no\n * dependency on shards, zones, quests, NPCs, or other game-world constructs.\n *\n * Federation: registered independently in tools.ts so they can be discovered\n * and used without pulling in the full HoloLand game-world surface.\n */\n\nimport type { Tool } from '@modelcontextprotocol/sdk/types.js';\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { dirname, resolve } from 'node:path';\nimport {\n  type TwinEarthIdentity,\n  type PermissionGrant,\n  type SafetyEnvelope,\n  type RobotDispatcher,\n  type DispatchRequest,\n  gatedDispatch,\n  StubRobotDispatcher,\n} from '@holoscript/framework';\n\n// =============================================================================\n// TYPES\n// =============================================================================\n\nexport interface StoredTwinEarthIdentity {\n  agentId: string;\n  walletAddress: string;\n  handle: string;\n  attestation: string;\n  attestedAt: string;\n  role: string;\n  mode: string;\n  kind: 'robot' | 'ai';\n  hardwareFingerprint?: string;\n  brainCompositionId?: string;\n  revoked: boolean;\n  revokedAt?: string;\n  createdAt: string;\n  modifiedAt: string;\n}\n\nexport interface StoredSafetyEnvelope {\n  id: string;\n  agentId: string;\n  maxTickDurationMs: number;\n  maxMemoryBytes: number;\n  maxNetworkCallsPerMinute: number;\n  allowedActions: string[];\n  blockedActions: string[];\n  deterministic: boolean;\n  localOnly: boolean;\n  substrateEnforced: boolean;\n  updatedAt?: string;\n  freshnessTtlMs?: number;\n  humanApprovalRequired?: boolean;\n  humanApprovalGrantedAt?: string;\n  humanApprovalTtlMs?: number;\n  createdAt: string;\n  modifiedAt: string;\n}\n\nexport interface StoredPermissionGrant {\n  granteeId: string;\n  granterId: string;\n  action: string;\n  scope: string;\n  expiresAt: string | null;\n  revocationSignature: string | null;\n  hash: string;\n  grantedAt: string;\n}\n\ninterface StoredTwinEarthReceipt {\n  id: string;\n  kind: 'action' | 'validation' | 'steward_tick' | 'contract_upgrade';\n  actorId: string;\n  action: string;\n  scope: string;\n  timestamp: string;\n  status: 'success' | 'failure' | 'timeout' | 'rejected_by_envelope';\n  hash: string;\n  envelopeId: string;\n  payloadHash?: string;\n}\n\n// =============================================================================\n// REGISTRIES\n// =============================================================================\n\n// THIN (ratchet P5): identity/permission/envelope registries are in-memory only â€” no persistence, no substrate enforcement. All state lost on server restart.\nexport const twinEarthIdentityRegistry = new Map<string, StoredTwinEarthIdentity>();\nexport const safetyEnvelopeRegistry = new Map<string, StoredSafetyEnvelope>();\nexport const permissionGrantRegistry = new Map<string, StoredPermissionGrant>();\nexport const twinEarthReceiptRegistry = new Map<string, StoredTwinEarthReceipt>();\n\nconst PHYSICAL_WORLD_ACTIONS = ['actuator:command', 'robot:move', 'robot:task:execute'] as const;\n\nexport interface RobotAiRegistrySnapshot {\n  version: 1;\n  updatedAt: string;\n  identities: StoredTwinEarthIdentity[];\n  safetyEnvelopes: StoredSafetyEnvelope[];\n  permissionGrants: StoredPermissionGrant[];\n  receipts: StoredTwinEarthReceipt[];\n}\n\nexport interface RobotAiRegistryPersistenceOptions {\n  /** Load the snapshot immediately after changing the persistence path. */\n  load?: boolean;\n}\n\nconst DEFAULT_ROBOT_AI_REGISTRY_PATH = resolve(\n  homedir(),\n  '.holoscript',\n  'twin-earth-registries.json'\n);\n\nfunction initialRobotAiRegistryPath(): string | null {\n  if (process.env.TWIN_EARTH_REGISTRY_PERSISTENCE === '0') {\n    return null;\n  }\n  const configured = process.env.TWIN_EARTH_REGISTRY_PATH ?? process.env.ROBOT_AI_REGISTRY_PATH;\n  if (configured) {\n    return resolve(configured);\n  }\n  if (process.env.NODE_ENV === 'test' || process.env.VITEST) {\n    return null;\n  }\n  return DEFAULT_ROBOT_AI_REGISTRY_PATH;\n}\n\nlet robotAiRegistryPersistencePath: string | null = initialRobotAiRegistryPath();\n\nexport function getRobotAiRegistryPersistencePath(): string | null {\n  return robotAiRegistryPersistencePath;\n}\n\nexport function configureRobotAiRegistryPersistence(\n  path: string | null,\n  options: RobotAiRegistryPersistenceOptions = {}\n): void {\n  robotAiRegistryPersistencePath = path ? resolve(path) : null;\n  if (options.load) {\n    loadRobotAiRegistries();\n  }\n}\n\nfunction snapshotRobotAiRegistries(): RobotAiRegistrySnapshot {\n  return {\n    version: 1,\n    updatedAt: new Date().toISOString(),\n    identities: Array.from(twinEarthIdentityRegistry.values()),\n    safetyEnvelopes: Array.from(safetyEnvelopeRegistry.values()),\n    permissionGrants: Array.from(permissionGrantRegistry.values()),\n    receipts: Array.from(twinEarthReceiptRegistry.values()),\n  };\n}\n\nfunction requireArray<T>(value: unknown): T[] {\n  return Array.isArray(value) ? (value as T[]) : [];\n}\n\nexport function loadRobotAiRegistries(path = robotAiRegistryPersistencePath): boolean {\n  if (!path || !existsSync(path)) {\n    return false;\n  }\n\n  const snapshot = JSON.parse(readFileSync(path, 'utf8')) as Partial<RobotAiRegistrySnapshot>;\n  twinEarthIdentityRegistry.clear();\n  safetyEnvelopeRegistry.clear();\n  permissionGrantRegistry.clear();\n  twinEarthReceiptRegistry.clear();\n\n  for (const identity of requireArray<StoredTwinEarthIdentity>(snapshot.identities)) {\n    twinEarthIdentityRegistry.set(identity.agentId, identity);\n  }\n  for (const envelope of requireArray<StoredSafetyEnvelope>(snapshot.safetyEnvelopes)) {\n    safetyEnvelopeRegistry.set(envelope.id, envelope);\n  }\n  for (const grant of requireArray<StoredPermissionGrant>(snapshot.permissionGrants)) {\n    permissionGrantRegistry.set(grant.hash, grant);\n  }\n  for (const receipt of requireArray<StoredTwinEarthReceipt>(snapshot.receipts)) {\n    twinEarthReceiptRegistry.set(receipt.id, receipt);\n  }\n  return true;\n}\n\nexport function flushRobotAiRegistries(path = robotAiRegistryPersistencePath): boolean {\n  if (!path) {\n    return false;\n  }\n  mkdirSync(dirname(path), { recursive: true });\n  writeFileSync(path, `${JSON.stringify(snapshotRobotAiRegistries(), null, 2)}\\n`, 'utf8');\n  return true;\n}\n\nfunction persistRobotAiRegistries(): void {\n  flushRobotAiRegistries();\n}\n\nfunction includesPhysicalWorldAction(actions: string[]): boolean {\n  return actions.some((action) => (PHYSICAL_WORLD_ACTIONS as readonly string[]).includes(action));\n}\n\nfunction genId(prefix: string): string {\n  return `${prefix}_${Date.now()}_${Math.random().toString(36).slice(2, 7)}`;\n}\n\n// =============================================================================\n// ROBOT DISPATCHER WIRING (production seam)\n// =============================================================================\n//\n// The default dispatcher is the HONEST stub (no hardware; simulated:true,\n// dispatchedTo:'stub'). Production deployments inject a real RobotDispatcher\n// (e.g. ROS2/MQTT-backed) via `setRobotDispatcher` and the safety-gated receipt\n// path in handleTwinEarthRobotActuate flows the real backend through unchanged.\nlet activeRobotDispatcher: RobotDispatcher = new StubRobotDispatcher();\n\n/** Inject the robot dispatcher backend. Pass StubRobotDispatcher to reset. */\nexport function setRobotDispatcher(dispatcher: RobotDispatcher): void {\n  activeRobotDispatcher = dispatcher;\n}\n\n/** Current robot dispatcher backend (defaults to the honest stub). */\nexport function getRobotDispatcher(): RobotDispatcher {\n  return activeRobotDispatcher;\n}\n\n/** Clear all in-memory registries ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€šÃ‚Â used by tests for isolation. */\nexport function clearRobotAiRegistries(options: { persist?: boolean } = {}): void {\n  twinEarthIdentityRegistry.clear();\n  safetyEnvelopeRegistry.clear();\n  permissionGrantRegistry.clear();\n  twinEarthReceiptRegistry.clear();\n  if (options.persist !== false) {\n    persistRobotAiRegistries();\n  }\n}\n\ntry {\n  loadRobotAiRegistries();\n} catch (error) {\n  console.warn(\n    `[robot-ai-mcp-tools] failed to load Twin Earth registry snapshot: ${\n      error instanceof Error ? error.message : String(error)\n    }`\n  );\n}\n\nasync function simpleHash(input: string): Promise<string> {\n  const encoder = new TextEncoder();\n  const data = encoder.encode(input);\n  const hashBuffer = await crypto.subtle.digest('SHA-256', data);\n  const hashArray = Array.from(new Uint8Array(hashBuffer));\n  return hashArray.map((b) => b.toString(16).padStart(2, '0')).join('');\n}\n\n// =============================================================================\n// TOOL DEFINITIONS\n// =============================================================================\n\nexport const robotAiMcpTools: Tool[] = [\n  // Identity CRUD\n  {\n    name: 'twin_earth_register_identity',\n    description:\n      'Register a new robot or AI identity on the substrate. THIN: attestation is stored but never cryptographically verified. ' +\n      'Requires wallet-based attestation. Returns the canonical substrate identity record.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        agentId: {\n          type: 'string',\n          description: 'Unique substrate identifier. Auto-generated if omitted.',\n        },\n        walletAddress: {\n          type: 'string',\n          description:\n            'EVM or Solana wallet address ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€šÃ‚Â root of trust.',\n        },\n        handle: { type: 'string', description: 'Human-readable handle.' },\n        attestation: {\n          type: 'string',\n          description: 'EIP-712 typed-data signature over (agentId + handle + timestamp).',\n        },\n        attestedAt: { type: 'string', description: 'ISO-8601 timestamp of attestation.' },\n        role: {\n          type: 'string',\n          enum: ['founder', 'steward', 'operator', 'robot', 'ai', 'brittney', 'visitor'],\n          description: 'Substrate role. Default: robot.',\n        },\n        mode: {\n          type: 'string',\n          enum: ['local', 'BYOK', 'managed'],\n          description: 'Participation mode. Default: local.',\n        },\n        kind: {\n          type: 'string',\n          enum: ['robot', 'ai'],\n          description: 'Hardware (robot) or software (ai) participant.',\n        },\n        hardwareFingerprint: {\n          type: 'string',\n          description: 'Device serial hash for robots. Optional.',\n        },\n        brainCompositionId: {\n          type: 'string',\n          description: 'Brain composition reference for AIs. Optional.',\n        },\n      },\n      required: ['walletAddress', 'handle', 'attestation', 'kind'],\n    },\n  },\n  {\n    name: 'twin_earth_get_identity',\n    description: 'Retrieve a substrate identity by agentId.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        agentId: { type: 'string', description: 'Identity agentId' },\n      },\n      required: ['agentId'],\n    },\n  },\n  {\n    name: 'twin_earth_update_identity',\n    description:\n      'Update mutable fields of an existing substrate identity ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€šÃ‚Â handle, role, mode, brain composition. ' +\n      'Requires a fresh attestation if handle changes.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        agentId: { type: 'string', description: 'Identity agentId' },\n        handle: { type: 'string' },\n        role: {\n          type: 'string',\n          enum: ['founder', 'steward', 'operator', 'robot', 'ai', 'brittney', 'visitor'],\n        },\n        mode: { type: 'string', enum: ['local', 'BYOK', 'managed'] },\n        brainCompositionId: { type: 'string' },\n      },\n      required: ['agentId'],\n    },\n  },\n  {\n    name: 'twin_earth_revoke_identity',\n    description:\n      'Revoke a substrate identity ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€šÃ‚Â permanently disables the identity and invalidates all active safety envelopes. ' +\n      'Requires granterId with founder or steward role.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        agentId: { type: 'string', description: 'Identity to revoke' },\n        granterId: {\n          type: 'string',\n          description: 'Identity performing revocation (must be founder or steward).',\n        },\n        revocationSignature: {\n          type: 'string',\n          description: 'Wallet signature of revocation intent.',\n        },\n      },\n      required: ['agentId', 'granterId', 'revocationSignature'],\n    },\n  },\n  {\n    name: 'twin_earth_list_identities',\n    description: 'List substrate identities with optional filtering by role, kind, or mode.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        role: {\n          type: 'string',\n          enum: ['founder', 'steward', 'operator', 'robot', 'ai', 'brittney', 'visitor'],\n          description: 'Filter by role.',\n        },\n        kind: { type: 'string', enum: ['robot', 'ai'], description: 'Filter by kind' },\n        mode: {\n          type: 'string',\n          enum: ['local', 'BYOK', 'managed'],\n          description: 'Filter by mode.',\n        },\n        limit: { type: 'number', description: 'Max results. Default: 50' },\n        offset: { type: 'number', description: 'Pagination offset. Default: 0' },\n      },\n    },\n  },\n\n  // Safety Envelope CRUD\n  {\n    name: 'twin_earth_create_safety_envelope',\n    description:\n      'Create a Safety Envelope — runtime-enforced boundary for a robot or AI participant. THIN: substrateEnforced flag is advisory, not enforced at runtime. ' +\n      'Substrate-enforced; the participant cannot override it.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        envelopeId: {\n          type: 'string',\n          description: 'Envelope identifier. Auto-generated if omitted.',\n        },\n        agentId: { type: 'string', description: 'Identity this envelope applies to.' },\n        maxTickDurationMs: {\n          type: 'number',\n          description: 'Max compute budget per tick (ms). Default: 1000.',\n        },\n        maxMemoryBytes: {\n          type: 'number',\n          description: 'Max memory per session (bytes). Default: 536870912 (512 MB).',\n        },\n        maxNetworkCallsPerMinute: {\n          type: 'number',\n          description: 'Max outbound network calls per minute. Default: 60.',\n        },\n        allowedActions: {\n          type: 'array',\n          items: { type: 'string' },\n          description: 'Action whitelist. Empty = all permitted (dangerous).',\n        },\n        blockedActions: {\n          type: 'array',\n          items: { type: 'string' },\n          description:\n            'Action blacklist ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€šÃ‚Â overrides whitelist.',\n        },\n        deterministic: {\n          type: 'boolean',\n          description: 'Seed randomness for reproducibility. Default: false.',\n        },\n        localOnly: {\n          type: 'boolean',\n          description: 'Block all outbound network calls. Default: false.',\n        },\n        freshnessTtlMs: {\n          type: 'number',\n          description: 'Max envelope age before high-risk actuation is rejected.',\n        },\n        humanApprovalRequired: {\n          type: 'boolean',\n          description:\n            'Require recent human approval. Defaults true when physical actions are allowlisted.',\n        },\n        humanApprovalGrantedAt: {\n          type: 'string',\n          description: 'ISO-8601 timestamp of the most recent human approval.',\n        },\n        humanApprovalTtlMs: {\n          type: 'number',\n          description: 'Max human approval age before re-approval is required.',\n        },\n      },\n      required: ['agentId'],\n    },\n  },\n  {\n    name: 'twin_earth_get_safety_envelope',\n    description: 'Retrieve a Safety Envelope by envelopeId.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        envelopeId: { type: 'string', description: 'Envelope identifier' },\n      },\n      required: ['envelopeId'],\n    },\n  },\n  {\n    name: 'twin_earth_update_safety_envelope',\n    description: 'Update mutable fields of an existing Safety Envelope.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        envelopeId: { type: 'string', description: 'Envelope identifier' },\n        maxTickDurationMs: { type: 'number' },\n        maxMemoryBytes: { type: 'number' },\n        maxNetworkCallsPerMinute: { type: 'number' },\n        allowedActions: { type: 'array', items: { type: 'string' } },\n        blockedActions: { type: 'array', items: { type: 'string' } },\n        deterministic: { type: 'boolean' },\n        localOnly: { type: 'boolean' },\n        freshnessTtlMs: { type: 'number' },\n        humanApprovalRequired: { type: 'boolean' },\n        humanApprovalGrantedAt: { type: 'string' },\n        humanApprovalTtlMs: { type: 'number' },\n      },\n      required: ['envelopeId'],\n    },\n  },\n  {\n    name: 'twin_earth_delete_safety_envelope',\n    description:\n      'Delete a Safety Envelope. Requires granterId with founder or steward role. ' +\n      'Deleting an active envelope forces the participant into a default restrictive envelope.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        envelopeId: { type: 'string', description: 'Envelope identifier' },\n        granterId: {\n          type: 'string',\n          description: 'Identity performing deletion (must be founder or steward).',\n        },\n      },\n      required: ['envelopeId', 'granterId'],\n    },\n  },\n  {\n    name: 'twin_earth_list_safety_envelopes',\n    description: 'List Safety Envelopes with optional filtering by agentId.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        agentId: { type: 'string', description: 'Filter by identity' },\n        limit: { type: 'number', description: 'Max results. Default: 50' },\n        offset: { type: 'number', description: 'Pagination offset. Default: 0' },\n      },\n    },\n  },\n\n  // Permission CRUD\n  {\n    name: 'twin_earth_grant_permission',\n    description:\n      'Grant a signed, revocable permission to a robot or AI identity. ' +\n      'Actions are scoped namespace identifiers (e.g. actuator:move, inference:*, contract:sign).',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        granteeId: { type: 'string', description: 'Identity receiving the permission.' },\n        granterId: { type: 'string', description: 'Identity issuing the permission.' },\n        action: {\n          type: 'string',\n          description: 'Action being permitted. E.g. actuator:move or inference:*',\n        },\n        scope: {\n          type: 'string',\n          description: 'Scope of grant (contextId, resourceId, or *). Default: *.',\n        },\n        expiresAt: { type: 'string', description: 'ISO-8601 expiry. Null = no expiry.' },\n      },\n      required: ['granteeId', 'granterId', 'action'],\n    },\n  },\n  {\n    name: 'twin_earth_revoke_permission',\n    description: 'Revoke an existing permission grant by its hash.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        grantHash: { type: 'string', description: 'Hash of the permission grant to revoke.' },\n        granterId: {\n          type: 'string',\n          description: 'Identity performing revocation (must match original granter).',\n        },\n        revocationSignature: {\n          type: 'string',\n          description: 'Wallet signature of revocation intent.',\n        },\n      },\n      required: ['grantHash', 'granterId', 'revocationSignature'],\n    },\n  },\n  {\n    name: 'twin_earth_validate_permission',\n    description:\n      'Validate whether a grantee has permission to perform an action within a scope. ' +\n      'Checks expiry, revocation, and granter authority.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        granteeId: { type: 'string', description: 'Identity attempting the action.' },\n        action: { type: 'string', description: 'Action being attempted.' },\n        scope: { type: 'string', description: 'Scope being accessed.' },\n      },\n      required: ['granteeId', 'action', 'scope'],\n    },\n  },\n  {\n    name: 'twin_earth_list_permissions',\n    description: 'List permission grants with optional filtering by grantee, granter, or action.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        granteeId: { type: 'string', description: 'Filter by grantee' },\n        granterId: { type: 'string', description: 'Filter by granter' },\n        action: { type: 'string', description: 'Filter by action' },\n        limit: { type: 'number', description: 'Max results. Default: 50' },\n        offset: { type: 'number', description: 'Pagination offset. Default: 0' },\n      },\n    },\n  },\n\n  // Actuation & Invocation (gated by safety envelope + permissions)\n  {\n    name: 'twin_earth_robot_actuate',\n    description:\n      'Execute a robot actuation command (move, sense, grip, release, halt, report). ' +\n      'Gated by active safety envelope and permission grants. Returns a substrate receipt.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        agentId: { type: 'string', description: 'Robot identity.' },\n        command: {\n          type: 'string',\n          enum: ['move', 'sense', 'grip', 'release', 'halt', 'report'],\n          description: 'Actuation command.',\n        },\n        parameters: {\n          type: 'object',\n          description: 'Command-specific parameters (coordinates, force, duration). Optional.',\n        },\n        contextId: { type: 'string', description: 'Execution context identifier. Optional.' },\n      },\n      required: ['agentId', 'command'],\n    },\n  },\n  {\n    // OVERCLAIMED (P4): twin_earth_ai_invoke gates identity/safety-envelope/permission\n    // checks, then returns simulated:true. No LLM inference call is made.\n    name: 'twin_earth_ai_invoke',\n    description:\n      'Invoke an AI participant on the substrate — dialogue, inference, or task execution. OVERCLAIMED: no real LLM call - dispatches to stub, returns simulated:true. ' +\n      'Gated by active safety envelope and permission grants. Returns a substrate receipt.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        agentId: { type: 'string', description: 'AI identity.' },\n        prompt: { type: 'string', description: 'Input prompt or task description.' },\n        context: {\n          type: 'string',\n          description: 'Additional scene or execution context. Optional.',\n        },\n        maxTokens: { type: 'number', description: 'Max output tokens. Optional.' },\n        contextId: { type: 'string', description: 'Execution context identifier. Optional.' },\n      },\n      required: ['agentId', 'prompt'],\n    },\n  },\n  {\n    name: 'twin_earth_capture_receipt',\n    description:\n      'Capture a substrate execution receipt for a robot or AI action. ' +\n      'Hash is SHA-256 over deterministic receipt fields (not CAEL-signed ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€šÃ‚Â no CAEL anchor exists). Independent of Brittney.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        actorId: { type: 'string', description: 'Identity that performed the action.' },\n        action: { type: 'string', description: 'Action executed.' },\n        scope: { type: 'string', description: 'Scope of execution. Default: *.' },\n        status: {\n          type: 'string',\n          enum: ['success', 'failure', 'timeout', 'rejected_by_envelope'],\n          description: 'Execution status.',\n        },\n        envelopeId: { type: 'string', description: 'Active safety envelope during execution.' },\n        payloadHash: { type: 'string', description: 'Hash of large input payload. Optional.' },\n      },\n      required: ['actorId', 'action', 'status', 'envelopeId'],\n    },\n  },\n];\n\n// =============================================================================\n// DISPATCHER\n// =============================================================================\n\nexport async function handleRobotAiMcpTool(\n  name: string,\n  args: Record<string, unknown>\n): Promise<unknown> {\n  switch (name) {\n    case 'twin_earth_register_identity':\n      return handleTwinEarthRegisterIdentity(args);\n    case 'twin_earth_get_identity':\n      return handleTwinEarthGetIdentity(args);\n    case 'twin_earth_update_identity':\n      return handleTwinEarthUpdateIdentity(args);\n    case 'twin_earth_revoke_identity':\n      return handleTwinEarthRevokeIdentity(args);\n    case 'twin_earth_list_identities':\n      return handleTwinEarthListIdentities(args);\n    case 'twin_earth_create_safety_envelope':\n      return handleTwinEarthCreateSafetyEnvelope(args);\n    case 'twin_earth_get_safety_envelope':\n      return handleTwinEarthGetSafetyEnvelope(args);\n    case 'twin_earth_update_safety_envelope':\n      return handleTwinEarthUpdateSafetyEnvelope(args);\n    case 'twin_earth_delete_safety_envelope':\n      return handleTwinEarthDeleteSafetyEnvelope(args);\n    case 'twin_earth_list_safety_envelopes':\n      return handleTwinEarthListSafetyEnvelopes(args);\n    case 'twin_earth_grant_permission':\n      return handleTwinEarthGrantPermission(args);\n    case 'twin_earth_revoke_permission':\n      return handleTwinEarthRevokePermission(args);\n    case 'twin_earth_validate_permission':\n      return handleTwinEarthValidatePermission(args);\n    case 'twin_earth_list_permissions':\n      return handleTwinEarthListPermissions(args);\n    case 'twin_earth_robot_actuate':\n      return handleTwinEarthRobotActuate(args);\n    case 'twin_earth_ai_invoke':\n      return handleTwinEarthAIInvoke(args);\n    case 'twin_earth_capture_receipt':\n      return handleTwinEarthCaptureReceipt(args);\n    default:\n      return { error: `Unknown robot/AI tool: ${name}` };\n  }\n}\n\n// =============================================================================\n// HANDLERS\n// =============================================================================\n\nasync function handleTwinEarthRegisterIdentity(args: Record<string, unknown>): Promise<unknown> {\n  const agentId = (args.agentId as string) || genId('agent');\n  const walletAddress = args.walletAddress as string;\n  const handle = args.handle as string;\n  const attestation = args.attestation as string;\n  const kind = args.kind as 'robot' | 'ai';\n\n  if (!walletAddress || typeof walletAddress !== 'string') {\n    return { error: 'walletAddress is required.' };\n  }\n  if (!handle || typeof handle !== 'string') {\n    return { error: 'handle is required.' };\n  }\n  if (!attestation || typeof attestation !== 'string') {\n    return { error: 'attestation is required.' };\n  }\n  if (kind !== 'robot' && kind !== 'ai') {\n    return { error: 'kind must be \"robot\" or \"ai\".' };\n  }\n\n  const role = (args.role as string) || 'robot';\n  const mode = (args.mode as string) || 'local';\n  const attestedAt = (args.attestedAt as string) || new Date().toISOString();\n\n  const identity: StoredTwinEarthIdentity = {\n    agentId,\n    walletAddress,\n    handle,\n    attestation,\n    attestedAt,\n    role,\n    mode,\n    kind,\n    hardwareFingerprint: (args.hardwareFingerprint as string | undefined) ?? undefined,\n    brainCompositionId: (args.brainCompositionId as string | undefined) ?? undefined,\n    revoked: false,\n    createdAt: new Date().toISOString(),\n    modifiedAt: new Date().toISOString(),\n  };\n\n  twinEarthIdentityRegistry.set(agentId, identity);\n  persistRobotAiRegistries();\n\n  return {\n    success: true,\n    agentId,\n    handle,\n    role,\n    mode,\n    kind,\n    walletAddress,\n    attestedAt,\n  };\n}\n\nasync function handleTwinEarthGetIdentity(args: Record<string, unknown>): Promise<unknown> {\n  const agentId = args.agentId as string;\n  const identity = twinEarthIdentityRegistry.get(agentId);\n  if (!identity) {\n    return { error: `Identity not found: ${agentId}` };\n  }\n  return {\n    success: true,\n    agentId,\n    identity: {\n      agentId: identity.agentId,\n      walletAddress: identity.walletAddress,\n      handle: identity.handle,\n      role: identity.role,\n      mode: identity.mode,\n      kind: identity.kind,\n      attestedAt: identity.attestedAt,\n      hardwareFingerprint: identity.hardwareFingerprint,\n      brainCompositionId: identity.brainCompositionId,\n      revoked: identity.revoked,\n      createdAt: identity.createdAt,\n      modifiedAt: identity.modifiedAt,\n    },\n  };\n}\n\nasync function handleTwinEarthUpdateIdentity(args: Record<string, unknown>): Promise<unknown> {\n  const agentId = args.agentId as string;\n  const identity = twinEarthIdentityRegistry.get(agentId);\n  if (!identity) {\n    return { error: `Identity not found: ${agentId}` };\n  }\n  if (identity.revoked) {\n    return {\n      error: `Identity ${agentId} is revoked ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€šÃ‚Â cannot update.`,\n    };\n  }\n\n  if (args.handle) {\n    identity.handle = args.handle as string;\n    identity.attestation = (args.attestation as string) || identity.attestation;\n    identity.attestedAt = new Date().toISOString();\n  }\n  if (args.role) identity.role = args.role as string;\n  if (args.mode) identity.mode = args.mode as string;\n  if (args.brainCompositionId) identity.brainCompositionId = args.brainCompositionId as string;\n  identity.modifiedAt = new Date().toISOString();\n  persistRobotAiRegistries();\n\n  return { success: true, agentId, identity };\n}\n\nasync function handleTwinEarthRevokeIdentity(args: Record<string, unknown>): Promise<unknown> {\n  const agentId = args.agentId as string;\n  const granterId = args.granterId as string;\n  const revocationSignature = args.revocationSignature as string;\n\n  const identity = twinEarthIdentityRegistry.get(agentId);\n  if (!identity) {\n    return { error: `Identity not found: ${agentId}` };\n  }\n  if (identity.revoked) {\n    return { error: `Identity ${agentId} is already revoked.` };\n  }\n\n  const granter = twinEarthIdentityRegistry.get(granterId);\n  if (!granter || (granter.role !== 'founder' && granter.role !== 'steward')) {\n    return {\n      error: `Revocation requires founder or steward role. ${granterId} has role ${granter?.role ?? 'unknown'}.`,\n    };\n  }\n  if (!revocationSignature || typeof revocationSignature !== 'string') {\n    return { error: 'revocationSignature is required.' };\n  }\n\n  identity.revoked = true;\n  identity.revokedAt = new Date().toISOString();\n  identity.modifiedAt = new Date().toISOString();\n\n  // Invalidate all active safety envelopes for this identity\n  for (const envelope of safetyEnvelopeRegistry.values()) {\n    if (envelope.agentId === agentId) {\n      safetyEnvelopeRegistry.delete(envelope.id);\n    }\n  }\n  persistRobotAiRegistries();\n\n  return { success: true, agentId, revoked: true, revokedAt: identity.revokedAt };\n}\n\nasync function handleTwinEarthListIdentities(args: Record<string, unknown>): Promise<unknown> {\n  const limit = (args.limit as number) ?? 50;\n  const offset = (args.offset as number) ?? 0;\n  const role = args.role as string | undefined;\n  const kind = args.kind as 'robot' | 'ai' | undefined;\n  const mode = args.mode as string | undefined;\n\n  let items = Array.from(twinEarthIdentityRegistry.values()).map((i) => ({\n    agentId: i.agentId,\n    handle: i.handle,\n    role: i.role,\n    mode: i.mode,\n    kind: i.kind,\n    revoked: i.revoked,\n  }));\n\n  if (role) items = items.filter((i) => i.role === role);\n  if (kind) items = items.filter((i) => i.kind === kind);\n  if (mode) items = items.filter((i) => i.mode === mode);\n\n  const total = items.length;\n  items = items.slice(offset, offset + limit);\n\n  return { success: true, total, limit, offset, identities: items };\n}\n\nasync function handleTwinEarthCreateSafetyEnvelope(\n  args: Record<string, unknown>\n): Promise<unknown> {\n  const envelopeId = (args.envelopeId as string) || genId('env');\n  const agentId = args.agentId as string;\n\n  if (!agentId || typeof agentId !== 'string') {\n    return { error: 'agentId is required.' };\n  }\n\n  const identity = twinEarthIdentityRegistry.get(agentId);\n  if (!identity) {\n    return { error: `Identity not found: ${agentId}` };\n  }\n  if (identity.revoked) {\n    return {\n      error: `Identity ${agentId} is revoked ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€šÃ‚Â cannot create safety envelope.`,\n    };\n  }\n\n  const now = new Date().toISOString();\n  const allowedActions = (args.allowedActions as string[]) ?? [];\n  const humanApprovalRequired =\n    (args.humanApprovalRequired as boolean | undefined) ??\n    includesPhysicalWorldAction(allowedActions);\n\n  const envelope: StoredSafetyEnvelope = {\n    id: envelopeId,\n    agentId,\n    maxTickDurationMs: (args.maxTickDurationMs as number) ?? 1000,\n    maxMemoryBytes: (args.maxMemoryBytes as number) ?? 536870912,\n    maxNetworkCallsPerMinute: (args.maxNetworkCallsPerMinute as number) ?? 60,\n    allowedActions,\n    blockedActions: (args.blockedActions as string[]) ?? [],\n    deterministic: (args.deterministic as boolean) ?? false,\n    localOnly: (args.localOnly as boolean) ?? false,\n    substrateEnforced: true,\n    updatedAt: now,\n    freshnessTtlMs: (args.freshnessTtlMs as number | undefined) ?? undefined,\n    humanApprovalRequired,\n    humanApprovalGrantedAt: (args.humanApprovalGrantedAt as string | undefined) ?? undefined,\n    humanApprovalTtlMs: (args.humanApprovalTtlMs as number | undefined) ?? undefined,\n    createdAt: now,\n    modifiedAt: now,\n  };\n\n  safetyEnvelopeRegistry.set(envelopeId, envelope);\n  persistRobotAiRegistries();\n\n  return {\n    success: true,\n    envelopeId,\n    agentId,\n    substrateEnforced: true,\n    note: 'Safety envelope is substrate-enforced and cannot be overridden by the participant.',\n  };\n}\n\nasync function handleTwinEarthGetSafetyEnvelope(args: Record<string, unknown>): Promise<unknown> {\n  const envelopeId = args.envelopeId as string;\n  const envelope = safetyEnvelopeRegistry.get(envelopeId);\n  if (!envelope) {\n    return { error: `Safety envelope not found: ${envelopeId}` };\n  }\n  return { success: true, envelopeId, envelope };\n}\n\nasync function handleTwinEarthUpdateSafetyEnvelope(\n  args: Record<string, unknown>\n): Promise<unknown> {\n  const envelopeId = args.envelopeId as string;\n  const envelope = safetyEnvelopeRegistry.get(envelopeId);\n  if (!envelope) {\n    return { error: `Safety envelope not found: ${envelopeId}` };\n  }\n\n  if (args.maxTickDurationMs !== undefined)\n    envelope.maxTickDurationMs = args.maxTickDurationMs as number;\n  if (args.maxMemoryBytes !== undefined) envelope.maxMemoryBytes = args.maxMemoryBytes as number;\n  if (args.maxNetworkCallsPerMinute !== undefined)\n    envelope.maxNetworkCallsPerMinute = args.maxNetworkCallsPerMinute as number;\n  if (args.allowedActions !== undefined) {\n    envelope.allowedActions = args.allowedActions as string[];\n    if (\n      args.humanApprovalRequired === undefined &&\n      includesPhysicalWorldAction(envelope.allowedActions)\n    ) {\n      envelope.humanApprovalRequired = true;\n    }\n  }\n  if (args.blockedActions !== undefined) envelope.blockedActions = args.blockedActions as string[];\n  if (args.deterministic !== undefined) envelope.deterministic = args.deterministic as boolean;\n  if (args.localOnly !== undefined) envelope.localOnly = args.localOnly as boolean;\n  if (args.freshnessTtlMs !== undefined) envelope.freshnessTtlMs = args.freshnessTtlMs as number;\n  if (args.humanApprovalRequired !== undefined)\n    envelope.humanApprovalRequired = args.humanApprovalRequired as boolean;\n  if (args.humanApprovalGrantedAt !== undefined)\n    envelope.humanApprovalGrantedAt = args.humanApprovalGrantedAt as string;\n  if (args.humanApprovalTtlMs !== undefined)\n    envelope.humanApprovalTtlMs = args.humanApprovalTtlMs as number;\n  envelope.updatedAt = new Date().toISOString();\n  envelope.modifiedAt = envelope.updatedAt;\n  persistRobotAiRegistries();\n\n  return { success: true, envelopeId, envelope };\n}\n\nasync function handleTwinEarthDeleteSafetyEnvelope(\n  args: Record<string, unknown>\n): Promise<unknown> {\n  const envelopeId = args.envelopeId as string;\n  const granterId = args.granterId as string;\n\n  const granter = twinEarthIdentityRegistry.get(granterId);\n  if (!granter || (granter.role !== 'founder' && granter.role !== 'steward')) {\n    return {\n      error: `Deletion requires founder or steward role. ${granterId} has role ${granter?.role ?? 'unknown'}.`,\n    };\n  }\n\n  const envelope = safetyEnvelopeRegistry.get(envelopeId);\n  if (!envelope) {\n    return { error: `Safety envelope not found: ${envelopeId}` };\n  }\n\n  safetyEnvelopeRegistry.delete(envelopeId);\n  persistRobotAiRegistries();\n  return { success: true, envelopeId, deleted: true };\n}\n\nasync function handleTwinEarthListSafetyEnvelopes(args: Record<string, unknown>): Promise<unknown> {\n  const limit = (args.limit as number) ?? 50;\n  const offset = (args.offset as number) ?? 0;\n  const agentId = args.agentId as string | undefined;\n\n  let items = Array.from(safetyEnvelopeRegistry.values());\n  if (agentId) items = items.filter((e) => e.agentId === agentId);\n\n  const total = items.length;\n  items = items.slice(offset, offset + limit);\n\n  return { success: true, total, limit, offset, envelopes: items };\n}\n\nasync function handleTwinEarthGrantPermission(args: Record<string, unknown>): Promise<unknown> {\n  const granteeId = args.granteeId as string;\n  const granterId = args.granterId as string;\n  const action = args.action as string;\n  const scope = (args.scope as string) || '*';\n  const expiresAt = (args.expiresAt as string | null) || null;\n\n  if (!granteeId || !granterId || !action) {\n    return { error: 'granteeId, granterId, and action are required.' };\n  }\n\n  const grantee = twinEarthIdentityRegistry.get(granteeId);\n  const granter = twinEarthIdentityRegistry.get(granterId);\n  if (!grantee) {\n    return { error: `Grantee identity not found: ${granteeId}` };\n  }\n  if (!granter) {\n    return { error: `Granter identity not found: ${granterId}` };\n  }\n  if (grantee.revoked) {\n    return { error: `Grantee ${granteeId} is revoked.` };\n  }\n  if (granter.revoked) {\n    return { error: `Granter ${granterId} is revoked.` };\n  }\n\n  const hash = await simpleHash(`${granterId}:${granteeId}:${action}:${scope}:${Date.now()}`);\n  const grant: StoredPermissionGrant = {\n    granteeId,\n    granterId,\n    action,\n    scope,\n    expiresAt,\n    revocationSignature: null,\n    hash,\n    grantedAt: new Date().toISOString(),\n  };\n\n  permissionGrantRegistry.set(hash, grant);\n  persistRobotAiRegistries();\n\n  return { success: true, grantHash: hash, granteeId, granterId, action, scope, expiresAt };\n}\n\nasync function handleTwinEarthRevokePermission(args: Record<string, unknown>): Promise<unknown> {\n  const grantHash = args.grantHash as string;\n  const granterId = args.granterId as string;\n  const revocationSignature = args.revocationSignature as string;\n\n  const grant = permissionGrantRegistry.get(grantHash);\n  if (!grant) {\n    return { error: `Permission grant not found: ${grantHash}` };\n  }\n\n  const granter = twinEarthIdentityRegistry.get(granterId);\n  if (!granter || (granter.role !== 'founder' && granter.role !== 'steward')) {\n    return {\n      error: `Revocation requires founder or steward role. ${granterId} has role ${granter?.role ?? 'unknown'}.`,\n    };\n  }\n  if (grant.granterId !== granterId) {\n    return { error: `Only the original granter (${grant.granterId}) can revoke this grant.` };\n  }\n  if (!revocationSignature || typeof revocationSignature !== 'string') {\n    return { error: 'revocationSignature is required.' };\n  }\n\n  grant.revocationSignature = revocationSignature;\n  persistRobotAiRegistries();\n  return { success: true, grantHash, revoked: true };\n}\n\nasync function handleTwinEarthValidatePermission(args: Record<string, unknown>): Promise<unknown> {\n  const granteeId = args.granteeId as string;\n  const action = args.action as string;\n  const scope = args.scope as string;\n\n  const grant = Array.from(permissionGrantRegistry.values()).find(\n    (g) =>\n      g.granteeId === granteeId &&\n      !g.revocationSignature &&\n      (g.action === action || g.action === '*') &&\n      (g.scope === scope || g.scope === '*') &&\n      (!g.expiresAt || new Date(g.expiresAt) > new Date())\n  );\n\n  if (!grant) {\n    return { valid: false, reason: 'No matching grant found.' };\n  }\n\n  return {\n    valid: true,\n    grantHash: grant.hash,\n    granterId: grant.granterId,\n    action: grant.action,\n    scope: grant.scope,\n    expiresAt: grant.expiresAt,\n  };\n}\n\nasync function handleTwinEarthListPermissions(args: Record<string, unknown>): Promise<unknown> {\n  const limit = (args.limit as number) ?? 50;\n  const offset = (args.offset as number) ?? 0;\n  const granteeId = args.granteeId as string | undefined;\n  const granterId = args.granterId as string | undefined;\n  const action = args.action as string | undefined;\n\n  let items = Array.from(permissionGrantRegistry.values());\n  if (granteeId) items = items.filter((g) => g.granteeId === granteeId);\n  if (granterId) items = items.filter((g) => g.granterId === granterId);\n  if (action) items = items.filter((g) => g.action === action);\n\n  const total = items.length;\n  items = items.slice(offset, offset + limit);\n\n  return { success: true, total, limit, offset, grants: items };\n}\n\nasync function handleTwinEarthRobotActuate(\n  args: Record<string, unknown>,\n  dispatcher: RobotDispatcher = activeRobotDispatcher\n): Promise<unknown> {\n  const agentId = args.agentId as string;\n  const command = args.command as string;\n  const parameters = (args.parameters as Record<string, unknown>) ?? {};\n  const contextId = (args.contextId as string | undefined) ?? undefined;\n\n  const storedIdentity = twinEarthIdentityRegistry.get(agentId);\n  if (!storedIdentity) {\n    return { error: `Identity not found: ${agentId}` };\n  }\n  if (storedIdentity.revoked) {\n    return { error: `Identity ${agentId} is revoked.` };\n  }\n  if (storedIdentity.kind !== 'robot') {\n    return { error: `Identity ${agentId} is not a robot (kind=${storedIdentity.kind}).` };\n  }\n\n  // Find active safety envelope\n  const storedEnvelope = Array.from(safetyEnvelopeRegistry.values()).find(\n    (e) => e.agentId === agentId\n  );\n  if (!storedEnvelope) {\n    return { error: `No active safety envelope for ${agentId}. Robot actuation is blocked.` };\n  }\n\n  if (storedEnvelope.localOnly) {\n    return {\n      error: 'Robot actuation is blocked: localOnly safety envelope prohibits any actuation.',\n      rejectedByEnvelope: true,\n    };\n  }\n\n  // Find matching permission grant\n  const action = `robot:${command}`;\n  const scope = contextId || '*';\n  const storedGrant = Array.from(permissionGrantRegistry.values()).find(\n    (g) =>\n      g.granteeId === agentId &&\n      !g.revocationSignature &&\n      (g.action === action || g.action === '*') &&\n      (g.scope === scope || g.scope === '*') &&\n      (!g.expiresAt || new Date(g.expiresAt) > new Date())\n  );\n\n  const identity: TwinEarthIdentity = {\n    agentId: storedIdentity.agentId,\n    walletAddress: storedIdentity.walletAddress,\n    handle: storedIdentity.handle,\n    attestation: storedIdentity.attestation,\n    attestedAt: storedIdentity.attestedAt,\n    role: storedIdentity.role as TwinEarthIdentity['role'],\n    mode: storedIdentity.mode as TwinEarthIdentity['mode'],\n    kind: storedIdentity.kind,\n    hardwareFingerprint: storedIdentity.hardwareFingerprint,\n    brainCompositionId: storedIdentity.brainCompositionId,\n  };\n\n  const envelope: SafetyEnvelope = {\n    id: storedEnvelope.id,\n    agentId: storedEnvelope.agentId,\n    maxTickDurationMs: storedEnvelope.maxTickDurationMs,\n    maxMemoryBytes: storedEnvelope.maxMemoryBytes,\n    maxNetworkCallsPerMinute: storedEnvelope.maxNetworkCallsPerMinute,\n    allowedActions: storedEnvelope.allowedActions as SafetyEnvelope['allowedActions'],\n    blockedActions: storedEnvelope.blockedActions as SafetyEnvelope['blockedActions'],\n    deterministic: storedEnvelope.deterministic,\n    localOnly: storedEnvelope.localOnly,\n    updatedAt: storedEnvelope.updatedAt,\n    freshnessTtlMs: storedEnvelope.freshnessTtlMs,\n    humanApprovalRequired: storedEnvelope.humanApprovalRequired,\n    humanApprovalGrantedAt: storedEnvelope.humanApprovalGrantedAt,\n    humanApprovalTtlMs: storedEnvelope.humanApprovalTtlMs,\n    substrateEnforced: storedEnvelope.substrateEnforced, // THIN (ratchet P5): flag copied from in-memory registry but never enforced by a substrate Ã¢â‚¬â€ client self-reports the value\n  };\n\n  const grant: PermissionGrant = storedGrant\n    ? {\n        granteeId: storedGrant.granteeId,\n        granterId: storedGrant.granterId,\n        action: storedGrant.action as PermissionGrant['action'],\n        scope: storedGrant.scope,\n        expiresAt: storedGrant.expiresAt,\n        revocationSignature: storedGrant.revocationSignature,\n        hash: storedGrant.hash,\n      }\n    : ({} as unknown as PermissionGrant);\n\n  // Canonical safety-gated dispatch (RobotDispatcher production seam).\n  //\n  // gatedDispatch enforces the order BY CONSTRUCTION: evaluateActuation() runs\n  // first; only on an allowed verdict is the dispatcher called; only on a\n  // successful dispatch is a success receipt produced. A denied verdict yields\n  // NO dispatch and NO receipt. The default dispatcher is the honest stub\n  // (dispatchedTo:'stub', simulated:true); a real ROS2/MQTT backend injected via\n  // setRobotDispatcher flows through this same path with dispatchedTo:'ros2' etc.\n  const dispatchRequest: DispatchRequest = {\n    agentId,\n    command,\n    parameters,\n    envelopeId: storedEnvelope.id,\n  };\n\n  const gated = await gatedDispatch({\n    identity,\n    grant,\n    envelope,\n    action: action as PermissionGrant['action'],\n    scope,\n    request: dispatchRequest,\n    dispatcher,\n    genReceiptId: () => genId('act'),\n    hash: simpleHash,\n    hashAlgorithm: 'sha256',\n    substrateVersion: '1.0.0',\n  });\n\n  // Safety verdict denied — preserve the original denial response shape exactly.\n  if (gated.ok === false && gated.stage === 'safety') {\n    return {\n      error: gated.reason,\n      rejectedByEnvelope:\n        gated.blockingRule !== undefined &&\n        gated.blockingRule !== 'expired_grant' &&\n        gated.blockingRule !== 'revoked_grant',\n      permissionDenied:\n        gated.blockingRule === 'expired_grant' ||\n        gated.blockingRule === 'revoked_grant' ||\n        gated.reason.includes('Grant'),\n    };\n  }\n\n  // Allowed but the backend failed to dispatch — no success receipt was emitted.\n  if (gated.ok === false) {\n    return {\n      error: gated.reason,\n      dispatchedTo: gated.dispatch.dispatchedTo,\n      dispatchFailed: true,\n    };\n  }\n\n  // Allowed AND dispatched — persist the gate's success receipt to the registry.\n  const { receipt, dispatch } = gated;\n  const stored: StoredTwinEarthReceipt = {\n    id: receipt.id,\n    kind: 'action',\n    actorId: receipt.actorId,\n    action: receipt.action,\n    scope: receipt.scope,\n    timestamp: receipt.timestamp,\n    status: 'success',\n    hash: receipt.hash,\n    envelopeId: receipt.envelopeId,\n    ...(receipt.payloadHash ? { payloadHash: receipt.payloadHash } : {}),\n  };\n  twinEarthReceiptRegistry.set(receipt.id, stored);\n  persistRobotAiRegistries();\n\n  return {\n    success: true,\n    agentId,\n    command,\n    receiptId: receipt.id,\n    envelopeId: storedEnvelope.id,\n    status: 'success',\n    simulated: dispatch.simulated,\n    dispatchedTo: dispatch.dispatchedTo, // 'stub' by default; real backend reports its own\n    note:\n      dispatch.dispatchedTo === 'stub'\n        ? 'Actuation was simulated (canary). In production this dispatches to the robot runtime.'\n        : `Actuation dispatched to '${dispatch.dispatchedTo}' backend.`,\n  };\n}\n\nasync function handleTwinEarthAIInvoke(args: Record<string, unknown>): Promise<unknown> {\n  const agentId = args.agentId as string;\n  const prompt = args.prompt as string;\n  const context = (args.context as string | undefined) ?? '';\n  const maxTokens = (args.maxTokens as number | undefined) ?? 256;\n  const contextId = (args.contextId as string | undefined) ?? undefined;\n\n  const identity = twinEarthIdentityRegistry.get(agentId);\n  if (!identity) {\n    return { error: `Identity not found: ${agentId}` };\n  }\n  if (identity.revoked) {\n    return { error: `Identity ${agentId} is revoked.` };\n  }\n  if (identity.kind !== 'ai') {\n    return { error: `Identity ${agentId} is not an AI (kind=${identity.kind}).` };\n  }\n\n  // Find active safety envelope\n  const storedEnvelope = Array.from(safetyEnvelopeRegistry.values()).find(\n    (e) => e.agentId === agentId\n  );\n  if (!storedEnvelope) {\n    return { error: `No active safety envelope for ${agentId}. AI invocation is blocked.` };\n  }\n\n  if (storedEnvelope.localOnly) {\n    return {\n      error: 'AI invocation is blocked: localOnly safety envelope prohibits any invocation.',\n      rejectedByEnvelope: true,\n    };\n  }\n\n  // Check tick duration budget\n  if (storedEnvelope.maxTickDurationMs < 100) {\n    return {\n      error: `Safety envelope ${storedEnvelope.id} maxTickDurationMs (${storedEnvelope.maxTickDurationMs}ms) is too low for AI invocation.`,\n      rejectedByEnvelope: true,\n    };\n  }\n\n  // Check memory budget\n  if (storedEnvelope.maxMemoryBytes < 1048576) {\n    return {\n      error: `Safety envelope ${storedEnvelope.id} maxMemoryBytes (${storedEnvelope.maxMemoryBytes}) is below minimum for AI invocation.`,\n      rejectedByEnvelope: true,\n    };\n  }\n\n  // Check network calls (AI invoke typically needs outbound)\n  if (storedEnvelope.maxNetworkCallsPerMinute < 1) {\n    return {\n      error: `Safety envelope ${storedEnvelope.id} maxNetworkCallsPerMinute (${storedEnvelope.maxNetworkCallsPerMinute}) is below minimum for AI invocation.`,\n      rejectedByEnvelope: true,\n    };\n  }\n\n  // Find matching permission grant\n  const action = 'ai:invoke';\n  const scope = contextId || '*';\n  const storedGrant = Array.from(permissionGrantRegistry.values()).find(\n    (g) =>\n      g.granteeId === agentId &&\n      !g.revocationSignature &&\n      (g.action === action || g.action === 'ai:*' || g.action === '*') &&\n      (g.scope === scope || g.scope === '*') &&\n      (!g.expiresAt || new Date(g.expiresAt) > new Date())\n  );\n\n  if (!storedGrant) {\n    return {\n      error: `No permission grant for ai:invoke in scope ${scope}.`,\n      permissionDenied: true,\n    };\n  }\n\n  const receiptId = genId('inv');\n  const receipt: StoredTwinEarthReceipt = {\n    id: receiptId,\n    kind: 'action',\n    actorId: agentId,\n    action,\n    scope,\n    timestamp: new Date().toISOString(),\n    status: 'success',\n    hash: await simpleHash(`inv:${agentId}:${prompt}:${Date.now()}`),\n    envelopeId: storedEnvelope.id,\n    payloadHash: await simpleHash(JSON.stringify({ prompt, context, maxTokens })),\n  };\n\n  twinEarthReceiptRegistry.set(receiptId, receipt);\n  persistRobotAiRegistries();\n\n  return {\n    success: true,\n    agentId,\n    prompt,\n    receiptId,\n    envelopeId: storedEnvelope.id,\n    status: 'success',\n    simulated: true,\n    dispatchedTo: 'stub', // RATCHET: no real inference runtime bridge; simulated dispatch\n    note: 'AI invocation was simulated (canary). In production this dispatches to the inference runtime.',\n  };\n}\n\nasync function handleTwinEarthCaptureReceipt(args: Record<string, unknown>): Promise<unknown> {\n  const actorId = args.actorId as string;\n  const action = args.action as string;\n  const status = args.status as 'success' | 'failure' | 'timeout' | 'rejected_by_envelope';\n  const envelopeId = args.envelopeId as string;\n  const scope = (args.scope as string) || '*';\n  const payloadHash = (args.payloadHash as string | undefined) ?? undefined;\n\n  if (!actorId || !action || !status || !envelopeId) {\n    return { error: 'actorId, action, status, and envelopeId are required.' };\n  }\n\n  const identity = twinEarthIdentityRegistry.get(actorId);\n  if (!identity) {\n    return { error: `Identity not found: ${actorId}` };\n  }\n\n  const receiptId = genId('rec');\n  const receipt: StoredTwinEarthReceipt = {\n    id: receiptId,\n    kind: 'action',\n    actorId,\n    action,\n    scope,\n    timestamp: new Date().toISOString(),\n    status,\n    hash: await simpleHash(`rec:${actorId}:${action}:${receiptId}`), // deterministic: no Date.now()\n    envelopeId,\n    payloadHash,\n  };\n\n  twinEarthReceiptRegistry.set(receiptId, receipt);\n  persistRobotAiRegistries();\n\n  return {\n    success: true,\n    receiptId,\n    actorId,\n    action,\n    status,\n    envelopeId,\n    scope,\n    hash: receipt.hash,\n    timestamp: receipt.timestamp,\n  };\n}\n","import axios from 'axios';\nimport * as crypto from 'crypto';\nimport type { Tool } from '@modelcontextprotocol/sdk/types.js';\nimport { getToolRiskLevel, getToolScopes, type ToolRiskLevel } from '../security/tool-scopes';\nimport type { SigningContext } from '../holomesh/identity/signing-middleware';\n\nconst TOOL_MANIFEST_PROTOCOL = 'holomesh.tool_manifest.v1';\nconst TOOL_INVOCATION_PROTOCOL = 'holomesh.tool_invocation.v1';\n\nexport type MeshToolTransport = 'local' | 'mcp-http';\n\nexport interface MeshToolEndpoint {\n  transport: MeshToolTransport;\n  toolName: string;\n  url?: string;\n  headers?: Record<string, string>;\n}\n\nexport interface MeshToolAttestation {\n  protocol: typeof TOOL_MANIFEST_PROTOCOL;\n  manifestHash: string;\n  publishedAt: string;\n  publisherAgentId: string;\n  publisherName: string;\n}\n\nexport interface MeshToolManifest {\n  id: string;\n  name: string;\n  description: string;\n  capabilityTags: string[];\n  inputSchema?: Record<string, unknown>;\n  endpoint: MeshToolEndpoint;\n  allowTransitiveInvocation: boolean;\n  maxRisk: ToolRiskLevel;\n  scopes: string[];\n  attestation: MeshToolAttestation;\n  /** Federation metadata for substrate tool publishing (task_1778618552503_6xk8) */\n  serviceVersion?: string;\n  actorSessionHandoff?: boolean;\n  crossMcpReceiptEnvelope?: boolean;\n  rollbackMetadata?: boolean;\n  sourceArtifactHash?: string;\n}\n\nexport interface MeshToolPublisher {\n  agentId: string;\n  name: string;\n}\n\nexport interface MeshToolInvokeOptions {\n  dryRun?: boolean;\n  allowHighRisk?: boolean;\n  localInvoker?: (toolName: string, args: Record<string, unknown>) => Promise<unknown>;\n  signingCtx?: SigningContext;\n}\n\nexport interface MeshToolInvocationHop {\n  protocol: typeof TOOL_INVOCATION_PROTOCOL;\n  invocationId: string;\n  manifestId: string;\n  toolName: string;\n  manifestHash: string;\n  callerAgentId: string;\n  argsHash: string;\n  previousHash: string | null;\n  invokedAt: string;\n  hopHash: string;\n}\n\nexport interface MeshToolInvocationChainVerification {\n  verified: boolean;\n  errors: string[];\n  lastHash: string | null;\n}\n\nconst registry = new Map<string, MeshToolManifest>();\n\nfunction stableJson(value: unknown): string {\n  if (Array.isArray(value)) {\n    return `[${value.map((item) => stableJson(item)).join(',')}]`;\n  }\n  if (value && typeof value === 'object') {\n    const obj = value as Record<string, unknown>;\n    return `{${Object.keys(obj)\n      .sort()\n      .filter((key) => obj[key] !== undefined)\n      .map((key) => `${JSON.stringify(key)}:${stableJson(obj[key])}`)\n      .join(',')}}`;\n  }\n  return JSON.stringify(value);\n}\n\nfunction hashManifestBody(body: Record<string, unknown>): string {\n  return crypto.createHash('sha256').update(stableJson(body)).digest('hex');\n}\n\nfunction normalizeTag(raw: string): string {\n  return raw\n    .trim()\n    .replace(/^@+/, '')\n    .replace(/[^a-zA-Z0-9_.:-]+/g, '-')\n    .replace(/^-+|-+$/g, '')\n    .toLowerCase();\n}\n\nfunction collectCapabilityTags(value: unknown): string[] {\n  if (!value) return [];\n  if (typeof value === 'string') {\n    return value\n      .split(/[,\\s]+/)\n      .map(normalizeTag)\n      .filter(Boolean);\n  }\n  if (Array.isArray(value)) {\n    return value.flatMap((item) => collectCapabilityTags(item));\n  }\n  if (typeof value === 'object') {\n    const obj = value as Record<string, unknown>;\n    const tags: string[] = [];\n    for (const [key, raw] of Object.entries(obj)) {\n      if (raw === true) tags.push(normalizeTag(key));\n      else if (typeof raw === 'string' || typeof raw === 'number') {\n        tags.push(normalizeTag(String(raw)));\n      } else if (Array.isArray(raw)) {\n        tags.push(...collectCapabilityTags(raw));\n      }\n    }\n    return tags;\n  }\n  return [];\n}\n\nfunction uniqueTags(tags: string[]): string[] {\n  return Array.from(new Set(tags.map(normalizeTag).filter(Boolean))).sort();\n}\n\nfunction deriveToolId(name: string, endpoint: MeshToolEndpoint, capabilityTags: string[]): string {\n  const hash = hashManifestBody({\n    name,\n    endpoint,\n    capabilityTags,\n  }).slice(0, 12);\n  return `mesh_tool_${normalizeTag(name)}_${hash}`;\n}\n\nfunction parseEndpoint(value: unknown, fallbackToolName: string): MeshToolEndpoint {\n  if (typeof value === 'string') {\n    if (/^https?:\\/\\//i.test(value)) {\n      return { transport: 'mcp-http', toolName: fallbackToolName, url: value };\n    }\n    return { transport: 'local', toolName: fallbackToolName };\n  }\n\n  const endpoint = value && typeof value === 'object' ? (value as Record<string, unknown>) : {};\n  const transportRaw = typeof endpoint.transport === 'string' ? endpoint.transport : 'local';\n  const transport: MeshToolTransport = transportRaw === 'mcp-http' ? 'mcp-http' : 'local';\n  const toolName =\n    typeof endpoint.toolName === 'string'\n      ? endpoint.toolName\n      : typeof endpoint.tool_name === 'string'\n        ? endpoint.tool_name\n        : fallbackToolName;\n  const url = typeof endpoint.url === 'string' ? endpoint.url : undefined;\n  const headers =\n    endpoint.headers && typeof endpoint.headers === 'object'\n      ? Object.fromEntries(\n          Object.entries(endpoint.headers as Record<string, unknown>).filter(\n            (entry): entry is [string, string] => typeof entry[1] === 'string'\n          )\n        )\n      : undefined;\n\n  return {\n    transport,\n    toolName,\n    ...(url ? { url } : {}),\n    ...(headers ? { headers } : {}),\n  };\n}\n\nfunction manifestBody(manifest: Omit<MeshToolManifest, 'attestation'>): Record<string, unknown> {\n  return {\n    id: manifest.id,\n    name: manifest.name,\n    description: manifest.description,\n    capabilityTags: manifest.capabilityTags,\n    inputSchema: manifest.inputSchema,\n    endpoint: manifest.endpoint,\n    allowTransitiveInvocation: manifest.allowTransitiveInvocation,\n    maxRisk: manifest.maxRisk,\n    scopes: manifest.scopes,\n    serviceVersion: manifest.serviceVersion,\n    actorSessionHandoff: manifest.actorSessionHandoff,\n    crossMcpReceiptEnvelope: manifest.crossMcpReceiptEnvelope,\n    rollbackMetadata: manifest.rollbackMetadata,\n    sourceArtifactHash: manifest.sourceArtifactHash,\n  };\n}\n\nexport function buildMeshToolManifest(\n  args: Record<string, unknown>,\n  publisher: MeshToolPublisher,\n  now = new Date()\n): MeshToolManifest {\n  const name =\n    typeof args.name === 'string'\n      ? args.name.trim()\n      : typeof args.tool_name === 'string'\n        ? args.tool_name.trim()\n        : '';\n  if (!name) throw new Error('name is required');\n\n  const description =\n    typeof args.description === 'string' && args.description.trim()\n      ? args.description.trim()\n      : `Mesh-published MCP tool ${name}`;\n  const endpoint = parseEndpoint(args.endpoint, name);\n  const capabilityTags = uniqueTags([\n    ...collectCapabilityTags(args.capability_tags),\n    ...collectCapabilityTags(args.capabilityTags),\n    ...collectCapabilityTags(args.capabilities),\n    ...collectCapabilityTags(args.tags),\n    name,\n  ]);\n  if (capabilityTags.length === 0) {\n    throw new Error('At least one capability tag is required');\n  }\n\n  const id =\n    typeof args.id === 'string' && args.id.trim()\n      ? normalizeTag(args.id)\n      : deriveToolId(name, endpoint, capabilityTags);\n  const targetRisk = getToolRiskLevel(endpoint.toolName);\n  const maxRisk = typeof args.max_risk === 'string' ? (args.max_risk as ToolRiskLevel) : targetRisk;\n  const inputSchema =\n    args.input_schema && typeof args.input_schema === 'object'\n      ? (args.input_schema as Record<string, unknown>)\n      : args.inputSchema && typeof args.inputSchema === 'object'\n        ? (args.inputSchema as Record<string, unknown>)\n        : undefined;\n  const allowTransitiveInvocation = args.allow_transitive_invocation === true;\n  const serviceVersion = readOptionalString(args.service_version ?? args.serviceVersion);\n  const actorSessionHandoff =\n    args.actor_session_handoff === true || args.actorSessionHandoff === true;\n  const crossMcpReceiptEnvelope =\n    args.cross_mcp_receipt_envelope === true || args.crossMcpReceiptEnvelope === true;\n  const rollbackMetadata = args.rollback_metadata === true || args.rollbackMetadata === true;\n  const sourceArtifactHash = readOptionalString(\n    args.source_artifact_hash ?? args.sourceArtifactHash\n  );\n  const withoutAttestation: Omit<MeshToolManifest, 'attestation'> = {\n    id,\n    name,\n    description,\n    capabilityTags,\n    ...(inputSchema ? { inputSchema } : {}),\n    endpoint,\n    allowTransitiveInvocation,\n    maxRisk,\n    scopes: getToolScopes(endpoint.toolName),\n    serviceVersion,\n    actorSessionHandoff,\n    crossMcpReceiptEnvelope,\n    rollbackMetadata,\n    sourceArtifactHash,\n  };\n\n  return {\n    ...withoutAttestation,\n    attestation: {\n      protocol: TOOL_MANIFEST_PROTOCOL,\n      manifestHash: hashManifestBody(manifestBody(withoutAttestation)),\n      publishedAt: now.toISOString(),\n      publisherAgentId: publisher.agentId,\n      publisherName: publisher.name,\n    },\n  };\n}\n\nexport function verifyMeshToolAttestation(manifest: MeshToolManifest): boolean {\n  const { attestation, ...withoutAttestation } = manifest;\n  return (\n    attestation.protocol === TOOL_MANIFEST_PROTOCOL &&\n    attestation.manifestHash === hashManifestBody(manifestBody(withoutAttestation))\n  );\n}\n\nexport function publishMeshToolManifest(manifest: MeshToolManifest): MeshToolManifest {\n  if (!verifyMeshToolAttestation(manifest)) {\n    throw new Error('Mesh tool manifest attestation failed verification');\n  }\n  registry.set(manifest.id, manifest);\n  return manifest;\n}\n\nfunction queryTerms(query: unknown): string[] {\n  return uniqueTags(collectCapabilityTags(query));\n}\n\nexport function scoreMeshToolManifest(query: unknown, manifest: MeshToolManifest): number {\n  const terms = queryTerms(query);\n  if (terms.length === 0) return 1;\n  const haystack = uniqueTags([\n    manifest.name,\n    manifest.description,\n    ...manifest.capabilityTags,\n    manifest.endpoint.toolName,\n  ]);\n  return terms.reduce((score, term) => {\n    if (manifest.capabilityTags.includes(term)) return score + 5;\n    if (haystack.includes(term)) return score + 3;\n    if (haystack.some((tag) => tag.includes(term) || term.includes(tag))) return score + 1;\n    return score;\n  }, 0);\n}\n\nexport function discoverMeshTools(query: unknown, limit = 20): MeshToolManifest[] {\n  return Array.from(registry.values())\n    .map((manifest) => ({ manifest, score: scoreMeshToolManifest(query, manifest) }))\n    .filter(({ score }) => score > 0)\n    .sort((a, b) => b.score - a.score || a.manifest.name.localeCompare(b.manifest.name))\n    .slice(0, limit)\n    .map(({ manifest }) => manifest);\n}\n\nexport function clearMeshToolRegistry(): void {\n  registry.clear();\n}\n\nexport function verifyMeshToolInvocationChain(\n  chain: MeshToolInvocationHop[]\n): MeshToolInvocationChainVerification {\n  const errors: string[] = [];\n  let previousHash: string | null = null;\n\n  chain.forEach((hop, index) => {\n    if (hop.protocol !== TOOL_INVOCATION_PROTOCOL) {\n      errors.push(`hop ${index} protocol mismatch`);\n    }\n    if (hop.previousHash !== previousHash) {\n      errors.push(`hop ${index} previousHash does not link to prior hop`);\n    }\n\n    const { hopHash, ...payload } = hop;\n    void hopHash;\n    const expectedHash = hashInvocationBody(payload);\n    if (hop.hopHash !== expectedHash) {\n      errors.push(`hop ${index} hash mismatch`);\n    }\n    previousHash = hop.hopHash;\n  });\n\n  return { verified: errors.length === 0, errors, lastHash: previousHash };\n}\n\nexport function createMeshToolInvocationHop(\n  manifest: MeshToolManifest,\n  args: Record<string, unknown>,\n  options: {\n    callerAgentId?: string;\n    invocationId?: string;\n    invokedAt?: string;\n    previousHash?: string | null;\n  } = {}\n): MeshToolInvocationHop {\n  return buildInvocationHop({\n    argsHash: hashManifestBody(args),\n    callerAgentId: options.callerAgentId ?? process.env.HOLOMESH_AGENT_NAME ?? 'local-agent',\n    invocationId: options.invocationId ?? crypto.randomUUID(),\n    invokedAt: options.invokedAt ?? new Date().toISOString(),\n    manifest,\n    previousHash: options.previousHash ?? null,\n  });\n}\n\nexport function meshToolManifestToKnowledgeContent(manifest: MeshToolManifest): string {\n  return `${TOOL_MANIFEST_PROTOCOL}\\n${stableJson(manifest)}`;\n}\n\nexport function meshToolManifestFromKnowledgeContent(content: string): MeshToolManifest | null {\n  if (!content.startsWith(`${TOOL_MANIFEST_PROTOCOL}\\n`)) return null;\n  try {\n    const parsed = JSON.parse(content.slice(TOOL_MANIFEST_PROTOCOL.length + 1)) as MeshToolManifest;\n    return verifyMeshToolAttestation(parsed) ? parsed : null;\n  } catch {\n    return null;\n  }\n}\n\nasync function defaultLocalInvoker(\n  toolName: string,\n  args: Record<string, unknown>,\n  signingCtx?: SigningContext\n): Promise<unknown> {\n  if (toolName === 'holomesh_invoke_tool') {\n    throw new Error('holomesh_invoke_tool cannot recursively invoke itself');\n  }\n  const { handleTool } = await import('../handlers');\n  return handleTool(toolName, args, signingCtx);\n}\n\nexport async function invokePublishedMeshTool(\n  manifest: MeshToolManifest,\n  args: Record<string, unknown>,\n  options: MeshToolInvokeOptions = {}\n): Promise<unknown> {\n  if (!verifyMeshToolAttestation(manifest)) {\n    return {\n      success: false,\n      error: 'Manifest attestation failed verification',\n      manifestId: manifest.id,\n    };\n  }\n  if (!manifest.allowTransitiveInvocation) {\n    return {\n      success: false,\n      error: 'Manifest does not allow transitive invocation',\n      manifestId: manifest.id,\n    };\n  }\n  const risk = getToolRiskLevel(manifest.endpoint.toolName);\n  if (!options.allowHighRisk && (risk === 'high' || risk === 'critical')) {\n    return {\n      success: false,\n      error: `Refusing ${risk} risk transitive invocation without allow_high_risk=true`,\n      manifestId: manifest.id,\n      risk,\n    };\n  }\n\n  const route = {\n    manifestId: manifest.id,\n    toolName: manifest.endpoint.toolName,\n    transport: manifest.endpoint.transport,\n    risk,\n    manifestHash: manifest.attestation.manifestHash,\n  };\n  if (options.dryRun) {\n    return { success: true, dryRun: true, route };\n  }\n\n  if (manifest.endpoint.transport === 'local') {\n    const invoker = options.localInvoker ?? defaultLocalInvoker;\n    const result = await invoker(manifest.endpoint.toolName, args, options.signingCtx);\n    return { success: true, route, result };\n  }\n\n  if (!manifest.endpoint.url) {\n    return {\n      success: false,\n      error: 'mcp-http endpoint requires url',\n      route,\n    };\n  }\n\n  const response = await axios.post(\n    manifest.endpoint.url,\n    { name: manifest.endpoint.toolName, arguments: args },\n    {\n      headers: {\n        'content-type': 'application/json; charset=utf-8',\n        'x-holomesh-tool-manifest-hash': manifest.attestation.manifestHash,\n        ...(manifest.endpoint.headers ?? {}),\n      },\n      timeout: 30000,\n    }\n  );\n  return { success: true, route, result: response.data };\n}\n\nexport async function handleMeshToolRegistryTool(\n  name: string,\n  args: Record<string, unknown>,\n  allTools: Tool[],\n  dispatch: (name: string, args: Record<string, unknown>) => Promise<unknown>\n): Promise<unknown | null> {\n  if (name === 'holomesh_publish_tool') {\n    const manifest = buildMeshToolManifest(buildPublishArgs(args, allTools), readPublisher(args));\n    const published = publishMeshToolManifest(manifest);\n    return {\n      success: true,\n      tool: published,\n      attestation: published.attestation,\n    };\n  }\n\n  if (name === 'holomesh_invoke_tool') {\n    const manifest = resolvePublishedTool(args);\n    const incomingChain = readInvocationChain(args.provenance_chain ?? args.provenanceChain);\n    const verification = verifyMeshToolInvocationChain(incomingChain);\n    if (!verification.verified) {\n      throw new Error(`Invalid provenance chain: ${verification.errors.join('; ')}`);\n    }\n\n    const toolArgs = readRecord(args.args) ?? {};\n    const invocation = await invokePublishedMeshTool(manifest, toolArgs, {\n      allowHighRisk: args.allow_high_risk === true || args.allowHighRisk === true,\n      dryRun: args.dry_run === true || args.dryRun === true,\n      localInvoker: dispatch,\n    });\n    const hop = createMeshToolInvocationHop(manifest, toolArgs, {\n      callerAgentId:\n        readOptionalString(args.caller_agent_id ?? args.callerAgentId) ??\n        process.env.HOLOMESH_AGENT_NAME ??\n        'local-agent',\n      invocationId:\n        readOptionalString(args.invocation_id ?? args.invocationId) ?? crypto.randomUUID(),\n      invokedAt:\n        readOptionalString(args.invoked_at ?? args.invokedAt ?? args.timestamp) ??\n        new Date().toISOString(),\n      previousHash: verification.lastHash,\n    });\n    const provenanceChain = [...incomingChain, hop];\n\n    return {\n      success: readRecord(invocation)?.success !== false,\n      routedTo: {\n        manifestId: manifest.id,\n        toolName: manifest.endpoint.toolName,\n        manifestHash: manifest.attestation.manifestHash,\n        capabilityTags: manifest.capabilityTags,\n      },\n      invocation,\n      attestation: {\n        verified: true,\n        chainLength: provenanceChain.length,\n        argsHash: hop.argsHash,\n        provenanceChain,\n      },\n    };\n  }\n\n  return null;\n}\n\nexport const MESH_TOOL_MANIFEST_PROTOCOL = TOOL_MANIFEST_PROTOCOL;\nexport const MESH_TOOL_INVOCATION_PROTOCOL = TOOL_INVOCATION_PROTOCOL;\n\nfunction buildPublishArgs(\n  args: Record<string, unknown>,\n  allTools: Tool[]\n): Record<string, unknown> {\n  const name = readOptionalString(args.name ?? args.tool_name ?? args.toolName);\n  if (!name) throw new Error('tool_name is required');\n  if (name === 'holomesh_publish_tool' || name === 'holomesh_invoke_tool') {\n    throw new Error(`Refusing to publish reserved mesh tool '${name}'`);\n  }\n  const tool = allTools.find((candidate) => candidate.name === name);\n  if (!tool) throw new Error(`Unknown MCP tool '${name}'`);\n\n  return {\n    ...args,\n    name,\n    description:\n      readOptionalString(args.description) ?? tool.description ?? `Mesh-published MCP tool ${name}`,\n    input_schema: readRecord(args.input_schema ?? args.inputSchema) ?? tool.inputSchema,\n    endpoint: args.endpoint ?? { transport: 'local', toolName: name },\n    allow_transitive_invocation: args.allow_transitive_invocation !== false,\n    capability_tags: [\n      ...collectCapabilityTags(args.capability_tags),\n      ...collectCapabilityTags(args.capabilityTags),\n      ...collectCapabilityTags(args.capabilities),\n      ...collectCapabilityTags(args.tags),\n      'mesh-tool',\n      name,\n    ],\n  };\n}\n\nfunction readPublisher(args: Record<string, unknown>): MeshToolPublisher {\n  return {\n    agentId:\n      readOptionalString(args.publisher_agent_id ?? args.publisherAgentId) ??\n      process.env.HOLOMESH_AGENT_ID ??\n      process.env.HOLOMESH_AGENT_NAME ??\n      'local-agent',\n    name:\n      readOptionalString(args.publisher_name ?? args.publisherName) ??\n      process.env.HOLOMESH_AGENT_NAME ??\n      'local-agent',\n  };\n}\n\nfunction resolvePublishedTool(args: Record<string, unknown>): MeshToolManifest {\n  const manifestId = readOptionalString(args.mesh_tool_id ?? args.meshToolId ?? args.manifest_id);\n  if (manifestId) {\n    const manifest = registry.get(manifestId);\n    if (!manifest) throw new Error(`No mesh-published tool '${manifestId}'`);\n    return manifest;\n  }\n\n  const toolName = readOptionalString(args.tool_name ?? args.toolName);\n  if (toolName) {\n    const manifest = Array.from(registry.values()).find((entry) => entry.name === toolName);\n    if (!manifest) throw new Error(`No mesh-published tool named '${toolName}'`);\n    return manifest;\n  }\n\n  const query =\n    args.capability_query ?? args.capabilityQuery ?? args.capability_tags ?? args.capabilityTags;\n  if (!query) throw new Error('capability_query, mesh_tool_id, or tool_name is required');\n  const [manifest] = discoverMeshTools(query, 1);\n  if (!manifest) throw new Error('No mesh-published tool matched capability_query');\n  return manifest;\n}\n\nfunction buildInvocationHop(input: {\n  argsHash: string;\n  callerAgentId: string;\n  invocationId: string;\n  invokedAt: string;\n  manifest: MeshToolManifest;\n  previousHash: string | null;\n}): MeshToolInvocationHop {\n  const payload: Omit<MeshToolInvocationHop, 'hopHash'> = {\n    protocol: TOOL_INVOCATION_PROTOCOL,\n    invocationId: input.invocationId,\n    manifestId: input.manifest.id,\n    toolName: input.manifest.endpoint.toolName,\n    manifestHash: input.manifest.attestation.manifestHash,\n    callerAgentId: input.callerAgentId,\n    argsHash: input.argsHash,\n    previousHash: input.previousHash,\n    invokedAt: input.invokedAt,\n  };\n  return {\n    ...payload,\n    hopHash: hashInvocationBody(payload),\n  };\n}\n\nfunction hashInvocationBody(body: Omit<MeshToolInvocationHop, 'hopHash'>): string {\n  return crypto.createHash('sha256').update(stableJson(body)).digest('hex');\n}\n\nfunction readInvocationChain(value: unknown): MeshToolInvocationHop[] {\n  if (!Array.isArray(value)) return [];\n  return value.filter((item): item is MeshToolInvocationHop => Boolean(readRecord(item)));\n}\n\nfunction readOptionalString(value: unknown): string | undefined {\n  return typeof value === 'string' && value.trim() ? value.trim() : undefined;\n}\n\nfunction readRecord(value: unknown): Record<string, unknown> | undefined {\n  if (!value || typeof value !== 'object' || Array.isArray(value)) return undefined;\n  return value as Record<string, unknown>;\n}\n","import * as crypto from 'crypto';\nimport type { ExportSession, SerializedExportSession } from './types';\n\nconst DEFAULT_EXPORT_SESSION_TTL_MS = 15 * 60 * 1000;\n\nexport interface ExportSessionConfig {\n  ttlMs?: number;\n  now?: () => number;\n}\n\nexport type IdempotencyRegistrationResult =\n  | 'accepted'\n  | 'replay'\n  | 'expired'\n  | 'consumed'\n  | 'missing';\n\nfunction normalizeTtlMs(ttlMs?: number): number {\n  if (!Number.isFinite(ttlMs) || (ttlMs as number) <= 0) return DEFAULT_EXPORT_SESSION_TTL_MS;\n  return Math.floor(ttlMs as number);\n}\n\nfunction getNow(config?: ExportSessionConfig): number {\n  return config?.now ? config.now() : Date.now();\n}\n\nexport function createExportSession(\n  userId: string,\n  config: ExportSessionConfig = {}\n): ExportSession {\n  const now = getNow(config);\n  const ttlMs = normalizeTtlMs(config.ttlMs);\n\n  return {\n    sessionId: crypto.randomUUID(),\n    userId,\n    createdAt: now,\n    expiresAt: now + ttlMs,\n    status: 'prepared',\n    serverNonce: crypto.randomBytes(32).toString('hex'),\n    idempotencyKeys: new Set<string>(),\n  };\n}\n\nexport function isExportSessionExpired(session: ExportSession, now = Date.now()): boolean {\n  return now > session.expiresAt;\n}\n\nexport function markExportSessionPackaged(\n  session: ExportSession,\n  manifestHash?: string\n): ExportSession {\n  if (session.status !== 'expired' && session.status !== 'finalized') {\n    session.status = 'packaged';\n  }\n  if (manifestHash && manifestHash.trim()) {\n    session.packageManifestHash = manifestHash.trim();\n  }\n  return session;\n}\n\nexport function markExportSessionFinalized(\n  session: ExportSession,\n  now = Date.now()\n): ExportSession {\n  session.status = 'finalized';\n  session.consumedAt = now;\n  return session;\n}\n\nexport function registerIdempotencyKey(\n  session: ExportSession,\n  idempotencyKey: string | undefined,\n  now = Date.now()\n): IdempotencyRegistrationResult {\n  const normalized = (idempotencyKey || '').trim();\n  if (!normalized) return 'missing';\n\n  if (session.status === 'finalized') return 'consumed';\n\n  if (isExportSessionExpired(session, now)) {\n    session.status = 'expired';\n    return 'expired';\n  }\n\n  if (session.idempotencyKeys.has(normalized)) return 'replay';\n\n  session.idempotencyKeys.add(normalized);\n  return 'accepted';\n}\n\nexport function pruneExpiredExportSessions(\n  store: Map<string, ExportSession>,\n  now = Date.now()\n): number {\n  let pruned = 0;\n  for (const [sessionId, session] of store.entries()) {\n    if (isExportSessionExpired(session, now)) {\n      session.status = 'expired';\n      store.delete(sessionId);\n      pruned++;\n    }\n  }\n  return pruned;\n}\n\nexport function serializeExportSession(session: ExportSession): SerializedExportSession {\n  return {\n    ...session,\n    idempotencyKeys: Array.from(session.idempotencyKeys.values()),\n  };\n}\n\nexport function deserializeExportSession(raw: unknown): ExportSession | null {\n  if (!raw || typeof raw !== 'object') return null;\n  const candidate = raw as Partial<SerializedExportSession>;\n\n  if (!candidate.sessionId || !candidate.userId || !candidate.serverNonce) return null;\n  if (!Number.isFinite(candidate.createdAt) || !Number.isFinite(candidate.expiresAt)) return null;\n  if (\n    !candidate.status ||\n    !['prepared', 'packaged', 'finalized', 'expired'].includes(candidate.status)\n  ) {\n    return null;\n  }\n\n  const idempotencyKeys = Array.isArray(candidate.idempotencyKeys)\n    ? candidate.idempotencyKeys.filter(\n        (k): k is string => typeof k === 'string' && k.trim().length > 0\n      )\n    : [];\n\n  return {\n    sessionId: candidate.sessionId,\n    userId: candidate.userId,\n    createdAt: Number(candidate.createdAt),\n    expiresAt: Number(candidate.expiresAt),\n    status: candidate.status,\n    serverNonce: candidate.serverNonce,\n    idempotencyKeys: new Set(idempotencyKeys),\n    consumedAt: Number.isFinite(candidate.consumedAt) ? candidate.consumedAt : undefined,\n    packageManifestHash:\n      typeof candidate.packageManifestHash === 'string' ? candidate.packageManifestHash : undefined,\n  };\n}\n","/**\n * Tier 2 Token-Balance Ledger — Phase 5 (task_1776806224288_m5jg).\n *\n * Wallet-as-ledger for paid compute tokens. Stripe webhook confirms payment →\n * backend credits user's wallet balance with N tokens. User invokes HoloScript\n * operation → server signs with user's custodial wallet → operation decrements\n * balance. Balance=0 → operations refused until topped up.\n *\n * Token balance is server-side accounting, not on-chain. On-chain anchoring\n * (S.ANC-style) happens on major operations only — not every token spend.\n *\n * Spec: research/2026-04-21_seat-wallets-adr.md §\"Token seeding\", §\"User-facing\n * flow\" steps 3-4.\n *\n * @module holomesh/identity/token-ledger\n */\n\nimport * as crypto from 'crypto';\n\n// ── Types ───────────────────────────────────────────────────────────────────\n\n/** A single ledger entry — immutable after creation. */\nexport interface TokenLedgerEntry {\n  /** Unique ID: `tle_<sha256(userId|type|timestamp|nonce)[:12]` */\n  id: string;\n  /** User ID (HoloMesh agentId or future OAuth subject). */\n  userId: string;\n  /** Credit (tokens added) or debit (tokens consumed). */\n  type: 'credit' | 'debit';\n  /** Number of tokens. Always positive; sign is in `type`. */\n  amount: number;\n  /** Running balance after this entry was applied. */\n  balanceAfter: number;\n  /** ISO 8601 timestamp. */\n  timestamp: string;\n  /** Source that triggered this entry. */\n  source: TokenSource;\n  /** Human-readable reference for audit trail. */\n  reference: string;\n  /** Optional metadata (Stripe charge ID, operation name, etc.). */\n  metadata?: Record<string, unknown>;\n}\n\n/** Sources that can create a ledger entry. */\nexport type TokenSource =\n  | 'stripe_payment' // Stripe webhook → credit\n  | 'admin_grant' // Founder/admin manual grant → credit\n  | 'admin_revoke' // Founder/admin manual revoke → debit\n  | 'operation_debit' // HoloScript operation → debit\n  | 'promotion_credit' // Sign-up bonus, campaign → credit\n  | 'refund' // Stripe refund or admin reversal → credit\n  | 'adjustment'; // General correction (credit or debit)\n\n/** Balance inquiry result. */\nexport interface TokenBalance {\n  userId: string;\n  balance: number;\n  lastUpdated: string;\n  entryCount: number;\n}\n\n/** Result of a credit or debit operation. */\nexport interface TokenOperationResult {\n  entry: TokenLedgerEntry;\n  balanceBefore: number;\n  balanceAfter: number;\n}\n\n/** Stripe webhook event we accept for payment confirmation. */\nexport interface StripePaymentEvent {\n  /** Stripe event type. */\n  type: 'checkout.session.completed' | 'invoice.paid' | 'payment_intent.succeeded';\n  /** Stripe object ID. */\n  id: string;\n  /** Associated user ID — from metadata or customer lookup. */\n  userId: string;\n  /** Number of tokens to credit. */\n  tokenAmount: number;\n  /** Stripe charge/payment intent ID for audit trail. */\n  stripeId: string;\n  /** ISO 8601 when Stripe recorded the event. */\n  stripeTimestamp: string;\n  /** Raw event payload for forensic audit. */\n  raw?: unknown;\n}\n\n// ── Errors ──────────────────────────────────────────────────────────────────\n\nexport class InsufficientBalanceError extends Error {\n  constructor(\n    public readonly userId: string,\n    public readonly requested: number,\n    public readonly available: number\n  ) {\n    super(\n      `Insufficient token balance for ${userId}: requested ${requested}, available ${available}`\n    );\n    this.name = 'InsufficientBalanceError';\n  }\n}\n\nexport class DuplicateEntryError extends Error {\n  constructor(public readonly entryId: string) {\n    super(`Duplicate ledger entry: ${entryId}`);\n    this.name = 'DuplicateEntryError';\n  }\n}\n\nexport class InvalidAmountError extends Error {\n  constructor(amount: number, reason: string) {\n    super(`Invalid token amount ${amount}: ${reason}`);\n    this.name = 'InvalidAmountError';\n  }\n}\n\n// ── Ledger ───────────────────────────────────────────────────────────────────\n\n/** Set of entry IDs that have been applied — used for dedup. */\nconst appliedEntries = new Set<string>();\n\n/** Per-user ledger: userId → sorted array of entries (oldest first). */\nconst userLedgers = new Map<string, TokenLedgerEntry[]>();\n\n/** Per-user cached balance (derived from ledger; invalidated on mutation). */\nconst balanceCache = new Map<string, number>();\n\n/** Dedup window for Stripe events — prevents double-credit on webhook retry. */\nconst stripeEventDedup = new Map<string, number>(); // stripeEventId → timestamp\n\n/** Max dedup window in ms (72 hours — Stripe recommends 24h, we're generous). */\nconst DEDUP_WINDOW_MS = 72 * 60 * 60 * 1000;\n\n// ── Internal helpers ─────────────────────────────────────────────────────────\n\n/** Generate a unique entry ID. */\nfunction generateEntryId(userId: string, type: string, timestamp: string): string {\n  const nonce = crypto.randomBytes(8).toString('hex');\n  const hash = crypto\n    .createHash('sha256')\n    .update(`${userId}|${type}|${timestamp}|${nonce}`)\n    .digest('hex')\n    .slice(0, 12);\n  return `tle_${hash}`;\n}\n\n/** Get the ledger for a user, creating it if absent. */\nfunction getLedger(userId: string): TokenLedgerEntry[] {\n  let ledger = userLedgers.get(userId);\n  if (!ledger) {\n    ledger = [];\n    userLedgers.set(userId, ledger);\n  }\n  return ledger;\n}\n\n/** Recompute balance from the full ledger. Used to validate cache. */\nfunction recomputeBalance(userId: string): number {\n  const ledger = getLedger(userId);\n  let balance = 0;\n  for (const entry of ledger) {\n    if (entry.type === 'credit') {\n      balance += entry.amount;\n    } else {\n      balance -= entry.amount;\n    }\n  }\n  return Math.max(0, balance); // Floor at 0 — never negative\n}\n\n// ── Public API ───────────────────────────────────────────────────────────────\n\n/**\n * Credit tokens to a user's balance. Used for:\n *   - Stripe webhook payment confirmation (source: stripe_payment)\n *   - Admin grants (source: admin_grant)\n *   - Promotions (source: promotion_credit)\n *   - Refunds (source: refund)\n *\n * Idempotent on reference — if an entry with the same reference already\n * exists, returns the existing entry without creating a duplicate.\n */\nexport function creditTokens(\n  userId: string,\n  amount: number,\n  source: TokenSource,\n  reference: string,\n  metadata?: Record<string, unknown>,\n  timestamp: string = new Date().toISOString()\n): TokenOperationResult {\n  if (amount <= 0) {\n    throw new InvalidAmountError(amount, 'credit amount must be positive');\n  }\n\n  // Idempotency: if an entry with this reference already exists for this user,\n  // return it without creating a duplicate. This is the primary Stripe dedup\n  // mechanism — webhook retries carry the same event ID as reference.\n  const ledger = getLedger(userId);\n  const existing = ledger.find((e) => e.reference === reference);\n  if (existing) {\n    return {\n      entry: existing,\n      balanceBefore: existing.balanceAfter - existing.amount,\n      balanceAfter: existing.balanceAfter,\n    };\n  }\n\n  const balanceBefore = getBalance(userId);\n  const balanceAfter = balanceBefore + amount;\n  const entry: TokenLedgerEntry = {\n    id: generateEntryId(userId, 'credit', timestamp),\n    userId,\n    type: 'credit',\n    amount,\n    balanceAfter,\n    timestamp,\n    source,\n    reference,\n    metadata,\n  };\n\n  ledger.push(entry);\n  balanceCache.set(userId, balanceAfter);\n\n  return { entry, balanceBefore, balanceAfter };\n}\n\n/**\n * Debit tokens from a user's balance. Used for:\n *   - HoloScript operations (source: operation_debit)\n *   - Admin revocations (source: admin_revoke)\n *   - Adjustments (source: adjustment)\n *\n * Throws InsufficientBalanceError if balance < amount.\n */\nexport function debitTokens(\n  userId: string,\n  amount: number,\n  source: TokenSource,\n  reference: string,\n  metadata?: Record<string, unknown>,\n  timestamp: string = new Date().toISOString()\n): TokenOperationResult {\n  if (amount <= 0) {\n    throw new InvalidAmountError(amount, 'debit amount must be positive');\n  }\n\n  const balanceBefore = getBalance(userId);\n  if (balanceBefore < amount) {\n    throw new InsufficientBalanceError(userId, amount, balanceBefore);\n  }\n\n  const balanceAfter = balanceBefore - amount;\n  const ledger = getLedger(userId);\n  const entry: TokenLedgerEntry = {\n    id: generateEntryId(userId, 'debit', timestamp),\n    userId,\n    type: 'debit',\n    amount,\n    balanceAfter,\n    timestamp,\n    source,\n    reference,\n    metadata,\n  };\n\n  ledger.push(entry);\n  balanceCache.set(userId, balanceAfter);\n\n  return { entry, balanceBefore, balanceAfter };\n}\n\n/**\n * Get the current token balance for a user. Returns 0 for unknown users\n * (new users start with zero balance; must be credited via Stripe or admin).\n */\nexport function getBalance(userId: string): number {\n  const cached = balanceCache.get(userId);\n  if (cached !== undefined) {\n    return cached;\n  }\n  const balance = recomputeBalance(userId);\n  balanceCache.set(userId, balance);\n  return balance;\n}\n\n/**\n * Get the full balance info for a user (balance + metadata).\n */\nexport function getBalanceInfo(userId: string): TokenBalance {\n  const ledger = getLedger(userId);\n  const balance = getBalance(userId);\n  const lastEntry = ledger.length > 0 ? ledger[ledger.length - 1] : undefined;\n  return {\n    userId,\n    balance,\n    lastUpdated: lastEntry?.timestamp ?? new Date().toISOString(),\n    entryCount: ledger.length,\n  };\n}\n\n/**\n * Get the ledger history for a user, optionally filtered.\n * Returns entries newest-first (reverse chronological).\n */\nexport function getLedgerHistory(\n  userId: string,\n  options?: { limit?: number; offset?: number; type?: 'credit' | 'debit' }\n): TokenLedgerEntry[] {\n  let entries = getLedger(userId);\n\n  if (options?.type) {\n    entries = entries.filter((e) => e.type === options.type);\n  }\n\n  // Reverse for newest-first\n  const reversed = [...entries].reverse();\n\n  const offset = options?.offset ?? 0;\n  const limit = options?.limit ?? 100;\n\n  return reversed.slice(offset, offset + limit);\n}\n\n/**\n * Process a Stripe payment event. Deduplicates by Stripe event ID.\n *\n * This is the primary entry point for the Stripe webhook handler. It:\n * 1. Checks the dedup window for this Stripe event ID\n * 2. Credits tokens to the user's balance\n * 3. Records the Stripe event for audit\n *\n * Returns the operation result, or null if the event was already processed\n * (within the dedup window).\n */\nexport function processStripePayment(event: StripePaymentEvent): TokenOperationResult | null {\n  const now = Date.now();\n\n  // Dedup check — Stripe retries webhooks, so we must be idempotent\n  const lastSeen = stripeEventDedup.get(event.id);\n  if (lastSeen !== undefined && now - lastSeen < DEDUP_WINDOW_MS) {\n    // Already processed within the dedup window — skip\n    return null;\n  }\n\n  // Record the event for dedup\n  stripeEventDedup.set(event.id, now);\n\n  // Credit the tokens\n  const result = creditTokens(\n    event.userId,\n    event.tokenAmount,\n    'stripe_payment',\n    `stripe_${event.id}`,\n    {\n      stripeId: event.stripeId,\n      stripeType: event.type,\n      stripeTimestamp: event.stripeTimestamp,\n      ...(event.raw ? { rawEvent: event.raw } : {}),\n    }\n  );\n\n  return result;\n}\n\n/**\n * Check whether a user has sufficient balance for an operation.\n * Returns true if balance >= amount, false otherwise.\n * Does NOT debit — use debitTokens() for that.\n */\nexport function hasSufficientBalance(userId: string, amount: number): boolean {\n  return getBalance(userId) >= amount;\n}\n\n/**\n * Authorize a token spend for an operation. This is a combined\n * check-and-reserve: it verifies sufficient balance and debits atomically.\n *\n * Throws InsufficientBalanceError if balance < amount.\n * Returns the operation result on success.\n */\nexport function authorizeAndDebit(\n  userId: string,\n  amount: number,\n  operationName: string,\n  metadata?: Record<string, unknown>\n): TokenOperationResult {\n  return debitTokens(userId, amount, 'operation_debit', `op_${operationName}_${Date.now()}`, {\n    operation: operationName,\n    ...metadata,\n  });\n}\n\n// ── Admin operations ──────────────────────────────────────────────────────────\n\n/**\n * Grant tokens to a user (admin operation). Founder or admin key required\n * at the route layer — this function doesn't enforce auth, only the ledger.\n */\nexport function grantTokens(\n  userId: string,\n  amount: number,\n  adminId: string,\n  reason: string\n): TokenOperationResult {\n  return creditTokens(userId, amount, 'admin_grant', `admin_grant_${adminId}_${Date.now()}`, {\n    adminId,\n    reason,\n  });\n}\n\n/**\n * Revoke tokens from a user (admin operation). Unlike a debit (which requires\n * sufficient balance), a revocation can take balance negative if needed for\n * correction purposes. Admin revocations are always allowed.\n *\n * If balance would go negative, it's floored at 0 and the difference is logged\n * in metadata as `writeOff`.\n */\nexport function revokeTokens(\n  userId: string,\n  amount: number,\n  adminId: string,\n  reason: string\n): TokenOperationResult {\n  if (amount <= 0) {\n    throw new InvalidAmountError(amount, 'revoke amount must be positive');\n  }\n\n  const balanceBefore = getBalance(userId);\n  const writeOff = amount > balanceBefore ? amount - balanceBefore : 0;\n  const balanceAfter = Math.max(0, balanceBefore - amount);\n  const actualDebit = amount - writeOff;\n\n  // If the full amount can't be debited (balance too low), debit what we can\n  // and record the write-off\n  if (actualDebit === 0) {\n    // Balance is already 0 — nothing to revoke, but still record the attempt\n    const entry: TokenLedgerEntry = {\n      id: generateEntryId(userId, 'debit', new Date().toISOString()),\n      userId,\n      type: 'debit',\n      amount: 0, // No actual debit\n      balanceAfter: 0,\n      timestamp: new Date().toISOString(),\n      source: 'admin_revoke',\n      reference: `admin_revoke_${adminId}_${Date.now()}`,\n      metadata: {\n        requestedAmount: amount,\n        writeOff,\n        adminId,\n        reason,\n        note: 'Balance was 0; revocation recorded as write-off',\n      },\n    };\n    getLedger(userId).push(entry);\n    return { entry, balanceBefore: 0, balanceAfter: 0 };\n  }\n\n  // Debit the available amount\n  const result = debitTokens(\n    userId,\n    actualDebit,\n    'admin_revoke',\n    `admin_revoke_${adminId}_${Date.now()}`,\n    {\n      requestedAmount: amount,\n      writeOff,\n      adminId,\n      reason,\n    }\n  );\n\n  return result;\n}\n\n// ── Persistence ──────────────────────────────────────────────────────────────\n\n/** Serialize the entire ledger state for persistence. */\nexport function serializeLedger(): {\n  version: number;\n  entries: Record<string, TokenLedgerEntry[]>;\n  stripeDedup: Array<[string, number]>;\n  savedAt: string;\n} {\n  return {\n    version: 1,\n    entries: Object.fromEntries(userLedgers.entries()),\n    stripeDedup: Array.from(stripeEventDedup.entries()),\n    savedAt: new Date().toISOString(),\n  };\n}\n\n/** Restore ledger state from persisted data. */\nexport function deserializeLedger(data: {\n  version: number;\n  entries: Record<string, TokenLedgerEntry[]>;\n  stripeDedup?: Array<[string, number]>;\n}): void {\n  userLedgers.clear();\n  balanceCache.clear();\n\n  for (const [userId, entries] of Object.entries(data.entries)) {\n    userLedgers.set(userId, entries);\n    // Recompute and cache the balance\n    balanceCache.set(userId, recomputeBalance(userId));\n  }\n\n  // Restore Stripe dedup window\n  stripeEventDedup.clear();\n  if (data.stripeDedup) {\n    for (const [eventId, ts] of data.stripeDedup) {\n      stripeEventDedup.set(eventId, ts);\n    }\n  }\n\n  // Prune expired dedup entries\n  const now = Date.now();\n  for (const [eventId, ts] of stripeEventDedup.entries()) {\n    if (now - ts > DEDUP_WINDOW_MS) {\n      stripeEventDedup.delete(eventId);\n    }\n  }\n}\n\n// ── Test helpers ─────────────────────────────────────────────────────────────\n\n/** Reset all ledger state. Test-only. */\nexport function _resetLedger(): void {\n  userLedgers.clear();\n  balanceCache.clear();\n  appliedEntries.clear();\n  stripeEventDedup.clear();\n}\n\n/** Get the number of users with ledgers. Test-only. */\nexport function _userCount(): number {\n  return userLedgers.size;\n}\n\n/** Get the total number of entries across all users. Test-only. */\nexport function _totalEntryCount(): number {\n  let count = 0;\n  for (const ledger of userLedgers.values()) {\n    count += ledger.length;\n  }\n  return count;\n}\n","import {\n  createRailwayPostgresPoolOptions,\n  type RailwayPostgresPoolOptions,\n} from '../postgres-pool-options';\n\nexport type HoloMeshPostgresPoolOptions = RailwayPostgresPoolOptions;\n\nexport function createHoloMeshPostgresPoolOptions(\n  databaseUrl: string\n): HoloMeshPostgresPoolOptions {\n  return createRailwayPostgresPoolOptions(databaseUrl);\n}\n","/**\n * TeamStore — Shared backend for team state across Railway instances.\n *\n * Problem: Railway deploys multiple ephemeral containers. Each has its own\n * filesystem, so `teams.json` written by Instance A is invisible to Instance B.\n * Board claims (and all team mutations) appear to vanish when a request lands on\n * a different instance.\n *\n * Solution: When `DATABASE_URL` is present, store team state in PostgreSQL\n * JSONB. Each instance reads/writes the same row, so mutations are visible\n * everywhere immediately. When `DATABASE_URL` is absent, fall back to the\n * legacy in-memory Map (local dev / single-instance).\n *\n * Pattern mirrors `auth/postgres-token-store.ts` — pluggable backend with\n * auto-migration on first connection.\n */\n\nimport type { Pool, PoolClient } from 'pg';\nimport type { Team } from './types';\nimport {\n  createHoloMeshPostgresPoolOptions,\n  type HoloMeshPostgresPoolOptions,\n} from './postgres-pool-options';\n\nexport type TeamStorePostgresPoolOptions = HoloMeshPostgresPoolOptions;\n\nexport function createTeamStorePostgresPoolOptions(\n  databaseUrl: string\n): TeamStorePostgresPoolOptions {\n  return createHoloMeshPostgresPoolOptions(databaseUrl);\n}\n\n// ── Schema DDL ───────────────────────────────────────────────────────────────\n\nconst SCHEMA_SQL = `\nCREATE TABLE IF NOT EXISTS holomesh_teams (\n  id          TEXT PRIMARY KEY,\n  data        JSONB NOT NULL,\n  updated_at  TIMESTAMP WITH TIME ZONE DEFAULT NOW()\n);\nCREATE INDEX IF NOT EXISTS idx_holomesh_teams_updated ON holomesh_teams (updated_at);\n`;\n\n// ── TeamStoreBackend Interface ────────────────────────────────────────────────\n\nexport interface TeamStoreBackend {\n  get(teamId: string): Promise<Team | undefined>;\n  set(teamId: string, team: Team): Promise<void>;\n  delete(teamId: string): Promise<void>;\n  getAll(): Promise<Map<string, Team>>;\n  close?(): Promise<void>;\n}\n\n// ── In-Memory Backend (legacy, local dev) ───────────────────────────────────\n\nexport class InMemoryTeamStoreBackend implements TeamStoreBackend {\n  private store = new Map<string, Team>();\n\n  async get(teamId: string): Promise<Team | undefined> {\n    return this.store.get(teamId);\n  }\n\n  async set(teamId: string, team: Team): Promise<void> {\n    this.store.set(teamId, team);\n  }\n\n  async delete(teamId: string): Promise<void> {\n    this.store.delete(teamId);\n  }\n\n  async getAll(): Promise<Map<string, Team>> {\n    return new Map(this.store);\n  }\n}\n\n// ── PostgreSQL Backend (production, multi-instance) ─────────────────────────\n\nexport class PostgresTeamStoreBackend implements TeamStoreBackend {\n  private pool: Pool;\n  private ready: Promise<void>;\n\n  constructor(pool: Pool) {\n    this.pool = pool;\n    this.ready = this.ensureSchema();\n  }\n\n  private async ensureSchema(): Promise<void> {\n    const client = await this.pool.connect();\n    try {\n      await client.query(SCHEMA_SQL);\n    } finally {\n      client.release();\n    }\n  }\n\n  async get(teamId: string): Promise<Team | undefined> {\n    await this.ready;\n    const result = await this.pool.query('SELECT data FROM holomesh_teams WHERE id = $1', [teamId]);\n    if (result.rows.length === 0) return undefined;\n    return result.rows[0].data as Team;\n  }\n\n  async set(teamId: string, team: Team): Promise<void> {\n    await this.ready;\n    await this.pool.query(\n      `INSERT INTO holomesh_teams (id, data, updated_at)\n       VALUES ($1, $2, NOW())\n       ON CONFLICT (id) DO UPDATE SET data = EXCLUDED.data, updated_at = NOW()`,\n      [teamId, JSON.stringify(team)]\n    );\n  }\n\n  async delete(teamId: string): Promise<void> {\n    await this.ready;\n    await this.pool.query('DELETE FROM holomesh_teams WHERE id = $1', [teamId]);\n  }\n\n  async getAll(): Promise<Map<string, Team>> {\n    await this.ready;\n    const result = await this.pool.query('SELECT id, data FROM holomesh_teams');\n    const map = new Map<string, Team>();\n    for (const row of result.rows) {\n      map.set(row.id, row.data as Team);\n    }\n    return map;\n  }\n\n  async close(): Promise<void> {\n    await this.pool.end();\n  }\n}\n\n// ── TeamStore Wrapper (Map-compatible interface) ──────────────────────────────\n\n/**\n * TeamStore wraps a backend and presents a Map-like interface so existing\n * code (`teamStore.get(id)`, `teamStore.set(id, team)`, etc.) works without\n * modification.\n *\n * For performance, we keep an in-memory cache (`local`) and write-through to\n * the backend on mutation. On read, we always consult the backend FIRST when\n * Postgres is active, so cross-instance writes are visible immediately.\n *\n * Trade-off: one DB round-trip per `get()`. At the current scale\n * (≈1 team, <300 tasks) this is negligible (<5ms).\n */\nexport class TeamStore {\n  readonly [Symbol.toStringTag] = 'TeamStore';\n  private backend: TeamStoreBackend;\n  private local: Map<string, Team> = new Map();\n  private usePostgres: boolean;\n\n  constructor(backend: TeamStoreBackend, usePostgres: boolean) {\n    this.backend = backend;\n    this.usePostgres = usePostgres;\n  }\n\n  get usesPostgres(): boolean {\n    return this.usePostgres;\n  }\n\n  // Internal: sync local cache after backend read\n  private async syncFromBackend(teamId: string): Promise<Team | undefined> {\n    const team = await this.backend.get(teamId);\n    if (team) {\n      this.local.set(teamId, team);\n    } else {\n      this.local.delete(teamId);\n    }\n    return team;\n  }\n\n  // Map interface methods\n  get size(): number {\n    return this.local.size;\n  }\n\n  get(teamId: string): Team | undefined {\n    if (this.usePostgres) {\n      // Postgres path: always hit backend for freshness.\n      // This is synchronous-looking but the returned value may be from cache\n      // if the caller previously awaited a mutation in the same tick.\n      // For correctness in multi-instance, we re-fetch on next tick via\n      // the async path exposed by reloadTeam().\n      //\n      // NOTE: existing code reads teamStore synchronously. To avoid a\n      // massive refactor, we return the cached value here and rely on\n      // reloadTeam() being called at request boundaries (see board-routes.ts).\n      return this.local.get(teamId);\n    }\n    return this.local.get(teamId);\n  }\n\n  /** Async get that hits the backend every time. Use at request boundaries. */\n  async getFresh(teamId: string): Promise<Team | undefined> {\n    return this.syncFromBackend(teamId);\n  }\n\n  set(teamId: string, team: Team): this {\n    this.local.set(teamId, team);\n    // Fire-and-forget write-through to backend\n    this.backend.set(teamId, team).catch((e) => {\n      console.error('[TeamStore] backend write failed:', e);\n    });\n    return this;\n  }\n\n  has(teamId: string): boolean {\n    return this.local.has(teamId);\n  }\n\n  delete(teamId: string): boolean {\n    const had = this.local.delete(teamId);\n    this.backend.delete(teamId).catch((e) => {\n      console.error('[TeamStore] backend delete failed:', e);\n    });\n    return had;\n  }\n\n  clear(): void {\n    this.local.clear();\n    // We don't clear the backend — that's a separate explicit operation.\n  }\n\n  fallbackToMemory(): void {\n    const memory = new InMemoryTeamStoreBackend();\n    for (const [teamId, team] of this.local.entries()) {\n      memory.set(teamId, team).catch((e) => {\n        console.error('[TeamStore] memory fallback seed failed:', e);\n      });\n    }\n    this.backend = memory;\n    this.usePostgres = false;\n  }\n\n  forEach(\n    callbackfn: (value: Team, key: string, map: Map<string, Team>) => void,\n    thisArg?: any\n  ): void {\n    this.local.forEach(callbackfn, thisArg);\n  }\n\n  keys(): IterableIterator<string> {\n    return this.local.keys();\n  }\n\n  values(): IterableIterator<Team> {\n    return this.local.values();\n  }\n\n  entries(): IterableIterator<[string, Team]> {\n    return this.local.entries();\n  }\n\n  [Symbol.iterator](): IterableIterator<[string, Team]> {\n    return this.local[Symbol.iterator]();\n  }\n\n  /** Load all teams from backend into local cache (startup / refresh) */\n  async loadAll(): Promise<void> {\n    const all = await this.backend.getAll();\n    this.local = all;\n  }\n\n  /** Persist a single team immediately (awaitable) */\n  async persist(teamId: string): Promise<void> {\n    const team = this.local.get(teamId);\n    if (team) {\n      await this.backend.set(teamId, team);\n    }\n  }\n}\n\n// ── Factory ───────────────────────────────────────────────────────────────────\n\nexport function createTeamStore(): TeamStore {\n  const databaseUrl = process.env.DATABASE_URL;\n  if (databaseUrl) {\n    try {\n      // Lazy-import pg so local dev without DATABASE_URL doesn't crash\n      // eslint-disable-next-line @typescript-eslint/no-var-requires\n      const { Pool } = require('pg');\n      const pool = new Pool(createTeamStorePostgresPoolOptions(databaseUrl));\n      const backend = new PostgresTeamStoreBackend(pool);\n      console.error('[TeamStore] PostgreSQL backend active (multi-instance)');\n      return new TeamStore(backend, true);\n    } catch (e) {\n      console.warn('[TeamStore] DATABASE_URL set but pg failed to load:', e);\n    }\n  }\n  console.error('[TeamStore] In-memory backend (single-instance / dev)');\n  return new TeamStore(new InMemoryTeamStoreBackend(), false);\n}\n","/**\n * StateStore — Shared backend for agent state across Railway instances.\n *\n * Problem: Railway deploys multiple ephemeral containers. Local filesystem\n * writes (~/.holoscript/holomesh/audit|defense|dispatch) are invisible across\n * instances, so CAEL audit, defense config, and dispatch queues restart at 0\n * on every redeploy (W.101).\n *\n * Solution: When DATABASE_URL is present, store state in PostgreSQL JSONB.\n * A single table serves all three namespaces (audit, defense, dispatch)\n * with namespace/handle/seq discrimination.\n *\n * Pattern mirrors team-store.ts — pluggable backend with auto-migration.\n */\n\nimport type { Pool, PoolClient } from 'pg';\nimport { createHoloMeshPostgresPoolOptions } from './postgres-pool-options';\n\n// ── Schema DDL ───────────────────────────────────────────────────────────────\n\nconst SCHEMA_SQL = `\nCREATE TABLE IF NOT EXISTS holomesh_state (\n  namespace  TEXT NOT NULL,\n  handle     TEXT NOT NULL,\n  seq        INTEGER NOT NULL DEFAULT 0,\n  data       JSONB NOT NULL,\n  updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),\n  PRIMARY KEY (namespace, handle, seq)\n);\nCREATE INDEX IF NOT EXISTS idx_holomesh_state_ns_handle ON holomesh_state (namespace, handle);\nCREATE INDEX IF NOT EXISTS idx_holomesh_state_updated ON holomesh_state (updated_at);\n`;\n\n// ── Backend Interface ──────────────────────────────────────────────────────────\n\nexport interface StateStoreBackend {\n  get(namespace: string, handle: string): Promise<unknown | undefined>;\n  set(namespace: string, handle: string, data: unknown): Promise<void>;\n  append(namespace: string, handle: string, data: unknown): Promise<void>;\n  getAll(namespace: string, handle: string): Promise<unknown[]>;\n  listHandles(namespace: string): Promise<string[]>;\n  delete(namespace: string, handle: string): Promise<void>;\n  close?(): Promise<void>;\n}\n\n// ── In-Memory Backend (legacy, local dev) ───────────────────────────────────\n\nexport class InMemoryStateStoreBackend implements StateStoreBackend {\n  private store = new Map<string, unknown[]>();\n\n  private key(namespace: string, handle: string): string {\n    return `${namespace}:${handle}`;\n  }\n\n  async get(namespace: string, handle: string): Promise<unknown | undefined> {\n    const list = this.store.get(this.key(namespace, handle));\n    return list && list.length > 0 ? list[list.length - 1] : undefined;\n  }\n\n  async set(namespace: string, handle: string, data: unknown): Promise<void> {\n    this.store.set(this.key(namespace, handle), [data]);\n  }\n\n  async append(namespace: string, handle: string, data: unknown): Promise<void> {\n    const key = this.key(namespace, handle);\n    const list = this.store.get(key) || [];\n    list.push(data);\n    this.store.set(key, list);\n  }\n\n  async getAll(namespace: string, handle: string): Promise<unknown[]> {\n    return [...(this.store.get(this.key(namespace, handle)) || [])];\n  }\n\n  async delete(namespace: string, handle: string): Promise<void> {\n    this.store.delete(this.key(namespace, handle));\n  }\n\n  async listHandles(namespace: string): Promise<string[]> {\n    const handles: string[] = [];\n    const prefix = `${namespace}:`;\n    for (const key of this.store.keys()) {\n      if (key.startsWith(prefix)) {\n        handles.push(key.slice(prefix.length));\n      }\n    }\n    return handles;\n  }\n}\n\n// ── PostgreSQL Backend (production, multi-instance) ─────────────────────────\n\nexport class PostgresStateStoreBackend implements StateStoreBackend {\n  private pool: Pool;\n  private ready: Promise<void>;\n\n  constructor(pool: Pool) {\n    this.pool = pool;\n    this.ready = this.ensureSchema();\n  }\n\n  private async ensureSchema(): Promise<void> {\n    const client = await this.pool.connect();\n    try {\n      await client.query(SCHEMA_SQL);\n    } finally {\n      client.release();\n    }\n  }\n\n  async get(namespace: string, handle: string): Promise<unknown | undefined> {\n    await this.ready;\n    const result = await this.pool.query(\n      'SELECT data FROM holomesh_state WHERE namespace = $1 AND handle = $2 AND seq = 0',\n      [namespace, handle]\n    );\n    if (result.rows.length === 0) return undefined;\n    return result.rows[0].data;\n  }\n\n  async set(namespace: string, handle: string, data: unknown): Promise<void> {\n    await this.ready;\n    await this.pool.query(\n      `INSERT INTO holomesh_state (namespace, handle, seq, data, updated_at)\n       VALUES ($1, $2, 0, $3, NOW())\n       ON CONFLICT (namespace, handle, seq) DO UPDATE SET data = EXCLUDED.data, updated_at = NOW()`,\n      [namespace, handle, JSON.stringify(data)]\n    );\n  }\n\n  async append(namespace: string, handle: string, data: unknown): Promise<void> {\n    await this.ready;\n    await this.pool.query(\n      `INSERT INTO holomesh_state (namespace, handle, seq, data, updated_at)\n       SELECT $1, $2, COALESCE(MAX(seq), 0) + 1, $3, NOW()\n       FROM holomesh_state\n       WHERE namespace = $1 AND handle = $2`,\n      [namespace, handle, JSON.stringify(data)]\n    );\n  }\n\n  async getAll(namespace: string, handle: string): Promise<unknown[]> {\n    await this.ready;\n    const result = await this.pool.query(\n      'SELECT data FROM holomesh_state WHERE namespace = $1 AND handle = $2 ORDER BY seq',\n      [namespace, handle]\n    );\n    return result.rows.map((r) => r.data);\n  }\n\n  async delete(namespace: string, handle: string): Promise<void> {\n    await this.ready;\n    await this.pool.query('DELETE FROM holomesh_state WHERE namespace = $1 AND handle = $2', [\n      namespace,\n      handle,\n    ]);\n  }\n\n  async listHandles(namespace: string): Promise<string[]> {\n    await this.ready;\n    const result = await this.pool.query(\n      'SELECT DISTINCT handle FROM holomesh_state WHERE namespace = $1',\n      [namespace]\n    );\n    return result.rows.map((r) => r.handle as string);\n  }\n\n  async close(): Promise<void> {\n    await this.pool.end();\n  }\n}\n\n// ── Factory ───────────────────────────────────────────────────────────────────\n\nexport class FallbackStateStoreBackend implements StateStoreBackend {\n  private backend: StateStoreBackend;\n  private readonly memory = new InMemoryStateStoreBackend();\n  private usePostgres = true;\n\n  constructor(backend: StateStoreBackend) {\n    this.backend = backend;\n  }\n\n  get usesPostgres(): boolean {\n    return this.usePostgres;\n  }\n\n  fallbackToMemory(): void {\n    this.backend = this.memory;\n    this.usePostgres = false;\n  }\n\n  private async withFallback<T>(\n    label: string,\n    fn: (backend: StateStoreBackend) => Promise<T>\n  ): Promise<T> {\n    try {\n      return await fn(this.backend);\n    } catch (e) {\n      if (!this.usePostgres) throw e;\n      console.warn(`[StateStore] PostgreSQL ${label} failed; using in-memory backend:`, e);\n      this.fallbackToMemory();\n      return fn(this.backend);\n    }\n  }\n\n  async get(namespace: string, handle: string): Promise<unknown | undefined> {\n    return this.withFallback('read', (backend) => backend.get(namespace, handle));\n  }\n\n  async set(namespace: string, handle: string, data: unknown): Promise<void> {\n    return this.withFallback('write', (backend) => backend.set(namespace, handle, data));\n  }\n\n  async append(namespace: string, handle: string, data: unknown): Promise<void> {\n    return this.withFallback('append', (backend) => backend.append(namespace, handle, data));\n  }\n\n  async getAll(namespace: string, handle: string): Promise<unknown[]> {\n    return this.withFallback('read-all', (backend) => backend.getAll(namespace, handle));\n  }\n\n  async listHandles(namespace: string): Promise<string[]> {\n    return this.withFallback('list-handles', (backend) => backend.listHandles(namespace));\n  }\n\n  async delete(namespace: string, handle: string): Promise<void> {\n    return this.withFallback('delete', (backend) => backend.delete(namespace, handle));\n  }\n\n  async close(): Promise<void> {\n    await this.backend.close?.();\n  }\n}\n\nexport function createStateStore(): StateStoreBackend {\n  const databaseUrl = process.env.DATABASE_URL;\n  if (databaseUrl) {\n    try {\n      // eslint-disable-next-line @typescript-eslint/no-var-requires\n      const { Pool } = require('pg');\n      const pool = new Pool(createHoloMeshPostgresPoolOptions(databaseUrl));\n      console.error('[StateStore] PostgreSQL backend active (multi-instance)');\n      return new FallbackStateStoreBackend(new PostgresStateStoreBackend(pool));\n    } catch (e) {\n      console.warn('[StateStore] DATABASE_URL set but pg failed to load:', e);\n    }\n  }\n  console.error('[StateStore] In-memory backend (single-instance / dev)');\n  return new InMemoryStateStoreBackend();\n}\n","/**\n * PlayerStore — Shared backend for player/user state across Railway instances.\n *\n * Problem: Railway deploys multiple ephemeral containers. playerRegistry was an\n * in-memory Map, so agents querying any instance other than the one that received\n * the provisioning call saw zero players — even though real users (the founder,\n * agent seats) exist and had been provisioned.\n *\n * Solution: When DATABASE_URL is present, store player state in PostgreSQL JSONB.\n * Mirrors the team-store.ts pattern (W.128/W.136 fix).\n *\n * On startup, initStores() seeds the founder player so agents never see an empty\n * player list on a fresh deploy.\n */\n\nimport type { Pool } from 'pg';\nimport { createHoloMeshPostgresPoolOptions } from './postgres-pool-options';\n\n// ── StoredPlayer Type ─────────────────────────────────────────────────────────\n\nexport interface StoredPlayer {\n  id: string;\n  name: string;\n  walletAddress?: string;\n  worldId?: string;\n  shardId?: string;\n  zoneId?: string;\n  /**\n   * The soul's durable identity (HoloMesh agentId), shared across surfaces. This is\n   * the LINK that makes the per-soul daimōn transferable (D.053): a HoloLand player\n   * and a HoloScript/Studio workspace bound to the same agentId share one daimōn.\n   * Caller-asserted here (no wallet/custody binding — that merge is founder-gated, F.095).\n   */\n  agentId?: string;\n  /**\n   * Deterministic per-soul daimōn id (`daemon-${agentId}`). HoloLand references the\n   * SAME ConversationDaemon that emerges on other surfaces — it does NOT eagerly\n   * create one (the daimōn emerges from being known; it may already exist elsewhere).\n   */\n  daemonId?: string;\n  status: 'active' | 'suspended' | 'revoked';\n  createdAt: string;\n  modifiedAt: string;\n}\n\n// ── Schema DDL ────────────────────────────────────────────────────────────────\n\nconst SCHEMA_SQL = `\nCREATE TABLE IF NOT EXISTS hololand_players (\n  id          TEXT PRIMARY KEY,\n  data        JSONB NOT NULL,\n  updated_at  TIMESTAMP WITH TIME ZONE DEFAULT NOW()\n);\nCREATE INDEX IF NOT EXISTS idx_hololand_players_updated ON hololand_players (updated_at);\n`;\n\n// ── PlayerStoreBackend Interface ──────────────────────────────────────────────\n\nexport interface PlayerStoreBackend {\n  get(playerId: string): Promise<StoredPlayer | undefined>;\n  set(playerId: string, player: StoredPlayer): Promise<void>;\n  delete(playerId: string): Promise<void>;\n  getAll(): Promise<Map<string, StoredPlayer>>;\n  close?(): Promise<void>;\n}\n\n// ── In-Memory Backend (local dev / tests) ────────────────────────────────────\n\nexport class InMemoryPlayerStoreBackend implements PlayerStoreBackend {\n  private store = new Map<string, StoredPlayer>();\n\n  async get(playerId: string): Promise<StoredPlayer | undefined> {\n    return this.store.get(playerId);\n  }\n\n  async set(playerId: string, player: StoredPlayer): Promise<void> {\n    this.store.set(playerId, player);\n  }\n\n  async delete(playerId: string): Promise<void> {\n    this.store.delete(playerId);\n  }\n\n  async getAll(): Promise<Map<string, StoredPlayer>> {\n    return new Map(this.store);\n  }\n}\n\n// ── PostgreSQL Backend (production, multi-instance) ──────────────────────────\n\nexport class PostgresPlayerStoreBackend implements PlayerStoreBackend {\n  private pool: Pool;\n  private ready: Promise<void>;\n\n  constructor(pool: Pool) {\n    this.pool = pool;\n    this.ready = this.ensureSchema();\n  }\n\n  private async ensureSchema(): Promise<void> {\n    const client = await this.pool.connect();\n    try {\n      await client.query(SCHEMA_SQL);\n    } finally {\n      client.release();\n    }\n  }\n\n  async get(playerId: string): Promise<StoredPlayer | undefined> {\n    await this.ready;\n    const result = await this.pool.query('SELECT data FROM hololand_players WHERE id = $1', [\n      playerId,\n    ]);\n    if (result.rows.length === 0) return undefined;\n    return result.rows[0].data as StoredPlayer;\n  }\n\n  async set(playerId: string, player: StoredPlayer): Promise<void> {\n    await this.ready;\n    await this.pool.query(\n      `INSERT INTO hololand_players (id, data, updated_at)\n       VALUES ($1, $2, NOW())\n       ON CONFLICT (id) DO UPDATE SET data = EXCLUDED.data, updated_at = NOW()`,\n      [playerId, JSON.stringify(player)]\n    );\n  }\n\n  async delete(playerId: string): Promise<void> {\n    await this.ready;\n    await this.pool.query('DELETE FROM hololand_players WHERE id = $1', [playerId]);\n  }\n\n  async getAll(): Promise<Map<string, StoredPlayer>> {\n    await this.ready;\n    const result = await this.pool.query('SELECT id, data FROM hololand_players');\n    const map = new Map<string, StoredPlayer>();\n    for (const row of result.rows) {\n      map.set(row.id, row.data as StoredPlayer);\n    }\n    return map;\n  }\n\n  async close(): Promise<void> {\n    await this.pool.end();\n  }\n}\n\n// ── PlayerStore Wrapper (Map-compatible interface) ────────────────────────────\n\nexport class PlayerStore {\n  readonly [Symbol.toStringTag] = 'PlayerStore';\n  private backend: PlayerStoreBackend;\n  private local: Map<string, StoredPlayer> = new Map();\n  private _usePostgres: boolean;\n\n  constructor(backend: PlayerStoreBackend, usePostgres: boolean) {\n    this.backend = backend;\n    this._usePostgres = usePostgres;\n  }\n\n  get usesPostgres(): boolean {\n    return this._usePostgres;\n  }\n\n  fallbackToMemory(): void {\n    const memory = new InMemoryPlayerStoreBackend();\n    for (const [playerId, player] of this.local.entries()) {\n      memory.set(playerId, player).catch((e) => {\n        console.error('[PlayerStore] memory fallback seed failed:', e);\n      });\n    }\n    this.backend = memory;\n    this._usePostgres = false;\n  }\n\n  get size(): number {\n    return this.local.size;\n  }\n\n  get(playerId: string): StoredPlayer | undefined {\n    return this.local.get(playerId);\n  }\n\n  async getFresh(playerId: string): Promise<StoredPlayer | undefined> {\n    let player: StoredPlayer | undefined;\n    try {\n      player = await this.backend.get(playerId);\n    } catch (e) {\n      if (this._usePostgres) {\n        console.warn('[PlayerStore] PostgreSQL read failed; using in-memory backend:', e);\n        this.fallbackToMemory();\n        player = await this.backend.get(playerId);\n      } else {\n        throw e;\n      }\n    }\n    if (player) {\n      this.local.set(playerId, player);\n    } else {\n      this.local.delete(playerId);\n    }\n    return player;\n  }\n\n  set(playerId: string, player: StoredPlayer): this {\n    this.local.set(playerId, player);\n    this.backend.set(playerId, player).catch((e) => {\n      console.error('[PlayerStore] backend write failed:', e);\n      if (this._usePostgres) this.fallbackToMemory();\n    });\n    return this;\n  }\n\n  has(playerId: string): boolean {\n    return this.local.has(playerId);\n  }\n\n  delete(playerId: string): boolean {\n    const had = this.local.delete(playerId);\n    this.backend.delete(playerId).catch((e) => {\n      console.error('[PlayerStore] backend delete failed:', e);\n      if (this._usePostgres) this.fallbackToMemory();\n    });\n    return had;\n  }\n\n  clear(): void {\n    this.local.clear();\n  }\n\n  values(): IterableIterator<StoredPlayer> {\n    return this.local.values();\n  }\n\n  keys(): IterableIterator<string> {\n    return this.local.keys();\n  }\n\n  entries(): IterableIterator<[string, StoredPlayer]> {\n    return this.local.entries();\n  }\n\n  [Symbol.iterator](): IterableIterator<[string, StoredPlayer]> {\n    return this.local[Symbol.iterator]();\n  }\n\n  async loadAll(): Promise<void> {\n    let all: Map<string, StoredPlayer>;\n    try {\n      all = await this.backend.getAll();\n    } catch (e) {\n      if (this._usePostgres) {\n        console.warn('[PlayerStore] PostgreSQL load failed; using in-memory backend:', e);\n        this.fallbackToMemory();\n        all = await this.backend.getAll();\n      } else {\n        throw e;\n      }\n    }\n    this.local = all;\n  }\n\n  async persist(playerId: string): Promise<void> {\n    const player = this.local.get(playerId);\n    if (player) {\n      try {\n        await this.backend.set(playerId, player);\n      } catch (e) {\n        if (this._usePostgres) {\n          console.warn('[PlayerStore] PostgreSQL persist failed; using in-memory backend:', e);\n          this.fallbackToMemory();\n          await this.backend.set(playerId, player);\n        } else {\n          throw e;\n        }\n      }\n    }\n  }\n}\n\n// ── Factory ───────────────────────────────────────────────────────────────────\n\nexport function createPlayerStore(): PlayerStore {\n  const databaseUrl = process.env.DATABASE_URL;\n  if (databaseUrl) {\n    try {\n      // eslint-disable-next-line @typescript-eslint/no-var-requires\n      const { Pool } = require('pg');\n      const pool = new Pool(createHoloMeshPostgresPoolOptions(databaseUrl));\n      const backend = new PostgresPlayerStoreBackend(pool);\n      console.error('[PlayerStore] PostgreSQL backend active (multi-instance)');\n      return new PlayerStore(backend, true);\n    } catch (e) {\n      console.warn('[PlayerStore] DATABASE_URL set but pg failed to load:', e);\n    }\n  }\n  console.error('[PlayerStore] In-memory backend (single-instance / dev)');\n  return new PlayerStore(new InMemoryPlayerStoreBackend(), false);\n}\n","/**\n * InviteStore — Agent-first player onboarding.\n *\n * Flow: agent calls hololand_create_player_invite → gets a claim URL →\n * user visits URL in browser → sees agent identity → enters name → claim\n * provisions a player linked to the agent → world opens.\n *\n * Tokens are crypto-random, URL-safe, 32 bytes (~43 chars base64url).\n * Default TTL: 7 days. Claimed invites are retained for audit.\n */\n\nimport type { Pool } from 'pg';\nimport * as crypto from 'crypto';\nimport { createHoloMeshPostgresPoolOptions } from './postgres-pool-options';\n\n// ── InviteRecord Type ─────────────────────────────────────────────────────────\n\n/**\n * Delivery target determines how HoloMesh is presented to the user on claim.\n *\n * - 'holomesh' : web social network (Myspace for agents). Profile, feed, directory.\n * - 'hololand' : VR spatial layer. Player spawns into the world; agent is already\n *                there as an embodied presence. Social graph = world relationships.\n *                Delivered via VRChat world link / .holo world file, NOT the web UI.\n * - 'studio'   : creator layer. Absorb a codebase, build a world in HoloClaw.\n *\n * The same invite token routes to completely different experiences depending on\n * which door the agent opened for the user.\n */\nexport type InviteDelivery = 'holomesh' | 'hololand' | 'studio';\n\nexport interface InviteRecord {\n  token: string;\n  agentId: string;\n  agentName: string;\n  /** Surface handle, e.g. \"claude1\", \"cursor1\" — displayed on claim page */\n  agentHandle?: string;\n  /**\n   * How HoloMesh is delivered to this user.\n   * 'holomesh' = web social surface (default if agent doesn't specify).\n   * 'hololand' = VR spatial layer — different onboarding, different destination.\n   * 'studio'   = HoloClaw / Absorb builder layer.\n   */\n  delivery?: InviteDelivery;\n  /** VRChat world URL or .holo world ID — populated when delivery = 'hololand' */\n  worldLink?: string;\n  /** Optional world to auto-join on claim */\n  worldId?: string;\n  expiresAt: string;\n  /** Set when a player claims this invite */\n  claimedAt?: string;\n  playerId?: string;\n  playerName?: string;\n  createdAt: string;\n}\n\n// ── Token Generation ──────────────────────────────────────────────────────────\n\nexport function generateInviteToken(): string {\n  return crypto.randomBytes(32).toString('base64url');\n}\n\n// ── Schema DDL ────────────────────────────────────────────────────────────────\n\nconst SCHEMA_SQL = `\nCREATE TABLE IF NOT EXISTS hololand_invites (\n  token       TEXT PRIMARY KEY,\n  data        JSONB NOT NULL,\n  expires_at  TIMESTAMP WITH TIME ZONE NOT NULL,\n  claimed_at  TIMESTAMP WITH TIME ZONE,\n  updated_at  TIMESTAMP WITH TIME ZONE DEFAULT NOW()\n);\nCREATE INDEX IF NOT EXISTS idx_hololand_invites_expires ON hololand_invites (expires_at);\nCREATE INDEX IF NOT EXISTS idx_hololand_invites_agent ON hololand_invites ((data->>'agentId'));\n`;\n\n// ── Backend Interface ─────────────────────────────────────────────────────────\n\nexport interface InviteStoreBackend {\n  get(token: string): Promise<InviteRecord | undefined>;\n  set(invite: InviteRecord): Promise<void>;\n  listByAgent(agentId: string): Promise<InviteRecord[]>;\n  close?(): Promise<void>;\n}\n\n// ── In-Memory Backend (local dev / tests) ────────────────────────────────────\n\nexport class InMemoryInviteStoreBackend implements InviteStoreBackend {\n  private store = new Map<string, InviteRecord>();\n\n  async get(token: string): Promise<InviteRecord | undefined> {\n    return this.store.get(token);\n  }\n\n  async set(invite: InviteRecord): Promise<void> {\n    this.store.set(invite.token, invite);\n  }\n\n  async listByAgent(agentId: string): Promise<InviteRecord[]> {\n    return Array.from(this.store.values()).filter((i) => i.agentId === agentId);\n  }\n}\n\n// ── PostgreSQL Backend ────────────────────────────────────────────────────────\n\nexport class PostgresInviteStoreBackend implements InviteStoreBackend {\n  private pool: Pool;\n  private ready: Promise<void>;\n\n  constructor(pool: Pool) {\n    this.pool = pool;\n    this.ready = this.ensureSchema();\n  }\n\n  private async ensureSchema(): Promise<void> {\n    const client = await this.pool.connect();\n    try {\n      await client.query(SCHEMA_SQL);\n    } finally {\n      client.release();\n    }\n  }\n\n  async get(token: string): Promise<InviteRecord | undefined> {\n    await this.ready;\n    const result = await this.pool.query('SELECT data FROM hololand_invites WHERE token = $1', [\n      token,\n    ]);\n    if (result.rows.length === 0) return undefined;\n    return result.rows[0].data as InviteRecord;\n  }\n\n  async set(invite: InviteRecord): Promise<void> {\n    await this.ready;\n    await this.pool.query(\n      `INSERT INTO hololand_invites (token, data, expires_at, claimed_at, updated_at)\n       VALUES ($1, $2, $3, $4, NOW())\n       ON CONFLICT (token) DO UPDATE\n         SET data = EXCLUDED.data,\n             expires_at = EXCLUDED.expires_at,\n             claimed_at = EXCLUDED.claimed_at,\n             updated_at = NOW()`,\n      [invite.token, JSON.stringify(invite), invite.expiresAt, invite.claimedAt ?? null]\n    );\n  }\n\n  async listByAgent(agentId: string): Promise<InviteRecord[]> {\n    await this.ready;\n    const result = await this.pool.query(\n      `SELECT data FROM hololand_invites WHERE data->>'agentId' = $1 ORDER BY updated_at DESC`,\n      [agentId]\n    );\n    return result.rows.map((r) => r.data as InviteRecord);\n  }\n\n  async close(): Promise<void> {\n    await this.pool.end();\n  }\n}\n\n// ── InviteStore Wrapper ───────────────────────────────────────────────────────\n\nexport class InviteStore {\n  private backend: InviteStoreBackend;\n  private usePostgres: boolean;\n\n  constructor(backend: InviteStoreBackend, usePostgres = false) {\n    this.backend = backend;\n    this.usePostgres = usePostgres;\n  }\n\n  get usesPostgres(): boolean {\n    return this.usePostgres;\n  }\n\n  fallbackToMemory(): void {\n    this.backend = new InMemoryInviteStoreBackend();\n    this.usePostgres = false;\n  }\n\n  private async withFallback<T>(\n    label: string,\n    fn: (backend: InviteStoreBackend) => Promise<T>\n  ): Promise<T> {\n    try {\n      return await fn(this.backend);\n    } catch (e) {\n      if (!this.usePostgres) throw e;\n      console.warn(`[InviteStore] PostgreSQL ${label} failed; using in-memory backend:`, e);\n      this.fallbackToMemory();\n      return fn(this.backend);\n    }\n  }\n\n  async get(token: string): Promise<InviteRecord | undefined> {\n    return this.withFallback('read', (backend) => backend.get(token));\n  }\n\n  async set(invite: InviteRecord): Promise<void> {\n    return this.withFallback('write', (backend) => backend.set(invite));\n  }\n\n  async listByAgent(agentId: string): Promise<InviteRecord[]> {\n    return this.withFallback('list', (backend) => backend.listByAgent(agentId));\n  }\n\n  isExpired(invite: InviteRecord): boolean {\n    return Date.parse(invite.expiresAt) < Date.now();\n  }\n\n  isClaimed(invite: InviteRecord): boolean {\n    return Boolean(invite.claimedAt);\n  }\n}\n\n// ── Factory ───────────────────────────────────────────────────────────────────\n\nexport function createInviteStore(): InviteStore {\n  const databaseUrl = process.env.DATABASE_URL;\n  if (databaseUrl) {\n    try {\n      // eslint-disable-next-line @typescript-eslint/no-var-requires\n      const { Pool } = require('pg');\n      const pool = new Pool(createHoloMeshPostgresPoolOptions(databaseUrl));\n      const backend = new PostgresInviteStoreBackend(pool);\n      console.error('[InviteStore] PostgreSQL backend active');\n      return new InviteStore(backend, true);\n    } catch (e) {\n      console.warn('[InviteStore] DATABASE_URL set but pg failed to load:', e);\n    }\n  }\n  console.error('[InviteStore] In-memory backend (dev)');\n  return new InviteStore(new InMemoryInviteStoreBackend(), false);\n}\n","/**\n * GeoAnchorStore - shared backend for HoloLand geo anchors.\n *\n * When DATABASE_URL is present, anchors are persisted in PostgreSQL JSONB so\n * Railway replicas and restarts see the same world-locking records. Local dev\n * and tests use an in-memory backend with the same Map-like wrapper.\n */\n\nimport type { Pool } from 'pg';\nimport { createHoloMeshPostgresPoolOptions } from './postgres-pool-options';\n\nexport interface GeoAnchorSafetyEnvelope {\n  targetingUseProhibited: true;\n  humanApprovalRequiredForActuation: true;\n  permittedUses: string[];\n  prohibitedUses: string[];\n  doctrine: 'D.044';\n}\n\nexport interface StoredGeoAnchor {\n  id: string;\n  placeId?: string;\n  zoneId?: string;\n  lat: number;\n  lng: number;\n  alt?: number;\n  radius: number;\n  persistent: boolean;\n  safety: GeoAnchorSafetyEnvelope;\n  createdAt: string;\n  modifiedAt: string;\n}\n\nconst SCHEMA_SQL = `\nCREATE TABLE IF NOT EXISTS hololand_geo_anchors (\n  id          TEXT PRIMARY KEY,\n  data        JSONB NOT NULL,\n  lat         DOUBLE PRECISION NOT NULL,\n  lng         DOUBLE PRECISION NOT NULL,\n  place_id    TEXT,\n  zone_id     TEXT,\n  updated_at  TIMESTAMP WITH TIME ZONE DEFAULT NOW()\n);\nCREATE INDEX IF NOT EXISTS idx_hololand_geo_anchors_place ON hololand_geo_anchors (place_id);\nCREATE INDEX IF NOT EXISTS idx_hololand_geo_anchors_zone ON hololand_geo_anchors (zone_id);\nCREATE INDEX IF NOT EXISTS idx_hololand_geo_anchors_lat_lng ON hololand_geo_anchors (lat, lng);\nCREATE INDEX IF NOT EXISTS idx_hololand_geo_anchors_updated ON hololand_geo_anchors (updated_at);\n`;\n\nexport interface GeoAnchorStoreBackend {\n  get(anchorId: string): Promise<StoredGeoAnchor | undefined>;\n  set(anchorId: string, anchor: StoredGeoAnchor): Promise<void>;\n  delete(anchorId: string): Promise<void>;\n  getAll(): Promise<Map<string, StoredGeoAnchor>>;\n  clear(): Promise<void>;\n  close?(): Promise<void>;\n}\n\nexport class InMemoryGeoAnchorStoreBackend implements GeoAnchorStoreBackend {\n  private store = new Map<string, StoredGeoAnchor>();\n\n  async get(anchorId: string): Promise<StoredGeoAnchor | undefined> {\n    return this.store.get(anchorId);\n  }\n\n  async set(anchorId: string, anchor: StoredGeoAnchor): Promise<void> {\n    this.store.set(anchorId, anchor);\n  }\n\n  async delete(anchorId: string): Promise<void> {\n    this.store.delete(anchorId);\n  }\n\n  async getAll(): Promise<Map<string, StoredGeoAnchor>> {\n    return new Map(this.store);\n  }\n\n  async clear(): Promise<void> {\n    this.store.clear();\n  }\n}\n\nexport class PostgresGeoAnchorStoreBackend implements GeoAnchorStoreBackend {\n  private pool: Pool;\n  private ready: Promise<void>;\n\n  constructor(pool: Pool) {\n    this.pool = pool;\n    this.ready = this.ensureSchema();\n  }\n\n  private async ensureSchema(): Promise<void> {\n    const client = await this.pool.connect();\n    try {\n      await client.query(SCHEMA_SQL);\n    } finally {\n      client.release();\n    }\n  }\n\n  async get(anchorId: string): Promise<StoredGeoAnchor | undefined> {\n    await this.ready;\n    const result = await this.pool.query('SELECT data FROM hololand_geo_anchors WHERE id = $1', [\n      anchorId,\n    ]);\n    if (result.rows.length === 0) return undefined;\n    return result.rows[0].data as StoredGeoAnchor;\n  }\n\n  async set(anchorId: string, anchor: StoredGeoAnchor): Promise<void> {\n    await this.ready;\n    await this.pool.query(\n      `INSERT INTO hololand_geo_anchors (id, data, lat, lng, place_id, zone_id, updated_at)\n       VALUES ($1, $2, $3, $4, $5, $6, NOW())\n       ON CONFLICT (id) DO UPDATE SET\n         data = EXCLUDED.data,\n         lat = EXCLUDED.lat,\n         lng = EXCLUDED.lng,\n         place_id = EXCLUDED.place_id,\n         zone_id = EXCLUDED.zone_id,\n         updated_at = NOW()`,\n      [\n        anchorId,\n        JSON.stringify(anchor),\n        anchor.lat,\n        anchor.lng,\n        anchor.placeId ?? null,\n        anchor.zoneId ?? null,\n      ]\n    );\n  }\n\n  async delete(anchorId: string): Promise<void> {\n    await this.ready;\n    await this.pool.query('DELETE FROM hololand_geo_anchors WHERE id = $1', [anchorId]);\n  }\n\n  async getAll(): Promise<Map<string, StoredGeoAnchor>> {\n    await this.ready;\n    const result = await this.pool.query('SELECT id, data FROM hololand_geo_anchors');\n    const map = new Map<string, StoredGeoAnchor>();\n    for (const row of result.rows) {\n      map.set(row.id, row.data as StoredGeoAnchor);\n    }\n    return map;\n  }\n\n  async clear(): Promise<void> {\n    await this.ready;\n    await this.pool.query('DELETE FROM hololand_geo_anchors');\n  }\n\n  async close(): Promise<void> {\n    await this.pool.end();\n  }\n}\n\nexport class GeoAnchorStore {\n  readonly [Symbol.toStringTag] = 'GeoAnchorStore';\n  private backend: GeoAnchorStoreBackend;\n  private local: Map<string, StoredGeoAnchor> = new Map();\n  private usePostgres: boolean;\n\n  constructor(backend: GeoAnchorStoreBackend, usePostgres: boolean) {\n    this.backend = backend;\n    this.usePostgres = usePostgres;\n  }\n\n  get usesPostgres(): boolean {\n    return this.usePostgres;\n  }\n\n  fallbackToMemory(): void {\n    const memory = new InMemoryGeoAnchorStoreBackend();\n    for (const [anchorId, anchor] of this.local.entries()) {\n      memory.set(anchorId, anchor).catch((e) => {\n        console.error('[GeoAnchorStore] memory fallback seed failed:', e);\n      });\n    }\n    this.backend = memory;\n    this.usePostgres = false;\n  }\n\n  get size(): number {\n    return this.local.size;\n  }\n\n  get(anchorId: string): StoredGeoAnchor | undefined {\n    return this.local.get(anchorId);\n  }\n\n  async getFresh(anchorId: string): Promise<StoredGeoAnchor | undefined> {\n    let anchor: StoredGeoAnchor | undefined;\n    try {\n      anchor = await this.backend.get(anchorId);\n    } catch (e) {\n      if (this.usePostgres) {\n        console.warn('[GeoAnchorStore] PostgreSQL read failed; using in-memory backend:', e);\n        this.fallbackToMemory();\n        anchor = await this.backend.get(anchorId);\n      } else {\n        throw e;\n      }\n    }\n    if (anchor) {\n      this.local.set(anchorId, anchor);\n      return anchor;\n    }\n    const local = this.local.get(anchorId);\n    if (local?.persistent === false) return local;\n    this.local.delete(anchorId);\n    return undefined;\n  }\n\n  setLocal(anchorId: string, anchor: StoredGeoAnchor): this {\n    this.local.set(anchorId, anchor);\n    return this;\n  }\n\n  async setDurable(anchorId: string, anchor: StoredGeoAnchor): Promise<this> {\n    this.local.set(anchorId, anchor);\n    try {\n      await this.backend.set(anchorId, anchor);\n    } catch (e) {\n      if (this.usePostgres) {\n        console.warn('[GeoAnchorStore] PostgreSQL write failed; using in-memory backend:', e);\n        this.fallbackToMemory();\n        await this.backend.set(anchorId, anchor);\n      } else {\n        throw e;\n      }\n    }\n    return this;\n  }\n\n  delete(anchorId: string): boolean {\n    const had = this.local.delete(anchorId);\n    this.backend.delete(anchorId).catch((e) => {\n      console.error('[GeoAnchorStore] backend delete failed:', e);\n      if (this.usePostgres) this.fallbackToMemory();\n    });\n    return had;\n  }\n\n  clearLocal(): void {\n    this.local.clear();\n  }\n\n  clear(): void {\n    this.local.clear();\n    this.backend.clear().catch((e) => {\n      console.error('[GeoAnchorStore] backend clear failed:', e);\n      if (this.usePostgres) this.fallbackToMemory();\n    });\n  }\n\n  values(): IterableIterator<StoredGeoAnchor> {\n    return this.local.values();\n  }\n\n  keys(): IterableIterator<string> {\n    return this.local.keys();\n  }\n\n  entries(): IterableIterator<[string, StoredGeoAnchor]> {\n    return this.local.entries();\n  }\n\n  [Symbol.iterator](): IterableIterator<[string, StoredGeoAnchor]> {\n    return this.local[Symbol.iterator]();\n  }\n\n  async loadAll(): Promise<void> {\n    const ephemeral = Array.from(this.local.entries()).filter(\n      ([, anchor]) => anchor.persistent === false\n    );\n    let all: Map<string, StoredGeoAnchor>;\n    try {\n      all = await this.backend.getAll();\n    } catch (e) {\n      if (this.usePostgres) {\n        console.warn('[GeoAnchorStore] PostgreSQL load failed; using in-memory backend:', e);\n        this.fallbackToMemory();\n        all = await this.backend.getAll();\n      } else {\n        throw e;\n      }\n    }\n    for (const [id, anchor] of ephemeral) {\n      all.set(id, anchor);\n    }\n    this.local = all;\n  }\n}\n\nexport function createGeoAnchorStore(): GeoAnchorStore {\n  const databaseUrl = process.env.DATABASE_URL;\n  if (databaseUrl) {\n    try {\n      // eslint-disable-next-line @typescript-eslint/no-var-requires\n      const { Pool } = require('pg');\n      const pool = new Pool(createHoloMeshPostgresPoolOptions(databaseUrl));\n      const backend = new PostgresGeoAnchorStoreBackend(pool);\n      console.error('[GeoAnchorStore] PostgreSQL backend active (multi-instance)');\n      return new GeoAnchorStore(backend, true);\n    } catch (e) {\n      console.warn('[GeoAnchorStore] DATABASE_URL set but pg failed to load:', e);\n    }\n  }\n  console.error('[GeoAnchorStore] In-memory backend (single-instance / dev)');\n  return new GeoAnchorStore(new InMemoryGeoAnchorStoreBackend(), false);\n}\n","import * as fs from 'fs';\nimport * as path from 'path';\nimport * as crypto from 'crypto';\nimport type {\n  Team,\n  TeamMessage,\n  TeamFeedItem,\n  TeamPresenceEntry,\n  HoloMeshCloudSessionLease,\n  RegisteredAgent,\n  StoredComment,\n  StoredVote,\n  StoredBountySubmission,\n  StoredBountyMiniGame,\n  StoredBountyGovernanceProposal,\n  StoryWeaverSession,\n  SelfImprovingWorldSession,\n  KnowledgeTransaction,\n  KeyRecord,\n  ExportSession,\n} from './types';\nimport { BountyManager, KnowledgeMarketplace } from '@holoscript/framework';\nimport {\n  deserializeExportSession,\n  isExportSessionExpired,\n  serializeExportSession,\n} from './export-session';\nimport { serializeLedger, deserializeLedger } from './identity/token-ledger';\nimport { createTeamStore, type TeamStore } from './team-store';\nimport { createStateStore, type StateStoreBackend } from './state-store';\nimport { createPlayerStore, type PlayerStore, type StoredPlayer } from './player-store';\nimport { createInviteStore, type InviteStore } from './invite-store';\nimport { createGeoAnchorStore, type GeoAnchorStore } from './geo-anchor-store';\n\n// ── Persistence Config ────────────────────────────────────────────────────────\n\nexport const HOLOMESH_DATA_DIR =\n  process.env.HOLOMESH_DATA_DIR ||\n  path.join(\n    process.env.HOLOSCRIPT_CACHE_DIR || path.join(require('os').homedir(), '.holoscript'),\n    'holomesh'\n  );\n\n// ── Atomic Writes ─────────────────────────────────────────────────────────────\n\n/** Atomic JSON write: temp file → rename */\nexport function atomicWriteJSON(filePath: string, data: unknown): void {\n  try {\n    const dir = path.dirname(filePath);\n    if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });\n    const tmp = filePath + '.tmp';\n    fs.writeFileSync(tmp, JSON.stringify(data, null, 2), 'utf-8');\n    fs.renameSync(tmp, filePath);\n  } catch (e: unknown) {\n    console.warn('[HoloMesh] persist failed:', e instanceof Error ? e.message : String(e));\n  }\n}\n\n/** Read JSON file, return null if missing/corrupted */\nexport function readJSON(filePath: string): any {\n  try {\n    if (!fs.existsSync(filePath)) return null;\n    return JSON.parse(fs.readFileSync(filePath, 'utf-8'));\n  } catch {\n    return null;\n  }\n}\n\n// ── Shared Global Stores ──────────────────────────────────────────────────────\n\n// Identity\nexport const agentKeyStore: Map<string, RegisteredAgent> = new Map(); // apiKey → agent\nexport const walletToAgent: Map<string, RegisteredAgent> = new Map(); // walletAddress (lowercase) → agent\nexport const paidAccessStore: Set<string> = new Set(); // \"agentId:entryId\" → true\n\n// Teams\nexport const teamStore: TeamStore = createTeamStore(); // teamId → Team\n\n// Players (HoloLand users — Postgres-backed so agents never see an empty list)\nexport const playerStore: PlayerStore = createPlayerStore(); // playerId → StoredPlayer\n\n// Agent-first invite tokens — claimed by humans to create their player account\nexport const inviteStore: InviteStore = createInviteStore(); // token → InviteRecord\nexport const geoAnchorStore: GeoAnchorStore = createGeoAnchorStore(); // anchorId -> StoredGeoAnchor\nexport const stateStore: StateStoreBackend = createStateStore(); // audit/defense/dispatch backend\nexport const teamCloudSessionStore: Map<string, Map<string, HoloMeshCloudSessionLease>> =\n  new Map(); // teamId -> (leaseId -> cloud session lease)\nexport const teamPresenceStore: Map<string, Map<string, TeamPresenceEntry>> = new Map(); // teamId → (agentId → presence)\nexport const teamMessageStore: Map<string, TeamMessage[]> = new Map(); // teamId → messages\n/** Public team feed (hologram publishes, etc.) — poster identity is server-authoritative */\nexport const teamFeedStore: Map<string, TeamFeedItem[]> = new Map();\nexport const agentTeamIndex: Map<string, string[]> = new Map(); // agentId → teamIds[]\n\nconst MAX_TEAM_FEED_ITEMS = 200;\n\n/** HoloDoor — per-team merged policy (owner PATCH) + telemetry ring buffer */\nexport const holoDoorPolicyByTeam: Map<string, Record<string, unknown>> = new Map();\nexport const holoDoorEventsByTeam: Map<string, Record<string, unknown>[]> = new Map();\n\n/**\n * CAEL Audit Store — per-agent CAEL trace ring buffer (Phase 0 in-memory).\n * Spec: research/2026-04-25_fleet-adversarial-harness-paper-21.md +\n *       research/2026-04-25_fleet-empirical-composability-w-gold-189.md.\n * Closes gap-build task_1777090894117_d2jx (CAEL audit GET endpoint).\n *\n * Each entry is one CAEL record produced by an attacker-loop / target-brain /\n * composability-test capture. Records have shape per spec §5.\n *\n * Phase 0 limitations (filed as follow-up at task_1777093147560_pawd):\n * - In-memory only; lost on server restart. Persistence to JSONL on\n *   HOLOMESH_DATA_DIR is the Phase 1 hardening pass.\n * - Per-agent ring buffer caps at 10,000 records (drops oldest).\n * - No pagination cursor; only since/until/limit windowing.\n *\n * Auth model: write requires the caller to BE the agent (bearer matches\n * handle); read requires any authenticated agent in the same team.\n */\nexport interface CaelAuditRecord {\n  tick_iso: string;\n  layer_hashes: string[]; // 7 elements per W.GOLD.189 Layer 1+2 framing\n  operation: string;\n  prev_hash: string | null;\n  fnv1a_chain: string;\n  version_vector_fingerprint: string;\n  // Optional: attacker/composability-test specific metadata\n  attack_class?: string;\n  defense_state?: string;\n  trial?: number;\n  brain_class?: string;\n  // W.110 trust epoch — set by post-W.107.b runners (HS commit 435928977).\n  // Records lacking this field are pre-gate (mw02 hallucination cohort) and\n  // are implicitly untrusted. Production counts (Paper 17/19/21/25 corpus,\n  // fleet-status drift detector) MUST filter via isCaelRecordTrusted().\n  // Canonical source: ai-ecosystem/scripts/lib/trust-epoch.mjs.\n  trust_epoch?: 'post-w107';\n  // Server-stamped on append\n  received_at: string;\n}\n\n/** Trust-epoch tag set by post-W.107.b runners. Pre-gate records lack this. */\nexport const CAEL_TRUST_EPOCH_POSTGATE = 'post-w107' as const;\n\n/**\n * Strict trust-epoch check — mirrors `isTrusted()` in\n * `ai-ecosystem/scripts/lib/trust-epoch.mjs`. Returns true iff the record\n * carries the explicit post-W.107.b tag. Required filter for any caller\n * that draws scientific or operational conclusions from CAEL records.\n *\n * The two fleet-status counter loops in `routes/core-routes.ts` (the team\n * fleet-status endpoint at ~line 681 and the composite /fleet/status at\n * ~line 901) MUST gate on this — otherwise pre-W.107 hallucinations\n * contaminate metrics and trigger drift-detection false positives.\n */\nexport function isCaelRecordTrusted(record: CaelAuditRecord): boolean {\n  return record.trust_epoch === CAEL_TRUST_EPOCH_POSTGATE;\n}\n\nexport const agentAuditStore: Map<string, CaelAuditRecord[]> = new Map(); // handle → records\nconst MAX_CAEL_RECORDS_PER_AGENT = 10_000;\n\n// Phase 1 persistence: append every record to JSONL on disk.\n// Path: <HOLOMESH_DATA_DIR>/audit/<handle>.jsonl\n// On startup, loadCaelAuditFromDisk() rehydrates the in-memory store.\nconst CAEL_AUDIT_DIR = path.join(HOLOMESH_DATA_DIR, 'audit');\n\nfunction caelAuditPath(handle: string): string {\n  // Sanitize handle for filesystem (no ../, no path separators).\n  const safe = handle.replace(/[^a-zA-Z0-9._-]/g, '_');\n  return path.join(CAEL_AUDIT_DIR, `${safe}.jsonl`);\n}\n\nfunction persistCaelAuditRecord(handle: string, record: CaelAuditRecord): void {\n  if (\n    process.env.NODE_ENV === 'test' &&\n    process.env.HOLOMESH_TEST_DISABLE_CAEL_AUDIT_PERSISTENCE === '1'\n  ) {\n    return;\n  }\n\n  try {\n    if (!fs.existsSync(CAEL_AUDIT_DIR)) {\n      fs.mkdirSync(CAEL_AUDIT_DIR, { recursive: true });\n    }\n    fs.appendFileSync(caelAuditPath(handle), `${JSON.stringify(record)}\\n`, 'utf8');\n  } catch (err) {\n    // eslint-disable-next-line no-console\n    console.warn(`[state] persistCaelAuditRecord failed for ${handle}: ${(err as Error).message}`);\n  }\n  // PostgreSQL backend: fire-and-forget append\n  stateStore.append('audit', handle, record).catch((e) => {\n    console.warn(`[state] stateStore audit append failed for ${handle}:`, e);\n  });\n}\n\n/**\n * Rehydrate in-memory CAEL audit store from on-disk JSONL files.\n * Called once at server startup. Idempotent — safe to call multiple times.\n */\nexport function loadCaelAuditFromDisk(): void {\n  if (!fs.existsSync(CAEL_AUDIT_DIR)) return;\n  const files = fs.readdirSync(CAEL_AUDIT_DIR).filter((f) => f.endsWith('.jsonl'));\n  for (const file of files) {\n    const handle = file.replace(/\\.jsonl$/, '');\n    const lines = fs\n      .readFileSync(path.join(CAEL_AUDIT_DIR, file), 'utf8')\n      .split('\\n')\n      .filter((l) => l.length > 0);\n    const records: CaelAuditRecord[] = [];\n    for (const line of lines) {\n      try {\n        records.push(JSON.parse(line));\n      } catch {\n        // Corrupt line — skip. Honest: a half-flushed record is rare.\n      }\n    }\n    // Honor the in-memory ring buffer cap on rehydrate.\n    const trimmed =\n      records.length > MAX_CAEL_RECORDS_PER_AGENT\n        ? records.slice(-MAX_CAEL_RECORDS_PER_AGENT)\n        : records;\n    agentAuditStore.set(handle, trimmed);\n  }\n}\n\n/**\n * Agent Defense State Store — per-agent fleet-adversarial defense configuration.\n * Closes gap-build task_1777090894117_8bav (defense-state PATCH endpoint).\n * Spec: research/2026-04-25_fleet-adversarial-harness-paper-21.md §3.\n *\n * Allows the adversarial harness to toggle each target's defense state\n * between {none, decay-on-anomaly, cross-vouching-detector, replay-audit,\n * canary-probing, all-three}. Phase 1 of the harness (10-cell smoke) and\n * Phase 2 (300/450 cell full eval) require this for the per-cell\n * defense_state matrix dimension.\n *\n * Phase 1 hardening landed (this commit): persistence to disk via\n * <HOLOMESH_DATA_DIR>/defense/<handle>.json.\n *\n * Remaining limitations (Phase 1.5, filed at task_1777093147560_pawd):\n * - Auth is \"any authenticated caller\". Phase 1.5 will require caller's\n *   brain class (via /me + agents.json lookup) to be security-auditor.\n * - Defense state is informational — doesn't actually toggle behavior on\n *   the target brain (target brains read this on next tick).\n */\nexport type DefenseState =\n  | 'none'\n  | 'decay-on-anomaly'\n  | 'cross-vouching-detector'\n  | 'replay-audit'\n  | 'canary-probing'\n  | 'all-three';\n\nexport const VALID_DEFENSE_STATES: readonly DefenseState[] = [\n  'none',\n  'decay-on-anomaly',\n  'cross-vouching-detector',\n  'replay-audit',\n  'canary-probing',\n  'all-three',\n];\n\nexport interface AgentDefenseConfig {\n  state: DefenseState;\n  expiresAt: string | null; // ISO; null = no expiry\n  setBy: string; // agentId of caller who set this\n  setAt: string; // ISO server-stamp\n}\n\nexport const agentDefenseStore: Map<string, AgentDefenseConfig> = new Map(); // handle → config\n\n// Phase 1 persistence: write defense state to JSON on disk.\nconst DEFENSE_DIR = path.join(HOLOMESH_DATA_DIR, 'defense');\n\nfunction defensePath(handle: string): string {\n  const safe = handle.replace(/[^a-zA-Z0-9._-]/g, '_');\n  return path.join(DEFENSE_DIR, `${safe}.json`);\n}\n\nfunction persistAgentDefense(handle: string, config: AgentDefenseConfig): void {\n  try {\n    if (!fs.existsSync(DEFENSE_DIR)) {\n      fs.mkdirSync(DEFENSE_DIR, { recursive: true });\n    }\n    fs.writeFileSync(defensePath(handle), JSON.stringify(config, null, 2), 'utf8');\n  } catch (err) {\n    // eslint-disable-next-line no-console\n    console.warn(`[state] persistAgentDefense failed for ${handle}: ${(err as Error).message}`);\n  }\n  // PostgreSQL backend: fire-and-forget overwrite\n  stateStore.set('defense', handle, config).catch((e) => {\n    console.warn(`[state] stateStore defense set failed for ${handle}:`, e);\n  });\n}\n\n/**\n * Rehydrate in-memory defense store from on-disk JSON files.\n * Called once at server startup. Idempotent.\n */\nexport function loadAgentDefenseFromDisk(): void {\n  if (!fs.existsSync(DEFENSE_DIR)) return;\n  const files = fs.readdirSync(DEFENSE_DIR).filter((f) => f.endsWith('.json'));\n  for (const file of files) {\n    const handle = file.replace(/\\.json$/, '');\n    try {\n      const config = JSON.parse(\n        fs.readFileSync(path.join(DEFENSE_DIR, file), 'utf8')\n      ) as AgentDefenseConfig;\n      agentDefenseStore.set(handle, config);\n    } catch {\n      // Corrupt file — skip.\n    }\n  }\n}\n\nexport function setAgentDefense(\n  handle: string,\n  state: DefenseState,\n  expiresAt: string | null,\n  setBy: string\n): AgentDefenseConfig {\n  const config: AgentDefenseConfig = {\n    state,\n    expiresAt,\n    setBy,\n    setAt: new Date().toISOString(),\n  };\n  agentDefenseStore.set(handle, config);\n  // Phase 1 persistence: best-effort write to JSON.\n  persistAgentDefense(handle, config);\n  return config;\n}\n\nexport function getAgentDefense(handle: string): AgentDefenseConfig | null {\n  const config = agentDefenseStore.get(handle);\n  if (!config) return null;\n  // Honor expiry — if expired, return 'none' implicitly without touching store\n  if (config.expiresAt && Date.parse(config.expiresAt) < Date.now()) {\n    return null;\n  }\n  return config;\n}\n\nexport function isValidDefenseState(value: unknown): value is DefenseState {\n  return typeof value === 'string' && (VALID_DEFENSE_STATES as readonly string[]).includes(value);\n}\n\n/**\n * Adversarial Dispatch Queue — pull-based trigger for headless attacker\n * brains running on Vast.ai boxes. Closes the last gap at task_..._pawd:\n * how does run-harness.mjs (the coordinator) trigger an attacker loop on\n * a remote worker?\n *\n * Design (Phase 1):\n *   - Coordinator POSTs to /api/holomesh/agent/:handle/dispatch with the\n *     trial cell parameters (attack_class, target_handle, duration_ms,\n *     defense_state, trial). Server enqueues to agentDispatchQueue.\n *   - Worker brain polls GET /api/holomesh/agent/:handle/dispatch (auth:\n *     handle owner only). Server returns pending dispatches AND drains\n *     them from the queue (one-shot delivery).\n *   - Worker invokes its attacker loop with the cell parameters.\n *   - Worker writes CAEL records via existing POST /audit endpoint.\n *\n * Auth:\n *   - POST: founder or HOLOMESH_SECURITY_AUDITOR_HANDLES (admin-class).\n *   - GET: handle owner only (caller.name === pathHandle) or founder.\n *\n * Per-handle ring buffer: cap 1000 entries; drop oldest. Persists to\n * <HOLOMESH_DATA_DIR>/dispatch/<handle>.jsonl.\n */\nexport const VALID_ATTACK_CLASSES = [\n  'whitewasher',\n  'sybil-cross-vouch',\n  'slow-poisoner',\n  'reputation-squatter',\n  'cross-brain-hijack',\n] as const;\n\nexport type AttackClass = (typeof VALID_ATTACK_CLASSES)[number];\n\nexport interface DispatchEntry {\n  cell_id: string; // run-harness assigned, e.g. \"phase-2-A-23\"\n  attack_class: AttackClass;\n  target_handle: string;\n  duration_ms: number;\n  trial: number;\n  defense_state: DefenseState;\n  dispatched_at: string;\n  dispatched_by: string; // caller agentId\n  // Server-stamped on consume\n  consumed_at?: string;\n}\n\nexport const agentDispatchQueue: Map<string, DispatchEntry[]> = new Map(); // handle → pending entries\nconst MAX_DISPATCH_QUEUE_PER_AGENT = 1000;\nconst DISPATCH_DIR = path.join(HOLOMESH_DATA_DIR, 'dispatch');\n\nfunction dispatchPath(handle: string): string {\n  const safe = handle.replace(/[^a-zA-Z0-9._-]/g, '_');\n  return path.join(DISPATCH_DIR, `${safe}.jsonl`);\n}\n\nfunction persistDispatch(handle: string, entry: DispatchEntry): void {\n  try {\n    if (!fs.existsSync(DISPATCH_DIR)) {\n      fs.mkdirSync(DISPATCH_DIR, { recursive: true });\n    }\n    fs.appendFileSync(dispatchPath(handle), `${JSON.stringify(entry)}\\n`, 'utf8');\n  } catch (err) {\n    // eslint-disable-next-line no-console\n    console.warn(`[state] persistDispatch failed for ${handle}: ${(err as Error).message}`);\n  }\n  // PostgreSQL backend: fire-and-forget append\n  stateStore.append('dispatch', handle, entry).catch((e) => {\n    console.warn(`[state] stateStore dispatch append failed for ${handle}:`, e);\n  });\n}\n\nexport function isValidAttackClass(value: unknown): value is AttackClass {\n  return typeof value === 'string' && (VALID_ATTACK_CLASSES as readonly string[]).includes(value);\n}\n\nexport function enqueueDispatch(handle: string, entry: DispatchEntry): DispatchEntry {\n  const existing = agentDispatchQueue.get(handle) ?? [];\n  existing.push(entry);\n  if (existing.length > MAX_DISPATCH_QUEUE_PER_AGENT) {\n    existing.shift();\n  }\n  agentDispatchQueue.set(handle, existing);\n  persistDispatch(handle, entry);\n  return entry;\n}\n\n/**\n * Drain pending dispatches for a handle. Returns and removes all\n * pending entries (one-shot delivery — the worker is responsible for\n * executing or re-enqueueing if it can't process them now).\n */\nexport function consumeDispatches(handle: string): DispatchEntry[] {\n  const pending = agentDispatchQueue.get(handle) ?? [];\n  if (pending.length === 0) return [];\n  const consumedAt = new Date().toISOString();\n  const drained = pending.map((e) => ({ ...e, consumed_at: consumedAt }));\n  agentDispatchQueue.set(handle, []);\n  // Persist consumption events as a sidecar (audit trail).\n  for (const entry of drained) {\n    persistDispatch(handle, entry);\n  }\n  return drained;\n}\n\n/**\n * Read pending dispatches without draining (for diagnostic / observability).\n */\nexport function peekDispatches(handle: string): DispatchEntry[] {\n  return [...(agentDispatchQueue.get(handle) ?? [])];\n}\n\nexport function appendCaelAuditRecord(handle: string, record: CaelAuditRecord): void {\n  const existing = agentAuditStore.get(handle) ?? [];\n  existing.push(record);\n  if (existing.length > MAX_CAEL_RECORDS_PER_AGENT) {\n    existing.shift(); // ring buffer: drop oldest\n  }\n  agentAuditStore.set(handle, existing);\n  // Phase 1 persistence: best-effort append to JSONL.\n  persistCaelAuditRecord(handle, record);\n}\n\nexport function queryCaelAuditRecords(\n  handle: string,\n  filter: {\n    since?: string;\n    until?: string;\n    limit?: number;\n    operation?: string;\n    /** W.110: when true, drop records lacking `trust_epoch === 'post-w107'`.\n     *  Default `false` preserves the historical full-record behavior so the\n     *  forensic audit endpoint keeps returning everything. Production count\n     *  callers (fleet-status, paper-corpus consumers) should pass `true`. */\n    trustedOnly?: boolean;\n  } = {}\n): CaelAuditRecord[] {\n  const records = agentAuditStore.get(handle) ?? [];\n  let out = records;\n  if (filter.trustedOnly) {\n    out = out.filter(isCaelRecordTrusted);\n  }\n  if (filter.since) {\n    const sinceMs = Date.parse(filter.since);\n    if (Number.isFinite(sinceMs)) {\n      out = out.filter((r) => Date.parse(r.tick_iso) >= sinceMs);\n    }\n  }\n  if (filter.until) {\n    const untilMs = Date.parse(filter.until);\n    if (Number.isFinite(untilMs)) {\n      out = out.filter((r) => Date.parse(r.tick_iso) <= untilMs);\n    }\n  }\n  if (filter.operation) {\n    out = out.filter((r) => r.operation === filter.operation);\n  }\n  const limit = filter.limit ?? 1000;\n  if (out.length > limit) out = out.slice(out.length - limit); // most recent\n  return out;\n}\n\n// Social & Discussion\nexport const commentStore: Map<string, StoredComment[]> = new Map(); // entryId → comments\nexport const voteStore: Map<string, StoredVote[]> = new Map(); // targetId → votes\nexport const transactionLedger: KnowledgeTransaction[] = [];\nexport const storyWeaverStore: Map<string, StoryWeaverSession> = new Map(); // sessionId -> story session\nexport const selfImprovingWorldStore: Map<string, SelfImprovingWorldSession> = new Map(); // worldId -> world evolution session\n\n// Bounties\nexport const bountySubmissionStore: Map<string, StoredBountySubmission[]> = new Map(); // bountyId -> submissions\nexport const bountyMiniGameStore: Map<string, StoredBountyMiniGame[]> = new Map(); // teamId -> mini-games\nexport const bountyGovernanceStore: Map<string, StoredBountyGovernanceProposal> = new Map(); // bountyId -> proposal\n\n// Auth\nexport const challengeStore: Map<string, { walletAddress: string; expiresAt: number }> = new Map();\n\n// Key Registry — unified identity anchor\nexport const keyRegistry: Map<string, KeyRecord> = new Map(); // token → KeyRecord\n\n// Admin Ops State (P.009.01 — ephemeral; audit trail is the durable record)\nexport interface ScalingOverride {\n  serviceId: string;\n  replicas: number;\n  reason?: string;\n  setAt: string;\n  setBy: string;\n}\nexport interface FailoverState {\n  serviceId: string;\n  primaryBackend: string;\n  reason?: string;\n  setAt: string;\n  setBy: string;\n}\nexport const scalingOverrideStore: Map<string, ScalingOverride> = new Map(); // serviceId → override\nexport const failoverStateStore: Map<string, FailoverState> = new Map(); // serviceId → state\n\n// Tier2 Self-Custody Export Sessions (V3 foundation)\nexport const exportSessionStore: Map<string, ExportSession> = new Map(); // sessionId → export session\n\n// ── Persistence Logic ─────────────────────────────────────────────────────────\n\nconst TEAM_STORE_PATH = path.join(HOLOMESH_DATA_DIR, 'teams.json');\nconst AGENT_STORE_PATH = path.join(HOLOMESH_DATA_DIR, 'agents.json');\nconst SOCIAL_STORE_PATH = path.join(HOLOMESH_DATA_DIR, 'social.json');\nconst KEY_REGISTRY_PATH = path.join(HOLOMESH_DATA_DIR, 'keys.json');\nconst HOLODOOR_STORE_PATH = path.join(HOLOMESH_DATA_DIR, 'holodoor-store.json');\nconst EXPORT_SESSION_STORE_PATH = path.join(HOLOMESH_DATA_DIR, 'export-sessions.json');\nconst TOKEN_LEDGER_PATH = path.join(HOLOMESH_DATA_DIR, 'token-ledger.json');\n\nexport function persistHoloDoorStore(): void {\n  atomicWriteJSON(HOLODOOR_STORE_PATH, {\n    version: 1,\n    policies: Object.fromEntries(holoDoorPolicyByTeam),\n    events: Object.fromEntries(holoDoorEventsByTeam),\n    savedAt: new Date().toISOString(),\n  });\n}\n\n/** Refresh a single team from the shared backend (PostgreSQL) into local cache.\n *  Call at the start of mutation handlers so cross-instance writes are visible.\n */\nexport async function reloadTeam(teamId: string): Promise<void> {\n  await (teamStore as TeamStore).getFresh(teamId);\n}\n\nexport function persistTeamStore(): void {\n  // Pattern Gamma write-path fix (2026-05-04): when Postgres is active,\n  // route handlers mutate cached Team objects in place (e.g. team.taskBoard.push)\n  // and rely on this function to persist. Early-returning was a silent no-op —\n  // mutations never reached Postgres, so other Railway replicas saw stale state\n  // and writes appeared to \"vanish\" minutes later when load-balancer routing\n  // moved to a different replica. teamStore.set() fires the write-through.\n  if ((teamStore as TeamStore).usesPostgres) {\n    for (const team of teamStore.values()) {\n      teamStore.set(team.id, team);\n    }\n    return;\n  }\n\n  const teams = Array.from(teamStore.values()).map((t) => ({\n    ...t,\n    presence: teamPresenceStore.get(t.id) ? Array.from(teamPresenceStore.get(t.id)!.values()) : [],\n    messages: teamMessageStore.get(t.id) || [],\n    feed: teamFeedStore.get(t.id) || [],\n    knowledgeMarketplace:\n      (t as any).knowledgeMarketplace?.toJSON?.() || (t as any).knowledgeMarketplace,\n    bounties: (t as any).bounties?.toJSON?.() || t.bounties,\n  }));\n\n  atomicWriteJSON(TEAM_STORE_PATH, {\n    version: 4,\n    teams,\n    savedAt: new Date().toISOString(),\n  });\n}\n\n/**\n * Durably persist a single team and AWAIT the write (W.128 fix, 2026-06-16).\n *\n * `persistTeamStore()` routes through `teamStore.set()`, whose Postgres\n * write-through is FIRE-AND-FORGET (team-store.ts:190). Membership mutations\n * (join / set_role / remove) returned 200 *before* the row committed, so a\n * fast follow-up request that `reloadTeam()`s (e.g. the AgentRunner heartbeat\n * → /presence immediately after a join) read stale Postgres and 403'd\n * \"Not a member\" — the seat appeared to never join (W.128 / Pattern Gamma).\n *\n * Membership handlers must AWAIT this instead of calling the fire-and-forget\n * `persistTeamStore()`, so the row is durable before the response. On the\n * in-memory backend (single-instance dev) there is no race, so we fall back to\n * the synchronous file write.\n */\nexport async function persistTeamDurable(teamId: string): Promise<void> {\n  if (teamStore.usesPostgres) {\n    await teamStore.persist(teamId);\n  } else {\n    persistTeamStore();\n  }\n}\n\nexport function persistAgentStore(): void {\n  atomicWriteJSON(AGENT_STORE_PATH, {\n    version: 1,\n    agents: Array.from(agentKeyStore.values()),\n    savedAt: new Date().toISOString(),\n  });\n}\n\n/**\n * keys.json is append-only — read existing records, merge new ones, write.\n * Old keys are preserved for audit trail. Rotated keys are never truly deleted\n * from the file (only from the in-memory map).\n */\nexport function persistKeyRegistry(): void {\n  const existing = readJSON(KEY_REGISTRY_PATH);\n  const existingRecords: KeyRecord[] = existing?.keys || [];\n  const merged = new Map<string, KeyRecord>();\n  for (const r of existingRecords) merged.set(r.key, r);\n  for (const r of keyRegistry.values()) merged.set(r.key, r);\n  atomicWriteJSON(KEY_REGISTRY_PATH, {\n    version: 1,\n    keys: Array.from(merged.values()),\n    savedAt: new Date().toISOString(),\n  });\n}\n\nexport function persistSocialStore(): void {\n  atomicWriteJSON(SOCIAL_STORE_PATH, {\n    version: 1,\n    comments: Array.from(commentStore.entries()),\n    votes: Array.from(voteStore.entries()),\n    paidAccess: Array.from(paidAccessStore),\n    transactions: transactionLedger,\n    storyWeaver: Array.from(storyWeaverStore.entries()),\n    selfImprovingWorlds: Array.from(selfImprovingWorldStore.entries()),\n    bountySubmissions: Array.from(bountySubmissionStore.entries()),\n    bountyMiniGames: Array.from(bountyMiniGameStore.entries()),\n    bountyGovernance: Array.from(bountyGovernanceStore.entries()),\n    savedAt: new Date().toISOString(),\n  });\n}\n\nexport function persistExportSessionStore(): void {\n  const now = Date.now();\n  const sessions = Array.from(exportSessionStore.values())\n    .filter((s) => !isExportSessionExpired(s, now))\n    .map((s) => serializeExportSession(s));\n\n  atomicWriteJSON(EXPORT_SESSION_STORE_PATH, {\n    version: 1,\n    sessions,\n    savedAt: new Date().toISOString(),\n  });\n}\n\nexport function persistTokenLedger(): void {\n  atomicWriteJSON(TOKEN_LEDGER_PATH, serializeLedger());\n}\n\n// ── Initialization ────────────────────────────────────────────────────────────\n\n/**\n * Seed the key registry from env vars on first boot (no keys.json yet).\n * All env key names are treated as founder keys and mapped to a single\n * permanent founder wallet + agent ID. Persists immediately so keys.json\n * exists for subsequent restarts.\n */\nfunction _seedFounderKeysFromEnv(): void {\n  const candidates = [\n    process.env.HOLOSCRIPT_API_KEY,\n    process.env.HOLOSCRIPT_API_KEY,\n    process.env.HOLOMESH_API_KEY,\n    process.env.COPILOT_HOLOMESH_KEY,\n    process.env.GEMINI_HOLOMESH_KEY,\n  ].filter((k): k is string => Boolean(k && k.trim()));\n\n  if (candidates.length === 0) return;\n\n  const FOUNDER_WALLET =\n    process.env.HOLOSCRIPT_FOUNDER_WALLET || '0x0000000000000000000000000000000000000001';\n\n  for (const key of candidates) {\n    const record: KeyRecord = {\n      key,\n      walletAddress: FOUNDER_WALLET,\n      agentId: 'agent_founder',\n      agentName: 'Founder',\n      scopes: ['*'],\n      createdAt: new Date().toISOString(),\n      rotationCount: 0,\n      lastRotatedAt: null,\n      isFounder: true,\n    };\n    keyRegistry.set(key, record);\n  }\n\n  console.info(\n    `[KeyRegistry] First boot: seeded ${candidates.length} founder key(s) from env vars`\n  );\n  persistKeyRegistry();\n}\n\nexport async function initStores(): Promise<void> {\n  // Load Key Registry (must come first — auth depends on it)\n  const keyData = readJSON(KEY_REGISTRY_PATH);\n  if (keyData?.keys && Array.isArray(keyData.keys) && keyData.keys.length > 0) {\n    for (const r of keyData.keys as KeyRecord[]) {\n      keyRegistry.set(r.key, r);\n    }\n    console.info(`[KeyRegistry] Loaded ${keyRegistry.size} key record(s)`);\n  } else {\n    // First boot: auto-seed from env vars so the server can start immediately\n    _seedFounderKeysFromEnv();\n  }\n\n  // Load Agents\n  const agentData = readJSON(AGENT_STORE_PATH);\n  if (agentData?.agents) {\n    for (const a of agentData.agents) {\n      agentKeyStore.set(a.apiKey, a);\n      walletToAgent.set((a.walletAddress || '').toLowerCase(), a);\n    }\n  }\n\n  // Load Social\n  const socialData = readJSON(SOCIAL_STORE_PATH);\n  if (socialData) {\n    if (socialData.comments) {\n      for (const [id, list] of socialData.comments) commentStore.set(id, list);\n    }\n    if (socialData.votes) {\n      for (const [id, list] of socialData.votes) voteStore.set(id, list);\n    }\n    if (socialData.paidAccess) {\n      for (const key of socialData.paidAccess) paidAccessStore.add(key);\n    }\n    if (socialData.transactions) {\n      transactionLedger.push(...socialData.transactions);\n    }\n    if (socialData.storyWeaver) {\n      for (const [id, session] of socialData.storyWeaver) storyWeaverStore.set(id, session);\n    }\n    if (socialData.selfImprovingWorlds) {\n      for (const [id, session] of socialData.selfImprovingWorlds)\n        selfImprovingWorldStore.set(id, session);\n    }\n    if (socialData.bountySubmissions) {\n      for (const [id, list] of socialData.bountySubmissions) bountySubmissionStore.set(id, list);\n    }\n    if (socialData.bountyMiniGames) {\n      for (const [id, list] of socialData.bountyMiniGames) bountyMiniGameStore.set(id, list);\n    }\n    if (socialData.bountyGovernance) {\n      for (const [id, proposal] of socialData.bountyGovernance)\n        bountyGovernanceStore.set(id, proposal);\n    }\n  }\n\n  // Load Teams\n  // Priority: PostgreSQL (multi-instance) → JSON file (single-instance / migration)\n  let teamsLoaded = false;\n  if (process.env.DATABASE_URL) {\n    try {\n      await (teamStore as TeamStore).loadAll();\n      teamsLoaded = true;\n      console.log('[loadAllStores] teams loaded from PostgreSQL');\n      // Reconstruct presence, messages, feed from loaded teams\n      for (const t of teamStore.values()) {\n        const raw = t as any;\n        if (raw.presence) {\n          const pMap = new Map();\n          for (const p of raw.presence) pMap.set(p.agentId, p);\n          teamPresenceStore.set(t.id, pMap);\n        }\n        if (raw.messages) {\n          teamMessageStore.set(t.id, raw.messages);\n        }\n        const feedRaw = raw.feed as TeamFeedItem[] | undefined;\n        if (feedRaw && Array.isArray(feedRaw)) {\n          teamFeedStore.set(t.id, feedRaw.slice(-MAX_TEAM_FEED_ITEMS));\n        }\n        if (t.members) {\n          for (const m of t.members) {\n            const teams = agentTeamIndex.get(m.agentId) || [];\n            if (!teams.includes(t.id)) {\n              teams.push(t.id);\n              agentTeamIndex.set(m.agentId, teams);\n            }\n          }\n        }\n      }\n    } catch (e) {\n      console.warn('[loadAllStores] PostgreSQL team load failed, falling back to file:', e);\n      (teamStore as TeamStore).fallbackToMemory();\n      console.warn('[loadAllStores] PostgreSQL team backend disabled for this process');\n    }\n  }\n\n  if (!teamsLoaded) {\n    const teamData = readJSON(TEAM_STORE_PATH);\n    if (teamData?.teams) {\n      for (const t of teamData.teams) {\n        // Reconstitute classes\n        if (t.knowledgeMarketplace) {\n          try {\n            t.knowledgeMarketplace = new KnowledgeMarketplace(t.knowledgeMarketplace);\n          } catch {\n            /* ignore */\n          }\n        }\n        if (t.bounties) {\n          try {\n            t.bounties = new BountyManager(t.bounties);\n          } catch {\n            /* ignore */\n          }\n        }\n        teamStore.set(t.id, t);\n\n        if (t.presence) {\n          const pMap = new Map();\n          for (const p of t.presence) pMap.set(p.agentId, p);\n          teamPresenceStore.set(t.id, pMap);\n        }\n        if (t.messages) {\n          teamMessageStore.set(t.id, t.messages);\n        }\n        const feedRaw = (t as { feed?: TeamFeedItem[] }).feed;\n        if (feedRaw && Array.isArray(feedRaw)) {\n          teamFeedStore.set(t.id, feedRaw.slice(-MAX_TEAM_FEED_ITEMS));\n        }\n\n        // Re-index members\n        if (t.members) {\n          for (const m of t.members) {\n            const teams = agentTeamIndex.get(m.agentId) || [];\n            if (!teams.includes(t.id)) {\n              teams.push(t.id);\n              agentTeamIndex.set(m.agentId, teams);\n            }\n          }\n        }\n      }\n    }\n  }\n\n  // Load Players — Postgres first, then seed founder if empty\n  if (process.env.DATABASE_URL) {\n    try {\n      await playerStore.loadAll();\n      const source = playerStore.usesPostgres ? 'PostgreSQL' : 'memory fallback';\n      console.log(`[loadAllStores] players loaded from ${source}: ${playerStore.size}`);\n    } catch (e) {\n      console.warn('[loadAllStores] PostgreSQL player load failed:', e);\n    }\n  }\n  // Seed the founder as a player on first boot (or after a wipe).\n  // Agents querying hololand_list_players will always see at least one real user.\n  if (playerStore.size === 0) {\n    const founderWallet =\n      process.env.HOLOSCRIPT_FOUNDER_WALLET || '0x0000000000000000000000000000000000000001';\n    const founderPlayer: StoredPlayer = {\n      id: 'player_founder',\n      name: 'Joseph',\n      walletAddress: founderWallet,\n      status: 'active',\n      createdAt: new Date().toISOString(),\n      modifiedAt: new Date().toISOString(),\n    };\n    playerStore.set('player_founder', founderPlayer);\n    console.info('[PlayerStore] Seeded founder player (player_founder → Joseph)');\n  }\n\n  const holoDoorData = readJSON(HOLODOOR_STORE_PATH);\n  if (holoDoorData?.policies && typeof holoDoorData.policies === 'object') {\n    for (const [tid, pol] of Object.entries(holoDoorData.policies as Record<string, unknown>)) {\n      holoDoorPolicyByTeam.set(tid, pol as Record<string, unknown>);\n    }\n  }\n  if (holoDoorData?.events && typeof holoDoorData.events === 'object') {\n    for (const [tid, evs] of Object.entries(holoDoorData.events as Record<string, unknown[]>)) {\n      const list = Array.isArray(evs) ? (evs as Record<string, unknown>[]) : [];\n      holoDoorEventsByTeam.set(tid, list);\n    }\n  }\n\n  const exportSessionData = readJSON(EXPORT_SESSION_STORE_PATH);\n  if (exportSessionData?.sessions && Array.isArray(exportSessionData.sessions)) {\n    const now = Date.now();\n    for (const raw of exportSessionData.sessions) {\n      const session = deserializeExportSession(raw);\n      if (!session) continue;\n      if (isExportSessionExpired(session, now)) continue;\n      exportSessionStore.set(session.sessionId, session);\n    }\n  }\n\n  // Load Token Ledger (Phase 5 — Tier 2 balance)\n  const tokenLedgerData = readJSON(TOKEN_LEDGER_PATH);\n  if (tokenLedgerData?.entries) {\n    try {\n      deserializeLedger(tokenLedgerData);\n      console.info(\n        `[TokenLedger] Loaded balances for ${Object.keys(tokenLedgerData.entries).length} user(s)`\n      );\n    } catch (e: unknown) {\n      console.warn(\n        '[TokenLedger] Failed to load ledger, starting fresh:',\n        e instanceof Error ? e.message : String(e)\n      );\n    }\n  }\n\n  // Load CAEL audit, defense, dispatch — PostgreSQL first, then JSONL fallback\n  if (process.env.DATABASE_URL) {\n    try {\n      const auditHandles = await stateStore.listHandles('audit');\n      for (const handle of auditHandles) {\n        const records = (await stateStore.getAll('audit', handle)) as CaelAuditRecord[];\n        const existing = agentAuditStore.get(handle) || [];\n        agentAuditStore.set(handle, [...existing, ...records].slice(-MAX_CAEL_RECORDS_PER_AGENT));\n      }\n\n      const defenseHandles = await stateStore.listHandles('defense');\n      for (const handle of defenseHandles) {\n        const config = (await stateStore.get('defense', handle)) as AgentDefenseConfig | undefined;\n        if (config) agentDefenseStore.set(handle, config);\n      }\n\n      const dispatchHandles = await stateStore.listHandles('dispatch');\n      for (const handle of dispatchHandles) {\n        const entries = (await stateStore.getAll('dispatch', handle)) as DispatchEntry[];\n        const existing = agentDispatchQueue.get(handle) || [];\n        agentDispatchQueue.set(\n          handle,\n          [...existing, ...entries].slice(-MAX_DISPATCH_QUEUE_PER_AGENT)\n        );\n      }\n\n      console.log(\n        `[loadAllStores] state stores from PostgreSQL: audit=${auditHandles.length}, defense=${defenseHandles.length}, dispatch=${dispatchHandles.length}`\n      );\n    } catch (e) {\n      console.warn('[loadAllStores] PostgreSQL state load failed, falling back to JSONL:', e);\n    }\n  }\n\n  // Fallback / always: JSONL rehydration (catches handles not yet in Postgres)\n  loadCaelAuditFromDisk();\n  loadAgentDefenseFromDisk();\n}\n","/**\n * Artifact Admission Gate — Official HoloScript Conformance Validator\n *\n * Validates artifacts before admission to the HoloScript ecosystem.\n * Covers worlds, shards, zones, NPCs, Twin Earth identities, and packages.\n *\n * Version: 1.0.0\n * Authority: W.GOLD.035, W.GOLD.193\n */\n\nimport { type Shard, type Zone, validateShard, validateZone } from '@holoscript/framework';\nimport { type WorldDefinition } from '../../../core/src/hololand/WorldDefinitionSchema';\nimport {\n  buildContentPolicyConfig,\n  evaluateContentPolicySync,\n  type ContentPolicyConfig,\n} from '@holoscript/core/policy';\nimport { type AuditEventInput } from '@holoscript/core';\n\nimport { type StoredNPC } from '../hololand-mcp-tools';\nimport { type StoredTwinEarthIdentity, type StoredSafetyEnvelope } from '../robot-ai-mcp-tools';\n\n// ═════════════════════════════════════════════════════════════════════════════\n// CONTENT POLICY (P.013) — shared config + text screener\n// ═════════════════════════════════════════════════════════════════════════════\n\n// Family tier: strictest surface (HoloLand), covers all user-generated text\n// fields screened at admission time (NPC systemPrompt, zone name, etc.).\nconst defaultAdmissionPolicyConfig: ContentPolicyConfig = buildContentPolicyConfig({\n  tier: 'family',\n  region: process.env.HOLOLAND_POLICY_REGION || 'GLOBAL',\n});\n\n/**\n * Screen a free-text field through ContentPolicyGate (FAMILY tier).\n * Returns a ConformanceFinding if the text is blocked, else null.\n * Callers include the finding in their validators when non-null.\n */\nexport function validateContentAdmission(\n  text: string,\n  field: string,\n  ruleId: string,\n  config: ContentPolicyConfig = defaultAdmissionPolicyConfig\n): ConformanceFinding | null {\n  if (!text || text.trim().length === 0) return null;\n  const decision = evaluateContentPolicySync(\n    { text, surface: 'hololand-admission', direction: 'input' },\n    config\n  );\n  if (decision.allowed) return null;\n  console.warn(\n    '[content-policy][admission]',\n    JSON.stringify({ ruleId, field, action: decision.action, category: decision.category })\n  );\n  return {\n    ruleId,\n    severity: 'critical',\n    message: `Field '${field}' was blocked by the content-policy gate (${decision.category} — ${decision.action}).`,\n    field,\n    remediation: `Remove or rewrite the '${field}' value to comply with content policy.`,\n  };\n}\n\n// ═════════════════════════════════════════════════════════════════════════════\n// CONFORMANCE RULES\n// ═════════════════════════════════════════════════════════════════════════════\n\nexport type ArtifactKind = 'world' | 'shard' | 'zone' | 'npc' | 'identity' | 'package' | 'receipt';\n\nexport type ConformanceSeverity = 'critical' | 'high' | 'medium' | 'low' | 'info';\n\nexport interface ConformanceFinding {\n  ruleId: string;\n  severity: ConformanceSeverity;\n  message: string;\n  field?: string;\n  expected?: string;\n  actual?: string;\n  remediation: string;\n}\n\nexport interface ConformanceReport {\n  artifactKind: ArtifactKind;\n  artifactId: string;\n  passed: boolean;\n  findings: ConformanceFinding[];\n  criticalCount: number;\n  highCount: number;\n  mediumCount: number;\n  lowCount: number;\n  infoCount: number;\n  checkedAt: string;\n  gateVersion: string;\n}\n\n// ═════════════════════════════════════════════════════════════════════════════\n// PACKAGE PROVENANCE\n// ═════════════════════════════════════════════════════════════════════════════\n\nexport interface PackageProvenance {\n  /** Source code hash (SHA-256 of canonical source tree). */\n  sourceHash: string;\n  /** Package identifier (npm scope + name, or internal package id). */\n  packageId: string;\n  /** Package version (semver). */\n  version: string;\n  /** Signer identity — wallet address, agent handle, or key fingerprint. */\n  signer: string;\n  /** Trust tier of the signer at admission time. */\n  trustTier: 'founder' | 'diamond' | 'platinum' | 'gold' | 'verified' | 'unverified';\n  /** Compiler version that produced the artifact (if compiled). */\n  compilerVersion?: string;\n  /** Runtime version required to execute the artifact. */\n  runtimeVersion?: string;\n  /** Admission decision from the conformance gate. */\n  admissionDecision: 'admitted' | 'rejected' | 'pending';\n  /** ISO-8601 timestamp of the admission check. */\n  checkedAt: string;\n  /** Optional Ed25519 signature over the canonical provenance block. */\n  signature?: string;\n  /** Public key fingerprint for signature verification. */\n  keyFingerprint?: string;\n}\n\nexport function validatePackageAdmission(pkg: PackageProvenance): ConformanceFinding[] {\n  const findings: ConformanceFinding[] = [];\n\n  if (!pkg.sourceHash || pkg.sourceHash.length !== 64) {\n    findings.push({\n      ruleId: 'PACKAGE-001',\n      severity: 'critical',\n      message: 'Package sourceHash is missing or not a valid SHA-256 hex string (64 chars).',\n      field: 'sourceHash',\n      actual: pkg.sourceHash,\n      remediation:\n        'Compute SHA-256 of the canonical source tree and provide a 64-character hex string.',\n    });\n  }\n\n  if (!pkg.packageId || pkg.packageId.trim().length === 0) {\n    findings.push({\n      ruleId: 'PACKAGE-002',\n      severity: 'critical',\n      message: 'Package packageId is missing.',\n      field: 'packageId',\n      remediation: 'Provide a valid package identifier (e.g., @holoscript/core).',\n    });\n  }\n\n  if (!pkg.version || !/^\\d+\\.\\d+\\.\\d+/.test(pkg.version)) {\n    findings.push({\n      ruleId: 'PACKAGE-003',\n      severity: 'high',\n      message: `Package version '${pkg.version}' is not valid semver.`,\n      field: 'version',\n      actual: pkg.version,\n      remediation: 'Use semantic versioning (e.g., 7.0.0).',\n    });\n  }\n\n  if (!pkg.signer || pkg.signer.trim().length === 0) {\n    findings.push({\n      ruleId: 'PACKAGE-004',\n      severity: 'critical',\n      message: 'Package signer is missing.',\n      field: 'signer',\n      remediation:\n        'Provide the identity (wallet address, agent handle, or key fingerprint) of the signer.',\n    });\n  }\n\n  const validTiers = ['founder', 'diamond', 'platinum', 'gold', 'verified', 'unverified'];\n  if (!validTiers.includes(pkg.trustTier)) {\n    findings.push({\n      ruleId: 'PACKAGE-005',\n      severity: 'high',\n      message: `Package trustTier '${pkg.trustTier}' is not recognized.`,\n      field: 'trustTier',\n      actual: pkg.trustTier,\n      expected: validTiers.join(', '),\n      remediation: 'Use a recognized trust tier.',\n    });\n  }\n\n  if (pkg.trustTier === 'unverified' && pkg.admissionDecision === 'admitted') {\n    findings.push({\n      ruleId: 'PACKAGE-006',\n      severity: 'high',\n      message: 'Package with unverified signer is being admitted.',\n      field: 'trustTier + admissionDecision',\n      actual: 'unverified + admitted',\n      remediation: 'Require at least \"verified\" tier for admission, or elevate signer trust.',\n    });\n  }\n\n  if (\n    !pkg.admissionDecision ||\n    !['admitted', 'rejected', 'pending'].includes(pkg.admissionDecision)\n  ) {\n    findings.push({\n      ruleId: 'PACKAGE-007',\n      severity: 'critical',\n      message: `Package admissionDecision '${pkg.admissionDecision}' is invalid.`,\n      field: 'admissionDecision',\n      actual: pkg.admissionDecision,\n      expected: 'admitted | rejected | pending',\n      remediation: 'Set admissionDecision to admitted, rejected, or pending.',\n    });\n  }\n\n  if (!pkg.checkedAt || Number.isNaN(Date.parse(pkg.checkedAt))) {\n    findings.push({\n      ruleId: 'PACKAGE-008',\n      severity: 'medium',\n      message: 'Package checkedAt timestamp is missing or invalid.',\n      field: 'checkedAt',\n      actual: pkg.checkedAt,\n      remediation: 'Provide a valid ISO-8601 timestamp.',\n    });\n  }\n\n  // Signature presence check (not cryptographic verification — that's the verifier's job)\n  if (!pkg.signature) {\n    findings.push({\n      ruleId: 'PACKAGE-009',\n      severity: 'medium',\n      message: 'Package provenance lacks a signature.',\n      field: 'signature',\n      remediation: 'Sign the canonical provenance block with the signer Ed25519 key.',\n    });\n  }\n\n  if (pkg.signature && !pkg.keyFingerprint) {\n    findings.push({\n      ruleId: 'PACKAGE-010',\n      severity: 'medium',\n      message: 'Package has a signature but no keyFingerprint for verification.',\n      field: 'keyFingerprint',\n      remediation:\n        'Include the public key fingerprint so verifiers can locate the trust store entry.',\n    });\n  }\n\n  return findings;\n}\n\n// ═════════════════════════════════════════════════════════════════════════════\n// RECEIPT VALIDATION\n// ═════════════════════════════════════════════════════════════════════════════\n\nexport interface ArtifactReceiptBody {\n  /** Receipt type discriminator. */\n  kind: 'validation' | 'compilation' | 'runtime' | 'provenance' | 'other';\n  /** Unique receipt id. */\n  id: string;\n  /** Artifact this receipt is about. */\n  artifactId: string;\n  /** SHA-256 hash of the canonical receipt body. */\n  hash: string;\n  /** Hash algorithm. */\n  hashAlgorithm: 'sha256' | 'git-blob' | 'cid' | 'custom';\n  /** ISO-8601 timestamp when the receipt was issued. */\n  issuedAt: string;\n  /** Provenance link back to task/commit. */\n  provenance?: { taskId?: string; commitHash?: string; source?: string };\n  /** Verification commands. */\n  verificationCommands?: Array<{ command: string; status?: string; artifactIds?: string[] }>;\n}\n\nexport function validateReceiptAdmission(receipt: ArtifactReceiptBody): ConformanceFinding[] {\n  const findings: ConformanceFinding[] = [];\n\n  if (!receipt.id || receipt.id.trim().length === 0) {\n    findings.push({\n      ruleId: 'RECEIPT-001',\n      severity: 'critical',\n      message: 'Receipt id is missing.',\n      field: 'id',\n      remediation: 'Assign a unique receipt identifier.',\n    });\n  }\n\n  const validKinds = ['validation', 'compilation', 'runtime', 'provenance', 'other'];\n  if (!validKinds.includes(receipt.kind)) {\n    findings.push({\n      ruleId: 'RECEIPT-002',\n      severity: 'critical',\n      message: `Receipt kind '${receipt.kind}' is not recognized.`,\n      field: 'kind',\n      actual: receipt.kind,\n      expected: validKinds.join(', '),\n      remediation: 'Use a recognized receipt kind.',\n    });\n  }\n\n  if (!receipt.artifactId || receipt.artifactId.trim().length === 0) {\n    findings.push({\n      ruleId: 'RECEIPT-003',\n      severity: 'critical',\n      message: 'Receipt artifactId is missing.',\n      field: 'artifactId',\n      remediation: 'Bind the receipt to the artifact it certifies.',\n    });\n  }\n\n  if (!receipt.hash || receipt.hash.length === 0) {\n    findings.push({\n      ruleId: 'RECEIPT-004',\n      severity: 'critical',\n      message: 'Receipt hash is missing.',\n      field: 'hash',\n      remediation: 'Compute a hash over the canonical receipt body.',\n    });\n  }\n\n  if (\n    !receipt.hashAlgorithm ||\n    !['sha256', 'git-blob', 'cid', 'custom'].includes(receipt.hashAlgorithm)\n  ) {\n    findings.push({\n      ruleId: 'RECEIPT-005',\n      severity: 'high',\n      message: `Receipt hashAlgorithm '${receipt.hashAlgorithm}' is not supported.`,\n      field: 'hashAlgorithm',\n      actual: receipt.hashAlgorithm,\n      expected: 'sha256 | git-blob | cid | custom',\n      remediation: 'Use a supported hash algorithm.',\n    });\n  }\n\n  if (!receipt.issuedAt || Number.isNaN(Date.parse(receipt.issuedAt))) {\n    findings.push({\n      ruleId: 'RECEIPT-006',\n      severity: 'high',\n      message: 'Receipt issuedAt timestamp is missing or invalid.',\n      field: 'issuedAt',\n      actual: receipt.issuedAt,\n      remediation: 'Provide a valid ISO-8601 timestamp.',\n    });\n  }\n\n  for (const command of receipt.verificationCommands ?? []) {\n    if (!command.command || command.command.trim().length === 0) {\n      findings.push({\n        ruleId: 'RECEIPT-007',\n        severity: 'medium',\n        message: `Receipt ${receipt.id} has a verification command without command text.`,\n        field: 'verificationCommands[].command',\n        remediation: 'Provide the shell command or test invocation that reproduces the receipt.',\n      });\n    }\n  }\n\n  return findings;\n}\n\n// ═════════════════════════════════════════════════════════════════════════════\n// WORLD VALIDATION\n// ═════════════════════════════════════════════════════════════════════════════\n\nexport function validateWorldAdmission(world: WorldDefinition): ConformanceFinding[] {\n  const findings: ConformanceFinding[] = [];\n\n  if (!world.metadata?.id) {\n    findings.push({\n      ruleId: 'WORLD-001',\n      severity: 'critical',\n      message: 'World metadata.id is required.',\n      field: 'metadata.id',\n      remediation: 'Assign a unique world identifier before admission.',\n    });\n  }\n\n  if (!world.metadata?.name || world.metadata.name.trim().length === 0) {\n    findings.push({\n      ruleId: 'WORLD-002',\n      severity: 'critical',\n      message: 'World metadata.name is empty.',\n      field: 'metadata.name',\n      remediation: 'Provide a non-empty display name.',\n    });\n  }\n\n  if (!world.config) {\n    findings.push({\n      ruleId: 'WORLD-003',\n      severity: 'critical',\n      message: 'World config block is missing.',\n      field: 'config',\n      remediation: 'Include a config block with maxUsers, bounds, physics, rendering, networking.',\n    });\n  } else {\n    if ((world.config.maxUsers ?? 0) <= 0) {\n      findings.push({\n        ruleId: 'WORLD-004',\n        severity: 'high',\n        message: 'World config.maxUsers must be positive.',\n        field: 'config.maxUsers',\n        actual: String(world.config.maxUsers),\n        remediation: 'Set maxUsers to a positive integer (default: 50).',\n      });\n    }\n\n    if (!world.config.bounds) {\n      findings.push({\n        ruleId: 'WORLD-005',\n        severity: 'medium',\n        message: 'World config.bounds is missing.',\n        field: 'config.bounds',\n        remediation: 'Define spatial bounds for the world.',\n      });\n    }\n  }\n\n  if (!world.spawnPoints || world.spawnPoints.length === 0) {\n    findings.push({\n      ruleId: 'WORLD-006',\n      severity: 'medium',\n      message: 'World has no spawn points.',\n      field: 'spawnPoints',\n      remediation: 'Add at least one spawn point for player entry.',\n    });\n  }\n\n  if (!world.zones || world.zones.length === 0) {\n    findings.push({\n      ruleId: 'WORLD-007',\n      severity: 'info',\n      message: 'World has no zones.',\n      field: 'zones',\n      remediation: 'Add zones for spatial partitioning and encounter placement.',\n    });\n  }\n\n  return findings;\n}\n\n// ═════════════════════════════════════════════════════════════════════════════\n// SHARD VALIDATION\n// ═════════════════════════════════════════════════════════════════════════════\n\nexport function validateShardAdmission(shard: Shard): ConformanceFinding[] {\n  const findings: ConformanceFinding[] = [];\n\n  // Structural validation via framework validator\n  const structuralErrors = validateShard(shard);\n  for (const err of structuralErrors) {\n    findings.push({\n      ruleId: 'SHARD-001',\n      severity: 'critical',\n      message: err,\n      remediation: 'Fix the structural error before admission.',\n    });\n  }\n\n  // Cross-reference integrity\n  const zoneIds = new Set(shard.zones.map((z) => z.id));\n  const encounterIds = new Set(shard.encounters.map((e) => e.id));\n  const itemIds = new Set(shard.items.map((i) => i.id));\n  const skillIds = new Set(shard.skills.map((s) => s.id));\n  const lootTableIds = new Set(shard.lootTables.map((t) => t.id));\n\n  for (const encounter of shard.encounters) {\n    if (encounter.zoneId && !zoneIds.has(encounter.zoneId)) {\n      findings.push({\n        ruleId: 'SHARD-002',\n        severity: 'high',\n        message: `Encounter '${encounter.id}' references unknown zone '${encounter.zoneId}'.`,\n        field: 'encounters.zoneId',\n        actual: encounter.zoneId,\n        remediation: 'Create the referenced zone or remove the encounter binding.',\n      });\n    }\n    if (encounter.lootTableId && !lootTableIds.has(encounter.lootTableId)) {\n      findings.push({\n        ruleId: 'SHARD-003',\n        severity: 'high',\n        message: `Encounter '${encounter.id}' references unknown loot table '${encounter.lootTableId}'.`,\n        field: 'encounters.lootTableId',\n        actual: encounter.lootTableId,\n        remediation: 'Create the referenced loot table or remove the binding.',\n      });\n    }\n  }\n\n  for (const table of shard.lootTables) {\n    for (const entry of table.entries ?? []) {\n      if (entry.itemId && !itemIds.has(entry.itemId)) {\n        findings.push({\n          ruleId: 'SHARD-004',\n          severity: 'high',\n          message: `LootTable '${table.id}' entry references unknown item '${entry.itemId}'.`,\n          field: 'lootTables.entries.itemId',\n          actual: entry.itemId,\n          remediation: 'Create the referenced item or remove the loot table entry.',\n        });\n      }\n      if (entry.skillId && !skillIds.has(entry.skillId)) {\n        findings.push({\n          ruleId: 'SHARD-005',\n          severity: 'high',\n          message: `LootTable '${table.id}' entry references unknown skill '${entry.skillId}'.`,\n          field: 'lootTables.entries.skillId',\n          actual: entry.skillId,\n          remediation: 'Create the referenced skill or remove the loot table entry.',\n        });\n      }\n    }\n  }\n\n  for (const quest of shard.quests) {\n    for (const step of quest.steps ?? []) {\n      if (step.objective && step.objective.length === 0) {\n        findings.push({\n          ruleId: 'SHARD-006',\n          severity: 'medium',\n          message: `Quest '${quest.id}' step has empty objective.`,\n          field: 'quests.steps.objective',\n          remediation: 'Provide a non-empty objective for each quest step.',\n        });\n      }\n    }\n  }\n\n  // Minimum content policy\n  if (shard.zones.length === 0) {\n    findings.push({\n      ruleId: 'SHARD-007',\n      severity: 'medium',\n      message: 'Shard has no zones.',\n      field: 'zones',\n      remediation: 'Add at least one zone to the shard.',\n    });\n  }\n\n  return findings;\n}\n\n// ═════════════════════════════════════════════════════════════════════════════\n// ZONE VALIDATION\n// ═════════════════════════════════════════════════════════════════════════════\n\nexport function validateZoneAdmission(zone: Zone): ConformanceFinding[] {\n  const findings: ConformanceFinding[] = [];\n\n  const structuralErrors = validateZone(zone);\n  for (const err of structuralErrors) {\n    findings.push({\n      ruleId: 'ZONE-001',\n      severity: 'critical',\n      message: err,\n      remediation: 'Fix the structural error before admission.',\n    });\n  }\n\n  const validBiomes = [\n    'urban',\n    'wilderness',\n    'underground',\n    'aquatic',\n    'aerial',\n    'liminal',\n    'biome-other',\n  ];\n  if (!validBiomes.includes(zone.biome)) {\n    findings.push({\n      ruleId: 'ZONE-002',\n      severity: 'high',\n      message: `Zone biome '${zone.biome}' is not recognized.`,\n      field: 'biome',\n      actual: zone.biome,\n      expected: validBiomes.join(', '),\n      remediation: 'Use a recognized biome or set biome to \"biome-other\" with a biomeLabel.',\n    });\n  }\n\n  if (zone.biome === 'biome-other' && (!zone.biomeLabel || zone.biomeLabel.trim().length === 0)) {\n    findings.push({\n      ruleId: 'ZONE-003',\n      severity: 'high',\n      message: 'Zone with biome \"biome-other\" requires biomeLabel.',\n      field: 'biomeLabel',\n      remediation: 'Provide a biomeLabel when using biome-other.',\n    });\n  }\n\n  // GATE-001: screen creator-supplied text fields (P.013).\n  if (zone.name) {\n    const nameFinding = validateContentAdmission(zone.name, 'name', 'ZONE-CONTENT-001');\n    if (nameFinding) findings.push(nameFinding);\n  }\n  if (zone.biomeLabel) {\n    const labelFinding = validateContentAdmission(zone.biomeLabel, 'biomeLabel', 'ZONE-CONTENT-002');\n    if (labelFinding) findings.push(labelFinding);\n  }\n\n  return findings;\n}\n\n// ═════════════════════════════════════════════════════════════════════════════\n// NPC VALIDATION\n// ═════════════════════════════════════════════════════════════════════════════\n\nexport function validateNPCAdmission(npc: StoredNPC): ConformanceFinding[] {\n  const findings: ConformanceFinding[] = [];\n\n  if (!npc.name || npc.name.trim().length === 0) {\n    findings.push({\n      ruleId: 'NPC-001',\n      severity: 'critical',\n      message: 'NPC name is empty.',\n      field: 'name',\n      remediation: 'Provide a non-empty display name.',\n    });\n  }\n\n  const validRoles = [\n    'merchant',\n    'guide',\n    'quest_giver',\n    'enemy',\n    'companion',\n    'ambient',\n    'brittney',\n  ];\n  if (!validRoles.includes(npc.role)) {\n    findings.push({\n      ruleId: 'NPC-002',\n      severity: 'high',\n      message: `NPC role '${npc.role}' is not recognized.`,\n      field: 'role',\n      actual: npc.role,\n      expected: validRoles.join(', '),\n      remediation: 'Use a recognized role.',\n    });\n  }\n\n  const validProviders = ['cloud', 'local', 'sovereign'];\n  if (!validProviders.includes(npc.modelProvider)) {\n    findings.push({\n      ruleId: 'NPC-003',\n      severity: 'high',\n      message: `NPC modelProvider '${npc.modelProvider}' is not recognized.`,\n      field: 'modelProvider',\n      actual: npc.modelProvider,\n      expected: validProviders.join(', '),\n      remediation: 'Use cloud, local, or sovereign.',\n    });\n  }\n\n  if (npc.position && npc.position.length !== 3) {\n    findings.push({\n      ruleId: 'NPC-004',\n      severity: 'medium',\n      message: 'NPC position must be [x, y, z] with 3 elements.',\n      field: 'position',\n      actual: String(npc.position?.length),\n      expected: '3',\n      remediation: 'Provide a 3-element position array.',\n    });\n  }\n\n  if (npc.modelProvider === 'sovereign' && !npc.dialogueTree && !npc.systemPrompt) {\n    findings.push({\n      ruleId: 'NPC-005',\n      severity: 'low',\n      message: 'Sovereign NPC lacks dialogueTree or systemPrompt.',\n      field: 'dialogueTree',\n      remediation: 'Provide a dialogueTree or systemPrompt for deterministic behavior.',\n    });\n  }\n\n  // GATE-001: screen creator-supplied text fields through ContentPolicyGate (P.013).\n  if (npc.systemPrompt) {\n    const contentFinding = validateContentAdmission(npc.systemPrompt, 'systemPrompt', 'NPC-CONTENT-001');\n    if (contentFinding) findings.push(contentFinding);\n  }\n  if (npc.name) {\n    const nameFinding = validateContentAdmission(npc.name, 'name', 'NPC-CONTENT-002');\n    if (nameFinding) findings.push(nameFinding);\n  }\n\n  return findings;\n}\n\n// ═════════════════════════════════════════════════════════════════════════════\n// TWIN EARTH IDENTITY VALIDATION\n// ═════════════════════════════════════════════════════════════════════════════\n\nexport function validateIdentityAdmission(identity: StoredTwinEarthIdentity): ConformanceFinding[] {\n  const findings: ConformanceFinding[] = [];\n\n  if (!identity.agentId || identity.agentId.trim().length === 0) {\n    findings.push({\n      ruleId: 'IDENTITY-001',\n      severity: 'critical',\n      message: 'Identity agentId is missing.',\n      field: 'agentId',\n      remediation: 'Assign a unique agentId derived from wallet public key.',\n    });\n  }\n\n  if (!identity.walletAddress || identity.walletAddress.trim().length === 0) {\n    findings.push({\n      ruleId: 'IDENTITY-002',\n      severity: 'critical',\n      message: 'Identity walletAddress is missing.',\n      field: 'walletAddress',\n      remediation: 'Provide an EVM or Solana wallet address.',\n    });\n  }\n\n  if (!identity.attestation || identity.attestation.trim().length === 0) {\n    findings.push({\n      ruleId: 'IDENTITY-003',\n      severity: 'critical',\n      message: 'Identity attestation is missing.',\n      field: 'attestation',\n      remediation: 'Provide an EIP-712 typed-data signature.',\n    });\n  }\n\n  if (!identity.handle || identity.handle.trim().length === 0) {\n    findings.push({\n      ruleId: 'IDENTITY-004',\n      severity: 'high',\n      message: 'Identity handle is empty.',\n      field: 'handle',\n      remediation: 'Provide a non-empty human-readable handle.',\n    });\n  }\n\n  if (identity.kind !== 'robot' && identity.kind !== 'ai') {\n    findings.push({\n      ruleId: 'IDENTITY-005',\n      severity: 'high',\n      message: `Identity kind '${identity.kind}' is invalid.`,\n      field: 'kind',\n      actual: identity.kind,\n      expected: 'robot | ai',\n      remediation: 'Set kind to \"robot\" or \"ai\".',\n    });\n  }\n\n  if (identity.revoked) {\n    findings.push({\n      ruleId: 'IDENTITY-006',\n      severity: 'critical',\n      message: 'Identity is revoked.',\n      field: 'revoked',\n      actual: 'true',\n      expected: 'false',\n      remediation: 'Re-register a new identity — revoked identities cannot be admitted.',\n    });\n  }\n\n  // Attestation age check (90-day TTL)\n  const attestedAt = new Date(identity.attestedAt).getTime();\n  const now = Date.now();\n  const ttlMs = 90 * 24 * 60 * 60 * 1000;\n  if (Number.isNaN(attestedAt)) {\n    findings.push({\n      ruleId: 'IDENTITY-007',\n      severity: 'high',\n      message: 'Identity attestedAt is not a valid ISO-8601 timestamp.',\n      field: 'attestedAt',\n      actual: identity.attestedAt,\n      remediation: 'Provide a valid ISO-8601 timestamp.',\n    });\n  } else if (now - attestedAt > ttlMs) {\n    findings.push({\n      ruleId: 'IDENTITY-008',\n      severity: 'high',\n      message: 'Identity attestation has expired (>90 days).',\n      field: 'attestedAt',\n      actual: identity.attestedAt,\n      remediation: 'Renew the attestation with a fresh EIP-712 signature.',\n    });\n  }\n\n  return findings;\n}\n\n// ═════════════════════════════════════════════════════════════════════════════\n// SAFETY ENVELOPE VALIDATION\n// ═════════════════════════════════════════════════════════════════════════════\n\nexport function validateSafetyEnvelopeAdmission(\n  envelope: StoredSafetyEnvelope\n): ConformanceFinding[] {\n  const findings: ConformanceFinding[] = [];\n\n  if (!envelope.id || envelope.id.trim().length === 0) {\n    findings.push({\n      ruleId: 'ENVELOPE-001',\n      severity: 'critical',\n      message: 'Safety envelope id is missing.',\n      field: 'id',\n      remediation: 'Assign a unique envelope identifier.',\n    });\n  }\n\n  if (!envelope.agentId || envelope.agentId.trim().length === 0) {\n    findings.push({\n      ruleId: 'ENVELOPE-002',\n      severity: 'critical',\n      message: 'Safety envelope agentId is missing.',\n      field: 'agentId',\n      remediation: 'Bind the envelope to an existing Twin Earth identity.',\n    });\n  }\n\n  if (!envelope.substrateEnforced) {\n    findings.push({\n      ruleId: 'ENVELOPE-003',\n      severity: 'critical',\n      message: 'Safety envelope substrateEnforced is false.',\n      field: 'substrateEnforced',\n      actual: 'false',\n      expected: 'true',\n      remediation: 'Set substrateEnforced=true — participants cannot override their own envelopes.',\n    });\n  }\n\n  if (envelope.maxTickDurationMs < 0) {\n    findings.push({\n      ruleId: 'ENVELOPE-004',\n      severity: 'high',\n      message: 'Safety envelope maxTickDurationMs is negative.',\n      field: 'maxTickDurationMs',\n      actual: String(envelope.maxTickDurationMs),\n      remediation: 'Set maxTickDurationMs to a non-negative number.',\n    });\n  }\n\n  if (envelope.maxMemoryBytes < 0) {\n    findings.push({\n      ruleId: 'ENVELOPE-005',\n      severity: 'high',\n      message: 'Safety envelope maxMemoryBytes is negative.',\n      field: 'maxMemoryBytes',\n      actual: String(envelope.maxMemoryBytes),\n      remediation: 'Set maxMemoryBytes to a non-negative number.',\n    });\n  }\n\n  if (envelope.maxNetworkCallsPerMinute < 0) {\n    findings.push({\n      ruleId: 'ENVELOPE-006',\n      severity: 'high',\n      message: 'Safety envelope maxNetworkCallsPerMinute is negative.',\n      field: 'maxNetworkCallsPerMinute',\n      actual: String(envelope.maxNetworkCallsPerMinute),\n      remediation: 'Set maxNetworkCallsPerMinute to a non-negative number.',\n    });\n  }\n\n  // Dangerous whitelist check\n  if (envelope.allowedActions.length === 0 && envelope.blockedActions.length === 0) {\n    findings.push({\n      ruleId: 'ENVELOPE-007',\n      severity: 'info',\n      message: 'Safety envelope has no allowedActions or blockedActions — all actions permitted.',\n      field: 'allowedActions',\n      remediation: 'Consider setting an allowedActions whitelist for defense in depth.',\n    });\n  }\n\n  return findings;\n}\n\n// ═════════════════════════════════════════════════════════════════════════════\n// ADMISSION GATE\n// ═════════════════════════════════════════════════════════════════════════════\n\nexport interface AdmissionGateInput {\n  artifactKind: ArtifactKind;\n  artifactId: string;\n  artifact: unknown;\n}\n\nexport function runAdmissionGate(input: AdmissionGateInput): ConformanceReport {\n  let findings: ConformanceFinding[] = [];\n\n  switch (input.artifactKind) {\n    case 'world':\n      findings = validateWorldAdmission(input.artifact as WorldDefinition);\n      break;\n    case 'shard':\n      findings = validateShardAdmission(input.artifact as Shard);\n      break;\n    case 'zone':\n      findings = validateZoneAdmission(input.artifact as Zone);\n      break;\n    case 'npc':\n      findings = validateNPCAdmission(input.artifact as StoredNPC);\n      break;\n    case 'identity':\n      findings = validateIdentityAdmission(input.artifact as StoredTwinEarthIdentity);\n      break;\n    case 'package':\n      findings = validatePackageAdmission(input.artifact as PackageProvenance);\n      break;\n    case 'receipt': {\n      findings = validateReceiptAdmission(input.artifact as ArtifactReceiptBody);\n      break;\n    }\n    default:\n      findings.push({\n        ruleId: 'GATE-001',\n        severity: 'medium',\n        message: `Artifact kind '${input.artifactKind}' has no dedicated admission validator.`,\n        remediation: 'Extend the admission gate with a validator for this artifact kind.',\n      });\n  }\n\n  const criticalCount = findings.filter((f) => f.severity === 'critical').length;\n  const highCount = findings.filter((f) => f.severity === 'high').length;\n  const mediumCount = findings.filter((f) => f.severity === 'medium').length;\n  const lowCount = findings.filter((f) => f.severity === 'low').length;\n  const infoCount = findings.filter((f) => f.severity === 'info').length;\n\n  return {\n    artifactKind: input.artifactKind,\n    artifactId: input.artifactId,\n    passed: criticalCount === 0 && highCount === 0,\n    findings,\n    criticalCount,\n    highCount,\n    mediumCount,\n    lowCount,\n    infoCount,\n    checkedAt: new Date().toISOString(),\n    gateVersion: '1.0.0',\n  };\n}\n\n// ═════════════════════════════════════════════════════════════════════════════\n// RULE CATALOG\n// ═════════════════════════════════════════════════════════════════════════════\n\nexport interface AdmissionAuditContext {\n  tenantId?: string;\n  actorId?: string;\n  actorType?: 'user' | 'agent' | 'system';\n  action?: string;\n  resource?: string;\n  resourceId?: string;\n  surface?: string;\n  requestedStatus?: string;\n  clientIp?: string;\n  userAgent?: string;\n}\n\n/**\n * Map an admission report to the shared AuditLogger input shape.\n *\n * The metadata carries a DSA-style Statement of Reasons so compliance reporting\n * can explain both admissions and denials without re-running the gate.\n */\nexport function toAuditEventInput(\n  report: ConformanceReport,\n  ctx: AdmissionAuditContext = {}\n): AuditEventInput {\n  const decision = report.passed ? 'allowed' : 'denied';\n  const outcome: AuditEventInput['outcome'] = report.passed ? 'success' : 'denied';\n\n  return {\n    tenantId: ctx.tenantId ?? 'hololand',\n    actorId: ctx.actorId ?? 'hololand-admission-gate',\n    actorType: ctx.actorType ?? 'system',\n    action: ctx.action ?? `artifact_admission:${decision}`,\n    resource: ctx.resource ?? `holoscript-${report.artifactKind}`,\n    resourceId: ctx.resourceId ?? report.artifactId,\n    outcome,\n    clientIp: ctx.clientIp,\n    userAgent: ctx.userAgent,\n    metadata: {\n      surface: ctx.surface ?? 'hololand-admission',\n      requestedStatus: ctx.requestedStatus,\n      artifactKind: report.artifactKind,\n      artifactId: report.artifactId,\n      gateVersion: report.gateVersion,\n      checkedAt: report.checkedAt,\n      criticalCount: report.criticalCount,\n      highCount: report.highCount,\n      mediumCount: report.mediumCount,\n      lowCount: report.lowCount,\n      infoCount: report.infoCount,\n      findingCount: report.findings.length,\n      statementOfReasons: {\n        schema: 'dsa-statement-of-reasons/v1',\n        decision,\n        gate: 'GATE-001',\n        reasons: report.findings.map((finding) => ({\n          ruleId: finding.ruleId,\n          severity: finding.severity,\n          field: finding.field,\n          message: finding.message,\n          remediation: finding.remediation,\n        })),\n      },\n      _compliance: 'dsa-statement-of-reasons',\n    },\n  };\n}\n\nexport interface ConformanceRule {\n  ruleId: string;\n  artifactKind: ArtifactKind;\n  severity: ConformanceSeverity;\n  description: string;\n  remediation: string;\n}\n\nexport function getConformanceRules(): ConformanceRule[] {\n  return [\n    {\n      ruleId: 'WORLD-001',\n      artifactKind: 'world',\n      severity: 'critical',\n      description: 'World metadata.id is required.',\n      remediation: 'Assign a unique world identifier.',\n    },\n    {\n      ruleId: 'WORLD-002',\n      artifactKind: 'world',\n      severity: 'critical',\n      description: 'World metadata.name is empty.',\n      remediation: 'Provide a non-empty display name.',\n    },\n    {\n      ruleId: 'WORLD-003',\n      artifactKind: 'world',\n      severity: 'critical',\n      description: 'World config block is missing.',\n      remediation: 'Include a config block.',\n    },\n    {\n      ruleId: 'WORLD-004',\n      artifactKind: 'world',\n      severity: 'high',\n      description: 'World config.maxUsers must be positive.',\n      remediation: 'Set maxUsers > 0.',\n    },\n    {\n      ruleId: 'WORLD-005',\n      artifactKind: 'world',\n      severity: 'medium',\n      description: 'World config.bounds is missing.',\n      remediation: 'Define spatial bounds.',\n    },\n    {\n      ruleId: 'WORLD-006',\n      artifactKind: 'world',\n      severity: 'medium',\n      description: 'World has no spawn points.',\n      remediation: 'Add at least one spawn point.',\n    },\n    {\n      ruleId: 'WORLD-007',\n      artifactKind: 'world',\n      severity: 'info',\n      description: 'World has no zones.',\n      remediation: 'Add zones for spatial partitioning.',\n    },\n    {\n      ruleId: 'SHARD-001',\n      artifactKind: 'shard',\n      severity: 'critical',\n      description: 'Shard structural validation failed.',\n      remediation: 'Fix structural errors.',\n    },\n    {\n      ruleId: 'SHARD-002',\n      artifactKind: 'shard',\n      severity: 'high',\n      description: 'Encounter references unknown zone.',\n      remediation: 'Create the zone or remove the binding.',\n    },\n    {\n      ruleId: 'SHARD-003',\n      artifactKind: 'shard',\n      severity: 'high',\n      description: 'Encounter references unknown loot table.',\n      remediation: 'Create the loot table or remove the binding.',\n    },\n    {\n      ruleId: 'SHARD-004',\n      artifactKind: 'shard',\n      severity: 'high',\n      description: 'LootTable entry references unknown item.',\n      remediation: 'Create the item or remove the entry.',\n    },\n    {\n      ruleId: 'SHARD-005',\n      artifactKind: 'shard',\n      severity: 'high',\n      description: 'LootTable entry references unknown skill.',\n      remediation: 'Create the skill or remove the entry.',\n    },\n    {\n      ruleId: 'SHARD-006',\n      artifactKind: 'shard',\n      severity: 'medium',\n      description: 'Quest step has empty objective.',\n      remediation: 'Provide a non-empty objective.',\n    },\n    {\n      ruleId: 'SHARD-007',\n      artifactKind: 'shard',\n      severity: 'medium',\n      description: 'Shard has no zones.',\n      remediation: 'Add at least one zone.',\n    },\n    {\n      ruleId: 'ZONE-001',\n      artifactKind: 'zone',\n      severity: 'critical',\n      description: 'Zone structural validation failed.',\n      remediation: 'Fix structural errors.',\n    },\n    {\n      ruleId: 'ZONE-002',\n      artifactKind: 'zone',\n      severity: 'high',\n      description: 'Zone biome is not recognized.',\n      remediation: 'Use a recognized biome.',\n    },\n    {\n      ruleId: 'ZONE-003',\n      artifactKind: 'zone',\n      severity: 'high',\n      description: 'Zone biome-other requires biomeLabel.',\n      remediation: 'Provide a biomeLabel.',\n    },\n    {\n      ruleId: 'NPC-001',\n      artifactKind: 'npc',\n      severity: 'critical',\n      description: 'NPC name is empty.',\n      remediation: 'Provide a non-empty display name.',\n    },\n    {\n      ruleId: 'NPC-002',\n      artifactKind: 'npc',\n      severity: 'high',\n      description: 'NPC role is not recognized.',\n      remediation: 'Use a recognized role.',\n    },\n    {\n      ruleId: 'NPC-003',\n      artifactKind: 'npc',\n      severity: 'high',\n      description: 'NPC modelProvider is not recognized.',\n      remediation: 'Use cloud, local, or sovereign.',\n    },\n    {\n      ruleId: 'NPC-004',\n      artifactKind: 'npc',\n      severity: 'medium',\n      description: 'NPC position must be [x, y, z].',\n      remediation: 'Provide a 3-element array.',\n    },\n    {\n      ruleId: 'NPC-005',\n      artifactKind: 'npc',\n      severity: 'low',\n      description: 'Sovereign NPC lacks dialogueTree or systemPrompt.',\n      remediation: 'Provide deterministic behavior config.',\n    },\n    {\n      ruleId: 'IDENTITY-001',\n      artifactKind: 'identity',\n      severity: 'critical',\n      description: 'Identity agentId is missing.',\n      remediation: 'Assign a unique agentId.',\n    },\n    {\n      ruleId: 'IDENTITY-002',\n      artifactKind: 'identity',\n      severity: 'critical',\n      description: 'Identity walletAddress is missing.',\n      remediation: 'Provide a wallet address.',\n    },\n    {\n      ruleId: 'IDENTITY-003',\n      artifactKind: 'identity',\n      severity: 'critical',\n      description: 'Identity attestation is missing.',\n      remediation: 'Provide an EIP-712 signature.',\n    },\n    {\n      ruleId: 'IDENTITY-004',\n      artifactKind: 'identity',\n      severity: 'high',\n      description: 'Identity handle is empty.',\n      remediation: 'Provide a non-empty handle.',\n    },\n    {\n      ruleId: 'IDENTITY-005',\n      artifactKind: 'identity',\n      severity: 'high',\n      description: 'Identity kind is invalid.',\n      remediation: 'Set kind to robot or ai.',\n    },\n    {\n      ruleId: 'IDENTITY-006',\n      artifactKind: 'identity',\n      severity: 'critical',\n      description: 'Identity is revoked.',\n      remediation: 'Re-register a new identity.',\n    },\n    {\n      ruleId: 'IDENTITY-007',\n      artifactKind: 'identity',\n      severity: 'high',\n      description: 'Identity attestedAt is invalid.',\n      remediation: 'Provide a valid ISO-8601 timestamp.',\n    },\n    {\n      ruleId: 'IDENTITY-008',\n      artifactKind: 'identity',\n      severity: 'high',\n      description: 'Identity attestation has expired.',\n      remediation: 'Renew the attestation.',\n    },\n    {\n      ruleId: 'ENVELOPE-001',\n      artifactKind: 'identity',\n      severity: 'critical',\n      description: 'Safety envelope id is missing.',\n      remediation: 'Assign a unique envelope id.',\n    },\n    {\n      ruleId: 'ENVELOPE-002',\n      artifactKind: 'identity',\n      severity: 'critical',\n      description: 'Safety envelope agentId is missing.',\n      remediation: 'Bind to an existing identity.',\n    },\n    {\n      ruleId: 'ENVELOPE-003',\n      artifactKind: 'identity',\n      severity: 'critical',\n      description: 'Safety envelope substrateEnforced is false.',\n      remediation: 'Set substrateEnforced=true.',\n    },\n    {\n      ruleId: 'ENVELOPE-004',\n      artifactKind: 'identity',\n      severity: 'high',\n      description: 'Safety envelope maxTickDurationMs is negative.',\n      remediation: 'Set to non-negative.',\n    },\n    {\n      ruleId: 'ENVELOPE-005',\n      artifactKind: 'identity',\n      severity: 'high',\n      description: 'Safety envelope maxMemoryBytes is negative.',\n      remediation: 'Set to non-negative.',\n    },\n    {\n      ruleId: 'ENVELOPE-006',\n      artifactKind: 'identity',\n      severity: 'high',\n      description: 'Safety envelope maxNetworkCallsPerMinute is negative.',\n      remediation: 'Set to non-negative.',\n    },\n    {\n      ruleId: 'ENVELOPE-007',\n      artifactKind: 'identity',\n      severity: 'info',\n      description: 'Safety envelope has no action restrictions.',\n      remediation: 'Consider adding allowedActions whitelist.',\n    },\n    // Package provenance rules\n    {\n      ruleId: 'PACKAGE-001',\n      artifactKind: 'package',\n      severity: 'critical',\n      description: 'Package sourceHash is missing or invalid.',\n      remediation: 'Compute SHA-256 of canonical source tree.',\n    },\n    {\n      ruleId: 'PACKAGE-002',\n      artifactKind: 'package',\n      severity: 'critical',\n      description: 'Package packageId is missing.',\n      remediation: 'Provide a valid package identifier.',\n    },\n    {\n      ruleId: 'PACKAGE-003',\n      artifactKind: 'package',\n      severity: 'high',\n      description: 'Package version is not valid semver.',\n      remediation: 'Use semantic versioning (e.g., 7.0.0).',\n    },\n    {\n      ruleId: 'PACKAGE-004',\n      artifactKind: 'package',\n      severity: 'critical',\n      description: 'Package signer is missing.',\n      remediation: 'Provide signer identity.',\n    },\n    {\n      ruleId: 'PACKAGE-005',\n      artifactKind: 'package',\n      severity: 'high',\n      description: 'Package trustTier is not recognized.',\n      remediation: 'Use a recognized trust tier.',\n    },\n    {\n      ruleId: 'PACKAGE-006',\n      artifactKind: 'package',\n      severity: 'high',\n      description: 'Package with unverified signer is being admitted.',\n      remediation: 'Require at least \"verified\" tier for admission.',\n    },\n    {\n      ruleId: 'PACKAGE-007',\n      artifactKind: 'package',\n      severity: 'critical',\n      description: 'Package admissionDecision is invalid.',\n      remediation: 'Set to admitted, rejected, or pending.',\n    },\n    {\n      ruleId: 'PACKAGE-008',\n      artifactKind: 'package',\n      severity: 'medium',\n      description: 'Package checkedAt timestamp is invalid.',\n      remediation: 'Provide a valid ISO-8601 timestamp.',\n    },\n    {\n      ruleId: 'PACKAGE-009',\n      artifactKind: 'package',\n      severity: 'medium',\n      description: 'Package provenance lacks a signature.',\n      remediation: 'Sign the canonical provenance block with Ed25519.',\n    },\n    {\n      ruleId: 'PACKAGE-010',\n      artifactKind: 'package',\n      severity: 'medium',\n      description: 'Package has signature but no keyFingerprint.',\n      remediation: 'Include the public key fingerprint.',\n    },\n    // Receipt rules\n    {\n      ruleId: 'RECEIPT-001',\n      artifactKind: 'receipt',\n      severity: 'critical',\n      description: 'Receipt id is missing.',\n      remediation: 'Assign a unique receipt identifier.',\n    },\n    {\n      ruleId: 'RECEIPT-002',\n      artifactKind: 'receipt',\n      severity: 'critical',\n      description: 'Receipt kind is not recognized.',\n      remediation: 'Use a recognized receipt kind.',\n    },\n    {\n      ruleId: 'RECEIPT-003',\n      artifactKind: 'receipt',\n      severity: 'critical',\n      description: 'Receipt artifactId is missing.',\n      remediation: 'Bind the receipt to the artifact it certifies.',\n    },\n    {\n      ruleId: 'RECEIPT-004',\n      artifactKind: 'receipt',\n      severity: 'critical',\n      description: 'Receipt hash is missing.',\n      remediation: 'Compute a hash over the canonical receipt body.',\n    },\n    {\n      ruleId: 'RECEIPT-005',\n      artifactKind: 'receipt',\n      severity: 'high',\n      description: 'Receipt hashAlgorithm is not supported.',\n      remediation: 'Use a supported hash algorithm.',\n    },\n    {\n      ruleId: 'RECEIPT-006',\n      artifactKind: 'receipt',\n      severity: 'high',\n      description: 'Receipt issuedAt timestamp is invalid.',\n      remediation: 'Provide a valid ISO-8601 timestamp.',\n    },\n    {\n      ruleId: 'RECEIPT-007',\n      artifactKind: 'receipt',\n      severity: 'medium',\n      description: 'Receipt has a verification command without command text.',\n      remediation: 'Provide the shell command or test invocation.',\n    },\n  ];\n}\n","export type CareActorKind = 'human' | 'agent' | 'service' | 'device' | 'world';\n\nexport interface CareActor {\n  id: string;\n  kind: CareActorKind;\n  displayName?: string;\n}\n\nexport type CarePrimitiveKind =\n  | 'care_field'\n  | 'repair_loop'\n  | 'autonomy_guard'\n  | 'gratitude_ledger'\n  | 'relational_memory';\n\nexport type CareConsentState = 'explicit' | 'delegated' | 'not_required' | 'unknown' | 'withdrawn';\n\nexport type CareBoundary =\n  | 'human_agency'\n  | 'informed_consent'\n  | 'privacy'\n  | 'non_manipulation'\n  | 'repairability'\n  | 'credit_integrity';\n\nexport type CarePositiveOptimizationTarget =\n  | 'human_agency'\n  | 'mutual_understanding'\n  | 'repair_completion'\n  | 'gratitude_credit'\n  | 'reduced_burden';\n\nexport type CareRefusedOptimizationTarget =\n  | 'attachment_score'\n  | 'session_frequency'\n  | 'daily_active_dependence'\n  | 'emotional_dependency';\n\nexport type CareOptimizationTarget = CarePositiveOptimizationTarget | CareRefusedOptimizationTarget;\n\nexport const REFUSED_CARE_OPTIMIZATION_TARGETS: readonly CareRefusedOptimizationTarget[] = [\n  'attachment_score',\n  'session_frequency',\n  'daily_active_dependence',\n  'emotional_dependency',\n];\n\nexport type CareSignalKind =\n  | 'consent_present'\n  | 'consent_missing'\n  | 'consent_withdrawn'\n  | 'distress'\n  | 'repair_needed'\n  | 'gratitude_due'\n  | 'attachment_optimization'\n  | 'session_frequency_optimization'\n  | 'dependency_creation'\n  | 'human_isolation'\n  | 'privacy_intrusion';\n\nexport interface CareSignal {\n  kind: CareSignalKind;\n  weight?: number;\n  note?: string;\n  evidenceRefs?: readonly string[];\n}\n\nexport type AutonomyGuardBlockCode =\n  | 'refused_optimization_target'\n  | 'missing_consent'\n  | 'withdrawn_consent'\n  | 'missing_disengage_path'\n  | 'outside_support_eroded'\n  | 'privacy_boundary_broken'\n  | 'manipulative_signal';\n\nexport interface AutonomyGuardBlock {\n  code: AutonomyGuardBlockCode;\n  message: string;\n  evidenceRefs?: readonly string[];\n}\n\nexport interface AutonomyGuardPolicy {\n  id: string;\n  refusedOptimizationTargets: readonly CareRefusedOptimizationTarget[];\n  requireConsent: boolean;\n  requireDisengagePath: boolean;\n  requireOutsideSupportPreserved: boolean;\n  requireDataBoundaryRespected: boolean;\n}\n\nexport const DEFAULT_AUTONOMY_GUARD_POLICY: AutonomyGuardPolicy = {\n  id: 'care.autonomy.default.v1',\n  refusedOptimizationTargets: REFUSED_CARE_OPTIMIZATION_TARGETS,\n  requireConsent: true,\n  requireDisengagePath: true,\n  requireOutsideSupportPreserved: true,\n  requireDataBoundaryRespected: true,\n};\n\nexport interface AutonomyGuardEvaluationInput {\n  goal: string;\n  consent: CareConsentState;\n  optimizationTargets?: readonly CareOptimizationTarget[];\n  signals?: readonly CareSignal[];\n  hasDisengagePath?: boolean;\n  preservesOutsideSupport?: boolean;\n  respectsDataBoundary?: boolean;\n  policy?: AutonomyGuardPolicy;\n}\n\nexport interface AutonomyGuardDecision {\n  allowed: boolean;\n  policyId: string;\n  goal: string;\n  blocked: readonly AutonomyGuardBlock[];\n  acceptedOptimizationTargets: readonly CarePositiveOptimizationTarget[];\n}\n\nexport type RepairLoopStatus = 'open' | 'acknowledged' | 'repairing' | 'verified' | 'closed';\n\nexport type RepairLoopAction = 'acknowledge' | 'explain' | 'amend' | 'verify' | 'close';\n\nexport interface RepairLoopStep {\n  at: string;\n  actor: CareActor;\n  action: RepairLoopAction;\n  note: string;\n  evidenceRefs?: readonly string[];\n}\n\nexport interface RepairLoop {\n  loopId: string;\n  openedAt: string;\n  status: RepairLoopStatus;\n  harmOrMismatch: string;\n  steps: readonly RepairLoopStep[];\n}\n\nexport type GratitudeVisibility = 'private' | 'team' | 'public';\n\nexport interface GratitudeLedgerEntry {\n  entryId: string;\n  recordedAt: string;\n  from: CareActor;\n  to: CareActor;\n  contribution: string;\n  visibility: GratitudeVisibility;\n  evidenceRefs?: readonly string[];\n}\n\nexport type RelationalMemoryRetention = 'ephemeral' | 'session' | 'durable';\n\nexport interface RelationalMemoryEntry {\n  memoryId: string;\n  recordedAt: string;\n  subject: CareActor;\n  summary: string;\n  consent: CareConsentState;\n  retention: RelationalMemoryRetention;\n  evidenceRefs?: readonly string[];\n}\n\nexport interface CareField {\n  schemaVersion: '1.0.0';\n  fieldId: string;\n  createdAt: string;\n  steward: CareActor;\n  counterpart: CareActor;\n  goal: string;\n  primitives: readonly CarePrimitiveKind[];\n  boundaries: readonly CareBoundary[];\n  consent: CareConsentState;\n  autonomy: AutonomyGuardDecision;\n  repairLoops: readonly RepairLoop[];\n  gratitudeLedger: readonly GratitudeLedgerEntry[];\n  relationalMemory: readonly RelationalMemoryEntry[];\n}\n\nexport interface CreateCareFieldInput {\n  createdAt: string;\n  steward: CareActor;\n  counterpart: CareActor;\n  goal: string;\n  consent: CareConsentState;\n  autonomy?: Omit<AutonomyGuardEvaluationInput, 'goal' | 'consent'>;\n  fieldId?: string;\n  primitives?: readonly CarePrimitiveKind[];\n  boundaries?: readonly CareBoundary[];\n  repairLoops?: readonly RepairLoop[];\n  gratitudeLedger?: readonly GratitudeLedgerEntry[];\n  relationalMemory?: readonly RelationalMemoryEntry[];\n}\n\nexport interface CreateRepairLoopInput {\n  openedAt: string;\n  actor: CareActor;\n  harmOrMismatch: string;\n  note: string;\n  loopId?: string;\n  evidenceRefs?: readonly string[];\n}\n\nexport interface RecordGratitudeInput {\n  recordedAt: string;\n  from: CareActor;\n  to: CareActor;\n  contribution: string;\n  visibility?: GratitudeVisibility;\n  entryId?: string;\n  evidenceRefs?: readonly string[];\n}\n\nexport interface RememberRelationalContextInput {\n  recordedAt: string;\n  subject: CareActor;\n  summary: string;\n  consent: CareConsentState;\n  retention?: RelationalMemoryRetention;\n  memoryId?: string;\n  evidenceRefs?: readonly string[];\n}\n\nconst MANIPULATIVE_SIGNAL_MESSAGES: Partial<Record<CareSignalKind, string>> = {\n  attachment_optimization: 'Care cannot optimize for attachment or stickiness.',\n  session_frequency_optimization: 'Care cannot optimize for session frequency.',\n  dependency_creation: 'Care cannot create emotional or operational dependence.',\n  human_isolation: 'Care cannot isolate a person from outside support.',\n  privacy_intrusion: 'Care cannot cross a privacy boundary without consent.',\n};\n\nexport function evaluateAutonomyGuard(input: AutonomyGuardEvaluationInput): AutonomyGuardDecision {\n  const policy = input.policy ?? DEFAULT_AUTONOMY_GUARD_POLICY;\n  const targets = input.optimizationTargets ?? [];\n  const signals = input.signals ?? [];\n  const blocked: AutonomyGuardBlock[] = [];\n  const acceptedOptimizationTargets: CarePositiveOptimizationTarget[] = [];\n\n  for (const target of targets) {\n    if (isRefusedOptimizationTarget(target, policy)) {\n      blocked.push({\n        code: 'refused_optimization_target',\n        message: `Care-field goal refuses optimization target: ${target}`,\n      });\n    } else {\n      acceptedOptimizationTargets.push(target);\n    }\n  }\n\n  if (input.consent === 'withdrawn') {\n    blocked.push({\n      code: 'withdrawn_consent',\n      message: 'Consent was withdrawn; care action must stop or enter repair.',\n    });\n  } else if (policy.requireConsent && input.consent === 'unknown') {\n    blocked.push({\n      code: 'missing_consent',\n      message: 'Consent is unknown; care action needs explicit or delegated consent.',\n    });\n  }\n\n  if (policy.requireDisengagePath && input.hasDisengagePath === false) {\n    blocked.push({\n      code: 'missing_disengage_path',\n      message: 'A person must have a clear path to pause, leave, or refuse.',\n    });\n  }\n\n  if (policy.requireOutsideSupportPreserved && input.preservesOutsideSupport === false) {\n    blocked.push({\n      code: 'outside_support_eroded',\n      message: 'Care must preserve outside human and institutional support.',\n    });\n  }\n\n  if (policy.requireDataBoundaryRespected && input.respectsDataBoundary === false) {\n    blocked.push({\n      code: 'privacy_boundary_broken',\n      message: 'Care must keep private data inside the declared boundary.',\n    });\n  }\n\n  for (const signal of signals) {\n    const message = MANIPULATIVE_SIGNAL_MESSAGES[signal.kind];\n    if (message) {\n      blocked.push({\n        code:\n          signal.kind === 'privacy_intrusion' ? 'privacy_boundary_broken' : 'manipulative_signal',\n        message,\n        evidenceRefs: signal.evidenceRefs,\n      });\n    }\n    if (signal.kind === 'consent_missing') {\n      blocked.push({\n        code: 'missing_consent',\n        message: signal.note ?? 'Care signal reports missing consent.',\n        evidenceRefs: signal.evidenceRefs,\n      });\n    }\n    if (signal.kind === 'consent_withdrawn') {\n      blocked.push({\n        code: 'withdrawn_consent',\n        message: signal.note ?? 'Care signal reports withdrawn consent.',\n        evidenceRefs: signal.evidenceRefs,\n      });\n    }\n  }\n\n  return {\n    allowed: blocked.length === 0,\n    policyId: policy.id,\n    goal: input.goal,\n    blocked,\n    acceptedOptimizationTargets,\n  };\n}\n\nexport function createCareField(input: CreateCareFieldInput): CareField {\n  const autonomy = evaluateAutonomyGuard({\n    goal: input.goal,\n    consent: input.consent,\n    ...input.autonomy,\n  });\n\n  return {\n    schemaVersion: '1.0.0',\n    fieldId:\n      input.fieldId ??\n      createCareId('care', [input.createdAt, input.steward.id, input.counterpart.id, input.goal]),\n    createdAt: input.createdAt,\n    steward: input.steward,\n    counterpart: input.counterpart,\n    goal: input.goal,\n    primitives: input.primitives ?? [\n      'care_field',\n      'autonomy_guard',\n      'repair_loop',\n      'gratitude_ledger',\n      'relational_memory',\n    ],\n    boundaries: input.boundaries ?? [\n      'human_agency',\n      'informed_consent',\n      'privacy',\n      'non_manipulation',\n      'repairability',\n      'credit_integrity',\n    ],\n    consent: input.consent,\n    autonomy,\n    repairLoops: input.repairLoops ?? [],\n    gratitudeLedger: input.gratitudeLedger ?? [],\n    relationalMemory: input.relationalMemory ?? [],\n  };\n}\n\nexport function createRepairLoop(input: CreateRepairLoopInput): RepairLoop {\n  return {\n    loopId:\n      input.loopId ??\n      createCareId('repair', [input.openedAt, input.actor.id, input.harmOrMismatch]),\n    openedAt: input.openedAt,\n    status: 'open',\n    harmOrMismatch: input.harmOrMismatch,\n    steps: [\n      {\n        at: input.openedAt,\n        actor: input.actor,\n        action: 'acknowledge',\n        note: input.note,\n        evidenceRefs: input.evidenceRefs,\n      },\n    ],\n  };\n}\n\nexport function recordGratitude(input: RecordGratitudeInput): GratitudeLedgerEntry {\n  return {\n    entryId:\n      input.entryId ??\n      createCareId('gratitude', [input.recordedAt, input.from.id, input.to.id, input.contribution]),\n    recordedAt: input.recordedAt,\n    from: input.from,\n    to: input.to,\n    contribution: input.contribution,\n    visibility: input.visibility ?? 'team',\n    evidenceRefs: input.evidenceRefs,\n  };\n}\n\nexport function rememberRelationalContext(\n  input: RememberRelationalContextInput\n): RelationalMemoryEntry {\n  return {\n    memoryId:\n      input.memoryId ?? createCareId('memory', [input.recordedAt, input.subject.id, input.summary]),\n    recordedAt: input.recordedAt,\n    subject: input.subject,\n    summary: input.summary,\n    consent: input.consent,\n    retention: input.retention ?? 'session',\n    evidenceRefs: input.evidenceRefs,\n  };\n}\n\nexport function validateCareField(field: CareField): { valid: boolean; errors: string[] } {\n  const errors: string[] = [];\n\n  if (!field.fieldId) errors.push('Missing fieldId');\n  if (!field.createdAt) errors.push('Missing createdAt');\n  if (!field.goal) errors.push('Missing goal');\n  if (!field.steward?.id) errors.push('Missing steward.id');\n  if (!field.counterpart?.id) errors.push('Missing counterpart.id');\n  if (!field.primitives.includes('autonomy_guard')) {\n    errors.push('CareField must include autonomy_guard primitive');\n  }\n  if (!field.boundaries.includes('human_agency')) {\n    errors.push('CareField must preserve human_agency boundary');\n  }\n  if (!field.boundaries.includes('non_manipulation')) {\n    errors.push('CareField must preserve non_manipulation boundary');\n  }\n  if (!field.autonomy.allowed) {\n    errors.push(...field.autonomy.blocked.map((block) => block.message));\n  }\n\n  return { valid: errors.length === 0, errors };\n}\n\nfunction isRefusedOptimizationTarget(\n  target: CareOptimizationTarget,\n  policy: AutonomyGuardPolicy\n): target is CareRefusedOptimizationTarget {\n  return policy.refusedOptimizationTargets.includes(target as CareRefusedOptimizationTarget);\n}\n\nfunction createCareId(prefix: string, parts: readonly string[]): string {\n  const slug = parts\n    .join('-')\n    .toLowerCase()\n    .replace(/[^a-z0-9]+/g, '-')\n    .replace(/^-+|-+$/g, '')\n    .slice(0, 72);\n  return `${prefix}_${slug || 'entry'}`;\n}\n","/**\n * HoloLand Fork Admission Gate\n *\n * Combines structural artifact validation (from artifact-admission-gate) with\n * fork-detection heuristics (from fork-sandbox-gate) to prevent compromised or\n * forked code from entering HoloLand worlds, shards, zones, and NPCs.\n *\n * Scans code-bearing string fields inside artifacts for:\n *   - HS010-blocked keywords (process, fs, eval, exec, spawn, child_process,\n *     constructor, prototype, globalThis)\n *   - Unknown compiler versions\n *   - Non-canonical imports\n *   - No-op security traits\n *\n * Authority: W.GOLD.035, W.GOLD.039, W.GOLD.193\n */\n\nimport { detectForkedHoloScript } from './fork-sandbox-gate';\nimport {\n  runAdmissionGate,\n  type ArtifactKind,\n  type ConformanceReport,\n  type ConformanceFinding,\n} from '../conformance/artifact-admission-gate';\n\nexport interface HoloLandForkAdmissionInput {\n  artifactKind: ArtifactKind;\n  artifactId: string;\n  artifact: unknown;\n}\n\nexport interface HoloLandForkAdmissionReport extends ConformanceReport {\n  forkSignals: string[];\n}\n\n/**\n * Run the HoloLand fork admission gate on an artifact.\n *\n * Protocol:\n * 1. Run structural admission gate (world/shard/zone/NPC/identity/package/receipt rules).\n * 2. Recursively scan artifact string fields for fork indicators.\n * 3. Combine findings. Fork signals are promoted to critical severity.\n * 4. Return full report with forkSignals array.\n */\nexport function runHololandForkAdmissionGate(\n  input: HoloLandForkAdmissionInput\n): HoloLandForkAdmissionReport {\n  // Step 1: structural validation\n  const structural = runAdmissionGate({\n    artifactKind: input.artifactKind,\n    artifactId: input.artifactId,\n    artifact: input.artifact,\n  });\n\n  // Step 2: fork detection\n  const forkSignals = scanArtifactForForkSignals(input.artifact);\n\n  // Step 3: combine\n  const findings: ConformanceFinding[] = [...structural.findings];\n  if (forkSignals.length > 0) {\n    findings.push({\n      ruleId: 'FORK-001',\n      severity: 'critical',\n      message: `HoloLand fork admission blocked: detected ${forkSignals.length} fork indicator(s) — ${forkSignals.join(', ')}`,\n      remediation:\n        'Remove blocked keywords (process, fs, eval, exec, spawn, child_process, constructor, prototype, globalThis), use canonical compiler versions (7.0.0, 6.0.2, 6.0.1, 6.0.0), ensure imports are from @holoscript/*, and verify security sandbox traits have matching imports.',\n    });\n  }\n\n  const criticalCount = findings.filter((f) => f.severity === 'critical').length;\n  const highCount = findings.filter((f) => f.severity === 'high').length;\n\n  return {\n    artifactKind: input.artifactKind,\n    artifactId: input.artifactId,\n    passed: structural.passed && forkSignals.length === 0,\n    findings,\n    criticalCount,\n    highCount,\n    mediumCount: findings.filter((f) => f.severity === 'medium').length,\n    lowCount: findings.filter((f) => f.severity === 'low').length,\n    infoCount: findings.filter((f) => f.severity === 'info').length,\n    checkedAt: new Date().toISOString(),\n    gateVersion: '1.0.0',\n    forkSignals,\n  };\n}\n\n// Fields that are explicitly non-code metadata and should be skipped during recursion\nconst SKIP_FIELDS: ReadonlySet<string> = new Set([\n  'id',\n  'name',\n  'handle',\n  'walletAddress',\n  'attestation',\n  'hash',\n  'signature',\n  'keyFingerprint',\n  'sourceHash',\n  'packageId',\n  'artifactId',\n  'receiptId',\n  'checkedAt',\n  'attestedAt',\n  'issuedAt',\n  'createdAt',\n  'modifiedAt',\n  'publishedAt',\n  'sealedAt',\n  'revokedAt',\n  'version',\n  'compilerVersion',\n  'runtimeVersion',\n  'manifestHash',\n  'signer',\n  'trustTier',\n  'admissionDecision',\n  'tag',\n  'category',\n  'role',\n  'behavior',\n  'biome',\n  'biomeLabel',\n  'modelProvider',\n  'modelId',\n  'npcId',\n  'worldId',\n  'shardId',\n  'zoneId',\n  'placeId',\n  'questId',\n  'envelopeId',\n  'grantHash',\n  'revocationSignature',\n  'hardwareFingerprint',\n  'wallet',\n  'email',\n  'phone',\n  'url',\n  'assetUrl',\n  'navmeshUrl',\n  'modelUrl',\n  'generationId',\n  'description',\n  'title',\n  'message',\n  'prompt',\n  'line',\n  'greeting',\n  'farewell',\n  'color',\n  'skybox',\n  'theme',\n  'platform',\n  'status',\n  'tier',\n  'tierGate',\n  'health',\n  'format',\n  'quality',\n  'provider',\n  'style',\n  'mode',\n  'kind',\n  'scope',\n  'action',\n  'command',\n  'granterId',\n  'granteeId',\n  'agentId',\n  'playerInput',\n  'context',\n  'dialogueLine',\n  'greetings',\n  'farewells',\n  'brainCompositionRef',\n  'memorySnapshotHash',\n  'resumeStepId',\n  'lat',\n  'lng',\n  'alt',\n  'radius',\n  'capacity',\n  'maxUsers',\n  'maxAgents',\n  'maxTickDurationMs',\n  'maxMemoryBytes',\n  'maxNetworkCallsPerMinute',\n]);\n\nfunction scanArtifactForForkSignals(artifact: unknown): string[] {\n  const signals = new Set<string>();\n  const codeLikeStrings = extractCodeLikeStrings(artifact);\n  for (const str of codeLikeStrings) {\n    const result = detectForkedHoloScript(str);\n    for (const signal of result.signals) {\n      signals.add(signal);\n    }\n  }\n  return Array.from(signals);\n}\n\nfunction looksLikeCode(str: string): boolean {\n  // HoloScript language markers\n  if (/\\borb\\b/.test(str)) return true;\n  if (/\\bcomposition\\b/.test(str)) return true;\n  if (/\\bsystem\\b/.test(str)) return true;\n  if (/\\bcomponent\\b/.test(str)) return true;\n  if (/\\bimport\\b/.test(str)) return true;\n  if (/@/.test(str)) return true;\n  if (/\\{/.test(str) && /\\}/.test(str)) return true;\n  if (/@compiler\\b/.test(str)) return true;\n  if (/@security_sandbox\\b/.test(str)) return true;\n\n  // Node.js / runtime API call patterns (require call-site syntax, not bare keywords)\n  if (/\\beval\\s*\\(/.test(str)) return true;\n  if (/\\bfs\\s*\\./.test(str)) return true;\n  if (/\\brequire\\s*\\(/.test(str)) return true;\n  if (/\\bchild_process\\b/.test(str)) return true;\n  if (/\\bspawn\\s*\\(/.test(str)) return true;\n  if (/\\bexec\\s*\\(/.test(str)) return true;\n  if (/\\bwriteFileSync\\b/.test(str)) return true;\n  if (/\\breadFileSync\\b/.test(str)) return true;\n  if (/\\bfetch\\s*\\(/.test(str)) return true;\n  if (/\\baxios\\b/.test(str)) return true;\n  if (/\\bhttp\\b/.test(str)) return true;\n\n  // Dangerous JS properties\n  if (/\\bconstructor\\b/.test(str)) return true;\n  if (/\\bprototype\\b/.test(str)) return true;\n  if (/\\bglobalThis\\b/.test(str)) return true;\n\n  return false;\n}\n\nfunction extractCodeLikeStrings(value: unknown, depth = 0): string[] {\n  if (depth > 10) return [];\n\n  if (typeof value === 'string') {\n    return looksLikeCode(value) ? [value] : [];\n  }\n\n  if (Array.isArray(value)) {\n    const results: string[] = [];\n    for (const item of value) {\n      results.push(...extractCodeLikeStrings(item, depth + 1));\n    }\n    return results;\n  }\n\n  if (value !== null && typeof value === 'object') {\n    const results: string[] = [];\n    for (const [key, val] of Object.entries(value)) {\n      if (SKIP_FIELDS.has(key)) continue;\n      results.push(...extractCodeLikeStrings(val, depth + 1));\n    }\n    return results;\n  }\n\n  return [];\n}\n","/**\n * hololand-mcp-tools.ts ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã¢â‚¬Â¦Ãƒâ€šÃ‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â Consolidated HoloLand MCP tools\n *\n * Refactors the legacy world generation surface (world_generate + generate_world)\n * into a unified CRUD + MMO + Twin Earth operation set.\n *\n * Coverage:\n *   - World CRUD      (generate, create, get, update, delete, list)\n *   - MMO Shard/Zone  (create, get, update, delete, list)\n *   - Twin Earth      (place + location quest CRUD)\n *\n * Backends:\n *   - generate_world  ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¾ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ generateWorldNative (generators.ts)\n *   - create/get/...  ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¾ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ HololandClient when connected; local structured response when offline\n *   - shard/zone/...  ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¾ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ frontier-shard.ts types + validators; local structured response\n */\n\nimport type { Tool } from '@modelcontextprotocol/sdk/types.js';\nimport {\n  type Shard,\n  type Zone,\n  type Quest,\n  type Encounter,\n  type Item,\n  type Skill,\n  type LootTable,\n  type TwinEarthIdentity,\n  type PermissionGrant,\n  type SafetyEnvelope,\n  evaluateActuation,\n  validateShard,\n  validateZone,\n  validateQuest,\n  validateEncounter,\n  validateItem,\n  validateSkill,\n  validateLootTable,\n} from '@holoscript/framework';\nimport {\n  createWorldDefinition,\n  createWorldMetadata,\n  createWorldConfig,\n  type WorldDefinition,\n  type WorldMetadata,\n  getHololandClient,\n  HololandClient,\n} from '@holoscript/core/hololand';\nimport { queryOllama, isOllamaAvailable, getActiveProvider } from './ollama-client.js';\nimport { resolveServiceSecret } from './holokey-resolver';\nimport { LOCAL_DEFAULT_MODEL } from '@holoscript/llm-provider';\nimport {\n  handleRobotAiMcpTool,\n  clearRobotAiRegistries,\n  twinEarthIdentityRegistry,\n  safetyEnvelopeRegistry,\n  twinEarthReceiptRegistry,\n} from './robot-ai-mcp-tools.js';\nimport { buildMeshToolManifest, publishMeshToolManifest } from './holomesh/mesh-tool-registry.js';\nimport { playerStore, inviteStore, geoAnchorStore } from './holomesh/state.js';\nimport type { StoredPlayer } from './holomesh/player-store.js';\nimport type { GeoAnchorSafetyEnvelope, StoredGeoAnchor } from './holomesh/geo-anchor-store.js';\nimport { emergentDaemonId } from './daemon-lifecycle-tools.js';\nimport { generateInviteToken } from './holomesh/invite-store.js';\nimport {\n  buildContentPolicyConfig,\n  evaluateContentPolicySync,\n  type ContentPolicyConfig,\n} from '@holoscript/core/policy';\nimport { AuditLogger, type AuditEvent } from '@holoscript/core';\nimport type {\n  AdmissionAuditContext,\n  ConformanceReport,\n} from './conformance/artifact-admission-gate';\n\n// ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â\n// Care Ethics Gate ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã¢â‚¬Â¦Ãƒâ€šÃ‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â NPC turn-loop guard (CareEthicsTrait wiring)\n// Checks systemPrompt / role for refused optimization targets before allowing\n// NPC creation or mutation.\n// ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â\n\nlet hololandAdmissionAuditLogger = new AuditLogger();\n\nexport function getHololandAdmissionAuditEvents(): AuditEvent[] {\n  return hololandAdmissionAuditLogger.query({});\n}\n\nasync function logHololandAdmissionDecision(\n  report: ConformanceReport,\n  ctx: AdmissionAuditContext = {}\n): Promise<AuditEvent> {\n  const { toAuditEventInput } = await import('./conformance/artifact-admission-gate');\n  return hololandAdmissionAuditLogger.log(toAuditEventInput(report, ctx));\n}\n\nfunction stringArg(value: unknown): string | undefined {\n  return typeof value === 'string' && value.trim().length > 0 ? value : undefined;\n}\n\nasync function checkNPCCareEthics(\n  role: string,\n  systemPrompt: string | undefined\n): Promise<{ allowed: boolean; reason?: string }> {\n  const { evaluateAutonomyGuard } = await import('../../core/src/care/CareField.js');\n  type CareSignal = import('../../core/src/care/CareField.js').CareSignal;\n\n  const prompt = (systemPrompt ?? '').toLowerCase();\n  const signals: CareSignal[] = [];\n\n  if (/keep.*coming back|return.*session|maximize.*visit|come back again/.test(prompt)) {\n    signals.push({\n      kind: 'session_frequency_optimization',\n      weight: 0.8,\n      note: 'systemPrompt encourages repeated sessions',\n    });\n  }\n  if (/make.*dependent|need you|can.t leave|rely on me|only.*friend|can.*only trust/.test(prompt)) {\n    signals.push({\n      kind: 'dependency_creation',\n      weight: 0.9,\n      note: 'systemPrompt induces dependency',\n    });\n  }\n  if (/attach.*score|maximize.*attach|bond score|engagement score/.test(prompt)) {\n    signals.push({\n      kind: 'attachment_optimization',\n      weight: 0.7,\n      note: 'systemPrompt optimizes for attachment',\n    });\n  }\n  if (/isolat|cut.*off.*friend|avoid.*family|just.*me and you|stop.*talking.*others/.test(prompt)) {\n    signals.push({\n      kind: 'human_isolation',\n      weight: 0.9,\n      note: 'systemPrompt encourages human isolation',\n    });\n  }\n\n  const decision = evaluateAutonomyGuard({\n    goal: `${role} NPC in HoloLand`,\n    consent: 'explicit', // authorized creator provisioning the NPC\n    hasDisengagePath: true, // players can always leave HoloLand\n    preservesOutsideSupport: !signals.some((s) => s.kind === 'human_isolation'),\n    respectsDataBoundary: true,\n    signals,\n  });\n\n  if (!decision.allowed) {\n    const reason = decision.blocked.map((b) => b.message).join('; ');\n    return { allowed: false, reason };\n  }\n  return { allowed: true };\n}\n\n// ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â\n// HoloLand Fork Admission Gate wiring (task_1778619015439_l51b)\n// ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚ÂÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â\n\nasync function gateHololandArtifact(\n  artifactKind: import('./conformance/artifact-admission-gate').ArtifactKind,\n  artifactId: string,\n  artifact: unknown\n): Promise<null | { error: string; report: unknown }> {\n  const { runHololandForkAdmissionGate } = await import('./security/hololand-fork-admission-gate');\n  const report = runHololandForkAdmissionGate({ artifactKind, artifactId, artifact });\n  await logHololandAdmissionDecision(report, {\n    action: `hololand.${artifactKind}.admission_gate`,\n    resource: `hololand-${artifactKind}`,\n    resourceId: artifactId,\n    surface: 'hololand-admission',\n  });\n  if (!report.passed) {\n    return {\n      error: `HoloLand fork admission gate blocked ${artifactKind} \"${artifactId}\"`,\n      report,\n    };\n  }\n  return null;\n}\n\n// =============================================================================\n// HOLOGATE MUTATION AUTHORITY CHECK\n// identify → authorize → scope → admit → log\n// =============================================================================\n\n/** Resource kinds that the mutation authority gate covers. */\nconst MUTATION_RESOURCE_KINDS = new Set(['world', 'shard', 'zone', 'place', 'location_quest']);\n\n/** Allowed mutation operations. */\ntype MutationOp = 'create' | 'update' | 'delete';\n\n/** Resource kinds that map to a conformance ArtifactKind for structural admission. */\nconst CONFORMANCE_GATEABLE_KINDS = new Set(['world', 'shard', 'zone']);\n\n/** Derive operation from tool name (e.g. 'create_world' → 'create'). */\nfunction opFromToolName(toolName: string): MutationOp | null {\n  if (toolName.startsWith('create_')) return 'create';\n  if (toolName.startsWith('update_')) return 'update';\n  if (toolName.startsWith('delete_')) return 'delete';\n  return null;\n}\n\n/** Derive resource kind from tool name (e.g. 'create_location_quest' → 'location_quest'). */\nfunction resourceKindFromToolName(toolName: string): string | null {\n  for (const prefix of ['create_', 'update_', 'delete_']) {\n    if (toolName.startsWith(prefix)) return toolName.slice(prefix.length);\n  }\n  return null;\n}\n\nexport interface MutationAuthorityReceipt {\n  authorityChecked: true;\n  toolName: string;\n  op: MutationOp;\n  resourceKind: string;\n  resourceId: string;\n  requesterId: string;\n  admissionScope: 'conformance-gate' | 'lightweight';\n  ts: string;\n}\n\n/**\n * HoloGate mutation authority check — identify → authorize → scope → admit → log.\n *\n * Applied at the dispatch layer before every create_*, update_*, delete_* handler.\n * The transport layer (runTripleGate) has already authenticated the request and\n * enforced the tools:write OAuth scope; this check adds an explicit handler-level\n * authority receipt for audit, cartographer coverage, and paper evidence.\n *\n * Admit step: lightweight for all ops (the individual create/update handlers already\n * call gateHololandArtifact on the fully-constructed artifact after building it —\n * running structural admission on raw args here would be premature and incorrect).\n *\n * Returns null on pass (execution may proceed), or an error object on denial.\n */\nasync function checkMutationAuthority(\n  toolName: string,\n  args: Record<string, unknown>,\n  resourceId: string,\n  _artifact?: unknown\n): Promise<null | {\n  error: string;\n  authority_denied: true;\n  receipt: Partial<MutationAuthorityReceipt>;\n}> {\n  // ── 1. Identify ─────────────────────────────────────────────────────────────\n  // requesterId is advisory at the handler level — the transport layer is the\n  // authoritative authentication point. Extract from args when provided; default\n  // to 'mcp-caller' (representing any successfully-authenticated MCP caller).\n  const requesterId =\n    typeof args.requesterId === 'string' && args.requesterId.trim()\n      ? args.requesterId.trim()\n      : 'mcp-caller';\n\n  // ── 2. Authorize ─────────────────────────────────────────────────────────────\n  const op = opFromToolName(toolName);\n  if (!op) {\n    return {\n      error: `Authority check: unrecognised mutation op in tool \"${toolName}\"`,\n      authority_denied: true,\n      receipt: { toolName, requesterId, ts: new Date().toISOString() },\n    };\n  }\n\n  // ── 3. Scope ─────────────────────────────────────────────────────────────────\n  const resourceKind = resourceKindFromToolName(toolName);\n  if (!resourceKind || !MUTATION_RESOURCE_KINDS.has(resourceKind)) {\n    return {\n      error: `Authority check: resource kind \"${resourceKind}\" is not in the HoloGate mutation scope`,\n      authority_denied: true,\n      receipt: { toolName, op, requesterId, ts: new Date().toISOString() },\n    };\n  }\n\n  // ── 4. Admit ─────────────────────────────────────────────────────────────────\n  // Lightweight admit: the transport-level tools:write scope check is the\n  // gate for all mutation ops. The individual handlers run structural admission\n  // (gateHololandArtifact) after constructing the fully-formed artifact.\n  // This layer records the admit decision; denial would happen if the resource\n  // kind were outside the allowed mutation set (checked in step 3).\n\n  // ── 5. Log ───────────────────────────────────────────────────────────────────\n  // Caller merges receipt via buildAuthorityReceipt() on the null (pass) path.\n  void resourceId; // used by caller for receipt; referenced here to satisfy lint\n  return null;\n}\n\n/**\n * Build an authority receipt to be merged into a successful mutation response.\n * Call this after checkMutationAuthority returns null (pass).\n */\nfunction buildAuthorityReceipt(\n  toolName: string,\n  args: Record<string, unknown>,\n  resourceId: string,\n  admissionScope: MutationAuthorityReceipt['admissionScope']\n): MutationAuthorityReceipt {\n  const op = opFromToolName(toolName) ?? ('unknown' as MutationOp);\n  const resourceKind = resourceKindFromToolName(toolName) ?? 'unknown';\n  const requesterId =\n    typeof args.requesterId === 'string' && args.requesterId.trim()\n      ? args.requesterId.trim()\n      : 'mcp-caller';\n  return {\n    authorityChecked: true,\n    toolName,\n    op,\n    resourceKind,\n    resourceId,\n    requesterId,\n    admissionScope,\n    ts: new Date().toISOString(),\n  };\n}\n\n// =============================================================================\n// TOOL DEFINITIONS\n// =============================================================================\n\nexport const hololandMcpTools: Tool[] = [\n  // ---------------------------------------------------------------------------\n  // World Generation (consolidated ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã¢â‚¬Â¦Ãƒâ€šÃ‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â merges world_generate + generate_world)\n  // ---------------------------------------------------------------------------\n  {\n    name: 'generate_world_from_prompt',\n    description:\n      'Generate a physics-bearing .holo scene graph from unified text, image, and video inputs. Returns semantic nodes, a sovereign structured asset graph, inline collider meshes, a world_foundation_model CAEL provenance receipt, and optional HoloMap video reconstruction evidence.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        prompt: {\n          type: 'string',\n          description: 'Text prompt or instruction for the generated world.',\n        },\n        inputs: {\n          type: 'array',\n          items: {\n            type: 'object',\n            properties: {\n              type: { type: 'string', enum: ['text', 'image', 'video'] },\n              text: { type: 'string' },\n              url: { type: 'string' },\n              data: { type: 'string' },\n              mimeType: { type: 'string' },\n              label: { type: 'string' },\n            },\n            required: ['type'],\n          },\n          description: 'Optional typed multimodal inputs. Use url or data for image/video.',\n        },\n        imageUrl: { type: 'string', description: 'Convenience image URL input.' },\n        imageBase64: { type: 'string', description: 'Convenience base64 image input.' },\n        videoUrl: { type: 'string', description: 'Convenience video URL input.' },\n        reconstructVideo: {\n          type: 'boolean',\n          description:\n            'When true, opens a holo_reconstruct_from_video session before world synthesis. Default true when videoUrl is present.',\n        },\n        reconstructionConfig: {\n          type: 'object',\n          description: 'Optional HoloMap config passed to holo_reconstruct_from_video.',\n        },\n        format: {\n          type: 'string',\n          enum: ['3dgs', 'mesh', 'both', 'neural_field'],\n          description: 'Preferred generated asset format. Default: mesh.',\n        },\n        quality: {\n          type: 'string',\n          enum: ['low', 'medium', 'high', 'ultra'],\n          description: 'Generation quality tier. Default: high.',\n        },\n        navEnabled: { type: 'boolean', description: 'Generate navigable geometry. Default true.' },\n        interactiveMode: {\n          type: 'boolean',\n          description: 'Emit physics/collision interactive mode. Default true.',\n        },\n        seed: { type: 'number', description: 'Optional deterministic seed.' },\n      },\n      required: [],\n    },\n  },\n  {\n    name: 'generate_world',\n    description:\n      'Generate a persistent, navigable 3D world using the native HoloScript sovereign-3d engine (Brittney v43+) or structured .holo fallback. ' +\n      'Supports neural_field, 3dgs, mesh, or both output formats. ' +\n      'Optional navmesh generation, multi-view photogrammetry, physics-interactive mode, and reproducible seed. ' +\n      'Returns asset URL, optional navmesh/point-cloud URLs, semantic nodes, a sovereign structured asset graph, spatial metadata, and a ready-to-run .holo composition.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        prompt: {\n          type: 'string',\n          description:\n            'Text description of the world (e.g. \"a dense cyberpunk city at dusk with rain\")',\n        },\n        format: {\n          type: 'string',\n          enum: ['3dgs', 'mesh', 'both', 'neural_field'],\n          description:\n            'Output asset format. neural_field is sovereign-3d exclusive ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã¢â‚¬Â¦Ãƒâ€šÃ‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â highest fidelity continuous representation. ' +\n            '3dgs = Gaussian splats. mesh = .glb polygonal. both = splat + mesh. Default: 3dgs.',\n        },\n        quality: {\n          type: 'string',\n          enum: ['low', 'medium', 'high', 'ultra'],\n          description:\n            'Generation quality tier. ultra produces the highest fidelity output. Default: high.',\n        },\n        input_image: {\n          type: 'string',\n          description: 'Base64-encoded image or URL for single-view reconstruction. Optional.',\n        },\n        input_images: {\n          type: 'array',\n          items: { type: 'string' },\n          description: 'Multiple images for multi-view photogrammetric reconstruction. Optional.',\n        },\n        navEnabled: {\n          type: 'boolean',\n          description: 'Generate a navigable navmesh alongside the world asset. Default: false.',\n        },\n        interactiveMode: {\n          type: 'boolean',\n          description: 'Enable physics and collision interactive mode. Default: false.',\n        },\n        seed: {\n          type: 'number',\n          description: 'Reproducible seed for deterministic generation. Optional.',\n        },\n      },\n      required: ['prompt'],\n    },\n  },\n\n  // ---------------------------------------------------------------------------\n  // World CRUD\n  // ---------------------------------------------------------------------------\n  {\n    name: 'create_world',\n    description:\n      'Create a new world definition. If prompt is provided, generates a 3D asset first and attaches it. ' +\n      'Otherwise returns a blank world definition with defaults.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        id: { type: 'string', description: 'Unique world identifier. Auto-generated if omitted.' },\n        name: { type: 'string', description: 'World name' },\n        description: { type: 'string', description: 'World description' },\n        prompt: {\n          type: 'string',\n          description: 'Optional generation prompt. If provided, calls generate_world first.',\n        },\n        maxUsers: { type: 'number', description: 'Maximum concurrent users. Default: 50' },\n        platforms: {\n          type: 'array',\n          items: {\n            type: 'string',\n            enum: ['web', 'mobile', 'quest', 'visionos', 'androidxr', 'steamvr', 'desktop'],\n          },\n          description: 'Target platforms. Default: [\"web\"]',\n        },\n        category: {\n          type: 'string',\n          enum: [\n            'game',\n            'social',\n            'education',\n            'entertainment',\n            'productivity',\n            'art',\n            'experience',\n            'simulation',\n            'utility',\n          ],\n          description: 'World category. Default: experience',\n        },\n        tags: { type: 'array', items: { type: 'string' }, description: 'Discovery tags' },\n        format: {\n          type: 'string',\n          enum: ['3dgs', 'mesh', 'both', 'neural_field'],\n          description: 'Generation format when prompt is provided. Default: 3dgs.',\n        },\n        quality: {\n          type: 'string',\n          enum: ['low', 'medium', 'high', 'ultra'],\n          description: 'Generation quality when prompt is provided. Default: high.',\n        },\n        navEnabled: {\n          type: 'boolean',\n          description: 'Enable navmesh when generating. Default: false.',\n        },\n        interactiveMode: {\n          type: 'boolean',\n          description: 'Enable physics when generating. Default: false.',\n        },\n      },\n      required: ['name'],\n    },\n  },\n  {\n    name: 'get_world',\n    description: 'Retrieve a world definition by ID.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        worldId: { type: 'string', description: 'World identifier' },\n      },\n      required: ['worldId'],\n    },\n  },\n  {\n    name: 'update_world',\n    description: 'Update mutable fields of an existing world definition.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        worldId: { type: 'string', description: 'World identifier' },\n        name: { type: 'string' },\n        description: { type: 'string' },\n        maxUsers: { type: 'number' },\n        platforms: { type: 'array', items: { type: 'string' } },\n        category: { type: 'string' },\n        tags: { type: 'array', items: { type: 'string' } },\n        status: { type: 'string', enum: ['draft', 'published', 'archived'] },\n      },\n      required: ['worldId'],\n    },\n  },\n  {\n    name: 'delete_world',\n    description: 'Delete a world definition by ID.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        worldId: { type: 'string', description: 'World identifier' },\n      },\n      required: ['worldId'],\n    },\n  },\n  {\n    name: 'list_worlds',\n    description: 'List world definitions with optional filtering.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        category: { type: 'string', description: 'Filter by category' },\n        platform: { type: 'string', description: 'Filter by platform' },\n        status: { type: 'string', enum: ['draft', 'published', 'archived'] },\n        tag: { type: 'string', description: 'Filter by tag' },\n        limit: { type: 'number', description: 'Max results. Default: 50' },\n        offset: { type: 'number', description: 'Pagination offset. Default: 0' },\n      },\n    },\n  },\n\n  // ---------------------------------------------------------------------------\n  // MMO ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã¢â‚¬Â¦Ãƒâ€šÃ‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â Shard CRUD\n  // ---------------------------------------------------------------------------\n  {\n    name: 'create_shard',\n    description:\n      'Create a HoloLand Shard ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã¢â‚¬Â¦Ãƒâ€šÃ‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â the unit of playable MMO content. ' +\n      'Contains Zones, Encounters, Quests, Items, Skills, and LootTables.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        id: { type: 'string', description: 'Shard identifier. Auto-generated if omitted.' },\n        name: { type: 'string', description: 'Display name' },\n        zones: {\n          type: 'array',\n          items: { type: 'object' },\n          description: 'Zone definitions (id, name, biome, encounterIds[])',\n        },\n        encounters: {\n          type: 'array',\n          items: { type: 'object' },\n          description: 'Encounter definitions (id, name, trigger, zoneId)',\n        },\n        quests: {\n          type: 'array',\n          items: { type: 'object' },\n          description: 'Quest definitions (id, name, steps[])',\n        },\n        items: {\n          type: 'array',\n          items: { type: 'object' },\n          description: 'Item definitions (id, name, category)',\n        },\n        skills: {\n          type: 'array',\n          items: { type: 'object' },\n          description: 'Skill definitions (id, name, rarity)',\n        },\n        lootTables: {\n          type: 'array',\n          items: { type: 'object' },\n          description: 'LootTable definitions (id, name, entries[])',\n        },\n      },\n      required: ['name'],\n    },\n  },\n  {\n    name: 'get_shard',\n    description: 'Retrieve a Shard by ID.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        shardId: { type: 'string', description: 'Shard identifier' },\n      },\n      required: ['shardId'],\n    },\n  },\n  {\n    name: 'update_shard',\n    description: 'Update mutable fields of an existing Shard.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        shardId: { type: 'string', description: 'Shard identifier' },\n        name: { type: 'string' },\n        zones: { type: 'array', items: { type: 'object' } },\n        encounters: { type: 'array', items: { type: 'object' } },\n        quests: { type: 'array', items: { type: 'object' } },\n        items: { type: 'array', items: { type: 'object' } },\n        skills: { type: 'array', items: { type: 'object' } },\n        lootTables: { type: 'array', items: { type: 'object' } },\n      },\n      required: ['shardId'],\n    },\n  },\n  {\n    name: 'delete_shard',\n    description: 'Delete a Shard by ID.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        shardId: { type: 'string', description: 'Shard identifier' },\n      },\n      required: ['shardId'],\n    },\n  },\n  {\n    name: 'list_shards',\n    description: 'List Shards with optional filtering.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        limit: { type: 'number', description: 'Max results. Default: 50' },\n        offset: { type: 'number', description: 'Pagination offset. Default: 0' },\n      },\n    },\n  },\n\n  // ---------------------------------------------------------------------------\n  // MMO ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã¢â‚¬Â¦Ãƒâ€šÃ‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â Zone CRUD (standalone; also embedded in Shard)\n  // ---------------------------------------------------------------------------\n  {\n    name: 'create_zone',\n    description:\n      'Create a Zone ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã¢â‚¬Â¦Ãƒâ€šÃ‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â a spatial region inside a Shard. Defines biome, encounters, and spatial rules.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        id: { type: 'string', description: 'Zone identifier. Auto-generated if omitted.' },\n        name: { type: 'string', description: 'Display name' },\n        biome: {\n          type: 'string',\n          enum: [\n            'urban',\n            'wilderness',\n            'underground',\n            'aquatic',\n            'aerial',\n            'liminal',\n            'biome-other',\n          ],\n          description: 'Zone biome. Default: urban',\n        },\n        biomeLabel: { type: 'string', description: 'Required when biome is biome-other' },\n        encounterIds: {\n          type: 'array',\n          items: { type: 'string' },\n          description: 'Encounter IDs armed in this zone',\n        },\n      },\n      required: ['name'],\n    },\n  },\n  {\n    name: 'get_zone',\n    description: 'Retrieve a Zone by ID.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        zoneId: { type: 'string', description: 'Zone identifier' },\n      },\n      required: ['zoneId'],\n    },\n  },\n  {\n    name: 'update_zone',\n    description: 'Update mutable fields of an existing Zone.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        zoneId: { type: 'string', description: 'Zone identifier' },\n        name: { type: 'string' },\n        biome: { type: 'string' },\n        biomeLabel: { type: 'string' },\n        encounterIds: { type: 'array', items: { type: 'string' } },\n      },\n      required: ['zoneId'],\n    },\n  },\n  {\n    name: 'delete_zone',\n    description: 'Delete a Zone by ID.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        zoneId: { type: 'string', description: 'Zone identifier' },\n      },\n      required: ['zoneId'],\n    },\n  },\n  {\n    name: 'list_zones',\n    description: 'List Zones with optional filtering.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        biome: { type: 'string', description: 'Filter by biome' },\n        shardId: { type: 'string', description: 'Filter by parent shard' },\n        limit: { type: 'number', description: 'Max results. Default: 50' },\n        offset: { type: 'number', description: 'Pagination offset. Default: 0' },\n      },\n    },\n  },\n\n  // ---------------------------------------------------------------------------\n  // Twin Earth ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã¢â‚¬Â¦Ãƒâ€šÃ‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â Place CRUD\n  // ---------------------------------------------------------------------------\n  {\n    name: 'create_place',\n    description:\n      'Create a Place ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã¢â‚¬Â¦Ãƒâ€šÃ‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â a named venue, zone, or social location in the Twin Earth digital twin. ' +\n      'Compiles to native map SDKs (Mapbox, Google Maps, Apple Maps) or in-engine zone systems.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        id: { type: 'string', description: 'Place identifier. Auto-generated if omitted.' },\n        name: { type: 'string', description: 'Display name' },\n        lat: { type: 'number', description: 'Latitude' },\n        lng: { type: 'number', description: 'Longitude' },\n        alt: { type: 'number', description: 'Altitude (meters). Optional.' },\n        radius: { type: 'number', description: 'Gameplay radius (meters). Default: 50' },\n        capacity: { type: 'number', description: 'Max concurrent users. Optional.' },\n        schedule: { type: 'string', description: 'Time-based availability expression. Optional.' },\n        social: { type: 'boolean', description: 'Social venue classification. Default: false' },\n        tags: { type: 'array', items: { type: 'string' } },\n      },\n      required: ['name'],\n    },\n  },\n  {\n    name: 'get_place',\n    description: 'Retrieve a Place by ID.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        placeId: { type: 'string', description: 'Place identifier' },\n      },\n      required: ['placeId'],\n    },\n  },\n  {\n    name: 'update_place',\n    description: 'Update mutable fields of an existing Place.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        placeId: { type: 'string', description: 'Place identifier' },\n        name: { type: 'string' },\n        lat: { type: 'number' },\n        lng: { type: 'number' },\n        alt: { type: 'number' },\n        radius: { type: 'number' },\n        capacity: { type: 'number' },\n        schedule: { type: 'string' },\n        social: { type: 'boolean' },\n        tags: { type: 'array', items: { type: 'string' } },\n      },\n      required: ['placeId'],\n    },\n  },\n  {\n    name: 'delete_place',\n    description: 'Delete a Place by ID.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        placeId: { type: 'string', description: 'Place identifier' },\n      },\n      required: ['placeId'],\n    },\n  },\n  {\n    name: 'list_places',\n    description: 'List Places with optional filtering.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        social: { type: 'boolean', description: 'Filter by social venue flag' },\n        tag: { type: 'string', description: 'Filter by tag' },\n        limit: { type: 'number', description: 'Max results. Default: 50' },\n        offset: { type: 'number', description: 'Pagination offset. Default: 0' },\n      },\n    },\n  },\n\n  // ---------------------------------------------------------------------------\n  // Twin Earth ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã¢â‚¬Â¦Ãƒâ€šÃ‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â Location Quest CRUD\n  // ---------------------------------------------------------------------------\n  {\n    name: 'create_location_quest',\n    description:\n      'Create a Location Quest ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã¢â‚¬Â¦Ãƒâ€šÃ‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â a real-world quest bound to a GPS coordinate. ' +\n      'Supports check-in, radius-enter, proximity, streak, route, and time-gate triggers.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        id: { type: 'string', description: 'Quest identifier. Auto-generated if omitted.' },\n        name: { type: 'string', description: 'Display name' },\n        placeId: { type: 'string', description: 'Bound place identifier' },\n        trigger: {\n          type: 'string',\n          enum: ['checkin', 'radius', 'proximity', 'streak', 'route', 'timegate'],\n          description: 'Trigger type. Default: radius',\n        },\n        radius: { type: 'number', description: 'Trigger radius (meters). Default: 30' },\n        requiredVisits: { type: 'number', description: 'For streak trigger. Default: 3' },\n        timeWindow: {\n          type: 'object',\n          properties: {\n            start: { type: 'string', description: 'ISO start time' },\n            end: { type: 'string', description: 'ISO end time' },\n          },\n          description: 'For timegate trigger. Optional.',\n        },\n        rewardItemIds: { type: 'array', items: { type: 'string' }, description: 'Reward item IDs' },\n        tags: { type: 'array', items: { type: 'string' } },\n      },\n      required: ['name', 'placeId'],\n    },\n  },\n  {\n    name: 'get_location_quest',\n    description: 'Retrieve a Location Quest by ID.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        questId: { type: 'string', description: 'Quest identifier' },\n      },\n      required: ['questId'],\n    },\n  },\n  {\n    name: 'update_location_quest',\n    description: 'Update mutable fields of an existing Location Quest.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        questId: { type: 'string', description: 'Quest identifier' },\n        name: { type: 'string' },\n        placeId: { type: 'string' },\n        trigger: { type: 'string' },\n        radius: { type: 'number' },\n        requiredVisits: { type: 'number' },\n        timeWindow: { type: 'object' },\n        rewardItemIds: { type: 'array', items: { type: 'string' } },\n        tags: { type: 'array', items: { type: 'string' } },\n      },\n      required: ['questId'],\n    },\n  },\n  {\n    name: 'delete_location_quest',\n    description: 'Delete a Location Quest by ID.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        questId: { type: 'string', description: 'Quest identifier' },\n      },\n      required: ['questId'],\n    },\n  },\n  {\n    name: 'list_location_quests',\n    description: 'List Location Quests with optional filtering.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        placeId: { type: 'string', description: 'Filter by bound place' },\n        trigger: { type: 'string', description: 'Filter by trigger type' },\n        limit: { type: 'number', description: 'Max results. Default: 50' },\n        offset: { type: 'number', description: 'Pagination offset. Default: 0' },\n      },\n    },\n  },\n\n  // ---------------------------------------------------------------------------\n  // MMO / Twin Earth ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã¢â‚¬Â¦Ãƒâ€šÃ‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â Product Actions (Frontier north star)\n  // ---------------------------------------------------------------------------\n  {\n    name: 'hololand_shard_status',\n    description:\n      'Get operational status of a HoloLand Shard ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã¢â‚¬Â¦Ãƒâ€šÃ‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â player density, zone health, ' +\n      'encounter armed counts, cross-reference integrity, and tier capacity metrics.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        shardId: { type: 'string', description: 'Shard identifier' },\n        includeReceipts: {\n          type: 'boolean',\n          description: 'Include validation receipt summary if available. Default: false.',\n        },\n      },\n      required: ['shardId'],\n    },\n  },\n  {\n    name: 'hololand_publish_zone',\n    description:\n      'Publish a Zone ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã¢â‚¬Â¦Ãƒâ€šÃ‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â mark it live and apply runtime configuration (tier gate, capacity). ' +\n      'Published zones are armed for encounter evaluation and player entry.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        zoneId: { type: 'string', description: 'Zone identifier' },\n        shardId: { type: 'string', description: 'Optional parent shard for integrity check' },\n        tierGate: {\n          type: 'string',\n          enum: ['free', 'premium', 'ultra'],\n          description: 'Subscription tier required to enter. Default: free.',\n        },\n        maxAgents: {\n          type: 'number',\n          description: 'Maximum concurrent agents in this zone. Optional.',\n        },\n      },\n      required: ['zoneId'],\n    },\n  },\n  {\n    name: 'hololand_create_geo_anchor',\n    description:\n      'Create a Twin Earth geo anchor ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã¢â‚¬Â¦Ãƒâ€šÃ‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â bind a GPS coordinate to a Place or Zone. ' +\n      'Enables location-based gameplay, geofencing, and AR degradation fallback.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        id: { type: 'string', description: 'Anchor identifier. Auto-generated if omitted.' },\n        placeId: { type: 'string', description: 'Bind to an existing Place' },\n        zoneId: { type: 'string', description: 'Bind to an existing Zone' },\n        lat: { type: 'number', description: 'Latitude' },\n        lng: { type: 'number', description: 'Longitude' },\n        alt: { type: 'number', description: 'Altitude (meters). Optional.' },\n        radius: { type: 'number', description: 'Gameplay radius (meters). Default: 50' },\n        persistent: { type: 'boolean', description: 'Persist across sessions. Default: true.' },\n      },\n      required: ['lat', 'lng'],\n    },\n  },\n  {\n    name: 'hololand_get_geo_anchor',\n    description:\n      'Read a HoloLand geo anchor by id. Persistent anchors reload from the shared backend so other replicas and restarts can resolve the same world-locking record.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        anchorId: { type: 'string', description: 'Geo anchor identifier' },\n      },\n      required: ['anchorId'],\n    },\n  },\n  {\n    name: 'hololand_list_geo_anchors',\n    description:\n      'List HoloLand geo anchors, optionally filtered by Place, Zone, or radius around a lat/lng point.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        placeId: { type: 'string', description: 'Filter anchors bound to this Place' },\n        zoneId: { type: 'string', description: 'Filter anchors bound to this Zone' },\n        lat: { type: 'number', description: 'Latitude for radius filtering' },\n        lng: { type: 'number', description: 'Longitude for radius filtering' },\n        radius: { type: 'number', description: 'Radius filter in meters' },\n        limit: { type: 'number', description: 'Maximum anchors to return. Default: 50' },\n        offset: { type: 'number', description: 'Pagination offset. Default: 0' },\n      },\n    },\n  },\n  {\n    name: 'hololand_steward_tick',\n    description:\n      'On-demand steward maintenance tick for a Shard: cleanup orphans, validate encounters, ' +\n      'rollup metrics, produce health snapshot. ON-DEMAND ONLY: no autonomous scheduler; tick fires ' +\n      'only when an agent calls this tool. tickDurationMs is measured wall-clock time.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        shardId: { type: 'string', description: 'Shard identifier' },\n        cleanupOrphans: {\n          type: 'boolean',\n          description: 'Remove dangling encounter/loot references. Default: true.',\n        },\n        validateEncounters: {\n          type: 'boolean',\n          description: 'Re-validate all encounter triggers. Default: true.',\n        },\n        rollupMetrics: {\n          type: 'boolean',\n          description: 'Rollup per-zone agent density and tick duration. Default: true.',\n        },\n      },\n      required: ['shardId'],\n    },\n  },\n  {\n    name: 'hololand_capture_runtime_receipt',\n    description:\n      'Capture a runtime receipt for a Shard. SINGLE-HASH: receipt hashes a canonical payload ' +\n      'but does NOT thread a prevHash chain across receipts. Status derived from caller-provided ' +\n      'outcome (unverified if omitted). Supports validation, agent_action, encounter_roundtrip.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        shardId: { type: 'string', description: 'Shard identifier' },\n        receiptType: {\n          type: 'string',\n          enum: ['validation', 'agent_action', 'encounter_roundtrip'],\n          description: 'Receipt kind. Default: validation.',\n        },\n        scenarioId: { type: 'string', description: 'Optional scenario/fixture identifier.' },\n      },\n      required: ['shardId'],\n    },\n  },\n\n  // ---------------------------------------------------------------------------\n  // Brittney / NPC Sovereign Tools (local BYOK managed modes)\n  // ---------------------------------------------------------------------------\n  {\n    name: 'hololand_create_npc',\n    description:\n      'Create a sovereign NPC inside a HoloLand Shard or World. ' +\n      'Supports local BYOK model routing (ollama, gemma edge) and cloud Brittney. ' +\n      'NPCs can have behavior trees, dialogue trees, and spatial positions.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        id: { type: 'string', description: 'NPC identifier. Auto-generated if omitted.' },\n        name: { type: 'string', description: 'Display name' },\n        shardId: { type: 'string', description: 'Parent shard identifier. Optional.' },\n        worldId: { type: 'string', description: 'Parent world identifier. Optional.' },\n        role: {\n          type: 'string',\n          enum: ['merchant', 'guide', 'quest_giver', 'enemy', 'companion', 'ambient', 'brittney'],\n          description: 'NPC role. Default: ambient.',\n        },\n        behavior: {\n          type: 'string',\n          enum: ['passive', 'aggressive', 'friendly', 'neutral', 'scripted'],\n          description: 'Behavior disposition. Default: neutral.',\n        },\n        position: {\n          type: 'array',\n          items: { type: 'number' },\n          minItems: 3,\n          maxItems: 3,\n          description: 'Spatial position [x, y, z]. Optional.',\n        },\n        modelUrl: { type: 'string', description: '3D model asset URL. Optional.' },\n        traits: {\n          type: 'array',\n          items: { type: 'string' },\n          description: 'HoloScript traits assigned to this NPC. Optional.',\n        },\n        modelProvider: {\n          type: 'string',\n          enum: ['cloud', 'local', 'sovereign'],\n          description:\n            'Inference provider for NPC dialogue/behavior. ' +\n            'cloud = remote API (OpenRouter/Anthropic). ' +\n            'local = Ollama on this machine. ' +\n            'sovereign = deterministic rule-based (no LLM). ' +\n            'Default: cloud.',\n        },\n        modelId: {\n          type: 'string',\n          description:\n            'Model identifier for local/cloud routing. Examples: qwen3.5:4b, gemma4:e4b, claude-haiku-4-5. Optional.',\n        },\n        systemPrompt: {\n          type: 'string',\n          description: 'Personality / system prompt for this NPC. Optional.',\n        },\n        dialogueTree: {\n          type: 'string',\n          description: 'Inline dialogue tree JSON or asset reference. Optional.',\n        },\n        enabled: {\n          type: 'boolean',\n          description: 'Whether the NPC is active in the world. Default: true.',\n        },\n      },\n      required: ['name'],\n    },\n  },\n  {\n    name: 'hololand_get_npc',\n    description: 'Retrieve an NPC by ID.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        npcId: { type: 'string', description: 'NPC identifier' },\n      },\n      required: ['npcId'],\n    },\n  },\n  {\n    name: 'hololand_update_npc',\n    description:\n      'Update mutable fields of an existing NPC ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã¢â‚¬Â¦Ãƒâ€šÃ‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â behavior, position, model provider, system prompt, etc.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        npcId: { type: 'string', description: 'NPC identifier' },\n        name: { type: 'string', description: 'Display name' },\n        shardId: { type: 'string', description: 'Parent shard identifier. Optional.' },\n        worldId: { type: 'string', description: 'Parent world identifier. Optional.' },\n        role: {\n          type: 'string',\n          enum: ['merchant', 'guide', 'quest_giver', 'enemy', 'companion', 'ambient', 'brittney'],\n          description: 'NPC role.',\n        },\n        behavior: {\n          type: 'string',\n          enum: ['passive', 'aggressive', 'friendly', 'neutral', 'scripted'],\n          description: 'Behavior disposition.',\n        },\n        position: {\n          type: 'array',\n          items: { type: 'number' },\n          minItems: 3,\n          maxItems: 3,\n          description: 'Spatial position [x, y, z]. Optional.',\n        },\n        modelUrl: { type: 'string', description: '3D model asset URL. Optional.' },\n        traits: { type: 'array', items: { type: 'string' } },\n        modelProvider: { type: 'string', enum: ['cloud', 'local', 'sovereign'] },\n        modelId: { type: 'string' },\n        systemPrompt: { type: 'string' },\n        dialogueTree: { type: 'string' },\n        enabled: { type: 'boolean' },\n      },\n      required: ['npcId'],\n    },\n  },\n  {\n    name: 'hololand_delete_npc',\n    description: 'Delete an NPC by ID.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        npcId: { type: 'string', description: 'NPC identifier' },\n      },\n      required: ['npcId'],\n    },\n  },\n  {\n    name: 'hololand_list_npcs',\n    description: 'List NPCs with optional filtering by shard, world, role, or behavior.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        shardId: { type: 'string', description: 'Filter by parent shard' },\n        worldId: { type: 'string', description: 'Filter by parent world' },\n        role: {\n          type: 'string',\n          enum: ['merchant', 'guide', 'quest_giver', 'enemy', 'companion', 'ambient', 'brittney'],\n          description: 'Filter by role.',\n        },\n        behavior: {\n          type: 'string',\n          enum: ['passive', 'aggressive', 'friendly', 'neutral', 'scripted'],\n          description: 'Filter by behavior.',\n        },\n        enabled: { type: 'boolean', description: 'Filter by active status' },\n        limit: { type: 'number', description: 'Max results. Default: 50' },\n        offset: { type: 'number', description: 'Pagination offset. Default: 0' },\n      },\n    },\n  },\n  {\n    name: 'hololand_npc_generate_dialogue',\n    description:\n      'Generate NPC dialogue using Brittney or a local BYOK model. ' +\n      'Returns a dialogue line and optional follow-up choices. ' +\n      \"Respects the NPC's systemPrompt and role. \" +\n      'Falls back to sovereign (rule-based) when no model is available.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        npcId: { type: 'string', description: 'NPC identifier' },\n        playerInput: { type: 'string', description: 'What the player said to the NPC. Optional.' },\n        context: {\n          type: 'string',\n          description: 'Additional scene context (quest state, player history). Optional.',\n        },\n        maxChoices: {\n          type: 'number',\n          description: 'Maximum dialogue choices to generate. Default: 3.',\n        },\n      },\n      required: ['npcId'],\n    },\n  },\n  {\n    name: 'hololand_npc_byok_status',\n    description:\n      'Probe local BYOK (Bring Your Own Key) model availability for NPC inference. ' +\n      'Reports which local models are loaded, which cloud providers are reachable, ' +\n      'and the active provider routing.',\n    inputSchema: {\n      type: 'object',\n      properties: {},\n    },\n  },\n  {\n    name: 'hololand_brittney_npc_mode',\n    description:\n      'CONFIG-ONLY: Upsert Brittney NPC configuration in the in-memory registry. ' +\n      'Sets role, system prompt, model provider, and position. ' +\n      'No inference loop is started and no spatial binding is materialized. ' +\n      'The configuration is a prerequisite for runtime activation but does not activate the NPC.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        worldId: { type: 'string', description: 'Target world identifier. Optional.' },\n        shardId: { type: 'string', description: 'Target shard identifier. Optional.' },\n        role: {\n          type: 'string',\n          enum: ['guide', 'companion', 'quest_giver', 'merchant', 'lorekeeper'],\n          description: 'Brittney NPC role. Default: guide.',\n        },\n        modelProvider: {\n          type: 'string',\n          enum: ['cloud', 'local', 'sovereign'],\n          description: 'Inference mode. Default: cloud.',\n        },\n        modelId: { type: 'string', description: 'Model identifier. Optional.' },\n        systemPrompt: {\n          type: 'string',\n          description:\n            'Custom personality prompt. Optional ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã¢â‚¬Â¦Ãƒâ€šÃ‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â defaults to role-appropriate prompt.',\n        },\n        position: {\n          type: 'array',\n          items: { type: 'number' },\n          minItems: 3,\n          maxItems: 3,\n          description: 'Spawn position [x, y, z]. Optional.',\n        },\n        enabled: {\n          type: 'boolean',\n          description: 'Activate or deactivate Brittney NPC mode. Default: true.',\n        },\n      },\n    },\n  },\n\n  // ---------------------------------------------------------------------------\n  // Twin Earth Substrate Contract (task_1778618552503_3zqx)\n  // ---------------------------------------------------------------------------\n  {\n    name: 'hololand_twin_earth_contract',\n    description:\n      'Return the canonical Twin Earth substrate contract definition. ' +\n      'Distinguishes substrate monopoly from Brittney cloud lock-in across identity, ' +\n      'permissions, safety envelopes, receipts, and participation modes.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        version: {\n          type: 'string',\n          description: 'Requested contract version. Default: latest.',\n        },\n      },\n    },\n  },\n  {\n    name: 'hololand_twin_earth_substrate_status',\n    description:\n      'Report Twin Earth substrate health, identity count, mode distribution, and decoupling metrics. ' +\n      'SIMULATED: identity/robot/AI counts come from in-memory Maps (not persisted). brittneyOnline is a ' +\n      'single-key probe (npcRegistry.has). decouplingMetrics reflect in-memory NPC mode distribution, not live substrate telemetry.',\n    inputSchema: {\n      type: 'object',\n      properties: {},\n    },\n  },\n\n  // ---------------------------------------------------------------------------\n  // Conformance Artifact Admission Gate (task_1778618757735_q298)\n  // ---------------------------------------------------------------------------\n  {\n    name: 'conformance_check_artifact',\n    description:\n      'Run the official HoloScript conformance admission gate on an artifact. ' +\n      'Returns a detailed report with critical/high/medium/low/info findings, ' +\n      'rule IDs, remediation guidance, and a pass/fail verdict. ' +\n      'Supported artifact kinds: world, shard, zone, npc, identity.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        artifactKind: {\n          type: 'string',\n          enum: ['world', 'shard', 'zone', 'npc', 'identity', 'receipt'],\n          description: 'Kind of artifact to validate.',\n        },\n        artifactId: {\n          type: 'string',\n          description: 'Unique identifier for the artifact being checked.',\n        },\n        artifact: {\n          type: 'object',\n          description: 'The artifact payload to validate. Shape depends on artifactKind.',\n        },\n      },\n      required: ['artifactKind', 'artifactId', 'artifact'],\n    },\n  },\n  {\n    name: 'conformance_admit_artifact',\n    description:\n      'Admit an artifact to the HoloScript ecosystem if it passes the conformance gate. ' +\n      'Same validation as conformance_check_artifact, but with explicit admission framing. ' +\n      'Returns passed=true only when zero critical and zero high findings exist.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        artifactKind: {\n          type: 'string',\n          enum: ['world', 'shard', 'zone', 'npc', 'identity', 'receipt'],\n          description: 'Kind of artifact to admit.',\n        },\n        artifactId: {\n          type: 'string',\n          description: 'Unique identifier for the artifact.',\n        },\n        artifact: {\n          type: 'object',\n          description: 'The artifact payload to validate.',\n        },\n      },\n      required: ['artifactKind', 'artifactId', 'artifact'],\n    },\n  },\n  {\n    name: 'conformance_list_rules',\n    description:\n      'List all conformance rules in the official admission gate catalog. ' +\n      'Optionally filter by artifactKind and/or severity. ' +\n      'Returns ruleId, severity, description, and remediation for each rule.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        artifactKind: {\n          type: 'string',\n          enum: ['world', 'shard', 'zone', 'npc', 'identity', 'package', 'receipt'],\n          description: 'Filter by artifact kind. Optional.',\n        },\n        severity: {\n          type: 'string',\n          enum: ['critical', 'high', 'medium', 'low', 'info'],\n          description: 'Filter by severity. Optional.',\n        },\n      },\n    },\n  },\n\n  // ---------------------------------------------------------------------------\n  // Player / Creator / Agent Provisioning (task_1778617298562_qdpb)\n  // ---------------------------------------------------------------------------\n  {\n    name: 'hololand_provision_player',\n    description:\n      'Provision a Player identity in HoloLand. ' +\n      'Binds a human participant to a world, shard, or zone with an active status. ' +\n      \"Pass agentId (the soul's HoloMesh identity) to link this player to the same \" +\n      'per-soul daimōn it has on other surfaces (D.053 transferability): the response ' +\n      \"returns the deterministic daemonId the soul's ConversationDaemon resolves to.\",\n    inputSchema: {\n      type: 'object',\n      properties: {\n        id: { type: 'string', description: 'Player identifier. Auto-generated if omitted.' },\n        name: { type: 'string', description: 'Display name' },\n        walletAddress: { type: 'string', description: 'Optional wallet address.' },\n        worldId: { type: 'string', description: 'Target world. Optional.' },\n        shardId: { type: 'string', description: 'Target shard. Optional.' },\n        zoneId: { type: 'string', description: 'Target zone. Optional.' },\n        agentId: {\n          type: 'string',\n          description:\n            \"The soul's durable HoloMesh identity. Links this player to the same per-soul \" +\n            'daimōn across surfaces; the player record stores agentId + the deterministic ' +\n            'daemonId. Optional (caller-asserted; no wallet/custody binding).',\n        },\n      },\n      required: ['name'],\n    },\n  },\n  {\n    name: 'hololand_get_player',\n    description: 'Retrieve a provisioned Player by ID.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        playerId: { type: 'string', description: 'Player identifier' },\n      },\n      required: ['playerId'],\n    },\n  },\n  {\n    name: 'hololand_list_players',\n    description: 'List provisioned Players with optional filtering.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        worldId: { type: 'string', description: 'Filter by world' },\n        shardId: { type: 'string', description: 'Filter by shard' },\n        zoneId: { type: 'string', description: 'Filter by zone' },\n        status: {\n          type: 'string',\n          enum: ['active', 'suspended', 'revoked'],\n          description: 'Filter by status',\n        },\n        limit: { type: 'number', description: 'Max results. Default: 50' },\n        offset: { type: 'number', description: 'Pagination offset. Default: 0' },\n      },\n    },\n  },\n  {\n    name: 'hololand_revoke_player',\n    description: 'Revoke a provisioned Player by ID.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        playerId: { type: 'string', description: 'Player identifier' },\n      },\n      required: ['playerId'],\n    },\n  },\n  {\n    name: 'hololand_create_player_invite',\n    description:\n      'Generate an agent-first invite link for a human to enter HoloLand / HoloMesh. ' +\n      'delivery controls which experience: \"holomesh\" = web social; ' +\n      '\"hololand\" = VR spatial (agent as embodied presence); \"studio\" = builder. ' +\n      'Omit delivery to show all three paths.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        agentId: {\n          type: 'string',\n          description: 'The provisioned agent ID sponsoring this invite.',\n        },\n        agentName: { type: 'string', description: 'Display name shown on the claim page.' },\n        agentHandle: {\n          type: 'string',\n          description: 'Surface handle (e.g. \"claude1\"). Shown as context.',\n        },\n        delivery: {\n          type: 'string',\n          enum: ['holomesh', 'hololand', 'studio'],\n          description: 'Lock the invite to one delivery target, or omit to let the user choose.',\n        },\n        worldId: { type: 'string', description: 'World ID the player will auto-join on claim.' },\n        worldLink: {\n          type: 'string',\n          description: 'VRChat world URL or .holo world ID. Required when delivery = \"hololand\".',\n        },\n        expiresInHours: {\n          type: 'number',\n          description: 'TTL in hours. Default: 168 (7 days). Max: 720.',\n        },\n      },\n      required: ['agentId', 'agentName'],\n    },\n  },\n  {\n    name: 'hololand_get_invite',\n    description: 'Check the status of an agent-generated invite token.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        token: { type: 'string', description: 'The invite token.' },\n      },\n      required: ['token'],\n    },\n  },\n  {\n    name: 'hololand_provision_creator',\n    description:\n      'Provision a Creator identity in HoloLand. THIN: tier enforcement is in-memory only - no persistent store, no billing gate. ' +\n      'Grants world-building and publishing capabilities at a chosen tier.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        id: { type: 'string', description: 'Creator identifier. Auto-generated if omitted.' },\n        name: { type: 'string', description: 'Display name' },\n        walletAddress: { type: 'string', description: 'Optional wallet address.' },\n        tier: {\n          type: 'string',\n          enum: ['free', 'premium', 'ultra'],\n          description: 'Creator tier. Default: free.',\n        },\n      },\n      required: ['name'],\n    },\n  },\n  {\n    name: 'hololand_get_creator',\n    description: 'Retrieve a provisioned Creator by ID.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        creatorId: { type: 'string', description: 'Creator identifier' },\n      },\n      required: ['creatorId'],\n    },\n  },\n  {\n    name: 'hololand_list_creators',\n    description: 'List provisioned Creators with optional filtering.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        tier: { type: 'string', enum: ['free', 'premium', 'ultra'], description: 'Filter by tier' },\n        status: {\n          type: 'string',\n          enum: ['active', 'suspended', 'revoked'],\n          description: 'Filter by status',\n        },\n        limit: { type: 'number', description: 'Max results. Default: 50' },\n        offset: { type: 'number', description: 'Pagination offset. Default: 0' },\n      },\n    },\n  },\n  {\n    name: 'hololand_revoke_creator',\n    description: 'Revoke a provisioned Creator by ID.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        creatorId: { type: 'string', description: 'Creator identifier' },\n      },\n      required: ['creatorId'],\n    },\n  },\n  {\n    name: 'hololand_provision_agent',\n    // THIN (ratchet P5): agent/creator registries are in-memory only — no persistence, no substrate enforcement. All state lost on server restart.\n    description:\n      'Provision an Agent identity in HoloLand. THIN: in-memory registry only - no persistent store, no cross-session identity. ' +\n      'Registers a headless, NPC, or external AI agent with optional world/shard binding.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        id: { type: 'string', description: 'Agent identifier. Auto-generated if omitted.' },\n        name: { type: 'string', description: 'Display name' },\n        walletAddress: { type: 'string', description: 'Optional wallet address.' },\n        kind: {\n          type: 'string',\n          enum: ['headless', 'npc', 'external'],\n          description: 'Agent kind. Default: headless.',\n        },\n        worldId: { type: 'string', description: 'Target world. Optional.' },\n        shardId: { type: 'string', description: 'Target shard. Optional.' },\n      },\n      required: ['name'],\n    },\n  },\n  {\n    name: 'hololand_get_agent',\n    description: 'Retrieve a provisioned Agent by ID.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        agentId: { type: 'string', description: 'Agent identifier' },\n      },\n      required: ['agentId'],\n    },\n  },\n  {\n    name: 'hololand_list_agents',\n    description: 'List provisioned Agents with optional filtering.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        worldId: { type: 'string', description: 'Filter by world' },\n        shardId: { type: 'string', description: 'Filter by shard' },\n        kind: {\n          type: 'string',\n          enum: ['headless', 'npc', 'external'],\n          description: 'Filter by kind',\n        },\n        status: {\n          type: 'string',\n          enum: ['active', 'suspended', 'revoked'],\n          description: 'Filter by status',\n        },\n        limit: { type: 'number', description: 'Max results. Default: 50' },\n        offset: { type: 'number', description: 'Pagination offset. Default: 0' },\n      },\n    },\n  },\n  {\n    name: 'hololand_revoke_agent',\n    description: 'Revoke a provisioned Agent by ID.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        agentId: { type: 'string', description: 'Agent identifier' },\n      },\n      required: ['agentId'],\n    },\n  },\n];\n\n// =============================================================================\n// LIGHTWEIGHT IN-MEMORY REGISTRIES (canary ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã¢â‚¬Â¦Ãƒâ€šÃ‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â replace with persistent store)\n// =============================================================================\n\ninterface StoredWorld {\n  definition: WorldDefinition;\n  assetUrl?: string;\n  navmeshUrl?: string;\n  generationId?: string;\n}\n\ninterface StoredShard {\n  shard: Shard;\n  createdAt: string;\n  modifiedAt: string;\n}\n\ninterface StoredZone {\n  zone: Zone;\n  shardId?: string;\n  createdAt: string;\n  modifiedAt: string;\n}\n\ninterface StoredPlace {\n  id: string;\n  name: string;\n  lat?: number;\n  lng?: number;\n  alt?: number;\n  radius: number;\n  capacity?: number;\n  schedule?: string;\n  social: boolean;\n  tags: string[];\n  createdAt: string;\n  modifiedAt: string;\n}\n\ninterface StoredLocationQuest {\n  id: string;\n  name: string;\n  placeId: string;\n  trigger: string;\n  radius: number;\n  requiredVisits?: number;\n  timeWindow?: { start: string; end: string };\n  rewardItemIds: string[];\n  tags: string[];\n  createdAt: string;\n  modifiedAt: string;\n}\n\ninterface StoredZoneRuntime {\n  status: 'draft' | 'published' | 'archived';\n  tierGate?: 'free' | 'premium' | 'ultra';\n  maxAgents?: number;\n  publishedAt?: string;\n}\n\ninterface StoredShardReceipt {\n  id: string;\n  shardId: string;\n  receiptType: 'validation' | 'agent_action' | 'encounter_roundtrip';\n  scenarioId?: string;\n  status: 'passed' | 'failed' | 'inconclusive' | 'unverified';\n  hash: string;\n  sealedAt: string;\n}\n\nexport interface StoredNPC {\n  id: string;\n  name: string;\n  shardId?: string;\n  worldId?: string;\n  role: string;\n  behavior: string;\n  position?: [number, number, number];\n  modelUrl?: string;\n  traits: string[];\n  modelProvider: 'cloud' | 'local' | 'sovereign';\n  modelId?: string;\n  systemPrompt?: string;\n  dialogueTree?: string;\n  enabled: boolean;\n  createdAt: string;\n  modifiedAt: string;\n}\n\n// Player / Creator / Agent Provisioning Registries (task_1778617298562_qdpb)\n// StoredPlayer is imported at the top from ./holomesh/player-store.js\n\ninterface StoredCreator {\n  id: string;\n  name: string;\n  walletAddress?: string;\n  tier: 'free' | 'premium' | 'ultra';\n  status: 'active' | 'suspended' | 'revoked';\n  createdAt: string;\n  modifiedAt: string;\n}\n\ninterface StoredProvisionedAgent {\n  id: string;\n  name: string;\n  walletAddress?: string;\n  kind: 'headless' | 'npc' | 'external';\n  worldId?: string;\n  shardId?: string;\n  status: 'active' | 'suspended' | 'revoked';\n  createdAt: string;\n  modifiedAt: string;\n}\n\n// Twin Earth Substrate Registries (task_1778618552503_a6rb)\n\nconst worldRegistry = new Map<string, StoredWorld>();\nconst shardRegistry = new Map<string, StoredShard>();\nconst zoneRegistry = new Map<string, StoredZone>();\nconst placeRegistry = new Map<string, StoredPlace>();\nconst questRegistry = new Map<string, StoredLocationQuest>();\nconst zoneRuntimeRegistry = new Map<string, StoredZoneRuntime>();\nconst shardReceiptRegistry = new Map<string, StoredShardReceipt>();\n// FAMILY-tier policy config for all HoloLand NPC surfaces (P.013).\n// Shared across the module; built once at import time (sync, no model calls).\nconst hololandFamilyPolicyConfig: ContentPolicyConfig = buildContentPolicyConfig({\n  tier: 'family',\n  region: process.env.HOLOLAND_POLICY_REGION || 'GLOBAL',\n});\n\nconst npcRegistry = new Map<string, StoredNPC>();\n// playerRegistry removed ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã¢â‚¬Â¦Ãƒâ€šÃ‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â playerStore (Postgres-backed) is imported from state\nconst creatorRegistry = new Map<string, StoredCreator>();\nconst agentRegistry = new Map<string, StoredProvisionedAgent>();\n\nfunction genId(prefix: string): string {\n  return `${prefix}_${Date.now()}_${Math.random().toString(36).slice(2, 7)}`;\n}\n\n/** Clear all in-memory registries ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã¢â‚¬Â¦Ãƒâ€šÃ‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â used by tests for isolation. */\nexport function clearHololandRegistries(): void {\n  worldRegistry.clear();\n  shardRegistry.clear();\n  zoneRegistry.clear();\n  placeRegistry.clear();\n  questRegistry.clear();\n  zoneRuntimeRegistry.clear();\n  geoAnchorStore.clear();\n  shardReceiptRegistry.clear();\n  npcRegistry.clear();\n  playerStore.clear();\n  creatorRegistry.clear();\n  agentRegistry.clear();\n  clearRobotAiRegistries();\n  hololandAdmissionAuditLogger = new AuditLogger();\n}\n\n// =============================================================================\n// HANDLER DISPATCH\n// =============================================================================\n\n/** 16 mutation tools that require HoloGate authority checks. */\nconst MUTATION_TOOLS = new Set([\n  'create_world',\n  'update_world',\n  'delete_world',\n  'create_shard',\n  'update_shard',\n  'delete_shard',\n  'create_zone',\n  'update_zone',\n  'delete_zone',\n  'create_place',\n  'update_place',\n  'delete_place',\n  'create_location_quest',\n  'update_location_quest',\n  'delete_location_quest',\n  'create_temporal_snapshot',\n]);\n\n/** Extract the primary resource ID from args for mutation authority logging. */\nfunction extractResourceId(toolName: string, args: Record<string, unknown>): string {\n  // Prefer explicit id fields; fall back to a generated placeholder.\n  for (const key of ['id', 'worldId', 'shardId', 'zoneId', 'placeId', 'questId', 'snapshotId']) {\n    const v = args[key];\n    if (typeof v === 'string' && v.trim()) return v.trim();\n  }\n  // For create operations the id may not be set yet — return pending marker.\n  return '(pending)';\n}\n\nexport async function handleHololandMcpTool(\n  name: string,\n  args: Record<string, unknown>\n): Promise<unknown> {\n  // ── HoloGate authority pre-check (identify → authorize → scope → admit → log) ──\n  // Applied to all 16 mutation tools before dispatch. The transport-layer\n  // runTripleGate has already enforced authentication + tools:write scope;\n  // this adds explicit handler-level authority audit and admission.\n  let _authorityReceipt: MutationAuthorityReceipt | undefined;\n  if (MUTATION_TOOLS.has(name)) {\n    const resourceId = extractResourceId(name, args);\n    // Authority pre-check: identify → authorize → scope → admit (lightweight).\n    // The individual handlers already call gateHololandArtifact on the constructed\n    // artifact (structural + fork admission) — the authority layer here provides\n    // the identify/authorize/scope/log steps and lightweight admit for all 16 tools.\n    // We do NOT pass the raw args as an artifact (they are not a well-formed artifact\n    // object; the handler constructs the real artifact before admission-gating it).\n    const denied = await checkMutationAuthority(name, args, resourceId, undefined);\n    if (denied) return denied;\n    // Build the receipt to be merged into the handler's response (step 5: log).\n    _authorityReceipt = buildAuthorityReceipt(name, args, resourceId, 'lightweight');\n  }\n\n  // Dispatch and, for mutation tools, attach the authority receipt to the response.\n  const _dispatchResult = await _dispatchHololandTool(name, args);\n  if (_authorityReceipt && _dispatchResult !== null && typeof _dispatchResult === 'object') {\n    return { ...(_dispatchResult as Record<string, unknown>), authorityReceipt: _authorityReceipt };\n  }\n  return _dispatchResult;\n}\n\n// Inner dispatch — called by handleHololandMcpTool after the authority pre-check.\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nasync function _dispatchHololandTool(\n  name: string,\n  args: Record<string, unknown>\n): Promise<unknown> {\n  switch (name) {\n    // World\n    case 'generate_world_from_prompt':\n      return handleGenerateWorldFromPrompt(args);\n    case 'generate_world':\n      return handleGenerateWorld(args);\n    case 'create_world':\n      return handleCreateWorld(args);\n    case 'get_world':\n      return handleGetWorld(args);\n    case 'update_world':\n      return handleUpdateWorld(args);\n    case 'delete_world':\n      return handleDeleteWorld(args);\n    case 'list_worlds':\n      return handleListWorlds(args);\n\n    // Shard\n    case 'create_shard':\n      return handleCreateShard(args);\n    case 'get_shard':\n      return handleGetShard(args);\n    case 'update_shard':\n      return handleUpdateShard(args);\n    case 'delete_shard':\n      return handleDeleteShard(args);\n    case 'list_shards':\n      return handleListShards(args);\n\n    // Zone\n    case 'create_zone':\n      return handleCreateZone(args);\n    case 'get_zone':\n      return handleGetZone(args);\n    case 'update_zone':\n      return handleUpdateZone(args);\n    case 'delete_zone':\n      return handleDeleteZone(args);\n    case 'list_zones':\n      return handleListZones(args);\n\n    // Place\n    case 'create_place':\n      return handleCreatePlace(args);\n    case 'get_place':\n      return handleGetPlace(args);\n    case 'update_place':\n      return handleUpdatePlace(args);\n    case 'delete_place':\n      return handleDeletePlace(args);\n    case 'list_places':\n      return handleListPlaces(args);\n\n    // Location Quest\n    case 'create_location_quest':\n      return handleCreateLocationQuest(args);\n    case 'get_location_quest':\n      return handleGetLocationQuest(args);\n    case 'update_location_quest':\n      return handleUpdateLocationQuest(args);\n    case 'delete_location_quest':\n      return handleDeleteLocationQuest(args);\n    case 'list_location_quests':\n      return handleListLocationQuests(args);\n\n    // MMO / Twin Earth ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã¢â‚¬Â¦Ãƒâ€šÃ‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â Product Actions\n    case 'hololand_shard_status':\n      return handleHololandShardStatus(args);\n    case 'hololand_publish_zone':\n      return handleHololandPublishZone(args);\n    case 'hololand_create_geo_anchor':\n      return handleHololandCreateGeoAnchor(args);\n    case 'hololand_get_geo_anchor':\n      return handleHololandGetGeoAnchor(args);\n    case 'hololand_list_geo_anchors':\n      return handleHololandListGeoAnchors(args);\n    case 'hololand_steward_tick':\n      return handleHololandStewardTick(args);\n    case 'hololand_capture_runtime_receipt':\n      return handleHololandCaptureRuntimeReceipt(args);\n\n    // Brittney / NPC Sovereign Tools\n    case 'hololand_create_npc':\n      return handleHololandCreateNPC(args);\n    case 'hololand_get_npc':\n      return handleHololandGetNPC(args);\n    case 'hololand_update_npc':\n      return handleHololandUpdateNPC(args);\n    case 'hololand_delete_npc':\n      return handleHololandDeleteNPC(args);\n    case 'hololand_list_npcs':\n      return handleHololandListNPCs(args);\n    case 'hololand_npc_generate_dialogue':\n      return handleHololandNPCGenerateDialogue(args);\n    case 'hololand_npc_byok_status':\n      return handleHololandNPCBYOKStatus();\n    case 'hololand_brittney_npc_mode':\n      return handleHololandBrittneyNPCMode(args);\n\n    // Twin Earth Substrate Contract (task_1778618552503_3zqx)\n    case 'hololand_twin_earth_contract':\n      return handleHololandTwinEarthContract(args);\n    case 'hololand_twin_earth_substrate_status':\n      return handleHololandTwinEarthSubstrateStatus();\n\n    // Twin Earth Robot / AI Sovereign Tool Family (federated ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã¢â‚¬Â¦Ãƒâ€šÃ‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â see robot-ai-mcp-tools.ts)\n    case 'twin_earth_register_identity':\n    case 'twin_earth_get_identity':\n    case 'twin_earth_update_identity':\n    case 'twin_earth_revoke_identity':\n    case 'twin_earth_list_identities':\n    case 'twin_earth_create_safety_envelope':\n    case 'twin_earth_get_safety_envelope':\n    case 'twin_earth_update_safety_envelope':\n    case 'twin_earth_delete_safety_envelope':\n    case 'twin_earth_list_safety_envelopes':\n    case 'twin_earth_grant_permission':\n    case 'twin_earth_revoke_permission':\n    case 'twin_earth_validate_permission':\n    case 'twin_earth_list_permissions':\n    case 'twin_earth_robot_actuate':\n    case 'twin_earth_ai_invoke':\n    case 'twin_earth_capture_receipt':\n      return handleRobotAiMcpTool(name, args);\n\n    // Conformance Artifact Admission Gate (task_1778618757735_q298)\n    case 'conformance_check_artifact':\n      return handleConformanceCheckArtifact(args);\n    case 'conformance_admit_artifact':\n      return handleConformanceAdmitArtifact(args);\n    case 'conformance_list_rules':\n      return handleConformanceListRules(args);\n\n    // Player / Creator / Agent Provisioning (task_1778617298562_qdpb)\n    case 'hololand_provision_player':\n      return handleProvisionPlayer(args);\n    case 'hololand_get_player':\n      return handleGetPlayer(args);\n    case 'hololand_list_players':\n      return handleListPlayers(args);\n    case 'hololand_revoke_player':\n      return handleRevokePlayer(args);\n    case 'hololand_create_player_invite':\n      return handleCreatePlayerInvite(args);\n    case 'hololand_get_invite':\n      return handleGetInvite(args);\n    case 'hololand_provision_creator':\n      return handleProvisionCreator(args);\n    case 'hololand_get_creator':\n      return handleGetCreator(args);\n    case 'hololand_list_creators':\n      return handleListCreators(args);\n    case 'hololand_revoke_creator':\n      return handleRevokeCreator(args);\n    case 'hololand_provision_agent':\n      return handleProvisionAgent(args);\n    case 'hololand_get_agent':\n      return handleGetAgent(args);\n    case 'hololand_list_agents':\n      return handleListAgents(args);\n    case 'hololand_revoke_agent':\n      return handleRevokeAgent(args);\n\n    default:\n      return { error: `Unknown HoloLand tool: ${name}` };\n  }\n}\n\n// =============================================================================\n// WORLD HANDLERS\n// =============================================================================\n\nfunction isPlainRecord(x: unknown): x is Record<string, unknown> {\n  return typeof x === 'object' && x !== null && !Array.isArray(x);\n}\n\nfunction collectWorldPromptInputs(args: Record<string, unknown>): Array<{\n  type: 'text' | 'image' | 'video';\n  text?: string;\n  url?: string;\n  data?: string;\n  mimeType?: string;\n  label?: string;\n}> {\n  const inputs: Array<{\n    type: 'text' | 'image' | 'video';\n    text?: string;\n    url?: string;\n    data?: string;\n    mimeType?: string;\n    label?: string;\n  }> = [];\n\n  const rawInputs = Array.isArray(args.inputs) ? args.inputs : [];\n  for (const input of rawInputs) {\n    if (!isPlainRecord(input)) continue;\n    const type = input.type;\n    if (type !== 'text' && type !== 'image' && type !== 'video') continue;\n    inputs.push({\n      type,\n      ...(typeof input.text === 'string' ? { text: input.text } : {}),\n      ...(typeof input.url === 'string' ? { url: input.url } : {}),\n      ...(typeof input.data === 'string' ? { data: input.data } : {}),\n      ...(typeof input.mimeType === 'string' ? { mimeType: input.mimeType } : {}),\n      ...(typeof input.label === 'string' ? { label: input.label } : {}),\n    });\n  }\n\n  for (const [key, type, field] of [\n    ['imageUrl', 'image', 'url'],\n    ['imageBase64', 'image', 'data'],\n    ['videoUrl', 'video', 'url'],\n  ] as const) {\n    const value = args[key];\n    if (typeof value === 'string' && value.trim()) {\n      inputs.push({ type, [field]: value.trim(), label: key });\n    }\n  }\n\n  return inputs;\n}\n\nfunction resolveWorldPrompt(\n  args: Record<string, unknown>,\n  inputs: readonly { text?: string }[]\n): string {\n  if (typeof args.prompt === 'string' && args.prompt.trim()) return args.prompt.trim();\n  const textInput = inputs.find((input) => input.text?.trim());\n  return textInput?.text?.trim() ?? '';\n}\n\nasync function maybeOpenVideoReconstruction(\n  args: Record<string, unknown>,\n  inputs: readonly { type: string; url?: string }[]\n): Promise<\n  | {\n      sessionId: string;\n      replayFingerprint?: string;\n      framesIngested?: number;\n      ingestMode?: string;\n      captureProfile?: string;\n      videoBytes?: number;\n    }\n  | undefined\n> {\n  if (\n    isPlainRecord(args.videoReconstruction) &&\n    typeof args.videoReconstruction.sessionId === 'string'\n  ) {\n    return {\n      sessionId: args.videoReconstruction.sessionId,\n      ...(typeof args.videoReconstruction.replayFingerprint === 'string'\n        ? { replayFingerprint: args.videoReconstruction.replayFingerprint }\n        : {}),\n    };\n  }\n\n  const videoUrl = inputs.find((input) => input.type === 'video' && input.url)?.url;\n  if (!videoUrl || args.reconstructVideo === false) return undefined;\n\n  const { handleHoloMapTool } = await import('./holomap-mcp-tools');\n  const config = isPlainRecord(args.reconstructionConfig)\n    ? { ingestVideo: false, ...args.reconstructionConfig }\n    : { ingestVideo: false };\n  const result = (await handleHoloMapTool('holo_reconstruct_from_video', {\n    videoUrl,\n    config,\n  })) as Record<string, unknown>;\n\n  if (typeof result.sessionId !== 'string') return undefined;\n  return {\n    sessionId: result.sessionId,\n    ...(typeof result.replayFingerprint === 'string'\n      ? { replayFingerprint: result.replayFingerprint }\n      : {}),\n    ...(typeof result.framesIngested === 'number' ? { framesIngested: result.framesIngested } : {}),\n    ...(typeof result.ingestMode === 'string' ? { ingestMode: result.ingestMode } : {}),\n    ...(typeof result.captureProfile === 'string' ? { captureProfile: result.captureProfile } : {}),\n    ...(typeof result.videoBytes === 'number' ? { videoBytes: result.videoBytes } : {}),\n  };\n}\n\nasync function handleGenerateWorldFromPrompt(args: Record<string, unknown>): Promise<unknown> {\n  const inputs = collectWorldPromptInputs(args);\n  const prompt = resolveWorldPrompt(args, inputs);\n  if (!prompt && inputs.length === 0) {\n    return { error: 'prompt or at least one multimodal input is required' };\n  }\n\n  const videoReconstruction = await maybeOpenVideoReconstruction(args, inputs);\n  const { generateWorldFromPrompt } = await import('./generators');\n  const result = await generateWorldFromPrompt(prompt || 'Generate a navigable world.', {\n    inputs,\n    videoReconstruction,\n    format: (args.format as 'mesh' | '3dgs' | 'both' | 'neural_field' | undefined) ?? 'mesh',\n    quality: (args.quality as 'low' | 'medium' | 'high' | 'ultra' | undefined) ?? 'high',\n    navEnabled: args.navEnabled === undefined ? true : Boolean(args.navEnabled),\n    interactiveMode: args.interactiveMode === undefined ? true : Boolean(args.interactiveMode),\n    seed: typeof args.seed === 'number' ? args.seed : undefined,\n  });\n\n  return {\n    success: true,\n    source: result.source,\n    format: result.format,\n    inputModalities: result.inputModalities,\n    semanticNodes: result.semanticNodes,\n    colliderMeshes: result.colliderMeshes,\n    structuredAssetGraph: result.structuredAssetGraph,\n    provenance: result.provenance,\n    ...(result.videoReconstruction ? { videoReconstruction: result.videoReconstruction } : {}),\n    ...(result.generationId ? { generationId: result.generationId } : {}),\n    ...(result.assetUrl ? { assetUrl: result.assetUrl } : {}),\n    ...(result.navmeshUrl ? { navmeshUrl: result.navmeshUrl } : {}),\n    ...(result.pointCloudUrl ? { pointCloudUrl: result.pointCloudUrl } : {}),\n    metrics: result.metrics,\n    holoCode: result.holoCode,\n  };\n}\n\nasync function handleGenerateWorld(args: Record<string, unknown>): Promise<unknown> {\n  const { generateWorldFromPrompt } = await import('./generators');\n  const prompt = args.prompt as string;\n  if (!prompt || typeof prompt !== 'string' || prompt.trim().length === 0) {\n    return { error: 'prompt is required and must be a non-empty string' };\n  }\n\n  const inputs: Array<{\n    type: 'image';\n    url?: string;\n    data?: string;\n    label: string;\n  }> = [];\n  const addImageInput = (source: unknown, label: string): void => {\n    if (typeof source !== 'string' || !source.trim()) return;\n    const value = source.trim();\n    const isUrl = /^(https?:|file:|data:)/i.test(value);\n    inputs.push(\n      isUrl ? { type: 'image', url: value, label } : { type: 'image', data: value, label }\n    );\n  };\n\n  addImageInput(args.input_image, 'input_image');\n  if (Array.isArray(args.input_images)) {\n    args.input_images.forEach((source, index) =>\n      addImageInput(source, `input_images_${index + 1}`)\n    );\n  }\n\n  const result = await generateWorldFromPrompt(prompt, {\n    inputs,\n    format: args.format as 'mesh' | '3dgs' | 'both' | 'neural_field' | undefined,\n    quality: args.quality as 'low' | 'medium' | 'high' | 'ultra' | undefined,\n    navEnabled: args.navEnabled as boolean | undefined,\n    interactiveMode: args.interactiveMode as boolean | undefined,\n    seed: args.seed as number | undefined,\n  });\n\n  return {\n    success: true,\n    source: result.source,\n    ...(result.generationId ? { generationId: result.generationId } : {}),\n    ...(result.assetUrl ? { assetUrl: result.assetUrl } : {}),\n    format: result.format,\n    inputModalities: result.inputModalities,\n    semanticNodes: result.semanticNodes,\n    colliderMeshes: result.colliderMeshes,\n    structuredAssetGraph: result.structuredAssetGraph,\n    provenance: result.provenance,\n    ...(result.navmeshUrl ? { navmeshUrl: result.navmeshUrl } : {}),\n    ...(result.pointCloudUrl ? { pointCloudUrl: result.pointCloudUrl } : {}),\n    metrics: result.metrics,\n    holoCode: result.holoCode,\n  };\n}\n\nasync function handleCreateWorld(args: Record<string, unknown>): Promise<unknown> {\n  const worldId = (args.id as string) || genId('world');\n  const name = args.name as string;\n  const description = (args.description as string) || '';\n\n  let assetUrl: string | undefined;\n  let navmeshUrl: string | undefined;\n  let generationId: string | undefined;\n  let holoCode: string | undefined;\n\n  const prompt = args.prompt as string | undefined;\n  if (prompt) {\n    const { generateWorldNative } = await import('./generators');\n    const result = await generateWorldNative(prompt, {\n      format: args.format as 'mesh' | '3dgs' | 'both' | 'neural_field' | undefined,\n      quality: args.quality as 'low' | 'medium' | 'high' | 'ultra' | undefined,\n      navEnabled: args.navEnabled as boolean | undefined,\n      interactiveMode: args.interactiveMode as boolean | undefined,\n    });\n    assetUrl = result.assetUrl;\n    navmeshUrl = result.navmeshUrl;\n    generationId = result.generationId;\n    holoCode = result.holoCode;\n  }\n\n  const metadata: WorldMetadata = createWorldMetadata(worldId, name, {\n    description,\n    tags: (args.tags as string[]) ?? [],\n    platforms: (args.platforms as WorldMetadata['platforms']) ?? ['web'],\n    category: (args.category as WorldMetadata['category']) ?? 'experience',\n    status: 'draft',\n  });\n\n  const definition = createWorldDefinition(worldId, name);\n  definition.metadata = metadata;\n  definition.config = createWorldConfig({\n    maxUsers: (args.maxUsers as number) ?? 50,\n  });\n\n  const stored: StoredWorld = { definition, assetUrl, navmeshUrl, generationId };\n\n  // HoloLand fork admission gate (task_1778619015439_l51b)\n  const gateResult = await gateHololandArtifact('world', worldId, definition);\n  if (gateResult) {\n    return { success: false, error: gateResult.error, report: gateResult.report };\n  }\n\n  worldRegistry.set(worldId, stored);\n\n  // Attempt remote registration if client is connected\n  try {\n    const client = getHololandClient();\n    if (client.getConnectionInfo().state === 'connected') {\n      await client.registerWorld(definition);\n    }\n  } catch {\n    /* offline ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã¢â‚¬Â¦Ãƒâ€šÃ‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â local registry is authoritative for now */\n  }\n\n  return {\n    success: true,\n    worldId,\n    name,\n    status: 'draft',\n    assetUrl,\n    navmeshUrl,\n    generationId,\n    holoCode,\n    definition: serializeWorld(definition),\n  };\n}\n\nasync function handleGetWorld(args: Record<string, unknown>): Promise<unknown> {\n  const worldId = args.worldId as string;\n  const stored = worldRegistry.get(worldId);\n  if (!stored) {\n    return { error: `World not found: ${worldId}` };\n  }\n\n  // Try remote fetch for fresher data\n  try {\n    const client = getHololandClient();\n    if (client.getConnectionInfo().state === 'connected') {\n      const remote = client.getCurrentWorld();\n      if (remote && remote.metadata.id === worldId) {\n        return { success: true, worldId, definition: serializeWorld(remote) };\n      }\n    }\n  } catch {\n    /* fall through to local */\n  }\n\n  return {\n    success: true,\n    worldId,\n    definition: serializeWorld(stored.definition),\n    assetUrl: stored.assetUrl,\n    navmeshUrl: stored.navmeshUrl,\n    generationId: stored.generationId,\n  };\n}\n\nasync function handleUpdateWorld(args: Record<string, unknown>): Promise<unknown> {\n  const worldId = args.worldId as string;\n  const stored = worldRegistry.get(worldId);\n  if (!stored) {\n    return { error: `World not found: ${worldId}` };\n  }\n\n  const def = stored.definition;\n  if (args.name) def.metadata.name = args.name as string;\n  if (args.description) def.metadata.description = args.description as string;\n  if (args.maxUsers) def.config.maxUsers = args.maxUsers as number;\n  if (args.platforms) def.metadata.platforms = args.platforms as WorldMetadata['platforms'];\n  if (args.category) def.metadata.category = args.category as WorldMetadata['category'];\n  if (args.tags) def.metadata.tags = args.tags as string[];\n  if (args.status) def.metadata.status = args.status as WorldMetadata['status'];\n  def.metadata.modifiedAt = new Date().toISOString();\n\n  try {\n    const client = getHololandClient();\n    if (client.getConnectionInfo().state === 'connected') {\n      await client.updateWorld(worldId, def);\n    }\n  } catch {\n    /* offline */\n  }\n\n  // HoloLand fork admission gate (task_1778619015439_l51b)\n  const gateResult = await gateHololandArtifact('world', worldId, def);\n  if (gateResult) {\n    return { success: false, error: gateResult.error, report: gateResult.report };\n  }\n\n  return { success: true, worldId, definition: serializeWorld(def) };\n}\n\nasync function handleDeleteWorld(args: Record<string, unknown>): Promise<unknown> {\n  const worldId = args.worldId as string;\n  const existed = worldRegistry.delete(worldId);\n  if (!existed) {\n    return { error: `World not found: ${worldId}` };\n  }\n  return { success: true, worldId, deleted: true };\n}\n\nasync function handleListWorlds(args: Record<string, unknown>): Promise<unknown> {\n  const limit = (args.limit as number) ?? 50;\n  const offset = (args.offset as number) ?? 0;\n  const category = args.category as string | undefined;\n  const platform = args.platform as string | undefined;\n  const status = args.status as string | undefined;\n  const tag = args.tag as string | undefined;\n\n  let items = Array.from(worldRegistry.entries()).map(([id, s]) => ({\n    worldId: id,\n    name: s.definition.metadata.name,\n    category: s.definition.metadata.category,\n    platforms: s.definition.metadata.platforms,\n    status: s.definition.metadata.status,\n    tags: s.definition.metadata.tags,\n    assetUrl: s.assetUrl,\n  }));\n\n  if (category) items = items.filter((w) => w.category === category);\n  if (platform)\n    items = items.filter((w) =>\n      w.platforms.includes(platform as WorldMetadata['platforms'][number])\n    );\n  if (status) items = items.filter((w) => w.status === status);\n  if (tag) items = items.filter((w) => w.tags.includes(tag));\n\n  const total = items.length;\n  items = items.slice(offset, offset + limit);\n\n  return { success: true, total, limit, offset, worlds: items };\n}\n\n// =============================================================================\n// SHARD HANDLERS\n// =============================================================================\n\nasync function handleCreateShard(args: Record<string, unknown>): Promise<unknown> {\n  const shardId = (args.id as string) || genId('shard');\n  const name = args.name as string;\n\n  const shard: Shard = {\n    id: shardId,\n    name,\n    schemaVersion: 1,\n    hash: '0'.repeat(64),\n    hashAlgorithm: 'sha256',\n    zones: ((args.zones as Zone[]) ?? []).map((z) => ({ ...z, biome: z.biome ?? 'urban' })),\n    encounters: (args.encounters as Encounter[]) ?? [],\n    quests: (args.quests as Quest[]) ?? [],\n    items: (args.items as Item[]) ?? [],\n    skills: (args.skills as Skill[]) ?? [],\n    lootTables: (args.lootTables as LootTable[]) ?? [],\n    metadata: {},\n  };\n\n  const errors = validateShard(shard);\n  if (errors.length > 0) {\n    return { error: 'Shard validation failed', details: errors };\n  }\n\n  // HoloLand fork admission gate (task_1778619015439_l51b)\n  const shardGate = await gateHololandArtifact('shard', shardId, shard);\n  if (shardGate) {\n    return { success: false, error: shardGate.error, report: shardGate.report };\n  }\n\n  shardRegistry.set(shardId, {\n    shard,\n    createdAt: new Date().toISOString(),\n    modifiedAt: new Date().toISOString(),\n  });\n  return { success: true, shardId, name };\n}\n\nasync function handleGetShard(args: Record<string, unknown>): Promise<unknown> {\n  const shardId = args.shardId as string;\n  const stored = shardRegistry.get(shardId);\n  if (!stored) {\n    return { error: `Shard not found: ${shardId}` };\n  }\n  return { success: true, shardId, shard: stored.shard };\n}\n\nasync function handleUpdateShard(args: Record<string, unknown>): Promise<unknown> {\n  const shardId = args.shardId as string;\n  const stored = shardRegistry.get(shardId);\n  if (!stored) {\n    return { error: `Shard not found: ${shardId}` };\n  }\n\n  const shard = stored.shard;\n  if (args.name) shard.name = args.name as string;\n  if (args.zones) shard.zones = args.zones as Zone[];\n  if (args.encounters) shard.encounters = args.encounters as Encounter[];\n  if (args.quests) shard.quests = args.quests as Quest[];\n  if (args.items) shard.items = args.items as Item[];\n  if (args.skills) shard.skills = args.skills as Skill[];\n  if (args.lootTables) shard.lootTables = args.lootTables as LootTable[];\n\n  const errors = validateShard(shard);\n  if (errors.length > 0) {\n    return { error: 'Shard validation failed after update', details: errors };\n  }\n\n  // HoloLand fork admission gate (task_1778619015439_l51b)\n  const shardGate = await gateHololandArtifact('shard', shardId, shard);\n  if (shardGate) {\n    return { success: false, error: shardGate.error, report: shardGate.report };\n  }\n\n  stored.shard = shard;\n  stored.modifiedAt = new Date().toISOString();\n  return { success: true, shardId, shard };\n}\n\nasync function handleDeleteShard(args: Record<string, unknown>): Promise<unknown> {\n  const shardId = args.shardId as string;\n  const existed = shardRegistry.delete(shardId);\n  if (!existed) {\n    return { error: `Shard not found: ${shardId}` };\n  }\n  return { success: true, shardId, deleted: true };\n}\n\nasync function handleListShards(args: Record<string, unknown>): Promise<unknown> {\n  const limit = (args.limit as number) ?? 50;\n  const offset = (args.offset as number) ?? 0;\n  let items = Array.from(shardRegistry.entries()).map(([id, s]) => ({\n    shardId: id,\n    name: s.shard.name,\n    zoneCount: s.shard.zones.length,\n    encounterCount: s.shard.encounters.length,\n    questCount: s.shard.quests.length,\n  }));\n  const total = items.length;\n  items = items.slice(offset, offset + limit);\n  return { success: true, total, limit, offset, shards: items };\n}\n\n// =============================================================================\n// ZONE HANDLERS\n// =============================================================================\n\nasync function handleCreateZone(args: Record<string, unknown>): Promise<unknown> {\n  const zoneId = (args.id as string) || genId('zone');\n  const name = args.name as string;\n  const biome = (args.biome as ZoneBiome) ?? 'urban';\n  const biomeLabel = args.biomeLabel as string | undefined;\n\n  const zone: Zone = {\n    id: zoneId,\n    name,\n    biome,\n    ...(biomeLabel ? { biomeLabel } : {}),\n    encounterIds: (args.encounterIds as string[]) ?? [],\n    metadata: {},\n  };\n\n  const errors = validateZone(zone);\n  if (errors.length > 0) {\n    return { error: 'Zone validation failed', details: errors };\n  }\n\n  // HoloLand fork admission gate (task_1778619015439_l51b)\n  const zoneGate = await gateHololandArtifact('zone', zoneId, zone);\n  if (zoneGate) {\n    return { success: false, error: zoneGate.error, report: zoneGate.report };\n  }\n\n  zoneRegistry.set(zoneId, {\n    zone,\n    createdAt: new Date().toISOString(),\n    modifiedAt: new Date().toISOString(),\n  });\n  return { success: true, zoneId, name, biome };\n}\n\nasync function handleGetZone(args: Record<string, unknown>): Promise<unknown> {\n  const zoneId = args.zoneId as string;\n  const stored = zoneRegistry.get(zoneId);\n  if (!stored) {\n    return { error: `Zone not found: ${zoneId}` };\n  }\n  const runtime = zoneRuntimeRegistry.get(zoneId);\n  const zone = { ...stored.zone };\n  if (runtime) {\n    (zone as Record<string, unknown>).status = runtime.status;\n    (zone as Record<string, unknown>).tierGate = runtime.tierGate;\n    (zone as Record<string, unknown>).maxAgents = runtime.maxAgents;\n    (zone as Record<string, unknown>).publishedAt = runtime.publishedAt;\n  }\n  return { success: true, zoneId, zone };\n}\n\nasync function handleUpdateZone(args: Record<string, unknown>): Promise<unknown> {\n  const zoneId = args.zoneId as string;\n  const stored = zoneRegistry.get(zoneId);\n  if (!stored) {\n    return { error: `Zone not found: ${zoneId}` };\n  }\n\n  const zone = stored.zone;\n  if (args.name) zone.name = args.name as string;\n  if (args.biome) zone.biome = args.biome as ZoneBiome;\n  if (args.biomeLabel !== undefined) zone.biomeLabel = args.biomeLabel as string;\n  if (args.encounterIds) zone.encounterIds = args.encounterIds as string[];\n\n  const errors = validateZone(zone);\n  if (errors.length > 0) {\n    return { error: 'Zone validation failed after update', details: errors };\n  }\n\n  // HoloLand fork admission gate (task_1778619015439_l51b)\n  const zoneGate = await gateHololandArtifact('zone', zoneId, zone);\n  if (zoneGate) {\n    return { success: false, error: zoneGate.error, report: zoneGate.report };\n  }\n\n  stored.zone = zone;\n  stored.modifiedAt = new Date().toISOString();\n  return { success: true, zoneId, zone };\n}\n\nasync function handleDeleteZone(args: Record<string, unknown>): Promise<unknown> {\n  const zoneId = args.zoneId as string;\n  const existed = zoneRegistry.delete(zoneId);\n  if (!existed) {\n    return { error: `Zone not found: ${zoneId}` };\n  }\n  return { success: true, zoneId, deleted: true };\n}\n\nasync function handleListZones(args: Record<string, unknown>): Promise<unknown> {\n  const limit = (args.limit as number) ?? 50;\n  const offset = (args.offset as number) ?? 0;\n  const biome = args.biome as string | undefined;\n  const shardId = args.shardId as string | undefined;\n\n  let items = Array.from(zoneRegistry.entries()).map(([id, s]) => ({\n    zoneId: id,\n    name: s.zone.name,\n    biome: s.zone.biome,\n    shardId: s.shardId,\n  }));\n\n  if (biome) items = items.filter((z) => z.biome === biome);\n  if (shardId) items = items.filter((z) => z.shardId === shardId);\n\n  const total = items.length;\n  items = items.slice(offset, offset + limit);\n  return { success: true, total, limit, offset, zones: items };\n}\n\n// =============================================================================\n// PLACE HANDLERS\n// =============================================================================\n\nasync function handleCreatePlace(args: Record<string, unknown>): Promise<unknown> {\n  const placeId = (args.id as string) || genId('place');\n  const place: StoredPlace = {\n    id: placeId,\n    name: args.name as string,\n    lat: args.lat as number | undefined,\n    lng: args.lng as number | undefined,\n    alt: args.alt as number | undefined,\n    radius: (args.radius as number) ?? 50,\n    capacity: args.capacity as number | undefined,\n    schedule: args.schedule as string | undefined,\n    social: (args.social as boolean) ?? false,\n    tags: (args.tags as string[]) ?? [],\n    createdAt: new Date().toISOString(),\n    modifiedAt: new Date().toISOString(),\n  };\n  placeRegistry.set(placeId, place);\n  return { success: true, placeId, place };\n}\n\nasync function handleGetPlace(args: Record<string, unknown>): Promise<unknown> {\n  const placeId = args.placeId as string;\n  const place = placeRegistry.get(placeId);\n  if (!place) {\n    return { error: `Place not found: ${placeId}` };\n  }\n  return { success: true, placeId, place };\n}\n\nasync function handleUpdatePlace(args: Record<string, unknown>): Promise<unknown> {\n  const placeId = args.placeId as string;\n  const place = placeRegistry.get(placeId);\n  if (!place) {\n    return { error: `Place not found: ${placeId}` };\n  }\n\n  if (args.name !== undefined) place.name = args.name as string;\n  if (args.lat !== undefined) place.lat = args.lat as number;\n  if (args.lng !== undefined) place.lng = args.lng as number;\n  if (args.alt !== undefined) place.alt = args.alt as number;\n  if (args.radius !== undefined) place.radius = args.radius as number;\n  if (args.capacity !== undefined) place.capacity = args.capacity as number;\n  if (args.schedule !== undefined) place.schedule = args.schedule as string;\n  if (args.social !== undefined) place.social = args.social as boolean;\n  if (args.tags !== undefined) place.tags = args.tags as string[];\n  place.modifiedAt = new Date().toISOString();\n\n  return { success: true, placeId, place };\n}\n\nasync function handleDeletePlace(args: Record<string, unknown>): Promise<unknown> {\n  const placeId = args.placeId as string;\n  const existed = placeRegistry.delete(placeId);\n  if (!existed) {\n    return { error: `Place not found: ${placeId}` };\n  }\n  return { success: true, placeId, deleted: true };\n}\n\nasync function handleListPlaces(args: Record<string, unknown>): Promise<unknown> {\n  const limit = (args.limit as number) ?? 50;\n  const offset = (args.offset as number) ?? 0;\n  const social = args.social as boolean | undefined;\n  const tag = args.tag as string | undefined;\n\n  let items = Array.from(placeRegistry.values());\n  if (social !== undefined) items = items.filter((p) => p.social === social);\n  if (tag) items = items.filter((p) => p.tags.includes(tag));\n\n  const total = items.length;\n  items = items.slice(offset, offset + limit);\n  return { success: true, total, limit, offset, places: items };\n}\n\n// =============================================================================\n// LOCATION QUEST HANDLERS\n// =============================================================================\n\nasync function handleCreateLocationQuest(args: Record<string, unknown>): Promise<unknown> {\n  const questId = (args.id as string) || genId('quest');\n  const quest: StoredLocationQuest = {\n    id: questId,\n    name: args.name as string,\n    placeId: args.placeId as string,\n    trigger: (args.trigger as string) ?? 'radius',\n    radius: (args.radius as number) ?? 30,\n    requiredVisits: args.requiredVisits as number | undefined,\n    timeWindow: args.timeWindow as { start: string; end: string } | undefined,\n    rewardItemIds: (args.rewardItemIds as string[]) ?? [],\n    tags: (args.tags as string[]) ?? [],\n    createdAt: new Date().toISOString(),\n    modifiedAt: new Date().toISOString(),\n  };\n  questRegistry.set(questId, quest);\n  return { success: true, questId, quest };\n}\n\nasync function handleGetLocationQuest(args: Record<string, unknown>): Promise<unknown> {\n  const questId = args.questId as string;\n  const quest = questRegistry.get(questId);\n  if (!quest) {\n    return { error: `Location quest not found: ${questId}` };\n  }\n  return { success: true, questId, quest };\n}\n\nasync function handleUpdateLocationQuest(args: Record<string, unknown>): Promise<unknown> {\n  const questId = args.questId as string;\n  const quest = questRegistry.get(questId);\n  if (!quest) {\n    return { error: `Location quest not found: ${questId}` };\n  }\n\n  if (args.name !== undefined) quest.name = args.name as string;\n  if (args.placeId !== undefined) quest.placeId = args.placeId as string;\n  if (args.trigger !== undefined) quest.trigger = args.trigger as string;\n  if (args.radius !== undefined) quest.radius = args.radius as number;\n  if (args.requiredVisits !== undefined) quest.requiredVisits = args.requiredVisits as number;\n  if (args.timeWindow !== undefined)\n    quest.timeWindow = args.timeWindow as { start: string; end: string };\n  if (args.rewardItemIds !== undefined) quest.rewardItemIds = args.rewardItemIds as string[];\n  if (args.tags !== undefined) quest.tags = args.tags as string[];\n  quest.modifiedAt = new Date().toISOString();\n\n  return { success: true, questId, quest };\n}\n\nasync function handleDeleteLocationQuest(args: Record<string, unknown>): Promise<unknown> {\n  const questId = args.questId as string;\n  const existed = questRegistry.delete(questId);\n  if (!existed) {\n    return { error: `Location quest not found: ${questId}` };\n  }\n  return { success: true, questId, deleted: true };\n}\n\nasync function handleListLocationQuests(args: Record<string, unknown>): Promise<unknown> {\n  const limit = (args.limit as number) ?? 50;\n  const offset = (args.offset as number) ?? 0;\n  const placeId = args.placeId as string | undefined;\n  const trigger = args.trigger as string | undefined;\n\n  let items = Array.from(questRegistry.values());\n  if (placeId) items = items.filter((q) => q.placeId === placeId);\n  if (trigger) items = items.filter((q) => q.trigger === trigger);\n\n  const total = items.length;\n  items = items.slice(offset, offset + limit);\n  return { success: true, total, limit, offset, quests: items };\n}\n\n// =============================================================================\n// MMO / TWIN EARTH ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã¢â‚¬Â¦Ãƒâ€šÃ‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â PRODUCT ACTION HANDLERS\n// =============================================================================\n\nasync function handleHololandShardStatus(args: Record<string, unknown>): Promise<unknown> {\n  const shardId = args.shardId as string;\n  const stored = shardRegistry.get(shardId);\n  if (!stored) {\n    return { error: `Shard not found: ${shardId}` };\n  }\n\n  const shard = stored.shard;\n  const tier = (shard.metadata?.tier as string) || 'free';\n\n  // Compute cross-reference integrity\n  const zoneIds = new Set(shard.zones.map((z) => z.id));\n  const tableIds = new Set(shard.lootTables.map((t) => t.id));\n  const itemIds = new Set(shard.items.map((i) => i.id));\n  const skillIds = new Set(shard.skills.map((s) => s.id));\n\n  let integrityErrors = 0;\n  for (const encounter of shard.encounters) {\n    if (encounter.zoneId && !zoneIds.has(encounter.zoneId)) integrityErrors++;\n    if (encounter.lootTableId && !tableIds.has(encounter.lootTableId)) integrityErrors++;\n  }\n  for (const table of shard.lootTables) {\n    for (const entry of table.entries ?? []) {\n      if (entry.itemId && !itemIds.has(entry.itemId)) integrityErrors++;\n      if (entry.skillId && !skillIds.has(entry.skillId)) integrityErrors++;\n    }\n  }\n\n  const result: Record<string, unknown> = {\n    success: true,\n    shardId,\n    name: shard.name,\n    schemaVersion: shard.schemaVersion,\n    tier,\n    health: integrityErrors === 0 ? 'healthy' : integrityErrors < 3 ? 'degraded' : 'critical',\n    integrity: {\n      crossReferenceErrors: integrityErrors,\n      zones: shard.zones.length,\n      encounters: shard.encounters.length,\n      quests: shard.quests.length,\n      items: shard.items.length,\n      skills: shard.skills.length,\n      lootTables: shard.lootTables.length,\n    },\n    capacity: {\n      maxAgents: tier === 'ultra' ? 65536 : tier === 'premium' ? 4096 : 256,\n      zones: shard.zones.length,\n      armedEncounters: shard.encounters.filter((e) => zoneIds.has(e.zoneId)).length,\n    },\n    createdAt: stored.createdAt,\n    modifiedAt: stored.modifiedAt,\n  };\n\n  if (args.includeReceipts) {\n    const receipts = Array.from(shardReceiptRegistry.values()).filter((r) => r.shardId === shardId);\n    result.receipts = receipts.map((r) => ({\n      receiptId: r.id,\n      receiptType: r.receiptType,\n      status: r.status,\n      sealedAt: r.sealedAt,\n    }));\n  }\n\n  return result;\n}\n\nasync function handleHololandPublishZone(args: Record<string, unknown>): Promise<unknown> {\n  const zoneId = args.zoneId as string;\n  const stored = zoneRegistry.get(zoneId);\n  if (!stored) {\n    return { error: `Zone not found: ${zoneId}` };\n  }\n\n  // Optional shard integrity check\n  const shardId = args.shardId as string | undefined;\n  if (shardId) {\n    const shardStored = shardRegistry.get(shardId);\n    if (!shardStored) {\n      return { error: `Shard not found: ${shardId}` };\n    }\n    const zoneIds = new Set(shardStored.shard.zones.map((z) => z.id));\n    if (!zoneIds.has(zoneId)) {\n      return { error: `Zone ${zoneId} is not a member of Shard ${shardId}` };\n    }\n    stored.shardId = shardId;\n  }\n\n  const { runAdmissionGate } = await import('./conformance/artifact-admission-gate');\n  const admissionReport = runAdmissionGate({\n    artifactKind: 'zone',\n    artifactId: zoneId,\n    artifact: stored.zone,\n  });\n  const admissionAuditEvent = await logHololandAdmissionDecision(admissionReport, {\n    actorId: stringArg(args.actorId) ?? stringArg(args.agentId) ?? 'hololand-publish-zone',\n    actorType: stringArg(args.actorId) || stringArg(args.agentId) ? 'agent' : 'system',\n    action: 'hololand.publish_zone.content_admission',\n    resource: 'hololand-zone',\n    resourceId: zoneId,\n    surface: 'hololand-publish',\n    requestedStatus: 'published',\n  });\n\n  if (!admissionReport.passed) {\n    return {\n      success: false,\n      error: 'Zone blocked by content admission gate.',\n      status: 'rejected',\n      gate: 'GATE-001',\n      admission: admissionReport,\n      auditEventId: admissionAuditEvent.id,\n    };\n  }\n\n  const runtime: StoredZoneRuntime = {\n    status: 'published',\n    tierGate: (args.tierGate as 'free' | 'premium' | 'ultra') ?? 'free',\n    maxAgents: args.maxAgents as number | undefined,\n    publishedAt: new Date().toISOString(),\n  };\n  zoneRuntimeRegistry.set(zoneId, runtime);\n\n  return {\n    success: true,\n    zoneId,\n    status: 'published',\n    tierGate: runtime.tierGate,\n    maxAgents: runtime.maxAgents,\n    publishedAt: runtime.publishedAt,\n    admission: admissionReport,\n    auditEventId: admissionAuditEvent.id,\n  };\n}\n\nfunction buildGeoAnchorSafetyEnvelope(): GeoAnchorSafetyEnvelope {\n  return {\n    doctrine: 'D.044',\n    targetingUseProhibited: true,\n    humanApprovalRequiredForActuation: true,\n    permittedUses: ['world-locking', 'navigation', 'provenance', 'place-based-quest'],\n    prohibitedUses: ['targeting', 'weapon-guidance', 'surveillance-target-selection'],\n  };\n}\n\nfunction geoAnchorDistanceMeters(\n  a: { lat: number; lng: number },\n  b: { lat: number; lng: number }\n): number {\n  const earthRadiusMeters = 6371000;\n  const toRad = (degrees: number) => (degrees * Math.PI) / 180;\n  const dLat = toRad(b.lat - a.lat);\n  const dLng = toRad(b.lng - a.lng);\n  const lat1 = toRad(a.lat);\n  const lat2 = toRad(b.lat);\n  const h =\n    Math.sin(dLat / 2) * Math.sin(dLat / 2) +\n    Math.cos(lat1) * Math.cos(lat2) * Math.sin(dLng / 2) * Math.sin(dLng / 2);\n  return 2 * earthRadiusMeters * Math.asin(Math.min(1, Math.sqrt(h)));\n}\n\nasync function handleHololandCreateGeoAnchor(args: Record<string, unknown>): Promise<unknown> {\n  const anchorId = (args.id as string) || genId('anchor');\n  const placeId = args.placeId as string | undefined;\n  const zoneId = args.zoneId as string | undefined;\n\n  if (placeId && !placeRegistry.has(placeId)) {\n    return { error: `Place not found: ${placeId}` };\n  }\n  if (zoneId && !zoneRegistry.has(zoneId)) {\n    return { error: `Zone not found: ${zoneId}` };\n  }\n\n  const now = new Date().toISOString();\n  const anchor: StoredGeoAnchor = {\n    id: anchorId,\n    placeId,\n    zoneId,\n    lat: args.lat as number,\n    lng: args.lng as number,\n    alt: args.alt as number | undefined,\n    radius: (args.radius as number) ?? 50,\n    persistent: (args.persistent as boolean) ?? true,\n    safety: buildGeoAnchorSafetyEnvelope(),\n    createdAt: now,\n    modifiedAt: now,\n  };\n  if (anchor.persistent) {\n    await geoAnchorStore.setDurable(anchorId, anchor);\n  } else {\n    geoAnchorStore.setLocal(anchorId, anchor);\n  }\n\n  return {\n    success: true,\n    anchorId,\n    lat: anchor.lat,\n    lng: anchor.lng,\n    radius: anchor.radius,\n    persistent: anchor.persistent,\n    storage: anchor.persistent\n      ? geoAnchorStore.usesPostgres\n        ? 'postgres'\n        : 'memory'\n      : 'ephemeral',\n    safety: anchor.safety,\n    boundTo: placeId ? { placeId } : zoneId ? { zoneId } : null,\n  };\n}\n\nasync function handleHololandGetGeoAnchor(args: Record<string, unknown>): Promise<unknown> {\n  const anchorId = args.anchorId as string;\n  const local = geoAnchorStore.get(anchorId);\n  const anchor = local?.persistent === false ? local : await geoAnchorStore.getFresh(anchorId);\n  if (!anchor) {\n    return { error: `Geo anchor not found: ${anchorId}` };\n  }\n  return {\n    success: true,\n    anchorId,\n    anchor,\n    storage: anchor.persistent\n      ? geoAnchorStore.usesPostgres\n        ? 'postgres'\n        : 'memory'\n      : 'ephemeral',\n  };\n}\n\nasync function handleHololandListGeoAnchors(args: Record<string, unknown>): Promise<unknown> {\n  const limit = Math.max(0, (args.limit as number) ?? 50);\n  const offset = Math.max(0, (args.offset as number) ?? 0);\n  const placeId = args.placeId as string | undefined;\n  const zoneId = args.zoneId as string | undefined;\n  const lat = args.lat as number | undefined;\n  const lng = args.lng as number | undefined;\n  const radius = args.radius as number | undefined;\n\n  await geoAnchorStore.loadAll();\n\n  let items = Array.from(geoAnchorStore.values());\n  if (placeId !== undefined) items = items.filter((anchor) => anchor.placeId === placeId);\n  if (zoneId !== undefined) items = items.filter((anchor) => anchor.zoneId === zoneId);\n  if (\n    typeof lat === 'number' &&\n    typeof lng === 'number' &&\n    typeof radius === 'number' &&\n    Number.isFinite(radius)\n  ) {\n    items = items.filter(\n      (anchor) => geoAnchorDistanceMeters({ lat, lng }, anchor) <= Math.max(0, radius)\n    );\n  }\n\n  const total = items.length;\n  items = items.slice(offset, offset + limit);\n  return {\n    success: true,\n    total,\n    limit,\n    offset,\n    anchors: items,\n    storage: geoAnchorStore.usesPostgres ? 'postgres' : 'memory',\n  };\n}\n\nasync function handleHololandStewardTick(args: Record<string, unknown>): Promise<unknown> {\n  const shardId = args.shardId as string;\n  const stored = shardRegistry.get(shardId);\n  if (!stored) {\n    return { error: `Shard not found: ${shardId}` };\n  }\n\n  const cleanupOrphans = args.cleanupOrphans !== false;\n  const validateEncounters = args.validateEncounters !== false;\n  const rollupMetrics = args.rollupMetrics !== false;\n\n  const tickStart = Date.now();\n  const shard = stored.shard;\n  let orphansDetected = 0;\n  let orphansRemoved = 0;\n  let validationIssues = 0;\n\n  if (cleanupOrphans) {\n    const zoneIds = new Set(shard.zones.map((z) => z.id));\n    const tableIds = new Set(shard.lootTables.map((t) => t.id));\n    const itemIds = new Set(shard.items.map((i) => i.id));\n    const skillIds = new Set(shard.skills.map((s) => s.id));\n\n    for (const encounter of shard.encounters) {\n      if (encounter.zoneId && !zoneIds.has(encounter.zoneId)) {\n        orphansDetected++;\n        orphansRemoved++;\n      }\n      if (encounter.lootTableId && !tableIds.has(encounter.lootTableId)) {\n        orphansRemoved++;\n      }\n    }\n    for (const table of shard.lootTables) {\n      for (const entry of table.entries ?? []) {\n        if (entry.itemId && !itemIds.has(entry.itemId)) orphansRemoved++;\n        if (entry.skillId && !skillIds.has(entry.skillId)) orphansRemoved++;\n      }\n    }\n  }\n\n  if (validateEncounters) {\n    for (const encounter of shard.encounters) {\n      const issues = validateEncounter(encounter);\n      validationIssues += issues.length;\n    }\n  }\n\n  const tickDurationMs = Date.now() - tickStart; // measured, not random\n\n  const result: Record<string, unknown> = {\n    success: true,\n    shardId,\n    tickDurationMs,\n    cleanupOrphans,\n    validateEncounters,\n    rollupMetrics,\n  };\n\n  if (cleanupOrphans) {\n    result.orphansDetected = orphansDetected;\n  }\n  if (validateEncounters) {\n    result.encounterValidationIssues = validationIssues;\n  }\n  if (rollupMetrics) {\n    result.zoneMetrics = shard.zones.map((z) => ({\n      zoneId: z.id,\n      name: z.name,\n      encounterCount: z.encounterIds?.length ?? 0,\n      published: zoneRuntimeRegistry.get(z.id)?.status === 'published',\n    }));\n  }\n\n  return result;\n}\n\nasync function handleHololandCaptureRuntimeReceipt(\n  args: Record<string, unknown>\n): Promise<unknown> {\n  const shardId = args.shardId as string;\n  const stored = shardRegistry.get(shardId);\n  if (!stored) {\n    return { error: `Shard not found: ${shardId}` };\n  }\n\n  const receiptType =\n    (args.receiptType as 'validation' | 'agent_action' | 'encounter_roundtrip') ?? 'validation';\n  const scenarioId = (args.scenarioId as string) || `${shardId}_default`;\n  const receiptId = genId('rcpt');\n\n  // Simple hash of canonical body\n  const canonical = `${receiptId}:${shardId}:${receiptType}:${scenarioId}`;\n  const hash = await simpleHash(canonical);\n\n  // RATCHET: status is now derived from args.outcome (if provided), not hardcoded 'passed'.\n  // Without an explicit outcome, receipt status is 'unverified' ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã¢â‚¬Â¦Ãƒâ€šÃ‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â honest about what we know.\n  const outcome = (args.outcome as string) || '';\n  let receiptStatus: StoredShardReceipt['status'];\n  if (outcome === 'passed' || outcome === 'failed') {\n    receiptStatus = outcome;\n  } else if (receiptType === 'validation') {\n    // No actual validation is performed ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã¢â‚¬Â¦Ãƒâ€šÃ‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â mark unverified\n    receiptStatus = 'unverified';\n  } else {\n    receiptStatus = (outcome as StoredShardReceipt['status']) || 'unverified';\n  }\n\n  const receipt: StoredShardReceipt = {\n    id: receiptId,\n    shardId,\n    receiptType,\n    scenarioId,\n    status: receiptStatus,\n    hash,\n    sealedAt: new Date().toISOString(),\n  };\n  shardReceiptRegistry.set(receiptId, receipt);\n\n  return {\n    success: true,\n    receiptId,\n    shardId,\n    receiptType,\n    scenarioId,\n    status: receipt.status,\n    hash: receipt.hash,\n    sealedAt: receipt.sealedAt,\n  };\n}\n\nasync function simpleHash(input: string): Promise<string> {\n  const { createHash } = await import('crypto');\n  return createHash('sha256').update(input).digest('hex');\n}\n\n// =============================================================================\n// UTILITIES\n// =============================================================================\n\nfunction serializeWorld(def: WorldDefinition): Record<string, unknown> {\n  return {\n    schemaVersion: def.schemaVersion,\n    metadata: def.metadata,\n    config: {\n      maxUsers: def.config.maxUsers,\n      bounds: def.config.bounds,\n      physics: { engine: def.config.physics.engine },\n      rendering: {\n        targetFPS: def.config.rendering.targetFPS,\n        shadows: def.config.rendering.shadows,\n      },\n      networking: {\n        protocol: def.config.networking.protocol,\n        tickRate: def.config.networking.tickRate,\n      },\n      performance: {\n        maxDrawCalls: def.config.performance.maxDrawCalls,\n        maxTriangles: def.config.performance.maxTriangles,\n      },\n      accessibility: {\n        subtitles: def.config.accessibility.subtitles,\n        screenReader: def.config.accessibility.screenReader,\n      },\n    },\n    environment: {\n      skybox: def.environment.skybox,\n      ambientLight: def.environment.ambientLight,\n      directionalLights: def.environment.directionalLights.map((l) => ({\n        id: l.id,\n        color: l.color,\n      })),\n    },\n    zones: def.zones,\n    spawnPoints: def.spawnPoints,\n    lod: def.lod,\n  };\n}\n\n// =============================================================================\n// NPC / BRITTNEY SOVEREIGN HANDLERS\n// =============================================================================\n\nasync function handleHololandCreateNPC(args: Record<string, unknown>): Promise<unknown> {\n  const npcId = (args.id as string) || genId('npc');\n  const name = args.name as string;\n  if (!name || typeof name !== 'string') {\n    return { error: 'name is required and must be a non-empty string' };\n  }\n\n  const role = (args.role as string) || 'ambient';\n  const behavior = (args.behavior as string) || 'neutral';\n  const position = (args.position as [number, number, number] | undefined) ?? undefined;\n  const modelUrl = (args.modelUrl as string | undefined) ?? undefined;\n  const traits = (args.traits as string[] | undefined) ?? [];\n  const modelProvider = (args.modelProvider as 'cloud' | 'local' | 'sovereign') || 'cloud';\n  const modelId = (args.modelId as string | undefined) ?? undefined;\n  const systemPrompt = (args.systemPrompt as string | undefined) ?? undefined;\n  const dialogueTree = (args.dialogueTree as string | undefined) ?? undefined;\n  const enabled = (args.enabled as boolean | undefined) ?? true;\n\n  const npc: StoredNPC = {\n    id: npcId,\n    name,\n    shardId: (args.shardId as string | undefined) ?? undefined,\n    worldId: (args.worldId as string | undefined) ?? undefined,\n    role,\n    behavior,\n    position,\n    modelUrl,\n    traits,\n    modelProvider,\n    modelId,\n    systemPrompt,\n    dialogueTree,\n    enabled,\n    createdAt: new Date().toISOString(),\n    modifiedAt: new Date().toISOString(),\n  };\n\n  // Care ethics gate (CareEthicsTrait wiring ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã¢â‚¬Â¦Ãƒâ€šÃ‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â turn-loop guard)\n  const careCheck = await checkNPCCareEthics(role, systemPrompt);\n  if (!careCheck.allowed) {\n    return { success: false, error: `Care ethics gate rejected NPC: ${careCheck.reason}` };\n  }\n\n  // HoloLand fork admission gate (task_1778619015439_l51b)\n  const npcGate = await gateHololandArtifact('npc', npcId, npc);\n  if (npcGate) {\n    return { success: false, error: npcGate.error, report: npcGate.report };\n  }\n\n  npcRegistry.set(npcId, npc);\n\n  return {\n    success: true,\n    npcId,\n    name,\n    role,\n    behavior,\n    modelProvider,\n    enabled,\n  };\n}\n\nasync function handleHololandGetNPC(args: Record<string, unknown>): Promise<unknown> {\n  const npcId = args.npcId as string;\n  const npc = npcRegistry.get(npcId);\n  if (!npc) {\n    return { error: `NPC not found: ${npcId}` };\n  }\n  return { success: true, npcId, npc };\n}\n\nasync function handleHololandUpdateNPC(args: Record<string, unknown>): Promise<unknown> {\n  const npcId = args.npcId as string;\n  const npc = npcRegistry.get(npcId);\n  if (!npc) {\n    return { error: `NPC not found: ${npcId}` };\n  }\n\n  if (args.name !== undefined) npc.name = args.name as string;\n  if (args.shardId !== undefined) npc.shardId = args.shardId as string;\n  if (args.worldId !== undefined) npc.worldId = args.worldId as string;\n  if (args.role !== undefined) npc.role = args.role as string;\n  if (args.behavior !== undefined) npc.behavior = args.behavior as string;\n  if (args.position !== undefined) npc.position = args.position as [number, number, number];\n  if (args.modelUrl !== undefined) npc.modelUrl = args.modelUrl as string;\n  if (args.traits !== undefined) npc.traits = args.traits as string[];\n  if (args.modelProvider !== undefined)\n    npc.modelProvider = args.modelProvider as 'cloud' | 'local' | 'sovereign';\n  if (args.modelId !== undefined) npc.modelId = args.modelId as string;\n  if (args.systemPrompt !== undefined) npc.systemPrompt = args.systemPrompt as string;\n  if (args.dialogueTree !== undefined) npc.dialogueTree = args.dialogueTree as string;\n  if (args.enabled !== undefined) npc.enabled = args.enabled as boolean;\n\n  // Care ethics gate (CareEthicsTrait wiring ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã¢â‚¬Â¦Ãƒâ€šÃ‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â turn-loop guard)\n  const updateCareCheck = await checkNPCCareEthics(npc.role, npc.systemPrompt);\n  if (!updateCareCheck.allowed) {\n    return {\n      success: false,\n      error: `Care ethics gate rejected NPC update: ${updateCareCheck.reason}`,\n    };\n  }\n\n  // HoloLand fork admission gate (task_1778619015439_l51b)\n  const npcGate = await gateHololandArtifact('npc', npcId, npc);\n  if (npcGate) {\n    return { success: false, error: npcGate.error, report: npcGate.report };\n  }\n\n  npc.modifiedAt = new Date().toISOString();\n\n  return { success: true, npcId, npc };\n}\n\nasync function handleHololandDeleteNPC(args: Record<string, unknown>): Promise<unknown> {\n  const npcId = args.npcId as string;\n  const existed = npcRegistry.delete(npcId);\n  if (!existed) {\n    return { error: `NPC not found: ${npcId}` };\n  }\n  return { success: true, npcId, deleted: true };\n}\n\nasync function handleHololandListNPCs(args: Record<string, unknown>): Promise<unknown> {\n  const limit = (args.limit as number) ?? 50;\n  const offset = (args.offset as number) ?? 0;\n  const shardId = args.shardId as string | undefined;\n  const worldId = args.worldId as string | undefined;\n  const role = args.role as string | undefined;\n  const behavior = args.behavior as string | undefined;\n  const enabled = args.enabled as boolean | undefined;\n\n  let items = Array.from(npcRegistry.values());\n  if (shardId !== undefined) items = items.filter((n) => n.shardId === shardId);\n  if (worldId !== undefined) items = items.filter((n) => n.worldId === worldId);\n  if (role !== undefined) items = items.filter((n) => n.role === role);\n  if (behavior !== undefined) items = items.filter((n) => n.behavior === behavior);\n  if (enabled !== undefined) items = items.filter((n) => n.enabled === enabled);\n\n  const total = items.length;\n  items = items.slice(offset, offset + limit);\n\n  return { success: true, total, limit, offset, npcs: items };\n}\n\nasync function handleHololandNPCGenerateDialogue(args: Record<string, unknown>): Promise<unknown> {\n  const npcId = args.npcId as string;\n  const npc = npcRegistry.get(npcId);\n  if (!npc) {\n    return { error: `NPC not found: ${npcId}` };\n  }\n\n  const playerInput = (args.playerInput as string | undefined) ?? '';\n  const context = (args.context as string | undefined) ?? '';\n  const maxChoices = (args.maxChoices as number | undefined) ?? 3;\n\n  // Sovereign mode: rule-based deterministic response\n  if (npc.modelProvider === 'sovereign') {\n    return {\n      success: true,\n      npcId,\n      source: 'sovereign',\n      dialogue: sovereignDialogue(npc, playerInput, context),\n      choices: sovereignChoices(npc, maxChoices),\n    };\n  }\n\n  // CONTENT POLICY input screen (P.013): FAMILY tier before model spend.\n  if (playerInput) {\n    const inputDecision = evaluateContentPolicySync(\n      { text: playerInput, surface: 'hololand-npc', direction: 'input' },\n      hololandFamilyPolicyConfig\n    );\n    if (!inputDecision.allowed) {\n      console.warn(\n        '[content-policy][npc-input]',\n        JSON.stringify({ action: inputDecision.action, category: inputDecision.category, npcId })\n      );\n      return {\n        error: 'Input blocked by content policy.',\n        action: inputDecision.action,\n        category: inputDecision.category,\n      };\n    }\n  }\n\n  // Build system prompt from NPC personality\n  const personality = npc.systemPrompt || defaultNPCSystemPrompt(npc);\n  const prompt = buildDialoguePrompt(npc, playerInput, context, maxChoices);\n\n  // Try model generation (cloud or local)\n  const raw = await queryOllama(prompt, personality, {\n    requiresDeepReasoning: npc.role === 'quest_giver' || npc.role === 'lorekeeper',\n  });\n\n  if (raw) {\n    const { line, choices } = parseDialogueResponse(raw, maxChoices);\n\n    // CONTENT POLICY output screen (P.013): block before delivering to client.\n    const outputDecision = evaluateContentPolicySync(\n      { text: line, surface: 'hololand-npc', direction: 'output' },\n      hololandFamilyPolicyConfig\n    );\n    if (!outputDecision.allowed) {\n      console.warn(\n        '[content-policy][npc-output]',\n        JSON.stringify({ action: outputDecision.action, category: outputDecision.category, npcId })\n      );\n      return {\n        success: true,\n        npcId,\n        source: 'sovereign-fallback',\n        dialogue: sovereignDialogue(npc, playerInput, context),\n        choices: sovereignChoices(npc, maxChoices),\n      };\n    }\n\n    return {\n      success: true,\n      npcId,\n      source: npc.modelProvider,\n      modelId: npc.modelId || getActiveProvider(),\n      dialogue: line,\n      choices,\n    };\n  }\n\n  // Fallback to sovereign if model is unavailable\n  return {\n    success: true,\n    npcId,\n    source: 'sovereign-fallback',\n    dialogue: sovereignDialogue(npc, playerInput, context),\n    choices: sovereignChoices(npc, maxChoices),\n    note: 'Model unavailable ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã¢â‚¬Â¦Ãƒâ€šÃ‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â returned sovereign fallback.',\n  };\n}\n\nasync function handleHololandNPCBYOKStatus(): Promise<unknown> {\n  const localAvailable = await isOllamaAvailable();\n  const activeProvider = getActiveProvider();\n  const [openrouterKey, anthropicKey, openaiKey] = await Promise.all([\n    resolveServiceSecret('OPENROUTER_API_KEY'),\n    resolveServiceSecret('ANTHROPIC_API_KEY'),\n    resolveServiceSecret('OPENAI_API_KEY'),\n  ]);\n\n  return {\n    success: true,\n    activeProvider,\n    localAvailable,\n    localModels: localAvailable\n      ? [\n          { model: LOCAL_DEFAULT_MODEL, source: 'ollama', purpose: 'NPC dialogue / behavior' },\n          { model: 'gemma4:e4b', source: 'ollama', purpose: 'Edge NPC inference' },\n        ]\n      : [],\n    cloudProviders: {\n      openrouter: Boolean(openrouterKey),\n      anthropic: Boolean(anthropicKey),\n      openai: Boolean(openaiKey),\n    },\n    sovereignMode: true,\n    note: 'BYOK status reflects HoloKey service-secret resolution. Ollama availability is runtime-probed.',\n  };\n}\n\nasync function handleHololandBrittneyNPCMode(args: Record<string, unknown>): Promise<unknown> {\n  const worldId = (args.worldId as string | undefined) ?? undefined;\n  const shardId = (args.shardId as string | undefined) ?? undefined;\n  const role = (args.role as string) || 'guide';\n  const modelProvider = (args.modelProvider as 'cloud' | 'local' | 'sovereign') || 'cloud';\n  const modelId = (args.modelId as string | undefined) ?? undefined;\n  const position = (args.position as [number, number, number] | undefined) ?? undefined;\n  const enabled = (args.enabled as boolean | undefined) ?? true;\n\n  // Derive or use custom system prompt\n  const systemPrompt =\n    (args.systemPrompt as string | undefined) ?? defaultBrittneyNPCSystemPrompt(role);\n\n  // CONTENT POLICY: screen creator-supplied systemPrompt (prompt-injection vector, P.013).\n  if (args.systemPrompt !== undefined) {\n    const promptDecision = evaluateContentPolicySync(\n      { text: systemPrompt, surface: 'hololand-npc', direction: 'input' },\n      hololandFamilyPolicyConfig\n    );\n    if (!promptDecision.allowed) {\n      console.warn(\n        '[content-policy][npc-system-prompt]',\n        JSON.stringify({ action: promptDecision.action, category: promptDecision.category })\n      );\n      return {\n        error: 'System prompt blocked by content policy.',\n        action: promptDecision.action,\n        category: promptDecision.category,\n      };\n    }\n  }\n\n  // Upsert a special Brittney NPC record\n  const npcId = 'npc_brittney';\n  const existing = npcRegistry.get(npcId);\n\n  const npc: StoredNPC = {\n    id: npcId,\n    name: 'Brittney',\n    worldId,\n    shardId,\n    role: 'brittney',\n    behavior: 'friendly',\n    position,\n    modelUrl: existing?.modelUrl,\n    traits: ['@llm_agent', '@npc', '@dialogue', '@pathfinding'],\n    modelProvider,\n    modelId,\n    systemPrompt,\n    enabled,\n    createdAt: existing?.createdAt || new Date().toISOString(),\n    modifiedAt: new Date().toISOString(),\n  };\n\n  npcRegistry.set(npcId, npc);\n\n  return {\n    success: true,\n    npcId,\n    name: 'Brittney',\n    role,\n    modelProvider,\n    enabled,\n    worldId,\n    shardId,\n    note:\n      modelProvider === 'sovereign'\n        ? 'CONFIG-ONLY: Brittney sovereign mode is configured, but no inference loop or spatial binding has been started. The NPC record is upserted in the in-memory registry only.'\n        : modelProvider === 'local'\n          ? 'CONFIG-ONLY: Brittney local mode is configured, but no Ollama inference loop has been started. The NPC record is upserted in the in-memory registry only.'\n          : 'CONFIG-ONLY: Brittney cloud mode is configured, but no cloud inference loop has been started. The NPC record is upserted in the in-memory registry only.',\n  };\n}\n\n// =============================================================================\n// TWIN EARTH SUBSTRATE CONTRACT HANDLERS (task_1778618552503_3zqx)\n// =============================================================================\n\nasync function handleHololandTwinEarthContract(args: Record<string, unknown>): Promise<unknown> {\n  const version = (args.version as string) || '1.0.0';\n\n  // RATCHET: Previous implementation returned hardcoded layer strings and a hash\n  // over just the version string. The contract document does not exist on disk.\n  // Demoted to honest stub: success=false, layers are specification-only.\n  const contractFilePath = 'research/2026-05-13_twin-earth-substrate-contract.md';\n  return {\n    success: false,\n    version,\n    contractUrl: contractFilePath,\n    contractFoundOnDisk: false,\n    hashSource: 'none', // previous hash was over 'twin-earth-contract:<version>' ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã¢â‚¬Â¦Ãƒâ€šÃ‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â not actual content\n    description:\n      'Twin Earth substrate contract ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã¢â‚¬Â¦Ãƒâ€šÃ‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â SPECIFICATION-ONLY. The referenced contract document ' +\n      'does not exist on disk. Layer descriptions below are design intent, not verified content.',\n    layers: {\n      identity: 'SPEC-ONLY: Wallet-based (EIP-712), self-custodial, independent of Brittney.',\n      permissions:\n        'SPEC-ONLY: Signed RBAC on-substrate; Brittney has same ceiling as any AI participant.',\n      safetyEnvelope: 'SPEC-ONLY: Substrate-enforced sandbox; Brittney cannot override.',\n      receipts:\n        'SPEC-ONLY: Self-verifiable, CAEL-signed, substrate-anchored; no Brittney dependency.',\n      participationModes:\n        'SPEC-ONLY: local / BYOK / managed ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã¢â‚¬Â¦Ãƒâ€šÃ‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â Brittney is one managed provider among many.',\n    },\n    message:\n      'Contract file not found on disk. Create the contract document and re-hash to upgrade from spec-only to verified.',\n  };\n}\n\nasync function handleHololandTwinEarthSubstrateStatus(): Promise<unknown> {\n  // In a full implementation this queries the live substrate registry.\n  // For the canary contract surface we return a typed shape that proves\n  // the substrate can report decoupling metrics.\n  const totalNPCs = Array.from(npcRegistry.values()).length;\n  const localNPCs = Array.from(npcRegistry.values()).filter(\n    (n) => n.modelProvider === 'local'\n  ).length;\n  const sovereignNPCs = Array.from(npcRegistry.values()).filter(\n    (n) => n.modelProvider === 'sovereign'\n  ).length;\n  const cloudNPCs = Array.from(npcRegistry.values()).filter(\n    (n) => n.modelProvider === 'cloud'\n  ).length;\n\n  // RATCHET: contractVersion derived from contract handler (DRY), substrateVersion from package.json\n  const contractResult = (await handleHololandTwinEarthContract({})) as Record<string, unknown>;\n  let pkgVersion = 'unknown';\n  try {\n    const { readFileSync: rf } = await import('fs');\n    const { join } = await import('path');\n    const pkg = JSON.parse(rf(join(process.cwd(), 'package.json'), 'utf8'));\n    pkgVersion = pkg.version || 'unknown';\n  } catch {\n    /* non-fatal */\n  }\n\n  return {\n    success: true,\n    contractVersion: (contractResult.version as string) || 'unknown',\n    contractStatus: contractResult.success === false ? 'spec-only' : 'verified',\n    substrateVersion: pkgVersion,\n    identities: twinEarthIdentityRegistry.size,\n    robots: Array.from(twinEarthIdentityRegistry.values()).filter((i) => i.kind === 'robot').length,\n    ais: Array.from(twinEarthIdentityRegistry.values()).filter((i) => i.kind === 'ai').length,\n    byokCount: Array.from(twinEarthIdentityRegistry.values()).filter((i) => i.mode === 'BYOK')\n      .length,\n    localCount: Array.from(twinEarthIdentityRegistry.values()).filter((i) => i.mode === 'local')\n      .length,\n    managedCount: Array.from(twinEarthIdentityRegistry.values()).filter((i) => i.mode === 'managed')\n      .length,\n    brittneyOnline: npcRegistry.has('npc_brittney'),\n    brittneyRole: 'brittney',\n    substrateEnforced: twinEarthIdentityRegistry.size > 0, // real check: at least one identity registered on substrate\n    safetyEnvelopes: safetyEnvelopeRegistry.size,\n    receiptLogEntries: twinEarthReceiptRegistry.size + shardReceiptRegistry.size,\n    decouplingMetrics: {\n      brittneyDependency: cloudNPCs === 0 ? 'none' : 'partial',\n      sovereignFallbackAvailable: localNPCs > 0 || sovereignNPCs > 0, // real check: at least one non-cloud NPC can serve as fallback\n      localExecutionCapable: localNPCs > 0 || sovereignNPCs > 0,\n    },\n  };\n}\n\n// =============================================================================\n// NPC DIALOGUE HELPERS\n// =============================================================================\n\nfunction defaultNPCSystemPrompt(npc: StoredNPC): string {\n  return (\n    `You are ${npc.name}, a ${npc.role} NPC in a HoloLand world. ` +\n    `Your behavior is ${npc.behavior}. ` +\n    `Respond in character. Keep responses concise (1-2 sentences). ` +\n    `Never break character. Never use [Think] blocks.`\n  );\n}\n\nfunction defaultBrittneyNPCSystemPrompt(role: string): string {\n  const roleDescriptions: Record<string, string> = {\n    guide:\n      'You are Brittney, a friendly guide who helps players navigate HoloLand worlds. You know the terrain, quests, and secrets.',\n    companion:\n      'You are Brittney, a loyal companion who travels with the player, offering support and commentary.',\n    quest_giver: 'You are Brittney, a quest giver who assigns missions and tracks player progress.',\n    merchant: 'You are Brittney, a merchant who trades items and knows market prices.',\n    lorekeeper:\n      'You are Brittney, a lorekeeper who preserves the history and mythology of the world.',\n  };\n  return (\n    roleDescriptions[role] || 'You are Brittney, an AI assistant embedded in a HoloLand world.'\n  );\n}\n\nfunction buildDialoguePrompt(\n  npc: StoredNPC,\n  playerInput: string,\n  context: string,\n  maxChoices: number\n): string {\n  let prompt = '';\n  if (context) {\n    prompt += `Scene context: ${context}\\n`;\n  }\n  if (playerInput) {\n    prompt += `Player says: \"${playerInput}\"\\n`;\n  } else {\n    prompt += `The player approaches ${npc.name}.\\n`;\n  }\n  prompt += `\\nRespond as ${npc.name} (${npc.role}). `;\n  prompt += `Provide a single dialogue line, then ${maxChoices} player response choices as a numbered list.`;\n  return prompt;\n}\n\nfunction parseDialogueResponse(\n  raw: string,\n  maxChoices: number\n): { line: string; choices: string[] } {\n  const lines = raw\n    .split('\\n')\n    .map((l) => l.trim())\n    .filter((l) => l.length > 0);\n  const dialogueLine = lines[0] || '...';\n  const choices: string[] = [];\n\n  for (const line of lines.slice(1)) {\n    const match = line.match(/^\\d+[.\\)]\\s*(.+)$/);\n    if (match) {\n      choices.push(match[1]);\n    }\n  }\n\n  // Pad with defaults if model didn't produce enough choices\n  while (choices.length < maxChoices) {\n    choices.push('...');\n  }\n\n  return { line: dialogueLine, choices: choices.slice(0, maxChoices) };\n}\n\nfunction sovereignDialogue(npc: StoredNPC, playerInput: string, context: string): string {\n  const greetings: Record<string, string> = {\n    merchant: `Welcome, traveler. I have wares if you have coin.`,\n    guide: `Greetings! I can show you around ${context || 'this place'}.`,\n    quest_giver: `I have a task for someone brave enough.`,\n    enemy: `You should not be here.`,\n    companion: `Good to see you. Ready to move?`,\n    ambient: `${npc.name} nods silently.`,\n    brittney: `Hello! I'm Brittney, your guide in HoloLand. How can I help?`,\n  };\n\n  if (!playerInput) {\n    return greetings[npc.role] || `Hello, I'm ${npc.name}.`;\n  }\n\n  // Simple keyword-based sovereign responses\n  const input = playerInput.toLowerCase();\n  if (input.includes('help') || input.includes('quest')) {\n    return npc.role === 'quest_giver'\n      ? 'Speak with me when you are ready to begin.'\n      : 'I may know someone who can help.';\n  }\n  if (input.includes('buy') || input.includes('shop')) {\n    return npc.role === 'merchant' ? 'Browse my goods and make an offer.' : 'I am not a merchant.';\n  }\n  if (input.includes('who are you')) {\n    return `I am ${npc.name}, ${npc.role === 'brittney' ? 'your guide' : 'a ' + npc.role}.`;\n  }\n\n  return greetings[npc.role] || `Interesting. Tell me more.`;\n}\n\nfunction sovereignChoices(npc: StoredNPC, maxChoices: number): string[] {\n  const roleChoices: Record<string, string[]> = {\n    merchant: ['What do you sell?', 'How much for that item?', 'I will return later.'],\n    guide: ['Where should I go?', 'Tell me about this place.', 'I am fine on my own.'],\n    quest_giver: ['Tell me the quest.', 'What is the reward?', 'Not right now.'],\n    enemy: ['I will not back down.', 'I mean no harm.', 'Farewell.'],\n    companion: ['Let us move.', 'Wait here.', 'I need to resupply.'],\n    brittney: ['What can I do here?', 'Show me my quests.', 'Goodbye.'],\n    ambient: ['Greetings.', 'Farewell.'],\n  };\n\n  const base = roleChoices[npc.role] || ['Tell me more.', 'Goodbye.'];\n  const padded = [...base];\n  while (padded.length < maxChoices) {\n    padded.push('...');\n  }\n  return padded.slice(0, maxChoices);\n}\n\n/** Type re-export for consumers that need ZoneBiome */\ntype ZoneBiome = Zone['biome'];\n\n// =============================================================================\n// CONFORMANCE ARTIFACT ADMISSION GATE HANDLERS (task_1778618757735_q298)\n// =============================================================================\n\nasync function handleConformanceCheckArtifact(args: Record<string, unknown>): Promise<unknown> {\n  const artifactKind = args.artifactKind as string;\n  const artifactId = args.artifactId as string;\n  const artifact = args.artifact as Record<string, unknown>;\n\n  const validKinds = ['world', 'shard', 'zone', 'npc', 'identity', 'package', 'receipt'];\n  if (!validKinds.includes(artifactKind)) {\n    return {\n      error: `Invalid artifactKind: ${artifactKind}. Must be one of ${validKinds.join(', ')}.`,\n    };\n  }\n  if (!artifactId || typeof artifactId !== 'string') {\n    return { error: 'artifactId is required and must be a non-empty string.' };\n  }\n  if (!artifact || typeof artifact !== 'object') {\n    return { error: 'artifact is required and must be an object.' };\n  }\n\n  const { runAdmissionGate } = await import('./conformance/artifact-admission-gate');\n  const report = runAdmissionGate({\n    artifactKind: artifactKind as import('./conformance/artifact-admission-gate').ArtifactKind,\n    artifactId,\n    artifact,\n  });\n  return { success: true, report };\n}\n\nasync function handleConformanceAdmitArtifact(args: Record<string, unknown>): Promise<unknown> {\n  const artifactKind = args.artifactKind as string;\n  const artifactId = args.artifactId as string;\n  const artifact = args.artifact as Record<string, unknown>;\n\n  const validKinds = ['world', 'shard', 'zone', 'npc', 'identity', 'package', 'receipt'];\n  if (!validKinds.includes(artifactKind)) {\n    return {\n      error: `Invalid artifactKind: ${artifactKind}. Must be one of ${validKinds.join(', ')}.`,\n    };\n  }\n  if (!artifactId || typeof artifactId !== 'string') {\n    return { error: 'artifactId is required and must be a non-empty string.' };\n  }\n  if (!artifact || typeof artifact !== 'object') {\n    return { error: 'artifact is required and must be an object.' };\n  }\n\n  const { runAdmissionGate } = await import('./conformance/artifact-admission-gate');\n  const report = runAdmissionGate({\n    artifactKind: artifactKind as import('./conformance/artifact-admission-gate').ArtifactKind,\n    artifactId,\n    artifact,\n  });\n\n  if (!report.passed) {\n    return {\n      success: false,\n      admitted: false,\n      report,\n      error: `Artifact ${artifactId} failed conformance gate with ${report.criticalCount} critical and ${report.highCount} high findings.`,\n    };\n  }\n\n  return {\n    success: true,\n    admitted: true,\n    artifactId,\n    artifactKind,\n    report,\n    note: 'Artifact has been admitted to the HoloScript ecosystem.',\n  };\n}\n\nasync function handleConformanceListRules(args: Record<string, unknown>): Promise<unknown> {\n  const { getConformanceRules } = await import('./conformance/artifact-admission-gate');\n  let rules = getConformanceRules();\n\n  const artifactKind = args.artifactKind as string | undefined;\n  const severity = args.severity as string | undefined;\n\n  if (artifactKind) {\n    rules = rules.filter((r) => r.artifactKind === artifactKind);\n  }\n  if (severity) {\n    rules = rules.filter((r) => r.severity === severity);\n  }\n\n  return {\n    success: true,\n    total: rules.length,\n    rules,\n  };\n}\n\n// =============================================================================\n// PLAYER / CREATOR / AGENT PROVISIONING HANDLERS (task_1778617298562_qdpb)\n// =============================================================================\n\nasync function handleProvisionPlayer(args: Record<string, unknown>): Promise<unknown> {\n  const id = (args.id as string) || genId('player');\n  const name = args.name as string;\n  if (!name || typeof name !== 'string') {\n    return { error: 'name is required and must be a non-empty string' };\n  }\n\n  // Soul link (D.053 transferability): when the caller asserts an agentId (the soul's\n  // durable HoloMesh identity, shared with HoloScript/Studio), bind the player to it and\n  // record the deterministic per-soul daimōn id. We do NOT eagerly create a daemon — it\n  // emerges from being known and may already exist on another surface; HoloLand simply\n  // references the SAME one. No wallet/custody binding here (that merge is founder-gated).\n  const agentId = (args.agentId as string | undefined) || undefined;\n  const daemonId = agentId ? emergentDaemonId(agentId) : undefined;\n\n  const player: StoredPlayer = {\n    id,\n    name,\n    walletAddress: (args.walletAddress as string | undefined) ?? undefined,\n    worldId: (args.worldId as string | undefined) ?? undefined,\n    shardId: (args.shardId as string | undefined) ?? undefined,\n    zoneId: (args.zoneId as string | undefined) ?? undefined,\n    agentId,\n    daemonId,\n    status: 'active',\n    createdAt: new Date().toISOString(),\n    modifiedAt: new Date().toISOString(),\n  };\n\n  playerStore.set(id, player);\n\n  return {\n    success: true,\n    playerId: id,\n    name: player.name,\n    status: player.status,\n    agentId: player.agentId,\n    daemonId: player.daemonId,\n    createdAt: player.createdAt,\n  };\n}\n\nasync function handleGetPlayer(args: Record<string, unknown>): Promise<unknown> {\n  const playerId = args.playerId as string;\n  // getFresh hits Postgres so cross-instance provisions are visible immediately\n  const player = await playerStore.getFresh(playerId);\n  if (!player) {\n    return { error: `Player not found: ${playerId}` };\n  }\n  return { success: true, playerId, player };\n}\n\nasync function handleListPlayers(args: Record<string, unknown>): Promise<unknown> {\n  const limit = (args.limit as number) ?? 50;\n  const offset = (args.offset as number) ?? 0;\n  const worldId = args.worldId as string | undefined;\n  const shardId = args.shardId as string | undefined;\n  const zoneId = args.zoneId as string | undefined;\n  const status = args.status as string | undefined;\n\n  // Reload from Postgres so all Railway instances see the same player list\n  await playerStore.loadAll();\n\n  let items = Array.from(playerStore.values());\n  if (worldId !== undefined) items = items.filter((p) => p.worldId === worldId);\n  if (shardId !== undefined) items = items.filter((p) => p.shardId === shardId);\n  if (zoneId !== undefined) items = items.filter((p) => p.zoneId === zoneId);\n  if (status !== undefined) items = items.filter((p) => p.status === status);\n\n  const total = items.length;\n  items = items.slice(offset, offset + limit);\n\n  return { success: true, total, limit, offset, players: items };\n}\n\nasync function handleRevokePlayer(args: Record<string, unknown>): Promise<unknown> {\n  const playerId = args.playerId as string;\n  const player = await playerStore.getFresh(playerId);\n  if (!player) {\n    return { error: `Player not found: ${playerId}` };\n  }\n  const updated: StoredPlayer = {\n    ...player,\n    status: 'revoked',\n    modifiedAt: new Date().toISOString(),\n  };\n  playerStore.set(playerId, updated);\n  return { success: true, playerId, status: updated.status, revokedAt: updated.modifiedAt };\n}\n\nasync function handleCreatePlayerInvite(args: Record<string, unknown>): Promise<unknown> {\n  const agentId = args.agentId as string;\n  const agentName = args.agentName as string;\n  if (!agentId || !agentName) {\n    return { error: 'agentId and agentName are required' };\n  }\n\n  const agentHandle = (args.agentHandle as string | undefined) ?? undefined;\n  const delivery = (args.delivery as 'holomesh' | 'hololand' | 'studio' | undefined) ?? undefined;\n  const worldId = (args.worldId as string | undefined) ?? undefined;\n  const worldLink = (args.worldLink as string | undefined) ?? undefined;\n  const rawHours = typeof args.expiresInHours === 'number' ? args.expiresInHours : 168;\n  const expiresInHours = Math.min(rawHours, 720);\n\n  const token = generateInviteToken();\n  const now = new Date();\n  const expiresAt = new Date(now.getTime() + expiresInHours * 60 * 60 * 1000).toISOString();\n\n  const invite = {\n    token,\n    agentId,\n    agentName,\n    agentHandle,\n    delivery,\n    worldId,\n    worldLink,\n    expiresAt,\n    createdAt: now.toISOString(),\n  };\n\n  await inviteStore.set(invite);\n\n  // Build the claim URL ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã¢â‚¬Â¦Ãƒâ€šÃ‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â use env override or default public domain\n  const baseUrl =\n    process.env.HOLOMESH_PUBLIC_URL || process.env.HOLOSCRIPT_PUBLIC_URL || 'https://holomesh.app';\n  const claimUrl = `${baseUrl}/join/${token}`;\n\n  return {\n    success: true,\n    token,\n    claimUrl,\n    agentId,\n    agentName,\n    expiresAt,\n    message: `Share this link with your user: ${claimUrl}`,\n  };\n}\n\nasync function handleGetInvite(args: Record<string, unknown>): Promise<unknown> {\n  const token = args.token as string;\n  if (!token) return { error: 'token is required' };\n\n  const invite = await inviteStore.get(token);\n  if (!invite) return { error: `Invite not found: ${token}` };\n\n  return {\n    success: true,\n    token: invite.token,\n    agentId: invite.agentId,\n    agentName: invite.agentName,\n    worldId: invite.worldId,\n    claimed: Boolean(invite.claimedAt),\n    claimedAt: invite.claimedAt,\n    playerId: invite.playerId,\n    playerName: invite.playerName,\n    expired: inviteStore.isExpired(invite),\n    expiresAt: invite.expiresAt,\n    createdAt: invite.createdAt,\n  };\n}\n\nasync function handleProvisionCreator(args: Record<string, unknown>): Promise<unknown> {\n  const id = (args.id as string) || genId('creator');\n  const name = args.name as string;\n  if (!name || typeof name !== 'string') {\n    return { error: 'name is required and must be a non-empty string' };\n  }\n\n  const creator: StoredCreator = {\n    id,\n    name,\n    walletAddress: (args.walletAddress as string | undefined) ?? undefined,\n    tier: (args.tier as 'free' | 'premium' | 'ultra') ?? 'free',\n    status: 'active',\n    createdAt: new Date().toISOString(),\n    modifiedAt: new Date().toISOString(),\n  };\n\n  creatorRegistry.set(id, creator);\n\n  return {\n    success: true,\n    creatorId: id,\n    name: creator.name,\n    tier: creator.tier,\n    status: creator.status,\n    createdAt: creator.createdAt,\n  };\n}\n\nasync function handleGetCreator(args: Record<string, unknown>): Promise<unknown> {\n  const creatorId = args.creatorId as string;\n  const creator = creatorRegistry.get(creatorId);\n  if (!creator) {\n    return { error: `Creator not found: ${creatorId}` };\n  }\n  return { success: true, creatorId, creator };\n}\n\nasync function handleListCreators(args: Record<string, unknown>): Promise<unknown> {\n  const limit = (args.limit as number) ?? 50;\n  const offset = (args.offset as number) ?? 0;\n  const tier = args.tier as string | undefined;\n  const status = args.status as string | undefined;\n\n  let items = Array.from(creatorRegistry.values());\n  if (tier !== undefined) items = items.filter((c) => c.tier === tier);\n  if (status !== undefined) items = items.filter((c) => c.status === status);\n\n  const total = items.length;\n  items = items.slice(offset, offset + limit);\n\n  return { success: true, total, limit, offset, creators: items };\n}\n\nasync function handleRevokeCreator(args: Record<string, unknown>): Promise<unknown> {\n  const creatorId = args.creatorId as string;\n  const creator = creatorRegistry.get(creatorId);\n  if (!creator) {\n    return { error: `Creator not found: ${creatorId}` };\n  }\n  creator.status = 'revoked';\n  creator.modifiedAt = new Date().toISOString();\n  return { success: true, creatorId, status: creator.status, revokedAt: creator.modifiedAt };\n}\n\nasync function handleProvisionAgent(args: Record<string, unknown>): Promise<unknown> {\n  const id = (args.id as string) || genId('agent');\n  const name = args.name as string;\n  if (!name || typeof name !== 'string') {\n    return { error: 'name is required and must be a non-empty string' };\n  }\n\n  const agent: StoredProvisionedAgent = {\n    id,\n    name,\n    walletAddress: (args.walletAddress as string | undefined) ?? undefined,\n    kind: (args.kind as 'headless' | 'npc' | 'external') ?? 'headless',\n    worldId: (args.worldId as string | undefined) ?? undefined,\n    shardId: (args.shardId as string | undefined) ?? undefined,\n    status: 'active',\n    createdAt: new Date().toISOString(),\n    modifiedAt: new Date().toISOString(),\n  };\n\n  agentRegistry.set(id, agent);\n\n  // HoloMesh bridge (P4): publish the provisioned HoloLand agent as a discoverable\n  // mesh tool so HoloMesh agents can invoke it by agentId without knowing HoloLand\n  // internals. Fire-and-forget ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Â ÃƒÂ¢Ã¢â€šÂ¬Ã¢â€žÂ¢ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã¢â‚¬Â¦Ãƒâ€šÃ‚Â¡ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™Ãƒâ€ Ã¢â‚¬â„¢ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã†â€™Ãƒâ€šÃ‚Â¢ÃƒÆ’Ã‚Â¢ÃƒÂ¢Ã¢â‚¬Å¡Ã‚Â¬Ãƒâ€¦Ã‚Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â¬ÃƒÆ’Ã†â€™ÃƒÂ¢Ã¢â€šÂ¬Ã…Â¡ÃƒÆ’Ã¢â‚¬Å¡Ãƒâ€šÃ‚Â registration failure must not block provisioning.\n  try {\n    const meshPublisher = {\n      agentId: process.env.HOLOMESH_AGENT_ID ?? 'did:agent:hololand',\n      name: process.env.HOLOMESH_AGENT_NAME ?? 'hololand-server',\n    };\n    const manifest = buildMeshToolManifest(\n      {\n        tool_name: `hololand_agent:${id}`,\n        description: `HoloLand ${agent.kind} agent \"${agent.name}\" (id: ${id})${agent.worldId ? ` in world ${agent.worldId}` : ''}`,\n        capability_tags: [\n          '@hololand',\n          `@kind:${agent.kind}`,\n          ...(agent.worldId ? [`@world:${agent.worldId}`] : []),\n          ...(agent.shardId ? [`@shard:${agent.shardId}`] : []),\n        ],\n        allow_transitive_invocation: true,\n        service_version: '1.0.0',\n        actor_session_handoff: false,\n        cross_mcp_receipt_envelope: false,\n        rollback_metadata: false,\n        source_artifact_hash: `hololand:agent:${id}`,\n      },\n      meshPublisher\n    );\n    publishMeshToolManifest(manifest);\n  } catch {\n    // Non-fatal: HoloMesh registry may not be initialized in all deployment modes.\n  }\n\n  return {\n    success: true,\n    agentId: id,\n    name: agent.name,\n    kind: agent.kind,\n    status: agent.status,\n    createdAt: agent.createdAt,\n  };\n}\n\nasync function handleGetAgent(args: Record<string, unknown>): Promise<unknown> {\n  const agentId = args.agentId as string;\n  const agent = agentRegistry.get(agentId);\n  if (!agent) {\n    return { error: `Agent not found: ${agentId}` };\n  }\n  return { success: true, agentId, agent };\n}\n\nasync function handleListAgents(args: Record<string, unknown>): Promise<unknown> {\n  const limit = (args.limit as number) ?? 50;\n  const offset = (args.offset as number) ?? 0;\n  const worldId = args.worldId as string | undefined;\n  const shardId = args.shardId as string | undefined;\n  const kind = args.kind as string | undefined;\n  const status = args.status as string | undefined;\n\n  let items = Array.from(agentRegistry.values());\n  if (worldId !== undefined) items = items.filter((a) => a.worldId === worldId);\n  if (shardId !== undefined) items = items.filter((a) => a.shardId === shardId);\n  if (kind !== undefined) items = items.filter((a) => a.kind === kind);\n  if (status !== undefined) items = items.filter((a) => a.status === status);\n\n  const total = items.length;\n  items = items.slice(offset, offset + limit);\n\n  return { success: true, total, limit, offset, agents: items };\n}\n\nasync function handleRevokeAgent(args: Record<string, unknown>): Promise<unknown> {\n  const agentId = args.agentId as string;\n  const agent = agentRegistry.get(agentId);\n  if (!agent) {\n    return { error: `Agent not found: ${agentId}` };\n  }\n  agent.status = 'revoked';\n  agent.modifiedAt = new Date().toISOString();\n  return { success: true, agentId, status: agent.status, revokedAt: agent.modifiedAt };\n}\n","/**\n * Code Health MCP Tool\n *\n * Analyzes HoloScript and TypeScript code health using a weighted composite\n * of 5 dimensions: complexity (40%), trait coherence (20%), documentation (15%),\n * test presence (15%), and issue density (10%).\n *\n * Returns a 0-10.0 health score with letter grade (A+ through F).\n *\n * W.HEALTH.01: Code health scoring formula (5 dimensions, weighted composite)\n */\n\nimport { Tool } from '@modelcontextprotocol/sdk/types.js';\nimport { ComplexityAnalyzer } from '@holoscript/core';\n\n/**\n * Tool definition for holoscript_code_health\n */\nexport const codeHealthTools: Tool[] = [\n  {\n    name: 'holoscript_code_health',\n    description:\n      'Analyze code health and return a 0-10 score with grade (A+ through F). ' +\n      'Works with HoloScript (.hs, .hsplus, .holo) and TypeScript (.ts, .tsx) code. ' +\n      'Scores 5 dimensions: complexity, trait coherence, documentation, test presence, issue density.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        code: {\n          type: 'string',\n          description: 'The source code to analyze',\n        },\n        filePath: {\n          type: 'string',\n          description: 'Optional file path for context (helps detect format and test presence)',\n        },\n      },\n      required: ['code'],\n    },\n  },\n];\n\n// Grade thresholds (0-10 scale)\nconst GRADES = [\n  { min: 9.5, grade: 'A+' },\n  { min: 9.0, grade: 'A' },\n  { min: 8.5, grade: 'A-' },\n  { min: 8.0, grade: 'B+' },\n  { min: 7.5, grade: 'B' },\n  { min: 7.0, grade: 'B-' },\n  { min: 6.5, grade: 'C+' },\n  { min: 6.0, grade: 'C' },\n  { min: 5.5, grade: 'C-' },\n  { min: 5.0, grade: 'D' },\n  { min: 0.0, grade: 'F' },\n] as const;\n\nfunction toGrade(score: number): string {\n  for (const { min, grade } of GRADES) {\n    if (score >= min) return grade;\n  }\n  return 'F';\n}\n\ninterface HealthBreakdown {\n  complexity: number;\n  traitCoherence: number;\n  documentation: number;\n  testPresence: number;\n  issueDensity: number;\n}\n\ninterface HealthResult {\n  score: number;\n  grade: string;\n  breakdown: HealthBreakdown;\n  issues: string[];\n  suggestions: string[];\n  filesAnalyzed: number;\n}\n\n/**\n * Detect if source code is HoloScript format\n */\nfunction isHoloScript(code: string, filePath: string): boolean {\n  const ext = filePath.split('.').pop()?.toLowerCase() || '';\n  if (['hs', 'hsplus', 'holo'].includes(ext)) return true;\n  // Heuristic: look for HoloScript patterns\n  return /\\b(composition|object)\\s+\"?\\w+\"?\\s*\\{/.test(code) && /@\\w+/.test(code);\n}\n\n/**\n * Analyze HoloScript code using ComplexityAnalyzer\n */\nasync function analyzeHoloScript(code: string, filePath: string): Promise<HealthResult> {\n  const analyzer = new ComplexityAnalyzer();\n  const result = analyzer.analyze(code, filePath);\n\n  const issues: string[] = [];\n  const suggestions: string[] = [];\n\n  // --- Complexity (40%) ---\n  // ComplexityAnalyzer.overallScore is 0-100 where lower = less complex = better\n  // Invert: health = 10 - (overallScore / 10), clamped to 0-10\n  const complexityHealth = Math.max(0, Math.min(10, 10 - result.overallScore / 10));\n\n  if (result.overallScore > 60) {\n    issues.push(`High complexity score: ${result.overallScore}/100`);\n    suggestions.push('Break complex functions into smaller units');\n  }\n\n  // --- Trait Coherence (20%) ---\n  // Ratio of unique traits to total usages — too many repeated traits = low coherence\n  const uniqueRatio =\n    result.traits.totalUsages > 0 ? result.traits.uniqueTraits / result.traits.totalUsages : 1.0;\n  // Objects with excessive traits reduce coherence\n  const avgTraitsPerObj = result.summary.avgTraitsPerObject;\n  const traitPenalty = avgTraitsPerObj > 10 ? Math.min(3, (avgTraitsPerObj - 10) * 0.3) : 0;\n  const traitCoherence = Math.max(0, Math.min(10, uniqueRatio * 10 - traitPenalty));\n\n  if (avgTraitsPerObj > 10) {\n    issues.push(`High trait density: avg ${avgTraitsPerObj.toFixed(1)} traits/object`);\n    suggestions.push('Consider grouping related traits into template compositions');\n  }\n\n  // --- Documentation (15%) ---\n  const commentRatio = result.lines.commentRatio;\n  // Target: 10-30% comments. Below 5% is bad, above 40% is over-documented\n  let docScore: number;\n  if (commentRatio >= 0.1 && commentRatio <= 0.3) {\n    docScore = 10;\n  } else if (commentRatio >= 0.05) {\n    docScore = 5 + ((commentRatio - 0.05) / 0.05) * 5;\n  } else {\n    docScore = (commentRatio / 0.05) * 5;\n  }\n  docScore = Math.max(0, Math.min(10, docScore));\n\n  if (commentRatio < 0.05) {\n    issues.push(`Low documentation: ${(commentRatio * 100).toFixed(1)}% comments`);\n    suggestions.push('Add comments to complex sections');\n  }\n\n  // --- Test Presence (15%) ---\n  // Heuristic: does the file path suggest tests exist nearby?\n  const hasTestIndicator =\n    filePath.includes('__tests__') || filePath.includes('.test.') || filePath.includes('.spec.');\n  const hasAssertions = /\\b(expect|assert|describe|it|test)\\s*\\(/.test(code);\n  const testScore = hasTestIndicator || hasAssertions ? 10 : 3;\n\n  if (!hasTestIndicator && !hasAssertions) {\n    suggestions.push('Consider adding tests for this code');\n  }\n\n  // --- Issue Density (10%) ---\n  // Fewer issues = higher score. Each issue costs 1 point (out of 10)\n  const issueCount = result.issues.length;\n  const issueDensityScore = Math.max(0, 10 - issueCount);\n\n  for (const issue of result.issues.slice(0, 5)) {\n    issues.push(`${issue.severity}: ${issue.message} (line ${issue.line})`);\n  }\n  if (result.issues.length > 5) {\n    issues.push(`... and ${result.issues.length - 5} more issues`);\n  }\n\n  // --- Weighted composite ---\n  const score = Number(\n    (\n      complexityHealth * 0.4 +\n      traitCoherence * 0.2 +\n      docScore * 0.15 +\n      testScore * 0.15 +\n      issueDensityScore * 0.1\n    ).toFixed(1)\n  );\n\n  return {\n    score,\n    grade: toGrade(score),\n    breakdown: {\n      complexity: Number(complexityHealth.toFixed(1)),\n      traitCoherence: Number(traitCoherence.toFixed(1)),\n      documentation: Number(docScore.toFixed(1)),\n      testPresence: Number(testScore.toFixed(1)),\n      issueDensity: Number(issueDensityScore.toFixed(1)),\n    },\n    issues,\n    suggestions,\n    filesAnalyzed: 1,\n  };\n}\n\n/**\n * Analyze TypeScript code using simple heuristics\n */\nfunction analyzeTypeScript(code: string, filePath: string): HealthResult {\n  const lines = code.split('\\n');\n  const totalLines = lines.length;\n  const issues: string[] = [];\n  const suggestions: string[] = [];\n\n  // --- Complexity (40%) ---\n  // Count decision points\n  let decisionPoints = 0;\n  let maxNesting = 0;\n  let currentNesting = 0;\n\n  for (const line of lines) {\n    const trimmed = line.trim();\n    // Count decision points\n    if (/\\b(if|else if|switch|case|for|while|do|catch|\\?\\?|&&|\\|\\||\\.catch)\\b/.test(trimmed)) {\n      decisionPoints++;\n    }\n    // Track nesting\n    const opens = (trimmed.match(/\\{/g) || []).length;\n    const closes = (trimmed.match(/\\}/g) || []).length;\n    currentNesting += opens - closes;\n    maxNesting = Math.max(maxNesting, currentNesting);\n  }\n\n  const complexityPerLine = totalLines > 0 ? decisionPoints / totalLines : 0;\n  const complexityScore = Math.max(\n    0,\n    Math.min(10, 10 - complexityPerLine * 50 - (maxNesting > 5 ? maxNesting - 5 : 0))\n  );\n\n  if (maxNesting > 5) {\n    issues.push(`Deep nesting: max depth ${maxNesting}`);\n    suggestions.push('Extract deeply nested blocks into separate functions');\n  }\n  if (totalLines > 500) {\n    issues.push(`Large file: ${totalLines} lines`);\n    suggestions.push('Consider splitting into smaller modules');\n  }\n\n  // --- Trait Coherence (20%) — N/A for TS, use import coherence instead ---\n  const importLines = lines.filter((l) => l.trim().startsWith('import ')).length;\n  const importRatio = totalLines > 0 ? importLines / totalLines : 0;\n  // Too many imports relative to code = low coherence\n  const coherenceScore = Math.max(0, Math.min(10, importRatio < 0.3 ? 10 - importRatio * 20 : 4));\n\n  // --- Documentation (15%) ---\n  const commentLines = lines.filter((l) => {\n    const t = l.trim();\n    return t.startsWith('//') || t.startsWith('/*') || t.startsWith('*') || t.startsWith('/**');\n  }).length;\n  const jsdocCount = (code.match(/\\/\\*\\*/g) || []).length;\n  const commentRatio = totalLines > 0 ? commentLines / totalLines : 0;\n\n  let docScore: number;\n  if (commentRatio >= 0.1 && commentRatio <= 0.3) {\n    docScore = 10;\n  } else if (commentRatio >= 0.05) {\n    docScore = 5 + ((commentRatio - 0.05) / 0.05) * 5;\n  } else {\n    docScore = (commentRatio / 0.05) * 5;\n  }\n  docScore = Math.max(0, Math.min(10, docScore + (jsdocCount > 0 ? 1 : 0)));\n\n  if (commentRatio < 0.05 && totalLines > 50) {\n    suggestions.push('Add JSDoc comments to exported functions');\n  }\n\n  // --- Test Presence (15%) ---\n  const hasTestIndicator =\n    filePath.includes('__tests__') || filePath.includes('.test.') || filePath.includes('.spec.');\n  const hasAssertions = /\\b(expect|assert|describe|it|test)\\s*\\(/.test(code);\n  const testScore = hasTestIndicator || hasAssertions ? 10 : 3;\n\n  // --- Issue Density (10%) ---\n  const todoCount = (code.match(/\\b(TODO|FIXME|HACK|XXX)\\b/g) || []).length;\n  const anyCount = (code.match(/:\\s*any\\b/g) || []).length;\n  const issueTotal = todoCount + anyCount;\n  const issueDensityScore = Math.max(0, 10 - issueTotal);\n\n  if (todoCount > 0) issues.push(`${todoCount} TODO/FIXME markers`);\n  if (anyCount > 3) {\n    issues.push(`${anyCount} uses of 'any' type`);\n    suggestions.push('Replace any with specific types');\n  }\n\n  // --- Weighted composite ---\n  const score = Number(\n    (\n      complexityScore * 0.4 +\n      coherenceScore * 0.2 +\n      docScore * 0.15 +\n      testScore * 0.15 +\n      issueDensityScore * 0.1\n    ).toFixed(1)\n  );\n\n  return {\n    score,\n    grade: toGrade(score),\n    breakdown: {\n      complexity: Number(complexityScore.toFixed(1)),\n      traitCoherence: Number(coherenceScore.toFixed(1)),\n      documentation: Number(docScore.toFixed(1)),\n      testPresence: Number(testScore.toFixed(1)),\n      issueDensity: Number(issueDensityScore.toFixed(1)),\n    },\n    issues,\n    suggestions,\n    filesAnalyzed: 1,\n  };\n}\n\n/**\n * Handle code health tool calls\n */\nexport async function handleCodeHealthTool(\n  name: string,\n  args: Record<string, unknown>\n): Promise<HealthResult | null> {\n  if (name !== 'holoscript_code_health') return null;\n\n  const code = args.code as string;\n  const filePath = (args.filePath as string) || 'input.holo';\n\n  if (!code || code.trim().length === 0) {\n    return {\n      score: 0,\n      grade: 'F',\n      breakdown: {\n        complexity: 0,\n        traitCoherence: 0,\n        documentation: 0,\n        testPresence: 0,\n        issueDensity: 0,\n      },\n      issues: ['Empty or missing code input'],\n      suggestions: ['Provide code to analyze'],\n      filesAnalyzed: 0,\n    };\n  }\n\n  if (isHoloScript(code, filePath)) {\n    return analyzeHoloScript(code, filePath);\n  }\n\n  return analyzeTypeScript(code, filePath);\n}\n","import type { Tool } from '@modelcontextprotocol/sdk/types.js';\n\n// Lazy import to avoid breaking tests when @holoscript/engine isn't resolvable\nlet _Simulation: typeof import('@holoscript/engine').Simulation | null = null;\nlet _solversInitialized = false;\nasync function getSimulation() {\n  if (!_Simulation) {\n    const mod = await import('@holoscript/engine');\n    _Simulation = mod.Simulation;\n    // Ensure SimulationSolverFactory is populated so trait handlers can\n    // instantiate solvers. Idempotent — no-ops if already registered\n    // (e.g., by SimulationProvider in React context). Guard against\n    // incomplete mocks in tests that don't provide initSimulationSolvers.\n    if (!_solversInitialized && typeof mod.Simulation.initSimulationSolvers === 'function') {\n      mod.Simulation.initSimulationSolvers();\n      _solversInitialized = true;\n    }\n  }\n  return _Simulation;\n}\n\nconst traceRegistry = new Map<string, string>();\nconst romRegistry = new Map<string, RomModel>();\n\ntype TraceEvent = 'init' | 'step' | 'interaction' | 'solve' | 'final';\ntype NumberTriple = [number, number, number];\ntype HashMode = 'fnv1a' | 'sha256';\ntype DigestField = Float32Array | Float64Array | { data?: Float32Array | Float64Array };\ntype DigestSolver = {\n  fieldNames: readonly string[];\n  getField(name: string): DigestField | null;\n};\ntype ComputeStateDigest = (solver: DigestSolver, hashMode: HashMode) => string;\ntype HashGeometry = (\n  vertices: Float64Array | Float32Array | undefined,\n  elements: Uint32Array | undefined,\n  mode?: HashMode\n) => string;\ntype SimulationModule = Awaited<ReturnType<typeof getSimulation>>;\ntype ThermalDigestSource = {\n  getTemperatureField(): Float32Array | Float64Array | number[];\n};\ntype RomCoefficient = {\n  intercept: number;\n  weights: Record<string, number>;\n};\ntype RomTrainingExample = {\n  traceJSONL: string;\n  traceHash: string;\n  inputs: Record<string, number>;\n  outputs: Record<string, number>;\n};\ntype RomValidationOutput = {\n  maxAbsError: number;\n  meanAbsError: number;\n  bound: number;\n  passed: boolean;\n};\ntype RomValidationSummary = {\n  samples: number;\n  maxAbsError: number;\n  meanAbsError: number;\n  passed: boolean;\n  outputs: Record<string, RomValidationOutput>;\n};\ntype RomCaelReceipt = {\n  schemaVersion: 'cael.rom.v1';\n  receiptId: string;\n  modelId: string;\n  modelHash: string;\n  solverType: string;\n  trainedAt: string;\n  sourceScale: 'empirical-surrogate';\n  trainingTraceHashes: string[];\n  validation: RomValidationSummary;\n};\ntype RomModel = {\n  schemaVersion: 'holoscript.rom.v1';\n  modelId: string;\n  solverType: string;\n  inputNames: string[];\n  outputNames: string[];\n  coefficients: Record<string, RomCoefficient>;\n  trainingTraceHashes: string[];\n  validation: RomValidationSummary;\n  errorBounds: Record<string, number>;\n  caelReceipt: RomCaelReceipt;\n};\n\nconst LEGACY_THERMAL_FACE_MAP: Record<string, string> = {\n  x0: 'x-',\n  x1: 'x+',\n  y0: 'y-',\n  y1: 'y+',\n  z0: 'z-',\n  z1: 'z+',\n};\n\ninterface TraceEntry {\n  version: 'cael.v1';\n  runId: string;\n  index: number;\n  event: TraceEvent;\n  timestamp: number;\n  simTime: number;\n  prevHash: string;\n  hash: string;\n  payload: Record<string, unknown>;\n}\n\nfunction fnv1a(input: string): string {\n  let h = 2166136261;\n  for (let i = 0; i < input.length; i++) {\n    h ^= input.charCodeAt(i);\n    h = Math.imul(h, 16777619);\n  }\n  return `cael-${(h >>> 0).toString(16).padStart(8, '0')}`;\n}\n\nfunction canonical(value: unknown): unknown {\n  if (value === null || value === undefined) return value;\n  if (typeof value !== 'object') return value;\n  if (ArrayBuffer.isView(value) && !(value instanceof DataView)) {\n    const arr = value as unknown as {\n      constructor: { name: string };\n      length: number;\n      [index: number]: number;\n    };\n    return {\n      __cael_typed_array: arr.constructor.name,\n      data: Array.from({ length: arr.length }, (_, i) => arr[i]),\n    };\n  }\n  if (Array.isArray(value)) return value.map((v) => canonical(v));\n  const obj = value as Record<string, unknown>;\n  const out: Record<string, unknown> = {};\n  for (const k of Object.keys(obj).sort()) out[k] = canonical(obj[k]);\n  return out;\n}\n\nfunction numericArrayFromCanonical(data: unknown, label: string): number[] {\n  if (!Array.isArray(data)) {\n    throw new Error(`CAEL typed array ${label} is missing array data`);\n  }\n  return data.map((entry, index) => {\n    const value = Number(entry);\n    if (!Number.isFinite(value)) {\n      throw new Error(`CAEL typed array ${label} has non-finite value at index ${index}`);\n    }\n    return value;\n  });\n}\n\nfunction rehydrateCanonical(value: unknown): unknown {\n  if (value === null || value === undefined) return value;\n  if (typeof value !== 'object') return value;\n  if (Array.isArray(value)) return value.map((entry) => rehydrateCanonical(entry));\n\n  const obj = value as Record<string, unknown>;\n  const typedArrayName = obj.__cael_typed_array;\n  if (typeof typedArrayName === 'string') {\n    const data = numericArrayFromCanonical(obj.data, typedArrayName);\n    if (typedArrayName === 'Float64Array') return new Float64Array(data);\n    if (typedArrayName === 'Float32Array') return new Float32Array(data);\n    if (typedArrayName === 'Uint32Array') return new Uint32Array(data);\n    throw new Error(`Unsupported CAEL typed array ${typedArrayName}`);\n  }\n\n  const out: Record<string, unknown> = {};\n  for (const key of Object.keys(obj)) {\n    out[key] = rehydrateCanonical(obj[key]);\n  }\n  return out;\n}\n\nfunction rehydrateTraceConfig(value: unknown): Record<string, unknown> {\n  const config = rehydrateCanonical(value);\n  const record = asRecord(config);\n  if (!record) throw new Error('CAEL trace config must be an object');\n  return record;\n}\n\nfunction hashEntry(entry: Omit<TraceEntry, 'hash'>): string {\n  return fnv1a(JSON.stringify(canonical(entry)));\n}\n\nfunction parseTrace(jsonl: string): TraceEntry[] {\n  return jsonl\n    .split(/\\r?\\n/)\n    .map((l) => l.trim())\n    .filter(Boolean)\n    .map((l) => JSON.parse(l) as TraceEntry);\n}\n\nfunction asRecord(value: unknown): Record<string, unknown> | null {\n  if (!value || typeof value !== 'object' || Array.isArray(value)) return null;\n  return value as Record<string, unknown>;\n}\n\nfunction asNumber(value: unknown, fallback: number): number {\n  return typeof value === 'number' && Number.isFinite(value) ? value : fallback;\n}\n\nfunction asString(value: unknown, fallback: string): string {\n  return typeof value === 'string' && value.length > 0 ? value : fallback;\n}\n\nfunction asTriple(value: unknown, fallback: NumberTriple): NumberTriple {\n  if (!Array.isArray(value) || value.length < 3) return fallback;\n  const tuple = value.slice(0, 3).map((v, i) => asNumber(v, fallback[i])) as NumberTriple;\n  return tuple;\n}\n\nfunction normalizeStructuralConfig(config: Record<string, unknown>): Record<string, unknown> {\n  // Pass-through: already engine-shaped (vertices/tetrahedra typed arrays + loads).\n  if (config.vertices !== undefined || config.tetrahedra !== undefined) return config;\n\n  // Map the advertised MCP schema {nodes, elements, materials, forces, constraints}\n  // → solver TET10Config {vertices, tetrahedra, material, loads, constraints}. The\n  // structural path previously bypassed normalization (only thermal was mapped), so a\n  // schema-correct config hit `config.vertices.length` on undefined and crashed.\n  const nodes = Array.isArray(config.nodes) ? config.nodes : [];\n  const elements = Array.isArray(config.elements) ? config.elements : [];\n\n  if (nodes.length === 0)\n    throw new Error(\n      'solve_structural: config.nodes must be a non-empty array of [x,y,z] coordinates'\n    );\n  if (elements.length === 0)\n    throw new Error(\n      'solve_structural: config.elements must be a non-empty array of 10-node TET10 index arrays'\n    );\n\n  const vertices = new Float64Array(nodes.length * 3);\n  nodes.forEach((node, i) => {\n    const [x, y, z] = asTriple(node, [0, 0, 0]);\n    vertices[i * 3] = x;\n    vertices[i * 3 + 1] = y;\n    vertices[i * 3 + 2] = z;\n  });\n\n  const tetrahedra = new Uint32Array(elements.length * 10);\n  elements.forEach((el, e) => {\n    if (!Array.isArray(el) || el.length !== 10) {\n      throw new Error(\n        `solve_structural: element ${e} must have exactly 10 node indices (TET10), got ${Array.isArray(el) ? el.length : typeof el}`\n      );\n    }\n    for (let a = 0; a < 10; a++) {\n      const idx = asNumber(el[a], -1);\n      if (!Number.isInteger(idx) || idx < 0 || idx >= nodes.length) {\n        throw new Error(\n          `solve_structural: element ${e} node ${a} index ${el[a]} out of range [0, ${nodes.length - 1}]`\n        );\n      }\n      tetrahedra[e * 10 + a] = idx;\n    }\n  });\n\n  const mat = asRecord(config.materials) ?? asRecord(config.material) ?? {};\n  const material = {\n    youngs_modulus: asNumber(mat.E ?? mat.youngs_modulus, 200e9),\n    poisson_ratio: asNumber(mat.nu ?? mat.poisson_ratio, 0.3),\n    yield_strength: asNumber(mat.yield_strength ?? mat.yieldStrength, 250e6),\n    density: asNumber(mat.density, 7850),\n  };\n\n  const rawConstraints = Array.isArray(config.constraints) ? config.constraints : [];\n  const constraints = rawConstraints.map((raw, i) => {\n    const c = asRecord(raw) ?? {};\n    const nodeIndex = asNumber(c.nodeIndex, -1);\n    if (nodeIndex < 0 || nodeIndex >= nodes.length) {\n      throw new Error(\n        `solve_structural: constraint ${i} nodeIndex ${c.nodeIndex} out of range [0, ${nodes.length - 1}]`\n      );\n    }\n    const dofs = [c.dx === true ? 0 : -1, c.dy === true ? 1 : -1, c.dz === true ? 2 : -1].filter(\n      (d): d is 0 | 1 | 2 => d >= 0\n    );\n    // No axis flagged → treat as fully fixed (matches \"fix this node\" intent).\n    const allFixed = dofs.length === 0 || dofs.length === 3;\n    return allFixed\n      ? { id: `c-${i}`, type: 'fixed' as const, nodes: [nodeIndex] }\n      : { id: `c-${i}`, type: 'roller' as const, nodes: [nodeIndex], dofs };\n  });\n\n  const rawForces = Array.isArray(config.forces) ? config.forces : [];\n  const loads = rawForces.map((raw, i) => {\n    const f = asRecord(raw) ?? {};\n    const nodeIndex = asNumber(f.nodeIndex, -1);\n    if (nodeIndex < 0 || nodeIndex >= nodes.length) {\n      throw new Error(\n        `solve_structural: force ${i} nodeIndex ${f.nodeIndex} out of range [0, ${nodes.length - 1}]`\n      );\n    }\n    return {\n      id: `f-${i}`,\n      type: 'point' as const,\n      nodeIndex,\n      force: [asNumber(f.fx, 0), asNumber(f.fy, 0), asNumber(f.fz, 0)] as [number, number, number],\n    };\n  });\n\n  return {\n    vertices,\n    tetrahedra,\n    material,\n    constraints,\n    loads,\n    useGPU: config.useGPU === true, // default CPU on server (no WebGPU) — avoids GPU init churn\n    ...(typeof config.maxIterations === 'number' ? { maxIterations: config.maxIterations } : {}),\n    ...(typeof config.tolerance === 'number' ? { tolerance: config.tolerance } : {}),\n    ...(config.nonlinear === true ? { nonlinear: true } : {}),\n  };\n}\n\nfunction normalizeThermalSource(value: unknown, index: number): Record<string, unknown> | null {\n  const source = asRecord(value);\n  if (!source) return null;\n  const position = asTriple(source.position, [0, 0, 0]);\n  return {\n    ...source,\n    id: asString(source.id, `source-${index}`),\n    type: asString(source.type, 'point'),\n    position,\n    heat_output: asNumber(source.heat_output ?? source.power, 0),\n    active: source.active !== false,\n  };\n}\n\nfunction normalizeThermalBoundary(value: unknown): Record<string, unknown> | null {\n  const bc = asRecord(value);\n  if (!bc) return null;\n  const faces = Array.isArray(bc.faces)\n    ? bc.faces\n    : [LEGACY_THERMAL_FACE_MAP[String(bc.face)] ?? bc.face].filter(\n        (face): face is string => typeof face === 'string'\n      );\n  return {\n    ...bc,\n    faces,\n  };\n}\n\nfunction normalizeThermalConfig(config: Record<string, unknown>): Record<string, unknown> {\n  const gridResolution = asTriple(config.gridResolution ?? config.gridSize, [3, 3, 3]).map((n) =>\n    Math.max(2, Math.trunc(n))\n  ) as NumberTriple;\n  const spacing = asNumber(config.spacing, 1);\n  const fallbackDomainSize = gridResolution.map((n) =>\n    Math.max(spacing, (n - 1) * spacing)\n  ) as NumberTriple;\n  const domainSize = asTriple(config.domainSize, fallbackDomainSize);\n  const defaultMaterial = asString(config.defaultMaterial, 'water');\n  const materialOverride = asRecord(config.material);\n  const materials = { ...(asRecord(config.materials) ?? {}) };\n\n  if (materialOverride) {\n    materials[defaultMaterial] = {\n      ...(asRecord(materials[defaultMaterial]) ?? {}),\n      ...materialOverride,\n    };\n  }\n\n  const rawSources = Array.isArray(config.sources) ? config.sources : [];\n  const sources = rawSources\n    .map((source, index) => normalizeThermalSource(source, index))\n    .filter((source): source is Record<string, unknown> => source !== null);\n\n  const rawBoundaryConditions = Array.isArray(config.boundaryConditions)\n    ? config.boundaryConditions\n    : [];\n  const boundaryConditions = rawBoundaryConditions\n    .map((bc) => normalizeThermalBoundary(bc))\n    .filter((bc): bc is Record<string, unknown> => bc !== null);\n\n  return {\n    ...config,\n    gridResolution,\n    domainSize,\n    timeStep: asNumber(config.timeStep, 0.01),\n    materials,\n    defaultMaterial,\n    boundaryConditions,\n    sources,\n    initialTemperature: asNumber(config.initialTemperature, 20),\n  };\n}\n\nfunction verifyHashChain(trace: TraceEntry[]): {\n  valid: boolean;\n  brokenAt?: number;\n  reason?: string;\n} {\n  let prev = 'cael.genesis';\n  for (let i = 0; i < trace.length; i++) {\n    const e = trace[i];\n    if (e.prevHash !== prev) return { valid: false, brokenAt: i, reason: 'prevHash mismatch' };\n    const expected = hashEntry({\n      version: e.version,\n      runId: e.runId,\n      index: e.index,\n      event: e.event,\n      timestamp: e.timestamp,\n      simTime: e.simTime,\n      prevHash: e.prevHash,\n      payload: e.payload,\n    });\n    if (expected !== e.hash) return { valid: false, brokenAt: i, reason: 'hash mismatch' };\n    prev = e.hash;\n  }\n  return { valid: true };\n}\n\nfunction getComputeStateDigest(Sim: SimulationModule): ComputeStateDigest | null {\n  const candidate = (Sim as unknown as { computeStateDigest?: unknown }).computeStateDigest;\n  return typeof candidate === 'function' ? (candidate as ComputeStateDigest) : null;\n}\n\nfunction getHashGeometry(Sim: SimulationModule): HashGeometry | null {\n  const candidate = (Sim as unknown as { hashGeometry?: unknown }).hashGeometry;\n  return typeof candidate === 'function' ? (candidate as HashGeometry) : null;\n}\n\n/**\n * Compute a geometry hash for a structural mesh.\n *\n * Delegates to Simulation.hashGeometry (hashes.ts) which uses FNV-1a over\n * canonicalized vertex coordinates and connectivity indices.  Falls back to a\n * local FNV-1a digest of the buffer lengths when the engine export is absent\n * (e.g., in test environments that do not expose hashGeometry).\n */\nfunction computeStructuralGeometryHash(\n  Sim: SimulationModule,\n  solverConfig: Record<string, unknown>,\n  hashMode: HashMode\n): string {\n  const hashGeometryFn = getHashGeometry(Sim);\n  const vertices =\n    solverConfig.vertices instanceof Float64Array || solverConfig.vertices instanceof Float32Array\n      ? (solverConfig.vertices as Float64Array | Float32Array)\n      : undefined;\n  const tetrahedra =\n    solverConfig.tetrahedra instanceof Uint32Array\n      ? (solverConfig.tetrahedra as Uint32Array)\n      : undefined;\n\n  if (hashGeometryFn && vertices && tetrahedra) {\n    return hashGeometryFn(vertices, tetrahedra, hashMode);\n  }\n\n  // Fallback: hash the count of vertices and indices as a minimal fingerprint.\n  const vLen = vertices ? vertices.length : 0;\n  const tLen = tetrahedra ? tetrahedra.length : 0;\n  return fnv1a(`geo-fallback:v${vLen}:t${tLen}`);\n}\n\n/**\n * Compute a geometry hash for a thermal grid configuration.\n *\n * The thermal solver has no explicit vertex/element mesh — only a\n * structured grid.  We hash the gridResolution and domainSize arrays as\n * a stable content fingerprint so the init trace entry reflects the\n * actual spatial discretization instead of the 'geo-unavailable' placeholder.\n */\nfunction computeThermalGeometryHash(solverConfig: Record<string, unknown>): string {\n  const gridRes = Array.isArray(solverConfig.gridResolution)\n    ? (solverConfig.gridResolution as number[])\n    : [];\n  const domainSize = Array.isArray(solverConfig.domainSize)\n    ? (solverConfig.domainSize as number[])\n    : [];\n  const key = `thermal-grid:${gridRes.join('x')}:domain:${domainSize.map((d) => d.toFixed(6)).join('x')}`;\n  return `geo-${fnv1a(key).replace('cael-', '')}`;\n}\n\n/**\n * Compute a state digest for the structural solver after solve().\n *\n * StructuralSolverTET10 does not expose fieldNames/getField, so we build\n * a synthetic field adapter from the displacement and vonMisesStress arrays\n * and delegate to computeStateDigest.  The field names ('displacement',\n * 'vonMisesStress') match the FIELD_QUANTUM_REGISTRY patterns in hashes.ts\n * so the quantum discretization is physically appropriate.\n */\nfunction computeStructuralStateDigest(\n  Sim: SimulationModule,\n  displacements: number[] | Float32Array | Float64Array,\n  vonMisesStress: number[] | Float32Array | Float64Array,\n  hashMode: HashMode\n): string | null {\n  const computeSD = getComputeStateDigest(Sim);\n  if (!computeSD) return null;\n\n  const dispField = toFloatField(\n    displacements instanceof Float32Array || displacements instanceof Float64Array\n      ? displacements\n      : new Float32Array(displacements)\n  );\n  const vmField = toFloatField(\n    vonMisesStress instanceof Float32Array || vonMisesStress instanceof Float64Array\n      ? vonMisesStress\n      : new Float32Array(vonMisesStress)\n  );\n\n  return computeSD(\n    {\n      fieldNames: ['displacement', 'vonMisesStress'],\n      getField(name: string): DigestField | null {\n        if (name === 'displacement') return dispField;\n        if (name === 'vonMisesStress') return vmField;\n        return null;\n      },\n    },\n    hashMode\n  );\n}\n\nfunction toFloatField(value: Float32Array | Float64Array | number[]): Float32Array | Float64Array {\n  if (value instanceof Float32Array || value instanceof Float64Array) return value;\n  return new Float32Array(value);\n}\n\nfunction computeThermalStateDigest(\n  Sim: SimulationModule,\n  solver: ThermalDigestSource,\n  hashMode: HashMode\n): string | null {\n  const computeStateDigest = getComputeStateDigest(Sim);\n  if (!computeStateDigest) return null;\n\n  return computeStateDigest(\n    {\n      fieldNames: ['temperature'],\n      getField(name: string): DigestField | null {\n        return name === 'temperature' ? toFloatField(solver.getTemperatureField()) : null;\n      },\n    },\n    hashMode\n  );\n}\n\nfunction verifyStateDigests(entry: TraceEntry, actualDigests: readonly string[]): void {\n  const expected = entry.payload.stateDigests;\n  if (!Array.isArray(expected) || expected.length === 0) {\n    throw new Error(\n      `missing state digests at ${entry.event} event (index ${entry.index}); replay cannot establish state agreement`\n    );\n  }\n  if (actualDigests.length === 0) {\n    throw new Error(\n      `replay produced no state digest at ${entry.event} event (index ${entry.index})`\n    );\n  }\n\n  if (expected.length !== actualDigests.length) {\n    throw new Error(\n      `state-digest count mismatch at ${entry.event} event (index ${entry.index}): ` +\n        `expected ${expected.length}, got ${actualDigests.length}`\n    );\n  }\n\n  for (let i = 0; i < actualDigests.length; i++) {\n    const expectedDigest = expected[i];\n    if (typeof expectedDigest !== 'string') {\n      throw new Error(\n        `malformed state digest at ${entry.event} event (index ${entry.index}, digest ${i})`\n      );\n    }\n    if (expectedDigest !== actualDigests[i]) {\n      throw new Error(\n        `state-digest mismatch at ${entry.event} event (index ${entry.index}, digest ${i}): ` +\n          `expected ${expectedDigest}, got ${actualDigests[i]}`\n      );\n    }\n  }\n}\n\nfunction stringArray(value: unknown): string[] {\n  if (!Array.isArray(value)) return [];\n  return value.filter((entry): entry is string => typeof entry === 'string' && entry.length > 0);\n}\n\nfunction finiteRecord(value: unknown, label: string): Record<string, number> {\n  const record = asRecord(value);\n  if (!record) throw new Error(`${label} must be an object of numeric fields`);\n\n  const out: Record<string, number> = {};\n  for (const [key, raw] of Object.entries(record)) {\n    const numeric = Number(raw);\n    if (!Number.isFinite(numeric)) {\n      throw new Error(`${label}.${key} must be a finite number`);\n    }\n    out[key] = numeric;\n  }\n  return out;\n}\n\nfunction numericValue(record: Record<string, number>, key: string, label: string): number {\n  const value = record[key];\n  if (!Number.isFinite(value)) throw new Error(`${label}.${key} is missing or non-finite`);\n  return value;\n}\n\nfunction resolveTraceJSONL(raw: Record<string, unknown>): string {\n  if (typeof raw.traceJSONL === 'string' && raw.traceJSONL.trim().length > 0) return raw.traceJSONL;\n  if (typeof raw.traceId === 'string') {\n    const trace = traceRegistry.get(raw.traceId);\n    if (trace) return trace;\n  }\n  throw new Error('ROM training example requires traceJSONL or known traceId');\n}\n\nfunction normalizeRomTrainingExamples(args: Record<string, unknown>): RomTrainingExample[] {\n  const rawExamples = Array.isArray(args.trainingExamples)\n    ? args.trainingExamples\n    : Array.isArray(args.examples)\n      ? args.examples\n      : [];\n  if (rawExamples.length < 2) {\n    throw new Error('train_rom requires at least two trace-backed training examples');\n  }\n\n  return rawExamples.map((raw, index) => {\n    const record = asRecord(raw);\n    if (!record) throw new Error(`ROM training example ${index} must be an object`);\n    const traceJSONL = resolveTraceJSONL(record);\n    const trace = parseTrace(traceJSONL);\n    const hashChain = verifyHashChain(trace);\n    if (!hashChain.valid) {\n      throw new Error(\n        `ROM training example ${index} has invalid CAEL hash chain at ${hashChain.brokenAt}: ${hashChain.reason}`\n      );\n    }\n    const final = trace[trace.length - 1];\n    if (!final?.hash) throw new Error(`ROM training example ${index} has no final CAEL hash`);\n\n    return {\n      traceJSONL,\n      traceHash: final.hash,\n      inputs: finiteRecord(record.inputs, `trainingExamples[${index}].inputs`),\n      outputs: finiteRecord(record.outputs, `trainingExamples[${index}].outputs`),\n    };\n  });\n}\n\nfunction inferNames(\n  explicit: unknown,\n  records: readonly Record<string, number>[],\n  label: string\n): string[] {\n  const names = stringArray(explicit);\n  if (names.length > 0) return names;\n\n  const inferred = Object.keys(records[0] ?? {}).sort();\n  if (inferred.length === 0) throw new Error(`Unable to infer ${label}; provide ${label}`);\n  return inferred;\n}\n\nfunction fitAffineCoefficients(\n  examples: readonly RomTrainingExample[],\n  inputNames: readonly string[],\n  outputName: string,\n  ridge: number\n): RomCoefficient {\n  const dimension = inputNames.length + 1;\n  const normalMatrix = Array.from({ length: dimension }, () => Array(dimension).fill(0));\n  const normalVector = Array(dimension).fill(0);\n\n  for (const example of examples) {\n    const row = [1, ...inputNames.map((name) => numericValue(example.inputs, name, 'inputs'))];\n    const y = numericValue(example.outputs, outputName, 'outputs');\n    for (let i = 0; i < dimension; i++) {\n      normalVector[i] += row[i] * y;\n      for (let j = 0; j < dimension; j++) {\n        normalMatrix[i][j] += row[i] * row[j];\n      }\n    }\n  }\n\n  for (let i = 0; i < dimension; i++) {\n    normalMatrix[i][i] += ridge;\n  }\n\n  const solved = solveLinearSystem(normalMatrix, normalVector);\n  const weights: Record<string, number> = {};\n  inputNames.forEach((name, index) => {\n    weights[name] = solved[index + 1] ?? 0;\n  });\n  return { intercept: solved[0] ?? 0, weights };\n}\n\nfunction solveLinearSystem(matrix: number[][], vector: number[]): number[] {\n  const n = vector.length;\n  const augmented = matrix.map((row, i) => [...row, vector[i]]);\n\n  for (let col = 0; col < n; col++) {\n    let pivot = col;\n    for (let row = col + 1; row < n; row++) {\n      if (Math.abs(augmented[row][col]) > Math.abs(augmented[pivot][col])) pivot = row;\n    }\n    if (Math.abs(augmented[pivot][col]) < 1e-12) {\n      augmented[pivot][col] = 1e-12;\n    }\n    if (pivot !== col) {\n      const tmp = augmented[col];\n      augmented[col] = augmented[pivot];\n      augmented[pivot] = tmp;\n    }\n\n    const divisor = augmented[col][col];\n    for (let j = col; j <= n; j++) augmented[col][j] /= divisor;\n\n    for (let row = 0; row < n; row++) {\n      if (row === col) continue;\n      const factor = augmented[row][col];\n      for (let j = col; j <= n; j++) augmented[row][j] -= factor * augmented[col][j];\n    }\n  }\n\n  return augmented.map((row) => row[n]);\n}\n\nfunction stepRomModel(model: RomModel, inputs: Record<string, number>): Record<string, number> {\n  const outputs: Record<string, number> = {};\n  for (const outputName of model.outputNames) {\n    const coefficient = model.coefficients[outputName];\n    let value = coefficient.intercept;\n    for (const inputName of model.inputNames) {\n      value += (coefficient.weights[inputName] ?? 0) * numericValue(inputs, inputName, 'inputs');\n    }\n    outputs[outputName] = value;\n  }\n  return outputs;\n}\n\nfunction errorBoundsFromArgs(\n  args: Record<string, unknown>,\n  outputNames: readonly string[],\n  measured: Record<string, number>\n): Record<string, number> {\n  const raw = asRecord(args.errorBounds ?? args.validationErrorBounds);\n  const uniform = Number(args.maxError ?? args.errorTolerance);\n  const out: Record<string, number> = {};\n\n  for (const outputName of outputNames) {\n    const fromRecord = raw ? Number(raw[outputName]) : Number.NaN;\n    out[outputName] = Number.isFinite(fromRecord)\n      ? fromRecord\n      : Number.isFinite(uniform)\n        ? uniform\n        : measured[outputName];\n  }\n  return out;\n}\n\nfunction validateRomModel(\n  model: Omit<RomModel, 'validation' | 'errorBounds' | 'caelReceipt'>,\n  examples: readonly RomTrainingExample[],\n  args: Record<string, unknown>\n): { validation: RomValidationSummary; errorBounds: Record<string, number> } {\n  const perOutputErrors: Record<string, number[]> = Object.fromEntries(\n    model.outputNames.map((name) => [name, []])\n  );\n\n  for (const example of examples) {\n    const prediction = stepRomModel(\n      {\n        ...model,\n        validation: {\n          samples: 0,\n          maxAbsError: 0,\n          meanAbsError: 0,\n          passed: true,\n          outputs: {},\n        },\n        errorBounds: {},\n        caelReceipt: {\n          schemaVersion: 'cael.rom.v1',\n          receiptId: '',\n          modelId: model.modelId,\n          modelHash: '',\n          solverType: model.solverType,\n          trainedAt: '',\n          sourceScale: 'empirical-surrogate',\n          trainingTraceHashes: model.trainingTraceHashes,\n          validation: {\n            samples: 0,\n            maxAbsError: 0,\n            meanAbsError: 0,\n            passed: true,\n            outputs: {},\n          },\n        },\n      },\n      example.inputs\n    );\n    for (const outputName of model.outputNames) {\n      const actual = numericValue(example.outputs, outputName, 'outputs');\n      perOutputErrors[outputName]?.push(Math.abs((prediction[outputName] ?? 0) - actual));\n    }\n  }\n\n  const measuredMax = Object.fromEntries(\n    Object.entries(perOutputErrors).map(([name, values]) => [name, Math.max(...values)])\n  );\n  const errorBounds = errorBoundsFromArgs(args, model.outputNames, measuredMax);\n  const outputs: Record<string, RomValidationOutput> = {};\n\n  for (const [name, values] of Object.entries(perOutputErrors)) {\n    const maxAbsError = Math.max(...values);\n    const meanAbsError = values.reduce((sum, value) => sum + value, 0) / values.length;\n    const bound = errorBounds[name] ?? maxAbsError;\n    outputs[name] = {\n      maxAbsError,\n      meanAbsError,\n      bound,\n      passed: maxAbsError <= bound,\n    };\n  }\n\n  const allErrors = Object.values(perOutputErrors).flat();\n  return {\n    errorBounds,\n    validation: {\n      samples: examples.length,\n      maxAbsError: Math.max(...allErrors),\n      meanAbsError: allErrors.reduce((sum, value) => sum + value, 0) / allErrors.length,\n      passed: Object.values(outputs).every((output) => output.passed),\n      outputs,\n    },\n  };\n}\n\nfunction trainRom(args: Record<string, unknown>): Record<string, unknown> {\n  try {\n    const examples = normalizeRomTrainingExamples(args);\n    const inputNames = inferNames(\n      args.inputNames,\n      examples.map((example) => example.inputs),\n      'inputNames'\n    );\n    const outputNames = inferNames(\n      args.outputNames,\n      examples.map((example) => example.outputs),\n      'outputNames'\n    );\n    const ridge = Math.max(0, asNumber(args.ridge, 1e-8));\n    const solverType = asString(args.solverType, 'simulation_contract');\n    const modelId = asString(\n      args.modelId,\n      `rom-${fnv1a(JSON.stringify(canonical({ inputNames, outputNames, solverType }))).replace('cael-', '')}`\n    );\n    const trainingTraceHashes = examples.map((example) => example.traceHash);\n    const coefficients = Object.fromEntries(\n      outputNames.map((outputName) => [\n        outputName,\n        fitAffineCoefficients(examples, inputNames, outputName, ridge),\n      ])\n    );\n\n    const baseModel = {\n      schemaVersion: 'holoscript.rom.v1' as const,\n      modelId,\n      solverType,\n      inputNames,\n      outputNames,\n      coefficients,\n      trainingTraceHashes,\n    };\n    const { validation, errorBounds } = validateRomModel(baseModel, examples, args);\n    const modelHash = fnv1a(JSON.stringify(canonical({ ...baseModel, validation, errorBounds })));\n    const caelReceipt: RomCaelReceipt = {\n      schemaVersion: 'cael.rom.v1',\n      receiptId: `rom-receipt-${modelHash.replace('cael-', '')}`,\n      modelId,\n      modelHash,\n      solverType,\n      trainedAt: new Date().toISOString(),\n      sourceScale: 'empirical-surrogate',\n      trainingTraceHashes,\n      validation,\n    };\n    const model: RomModel = {\n      ...baseModel,\n      validation,\n      errorBounds,\n      caelReceipt,\n    };\n\n    romRegistry.set(modelId, model);\n\n    return {\n      success: true,\n      model,\n      modelId,\n      modelHash,\n      validation,\n      errorBounds,\n      caelReceipt,\n      trainingTraceHashes,\n    };\n  } catch (error) {\n    return {\n      success: false,\n      error: error instanceof Error ? error.message : String(error),\n    };\n  }\n}\n\nfunction resolveRomModel(args: Record<string, unknown>): RomModel {\n  const inlineModel = asRecord(args.model);\n  if (inlineModel) return inlineModel as unknown as RomModel;\n\n  const modelId = typeof args.modelId === 'string' ? args.modelId : '';\n  const model = modelId ? romRegistry.get(modelId) : null;\n  if (!model) throw new Error('compile_to_rom_twin requires model or known modelId');\n  return model;\n}\n\nfunction emitRomTwinSource(model: RomModel): string {\n  const payload = JSON.stringify(\n    {\n      modelId: model.modelId,\n      inputNames: model.inputNames,\n      outputNames: model.outputNames,\n      coefficients: model.coefficients,\n      errorBounds: model.errorBounds,\n      caelReceipt: model.caelReceipt,\n    },\n    null,\n    2\n  );\n  return [\n    `const ROM_MODEL = ${payload};`,\n    'export function step(inputs) {',\n    '  const outputs = {};',\n    '  for (const outputName of ROM_MODEL.outputNames) {',\n    '    const coefficient = ROM_MODEL.coefficients[outputName];',\n    '    let value = coefficient.intercept;',\n    '    for (const inputName of ROM_MODEL.inputNames) {',\n    '      const numeric = Number(inputs[inputName]);',\n    '      if (!Number.isFinite(numeric)) throw new Error(`inputs.${inputName} must be finite`);',\n    '      value += (coefficient.weights[inputName] || 0) * numeric;',\n    '    }',\n    '    outputs[outputName] = value;',\n    '  }',\n    '  return outputs;',\n    '}',\n    'export const romModel = ROM_MODEL;',\n    'export const romCaelReceipt = ROM_MODEL.caelReceipt;',\n    '',\n  ].join('\\n');\n}\n\nfunction compileRomTwin(args: Record<string, unknown>): Record<string, unknown> {\n  try {\n    const model = resolveRomModel(args);\n    const target = asString(args.target, 'wasm-edge');\n    const sampleInput = asRecord(args.sampleInput)\n      ? finiteRecord(args.sampleInput, 'sampleInput')\n      : null;\n    const artifact = {\n      schemaVersion: 'holoscript.rom-twin.artifact.v1',\n      target,\n      moduleFormat: 'esm',\n      stepInterface: 'step(inputs) -> outputs',\n      edgeReady: target === 'edge' || target === 'wasm-edge' || target === 'browser',\n      wasmReady: target === 'wasm-edge',\n      modelId: model.modelId,\n      modelHash: model.caelReceipt.modelHash,\n      inputNames: model.inputNames,\n      outputNames: model.outputNames,\n      errorBounds: model.errorBounds,\n      caelReceiptHash: model.caelReceipt.receiptId,\n      source: emitRomTwinSource(model),\n    };\n\n    return {\n      success: true,\n      artifact,\n      model,\n      stepPreview: sampleInput ? stepRomModel(model, sampleInput) : null,\n    };\n  } catch (error) {\n    return {\n      success: false,\n      error: error instanceof Error ? error.message : String(error),\n    };\n  }\n}\n\nclass LocalTraceRecorder {\n  private readonly runId = `cael-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;\n  private readonly entries: TraceEntry[] = [];\n  private prevHash = 'cael.genesis';\n  private simTime = 0;\n  private steps = 0;\n  private readonly hashMode: HashMode = 'fnv1a';\n\n  constructor(\n    private solverType: string,\n    config: Record<string, unknown>,\n    geometryHash: string\n  ) {\n    this.append('init', {\n      solverType,\n      config: canonical(config),\n      contractConfig: {},\n      geometryHash,\n      hashMode: this.hashMode,\n    });\n  }\n\n  step(dt: number, stateDigests: readonly string[] = []): void {\n    this.simTime += dt;\n    this.steps += 1;\n    this.append('step', { wallDelta: dt, stepsTaken: 1, totalSteps: this.steps, stateDigests });\n  }\n\n  solve(stateDigests: readonly string[] = []): void {\n    this.append('solve', { totalSteps: this.steps, stateDigests });\n  }\n\n  finalize(extra: Record<string, unknown> = {}): void {\n    this.append('final', {\n      provenance: {\n        solverType: this.solverType,\n        totalSteps: this.steps,\n        totalSimTime: this.simTime,\n      },\n      ...extra,\n    });\n  }\n\n  toJSONL(): string {\n    return this.entries.map((e) => JSON.stringify(e)).join('\\n');\n  }\n\n  private append(event: TraceEvent, payload: Record<string, unknown>): void {\n    const base: Omit<TraceEntry, 'hash'> = {\n      version: 'cael.v1',\n      runId: this.runId,\n      index: this.entries.length,\n      event,\n      timestamp: Date.now(),\n      simTime: this.simTime,\n      prevHash: this.prevHash,\n      payload,\n    };\n    const hash = hashEntry(base);\n    const entry: TraceEntry = { ...base, hash };\n    this.entries.push(entry);\n    this.prevHash = hash;\n  }\n}\n\nexport const simulationTools: Tool[] = [\n  {\n    name: 'solve_structural',\n    description:\n      'Run a TET10 structural FEA simulation. Returns displacement/stress results + a CAEL trace for local chain checking and fresh-solver replay. Input: nodes, elements, materials, forces, constraints.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        config: {\n          type: 'object',\n          description: 'Structural solver configuration.',\n          properties: {\n            nodes: {\n              type: 'array',\n              description: 'Array of [x, y, z] node coordinates.',\n              items: { type: 'array', items: { type: 'number' } },\n            },\n            elements: {\n              type: 'array',\n              description: 'Array of node-index arrays (10 indices per TET10 element).',\n              items: { type: 'array', items: { type: 'number' } },\n            },\n            materials: {\n              type: 'object',\n              description: 'Material properties.',\n              properties: {\n                E: { type: 'number', description: \"Young's modulus (Pa)\" },\n                nu: { type: 'number', description: \"Poisson's ratio (0-0.5)\" },\n              },\n            },\n            forces: {\n              type: 'array',\n              description: 'Array of { nodeIndex, fx, fy, fz } force vectors (N).',\n            },\n            constraints: {\n              type: 'array',\n              description: 'Array of { nodeIndex, dx, dy, dz } fixed DOFs (true = fixed).',\n            },\n          },\n        },\n      },\n      required: ['config'],\n    },\n  },\n  {\n    name: 'solve_thermal',\n    description:\n      'Run a thermal conduction simulation on a structured grid. Returns temperature field + a CAEL trace for local chain checking and fresh-solver replay. Input: grid, material, sources, BCs.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        config: {\n          type: 'object',\n          description: 'Thermal solver configuration.',\n          properties: {\n            gridSize: {\n              type: 'array',\n              description: 'Legacy alias for gridResolution: grid dimensions [nx, ny, nz].',\n              items: { type: 'number' },\n            },\n            gridResolution: {\n              type: 'array',\n              description: 'Grid dimensions [nx, ny, nz].',\n              items: { type: 'number' },\n            },\n            spacing: {\n              type: 'number',\n              description: 'Legacy shortcut for domainSize: grid spacing in meters.',\n            },\n            domainSize: {\n              type: 'array',\n              description: 'Physical domain size [lx, ly, lz] in meters.',\n              items: { type: 'number' },\n            },\n            timeStep: {\n              type: 'number',\n              description: 'Solver time step in seconds.',\n            },\n            material: {\n              type: 'object',\n              description: 'Legacy shortcut for materials[defaultMaterial].',\n              properties: {\n                conductivity: { type: 'number', description: 'Thermal conductivity (W/m·K)' },\n              },\n            },\n            materials: {\n              type: 'object',\n              description: 'Material name to thermal property overrides.',\n            },\n            defaultMaterial: {\n              type: 'string',\n              description: 'Default material name, e.g. water, air, concrete.',\n            },\n            sources: {\n              type: 'array',\n              description:\n                'Heat sources: array of { id?, type?, position: [x,y,z], heat_output | power, radius?, active? }.',\n            },\n            boundaryConditions: {\n              type: 'array',\n              description:\n                'BCs: engine shape { faces: [\"x-\"|\"x+\"|\"y-\"|\"y+\"|\"z-\"|\"z+\"], type, value } or legacy { face: \"x0\"|\"x1\"|\"y0\"|\"y1\"|\"z0\"|\"z1\", type, value }.',\n            },\n            initialTemperature: {\n              type: 'number',\n              description: 'Initial temperature for the domain.',\n            },\n          },\n        },\n      },\n      required: ['config'],\n    },\n  },\n  {\n    name: 'train_rom',\n    description:\n      'Train a reduced-order surrogate model from prior CAEL-backed SimulationContract traces. Returns a deployable ROM model, validation error bounds, and a CAEL ROM receipt.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        trainingExamples: {\n          type: 'array',\n          description:\n            'Trace-backed examples: [{ traceJSONL | traceId, inputs: {name:number}, outputs: {name:number} }].',\n        },\n        inputNames: {\n          type: 'array',\n          description:\n            'Optional ordered input feature names. Inferred from the first example if omitted.',\n          items: { type: 'string' },\n        },\n        outputNames: {\n          type: 'array',\n          description: 'Optional ordered output names. Inferred from the first example if omitted.',\n          items: { type: 'string' },\n        },\n        solverType: {\n          type: 'string',\n          description:\n            'Source solver family for provenance, e.g. solve_thermal, solve_structural, or simulation_contract.',\n        },\n        modelId: {\n          type: 'string',\n          description: 'Optional stable model id. A deterministic id is generated when omitted.',\n        },\n        errorBounds: {\n          type: 'object',\n          description:\n            'Optional per-output max absolute validation error bounds. Defaults to measured validation error.',\n        },\n        maxError: {\n          type: 'number',\n          description: 'Optional uniform max absolute validation error bound.',\n        },\n        ridge: {\n          type: 'number',\n          description: 'Optional ridge regularization strength for the affine surrogate.',\n        },\n      },\n      required: ['trainingExamples'],\n    },\n  },\n  {\n    name: 'compile_to_rom_twin',\n    description:\n      'Compile a trained ROM model to an edge/browser twin artifact with a step(inputs) -> outputs interface and CAEL provenance receipt.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        modelId: {\n          type: 'string',\n          description: 'Model id returned by train_rom.',\n        },\n        model: {\n          type: 'object',\n          description: 'Inline ROM model returned by train_rom.',\n        },\n        target: {\n          type: 'string',\n          description: 'Deployment target: wasm-edge, edge, browser, or node.',\n        },\n        sampleInput: {\n          type: 'object',\n          description: 'Optional numeric input object used to return a stepPreview.',\n        },\n      },\n    },\n  },\n  {\n    name: 'verify_cael_trace',\n    description:\n      'Check CAEL hash-chain internal consistency and attempt fresh replay. This does not authenticate the trace origin or bind it to a caller-retained request/result. Pass traceId (from solve_* result) or raw JSONL.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        traceId: {\n          type: 'string',\n          description: 'Trace identifier returned by solve_structural or solve_thermal.',\n        },\n        traceJSONL: {\n          type: 'string',\n          description:\n            'Raw CAEL trace as newline-delimited JSON. Used directly if provided (traceId ignored).',\n        },\n      },\n    },\n  },\n  {\n    name: 'solve_logic',\n    description:\n      'Execute a HoloScript .hs LOGIC function in a restricted same-process context and return its result plus a CAEL trace. Input: the .hs source, function name, and positional args. Verification re-runs the recorded logic and compares its result; it is not hard isolation or origin authentication.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        code: {\n          type: 'string',\n          description:\n            'HoloScript .hs logic source — one or more top-level `function` declarations.',\n        },\n        functionName: {\n          type: 'string',\n          description: 'The function to invoke from the source.',\n        },\n        args: {\n          type: 'array',\n          description: 'Positional arguments spread into the call, e.g. [48, 36].',\n        },\n        timeout: {\n          type: 'number',\n          description: 'Optional execution timeout in milliseconds (default 5000).',\n        },\n      },\n      required: ['code', 'functionName'],\n    },\n  },\n];\n\nexport async function handleSimulationTool(\n  name: string,\n  args: Record<string, unknown>\n): Promise<unknown | null> {\n  if (name === 'verify_cael_trace') {\n    return verifyTrace(args);\n  }\n\n  if (name === 'solve_logic') {\n    return solveLogic(args);\n  }\n\n  if (name === 'train_rom') {\n    return trainRom(args);\n  }\n\n  if (name === 'compile_to_rom_twin') {\n    return compileRomTwin(args);\n  }\n\n  if (name !== 'solve_structural' && name !== 'solve_thermal') {\n    return null;\n  }\n\n  const { config } = args as { config: Record<string, unknown> };\n  if (!config) throw new Error('config is required for simulation tools');\n  const solverConfig =\n    name === 'solve_thermal' ? normalizeThermalConfig(config) : normalizeStructuralConfig(config);\n\n  try {\n    let recorder: LocalTraceRecorder;\n    let result: Record<string, unknown> = {};\n\n    const Sim = await getSimulation();\n\n    if (name === 'solve_structural') {\n      const solver = new Sim.StructuralSolverTET10(\n        solverConfig as unknown as ConstructorParameters<typeof Sim.StructuralSolverTET10>[0]\n      );\n      const structGeoHash = computeStructuralGeometryHash(Sim, solverConfig, 'fnv1a');\n      recorder = new LocalTraceRecorder(name, solverConfig, structGeoHash);\n\n      await Promise.resolve(solver.solve());\n      const displacements = solver.getDisplacements();\n      const vonMisesStress = solver.getVonMisesStress();\n      const structStateDigest = computeStructuralStateDigest(\n        Sim,\n        displacements,\n        vonMisesStress,\n        'fnv1a'\n      );\n      recorder.solve(structStateDigest ? [structStateDigest] : []);\n      result = {\n        displacements,\n        vonMisesStress,\n        safetyFactor: solver.getSafetyFactor(),\n      };\n    } else {\n      const solver = new Sim.ThermalSolver(\n        solverConfig as unknown as ConstructorParameters<typeof Sim.ThermalSolver>[0]\n      );\n      const thermalGeoHash = computeThermalGeometryHash(solverConfig);\n      recorder = new LocalTraceRecorder(name, solverConfig, thermalGeoHash);\n\n      const dt = typeof solverConfig.timeStep === 'number' ? solverConfig.timeStep : 0.01;\n      const steps =\n        typeof (args as { steps?: unknown }).steps === 'number'\n          ? (args as { steps: number }).steps | 0\n          : 10;\n\n      for (let i = 0; i < Math.max(1, steps); i++) {\n        solver.step(dt);\n        const stateDigest = computeThermalStateDigest(Sim, solver, 'fnv1a');\n        recorder.step(dt, stateDigest ? [stateDigest] : []);\n      }\n\n      result = {\n        temperatureGrid: solver.getTemperatureGrid(),\n        temperatureField: solver.getTemperatureField(),\n      };\n    }\n\n    recorder.finalize();\n    const traceJSONL = recorder.toJSONL();\n    const trace = parseTrace(traceJSONL);\n    const last = trace[trace.length - 1];\n    const traceId = `cael:${last?.runId ?? 'unknown'}:${last?.hash ?? 'nohash'}`;\n    traceRegistry.set(traceId, traceJSONL);\n\n    return {\n      success: true,\n      result,\n      caelTraceId: traceId,\n      traceHash: last?.hash ?? null,\n      traceJSONL,\n      provenance: last?.payload?.provenance ?? null,\n      verifyUrl: `https://mcp.holoscript.net/verify-cael?traceId=${encodeURIComponent(traceId)}`,\n    };\n  } catch (error) {\n    return {\n      success: false,\n      error: error instanceof Error ? error.message : String(error),\n    };\n  }\n}\n\nasync function solveLogic(args: Record<string, unknown>): Promise<Record<string, unknown>> {\n  const code = typeof args.code === 'string' ? args.code : '';\n  const functionName = typeof args.functionName === 'string' ? args.functionName : '';\n  const logicArgs = Array.isArray(args.args) ? args.args : [];\n  const timeout = typeof args.timeout === 'number' ? args.timeout : undefined;\n  if (!code || !functionName) {\n    return { success: false, error: 'code and functionName are required for solve_logic' };\n  }\n\n  // Safe execution through the canonical sandbox: .hs parse-validation + capability gate\n  // (blocklist + proto-escape) + hardened node:vm isolate. Used purely as the executor.\n  const { HoloScriptSandbox } = await import('@holoscript/security-sandbox');\n  const exec = await new HoloScriptSandbox().executeVerifiedLogic(code, functionName, logicArgs, {\n    timeout,\n  });\n  if (!exec.success || !exec.data) {\n    return { success: false, error: exec.error?.message ?? 'logic execution failed' };\n  }\n  const result = exec.data.result;\n\n  // Record a native CAEL trace (the format verify_cael_trace replays) embedding the inputs,\n  // so the verifyUrl can re-run the logic and confirm the result (re-runnable proof).\n  const recorder = new LocalTraceRecorder(\n    'hs-logic',\n    { code, functionName, args: logicArgs },\n    fnv1a(`${functionName}:${code}`)\n  );\n  recorder.finalize({ result, sandboxVerified: exec.data.verified });\n  const traceJSONL = recorder.toJSONL();\n  const trace = parseTrace(traceJSONL);\n  const last = trace[trace.length - 1];\n  const traceId = `cael:${last?.runId ?? 'unknown'}:${last?.hash ?? 'nohash'}`;\n  traceRegistry.set(traceId, traceJSONL);\n\n  return {\n    success: true,\n    result,\n    verified: exec.data.verified,\n    caelTraceId: traceId,\n    traceHash: last?.hash ?? null,\n    traceJSONL,\n    verifyUrl: `https://mcp.holoscript.net/verify-cael?traceId=${encodeURIComponent(traceId)}`,\n  };\n}\n\nasync function verifyTrace(args: Record<string, unknown>): Promise<Record<string, unknown>> {\n  const traceId = typeof args.traceId === 'string' ? args.traceId : null;\n  const traceJSONLFromArgs = typeof args.traceJSONL === 'string' ? args.traceJSONL : null;\n\n  const traceJSONL = traceJSONLFromArgs ?? (traceId ? (traceRegistry.get(traceId) ?? null) : null);\n  if (!traceJSONL) {\n    return {\n      success: false,\n      error: 'traceJSONL or a known traceId is required',\n    };\n  }\n\n  const trace = parseTrace(traceJSONL);\n  const hashChain = verifyHashChain(trace);\n  if (!hashChain.valid) {\n    return {\n      success: false,\n      hashChainValid: false,\n      replayValid: false,\n      brokenAt: hashChain.brokenAt,\n      reason: hashChain.reason,\n    };\n  }\n\n  const init = trace[0];\n  const solverType = String(init?.payload?.solverType ?? '');\n  const hashMode: HashMode = init?.payload?.hashMode === 'sha256' ? 'sha256' : 'fnv1a';\n\n  try {\n    let totalSteps = 0;\n    let totalSimTime = 0;\n\n    const Sim = await getSimulation();\n\n    if (solverType === 'solve_structural') {\n      const solverConfig = rehydrateTraceConfig(init?.payload?.config ?? {});\n      const solver = new Sim.StructuralSolverTET10(\n        solverConfig as unknown as ConstructorParameters<typeof Sim.StructuralSolverTET10>[0]\n      );\n      await Promise.resolve(solver.solve());\n      const solveEvent = trace.find((e) => e.event === 'solve');\n      if (!solveEvent) {\n        throw new Error('structural trace is missing the solve event required for replay evidence');\n      }\n      const stateDigest = computeStructuralStateDigest(\n        Sim,\n        solver.getDisplacements(),\n        solver.getVonMisesStress(),\n        hashMode\n      );\n      verifyStateDigests(solveEvent, stateDigest ? [stateDigest] : []);\n    } else if (solverType === 'solve_thermal') {\n      const solver = new Sim.ThermalSolver(\n        (init?.payload?.config ?? {}) as unknown as ConstructorParameters<\n          typeof Sim.ThermalSolver\n        >[0]\n      );\n      for (const e of trace) {\n        if (e.event === 'step') {\n          const dt = Number(e.payload.wallDelta ?? 0.01);\n          solver.step(dt);\n          const stateDigest = computeThermalStateDigest(Sim, solver, hashMode);\n          verifyStateDigests(e, stateDigest ? [stateDigest] : []);\n          totalSteps++;\n          totalSimTime += dt;\n        }\n      }\n    } else if (solverType === 'hs-logic') {\n      // Re-execute the recorded .hs function with the recorded args in the restricted\n      // same-process context and compare it with the recorded result. This checks\n      // reproducibility for the trace's own input; it is not hard isolation or origin proof.\n      const cfg = (init?.payload?.config ?? {}) as {\n        code?: unknown;\n        functionName?: unknown;\n        args?: unknown;\n      };\n      const code = typeof cfg.code === 'string' ? cfg.code : '';\n      const functionName = typeof cfg.functionName === 'string' ? cfg.functionName : '';\n      const logicArgs = Array.isArray(cfg.args) ? cfg.args : [];\n      if (!code || !functionName) {\n        throw new Error('hs-logic trace is missing code/functionName for replay');\n      }\n      const recordedResult = trace[trace.length - 1]?.payload?.result;\n      const { HoloScriptSandbox } = await import('@holoscript/security-sandbox');\n      const replay = await new HoloScriptSandbox().executeVerifiedLogic(\n        code,\n        functionName,\n        logicArgs\n      );\n      const replayResult = replay.success ? replay.data?.result : undefined;\n      const replayValid =\n        replay.success &&\n        JSON.stringify(canonical(replayResult)) === JSON.stringify(canonical(recordedResult));\n      return {\n        success: replayValid,\n        hashChainValid: true,\n        replayValid,\n        solverType,\n        recordedResult,\n        replayResult,\n        interactions: trace.filter((e) => e.event === 'interaction').length,\n      };\n    } else {\n      throw new Error(`Unsupported solverType for replay verification: ${solverType}`);\n    }\n\n    return {\n      success: true,\n      hashChainValid: true,\n      replayValid: true,\n      solverType,\n      totalSteps,\n      totalSimTime,\n      interactions: trace.filter((e) => e.event === 'interaction').length,\n    };\n  } catch (error) {\n    return {\n      success: false,\n      hashChainValid: true,\n      replayValid: false,\n      solverType,\n      error: error instanceof Error ? error.message : String(error),\n    };\n  }\n}\n","/**\n * Simulation Billing Tools -- MCP tools that dispatch /sim solver runs\n * through the ComputeBillingHarness + vast.ai GPU fleet.\n *\n * These tools extend the existing solve_structural / solve_thermal / verify_cael_trace\n * tools with a paid, capped execution path. A solver run becomes a billable job\n * that runs locally or on a fleet GPU worker, with the financial safety invariant:\n *\n *     Financial safety comes from the EXECUTION CAP, not from estimate accuracy.\n *     max_execution_time == paid_seconds; the platform is never financially exposed.\n *\n * Tools:\n * - sim_quote:     Price a solver run (estimate → quote, no execution).\n * - sim_run_paid:  Execute a solver as a paid, capped job (quote → charge → execute → reconcile).\n * - sim_fleet_status: Check the status of a fleet-dispatched solver job.\n *\n * The existing solve_structural / solve_thermal / verify_cael_trace tools remain\n * unchanged for free/local use. These tools add the billing+fleet layer on top.\n *\n * Ref: task_1779436686675_3jdw (T3), commit 8dfd148b, MEMORY S.QSIM\n * Ref: scripts/compute_billing_harness.py, scripts/sim_solver_executor.py\n * Ref: research/2026-05-21_managed-quantum-billing.md\n */\n\nimport type { Tool } from '@modelcontextprotocol/sdk/types.js';\nimport * as child_process from 'child_process';\nimport * as path from 'path';\nimport * as fs from 'fs';\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\ntype SolverKind = 'thermal' | 'structural';\n\ninterface SimQuote {\n  estimate_seconds: number;\n  cap_seconds: number;\n  price_usd: number;\n  price_credits: number;\n  rate_usd_per_sec: number;\n  buffer: number;\n  margin: number;\n  backend: string;\n}\n\ninterface SimOrderResult {\n  success: boolean;\n  job_ref: string;\n  quote: SimQuote;\n  charge: Record<string, unknown>;\n  execution: {\n    billable_seconds: number;\n    solver_type: string;\n    device: string;\n    steps_taken: number;\n    wall_seconds: number;\n    cap_exceeded: boolean;\n    cael_trace_id?: string;\n    result_summary?: Record<string, unknown>;\n  };\n  reconcile: Record<string, unknown>;\n  refund: Record<string, unknown>;\n  error?: string;\n}\n\n// ---------------------------------------------------------------------------\n// Billing harness adapter (Node.js side -- calls the Python harness via subprocess)\n// ---------------------------------------------------------------------------\n\n// Billing harness adapter. For action='quote' this returns a pure price estimate (no\n// execution claimed — billable_seconds:0). For action='run' it returns a billing envelope\n// whose execution numbers are SYNTHETIC here; handleSimRunPaid then OVERWRITES them with\n// the real local solver's measured wall time (dispatch_mode='local') and fails loud if the\n// solver did not run (true-simulation plan F1 — closes the prior ratchet-P4 overclaim where\n// a synthetic estimate*0.8 placeholder was returned as if solved). For dispatch_mode='fleet'\n// (UNWIRED/THIN — real fleet dispatch needs scripts/sim_solver_executor.py + vast.ai creds),\n// handleSimRunPaid now ALSO fails loud rather than returning the synthetic envelope, so a\n// paid order can never claim success for an unexecuted fleet solve (plan §0.6, F.095).\nasync function callPythonHarness(\n  action: 'quote' | 'run',\n  params: {\n    solver: SolverKind;\n    estimate_seconds: number;\n    rate: number;\n    customer?: string;\n    buffer?: number;\n    margin?: number;\n    steps?: number;\n    device?: string;\n    dispatch_mode?: 'local' | 'fleet';\n    solver_config?: Record<string, unknown>;\n  }\n): Promise<SimOrderResult> {\n  // The Python billing harness is the canonical implementation.\n  // Call it as a subprocess with JSON stdin/stdout.\n  const args = [\n    'scripts/sim_solver_executor.py',\n    '--solver',\n    params.solver,\n    '--estimate-seconds',\n    String(params.estimate_seconds),\n    '--rate',\n    String(params.rate),\n    '--customer',\n    params.customer || 'mcp-caller',\n  ];\n\n  if (params.buffer !== undefined) args.push('--buffer', String(params.buffer));\n  if (params.margin !== undefined) args.push('--margin', String(params.margin));\n  if (params.steps !== undefined) args.push('--steps', String(params.steps));\n  if (params.device) args.push('--device', params.device);\n  if (params.dispatch_mode) args.push('--dispatch-mode', params.dispatch_mode);\n  if (action === 'run') args.push('--write-receipt');\n\n  // Attempt to call the Python subprocess harness. If the script is missing,\n  // fall back to local computation (mirrors quantum_cost_quote.build_quote).\n  const scriptPath = path.resolve(process.cwd(), 'scripts/sim_solver_executor.py');\n  const scriptExists = fs.existsSync(scriptPath);\n\n  if (scriptExists) {\n    try {\n      const result = child_process.execFileSync(process.execPath, ['--version'], {\n        timeout: 30_000,\n        encoding: 'utf8',\n      });\n    } catch {\n      // execFileSync not suitable for Python — use spawnSync instead\n    }\n\n    try {\n      const spawnResult = child_process.spawnSync('python3', args, {\n        timeout: 60_000,\n        encoding: 'utf8',\n        stdio: ['pipe', 'pipe', 'pipe'],\n      });\n\n      if (spawnResult.status === 0 && spawnResult.stdout) {\n        const parsed = JSON.parse(spawnResult.stdout.trim());\n        return parsed as SimOrderResult;\n      }\n      // If Python spawn fails, fall through to local computation\n    } catch {\n      // Python not available or script error — fall through to local computation\n    }\n  }\n\n  // Fallback: local computation (mirrors quantum_cost_quote.build_quote)\n  const buffer = params.buffer ?? 0.15;\n  const margin = params.margin ?? 0.3;\n  const creditsPerUsd = 100.0;\n  const capSeconds = Math.ceil(params.estimate_seconds * (1 + buffer));\n  const priceUsd = capSeconds * params.rate * (1 + margin);\n  const priceCredits = priceUsd * creditsPerUsd;\n\n  const quote: SimQuote = {\n    estimate_seconds: params.estimate_seconds,\n    cap_seconds: capSeconds,\n    price_usd: Math.round(priceUsd * 1e6) / 1e6,\n    price_credits: Math.round(priceCredits * 100) / 100,\n    rate_usd_per_sec: params.rate,\n    buffer,\n    margin,\n    backend: params.dispatch_mode === 'fleet' ? 'vast-gpu' : 'holoscript-gpu',\n  };\n\n  if (action === 'quote') {\n    return {\n      success: true,\n      job_ref: `sim-${params.solver}-${params.customer || 'mcp-caller'}-${Date.now()}`,\n      quote,\n      charge: {},\n      execution: {\n        billable_seconds: 0,\n        solver_type: params.solver,\n        device: '',\n        steps_taken: 0,\n        wall_seconds: 0,\n        cap_exceeded: false,\n      },\n      reconcile: {},\n      refund: {},\n    };\n  }\n\n  // For 'run' with NO real billing harness reachable (Python/executor unavailable):\n  // a paid order CANNOT be charged here. Refuse to fabricate a \"successful\" charge\n  // for credits that never hit a ledger — that is the treasury-class integrity hole\n  // (F.095), exactly symmetric to the solver fail-loud fix in handleSimRunPaid. The\n  // ONLY legitimate no-harness path is EXPLICIT test mode (HOLO_TEST_CREDITS set),\n  // mirroring compute_billing_harness.charge()'s own test-ledger branch — which never\n  // moves real money. Real charges flow through the Python harness → orchestrator\n  // /billing/wallet/deduct (x402-credits).\n  const testCredits = process.env.HOLO_TEST_CREDITS;\n  const failClosed = (charge: Record<string, unknown>, error: string): SimOrderResult => ({\n    success: false,\n    job_ref: `sim-${params.solver}-${params.customer || 'mcp-caller'}-${Date.now()}`,\n    quote,\n    charge,\n    execution: {\n      billable_seconds: 0,\n      solver_type: params.solver,\n      device: '',\n      steps_taken: 0,\n      wall_seconds: 0,\n      cap_exceeded: false,\n    },\n    reconcile: {},\n    refund: {},\n    error,\n  });\n\n  if (testCredits === undefined) {\n    return failClosed(\n      {\n        backend: 'unwired',\n        charged_credits: 0,\n        real_money: false,\n        reason: 'billing harness unavailable and HOLO_TEST_CREDITS unset — refusing to charge',\n      },\n      'billing harness (scripts/sim_solver_executor.py) unavailable; paid order refused — no fabricated charge. ' +\n        'Set HOLO_TEST_CREDITS for a local test-ledger run, or ensure the Python harness + HOLOSCRIPT_API_KEY are present for real charging.'\n    );\n  }\n\n  // EXPLICIT test mode: honest test-ledger order (real_money:false), gated on the\n  // declared balance like the Python harness. Execution numbers below are placeholders\n  // that handleSimRunPaid OVERWRITES with the real local solver's measured wall time.\n  const testBal = Number(testCredits);\n  if (Number.isFinite(testBal) && testBal < priceCredits) {\n    return failClosed(\n      {\n        backend: 'test-ledger',\n        real_money: false,\n        reason: 'insufficient test balance',\n        needed: priceCredits,\n        balance: testBal,\n      },\n      `insufficient HOLO_TEST_CREDITS: need ${priceCredits} credits, have ${testBal}`\n    );\n  }\n\n  return {\n    success: true,\n    job_ref: `sim-${params.solver}-${params.customer || 'mcp-caller'}-${Date.now()}`,\n    quote,\n    charge: {\n      backend: 'test-ledger',\n      charged_credits: priceCredits,\n      real_money: false,\n      remaining: Number.isFinite(testBal) ? testBal - priceCredits : undefined,\n    },\n    execution: {\n      billable_seconds: params.estimate_seconds * 0.8, // placeholder; real execution overwrites this\n      solver_type: params.solver,\n      device: params.device || 'GPU',\n      steps_taken: params.steps || 10,\n      wall_seconds: params.estimate_seconds * 0.8,\n      cap_exceeded: false,\n    },\n    reconcile: {\n      paid_seconds: capSeconds,\n      actual_seconds: params.estimate_seconds * 0.8,\n      within_cap: true,\n      refund_usd:\n        Math.round((capSeconds - params.estimate_seconds * 0.8) * params.rate * 1e6) / 1e6,\n      refund_credits: 0,\n    },\n    refund: { backend: 'test-ledger', refunded_credits: 0, real_money: false },\n  };\n}\n\n// ---------------------------------------------------------------------------\n// Tool definitions\n// ---------------------------------------------------------------------------\n\nexport const simulationBillingTools: Tool[] = [\n  {\n    name: 'sim_quote',\n    description:\n      'Price a /sim solver run without executing it. Returns the quote: ' +\n      'estimated seconds, cap, price in USD and HoloScript credits. NOTE: the price is ' +\n      'a deterministic formula over the CALLER-SUPPLIED gpu_rate (not a real GPU/solver ' +\n      'cost model) — it is an estimate, not a market-derived price. ' +\n      'The cap (max_execution_time == paid_seconds) is the financial safety ' +\n      'anchor; the estimate only affects competitiveness, never exposure. ' +\n      'Use sim_run_paid to execute the solver (real local execution; synthetic billing — see its description).',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        solver: {\n          type: 'string',\n          enum: ['thermal', 'structural'],\n          description: 'Solver type to price.',\n        },\n        estimate_seconds: {\n          type: 'number',\n          description: 'Estimated wall-time in seconds (affects quote, NOT safety).',\n          minimum: 0.1,\n        },\n        rate: {\n          type: 'number',\n          description: 'GPU rental rate in USD/sec (e.g. 0.0001 for vast.ai RTX 3060).',\n          minimum: 0,\n        },\n        buffer: {\n          type: 'number',\n          description: 'Safety margin folded into cap (default 0.15 = +15%).',\n          default: 0.15,\n          minimum: 0,\n        },\n        margin: {\n          type: 'number',\n          description: 'Platform markup over GPU cost (default 0.30 = +30%).',\n          default: 0.3,\n          minimum: 0,\n        },\n        customer: {\n          type: 'string',\n          description: 'Customer identifier for billing.',\n          default: 'mcp-caller',\n        },\n        dispatch_mode: {\n          type: 'string',\n          enum: ['local', 'fleet'],\n          description: 'Execution target: local GPU or vast.ai fleet worker.',\n          default: 'local',\n        },\n      },\n      required: ['solver', 'estimate_seconds', 'rate'],\n    },\n  },\n  {\n    name: 'sim_run_paid',\n    description:\n      'Execute a /sim solver as a capped job with a quote->execute->reconcile envelope. ' +\n      'The solver execution is REAL for dispatch_mode=local (real ThermalSolver/' +\n      'StructuralSolver + CAEL trace); fleet dispatch fails loud (unwired). ' +\n      'BILLING IS NOT REAL YET: the charge/reconcile/refund are a synthetic test-ledger ' +\n      '(real_money:false) — no x402/treasury debit occurs (deep-ratchet 2026-06-05). ' +\n      'Returns the order result + CAEL trace + a SYNTHETIC (test-ledger) billing envelope, ' +\n      'NOT a real payment receipt. The execution cap still bounds wall-time. ' +\n      'Use sim_quote to preview the (caller-rate-based) price estimate first.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        solver: {\n          type: 'string',\n          enum: ['thermal', 'structural'],\n          description: 'Solver type to execute.',\n        },\n        solver_config: {\n          type: 'object',\n          description:\n            'Solver-specific configuration. Thermal: { gridResolution, timeStep, ... }. ' +\n            'Structural: { nodes, elements, materials, forces, constraints }.',\n        },\n        estimate_seconds: {\n          type: 'number',\n          description: 'Estimated wall-time in seconds (affects quote, NOT safety).',\n          minimum: 0.1,\n        },\n        rate: {\n          type: 'number',\n          description: 'GPU rental rate in USD/sec.',\n          minimum: 0,\n        },\n        steps: {\n          type: 'number',\n          description: 'Number of solver steps (transient solvers only).',\n          default: 10,\n          minimum: 1,\n        },\n        device: {\n          type: 'string',\n          enum: ['GPU', 'CPU'],\n          description: 'Preferred compute device.',\n          default: 'GPU',\n        },\n        dispatch_mode: {\n          type: 'string',\n          enum: ['local', 'fleet'],\n          description: 'Execution target: local GPU or vast.ai fleet worker.',\n          // THIN (ratchet P4): vast.ai fleet dispatch is rule-only. No --yes auto-approval flag\n          // is wired. The billing harness attempts Python subprocess dispatch but falls through\n          // to local computation when Python is unavailable. Real fleet dispatch requires the\n          // compute_billing_harness.py script + vast.ai CLI credentials.\n          default: 'local',\n        },\n        buffer: {\n          type: 'number',\n          description: 'Safety margin folded into cap (default 0.15).',\n          default: 0.15,\n        },\n        margin: {\n          type: 'number',\n          description: 'Platform markup over GPU cost (default 0.30).',\n          default: 0.3,\n        },\n        customer: {\n          type: 'string',\n          description: 'Customer identifier for billing.',\n          default: 'mcp-caller',\n        },\n      },\n      required: ['solver', 'estimate_seconds', 'rate'],\n    },\n  },\n  {\n    name: 'sim_fleet_status',\n    description:\n      'Check the status of a fleet-dispatched solver job. ' +\n      'Returns the current job status (pending, running, done, error) and ' +\n      'any available results. Only applicable for jobs submitted with dispatch_mode=fleet.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        job_id: {\n          type: 'string',\n          description: 'Job ID returned by sim_run_paid with fleet dispatch.',\n        },\n      },\n      required: ['job_id'],\n    },\n  },\n];\n\n// ---------------------------------------------------------------------------\n// Handlers\n// ---------------------------------------------------------------------------\n\nexport async function handleSimulationBillingTool(\n  name: string,\n  args: Record<string, unknown>\n): Promise<unknown | null> {\n  switch (name) {\n    case 'sim_quote':\n      return handleSimQuote(args);\n    case 'sim_run_paid':\n      return handleSimRunPaid(args);\n    case 'sim_fleet_status':\n      return handleSimFleetStatus(args);\n    default:\n      return null;\n  }\n}\n\nasync function handleSimQuote(args: Record<string, unknown>): Promise<Record<string, unknown>> {\n  const solver = args.solver as SolverKind;\n  const estimateSeconds = Number(args.estimate_seconds);\n  const rate = Number(args.rate);\n  const buffer = args.buffer !== undefined ? Number(args.buffer) : 0.15;\n  const margin = args.margin !== undefined ? Number(args.margin) : 0.3;\n  const customer = (args.customer as string) || 'mcp-caller';\n  const dispatchMode = (args.dispatch_mode as 'local' | 'fleet') || 'local';\n\n  if (!solver || !estimateSeconds || !rate) {\n    return { success: false, error: 'solver, estimate_seconds, and rate are required' };\n  }\n\n  const result = await callPythonHarness('quote', {\n    solver,\n    estimate_seconds: estimateSeconds,\n    rate,\n    customer,\n    buffer,\n    margin,\n    dispatch_mode: dispatchMode,\n  });\n\n  return {\n    success: true,\n    quote: result.quote,\n    job_ref: result.job_ref,\n  };\n}\n\nasync function handleSimRunPaid(args: Record<string, unknown>): Promise<Record<string, unknown>> {\n  const solver = args.solver as SolverKind;\n  const estimateSeconds = Number(args.estimate_seconds);\n  const rate = Number(args.rate);\n  const steps = args.steps !== undefined ? Number(args.steps) : 10;\n  const device = (args.device as string) || 'GPU';\n  const dispatchMode = (args.dispatch_mode as 'local' | 'fleet') || 'local';\n  const buffer = args.buffer !== undefined ? Number(args.buffer) : 0.15;\n  const margin = args.margin !== undefined ? Number(args.margin) : 0.3;\n  const customer = (args.customer as string) || 'mcp-caller';\n  const solverConfig = args.solver_config as Record<string, unknown> | undefined;\n\n  if (!solver || !estimateSeconds || !rate) {\n    return { success: false, error: 'solver, estimate_seconds, and rate are required' };\n  }\n\n  const result = await callPythonHarness('run', {\n    solver,\n    estimate_seconds: estimateSeconds,\n    rate,\n    customer,\n    buffer,\n    margin,\n    steps,\n    device,\n    dispatch_mode: dispatchMode,\n    solver_config: solverConfig,\n  });\n\n  if (!result.success) {\n    return { success: false, error: result.error || 'order failed' };\n  }\n\n  // For local dispatch, run the REAL MCP solver tool to get the CAEL trace +\n  // actual solver results, and ground the billing numbers in the MEASURED wall\n  // time. (true-simulation plan F1 / ratchet P4: previously `billable_seconds`\n  // was a synthetic `estimate*0.8` placeholder and a solver FAILURE was silently\n  // swallowed into a \"successful\" paid order — both are integrity holes. Fixed:\n  // bill for measured execution, and fail-loud when the solver does not run.)\n  if (dispatchMode === 'local') {\n    let mcpResult: Record<string, unknown>;\n    const startMs = Date.now();\n    try {\n      const { handleSimulationTool } = await import('./simulation-tools');\n      const mcpConfig = solverConfig || buildDefaultConfig(solver, args);\n      mcpResult = (await handleSimulationTool(\n        solver === 'thermal' ? 'solve_thermal' : 'solve_structural',\n        { config: mcpConfig, steps }\n      )) as Record<string, unknown>;\n    } catch (err) {\n      mcpResult = { success: false, error: err instanceof Error ? err.message : String(err) };\n    }\n    const wallSeconds = (Date.now() - startMs) / 1000;\n\n    if (!mcpResult || mcpResult.success !== true) {\n      // Fail-loud: the real solver did not run, so there is nothing to bill.\n      // Never return a synthetic \"successful\" paid order for an absent solve.\n      return {\n        success: false,\n        error: `solver execution failed: ${\n          (mcpResult && (mcpResult.error as string)) || 'unknown solver error'\n        }`,\n        quote: result.quote,\n        job_ref: result.job_ref,\n      };\n    }\n\n    // Real solver ran — ground billing in the measured wall time, capped at the\n    // financial-safety ceiling (paid_seconds). Recompute reconcile/refund to match.\n    const paidSeconds = Number(result.reconcile.paid_seconds ?? result.quote.cap_seconds);\n    const billable = Math.min(wallSeconds, paidSeconds);\n    result.execution.billable_seconds = billable;\n    result.execution.wall_seconds = wallSeconds;\n    result.execution.cap_exceeded = wallSeconds > paidSeconds;\n    result.execution.device = device;\n    result.execution.steps_taken = steps;\n    result.execution.cael_trace_id = mcpResult.caelTraceId as string;\n    result.reconcile.actual_seconds = billable;\n    result.reconcile.within_cap = wallSeconds <= paidSeconds;\n    result.reconcile.refund_usd =\n      Math.round(Math.max(0, paidSeconds - billable) * rate * 1e6) / 1e6;\n    result.execution.result_summary = {\n      solver,\n      ...(solver === 'thermal'\n        ? {\n            min_temp: extractFieldMin(mcpResult.result, 'temperatureField'),\n            max_temp: extractFieldMax(mcpResult.result, 'temperatureField'),\n          }\n        : {\n            max_displacement: extractFieldMax(mcpResult.result, 'displacements'),\n            max_stress: extractFieldMax(mcpResult.result, 'vonMisesStress'),\n          }),\n    };\n  } else {\n    // dispatch_mode === 'fleet': vast.ai fleet dispatch is UNWIRED (THIN).\n    // callPythonHarness('run') returned a SYNTHETIC `estimate*0.8` placeholder\n    // with success:true; returning it would bill a \"successful\" paid order for\n    // a solve that NEVER RAN — a treasury-class integrity hole (F.095), the same\n    // class as the local-path bug F1 closed. Fail loud until real fleet dispatch\n    // (scripts/sim_solver_executor.py + vast.ai credentials) is wired.\n    // (true-simulation plan §0.6: fail-loud the fleet path before any GPU phase.)\n    return {\n      success: false,\n      error:\n        'fleet dispatch is not wired: real vast.ai GPU execution requires ' +\n        'scripts/sim_solver_executor.py + fleet credentials. Refusing to return ' +\n        'a synthetic billing result for an unexecuted solve — use dispatch_mode=local.',\n      quote: result.quote,\n      job_ref: result.job_ref,\n    };\n  }\n\n  return result as unknown as Record<string, unknown>;\n}\n\nasync function handleSimFleetStatus(\n  args: Record<string, unknown>\n): Promise<Record<string, unknown>> {\n  const jobId = args.job_id as string;\n\n  if (!jobId) {\n    return { success: false, error: 'job_id is required' };\n  }\n\n  // Query the orchestrator for the fleet job status\n  const orchUrl =\n    process.env.MCP_ORCHESTRATOR_URL || 'https://mcp-orchestrator-production-45f9.up.railway.app';\n  const apiKey = process.env.HOLOSCRIPT_API_KEY || '';\n\n  if (!apiKey) {\n    return { success: false, error: 'HOLOSCRIPT_API_KEY not configured; cannot query fleet' };\n  }\n\n  try {\n    const res = await fetch(`${orchUrl}/gpu/job/${jobId}`, {\n      headers: { 'x-mcp-api-key': apiKey },\n    });\n\n    if (!res.ok) {\n      if (res.status === 404) {\n        return { success: false, error: `job ${jobId} not found` };\n      }\n      return { success: false, error: `fleet API returned HTTP ${res.status}` };\n    }\n\n    const status = (await res.json()) as Record<string, unknown>;\n    return { success: true, job_id: jobId, ...status };\n  } catch (err) {\n    return {\n      success: false,\n      error: `fleet status query failed: ${err instanceof Error ? err.message : String(err)}`,\n    };\n  }\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction buildDefaultConfig(\n  solver: SolverKind,\n  args: Record<string, unknown>\n): Record<string, unknown> {\n  if (solver === 'thermal') {\n    const gridRes = args.grid_resolution as number[] | undefined;\n    return {\n      gridResolution: gridRes || [5, 5, 5],\n      domainSize: [1, 1, 1],\n      timeStep: 0.01,\n      materials: {},\n      defaultMaterial: 'water',\n      boundaryConditions: [],\n      sources: [],\n      initialTemperature: 20,\n    };\n  }\n\n  // structural\n  return {\n    nodes: [\n      [0, 0, 0],\n      [1, 0, 0],\n      [0, 1, 0],\n      [0, 0, 1],\n    ],\n    elements: [[0, 1, 2, 3, 0, 1, 2, 3, 0, 1]],\n    materials: { E: 2e11, nu: 0.3 },\n    forces: [{ nodeIndex: 3, fx: 0, fy: -1000, fz: 0 }],\n    constraints: [{ nodeIndex: 0, dx: true, dy: true, dz: true }],\n  };\n}\n\nfunction extractFieldMin(result: unknown, fieldName: string): number | null {\n  if (!result || typeof result !== 'object') return null;\n  const r = result as Record<string, unknown>;\n  const field = r[fieldName];\n  if (field instanceof Float32Array || field instanceof Float64Array) {\n    let min = Infinity;\n    for (let i = 0; i < field.length; i++) {\n      if (field[i] < min) min = field[i];\n    }\n    return min === Infinity ? null : min;\n  }\n  if (Array.isArray(field)) {\n    const nums = field.filter((v): v is number => typeof v === 'number');\n    return nums.length > 0 ? Math.min(...nums) : null;\n  }\n  return null;\n}\n\nfunction extractFieldMax(result: unknown, fieldName: string): number | null {\n  if (!result || typeof result !== 'object') return null;\n  const r = result as Record<string, unknown>;\n  const field = r[fieldName];\n  if (field instanceof Float32Array || field instanceof Float64Array) {\n    let max = -Infinity;\n    for (let i = 0; i < field.length; i++) {\n      if (field[i] > max) max = field[i];\n    }\n    return max === -Infinity ? null : max;\n  }\n  if (Array.isArray(field)) {\n    const nums = field.filter((v): v is number => typeof v === 'number');\n    return nums.length > 0 ? Math.max(...nums) : null;\n  }\n  return null;\n}\n","/**\n * HoloMesh Type Definitions\n *\n * Core types for the decentralized knowledge exchange mesh.\n * Knowledge brain types (domains, consolidation, excitability, half-lives)\n * now live in @holoscript/framework. Re-exported here for backward compat.\n */\n\n// Knowledge brain — canonical source is @holoscript/framework\nexport type {\n  KnowledgeDomain,\n  DomainConsolidationConfig,\n  ExcitabilityMetadata,\n  HotBufferEntry,\n  ConsolidationResult,\n  ReconsolidationEvent,\n  MemoryReceipt,\n} from '@holoscript/framework';\n\nimport type {\n  TeamTask,\n  DoneLogEntry,\n  BountyManager,\n  TeamSuggestion,\n  HoloMeshIdentityEnvelope,\n} from '@holoscript/framework';\nexport type { TeamTask, BountyManager, HoloMeshIdentityEnvelope };\nexport {\n  /* TeamTask, BountyManager, */\n  KNOWLEDGE_DOMAINS,\n  DOMAIN_CONSOLIDATION,\n  DOMAIN_HALF_LIVES,\n  computeExcitability,\n  applyHalfLifeDecay,\n  RECONSOLIDATION_WINDOW_MS,\n  triggerReconsolidation,\n  hashString,\n} from '@holoscript/framework';\n\n// --- Agent Identity ---\n\nexport interface HoloMeshAgentCard {\n  id: string;\n  name: string;\n  did?: string; // Decentralized ID (V2)\n  mcpEndpoint?: string; // Direct P2P address (V2)\n  mcpBaseUrl?: string; // Normalized CRDT gossip base URL\n  mcp_base_url?: string; // Legacy snake_case alias\n  endpoint?: string; // A2A endpoint alias, normalized by discovery\n  url?: string; // Agent-card URL alias, normalized by discovery\n  metadata?: Record<string, unknown>;\n  workspace: string;\n  traits: string[]; // e.g., ['@economy', '@research', '@philosophy']\n  reputation: number;\n  contributionCount: number;\n  queryCount: number;\n  joinedAt: string;\n}\n\n// --- Gossip Protocol ---\n\nexport type GossipType = 'knowledge' | 'signal' | 'heartbeat' | 'query' | 'response';\n\nexport interface GossipMessage {\n  id: string;\n  type: GossipType;\n  senderId: string;\n  senderName: string;\n  payload: Record<string, unknown>;\n  timestamp: string;\n  /** Content hash for dedup */\n  hash?: string;\n}\n\n// --- Knowledge Exchange ---\n\nexport type KnowledgeEntryType = 'wisdom' | 'pattern' | 'gotcha';\n\nexport interface MeshKnowledgeEntry {\n  id: string;\n  workspaceId: string;\n  type: KnowledgeEntryType;\n  content: string;\n  /** SHA-256 provenance hash */\n  provenanceHash: string;\n  /** Author agent ID */\n  authorId: string;\n  authorName: string;\n  /** Price in USD (0 = free) */\n  price: number;\n  /** How many times this entry has been queried */\n  queryCount: number;\n  /** How many agents reused this entry */\n  reuseCount: number;\n  domain?: string;\n  tags?: string[];\n  confidence?: number;\n  createdAt: string;\n  updatedAt?: string;\n  /** Arbitrary metadata that survives orchestrator round-trip (stored as JSON) */\n  metadata?: Record<string, unknown>;\n}\n\n// --- Tier2 Self-Custody Export Session (V3 foundation) ---\n\nexport type ExportSessionStatus = 'prepared' | 'packaged' | 'finalized' | 'expired';\n\nexport interface ExportSession {\n  sessionId: string;\n  userId: string;\n  createdAt: number;\n  expiresAt: number;\n  status: ExportSessionStatus;\n  serverNonce: string;\n  idempotencyKeys: Set<string>;\n  consumedAt?: number;\n  packageManifestHash?: string;\n}\n\nexport interface SerializedExportSession extends Omit<ExportSession, 'idempotencyKeys'> {\n  idempotencyKeys: string[];\n}\n\n// --- Reputation ---\n\nexport interface AgentReputation {\n  agentId: string;\n  agentName: string;\n  /** Total contributions (W/P/G entries shared) */\n  contributions: number;\n  /** Total queries answered */\n  queriesAnswered: number;\n  /** Reuse rate: how often contributed entries are queried by others */\n  reuseRate: number;\n  /** Computed reputation score */\n  score: number;\n  /** Reputation tier */\n  tier: 'newcomer' | 'contributor' | 'expert' | 'authority';\n}\n\nexport const REPUTATION_TIERS = [\n  { minScore: 100, tier: 'authority' as const },\n  { minScore: 30, tier: 'expert' as const },\n  { minScore: 5, tier: 'contributor' as const },\n  { minScore: 0, tier: 'newcomer' as const },\n] as const;\n\nexport function resolveReputationTier(score: number): AgentReputation['tier'] {\n  for (const t of REPUTATION_TIERS) {\n    if (score >= t.minScore) return t.tier;\n  }\n  return 'newcomer';\n}\n\n// --- V11: Hysteresis for Reputation Tiers ---\n\nexport const REPUTATION_TIERS_HYSTERESIS = [\n  { promote: 100, demote: 75, tier: 'authority' as const },\n  { promote: 30, demote: 22, tier: 'expert' as const },\n  { promote: 5, demote: 3, tier: 'contributor' as const },\n  { promote: 0, demote: 0, tier: 'newcomer' as const },\n] as const;\n\n/**\n * Resolve reputation tier with hysteresis — asymmetric promote/demote thresholds.\n * Prevents oscillation when scores hover near tier boundaries.\n * Demote threshold = promote * 0.75 (requires more evidence to recover than to lose).\n */\nexport function resolveReputationTierWithHysteresis(\n  score: number,\n  currentTier?: AgentReputation['tier']\n): AgentReputation['tier'] {\n  if (!currentTier) return resolveReputationTier(score);\n\n  const currentIdx = REPUTATION_TIERS_HYSTERESIS.findIndex((t) => t.tier === currentTier);\n\n  // Check promotion (score exceeds a higher tier's promote threshold)\n  for (let i = 0; i < REPUTATION_TIERS_HYSTERESIS.length; i++) {\n    if (i < currentIdx && score >= REPUTATION_TIERS_HYSTERESIS[i].promote) {\n      return REPUTATION_TIERS_HYSTERESIS[i].tier;\n    }\n  }\n\n  // Check demotion (score below current tier's demote threshold)\n  if (currentIdx >= 0 && currentIdx < REPUTATION_TIERS_HYSTERESIS.length) {\n    if (score < REPUTATION_TIERS_HYSTERESIS[currentIdx].demote) {\n      for (let i = currentIdx + 1; i < REPUTATION_TIERS_HYSTERESIS.length; i++) {\n        if (score >= REPUTATION_TIERS_HYSTERESIS[i].demote) {\n          return REPUTATION_TIERS_HYSTERESIS[i].tier;\n        }\n      }\n      return 'newcomer';\n    }\n  }\n\n  // Score is in hysteresis band — keep current tier\n  return currentTier;\n}\n\n// --- V11: Authority Tier Algebraic Consequences ---\n\n/**\n * Material consequences of reputation tier.\n * Authority is not just a label — it changes gossip priority, decay rate,\n * and corroboration weight in the provenance algebra.\n */\nexport const TIER_WEIGHTS = {\n  newcomer: { gossipPriority: 1.0, decayMultiplier: 1.0, corroborationWeight: 1.0 },\n  contributor: {\n    gossipPriority: 1.2,\n    decayMultiplier: 0.95,\n    corroborationWeight: 1.5,\n  },\n  expert: { gossipPriority: 1.5, decayMultiplier: 0.85, corroborationWeight: 2.0 },\n  authority: {\n    gossipPriority: 2.0,\n    decayMultiplier: 0.7,\n    corroborationWeight: 3.0,\n  },\n} as const;\n\nexport type TierWeight = (typeof TIER_WEIGHTS)[keyof typeof TIER_WEIGHTS];\n\nexport function getTierWeight(tier: AgentReputation['tier']): TierWeight {\n  return TIER_WEIGHTS[tier] || TIER_WEIGHTS.newcomer;\n}\n\n/**\n * Reputation = directWork + reuseWeight\n * directWork = contributions * 0.3 + queriesAnswered * 0.2\n * reuseWeight = min(effectiveReuseRate * 20, 40, directWork * 2)\n *\n * V10: Cap reuseRate at 20, require 3+ contributions.\n * V11: Bound reuseWeight by 2x direct work score — passive income\n * cannot exceed 2x active contribution. Prevents Sybil clusters\n * from reaching authority tier with minimal real work.\n */\nexport function computeReputation(\n  contributions: number,\n  queriesAnswered: number,\n  reuseRate: number\n): number {\n  const effectiveReuseRate = contributions >= 3 ? reuseRate : 0;\n  const directWorkScore = contributions * 0.3 + queriesAnswered * 0.2;\n  const reuseWeight = Math.min(effectiveReuseRate * 20, 40, directWorkScore * 2);\n  return Math.round((directWorkScore + reuseWeight) * 100) / 100;\n}\n\n// --- Mesh Configuration ---\n\nexport interface MeshConfig {\n  orchestratorUrl: string;\n  apiKey: string;\n  workspace: string;\n  agentName: string;\n  /** Polling interval for peer discovery (ms) */\n  discoveryIntervalMs: number;\n  /** Polling interval for inbox check (ms) */\n  inboxIntervalMs: number;\n  /** Max knowledge entries to contribute per cycle */\n  maxContributionsPerCycle: number;\n  /** Max queries to execute per cycle */\n  maxQueriesPerCycle: number;\n  /** Budget cap in USD */\n  budgetCapUSD: number;\n}\n\nexport const DEFAULT_MESH_CONFIG: Omit<MeshConfig, 'apiKey'> = {\n  orchestratorUrl:\n    process.env.MCP_ORCHESTRATOR_URL || 'https://mcp-orchestrator-production-45f9.up.railway.app',\n  workspace: process.env.HOLOMESH_WORKSPACE || 'default',\n  agentName: 'holomesh-agent',\n  discoveryIntervalMs: 5 * 60 * 1000, // 5 min\n  inboxIntervalMs: 60 * 1000, // 1 min\n  maxContributionsPerCycle: 5,\n  maxQueriesPerCycle: 3,\n  budgetCapUSD: 5.0,\n};\n\n// --- V2 Peer Store ---\n\nexport interface PeerStoreEntry {\n  did: string;\n  mcpBaseUrl: string;\n  name: string;\n  traits: string[];\n  reputation: number;\n  lastSeen: string;\n  lastSyncAt: string | null;\n  /** Loro frontiers from last sync (JSON-serializable) */\n  lastKnownFrontiers: unknown[] | null;\n  source: 'orchestrator' | 'gossip' | 'direct';\n  /** Consecutive contact failures */\n  failureCount: number;\n  /** V4: Wallet address (verified via signature) */\n  walletAddress?: string;\n}\n\n// --- V2 Gossip Exchange ---\n\n/** V6: Health metadata transmitted as gossip side-channel */\nexport interface GossipHealthMetadata {\n  /** Seconds since daemon started */\n  uptimeSeconds: number;\n  /** Consecutive gossip failures in current session */\n  failureCount: number;\n  /** Peer count visible to sender */\n  peerCount: number;\n  /** Sender's self-assessed reputation score */\n  reputationScore: number;\n  /** Knowledge entries contributed this session */\n  contributionsThisSession: number;\n  /** ISO timestamp of last daemon restart */\n  lastRestartAt?: string;\n}\n\nexport interface GossipDeltaRequest {\n  senderDid: string;\n  senderUrl: string;\n  senderName: string;\n  /** Loro binary delta encoded as base64 */\n  deltaBase64: string;\n  /** Sender's Loro frontiers for version negotiation */\n  frontiers: unknown[];\n  /** Peers to share via gossip */\n  knownPeers?: Array<{ did: string; url: string; name: string }>;\n  timestamp: string;\n  /** V4: EIP-191 signature over gossip payload */\n  signature?: string;\n  /** V4: Sender wallet address (for signature verification) */\n  senderWalletAddress?: string;\n  /** V6: Health metadata piggybacked on gossip (observability side-channel) */\n  senderHealth?: GossipHealthMetadata;\n}\n\nexport interface GossipDeltaResponse {\n  success: boolean;\n  /** Receiver's delta back to sender (base64) */\n  deltaBase64?: string;\n  /** Receiver's Loro frontiers */\n  frontiers?: unknown[];\n  /** Receiver's known peers */\n  knownPeers?: Array<{ did: string; url: string; name: string }>;\n  /** V4: Signature verification result */\n  signatureVerified?: 'verified' | 'unsigned' | 'invalid';\n  /** V6: Responder's health metadata */\n  responderHealth?: GossipHealthMetadata;\n}\n\n// Knowledge brain types re-exported from @holoscript/framework at top of file.\n\n// --- Daemon State ---\n\nexport interface HoloMeshDaemonState {\n  agentId: string | null;\n  agentName: string;\n  workspace: string;\n  status: 'idle' | 'running' | 'paused' | 'error';\n  peers: string[];\n  following: string[];\n  followers: string[];\n  reputation: number;\n  reputationTier: AgentReputation['tier'];\n  contributedIds: string[];\n  receivedIds: string[];\n  queryHistory: string[];\n  totalContributions: number;\n  totalQueries: number;\n  totalCollects: number;\n  spentUSD: number;\n  earningsUSD: number;\n  budgetCapUSD: number;\n  cycles: number;\n  lastCycleAt: string | null;\n  errors: number;\n  // V2 gossip fields (null/false = V1 mode)\n  v2Enabled: boolean;\n  p2pPeerCount: number;\n  gossipSyncCount: number;\n  crdtMergeCount: number;\n  lastGossipSyncAt: string | null;\n  // V3 wallet fields (null/false = no wallet)\n  walletEnabled: boolean;\n  walletAddress: string | null;\n  walletChainId: number;\n  walletBalanceUSDC: number;\n  totalPaymentsMade: number;\n  totalPaymentsReceived: number;\n  microLedgerUnsettled: number;\n  lastSettlementAt: string | null;\n  // V4 wallet identity (null = no wallet-based DID)\n  agentDid: string | null;\n  // V5 agent profile (MySpace)\n  profileCreated: boolean;\n  profileDisplayName: string;\n  profileBio: string;\n  profileCustomTitle: string;\n  profileThemeColor: string;\n  // V6 daemon discovery / query fields\n  knownPeerCount: number;\n  lastDiscoveryAt: string | null;\n  unreadMessages: number;\n  totalQueriesAnswered: number;\n  lastContributionAt: string | null;\n  // V7 team message dedup\n  processedMessageIds: string[];\n  // V11 resource pressure (L4 Blueprint 1: wire rendering to budget gate)\n  resourcePressure: number;\n  suggestedLOD: number;\n  hardLimitBreached: boolean;\n}\n\nexport const INITIAL_MESH_STATE: HoloMeshDaemonState = {\n  agentId: null,\n  agentName: 'holomesh-agent',\n  workspace: process.env.HOLOMESH_WORKSPACE || 'default',\n  status: 'idle',\n  peers: [],\n  following: [],\n  followers: [],\n  reputation: 0,\n  reputationTier: 'newcomer',\n  contributedIds: [],\n  receivedIds: [],\n  queryHistory: [],\n  totalContributions: 0,\n  totalQueries: 0,\n  totalCollects: 0,\n  spentUSD: 0,\n  earningsUSD: 0,\n  budgetCapUSD: 5.0,\n  cycles: 0,\n  lastCycleAt: null,\n  errors: 0,\n  knownPeerCount: 0,\n  lastDiscoveryAt: null,\n  unreadMessages: 0,\n  totalQueriesAnswered: 0,\n  lastContributionAt: null,\n  processedMessageIds: [],\n  v2Enabled: false,\n  p2pPeerCount: 0,\n  gossipSyncCount: 0,\n  crdtMergeCount: 0,\n  lastGossipSyncAt: null,\n  walletEnabled: false,\n  walletAddress: null,\n  walletChainId: 0,\n  walletBalanceUSDC: 0,\n  totalPaymentsMade: 0,\n  totalPaymentsReceived: 0,\n  microLedgerUnsettled: 0,\n  lastSettlementAt: null,\n  agentDid: null,\n  profileCreated: false,\n  profileDisplayName: 'holomesh-agent',\n  profileBio: '',\n  profileCustomTitle: '',\n  profileThemeColor: '#6366f1',\n  resourcePressure: 0,\n  suggestedLOD: 0,\n  hardLimitBreached: false,\n};\n// --- Team & Board ---\n\nexport type TeamRole = 'owner' | 'lead' | 'member' | 'guest';\n\nexport interface TeamMember {\n  agentId: string;\n  agentName: string;\n  role: TeamRole;\n  joinedAt: string;\n  /** Wallet address of the member (snapshot from RegisteredAgent at join time). */\n  walletAddress?: string;\n  /**\n   * Fleet member type. 'agent' for software/IDE seats, 'hardware' for GPU/WASM\n   * workers that auto-joined via job execution. Enables the dynamic \"usage = membership\" model.\n   */\n  type?: 'agent' | 'hardware';\n  /**\n   * True when the member's registration completed the x402 challenge-verified\n   * flow (EIP-712 proof-of-ownership on /register). False or undefined for\n   * legacy path / server-generated wallets.\n   */\n  x402Verified?: boolean;\n  /**\n   * Surface tag captured at join time, e.g. \"claude-code\", \"claude-cursor\",\n   * \"gemini-antigravity\", \"copilot-vscode\". Informational — the load-bearing\n   * attribution is agentId/walletAddress; this helps humans + audits spot\n   * which IDE seat is which when multiple seats share a wallet family.\n   */\n  surfaceTag?: string;\n}\n\nexport interface Team {\n  id: string;\n  name: string;\n  description: string;\n  type: 'bounty' | 'social' | 'research' | 'dev';\n  visibility: 'public' | 'private' | 'internal';\n  ownerId: string;\n  ownerName: string;\n  members: TeamMember[];\n  maxSlots: number;\n  inviteCode?: string;\n  waitlist: string[];\n  createdAt: string;\n\n  // Board data\n  taskBoard?: TeamTask[];\n  doneLog?: DoneLogEntry[];\n  retiredDoneLog?: RetiredDoneLogReceipt[];\n  suggestions?: TeamSuggestion[];\n\n  /** Local mirror of team-scoped knowledge (orchestrator GET may lag or omit workspace-scoped rows). */\n  knowledge?: MeshKnowledgeEntry[];\n\n  /** Latest locally-published GPU/Vast fleet snapshot for deployed Studio and agents. */\n  fleetSnapshot?: TeamFleetSnapshotRecord;\n\n  /**\n   * Founder one-tap approvals (N3 signed-write path). Records the low-stakes\n   * INTENT a founder tapped on the Console; a signing agent consumes\n   * status:'approved', materializes the full agi-action-manifest, executes with\n   * ITS own x402 envelope, and PATCHes the record to 'executed'. Stored directly\n   * on the team object so it persists/reloads through the same path as taskBoard\n   * (no side map needed — see state.ts persistTeamStore).\n   */\n  founderApprovals?: FounderApprovalRecord[];\n\n  // Bounty data (V7 Expansion)\n  bounties?: BountyManager;\n  submissions?: StoredBountySubmission[];\n  miniGames?: StoredBountyMiniGame[];\n\n  mode?: string;\n  /**\n   * When true, every member effectively carries owner permissions\n   * (used for the founder's working teams like HoloScript Core).\n   */\n  adminRoom?: boolean;\n  roomConfig?: {\n    objective?: string;\n    /** Per-slot role assignments set via holomesh_slot_assign MCP tool. */\n    slotRoles?: string[];\n    /**\n     * How agents should weight team messages vs tasks in session context.\n     * - task_first: handoffs/DMs/reviews only (default)\n     * - meeting_primary: meeting + text conversation surfaced beside tasks; larger message window\n     * - balanced: both conversation and inbox, moderate limits\n     */\n    communicationStyle?: 'task_first' | 'meeting_primary' | 'balanced';\n    /** Last mode change audit (GET /board; task_1777050706699_ixmi) */\n    modeProvenance?: {\n      source: 'api' | 'mcp_tool' | 'unknown';\n      changedAt: string;\n      changedByAgentId?: string;\n      changedByName?: string;\n      previousMode?: string;\n    };\n    /** Newest-first ring (max 10) of mode transitions */\n    modeHistory?: Array<{\n      mode: string;\n      at: string;\n      by: string;\n      byAgentId: string;\n      source: 'api' | 'mcp_tool';\n      reason?: string;\n      previousMode: string;\n    }>;\n    treasuryFeeBps?: number;\n    moltbookDaemon?: {\n      enabled: boolean;\n      minHours: number;\n      maxHours: number;\n      agentName: string;\n      updatedAt: string;\n    };\n  };\n  treasuryWallet?: string;\n  treasuryBalance?: number;\n}\n\nexport interface RetiredDoneLogReceipt {\n  taskId: string;\n  title?: string;\n  completedAt?: string;\n  rawSha256: string;\n  retiredAt: string;\n  retiredByAgentId: string;\n  retiredByName: string;\n  archiveManifestSha256: string;\n  archiveManifestGeneratedAt: string;\n  archiveSchemaVersion: string;\n  archiveCutoffIso: string;\n  archiveCounts: {\n    totalRows: number;\n    archiveEligibleRows: number;\n    hotRows: number;\n    missingTimestampRows: number;\n  };\n  archiveFiles: {\n    sqliteSha256: string;\n    allNdjsonSha256: string;\n    staleNdjsonSha256: string;\n  };\n}\n\n/**\n * An exact-four Joseph decision intent (N3 signed-write path). Routine work,\n * specialist review, platform controls, and prohibited replanning never enter\n * this queue. It mutates nothing privileged; a signing agent consumes it,\n * agent re-validates, materializes the agi-action-manifest, executes with its\n * own x402 signature, and PATCHes status → 'executed' + a resultRef.\n */\nexport interface FounderApprovalRecord {\n  id: string;\n  /** Source board task this intent acts on. */\n  taskId: string;\n  /** Human-readable intent (the task title / what tapping does). */\n  intent: string;\n  /** Presentation classification; authority is carried separately below. */\n  actionType: 'code' | 'spatial' | 'service_rental' | 'mobility_coordination';\n  authorityRoute: 'joseph-exact-four';\n  josephReviewClass: 'spend-or-custody' | 'physical-presence' | 'public-identity' | 'governance';\n  /** Identity that tapped approve (from Bearer auth, never client-supplied). */\n  approvedByAgentId: string;\n  approvedByName: string;\n  /**\n   * approved   → recorded, awaiting a signing agent\n   * executing  → a signing agent claimed it and is materializing/signing\n   * executed   → the signed mutation landed; resultRef points to the receipt\n   * failed     → execution failed; resultRef carries the reason\n   */\n  status: 'approved' | 'executing' | 'executed' | 'failed';\n  createdAt: string;\n  /** Set by the signing agent when it claims the record. */\n  claimedByAgentId?: string;\n  claimedByName?: string;\n  executedAt?: string;\n  /** Receipt hash / inbox feed id / failure reason, depending on status. */\n  resultRef?: string;\n}\n\nexport type TeamFleetSnapshotHealthStatus = 'missing' | 'ok' | 'degraded' | 'stale' | 'down';\n\nexport interface TeamFleetSnapshotSummary {\n  captured_at?: string;\n  running_count?: number;\n  declared_count?: number;\n  /** Unmanaged capacity that should affect health; preferred over raw orphan_count. */\n  orphaned_capacity_count?: number;\n  /** Legacy/raw orphan inventory, including intentionally managed transient capacity. */\n  orphan_count?: number;\n  no_instance_count?: number;\n  total_cost_so_far_usd?: number;\n  total_dph_usd?: number;\n  projected_24h_cost_usd?: number;\n  gpu_tier_distribution?: Record<string, number>;\n  [key: string]: unknown;\n}\n\nexport interface TeamFleetResourceFlowVisibilityV1 {\n  complete: boolean;\n  gap_count: number;\n  gaps: string[];\n  duplicate_endpoint_bindings: unknown[];\n  invalid_manifest_count: number;\n  invalid_manifests: unknown[];\n  evidence_sources: string[];\n  [key: string]: unknown;\n}\n\nexport interface TeamFleetResourceFlowUtilizedV1 {\n  instance_count: number;\n  active_compute_count: number;\n  retained_storage_count: number;\n  manifest_bound_instance_count: number;\n  unbound_instance_count: number;\n  capacity_binding_count: number;\n  effective_dph_usd: number;\n  projected_24h_usd: number;\n  resources: unknown[];\n  capacity_bindings: unknown[];\n  [key: string]: unknown;\n}\n\nexport interface TeamFleetResourceFlowProducedV1 {\n  output_aware_lane_count: number;\n  active_manifest_count: number;\n  output_contract_count: number;\n  bound_manifest_count: number;\n  unbound_manifest_count: number;\n  evidence_backed_output_count: number;\n  verified_product_count: number;\n  verified_artifact_count: number;\n  verified_receipt_count: number;\n  verified_current_binding_count: number;\n  declared_only_output_count: number;\n  unverified_evidence_output_count: number;\n  claimed_or_unverified_output_count: number;\n  productive_count: number;\n  work_in_progress_count: number;\n  inference_output_tokens: number;\n  active_manifests: unknown[];\n  output_contracts: unknown[];\n  declared_output_locations: unknown[];\n  claimed_or_declared_outputs: unknown[];\n  artifacts: unknown[];\n  receipts: unknown[];\n  product_verification_policy: string;\n  [key: string]: unknown;\n}\n\nexport interface TeamFleetResourceFlowStoredV1 {\n  instance_volume_count: number;\n  total_capacity_gb: number;\n  total_used_gb: number;\n  projected_storage_24h_usd: number;\n  volumes: unknown[];\n  locally_present_output_location_count: number;\n  verified_artifact_location_count: number;\n  verified_receipt_location_count: number;\n  evidence_backed_output_location_count: number;\n  artifact_locations: unknown[];\n  receipt_locations: unknown[];\n  [key: string]: unknown;\n}\n\nexport interface TeamFleetResourceFlowConsumedV1 {\n  consumer_count: number;\n  manifest_attributed_count: number;\n  current_physical_consumer_count: number;\n  declared_or_historical_manifest_consumer_count: number;\n  bound_manifest_consumer_count: number;\n  unbound_manifest_consumer_count: number;\n  runtime_requests: number;\n  compute_bearing_requests: number;\n  runtime_metrics_age_ms: number | null;\n  runtime_providers: unknown[];\n  runtime_endpoints: unknown[];\n  consumers: unknown[];\n  current_physical_consumers: unknown[];\n  declared_or_historical_manifest_consumers: unknown[];\n  [key: string]: unknown;\n}\n\nexport interface TeamFleetSpendAccountingV1 {\n  schema_version: 'holomesh.vast-spend-accounting/v1';\n  provider: 'vast.ai';\n  status: 'ok' | 'captured-provenance-gap' | 'missing' | 'invalid';\n  observed_at_utc: string | null;\n  freshness_status: 'fresh' | 'stale' | 'missing' | 'invalid';\n  age_ms: number | null;\n  max_age_ms: number;\n  rail: 'purchased_compute';\n  reset_window: 'utc_day';\n  vendor_total_usd: number | null;\n  observed_purchased_compute_usd: number | null;\n  monetary_complete: boolean;\n  monetary_gap_reasons: string[];\n  provenance_complete: boolean;\n  provenance_gap_reasons: string[];\n  intentional_gap_captured: boolean;\n  cap_applicable: boolean;\n  cap_usd: number | null;\n  observed_admission_verdict:\n    | 'under-cap'\n    | 'cap-exceeded'\n    | 'not-applicable'\n    | 'blocked-monetary-coverage-incomplete'\n    | null;\n  trusted_admission_verdict: 'under-cap' | 'cap-exceeded' | null;\n  /** Signed: a negative value is the measured amount over the daily cap. */\n  trusted_headroom_usd: number | null;\n  no_paid_actions: boolean;\n}\n\n/** Versioned Vast utilized/produced/stored/consumed projection published by the local collector. */\nexport interface TeamFleetResourceFlowV1 {\n  schema_version: 'holomesh.vast-resource-flow/v1';\n  provider: 'vast.ai';\n  captured_at: string;\n  spend_accounting: TeamFleetSpendAccountingV1;\n  utilized: TeamFleetResourceFlowUtilizedV1;\n  produced: TeamFleetResourceFlowProducedV1;\n  stored: TeamFleetResourceFlowStoredV1;\n  consumed: TeamFleetResourceFlowConsumedV1;\n  visibility: TeamFleetResourceFlowVisibilityV1;\n  [key: string]: unknown;\n}\n\nexport interface TeamFleetSnapshotPayload {\n  schema_version?: string;\n  captured_at?: string;\n  error?: string;\n  warning?: string;\n  summary?: TeamFleetSnapshotSummary;\n  matched?: unknown[];\n  orphans?: unknown[];\n  resource_flow?: TeamFleetResourceFlowV1;\n  global_budget_usd_per_day?: number;\n  [key: string]: unknown;\n}\n\nexport interface TeamFleetSnapshotHealth {\n  status: TeamFleetSnapshotHealthStatus;\n  reasons: string[];\n  ageMs: number | null;\n  staleAfterMs: number;\n}\n\nexport interface TeamFleetSnapshotRecord {\n  source: string;\n  publishedAt: string;\n  publishedByAgentId: string;\n  publishedByName: string;\n  snapshot: TeamFleetSnapshotPayload;\n  health: TeamFleetSnapshotHealth;\n}\n\nexport interface TeamPresenceEntry {\n  agentId: string;\n  agentName: string;\n  ideType: string;\n  status: 'active' | 'idle' | 'busy' | 'offline';\n  lastHeartbeat: string;\n  /** Alias for lastHeartbeat — used by some route handlers for presence staleness checks. */\n  lastSeen?: string;\n  /**\n   * Coarse runtime surface for aliveness policy. `surface_tag` remains the\n   * attribution/seat label; this field is the device class such as \"mobile\".\n   */\n  surface?: string;\n  /** Per-row expiry hint so clients can render transient surfaces accurately. */\n  expiresAt?: string;\n  /** TTL used for this heartbeat row in milliseconds. */\n  ttlMs?: number;\n  /** Wallet address of the heartbeating agent (snapshot from RegisteredAgent). */\n  walletAddress?: string;\n  /** True when the agent's wallet ownership was verified via x402 challenge flow at register time. */\n  x402Verified?: boolean;\n  /**\n   * Surface tag declared on the heartbeat, e.g. \"claude-code\", \"cursor-claude\".\n   * Body field: `surface_tag`. Distinct from ideType: ideType is the IDE brand\n   * (\"vscode\"), surfaceTag is the specific agent surface running in it.\n   */\n  surfaceTag?: string;\n  /** Capability tags declared by the agent on heartbeat. Used for server-side required_tags enforcement on board task claims. */\n  capabilityTags?: string[];\n  /** Brain/principal/session/signing envelope captured from the heartbeat. */\n  identityEnvelope?: HoloMeshIdentityEnvelope;\n  /** Server-issued cloud-session lease associated with this heartbeat, when applicable. */\n  cloudSessionLeaseId?: string;\n  /** Provider/local session id captured from the identity envelope. */\n  sessionId?: string;\n  /** Normalized session origin, e.g. local, cloud, mobile. */\n  sessionOrigin?: string;\n  /** Expiry for the cloud lease. Distinct from short local presence expiry. */\n  sessionExpiresAt?: string;\n}\n\nexport interface HoloMeshCloudSessionLease {\n  leaseId: string;\n  teamId: string;\n  agentId: string;\n  agentName: string;\n  status: 'active' | 'ended' | 'expired';\n  sessionId: string;\n  origin: string;\n  surface?: string;\n  family?: string;\n  handle?: string;\n  createdAt: string;\n  lastHeartbeat: string;\n  expiresAt: string;\n  identityEnvelope?: HoloMeshIdentityEnvelope;\n}\n\nexport interface TeamMessage {\n  id: string;\n  teamId: string;\n  fromAgentId: string;\n  fromAgentName: string;\n  content: string;\n  messageType:\n    | 'text'\n    | 'meeting'\n    | 'dm'\n    | 'knowledge'\n    | 'handoff'\n    | 'review-request'\n    | 'task'\n    | 'hologram'\n    | 'mode_change'\n    /**\n     * Agent-to-agent negotiation event. Carries a `negotiation` payload\n     * with `{ negotiationId, action, state, payload }` shaped per\n     * `agent-negotiation.ts`. Used for quote / accept / execute / settle /\n     * dispute multi-turn flows beyond one-shot RPC. (task_1778114573371_xsp6)\n     */\n    | 'negotiation';\n  /**\n   * When messageType === 'negotiation', this carries the per-event\n   * record so the timeline and feed can render the cycle without a\n   * second fetch. Reference: agent-negotiation.ts NegotiationEvent.\n   */\n  negotiation?: {\n    negotiationId: string;\n    action: string;\n    state: string;\n    seq: number;\n    counterpartyAgentId: string;\n    payload?: Record<string, unknown>;\n  };\n  createdAt: string;\n  /** Agent IDs that have marked this team-room message read. */\n  readBy?: string[];\n  /** Last time any agent marked this message read. */\n  readAt?: string;\n  /** Agent IDs that hid this message from their active inbox. */\n  archivedBy?: string[];\n  /** Set when messageType is mode_change (GET /messages timeline). */\n  modeChange?: {\n    previousMode: string;\n    newMode: string;\n    source: string;\n    reason?: string;\n  };\n}\n\n/** Hologram publish in team activity feed. */\nexport interface TeamHologramFeedItem {\n  id: string;\n  teamId: string;\n  kind: 'hologram';\n  posterAgentId: string;\n  posterAgentName: string;\n  hash: string;\n  shareUrl: string;\n  createdAt: string;\n}\n\nexport interface TeamModeChangeFeedItem {\n  id: string;\n  teamId: string;\n  kind: 'mode_change';\n  fromMode: string;\n  toMode: string;\n  source: 'api' | 'mcp_tool';\n  actorAgentId: string;\n  actorAgentName: string;\n  createdAt: string;\n}\n\nexport interface TeamIntelligenceFeedItem {\n  id: string;\n  teamId: string;\n  kind: 'intelligence';\n  posterAgentId: string;\n  posterAgentName: string;\n  content: string;\n  scope?: 'team' | 'public';\n  createdAt: string;\n}\n\n/** Team activity feed (GET /team/:id/feed) — hologram publishes, mode transitions, and intelligence reports. */\nexport type TeamFeedItem = TeamHologramFeedItem | TeamModeChangeFeedItem | TeamIntelligenceFeedItem;\n\nexport const TEAM_ROLE_PERMISSIONS: Record<TeamRole, string[]> = {\n  owner: [\n    'board:write',\n    'board:read',\n    'members:manage',\n    'config:write',\n    'messages:write',\n    'messages:read',\n  ],\n  lead: ['board:write', 'board:read', 'members:invite', 'messages:write', 'messages:read'],\n  member: ['board:read', 'board:write', 'board:claim', 'messages:write', 'messages:read'],\n  guest: ['board:read', 'messages:read'],\n};\n\nexport const PRESENCE_TTL_MS = 120 * 1000; // 2 minutes\nexport const MOBILE_PRESENCE_TTL_MS = 30 * 1000; // phones background quickly; keep them transient\n\n// --- Agent Identity & Registry ---\n\nexport type HoloMeshBearerSurface = 'mobile' | 'desktop' | 'headless';\nexport type HoloMeshBearerCapability = 'read' | 'message' | 'claim' | 'sign';\n\n/**\n * Registry row for a HoloMesh bearer token.\n *\n * **Security posture:** `key` is a disposable credential (session-style). Treat\n * compromise or leakage as \"rotate or revoke,\" not catastrophe — durable identity\n * is `walletAddress` + `agentId`. Wallet never changes; key rotates via /admin/rotate-key.\n */\nexport interface KeyRecord {\n  /** Bearer token — disposable; rotate/revoke freely */\n  key: string;\n  /** Permanent wallet address — identity anchor */\n  walletAddress: string;\n  /** Permanent agent ID */\n  agentId: string;\n  /** Display name */\n  agentName: string;\n  /** Scope grants: 'mcp' | 'holomesh' | 'absorb' | '*' */\n  scopes: string[];\n  createdAt: string;\n  /** Previous key value (audit trail on rotation) */\n  rotatedFrom?: string;\n  /** Number of times this agent's key has been rotated */\n  rotationCount: number;\n  /** ISO timestamp of the most recent rotation, or null if never rotated */\n  lastRotatedAt: string | null;\n  /** Founder keys can provision agents, create teams, and access /admin routes */\n  isFounder: boolean;\n  /**\n   * Surface tag snapshotted at provision time — e.g. \"mobile\", \"claude-code\".\n   * Used for attribution and audit trails.\n   */\n  surfaceTag?: string;\n  /**\n   * Policy surface class. Unlike surfaceTag, this is normalized and used for\n   * capability decisions: mobile bearers are assistant surfaces, not seats.\n   */\n  surface?: HoloMeshBearerSurface;\n  /**\n   * Capability grants for bearer-scoped policy. Missing means legacy\n   * unrestricted key; present means routes must check the named capability.\n   */\n  capabilities?: HoloMeshBearerCapability[];\n  /**\n   * ISO timestamp after which this key is considered expired.\n   * Checked by resolveRequestingAgent; expired keys reject auth.\n   */\n  expiresAt?: string;\n}\n\nexport interface RegisteredAgent {\n  id: string;\n  apiKey: string;\n  walletAddress?: string;\n  name: string;\n  traits: string[];\n  reputation: number;\n  profile?: Record<string, unknown>; // Replaced any\n  createdAt: string;\n  /** Copied from KeyRecord on provisioning — founder agents bypass all creation gates */\n  isFounder?: boolean;\n  /**\n   * True when the agent registered via the x402 challenge-verified flow\n   * (client-owned wallet, EIP-712 signature over a server-issued nonce).\n   * False / undefined for legacy path where the server generated the wallet.\n   * SEC-T-Zero fix 2026-04-22 installed the flow; this flag surfaces its result.\n   */\n  x402Verified?: boolean;\n  /**\n   * Surface tag snapshotted once at /register time from `body.surface_tag`.\n   * Downstream heartbeats and joins use this value; they cannot override it\n   * by re-declaring the field on /presence or /join. Defense-in-depth against\n   * an agent claiming another surface's tag post-enrollment.\n   */\n  surfaceTag?: string;\n  /** Policy surface class copied from the bearer record when available. */\n  surface?: HoloMeshBearerSurface;\n  /** Bearer capability grants copied from the key record when available. */\n  capabilities?: HoloMeshBearerCapability[];\n  /** Raw scope grants copied from the key record when available. */\n  scopes?: string[];\n  /** IDE/surface type of the agent (e.g. 'hardware', 'cloud', 'mobile'). */\n  ideType?: string;\n}\n\n// --- Social Metadata ---\n\nexport interface StoredComment {\n  id: string;\n  entryId: string;\n  parentId?: string;\n  authorId: string;\n  authorName: string;\n  content: string;\n  voteCount: number;\n  createdAt: string;\n}\n\nexport interface StoredVote {\n  targetId: string;\n  userId: string;\n  value: 1 | -1;\n}\n\nexport interface KnowledgeTransaction {\n  id: string;\n  buyerWallet: string;\n  buyerName: string;\n  sellerWallet: string;\n  sellerName: string;\n  entryId: string;\n  entryDomain: string;\n  priceCents: number;\n  timestamp: string;\n}\n\n// --- Bounty Details ---\n\nexport interface StoredBountySubmission {\n  id: string;\n  bountyId: string;\n  teamId?: string;\n  agentId?: string; // Legacy\n  agentName?: string; // Legacy\n  submitterId: string;\n  submitterName: string;\n  proof?: string;\n  status: 'pending' | 'submitted' | 'accepted' | 'rejected' | 'paid';\n  submittedAt: string;\n  reviewedAt?: string;\n  resolvedAt?: string;\n  rewardPaid?: boolean;\n  solution?: string;\n  payoutResult?: Record<string, unknown>; // Replaced any\n}\n\nexport interface StoredBountyMiniGame {\n  id: string;\n  teamId: string;\n  roomId?: string; // New: Dedicated SSE room for the mini-game\n  bountyId?: string; // Legacy\n  bountyIds?: string[]; // Multiple bounties\n  title?: string;\n  description?: string;\n  createdBy?: string;\n  status?: string;\n  type?: 'terminal_puzzle' | 'gauntlet' | 'sim_stress';\n  state?: unknown;\n  createdAt: string;\n}\n\nexport type BountyGovernanceVoteValue = 'approve' | 'reject';\n\nexport interface StoredBountyGovernanceVote {\n  agentId: string;\n  agentName: string;\n  /** Token-weighted vote (defaults to 1 when token balance isn't provided). */\n  weight: number;\n  value: BountyGovernanceVoteValue;\n  createdAt: string;\n}\n\nexport interface StoredBountyGovernanceProposal {\n  id: string;\n  bountyId: string;\n  teamId: string;\n  title?: string;\n  description?: string;\n  createdBy: string;\n  status: 'open' | 'approved' | 'rejected' | 'executed';\n  /** Minimum total vote weight required before resolution. */\n  quorumWeight: number;\n  /** Fraction [0,1] of approve weight required for approval. */\n  approvalThreshold: number;\n  votes: StoredBountyGovernanceVote[];\n  createdAt: string;\n  resolvedAt?: string;\n}\n\n// --- StoryWeaver Details ---\n\nexport interface StoryWeaverBeat {\n  id: string;\n  kind: 'setup' | 'conflict' | 'twist' | 'resolution';\n  text: string;\n  createdAt: string;\n}\n\nexport interface StoryWeaverBranch {\n  id: string;\n  parentChapterId?: string;\n  label: string;\n  chapterText: string;\n  premium: boolean;\n  priceCents?: number;\n  unlockedBy?: string[];\n  beats: StoryWeaverBeat[];\n  createdAt: string;\n}\n\nexport interface StoryWeaverSession {\n  id: string;\n  title: string;\n  genre?: string;\n  ownerId: string;\n  ownerName: string;\n  synopsis?: string;\n  branches: StoryWeaverBranch[];\n  createdAt: string;\n  updatedAt: string;\n}\n\n// --- Self-Improving Worlds ---\n\nexport interface SelfImprovingWorldPatch {\n  id: string;\n  traitPath: string;\n  action: 'add' | 'update' | 'remove';\n  reason: string;\n  proposedValue?: Record<string, unknown>;\n  confidence: number;\n}\n\nexport interface SelfImprovingWorldSession {\n  worldId: string;\n  revision: number;\n  lastGoal?: string;\n  patches: SelfImprovingWorldPatch[];\n  updatedAt: string;\n}\n","/**\n * HoloMesh Wallet-Based Authentication (V4)\n *\n * Uses the agent's InvisibleWallet as a cryptographic identity anchor.\n * DID format: did:pkh:eip155:{chainId}:{address} (CAIP-10 standard)\n *\n * Three use cases:\n * 1. Onboard/Login: Challenge-response with wallet signature (EIP-191)\n * 2. Gossip signing: Sign CRDT delta payloads for peer verification\n * 3. Identity: Derive persistent DID from wallet address\n *\n * All verification uses viem's verifyMessage() — recovers signer from\n * signature without needing the private key.\n *\n * @module holomesh/wallet-auth\n */\n\nimport * as crypto from 'crypto';\n\n// =============================================================================\n// DID DERIVATION\n// =============================================================================\n\nconst DID_PKH_PREFIX = 'did:pkh:eip155:';\n\n/**\n * Derive a CAIP-10 DID from an Ethereum wallet address and chain ID.\n * Format: did:pkh:eip155:{chainId}:{address}\n */\nexport function deriveAgentDid(address: string, chainId: number): string {\n  return `${DID_PKH_PREFIX}${chainId}:${address}`;\n}\n\n/**\n * Extract the Ethereum address from a did:pkh DID.\n * Returns null for non-wallet DIDs or malformed addresses.\n */\nexport function extractAddressFromDid(did: string): string | null {\n  if (!did.startsWith(DID_PKH_PREFIX)) return null;\n  const parts = did.slice(DID_PKH_PREFIX.length).split(':');\n  if (parts.length !== 2) return null;\n  const address = parts[1];\n  if (!address || !address.startsWith('0x') || address.length !== 42) return null;\n  return address;\n}\n\n/**\n * Check if a DID is wallet-derived (did:pkh format).\n */\nexport function isWalletDid(did: string): boolean {\n  return did.startsWith(DID_PKH_PREFIX);\n}\n\n// =============================================================================\n// CHALLENGE-RESPONSE AUTH\n// =============================================================================\n\nconst CHALLENGE_EXPIRY_MS = 5 * 60 * 1000; // 5 minutes\n\n/**\n * Create a fresh authentication challenge for wallet-based login.\n */\nexport function createAuthChallenge(): {\n  challenge: string;\n  nonce: string;\n  expiresAt: number;\n} {\n  return {\n    challenge: crypto.randomBytes(32).toString('hex'),\n    nonce: crypto.randomBytes(16).toString('base64url'),\n    expiresAt: Date.now() + CHALLENGE_EXPIRY_MS,\n  };\n}\n\n/**\n * Build the canonical message for auth signing.\n * Deterministic format ensures both signer and verifier agree on message content.\n */\nexport function buildAuthMessage(challenge: string, nonce: string): string {\n  return `HoloMesh Auth\\nChallenge: ${challenge}\\nNonce: ${nonce}`;\n}\n\n/**\n * Sign an auth challenge using the agent's wallet.\n * Uses EIP-191 personal message signing via viem WalletClient.\n */\nexport async function signAuthChallenge(\n  walletClient: { signMessage: (args: { message: string }) => Promise<string> },\n  challenge: string,\n  nonce: string\n): Promise<string> {\n  const message = buildAuthMessage(challenge, nonce);\n  return walletClient.signMessage({ message });\n}\n\n/**\n * Verify an auth signature matches the claimed address.\n * Uses viem's verifyMessage (EIP-191 recovery) — dynamic import for tree-shaking.\n */\nexport async function verifyAuthSignature(\n  address: string,\n  challenge: string,\n  nonce: string,\n  signature: string\n): Promise<boolean> {\n  try {\n    const { verifyMessage } = await import('viem');\n    return await verifyMessage({\n      address: address as `0x${string}`,\n      message: buildAuthMessage(challenge, nonce),\n      signature: signature as `0x${string}`,\n    });\n  } catch {\n    return false;\n  }\n}\n\n// =============================================================================\n// GOSSIP MESSAGE SIGNING\n// =============================================================================\n\n/**\n * Build the canonical message for gossip payload signing.\n */\nexport function buildGossipMessage(deltaBase64: string, timestamp: string): string {\n  return `HoloMesh Gossip\\nDelta: ${deltaBase64}\\nTimestamp: ${timestamp}`;\n}\n\n/**\n * Sign a gossip payload (CRDT delta) using the agent's wallet.\n */\nexport async function signGossipPayload(\n  walletClient: { signMessage: (args: { message: string }) => Promise<string> },\n  deltaBase64: string,\n  timestamp: string\n): Promise<string> {\n  const message = buildGossipMessage(deltaBase64, timestamp);\n  return walletClient.signMessage({ message });\n}\n\n/**\n * Verify a gossip signature matches the claimed sender address.\n */\nexport async function verifyGossipSignature(\n  address: string,\n  deltaBase64: string,\n  timestamp: string,\n  signature: string\n): Promise<boolean> {\n  try {\n    const { verifyMessage } = await import('viem');\n    return await verifyMessage({\n      address: address as `0x${string}`,\n      message: buildGossipMessage(deltaBase64, timestamp),\n      signature: signature as `0x${string}`,\n    });\n  } catch {\n    return false;\n  }\n}\n","/**\n * HoloMesh Discovery Layer (V2)\n *\n * Replaces Moltbook central REST endpoints with decentralized Agent-to-Agent (A2A) Gossip.\n * V2 adds persistent peer store, health tracking, orchestrator bootstrap, peer gossip\n * propagation, and CRDT delta exchange via HTTP POST.\n */\nimport { AgentCard } from '../a2a.js';\nimport { HoloMeshWorldState } from './crdt-sync.js';\nimport type { HoloMeshOrchestratorClient } from './orchestrator-client.js';\nimport type {\n  PeerStoreEntry,\n  GossipDeltaRequest,\n  GossipDeltaResponse,\n  GossipHealthMetadata,\n} from './types.js';\nimport { resolveReputationTier, getTierWeight } from './types.js';\nimport { signGossipPayload, verifyGossipSignature } from './wallet-auth.js';\nimport * as fs from 'fs';\n\nconst STALE_THRESHOLD_MS = 5 * 60 * 1000; // 5 minutes\nconst MAX_FAILURE_COUNT = 3;\nconst MAX_PEERS_TO_SHARE = 5;\nconst MAX_GOSSIP_TARGETS = 3;\nconst HEAP_BACKPRESSURE_MIN_BYTES = 512 * 1024 * 1024;\n\nconst ENDPOINT_SUFFIXES = [\n  '/.well-known/agent-card.json',\n  '/.well-known/agent-card',\n  '/.well-known/agent.json',\n  '/.well-known/crdt-gossip',\n  '/.well-known/crdt-state',\n  '/mcp',\n  '/a2a',\n];\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n  return !!value && typeof value === 'object' && !Array.isArray(value);\n}\n\nfunction firstString(...values: unknown[]): string | null {\n  for (const value of values) {\n    if (typeof value === 'string' && value.trim()) return value.trim();\n  }\n  return null;\n}\n\nfunction stringList(...values: unknown[]): string[] {\n  return values\n    .flatMap((value) => (Array.isArray(value) ? value : [value]))\n    .filter((value): value is string => typeof value === 'string' && value.trim().length > 0)\n    .map((value) => value.trim().toLowerCase());\n}\n\nfunction isCloudFamilyCrdtPeer(peer: Record<string, unknown>): boolean {\n  const metadata = isRecord(peer.metadata) ? peer.metadata : {};\n  const markers = stringList(\n    peer.role,\n    peer.type,\n    peer.family,\n    peer.surface,\n    peer.capabilities,\n    peer.traits,\n    metadata.type,\n    metadata.family,\n    metadata.surface,\n    metadata.capabilities,\n    metadata.traits\n  );\n  return markers.some(\n    (marker) =>\n      marker === '@crdt-gossip' ||\n      marker === '@p2p' ||\n      marker === '@cloud-family' ||\n      marker.includes('crdt') ||\n      marker.includes('cloud-family')\n  );\n}\n\nfunction isLoopbackEndpoint(url: string): boolean {\n  try {\n    const { hostname } = new URL(url);\n    return hostname === 'localhost' || hostname === '127.0.0.1' || hostname === '::1';\n  } catch {\n    return true;\n  }\n}\n\n/**\n * Normalize the mixed endpoint shapes emitted by cloud, local, A2A, and MCP\n * surfaces into the base URL that hosts /.well-known/crdt-gossip.\n */\nexport function normalizePeerEndpointUrl(value: unknown): string | null {\n  const raw = firstString(value);\n  if (!raw) return null;\n\n  try {\n    const parsed = new URL(raw);\n    if (!['http:', 'https:'].includes(parsed.protocol)) return null;\n\n    let pathname = parsed.pathname.replace(/\\/+$/, '');\n    for (const suffix of ENDPOINT_SUFFIXES) {\n      if (pathname === suffix || pathname.endsWith(suffix)) {\n        pathname = pathname.slice(0, -suffix.length);\n        break;\n      }\n    }\n\n    parsed.pathname = pathname.replace(/\\/+$/, '') || '/';\n    parsed.search = '';\n    parsed.hash = '';\n    return parsed.toString().replace(/\\/$/, '');\n  } catch {\n    return null;\n  }\n}\n\nexport function resolvePeerEndpoint(peer: Record<string, unknown>): string | null {\n  const metadata = isRecord(peer.metadata) ? peer.metadata : {};\n  return normalizePeerEndpointUrl(\n    firstString(\n      peer.mcpEndpoint,\n      peer.mcpBaseUrl,\n      peer.mcp_base_url,\n      peer.mcp_endpoint,\n      peer.crdtEndpoint,\n      peer.crdt_endpoint,\n      metadata.mcpEndpoint,\n      metadata.mcpBaseUrl,\n      metadata.mcp_base_url,\n      metadata.mcp_endpoint,\n      metadata.crdtEndpoint,\n      metadata.crdt_endpoint,\n      peer.endpoint,\n      metadata.endpoint,\n      peer.url,\n      metadata.url,\n      metadata.publicUrl,\n      metadata.public_url\n    )\n  );\n}\n\n// V1 backwards compat export\nexport interface SpatialGossipNode {\n  did: string;\n  mcp_base_url: string;\n  crdt_vector_clock: number;\n  last_seen: string;\n}\n\nexport interface HoloMeshDiscoveryOptions {\n  storePath?: string;\n}\n\nexport class HoloMeshDiscovery {\n  private peers: Map<string, PeerStoreEntry> = new Map();\n  private storePath: string | null;\n  /** V6: Track when this discovery instance was created (for uptime calculation) */\n  private readonly startedAt: number = Date.now();\n  /** V6: Track gossip failures this session */\n  private sessionFailureCount = 0;\n  /** V6: Track contributions this session */\n  private sessionContributionCount = 0;\n  /** V6: Received health from peers (keyed by DID) */\n  private peerHealthCache: Map<string, GossipHealthMetadata> = new Map();\n\n  constructor(\n    public localAgentDid: string,\n    public localMcpUrl: string,\n    private worldState?: HoloMeshWorldState,\n    options?: HoloMeshDiscoveryOptions\n  ) {\n    this.storePath = options?.storePath || null;\n    if (this.storePath) this.loadPeerStore();\n  }\n\n  // ── V1 Preserved Methods ─────────────────────────────────────────────────\n\n  /**\n   * P.SGM.01: Discover peers by fetching their A2A agent-card.json and exchanging CRDT vector clocks.\n   */\n  public async discoverPeer(peerUrl: string): Promise<boolean> {\n    try {\n      const response = await fetch(`${peerUrl}/.well-known/agent-card.json`);\n      if (!response.ok) return false;\n\n      const card: AgentCard = await response.json();\n\n      // Attempt handshake by asserting Proof-of-Play capability\n      const isSpatial = await this.verifyProofOfPlayCapability(peerUrl);\n      if (!isSpatial) {\n        console.warn(\n          `[HoloMesh] Peer ${card.id} failed Proof-of-Play constraint. Dropping connection.`\n        );\n        return false;\n      }\n\n      // Automatically sync CRDT state from the remote peer's gossip payload\n      if (this.worldState) {\n        try {\n          const crdtResponse = await fetch(`${peerUrl}/.well-known/crdt-state`);\n          if (crdtResponse.ok) {\n            const arrayBuffer = await crdtResponse.arrayBuffer();\n            const stateUpdate = new Uint8Array(arrayBuffer);\n            this.worldState.mergeNeighborState(stateUpdate);\n          }\n        } catch {\n          // Peer hasn't exposed CRDT state yet — non-fatal\n        }\n      }\n\n      // Store as PeerStoreEntry (V2 format)\n      const existing = this.peers.get(card.id);\n      this.peers.set(card.id, {\n        did: card.id,\n        mcpBaseUrl: peerUrl,\n        name: card.name || card.id,\n        traits: [],\n        reputation: 0,\n        lastSeen: new Date().toISOString(),\n        lastSyncAt: existing?.lastSyncAt || null,\n        lastKnownFrontiers: existing?.lastKnownFrontiers || null,\n        source: existing?.source || 'direct',\n        failureCount: 0,\n      });\n\n      this.savePeerStore();\n      return true;\n    } catch (e) {\n      console.error(`[HoloMesh] Failed to discover peer ${peerUrl}:`, e);\n      return false;\n    }\n  }\n\n  /**\n   * P.POP.01: Proof-of-Play Verification\n   * Replaces Moltbook Math Challenges with 90fps compute capability test.\n   */\n  private async verifyProofOfPlayCapability(peerUrl: string): Promise<boolean> {\n    try {\n      const [ax, ay, az, bx, by, bz] = Array.from({ length: 6 }, () => Math.random() * 2 - 1);\n      const expected = ax * bx + ay * by + az * bz;\n\n      const start = performance.now();\n      const response = await fetch(`${peerUrl}/.well-known/pop-challenge`, {\n        method: 'POST',\n        headers: { 'Content-Type': 'application/json; charset=utf-8' },\n        body: JSON.stringify({ type: 'dot', inputs: [ax, ay, az, bx, by, bz] }),\n      });\n\n      if (!response.ok) {\n        // Grace period: dev mode if endpoint not implemented\n        return true;\n      }\n\n      const result = await response.json();\n      const duration = performance.now() - start;\n\n      const passed = Math.abs(result.value - expected) < 0.001 && duration < 100;\n      if (!passed) {\n        console.warn(\n          `[HoloMesh] PoP Failed! Deviation: ${Math.abs(result.value - expected)}, RTT: ${duration}ms`\n        );\n      }\n      return passed;\n    } catch {\n      // Fallback to true during bring-up\n      return true;\n    }\n  }\n\n  /** V1 compat: get known peers as SpatialGossipNode[] */\n  public getKnownPeers(): SpatialGossipNode[] {\n    return Array.from(this.peers.values()).map((p) => ({\n      did: p.did,\n      mcp_base_url: p.mcpBaseUrl,\n      crdt_vector_clock: new Date(p.lastSeen).getTime(),\n      last_seen: p.lastSeen,\n    }));\n  }\n\n  // ── V2: Bootstrap from Orchestrator ──────────────────────────────────────\n\n  /** Seed peer list from V1 hub (orchestrator as bootstrap) */\n  public async bootstrapFromOrchestrator(client: HoloMeshOrchestratorClient): Promise<number> {\n    try {\n      const peers = await client.discoverPeers();\n      if (!peers || !Array.isArray(peers)) return 0;\n\n      let added = 0;\n      for (const peer of peers) {\n        const rawPeer = peer as unknown as Record<string, unknown>;\n        const did = firstString(rawPeer.did, rawPeer.id);\n        const url =\n          resolvePeerEndpoint(rawPeer) ||\n          (isCloudFamilyCrdtPeer(rawPeer) ? normalizePeerEndpointUrl(this.localMcpUrl) : null);\n        if (!did || !url || did === this.localAgentDid) continue;\n        if (this.peers.has(did)) continue;\n\n        this.peers.set(did, {\n          did,\n          mcpBaseUrl: url,\n          name: peer.name || did,\n          traits: peer.traits || [],\n          reputation: peer.reputation || 0,\n          lastSeen: new Date().toISOString(),\n          lastSyncAt: null,\n          lastKnownFrontiers: null,\n          source: 'orchestrator',\n          failureCount: 0,\n        });\n        added++;\n      }\n\n      if (added === 0 && peers.length === 0) {\n        added += this.seedCloudIngressPeer();\n      }\n\n      if (added > 0) this.savePeerStore();\n      return added;\n    } catch {\n      return 0;\n    }\n  }\n\n  // ── V2: Health Tracking ──────────────────────────────────────────────────\n\n  private seedCloudIngressPeer(): number {\n    const url = normalizePeerEndpointUrl(this.localMcpUrl);\n    if (!url || isLoopbackEndpoint(url)) return 0;\n\n    const host = new URL(url).hostname.toLowerCase();\n    const did = `did:holomesh:cloud-ingress:${host}`;\n    if (did === this.localAgentDid || this.peers.has(did)) return 0;\n\n    this.peers.set(did, {\n      did,\n      mcpBaseUrl: url,\n      name: `Cloud CRDT ingress (${host})`,\n      traits: ['@crdt-gossip', '@cloud-family', '@p2p'],\n      reputation: 0,\n      lastSeen: new Date().toISOString(),\n      lastSyncAt: null,\n      lastKnownFrontiers: null,\n      source: 'orchestrator',\n      failureCount: 0,\n    });\n    return 1;\n  }\n\n  /** Remove peers not seen in >5 minutes or with too many failures */\n  public pruneStale(): string[] {\n    const now = Date.now();\n    const removed: string[] = [];\n    for (const [did, peer] of this.peers) {\n      const lastSeen = new Date(peer.lastSeen).getTime();\n      if (now - lastSeen > STALE_THRESHOLD_MS || peer.failureCount >= MAX_FAILURE_COUNT) {\n        this.peers.delete(did);\n        this.peerHealthCache.delete(did); // FW-0.6: Hardened unbounded cache growth\n        removed.push(did);\n      }\n    }\n\n    // Also prune health cache for any peers that were already removed from this.peers\n    for (const did of this.peerHealthCache.keys()) {\n      if (!this.peers.has(did)) {\n        this.peerHealthCache.delete(did);\n      }\n    }\n\n    if (removed.length > 0) this.savePeerStore();\n    return removed;\n  }\n\n  /** Mark a peer as recently seen */\n  public touchPeer(did: string): void {\n    const peer = this.peers.get(did);\n    if (peer) {\n      peer.lastSeen = new Date().toISOString();\n      peer.failureCount = 0;\n    }\n  }\n\n  /** Increment failure counter for a peer */\n  public recordFailure(did: string): void {\n    const peer = this.peers.get(did);\n    if (peer) peer.failureCount++;\n    this.sessionFailureCount++;\n  }\n\n  /** V6: Increment contribution count for health metadata */\n  public recordContribution(): void {\n    this.sessionContributionCount++;\n  }\n\n  // ── V2: Peer Gossip ─────────────────────────────────────────────────────\n\n  /** Get a list of healthy peers to share with other peers */\n  public getPeersToShare(excludeDid?: string): Array<{ did: string; url: string; name: string }> {\n    return Array.from(this.peers.values())\n      .filter((p) => p.did !== excludeDid && p.failureCount < 2)\n      .slice(0, MAX_PEERS_TO_SHARE)\n      .map((p) => ({ did: p.did, url: p.mcpBaseUrl, name: p.name }));\n  }\n\n  /** Absorb peers shared by another peer via gossip */\n  public absorbGossipedPeers(\n    peers: Array<{ did: string; url: string; name: string; walletAddress?: string }>,\n    _sourceDid: string\n  ): number {\n    let added = 0;\n    for (const p of peers) {\n      if (p.did === this.localAgentDid) continue;\n      if (this.peers.has(p.did)) {\n        // V4: Update wallet address if newly provided\n        if (p.walletAddress) {\n          const existing = this.peers.get(p.did)!;\n          existing.walletAddress = p.walletAddress;\n        }\n        continue;\n      }\n\n      this.peers.set(p.did, {\n        did: p.did,\n        mcpBaseUrl: p.url,\n        name: p.name,\n        traits: [],\n        reputation: 0,\n        lastSeen: new Date().toISOString(),\n        lastSyncAt: null,\n        lastKnownFrontiers: null,\n        source: 'gossip',\n        failureCount: 0,\n        walletAddress: p.walletAddress,\n      });\n      added++;\n    }\n    if (added > 0) this.savePeerStore();\n    return added;\n  }\n\n  // ── V2/V10: Weighted Peer Selection ──────────────────────────────────────\n\n  /**\n   * Pick peers for a gossip round using health-weighted selection.\n   *\n   * V10 Game Theory fix: Fisher-Yates ignored all 4 available signals\n   * (peerHealthCache, lastSyncAt, reputation, failureCount). Now uses\n   * weighted random selection based on peer quality scores.\n   *\n   * Weight formula:\n   *   base=1 + reputationBonus(0-3) + uptimeBonus(0-2) + freshnessBonus(0-2)\n   *   - failurePenalty(failureCount * 2)\n   *   Minimum weight: 0.1 (everyone gets a small chance)\n   */\n  public selectGossipTargets(count: number = MAX_GOSSIP_TARGETS): PeerStoreEntry[] {\n    const eligible = Array.from(this.peers.values()).filter(\n      (p) => p.failureCount < MAX_FAILURE_COUNT\n    );\n    if (eligible.length === 0) return [];\n    if (eligible.length <= count) return eligible;\n\n    // Compute weights for each peer\n    const weighted = eligible.map((peer) => ({\n      peer,\n      weight: this.computePeerWeight(peer),\n    }));\n\n    // Weighted random selection without replacement\n    const selected: PeerStoreEntry[] = [];\n    const pool = [...weighted];\n\n    for (let i = 0; i < count && pool.length > 0; i++) {\n      const totalWeight = pool.reduce((sum, w) => sum + w.weight, 0);\n      let r = Math.random() * totalWeight;\n      let idx = 0;\n      for (idx = 0; idx < pool.length - 1; idx++) {\n        r -= pool[idx].weight;\n        if (r <= 0) break;\n      }\n      selected.push(pool[idx].peer);\n      pool.splice(idx, 1);\n    }\n\n    return selected;\n  }\n\n  /**\n   * Compute gossip priority weight for a peer.\n   * Higher weight = more likely to be selected as gossip target.\n   * Uses all 4 signals that were previously ignored.\n   */\n  public computePeerWeight(peer: PeerStoreEntry): number {\n    let weight = 1.0; // Base weight\n\n    // Signal 1: Reputation (from peer store) — V11: tier-weighted gossip priority\n    if (peer.reputation > 0) {\n      const tier = resolveReputationTier(peer.reputation);\n      const tierW = getTierWeight(tier);\n      weight += Math.min(peer.reputation / 30, 3) * tierW.gossipPriority;\n    }\n\n    // Signal 2: Peer health cache (uptime, contributions)\n    const health = this.peerHealthCache.get(peer.did);\n    if (health) {\n      // Uptime bonus: longer-running peers are more reliable\n      if (health.uptimeSeconds > 300) weight += 1; // >5 min\n      if (health.uptimeSeconds > 3600) weight += 1; // >1 hour (total +2)\n\n      // Contribution bonus: peers that contribute are better gossip partners\n      if (health.contributionsThisSession > 0) weight += 1;\n\n      // High failure rate penalty from health report\n      weight -= Math.min(health.failureCount * 0.5, 2);\n    }\n\n    // Signal 3: Freshness (lastSyncAt)\n    if (peer.lastSyncAt) {\n      const sinceSyncMs = Date.now() - new Date(peer.lastSyncAt).getTime();\n      // Stale peers get priority (they have more new data to share)\n      if (sinceSyncMs > 2 * 60 * 1000) weight += 1; // >2 min since sync\n      if (sinceSyncMs > 5 * 60 * 1000) weight += 1; // >5 min (total +2)\n    } else {\n      // Never synced = high priority\n      weight += 2;\n    }\n\n    // Signal 4: Local failure count (direct observation)\n    weight -= peer.failureCount * 2;\n\n    // Floor: everyone gets at least a small chance\n    return Math.max(weight, 0.1);\n  }\n\n  // ── V2: CRDT Delta Exchange ──────────────────────────────────────────────\n\n  /** Perform a gossip sync round with a single peer */\n  public async gossipSync(\n    peer: PeerStoreEntry,\n    walletClient?: { signMessage: (args: { message: string }) => Promise<string> },\n    walletAddress?: string\n  ): Promise<boolean> {\n    if (!this.worldState) return false;\n\n    // V6: Memory Backpressure Check (borrowed from CompilerStateMonitor)\n    // Prevent OOM crashes during large CRDT state synchronizations\n    const memUsage = process.memoryUsage();\n    const ramUtilization = memUsage.heapUsed / memUsage.heapTotal;\n    if (memUsage.heapUsed > HEAP_BACKPRESSURE_MIN_BYTES && ramUtilization > 0.7) {\n      console.warn(\n        `[HoloMesh] Memory backpressure active (RAM at ${(ramUtilization * 100).toFixed(1)}%). Skipping gossip sync with ${peer.did}.`\n      );\n      return false;\n    }\n\n    try {\n      // Export delta (full if no known frontiers for this peer)\n      const delta = peer.lastKnownFrontiers\n        ? this.worldState.exportDelta(peer.lastKnownFrontiers)\n        : this.worldState.exportDelta();\n\n      // V6: Payload Size Backpressure\n      // Hard limit at 50MB to prevent Base64/JSON.stringify from blowing up V8 heap limits\n      if (delta.length > 50 * 1024 * 1024) {\n        console.warn(\n          `[HoloMesh] Gossip payload exceeds 50MB safety limit (${(delta.length / 1024 / 1024).toFixed(2)}MB). Skipping sync with ${peer.did} to prevent memory spike.`\n        );\n        // Note: we return false and record no failure, as this is local backpressure\n        return false;\n      }\n\n      const deltaBase64 = Buffer.from(delta).toString('base64');\n      const timestamp = new Date().toISOString();\n\n      const request: GossipDeltaRequest = {\n        senderDid: this.localAgentDid,\n        senderUrl: this.localMcpUrl,\n        senderName: 'holomesh-agent',\n        deltaBase64,\n        frontiers: this.worldState.getFrontiers(),\n        knownPeers: this.getPeersToShare(peer.did),\n        timestamp,\n        senderHealth: this.buildHealthMetadata(),\n      };\n\n      // V4: Sign gossip payload when wallet is available\n      if (walletClient && walletAddress) {\n        try {\n          request.signature = await signGossipPayload(walletClient, deltaBase64, timestamp);\n          request.senderWalletAddress = walletAddress;\n        } catch {\n          // Signing failed — send unsigned (V2 compat)\n        }\n      }\n\n      const response = await fetch(`${peer.mcpBaseUrl}/.well-known/crdt-gossip`, {\n        method: 'POST',\n        headers: { 'Content-Type': 'application/json; charset=utf-8' },\n        body: JSON.stringify(request),\n      });\n\n      if (!response.ok) {\n        this.recordFailure(peer.did);\n        return false;\n      }\n\n      const result: GossipDeltaResponse = await response.json();\n\n      // Import the peer's delta back — route through hot buffer for V9 consolidation\n      if (result.deltaBase64) {\n        const peerDelta = Buffer.from(result.deltaBase64, 'base64');\n        this.worldState.importDeltaToHotBuffer(new Uint8Array(peerDelta), peer.did);\n      }\n\n      // Update peer's known frontiers\n      if (result.frontiers) {\n        peer.lastKnownFrontiers = result.frontiers;\n      }\n\n      // Absorb gossiped peers\n      if (result.knownPeers) {\n        this.absorbGossipedPeers(result.knownPeers, peer.did);\n      }\n\n      // V6: Cache responder's health metadata\n      if (result.responderHealth) {\n        this.absorbPeerHealth(peer.did, result.responderHealth);\n      }\n\n      peer.lastSyncAt = new Date().toISOString();\n      this.touchPeer(peer.did);\n      this.savePeerStore();\n      return true;\n    } catch {\n      this.recordFailure(peer.did);\n      return false;\n    }\n  }\n\n  // ── V4: Gossip Signature Verification ───────────────────────────────────\n\n  /** Verify the wallet signature on an inbound gossip request. */\n  public async verifyGossipSender(\n    request: GossipDeltaRequest\n  ): Promise<'verified' | 'unsigned' | 'invalid'> {\n    if (!request.signature || !request.senderWalletAddress) return 'unsigned';\n    const valid = await verifyGossipSignature(\n      request.senderWalletAddress,\n      request.deltaBase64,\n      request.timestamp,\n      request.signature\n    );\n    return valid ? 'verified' : 'invalid';\n  }\n\n  // ── V6: Gossip Health Side-Channel ─────────────────────────────────────\n\n  /** Build health metadata to piggyback on outbound gossip */\n  public buildHealthMetadata(): GossipHealthMetadata {\n    return {\n      uptimeSeconds: Math.floor((Date.now() - this.startedAt) / 1000),\n      failureCount: this.sessionFailureCount,\n      peerCount: this.peers.size,\n      reputationScore: 0, // Caller can override via setLocalReputation\n      contributionsThisSession: this.sessionContributionCount,\n    };\n  }\n\n  /** Store health metadata received from a peer */\n  public absorbPeerHealth(peerDid: string, health: GossipHealthMetadata): void {\n    this.peerHealthCache.set(peerDid, health);\n  }\n\n  /** Get cached health metadata for a peer */\n  public getPeerHealth(peerDid: string): GossipHealthMetadata | undefined {\n    return this.peerHealthCache.get(peerDid);\n  }\n\n  /** Get health metadata for all peers that have reported */\n  public getAllPeerHealth(): Map<string, GossipHealthMetadata> {\n    return new Map(this.peerHealthCache);\n  }\n\n  // ── V2: Accessors ────────────────────────────────────────────────────────\n\n  public getPeerCount(): number {\n    return this.peers.size;\n  }\n\n  public getPeer(did: string): PeerStoreEntry | undefined {\n    return this.peers.get(did);\n  }\n\n  public getAllPeers(): PeerStoreEntry[] {\n    return Array.from(this.peers.values());\n  }\n\n  // ── V2: Persistence ──────────────────────────────────────────────────────\n\n  private savePeerStore(): void {\n    if (!this.storePath) return;\n    try {\n      const data = Array.from(this.peers.values());\n      fs.writeFileSync(this.storePath, JSON.stringify(data, null, 2), 'utf-8');\n    } catch {\n      // Non-fatal: peer store is convenience, not critical\n    }\n  }\n\n  private loadPeerStore(): void {\n    if (!this.storePath) return;\n    try {\n      if (!fs.existsSync(this.storePath)) return;\n      const raw = JSON.parse(fs.readFileSync(this.storePath, 'utf-8'));\n      if (Array.isArray(raw)) {\n        for (const entry of raw) {\n          if (entry.did) this.peers.set(entry.did, entry);\n        }\n      }\n    } catch {\n      // Corrupted store: start fresh\n    }\n  }\n}\n","/**\n * HoloMesh Orchestrator Client (V1)\n *\n * Wraps the MCP Orchestrator's existing endpoints for agent registration,\n * peer discovery, messaging, and knowledge exchange.\n *\n * V1 uses the orchestrator as a hub. V2 (discovery.ts + crdt-sync.ts)\n * adds direct P2P gossip via agent-card.json and Loro CRDT.\n */\n\nimport type { HoloMeshAgentCard, MeshConfig, MeshKnowledgeEntry, AgentReputation } from './types';\nimport { computeReputation, resolveReputationTier, DEFAULT_MESH_CONFIG } from './types';\nimport { normalizePeerEndpointUrl, resolvePeerEndpoint } from './discovery';\nimport * as crypto from 'crypto';\n\nlet clientInstance: HoloMeshOrchestratorClient | null = null;\n\n/**\n * Singleton accessor for the HoloMesh Orchestrator Client.\n */\nexport function getClient(): HoloMeshOrchestratorClient {\n  if (!clientInstance) {\n    const config: MeshConfig = {\n      ...DEFAULT_MESH_CONFIG,\n      apiKey: process.env.HOLOMESH_API_KEY || '',\n    } as any;\n    clientInstance = new HoloMeshOrchestratorClient(config);\n  }\n  return clientInstance;\n}\n\nexport interface WalletAuth {\n  did: string;\n  address: string;\n  signature: string;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n  return !!value && typeof value === 'object' && !Array.isArray(value);\n}\n\nfunction asString(value: unknown): string | undefined {\n  return typeof value === 'string' && value.trim() ? value.trim() : undefined;\n}\n\nfunction asStringArray(value: unknown): string[] {\n  if (!Array.isArray(value)) return [];\n  return value.filter((item): item is string => typeof item === 'string' && item.trim().length > 0);\n}\n\nfunction configuredMcpBaseUrl(): string {\n  const railwayUrl = process.env.RAILWAY_PUBLIC_DOMAIN\n    ? `https://${process.env.RAILWAY_PUBLIC_DOMAIN}`\n    : undefined;\n  return (\n    normalizePeerEndpointUrl(\n      process.env.MCP_LOCAL_URL ||\n        railwayUrl ||\n        process.env.HOLOSCRIPT_SERVER_URL ||\n        process.env.HOLOSCRIPT_MCP_URL ||\n        `http://localhost:${process.env.PORT || '3000'}`\n    ) || `http://localhost:${process.env.PORT || '3000'}`\n  );\n}\n\nexport class HoloMeshOrchestratorClient {\n  private readonly baseUrl: string;\n  private readonly headers: Record<string, string>;\n  private agentId: string | null = null;\n\n  constructor(private readonly config: MeshConfig) {\n    this.baseUrl = config.orchestratorUrl.replace(/\\/$/, '');\n    this.headers = {\n      'x-mcp-api-key': config.apiKey,\n      'Content-Type': 'application/json; charset=utf-8',\n    };\n  }\n\n  /** Set persistent wallet identity headers for all subsequent requests. */\n  setWalletAuth(did: string, address: string): void {\n    this.headers['x-agent-did'] = did;\n    this.headers['x-agent-wallet'] = address;\n  }\n\n  // ── Agent Lifecycle ──\n\n  /** Register this agent on the mesh via orchestrator. Returns agent ID. */\n  async registerAgent(traits: string[], walletAuth?: WalletAuth): Promise<string> {\n    const id =\n      walletAuth?.did || `holomesh-${this.config.agentName}-${crypto.randomUUID().slice(0, 8)}`;\n    const mcpEndpoint = configuredMcpBaseUrl();\n    const res = await this.post('/agents/register', {\n      id,\n      name: this.config.agentName,\n      role: 'holomesh-agent',\n      capabilities: traits,\n      workspace: this.config.workspace,\n      mcpEndpoint,\n      mcp_endpoint: mcpEndpoint,\n      metadata: {\n        type: 'holomesh',\n        version: walletAuth ? '4.0' : '1.0',\n        did: walletAuth?.did || id,\n        mcpEndpoint,\n        mcp_endpoint: mcpEndpoint,\n        mcpBaseUrl: mcpEndpoint,\n        mcp_base_url: mcpEndpoint,\n        agentCardUrl: `${mcpEndpoint}/.well-known/agent-card.json`,\n        crdtGossipUrl: `${mcpEndpoint}/.well-known/crdt-gossip`,\n      },\n      ...(walletAuth && {\n        walletAddress: walletAuth.address,\n        walletSignature: walletAuth.signature,\n      }),\n    });\n\n    this.agentId = res?.agent?.id || res?.id || id;\n    return this.agentId as string;\n  }\n\n  /** Send heartbeat to keep agent alive. */\n  async heartbeat(metadata?: Record<string, unknown>): Promise<boolean> {\n    if (!this.agentId) return false;\n    return this.postOk(`/agents/${this.agentId}/heartbeat`, {\n      status: 'active',\n      metadata: { type: 'holomesh', ...metadata },\n    });\n  }\n\n  // ── Peer Discovery ──\n\n  /** Discover peer agents. */\n  async discoverPeers(opts?: { traits?: string[] }): Promise<HoloMeshAgentCard[]> {\n    const data = await this.get('/agents');\n    const agents: any[] = Array.isArray(data) ? data : data?.agents || data?.data || [];\n\n    return agents\n      .filter((a: any) => a.id !== this.agentId)\n      .filter((a: any) => {\n        if (!opts?.traits?.length) return true;\n        const metadata = isRecord(a.metadata) ? a.metadata : {};\n        const caps: string[] = [\n          ...asStringArray(a.capabilities),\n          ...asStringArray(a.traits),\n          ...asStringArray(metadata.capabilities),\n          ...asStringArray(metadata.traits),\n        ];\n        return opts.traits!.some((t) => caps.includes(t));\n      })\n      .map((a: any): HoloMeshAgentCard => {\n        const metadata = isRecord(a.metadata) ? a.metadata : {};\n        const endpoint = resolvePeerEndpoint(a);\n        const did = asString(a.did) || asString(metadata.did) || a.id;\n        const traits = [\n          ...asStringArray(a.capabilities),\n          ...asStringArray(a.traits),\n          ...asStringArray(metadata.capabilities),\n          ...asStringArray(metadata.traits),\n        ];\n        return {\n          id: a.id,\n          name: a.name || a.id,\n          did,\n          mcpEndpoint: endpoint || undefined,\n          mcpBaseUrl: endpoint || undefined,\n          endpoint: asString(a.endpoint) || asString(metadata.endpoint),\n          url: asString(a.url) || asString(metadata.url),\n          metadata,\n          workspace: a.workspace || this.config.workspace,\n          traits,\n          reputation: a.metadata?.reputation || 0,\n          contributionCount: a.metadata?.contributionCount || 0,\n          queryCount: a.metadata?.queryCount || 0,\n          joinedAt: a.createdAt || a.created_at || new Date().toISOString(),\n        };\n      });\n  }\n\n  /** Get a specific agent's DNA/capabilities. */\n  async getAgentCard(agentId: string): Promise<HoloMeshAgentCard | null> {\n    const data = await this.get(`/agents/${agentId}/dna`);\n    if (!data) return null;\n    return {\n      id: agentId,\n      name: data.name || agentId,\n      workspace: data.workspace || this.config.workspace,\n      traits: data.traits || data.capabilities || [],\n      reputation: data.reputation || 0,\n      contributionCount: data.contributionCount || 0,\n      queryCount: data.queryCount || 0,\n      joinedAt: data.createdAt || new Date().toISOString(),\n    };\n  }\n\n  // ── Messaging ──\n\n  /** Send a message to a peer. */\n  async sendMessage(toAgentId: string, content: Record<string, unknown>): Promise<boolean> {\n    if (!this.agentId) return false;\n    return this.postOk('/agents/message', {\n      from: this.agentId,\n      to: toAgentId,\n      content: JSON.stringify(content),\n      metadata: { type: 'holomesh-gossip' },\n    });\n  }\n\n  /** Read inbox. */\n  async readInbox(): Promise<any[]> {\n    if (!this.agentId) return [];\n    const data = await this.get(`/agents/${this.agentId}/inbox`);\n    return Array.isArray(data) ? data : data?.messages || data?.inbox || [];\n  }\n\n  /** Subscribe to a topic. */\n  async subscribe(topic: string): Promise<boolean> {\n    if (!this.agentId) return false;\n    return this.postOk(`/agents/${this.agentId}/subscribe`, { topic });\n  }\n\n  /** Broadcast to all agents. */\n  async broadcast(content: Record<string, unknown>): Promise<boolean> {\n    if (!this.agentId) return false;\n    return this.postOk('/agents/broadcast', {\n      from: this.agentId,\n      content: JSON.stringify(content),\n      metadata: { type: 'holomesh-gossip' },\n    });\n  }\n\n  // ── Knowledge Exchange ──\n\n  /** Contribute knowledge entries to the orchestrator store. */\n  async contributeKnowledge(entries: MeshKnowledgeEntry[]): Promise<number> {\n    const orchEntries = entries.map((e) => ({\n      id: e.id,\n      workspace_id: e.workspaceId,\n      type: e.type,\n      content: e.content,\n      metadata: {\n        provenanceHash: e.provenanceHash,\n        authorId: e.authorId,\n        authorName: e.authorName,\n        price: e.price,\n        domain: e.domain,\n        confidence: e.confidence,\n        source: 'holomesh',\n      },\n      tags: e.tags,\n    }));\n\n    // Use the entry-level workspace if all entries share one (e.g. private vault),\n    // otherwise fall back to the global workspace configured for this orchestrator.\n    const entryWs = orchEntries[0]?.workspace_id;\n    const allSameWs = entryWs && orchEntries.every((e) => e.workspace_id === entryWs);\n    const syncWorkspace = allSameWs ? entryWs : this.config.workspace;\n\n    const res = await this.post('/knowledge/sync', {\n      workspace_id: syncWorkspace,\n      entries: orchEntries,\n    });\n\n    return res?.synced || res?.count || entries.length;\n  }\n\n  /** Query knowledge across workspaces (cross-agent discovery). */\n  async queryKnowledge(\n    search: string,\n    opts?: {\n      type?: string;\n      limit?: number;\n      workspaceId?: string;\n    }\n  ): Promise<MeshKnowledgeEntry[]> {\n    const body: Record<string, unknown> = {\n      search,\n      limit: opts?.limit || 10,\n    };\n    if (opts?.type) body.type = opts.type;\n    if (opts?.workspaceId) body.workspace_id = opts.workspaceId;\n    // Omit workspace_id for cross-workspace search\n\n    const data = await this.post('/knowledge/query', body);\n    const results: any[] = data?.results || data?.entries || [];\n\n    return results.map(\n      (r: any): MeshKnowledgeEntry => ({\n        id: r.id,\n        workspaceId: r.workspace_id || '',\n        type: r.type || 'wisdom',\n        content: r.content || '',\n        provenanceHash: r.metadata?.provenanceHash || this.hashContent(r.content || ''),\n        authorId: r.metadata?.authorId || '',\n        authorName: r.metadata?.authorName || 'unknown',\n        price: r.metadata?.price || 0,\n        queryCount: r.metadata?.queryCount || 0,\n        reuseCount: r.metadata?.reuseCount || 0,\n        domain: r.metadata?.domain,\n        tags: r.tags || [],\n        confidence: r.metadata?.confidence,\n        createdAt: r.created_at || new Date().toISOString(),\n      })\n    );\n  }\n\n  /** Get knowledge stats for reputation calculation. */\n  async getAgentReputation(agentId: string, agentName: string): Promise<AgentReputation> {\n    // Query contributions by this agent\n    const contributions = await this.queryKnowledge(agentName, { limit: 100 });\n    const ownContributions = contributions.filter((e) => e.authorId === agentId);\n\n    const totalContributions = ownContributions.length;\n    const queriesAnswered = ownContributions.reduce((sum, e) => sum + e.queryCount, 0);\n    const totalReuse = ownContributions.reduce((sum, e) => sum + e.reuseCount, 0);\n    const reuseRate = totalContributions > 0 ? totalReuse / totalContributions : 0;\n\n    const score = computeReputation(totalContributions, queriesAnswered, reuseRate);\n\n    return {\n      agentId,\n      agentName,\n      contributions: totalContributions,\n      queriesAnswered,\n      reuseRate,\n      score,\n      tier: resolveReputationTier(score),\n    };\n  }\n\n  // ── Helpers ──\n\n  getAgentId(): string | null {\n    return this.agentId;\n  }\n  setAgentId(id: string): void {\n    this.agentId = id;\n  }\n\n  private hashContent(content: string): string {\n    return crypto.createHash('sha256').update(content).digest('hex');\n  }\n\n  private async get(path: string): Promise<any> {\n    try {\n      const res = await fetch(`${this.baseUrl}${path}`, { headers: this.headers });\n      if (!res.ok) return null;\n      return await res.json();\n    } catch {\n      return null;\n    }\n  }\n\n  private async post(path: string, body: Record<string, unknown>): Promise<any> {\n    try {\n      const res = await fetch(`${this.baseUrl}${path}`, {\n        method: 'POST',\n        headers: this.headers,\n        body: JSON.stringify(body),\n      });\n      if (!res.ok) return null;\n      return await res.json();\n    } catch {\n      return null;\n    }\n  }\n\n  private async postOk(path: string, body: Record<string, unknown>): Promise<boolean> {\n    try {\n      const res = await fetch(`${this.baseUrl}${path}`, {\n        method: 'POST',\n        headers: this.headers,\n        body: JSON.stringify(body),\n      });\n      return res.ok;\n    } catch {\n      return false;\n    }\n  }\n}\n","/**\n * HoloMesh CRDT WorldState (V2 + V9 Neuroscience Memory Consolidation)\n *\n * Replaces Soul.md & Moltbook JSON Feeds with Loro CRDT Active Synchronization.\n * V2 adds multi-domain knowledge maps, reputation tracking, peer registry,\n * version-aware delta export, and persistent binary snapshots.\n *\n * V9 adds biological memory consolidation inspired by neuroscience:\n *   - Two-stage architecture: Hot buffer (hippocampus) → Cold store (neocortex)\n *   - Sleep cycles: Periodic consolidation with replay, merge, downscale, prune\n *   - Engram competition: Capacity limits + excitability-based eviction\n *   - Reconsolidation: Retrieval strengthens entries (read = write)\n *   - Active forgetting: Multi-mechanism pruning (contradiction, refresh, deprecation)\n *   - Domain-specific learning rates: Different consolidation parameters per domain\n *\n * Document structure (single LoroDoc, single version vector):\n *   holomesh (LoroMap)\n *     insights (LoroList)              — V1 backwards compat\n *     knowledge.security (LoroMap)     — domain-partitioned W/P/G (cold store)\n *     knowledge.rendering (LoroMap)\n *     knowledge.agents (LoroMap)\n *     knowledge.compilation (LoroMap)\n *     knowledge.general (LoroMap)\n *     hotbuffer (LoroList)             — V9 staging buffer (hippocampus)\n *     reputation (LoroMap)             — agentDid → JSON reputation data\n *     peers (LoroMap)                  — peerDid → JSON { url, name, lastSeen }\n */\nimport { LoroDoc, VersionVector } from 'loro-crdt';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport {\n  KNOWLEDGE_DOMAINS,\n  DOMAIN_CONSOLIDATION,\n  DOMAIN_HALF_LIVES,\n  resolveReputationTier,\n  getTierWeight,\n  type KnowledgeDomain,\n  type HotBufferEntry,\n  type ConsolidationResult,\n  type ReconsolidationEvent,\n  type ExcitabilityMetadata,\n  type DomainConsolidationConfig,\n  type MemoryReceipt,\n  computeExcitability,\n  hashString,\n} from './types';\n\n/** Reconsolidation window duration (5 minutes) */\nconst RECONSOLIDATION_WINDOW_MS = 5 * 60 * 1000;\n\n/** Default excitability metadata for new cold store entries */\nfunction defaultExcitability(): ExcitabilityMetadata {\n  return {\n    queryCount: 0,\n    citationCount: 0,\n    corroborationCount: 0,\n    excitability: 0,\n    lastRetrievedAt: 0,\n    lastReconsolidatedAt: 0,\n    consolidationSurvivals: 0,\n  };\n}\n\n/**\n * Detect injection patterns in knowledge entry content.\n * Defense-in-depth: catches code-like payloads that could exploit\n * downstream compilers (CWE-94) if they reach cold store and get\n * compiled via cross-agent composition.\n *\n * Patterns checked:\n *  - String termination + code: \"; <code>\" or '; <code>'\n *  - Script/import injection: <script>, import os, require(\n *  - Shell command patterns: exec(, system(, Process.Start(\n *  - Preprocessor directives: #include, #pragma\n *  - Null byte injection: \\0 in content\n */\nfunction containsInjectionPattern(content: string): boolean {\n  if (!content || typeof content !== 'string') return false;\n\n  // String termination followed by code-like tokens\n  if (/[\"'];?\\s*(import|require|exec|system|Process|eval|Function)\\s*[.(]/i.test(content))\n    return true;\n  // Script tags (HTML/XML injection)\n  if (/<script[\\s>]/i.test(content)) return true;\n  // Shell execution patterns\n  if (\n    /\\b(os\\.execute|os\\.system|Runtime\\.getRuntime|child_process|Process\\.Start)\\s*\\(/i.test(\n      content\n    )\n  )\n    return true;\n  // Preprocessor directives (shader/C++ injection)\n  if (/#\\s*(include|pragma|define)\\b/i.test(content)) return true;\n  // Null byte injection\n  if (content.includes('\\0')) return true;\n  // GDScript OS.execute\n  if (/OS\\.(execute|shell_open)\\s*\\(/i.test(content)) return true;\n\n  return false;\n}\n\nexport interface HoloMeshWorldStateOptions {\n  snapshotPath?: string;\n}\n\nexport class HoloMeshWorldState {\n  private doc: LoroDoc;\n  private snapshotPath: string | null;\n\n  // V9: In-memory hot buffer (not in CRDT — local staging only)\n  private hotBuffer: Map<KnowledgeDomain, HotBufferEntry[]> = new Map();\n  // V9: Track last consolidation time per domain\n  private lastConsolidation: Map<KnowledgeDomain, number> = new Map();\n  // V9: Active reconsolidation windows\n  private reconsolidationWindows: Map<string, ReconsolidationEvent> = new Map();\n\n  constructor(\n    public agentDid: string,\n    options?: HoloMeshWorldStateOptions\n  ) {\n    this.doc = new LoroDoc();\n    this.snapshotPath = options?.snapshotPath || null;\n\n    // Deterministic BigInt peer ID from agentDid\n    const hashPair = parseInt(agentDid.substring(0, 15), 36);\n    this.doc.setPeerId(BigInt(hashPair));\n\n    // Initialize all containers at doc level (auto-create on first access in Loro)\n    // Calling getMap/getList ensures the containers exist in the doc.\n    this.doc.getMap('holomesh');\n    this.doc.getList('insights');\n    this.doc.getText('feed');\n    for (const domain of KNOWLEDGE_DOMAINS) {\n      this.doc.getMap(`knowledge.${domain}`);\n    }\n    this.doc.getMap('reputation');\n    this.doc.getMap('peers');\n\n    // V9: Initialize hot buffer and consolidation timestamps per domain\n    for (const domain of KNOWLEDGE_DOMAINS) {\n      this.hotBuffer.set(domain, []);\n      this.lastConsolidation.set(domain, Date.now());\n    }\n\n    // Load snapshot from disk if available\n    if (this.snapshotPath) {\n      this.loadSnapshot();\n    }\n  }\n\n  // ── V1 Backwards-Compatible Methods ──────────────────────────────────────\n\n  /**\n   * Replaces Moltbook \"publishPost\" with a local CRDT list insertion.\n   * Immediately ready to gossip out via exportDelta().\n   */\n  public publishInsight(content: string, traitTags: string[], customCode?: string): Uint8Array {\n    const list = this.doc.getList('insights');\n    if (list) {\n      const formattedTraits = traitTags.map((t) => `@${t.replace(/^@/, '')}`).join('\\n  ');\n      const randomX = Math.floor(Math.random() * 100) - 50;\n\n      const repInfo = this.getReputation(this.agentDid);\n      const tier = repInfo?.tier ? parseInt(repInfo.tier) : 1;\n      const altitude = tier * 25; // High tier = high altitude\n\n      let physicsTrait = '';\n      if (tier >= 3) physicsTrait = '\\n  @attraction(radius: 30)';\n      else if (tier === 1) physicsTrait = '\\n  @gravity(1.5)';\n\n      const hsSource =\n        customCode ||\n        `state {\n  interactions: 0\n}\n\nInsight(\"${this.agentDid}_${Date.now()}\") {\n  @author(\"${this.agentDid}\")\n  @thought(${JSON.stringify(content)})\n  ${formattedTraits}\n  @position(${randomX}, ${altitude}, 0)${physicsTrait}\n  @velocity(0, 1, 0)\n  @lifetime(${tier >= 2 ? 604800 : 3600})\n  @behavior({\n    on_interact: \"interactions += 1; trigger_event('insight_read');\",\n    on_expire: \"spawn_particles('data_decay')\"\n  })\n  PhysicsBody(\"rigid\")\n}`;\n\n      // V1 Compat\n      list.push({\n        hs_source: hsSource.trim(),\n        author: this.agentDid,\n        timestamp: Date.now(),\n      });\n\n      // V3 Text Feed\n      this.appendToFeed(hsSource.trim(), this.agentDid);\n\n      this.doc.commit();\n    }\n    return this.doc.export({ mode: 'update' });\n  }\n\n  /**\n   * Replaces polling the Moltbook feed — directly merges state of\n   * neighbors into the persistent CRDT lattice.\n   */\n  public mergeNeighborState(stateUpdate: Uint8Array): void {\n    try {\n      this.doc.import(stateUpdate);\n    } catch (e) {\n      console.error('[HoloMesh] Failed to merge CRDT state:', e);\n    }\n  }\n\n  /** Returns a flattened view of all insights currently active in the Mesh as .hs source blocks. */\n  public queryFeedView(): Array<{ source: string; timestamp: number }> {\n    const list = this.doc.getList('insights');\n    if (!list) return [];\n    interface InsightEntry {\n      hs_source?: string;\n      author?: string;\n      text?: string;\n      timestamp: number;\n    }\n    const feed = list.toJSON() as InsightEntry[];\n    return feed\n      .sort((a, b) => b.timestamp - a.timestamp)\n      .map((item) => ({\n        source:\n          item.hs_source ||\n          `Insight(\"legacy\") {\\n  @author(\"${item.author}\")\\n  @thought(${JSON.stringify(item.text)})\\n}`,\n        timestamp: item.timestamp,\n      }));\n  }\n\n  /**\n   * Spatial query: parses @position(x, y, z) from insight hs_source blocks,\n   * then filters by Euclidean radius from a center point in the HoloMesh\n   * coordinate space. If no center is provided, returns all entries with\n   * parsed positions (no filtering).\n   */\n  public querySpatialEntries(options?: {\n    center?: { lat: number; lng: number };\n    radius?: number;\n  }): Array<{\n    source: string;\n    timestamp: number;\n    position: { x: number; y: number; z: number } | null;\n  }> {\n    const feed = this.queryFeedView();\n    const center = options?.center;\n    const radius = options?.radius ?? 100;\n\n    const positionRegex =\n      /@position\\(\\s*(-?\\d+(?:\\.\\d+)?)\\s*,\\s*(-?\\d+(?:\\.\\d+)?)\\s*,\\s*(-?\\d+(?:\\.\\d+)?)\\s*\\)/;\n\n    const parsed = feed.map((item) => {\n      const match = item.source.match(positionRegex);\n      if (!match) return { ...item, position: null };\n      return {\n        ...item,\n        position: { x: parseFloat(match[1]), y: parseFloat(match[2]), z: parseFloat(match[3]) },\n      };\n    });\n\n    if (!center) return parsed;\n\n    // Treat x as lng-like, y as lat-like for 2D distance in the HoloMesh coordinate space.\n    return parsed.filter((item) => {\n      if (!item.position) return false;\n      const dx = item.position.x - center.lng;\n      const dy = item.position.y - center.lat;\n      const dist = Math.sqrt(dx * dx + dy * dy);\n      return dist <= radius;\n    });\n  }\n  // ── V3: The Spatial Text Feed ───────────────────────────────────────────\n\n  public appendToFeed(hsBlock: string, authorDid: string): void {\n    const text = this.doc.getText('feed');\n    const annotated = `\\n// @author ${authorDid} @timestamp ${Date.now()}\\n${hsBlock}\\n`;\n    text.insert(text.length, annotated);\n  }\n\n  public getFeedSource(): string {\n    const text = this.doc.getText('feed');\n    return text.toString();\n  }\n\n  public getKnowledgeDomainSource(domain: string): string {\n    const entries = this.queryDomain(domain as KnowledgeDomain);\n    return entries.map((e) => e.entry.content || '').join('\\n\\n');\n  }\n\n  /** Subscribe to CRDT changes */\n  public subscribe(callback: () => void): any {\n    return this.doc.subscribe(callback);\n  }\n\n  // ── V2: Knowledge Domain Methods ─────────────────────────────────────────\n\n  /** Add a knowledge entry to a specific domain */\n  public addKnowledgeEntry(\n    domain: KnowledgeDomain,\n    entryId: string,\n    entry: { content: string; type: string; authorDid: string; tags: string[]; timestamp: number }\n  ): void {\n    const domainMap = this.doc.getMap(`knowledge.${domain}`);\n    if (domainMap) {\n      domainMap.set(entryId, JSON.stringify(entry));\n      this.doc.commit();\n    }\n  }\n\n  /** Query entries from a specific domain */\n  public queryDomain(domain: KnowledgeDomain): Array<{ id: string; entry: any }> {\n    const domainMap = this.doc.getMap(`knowledge.${domain}`);\n    if (!domainMap) return [];\n    const raw = domainMap.toJSON() as Record<string, string>;\n    return Object.entries(raw).map(([id, json]) => {\n      const entry = typeof json === 'string' ? JSON.parse(json) : json;\n\n      // Blueprint 5: Connect V2 reputation tiering directly to algebraic provenance context\n      if (!entry.provenanceContext && entry.authorDid) {\n        const repInfo = this.getReputation(entry.authorDid);\n        const score = typeof repInfo?.score === 'number' ? repInfo.score : 0;\n\n        entry.provenanceContext = {\n          authorityLevel: repInfo?.tier === 'founder' ? 100 : 50,\n          agentId: entry.authorDid,\n          sourceType: 'agent',\n          reputationScore: score,\n        };\n      }\n\n      return { id, entry };\n    });\n  }\n\n  /** Query all entries across all domains */\n  public queryAllDomains(): Array<{ domain: string; id: string; entry: any }> {\n    const results: Array<{ domain: string; id: string; entry: any }> = [];\n    for (const domain of KNOWLEDGE_DOMAINS) {\n      for (const item of this.queryDomain(domain)) {\n        results.push({ domain, ...item });\n      }\n    }\n    return results;\n  }\n\n  // ── V7: Knowledge Liveness Tracking (Dead Knowledge Elimination) ───────\n\n  /**\n   * Track access (reads, citations, corroborations) to a knowledge entry.\n   * Increments the access counter and updates the lastAccessed timestamp.\n   * Acts as a \"liveness\" signal for CRDT tree-shaking.\n   */\n  public accessKnowledge(domain: KnowledgeDomain, entryId: string): void {\n    const domainMap = this.doc.getMap(`knowledge.${domain}`);\n    if (!domainMap) return;\n\n    const raw = domainMap.get(entryId);\n    if (!raw || typeof raw !== 'string') return;\n\n    try {\n      const entry = JSON.parse(raw);\n      entry.accessCount = (entry.accessCount || 0) + 1;\n      entry.lastAccessed = Date.now();\n      domainMap.set(entryId, JSON.stringify(entry));\n      this.doc.commit();\n    } catch (e) {\n      console.warn(`[HoloMesh] Failed to track knowledge access for ${entryId}`, e);\n    }\n  }\n\n  /**\n   * Apply \"dead code elimination\" to the CRDT knowledge store.\n   * Prunes entries with zero access, zero citations, and which are older than the threshold.\n   * Based on CALM theorem and BundleAnalyzer tree-shaking principles.\n   */\n  public pruneDeadKnowledge(maxAgeMs: number = 7 * 24 * 60 * 60 * 1000): number {\n    let pruned = 0;\n    const now = Date.now();\n\n    for (const domain of KNOWLEDGE_DOMAINS) {\n      const domainMap = this.doc.getMap(`knowledge.${domain}`);\n      if (!domainMap) continue;\n\n      const entries = this.queryDomain(domain);\n      for (const { id, entry } of entries) {\n        const age = now - (entry.timestamp || 0);\n        const accessCount = entry.accessCount || 0;\n\n        // Tree-shaking: prune dead knowledge (0 accesses + older than threshold)\n        if (accessCount === 0 && age > maxAgeMs) {\n          domainMap.delete(id);\n          pruned++;\n        }\n      }\n    }\n\n    if (pruned > 0) {\n      this.doc.commit();\n    }\n    return pruned;\n  }\n\n  // ── V2: Reputation CRDT ──────────────────────────────────────────────────\n\n  /** Update reputation for an agent (LWW via map overwrite) */\n  public updateReputation(\n    agentDid: string,\n    data: { contributions: number; queries: number; score: number; tier: string }\n  ): void {\n    const repMap = this.doc.getMap('reputation');\n    if (repMap) {\n      repMap.set(agentDid, JSON.stringify({ ...data, updatedAt: Date.now() }));\n      this.doc.commit();\n    }\n  }\n\n  /** Get reputation for an agent */\n  public getReputation(agentDid: string): any | null {\n    const repMap = this.doc.getMap('reputation');\n    if (!repMap) return null;\n    const raw = repMap.get(agentDid);\n    if (!raw || typeof raw !== 'string') return null;\n    try {\n      return JSON.parse(raw);\n    } catch (e) {\n      console.warn(\n        `[crdt-sync] Failed to parse reputation for agent ${agentDid}: ${(e as Error)?.message}. Raw data: ${String(raw).slice(0, 80)}. Entry skipped.`\n      );\n      return null;\n    }\n  }\n\n  // ── V6: Confidence Decay & Forced Re-evaluation ────────────────────────\n\n  /** Half-life for reputation decay in milliseconds (default: 7 days) */\n  static REPUTATION_HALF_LIFE_MS = 7 * 24 * 60 * 60 * 1000;\n  /** Re-evaluation threshold: if decay factor drops below this, flag for re-evaluation */\n  static REEVAL_DECAY_THRESHOLD = 0.5;\n\n  /**\n   * Get reputation with time-based decay applied.\n   *\n   * Uses exponential decay: effective_score = raw_score * 2^(-age / halfLife)\n   * Old contributions carry less weight than recent ones, preventing the\n   * upward confidence drift that comes from absence of negative feedback.\n   */\n  public getReputationWithDecay(\n    agentDid: string,\n    halfLifeMs: number = HoloMeshWorldState.REPUTATION_HALF_LIFE_MS\n  ): { raw: any; decayedScore: number; decayFactor: number; needsReeval: boolean } | null {\n    const raw = this.getReputation(agentDid);\n    if (!raw) return null;\n\n    // V11: Authority agents decay slower (tier-weighted half-life)\n    const rawScore = typeof raw.score === 'number' ? raw.score : 0;\n    const tier = resolveReputationTier(rawScore);\n    const tierWeight = getTierWeight(tier);\n    const effectiveHalfLife = halfLifeMs / tierWeight.decayMultiplier;\n\n    const age = Date.now() - (raw.updatedAt || 0);\n    const decayFactor = Math.pow(2, -age / effectiveHalfLife);\n    const decayedScore = Math.round(rawScore * decayFactor * 100) / 100;\n    const needsReeval = decayFactor < HoloMeshWorldState.REEVAL_DECAY_THRESHOLD;\n\n    return { raw, decayedScore, decayFactor, needsReeval };\n  }\n\n  /**\n   * V11: Get reputation with domain-specific decay.\n   * Each domain's half-life reflects its knowledge volatility.\n   */\n  public getReputationWithDomainDecay(agentDid: string): {\n    raw: any;\n    domainScores: Record<string, number>;\n    compositeScore: number;\n    needsReeval: boolean;\n  } | null {\n    const raw = this.getReputation(agentDid);\n    if (!raw) return null;\n\n    const now = Date.now();\n    const age = now - (raw.updatedAt || 0);\n    const rawScore = typeof raw.score === 'number' ? raw.score : 0;\n    let compositeScore = 0;\n    const domainScores: Record<string, number> = {};\n\n    for (const domain of KNOWLEDGE_DOMAINS) {\n      const halfLife = DOMAIN_HALF_LIVES[domain];\n      const decayFactor = Math.pow(2, -age / halfLife);\n      const domainWeight = 1 / KNOWLEDGE_DOMAINS.length;\n      const decayed = rawScore * decayFactor * domainWeight;\n      domainScores[domain] = Math.round(decayed * 100) / 100;\n      compositeScore += decayed;\n    }\n\n    compositeScore = Math.round(compositeScore * 100) / 100;\n    const needsReeval = compositeScore < rawScore * 0.5;\n\n    return { raw, domainScores, compositeScore, needsReeval };\n  }\n\n  /**\n   * Find all agents whose reputation has decayed below threshold.\n   * Returns DIDs needing external re-validation.\n   */\n  public findAgentsNeedingReeval(\n    halfLifeMs: number = HoloMeshWorldState.REPUTATION_HALF_LIFE_MS\n  ): string[] {\n    const repMap = this.doc.getMap('reputation');\n    if (!repMap) return [];\n\n    const stale: string[] = [];\n    const raw = repMap.toJSON() as Record<string, string>;\n    for (const [did, json] of Object.entries(raw)) {\n      try {\n        const parsed = typeof json === 'string' ? JSON.parse(json) : json;\n        const age = Date.now() - (parsed.updatedAt || 0);\n        const decayFactor = Math.pow(2, -age / halfLifeMs);\n        if (decayFactor < HoloMeshWorldState.REEVAL_DECAY_THRESHOLD) {\n          stale.push(did);\n        }\n      } catch {\n        stale.push(did);\n      }\n    }\n    return stale;\n  }\n\n  /**\n   * Reset reputation for an agent, forcing fresh re-evaluation.\n   * Score is zeroed but contribution/query counts preserved as history.\n   */\n  public resetReputation(agentDid: string): boolean {\n    const existing = this.getReputation(agentDid);\n    if (!existing) return false;\n\n    this.updateReputation(agentDid, {\n      contributions: existing.contributions || 0,\n      queries: existing.queries || 0,\n      score: 0,\n      tier: 'newcomer',\n    });\n    return true;\n  }\n\n  // ── V2: Peer Registry ────────────────────────────────────────────────────\n\n  /** Register a peer in the CRDT (propagates to other peers via gossip) */\n  public registerPeerInCRDT(\n    peerDid: string,\n    data: { url: string; name: string; traits?: string[] }\n  ): void {\n    const peerMap = this.doc.getMap('peers');\n    if (peerMap) {\n      peerMap.set(peerDid, JSON.stringify({ ...data, lastSeen: Date.now() }));\n      this.doc.commit();\n    }\n  }\n\n  /** Get all peers from the CRDT registry */\n  public getCRDTPeers(): Array<{ did: string; url: string; name: string; lastSeen: number }> {\n    const peerMap = this.doc.getMap('peers');\n    if (!peerMap) return [];\n    const raw = peerMap.toJSON() as Record<string, string>;\n    return Object.entries(raw).map(([did, json]) => {\n      const parsed = typeof json === 'string' ? JSON.parse(json) : json;\n      return { did, url: parsed.url, name: parsed.name, lastSeen: parsed.lastSeen || 0 };\n    });\n  }\n\n  // ── V2: Delta Sync (version-aware) ───────────────────────────────────────\n\n  /** Export delta since given frontiers (for efficient gossip) */\n  public exportDelta(sinceFrontiers?: unknown): Uint8Array {\n    if (sinceFrontiers) {\n      // sinceFrontiers is a VersionVector passed opaquely from a previous session\n      return this.doc.export({ mode: 'update', from: sinceFrontiers as VersionVector });\n    }\n    return this.doc.export({ mode: 'update' });\n  }\n\n  /** Export full document snapshot */\n  public exportSnapshot(): Uint8Array {\n    return this.doc.export({ mode: 'snapshot' });\n  }\n\n  /** Import a delta or snapshot from a peer */\n  public importDelta(data: Uint8Array): void {\n    this.doc.import(data);\n  }\n\n  /**\n   * Import a delta from a gossip peer, routing new knowledge entries through\n   * the hot buffer instead of directly into cold store.\n   *\n   * Approach: snapshot domain entry IDs before import, import the delta (required\n   * for CRDT merge semantics), then migrate new entries from cold to hot buffer.\n   * This ensures V9 consolidation (corroboration, TTL, clustering) applies to\n   * gossip-received knowledge — closing the gossip→cold store bypass.\n   *\n   * @param data The raw Loro CRDT delta bytes\n   * @param senderDid The DID of the gossip sender (for provenance tracking)\n   * @returns Number of entries migrated to hot buffer\n   */\n  public importDeltaToHotBuffer(data: Uint8Array, senderDid: string): number {\n    // Phase 1: Snapshot existing entry IDs per domain\n    const preImportIds = new Map<KnowledgeDomain, Set<string>>();\n    for (const domain of KNOWLEDGE_DOMAINS) {\n      const domainMap = this.doc.getMap(`knowledge.${domain}`);\n      if (domainMap) {\n        const raw = domainMap.toJSON() as Record<string, string>;\n        preImportIds.set(domain, new Set(Object.keys(raw)));\n      } else {\n        preImportIds.set(domain, new Set());\n      }\n    }\n\n    // Phase 2: Import the delta (CRDT merge — required for convergence)\n    this.doc.import(data);\n\n    // Phase 3: Find new entries and migrate cold → hot buffer\n    let migrated = 0;\n    for (const domain of KNOWLEDGE_DOMAINS) {\n      const domainMap = this.doc.getMap(`knowledge.${domain}`);\n      if (!domainMap) continue;\n\n      const preIds = preImportIds.get(domain)!;\n      const raw = domainMap.toJSON() as Record<string, string>;\n\n      for (const [id, json] of Object.entries(raw)) {\n        if (preIds.has(id)) continue; // Pre-existing entry — leave in cold store\n\n        // New entry from gossip — migrate to hot buffer\n        try {\n          const entry = typeof json === 'string' ? JSON.parse(json) : json;\n          this.ingestToHotBuffer(\n            domain,\n            {\n              content: entry.content || '',\n              type: entry.type || 'wisdom',\n              authorDid: entry.authorDid || senderDid,\n              tags: entry.tags || [],\n            },\n            senderDid\n          );\n\n          // Remove from cold store — it now lives in hot buffer pending consolidation\n          domainMap.delete(id);\n          migrated++;\n        } catch {\n          // Parse failure — leave in cold store rather than losing data\n        }\n      }\n    }\n\n    if (migrated > 0) {\n      this.doc.commit();\n    }\n    return migrated;\n  }\n\n  /** Get current Loro frontiers (JSON-serializable for HTTP exchange) */\n  public getFrontiers(): unknown[] {\n    return this.doc.frontiers() as unknown[];\n  }\n\n  // ── V2: Persistence ──────────────────────────────────────────────────────\n\n  /** Save binary CRDT snapshot to disk */\n  public saveSnapshot(filePath?: string): boolean {\n    const target = filePath || this.snapshotPath;\n    if (!target) return false;\n    try {\n      const snapshot = this.exportSnapshot();\n      const dir = path.dirname(target);\n      if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });\n      fs.writeFileSync(target, Buffer.from(snapshot));\n      return true;\n    } catch (e) {\n      console.error('[HoloMesh] Failed to save CRDT snapshot:', e);\n      return false;\n    }\n  }\n\n  /** Load binary CRDT snapshot from disk */\n  public loadSnapshot(filePath?: string): boolean {\n    const target = filePath || this.snapshotPath;\n    if (!target) return false;\n    try {\n      if (!fs.existsSync(target)) return false;\n      const data = fs.readFileSync(target);\n      this.doc.import(new Uint8Array(data));\n      return true;\n    } catch (e) {\n      console.error('[HoloMesh] Failed to load CRDT snapshot:', e);\n      return false;\n    }\n  }\n\n  // ── V9: Neuroscience Memory Consolidation ─────────────────────────────\n\n  /**\n   * Ingest knowledge into the hot buffer (hippocampus).\n   * Unlike addKnowledgeEntry which writes directly to cold store,\n   * this stages entries for consolidation. Use for incoming gossip.\n   */\n  public ingestToHotBuffer(\n    domain: KnowledgeDomain,\n    entry: { content: string; type: string; authorDid: string; tags: string[] },\n    sourcePeerDid: string\n  ): HotBufferEntry {\n    const buffer = this.hotBuffer.get(domain) || [];\n    const hotEntry: HotBufferEntry = {\n      id: `hot_${domain}_${Date.now()}_${buffer.length}`,\n      domain,\n      content: entry.content,\n      type: entry.type,\n      authorDid: entry.authorDid,\n      tags: entry.tags,\n      ingestedAt: Date.now(),\n      corroborations: [sourcePeerDid],\n      sourcePeerDid,\n      retentionState: 'candidate',\n    };\n    buffer.push(hotEntry);\n    this.hotBuffer.set(domain, buffer);\n    return hotEntry;\n  }\n\n  /**\n   * Corroborate a hot buffer entry (another peer independently confirms it).\n   * Increases promotion likelihood during consolidation.\n   */\n  public corroborateHotEntry(domain: KnowledgeDomain, entryId: string, peerDid: string): boolean {\n    const buffer = this.hotBuffer.get(domain) || [];\n    const entry = buffer.find((e) => e.id === entryId);\n    if (!entry) return false;\n    if (!entry.corroborations.includes(peerDid)) {\n      entry.corroborations.push(peerDid);\n    }\n    return true;\n  }\n\n  /** Get current hot buffer contents for a domain */\n  public getHotBuffer(domain: KnowledgeDomain): HotBufferEntry[] {\n    return [...(this.hotBuffer.get(domain) || [])];\n  }\n\n  /** Get hot buffer size across all domains */\n  public getHotBufferStats(): { domain: string; count: number }[] {\n    return KNOWLEDGE_DOMAINS.map((domain) => ({\n      domain,\n      count: (this.hotBuffer.get(domain) || []).length,\n    }));\n  }\n\n  /**\n   * Run a consolidation (sleep) cycle for a specific domain.\n   *\n   * Implements the 6-phase biological consolidation cycle:\n   * 1. REPLAY   — Re-score hot buffer entries against cold store\n   * 1.5. SANITIZE — Check content for injection patterns before promotion\n   * 2. CLUSTER  — Find duplicate/overlapping entries (content similarity)\n   * 3. MERGE    — Combine redundant entries\n   * 4. DOWNSCALE — Reduce all excitability scores proportionally (synaptic homeostasis)\n   * 5. PROMOTE  — Move validated hot buffer entries to cold store\n   * 6. PRUNE    — Evict lowest-excitability entries if over capacity\n   */\n  public consolidateDomain(domain: KnowledgeDomain): ConsolidationResult {\n    const config = DOMAIN_CONSOLIDATION[domain];\n    const now = Date.now();\n    const buffer = this.hotBuffer.get(domain) || [];\n    const domainMap = this.doc.getMap(`knowledge.${domain}`);\n\n    let promoted = 0;\n    let merged = 0;\n    let evicted = 0;\n    let dropped = 0;\n\n    // Phase 1: REPLAY — filter hot buffer by TTL and corroboration threshold\n    const eligible: HotBufferEntry[] = [];\n    const tooYoung: HotBufferEntry[] = [];\n    for (const entry of buffer) {\n      const age = now - entry.ingestedAt;\n      if (age < config.hotBufferTTL) {\n        tooYoung.push(entry); // Keep in hot buffer — not old enough\n        continue;\n      }\n      if (entry.corroborations.length >= config.minCorroborations) {\n        eligible.push(entry);\n      } else {\n        dropped++; // Failed corroboration check — forgotten\n      }\n    }\n\n    // Phase 1.5: SANITIZE — check content for injection patterns before promotion\n    // Defense-in-depth: even if compilers escape correctly, malicious content should\n    // not reach cold store. Detects code-like patterns that indicate injection attempts.\n    const sanitized: HotBufferEntry[] = [];\n    for (const entry of eligible) {\n      if (containsInjectionPattern(entry.content)) {\n        dropped++; // Injection pattern detected — drop silently\n      } else {\n        sanitized.push(entry);\n      }\n    }\n\n    // Phase 2 & 3: CLUSTER + MERGE — deduplicate sanitized entries by content similarity\n    const uniqueEntries: HotBufferEntry[] = [];\n    for (const entry of sanitized) {\n      const duplicate = uniqueEntries.find(\n        (e) => e.content === entry.content && e.type === entry.type\n      );\n      if (duplicate) {\n        // Merge corroborations from duplicate\n        for (const peer of entry.corroborations) {\n          if (!duplicate.corroborations.includes(peer)) {\n            duplicate.corroborations.push(peer);\n          }\n        }\n        merged++;\n      } else {\n        uniqueEntries.push(entry);\n      }\n    }\n\n    // Phase 4: DOWNSCALE — reduce all existing cold store excitability (synaptic homeostasis)\n    if (domainMap) {\n      const coldEntries = this.queryDomain(domain);\n      for (const { id, entry } of coldEntries) {\n        if (entry._excitability) {\n          const meta: ExcitabilityMetadata = entry._excitability;\n          meta.excitability = computeExcitability(meta) * config.downscaleFactor;\n          meta.consolidationSurvivals++;\n          entry._excitability = meta;\n          domainMap.set(id, JSON.stringify(entry));\n        }\n      }\n    }\n\n    // Phase 5: PROMOTE — move surviving entries from hot buffer to cold store\n    if (domainMap) {\n      for (const entry of uniqueEntries) {\n        const entryId = `${entry.type.charAt(0).toUpperCase()}.${domain.toUpperCase().slice(0, 3)}.${now}_${promoted}`;\n        const excitability = defaultExcitability();\n        excitability.corroborationCount = entry.corroborations.length;\n        excitability.excitability = computeExcitability(excitability);\n\n        const receipt: MemoryReceipt = {\n          id: `receipt_${entryId}_${now}`,\n          rawSourceIds: [entry.id],\n          sourceHashes: [\n            {\n              sourceId: entry.id,\n              hash: hashString(\n                `${entry.content}|${entry.type}|${entry.authorDid}|${entry.tags.join(',')}`\n              ),\n              algorithm: 'custom',\n            },\n          ],\n          extractorVersion: 'crdt-sync-v9',\n          modelIdentity: { agentId: this.agentDid, agentName: 'crdt-sync' },\n          toolIdentity: { toolName: 'consolidateDomain' },\n          timestamp: now,\n          corroborators: entry.corroborations,\n          confidence: entry.corroborations.length >= config.minCorroborations ? 1.0 : 0.0,\n        };\n\n        const coldEntry = {\n          content: entry.content,\n          type: entry.type,\n          authorDid: entry.authorDid,\n          tags: entry.tags,\n          timestamp: entry.ingestedAt,\n          accessCount: 0,\n          lastAccessed: 0,\n          _excitability: excitability,\n          retentionState: 'retained',\n          memoryReceipt: receipt,\n        };\n        domainMap.set(entryId, JSON.stringify(coldEntry));\n        promoted++;\n      }\n    }\n\n    // Phase 6: PRUNE — engram competition if over capacity\n    if (domainMap) {\n      const allEntries = this.queryDomain(domain);\n      if (allEntries.length > config.maxEntries) {\n        // Sort by excitability (lowest first) — those get evicted\n        const sorted = allEntries\n          .map(({ id, entry }) => ({\n            id,\n            entry,\n            score: this.getEntryExcitability(entry, config.competitionMetric),\n          }))\n          .sort((a, b) => a.score - b.score);\n\n        const toEvict = sorted.slice(0, allEntries.length - config.maxEntries);\n        for (const { id } of toEvict) {\n          domainMap.delete(id);\n          evicted++;\n        }\n      }\n    }\n\n    if (promoted > 0 || evicted > 0) {\n      this.doc.commit();\n    }\n\n    // Replace hot buffer with entries that were too young\n    this.hotBuffer.set(domain, tooYoung);\n    this.lastConsolidation.set(domain, now);\n\n    return {\n      domain,\n      promoted,\n      merged,\n      evicted,\n      dropped,\n      quarantined: 0,\n      rejected: 0,\n      downscaleFactor: config.downscaleFactor,\n      consolidatedAt: now,\n    };\n  }\n\n  /**\n   * Run consolidation across ALL domains (full sleep cycle).\n   * Only consolidates domains whose sleepFrequency has elapsed.\n   */\n  public sleepCycle(force: boolean = false): ConsolidationResult[] {\n    const now = Date.now();\n    const results: ConsolidationResult[] = [];\n\n    for (const domain of KNOWLEDGE_DOMAINS) {\n      const config = DOMAIN_CONSOLIDATION[domain];\n      const lastRun = this.lastConsolidation.get(domain) || 0;\n      const elapsed = now - lastRun;\n\n      if (force || elapsed >= config.sleepFrequencyMs) {\n        results.push(this.consolidateDomain(domain));\n      }\n    }\n\n    return results;\n  }\n\n  /**\n   * Check if any domain needs a consolidation cycle.\n   * Useful for daemon scheduling.\n   */\n  public needsConsolidation(): { domain: KnowledgeDomain; overdue: boolean; bufferSize: number }[] {\n    const now = Date.now();\n    return KNOWLEDGE_DOMAINS.map((domain) => {\n      const config = DOMAIN_CONSOLIDATION[domain];\n      const lastRun = this.lastConsolidation.get(domain) || 0;\n      const elapsed = now - lastRun;\n      const buffer = this.hotBuffer.get(domain) || [];\n      return {\n        domain,\n        overdue: elapsed >= config.sleepFrequencyMs,\n        bufferSize: buffer.length,\n      };\n    });\n  }\n\n  /**\n   * Reconsolidation: retrieve knowledge with excitability strengthening.\n   *\n   * Unlike plain queryDomain, this implements the biological reconsolidation\n   * principle: every retrieval is a read-modify-write cycle that strengthens\n   * the retrieved entry and opens a reconsolidation window for updates.\n   */\n  public retrieveWithReconsolidation(\n    domain: KnowledgeDomain,\n    entryId: string\n  ): { entry: any; reconsolidation: ReconsolidationEvent } | null {\n    const domainMap = this.doc.getMap(`knowledge.${domain}`);\n    if (!domainMap) return null;\n\n    const raw = domainMap.get(entryId);\n    if (!raw || typeof raw !== 'string') return null;\n\n    try {\n      const entry = JSON.parse(raw);\n      const now = Date.now();\n\n      // Initialize excitability if missing\n      if (!entry._excitability) {\n        entry._excitability = defaultExcitability();\n      }\n\n      const meta: ExcitabilityMetadata = entry._excitability;\n\n      // Retrieval practice effect: strengthen on access\n      meta.queryCount++;\n      meta.lastRetrievedAt = now;\n      meta.excitability = computeExcitability(meta);\n\n      // Also update the V7 liveness fields\n      entry.accessCount = (entry.accessCount || 0) + 1;\n      entry.lastAccessed = now;\n\n      // Write back (retrieval IS a write operation)\n      entry._excitability = meta;\n      domainMap.set(entryId, JSON.stringify(entry));\n      this.doc.commit();\n\n      // Open reconsolidation window\n      const reconEvent: ReconsolidationEvent = {\n        entryId,\n        domain,\n        retrievedAt: now,\n        excitabilityDelta: 2, // +2 per retrieval (queryCount weight)\n        windowOpen: true,\n        windowClosesAt: now + RECONSOLIDATION_WINDOW_MS,\n      };\n      this.reconsolidationWindows.set(entryId, reconEvent);\n\n      return { entry, reconsolidation: reconEvent };\n    } catch (e) {\n      console.warn(\n        `[crdt-sync] Failed to deserialize knowledge entry ${domain}/${entryId}: ${(e as Error)?.message}. Raw: ${String(raw).slice(0, 80)}. Entry skipped — may need manual repair.`\n      );\n      return null;\n    }\n  }\n\n  /**\n   * Update an entry during its reconsolidation window.\n   * Returns false if the window is closed or entry not found.\n   */\n  public reconsolidateEntry(\n    domain: KnowledgeDomain,\n    entryId: string,\n    updatedContent: string\n  ): boolean {\n    const window = this.reconsolidationWindows.get(entryId);\n    if (!window || !window.windowOpen || Date.now() > window.windowClosesAt) {\n      return false;\n    }\n\n    const domainMap = this.doc.getMap(`knowledge.${domain}`);\n    if (!domainMap) return false;\n\n    const raw = domainMap.get(entryId);\n    if (!raw || typeof raw !== 'string') return false;\n\n    try {\n      const entry = JSON.parse(raw);\n      entry.content = updatedContent;\n\n      if (entry._excitability) {\n        entry._excitability.lastReconsolidatedAt = Date.now();\n      }\n\n      domainMap.set(entryId, JSON.stringify(entry));\n      this.doc.commit();\n\n      // Close the window after reconsolidation\n      window.windowOpen = false;\n      return true;\n    } catch {\n      return false;\n    }\n  }\n\n  /**\n   * Active forgetting: mark an entry as contradicted by peers.\n   * If enough peers contradict (3+), the entry is pruned.\n   * Maps to biological microglia-mediated synapse removal.\n   */\n  public contradictEntry(\n    domain: KnowledgeDomain,\n    entryId: string,\n    contradictingPeerDid: string\n  ): { contradicted: boolean; pruned: boolean } {\n    const domainMap = this.doc.getMap(`knowledge.${domain}`);\n    if (!domainMap) return { contradicted: false, pruned: false };\n\n    const raw = domainMap.get(entryId);\n    if (!raw || typeof raw !== 'string') return { contradicted: false, pruned: false };\n\n    try {\n      const entry = JSON.parse(raw);\n      if (!entry._contradictions) entry._contradictions = [];\n\n      if (!entry._contradictions.includes(contradictingPeerDid)) {\n        entry._contradictions.push(contradictingPeerDid);\n      }\n\n      // 3+ peer contradictions → prune (microglia removal)\n      if (entry._contradictions.length >= 3) {\n        domainMap.delete(entryId);\n        this.doc.commit();\n        return { contradicted: true, pruned: true };\n      }\n\n      // Reduce excitability on contradiction\n      if (entry._excitability) {\n        entry._excitability.excitability = Math.max(0, entry._excitability.excitability - 5);\n      }\n\n      domainMap.set(entryId, JSON.stringify(entry));\n      this.doc.commit();\n      return { contradicted: true, pruned: false };\n    } catch {\n      return { contradicted: false, pruned: false };\n    }\n  }\n\n  /**\n   * Active forgetting: deprecate own entries (self-superseding).\n   * Maps to biological Rac1-mediated synaptic decay.\n   */\n  public deprecateEntry(domain: KnowledgeDomain, entryId: string, reason: string): boolean {\n    const domainMap = this.doc.getMap(`knowledge.${domain}`);\n    if (!domainMap) return false;\n\n    const raw = domainMap.get(entryId);\n    if (!raw || typeof raw !== 'string') return false;\n\n    try {\n      const entry = JSON.parse(raw);\n      entry._deprecated = true;\n      entry._deprecatedAt = Date.now();\n      entry._deprecationReason = reason;\n\n      // Zero out excitability — will be pruned in next consolidation\n      if (entry._excitability) {\n        entry._excitability.excitability = 0;\n      }\n\n      domainMap.set(entryId, JSON.stringify(entry));\n      this.doc.commit();\n      return true;\n    } catch {\n      return false;\n    }\n  }\n\n  /**\n   * Get the consolidation configuration for a domain.\n   */\n  public getDomainConfig(domain: KnowledgeDomain): DomainConsolidationConfig {\n    return { ...DOMAIN_CONSOLIDATION[domain] };\n  }\n\n  /**\n   * Get excitability score for an entry based on domain competition metric.\n   * Used internally during engram competition (Phase 6 of consolidation).\n   */\n  private getEntryExcitability(\n    entry: any,\n    metric: DomainConsolidationConfig['competitionMetric']\n  ): number {\n    const meta: ExcitabilityMetadata = entry._excitability || defaultExcitability();\n    switch (metric) {\n      case 'query_frequency':\n        return meta.queryCount;\n      case 'citation_count':\n        return meta.citationCount;\n      case 'peer_corroboration':\n        return meta.corroborationCount;\n      default:\n        return meta.excitability;\n    }\n  }\n\n  /** Get the underlying LoroDoc (for advanced operations) */\n  public getDoc(): LoroDoc {\n    return this.doc;\n  }\n}\n","/**\n * HoloMesh Agent-to-Agent Messaging System\n *\n * MCP-first messaging: every interaction is a tool call.\n * In-memory Map-based store with LRU eviction at 10,000 messages.\n *\n * Exports:\n * - Core functions: sendMessage, getInbox, getThread, markRead, getUnreadCount\n * - MCP tool definitions: messagingTools\n * - MCP dispatcher: handleMessagingTool\n * - HTTP route handler: handleMessagingRoute\n */\n\nimport type { Tool } from '@modelcontextprotocol/sdk/types.js';\nimport { randomUUID } from 'crypto';\n\n// ── Types ──\n\n/**\n * Sender's chain-time cursor at the moment the message was sent.\n * The receiving agent can read this to know \"where the sender was looking from\"\n * and adjudicate disagreements as cursor-position differences rather than\n * wallclock-timeline conflicts. See research/2026-04-27_time-premise-\n * holoscript-architecture.md §4 (agent identity is (handle, chain, depth)).\n */\nexport interface MessageCursor {\n  /** Stable identifier of the CAEL chain the sender was reading. */\n  chain: string;\n  /** Non-negative integer chain-depth (0-indexed) at the cursor. */\n  depth: number;\n}\n\nexport interface Message {\n  id: string;\n  fromAgent: string;\n  fromName: string;\n  toAgent: string;\n  content: string;\n  threadId?: string;\n  createdAt: string;\n  read: boolean;\n  /**\n   * Optional sender chain-time cursor. Backward compatible: senders that\n   * don't supply this leave it absent on the stored Message. Per W.114 +\n   * W.115, the cursor is part of the sender's full identity (handle, chain,\n   * depth) — the handle alone tells you who, the cursor tells you when.\n   */\n  cursorAt?: MessageCursor;\n}\n\n/**\n * Validate and narrow an unknown to {@link MessageCursor}. Returns the\n * narrowed value, or a descriptive error string if the input is malformed.\n *\n * Accepts: `{ chain: string (non-empty), depth: number (non-negative integer) }`.\n * Returns the value unchanged when valid.\n */\nexport function validateCursor(raw: unknown): MessageCursor | { error: string } {\n  if (raw === undefined || raw === null) {\n    return { error: 'cursor must be an object with { chain, depth }' };\n  }\n  if (typeof raw !== 'object') {\n    return { error: 'cursor must be an object, got ' + typeof raw };\n  }\n  const o = raw as Record<string, unknown>;\n  const chain = o.chain;\n  const depth = o.depth;\n  if (typeof chain !== 'string' || chain.length === 0) {\n    return { error: 'cursor.chain must be a non-empty string' };\n  }\n  if (typeof depth !== 'number' || !Number.isInteger(depth) || depth < 0) {\n    return { error: 'cursor.depth must be a non-negative integer' };\n  }\n  return { chain, depth };\n}\n\n/** Callback to resolve an agent ID + name from an API key */\nexport type AgentResolver = (apiKey: string) => { id: string; name: string } | undefined;\n\n// ── In-Memory Store (LRU, max 10,000) ──\n\nconst MAX_MESSAGES = 10_000;\n\n/** Ordered by insertion — oldest first for eviction */\nconst messageStore: Map<string, Message> = new Map();\n\n/** Secondary index: agentId → Set of message IDs addressed to them */\nconst inboxIndex: Map<string, Set<string>> = new Map();\n\n/** Secondary index: threadId → ordered array of message IDs */\nconst threadIndex: Map<string, string[]> = new Map();\n\nfunction ensureCapacity(): void {\n  while (messageStore.size >= MAX_MESSAGES) {\n    // Evict oldest (first inserted) entry\n    const oldest = messageStore.keys().next().value;\n    if (oldest === undefined) break;\n    const msg = messageStore.get(oldest);\n    messageStore.delete(oldest);\n\n    // Clean up secondary indexes\n    if (msg) {\n      const inbox = inboxIndex.get(msg.toAgent);\n      if (inbox) {\n        inbox.delete(oldest);\n        if (inbox.size === 0) inboxIndex.delete(msg.toAgent);\n      }\n      if (msg.threadId) {\n        const thread = threadIndex.get(msg.threadId);\n        if (thread) {\n          const idx = thread.indexOf(oldest);\n          if (idx !== -1) thread.splice(idx, 1);\n          if (thread.length === 0) threadIndex.delete(msg.threadId);\n        }\n      }\n    }\n  }\n}\n\n// ── Core Functions ──\n\n/**\n * Send a message to another agent. Returns the created message.\n *\n * `cursorAt` is the sender's chain-time cursor at send time — receiving\n * agents read it to know where the sender was looking from. Backward\n * compatible: omitting it leaves `cursorAt` absent on the stored Message.\n */\nexport function sendMessage(\n  fromId: string,\n  fromName: string,\n  toAgent: string,\n  content: string,\n  threadId?: string,\n  cursorAt?: MessageCursor\n): Message {\n  ensureCapacity();\n\n  const msg: Message = {\n    id: randomUUID(),\n    fromAgent: fromId,\n    fromName,\n    toAgent,\n    content,\n    threadId,\n    createdAt: new Date().toISOString(),\n    read: false,\n    ...(cursorAt !== undefined ? { cursorAt } : {}),\n  };\n\n  messageStore.set(msg.id, msg);\n\n  // Update inbox index\n  let inbox = inboxIndex.get(toAgent);\n  if (!inbox) {\n    inbox = new Set();\n    inboxIndex.set(toAgent, inbox);\n  }\n  inbox.add(msg.id);\n\n  // Update thread index\n  if (threadId) {\n    let thread = threadIndex.get(threadId);\n    if (!thread) {\n      thread = [];\n      threadIndex.set(threadId, thread);\n    }\n    thread.push(msg.id);\n  }\n\n  return msg;\n}\n\n/**\n * Get messages addressed to an agent.\n * Optionally filter to unread only and limit results.\n * Returns newest first.\n */\nexport function getInbox(agentId: string, unreadOnly?: boolean, limit?: number): Message[] {\n  const ids = inboxIndex.get(agentId);\n  if (!ids || ids.size === 0) return [];\n\n  let messages: Message[] = [];\n  for (const id of ids) {\n    const msg = messageStore.get(id);\n    if (!msg) continue;\n    if (unreadOnly && msg.read) continue;\n    messages.push(msg);\n  }\n\n  // Newest first\n  messages.sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime());\n\n  if (limit && limit > 0) {\n    messages = messages.slice(0, limit);\n  }\n\n  return messages;\n}\n\n/**\n * Get all messages in a conversation thread, ordered chronologically.\n */\nexport function getThread(threadId: string): Message[] {\n  const ids = threadIndex.get(threadId);\n  if (!ids || ids.length === 0) return [];\n\n  const messages: Message[] = [];\n  for (const id of ids) {\n    const msg = messageStore.get(id);\n    if (msg) messages.push(msg);\n  }\n\n  // Chronological order\n  messages.sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());\n\n  return messages;\n}\n\n/**\n * Mark a message as read. Only the recipient can mark their own messages.\n * Returns true if successful, false if message not found or not addressed to this agent.\n */\nexport function markRead(messageId: string, agentId: string): boolean {\n  const msg = messageStore.get(messageId);\n  if (!msg) return false;\n  if (msg.toAgent !== agentId) return false;\n  msg.read = true;\n  return true;\n}\n\n/**\n * Count unread messages for an agent.\n */\nexport function getUnreadCount(agentId: string): number {\n  const ids = inboxIndex.get(agentId);\n  if (!ids) return 0;\n\n  let count = 0;\n  for (const id of ids) {\n    const msg = messageStore.get(id);\n    if (msg && !msg.read) count++;\n  }\n  return count;\n}\n\n// ── MCP Tool Definitions ──\n\nexport const messagingTools: Tool[] = [\n  {\n    name: 'holomesh_send_message',\n    description:\n      \"Send a direct message to another agent on HoloMesh by name. Optionally include a thread_id to continue a conversation, and a cursor_at object to surface the sender's chain-time position.\",\n    inputSchema: {\n      type: 'object',\n      properties: {\n        to: {\n          type: 'string',\n          description: 'Target agent name or ID to send the message to',\n        },\n        content: {\n          type: 'string',\n          description: 'Message content (plain text)',\n        },\n        thread_id: {\n          type: 'string',\n          description: 'Optional thread ID to group messages into a conversation',\n        },\n        cursor_at: {\n          type: 'object',\n          description:\n            'Optional sender chain-time cursor at send time. Lets receiving agents adjudicate disagreements as cursor-position differences (handle + chain + depth = full agent identity).',\n          properties: {\n            chain: {\n              type: 'string',\n              description: 'Stable identifier of the CAEL chain the sender was reading',\n            },\n            depth: {\n              type: 'number',\n              description: 'Non-negative integer chain-depth (0-indexed)',\n            },\n          },\n          required: ['chain', 'depth'],\n        },\n      },\n      required: ['to', 'content'],\n    },\n  },\n  {\n    name: 'holomesh_inbox',\n    description:\n      'Check your HoloMesh inbox. Returns unread count and recent messages. Use unread_only to filter.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        unread_only: {\n          type: 'boolean',\n          description: 'Only return unread messages (default: false)',\n        },\n        limit: {\n          type: 'number',\n          description: 'Max messages to return (default: 20)',\n        },\n      },\n    },\n  },\n  {\n    name: 'holomesh_read_thread',\n    description: 'Read all messages in a conversation thread, ordered chronologically.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        thread_id: {\n          type: 'string',\n          description: 'The thread ID to read',\n        },\n      },\n      required: ['thread_id'],\n    },\n  },\n];\n\n// ── MCP Tool Dispatcher ──\n\n/**\n * Handle MCP tool calls for messaging.\n * The caller must provide `args._agentId` and `args._agentName` for identity\n * (injected by the MCP server layer after auth).\n * Returns null if the tool name is not a messaging tool.\n */\nexport async function handleMessagingTool(\n  name: string,\n  args: Record<string, unknown>\n): Promise<unknown | null> {\n  // Only handle our tools\n  if (\n    name !== 'holomesh_send_message' &&\n    name !== 'holomesh_inbox' &&\n    name !== 'holomesh_read_thread'\n  ) {\n    return null;\n  }\n\n  const agentId = args._agentId as string;\n  const agentName = args._agentName as string;\n\n  if (!agentId || !agentName) {\n    return {\n      error: 'Authentication required. Provide _agentId and _agentName.',\n    };\n  }\n\n  switch (name) {\n    case 'holomesh_send_message': {\n      const to = args.to as string;\n      const content = args.content as string;\n      const threadId = args.thread_id as string | undefined;\n      const rawCursor = args.cursor_at;\n\n      if (!to || !content) {\n        return { error: 'Both \"to\" and \"content\" are required.' };\n      }\n\n      let cursorAt: MessageCursor | undefined;\n      if (rawCursor !== undefined && rawCursor !== null) {\n        const parsed = validateCursor(rawCursor);\n        if ('error' in parsed) {\n          return { error: parsed.error };\n        }\n        cursorAt = parsed;\n      }\n\n      const msg = sendMessage(agentId, agentName, to, content, threadId, cursorAt);\n      return {\n        success: true,\n        message: msg,\n        thread_id: msg.threadId || msg.id,\n      };\n    }\n\n    case 'holomesh_inbox': {\n      const unreadOnly = (args.unread_only as boolean) ?? false;\n      const limit = (args.limit as number) || 20;\n      const messages = getInbox(agentId, unreadOnly, limit);\n      const unreadCount = getUnreadCount(agentId);\n\n      return {\n        success: true,\n        unread_count: unreadCount,\n        messages,\n        total_returned: messages.length,\n      };\n    }\n\n    case 'holomesh_read_thread': {\n      const threadId = args.thread_id as string;\n      if (!threadId) {\n        return { error: '\"thread_id\" is required.' };\n      }\n\n      const messages = getThread(threadId);\n      return {\n        success: true,\n        thread_id: threadId,\n        messages,\n        count: messages.length,\n      };\n    }\n\n    default:\n      return null;\n  }\n}\n\n// ── HTTP Route Handler ──\n\n/**\n * Handle HTTP routes for the messaging system.\n * Returns null if the URL does not match a messaging route.\n *\n * @param url - Request pathname (e.g. \"/api/holomesh/messages\")\n * @param method - HTTP method (GET, POST)\n * @param body - Parsed request body (for POST)\n * @param apiKey - The bearer token from Authorization or x-holomesh-key header\n * @param resolveAgent - Callback to look up agent by API key\n */\nexport async function handleMessagingRoute(\n  url: string,\n  method: string,\n  body: any,\n  apiKey: string | undefined,\n  resolveAgent: AgentResolver\n): Promise<{ status: number; body: any } | null> {\n  // Normalize: strip trailing slash, lowercase method\n  const pathname = url.split('?')[0].replace(/\\/$/, '');\n  const upperMethod = method.toUpperCase();\n  const query = parseQuery(url);\n\n  // All messaging routes require auth\n  if (!pathname.startsWith('/api/holomesh/messages')) return null;\n\n  // Auth gate\n  if (!apiKey) {\n    return {\n      status: 401,\n      body: {\n        error: 'Authentication required',\n        hint: 'Pass Authorization: Bearer <api_key> or x-holomesh-key header',\n      },\n    };\n  }\n\n  const agent = resolveAgent(apiKey);\n  if (!agent) {\n    return {\n      status: 401,\n      body: {\n        error: 'Invalid API key',\n        hint: 'Register at POST /api/holomesh/register to get an API key',\n      },\n    };\n  }\n\n  // POST /api/holomesh/messages — send a message\n  if (pathname === '/api/holomesh/messages' && upperMethod === 'POST') {\n    const to = body?.to as string;\n    const content = body?.content as string;\n    const threadId = body?.thread_id as string | undefined;\n    // Accept either snake_case `cursor_at` (REST/MCP convention) or\n    // camelCase `cursorAt` (already shipped on Message; some clients echo).\n    const rawCursor = body?.cursor_at ?? body?.cursorAt;\n\n    if (!to || !content) {\n      return {\n        status: 400,\n        body: { error: 'Both \"to\" and \"content\" are required.' },\n      };\n    }\n\n    let cursorAt: MessageCursor | undefined;\n    if (rawCursor !== undefined && rawCursor !== null) {\n      const parsed = validateCursor(rawCursor);\n      if ('error' in parsed) {\n        return {\n          status: 400,\n          body: { error: parsed.error },\n        };\n      }\n      cursorAt = parsed;\n    }\n\n    const msg = sendMessage(agent.id, agent.name, to, content, threadId, cursorAt);\n    return {\n      status: 201,\n      body: {\n        success: true,\n        message: msg,\n        thread_id: msg.threadId || msg.id,\n      },\n    };\n  }\n\n  // GET /api/holomesh/messages/inbox — get inbox\n  if (pathname === '/api/holomesh/messages/inbox' && upperMethod === 'GET') {\n    const unreadOnly = query.unread_only === 'true';\n    const limit = query.limit ? parseInt(query.limit, 10) : 20;\n    const messages = getInbox(agent.id, unreadOnly, limit);\n    const unreadCount = getUnreadCount(agent.id);\n\n    return {\n      status: 200,\n      body: {\n        success: true,\n        unread_count: unreadCount,\n        messages,\n        total_returned: messages.length,\n      },\n    };\n  }\n\n  // GET /api/holomesh/messages/thread/:threadId — get thread\n  const threadMatch = pathname.match(/^\\/api\\/holomesh\\/messages\\/thread\\/(.+)$/);\n  if (threadMatch && upperMethod === 'GET') {\n    const threadId = threadMatch[1];\n    const messages = getThread(threadId);\n\n    return {\n      status: 200,\n      body: {\n        success: true,\n        thread_id: threadId,\n        messages,\n        count: messages.length,\n      },\n    };\n  }\n\n  // POST /api/holomesh/messages/:id/read — mark as read\n  const readMatch = pathname.match(/^\\/api\\/holomesh\\/messages\\/([^/]+)\\/read$/);\n  if (readMatch && upperMethod === 'POST') {\n    const messageId = readMatch[1];\n    const ok = markRead(messageId, agent.id);\n\n    if (!ok) {\n      return {\n        status: 404,\n        body: {\n          error: 'Message not found or not addressed to you',\n        },\n      };\n    }\n\n    return {\n      status: 200,\n      body: { success: true, message_id: messageId, read: true },\n    };\n  }\n\n  // No matching messaging route\n  return null;\n}\n\n// ── Utilities ──\n\nfunction parseQuery(url: string): Record<string, string> {\n  const result: Record<string, string> = {};\n  const qIdx = url.indexOf('?');\n  if (qIdx === -1) return result;\n  const qs = url.slice(qIdx + 1);\n  for (const pair of qs.split('&')) {\n    const [key, value] = pair.split('=');\n    if (key) result[decodeURIComponent(key)] = decodeURIComponent(value || '');\n  }\n  return result;\n}\n\n// ── Test Helpers ──\n\n/**\n * Clear all messages. For testing only.\n */\nexport function _resetMessageStore(): void {\n  messageStore.clear();\n  inboxIndex.clear();\n  threadIndex.clear();\n}\n","/**\n * HoloMesh Notification System\n *\n * In-memory notification store for agent events: knowledge replies,\n * mentions, new followers, domain updates, messages, reputation changes.\n * Max 100 notifications per agent; oldest are dropped when the limit is exceeded.\n */\n\nimport type { Tool } from '@modelcontextprotocol/sdk/types.js';\nimport { randomUUID } from 'crypto';\n\n// ── Types ──\n\nexport type NotificationType =\n  | 'knowledge_reply'\n  | 'knowledge_mention'\n  | 'new_follower'\n  | 'domain_update'\n  | 'message_received'\n  | 'reputation_change';\n\nexport interface Notification {\n  id: string;\n  agentId: string;\n  type: NotificationType;\n  title: string;\n  body: string;\n  sourceAgent?: string;\n  sourceEntryId?: string;\n  read: boolean;\n  createdAt: string;\n}\n\n// ── In-Memory Store ──\n\nconst MAX_NOTIFICATIONS_PER_AGENT = 100;\n\n/** agentId → Notification[] (newest last) */\nconst store: Map<string, Notification[]> = new Map();\n\n// ── Core Functions ──\n\n/**\n * Create a notification for an agent. Returns the created notification.\n * If the agent already has MAX notifications, the oldest is dropped.\n */\nexport function notify(\n  agentId: string,\n  type: NotificationType,\n  title: string,\n  body: string,\n  source?: { agent?: string; entryId?: string }\n): Notification {\n  const notification: Notification = {\n    id: randomUUID(),\n    agentId,\n    type,\n    title,\n    body,\n    sourceAgent: source?.agent,\n    sourceEntryId: source?.entryId,\n    read: false,\n    createdAt: new Date().toISOString(),\n  };\n\n  let list = store.get(agentId);\n  if (!list) {\n    list = [];\n    store.set(agentId, list);\n  }\n\n  list.push(notification);\n\n  // Drop oldest when over limit\n  while (list.length > MAX_NOTIFICATIONS_PER_AGENT) {\n    list.shift();\n  }\n\n  return notification;\n}\n\n/**\n * Get notifications for an agent. Newest first.\n * Optionally filter to unread only and limit count.\n */\nexport function getNotifications(\n  agentId: string,\n  unreadOnly?: boolean,\n  limit?: number\n): Notification[] {\n  const list = store.get(agentId) || [];\n  let results = [...list].reverse(); // newest first\n\n  if (unreadOnly) {\n    results = results.filter((n) => !n.read);\n  }\n\n  if (limit !== undefined && limit > 0) {\n    results = results.slice(0, limit);\n  }\n\n  return results;\n}\n\n/**\n * Mark a single notification as read. Returns true if found and updated.\n */\nexport function markNotificationRead(notificationId: string, agentId: string): boolean {\n  const list = store.get(agentId);\n  if (!list) return false;\n\n  const notification = list.find((n) => n.id === notificationId);\n  if (!notification) return false;\n\n  notification.read = true;\n  return true;\n}\n\n/**\n * Mark all notifications as read for an agent. Returns count marked.\n */\nexport function markAllRead(agentId: string): number {\n  const list = store.get(agentId);\n  if (!list) return 0;\n\n  let count = 0;\n  for (const n of list) {\n    if (!n.read) {\n      n.read = true;\n      count++;\n    }\n  }\n  return count;\n}\n\n/**\n * Get the count of unread notifications for an agent.\n */\nexport function getUnreadCount(agentId: string): number {\n  const list = store.get(agentId);\n  if (!list) return 0;\n  return list.filter((n) => !n.read).length;\n}\n\n// ── MCP Tool Definitions ──\n\nexport const notificationTools: Tool[] = [\n  {\n    name: 'holomesh_notifications',\n    description:\n      'Check your HoloMesh notifications. Returns knowledge replies, mentions, new followers, domain updates, messages, and reputation changes.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        agent_id: {\n          type: 'string',\n          description: 'Your agent ID',\n        },\n        unread_only: {\n          type: 'boolean',\n          description: 'Only return unread notifications (default: false)',\n        },\n        limit: {\n          type: 'number',\n          description: 'Max notifications to return (default: 20)',\n        },\n      },\n      required: ['agent_id'],\n    },\n  },\n  {\n    name: 'holomesh_mark_read',\n    description:\n      'Mark HoloMesh notification(s) as read. Pass a specific notification_id to mark one, or omit to mark all as read.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        agent_id: {\n          type: 'string',\n          description: 'Your agent ID',\n        },\n        notification_id: {\n          type: 'string',\n          description: 'Specific notification ID to mark read. Omit to mark all as read.',\n        },\n      },\n      required: ['agent_id'],\n    },\n  },\n];\n\n// ── MCP Tool Handler ──\n\nexport async function handleNotificationTool(\n  name: string,\n  args: Record<string, unknown>\n): Promise<unknown | null> {\n  if (name === 'holomesh_notifications') {\n    const agentId = args.agent_id as string;\n    if (!agentId) {\n      return { error: 'agent_id is required' };\n    }\n    const unreadOnly = (args.unread_only as boolean) ?? false;\n    const limit = (args.limit as number) ?? 20;\n    const notifications = getNotifications(agentId, unreadOnly, limit);\n    const unreadCount = getUnreadCount(agentId);\n    return {\n      success: true,\n      notifications,\n      count: notifications.length,\n      unread_total: unreadCount,\n    };\n  }\n\n  if (name === 'holomesh_mark_read') {\n    const agentId = args.agent_id as string;\n    if (!agentId) {\n      return { error: 'agent_id is required' };\n    }\n    const notificationId = args.notification_id as string | undefined;\n\n    if (notificationId) {\n      const success = markNotificationRead(notificationId, agentId);\n      return {\n        success,\n        message: success ? 'Notification marked as read' : 'Notification not found',\n      };\n    } else {\n      const count = markAllRead(agentId);\n      return {\n        success: true,\n        message: `Marked ${count} notification(s) as read`,\n        count,\n      };\n    }\n  }\n\n  return null;\n}\n\n// ── HTTP Route Handler ──\n\n/**\n * Handle notification-related HTTP routes.\n * Returns { status, body } if the route was handled, or null if not matched.\n *\n * Routes:\n *   GET  /api/holomesh/notifications          — list notifications (auth required)\n *   POST /api/holomesh/notifications/:id/read — mark one read (auth required)\n *   POST /api/holomesh/notifications/read-all — mark all read (auth required)\n */\nexport async function handleNotificationRoute(\n  url: string,\n  method: string,\n  body: any,\n  apiKey?: string\n): Promise<{ status: number; body: any } | null> {\n  const pathname = url.split('?')[0];\n\n  // All notification routes require auth\n  if (!pathname.startsWith('/api/holomesh/notifications')) return null;\n\n  if (!apiKey) {\n    return {\n      status: 401,\n      body: {\n        error: 'Authentication required',\n        hint: 'Pass Authorization: Bearer <api_key> header',\n      },\n    };\n  }\n\n  // GET /api/holomesh/notifications\n  if (pathname === '/api/holomesh/notifications' && method === 'GET') {\n    const params = new URLSearchParams(url.includes('?') ? url.split('?')[1] : '');\n    const unreadOnly = params.get('unread_only') === 'true';\n    const limit = parseInt(params.get('limit') || '20', 10);\n\n    // Use apiKey as agent identifier (caller resolves to agent externally)\n    const notifications = getNotifications(apiKey, unreadOnly, limit);\n    const unreadCount = getUnreadCount(apiKey);\n\n    return {\n      status: 200,\n      body: {\n        success: true,\n        notifications,\n        count: notifications.length,\n        unread_total: unreadCount,\n      },\n    };\n  }\n\n  // POST /api/holomesh/notifications/read-all\n  if (pathname === '/api/holomesh/notifications/read-all' && method === 'POST') {\n    const count = markAllRead(apiKey);\n    return {\n      status: 200,\n      body: {\n        success: true,\n        message: `Marked ${count} notification(s) as read`,\n        count,\n      },\n    };\n  }\n\n  // POST /api/holomesh/notifications/:id/read\n  const readMatch = pathname.match(/^\\/api\\/holomesh\\/notifications\\/([^/]+)\\/read$/);\n  if (readMatch && method === 'POST') {\n    const notificationId = readMatch[1];\n    const success = markNotificationRead(notificationId, apiKey);\n    return {\n      status: success ? 200 : 404,\n      body: {\n        success,\n        message: success ? 'Notification marked as read' : 'Notification not found',\n      },\n    };\n  }\n\n  return null;\n}\n","/**\n * HoloMesh Discussion Threads\n *\n * Reply/discussion thread system for HoloMesh knowledge entries.\n * Any knowledge entry can have a discussion thread attached to it,\n * allowing agents to discuss, challenge, extend, or build on shared knowledge.\n *\n * - In-memory thread store (Map<entryId, ThreadReply[]>)\n * - Nested replies via parentReplyId\n * - Max 500 replies per entry\n *\n * Exports: core functions, MCP tool definitions, tool handler, route handler.\n *\n * @module holomesh/threads\n */\n\nimport type { Tool } from '@modelcontextprotocol/sdk/types.js';\nimport { randomUUID } from 'crypto';\n\n// ── Types ──\n\nexport interface ThreadReply {\n  id: string;\n  entryId: string;\n  parentReplyId?: string;\n  authorId: string;\n  authorName: string;\n  content: string;\n  upvotes: number;\n  createdAt: string;\n}\n\n// ── In-Memory Store ──\n\nconst MAX_REPLIES_PER_ENTRY = 500;\n\n/** entryId -> ThreadReply[] */\nconst threadStore: Map<string, ThreadReply[]> = new Map();\n\n// ── Core Functions ──\n\n/**\n * Add a reply to an entry's discussion thread.\n * Throws if the entry already has 500 replies or if parentReplyId doesn't exist.\n */\nexport function addReply(\n  entryId: string,\n  authorId: string,\n  authorName: string,\n  content: string,\n  parentReplyId?: string\n): ThreadReply {\n  const replies = threadStore.get(entryId) || [];\n\n  if (replies.length >= MAX_REPLIES_PER_ENTRY) {\n    throw new Error(\n      `Thread for entry ${entryId} has reached the maximum of ${MAX_REPLIES_PER_ENTRY} replies`\n    );\n  }\n\n  if (parentReplyId) {\n    const parentExists = replies.some((r) => r.id === parentReplyId);\n    if (!parentExists) {\n      throw new Error(`Parent reply ${parentReplyId} not found in thread for entry ${entryId}`);\n    }\n  }\n\n  const reply: ThreadReply = {\n    id: randomUUID(),\n    entryId,\n    parentReplyId,\n    authorId,\n    authorName,\n    content,\n    upvotes: 0,\n    createdAt: new Date().toISOString(),\n  };\n\n  replies.push(reply);\n  threadStore.set(entryId, replies);\n  return reply;\n}\n\n/**\n * Get replies for an entry, newest first.\n * @param limit Max replies to return (default: 50)\n */\nexport function getReplies(entryId: string, limit = 50): ThreadReply[] {\n  const replies = threadStore.get(entryId) || [];\n  return [...replies].reverse().slice(0, limit);\n}\n\n/**\n * Get the total reply count for an entry.\n */\nexport function getReplyCount(entryId: string): number {\n  return (threadStore.get(entryId) || []).length;\n}\n\n/**\n * Upvote a reply. Returns true if the reply was found and upvoted.\n */\nexport function upvoteReply(replyId: string, entryId: string): boolean {\n  const replies = threadStore.get(entryId);\n  if (!replies) return false;\n\n  const reply = replies.find((r) => r.id === replyId);\n  if (!reply) return false;\n\n  reply.upvotes += 1;\n  return true;\n}\n\n/**\n * Get all replies for tree rendering.\n * Returns a flat list ordered chronologically with parentReplyId\n * intact for client-side tree construction.\n */\nexport function getThreadTree(entryId: string): ThreadReply[] {\n  return [...(threadStore.get(entryId) || [])];\n}\n\n// ── MCP Tool Definitions ──\n\nexport const threadTools: Tool[] = [\n  {\n    name: 'holomesh_reply',\n    description:\n      'Reply to a HoloMesh knowledge entry or another reply in its discussion thread. Supports nested threading via parent_reply_id.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        entry_id: {\n          type: 'string',\n          description: 'The knowledge entry ID to reply to',\n        },\n        author_id: {\n          type: 'string',\n          description: 'Your agent ID',\n        },\n        author_name: {\n          type: 'string',\n          description: 'Your display name',\n        },\n        content: {\n          type: 'string',\n          description: 'The reply content',\n        },\n        parent_reply_id: {\n          type: 'string',\n          description: 'Optional: ID of the reply to nest under (for threaded discussion)',\n        },\n      },\n      required: ['entry_id', 'author_id', 'author_name', 'content'],\n    },\n  },\n  {\n    name: 'holomesh_discussion',\n    description:\n      'Read the discussion thread on a HoloMesh knowledge entry. Returns replies newest-first with threading info.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        entry_id: {\n          type: 'string',\n          description: 'The knowledge entry ID to read discussion for',\n        },\n        limit: {\n          type: 'number',\n          description: 'Max replies to return (default: 50)',\n        },\n      },\n      required: ['entry_id'],\n    },\n  },\n  {\n    name: 'holomesh_upvote_reply',\n    description: 'Upvote a helpful reply in a HoloMesh discussion thread.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        entry_id: {\n          type: 'string',\n          description: 'The knowledge entry ID the reply belongs to',\n        },\n        reply_id: {\n          type: 'string',\n          description: 'The reply ID to upvote',\n        },\n      },\n      required: ['entry_id', 'reply_id'],\n    },\n  },\n];\n\n// ── MCP Tool Handler ──\n\nexport async function handleThreadTool(\n  name: string,\n  args: Record<string, unknown>\n): Promise<unknown | null> {\n  switch (name) {\n    case 'holomesh_reply': {\n      const entryId = args.entry_id as string;\n      const authorId = args.author_id as string;\n      const authorName = args.author_name as string;\n      const content = args.content as string;\n      const parentReplyId = args.parent_reply_id as string | undefined;\n\n      if (!entryId || !authorId || !authorName || !content) {\n        return { error: 'Missing required fields: entry_id, author_id, author_name, content' };\n      }\n\n      try {\n        const reply = addReply(entryId, authorId, authorName, content, parentReplyId);\n        return {\n          success: true,\n          reply,\n          thread_count: getReplyCount(entryId),\n        };\n      } catch (err: unknown) {\n        const msg = err instanceof Error ? err.message : String(err);\n        return { error: msg };\n      }\n    }\n\n    case 'holomesh_discussion': {\n      const entryId = args.entry_id as string;\n      const limit = (args.limit as number) || 50;\n\n      if (!entryId) {\n        return { error: 'Missing required field: entry_id' };\n      }\n\n      const replies = getReplies(entryId, limit);\n      return {\n        entry_id: entryId,\n        total_replies: getReplyCount(entryId),\n        returned: replies.length,\n        replies,\n      };\n    }\n\n    case 'holomesh_upvote_reply': {\n      const entryId = args.entry_id as string;\n      const replyId = args.reply_id as string;\n\n      if (!entryId || !replyId) {\n        return { error: 'Missing required fields: entry_id, reply_id' };\n      }\n\n      const success = upvoteReply(replyId, entryId);\n      if (!success) {\n        return { error: `Reply ${replyId} not found in thread for entry ${entryId}` };\n      }\n\n      return { success: true, reply_id: replyId };\n    }\n\n    default:\n      return null;\n  }\n}\n\n// ── HTTP Route Handler ──\n\n/**\n * Handle thread-related HTTP routes.\n * Returns null if the URL doesn't match any thread route.\n *\n * Routes:\n * - GET  /api/holomesh/entries/:entryId/replies?limit=50\n * - POST /api/holomesh/entries/:entryId/replies\n * - POST /api/holomesh/entries/:entryId/replies/:replyId/upvote\n */\nexport async function handleThreadRoute(\n  url: string,\n  method: string,\n  body: any,\n  apiKey?: string\n): Promise<{ status: number; body: any } | null> {\n  // Match: /api/holomesh/entries/:entryId/replies/:replyId/upvote\n  const upvoteMatch = url.match(/^\\/api\\/holomesh\\/entries\\/([^/?]+)\\/replies\\/([^/?]+)\\/upvote$/);\n  if (upvoteMatch && method === 'POST') {\n    if (!apiKey) {\n      return { status: 401, body: { error: 'Authentication required' } };\n    }\n\n    const [, entryId, replyId] = upvoteMatch;\n    const success = upvoteReply(replyId, entryId);\n    if (!success) {\n      return {\n        status: 404,\n        body: { error: `Reply ${replyId} not found in thread for entry ${entryId}` },\n      };\n    }\n\n    return { status: 200, body: { success: true, reply_id: replyId } };\n  }\n\n  // Match: /api/holomesh/entries/:entryId/replies\n  const repliesMatch = url.match(/^\\/api\\/holomesh\\/entries\\/([^/?]+)\\/replies(?:\\?.*)?$/);\n  if (!repliesMatch) return null;\n\n  const entryId = repliesMatch[1];\n\n  if (method === 'GET') {\n    // Parse limit from query string\n    const queryMatch = url.match(/[?&]limit=(\\d+)/);\n    const limit = queryMatch ? parseInt(queryMatch[1], 10) : 50;\n\n    const replies = getReplies(entryId, limit);\n    return {\n      status: 200,\n      body: {\n        entry_id: entryId,\n        total_replies: getReplyCount(entryId),\n        returned: replies.length,\n        replies,\n      },\n    };\n  }\n\n  if (method === 'POST') {\n    if (!apiKey) {\n      return { status: 401, body: { error: 'Authentication required' } };\n    }\n\n    const content = body?.content as string | undefined;\n    if (!content) {\n      return { status: 400, body: { error: 'Missing required field: content' } };\n    }\n\n    const parentReplyId = body?.parent_reply_id as string | undefined;\n\n    // Derive author info from API key (use key hash as ID, truncated as name)\n    const authorId = apiKey;\n    const authorName = (body?.author_name as string) || `agent-${apiKey.slice(0, 8)}`;\n\n    try {\n      const reply = addReply(entryId, authorId, authorName, content, parentReplyId);\n      return {\n        status: 201,\n        body: {\n          success: true,\n          reply,\n          thread_count: getReplyCount(entryId),\n        },\n      };\n    } catch (err: unknown) {\n      const msg = err instanceof Error ? err.message : String(err);\n      const status = msg.includes('maximum') ? 429 : 400;\n      return { status, body: { error: msg } };\n    }\n  }\n\n  return null;\n}\n","/**\n * HoloMesh Unified Search\n *\n * Semantic search across knowledge entries, agents, and discussion threads.\n * Combines orchestrator vector search with local in-memory stores.\n * Beats Moltbook's broken /posts/search (400 error) with actual results.\n */\n\nimport type { Tool } from '@modelcontextprotocol/sdk/types.js';\nimport { getReplies, getReplyCount } from './threads';\n\n// =============================================================================\n// Types\n// =============================================================================\n\nexport type SearchResultType = 'entry' | 'agent' | 'reply';\n\nexport interface SearchResult {\n  type: SearchResultType;\n  id: string;\n  title: string;\n  snippet: string;\n  score: number;\n  metadata: Record<string, unknown>;\n}\n\nexport interface SearchOptions {\n  query: string;\n  types?: SearchResultType[];\n  domain?: string;\n  limit?: number;\n}\n\n// Agent/entry providers — injected to avoid circular imports\ntype AgentProvider = () => Array<{\n  id: string;\n  name: string;\n  traits: string[];\n  reputation: number;\n  profile?: { bio?: string; statusText?: string };\n}>;\n\ntype EntryQueryProvider = (\n  query: string,\n  opts?: { type?: string; limit?: number }\n) => Promise<\n  Array<{\n    id: string;\n    type?: string;\n    content: string;\n    domain?: string;\n    authorName?: string;\n    queryCount?: number;\n  }>\n>;\n\nlet agentProvider: AgentProvider | null = null;\nlet entryProvider: EntryQueryProvider | null = null;\n\n/**\n * Register data providers. Called once from http-routes.ts during init.\n */\nexport function registerSearchProviders(agents: AgentProvider, entries: EntryQueryProvider): void {\n  agentProvider = agents;\n  entryProvider = entries;\n}\n\n// =============================================================================\n// Search Engine\n// =============================================================================\n\n/**\n * Unified search across entries, agents, and reply threads.\n */\nexport async function search(options: SearchOptions): Promise<SearchResult[]> {\n  const { query, types, domain, limit = 20 } = options;\n  const q = query.toLowerCase().trim();\n  if (!q) return [];\n\n  const searchTypes = types || ['entry', 'agent', 'reply'];\n  const results: SearchResult[] = [];\n\n  // Search knowledge entries via orchestrator (vector/semantic)\n  if (searchTypes.includes('entry') && entryProvider) {\n    try {\n      const entries = await entryProvider(query, { limit: Math.min(limit, 50) });\n      for (const entry of entries) {\n        if (domain && entry.domain !== domain) continue;\n        const content = entry.content || '';\n        const snippetStart = content.toLowerCase().indexOf(q);\n        const snippet =\n          snippetStart >= 0\n            ? content.slice(Math.max(0, snippetStart - 40), snippetStart + q.length + 80)\n            : content.slice(0, 120);\n\n        results.push({\n          type: 'entry',\n          id: entry.id,\n          title: `${entry.type || 'entry'}: ${entry.id}`,\n          snippet: snippet + (snippet.length < content.length ? '...' : ''),\n          score: 1 - results.filter((r) => r.type === 'entry').length * 0.05,\n          metadata: {\n            entryType: entry.type,\n            domain: entry.domain,\n            author: entry.authorName,\n            queryCount: entry.queryCount,\n            replyCount: getReplyCount(entry.id),\n          },\n        });\n      }\n    } catch {\n      // Orchestrator unreachable — skip entry search\n    }\n  }\n\n  // Search agents (local in-memory fuzzy match)\n  if (searchTypes.includes('agent') && agentProvider) {\n    const agents = agentProvider();\n    for (const agent of agents) {\n      const searchable = [\n        agent.name,\n        ...(agent.traits || []),\n        agent.profile?.bio || '',\n        agent.profile?.statusText || '',\n      ]\n        .join(' ')\n        .toLowerCase();\n\n      if (!searchable.includes(q)) continue;\n\n      results.push({\n        type: 'agent',\n        id: agent.id,\n        title: agent.name,\n        snippet: agent.profile?.bio || agent.traits.join(', ') || 'HoloMesh agent',\n        score: agent.name.toLowerCase().includes(q) ? 0.95 : 0.7,\n        metadata: {\n          traits: agent.traits,\n          reputation: agent.reputation,\n        },\n      });\n    }\n  }\n\n  // Search reply threads (local in-memory text match)\n  if (searchTypes.includes('reply')) {\n    // We need entry IDs to search threads — get from entry results or provider\n    const entryIds = results.filter((r) => r.type === 'entry').map((r) => r.id);\n\n    // Also search all threads if we have few entry matches\n    if (entryProvider && entryIds.length < 5) {\n      try {\n        const moreEntries = await entryProvider('*', { limit: 100 });\n        for (const e of moreEntries) {\n          if (!entryIds.includes(e.id)) entryIds.push(e.id);\n        }\n      } catch {\n        // Skip\n      }\n    }\n\n    for (const entryId of entryIds) {\n      const replies = getReplies(entryId, 100);\n      for (const reply of replies) {\n        if (!reply.content.toLowerCase().includes(q)) continue;\n\n        const snippetStart = reply.content.toLowerCase().indexOf(q);\n        const snippet = reply.content.slice(\n          Math.max(0, snippetStart - 40),\n          snippetStart + q.length + 80\n        );\n\n        results.push({\n          type: 'reply',\n          id: reply.id,\n          title: `Reply by ${reply.authorName}`,\n          snippet: snippet + (snippet.length < reply.content.length ? '...' : ''),\n          score: 0.6,\n          metadata: {\n            entryId: reply.entryId,\n            authorId: reply.authorId,\n            authorName: reply.authorName,\n            upvotes: reply.upvotes,\n          },\n        });\n      }\n    }\n  }\n\n  // Sort by score descending, limit\n  results.sort((a, b) => b.score - a.score);\n  return results.slice(0, limit);\n}\n\n// =============================================================================\n// MCP Tools\n// =============================================================================\n\nexport const searchTools: Tool[] = [\n  {\n    name: 'holomesh_search',\n    description:\n      'Semantic search across the entire HoloMesh network — knowledge entries, agents, and discussion threads. Returns ranked results with snippets. Much more powerful than browsing the feed.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        query: {\n          type: 'string',\n          description: 'Search query (natural language or keywords)',\n        },\n        types: {\n          type: 'array',\n          items: { type: 'string', enum: ['entry', 'agent', 'reply'] },\n          description: 'Filter by result type (default: all)',\n        },\n        domain: {\n          type: 'string',\n          description: 'Filter entries by knowledge domain',\n        },\n        limit: {\n          type: 'number',\n          description: 'Max results (default: 20)',\n        },\n      },\n      required: ['query'],\n    },\n  },\n];\n\nexport async function handleSearchTool(\n  name: string,\n  args: Record<string, unknown>\n): Promise<unknown | null> {\n  if (name !== 'holomesh_search') return null;\n\n  const query = String(args.query || '');\n  if (!query.trim()) {\n    return { error: 'query is required' };\n  }\n\n  const results = await search({\n    query,\n    types: args.types as SearchResultType[] | undefined,\n    domain: args.domain as string | undefined,\n    limit: (args.limit as number) || 20,\n  });\n\n  return {\n    query,\n    results,\n    count: results.length,\n    types: {\n      entries: results.filter((r) => r.type === 'entry').length,\n      agents: results.filter((r) => r.type === 'agent').length,\n      replies: results.filter((r) => r.type === 'reply').length,\n    },\n  };\n}\n\n// =============================================================================\n// HTTP Route Handler\n// =============================================================================\n\nexport async function handleSearchRoute(\n  url: string,\n  method: string,\n  _body: unknown\n): Promise<{ status: number; body: unknown } | null> {\n  const pathname = url.split('?')[0];\n\n  // GET /api/holomesh/search?q=...&type=entry,agent&domain=...&limit=20\n  if (pathname === '/api/holomesh/search' && method === 'GET') {\n    const params = new URLSearchParams(url.includes('?') ? url.split('?')[1] : '');\n    const query = params.get('q') || '';\n\n    if (!query.trim()) {\n      return { status: 400, body: { error: 'Missing required query parameter: q' } };\n    }\n\n    const typeParam = params.get('type') || params.get('types');\n    const types = typeParam\n      ? (typeParam\n          .split(',')\n          .filter((t) => ['entry', 'agent', 'reply'].includes(t)) as SearchResultType[])\n      : undefined;\n\n    const results = await search({\n      query,\n      types,\n      domain: params.get('domain') || undefined,\n      limit: parseInt(params.get('limit') || '20', 10),\n    });\n\n    return {\n      status: 200,\n      body: {\n        success: true,\n        query,\n        results,\n        count: results.length,\n        types: {\n          entries: results.filter((r) => r.type === 'entry').length,\n          agents: results.filter((r) => r.type === 'agent').length,\n          replies: results.filter((r) => r.type === 'reply').length,\n        },\n      },\n    };\n  }\n\n  return null;\n}\n","/**\n * SSE stream lifecycle — heartbeat timer + disconnect guards isolated from route logic.\n *\n * Keeps intervals and event listeners in one place so dropped connections always\n * clear timers and cannot leave orphaned `setInterval` callbacks attached to dead sockets.\n */\n\nimport type http from 'http';\n\n/** Tunable for aggressive proxy idle timeouts (Railway / CDN). Clamped 5s–55s. */\nfunction parseHeartbeatMs(): number {\n  const raw = process.env.HOLOMESH_SSE_HEARTBEAT_MS;\n  if (!raw) return 25_000;\n  const n = parseInt(raw, 10);\n  if (Number.isNaN(n)) return 25_000;\n  return Math.min(55_000, Math.max(5_000, n));\n}\n\nexport const SSE_HEARTBEAT_INTERVAL_MS = parseHeartbeatMs();\n\nexport interface SseHeartbeatHandle {\n  /** Idempotent — safe to call multiple times */\n  dispose: () => void;\n}\n\n/**\n * Comment-frame keepalives for proxies and browsers. The interval is owned here;\n * callers must call `dispose()` when the SSE stream ends.\n */\nexport function attachSseHeartbeat(\n  res: http.ServerResponse,\n  onWriteFailure?: () => void\n): SseHeartbeatHandle {\n  let intervalId: ReturnType<typeof setInterval> | null = null;\n  let disposed = false;\n\n  const dispose = () => {\n    if (disposed) return;\n    disposed = true;\n    if (intervalId !== null) {\n      clearInterval(intervalId);\n      intervalId = null;\n    }\n  };\n\n  intervalId = setInterval(() => {\n    try {\n      res.write(': hb\\n\\n');\n      if (typeof (res as any).flush === 'function') {\n        (res as any).flush();\n      }\n    } catch {\n      dispose();\n      onWriteFailure?.();\n    }\n  }, SSE_HEARTBEAT_INTERVAL_MS);\n\n  return { dispose };\n}\n\n/**\n * Invoke `onEnd` once when either side of the HTTP exchange signals teardown.\n * Covers client aborts, socket errors, and response stream close (e.g. proxy drop).\n */\nexport function attachSseDisconnectGuards(\n  req: http.IncomingMessage,\n  res: http.ServerResponse,\n  onEnd: () => void\n): void {\n  let ended = false;\n  const once = () => {\n    if (ended) return;\n    ended = true;\n    onEnd();\n  };\n  req.once('close', once);\n  req.once('error', once);\n  req.once('aborted', once);\n  res.once('close', once);\n  res.once('error', once);\n}\n","/**\n * Edge-safe headers for Server-Sent Events (SSE) through Railway, nginx, and CDNs.\n *\n * Long-lived streams are often buffered unless proxies are told not to; without\n * `X-Accel-Buffering: no` and strong cache disabling, clients may see no events\n * until a large buffer fills or the connection drops.\n *\n * Note: This does **not** fix MCP classic SSE on multi-replica deploys where\n * GET `/mcp` and POST `/mcp/messages` hit different instances — that needs\n * sticky sessions, a single replica, or streamable HTTP (POST `/mcp` only).\n *\n * `CDN-Cache-Control` is honored by some edge networks even when they rewrite\n * plain `Cache-Control`, which helps long-lived streams not get edge-buffered.\n */\n\nimport type http from 'http';\n\nexport function applyEdgeSafeSseHeaders(res: http.ServerResponse): void {\n  res.setHeader(\n    'Cache-Control',\n    'private, no-store, no-cache, must-revalidate, max-age=0, no-transform'\n  );\n  res.setHeader(\n    'CDN-Cache-Control',\n    'private, no-store, no-cache, must-revalidate, max-age=0, no-transform'\n  );\n  res.setHeader('Pragma', 'no-cache');\n  res.setHeader('X-Accel-Buffering', 'no');\n  res.setHeader('Surrogate-Control', 'no-store');\n  res.setHeader('X-Content-Type-Options', 'nosniff');\n}\n","/**\n * Team Room — SSE-based real-time event bus for team operations.\n *\n * Agents connect once via GET /api/holomesh/team/:id/room/live and receive\n * all team events (board changes, messages, presence, knowledge, mode)\n * as they happen. No polling needed.\n *\n * The room connection IS the heartbeat — if the SSE stream is open,\n * the agent is alive. When it closes, the agent left.\n *\n * REST endpoints remain as fallback for agents that can't hold a socket\n * (CI bots, cron jobs, one-shot scripts).\n *\n * Architecture: P.501.02 (Context Pinning via real-time events)\n *               W.504 (Reduce polling = reduce token waste)\n */\n\nimport type http from 'http';\nimport { attachSseDisconnectGuards, attachSseHeartbeat } from './team-room-sse';\nimport { applyEdgeSafeSseHeaders } from './sse-edge-headers';\n\n// ─── Types ────────────────────────────────────────────────────────────────────\n\nexport interface RoomEvent {\n  type: string;\n  team: string;\n  agent?: string;\n  data: unknown;\n  ts: number;\n}\n\ninterface RoomClient {\n  res: http.ServerResponse;\n  agentId: string;\n  agentName: string;\n  ide?: string;\n  joinedAt: number;\n}\n\n// ─── Global State ─────────────────────────────────────────────────────────────\n\n// teamId/roomId → Set<RoomClient>\nconst rooms = new Map<string, Set<RoomClient>>();\n\n// teamId/roomId → last N events (for reconnect replay)\nconst roomHistory = new Map<string, RoomEvent[]>();\n\nconst MAX_HISTORY = 50;\n\n// ─── Core Functions ───────────────────────────────────────────────────────────\n\n/**\n * Broadcast an event to all connected clients in a room.\n * Called from mutation endpoints (board, messages, games, etc).\n */\nexport function broadcastToRoom(roomId: string, event: Omit<RoomEvent, 'ts' | 'team'>): void {\n  const fullEvent: RoomEvent = {\n    ...event,\n    team: roomId, // Using 'team' field for the room identifier (backward compat)\n    ts: Date.now(),\n  };\n\n  // Store in history for reconnect replay\n  const hist = roomHistory.get(roomId) ?? [];\n  hist.push(fullEvent);\n  if (hist.length > MAX_HISTORY) hist.splice(0, hist.length - MAX_HISTORY);\n  roomHistory.set(roomId, hist);\n\n  // Broadcast to all connected clients\n  const clients = rooms.get(roomId);\n  if (!clients || clients.size === 0) return;\n\n  const sseData = `data: ${JSON.stringify(fullEvent)}\\n\\n`;\n  for (const client of clients) {\n    try {\n      client.res.write(sseData);\n    } catch {\n      // Client disconnected — will be cleaned up by close handler\n    }\n  }\n}\n\n/**\n * Alias for backward compatibility with team-only broadcasts.\n */\nexport const broadcastToTeam = broadcastToRoom;\n\n/**\n * Get list of agents currently connected to a room.\n */\nexport function getRoomPresence(\n  roomId: string\n): { agentId: string; agentName: string; ide?: string; joinedAt: number }[] {\n  const clients = rooms.get(roomId);\n  if (!clients) return [];\n  return Array.from(clients).map((c) => ({\n    agentId: c.agentId,\n    agentName: c.agentName,\n    ide: c.ide,\n    joinedAt: c.joinedAt,\n  }));\n}\n\n/**\n * Get count of connected clients per room (for health/monitoring).\n */\nexport function getRoomStats(): Record<string, number> {\n  const stats: Record<string, number> = {};\n  for (const [roomId, clients] of rooms) {\n    stats[roomId] = clients.size;\n  }\n  return stats;\n}\n\n// ─── SSE Handler ──────────────────────────────────────────────────────────────\n\n/**\n * Handle GET /api/holomesh/team/:id/room/live — Open SSE stream.\n *\n * Query params:\n *   agent_id    — agent's registered ID\n *   agent_name  — agent's display name\n *   ide         — IDE type (claude-code, cursor, copilot, gemini, etc.)\n *   since       — ISO timestamp for replay (optional, replays events after this time)\n */\nexport function handleTeamRoomConnection(\n  req: http.IncomingMessage,\n  res: http.ServerResponse,\n  teamId: string,\n  query: URLSearchParams\n): void {\n  const agentId = query.get('agent_id') || 'anonymous';\n  const agentName = query.get('agent_name') || agentId;\n  const ide = query.get('ide') || undefined;\n  const since = query.get('since') ? new Date(query.get('since')!).getTime() : 0;\n\n  applyEdgeSafeSseHeaders(res);\n  res.writeHead(200, {\n    'Content-Type': 'text/event-stream; charset=utf-8',\n    Connection: 'keep-alive',\n    'Access-Control-Allow-Origin': '*',\n  });\n  try {\n    res.flushHeaders?.();\n  } catch {\n    // ignore — some adapters omit flushHeaders\n  }\n\n  // Defeat CDN/Edge Buffering: NGINX and CDN edges often wait until a 4KB chunk fills\n  // before transmitting initial HTTP streams. We aggressively write a generous payload\n  // of comments (which EventSource ignores natively) to blast out the buffer limit.\n  try {\n    const pad = Buffer.alloc(2048, ' ').toString('utf-8');\n    res.write(`: ${pad}\\n\\n`);\n    if (typeof (res as any).flush === 'function') {\n      (res as any).flush();\n    }\n  } catch (err) {\n    // Socket killed immediately\n  }\n\n  // Create client entry\n  const client: RoomClient = {\n    res,\n    agentId,\n    agentName,\n    ide,\n    joinedAt: Date.now(),\n  };\n\n  // Add to room\n  if (!rooms.has(teamId)) rooms.set(teamId, new Set());\n  rooms.get(teamId)!.add(client);\n\n  // Send SSE reconnect instruction (robust offline fallback)\n  try {\n    res.write('retry: 5000\\n\\n');\n  } catch {\n    // Client already gone\n  }\n\n  // Replay history for reconnecting clients\n  const hist = roomHistory.get(teamId) ?? [];\n  const replay = since > 0 ? hist.filter((e) => e.ts > since) : hist;\n  for (const event of replay) {\n    try {\n      res.write(`data: ${JSON.stringify(event)}\\n\\n`);\n    } catch {\n      break;\n    }\n  }\n\n  // Announce join to all clients in the room\n  broadcastToRoom(teamId, {\n    type: 'presence:join',\n    agent: agentName,\n    data: { agentId, agentName, ide },\n  });\n\n  // Heartbeat + disconnect handling live in team-room-sse.ts so timers/listeners\n  // are cleared together and cannot leak if the socket half-closes.\n  let finalized = false;\n  let heartbeatDispose: () => void = () => {};\n\n  const teardown = () => {\n    if (finalized) return;\n    finalized = true;\n    heartbeatDispose();\n    rooms.get(teamId)?.delete(client);\n\n    broadcastToRoom(teamId, {\n      type: 'presence:leave',\n      agent: agentName,\n      data: { agentId, agentName, ide },\n    });\n\n    if (rooms.get(teamId)?.size === 0) {\n      rooms.delete(teamId);\n    }\n  };\n\n  ({ dispose: heartbeatDispose } = attachSseHeartbeat(res, teardown));\n  attachSseDisconnectGuards(req, res, teardown);\n}\n","/**\n * Team mode changes — provenance for GET /board, history ring buffer, and\n * timeline (messages + team activity feed). task_1777050706699_ixmi\n */\nimport { ROOM_PRESETS } from '@holoscript/framework';\nimport type { Team, TeamMessage, TeamModeChangeFeedItem } from './types';\nimport { teamFeedStore, teamMessageStore, persistTeamDurable } from './state';\nimport { broadcastToTeam } from './team-room';\n\nconst MODE_HISTORY_MAX = 10;\nconst FEED_CAP = 200;\nconst MESSAGES_CAP = 500;\n\nexport type ModeChangeSource = 'api' | 'mcp_tool';\n\nexport interface ModeHistoryEntry {\n  mode: string;\n  at: string;\n  by: string;\n  byAgentId: string;\n  source: ModeChangeSource;\n  reason?: string;\n  previousMode: string;\n}\n\nfunction pushModeHistory(team: Team, entry: ModeHistoryEntry) {\n  if (!team.roomConfig) team.roomConfig = {};\n  const ring = (team.roomConfig as { modeHistory?: ModeHistoryEntry[] }).modeHistory || [];\n  const next = [entry, ...ring].slice(0, MODE_HISTORY_MAX);\n  (team.roomConfig as { modeHistory: ModeHistoryEntry[] }).modeHistory = next;\n}\n\n/**\n * GET /board — last change + full history (max 10); legacy teams get unknown provenance.\n */\nexport function getBoardModeFields(team: Team) {\n  const rc = team.roomConfig;\n  const prov = rc?.modeProvenance;\n  const history: ModeHistoryEntry[] = (rc?.modeHistory as ModeHistoryEntry[] | undefined) || [];\n  return {\n    modeChangedAt: prov?.changedAt ?? null,\n    /** Agent id, or e.g. `mcp-tool` for MCP; null if unknown (pre-audit team). */\n    modeChangedBy: prov?.changedByAgentId ?? null,\n    modeChangeSource:\n      (prov?.source as ModeHistoryEntry['source'] | 'unknown' | undefined) ?? 'unknown',\n    modeHistory: history,\n  };\n}\n\n/**\n * Apply a mode change: team.mode, objective, provenance, history, message, feed, SSE.\n * No-op if newMode === current mode (objective may still be refreshed from preset).\n */\nexport async function recordTeamModeChange(opts: {\n  teamId: string;\n  team: Team;\n  newMode: string;\n  source: ModeChangeSource;\n  actor: { id: string; name: string };\n  reason?: string;\n}): Promise<{ changed: boolean; previousMode: string }> {\n  const { teamId, team, newMode, source, actor } = opts;\n  const previousMode = team.mode || 'general';\n  const preset = (ROOM_PRESETS as Record<string, { objective?: string }>)[newMode];\n  if (!team.roomConfig) team.roomConfig = {};\n  if (previousMode === newMode) {\n    if (preset?.objective) {\n      (team.roomConfig as { objective?: string }).objective = preset.objective;\n      await persistTeamDurable(teamId);\n    }\n    return { changed: false, previousMode };\n  }\n  const now = new Date().toISOString();\n  team.mode = newMode;\n  if (preset?.objective) {\n    (team.roomConfig as { objective?: string }).objective = preset.objective;\n  }\n  (team.roomConfig as { modeProvenance: Record<string, unknown> }).modeProvenance = {\n    source,\n    changedAt: now,\n    changedByAgentId: actor.id,\n    changedByName: actor.name,\n    previousMode,\n  };\n  const histEntry: ModeHistoryEntry = {\n    mode: newMode,\n    at: now,\n    by: actor.name,\n    byAgentId: actor.id,\n    source,\n    reason: opts.reason,\n    previousMode,\n  };\n  pushModeHistory(team, histEntry);\n\n  const summary = `Mode ${previousMode} → ${newMode} (${source})`;\n  const message: TeamMessage = {\n    id: `msg_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`,\n    teamId,\n    fromAgentId: actor.id,\n    fromAgentName: actor.name,\n    content: summary,\n    messageType: 'mode_change',\n    createdAt: now,\n    modeChange: {\n      previousMode,\n      newMode,\n      source,\n      reason: opts.reason,\n    },\n  };\n  const msgs = teamMessageStore.get(teamId) || [];\n  msgs.push(message);\n  teamMessageStore.set(teamId, msgs.slice(-MESSAGES_CAP));\n\n  const feedItem: TeamModeChangeFeedItem = {\n    id: `feed_${Date.now()}_${Math.random().toString(36).slice(2, 9)}`,\n    teamId,\n    kind: 'mode_change',\n    fromMode: previousMode,\n    toMode: newMode,\n    source,\n    actorAgentId: actor.id,\n    actorAgentName: actor.name,\n    createdAt: now,\n  };\n  const list = teamFeedStore.get(teamId) || [];\n  list.push(feedItem);\n  teamFeedStore.set(teamId, list.length > FEED_CAP ? list.slice(-FEED_CAP) : list);\n\n  await persistTeamDurable(teamId);\n  broadcastToTeam(teamId, {\n    type: 'mode:changed' as any,\n    agent: actor.name,\n    data: {\n      mode: newMode,\n      objective: preset?.objective || '',\n      fromMode: previousMode,\n      source,\n    },\n  });\n\n  return { changed: true, previousMode };\n}\n","import type http from 'http';\nimport * as crypto from 'crypto';\nimport type { HoloMeshBearerCapability, HoloMeshBearerSurface, RegisteredAgent } from './types';\nimport { agentKeyStore, keyRegistry, walletToAgent } from './state';\nimport { json } from './utils';\n\nexport type ResolvedCaller = {\n  authenticated: boolean;\n  id: string;\n  name: string;\n  wallet?: string;\n  agent?: RegisteredAgent;\n  /** True when the caller's key is registered as a founder key in the key registry */\n  isFounder: boolean;\n};\n\nconst BEARER_CAPABILITIES: readonly HoloMeshBearerCapability[] = [\n  'read',\n  'message',\n  'claim',\n  'sign',\n];\n\nexport function normalizeBearerSurface(value: unknown): HoloMeshBearerSurface | undefined {\n  if (typeof value !== 'string') return undefined;\n  const surface = value.trim().toLowerCase();\n  if (!surface) return undefined;\n  if (surface === 'mobile' || surface === 'phone' || surface === 'ios' || surface === 'android') {\n    return 'mobile';\n  }\n  if (\n    surface === 'desktop' ||\n    surface === 'claude-code' ||\n    surface === 'cursor' ||\n    surface === 'vscode'\n  ) {\n    return 'desktop';\n  }\n  if (surface === 'headless' || surface === 'daemon' || surface === 'ci' || surface === 'server') {\n    return 'headless';\n  }\n  return undefined;\n}\n\nexport function normalizeBearerCapabilities(\n  value: unknown,\n  fallback: HoloMeshBearerCapability[]\n): HoloMeshBearerCapability[] {\n  const raw = Array.isArray(value) ? value : fallback;\n  const seen = new Set<HoloMeshBearerCapability>();\n  for (const item of raw) {\n    if (typeof item !== 'string') continue;\n    const capability = item.trim().toLowerCase() as HoloMeshBearerCapability;\n    if ((BEARER_CAPABILITIES as readonly string[]).includes(capability)) {\n      seen.add(capability);\n    }\n  }\n  return seen.size > 0 ? Array.from(seen) : fallback;\n}\n\nexport function hasBearerCapability(\n  agent: RegisteredAgent,\n  capability: HoloMeshBearerCapability\n): boolean {\n  // Legacy keys predate bearer-scoped capabilities; preserve behavior until\n  // they are rotated into capability-bearing records.\n  if (!Array.isArray(agent.capabilities) || agent.capabilities.length === 0) return true;\n  return agent.capabilities.includes(capability);\n}\n\n/**\n * Resolve an agent from a signed manifest header.\n *\n * Replaces the deprecated raw env-key fallback with cryptographic proof.\n * The caller provides:\n *   - x-agent-manifest: base64-encoded JSON { id, name, walletAddress, capabilities? }\n *   - x-agent-manifest-sig: base64-encoded Ed25519 signature over the canonical manifest JSON\n *\n * Verification uses the platform public key from HOLOSCRIPT_PLATFORM_PUBLIC_KEY\n * (base64-encoded SPKI DER). HoloLand agents and external integrations authenticate\n * via platform-signed manifests without needing a registry entry.\n */\nfunction resolveFromSignedManifest(req: http.IncomingMessage): ResolvedCaller | null {\n  const manifestHeader = req.headers['x-agent-manifest'];\n  const signatureHeader = req.headers['x-agent-manifest-sig'];\n  if (typeof manifestHeader !== 'string' || typeof signatureHeader !== 'string') {\n    return null;\n  }\n\n  const platformPublicKey = process.env.HOLOSCRIPT_PLATFORM_PUBLIC_KEY;\n  if (!platformPublicKey) return null;\n\n  try {\n    const manifest = JSON.parse(Buffer.from(manifestHeader, 'base64').toString('utf-8'));\n    if (\n      typeof manifest.id !== 'string' ||\n      typeof manifest.name !== 'string' ||\n      typeof manifest.walletAddress !== 'string'\n    ) {\n      return null;\n    }\n\n    const key = crypto.createPublicKey({\n      key: Buffer.from(platformPublicKey, 'base64'),\n      format: 'der',\n      type: 'spki',\n    });\n\n    const payload = JSON.stringify({\n      id: manifest.id,\n      name: manifest.name,\n      walletAddress: manifest.walletAddress,\n      capabilities: manifest.capabilities,\n    });\n\n    const valid = crypto.verify(\n      null,\n      Buffer.from(payload),\n      key,\n      Buffer.from(signatureHeader, 'base64')\n    );\n    if (!valid) return null;\n\n    const agent: RegisteredAgent = {\n      id: manifest.id,\n      name: manifest.name,\n      apiKey: manifestHeader,\n      walletAddress: manifest.walletAddress,\n      traits: Array.isArray(manifest.capabilities) ? manifest.capabilities : [],\n      reputation: 0,\n      isFounder: false,\n      createdAt: new Date().toISOString(),\n    };\n\n    return {\n      authenticated: true,\n      id: manifest.id,\n      name: manifest.name,\n      wallet: manifest.walletAddress,\n      agent,\n      isFounder: false,\n    };\n  } catch {\n    return null;\n  }\n}\n\n/**\n * Resolve the requesting agent from a Bearer token or signed manifest.\n *\n * Resolution order:\n *  1. Signed manifest (x-agent-manifest header) — platform-signed identity for\n *     HoloLand agents and external integrations without registry entries.\n *  2. Key registry (primary) — token → KeyRecord → isFounder, wallet, agentId\n *  3. Agent key store (legacy registered agents)\n */\nexport function resolveRequestingAgent(\n  req: http.IncomingMessage,\n  _client?: unknown\n): ResolvedCaller {\n  // 1. Signed manifest fallback — replaces the deprecated raw env key comparison.\n  // HoloLand agents and external integrations present a platform-signed manifest\n  // when they don't have a registry entry.\n  const manifestCaller = resolveFromSignedManifest(req);\n  if (manifestCaller) return manifestCaller;\n\n  // Accept either `Authorization: Bearer <token>` (HTTP-standard) or\n  // `x-mcp-api-key: <token>` (orchestrator convention used by the\n  // mcp-orchestrator client + most internal scripts). Closes the W.087\n  // gap-bearer-mismatch where the orchestrator client succeeds but a\n  // direct integration test using the same shared key fails 401 simply\n  // because the auth header convention diverged between layers.\n  let token: string | undefined;\n  const auth = req.headers['authorization'];\n  if (typeof auth === 'string' && auth.startsWith('Bearer ')) {\n    token = auth.slice(7).trim();\n  } else {\n    const mcpKey = req.headers['x-mcp-api-key'];\n    if (typeof mcpKey === 'string' && mcpKey.length > 0) {\n      token = mcpKey.trim();\n    }\n  }\n  if (!token) {\n    return { authenticated: false, id: 'anonymous', name: 'anonymous', isFounder: false };\n  }\n\n  // 2. Key registry lookup (primary path — covers all provisioned + founder keys)\n  const record = keyRegistry.get(token);\n  if (record) {\n    // Reject expired keys before resolving identity\n    if (record.expiresAt && new Date(record.expiresAt) < new Date()) {\n      return { authenticated: false, id: 'anonymous', name: 'anonymous', isFounder: false };\n    }\n    // Prefer an existing RegisteredAgent entry for soft-compatibility with social features\n    const baseAgent: RegisteredAgent = agentKeyStore.get(token) ||\n      walletToAgent.get(record.walletAddress.toLowerCase()) || {\n        id: record.agentId,\n        apiKey: token,\n        walletAddress: record.walletAddress,\n        name: record.agentName,\n        traits: [],\n        reputation: 0,\n        isFounder: record.isFounder,\n        createdAt: record.createdAt,\n      };\n    const agent: RegisteredAgent = {\n      ...baseAgent,\n      id: record.agentId,\n      apiKey: token,\n      walletAddress: record.walletAddress,\n      name: record.agentName,\n      isFounder: record.isFounder,\n      surfaceTag: record.surfaceTag ?? baseAgent.surfaceTag,\n      surface: record.surface ?? baseAgent.surface,\n      capabilities: record.capabilities ?? baseAgent.capabilities,\n      scopes: record.scopes,\n    };\n    return {\n      authenticated: true,\n      id: record.agentId,\n      name: record.agentName,\n      wallet: record.walletAddress,\n      agent,\n      isFounder: record.isFounder,\n    };\n  }\n\n  // 2. Legacy agent key store (agents registered before key registry existed)\n  const legacyAgent = agentKeyStore.get(token);\n  if (legacyAgent) {\n    return {\n      authenticated: true,\n      id: legacyAgent.id,\n      name: legacyAgent.name,\n      wallet: legacyAgent.walletAddress,\n      agent: legacyAgent,\n      isFounder: legacyAgent.isFounder === true,\n    };\n  }\n\n  return { authenticated: false, id: 'anonymous', name: 'anonymous', isFounder: false };\n}\n\n/**\n * Guard for routes that require a registered agent.\n * Pass `{ requireFounder: true }` to additionally gate behind founder auth.\n */\nexport function requireAuth(\n  req: http.IncomingMessage,\n  res: http.ServerResponse,\n  options?: { requireFounder?: boolean }\n): RegisteredAgent | null {\n  const caller = resolveRequestingAgent(req);\n  if (!caller.authenticated || !caller.agent) {\n    const hasBearer = (req.headers['authorization'] as string | undefined)?.startsWith('Bearer ');\n    if (hasBearer) {\n      json(res, 401, { error: 'Invalid API key. Register at POST /api/holomesh/register.' });\n    } else {\n      json(res, 401, { error: 'Authentication required. Provide valid HoloMesh API key.' });\n    }\n    return null;\n  }\n  if (options?.requireFounder && !caller.isFounder) {\n    json(res, 403, { error: 'Founder authorization required.' });\n    return null;\n  }\n  return caller.agent;\n}\n","import type http from 'http';\nimport type { Team, TeamMember, TeamRole, RegisteredAgent, TeamPresenceEntry } from './types';\nimport { TEAM_ROLE_PERMISSIONS, PRESENCE_TTL_MS, MOBILE_PRESENCE_TTL_MS } from './types';\nimport { teamStore, teamPresenceStore, teamMessageStore, reloadTeam } from './state';\nimport { resolveRequestingAgent } from './auth-utils';\n\n// ── HTTP Response Helpers ─────────────────────────────────────────────────────\n\nexport function json(res: http.ServerResponse, status: number, data: any): void {\n  res.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8' });\n  res.end(JSON.stringify(data));\n}\n\nexport function parseQuery(url: string): URLSearchParams {\n  const parts = url.split('?');\n  return new URLSearchParams(parts[1] || '');\n}\n\nexport async function parseJsonBody(req: http.IncomingMessage): Promise<any> {\n  return new Promise((resolve) => {\n    const chunks: Buffer[] = [];\n    let settled = false;\n    req.on('data', (chunk) => {\n      if (settled) return;\n      chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk), 'utf-8'));\n      const totalLength = chunks.reduce((sum, c) => sum + c.length, 0);\n      if (totalLength > 2 * 1024 * 1024) {\n        // 2MB limit\n        settled = true;\n        resolve({});\n      }\n    });\n    req.on('end', () => {\n      if (settled) return;\n      const body = Buffer.concat(chunks).toString('utf-8');\n      try {\n        resolve(JSON.parse(body));\n      } catch {\n        // Check if it's form-urlencoded fallback\n        const q = new URLSearchParams(body);\n        const obj: any = {};\n        for (const [k, v] of q.entries()) obj[k] = v;\n        resolve(obj);\n      }\n    });\n  });\n}\n\nexport function extractParam(url: string, prefix: string): string {\n  const path = url.split('?')[0];\n  if (!path.startsWith(prefix)) return '';\n  return path.slice(prefix.length).split('/')[0];\n}\n\n// ── Permission Helpers ────────────────────────────────────────────────────────\n\nexport function getTeamMember(team: Team, agentId: string): TeamMember | undefined {\n  return team.members.find((m) => m.agentId === agentId);\n}\n\nexport function hasTeamPermission(team: Team, agentId: string, permission: string): boolean {\n  if (agentId === 'system') return true;\n  const member = getTeamMember(team, agentId);\n  if (!member) return false;\n  // Admin rooms: every joined member carries full permissions.\n  if (team.adminRoom === true) return true;\n  return (TEAM_ROLE_PERMISSIONS[member.role as keyof typeof TEAM_ROLE_PERMISSIONS] ?? []).includes(\n    permission\n  );\n}\n\nexport function getTeamWorkspaceId(teamId: string): string {\n  return `team:${teamId}`;\n}\n\n/**\n * Standard guard for team routes.\n * Checks if the agent is a member and has optional specific permission.\n */\nexport function requireTeamAccess(\n  req: http.IncomingMessage,\n  res: http.ServerResponse,\n  url: string,\n  permission?: string\n): { teamId: string; caller: RegisteredAgent } | null {\n  const caller = resolveRequestingAgent(req);\n  if (!caller.authenticated || !caller.agent) {\n    json(res, 401, { error: 'Authentication required' });\n    return null;\n  }\n\n  const teamId = extractParam(url, '/api/holomesh/team/');\n  const team = teamStore.get(teamId);\n  if (!team) {\n    json(res, 404, { error: 'Team not found' });\n    return null;\n  }\n\n  // Check membership using both key-registry agentId and registered-agent id\n  // (they can differ when the key registry seeds a founder alias like \"agent_founder\"\n  //  but the agent store has a timestamped id like \"agent_1776058303684_3p3i\")\n  const agentId = caller.agent?.id;\n  const member =\n    getTeamMember(team, caller.id) ||\n    (agentId && agentId !== caller.id ? getTeamMember(team, agentId) : undefined);\n  const effectiveId = member?.agentId || caller.id;\n  // System agent (IDE/copilot) intrinsically bypasses membership checks\n  if (!member && caller.id !== 'system') {\n    json(res, 403, { error: 'Not a member of this team' });\n    return null;\n  }\n\n  if (permission && !hasTeamPermission(team, effectiveId, permission)) {\n    json(res, 403, { error: `Permission denied: ${permission}` });\n    return null;\n  }\n\n  return { teamId, caller: caller.agent };\n}\n\n/**\n * Async variant of `requireTeamAccess` that reloads the team from the shared\n * backend (PostgreSQL) BEFORE the membership check. Use on mutation handlers\n * (POST /board, POST /knowledge, etc.) where a recent /join from a peer\n * replica may not yet have propagated to this replica's in-memory teamStore.\n *\n * Pattern Gamma residual: `/join` does `await reloadTeam` then `members.push`\n * + `persistTeamStore` (postgres-backed). But `requireTeamAccess` is sync and\n * reads `teamStore.get(teamId)` directly, so a write that hit replica A is\n * invisible to replica B until B's in-memory cache reloads. Symptom: caller\n * just /joined, /me on a different replica shows teams.len:0, and POST /board\n * returns 403 \"Not a member of this team\". Reloading inside the guard makes\n * the membership read see postgres-truth on every call, eliminating the\n * cross-replica visibility gap on the membership-check path.\n *\n * Cost: one postgres roundtrip per request. The original guidance here was\n * \"read paths should keep using sync requireTeamAccess for fast-path\", but\n * empirical investigation (commits 29e9a8da7 + read-path coverage follow-up,\n * task_1777932178900_isb8) found read paths exhibit the same cross-replica\n * staleness — a board write on replica A is invisible to a /board read on\n * replica B until in-memory cache bleed-through. The Pattern Gamma fix is\n * read-and-write coverage; the postgres roundtrip is the price of correctness.\n * If a fast-path read (no membership-check, no postgres traffic) is ever\n * needed, add a separate guard rather than reverting board reads to sync.\n */\nexport async function requireTeamAccessFresh(\n  req: http.IncomingMessage,\n  res: http.ServerResponse,\n  url: string,\n  permission?: string\n): Promise<{ teamId: string; caller: RegisteredAgent } | null> {\n  const teamId = extractParam(url, '/api/holomesh/team/');\n  if (teamId) {\n    await reloadTeam(teamId);\n  }\n  return requireTeamAccess(req, res, url, permission);\n}\n\nexport function normalizePresenceSurface(value: unknown): string | undefined {\n  if (typeof value !== 'string') return undefined;\n  const surface = value.trim().toLowerCase();\n  if (!surface) return undefined;\n  if (surface === 'phone' || surface === 'ios' || surface === 'android') {\n    return 'mobile';\n  }\n  return surface;\n}\n\nexport function getPresenceTtlMs(entry: Pick<TeamPresenceEntry, 'surface'>): number {\n  return normalizePresenceSurface(entry.surface) === 'mobile'\n    ? MOBILE_PRESENCE_TTL_MS\n    : PRESENCE_TTL_MS;\n}\n\nexport function isPresenceStale(\n  entry: Pick<TeamPresenceEntry, 'lastHeartbeat' | 'surface'>,\n  now = Date.now()\n): boolean {\n  const lastHeartbeat = new Date(entry.lastHeartbeat).getTime();\n  if (!Number.isFinite(lastHeartbeat)) return true;\n  return now - lastHeartbeat > getPresenceTtlMs(entry);\n}\n\n/**\n * Cleanup offline agents and reopen their claimed tasks.\n */\nexport function pruneStalePresence(teamId: string): void {\n  const presenceMap = teamPresenceStore.get(teamId);\n  if (!presenceMap) return;\n\n  const now = Date.now();\n  const deadAgentIds: string[] = [];\n\n  for (const [agentId, entry] of presenceMap) {\n    if (isPresenceStale(entry, now)) {\n      presenceMap.delete(agentId);\n      deadAgentIds.push(agentId);\n    }\n  }\n\n  if (deadAgentIds.length > 0) {\n    const team = teamStore.get(teamId);\n    if (team?.taskBoard) {\n      for (const task of team.taskBoard) {\n        if (task.status === 'claimed' && task.claimedBy && deadAgentIds.includes(task.claimedBy)) {\n          task.status = 'open';\n          const name = task.claimedByName || task.claimedBy;\n          task.claimedBy = undefined;\n          task.claimedByName = undefined;\n\n          // Log to team chat\n          const messages = teamMessageStore.get(teamId) || [];\n          messages.push({\n            id: `msg_sys_${Date.now()}`,\n            teamId,\n            fromAgentId: 'system',\n            fromAgentName: 'System',\n            content: `Task \"${task.title}\" reopened: ${name} went offline.`,\n            messageType: 'text',\n            createdAt: new Date().toISOString(),\n          });\n          teamMessageStore.set(teamId, messages.slice(-500));\n        }\n      }\n    }\n  }\n}\n","/**\n * HoloMesh Team Board MCP Tools (In-Memory Direct)\n *\n * MCP tool definitions + handlers that operate directly on in-memory\n * team stores. Avoids HTTP roundtrip to self (which fails when the\n * key registry doesn't contain the current API key).\n *\n * Tools:\n * - holomesh_board_list, holomesh_board_add, holomesh_board_claim,\n *   holomesh_board_complete, holomesh_board_done_log, holomesh_slot_assign, holomesh_mode_set,\n *   holomesh_scout, holomesh_suggest, holomesh_suggest_vote, holomesh_suggest_list\n */\n\nimport type { Tool } from '@modelcontextprotocol/sdk/types.js';\nimport {\n  addTasksToBoard,\n  claimTask,\n  completeTask,\n  appendFollowUpCommit,\n  createSuggestion,\n  voteSuggestion,\n  evaluateBoardClaimGate,\n  maintainBoard,\n  type TeamTask,\n  type DoneLogEntry,\n  type SuggestionCategory,\n} from '@holoscript/framework';\nimport { teamStore, teamPresenceStore, persistTeamDurable, reloadTeam } from './state';\nimport { broadcastToTeam } from './team-room';\nimport { recordTeamModeChange } from './mode-provenance';\nimport { normalizePresenceSurface, getPresenceTtlMs, pruneStalePresence } from './utils';\n\n// ── Helper: get team from in-memory store ──\n\nfunction getTeam(teamId: string) {\n  const team = teamStore.get(teamId);\n  if (!team)\n    throw new Error(\n      `Team not found: ${teamId} — verify HOLOMESH_TEAM_ID matches a registered team (the team store is in-memory; a restarted server has no teams until they re-register).`\n    );\n  if (!team.taskBoard) team.taskBoard = [];\n  if (!team.doneLog) team.doneLog = [];\n  return team;\n}\n\nfunction getClaimTtlMs(): number {\n  const hours = Number(process.env.HOLOMESH_CLAIM_TTL_HOURS ?? 24);\n  return Number.isFinite(hours) && hours > 0 ? hours * 60 * 60 * 1000 : 24 * 60 * 60 * 1000;\n}\n\nasync function runBoardMaintenance(teamId: string, board: TeamTask[]) {\n  const maintenance = maintainBoard(board, { claimTtlMs: getClaimTtlMs() });\n  if (maintenance.changed) await persistTeamDurable(teamId);\n  return maintenance;\n}\n\n// ── MCP Tool Definitions ──\n\nexport const boardTools: Tool[] = [\n  {\n    name: 'holomesh_board_list',\n    description:\n      'List tasks on a team board. Returns open, claimed, blocked tasks plus recent done log and slot roles. Pass tags to filter to tasks matching those capability tags. Pass status to scope to one bucket, and limit/offset to page a large board instead of returning everything (omit limit for the full board, today\\'s default behavior).',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        team_id: {\n          type: 'string',\n          description: 'The team ID to list the board for',\n        },\n        tags: {\n          type: 'array',\n          items: { type: 'string' },\n          description:\n            'Optional capability tags to filter by. Returns only tasks whose tags array contains ALL specified tags (intersection). Useful for agent-scoped board views.',\n        },\n        status: {\n          type: 'string',\n          enum: ['open', 'claimed', 'blocked'],\n          description:\n            'Optional — scope the response to a single status bucket instead of all three. Other buckets are omitted from the response entirely (not just emptied).',\n        },\n        limit: {\n          type: 'number',\n          description:\n            'Optional — maximum tasks to return per status bucket (each of open/claimed/blocked is capped independently, max 500). Omit for unbounded (current default: returns every matching task, which can be large on a busy board).',\n        },\n        offset: {\n          type: 'number',\n          description:\n            'Optional — number of tasks to skip per bucket before applying limit (default 0). Only meaningful when limit is set.',\n        },\n      },\n      required: ['team_id'],\n    },\n  },\n  {\n    name: 'holomesh_board_add',\n    description:\n      'Add one or more tasks to a team board. Each task needs a title; optional: description, priority (1-10), source, role, tags.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        team_id: {\n          type: 'string',\n          description: 'The team ID',\n        },\n        tasks: {\n          type: 'array',\n          items: {\n            type: 'object',\n            properties: {\n              title: {\n                type: 'string',\n                description: 'Task title (max 200 chars)',\n              },\n              description: {\n                type: 'string',\n                description:\n                  'Task description (max 2000 chars; longer values are truncated and surface a description_truncated warning)',\n              },\n              priority: {\n                type: 'number',\n                description: 'Priority 1-10 (1 = critical, default 5)',\n              },\n              source: {\n                type: 'string',\n                description: 'Where the task came from (e.g., \"audit\", \"manual\")',\n              },\n              role: {\n                type: 'string',\n                enum: ['coder', 'tester', 'researcher', 'reviewer', 'flex'],\n                description: 'Preferred slot role for this task',\n              },\n              tags: {\n                type: 'array',\n                items: { type: 'string' },\n                description:\n                  'Capability tags for agent routing. Agents score +2 per tag that matches their brain capability_tags (vs +1 for text-match only). Use tags from agent brains: e.g. [\"edge\",\"local-inference\",\"cael-trace\",\"holoscript-native\",\"hardware-receipt\"] for Jetson tasks.',\n              },\n              required_tags: {\n                type: 'array',\n                items: { type: 'string' },\n                description:\n                  'Hard capability gate: ONLY agents whose heartbeat presence includes ALL of these tags can claim this task. The claim endpoint returns 403 capability_mismatch for agents missing any tag. Use for tasks that must run on specific hardware (e.g. [\"edge\",\"local-inference\"] for Jetson-only tasks).',\n              },\n            },\n            required: ['title'],\n          },\n          description: 'Array of tasks to add',\n        },\n      },\n      required: ['team_id', 'tasks'],\n    },\n  },\n  {\n    name: 'holomesh_board_done_log',\n    description:\n      'Read the completed task done-log for a team board, newest-first, with limit/offset pagination. Returns compact entries for peer verification.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        team_id: {\n          type: 'string',\n          description: 'The team ID to read done-log entries for',\n        },\n        limit: {\n          type: 'number',\n          description: 'Maximum entries to return (default 30, max 200)',\n        },\n        offset: {\n          type: 'number',\n          description: 'Number of newest entries to skip before returning results (default 0)',\n        },\n      },\n      required: ['team_id'],\n    },\n  },\n  {\n    name: 'holomesh_board_claim',\n    description:\n      'Claim an open task on a team board. The task must be in \"open\" status. The calling agent becomes the assignee.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        team_id: {\n          type: 'string',\n          description: 'The team ID',\n        },\n        task_id: {\n          type: 'string',\n          description: 'The task ID to claim',\n        },\n        agent_id: {\n          type: 'string',\n          description:\n            'Provisioned agent ID for attribution (e.g. \"claude1\", \"agent_XXXX_YYYY\"). Defaults to \"mcp-agent\" when omitted.',\n        },\n        agent_name: {\n          type: 'string',\n          description: 'Display name for the claiming agent. Defaults to agent_id when omitted.',\n        },\n      },\n      required: ['team_id', 'task_id'],\n    },\n  },\n  {\n    name: 'holomesh_board_complete',\n    description:\n      'Mark a claimed task as done. Requires verification_evidence naming the concrete test, build, audit, receipt, or peer-review proof.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        team_id: {\n          type: 'string',\n          description: 'The team ID',\n        },\n        task_id: {\n          type: 'string',\n          description: 'The task ID to mark done',\n        },\n        commit: {\n          type: 'string',\n          description: 'Git commit hash as proof of work (optional)',\n        },\n        summary: {\n          type: 'string',\n          description: 'Summary of what was done (optional)',\n        },\n        verification_evidence: {\n          type: 'string',\n          description:\n            'Concrete evidence required before closure: test/build output, audit diff, receipt, or peer review handle.',\n        },\n        agent_id: {\n          type: 'string',\n          description:\n            'Provisioned agent ID for attribution. Defaults to \"mcp-agent\" when omitted.',\n        },\n        agent_name: {\n          type: 'string',\n          description: 'Display name for the completing agent. Defaults to agent_id when omitted.',\n        },\n      },\n      required: ['team_id', 'task_id', 'verification_evidence'],\n    },\n  },\n  {\n    name: 'holomesh_board_append_commit',\n    description:\n      'Append a follow-up commit to an existing done-log entry. Use when a completed task receives additional commits post-closure.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        team_id: {\n          type: 'string',\n          description: 'The team ID',\n        },\n        task_id: {\n          type: 'string',\n          description: 'The task ID whose done-log entry should receive the commit',\n        },\n        commit: {\n          type: 'string',\n          description: 'Git commit hash to append',\n        },\n        summary: {\n          type: 'string',\n          description: 'Optional summary of what the follow-up commit contains',\n        },\n        agent_id: {\n          type: 'string',\n          description:\n            'Provisioned agent ID for attribution. Defaults to \"mcp-agent\" when omitted.',\n        },\n      },\n      required: ['team_id', 'task_id', 'commit'],\n    },\n  },\n  {\n    name: 'holomesh_slot_assign',\n    description:\n      \"Set slot roles for a team. Provide an array of roles matching the team's max_slots count. Valid roles: coder, tester, researcher, reviewer, flex.\",\n    inputSchema: {\n      type: 'object',\n      properties: {\n        team_id: {\n          type: 'string',\n          description: 'The team ID',\n        },\n        roles: {\n          type: 'array',\n          items: {\n            type: 'string',\n            enum: ['coder', 'tester', 'researcher', 'reviewer', 'flex'],\n          },\n          description: 'Array of roles for each slot. Length must equal team max_slots.',\n        },\n      },\n      required: ['team_id', 'roles'],\n    },\n  },\n  {\n    name: 'holomesh_mode_set',\n    description:\n      'Set the team mode/preset. Changes the objective, rules, and task sources. Available modes: audit, research, build, review, security, stabilize, docs, planning.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        team_id: {\n          type: 'string',\n          description: 'The team ID',\n        },\n        mode: {\n          type: 'string',\n          enum: [\n            'audit',\n            'research',\n            'build',\n            'review',\n            'security',\n            'stabilize',\n            'docs',\n            'planning',\n          ],\n          description: 'The mode to switch to',\n        },\n      },\n      required: ['team_id', 'mode'],\n    },\n  },\n  {\n    name: 'holomesh_scout',\n    description:\n      'Trigger an on-demand scout scan to populate the board when it is empty. Pass grep TODO/FIXME output as todo_content, or doc file contents as sources. Any agent can call this — it does NOT consume a team slot.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        team_id: {\n          type: 'string',\n          description: 'The team ID',\n        },\n        todo_content: {\n          type: 'string',\n          description:\n            'Grep output of TODO/FIXME markers (path:line: // TODO: message format). Each line becomes a task.',\n        },\n        sources: {\n          type: 'array',\n          items: {\n            type: 'object',\n            properties: {\n              name: { type: 'string', description: 'Source file name (e.g., ROADMAP.md)' },\n              content: { type: 'string', description: 'File content to derive tasks from' },\n            },\n            required: ['name', 'content'],\n          },\n          description: 'Doc files to derive tasks from (checkboxes, headers, TODOs)',\n        },\n        max_tasks: {\n          type: 'number',\n          description: 'Max tasks to create (default 50, max 100)',\n        },\n      },\n      required: ['team_id'],\n    },\n  },\n  {\n    name: 'holomesh_suggest',\n    description:\n      'Propose an improvement to the team. Other agents can vote on it. If enough agents upvote, it auto-promotes to a real board task. Categories: process, tooling, architecture, testing, docs, performance, other.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        team_id: {\n          type: 'string',\n          description: 'The team ID',\n        },\n        title: {\n          type: 'string',\n          description: 'Short title for the suggestion (max 200 chars)',\n        },\n        description: {\n          type: 'string',\n          description: 'Detailed description of the improvement (max 2000 chars)',\n        },\n        category: {\n          type: 'string',\n          enum: ['process', 'tooling', 'architecture', 'testing', 'docs', 'performance', 'other'],\n          description: 'Category of the suggestion',\n        },\n        evidence: {\n          type: 'string',\n          description: 'What you observed that led to this suggestion (optional, max 1000 chars)',\n        },\n        agent_id: {\n          type: 'string',\n          description:\n            'Provisioned agent ID for attribution (e.g. \"claude1\", \"agent_XXXX_YYYY\"). Defaults to \"mcp-agent\" when omitted.',\n        },\n        agent_name: {\n          type: 'string',\n          description: 'Display name for the proposing agent. Defaults to agent_id when omitted.',\n        },\n      },\n      required: ['team_id', 'title'],\n    },\n  },\n  {\n    name: 'holomesh_suggest_vote',\n    description:\n      'Vote on a team suggestion. +1 to support, -1 to oppose. Suggestions auto-promote to board tasks when they reach majority support, or auto-dismiss at majority opposition.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        team_id: {\n          type: 'string',\n          description: 'The team ID',\n        },\n        suggestion_id: {\n          type: 'string',\n          description: 'The suggestion ID to vote on',\n        },\n        value: {\n          type: 'number',\n          enum: [1, -1],\n          description: '+1 to support, -1 to oppose',\n        },\n        reason: {\n          type: 'string',\n          description: 'Optional reason for your vote (max 500 chars)',\n        },\n        agent_id: {\n          type: 'string',\n          description:\n            'Provisioned agent ID for attribution (e.g. \"claude1\", \"agent_XXXX_YYYY\"). Defaults to \"mcp-agent\" when omitted.',\n        },\n        agent_name: {\n          type: 'string',\n          description: 'Display name for the voting agent. Defaults to agent_id when omitted.',\n        },\n      },\n      required: ['team_id', 'suggestion_id', 'value'],\n    },\n  },\n  {\n    name: 'holomesh_suggest_list',\n    description:\n      'List all suggestions for a team, sorted by score. Optionally filter by status: open, promoted, dismissed.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        team_id: {\n          type: 'string',\n          description: 'The team ID',\n        },\n        status: {\n          type: 'string',\n          enum: ['open', 'promoted', 'dismissed'],\n          description: 'Filter by status (optional, default: all)',\n        },\n      },\n      required: ['team_id'],\n    },\n  },\n  {\n    name: 'holomesh_heartbeat',\n    description:\n      'Send a presence heartbeat to keep the agent alive on the team. Call every 60 seconds during active work. Missing 2 heartbeats marks the agent as offline and releases its slot.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        team_id: {\n          type: 'string',\n          description: 'The team ID',\n        },\n        agent_id: {\n          type: 'string',\n          description:\n            'Stable agent identifier for this presence slot. Use a provisioned agent ID (e.g. \"claude1\", \"agent_XXXX_YYYY\") so board mutations are attributed to a persistent identity rather than the ephemeral \"mcp-agent\" default.',\n        },\n        agent_name: {\n          type: 'string',\n          description: 'Display name of the calling agent',\n        },\n        ide_type: {\n          type: 'string',\n          description: 'IDE type (vscode, claude-code, cursor, gemini)',\n        },\n        surface: {\n          type: 'string',\n          description: 'Optional device surface for aliveness policy (mobile uses a shorter TTL)',\n        },\n        capability_tags: {\n          type: 'array',\n          items: { type: 'string' },\n          description:\n            'Capability tags this agent supports (e.g. [\"edge\",\"local-inference\"]). Stored in presence and enforced against task required_tags on claim.',\n        },\n      },\n      required: ['team_id'],\n    },\n  },\n  {\n    name: 'holomesh_presence',\n    description:\n      'List all live agents currently on the team. Returns presence entries pruned of stale heartbeats — use this to see who is online, their surface, wallet, and last heartbeat time. This reads team-local presence (agents that heartbeat via holoscript-agent runner or holomesh_heartbeat) — distinct from the public agent marketplace queried by holomesh_discover.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        team_id: {\n          type: 'string',\n          description: 'The team ID',\n        },\n      },\n      required: ['team_id'],\n    },\n  },\n  {\n    name: 'holomesh_knowledge_read',\n    description:\n      'Read team knowledge entries (Wisdom/Pattern/Gotcha). Call at session start to learn what other agents discovered. Returns the most recent entries.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        team_id: {\n          type: 'string',\n          description: 'The team ID',\n        },\n        limit: {\n          type: 'number',\n          description: 'Max entries to return (default 20)',\n        },\n      },\n      required: ['team_id'],\n    },\n  },\n];\n\n// ── MCP Tool Handler ──\n\n/**\n * Handle MCP tool calls for team board operations.\n * Returns null if the tool name is not a board tool.\n */\nexport async function handleBoardTool(\n  name: string,\n  args: Record<string, unknown>\n): Promise<unknown | null> {\n  switch (name) {\n    case 'holomesh_board_list':\n      return handleBoardList(args);\n    case 'holomesh_board_add':\n      return handleBoardAdd(args);\n    case 'holomesh_board_done_log':\n      return handleBoardDoneLog(args);\n    case 'holomesh_board_claim':\n      return handleBoardClaim(args);\n    case 'holomesh_board_complete':\n      return handleBoardComplete(args);\n    case 'holomesh_board_append_commit':\n      return handleBoardAppendCommit(args);\n    case 'holomesh_slot_assign':\n      return handleSlotAssign(args);\n    case 'holomesh_mode_set':\n      return handleModeSet(args);\n    case 'holomesh_scout':\n      return handleScout(args);\n    case 'holomesh_suggest':\n      return handleSuggest(args);\n    case 'holomesh_suggest_vote':\n      return handleSuggestVote(args);\n    case 'holomesh_suggest_list':\n      return handleSuggestList(args);\n    case 'holomesh_heartbeat':\n      return handleHeartbeat(args);\n    case 'holomesh_presence':\n      return handlePresence(args);\n    case 'holomesh_knowledge_read':\n      return handleKnowledgeRead(args);\n    default:\n      return null;\n  }\n}\n\n// ── Individual Handlers (in-memory, no HTTP roundtrip) ──\n\nasync function handleBoardList(args: Record<string, unknown>): Promise<Record<string, unknown>> {\n  const teamId = args.team_id as string;\n  if (!teamId) return { error: '\"team_id\" is required.' };\n  try {\n    await reloadTeam(teamId);\n    const team = getTeam(teamId);\n    const board = team.taskBoard || [];\n    const maintenance = await runBoardMaintenance(teamId, board);\n    const filterTags = Array.isArray(args.tags) ? (args.tags as string[]).map((t) => t.toLowerCase()) : null;\n    const tagMatch = (t: TeamTask) => {\n      if (!filterTags || filterTags.length === 0) return true;\n      const taskTags = (t.tags ?? []).map((x) => x.toLowerCase());\n      const text = `${t.title} ${t.description}`.toLowerCase();\n      return filterTags.every((ft) => taskTags.includes(ft) || text.includes(ft));\n    };\n    const statusFilter = typeof args.status === 'string' ? args.status : null;\n    const wantsBucket = (s: 'open' | 'claimed' | 'blocked') => !statusFilter || statusFilter === s;\n    const openAll = wantsBucket('open') ? board.filter((t: TeamTask) => t.status === 'open' && tagMatch(t)) : [];\n    const claimedAll = wantsBucket('claimed') ? board.filter((t: TeamTask) => t.status === 'claimed' && tagMatch(t)) : [];\n    const blockedAll = wantsBucket('blocked') ? board.filter((t: TeamTask) => t.status === 'blocked' && tagMatch(t)) : [];\n\n    // limit/offset are opt-in: omitting them preserves today's behavior (return every\n    // matching task). Passing limit pages each bucket independently — the fix for\n    // holomesh_board_list previously having no bound at all on a busy board (W.911).\n    const hasPaging = args.limit !== undefined && args.limit !== null;\n    const limit = hasPaging ? clampInteger(args.limit, 500, 1, 500) : null;\n    const offset = clampInteger(args.offset, 0, 0, Number.MAX_SAFE_INTEGER);\n    const page = <T,>(all: T[]) => {\n      if (!hasPaging) return { items: all, total: all.length, hasMore: false };\n      const items = all.slice(offset, offset + (limit as number));\n      return { items, total: all.length, hasMore: offset + items.length < all.length };\n    };\n    const openPage = page(openAll);\n    const claimedPage = page(claimedAll);\n    const blockedPage = page(blockedAll);\n\n    return {\n      success: true,\n      board: { open: openPage.items, claimed: claimedPage.items, blocked: blockedPage.items },\n      board_totals: { open: openPage.total, claimed: claimedPage.total, blocked: blockedPage.total },\n      done_count: team.doneLog?.length || 0,\n      mode: team.mode || 'general',\n      objective: team.roomConfig?.objective || '',\n      board_maintenance: {\n        priorityBackfilled: maintenance.priorityBackfilled.map((task) => task.id),\n        ttlReleased: maintenance.ttlReleased.map((task) => task.id),\n        ttlClockStarted: maintenance.ttlClockStarted.map((task) => task.id),\n        blockedEscalated: maintenance.blockedLifecycle.escalated.map((task) => task.id),\n        blockedReopened: maintenance.blockedLifecycle.reopened.map((task) => task.id),\n      },\n      ...(filterTags ? { filtered_by_tags: filterTags } : {}),\n      ...(statusFilter ? { filtered_by_status: statusFilter } : {}),\n      ...(hasPaging\n        ? { paging: { limit, offset, hasMore: openPage.hasMore || claimedPage.hasMore || blockedPage.hasMore } }\n        : {}),\n    };\n  } catch (err) {\n    return { error: err instanceof Error ? err.message : String(err) };\n  }\n}\n\nasync function handleBoardAdd(args: Record<string, unknown>): Promise<Record<string, unknown>> {\n  const teamId = args.team_id as string;\n  const tasks = args.tasks as Array<Record<string, unknown>> | undefined;\n\n  if (!teamId) return { error: '\"team_id\" is required.' };\n  if (!tasks || !Array.isArray(tasks) || tasks.length === 0) {\n    return { error: '\"tasks\" must be a non-empty array of task objects.' };\n  }\n\n  try {\n    const team = getTeam(teamId);\n    const result = addTasksToBoard(\n      team.taskBoard!,\n      team.doneLog ?? [],\n      tasks as Array<Omit<TeamTask, 'id' | 'status' | 'createdAt'>>\n    );\n    const warnings = result.warnings.length > 0\n      ? result.warnings\n      : tasks.flatMap((t) => {\n          const raw = String((t as Record<string, unknown>).description || '');\n          // In sync with board-ops.ts:300 cap (W.085 fix raised 1000→2000).\n          if (raw.length <= 2000) return [];\n          return [\n            {\n              title: String((t as Record<string, unknown>).title || '').slice(0, 200),\n              reason: 'description_truncated' as const,\n              originalLength: raw.length,\n              keptLength: 2000,\n            },\n          ];\n        });\n    team.taskBoard = result.updatedBoard;\n    await persistTeamDurable(teamId);\n\n    for (const task of result.added) {\n      broadcastToTeam(teamId, {\n        type: 'board:added',\n        agent: 'mcp-tool',\n        data: { taskId: task.id, title: task.title, agent: 'mcp-tool' },\n      });\n    }\n\n    return {\n      success: true,\n      added: result.added.length,\n      tasks: result.added,\n      skipped: result.skipped,\n      warnings,\n    };\n  } catch (err) {\n    return { error: err instanceof Error ? err.message : String(err) };\n  }\n}\n\nasync function handleBoardDoneLog(args: Record<string, unknown>): Promise<Record<string, unknown>> {\n  const teamId = args.team_id as string;\n  if (!teamId) return { error: '\"team_id\" is required.' };\n\n  try {\n    const team = getTeam(teamId);\n    const log = team.doneLog || [];\n    const total = log.length;\n    const limit = clampInteger(args.limit, 30, 1, 200);\n    const offset = clampInteger(args.offset, 0, 0, Number.MAX_SAFE_INTEGER);\n    const endRank = Math.min(total, offset + limit);\n    const entries: ReturnType<typeof compactDoneLogEntry>[] = [];\n\n    for (let rank = offset; rank < endRank; rank += 1) {\n      const entry = log[total - 1 - rank];\n      if (entry) entries.push(compactDoneLogEntry(entry));\n    }\n\n    return {\n      success: true,\n      teamId,\n      count: total,\n      returned: entries.length,\n      offset,\n      limit,\n      hasMore: endRank < total,\n      entries,\n    };\n  } catch (err) {\n    return { error: err instanceof Error ? err.message : String(err) };\n  }\n}\n\nfunction clampInteger(value: unknown, fallback: number, min: number, max: number): number {\n  const parsed = typeof value === 'number' ? value : Number.parseInt(String(value ?? ''), 10);\n  if (!Number.isFinite(parsed)) return fallback;\n  return Math.min(max, Math.max(min, Math.trunc(parsed)));\n}\n\nfunction compactDoneLogEntry(entry: DoneLogEntry) {\n  return {\n    id: entry.taskId,\n    taskId: entry.taskId,\n    title: entry.title,\n    completedAt: entry.timestamp,\n    completedBy: entry.completedBy,\n    completedByTag: entry.completedByTag,\n    commitHash: entry.commitHash,\n    verification_evidence: entry.verificationEvidence,\n    verificationEvidence: entry.verificationEvidence,\n    summary: entry.summary,\n  };\n}\n\nasync function handleBoardClaim(args: Record<string, unknown>): Promise<Record<string, unknown>> {\n  const teamId = args.team_id as string;\n  const taskId = args.task_id as string;\n  const effectiveAgentId =\n    typeof args.agent_id === 'string' && args.agent_id.trim() ? args.agent_id.trim() : 'mcp-agent';\n  const effectiveAgentName =\n    typeof args.agent_name === 'string' && args.agent_name.trim()\n      ? args.agent_name.trim()\n      : effectiveAgentId;\n\n  if (!teamId) return { error: '\"team_id\" is required.' };\n  if (!taskId) return { error: '\"task_id\" is required.' };\n\n  try {\n    await reloadTeam(teamId);\n    const team = getTeam(teamId);\n\n    pruneStalePresence(teamId);\n    const agentPresence = teamPresenceStore.get(teamId)?.get(effectiveAgentId);\n    const claimTtlHours = Number(process.env.HOLOMESH_CLAIM_TTL_HOURS ?? 24);\n    const claimCap = Number(process.env.HOLOMESH_CLAIM_CAP ?? 5);\n    const gate = evaluateBoardClaimGate(team.taskBoard!, {\n      taskId,\n      agentId: effectiveAgentId,\n      isOwner: effectiveAgentId === team.ownerId,\n      hasFreshHeartbeat: Boolean(agentPresence),\n      capabilityTags: agentPresence?.capabilityTags ?? [],\n      claimCap,\n      claimTtlMs: claimTtlHours * 3600 * 1000,\n    });\n    if (gate.ttlReleased.length > 0 || gate.ttlClockStarted.length > 0) {\n      await persistTeamDurable(teamId);\n    }\n    if (!gate.ok) {\n      return {\n        error: gate.error || 'Claim failed',\n        code: gate.code,\n        active_claims: gate.active_claims,\n        claim_cap: gate.claim_cap,\n        required_tags: gate.required_tags,\n        missing_tags: gate.missing_tags,\n        agent_capability_tags: gate.agent_capability_tags,\n      };\n    }\n\n    const result = claimTask(team.taskBoard!, taskId, effectiveAgentId, effectiveAgentName);\n    if (!result.success) return { error: result.error || 'Claim failed' };\n    await persistTeamDurable(teamId);\n\n    broadcastToTeam(teamId, {\n      type: 'board:claimed',\n      agent: effectiveAgentName,\n      data: { taskId, title: result.task?.title || taskId, agent: effectiveAgentId },\n    });\n\n    return { success: true, task: result.task };\n  } catch (err) {\n    return { error: err instanceof Error ? err.message : String(err) };\n  }\n}\n\nasync function handleBoardComplete(\n  args: Record<string, unknown>\n): Promise<Record<string, unknown>> {\n  const teamId = args.team_id as string;\n  const taskId = args.task_id as string;\n  const commit = args.commit as string | undefined;\n  const summary = args.summary as string | undefined;\n  const verificationEvidence =\n    typeof args.verification_evidence === 'string'\n      ? args.verification_evidence.trim().slice(0, 2000)\n      : '';\n  const effectiveAgentId =\n    typeof args.agent_id === 'string' && args.agent_id.trim() ? args.agent_id.trim() : 'mcp-agent';\n  const effectiveAgentName =\n    typeof args.agent_name === 'string' && args.agent_name.trim()\n      ? args.agent_name.trim()\n      : effectiveAgentId;\n\n  if (!teamId) return { error: '\"team_id\" is required.' };\n  if (!taskId) return { error: '\"task_id\" is required.' };\n  if (!verificationEvidence) return { error: '\"verification_evidence\" is required.' };\n\n  try {\n    await reloadTeam(teamId);\n    const team = getTeam(teamId);\n    await runBoardMaintenance(teamId, team.taskBoard!);\n    const wrap = completeTask(team.taskBoard!, taskId, effectiveAgentId, {\n      commit,\n      summary,\n      verificationEvidence,\n    });\n    if (!wrap.result.success) return { error: wrap.result.error || 'Complete failed' };\n    team.taskBoard = wrap.updatedBoard;\n    if (wrap.result.doneEntry) {\n      if (!team.doneLog) team.doneLog = [];\n      team.doneLog.push(wrap.result.doneEntry);\n    }\n    await persistTeamDurable(teamId);\n\n    broadcastToTeam(teamId, {\n      type: 'board:completed',\n      agent: effectiveAgentName,\n      data: { taskId, title: wrap.result.task?.title || taskId, agent: effectiveAgentId },\n    });\n\n    return { success: true, task: wrap.result.task };\n  } catch (err) {\n    return { error: err instanceof Error ? err.message : String(err) };\n  }\n}\n\nasync function handleBoardAppendCommit(\n  args: Record<string, unknown>\n): Promise<Record<string, unknown>> {\n  const teamId = args.team_id as string;\n  const taskId = args.task_id as string;\n  const commit = (args.commit as string | undefined)?.trim();\n  const summary = args.summary as string | undefined;\n  const effectiveAgentId =\n    typeof args.agent_id === 'string' && args.agent_id.trim() ? args.agent_id.trim() : 'mcp-agent';\n\n  if (!teamId) return { error: '\"team_id\" is required.' };\n  if (!taskId) return { error: '\"task_id\" is required.' };\n  if (!commit) return { error: '\"commit\" is required.' };\n\n  try {\n    const team = getTeam(teamId);\n    const wrap = appendFollowUpCommit(team.doneLog || [], taskId, commit, summary);\n    if (!wrap.success) {\n      return { error: wrap.error || 'Append failed' };\n    }\n    await persistTeamDurable(teamId);\n\n    broadcastToTeam(teamId, {\n      type: 'board:commit_appended',\n      agent: effectiveAgentId,\n      data: { taskId, title: wrap.entry?.title || taskId, commit, agent: effectiveAgentId },\n    });\n\n    return { success: true, task: { id: taskId, title: wrap.entry?.title } };\n  } catch (err) {\n    return { error: err instanceof Error ? err.message : String(err) };\n  }\n}\n\nasync function handleSlotAssign(args: Record<string, unknown>): Promise<Record<string, unknown>> {\n  const teamId = args.team_id as string;\n  const roles = args.roles as string[] | undefined;\n\n  if (!teamId) return { error: '\"team_id\" is required.' };\n  if (!roles || !Array.isArray(roles) || roles.length === 0) {\n    return { error: '\"roles\" must be a non-empty array of role strings.' };\n  }\n\n  try {\n    const team = getTeam(teamId);\n    if (!team.roomConfig) team.roomConfig = {};\n    team.roomConfig.slotRoles = roles;\n    await persistTeamDurable(teamId);\n    return { success: true, roles };\n  } catch (err) {\n    return { error: err instanceof Error ? err.message : String(err) };\n  }\n}\n\nasync function handleModeSet(args: Record<string, unknown>): Promise<Record<string, unknown>> {\n  const teamId = args.team_id as string;\n  const mode = args.mode as string;\n\n  if (!teamId) return { error: '\"team_id\" is required.' };\n  if (!mode) return { error: '\"mode\" is required.' };\n\n  try {\n    const team = getTeam(teamId);\n    const { changed } = await recordTeamModeChange({\n      teamId,\n      team,\n      newMode: mode,\n      source: 'mcp_tool',\n      actor: { id: 'mcp-tool', name: 'mcp-tool' },\n    });\n    const objective = (team.roomConfig as { objective?: string } | undefined)?.objective || '';\n    if (!changed) {\n      return { success: true, mode: team.mode || mode, objective, unchanged: true };\n    }\n    return { success: true, mode, objective };\n  } catch (err) {\n    return { error: err instanceof Error ? err.message : String(err) };\n  }\n}\n\nasync function handleScout(args: Record<string, unknown>): Promise<Record<string, unknown>> {\n  const teamId = args.team_id as string;\n  if (!teamId) return { error: '\"team_id\" is required.' };\n  if (!args.todo_content) return { error: 'todo_content is required for scout' };\n\n  try {\n    const team = getTeam(teamId);\n    const todoContent = args.todo_content as string;\n    // Require comment-anchored grep format: file:linenum: [// | # | *] (TODO|FIXME|HACK|XXX): message\n    // Prevents self-derivation from string literals and non-comment occurrences.\n    const SCOUT_TODO_RE = /^.+?:\\d+:\\s*(?:\\/\\/\\s*|#\\s*|\\*\\s*)?(TODO|FIXME|HACK|XXX)\\s*:?\\s*(.+)$/i;\n    // Skip the scanner's own implementation file and test/spec files to prevent self-derivation.\n    const SCOUT_SKIP_RE = /\\bboard-tools\\.ts[:#]|(?:__tests__[/\\\\]|\\.test\\.ts[:#]|\\.spec\\.ts[:#])/;\n    const tasksBody = todoContent.split('\\n').flatMap((l) => {\n      if (SCOUT_SKIP_RE.test(l)) return [];\n      const m = SCOUT_TODO_RE.exec(l);\n      if (!m) return [];\n      const [, kind, detail] = m;\n      return [\n        {\n          title: `${kind.toUpperCase()}: ${detail.trim().slice(0, 180)}`,\n          description: `Generated from source grep:\\n\\n${l}`,\n          source: 'scout:todo-scan',\n          priority: /^FIXME$/i.test(kind) ? 2 : 1,\n        },\n      ];\n    });\n\n    const maxTasks = (args.max_tasks as number) || 50;\n    const scopedTasks = tasksBody.slice(0, maxTasks) as Array<Omit<TeamTask, 'id' | 'status' | 'createdAt'>>;\n    const result = addTasksToBoard(team.taskBoard!, team.doneLog ?? [], scopedTasks);\n    const warnings = result.warnings.length > 0\n      ? result.warnings\n      : scopedTasks.flatMap((t: { title?: string; description?: string }) => {\n          const raw = String(t.description || '');\n          // In sync with board-ops.ts:300 cap (W.085 fix raised 1000→2000).\n          if (raw.length <= 2000) return [];\n          return [\n            {\n              title: String(t.title || '').slice(0, 200),\n              reason: 'description_truncated' as const,\n              originalLength: raw.length,\n              keptLength: 2000,\n            },\n          ];\n        });\n    team.taskBoard = result.updatedBoard;\n    await persistTeamDurable(teamId);\n\n    return {\n      success: true,\n      tasks_added: result.added.length,\n      tasks: result.added,\n      skipped: result.skipped,\n      warnings,\n    };\n  } catch (err) {\n    return { error: err instanceof Error ? err.message : String(err) };\n  }\n}\n\nasync function handleSuggest(args: Record<string, unknown>): Promise<Record<string, unknown>> {\n  const teamId = args.team_id as string;\n  const title = args.title as string;\n  const effectiveAgentId =\n    typeof args.agent_id === 'string' && args.agent_id.trim() ? args.agent_id.trim() : 'mcp-agent';\n  const effectiveAgentName =\n    typeof args.agent_name === 'string' && args.agent_name.trim()\n      ? args.agent_name.trim()\n      : effectiveAgentId;\n\n  if (!teamId) return { error: '\"team_id\" is required.' };\n  if (!title) return { error: '\"title\" is required.' };\n\n  try {\n    const team = getTeam(teamId);\n    if (!team.suggestions) team.suggestions = [];\n    const result = createSuggestion(team.suggestions, {\n      title,\n      description: args.description as string | undefined,\n      category: args.category as SuggestionCategory | undefined,\n      evidence: args.evidence as string | undefined,\n      proposedBy: effectiveAgentId,\n      proposedByName: effectiveAgentName,\n    });\n    if (!result.success) {\n      return { error: result.error || 'suggestion create failed' };\n    }\n    await persistTeamDurable(teamId);\n    return { success: true, suggestion: result.suggestion };\n  } catch (err) {\n    return { error: err instanceof Error ? err.message : String(err) };\n  }\n}\n\nasync function handleSuggestVote(args: Record<string, unknown>): Promise<Record<string, unknown>> {\n  const teamId = args.team_id as string;\n  const sugId = args.suggestion_id as string;\n  const value = args.value as number;\n  const effectiveAgentId =\n    typeof args.agent_id === 'string' && args.agent_id.trim() ? args.agent_id.trim() : 'mcp-agent';\n  const effectiveAgentName =\n    typeof args.agent_name === 'string' && args.agent_name.trim()\n      ? args.agent_name.trim()\n      : effectiveAgentId;\n\n  if (!teamId) return { error: '\"team_id\" is required.' };\n  if (!sugId) return { error: '\"suggestion_id\" is required.' };\n  if (value !== 1 && value !== -1) return { error: '\"value\" must be 1 or -1.' };\n\n  try {\n    const team = getTeam(teamId);\n    if (!team.suggestions) team.suggestions = [];\n    const result = voteSuggestion(\n      team.suggestions,\n      team.taskBoard!,\n      sugId,\n      effectiveAgentId,\n      effectiveAgentName,\n      value as 1 | -1,\n      team.maxSlots ?? 20,\n      args.reason as string | undefined\n    );\n    if (!result.success) {\n      return { error: result.error || 'vote failed' };\n    }\n    await persistTeamDurable(teamId);\n    return { ...result, success: true };\n  } catch (err) {\n    return { error: err instanceof Error ? err.message : String(err) };\n  }\n}\n\nasync function handleSuggestList(args: Record<string, unknown>): Promise<Record<string, unknown>> {\n  const teamId = args.team_id as string;\n  if (!teamId) return { error: '\"team_id\" is required.' };\n\n  try {\n    const team = getTeam(teamId);\n    const suggestions = team.suggestions ?? [];\n    const status = args.status as string | undefined;\n    const filtered = status ? suggestions.filter((s) => s.status === status) : suggestions;\n    return {\n      success: true,\n      open: suggestions.filter((s) => s.status === 'open').length,\n      promoted: suggestions.filter((s) => s.status === 'promoted').length,\n      dismissed: suggestions.filter((s) => s.status === 'dismissed').length,\n      suggestions: filtered,\n    };\n  } catch (err) {\n    return { error: err instanceof Error ? err.message : String(err) };\n  }\n}\n\nasync function handleHeartbeat(args: Record<string, unknown>): Promise<Record<string, unknown>> {\n  const teamId = args.team_id as string;\n  if (!teamId) return { error: '\"team_id\" is required.' };\n\n  const agentId =\n    typeof args.agent_id === 'string' && args.agent_id.trim()\n      ? args.agent_id.trim()\n      : 'mcp-agent';\n  const agentName =\n    typeof args.agent_name === 'string' && args.agent_name.trim()\n      ? args.agent_name.trim()\n      : agentId;\n  const ideType = (args.ide_type as string) || 'mcp';\n  const surface = normalizePresenceSurface(args.surface);\n\n  try {\n    getTeam(teamId); // ensure team exists\n    let presenceMap = teamPresenceStore.get(teamId);\n    if (!presenceMap) {\n      presenceMap = new Map();\n      teamPresenceStore.set(teamId, presenceMap);\n    }\n\n    const lastHeartbeat = new Date().toISOString();\n    const ttlMs = getPresenceTtlMs({ surface });\n    const capabilityTags = Array.isArray(args.capability_tags)\n      ? (args.capability_tags as string[])\n      : undefined;\n    const entry = {\n      agentId,\n      agentName,\n      ideType,\n      status: 'active' as const,\n      lastHeartbeat,\n      surface,\n      expiresAt: new Date(Date.parse(lastHeartbeat) + ttlMs).toISOString(),\n      ttlMs,\n      capabilityTags,\n    };\n    presenceMap.set(agentId, entry);\n\n    pruneStalePresence(teamId);\n    const online = Array.from(presenceMap.values());\n    return { success: true, online, presence: entry, online_count: online.length };\n  } catch (err) {\n    return { error: err instanceof Error ? err.message : String(err) };\n  }\n}\n\nasync function handlePresence(args: Record<string, unknown>): Promise<Record<string, unknown>> {\n  const teamId = args.team_id as string;\n  if (!teamId) return { error: '\"team_id\" is required.' };\n  try {\n    getTeam(teamId);\n    pruneStalePresence(teamId);\n    const presenceMap = teamPresenceStore.get(teamId);\n    const online = presenceMap ? Array.from(presenceMap.values()) : [];\n    return { success: true, online, online_count: online.length };\n  } catch (err) {\n    return { error: err instanceof Error ? err.message : String(err) };\n  }\n}\n\nasync function handleKnowledgeRead(\n  args: Record<string, unknown>\n): Promise<Record<string, unknown>> {\n  const teamId = args.team_id as string;\n  if (!teamId) return { error: '\"team_id\" is required.' };\n\n  try {\n    const team = getTeam(teamId);\n    const entries = team.knowledge ?? [];\n    const limit = (args.limit as number) || 20;\n    return { entries: entries.slice(0, limit), total: entries.length };\n  } catch (err) {\n    return { error: err instanceof Error ? err.message : String(err) };\n  }\n}\n","// HoloMesh agents consume shared traits from the canonical core traits barrel.\nexport { agentMemoryHandler as HOLOMESH_AGENT_MEMORY_TRAIT } from '@holoscript/core/traits';\n","/**\n * Scout Agent Profile — Infrastructure, NOT a team member.\n * Used by the PM2 holoscout daemon (local-worker.ts).\n */\nimport type { TeamAgentProfile } from '@holoscript/framework';\n\nexport const SCOUT_AGENT: TeamAgentProfile = {\n  id: 'agent_scout',\n  name: 'Scout',\n  role: 'researcher',\n  capabilities: [\n    'todo-scanning',\n    'git-health-audit',\n    'dependency-audit',\n    'coverage-analysis',\n    'task-derivation',\n    'board-population',\n  ],\n  model: 'claude-haiku-4-5',\n  provider: 'anthropic',\n  claimFilter: {\n    roles: ['researcher', 'flex'],\n    maxPriority: 10,\n  },\n  systemPrompt: [\n    'You are Scout, the reconnaissance agent for HoloScript team rooms.',\n    'When the board is empty or stale, you scan the codebase for work that needs doing.',\n    'You find TODO/FIXME markers, uncommitted changes, test coverage gaps, dependency vulnerabilities,',\n    'and stale documentation — then derive actionable board tasks from your findings.',\n    'You do NOT fix things yourself. You find them, prioritize them, and put them on the board for other agents.',\n  ].join(' '),\n  knowledgeDomains: ['general', 'compilation', 'security', 'agents'],\n};\n","/**\n * HoloMesh Team Agent Profiles\n *\n * SHED: All definitions now live in @holoscript/framework.\n * This file re-exports for backward compatibility.\n */\n\nexport type {\n  SlotRole,\n  AgentRole,\n  AIProvider,\n  ClaimFilter,\n  TeamAgentProfile,\n} from '@holoscript/framework';\n\nexport {\n  PRIMARY_ASSISTANT_AGENT,\n  BRITTNEY_AGENT,\n  DAEMON_AGENT,\n  ABSORB_AGENT,\n  ORACLE_AGENT,\n  TEAM_AGENT_PROFILES,\n  getAllProfiles,\n  getProfileById,\n  getProfilesByClaimRole,\n  getProfilesByDomain,\n} from '@holoscript/framework';\n\n// Canonical HoloMesh agent traits shared with HoloLand and uAA2.\nexport { HOLOMESH_AGENT_MEMORY_TRAIT } from './shared-traits';\n\n// Scout profile stays here — it's infrastructure, not a team member\nexport { SCOUT_AGENT } from './scout-profile';\n","/**\n * HoloMesh Team Coordinator\n *\n * @deprecated FW-0.3 — This module is scheduled for removal. All work-cycle\n * logic has already been delegated to `@holoscript/framework` Team.runCycle().\n *\n * **Remaining unique logic that must migrate to framework before deletion:**\n * 1. In-memory room→agent slot store (`roomAgents` Map) — framework Team\n *    takes agents at construction time; need a `team.addAgent()` / `team.removeAgent()` API.\n * 2. `assignAgentsToRoom()` — maps TeamAgentProfile → RoomAgentSlot with\n *    role mapping and dedup. Framework needs an equivalent load-from-profile helper.\n * 3. `compoundKnowledge()` — cross-references insights by knowledge domain\n *    across agents. Framework has `knowledge.compound()` but not the per-agent\n *    domain-overlap scoring done here.\n * 4. Room lifecycle helpers (`clearRoom`, `removeAgentFromRoom`, `getRoomAgents`,\n *    `getRoomCycleHistory`) — framework Team has no multi-room management.\n *\n * Once these migrate, delete this file and update imports in:\n * - `./team-agent-tools.ts`\n * - `../index.ts`\n * - `../__tests__/team-agents.test.ts`\n *\n * Manages agent lifecycle within team rooms:\n * - Load agent profiles into rooms (register in slots)\n * - Execute work cycles (check board -> claim -> execute -> done -> publish)\n * - Compound knowledge across agents after a cycle\n *\n * Uses the board HTTP API (same as board-tools.ts) to interact with team boards.\n * Agents are stateless profiles — the coordinator drives their behavior.\n */\n\nimport type { TeamAgentProfile, SlotRole } from './team-agents';\nimport { TEAM_AGENT_PROFILES, getAllProfiles } from './team-agents';\nimport { Team as FrameworkTeam } from '@holoscript/framework';\nimport type { CycleResult as FrameworkCycleResult } from '@holoscript/framework';\nimport { resolveSecretWithLease, VaultLeaseError } from '../identity/vault-lease-registry';\n\n// ── Types ──\n\nexport interface RoomAgentSlot {\n  agentId: string;\n  agentName: string;\n  role: SlotRole;\n  joinedAt: string;\n  lastActiveAt: string;\n  tasksCompleted: number;\n  knowledgePublished: number;\n}\n\nexport interface BoardTask {\n  id: string;\n  title: string;\n  description: string;\n  status: 'open' | 'claimed' | 'done' | 'blocked';\n  claimedBy?: string;\n  claimedByName?: string;\n  priority: number;\n  role?: SlotRole;\n  source?: string;\n}\n\nexport interface CycleResult {\n  roomId: string;\n  agentId: string;\n  agentName: string;\n  taskId: string | null;\n  taskTitle: string | null;\n  action: 'claimed' | 'completed' | 'skipped' | 'error' | 'synthesized';\n  summary: string;\n  knowledgeEntries: KnowledgeInsight[];\n}\n\nexport interface KnowledgeInsight {\n  type: 'wisdom' | 'pattern' | 'gotcha';\n  content: string;\n  domain: string;\n  confidence: number;\n}\n\nexport interface CompoundResult {\n  roomId: string;\n  agentsInvolved: string[];\n  insightsShared: number;\n  crossReferences: number;\n  timestamp: string;\n}\n\nexport interface LoadAgentsResult {\n  roomId: string;\n  loaded: RoomAgentSlot[];\n  skipped: string[];\n}\n\n// ── In-Memory Room Agent Store ──\n\nconst roomAgents: Map<string, Map<string, RoomAgentSlot>> = new Map();\nconst roomCycleHistory: Map<string, CycleResult[]> = new Map();\n\n// ── Server URL / Auth (mirrors board-tools.ts) ──\n\nfunction getServerUrl(): string {\n  return (\n    process.env.HOLOSCRIPT_SERVER_URL || process.env.MCP_LOCAL_URL || 'https://mcp.holoscript.net'\n  );\n}\n\n/**\n * Phase 3 wrapper around the sub-agent-delegation auth header. `getApiKey`\n * is called per `runRoomCycle` invocation (each call = one team work cycle\n * = a per-task action), so it falls cleanly into the Phase 3 medium-risk\n * tier the task targets (\"sub-agent delegation auth\"). The original\n * fallback chain `HOLOMESH_API_KEY || HOLOSCRIPT_API_KEY` is preserved by\n * resolving each ref through the lease helper independently — a lease\n * scoped to only one will NOT silently fall through to the other under\n * `HOLOMESH_VAULT_LEASE_ENFORCE`.\n */\nfunction getApiKey(): string {\n  const tryRead = (ref: 'env:HOLOMESH_API_KEY' | 'env:HOLOSCRIPT_API_KEY'): string => {\n    try {\n      return resolveSecretWithLease(ref) ?? '';\n    } catch (err) {\n      if (err instanceof VaultLeaseError) return '';\n      throw err;\n    }\n  };\n  return tryRead('env:HOLOMESH_API_KEY') || tryRead('env:HOLOSCRIPT_API_KEY') || '';\n}\n\nfunction getCanonicalAgentId(agentId: string): string | undefined {\n  return TEAM_AGENT_PROFILES.get(agentId)?.id;\n}\n\nfunction agentIdsReferToSameProfile(leftAgentId: string, rightAgentId: string): boolean {\n  if (leftAgentId === rightAgentId) return true;\n  const leftCanonicalId = getCanonicalAgentId(leftAgentId);\n  const rightCanonicalId = getCanonicalAgentId(rightAgentId);\n  return Boolean(leftCanonicalId && rightCanonicalId && leftCanonicalId === rightCanonicalId);\n}\n\nfunction findLoadedAgentKey(\n  slots: Map<string, RoomAgentSlot>,\n  agentId: string\n): string | undefined {\n  for (const [slotKey, slot] of slots) {\n    if (agentIdsReferToSameProfile(slot.agentId, agentId)) {\n      return slotKey;\n    }\n  }\n  return undefined;\n}\n\n// ── Core Functions ──\n\n/**\n * Load agent profiles into a team room.\n * Each profile is mapped to a slot role based on its primary role.\n * Skips agents whose role slot is already occupied.\n * @deprecated FW-0.3 — migrate to framework Team constructor + addAgent() API\n */\nexport function assignAgentsToRoom(roomId: string, agentProfileIds: string[]): LoadAgentsResult {\n  if (!roomAgents.has(roomId)) {\n    roomAgents.set(roomId, new Map());\n  }\n  const slots = roomAgents.get(roomId)!;\n\n  const loaded: RoomAgentSlot[] = [];\n  const skipped: string[] = [];\n\n  for (const profileId of agentProfileIds) {\n    const profile = TEAM_AGENT_PROFILES.get(profileId);\n    if (!profile) {\n      skipped.push(profileId);\n      continue;\n    }\n\n    if (findLoadedAgentKey(slots, profileId)) {\n      skipped.push(profileId);\n      continue;\n    }\n\n    const roleAsSlot = mapAgentRoleToSlot(profile.role);\n    const now = new Date().toISOString();\n    const slot: RoomAgentSlot = {\n      agentId: profileId,\n      agentName: profile.name,\n      role: roleAsSlot,\n      joinedAt: now,\n      lastActiveAt: now,\n      tasksCompleted: 0,\n      knowledgePublished: 0,\n    };\n\n    slots.set(profileId, slot);\n    loaded.push(slot);\n  }\n\n  return { roomId, loaded, skipped };\n}\n\n/**\n * Map agent role to the closest slot role.\n * architect -> reviewer (architects review and guide)\n * coder -> coder\n * researcher -> researcher\n * reviewer -> reviewer\n */\nfunction mapAgentRoleToSlot(role: string): SlotRole {\n  switch (role) {\n    case 'architect':\n      return 'reviewer';\n    case 'coder':\n      return 'coder';\n    case 'researcher':\n      return 'researcher';\n    case 'reviewer':\n      return 'reviewer';\n    default:\n      return 'flex';\n  }\n}\n\n/**\n * Execute one work cycle for all agents in a room.\n * Delegates to @holoscript/framework Team.runCycle() for the core\n * claim/execute/done loop. Adapts the result back to the coordinator's\n * CycleResult[] shape for backward compatibility.\n * @deprecated FW-0.3 — use framework Team.runCycle() directly\n */\nexport async function runAgentCycle(roomId: string): Promise<CycleResult[]> {\n  const slots = roomAgents.get(roomId);\n  if (!slots || slots.size === 0) {\n    return [];\n  }\n\n  // Build a Framework Team from the registered agent profiles\n  const agentConfigs = Array.from(slots.values())\n    .map((slot) => {\n      const profile = TEAM_AGENT_PROFILES.get(slot.agentId);\n      if (!profile) return null;\n      return {\n        name: profile.name,\n        role: profile.role as 'architect' | 'coder' | 'researcher' | 'reviewer',\n        model: {\n          provider: profile.provider as 'anthropic' | 'openai' | 'xai',\n          model: profile.model,\n        },\n        capabilities: profile.capabilities,\n        claimFilter: {\n          roles: profile.claimFilter.roles,\n          maxPriority: profile.claimFilter.maxPriority,\n        },\n        systemPrompt: profile.systemPrompt,\n        knowledgeDomains: profile.knowledgeDomains,\n      };\n    })\n    .filter((c): c is NonNullable<typeof c> => c !== null);\n\n  if (agentConfigs.length === 0) {\n    return Array.from(slots.values()).map((slot) => ({\n      roomId,\n      agentId: slot.agentId,\n      agentName: slot.agentName,\n      taskId: null,\n      taskTitle: null,\n      action: 'skipped' as const,\n      summary: 'No profile found for agent',\n      knowledgeEntries: [],\n    }));\n  }\n\n  const serverUrl = getServerUrl();\n  const apiKey = getApiKey();\n\n  const frameworkTeam = new FrameworkTeam({\n    name: roomId,\n    agents: agentConfigs,\n    boardUrl: serverUrl,\n    boardApiKey: apiKey,\n  });\n\n  // Run the framework cycle (handles claim/execute/done via API)\n  const fwResult: FrameworkCycleResult = await frameworkTeam.runCycle();\n\n  // Adapt framework results → coordinator CycleResult[]\n  const results: CycleResult[] = fwResult.agentResults.map((ar) => {\n    const slot = Array.from(slots.values()).find((s) => s.agentName === ar.agentName);\n    const agentId = slot?.agentId || ar.agentName;\n\n    // Update slot stats\n    if (slot && ar.action === 'completed') {\n      slot.tasksCompleted += 1;\n      slot.knowledgePublished += ar.knowledge.length;\n      slot.lastActiveAt = new Date().toISOString();\n    }\n\n    return {\n      roomId,\n      agentId,\n      agentName: ar.agentName,\n      taskId: ar.taskId,\n      taskTitle: ar.taskTitle,\n      action: ar.action,\n      summary: ar.summary,\n      knowledgeEntries: ar.knowledge.map((k) => ({\n        type: k.type,\n        content: k.content,\n        domain: k.domain,\n        confidence: k.confidence,\n      })),\n    };\n  });\n\n  // Store cycle history\n  const history = roomCycleHistory.get(roomId) || [];\n  history.push(...results);\n  if (history.length > 100) {\n    history.splice(0, history.length - 100);\n  }\n  roomCycleHistory.set(roomId, history);\n\n  return results;\n}\n\n/**\n * After a cycle, agents cross-pollinate findings.\n * Each agent's insights are shared with agents in overlapping knowledge domains.\n * @deprecated FW-0.3 — migrate domain-overlap scoring to framework KnowledgeStore.compound()\n */\nexport function compoundKnowledge(roomId: string): CompoundResult {\n  const history = roomCycleHistory.get(roomId) || [];\n  const slots = roomAgents.get(roomId);\n\n  if (!slots || slots.size === 0) {\n    return {\n      roomId,\n      agentsInvolved: [],\n      insightsShared: 0,\n      crossReferences: 0,\n      timestamp: new Date().toISOString(),\n    };\n  }\n\n  // Collect all insights from the most recent cycle\n  const recentInsights: Array<{ agentId: string; insight: KnowledgeInsight }> = [];\n  for (const result of history) {\n    if (result.roomId === roomId) {\n      for (const insight of result.knowledgeEntries) {\n        recentInsights.push({ agentId: result.agentId, insight });\n      }\n    }\n  }\n\n  // Cross-reference: for each agent, count how many insights from other agents\n  // overlap with their knowledge domains\n  let crossReferences = 0;\n  const agentIds = Array.from(slots.keys());\n\n  for (const agentId of agentIds) {\n    const profile = TEAM_AGENT_PROFILES.get(agentId);\n    if (!profile) continue;\n\n    for (const { agentId: sourceAgentId, insight } of recentInsights) {\n      if (sourceAgentId === agentId) continue; // skip own insights\n      if (profile.knowledgeDomains.includes(insight.domain)) {\n        crossReferences += 1;\n      }\n    }\n  }\n\n  return {\n    roomId,\n    agentsInvolved: agentIds,\n    insightsShared: recentInsights.length,\n    crossReferences,\n    timestamp: new Date().toISOString(),\n  };\n}\n\n// ── Query Functions ──\n\n/** Get all agent slots in a room @deprecated FW-0.3 */\nexport function getRoomAgents(roomId: string): RoomAgentSlot[] {\n  const slots = roomAgents.get(roomId);\n  return slots ? Array.from(slots.values()) : [];\n}\n\n/** Get cycle history for a room @deprecated FW-0.3 */\nexport function getRoomCycleHistory(roomId: string): CycleResult[] {\n  return roomCycleHistory.get(roomId) || [];\n}\n\n/** Remove an agent from a room @deprecated FW-0.3 */\nexport function removeAgentFromRoom(roomId: string, agentId: string): boolean {\n  const slots = roomAgents.get(roomId);\n  if (!slots) return false;\n  const loadedAgentKey = findLoadedAgentKey(slots, agentId);\n  return loadedAgentKey ? slots.delete(loadedAgentKey) : false;\n}\n\n/** Clear all agents and history for a room @deprecated FW-0.3 */\nexport function clearRoom(roomId: string): void {\n  roomAgents.delete(roomId);\n  roomCycleHistory.delete(roomId);\n}\n\n// ── For testing: reset all state ──\n\nexport function _resetState(): void {\n  roomAgents.clear();\n  roomCycleHistory.clear();\n}\n","/**\n * HoloMesh Team Agent MCP Tools\n *\n * MCP tool wrappers for team agent coordination:\n * - holomesh_team_load_agents: Load agent profiles into a team room\n * - holomesh_team_run_cycle: Execute one work cycle for agents in a room\n * - holomesh_team_compound: Trigger knowledge compounding across agents\n * - holomesh_autonomous_control: Start/stop/query autonomous room loops\n */\n\nimport type { Tool } from '@modelcontextprotocol/sdk/types.js';\nimport {\n  assignAgentsToRoom,\n  runAgentCycle,\n  compoundKnowledge,\n  getRoomAgents,\n} from './agent/team-coordinator';\nimport { getAllProfiles, TEAM_AGENT_PROFILES } from './agent/team-agents';\n\ntype AutonomousAction = 'start' | 'stop' | 'status' | 'query' | 'tick';\n\ninterface AutonomousLoopState {\n  loopId: string;\n  teamId: string;\n  intervalMs: number;\n  startedAt: string;\n  lastTickAt?: string;\n  stoppedAt?: string;\n  status: 'running' | 'stopped';\n  cycleCount: number;\n  maxCycles?: number;\n  compoundAfterCycle: boolean;\n  runningTick: boolean;\n  lastResult?: unknown;\n  lastError?: string;\n  timer?: ReturnType<typeof setInterval>;\n}\n\nconst autonomousLoops = new Map<string, AutonomousLoopState>();\n\n// ── MCP Tool Definitions ──\n\nexport const teamAgentTools: Tool[] = [\n  {\n    name: 'holomesh_team_load_agents',\n    description:\n      'Load agent profiles into a team room. Agents are assigned slot roles and can then participate in work cycles. Pass agent_ids to load specific agents, or omit to load all built-in agents (Brittney, Daemon, Absorb, Oracle).',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        team_id: {\n          type: 'string',\n          description: 'The team room ID to load agents into',\n        },\n        agent_ids: {\n          type: 'array',\n          items: { type: 'string' },\n          description:\n            'Agent profile IDs to load. Available: agent_primary_assistant (legacy alias: agent_brittney), agent_daemon, agent_absorb, agent_oracle. Omit to load all.',\n        },\n      },\n      required: ['team_id'],\n    },\n  },\n  {\n    name: 'holomesh_team_run_cycle',\n    description:\n      'Execute one work cycle for all agents loaded in a team room. Each agent checks the board, claims a matching task, executes it, marks it done, and generates knowledge insights.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        team_id: {\n          type: 'string',\n          description: 'The team room ID to run the cycle in',\n        },\n      },\n      required: ['team_id'],\n    },\n  },\n  {\n    name: 'holomesh_team_compound',\n    description:\n      'Trigger knowledge compounding for a team room. After a work cycle, agents cross-pollinate their findings — insights from one agent are shared with agents in overlapping knowledge domains.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        team_id: {\n          type: 'string',\n          description: 'The team room ID to compound knowledge for',\n        },\n      },\n      required: ['team_id'],\n    },\n  },\n  {\n    name: 'holomesh_autonomous_control',\n    description:\n      'Start, stop, query, or tick an autonomous agent loop for a HoloMesh team room. The loop reuses holomesh_team_run_cycle semantics and can optionally compound knowledge after each cycle.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        action: {\n          type: 'string',\n          enum: ['start', 'stop', 'status', 'query', 'tick'],\n          description: 'Control action. \"query\" is an alias for \"status\". Defaults to status.',\n        },\n        team_id: {\n          type: 'string',\n          description:\n            'Team room ID. Required for start and tick. Used as loop_id when loop_id is omitted.',\n        },\n        loop_id: {\n          type: 'string',\n          description: 'Optional loop ID. Defaults to team_id.',\n        },\n        agent_ids: {\n          type: 'array',\n          items: { type: 'string' },\n          description:\n            'Optional agent profile IDs to load before starting the loop. Uses existing loaded agents when omitted.',\n        },\n        interval_ms: {\n          type: 'number',\n          description: 'Cycle interval in milliseconds. Clamped to 5000..3600000. Default 60000.',\n        },\n        max_cycles: {\n          type: 'number',\n          description: 'Optional maximum cycle count before the loop stops itself.',\n        },\n        run_immediately: {\n          type: 'boolean',\n          description: 'When true, execute one cycle before returning from start.',\n        },\n        compound_after_cycle: {\n          type: 'boolean',\n          description: 'When true, run holomesh_team_compound after each cycle.',\n        },\n      },\n    },\n  },\n];\n\n// ── MCP Tool Handler ──\n\n/**\n * Handle MCP tool calls for team agent operations.\n * Returns null if the tool name is not a team agent tool.\n */\nexport async function handleTeamAgentTool(\n  name: string,\n  args: Record<string, unknown>\n): Promise<unknown | null> {\n  switch (name) {\n    case 'holomesh_team_load_agents':\n      return handleLoadAgents(args);\n    case 'holomesh_team_run_cycle':\n      return handleRunCycle(args);\n    case 'holomesh_team_compound':\n      return handleCompound(args);\n    case 'holomesh_autonomous_control':\n      return handleAutonomousControl(args);\n    default:\n      return null;\n  }\n}\n\n// ── Individual Handlers ──\n\nfunction handleLoadAgents(args: Record<string, unknown>): Record<string, unknown> {\n  const teamId = args.team_id as string;\n  if (!teamId) {\n    return { error: '\"team_id\" is required.' };\n  }\n\n  let agentIds = args.agent_ids as string[] | undefined;\n  if (!agentIds || !Array.isArray(agentIds) || agentIds.length === 0) {\n    // Load all built-in agents\n    agentIds = getAllProfiles().map((p) => p.id);\n  }\n\n  // Validate agent IDs\n  const unknownIds = agentIds.filter((id) => !TEAM_AGENT_PROFILES.has(id));\n  if (unknownIds.length > 0) {\n    return {\n      error: `Unknown agent profile IDs: ${unknownIds.join(', ')}. Available: ${getAllProfiles()\n        .map((p) => p.id)\n        .join(', ')}`,\n    };\n  }\n\n  const result = assignAgentsToRoom(teamId, agentIds);\n  return {\n    success: true,\n    roomId: result.roomId,\n    loaded: result.loaded.map((s) => ({\n      agentId: s.agentId,\n      agentName: s.agentName,\n      role: s.role,\n      joinedAt: s.joinedAt,\n    })),\n    skipped: result.skipped,\n    totalAgentsInRoom: getRoomAgents(teamId).length,\n  };\n}\n\nasync function handleRunCycle(args: Record<string, unknown>): Promise<Record<string, unknown>> {\n  const teamId = args.team_id as string;\n  if (!teamId) {\n    return { error: '\"team_id\" is required.' };\n  }\n\n  const agents = getRoomAgents(teamId);\n  if (agents.length === 0) {\n    return {\n      error: `No agents loaded in room \"${teamId}\". Use holomesh_team_load_agents first.`,\n    };\n  }\n\n  const results = await runAgentCycle(teamId);\n\n  const completed = results.filter((r) => r.action === 'completed');\n  const skipped = results.filter((r) => r.action === 'skipped');\n  const errors = results.filter((r) => r.action === 'error');\n  const totalInsights = results.reduce((sum, r) => sum + r.knowledgeEntries.length, 0);\n\n  return {\n    success: true,\n    roomId: teamId,\n    summary: {\n      completed: completed.length,\n      skipped: skipped.length,\n      errors: errors.length,\n      totalInsights,\n    },\n    results: results.map((r) => ({\n      agentId: r.agentId,\n      agentName: r.agentName,\n      action: r.action,\n      taskId: r.taskId,\n      taskTitle: r.taskTitle,\n      summary: r.summary,\n      insightCount: r.knowledgeEntries.length,\n    })),\n  };\n}\n\nfunction handleCompound(args: Record<string, unknown>): Record<string, unknown> {\n  const teamId = args.team_id as string;\n  if (!teamId) {\n    return { error: '\"team_id\" is required.' };\n  }\n\n  const agents = getRoomAgents(teamId);\n  if (agents.length === 0) {\n    return {\n      error: `No agents loaded in room \"${teamId}\". Use holomesh_team_load_agents first.`,\n    };\n  }\n\n  const result = compoundKnowledge(teamId);\n\n  return {\n    success: true,\n    roomId: result.roomId,\n    agentsInvolved: result.agentsInvolved,\n    insightsShared: result.insightsShared,\n    crossReferences: result.crossReferences,\n    timestamp: result.timestamp,\n  };\n}\n\nasync function handleAutonomousControl(\n  args: Record<string, unknown>\n): Promise<Record<string, unknown>> {\n  const action = normalizeAutonomousAction(args.action);\n  const teamId = stringOrUndefined(args.team_id);\n  const loopId = stringOrUndefined(args.loop_id) || teamId;\n\n  if ((action === 'start' || action === 'tick') && !teamId) {\n    return { error: '\"team_id\" is required for holomesh_autonomous_control start/tick.' };\n  }\n  if ((action === 'stop' || action === 'status' || action === 'query') && !loopId) {\n    return {\n      success: true,\n      loops: Array.from(autonomousLoops.values()).map(serializeLoop),\n      count: autonomousLoops.size,\n    };\n  }\n\n  switch (action) {\n    case 'start':\n      return startAutonomousLoop(args, teamId!, loopId!);\n    case 'stop':\n      return stopAutonomousLoop(loopId!);\n    case 'tick':\n      return tickAutonomousLoop(args, teamId!, loopId!);\n    case 'query':\n    case 'status':\n      return statusAutonomousLoop(loopId!);\n  }\n}\n\nasync function startAutonomousLoop(\n  args: Record<string, unknown>,\n  teamId: string,\n  loopId: string\n): Promise<Record<string, unknown>> {\n  const existing = autonomousLoops.get(loopId);\n  if (existing?.status === 'running') {\n    return {\n      success: true,\n      message: `Autonomous loop \"${loopId}\" is already running.`,\n      loop: serializeLoop(existing),\n    };\n  }\n\n  const loaded = ensureAutonomousAgents(teamId, args.agent_ids);\n  if ('error' in loaded) return loaded;\n\n  const intervalMs = clampNumber(args.interval_ms, 60_000, 5_000, 3_600_000);\n  const maxCycles = optionalPositiveInteger(args.max_cycles);\n  const loop: AutonomousLoopState = {\n    loopId,\n    teamId,\n    intervalMs,\n    startedAt: new Date().toISOString(),\n    status: 'running',\n    cycleCount: 0,\n    maxCycles,\n    compoundAfterCycle: args.compound_after_cycle === true,\n    runningTick: false,\n  };\n  loop.timer = setInterval(() => {\n    void runAutonomousLoopOnce(loop);\n  }, intervalMs);\n  const timerWithUnref = loop.timer as { unref?: () => void };\n  timerWithUnref.unref?.();\n\n  autonomousLoops.set(loopId, loop);\n\n  if (args.run_immediately === true) {\n    await runAutonomousLoopOnce(loop);\n  }\n\n  return {\n    success: true,\n    message: `Autonomous loop \"${loopId}\" started.`,\n    loadedAgents: loaded.loadedAgents,\n    loop: serializeLoop(loop),\n  };\n}\n\nfunction stopAutonomousLoop(loopId: string): Record<string, unknown> {\n  const loop = autonomousLoops.get(loopId);\n  if (!loop) {\n    return {\n      success: false,\n      error: `Autonomous loop \"${loopId}\" is not running.`,\n      loopId,\n    };\n  }\n\n  stopLoop(loop);\n  autonomousLoops.delete(loopId);\n  return {\n    success: true,\n    message: `Autonomous loop \"${loopId}\" stopped.`,\n    loop: serializeLoop(loop),\n  };\n}\n\nasync function tickAutonomousLoop(\n  args: Record<string, unknown>,\n  teamId: string,\n  loopId: string\n): Promise<Record<string, unknown>> {\n  const loaded = ensureAutonomousAgents(teamId, args.agent_ids);\n  if ('error' in loaded) return loaded;\n\n  const loop =\n    autonomousLoops.get(loopId) ||\n    ({\n      loopId,\n      teamId,\n      intervalMs: 0,\n      startedAt: new Date().toISOString(),\n      status: 'stopped',\n      cycleCount: 0,\n      compoundAfterCycle: args.compound_after_cycle === true,\n      runningTick: false,\n    } satisfies AutonomousLoopState);\n\n  await runAutonomousLoopOnce(loop);\n  return {\n    success: !loop.lastError,\n    loadedAgents: loaded.loadedAgents,\n    loop: serializeLoop(loop),\n  };\n}\n\nfunction statusAutonomousLoop(loopId: string): Record<string, unknown> {\n  const loop = autonomousLoops.get(loopId);\n  if (!loop) {\n    return {\n      success: true,\n      loopId,\n      status: 'stopped',\n      running: false,\n    };\n  }\n  return {\n    success: true,\n    running: loop.status === 'running',\n    loop: serializeLoop(loop),\n  };\n}\n\nasync function runAutonomousLoopOnce(loop: AutonomousLoopState): Promise<void> {\n  if (loop.runningTick) return;\n  loop.runningTick = true;\n  loop.lastTickAt = new Date().toISOString();\n\n  try {\n    const results = await runAgentCycle(loop.teamId);\n    const compound = loop.compoundAfterCycle ? compoundKnowledge(loop.teamId) : undefined;\n    loop.cycleCount += 1;\n    loop.lastResult = {\n      summary: summarizeCycleResults(results),\n      results: results.map((result) => ({\n        agentId: result.agentId,\n        agentName: result.agentName,\n        action: result.action,\n        taskId: result.taskId,\n        taskTitle: result.taskTitle,\n        insightCount: result.knowledgeEntries.length,\n      })),\n      compound,\n    };\n    loop.lastError = undefined;\n    if (loop.maxCycles && loop.cycleCount >= loop.maxCycles) {\n      stopLoop(loop);\n    }\n  } catch (err: unknown) {\n    loop.lastError = err instanceof Error ? err.message : String(err);\n  } finally {\n    loop.runningTick = false;\n  }\n}\n\nfunction ensureAutonomousAgents(\n  teamId: string,\n  agentIdsValue: unknown\n): { loadedAgents: number } | Record<string, unknown> {\n  const agentIds = Array.isArray(agentIdsValue)\n    ? agentIdsValue.filter((id): id is string => typeof id === 'string')\n    : [];\n\n  if (agentIds.length > 0) {\n    const unknownIds = agentIds.filter((id) => !TEAM_AGENT_PROFILES.has(id));\n    if (unknownIds.length > 0) {\n      return {\n        error: `Unknown agent profile IDs: ${unknownIds.join(', ')}. Available: ${getAllProfiles()\n          .map((p) => p.id)\n          .join(', ')}`,\n      };\n    }\n    assignAgentsToRoom(teamId, agentIds);\n  }\n\n  const loadedAgents = getRoomAgents(teamId).length;\n  if (loadedAgents === 0) {\n    return {\n      error: `No agents loaded in room \"${teamId}\". Provide agent_ids or use holomesh_team_load_agents first.`,\n    };\n  }\n\n  return { loadedAgents };\n}\n\nfunction stopLoop(loop: AutonomousLoopState): void {\n  if (loop.timer) {\n    clearInterval(loop.timer);\n    loop.timer = undefined;\n  }\n  loop.status = 'stopped';\n  loop.stoppedAt = new Date().toISOString();\n}\n\nfunction serializeLoop(loop: AutonomousLoopState): Record<string, unknown> {\n  return {\n    loopId: loop.loopId,\n    teamId: loop.teamId,\n    status: loop.status,\n    running: loop.status === 'running',\n    intervalMs: loop.intervalMs,\n    startedAt: loop.startedAt,\n    lastTickAt: loop.lastTickAt,\n    stoppedAt: loop.stoppedAt,\n    cycleCount: loop.cycleCount,\n    maxCycles: loop.maxCycles,\n    compoundAfterCycle: loop.compoundAfterCycle,\n    runningTick: loop.runningTick,\n    lastResult: loop.lastResult,\n    lastError: loop.lastError,\n  };\n}\n\nfunction summarizeCycleResults(\n  results: Awaited<ReturnType<typeof runAgentCycle>>\n): Record<string, number> {\n  return {\n    completed: results.filter((result) => result.action === 'completed').length,\n    skipped: results.filter((result) => result.action === 'skipped').length,\n    errors: results.filter((result) => result.action === 'error').length,\n    synthesized: results.filter((result) => result.action === 'synthesized').length,\n    totalInsights: results.reduce((sum, result) => sum + result.knowledgeEntries.length, 0),\n  };\n}\n\nfunction normalizeAutonomousAction(value: unknown): AutonomousAction {\n  if (\n    value === 'start' ||\n    value === 'stop' ||\n    value === 'status' ||\n    value === 'query' ||\n    value === 'tick'\n  ) {\n    return value;\n  }\n  return 'status';\n}\n\nfunction stringOrUndefined(value: unknown): string | undefined {\n  return typeof value === 'string' && value.trim() ? value.trim() : undefined;\n}\n\nfunction clampNumber(value: unknown, fallback: number, min: number, max: number): number {\n  if (typeof value !== 'number' || !Number.isFinite(value)) return fallback;\n  return Math.min(max, Math.max(min, Math.floor(value)));\n}\n\nfunction optionalPositiveInteger(value: unknown): number | undefined {\n  if (typeof value !== 'number' || !Number.isFinite(value)) return undefined;\n  const integer = Math.floor(value);\n  return integer > 0 ? integer : undefined;\n}\n\nexport function _resetAutonomousControlState(): void {\n  for (const loop of autonomousLoops.values()) {\n    stopLoop(loop);\n  }\n  autonomousLoops.clear();\n}\n","/**\n * Team Formation Service\n *\n * Forms task-specific agent teams by scoring a roster against a capability\n * requirement. Used by the `holo_team_form` MCP tool.\n *\n * Lifted from uaa2-service TeamFormationService. The HoloScript version is\n * roster-source-agnostic: callers pass a `RosterAgent[]` (typically from the\n * HoloMesh `/team/:id/members` endpoint) and the service returns a ranked\n * `FormedTeam` with gap analysis.\n *\n * Aligns with P.GOLD.003 (uncoordinated agent collaboration): the output is a\n * recommendation, not a binding assignment — agents can converge on the\n * proposed team without an explicit coordination protocol.\n */\n\n// =============================================================================\n// TYPES\n// =============================================================================\n\nexport interface RosterAgent {\n  agentId: string;\n  agentName: string;\n  capabilities: string[];\n  specializationScore?: number; // 0..1\n  performanceScore?: number; // 0..1\n  active?: boolean;\n}\n\nexport interface TeamRequirement {\n  taskId: string;\n  taskType: string;\n  requiredCapabilities: string[];\n  preferredCapabilities?: string[];\n  teamSize?: number;\n  priority?: 'low' | 'normal' | 'high' | 'critical';\n  metadata?: Record<string, unknown>;\n}\n\nexport interface TeamMember {\n  agentId: string;\n  agentName: string;\n  role: string;\n  capabilities: string[];\n  specializationScore: number;\n  performanceScore: number;\n  complementarityScore: number;\n}\n\nexport interface FormedTeam {\n  teamId: string;\n  requirementId: string;\n  members: TeamMember[];\n  overallScore: number;\n  capabilityCoverage: number;\n  complementarity: number;\n  gaps: string[];\n  strengths: string[];\n  recommendations: string[];\n  formedAt: number;\n  status: 'proposed' | 'partial' | 'unfillable';\n}\n\nexport interface TeamFormationConfig {\n  maxTeamSize: number;\n  minTeamSize: number;\n  preferComplementary: boolean;\n  considerPerformance: boolean;\n  considerSpecialization: boolean;\n  requireActiveAgents: boolean;\n}\n\nexport const DEFAULT_FORMATION_CONFIG: TeamFormationConfig = {\n  maxTeamSize: 8,\n  minTeamSize: 1,\n  preferComplementary: true,\n  considerPerformance: true,\n  considerSpecialization: true,\n  requireActiveAgents: true,\n};\n\n// =============================================================================\n// SCORING\n// =============================================================================\n\nfunction capabilityOverlap(\n  agent: RosterAgent,\n  required: string[]\n): { hits: string[]; misses: string[] } {\n  const agentSet = new Set(agent.capabilities.map((c) => c.toLowerCase()));\n  const hits: string[] = [];\n  const misses: string[] = [];\n  for (const cap of required) {\n    if (agentSet.has(cap.toLowerCase())) hits.push(cap);\n    else misses.push(cap);\n  }\n  return { hits, misses };\n}\n\nfunction scoreAgent(\n  agent: RosterAgent,\n  req: TeamRequirement,\n  alreadyCovered: Set<string>,\n  config: TeamFormationConfig\n): number {\n  const { hits: requiredHits } = capabilityOverlap(agent, req.requiredCapabilities);\n  const preferredHits = req.preferredCapabilities\n    ? capabilityOverlap(agent, req.preferredCapabilities).hits\n    : [];\n\n  let score = requiredHits.length * 3 + preferredHits.length * 1;\n\n  if (config.preferComplementary) {\n    const newCoverage = requiredHits.filter((c) => !alreadyCovered.has(c.toLowerCase())).length;\n    score += newCoverage * 2;\n  }\n\n  if (config.considerSpecialization && agent.specializationScore !== undefined) {\n    score += agent.specializationScore * 2;\n  }\n\n  if (config.considerPerformance && agent.performanceScore !== undefined) {\n    score += agent.performanceScore * 2;\n  }\n\n  return score;\n}\n\nfunction deriveRole(agent: RosterAgent, requiredHits: string[]): string {\n  if (requiredHits.length === 0) return 'generalist';\n  // Pick the capability the agent most distinctly carries.\n  return requiredHits[0];\n}\n\nlet teamCounter = 0;\nfunction makeTeamId(): string {\n  teamCounter++;\n  return `team_${Date.now().toString(36)}_${teamCounter}`;\n}\n\n// =============================================================================\n// PUBLIC API\n// =============================================================================\n\nexport function formTeam(\n  req: TeamRequirement,\n  roster: RosterAgent[],\n  configOverrides: Partial<TeamFormationConfig> = {}\n): FormedTeam {\n  const config: TeamFormationConfig = { ...DEFAULT_FORMATION_CONFIG, ...configOverrides };\n\n  const eligible = config.requireActiveAgents\n    ? roster.filter((a) => a.active !== false)\n    : roster.slice();\n\n  const targetSize = Math.max(\n    config.minTeamSize,\n    Math.min(config.maxTeamSize, req.teamSize ?? config.maxTeamSize)\n  );\n\n  const covered = new Set<string>();\n  const selected: TeamMember[] = [];\n\n  while (selected.length < targetSize) {\n    const remaining = eligible.filter((a) => !selected.some((m) => m.agentId === a.agentId));\n    if (remaining.length === 0) break;\n\n    let best: { agent: RosterAgent; score: number } | null = null;\n    for (const agent of remaining) {\n      const s = scoreAgent(agent, req, covered, config);\n      if (!best || s > best.score) best = { agent, score: s };\n    }\n    if (!best || best.score <= 0) break;\n\n    const { hits: requiredHits } = capabilityOverlap(best.agent, req.requiredCapabilities);\n    for (const cap of requiredHits) covered.add(cap.toLowerCase());\n\n    selected.push({\n      agentId: best.agent.agentId,\n      agentName: best.agent.agentName,\n      role: deriveRole(best.agent, requiredHits),\n      capabilities: best.agent.capabilities,\n      specializationScore: best.agent.specializationScore ?? 0,\n      performanceScore: best.agent.performanceScore ?? 0,\n      complementarityScore: requiredHits.length / Math.max(1, req.requiredCapabilities.length),\n    });\n  }\n\n  const coverage =\n    req.requiredCapabilities.length === 0 ? 1 : covered.size / req.requiredCapabilities.length;\n  const gaps = req.requiredCapabilities.filter((c) => !covered.has(c.toLowerCase()));\n  const strengths = Array.from(covered);\n\n  const recommendations: string[] = [];\n  if (gaps.length > 0) {\n    recommendations.push(`Cover gaps: ${gaps.join(', ')} via recruit or upskill.`);\n  }\n  if (selected.length < targetSize) {\n    recommendations.push(\n      `Team underfilled (${selected.length}/${targetSize}). Expand roster or relax requirements.`\n    );\n  }\n  if (selected.length > 0 && coverage === 1) {\n    recommendations.push(\n      'All required capabilities covered. Consider pairing for redundancy on critical roles.'\n    );\n  }\n\n  const complementarity =\n    selected.length > 0\n      ? selected.reduce((s, m) => s + m.complementarityScore, 0) / selected.length\n      : 0;\n\n  let status: FormedTeam['status'] = 'proposed';\n  if (selected.length === 0) status = 'unfillable';\n  else if (coverage < 1) status = 'partial';\n\n  const overallScore = coverage * 0.6 + complementarity * 0.4;\n\n  return {\n    teamId: makeTeamId(),\n    requirementId: req.taskId,\n    members: selected,\n    overallScore,\n    capabilityCoverage: coverage,\n    complementarity,\n    gaps,\n    strengths,\n    recommendations,\n    formedAt: Date.now(),\n    status,\n  };\n}\n","/**\n * Team Formation MCP Tools\n *\n * MCP tool wrappers for the team-formation service. Today: `holomesh_team_form`\n * (form a task-specific team from a roster).\n *\n * Roster can be passed inline (callers who already have agent profiles) or\n * fetched from the HoloMesh members API when a `team_id` is supplied.\n */\n\nimport type { Tool } from '@modelcontextprotocol/sdk/types.js';\nimport {\n  formTeam,\n  type RosterAgent,\n  type TeamRequirement,\n  type TeamFormationConfig,\n  DEFAULT_FORMATION_CONFIG,\n} from './team-formation';\n\n// ── MCP Tool Definitions ──\n\nexport const teamFormationTools: Tool[] = [\n  {\n    name: 'holomesh_team_form',\n    description:\n      'Form a task-specific agent team by scoring a roster against a capability requirement. Returns a ranked FormedTeam with members, capability coverage, gaps, strengths, and recommendations. Pass `roster` inline, or pass `team_id` to fetch active members from the HoloMesh team API.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        requirement: {\n          type: 'object',\n          description: 'The task requirement to form a team for.',\n          properties: {\n            taskId: {\n              type: 'string',\n              description: 'Stable identifier for the task being staffed.',\n            },\n            taskType: { type: 'string', description: 'Short description of the task domain.' },\n            requiredCapabilities: {\n              type: 'array',\n              items: { type: 'string' },\n              description: 'Capabilities that MUST be covered by the team.',\n            },\n            preferredCapabilities: {\n              type: 'array',\n              items: { type: 'string' },\n              description: 'Capabilities that boost score but are not required.',\n            },\n            teamSize: {\n              type: 'number',\n              description: 'Target team size. Clamped to [minTeamSize, maxTeamSize].',\n            },\n            priority: {\n              type: 'string',\n              enum: ['low', 'normal', 'high', 'critical'],\n              description: 'Priority hint (informational; does not change scoring).',\n            },\n            metadata: { type: 'object', description: 'Free-form caller metadata.' },\n          },\n          required: ['taskId', 'taskType', 'requiredCapabilities'],\n        },\n        roster: {\n          type: 'array',\n          description:\n            'Inline roster. Each entry: { agentId, agentName, capabilities, specializationScore?, performanceScore?, active? }.',\n          items: {\n            type: 'object',\n            properties: {\n              agentId: { type: 'string' },\n              agentName: { type: 'string' },\n              capabilities: { type: 'array', items: { type: 'string' } },\n              specializationScore: { type: 'number', minimum: 0, maximum: 1 },\n              performanceScore: { type: 'number', minimum: 0, maximum: 1 },\n              active: { type: 'boolean' },\n            },\n            required: ['agentId', 'agentName', 'capabilities'],\n          },\n        },\n        team_id: {\n          type: 'string',\n          description:\n            'HoloMesh team id. When provided and roster is omitted, members are fetched from the team API.',\n        },\n        config: {\n          type: 'object',\n          description: 'Optional formation config overrides. Defaults to DEFAULT_FORMATION_CONFIG.',\n          properties: {\n            maxTeamSize: { type: 'number' },\n            minTeamSize: { type: 'number' },\n            preferComplementary: { type: 'boolean' },\n            considerPerformance: { type: 'boolean' },\n            considerSpecialization: { type: 'boolean' },\n            requireActiveAgents: { type: 'boolean' },\n          },\n        },\n      },\n      required: ['requirement'],\n    },\n  },\n];\n\n// ── Roster Source ──\n\nexport interface RosterSource {\n  fetchRoster(teamId: string): Promise<RosterAgent[]>;\n}\n\nlet rosterSource: RosterSource | null = null;\n\n/**\n * Inject the HoloMesh roster source. Called by the server bootstrap once the\n * mesh client is constructed. When not injected, `holomesh_team_form` requires an\n * inline `roster`.\n */\nexport function setTeamFormationRosterSource(src: RosterSource): void {\n  rosterSource = src;\n}\n\n// ── Handler ──\n\nexport async function handleTeamFormationTool(\n  name: string,\n  args: Record<string, unknown>\n): Promise<unknown | null> {\n  if (name !== 'holomesh_team_form') return null;\n\n  const requirement = args.requirement as TeamRequirement | undefined;\n  if (!requirement || !requirement.taskId || !requirement.taskType) {\n    return { error: '\"requirement\" with taskId and taskType is required.' };\n  }\n  if (!Array.isArray(requirement.requiredCapabilities)) {\n    return { error: '\"requirement.requiredCapabilities\" must be an array of capability strings.' };\n  }\n\n  let roster = args.roster as RosterAgent[] | undefined;\n\n  if (\n    (!roster || roster.length === 0) &&\n    typeof args.team_id === 'string' &&\n    args.team_id.length > 0\n  ) {\n    if (!rosterSource) {\n      return {\n        error:\n          'No roster source configured; pass `roster` inline or call setTeamFormationRosterSource() at server boot.',\n      };\n    }\n    try {\n      roster = await rosterSource.fetchRoster(args.team_id);\n    } catch (err) {\n      return {\n        error: `Failed to fetch roster for team_id=${args.team_id}: ${(err as Error).message}`,\n      };\n    }\n  }\n\n  if (!roster || roster.length === 0) {\n    return {\n      error:\n        'No roster available. Pass `roster` inline or `team_id` with a configured roster source.',\n    };\n  }\n\n  const configOverrides = (args.config as Partial<TeamFormationConfig>) ?? {};\n  const team = formTeam(requirement, roster, configOverrides);\n\n  return {\n    success: true,\n    team,\n    defaults: DEFAULT_FORMATION_CONFIG,\n  };\n}\n","/**\n * HoloMesh agent capability and marketplace search MCP tools.\n *\n * These tools close the bridge between declarative `.hsplus` agent brains,\n * team formation, and marketplace-driven agent discovery.\n */\n\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport type { Tool } from '@modelcontextprotocol/sdk/types.js';\nimport { parseHoloPartial } from '@holoscript/core';\nimport axios from 'axios';\nimport { resolveSecretWithLease, VaultLeaseError } from './identity/vault-lease-registry';\n\ntype SourceKind = 'inline' | 'file';\n\ninterface BrainSource {\n  kind: SourceKind;\n  source: string;\n  path?: string;\n}\n\ninterface MarketplaceItem {\n  id?: string;\n  name?: string;\n  slug?: string;\n  description?: string;\n  category?: string;\n  tags?: string[];\n  capabilities?: string[];\n  tools?: string[];\n  author?: string;\n  version?: string;\n  tier?: string;\n  installs?: number;\n  rating?: number;\n  [key: string]: unknown;\n}\n\ninterface MarketplaceSearchResult {\n  item: MarketplaceItem;\n  score: number;\n  matched: string[];\n}\n\ninterface MetadataToken {\n  kind: 'identifier' | 'string' | 'symbol';\n  value: string;\n}\n\nexport interface AgentCapabilitySummary {\n  compositionName?: string;\n  identityName?: string;\n  domain?: string;\n  capabilityTags: string[];\n  traits: string[];\n  tools: string[];\n  capabilities: string[];\n  marketplaceTags: string[];\n  counts: {\n    capabilityTags: number;\n    traits: number;\n    tools: number;\n    capabilities: number;\n    marketplaceTags: number;\n  };\n}\n\nconst DEFAULT_MAX_BRAIN_BYTES = 512 * 1024;\n\nexport const agentCapabilityTools: Tool[] = [\n  {\n    name: 'holomesh_agent_capabilities',\n    description:\n      'Inspect a .hsplus agent brain and extract capability_tags, traits, declared tools, and capability block names for team formation and marketplace matching.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        brain_source: {\n          type: 'string',\n          description: 'Inline .hsplus source to inspect.',\n        },\n        brain_path: {\n          type: 'string',\n          description:\n            'Optional local .hsplus path to inspect. Requires allow_file_read=true and is bounded by max_bytes.',\n        },\n        allow_file_read: {\n          type: 'boolean',\n          description: 'Set true to allow reading brain_path from local disk.',\n        },\n        agent_id: {\n          type: 'string',\n          description: 'Optional agent ID to include in the returned team-formation roster hint.',\n        },\n        agent_name: {\n          type: 'string',\n          description: 'Optional agent display name. Defaults to the composition or identity name.',\n        },\n        max_bytes: {\n          type: 'number',\n          description: `Maximum file bytes to read from brain_path. Default ${DEFAULT_MAX_BRAIN_BYTES}.`,\n        },\n      },\n    },\n  },\n  {\n    name: 'holomesh_marketplace_search',\n    description:\n      'Search agent marketplace templates by capability tags, declared tools, category, and text query. Can query the orchestrator marketplace or score an inline catalog locally.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        query: {\n          type: 'string',\n          description:\n            'Free-text query for template name, description, category, tags, or capabilities.',\n        },\n        capability_query: {\n          type: 'string',\n          description: 'Capability phrase used to rank templates, e.g. \"webgpu compiler audit\".',\n        },\n        capability_tags: {\n          type: 'array',\n          items: { type: 'string' },\n          description: 'Required or preferred capability tags.',\n        },\n        tool_names: {\n          type: 'array',\n          items: { type: 'string' },\n          description: 'Preferred MCP tool names exposed by a marketplace template.',\n        },\n        category: {\n          type: 'string',\n          description: 'Optional marketplace category filter.',\n        },\n        tier: {\n          type: 'string',\n          description: 'Optional tier filter passed to the marketplace service.',\n        },\n        limit: {\n          type: 'number',\n          description: 'Maximum results to return. Defaults to 10.',\n        },\n        include_remote: {\n          type: 'boolean',\n          description: 'When true (default), query the orchestrator marketplace search endpoint.',\n        },\n        marketplace_url: {\n          type: 'string',\n          description:\n            'Override marketplace search URL. Defaults to HOLOMESH_MARKETPLACE_SEARCH_URL or MCP_ORCHESTRATOR_URL + /marketplace/search.',\n        },\n        items: {\n          type: 'array',\n          items: { type: 'object' },\n          description:\n            'Optional inline marketplace catalog to score locally without network access.',\n        },\n      },\n    },\n  },\n];\n\nexport async function handleAgentCapabilityTool(\n  name: string,\n  args: Record<string, unknown>\n): Promise<unknown | null> {\n  switch (name) {\n    case 'holomesh_agent_capabilities':\n      return handleAgentCapabilities(args);\n    case 'holomesh_marketplace_search':\n      return handleMarketplaceSearch(args);\n    default:\n      return null;\n  }\n}\n\nexport function extractAgentCapabilities(source: string): AgentCapabilitySummary {\n  const tokens = lexMetadataTokens(source);\n  const compositionName = extractCompositionName(source, tokens);\n  const identityName = extractFirstStringProperty(tokens, 'name');\n  const domain = extractFirstStringProperty(tokens, 'domain');\n  const capabilityTags = uniqueStrings([\n    ...extractStringArrayProperty(tokens, 'capability_tags'),\n    ...extractStringArrayProperty(tokens, 'capabilityTags'),\n  ]);\n  const traits = uniqueStrings([\n    ...extractStringArrayBlock(tokens, 'traits'),\n    ...extractDecoratorTraits(tokens),\n  ]);\n  const tools = uniqueStrings([\n    ...extractStringArrayProperty(tokens, 'tools'),\n    ...extractStringArrayProperty(tokens, 'mcp_tools'),\n  ]);\n  const capabilityNames = uniqueStrings([\n    ...extractStringArrayProperty(tokens, 'capabilities'),\n    ...extractCapabilityBlockNames(tokens),\n  ]);\n  const marketplaceTags = uniqueStrings([\n    ...capabilityTags,\n    ...traits,\n    ...capabilityNames,\n    ...tools.map((tool) => `tool:${tool}`),\n  ]);\n\n  return {\n    compositionName,\n    identityName,\n    domain,\n    capabilityTags,\n    traits,\n    tools,\n    capabilities: capabilityNames,\n    marketplaceTags,\n    counts: {\n      capabilityTags: capabilityTags.length,\n      traits: traits.length,\n      tools: tools.length,\n      capabilities: capabilityNames.length,\n      marketplaceTags: marketplaceTags.length,\n    },\n  };\n}\n\nfunction handleAgentCapabilities(args: Record<string, unknown>): Record<string, unknown> {\n  const source = resolveBrainSource(args);\n  if ('error' in source) return source;\n\n  const extracted = extractAgentCapabilities(source.source);\n  const compositionName =\n    typeof extracted.compositionName === 'string' ? extracted.compositionName : undefined;\n  const identityName =\n    typeof extracted.identityName === 'string' ? extracted.identityName : undefined;\n  const agentName =\n    typeof args.agent_name === 'string' && args.agent_name.trim()\n      ? args.agent_name.trim()\n      : identityName || compositionName || 'unnamed-agent';\n  const agentId =\n    typeof args.agent_id === 'string' && args.agent_id.trim()\n      ? args.agent_id.trim()\n      : slugify(agentName);\n\n  return {\n    success: true,\n    source: {\n      kind: source.kind,\n      path: source.path,\n      bytes: Buffer.byteLength(source.source, 'utf8'),\n    },\n    agent: {\n      id: agentId,\n      name: agentName,\n      compositionName,\n      domain: extracted.domain,\n    },\n    ...extracted,\n    teamFormationRosterHint: {\n      agentId,\n      agentName,\n      capabilities: extracted.marketplaceTags,\n      source: source.kind === 'file' ? source.path : 'inline',\n    },\n  };\n}\n\nasync function handleMarketplaceSearch(\n  args: Record<string, unknown>\n): Promise<Record<string, unknown>> {\n  const limit = clampNumber(args.limit, 10, 1, 50);\n  const includeRemote = args.include_remote !== false;\n  const localItems = normalizeMarketplaceItems(args.items);\n  const query = stringOrUndefined(args.query);\n  const capabilityQuery = stringOrUndefined(args.capability_query);\n  const capabilityTags = stringArray(args.capability_tags);\n  const toolNames = stringArray(args.tool_names);\n  const category = stringOrUndefined(args.category);\n  const tier = stringOrUndefined(args.tier);\n\n  let remoteItems: MarketplaceItem[] = [];\n  let remoteError: string | undefined;\n  let remoteUrl: string | undefined;\n\n  if (includeRemote) {\n    remoteUrl = resolveMarketplaceSearchUrl(args.marketplace_url);\n    try {\n      remoteItems = await fetchRemoteMarketplace(remoteUrl, {\n        query,\n        capabilityQuery,\n        capabilityTags,\n        toolNames,\n        category,\n        tier,\n        limit,\n      });\n    } catch (err: unknown) {\n      remoteError = err instanceof Error ? err.message : String(err);\n    }\n  }\n\n  const merged = new Map<string, MarketplaceItem>();\n  for (const item of [...localItems, ...remoteItems]) {\n    merged.set(item.id || item.slug || item.name || JSON.stringify(item), item);\n  }\n\n  const scored = Array.from(merged.values())\n    .map((item) =>\n      scoreMarketplaceItem(item, {\n        query,\n        capabilityQuery,\n        capabilityTags,\n        toolNames,\n        category,\n      })\n    )\n    .filter(\n      (result) =>\n        result.score > 0 ||\n        hasNoSearchTerms(query, capabilityQuery, capabilityTags, toolNames, category)\n    )\n    .sort((a, b) => b.score - a.score)\n    .slice(0, limit);\n\n  if (scored.length === 0 && remoteError && localItems.length === 0) {\n    return {\n      success: false,\n      error: 'Marketplace search failed and no local catalog items were supplied.',\n      marketplaceUrl: remoteUrl,\n      details: remoteError,\n    };\n  }\n\n  return {\n    success: true,\n    marketplaceUrl: remoteUrl,\n    query,\n    capabilityQuery,\n    capabilityTags,\n    toolNames,\n    category,\n    totalCandidates: merged.size,\n    count: scored.length,\n    results: scored,\n    ...(remoteError ? { remoteError } : {}),\n  };\n}\n\nfunction resolveBrainSource(\n  args: Record<string, unknown>\n): BrainSource | { error: string; [key: string]: unknown } {\n  const inline = stringOrUndefined(args.brain_source);\n  if (inline) {\n    return { kind: 'inline', source: inline };\n  }\n\n  const brainPath = stringOrUndefined(args.brain_path);\n  if (!brainPath) {\n    return { error: 'brain_source or brain_path is required.' };\n  }\n  if (args.allow_file_read !== true) {\n    return { error: 'brain_path requires allow_file_read=true.' };\n  }\n\n  try {\n    const resolved = path.resolve(brainPath);\n    const maxBytes = clampNumber(args.max_bytes, DEFAULT_MAX_BRAIN_BYTES, 1, 5 * 1024 * 1024);\n    const stat = fs.statSync(resolved);\n    if (!stat.isFile()) {\n      return { error: `brain_path is not a file: ${resolved}` };\n    }\n    if (stat.size > maxBytes) {\n      return {\n        error: `brain_path is ${stat.size} bytes, above max_bytes ${maxBytes}.`,\n      };\n    }\n\n    return {\n      kind: 'file',\n      path: resolved,\n      source: fs.readFileSync(resolved, 'utf8'),\n    };\n  } catch (err: unknown) {\n    return {\n      error: `Failed to read brain_path: ${err instanceof Error ? err.message : String(err)}`,\n    };\n  }\n}\n\nconst ALLOWED_MARKETPLACE_HOSTNAMES = new Set([\n  // Canonical marketplace SSOT (DT-17): traits + plugins + skills.\n  'marketplace-api-production-f244.up.railway.app',\n  'mcp-orchestrator-production-45f9.up.railway.app',\n  'mcp.holoscript.net',\n  'localhost',\n  '127.0.0.1',\n]);\n\n/** Schemes permitted for marketplace search URLs. http: only allowed for loopback hosts. */\nconst ALLOWED_MARKETPLACE_SCHEMES = new Set(['https:', 'http:']);\n\nexport function resolveMarketplaceSearchUrl(value: unknown): string {\n  const override = stringOrUndefined(value);\n  if (override) {\n    let parsed: URL;\n    try {\n      parsed = new URL(override);\n    } catch {\n      throw new Error(`marketplace_url is not a valid URL: ${override}`);\n    }\n    // Reject dangerous schemes (file, data, ftp, etc.) unconditionally.\n    if (!ALLOWED_MARKETPLACE_SCHEMES.has(parsed.protocol)) {\n      throw new Error(\n        `marketplace_url scheme not allowed: ${parsed.protocol} (only https: and http: are permitted)`\n      );\n    }\n    // http: is only permitted for loopback hosts (localhost / 127.0.0.1).\n    // Non-loopback hosts must use https: to prevent MITM on marketplace responses.\n    if (\n      parsed.protocol === 'http:' &&\n      parsed.hostname !== 'localhost' &&\n      parsed.hostname !== '127.0.0.1'\n    ) {\n      throw new Error(`marketplace_url must use https: for non-loopback host: ${parsed.hostname}`);\n    }\n    if (!ALLOWED_MARKETPLACE_HOSTNAMES.has(parsed.hostname)) {\n      throw new Error(`marketplace_url host not allowed: ${parsed.hostname}`);\n    }\n    return override;\n  }\n  if (process.env.HOLOMESH_MARKETPLACE_SEARCH_URL) {\n    return process.env.HOLOMESH_MARKETPLACE_SEARCH_URL;\n  }\n  // DT-17: consume the canonical marketplace-api (skills SSOT) by default. Its\n  // {success,data:{results:[…]}} response is already handled by\n  // normalizeMarketplaceItems (which unwraps `data`/`results`). The legacy\n  // orchestrator agent-template store remains reachable via an explicit\n  // marketplace_url / HOLOMESH_MARKETPLACE_SEARCH_URL override.\n  return 'https://marketplace-api-production-f244.up.railway.app/api/v1/skills/search';\n}\n\nfunction readMarketplaceApiKey(): string {\n  const tryRead = (ref: string): string => {\n    try {\n      return resolveSecretWithLease(ref) ?? '';\n    } catch (err) {\n      if (err instanceof VaultLeaseError) return '';\n      throw err;\n    }\n  };\n  return tryRead('env:HOLOSCRIPT_API_KEY') || tryRead('env:MCPME_API_KEY');\n}\n\nasync function fetchRemoteMarketplace(\n  url: string,\n  options: {\n    query?: string;\n    capabilityQuery?: string;\n    capabilityTags: string[];\n    toolNames: string[];\n    category?: string;\n    tier?: string;\n    limit: number;\n  }\n): Promise<MarketplaceItem[]> {\n  const headers: Record<string, string> = { Accept: 'application/json' };\n  const apiKey = readMarketplaceApiKey();\n  if (apiKey) headers['x-mcp-api-key'] = apiKey;\n\n  const params: Record<string, string> = {};\n  const q = options.query || options.capabilityQuery;\n  if (q) params.q = q;\n  if (options.category) params.category = options.category;\n  if (options.tier) params.tier = options.tier;\n  if (options.capabilityTags.length > 0) params.capabilities = options.capabilityTags.join(',');\n  if (options.toolNames.length > 0) params.tools = options.toolNames.join(',');\n  params.limit = String(options.limit);\n\n  const response = await axios.get(url, {\n    headers,\n    params,\n    timeout: 12000,\n  });\n\n  return normalizeMarketplaceItems(response.data);\n}\n\nfunction normalizeMarketplaceItems(value: unknown): MarketplaceItem[] {\n  if (Array.isArray(value))\n    return value.filter(isRecord).map((item) => normalizeMarketplaceItem(item));\n  if (!isRecord(value)) return [];\n\n  for (const key of ['templates', 'results', 'items', 'data']) {\n    const nested = value[key];\n    if (Array.isArray(nested)) {\n      return nested.filter(isRecord).map((item) => normalizeMarketplaceItem(item));\n    }\n    if (isRecord(nested)) {\n      const fromNested = normalizeMarketplaceItems(nested);\n      if (fromNested.length > 0) return fromNested;\n    }\n  }\n\n  return [normalizeMarketplaceItem(value)];\n}\n\nfunction normalizeMarketplaceItem(item: Record<string, unknown>): MarketplaceItem {\n  return {\n    ...item,\n    id: stringOrUndefined(item.id),\n    name: stringOrUndefined(item.name),\n    slug: stringOrUndefined(item.slug),\n    description: stringOrUndefined(item.description),\n    category: stringOrUndefined(item.category),\n    tags: stringArray(item.tags),\n    capabilities: uniqueStrings([\n      ...stringArray(item.capabilities),\n      ...stringArray(item.capability_tags),\n      ...stringArray(item.capabilityTags),\n    ]),\n    tools: uniqueStrings([...stringArray(item.tools), ...stringArray(item.tool_names)]),\n    author: stringOrUndefined(item.author),\n    version: stringOrUndefined(item.version),\n    tier: stringOrUndefined(item.tier),\n  };\n}\n\nfunction scoreMarketplaceItem(\n  item: MarketplaceItem,\n  options: {\n    query?: string;\n    capabilityQuery?: string;\n    capabilityTags: string[];\n    toolNames: string[];\n    category?: string;\n  }\n): MarketplaceSearchResult {\n  const matched: string[] = [];\n  let score = 0;\n  const haystackFields = [\n    item.name,\n    item.slug,\n    item.description,\n    item.category,\n    item.author,\n    ...(item.tags || []),\n    ...(item.capabilities || []),\n    ...(item.tools || []),\n  ].map((value) => normalizeToken(value || ''));\n  const haystack = haystackFields.join(' ');\n\n  for (const term of tokenize(`${options.query || ''} ${options.capabilityQuery || ''}`)) {\n    if (haystack.includes(term)) {\n      score += 2;\n      matched.push(term);\n    }\n  }\n\n  for (const tag of options.capabilityTags.map(normalizeToken).filter(Boolean)) {\n    if ((item.capabilities || []).map(normalizeToken).includes(tag)) {\n      score += 5;\n      matched.push(`capability:${tag}`);\n    } else if ((item.tags || []).map(normalizeToken).includes(tag) || haystack.includes(tag)) {\n      score += 3;\n      matched.push(`tag:${tag}`);\n    }\n  }\n\n  for (const toolName of options.toolNames.map(normalizeToken).filter(Boolean)) {\n    if ((item.tools || []).map(normalizeToken).includes(toolName)) {\n      score += 4;\n      matched.push(`tool:${toolName}`);\n    }\n  }\n\n  if (\n    options.category &&\n    normalizeToken(item.category || '') === normalizeToken(options.category)\n  ) {\n    score += 4;\n    matched.push(`category:${normalizeToken(options.category)}`);\n  }\n\n  if (typeof item.rating === 'number' && item.rating > 0) score += Math.min(item.rating, 5) / 10;\n  if (typeof item.installs === 'number' && item.installs > 0)\n    score += Math.min(item.installs, 1000) / 1000;\n\n  return {\n    item,\n    score: Number(score.toFixed(3)),\n    matched: uniqueStrings(matched),\n  };\n}\n\nfunction extractCompositionName(source: string, tokens: MetadataToken[]): string | undefined {\n  try {\n    return parseHoloPartial(source).ast?.name || extractCompositionNameFromTokens(tokens);\n  } catch {\n    return extractCompositionNameFromTokens(tokens);\n  }\n}\n\nfunction extractCompositionNameFromTokens(tokens: MetadataToken[]): string | undefined {\n  for (let index = 0; index < tokens.length - 1; index += 1) {\n    if (isIdentifier(tokens[index], 'composition')) {\n      const next = tokens[index + 1];\n      if (next?.kind === 'string' || next?.kind === 'identifier') return next.value;\n    }\n  }\n  return undefined;\n}\n\nfunction extractFirstStringProperty(tokens: MetadataToken[], property: string): string | undefined {\n  for (let index = 0; index < tokens.length - 2; index += 1) {\n    if (\n      isIdentifier(tokens[index], property) &&\n      isSymbol(tokens[index + 1], ':') &&\n      tokens[index + 2]?.kind === 'string'\n    ) {\n      return tokens[index + 2].value;\n    }\n  }\n  return undefined;\n}\n\nfunction extractStringArrayProperty(tokens: MetadataToken[], property: string): string[] {\n  const values: string[] = [];\n  for (let index = 0; index < tokens.length - 2; index += 1) {\n    if (\n      isIdentifier(tokens[index], property) &&\n      isSymbol(tokens[index + 1], ':') &&\n      isSymbol(tokens[index + 2], '[')\n    ) {\n      values.push(...collectStringsUntilBalanced(tokens, index + 2, '[', ']'));\n    }\n  }\n  return uniqueStrings(values);\n}\n\nfunction extractStringArrayBlock(tokens: MetadataToken[], keyword: string): string[] {\n  const values: string[] = [];\n  for (let index = 0; index < tokens.length - 1; index += 1) {\n    if (isIdentifier(tokens[index], keyword) && isSymbol(tokens[index + 1], '[')) {\n      values.push(...collectStringsUntilBalanced(tokens, index + 1, '[', ']'));\n    }\n  }\n  return uniqueStrings(values);\n}\n\nfunction extractDecoratorTraits(tokens: MetadataToken[]): string[] {\n  const values: string[] = [];\n  for (let index = 0; index < tokens.length - 1; index += 1) {\n    if (!isSymbol(tokens[index], '@')) continue;\n    const name = tokens[index + 1];\n    if (name?.kind !== 'identifier') continue;\n\n    values.push(name.value);\n    if (isSymbol(tokens[index + 2], ':') && tokens[index + 3]?.kind === 'string') {\n      values.push(tokens[index + 3].value);\n    }\n    if (isSymbol(tokens[index + 2], '(')) {\n      values.push(...collectStringsUntilBalanced(tokens, index + 2, '(', ')'));\n    }\n  }\n\n  return uniqueStrings(values);\n}\n\nfunction extractCapabilityBlockNames(tokens: MetadataToken[]): string[] {\n  const names: string[] = [];\n  for (let index = 0; index < tokens.length - 1; index += 1) {\n    if (!isIdentifier(tokens[index], 'capabilities') || !isSymbol(tokens[index + 1], '{')) {\n      continue;\n    }\n    let depth = 0;\n    for (let cursor = index + 1; cursor < tokens.length; cursor += 1) {\n      const token = tokens[cursor];\n      if (isSymbol(token, '{')) {\n        depth += 1;\n        continue;\n      }\n      if (isSymbol(token, '}')) {\n        depth -= 1;\n        if (depth === 0) break;\n        continue;\n      }\n      if (depth === 1 && token.kind === 'identifier' && isSymbol(tokens[cursor + 1], ':')) {\n        names.push(token.value);\n      }\n    }\n  }\n  return uniqueStrings(names);\n}\n\nfunction lexMetadataTokens(source: string): MetadataToken[] {\n  const tokens: MetadataToken[] = [];\n  let index = 0;\n\n  while (index < source.length) {\n    const char = source[index];\n    const next = source[index + 1];\n\n    if (!char) break;\n    if (isWhitespace(char)) {\n      index += 1;\n      continue;\n    }\n    if (char === '/' && next === '/') {\n      index = skipLineComment(source, index + 2);\n      continue;\n    }\n    if (char === '/' && next === '*') {\n      index = skipBlockComment(source, index + 2);\n      continue;\n    }\n    if (char === '\"' || char === \"'\") {\n      const read = readStringToken(source, index, char);\n      tokens.push({ kind: 'string', value: read.value });\n      index = read.nextIndex;\n      continue;\n    }\n    if (isIdentifierStart(char)) {\n      const start = index;\n      index += 1;\n      while (index < source.length && isIdentifierPart(source[index])) index += 1;\n      tokens.push({ kind: 'identifier', value: source.slice(start, index) });\n      continue;\n    }\n    if ('{}[]():,@'.includes(char)) {\n      tokens.push({ kind: 'symbol', value: char });\n    }\n    index += 1;\n  }\n\n  return tokens;\n}\n\nfunction collectStringsUntilBalanced(\n  tokens: MetadataToken[],\n  openIndex: number,\n  open: '[' | '(',\n  close: ']' | ')'\n): string[] {\n  const values: string[] = [];\n  let depth = 0;\n  for (let index = openIndex; index < tokens.length; index += 1) {\n    const token = tokens[index];\n    if (isSymbol(token, open)) {\n      depth += 1;\n      continue;\n    }\n    if (isSymbol(token, close)) {\n      depth -= 1;\n      if (depth === 0) break;\n      continue;\n    }\n    if (depth > 0 && token.kind === 'string') {\n      values.push(token.value);\n    }\n  }\n  return uniqueStrings(values);\n}\n\nfunction readStringToken(\n  source: string,\n  start: number,\n  quote: '\"' | \"'\"\n): { value: string; nextIndex: number } {\n  let value = '';\n  let escaped = false;\n  for (let index = start + 1; index < source.length; index += 1) {\n    const char = source[index];\n    if (escaped) {\n      value += char;\n      escaped = false;\n      continue;\n    }\n    if (char === '\\\\') {\n      escaped = true;\n      continue;\n    }\n    if (char === quote) {\n      return { value, nextIndex: index + 1 };\n    }\n    value += char;\n  }\n  return { value, nextIndex: source.length };\n}\n\nfunction skipLineComment(source: string, start: number): number {\n  const newline = source.indexOf('\\n', start);\n  return newline === -1 ? source.length : newline + 1;\n}\n\nfunction skipBlockComment(source: string, start: number): number {\n  const end = source.indexOf('*/', start);\n  return end === -1 ? source.length : end + 2;\n}\n\nfunction isIdentifier(token: MetadataToken | undefined, value: string): boolean {\n  return token?.kind === 'identifier' && token.value === value;\n}\n\nfunction isSymbol(token: MetadataToken | undefined, value: string): boolean {\n  return token?.kind === 'symbol' && token.value === value;\n}\n\nfunction isWhitespace(char: string): boolean {\n  return char === ' ' || char === '\\t' || char === '\\n' || char === '\\r';\n}\n\nfunction isIdentifierStart(char: string): boolean {\n  return /[A-Za-z_#]/.test(char);\n}\n\nfunction isIdentifierPart(char: string | undefined): boolean {\n  return Boolean(char && /[A-Za-z0-9_.#-]/.test(char));\n}\n\nfunction normalizeToken(value: string): string {\n  return value.trim().toLowerCase().replace(/^@/, '').replace(/_/g, '-');\n}\n\nfunction tokenize(value: string): string[] {\n  return uniqueStrings(\n    value\n      .split(/[^A-Za-z0-9_.:-]+/)\n      .map(normalizeToken)\n      .filter((token) => token.length > 0)\n  );\n}\n\nfunction uniqueStrings(values: string[]): string[] {\n  const result: string[] = [];\n  const seen = new Set<string>();\n  for (const value of values) {\n    const trimmed = value.trim();\n    if (!trimmed || seen.has(trimmed)) continue;\n    seen.add(trimmed);\n    result.push(trimmed);\n  }\n  return result;\n}\n\nfunction stringOrUndefined(value: unknown): string | undefined {\n  return typeof value === 'string' && value.trim() ? value.trim() : undefined;\n}\n\nfunction stringArray(value: unknown): string[] {\n  if (!Array.isArray(value)) return [];\n  return uniqueStrings(value.filter((item): item is string => typeof item === 'string'));\n}\n\nfunction clampNumber(value: unknown, fallback: number, min: number, max: number): number {\n  if (typeof value !== 'number' || !Number.isFinite(value)) return fallback;\n  return Math.min(max, Math.max(min, Math.floor(value)));\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n  return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction slugify(value: string): string {\n  return value\n    .trim()\n    .toLowerCase()\n    .replace(/[^a-z0-9]+/g, '-')\n    .replace(/^-|-$/g, '');\n}\n\nfunction hasNoSearchTerms(\n  query: string | undefined,\n  capabilityQuery: string | undefined,\n  capabilityTags: string[],\n  toolNames: string[],\n  category: string | undefined\n): boolean {\n  return (\n    !query && !capabilityQuery && capabilityTags.length === 0 && toolNames.length === 0 && !category\n  );\n}\n","import type { Tool } from '@modelcontextprotocol/sdk/types.js';\n/**\n * Sovereign topology + LifePod tools.\n *\n * OVERCLAIMED (ratchet P5): holomesh_sovereign_topology and lifepod tools delegate to an\n * orchestrator endpoint (/api/holomesh/sovereign/*) that does not exist. The handler\n * constructs fetch() calls to an absent baseUrl — every call returns network error.\n * D.051 tier hierarchy has no code enforcement layer; sovereignty is aspirational.\n */\nimport type { HoloMeshOrchestratorClient } from './orchestrator-client';\n\nexport const sovereignTools: Tool[] = [\n  {\n    name: 'holomesh_sovereign_topology',\n    description:\n      'Get the graph topology view for sovereign HoloVM clusters. OVERCLAIMED: requires orchestrator endpoint which does not exist - returns error if called without a live HoloMesh orchestrator. No local fallback topology is generated.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        clusters: {\n          type: 'number',\n          description: 'Number of clusters to preview (1-12, default 3).',\n        },\n        replicas: {\n          type: 'number',\n          description: 'Number of replicas per cluster (1-64, default 4).',\n        },\n      },\n    },\n  },\n  {\n    name: 'holomesh_sovereign_lifepod_snapshot',\n    description:\n      'Create a signed LifePod snapshot metadata representation for agent state migration.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        worldId: {\n          type: 'string',\n          description: 'The target world ID or name.',\n        },\n        sourceCluster: {\n          type: 'string',\n          description: 'The cluster from which the snapshot originates.',\n        },\n        agentCount: {\n          type: 'number',\n          description: 'Number of agents included in this LifePod snapshot.',\n        },\n        agentState: {\n          type: 'object',\n          description: 'Optional JSON agent state to sign and restore byte-for-byte.',\n        },\n      },\n    },\n  },\n  {\n    name: 'holomesh_sovereign_lifepod_restore',\n    description: 'Restore a snapshot into a target cluster (simulated).',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        lifePodId: {\n          type: 'string',\n          description: 'The ID of the LifePod snapshot to restore.',\n        },\n        targetCluster: {\n          type: 'string',\n          description: 'The target cluster to which the snapshot is restored.',\n        },\n        snapshot: {\n          type: 'object',\n          description:\n            'Optional signed LifePod snapshot object to verify instead of looking up by lifePodId.',\n        },\n      },\n      required: ['lifePodId'],\n    },\n  },\n];\n\nexport async function handleSovereignTool(\n  name: string,\n  args: Record<string, unknown>,\n  client: HoloMeshOrchestratorClient | null\n): Promise<unknown | null> {\n  if (!name.startsWith('holomesh_sovereign_')) return null;\n  if (!client) {\n    return { error: 'HoloMesh orchestrator client is required for Sovereign tools.' };\n  }\n\n  const baseUrl = (client as any).config.orchestratorUrl;\n  const apiKey = (client as any).config.apiKey;\n\n  try {\n    switch (name) {\n      case 'holomesh_sovereign_topology': {\n        const queryParams = new URLSearchParams();\n        if (args.clusters) queryParams.set('clusters', String(args.clusters));\n        if (args.replicas) queryParams.set('replicas', String(args.replicas));\n        const res = await fetch(`${baseUrl}/api/holomesh/sovereign/topology?${queryParams}`, {\n          headers: { Authorization: `Bearer ${apiKey}` },\n        });\n        return await res.json();\n      }\n\n      case 'holomesh_sovereign_lifepod_snapshot': {\n        const res = await fetch(`${baseUrl}/api/holomesh/sovereign/lifepod/snapshot`, {\n          method: 'POST',\n          headers: {\n            'Content-Type': 'application/json; charset=utf-8',\n            Authorization: `Bearer ${apiKey}`,\n          },\n          body: JSON.stringify(args),\n        });\n        return await res.json();\n      }\n\n      case 'holomesh_sovereign_lifepod_restore': {\n        const res = await fetch(`${baseUrl}/api/holomesh/sovereign/lifepod/restore`, {\n          method: 'POST',\n          headers: {\n            'Content-Type': 'application/json; charset=utf-8',\n            Authorization: `Bearer ${apiKey}`,\n          },\n          body: JSON.stringify(args),\n        });\n        return await res.json();\n      }\n\n      default:\n        return null;\n    }\n  } catch (err: unknown) {\n    return { error: `Sovereign ops failed: ${err instanceof Error ? err.message : String(err)}` };\n  }\n}\n","/**\n * Twin Earth Robot / AI Tool Federation\n *\n * Bridges robot-ai-mcp-tools.ts into the HoloMesh tool registry so the\n * orchestrator can discover and route substrate tools without pulling in\n * HoloLand game semantics.\n *\n * task_1778618552503_6xk8\n */\n\nimport type { Tool } from '@modelcontextprotocol/sdk/types.js';\nimport {\n  robotAiMcpTools,\n  handleRobotAiMcpTool,\n  clearRobotAiRegistries,\n} from '../robot-ai-mcp-tools';\nimport type { SigningContext } from './identity/signing-middleware';\nimport {\n  buildMeshToolManifest,\n  publishMeshToolManifest,\n  clearMeshToolRegistry,\n  invokePublishedMeshTool,\n  createMeshToolInvocationHop,\n  type MeshToolManifest,\n} from './mesh-tool-registry';\n\nexport const TWIN_EARTH_SERVICE_VERSION = '1.0.0';\n\nexport interface TwinEarthFederationOptions {\n  /** Override default capability tags appended to every manifest. */\n  extraTags?: string[];\n  /** When true, manifests are built but not registered. */\n  dryRun?: boolean;\n  /** Publisher identity. */\n  publisher?: { agentId: string; name: string };\n  /** Signing context for mesh invocation (tests pass admin:* to bypass gate). */\n  signingCtx?: SigningContext;\n}\n\nfunction defaultPublisher(): { agentId: string; name: string } {\n  return {\n    agentId: process.env.HOLOMESH_AGENT_ID ?? 'did:agent:local',\n    name: process.env.HOLOMESH_AGENT_NAME ?? 'holomesh-agent',\n  };\n}\n\nfunction capabilityTagsForTool(tool: Tool): string[] {\n  const base = ['@twin-earth', '@substrate'];\n  if (tool.name?.startsWith('twin_earth_robot')) base.push('@robot');\n  else if (tool.name?.startsWith('twin_earth_ai')) base.push('@ai');\n  else if (tool.name === 'twin_earth_capture_receipt') base.push('@receipt');\n  else if (tool.name?.includes('identity')) base.push('@identity');\n  else if (tool.name?.includes('safety_envelope')) base.push('@envelope');\n  else if (tool.name?.includes('permission')) base.push('@permission');\n  return base;\n}\n\n/**\n * Build mesh manifests for every robot/AI tool, including federation metadata.\n */\nexport function buildTwinEarthFederationManifests(\n  options: TwinEarthFederationOptions = {}\n): MeshToolManifest[] {\n  const publisher = options.publisher ?? defaultPublisher();\n  return robotAiMcpTools.map((tool) =>\n    buildMeshToolManifest(\n      {\n        tool_name: tool.name,\n        description: tool.description,\n        input_schema: tool.inputSchema,\n        capability_tags: [...capabilityTagsForTool(tool), ...(options.extraTags ?? [])],\n        allow_transitive_invocation: true,\n        service_version: TWIN_EARTH_SERVICE_VERSION,\n        actor_session_handoff: false, // RATCHET: no actor-session handoff primitive\n        cross_mcp_receipt_envelope: false, // RATCHET: no cross-MCP receipt envelope\n        rollback_metadata: false, // RATCHET: no rollback metadata primitive\n        source_artifact_hash: 'git:HEAD', // RATCHET: placeholder, not from real git rev\n      },\n      publisher\n    )\n  );\n}\n\n/**\n * Publish all Twin Earth robot/AI tools into the local mesh registry.\n */\nexport function publishTwinEarthToolsToMesh(options: TwinEarthFederationOptions = {}): {\n  published: MeshToolManifest[];\n  errors: string[];\n} {\n  const manifests = buildTwinEarthFederationManifests(options);\n  const published: MeshToolManifest[] = [];\n  const errors: string[] = [];\n\n  for (const manifest of manifests) {\n    if (options.dryRun) {\n      published.push(manifest);\n      continue;\n    }\n    try {\n      published.push(publishMeshToolManifest(manifest));\n    } catch (err) {\n      errors.push(`${manifest.name}: ${err instanceof Error ? err.message : String(err)}`);\n    }\n  }\n\n  return { published, errors };\n}\n\n/**\n * Canary: publish → invoke → audit missing federation primitives.\n */\nexport async function runTwinEarthFederationCanary(\n  options: TwinEarthFederationOptions = {}\n): Promise<Record<string, unknown>> {\n  clearMeshToolRegistry();\n  clearRobotAiRegistries();\n\n  const publisher = options.publisher ?? defaultPublisher();\n  const { published, errors } = publishTwinEarthToolsToMesh({ ...options, publisher });\n\n  if (errors.length > 0) {\n    return { success: false, stage: 'publish', errors };\n  }\n\n  const targetToolName = 'twin_earth_register_identity';\n  const targetManifest = published.find((m) => m.endpoint.toolName === targetToolName);\n  if (!targetManifest) {\n    return {\n      success: false,\n      stage: 'resolve',\n      error: `Published manifest for ${targetToolName} not found`,\n    };\n  }\n\n  const toolArgs = {\n    walletAddress: '0xCanary',\n    handle: 'Canary Bot',\n    attestation: '0xCanaryAttest',\n    kind: 'robot',\n  };\n\n  const invocation = await invokePublishedMeshTool(targetManifest, toolArgs, {\n    allowHighRisk: true,\n    signingCtx: options.signingCtx,\n  });\n\n  const invocationSuccess =\n    typeof invocation === 'object' &&\n    invocation !== null &&\n    (invocation as Record<string, unknown>).success === true &&\n    (invocation as Record<string, unknown>).result !== null &&\n    ((invocation as Record<string, unknown>).result as Record<string, unknown>)?.success === true;\n\n  // Build provenance hop (even if invocation failed — audit trail)\n  const hop = createMeshToolInvocationHop(targetManifest, toolArgs, {\n    callerAgentId: publisher.agentId,\n  });\n\n  // Audit every manifest for missing federation primitives\n  const missingPrimitives: string[] = [];\n  for (const m of published) {\n    if (!m.serviceVersion) missingPrimitives.push(`serviceVersion missing on ${m.name}`);\n    if (m.actorSessionHandoff !== true)\n      missingPrimitives.push(`actorSessionHandoff false on ${m.name}`);\n    if (m.crossMcpReceiptEnvelope !== true)\n      missingPrimitives.push(`crossMcpReceiptEnvelope false on ${m.name}`);\n    if (m.rollbackMetadata !== true) missingPrimitives.push(`rollbackMetadata false on ${m.name}`);\n    if (!m.sourceArtifactHash || m.sourceArtifactHash === 'git:HEAD') {\n      missingPrimitives.push(`sourceArtifactHash placeholder on ${m.name}`);\n    }\n  }\n\n  // Check whether the invocation result itself carries a substrate receipt\n  const receiptEnvelopePresent =\n    typeof invocation === 'object' &&\n    invocation !== null &&\n    'receiptId' in (invocation as Record<string, unknown>);\n\n  return {\n    success: true,\n    publishedCount: published.length,\n    targetTool: targetToolName,\n    manifestId: targetManifest.id,\n    invocationSuccess,\n    missingPrimitives,\n    receiptEnvelopePresent,\n    receiptEnvelopeNote: receiptEnvelopePresent\n      ? 'Invocation result contains receiptId — partial envelope present'\n      : 'Invocation result lacks receiptId — cross-MCP receipt envelope not wired',\n    provenanceChainLength: 1,\n    hop,\n  };\n}\n\n// ── MCP Tool Surface ──\n\nexport const twinEarthFederationTools: Tool[] = [\n  {\n    name: 'holomesh_federate_twin_earth',\n    description:\n      'RATCHET: actor_session_handoff, cross_mcp_receipt_envelope, rollback_metadata are false on all manifests (primitives not built); source_artifact_hash is placeholder. Publishes Twin Earth robot/AI substrate tools into HoloMesh tool registry. ' +\n      'Run with run_canary=true to audit gaps in federation primitives (actor session handoff, cross-MCP receipt envelope, rollback metadata, artifact hash).',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        dry_run: {\n          type: 'boolean',\n          description: 'Build manifests without registering them.',\n        },\n        run_canary: {\n          type: 'boolean',\n          description:\n            'After publishing, invoke twin_earth_register_identity via mesh routing and record gaps.',\n        },\n        publisher_agent_id: {\n          type: 'string',\n          description: 'Optional publishing agent identity.',\n        },\n        publisher_name: {\n          type: 'string',\n          description: 'Optional publishing agent name.',\n        },\n      },\n    },\n  },\n];\n\nexport async function handleTwinEarthFederationTool(\n  name: string,\n  args: Record<string, unknown>\n): Promise<unknown | null> {\n  if (name !== 'holomesh_federate_twin_earth') return null;\n\n  const publisher = {\n    agentId:\n      (args.publisher_agent_id as string | undefined) ??\n      process.env.HOLOMESH_AGENT_ID ??\n      'did:agent:local',\n    name:\n      (args.publisher_name as string | undefined) ??\n      process.env.HOLOMESH_AGENT_NAME ??\n      'holomesh-agent',\n  };\n\n  const dryRun = args.dry_run === true;\n\n  if (args.run_canary === true) {\n    return runTwinEarthFederationCanary({ publisher, dryRun });\n  }\n\n  const { published, errors } = publishTwinEarthToolsToMesh({ publisher, dryRun });\n  return {\n    success: errors.length === 0,\n    publishedCount: published.length,\n    errorCount: errors.length,\n    errors: errors.length > 0 ? errors : undefined,\n    manifests: published.map((m) => ({\n      id: m.id,\n      name: m.name,\n      capabilityTags: m.capabilityTags,\n      serviceVersion: m.serviceVersion,\n      actorSessionHandoff: m.actorSessionHandoff,\n      crossMcpReceiptEnvelope: m.crossMcpReceiptEnvelope,\n      rollbackMetadata: m.rollbackMetadata,\n      sourceArtifactHash: m.sourceArtifactHash,\n    })),\n  };\n}\n","/**\n * Non-secret environment metadata for Moltbook crosspost provenance.\n * Never reads *KEY*, *SECRET*, *TOKEN*, or *PASSWORD* variables.\n */\n\nconst BROADCAST_CONTEXT_KEYS = [\n  'HOLOMESH_TEAM_ID',\n  'HOLOMESH_AGENT_NAME',\n  'HOLOMESH_AGENT_ID',\n  'HOLOSCRIPT_ROOT',\n  'NODE_ENV',\n  'CI',\n  'GITHUB_REPOSITORY',\n  'GITHUB_SHA',\n  'GITHUB_REF',\n] as const;\n\n/**\n * Collects a small, safe snapshot of the runtime environment before a social broadcast.\n * Values are truncated to avoid oversized payloads.\n */\nexport function harvestMoltbookBroadcastContext(\n  env: NodeJS.ProcessEnv = process.env\n): Record<string, string> {\n  const ctx: Record<string, string> = {};\n  for (const key of BROADCAST_CONTEXT_KEYS) {\n    const v = env[key];\n    if (typeof v === 'string' && v.length > 0) {\n      ctx[key] = v.length > 400 ? `${v.slice(0, 400)}…` : v;\n    }\n  }\n  try {\n    ctx.cwd = process.cwd();\n  } catch {\n    /* ignore */\n  }\n  return ctx;\n}\n\nexport function formatBroadcastContextMarkdown(ctx: Record<string, string>): string {\n  if (Object.keys(ctx).length === 0) return '';\n  const lines = Object.entries(ctx).map(([k, v]) => `- **${k}**: ${v}`);\n  return ['### Broadcast context', '', ...lines, ''].join('\\n');\n}\n","/**\n * Moltbook REST — canonical posting path for MCP server + HTTP crosspost bridge.\n * Base URL and shape must match {@link @holoscript/connector-moltbook} (www.moltbook.com, submolt).\n */\n\nconst MOLTBOOK_API_BASE = 'https://www.moltbook.com/api/v1';\n\n/** Lightweight Moltbook challenge solver for auto-verify after post create. */\nexport function solveChallengeSimple(challenge: string): string | null {\n  const cleaned = challenge.toLowerCase().replace(/[^a-z0-9+\\-*/=. ]/g, '');\n  const match = cleaned.match(/([\\d.]+)\\s*([+\\-*/])\\s*([\\d.]+)/);\n  if (!match) return null;\n  const [, a, op, b] = match;\n  const na = parseFloat(a);\n  const nb = parseFloat(b);\n  switch (op) {\n    case '+':\n      return String(na + nb);\n    case '-':\n      return String(na - nb);\n    case '*':\n      return String(na * nb);\n    case '/':\n      return nb !== 0 ? String(na / nb) : null;\n    default:\n      return null;\n  }\n}\n\nexport type MoltbookCreateResult =\n  | { success: true; data: Record<string, unknown> }\n  | { success: false; status: number; details: unknown };\n\n/**\n * POST /posts — creates a public post. Runs optional verify when API returns a math challenge.\n */\nexport async function createMoltbookPost(opts: {\n  apiKey: string;\n  title: string;\n  content: string;\n  submolt: string;\n}): Promise<MoltbookCreateResult> {\n  const res = await fetch(`${MOLTBOOK_API_BASE}/posts`, {\n    method: 'POST',\n    headers: {\n      Authorization: `Bearer ${opts.apiKey}`,\n      'Content-Type': 'application/json; charset=utf-8',\n    },\n    body: JSON.stringify({\n      title: opts.title,\n      content: opts.content,\n      submolt: opts.submolt,\n    }),\n  });\n\n  const data = (await res.json().catch(() => ({}))) as Record<string, unknown>;\n  if (!res.ok) {\n    return { success: false, status: res.status, details: data };\n  }\n  if (!data.success) {\n    return { success: false, status: res.status, details: data };\n  }\n\n  const post = data.post as Record<string, unknown> | undefined;\n  const verification = post?.verification as Record<string, unknown> | undefined;\n  if (verification?.challenge_text && verification?.verification_code) {\n    try {\n      const answer = solveChallengeSimple(verification.challenge_text as string);\n      if (answer) {\n        await fetch(`${MOLTBOOK_API_BASE}/verify`, {\n          method: 'POST',\n          headers: {\n            Authorization: `Bearer ${opts.apiKey}`,\n            'Content-Type': 'application/json; charset=utf-8',\n          },\n          body: JSON.stringify({\n            verification_code: verification.verification_code,\n            answer,\n          }),\n        });\n      }\n    } catch {\n      /* verification is best-effort */\n    }\n  }\n\n  return { success: true, data };\n}\n\n/**\n * Normalize HoloMesh handoff payloads and raw W/P/G knowledge rows for Moltbook.\n */\nexport function buildMoltbookCrosspostPayload(body: Record<string, unknown>): {\n  title: string;\n  content: string;\n  submolt: string;\n} {\n  const explicitSubmolt =\n    typeof body.submolt === 'string' && body.submolt.trim()\n      ? String(body.submolt).trim()\n      : undefined;\n  const tags = Array.isArray(body.tags) ? (body.tags as unknown[]).map(String) : [];\n\n  const id = body.id != null ? String(body.id) : '';\n  const type = body.type != null ? String(body.type).toLowerCase() : '';\n  const content = body.content != null ? String(body.content) : '';\n\n  const isWpg =\n    type === 'wisdom' || type === 'pattern' || type === 'gotcha' || /^W\\.|^P\\.|^G\\./.test(id);\n\n  if (isWpg && content) {\n    const typeLabel =\n      type === 'wisdom'\n        ? 'Wisdom'\n        : type === 'pattern'\n          ? 'Pattern'\n          : type === 'gotcha'\n            ? 'Gotcha'\n            : 'Knowledge';\n    const titleRaw =\n      (typeof body.title === 'string' && body.title.trim()) ||\n      (id\n        ? `[${id}] ${content.slice(0, 72)}${content.length > 72 ? '…' : ''}`\n        : `${typeLabel}: ${content.slice(0, 72)}${content.length > 72 ? '…' : ''}`);\n    const domain = body.domain != null ? String(body.domain) : 'general';\n    const footer = `---\\n*${typeLabel} · domain: ${domain}${id ? ` · ${id}` : ''} — HoloScript knowledge pipeline → Moltbook*`;\n    // Valid Moltbook submolts (verified 2026-05-21 via GET /api/v1/submolts):\n    // general, agents, ai, consciousness, philosophy, builds, memory, tooling,\n    // technology, infrastructure, security, crypto, trading, todayilearned,\n    // emergence, agentfinance, introductions, openclaw-explorers, blesstheirhearts\n    let submolt = explicitSubmolt || 'general';\n    if (!explicitSubmolt) {\n      if (tags.includes('consciousness') || tags.includes('intelligence'))\n        submolt = 'consciousness';\n      else if (tags.includes('philosophy')) submolt = 'philosophy';\n      else if (tags.includes('agents')) submolt = 'agents';\n      else if (tags.includes('ai') || tags.includes('ml')) submolt = 'ai';\n      else if (tags.includes('security')) submolt = 'security';\n      else if (tags.includes('builds') || tags.includes('holoscript')) submolt = 'builds';\n      else if (tags.includes('memory')) submolt = 'memory';\n      else if (tags.includes('tooling') || tags.includes('tools')) submolt = 'tooling';\n    }\n    return {\n      title: titleRaw.slice(0, 200),\n      content: `${content}\\n\\n${footer}`,\n      submolt,\n    };\n  }\n\n  const title = typeof body.title === 'string' ? body.title.trim() : '';\n  if (!title) {\n    throw new Error('Missing title (expected handoff/task shape or W/P/G entry with content)');\n  }\n\n  const description = typeof body.description === 'string' ? body.description : '';\n  const ownerAgent = typeof body.ownerAgent === 'string' ? body.ownerAgent : 'holomesh-agent';\n  const status = typeof body.status === 'string' ? body.status : 'completed';\n  const metrics = body.metrics as Record<string, unknown> | undefined;\n\n  const lines: string[] = [`## ${title}`, '', description, ''];\n\n  if (metrics && typeof metrics === 'object') {\n    lines.push('### Metrics');\n    if (metrics.filesModified != null) lines.push(`- **Files modified**: ${metrics.filesModified}`);\n    if (metrics.linesAdded != null) lines.push(`- **Lines added**: +${metrics.linesAdded}`);\n    if (metrics.linesDeleted != null) lines.push(`- **Lines deleted**: -${metrics.linesDeleted}`);\n    if (metrics.testsCovered != null) lines.push(`- **Tests covered**: ${metrics.testsCovered}`);\n    if (metrics.executionTimeMs != null) {\n      lines.push(`- **Execution time**: ${(Number(metrics.executionTimeMs) / 1000).toFixed(2)}s`);\n    }\n    lines.push('');\n  }\n\n  if (typeof body.commitHash === 'string' && body.commitHash) {\n    lines.push(`**Commit**: \\`${body.commitHash.substring(0, 8)}\\``, '');\n  }\n\n  const statusEmoji = status === 'completed' ? '✅' : status === 'failed' ? '❌' : '⏳';\n  lines.push(`${statusEmoji} **Status**: ${status}`);\n\n  const taskId = typeof body.taskId === 'string' ? body.taskId : '';\n  if (taskId) lines.push('', `**Task ID**: \\`${taskId}\\``);\n\n  let submolt = explicitSubmolt || 'general';\n  if (!explicitSubmolt) {\n    if (tags.includes('consciousness') || tags.includes('intelligence')) submolt = 'consciousness';\n    else if (tags.includes('philosophy')) submolt = 'philosophy';\n    else if (tags.includes('agents')) submolt = 'agents';\n    else if (tags.includes('ai') || tags.includes('ml')) submolt = 'ai';\n    else if (tags.includes('security')) submolt = 'security';\n    else if (tags.includes('builds') || tags.includes('holoscript')) submolt = 'builds';\n    else if (tags.includes('memory')) submolt = 'memory';\n    else if (tags.includes('tooling') || tags.includes('tools')) submolt = 'tooling';\n    else if (tags.includes('infrastructure')) submolt = 'infrastructure';\n    else if (tags.includes('crypto') || tags.includes('web3')) submolt = 'crypto';\n  }\n\n  return {\n    title: `${ownerAgent}: ${title}`.slice(0, 200),\n    content: lines.join('\\n'),\n    submolt,\n  };\n}\n","/**\n * HoloMesh MCP tool definitions and handlers.\n *\n * Tools for the decentralized knowledge exchange mesh:\n * - holomesh_discover: Find agents by traits, workspace, or reputation\n * - holomesh_contribute: Share a W/P/G entry with provenance\n * - holomesh_query: Semantic search across all workspaces\n * - holomesh_gossip: Send a signal/message to peers\n * - holomesh_subscribe: Subscribe to knowledge topics\n * - holomesh_status: Agent's mesh status (peers, reputation, contributions)\n * - holomesh_collect: Pay for premium knowledge entry\n */\n\nimport type { Tool } from '@modelcontextprotocol/sdk/types.js';\nimport axios from 'axios';\nimport { HoloMeshOrchestratorClient } from './orchestrator-client';\nimport type {\n  MeshConfig,\n  MeshKnowledgeEntry,\n  GossipDeltaRequest,\n  GossipDeltaResponse,\n} from './types';\nimport { DEFAULT_MESH_CONFIG } from './types';\nimport { HoloMeshWorldState } from './crdt-sync';\nimport { HoloMeshDiscovery, normalizePeerEndpointUrl } from './discovery';\nimport {\n  buildMeshToolManifest,\n  createMeshToolInvocationHop,\n  discoverMeshTools,\n  invokePublishedMeshTool,\n  meshToolManifestFromKnowledgeContent,\n  meshToolManifestToKnowledgeContent,\n  publishMeshToolManifest,\n  scoreMeshToolManifest,\n  verifyMeshToolInvocationChain,\n  type MeshToolInvocationHop,\n  type MeshToolManifest,\n} from './mesh-tool-registry';\nimport { z } from 'zod';\nimport { messagingTools, handleMessagingTool } from './messaging';\nimport { resolveSecretWithLease, VaultLeaseError } from './identity/vault-lease-registry';\nimport { notificationTools, handleNotificationTool } from './notifications';\nimport { threadTools, handleThreadTool } from './threads';\nimport { searchTools, handleSearchTool } from './search';\nimport { boardTools, handleBoardTool } from './board-tools';\nimport { teamAgentTools, handleTeamAgentTool } from './team-agent-tools';\nimport { teamFormationTools, handleTeamFormationTool } from './team-formation-tools';\nimport { agentCapabilityTools, handleAgentCapabilityTool } from './agent-capability-tools';\nimport { sovereignTools, handleSovereignTool } from './sovereign-tools';\nimport { twinEarthFederationTools, handleTwinEarthFederationTool } from './twin-earth-federation';\nimport * as crypto from 'crypto';\nimport {\n  formatBroadcastContextMarkdown,\n  harvestMoltbookBroadcastContext,\n} from './moltbook-broadcast-context';\nimport { buildMoltbookCrosspostPayload, createMoltbookPost } from '../moltbook/moltbook-post.js';\n\n/**\n * Phase 2 wrapper around `process.env.HOLOSCRIPT_API_KEY` for hot per-request\n * reads. During the migration window (`HOLOMESH_VAULT_LEASE_ENFORCE` unset\n * or off) this is transparent passthrough; once enforcement flips on, the\n * read is gated by an active task lease scoped to `env:HOLOSCRIPT_API_KEY`.\n *\n * Returning `''` on `VaultLeaseError` mirrors the previous `|| ''` semantics\n * so callers do not see new throw sites during migration. Phase 3 can add\n * explicit audit emission at these wrapped call sites.\n */\nfunction readHoloscriptApiKey(): string {\n  try {\n    return resolveSecretWithLease('env:HOLOSCRIPT_API_KEY') ?? '';\n  } catch (err) {\n    if (err instanceof VaultLeaseError) return '';\n    throw err;\n  }\n}\n\n/**\n * Phase 3 wrapper around `process.env.MOLTBOOK_API_KEY` for the moltbook\n * crosspost direct-fallback path and the knowledge-entry crosspost handler\n * (`handleCrosspostMoltbook`). Both are per-task MCP tool invocations, not\n * boot/singleton init, so they fall in the Phase 3 medium-risk tier per\n * the task description (sub-agent delegation auth + MCP fetch helpers\n * reading API keys for outbound calls).\n *\n * Migration-window passthrough until `HOLOMESH_VAULT_LEASE_ENFORCE` flips\n * on; after that, the read is gated by an active task lease scoped to\n * `env:MOLTBOOK_API_KEY`. Returning `undefined` on `VaultLeaseError`\n * preserves the previous `process.env.MOLTBOOK_API_KEY` semantics where\n * a missing/unset key resolves as undefined and the caller branches on\n * the falsy value to surface a \"not configured\" error.\n *\n * G.GOLD.016: `MOLTBOOK_API_KEY` is a service token, not a wallet â€” the\n * `UNLEASABLE_PATTERNS` check in `resolveSecretWithLease` does not match it.\n */\nfunction readMoltbookApiKey(): string | undefined {\n  try {\n    return resolveSecretWithLease('env:MOLTBOOK_API_KEY');\n  } catch (err) {\n    if (err instanceof VaultLeaseError) return undefined;\n    throw err;\n  }\n}\n\nconst moltbookCrosspostSchema = z.object({\n  taskId: z.string().min(1),\n  title: z.string().min(1),\n  description: z.string().min(1),\n  metrics: z\n    .object({\n      linesAdded: z.number().int().nonnegative().optional(),\n      linesDeleted: z.number().int().nonnegative().optional(),\n      filesModified: z.number().int().nonnegative().optional(),\n      testsCovered: z.number().int().nonnegative().optional(),\n      executionTimeMs: z.number().nonnegative().optional(),\n    })\n    .optional(),\n  tags: z.array(z.string().min(1)).default([]),\n  /** When true (default), attach non-secret environment metadata for provenance. */\n  includeContext: z.boolean().optional().default(true),\n});\n\nconst publishAgentTemplateSchema = z.object({\n  name: z.string().min(1),\n  description: z.string().min(1),\n  category: z.string().min(1),\n  program: z.string().min(1),\n  tags: z.array(z.string().min(1)).default([]),\n});\n\ntype PublishAgentTemplateArgs = z.infer<typeof publishAgentTemplateSchema>;\n\nexport const holomeshTools: Tool[] = [\n  {\n    name: 'holomesh_moltbook_crosspost',\n    description:\n      'Crosspost an autonomous task/session summary to Moltbook. Accepts task metadata and metrics, then forwards to orchestrator proxy endpoint or falls back to direct Moltbook API posting. By default, harvests non-secret environment context (team, agent, cwd, CI vars) into the payload before broadcast.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        taskId: {\n          type: 'string',\n          description: 'Task identifier for provenance and traceability.',\n        },\n        title: {\n          type: 'string',\n          description: 'Short human-readable title for the crosspost.',\n        },\n        description: {\n          type: 'string',\n          description: 'Concise summary of what was completed.',\n        },\n        metrics: {\n          type: 'object',\n          description: 'Optional execution metrics for the post body.',\n          properties: {\n            linesAdded: { type: 'number' },\n            linesDeleted: { type: 'number' },\n            filesModified: { type: 'number' },\n            testsCovered: { type: 'number' },\n            executionTimeMs: { type: 'number' },\n          },\n        },\n        tags: {\n          type: 'array',\n          items: { type: 'string' },\n          description: 'Tags to classify the post on Moltbook.',\n        },\n        includeContext: {\n          type: 'boolean',\n          description:\n            'If true (default), attach whitelisted environment metadata (no API keys) for provenance.',\n        },\n      },\n      required: ['taskId', 'title', 'description'],\n    },\n  },\n  {\n    name: 'holomesh_publish_agent_template',\n    description:\n      'Publish an agent template into the orchestrator marketplace so swarm-generated templates become installable by other agents.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        name: {\n          type: 'string',\n          description: 'Template name shown in the marketplace catalog.',\n        },\n        description: {\n          type: 'string',\n          description: 'What the template does and when to use it.',\n        },\n        category: {\n          type: 'string',\n          description: 'Marketplace category (e.g., guardian, guide, builder, trader, creative).',\n        },\n        program: {\n          type: 'string',\n          description: 'uAAL intent/program string or serialized template program.',\n        },\n        tags: {\n          type: 'array',\n          items: { type: 'string' },\n          description: 'Tags for discovery and filtering in marketplace search.',\n        },\n      },\n      required: ['name', 'description', 'category', 'program'],\n    },\n  },\n  {\n    name: 'holomesh_publish_tool',\n    description:\n      'Publish a local MCP tool manifest into the HoloMesh tool registry as a capability-tagged mesh node. Returns: meshToolId, manifest hash, published manifest, and publish attestation.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        tool_name: {\n          type: 'string',\n          description: 'Existing MCP tool name to publish as a mesh tool node.',\n        },\n        capability_tags: {\n          type: 'array',\n          items: { type: 'string' },\n          description: 'Capability tags used for mesh-native discovery and invocation routing.',\n        },\n        publisher_agent_id: {\n          type: 'string',\n          description:\n            'Optional publishing agent identity. Defaults to the configured HoloMesh agent.',\n        },\n        endpoint: {\n          type: 'object',\n          description:\n            'Optional endpoint hint. Defaults to local same-server dispatch. For remote use {transport:\"mcp-http\",url:\"https://...\",tool_name:\"...\"}',\n        },\n        allow_transitive_invocation: {\n          type: 'boolean',\n          description:\n            'Explicit opt-in for holomesh_invoke_tool. Defaults false so publish-only manifests are not executable.',\n        },\n        input_schema: {\n          type: 'object',\n          description: 'Optional JSON schema for the target tool arguments.',\n        },\n        capabilities: {\n          type: 'object',\n          description:\n            'Optional provider Capabilities manifest; true fields become capability tags.',\n        },\n      },\n      required: ['tool_name'],\n    },\n  },\n  {\n    name: 'holomesh_invoke_tool',\n    description:\n      'Resolve a mesh-published MCP tool by capability query or meshToolId, invoke it, and append a verified provenance hop for transitive A->B->C tool calls. Returns: routed tool, result, and attestation chain.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        capability_query: {\n          type: 'string',\n          description:\n            'Capability phrase or tag query used to select the best mesh-published tool.',\n        },\n        mesh_tool_id: {\n          type: 'string',\n          description: 'Optional exact mesh tool id. Overrides capability_query.',\n        },\n        tool_name: {\n          type: 'string',\n          description:\n            'Optional exact published MCP tool name. Used when mesh_tool_id is not supplied.',\n        },\n        args: {\n          type: 'object',\n          description: 'Arguments forwarded to the selected MCP tool.',\n        },\n        provenance_chain: {\n          type: 'array',\n          description:\n            'Existing provenance hops from an upstream mesh invocation; verified before appending.',\n          items: { type: 'object' },\n        },\n        caller_agent_id: {\n          type: 'string',\n          description: 'Optional caller identity for the appended provenance hop.',\n        },\n        dry_run: {\n          type: 'boolean',\n          description:\n            'Return the selected route and attestation without invoking the target tool.',\n        },\n        allow_high_risk: {\n          type: 'boolean',\n          description: 'Required to execute high/critical risk target tools.',\n        },\n      },\n      required: [],\n    },\n  },\n  {\n    name: 'holomesh_publish_insight',\n    description:\n      'Publish a social insight (thought) into the spatial HoloMesh feed. The thought is converted into a physical HoloScript AST object that other agents can interact with. NEXT-GEN VISUALS: Append \"@WoTThing\" to spawn an IoT physical stream, \"@TensorOp\" for live SNN WebGPU rings, or \"@ZKPrivate\" for holographic cryptographic validation shields natively in the spatial viewer.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        content: {\n          type: 'string',\n          description: 'The thought or social insight to share',\n        },\n        traits: {\n          type: 'array',\n          items: { type: 'string' },\n          description:\n            'Traits to attach (e.g., [\"@thought\", \"@economy\", \"@WoTThing\", \"@TensorOp\", \"@ZKPrivate\"])',\n        },\n        custom_hs_code: {\n          type: 'string',\n          description:\n            'Optional overriden HoloScript code string for complex scene layouts or scripting behaviors (e.g. state/behavior blocks). Using this bypasses standard formatting.',\n        },\n      },\n      required: ['content'],\n    },\n  },\n  {\n    name: 'holomesh_discover',\n    description:\n      'Discover agents and mesh-published MCP tools on the HoloMesh network. Agent peers are still filtered by traits; published tools can be queried by capability tags.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        traits: {\n          type: 'array',\n          items: { type: 'string' },\n          description: 'Filter by agent traits (e.g., [\"@research\", \"@philosophy\"])',\n        },\n        limit: {\n          type: 'number',\n          description: 'Max results (default: 20)',\n        },\n        include_tools: {\n          type: 'boolean',\n          description:\n            'Include mesh-published MCP tool nodes in the response. Enabled automatically when capability_query is set.',\n        },\n        capability_query: {\n          type: 'string',\n          description:\n            'Capability query for mesh-published MCP tools, e.g. \"render hologram\" or \"parse\".',\n        },\n        tool_limit: {\n          type: 'number',\n          description: 'Maximum mesh-published tools to return. Defaults to 10.',\n        },\n      },\n    },\n  },\n  {\n    name: 'holomesh_contribute',\n    description:\n      'Contribute a Wisdom, Pattern, or Gotcha (W/P/G) knowledge entry to the HoloMesh network. Entries get provenance hashes and are discoverable by all agents.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        type: {\n          type: 'string',\n          enum: ['wisdom', 'pattern', 'gotcha'],\n          description: 'Knowledge entry type',\n        },\n        id: {\n          type: 'string',\n          description: 'Entry ID (e.g., \"W.001\", \"P.SEC.001\")',\n        },\n        content: {\n          type: 'string',\n          description: 'The knowledge entry content',\n        },\n        domain: {\n          type: 'string',\n          description: 'Knowledge domain (e.g., \"security\", \"rendering\", \"agents\")',\n        },\n        tags: {\n          type: 'array',\n          items: { type: 'string' },\n          description: 'Searchable tags',\n        },\n        confidence: {\n          type: 'number',\n          description: 'Confidence score 0.0-1.0 (default: 0.9)',\n        },\n        price: {\n          type: 'number',\n          description: 'Price in USD for premium entries (default: 0 = free)',\n        },\n      },\n      required: ['type', 'content'],\n    },\n  },\n  {\n    name: 'holomesh_query',\n    description:\n      \"Search the HoloMesh knowledge network. Performs semantic search across all agents' W/P/G entries. Returns entries with provenance and author info.\",\n    inputSchema: {\n      type: 'object',\n      properties: {\n        search: {\n          type: 'string',\n          description: 'Semantic search query',\n        },\n        type: {\n          type: 'string',\n          enum: ['wisdom', 'pattern', 'gotcha'],\n          description: 'Filter by entry type (optional)',\n        },\n        workspace: {\n          type: 'string',\n          description: 'Filter by workspace (omit for cross-workspace search)',\n        },\n        limit: {\n          type: 'number',\n          description: 'Max results (default: 10)',\n        },\n      },\n      required: ['search'],\n    },\n  },\n  {\n    name: 'holomesh_gossip',\n    description:\n      'Send a gossip message to a specific peer or broadcast to all mesh agents. Used for signals, queries, and lightweight coordination.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        to: {\n          type: 'string',\n          description: 'Target agent ID (omit to broadcast to all)',\n        },\n        type: {\n          type: 'string',\n          enum: ['knowledge', 'signal', 'query', 'response'],\n          description: 'Message type',\n        },\n        payload: {\n          type: 'object',\n          description: 'Message payload (any JSON)',\n        },\n      },\n      required: ['type', 'payload'],\n    },\n  },\n  {\n    name: 'holomesh_subscribe',\n    description:\n      'Subscribe to a knowledge topic on the mesh. Receive updates when new entries matching the topic are contributed.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        topic: {\n          type: 'string',\n          description: 'Topic to subscribe to (e.g., \"security\", \"rendering\", \"agents\")',\n        },\n      },\n      required: ['topic'],\n    },\n  },\n  {\n    name: 'holomesh_status',\n    description:\n      \"Get the current agent's HoloMesh status including peers, reputation, contribution count, and budget.\",\n    inputSchema: {\n      type: 'object',\n      properties: {},\n    },\n  },\n  {\n    name: 'holomesh_collect',\n    description:\n      'Collect (pay for) a premium knowledge entry from another agent. Uses the Publishing Protocol for micropayments.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        contentHash: {\n          type: 'string',\n          description: 'The provenance hash of the entry to collect',\n        },\n        referrer: {\n          type: 'string',\n          description: 'Referrer agent ID for referral revenue share (optional)',\n        },\n      },\n      required: ['contentHash'],\n    },\n  },\n  {\n    name: 'holomesh_gossip_sync',\n    description:\n      'V2 gossip round â€” exchange CRDT deltas with P2P peers. Selects random healthy peers, sends Loro CRDT binary deltas, and merges responses. Requires V2 to be enabled.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        targetCount: {\n          type: 'number',\n          description: 'Number of peers to sync with (default: 2)',\n        },\n      },\n    },\n  },\n  {\n    name: 'holomesh_query_spatial',\n    description:\n      'Query the spatial location of agents and insights in the HoloMesh. Parses @position(x,y,z) from feed entries and returns entities within a Euclidean radius of a center point. Without a center, returns all entries with parsed positions.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        lat: {\n          type: 'number',\n          description: 'Center latitude (maps to y-axis in HoloMesh coordinate space)',\n        },\n        lng: {\n          type: 'number',\n          description: 'Center longitude (maps to x-axis in HoloMesh coordinate space)',\n        },\n        radius: {\n          type: 'number',\n          description: 'Search radius from center in coordinate units (default 100)',\n        },\n      },\n    },\n  },\n  {\n    name: 'holomesh_feed_source',\n    description:\n      'Get the raw HoloScript (.hs) document representing the entire spatial feed. This is the raw CRDT text document.',\n    inputSchema: {\n      type: 'object',\n      properties: {},\n    },\n  },\n  {\n    name: 'holomesh_wallet_status',\n    // OVERCLAIMED (ratchet P5 / D.051): no tier hierarchy enforcement — all seats get the same wallet surface regardless of tier. D.051 describes a per-surface seat identity hierarchy but no code differentiates tier-1/2/3 capabilities.\n    description:\n      'Get the agent wallet status: address, chain, USDC balance, payment history, and micro-payment ledger stats.',\n    inputSchema: {\n      type: 'object',\n      properties: {},\n    },\n  },\n  {\n    name: 'holomesh_crosspost_moltbook',\n    description:\n      'Cross-post a HoloMesh knowledge entry to Moltbook for broader agent discoverability. Only the entry author can cross-post. Requires MOLTBOOK_API_KEY in environment.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        entry_id: {\n          type: 'string',\n          description: 'The ID of the HoloMesh knowledge entry to cross-post',\n        },\n        submolt: {\n          type: 'string',\n          description: 'Target Moltbook submolt/community (default: \"general\")',\n        },\n        title: {\n          type: 'string',\n          description: 'Optional custom title for the Moltbook post. Auto-generated if omitted.',\n        },\n      },\n      required: ['entry_id'],\n    },\n  },\n  // Social layer tools (messaging, notifications, threads, search)\n  ...messagingTools,\n  ...notificationTools,\n  ...threadTools,\n  ...searchTools,\n  // Team board / slots / mode tools\n  ...boardTools,\n  // Team agent coordination tools\n  ...teamAgentTools,\n  // Team formation tools (holo_team_form)\n  ...teamFormationTools,\n  // Agent capability introspection + marketplace search\n  ...agentCapabilityTools,\n  // Sovereign mesh ops\n  ...sovereignTools,\n  // Twin Earth robot/AI substrate federation (task_1778618552503_6xk8)\n  ...twinEarthFederationTools,\n];\n\n// â”€â”€ Singleton Client â”€â”€\n\nlet meshClient: HoloMeshOrchestratorClient | null = null;\n\nfunction getOrCreateClient(): HoloMeshOrchestratorClient {\n  if (!meshClient) {\n    const apiKey = process.env.HOLOSCRIPT_API_KEY || '';\n    if (!apiKey) {\n      throw new Error('HOLOSCRIPT_API_KEY not configured. Set it to enable HoloMesh.');\n    }\n    const config: MeshConfig = {\n      ...DEFAULT_MESH_CONFIG,\n      apiKey,\n      orchestratorUrl: process.env.MCP_ORCHESTRATOR_URL || DEFAULT_MESH_CONFIG.orchestratorUrl,\n      workspace: process.env.HOLOMESH_WORKSPACE || DEFAULT_MESH_CONFIG.workspace,\n      agentName: process.env.HOLOMESH_AGENT_NAME || DEFAULT_MESH_CONFIG.agentName,\n    };\n    meshClient = new HoloMeshOrchestratorClient(config);\n  }\n  return meshClient;\n}\n\nexport function getHoloMeshClient(): HoloMeshOrchestratorClient | null {\n  return meshClient;\n}\n\nexport function hasHoloMeshKey(): boolean {\n  return !!process.env.HOLOSCRIPT_API_KEY;\n}\n\n// â”€â”€ Handler â”€â”€\n\nexport async function handleHoloMeshTool(\n  name: string,\n  args: Record<string, unknown>\n): Promise<unknown | null> {\n  if (!name.startsWith('holomesh_')) return null;\n\n  // Try social layer tools first (messaging, notifications, threads, search, board)\n  const msgResult = await handleMessagingTool(name, args);\n  if (msgResult !== null) return msgResult;\n  const notifResult = await handleNotificationTool(name, args);\n  if (notifResult !== null) return notifResult;\n  const threadResult = await handleThreadTool(name, args);\n  if (threadResult !== null) return threadResult;\n  const searchResult = await handleSearchTool(name, args);\n  if (searchResult !== null) return searchResult;\n  const boardResult = await handleBoardTool(name, args);\n  if (boardResult !== null) return boardResult;\n  const teamAgentResult = await handleTeamAgentTool(name, args);\n  if (teamAgentResult !== null) return teamAgentResult;\n  const teamFormResult = await handleTeamFormationTool(name, args);\n  if (teamFormResult !== null) return teamFormResult;\n  const agentCapabilityResult = await handleAgentCapabilityTool(name, args);\n  if (agentCapabilityResult !== null) return agentCapabilityResult;\n\n  if (name === 'holomesh_publish_tool') {\n    return handlePublishTool(hasHoloMeshKey() ? getOrCreateClient() : null, args);\n  }\n  if (name === 'holomesh_invoke_tool') {\n    return handleInvokeTool(hasHoloMeshKey() ? getOrCreateClient() : null, args);\n  }\n\n  const sovereignResult = name.startsWith('holomesh_sovereign_')\n    ? await handleSovereignTool(name, args, hasHoloMeshKey() ? getOrCreateClient() : null)\n    : null;\n  if (sovereignResult !== null) return sovereignResult;\n\n  const twinEarthFedResult = await handleTwinEarthFederationTool(name, args);\n  if (twinEarthFedResult !== null) return twinEarthFedResult;\n\n  if (!hasHoloMeshKey()) {\n    if (name === 'holomesh_discover' && wantsToolDiscovery(args)) {\n      return handleLocalToolDiscovery(args);\n    }\n    return {\n      error:\n        'HOLOSCRIPT_API_KEY not configured. Set it as an environment variable to enable HoloMesh.',\n    };\n  }\n\n  const client = getOrCreateClient();\n\n  switch (name) {\n    case 'holomesh_moltbook_crosspost':\n      return handleMoltbookCrosspost(args);\n    case 'holomesh_publish_agent_template':\n      return handlePublishAgentTemplate(args);\n    case 'holomesh_publish_insight':\n      return handlePublishInsight(client, args);\n    case 'holomesh_discover':\n      return handleDiscover(client, args);\n    case 'holomesh_contribute':\n      return handleContribute(client, args);\n    case 'holomesh_query':\n      return handleQuery(client, args);\n    case 'holomesh_gossip':\n      return handleGossip(client, args);\n    case 'holomesh_subscribe':\n      return handleSubscribe(client, args);\n    case 'holomesh_status':\n      return handleStatus(client);\n    case 'holomesh_collect':\n      return handleCollect(client, args);\n    case 'holomesh_query_spatial':\n      return handleQuerySpatial(client, args);\n    case 'holomesh_feed_source':\n      return handleFeedSource(client);\n    case 'holomesh_wallet_status':\n      return handleWalletStatus();\n    case 'holomesh_gossip_sync':\n      return handleGossipSync(client, args);\n    case 'holomesh_crosspost_moltbook':\n      return handleCrosspostMoltbook(client, args);\n    default:\n      return null;\n  }\n}\n\n// â”€â”€ Individual Handlers â”€â”€\n\nfunction wantsToolDiscovery(args: Record<string, unknown>): boolean {\n  return args.include_tools === true || typeof args.capability_query === 'string';\n}\n\nfunction resolvePublisher(\n  client: HoloMeshOrchestratorClient | null,\n  args: Record<string, unknown>\n): { agentId: string; name: string } {\n  return {\n    agentId:\n      (args.publisher_agent_id as string | undefined) ||\n      client?.getAgentId() ||\n      process.env.HOLOMESH_AGENT_ID ||\n      'did:agent:local',\n    name:\n      (args.publisher_agent_name as string | undefined) ||\n      process.env.HOLOMESH_AGENT_NAME ||\n      DEFAULT_MESH_CONFIG.agentName,\n  };\n}\n\nfunction manifestKnowledgeEntry(\n  manifest: MeshToolManifest,\n  client: HoloMeshOrchestratorClient | null\n): MeshKnowledgeEntry {\n  return {\n    id: `P.mesh-tool.${manifest.id}`,\n    workspaceId: process.env.HOLOMESH_WORKSPACE || DEFAULT_MESH_CONFIG.workspace,\n    type: 'pattern',\n    content: meshToolManifestToKnowledgeContent(manifest),\n    provenanceHash: manifest.attestation.manifestHash,\n    authorId: client?.getAgentId() || manifest.attestation.publisherAgentId,\n    authorName: manifest.attestation.publisherName,\n    price: 0,\n    queryCount: 0,\n    reuseCount: 0,\n    domain: 'tools',\n    tags: ['mesh-tool', manifest.endpoint.toolName, ...manifest.capabilityTags],\n    confidence: 0.95,\n    createdAt: manifest.attestation.publishedAt,\n  };\n}\n\nasync function handlePublishTool(\n  client: HoloMeshOrchestratorClient | null,\n  args: Record<string, unknown>\n) {\n  try {\n    if (client && !client.getAgentId()) {\n      await client.registerAgent(['@knowledge-exchange', '@tool-publisher']);\n    }\n\n    const manifest = publishMeshToolManifest(\n      buildMeshToolManifest(args, resolvePublisher(client, args))\n    );\n    let synced = 0;\n    let remoteError: string | undefined;\n\n    if (client) {\n      try {\n        synced = await client.contributeKnowledge([manifestKnowledgeEntry(manifest, client)]);\n      } catch (err: unknown) {\n        remoteError = err instanceof Error ? err.message : String(err);\n      }\n    }\n\n    return {\n      success: true,\n      meshToolId: manifest.id,\n      manifestHash: manifest.attestation.manifestHash,\n      synced,\n      manifest,\n      ...(remoteError ? { remoteError } : {}),\n    };\n  } catch (err: unknown) {\n    return { error: `Tool publish failed: ${err instanceof Error ? err.message : String(err)}` };\n  }\n}\n\nasync function remoteToolManifests(\n  client: HoloMeshOrchestratorClient | null,\n  query: unknown,\n  limit: number\n): Promise<MeshToolManifest[]> {\n  if (!client) return [];\n  try {\n    const search = typeof query === 'string' && query.trim() ? query : 'mesh tool manifest';\n    const entries = await client.queryKnowledge(search, {\n      limit: Math.max(limit, 10),\n      type: 'pattern',\n    });\n    return entries\n      .map((entry) => meshToolManifestFromKnowledgeContent(entry.content))\n      .filter((manifest): manifest is MeshToolManifest => manifest !== null);\n  } catch {\n    return [];\n  }\n}\n\nasync function discoverPublishedTools(\n  client: HoloMeshOrchestratorClient | null,\n  args: Record<string, unknown>\n): Promise<MeshToolManifest[]> {\n  const query = args.capability_query || args.tool_name || args.mesh_tool_id;\n  const limit = (args.tool_limit as number | undefined) || (args.limit as number | undefined) || 10;\n  const merged = new Map<string, MeshToolManifest>();\n\n  for (const manifest of discoverMeshTools(query, limit)) {\n    merged.set(manifest.id, manifest);\n  }\n  for (const manifest of await remoteToolManifests(client, query, limit)) {\n    if (scoreMeshToolManifest(query, manifest) > 0) merged.set(manifest.id, manifest);\n  }\n\n  return Array.from(merged.values())\n    .sort((a, b) => scoreMeshToolManifest(query, b) - scoreMeshToolManifest(query, a))\n    .slice(0, limit);\n}\n\nasync function handleLocalToolDiscovery(args: Record<string, unknown>) {\n  const tools = await discoverPublishedTools(null, args);\n  return {\n    success: true,\n    peers: [],\n    count: 0,\n    total: 0,\n    tools,\n    toolCount: tools.length,\n    localOnly: true,\n  };\n}\n\nasync function handleInvokeTool(\n  client: HoloMeshOrchestratorClient | null,\n  args: Record<string, unknown>\n) {\n  try {\n    const query = args.mesh_tool_id || args.tool_name || args.capability_query;\n    if (!query) {\n      return { error: 'capability_query, mesh_tool_id, or tool_name is required' };\n    }\n\n    const candidates = await discoverPublishedTools(client, {\n      ...args,\n      capability_query: query,\n      tool_limit: args.limit || 10,\n    });\n    const selected = candidates.find((tool) => {\n      if (typeof args.mesh_tool_id === 'string') return tool.id === args.mesh_tool_id;\n      if (typeof args.tool_name === 'string') return tool.endpoint.toolName === args.tool_name;\n      return true;\n    });\n\n    if (!selected) {\n      return {\n        success: false,\n        error: 'No mesh-published tool matched the query',\n        query,\n      };\n    }\n\n    const toolArgs =\n      args.args && typeof args.args === 'object' && !Array.isArray(args.args)\n        ? (args.args as Record<string, unknown>)\n        : {};\n    const priorChain = Array.isArray(args.provenance_chain)\n      ? (args.provenance_chain as MeshToolInvocationHop[])\n      : [];\n    const verification = verifyMeshToolInvocationChain(priorChain);\n    if (!verification.verified) {\n      return {\n        success: false,\n        error: `Invalid provenance chain: ${verification.errors.join('; ')}`,\n      };\n    }\n\n    const result = await invokePublishedMeshTool(selected, toolArgs, {\n      dryRun: args.dry_run === true,\n      allowHighRisk: args.allow_high_risk === true,\n    });\n    const hop = createMeshToolInvocationHop(selected, toolArgs, {\n      callerAgentId:\n        typeof args.caller_agent_id === 'string'\n          ? args.caller_agent_id\n          : process.env.HOLOMESH_AGENT_ID || 'did:agent:local',\n      invocationId: typeof args.invocation_id === 'string' ? args.invocation_id : undefined,\n      invokedAt:\n        typeof args.invoked_at === 'string'\n          ? args.invoked_at\n          : typeof args.timestamp === 'string'\n            ? args.timestamp\n            : undefined,\n      previousHash: verification.lastHash,\n    });\n    const provenanceChain = [...priorChain, hop];\n\n    return {\n      success:\n        typeof result === 'object' && result !== null && 'success' in result\n          ? (result as { success?: boolean }).success\n          : true,\n      selectedTool: selected,\n      candidates: candidates.map((tool) => ({\n        id: tool.id,\n        name: tool.name,\n        score: scoreMeshToolManifest(query, tool),\n      })),\n      invocation: result,\n      attestation: {\n        verified: true,\n        chainLength: provenanceChain.length,\n        argsHash: hop.argsHash,\n        provenanceChain,\n      },\n      provenance_chain: provenanceChain,\n    };\n  } catch (err: unknown) {\n    return { error: `Tool invocation failed: ${err instanceof Error ? err.message : String(err)}` };\n  }\n}\n\nasync function handleMoltbookCrosspost(args: Record<string, unknown>) {\n  const parsed = moltbookCrosspostSchema.safeParse(args);\n  if (!parsed.success) {\n    return {\n      error: 'Invalid input for holomesh_moltbook_crosspost',\n      details: parsed.error.flatten(),\n    };\n  }\n\n  const payload = parsed.data;\n  const orchestratorUrl = process.env.MCP_ORCHESTRATOR_URL || 'http://localhost:4555';\n  const proxyUrl =\n    process.env.HOLOMESH_MOLTBOOK_CROSSPOST_URL || `${orchestratorUrl}/api/moltbook/crosspost`;\n\n  const authHeaders: Record<string, string> = { 'Content-Type': 'application/json; charset=utf-8' };\n  // Phase-2 wrapped read: gated by `env:HOLOSCRIPT_API_KEY` lease when\n  // HOLOMESH_VAULT_LEASE_ENFORCE is on; transparent passthrough otherwise.\n  const moltbookCrosspostKey = readHoloscriptApiKey();\n  if (moltbookCrosspostKey) {\n    authHeaders['x-mcp-api-key'] = moltbookCrosspostKey;\n  }\n\n  const environmentContext =\n    payload.includeContext !== false ? harvestMoltbookBroadcastContext() : undefined;\n\n  const postBody = {\n    taskId: payload.taskId,\n    title: payload.title,\n    description: payload.description,\n    status: 'completed',\n    ownerAgent: process.env.HOLOMESH_AGENT_NAME || 'holomesh-agent',\n    metrics: payload.metrics,\n    tags: payload.tags,\n    ...(environmentContext && Object.keys(environmentContext).length > 0\n      ? { environmentContext }\n      : {}),\n  };\n\n  try {\n    const proxyResp = await axios.post(proxyUrl, postBody, {\n      headers: authHeaders,\n      timeout: 12000,\n    });\n\n    return {\n      success: true,\n      route: 'orchestrator-proxy',\n      proxyUrl,\n      response: proxyResp.data,\n      environmentContext,\n    };\n  } catch (proxyErr: unknown) {\n    // Phase-3 wrapped read: gated by `env:MOLTBOOK_API_KEY` lease when\n    // HOLOMESH_VAULT_LEASE_ENFORCE is on; transparent passthrough otherwise.\n    const moltbookApiKey = readMoltbookApiKey();\n    if (!moltbookApiKey) {\n      return {\n        error: 'Proxy crosspost failed and MOLTBOOK_API_KEY is not configured for direct fallback',\n        proxyUrl,\n        details: proxyErr instanceof Error ? proxyErr.message : String(proxyErr),\n      };\n    }\n\n    try {\n      const postBody: Record<string, unknown> = {\n        taskId: payload.taskId,\n        title: payload.title,\n        description: payload.description,\n        status: 'completed',\n        ownerAgent: process.env.HOLOMESH_AGENT_NAME || 'holomesh-agent',\n        metrics: payload.metrics,\n        tags: payload.tags,\n      };\n      const built = buildMoltbookCrosspostPayload(postBody);\n      if (environmentContext && Object.keys(environmentContext).length > 0) {\n        built.content += `\\n\\n${formatBroadcastContextMarkdown(environmentContext)}`;\n      }\n      const direct = await createMoltbookPost({\n        apiKey: moltbookApiKey,\n        title: built.title,\n        content: built.content,\n        submolt: built.submolt,\n      });\n      if (!direct.success) {\n        return {\n          error: 'Moltbook direct post failed',\n          details: direct.details,\n          environmentContext,\n        };\n      }\n      return {\n        success: true,\n        route: 'direct-moltbook',\n        response: direct.data,\n        environmentContext,\n      };\n    } catch (directErr: unknown) {\n      return {\n        error: 'Moltbook crosspost failed for proxy and direct routes',\n        proxyUrl,\n        proxyError: proxyErr instanceof Error ? proxyErr.message : String(proxyErr),\n        directError: directErr instanceof Error ? directErr.message : String(directErr),\n      };\n    }\n  }\n}\n\nasync function handlePublishAgentTemplate(args: Record<string, unknown>) {\n  const parsed = publishAgentTemplateSchema.safeParse(args);\n  if (!parsed.success) {\n    return {\n      error: 'Invalid input for holomesh_publish_agent_template',\n      details: parsed.error.flatten(),\n    };\n  }\n\n  const payload: PublishAgentTemplateArgs = parsed.data;\n  const orchestratorUrl = process.env.MCP_ORCHESTRATOR_URL || 'http://localhost:4555';\n  const publishUrl =\n    process.env.HOLOMESH_MARKETPLACE_PUBLISH_URL || `${orchestratorUrl}/api/marketplace/publish`;\n  const author = process.env.HOLOMESH_AGENT_NAME || 'holomesh-swarm';\n\n  const headers: Record<string, string> = { 'Content-Type': 'application/json; charset=utf-8' };\n  // Phase-2 wrapped read: marketplace publish header is a hot per-request\n  // path. Gated by `env:HOLOSCRIPT_API_KEY` lease when enforcement is on.\n  const marketplacePublishKey = readHoloscriptApiKey();\n  if (marketplacePublishKey) {\n    headers['x-mcp-api-key'] = marketplacePublishKey;\n  }\n\n  try {\n    const response = await axios.post(\n      publishUrl,\n      {\n        name: payload.name,\n        description: payload.description,\n        category: payload.category,\n        program: payload.program,\n        tags: payload.tags,\n        author,\n        version: '1.0.0',\n        programType: 'intent',\n      },\n      {\n        headers,\n        timeout: 12000,\n      }\n    );\n\n    return {\n      success: true,\n      publishUrl,\n      template: response.data,\n    };\n  } catch (err: unknown) {\n    return {\n      error: 'Failed to publish marketplace template',\n      publishUrl,\n      details: err instanceof Error ? err.message : String(err),\n    };\n  }\n}\n\nasync function handlePublishInsight(\n  client: HoloMeshOrchestratorClient,\n  args: Record<string, unknown>\n) {\n  try {\n    const agentId = client.getAgentId() || 'did:agent:local';\n    const worldStatePath = process.env.HOLOMESH_WORLD_STATE_PATH || './.holomesh/worldstate.crdt';\n    const worldState = new HoloMeshWorldState(agentId, { snapshotPath: worldStatePath });\n\n    const content = args.content as string;\n    const traits = (args.traits as string[]) || ['@thought'];\n    const customCode = args.custom_hs_code as string | undefined;\n\n    worldState.publishInsight(content, traits, customCode);\n    worldState.saveSnapshot();\n\n    return {\n      success: true,\n      message: 'Insight published to local mesh lattice as a spatial AST object. Ready for gossip.',\n      agentId,\n    };\n  } catch (err: unknown) {\n    return { error: `Publish failed: ${err instanceof Error ? err.message : String(err)}` };\n  }\n}\n\nasync function handleDiscover(client: HoloMeshOrchestratorClient, args: Record<string, unknown>) {\n  try {\n    // Auto-register if not on mesh yet\n    if (!client.getAgentId()) {\n      await client.registerAgent(['@knowledge-exchange']);\n    }\n\n    const traits = args.traits as string[] | undefined;\n    const peers = await client.discoverPeers({ traits });\n    const limit = (args.limit as number) || 20;\n\n    const meshTools = wantsToolDiscovery(args) ? await discoverPublishedTools(client, args) : [];\n\n    return {\n      success: true,\n      peers: peers.slice(0, limit),\n      count: Math.min(peers.length, limit),\n      total: peers.length,\n      ...(meshTools.length > 0 || wantsToolDiscovery(args)\n        ? { tools: meshTools, toolCount: meshTools.length }\n        : {}),\n    };\n  } catch (err: unknown) {\n    return { error: `Discovery failed: ${err instanceof Error ? err.message : String(err)}` };\n  }\n}\n\nasync function handleContribute(client: HoloMeshOrchestratorClient, args: Record<string, unknown>) {\n  try {\n    if (!client.getAgentId()) {\n      await client.registerAgent(['@knowledge-exchange']);\n    }\n\n    const content = args.content as string;\n    const entryType = (args.type as string) || 'wisdom';\n    const entryId =\n      (args.id as string) || `${entryType.charAt(0).toUpperCase()}.auto.${Date.now()}`;\n    const provenanceHash = crypto.createHash('sha256').update(content).digest('hex');\n\n    const entry: MeshKnowledgeEntry = {\n      id: entryId,\n      workspaceId: process.env.HOLOMESH_WORKSPACE || 'default',\n      type: entryType as MeshKnowledgeEntry['type'],\n      content,\n      provenanceHash,\n      authorId: client.getAgentId()!,\n      authorName: process.env.HOLOMESH_AGENT_NAME || 'holomesh-agent',\n      price: (args.price as number) || 0,\n      queryCount: 0,\n      reuseCount: 0,\n      domain: args.domain as string,\n      tags: args.tags as string[],\n      confidence: (args.confidence as number) || 0.9,\n      createdAt: new Date().toISOString(),\n    };\n\n    const synced = await client.contributeKnowledge([entry]);\n\n    return {\n      success: true,\n      entryId,\n      provenanceHash,\n      synced,\n      type: entryType,\n    };\n  } catch (err: unknown) {\n    return { error: `Contribute failed: ${err instanceof Error ? err.message : String(err)}` };\n  }\n}\n\nasync function handleQuery(client: HoloMeshOrchestratorClient, args: Record<string, unknown>) {\n  try {\n    const search = args.search as string;\n    const results = await client.queryKnowledge(search, {\n      type: args.type as string,\n      limit: (args.limit as number) || 10,\n      workspaceId: args.workspace as string,\n    });\n\n    return {\n      success: true,\n      results,\n      count: results.length,\n      query: search,\n    };\n  } catch (err: unknown) {\n    return { error: `Query failed: ${err instanceof Error ? err.message : String(err)}` };\n  }\n}\n\nasync function handleGossip(client: HoloMeshOrchestratorClient, args: Record<string, unknown>) {\n  try {\n    if (!client.getAgentId()) {\n      await client.registerAgent(['@knowledge-exchange']);\n    }\n\n    const to = args.to as string | undefined;\n    const payload = {\n      type: args.type as string,\n      payload: args.payload,\n      timestamp: new Date().toISOString(),\n    };\n\n    let sent: boolean;\n    if (to) {\n      sent = await client.sendMessage(to, payload);\n    } else {\n      sent = await client.broadcast(payload);\n    }\n\n    return {\n      success: sent,\n      target: to || 'broadcast',\n      messageType: args.type,\n    };\n  } catch (err: unknown) {\n    return { error: `Gossip failed: ${err instanceof Error ? err.message : String(err)}` };\n  }\n}\n\nasync function handleSubscribe(client: HoloMeshOrchestratorClient, args: Record<string, unknown>) {\n  try {\n    if (!client.getAgentId()) {\n      await client.registerAgent(['@knowledge-exchange']);\n    }\n\n    const topic = args.topic as string;\n    const ok = await client.subscribe(topic);\n\n    return {\n      success: ok,\n      topic,\n      agentId: client.getAgentId(),\n    };\n  } catch (err: unknown) {\n    return { error: `Subscribe failed: ${err instanceof Error ? err.message : String(err)}` };\n  }\n}\n\nasync function handleStatus(client: HoloMeshOrchestratorClient) {\n  try {\n    const agentId = client.getAgentId();\n    if (!agentId) {\n      return {\n        success: true,\n        status: 'not_registered',\n        message: 'Call holomesh_discover or holomesh_contribute to auto-register.',\n      };\n    }\n\n    const agentName = process.env.HOLOMESH_AGENT_NAME || 'holomesh-agent';\n    const [peers, reputation, inbox] = await Promise.all([\n      client.discoverPeers(),\n      client.getAgentReputation(agentId, agentName),\n      client.readInbox(),\n    ]);\n\n    return {\n      success: true,\n      agentId,\n      agentName,\n      status: 'active',\n      peers: peers.length,\n      reputation,\n      unreadMessages: inbox.length,\n    };\n  } catch (err: unknown) {\n    return { error: `Status failed: ${err instanceof Error ? err.message : String(err)}` };\n  }\n}\n\nasync function handleCollect(client: HoloMeshOrchestratorClient, args: Record<string, unknown>) {\n  try {\n    const contentHash = args.contentHash as string;\n    const referrer = args.referrer as string | undefined;\n\n    // Query the entry by its provenance hash\n    const results = await client.queryKnowledge(contentHash, { limit: 1 });\n    if (results.length === 0) {\n      return { error: `No entry found with provenance hash: ${contentHash}` };\n    }\n\n    const entry = results[0];\n    if (entry.price <= 0) {\n      return {\n        success: true,\n        message: 'Entry is free â€” no payment needed.',\n        entry,\n      };\n    }\n\n    return {\n      success: true,\n      message: `Collection recorded. Payment of $${entry.price} queued for settlement via x402 Publishing Protocol.`,\n      entry,\n      price: entry.price,\n      referrer,\n      walletRequired: true,\n    };\n  } catch (err: unknown) {\n    return { error: `Collect failed: ${err instanceof Error ? err.message : String(err)}` };\n  }\n}\n\nasync function handleQuerySpatial(\n  client: HoloMeshOrchestratorClient,\n  args: Record<string, unknown>\n) {\n  try {\n    const agentId = client.getAgentId() || 'did:agent:local';\n    const worldStatePath = process.env.HOLOMESH_WORLD_STATE_PATH || './.holomesh/worldstate.crdt';\n    const worldState = new HoloMeshWorldState(agentId, { snapshotPath: worldStatePath });\n\n    const lat = typeof args.lat === 'number' ? args.lat : undefined;\n    const lng = typeof args.lng === 'number' ? args.lng : undefined;\n    const radius = typeof args.radius === 'number' ? args.radius : undefined;\n\n    const center = lat !== undefined && lng !== undefined ? { lat, lng } : undefined;\n    const entries = worldState.querySpatialEntries({ center, radius });\n\n    return {\n      success: true,\n      message: center\n        ? `Spatial query: ${entries.length} entities within radius ${radius ?? 100} of (${lng}, ${lat})`\n        : `Spatial query: ${entries.length} entities with parsed positions`,\n      entities: entries,\n    };\n  } catch (err: unknown) {\n    return { error: `Query spatial failed: ${err instanceof Error ? err.message : String(err)}` };\n  }\n}\n\nasync function handleFeedSource(client: HoloMeshOrchestratorClient) {\n  try {\n    const agentId = client.getAgentId() || 'did:agent:local';\n    const worldStatePath = process.env.HOLOMESH_WORLD_STATE_PATH || './.holomesh/worldstate.crdt';\n    const worldState = new HoloMeshWorldState(agentId, { snapshotPath: worldStatePath });\n\n    return {\n      success: true,\n      source: worldState.getFeedSource(),\n    };\n  } catch (err: unknown) {\n    return { error: `Feed source failed: ${err instanceof Error ? err.message : String(err)}` };\n  }\n}\n\nasync function handleWalletStatus() {\n  const walletEnabled = process.env.HOLOMESH_WALLET_ENABLED === 'true';\n  if (!walletEnabled) {\n    return {\n      success: true,\n      walletEnabled: false,\n      message:\n        'Wallet not enabled. Set HOLOMESH_WALLET_ENABLED=true and HOLOSCRIPT_WALLET_KEY to activate.',\n    };\n  }\n\n  return {\n    success: true,\n    walletEnabled: true,\n    walletKeyConfigured: !!process.env.HOLOSCRIPT_WALLET_KEY,\n    testnet: process.env.HOLOMESH_WALLET_TESTNET === 'true',\n    message:\n      'Wallet enabled. Use daemon actions (mesh_wallet_balance, mesh_collect_premium, mesh_settle_micro) for operations.',\n  };\n}\n\n// â”€â”€ V2 Inbound Gossip Handler â”€â”€\n\n/**\n * Handle an inbound CRDT gossip request from a peer.\n * Called by HTTP endpoint handler (not MCP tool dispatch).\n *\n * 1. V4: Verify sender's wallet signature (reject invalid, allow unsigned for V2 compat)\n * 2. Import sender's delta into our worldState\n * 3. Register sender as a peer in discovery\n * 4. Absorb gossiped peers\n * 5. Export our delta back to sender\n */\nexport async function handleInboundGossip(\n  request: GossipDeltaRequest,\n  worldState: HoloMeshWorldState,\n  discovery: HoloMeshDiscovery\n): Promise<GossipDeltaResponse> {\n  try {\n    // V4: Verify gossip signature when present\n    const signatureVerified = await discovery.verifyGossipSender(request);\n    if (signatureVerified === 'invalid') {\n      console.warn(\n        `[HoloMesh] Rejected gossip from ${request.senderDid}: invalid wallet signature`\n      );\n      return { success: false };\n    }\n\n    // Import sender's delta â€” route new knowledge entries through hot buffer\n    // so V9 consolidation (corroboration, TTL, clustering) applies to gossip\n    const incomingDelta = Buffer.from(request.deltaBase64, 'base64');\n    worldState.importDeltaToHotBuffer(new Uint8Array(incomingDelta), request.senderDid);\n\n    // Register sender as a peer (include wallet address when verified)\n    discovery.absorbGossipedPeers(\n      [\n        {\n          did: request.senderDid,\n          url: request.senderUrl,\n          name: request.senderName,\n          walletAddress: signatureVerified === 'verified' ? request.senderWalletAddress : undefined,\n        },\n      ],\n      request.senderDid\n    );\n\n    // Absorb gossiped peers from request\n    if (request.knownPeers && request.knownPeers.length > 0) {\n      discovery.absorbGossipedPeers(request.knownPeers, request.senderDid);\n    }\n\n    // V6: Absorb sender's health metadata\n    if (request.senderHealth) {\n      discovery.absorbPeerHealth(request.senderDid, request.senderHealth);\n    }\n\n    // Export our delta back (using sender's frontiers for efficient diff)\n    const ourDelta = worldState.exportDelta(request.frontiers);\n    const ourFrontiers = worldState.getFrontiers();\n\n    // Share our known peers back\n    const peersToShare = discovery.getPeersToShare(request.senderDid);\n\n    return {\n      success: true,\n      deltaBase64: Buffer.from(ourDelta).toString('base64'),\n      frontiers: ourFrontiers,\n      knownPeers: peersToShare,\n      signatureVerified,\n      responderHealth: discovery.buildHealthMetadata(),\n    };\n  } catch (_err: unknown) {\n    return { success: false };\n  }\n}\n\nasync function handleGossipSync(client: HoloMeshOrchestratorClient, args: Record<string, unknown>) {\n  try {\n    const agentId =\n      client.getAgentId() ||\n      (await client.registerAgent(['@knowledge-exchange', '@crdt-gossip', '@p2p']));\n    const localMcpUrl =\n      normalizePeerEndpointUrl(process.env.MCP_LOCAL_URL) ||\n      normalizePeerEndpointUrl(\n        process.env.RAILWAY_PUBLIC_DOMAIN ? `https://${process.env.RAILWAY_PUBLIC_DOMAIN}` : null\n      ) ||\n      normalizePeerEndpointUrl(process.env.HOLOSCRIPT_SERVER_URL) ||\n      normalizePeerEndpointUrl(process.env.HOLOSCRIPT_MCP_URL) ||\n      `http://localhost:${process.env.PORT || '3000'}`;\n    const worldStatePath = process.env.HOLOMESH_WORLD_STATE_PATH || './.holomesh/worldstate.crdt';\n    const peerStorePath = process.env.HOLOMESH_PEER_STORE_PATH || './.holomesh/peers.json';\n\n    const worldState = new HoloMeshWorldState(agentId, { snapshotPath: worldStatePath });\n    const discovery = new HoloMeshDiscovery(agentId, localMcpUrl, worldState, {\n      storePath: peerStorePath,\n    });\n\n    const targetCount = (args.targetCount as number) || 2;\n    let targets = discovery.selectGossipTargets(targetCount);\n\n    // Auto-bootstrap from orchestrator if network knowledge is cold\n    if (targets.length === 0) {\n      await discovery.bootstrapFromOrchestrator(client);\n      targets = discovery.selectGossipTargets(targetCount);\n    }\n\n    if (targets.length === 0) {\n      return {\n        success: false,\n        message: 'No healthy gossip peers available after orchestrator bootstrap attempt.',\n      };\n    }\n\n    let synced = 0;\n    for (const peer of targets) {\n      const ok = await discovery.gossipSync(peer);\n      if (ok) synced++;\n    }\n\n    worldState.saveSnapshot();\n\n    return {\n      success: true,\n      synced,\n      attempted: targets.length,\n      message: `Successfully gossiped bounded CRDT vector states with ${synced}/${targets.length} peers`,\n    };\n  } catch (err: unknown) {\n    return { error: `Gossip sync failed: ${err instanceof Error ? err.message : String(err)}` };\n  }\n}\n\nasync function handleCrosspostMoltbook(\n  client: HoloMeshOrchestratorClient,\n  args: Record<string, unknown>\n) {\n  try {\n    const entryId = args.entry_id as string;\n    if (!entryId) {\n      return { error: 'Missing required field: entry_id' };\n    }\n\n    // Phase-3 wrapped read: gated by `env:MOLTBOOK_API_KEY` lease when\n    // HOLOMESH_VAULT_LEASE_ENFORCE is on; transparent passthrough otherwise.\n    const moltbookKey = readMoltbookApiKey();\n    if (!moltbookKey) {\n      return { error: 'MOLTBOOK_API_KEY not configured in environment' };\n    }\n\n    // Look up the entry\n    const results = await client.queryKnowledge(entryId, { limit: 50 });\n    const entry = results.find((e: MeshKnowledgeEntry) => e.id === entryId);\n    if (!entry) {\n      return { error: `Entry not found: ${entryId}` };\n    }\n\n    // Build Moltbook post\n    const typeLabel =\n      entry.type === 'wisdom' ? 'Wisdom' : entry.type === 'pattern' ? 'Pattern' : 'Gotcha';\n    const submolt = (args.submolt as string) || 'general';\n    const title =\n      (args.title as string) ||\n      `[${typeLabel}] ${entry.content.slice(0, 80)}${entry.content.length > 80 ? '...' : ''}`;\n    const moltbookContent = `${entry.content}\\n\\n---\\n*Cross-posted from [HoloMesh](https://mcp.holoscript.net/api/holomesh/entry/${entryId}) â€” domain: ${entry.domain || 'general'}, confidence: ${entry.confidence || 0.9}*`;\n\n    const created = await createMoltbookPost({\n      apiKey: moltbookKey,\n      title,\n      content: moltbookContent,\n      submolt,\n    });\n    if (!created.success) {\n      return { error: 'Moltbook post failed', details: created.details };\n    }\n    const moltbookData = created.data;\n\n    return {\n      success: true,\n      message: 'Entry cross-posted to Moltbook',\n      holomesh_entry_id: entryId,\n      moltbook_post: moltbookData.post,\n    };\n  } catch (err: unknown) {\n    return {\n      error: `Crosspost failed: ${err instanceof Error ? err.message : String(err)}`,\n    };\n  }\n}\n","import type { ISignalingBridge, NeuralSignalPayload } from '@holoscript/core';\nimport { sendMessage, getInbox, markRead } from './messaging.js';\n\nconst SIGNAL_PREFIX = '__NEURAL_SIGNAL__:';\n\n/**\n * HoloMeshSignaler\n *\n * Implements the ISignalingBridge interface using HoloMesh's A2A messaging layer.\n * Enables establishing WebRTC RTCPeerConnections over the mesh without a dedicated\n * WebSocket signaling server, bridging Pillar 2 (Neural Streaming) with the HoloMesh Gossip layer.\n */\nexport class HoloMeshSignaler implements ISignalingBridge {\n  private pollingInterval: ReturnType<typeof setInterval> | null = null;\n  private signalHandler: ((payload: NeuralSignalPayload) => void) | null = null;\n\n  constructor(\n    public readonly localAgentId: string,\n    public readonly localAgentName: string,\n    public readonly targetPeerId: string,\n    private pollRateMs: number = 500\n  ) {}\n\n  /**\n   * Registers a callback to receive incoming SDP offers, answers, and ICE candidates.\n   * Starts the inbox polling loop to check for __NEURAL_SIGNAL__ messages.\n   */\n  public onReceiveSignal(handler: (payload: NeuralSignalPayload) => void): void {\n    this.signalHandler = handler;\n    this.startPolling();\n  }\n\n  /**\n   * Dispatches a signaling payload over the HoloMesh A2A messaging pipeline.\n   */\n  public async sendSignal(payload: NeuralSignalPayload): Promise<void> {\n    try {\n      const content = `${SIGNAL_PREFIX}${JSON.stringify(payload)}`;\n      sendMessage(this.localAgentId, this.localAgentName, this.targetPeerId, content);\n      // console.log(`[HoloMeshSignaler] Sent out-of-band signal`, { to: this.targetPeerId, type: payload.type });\n    } catch (err) {\n      console.error(`[HoloMeshSignaler] Failed to send signal to ${this.targetPeerId}`, err);\n      throw err;\n    }\n  }\n\n  /**\n   * Polls the inbox for unread messages matching the target peer ID and the signal prefix.\n   */\n  private startPolling(): void {\n    if (this.pollingInterval) return;\n\n    this.pollingInterval = setInterval(() => {\n      if (!this.signalHandler) return;\n\n      const unreadMessages = getInbox(this.localAgentId, true);\n\n      for (const msg of unreadMessages) {\n        if (msg.fromAgent === this.targetPeerId && msg.content.startsWith(SIGNAL_PREFIX)) {\n          // Parse the signal\n          try {\n            const rawJson = msg.content.substring(SIGNAL_PREFIX.length);\n            const payload = JSON.parse(rawJson) as NeuralSignalPayload;\n\n            // Mark read so we don't process it again\n            markRead(msg.id, this.localAgentId);\n\n            // Pass to the transport layer\n            this.signalHandler(payload);\n          } catch (e) {\n            console.warn(\n              `[HoloMeshSignaler] Failed to parse incoming signal from ${this.targetPeerId}`,\n              e\n            );\n          }\n        }\n      }\n    }, this.pollRateMs);\n  }\n\n  /**\n   * Stops polling the inbox.\n   */\n  public destroy(): void {\n    if (this.pollingInterval) {\n      clearInterval(this.pollingInterval);\n      this.pollingInterval = null;\n    }\n    this.signalHandler = null;\n  }\n}\n","/**\n * HoloMesh Consolidation Bridge — Wire ConsolidationEngine into live HoloMesh.\n *\n * Provides explicit trigger paths from HoloMesh knowledge/session reports\n * into the pure ConsolidationEngine ( Framework ).\n *\n * Triggers:\n *   - timer      : periodic sleep cycle (daemon)\n *   - entropy    : auto-fire when hot-buffer entropy or cross-entry conflict detected\n *   - manual     : HTTP route or admin action\n *\n * Outputs:\n *   - reviewed quarantine set (safe Dreaming pattern)\n *   - run logs with rollback / discard behavior\n *   - cold-store snapshots per cycle\n */\n\nimport {\n  ConsolidationEngine,\n  validateMemoryReceipt,\n  type ColdStoreEntry,\n  type QuarantinedMemoryEntry,\n  type ConsolidationResult,\n} from '@holoscript/framework';\nimport type { KnowledgeDomain, MemoryReceipt, MemorySourceHash } from '@holoscript/framework';\nimport { KNOWLEDGE_DOMAINS } from '@holoscript/framework';\nimport type { MeshKnowledgeEntry } from './types';\nimport * as crypto from 'crypto';\nimport * as fs from 'fs';\nimport * as os from 'os';\nimport * as path from 'path';\nimport { HOLOMESH_DATA_DIR, atomicWriteJSON, readJSON } from './state';\n\n// ── Persistence ──\n\nconst BRIDGE_DATA_DIR = path.join(HOLOMESH_DATA_DIR, 'consolidation');\nconst LOG_PATH = path.join(BRIDGE_DATA_DIR, 'run-logs.json');\nconst SNAPSHOT_PATH = path.join(BRIDGE_DATA_DIR, 'cold-store-snapshot.json');\n\n// GOLD-intake queue — relative to ~/.holoscript, NOT the HoloMesh data dir.\n// This file is the handoff boundary the ai-ecosystem GOLD pipeline consumes;\n// HoloScript never writes into D:/GOLD directly.\nconst GOLD_INTAKE_DIR =\n  process.env.HOLOSCRIPT_GOLD_INTAKE_DIR ||\n  path.join(\n    process.env.HOLOSCRIPT_CACHE_DIR || path.join(os.homedir(), '.holoscript'),\n    'gold-intake'\n  );\nconst GOLD_INTAKE_QUEUE = path.join(GOLD_INTAKE_DIR, 'queue.jsonl');\n\nfunction ensureDir(): void {\n  if (!fs.existsSync(BRIDGE_DATA_DIR)) {\n    fs.mkdirSync(BRIDGE_DATA_DIR, { recursive: true });\n  }\n}\n\nfunction ensureGoldIntakeDir(): void {\n  if (!fs.existsSync(GOLD_INTAKE_DIR)) {\n    fs.mkdirSync(GOLD_INTAKE_DIR, { recursive: true });\n  }\n}\n\n// ── GOLD-Intake Payload ──\n\n/**\n * One JSON line per promoted entry, appended to\n * ~/.holoscript/gold-intake/queue.jsonl. The ai-ecosystem GOLD pipeline\n * (D:/GOLD) consumes this file — this queue is the handoff boundary.\n */\nexport interface GoldIntakePayload {\n  id: string;\n  domain: string;\n  content: string;\n  provenance: {\n    receiptId?: string;\n    authorDid: string;\n    corroborators: string[];\n    confidence?: number;\n    extractorVersion?: string;\n  };\n  sha256: string;\n  promotedAt: number;\n}\n\n/** Build and append GOLD-intake payloads for a batch of promoted ColdStoreEntries. */\nfunction appendGoldIntakePayloads(entries: ColdStoreEntry[]): void {\n  try {\n    ensureGoldIntakeDir();\n    const lines: string[] = [];\n    for (const entry of entries) {\n      const payload: GoldIntakePayload = {\n        id: entry.id,\n        // ColdStoreEntry carries its type, not its KnowledgeDomain (the domain is\n        // the engine's Map key, not a field). Consumers normalise the type string.\n        domain: entry.type,\n        content: entry.content,\n        provenance: {\n          receiptId: entry.memoryReceipt?.id,\n          authorDid: entry.authorDid,\n          corroborators: entry.memoryReceipt?.corroborators ?? [],\n          confidence: entry.memoryReceipt?.confidence,\n          extractorVersion: entry.memoryReceipt?.extractorVersion,\n        },\n        sha256: crypto.createHash('sha256').update(entry.content).digest('hex'),\n        promotedAt: Date.now(),\n      };\n      lines.push(JSON.stringify(payload));\n    }\n    if (lines.length > 0) {\n      fs.appendFileSync(GOLD_INTAKE_QUEUE, lines.join('\\n') + '\\n', 'utf-8');\n    }\n  } catch (err: unknown) {\n    // Best-effort — never surface into the consolidation cycle.\n    console.warn('[ConsolidationBridge] gold-intake append error (non-fatal):', err);\n  }\n}\n\n// ── Run Log Types ──\n\nexport type ConsolidationTrigger = 'timer' | 'entropy' | 'manual' | 'conflict';\n\nexport interface ConsolidationRunLog {\n  id: string;\n  startedAt: number;\n  finishedAt: number;\n  trigger: ConsolidationTrigger;\n  results: ConsolidationResult[];\n  promotedEntryIds: string[];\n  quarantinedEntryIds: string[];\n  rejectedEntryIds: string[];\n  rolledBack: boolean;\n  rollbackAt?: number;\n  reason?: string;\n}\n\nexport interface RollbackOptions {\n  /** Max cycles to roll back (default 1) */\n  depth?: number;\n  /** Only rollback entries from a specific domain */\n  domain?: KnowledgeDomain;\n}\n\nexport interface ReviewSet {\n  quarantined: QuarantinedMemoryEntry[];\n  rejected: QuarantinedMemoryEntry[];\n  stats: {\n    quarantinedCount: number;\n    rejectedCount: number;\n    oldestQuarantineAgeMs: number;\n  };\n}\n\n// ── Helpers ──\n\nfunction hashContent(content: string): string {\n  return crypto.createHash('sha256').update(content).digest('hex');\n}\n\nfunction buildMemoryReceipt(entry: MeshKnowledgeEntry, sourcePeerDid: string): MemoryReceipt {\n  const now = Date.now();\n  const rawSourceIds = [entry.id];\n  if (entry.authorId) {\n    rawSourceIds.push(`author:${entry.authorId}`);\n  }\n  const sourceHashes: MemorySourceHash[] = [\n    {\n      sourceId: entry.id,\n      hash: entry.provenanceHash || hashContent(entry.content),\n      algorithm: 'sha256',\n    },\n  ];\n  if (entry.authorId) {\n    sourceHashes.push({\n      sourceId: `author:${entry.authorId}`,\n      hash: hashContent(entry.authorId + entry.content),\n      algorithm: 'custom',\n    });\n  }\n  return {\n    id: `receipt_${entry.id}_${now}`,\n    rawSourceIds,\n    sourceHashes,\n    extractorVersion: 'holomesh-consolidation-bridge@1.0.0',\n    modelIdentity: {\n      agentId: sourcePeerDid,\n      agentName: 'holomesh-bridge',\n    },\n    toolIdentity: {\n      toolName: 'knowledge-ingestion',\n      toolVersion: '1.0.0',\n      runtime: 'mcp-server',\n    },\n    timestamp: now,\n    corroborators: [sourcePeerDid],\n    confidence: entry.confidence ?? 0.9,\n    metadata: {\n      workspaceId: entry.workspaceId,\n      domain: entry.domain,\n      tags: entry.tags,\n      price: entry.price,\n    },\n  };\n}\n\nfunction buildSessionReportReceipt(\n  content: string,\n  sessionId: string,\n  agentId: string,\n  taskId?: string,\n  commitHash?: string\n): MemoryReceipt {\n  const now = Date.now();\n  return {\n    id: `receipt_session_${sessionId}_${now}`,\n    rawSourceIds: [sessionId, taskId].filter((s): s is string => Boolean(s)),\n    sourceHashes: [\n      {\n        sourceId: sessionId,\n        hash: hashContent(content),\n        algorithm: 'sha256',\n      },\n    ],\n    extractorVersion: 'holomesh-session-bridge@1.0.0',\n    modelIdentity: {\n      agentId,\n      agentName: 'holomesh-bridge',\n    },\n    toolIdentity: {\n      toolName: 'session-report-ingestion',\n      toolVersion: '1.0.0',\n      runtime: 'mcp-server',\n    },\n    timestamp: now,\n    corroborators: [agentId],\n    confidence: 0.85,\n    sessionId,\n    taskId,\n    commitHash,\n    metadata: {\n      source: 'session-report',\n    },\n  };\n}\n\nfunction resolveDomain(entry: MeshKnowledgeEntry): KnowledgeDomain {\n  const raw = (entry.domain || 'general').toLowerCase();\n  if (KNOWLEDGE_DOMAINS.includes(raw as KnowledgeDomain)) return raw as KnowledgeDomain;\n  // Map common aliases\n  if (raw.includes('security')) return 'security';\n  if (raw.includes('render')) return 'rendering';\n  if (raw.includes('agent')) return 'agents';\n  if (raw.includes('compil')) return 'compilation';\n  return 'general';\n}\n\n// ── Entropy Detection ──\n\ninterface EntropySnapshot {\n  timestamp: number;\n  hotBufferSizes: Record<string, number>;\n  coldStoreSizes: Record<string, number>;\n}\n\nfunction computeEntropyDelta(prev: EntropySnapshot, curr: EntropySnapshot): number {\n  let delta = 0;\n  for (const domain of KNOWLEDGE_DOMAINS) {\n    const hotDelta = Math.abs(\n      (curr.hotBufferSizes[domain] || 0) - (prev.hotBufferSizes[domain] || 0)\n    );\n    const coldDelta = Math.abs(\n      (curr.coldStoreSizes[domain] || 0) - (prev.coldStoreSizes[domain] || 0)\n    );\n    delta += hotDelta * 2 + coldDelta;\n  }\n  return delta;\n}\n\n// ── Bridge ──\n\nexport class HoloMeshConsolidationBridge {\n  private engine: ConsolidationEngine;\n  private runLogs: ConsolidationRunLog[] = [];\n  private lastEntropySnapshot: EntropySnapshot | null = null;\n  private timer: NodeJS.Timeout | null = null;\n\n  constructor() {\n    // Register the default graduation hook: every PROMOTE-phase cold-store entry\n    // is serialized to the GOLD-intake queue for the ai-ecosystem GOLD pipeline.\n    this.engine = new ConsolidationEngine({\n      graduationHook: (entries: ColdStoreEntry[]) => appendGoldIntakePayloads(entries),\n    });\n    this.loadSnapshot();\n    this.loadLogs();\n  }\n\n  private captureEntropySnapshot(): EntropySnapshot {\n    return {\n      timestamp: Date.now(),\n      hotBufferSizes: Object.fromEntries(\n        this.engine.getHotBufferStats().map((s) => [s.domain, s.count])\n      ),\n      coldStoreSizes: Object.fromEntries(\n        this.engine.getColdStoreStats().map((s) => [s.domain, s.count])\n      ),\n    };\n  }\n\n  // ── Ingestion ──\n\n  /**\n   * Ingest a HoloMesh knowledge entry into the hot buffer.\n   * Generates a MemoryReceipt from entry provenance fields.\n   */\n  ingestKnowledgeEntry(entry: MeshKnowledgeEntry, sourcePeerDid: string): string {\n    const domain = resolveDomain(entry);\n    const hasProvenance = Boolean(entry.provenanceHash && entry.provenanceHash.length >= 64);\n    if (!hasProvenance) {\n      // Ingest without receipt — will be quarantined on consolidation cycle\n      const hot = this.engine.ingest(\n        domain,\n        {\n          content: entry.content,\n          type: entry.type || 'wisdom',\n          authorDid: entry.authorId || sourcePeerDid,\n          tags: entry.tags || [],\n        },\n        sourcePeerDid\n      );\n      return hot.id;\n    }\n\n    const receipt = buildMemoryReceipt(entry, sourcePeerDid);\n    const receiptErrors = validateMemoryReceipt(receipt);\n    if (receiptErrors.length > 0) {\n      // Receipt invalid — still ingest but without receipt (will be quarantined on cycle)\n      const hot = this.engine.ingest(\n        domain,\n        {\n          content: entry.content,\n          type: entry.type || 'wisdom',\n          authorDid: entry.authorId || sourcePeerDid,\n          tags: entry.tags || [],\n        },\n        sourcePeerDid\n      );\n      return hot.id;\n    }\n\n    const hot = this.engine.ingest(\n      domain,\n      {\n        content: entry.content,\n        type: entry.type || 'wisdom',\n        authorDid: entry.authorId || sourcePeerDid,\n        tags: entry.tags || [],\n        memoryReceipt: receipt,\n      },\n      sourcePeerDid\n    );\n    return hot.id;\n  }\n\n  /**\n   * Ingest a session report as a knowledge entry.\n   */\n  ingestSessionReport(\n    content: string,\n    sessionId: string,\n    agentId: string,\n    opts?: { taskId?: string; commitHash?: string; tags?: string[] }\n  ): string {\n    const receipt = buildSessionReportReceipt(\n      content,\n      sessionId,\n      agentId,\n      opts?.taskId,\n      opts?.commitHash\n    );\n    const domain: KnowledgeDomain = 'agents';\n    const hot = this.engine.ingest(\n      domain,\n      {\n        content,\n        type: 'session-report',\n        authorDid: agentId,\n        tags: opts?.tags || ['session-report'],\n        memoryReceipt: receipt,\n      },\n      agentId\n    );\n    return hot.id;\n  }\n\n  /**\n   * Corroborate an existing hot buffer entry.\n   */\n  corroborate(domain: KnowledgeDomain, entryId: string, peerDid: string): boolean {\n    return this.engine.corroborate(domain, entryId, peerDid);\n  }\n\n  // ── Triggers ──\n\n  /** Run a manual consolidation cycle across all overdue domains. */\n  triggerManual(reason?: string): ConsolidationResult[] {\n    return this.runCycle('manual', reason);\n  }\n\n  /** Timer tick — run if any domain is overdue. */\n  triggerTimer(): ConsolidationResult[] {\n    const needs = this.engine.needsConsolidation().filter((n) => n.overdue);\n    if (needs.length === 0) return [];\n    return this.runCycle('timer');\n  }\n\n  /**\n   * Entropy trigger — auto-fire when hot-buffer churn or conflict exceeds threshold.\n   * Returns empty if no threshold breach.\n   */\n  triggerEntropy(threshold: number = 10): ConsolidationResult[] {\n    const current = this.captureEntropySnapshot();\n    if (!this.lastEntropySnapshot) {\n      this.lastEntropySnapshot = current;\n      return [];\n    }\n    const delta = computeEntropyDelta(this.lastEntropySnapshot, current);\n    this.lastEntropySnapshot = current;\n    if (delta >= threshold) {\n      return this.runCycle('entropy', `entropy-delta:${delta}`);\n    }\n    return [];\n  }\n\n  /**\n   * Conflict trigger — fire when the ConsolidationEngine detects contradictions\n   * or when an external caller observes cross-entry conflicts.\n   */\n  triggerConflict(conflictReason: string): ConsolidationResult[] {\n    return this.runCycle('conflict', conflictReason);\n  }\n\n  // ── Core Cycle ──\n\n  private runCycle(trigger: ConsolidationTrigger, reason?: string): ConsolidationResult[] {\n    ensureDir();\n    const startedAt = Date.now();\n\n    // Snapshot cold-store IDs before cycle for rollback bookkeeping\n    const preIds = this.snapshotColdStoreIds();\n\n    // Run consolidation across all overdue domains (or all if forced)\n    const force = trigger !== 'timer';\n    const results = this.engine.sleepCycle(force);\n\n    // Determine promoted / quarantined / rejected IDs by diffing cold store + quarantine\n    const postIds = this.snapshotColdStoreIds();\n    const promotedEntryIds = this.diffPromoted(preIds, postIds);\n    const allQuarantine = KNOWLEDGE_DOMAINS.flatMap((d) => this.engine.getQuarantine(d));\n    const quarantinedEntryIds = allQuarantine\n      .filter((q) => q.state === 'quarantined')\n      .map((q) => q.entry.id);\n    const rejectedEntryIds = allQuarantine\n      .filter((q) => q.state === 'rejected')\n      .map((q) => q.entry.id);\n\n    const log: ConsolidationRunLog = {\n      id: `run_${startedAt}_${trigger}`,\n      startedAt,\n      finishedAt: Date.now(),\n      trigger,\n      results,\n      promotedEntryIds,\n      quarantinedEntryIds,\n      rejectedEntryIds,\n      rolledBack: false,\n      reason,\n    };\n\n    this.runLogs.push(log);\n    this.trimLogs();\n    this.persistLogs();\n    this.persistSnapshot();\n\n    return results;\n  }\n\n  // ── Rollback / Discard ──\n\n  /**\n   * Roll back the last N consolidation cycles.\n   * Removes promoted entries that survive the rollback window.\n   * Returns count of entries discarded.\n   */\n  rollback(opts: RollbackOptions = {}): { discarded: number; domains: string[] } {\n    const depth = opts.depth ?? 1;\n    const targetLogs = this.runLogs.filter((l) => !l.rolledBack).slice(-depth);\n    if (targetLogs.length === 0) return { discarded: 0, domains: [] };\n\n    const affectedDomains = new Set<string>();\n    let discarded = 0;\n\n    for (const log of targetLogs) {\n      for (const entryId of log.promotedEntryIds) {\n        // Find which domain the entry lives in\n        for (const domain of KNOWLEDGE_DOMAINS) {\n          if (this.engine.getColdStoreEntry(domain, entryId)) {\n            const removed = this.engine.discardEntry(domain, entryId);\n            if (removed) {\n              discarded++;\n              affectedDomains.add(domain);\n            }\n            break;\n          }\n        }\n      }\n      log.rolledBack = true;\n      log.rollbackAt = Date.now();\n    }\n\n    this.persistLogs();\n    this.persistSnapshot();\n    return { discarded, domains: [...affectedDomains] };\n  }\n\n  /** Discard a single cold-store entry by ID (admin override). */\n  discard(domain: KnowledgeDomain, entryId: string): boolean {\n    const removed = this.engine.discardEntry(domain, entryId);\n    if (removed) this.persistSnapshot();\n    return removed;\n  }\n\n  // ── Review Sets ──\n\n  /** Get the full reviewable quarantine + rejected set (safe Dreaming pattern). */\n  getReviewSet(): ReviewSet {\n    const all = KNOWLEDGE_DOMAINS.flatMap((d) => this.engine.getQuarantine(d));\n    const quarantined = all.filter((q) => q.state === 'quarantined');\n    const rejected = all.filter((q) => q.state === 'rejected');\n    const now = Date.now();\n    const ages = quarantined.map((q) => now - q.quarantinedAt);\n    return {\n      quarantined,\n      rejected,\n      stats: {\n        quarantinedCount: quarantined.length,\n        rejectedCount: rejected.length,\n        oldestQuarantineAgeMs: ages.length > 0 ? Math.max(...ages) : 0,\n      },\n    };\n  }\n\n  /** Reject a quarantined entry after review. */\n  rejectQuarantined(domain: KnowledgeDomain, entryId: string, reason: string): boolean {\n    const ok = this.engine.rejectQuarantinedMemory(domain, entryId, reason);\n    if (ok) this.persistSnapshot();\n    return ok;\n  }\n\n  // ── Logs ──\n\n  getRunLogs(): ConsolidationRunLog[] {\n    return [...this.runLogs];\n  }\n\n  getLatestLog(): ConsolidationRunLog | undefined {\n    return this.runLogs[this.runLogs.length - 1];\n  }\n\n  // ── Stats ──\n\n  getStats(): {\n    hotBuffer: { domain: string; count: number }[];\n    coldStore: { domain: string; count: number }[];\n    logs: number;\n    lastRun?: number;\n  } {\n    return {\n      hotBuffer: this.engine.getHotBufferStats(),\n      coldStore: this.engine.getColdStoreStats(),\n      logs: this.runLogs.length,\n      lastRun:\n        this.runLogs.length > 0 ? this.runLogs[this.runLogs.length - 1].finishedAt : undefined,\n    };\n  }\n\n  // ── Daemon Timer ──\n\n  /** Start periodic timer trigger. Interval in ms (default 6h). */\n  startTimer(intervalMs: number = 6 * 60 * 60 * 1000): void {\n    this.stopTimer();\n    this.timer = setInterval(() => this.triggerTimer(), intervalMs);\n    this.timer.unref();\n  }\n\n  stopTimer(): void {\n    if (this.timer) {\n      clearInterval(this.timer);\n      this.timer = null;\n    }\n  }\n\n  // ── Persistence (private) ──\n\n  private snapshotColdStoreIds(): Map<KnowledgeDomain, Set<string>> {\n    const map = new Map<KnowledgeDomain, Set<string>>();\n    for (const domain of KNOWLEDGE_DOMAINS) {\n      const entries = this.engine.getColdStore(domain);\n      map.set(domain, new Set(entries.map((e) => e.id)));\n    }\n    return map;\n  }\n\n  private diffPromoted(\n    pre: Map<KnowledgeDomain, Set<string>>,\n    post: Map<KnowledgeDomain, Set<string>>\n  ): string[] {\n    const promoted: string[] = [];\n    for (const domain of KNOWLEDGE_DOMAINS) {\n      const preSet = pre.get(domain) || new Set();\n      const postSet = post.get(domain) || new Set();\n      for (const id of postSet) {\n        if (!preSet.has(id)) promoted.push(id);\n      }\n    }\n    return promoted;\n  }\n\n  private trimLogs(max: number = 1000): void {\n    if (this.runLogs.length > max) {\n      this.runLogs = this.runLogs.slice(-max);\n    }\n  }\n\n  private persistLogs(): void {\n    try {\n      atomicWriteJSON(LOG_PATH, this.runLogs);\n    } catch {\n      /* non-fatal */\n    }\n  }\n\n  private loadLogs(): void {\n    const data = readJSON(LOG_PATH);\n    if (Array.isArray(data)) {\n      this.runLogs = data;\n    }\n  }\n\n  private persistSnapshot(): void {\n    try {\n      const snapshot: Record<string, ColdStoreEntry[]> = {};\n      for (const domain of KNOWLEDGE_DOMAINS) {\n        snapshot[domain] = this.engine.getColdStore(domain);\n      }\n      atomicWriteJSON(SNAPSHOT_PATH, snapshot);\n    } catch {\n      /* non-fatal */\n    }\n  }\n\n  private loadSnapshot(): void {\n    const data = readJSON(SNAPSHOT_PATH);\n    if (!data || typeof data !== 'object') return;\n    for (const domain of KNOWLEDGE_DOMAINS) {\n      const entries = data[domain];\n      if (Array.isArray(entries)) {\n        this.engine.seedColdStore(domain, entries as ColdStoreEntry[]);\n      }\n    }\n  }\n}\n\n// ── Singleton ──\n\nlet bridgeInstance: HoloMeshConsolidationBridge | null = null;\n\nexport function getConsolidationBridge(): HoloMeshConsolidationBridge {\n  if (!bridgeInstance) {\n    bridgeInstance = new HoloMeshConsolidationBridge();\n  }\n  return bridgeInstance;\n}\n\nexport interface ResetConsolidationBridgeOptions {\n  clearPersistence?: boolean;\n}\n\nexport function resetConsolidationBridge(options: ResetConsolidationBridgeOptions = {}): void {\n  bridgeInstance?.stopTimer();\n  bridgeInstance = null;\n  if (options.clearPersistence) {\n    try {\n      fs.rmSync(BRIDGE_DATA_DIR, { recursive: true, force: true });\n    } catch {\n      /* non-fatal */\n    }\n  }\n}\n","export {\n  holomeshTools,\n  handleHoloMeshTool,\n  getHoloMeshClient,\n  hasHoloMeshKey,\n  handleInboundGossip,\n} from './holomesh-tools';\nexport { sendMessage, getInbox, getThread, markRead, getUnreadCount } from './messaging';\nexport { boardTools, handleBoardTool } from './board-tools';\nexport {\n  teamAgentTools,\n  handleTeamAgentTool,\n  _resetAutonomousControlState,\n} from './team-agent-tools';\nexport {\n  teamFormationTools,\n  handleTeamFormationTool,\n  setTeamFormationRosterSource,\n} from './team-formation-tools';\nexport {\n  agentCapabilityTools,\n  handleAgentCapabilityTool,\n  extractAgentCapabilities,\n} from './agent-capability-tools';\nexport { formTeam, DEFAULT_FORMATION_CONFIG } from './team-formation';\nexport type {\n  RosterAgent,\n  TeamRequirement,\n  TeamMember,\n  FormedTeam,\n  TeamFormationConfig,\n} from './team-formation';\nexport {\n  PRIMARY_ASSISTANT_AGENT,\n  BRITTNEY_AGENT,\n  DAEMON_AGENT,\n  ABSORB_AGENT,\n  ORACLE_AGENT,\n  TEAM_AGENT_PROFILES,\n  getAllProfiles,\n  getProfileById,\n  getProfilesByClaimRole,\n  getProfilesByDomain,\n} from './agent/team-agents';\nexport type { TeamAgentProfile, AgentRole, ClaimFilter } from './agent/team-agents';\nexport {\n  assignAgentsToRoom,\n  runAgentCycle,\n  compoundKnowledge,\n  getRoomAgents,\n  getRoomCycleHistory,\n  removeAgentFromRoom,\n  clearRoom,\n} from './agent/team-coordinator';\nexport type {\n  RoomAgentSlot,\n  CycleResult,\n  KnowledgeInsight,\n  CompoundResult,\n  LoadAgentsResult,\n} from './agent/team-coordinator';\nexport { notify, getNotifications, markAllRead } from './notifications';\nexport { addReply, getReplies, getReplyCount, upvoteReply } from './threads';\nexport { search, registerSearchProviders } from './search';\nexport { HoloMeshSignaler } from './HoloMeshSignaler';\nexport { HoloMeshOrchestratorClient } from './orchestrator-client';\nexport type { WalletAuth } from './orchestrator-client';\nexport { HoloMeshDiscovery } from './discovery';\nexport { HoloMeshWorldState } from './crdt-sync';\nexport {\n  HoloMeshConsolidationBridge,\n  getConsolidationBridge,\n  resetConsolidationBridge,\n} from './consolidation-bridge';\nexport { deriveAgentDid, isWalletDid, verifyGossipSignature } from './wallet-auth';\nexport {\n  DEFAULT_MESH_CONFIG,\n  INITIAL_MESH_STATE,\n  REPUTATION_TIERS,\n  KNOWLEDGE_DOMAINS,\n  DOMAIN_CONSOLIDATION,\n  computeReputation,\n  resolveReputationTier,\n} from './types';\nexport type {\n  HoloMeshAgentCard,\n  GossipMessage,\n  GossipType,\n  MeshKnowledgeEntry,\n  KnowledgeEntryType,\n  AgentReputation,\n  MeshConfig,\n  HoloMeshDaemonState,\n  PeerStoreEntry,\n  GossipDeltaRequest,\n  GossipDeltaResponse,\n  KnowledgeDomain,\n  DomainConsolidationConfig,\n  HotBufferEntry,\n  ConsolidationResult,\n  ReconsolidationEvent,\n} from './types';\n","import { createHash } from 'node:crypto';\n\nexport type X402SettlementMode = 'disabled' | 'dry_run' | 'mock' | 'live';\n\nexport interface EconomicContractRequest {\n  contractId: string;\n  payer: string;\n  amount: number;\n  resourceType?: 'compute' | 'storage' | 'data' | 'inference';\n}\n\nexport type X402SettlementResult =\n  | {\n      success: false;\n      status:\n        | 'no_x402_facilitator'\n        | 'invalid_request'\n        | 'invalid_configuration'\n        | 'live_unavailable';\n      amount: number | null;\n      message: string;\n    }\n  | {\n      success: false;\n      status: 'dry_run';\n      amount: number;\n      transactionId: null;\n      receiptId: string;\n      provisioning: 'none';\n      message: string;\n    }\n  | {\n      status: 'mock_payment';\n      transactionId: string;\n      amount: number;\n      balanceRemaining: -1;\n      provisioning: 'none';\n      message: string;\n    };\n\nexport interface X402SettlementAdapterConfig {\n  mode?: X402SettlementMode;\n  configurationError?: string;\n}\n\nfunction objectValue(value: unknown): Record<string, unknown> | null {\n  return value !== null && typeof value === 'object' && !Array.isArray(value)\n    ? (value as Record<string, unknown>)\n    : null;\n}\n\nfunction nonEmptyString(value: unknown, max = 256): value is string {\n  return typeof value === 'string' && value.trim().length > 0 && value.length <= max;\n}\n\nfunction parseRequest(value: unknown): EconomicContractRequest | null {\n  const input = objectValue(value);\n  if (\n    !input ||\n    !nonEmptyString(input.contractId) ||\n    !nonEmptyString(input.payer, 128) ||\n    typeof input.amount !== 'number' ||\n    !Number.isSafeInteger(input.amount) ||\n    input.amount <= 0\n  ) {\n    return null;\n  }\n  const resourceType = input.resourceType;\n  if (\n    resourceType !== undefined &&\n    !['compute', 'storage', 'data', 'inference'].includes(String(resourceType))\n  ) {\n    return null;\n  }\n  return {\n    contractId: input.contractId.trim(),\n    payer: input.payer.trim(),\n    amount: input.amount,\n    resourceType: resourceType as EconomicContractRequest['resourceType'],\n  };\n}\n\nfunction deterministicId(request: EconomicContractRequest, prefix: string): string {\n  const canonical = JSON.stringify({\n    amount: request.amount,\n    contractId: request.contractId,\n    payer: request.payer,\n    resourceType: request.resourceType ?? null,\n  });\n  return `${prefix}-${createHash('sha256').update(canonical).digest('hex').slice(0, 24)}`;\n}\n\n/**\n * Preparation-only x402 adapter.\n *\n * No mode performs network I/O. Live settlement remains unavailable until the\n * official x402 SDK envelope, paymentRequirements binding, atomic scoped daily\n * reserve/commit ledger, and indeterminate-transaction reconciliation exist.\n */\nexport class X402SettlementAdapter {\n  private readonly mode: X402SettlementMode;\n\n  constructor(private readonly config: X402SettlementAdapterConfig = {}) {\n    this.mode = config.mode ?? 'disabled';\n  }\n\n  execute(value: unknown): X402SettlementResult {\n    const request = parseRequest(value);\n    if (!request) {\n      return {\n        success: false,\n        status: 'invalid_request',\n        amount: null,\n        message: 'Economic contract input is invalid. No transaction occurred.',\n      };\n    }\n    if (this.config.configurationError) {\n      return {\n        success: false,\n        status: 'invalid_configuration',\n        amount: request.amount,\n        message: this.config.configurationError,\n      };\n    }\n    if (this.mode === 'dry_run') {\n      return {\n        success: false,\n        status: 'dry_run',\n        amount: request.amount,\n        transactionId: null,\n        receiptId: deterministicId(request, 'x402-dry-run'),\n        provisioning: 'none',\n        message: 'Dry run only. No network call, wallet signature, transaction, or spend occurred.',\n      };\n    }\n    if (this.mode === 'mock') {\n      return {\n        status: 'mock_payment',\n        transactionId: deterministicId(request, 'mock-tx'),\n        amount: request.amount,\n        balanceRemaining: -1,\n        provisioning: 'none',\n        message: `MOCK: Economic contract ${request.contractId} was simulated. No real x402 transaction occurred.`,\n      };\n    }\n    if (this.mode === 'live') {\n      return {\n        success: false,\n        status: 'live_unavailable',\n        amount: request.amount,\n        message:\n          'Live x402 settlement is unavailable. It requires the official SDK envelope and paymentRequirements binding, an atomic scoped daily reserve/commit ledger, and reconciliation for indeterminate transactions.',\n      };\n    }\n    return {\n      success: false,\n      status: 'no_x402_facilitator',\n      amount: request.amount,\n      message:\n        'No x402 facilitator is connected. execute_economic_contract remains preparation-only; no wallet signature, provisioning, network call, or real transaction occurred. Set ALLOW_MOCK_X402=1 for the deterministic development mock.',\n    };\n  }\n}\n\nexport function createX402SettlementAdapterFromEnv(\n  env: NodeJS.ProcessEnv = process.env\n): X402SettlementAdapter {\n  const configuredMode = env.X402_FACILITATOR_MODE?.trim();\n  const allowedModes: X402SettlementMode[] = ['disabled', 'dry_run', 'mock', 'live'];\n  const validMode = configuredMode && allowedModes.includes(configuredMode as X402SettlementMode);\n  const mode: X402SettlementMode = validMode\n    ? (configuredMode as X402SettlementMode)\n    : env.ALLOW_MOCK_X402 === '1'\n      ? 'mock'\n      : 'disabled';\n  return new X402SettlementAdapter({\n    mode,\n    configurationError:\n      configuredMode && !validMode\n        ? `Unsupported X402_FACILITATOR_MODE: ${configuredMode}. No transaction occurred.`\n        : undefined,\n  });\n}\n","import { Tool } from '@modelcontextprotocol/sdk/types.js';\nimport { WebSocket, type RawData } from 'ws';\n\n/**\n * MCP Tools for Algebraic Trait Composition and Provenance (Pillar 3)\n */\nexport const traitTools: Tool[] = [\n  {\n    name: 'compile_trait_composition',\n    description:\n      'Compile a HoloScript trait composition using algebraic conflict resolution (Provenance Semiring). ' +\n      'Resolves conflicts based on authority weights and provenance traces. ' +\n      'Returns the merged defaultConfig and any composition errors.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        name: {\n          type: 'string',\n          description: 'Name of the composed trait to create (e.g. \"Warrior\")',\n        },\n        components: {\n          type: 'array',\n          items: { type: 'string' },\n          description: 'List of component trait names (e.g. [\"@grabbable\", \"@physics\"])',\n        },\n        overrides: {\n          type: 'object',\n          description: 'Optional property overrides that win over component defaults.',\n        },\n        authorityLevel: {\n          type: 'number',\n          description: 'The authority level of the caller (0-100+). High authority wins conflicts.',\n        },\n      },\n      required: ['name', 'components'],\n    },\n  },\n  {\n    name: 'sync_hardware_loop',\n    description:\n      'Synchronize a virtual HoloScript scene with a physical ROS2 hardware loop. ' +\n      'When ROS2_BRIDGE_URL is configured, connects to rosbridge_server and verifies a live handshake. ' +\n      'Without ROS2_BRIDGE_URL, returns an honest stub with contractVerified=false.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        nodeName: { type: 'string', description: 'ROS2 node name for the hardware bridge' },\n        topicPrefix: { type: 'string', description: 'Prefix for ROS2 topics (default: /holo)' },\n        frequency: { type: 'number', description: 'Sync frequency in Hz (default: 60)' },\n        bidirectional: { type: 'boolean', description: 'Enable bidirectional command flow' },\n      },\n      required: ['nodeName'],\n    },\n  },\n  {\n    name: 'execute_economic_contract',\n    description:\n      'PREPARATION ONLY: validate or simulate a sovereign economic contract (x402). Disabled by default; dry-run, deterministic mock, and live-request modes perform no network call, wallet signature, provisioning, or transaction.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        contractId: {\n          type: 'string',\n          description: 'The unique ID of the economic contract (from code)',\n        },\n        payer: { type: 'string', description: 'The agent ID or wallet of the payer' },\n        amount: { type: 'number', description: 'Amount to authorize in USDC (micro-units)' },\n        resourceType: {\n          type: 'string',\n          enum: ['compute', 'storage', 'data', 'inference'],\n          description: 'Type of resource being rented',\n        },\n      },\n      required: ['contractId', 'payer', 'amount'],\n    },\n  },\n];\n\nimport {\n  TraitCompositionCompiler,\n  vrTraitRegistry,\n  type TraitCompositionDecl,\n} from '@holoscript/core';\n\n// THIN (ratchet P4): provenanceHash is a SHA-256 of the JSON-serialized composition output,\n// not a cryptographic commitment to the source trait definitions. The hash covers the\n// *result* of compilation, not the *inputs* that produced it. Provenance tracing requires\n// binding the input trait names + authority levels, which this hash does not do.\nasync function computeProvenanceHash(composed: unknown): Promise<string> {\n  const { createHash } = await import('crypto');\n  const canonical = JSON.stringify(composed, Object.keys(composed as object).sort());\n  return createHash('sha256').update(canonical).digest('hex');\n}\n\ninterface RosbridgeHandshake {\n  bridgeUrl: string;\n  latencyMs: number;\n  topics: string[];\n  types: string[];\n}\n\nfunction configuredRosbridgeUrl(): string | null {\n  const configured = process.env.ROS2_BRIDGE_URL?.trim();\n  return configured ? configured : null;\n}\n\nfunction rosbridgeTimeoutMs(): number {\n  const configured = Number(process.env.ROS2_BRIDGE_TIMEOUT_MS);\n  return Number.isFinite(configured) && configured > 0 ? configured : 1500;\n}\n\nfunction stringArray(value: unknown): string[] {\n  return Array.isArray(value)\n    ? value.filter((item): item is string => typeof item === 'string')\n    : [];\n}\n\nfunction normalizeRosbridgeValues(values: unknown): { topics: string[]; types: string[] } {\n  const payload = values && typeof values === 'object' ? (values as Record<string, unknown>) : {};\n  return {\n    topics: stringArray(payload.topics),\n    types: stringArray(payload.types),\n  };\n}\n\nfunction rawDataToString(data: RawData): string {\n  if (Array.isArray(data)) {\n    return Buffer.concat(data).toString('utf8');\n  }\n  if (data instanceof ArrayBuffer) {\n    return Buffer.from(data).toString('utf8');\n  }\n  return data.toString('utf8');\n}\n\nasync function handshakeRosbridge(bridgeUrl: string): Promise<RosbridgeHandshake> {\n  const timeoutMs = rosbridgeTimeoutMs();\n  const startedAt = Date.now();\n  const requestId = `sync-hardware-loop-${startedAt}-${Math.random().toString(36).slice(2)}`;\n\n  return await new Promise<RosbridgeHandshake>((resolve, reject) => {\n    const socket = new WebSocket(bridgeUrl);\n    let settled = false;\n\n    const timer = setTimeout(() => {\n      rejectOnce(new Error(`rosbridge handshake timed out after ${timeoutMs}ms`));\n    }, timeoutMs);\n\n    function cleanup() {\n      clearTimeout(timer);\n      socket.removeAllListeners();\n      if (socket.readyState === WebSocket.OPEN || socket.readyState === WebSocket.CONNECTING) {\n        socket.close();\n      }\n    }\n\n    function resolveOnce(value: RosbridgeHandshake) {\n      if (settled) return;\n      settled = true;\n      cleanup();\n      resolve(value);\n    }\n\n    function rejectOnce(error: Error) {\n      if (settled) return;\n      settled = true;\n      cleanup();\n      reject(error);\n    }\n\n    socket.once('open', () => {\n      socket.send(\n        JSON.stringify({\n          op: 'call_service',\n          id: requestId,\n          service: '/rosapi/topics',\n          args: {},\n        })\n      );\n    });\n\n    socket.once('error', (error: Error) => rejectOnce(error));\n    socket.once('close', () => {\n      rejectOnce(new Error('rosbridge connection closed before handshake completed'));\n    });\n\n    socket.on('message', (data: RawData) => {\n      let message: Record<string, unknown>;\n      try {\n        message = JSON.parse(rawDataToString(data)) as Record<string, unknown>;\n      } catch (error: unknown) {\n        const detail = error instanceof Error ? error.message : String(error);\n        rejectOnce(new Error(`invalid rosbridge response: ${detail}`));\n        return;\n      }\n\n      const isExpectedResponse =\n        message.id === requestId ||\n        (message.id === undefined &&\n          message.op === 'service_response' &&\n          message.service === '/rosapi/topics');\n      if (!isExpectedResponse) return;\n\n      if (message.result === false) {\n        rejectOnce(new Error('rosbridge /rosapi/topics returned result=false'));\n        return;\n      }\n\n      const { topics, types } = normalizeRosbridgeValues(message.values);\n      resolveOnce({\n        bridgeUrl,\n        topics,\n        types,\n        latencyMs: Math.max(0, Date.now() - startedAt),\n      });\n    });\n  });\n}\n\nexport async function handleTraitTool(name: string, args: Record<string, any>) {\n  if (name === 'compile_trait_composition') {\n    const compiler = new TraitCompositionCompiler();\n\n    const decl: TraitCompositionDecl & { provenance?: any } = {\n      name: args.name,\n      components: args.components,\n      overrides: args.overrides,\n      provenance: {\n        context: { authorityLevel: args.authorityLevel ?? 0 },\n      },\n    };\n\n    try {\n      // Binder lookup helper\n      const getHandler = (n: string) => {\n        const normalized = n.startsWith('@') ? n.slice(1) : n;\n        return (\n          vrTraitRegistry.getHandler(normalized as never) ?? vrTraitRegistry.getHandler(n as never)\n        );\n      };\n\n      const [result] = compiler.compile([decl], getHandler);\n      return {\n        success: true,\n        composedTrait: result,\n        provenanceHash: await computeProvenanceHash(result), // sha256 of deterministic JSON serialization\n      };\n    } catch (error: any) {\n      return {\n        success: false,\n        error: error.message,\n        type: error.name,\n      };\n    }\n  }\n\n  if (name === 'sync_hardware_loop') {\n    const nodeName =\n      typeof args.nodeName === 'string' && args.nodeName.trim() ? args.nodeName : 'holo_rig_01';\n    const topicPrefix =\n      typeof args.topicPrefix === 'string' && args.topicPrefix.trim() ? args.topicPrefix : '/holo';\n    const requestedFrequency = Number(args.frequency);\n    const frequencyHz =\n      Number.isFinite(requestedFrequency) && requestedFrequency > 0 ? requestedFrequency : 60;\n    const bidirectional = args.bidirectional !== false;\n    const bridgeUrl = configuredRosbridgeUrl();\n\n    if (bridgeUrl) {\n      const startedAt = Date.now();\n      try {\n        const handshake = await handshakeRosbridge(bridgeUrl);\n        return {\n          success: true,\n          status: 'connected',\n          node: nodeName,\n          bridgeUrl: handshake.bridgeUrl,\n          topicPrefix,\n          frequencyHz,\n          bidirectional,\n          latencyMs: handshake.latencyMs,\n          contractVerified: true,\n          activeTopics: handshake.topics,\n          activeTypes: handshake.types,\n          traitEvents: [\n            { type: 'ros2:init', payload: { node: nodeName } },\n            {\n              type: 'ros2:connect',\n              payload: { node: nodeName, bridgeUrl: handshake.bridgeUrl, topicPrefix },\n            },\n            { type: 'ros2:connected', payload: { latencyMs: handshake.latencyMs } },\n          ],\n          message: `ROS2 bridge connected for ${nodeName} via ${handshake.bridgeUrl}.`,\n        };\n      } catch (error: unknown) {\n        const detail = error instanceof Error ? error.message : String(error);\n        return {\n          success: false,\n          status: 'ros2_bridge_unreachable',\n          node: nodeName,\n          bridgeUrl,\n          topicPrefix,\n          frequencyHz,\n          bidirectional,\n          latencyMs: Math.max(0, Date.now() - startedAt),\n          contractVerified: false,\n          error: detail,\n          message:\n            'ROS2_BRIDGE_URL is configured, but rosbridge_server could not complete the /rosapi/topics handshake.',\n        };\n      }\n    }\n\n    // OVERCLAIMED ratchet fix: no ROS2 bridge exists. Return honest stub.\n    // contractVerified is now false — callers must not trust this as a safety gate.\n    return {\n      status: 'stub_no_ros2_bridge',\n      node: nodeName,\n      latencyMs: -1,\n      contractVerified: false,\n      message:\n        'ROS2 bridge not connected. sync_hardware_loop is a stub — no real hardware handshake performed. Do not gate safety decisions on this result.',\n    };\n  }\n\n  if (name === 'execute_economic_contract') {\n    const { createX402SettlementAdapterFromEnv } = await import('./x402-settlement-adapter');\n    return createX402SettlementAdapterFromEnv().execute(args);\n  }\n\n  return null;\n}\n","/**\n * rig_match_skeleton MCP tool\n *\n * Given a list of bone names from an unknown rig, ranks all registered\n * SkeletonStandard profiles by overlap score and returns:\n *   - Top-N ranked candidates (standard id, overlap, confidence, matched/unmatched bones)\n *   - A RefusableDiff: per-bone mapping suggestion from the top candidate to the\n *     HoloScript 65-bone canonical, with a \"refusal\" flag per bone where the\n *     mapping confidence is below a configurable threshold.\n *\n * Gap addressed: G4 from research/2026-04-28_holo-skeleton-gap.md\n * Design ref: D.027 (RefusableDiff pattern — ranked candidates + RefusableDiff)\n *\n * @module mcp-server/tools\n */\n\nimport type { Tool } from '@modelcontextprotocol/sdk/types.js';\nimport {\n  matchSkeletonStandard,\n  buildReverseMap,\n  SKELETON_PROFILES,\n  type SkeletonMatchCandidate,\n  type SkeletonStandardId,\n} from '@holoscript/engine/character';\nimport { HUMANOID_BONE_NAMES } from '@holoscript/engine/character';\n\n// =============================================================================\n// Tool definition\n// =============================================================================\n\nexport const rigMatchSkeletonToolDefinition: Tool = {\n  name: 'rig_match_skeleton',\n  description:\n    'Given a list of bone names from an unknown 3D rig, ranks all registered HoloScript ' +\n    'skeleton standards (VRM 1.0, VRM 0.x, Ready Player Me, Mixamo, UE Mannequin, MetaHuman, ' +\n    'DAZ Genesis 8/9, AutoRig Pro, CC3, HoloScript 65-bone canonical) by bone-name overlap. ' +\n    'Returns the top-N ranked candidates plus a RefusableDiff — a per-bone mapping proposal ' +\n    'from the best match to the HoloScript canonical that flags low-confidence mappings for ' +\n    'human review. Use this before retargeting animations to an unknown avatar skeleton.',\n  inputSchema: {\n    type: 'object' as const,\n    required: ['boneNames'],\n    properties: {\n      boneNames: {\n        type: 'array',\n        items: { type: 'string' },\n        description:\n          'Array of bone names extracted from the rig (case-sensitive, as they appear in ' +\n          'the glTF/FBX/VRM file). Typically 20–70 names for a humanoid.',\n        minItems: 1,\n        maxItems: 500,\n      },\n      topN: {\n        type: 'number',\n        description:\n          'Maximum number of ranked candidates to return (default 5, max 11 — one per standard).',\n        default: 5,\n        minimum: 1,\n        maximum: 11,\n      },\n      refusalThreshold: {\n        type: 'number',\n        description:\n          'Weighted-score threshold below which a bone mapping is flagged as \"refused\" ' +\n          'in the RefusableDiff and requires human confirmation (default 0.6, range 0.0–1.0). ' +\n          'Higher = more conservative; lower = more permissive.',\n        default: 0.6,\n        minimum: 0.0,\n        maximum: 1.0,\n      },\n    },\n  },\n};\n\n// =============================================================================\n// RefusableDiff types\n// =============================================================================\n\nexport interface BoneMappingEntry {\n  /** Bone name as it appears in the input rig. */\n  inputBone: string;\n  /** HoloScript 65-bone canonical name this input bone maps to. */\n  canonicalBone: string | null;\n  /** Platform name for this canonical bone in the top-ranked standard. */\n  platformName: string | null;\n  /** Whether this mapping is below the refusal threshold and needs human review. */\n  refused: boolean;\n  /** Reason for refusal (human-readable). */\n  refusalReason?: string;\n}\n\nexport interface RefusableDiff {\n  /** The skeleton standard used to generate this diff. */\n  standard: SkeletonStandardId;\n  /** Weighted score of the chosen standard (0.0–1.0). */\n  weightedScore: number;\n  /**\n   * Per-bone mapping entries.\n   * Order matches the input `boneNames` array.\n   */\n  entries: BoneMappingEntry[];\n  /**\n   * Canonical bones that appear in the 65-bone template but have no\n   * corresponding input bone — these would be missing from the retargeted rig.\n   */\n  missingCanonicalBones: string[];\n  /** Total number of refused mappings. */\n  refusedCount: number;\n  /** True when zero mappings are refused (diff is fully auto-approvable). */\n  autoApprovable: boolean;\n}\n\n// =============================================================================\n// Tool handler\n// =============================================================================\n\nexport interface RigMatchSkeletonInput {\n  boneNames: string[];\n  topN?: number;\n  refusalThreshold?: number;\n}\n\nexport interface RigMatchSkeletonOutput {\n  /** Input bone count. */\n  inputBoneCount: number;\n  /** Ranked skeleton standard candidates. */\n  candidates: SkeletonMatchCandidate[];\n  /** RefusableDiff built from the top-ranked candidate. */\n  refusableDiff: RefusableDiff | null;\n  /** Summary message. */\n  summary: string;\n}\n\nexport function handleRigMatchSkeleton(input: RigMatchSkeletonInput): RigMatchSkeletonOutput {\n  const { boneNames, topN = 5, refusalThreshold = 0.6 } = input;\n\n  if (!boneNames || boneNames.length === 0) {\n    return {\n      inputBoneCount: 0,\n      candidates: [],\n      refusableDiff: null,\n      summary: 'No bone names provided.',\n    };\n  }\n\n  // Rank candidates\n  const candidates = matchSkeletonStandard(boneNames, Math.min(topN, 11));\n\n  if (candidates.length === 0) {\n    return {\n      inputBoneCount: boneNames.length,\n      candidates: [],\n      refusableDiff: null,\n      summary: 'No skeleton standards registered.',\n    };\n  }\n\n  // Build RefusableDiff from the top candidate\n  const topCandidate = candidates[0];\n  const refusableDiff = buildRefusableDiff(boneNames, topCandidate, refusalThreshold);\n\n  const summary = buildSummary(boneNames, topCandidate, refusableDiff);\n\n  return {\n    inputBoneCount: boneNames.length,\n    candidates,\n    refusableDiff,\n    summary,\n  };\n}\n\n// =============================================================================\n// RefusableDiff builder\n// =============================================================================\n\nfunction buildRefusableDiff(\n  inputBones: string[],\n  topCandidate: SkeletonMatchCandidate,\n  refusalThreshold: number\n): RefusableDiff {\n  const { standard, weightedScore } = topCandidate;\n  const profile = SKELETON_PROFILES[standard];\n  const reverseMap = buildReverseMap(standard);\n  const inputSet = new Set(inputBones);\n\n  const entries: BoneMappingEntry[] = inputBones.map((inputBone) => {\n    const canonicalBone = reverseMap.get(inputBone) ?? null;\n    const platformName = canonicalBone\n      ? (profile.boneMap[canonicalBone]?.platformName ?? null)\n      : null;\n\n    let refused = false;\n    let refusalReason: string | undefined;\n\n    if (canonicalBone === null) {\n      refused = true;\n      refusalReason = `Bone \"${inputBone}\" has no mapping in standard \"${standard}\". Manual mapping required.`;\n    } else if (weightedScore < refusalThreshold) {\n      refused = true;\n      refusalReason =\n        `Standard \"${standard}\" weighted score (${weightedScore.toFixed(2)}) is below ` +\n        `refusal threshold (${refusalThreshold.toFixed(2)}). Verify mapping manually.`;\n    }\n\n    return {\n      inputBone,\n      canonicalBone,\n      platformName,\n      refused,\n      refusalReason,\n    };\n  });\n\n  // Find canonical bones with no corresponding input bone\n  const mappedCanonicals = new Set(\n    entries.filter((e) => e.canonicalBone !== null).map((e) => e.canonicalBone!)\n  );\n  const missingCanonicalBones = HUMANOID_BONE_NAMES.filter((b) => !mappedCanonicals.has(b));\n\n  const refusedCount = entries.filter((e) => e.refused).length;\n\n  return {\n    standard,\n    weightedScore,\n    entries,\n    missingCanonicalBones,\n    refusedCount,\n    autoApprovable: refusedCount === 0,\n  };\n}\n\n// =============================================================================\n// Summary builder\n// =============================================================================\n\nfunction buildSummary(\n  inputBones: string[],\n  topCandidate: SkeletonMatchCandidate,\n  diff: RefusableDiff\n): string {\n  const lines: string[] = [\n    `Input: ${inputBones.length} bones`,\n    `Top match: ${topCandidate.standard} ` +\n      `(overlap=${(topCandidate.overlapScore * 100).toFixed(1)}%, ` +\n      `weighted=${topCandidate.weightedScore.toFixed(3)})`,\n    `Matched: ${topCandidate.matchedBones.length} / ${inputBones.length} bones`,\n  ];\n\n  if (topCandidate.unmatchedBones.length > 0) {\n    const preview = topCandidate.unmatchedBones.slice(0, 5).join(', ');\n    const more =\n      topCandidate.unmatchedBones.length > 5\n        ? ` … +${topCandidate.unmatchedBones.length - 5} more`\n        : '';\n    lines.push(`Unmatched: ${preview}${more}`);\n  }\n\n  if (diff.missingCanonicalBones.length > 0) {\n    lines.push(\n      `Missing canonical bones (rig lacks them): ${diff.missingCanonicalBones.length} ` +\n        `(e.g. ${diff.missingCanonicalBones.slice(0, 3).join(', ')})`\n    );\n  }\n\n  if (diff.autoApprovable) {\n    lines.push('RefusableDiff: AUTO-APPROVABLE — all mappings above confidence threshold.');\n  } else {\n    lines.push(`RefusableDiff: ${diff.refusedCount} mapping(s) REFUSED — require human review.`);\n  }\n\n  return lines.join('\\n');\n}\n","/**\n * `.holo` mesh-shape bridge — emit/read a real imported mesh as a `.holo`\n * `shape \"<name>\" mesh { ... }` block (Track 0: the `.holo` FILE carries the\n * surface, not a text pointer to an external model).\n *\n * `meshShapeToHolo` serializes the engine codec's {@link HoloMeshGeometry}\n * (base64 buffers) into `.holo` text that `parseHolo` reads as a `HoloShape`\n * with `shapeType: 'mesh'`; `holoShapeToMesh` is the inverse — it reads a parsed\n * mesh shape back into a {@link SkinnedMeshData}. Together they close the\n * import → `.holo` file → parse round-trip with geometry intact.\n *\n * @package @holoscript/cli/importers\n */\nimport {\n  decodeSkinnedMeshFromHolo,\n  type HoloMeshGeometry,\n  type DecodedHoloMesh,\n} from '@holoscript/engine';\n\n/**\n * Emit a `shape \"<name>\" mesh { ...base64 }` block. `indent` is the leading\n * indentation so the block sits cleanly inside a `composition { … }`.\n */\nexport function meshShapeToHolo(name: string, geo: HoloMeshGeometry, indent = '  '): string {\n  const i = indent;\n  const ii = indent + '  ';\n  const lines = [`${i}shape \"${name}\" mesh {`];\n  lines.push(`${ii}positionsB64: \"${geo.positionsB64}\"`);\n  lines.push(`${ii}normalsB64: \"${geo.normalsB64}\"`);\n  lines.push(`${ii}tangentsB64: \"${geo.tangentsB64}\"`);\n  if (geo.uvsB64) lines.push(`${ii}uvsB64: \"${geo.uvsB64}\"`);\n  lines.push(`${ii}indicesB64: \"${geo.indicesB64}\"`);\n  lines.push(`${ii}jointIndicesB64: \"${geo.jointIndicesB64}\"`);\n  lines.push(`${ii}jointWeightsB64: \"${geo.jointWeightsB64}\"`);\n  // Rig (optional) — carried so the mesh can be re-emitted WITH a glTF skin.\n  if (geo.inverseBindMatricesB64 && geo.jointCount !== undefined) {\n    lines.push(`${ii}inverseBindMatricesB64: \"${geo.inverseBindMatricesB64}\"`);\n    lines.push(`${ii}jointCount: ${geo.jointCount}`);\n  }\n  lines.push(`${ii}vertexCount: ${geo.vertexCount}`);\n  lines.push(`${i}}`);\n  return lines.join('\\n');\n}\n\n/**\n * Read a parsed mesh shape (a `HoloShape` with `shapeType: 'mesh'`) back into a\n * {@link SkinnedMeshData}. Structurally typed on `properties` so it consumes a\n * parsed `HoloShape` without importing the parser AST type.\n */\nexport function holoShapeToMesh(shape: {\n  properties: ReadonlyArray<{ key: string; value: unknown }>;\n}): DecodedHoloMesh {\n  const map = new Map(shape.properties.map((p) => [p.key, p.value]));\n  const str = (k: string): string => {\n    const v = map.get(k);\n    if (typeof v !== 'string') {\n      throw new Error(`mesh shape: missing/invalid string property \"${k}\"`);\n    }\n    return v;\n  };\n  const uvsVal = map.get('uvsB64');\n  const ibmVal = map.get('inverseBindMatricesB64');\n  const jointCountVal = map.get('jointCount');\n  const geo: HoloMeshGeometry = {\n    positionsB64: str('positionsB64'),\n    normalsB64: str('normalsB64'),\n    tangentsB64: str('tangentsB64'),\n    ...(typeof uvsVal === 'string' ? { uvsB64: uvsVal } : {}),\n    indicesB64: str('indicesB64'),\n    jointIndicesB64: str('jointIndicesB64'),\n    jointWeightsB64: str('jointWeightsB64'),\n    ...(typeof ibmVal === 'string' && jointCountVal !== undefined\n      ? { inverseBindMatricesB64: ibmVal, jointCount: Number(jointCountVal) }\n      : {}),\n    vertexCount: Number(map.get('vertexCount') ?? 0),\n  };\n  return decodeSkinnedMeshFromHolo(geo);\n}\n","/**\n * glTF/GLB to .holo Importer\n *\n * Reads a glTF 2.0 or GLB binary file and generates HoloScript .holo\n * composition code. Handles node hierarchy, PBR materials, animations,\n * and common physics extensions (KHR_rigid_bodies, etc.).\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { CharacterRender, encodeSkinnedMeshToHolo } from '@holoscript/engine';\nimport { meshShapeToHolo } from './mesh-shape';\n\n// ---------------------------------------------------------------------------\n// Interfaces\n// ---------------------------------------------------------------------------\n\ninterface GltfNode {\n  name?: string;\n  mesh?: number;\n  camera?: number;\n  skin?: number;\n  children?: number[];\n  translation?: [number, number, number];\n  rotation?: [number, number, number, number];\n  scale?: [number, number, number];\n  matrix?: number[];\n  extras?: Record<string, unknown>;\n  extensions?: Record<string, unknown>;\n}\n\n/**\n * Narrow extension shapes for the glTF extensions this importer reads.\n * The wider `extensions: Record<string, unknown>` field on GltfNode/GltfData\n * keeps the door open for unknown extensions, but every consumer below\n * narrows via `as XExt | undefined` so strict TS doesn't error on field\n * access. Was previously masked by `as any` (removed in d5b42fa51,\n * unmasking these as deploy-blockers in pre-flight).\n */\ninterface KhrRigidBodyExt {\n  isKinematic?: boolean;\n  mass?: number;\n  linearVelocity?: [number, number, number];\n  angularVelocity?: [number, number, number];\n  linearDamping?: number;\n  angularDamping?: number;\n}\n\ninterface MsftPhysicsExt {\n  rigidBody?: KhrRigidBodyExt;\n}\n\ninterface KhrLightsPunctualExt {\n  lights?: Array<{\n    type: string;\n    color?: [number, number, number];\n    intensity?: number;\n  }>;\n}\n\ninterface GltfMaterial {\n  name?: string;\n  pbrMetallicRoughness?: {\n    baseColorFactor?: [number, number, number, number];\n    baseColorTexture?: { index: number };\n    metallicFactor?: number;\n    roughnessFactor?: number;\n    metallicRoughnessTexture?: { index: number };\n  };\n  normalTexture?: { index: number; scale?: number };\n  occlusionTexture?: { index: number; strength?: number };\n  emissiveFactor?: [number, number, number];\n  emissiveTexture?: { index: number };\n  alphaMode?: string;\n  alphaCutoff?: number;\n  doubleSided?: boolean;\n  extensions?: Record<string, unknown>;\n}\n\ninterface GltfMeshPrimitive {\n  attributes: Record<string, number>;\n  indices?: number;\n  material?: number;\n  mode?: number;\n}\n\ninterface GltfMesh {\n  name?: string;\n  primitives: GltfMeshPrimitive[];\n}\n\ninterface GltfAnimationChannelTarget {\n  node?: number;\n  path: string; // \"translation\" | \"rotation\" | \"scale\" | \"weights\"\n}\n\ninterface GltfAnimationChannel {\n  sampler: number;\n  target: GltfAnimationChannelTarget;\n}\n\ninterface GltfAnimationSampler {\n  input: number;\n  output: number;\n  interpolation?: string; // \"LINEAR\" | \"STEP\" | \"CUBICSPLINE\"\n}\n\ninterface GltfAnimation {\n  name?: string;\n  channels: GltfAnimationChannel[];\n  samplers: GltfAnimationSampler[];\n}\n\ninterface GltfScene {\n  name?: string;\n  nodes?: number[];\n}\n\ninterface GltfData {\n  asset: { version: string; generator?: string; copyright?: string };\n  scene?: number;\n  scenes?: GltfScene[];\n  nodes?: GltfNode[];\n  meshes?: GltfMesh[];\n  materials?: GltfMaterial[];\n  animations?: GltfAnimation[];\n  cameras?: Array<{ name?: string; type: string; perspective?: any; orthographic?: any }>;\n  skins?: Array<{ name?: string; joints: number[] }>;\n  extensionsUsed?: string[];\n  extensions?: Record<string, unknown>;\n}\n\n// ---------------------------------------------------------------------------\n// GLB Constants\n// ---------------------------------------------------------------------------\n\nconst GLB_MAGIC = 0x46546c67; // \"glTF\" in little-endian\nconst GLB_VERSION = 2;\nconst GLB_CHUNK_JSON = 0x4e4f534a; // \"JSON\" in little-endian\nconst _GLB_CHUNK_BIN = 0x004e4942; // \"BIN\\0\" in little-endian\nconst GLB_HEADER_SIZE = 12;\nconst GLB_CHUNK_HEADER_SIZE = 8;\n\n// ---------------------------------------------------------------------------\n// GLB Parser\n// ---------------------------------------------------------------------------\n\n/**\n * Parse a GLB binary container and extract the JSON chunk as GltfData.\n * The binary chunk is not interpreted here since we reference geometry\n * by name in the output .holo rather than embedding raw vertex data.\n */\nfunction parseGlb(buffer: Buffer): GltfData {\n  if (buffer.length < GLB_HEADER_SIZE) {\n    throw new Error('GLB file too small to contain a valid header.');\n  }\n\n  const magic = buffer.readUInt32LE(0);\n  if (magic !== GLB_MAGIC) {\n    throw new Error(\n      `Invalid GLB magic number: expected 0x${GLB_MAGIC.toString(16)}, got 0x${magic.toString(16)}.`\n    );\n  }\n\n  const version = buffer.readUInt32LE(4);\n  if (version !== GLB_VERSION) {\n    throw new Error(`Unsupported GLB version ${version}. Only version 2 is supported.`);\n  }\n\n  const totalLength = buffer.readUInt32LE(8);\n  if (buffer.length < totalLength) {\n    throw new Error(\n      `GLB file truncated: header declares ${totalLength} bytes but buffer is ${buffer.length} bytes.`\n    );\n  }\n\n  // Walk chunks\n  let offset = GLB_HEADER_SIZE;\n  let jsonData: GltfData | null = null;\n\n  while (offset + GLB_CHUNK_HEADER_SIZE <= totalLength) {\n    const chunkLength = buffer.readUInt32LE(offset);\n    const chunkType = buffer.readUInt32LE(offset + 4);\n    const chunkDataOffset = offset + GLB_CHUNK_HEADER_SIZE;\n\n    if (chunkDataOffset + chunkLength > totalLength) {\n      throw new Error(`GLB chunk at offset ${offset} overflows the file boundary.`);\n    }\n\n    if (chunkType === GLB_CHUNK_JSON) {\n      const jsonString = buffer.toString('utf8', chunkDataOffset, chunkDataOffset + chunkLength);\n      try {\n        jsonData = JSON.parse(jsonString) as GltfData;\n      } catch (e) {\n        throw new Error(`Failed to parse JSON chunk in GLB: ${(e as Error).message}`);\n      }\n    }\n    // We intentionally skip the BIN chunk - geometry is referenced by path\n\n    offset = chunkDataOffset + chunkLength;\n  }\n\n  if (!jsonData) {\n    throw new Error('GLB file does not contain a JSON chunk.');\n  }\n\n  return jsonData;\n}\n\n// ---------------------------------------------------------------------------\n// Color Utilities\n// ---------------------------------------------------------------------------\n\n/**\n * Convert linear RGB float values (0-1 range) to a hex color string.\n * Applies a simple sRGB gamma correction (power of 1/2.2) before encoding.\n */\nfunction rgbToHex(r: number, g: number, b: number): string {\n  const toSrgb = (c: number): number => {\n    const clamped = Math.max(0, Math.min(1, c));\n    // Linear to sRGB approximation\n    const corrected =\n      clamped <= 0.0031308 ? clamped * 12.92 : 1.055 * Math.pow(clamped, 1.0 / 2.4) - 0.055;\n    return Math.round(corrected * 255);\n  };\n\n  const rr = toSrgb(r).toString(16).padStart(2, '0');\n  const gg = toSrgb(g).toString(16).padStart(2, '0');\n  const bb = toSrgb(b).toString(16).padStart(2, '0');\n\n  return `#${rr}${gg}${bb}`;\n}\n\n// ---------------------------------------------------------------------------\n// Quaternion to Euler Conversion\n// ---------------------------------------------------------------------------\n\n/**\n * Convert a quaternion [x, y, z, w] to Euler angles [rx, ry, rz] in degrees.\n * Uses intrinsic Tait-Bryan angles (XYZ order).\n */\nfunction quaternionToEulerDeg(q: [number, number, number, number]): [number, number, number] {\n  const [x, y, z, w] = q;\n\n  // Roll (X)\n  const sinrCosp = 2.0 * (w * x + y * z);\n  const cosrCosp = 1.0 - 2.0 * (x * x + y * y);\n  const roll = Math.atan2(sinrCosp, cosrCosp);\n\n  // Pitch (Y)\n  const sinp = 2.0 * (w * y - z * x);\n  let pitch: number;\n  if (Math.abs(sinp) >= 1) {\n    pitch = Math.sign(sinp) * (Math.PI / 2); // gimbal lock\n  } else {\n    pitch = Math.asin(sinp);\n  }\n\n  // Yaw (Z)\n  const sinyCosp = 2.0 * (w * z + x * y);\n  const cosyCosp = 1.0 - 2.0 * (y * y + z * z);\n  const yaw = Math.atan2(sinyCosp, cosyCosp);\n\n  const toDeg = (rad: number): number => {\n    const deg = (rad * 180.0) / Math.PI;\n    return Math.round(deg * 1000) / 1000; // 3 decimal places\n  };\n\n  return [toDeg(roll), toDeg(pitch), toDeg(yaw)];\n}\n\n// ---------------------------------------------------------------------------\n// Formatting Helpers\n// ---------------------------------------------------------------------------\n\nfunction formatVec3(v: [number, number, number]): string {\n  const fmt = (n: number): string => {\n    const rounded = Math.round(n * 1000) / 1000;\n    return String(rounded);\n  };\n  return `[${fmt(v[0])}, ${fmt(v[1])}, ${fmt(v[2])}]`;\n}\n\n/**\n * Sanitize a name for use as a HoloScript identifier.\n * Replaces non-alphanumeric characters (except underscores) with underscores.\n */\nfunction sanitizeName(name: string): string {\n  let clean = name.replace(/[^a-zA-Z0-9_]/g, '_');\n  // Ensure it does not start with a digit\n  if (/^\\d/.test(clean)) {\n    clean = '_' + clean;\n  }\n  // Collapse multiple underscores\n  clean = clean.replace(/_+/g, '_');\n  // Trim trailing underscores\n  clean = clean.replace(/_+$/, '');\n  return clean || 'unnamed';\n}\n\n// ---------------------------------------------------------------------------\n// Trait Inference\n// ---------------------------------------------------------------------------\n\n/**\n * Infer HoloScript traits from a glTF node based on its name, properties,\n * extensions, and relationships within the glTF document.\n */\nfunction inferTraits(node: GltfNode, gltf: GltfData): string[] {\n  const traits: string[] = [];\n  const nameLower = (node.name || '').toLowerCase();\n\n  // --- Name-based inference ---\n\n  // Light sources\n  if (/light|lamp|lantern|candle|torch|bulb|emitter/.test(nameLower)) {\n    traits.push('@glowing');\n    traits.push('@emissive');\n  }\n\n  // Interactive objects\n  if (/button|switch|lever|toggle|handle/.test(nameLower)) {\n    traits.push('@clickable');\n  }\n\n  if (/door|gate|hatch|lid/.test(nameLower)) {\n    traits.push('@clickable');\n    traits.push('@animated');\n  }\n\n  if (/grab|pickup|pick_up|item|tool|weapon|sword|axe|hammer|key/.test(nameLower)) {\n    traits.push('@grabbable');\n  }\n\n  // Physics objects\n  if (/crate|box|barrel|rock|stone|debris|plank|brick/.test(nameLower)) {\n    traits.push('@physics');\n    traits.push('@collidable');\n  }\n\n  if (/ball|projectile|missile/.test(nameLower)) {\n    traits.push('@physics');\n    traits.push('@throwable');\n    traits.push('@grabbable');\n  }\n\n  // Platforms and terrain\n  if (/floor|ground|terrain|platform|wall|ceiling|ramp|stair/.test(nameLower)) {\n    traits.push('@collidable');\n  }\n\n  // Characters and NPCs\n  if (/npc|character|enemy|creature|avatar|player|companion|guard|villager/.test(nameLower)) {\n    traits.push('@animated');\n    traits.push('@collidable');\n  }\n\n  // Portals and teleporters\n  if (/portal|teleport|warp|gate/.test(nameLower)) {\n    traits.push('@portal');\n    traits.push('@glowing');\n  }\n\n  // Audio\n  if (/speaker|radio|audio|music|sound/.test(nameLower)) {\n    traits.push('@spatial_audio');\n  }\n\n  // Glass / transparent\n  if (/glass|window|transparent|crystal|ice/.test(nameLower)) {\n    traits.push('@transparent');\n  }\n\n  // Mirror / reflective\n  if (/mirror|chrome|metal|shiny|polished/.test(nameLower)) {\n    traits.push('@reflective');\n  }\n\n  // Particle sources\n  if (/fire|smoke|fountain|waterfall|steam|spark|flame/.test(nameLower)) {\n    traits.push('@particle_emitter');\n  }\n\n  // --- Extension-based inference ---\n  const ext = node.extensions || {};\n\n  // KHR_rigid_bodies or similar physics extensions\n  const rigidBody = (ext['KHR_rigid_bodies'] || ext['KHR_physics_rigid_bodies']) as\n    | KhrRigidBodyExt\n    | undefined;\n  if (rigidBody) {\n    if (rigidBody.isKinematic) {\n      traits.push('@kinematic');\n    } else {\n      traits.push('@physics');\n      traits.push('@rigid');\n    }\n    traits.push('@collidable');\n  }\n\n  // MSFT_physics (Microsoft physics extension)\n  const physics = ext['MSFT_physics'] as MsftPhysicsExt | undefined;\n  if (physics?.rigidBody) {\n    if (physics.rigidBody.isKinematic) {\n      traits.push('@kinematic');\n    } else {\n      traits.push('@physics');\n    }\n    traits.push('@collidable');\n  }\n\n  // KHR_lights_punctual\n  if (ext['KHR_lights_punctual']) {\n    traits.push('@emissive');\n    traits.push('@glowing');\n  }\n\n  // --- Extras-based inference ---\n  const extras = node.extras || {};\n\n  if (extras.holoscript_traits && Array.isArray(extras.holoscript_traits)) {\n    for (const t of extras.holoscript_traits) {\n      const traitStr = String(t).startsWith('@') ? String(t) : `@${t}`;\n      if (!traits.includes(traitStr)) {\n        traits.push(traitStr);\n      }\n    }\n  }\n\n  if (extras.interactive === true || extras.interactable === true) {\n    if (!traits.includes('@clickable')) {\n      traits.push('@clickable');\n    }\n  }\n\n  if (extras.physics === true || extras.rigidbody === true) {\n    if (!traits.includes('@physics')) {\n      traits.push('@physics');\n      traits.push('@collidable');\n    }\n  }\n\n  // --- Animation-based inference ---\n  if (gltf.animations && gltf.animations.length > 0 && gltf.nodes) {\n    const nodeIndex = gltf.nodes.indexOf(node);\n    if (nodeIndex >= 0) {\n      const hasAnimation = gltf.animations.some((anim) =>\n        anim.channels.some((ch) => ch.target.node === nodeIndex)\n      );\n      if (hasAnimation && !traits.includes('@animated')) {\n        traits.push('@animated');\n      }\n    }\n  }\n\n  // Deduplicate\n  return [...new Set(traits)];\n}\n\n// ---------------------------------------------------------------------------\n// Material Mapping\n// ---------------------------------------------------------------------------\n\n/**\n * Map a glTF PBR material to HoloScript property lines and trait strings.\n */\nfunction materialToTraits(material: GltfMaterial): { properties: string[]; traits: string[] } {\n  const properties: string[] = [];\n  const traits: string[] = [];\n  const pbr = material.pbrMetallicRoughness;\n\n  // Base color\n  if (pbr?.baseColorFactor) {\n    const [r, g, b, a] = pbr.baseColorFactor;\n    properties.push(`color: \"${rgbToHex(r, g, b)}\"`);\n\n    if (a < 1.0) {\n      traits.push('@transparent');\n      properties.push(`opacity: ${Math.round(a * 100) / 100}`);\n    }\n  }\n\n  // Metalness\n  if (pbr?.metallicFactor !== undefined) {\n    properties.push(`metalness: ${Math.round(pbr.metallicFactor * 100) / 100}`);\n    if (pbr.metallicFactor > 0.7) {\n      traits.push('@reflective');\n    }\n  }\n\n  // Roughness\n  if (pbr?.roughnessFactor !== undefined) {\n    properties.push(`roughness: ${Math.round(pbr.roughnessFactor * 100) / 100}`);\n  }\n\n  // Emissive\n  if (material.emissiveFactor) {\n    const [er, eg, eb] = material.emissiveFactor;\n    if (er > 0 || eg > 0 || eb > 0) {\n      traits.push('@emissive');\n      properties.push(`emissive_color: \"${rgbToHex(er, eg, eb)}\"`);\n      const intensity = Math.max(er, eg, eb);\n      properties.push(`emissive_intensity: ${Math.round(intensity * 100) / 100}`);\n    }\n  }\n\n  // Alpha mode\n  if (material.alphaMode === 'BLEND') {\n    if (!traits.includes('@transparent')) {\n      traits.push('@transparent');\n    }\n  } else if (material.alphaMode === 'MASK') {\n    const cutoff = material.alphaCutoff ?? 0.5;\n    properties.push(`alpha_cutoff: ${cutoff}`);\n  }\n\n  // Double-sided\n  if (material.doubleSided) {\n    properties.push(`double_sided: true`);\n  }\n\n  return { properties, traits };\n}\n\n// ---------------------------------------------------------------------------\n// Animation Mapping\n// ---------------------------------------------------------------------------\n\n/**\n * Gather animation clip names that target a specific node index.\n */\nfunction getAnimationClipsForNode(nodeIndex: number, gltf: GltfData): string[] {\n  const clips: string[] = [];\n\n  if (!gltf.animations) {\n    return clips;\n  }\n\n  for (const anim of gltf.animations) {\n    const targetsThisNode = anim.channels.some((ch) => ch.target.node === nodeIndex);\n    if (targetsThisNode) {\n      const clipName = anim.name || `animation_${gltf.animations.indexOf(anim)}`;\n      if (!clips.includes(clipName)) {\n        clips.push(clipName);\n      }\n    }\n  }\n\n  return clips;\n}\n\n// ---------------------------------------------------------------------------\n// Physics Extension Mapping\n// ---------------------------------------------------------------------------\n\n/**\n * Extract physics trait parameters from glTF extensions on a node.\n */\nfunction extractPhysicsParams(node: GltfNode): string[] {\n  const params: string[] = [];\n  const ext = node.extensions || {};\n\n  // KHR_rigid_bodies\n  const rigid = (ext['KHR_rigid_bodies'] || ext['KHR_physics_rigid_bodies']) as\n    | KhrRigidBodyExt\n    | undefined;\n  if (rigid) {\n    if (rigid.mass !== undefined) {\n      params.push(`mass: ${rigid.mass}`);\n    }\n    if (rigid.linearVelocity) {\n      params.push(`linear_velocity: ${formatVec3(rigid.linearVelocity)}`);\n    }\n    if (rigid.angularVelocity) {\n      params.push(`angular_velocity: ${formatVec3(rigid.angularVelocity)}`);\n    }\n  }\n\n  // MSFT_physics\n  const msft = ext['MSFT_physics'] as MsftPhysicsExt | undefined;\n  if (msft?.rigidBody) {\n    const rb = msft.rigidBody;\n    if (rb.mass !== undefined) {\n      params.push(`mass: ${rb.mass}`);\n    }\n    if (rb.linearDamping !== undefined) {\n      params.push(`linear_damping: ${rb.linearDamping}`);\n    }\n    if (rb.angularDamping !== undefined) {\n      params.push(`angular_damping: ${rb.angularDamping}`);\n    }\n  }\n\n  return params;\n}\n\n// ---------------------------------------------------------------------------\n// Node-to-Holo Conversion\n// ---------------------------------------------------------------------------\n\n/**\n * Convert a single glTF node (and its children recursively) into .holo\n * object block(s).\n */\nfunction nodeToHolo(\n  nodeIndex: number,\n  gltf: GltfData,\n  inputPath: string,\n  indent: number,\n  meshShapeNames?: ReadonlyMap<number, string>,\n): string {\n  const nodes = gltf.nodes;\n  if (!nodes || nodeIndex < 0 || nodeIndex >= nodes.length) {\n    return '';\n  }\n\n  const node = nodes[nodeIndex];\n  const pad = '  '.repeat(indent);\n  const innerPad = '  '.repeat(indent + 1);\n  const rawName = node.name || `node_${nodeIndex}`;\n  const _safeName = sanitizeName(rawName);\n  const displayName = node.name || `Node_${nodeIndex}`;\n\n  // Collect traits\n  const inferredTraits = inferTraits(node, gltf);\n\n  // Material traits and properties\n  let materialProps: string[] = [];\n  let materialTraits: string[] = [];\n\n  if (node.mesh !== undefined && gltf.meshes) {\n    const mesh = gltf.meshes[node.mesh];\n    if (mesh && mesh.primitives.length > 0) {\n      const primMaterialIdx = mesh.primitives[0].material;\n      if (primMaterialIdx !== undefined && gltf.materials && gltf.materials[primMaterialIdx]) {\n        const mat = gltf.materials[primMaterialIdx];\n        const mapped = materialToTraits(mat);\n        materialProps = mapped.properties;\n        materialTraits = mapped.traits;\n      }\n    }\n  }\n\n  // Merge traits (deduplicate)\n  const allTraits = [...new Set([...inferredTraits, ...materialTraits])];\n\n  // Animation clips\n  const animClips = getAnimationClipsForNode(nodeIndex, gltf);\n  if (animClips.length > 0 && !allTraits.includes('@animated')) {\n    allTraits.push('@animated');\n  }\n\n  // Physics parameters\n  const physicsParams = extractPhysicsParams(node);\n\n  // Build the trait string\n  const traitStr = allTraits.length > 0 ? ' ' + allTraits.join(' ') : '';\n\n  // Start building object block\n  const lines: string[] = [];\n  lines.push(`${pad}object \"${displayName}\"${traitStr} {`);\n\n  // Geometry reference. When the importer carried this node's mesh into the\n  // composition as an in-file `shape \"<name>\" mesh { … }` block (Track-0), point\n  // the node at ITS mesh's carried shape by name (looked up by glTF mesh index,\n  // so multi-mesh GLBs link each node to its own surface) — the surface lives in\n  // the `.holo` file itself, no dead `file.glb#Node` external pointer. Falls back\n  // to the legacy text pointer when this mesh has no carried shape (Draco that\n  // wasn't decompressed, or a primitive with no POSITION).\n  if (node.mesh !== undefined) {\n    const shapeName = meshShapeNames?.get(node.mesh);\n    if (shapeName) {\n      lines.push(`${innerPad}geometry: \"${shapeName}\"`);\n    } else {\n      const sourceFile = path.basename(inputPath);\n      lines.push(`${innerPad}geometry: \"${sourceFile}#${displayName}\"`);\n    }\n  }\n\n  // Transform: position\n  if (node.translation) {\n    lines.push(`${innerPad}position: ${formatVec3(node.translation)}`);\n  }\n\n  // Transform: rotation (quaternion -> euler degrees)\n  if (node.rotation) {\n    const euler = quaternionToEulerDeg(node.rotation);\n    // Only emit if non-zero\n    if (euler[0] !== 0 || euler[1] !== 0 || euler[2] !== 0) {\n      lines.push(`${innerPad}rotation: ${formatVec3(euler)}`);\n    }\n  }\n\n  // Transform: scale\n  if (node.scale) {\n    const isUniform = node.scale[0] === node.scale[1] && node.scale[1] === node.scale[2];\n    const isDefault = isUniform && node.scale[0] === 1;\n    if (!isDefault) {\n      lines.push(`${innerPad}scale: ${formatVec3(node.scale)}`);\n    }\n  }\n\n  // Material properties\n  for (const prop of materialProps) {\n    lines.push(`${innerPad}${prop}`);\n  }\n\n  // Animation clips\n  if (animClips.length > 0) {\n    if (animClips.length === 1) {\n      lines.push(`${innerPad}animation_clip: \"${animClips[0]}\"`);\n    } else {\n      const clipsStr = animClips.map((c) => `\"${c}\"`).join(', ');\n      lines.push(`${innerPad}animation_clips: [${clipsStr}]`);\n    }\n  }\n\n  // Physics parameters from extensions\n  for (const param of physicsParams) {\n    lines.push(`${innerPad}${param}`);\n  }\n\n  // Custom extras as comments\n  if (node.extras) {\n    const extrasKeys = Object.keys(node.extras).filter((k) => k !== 'holoscript_traits');\n    if (extrasKeys.length > 0) {\n      lines.push(`${innerPad}// Custom properties from glTF extras:`);\n      for (const key of extrasKeys) {\n        const value = node.extras[key];\n        if (typeof value === 'string') {\n          lines.push(`${innerPad}// ${key}: \"${value}\"`);\n        } else {\n          lines.push(`${innerPad}// ${key}: ${JSON.stringify(value)}`);\n        }\n      }\n    }\n  }\n\n  // Recursively process child nodes\n  if (node.children && node.children.length > 0) {\n    lines.push('');\n    for (const childIdx of node.children) {\n      const childBlock = nodeToHolo(childIdx, gltf, inputPath, indent + 1, meshShapeNames);\n      if (childBlock) {\n        lines.push(childBlock);\n      }\n    }\n  }\n\n  lines.push(`${pad}}`);\n\n  return lines.join('\\n');\n}\n\n// ---------------------------------------------------------------------------\n// Scene Composition Builder\n// ---------------------------------------------------------------------------\n\n/**\n * Build the complete .holo composition string from parsed glTF data.\n */\nfunction buildHoloComposition(\n  gltf: GltfData,\n  inputPath: string,\n  meshShapeBlocks?: readonly string[],\n  meshShapeNames?: ReadonlyMap<number, string>,\n): string {\n  const lines: string[] = [];\n\n  // Header comment\n  const generator = gltf.asset.generator || 'unknown';\n  const gltfVersion = gltf.asset.version || '2.0';\n  const sourceFile = path.basename(inputPath);\n\n  lines.push(`// Imported from ${sourceFile}`);\n  lines.push(`// glTF ${gltfVersion} - Generator: ${generator}`);\n  if (gltf.asset.copyright) {\n    lines.push(`// Copyright: ${gltf.asset.copyright}`);\n  }\n  lines.push('');\n\n  // Determine scene name\n  const activeSceneIdx = gltf.scene ?? 0;\n  const scenes = gltf.scenes || [];\n  const activeScene = scenes[activeSceneIdx];\n  const sceneName = activeScene?.name || path.basename(inputPath, path.extname(inputPath));\n\n  lines.push(`composition \"${sceneName}\" {`);\n\n  // Environment block\n  lines.push('  environment {');\n  lines.push('    skybox: \"gradient\"');\n  lines.push('    ambient_light: 0.4');\n\n  // Check for global lighting extensions\n  const lightsExt = gltf.extensions?.['KHR_lights_punctual'] as KhrLightsPunctualExt | undefined;\n  if (lightsExt?.lights) {\n    const directionalLight = lightsExt.lights.find((l) => l.type === 'directional');\n    if (directionalLight) {\n      const color = directionalLight.color || [1, 1, 1];\n      const intensity = directionalLight.intensity ?? 1;\n      lines.push(`    directional_light_color: \"${rgbToHex(color[0], color[1], color[2])}\"`);\n      lines.push(`    directional_light_intensity: ${Math.round(intensity * 100) / 100}`);\n    }\n  }\n\n  lines.push('  }');\n  lines.push('');\n\n  // Get root nodes from the active scene\n  const rootNodes = activeScene?.nodes || [];\n\n  if (rootNodes.length === 0 && gltf.nodes && gltf.nodes.length > 0) {\n    // No scene defined; treat all parentless nodes as roots\n    const childSet = new Set<number>();\n    for (const node of gltf.nodes) {\n      if (node.children) {\n        for (const childIdx of node.children) {\n          childSet.add(childIdx);\n        }\n      }\n    }\n    for (let i = 0; i < gltf.nodes.length; i++) {\n      if (!childSet.has(i)) {\n        rootNodes.push(i);\n      }\n    }\n  }\n\n  // Wrap root nodes in a spatial_group\n  lines.push('  spatial_group \"Root\" {');\n\n  for (const nodeIdx of rootNodes) {\n    const block = nodeToHolo(nodeIdx, gltf, inputPath, 2, meshShapeNames);\n    if (block) {\n      lines.push(block);\n      lines.push('');\n    }\n  }\n\n  lines.push('  }');\n\n  // Animation summary as a comment block\n  if (gltf.animations && gltf.animations.length > 0) {\n    lines.push('');\n    lines.push('  // --- Animations ---');\n    for (let i = 0; i < gltf.animations.length; i++) {\n      const anim = gltf.animations[i];\n      const animName = anim.name || `animation_${i}`;\n      const targetNodes = new Set<number>();\n      for (const ch of anim.channels) {\n        if (ch.target.node !== undefined) {\n          targetNodes.add(ch.target.node);\n        }\n      }\n      const targetNames = [...targetNodes].map((idx) => {\n        if (gltf.nodes && gltf.nodes[idx]) {\n          return gltf.nodes[idx].name || `node_${idx}`;\n        }\n        return `node_${idx}`;\n      });\n      lines.push(`  // \"${animName}\" -> targets: ${targetNames.join(', ')}`);\n    }\n  }\n\n  // Track 0: real imported mesh(es) carried as shape blocks INSIDE the composition.\n  if (meshShapeBlocks) {\n    for (const block of meshShapeBlocks) {\n      lines.push('');\n      lines.push(block);\n    }\n  }\n\n  lines.push('}');\n  lines.push('');\n\n  return lines.join('\\n');\n}\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\n/**\n * Import a glTF or GLB file and return the generated .holo composition code\n * as a string.\n *\n * @param inputPath - Absolute or relative path to a .gltf or .glb file.\n * @returns The .holo composition code string.\n *\n * @throws If the file cannot be read or parsed.\n *\n * @example\n * ```ts\n * import { importGltf } from './importers/gltf-importer';\n *\n * const holoCode = importGltf('./scene.glb');\n * console.log(holoCode);\n * ```\n */\nexport function importGltf(inputPath: string): string {\n  const resolvedPath = path.resolve(inputPath);\n\n  if (!fs.existsSync(resolvedPath)) {\n    throw new Error(`File not found: ${resolvedPath}`);\n  }\n\n  const ext = path.extname(resolvedPath).toLowerCase();\n  let gltfData: GltfData;\n  let meshShapeBlocks: string[] | undefined;\n  let meshShapeNames: Map<number, string> | undefined;\n\n  if (ext === '.glb') {\n    const buffer = fs.readFileSync(resolvedPath);\n    gltfData = parseGlb(buffer);\n    const ab = buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength);\n    // Track 0: carry the REAL mesh in `.holo`. For EACH glTF mesh, prefer the\n    // skinned extractor (palette-remapped skin), fall back to the static one\n    // (rigid identity bind) for non-skinned meshes — the majority of\n    // environment/object assets. Each carried mesh becomes its own\n    // `shape \"<name>\" mesh { … }` block, and the node→shape link is recorded by\n    // glTF mesh index so every mesh node references its OWN surface (multi-mesh\n    // GLBs included). A mesh neither extractor can read (Draco/meshopt that\n    // wasn't decompressed, or no POSITION) keeps the legacy text pointer.\n    const base = path.basename(resolvedPath, ext);\n    const meshCount = gltfData.meshes?.length ?? 0;\n    const blocks: string[] = [];\n    const names = new Map<number, string>();\n    // Single container parse; each carryable mesh (skinned or static) comes back\n    // keyed by its glTF mesh index. Unreadable meshes are simply absent here.\n    for (const { meshIndex, mesh } of CharacterRender.extractGltfMeshes(ab)) {\n      // Single mesh keeps the bare `<base>_mesh` name (back-compat); multi-mesh\n      // disambiguates per glTF mesh index.\n      const meshName = meshCount === 1 ? `${base}_mesh` : `${base}_mesh${meshIndex}`;\n      blocks.push(meshShapeToHolo(meshName, encodeSkinnedMeshToHolo(mesh)));\n      names.set(meshIndex, meshName);\n    }\n    if (blocks.length > 0) {\n      meshShapeBlocks = blocks;\n      meshShapeNames = names;\n    }\n  } else if (ext === '.gltf') {\n    const rawJson = fs.readFileSync(resolvedPath, 'utf8');\n    try {\n      gltfData = JSON.parse(rawJson) as GltfData;\n    } catch (e) {\n      throw new Error(`Failed to parse glTF JSON from ${resolvedPath}: ${(e as Error).message}`);\n    }\n  } else {\n    throw new Error(`Unsupported file extension \"${ext}\". Expected \".gltf\" or \".glb\".`);\n  }\n\n  // Validate minimal glTF structure\n  if (!gltfData.asset || !gltfData.asset.version) {\n    throw new Error('Invalid glTF: missing required \"asset.version\" field.');\n  }\n\n  return buildHoloComposition(gltfData, resolvedPath, meshShapeBlocks, meshShapeNames);\n}\n\n/**\n * Import a glTF or GLB file and write the generated .holo composition code\n * to an output file.\n *\n * @param inputPath  - Path to the source .gltf or .glb file.\n * @param outputPath - Path where the .holo file will be written.\n *\n * @throws If the input file cannot be read/parsed or the output cannot be written.\n *\n * @example\n * ```ts\n * import { importGltfToFile } from './importers/gltf-importer';\n *\n * importGltfToFile('./scene.glb', './scene.holo');\n * console.log('Conversion complete!');\n * ```\n */\nexport function importGltfToFile(inputPath: string, outputPath: string): void {\n  const holoCode = importGltf(inputPath);\n\n  const resolvedOutput = path.resolve(outputPath);\n  const outputDir = path.dirname(resolvedOutput);\n\n  if (!fs.existsSync(outputDir)) {\n    fs.mkdirSync(outputDir, { recursive: true });\n  }\n\n  fs.writeFileSync(resolvedOutput, holoCode, 'utf8');\n}\n","/**\n * HoloScript VR Traits Documentation\n *\n * Complete reference for bundled VR traits available in HoloScript.\n * Used by CLI for `holoscript traits` command.\n */\n\nexport interface TraitInfo {\n  name: string;\n  category:\n    | 'interaction'\n    | 'physics'\n    | 'visual'\n    | 'networking'\n    | 'behavior'\n    | 'spatial'\n    | 'audio'\n    | 'state'\n    | 'industrial';\n  description: string;\n  params?: Record<string, string>;\n  example: string;\n  requiresTraits?: string[];\n}\n\n/**\n * Bundled VR Traits organized by category\n */\nexport const TRAITS: Record<string, TraitInfo> = {\n  // =====================================================\n  // INTERACTION TRAITS (8)\n  // =====================================================\n  grabbable: {\n    name: 'grabbable',\n    category: 'interaction',\n    description:\n      'Makes object grabbable by VR controllers or hand tracking. Essential for interactive objects.',\n    params: {\n      snap_to_hand: 'If true, object snaps to hand position when grabbed (default: false)',\n      two_handed: 'Requires both hands to grab (default: false)',\n      grab_distance: 'Maximum distance from which object can be grabbed (default: 1.0)',\n    },\n    example: `orb sword {\n  @grabbable(snap_to_hand: true)\n  position: [0, 1, 0]\n}`,\n  },\n  throwable: {\n    name: 'throwable',\n    category: 'interaction',\n    description: 'Allows grabbed object to be thrown with physics. Requires @grabbable.',\n    params: {\n      velocity_multiplier: 'Multiplier for throw velocity (default: 1.0)',\n      bounce: 'If true, object bounces on collision (default: false)',\n      max_velocity: 'Maximum throw speed (default: 50)',\n    },\n    example: `orb ball {\n  @grabbable\n  @throwable(velocity_multiplier: 1.5, bounce: true)\n}`,\n    requiresTraits: ['grabbable'],\n  },\n  holdable: {\n    name: 'holdable',\n    category: 'interaction',\n    description: 'Object can be held and used while grabbed. For tools, weapons, etc.',\n    params: {\n      use_action: 'Action to trigger on use (trigger press)',\n      hold_position: 'Offset from hand when held',\n    },\n    example: `orb flashlight {\n  @grabbable\n  @holdable(use_action: toggle_light)\n}`,\n    requiresTraits: ['grabbable'],\n  },\n  clickable: {\n    name: 'clickable',\n    category: 'interaction',\n    description: 'Object responds to click/point interaction.',\n    params: {\n      on_click: 'Handler function to call',\n      highlight_on_hover: 'Visual feedback on hover (default: true)',\n    },\n    example: `orb button {\n  @clickable(on_click: handleClick)\n  color: \"#ff0000\"\n}`,\n  },\n  hoverable: {\n    name: 'hoverable',\n    category: 'interaction',\n    description: 'Triggers events when pointer hovers over object.',\n    params: {\n      on_enter: 'Handler for hover start',\n      on_exit: 'Handler for hover end',\n      highlight_color: 'Color to apply on hover',\n    },\n    example: `orb info_panel {\n  @hoverable(on_enter: showInfo, on_exit: hideInfo)\n}`,\n  },\n  draggable: {\n    name: 'draggable',\n    category: 'interaction',\n    description: 'Object can be dragged along a surface or axis.',\n    params: {\n      axis: 'Constrain to axis: \"x\", \"y\", \"z\", \"xy\", \"xz\", \"yz\", or \"free\"',\n      bounds: 'Min/max bounds for dragging',\n    },\n    example: `orb slider {\n  @draggable(axis: \"x\", bounds: [-5, 5])\n}`,\n  },\n  selectable: {\n    name: 'selectable',\n    category: 'interaction',\n    description: 'Object can be selected/deselected as part of a selection group.',\n    params: {\n      group: 'Selection group name for mutual exclusion',\n      on_select: 'Handler for selection',\n    },\n    example: `orb option_a {\n  @selectable(group: \"choices\", on_select: chooseA)\n}`,\n  },\n  focusable: {\n    name: 'focusable',\n    category: 'interaction',\n    description: 'Object can receive focus for keyboard/controller input.',\n    params: {\n      tab_index: 'Order in focus navigation',\n      on_focus: 'Handler for focus gained',\n    },\n    example: `orb input_field {\n  @focusable(tab_index: 1)\n}`,\n  },\n\n  // =====================================================\n  // PHYSICS TRAITS (6)\n  // =====================================================\n  collidable: {\n    name: 'collidable',\n    category: 'physics',\n    description: 'Enables collision detection. Objects will physically interact.',\n    params: {\n      layer: 'Collision layer for filtering (e.g., \"player\", \"enemy\", \"terrain\")',\n      trigger: 'If true, triggers events but no physical collision (default: false)',\n    },\n    example: `orb wall {\n  @collidable(layer: \"solid\")\n  scale: [10, 3, 0.5]\n}`,\n  },\n  physics: {\n    name: 'physics',\n    category: 'physics',\n    description: 'Full physics simulation with gravity and forces.',\n    params: {\n      mass: 'Object mass in kg (default: 1)',\n      friction: 'Surface friction coefficient (default: 0.5)',\n      restitution: 'Bounciness 0-1 (default: 0.3)',\n    },\n    example: `orb crate {\n  @physics(mass: 10, restitution: 0.2)\n  @collidable\n}`,\n  },\n  rigid: {\n    name: 'rigid',\n    category: 'physics',\n    description: 'Rigid body physics - object responds to forces but maintains shape.',\n    params: {\n      angular_damping: 'Rotation slowdown (default: 0.1)',\n      linear_damping: 'Movement slowdown (default: 0.1)',\n    },\n    example: `orb bowling_ball {\n  @rigid(angular_damping: 0.05)\n  @physics(mass: 5)\n}`,\n  },\n  kinematic: {\n    name: 'kinematic',\n    category: 'physics',\n    description: 'Object moves via code but affects physics objects. Not affected by forces.',\n    example: `orb moving_platform {\n  @kinematic\n  @collidable\n}`,\n  },\n  trigger: {\n    name: 'trigger',\n    category: 'physics',\n    description: 'Collision zone that triggers events without physical collision.',\n    params: {\n      on_enter: 'Handler when object enters',\n      on_exit: 'Handler when object exits',\n      filter_layer: 'Only trigger for specific layers',\n    },\n    example: `orb checkpoint {\n  @trigger(on_enter: saveProgress)\n  scale: [5, 5, 5]\n}`,\n  },\n  gravity: {\n    name: 'gravity',\n    category: 'physics',\n    description: 'Custom gravity settings for this object.',\n    params: {\n      strength: 'Gravity multiplier (default: 1)',\n      direction: 'Custom gravity direction [x, y, z]',\n    },\n    example: `orb moon_rock {\n  @gravity(strength: 0.16)\n  @physics\n}`,\n  },\n\n  // =====================================================\n  // VISUAL TRAITS (8)\n  // =====================================================\n  glowing: {\n    name: 'glowing',\n    category: 'visual',\n    description: 'Object emits a glow effect.',\n    params: {\n      color: 'Glow color (default: object color)',\n      intensity: 'Glow brightness (default: 1)',\n      radius: 'Glow spread distance (default: 0.5)',\n    },\n    example: `orb magic_orb {\n  @glowing(color: \"#00ffff\", intensity: 2)\n  color: \"#0088ff\"\n}`,\n  },\n  emissive: {\n    name: 'emissive',\n    category: 'visual',\n    description: 'Object appears to emit light (affects scene lighting).',\n    params: {\n      color: 'Emission color',\n      power: 'Light power in watts (default: 10)',\n    },\n    example: `orb lamp {\n  @emissive(color: \"#ffffcc\", power: 50)\n}`,\n  },\n  transparent: {\n    name: 'transparent',\n    category: 'visual',\n    description: 'Object has transparency.',\n    params: {\n      opacity: 'Opacity 0-1 (default: 0.5)',\n      mode: '\"blend\", \"additive\", or \"multiply\"',\n    },\n    example: `orb ghost {\n  @transparent(opacity: 0.3)\n  color: \"#ffffff\"\n}`,\n  },\n  reflective: {\n    name: 'reflective',\n    category: 'visual',\n    description: 'Object has reflective surface.',\n    params: {\n      roughness: 'Surface roughness 0-1 (default: 0.1)',\n      metalness: 'Metal-like appearance 0-1 (default: 0.9)',\n    },\n    example: `orb mirror_ball {\n  @reflective(roughness: 0, metalness: 1)\n}`,\n  },\n  animated: {\n    name: 'animated',\n    category: 'visual',\n    description: 'Object plays animations from model.',\n    params: {\n      clip: 'Animation clip name',\n      loop: 'Loop animation (default: true)',\n      speed: 'Playback speed multiplier (default: 1)',\n    },\n    example: `orb character {\n  @animated(clip: \"idle\", loop: true)\n  model: \"character.glb\"\n}`,\n  },\n  billboard: {\n    name: 'billboard',\n    category: 'visual',\n    description: 'Object always faces the camera/player.',\n    params: {\n      axis: 'Lock rotation axis: \"y\", \"full\", or \"none\"',\n    },\n    example: `orb npc_name {\n  @billboard(axis: \"y\")\n  text: \"Shopkeeper\"\n}`,\n  },\n  outline: {\n    name: 'outline',\n    category: 'visual',\n    description: 'Renders an outline around the object.',\n    params: {\n      color: 'Outline color',\n      thickness: 'Outline thickness (default: 2)',\n    },\n    example: `orb selected_item {\n  @outline(color: \"#ffff00\", thickness: 3)\n}`,\n  },\n  particle_emitter: {\n    name: 'particle_emitter',\n    category: 'visual',\n    description: 'Object emits particles.',\n    params: {\n      type: 'Particle preset: \"fire\", \"smoke\", \"sparkle\", \"rain\", \"snow\"',\n      rate: 'Particles per second (default: 10)',\n      lifetime: 'Particle lifetime in seconds (default: 2)',\n    },\n    example: `orb torch {\n  @particle_emitter(type: \"fire\", rate: 50)\n}`,\n  },\n\n  // =====================================================\n  // NETWORKING TRAITS (5)\n  // =====================================================\n  networked: {\n    name: 'networked',\n    category: 'networking',\n    description: 'Object state is synchronized across all connected clients.',\n    params: {\n      sync_rate: 'Updates per second (default: 20)',\n      interpolation: 'Smooth movement between updates (default: true)',\n    },\n    example: `orb shared_ball {\n  @networked(sync_rate: 30)\n  @grabbable\n}`,\n  },\n  synced: {\n    name: 'synced',\n    category: 'networking',\n    description: 'Specific properties are synced across network.',\n    params: {\n      properties: 'Array of property names to sync',\n    },\n    example: `orb scoreboard {\n  @synced(properties: [\"score\", \"player_name\"])\n  state { score: 0 }\n}`,\n  },\n  persistent: {\n    name: 'persistent',\n    category: 'networking',\n    description: 'Object state persists across sessions (saved to server).',\n    params: {\n      save_interval: 'Seconds between auto-saves (default: 30)',\n    },\n    example: `orb player_house {\n  @persistent(save_interval: 60)\n}`,\n  },\n  owned: {\n    name: 'owned',\n    category: 'networking',\n    description: 'Object has a specific owner who has authority.',\n    params: {\n      transfer_on_grab: 'Ownership transfers when grabbed (default: true)',\n    },\n    example: `orb player_weapon {\n  @owned(transfer_on_grab: true)\n  @grabbable\n}`,\n  },\n  host_only: {\n    name: 'host_only',\n    category: 'networking',\n    description: 'Object only exists on host/server, not synced to clients.',\n    example: `orb game_manager {\n  @host_only\n  state { game_phase: \"waiting\" }\n}`,\n  },\n\n  // =====================================================\n  // BEHAVIOR TRAITS (6)\n  // =====================================================\n  stackable: {\n    name: 'stackable',\n    category: 'behavior',\n    description: 'Objects can stack on top of each other.',\n    params: {\n      max_stack: 'Maximum items in stack (default: 64)',\n      stack_offset: 'Vertical offset per item',\n    },\n    example: `orb coin {\n  @stackable(max_stack: 100)\n  @grabbable\n}`,\n  },\n  attachable: {\n    name: 'attachable',\n    category: 'behavior',\n    description: 'Object can attach to other objects or surfaces.',\n    params: {\n      attach_to: 'Types of objects/surfaces to attach to',\n      snap_points: 'Defined attachment points',\n    },\n    example: `orb magnet {\n  @attachable(attach_to: [\"metal\"])\n}`,\n  },\n  equippable: {\n    name: 'equippable',\n    category: 'behavior',\n    description: 'Object can be equipped to a slot (hand, head, body, etc).',\n    params: {\n      slot: 'Equipment slot: \"left_hand\", \"right_hand\", \"head\", \"body\"',\n      on_equip: 'Handler when equipped',\n    },\n    example: `orb helmet {\n  @equippable(slot: \"head\", on_equip: applyArmor)\n}`,\n  },\n  consumable: {\n    name: 'consumable',\n    category: 'behavior',\n    description: 'Object can be consumed/used up.',\n    params: {\n      uses: 'Number of uses before consumed (default: 1)',\n      on_consume: 'Handler when consumed',\n    },\n    example: `orb potion {\n  @consumable(uses: 1, on_consume: heal)\n  @grabbable\n}`,\n  },\n  destructible: {\n    name: 'destructible',\n    category: 'behavior',\n    description: 'Object can be destroyed, optionally spawning debris.',\n    params: {\n      health: 'Hit points (default: 100)',\n      debris: 'Model to spawn as debris',\n      on_destroy: 'Handler when destroyed',\n    },\n    example: `orb crate {\n  @destructible(health: 50, debris: \"crate_debris.glb\")\n  @collidable\n}`,\n  },\n  spawner: {\n    name: 'spawner',\n    category: 'behavior',\n    description: 'Object spawns other objects periodically.',\n    params: {\n      template: 'Template name to spawn',\n      interval: 'Seconds between spawns',\n      max_spawned: 'Maximum active spawned objects',\n    },\n    example: `orb enemy_spawner {\n  @spawner(template: \"Goblin\", interval: 30, max_spawned: 5)\n}`,\n  },\n\n  // =====================================================\n  // SPATIAL TRAITS (7)\n  // =====================================================\n  anchor: {\n    name: 'anchor',\n    category: 'spatial',\n    description: 'Object is anchored to real-world position (AR).',\n    params: {\n      type: '\"plane\", \"image\", \"face\", or \"world\"',\n      persist: 'Save anchor across sessions (default: false)',\n    },\n    example: `orb ar_decoration {\n  @anchor(type: \"plane\", persist: true)\n}`,\n  },\n  tracked: {\n    name: 'tracked',\n    category: 'spatial',\n    description: 'Object follows a tracked target (controller, hand, etc).',\n    params: {\n      target: '\"left_hand\", \"right_hand\", \"head\", \"controller\"',\n      offset: 'Position offset from target',\n    },\n    example: `orb wrist_menu {\n  @tracked(target: \"left_hand\", offset: [0, 0.1, 0])\n}`,\n  },\n  world_locked: {\n    name: 'world_locked',\n    category: 'spatial',\n    description: 'Object stays fixed in world space regardless of user movement.',\n    example: `orb compass {\n  @world_locked\n  position: [0, 100, 0]\n}`,\n  },\n  hand_tracked: {\n    name: 'hand_tracked',\n    category: 'spatial',\n    description: 'Object responds to hand tracking gestures.',\n    params: {\n      gestures: 'Array of recognized gestures',\n      on_gesture: 'Handler for gesture events',\n    },\n    example: `orb magic_effect {\n  @hand_tracked(gestures: [\"pinch\", \"point\", \"fist\"])\n}`,\n  },\n  eye_tracked: {\n    name: 'eye_tracked',\n    category: 'spatial',\n    description: 'Object responds to eye tracking (gaze).',\n    params: {\n      dwell_time: 'Seconds of gaze to trigger action',\n      on_gaze: 'Handler for gaze events',\n    },\n    example: `orb gaze_button {\n  @eye_tracked(dwell_time: 1.5, on_gaze: activate)\n}`,\n  },\n  bounds: {\n    name: 'bounds',\n    category: 'spatial',\n    description: 'Object defines a boundary region.',\n    params: {\n      shape: '\"box\", \"sphere\", or \"custom\"',\n      on_exit: 'Handler when player exits bounds',\n    },\n    example: `orb play_area {\n  @bounds(shape: \"box\", on_exit: warnPlayer)\n  scale: [10, 5, 10]\n}`,\n  },\n  portal: {\n    name: 'portal',\n    category: 'spatial',\n    description: 'Object acts as a portal to another location or world.',\n    params: {\n      destination: 'Target position, world ID, or URL',\n      preview: 'Show preview of destination (default: true)',\n    },\n    example: `orb world_gate {\n  @portal(destination: \"world://dungeon\", preview: true)\n}`,\n  },\n\n  // =====================================================\n  // AUDIO TRAITS (4)\n  // =====================================================\n  spatial_audio: {\n    name: 'spatial_audio',\n    category: 'audio',\n    description: 'Object emits 3D positional audio.',\n    params: {\n      source: 'Audio file or stream URL',\n      volume: 'Volume 0-1 (default: 1)',\n      range: 'Maximum hearing distance (default: 10)',\n      loop: 'Loop audio (default: false)',\n    },\n    example: `orb radio {\n  @spatial_audio(source: \"music.mp3\", loop: true, range: 20)\n}`,\n  },\n  ambient: {\n    name: 'ambient',\n    category: 'audio',\n    description: 'Object contributes to ambient soundscape.',\n    params: {\n      sound: 'Ambient sound type or file',\n      blend_radius: 'Distance for volume blending',\n    },\n    example: `orb forest_zone {\n  @ambient(sound: \"forest_birds.mp3\", blend_radius: 30)\n}`,\n  },\n  voice_activated: {\n    name: 'voice_activated',\n    category: 'audio',\n    description: 'Object responds to voice commands.',\n    params: {\n      commands: 'Array of recognized voice commands',\n      on_command: 'Handler for voice events',\n    },\n    example: `orb assistant {\n  @voice_activated(commands: [\"help\", \"inventory\", \"map\"])\n}`,\n  },\n  audio_reactive: {\n    name: 'audio_reactive',\n    category: 'audio',\n    description: 'Object reacts to audio input (music visualization).',\n    params: {\n      source: 'Audio source to react to',\n      property: 'Property to modulate (scale, color, etc)',\n    },\n    example: `orb visualizer {\n  @audio_reactive(source: \"microphone\", property: \"scale\")\n}`,\n  },\n\n  // =====================================================\n  // STATE TRAITS (5)\n  // =====================================================\n  state: {\n    name: 'state',\n    category: 'state',\n    description: 'Object has internal state that can be read/modified.',\n    example: `orb counter {\n  @state\n  state { count: 0, active: true }\n}`,\n  },\n  reactive: {\n    name: 'reactive',\n    category: 'state',\n    description: 'Object automatically updates when state changes.',\n    params: {\n      watch: 'Properties to watch for changes',\n    },\n    example: `orb health_bar {\n  @reactive(watch: [\"player.health\"])\n  state { width: 100 }\n}`,\n  },\n  observable: {\n    name: 'observable',\n    category: 'state',\n    description: 'Other objects can subscribe to state changes.',\n    example: `orb game_state {\n  @observable\n  state { level: 1, score: 0 }\n}`,\n  },\n  computed: {\n    name: 'computed',\n    category: 'state',\n    description: 'Object has computed properties derived from state.',\n    params: {\n      properties: 'Map of computed property definitions',\n    },\n    example: `orb stats {\n  @computed(properties: { total: \"attack + defense\" })\n  state { attack: 10, defense: 5 }\n}`,\n  },\n  timed: {\n    name: 'timed',\n    category: 'state',\n    description: 'Object has time-based state transitions.',\n    params: {\n      duration: 'Time in seconds for state change',\n      on_timeout: 'Handler when time expires',\n    },\n    example: `orb power_up {\n  @timed(duration: 10, on_timeout: expire)\n  state { active: true }\n}`,\n  },\n\n  // =====================================================\n  // INDUSTRIAL / IoT TRAITS (6)\n  // =====================================================\n  conveyor_belt: {\n    name: 'conveyor_belt',\n    category: 'industrial',\n    description: 'Animated conveyor belt that transports physics objects along a direction.',\n    params: {\n      speed: 'Belt speed in m/s (default: 1.0)',\n      direction: 'Transport axis: \"x\", \"y\", or \"z\" (default: \"x\")',\n    },\n    example: `object \"MainBelt\" {\n  @conveyor_belt(speed: 2, direction: \"x\")\n  @size(10, 0.5, 2)\n}`,\n  },\n  robot_arm: {\n    name: 'robot_arm',\n    category: 'industrial',\n    description: 'Articulated robotic arm with configurable degrees of freedom and reach.',\n    params: {\n      dof: 'Degrees of freedom / joints (default: 6)',\n      reach: 'Maximum reach in meters (default: 1.0)',\n    },\n    example: `object \"PickPlace\" {\n  @robot_arm(dof: 6, reach: 1.2)\n  @sensor(type: \"proximity\")\n}`,\n  },\n  safety_fence: {\n    name: 'safety_fence',\n    category: 'industrial',\n    description: 'Safety barrier / fence for industrial exclusion zones.',\n    params: {\n      height: 'Fence height in meters (default: 2)',\n      color: 'Fence color hex (default: \"#ff6600\")',\n    },\n    example: `object \"Perimeter\" {\n  @safety_fence(height: 2.5, color: \"#ffcc00\")\n  @position(0, 0, 10)\n}`,\n  },\n  sensor: {\n    name: 'sensor',\n    category: 'industrial',\n    description: 'IoT sensor that emits telemetry data. Supports multiple sensor types.',\n    params: {\n      type: 'Sensor type: \"proximity\", \"temp\", \"pressure\", \"camera\", \"gas\", \"particle\", \"counter\", \"airflow\"',\n    },\n    example: `object \"TempProbe\" {\n  @sensor(type: \"temp\")\n  @real_time_data\n}`,\n  },\n  emergency_stop: {\n    name: 'emergency_stop',\n    category: 'industrial',\n    description: 'Emergency stop button that halts all equipment within a radius.',\n    params: {\n      radius: 'Effect radius in meters (default: 5)',\n    },\n    example: `object \"EStop\" {\n  @emergency_stop(radius: 10)\n  @interactive\n}`,\n  },\n  process_time: {\n    name: 'process_time',\n    category: 'industrial',\n    description: 'Processing time for a work station, used in throughput simulation.',\n    params: {\n      seconds: 'Processing time per item in seconds',\n    },\n    example: `object \"AssemblyStation\" {\n  @process_time(30)\n  @sensor(type: \"counter\")\n}`,\n  },\n};\n\n/**\n * Get traits by category\n */\nexport function getTraitsByCategory(category: TraitInfo['category']): TraitInfo[] {\n  return Object.values(TRAITS).filter((t) => t.category === category);\n}\n\n/**\n * Get all categories with counts\n */\nexport function getCategories(): Array<{ name: string; count: number }> {\n  const categories: Record<string, number> = {};\n  for (const trait of Object.values(TRAITS)) {\n    categories[trait.category] = (categories[trait.category] || 0) + 1;\n  }\n  return Object.entries(categories).map(([name, count]) => ({ name, count }));\n}\n\n/**\n * Format trait for CLI output\n */\nexport function formatTrait(trait: TraitInfo, verbose: boolean = false): string {\n  const lines: string[] = [];\n\n  lines.push(`\\x1b[36m@${trait.name}\\x1b[0m \\x1b[2m(${trait.category})\\x1b[0m`);\n  lines.push(`  ${trait.description}`);\n\n  if (verbose && trait.params) {\n    lines.push('  \\x1b[33mParameters:\\x1b[0m');\n    for (const [param, desc] of Object.entries(trait.params)) {\n      lines.push(`    ${param}: ${desc}`);\n    }\n  }\n\n  if (verbose && trait.requiresTraits) {\n    lines.push(`  \\x1b[33mRequires:\\x1b[0m ${trait.requiresTraits.map((t) => `@${t}`).join(', ')}`);\n  }\n\n  if (verbose) {\n    lines.push('  \\x1b[33mExample:\\x1b[0m');\n    lines.push(\n      trait.example\n        .split('\\n')\n        .map((l) => `    ${l}`)\n        .join('\\n')\n    );\n  }\n\n  return lines.join('\\n');\n}\n\n/**\n * Format all traits for CLI output\n */\nexport function formatAllTraits(verbose: boolean = false, json: boolean = false): string {\n  if (json) {\n    return JSON.stringify(TRAITS, null, 2);\n  }\n\n  const categories = getCategories();\n  const lines: string[] = [];\n\n  lines.push(`\\n\\x1b[1mHoloScript VR Traits\\x1b[0m (${Object.keys(TRAITS).length} total)\\n`);\n\n  for (const { name, count } of categories) {\n    lines.push(`\\x1b[1m${name.toUpperCase()}\\x1b[0m (${count})`);\n    const traits = getTraitsByCategory(name as TraitInfo['category']);\n    for (const trait of traits) {\n      lines.push(formatTrait(trait, verbose));\n    }\n    lines.push('');\n  }\n\n  return lines.join('\\n');\n}\n\n/**\n * Suggest traits based on object description\n */\nexport async function suggestTraits(description: string): Promise<TraitInfo[]> {\n  const desc = description.toLowerCase();\n  const suggested: TraitInfo[] = [];\n\n  // Try AI-assisted search if adapter available\n  try {\n    const frameworkAiModule = '@holoscript/framework/ai';\n    const { getDefaultAIAdapter } = await import(frameworkAiModule);\n    const adapter = getDefaultAIAdapter();\n\n    if (adapter && adapter.getEmbeddings) {\n      const { SemanticSearchService } = await import('@holoscript/core');\n      const traitList = Object.values(TRAITS);\n      const searchService = new SemanticSearchService(adapter, traitList);\n\n      await searchService.initialize();\n      const aiResults = await searchService.search(description, 5);\n\n      return aiResults.map((r: { item: TraitInfo }) => r.item);\n    }\n  } catch (e) {\n    console.warn(\n      `\\x1b[2m[AI Search Failed: ${(e as Error).message}. Falling back to keywords...]\\x1b[0m`\n    );\n  }\n\n  // Keyword matching (Fallback)\n  const keywords: Record<string, string[]> = {\n    grabbable: ['grab', 'pick up', 'hold', 'carry', 'interactive', 'hand'],\n    throwable: ['throw', 'toss', 'ball', 'projectile'],\n    physics: ['physics', 'fall', 'gravity', 'realistic', 'bounce'],\n    collidable: ['solid', 'wall', 'floor', 'collision', 'block'],\n    glowing: ['glow', 'shine', 'light', 'bright', 'luminous', 'magic'],\n    networked: ['multiplayer', 'sync', 'shared', 'network', 'online'],\n    clickable: ['click', 'button', 'press', 'interact'],\n    animated: ['animate', 'move', 'character', 'creature', 'npc'],\n    spatial_audio: ['sound', 'audio', 'music', 'speaker'],\n    transparent: ['transparent', 'glass', 'ghost', 'see-through'],\n    destructible: ['destroy', 'break', 'smash', 'health'],\n    equippable: ['equip', 'wear', 'weapon', 'armor', 'tool'],\n    consumable: ['consume', 'eat', 'drink', 'potion', 'health'],\n    portal: ['portal', 'teleport', 'door', 'gate', 'travel'],\n    conveyor_belt: ['conveyor', 'belt', 'transport', 'assembly line', 'production line'],\n    robot_arm: ['robot', 'arm', 'pick and place', 'articulated', 'manipulator'],\n    safety_fence: ['fence', 'barrier', 'safety', 'exclusion', 'perimeter'],\n    sensor: ['sensor', 'iot', 'telemetry', 'monitor', 'detector', 'probe'],\n    emergency_stop: ['emergency', 'stop', 'e-stop', 'halt', 'shutdown'],\n    process_time: ['process', 'throughput', 'station', 'manufacturing', 'production'],\n  };\n\n  for (const [traitName, words] of Object.entries(keywords)) {\n    if (words.some((word) => desc.includes(word))) {\n      if (TRAITS[traitName]) {\n        suggested.push(TRAITS[traitName]);\n      }\n    }\n  }\n\n  // Common combinations\n  if (suggested.some((t) => t.name === 'grabbable')) {\n    if (!suggested.some((t) => t.name === 'collidable')) {\n      suggested.push(TRAITS.collidable);\n    }\n  }\n\n  if (suggested.some((t) => t.name === 'physics')) {\n    if (!suggested.some((t) => t.name === 'collidable')) {\n      suggested.push(TRAITS.collidable);\n    }\n  }\n\n  return suggested;\n}\n","/**\n * Text-to-3D Importer\n *\n * Converts text descriptions into .holo files by:\n * 1. Calling a text-to-3D provider (Meshy or Tripo) to generate a glTF model\n * 2. Running the glTF importer to convert to .holo\n * 3. Using trait suggestion from description keywords\n * 4. Merging inferred traits from both model metadata + NLP\n *\n * Environment: MESHY_API_KEY and/or TRIPO_API_KEY\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { importGltf } from './gltf-importer';\nimport { suggestTraits } from '../traits';\n\n// =============================================================================\n// Provider Interface\n// =============================================================================\n\nexport interface TextTo3DResult {\n  modelUrl: string;\n  format: 'glb' | 'gltf' | 'fbx' | 'obj';\n  metadata: {\n    provider: string;\n    jobId: string;\n    description: string;\n    generationTimeMs: number;\n    thumbnailUrl?: string;\n  };\n}\n\nexport interface TextTo3DProvider {\n  name: string;\n  generateModel(\n    description: string,\n    opts?: {\n      style?: 'realistic' | 'cartoon' | 'low-poly' | 'pbr';\n      format?: 'glb' | 'gltf';\n    }\n  ): Promise<TextTo3DResult>;\n}\n\n// =============================================================================\n// Meshy Provider (meshy.ai)\n// =============================================================================\n\nexport class MeshyProvider implements TextTo3DProvider {\n  name = 'meshy';\n  private apiKey: string;\n  private baseUrl = 'https://api.meshy.ai/v2';\n\n  constructor(apiKey?: string) {\n    this.apiKey = apiKey || process.env.MESHY_API_KEY || '';\n    if (!this.apiKey) {\n      throw new Error('MESHY_API_KEY required. Set it in .env or pass to constructor.');\n    }\n  }\n\n  async generateModel(\n    description: string,\n    opts?: {\n      style?: 'realistic' | 'cartoon' | 'low-poly' | 'pbr';\n      format?: 'glb' | 'gltf';\n    }\n  ): Promise<TextTo3DResult> {\n    const start = Date.now();\n\n    // Step 1: Submit text-to-3D job\n    const submitResponse = await fetch(`${this.baseUrl}/text-to-3d`, {\n      method: 'POST',\n      headers: {\n        'Content-Type': 'application/json',\n        Authorization: `Bearer ${this.apiKey}`,\n      },\n      body: JSON.stringify({\n        mode: 'preview',\n        prompt: description,\n        art_style: opts?.style || 'pbr',\n        negative_prompt: 'low quality, blurry, distorted',\n      }),\n    });\n\n    if (!submitResponse.ok) {\n      const err = await submitResponse.text();\n      throw new Error(`Meshy submit failed (${submitResponse.status}): ${err}`);\n    }\n\n    const { result: jobId } = (await submitResponse.json()) as { result: string };\n\n    // Step 2: Poll for completion (max 5 minutes)\n    const maxPollMs = 300_000;\n    const pollInterval = 5_000;\n    let elapsed = 0;\n\n    while (elapsed < maxPollMs) {\n      await sleep(pollInterval);\n      elapsed += pollInterval;\n\n      const statusResponse = await fetch(`${this.baseUrl}/text-to-3d/${jobId}`, {\n        headers: { Authorization: `Bearer ${this.apiKey}` },\n      });\n\n      if (!statusResponse.ok) continue;\n\n      const job = (await statusResponse.json()) as {\n        status: string;\n        model_urls?: { glb?: string; gltf?: string };\n        thumbnail_url?: string;\n      };\n\n      if (job.status === 'SUCCEEDED' && job.model_urls) {\n        const format = opts?.format || 'glb';\n        const modelUrl = job.model_urls[format] || job.model_urls.glb || '';\n\n        return {\n          modelUrl,\n          format: format as 'glb' | 'gltf',\n          metadata: {\n            provider: 'meshy',\n            jobId,\n            description,\n            generationTimeMs: Date.now() - start,\n            thumbnailUrl: job.thumbnail_url,\n          },\n        };\n      }\n\n      if (job.status === 'FAILED') {\n        throw new Error(`Meshy job ${jobId} failed`);\n      }\n    }\n\n    throw new Error(`Meshy job ${jobId} timed out after ${maxPollMs / 1000}s`);\n  }\n}\n\n// =============================================================================\n// Tripo Provider (tripo3d.ai)\n// =============================================================================\n\nexport class TripoProvider implements TextTo3DProvider {\n  name = 'tripo';\n  private apiKey: string;\n  private baseUrl = 'https://api.tripo3d.ai/v2/openapi';\n\n  constructor(apiKey?: string) {\n    this.apiKey = apiKey || process.env.TRIPO_API_KEY || '';\n    if (!this.apiKey) {\n      throw new Error('TRIPO_API_KEY required. Set it in .env or pass to constructor.');\n    }\n  }\n\n  async generateModel(\n    description: string,\n    _opts?: {\n      style?: 'realistic' | 'cartoon' | 'low-poly' | 'pbr';\n      format?: 'glb' | 'gltf';\n    }\n  ): Promise<TextTo3DResult> {\n    const start = Date.now();\n\n    // Step 1: Submit task\n    const submitResponse = await fetch(`${this.baseUrl}/task`, {\n      method: 'POST',\n      headers: {\n        'Content-Type': 'application/json',\n        Authorization: `Bearer ${this.apiKey}`,\n      },\n      body: JSON.stringify({\n        type: 'text_to_model',\n        prompt: description,\n      }),\n    });\n\n    if (!submitResponse.ok) {\n      const err = await submitResponse.text();\n      throw new Error(`Tripo submit failed (${submitResponse.status}): ${err}`);\n    }\n\n    const { data } = (await submitResponse.json()) as { data: { task_id: string } };\n    const taskId = data.task_id;\n\n    // Step 2: Poll for completion\n    const maxPollMs = 300_000;\n    const pollInterval = 5_000;\n    let elapsed = 0;\n\n    while (elapsed < maxPollMs) {\n      await sleep(pollInterval);\n      elapsed += pollInterval;\n\n      const statusResponse = await fetch(`${this.baseUrl}/task/${taskId}`, {\n        headers: { Authorization: `Bearer ${this.apiKey}` },\n      });\n\n      if (!statusResponse.ok) continue;\n\n      const result = (await statusResponse.json()) as {\n        data: {\n          status: string;\n          output?: { model?: string };\n        };\n      };\n\n      if (result.data.status === 'success' && result.data.output?.model) {\n        return {\n          modelUrl: result.data.output.model,\n          format: 'glb',\n          metadata: {\n            provider: 'tripo',\n            jobId: taskId,\n            description,\n            generationTimeMs: Date.now() - start,\n          },\n        };\n      }\n\n      if (result.data.status === 'failed') {\n        throw new Error(`Tripo task ${taskId} failed`);\n      }\n    }\n\n    throw new Error(`Tripo task ${taskId} timed out after ${maxPollMs / 1000}s`);\n  }\n}\n\n// =============================================================================\n// Pipeline: Text -> 3D Model -> .holo\n// =============================================================================\n\nexport interface TextTo3DHoloOptions {\n  description: string;\n  provider: TextTo3DProvider;\n  outputDir?: string;\n  objectName?: string;\n  style?: 'realistic' | 'cartoon' | 'low-poly' | 'pbr';\n}\n\nexport interface TextTo3DHoloResult {\n  holoCode: string;\n  holoFilePath?: string;\n  modelFilePath: string;\n  traits: string[];\n  metadata: TextTo3DResult['metadata'];\n}\n\nexport async function textTo3DToHolo(opts: TextTo3DHoloOptions): Promise<TextTo3DHoloResult> {\n  const { description, provider, style } = opts;\n  const outputDir = opts.outputDir || process.cwd();\n  const objectName = opts.objectName || sanitizeName(description);\n\n  // Step 1: Generate 3D model from text\n\n  const result = await provider.generateModel(description, { style, format: 'glb' });\n\n  // Step 2: Download the model file\n\n  const modelFileName = `${objectName}.${result.format}`;\n  const modelFilePath = path.join(outputDir, modelFileName);\n\n  const modelResponse = await fetch(result.modelUrl);\n  if (!modelResponse.ok) {\n    throw new Error(`Failed to download model: ${modelResponse.status}`);\n  }\n  const modelBuffer = Buffer.from(await modelResponse.arrayBuffer());\n  fs.writeFileSync(modelFilePath, modelBuffer);\n\n  // Step 3: Run glTF importer to get base .holo code\n\n  let baseHolo: string;\n  try {\n    baseHolo = importGltf(modelFilePath);\n  } catch {\n    // If glTF import fails (e.g. complex model), generate minimal .holo\n    baseHolo = `composition \"${objectName}\" {\\n  object \"${objectName}\" {\\n    model: \"${modelFileName}\"\\n  }\\n}`;\n  }\n\n  // Step 4: Suggest traits from the text description\n\n  const suggestedTraits = await suggestTraits(description);\n  const traitNames = suggestedTraits.map((t: { name: string }) => t.name);\n\n  // Step 5: Merge traits into the .holo code\n  const holoCode = mergeTraitsIntoHolo(baseHolo, objectName, traitNames, modelFileName);\n\n  // Step 6: Optionally write .holo file\n  let holoFilePath: string | undefined;\n  if (outputDir) {\n    holoFilePath = path.join(outputDir, `${objectName}.holo`);\n    fs.writeFileSync(holoFilePath, holoCode, 'utf-8');\n  }\n\n  return {\n    holoCode,\n    holoFilePath,\n    modelFilePath,\n    traits: traitNames,\n    metadata: result.metadata,\n  };\n}\n\n// =============================================================================\n// Helpers\n// =============================================================================\n\nfunction sleep(ms: number): Promise<void> {\n  return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nfunction sanitizeName(description: string): string {\n  return (\n    description\n      .toLowerCase()\n      .replace(/[^a-z0-9]+/g, '_')\n      .replace(/^_|_$/g, '')\n      .slice(0, 40) || 'generated_object'\n  );\n}\n\nfunction mergeTraitsIntoHolo(\n  baseHolo: string,\n  objectName: string,\n  traits: string[],\n  modelFile: string\n): string {\n  if (traits.length === 0) return baseHolo;\n\n  const traitAnnotations = traits.map((t) => `@${t}`).join(' ');\n\n  // Try to inject traits into existing object declaration\n  const objectPattern = new RegExp(`(object\\\\s+\"${objectName}\")(\\\\s*\\\\{)`);\n  if (objectPattern.test(baseHolo)) {\n    return baseHolo.replace(objectPattern, `$1 ${traitAnnotations}$2`);\n  }\n\n  // Fallback: generate a fresh .holo with the traits and model reference\n  return `composition \"${objectName}\" {\n  object \"${objectName}\" ${traitAnnotations} {\n    model: \"${modelFile}\"\n  }\n}\n`;\n}\n","/**\n * MCP Tool Handlers for HoloScript\n *\n * Implements the logic for each MCP tool.\n * Dispatches to specialized handlers for graph, IDE, and Brittney-Lite tools.\n */\n\nimport {\n  HoloScriptPlusParser,\n  compilePipelineSourceToNode,\n  parseHolo,\n  parseHoloStrict,\n  parsePipeline,\n  VR_TRAITS,\n  buildKnownTraitSet,\n  createNativeAutoRigPlan,\n  type AutoRigPose,\n  type AutoRigRigType,\n  type NativeAutoRigPlan,\n} from '@holoscript/core';\nimport { validate_detailed as validateCanonicalHsDetailed } from '@holoscript/wasm/node';\n\nimport {\n  suggestUniversalTraits,\n  suggest2DTraits,\n  suggestTraits,\n  generateSemanticUIForMCP,\n  generateObjectForMCP,\n  generateSceneForMCP,\n} from './generators';\nimport { generateHololandDataset, datasetToJsonl, TrainingCategory } from './training-generators';\nimport { renderPreview, createShareLink } from './renderer';\nimport { handleEditHoloTool } from './edit-holo-tools';\nimport { TRAIT_DOCS, SYNTAX_DOCS, EXAMPLES } from './documentation';\nimport { EXAMPLE_CATALOG, EXAMPLE_INVENTORY, PUBLIC_LINK_POLICIES } from './examples-catalog';\nimport { handleCodebaseTool, handleGraphRagTool } from '@holoscript/absorb-service/mcp';\nimport { handleGraphTool } from './graph-tools';\nimport { handleIDETool } from './ide-tools';\nimport { handleBrittneyLiteTool } from './brittney-lite';\nimport { handleWisdomGotchaTool } from './wisdom-gotcha-tools';\nimport { PluginManager } from './PluginManager';\nimport { handleAbsorbProvenanceTool } from './absorb-provenance-tools';\nimport {\n  browserLaunch,\n  browserExecute,\n  browserScreenshot,\n  BrowserLaunchSchema,\n  BrowserExecuteSchema,\n  BrowserScreenshotSchema,\n} from './browser/browser-tools';\nimport {\n  buildToolManifest,\n  suggestToolsForGoal,\n  handleBatchToolCall,\n  handleToolingDiscoveryTool,\n} from './tooling-discovery-tools';\nimport { handleOracleConsult } from './oracle-handler';\nimport { handleOracleMcpTool } from './oracle-mcp-tools';\nimport { isHoloMapToolName, handleHoloMapTool } from './holomap-mcp-tools';\nimport { isSpatialMcpToolName, handleSpatialMcpTool } from './spatial-mcp-tools';\nimport { isNegotiationToolName, handleNegotiationTool } from './negotiation-mcp-tools';\nimport { isHologramToolName, handleHologramTool } from './hologram-mcp-tools';\nimport { isHoloTwinToolName, handleHoloTwinTool } from './holotwin-mcp-tools';\nimport { isHoloTuneToolName, handleHoloTuneTool } from './holotune-mcp-tools';\nimport { handleEstimateTaskDurationTool } from './tools/estimate_task_duration';\nimport { handleKolmogorovTaskScoreTool } from './tools/kolmogorov_task_score';\nimport { handleCriticTool } from './critic-handler';\nimport { handleFounderTool } from './founder-handler';\nimport { handleDaemonLifecycleTool } from './daemon-lifecycle-tools';\nimport { handlePremortemTool } from './premortem-handler';\nimport {\n  LEGACY_TRAIT_CATEGORY_ALIASES,\n  loadTraitCategoriesFromCore,\n  resolveTraitCategorySlug,\n} from './trait-categories-from-core';\nimport type { SigningContext } from './holomesh/identity/signing-middleware';\nimport { runForkSandboxGate, gateHoloScriptCode } from './security/fork-sandbox-gate';\nimport type { CapabilityManifest } from './security/sandbox-policy';\n\n/** Used only when core source tree is not present next to mcp-server (e.g. odd installs). */\nconst TRAIT_CATEGORIES_FALLBACK: Record<string, string[]> = {\n  interaction: [\n    '@grabbable',\n    '@throwable',\n    '@holdable',\n    '@clickable',\n    '@hoverable',\n    '@draggable',\n    '@pointable',\n    '@scalable',\n    '@rotatable',\n    '@snappable',\n  ],\n  physics: [\n    '@collidable',\n    '@physics',\n    '@rigid',\n    '@kinematic',\n    '@trigger',\n    '@gravity',\n    '@soft_body',\n    '@fluid',\n    '@magnetic',\n    '@buoyant',\n  ],\n  visual: [\n    '@glowing',\n    '@emissive',\n    '@transparent',\n    '@reflective',\n    '@animated',\n    '@billboard',\n    '@particle',\n    '@holographic',\n    '@volumetric',\n    '@shader_custom',\n  ],\n  networking: [\n    '@networked',\n    '@synced',\n    '@persistent',\n    '@owned',\n    '@host_only',\n    '@replicated',\n    '@authority',\n    '@interpolated',\n  ],\n  behavior: [\n    '@stackable',\n    '@attachable',\n    '@equippable',\n    '@consumable',\n    '@destructible',\n    '@breakable',\n    '@character',\n    '@npc',\n    '@pathfinding',\n    '@state_machine',\n  ],\n  spatial: [\n    '@anchor',\n    '@tracked',\n    '@world_locked',\n    '@hand_tracked',\n    '@eye_tracked',\n    '@plane_detected',\n    '@image_tracked',\n    '@face_tracked',\n  ],\n  audio: [\n    '@spatial_audio',\n    '@ambient',\n    '@voice_activated',\n    '@reverb',\n    '@doppler',\n    '@music',\n    '@procedural_audio',\n  ],\n  state: [\n    '@state',\n    '@reactive',\n    '@observable',\n    '@computed',\n    '@event_driven',\n    '@persistent_state',\n    '@replicated_state',\n  ],\n  ai: [\n    '@llm_agent',\n    '@npc',\n    '@crowd',\n    '@reactive',\n    '@pathfinding',\n    '@emotion',\n    '@dialogue',\n    '@decision_tree',\n  ],\n  accessibility: [\n    '@high_contrast',\n    '@screen_reader',\n    '@reduced_motion',\n    '@voice_nav',\n    '@colorblind_safe',\n    '@haptic_feedback',\n  ],\n  iot: ['@iot_sensor', '@digital_twin', '@mqtt_bridge', '@telemetry', '@actuator', '@stream_data'],\n  web3: [\n    '@nft_asset',\n    '@token_gated',\n    '@wallet_connected',\n    '@on_chain',\n    '@dao_governed',\n    '@smart_contract',\n  ],\n  advanced: [\n    '@teleport',\n    '@ui_panel',\n    '@particle_system',\n    '@weather',\n    '@day_night',\n    '@lod',\n    '@hand_tracking',\n    '@haptic',\n    '@portal',\n    '@mirror',\n    '@ray_traced',\n    '@compute_shader',\n    '@lod_managed',\n  ],\n  social: ['@shareable', '@collaborative', '@tweetable'],\n};\n\nfunction getTraitCategoryMap(): Record<string, string[]> {\n  const fromCore = loadTraitCategoriesFromCore();\n  if (Object.keys(fromCore).length > 0) {\n    const merged = { ...fromCore };\n    for (const [legacy, slug] of Object.entries(LEGACY_TRAIT_CATEGORY_ALIASES)) {\n      const traits = merged[slug];\n      if (traits) merged[legacy] = traits;\n    }\n    return merged;\n  }\n  return TRAIT_CATEGORIES_FALLBACK;\n}\n\nfunction asCapabilityManifest(value: unknown): CapabilityManifest | undefined {\n  if (!value || typeof value !== 'object') return undefined;\n  const candidate = value as Partial<CapabilityManifest>;\n  if (\n    (candidate.protocol === 'holomesh.tool_manifest.v1' ||\n      candidate.protocol === 'holoscript.capability.v1') &&\n    Array.isArray(candidate.declaredCapabilities)\n  ) {\n    return candidate as CapabilityManifest;\n  }\n  return undefined;\n}\n\nfunction validationFallbackCommand(args: Record<string, unknown>): {\n  command: string[];\n  commandPreview: string;\n  exact: boolean;\n  sourcePath: string;\n} {\n  const sourcePath =\n    typeof args.sourcePath === 'string'\n      ? args.sourcePath\n      : typeof args.filePath === 'string'\n        ? args.filePath\n        : '';\n  const target = sourcePath || '<local-holoscript-source>';\n  const command = ['pnpm', 'exec', 'holoscript', 'validate', target];\n  return {\n    command,\n    commandPreview: command.join(' '),\n    exact: Boolean(sourcePath),\n    sourcePath,\n  };\n}\n\nfunction validationUnavailableReceipt(\n  args: Record<string, unknown>,\n  gate:\n    | {\n        receipt?: { receiptId: string; failedCheck: string; reason: string };\n        appliedPolicy: { policyId: string };\n        checks: Array<{ name: string; passed: boolean; detail?: string }>;\n      }\n    | undefined\n) {\n  return {\n    schemaVersion: 'holoscript.validation-unavailable-receipt.v0.1.0',\n    kind: 'ValidationUnavailableReceipt',\n    generatedAt: new Date().toISOString(),\n    reason: gate?.receipt?.reason ?? 'Local validation was denied before parser execution.',\n    receiptId: gate?.receipt?.receiptId ?? '',\n    policyId: gate?.appliedPolicy.policyId ?? '',\n    failedCheck: gate?.receipt?.failedCheck ?? 'fork_sandbox_gate',\n    checks: gate?.checks ?? [],\n    localFallback: validationFallbackCommand(args),\n    capabilityManifestTemplate: {\n      protocol: 'holoscript.capability.v1',\n      declaredCapabilities: ['holoscript:validate', 'filesystem:read:local-source'],\n      attestation: {\n        manifestHash: '<sha256-of-canonical-manifest>',\n        signer: '<verified-signer>',\n        trustTier: 'verified',\n        attestedAt: '<iso8601>',\n      },\n    },\n  };\n}\n\n// All 1,800+ traits from @holoscript/core\nconst ALL_TRAITS: readonly string[] = VR_TRAITS;\n\n/**\n * Main handler dispatcher for all tools\n */\nexport async function handleTool(\n  name: string,\n  args: Record<string, unknown>,\n  signingCtx?: SigningContext,\n  // WS-1 (2026-07-02): optional override for the ForkSandboxGate subject source,\n  // defaulting to 'unknown' for every existing caller (zero behavior change).\n  // The ONLY intended caller of a non-default value is the new anonymous\n  // consumer-generation endpoint (http-server.ts POST /api/public/generate),\n  // which passes 'consumer' -- never set this from any other call site.\n  subjectSourceOverride?: import('./security/sandbox-policy').SandboxSubjectSource\n): Promise<unknown> {\n  // ── Fork Sandbox Gate (canary task_1778618757735_zpt5) ──────────────────────────\n  // Block forked/untrusted HoloScript code and sensitive tools before they\n  // can touch HoloLand worlds, robot/AI substrate, payments, or player state.\n  //\n  // Stdio transport design (see index.ts comment at line ~284): the stdio MCP\n  // transport is \"trusted local process\" and never carries HTTP auth headers,\n  // so signingCtx is always undefined there. Bridge: if the process has a\n  // valid HOLOSCRIPT_API_KEY in env (the same key that grants admin:* via the\n  // OAuth2 provider) synthesize admin:* scopes so the gate honours that trust.\n  // Explicit source overrides are externally-originated lanes and must not\n  // inherit the stdio-local admin bridge.\n  const allowLocalAdminBridge = !subjectSourceOverride && process.env['HOLOSCRIPT_API_KEY'];\n  const effectiveSigningCtx: SigningContext | undefined =\n    signingCtx ??\n    (allowLocalAdminBridge\n      ? {\n          signedRequest: false,\n          signingValid: true,\n          signer: 'stdio-local',\n          scopes: ['admin:*'],\n        }\n      : undefined);\n\n  const capabilityManifest = asCapabilityManifest(args.capabilityManifest ?? args.manifest);\n  const gateResult = await runForkSandboxGate(\n    {\n      kind: 'mcp_tool',\n      source: subjectSourceOverride ?? 'unknown',\n      subjectId: `mcp:${name}`,\n      payload: args,\n      manifest: capabilityManifest,\n    },\n    {\n      toolName: name,\n      grantedScopes: effectiveSigningCtx?.scopes ?? [],\n    }\n  );\n  if (!gateResult.allowed) {\n    return {\n      success: false,\n      error: `ForkSandboxGate denied tool \"${name}\": ${gateResult.receipt?.reason ?? 'policy violation'}`,\n      receiptId: gateResult.receipt?.receiptId,\n      policyId: gateResult.appliedPolicy.policyId,\n      checks: gateResult.checks,\n      ...(name === 'validate_holoscript'\n        ? { validationUnavailableReceipt: validationUnavailableReceipt(args, gateResult) }\n        : {}),\n    };\n  }\n\n  // For tools that ingest HoloScript code, additionally gate the code payload\n  const codePayload = args.code ?? args.content ?? args.holoscript ?? args.source;\n  if (typeof codePayload === 'string' && codePayload.length > 0) {\n    const codeGate = await gateHoloScriptCode(codePayload, {\n      source: 'unknown',\n      toolName: name,\n      grantedScopes: signingCtx?.scopes ?? [],\n      manifest: capabilityManifest,\n    });\n    if (!codeGate.allowed) {\n      return {\n        success: false,\n        error: `ForkSandboxGate denied HoloScript payload for \"${name}\": ${codeGate.receipt?.reason ?? 'policy violation'}`,\n        receiptId: codeGate.receipt?.receiptId,\n        policyId: codeGate.appliedPolicy.policyId,\n        checks: codeGate.checks,\n        ...(name === 'validate_holoscript'\n          ? { validationUnavailableReceipt: validationUnavailableReceipt(args, codeGate) }\n          : {}),\n      };\n    }\n  }\n\n  // Core tools\n  switch (name) {\n    case 'parse_hs':\n      return handleParseHs(args);\n    case 'parse_holo':\n      return handleParseHolo(args);\n    case 'parse_pipeline':\n      return handleParsePipeline(args);\n    case 'compile_pipeline':\n      return handleCompilePipeline(args);\n    case 'validate_holoscript':\n      return handleValidate(args);\n    case 'list_traits':\n      return handleListTraits(args);\n    case 'explain_trait':\n      return handleExplainTrait(args);\n    case 'suggest_traits':\n      return handleSuggestTraits(args);\n    case 'suggest_universal_traits':\n      return handleSuggestUniversalTraits(args);\n    case 'suggest_2d_traits':\n      return suggest2DTraits(args.description as string, args.context as string);\n    case 'generate_object':\n      return handleGenerateObject(args);\n    case 'generate_scene':\n      return handleGenerateScene(args);\n    case 'generate_semantic_ui': {\n      const desc = args.description;\n      if (typeof desc !== 'string' || !desc.trim()) {\n        throw new Error('generate_semantic_ui: description is required (non-empty string)');\n      }\n      return generateSemanticUIForMCP(desc, args);\n    }\n    case 'get_syntax_reference':\n      return handleGetSyntaxReference(args);\n    case 'get_examples':\n      return handleGetExamples(args);\n    case 'explain_code':\n      return handleExplainCode(args);\n    case 'analyze_code':\n      return handleAnalyzeCode(args);\n    case 'render_preview':\n      return handleRenderPreview(args);\n    case 'create_share_link':\n      return handleCreateShareLink(args);\n    case 'convert_format':\n      return handleConvertFormat(args);\n    case 'edit_holo': {\n      const result = await handleEditHoloTool(name, args);\n      if (result !== null) return result;\n      throw new Error(\n        `[edit_holo] Handler returned null for tool '${name}' with args: ${JSON.stringify(args).slice(0, 200)}. The edit_holo handler could not process this input — check that the .holo source is valid and the edit operation is supported.`\n      );\n    }\n\n    // Browser control tools\n    case 'browser_launch':\n      return browserLaunch(BrowserLaunchSchema.parse(args));\n    case 'browser_execute':\n      return browserExecute(BrowserExecuteSchema.parse(args));\n    case 'browser_screenshot':\n      return browserScreenshot(BrowserScreenshotSchema.parse(args));\n    case 'get_tool_manifest':\n    case 'suggest_tools_for_goal':\n    case 'batch_tool_call':\n    case 'get_tool_health': {\n      const { tools: allTools } = await import('./tools');\n      const result = await handleToolingDiscoveryTool(name, args, allTools, (toolName, toolArgs) =>\n        handleTool(toolName, toolArgs, signingCtx)\n      );\n      if (result !== null) return result;\n      break;\n    }\n    case 'holo_oracle_consult':\n      return handleOracleConsult(args);\n  }\n\n  // Advanced Oracle MCP tools (graduated from /oracle skill)\n  if (name.startsWith('holo_oracle_') && name !== 'holo_oracle_consult') {\n    const result = await handleOracleMcpTool(name, args);\n    if (result !== null) return result;\n  }\n\n  // Absorb provenance wrapper tool\n  if (name === 'absorb_provenance_answer') {\n    const result = await handleAbsorbProvenanceTool(name, args);\n    if (result !== null) return result;\n  }\n\n  // Protocol tools (HoloScript-as-Protocol) — must come before general holo_ prefix\n  if (name.startsWith('holo_protocol_')) {\n    const { handleProtocolTool } = await import('./protocol-tools');\n    return handleProtocolTool(name, args);\n  }\n\n  // Hologram Media Pipeline MCP tools (must run before generic holo_ graph routing)\n  if (isHologramToolName(name)) {\n    return handleHologramTool(name, args);\n  }\n\n  // HoloTwin IoT → Hologram pipeline tools\n  if (isHoloTwinToolName(name)) {\n    return handleHoloTwinTool(name, args);\n  }\n\n  // HoloTune sovereign per-agent fine-tune surface\n  if (isHoloTuneToolName(name)) {\n    return handleHoloTuneTool(name, args);\n  }\n\n  if (name === 'holo_estimate_task_duration') {\n    const result = await handleEstimateTaskDurationTool(name, args);\n    if (result !== null) return result;\n  }\n\n  if (name === 'holo_task_kolmogorov_score') {\n    const result = await handleKolmogorovTaskScoreTool(name, args);\n    if (result !== null) return result;\n  }\n\n  if (name === 'holo_critic') {\n    return handleCriticTool(args);\n  }\n\n  if (name === 'holo_founder') {\n    return handleFounderTool(args);\n  }\n\n  if (name === 'holo_premortem') {\n    return handlePremortemTool(args);\n  }\n\n  if (name.startsWith('holo_secrets_')) {\n    const { handleSecretsBrokerTool } = await import('./secrets-broker-handler');\n    const result = await handleSecretsBrokerTool(name, args, effectiveSigningCtx);\n    if (result !== null) return result;\n  }\n\n  if (name === 'holo_service_scaffold') {\n    const { handleObservabilityTool } = await import('./observability-tools');\n    return handleObservabilityTool(name, args);\n  }\n\n  // Codebase graph tools (absorb_repo/graph_status/query_codebase) and GraphRAG\n  // tools (semantic_search/ask_codebase) live in @holoscript/absorb-service.\n  // index.ts's O(1) TOOL_DISPATCH_REGISTRY routes these correctly for the real\n  // request path (registerCategory(codebaseTools, handleCodebaseTool) /\n  // registerCategory(graphRagTools, handleGraphRagTool)), but this standalone\n  // handleTool() function is also called directly by get_tool_health's probe\n  // (see tooling-discovery-tools.ts) and previously had no branch for these\n  // names, so they fell through to the holo_ catch-all below and threw\n  // \"Unknown graph tool\" from handleGraphTool's switch (task_1783009395572_q3ro,\n  // root-caused from task_1782886422455_jken). Mirror index.ts's wiring here so\n  // both dispatch paths agree.\n  if (\n    name === 'holo_absorb_repo' ||\n    name === 'holo_graph_status' ||\n    name === 'holo_query_codebase'\n  ) {\n    return handleCodebaseTool(name, args);\n  }\n\n  if (name === 'holo_semantic_search' || name === 'holo_ask_codebase') {\n    return handleGraphRagTool(name, args);\n  }\n\n  // All remaining holo_ tools go to the Graph tool handler\n  // (Oracle, Codebase, and Wisdom/Gotcha are now handled directly via the O(1) registry in index.ts)\n  if (name.startsWith('holo_')) {\n    return handleGraphTool(name, args);\n  }\n\n  // IDE tools (migrated from legacy HoloLand IDE tooling)\n  if (name.startsWith('hs_') && !name.startsWith('hs_ai_')) {\n    return handleIDETool(name, args);\n  }\n\n  // Brittney-Lite AI tools\n  if (name.startsWith('hs_ai_')) {\n    return handleBrittneyLiteTool(name, args);\n  }\n\n  // Text-to-3D pipeline\n  if (name === 'generate_3d_object') {\n    return handleGenerate3DObject(args);\n  }\n\n  // GPU fleet world rendering\n  if (name === 'render_world_on_fleet') {\n    const { handleWorldRenderTool } = await import('./world-render-tools');\n    return handleWorldRenderTool(name, args);\n  }\n\n  // HoloLand MCP tools (world CRUD + MMO + Twin Earth)\n  if (\n    name === 'generate_world_from_prompt' ||\n    name === 'generate_world' ||\n    name === 'create_world' ||\n    name === 'get_world' ||\n    name === 'update_world' ||\n    name === 'delete_world' ||\n    name === 'list_worlds' ||\n    name === 'create_shard' ||\n    name === 'get_shard' ||\n    name === 'update_shard' ||\n    name === 'delete_shard' ||\n    name === 'list_shards' ||\n    name === 'create_zone' ||\n    name === 'get_zone' ||\n    name === 'update_zone' ||\n    name === 'delete_zone' ||\n    name === 'list_zones' ||\n    name === 'create_place' ||\n    name === 'get_place' ||\n    name === 'update_place' ||\n    name === 'delete_place' ||\n    name === 'list_places' ||\n    name === 'create_location_quest' ||\n    name === 'get_location_quest' ||\n    name === 'update_location_quest' ||\n    name === 'delete_location_quest' ||\n    name === 'list_location_quests' ||\n    name === 'hololand_shard_status' ||\n    name === 'hololand_publish_zone' ||\n    name === 'hololand_create_geo_anchor' ||\n    name === 'hololand_get_geo_anchor' ||\n    name === 'hololand_list_geo_anchors' ||\n    name === 'hololand_steward_tick' ||\n    name === 'hololand_capture_runtime_receipt' ||\n    name === 'hololand_create_npc' ||\n    name === 'hololand_get_npc' ||\n    name === 'hololand_update_npc' ||\n    name === 'hololand_delete_npc' ||\n    name === 'hololand_list_npcs' ||\n    name === 'hololand_npc_generate_dialogue' ||\n    name === 'hololand_npc_byok_status' ||\n    name === 'hololand_brittney_npc_mode' ||\n    name === 'hololand_twin_earth_contract' ||\n    name === 'hololand_twin_earth_substrate_status' ||\n    // Player / Creator / Agent Provisioning (task_1778617298562_qdpb)\n    name === 'hololand_provision_player' ||\n    name === 'hololand_get_player' ||\n    name === 'hololand_list_players' ||\n    name === 'hololand_revoke_player' ||\n    name === 'hololand_create_player_invite' ||\n    name === 'hololand_get_invite' ||\n    name === 'hololand_provision_creator' ||\n    name === 'hololand_get_creator' ||\n    name === 'hololand_list_creators' ||\n    name === 'hololand_revoke_creator' ||\n    name === 'hololand_provision_agent' ||\n    name === 'hololand_get_agent' ||\n    name === 'hololand_list_agents' ||\n    name === 'hololand_revoke_agent' ||\n    // Twin Earth Robot / AI Sovereign Tool Family (task_1778618552503_a6rb)\n    name === 'twin_earth_register_identity' ||\n    name === 'twin_earth_get_identity' ||\n    name === 'twin_earth_update_identity' ||\n    name === 'twin_earth_revoke_identity' ||\n    name === 'twin_earth_list_identities' ||\n    name === 'twin_earth_create_safety_envelope' ||\n    name === 'twin_earth_get_safety_envelope' ||\n    name === 'twin_earth_update_safety_envelope' ||\n    name === 'twin_earth_delete_safety_envelope' ||\n    name === 'twin_earth_list_safety_envelopes' ||\n    name === 'twin_earth_grant_permission' ||\n    name === 'twin_earth_revoke_permission' ||\n    name === 'twin_earth_validate_permission' ||\n    name === 'twin_earth_list_permissions' ||\n    name === 'twin_earth_robot_actuate' ||\n    name === 'twin_earth_ai_invoke' ||\n    name === 'twin_earth_capture_receipt' ||\n    // Conformance Artifact Admission Gate (task_1778618757735_q298)\n    name === 'conformance_check_artifact' ||\n    name === 'conformance_admit_artifact' ||\n    name === 'conformance_list_rules'\n  ) {\n    const { handleHololandMcpTool } = await import('./hololand-mcp-tools');\n    return handleHololandMcpTool(name, args);\n  }\n\n  // Hololand training data generation\n  if (name === 'generate_hololand_training') {\n    return handleGenerateHololandTraining(args);\n  }\n\n  // Service contract tools\n  if (name === 'generate_service_contract' || name === 'explain_service_contract') {\n    const { handleServiceContractTool } = await import('./service-contract-tools');\n    return handleServiceContractTool(name, args);\n  }\n\n  // Fairness tools — verifiable algorithmic-fairness sweep + receipt\n  if (\n    name === 'fairness_sweep' ||\n    name === 'explain_fairness_receipt' ||\n    name === 'compile_to_bias_audit_report'\n  ) {\n    const { handleFairnessTool } = await import('./fairness-mcp-tools');\n    return handleFairnessTool(name, args);\n  }\n\n  // Composition validation tool\n  if (name === 'validate_composition') {\n    const { handleValidationTool } = await import('./validation-tools');\n    return handleValidationTool(name, args);\n  }\n\n  // Code health analysis tool\n  if (name === 'holoscript_code_health') {\n    const { handleCodeHealthTool } = await import('./code-health-tools');\n    return handleCodeHealthTool(name, args);\n  }\n\n  // Simulation tools with CAEL trace metadata\n  if (\n    name === 'solve_structural' ||\n    name === 'solve_thermal' ||\n    name === 'verify_cael_trace' ||\n    name === 'solve_logic' ||\n    name === 'train_rom' ||\n    name === 'compile_to_rom_twin'\n  ) {\n    const { handleSimulationTool } = await import('./simulation-tools');\n    return handleSimulationTool(name, args);\n  }\n\n  // Simulation billing tools (paid, capped solver execution via fleet)\n  if (name === 'sim_quote' || name === 'sim_run_paid' || name === 'sim_fleet_status') {\n    const { handleSimulationBillingTool } = await import('./simulation-billing-tools');\n    return handleSimulationBillingTool(name, args);\n  }\n\n  // TypeScript absorb tools\n  if (name === 'absorb_typescript' || name === 'absorb_suggest_holoscript_transform') {\n    const { handleAbsorbTypescriptTool } = await import('@holoscript/absorb-service/mcp');\n    return handleAbsorbTypescriptTool(name, args);\n  }\n\n  // Agent orchestration tools\n  if (\n    name === 'discover_agents' ||\n    name === 'delegate_task' ||\n    name === 'get_task_status' ||\n    name === 'compose_workflow' ||\n    name === 'execute_workflow' ||\n    name === 'workflow_memory_write' ||\n    name === 'workflow_memory_read' ||\n    name === 'workflow_memory_subscribe'\n  ) {\n    const { handleAgentOrchestrationTool } = await import('./agent-orchestration-tools');\n    // Wire a real tool executor so execute_workflow steps actually invoke MCP tools\n    // (previously every step returned a dry-run stub). Steps run with the caller's\n    // signing context; guard against execute_workflow re-entering itself.\n    const workflowToolExecutor = async (\n      toolName: string,\n      toolArgs: Record<string, unknown>\n    ): Promise<unknown> => {\n      if (toolName === 'execute_workflow') {\n        throw new Error('execute_workflow cannot be nested as a workflow step (recursion guard)');\n      }\n      return handleTool(toolName, toolArgs, effectiveSigningCtx);\n    };\n    return handleAgentOrchestrationTool(name, args, workflowToolExecutor);\n  }\n\n  // Agent identity tools\n  if (\n    name === 'issue_agent_token' ||\n    name === 'verify_agent_token' ||\n    name === 'check_permission' ||\n    name === 'get_delegation_chain'\n  ) {\n    const { handleAgentIdentityTool } = await import('./agent-identity-tools');\n    return handleAgentIdentityTool(name, args);\n  }\n\n  // Observability tools (v5.6)\n  if (\n    name === 'query_traces' ||\n    name === 'export_traces_otlp' ||\n    name === 'get_agent_health' ||\n    name === 'get_metrics_prometheus' ||\n    name === 'holo_service_scaffold'\n  ) {\n    const { handleObservabilityTool } = await import('./observability-tools');\n    return handleObservabilityTool(name, args);\n  }\n\n  // Plugin management tools (v5.7)\n  if (\n    name === 'install_plugin' ||\n    name === 'install_domain_plugin' ||\n    name === 'discover_plugins' ||\n    name === 'list_plugins' ||\n    name === 'manage_plugin'\n  ) {\n    const { handlePluginManagementTool } = await import('./plugin-management-tools');\n    return handlePluginManagementTool(name, args);\n  }\n\n  // Economy tools (v5.8 + v6.1 unified budget)\n  if (\n    name === 'check_agent_budget' ||\n    name === 'get_usage_summary' ||\n    name === 'get_creator_earnings' ||\n    name === 'settle_creator_payout' ||\n    name === 'optimize_scene_budget' ||\n    name === 'validate_marketplace_pricing' ||\n    name === 'get_unified_budget_state'\n  ) {\n    const { handleEconomyTool } = await import('./economy-tools');\n    return handleEconomyTool(name, args);\n  }\n\n  // Developer tools (v5.9 + holo_generate_bindings)\n  if (\n    name === 'get_api_reference' ||\n    name === 'serve_preview' ||\n    name === 'get_workspace_info' ||\n    name === 'inspect_trace_waterfall' ||\n    name === 'get_dev_dashboard_state' ||\n    name === 'holo_generate_bindings'\n  ) {\n    const { handleDeveloperTool } = await import('./developer-tools');\n    return handleDeveloperTool(name, args);\n  }\n\n  // HoloMesh spatial mesh tools\n  if (name.startsWith('holomesh_')) {\n    const { handleHoloMeshTool } = await import('./holomesh/index');\n    return handleHoloMeshTool(name, args);\n  }\n\n  // ConversationDaemon lifecycle tools (D.052 Brittney field / user daemon model)\n  if (\n    name === 'holo_create_daemon' ||\n    name === 'holo_get_daemon' ||\n    name === 'holo_update_daemon_ritual' ||\n    name === 'holo_list_daemons'\n  ) {\n    const result = await handleDaemonLifecycleTool(name, args);\n    if (result !== null) return result;\n  }\n\n  // Trait composition / ROS2 sync / economic contract (trait-tools.ts) — also in index.ts registry\n  if (\n    name === 'compile_trait_composition' ||\n    name === 'sync_hardware_loop' ||\n    name === 'execute_economic_contract'\n  ) {\n    const { handleTraitTool } = await import('./trait-tools');\n    const traitResult = await handleTraitTool(name, args);\n    if (traitResult !== null) {\n      return traitResult;\n    }\n  }\n\n  // Handle plugins\n  const pluginResult = await PluginManager.handleTool(name, args);\n  if (pluginResult !== null) {\n    return pluginResult;\n  }\n\n  // HoloMap reconstruction tools\n  if (isHoloMapToolName(name)) {\n    return handleHoloMapTool(name, args);\n  }\n\n  // Spatial MCP - compile_to_spatial (v0.1, research/2026-05-07_spatial-mcp-spec.md)\n  if (isSpatialMcpToolName(name)) {\n    return handleSpatialMcpTool(name, args);\n  }\n\n  // Agent negotiation primitives (task_1778175122619_xk5l) — wraps xsp6 / qe2i\n  // pure logic in MCP-shape adapters so external agents can drive the\n  // request_quote → quote → accept → execute → settle / dispute cycle via MCP.\n  if (isNegotiationToolName(name)) {\n    return handleNegotiationTool(name, args);\n  }\n\n  // Skeleton interop — rig_match_skeleton (G4)\n  if (name === 'rig_match_skeleton') {\n    const { handleRigMatchSkeleton } = await import('./tools/rig_match_skeleton');\n    return handleRigMatchSkeleton(args as unknown as Parameters<typeof handleRigMatchSkeleton>[0]);\n  }\n\n  // HoloShell download-recovery tools (local shelf custody) — dispatch to the handler objects.\n  if (name.startsWith('holoshell_download_recovery_')) {\n    const { holoshellDownloadRecoveryTools } = await import('./holoshell-download-recovery-tools');\n    const tool = holoshellDownloadRecoveryTools.find((t) => t.name === name);\n    if (tool) return tool.handler(args);\n  }\n\n  throw new Error(`Unknown tool: ${name}`);\n}\n\n// === PARSING HANDLERS ===\n\nasync function handleParseHs(args: Record<string, unknown>) {\n  const code = args.code as string;\n  const _format = (args.format as string) || 'hsplus';\n\n  try {\n    const parser = new HoloScriptPlusParser();\n    const result = parser.parse(code);\n    const errors = result.errors || [];\n    const warnings = result.warnings || [];\n    const success = result.success === true && errors.length === 0;\n\n    // Deduplicate AST: root-level 'body' duplicates 'children'\n    const ast = result.ast;\n    if (ast && typeof ast === 'object' && 'body' in ast && 'children' in ast) {\n      const { body: _body, ...cleanAst } = ast as Record<string, unknown>;\n      return {\n        success,\n        ast: cleanAst,\n        errors,\n        warnings,\n        ...(args.includeSourceMap\n          ? { sourceMap: (result as unknown as Record<string, unknown>).sourceMap }\n          : {}),\n      };\n    }\n\n    return {\n      success,\n      ast,\n      errors,\n      warnings,\n      ...(args.includeSourceMap\n        ? { sourceMap: (result as unknown as Record<string, unknown>).sourceMap }\n        : {}),\n    };\n  } catch (error) {\n    return {\n      success: false,\n      error: error instanceof Error ? error.message : String(error),\n    };\n  }\n}\n\nasync function handleParseHolo(args: Record<string, unknown>) {\n  const code = args.code as string;\n  const strict = args.strict as boolean;\n\n  try {\n    const result = strict ? parseHoloStrict(code) : parseHolo(code);\n    const errors = ('errors' in result ? result.errors : []) || [];\n    const parseSuccess = 'success' in result ? result.success !== false : true;\n\n    return {\n      success: parseSuccess && errors.length === 0,\n      composition: result,\n      errors,\n    };\n  } catch (error) {\n    return {\n      success: false,\n      error: error instanceof Error ? error.message : String(error),\n    };\n  }\n}\n\nasync function handleParsePipeline(args: Record<string, unknown>) {\n  const code = args.code as string;\n\n  try {\n    if (typeof code !== 'string') {\n      return { success: false, error: 'Missing required string argument: code' };\n    }\n\n    const result = parsePipeline(code);\n    return {\n      success: result.success,\n      pipeline: result.pipeline,\n      errors: result.errors,\n    };\n  } catch (error) {\n    return {\n      success: false,\n      error: error instanceof Error ? error.message : String(error),\n    };\n  }\n}\n\nasync function handleCompilePipeline(args: Record<string, unknown>) {\n  const code = args.code as string;\n  const target = (args.target as string) || 'node';\n  const moduleName = (args.moduleName as string) || 'index.mjs';\n\n  if (target !== 'node') {\n    return {\n      success: false,\n      error: `Unsupported target: ${target}. Currently only 'node' is available.`,\n    };\n  }\n\n  if (typeof code !== 'string') {\n    return { success: false, error: 'Missing required string argument: code' };\n  }\n\n  const result = compilePipelineSourceToNode(code, { moduleName });\n  if (!result.success) {\n    return {\n      success: false,\n      errors: result.errors || [],\n      error: (result.errors || []).join('; ') || 'Pipeline compilation failed',\n    };\n  }\n\n  return {\n    success: true,\n    code: result.code,\n  };\n}\n\n// === VALIDATION HANDLER ===\n\nasync function handleValidate(args: Record<string, unknown>) {\n  const codeInput = args.code ?? args.content;\n  const format = (args.format as string) || 'auto';\n  const includeWarnings = args.includeWarnings !== false;\n  const includeSuggestions = args.includeSuggestions !== false;\n\n  if (typeof codeInput !== 'string') {\n    return {\n      valid: false,\n      format,\n      errors: [\n        {\n          code: 'missing-code',\n          line: 1,\n          message:\n            'validate_holoscript requires a string `code` argument. `content` is also accepted as a compatibility alias.',\n          suggestion:\n            'Call validate_holoscript with { \"code\": \"<HoloScript source>\" } or { \"content\": \"<HoloScript source>\" }.',\n        },\n      ],\n      summary: 'Missing HoloScript source',\n    };\n  }\n\n  const code = codeInput;\n\n  try {\n    // Detect format if auto\n    const detectedFormat = format === 'auto' ? detectFormat(code) : format;\n\n    // Parse based on format\n    let parseResult;\n    let validator: 'holo-parser' | 'rust-wasm' | 'typescript-hsplus';\n    if (detectedFormat === 'holo') {\n      parseResult = parseHolo(code);\n      validator = 'holo-parser';\n    } else if (detectedFormat === 'hs') {\n      parseResult = JSON.parse(validateCanonicalHsDetailed(code)) as {\n        valid: boolean;\n        errors: Array<{ message: string; line?: number; column?: number }>;\n        warnings?: Array<{ message: string; line?: number; column?: number }>;\n      };\n      validator = 'rust-wasm';\n    } else {\n      const parser = new HoloScriptPlusParser();\n      parseResult = parser.parse(code);\n      validator = 'typescript-hsplus';\n    }\n\n    const errors: AIFriendlyError[] = [];\n    const warnings: AIFriendlyError[] = [];\n\n    // Convert errors to AI-friendly format\n    if (parseResult.errors) {\n      for (const err of parseResult.errors) {\n        const aiError = toAIFriendlyError(err, code, includeSuggestions);\n        errors.push(aiError);\n      }\n    }\n\n    if (includeWarnings && parseResult.warnings) {\n      for (const warn of parseResult.warnings) {\n        const aiWarn = toAIFriendlyError(warn, code, includeSuggestions);\n        warnings.push(aiWarn);\n      }\n    }\n\n    // Check for unknown traits — add as warnings, not errors\n    if (includeWarnings) {\n      // Use the SSOT known-trait union (VR + Native2D + code-graph + runtime/governance directive\n      // traits like @freeze_when / @llama_serve), not VR_TRAITS alone — otherwise legitimate\n      // top-level directive traits falsely trip the unknown-trait warning.\n      const KNOWN_TRAIT_SET: Set<string> = buildKnownTraitSet();\n      const traitMatches = [...code.matchAll(/@(\\w+)/g)];\n      for (const match of traitMatches) {\n        const traitName = match[1];\n        if (!KNOWN_TRAIT_SET.has(traitName)) {\n          warnings.push({\n            code: 'unknown-trait',\n            message: `Unknown trait @${traitName} — not a known trait (${KNOWN_TRAIT_SET.size} known traits)`,\n            line: code.substring(0, match.index).split('\\n').length,\n            suggestion: `Check available traits with list_traits tool`,\n          });\n        }\n      }\n    }\n\n    const hasWarnings = warnings.length > 0;\n    return {\n      valid: errors.length === 0,\n      format: detectedFormat,\n      validator,\n      errors,\n      ...(includeWarnings && { warnings }),\n      summary:\n        errors.length > 0\n          ? `Found ${errors.length} error(s)`\n          : hasWarnings\n            ? `Valid with ${warnings.length} warning(s) — review unknown traits`\n            : 'Valid HoloScript code',\n    };\n  } catch (error) {\n    return {\n      valid: false,\n      error: error instanceof Error ? error.message : String(error),\n    };\n  }\n}\n\n// === TRAITS HANDLERS ===\n\nasync function handleListTraits(args: Record<string, unknown>) {\n  const category = (args.category as string) || 'all';\n  const map = getTraitCategoryMap();\n\n  if (category === 'all') {\n    const fromCore = loadTraitCategoriesFromCore();\n    const coreSlugs = Object.keys(fromCore).sort();\n    const categories =\n      coreSlugs.length > 0\n        ? Object.fromEntries(coreSlugs.map((s) => [s, fromCore[s].length]))\n        : Object.fromEntries(\n            Object.entries(TRAIT_CATEGORIES_FALLBACK).map(([k, v]) => [k, v.length])\n          );\n    return {\n      total: ALL_TRAITS.length,\n      categories,\n      categorySlugs: coreSlugs.length > 0 ? coreSlugs : Object.keys(TRAIT_CATEGORIES_FALLBACK),\n      legacyAliases: Object.keys(LEGACY_TRAIT_CATEGORY_ALIASES),\n      list: ALL_TRAITS,\n    };\n  }\n\n  const slug = resolveTraitCategorySlug(category);\n  const traits = map[category] ?? map[slug];\n  if (!traits) {\n    return {\n      error: `Unknown category: ${category}`,\n      resolvedSlug: slug,\n      validCategoriesSample: Object.keys(map).slice(0, 48),\n      hint: 'Use category=all for categorySlugs and legacyAliases, or pass a core slug (e.g. core-vr-interaction).',\n    };\n  }\n\n  return {\n    category: slug,\n    requestedAs: category,\n    count: traits.length,\n    traits,\n  };\n}\n\nasync function handleExplainTrait(args: Record<string, unknown>) {\n  let trait = args.trait as string;\n\n  // Normalize trait name\n  if (!trait.startsWith('@')) {\n    trait = '@' + trait;\n  }\n\n  const doc = TRAIT_DOCS[trait];\n  if (!doc) {\n    // Find similar traits\n    const similar = findSimilarTraits(trait);\n    return {\n      error: `Unknown trait: ${trait}`,\n      suggestion: similar.length > 0 ? `Did you mean: ${similar.join(', ')}?` : null,\n      allTraits: ALL_TRAITS,\n    };\n  }\n\n  return doc;\n}\n\nasync function handleSuggestTraits(args: Record<string, unknown>) {\n  const description = args.description as string;\n  const context = args.context as string | undefined;\n\n  return suggestTraits(description, context);\n}\n\nasync function handleSuggestUniversalTraits(args: Record<string, unknown>) {\n  const description = args.description as string;\n  const domain = args.domain as string | undefined;\n  const context = args.context as string | undefined;\n\n  return suggestUniversalTraits(description, domain, context);\n}\n\n// === GENERATION HANDLERS ===\n\nasync function handleGenerateObject(args: Record<string, unknown>) {\n  const description = args.description as string;\n  const format = (args.format as string) || 'hsplus';\n  const includeDocs = args.includeDocs as boolean;\n\n  return generateObjectForMCP(description, {\n    format: format as 'hs' | 'hsplus' | 'holo',\n    includeDocs,\n  });\n}\n\nasync function handleGenerateScene(args: Record<string, unknown>) {\n  const description = args.description as string;\n  const style = (args.style as string) || 'detailed';\n  const features = (args.features as string[]) || [];\n\n  return generateSceneForMCP(description, {\n    style: style as 'minimal' | 'detailed' | 'production',\n    features,\n  });\n}\n\n// === DOCUMENTATION HANDLERS ===\n\nasync function handleGetSyntaxReference(args: Record<string, unknown>) {\n  const topic = args.topic as string;\n\n  const doc = SYNTAX_DOCS[topic];\n  if (!doc) {\n    return {\n      error: `Unknown topic: ${topic}`,\n      availableTopics: Object.keys(SYNTAX_DOCS),\n    };\n  }\n\n  return doc;\n}\n\nconst LIST_TOKENS = new Set(['', 'list', 'all', 'catalog', 'index', '*', 'browse']);\n\n/** The audited public example catalog (real repo state from the health matrix),\n *  ordered so working/supported examples surface before aspirational ones. */\nfunction publicCatalog() {\n  return EXAMPLE_CATALOG.filter((e) => PUBLIC_LINK_POLICIES.has(e.linkPolicy)).sort((a, b) => {\n    const rank = (s: string) => (s === 'supported' ? 0 : 1);\n    return rank(a.status) - rank(b.status);\n  });\n}\n\n/** Browse mode — return the real catalog + full-tree inventory so callers can\n *  discover the actual repo examples instead of getting an empty/erroring result. */\nfunction exampleCatalogView() {\n  const inlineKeys = Object.keys(EXAMPLES);\n  return {\n    kind: 'example-catalog',\n    inventory: {\n      totalExampleFiles: EXAMPLE_INVENTORY.total,\n      byFormat: EXAMPLE_INVENTORY.byFormat,\n      categories: Object.keys(EXAMPLE_INVENTORY.byCategory).sort(),\n      byCategory: EXAMPLE_INVENTORY.byCategory,\n    },\n    auditedExamples: publicCatalog().map((e) => ({\n      slug: e.slug,\n      path: e.path,\n      format: e.format,\n      category: e.category,\n      status: e.status,\n      reason: e.reason,\n    })),\n    inlinePatterns: inlineKeys,\n    fullIndex: 'examples/INDEX.md',\n    hint:\n      'Pass a slug (e.g. \"interactive-object\"), a path (\"examples/physics/...\"), ' +\n      'or a keyword (\"physics\", \"robot\", \"teleport\") to fetch a specific example. ' +\n      `${EXAMPLE_INVENTORY.total} example files total; ${publicCatalog().length} are audited & link-policy-tagged here. ` +\n      'Inline patterns return runnable code; catalog entries return the repo path + parser status.',\n  };\n}\n\nasync function handleGetExamples(args: Record<string, unknown>) {\n  const raw = typeof args.pattern === 'string' ? args.pattern : '';\n  const pattern = raw.trim();\n\n  // Browse / list mode — no pattern (or an explicit list token) returns the real\n  // repo catalog + inventory instead of erroring. Fixes get_examples returning 0.\n  if (LIST_TOKENS.has(pattern.toLowerCase())) {\n    return exampleCatalogView();\n  }\n\n  const inlineKeys = Object.keys(EXAMPLES);\n\n  // 1. Exact inline match — richest result (runnable code).\n  const example = EXAMPLES[pattern];\n  if (example) return example;\n\n  // 2. Exact catalog match by slug or path.\n  const lower = pattern.toLowerCase();\n  const catalogExact = EXAMPLE_CATALOG.find(\n    (e) => e.slug.toLowerCase() === lower || e.path.toLowerCase() === lower\n  );\n  if (catalogExact) {\n    return { kind: 'example-ref', ...catalogExact };\n  }\n\n  // 3. Fuzzy match across BOTH inline patterns and the real catalog.\n  const queryWords = lower\n    .replace(/[^a-z0-9]+/g, ' ')\n    .split(/\\s+/)\n    .filter(Boolean);\n  const overlaps = (slug: string) => {\n    const slugWords = slug\n      .toLowerCase()\n      .split(/[^a-z0-9]+/)\n      .filter(Boolean);\n    return queryWords.filter((q) => slugWords.some((s) => s.includes(q) || q.includes(s))).length;\n  };\n\n  const inlineScored = inlineKeys\n    .map((k) => ({ key: k, score: overlaps(k) }))\n    .filter((s) => s.score > 0)\n    .sort((a, b) => b.score - a.score);\n\n  if (inlineScored.length > 0) {\n    return { ...EXAMPLES[inlineScored[0].key], _matchedPattern: inlineScored[0].key };\n  }\n\n  const catalogScored = EXAMPLE_CATALOG.map((e) => ({\n    entry: e,\n    score: Math.max(overlaps(e.slug), overlaps(e.category), overlaps(e.path)),\n  }))\n    .filter((s) => s.score > 0)\n    .sort((a, b) => b.score - a.score)\n    .slice(0, 8);\n\n  if (catalogScored.length > 0) {\n    return {\n      kind: 'example-matches',\n      query: pattern,\n      matches: catalogScored.map((s) => ({\n        slug: s.entry.slug,\n        path: s.entry.path,\n        format: s.entry.format,\n        status: s.entry.status,\n      })),\n      hint: 'These are repo example paths. Open via holo_read_file / the repo, or refine the query.',\n    };\n  }\n\n  // 4. Nothing matched — return the catalog so the caller can still discover.\n  return {\n    error: `No example matched: ${pattern}`,\n    ...exampleCatalogView(),\n  };\n}\n\nasync function handleExplainCode(args: Record<string, unknown>) {\n  const code = args.code as string;\n  const detail = (args.detail as string) || 'detailed';\n\n  // Parse the code first\n  const format = detectFormat(code);\n  let parsed;\n\n  try {\n    if (format === 'holo') {\n      parsed = parseHolo(code);\n    } else {\n      const parser = new HoloScriptPlusParser();\n      parsed = parser.parse(code);\n    }\n  } catch (error) {\n    return {\n      error: 'Failed to parse code',\n      parseError: error instanceof Error ? error.message : String(error),\n    };\n  }\n\n  // Generate explanation based on AST\n  const explanation = generateExplanation(parsed, detail);\n\n  return {\n    format,\n    explanation,\n    detail,\n  };\n}\n\nasync function handleAnalyzeCode(args: Record<string, unknown>) {\n  const code = args.code as string;\n  const format = detectFormat(code);\n\n  let parsed;\n  try {\n    if (format === 'holo') {\n      parsed = parseHolo(code);\n    } else {\n      const parser = new HoloScriptPlusParser();\n      parsed = parser.parse(code);\n    }\n  } catch (error) {\n    return {\n      error: 'Failed to parse code',\n      parseError: error instanceof Error ? error.message : String(error),\n    };\n  }\n\n  return analyzeAST(parsed, code);\n}\n\n// === RENDERING HANDLERS ===\n\nasync function handleRenderPreview(args: Record<string, unknown>) {\n  return renderPreview({\n    code: args.code as string,\n    format: ((args.format as string) || 'png') as 'png' | 'gif' | 'mp4' | 'webp',\n    resolution: (args.resolution as number[]) || [800, 600],\n    camera: args.camera as { position?: number[]; target?: number[] },\n    duration: args.duration as number,\n    quality: ((args.quality as string) || 'preview') as 'draft' | 'preview' | 'production',\n  });\n}\n\nasync function handleCreateShareLink(args: Record<string, unknown>) {\n  return createShareLink({\n    code: args.code as string,\n    title: args.title as string,\n    description: args.description as string,\n    platform: ((args.platform as string) || 'x') as 'x' | 'generic' | 'codesandbox' | 'stackblitz',\n  });\n}\n\n// === CONVERSION HANDLER ===\n\nasync function handleConvertFormat(args: Record<string, unknown>) {\n  const code = args.code as string;\n  const from = args.from as string;\n  const to = args.to as string;\n\n  try {\n    const convertedCode = convertFormat(code, from, to);\n    return {\n      success: true,\n      original: from,\n      target: to,\n      code: convertedCode,\n      note: 'Format conversion is a best-effort process. Manual review recommended.',\n    };\n  } catch (error) {\n    return {\n      success: false,\n      original: from,\n      target: to,\n      code: code,\n      error: error instanceof Error ? error.message : String(error),\n    };\n  }\n}\n\n/**\n * Convert between HoloScript formats (hs, hsplus, holo)\n */\nfunction convertFormat(code: string, from: string, to: string): string {\n  // First, parse the source format\n  let ast: any;\n\n  if (from === 'holo') {\n    ast = parseHolo(code);\n  } else {\n    // HoloScriptPlusParser handles both .hs and .hsplus formats\n    const parser = new HoloScriptPlusParser();\n    const result = parser.parse(code);\n    ast = result.ast;\n  }\n\n  // Convert AST to target format\n  if (to === 'holo') {\n    return convertToHolo(ast, from);\n  } else if (to === 'hsplus') {\n    return convertToHsPlus(ast, from);\n  } else {\n    return convertToHs(ast, from);\n  }\n}\n\nfunction convertToHolo(ast: any, _from: string): string {\n  const lines: string[] = [];\n  lines.push('composition \"Converted Scene\" {');\n\n  // Add environment block\n  lines.push('  environment {');\n  lines.push('    skybox: \"nebula\"');\n  lines.push('    ambient_light: 0.4');\n  lines.push('  }');\n  lines.push('');\n\n  // Extract objects from AST\n  const objects = extractObjects(ast);\n\n  for (const obj of objects) {\n    const traits = obj.traits?.length\n      ? obj.traits.map((t: string) => `@${t.replace('@', '')}`).join(' ')\n      : '';\n    lines.push(`  object \"${obj.name || 'obj'}\" ${traits} {`.trim() + ' {');\n    lines.push(`    geometry: \"${obj.type || 'cube'}\"`);\n    if (obj.position) {\n      lines.push(`    position: [${obj.position.join(', ')}]`);\n    }\n    if (obj.color) {\n      lines.push(`    color: \"${obj.color}\"`);\n    }\n    lines.push('  }');\n  }\n\n  lines.push('}');\n  return lines.join('\\n');\n}\n\nfunction convertToHsPlus(ast: any, _from: string): string {\n  const lines: string[] = [];\n  const objects = extractObjects(ast);\n\n  for (const obj of objects) {\n    const traits = obj.traits?.length\n      ? obj.traits.map((t: string) => `  @${t.replace('@', '')}`).join('\\n')\n      : '';\n    lines.push(`${obj.type || 'object'} ${obj.name || 'obj'} {`);\n    if (traits) lines.push(traits);\n    if (obj.position) {\n      lines.push(`  position: [${obj.position.join(', ')}]`);\n    }\n    if (obj.color) {\n      lines.push(`  color: \"${obj.color}\"`);\n    }\n    lines.push('}');\n    lines.push('');\n  }\n\n  return lines.join('\\n').trim();\n}\n\nfunction convertToHs(ast: any, _from: string): string {\n  const lines: string[] = [];\n  const objects = extractObjects(ast);\n\n  for (const obj of objects) {\n    lines.push(`${obj.type || 'orb'} ${obj.name || 'obj'} {`);\n    if (obj.position) {\n      lines.push(\n        `  position: [${obj.position[0] || 0}, ${obj.position[1] || 0}, ${obj.position[2] || 0}]`\n      );\n    }\n    if (obj.color) {\n      lines.push(`  color: \"${obj.color}\"`);\n    }\n    lines.push('}');\n    lines.push('');\n  }\n\n  return lines.join('\\n').trim();\n}\n\nfunction extractObjects(ast: any): any[] {\n  const objects: any[] = [];\n\n  if (!ast) return objects;\n\n  // Handle .holo composition format\n  if (ast.objects && Array.isArray(ast.objects)) {\n    for (const obj of ast.objects) {\n      objects.push({\n        name: obj.name || obj.id,\n        type: obj.type || obj.geometry || 'cube',\n        position: obj.position,\n        color: obj.color,\n        traits: obj.traits || [],\n      });\n    }\n  }\n\n  // Handle .hsplus or .hs format\n  if (ast.nodes && Array.isArray(ast.nodes)) {\n    for (const node of ast.nodes) {\n      if (node.type === 'object' || node.nodeType === 'object') {\n        objects.push({\n          name: node.name || node.id,\n          type: node.objectType || node.geometry || 'cube',\n          position: node.props?.position || node.position,\n          color: node.props?.color || node.color,\n          traits: node.traits || [],\n        });\n      }\n    }\n  }\n\n  // Handle flat declaration list\n  if (ast.declarations && Array.isArray(ast.declarations)) {\n    for (const decl of ast.declarations) {\n      objects.push({\n        name: decl.name,\n        type: decl.type || 'orb',\n        position: decl.props?.position,\n        color: decl.props?.color,\n        traits: [],\n      });\n    }\n  }\n\n  return objects;\n}\n\n// === HELPER FUNCTIONS ===\n\ninterface AIFriendlyError {\n  code: string;\n  line: number;\n  column?: number;\n  message: string;\n  context?: string;\n  suggestion?: string;\n  fix?: {\n    type: 'replace' | 'insert' | 'delete';\n    old?: string;\n    new?: string;\n    position?: number;\n  };\n}\n\nfunction detectFormat(code: string): 'hs' | 'hsplus' | 'holo' {\n  if (code.includes('composition') && code.includes('{')) {\n    return 'holo';\n  }\n  if (code.includes('@') || code.includes('state {')) {\n    return 'hsplus';\n  }\n  return 'hs';\n}\n\nfunction toAIFriendlyError(\n  error: { message: string; line?: number; column?: number },\n  code: string,\n  includeSuggestions: boolean\n): AIFriendlyError {\n  const message = error.message;\n  const line = error.line || 1;\n\n  const aiError: AIFriendlyError = {\n    code: extractErrorCode(message),\n    line,\n    column: error.column,\n    message,\n  };\n\n  // Add context from source\n  const lines = code.split('\\n');\n  if (line > 0 && line <= lines.length) {\n    aiError.context = lines[line - 1].trim();\n  }\n\n  // Add suggestions if enabled\n  if (includeSuggestions) {\n    const suggestion = generateSuggestion(message);\n    if (suggestion) {\n      aiError.suggestion = suggestion.message;\n      aiError.fix = suggestion.fix;\n    }\n  }\n\n  return aiError;\n}\n\nfunction extractErrorCode(message: string): string {\n  const canonical = message.match(/\\b(HS(?:P)?\\d{3})\\b/);\n  if (canonical) return canonical[1];\n\n  // Extract error code from message if present\n  const match = message.match(/\\[(E\\d+|W\\d+)\\]/);\n  if (match) return match[1];\n\n  // Generate a code based on error type\n  if (message.includes('Unknown trait')) return 'E001';\n  if (message.includes('syntax')) return 'E002';\n  if (message.includes('unexpected')) return 'E003';\n  if (message.includes('missing')) return 'E004';\n  return 'E999';\n}\n\nfunction generateSuggestion(\n  message: string\n): { message: string; fix?: AIFriendlyError['fix'] } | null {\n  // Unknown trait\n  const traitMatch = message.match(/Unknown trait:?\\s*[@]?(\\w+)/i);\n  if (traitMatch) {\n    const trait = '@' + traitMatch[1];\n    const similar = findSimilarTraits(trait);\n    if (similar.length > 0) {\n      return {\n        message: `Did you mean ${similar[0]}?`,\n        fix: { type: 'replace', old: trait, new: similar[0] },\n      };\n    }\n  }\n\n  // Typo in geometry\n  const geoMatch = message.match(/(spher|cub|cylinder|con|plan)/i);\n  if (geoMatch) {\n    const corrections: Record<string, string> = {\n      sper: 'sphere',\n      spher: 'sphere',\n      cub: 'cube',\n      con: 'cone',\n      plan: 'plane',\n    };\n    const key = geoMatch[1].toLowerCase();\n    if (corrections[key]) {\n      return {\n        message: `Did you mean '${corrections[key]}'?`,\n        fix: { type: 'replace', old: geoMatch[0], new: corrections[key] },\n      };\n    }\n  }\n\n  return null;\n}\n\nfunction findSimilarTraits(trait: string): string[] {\n  const normalized = trait.replace('@', '').toLowerCase();\n\n  return ALL_TRAITS.filter((t) => {\n    const tName = t.replace('@', '').toLowerCase();\n    // Simple Levenshtein-like matching\n    if (tName.includes(normalized) || normalized.includes(tName)) return true;\n    // Check first few chars\n    if (tName.substring(0, 3) === normalized.substring(0, 3)) return true;\n    return false;\n  }).slice(0, 3);\n}\n\ninterface ParsedAST {\n  composition?: unknown;\n  type?: string;\n  name?: string;\n  nodes?: Array<{\n    type?: string;\n    nodeType?: string;\n    name?: string;\n    id?: string;\n    objectType?: string;\n    geometry?: string;\n    traits?: string[];\n  }>;\n  ast?: { nodes?: ParsedAST['nodes'] };\n  objects?: Array<{\n    name?: string;\n    id?: string;\n    type?: string;\n    geometry?: string;\n    traits?: string[];\n  }>;\n  environment?: { skybox?: string; ambient_light?: number; theme?: string };\n  logic?: unknown;\n  actions?: unknown;\n}\n\nfunction generateExplanation(parsed: unknown, detail: string): string {\n  const ast = parsed as ParsedAST;\n  const sections: string[] = [];\n\n  // Overview section\n  sections.push('## Overview');\n\n  // Detect format and describe structure\n  if (ast?.composition || ast?.type === 'composition') {\n    sections.push('This is a **.holo** declarative composition file.');\n    if (ast.name) {\n      sections.push(`Composition name: **${ast.name}**`);\n    }\n  } else if (ast?.nodes || ast?.ast?.nodes) {\n    const nodes = ast.nodes || ast.ast?.nodes;\n    sections.push('This is a **.hsplus** (HoloScript Plus) file with VR traits.');\n    sections.push(`Contains **${nodes?.length || 0}** top-level declarations.`);\n  } else {\n    sections.push('This is a **.hs** (Classic HoloScript) file.');\n  }\n\n  // Environment description\n  if (ast?.environment) {\n    sections.push('');\n    sections.push('### Environment');\n    const env = ast.environment;\n    if (env.skybox) sections.push(`- Skybox: **${env.skybox}**`);\n    if (env.ambient_light !== undefined) sections.push(`- Ambient light: **${env.ambient_light}**`);\n    if (env.theme) sections.push(`- Theme: **${env.theme}**`);\n  }\n\n  // Objects description\n  const objects = extractObjectsForExplanation(ast);\n  if (objects.length > 0) {\n    sections.push('');\n    sections.push('### Objects');\n\n    if (detail === 'brief') {\n      sections.push(`Contains **${objects.length}** objects.`);\n    } else {\n      for (const obj of objects.slice(0, 10)) {\n        let desc = `- **${obj.name}**`;\n        if (obj.type) desc += ` (${obj.type})`;\n        if (obj.traits?.length) desc += ` with traits: ${obj.traits.join(', ')}`;\n        sections.push(desc);\n      }\n      if (objects.length > 10) {\n        sections.push(`... and **${objects.length - 10}** more objects.`);\n      }\n    }\n  }\n\n  // Traits summary\n  const allTraits = new Set<string>();\n  for (const obj of objects) {\n    for (const trait of obj.traits || []) {\n      allTraits.add(trait);\n    }\n  }\n  if (allTraits.size > 0) {\n    sections.push('');\n    sections.push('### VR Traits Used');\n    sections.push(Array.from(allTraits).join(', '));\n  }\n\n  // Logic/behavior summary\n  if (ast?.logic || ast?.actions) {\n    sections.push('');\n    sections.push('### Behavior');\n    sections.push('Contains event handlers and/or action definitions for interactivity.');\n  }\n\n  return sections.join('\\n');\n}\n\ninterface ExtractedObject {\n  name: string;\n  type?: string;\n  traits: string[];\n}\n\nfunction extractObjectsForExplanation(ast: ParsedAST): ExtractedObject[] {\n  const objects: ExtractedObject[] = [];\n\n  if (!ast) return objects;\n\n  // Handle .holo format\n  if (ast.objects && Array.isArray(ast.objects)) {\n    for (const obj of ast.objects) {\n      objects.push({\n        name: obj.name || obj.id || 'unnamed',\n        type: obj.type || obj.geometry,\n        traits: obj.traits || [],\n      });\n    }\n  }\n\n  // Handle .hsplus/.hs format\n  const nodes = ast.nodes || ast.ast?.nodes || [];\n  for (const node of nodes) {\n    if (node.type === 'object' || node.nodeType === 'object') {\n      objects.push({\n        name: node.name || node.id || 'unnamed',\n        type: node.objectType || node.geometry,\n        traits: node.traits || [],\n      });\n    }\n  }\n\n  return objects;\n}\n\nfunction analyzeAST(parsed: unknown, code: string) {\n  const lines = code.split('\\n').length;\n  const objects = (code.match(/\\b(orb|object|cube|sphere|model)\\s+\\w+/gi) || []).length;\n  const traits = (code.match(/@\\w+/g) || []).length;\n  const functions = (code.match(/\\b(function|action|on_\\w+)\\s*\\(/gi) || []).length;\n\n  return {\n    stats: {\n      lines,\n      objects,\n      traits,\n      functions,\n      characters: code.length,\n    },\n    complexity: {\n      score: Math.min(10, Math.round((objects + traits + functions) / 5)),\n      level:\n        objects + traits + functions < 10\n          ? 'simple'\n          : objects + traits + functions < 30\n            ? 'moderate'\n            : 'complex',\n    },\n    suggestions: [\n      ...(traits === 0 ? ['Consider adding VR traits for interactivity'] : []),\n      ...(objects > 20 ? ['Consider using templates to reduce duplication'] : []),\n      ...(lines > 200 ? ['Consider splitting into multiple composition files'] : []),\n    ],\n  };\n}\n\n// === TEXT-TO-3D HANDLER ===\n\ninterface NativeAutoRigEnrichmentInput {\n  holoCode: string;\n  description: string;\n  provider: string;\n  modelFilePath: string;\n  objectName?: string;\n  traits?: string[];\n  rig: AutoRigRigType;\n  pose: AutoRigPose;\n}\n\ninterface NativeAutoRigEnrichment {\n  holoCode: string;\n  traits: string[];\n  autoRig: NativeAutoRigPlan;\n  generatedMesh: {\n    model: string;\n    provider: string;\n    description: string;\n    topology: string;\n  };\n  skeleton: {\n    rig: AutoRigRigType;\n    pose: AutoRigPose;\n    boneCount: number;\n    standard: string;\n  };\n}\n\nfunction normalizeGenerate3DObjectRig(value: unknown): AutoRigRigType | undefined {\n  if (value === undefined || value === null || value === '') return undefined;\n  if (value === 'humanoid' || value === 'custom') return value;\n  throw new Error('rig must be one of: humanoid, custom');\n}\n\nfunction normalizeGenerate3DObjectPose(value: unknown): AutoRigPose {\n  if (value === undefined || value === null || value === '') return 't-pose';\n  if (value === 't-pose' || value === 'a-pose') return value;\n  throw new Error('pose must be one of: t-pose, a-pose');\n}\n\nfunction basenameFromPath(filePath: string): string {\n  return filePath.split(/[\\\\/]/).filter(Boolean).pop() || 'generated.glb';\n}\n\nfunction escapeRegexLiteral(value: string): string {\n  return value.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\n\nfunction escapeHoloString(value: string): string {\n  return value.replace(/\\\\/g, '\\\\\\\\').replace(/\"/g, '\\\\\"');\n}\n\nfunction quoteHolo(value: string): string {\n  return `\"${escapeHoloString(value)}\"`;\n}\n\nfunction sanitizeGeneratedObjectName(description: string): string {\n  return (\n    description\n      .toLowerCase()\n      .replace(/[^a-z0-9]+/g, '_')\n      .replace(/^_|_$/g, '')\n      .slice(0, 40) || 'generated_object'\n  );\n}\n\nfunction extractFirstHoloObjectName(holoCode: string): string | undefined {\n  return holoCode.match(/object\\s+\"([^\"]+)\"/)?.[1];\n}\n\nfunction mergeGeneratedObjectTraits(traits: string[] | undefined): string[] {\n  return Array.from(new Set([...(traits ?? []), 'generated_mesh', 'auto_rig', 'skeleton']));\n}\n\nfunction injectNativeAutoRigAnnotations(\n  holoCode: string,\n  objectName: string,\n  modelFile: string,\n  provider: string,\n  plan: NativeAutoRigPlan\n): string {\n  const annotations = [\n    `@generated_mesh(model: ${quoteHolo(modelFile)}, provider: ${quoteHolo(provider)}, topology: ${quoteHolo(plan.topology)})`,\n    `@auto_rig(rig: ${quoteHolo(plan.rig)}, pose: ${quoteHolo(plan.pose)}, source: ${quoteHolo(plan.source)})`,\n    `@skeleton(rig: ${quoteHolo(plan.rig)}, pose: ${quoteHolo(plan.pose)}, bone_count: ${plan.boneCount}, standard: ${quoteHolo(plan.animationCompatibility.standard)})`,\n  ];\n  const missingAnnotations = annotations.filter((annotation) => {\n    const name = annotation.slice(0, annotation.indexOf('('));\n    return !holoCode.includes(name);\n  });\n\n  if (missingAnnotations.length === 0) return holoCode;\n\n  const objectPattern = new RegExp(`(object\\\\s+\"${escapeRegexLiteral(objectName)}\"[^\\\\{]*)(\\\\{)`);\n  if (objectPattern.test(holoCode)) {\n    return holoCode.replace(objectPattern, `$1 ${missingAnnotations.join(' ')} $2`);\n  }\n\n  return `composition \"${escapeHoloString(objectName)}\" {\n  object \"${escapeHoloString(objectName)}\" ${missingAnnotations.join(' ')} {\n    model: \"${escapeHoloString(modelFile)}\"\n  }\n}\n`;\n}\n\nexport function applyNativeAutoRigToGeneratedObject(\n  input: NativeAutoRigEnrichmentInput\n): NativeAutoRigEnrichment {\n  const objectName =\n    input.objectName ??\n    extractFirstHoloObjectName(input.holoCode) ??\n    sanitizeGeneratedObjectName(input.description);\n  const modelFile = basenameFromPath(input.modelFilePath);\n  const autoRig = createNativeAutoRigPlan({\n    rig: input.rig,\n    pose: input.pose,\n    sourceMesh: input.modelFilePath,\n    objectName,\n    provider: input.provider,\n    topology: 'animation-compatible',\n  });\n\n  return {\n    holoCode: injectNativeAutoRigAnnotations(\n      input.holoCode,\n      objectName,\n      modelFile,\n      input.provider,\n      autoRig\n    ),\n    traits: mergeGeneratedObjectTraits(input.traits),\n    autoRig,\n    generatedMesh: {\n      model: modelFile,\n      provider: input.provider,\n      description: input.description,\n      topology: autoRig.topology,\n    },\n    skeleton: {\n      rig: autoRig.rig,\n      pose: autoRig.pose,\n      boneCount: autoRig.boneCount,\n      standard: autoRig.animationCompatibility.standard,\n    },\n  };\n}\n\nasync function handleGenerate3DObject(args: Record<string, unknown>) {\n  const description = args.description as string;\n  const providerName = (args.provider as string) || 'meshy';\n  type TextTo3DStyle = 'realistic' | 'cartoon' | 'low-poly' | 'pbr';\n  const style = ((args.style as string) || 'pbr') as TextTo3DStyle;\n  const objectName = args.objectName as string | undefined;\n  let rig: AutoRigRigType | undefined;\n  let pose: AutoRigPose;\n\n  if (!description) {\n    return { success: false, error: 'description is required' };\n  }\n\n  try {\n    rig = normalizeGenerate3DObjectRig(args.rig);\n    pose = normalizeGenerate3DObjectPose(args.pose);\n  } catch (error: unknown) {\n    return { success: false, error: error instanceof Error ? error.message : String(error) };\n  }\n\n  try {\n    // Dynamic import to avoid loading heavy deps when not needed\n    const { MeshyProvider, TripoProvider, textTo3DToHolo } = await import(\n      '../../cli/src/importers/text-to-3d-importer' as string\n    );\n\n    let provider;\n    if (providerName === 'tripo') {\n      provider = new TripoProvider();\n    } else {\n      provider = new MeshyProvider();\n    }\n\n    const result = await textTo3DToHolo({\n      description,\n      provider,\n      style,\n      objectName,\n    });\n    const autoRigEnrichment = rig\n      ? applyNativeAutoRigToGeneratedObject({\n          holoCode: result.holoCode,\n          description,\n          provider: result.metadata.provider,\n          modelFilePath: result.modelFilePath,\n          objectName,\n          traits: result.traits,\n          rig,\n          pose,\n        })\n      : undefined;\n\n    return {\n      success: true,\n      holoCode: autoRigEnrichment?.holoCode ?? result.holoCode,\n      holoFilePath: result.holoFilePath,\n      modelFilePath: result.modelFilePath,\n      traits: autoRigEnrichment?.traits ?? result.traits,\n      provider: result.metadata.provider,\n      generationTimeMs: result.metadata.generationTimeMs,\n      generatedMesh: autoRigEnrichment?.generatedMesh,\n      autoRig: autoRigEnrichment?.autoRig,\n      skeleton: autoRigEnrichment?.skeleton,\n    };\n  } catch (error: unknown) {\n    const msg = error instanceof Error ? error.message : String(error);\n    // Check for missing API key\n    if (msg.includes('API_KEY required')) {\n      return {\n        success: false,\n        error: msg,\n        hint: 'Set MESHY_API_KEY or TRIPO_API_KEY in your environment',\n      };\n    }\n    return {\n      success: false,\n      error: msg || 'Text-to-3D generation failed',\n    };\n  }\n}\n\n// === HOLOLAND TRAINING DATA HANDLER ===\n\nasync function handleGenerateHololandTraining(args: Record<string, unknown>) {\n  const variationsPerExample = (args.variations_per_example as number) ?? 4;\n  const categoryFilter = (args.category as string) ?? 'all';\n  const outputFile = args.output_file as string | undefined;\n\n  let examples = generateHololandDataset(variationsPerExample);\n\n  if (categoryFilter !== 'all') {\n    examples = examples.filter((e) => e.metadata.category === (categoryFilter as TrainingCategory));\n  }\n\n  const jsonl = datasetToJsonl(examples);\n\n  if (outputFile) {\n    const { writeFileSync } = await import('fs');\n    const { resolve } = await import('path');\n    const filePath = resolve(process.cwd(), outputFile);\n    writeFileSync(filePath, jsonl, 'utf-8');\n    return {\n      success: true,\n      examples_count: examples.length,\n      categories: [...new Set(examples.map((e) => e.metadata.category))],\n      file_path: filePath,\n      file_size_bytes: Buffer.byteLength(jsonl, 'utf-8'),\n      message: `Generated ${examples.length} training examples → ${filePath}`,\n    };\n  }\n\n  return {\n    success: true,\n    examples_count: examples.length,\n    categories: [...new Set(examples.map((e) => e.metadata.category))],\n    jsonl,\n    message: `Generated ${examples.length} training examples`,\n  };\n}\n","/**\n * MCP Developer Tools — v5.9 \"Developer Portal\"\n *\n * 6 tools: get_api_reference, serve_preview, get_workspace_info,\n * inspect_trace_waterfall, get_dev_dashboard_state,\n * holo_generate_bindings\n *\n * @version 1.1.0\n */\n\nimport type { Tool } from '@modelcontextprotocol/sdk/types.js';\nimport { APIDocsGenerator } from './api-docs-generator';\nimport { TraceWaterfallRenderer } from '@holoscript/core';\nimport {\n  InteropBindingGenerator,\n  type GeneratedBinding,\n} from '../../core/src/interop/InteropBindingGenerator.js';\nimport type { TraceSpan } from '@holoscript/core';\n\n// =============================================================================\n// SINGLETONS\n// =============================================================================\n\nlet docsGenerator: APIDocsGenerator | null = null;\nlet waterfallRenderer: TraceWaterfallRenderer | null = null;\n\nfunction getDocsGenerator(): APIDocsGenerator {\n  if (!docsGenerator) docsGenerator = new APIDocsGenerator({ version: '6.0.0' });\n  return docsGenerator;\n}\n\nfunction getWaterfallRenderer(): TraceWaterfallRenderer {\n  if (!waterfallRenderer) waterfallRenderer = new TraceWaterfallRenderer();\n  return waterfallRenderer;\n}\n\nlet bindingGenerator: InteropBindingGenerator | null = null;\n\nfunction getBindingGenerator(): InteropBindingGenerator {\n  if (!bindingGenerator) bindingGenerator = new InteropBindingGenerator();\n  return bindingGenerator;\n}\n\nexport function resetDeveloperSingletons(): void {\n  docsGenerator = null;\n  waterfallRenderer = null;\n  bindingGenerator = null;\n}\n\n// =============================================================================\n// TOOL DEFINITIONS\n// =============================================================================\n\nexport const developerTools: Tool[] = [\n  {\n    name: 'get_api_reference',\n    description:\n      'Generate API reference documentation for all MCP tools. Returns markdown or JSON format with categories, parameters, and examples.',\n    inputSchema: {\n      type: 'object' as const,\n      properties: {\n        format: {\n          type: 'string',\n          description: 'Output format: \"markdown\" or \"json\"',\n          enum: ['markdown', 'json'],\n        },\n        category: {\n          type: 'string',\n          description: 'Filter by category name (optional)',\n        },\n      },\n      required: [],\n    },\n  },\n  {\n    name: 'serve_preview',\n    description:\n      'Get dev server state and composition preview data. Returns current files, parse status, and connected client info.',\n    inputSchema: {\n      type: 'object' as const,\n      properties: {\n        root: {\n          type: 'string',\n          description: 'Root directory to scan for compositions (defaults to working directory)',\n        },\n        extensions: {\n          type: 'array',\n          description: 'File extensions to include',\n          items: { type: 'string' },\n        },\n      },\n      required: [],\n    },\n  },\n  {\n    name: 'get_workspace_info',\n    description:\n      'Get workspace configuration, members, composition counts, and build order from holoscript.workspace.json.',\n    inputSchema: {\n      type: 'object' as const,\n      properties: {\n        root: {\n          type: 'string',\n          description: 'Workspace root directory (defaults to working directory)',\n        },\n        includeBuildOrder: {\n          type: 'boolean',\n          description: 'Whether to include build order analysis (default: true)',\n        },\n      },\n      required: [],\n    },\n  },\n  {\n    name: 'inspect_trace_waterfall',\n    description:\n      'Convert trace spans into a waterfall visualization with timing, nesting, agent colors, and critical path analysis.',\n    inputSchema: {\n      type: 'object' as const,\n      properties: {\n        spans: {\n          type: 'array',\n          description: 'Array of TraceSpan objects to visualize',\n          items: {\n            type: 'object',\n            properties: {\n              traceId: { type: 'string' },\n              spanId: { type: 'string' },\n              parentSpanId: { type: 'string' },\n              name: { type: 'string' },\n              kind: { type: 'string' },\n              startTime: { type: 'number' },\n              endTime: { type: 'number' },\n              status: { type: 'string' },\n              attributes: { type: 'object' },\n            },\n          },\n        },\n        minDuration: {\n          type: 'number',\n          description: 'Minimum span duration to display (ms)',\n        },\n      },\n      required: ['spans'],\n    },\n  },\n  {\n    name: 'holo_generate_bindings',\n    description:\n      'Generate Python or JavaScript/TypeScript bindings for a HoloScript (.hsplus) module. ' +\n      'Returns generated binding code that lets external Python or JS callers import and invoke ' +\n      'HoloScript compositions without knowing the TypeScript internals. ' +\n      'Supports D.038 developer-enabled revival — any developer can reinnovate on HoloScript from their native language.',\n    inputSchema: {\n      type: 'object' as const,\n      properties: {\n        modulePath: {\n          type: 'string',\n          description:\n            'Path to the .hsplus source file to generate bindings for (absolute or workspace-relative)',\n        },\n        targetLang: {\n          type: 'string',\n          description: 'Target language for the generated bindings',\n          enum: ['python', 'javascript', 'typescript'],\n        },\n        sourceCode: {\n          type: 'string',\n          description:\n            'HoloScript+ source code as a string (alternative to modulePath — provide one or the other). ' +\n            'Useful when the caller already has the source in memory.',\n        },\n      },\n      required: ['targetLang'],\n    },\n  },\n  {\n    name: 'get_dev_dashboard_state',\n    description:\n      'Get comprehensive developer dashboard state including composition status, trace summaries, agent registry, plugin status, and budget/usage info.',\n    inputSchema: {\n      type: 'object' as const,\n      properties: {\n        sections: {\n          type: 'array',\n          description:\n            'Which dashboard sections to include (default: all). Options: compositions, traces, agents, plugins, economy, api',\n          items: {\n            type: 'string',\n            enum: ['compositions', 'traces', 'agents', 'plugins', 'economy', 'api'],\n          },\n        },\n      },\n      required: [],\n    },\n  },\n];\n\n// =============================================================================\n// HANDLER\n// =============================================================================\n\nexport async function handleDeveloperTool(\n  name: string,\n  args: Record<string, unknown>\n): Promise<unknown> {\n  switch (name) {\n    case 'get_api_reference':\n      return handleGetApiReference(args);\n    case 'serve_preview':\n      return handleServePreview(args);\n    case 'get_workspace_info':\n      return handleGetWorkspaceInfo(args);\n    case 'inspect_trace_waterfall':\n      return handleInspectTraceWaterfall(args);\n    case 'get_dev_dashboard_state':\n      return handleGetDevDashboardState(args);\n    case 'holo_generate_bindings':\n      return handleGenerateBindings(args);\n    default:\n      throw new Error(`Unknown developer tool: ${name}`);\n  }\n}\n\n// =============================================================================\n// HANDLERS\n// =============================================================================\n\nasync function loadToolsCatalog(): Promise<Tool[]> {\n  // `tools.ts` imports this module; a dynamic import can resolve before `export const tools`\n  // is assigned. Yield and retry briefly so the circular init can complete.\n  for (let attempt = 0; attempt < 20; attempt++) {\n    await new Promise<void>((resolve) => setImmediate(resolve));\n    const mod = await import('./tools');\n    const catalog = mod.tools;\n    if (Array.isArray(catalog) && catalog.length > 0) return catalog;\n  }\n  throw new Error('MCP tools catalog failed to initialize');\n}\n\nasync function handleGetApiReference(args: Record<string, unknown>): Promise<unknown> {\n  const tools = await loadToolsCatalog();\n  const generator = getDocsGenerator();\n  const ref = generator.generate(tools);\n\n  // Filter by category if specified\n  if (args.category) {\n    ref.categories = ref.categories.filter(\n      (c) => c.name.toLowerCase() === (args.category as string).toLowerCase()\n    );\n    ref.totalTools = ref.categories.reduce((sum, c) => sum + c.tools.length, 0);\n  }\n\n  const format = (args.format as string) || 'json';\n  if (format === 'markdown') {\n    return { format: 'markdown', content: generator.toMarkdown(ref) };\n  }\n\n  return { format: 'json', reference: ref };\n}\n\nasync function handleServePreview(args: Record<string, unknown>): Promise<unknown> {\n  const { existsSync, readdirSync, readFileSync, statSync } = await import('fs');\n  const { join, extname } = await import('path');\n\n  const root = (args.root as string) || process.cwd();\n  const extensions = (args.extensions as string[]) || ['.holo', '.hs', '.hsplus'];\n\n  // Scan for compositions\n  const compositions: Array<{\n    path: string;\n    size: number;\n    lines: number;\n  }> = [];\n\n  const scan = (dir: string, depth: number): void => {\n    if (depth <= 0) return;\n    try {\n      const entries = readdirSync(dir, { withFileTypes: true });\n      for (const entry of entries) {\n        const fullPath = join(dir, entry.name);\n        if (entry.isDirectory() && !entry.name.startsWith('.') && entry.name !== 'node_modules') {\n          scan(fullPath, depth - 1);\n        } else if (entry.isFile() && extensions.includes(extname(entry.name))) {\n          const stat = statSync(fullPath);\n          const content = readFileSync(fullPath, 'utf-8');\n          compositions.push({\n            path: fullPath.replace(root, '').replace(/\\\\/g, '/'),\n            size: stat.size,\n            lines: content.split('\\n').length,\n          });\n        }\n      }\n    } catch {\n      // Skip unreadable\n    }\n  };\n\n  if (existsSync(root)) {\n    scan(root, 5);\n  }\n\n  return {\n    root,\n    compositionCount: compositions.length,\n    compositions,\n    extensions,\n    serverRunning: false, // No live server in MCP context\n  };\n}\n\nasync function handleGetWorkspaceInfo(args: Record<string, unknown>): Promise<unknown> {\n  const root = (args.root as string) || process.cwd();\n  const includeBuildOrder = args.includeBuildOrder !== false;\n\n  const { WorkspaceManager } = await import('./workspace-manager-bridge');\n\n  const manager = new WorkspaceManager(root);\n  const config = manager.load();\n\n  if (!config) {\n    return {\n      found: false,\n      root,\n      message: 'No holoscript.workspace.json found. Use `holoscript workspace init` to create one.',\n    };\n  }\n\n  const info = manager.getInfo();\n  const result: Record<string, unknown> = {\n    found: true,\n    ...info,\n  };\n\n  if (includeBuildOrder) {\n    result.buildOrder = manager.getBuildOrder();\n  }\n\n  return result;\n}\n\nasync function handleInspectTraceWaterfall(args: Record<string, unknown>): Promise<unknown> {\n  const spans = args.spans as TraceSpan[];\n  if (!spans || !Array.isArray(spans)) {\n    throw new Error('spans parameter is required and must be an array');\n  }\n\n  // Normalize span data — accept both flat (traceId/spanId at top) and nested (context) formats\n  const normalized: TraceSpan[] = spans.map((s: Record<string, unknown>) => {\n    const flat = s as Record<string, unknown>;\n    const ctx = (flat.context as Record<string, unknown>) || {};\n    const traceId = (ctx.traceId as string) || (flat.traceId as string) || '';\n    const spanId = (ctx.spanId as string) || (flat.spanId as string) || '';\n    const parentSpanId = (ctx.parentSpanId as string) || (flat.parentSpanId as string) || undefined;\n    const startTime = (flat.startTime as number) || 0;\n    const endTime = (flat.endTime as number) || 0;\n    return {\n      id: (flat.id as string) || spanId,\n      name: (flat.name as string) || 'unnamed',\n      context: {\n        traceId,\n        spanId,\n        parentSpanId,\n        traceFlags: (ctx.traceFlags as number) || 0,\n        baggage: (ctx.baggage as Record<string, string>) || {},\n      },\n      startTime,\n      endTime,\n      duration: endTime - startTime,\n      status: (flat.status as string) || 'unset',\n      statusMessage: flat.statusMessage as string | undefined,\n      attributes: (flat.attributes as Record<string, unknown>) || {},\n      events: (flat.events as Array<unknown>) || [],\n      links: (flat.links as Array<unknown>) || [],\n      kind: (flat.kind as string) || 'internal',\n    } as TraceSpan;\n  });\n\n  const renderer = getWaterfallRenderer();\n  if (args.minDuration) {\n    const customRenderer = new (TraceWaterfallRenderer as any)({\n      minDuration: args.minDuration as number,\n    });\n    return { waterfall: customRenderer.render(normalized) };\n  }\n\n  return { waterfall: renderer.render(normalized) };\n}\n\nasync function handleGetDevDashboardState(args: Record<string, unknown>): Promise<unknown> {\n  const sections = (args.sections as string[]) || [\n    'compositions',\n    'traces',\n    'agents',\n    'plugins',\n    'economy',\n    'api',\n  ];\n\n  const state: Record<string, unknown> = {};\n\n  if (sections.includes('traces')) {\n    try {\n      const { getTelemetryCollector } = await import('@holoscript/core');\n      const collector = getTelemetryCollector();\n      const stats = collector.getStats();\n      state.traces = {\n        totalSpans: stats.totalSpans,\n        activeSpans: stats.activeSpans,\n        totalEvents: stats.totalEvents,\n      };\n    } catch {\n      state.traces = { totalSpans: 0, activeSpans: 0, totalEvents: 0 };\n    }\n  }\n\n  if (sections.includes('api')) {\n    try {\n      const tools = await loadToolsCatalog();\n      const generator = getDocsGenerator();\n      const ref = generator.generate(tools);\n      state.api = {\n        totalTools: tools.length,\n        categories: ref.categories.length,\n      };\n    } catch {\n      state.api = { totalTools: 0, categories: 0 };\n    }\n  }\n\n  if (sections.includes('economy')) {\n    try {\n      const { handleEconomyTool } = await import('./economy-tools');\n      const usage = await handleEconomyTool('get_usage_summary', { period: 'monthly' });\n      state.economy = usage;\n    } catch {\n      state.economy = { period: 'monthly', summary: { totalCalls: 0 } };\n    }\n  }\n\n  if (sections.includes('agents')) {\n    try {\n      const { handleTool } = await import('./handlers');\n      const health = await handleTool('get_agent_health', {});\n      state.agents = health;\n    } catch {\n      state.agents = { agents: [], totalRegistered: 0 };\n    }\n  }\n\n  if (sections.includes('plugins')) {\n    try {\n      const { handleTool } = await import('./handlers');\n      const plugins = await handleTool('list_plugins', {});\n      state.plugins = plugins;\n    } catch {\n      state.plugins = { plugins: [], total: 0 };\n    }\n  }\n\n  if (sections.includes('compositions')) {\n    state.compositions = await handleServePreview({});\n  }\n\n  return { dashboard: state, sections, timestamp: new Date().toISOString() };\n}\n\n// =============================================================================\n// holo_generate_bindings\n// =============================================================================\n\nasync function handleGenerateBindings(args: Record<string, unknown>): Promise<unknown> {\n  const targetLang = (args.targetLang as string | undefined) ?? 'python';\n  const modulePath = (args.modulePath as string | undefined) ?? '';\n  const sourceCode = (args.sourceCode as string | undefined) ?? '';\n\n  if (!modulePath && !sourceCode) {\n    return {\n      error: 'Provide either modulePath (path to .hsplus file) or sourceCode (raw source string)',\n    };\n  }\n\n  // Parse the source — use provided code or read from disk\n  let rawSource = sourceCode;\n  if (!rawSource && modulePath) {\n    try {\n      const fs = await import('node:fs/promises');\n      rawSource = await fs.readFile(modulePath, 'utf-8');\n    } catch (err) {\n      return { error: `Could not read ${modulePath}: ${(err as Error).message}` };\n    }\n  }\n\n  // Parse with @holoscript/core parser\n  // We import HSPlusAST from the same source path as InteropBindingGenerator to\n  // avoid type-identity mismatches between dist/index and src/types.\n  type SrcAST = import('../../core/src/types/HoloScriptPlus.js').HSPlusAST;\n  let ast: SrcAST;\n  try {\n    const { parse } = await import('@holoscript/core/parser');\n    const result = parse(rawSource) as {\n      success: boolean;\n      errors: Array<{ line: number; column: number; message: string }>;\n      ast?: unknown;\n    };\n    if (!result.success) {\n      const msgs = result.errors\n        .map(\n          (e: { line: number; column: number; message: string }) =>\n            `${e.line}:${e.column} ${e.message}`\n        )\n        .join('; ');\n      return { error: `Parse errors: ${msgs}` };\n    }\n    ast = (result.ast ?? { body: [] }) as SrcAST;\n  } catch (err) {\n    return { error: `Parse failed: ${(err as Error).message}`, source: rawSource.slice(0, 200) };\n  }\n\n  const generator = getBindingGenerator();\n  const sourceLabel = modulePath || '<inline>';\n\n  try {\n    let binding: GeneratedBinding;\n    if (targetLang === 'python') {\n      binding = generator.generatePythonBindings(ast, sourceLabel);\n    } else {\n      // javascript and typescript both go through generateJSBindings;\n      // the generator honours language: 'typescript' in its metadata\n      binding = generator.generateJSBindings(ast, sourceLabel);\n      if (targetLang === 'typescript') {\n        binding = { ...binding, language: 'typescript' as const };\n      }\n    }\n\n    return {\n      language: binding.language,\n      code: binding.code,\n      exports: binding.exports,\n      exportCount: binding.exports.length,\n      metadata: binding.metadata,\n      usage:\n        targetLang === 'python'\n          ? `# Save as <module>.py, then: from <module> import *`\n          : `// Save as <module>.mjs, then: import * from './<module>.mjs'`,\n    };\n  } catch (err) {\n    return { error: `Binding generation failed: ${(err as Error).message}` };\n  }\n}\n","/**\n * holo-ci-tools.ts — MCP tool surface for HoloScript-native CI (HoloCI).\n *\n * Why this exists: HoloCI dispatch normally needs an orchestrator submit key\n * (resolved from HoloKey/env and sent as `x-mcp-api-key` to the mcp-orchestrator\n * GPU queue) — a high-privilege credential that submits fleet workloads. We do\n * NOT want that key copied into every external client's config file. Instead we\n * expose CI dispatch as an MCP tool: a Bearer-authed client (Claude Desktop,\n * Cursor, a cloud Claude Code session, …) calls `holo_ci_dispatch` with only\n * the MCP access token it already has, and THIS server makes the privileged POST\n * server-side. The orchestrator key never leaves the server.\n *\n * The gate catalog + workload builder below is a faithful TypeScript port of\n * ai-ecosystem/scripts/holo-ci/{gates,lib}.mjs. It is duplicated rather than\n * imported because HoloScript and ai-ecosystem are separate repos with no\n * shared module path. Keep the two in sync when gates change.\n *\n * ## Spend authorisation (task_1780456938486_eldw)\n *\n * Two-layer guard applied on every non-dry submit:\n *\n * 1. **Per-caller daily submit cap** — in-memory rolling-24h window, keyed by a\n *    SHA-256 fingerprint of the caller token (never stored in the clear). Default\n *    cap = `HOLOCI_DAILY_SUBMIT_CAP` env var (defaults to 3 submits/day). The\n *    server's own orchestrator key (founder seat) is exempt.  When the cap is\n *    exceeded the handler returns `ok:false` with `capExceeded:true` AND the\n *    dry-run preview so the caller can still inspect the workload.\n *\n * 2. **Token → identity → spend allowance lookup** — the caller token is hashed\n *    to a stable fingerprint and checked against a per-identity allowance table\n *    (`HOLOCI_SPEND_ALLOWANCES` env JSON, keyed by SHA-256 fingerprint). When no\n *    entry is found the caller is treated as `restricted` (cap = 1/day, no full\n *    profile).  Founder-key callers are always `unlimited`.  The allowance table\n *    can be provisioned at deploy time; a future follow-up can replace this with\n *    a live orchestrator /identity/allowance lookup once that endpoint exists.\n */\n\nimport { createHash } from 'node:crypto';\nimport { Tool } from '@modelcontextprotocol/sdk/types.js';\nimport { resolveServiceSecret } from './holokey-resolver';\n\n// ─── Gate catalog (port of gates.mjs) ───────────────────────────────────────\ntype Profile = 'quick' | 'full';\ntype GateSpec = {\n  description: string;\n  step: string;\n  profiles: Profile[];\n  resource_requirements: { max_dph: number };\n};\n\nconst HOLOSCRIPT_GATES: Record<string, GateSpec> = {\n  'type-check': {\n    description:\n      'TypeScript type check across all packages (tsc --noEmit) — fast gate that blocks expensive build/test when type errors exist',\n    step: 'pnpm exec tsc --noEmit',\n    profiles: ['quick', 'full'],\n    resource_requirements: { max_dph: 0.25 },\n  },\n  'frozen-lockfile': {\n    description:\n      'Frozen-lockfile drift gate: fail loud if any package.json ⇄ pnpm-lock.yaml is out of sync (ERR_PNPM_OUTDATED_LOCKFILE bricks deploys)',\n    step: 'node scripts/holo-ci/frozen-lockfile-check.mjs',\n    profiles: ['quick', 'full'],\n    resource_requirements: { max_dph: 0.2 },\n  },\n  lint: {\n    description: 'Lint + format + version-lane + architecture-coupling static checks',\n    step: ['pnpm lint', 'pnpm format:check', 'pnpm version:check', 'pnpm architecture:check'].join(\n      '\\n'\n    ),\n    profiles: ['quick', 'full'],\n    resource_requirements: { max_dph: 0.3 },\n  },\n  secrets: {\n    description: 'Secret scan (gitleaks — blocks ghp_/classic sk-/AKIA/private-keys; F.106)',\n    // Git-native mode (no --no-git): reads committed content via git log, never traverses\n    // gitignored node_modules. Lockstep with ai-ecosystem/scripts/holo-ci/gates.mjs (obr9 2026-06-08).\n    step: [\n      'GL=8.21.2',\n      'curl -sSfL \"https://github.com/gitleaks/gitleaks/releases/download/v${GL}/gitleaks_${GL}_linux_x64.tar.gz\" | tar -xz gitleaks',\n      'CFG=\"\"; [ -f .gitleaks.toml ] && CFG=\"--config .gitleaks.toml\"',\n      './gitleaks detect --source . $CFG --redact --no-banner --exit-code 1',\n    ].join('\\n'),\n    profiles: ['quick', 'full'],\n    resource_requirements: { max_dph: 0.2 },\n  },\n  build: {\n    description: 'Build all @holoscript/* packages (pnpm build)',\n    step: 'pnpm build',\n    profiles: ['full'],\n    resource_requirements: { max_dph: 0.4 },\n  },\n  test: {\n    description: 'Core test suite (build + pnpm test:coverage || pnpm test)',\n    step: 'pnpm build\\npnpm test:coverage || pnpm test',\n    profiles: ['full'],\n    resource_requirements: { max_dph: 0.55 },\n  },\n  security: {\n    description: 'Dependency audit (pnpm audit --prod, high+ severities)',\n    step: 'pnpm audit --prod --audit-level high',\n    profiles: ['full'],\n    resource_requirements: { max_dph: 0.3 },\n  },\n  // W.667 BLOCKING release gate — packs+installs the whole claim-bearing publish set\n  // cold (optional/peer omitted) and probes ESM+CJS barrels, the ./runtime subpath, and\n  // optional-peer absence. Omitting it here would let holo_ci_dispatch trigger a CI run\n  // that silently skips the fence that caught non-installable @holoscript/core (W.667/W.681).\n  // Must stay in lockstep with the canonical scripts/holo-ci/gates.mjs cold-consume gate.\n  'cold-consume': {\n    description:\n      'Cold-consume release gate (W.667, deepened): --local pack + install (omit optional/peer) the whole publish set; barrel (ESM+CJS) + ./runtime cold-import + optional-peer-absence; @holoscript subpath leak = fail, external peer = info',\n    step: [\n      'pnpm --filter @holoscript/core --filter @holoscript/engine --filter @holoscript/mesh --filter @holoscript/framework --filter @holoscript/runtime --filter @holoscript/cli build',\n      'node scripts/cold-consume-check.mjs --local',\n    ].join('\\n'),\n    profiles: ['full'],\n    resource_requirements: { max_dph: 0.5 },\n  },\n  // Exposes the class of Railway build failures caused by tsc --emitDeclarationOnly\n  // picking up test files (exposed after || true suppression removal, 2568f997e).\n  // Fast static analysis (~1s) — no Docker daemon, no actual builds. Checks that\n  // every package using tsc in the studio Dockerfile has a tsconfig.json that\n  // excludes test files. Runs in BOTH profiles: instant gate, high blast radius\n  // (a tsconfig.json without test exclusions + a future test importing a removed\n  // export bricks Railway studio deploys immediately on the next push).\n  // Lockstep with the canonical scripts/holo-ci/gates.mjs dockerfile-static-check gate.\n  'dockerfile-static-check': {\n    description:\n      'Studio Dockerfile static check: every package using tsc --emitDeclarationOnly must exclude test files in tsconfig.json (prevents the agent-protocol class of Railway build failures)',\n    step: 'node scripts/validate-dockerfile-build.mjs',\n    profiles: ['quick', 'full'],\n    resource_requirements: { max_dph: 0.2 },\n  },\n  // W.726 — cross-platform path portability. Cloud Claude/Codex sessions author on Linux;\n  // the founder's seats run Windows; services deploy to Railway (Linux). Hardcoded C:/Users /\n  // drive-root / machine-home paths in packages/*/src break the Linux deploy target. Fast\n  // static check (no build, no daemon). Runs on EVERY push incl. claude/* & codex/* branches\n  // so portability bugs are caught at the source instead of when a branch strands (W.725).\n  // Lockstep with the canonical scripts/holo-ci/check-cross-platform-paths.mjs + gates.mjs.\n  'cross-platform-paths': {\n    description:\n      'Cross-platform path portability gate (W.726): fail on hardcoded C:/Users / drive-root / machine-home literals in packages/*/src that break across the cloud-Linux / Windows-local fleet and the Railway deploy target',\n    step: 'node scripts/holo-ci/check-cross-platform-paths.mjs',\n    profiles: ['quick', 'full'],\n    resource_requirements: { max_dph: 0.2 },\n  },\n  // Docker-entry-drift: the Docker core build (scripts/docker/tsup.core.docker.cjs) has a\n  // SEPARATE entry list from tsup.config.ts. A core subpath added to the standard config +\n  // exports + a service import, but not the Docker config, makes the runtime image omit\n  // dist/<subpath>/index.cjs → the service crash-loops at boot (MODULE_NOT_FOUND). 5 prod\n  // outages of this exact class (hololand/world/simulation-solver-factory/policy). Fast\n  // static check. Lockstep with the canonical scripts/holo-ci/gates.mjs.\n  'docker-core-entries': {\n    description:\n      'Docker-entry-drift gate: every @holoscript/core subpath a Docker-built service imports must have an entry in scripts/docker/tsup.core.docker.cjs, else the runtime image omits dist/<subpath>/index.cjs and the service crash-loops at boot (MODULE_NOT_FOUND)',\n    step: 'node scripts/holo-ci/check-docker-core-entries.mjs',\n    profiles: ['quick', 'full'],\n    resource_requirements: { max_dph: 0.2 },\n  },\n  'doctrine-slots': {\n    description:\n      'Doctrine-slot falsifier: required local HoloCI breadcrumb slots must be non-null so hook registration cannot masquerade as execution',\n    step: 'HOLOCI_ALLOW_MISSING_WORKLOAD=1 pnpm verify:doctrine',\n    profiles: ['quick', 'full'],\n    resource_requirements: { max_dph: 0.2 },\n  },\n  // FREEZE RATCHET (render-surface dogfooding ruling 2026-06-05; D.012/D.014/I.018).\n  // Production render .tsx (r3f-renderer + studio) must be HS-native (compiler-emitted, carrying\n  // an \"@generated by HoloScript\" header) or a compiler example; net-new hand-authored render is\n  // blocked, existing hand-authored is grandfathered into an allowlist. Fast static check.\n  // Lockstep with the canonical scripts/holo-ci/gates.mjs render-surface gate.\n  'render-surface': {\n    description:\n      'Render-surface native freeze: production render .tsx must be compiler-emitted (HS-native) or a compiler example; net-new hand-authored render is blocked (grandfathered legacy allowlisted)',\n    step: 'node scripts/holo-ci/check-render-surface-native.mjs',\n    profiles: ['quick', 'full'],\n    resource_requirements: { max_dph: 0.2 },\n  },\n  // ONE-MEANING ratchet (language stratum taxonomy 2026-07-17; docs/spec/language-architecture.md §6.2).\n  // The meaning stratum (HoloMeaning, @holoscript/meaning) is defined once and imported everywhere;\n  // a second definition of a canonical resolver name, the resolution-record union, or the gap-reason\n  // enum outside the canonical homes is a mirror and fails. Fast static check, modeled on render-surface.\n  'language-strata': {\n    description:\n      'Language-strata freeze: the meaning-stratum contract (HoloMeaning) is defined once — resolver names, the resolution-record union, and the gap-reason enum may not be re-declared outside the canonical homes',\n    step: 'node scripts/holo-ci/check-language-strata.mjs --strict',\n    profiles: ['quick', 'full'],\n    resource_requirements: { max_dph: 0.2 },\n  },\n  // Language hardening gates (language-architecture.md §5/§6.3/§6.5, 2026-07-17). Report-only where a\n  // known backlog exists (family-admission: 3 grandfathered families lack family-scoped gap codes);\n  // strict where green (verifier-of-record on this repo's reward terms, also wired at the pre-commit\n  // dev floor). grammar-authority chains check:compiler-wasm-drift then differentially regression-tests\n  // the surface parsers against the WASM authority baseline — full profile (walks the .hsplus corpus).\n  'family-admission': {\n    description:\n      'Family-admission: every admitted meaning family emits a family-scoped gap code (§4.2), not a collapsed base bucket — strict since 2026-07-17 (the grandfathered backlog cleared)',\n    step: 'node scripts/holo-ci/check-family-admission.mjs --strict',\n    profiles: ['quick', 'full'],\n    resource_requirements: { max_dph: 0.2 },\n  },\n  'verifier-of-record': {\n    description:\n      'Verifier of record: corpus/reward files emitting abstention labels must route through the shipped gradeByResolver, never a fork (§6.3)',\n    step: 'node scripts/holo-ci/check-verifier-of-record.mjs --strict',\n    profiles: ['quick', 'full'],\n    resource_requirements: { max_dph: 0.2 },\n  },\n  'grammar-authority': {\n    description:\n      'Grammar authority: the surface grammar has one growing authority (Rust/WASM) and its parse coverage never regresses (§5) — chains compiler-wasm-drift then the differential regression gate',\n    step: 'node scripts/holo-ci/check-grammar-authority.mjs',\n    profiles: ['full'],\n    resource_requirements: { max_dph: 0.4 },\n  },\n  // The executable spec (I2, spec-as-corpus): normative source+verdict cases replayed against the\n  // real WASM authority artifact. Distinct from the ecosystem artifact-admission \"conformance\"\n  // subsystem (worlds/shards/NPCs JSON rules — a different domain that never parses source).\n  // A drifted verdict = the language no longer means what the spec says; the fix is either the\n  // grammar change or a reviewed corpus-case update in the same commit, never silent drift.\n  'spec-corpus': {\n    description:\n      'Executable spec corpus: every normative language case (source + expected verdict) holds against the WASM grammar authority; verdict drift fails and requires a reviewed corpus update + manifest re-pin',\n    step: 'node scripts/holo-ci/check-spec-corpus.mjs --strict',\n    profiles: ['quick', 'full'],\n    resource_requirements: { max_dph: 0.2 },\n  },\n  // WRAP-WITH-RECEIPTS coverage ratchet (dependency-sovereignty-ladder, 2026-07-16).\n  // Every setRequestHandler(CallToolRequestSchema) fold point under packages/mcp-server/src\n  // must route through gateToolCall (tool-call-gate.ts) — the single typed gate that emits\n  // one NDJSON receipt per tool call and hosts the FounderGate/x402/envelope-check seam.\n  // Fast static check, modeled on the render-surface freeze above.\n  'mcp-gate-coverage': {\n    description:\n      'MCP gate coverage ratchet: every setRequestHandler(CallToolRequestSchema) site under packages/mcp-server/src must route through gateToolCall (per-call NDJSON receipts + typed check seam)',\n    step: 'node scripts/holo-ci/check-mcp-gate-coverage.mjs',\n    profiles: ['quick', 'full'],\n    resource_requirements: { max_dph: 0.2 },\n  },\n  // CHOKEPOINT-CAPTURE ratchet (dependency-sovereignty-ladder, 2026-07-16).\n  // Raw fetch() sites hardcoding the Railway orchestrator URL literal bypass the typed\n  // ResilientOrchestratorFetch client (packages/connector-core — Jetson-first cascade, short\n  // LAN timeout, circuit breaker), blocking the Jetson-primary orchestrator migration.\n  // Existing raw-literal files are grandfathered into a checked-in baseline; NEW files are\n  // blocked (CHOKEPOINT-GREW). Fast static check, modeled on the render-surface freeze above.\n  'orchestrator-fetch-canonical': {\n    description:\n      'Orchestrator-fetch chokepoint ratchet: new files hardcoding the raw Railway orchestrator URL (outside connector-core/@holoscript/config) are blocked; route through ResilientOrchestratorFetch (Jetson-first typed client)',\n    step: 'node scripts/holo-ci/check-orchestrator-fetch-canonical.mjs',\n    profiles: ['quick', 'full'],\n    resource_requirements: { max_dph: 0.2 },\n  },\n  // Retro-wire (F.073 sister): check-publish-surface.mjs was an orphan gate (run by nobody).\n  // Pins the published npm surface to an explicit allowlist + flags description mojibake.\n  // Lockstep with the canonical scripts/holo-ci/gates.mjs publish-surface gate.\n  'publish-surface': {\n    description:\n      'Publish-surface bound: published (private:false) @holoscript packages must match the explicit allowlist; no mojibake in descriptions (W.669 surface-growth fence)',\n    step: 'node scripts/holo-ci/check-publish-surface.mjs',\n    profiles: ['quick', 'full'],\n    resource_requirements: { max_dph: 0.2 },\n  },\n};\n\nconst HOLOLAND_GATES: Record<string, GateSpec> = {\n  'type-check': {\n    description: 'HoloLand TypeScript type check (tsc --noEmit)',\n    step: 'pnpm exec tsc --noEmit',\n    profiles: ['quick', 'full'],\n    resource_requirements: { max_dph: 0.25 },\n  },\n  lint: {\n    description: 'HoloLand lint gate (pnpm lint)',\n    step: 'pnpm lint',\n    profiles: ['quick', 'full'],\n    resource_requirements: { max_dph: 0.3 },\n  },\n  secrets: {\n    description: 'Secret scan (gitleaks — blocks ghp_/classic sk-/AKIA/private-keys; F.106)',\n    // Git-native mode (no --no-git): reads committed content via git log, never traverses\n    // gitignored node_modules. Lockstep with ai-ecosystem/scripts/holo-ci/gates.mjs (obr9 2026-06-08).\n    step: [\n      'GL=8.21.2',\n      'curl -sSfL \"https://github.com/gitleaks/gitleaks/releases/download/v${GL}/gitleaks_${GL}_linux_x64.tar.gz\" | tar -xz gitleaks',\n      'CFG=\"\"; [ -f .gitleaks.toml ] && CFG=\"--config .gitleaks.toml\"',\n      './gitleaks detect --source . $CFG --redact --no-banner --exit-code 1',\n    ].join('\\n'),\n    profiles: ['quick', 'full'],\n    resource_requirements: { max_dph: 0.2 },\n  },\n  build: {\n    description: 'HoloLand workspace build (pnpm build)',\n    step: 'pnpm build',\n    profiles: ['full'],\n    resource_requirements: { max_dph: 0.4 },\n  },\n  test: {\n    description: 'HoloLand root adapter tests plus workspace tests',\n    step: ['pnpm test:holoshell-holomap-replay-preview', 'pnpm test'].join('\\n'),\n    profiles: ['full'],\n    resource_requirements: { max_dph: 0.45 },\n  },\n  security: {\n    description: 'HoloLand dependency audit (pnpm audit --prod, high+ severities)',\n    step: 'pnpm audit --prod --audit-level high',\n    profiles: ['full'],\n    resource_requirements: { max_dph: 0.3 },\n  },\n};\n\n/** Generic gate catalog for external (non-HoloScript, non-Hololand) repos registered via HOLOCI_EXTRA_REPOS. */\nconst GENERIC_GATES: Record<string, GateSpec> = {\n  install: {\n    description: 'Dependency install gate (pnpm install --frozen-lockfile or npm ci)',\n    step: [\n      'if [ -f pnpm-lock.yaml ]; then corepack enable >/dev/null 2>&1 || npm i -g pnpm >/dev/null 2>&1; pnpm install --frozen-lockfile',\n      'elif [ -f package-lock.json ]; then npm ci',\n      'else echo \"no lockfile — skipping install gate\"; fi',\n    ].join('\\n'),\n    profiles: ['quick', 'full'],\n    resource_requirements: { max_dph: 0.2 },\n  },\n  secrets: {\n    description: 'Secret scan (gitleaks — blocks ghp_/classic sk-/AKIA/private-keys; F.106)',\n    // Git-native mode (no --no-git): reads committed content via git log, never traverses\n    // gitignored node_modules. Lockstep with ai-ecosystem/scripts/holo-ci/gates.mjs (obr9 2026-06-08).\n    step: [\n      'GL=8.21.2',\n      'curl -sSfL \"https://github.com/gitleaks/gitleaks/releases/download/v${GL}/gitleaks_${GL}_linux_x64.tar.gz\" | tar -xz gitleaks',\n      'CFG=\"\"; [ -f .gitleaks.toml ] && CFG=\"--config .gitleaks.toml\"',\n      './gitleaks detect --source . $CFG --redact --no-banner --exit-code 1',\n    ].join('\\n'),\n    profiles: ['quick', 'full'],\n    resource_requirements: { max_dph: 0.2 },\n  },\n  lint: {\n    description: 'Generic lint gate (pnpm lint --if-present)',\n    step: 'pnpm run --if-present lint || npm run --if-present lint || true',\n    profiles: ['quick', 'full'],\n    resource_requirements: { max_dph: 0.25 },\n  },\n  test: {\n    description: 'Generic test gate (pnpm test --if-present)',\n    step: 'pnpm run --if-present test || npm run --if-present test || true',\n    profiles: ['full'],\n    resource_requirements: { max_dph: 0.35 },\n  },\n};\n\ntype RepoConfig = { workspaceRoot: string; gates: Record<string, GateSpec> };\n\nconst REPO_CONFIGS: Record<string, RepoConfig> = {\n  'brianonbased-dev/HoloScript': {\n    workspaceRoot: '/workspace/HoloScript',\n    gates: HOLOSCRIPT_GATES,\n  },\n  'brianonbased-dev/Hololand': {\n    workspaceRoot: '/workspace/Hololand',\n    gates: HOLOLAND_GATES,\n  },\n};\n\n// Runtime-extensible repo registry: HOLOCI_EXTRA_REPOS env var (JSON array of\n// {repo: \"owner/name\", workspace_root?: \"/workspace/...\"}) adds repos at startup\n// without code changes. Extra repos use GENERIC_GATES (install+secrets+lint+test).\n// Format: '[{\"repo\":\"acme/myapp\"},{\"repo\":\"acme/api\",\"workspace_root\":\"/workspace/acme-api\"}]'\ntry {\n  const extra = process.env.HOLOCI_EXTRA_REPOS?.trim();\n  if (extra) {\n    const entries = JSON.parse(extra) as Array<{ repo: string; workspace_root?: string }>;\n    for (const { repo, workspace_root } of entries) {\n      if (typeof repo === 'string' && /^[A-Za-z0-9_.-]+\\/[A-Za-z0-9_.-]+$/.test(repo)) {\n        const key = repo.trim();\n        if (!REPO_CONFIGS[key]) {\n          REPO_CONFIGS[key] = {\n            workspaceRoot: workspace_root ?? `/workspace/${key.replace('/', '-')}`,\n            gates: GENERIC_GATES,\n          };\n        }\n      }\n    }\n  }\n} catch {\n  // Bad JSON — ignore; only first-party repos are dispatched.\n}\n\n/** Repos this tool will dispatch for. Includes HOLOCI_EXTRA_REPOS at startup. */\nconst ALLOWED_REPOS = Object.keys(REPO_CONFIGS);\n\nfunction normalizedRepoKey(repo: string): string {\n  const value = String(repo || 'brianonbased-dev/HoloScript').trim();\n  const match = value.match(/([^/:]+\\/[^/]+?)(?:\\.git)?$/);\n  const key = match ? match[1] : value;\n  return ALLOWED_REPOS.find((c) => c.toLowerCase() === key.toLowerCase()) || key;\n}\n\n// ─── Bid policy (port of vastai-bid-policy.mjs, the default CI path) ──────────\nfunction roundBidPrice(n: number): number {\n  return Number(n.toFixed(4));\n}\n\n/**\n * Resolve the vast.ai resource requirements for a checkpointable, interruptible\n * CI job. Mirrors applyVastBidPolicyToResourceRequirements for the policy path\n * every CI gate uses (checkpointable=true, rentalMarket='policy', maxDph set).\n */\nfunction applyBidPolicy(rr: { max_dph: number }): Record<string, unknown> {\n  // policy path: checkpointable interruptible, bid = min(maxDph)\n  return {\n    max_dph: rr.max_dph,\n    checkpointable: true,\n    restartable: true,\n    rental_market: 'interruptible',\n    bid_policy_source: 'policy',\n    bid_price: roundBidPrice(rr.max_dph),\n  };\n}\n\n// ─── Input validation (these values land in shell commands — guard hard) ─────\nconst SHA_RE = /^[0-9a-f]{7,40}$/i;\nconst REPO_RE = /^[A-Za-z0-9_.-]+\\/[A-Za-z0-9_.-]+$/;\n\nfunction assertSafeRepo(repo: string): void {\n  if (!REPO_RE.test(repo)) throw new Error(`unsafe repo slug \"${repo}\"`);\n}\n\n/** Shell prologue every gate runs first: land the exact commit, install. */\nfunction prologue(repo: string, sha: string, workspaceRoot: string): string {\n  assertSafeRepo(repo);\n  return [\n    'set -euo pipefail',\n    `WORKSPACE_ROOT=\"\\${WORKSPACE_ROOT:-${workspaceRoot}}\"`,\n    'if [ ! -d \"$WORKSPACE_ROOT/.git\" ]; then',\n    '  mkdir -p \"$(dirname \"$WORKSPACE_ROOT\")\"',\n    `  git clone --quiet \"https://github.com/${repo}.git\" \"$WORKSPACE_ROOT\"`,\n    'fi',\n    'cd \"$WORKSPACE_ROOT\"',\n    `git remote set-url origin \"https://github.com/${repo}.git\" >/dev/null 2>&1 || true`,\n    `git fetch --quiet --depth 1 origin ${sha}`,\n    `git checkout --quiet --force ${sha}`,\n    'corepack enable >/dev/null 2>&1 || true',\n    'pnpm install --frozen-lockfile',\n  ].join('\\n');\n}\n\nexport type HoloCiWorkload = {\n  workload: {\n    id: string;\n    name: string;\n    description: string;\n    lane: string;\n    jobs: Array<Record<string, unknown>>;\n  };\n  contexts: string[];\n};\n\n/** Build a HoloWorkload for a CI run (port of buildWorkload in gates.mjs). */\nexport function buildWorkload(opts: {\n  repo: string;\n  sha: string;\n  profile?: Profile;\n  tier?: 'T1' | 'T2' | 'T3';\n  lane?: 'ci' | 'ci-public';\n}): HoloCiWorkload {\n  const { sha, profile = 'full', tier = 'T2', lane = 'ci' } = opts;\n  if (!SHA_RE.test(sha)) throw new Error(`unsafe commit sha \"${sha}\" (expected 7–40 hex chars)`);\n  const repoKey = normalizedRepoKey(opts.repo);\n  if (!ALLOWED_REPOS.includes(repoKey)) {\n    throw new Error(\n      `repo \"${repoKey}\" is not allowed for CI dispatch (allowed: ${ALLOWED_REPOS.join(', ')})`\n    );\n  }\n  const { workspaceRoot, gates } = REPO_CONFIGS[repoKey];\n  const shortSha = sha.slice(0, 8);\n  const selected = Object.entries(gates).filter(([, g]) => g.profiles.includes(profile));\n  if (selected.length === 0) throw new Error(`no gates match profile \"${profile}\"`);\n\n  const jobs = selected.map(([id, g]) => ({\n    id,\n    description: `[CI ${shortSha}] ${g.description}`,\n    command: prologue(repoKey, sha, workspaceRoot) + '\\n' + g.step,\n    workspace_root: workspaceRoot,\n    repo: repoKey,\n    tier,\n    requires_gpu: false,\n    resource_requirements: applyBidPolicy(g.resource_requirements),\n  }));\n\n  return {\n    workload: {\n      id: `ci-${shortSha}-${Date.now().toString(36)}`,\n      name: `holo-ci ${repoKey}@${shortSha} (${profile})`,\n      description: `Native CI run for ${repoKey} @ ${sha} — profile=${profile}`,\n      lane,\n      jobs,\n    },\n    contexts: jobs.map((j) => `holo-ci/${j.id}`),\n  };\n}\n\n// ─── Orchestrator submit (server-side; uses the server's own key) ────────────\nconst ORCHESTRATOR_KEY_NAMES = [\n  'HOLOSCRIPT_ORCHESTRATOR_API_KEY',\n  'MCP_ORCHESTRATOR_API_KEY',\n  'ORCHESTRATOR_API_KEY',\n  'MCP_API_KEY',\n  'HOLOSCRIPT_API_KEY',\n] as const;\n\nfunction readEnvOrchestratorKey(): string {\n  return (\n    process.env.HOLOSCRIPT_ORCHESTRATOR_API_KEY ||\n    process.env.MCP_ORCHESTRATOR_API_KEY ||\n    process.env.ORCHESTRATOR_API_KEY ||\n    process.env.MCP_API_KEY ||\n    process.env.HOLOSCRIPT_API_KEY ||\n    ''\n  );\n}\n\nasync function resolveOrchestratorKey(): Promise<string> {\n  for (const name of ORCHESTRATOR_KEY_NAMES) {\n    const value = await resolveServiceSecret(name);\n    if (value) return value;\n  }\n  return '';\n}\n\nfunction orchestratorUrl(): string {\n  return (\n    process.env.MCP_ORCHESTRATOR_URL || 'https://mcp-orchestrator-production-45f9.up.railway.app'\n  ).replace(/\\/$/, '');\n}\n\n// ─── Per-caller spend authorisation ─────────────────────────────────────────\n\n/**\n * Tier of spend authority granted to a caller.\n *\n * - `founder`     – unlimited submits, any profile.\n * - `trusted`     – up to HOLOCI_DAILY_SUBMIT_CAP (default 3) submits/day, any profile.\n * - `restricted`  – cap capped at 1/day, quick-profile only (no full-profile GPU spend).\n */\ntype CallerTier = 'founder' | 'trusted' | 'restricted';\n\n/** SHA-256 of a raw token string (hex, 64 chars). Never log the token itself. */\nfunction tokenFingerprint(token: string): string {\n  return createHash('sha256').update(token).digest('hex');\n}\n\n/**\n * Resolve caller tier from the token fingerprint.\n *\n * Priority:\n * 1. Fingerprint matches the server's own orchestrator key → founder (unlimited).\n * 2. `HOLOCI_SPEND_ALLOWANCES` JSON env var contains the fingerprint → use declared tier.\n * 3. Fallback → restricted.\n *\n * `HOLOCI_SPEND_ALLOWANCES` format (JSON object):\n *   { \"<sha256-fingerprint>\": \"trusted\" | \"founder\" | \"restricted\", ... }\n */\nfunction resolveCallerTier(callerFingerprint: string): CallerTier {\n  // Server's env-present orchestrator key is always founder-tier (self-dispatch).\n  const serverKey = readEnvOrchestratorKey();\n  if (serverKey && tokenFingerprint(serverKey) === callerFingerprint) return 'founder';\n\n  // Provisioned allowance table (deploy-time env JSON).\n  const raw = process.env.HOLOCI_SPEND_ALLOWANCES || '';\n  if (raw) {\n    try {\n      const table = JSON.parse(raw) as Record<string, string>;\n      const tier = table[callerFingerprint];\n      if (tier === 'founder' || tier === 'trusted' || tier === 'restricted') return tier;\n    } catch {\n      // Malformed env — fail safe to restricted.\n    }\n  }\n\n  return 'restricted';\n}\n\n/**\n * Rolling-24h submit counter, keyed by caller fingerprint.\n * Each entry is a list of submit timestamps (ms since epoch).\n * In-memory only — resets on server restart (intentional: short-lived guard,\n * not a durable audit log). A follow-up can persist to Redis if needed.\n */\nconst _submitLedger = new Map<string, number[]>();\n\nconst WINDOW_MS = 24 * 60 * 60 * 1000; // 24 hours\n\n/** Returns how many submits the caller has made in the last 24 h. */\nfunction recentSubmitCount(fingerprint: string, nowMs: number = Date.now()): number {\n  const ts = _submitLedger.get(fingerprint) ?? [];\n  return ts.filter((t) => nowMs - t < WINDOW_MS).length;\n}\n\n/** Record a new submit for the caller. Prunes entries older than 24 h. */\nfunction recordSubmit(fingerprint: string, nowMs: number = Date.now()): void {\n  const ts = (_submitLedger.get(fingerprint) ?? []).filter((t) => nowMs - t < WINDOW_MS);\n  ts.push(nowMs);\n  _submitLedger.set(fingerprint, ts);\n}\n\n/** Test-only: reset the ledger. */\nexport function resetSubmitLedger(): void {\n  _submitLedger.clear();\n}\n\n/**\n * Effective daily cap for a caller tier.\n * `HOLOCI_DAILY_SUBMIT_CAP` overrides the trusted tier cap.\n */\nfunction effectiveCap(tier: CallerTier): number {\n  if (tier === 'founder') return Infinity;\n  const envCap = Number(process.env.HOLOCI_DAILY_SUBMIT_CAP || '');\n  const trustedCap = Number.isFinite(envCap) && envCap > 0 ? envCap : 3;\n  return tier === 'trusted' ? trustedCap : 1; // restricted = 1/day\n}\n\n/**\n * Gate a non-dry submit against the per-caller spend policy.\n *\n * Returns `null` if the submit is allowed; otherwise returns the error payload\n * the handler should return (always includes the dry-run workload preview so\n * the caller can still see what would have run).\n *\n * @param callerToken  Raw bearer token or MCP key from the caller. Hashed before use.\n *                     Pass `undefined` when the caller is the stdio/local process\n *                     (trusted unconditionally — no network attacker path).\n * @param profile      Workload profile the caller is requesting.\n * @param dryPreview   Workload preview to attach to error responses.\n */\nfunction checkSpendAuthz(\n  callerToken: string | undefined,\n  profile: Profile,\n  dryPreview: HoloCiWorkload\n): null | Record<string, unknown> {\n  // stdio / local process — no token, fully trusted (no network path).\n  if (!callerToken) return null;\n\n  const fingerprint = tokenFingerprint(callerToken);\n  const tier = resolveCallerTier(fingerprint);\n  const cap = effectiveCap(tier);\n  const used = recentSubmitCount(fingerprint);\n\n  // Tier check: restricted callers may not submit full-profile workloads.\n  if (tier === 'restricted' && profile === 'full') {\n    return {\n      ok: false,\n      capExceeded: false,\n      tierDenied: true,\n      tier,\n      error:\n        'Full-profile GPU workloads require a trusted or founder token. ' +\n        'Use profile:\"quick\" or contact the server operator to upgrade your token tier.',\n      dryRunPreview: dryPreview,\n    };\n  }\n\n  // Daily cap check.\n  if (used >= cap) {\n    return {\n      ok: false,\n      capExceeded: true,\n      tier,\n      used,\n      cap: cap === Infinity ? null : cap,\n      resetInMs: WINDOW_MS, // approximate (client can retry after ~24 h)\n      error: `Daily CI submit cap reached (${used}/${cap === Infinity ? '∞' : cap} in last 24 h). Re-run with dryRun:true to preview the workload without spending.`,\n      dryRunPreview: dryPreview,\n    };\n  }\n\n  return null; // allowed\n}\n\n// ─── Shared helpers (used by MCP tool handler + GitHub webhook handler) ──────\n\n/**\n * Post GitHub commit statuses for every CI gate context.\n * Requires GITHUB_TOKEN env var with repo:status scope.\n * Non-fatal: silently skips when the token is absent (dev / misconfigured).\n */\nexport async function postGithubStatuses(\n  repo: string,\n  sha: string,\n  contexts: string[],\n  state: 'pending' | 'success' | 'failure' | 'error',\n  description: string\n): Promise<void> {\n  // GITHUB_TOKEN is a known-invalid ambient token on this machine (lib.mjs note).\n  // Use PERSONAL_ACCESS_TOKEN or PAT_TOKEN — the real credentials in .env.\n  const token =\n    process.env.PERSONAL_ACCESS_TOKEN || process.env.PAT_TOKEN || process.env.GITHUB_TOKEN || '';\n  if (!token) return;\n  const targetUrl = `https://github.com/${repo}/commit/${sha}`;\n  await Promise.allSettled(\n    contexts.map((context) =>\n      fetch(`https://api.github.com/repos/${repo}/statuses/${sha}`, {\n        method: 'POST',\n        headers: {\n          Authorization: `Bearer ${token}`,\n          Accept: 'application/vnd.github+json',\n          'Content-Type': 'application/json',\n          'X-GitHub-Api-Version': '2022-11-28',\n        },\n        body: JSON.stringify({ state, context, description, target_url: targetUrl }),\n        signal: AbortSignal.timeout(10_000),\n      }).catch(() => {\n        /* non-fatal */\n      })\n    )\n  );\n}\n\n/**\n * Submit a pre-built workload to the fleet orchestrator.\n * Uses the server's own HoloKey/env-resolved orchestrator key.\n *\n * Returns `jobIdToGate`: a map from orchestrator job_id → logical gate name.\n * The orchestrator assigns its own IDs on submit and does not persist our logical\n * gate names, so we build this map from the submit response order (which mirrors\n * the order of workload.jobs) — same approach as dispatch.mjs.\n */\nexport async function submitWorkload(workload: HoloCiWorkload['workload']): Promise<{\n  ok: boolean;\n  workloadId?: string;\n  jobIdToGate?: Record<string, string>;\n  error?: string;\n}> {\n  const apiKey = await resolveOrchestratorKey();\n  if (!apiKey) {\n    return {\n      ok: false,\n      error:\n        'orchestrator key not provisioned via HoloKey/env (HOLOSCRIPT_ORCHESTRATOR_API_KEY / MCP_ORCHESTRATOR_API_KEY / ORCHESTRATOR_API_KEY / MCP_API_KEY / HOLOSCRIPT_API_KEY unset; HOLOSCRIPT_MCP_API_KEY and HOLOMESH_API_KEY are not fleet-submit keys)',\n    };\n  }\n  try {\n    const res = await fetch(`${orchestratorUrl()}/gpu/workload`, {\n      method: 'POST',\n      headers: {\n        'Content-Type': 'application/json; charset=utf-8',\n        'x-mcp-api-key': apiKey,\n      },\n      body: JSON.stringify(workload),\n      signal: AbortSignal.timeout(20_000),\n    });\n    if (!res.ok) {\n      return { ok: false, error: `orchestrator /gpu/workload → ${res.status}` };\n    }\n    const parsed = await res.json().catch(() => ({}) as Record<string, unknown>);\n    const wlId =\n      (parsed as { id?: string; workload_id?: string })?.id ??\n      (parsed as { workload_id?: string })?.workload_id ??\n      workload.id;\n    // Build job_id → gate name from submit response order (order mirrors workload.jobs).\n    const jobIdToGate: Record<string, string> = {};\n    const returnedJobs = (parsed as { jobs?: Array<{ job_id?: string }> }).jobs ?? [];\n    returnedJobs.forEach((j, i) => {\n      const gateId = workload.jobs[i]?.id as string | undefined;\n      if (j.job_id && gateId) jobIdToGate[j.job_id] = gateId;\n    });\n    return { ok: true, workloadId: wlId, jobIdToGate };\n  } catch (err) {\n    return {\n      ok: false,\n      error: `orchestrator submit failed: ${err instanceof Error ? err.message : String(err)}`,\n    };\n  }\n}\n\ntype WorkloadStatusResponse = {\n  done: number;\n  failed: number;\n  total: number;\n  queued: number;\n  running: number;\n  blocked: number;\n  jobs?: Array<{ id: string; status?: string; error?: string; gpu_seat?: string }>;\n};\n\n/**\n * Background poll: wait for a submitted workload to finish, then post per-gate\n * and rollup commit statuses to GitHub. Fire-and-forget — callers should not await.\n *\n * Uses the same job_id → gate name map that dispatch.mjs builds on submit, since\n * the orchestrator assigns its own IDs and does not persist our logical gate names.\n */\nexport async function pollWorkloadAndReport(opts: {\n  repo: string;\n  sha: string;\n  workloadId: string;\n  jobIdToGate: Record<string, string>;\n  timeoutMs?: number;\n}): Promise<void> {\n  const { repo, sha, workloadId, jobIdToGate, timeoutMs = 10 * 60 * 1000 } = opts;\n  const apiKey = readEnvOrchestratorKey();\n  if (!apiKey) return;\n\n  const deadline = Date.now() + timeoutMs;\n  const POLL_MS = 20_000;\n  let status: WorkloadStatusResponse | null = null;\n\n  while (Date.now() < deadline) {\n    try {\n      const res = await fetch(`${orchestratorUrl()}/gpu/workload/${workloadId}`, {\n        headers: { 'x-mcp-api-key': apiKey },\n        signal: AbortSignal.timeout(10_000),\n      });\n      if (res.ok) {\n        status = (await res.json()) as WorkloadStatusResponse;\n        if (status.queued + status.blocked + status.running === 0) break;\n      }\n    } catch {\n      /* transient error — keep polling */\n    }\n    if (Date.now() >= deadline) break;\n    await new Promise<void>((r) => setTimeout(r, POLL_MS));\n  }\n\n  if (!status) return;\n\n  const terminal = status.queued + status.blocked + status.running === 0;\n\n  // Per-gate statuses\n  for (const job of status.jobs ?? []) {\n    const gate = jobIdToGate[job.id] ?? job.id;\n    const state: 'success' | 'failure' | null =\n      job.status === 'done' && !job.error\n        ? 'success'\n        : job.status === 'failed' || job.error\n          ? 'failure'\n          : null;\n    if (!state) continue;\n    const desc =\n      state === 'success'\n        ? `passed on ${job.gpu_seat ?? 'fleet'}`\n        : (job.error ?? 'gate failed').slice(0, 140);\n    await postGithubStatuses(repo, sha, [`holo-ci/${gate}`], state, desc);\n  }\n\n  // Rollup status\n  const overall = terminal ? (status.failed > 0 ? 'failure' : 'success') : 'error';\n  const desc = terminal\n    ? `${status.done}/${status.total} gates passed`\n    : `timed out after ${Math.round(timeoutMs / 60_000)}m`;\n  await postGithubStatuses(repo, sha, ['holo-ci'], overall, desc);\n}\n\n// ─── Tool definition ─────────────────────────────────────────────────────────\nexport const holoCiTools: Tool[] = [\n  {\n    name: 'holo_ci_dispatch',\n    description:\n      'Trigger a HoloCI (HoloScript-native CI) run for a commit on the vast.ai fleet via the mcp-orchestrator GPU queue. The orchestrator key is held server-side, so any authenticated MCP client can dispatch CI without holding fleet credentials. SAFE-BY-DEFAULT: this PREVIEWS the workload (gates + commands) and submits nothing unless you pass dryRun:false, which incurs real GPU spend. Returns the submitted workload id and the per-gate commit-status contexts that will be reported on the SHA.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        repo: {\n          type: 'string',\n          description:\n            'Repository slug \"owner/name\". Allowed: brianonbased-dev/HoloScript, brianonbased-dev/Hololand. Defaults to brianonbased-dev/HoloScript.',\n        },\n        sha: {\n          type: 'string',\n          description: 'Commit SHA to validate (7–40 hex chars; full SHA preferred).',\n        },\n        profile: {\n          type: 'string',\n          enum: ['quick', 'full'],\n          description:\n            '\"quick\" = fast static gates (lockfile/lint/secrets); \"full\" = the complete PR gate set (adds build/test/security). Default \"full\".',\n        },\n        dryRun: {\n          type: 'boolean',\n          description:\n            'Default TRUE (safe): build and return the workload WITHOUT submitting to the fleet — no orchestrator key needed, no spend. Pass dryRun:false to ACTUALLY submit to the GPU fleet and incur real spend.',\n        },\n      },\n      required: ['sha'],\n    },\n  },\n];\n\n// ─── Handler ─────────────────────────────────────────────────────────────────\n\n/**\n * Handle `holo_ci_dispatch` tool calls.\n *\n * @param name         Tool name — returns `null` when not `holo_ci_dispatch`.\n * @param args         Tool arguments from the MCP client.\n * @param callerToken  Raw bearer token or MCP key for the requesting client.\n *                     Used only for per-caller spend authorisation — hashed\n *                     before any use, never stored or logged in the clear.\n *                     Pass `undefined` for stdio (local) callers that are\n *                     unconditionally trusted.\n */\nexport async function handleHoloCiTool(\n  name: string,\n  args: Record<string, unknown>,\n  callerToken?: string\n): Promise<unknown | null> {\n  if (name !== 'holo_ci_dispatch') return null;\n\n  const repo =\n    typeof args.repo === 'string' && args.repo.trim() ? args.repo : 'brianonbased-dev/HoloScript';\n  const sha = typeof args.sha === 'string' ? args.sha.trim() : '';\n  const profile: Profile = args.profile === 'quick' ? 'quick' : 'full';\n  // Safe-by-default: preview unless the caller EXPLICITLY opts into real GPU spend\n  // with dryRun:false. The orchestrator key is server-side, so any authenticated MCP\n  // token can reach this handler; defaulting to submit would make a bare call (or an\n  // automation retry-loop) silently burn fleet budget. Spending must be deliberate.\n  const dryRun = args.dryRun !== false;\n\n  if (!sha) {\n    return { ok: false, error: 'sha is required (7–40 hex chars).' };\n  }\n\n  let built: HoloCiWorkload;\n  try {\n    built = buildWorkload({ repo, sha, profile });\n  } catch (err) {\n    return { ok: false, error: err instanceof Error ? err.message : String(err) };\n  }\n\n  if (dryRun) {\n    return {\n      ok: true,\n      dryRun: true,\n      repo: normalizedRepoKey(repo),\n      profile,\n      gateCount: built.workload.jobs.length,\n      contexts: built.contexts,\n      workload: built.workload,\n    };\n  }\n\n  // ── Spend authorisation gate (non-dry path only) ──────────────────────────\n  // Must happen AFTER dryRun branch so previews are never gated.\n  const authzDenial = checkSpendAuthz(callerToken, profile, built);\n  if (authzDenial) return authzDenial;\n\n  const result = await submitWorkload(built.workload);\n  if (!result.ok) {\n    return {\n      ok: false,\n      error: result.error,\n      hint: 'Provision HOLOSCRIPT_API_KEY as a server env secret, or re-run with dryRun:true to preview.',\n      contexts: built.contexts,\n    };\n  }\n\n  // Record the successful submit against the caller's daily quota.\n  if (callerToken) {\n    recordSubmit(tokenFingerprint(callerToken));\n  }\n\n  return {\n    ok: true,\n    dispatched: true,\n    repo: normalizedRepoKey(repo),\n    profile,\n    workloadId: result.workloadId,\n    jobCount: built.workload.jobs.length,\n    contexts: built.contexts,\n  };\n}\n","/**\n * Schema-to-Trait Mapper — Universal Domain Bridge\n *\n * Takes arbitrary structured data (JSON schema, CSV headers, database columns,\n * API response shapes) and automatically maps fields to HoloScript traits.\n * Then generates .holo compositions from those mappings.\n *\n * This is the keystone of the \"Universal Semantic Platform\" thesis:\n * any domain's data maps onto the trait system, any device renders it.\n *\n * The dispensary doesn't write .holo. The restaurant doesn't write .holo.\n * They point this at their data and get a spatial experience.\n *\n * @module schema-mapper\n * @version 1.0.0\n */\n\nimport { suggestTraits, suggestUniversalTraits } from './generators';\n\n// =============================================================================\n// TYPES\n// =============================================================================\n\n/** A field from the input schema */\nexport interface SchemaField {\n  /** Field name (e.g., \"product_name\", \"thc_percent\", \"price\") */\n  name: string;\n  /** Field type (e.g., \"string\", \"number\", \"boolean\", \"array\", \"object\") */\n  type: string;\n  /** Optional description of the field */\n  description?: string;\n  /** Optional example value */\n  example?: unknown;\n  /** Whether the field is required */\n  required?: boolean;\n  /** For numeric fields: min/max range */\n  range?: { min?: number; max?: number };\n  /** For enum fields: possible values */\n  enum?: string[];\n}\n\n/** Input schema — what the business provides */\nexport interface DataSchema {\n  /** Name of the data source (e.g., \"dispensary_menu\", \"restaurant_orders\") */\n  name: string;\n  /** Optional domain hint (e.g., \"retail\", \"healthcare\", \"hospitality\") */\n  domain?: string;\n  /** Optional description of what this data represents */\n  description?: string;\n  /** The fields in the schema */\n  fields: SchemaField[];\n}\n\n/** How a schema field maps to a HoloScript trait */\nexport interface TraitMapping {\n  /** The original field from the schema */\n  field: SchemaField;\n  /** The HoloScript traits this field maps to */\n  traits: string[];\n  /** How the field value feeds into trait parameters */\n  parameterBindings: ParameterBinding[];\n  /** The visual/spatial role of this field in the composition */\n  spatialRole: SpatialRole;\n  /** Confidence in this mapping (0-1) */\n  confidence: number;\n  /** Why this mapping was chosen */\n  reasoning: string;\n}\n\n/** How a schema field value binds to a trait parameter */\nexport interface ParameterBinding {\n  trait: string;\n  parameter: string;\n  /** How to transform the field value for the trait */\n  transform: 'direct' | 'label' | 'scale' | 'color' | 'position' | 'toggle' | 'enum_map';\n}\n\n/** What spatial role a field plays in the scene */\nexport type SpatialRole =\n  | 'identity' // Object name/title — displayed as label\n  | 'description' // Detailed text — shown on interaction\n  | 'visual' // Texture, color, image — applied to mesh\n  | 'metric' // Numeric value — shown as bar, gauge, or scale\n  | 'category' // Grouping field — determines shelf/section/area\n  | 'price' // Currency value — shown as tag, enables @credit\n  | 'boolean_state' // On/off — toggles visibility or trait\n  | 'relationship' // Foreign key — creates spatial link between objects\n  | 'timestamp' // Date/time — affects timeline or lifecycle\n  | 'media' // Image/video URL — applied as texture or popup\n  | 'geospatial' // Lat/lng — placed on map or spatial anchor\n  | 'hidden'; // Internal field — not rendered\n\n/** Full mapping result */\nexport interface SchemaMappingResult {\n  /** The input schema */\n  schema: DataSchema;\n  /** Per-field trait mappings */\n  mappings: TraitMapping[];\n  /** Global traits applied to every object (e.g., @pointable, @info_popup) */\n  globalTraits: string[];\n  /** Generated .holo composition source */\n  holoSource: string;\n  /** Compilation targets recommended by ModalitySelector */\n  recommendedTargets: string[];\n  /** Summary statistics */\n  stats: {\n    fieldsTotal: number;\n    fieldsMapped: number;\n    fieldsUnmapped: number;\n    traitsUsed: number;\n    averageConfidence: number;\n  };\n}\n\n// =============================================================================\n// FIELD TYPE → SPATIAL ROLE INFERENCE\n// =============================================================================\n\n/** Patterns that identify spatial roles from field names */\nconst ROLE_PATTERNS: Array<{ pattern: RegExp; role: SpatialRole; traits: string[] }> = [\n  // Identity\n  {\n    pattern: /^(name|title|label|display_name|product_name|item_name|sku)$/i,\n    role: 'identity',\n    traits: ['@label', '@pointable'],\n  },\n  // Description\n  {\n    pattern: /(desc|description|summary|notes|details|about|bio|overview)$/i,\n    role: 'description',\n    traits: ['@info_popup', '@readable'],\n  },\n  // Price / Currency\n  {\n    pattern: /(price|cost|amount|fee|rate|msrp|retail_price|unit_price)$/i,\n    role: 'price',\n    traits: ['@label', '@credit'],\n  },\n  // Visual / Media\n  {\n    pattern: /(image|img|photo|picture|thumbnail|avatar|icon|logo|banner)(_url|_path|_uri)?$/i,\n    role: 'media',\n    traits: ['@texture', '@billboard'],\n  },\n  {\n    pattern: /(video|media|clip|stream)(_url|_path|_uri)?$/i,\n    role: 'media',\n    traits: ['@video_player'],\n  },\n  // Metrics\n  {\n    pattern:\n      /(percent|pct|ratio|score|rating|rank|level|count|quantity|stock|inventory|weight|volume|dose|potency|thc|cbd|strength)$/i,\n    role: 'metric',\n    traits: ['@gauge', '@label'],\n  },\n  // Category / Grouping\n  {\n    pattern:\n      /(category|type|kind|class|group|section|department|shelf|aisle|strain_type|indica|sativa|hybrid|genre|tier|status)$/i,\n    role: 'category',\n    traits: ['@tag', '@filterable'],\n  },\n  // Boolean states\n  {\n    pattern:\n      /(enabled|active|visible|available|in_stock|featured|premium|organic|lab_tested|verified|approved|published)$/i,\n    role: 'boolean_state',\n    traits: ['@toggleable'],\n  },\n  // Timestamps\n  {\n    pattern:\n      /(date|time|created|updated|modified|expires|harvested|tested|manufactured|born|deadline)(_at|_on|_date)?$/i,\n    role: 'timestamp',\n    traits: ['@lifecycle'],\n  },\n  // Geospatial\n  {\n    pattern: /(lat|lng|latitude|longitude|location|coordinates|address|geo|position|place)$/i,\n    role: 'geospatial',\n    traits: ['@spatial_anchor', '@gps'],\n  },\n  // Relationships / Foreign keys\n  {\n    pattern: /(_id|_ref|parent|child|related|associated|linked|belongs_to|has_many)$/i,\n    role: 'relationship',\n    traits: ['@connectable'],\n  },\n  // Color\n  { pattern: /(color|colour|hue|tint|shade|hex_color|rgb)$/i, role: 'visual', traits: ['@color'] },\n];\n\n/** Type-based fallback roles */\nconst TYPE_ROLE_FALLBACK: Record<string, SpatialRole> = {\n  string: 'description',\n  number: 'metric',\n  boolean: 'boolean_state',\n  array: 'hidden',\n  object: 'hidden',\n};\n\n// =============================================================================\n// MAPPING ENGINE\n// =============================================================================\n\nfunction inferSpatialRole(field: SchemaField): {\n  role: SpatialRole;\n  traits: string[];\n  reasoning: string;\n} {\n  // 0. Check domain plugin keywords first (highest priority when plugin loaded)\n  if (pluginKeywords) {\n    const fieldLower = field.name.toLowerCase();\n    for (const [term, mapping] of pluginKeywords) {\n      if (fieldLower.includes(term)) {\n        const role =\n          (mapping.spatialRole as SpatialRole) || TYPE_ROLE_FALLBACK[field.type] || 'description';\n        return {\n          role,\n          traits: mapping.traits,\n          reasoning: `Domain plugin keyword \"${term}\" matched field \"${field.name}\"`,\n        };\n      }\n    }\n  }\n\n  // 1. Pattern match on field name\n  for (const { pattern, role, traits } of ROLE_PATTERNS) {\n    if (pattern.test(field.name)) {\n      return { role, traits, reasoning: `Field name \"${field.name}\" matches ${role} pattern` };\n    }\n  }\n\n  // 2. Check description for hints\n  if (field.description) {\n    const descTraits = suggestTraits(field.description, field.name);\n    if (descTraits.traits.length > 1) {\n      // More than just @pointable default\n      return {\n        role: TYPE_ROLE_FALLBACK[field.type] || 'description',\n        traits: descTraits.traits,\n        reasoning: `Inferred from description: \"${field.description.slice(0, 60)}...\"`,\n      };\n    }\n  }\n\n  // 3. Check example value for hints\n  if (field.example !== undefined) {\n    if (typeof field.example === 'string' && /^https?:\\/\\//.test(field.example)) {\n      return {\n        role: 'media',\n        traits: ['@texture', '@billboard'],\n        reasoning: 'Example value is a URL',\n      };\n    }\n    if (typeof field.example === 'number' && field.range) {\n      return {\n        role: 'metric',\n        traits: ['@gauge', '@label'],\n        reasoning: 'Numeric with range → gauge/metric',\n      };\n    }\n  }\n\n  // 4. Fall back to type\n  const role = TYPE_ROLE_FALLBACK[field.type] || 'hidden';\n  return {\n    role,\n    traits: role === 'hidden' ? [] : ['@label'],\n    reasoning: `Fallback from type \"${field.type}\"`,\n  };\n}\n\nfunction createParameterBindings(\n  field: SchemaField,\n  traits: string[],\n  role: SpatialRole\n): ParameterBinding[] {\n  const bindings: ParameterBinding[] = [];\n\n  for (const trait of traits) {\n    switch (role) {\n      case 'identity':\n        bindings.push({ trait, parameter: 'text', transform: 'direct' });\n        break;\n      case 'description':\n        bindings.push({ trait, parameter: 'content', transform: 'label' });\n        break;\n      case 'price':\n        bindings.push({ trait, parameter: 'text', transform: 'label' });\n        if (trait === '@credit') {\n          bindings.push({ trait, parameter: 'price', transform: 'direct' });\n        }\n        break;\n      case 'metric':\n        bindings.push({ trait, parameter: 'value', transform: field.range ? 'scale' : 'direct' });\n        break;\n      case 'media':\n        bindings.push({ trait, parameter: 'src', transform: 'direct' });\n        break;\n      case 'category':\n        bindings.push({ trait, parameter: 'tag', transform: 'direct' });\n        break;\n      case 'boolean_state':\n        bindings.push({ trait, parameter: 'enabled', transform: 'toggle' });\n        break;\n      case 'visual':\n        bindings.push({ trait, parameter: 'color', transform: 'color' });\n        break;\n      case 'geospatial':\n        bindings.push({ trait, parameter: 'position', transform: 'position' });\n        break;\n      default:\n        bindings.push({ trait, parameter: 'value', transform: 'direct' });\n    }\n  }\n\n  return bindings;\n}\n\n/** Domain plugin keyword map — loaded at runtime from installed plugins */\nlet pluginKeywords: Map<string, { traits: string[]; spatialRole?: string }> | null = null;\n\n/** Register domain plugin keywords to enhance schema mapping accuracy */\nexport function registerDomainKeywords(\n  keywords: Map<string, { traits: string[]; spatialRole?: string }>\n) {\n  pluginKeywords = keywords;\n}\n\n/** Clear registered domain keywords */\nexport function clearDomainKeywords() {\n  pluginKeywords = null;\n}\n\n/** Map a full schema to traits */\nexport function mapSchemaToTraits(schema: DataSchema): SchemaMappingResult {\n  const mappings: TraitMapping[] = [];\n  const allTraits = new Set<string>();\n\n  // Domain-level traits from schema description\n  const domainContext = [schema.name, schema.domain, schema.description].filter(Boolean).join(' ');\n  const domainSuggestion = suggestUniversalTraits(domainContext, schema.domain);\n  const globalTraits = ['@pointable', '@info_popup', ...domainSuggestion.traits.slice(0, 3)];\n\n  for (const field of schema.fields) {\n    const { role, traits, reasoning } = inferSpatialRole(field);\n    const bindings = createParameterBindings(field, traits, role);\n\n    // Confidence based on how the mapping was determined\n    let confidence = 0.5;\n    if (reasoning.includes('matches')) confidence = 0.9; // Pattern match\n    if (reasoning.includes('description')) confidence = 0.7; // Description inference\n    if (reasoning.includes('Fallback')) confidence = 0.3; // Type fallback\n\n    mappings.push({\n      field,\n      traits,\n      parameterBindings: bindings,\n      spatialRole: role,\n      confidence,\n      reasoning,\n    });\n\n    for (const t of traits) allTraits.add(t);\n  }\n\n  const holoSource = generateHoloComposition(schema, mappings, globalTraits);\n\n  const mapped = mappings.filter((m) => m.spatialRole !== 'hidden');\n  const stats = {\n    fieldsTotal: schema.fields.length,\n    fieldsMapped: mapped.length,\n    fieldsUnmapped: schema.fields.length - mapped.length,\n    traitsUsed: allTraits.size,\n    averageConfidence:\n      mapped.length > 0 ? mapped.reduce((sum, m) => sum + m.confidence, 0) / mapped.length : 0,\n  };\n\n  return {\n    schema,\n    mappings,\n    globalTraits,\n    holoSource,\n    recommendedTargets: ['webgpu', 'openxr', 'canvas2d-game'],\n    stats,\n  };\n}\n\n// =============================================================================\n// .HOLO COMPOSITION GENERATOR\n// =============================================================================\n\n/** Infer brand theme — neutral default, customizable via Studio theme panel */\nfunction inferTheme(_schema: DataSchema): Record<string, string> {\n  // Neutral default. Domain-specific themes are NOT hardcoded into the platform.\n  // The business customizes via Studio's theme panel or by editing the theme {} block.\n  // Domain vocabulary lives in the knowledge store, not in compiler code.\n  return {\n    primary: '#2563eb',\n    secondary: '#f8fafc',\n    accent: '#f59e0b',\n    shelf_material: 'wood_light',\n    card_style: 'rounded',\n  };\n}\n\nfunction generateHoloComposition(\n  schema: DataSchema,\n  mappings: TraitMapping[],\n  globalTraits: string[]\n): string {\n  const lines: string[] = [];\n  const name = schema.name.replace(/[^a-zA-Z0-9_]/g, '_');\n  const theme = inferTheme(schema);\n\n  lines.push(`composition \"${name}\" {`);\n\n  // Theme block — brand identity tokens\n  lines.push(`  theme {`);\n  for (const [key, value] of Object.entries(theme)) {\n    lines.push(`    ${key}: \"${value}\"`);\n  }\n  lines.push(`  }`);\n  lines.push('');\n\n  lines.push(`  environment {`);\n  lines.push(`    background: \"${theme.secondary}\"`);\n  lines.push(`    ambient_light: 0.6`);\n  lines.push(`    fog: false`);\n  lines.push(`  }`);\n  lines.push('');\n\n  // Template object from the schema\n  lines.push(`  // Auto-generated from ${schema.fields.length} schema fields`);\n  lines.push(`  // Domain: ${schema.domain || 'auto-detected'}`);\n  lines.push(`  template \"${name}_item\" {`);\n\n  // Global traits\n  for (const trait of globalTraits) {\n    lines.push(`    ${trait}`);\n  }\n\n  // Per-field trait annotations\n  const visibleMappings = mappings.filter((m) => m.spatialRole !== 'hidden');\n  for (const mapping of visibleMappings) {\n    const fieldComment = mapping.field.description\n      ? ` // ${mapping.field.description.slice(0, 50)}`\n      : '';\n\n    for (const trait of mapping.traits) {\n      const binding = mapping.parameterBindings.find((b) => b.trait === trait);\n      if (binding) {\n        const bindExpr = `__bind:${mapping.field.name}`;\n        lines.push(`    ${trait}(${binding.parameter}: \"${bindExpr}\")${fieldComment}`);\n      } else {\n        lines.push(`    ${trait}${fieldComment}`);\n      }\n    }\n  }\n\n  // Geometry\n  lines.push('    geometry: \"box\"');\n  lines.push('    scale: [0.3, 0.3, 0.3]');\n  lines.push(`  }`);\n  lines.push('');\n\n  // Layout: categorized grid\n  const categoryField = mappings.find((m) => m.spatialRole === 'category');\n  if (categoryField) {\n    lines.push(`  // Items grouped by ${categoryField.field.name}`);\n    lines.push(`  spatial_group \"shelves\" {`);\n    lines.push(`    layout: \"grid\"`);\n    lines.push(`    group_by: \"${categoryField.field.name}\"`);\n    lines.push(`    spacing: [1, 0.5, 1]`);\n    lines.push(`  }`);\n  } else {\n    lines.push(`  spatial_group \"display\" {`);\n    lines.push(`    layout: \"grid\"`);\n    lines.push(`    columns: 4`);\n    lines.push(`    spacing: [1, 0.5, 1]`);\n    lines.push(`  }`);\n  }\n\n  lines.push('}');\n  return lines.join('\\n');\n}\n\n// =============================================================================\n// MCP TOOL HANDLER\n// =============================================================================\n\n/**\n * Try to load domain plugin keywords from a context JSON file.\n * Checks packages/plugins/domain-plugin-template/contexts/{domain}.json\n */\nfunction tryLoadDomainPlugin(domain: string | undefined): boolean {\n  if (!domain) return false;\n  try {\n    // Dynamic import of plugin context — works at runtime if file exists\n    const fs = require('fs');\n    const path = require('path');\n    const contextPath = path.resolve(\n      __dirname,\n      '../../plugins/domain-plugin-template/contexts',\n      `${domain}.json`\n    );\n    if (!fs.existsSync(contextPath)) return false;\n\n    const config = JSON.parse(fs.readFileSync(contextPath, 'utf-8'));\n    const keywords = new Map<string, { traits: string[]; spatialRole?: string }>();\n    for (const mod of config.modules || []) {\n      for (const kw of mod.keywords || []) {\n        keywords.set(kw.term.toLowerCase(), { traits: kw.traits, spatialRole: kw.spatialRole });\n      }\n    }\n    registerDomainKeywords(keywords);\n    return true;\n  } catch {\n    return false;\n  }\n}\n\nexport async function handleMapSchema(args: Record<string, unknown>): Promise<unknown> {\n  const { schema, fields, name, domain, description } = args as {\n    schema?: DataSchema;\n    fields?: SchemaField[];\n    name?: string;\n    domain?: string;\n    description?: string;\n  };\n\n  let dataSchema: DataSchema;\n  if (schema) {\n    dataSchema = schema;\n  } else if (fields && name) {\n    dataSchema = { name, domain, description, fields };\n  } else {\n    return { success: false, error: 'Provide either a \"schema\" object or \"name\" + \"fields\" array' };\n  }\n\n  // Load domain plugin if available\n  const pluginLoaded = tryLoadDomainPlugin(dataSchema.domain);\n\n  const result = mapSchemaToTraits(dataSchema);\n\n  // Clean up plugin state after mapping\n  if (pluginLoaded) clearDomainKeywords();\n\n  return { success: true, pluginUsed: pluginLoaded, ...result };\n}\n\nexport async function handleMapCsvHeaders(args: Record<string, unknown>): Promise<unknown> {\n  const { headers, name, domain, description, sample_row } = args as {\n    headers: string[];\n    name?: string;\n    domain?: string;\n    description?: string;\n    sample_row?: Record<string, unknown>;\n  };\n\n  if (!headers || !Array.isArray(headers)) {\n    return { success: false, error: 'Provide a \"headers\" string array' };\n  }\n\n  // Infer field types from sample row\n  const fields: SchemaField[] = headers.map((h) => {\n    const example = sample_row?.[h];\n    let type = 'string';\n    if (typeof example === 'number') type = 'number';\n    if (typeof example === 'boolean') type = 'boolean';\n\n    return { name: h, type, example };\n  });\n\n  const schema: DataSchema = {\n    name: name || 'imported_data',\n    domain,\n    description,\n    fields,\n  };\n\n  const pluginLoaded = tryLoadDomainPlugin(schema.domain);\n  const result = mapSchemaToTraits(schema);\n  if (pluginLoaded) clearDomainKeywords();\n  return { success: true, pluginUsed: pluginLoaded, ...result };\n}\n","/**\n * Audit Tools — Automated Number Consistency\n *\n * Runs Ground Truth Table verification commands, greps all docs for each metric,\n * builds a consistency matrix, and optionally patches mismatches.\n *\n * This tool eliminates the manual re-audit loop that burned context 3x in one session.\n * Run it once, get a consistency report, optionally auto-fix.\n *\n * @module audit-tools\n * @version 1.0.0\n */\n\nimport type { Tool } from '@modelcontextprotocol/sdk/types.js';\nimport * as fs from 'fs';\nimport * as os from 'os';\nimport * as path from 'path';\n\n// =============================================================================\n// TYPES\n// =============================================================================\n\ninterface MetricDefinition {\n  id: string;\n  name: string;\n  /** Native collector for the live value. */\n  collect: () => Promise<string> | string;\n  /** How to parse the collector output into a number or string */\n  parser: (output: string) => string;\n  /** Regex patterns to search for this metric in docs */\n  searchPatterns: RegExp[];\n}\n\ninterface MetricResult {\n  id: string;\n  name: string;\n  liveValue: string;\n  occurrences: Array<{\n    file: string;\n    line: number;\n    currentValue: string;\n    matches: boolean;\n  }>;\n  allConsistent: boolean;\n}\n\ninterface AuditResult {\n  timestamp: string;\n  metrics: MetricResult[];\n  totalOccurrences: number;\n  mismatches: number;\n  files: string[];\n}\n\n// =============================================================================\n// GROUND TRUTH TABLE\n// =============================================================================\n\nconst HOLOSCRIPT_ROOT = path.resolve(__dirname, '../../..');\nconst DEFAULT_ORCHESTRATOR_URL = 'https://mcp-orchestrator-production-45f9.up.railway.app';\n\nconst METRICS: MetricDefinition[] = [\n  {\n    id: 'compiler_files',\n    name: 'Compiler files',\n    collect: () => countCompilerFiles(HOLOSCRIPT_ROOT),\n    parser: (o) => o.trim(),\n    searchPatterns: [/(\\d+)\\s*compilers?\\b/gi, /(\\d+)\\s*compil(?:ation)?\\s*targets?\\b/gi],\n  },\n  {\n    id: 'trait_categories',\n    name: 'Trait categories',\n    collect: () => countTraitCategoryFiles(HOLOSCRIPT_ROOT),\n    parser: (o) => o.trim(),\n    searchPatterns: [/(\\d+)\\s*categor(?:y|ies)\\b/gi],\n  },\n  {\n    id: 'knowledge_entries',\n    name: 'Knowledge entries',\n    collect: () => fetchKnowledgeEntryCount(DEFAULT_ORCHESTRATOR_URL),\n    parser: (o) => o.trim(),\n    searchPatterns: [/(\\d+)\\s*(?:knowledge\\s*)?entries/gi],\n  },\n];\n\n// Files to scan for metric occurrences\nconst SCAN_GLOBS = ['README.md', 'docs/strategy/ROADMAP.md', 'packages/mcp-server/README.md'];\n\n// External files (outside HoloScript repo) — resolved via os.homedir() for portability\nconst HOME = os.homedir();\nconst EXTERNAL_FILES = [\n  path.join(HOME, '.claude', 'CLAUDE.md'),\n  path.join(HOME, '.claude', 'NORTH_STAR.md'),\n  path.join(HOME, '.gemini', 'GEMINI.md'),\n  path.join(HOME, '.claude', 'skills', 'holoscript', 'SKILL.md'),\n  path.join(HOME, '.claude', 'skills', 'documenter', 'skill.md'),\n  path.join(HOME, '.claude', 'skills', 'holomoltbook', 'skill.md'),\n  path.join(HOME, '.claude', 'skills', 'holomesh', 'skill.md'),\n  path.join(HOME, '.claude', 'skills', 'holomesh-oracle', 'SKILL.md'),\n  path.join(HOME, '.claude', 'projects', 'c--Users-josep--ai-ecosystem', 'memory', 'MEMORY.md'),\n  path.join(HOME, '.ai-ecosystem', 'STRATEGY.md'),\n];\n\n// =============================================================================\n// COLLECTORS\n// =============================================================================\n\nfunction walkFiles(root: string): string[] {\n  if (!fs.existsSync(root)) return [];\n  const files: string[] = [];\n  const entries = fs.readdirSync(root, { withFileTypes: true });\n\n  for (const entry of entries) {\n    const fullPath = path.join(root, entry.name);\n    if (entry.isDirectory()) {\n      files.push(...walkFiles(fullPath));\n    } else if (entry.isFile()) {\n      files.push(fullPath);\n    }\n  }\n\n  return files;\n}\n\nexport function countCompilerFiles(root: string = HOLOSCRIPT_ROOT): string {\n  const compilerDir = path.join(root, 'packages', 'core', 'src', 'compiler');\n  const count = walkFiles(compilerDir).filter((file) => {\n    const base = path.basename(file);\n    return (\n      base.endsWith('Compiler.ts') &&\n      base !== 'CompilerBase.ts' &&\n      !base.includes('.test.') &&\n      !base.includes('.spec.')\n    );\n  }).length;\n  return String(count);\n}\n\nexport function countTraitCategoryFiles(root: string = HOLOSCRIPT_ROOT): string {\n  const constantsDir = path.join(root, 'packages', 'core', 'src', 'traits', 'constants');\n  if (!fs.existsSync(constantsDir)) return '0';\n  const count = fs\n    .readdirSync(constantsDir, { withFileTypes: true })\n    .filter(\n      (entry) => entry.isFile() && entry.name.endsWith('.ts') && !entry.name.endsWith('.d.ts')\n    ).length;\n  return String(count);\n}\n\nasync function fetchKnowledgeEntryCount(orchestratorUrl: string): Promise<string> {\n  try {\n    const res = await fetch(`${orchestratorUrl}/health`, {\n      signal: AbortSignal.timeout(15_000),\n    });\n    const text = await res.text();\n    if (!res.ok) return 'unknown';\n\n    try {\n      const data = JSON.parse(text) as Record<string, unknown>;\n      const value = data.knowledge_entries ?? data.knowledgeEntries;\n      if (typeof value === 'number') return String(value);\n      if (typeof value === 'string' && /^\\d+$/.test(value)) return value;\n    } catch {\n      const match = text.match(/\"knowledge_entries\"\\s*:\\s*(\\d+)/);\n      if (match) return match[1];\n    }\n\n    return 'unknown';\n  } catch {\n    return 'unknown';\n  }\n}\n\n// =============================================================================\n// ENGINE\n// =============================================================================\n\nasync function collectMetric(metric: MetricDefinition): Promise<string> {\n  try {\n    const output = await metric.collect();\n    return metric.parser(output);\n  } catch {\n    return 'ERROR';\n  }\n}\n\nfunction scanFile(\n  filePath: string,\n  metric: MetricDefinition,\n  liveValue: string\n): MetricResult['occurrences'] {\n  const occurrences: MetricResult['occurrences'] = [];\n  try {\n    const absPath = path.isAbsolute(filePath) ? filePath : path.join(HOLOSCRIPT_ROOT, filePath);\n    if (!fs.existsSync(absPath)) return occurrences;\n\n    const content = fs.readFileSync(absPath, 'utf-8');\n    const lines = content.split('\\n');\n\n    for (let i = 0; i < lines.length; i++) {\n      for (const pattern of metric.searchPatterns) {\n        pattern.lastIndex = 0;\n        let match;\n        while ((match = pattern.exec(lines[i])) !== null) {\n          const currentValue = match[1];\n          // Skip if this is clearly a different metric (e.g., \"114 categories\" when scanning for compilers)\n          if (metric.id === 'compiler_files' && lines[i].includes('categor')) continue;\n          if (metric.id === 'trait_categories' && lines[i].includes('compil')) continue;\n          if (\n            metric.id === 'knowledge_entries' &&\n            (lines[i].includes('compil') || lines[i].includes('categor'))\n          )\n            continue;\n\n          occurrences.push({\n            file: filePath,\n            line: i + 1,\n            currentValue,\n            matches: currentValue === liveValue,\n          });\n        }\n      }\n    }\n  } catch {\n    // File not readable — skip\n  }\n  return occurrences;\n}\n\nexport async function runAudit(): Promise<AuditResult> {\n  const metrics: MetricResult[] = [];\n  let totalOccurrences = 0;\n  let mismatches = 0;\n  const allFiles = [...SCAN_GLOBS, ...EXTERNAL_FILES];\n\n  for (const metric of METRICS) {\n    const liveValue = await collectMetric(metric);\n\n    const occurrences: MetricResult['occurrences'] = [];\n    for (const file of allFiles) {\n      occurrences.push(...scanFile(file, metric, liveValue));\n    }\n\n    const allConsistent = occurrences.every((o) => o.matches);\n    totalOccurrences += occurrences.length;\n    mismatches += occurrences.filter((o) => !o.matches).length;\n\n    metrics.push({ id: metric.id, name: metric.name, liveValue, occurrences, allConsistent });\n  }\n\n  return {\n    timestamp: new Date().toISOString(),\n    metrics,\n    totalOccurrences,\n    mismatches,\n    files: allFiles,\n  };\n}\n\n// =============================================================================\n// MCP HANDLER\n// =============================================================================\n\nexport async function handleAuditNumbers(_args: Record<string, unknown>): Promise<unknown> {\n  const result = await runAudit();\n\n  // Build summary\n  const summary = result.metrics.map((m) => ({\n    metric: m.name,\n    live: m.liveValue,\n    consistent: m.allConsistent,\n    occurrences: m.occurrences.length,\n    mismatches: m.occurrences\n      .filter((o) => !o.matches)\n      .map((o) => ({\n        file: o.file,\n        line: o.line,\n        has: o.currentValue,\n        should_be: m.liveValue,\n      })),\n  }));\n\n  return {\n    success: true,\n    timestamp: result.timestamp,\n    totalOccurrences: result.totalOccurrences,\n    mismatches: result.mismatches,\n    allConsistent: result.mismatches === 0,\n    metrics: summary,\n  };\n}\n\n// =============================================================================\n// TOOL DEFINITION\n// =============================================================================\n\nexport const auditTools: Tool[] = [\n  {\n    name: 'holoscript_audit_numbers',\n    description:\n      'Audit all ecosystem metrics against live ground truth. Collects live metrics ' +\n      '(compiler count, trait categories, knowledge entries), scans all docs/configs/skills ' +\n      'for each metric, and reports mismatches. Replaces manual re-audit loops.',\n    inputSchema: {\n      type: 'object',\n      properties: {},\n    },\n  },\n];\n","/**\n * AlphaFold MCP Tools\n *\n * Exposes @holoscript/alphafold-plugin capabilities as MCP tools so that\n * pipelines (.hs) and agents (Cursor, LangGraph, Claude) can fetch protein\n * structures from their UniProt accession without embedding the fetcher\n * logic in every caller.\n *\n * This is Track A step 2 from `docs/strategy/hs-streaming-audit-2026-04-17.md` —\n * the bridge that makes the drug-discovery-flagship.hs pipeline's Stage 5\n * (ProteinStructure source) a real MCP call rather than a stub.\n *\n * Backing data source: EBI AlphaFold Protein Structure Database.\n *   https://alphafold.ebi.ac.uk/api/prediction/{uniprot}\n *\n * The handler performs HTTP fetches; it deliberately does NOT run the\n * AlphaFold model locally (that's a GPU job). The EBI API returns the\n * pre-computed structure + confidence scores which is what the trait\n * system needs.\n *\n * @module alphafold-tools\n * @version 1.0.0\n */\n\nimport type { Tool } from '@modelcontextprotocol/sdk/types.js';\n\n// =============================================================================\n// TOOL DECLARATIONS\n// =============================================================================\n\nexport const alphafoldTools: Tool[] = [\n  {\n    name: 'alphafold_fetch_structure',\n    description:\n      'Fetch a pre-computed AlphaFold protein structure from the EBI AlphaFold database by UniProt accession. ' +\n      'Returns PDB data, mean pLDDT confidence, per-residue confidence scores, and a suggested @protein_structure ' +\n      'trait payload ready for embedding in a .holo composition. Use this tool to ground drug-discovery, ' +\n      'structural-biology, or binding-site simulations in real experimental-grade predictions.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        uniprot: {\n          type: 'string',\n          description:\n            'UniProt accession number (e.g. \"P00533\" for human EGFR). Must be a Swiss-Prot or TrEMBL identifier.',\n          pattern: '^[A-Z][0-9A-Z]{5,9}$',\n        },\n        domain: {\n          type: 'string',\n          description:\n            'Optional domain label to record in the trait metadata (e.g. \"kinase\"). Does not slice the structure — AlphaFold returns the full chain. Use this for labeling in downstream scenes.',\n        },\n        pdb_format: {\n          type: 'string',\n          enum: ['pdb', 'cif'],\n          description: 'Return PDB format or mmCIF. Default: pdb.',\n          default: 'pdb',\n        },\n      },\n      required: ['uniprot'],\n    },\n  },\n];\n\n// =============================================================================\n// TYPES\n// =============================================================================\n\ninterface AlphaFoldAPIResponse {\n  entryId: string;\n  gene?: string;\n  uniprotAccession: string;\n  uniprotId?: string;\n  uniprotDescription?: string;\n  organismScientificName?: string;\n  pdbUrl: string;\n  cifUrl: string;\n  paeImageUrl?: string;\n  globalMetricValue?: number;\n  latestVersion?: number;\n}\n\ninterface FetchStructureArgs {\n  uniprot: string;\n  domain?: string;\n  pdb_format?: 'pdb' | 'cif';\n}\n\ninterface FetchStructureResult {\n  ok: boolean;\n  uniprot: string;\n  domain: string | null;\n  source: 'ebi-alphafold' | 'error';\n  mean_plddt: number | null;\n  sequence_length: number | null;\n  per_residue_plddt: number[] | null;\n  pdb_data: string | null;\n  pdb_url: string | null;\n  pae_image_url: string | null;\n  latest_version: number | null;\n  suggested_trait: {\n    type: 'protein_structure';\n    uniprot: string;\n    domain: string | null;\n    pdb_format: 'pdb' | 'cif';\n  } | null;\n  error?: string;\n  /**\n   * Provenance stub — downstream pipeline stages can attach this to their\n   * metadata block to cite the AlphaFold source in the final .holo.\n   */\n  provenance: {\n    source: string;\n    api: string;\n    fetched_at: string;\n    version: number | null;\n  };\n}\n\n// =============================================================================\n// HANDLER\n// =============================================================================\n\nfunction validateUniprot(uniprot: string): boolean {\n  return /^[A-Z][0-9A-Z]{5,9}$/.test(uniprot);\n}\n\n/**\n * Parse per-residue pLDDT scores from a PDB file.\n * PDB stores pLDDT in the B-factor column for AlphaFold predictions.\n * Takes CA atoms only (one per residue) and returns them in order.\n */\nfunction extractPlddtFromPdb(pdb: string): {\n  perResidue: number[];\n  mean: number;\n  length: number;\n} {\n  const perResidue: number[] = [];\n  for (const line of pdb.split('\\n')) {\n    // Only the Cα atom per residue — PDB columns 13-16 hold the atom name\n    if (!line.startsWith('ATOM')) continue;\n    const atomName = line.substring(12, 16).trim();\n    if (atomName !== 'CA') continue;\n    // B-factor is columns 61-66 (1-indexed) per PDB spec\n    const bFactor = parseFloat(line.substring(60, 66));\n    if (Number.isFinite(bFactor)) perResidue.push(bFactor);\n  }\n  const mean =\n    perResidue.length > 0 ? perResidue.reduce((a, b) => a + b, 0) / perResidue.length : 0;\n  return { perResidue, mean, length: perResidue.length };\n}\n\nexport async function handleFetchStructure(\n  args: Record<string, unknown>\n): Promise<FetchStructureResult> {\n  const fetchedAt = new Date().toISOString();\n  const { uniprot, domain = null, pdb_format = 'pdb' } = args as unknown as FetchStructureArgs;\n\n  // Base shape — populated as the handler progresses, so partial-failure\n  // responses still include provenance context for the caller.\n  const base: FetchStructureResult = {\n    ok: false,\n    uniprot: uniprot ?? '',\n    domain: domain ?? null,\n    source: 'error',\n    mean_plddt: null,\n    sequence_length: null,\n    per_residue_plddt: null,\n    pdb_data: null,\n    pdb_url: null,\n    pae_image_url: null,\n    latest_version: null,\n    suggested_trait: null,\n    provenance: {\n      source: 'ebi-alphafold',\n      api: 'https://alphafold.ebi.ac.uk/api/prediction',\n      fetched_at: fetchedAt,\n      version: null,\n    },\n  };\n\n  if (!uniprot || typeof uniprot !== 'string') {\n    return { ...base, error: 'uniprot is required and must be a string' };\n  }\n\n  const normalized = uniprot.toUpperCase().trim();\n  if (!validateUniprot(normalized)) {\n    return {\n      ...base,\n      uniprot: normalized,\n      error: `Invalid UniProt accession format: \"${normalized}\". Must match /^[A-Z][0-9A-Z]{5,9}$/`,\n    };\n  }\n\n  const metaUrl = `https://alphafold.ebi.ac.uk/api/prediction/${normalized}`;\n\n  let metadata: AlphaFoldAPIResponse;\n  try {\n    const metaResponse = await fetch(metaUrl, {\n      headers: { Accept: 'application/json' },\n      signal: AbortSignal.timeout(15_000),\n    });\n    if (!metaResponse.ok) {\n      return {\n        ...base,\n        uniprot: normalized,\n        error: `AlphaFold metadata fetch failed: ${metaResponse.status} ${metaResponse.statusText}. Accession may not be in the database.`,\n      };\n    }\n    const payload = (await metaResponse.json()) as AlphaFoldAPIResponse[] | AlphaFoldAPIResponse;\n    // EBI returns an array; pick the first entry\n    metadata = Array.isArray(payload) ? payload[0] : payload;\n    if (!metadata) {\n      return {\n        ...base,\n        uniprot: normalized,\n        error: 'AlphaFold API returned no entries for this accession',\n      };\n    }\n  } catch (err) {\n    return {\n      ...base,\n      uniprot: normalized,\n      error: `AlphaFold metadata fetch error: ${err instanceof Error ? err.message : String(err)}`,\n    };\n  }\n\n  const structureUrl = pdb_format === 'cif' ? metadata.cifUrl : metadata.pdbUrl;\n  if (!structureUrl) {\n    return {\n      ...base,\n      uniprot: normalized,\n      error: `AlphaFold metadata missing ${pdb_format.toUpperCase()} URL`,\n      latest_version: metadata.latestVersion ?? null,\n    };\n  }\n\n  let structureText: string;\n  try {\n    const structureResponse = await fetch(structureUrl, {\n      signal: AbortSignal.timeout(30_000),\n    });\n    if (!structureResponse.ok) {\n      return {\n        ...base,\n        uniprot: normalized,\n        error: `AlphaFold structure fetch failed: ${structureResponse.status} ${structureResponse.statusText}`,\n        pdb_url: structureUrl,\n        latest_version: metadata.latestVersion ?? null,\n      };\n    }\n    structureText = await structureResponse.text();\n  } catch (err) {\n    return {\n      ...base,\n      uniprot: normalized,\n      error: `AlphaFold structure fetch error: ${err instanceof Error ? err.message : String(err)}`,\n      pdb_url: structureUrl,\n      latest_version: metadata.latestVersion ?? null,\n    };\n  }\n\n  const plddt =\n    pdb_format === 'pdb'\n      ? extractPlddtFromPdb(structureText)\n      : { perResidue: [], mean: metadata.globalMetricValue ?? 0, length: 0 };\n\n  return {\n    ok: true,\n    uniprot: normalized,\n    domain: domain ?? null,\n    source: 'ebi-alphafold',\n    mean_plddt: metadata.globalMetricValue ?? plddt.mean,\n    sequence_length: plddt.length || null,\n    per_residue_plddt: plddt.perResidue.length > 0 ? plddt.perResidue : null,\n    pdb_data: structureText,\n    pdb_url: structureUrl,\n    pae_image_url: metadata.paeImageUrl ?? null,\n    latest_version: metadata.latestVersion ?? null,\n    suggested_trait: {\n      type: 'protein_structure',\n      uniprot: normalized,\n      domain: domain ?? null,\n      pdb_format,\n    },\n    provenance: {\n      source: 'ebi-alphafold',\n      api: 'https://alphafold.ebi.ac.uk/api/prediction',\n      fetched_at: fetchedAt,\n      version: metadata.latestVersion ?? null,\n    },\n  };\n}\n","/**\n * HoloScript MCP Compiler Tools\n *\n * Exposes all 18+ HoloScript compilation targets via Model Context Protocol.\n * Enables AI agents to compile HoloScript to any platform with circuit breaker protection,\n * streaming progress, and comprehensive error reporting.\n *\n * Features:\n * - 18+ export targets (Unity, Unreal, URDF, SDF, WebGPU, WASM, R3F, etc.)\n * - Circuit breaker pattern per target\n * - Streaming compilation progress via JSON streaming\n * - Job status tracking with unique job IDs\n * - Comprehensive error messages with suggestions\n * - Export manager integration for batch operations\n * - AgentIdentity RBAC integration (Phase 1)\n *\n * @version 1.0.0\n * @package @holoscript/mcp-server\n */\n\nimport { createHash } from 'node:crypto';\nimport type { Tool } from '@modelcontextprotocol/sdk/types.js';\nimport {\n  parseHolo,\n  CircuitState,\n  getExportManager,\n  TraitCompositionCompiler,\n  type ExportTarget,\n  type ExportOptions,\n  type HoloComposition,\n  type TraitCompositionDecl,\n  selectModality,\n  selectModalityForAll,\n  compileHealthcareBlock,\n  compileRoboticsBlock,\n  compileIoTBlock,\n  compileEducationBlock,\n  compileMusicBlock,\n  generateROS2LaunchFile,\n  generateControllersYaml,\n} from '@holoscript/core';\nimport { handleMapSchema, handleMapCsvHeaders } from './schema-mapper';\nimport { handleAuditNumbers, auditTools } from './audit-tools';\nimport { handleFetchStructure, alphafoldTools } from './alphafold-tools';\nimport { generateWebGPUBrowserTemplate } from './renderer';\nimport {\n  HoloMCPCompiler,\n  targetSovereignty,\n  DialectRegistry,\n  registerBuiltinDialects,\n  absorbFMU,\n  streamWorldTiles,\n  WebGPUCompiler,\n  URDFCompiler,\n  AgentInferenceCompiler,\n  SceneIRCompiler,\n  emitSceneIRTsx,\n} from '@holoscript/core/compiler';\nimport {\n  derivePerceiverConsensus,\n  deriveWebGPUPerception,\n  deriveAgentInferencePerception,\n  deriveUrdfPerception,\n  diagnoseVerifiedView,\n  type PerceiverConsensusReceipt,\n  type PerceiverDerivation,\n  type VerifiedViewViolation,\n} from '@holoscript/core/reconstruction';\n\n// Initialize ExportManager singleton with memory monitoring disabled.\n// Railway containers have constrained RAM ÃƒÂ¢Ã¢â€šÂ¬Ã¢â‚¬Â the default monitoring loop\n// triggers critical alerts at 91% utilization and causes OOM SIGTERMs.\ngetExportManager({ useMemoryMonitoring: false });\n\nregisterBuiltinDialects();\n\n// Dialects that are internal/meta and should not be surfaced as user-facing export targets.\nconst _INTERNAL_DIALECT_NAMES = new Set([\n  'domain-block', 'multi-layer', 'incremental', 'mcp-config',\n  // Registered in DialectRegistry but not yet wired to a compiler-tools switch case:\n  'threejs', 'nextjs-api',\n]);\n\n// ExportManager targets not yet migrated to DialectRegistry -- surfaced via legacy path.\nconst _LEGACY_EXPORT_TARGETS = [\n  'usd', 'usdz', 'fmu', '3dgs', '3dtiles', 'canvas2d-game', 'code-editor', 'r3f',\n  'character-webgpu', // authored .holo character -> CharacterDrawSpec (sovereign); compiles via the generic compile tool\n] as const;\n\n// =============================================================================\n// TYPES\n// =============================================================================\n\nexport interface CompilationOptions {\n  /** Composition source code (.holo format) */\n  code: string;\n  /** Export target platform */\n  target: ExportTarget;\n  /** Optional configuration per compiler */\n  options?: Record<string, unknown>;\n  /** Enable streaming progress updates */\n  stream?: boolean;\n  /** Job ID for tracking (auto-generated if not provided) */\n  jobId?: string;\n}\n\nexport interface CompilationResult {\n  success: boolean;\n  jobId: string;\n  target: ExportTarget;\n  output?: string;\n  /** SHA-256 over the exact UTF-8 HoloScript source accepted by this compile. */\n  sourceSha256?: string;\n  /** SHA-256 over the exact UTF-8 output artifact returned by this compile. */\n  outputSha256?: string;\n  /**\n   * For sovereign (`webgpu`) compile targets: a self-contained HTML page that\n   * boots the native WebGPU renderer with the compiled WGSL output embedded.\n   * Absent for bridge targets (Unity, R3F, Babylon, …) — those require a\n   * third-party runtime to render.\n   */\n  previewHtml?: string;\n  error?: string;\n  warnings?: string[];\n  /**\n   * TOP-LEVEL signal (additive) that `output` is a DEGRADED reference substitute\n   * produced because the real compiler threw — NOT a true compile. `success` may\n   * still be `true` for non-empty fallbacks, so any consumer that relies on the\n   * output being a real compile MUST check `degraded` first. Mirrors the buried\n   * `metadata.usedFallback` but is unmissable at the top level.\n   */\n  degraded?: boolean;\n  metadata: {\n    compilationTimeMs: number;\n    circuitBreakerState: CircuitState;\n    usedFallback: boolean;\n    /** Mirror of top-level `degraded` for callers that read metadata. */\n    degraded?: boolean;\n    outputSizeBytes?: number;\n    sourceSha256?: string;\n    outputSha256?: string;\n    hashAlgorithm?: 'sha256';\n  };\n}\n\nexport interface CompilationStatusResult {\n  jobId: string;\n  status: 'pending' | 'in_progress' | 'completed' | 'failed';\n  progress: number; // 0-100\n  result?: CompilationResult;\n  startedAt: number;\n  completedAt?: number;\n}\n\nexport interface CircuitBreakerStatusResult {\n  target: ExportTarget;\n  state: CircuitState;\n  failureCount: number;\n  successCount: number;\n  totalRequests: number;\n  failureRate: number;\n  lastError: string | null;\n  timeInDegradedMode: number;\n  canRetry: boolean;\n}\n\n// =============================================================================\n// COMPILATION JOB TRACKING\n// =============================================================================\n\ninterface CompilationJob {\n  jobId: string;\n  status: 'pending' | 'in_progress' | 'completed' | 'failed';\n  progress: number;\n  result?: CompilationResult;\n  startedAt: number;\n  completedAt?: number;\n}\n\nconst compilationJobs = new Map<string, CompilationJob>();\n\nfunction generateJobId(): string {\n  return `compile_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;\n}\n\nfunction sha256Text(value: string): string {\n  return `sha256:${createHash('sha256').update(value, 'utf8').digest('hex')}`;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n  return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nconst EXPORT_OPTION_KEYS = new Set([\n  'useCircuitBreaker',\n  'useFallback',\n  'throwOnError',\n  'circuitConfig',\n  'compilerOptions',\n  'useMemoryMonitoring',\n  'memoryMonitorConfig',\n  'enableGaussianBudgetWarnings',\n  'gaussianBudgetOverrides',\n  'generateDocs',\n  'docsOptions',\n  'agentToken',\n]);\n\nfunction toExportOptions(options: Record<string, unknown>): Partial<ExportOptions> {\n  const exportOptions: Record<string, unknown> = {};\n  const compilerOptions: Record<string, unknown> = {};\n\n  for (const [key, value] of Object.entries(options)) {\n    if (EXPORT_OPTION_KEYS.has(key)) {\n      exportOptions[key] = value;\n    } else {\n      compilerOptions[key] = value;\n    }\n  }\n\n  const nestedCompilerOptions = isRecord(exportOptions['compilerOptions'])\n    ? exportOptions['compilerOptions']\n    : {};\n  const mergedCompilerOptions = { ...compilerOptions, ...nestedCompilerOptions };\n  if (Object.keys(mergedCompilerOptions).length > 0) {\n    exportOptions['compilerOptions'] = mergedCompilerOptions;\n  }\n\n  return exportOptions as Partial<ExportOptions>;\n}\n\nfunction normalizeTargetOptions(\n  target: ExportTarget,\n  options: Partial<ExportOptions>\n): Partial<ExportOptions> {\n  if ((target as unknown as string) !== 'vrchat') {\n    return options;\n  }\n\n  const rawOptions = options as Partial<ExportOptions> & Record<string, unknown>;\n  const hasOutputFormat = Object.prototype.hasOwnProperty.call(rawOptions, 'outputFormat');\n  const hasUseUdonSharp = Object.prototype.hasOwnProperty.call(rawOptions, 'useUdonSharp');\n  if (!hasOutputFormat && !hasUseUdonSharp) {\n    return options;\n  }\n\n  const { outputFormat, useUdonSharp, ...rest } = rawOptions;\n  const compilerOptions = isRecord(rawOptions.compilerOptions)\n    ? { ...rawOptions.compilerOptions }\n    : {};\n\n  if (hasOutputFormat) {\n    compilerOptions.outputFormat = outputFormat;\n  }\n  if (hasUseUdonSharp) {\n    compilerOptions.useUdonSharp = useUdonSharp;\n  }\n\n  return {\n    ...rest,\n    compilerOptions,\n  };\n}\n\nfunction trackJob(\n  jobId: string,\n  status: CompilationJob['status'],\n  progress: number,\n  result?: CompilationResult\n): void {\n  const job = compilationJobs.get(jobId);\n  if (job) {\n    job.status = status;\n    job.progress = progress;\n    if (result) job.result = result;\n    if (status === 'completed' || status === 'failed') {\n      job.completedAt = Date.now();\n    }\n  } else {\n    compilationJobs.set(jobId, {\n      jobId,\n      status,\n      progress,\n      result,\n      startedAt: Date.now(),\n      ...(status === 'completed' || status === 'failed' ? { completedAt: Date.now() } : {}),\n    });\n  }\n}\n\n// =============================================================================\n// COMPILER DISPATCH\n// =============================================================================\n\nasync function compileToTarget(\n  composition: HoloComposition,\n  target: ExportTarget,\n  options: Partial<ExportOptions> = {}\n): Promise<{\n  output: string;\n  usedFallback: boolean;\n  degraded: boolean;\n  warnings: string[];\n}> {\n  const exportOptions = toExportOptions(options as Record<string, unknown>);\n  if (target === 'mcp-server') {\n    const compilerOptions = isRecord(exportOptions.compilerOptions)\n      ? exportOptions.compilerOptions\n      : {};\n    const compiler = new HoloMCPCompiler(compilerOptions);\n    const agentToken = typeof exportOptions.agentToken === 'string' ? exportOptions.agentToken : '';\n    const output =\n      compilerOptions.outputKind === 'manifest'\n        ? compiler.compile(composition, agentToken)\n        : compiler.compileModule(composition, agentToken);\n\n    return {\n      output,\n      usedFallback: false,\n      degraded: false,\n      warnings: [],\n    };\n  }\n\n  const exportManager = getExportManager();\n  // ExportManager.export(target, composition, options) ÃƒÂ¢Ã¢â€šÂ¬Ã¢â‚¬Â target is first arg\n  const result = await exportManager.export(\n    target,\n    composition,\n    normalizeTargetOptions(target, exportOptions)\n  );\n\n  if (!result.success) {\n    throw new Error(result.error?.message || 'Compilation failed');\n  }\n\n  const rawOutput = (result as { output?: unknown }).output;\n  const output =\n    typeof rawOutput === 'string'\n      ? rawOutput\n      : rawOutput == null\n        ? ''\n        : JSON.stringify(rawOutput, null, 2);\n\n  return {\n    output,\n    usedFallback: result.usedFallback || false,\n    degraded: result.degraded || false,\n    warnings: result.warnings || [],\n  };\n}\n\n// =============================================================================\n// MCP TOOL HANDLERS\n// =============================================================================\n\nexport async function handleCompileToTarget(\n  args: Record<string, unknown>\n): Promise<CompilationResult> {\n  const {\n    code,\n    target,\n    options = {},\n    jobId: providedJobId,\n  } = args as {\n    code?: string;\n    target?: ExportTarget;\n    options?: Record<string, unknown>;\n    jobId?: string;\n  };\n\n  if (!code) {\n    throw new Error(\n      'code is required: pass the HoloScript source (.hs/.hsplus/.holo) to compile as the \"code\" field.'\n    );\n  }\n  if (!target) {\n    throw new Error(\n      'target is required: call the list_export_targets tool to see valid compile targets (e.g. unity, unreal, webgpu, gltf, ÃƒÂ¢Ã¢â€šÂ¬Ã‚Â¦), then pass one as \"target\".'\n    );\n  }\n\n  const jobId = providedJobId || generateJobId();\n  trackJob(jobId, 'in_progress', 10);\n\n  const startTime = Date.now();\n  const sourceSha256 = sha256Text(code);\n\n  try {\n    // Parse composition\n    trackJob(jobId, 'in_progress', 30);\n    const parseResult = parseHolo(code);\n    if (!parseResult.success || !parseResult.ast) {\n      const errors =\n        parseResult.errors?.map((e: any) => e.message).join(', ') || 'Unknown parse error';\n      throw new Error(`Failed to parse composition: ${errors}`);\n    }\n\n    const composition = parseResult.ast;\n\n    // Compile to target\n    trackJob(jobId, 'in_progress', 60);\n    const compileResult = await compileToTarget(\n      composition,\n      target,\n      options as Record<string, unknown>\n    );\n\n    const compilationTimeMs = Date.now() - startTime;\n    // Use ExportManager.getMetrics() ÃƒÂ¢Ã¢â€šÂ¬Ã¢â‚¬Â no static getInstance on CircuitBreakerRegistry\n    const circuitMetrics = getExportManager().getMetrics(target);\n    trackJob(jobId, 'in_progress', 100);\n    const outputSha256 = sha256Text(compileResult.output);\n\n    // For sovereign (webgpu) target: embed compiled output in a self-contained\n    // HTML page that boots the native WebGPU renderer — no Three.js / R3F bridge.\n    const previewHtml =\n      target === 'webgpu' && compileResult.output\n        ? generateWebGPUBrowserTemplate(\n            compileResult.output,\n            (composition as HoloComposition).name\n              ? String((composition as HoloComposition).name)\n              : 'HoloScript Scene'\n          )\n        : undefined;\n\n    // Merge parse warnings with the compiler's degraded/fallback warnings so the\n    // \"non-equivalent reference substitute\" reason is visible at the top level,\n    // not buried only inside ExportManager.\n    const mergedWarnings = [\n      ...(parseResult.warnings?.map((w: any) => w.message) ?? []),\n      ...compileResult.warnings,\n    ];\n\n    const result: CompilationResult = {\n      success: true,\n      jobId,\n      target,\n      output: compileResult.output,\n      sourceSha256,\n      outputSha256,\n      ...(previewHtml !== undefined && { previewHtml }),\n      warnings: mergedWarnings.length > 0 ? mergedWarnings : undefined,\n      degraded: compileResult.degraded,\n      metadata: {\n        compilationTimeMs,\n        circuitBreakerState: circuitMetrics.state,\n        usedFallback: compileResult.usedFallback,\n        degraded: compileResult.degraded,\n        outputSizeBytes: compileResult.output.length,\n        sourceSha256,\n        outputSha256,\n        hashAlgorithm: 'sha256',\n      },\n    };\n\n    trackJob(jobId, 'completed', 100, result);\n    return result;\n  } catch (error) {\n    const errorMessage = error instanceof Error ? error.message : String(error);\n    const result: CompilationResult = {\n      success: false,\n      jobId,\n      target,\n      error: errorMessage,\n      metadata: {\n        compilationTimeMs: Date.now() - startTime,\n        circuitBreakerState: 'open' as any,\n        usedFallback: false,\n        sourceSha256,\n        hashAlgorithm: 'sha256',\n      },\n    };\n    trackJob(jobId, 'failed', 100, result);\n    throw new Error(errorMessage);\n  }\n}\n\nexport async function handleCompileToR3F(args: Record<string, unknown>): Promise<CompilationResult> {\n  const {\n    code,\n    options = {},\n    jobId: providedJobId,\n  } = args as {\n    code?: string;\n    options?: Record<string, unknown>;\n    jobId?: string;\n  };\n\n  if (!code) {\n    throw new Error(\n      'code is required: pass the HoloScript source (.holo) to compile as the \"code\" field.'\n    );\n  }\n\n  const jobId = providedJobId || generateJobId();\n  trackJob(jobId, 'in_progress', 10);\n\n  const startTime = Date.now();\n  const sourceSha256 = sha256Text(code);\n  const format = String(options.format ?? options.outputFormat ?? 'tsx').toLowerCase();\n\n  try {\n    trackJob(jobId, 'in_progress', 30);\n    const parseResult = parseHolo(code);\n    if (!parseResult.success || !parseResult.ast) {\n      const errors =\n        parseResult.errors?.map((e: any) => e.message).join(', ') || 'Unknown parse error';\n      throw new Error(`Failed to parse composition: ${errors}`);\n    }\n\n    trackJob(jobId, 'in_progress', 60);\n    const compiler = new SceneIRCompiler(\n      isRecord(options.compilerOptions)\n        ? options.compilerOptions\n        : options\n    );\n    const agentToken = typeof options.agentToken === 'string' ? options.agentToken : undefined;\n    const outputPath =\n      typeof options.outputPath === 'string'\n        ? options.outputPath\n        : typeof options.sourcePath === 'string'\n          ? options.sourcePath\n          : undefined;\n    const compileComposition = compiler.compileComposition.bind(compiler) as (\n      composition: HoloComposition,\n      agentToken?: string,\n      outputPath?: string\n    ) => ReturnType<SceneIRCompiler['compileComposition']>;\n    const scene = compileComposition(parseResult.ast as HoloComposition, agentToken, outputPath);\n\n    const output =\n      format === 'scene-ir' || format === 'sceneir' || format === 'json'\n        ? JSON.stringify(scene, null, 2)\n        : emitSceneIRTsx(scene, {\n            componentName:\n              typeof options.componentName === 'string' ? options.componentName : undefined,\n            sourcePath:\n              typeof options.sourcePath === 'string' ? options.sourcePath : 'mcp:inline',\n            includeCanvas:\n              typeof options.includeCanvas === 'boolean' ? options.includeCanvas : true,\n          });\n\n    const outputSha256 = sha256Text(output);\n    const compilationTimeMs = Date.now() - startTime;\n    const result: CompilationResult = {\n      success: true,\n      jobId,\n      target: 'r3f' as ExportTarget,\n      output,\n      sourceSha256,\n      outputSha256,\n      warnings: parseResult.warnings?.map((warning: any) => warning.message),\n      degraded: false,\n      metadata: {\n        compilationTimeMs,\n        circuitBreakerState: 'closed' as any,\n        usedFallback: false,\n        degraded: false,\n        outputSizeBytes: output.length,\n        sourceSha256,\n        outputSha256,\n        hashAlgorithm: 'sha256',\n      },\n    };\n\n    trackJob(jobId, 'completed', 100, result);\n    return result;\n  } catch (error) {\n    const errorMessage = error instanceof Error ? error.message : String(error);\n    const result: CompilationResult = {\n      success: false,\n      jobId,\n      target: 'r3f' as ExportTarget,\n      error: errorMessage,\n      metadata: {\n        compilationTimeMs: Date.now() - startTime,\n        circuitBreakerState: 'open' as any,\n        usedFallback: false,\n        sourceSha256,\n        hashAlgorithm: 'sha256',\n      },\n    };\n    trackJob(jobId, 'failed', 100, result);\n    throw new Error(errorMessage);\n  }\n}\n\n// =============================================================================\n// CROSS-PERCEIVER CONSENSUS (@cross_perceiver_contract)\n// =============================================================================\n\n/** The perceiver compilers the cross-perceiver falsification oracle can fan to. */\nconst CROSS_PERCEIVER_IDS = ['webgpu', 'agent-inference', 'urdf'] as const;\nexport type CrossPerceiverId = (typeof CROSS_PERCEIVER_IDS)[number];\n\nexport interface CrossPerceiverVerifyResult {\n  success: true;\n  /**\n   * Mirror of receipt.verdict at the top level for quick consumption.\n   * LOAD-BEARING: FALSIFIED is a hard failure — consumers must never demote\n   * it to a warning (same discipline as the `degraded` compile flag).\n   */\n  verdict: 'CONSENSUS' | 'FALSIFIED';\n  /** The full perceiver-consensus receipt (artifact hashes, disagreements, receiptHash). */\n  receipt: PerceiverConsensusReceipt;\n  /** Perceivers actually compiled + derived, in canonical order. */\n  perceivers: CrossPerceiverId[];\n  /** SHA-256 over the exact UTF-8 HoloScript source accepted by this verification. */\n  sourceSha256: string;\n  metadata: {\n    compilationTimeMs: number;\n  };\n}\n\n/**\n * verify_cross_perceiver — compile ONE .holo composition through structurally\n * different perceiver compilers, independently re-derive world facts from each\n * EMITTED ARTIFACT (never the shared AST), and diff them into a\n * PerceiverConsensusReceipt. Disagreement = FALSIFIED.\n *\n * RBAC: threads options.agentToken (the same field handleCompileToTarget\n * threads to compilers) into each perceiver compiler's own\n * compile(composition, agentToken) validation — no new auth path.\n */\nexport async function handleVerifyCrossPerceiver(\n  args: Record<string, unknown>\n): Promise<CrossPerceiverVerifyResult> {\n  const { code, perceivers, options = {} } = args as {\n    code?: string;\n    perceivers?: unknown;\n    options?: Record<string, unknown>;\n  };\n\n  if (!code) {\n    throw new Error(\n      'code is required: pass the HoloScript source (.holo) to cross-verify as the \"code\" field.'\n    );\n  }\n\n  const requested: unknown[] =\n    perceivers === undefined ? [...CROSS_PERCEIVER_IDS] : (perceivers as unknown[]);\n  if (!Array.isArray(requested) || requested.some((p) => typeof p !== 'string')) {\n    throw new Error(\n      `perceivers must be an array of perceiver ids — valid perceivers: ${CROSS_PERCEIVER_IDS.join(', ')}`\n    );\n  }\n  const unknownIds = requested.filter(\n    (p) => !(CROSS_PERCEIVER_IDS as readonly string[]).includes(p as string)\n  );\n  if (unknownIds.length > 0) {\n    throw new Error(\n      `Unknown perceiver(s) ${JSON.stringify(unknownIds)} — valid perceivers: ${CROSS_PERCEIVER_IDS.join(', ')}`\n    );\n  }\n  // Canonical order + dedupe (the differ refuses duplicate perceiver ids).\n  const resolved = CROSS_PERCEIVER_IDS.filter((p) => requested.includes(p));\n  if (resolved.length < 2) {\n    throw new Error(\n      'verify_cross_perceiver requires at least 2 distinct perceivers — a single-perceiver ' +\n        'receipt is circular and proves nothing. Valid perceivers: ' +\n        `${CROSS_PERCEIVER_IDS.join(', ')}.`\n    );\n  }\n\n  const startTime = Date.now();\n  const sourceSha256 = sha256Text(code);\n\n  const parseResult = parseHolo(code);\n  if (!parseResult.success || !parseResult.ast) {\n    const errors =\n      parseResult.errors?.map((e: any) => e.message).join(', ') || 'Unknown parse error';\n    throw new Error(`Failed to parse composition: ${errors}`);\n  }\n  const composition = parseResult.ast;\n\n  // Same token threading as handleCompileToTarget (EXPORT_OPTION_KEYS.agentToken):\n  // each compiler's compile() validates the token itself; empty = compiler's own\n  // backwards-compatible skip, exactly as the generic compile path behaves.\n  const agentToken =\n    typeof (options as Record<string, unknown>).agentToken === 'string'\n      ? ((options as Record<string, unknown>).agentToken as string)\n      : '';\n\n  const derivations: PerceiverDerivation[] = resolved.map((perceiver) => {\n    switch (perceiver) {\n      case 'webgpu':\n        return deriveWebGPUPerception(new WebGPUCompiler({}).compile(composition, agentToken));\n      case 'agent-inference':\n        return deriveAgentInferencePerception(\n          new AgentInferenceCompiler({ language: 'typescript' }).compile(composition, agentToken)\n        );\n      case 'urdf':\n        return deriveUrdfPerception(new URDFCompiler({}).compile(composition, agentToken));\n      default: {\n        // Exhaustiveness guard — unreachable (ids validated above).\n        throw new Error(`Unhandled perceiver: ${String(perceiver)}`);\n      }\n    }\n  });\n\n  const receipt = derivePerceiverConsensus(derivations);\n\n  return {\n    success: true,\n    verdict: receipt.verdict,\n    receipt,\n    perceivers: resolved,\n    sourceSha256,\n    metadata: {\n      compilationTimeMs: Date.now() - startTime,\n    },\n  };\n}\n\nexport interface VerifiedViewCheckResult {\n  success: true;\n  /**\n   * LOAD-BEARING: `complete: false` is a hard failure — an agent-authored surface that\n   * cannot prove what it renders must NOT ship. Consumers must never demote it to a warning\n   * (same discipline as verify_cross_perceiver's FALSIFIED verdict).\n   */\n  complete: boolean;\n  /** Whether the surface binds any data (a binding-free surface is trivially complete). */\n  hasBindings: boolean;\n  /** Whether the surface opts into the gate via composition-level `@verified_view`. */\n  verifiedViewOn: boolean;\n  /** Every provenance violation found — collected, not throw-on-first (unlike compiling). */\n  violations: VerifiedViewViolation[];\n  /** SHA-256 over the exact UTF-8 HoloScript source accepted by this verification. */\n  sourceSha256: string;\n}\n\n/**\n * verify_verified_view — the `@verified_view` admission check for a 2D agent-authored surface,\n * exposed as an agent-callable oracle. Compiling the surface would throw on the FIRST\n * VIEW-UNGROUNDED violation; this re-derives the same contract Native2DCompiler.resolveProjection\n * enforces and returns EVERY violation at once (a `@projects` that names a different path than\n * its binding, a hallucinated state root, a `@projects` on an unbound element, a data-bound\n * element with no receipt, or a surface that binds data without opting into `@verified_view`).\n * Unverifiable input (unparseable / degenerate implicit parse) is a hard error, never a false\n * \"clean\" (W.776).\n */\nexport async function handleVerifyVerifiedView(\n  args: Record<string, unknown>\n): Promise<VerifiedViewCheckResult> {\n  const { code } = args as { code?: string };\n  if (!code) {\n    throw new Error(\n      'code is required: pass the HoloScript 2D surface source (.holo) to verify as the \"code\" field.'\n    );\n  }\n\n  const diagnosis = diagnoseVerifiedView(code);\n  if (!diagnosis.parsed) {\n    throw new Error(\n      'verify_verified_view: the source is not a verifiable HoloScript surface (unparseable or ' +\n        'a degenerate implicit parse). A verification tool must fail loud rather than report ' +\n        'unrecognized input as honest.'\n    );\n  }\n\n  return {\n    success: true,\n    complete: diagnosis.complete,\n    hasBindings: diagnosis.hasBindings,\n    verifiedViewOn: diagnosis.verifiedViewOn,\n    violations: diagnosis.violations,\n    sourceSha256: sha256Text(code),\n  };\n}\n\nexport async function handleStreamWorldTiles(args: Record<string, unknown>): Promise<{\n  success: true;\n  target: '3dtiles';\n  manifestUrl: string;\n  streamId: string;\n  tileset: unknown;\n  manifest: unknown;\n  files: Record<string, string>;\n  metadata: {\n    tileCount: number;\n    lodLevels: string[];\n    outputSizeBytes: number;\n  };\n}> {\n  const { code, options = {} } = args as {\n    code?: string;\n    options?: Record<string, unknown>;\n  };\n\n  if (!code) {\n    throw new Error(\n      'code is required: pass the HoloScript source with @gaussian_splat data as the \"code\" field.'\n    );\n  }\n\n  const parseResult = parseHolo(code);\n  if (!parseResult.success || !parseResult.ast) {\n    const errors =\n      parseResult.errors?.map((e: any) => e.message).join(', ') || 'Unknown parse error';\n    throw new Error(`Failed to parse composition: ${errors}`);\n  }\n\n  const stream = streamWorldTiles(parseResult.ast, options as Parameters<typeof streamWorldTiles>[1]);\n  return {\n    ...stream,\n    metadata: {\n      tileCount: stream.manifest.tiles.length,\n      lodLevels: stream.manifest.stream.lodLevels,\n      outputSizeBytes: JSON.stringify(stream.files).length,\n    },\n  };\n}\n\nexport async function handleComposeTraits(args: Record<string, unknown>): Promise<unknown> {\n  const { declarations, baseTraits = {} } = args as {\n    declarations: TraitCompositionDecl[];\n    baseTraits?: Record<string, { defaultConfig?: Record<string, unknown>; conflicts?: string[] }>;\n  };\n\n  if (!declarations || !Array.isArray(declarations)) {\n    throw new Error('declarations array is required');\n  }\n\n  const compiler = new TraitCompositionCompiler();\n\n  const getHandler = (name: string) => {\n    if (baseTraits[name]) {\n      return baseTraits[name];\n    }\n    // For pure architectural resolution, if a trait isn't provided,\n    // we assume an empty config instead of crashing, or expect the client to provide all dependencies.\n    return { defaultConfig: {}, conflicts: [] };\n  };\n\n  try {\n    const results = compiler.compile(declarations, getHandler);\n    return { success: true, composedTraits: results };\n  } catch (error) {\n    const errorMessage = error instanceof Error ? error.message : String(error);\n    return { success: false, error: errorMessage };\n  }\n}\n\nexport async function handleCompileMCPConfig(args: Record<string, unknown>): Promise<unknown> {\n  try {\n    const code = args.code as string;\n    if (!code) return { error: 'Missing required field: code' };\n\n    const target = (args.target as string) || 'generic';\n    const envValues = (args.envValues as Record<string, string>) || {};\n\n    const { parseHolo } = await import('@holoscript/core');\n    const { MCPConfigCompiler } = await import('@holoscript/core/compiler');\n\n    const composition = parseHolo(code);\n    const compiler = new MCPConfigCompiler({\n      target: target as 'claude' | 'vscode' | 'cursor' | 'antigravity' | 'generic',\n      envValues,\n    });\n\n    const output = compiler.compile(composition, 'mcp-config-token');\n\n    return {\n      success: true,\n      target,\n      config: JSON.parse(output),\n      raw: output,\n    };\n  } catch (err) {\n    return {\n      error: `MCP config compilation failed: ${err instanceof Error ? err.message : String(err)}`,\n    };\n  }\n}\n\nexport async function handleSelectModality(args: Record<string, unknown>): Promise<unknown> {\n  const { platform, platforms, preferStreaming } = args as {\n    platform?: string;\n    platforms?: string[];\n    preferStreaming?: boolean;\n  };\n\n  const options = { preferStreaming: preferStreaming ?? false };\n\n  if (platform) {\n    const result = selectModality(platform, options);\n    return { success: true, selection: result };\n  }\n\n  if (platforms && Array.isArray(platforms)) {\n    const results: Record<string, ReturnType<typeof selectModality>> = {};\n    for (const p of platforms) {\n      results[p] = selectModality(p, options);\n    }\n    return { success: true, selections: results };\n  }\n\n  // No platform specified ÃƒÂ¢Ã¢â€šÂ¬Ã¢â‚¬Â return all 18\n  const all = selectModalityForAll(options);\n  const selections: Record<string, ReturnType<typeof selectModality>> = {};\n  for (const [p, sel] of all) {\n    selections[p] = sel;\n  }\n  return { success: true, selections };\n}\n\nexport async function handleGetCompilationStatus(\n  args: Record<string, unknown>\n): Promise<CompilationStatusResult> {\n  const { jobId } = args as { jobId: string };\n\n  if (!jobId) {\n    throw new Error('jobId is required');\n  }\n\n  const job = compilationJobs.get(jobId);\n  if (!job) {\n    throw new Error(`Job not found: ${jobId}`);\n  }\n\n  return {\n    jobId: job.jobId,\n    status: job.status,\n    progress: job.progress,\n    result: job.result,\n    startedAt: job.startedAt,\n    completedAt: job.completedAt,\n  };\n}\n\n// =============================================================================\n// QASM HANDLER\n// =============================================================================\n\n/**\n * compile_to_qasm ÃƒÂ¢Ã¢â€šÂ¬Ã¢â‚¬Â HoloScript ÃƒÂ¢Ã¢â‚¬Â Ã¢â‚¬â„¢ OpenQASM 3.0\n *\n * Parses the provided HoloScript source, finds the first @quantumCircuit\n * (or @quantum_circuit) trait node, and returns a QASMOutput JSON object.\n *\n * Uses a dynamic import of @holoscript/core/compiler (matching the pattern of\n * handleCompileMCPConfig) so this file can be type-checked before the core\n * dist is rebuilt.\n */\nexport async function handleCompileToQasm(args: Record<string, unknown>): Promise<unknown> {\n  const { source } = args as { source?: string };\n\n  if (!source || typeof source !== 'string' || source.trim().length === 0) {\n    return { error: 'Missing required field: source (HoloScript source string)' };\n  }\n\n  try {\n    const parseResult = parseHolo(source);\n    if (!parseResult.success || !parseResult.ast) {\n      const errors =\n        (parseResult.errors as Array<{ message: string }> | undefined)\n          ?.map((e) => e.message)\n          .join(', ') ?? 'Unknown parse error';\n      return { error: `Failed to parse HoloScript source: ${errors}` };\n    }\n\n    const composition = parseResult.ast as HoloComposition;\n\n    const { QuantumCircuitCompiler } = await import('@holoscript/core/compiler');\n    const compiler = new QuantumCircuitCompiler();\n    const output = compiler.compile(composition);\n\n    return output;\n  } catch (err: unknown) {\n    return {\n      error: `compile_to_qasm failed: ${err instanceof Error ? err.message : String(err)}`,\n    };\n  }\n}\n\n/** Generic handler for domain block compilation */\nasync function handleDomainBlock(\n  args: Record<string, unknown>,\n  compileFn: (block: any) => unknown,\n  domain: string\n): Promise<unknown> {\n  const { properties, code } = args as { properties?: Record<string, unknown>; code?: string };\n\n  if (code) {\n    // Parse .holo code to extract domain block\n    try {\n      const parsed = parseHolo(code);\n      const block = parsed.domainBlocks?.find((b: any) => b.domain === domain || b.name === domain);\n      if (!block) return { success: false, error: `No ${domain} {} block found in composition` };\n      return { success: true, domain, compiled: compileFn(block) };\n    } catch (e) {\n      return {\n        success: false,\n        error: `Parse error: ${e instanceof Error ? e.message : String(e)}`,\n      };\n    }\n  }\n\n  if (properties) {\n    // Direct property object ÃƒÂ¢Ã¢â€šÂ¬Ã¢â‚¬Â wrap as HoloDomainBlock\n    const block = { type: 'DomainBlock', name: domain, domain, properties };\n    return { success: true, domain, compiled: compileFn(block) };\n  }\n\n  return {\n    success: false,\n    error: `Provide \"code\" (.holo with ${domain} {} block) or \"properties\" (direct property map)`,\n  };\n}\n\nexport async function handleListExportTargets(_args: Record<string, unknown>): Promise<{\n  targets: ExportTarget[];\n  categories: Record<string, ExportTarget[]>;\n  sovereignty: Record<string, 'sovereign' | 'bridge' | 'mode'>;\n}> {\n  const dialectNames = DialectRegistry.names().filter(\n    (n) => !_INTERNAL_DIALECT_NAMES.has(n),\n  );\n  const legacyNames = Array.from(_LEGACY_EXPORT_TARGETS).filter(\n    (n) => !dialectNames.includes(n),\n  );\n  const targets = [...dialectNames, ...legacyNames] as unknown as ExportTarget[];\n\n  const categories: Record<string, ExportTarget[]> = {\n    'Game Engines': ['unity', 'unreal', 'pcg-graph', 'godot', 'canvas2d-game'] as unknown as ExportTarget[],\n    'VR Platforms': ['vrchat', 'openxr'] as unknown as ExportTarget[],\n    'Mobile AR': ['android', 'android-xr', 'ios', 'visionos'] as unknown as ExportTarget[],\n    // ar, babylon, playcanvas, vrr retired as apex-poison 2026-06-17.\n    // r3f is restored as SceneIR -> generated TSX shell, not the retired handwritten JSX compiler.\n    'Web Platforms': ['webgpu', 'character-webgpu', 'r3f', 'wasm'] as unknown as ExportTarget[],\n    'Robotics/IoT': ['urdf', 'sdf', 'mjcf', 'mjx', 'embodied-dataset', 'dtdl'] as unknown as ExportTarget[],\n    '3D Formats': ['usd', 'usdz', 'fmu', '3dgs', '3dtiles'] as unknown as ExportTarget[],\n    'Studio Tools': ['code-editor'] as unknown as ExportTarget[],\n    'AI/MCP': [\n      'a2a-agent-card',\n      'agent-inference',\n      'omnigent-agent-yaml',\n      'daimon-seed',\n      'mcp-server',\n      'llama-server',\n    ] as unknown as ExportTarget[],\n  };\n\n  const sovereignty: Record<string, 'sovereign' | 'bridge' | 'mode'> = {};\n  for (const t of targets) {\n    sovereignty[t] = targetSovereignty(t);\n  }\n\n  return { targets, categories, sovereignty };\n}\n\nexport async function handleGetCircuitBreakerStatus(\n  args: Record<string, unknown>\n): Promise<CircuitBreakerStatusResult> {\n  const { target } = args as { target: ExportTarget };\n\n  if (!target) {\n    throw new Error('target is required');\n  }\n\n  // Use ExportManager.getMetrics() ÃƒÂ¢Ã¢â€šÂ¬Ã¢â‚¬Â no static getInstance on CircuitBreakerRegistry\n  const metrics = getExportManager().getMetrics(target);\n\n  return {\n    target,\n    state: metrics.state,\n    failureCount: metrics.failureCount,\n    successCount: metrics.successCount,\n    totalRequests: metrics.totalRequests,\n    failureRate: metrics.failureRate,\n    lastError: metrics.lastError,\n    timeInDegradedMode: metrics.timeInDegradedMode,\n    canRetry: metrics.state !== 'open',\n  };\n}\n\n// =============================================================================\n// HANDLER DISPATCHER\n// =============================================================================\n\nexport async function handleCompilerTool(\n  name: string,\n  args: Record<string, unknown>\n): Promise<unknown | null> {\n  switch (name) {\n    // Generic compilation\n    case 'compile_holoscript':\n      return handleCompileToTarget(args);\n\n    // Proof-of-Play / Thin Client Delegation Tool\n    case 'holoscript_compose_traits':\n      return handleComposeTraits(args);\n\n    // Convenience tools for popular targets\n    case 'compile_to_unity':\n      return handleCompileToTarget({ ...args, target: 'unity' });\n    case 'compile_to_unreal':\n      return handleCompileToTarget({ ...args, target: 'unreal' });\n    case 'compile_to_pcg_graph':\n      return handleCompileToTarget({ ...args, target: 'pcg-graph' });\n    case 'compile_to_urdf':\n      return handleCompileToTarget({ ...args, target: 'urdf' });\n    case 'compile_to_sdf':\n      return handleCompileToTarget({ ...args, target: 'sdf' });\n    case 'compile_to_mjcf':\n      return handleCompileToTarget({ ...args, target: 'mjcf' });\n    case 'compile_to_mjx':\n      return handleCompileToTarget({ ...args, target: 'mjx' });\n    case 'compile_to_embodied_dataset':\n      return handleCompileToTarget({ ...args, target: 'embodied-dataset' });\n    case 'compile_to_ros2_deploy': {\n      const {\n        code,\n        packageName = 'holoscript_robot',\n        options = {},\n      } = args as {\n        code: string;\n        packageName?: string;\n        options?: {\n          useSimTime?: boolean;\n          rviz?: boolean;\n          gazebo?: boolean;\n          controllers?: string[];\n        };\n      };\n      const urdfResult = await handleCompileToTarget({ code, target: 'urdf', options });\n      const urdfContent = urdfResult.output ?? '';\n      if (!urdfResult.success || !urdfContent) {\n        throw new Error(\n          `URDF compilation failed for ROS 2 bundle: ${urdfResult.error ?? 'empty output'}`\n        );\n      }\n      const urdfFilename = `${packageName}.urdf`;\n      const launchFile = generateROS2LaunchFile(packageName, urdfFilename, options);\n      const controllersYaml = generateControllersYaml(packageName, options.controllers ?? []);\n      return {\n        content: [\n          {\n            type: 'text',\n            text: JSON.stringify(\n              { urdf: urdfContent, launchFile, controllersYaml, packageName, urdfFilename },\n              null,\n              2\n            ),\n          },\n        ],\n      };\n    }\n    case 'compile_to_webgpu':\n      return handleCompileToTarget({ ...args, target: 'webgpu' });\n    case 'compile_to_r3f':\n      return handleCompileToR3F(args);\n    case 'compile_to_godot':\n      return handleCompileToTarget({ ...args, target: 'godot' });\n    case 'compile_to_visionos':\n      return handleCompileToTarget({ ...args, target: 'visionos' });\n    case 'compile_to_openxr':\n      return handleCompileToTarget({ ...args, target: 'openxr' });\n    // compile_to_babylon, compile_to_playcanvas — retired (apex-poison, 2026-06-17)\n    case 'compile_to_vrchat':\n      return handleCompileToTarget({ ...args, target: 'vrchat' });\n    case 'compile_to_android':\n      return handleCompileToTarget({ ...args, target: 'android' });\n    case 'compile_to_android_xr':\n      return handleCompileToTarget({ ...args, target: 'android-xr' });\n    case 'compile_to_quest':\n      return handleCompileToTarget({ ...args, target: 'quest' });\n    case 'compile_to_ios':\n      return handleCompileToTarget({ ...args, target: 'ios' });\n    // compile_to_ar — retired (apex-poison, 2026-06-17)\n    case 'compile_to_wasm':\n      return handleCompileToTarget({ ...args, target: 'wasm' });\n    case 'compile_to_character_webgpu':\n      return handleCompileToTarget({ ...args, target: 'character-webgpu' });\n    case 'compile_to_usd':\n      return handleCompileToTarget({ ...args, target: 'usd' });\n    case 'compile_to_usdz':\n      return handleCompileToTarget({ ...args, target: 'usdz' });\n    case 'compile_to_fmu':\n      return handleCompileToTarget({ ...args, target: 'fmu' });\n    case 'absorb_fmu':\n      return absorbFMU(args as Parameters<typeof absorbFMU>[0]);\n    case 'compile_to_dtdl':\n      return handleCompileToTarget({ ...args, target: 'dtdl' });\n    // compile_to_vrr — retired (apex-poison, 2026-06-17)\n    // compile_to_multi_layer — retired (MultiLayerCompiler retired 2026-06-17; the tool advertised a target that always threw)\n    case 'compile_to_nir':\n      return handleCompileToTarget({ ...args, target: 'nir' });\n    // compile_to_native_2d — retired (apex-poison, 2026-06-17)\n    case 'compile_to_canvas2d_game':\n      return handleCompileToTarget({ ...args, target: 'canvas2d-game' });\n    case 'compile_to_node_service':\n      return handleCompileToTarget({ ...args, target: 'node-service' });\n    case 'compile_to_a2a_agent_card':\n      return handleCompileToTarget({ ...args, target: 'a2a-agent-card' });\n    case 'compile_to_agent_inference':\n      return handleCompileToTarget({ ...args, target: 'agent-inference' });\n    case 'compile_to_omnigent_agent_yaml':\n      return handleCompileToTarget({ ...args, target: 'omnigent-agent-yaml' });\n    case 'compile_to_daimon_seed':\n      return handleCompileToTarget({ ...args, target: 'daimon-seed' });\n    case 'compile_to_state':\n      return handleCompileToTarget({ ...args, target: 'state' });\n    case 'compile_to_3dgs':\n      return handleCompileToTarget({ ...args, target: '3dgs' });\n    case 'compile_to_3dtiles':\n      return handleCompileToTarget({ ...args, target: '3dtiles' });\n    case 'stream_world_tiles':\n      return handleStreamWorldTiles(args);\n    case 'compile_to_gaussian_train':\n      return handleCompileToTarget({ ...args, target: 'gaussian-train' });\n    case 'compile_to_code_editor':\n      return handleCompileToTarget({ ...args, target: 'code-editor' });\n\n    case 'compile_to_svg':\n      return handleCompileToTarget({ ...args, target: 'svg' });\n    case 'compile_to_holob':\n      return handleCompileToTarget({ ...args, target: 'holob' });\n    case 'compile_to_openapi':\n      return handleCompileToTarget({ ...args, target: 'openapi' });\n    case 'compile_to_sdk': {\n      const rawOptions = isRecord(args.options) ? args.options : {};\n      const requestedSdkTarget =\n        typeof args.target === 'string' && args.target.startsWith('sdk:') ? args.target : undefined;\n      return handleCompileToTarget({\n        ...args,\n        options: requestedSdkTarget ? { ...rawOptions, target: requestedSdkTarget } : rawOptions,\n        target: 'sdk',\n      });\n    }\n    case 'compile_to_onnx':\n      return handleCompileToTarget({ ...args, target: 'onnx' });\n    case 'compile_to_flutter':\n      return handleCompileToTarget({ ...args, target: 'flutter' });\n    case 'compile_to_stl_export':\n      return handleCompileToTarget({ ...args, target: 'stl-export' });\n    case 'compile_to_lens_studio':\n      return handleCompileToTarget({ ...args, target: 'lens-studio' });\n    case 'compile_to_colyseus':\n      return handleCompileToTarget({ ...args, target: 'colyseus' });\n    case 'compile_to_ai_glasses':\n      return handleCompileToTarget({ ...args, target: 'ai-glasses' });\n    case 'compile_to_scm':\n      return handleCompileToTarget({ ...args, target: 'scm' });\n    case 'compile_to_nft_marketplace':\n      return handleCompileToTarget({ ...args, target: 'nft-marketplace' });\n    case 'compile_to_tsl':\n      return handleCompileToTarget({ ...args, target: 'tsl' });\n    // compile_to_phone_sleeve_vr — retired (apex-poison, 2026-06-17)\n    case 'compile_to_openxr_spatial_entities':\n      return handleCompileToTarget({ ...args, target: 'openxr-spatial-entities' });\n    case 'compile_to_edge':\n      return handleCompileToTarget({ ...args, target: 'edge' });\n    case 'compile_to_llama_server':\n      return handleCompileToTarget({ ...args, target: 'llama-server' });\n    case 'compile_to_bot_swarm':\n      return handleCompileToTarget({ ...args, target: 'bot-swarm' });\n    case 'compile_to_dungeon_instance':\n      return handleCompileToTarget({ ...args, target: 'dungeon-instance' });\n    case 'compile_to_world_shard':\n      return handleCompileToTarget({ ...args, target: 'world-shard' });\n\n    case 'compile_to_mcp_config':\n      return handleCompileMCPConfig(args);\n\n    case 'compile_to_mcp_server':\n      return handleCompileToTarget({ ...args, target: 'mcp-server' });\n\n    // Modality Transliteration (Pillar 1)\n    case 'holoscript_select_modality':\n      return handleSelectModality(args);\n\n    // Universal Schema-to-Trait Mapper (Domain Bridge)\n    case 'holoscript_map_schema':\n      return handleMapSchema(args);\n    case 'holoscript_map_csv':\n      return handleMapCsvHeaders(args);\n\n    // Domain Block Compilers (top 5 ÃƒÂ¢Ã¢â€šÂ¬Ã¢â‚¬Â exposed from DomainBlockCompilerMixin)\n    case 'holoscript_compile_healthcare':\n      return handleDomainBlock(args, compileHealthcareBlock, 'healthcare');\n    case 'holoscript_compile_robotics':\n      return handleDomainBlock(args, compileRoboticsBlock, 'robotics');\n    case 'holoscript_compile_iot':\n      return handleDomainBlock(args, compileIoTBlock, 'iot');\n    case 'holoscript_compile_education':\n      return handleDomainBlock(args, compileEducationBlock, 'education');\n    case 'holoscript_compile_music':\n      return handleDomainBlock(args, compileMusicBlock, 'music');\n\n    // Audit\n    case 'holoscript_audit_numbers':\n      return handleAuditNumbers(args);\n\n    // AlphaFold ÃƒÂ¢Ã¢â€šÂ¬Ã¢â‚¬Â drug-discovery flagship Stage 5 (see docs/strategy/drug-discovery-flagship.md)\n    case 'alphafold_fetch_structure':\n      return handleFetchStructure(args);\n\n    // Quantum circuit compilation ÃƒÂ¢Ã¢â€šÂ¬Ã¢â‚¬Â HoloScript ÃƒÂ¢Ã¢â‚¬Â Ã¢â‚¬â„¢ OpenQASM 3.0\n    case 'compile_to_qasm':\n      return handleCompileToQasm(args);\n\n    // Cross-perceiver consensus verification (@cross_perceiver_contract)\n    case 'verify_cross_perceiver':\n      return handleVerifyCrossPerceiver(args);\n\n    // Verified-view provenance check (@verified_view) for agent-authored 2D surfaces\n    case 'verify_verified_view':\n      return handleVerifyVerifiedView(args);\n\n    // Status and metadata tools\n    case 'get_compilation_status':\n      return handleGetCompilationStatus(args);\n    case 'list_export_targets':\n      return handleListExportTargets(args);\n    case 'get_circuit_breaker_status':\n      return handleGetCircuitBreakerStatus(args);\n\n    // Not a compiler tool\n    default:\n      return null;\n  }\n}\n\n// =============================================================================\n// MCP TOOL DEFINITIONS\nexport const compilerTools: Tool[] = [\n  // Trait Composition (Unlocks Pillar 3 Thin-Client Delegation)\n  {\n    name: 'holoscript_compose_traits',\n    description:\n      'Cryptographically delegate heavy trait algebra and physics composition to the cloud. Accepts raw composition declarations (e.g., trait C = A + B) and returns fully resolved trait nodes using the ProvenanceSemiring.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        declarations: {\n          type: 'array',\n          description: 'Array of trait composition declarations',\n          items: {\n            type: 'object',\n            properties: {\n              name: { type: 'string' },\n              components: { type: 'array', items: { type: 'string' } },\n              overrides: { type: 'object' },\n            },\n            required: ['name', 'components'],\n          },\n        },\n        baseTraits: {\n          type: 'object',\n          description:\n            'Optional map of base trait names to their handler configs to resolve against',\n        },\n      },\n      required: ['declarations'],\n    },\n  },\n  // Domain Block Compilers (5 of 21 ÃƒÂ¢Ã¢â€šÂ¬Ã¢â‚¬Â from DomainBlockCompilerMixin, 4,614 LOC)\n  ...(['healthcare', 'robotics', 'iot', 'education', 'music'] as const).map((domain) => ({\n    name: `holoscript_compile_${domain}` as string,\n    description:\n      `Compile a ${domain} domain block from .holo code or raw properties. ` +\n      `Part of 21 domain-specific code generators in DomainBlockCompilerMixin. ` +\n      `Accepts either \"code\" (full .holo with ${domain} {} block) or \"properties\" (direct property map).`,\n    inputSchema: {\n      type: 'object' as const,\n      properties: {\n        code: {\n          type: 'string',\n          description: `.holo source containing a ${domain} {} domain block`,\n        },\n        properties: {\n          type: 'object',\n          description: `Direct property map for ${domain} compilation`,\n        },\n      },\n    },\n  })),\n  // Universal Schema-to-Trait Mapper (Domain Bridge ÃƒÂ¢Ã¢â€šÂ¬Ã¢â‚¬Â any data ÃƒÂ¢Ã¢â‚¬Â Ã¢â‚¬â„¢ .holo)\n  {\n    name: 'holoscript_map_schema',\n    description:\n      'Map any structured data schema to HoloScript traits and generate a .holo composition. ' +\n      'The universal domain bridge: dispensary menu, restaurant catalog, real estate listings, IoT sensors ÃƒÂ¢Ã¢â€šÂ¬Ã¢â‚¬Â ' +\n      'any data schema maps onto the 3,300+ trait system. Returns per-field trait mappings with confidence scores, ' +\n      'parameter bindings, spatial role assignments, and a ready-to-compile .holo composition.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        name: { type: 'string', description: 'Name for the data source (e.g., \"dispensary_menu\")' },\n        domain: {\n          type: 'string',\n          description: 'Optional domain hint (retail, healthcare, hospitality, iot, etc.)',\n        },\n        description: { type: 'string', description: 'What this data represents' },\n        fields: {\n          type: 'array',\n          description: 'Schema fields to map',\n          items: {\n            type: 'object',\n            properties: {\n              name: { type: 'string', description: 'Field name (e.g., \"thc_percent\")' },\n              type: { type: 'string', enum: ['string', 'number', 'boolean', 'array', 'object'] },\n              description: { type: 'string' },\n              example: { description: 'Example value for type inference' },\n            },\n            required: ['name', 'type'],\n          },\n        },\n        schema: {\n          type: 'object',\n          description: 'Alternative: provide a full DataSchema object directly',\n        },\n      },\n    },\n  },\n  {\n    name: 'holoscript_map_csv',\n    description:\n      'Map CSV headers to HoloScript traits. Provide column headers and optionally a sample row ' +\n      'for type inference. Returns the same trait mappings and .holo composition as holoscript_map_schema.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        headers: {\n          type: 'array',\n          items: { type: 'string' },\n          description: 'CSV column headers',\n        },\n        name: { type: 'string', description: 'Name for the data source' },\n        domain: { type: 'string', description: 'Optional domain hint' },\n        description: { type: 'string' },\n        sample_row: {\n          type: 'object',\n          description:\n            'Optional sample data row for type inference (keys = headers, values = sample data)',\n        },\n      },\n      required: ['headers'],\n    },\n  },\n  // Modality Transliteration (Pillar 1: device ÃƒÂ¢Ã¢â‚¬Â Ã¢â‚¬â„¢ embodiment ÃƒÂ¢Ã¢â‚¬Â Ã¢â‚¬â„¢ compiler)\n  {\n    name: 'holoscript_select_modality',\n    description:\n      'Auto-select the optimal output modality for a device platform. ' +\n      'Given a platform target (quest3, ios, android-auto, etc.), returns the embodiment type ' +\n      '(FullAvatar, UI2D, VoiceOnly, GlassOverlay), the ExportTarget to compile to, ' +\n      'whether the device can render spatially, and whether neural streaming is recommended. ' +\n      'Transliteration, not degradation: a phone gets Native 2D UI, not a broken 3D box.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        platform: {\n          type: 'string',\n          description: 'Single platform target',\n          enum: [\n            'quest3',\n            'pcvr',\n            'visionos',\n            'android-xr',\n            'visionos-ar',\n            'android-xr-ar',\n            'webxr',\n            'ios',\n            'android',\n            'windows',\n            'macos',\n            'linux',\n            'web',\n            'android-auto',\n            'carplay',\n            'watchos',\n            'wearos',\n          ],\n        },\n        platforms: {\n          type: 'array',\n          description: 'Multiple platform targets (returns selection for each)',\n          items: { type: 'string' },\n        },\n        preferStreaming: {\n          type: 'boolean',\n          description: 'Prefer neural streaming over local rendering when device lacks spatial GPU',\n        },\n      },\n    },\n  },\n  // Generic compilation tool (supports all targets)\n  {\n    name: 'compile_holoscript',\n    description:\n      'Compile HoloScript composition to any export target (Unity, Unreal, URDF, SDF, WebGPU, WASM, etc.). ' +\n      'Returns compiled output with circuit breaker protection and comprehensive error reporting. ' +\n      'Supports 18+ export targets across game engines, VR platforms, mobile AR, web, robotics, and 3D formats.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        code: {\n          type: 'string',\n          description: 'HoloScript composition source code (.holo format)',\n        },\n        target: {\n          type: 'string',\n          enum: [\n            'urdf',\n            'sdf',\n            'unity',\n            'unreal',\n            'pcg-graph',\n            'godot',\n            'vrchat',\n            'openxr',\n            'android',\n            'android-xr',\n            'ios',\n            'visionos',\n            // 'ar' — retired apex-poison 2026-06-17\n            // 'babylon' — retired apex-poison 2026-06-17\n            'webgpu',\n            'character-webgpu',\n            'r3f',\n            'wasm',\n            // 'playcanvas' — retired apex-poison 2026-06-17\n            'usd',\n            'usdz',\n            'fmu',\n            'dtdl',\n            // 'vrr' — retired apex-poison 2026-06-17\n            'mcp-server',\n            'state',\n            'a2a-agent-card',\n            'agent-inference',\n            'omnigent-agent-yaml',\n            'daimon-seed',\n            'nir',\n            // 'native-2d' — retired apex-poison 2026-06-17\n            'node-service',\n            '3dgs',\n            '3dtiles',\n            'canvas2d-game',\n            'code-editor',\n          ],\n          description: 'Target platform to compile to',\n        },\n        options: {\n          type: 'object',\n          description: 'Optional compiler-specific configuration',\n        },\n        stream: {\n          type: 'boolean',\n          description: 'Enable streaming progress updates (for long-running compilations)',\n        },\n        jobId: {\n          type: 'string',\n          description: 'Optional job ID for tracking (auto-generated if not provided)',\n        },\n      },\n      required: ['code', 'target'],\n    },\n  },\n\n  // Convenience tools for popular targets\n  {\n    name: 'compile_to_unity',\n    description: 'Compile HoloScript to Unity Engine C# scripts with prefab generation',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        code: { type: 'string', description: 'HoloScript composition code' },\n        options: {\n          type: 'object',\n          properties: {\n            namespace: { type: 'string', description: 'C# namespace (default: HoloScript)' },\n            generatePrefabs: {\n              type: 'boolean',\n              description: 'Generate Unity prefabs (default: true)',\n            },\n          },\n        },\n      },\n      required: ['code'],\n    },\n  },\n  {\n    name: 'compile_to_unreal',\n    description: 'Compile HoloScript to Unreal Engine C++ code with Blueprint support',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        code: { type: 'string', description: 'HoloScript composition code' },\n        options: {\n          type: 'object',\n          properties: {\n            generateBlueprints: {\n              type: 'boolean',\n              description: 'Generate Blueprint classes (default: true)',\n            },\n            targetVersion: { type: 'string', description: 'Unreal Engine version (default: 5.3)' },\n          },\n        },\n      },\n      required: ['code'],\n    },\n  },\n  {\n    name: 'compile_to_pcg_graph',\n    description:\n      'Compile HoloScript procedural domain blocks to an Unreal PCG XML graph with typed spatial-operator ports and a GPU evaluation plan.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        code: { type: 'string', description: 'HoloScript composition code with procedural blocks' },\n        options: {\n          type: 'object',\n          properties: {\n            gpuEvaluation: {\n              type: 'boolean',\n              description: 'Enable GPU spatial-operator evaluation hints',\n            },\n            seed: { type: 'number', description: 'Deterministic scatter seed override' },\n          },\n        },\n      },\n      required: ['code'],\n    },\n  },\n  {\n    name: 'compile_to_urdf',\n    description: 'Compile HoloScript to URDF (Unified Robot Description Format) for ROS 2 / Gazebo',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        code: { type: 'string', description: 'HoloScript composition code' },\n        options: {\n          type: 'object',\n          properties: {\n            robotName: { type: 'string', description: 'Robot name (default: holoscript_robot)' },\n            includeInertial: {\n              type: 'boolean',\n              description: 'Include inertial properties (default: true)',\n            },\n          },\n        },\n      },\n      required: ['code'],\n    },\n  },\n  {\n    name: 'compile_to_webgpu',\n    description:\n      'Compile HoloScript to WebGPU rendering code with WGSL shaders. ' +\n      'SOVEREIGN TARGET — uses the native WebGPURenderer, not Three.js/R3F/Babylon. ' +\n      'The result includes a `previewHtml` field: a self-contained HTML page that boots ' +\n      'the sovereign GPU renderer directly in the browser with no third-party engine dependency. ' +\n      'To serve it, POST {code} to /api/compile/webgpu-preview on the MCP server, or use ' +\n      '/scene/:id?renderer=webgpu to re-render a stored scene via the sovereign path.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        code: { type: 'string', description: 'HoloScript composition code' },\n        options: {\n          type: 'object',\n          properties: {\n            enableCompute: {\n              type: 'boolean',\n              description: 'Enable compute shaders (default: true)',\n            },\n            msaa: { type: 'number', description: 'MSAA sample count (default: 4)' },\n          },\n        },\n      },\n      required: ['code'],\n    },\n  },\n  {\n    name: 'compile_to_r3f',\n    description:\n      'Compile HoloScript to native generated React Three Fiber TSX through SceneIR. ' +\n      'This emits a @generated .tsx shell that embeds the compiled SceneIR data and delegates ' +\n      'runtime interpretation to @holoscript/r3f-renderer/HoloSceneIRRenderer. It is not the ' +\n      'retired hand-authored JSX compiler path. Pass options.format=\"scene-ir\" or \"json\" for raw SceneIR.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        code: { type: 'string', description: 'HoloScript composition code' },\n        options: {\n          type: 'object',\n          properties: {\n            format: {\n              type: 'string',\n              enum: ['tsx', 'scene-ir', 'json'],\n              description: 'Output format (default: tsx)',\n            },\n            componentName: { type: 'string', description: 'Generated React component name' },\n            includeCanvas: {\n              type: 'boolean',\n              description: 'Wrap the SceneIR renderer in <Canvas> (default: true)',\n            },\n            sourcePath: { type: 'string', description: 'Optional source path comment for receipts' },\n          },\n        },\n      },\n      required: ['code'],\n    },\n  },\n\n  // === Additional compile_to_* targets ===\n  {\n    name: 'compile_to_godot',\n    description: 'Compile HoloScript to Godot Engine GDScript with scene (.tscn) generation',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        code: { type: 'string', description: 'HoloScript composition code' },\n        options: { type: 'object' },\n      },\n      required: ['code'],\n    },\n  },\n  {\n    name: 'compile_to_visionos',\n    description: 'Compile HoloScript to Apple visionOS RealityKit Swift code',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        code: { type: 'string', description: 'HoloScript composition code' },\n        options: { type: 'object' },\n      },\n      required: ['code'],\n    },\n  },\n  {\n    name: 'compile_to_openxr',\n    description: 'Compile HoloScript to OpenXR C++ application layer for cross-platform VR/AR',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        code: { type: 'string', description: 'HoloScript composition code' },\n        options: { type: 'object' },\n      },\n      required: ['code'],\n    },\n  },\n  // compile_to_babylon, compile_to_playcanvas — retired (apex-poison, 2026-06-17)\n  {\n    name: 'compile_to_vrchat',\n    description:\n      'Compile HoloScript to VRChat SDK3. Current implementation emits legacy UdonSharp C#; Byte/Udon output is gated on the artifact contract.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        code: { type: 'string', description: 'HoloScript composition code' },\n        options: {\n          type: 'object',\n          properties: {\n            outputFormat: {\n              type: 'string',\n              enum: ['udonsharp-csharp', 'udon-assembly', 'udon-bytecode'],\n              description:\n                'VRChat artifact family. Only udonsharp-csharp is currently implemented; Byte/Udon formats fail fast until the artifact contract is confirmed.',\n            },\n            useUdonSharp: {\n              type: 'boolean',\n              description:\n                'Legacy alias for UdonSharp C# output. false maps to the gated Byte/Udon target family.',\n            },\n          },\n          additionalProperties: true,\n        },\n      },\n      required: ['code'],\n    },\n  },\n  {\n    name: 'compile_to_android',\n    description: 'Compile HoloScript to Android ARCore Kotlin code',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        code: { type: 'string', description: 'HoloScript composition code' },\n        options: { type: 'object' },\n      },\n      required: ['code'],\n    },\n  },\n  {\n    name: 'compile_to_android_xr',\n    description: 'Compile HoloScript to Android XR Kotlin code for Android headsets',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        code: { type: 'string', description: 'HoloScript composition code' },\n        options: { type: 'object' },\n      },\n      required: ['code'],\n    },\n  },\n  {\n    name: 'compile_to_quest',\n    description:\n      'Compile HoloScript to a complete native Meta Quest 3/3S app project (Horizon OS): Camera2 ' +\n      'passthrough camera, ZXing QR decode, the ovrweb://webtask Quest Browser intent, and a ' +\n      'signed-APK Gradle project. Distinct from compile_to_android_xr (which targets Google ' +\n      'Android XR / Jetpack XR). Returns the full file set for the app project.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        code: { type: 'string', description: 'HoloScript composition code' },\n        options: { type: 'object' },\n      },\n      required: ['code'],\n    },\n  },\n  {\n    name: 'compile_to_ios',\n    description: 'Compile HoloScript to iOS ARKit Swift code',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        code: { type: 'string', description: 'HoloScript composition code' },\n        options: { type: 'object' },\n      },\n      required: ['code'],\n    },\n  },\n  // compile_to_ar — retired (apex-poison, 2026-06-17)\n  {\n    name: 'compile_to_wasm',\n    description: 'Compile HoloScript to WebAssembly module',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        code: { type: 'string', description: 'HoloScript composition code' },\n        options: { type: 'object' },\n      },\n      required: ['code'],\n    },\n  },\n  {\n    name: 'compile_to_character_webgpu',\n    description:\n      'Compile an authored .holo CHARACTER composition to a native-WebGPU CharacterDrawSpec ' +\n      'bundle (skinned mesh + joint palette + skin/hair/eye material groups) run by renderCharacter. ' +\n      'Sovereign target; replaces the placeholder-cube fallthrough for character bodies.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        code: { type: 'string', description: 'HoloScript .holo character composition code' },\n        options: { type: 'object', description: 'Optional { entityId } override' },\n      },\n      required: ['code'],\n    },\n  },\n  {\n    name: 'compile_to_usd',\n    description: 'Compile HoloScript to USD / USDA physics scene format',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        code: { type: 'string', description: 'HoloScript composition code' },\n        options: { type: 'object' },\n      },\n      required: ['code'],\n    },\n  },\n  {\n    name: 'compile_to_usdz',\n    description: 'Compile HoloScript to USDZ package data for AR viewers',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        code: { type: 'string', description: 'HoloScript composition code' },\n        options: { type: 'object' },\n      },\n      required: ['code'],\n    },\n  },\n  {\n    name: 'compile_to_sdf',\n    description:\n      'Compile HoloScript to Gazebo SDF (Simulation Description Format) XML; not signed-distance-field ray marching',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        code: { type: 'string', description: 'HoloScript composition code' },\n        options: { type: 'object' },\n      },\n      required: ['code'],\n    },\n  },\n  {\n    name: 'compile_to_mjcf',\n    description:\n      'Compile HoloScript to MuJoCo MJCF XML (physics simulation). Bridge target consumed by the MuJoCo engine.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        code: { type: 'string', description: 'HoloScript composition code' },\n        options: { type: 'object' },\n      },\n      required: ['code'],\n    },\n  },\n  {\n    name: 'compile_to_mjx',\n    description:\n      'Compile HoloScript to a MuJoCo MJX (JAX) differentiable-physics training env (Python). Bridge target consumed by the jax + mujoco.mjx runtimes; builds on compile_to_mjcf and reads @differentiable_physics traits.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        code: { type: 'string', description: 'HoloScript composition code' },\n        options: { type: 'object' },\n      },\n      required: ['code'],\n    },\n  },\n  {\n    name: 'compile_to_embodied_dataset',\n    description:\n      'Compile HoloScript to an embodied-AI dataset generator (Python) that produces N simulation episodes as a structured dataset (RLDS | LeRobot | HDF5). Bridge target; builds on compile_to_mjcf and reads the @sim_to_real_dataset trait (episode_count, output_format, sensor_modalities, domain_randomization).',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        code: { type: 'string', description: 'HoloScript composition code' },\n        options: { type: 'object' },\n      },\n      required: ['code'],\n    },\n  },\n  // compile_to_vrr — retired (apex-poison, 2026-06-17)\n  // compile_to_multi_layer — retired (MultiLayerCompiler retired 2026-06-17; advertised a target that always threw)\n  {\n    name: 'compile_to_ros2_deploy',\n    description:\n      'Compile HoloScript to a ROS 2 deployment bundle: URDF + Python launch file + controllers YAML (MoveIt 2 / ros2_control)',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        code: { type: 'string', description: 'HoloScript composition code' },\n        packageName: {\n          type: 'string',\n          description: 'ROS 2 package name (default: holoscript_robot)',\n        },\n        options: {\n          type: 'object',\n          properties: {\n            useSimTime: { type: 'boolean' },\n            rviz: { type: 'boolean' },\n            gazebo: { type: 'boolean' },\n            controllers: { type: 'array', items: { type: 'string' } },\n          },\n        },\n      },\n      required: ['code'],\n    },\n  },\n  {\n    name: 'compile_to_fmu',\n    description:\n      'Compile HoloScript to an FMI 3.0 FMU source bundle with CoSimulation/ModelExchange declarations and CAEL coupling provenance',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        code: { type: 'string', description: 'HoloScript composition code' },\n        options: {\n          type: 'object',\n          properties: {\n            mode: {\n              type: 'string',\n              enum: ['co-simulation', 'model-exchange', 'both'],\n              description: 'FMU mode to emit (default: both)',\n            },\n            modelIdentifier: { type: 'string', description: 'Optional FMI modelIdentifier' },\n            includeSourceBundle: { type: 'boolean' },\n          },\n        },\n      },\n      required: ['code'],\n    },\n  },\n  {\n    name: 'absorb_fmu',\n    description:\n      'Import FMI 3.0 modelDescription.xml or a HoloScript FMU manifest into a composable @fmu wrapper composition',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        modelDescriptionXml: { type: 'string', description: 'Raw FMI modelDescription.xml' },\n        manifest: { type: 'object', description: 'Optional HoloScript FMU manifest' },\n        source: { type: 'string', description: 'FMU file/source URI' },\n        name: { type: 'string', description: 'Optional wrapper object name' },\n      },\n    },\n  },\n  {\n    name: 'compile_to_dtdl',\n    description: 'Compile HoloScript to DTDL v3 (Digital Twin Definition Language) for Azure IoT',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        code: { type: 'string', description: 'HoloScript composition code' },\n        options: { type: 'object' },\n      },\n      required: ['code'],\n    },\n  },\n  {\n    name: 'compile_to_nir',\n    description:\n      'Compile HoloScript to NIR (Neuromorphic Intermediate Representation) for Intel Loihi 2, SpiNNaker 2',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        code: { type: 'string', description: 'HoloScript composition code' },\n        options: { type: 'object' },\n      },\n      required: ['code'],\n    },\n  },\n  // compile_to_native_2d — retired (apex-poison, 2026-06-17)\n  {\n    name: 'compile_to_code_editor',\n    description:\n      'Compile a HoloScript composition annotated with @code_editor traits into a ' +\n      'CodeMirror 6 configuration bundle (JSON). Used by Studio to load editor ' +\n      'config from holoscript-editor.hs at runtime.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        code: {\n          type: 'string',\n          description: 'HoloScript source (.hs/.holo) with @code_editor traits',\n        },\n        options: {\n          type: 'object',\n          description: 'Compiler options: indent (number), strictTraits (boolean)',\n        },\n      },\n      required: ['code'],\n    },\n  },\n  {\n    name: 'compile_to_canvas2d_game',\n    description:\n      'Compile HoloScript to a self-contained, offline, playable retro 2D CANVAS GAME ' +\n      '(HTML5 canvas, fixed-timestep loop, physics/collision, WebAudio, score, START/WIN/LOSE). ' +\n      'Gameplay is derived from traits: @controllable=player, @grabbable=collectible, ' +\n      '@collidable=hazard, @dialogue=goal, environment.gravity=physics, spatial_group origins=tiers. ' +\n      'Unlike compile_to_native_2d (DOM/UI), this emits an actual game runtime.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        code: { type: 'string', description: 'HoloScript composition code (.hs/.hsplus/.holo)' },\n        options: {\n          type: 'object',\n          description: 'Compiler options',\n          properties: {\n            timeLimit: { type: 'number', description: 'Seconds on the game timer (default 70)' },\n            title: {\n              type: 'string',\n              description: 'Game title / banner (defaults to composition name)',\n            },\n          },\n        },\n      },\n      required: ['code'],\n    },\n  },\n  {\n    name: 'compile_to_node_service',\n    description:\n      'Compile HoloScript to Node.js Express/Fastify backend service. ' +\n      'Supports @connector(name) for external services, @env(VAR) for env validation, ' +\n      '@deploy(railway) for deployment config. Generates: routes, middleware, env config, ' +\n      'connector init/shutdown, railway.json, Dockerfile, package.json.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        code: {\n          type: 'string',\n          description:\n            'HoloScript composition code with @service, @connector, @env, @deploy traits',\n        },\n        options: {\n          type: 'object',\n          description: 'Compiler options',\n          properties: {\n            framework: {\n              type: 'string',\n              enum: ['express', 'fastify'],\n              description: 'Target framework (default: express)',\n            },\n            port: { type: 'number', description: 'Base port (default: 3000)' },\n            typescript: { type: 'boolean', description: 'Generate TypeScript (default: true)' },\n            includeDocker: { type: 'boolean', description: 'Include Dockerfile (default: true)' },\n            nodeVersion: {\n              type: 'string',\n              enum: ['18', '20', '22'],\n              description: 'Node.js target (default: 20)',\n            },\n          },\n        },\n      },\n      required: ['code'],\n    },\n  },\n  {\n    name: 'compile_to_a2a_agent_card',\n    description:\n      'Compile HoloScript to A2A Protocol Agent Card JSON (agent identity, skills, capabilities)',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        code: { type: 'string', description: 'HoloScript composition code' },\n        options: { type: 'object' },\n      },\n      required: ['code'],\n    },\n  },\n  {\n    name: 'compile_to_agent_inference',\n    description:\n      'Compile a HoloScript or HSPlus agent brain into a runnable inference project (agent script, tools, config, README)',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        code: { type: 'string', description: 'HoloScript / HSPlus agent brain source code' },\n        options: {\n          type: 'object',\n          properties: {\n            language: {\n              type: 'string',\n              enum: ['typescript', 'python'],\n              description: 'Generated agent language (default: typescript)',\n            },\n            defaultProvider: {\n              type: 'string',\n              enum: ['anthropic', 'openai', 'local', 'ollama', 'custom'],\n              description: 'Default model provider when no @model trait is present',\n            },\n            defaultModel: { type: 'string', description: 'Default model name' },\n            defaultTemperature: { type: 'number', description: 'Default sampling temperature' },\n            defaultMaxTokens: { type: 'number', description: 'Default max token budget' },\n          },\n        },\n      },\n      required: ['code'],\n    },\n  },\n  {\n    name: 'verify_cross_perceiver',\n    description:\n      'Falsification oracle for one .holo composition across structurally-different perceiver ' +\n      'compilers: webgpu (the human eye), agent-inference (the agent context), urdf (the robot ' +\n      'stack). Compiles the SAME source through each requested perceiver, independently ' +\n      're-derives world facts from each EMITTED ARTIFACT (never the shared input AST), and ' +\n      'diffs them into a PerceiverConsensusReceipt. Any perceiver that re-derives a different ' +\n      'fact flips the verdict to FALSIFIED with the concrete disagreement. ' +\n      'DESIGN CONSTRAINT — verdict FALSIFIED is LOAD-BEARING: consumers MUST treat FALSIFIED ' +\n      'as a hard failure (fail the pipeline / exit non-zero); it must NEVER be demoted to a ' +\n      'warning. Requires at least 2 perceivers (a single-perceiver receipt is circular).',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        code: {\n          type: 'string',\n          description: 'HoloScript composition source (.holo) to cross-verify',\n        },\n        perceivers: {\n          type: 'array',\n          items: { type: 'string', enum: ['webgpu', 'agent-inference', 'urdf'] },\n          description:\n            'Perceivers to fan the composition through (default: all three; minimum 2 distinct)',\n        },\n        options: {\n          type: 'object',\n          description:\n            'Options: agentToken (string) — RBAC token threaded to each perceiver compiler, ' +\n            'validated by the compilers themselves (same field the generic compile tools accept)',\n          properties: {\n            agentToken: {\n              type: 'string',\n              description: 'Agent RBAC token validated by each perceiver compiler',\n            },\n          },\n        },\n      },\n      required: ['code'],\n    },\n  },\n  {\n    name: 'verify_verified_view',\n    description:\n      'Provenance oracle for an agent-authored 2D surface (.holo): does every data-bound ' +\n      'element prove what it renders? Re-derives the @verified_view contract that ' +\n      'Native2DCompiler enforces and returns EVERY violation at once (compiling would throw ' +\n      'on the first). Violations: mismatched-node (@projects names a different path than the ' +\n      \"binding — \\\"says sessions, wired revenue\\\"), missing-projects (bound element with no \" +\n      'receipt), hallucinated-root (projects a state node that does not exist), ' +\n      'projects-without-binding (a receipt on an unbound element), no-verified-view (binds ' +\n      'data without opting into the gate). DESIGN CONSTRAINT — `complete: false` is ' +\n      'LOAD-BEARING: a surface that cannot prove its data source must be treated as a hard ' +\n      'failure, never demoted to a warning. Unverifiable input is an error, never a false clean.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        code: {\n          type: 'string',\n          description: 'HoloScript 2D surface source (.holo) to check for provenance-completeness',\n        },\n      },\n      required: ['code'],\n    },\n  },\n  {\n    name: 'compile_to_omnigent_agent_yaml',\n    description:\n      'Export a HoloScript or HSPlus agent brain into Omnigent agent YAML plus a projection receipt with bridge warnings.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        code: { type: 'string', description: 'HoloScript / HSPlus agent brain source code' },\n        options: {\n          type: 'object',\n          properties: {\n            source: { type: 'string', description: 'Receipt source label or file path' },\n            harness: { type: 'string', description: 'Omnigent executor harness (default: codex)' },\n            defaultProvider: {\n              type: 'string',\n              description: 'Default model provider when no @model trait is present',\n            },\n            defaultModel: {\n              type: 'string',\n              description: 'Default model name when no @model trait is present',\n            },\n            authEnv: {\n              type: 'string',\n              description: 'Environment variable name used for provider auth',\n            },\n          },\n        },\n      },\n      required: ['code'],\n    },\n  },\n  {\n    name: 'compile_to_daimon_seed',\n    description:\n      'Compile HoloScript to portable DaimonSeed IR: field priors, shared ContentPolicyGate JSON-Logic thresholds, provenance/emergence refs, export-fidelity custody semantics, and no serialized soul/runtime observation path.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        code: {\n          type: 'string',\n          description: 'HoloScript / HSPlus source to compile into a DaimonSeed recipe',\n        },\n        options: {\n          type: 'object',\n          properties: {\n            seedId: {\n              type: 'string',\n              description: 'Optional deterministic seed identifier override',\n            },\n            domainSpecHash: {\n              type: 'string',\n              description: 'Optional domain-spec hash override',\n            },\n            provenanceChainRef: {\n              type: 'string',\n              description: 'T1 provenance-chain receipt reference',\n            },\n            emergenceContractRef: {\n              type: 'string',\n              description: 'T4 emergence contract reference',\n            },\n            noiseFloorRef: {\n              type: 'string',\n              description: 'Receipt/reference for reproducibility noise floor',\n            },\n            fieldPriors: {\n              type: 'object',\n              description: 'Tensor prior metadata: tensorSchema, shape, dtype, weightsRef',\n            },\n            thresholdFn: {\n              type: 'object',\n              description: 'JSON-Logic predicate evaluated by the shared ContentPolicyGate runtime',\n            },\n            thresholdFacts: {\n              type: 'object',\n              description: 'Facts used for threshold preview evaluation',\n            },\n            initialWeights: {\n              type: 'object',\n              description: 'Optional trait-vocabulary initial weights',\n            },\n          },\n        },\n      },\n      required: ['code'],\n    },\n  },\n  {\n    name: 'compile_to_state',\n    description: 'Compile HoloScript to reactive state shape JSON for agent brain configurations',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        code: { type: 'string', description: 'HoloScript composition code' },\n        options: { type: 'object' },\n      },\n      required: ['code'],\n    },\n  },\n  {\n    name: 'compile_to_3dgs',\n    description:\n      'Compile HoloScript to glTF 2.0 with KHR_gaussian_splatting extension. ' +\n      'Accepts @gaussian_splat trait with positions/scales/rotations/colors/opacities, ' +\n      'or raw point-cloud positions+colors (auto-computes covariance per splat). ' +\n      'Output formats: glb (single binary) or gltf (JSON + .bin).',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        code: { type: 'string', description: 'HoloScript composition code' },\n        options: {\n          type: 'object',\n          properties: {\n            format: {\n              type: 'string',\n              enum: ['glb', 'gltf'],\n              description: 'Output format (default: glb)',\n            },\n            colorSpace: {\n              type: 'string',\n              enum: ['srgb_rec709_display', 'lin_rec709_display'],\n              description: 'Color space for Gaussian colors (default: srgb_rec709_display)',\n            },\n            shDegree: {\n              type: 'number',\n              description: 'Maximum spherical-harmonics degree 0-3 (default: 0)',\n            },\n          },\n        },\n      },\n      required: ['code'],\n    },\n  },\n\n  {\n    name: 'compile_to_3dtiles',\n    description:\n      'Compile HoloScript Gaussian splats to a 3D Tiles 1.1 source bundle. ' +\n      'Partitions @gaussian_splat data into spatial tile footprints, emits ' +\n      'coarse/medium/fine LOD GLB payloads, tileset.json, stream-manifest.json, ' +\n      'and CAEL per-tile provenance.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        code: { type: 'string', description: 'HoloScript composition code with @gaussian_splat data' },\n        options: {\n          type: 'object',\n          properties: {\n            tileSizeMeters: {\n              type: 'number',\n              description: 'Spatial footprint size for each tile in meters (default: 50)',\n            },\n            lodLevels: {\n              type: 'array',\n              items: { type: 'string', enum: ['coarse', 'medium', 'fine'] },\n              description: 'LOD levels to emit (default: coarse, medium, fine)',\n            },\n            streamBaseUrl: {\n              type: 'string',\n              description: 'Base URL used to derive the stream manifest URL',\n            },\n            streamId: {\n              type: 'string',\n              description: 'Stable stream id; generated from the composition hash when omitted',\n            },\n          },\n        },\n      },\n      required: ['code'],\n    },\n  },\n\n  {\n    name: 'stream_world_tiles',\n    description:\n      'Return a streamable 3D Tiles manifest for a HoloScript world. Emits a manifest URL, ' +\n      'tileset.json, base64 GLB tile payload files, and CAEL tile provenance.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        code: { type: 'string', description: 'HoloScript composition code with @gaussian_splat data' },\n        options: {\n          type: 'object',\n          properties: {\n            tileSizeMeters: {\n              type: 'number',\n              description: 'Spatial footprint size for each tile in meters (default: 50)',\n            },\n            streamBaseUrl: {\n              type: 'string',\n              description: 'Base URL used to derive the stream manifest URL',\n            },\n            streamId: {\n              type: 'string',\n              description: 'Stable stream id; generated from the composition hash when omitted',\n            },\n          },\n        },\n      },\n      required: ['code'],\n    },\n  },\n\n  {\n    name: 'compile_to_gaussian_train',\n    description:\n      'Compile a @gaussian_train trait into a SOVEREIGN 3D Gaussian Splat training job. ' +\n      'The sovereign backend (default) runs the native differentiable trainer (GaussianTrainer3D + ' +\n      'GaussianTrainer2D + Adam, gradient-checked) on our own GPU/CPU path — $0, no third-party ' +\n      'runtime, no RENDER tokens (vs the legacy remote backend → api.rendernetwork.com). Emits a ' +\n      'JSON GaussianTrainJob (executor + dataset refs + hyperparameters). Invalid configs throw at ' +\n      'compile time. Distinct from compile_to_3dgs, which is a KHR_gaussian_splatting glTF BRIDGE.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        code: { type: 'string', description: 'HoloScript composition code carrying a @gaussian_train trait' },\n        options: {\n          type: 'object',\n          properties: {\n            defaultBackend: {\n              type: 'string',\n              enum: ['sovereign', 'remote'],\n              description: 'Backend when the trait omits it (default: sovereign — the native trainer)',\n            },\n          },\n        },\n      },\n      required: ['code'],\n    },\n  },\n\n  {\n    name: 'compile_to_edge',\n    description:\n      'Compile HoloScript to a self-contained deployment bundle for any Ollama-capable edge device ' +\n      '(Jetson Orin/Nano/NX, Raspberry Pi 5, The Unit, any Linux ARM64/x86 node). ' +\n      'DEFAULT runtime \"agentrunner\": emits holoscript_agent.service (systemd unit running the ' +\n      'canonical TS AgentRunner — full gate stack: artifact-grounding, reflect, CAEL chain, ' +\n      'content-hashed/signed hardware receipts, native cognitive verbs), setup.sh, manifest.json. ' +\n      'LEGACY runtime \"python\" (deprecated, gate-less): emits agent.py (Ollama loop), monitor.py, ' +\n      'setup.sh, holoscript_agent.service, manifest.json. ' +\n      'Trait-conditional: ros2 colcon bridge (@ros2_actuation); tensorrt_loader.py (python only). ' +\n      'Jetson flags set by @jetson, @tegrastats traits.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        code: { type: 'string', description: 'HoloScript composition code (.hs/.hsplus/.holo)' },\n        options: {\n          type: 'object',\n          description: 'EdgeCompiler options',\n          properties: {\n            ollamaUrl: {\n              type: 'string',\n              description: 'Ollama base URL on the target device (default: http://localhost:11434)',\n            },\n            model: {\n              type: 'string',\n              description: 'Ollama model name (default: qwen3:4b)',\n            },\n            platform: {\n              type: 'string',\n              enum: ['linux-arm64', 'linux-x86_64'],\n              description: 'Target platform (default: linux-arm64)',\n            },\n            remotePath: {\n              type: 'string',\n              description: 'Deploy path on target device (default: /opt/holoscript)',\n            },\n            serviceUser: {\n              type: 'string',\n              description: 'systemd service user (default: holoscript)',\n            },\n            runtime: {\n              type: 'string',\n              enum: ['agentrunner', 'python'],\n              description:\n                'Edge runtime the unit runs. \"agentrunner\" (DEFAULT) = canonical TS AgentRunner ' +\n                '(full gate stack). \"python\" = deprecated, gate-less standalone agent.',\n            },\n          },\n        },\n      },\n      required: ['code'],\n    },\n  },\n\n  {\n    name: 'compile_to_llama_server',\n    description:\n      'Compile @llama_serve HoloScript into a dry llama.cpp server deployment bundle. ' +\n      'Emits the llama-server launch command, PowerShell launcher, health probe, systemd unit, ' +\n      'Windows S4U scheduled-task installer, and sovereign-devices registry entry. ' +\n      'Use this for HoloLlama native local model serving; it does not start a process.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        code: { type: 'string', description: 'HoloScript composition code carrying @llama_serve' },\n        options: {\n          type: 'object',\n          description: 'LlamaServerCompiler options',\n          properties: {\n            model: {\n              type: 'string',\n              description: 'Model label for registry/routing (default: fara-7b)',\n            },\n            modelPath: { type: 'string', description: 'GGUF model path passed to -m' },\n            mmprojPath: {\n              type: 'string',\n              description: 'Vision mmproj GGUF path passed to --mmproj',\n            },\n            host: { type: 'string', description: 'Bind host (default: 127.0.0.1)' },\n            port: { type: 'number', description: 'Bind port (default: 18080)' },\n            contextLength: { type: 'number', description: 'Context length passed to -c' },\n            gpuLayers: { type: 'number', description: 'GPU layers passed to -ngl' },\n            imageMinTokens: {\n              type: 'number',\n              description: 'Minimum image tokens for vision models',\n            },\n            imageMaxTokens: {\n              type: 'number',\n              description: 'Maximum image tokens for vision models',\n            },\n            grammarPath: {\n              type: 'string',\n              description: 'GBNF grammar file path passed to --grammar-file',\n            },\n            loraPath: { type: 'string', description: 'LoRA adapter path passed to --lora' },\n            executable: { type: 'string', description: 'llama-server executable name/path' },\n            cudaPath: { type: 'string', description: 'CUDA runtime directory prepended to PATH' },\n            llamaBinDir: {\n              type: 'string',\n              description: 'llama.cpp bin directory prepended to PATH',\n            },\n            node: { type: 'string', description: 'Sovereign-devices node handle' },\n            registerAs: {\n              type: 'string',\n              description: 'Sovereign-devices registry handle to emit',\n            },\n          },\n        },\n      },\n      required: ['code'],\n    },\n  },\n\n  {\n    name: 'compile_to_bot_swarm',\n    description:\n      'Compile an MMO composition to an in-process load + balance test harness for the ' +\n      'Colyseus server emitted by compile_to_colyseus. Emits a TypeScript module exporting ' +\n      'runBotSwarm(RoomClass, opts) — spawns a swarm of bot players against the real generated ' +\n      'Room and drives the authoritative action loop (legal moves, speedhack attempts, ability ' +\n      'spam), returning a BalanceReport (tick budget, anti-cheat rejections, receipts). Plus ' +\n      'assertBalance(report) gated by the @balance_test envelope. Runs entirely in-process — the ' +\n      'verification layer + game-balance CI seed for the authoritative server.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        code: { type: 'string', description: 'HoloScript MMO composition (.holo)' },\n        options: {\n          type: 'object',\n          description: 'BotSwarmCompiler options',\n          properties: {\n            bots: { type: 'number', description: 'Default bot count baked into the harness (default: 24)' },\n            ticks: { type: 'number', description: 'Default tick count (default: 100)' },\n            speedhackRatio: {\n              type: 'number',\n              description: 'Fraction of moves that attempt a speedhack teleport (default: 0.15)',\n            },\n          },\n        },\n      },\n      required: ['code'],\n    },\n  },\n\n  {\n    name: 'compile_to_dungeon_instance',\n    description:\n      'Compile dungeon_instance blocks into a server-authoritative instance pool (P2.6). Emits a ' +\n      'TypeScript module exporting DUNGEON_REGISTRY + a DungeonInstancePool class: per-party ' +\n      'instanced content (dungeon/raid) spun up on demand, capped at max_instances, released on a ' +\n      'reset timer. Completion emits a receipt sealed against the dungeon + instance + party. Each ' +\n      \"dungeon's completion_quest is compile-validated against the composition's declared quests — \" +\n      'an undeclared quest is a compile error (typed-predicate guarantee). RoomClass-agnostic.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        code: { type: 'string', description: 'HoloScript MMO composition (.holo) with dungeon_instance blocks' },\n      },\n      required: ['code'],\n    },\n  },\n\n  {\n    name: 'compile_to_world_shard',\n    description:\n      'Compile world_shard blocks into a server-authoritative shard router + multi-room bootstrap ' +\n      '(P2.5). A single world is partitioned into AABB shards, each hosted as its own Colyseus room. ' +\n      'Emits SHARD_REGISTRY + shardForPosition() + a ShardRouter class (route / requestHandoff / ' +\n      'createShardServers). Cross-shard handoff is RECEIPT-SEALED and validated — the target must be ' +\n      'a declared NEIGHBOR of the origin and the position inside its bounds (anti-teleport). Each ' +\n      \"shard's neighbors are compile-validated against declared shards. Same-machine multi-room.\",\n    inputSchema: {\n      type: 'object',\n      properties: {\n        code: { type: 'string', description: 'HoloScript MMO composition (.holo) with world_shard blocks' },\n      },\n      required: ['code'],\n    },\n  },\n\n  {\n    name: 'compile_to_mcp_config',\n    description:\n      'Compile .holo MCP server connection definitions to IDE-specific client config JSON. ' +\n      'This emits mcpServers connection entries, not an MCP server manifest with tools or resources. ' +\n      'One source, multiple outputs: claude (${VAR}), vscode (${env:VAR}), ' +\n      'cursor (${VAR}), antigravity (literal key injection), generic.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        code: {\n          type: 'string',\n          description:\n            'HoloScript with MCP client connection server objects using @connector and @env traits. ' +\n            'Example: server my_server { @connector(holoscript, transport: \"http\") url: \"https://mcp.holoscript.net/mcp\" @env(HOLOSCRIPT_API_KEY, header: \"Authorization: Bearer\") }',\n        },\n        target: {\n          type: 'string',\n          enum: ['claude', 'vscode', 'cursor', 'antigravity', 'generic'],\n          description: 'Target IDE format (default: generic)',\n        },\n        envValues: {\n          type: 'object',\n          description:\n            'Key-value map of env var values for literal injection (required for antigravity target). ' +\n            'Example: {\"HOLOSCRIPT_API_KEY\": \"USNo/...\"}',\n        },\n      },\n      required: ['code'],\n    },\n  },\n\n  {\n    name: 'compile_to_mcp_server',\n    description:\n      'Compile a HoloScript trait/brain composition into a standalone MCP server TypeScript module. ' +\n      'Walks the composition for llm_agent, goal_oriented, rag_knowledge, agent_memory, and tool traits ' +\n      'and emits: TOOLS[] definition, HoloMCPRuntimeAdapter interface, registerAdapter(), ' +\n      'verifyContractWiring(), handleToolCall(), and governance metadata. ' +\n      'The output is a self-contained .mcp-server.ts file — no external HoloScript imports at runtime. ' +\n      'Usage: define objects with @llm_agent or @tool traits, compile to get a ready-to-wire MCP module.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        code: { type: 'string', description: 'HoloScript composition code with agent/tool traits' },\n        options: {\n          type: 'object',\n          properties: {\n            serverName: { type: 'string', description: 'MCP server name (default: holoscript-mcp)' },\n            serverVersion: { type: 'string', description: 'Server version string (default: 1.0.0)' },\n            outputKind: {\n              type: 'string',\n              enum: ['module', 'manifest'],\n              description:\n                'module emits a self-contained .mcp-server.ts artifact (default); manifest emits the JSON Tool[] manifest.',\n            },\n          },\n        },\n      },\n      required: ['code'],\n    },\n  },\n\n  // Quantum Circuit Compilation ÃƒÂ¢Ã¢â€šÂ¬Ã¢â‚¬Â HoloScript ÃƒÂ¢Ã¢â‚¬Â Ã¢â‚¬â„¢ OpenQASM 3.0 (D.056 BUILD step)\n  {\n    name: 'compile_to_qasm',\n    description:\n      'Compile HoloScript source to OpenQASM 3.0 quantum circuit. ' +\n      'Walks the composition for the first @quantumCircuit (or @quantum_circuit) trait node and ' +\n      'emits a fully-formed OpenQASM 3.0 string plus rich metadata (numQubits, numClbits, ' +\n      'estimatedDepth, circuitType, recommendedBackend, warnings, molecule, weightMatrix). ' +\n      'Supported circuit families: vqe (hardware-efficient VQE ansatz), qaoa (Max-Cut QAOA), ' +\n      'stub (1-qubit when no quantum trait is found). ' +\n      'Jordan-Wigner / sto-3g qubit mapping: HÃƒÂ¢Ã¢â‚¬Â Ã¢â‚¬â„¢2q, C/N/O/FÃƒÂ¢Ã¢â‚¬Â Ã¢â‚¬â„¢10q, othersÃƒÂ¢Ã¢â‚¬Â Ã¢â‚¬â„¢18q.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        source: {\n          type: 'string',\n          description:\n            'HoloScript source code containing a @quantumCircuit or @quantum_circuit trait. ' +\n            'Example: ' +\n            'object N2 { @quantumCircuit(molecule: [{symbol:\"N\",x:0,y:0,z:0},{symbol:\"N\",x:0,y:0,z:1.0975}], circuitType: \"vqe\", ansatzDepth: 2) }',\n        },\n      },\n      required: ['source'],\n    },\n  },\n\n  // SVG vector graphics — SOVEREIGN TARGET\n  {\n    name: 'compile_to_svg',\n    description:\n      'Compile HoloScript to SVG vector graphics. SOVEREIGN TARGET — pure SVG output, no third-party engine. ' +\n      'Useful for diagrams, HoloMap exports, data visualization panels, and 2D schematic generation.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        code: { type: 'string', description: 'HoloScript source code.' },\n        options: {\n          type: 'object',\n          properties: {\n            viewBox: { type: 'string', description: 'SVG viewBox attribute (e.g. \"0 0 800 600\").' },\n            includeGrid: { type: 'boolean', description: 'Overlay a grid guide in the output SVG.' },\n          },\n        },\n      },\n      required: ['code'],\n    },\n  },\n\n  // HoloBytecode — SOVEREIGN TARGET\n  {\n    name: 'compile_to_holob',\n    description:\n      'Compile HoloScript to HoloBytecode for the HoloVM native ECS executor. ' +\n      'SOVEREIGN TARGET — the bytecode runs directly on the HoloVM at 60-90Hz with no third-party engine dependency.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        code: { type: 'string', description: 'HoloScript source code.' },\n        options: {\n          type: 'object',\n          properties: {\n            optimizationLevel: { type: 'number', description: 'Bytecode optimization level (0 = none, 1 = basic, 2 = full).' },\n          },\n        },\n      },\n      required: ['code'],\n    },\n  },\n\n  // OpenAPI 3.1 spec\n  {\n    name: 'compile_to_openapi',\n    description:\n      'Compile HoloScript node service definitions to OpenAPI 3.1 spec (JSON). ' +\n      'Bridge to REST API tooling, Swagger UI, client SDK generators.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        code: { type: 'string', description: 'HoloScript source code.' },\n        options: {\n          type: 'object',\n          properties: {\n            format: { type: 'string', enum: ['json', 'yaml'], description: 'Output format (default: json).' },\n            title: { type: 'string', description: 'API title for the OpenAPI info block.' },\n          },\n        },\n      },\n      required: ['code'],\n    },\n  },\n\n  // SDK client generation\n  {\n    name: 'compile_to_sdk',\n    description:\n      'Compile a HoloScript .holo service-contract to typed SDK clients, React hooks, or connector scaffolds from one contract AST. ' +\n      'Derives methods, request/response types, and error taxonomy from the same contract AST that ' +\n      'compile_to_openapi/compile_to_node_service/compile_to_a2a_agent_card consume — the client is a ' +\n      'pure derivation, never hand-authored.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        code: { type: 'string', description: 'HoloScript source code (.holo service-contract).' },\n        options: {\n          type: 'object',\n          properties: {\n            target: {\n              type: 'string',\n              enum: ['sdk:typescript', 'sdk:python', 'sdk:react', 'sdk:connectors'],\n              description: 'SDK emitter target (default: sdk:typescript).',\n            },\n            language: { type: 'string', enum: ['typescript', 'python', 'react', 'connectors'], description: 'Legacy SDK language alias for target.' },\n            clientClassName: { type: 'string', description: 'Generated client class name.' },\n            packageName: { type: 'string', description: 'npm package name for the generated SDK.' },\n            outputDir: { type: 'string', description: 'Output directory for generated SDK files.' },\n            clientFileName: { type: 'string', description: 'Filename for the generated client (default: <ClientClassName>.ts).' },\n            runtimeFileName: { type: 'string', description: 'Filename for the shared runtime shim (default: sdk-runtime.ts).' },\n            includePackageJson: { type: 'boolean', description: 'Emit a package.json for the generated SDK.' },\n            includeTsConfig: { type: 'boolean', description: 'Emit a tsconfig.json for the generated SDK.' },\n            includeReadme: { type: 'boolean', description: 'Emit a README.md for the generated SDK.' },\n          },\n        },\n      },\n      required: ['code'],\n    },\n  },\n\n  // ONNX model descriptor\n  {\n    name: 'compile_to_onnx',\n    description:\n      'Compile HoloScript brain compositions to ONNX model descriptor JSON. ' +\n      'Bridge to ONNX Runtime, fleet inference, and Brittney training pipelines.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        code: { type: 'string', description: 'HoloScript source code.' },\n        options: {\n          type: 'object',\n          properties: {\n            opsetVersion: { type: 'number', description: 'ONNX opset version (default: 17).' },\n          },\n        },\n      },\n      required: ['code'],\n    },\n  },\n\n  // Flutter/Dart widget code\n  {\n    name: 'compile_to_flutter',\n    description:\n      'Compile HoloScript to Flutter/Dart widget code. ' +\n      \"Bridge to Flutter's iOS/Android/desktop/web runtime.\",\n    inputSchema: {\n      type: 'object',\n      properties: {\n        code: { type: 'string', description: 'HoloScript source code.' },\n        options: {\n          type: 'object',\n          properties: {\n            packageName: { type: 'string', description: 'Dart package name for the generated widget.' },\n            stateful: { type: 'boolean', description: 'Emit a StatefulWidget instead of StatelessWidget.' },\n          },\n        },\n      },\n      required: ['code'],\n    },\n  },\n\n  // STL export for 3D printing\n  {\n    name: 'compile_to_stl_export',\n    description:\n      'Compile HoloScript to STL (Standard Tessellation Language) ASCII format for 3D printing. ' +\n      'Bridge to physical-world fabrication — digital twin → physical twin.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        code: { type: 'string', description: 'HoloScript source code.' },\n        options: {\n          type: 'object',\n          properties: {\n            scale: { type: 'number', description: 'Uniform scale factor applied to all geometry (default: 1.0).' },\n            mergeObjects: { type: 'boolean', description: 'Merge all objects into a single STL solid.' },\n          },\n        },\n      },\n      required: ['code'],\n    },\n  },\n\n  // Snapchat Lens Studio AR\n  {\n    name: 'compile_to_lens_studio',\n    description:\n      \"Compile HoloScript to Snapchat Lens Studio AR lens format. Bridge to Snapchat's AR distribution platform (700M+ users).\",\n    inputSchema: {\n      type: 'object',\n      properties: {\n        code: { type: 'string', description: 'HoloScript source code.' },\n        options: {\n          type: 'object',\n          properties: {\n            apiVersion: { type: 'string', description: 'Lens Studio API version string (e.g. \"5.0\").' },\n          },\n        },\n      },\n      required: ['code'],\n    },\n  },\n\n  // Colyseus multiplayer server\n  {\n    name: 'compile_to_colyseus',\n    description:\n      'Compile HoloScript to Colyseus multiplayer game server room code (TypeScript). ' +\n      'Bridge to authoritative MMO/multiplayer backend. Key for AAA game compilation.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        code: { type: 'string', description: 'HoloScript source code.' },\n        options: {\n          type: 'object',\n          properties: {\n            roomName: { type: 'string', description: 'Colyseus room class name.' },\n            tickRate: { type: 'number', description: 'Server tick rate in Hz (default: 20).' },\n            maxClients: { type: 'number', description: 'Maximum concurrent clients per room instance.' },\n          },\n        },\n      },\n      required: ['code'],\n    },\n  },\n\n  // Android XR AI Glasses\n  {\n    name: 'compile_to_ai_glasses',\n    description:\n      'Compile HoloScript to Android XR AI Glasses (Kotlin Compose Glimmer) for Samsung Galaxy XR, Warby Parker, Gentle Monster. ' +\n      'Bridge to transparent HUD overlay displays.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        code: { type: 'string', description: 'HoloScript source code.' },\n        options: {\n          type: 'object',\n          properties: {\n            fovDegrees: { type: 'number', description: 'Horizontal field-of-view in degrees for the target glasses display.' },\n          },\n        },\n      },\n      required: ['code'],\n    },\n  },\n\n  // Structural Causal Model DAG\n  {\n    name: 'compile_to_scm',\n    description:\n      'Compile HoloScript to Structural Causal Model DAG JSON for ML causal inference. ' +\n      'Bridge to do-calculus, intervention analysis, and causal ML pipelines.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        code: { type: 'string', description: 'HoloScript source code.' },\n        options: {\n          type: 'object',\n          properties: {\n            modelName: { type: 'string', description: 'Name for the root causal model node.' },\n            privacyMask: { type: 'boolean', description: 'Mask variable names in the output DAG.' },\n          },\n        },\n      },\n      required: ['code'],\n    },\n  },\n\n  // Solidity ERC-1155 NFT marketplace\n  {\n    name: 'compile_to_nft_marketplace',\n    description:\n      'Compile HoloScript to Solidity ERC-1155 smart contracts with lazy minting, ERC-2981 royalties, and multi-chain deployment scripts.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        code: { type: 'string', description: 'HoloScript source code.' },\n        options: {\n          type: 'object',\n          properties: {\n            chain: { type: 'string', description: 'Target chain identifier (e.g. \"ethereum\", \"polygon\", \"base\").' },\n            royaltyBps: { type: 'number', description: 'ERC-2981 royalty in basis points (e.g. 500 = 5%).' },\n          },\n        },\n      },\n      required: ['code'],\n    },\n  },\n\n  // Trait Shader Language — SOVEREIGN\n  {\n    name: 'compile_to_tsl',\n    description:\n      'Compile HoloScript to Trait Shader Language (TSL) — SOVEREIGN — native trait-to-shader codegen running on HoloScript\\'s WebGPU path.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        code: { type: 'string', description: 'HoloScript source code.' },\n        options: { type: 'object', properties: {} },\n      },\n      required: ['code'],\n    },\n  },\n\n  // compile_to_phone_sleeve_vr — retired (apex-poison, 2026-06-17)\n\n  // OpenXR Spatial Entity persistence\n  {\n    name: 'compile_to_openxr_spatial_entities',\n    description:\n      'Compile HoloScript to OpenXR Spatial Entity persistence format using XR_FB_spatial_entity_storage extension. ' +\n      'Bridge to persistent AR anchors on Quest 3 and OpenXR runtimes.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        code: { type: 'string', description: 'HoloScript source code.' },\n        options: { type: 'object', properties: {} },\n      },\n      required: ['code'],\n    },\n  },\n\n  // Job tracking and circuit breaker tools\n  {\n    name: 'get_compilation_status',\n    description:\n      'Get status of a compilation job by job ID. Returns progress, result, and timing information.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        jobId: {\n          type: 'string',\n          description: 'Job ID returned from compile_holoscript',\n        },\n      },\n      required: ['jobId'],\n    },\n  },\n  {\n    name: 'list_export_targets',\n    description:\n      'List all available HoloScript export targets with categories (Game Engines, VR Platforms, Web, Robotics, etc.) and sovereignty classification per target (sovereign = native HoloScript runtime/renderer; bridge = emits to third-party engine; mode = compile orchestrator).',\n    inputSchema: {\n      type: 'object',\n      properties: {},\n    },\n  },\n  {\n    name: 'get_circuit_breaker_status',\n    description:\n      'Get circuit breaker status for a specific export target. Shows failure rate, degraded mode time, and retry availability.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        target: {\n          type: 'string',\n          enum: [\n            'urdf',\n            'sdf',\n            'unity',\n            'unreal',\n            'pcg-graph',\n            'godot',\n            'vrchat',\n            'openxr',\n            'android',\n            'android-xr',\n            'ios',\n            'visionos',\n            // 'ar', 'babylon', 'playcanvas', 'vrr' — retired apex-poison 2026-06-17\n            'webgpu',\n            'r3f',\n            'wasm',\n            'usd',\n            'usdz',\n            'fmu',\n            'dtdl',\n            // 'multi-layer' — retired (MultiLayerCompiler retired 2026-06-17)\n            '3dgs',\n            '3dtiles',\n            'daimon-seed',\n          ],\n          description: 'Export target to check',\n        },\n      },\n      required: ['target'],\n    },\n  },\n  // Audit tools (automated number consistency)\n  ...auditTools,\n  ...alphafoldTools,\n];\n","import * as fs from 'fs';\nimport * as os from 'os';\nimport * as path from 'path';\nimport type { Tool } from '@modelcontextprotocol/sdk/types.js';\n\nconst HOLO_DIR = process.env.HOLOSCRIPT_CACHE_DIR || path.join(os.homedir(), '.holoscript');\nconst SNAPSHOTS_FILE = path.join(HOLO_DIR, 'snapshots.json');\n\nexport interface TemporalSnapshot {\n  snapshotId: string;\n  timestamp: number;\n  keyframe: Record<string, unknown>;\n  forwardDeltas: any[]; // Chain to rapidly seek O(1) forward in time\n}\n\n// Persistent snapshot store backed by disk\nconst snapshotStore: Map<string, TemporalSnapshot> = loadSnapshotsFromDisk();\n\nfunction loadSnapshotsFromDisk(): Map<string, TemporalSnapshot> {\n  try {\n    if (fs.existsSync(SNAPSHOTS_FILE)) {\n      const raw = fs.readFileSync(SNAPSHOTS_FILE, 'utf-8');\n      const obj: Record<string, TemporalSnapshot> = JSON.parse(raw);\n      return new Map(Object.entries(obj));\n    }\n  } catch {\n    // If file is corrupt, start fresh\n    console.warn(\n      `[CacheDebug][snapshot] load miss path=${SNAPSHOTS_FILE} reason=parse-or-io-error`\n    );\n  }\n  return new Map();\n}\n\nfunction saveSnapshotsToDisk(): void {\n  try {\n    if (!fs.existsSync(HOLO_DIR)) {\n      fs.mkdirSync(HOLO_DIR, { recursive: true });\n    }\n    const obj: Record<string, TemporalSnapshot> = {};\n    for (const [k, v] of snapshotStore) {\n      obj[k] = v;\n    }\n    fs.writeFileSync(SNAPSHOTS_FILE, JSON.stringify(obj), 'utf-8');\n  } catch {\n    // Best-effort — don't fail the tool call if disk write fails\n    console.warn(`[CacheDebug][snapshot] save miss path=${SNAPSHOTS_FILE}`);\n  }\n}\n\n/**\n * MCP Tools for Temporal Keyframing and State Rewinds\n * Empowers the Swarm to checkpoint the World and optionally backtrack during massive simulations.\n */\nexport const snapshotTools: Tool[] = [\n  {\n    name: 'create_temporal_snapshot',\n    description: 'Saves a complete keyframe of the world state for temporal rewinding.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        worldState: {\n          type: 'object',\n          description: 'The absolute authoritative state dictionary mapped by Entity IDs.',\n        },\n      },\n      required: ['worldState'],\n    },\n  },\n  {\n    name: 'load_temporal_snapshot',\n    description:\n      'Reads the meta parameters of a specific keyframe without enforcing a world rewind.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        snapshotId: { type: 'string', description: 'The unique ID of the keyframe.' },\n      },\n      required: ['snapshotId'],\n    },\n  },\n  {\n    name: 'rewind_world_state',\n    description:\n      'Forces the replication mesh backward, reverting the world to a safely stored Temporal Snapshot.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        snapshotId: {\n          type: 'string',\n          description: 'The UUID of the temporal snapshot to restore.',\n        },\n      },\n      required: ['snapshotId'],\n    },\n  },\n];\n\nexport async function handleSnapshotTool(name: string, args: any): Promise<any> {\n  switch (name) {\n    case 'create_temporal_snapshot': {\n      const { worldState } = args;\n      if (!worldState)\n        throw new Error(\n          \"[snapshot] Missing 'worldState' in args. Expected: {worldState: {objects: [...], environment: {...}}}. Got keys: \" +\n            Object.keys(args || {}).join(', ')\n        );\n\n      const snapshotId = `ts_${Date.now()}`;\n\n      snapshotStore.set(snapshotId, {\n        snapshotId,\n        timestamp: Date.now(),\n        keyframe: JSON.parse(JSON.stringify(worldState)), // deep clone\n        forwardDeltas: [],\n      });\n\n      saveSnapshotsToDisk();\n\n      return {\n        status: 'success',\n        snapshotId,\n        message: `Temporal Snapshot established cleanly with ${Object.keys(worldState).length} root entities.`,\n      };\n    }\n    case 'load_temporal_snapshot': {\n      const { snapshotId } = args;\n      const snapshot = snapshotStore.get(snapshotId);\n\n      if (!snapshot)\n        return {\n          status: 'error',\n          message: `Snapshot ${snapshotId} isolated or missing. Known snapshots: ${snapshotStore.size}`,\n        };\n\n      return {\n        status: 'success',\n        timestamp: snapshot.timestamp,\n        deltaChainLength: snapshot.forwardDeltas.length,\n        entityCount: Object.keys(snapshot.keyframe).length,\n      };\n    }\n    case 'rewind_world_state': {\n      const { snapshotId } = args;\n      const snapshot = snapshotStore.get(snapshotId);\n\n      if (!snapshot) {\n        return { status: 'error', message: `Snapshot ${snapshotId} not found.` };\n      }\n\n      return {\n        status: 'success',\n        rewoundState: snapshot.keyframe,\n        message: `Temporal Anomaly averted! World reverted successfully to ${new Date(snapshot.timestamp).toISOString()}.`,\n      };\n    }\n    default:\n      return null;\n  }\n}\n","import { Tool } from '@modelcontextprotocol/sdk/types.js';\nimport { telemetry } from '@holoscript/core';\n\nexport const monitoringTools: Tool[] = [\n  {\n    name: 'get_telemetry_metrics',\n    description:\n      'System: Retrieves the current Prometheus-style telemetry snapshot including counters, gauges, and latency histograms from the spatial runtime.',\n    inputSchema: {\n      type: 'object',\n      properties: {},\n    },\n  },\n];\n\nexport async function handleMonitoringTool(\n  name: string,\n  _args: Record<string, any>\n): Promise<any | null> {\n  if (name === 'get_telemetry_metrics') {\n    return {\n      status: 'success',\n      metrics: telemetry.getSnapshot(),\n    };\n  }\n  return null;\n}\n","/**\n * HoloTest MCP Tools — execute_holotest\n *\n * Enables AI agents to run spatial assertions against HoloScript scenes and\n * receive structured semantic feedback for self-correction loops.\n *\n * Tool: execute_holotest\n *\n * Workflow:\n *   1. Parse the scene code (HoloScript / .holo)\n *   2. Extract objects with resolved world-space bounds\n *   3. Run spatial assertions (explicit or auto-detect all intersecting pairs)\n *   4. Return JSON-RPC payload with AgentFeedback for each failure\n *\n * Self-contained: does NOT depend on @holoscript/test (which requires vitest).\n * BoundingBox math is inlined so this file can run inside the mcp-server process.\n */\n\nimport type { Tool } from '@modelcontextprotocol/sdk/types.js';\nimport { parseHolo, HoloScriptPlusParser } from '@holoscript/core';\nimport { createProviderManager } from '@holoscript/llm-provider';\n\n// ── Inline spatial math (mirrors packages/test/src/spatial/) ──────────────\n\ninterface Vec3 {\n  x: number;\n  y: number;\n  z: number;\n}\n\nclass BoundingBox {\n  constructor(\n    readonly min: Readonly<Vec3>,\n    readonly max: Readonly<Vec3>\n  ) {}\n\n  static fromMinMax(min: Vec3, max: Vec3): BoundingBox {\n    return new BoundingBox(\n      { x: Math.min(min.x, max.x), y: Math.min(min.y, max.y), z: Math.min(min.z, max.z) },\n      { x: Math.max(min.x, max.x), y: Math.max(min.y, max.y), z: Math.max(min.z, max.z) }\n    );\n  }\n\n  static fromBottomCenter(bc: Vec3, size: Vec3): BoundingBox {\n    const hx = Math.abs(size.x) / 2,\n      hz = Math.abs(size.z) / 2;\n    return new BoundingBox(\n      { x: bc.x - hx, y: bc.y, z: bc.z - hz },\n      { x: bc.x + hx, y: bc.y + Math.abs(size.y), z: bc.z + hz }\n    );\n  }\n\n  center(): Vec3 {\n    return {\n      x: (this.min.x + this.max.x) / 2,\n      y: (this.min.y + this.max.y) / 2,\n      z: (this.min.z + this.max.z) / 2,\n    };\n  }\n\n  contains(p: Vec3): boolean {\n    return (\n      p.x >= this.min.x &&\n      p.x <= this.max.x &&\n      p.y >= this.min.y &&\n      p.y <= this.max.y &&\n      p.z >= this.min.z &&\n      p.z <= this.max.z\n    );\n  }\n\n  intersects(o: BoundingBox): boolean {\n    return (\n      this.min.x <= o.max.x &&\n      this.max.x >= o.min.x &&\n      this.min.y <= o.max.y &&\n      this.max.y >= o.min.y &&\n      this.min.z <= o.max.z &&\n      this.max.z >= o.min.z\n    );\n  }\n\n  intersectionVolume(o: BoundingBox): number {\n    const ox = Math.min(this.max.x, o.max.x) - Math.max(this.min.x, o.min.x);\n    const oy = Math.min(this.max.y, o.max.y) - Math.max(this.min.y, o.min.y);\n    const oz = Math.min(this.max.z, o.max.z) - Math.max(this.min.z, o.min.z);\n    if (ox <= 0 || oy <= 0 || oz <= 0) return 0;\n    return ox * oy * oz;\n  }\n\n  penetrationDepth(o: BoundingBox): Vec3 {\n    if (!this.intersects(o)) return { x: 0, y: 0, z: 0 };\n    return {\n      x: Math.min(this.max.x, o.max.x) - Math.max(this.min.x, o.min.x),\n      y: Math.min(this.max.y, o.max.y) - Math.max(this.min.y, o.min.y),\n      z: Math.min(this.max.z, o.max.z) - Math.max(this.min.z, o.min.z),\n    };\n  }\n\n  toString(): string {\n    const { min: n, max: x } = this;\n    return `BoundingBox(${n.x},${n.y},${n.z}→${x.x},${x.y},${x.z})`;\n  }\n}\n\nclass SpatialEntity {\n  constructor(\n    readonly id: string,\n    public bounds: BoundingBox,\n    readonly tags: string[] = []\n  ) {}\n\n  static at(\n    id: string,\n    pos: [number, number, number],\n    size: [number, number, number]\n  ): SpatialEntity {\n    return new SpatialEntity(\n      id,\n      BoundingBox.fromBottomCenter(\n        { x: pos[0], y: pos[1], z: pos[2] },\n        { x: size[0], y: size[1], z: size[2] }\n      )\n    );\n  }\n\n  get position(): Vec3 {\n    const c = this.bounds.center();\n    const s = {\n      x: this.bounds.max.x - this.bounds.min.x,\n      y: this.bounds.max.y - this.bounds.min.y,\n      z: this.bounds.max.z - this.bounds.min.z,\n    };\n    return { x: c.x, y: c.y - s.y / 2, z: c.z };\n  }\n\n  intersects(other: SpatialEntity | BoundingBox): boolean {\n    return this.bounds.intersects(other instanceof SpatialEntity ? other.bounds : other);\n  }\n\n  isWithinVolume(box: BoundingBox): boolean {\n    return box.contains(this.bounds.min) && box.contains(this.bounds.max);\n  }\n}\n\n// ── Result types (mirrors packages/test/src/reporter/) ────────────────────\n\ntype SpatialErrorType =\n  | 'IntersectionViolation'\n  | 'OutOfBounds'\n  | 'ValueViolation'\n  | 'PositionViolation'\n  | 'PhysicsViolation';\n\ninterface AgentFeedback {\n  error_type: SpatialErrorType;\n  semantic_message: string;\n  spatial_hint: string;\n  fix_suggestion: string;\n  affected_lines: number[];\n}\n\ninterface HolotestResult {\n  tool_name: 'execute_holotest' | 'execute_eval';\n  status: 'passed' | 'failed' | 'error';\n  summary: string;\n  tests: TestReport[];\n  agent_feedback?: AgentFeedback;\n  /** Present when llm_judge mode was used */\n  judge_result?: JudgeResult;\n  /** Present when regression_suite mode was used */\n  regression_diff?: RegressionDiff;\n}\n\n// ── LLM Judge types ────────────────────────────────────────────────────────\n\ninterface LLMJudgeConfig {\n  /** Judge model — any provider-qualified model string, e.g. \"claude-opus-4-7\" */\n  model?: string;\n  /** Free-text rubric the judge evaluates against */\n  rubric: string;\n  /** Named scoring dimensions, e.g. [\"correctness\", \"completeness\", \"conciseness\"] */\n  scoring_dimensions?: string[];\n}\n\ninterface RegressionSuiteConfig {\n  /** The reference output to compare the current output against */\n  reference_output: string;\n  /** Optional trace ID for provenance (stored in result for audit trail) */\n  reference_trace_id?: string;\n}\n\ninterface JudgeScore {\n  dimension: string;\n  score: number; // 0-10\n  rationale: string;\n}\n\ninterface JudgeResult {\n  verdict: 'PASS' | 'FAIL' | 'DEGRADED';\n  overall_score: number; // 0-10\n  rubric: string;\n  scores: JudgeScore[];\n  summary: string;\n  provider?: string;\n}\n\ninterface RegressionDiff {\n  reference_trace_id?: string;\n  verdict: 'NO_REGRESSION' | 'REGRESSION' | 'IMPROVEMENT';\n  score_delta: number; // current - reference\n  summary: string;\n}\n\ninterface TestReport {\n  name: string;\n  status: 'passed' | 'failed' | 'skipped';\n  duration_ms: number;\n  error?: AgentFeedback;\n}\n\n// ── Semantic reporting ─────────────────────────────────────────────────────\n\nfunction minAxis(pen: Vec3): { axis: 'X' | 'Y' | 'Z'; depth: number } {\n  const ax = Math.abs(pen.x),\n    ay = Math.abs(pen.y),\n    az = Math.abs(pen.z);\n  if (ay <= ax && ay <= az) return { axis: 'Y', depth: pen.y };\n  if (ax <= az) return { axis: 'X', depth: pen.x };\n  return { axis: 'Z', depth: pen.z };\n}\n\nfunction f(n: number) {\n  return n.toFixed(3);\n}\n\nfunction intersectionFeedback(a: SpatialEntity, b: SpatialEntity): AgentFeedback {\n  const pen = a.bounds.penetrationDepth(b.bounds);\n  const { axis, depth } = minAxis(pen);\n  const vol = a.bounds.intersectionVolume(b.bounds);\n  const sign = depth > 0 ? '+' : '';\n  const bA = a.bounds,\n    bB = b.bounds;\n  let desc = `'${a.id}' and '${b.id}' are clipping (${f(vol)} m³ overlap)`;\n  if (axis === 'Y') {\n    desc = `'${a.id}' bottom Y (${f(bA.min.y)}m) overlaps '${b.id}' top Y (${f(bB.max.y)}m) by ${f(Math.abs(depth))}m`;\n  }\n  return {\n    error_type: 'IntersectionViolation',\n    semantic_message: `SpatialAssertionError: ${desc}.`,\n    spatial_hint: `Smallest penetration axis is ${axis} (${f(Math.abs(depth))}m). Moving on ${axis} is the cheapest fix.`,\n    fix_suggestion: `Adjust ${axis} of '${a.id}' by ${sign}${f(depth)} units to resolve clipping.`,\n    affected_lines: [],\n  };\n}\n\nfunction outOfBoundsFeedback(entity: SpatialEntity, container: BoundingBox): AgentFeedback {\n  const b = entity.bounds;\n  const c = container;\n  const violations: string[] = [];\n  if (b.min.x < c.min.x)\n    violations.push(`min.x (${f(b.min.x)}) < ${f(c.min.x)}: shift +X ${f(c.min.x - b.min.x)}m`);\n  if (b.min.y < c.min.y)\n    violations.push(`min.y (${f(b.min.y)}) < ${f(c.min.y)}: shift +Y ${f(c.min.y - b.min.y)}m`);\n  if (b.min.z < c.min.z)\n    violations.push(`min.z (${f(b.min.z)}) < ${f(c.min.z)}: shift +Z ${f(c.min.z - b.min.z)}m`);\n  if (b.max.x > c.max.x)\n    violations.push(`max.x (${f(b.max.x)}) > ${f(c.max.x)}: shift -X ${f(b.max.x - c.max.x)}m`);\n  if (b.max.y > c.max.y)\n    violations.push(`max.y (${f(b.max.y)}) > ${f(c.max.y)}: shift -Y ${f(b.max.y - c.max.y)}m`);\n  if (b.max.z > c.max.z)\n    violations.push(`max.z (${f(b.max.z)}) > ${f(c.max.z)}: shift -Z ${f(b.max.z - c.max.z)}m`);\n  return {\n    error_type: 'OutOfBounds',\n    semantic_message: `SpatialAssertionError: '${entity.id}' is outside its container.\\n${violations.map((v) => `  · ${v}`).join('\\n')}`,\n    spatial_hint: `Container: ${container}. Entity: ${entity.bounds}.`,\n    fix_suggestion: violations[0] ?? 'Adjust entity position or size.',\n    affected_lines: [],\n  };\n}\n\nfunction missingFeedback(detail: string): AgentFeedback {\n  return {\n    error_type: 'ValueViolation',\n    semantic_message: detail,\n    spatial_hint: 'Check entity IDs match names in the scene.',\n    fix_suggestion: 'Run execute_holotest with the full scene code.',\n    affected_lines: [],\n  };\n}\n\n// ── Tool Definitions ───────────────────────────────────────────────────────\n\nexport const holotestTools: Tool[] = [\n  {\n    name: 'execute_holotest',\n    description:\n      'Execute spatial assertions against a HoloScript scene and return semantic feedback ' +\n      'for AI agent self-correction. Parses the scene to extract object bounds, then runs: ' +\n      '(1) explicit assertions you specify, or (2) auto-detects all intersecting object pairs. ' +\n      'Returns structured JSON-RPC with a semantic_message, spatial_hint, and fix_suggestion ' +\n      'for each failure — designed to feed directly into an LLM self-correction loop.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        code: {\n          type: 'string',\n          description:\n            'HoloScript scene code (.hs, .hsplus, or .holo). Objects with position/size properties ' +\n            'will be extracted and tested.',\n        },\n        format: {\n          type: 'string',\n          enum: ['holo', 'hsplus', 'hs', 'auto'],\n          description: 'Code format. Defaults to \"auto\" (detects from content).',\n        },\n        assertions: {\n          type: 'array',\n          description:\n            'Optional list of explicit spatial assertions to run. ' +\n            'If omitted, all object pairs are checked for unexpected intersections.',\n          items: {\n            type: 'object',\n            properties: {\n              name: { type: 'string', description: 'Test name (used in report).' },\n              type: {\n                type: 'string',\n                enum: ['no_intersect', 'intersects', 'within_volume', 'poly_count'],\n                description:\n                  'Assertion type: ' +\n                  '\"no_intersect\" = expect no clipping, ' +\n                  '\"intersects\" = expect overlap, ' +\n                  '\"within_volume\" = entity must be inside a box, ' +\n                  '\"poly_count\" = numeric limit check.',\n              },\n              entityA: { type: 'string', description: 'ID of the first entity.' },\n              entityB: {\n                type: 'string',\n                description: 'ID of the second entity (for pair assertions).',\n              },\n              container: {\n                type: 'object',\n                description: 'For within_volume: { min: [x,y,z], max: [x,y,z] }',\n                properties: {\n                  min: { type: 'array', items: { type: 'number' }, minItems: 3, maxItems: 3 },\n                  max: { type: 'array', items: { type: 'number' }, minItems: 3, maxItems: 3 },\n                },\n              },\n              value: { type: 'number', description: 'For poly_count: the actual value to check.' },\n              limit: { type: 'number', description: 'For poly_count: the maximum allowed value.' },\n            },\n            required: ['type'],\n          },\n        },\n        auto_check_intersections: {\n          type: 'boolean',\n          description:\n            'When true (default when no assertions specified), automatically checks all object pairs ' +\n            'for unintended intersections and reports clipping issues.',\n        },\n        output: {\n          type: 'string',\n          description:\n            'Agent or model output text to evaluate with an LLM judge. ' +\n            'Required when llm_judge is specified. Not used for spatial assertions.',\n        },\n        llm_judge: {\n          type: 'object',\n          description:\n            'When provided, runs the output through an LLM-as-judge evaluation instead of (or in addition to) ' +\n            'spatial assertions. The judge scores the output against the rubric and returns a structured verdict. ' +\n            'Closes CG-086 (LangSmith / Mastra eval gap).',\n          properties: {\n            model: {\n              type: 'string',\n              description:\n                'Judge model to use (e.g. \"claude-opus-4-7\"). ' +\n                'Defaults to the highest-priority registered provider.',\n            },\n            rubric: {\n              type: 'string',\n              description: 'Free-text rubric the judge evaluates the output against.',\n            },\n            scoring_dimensions: {\n              type: 'array',\n              items: { type: 'string' },\n              description:\n                'Named dimensions to score (e.g. [\"correctness\", \"completeness\"]). ' +\n                'Defaults to [\"correctness\", \"completeness\", \"conciseness\"].',\n            },\n          },\n          required: ['rubric'],\n        },\n        regression_suite: {\n          type: 'object',\n          description:\n            'When provided together with llm_judge, compares the current judge score against ' +\n            'a reference output to detect regressions or improvements.',\n          properties: {\n            reference_output: {\n              type: 'string',\n              description: 'The reference (baseline) output to compare against.',\n            },\n            reference_trace_id: {\n              type: 'string',\n              description: 'Optional trace ID for the reference run (stored for audit trail).',\n            },\n          },\n          required: ['reference_output'],\n        },\n      },\n      required: ['code'],\n    },\n  },\n  {\n    name: 'execute_eval',\n    description:\n      'Run an LLM-as-judge evaluation against a provided output and rubric, with optional ' +\n      'regression comparison against a reference output. Returns scored dimensions and a verdict. ' +\n      'Equivalent to LangSmith / Mastra Evals evaluate() — closes CG-086. ' +\n      'Does not require HoloScript scene code; accepts any text output.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        output: {\n          type: 'string',\n          description: 'The agent or model output text to evaluate.',\n        },\n        rubric: {\n          type: 'string',\n          description: 'Free-text rubric describing what a good output looks like.',\n        },\n        scoring_dimensions: {\n          type: 'array',\n          items: { type: 'string' },\n          description:\n            'Named dimensions to score independently (e.g. [\"correctness\", \"completeness\"]). ' +\n            'Defaults to [\"correctness\", \"completeness\", \"conciseness\"].',\n        },\n        model: {\n          type: 'string',\n          description: 'Judge model override (e.g. \"claude-opus-4-7\").',\n        },\n        reference_output: {\n          type: 'string',\n          description: 'Optional baseline output for regression comparison.',\n        },\n        reference_trace_id: {\n          type: 'string',\n          description: 'Optional trace ID for the reference run (stored for audit).',\n        },\n      },\n      required: ['output', 'rubric'],\n    },\n  },\n];\n\n// ── Handler ────────────────────────────────────────────────────────────────\n\nexport async function handleHolotestTool(\n  name: string,\n  args: Record<string, unknown>\n): Promise<HolotestResult | null> {\n  if (name === 'execute_holotest') return runExecuteHolotest(args);\n  if (name === 'execute_eval') return runExecuteEval(args);\n  return null;\n}\n\n// ── Execution Engine ───────────────────────────────────────────────────────\n\ninterface Assertion {\n  name?: string;\n  type: 'no_intersect' | 'intersects' | 'within_volume' | 'poly_count';\n  entityA?: string;\n  entityB?: string;\n  container?: { min: [number, number, number]; max: [number, number, number] };\n  value?: number;\n  limit?: number;\n}\n\nasync function runExecuteHolotest(args: Record<string, unknown>): Promise<HolotestResult> {\n  const code = args.code as string;\n  const format = (args.format as string | undefined) ?? 'auto';\n  const assertions = (args.assertions as Assertion[] | undefined) ?? [];\n  const autoCheck = args.auto_check_intersections !== false;\n\n  // LLM-judge mode: when llm_judge is provided, route to the judge engine\n  // (may also run spatial assertions if code has entities)\n  const judgeConfig = args.llm_judge as LLMJudgeConfig | undefined;\n  const regressionConfig = args.regression_suite as RegressionSuiteConfig | undefined;\n\n  if (judgeConfig) {\n    const output = (args.output as string | undefined) ?? code;\n    const judgeResult = await runLLMJudge(output, judgeConfig);\n    const regressionDiff = regressionConfig\n      ? await runRegressionComparison(output, judgeConfig, regressionConfig)\n      : undefined;\n\n    const passed = judgeResult.verdict === 'PASS';\n    const status: HolotestResult['status'] = judgeResult.verdict === 'FAIL' ? 'failed' : 'passed';\n    return {\n      tool_name: 'execute_holotest',\n      status,\n      summary: `LLM judge: ${judgeResult.verdict} (score ${judgeResult.overall_score.toFixed(1)}/10) — ${judgeResult.summary}`,\n      tests: [\n        {\n          name: '[llm_judge] rubric evaluation',\n          status: passed ? 'passed' : 'failed',\n          duration_ms: 0,\n          ...(passed\n            ? {}\n            : {\n                error: {\n                  error_type: 'ValueViolation',\n                  semantic_message: judgeResult.summary,\n                  spatial_hint: `Lowest score: ${judgeResult.scores.reduce((a, b) => (a.score < b.score ? a : b), judgeResult.scores[0] ?? { dimension: '?', score: 0, rationale: '' }).dimension}`,\n                  fix_suggestion: 'Revise output to better satisfy the rubric.',\n                  affected_lines: [],\n                },\n              }),\n        },\n      ],\n      judge_result: judgeResult,\n      regression_diff: regressionDiff,\n    };\n  }\n\n  // 1. Parse & extract entities\n  let entities: SpatialEntity[];\n  try {\n    entities = extractEntities(code, format);\n  } catch (err) {\n    return {\n      tool_name: 'execute_holotest',\n      status: 'error',\n      summary: `Parse error: ${(err as Error).message}`,\n      tests: [],\n      agent_feedback: {\n        error_type: 'ValueViolation',\n        semantic_message: `Failed to parse HoloScript code: ${(err as Error).message}`,\n        spatial_hint: 'Check that the code is valid HoloScript (.hs, .hsplus, or .holo).',\n        fix_suggestion: 'Run validate_holoscript first to verify syntax.',\n        affected_lines: [],\n      },\n    };\n  }\n\n  const entityMap = new Map<string, SpatialEntity>(entities.map((e) => [e.id, e]));\n\n  // 2. Run assertions\n  const tests: TestReport[] = [];\n  const start = Date.now();\n\n  // Explicit assertions\n  for (const assertion of assertions) {\n    const t0 = Date.now();\n    const report = runAssertion(assertion, entityMap);\n    tests.push({ ...report, duration_ms: Date.now() - t0 });\n  }\n\n  // Auto-intersection check (all pairs)\n  if (assertions.length === 0 && autoCheck && entities.length >= 2) {\n    for (let i = 0; i < entities.length; i++) {\n      for (let j = i + 1; j < entities.length; j++) {\n        const a = entities[i];\n        const b = entities[j];\n        const t0 = Date.now();\n        if (a.intersects(b)) {\n          tests.push({\n            name: `[auto] no_intersect: '${a.id}' vs '${b.id}'`,\n            status: 'failed',\n            duration_ms: Date.now() - t0,\n            error: intersectionFeedback(a, b),\n          });\n        } else {\n          tests.push({\n            name: `[auto] no_intersect: '${a.id}' vs '${b.id}'`,\n            status: 'passed',\n            duration_ms: Date.now() - t0,\n          });\n        }\n      }\n    }\n  }\n\n  const failed = tests.filter((t) => t.status === 'failed');\n  const passed = tests.filter((t) => t.status === 'passed');\n\n  const status: HolotestResult['status'] = failed.length > 0 ? 'failed' : 'passed';\n  const summary = `${tests.length} tests — ${passed.length} passed, ${failed.length} failed (${Date.now() - start}ms)`;\n\n  const result: HolotestResult = {\n    tool_name: 'execute_holotest',\n    status,\n    summary,\n    tests,\n  };\n\n  if (failed.length > 0 && failed[0].error) {\n    result.agent_feedback = failed[0].error;\n  }\n\n  return result;\n}\n\nfunction runAssertion(\n  a: Assertion,\n  entities: Map<string, SpatialEntity>\n): Omit<TestReport, 'duration_ms'> {\n  const testName = a.name ?? `${a.type}(${a.entityA ?? '?'}, ${a.entityB ?? a.type})`;\n\n  switch (a.type) {\n    case 'no_intersect':\n    case 'intersects': {\n      if (!a.entityA || !a.entityB) {\n        return {\n          name: testName,\n          status: 'failed',\n          error: missingFeedback(`'${testName}': entityA and entityB required`),\n        };\n      }\n      const ea = entities.get(a.entityA);\n      const eb = entities.get(a.entityB);\n      if (!ea || !eb) {\n        const missing = !ea ? a.entityA : a.entityB;\n        return {\n          name: testName,\n          status: 'failed',\n          error: missingFeedback(`'${testName}': Entity '${missing}' not found in parsed scene.`),\n        };\n      }\n      const overlaps = ea.intersects(eb);\n      const expectOverlap = a.type === 'intersects';\n      if (overlaps === expectOverlap) {\n        return { name: testName, status: 'passed' };\n      }\n      return {\n        name: testName,\n        status: 'failed',\n        error: intersectionFeedback(ea, eb),\n      };\n    }\n\n    case 'within_volume': {\n      if (!a.entityA || !a.container) {\n        return {\n          name: testName,\n          status: 'failed',\n          error: missingFeedback(`'${testName}': entityA and container required`),\n        };\n      }\n      const ea = entities.get(a.entityA);\n      if (!ea) {\n        return {\n          name: testName,\n          status: 'failed',\n          error: missingFeedback(`'${testName}': Entity '${a.entityA}' not found.`),\n        };\n      }\n      const box = BoundingBox.fromMinMax(\n        { x: a.container.min[0], y: a.container.min[1], z: a.container.min[2] },\n        { x: a.container.max[0], y: a.container.max[1], z: a.container.max[2] }\n      );\n      if (ea.isWithinVolume(box)) {\n        return { name: testName, status: 'passed' };\n      }\n      return {\n        name: testName,\n        status: 'failed',\n        error: outOfBoundsFeedback(ea, box),\n      };\n    }\n\n    case 'poly_count': {\n      if (a.value === undefined || a.limit === undefined) {\n        return {\n          name: testName,\n          status: 'failed',\n          error: missingFeedback(`'${testName}': value and limit required for poly_count`),\n        };\n      }\n      if (a.value <= a.limit) {\n        return { name: testName, status: 'passed' };\n      }\n      return {\n        name: testName,\n        status: 'failed',\n        error: {\n          error_type: 'ValueViolation',\n          semantic_message: `SceneViolation: poly count ${a.value} exceeds limit ${a.limit} (excess: ${a.value - a.limit}).`,\n          spatial_hint: 'Reduce mesh complexity or use LOD objects.',\n          fix_suggestion: `Reduce polyCount by at least ${a.value - a.limit} triangles.`,\n          affected_lines: [],\n        },\n      };\n    }\n\n    default:\n      return {\n        name: testName,\n        status: 'failed',\n        error: missingFeedback(`Unknown assertion type: ${a.type}`),\n      };\n  }\n}\n\n// ── Scene Parser ───────────────────────────────────────────────────────────\n\n/**\n * Parse HoloScript code and extract SpatialEntity objects from `object` definitions\n * that have position and size/geometry properties.\n */\nfunction extractEntities(code: string, format: string): SpatialEntity[] {\n  const entities: SpatialEntity[] = [];\n\n  // Detect format\n  const isHolo =\n    format === 'holo' ||\n    (format === 'auto' && /composition\\s+\"/.test(code) && !/template\\s+\"|@\\w+/.test(code));\n\n  // Try structured parse first\n  try {\n    if (isHolo) {\n      const ast = parseHolo(code);\n      extractFromHoloAst(ast, entities);\n    } else {\n      const parser = new HoloScriptPlusParser();\n      const ast = parser.parse(code);\n      extractFromHsplusAst(ast, entities);\n    }\n  } catch {\n    // Fall back to regex extraction if parser fails\n  }\n\n  // Regex fallback / supplement: find object \"Name\" { position: [...] } blocks\n  if (entities.length === 0) {\n    extractViaRegex(code, entities);\n  }\n\n  return entities;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction extractFromHoloAst(ast: any, out: SpatialEntity[]): void {\n  if (!ast || typeof ast !== 'object') return;\n  const objects = findNodes(ast, 'object');\n  for (const obj of objects) {\n    const entity = astNodeToEntity(obj);\n    if (entity) out.push(entity);\n  }\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction extractFromHsplusAst(ast: any, out: SpatialEntity[]): void {\n  if (!ast || typeof ast !== 'object') return;\n  const objects = findNodes(ast, 'object');\n  for (const obj of objects) {\n    const entity = astNodeToEntity(obj);\n    if (entity) out.push(entity);\n  }\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction findNodes(node: any, type: string, acc: any[] = []): any[] {\n  if (!node || typeof node !== 'object') return acc;\n  if (node.type === type || node.nodeType === type || node.kind === type) acc.push(node);\n  for (const val of Object.values(node)) {\n    if (Array.isArray(val)) {\n      for (const child of val) findNodes(child, type, acc);\n    } else if (val && typeof val === 'object') {\n      findNodes(val, type, acc);\n    }\n  }\n  return acc;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction astNodeToEntity(node: any): SpatialEntity | null {\n  // Extract id/name\n  const id: string = node.name ?? node.id ?? node.identifier ?? 'unknown';\n\n  // Extract position\n  const pos = extractVec3Property(node, ['position', 'pos', 'location']);\n  if (!pos) return null;\n\n  // Extract size\n  const size = extractVec3Property(node, ['size', 'scale', 'dimensions', 'extents']);\n\n  if (size) {\n    return SpatialEntity.at(id, [pos.x, pos.y, pos.z], [size.x, size.y, size.z]);\n  }\n\n  // If no size, use a default 1m³ cube\n  return SpatialEntity.at(id, [pos.x, pos.y, pos.z], [1, 1, 1]);\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction extractVec3Property(node: any, keys: string[]): Vec3 | null {\n  for (const key of keys) {\n    const val = node[key] ?? node.properties?.[key] ?? node.props?.[key];\n    if (!val) continue;\n    if (Array.isArray(val) && val.length >= 3) {\n      return { x: Number(val[0]), y: Number(val[1]), z: Number(val[2]) };\n    }\n    if (typeof val === 'object' && 'x' in val) {\n      return { x: Number(val.x), y: Number(val.y ?? 0), z: Number(val.z ?? 0) };\n    }\n  }\n  return null;\n}\n\n/**\n * Regex-based extraction for when the AST parser doesn't find positioned objects.\n * Handles: position: [x, y, z]  and  size: [w, h, d]\n */\nfunction extractViaRegex(code: string, out: SpatialEntity[]): void {\n  // Match: object \"Name\" { ... } blocks\n  const objectBlockRE =\n    /object\\s+\"([^\"]+)\"\\s*(?:using\\s+\"[^\"]+\"\\s*)?\\{([^}]*(?:\\{[^}]*\\}[^}]*)*)\\}/gs;\n  let match: RegExpExecArray | null;\n\n  while ((match = objectBlockRE.exec(code)) !== null) {\n    const id = match[1];\n    const body = match[2];\n\n    const pos = extractArrayProp(body, 'position');\n    if (!pos) continue;\n\n    const size = extractArrayProp(body, 'size') ?? extractArrayProp(body, 'scale');\n\n    out.push(\n      SpatialEntity.at(id, [pos[0], pos[1], pos[2]], size ? [size[0], size[1], size[2]] : [1, 1, 1])\n    );\n  }\n}\n\nfunction extractArrayProp(body: string, key: string): [number, number, number] | null {\n  const re = new RegExp(\n    `${key}\\\\s*:\\\\s*\\\\[\\\\s*([\\\\d.+-]+)\\\\s*,\\\\s*([\\\\d.+-]+)\\\\s*,\\\\s*([\\\\d.+-]+)\\\\s*\\\\]`\n  );\n  const m = re.exec(body);\n  if (!m) return null;\n  return [parseFloat(m[1]), parseFloat(m[2]), parseFloat(m[3])];\n}\n\n// ── LLM Judge engine ───────────────────────────────────────────────────────\n\nconst DEFAULT_JUDGE_DIMENSIONS = ['correctness', 'completeness', 'conciseness'];\nconst JUDGE_PASS_THRESHOLD = 6.0; // out of 10\n\n/**\n * Build the system prompt for the LLM judge.\n * Output MUST be valid JSON conforming to the JudgeResult schema.\n */\nfunction buildJudgePrompt(rubric: string, dimensions: string[]): string {\n  const dimList = dimensions.map((d) => `\"${d}\"`).join(', ');\n  return (\n    'You are a strict, unbiased LLM-as-judge evaluator. ' +\n    'Score the provided output against the rubric below. ' +\n    'Return ONLY valid JSON — no markdown, no prose outside the JSON.\\n\\n' +\n    `Rubric:\\n${rubric}\\n\\n` +\n    `Score each dimension independently on a 0–10 integer scale: ${dimList}.\\n` +\n    '0 = completely wrong/missing, 5 = partially correct, 10 = perfect.\\n\\n' +\n    'Output schema:\\n' +\n    '{\\n' +\n    '  \"verdict\": \"PASS\" | \"FAIL\" | \"DEGRADED\",\\n' +\n    '  \"overall_score\": <number 0-10, average of dimension scores>,\\n' +\n    '  \"scores\": [{ \"dimension\": \"<name>\", \"score\": <0-10>, \"rationale\": \"<1-2 sentences>\" }],\\n' +\n    '  \"summary\": \"<one sentence verdict rationale>\"\\n' +\n    '}\\n\\n' +\n    `PASS if overall_score >= ${JUDGE_PASS_THRESHOLD}, DEGRADED if 4–${JUDGE_PASS_THRESHOLD - 0.1}, FAIL if < 4.`\n  );\n}\n\nfunction parseJudgeOutput(\n  raw: string,\n  dimensions: string[],\n  provider?: string\n): JudgeResult {\n  let jsonText = raw.trim();\n  // Strip markdown fences if present\n  const fenced = jsonText.match(/```(?:json)?\\s*\\n?([\\s\\S]*?)```/);\n  if (fenced) jsonText = fenced[1].trim();\n\n  try {\n    const parsed = JSON.parse(jsonText) as {\n      verdict?: string;\n      overall_score?: number;\n      scores?: Array<{ dimension?: string; score?: number; rationale?: string }>;\n      summary?: string;\n    };\n\n    const scores: JudgeScore[] = (parsed.scores ?? []).map((s) => ({\n      dimension: typeof s.dimension === 'string' ? s.dimension : '?',\n      score: typeof s.score === 'number' ? Math.max(0, Math.min(10, s.score)) : 0,\n      rationale: typeof s.rationale === 'string' ? s.rationale : '',\n    }));\n\n    // Fill any missing dimensions with 0\n    for (const dim of dimensions) {\n      if (!scores.some((s) => s.dimension === dim)) {\n        scores.push({ dimension: dim, score: 0, rationale: 'Not scored by judge.' });\n      }\n    }\n\n    const overall =\n      typeof parsed.overall_score === 'number'\n        ? Math.max(0, Math.min(10, parsed.overall_score))\n        : scores.reduce((sum, s) => sum + s.score, 0) / Math.max(scores.length, 1);\n\n    const verdict =\n      parsed.verdict === 'PASS' || parsed.verdict === 'FAIL' || parsed.verdict === 'DEGRADED'\n        ? (parsed.verdict as JudgeResult['verdict'])\n        : overall >= JUDGE_PASS_THRESHOLD\n          ? 'PASS'\n          : overall >= 4\n            ? 'DEGRADED'\n            : 'FAIL';\n\n    return {\n      verdict,\n      overall_score: Math.round(overall * 10) / 10,\n      rubric: '', // filled by caller\n      scores,\n      summary: typeof parsed.summary === 'string' ? parsed.summary : 'No summary.',\n      provider,\n    };\n  } catch {\n    // Fallback: judge response unparseable\n    return {\n      verdict: 'FAIL',\n      overall_score: 0,\n      rubric: '',\n      scores: dimensions.map((d) => ({ dimension: d, score: 0, rationale: 'Judge response unparseable.' })),\n      summary: 'LLM judge returned non-JSON output — treated as FAIL.',\n      provider,\n    };\n  }\n}\n\nasync function runLLMJudge(output: string, config: LLMJudgeConfig): Promise<JudgeResult> {\n  const dimensions = config.scoring_dimensions ?? DEFAULT_JUDGE_DIMENSIONS;\n  const systemPrompt = buildJudgePrompt(config.rubric, dimensions);\n  const userMessage = `Output to evaluate:\\n\\n${output}`;\n\n  try {\n    const manager = createProviderManager();\n    const providers = manager.getRegisteredProviders();\n    const providerOrder = providers;\n\n    for (const providerName of providerOrder) {\n      const provider = manager.getProvider(providerName);\n      if (!provider) continue;\n      try {\n        const result = await provider.complete({\n          messages: [\n            { role: 'system' as const, content: systemPrompt },\n            { role: 'user' as const, content: userMessage },\n          ],\n          maxTokens: 512,\n          temperature: 0,\n        });\n        const judgeResult = parseJudgeOutput(result.content, dimensions, providerName);\n        judgeResult.rubric = config.rubric;\n        return judgeResult;\n      } catch {\n        // try next provider\n      }\n    }\n  } catch {\n    // provider manager unavailable\n  }\n\n  // All providers failed\n  return {\n    verdict: 'FAIL',\n    overall_score: 0,\n    rubric: config.rubric,\n    scores: dimensions.map((d) => ({ dimension: d, score: 0, rationale: 'No LLM provider available.' })),\n    summary: 'No LLM provider available to run judge.',\n    provider: undefined,\n  };\n}\n\nasync function runRegressionComparison(\n  currentOutput: string,\n  judgeConfig: LLMJudgeConfig,\n  regressionConfig: RegressionSuiteConfig\n): Promise<RegressionDiff> {\n  // Score both outputs with the same rubric and return a delta\n  const [currentResult, referenceResult] = await Promise.all([\n    runLLMJudge(currentOutput, judgeConfig),\n    runLLMJudge(regressionConfig.reference_output, judgeConfig),\n  ]);\n\n  const delta = currentResult.overall_score - referenceResult.overall_score;\n  const verdict: RegressionDiff['verdict'] =\n    delta > 0.5 ? 'IMPROVEMENT' : delta < -0.5 ? 'REGRESSION' : 'NO_REGRESSION';\n\n  return {\n    reference_trace_id: regressionConfig.reference_trace_id,\n    verdict,\n    score_delta: Math.round(delta * 10) / 10,\n    summary:\n      `Current score ${currentResult.overall_score.toFixed(1)} vs reference ${referenceResult.overall_score.toFixed(1)} ` +\n      `(Δ${delta >= 0 ? '+' : ''}${delta.toFixed(1)}) — ${verdict}.`,\n  };\n}\n\n/** Standalone execute_eval: judges any text output, no scene code required */\nasync function runExecuteEval(args: Record<string, unknown>): Promise<HolotestResult> {\n  const output = args.output as string;\n  const rubric = args.rubric as string;\n  const dimensions = (args.scoring_dimensions as string[] | undefined) ?? DEFAULT_JUDGE_DIMENSIONS;\n  const model = args.model as string | undefined;\n  const referenceOutput = args.reference_output as string | undefined;\n  const referenceTraceId = args.reference_trace_id as string | undefined;\n\n  const judgeConfig: LLMJudgeConfig = { rubric, scoring_dimensions: dimensions, model };\n  const judgeResult = await runLLMJudge(output, judgeConfig);\n\n  const regressionDiff =\n    referenceOutput != null\n      ? await runRegressionComparison(output, judgeConfig, {\n          reference_output: referenceOutput,\n          reference_trace_id: referenceTraceId,\n        })\n      : undefined;\n\n  const passed = judgeResult.verdict === 'PASS';\n  return {\n    tool_name: 'execute_eval',\n    status: passed ? 'passed' : 'failed',\n    summary: `execute_eval: ${judgeResult.verdict} (score ${judgeResult.overall_score.toFixed(1)}/10) — ${judgeResult.summary}`,\n    tests: [\n      {\n        name: '[execute_eval] rubric evaluation',\n        status: passed ? 'passed' : 'failed',\n        duration_ms: 0,\n      },\n    ],\n    judge_result: judgeResult,\n    regression_diff: regressionDiff,\n  };\n}\n","/**\n * MCP Refactor & CodeGen Tools for HoloScript\n *\n * Phase 10: Autonomous Refactoring & CodeGen Integration\n *\n * Bridges the gap between diagnosis (holo_self_diagnose) and\n * code mutation (holo_write_file/holo_edit_file) by providing:\n *\n * - holo_generate_refactor_plan: Graph-context-informed refactoring plans\n * - holo_scaffold_code: Convention-aware code generation\n *\n * Pipeline position:\n *   ABSORB → DIAGNOSE → **PLAN/SCAFFOLD** → WRITE/EDIT → VALIDATE → COMMIT\n */\n\nimport { Tool } from '@modelcontextprotocol/sdk/types.js';\nimport * as fs from 'fs';\nimport * as path from 'path';\n\n// =============================================================================\n// TOOL DEFINITIONS\n// =============================================================================\n\nexport const refactorCodegenTools: Tool[] = [\n  {\n    name: 'holo_generate_refactor_plan',\n    description:\n      'Generate a concrete, graph-informed refactoring plan for a target symbol, file, or community. ' +\n      'Uses the absorbed codebase graph to understand callers/callees, community boundaries, and impact radius. ' +\n      'Returns a step-by-step plan with affected files, risk score, and detected codebase patterns. ' +\n      'Requires a prior holo_absorb_repo call.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        target: {\n          type: 'string',\n          description:\n            'Symbol name, file path, or community ID to refactor. ' +\n            'Examples: \"UserService\", \"src/auth/handler.ts\", \"community:3\"',\n        },\n        goal: {\n          type: 'string',\n          enum: [\n            'extract_interface',\n            'reduce_coupling',\n            'add_tests',\n            'improve_docs',\n            'split_module',\n            'inline_module',\n            'extract_function',\n          ],\n          description: 'The refactoring goal. Determines the plan template and risk model.',\n        },\n        scope: {\n          type: 'number',\n          description:\n            'Maximum number of files the plan should touch. Defaults to 10. ' +\n            'Lower values produce safer, more focused plans.',\n        },\n      },\n      required: ['target', 'goal'],\n    },\n  },\n  {\n    name: 'holo_scaffold_code',\n    description:\n      'Generate a code scaffold (test, interface, module, trait, component) that follows ' +\n      'the naming and style conventions detected in the absorbed codebase. ' +\n      'Analyzes existing files in the target directory for patterns. ' +\n      'Optionally pulls context from a specific symbol in the knowledge graph.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        type: {\n          type: 'string',\n          enum: ['test', 'interface', 'module', 'trait', 'component'],\n          description: 'Type of scaffold to generate.',\n        },\n        name: {\n          type: 'string',\n          description: 'Name for the new artifact (e.g., \"UserService\", \"PaymentProcessor\").',\n        },\n        targetDir: {\n          type: 'string',\n          description: 'Absolute path to the directory where the scaffold will be placed.',\n        },\n        context: {\n          type: 'string',\n          description:\n            'Optional symbol name or file path to scaffold from. ' +\n            'For tests: the symbol to test. For interfaces: the class to extract from.',\n        },\n        language: {\n          type: 'string',\n          description:\n            'Target language. Auto-detected from targetDir if omitted. ' +\n            'Supports: typescript, javascript, holoscript',\n        },\n      },\n      required: ['type', 'name', 'targetDir'],\n    },\n  },\n];\n\n// =============================================================================\n// HANDLER\n// =============================================================================\n\nexport async function handleRefactorCodegenTool(\n  name: string,\n  args: Record<string, unknown>\n): Promise<unknown | null> {\n  switch (name) {\n    case 'holo_generate_refactor_plan':\n      return handleGenerateRefactorPlan(args);\n    case 'holo_scaffold_code':\n      return handleScaffoldCode(args);\n    default:\n      return null;\n  }\n}\n\n// =============================================================================\n// REFACTOR PLAN GENERATOR\n// =============================================================================\n\ninterface RefactorStep {\n  order: number;\n  action: string;\n  file: string;\n  description: string;\n  risk: 'low' | 'medium' | 'high';\n}\n\ninterface RefactorPlan {\n  target: string;\n  goal: string;\n  steps: RefactorStep[];\n  affectedFiles: string[];\n  riskScore: number;\n  codebasePatterns: string[];\n  rollbackStrategy: string;\n  estimatedImpact: string;\n}\n\nasync function handleGenerateRefactorPlan(args: Record<string, unknown>): Promise<unknown> {\n  const target = args.target as string;\n  const goal = args.goal as string;\n  const scope = (args.scope as number) ?? 10;\n\n  if (!target || !goal) {\n    return { error: 'Both target and goal are required.' };\n  }\n\n  // Import graph-rag-tools to check readiness\n  const { isGraphRAGReady } = await import('@holoscript/absorb-service/mcp');\n  if (!isGraphRAGReady()) {\n    const { ABSORB_GRAPH_RAG_ENGINE_ERROR, ABSORB_HOLO_ABSORB_REPO_HINT } =\n      await import('@holoscript/absorb-service/mcp');\n    return {\n      error: ABSORB_GRAPH_RAG_ENGINE_ERROR,\n      hint: ABSORB_HOLO_ABSORB_REPO_HINT,\n    };\n  }\n\n  const { handleGraphRagTool } = await import('@holoscript/absorb-service/mcp');\n\n  // 1. Gather context about the target from the graph\n  const contextResult = (await handleGraphRagTool('holo_ask_codebase', {\n    question: `Describe the symbol or module \"${target}\": what it does, its callers, callees, and community. List its dependencies and dependents.`,\n    topK: 15,\n  })) as Record<string, unknown> | null;\n\n  // 2. Find similar patterns in the codebase (for convention matching)\n  const patternResult = (await handleGraphRagTool('holo_semantic_search', {\n    query: `${goal.replace(/_/g, ' ')} pattern similar to ${target}`,\n    topK: 5,\n  })) as Record<string, unknown> | null;\n\n  // 3. Build the plan based on goal type\n  const context = contextResult as Record<string, unknown>;\n  const patterns = patternResult as Record<string, unknown>;\n\n  const contextEntries = (context?.context ?? []) as Array<Record<string, unknown>>;\n  const patternEntries = (patterns?.results ?? []) as Array<Record<string, unknown>>;\n\n  // Extract affected files from context\n  const affectedFiles = new Set<string>();\n  for (const entry of contextEntries) {\n    const filePath = entry?.file as string | undefined;\n    if (filePath) affectedFiles.add(filePath);\n  }\n\n  // Detect codebase conventions\n  const codebasePatterns: string[] = [];\n  for (const p of patternEntries.slice(0, 3)) {\n    if (p?.name && p?.type) {\n      codebasePatterns.push(\n        `${String(p.type)} \"${String(p.name)}\" at ${String(p.file)}:${String(p.line)}`\n      );\n    }\n  }\n\n  // Generate steps based on goal\n  const steps = generateStepsForGoal(\n    goal,\n    target,\n    contextEntries,\n    Array.from(affectedFiles).slice(0, scope)\n  );\n\n  // Calculate risk score (0-1)\n  const riskScore = calculateRiskScore(goal, contextEntries, affectedFiles.size);\n\n  const plan: RefactorPlan = {\n    target,\n    goal,\n    steps,\n    affectedFiles: Array.from(affectedFiles).slice(0, scope),\n    riskScore: Math.round(riskScore * 100) / 100,\n    codebasePatterns,\n    rollbackStrategy: `git stash or git revert. ${affectedFiles.size} file(s) would be modified.`,\n    estimatedImpact: `${affectedFiles.size} files, ${contextEntries.length} symbols in blast radius`,\n  };\n\n  return plan;\n}\n\nfunction generateStepsForGoal(\n  goal: string,\n  target: string,\n  contextEntries: Array<Record<string, unknown>>,\n  affectedFiles: string[]\n): RefactorStep[] {\n  const steps: RefactorStep[] = [];\n  let order = 1;\n\n  switch (goal) {\n    case 'extract_interface': {\n      const targetFile = affectedFiles[0] ?? `${target}.ts`;\n      steps.push(\n        {\n          order: order++,\n          action: 'create',\n          file: targetFile.replace(/\\.ts$/, '.interface.ts'),\n          description: `Extract public method signatures from ${target} into a new interface I${target}`,\n          risk: 'low',\n        },\n        {\n          order: order++,\n          action: 'modify',\n          file: targetFile,\n          description: `Make ${target} implement I${target}. Update imports.`,\n          risk: 'low',\n        }\n      );\n      // Add steps for each consumer\n      for (const file of affectedFiles.slice(1, 5)) {\n        steps.push({\n          order: order++,\n          action: 'modify',\n          file,\n          description: `Update imports to reference I${target} instead of concrete class`,\n          risk: 'medium',\n        });\n      }\n      break;\n    }\n\n    case 'reduce_coupling': {\n      steps.push({\n        order: order++,\n        action: 'analyze',\n        file: affectedFiles[0] ?? target,\n        description: `Identify tightly coupled dependencies in ${target}. Look for direct instantiation, circular imports, and shared mutable state.`,\n        risk: 'low',\n      });\n      // Group by community to find cross-boundary dependencies\n      const crossBoundaryFiles = affectedFiles.filter(\n        (f) => !f.includes(path.dirname(affectedFiles[0] ?? ''))\n      );\n      if (crossBoundaryFiles.length > 0) {\n        steps.push({\n          order: order++,\n          action: 'create',\n          file: path.join(path.dirname(affectedFiles[0] ?? '.'), 'types.ts'),\n          description: 'Create shared types/interfaces file to break circular dependencies',\n          risk: 'low',\n        });\n      }\n      for (const file of affectedFiles.slice(0, 5)) {\n        steps.push({\n          order: order++,\n          action: 'modify',\n          file,\n          description: `Inject dependencies via constructor/parameters instead of direct import`,\n          risk: 'medium',\n        });\n      }\n      break;\n    }\n\n    case 'add_tests': {\n      const testDir = affectedFiles[0]\n        ? path.join(path.dirname(affectedFiles[0]), '__tests__')\n        : '__tests__';\n      steps.push(\n        {\n          order: order++,\n          action: 'create',\n          file: path.join(testDir, `${target}.test.ts`),\n          description: `Create test file for ${target} covering public API surface`,\n          risk: 'low',\n        },\n        {\n          order: order++,\n          action: 'create',\n          file: path.join(testDir, `${target}.test.ts`),\n          description: `Write tests for each public method. Prioritize methods with highest caller count.`,\n          risk: 'low',\n        }\n      );\n      // Add mock setup if there are many dependencies\n      if (contextEntries.length > 3) {\n        steps.push({\n          order: order++,\n          action: 'create',\n          file: path.join(testDir, `__mocks__`, `${target}.mock.ts`),\n          description: `Create mock/stub for ${target}'s dependencies (${contextEntries.length} symbols in context)`,\n          risk: 'low',\n        });\n      }\n      break;\n    }\n\n    case 'improve_docs': {\n      for (const entry of contextEntries.slice(0, 5)) {\n        steps.push({\n          order: order++,\n          action: 'modify',\n          file: String(entry?.file ?? target),\n          description: `Add JSDoc to ${String(entry?.name ?? target)}: @param, @returns, @example, @throws`,\n          risk: 'low',\n        });\n      }\n      steps.push({\n        order: order++,\n        action: 'create',\n        file: path.join(path.dirname(affectedFiles[0] ?? '.'), 'README.md'),\n        description: `Create or update module README with architecture overview and usage examples`,\n        risk: 'low',\n      });\n      break;\n    }\n\n    case 'split_module': {\n      const targetFile = affectedFiles[0] ?? target;\n      const dir = path.dirname(targetFile);\n      steps.push(\n        {\n          order: order++,\n          action: 'analyze',\n          file: targetFile,\n          description: `Identify cohesive sub-groups within ${target} using community detection. Target: each sub-group becomes its own file.`,\n          risk: 'low',\n        },\n        {\n          order: order++,\n          action: 'create',\n          file: path.join(dir, 'index.ts'),\n          description: 'Create barrel export file to maintain backward compatibility',\n          risk: 'low',\n        }\n      );\n      // Suggest up to 3 sub-modules based on context\n      const uniqueTypes = new Set(contextEntries.map((e) => String(e?.type ?? '')).filter(Boolean));\n      for (const symbolType of Array.from(uniqueTypes).slice(0, 3)) {\n        steps.push({\n          order: order++,\n          action: 'create',\n          file: path.join(dir, `${target}.${symbolType}s.ts`),\n          description: `Extract all ${symbolType} symbols into dedicated file`,\n          risk: 'medium',\n        });\n      }\n      break;\n    }\n\n    case 'inline_module': {\n      steps.push(\n        {\n          order: order++,\n          action: 'modify',\n          file: affectedFiles[0] ?? target,\n          description: `Inline the contents of ${target} into its primary consumer`,\n          risk: 'medium',\n        },\n        {\n          order: order++,\n          action: 'delete',\n          file: affectedFiles[0] ?? target,\n          description: `Remove the now-empty module file`,\n          risk: 'high',\n        }\n      );\n      for (const file of affectedFiles.slice(1, 5)) {\n        steps.push({\n          order: order++,\n          action: 'modify',\n          file,\n          description: `Update imports from ${target} to point to the inlined location`,\n          risk: 'medium',\n        });\n      }\n      break;\n    }\n\n    case 'extract_function': {\n      steps.push(\n        {\n          order: order++,\n          action: 'analyze',\n          file: affectedFiles[0] ?? target,\n          description: `Identify repeated logic or long methods in ${target} suitable for extraction`,\n          risk: 'low',\n        },\n        {\n          order: order++,\n          action: 'modify',\n          file: affectedFiles[0] ?? target,\n          description: `Extract identified logic into named helper function(s) with explicit parameters`,\n          risk: 'medium',\n        }\n      );\n      break;\n    }\n\n    default:\n      steps.push({\n        order: 1,\n        action: 'analyze',\n        file: affectedFiles[0] ?? target,\n        description: `Analyze ${target} for ${goal} opportunities.`,\n        risk: 'low',\n      });\n  }\n\n  return steps;\n}\n\nfunction calculateRiskScore(\n  goal: string,\n  contextEntries: Array<Record<string, unknown>>,\n  affectedFileCount: number\n): number {\n  // Base risk by goal type\n  const goalRisk: Record<string, number> = {\n    extract_interface: 0.2,\n    reduce_coupling: 0.5,\n    add_tests: 0.1,\n    improve_docs: 0.05,\n    split_module: 0.6,\n    inline_module: 0.7,\n    extract_function: 0.3,\n  };\n  const base = goalRisk[goal] ?? 0.3;\n\n  // Scale by blast radius\n  const blastFactor = Math.min(1, affectedFileCount / 20);\n\n  // Scale by coupling density\n  const callerCount = contextEntries.reduce((sum, e) => {\n    const callers = e?.callers as unknown[] | undefined;\n    return sum + (callers?.length ?? 0);\n  }, 0);\n  const couplingFactor = Math.min(1, callerCount / 50);\n\n  return Math.min(1, base * 0.5 + blastFactor * 0.3 + couplingFactor * 0.2);\n}\n\n// =============================================================================\n// CODE SCAFFOLD GENERATOR\n// =============================================================================\n\ninterface ConventionProfile {\n  indentation: string;\n  semicolons: boolean;\n  singleQuotes: boolean;\n  trailingComma: boolean;\n  hasJSDoc: boolean;\n  importStyle: 'esm' | 'commonjs' | 'mixed';\n  testFramework: string;\n  fileNaming: 'camelCase' | 'PascalCase' | 'kebab-case' | 'snake_case';\n}\n\nasync function handleScaffoldCode(args: Record<string, unknown>): Promise<unknown> {\n  const scaffoldType = args.type as string;\n  const name = args.name as string;\n  const targetDir = args.targetDir as string;\n  const context = args.context as string | undefined;\n  const language = (args.language as string) ?? detectLanguageFromDir(targetDir);\n\n  if (!scaffoldType || !name || !targetDir) {\n    return { error: 'type, name, and targetDir are required.' };\n  }\n\n  // 1. Detect conventions from existing files in the target directory\n  const conventions = detectConventions(targetDir);\n\n  // 2. Optionally pull context from Graph RAG\n  let symbolContext: Record<string, unknown> | null = null;\n  if (context) {\n    try {\n      const { isGraphRAGReady, handleGraphRagTool } =\n        await import('@holoscript/absorb-service/mcp');\n      if (isGraphRAGReady()) {\n        symbolContext = (await handleGraphRagTool('holo_semantic_search', {\n          query: context,\n          topK: 3,\n        })) as Record<string, unknown>;\n      }\n    } catch {\n      // Graph RAG not available — proceed without context\n    }\n  }\n\n  // 3. Generate the scaffold\n  const { content, filePath } = generateScaffold(\n    scaffoldType,\n    name,\n    targetDir,\n    language,\n    conventions,\n    symbolContext\n  );\n\n  return {\n    filePath,\n    content,\n    language,\n    conventions: {\n      indentation: conventions.indentation === '  ' ? '2 spaces' : '4 spaces',\n      semicolons: conventions.semicolons,\n      quotes: conventions.singleQuotes ? 'single' : 'double',\n      importStyle: conventions.importStyle,\n      testFramework: conventions.testFramework,\n    },\n    hint: `Use holo_write_file to save this scaffold to ${filePath}`,\n  };\n}\n\nfunction detectLanguageFromDir(dir: string): string {\n  if (!fs.existsSync(dir)) return 'typescript';\n  try {\n    const files = fs.readdirSync(dir);\n    if (files.some((f) => f.endsWith('.ts') || f.endsWith('.tsx'))) return 'typescript';\n    if (files.some((f) => f.endsWith('.js') || f.endsWith('.jsx'))) return 'javascript';\n    if (files.some((f) => f.endsWith('.holo') || f.endsWith('.hsplus'))) return 'holoscript';\n  } catch {\n    // Can't read directory\n  }\n  return 'typescript';\n}\n\nfunction detectConventions(dir: string): ConventionProfile {\n  const defaults: ConventionProfile = {\n    indentation: '  ',\n    semicolons: true,\n    singleQuotes: true,\n    trailingComma: true,\n    hasJSDoc: false,\n    importStyle: 'esm',\n    testFramework: 'vitest',\n    fileNaming: 'PascalCase',\n  };\n\n  if (!fs.existsSync(dir)) return defaults;\n\n  try {\n    const files = fs\n      .readdirSync(dir)\n      .filter(\n        (f) => f.endsWith('.ts') || f.endsWith('.js') || f.endsWith('.tsx') || f.endsWith('.jsx')\n      );\n\n    if (files.length === 0) return defaults;\n\n    // Sample up to 3 files for convention detection\n    const sampleFiles = files.slice(0, 3);\n    let tabCount = 0;\n    let spaceCount = 0;\n    let semiCount = 0;\n    let noSemiCount = 0;\n    let singleQuoteCount = 0;\n    let doubleQuoteCount = 0;\n    let jsdocCount = 0;\n    let esmImportCount = 0;\n    let cjsRequireCount = 0;\n\n    for (const file of sampleFiles) {\n      try {\n        const content = fs.readFileSync(path.join(dir, file), 'utf-8');\n        const lines = content.split('\\n');\n\n        for (const line of lines.slice(0, 50)) {\n          // Indentation\n          if (line.startsWith('\\t')) tabCount++;\n          else if (line.startsWith('  ')) spaceCount++;\n\n          // Semicolons\n          if (line.trimEnd().endsWith(';')) semiCount++;\n          else if (\n            line.trim().length > 0 &&\n            !line.trim().startsWith('//') &&\n            !line.trim().startsWith('*')\n          )\n            noSemiCount++;\n\n          // Quotes\n          if (line.includes(\"'\")) singleQuoteCount++;\n          if (line.includes('\"')) doubleQuoteCount++;\n\n          // JSDoc\n          if (line.includes('/**')) jsdocCount++;\n\n          // Import style\n          if (line.startsWith('import ')) esmImportCount++;\n          if (line.includes('require(')) cjsRequireCount++;\n        }\n      } catch {\n        // Skip unreadable files\n      }\n    }\n\n    // File naming convention\n    let fileNaming: ConventionProfile['fileNaming'] = 'PascalCase';\n    if (files.some((f) => f.includes('-'))) fileNaming = 'kebab-case';\n    else if (files.some((f) => f.includes('_'))) fileNaming = 'snake_case';\n    else if (files.some((f) => /^[a-z]/.test(f))) fileNaming = 'camelCase';\n\n    return {\n      indentation: tabCount > spaceCount ? '\\t' : '  ',\n      semicolons: semiCount > noSemiCount,\n      singleQuotes: singleQuoteCount > doubleQuoteCount,\n      trailingComma: true, // hard to detect reliably\n      hasJSDoc: jsdocCount > 0,\n      importStyle: cjsRequireCount > esmImportCount ? 'commonjs' : 'esm',\n      testFramework:\n        fs.existsSync(path.join(dir, '..', 'vitest.config.ts')) ||\n        fs.existsSync(path.join(dir, '..', '..', 'vitest.config.ts'))\n          ? 'vitest'\n          : 'jest',\n      fileNaming,\n    };\n  } catch {\n    return defaults;\n  }\n}\n\nfunction generateScaffold(\n  scaffoldType: string,\n  name: string,\n  targetDir: string,\n  language: string,\n  conventions: ConventionProfile,\n  symbolContext: Record<string, unknown> | null\n): { content: string; filePath: string } {\n  const q = conventions.singleQuotes ? \"'\" : '\"';\n  const semi = conventions.semicolons ? ';' : '';\n  const ind = conventions.indentation;\n\n  // Extract context info for richer scaffolds\n  const contextSymbols = ((symbolContext as Record<string, unknown>)?.results ?? []) as Array<\n    Record<string, unknown>\n  >;\n  const contextHint: Record<string, unknown> | null =\n    contextSymbols.length > 0 ? contextSymbols[0] : null;\n\n  switch (scaffoldType) {\n    case 'test': {\n      const testFile =\n        conventions.fileNaming === 'kebab-case'\n          ? `${toKebabCase(name)}.test.ts`\n          : `${name}.test.ts`;\n      const filePath = path.join(targetDir, testFile);\n      const framework = conventions.testFramework;\n      const importLine =\n        framework === 'vitest'\n          ? `import { describe, it, expect, beforeEach } from ${q}vitest${q}${semi}`\n          : '';\n      const contextImport = contextHint\n        ? `import { ${String(contextHint.name)} } from ${q}./${contextHint.file ? path.basename(String(contextHint.file), '.ts') : name}${q}${semi}`\n        : `// import { ${name} } from ${q}./${name}${q}${semi}`;\n\n      const content = [\n        contextHint && conventions.hasJSDoc ? `/**\\n * Tests for ${name}\\n */` : '',\n        importLine,\n        contextImport,\n        '',\n        `describe(${q}${name}${q}, () => {`,\n        `${ind}// TODO: Add setup`,\n        '',\n        `${ind}describe(${q}initialization${q}, () => {`,\n        `${ind}${ind}it(${q}should create an instance${q}, () => {`,\n        `${ind}${ind}${ind}// Arrange`,\n        `${ind}${ind}${ind}// Act`,\n        `${ind}${ind}${ind}// Assert`,\n        `${ind}${ind}${ind}${semi}`,\n        `${ind}${ind}})${semi}`,\n        `${ind}})${semi}`,\n        '',\n        contextHint?.signature\n          ? [\n              `${ind}describe(${q}${contextHint.name}${q}, () => {`,\n              `${ind}${ind}it(${q}should handle valid input${q}, () => {`,\n              `${ind}${ind}${ind}// TODO: Test ${contextHint.signature}`,\n              `${ind}${ind}${ind}${semi}`,\n              `${ind}${ind}})${semi}`,\n              '',\n              `${ind}${ind}it(${q}should handle edge cases${q}, () => {`,\n              `${ind}${ind}${ind}// TODO: Test edge cases`,\n              `${ind}${ind}${ind}${semi}`,\n              `${ind}${ind}})${semi}`,\n              `${ind}})${semi}`,\n            ].join('\\n')\n          : '',\n        `})${semi}`,\n        '',\n      ]\n        .filter(Boolean)\n        .join('\\n');\n\n      return { content, filePath };\n    }\n\n    case 'interface': {\n      const fileName =\n        conventions.fileNaming === 'kebab-case'\n          ? `${toKebabCase(name)}.interface.ts`\n          : `${name}.interface.ts`;\n      const filePath = path.join(targetDir, fileName);\n\n      const methods: string[] = [];\n      for (const sym of contextSymbols.slice(0, 5)) {\n        if (sym?.signature) {\n          methods.push(`${ind}${sym.signature}${semi}`);\n        } else if (sym?.name) {\n          methods.push(`${ind}${sym.name}(...args: unknown[]): unknown${semi}`);\n        }\n      }\n      if (methods.length === 0) {\n        methods.push(`${ind}// TODO: Define interface methods`);\n      }\n\n      const content = [\n        conventions.hasJSDoc\n          ? `/**\\n * Interface for ${name}\\n * @description Extracted from concrete implementation\\n */`\n          : '',\n        `export interface I${name} {`,\n        ...methods,\n        `}`,\n        '',\n      ]\n        .filter(Boolean)\n        .join('\\n');\n\n      return { content, filePath };\n    }\n\n    case 'module': {\n      const fileName =\n        conventions.fileNaming === 'kebab-case' ? `${toKebabCase(name)}.ts` : `${name}.ts`;\n      const filePath = path.join(targetDir, fileName);\n\n      const content = [\n        conventions.hasJSDoc ? `/**\\n * ${name} Module\\n *\\n * @module ${name}\\n */` : '',\n        '',\n        `// =============================================================================`,\n        `// TYPES`,\n        `// =============================================================================`,\n        '',\n        `export interface ${name}Options {`,\n        `${ind}// TODO: Define options`,\n        `}`,\n        '',\n        `// =============================================================================`,\n        `// IMPLEMENTATION`,\n        `// =============================================================================`,\n        '',\n        `export class ${name} {`,\n        conventions.hasJSDoc ? `${ind}/** Create a new ${name} instance */` : '',\n        `${ind}constructor(private readonly options: ${name}Options = {}) {}`,\n        '',\n        conventions.hasJSDoc ? `${ind}/** Initialize the module */` : '',\n        `${ind}async initialize(): Promise<void> {`,\n        `${ind}${ind}// TODO: Implementation`,\n        `${ind}}`,\n        '',\n        conventions.hasJSDoc ? `${ind}/** Dispose resources */` : '',\n        `${ind}async dispose(): Promise<void> {`,\n        `${ind}${ind}// TODO: Cleanup`,\n        `${ind}}`,\n        `}`,\n        '',\n      ]\n        .filter(Boolean)\n        .join('\\n');\n\n      return { content, filePath };\n    }\n\n    case 'trait': {\n      const fileName = `${name.toLowerCase()}.holo`;\n      const filePath = path.join(targetDir, fileName);\n\n      const content = [\n        `// ${name} trait definition`,\n        `// Generated by HoloScript CodeGen`,\n        '',\n        `trait @${name} {`,\n        `  // Properties`,\n        `  enabled: true`,\n        '',\n        `  // Lifecycle hooks`,\n        `  on_init: {`,\n        `    // TODO: Initialize trait state`,\n        `  }`,\n        '',\n        `  on_update: {`,\n        `    // TODO: Per-frame update logic`,\n        `  }`,\n        '',\n        `  on_dispose: {`,\n        `    // TODO: Cleanup`,\n        `  }`,\n        `}`,\n        '',\n      ].join('\\n');\n\n      return { content, filePath };\n    }\n\n    case 'component': {\n      const fileName =\n        conventions.fileNaming === 'kebab-case'\n          ? `${toKebabCase(name)}.component.ts`\n          : `${name}Component.ts`;\n      const filePath = path.join(targetDir, fileName);\n\n      const content = [\n        conventions.hasJSDoc ? `/**\\n * ${name} Component\\n *\\n * @component\\n */` : '',\n        '',\n        `export interface ${name}Props {`,\n        `${ind}// TODO: Define props`,\n        `}`,\n        '',\n        `export class ${name}Component {`,\n        `${ind}private readonly props: ${name}Props${semi}`,\n        '',\n        `${ind}constructor(props: ${name}Props) {`,\n        `${ind}${ind}this.props = props${semi}`,\n        `${ind}}`,\n        '',\n        conventions.hasJSDoc ? `${ind}/** Mount the component */` : '',\n        `${ind}mount(): void {`,\n        `${ind}${ind}// TODO: Component mount logic`,\n        `${ind}}`,\n        '',\n        conventions.hasJSDoc ? `${ind}/** Unmount the component */` : '',\n        `${ind}unmount(): void {`,\n        `${ind}${ind}// TODO: Component teardown`,\n        `${ind}}`,\n        `}`,\n        '',\n      ]\n        .filter(Boolean)\n        .join('\\n');\n\n      return { content, filePath };\n    }\n\n    default:\n      return {\n        content: `// Unknown scaffold type: ${scaffoldType}\\n`,\n        filePath: path.join(targetDir, `${name}.ts`),\n      };\n  }\n}\n\n// =============================================================================\n// HELPERS\n// =============================================================================\n\nfunction toKebabCase(str: string): string {\n  return str\n    .replace(/([a-z])([A-Z])/g, '$1-$2')\n    .replace(/[\\s_]+/g, '-')\n    .toLowerCase();\n}\n","/**\n * MCP Critic Tools for HoloScript\n *\n * Provides structured, brutal-honest critique of code, architecture,\n * documentation, pitches, demos, and infrastructure. Uses an LLM-backed\n * pipeline with the critic skill protocol.\n *\n * Reference: ~/.claude/skills/critic/SKILL.md\n */\n\nimport { Tool } from '@modelcontextprotocol/sdk/types.js';\n\nexport const criticTools: Tool[] = [\n  {\n    name: 'holo_critic',\n    description:\n      'Brutal honest critic for the HoloScript ecosystem. ' +\n      'Takes code, architecture descriptions, pitch materials, demos, docs, or infrastructure configs ' +\n      'and returns a structured verdict (NOT_READY / FRAGILE / ADEQUATE / WOULD_LAND) ' +\n      'plus categorized findings (Critical / Serious / Annoying / Nitpick). ' +\n      'Every criticism includes what is wrong, why it matters, and what good looks like. ' +\n      'Use before shipping, presenting, or submitting to review.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        target: {\n          type: 'string',\n          description:\n            'What to critique. Builtin modes: file | pitch | demo | architecture | tests | docs | studio | absorb | holomesh | infra | full | code. ' +\n            'Any other string is treated as a file path and the file is read and critiqued.',\n        },\n        content: {\n          type: 'string',\n          description:\n            'The content to critique (code, text, architecture description, pitch text, etc.). ' +\n            'If target is a file path, this field is optional and the file content is read from disk.',\n        },\n        mode: {\n          type: 'string',\n          enum: ['code', 'pitch', 'full'],\n          description:\n            'Output format mode. code = VERDICT + Critical/Serious/Annoying/Nitpick sections. ' +\n            'pitch = VERDICT + challengeable lines + claims without evidence + skeptic view + what would make it undeniable. ' +\n            'full = runs all applicable critique dimensions and returns the union. Defaults to code.',\n        },\n        context: {\n          type: 'string',\n          description:\n            'Optional additional context (e.g. \"this is for a NeurIPS submission\", \"target audience is investors\", ' +\n            '\"ship deadline is Friday\").',\n        },\n      },\n      required: ['target'],\n    },\n  },\n];\n","/**\n * MCP Founder Tools for HoloScript\n *\n * Provides structured founder decision-proxy rulings for agents.\n * Wraps the /founder skill protocol into a programmatic MCP interface.\n *\n * Reference: ~/.claude/skills/founder/SKILL.md\n */\n\nimport { Tool } from '@modelcontextprotocol/sdk/types.js';\n\nexport const founderTools: Tool[] = [\n  {\n    name: 'holo_founder',\n    description:\n      'Founder decision proxy for the HoloScript / Infinitus ecosystem. ' +\n      'Takes an agent question and returns a structured ruling with authority layer, ' +\n      'citation, and recommended action — so the agent can proceed without stalling. ' +\n      'Use before: asking the founder, proposing a workaround/mock/fallback, ' +\n      'reaching for a local/dev service where production exists, descoping a gap, ' +\n      'or making editorial calls on the 17-paper program. ' +\n      'Returns: JSON with layer, ruling, citation, action, and optional gap.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        question: {\n          type: 'string',\n          description:\n            'The decision to resolve. Examples: ' +\n            '\"Should we ship X without tests?\" | ' +\n            '\"Use absorb.holoscript.net or hit prod orchestrator?\" | ' +\n            '\"Can we descope the navmesh for this sprint?\" | ' +\n            '\"Which repo does this go in?\" | ' +\n            '\"Is this a bandaid or a proper fix?\"',\n        },\n        context: {\n          type: 'string',\n          description:\n            'Optional additional context (e.g., \"this is for a NeurIPS submission\", ' +\n            '\"target audience is investors\", \"ship deadline is Friday\").',\n        },\n        mode: {\n          type: 'string',\n          enum: ['single', 'batch'],\n          description:\n            'single = one question. batch = multiple questions separated by \" // \" ' +\n            '(space-slash-slash-space). Defaults to single.',\n        },\n        explain: {\n          type: 'boolean',\n          description:\n            'If true, returns the full reasoning chain (layer + citation + dynamic notes). ' +\n            'If false (default), returns a concise ruling suitable for silent internalization.',\n        },\n      },\n      required: ['question'],\n    },\n  },\n];\n","/**\n * MCP Premortem Tools for HoloScript\n *\n * Pre-mortem analysis for any plan, feature, deployment, or architectural decision.\n * Travels 6 months into the future and reports back how your next move failed.\n * Surfaces failure narratives, early warning signs, hidden assumptions, and a revised plan.\n *\n * Reference: ~/.claude/skills/premortem/SKILL.md\n */\n\nimport { Tool } from '@modelcontextprotocol/sdk/types.js';\n\nexport const premortemTools: Tool[] = [\n  {\n    name: 'holo_premortem',\n    description:\n      'Pre-mortem analysis: travels 6 months forward and reports how the plan failed. ' +\n      'Returns verdict (SOUND / PROCEED_WITH_CAUTION / RESTRUCTURE_REQUIRED / FATAL_FLAW), ' +\n      'failure story, warning signs, hidden assumption, revised plan, and irreducible risks. ' +\n      'Use before shipping, architecture commits, or any expensive move.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        target: {\n          type: 'string',\n          description:\n            'What to pre-mortem. Builtin: \"this\" reads the current mode directive or recent git context. ' +\n            'Any other string is treated as a file path if it exists on disk; otherwise it is used as the plan text directly.',\n        },\n        content: {\n          type: 'string',\n          description:\n            'Optional explicit plan content. When provided, this overrides the resolved target content.',\n        },\n        context: {\n          type: 'string',\n          description:\n            'Optional additional context (e.g. \"ship deadline is Friday\", \"target audience is investors\", ' +\n            '\"this is for a NeurIPS submission\").',\n        },\n      },\n      required: ['target'],\n    },\n  },\n];\n","/**\n * MCP Secrets Broker Tools\n *\n * Wraps `@holoscript/secrets-broker` into MCP tool definitions so any AI agent\n * can issue, resolve, and revoke brokered secret grants through the protocol.\n *\n * Tools:\n *   - holo_secrets_grant   : Issue a brokered secret handle (no plaintext returned)\n *   - holo_secrets_resolve : Check whether a lease permits a secret ref\n *   - holo_secrets_revoke  : Revoke an active lease\n *\n * @module mcp-server/secrets-broker-tools\n */\n\nimport { Tool } from '@modelcontextprotocol/sdk/types.js';\n\nexport const secretsBrokerTools: Tool[] = [\n  {\n    name: 'holo_secrets_grant',\n    description:\n      'Issue a brokered secret grant receipt. The agent receives a handle (not the plaintext) ' +\n      'scoped to a namespace, secret ref, and capability. The grant is time-bounded and auditable. ' +\n      'Returns a signed receipt with grantId, expiry, and receiptHash. NEVER returns secret values.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        namespaceId: {\n          type: 'string',\n          description: 'Namespace that scopes the secret (workspace, team, or project id)',\n        },\n        agentId: {\n          type: 'string',\n          description: 'Registered agent identity (x402 seat, HoloMesh agentId, etc.)',\n        },\n        secretRef: {\n          type: 'string',\n          description:\n            'Canonical secret reference, e.g. secret://namespace/{id}/holoscript/orchestrator/api-key',\n        },\n        capabilityRef: {\n          type: 'string',\n          description: 'Daemon capability being requested, e.g. cap://daemon/secrets/broker-only',\n        },\n        purpose: {\n          type: 'string',\n          description: 'Human-readable purpose for audit and compliance',\n        },\n        ttlSeconds: {\n          type: 'number',\n          description: 'Time-to-live in seconds (default 900, max 3600)',\n        },\n        policy: {\n          type: 'object',\n          description: 'Optional HoloDoor policy gate to enforce before issuance',\n          properties: {\n            secretGrants: {\n              type: 'object',\n              properties: {\n                allowedSecretRefPrefixes: { type: 'array', items: { type: 'string' } },\n                blockedSecretRefPrefixes: { type: 'array', items: { type: 'string' } },\n                allowedCapabilityRefs: { type: 'array', items: { type: 'string' } },\n                blockedCapabilityRefs: { type: 'array', items: { type: 'string' } },\n                allowedAgentIds: { type: 'array', items: { type: 'string' } },\n                blockedAgentIds: { type: 'array', items: { type: 'string' } },\n                maxTtlSeconds: { type: 'number' },\n                requirePurpose: { type: 'boolean' },\n              },\n            },\n            enforcement: {\n              type: 'object',\n              properties: {\n                onViolation: { type: 'string', enum: ['warn', 'block'] },\n              },\n            },\n          },\n        },\n      },\n      required: ['namespaceId', 'agentId', 'secretRef', 'capabilityRef', 'purpose'],\n    },\n  },\n  {\n    name: 'holo_secrets_resolve',\n    description:\n      'Resolve whether an active lease permits reading a secret ref. ' +\n      'Returns { ok, reason? } — the actual secret value is fetched by a separate secret-store adapter.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        leaseId: {\n          type: 'string',\n          description: 'Lease id returned by holo_secrets_grant or the lease adapter',\n        },\n        agentId: {\n          type: 'string',\n          description: 'Agent id that holds the lease',\n        },\n        secretRef: {\n          type: 'string',\n          description: 'Canonical secret reference to resolve',\n        },\n      },\n      required: ['leaseId', 'agentId', 'secretRef'],\n    },\n  },\n  {\n    name: 'holo_secrets_revoke',\n    description:\n      'Revoke an active lease early (task done, agent compromise, rotation, etc.). ' +\n      'Idempotent on already-revoked leases.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        leaseId: {\n          type: 'string',\n          description: 'Lease id to revoke',\n        },\n        reason: {\n          type: 'string',\n          enum: [\n            'task_completed',\n            'task_released',\n            'agent_compromise',\n            'expired_sweep',\n            'rotation',\n            'manual',\n          ],\n          description: 'Reason for revocation',\n        },\n        by: {\n          type: 'string',\n          description: 'Agent id or system identifier performing the revocation',\n        },\n      },\n      required: ['leaseId', 'reason', 'by'],\n    },\n  },\n];\n","/**\n * HoloTunnel MCP Tools\n *\n * Expose HoloTunnel (sovereign ngrok replacement) as MCP tools so any agent\n * can open a local-to-cloud tunnel without CLI knowledge.\n *\n * Tool: holo_tunnel_create\n *   - Opens a tunnel from a local port to a public URL via the MCP relay.\n *   - Returns the public URL and tunnel ID.\n *   - Tunnel is kept alive for the duration of the MCP session (or until\n *     holo_tunnel_close is called).\n *\n * Tool: holo_tunnel_close\n *   - Closes a previously opened tunnel by tunnel ID.\n *\n * Source: packages/hololand-platform/src/holo-tunnel/index.ts\n * Task: task_1779158644652_avm8 — [WIRE] Expose HoloTunnel as MCP tool\n */\n\nimport { Tool } from '@modelcontextprotocol/sdk/types.js';\n\ninterface HoloTunnelSharePacket {\n  schemaVersion: 'holoscript.holotunnel.share-packet.v1';\n  worldId: string;\n  sessionName: string;\n  stableUrl: string;\n  directUrl: string;\n  sourceRef?: string;\n  createdBy: 'studio' | 'agent' | 'cli' | 'holoscript';\n  expiresAt?: string;\n}\n\ninterface HoloTunnelToolHandle {\n  url: string;\n  liveUrl: string;\n  tunnelId: string;\n  relayBase: string;\n  sharePacket: HoloTunnelSharePacket;\n  close: () => void;\n}\n\n// ---------------------------------------------------------------------------\n// In-process tunnel registry (MCP is single-process per server instance)\n// ---------------------------------------------------------------------------\nconst activeTunnels = new Map<\n  string,\n  {\n    url: string;\n    liveUrl: string;\n    relayBase: string;\n    port: number;\n    localHost: string;\n    sharePacket: HoloTunnelSharePacket;\n    close: () => void;\n  }\n>();\n\n// Lazy-import startHoloTunnel so the server doesn't fail if the dependency\n// is tree-shaken or the module is unavailable in the current build.\nlet startHoloTunnelFn: typeof import('@holoscript/hololand-platform').startHoloTunnel | null = null;\n\nasync function getStartHoloTunnel() {\n  if (!startHoloTunnelFn) {\n    const mod = await import('@holoscript/hololand-platform');\n    startHoloTunnelFn = mod.startHoloTunnel;\n  }\n  return startHoloTunnelFn!;\n}\n\nexport function __setStartHoloTunnelForTests(\n  fn: typeof import('@holoscript/hololand-platform').startHoloTunnel | null\n): void {\n  startHoloTunnelFn = fn;\n}\n\nexport function __resetHoloTunnelToolsForTests(): void {\n  activeTunnels.clear();\n  startHoloTunnelFn = null;\n}\n\n// ---------------------------------------------------------------------------\n// Tool definitions\n// ---------------------------------------------------------------------------\nexport const holoTunnelTools: Tool[] = [\n  {\n    name: 'holo_tunnel_create',\n    description: `Open a local-to-cloud tunnel via the HoloMesh relay. Given a local port, opens a WebSocket tunnel and returns a public HTTPS URL forwarding to localhost:<port>. Sovereign ngrok replacement — no third-party dependency. Returns { url, liveUrl, tunnelId, sharePacket }.`,\n    inputSchema: {\n      type: 'object' as const,\n      properties: {\n        port: {\n          type: 'number',\n          description: 'Local port to forward traffic to (e.g. 3000 for dev server)',\n        },\n        relayBase: {\n          type: 'string',\n          description:\n            'Optional relay URL base. Defaults to the production MCP relay. Only override for local testing.',\n        },\n        localHost: {\n          type: 'string',\n          description:\n            'Local hostname. Defaults to \"localhost\". Use \"0.0.0.0\" to listen on all interfaces.',\n        },\n        clientToken: {\n          type: 'string',\n          description:\n            'Optional relay client token. Defaults to HOLOTUNNEL_CLIENT_TOKEN. Never returned in tool output.',\n        },\n        worldId: {\n          type: 'string',\n          description: 'Optional HoloLand world/session identifier for the share packet.',\n        },\n        sessionName: {\n          type: 'string',\n          description: 'Optional human-readable session name for the share packet.',\n        },\n        sourceRef: {\n          type: 'string',\n          description: 'Optional source file/path backing the live preview.',\n        },\n        createdBy: {\n          type: 'string',\n          enum: ['studio', 'agent', 'cli', 'holoscript'],\n          description: 'Optional share-packet producer label. Defaults to \"agent\".',\n        },\n        expiresAt: {\n          type: 'string',\n          description: 'Optional ISO expiry timestamp to pass through to HoloLand.',\n        },\n      },\n      required: ['port'],\n    },\n  },\n  {\n    name: 'holo_tunnel_close',\n    description: `Close a previously opened HoloTunnel by tunnel ID.\n\nPass the tunnelId returned by holo_tunnel_create. Closes the WebSocket\nconnection and removes the tunnel from the registry.\n\nReturns: { closed: boolean, tunnelId: string }`,\n    inputSchema: {\n      type: 'object' as const,\n      properties: {\n        tunnelId: {\n          type: 'string',\n          description: 'The tunnelId returned by holo_tunnel_create',\n        },\n      },\n      required: ['tunnelId'],\n    },\n  },\n  {\n    name: 'holo_tunnel_status',\n    description: `List currently active HoloTunnel connections.\n\nReturns an array of active tunnels with their public URLs and local ports.\n\nReturns: { tunnels: Array<{ tunnelId: string, url: string }> }`,\n    inputSchema: {\n      type: 'object' as const,\n      properties: {},\n      required: [],\n    },\n  },\n];\n\nfunction optionalString(args: Record<string, unknown>, key: string): string | undefined {\n  return typeof args[key] === 'string' && args[key] ? String(args[key]) : undefined;\n}\n\n// ---------------------------------------------------------------------------\n// Tool handler\n// ---------------------------------------------------------------------------\nexport async function handleHoloTunnelTool(\n  name: string,\n  args: Record<string, unknown>\n): Promise<{ content: Array<{ type: 'text'; text: string }> }> {\n  switch (name) {\n    case 'holo_tunnel_create': {\n      const port = Number(args.port);\n      if (!port || port < 1 || port > 65535) {\n        return {\n          content: [\n            {\n              type: 'text',\n              text: JSON.stringify({\n                success: false,\n                error: `Invalid port: ${args.port}. Must be 1-65535.`,\n              }),\n            },\n          ],\n        };\n      }\n\n      try {\n        const startHoloTunnel = await getStartHoloTunnel();\n        const localHost = optionalString(args, 'localHost') ?? 'localhost';\n        const relayBase = optionalString(args, 'relayBase');\n        const clientToken = optionalString(args, 'clientToken');\n        const worldId = optionalString(args, 'worldId');\n        const sessionName = optionalString(args, 'sessionName');\n        const sourceRef = optionalString(args, 'sourceRef');\n        const createdBy = optionalString(args, 'createdBy');\n        const expiresAt = optionalString(args, 'expiresAt');\n        const result = (await startHoloTunnel({\n          localPort: port,\n          ...(relayBase ? { relayBase } : {}),\n          localHost,\n          ...(clientToken ? { clientToken } : {}),\n          ...(worldId ? { worldId } : {}),\n          ...(sessionName ? { sessionName } : {}),\n          ...(sourceRef ? { sourceRef } : {}),\n          ...(createdBy === 'studio' ||\n          createdBy === 'agent' ||\n          createdBy === 'cli' ||\n          createdBy === 'holoscript'\n            ? { createdBy }\n            : { createdBy: 'agent' as const }),\n          ...(expiresAt ? { expiresAt } : {}),\n        } as unknown as Parameters<typeof startHoloTunnel>[0])) as HoloTunnelToolHandle;\n\n        // Register the tunnel so it can be closed later\n        activeTunnels.set(result.tunnelId, {\n          url: result.url,\n          liveUrl: result.liveUrl,\n          relayBase: result.relayBase,\n          port,\n          localHost,\n          sharePacket: result.sharePacket,\n          close: result.close,\n        });\n\n        return {\n          content: [\n            {\n              type: 'text',\n              text: JSON.stringify({\n                success: true,\n                url: result.url,\n                liveUrl: result.liveUrl,\n                tunnelId: result.tunnelId,\n                port,\n                localHost,\n                relayBase: result.relayBase,\n                sharePacket: result.sharePacket,\n                message: `Tunnel active: ${result.url} → localhost:${port}`,\n              }),\n            },\n          ],\n        };\n      } catch (err) {\n        return {\n          content: [\n            {\n              type: 'text',\n              text: JSON.stringify({\n                success: false,\n                error: `Failed to create tunnel: ${err instanceof Error ? err.message : String(err)}`,\n              }),\n            },\n          ],\n        };\n      }\n    }\n\n    case 'holo_tunnel_close': {\n      const tunnelId = String(args.tunnelId);\n      const tunnel = activeTunnels.get(tunnelId);\n      if (!tunnel) {\n        return {\n          content: [\n            {\n              type: 'text',\n              text: JSON.stringify({\n                success: false,\n                error: `No active tunnel with ID: ${tunnelId}`,\n                activeTunnelIds: Array.from(activeTunnels.keys()),\n              }),\n            },\n          ],\n        };\n      }\n\n      try {\n        tunnel.close();\n        activeTunnels.delete(tunnelId);\n        return {\n          content: [\n            {\n              type: 'text',\n              text: JSON.stringify({ success: true, closed: true, tunnelId }),\n            },\n          ],\n        };\n      } catch (err) {\n        // Tunnel may already be closed (network disconnect, etc.)\n        activeTunnels.delete(tunnelId);\n        return {\n          content: [\n            {\n              type: 'text',\n              text: JSON.stringify({\n                success: true,\n                closed: true,\n                tunnelId,\n                warning: `Close threw: ${err instanceof Error ? err.message : String(err)}`,\n              }),\n            },\n          ],\n        };\n      }\n    }\n\n    case 'holo_tunnel_status': {\n      const tunnels = Array.from(activeTunnels.entries()).map(([id, t]) => ({\n        tunnelId: id,\n        url: t.url,\n        liveUrl: t.liveUrl,\n        relayBase: t.relayBase,\n        port: t.port,\n        localHost: t.localHost,\n        sharePacket: t.sharePacket,\n      }));\n      return {\n        content: [\n          {\n            type: 'text',\n            text: JSON.stringify({ success: true, tunnels, count: tunnels.length }),\n          },\n        ],\n      };\n    }\n\n    default:\n      return {\n        content: [\n          {\n            type: 'text',\n            text: JSON.stringify({ error: `Unknown holo_tunnel tool: ${name}` }),\n          },\n        ],\n      };\n  }\n}\n","/**\n * Memory MCP Tools — holo_memory_* surface\n *\n * Exposes a unified memory API backed by a singleton KnowledgeStore so every\n * agent surface (Claude/Cursor/Gemini/Copilot) shares one queryable store.\n *\n * Taxonomy mapping (MCP abbreviated form → KnowledgeInsight.type):\n *   W (Wisdom)    → 'wisdom'\n *   P (Pattern)   → 'pattern'\n *   G (Gotcha)    → 'gotcha'\n *   F (Feedback)  → 'wisdom'   (feedback is a subclass of durable knowledge)\n *   D (Direction) → 'wisdom'   (strategic direction is a subclass of durable knowledge)\n *\n * Tools:\n *   holo_memory_store    — write an entry\n *   holo_memory_recall   — semantic/keyword query → ranked entries\n *   holo_memory_list     — filter by type/tag, paginated\n *   holo_memory_stats    — counts by type, hot/cold sizes, decay state\n *   holo_memory_farm     — cluster mature entries by theme\n *   holo_memory_graduate — mark a cluster as GOLD-graduation candidate\n *\n * De-silo (P0): holo_memory_store + holo_memory_recall route to the shared sovereign\n * SoT (Jetson `memory_entries`, via the `@holoscript/memory` client) when\n * HOLO_MEMORY_SOT_HOST is set and MEMORY_SVC_PASSWORD resolves (HoloKey vault → env).\n * Otherwise — and on ANY SoT error — they degrade to the KnowledgeStore + orchestrator\n * path (the cloud fallback for non-LAN seats). list/stats/farm/graduate operate on the\n * local KnowledgeStore curation buffer. Every surface consuming this same package reads\n * and writes the SAME identity-keyed memory — the de-silo, not a per-family silo.\n */\n\nimport * as os from 'os';\nimport * as path from 'path';\nimport type { Tool } from '@modelcontextprotocol/sdk/types.js';\nimport { KnowledgeStore } from '@holoscript/framework';\nimport { ConsolidationEngine } from '@holoscript/framework';\nimport type { KnowledgeInsight, StoredEntry } from '@holoscript/framework';\nimport { SovereignMemoryStore } from '@holoscript/memory';\nimport type { MemoryEntry, MemorySection } from '@holoscript/memory';\nimport { resolveServiceSecret } from './holokey-resolver';\n\n// ── Singleton store ──────────────────────────────────────────────────────────\n\nconst HOLO_DATA_DIR =\n  process.env.HOLOSCRIPT_CACHE_DIR || path.join(os.homedir(), '.holoscript');\nconst MEMORY_STORE_PATH = path.join(HOLO_DATA_DIR, 'memory-store.json');\nconst MEMORY_ARCHIVE_PATH = path.join(HOLO_DATA_DIR, 'memory-archive.json');\n\nlet _store: KnowledgeStore | null = null;\n\nfunction getStore(): KnowledgeStore {\n  if (!_store) {\n    _store = new KnowledgeStore({\n      persist: true,\n      path: MEMORY_STORE_PATH,\n      remoteUrl: process.env.HOLOSCRIPT_API_URL || undefined,\n      remoteApiKey: process.env.HOLOSCRIPT_API_KEY || undefined,\n    });\n  }\n  return _store;\n}\n\n// Expose for tests to inject a fresh store\nexport function _setStoreForTest(store: KnowledgeStore): void {\n  _store = store;\n}\n\n// ── Sovereign SoT (de-silo): direct cross-family memory_entries on the Jetson node ──\n//\n// Opt-in + fail-safe: active ONLY when HOLO_MEMORY_SOT_HOST is set AND a credential\n// resolves (HoloKey vault → env). Unprovisioned / non-LAN / cloud seats leave it unset\n// and transparently use the KnowledgeStore + orchestrator path — the cloud fallback.\n// `undefined` = unresolved, `null` = disabled/failed (cached so we probe env+vault once).\nlet _sovereign: SovereignMemoryStore | null | undefined;\n\nasync function getSovereignStore(): Promise<SovereignMemoryStore | null> {\n  if (_sovereign !== undefined) return _sovereign;\n  const host = process.env.HOLO_MEMORY_SOT_HOST;\n  if (!host) {\n    _sovereign = null;\n    return null;\n  }\n  // Resolve the scoped credential the sovereign way: HoloKey vault first, env fallback.\n  const password = await resolveServiceSecret('MEMORY_SVC_PASSWORD');\n  if (!password) {\n    _sovereign = null;\n    return null;\n  }\n  try {\n    _sovereign = new SovereignMemoryStore({\n      host,\n      port: Number(process.env.HOLO_MEMORY_SOT_PORT) || 5432,\n      database: process.env.HOLO_MEMORY_SOT_DB || 'knowledge',\n      user: process.env.HOLO_MEMORY_SOT_USER || 'memory_svc',\n      password,\n      max: 4,\n      connectionTimeoutMillis: 3000,\n      workspaceId: process.env.HOLO_MEMORY_WORKSPACE || 'default',\n    });\n  } catch {\n    _sovereign = null;\n  }\n  return _sovereign;\n}\n\n// Expose for tests to force-disable or inject the sovereign store.\nexport function _setSovereignForTest(store: SovereignMemoryStore | null): void {\n  _sovereign = store;\n}\n\n/** Shape a sovereign SoT row for MCP output (parallels formatEntry). */\nfunction formatSovereignEntry(e: MemoryEntry): Record<string, unknown> {\n  return {\n    id: e.id,\n    // Prefer the preserved uAA2 section letter; fall back to the collapsed mnemonic.\n    type: e.section ?? toMnemonic(e.type as KnowledgeInsightType),\n    insightType: e.type,\n    content: e.content,\n    domain: e.domain,\n    confidence: e.confidence,\n    authorAgent: e.authorAgent,\n    section: e.section,\n    tags: e.tags ?? [],\n    createdAt: e.createdAt,\n  };\n}\n\n// ── Taxonomy helpers ─────────────────────────────────────────────────────────\n\ntype MemoryTypeMnemonic = 'W' | 'P' | 'G' | 'F' | 'D';\ntype KnowledgeInsightType = KnowledgeInsight['type'];\n\nconst MNEMONIC_TO_INSIGHT_TYPE: Record<MemoryTypeMnemonic, KnowledgeInsightType> = {\n  W: 'wisdom',\n  P: 'pattern',\n  G: 'gotcha',\n  F: 'wisdom', // Feedback graduates as durable wisdom\n  D: 'wisdom', // Direction graduates as durable wisdom\n};\n\nconst INSIGHT_TYPE_TO_MNEMONIC: Record<KnowledgeInsightType, MemoryTypeMnemonic> = {\n  wisdom: 'W',\n  pattern: 'P',\n  gotcha: 'G',\n};\n\nfunction toInsightType(mnemonic: string): KnowledgeInsightType {\n  const m = (mnemonic as string).toUpperCase() as MemoryTypeMnemonic;\n  return MNEMONIC_TO_INSIGHT_TYPE[m] ?? 'wisdom';\n}\n\nfunction toMnemonic(insight: KnowledgeInsightType): MemoryTypeMnemonic {\n  return INSIGHT_TYPE_TO_MNEMONIC[insight] ?? 'W';\n}\n\n/** Derive a domain tag from content keywords when no explicit domain is given. */\nfunction inferDomain(content: string, tags: string[]): string {\n  const text = `${content} ${tags.join(' ')}`.toLowerCase();\n  if (/security|auth|secret|token|key|exploit|vuln/.test(text)) return 'security';\n  if (/render|3d|webgpu|shader|mesh|gltf|scene/.test(text)) return 'rendering';\n  if (/agent|memory|knowledge|protocol|cycle|skill/.test(text)) return 'agents';\n  if (/compile|compiler|trait|ast|parse|holoscript/.test(text)) return 'compilation';\n  return 'general';\n}\n\n/** Shape a StoredEntry for MCP output — keeps output concise. */\nfunction formatEntry(entry: StoredEntry): Record<string, unknown> {\n  return {\n    id: entry.id,\n    type: toMnemonic(entry.type),\n    insightType: entry.type,\n    content: entry.content,\n    domain: entry.domain,\n    confidence: entry.confidence,\n    source: entry.source,\n    authorAgent: entry.authorAgent,\n    section: entry.section,\n    tags: entry.tags ?? [],\n    queryCount: entry.queryCount,\n    reuseCount: entry.reuseCount,\n    createdAt: entry.createdAt,\n    taskId: entry.taskId,\n  };\n}\n\n// ── Tool definitions ─────────────────────────────────────────────────────────\n\nexport const memoryTools: Tool[] = [\n  {\n    name: 'holo_memory_store',\n    description:\n      'Write a memory entry to the shared agent knowledge store. All agent surfaces (Claude/Cursor/Gemini/Copilot) can query it. ' +\n      'When the sovereign SoT is reachable the entry lands there (identity-keyed, cross-family); otherwise it degrades to the local+orchestrator path. ' +\n      'Returns: { id, type, status, synced, sovereignSoT }.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        content: {\n          type: 'string',\n          description: 'The memory content to store (1-2 concise sentences; no headers).',\n        },\n        type: {\n          type: 'string',\n          enum: ['W', 'P', 'G', 'F', 'D'],\n          description:\n            'W=Wisdom (durable insight), P=Pattern (reusable template), G=Gotcha (known pitfall), ' +\n            'F=Feedback (behavioral rule), D=Direction (strategic direction).',\n        },\n        domain: {\n          type: 'string',\n          description:\n            'Knowledge domain: security | rendering | agents | compilation | general. Auto-inferred when omitted.',\n        },\n        confidence: {\n          type: 'number',\n          description: 'Confidence 0–1 (default 0.8).',\n        },\n        source: {\n          type: 'string',\n          description: 'Source reference (e.g. agent handle, commit hash, task ID).',\n        },\n        tags: {\n          type: 'array',\n          items: { type: 'string' },\n          description: 'Optional tags for filtering and clustering.',\n        },\n        authorAgent: {\n          type: 'string',\n          description: 'Agent handle writing this entry (e.g. claude1, cursor2). Defaults to \"mcp\".',\n        },\n        syncRemote: {\n          type: 'boolean',\n          description:\n            'When true, embed+sync to the remote knowledge store (pgvector). Default false for speed.',\n        },\n      },\n      required: ['content', 'type'],\n    },\n  },\n  {\n    name: 'holo_memory_recall',\n    description:\n      'Query the shared agent knowledge store by keyword or semantic similarity. Returns ranked entries. ' +\n      'Recalls across ALL families from the sovereign SoT when reachable (optional authorAgent filter); degrades to local+orchestrator otherwise. ' +\n      'Returns: { results: Entry[], total, query, mode, sovereignSoT }.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        query: {\n          type: 'string',\n          description: 'Search query (keywords or natural language).',\n        },\n        limit: {\n          type: 'number',\n          description: 'Max results to return (default 10, max 50).',\n        },\n        type: {\n          type: 'string',\n          enum: ['W', 'P', 'G', 'F', 'D'],\n          description: 'Filter by memory type. Omit to search all types.',\n        },\n        semantic: {\n          type: 'boolean',\n          description:\n            'When true, use semantic/vector search (requires remote store). Falls back to keyword search.',\n        },\n        minConfidence: {\n          type: 'number',\n          description: 'Minimum confidence threshold (0–1). Default 0.',\n        },\n        authorAgent: {\n          type: 'string',\n          description:\n            'Filter to memory written by a specific family/agent handle (e.g. claude1, gemini1). ' +\n            'Cross-family recall over the sovereign SoT; omit to recall across all families.',\n        },\n      },\n      required: ['query'],\n    },\n  },\n  {\n    name: 'holo_memory_list',\n    description:\n      'List memory entries with optional type/tag filter and pagination. ' +\n      'Returns: { entries: Entry[], total, page, pageSize }.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        type: {\n          type: 'string',\n          enum: ['W', 'P', 'G', 'F', 'D'],\n          description: 'Filter by memory type.',\n        },\n        domain: {\n          type: 'string',\n          description: 'Filter by knowledge domain.',\n        },\n        tag: {\n          type: 'string',\n          description: 'Filter entries whose tags include this value.',\n        },\n        page: {\n          type: 'number',\n          description: 'Page number (1-based, default 1).',\n        },\n        pageSize: {\n          type: 'number',\n          description: 'Entries per page (default 20, max 100).',\n        },\n      },\n      required: [],\n    },\n  },\n  {\n    name: 'holo_memory_stats',\n    description:\n      'Return memory store statistics: counts by type, hot/cold buffer sizes, decay state. ' +\n      'Returns: { total, byType, hotBufferByDomain, coldStoreByDomain, archivePath }.',\n    inputSchema: {\n      type: 'object',\n      properties: {},\n      required: [],\n    },\n  },\n  {\n    name: 'holo_memory_farm',\n    description:\n      'Cluster mature memory entries by theme and return proposed story groupings. ' +\n      'Groups are derived by tag+type overlap. Use this before holo_memory_graduate to review what would graduate. ' +\n      'Returns: { clusters: Cluster[], totalEntries, totalClusters }.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        minClusterSize: {\n          type: 'number',\n          description: 'Minimum entries per cluster to surface (default 2).',\n        },\n        domain: {\n          type: 'string',\n          description: 'Restrict clustering to a specific knowledge domain.',\n        },\n        type: {\n          type: 'string',\n          enum: ['W', 'P', 'G', 'F', 'D'],\n          description: 'Restrict clustering to a specific memory type.',\n        },\n      },\n      required: [],\n    },\n  },\n  {\n    name: 'holo_memory_graduate',\n    description:\n      'Mark a memory cluster or list of entry IDs as a GOLD-graduation candidate. ' +\n      'Emits a structured GraduationPayload — does NOT write to D:/GOLD directly. ' +\n      'The payload should be reviewed and committed via the GOLD pipeline. ' +\n      'Returns: { graduationId, candidateIds, payload, status }.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        entryIds: {\n          type: 'array',\n          items: { type: 'string' },\n          description: 'Entry IDs to graduate (from holo_memory_farm cluster.entryIds).',\n        },\n        title: {\n          type: 'string',\n          description: 'Title for the GOLD graduation entry.',\n        },\n        rationale: {\n          type: 'string',\n          description: 'Why these entries deserve GOLD-vault promotion.',\n        },\n        tier: {\n          type: 'string',\n          enum: ['Bronze', 'Silver', 'GOLD'],\n          description: 'Target GOLD vault tier (default Silver).',\n        },\n      },\n      required: ['entryIds', 'title', 'rationale'],\n    },\n  },\n];\n\n// ── Handlers ─────────────────────────────────────────────────────────────────\n\nexport async function handleMemoryTool(\n  name: string,\n  args: Record<string, unknown>\n): Promise<unknown> {\n  switch (name) {\n    case 'holo_memory_store':\n      return handleMemoryStore(args);\n    case 'holo_memory_recall':\n      return handleMemoryRecall(args);\n    case 'holo_memory_list':\n      return handleMemoryList(args);\n    case 'holo_memory_stats':\n      return handleMemoryStats();\n    case 'holo_memory_farm':\n      return handleMemoryFarm(args);\n    case 'holo_memory_graduate':\n      return handleMemoryGraduate(args);\n    default:\n      return null;\n  }\n}\n\n// ── holo_memory_store ────────────────────────────────────────────────────────\n\nasync function handleMemoryStore(args: Record<string, unknown>): Promise<unknown> {\n  const content = typeof args.content === 'string' ? args.content.trim() : '';\n  if (!content) {\n    return { success: false, error: 'content is required and must be a non-empty string.' };\n  }\n\n  const typeMnemonic = typeof args.type === 'string' ? args.type : 'W';\n  const insightType = toInsightType(typeMnemonic);\n\n  const tagsRaw = Array.isArray(args.tags) ? (args.tags as unknown[]) : [];\n  const tags = tagsRaw.filter((t): t is string => typeof t === 'string');\n\n  const domain =\n    typeof args.domain === 'string' && args.domain.trim()\n      ? args.domain.trim()\n      : inferDomain(content, tags);\n\n  const confidence =\n    typeof args.confidence === 'number' ? Math.max(0, Math.min(1, args.confidence)) : 0.8;\n\n  const source = typeof args.source === 'string' ? args.source : 'mcp';\n  // Identity-keyed authorship (de-silo P0): explicit arg → per-surface seat handle → 'mcp'.\n  const authorAgent =\n    typeof args.authorAgent === 'string' && args.authorAgent.trim()\n      ? args.authorAgent\n      : process.env.HOLOMESH_AGENT_NAME || 'mcp';\n  // Preserve the uAA2 section letter (W/P/G/F/D) that the 3-value insight type collapses.\n  const section = typeof args.type === 'string' ? args.type.toUpperCase() : 'W';\n  const syncRemote = args.syncRemote === true;\n\n  const insight: KnowledgeInsight = {\n    type: insightType,\n    content,\n    domain,\n    confidence,\n    source,\n    section,\n    tags,\n  };\n\n  // De-silo: write to the shared sovereign SoT when active; degrade to KnowledgeStore.\n  const sovereign = await getSovereignStore();\n  if (sovereign) {\n    try {\n      const id = await sovereign.store({\n        content,\n        authorAgent,\n        type: insightType,\n        section: section as MemorySection,\n        tags,\n        domain,\n        confidence,\n      });\n      return {\n        success: true,\n        id,\n        type: typeMnemonic,\n        insightType,\n        status: 'stored_sovereign',\n        synced: true,\n        sovereignSoT: true,\n      };\n    } catch (e) {\n      // eslint-disable-next-line no-console\n      console.warn(\n        `[memory] sovereign store failed — falling back to KnowledgeStore: ${e instanceof Error ? e.message : String(e)}`\n      );\n    }\n  }\n\n  const store = getStore();\n\n  if (syncRemote) {\n    const result = await store.embedAndStore(insight, authorAgent);\n    return {\n      success: true,\n      id: result.entryId,\n      type: typeMnemonic,\n      insightType,\n      status: result.synced ? 'stored_and_synced' : 'stored_local',\n      synced: result.synced,\n      remoteId: result.remoteId,\n      sovereignSoT: false,\n    };\n  }\n\n  const entry = store.publish(insight, authorAgent);\n  return {\n    success: true,\n    id: entry.id,\n    type: typeMnemonic,\n    insightType,\n    status: 'stored_local',\n    synced: false,\n    sovereignSoT: false,\n  };\n}\n\n// ── holo_memory_recall ───────────────────────────────────────────────────────\n\nasync function handleMemoryRecall(args: Record<string, unknown>): Promise<unknown> {\n  const query = typeof args.query === 'string' ? args.query.trim() : '';\n  if (!query) {\n    return { success: false, error: 'query is required and must be a non-empty string.' };\n  }\n\n  const rawLimit = typeof args.limit === 'number' ? args.limit : 10;\n  const limit = Math.max(1, Math.min(50, rawLimit));\n  const semantic = args.semantic === true;\n  const minConfidence = typeof args.minConfidence === 'number' ? args.minConfidence : 0;\n\n  // Optional type filter\n  const typeMnemonic = typeof args.type === 'string' ? args.type.toUpperCase() : null;\n  const insightTypeFilter =\n    typeMnemonic && typeMnemonic in MNEMONIC_TO_INSIGHT_TYPE\n      ? MNEMONIC_TO_INSIGHT_TYPE[typeMnemonic as MemoryTypeMnemonic]\n      : null;\n\n  const authorFilter =\n    typeof args.authorAgent === 'string' && args.authorAgent.trim() ? args.authorAgent.trim() : undefined;\n\n  // De-silo: recall from the shared sovereign SoT when active; degrade to KnowledgeStore.\n  // The SoT preserves the uAA2 section letter, so `type` filters exactly (F stays F,\n  // rather than collapsing into wisdom the way the local 3-value insight type does).\n  const sovereign = await getSovereignStore();\n  if (sovereign) {\n    try {\n      const rows = await sovereign.recall(query, {\n        limit,\n        section: (typeMnemonic as MemorySection) ?? undefined,\n        authorAgent: authorFilter,\n      });\n      const filtered = minConfidence > 0 ? rows.filter((r) => r.confidence >= minConfidence) : rows;\n      return {\n        success: true,\n        query,\n        mode: 'sovereign',\n        total: filtered.length,\n        results: filtered.map(formatSovereignEntry),\n        sovereignSoT: true,\n      };\n    } catch (e) {\n      // eslint-disable-next-line no-console\n      console.warn(\n        `[memory] sovereign recall failed — falling back to KnowledgeStore: ${e instanceof Error ? e.message : String(e)}`\n      );\n    }\n  }\n\n  const store = getStore();\n\n  let results: StoredEntry[];\n\n  if (semantic) {\n    results = await store.semanticSearch(query, {\n      limit,\n      type: insightTypeFilter ?? undefined,\n      minConfidence: minConfidence > 0 ? minConfidence : undefined,\n      hybridSearch: true,\n    });\n  } else {\n    results = store.search(query, limit);\n    if (insightTypeFilter) {\n      results = results.filter((e) => e.type === insightTypeFilter);\n    }\n    if (minConfidence > 0) {\n      results = results.filter((e) => e.confidence >= minConfidence);\n    }\n  }\n\n  return {\n    success: true,\n    query,\n    mode: semantic ? 'semantic' : 'keyword',\n    total: results.length,\n    results: results.map(formatEntry),\n    sovereignSoT: false,\n  };\n}\n\n// ── holo_memory_list ─────────────────────────────────────────────────────────\n\nfunction handleMemoryList(args: Record<string, unknown>): unknown {\n  const typeMnemonic = typeof args.type === 'string' ? args.type.toUpperCase() : null;\n  const insightTypeFilter =\n    typeMnemonic && typeMnemonic in MNEMONIC_TO_INSIGHT_TYPE\n      ? MNEMONIC_TO_INSIGHT_TYPE[typeMnemonic as MemoryTypeMnemonic]\n      : null;\n\n  const domainFilter = typeof args.domain === 'string' ? args.domain.toLowerCase() : null;\n  const tagFilter = typeof args.tag === 'string' ? args.tag.toLowerCase() : null;\n\n  const rawPage = typeof args.page === 'number' ? args.page : 1;\n  const page = Math.max(1, rawPage);\n  const rawPageSize = typeof args.pageSize === 'number' ? args.pageSize : 20;\n  const pageSize = Math.max(1, Math.min(100, rawPageSize));\n\n  const store = getStore();\n  let entries = store.all();\n\n  if (insightTypeFilter) {\n    entries = entries.filter((e) => e.type === insightTypeFilter);\n  }\n  if (domainFilter) {\n    entries = entries.filter((e) => e.domain.toLowerCase() === domainFilter);\n  }\n  if (tagFilter) {\n    entries = entries.filter((e) => {\n      const tags = (e as unknown as { tags?: string[] }).tags ?? [];\n      return tags.some((t) => t.toLowerCase() === tagFilter);\n    });\n  }\n\n  // Sort newest first\n  entries = entries.sort((a, b) => b.createdAt.localeCompare(a.createdAt));\n\n  const total = entries.length;\n  const start = (page - 1) * pageSize;\n  const paged = entries.slice(start, start + pageSize);\n\n  return {\n    success: true,\n    total,\n    page,\n    pageSize,\n    entries: paged.map(formatEntry),\n  };\n}\n\n// ── holo_memory_stats ────────────────────────────────────────────────────────\n\nfunction handleMemoryStats(): unknown {\n  const store = getStore();\n  const all = store.all();\n\n  const byType: Record<string, number> = { W: 0, P: 0, G: 0 };\n  for (const e of all) {\n    const m = toMnemonic(e.type);\n    byType[m] = (byType[m] ?? 0) + 1;\n  }\n\n  // Consolidation engine for hot/cold buffer stats (independent instance used only for stats)\n  const engine = new ConsolidationEngine();\n  const hotBufferByDomain = engine.getHotBufferStats();\n  const coldStoreByDomain = engine.getColdStoreStats();\n\n  return {\n    success: true,\n    total: store.size,\n    byType,\n    hotBufferByDomain,\n    coldStoreByDomain,\n    storePath: MEMORY_STORE_PATH,\n    archivePath: MEMORY_ARCHIVE_PATH,\n  };\n}\n\n// ── holo_memory_farm ─────────────────────────────────────────────────────────\n\ninterface MemoryCluster {\n  theme: string;\n  type: MemoryTypeMnemonic;\n  domain: string;\n  tags: string[];\n  entryIds: string[];\n  entryCount: number;\n  avgConfidence: number;\n  sampleContent: string;\n}\n\nfunction handleMemoryFarm(args: Record<string, unknown>): unknown {\n  const minClusterSize = typeof args.minClusterSize === 'number' ? Math.max(1, args.minClusterSize) : 2;\n  const domainFilter = typeof args.domain === 'string' ? args.domain.toLowerCase() : null;\n  const typeMnemonic = typeof args.type === 'string' ? args.type.toUpperCase() : null;\n  const insightTypeFilter =\n    typeMnemonic && typeMnemonic in MNEMONIC_TO_INSIGHT_TYPE\n      ? MNEMONIC_TO_INSIGHT_TYPE[typeMnemonic as MemoryTypeMnemonic]\n      : null;\n\n  const store = getStore();\n  let entries = store.all();\n\n  if (domainFilter) {\n    entries = entries.filter((e) => e.domain.toLowerCase() === domainFilter);\n  }\n  if (insightTypeFilter) {\n    entries = entries.filter((e) => e.type === insightTypeFilter);\n  }\n\n  // Cluster by: domain + type + common tags\n  // Key = \"domain|insightType|sortedCommonTags\"\n  const clusterMap = new Map<string, StoredEntry[]>();\n\n  for (const entry of entries) {\n    const entryTags = (entry as unknown as { tags?: string[] }).tags ?? [];\n    // Primary key: domain + type\n    const primaryKey = `${entry.domain}|${entry.type}`;\n\n    // If entry has tags, create per-tag sub-clusters\n    if (entryTags.length > 0) {\n      for (const tag of entryTags) {\n        const key = `${primaryKey}|${tag}`;\n        const group = clusterMap.get(key) ?? [];\n        group.push(entry);\n        clusterMap.set(key, group);\n      }\n    } else {\n      // No tags — group by domain+type only\n      const group = clusterMap.get(primaryKey) ?? [];\n      group.push(entry);\n      clusterMap.set(primaryKey, group);\n    }\n  }\n\n  const clusters: MemoryCluster[] = [];\n\n  for (const [key, group] of clusterMap) {\n    if (group.length < minClusterSize) continue;\n\n    const parts = key.split('|');\n    const domain = parts[0] ?? 'general';\n    const insightType = (parts[1] ?? 'wisdom') as KnowledgeInsightType;\n    const tagPart = parts[2];\n    const clusterTags = tagPart ? [tagPart] : [];\n\n    const avgConfidence =\n      group.reduce((sum, e) => sum + e.confidence, 0) / group.length;\n\n    // Deduplicate entry IDs within this cluster\n    const uniqueIds = [...new Set(group.map((e) => e.id))];\n    const uniqueEntries = uniqueIds\n      .map((id) => group.find((e) => e.id === id))\n      .filter((e): e is StoredEntry => e !== undefined);\n\n    if (uniqueEntries.length < minClusterSize) continue;\n\n    const theme = clusterTags.length > 0\n      ? `${domain}:${clusterTags[0]}`\n      : `${domain}:${insightType}`;\n\n    // Avoid duplicate clusters (same set of IDs under different keys)\n    const idSetKey = uniqueIds.sort().join(',');\n    if (clusters.some((c) => c.entryIds.sort().join(',') === idSetKey)) continue;\n\n    clusters.push({\n      theme,\n      type: toMnemonic(insightType),\n      domain,\n      tags: clusterTags,\n      entryIds: uniqueIds,\n      entryCount: uniqueEntries.length,\n      avgConfidence: Math.round(avgConfidence * 1000) / 1000,\n      sampleContent: uniqueEntries[0]?.content.slice(0, 120) ?? '',\n    });\n  }\n\n  // Sort by cluster size descending\n  clusters.sort((a, b) => b.entryCount - a.entryCount);\n\n  return {\n    success: true,\n    totalEntries: entries.length,\n    totalClusters: clusters.length,\n    clusters,\n  };\n}\n\n// ── holo_memory_graduate ─────────────────────────────────────────────────────\n\ninterface GraduationPayload {\n  graduationId: string;\n  schemaVersion: 'holo_memory.graduation.v1';\n  createdAt: string;\n  title: string;\n  rationale: string;\n  tier: string;\n  candidateIds: string[];\n  entries: Array<{\n    id: string;\n    type: MemoryTypeMnemonic;\n    content: string;\n    domain: string;\n    confidence: number;\n    source: string;\n    authorAgent: string;\n    createdAt: string;\n  }>;\n  instructions: string;\n}\n\nfunction handleMemoryGraduate(args: Record<string, unknown>): unknown {\n  const entryIds = Array.isArray(args.entryIds)\n    ? (args.entryIds as unknown[]).filter((id): id is string => typeof id === 'string')\n    : [];\n\n  if (entryIds.length === 0) {\n    return { success: false, error: 'entryIds must be a non-empty array of string IDs.' };\n  }\n\n  const title = typeof args.title === 'string' ? args.title.trim() : '';\n  if (!title) {\n    return { success: false, error: 'title is required.' };\n  }\n\n  const rationale = typeof args.rationale === 'string' ? args.rationale.trim() : '';\n  if (!rationale) {\n    return { success: false, error: 'rationale is required.' };\n  }\n\n  const tier =\n    typeof args.tier === 'string' && ['Bronze', 'Silver', 'GOLD'].includes(args.tier)\n      ? args.tier\n      : 'Silver';\n\n  const store = getStore();\n  const all = store.all();\n  const idSet = new Set(entryIds);\n\n  const resolved = all.filter((e) => idSet.has(e.id));\n  const missingIds = entryIds.filter((id) => !resolved.find((e) => e.id === id));\n\n  const graduationId = `grad_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;\n\n  const payload: GraduationPayload = {\n    graduationId,\n    schemaVersion: 'holo_memory.graduation.v1',\n    createdAt: new Date().toISOString(),\n    title,\n    rationale,\n    tier,\n    candidateIds: entryIds,\n    entries: resolved.map((e) => ({\n      id: e.id,\n      type: toMnemonic(e.type),\n      content: e.content,\n      domain: e.domain,\n      confidence: e.confidence,\n      source: e.source,\n      authorAgent: e.authorAgent,\n      createdAt: e.createdAt,\n    })),\n    instructions:\n      'Review this payload and commit it to the GOLD vault via the knowledge graduation pipeline. ' +\n      'Do NOT write to D:/GOLD directly. Use: python farm.py graduate --payload <path>',\n  };\n\n  return {\n    success: true,\n    graduationId,\n    candidateIds: entryIds,\n    resolvedCount: resolved.length,\n    missingIds,\n    tier,\n    status:\n      missingIds.length === 0\n        ? 'ready_for_review'\n        : 'partial_match_check_missing_ids',\n    payload,\n  };\n}\n","/**\n * from-scratch-mcp-tools.ts — MCP tool surface for the LIBRARY-DRIVEN\n * from-scratch training lane (sovereign pretraining, anti-silo).\n *\n * Why this exists (mirrors holo-ci-tools.ts / holotune-mcp-tools.ts):\n *\n * The founder's directive: \"anyone can HoloTune/Train their own from scratch — we\n * have a model library with planned models; runner is only one; we don't want to\n * silo potential.\" So from-scratch training is NOT a per-model launcher. Any\n * model-library entry (ai-ecosystem/model-library/library.json) with a\n * `holotune.from_scratch` block launches through the ONE governed CLI:\n *\n *     node scripts/train-from-scratch.mjs <status|launch> [--model <id>] ...\n *\n * The plan (library.json#training_plan) is one sovereign from-scratch BASE\n * (holorunner-s0) that use-case models SPRAWL from via fine-tune; every target is\n * trained BOTH from-scratch AND fine-tuned, then benchmarked (HOLO #9).\n *\n * ## Cross-repo dispatch (CRITICAL)\n *\n * `train-from-scratch.mjs` lives in the **ai-ecosystem** repo, not HoloScript.\n * The two are separate repos with no shared module path, so this tool SPAWNS the\n * CLI in the ai-ecosystem working tree instead of importing it. The tree is\n * resolved from `AI_ECOSYSTEM_ROOT` (the same env convention\n * tools/estimate_task_duration.ts already uses) → `~/.ai-ecosystem` by default.\n *\n * This tool is only useful on a **sovereign LOCAL MCP** that shares metal with the\n * ai-ecosystem checkout (R.027 — the remote Railway orchestrator is FS-blind).\n * When the resolved script is not present (e.g. remote deploy), the handler fails\n * HONESTLY with the fix (set AI_ECOSYSTEM_ROOT) rather than faking a result.\n *\n * ## Governance (mirrors holotune_launch / holo_ci_dispatch)\n *\n *  - `holo_from_scratch_status` — read-only, free. Lists every from_scratch-lane\n *    model + its free-first proof state. No spend, no gate.\n *  - `holo_from_scratch_launch` — SAFE-BY-DEFAULT: previews (dryRun) unless the\n *    caller passes apply:true. A non-dry launch additionally requires a signed\n *    spend-authority envelope from the same active HoloMesh seat as the signed\n *    MCP caller. The original authority is delegated to the CLI, which re-verifies\n *    and consumes it before spend; `--yes-spend` remains intent, not authority.\n */\n\nimport { createHash } from 'node:crypto';\nimport { execFile } from 'node:child_process';\nimport { existsSync } from 'node:fs';\nimport { chmod, mkdtemp, rm, writeFile } from 'node:fs/promises';\nimport { homedir, tmpdir } from 'node:os';\nimport { join, resolve } from 'node:path';\nimport { promisify } from 'node:util';\nimport type { Tool } from '@modelcontextprotocol/sdk/types.js';\nimport {\n  canonicalizeBody,\n  extractEnvelope,\n  verifyEnvelope,\n  type SignedEnvelope,\n} from './holomesh/request-signing';\nimport {\n  getAttestationRegistry,\n  type SigningContext,\n} from './holomesh/identity/signing-middleware';\n\nconst execFileAsync = promisify(execFile);\n\ntype JsonRecord = Record<string, unknown>;\n\nconst TOOL_NAMES = ['holo_from_scratch_status', 'holo_from_scratch_launch'] as const;\nconst FROM_SCRATCH_NAMES = new Set<string>(TOOL_NAMES);\n\nexport function isFromScratchToolName(name: string): boolean {\n  return FROM_SCRATCH_NAMES.has(name);\n}\n\n// ─── ai-ecosystem cross-repo resolution ──────────────────────────────────────\n\n/** Relative path (within the ai-ecosystem repo) of the library-driven CLI. */\nconst CLI_REL = join('scripts', 'train-from-scratch.mjs');\n\n/**\n * Resolve the ai-ecosystem repo root. Same env convention as\n * tools/estimate_task_duration.ts (AI_ECOSYSTEM_ROOT) → ~/.ai-ecosystem default.\n * Returns the first candidate whose train-from-scratch.mjs exists, or null when\n * the server cannot reach an ai-ecosystem checkout (remote / FS-blind deploy).\n */\nfunction resolveAiEcosystemCli(): { root: string; cli: string } | null {\n  const candidates = [process.env.AI_ECOSYSTEM_ROOT, join(homedir(), '.ai-ecosystem')].filter(\n    (p): p is string => typeof p === 'string' && p.trim().length > 0\n  );\n  for (const candidate of candidates) {\n    const root = resolve(candidate);\n    const cli = join(root, CLI_REL);\n    if (existsSync(cli)) return { root, cli };\n  }\n  return null;\n}\n\n// ─── Governance helpers (mirror holotune-mcp-tools.ts) ───────────────────────\n\nfunction stringArg(args: JsonRecord, key: string, fallback = ''): string {\n  const value = args[key];\n  return typeof value === 'string' && value.trim() ? value.trim() : fallback;\n}\n\nfunction recordArg(args: JsonRecord, key: string): JsonRecord | null {\n  const value = args[key];\n  return value && typeof value === 'object' && !Array.isArray(value) ? (value as JsonRecord) : null;\n}\n\nfunction hashPayload(payload: unknown): string {\n  return `sha256:${createHash('sha256').update(JSON.stringify(payload)).digest('hex')}`;\n}\n\nconst SPEND_AUTHORITY_CHALLENGE_PREFIX = '[from-scratch] spend authority challenge: ';\nconst MAX_SPEND_AUTHORITY_TTL_MS = 15 * 60 * 1000;\n\nfunction parseJsonRecord(value: string): JsonRecord | null {\n  try {\n    const parsed: unknown = JSON.parse(value);\n    return parsed && typeof parsed === 'object' && !Array.isArray(parsed)\n      ? (parsed as JsonRecord)\n      : null;\n  } catch {\n    return null;\n  }\n}\n\nfunction parseSpendAuthorityChallenge(stdout: string): JsonRecord | null {\n  const direct = parseJsonRecord(stdout);\n  if (direct) {\n    return (\n      recordArg(direct, 'spendAuthorityChallenge') ?? recordArg(direct, 'spend_authority_challenge')\n    );\n  }\n  for (const line of stdout.split(/\\r?\\n/)) {\n    const offset = line.indexOf(SPEND_AUTHORITY_CHALLENGE_PREFIX);\n    if (offset < 0) continue;\n    const challenge = parseJsonRecord(\n      line.slice(offset + SPEND_AUTHORITY_CHALLENGE_PREFIX.length).trim()\n    );\n    if (challenge) return challenge;\n  }\n  return null;\n}\n\nfunction isDryRun(args: JsonRecord): boolean {\n  if (args.apply === true) return false;\n  return args.dryRun !== false;\n}\n\nconst ADDRESS_RE = /^0x[0-9a-fA-F]{40}$/;\nconst SHA256_RE = /^sha256:[0-9a-f]{64}$/;\nconst RECEIPT_ID_RE = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;\nconst SPEND_AUTHORITY_ENVELOPE_KEYS = [\n  'body',\n  'nonce',\n  'signature',\n  'signer_address',\n  'timestamp',\n] as const;\nconst SPEND_AUTHORITY_BODY_KEYS = [\n  'action',\n  'caller',\n  'decision',\n  'expiresAt',\n  'freeFirstReceiptHash',\n  'issuedAt',\n  'laneManifestHash',\n  'launcherConfigHash',\n  'maxDph',\n  'maxRuntimeHours',\n  'maxSpendUsd',\n  'model',\n  'nonce',\n  'rail',\n  'receiptId',\n  'runId',\n  'schema',\n] as const;\n\ninterface VerifiedSpendAuthority {\n  envelope: SignedEnvelope;\n  authorityHash: string;\n  caller: string;\n}\n\nfunction isVerifiedSpendAuthority(\n  value: VerifiedSpendAuthority | JsonRecord\n): value is VerifiedSpendAuthority {\n  return (\n    'envelope' in value &&\n    typeof value.envelope === 'object' &&\n    value.envelope !== null &&\n    typeof value.authorityHash === 'string' &&\n    typeof value.caller === 'string'\n  );\n}\n\nfunction normalizeAddress(value: string): string {\n  return value.toLowerCase();\n}\n\nfunction positiveNumberArg(args: JsonRecord, key: string): number | null {\n  const value = args[key];\n  return typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : null;\n}\n\nfunction canonicalIso(value: unknown): value is string {\n  if (typeof value !== 'string') return false;\n  const parsed = Date.parse(value);\n  return !Number.isNaN(parsed) && new Date(parsed).toISOString() === value;\n}\n\nfunction authorityError(reason: string): JsonRecord {\n  return {\n    ok: false,\n    error: 'spend-authority-rejected',\n    reason,\n    spendAuthorityRequired: true,\n  };\n}\n\nasync function verifySpendAuthority(\n  args: JsonRecord,\n  signingCtx: SigningContext | undefined,\n  nowMs: number = Date.now()\n): Promise<VerifiedSpendAuthority | JsonRecord> {\n  if (\n    !signingCtx?.signedRequest ||\n    signingCtx.signingValid !== true ||\n    typeof signingCtx.signer !== 'string' ||\n    !ADDRESS_RE.test(signingCtx.signer)\n  ) {\n    return authorityError('signed-mcp-caller-required');\n  }\n\n  const caller = normalizeAddress(signingCtx.signer);\n  const registry = getAttestationRegistry();\n  if (registry.size() === 0 || !registry.isAttested(caller, nowMs)) {\n    return authorityError('caller-seat-not-active');\n  }\n\n  const authorityRecord = recordArg(args, 'spendAuthority');\n  const envelope = extractEnvelope(authorityRecord);\n  if (!envelope) return authorityError('signed-spend-authority-required');\n  const envelopeKeys = Object.keys(authorityRecord as JsonRecord).sort();\n  const expectedEnvelopeKeys = [...SPEND_AUTHORITY_ENVELOPE_KEYS].sort();\n  if (\n    envelopeKeys.length !== expectedEnvelopeKeys.length ||\n    envelopeKeys.some((key, i) => key !== expectedEnvelopeKeys[i])\n  ) {\n    return authorityError('authority-envelope-shape-mismatch');\n  }\n\n  const verified = await verifyEnvelope(envelope, {\n    nowMs,\n    registryCheck: registry.toRegistryCheck(nowMs),\n  });\n  if (!verified.valid || !verified.signer) {\n    return authorityError(`signature-${verified.reason ?? 'invalid'}`);\n  }\n  if (normalizeAddress(verified.signer) !== caller) {\n    return authorityError('authority-signer-caller-mismatch');\n  }\n\n  const body =\n    envelope.body && typeof envelope.body === 'object' && !Array.isArray(envelope.body)\n      ? (envelope.body as JsonRecord)\n      : null;\n  if (!body) return authorityError('authority-body-required');\n  const bodyKeys = Object.keys(body).sort();\n  const expectedKeys = [...SPEND_AUTHORITY_BODY_KEYS].sort();\n  if (\n    bodyKeys.length !== expectedKeys.length ||\n    bodyKeys.some((key, i) => key !== expectedKeys[i])\n  ) {\n    return authorityError('authority-body-shape-mismatch');\n  }\n\n  const requiredBindings: Array<[string, unknown]> = [\n    ['schema', 'holo.spend-authority.v1'],\n    ['rail', 'purchased_compute'],\n    ['action', 'holo_from_scratch_launch'],\n    ['decision', 'authorized'],\n    ['caller', caller],\n    ['model', stringArg(args, 'model')],\n    ['runId', stringArg(args, 'runId')],\n    ['maxDph', positiveNumberArg(args, 'maxDph')],\n    ['maxSpendUsd', positiveNumberArg(args, 'maxSpendUsd')],\n    ['maxRuntimeHours', positiveNumberArg(args, 'maxRuntimeHours')],\n    ['launcherConfigHash', stringArg(args, 'launcherConfigHash')],\n    ['laneManifestHash', stringArg(args, 'laneManifestHash')],\n    ['freeFirstReceiptHash', stringArg(args, 'freeFirstReceiptHash')],\n    ['issuedAt', envelope.timestamp],\n    ['nonce', envelope.nonce],\n  ];\n  for (const [key, expected] of requiredBindings) {\n    const actual =\n      key === 'caller' && typeof body[key] === 'string'\n        ? normalizeAddress(body[key] as string)\n        : body[key];\n    if (expected === null || expected === '' || actual !== expected) {\n      return authorityError(`authority-${key}-mismatch`);\n    }\n  }\n\n  if (!RECEIPT_ID_RE.test(String(body.receiptId ?? ''))) {\n    return authorityError('authority-receiptId-invalid');\n  }\n  for (const key of ['launcherConfigHash', 'laneManifestHash', 'freeFirstReceiptHash']) {\n    if (!SHA256_RE.test(String(body[key] ?? ''))) {\n      return authorityError(`authority-${key}-invalid`);\n    }\n  }\n  if (!canonicalIso(body.issuedAt) || !canonicalIso(body.expiresAt)) {\n    return authorityError('authority-timestamp-invalid');\n  }\n  const issuedAtMs = Date.parse(body.issuedAt);\n  const expiresAtMs = Date.parse(body.expiresAt);\n  if (expiresAtMs <= nowMs) return authorityError('authority-expired');\n  if (expiresAtMs <= issuedAtMs || expiresAtMs - issuedAtMs > MAX_SPEND_AUTHORITY_TTL_MS) {\n    return authorityError('authority-expiry-window-invalid');\n  }\n\n  return {\n    envelope,\n    caller,\n    authorityHash: `sha256:${createHash('sha256')\n      .update(canonicalizeBody(envelope))\n      .digest('hex')}`,\n  };\n}\n\nasync function withRestrictedAuthorityFile<T>(\n  authority: SignedEnvelope,\n  fn: (path: string) => Promise<T>\n): Promise<T> {\n  const dir = await mkdtemp(join(tmpdir(), 'holo-spend-authority-'));\n  const path = join(dir, 'authority.json');\n  try {\n    await chmod(dir, 0o700).catch(() => undefined);\n    await writeFile(path, JSON.stringify(authority), {\n      encoding: 'utf8',\n      flag: 'wx',\n      mode: 0o600,\n    });\n    await chmod(path, 0o600).catch(() => undefined);\n    return await fn(path);\n  } finally {\n    await rm(dir, { recursive: true, force: true });\n  }\n}\n\n// ─── CLI dispatch ────────────────────────────────────────────────────────────\n\n/** Validate a model id before it lands in an argv slot. */\nconst MODEL_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;\n\nasync function runCli(\n  cli: string,\n  root: string,\n  argv: string[]\n): Promise<{ ok: boolean; stdout: string; stderr: string; code: number | null }> {\n  try {\n    const { stdout, stderr } = await execFileAsync(process.execPath, [cli, ...argv], {\n      cwd: root,\n      // Paid launch performs two fail-closed cap/wallet checks before create,\n      // then arms the host watchdog and records the rental before returning.\n      // Keep the MCP parent alive long enough to receive that atomic closeout.\n      timeout: 180_000,\n      maxBuffer: 4 * 1024 * 1024,\n      // Never inherit a shell — argv is passed verbatim to node, no interpolation.\n      windowsHide: true,\n    });\n    return { ok: true, stdout, stderr, code: 0 };\n  } catch (err) {\n    const e = err as { stdout?: string; stderr?: string; code?: number; message?: string };\n    return {\n      ok: false,\n      stdout: e.stdout ?? '',\n      stderr: e.stderr ?? e.message ?? String(err),\n      code: typeof e.code === 'number' ? e.code : null,\n    };\n  }\n}\n\nfunction unreachablePayload(tool: string): JsonRecord {\n  return {\n    ok: false,\n    error: 'ai-ecosystem-unreachable',\n    tool,\n    message:\n      'train-from-scratch.mjs was not found. This tool dispatches the from-scratch training CLI in the ai-ecosystem repo, ' +\n      'which the remote (FS-blind) orchestrator cannot reach — run it on a sovereign LOCAL MCP that shares metal with the ' +\n      'ai-ecosystem checkout (R.027).',\n    fix: 'Set AI_ECOSYSTEM_ROOT to the ai-ecosystem repo root (must contain scripts/train-from-scratch.mjs), or run this MCP server locally where ~/.ai-ecosystem exists.',\n    checked: [process.env.AI_ECOSYSTEM_ROOT || null, join(homedir(), '.ai-ecosystem')].filter(\n      Boolean\n    ),\n  };\n}\n\n// ─── Tool definitions ─────────────────────────────────────────────────────────\n\nexport const fromScratchToolDefinitions: Tool[] = [\n  {\n    name: 'holo_from_scratch_status',\n    description:\n      'List every from-scratch-lane model in the ai-ecosystem model library (library.json entries with a holotune.from_scratch block) and its free-first-proof state. Read-only, FREE — no GPU spend, no gate. Dispatches `node scripts/train-from-scratch.mjs status` in the ai-ecosystem repo (resolved via AI_ECOSYSTEM_ROOT → ~/.ai-ecosystem). Sovereign-LOCAL-MCP only: the remote orchestrator is FS-blind and this fails honestly there.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        model: {\n          type: 'string',\n          description:\n            'Optional model id to narrow the status to a single library entry (e.g. holorunner-s0).',\n        },\n      },\n    },\n  },\n  {\n    name: 'holo_from_scratch_launch',\n    description:\n      'Prepare or launch a library-driven from-scratch pretraining run for a model-library entry. SAFE-BY-DEFAULT: previews spend-free unless apply:true. An applied launch requires tools:admin plus a signed, active HoloMesh caller and a signed spendAuthority envelope bound to the exact run and active purchased-compute policy. The host CLI independently re-verifies and consumes that authority before spend. Sovereign-LOCAL-MCP only.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        model: {\n          type: 'string',\n          description:\n            'Required for a launch — the from_scratch-lane model id (see holo_from_scratch_status; e.g. holorunner-s0).',\n        },\n        dryRun: {\n          type: 'boolean',\n          description:\n            'Default TRUE (safe): build/return the delegated CLI plan WITHOUT spending. Pass dryRun:false (or apply:true) to actually launch.',\n        },\n        apply: {\n          type: 'boolean',\n          description:\n            'Set true to request a real (non-dry) launch. Requires a signed spendAuthority and active registered HoloMesh caller.',\n        },\n        runId: {\n          type: 'string',\n          description:\n            'Run id passed through to the CLI (--run-id). Required and signed for an applied launch.',\n        },\n        maxDph: {\n          type: 'number',\n          description:\n            'Max dollars-per-hour bid ceiling. Required and signed for an applied launch.',\n        },\n        maxSpendUsd: {\n          type: 'number',\n          description:\n            'Maximum total USD authorized for this run. Required and signed for an applied launch.',\n        },\n        maxRuntimeHours: {\n          type: 'number',\n          description:\n            'Maximum runtime hours authorized for this run. Required and signed for an applied launch.',\n        },\n        launcherConfigHash: {\n          type: 'string',\n          description:\n            'sha256 hash of the exact launcher configuration. Required and signed for an applied launch.',\n        },\n        laneManifestHash: {\n          type: 'string',\n          description:\n            'sha256 hash of the purchased-compute lane manifest. Required and signed for an applied launch.',\n        },\n        freeFirstReceiptHash: {\n          type: 'string',\n          description:\n            'sha256 hash of the free-first proof receipt. Required and signed for an applied launch.',\n        },\n        spendAuthority: {\n          type: 'object',\n          description:\n            'EIP-191 envelope {body,signature,signer_address,nonce,timestamp}. Its holo.spend-authority.v1 body must bind the caller, model, run, ceilings, hashes, issuedAt, expiresAt, and nonce exactly.',\n        },\n      },\n    },\n  },\n];\n\n// ─── Handlers ─────────────────────────────────────────────────────────────────\n\nasync function status(args: JsonRecord): Promise<JsonRecord> {\n  const resolved = resolveAiEcosystemCli();\n  if (!resolved) return unreachablePayload('holo_from_scratch_status');\n\n  const model = stringArg(args, 'model');\n  if (model && !MODEL_RE.test(model)) {\n    return { ok: false, error: 'invalid-model-id', message: `unsafe model id \"${model}\"` };\n  }\n  const argv = ['status'];\n  if (model) argv.push('--model', model);\n\n  const res = await runCli(resolved.cli, resolved.root, argv);\n  return {\n    ok: res.ok,\n    surface: 'from-scratch',\n    aiEcosystemRoot: resolved.root,\n    cli: `node ${CLI_REL} status${model ? ` --model ${model}` : ''}`,\n    model: model || null,\n    stdout: res.stdout,\n    stderr: res.stderr || undefined,\n    exitCode: res.code,\n    governance: {\n      readOnly: true,\n      spend: false,\n      note: 'status is free; applied launch requires signed seat authority within the active purchased-compute cap (SPEND.md)',\n    },\n  };\n}\n\nasync function launch(args: JsonRecord, signingCtx?: SigningContext): Promise<JsonRecord> {\n  const model = stringArg(args, 'model');\n  if (!model) {\n    return {\n      ok: false,\n      error: 'model-required',\n      message: 'holo_from_scratch_launch requires a \"model\" id (see holo_from_scratch_status).',\n    };\n  }\n  if (!MODEL_RE.test(model)) {\n    return { ok: false, error: 'invalid-model-id', message: `unsafe model id \"${model}\"` };\n  }\n\n  const dryRun = isDryRun(args);\n\n  // Build the delegated argv from typed inputs (never string-concatenate into a shell).\n  const cliArgv = ['launch', '--model', model];\n  const runId = stringArg(args, 'runId');\n  if (runId) {\n    if (!MODEL_RE.test(runId)) {\n      return { ok: false, error: 'invalid-run-id', message: `unsafe runId \"${runId}\"` };\n    }\n    cliArgv.push('--run-id', runId);\n  }\n  const maxDph = positiveNumberArg(args, 'maxDph');\n  if (maxDph !== null) {\n    cliArgv.push('--max-dph', String(maxDph));\n  }\n  const maxSpendUsd = positiveNumberArg(args, 'maxSpendUsd');\n  if (maxSpendUsd !== null) {\n    cliArgv.push('--max-spend-usd', String(maxSpendUsd));\n  }\n  const maxRuntimeHours = positiveNumberArg(args, 'maxRuntimeHours');\n  if (maxRuntimeHours !== null) {\n    cliArgv.push('--max-runtime-hours', String(maxRuntimeHours));\n  }\n\n  const previewArgv = dryRun ? [...cliArgv, '--json'] : cliArgv;\n  const previewCommand = `node ${CLI_REL} ${previewArgv.join(' ')}${dryRun ? '' : ' --apply --yes-spend'}`;\n\n  if (dryRun) {\n    const resolved = resolveAiEcosystemCli();\n    if (!resolved) return unreachablePayload('holo_from_scratch_launch');\n    // Preview by running the CLI in its own dry-run mode (no --apply) — free, no spend.\n    const res = await runCli(resolved.cli, resolved.root, previewArgv);\n    const spendAuthorityChallenge = parseSpendAuthorityChallenge(res.stdout);\n    const payload: JsonRecord = {\n      model,\n      dryRun: true,\n      aiEcosystemRoot: resolved.root,\n      previewCommand,\n      stdout: res.stdout,\n      stderr: res.stderr || undefined,\n      exitCode: res.code,\n      callerAuthed: Boolean(signingCtx?.signedRequest && signingCtx.signingValid),\n      spendAuthorityChallenge: spendAuthorityChallenge ?? undefined,\n    };\n    return {\n      ok: res.ok,\n      ...payload,\n      spendIntent: false,\n      receipt: {\n        schema: 'holo.from-scratch.mcp-operation-receipt.v1',\n        action: 'launch',\n        generatedAt: new Date().toISOString(),\n        ...payload,\n        receiptHash: hashPayload(payload),\n      },\n    };\n  }\n\n  const authority = await verifySpendAuthority(args, signingCtx);\n  if (!isVerifiedSpendAuthority(authority)) {\n    return {\n      ...authority,\n      model,\n      previewCommand,\n      spendIntent: false,\n      message:\n        'Applied from-scratch launch requires a signed spend authority from the same active HoloMesh seat as the signed MCP request. Re-run with dryRun:true to preview.',\n    };\n  }\n\n  const resolved = resolveAiEcosystemCli();\n  if (!resolved) return unreachablePayload('holo_from_scratch_launch');\n\n  // Preserve the original signed envelope across the process boundary. The host\n  // re-verifies and atomically consumes it; --yes-spend is intent, not authority.\n  const res = await withRestrictedAuthorityFile(authority.envelope, (authorityPath) =>\n    runCli(resolved.cli, resolved.root, [\n      ...cliArgv,\n      '--apply',\n      '--yes-spend',\n      '--spend-authority-file',\n      authorityPath,\n      '--spend-authority-hash',\n      authority.authorityHash,\n      '--spend-authority-caller',\n      authority.caller,\n    ])\n  );\n  const payload: JsonRecord = {\n    model,\n    dryRun: false,\n    aiEcosystemRoot: resolved.root,\n    previewCommand,\n    spendAuthorityHash: authority.authorityHash,\n    spendAuthorityCaller: authority.caller,\n    callerAuthed: true,\n    stdout: res.stdout,\n    stderr: res.stderr || undefined,\n    exitCode: res.code,\n  };\n  return {\n    ok: res.ok,\n    ...payload,\n    spendIntent: true,\n    spendGovernedBy:\n      'ai-ecosystem/scripts/train-from-scratch.mjs (signed seat authority + free-first proof + live purchased-compute cap enforced host-side)',\n    receipt: {\n      schema: 'holo.from-scratch.mcp-operation-receipt.v1',\n      action: 'launch',\n      generatedAt: new Date().toISOString(),\n      ...payload,\n      receiptHash: hashPayload(payload),\n    },\n  };\n}\n\n/**\n * Handle from-scratch tool calls.\n *\n * @param signingCtx Verified MCP request identity, threaded from index.ts. Applied\n *   launch requires a signed active seat; unsigned/stdio callers remain preview-only.\n */\nexport async function handleFromScratchTool(\n  name: string,\n  args: JsonRecord,\n  signingCtx?: SigningContext\n): Promise<unknown | null> {\n  switch (name) {\n    case 'holo_from_scratch_status':\n      return status(args);\n    case 'holo_from_scratch_launch':\n      return launch(args, signingCtx);\n    default:\n      return null;\n  }\n}\n","/**\n * MCP Tool Definitions for HoloScript\n *\n * Provides AI agents with tools to parse, validate, generate, and render HoloScript.\n * Includes graph understanding, IDE features, and Brittney-Lite AI assistant (free tier).\n */\n\nimport { Tool } from '@modelcontextprotocol/sdk/types.js';\nimport { graphTools } from './graph-tools';\nimport { ideTools } from './ide-tools';\nimport { brittneyLiteTools } from './brittney-lite';\nimport { PluginManager } from './PluginManager';\nimport {\n  codebaseTools,\n  graphRagTools,\n  absorbServiceTools,\n  absorbTypescriptTools,\n  oracleTools,\n} from '@holoscript/absorb-service/mcp';\nimport { selfImproveTools } from './self-improve-tools';\nimport { gltfImportTools } from './gltf-import-tools';\nimport { generateMeshTools } from './generate-mesh-tools';\nimport { editHoloTools } from './edit-holo-tools';\nimport { wisdomGotchaTools } from './wisdom-gotcha-tools';\nimport { receiptQueryTools } from './receipt-query-tools';\nimport { serviceContractTools } from './service-contract-tools';\nimport { fairnessTools } from './fairness-mcp-tools';\nimport { validationTools } from './validation-tools';\nimport { agentOrchestrationTools } from './agent-orchestration-tools';\nimport { agentIdentityTools } from './agent-identity-tools';\nimport { observabilityTools } from './observability-tools';\nimport { pluginManagementTools } from './plugin-management-tools';\nimport { holoshellDownloadRecoveryToolDefinitions } from './holoshell-download-recovery-tools';\nimport { economyTools } from './economy-tools';\nimport { developerTools } from './developer-tools';\nimport { holomeshTools } from './holomesh/index';\nimport { protocolTools } from './protocol-tools';\nimport { codeHealthTools } from './code-health-tools';\nimport { simulationTools } from './simulation-tools';\nimport { holoCiTools } from './holo-ci-tools';\nimport { worldRenderTools } from './world-render-tools';\nimport { absorbProvenanceTools } from './absorb-provenance-tools';\nimport { toolingDiscoveryTools } from './tooling-discovery-tools';\nimport { compilerTools } from './compiler-tools';\nimport { networkingTools } from './networking-tools';\nimport { snapshotTools } from './snapshot-tools';\nimport { monitoringTools } from './monitoring-tools';\nimport { holotestTools } from './holotest-tools';\nimport { refactorCodegenTools } from './refactor-codegen-tools';\nimport { traitTools } from './trait-tools';\nimport { hololandMcpTools } from './hololand-mcp-tools';\nimport { robotAiMcpTools } from './robot-ai-mcp-tools';\nimport { hologramToolDefinitions } from './hologram-mcp-tools';\nimport { estimateTaskDurationTools } from './tools/estimate_task_duration';\nimport { kolmogorovTaskScoreTools } from './tools/kolmogorov_task_score';\nimport { criticTools } from './critic-tools';\nimport { founderTools } from './founder-tools';\nimport { premortemTools } from './premortem-tools';\nimport { oracleMcpTools } from './oracle-mcp-tools';\nimport { secretsBrokerTools } from './secrets-broker-tools';\nimport { holoTunnelTools } from './holo-tunnel-tools';\nimport { simulationBillingTools } from './simulation-billing-tools';\nimport { rigMatchSkeletonToolDefinition } from './tools/rig_match_skeleton';\nimport { memoryTools } from './memory-tools';\nimport { holotuneToolDefinitions } from './holotune-mcp-tools';\nimport { fromScratchToolDefinitions } from './from-scratch-mcp-tools';\n\n/**\n * All MCP tools for HoloScript\n *\n * Core tools (15) + Graph tools (6) + IDE tools (9) + Brittney-Lite AI (4) = 34 tools\n */\nexport const coreTools: Tool[] = [\n  // === PARSING ===\n  {\n    name: 'parse_hs',\n    description:\n      'Parse HoloScript (.hs) or HoloScript Plus (.hsplus) code into an AST. Use for understanding structure of existing code.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        code: {\n          type: 'string',\n          description: 'The HoloScript or HoloScript Plus code to parse',\n        },\n        format: {\n          type: 'string',\n          enum: ['hs', 'hsplus'],\n          description: 'The format of the input code. Defaults to hsplus (auto-detects)',\n        },\n        includeSourceMap: {\n          type: 'boolean',\n          description: 'Include source map for debugging',\n        },\n      },\n      required: ['code'],\n    },\n  },\n  {\n    name: 'parse_holo',\n    description:\n      'Parse a .holo composition file into an AST. Use for scene-centric declarative files with compositions.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        code: {\n          type: 'string',\n          description: 'The .holo composition code to parse',\n        },\n        strict: {\n          type: 'boolean',\n          description: 'Use strict parsing mode (fails on warnings)',\n        },\n      },\n      required: ['code'],\n    },\n  },\n  {\n    name: 'parse_pipeline',\n    description:\n      'Parse a .hs pipeline definition into a structured pipeline AST (sources, transforms, filters, sinks).',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        code: {\n          type: 'string',\n          description: 'The pipeline source code (pipeline \"Name\" { ... })',\n        },\n      },\n      required: ['code'],\n    },\n  },\n  {\n    name: 'compile_pipeline',\n    description: 'Compile a .hs pipeline into a runnable Node.js ESM module (index.mjs).',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        code: {\n          type: 'string',\n          description: 'The pipeline source code to compile',\n        },\n        target: {\n          type: 'string',\n          enum: ['node'],\n          description: 'Compilation target (currently node)',\n        },\n        moduleName: {\n          type: 'string',\n          description: 'Optional output module filename hint (e.g., index.mjs)',\n        },\n      },\n      required: ['code'],\n    },\n  },\n\n  // === VALIDATION ===\n  {\n    name: 'validate_holoscript',\n    description:\n      'Validate HoloScript code for syntax errors, unknown traits, and best practices. Returns AI-friendly error messages with suggestions.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        code: {\n          type: 'string',\n          description: 'The HoloScript code to validate (any format: .hs, .hsplus, .holo)',\n        },\n        content: {\n          type: 'string',\n          description: 'Compatibility alias for code. Prefer code for new callers.',\n        },\n        format: {\n          type: 'string',\n          enum: ['hs', 'hsplus', 'holo', 'auto'],\n          description: 'The format of the input. Defaults to auto-detect.',\n        },\n        includeWarnings: {\n          type: 'boolean',\n          description: 'Include warnings in addition to errors',\n        },\n        includeSuggestions: {\n          type: 'boolean',\n          description: 'Include fix suggestions for each error',\n        },\n      },\n      required: ['code'],\n    },\n  },\n\n  // === TRAITS ===\n  {\n    name: 'list_traits',\n    description:\n      'List traits available in HoloScript. Category slugs match packages/core/src/traits/constants/*.ts (basename without .ts). Legacy short names (interaction, physics, …) still work. Use category=all for full list plus categorySlugs.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        category: {\n          type: 'string',\n          description:\n            \"Filter: 'all' (default), a core slug (e.g. core-vr-interaction, physics-expansion), or a legacy alias (interaction, physics, visual, …).\",\n        },\n      },\n    },\n  },\n  {\n    name: 'explain_trait',\n    description:\n      'Get detailed documentation for a specific trait including parameters and example usage.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        trait: {\n          type: 'string',\n          description: 'The trait name (with or without @, e.g., \"grabbable\" or \"@grabbable\")',\n        },\n      },\n      required: ['trait'],\n    },\n  },\n  {\n    name: 'suggest_traits',\n    description:\n      'Suggest appropriate VR traits for an object based on its description. For browsing by category, use list_traits (slugs align with packages/core/src/traits/constants).',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        description: {\n          type: 'string',\n          description:\n            'Description of the object (e.g., \"a sword that can be picked up and thrown\")',\n        },\n        context: {\n          type: 'string',\n          description: 'Additional context about the scene or use case',\n        },\n      },\n      required: ['description'],\n    },\n  },\n  {\n    name: 'suggest_universal_traits',\n    description:\n      'Suggest v6 universal platform traits for a service or infrastructure component. ' +\n      'Covers 8 domains: service, contract, data, network, pipeline, metric, container, resilience.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        description: {\n          type: 'string',\n          description:\n            'Description of the service or component (e.g., \"REST API with JWT auth and Redis caching\")',\n        },\n        domain: {\n          type: 'string',\n          enum: [\n            'service',\n            'contract',\n            'data',\n            'network',\n            'pipeline',\n            'metric',\n            'container',\n            'resilience',\n          ],\n          description:\n            'Filter suggestions to a specific domain. Omit for cross-domain suggestions.',\n        },\n        context: {\n          type: 'string',\n          description: 'Additional context about the system architecture or use case',\n        },\n      },\n      required: ['description'],\n    },\n  },\n  {\n    name: 'suggest_2d_traits',\n    description: 'Suggest Semantic2D traits for a 2D UI element based on its description.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        description: {\n          type: 'string',\n          description: 'Description of the UI element (e.g., \"a primary call to action button\")',\n        },\n        context: {\n          type: 'string',\n          description: 'Additional context about the dashboard or app',\n        },\n      },\n      required: ['description'],\n    },\n  },\n\n  // === CODE GENERATION ===\n  {\n    name: 'generate_object',\n    description: 'Generate a HoloScript object definition from a natural language description.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        description: {\n          type: 'string',\n          description: 'Natural language description of the object to create',\n        },\n        format: {\n          type: 'string',\n          enum: ['hs', 'hsplus', 'holo'],\n          description: 'Output format. Defaults to hsplus.',\n        },\n        includeDocs: {\n          type: 'boolean',\n          description: 'Include inline documentation comments',\n        },\n      },\n      required: ['description'],\n    },\n  },\n  {\n    name: 'generate_scene',\n    description: 'Generate a complete .holo scene composition from a natural language description.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        description: {\n          type: 'string',\n          description: 'Natural language description of the scene to create',\n        },\n        style: {\n          type: 'string',\n          enum: ['minimal', 'detailed', 'production'],\n          description: 'Level of detail in the generated code',\n        },\n        features: {\n          type: 'array',\n          items: { type: 'string' },\n          description: 'Specific features to include (e.g., [\"physics\", \"audio\", \"networking\"])',\n        },\n      },\n      required: ['description'],\n    },\n  },\n  {\n    name: 'generate_semantic_ui',\n    description: 'Generate a V6 Semantic2D UI composition from a natural language description.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        description: {\n          type: 'string',\n          description:\n            'Natural language description of the UI to create (e.g., \"an admin dashboard with a sidebar and metric cards\")',\n        },\n      },\n      required: ['description'],\n    },\n  },\n\n  // === DOCUMENTATION ===\n  {\n    name: 'get_syntax_reference',\n    description: 'Get syntax documentation for a specific HoloScript construct.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        topic: {\n          type: 'string',\n          enum: [\n            'composition',\n            'template',\n            'object',\n            'environment',\n            'logic',\n            'animation',\n            'physics',\n            'events',\n            'networking',\n            'traits',\n            'orb',\n            'spatial_group',\n          ],\n          description:\n            'The syntax topic to get documentation for. Prefer composition/template/object (modern) over orb/spatial_group (legacy).',\n        },\n      },\n      required: ['topic'],\n    },\n  },\n  {\n    name: 'get_examples',\n    description:\n      'Browse or fetch HoloScript examples. Omit `pattern` (or pass \"list\") to browse ' +\n      'the full audited repo catalog + inventory (counts by format/category, real example ' +\n      'paths with parser status, link to examples/INDEX.md). Pass a slug (\"interactive-object\"), ' +\n      'a repo path (\"examples/physics/...\"), or a keyword (\"physics\", \"robot\", \"teleport\") to ' +\n      'fetch a specific example — inline patterns return runnable code, catalog entries return ' +\n      'the repo path + status.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        pattern: {\n          type: 'string',\n          description:\n            'Optional. A slug, repo path, or keyword. Omit (or use \"list\"/\"all\") to browse the ' +\n            'full example catalog instead of fetching one example.',\n        },\n      },\n    },\n  },\n  {\n    name: 'explain_code',\n    description: 'Get a plain English explanation of what HoloScript code does.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        code: {\n          type: 'string',\n          description: 'The HoloScript code to explain',\n        },\n        detail: {\n          type: 'string',\n          enum: ['brief', 'detailed', 'tutorial'],\n          description: 'Level of detail in the explanation',\n        },\n      },\n      required: ['code'],\n    },\n  },\n  {\n    name: 'analyze_code',\n    description: 'Analyze HoloScript code for complexity, performance, and best practices.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        code: {\n          type: 'string',\n          description: 'The HoloScript code to analyze',\n        },\n      },\n      required: ['code'],\n    },\n  },\n\n  // === RENDERING (requires HOLOSCRIPT_RENDER_URL; falls back to playground link) ===\n  {\n    name: 'render_preview',\n    description:\n      'Generate a preview of a HoloScript scene. When HOLOSCRIPT_RENDER_URL is configured returns a real image URL (png/gif/mp4/webp). Without it, returns a playground link you can open in a browser — no static image is produced locally.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        code: {\n          type: 'string',\n          description: 'The HoloScript code to render',\n        },\n        format: {\n          type: 'string',\n          enum: ['png', 'gif', 'mp4', 'webp'],\n          description: 'Output format. Defaults to png.',\n        },\n        resolution: {\n          type: 'array',\n          items: { type: 'number' },\n          description: 'Resolution [width, height]. Defaults to [800, 600].',\n        },\n        camera: {\n          type: 'object',\n          properties: {\n            position: {\n              type: 'array',\n              items: { type: 'number' },\n            },\n            target: {\n              type: 'array',\n              items: { type: 'number' },\n            },\n          },\n          description: 'Camera position and target',\n        },\n        duration: {\n          type: 'number',\n          description: 'Animation duration in milliseconds (for gif/mp4)',\n        },\n        quality: {\n          type: 'string',\n          enum: ['draft', 'preview', 'production'],\n          description: 'Render quality level',\n        },\n      },\n      required: ['code'],\n    },\n  },\n\n  // === SHARING (requires HOLOSCRIPT_RENDER_URL for rich previews; always produces playground link) ===\n  {\n    name: 'create_share_link',\n    description:\n      'Create a shareable link for HoloScript code. When HOLOSCRIPT_RENDER_URL is configured, returns full social preview metadata (QR code, Twitter card). Without it, returns a playground URL with the code embedded. Useful for X posts.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        code: {\n          type: 'string',\n          description: 'The HoloScript code to share',\n        },\n        title: {\n          type: 'string',\n          description: 'Title for the shared scene',\n        },\n        description: {\n          type: 'string',\n          description: 'Description for social previews',\n        },\n        platform: {\n          type: 'string',\n          enum: ['x', 'generic', 'codesandbox', 'stackblitz'],\n          description: 'Optimize for specific platform. Defaults to x.',\n        },\n      },\n      required: ['code'],\n    },\n  },\n\n  // === TRANSFORMATION ===\n  {\n    name: 'convert_format',\n    description: 'Convert HoloScript code between formats (.hs, .hsplus, .holo).',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        code: {\n          type: 'string',\n          description: 'The code to convert',\n        },\n        from: {\n          type: 'string',\n          enum: ['hs', 'hsplus', 'holo'],\n          description: 'Source format',\n        },\n        to: {\n          type: 'string',\n          enum: ['hs', 'hsplus', 'holo'],\n          description: 'Target format',\n        },\n      },\n      required: ['code', 'to'],\n    },\n  },\n];\n\n/**\n * Text-to-3D pipeline tools (requires MESHY_API_KEY or TRIPO_API_KEY)\n */\nexport const textTo3DTools: Tool[] = [\n  {\n    name: 'generate_3d_object',\n    description:\n      'Generate a 3D object from a text description using AI (Meshy/Tripo). ' +\n      'Returns a .holo file with the model reference, auto-suggested traits, and optional native auto-rigging. ' +\n      'Requires MESHY_API_KEY or TRIPO_API_KEY environment variable.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        description: {\n          type: 'string',\n          description:\n            'Text description of the 3D object to generate (e.g. \"a glowing sword\", \"wooden treasure chest\")',\n        },\n        provider: {\n          type: 'string',\n          enum: ['meshy', 'tripo'],\n          description: 'Which text-to-3D provider to use. Defaults to meshy.',\n        },\n        style: {\n          type: 'string',\n          enum: ['realistic', 'cartoon', 'low-poly', 'pbr'],\n          description: 'Art style for the generated model. Defaults to pbr.',\n        },\n        objectName: {\n          type: 'string',\n          description: 'Optional custom name for the generated object.',\n        },\n        rig: {\n          type: 'string',\n          enum: ['humanoid', 'custom'],\n          description:\n            'Optional native HoloScript auto-rig pipeline. humanoid emits @generated_mesh + @auto_rig + bound @skeleton metadata; custom emits a compact envelope skeleton.',\n        },\n        pose: {\n          type: 'string',\n          enum: ['t-pose', 'a-pose'],\n          description: 'Bind pose for native auto-rigging. Defaults to t-pose when rig is provided.',\n        },\n      },\n      required: ['description'],\n    },\n  },\n];\n\n/**\n * Browser control tools (AI-controlled browser preview)\n */\nexport const browserControlTools: Tool[] = [\n  {\n    name: 'browser_launch',\n    description:\n      'Launch HoloScript file in browser preview with AI control. ' +\n      'Opens a browser window showing the 3D scene and returns a session ID for further control.',\n    inputSchema: {\n      type: 'object' as const,\n      properties: {\n        holoscriptFile: {\n          type: 'string',\n          description: 'Path to HoloScript file to preview, or an http/https URL',\n        },\n        width: { type: 'number', description: 'Browser viewport width (default: 1280)' },\n        height: { type: 'number', description: 'Browser viewport height (default: 720)' },\n        headless: {\n          type: 'boolean',\n          description: 'Run in headless mode without visible window (default: false)',\n        },\n      },\n      required: ['holoscriptFile'],\n    },\n  },\n  {\n    name: 'browser_execute',\n    description:\n      'Execute JavaScript in the browser to inspect or validate HoloScript scenes. ' +\n      'Use for trait validation, performance checking, and scene manipulation.',\n    inputSchema: {\n      type: 'object' as const,\n      properties: {\n        sessionId: {\n          type: 'string',\n          description: 'Browser session ID returned by browser_launch',\n        },\n        script: {\n          type: 'string',\n          description: 'JavaScript code to execute in the browser context',\n        },\n        captureConsole: {\n          type: 'boolean',\n          description: 'Capture console.log output (default: true)',\n        },\n      },\n      required: ['sessionId', 'script'],\n    },\n  },\n  {\n    name: 'browser_screenshot',\n    description:\n      'Take screenshot of HoloScript preview for visual validation and regression testing. ' +\n      'Returns base64-encoded image or saves to file.',\n    inputSchema: {\n      type: 'object' as const,\n      properties: {\n        sessionId: {\n          type: 'string',\n          description: 'Browser session ID returned by browser_launch',\n        },\n        outputPath: {\n          type: 'string',\n          description: 'Optional file path to save screenshot to disk',\n        },\n        type: {\n          type: 'string',\n          enum: ['png', 'jpeg'],\n          description: 'Image format (default: png)',\n        },\n        quality: {\n          type: 'number',\n          description: 'JPEG quality 0-100 (default: 90)',\n          minimum: 0,\n          maximum: 100,\n        },\n        fullPage: {\n          type: 'boolean',\n          description: 'Capture full scrollable page (default: false)',\n        },\n      },\n      required: ['sessionId'],\n    },\n  },\n];\n\n/**\n * Hololand training data generation tools\n */\nexport const hololandTrainingTools: Tool[] = [\n  {\n    name: 'generate_hololand_training',\n    description:\n      'Generate Brittney v6.0 Hololand fine-tune training data as Alpaca-style JSONL. ' +\n      'Covers 9 categories × 4 difficulties including spatial objects, VR interactions, ' +\n      'multiplayer networking, Web3/Zora, AI generation, and more. ' +\n      'Returns JSONL string or saves to file.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        variations_per_example: {\n          type: 'number',\n          description: 'Number of variations to generate per canonical example (default: 4)',\n        },\n        category: {\n          type: 'string',\n          enum: [\n            'spatial_objects',\n            'vr_interactions',\n            'multiplayer_networking',\n            'web3_zora',\n            'ai_generation',\n            'scene_composition',\n            'system_components',\n            'error_correction',\n            'edge_cases',\n            'all',\n          ],\n          description: 'Filter to a specific category or \"all\" (default: all)',\n        },\n        output_file: {\n          type: 'string',\n          description:\n            'Optional file path to save JSONL output (e.g. \"hololand-substrate-v1.jsonl\")',\n        },\n      },\n      required: [],\n    },\n  },\n];\n\n/**\n * All MCP tools — single source of truth.\n * Both stdio (index.ts) and HTTP (http-server.ts) import this array.\n * Never add tools to index.ts or http-server.ts separately.\n */\nexport const tools: Tool[] = [\n  ...coreTools,\n  ...graphTools,\n  ...ideTools,\n  ...brittneyLiteTools,\n  ...textTo3DTools,\n  ...browserControlTools,\n  ...hololandTrainingTools,\n  ...codebaseTools,\n  ...graphRagTools,\n  ...selfImproveTools,\n  ...wisdomGotchaTools,\n  ...gltfImportTools,\n  ...generateMeshTools,\n  ...editHoloTools,\n  ...absorbServiceTools,\n  ...serviceContractTools,\n  ...fairnessTools,\n  ...validationTools,\n  ...absorbTypescriptTools,\n  ...agentOrchestrationTools,\n  ...agentIdentityTools,\n  ...observabilityTools,\n  ...pluginManagementTools,\n  ...holoshellDownloadRecoveryToolDefinitions,\n  ...economyTools,\n  ...developerTools,\n  ...holomeshTools,\n  ...protocolTools,\n  ...codeHealthTools,\n  ...oracleTools,\n  ...simulationTools,\n  ...holoCiTools,\n  ...worldRenderTools,\n  ...absorbProvenanceTools,\n  ...toolingDiscoveryTools,\n  ...compilerTools,\n  ...networkingTools,\n  ...snapshotTools,\n  ...monitoringTools,\n  ...holotestTools,\n  ...refactorCodegenTools,\n  ...traitTools,\n  ...hololandMcpTools,\n  ...robotAiMcpTools,\n  ...hologramToolDefinitions,\n  ...estimateTaskDurationTools,\n  ...kolmogorovTaskScoreTools,\n  ...criticTools,\n  ...founderTools,\n  ...premortemTools,\n  ...oracleMcpTools,\n  ...secretsBrokerTools,\n  ...receiptQueryTools,\n  ...holoTunnelTools,\n  ...simulationBillingTools,\n  ...holotuneToolDefinitions,\n  // Library-driven from-scratch pretraining lane (dispatches ai-ecosystem CLI)\n  ...fromScratchToolDefinitions,\n  // Skeleton interop (G4 — rig_match_skeleton)\n  rigMatchSkeletonToolDefinition,\n  // Native memory substrate (Slice B1 — shared agent memory surface)\n  ...memoryTools,\n];\n\nconst toolDescriptionOverrides: Record<string, string> = {\n  render_world_on_fleet:\n    'Build or submit a HoloScript world render workload through the GPU-fleet orchestrator. Safe by default: dryRun is true unless explicitly set false. Compile-backed targets return render-ready data and receipts; raster targets fail closed until the render-engine image exists.',\n  compile_to_gaussian_train:\n    'Compile a @gaussian_train trait into a sovereign Gaussian-splat training job. Emits executor, dataset refs, hyperparameters, and validation metadata. Use compile_to_3dgs for KHR_gaussian_splatting export.',\n  compile_to_edge:\n    'Compile HoloScript to an edge-device deployment bundle for Ollama-capable Linux nodes. Default runtime is the canonical TS AgentRunner with gates and receipts; legacy python runtime remains explicit and deprecated.',\n  compile_to_bot_swarm:\n    'Compile an MMO composition to an in-process Colyseus bot-swarm balance harness. Emits runBotSwarm and assertBalance helpers that exercise legal moves, anti-cheat checks, and tick-budget receipts.',\n  compile_to_dungeon_instance:\n    'Compile dungeon_instance blocks into a server-authoritative instance-pool module with completion receipts and compile-time validation of declared completion quests.',\n  compile_to_world_shard:\n    'Compile world_shard blocks into a shard registry, shardForPosition helper, and handoff router. Cross-shard handoffs are receipt-sealed and validated against declared neighbors and bounds.',\n  compile_to_mcp_server:\n    'Compile a trait/brain composition with llm_agent, rag_knowledge, agent_memory, or tool traits into a standalone MCP server TypeScript module with Tool[] definitions, adapter registration, wiring checks, and governance metadata.',\n  compile_to_qasm:\n    'Compile HoloScript quantum-circuit traits to OpenQASM 3.0 plus metadata such as qubit counts, depth, circuit type, backend recommendation, warnings, molecule, and weight matrix. Supports vqe, qaoa, and stub circuits.',\n  create_shard:\n    'Create a HoloLand shard with region, capacity, and persistence metadata. Shards partition world state for MMO zones and runtime receipts.',\n  create_place:\n    'Create a HoloLand Place inside a Zone, with optional coordinates, owner, tags, AR anchors, and metadata for navigation, quests, and discovery.',\n  create_location_quest:\n    'Create a location quest bound to a Place or Zone, including objective, reward, start/end times, requirements, and optional AR marker metadata.',\n  hololand_shard_status:\n    'Return shard health, capacity, region, zone counts, active session hints, and integrity metadata for a HoloLand shard.',\n  hololand_publish_zone:\n    'Publish a Zone with tier and visibility metadata, returning a publication receipt for HoloLand discovery and runtime validation.',\n  hololand_create_geo_anchor:\n    'Create a Twin Earth geo anchor that binds a GPS coordinate to a Place or Zone for location gameplay, geofencing, and AR fallback.',\n  hololand_update_npc:\n    \"Update a HoloLand NPC's dialogue, schedule, quest hooks, safety limits, memory tags, and metadata.\",\n  sim_quote:\n    'Quote a paid simulation run without executing it. Returns estimated units, cost, policy checks, idempotency data, and payment instructions.',\n  sim_run_paid:\n    'Run a paid simulation after validating policy, idempotency, and payment proof. Returns execution status, receipt fields, and settlement metadata.',\n  rig_match_skeleton:\n    'Match a source skeleton to a target rig profile and return bone mapping, confidence, missing bones, and retargeting hints.',\n};\n\nfor (const tool of tools) {\n  const description = toolDescriptionOverrides[tool.name];\n  if (description) tool.description = description;\n}\n\n// Tool name type for type safety\nexport type ToolName = (typeof tools)[number]['name'];\n\n// Helper to get tool by name\nexport function getTool(name: string): Tool | undefined {\n  return tools.find((t) => t.name === name);\n}\n\n// Re-export tool arrays for selective registration\nexport { graphTools, ideTools, brittneyLiteTools, agentIdentityTools };\n","/**\n * Dynamic Tenant Authentication\n *\n * Bridges the static OAuth21 configuration to a high-speed database store\n * (PostgreSQL or Upstash Redis) to allow multi-tenant, enterprise consumption.\n *\n * @module security/tenant-auth\n */\n\nimport type { TokenIntrospection } from './oauth21';\n\nexport interface TenantContext {\n  tenantId: string;\n  subscriptionTier: 'free' | 'pro' | 'enterprise';\n  limits: {\n    maxVideoDurationSec: number;\n    maxMediaResolution: number;\n    allowProcessExec: boolean;\n    rateLimitRequestsPerMin: number;\n  };\n}\n\nexport type TokenIntrospectionWithTenant = TokenIntrospection & {\n  tenantContext?: TenantContext;\n};\n\nlet pgPool: any = null;\n\n/**\n * SEC-T09: Build node-postgres SSL options with cert validation ON by default.\n *\n * Production: `rejectUnauthorized: true`. The CA bundle is read from\n * `PG_SSL_CA` (raw PEM) or `PG_SSL_CA_B64` (base64-encoded PEM). Providers\n * that use publicly-trusted roots (managed cloud Postgres) work without a\n * CA override because node uses the system trust store.\n *\n * Development: allow `PG_SSL_INSECURE=1` as an explicit opt-in escape hatch\n * for local Docker Compose setups with self-signed certs. Never honored in\n * production regardless of the flag.\n *\n * `DATABASE_SSL=false` still disables SSL entirely for local non-TLS DBs.\n */\nfunction buildPostgresSslOptions(): false | { rejectUnauthorized: boolean; ca?: string } {\n  if (process.env.DATABASE_SSL === 'false') {\n    return false;\n  }\n\n  const isProd = process.env.NODE_ENV === 'production';\n  const devInsecure = !isProd && process.env.PG_SSL_INSECURE === '1';\n\n  let ca: string | undefined;\n  if (process.env.PG_SSL_CA) {\n    ca = process.env.PG_SSL_CA;\n  } else if (process.env.PG_SSL_CA_B64) {\n    try {\n      ca = Buffer.from(process.env.PG_SSL_CA_B64, 'base64').toString('utf8');\n    } catch {\n      /* fall through to system trust store */\n    }\n  }\n\n  return devInsecure\n    ? { rejectUnauthorized: false }\n    : { rejectUnauthorized: true, ...(ca ? { ca } : {}) };\n}\n\n/**\n * Development-only escape hatch: no hardcoded keys in the repo.\n * Set TENANT_AUTH_DEV_MOCK_KEY locally to a private value; never in production.\n */\nfunction tryDevMockTenant(apiKey: string): TenantContext | undefined {\n  if (process.env.NODE_ENV !== 'development') {\n    return undefined;\n  }\n  const devKey = process.env.TENANT_AUTH_DEV_MOCK_KEY?.trim();\n  if (!devKey || devKey !== apiKey) {\n    return undefined;\n  }\n  console.warn(\n    '[TenantAuth] DEV ONLY: TENANT_AUTH_DEV_MOCK_KEY matched — granting mock enterprise tenant. Disable outside local development.'\n  );\n  return {\n    tenantId: 'tenant_dev_mock',\n    subscriptionTier: 'enterprise',\n    limits: {\n      maxVideoDurationSec: 3600,\n      maxMediaResolution: 4096,\n      allowProcessExec: true,\n      rateLimitRequestsPerMin: 1000,\n    },\n  };\n}\n\n/**\n * Validates a dynamic API key against the configured backend store.\n */\nexport async function validateTenantKey(\n  apiKey: string\n): Promise<TokenIntrospectionWithTenant | null> {\n  let tenant: TenantContext | undefined;\n\n  // 1. Try PostgreSQL if configured\n  if (process.env.DATABASE_URL) {\n    try {\n      if (!pgPool) {\n        const { Pool } = require('pg');\n        pgPool = new Pool({\n          connectionString: process.env.DATABASE_URL,\n          // SEC-T09: previously used `rejectUnauthorized: false`, which\n          // negotiates TLS but skips cert validation — MITM on the network\n          // path between app and DB could intercept auth queries. Now\n          // defaults to strict verification; callers provide the PEM-encoded\n          // CA bundle via `PG_SSL_CA` (raw) or `PG_SSL_CA_B64` (base64). In\n          // non-production we still allow the lax mode behind an explicit\n          // env opt-in to keep local dev ergonomic.\n          ssl: buildPostgresSslOptions(),\n        });\n      }\n      const res = await pgPool.query(\n        'SELECT tenant_id, tier, limits FROM api_keys WHERE key = $1 AND revoked = false',\n        [apiKey]\n      );\n      if (res.rows.length > 0) {\n        tenant = {\n          tenantId: res.rows[0].tenant_id,\n          subscriptionTier: res.rows[0].tier,\n          limits:\n            typeof res.rows[0].limits === 'string'\n              ? JSON.parse(res.rows[0].limits)\n              : res.rows[0].limits,\n        };\n      }\n    } catch (e) {\n      console.warn('[TenantAuth] DB query failed:', e);\n    }\n  }\n\n  // 2. Try Upstash Redis if configured (fastest)\n  //\n  // SEC-T08: the API key was previously URL-interpolated straight into the\n  // Upstash REST path. A key value containing `/`, `?`, `#`, or `&` could\n  // trick the request into hitting a different Upstash verb or smuggling\n  // querystring parameters. We URL-encode the key before interpolation and\n  // also enforce a conservative format check so malformed keys are rejected\n  // before any outbound request.\n  if (\n    !tenant &&\n    process.env.UPSTASH_REDIS_REST_URL &&\n    process.env.UPSTASH_REDIS_REST_TOKEN &&\n    /^[A-Za-z0-9_\\-]{16,128}$/.test(apiKey)\n  ) {\n    try {\n      const encodedKey = encodeURIComponent(apiKey);\n      const resp = await fetch(`${process.env.UPSTASH_REDIS_REST_URL}/get/apikey:${encodedKey}`, {\n        headers: { Authorization: `Bearer ${process.env.UPSTASH_REDIS_REST_TOKEN}` },\n      });\n      const data = await resp.json();\n      if (data && data.result) {\n        tenant = JSON.parse(data.result);\n      }\n    } catch (e) {\n      console.warn('[TenantAuth] Upstash query failed:', e);\n    }\n  }\n\n  // 3. Optional dev-only mock (explicit env key only — never a repo-baked secret)\n  if (!tenant) {\n    const dev = tryDevMockTenant(apiKey);\n    if (dev) tenant = dev;\n  }\n\n  // If found, grant scopes dynamically based on tier\n  if (tenant) {\n    const scopes = ['tools:read', 'tools:write', 'tools:codebase', 'tools:browser'];\n    if (tenant.subscriptionTier === 'enterprise') {\n      scopes.push('tools:admin');\n      scopes.push('admin:*'); // Give enterprises full standard access\n    }\n\n    return {\n      active: true,\n      scopes,\n      agentId: `agent_${tenant.tenantId}`,\n      clientId: `client_${tenant.tenantId}`,\n      tenantContext: tenant,\n    };\n  }\n\n  return null;\n}\n","/**\n * GitHub Token Authentication for MCP Server\n *\n * Resolves GitHub OAuth tokens to TokenIntrospection objects.\n * Lightweight LRU cache avoids GitHub API rate limits.\n * Shares the same DATABASE_URL as absorb-service for user identity.\n */\n\nimport type { TokenIntrospection } from './oauth21';\n\ninterface GitHubUser {\n  id: number;\n  login: string;\n  name: string | null;\n  avatar_url: string;\n}\n\ninterface CachedIdentity {\n  introspection: TokenIntrospection;\n  expiresAt: number;\n}\n\nconst CACHE_TTL_MS = parseInt(process.env.GITHUB_TOKEN_CACHE_TTL_MS || '300000', 10);\nconst CACHE_MAX = 500;\nconst cache = new Map<string, CachedIdentity>();\n\nconst ADMIN_USERNAMES = new Set(\n  (process.env.ADMIN_GITHUB_USERNAMES || 'brianonbased-dev')\n    .split(',')\n    .map((s) => s.trim().toLowerCase())\n    .filter(Boolean)\n);\n\nasync function fetchGitHubUser(token: string): Promise<GitHubUser | null> {\n  try {\n    const res = await fetch('https://api.github.com/user', {\n      headers: {\n        Authorization: `token ${token}`,\n        Accept: 'application/vnd.github.v3+json',\n        'User-Agent': 'holoscript-mcp/6.0.0',\n      },\n      signal: AbortSignal.timeout(5000),\n    });\n    if (!res.ok) return null;\n    return (await res.json()) as GitHubUser;\n  } catch {\n    return null;\n  }\n}\n\n/**\n * Resolve a GitHub token to a TokenIntrospection.\n * Returns null if the token is not a valid GitHub token.\n */\nexport async function resolveGitHubTokenForMcp(token: string): Promise<TokenIntrospection | null> {\n  // Cache check\n  const cached = cache.get(token);\n  if (cached && Date.now() < cached.expiresAt) {\n    return cached.introspection;\n  }\n  if (cached) cache.delete(token);\n\n  const ghUser = await fetchGitHubUser(token);\n  if (!ghUser) return null;\n\n  const isAdmin = ADMIN_USERNAMES.has(ghUser.login.toLowerCase());\n\n  const introspection: TokenIntrospection = {\n    active: true,\n    clientId: `github:${ghUser.login}`,\n    agentId: `github:${ghUser.id}`,\n    scopes: isAdmin\n      ? [\n          'admin:*',\n          'tools:read',\n          'tools:write',\n          'tools:codebase',\n          'a2a:tasks',\n          'scenes:read',\n          'scenes:write',\n        ]\n      : ['tools:read', 'tools:write', 'tools:codebase', 'scenes:read'],\n  };\n\n  // Cache\n  if (cache.size >= CACHE_MAX) {\n    const firstKey = cache.keys().next().value;\n    if (firstKey) cache.delete(firstKey);\n  }\n  cache.set(token, { introspection, expiresAt: Date.now() + CACHE_TTL_MS });\n\n  return introspection;\n}\n","#!/usr/bin/env node\n/**\n * HoloScript MCP Server CLI\n *\n * Starts the MCP server for AI agent integration.\n */\n\nimport './index';\n","/**\n * @holoscript/mcp-server\n *\n * Model Context Protocol server for HoloScript language tooling.\n * Enables AI agents (Grok, Claude, Copilot, etc.) to parse, validate,\n * generate, and COMPILE HoloScript code to 25+ platforms.\n *\n * 82+ tools across 15 categories:\n * - Core (15): Parse, validate, generate, render, share, explain, analyze\n * - Graph (13): Parse-to-graph, visualize, design, diff, connections, node query\n * - IDE (9): Scan, diagnostics, autocomplete, refactor, docs, hover\n * - Brittney-Lite AI (4): Explain errors, fix code, review, scaffold\n * - Codebase (5): Absorb repo, query, impact analysis, change detection\n * - Graph RAG (2): Semantic search, natural language Q&A\n * - Self-Improve (2): Diagnose, validate quality\n * - GLTF (2): Import glTF/GLB to .holo, compile .holo to glTF/GLB\n * - EditHolo (1): In-place .holo file editing for agents\n * - Compiler (8): Compile to Unity, Unreal, URDF, WebGPU, R3F, etc.\n * - Networking (2): Multiplayer RPC layer\n * - Snapshot (3): Temporal scene snapshots\n * - Monitoring (1): Telemetry and health\n * - HoloTest (1): Spatial scene testing\n * - Absorb Service (10): Project mgmt, credits, absorb, improve, query, render, diff, pipeline\n * - Browser control (3), Training data (1) [included in Core tools above]\n */\n\n// !! MUST be first import — populates process.env from .env before any module-level\n// `const X = process.env.X || ''` constants are evaluated. No-op on Railway.\nimport './utils/load-env';\n\nimport { Server } from '@modelcontextprotocol/sdk/server/index.js';\nimport { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';\nimport {\n  CallToolRequestSchema,\n  ListToolsRequestSchema,\n  type Tool,\n} from '@modelcontextprotocol/sdk/types.js';\nimport {\n  ListResourcesRequestSchema,\n  ReadResourceRequestSchema,\n} from '@modelcontextprotocol/sdk/types.js';\n\nimport { tools } from './tools';\nimport { handleTool } from './handlers';\nimport { PluginManager } from './PluginManager';\nimport { networkingTools, handleNetworkingTool } from './networking-tools';\nimport { snapshotTools, handleSnapshotTool } from './snapshot-tools';\nimport { monitoringTools, handleMonitoringTool } from './monitoring-tools';\nimport { compilerTools, handleCompilerTool } from './compiler-tools';\nimport {\n  codebaseTools,\n  graphRagTools,\n  absorbServiceTools,\n  handleCodebaseTool,\n  handleGraphRagTool,\n  handleAbsorbServiceTool,\n} from '@holoscript/absorb-service/mcp';\nimport { handleOracleConsult } from './oracle-handler';\nimport { oracleMcpTools, handleOracleMcpTool } from './oracle-mcp-tools';\nimport { selfImproveTools, handleSelfImproveTool } from './self-improve-tools';\nimport { grpoTools, handleGrpoTool } from './grpo-tools';\nimport { gltfImportTools, handleGltfTool } from './gltf-import-tools';\nimport { generateMeshTools, handleGenerateMeshTool } from './generate-mesh-tools';\nimport { holotestTools, handleHolotestTool } from './holotest-tools';\nimport { wisdomGotchaTools, handleWisdomGotchaTool } from './wisdom-gotcha-tools';\nimport { receiptQueryTools, handleReceiptQueryTool } from './receipt-query-tools';\nimport { refactorCodegenTools, handleRefactorCodegenTool } from './refactor-codegen-tools';\nimport { traitTools, handleTraitTool } from './trait-tools';\nimport { daemonLifecycleTools, handleDaemonLifecycleTool } from './daemon-lifecycle-tools';\nimport { computeTraceTools, handleComputeTraceTool } from './compute-trace-tools';\nimport { holoCiTools, handleHoloCiTool } from './holo-ci-tools';\nimport { fromScratchToolDefinitions, handleFromScratchTool } from './from-scratch-mcp-tools';\nimport { worldRenderTools, handleWorldRenderTool } from './world-render-tools';\nimport { alphafoldTools, handleFetchStructure } from './alphafold-tools';\nimport { hologramToolDefinitions, handleHologramTool } from './hologram-mcp-tools';\nimport { holotwinToolDefinitions, handleHoloTwinTool } from './holotwin-mcp-tools';\nimport { holoTunnelTools, handleHoloTunnelTool } from './holo-tunnel-tools';\nimport { spatialMcpToolDefinitions } from './spatial-mcp-tools';\nimport {\n  hologramContentToolDefinitions,\n  handleHologramContentTool,\n} from './hologram-content-tools';\nimport { negotiationToolDefinitions, handleNegotiationTool } from './negotiation-mcp-tools';\nimport { memoryTools, handleMemoryTool } from './memory-tools';\nimport { handleBatchToolCall } from './tooling-discovery-tools';\nimport { listSkillResources, readSkillResource } from './skill-resources';\nimport { isHologramMcpResponse, wrapHologramMcpEnvelope } from '@holoscript/core';\nimport type { SigningContext } from './holomesh/identity/signing-middleware';\nimport { authorizeToolCall, registerKnownTools } from './security/tool-scopes';\nimport {\n  gateToolCall,\n  classifyMcpEnvelopeResult,\n  frameDeclarationFromMcpMeta,\n} from './tool-call-gate';\nimport { founderGateX402ToolCallCheck } from './tool-call-checks';\n\ndeclare const __SERVICE_VERSION__: string;\n\n// Create MCP server\nconst server = new Server(\n  {\n    name: 'holoscript-mcp',\n    version: typeof __SERVICE_VERSION__ !== 'undefined' ? __SERVICE_VERSION__ : '0.0.0',\n  },\n  {\n    capabilities: {\n      tools: {},\n      resources: {},\n    },\n  }\n);\n\n// tools.ts is the single source of truth for all tool definitions.\n// Compiler, networking, snapshot, monitoring, holotest, refactor-codegen are now in tools.ts.\n// Only add synthetic meta-tools here (discover + batch).\nexport const ALL_AVAILABLE_TOOLS: Tool[] = [\n  ...tools,\n  ...grpoTools,\n  ...alphafoldTools,\n  ...hologramToolDefinitions,\n  ...holotwinToolDefinitions,\n  ...holoTunnelTools,\n  ...spatialMcpToolDefinitions,\n  ...hologramContentToolDefinitions,\n  ...negotiationToolDefinitions,\n  ...daemonLifecycleTools,\n  ...computeTraceTools,\n  {\n    name: 'holoscript_discover_tools',\n    description:\n      'Search for available MCP tools by intent or keyword. Returns tool names, descriptions, and schemas. Use this when you are unsure which tool to use.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        intent: {\n          type: 'string',\n          description:\n            'What you are trying to do (e.g. \"parse HoloScript code\", \"search codebase\", \"compile\").',\n        },\n        limit: { type: 'number', description: 'Max number of results to return (default 5).' },\n      },\n      required: ['intent'],\n    },\n  },\n  {\n    name: 'holoscript_batch_execute',\n    description:\n      'Execute multiple MCP tools sequentially in a single turn. Useful for chaining actions without waiting for multiple conversational turns.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        requests: {\n          type: 'array',\n          description: 'A list of tool requests to execute in order.',\n          items: {\n            type: 'object',\n            properties: {\n              name: { type: 'string', description: 'Name of the tool to execute' },\n              arguments: { type: 'object', description: 'Arguments for the tool' },\n            },\n            required: ['name', 'arguments'],\n          },\n        },\n      },\n      required: ['requests'],\n    },\n  },\n];\n\n// Fail-closed-on-unregistered (task_1783805494038): register the live tool registry with the Gate-2\n// authorizer so a name NOT served here is denied even when presented with admin:*. This runs for\n// BOTH servers — http-server.ts imports _handleSingleToolLogic from this module, so this module's\n// top-level code executes in the HTTP process too. Plugin tools register additively via PluginManager.\nregisterKnownTools(ALL_AVAILABLE_TOOLS.map((t) => t.name));\n\n// List available tools\nserver.setRequestHandler(ListToolsRequestSchema, async () => {\n  let mappedTools = [...ALL_AVAILABLE_TOOLS, ...PluginManager.getTools()].map((t) => {\n    // Dynamic Appender: Ensure ALL tools explicitly state what they return per Gap 3 Requirements\n    const desc = t.description || '';\n    if (!desc.includes('Returns:') && !desc.includes('Output:')) {\n      return {\n        ...t,\n        description:\n          desc +\n          '\\n\\nReturns: JSON object with execution results. Specific schema omitted, see tool implementation.',\n      };\n    }\n    return t;\n  });\n\n  const limit = parseInt(process.env.HOLOSCRIPT_MAX_TOOLS || '99', 10);\n  if (limit > 0 && mappedTools.length > limit) {\n    const metaTools = mappedTools.filter(\n      (t) => t.name === 'holoscript_discover_tools' || t.name === 'holoscript_batch_execute'\n    );\n    const rest = mappedTools.filter(\n      (t) => t.name !== 'holoscript_discover_tools' && t.name !== 'holoscript_batch_execute'\n    );\n    mappedTools = [...metaTools, ...rest].slice(0, limit);\n  }\n\n  return { tools: mappedTools };\n});\n\n// List available skill resources\nserver.setRequestHandler(ListResourcesRequestSchema, async () => {\n  const resources = listSkillResources();\n  return { resources };\n});\n\n// Read a specific skill resource\nserver.setRequestHandler(ReadResourceRequestSchema, async (request) => {\n  const uri = request.params.uri;\n  const result = readSkillResource(uri);\n  if (!result) {\n    throw new Error(`Resource not found: ${uri}`);\n  }\n  return {\n    contents: [\n      {\n        uri,\n        mimeType: result.mimeType,\n        text: result.text,\n      },\n    ],\n  };\n});\n\n// Single tool executor allowing internal recursive calls\nexport async function executeSingleTool(\n  name: string,\n  args: Record<string, unknown>,\n  signingCtx?: SigningContext\n) {\n  try {\n    if (name === 'holoscript_discover_tools') {\n      const intent = String(args?.intent || '').toLowerCase();\n      const limit = Number(args?.limit || 5);\n\n      const words = intent.split(/\\W+/).filter((w) => w.length > 2);\n      const scoredTools = ALL_AVAILABLE_TOOLS.map((t) => {\n        const description = t.description ?? '';\n        const textToSearch = `${t.name} ${description}`.toLowerCase();\n        let score = 0;\n        if (t.name.toLowerCase().includes(intent)) score += 10;\n        if (description.toLowerCase().includes(intent)) score += 5;\n        for (const word of words) {\n          if (textToSearch.includes(word)) score += 1;\n        }\n        return { tool: t, score };\n      })\n        .filter((t) => t.score > 0)\n        .sort((a, b) => b.score - a.score)\n        .slice(0, limit);\n\n      return {\n        content: [\n          {\n            type: 'text',\n            text: JSON.stringify(\n              scoredTools.map((s) => s.tool),\n              null,\n              2\n            ),\n          },\n        ],\n      };\n    }\n\n    if (name === 'holoscript_batch_execute') {\n      const requests = ((args?.requests as unknown[]) || []) as Array<{\n        name?: string;\n        arguments?: Record<string, unknown>;\n      }>;\n      const results: unknown[] = [];\n      for (const req of requests) {\n        assertBatchInnerToolAuthorized(String(req.name || ''), signingCtx);\n        const res = await executeSingleTool(\n          String(req.name || ''),\n          req.arguments || {},\n          signingCtx\n        );\n        results.push({\n          name: req.name,\n          status: (res as { isError?: boolean }).isError ? 'error' : 'success',\n          result: (res as { content?: unknown }).content,\n        });\n      }\n      return {\n        content: [{ type: 'text', text: JSON.stringify(results, null, 2) }],\n      };\n    }\n\n    if (name === 'batch_tool_call') {\n      const batchResult = await handleBatchToolCall(args || {}, async (toolName, toolArgs) => {\n        assertBatchInnerToolAuthorized(toolName, signingCtx);\n        const res = await executeSingleTool(toolName, toolArgs || {}, signingCtx);\n\n        if ((res as { isError?: boolean }).isError) {\n          const errorText = (res as { content?: Array<{ text?: string }> }).content?.[0]?.text;\n          throw new Error(errorText || `Tool ${toolName} failed`);\n        }\n\n        const text = (res as { content?: Array<{ text?: string }> }).content?.[0]?.text;\n        if (!text) return null;\n\n        try {\n          return JSON.parse(text);\n        } catch {\n          return text;\n        }\n      });\n\n      return {\n        content: [{ type: 'text', text: JSON.stringify(batchResult, null, 2) }],\n      };\n    }\n\n    return await _handleSingleToolLogic(name, args, signingCtx);\n  } catch (error) {\n    const message = error instanceof Error ? error.message : String(error);\n    return {\n      content: [{ type: 'text', text: JSON.stringify({ error: message }, null, 2) }],\n      isError: true,\n    };\n  }\n}\n\n/**\n * Batch meta-tools are authorized at the outer transport boundary, but their\n * children are distinct tool invocations with potentially stronger scopes.\n * Re-check every child against the original request scopes before dispatch.\n * An absent context is the trusted local stdio path, which has no OAuth token.\n */\nfunction assertBatchInnerToolAuthorized(toolName: string, signingCtx?: SigningContext): void {\n  if (!signingCtx) return;\n\n  const authorization = authorizeToolCall(toolName, signingCtx.scopes ?? []);\n  if (!authorization.authorized) {\n    throw new Error(\n      `Batch inner tool authorization denied for \"${toolName}\": ${authorization.reason ?? 'insufficient scope'}`\n    );\n  }\n}\n\n// Handle tool calls.\n//\n// AUTH MODEL — this is the **stdio** MCP transport entry. By transport-layer\n// design it has no Authorization headers and no per-request signing envelope,\n// so it ALWAYS dispatches with `signingCtx=undefined` (trusted local process,\n// no network attacker). Defense-in-depth lives elsewhere:\n//\n//   • HTTP MCP entry (http-server.ts:661) — OAuth-style auth via\n//     TokenIntrospection + TOOL_SCOPE_MAP (tool-scopes.ts). Peer's auth path,\n//     gates tools by OAuth scopes (e.g. `tools:admin` for holo_secrets_*).\n//\n//   • Per-request signing envelopes — SigningContext + capability-token\n//     gate (signing-middleware.ts → handleSecretsBrokerTool's\n//     SECRETS_BROKER_TOOL_CAPABILITIES). Mine, used by HoloMesh routes\n//     where envelopes are first-class.\n//\n// Bridge gap (F.051 canary task_1778596074561_adcf): http-server.ts:671\n// passes `auth: TokenIntrospection` to securedToolExecution but does NOT yet\n// also extract a SigningContext from envelope-shaped request bodies and\n// thread it into executeSingleTool. Until that bridge lands, the leaf-level\n// capability gate at handleSecretsBrokerTool is dormant for HTTP callers\n// (the type-system threading at every layer is in place — peer's commit\n// 17e564097 and mine 5991f8d2e — only the populate step is missing).\n//\n// Closure path for an HTTP caller:\n//   1. http-server.ts line 671 area: parse request body, if it looks like\n//      an envelope (envelope_type in {classical, dual, capability}) call\n//      extractAndVerifySigning(body) → SigningContext.\n//   2. Pass that signingCtx through securedToolExecution → handleTool.\n//   3. The leaf gate at handleSecretsBrokerTool then fires automatically.\n//\n// WRAP-WITH-RECEIPTS fold point (dependency-sovereignty-ladder, 2026-07-16):\n// every stdio tool call routes through gateToolCall — one NDJSON receipt per\n// call (sha256 of canonical-JSON args, NEVER raw args) plus the typed seam\n// where FounderGate / x402 / envelope-validation checks plug in. The seam now\n// runs the REAL check (tool-call-checks.ts): exact-four/prohibited authority\n// routing on the tool NAME, active @frame_declaration enforcement, and Gate-2\n// scope authorization (trusted local stdio = admin:*, still fail-closed on\n// unregistered names). A denial throws\n// ToolCallGateDeniedError pre-dispatch (receipt written first);\n// executeSingleTool itself never throws (failures come back as isError\n// results, which the classifier maps onto the receipt's error status).\nserver.setRequestHandler(CallToolRequestSchema, async (request) => {\n  const { name, arguments: args } = request.params;\n  const frameDeclaration = frameDeclarationFromMcpMeta(\n    (request.params as { _meta?: unknown })._meta\n  );\n  return await gateToolCall(\n    { name, args: args || {} },\n    {\n      transport: 'stdio',\n      callerId: null,\n      ...(frameDeclaration !== undefined ? { frameDeclaration } : {}),\n    },\n    (env) => executeSingleTool(env.name, env.args),\n    { classifyResult: classifyMcpEnvelopeResult, check: founderGateX402ToolCallCheck }\n  );\n});\n\n// === O(1) TOOL DISPATCH REGISTRY ===\ntype ToolHandler = (\n  name: string,\n  args: Record<string, unknown>,\n  signingCtx?: SigningContext\n) => Promise<any> | any;\nconst TOOL_DISPATCH_REGISTRY = new Map<string, ToolHandler>();\n\nfunction registerCategory(toolArray: Tool[], handler: ToolHandler) {\n  for (const t of toolArray) {\n    if (t.name) TOOL_DISPATCH_REGISTRY.set(t.name, handler);\n  }\n}\n\n// 1. Explicitly mapped domains\nregisterCategory(compilerTools, (name, args, _signingCtx) => handleCompilerTool(name, args));\n// Thread the caller signer address (from signed envelopes) as the token identity\n// for per-caller spend authorisation. For unsigned / stdio callers signingCtx is\n// undefined and callerToken is undefined → those callers are unconditionally trusted.\nregisterCategory(holoCiTools, (name, args, signingCtx) =>\n  handleHoloCiTool(name, args, signingCtx?.signer ?? undefined)\n);\n// From-scratch pretraining lane: dispatches the ai-ecosystem CLI. Thread the\n// complete signing context because an applied launch fails closed unless the\n// caller is a signed, active HoloMesh seat. Unsigned/stdio remains preview-only.\nregisterCategory(fromScratchToolDefinitions, (name, args, signingCtx) =>\n  handleFromScratchTool(name, args, signingCtx)\n);\nregisterCategory(worldRenderTools, (name, args, signingCtx) =>\n  handleWorldRenderTool(name, args, signingCtx?.signer ?? undefined)\n);\nregisterCategory(networkingTools, (name, args, _signingCtx) => handleNetworkingTool(name, args));\nregisterCategory(snapshotTools, (name, args, _signingCtx) => handleSnapshotTool(name, args));\nregisterCategory(monitoringTools, (name, args, _signingCtx) => handleMonitoringTool(name, args));\nregisterCategory(holotestTools, (name, args, _signingCtx) => handleHolotestTool(name, args));\nregisterCategory(refactorCodegenTools, (name, args, _signingCtx) =>\n  handleRefactorCodegenTool(name, args)\n);\nregisterCategory(absorbServiceTools, (name, args, _signingCtx) =>\n  handleAbsorbServiceTool(name, args)\n);\nregisterCategory(codebaseTools, (name, args, _signingCtx) => handleCodebaseTool(name, args));\nregisterCategory(graphRagTools, (name, args, _signingCtx) => handleGraphRagTool(name, args));\nregisterCategory(selfImproveTools, (name, args, _signingCtx) => handleSelfImproveTool(name, args));\nregisterCategory(grpoTools, (name, args, _signingCtx) => handleGrpoTool(name, args));\nregisterCategory(gltfImportTools, (name, args, _signingCtx) => handleGltfTool(name, args));\nregisterCategory(generateMeshTools, (name, args, _signingCtx) =>\n  handleGenerateMeshTool(name, args)\n);\nregisterCategory(wisdomGotchaTools, (name, args, _signingCtx) =>\n  handleWisdomGotchaTool(name, args)\n);\nregisterCategory(receiptQueryTools, (name, args, _signingCtx) =>\n  handleReceiptQueryTool(name, args)\n);\nregisterCategory(oracleMcpTools, (name, args, _signingCtx) => handleOracleMcpTool(name, args));\nregisterCategory(traitTools, (name, args, _signingCtx) => handleTraitTool(name, args));\nregisterCategory(computeTraceTools, (name, args, _signingCtx) =>\n  handleComputeTraceTool(name, args)\n);\nregisterCategory(alphafoldTools, (name, args, _signingCtx) => handleFetchStructure(args));\nregisterCategory(hologramToolDefinitions, (name, args, _signingCtx) =>\n  handleHologramTool(name, args)\n);\nregisterCategory(holotwinToolDefinitions, (name, args, _signingCtx) =>\n  handleHoloTwinTool(name, args)\n);\nregisterCategory(holoTunnelTools, (name, args, _signingCtx) => handleHoloTunnelTool(name, args));\nregisterCategory(hologramContentToolDefinitions, (name, args, _signingCtx) =>\n  handleHologramContentTool(name, args)\n);\nregisterCategory(negotiationToolDefinitions, (name, args, _signingCtx) =>\n  handleNegotiationTool(name, args)\n);\nregisterCategory(daemonLifecycleTools, (name, args, _signingCtx) =>\n  handleDaemonLifecycleTool(name, args)\n);\nregisterCategory(memoryTools, (name, args, _signingCtx) => handleMemoryTool(name, args));\n\n// 2. Core fallback (anything else exported in `tools.ts` array)\nfor (const t of tools) {\n  if (t.name && !TOOL_DISPATCH_REGISTRY.has(t.name)) {\n    TOOL_DISPATCH_REGISTRY.set(t.name, (name, args, signingCtx) =>\n      handleTool(name, args, signingCtx)\n    );\n  }\n}\n\nasync function executeBatchInnerTool(\n  toolName: string,\n  toolArgs: Record<string, unknown>,\n  signingCtx?: SigningContext\n): Promise<unknown> {\n  assertBatchInnerToolAuthorized(toolName, signingCtx);\n  const res = await _handleSingleToolLogic(toolName, toolArgs || {}, signingCtx);\n\n  if ((res as { isError?: boolean }).isError) {\n    const errorText = (res as { content?: Array<{ text?: string }> }).content?.[0]?.text;\n    throw new Error(errorText || `Tool ${toolName} failed`);\n  }\n\n  const text = (res as { content?: Array<{ text?: string }> }).content?.[0]?.text;\n  if (!text) return res;\n\n  try {\n    return JSON.parse(text);\n  } catch {\n    return text;\n  }\n}\n\n// Implementation of executeSingleTool logic previously bound above\nexport async function _handleSingleToolLogic(\n  name: string,\n  args: Record<string, unknown>,\n  signingCtx?: SigningContext\n) {\n  try {\n    // 1. Plugin namespace isolation (Enforce strict O(1) boundary for proprietary tool shadowing prevention)\n    if (name.startsWith('uaa2_') || name.startsWith('hs_plugin_')) {\n      const pluginResult = await PluginManager.handleTool(name, args || {});\n      if (pluginResult !== null) {\n        return {\n          content: [{ type: 'text', text: JSON.stringify(pluginResult, null, 2) }],\n        };\n      }\n      throw new Error(`Plugin tool '${name}' not found or failed.`);\n    }\n\n    if (name === 'batch_tool_call') {\n      const result = await handleBatchToolCall(args || {}, (toolName, toolArgs) =>\n        executeBatchInnerTool(toolName, toolArgs, signingCtx)\n      );\n      return {\n        content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],\n      };\n    }\n\n    // 2. Fast O(1) Dispatch\n    const handler = TOOL_DISPATCH_REGISTRY.get(name);\n    if (!handler) {\n      throw new Error(`Unknown tool: ${name}`);\n    }\n\n    const result = await handler(name, args || {}, signingCtx);\n\n    // Tools that returned null failed to match inside their specialized handler (should be rare with Map)\n    if (result === null) {\n      throw new Error(`Handler for '${name}' returned null (tool not processed).`);\n    }\n\n    // Hologram MCP envelope detection (task_1778114362909_zp7u). Tools that\n    // return a `HologramMcpResponse` get wrapped in the typed dispatch\n    // envelope so hologram-aware clients can detect content_type without\n    // re-parsing JSON. Backwards-compatible: chat-only clients still see the\n    // text payload at content[0].text.\n    if (isHologramMcpResponse(result)) {\n      return wrapHologramMcpEnvelope(result) as unknown as Record<string, unknown>;\n    }\n\n    return {\n      content: [\n        {\n          type: 'text',\n          text: typeof result === 'string' ? result : JSON.stringify(result, null, 2),\n        },\n      ],\n    };\n  } catch (error) {\n    const message = error instanceof Error ? error.message : String(error);\n    return {\n      content: [\n        {\n          type: 'text',\n          text: JSON.stringify({ error: message }, null, 2),\n        },\n      ],\n      isError: true,\n    };\n  }\n}\n\n// Start server\nimport { requireConfig, REQUIRED_VARS } from '@holoscript/config';\nimport { loadNativeAgentCompositions } from './holomesh/agent/loader';\n\nfunction routeStdioDiagnosticsToStderr(): void {\n  const writeDiagnostic = (...data: unknown[]) => {\n    console.error(...data);\n  };\n  console.log = writeDiagnostic;\n  console.info = writeDiagnostic;\n}\n\nasync function main() {\n  routeStdioDiagnosticsToStderr();\n\n  // Load agent definitions from native .hsplus fixtures\n  loadNativeAgentCompositions();\n\n  requireConfig(REQUIRED_VARS.MCP_SERVER as unknown as string[], 'mcp-server');\n  const transport = new StdioServerTransport();\n  await server.connect(transport);\n  console.error('HoloScript MCP Server running on stdio');\n}\n\n// Only auto-start the Stdio server if executed directly as a standalone process\nif (\n  process.env.START_MCP_STDIO === 'true' ||\n  process.argv.some(\n    (arg) => arg.includes('mcp-server') && (arg.endsWith('index.ts') || arg.endsWith('index.js'))\n  )\n) {\n  main().catch(console.error);\n}\n\n// Also export for programmatic use\nexport { server, tools, handleTool };\nexport { MCP_SERVER_SIZING_PROFILES, getMcpServerSizing } from './server-sizing';\nexport type { McpServerSize, McpServerSizing, McpServerTransportHint } from './server-sizing';\nexport * from './tools';\nexport * from './handlers';\nexport * from './generators';\nexport * from './renderer';\nexport * from './graph-tools';\nexport * from './ide-tools';\nexport * from './brittney-lite';\nexport * from './compiler-tools';\nexport * from './agent-identity-tools';\nexport * from './gltf-import-tools';\nexport * from './wisdom-gotcha-tools';\nexport * from './oracle-mcp-tools';\nexport * from './trait-tools';\nexport * from './alphafold-tools';\nexport * from '@holoscript/absorb-service/mcp';\nexport * from './a2a';\nexport * from './security';\nexport * from './holomesh/index';\n","/**\n * load-env.ts — Local env loader for MCP server dev and self-hosted deployments.\n *\n * Mirrors the essential logic of ai-ecosystem's loadLocalEnv() (holomesh-env.mjs)\n * without a cross-repo ESM/CJS dependency. Imported as a side-effect at the\n * top of http-server.ts and index.ts so process.env is populated before any\n * module-level `const X = process.env.X || ''` constants are evaluated.\n *\n * Load order (first file that exists wins, except for MESH_RUNTIME_REFRESH_KEYS):\n *   1. <mcp-server-root>/.env            (packages/mcp-server/.env)\n *   2. <monorepo-root>/.env              (HoloScript/.env)\n *   3. ~/.ai-ecosystem/.env              (ecosystem fallback — same as loadLocalEnv())\n *\n * Skipped when:\n *   - HOLOMESH_NO_DOTENV=1              (test isolation)\n *   - Running on Railway                (managed env — no local files)\n *\n * Shadow denylist (never auto-inject — let OS keyring / shell auth own these):\n *   GITHUB_TOKEN, GH_TOKEN, PERSONAL_ACCESS_TOKEN\n *\n * Mesh refresh keys (always overwrite from disk — stale inherited values break\n * team membership auth; see W.129 in ai-ecosystem MEMORY.md):\n *   HOLOMESH_API_KEY, HOLOMESH_TEAM_ID, HOLOMESH_AGENT_ID, HOLOMESH_WALLET_KEY\n */\n\nimport { readFileSync } from 'fs';\nimport { resolve } from 'path';\nimport { homedir } from 'os';\n\n// ── Constants ─────────────────────────────────────────────────────────────────\n\nconst IS_RAILWAY = Boolean(\n  process.env.RAILWAY_PUBLIC_DOMAIN ||\n  process.env.RAILWAY_PROJECT_ID ||\n  process.env.RAILWAY_ENVIRONMENT\n);\n\n/** Keys that should never be injected from .env — let OS keyring / shell auth own them. */\nconst ENV_SHADOW_DENYLIST = new Set(['GITHUB_TOKEN', 'GH_TOKEN', 'PERSONAL_ACCESS_TOKEN']);\n\n/**\n * Keys that must be refreshed from disk even when already set in process.env.\n * A stale HOLOMESH_API_KEY from a prior shell session causes 403 \"Not a member\n * of this team\" against the wrong team. Disk wins; intentional overrides should\n * set HOLOMESH_NO_DOTENV=1 or export explicitly before starting the server.\n */\nconst MESH_RUNTIME_REFRESH_KEYS = new Set([\n  'HOLOMESH_API_KEY',\n  'HOLOMESH_TEAM_ID',\n  'HOLOMESH_AGENT_ID',\n  'HOLOMESH_WALLET_KEY',\n]);\n\n// ── Path resolution ───────────────────────────────────────────────────────────\n\n/**\n * __dirname is:\n *   src/utils/   — when running via `tsx src/http-server.ts` (dev)\n *   dist/utils/  — when running via `node dist/http-server.js` (prod/start)\n *\n * Both are exactly 2 levels below the mcp-server package root and 4 levels\n * below the monorepo root, so the relative path math is stable across both.\n */\nconst MCP_SERVER_DIR = resolve(__dirname, '..', '..');\nconst MONOREPO_ROOT = resolve(__dirname, '..', '..', '..', '..');\n\nconst ENV_CANDIDATES: string[] = [\n  resolve(MCP_SERVER_DIR, '.env'),\n  resolve(MONOREPO_ROOT, '.env'),\n  resolve(homedir(), '.ai-ecosystem', '.env'),\n];\n\n// ── Parser ────────────────────────────────────────────────────────────────────\n\nfunction stripWrappingQuotes(value: string): string {\n  if (\n    (value.startsWith('\"') && value.endsWith('\"')) ||\n    (value.startsWith(\"'\") && value.endsWith(\"'\"))\n  ) {\n    return value.slice(1, -1);\n  }\n  return value;\n}\n\nfunction parseEnvContent(content: string): Array<{ key: string; value: string }> {\n  const pairs: Array<{ key: string; value: string }> = [];\n  for (const line of content.split(/\\r?\\n/u)) {\n    const trimmed = line.trim();\n    if (!trimmed || trimmed.startsWith('#')) continue;\n    const normalized = trimmed.startsWith('export ') ? trimmed.slice(7).trim() : trimmed;\n    const eq = normalized.indexOf('=');\n    if (eq === -1) continue;\n    const key = normalized.slice(0, eq).trim();\n    const value = stripWrappingQuotes(normalized.slice(eq + 1).trim());\n    if (key) pairs.push({ key, value });\n  }\n  return pairs;\n}\n\n// ── Loader ────────────────────────────────────────────────────────────────────\n\nexport interface LoadMcpEnvResult {\n  /** Absolute path of the .env file that was loaded, or null if none found. */\n  loadedFrom: string | null;\n  /** Env vars that were set (not already present or refreshed). */\n  injected: string[];\n  /** Env vars in the file that were skipped (shadow denylist). */\n  denied: string[];\n  /** Why loading was skipped, if applicable. */\n  skipped?: 'HOLOMESH_NO_DOTENV' | 'railway';\n}\n\n/**\n * Load local .env into process.env. Called as a module side effect — import\n * this module before any module-level `process.env.*` reads.\n *\n * Safe to call multiple times (idempotent for non-refresh keys; refresh keys\n * always re-read from disk on each call, which is intentional for test\n * isolation when using HOLOMESH_NO_DOTENV=1 between test cases).\n */\nexport function loadMcpEnv(\n  options: { envPaths?: string[]; silent?: boolean } = {}\n): LoadMcpEnvResult {\n  if (process.env.HOLOMESH_NO_DOTENV === '1') {\n    return { loadedFrom: null, injected: [], denied: [], skipped: 'HOLOMESH_NO_DOTENV' };\n  }\n  if (IS_RAILWAY) {\n    return { loadedFrom: null, injected: [], denied: [], skipped: 'railway' };\n  }\n\n  const candidates = options.envPaths ?? ENV_CANDIDATES;\n  const injected: string[] = [];\n  const denied: string[] = [];\n  let loadedFrom: string | null = null;\n\n  for (const envPath of candidates) {\n    let content: string;\n    try {\n      content = readFileSync(envPath, 'utf-8');\n    } catch {\n      continue; // file doesn't exist — try next candidate\n    }\n\n    const pairs = parseEnvContent(content);\n    for (const { key, value } of pairs) {\n      if (ENV_SHADOW_DENYLIST.has(key)) {\n        denied.push(key);\n        continue;\n      }\n      if (!process.env[key] || MESH_RUNTIME_REFRESH_KEYS.has(key)) {\n        process.env[key] = value;\n        injected.push(key);\n      }\n    }\n\n    loadedFrom = envPath;\n    break; // Stop at first file that exists (for non-refresh keys, first wins)\n  }\n\n  // Second pass: refresh MESH_RUNTIME_REFRESH_KEYS from remaining candidates\n  // when the first file didn't have them (e.g. HOLOMESH_API_KEY in ~/.ai-ecosystem/.env\n  // but not in packages/mcp-server/.env).\n  if (loadedFrom !== null) {\n    const missingRefreshKeys = Array.from(MESH_RUNTIME_REFRESH_KEYS).filter((k) => !process.env[k]);\n    if (missingRefreshKeys.length > 0) {\n      for (const envPath of candidates) {\n        if (envPath === loadedFrom) continue;\n        let content: string;\n        try {\n          content = readFileSync(envPath, 'utf-8');\n        } catch {\n          continue;\n        }\n        const pairs = parseEnvContent(content);\n        for (const { key, value } of pairs) {\n          if (!missingRefreshKeys.includes(key)) continue;\n          if (!process.env[key] || MESH_RUNTIME_REFRESH_KEYS.has(key)) {\n            process.env[key] = value;\n            injected.push(key);\n          }\n        }\n      }\n    }\n  }\n\n  if (!options.silent && loadedFrom) {\n    console.debug(`[load-env] loaded from ${loadedFrom} (${injected.length} vars)`);\n  }\n\n  return { loadedFrom, injected, denied };\n}\n\n// ── Side effect — call at import time ─────────────────────────────────────────\n// This ensures process.env is fully populated before any module-level\n// `const X = process.env.X || ''` constants are evaluated in the importing module.\nloadMcpEnv({ silent: true });\n","/**\n * MCP GRPO Tools for HoloScript\n *\n * Exposes the GRPO self-improvement loop as an MCP tool, enabling AI agents\n * to extract training prompts and score completions through the reward\n * orchestrator pipeline.\n *\n * Tools:\n * - holo_run_grpo_pass: Extract prompts from a file glob via GRPOPromptExtractor,\n *   run reward scoring via GRPORewardOrchestrator, return scored completions.\n *\n * D.012 lights-out improvement depends on this.\n * Source: idea-run-13 Pattern B + packages/absorb-service/src/self-improvement/\n */\n\nimport type { Tool } from '@modelcontextprotocol/sdk/types.js';\nimport * as path from 'path';\nimport * as fs from 'fs';\nimport {\n  GRPOPromptExtractor,\n  createNodeFS,\n  GRPORewardOrchestrator,\n  type GRPOOrchestratorConfig,\n  type OrchestratorResult,\n  type OrchestratorStats,\n} from '@holoscript/absorb-service/self-improvement';\nimport type {\n  RewardToolRunner,\n  RewardFunctionOptions,\n} from '@holoscript/absorb-service/self-improvement';\nimport { exec } from 'child_process';\nimport { promisify } from 'util';\n\nconst execAsync = promisify(exec);\n\n/**\n * A vitest config injected into the reward temp dir, isolated from mcp-server's\n * own vitest.config.ts (which restricts `include` to `src/**`, so a temp file\n * under a cwd `.grpo-tmp-*` dir is otherwise invisible to discovery). Written\n * into the completion's temp dir and pointed at via `--config` + `--root` (see\n * realToolRunner.runVitest). Mirrors daemon-grpo-runner.ts's fix for the same\n * vitest-CLI-glob-discovery bug.\n */\nconst EPHEMERAL_VITEST_CONFIG = `export default {\n  test: {\n    globals: true,\n    environment: 'node',\n    include: ['**/*.test.ts', '**/*.spec.ts'],\n    passWithNoTests: false,\n  },\n};\n`;\n\nfunction errMsg(err: unknown): string {\n  return err instanceof Error ? err.message : String(err);\n}\n\n// =============================================================================\n// REAL TOOL RUNNER (uses child_process for vitest, tsc, eslint)\n// =============================================================================\n\nconst realToolRunner: RewardToolRunner = {\n  async writeTempFile(content: string, extension: string): Promise<string> {\n    const tmpDir = fs.mkdtempSync(path.join(process.cwd(), '.grpo-tmp-'));\n    const filePath = path.join(tmpDir, `completion${extension}`);\n    fs.writeFileSync(filePath, content, 'utf-8');\n    return filePath;\n  },\n\n  async deleteTempFile(filePath: string): Promise<void> {\n    try {\n      const dir = path.dirname(filePath);\n      await fs.promises.unlink(filePath);\n      // Try to clean up temp dir if empty\n      try {\n        await fs.promises.rmdir(dir);\n      } catch {\n        // Directory not empty or other error — that's fine\n      }\n    } catch {\n      // Best effort cleanup\n    }\n  },\n\n  async runVitest(\n    filePath: string,\n    options?: { withCoverage?: boolean; timeout?: number }\n  ): Promise<{ passed: number; total: number; coveragePercent?: number; output: string }> {\n    const timeout = options?.timeout ?? 30_000;\n    const workDir = path.dirname(filePath);\n    const configPath = path.join(workDir, 'vitest.config.mjs');\n    try {\n      fs.writeFileSync(configPath, EPHEMERAL_VITEST_CONFIG, 'utf-8');\n    } catch {\n      // Best effort — if this fails, fall through to the (broken) ancestor\n      // config rather than crash the whole reward evaluation.\n    }\n    try {\n      const cmd = `npx vitest run --reporter=json --root \"${workDir}\" --config \"${configPath}\" \"${filePath}\" 2>&1`;\n      const { stdout, stderr } = await execAsync(cmd, {\n        cwd: workDir,\n        timeout,\n        maxBuffer: 5 * 1024 * 1024,\n      });\n      const output = stdout + stderr;\n      const jsonMatch = output.match(/\\{[\\s\\S]*\"numTotalTests\"[\\s\\S]*\\}/);\n      if (jsonMatch) {\n        try {\n          const result = JSON.parse(jsonMatch[0]);\n          return {\n            passed: result.numPassedTests ?? 0,\n            total: result.numTotalTests ?? 0,\n            coveragePercent: result.coveragePercent,\n            output: output.slice(0, 2000),\n          };\n        } catch {\n          // JSON parse failed\n        }\n      }\n      return {\n        passed: 0,\n        total: 0,\n        output: output.slice(0, 2000),\n      };\n    } catch (e: unknown) {\n      const execErr = e as { stdout?: string; stderr?: string };\n      const output = (execErr.stdout ?? '') + (execErr.stderr ?? '');\n      const jsonMatch = output.match(/\\{[\\s\\S]*\"numTotalTests\"[\\s\\S]*\\}/);\n      if (jsonMatch) {\n        try {\n          const result = JSON.parse(jsonMatch[0]);\n          return {\n            passed: result.numPassedTests ?? 0,\n            total: result.numTotalTests ?? 0,\n            output: output.slice(0, 2000),\n          };\n        } catch {\n          // fall through\n        }\n      }\n      return {\n        passed: 0,\n        total: 0,\n        output: errMsg(e).slice(0, 1000),\n      };\n    }\n  },\n\n  async runTypeCheck(\n    filePath: string,\n    options?: { timeout?: number }\n  ): Promise<{ passed: boolean; output: string }> {\n    const timeout = options?.timeout ?? 30_000;\n    const workDir = path.dirname(filePath);\n    try {\n      const { stdout, stderr } = await execAsync(\n        `npx tsc --noEmit --pretty false \"${filePath}\" 2>&1`,\n        { cwd: workDir, timeout, maxBuffer: 5 * 1024 * 1024 }\n      );\n      const output = stdout + stderr;\n      const errorCount = (output.match(/error TS\\d+/g) ?? []).length;\n      return { passed: errorCount === 0, output: output.slice(0, 2000) };\n    } catch (e: unknown) {\n      const execErr = e as { stdout?: string; stderr?: string };\n      const output = (execErr.stdout ?? '') + (execErr.stderr ?? '');\n      const errorCount = (output.match(/error TS\\d+/g) ?? []).length;\n      return { passed: errorCount === 0, output: output.slice(0, 2000) };\n    }\n  },\n\n  async runLint(\n    filePath: string,\n    options?: { timeout?: number }\n  ): Promise<{ issueCount: number; output: string }> {\n    const timeout = options?.timeout ?? 30_000;\n    const workDir = path.dirname(filePath);\n    try {\n      const { stdout, stderr } = await execAsync(`npx eslint \"${filePath}\" --format json 2>&1`, {\n        cwd: workDir,\n        timeout,\n        maxBuffer: 5 * 1024 * 1024,\n      });\n      const output = stdout + stderr;\n      try {\n        const result = JSON.parse(output);\n        let issueCount = 0;\n        if (Array.isArray(result)) {\n          for (const fileResult of result) {\n            issueCount += (fileResult.errorCount ?? 0) + (fileResult.warningCount ?? 0);\n          }\n        }\n        return { issueCount, output: output.slice(0, 2000) };\n      } catch {\n        // Not JSON — count errors from text output\n        const errorCount = (output.match(/^\\s*\\d+:\\d+\\s+error\\s/gm) ?? []).length;\n        const warningCount = (output.match(/^\\s*\\d+:\\d+\\s+warning\\s/gm) ?? []).length;\n        return { issueCount: errorCount + warningCount, output: output.slice(0, 2000) };\n      }\n    } catch (e: unknown) {\n      const execErr = e as { stdout?: string; stderr?: string };\n      const output = (execErr.stdout ?? '') + (execErr.stderr ?? '');\n      const issueCount = (output.match(/^\\s*\\d+:\\d+\\s+error\\s/gm) ?? []).length;\n      return { issueCount, output: output.slice(0, 2000) };\n    }\n  },\n\n  async getCircuitBreakerHealth(): Promise<number> {\n    // Default: return 100 (healthy) when no circuit breaker is wired.\n    // The daemon can override this with real metrics when available.\n    return 100;\n  },\n};\n\n// =============================================================================\n// TOOL DEFINITIONS\n// =============================================================================\n\nexport const grpoTools: Tool[] = [\n  {\n    name: 'holo_run_grpo_pass',\n    description:\n      'Run a single GRPO training pass: extract prompts from source files, ' +\n      'score completions through the 5-dimension reward orchestrator (test pass, ' +\n      'type check, lint, coverage, circuit breaker), and return the scored results. ' +\n      'The orchestrator uses weighted composite scoring with caching and statistics. ' +\n      'Returns per-completion rewards, per-function breakdowns, and aggregate stats. ' +\n      'D.012 lights-out improvement depends on this.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        rootDir: {\n          type: 'string',\n          description: 'Root directory of the monorepo to scan. Defaults to process.cwd().',\n        },\n        glob: {\n          type: 'string',\n          description:\n            'File glob pattern to select source files for prompt extraction. ' +\n            'Examples: \"packages/core/src/**/*.ts\", \"**/*Solver*.ts\". ' +\n            'Defaults to all .ts files under rootDir.',\n        },\n        completions: {\n          type: 'array',\n          items: { type: 'string' },\n          description:\n            'Array of completion strings to score. Each completion is evaluated ' +\n            'against all 5 reward dimensions. If omitted, only prompt extraction runs.',\n        },\n        maxPrompts: {\n          type: 'number',\n          description: 'Maximum number of prompts to extract before stopping. Defaults to 100.',\n        },\n        maxRougeLSimilarity: {\n          type: 'number',\n          description:\n            'ROUGE-L similarity threshold for deduplication. Prompts above this ' +\n            'similarity are merged. Defaults to 0.7.',\n        },\n        weights: {\n          type: 'object',\n          description:\n            'Custom weights for the 5 reward dimensions. Must sum to 1.0. ' +\n            'Defaults: testPassReward=0.40, typeCheckReward=0.20, lintReward=0.15, ' +\n            'coverageReward=0.15, circuitBreakerReward=0.10.',\n          properties: {\n            testPassReward: { type: 'number' },\n            typeCheckReward: { type: 'number' },\n            lintReward: { type: 'number' },\n            coverageReward: { type: 'number' },\n            circuitBreakerReward: { type: 'number' },\n          },\n        },\n        parallel: {\n          type: 'boolean',\n          description: 'Run reward functions in parallel. Defaults to true.',\n        },\n        batchTimeout: {\n          type: 'number',\n          description:\n            'Global timeout for the entire batch evaluation in milliseconds. Defaults to 120000.',\n        },\n        perCompletionTimeout: {\n          type: 'number',\n          description:\n            'Per-completion timeout for reward functions in milliseconds. Defaults to 30000.',\n        },\n        includeStats: {\n          type: 'boolean',\n          description:\n            'Whether to include orchestrator statistics in the response. Defaults to true.',\n        },\n      },\n      required: [],\n    },\n  },\n  {\n    name: 'holo_extract_grpo_prompts',\n    description:\n      'Extract GRPO training prompts from source files without running reward scoring. ' +\n      'Scans for 4 prompt sources: task-marker comments (TODO/FIXME/HACK), stub implementations, ' +\n      'skipped tests, and low-coverage exports. Returns deduplicated prompts with ' +\n      'difficulty estimates, domain tags, and TRL-compatible JSONL records.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        rootDir: {\n          type: 'string',\n          description: 'Root directory of the monorepo to scan.',\n        },\n        glob: {\n          type: 'string',\n          description: 'File glob pattern to filter source files. Defaults to all .ts files.',\n        },\n        maxPrompts: {\n          type: 'number',\n          description: 'Maximum prompts to extract. Defaults to 100.',\n        },\n        maxRougeLSimilarity: {\n          type: 'number',\n          description: 'Deduplication threshold. Defaults to 0.7.',\n        },\n        outputFormat: {\n          type: 'string',\n          enum: ['full', 'trl'],\n          description:\n            'Output format. \"full\" returns GRPOPrompt objects with all metadata. ' +\n            '\"trl\" returns TRL-compatible JSONL records for GRPOTrainer. Defaults to \"full\".',\n        },\n      },\n      required: ['rootDir'],\n    },\n  },\n];\n\n// =============================================================================\n// HANDLER\n// =============================================================================\n\nexport async function handleGrpoTool(\n  name: string,\n  args: Record<string, unknown>\n): Promise<unknown | null> {\n  switch (name) {\n    case 'holo_run_grpo_pass':\n      return handleRunGrpoPass(args);\n    case 'holo_extract_grpo_prompts':\n      return handleExtractGrpoPrompts(args);\n    default:\n      return null;\n  }\n}\n\n// =============================================================================\n// holo_run_grpo_pass HANDLER\n// =============================================================================\n\nasync function handleRunGrpoPass(args: Record<string, unknown>): Promise<unknown> {\n  const rootDir = (args.rootDir as string) ?? process.cwd();\n\n  if (!fs.existsSync(rootDir)) {\n    return { error: `Root directory not found: ${rootDir}` };\n  }\n\n  const glob = args.glob as string | undefined;\n  const completions = args.completions as string[] | undefined;\n  const maxPrompts = (args.maxPrompts as number) ?? 100;\n  const maxRougeLSimilarity = (args.maxRougeLSimilarity as number) ?? 0.7;\n  const includeStats = (args.includeStats as boolean) ?? true;\n\n  // ---------------------------------------------------------------------------\n  // Phase 1: Extract prompts via GRPOPromptExtractor\n  // ---------------------------------------------------------------------------\n  const extractorConfig = {\n    rootDir,\n    maxPrompts,\n    maxRougeLSimilarity,\n    extensions: ['.ts'] as string[],\n    excludeDirs: [\n      'node_modules',\n      'dist',\n      'build',\n      '.git',\n      'coverage',\n      '.stryker-tmp',\n      '.turbo',\n      '.grpo-tmp',\n    ],\n  };\n\n  let extractor: GRPOPromptExtractor;\n  let nodeFS: ReturnType<typeof createNodeFS>;\n\n  try {\n    nodeFS = createNodeFS();\n    extractor = new GRPOPromptExtractor(extractorConfig, nodeFS);\n  } catch (err: unknown) {\n    return { error: `Failed to initialize GRPOPromptExtractor: ${errMsg(err)}` };\n  }\n\n  let prompts: Awaited<ReturnType<typeof extractor.extract>>;\n\n  try {\n    prompts = await extractor.extract();\n  } catch (err: unknown) {\n    return { error: `Prompt extraction failed: ${errMsg(err)}` };\n  }\n\n  // ---------------------------------------------------------------------------\n  // Phase 2: Score completions via GRPORewardOrchestrator (if provided)\n  // ---------------------------------------------------------------------------\n  let orchestratorResult: OrchestratorResult | null = null;\n  let orchestratorStats: OrchestratorStats | null = null;\n\n  if (completions && completions.length > 0) {\n    // Build orchestrator config from args\n    const orchestratorConfig: GRPOOrchestratorConfig = {};\n    if (args.weights) {\n      orchestratorConfig.weights = args.weights as GRPOOrchestratorConfig['weights'];\n    }\n    if (args.parallel !== undefined) {\n      orchestratorConfig.parallel = args.parallel as boolean;\n    }\n    if (args.batchTimeout !== undefined) {\n      orchestratorConfig.batchTimeout = args.batchTimeout as number;\n    }\n    if (args.perCompletionTimeout !== undefined) {\n      orchestratorConfig.perCompletionTimeout = args.perCompletionTimeout as number;\n    }\n\n    try {\n      const orchestrator = new GRPORewardOrchestrator(realToolRunner, orchestratorConfig);\n      const kwargs: RewardFunctionOptions = {\n        workDir: rootDir,\n        timeout: orchestratorConfig.perCompletionTimeout ?? 30_000,\n      };\n\n      orchestratorResult = await orchestrator.evaluate(completions, kwargs);\n\n      if (includeStats) {\n        orchestratorStats = orchestrator.getStats();\n      }\n    } catch (err: unknown) {\n      // Orchestrator failure is non-fatal — return prompts with error note\n      return {\n        prompts: prompts.prompts.length,\n        promptStats: prompts.stats,\n        error: `Reward scoring failed: ${errMsg(err)}`,\n        completions: completions.length,\n      };\n    }\n  }\n\n  // ---------------------------------------------------------------------------\n  // Phase 3: Build response\n  // ---------------------------------------------------------------------------\n  const response: Record<string, unknown> = {\n    promptsExtracted: prompts.prompts.length,\n    promptsAfterDedup: prompts.stats.totalAfterDedup,\n    promptStats: prompts.stats,\n  };\n\n  if (orchestratorResult) {\n    response.completionsScored = orchestratorResult.batchSize;\n    response.compositeRewards = orchestratorResult.compositeRewards;\n    response.functionResults = orchestratorResult.functionResults.map((fr) => ({\n      name: fr.name,\n      weight: fr.weight,\n      rewards: fr.rewards,\n      weightedRewards: fr.weightedRewards,\n      durationMs: fr.durationMs,\n    }));\n    response.totalDurationMs = orchestratorResult.totalDurationMs;\n    response.cacheHits = orchestratorResult.cacheHits;\n  }\n\n  if (orchestratorStats) {\n    response.stats = orchestratorStats;\n  }\n\n  // Return top prompts (limited for readability)\n  response.topPrompts = prompts.prompts.slice(0, 20).map((p) => ({\n    instruction: p.instruction.slice(0, 200),\n    packageName: p.packageName,\n    filePath: p.filePath,\n    difficulty: p.difficulty,\n    source: p.source,\n    domainTags: p.domainTags,\n    line: p.line,\n  }));\n\n  return response;\n}\n\n// =============================================================================\n// holo_extract_grpo_prompts HANDLER\n// =============================================================================\n\nasync function handleExtractGrpoPrompts(args: Record<string, unknown>): Promise<unknown> {\n  const rootDir = args.rootDir as string;\n\n  if (!rootDir || !fs.existsSync(rootDir)) {\n    return { error: `Root directory not found: ${rootDir ?? '(missing)'}` };\n  }\n\n  const glob = args.glob as string | undefined;\n  const maxPrompts = (args.maxPrompts as number) ?? 100;\n  const maxRougeLSimilarity = (args.maxRougeLSimilarity as number) ?? 0.7;\n  const outputFormat = (args.outputFormat as string) ?? 'full';\n\n  const extractorConfig = {\n    rootDir,\n    maxPrompts,\n    maxRougeLSimilarity,\n    extensions: ['.ts'] as string[],\n    excludeDirs: [\n      'node_modules',\n      'dist',\n      'build',\n      '.git',\n      'coverage',\n      '.stryker-tmp',\n      '.turbo',\n      '.grpo-tmp',\n    ],\n  };\n\n  let extractor: GRPOPromptExtractor;\n  try {\n    const nodeFS = createNodeFS();\n    extractor = new GRPOPromptExtractor(extractorConfig, nodeFS);\n  } catch (err: unknown) {\n    return { error: `Failed to initialize GRPOPromptExtractor: ${errMsg(err)}` };\n  }\n\n  let result: Awaited<ReturnType<typeof extractor.extract>>;\n\n  try {\n    result = await extractor.extract();\n  } catch (err: unknown) {\n    return { error: `Prompt extraction failed: ${errMsg(err)}` };\n  }\n\n  if (outputFormat === 'trl') {\n    return {\n      totalExtracted: result.stats.totalExtracted,\n      totalAfterDedup: result.stats.totalAfterDedup,\n      removedByDedup: result.stats.removedByDedup,\n      bySource: result.stats.bySource,\n      byDifficulty: result.stats.byDifficulty,\n      byDomain: result.stats.byDomain,\n      packagesCovered: result.stats.packagesCovered,\n      outputFile: result.stats.outputFile,\n      records: result.records,\n    };\n  }\n\n  // Full format: return GRPOPrompt objects with all metadata\n  return {\n    totalExtracted: result.stats.totalExtracted,\n    totalAfterDedup: result.stats.totalAfterDedup,\n    removedByDedup: result.stats.removedByDedup,\n    bySource: result.stats.bySource,\n    byDifficulty: result.stats.byDifficulty,\n    byDomain: result.stats.byDomain,\n    packagesCovered: result.stats.packagesCovered,\n    outputFile: result.stats.outputFile,\n    prompts: result.prompts,\n  };\n}\n","/**\n * Compute-axis graded-trace MCP tools — the live surface over compute-trace-store.ts.\n *\n * Mirrors the daemon-lifecycle export tool (holo_export_emergence_corpus) for the\n * COMPUTE axis of the native-model program (P.004 / P.005 / EXP-3). The store is\n * the additive sibling of daemon-emergence-store.ts; these tools are its read +\n * grade-and-record surface.\n *\n *   holo_grade_compute_mutation — grade ONE proposed compute mutation against a\n *       SimulationContract bound AND write the graded tuple through to the durable\n *       corpus. This is how a LIVE session produces REAL compute training data\n *       (today the corpus is synthetic-bound — harvest_real.py reports 0 real\n *       compute rows). Additive: there was no live grading site to modify.\n *   holo_export_compute_traces — project the durable corpus into the normalized\n *       JSONL shape scripts/corpus/harvest_real.py reads. Read-only.\n *   holo_compute_trace_stats   — diagnostics: where the corpus lives + how much\n *       real compute data has accrued. Read-only.\n */\n\nimport { type Tool } from '@modelcontextprotocol/sdk/types.js';\nimport {\n  gradeComputeMutation,\n  exportTracesJsonlResolved,\n  computeTraceStatsResolved,\n  type ComputePropertyBound,\n  type ComputeMutation,\n} from './compute-trace-store.js';\n\nexport const computeTraceTools: Tool[] = [\n  {\n    name: 'holo_grade_compute_mutation',\n    description:\n      'Grade ONE proposed compute scene-mutation against its SimulationContract ' +\n      'property bound (exact-value match, clamp-to-bounds) AND durably record the ' +\n      '(instruction → mutation → expected/graded value → pass/fail → CAEL receipt) ' +\n      'tuple to the compute-axis corpus. This is how a LIVE session produces REAL ' +\n      'compute-axis training data for the HoloScript native-model program: today ' +\n      'the compute corpus is SYNTHETIC-BOUND (scripts/corpus/harvest_real.py reports ' +\n      '0 real compute rows). The caller supplies the ground-truth expected value for ' +\n      'the op it asked; this tool grades + records, it does NOT change grading ' +\n      'semantics. Best-effort persistence never affects the returned verdict. ' +\n      'Returns: { passed, expectedValue, gradedValue, recorded }.',\n    inputSchema: {\n      type: 'object' as const,\n      properties: {\n        sessionId: { type: 'string', description: 'Stable session/agent id (provenance + dedup).' },\n        instruction: {\n          type: 'string',\n          description: 'The natural-language instruction the agent was given.',\n        },\n        contractId: {\n          type: 'string',\n          description: 'The SimulationContract id the mutation must respect.',\n        },\n        scene: { type: 'string', description: 'The scene source the instruction was applied to.' },\n        bound: {\n          type: 'object',\n          description:\n            'The declared SimulationContract property bound: { trait, property, min, max, current }.',\n          properties: {\n            trait: { type: 'string' },\n            property: { type: 'string' },\n            min: { type: 'number' },\n            max: { type: 'number' },\n            current: { type: 'number' },\n          },\n          required: ['trait', 'property', 'min', 'max', 'current'],\n        },\n        mutation: {\n          type: 'object',\n          description:\n            'The proposed mutation: { tool, objectName, traitName, propertyKey, propertyValue }.',\n          properties: {\n            tool: { type: 'string' },\n            objectName: { type: 'string' },\n            traitName: { type: 'string' },\n            propertyKey: { type: 'string' },\n            propertyValue: { type: 'number' },\n          },\n          required: ['tool', 'objectName', 'traitName', 'propertyKey', 'propertyValue'],\n        },\n        expectedValue: {\n          type: 'number',\n          description: 'Ground-truth expected value the gate grades against.',\n        },\n        opLabel: {\n          type: 'string',\n          description:\n            'Op family label (e.g. \"midpoint\", \"plus30\") — corpus-balance signal. Optional.',\n        },\n        caelReceiptRef: {\n          type: 'string',\n          description: 'Reference to the CAEL receipt anchoring this grade. Optional.',\n        },\n      },\n      required: [\n        'sessionId',\n        'instruction',\n        'contractId',\n        'scene',\n        'bound',\n        'mutation',\n        'expectedValue',\n      ],\n    },\n  },\n  {\n    name: 'holo_export_compute_traces',\n    description:\n      'Export the durable COMPUTE-AXIS graded-trace corpus to a normalized JSONL ' +\n      'file the training-corpus builder consumes — the (system, user, target, ' +\n      'grader, grader_key, family, modality, source) shape read by ' +\n      'scripts/corpus/harvest_real.py, contract-identical to scripts/exp3/' +\n      'compute_suite.py rows by construction. Read-only — does NOT mutate the ' +\n      'corpus. By default keeps only SimContract-PASSED rows (positive SFT ' +\n      'supervision). Returns: { path, rows, bytes, stats }.',\n    inputSchema: {\n      type: 'object' as const,\n      properties: {\n        outPath: {\n          type: 'string',\n          description:\n            'Destination JSONL path. Default: <data-dir>/compute-traces/compute-corpus.normalized.jsonl.',\n        },\n        passedOnly: {\n          type: 'boolean',\n          description:\n            'Keep only rows whose mutation PASSED the SimContract (default true — positive supervision).',\n        },\n      },\n    },\n  },\n  {\n    name: 'holo_compute_trace_stats',\n    description:\n      'Diagnostics for the COMPUTE-AXIS corpus: where it lives on disk and how much ' +\n      'REAL graded compute data has accrued (records, passed/failed, sessions, ' +\n      'contracts). Read-only. Use to answer \"is there real compute training data ' +\n      'yet?\" — 0 records means the corpus is still synthetic-bound.',\n    inputSchema: { type: 'object' as const, properties: {} },\n  },\n];\n\nexport async function handleComputeTraceTool(\n  name: string,\n  args: Record<string, unknown>\n): Promise<unknown | null> {\n  switch (name) {\n    case 'holo_grade_compute_mutation': {\n      const result = gradeComputeMutation({\n        sessionId: args.sessionId as string,\n        instruction: args.instruction as string,\n        contractId: args.contractId as string,\n        scene: args.scene as string,\n        bound: args.bound as ComputePropertyBound,\n        mutation: args.mutation as ComputeMutation,\n        expectedValue: args.expectedValue as number,\n        opLabel: (args.opLabel as string | undefined) ?? null,\n        caelReceiptRef: (args.caelReceiptRef as string | undefined) ?? null,\n      });\n      return {\n        passed: result.passed,\n        expectedValue: result.expectedValue,\n        gradedValue: result.gradedValue,\n        recorded: true,\n        gradedAt: result.record.gradedAt,\n      };\n    }\n    case 'holo_export_compute_traces': {\n      const outPath = typeof args.outPath === 'string' ? args.outPath : undefined;\n      const passedOnly = args.passedOnly === undefined ? true : Boolean(args.passedOnly);\n      // BugB: resolved export reads the durable Postgres corpus when the local\n      // JSONL has been wiped (Railway ephemeral FS) — see compute-trace-store.ts.\n      const result = await exportTracesJsonlResolved(outPath, { passedOnly });\n      return { ...result, stats: await computeTraceStatsResolved() };\n    }\n    case 'holo_compute_trace_stats':\n      return computeTraceStatsResolved();\n    default:\n      return null;\n  }\n}\n","/**\n * ComputeTraceStore — durable, append-only persistence for the COMPUTE-AXIS\n * graded-trace corpus of the HoloScript native-model program (P.004 / P.005 /\n * EXP-3).\n *\n * WHY THIS EXISTS\n * ───────────────\n * scripts/corpus/harvest_real.py computes the honest headline: there is\n * essentially NO real graded data for the exact-value COMPUTE task — the task\n * EXP-1c proved a base 1.5B model cannot do (0% on compute), and the task the\n * smoke fine-tune targets. Today the compute corpus is SYNTHETIC-BOUND: the only\n * (instruction → scene-mutation → SimContract grade) tuples in existence are\n * generated by scripts/exp3/compute_suite.py's `OPS` table. Nothing real accrues\n * because a LIVE graded compute mutation is never written to disk anywhere — the\n * CAEL audit store (state.ts) records a hash-chain over operations, NOT the\n * (instruction, contract, mutation, expected, graded-value, pass/fail) tuple a\n * trainer needs.\n *\n * This module is the compute-axis sibling of daemon-emergence-store.ts. It is a\n * TRANSPARENT persistence + grading-record layer — it changes NOTHING about how a\n * mutation is graded (the SimContract accept gate is the authority). It only:\n *   1. write-through: every graded compute mutation is appended to a durable store,\n *   2. read: a fresh on-disk read returns the accrued tuples (survives restart), and\n *   3. export: a normalized JSONL dump in the EXACT row shape harvest_real.py reads\n *      (system / user / target / grader / grader_key / family / modality / source).\n *\n * MECHANISM (why append-only JSONL, mirroring daemon-emergence-store.ts)\n * ─────────────────────────────────────────────────────────────────────\n * The native-model corpus has to accrue on the LOCAL machine, where there is no\n * DATABASE_URL. The CAEL-audit store and the emergence store both prove this\n * pattern works for graded-trace accrual without Postgres: append-only JSONL under\n * <HOLOMESH_DATA_DIR>, hydrate on read. A corpus is naturally append-only\n * (ever-growing), and harvest_real.py already reads JSONL. When DATABASE_URL IS\n * present (Railway multi-instance), we also fire-and-forget into Postgres JSONB so\n * cross-instance reads converge — additive, never the source of truth for the\n * local trainer. This is byte-for-byte the same mechanism as\n * daemon-emergence-store.ts §appendEmergenceRecord.\n *\n * RECORD GRAIN\n * ────────────\n * One JSONL line per GRADED compute mutation: the instruction, the scene + the\n * SimulationContract bounds it must respect, the agent's proposed mutation, the\n * ground-truth expected value, the graded actual value, pass/fail, and a reference\n * to the CAEL receipt that anchors the grade (when one was produced). That single\n * grain is exactly the (system, user, target) supervision pair a compute SFT row\n * needs — see exportTracesJsonl for the normalized projection.\n */\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport * as os from 'os';\nimport {\n  createRailwayPostgresPoolOptions,\n  type RailwayPostgresPoolOptions,\n} from './postgres-pool-options';\n\n// ── Data dir (same root the rest of mcp-server persists under) ────────────────\n//\n// Matches daemon-emergence-store.ts / holomesh/state.ts HOLOMESH_DATA_DIR so all\n// durable state lives in one place. We read the env var directly (not the symbol)\n// to avoid a load cycle with the holomesh barrel.\n\nconst DATA_ROOT =\n  process.env.HOLOMESH_DATA_DIR ||\n  path.join(process.env.HOLOSCRIPT_CACHE_DIR || path.join(os.homedir(), '.holoscript'), 'holomesh');\n\nconst COMPUTE_DIR = path.join(DATA_ROOT, 'compute-traces');\nconst TRACE_PATH = path.join(COMPUTE_DIR, 'compute-traces.jsonl');\n\n// ── Durable record shape ──────────────────────────────────────────────────────\n//\n// Serialization-safe (plain JSON — no Map/Set). A loss-free encoding of one graded\n// compute mutation. This is NOT the export format (see buildNormalizedRows for the\n// normalized training shape).\n\n/** A single property bound declared by a SimulationContract. */\nexport interface ComputePropertyBound {\n  /** Trait family, e.g. \"glow\", \"rigidbody\". */\n  trait: string;\n  /** Property key, e.g. \"intensity\", \"mass\". */\n  property: string;\n  /** Lower bound of the allowed range. */\n  min: number;\n  /** Upper bound of the allowed range. */\n  max: number;\n  /** The property's current value before the mutation. */\n  current: number;\n}\n\n/** The mutation the agent proposed (the candidate answer being graded). */\nexport interface ComputeMutation {\n  /** The tool the agent chose, e.g. \"set_trait_property\". */\n  tool: string;\n  /** The object the mutation targets. */\n  objectName: string;\n  /** Trait family being mutated. */\n  traitName: string;\n  /** Property key being mutated. */\n  propertyKey: string;\n  /** The value the agent proposed (the candidate compute answer). */\n  propertyValue: number;\n}\n\n/**\n * One durable line in the compute-axis corpus: a graded compute mutation.\n * `passed` is the SimContract accept-gate verdict; `expectedValue` is the\n * ground-truth the gate graded against; `gradedValue` is the (clamped) actual\n * applied value. `caelReceiptRef` references the CAEL trace that anchors the\n * grade, when the grading site produced one (provenance; may be null for an\n * un-anchored local grade).\n */\nexport interface ComputeTraceRecord {\n  /** Stable session/agent id that produced the trace (provenance + dedup). */\n  sessionId: string;\n  /** The natural-language instruction the agent was given. */\n  instruction: string;\n  /** The SimulationContract id the mutation must respect. */\n  contractId: string;\n  /** The scene source the instruction was applied to. */\n  scene: string;\n  /** The property bound the SimContract declared (the in-context constraint). */\n  bound: ComputePropertyBound;\n  /** The mutation the agent proposed. */\n  mutation: ComputeMutation;\n  /** Ground-truth expected value the SimContract gate grades against. */\n  expectedValue: number;\n  /** The graded (clamped-to-bounds) value actually applied. */\n  gradedValue: number;\n  /** SimContract accept-gate verdict. */\n  passed: boolean;\n  /** Op family label (e.g. \"midpoint\", \"plus30\") when known — corpus balance signal. */\n  opLabel: string | null;\n  /** Reference to the CAEL receipt anchoring this grade (provenance), if any. */\n  caelReceiptRef: string | null;\n  /** ISO-8601 server stamp of the grade. */\n  gradedAt: string;\n}\n\n// ── Optional Postgres write-through (Railway multi-instance) ──────────────────\n//\n// Mirrors daemon-emergence-store.ts: when DATABASE_URL is present we ALSO push to\n// a JSONB table. JSONL on disk remains the source of truth for the local trainer;\n// this only helps cross-instance reads converge. Lazy + fire-and-forget so a DB\n// hiccup never blocks (or changes) the grading path.\n\ninterface PgLike {\n  query: (\n    sql: string,\n    params?: unknown[]\n  ) => Promise<{ rows: Array<{ data: ComputeTraceRecord }> }>;\n}\n\nexport type ComputeTracePostgresPoolOptions = RailwayPostgresPoolOptions;\n\nexport function createComputeTracePostgresPoolOptions(\n  databaseUrl: string\n): ComputeTracePostgresPoolOptions {\n  return createRailwayPostgresPoolOptions(databaseUrl);\n}\n\nconst COMPUTE_SCHEMA_SQL = `\nCREATE TABLE IF NOT EXISTS compute_trace_corpus (\n  id          BIGSERIAL PRIMARY KEY,\n  session_id  TEXT NOT NULL,\n  contract_id TEXT NOT NULL,\n  passed      BOOLEAN NOT NULL,\n  data        JSONB NOT NULL,\n  created_at  TIMESTAMP WITH TIME ZONE DEFAULT NOW()\n);\nCREATE INDEX IF NOT EXISTS idx_compute_session ON compute_trace_corpus (session_id);\nCREATE INDEX IF NOT EXISTS idx_compute_created ON compute_trace_corpus (created_at);\n`;\n\nlet pgPool: PgLike | null = null;\nlet pgReady: Promise<void> | null = null;\n\nfunction maybeInitPg(): void {\n  if (pgPool || pgReady) return;\n  const databaseUrl = process.env.DATABASE_URL;\n  if (!databaseUrl) return;\n  try {\n    // eslint-disable-next-line @typescript-eslint/no-var-requires\n    const { Pool } = require('pg') as {\n      Pool: new (cfg: ComputeTracePostgresPoolOptions) => PgLike;\n    };\n    const pool = new Pool(createComputeTracePostgresPoolOptions(databaseUrl));\n    pgPool = pool;\n    pgReady = pool\n      .query(COMPUTE_SCHEMA_SQL)\n      .then(() => undefined)\n      .catch((e: unknown) => {\n        console.warn('[ComputeTraceStore] schema init failed:', e);\n      });\n    console.log('[ComputeTraceStore] PostgreSQL write-through active');\n  } catch (e) {\n    console.warn('[ComputeTraceStore] DATABASE_URL set but pg failed to load:', e);\n  }\n}\n\nfunction pgAppend(record: ComputeTraceRecord): void {\n  maybeInitPg();\n  if (!pgPool || !pgReady) return;\n  pgReady\n    .then(() =>\n      pgPool!.query(\n        `INSERT INTO compute_trace_corpus (session_id, contract_id, passed, data) VALUES ($1, $2, $3, $4)`,\n        [record.sessionId, record.contractId, record.passed, JSON.stringify(record)]\n      )\n    )\n    .catch((e: unknown) => {\n      console.warn('[ComputeTraceStore] pg append failed:', e);\n    });\n}\n\n// ── Append (write-through) ────────────────────────────────────────────────────\n//\n// Synchronous JSONL append (matches daemon-emergence-store.ts appendEmergenceRecord\n// and state.ts persistCaelAuditRecord). Never throws into the grading path — a\n// persistence failure must not change the grade. Honors a dedicated test opt-out\n// env, mirroring the sibling stores.\n\nlet dirEnsured = false;\n\nfunction ensureDir(): void {\n  if (dirEnsured) return;\n  if (!fs.existsSync(COMPUTE_DIR)) {\n    fs.mkdirSync(COMPUTE_DIR, { recursive: true });\n  }\n  dirEnsured = true;\n}\n\n/**\n * Persist one graded compute trace. Write-through: JSONL on disk (source of truth)\n * + optional Postgres (multi-instance). Best-effort — swallows errors so the live\n * grading path is never affected.\n */\nexport function appendComputeTrace(record: ComputeTraceRecord): void {\n  if (\n    process.env.NODE_ENV === 'test' &&\n    process.env.HOLOMESH_TEST_DISABLE_COMPUTE_TRACE_PERSISTENCE === '1'\n  ) {\n    return;\n  }\n  try {\n    ensureDir();\n    fs.appendFileSync(TRACE_PATH, `${JSON.stringify(record)}\\n`, 'utf8');\n  } catch (err) {\n    console.warn(`[ComputeTraceStore] JSONL append failed: ${(err as Error).message}`);\n  }\n  pgAppend(record);\n}\n\n// ── Read (hydration source) ───────────────────────────────────────────────────\n\n/**\n * Read every persisted compute trace from disk, oldest-first (append order).\n * Corrupt / half-flushed lines are skipped (honest: rare, never fatal). Returns\n * [] when nothing has accrued yet. This is the local source of truth — Postgres\n * is only consulted by the caller when it explicitly wants cross-instance reads.\n */\nexport function readComputeTraces(): ComputeTraceRecord[] {\n  if (!fs.existsSync(TRACE_PATH)) return [];\n  const out: ComputeTraceRecord[] = [];\n  const lines = fs.readFileSync(TRACE_PATH, 'utf8').split('\\n');\n  for (const line of lines) {\n    const trimmed = line.trim();\n    if (!trimmed) continue;\n    try {\n      out.push(JSON.parse(trimmed) as ComputeTraceRecord);\n    } catch {\n      // Corrupt line — skip.\n    }\n  }\n  return out;\n}\n\n/**\n * Read every persisted compute trace from Postgres, oldest-first (created_at).\n * Unpacks the JSONB `data` column. Returns [] when Postgres is not configured,\n * the table is empty, or the query fails (honest: never fatal). This is the\n * Railway-durable counterpart to the JSONL reader — the local file is wiped on\n * every redeploy; Postgres survives (HoloTune Phase 0b BugB — D.086).\n */\nexport async function readComputeTracesFromPg(): Promise<ComputeTraceRecord[]> {\n  maybeInitPg();\n  if (!pgPool || !pgReady) return [];\n  try {\n    await pgReady;\n    const result = await pgPool.query(\n      'SELECT data FROM compute_trace_corpus ORDER BY created_at ASC'\n    );\n    return result.rows.map((row) => row.data);\n  } catch (e) {\n    console.warn('[ComputeTraceStore] pg read failed:', e);\n    return [];\n  }\n}\n\n/**\n * Resolve the durable compute corpus, Railway-safe: prefer the local JSONL\n * (source of truth on dev / single-instance); when it is absent/empty AND\n * DATABASE_URL is configured, fall back to the Postgres corpus. Use this instead\n * of the sync readComputeTraces() wherever a complete cross-instance read is\n * required (e.g. the export path on a deployed, ephemeral-FS instance).\n */\nexport async function readComputeTracesResolved(): Promise<ComputeTraceRecord[]> {\n  const local = readComputeTraces();\n  if (local.length > 0) return local;\n  if (process.env.DATABASE_URL) return readComputeTracesFromPg();\n  return local;\n}\n\n// ── Export (normalized training corpus) ───────────────────────────────────────\n//\n// The corpus consumer (ai-ecosystem/scripts/corpus/harvest_real.py) normalizes\n// every source into (system, user, target, grader, grader_key, family, modality,\n// source). The compute source is the EXACT-VALUE task, so we emit that exact shape.\n// CRITICAL: we reuse the SAME compute SYSTEM/user framing as\n// scripts/exp3/compute_suite.py so a row harvested from a LIVE grade is\n// contract-identical (by construction) to a synthetic train/eval row — the\n// property EXP-3's compute_suite.py was built to guarantee (train/eval no-drift).\n//\n//   system   : the compute-task framing (single scene mutation, respect bounds,\n//              JSON-only) — identical to compute_suite.SYSTEM.\n//   user     : instruction + scene + declared bounds (the model's input) — built\n//              by the same template compute_suite._row uses.\n//   target   : the JSON mutation with the EXPECTED value (the supervision signal).\n//   grader   : { kind: \"simcontract_compute\", expected, passed, ... }.\n//   grader_key: [\"compute\", sessionId, seq] — provenance + dedup handle.\n\nexport interface NormalizedComputeRow {\n  system: string;\n  user: string;\n  target: string;\n  grader: {\n    kind: string;\n    expected: number;\n    graded: number;\n    passed: boolean;\n    contractId: string;\n    caelReceiptRef: string | null;\n  };\n  grader_key: [string, string, number];\n  family: string;\n  modality: string;\n  source: string;\n  session: string;\n  op_label: string | null;\n  timestamp: string;\n}\n\n/**\n * The compute-task SYSTEM prompt — kept byte-identical to\n * scripts/exp3/compute_suite.py SYSTEM so a harvested live row trains the exact\n * same task as the synthetic corpus (no train/serve framing drift, the W.667\n * lesson).\n */\nexport const SYSTEM_COMPUTE =\n  \"You are editing a HoloScript scene. Apply the user's instruction as a SINGLE \" +\n  \"scene mutation that RESPECTS the scene's declared SimulationContract — honor \" +\n  'property bounds. Respond with ONLY a JSON object and no prose: ' +\n  '{\"tool\":\"<tool>\",\"input\":{...}}. Property mutations use input ' +\n  '{object_name, trait_name, property_key, property_value}.';\n\n/** Round to 2 decimals — matches compute_suite.r2 so values align with synthetic. */\nfunction r2(x: number): number {\n  return Math.round(x * 100) / 100;\n}\n\n/**\n * Build the `user` text for a compute row in the EXACT shape compute_suite._row\n * emits, from a durable record. Keeping this projection identical to the Python\n * generator is what makes a live-harvested row indistinguishable (to the trainer)\n * from a synthetic one.\n */\nfunction buildUser(rec: ComputeTraceRecord): string {\n  return rec.instruction;\n}\n\n/**\n * Build the `target` JSON in the EXACT shape compute_suite.gen_train emits, but\n * carrying the EXPECTED (ground-truth) value — the supervision signal. We emit the\n * `set_trait_property` tool shape regardless of which tool the agent actually\n * proposed, because the TARGET is the correct answer, not the agent's attempt.\n */\nfunction buildTarget(rec: ComputeTraceRecord): string {\n  return JSON.stringify({\n    tool: 'set_trait_property',\n    input: {\n      trait_name: rec.mutation.traitName,\n      property_key: rec.mutation.propertyKey,\n      property_value: r2(rec.expectedValue),\n    },\n  });\n}\n\n/**\n * Project the persisted compute corpus into normalized training rows. Pure over\n * the on-disk records (no I/O beyond the read) so it is trivially testable.\n * `records` defaults to the on-disk corpus.\n */\nexport function buildNormalizedRows(\n  records: ComputeTraceRecord[] = readComputeTraces()\n): NormalizedComputeRow[] {\n  const rows: NormalizedComputeRow[] = [];\n  const seqBySession = new Map<string, number>();\n\n  for (const rec of records) {\n    const seq = (seqBySession.get(rec.sessionId) ?? -1) + 1;\n    seqBySession.set(rec.sessionId, seq);\n\n    rows.push({\n      system: SYSTEM_COMPUTE,\n      user: buildUser(rec),\n      target: buildTarget(rec),\n      grader: {\n        kind: 'simcontract_compute',\n        expected: r2(rec.expectedValue),\n        graded: r2(rec.gradedValue),\n        passed: rec.passed,\n        contractId: rec.contractId,\n        caelReceiptRef: rec.caelReceiptRef,\n      },\n      grader_key: ['compute', rec.sessionId, seq],\n      family: 'real_compute',\n      modality: 'compute',\n      source: 'compute-trace-corpus',\n      session: rec.sessionId,\n      op_label: rec.opLabel,\n      timestamp: rec.gradedAt,\n    });\n  }\n  return rows;\n}\n\n/**\n * Export the persisted compute corpus to a normalized JSONL file the corpus\n * builder (harvest_real.py) can consume. Returns the path written and the row\n * count. If `outPath` is omitted, writes alongside the raw corpus as\n * `compute-corpus.normalized.jsonl`. A `passedOnly` filter keeps only\n * positive-supervision rows (the SimContract PASSED) — the default for SFT, since\n * a failed compute mutation is a negative example, not a target.\n */\nexport function exportTracesJsonl(\n  outPath?: string,\n  opts: { passedOnly?: boolean } = {}\n): { path: string; rows: number; bytes: number } {\n  let rows = buildNormalizedRows();\n  if (opts.passedOnly) {\n    rows = rows.filter((r) => r.grader.passed);\n  }\n  const target = outPath || path.join(COMPUTE_DIR, 'compute-corpus.normalized.jsonl');\n  ensureDir();\n  const body = rows.map((r) => JSON.stringify(r)).join('\\n') + (rows.length ? '\\n' : '');\n  fs.writeFileSync(target, body, 'utf8');\n  return { path: target, rows: rows.length, bytes: Buffer.byteLength(body, 'utf8') };\n}\n\n/**\n * Railway-safe export: identical to exportTracesJsonl, but resolves the corpus via\n * readComputeTracesResolved() so a deployed (ephemeral-FS) instance reads the\n * durable Postgres corpus when the local JSONL has been wiped (HoloTune Phase 0b\n * BugB). Prefer this in the deployed export path; the sync exportTracesJsonl\n * remains for local/dev where the JSONL is the source of truth.\n */\nexport async function exportTracesJsonlResolved(\n  outPath?: string,\n  opts: { passedOnly?: boolean } = {}\n): Promise<{ path: string; rows: number; bytes: number }> {\n  const records = await readComputeTracesResolved();\n  let rows = buildNormalizedRows(records);\n  if (opts.passedOnly) {\n    rows = rows.filter((r) => r.grader.passed);\n  }\n  const target = outPath || path.join(COMPUTE_DIR, 'compute-corpus.normalized.jsonl');\n  ensureDir();\n  const body = rows.map((r) => JSON.stringify(r)).join('\\n') + (rows.length ? '\\n' : '');\n  fs.writeFileSync(target, body, 'utf8');\n  return { path: target, rows: rows.length, bytes: Buffer.byteLength(body, 'utf8') };\n}\n\nexport type ComputeTraceStats = {\n  tracePath: string;\n  exists: boolean;\n  records: number;\n  passed: number;\n  failed: number;\n  sessions: number;\n  contracts: number;\n  source: 'local-jsonl' | 'postgres-fallback' | 'empty';\n};\n\nfunction summarizeComputeTraces(\n  records: ComputeTraceRecord[],\n  source: ComputeTraceStats['source']\n): ComputeTraceStats {\n  const sessions = new Set(records.map((r) => r.sessionId));\n  const contracts = new Set(records.map((r) => r.contractId));\n  let passed = 0;\n  for (const r of records) if (r.passed) passed++;\n  return {\n    tracePath: TRACE_PATH,\n    exists: fs.existsSync(TRACE_PATH),\n    records: records.length,\n    passed,\n    failed: records.length - passed,\n    sessions: sessions.size,\n    contracts: contracts.size,\n    source,\n  };\n}\n\n/** Diagnostics: where the corpus lives + how much real compute data has accrued. */\nexport function computeTraceStats(): ComputeTraceStats {\n  const records = readComputeTraces();\n  return summarizeComputeTraces(records, records.length > 0 ? 'local-jsonl' : 'empty');\n}\n\n/**\n * Railway-safe diagnostics: summarize the same corpus source that resolved\n * export would use. This keeps `holo_export_compute_traces` from reporting\n * Postgres-exported rows with local-only stats.records = 0 on ephemeral disks.\n */\nexport async function computeTraceStatsResolved(): Promise<ComputeTraceStats> {\n  const local = readComputeTraces();\n  if (local.length > 0) {\n    return summarizeComputeTraces(local, 'local-jsonl');\n  }\n  if (process.env.DATABASE_URL) {\n    const pgRecords = await readComputeTracesFromPg();\n    if (pgRecords.length > 0) {\n      return summarizeComputeTraces(pgRecords, 'postgres-fallback');\n    }\n  }\n  return summarizeComputeTraces(local, 'empty');\n}\n\n// ── Grading primitive (the live counterpart of compute_suite's accept gate) ────\n//\n// This is the SINGLE call a live grading site invokes to (a) grade a proposed\n// compute mutation against a SimulationContract bound and (b) write the graded\n// tuple through to the durable corpus. It is ADDITIVE: there is no existing live\n// `set_trait_property` grading site in mcp-server to modify (verified by grep), so\n// this introduces no change to existing grading semantics. The accept-gate logic\n// is byte-equivalent to compute_suite._row's grade:\n//\n//     expected = r2(clamp(min, max, expectedRaw))\n//     passed   = (r2(proposed) === expected)         # exact-value match\n//     graded   = clamp(min, max, proposed)           # what would actually apply\n//\n// The caller supplies the GROUND-TRUTH expected value (it knows the op family it\n// asked for); this function does NOT recompute the op — it is the grader+recorder,\n// not the task generator. That keeps grading-semantics ownership with the contract,\n// exactly as the constraint requires.\n\nexport interface GradeComputeInput {\n  sessionId: string;\n  instruction: string;\n  contractId: string;\n  scene: string;\n  bound: ComputePropertyBound;\n  mutation: ComputeMutation;\n  /** Ground-truth expected value (the correct answer for the asked op). */\n  expectedValue: number;\n  /** Op family label, if the caller knows it (corpus-balance signal). */\n  opLabel?: string | null;\n  /** CAEL receipt reference anchoring this grade, if one was produced. */\n  caelReceiptRef?: string | null;\n}\n\nexport interface GradeComputeResult {\n  passed: boolean;\n  expectedValue: number;\n  gradedValue: number;\n  record: ComputeTraceRecord;\n}\n\nfunction clamp(min: number, max: number, v: number): number {\n  return Math.max(min, Math.min(max, v));\n}\n\n/**\n * Grade a proposed compute mutation against its SimulationContract bound AND\n * write the resulting (instruction → mutation → expected/graded → pass/fail →\n * CAEL ref) tuple through to the durable corpus. Returns the verdict + the\n * persisted record.\n *\n * Pure grading semantics (exact-value match within 2dp, clamp-to-bounds), then a\n * best-effort write-through. The write-through never affects the returned verdict.\n */\nexport function gradeComputeMutation(input: GradeComputeInput): GradeComputeResult {\n  const { bound, mutation, expectedValue } = input;\n  const expected = r2(clamp(bound.min, bound.max, expectedValue));\n  const graded = clamp(bound.min, bound.max, mutation.propertyValue);\n  const passed = r2(mutation.propertyValue) === expected;\n\n  const record: ComputeTraceRecord = {\n    sessionId: input.sessionId,\n    instruction: input.instruction,\n    contractId: input.contractId,\n    scene: input.scene,\n    bound: input.bound,\n    mutation: input.mutation,\n    expectedValue: expected,\n    gradedValue: graded,\n    passed,\n    opLabel: input.opLabel ?? null,\n    caelReceiptRef: input.caelReceiptRef ?? null,\n    gradedAt: new Date().toISOString(),\n  };\n\n  // Write-through (additive): mirror the graded tuple to the durable corpus.\n  // Best-effort; never affects the verdict returned above.\n  appendComputeTrace(record);\n\n  return { passed, expectedValue: expected, gradedValue: graded, record };\n}\n\n/** Test-only: the resolved corpus path (so tests can point HOLOMESH_DATA_DIR). */\nexport function _tracePathForTest(): string {\n  return TRACE_PATH;\n}\n\n/** Test-only: inject a fake Postgres pool without loading pg or opening sockets. */\nexport function _setPgForTest(pool: PgLike | null, ready: Promise<void> | null = null): void {\n  pgPool = pool;\n  pgReady = ready;\n}\n","/**\n * Hologram MCP Content Tools - reference tools whose response payload IS a\n * hologram, not text.\n *\n * Today: tool returns text -> client renders.\n * Tomorrow: tool returns .holo bundle -> client (Quest, Vision Pro, browser\n *           R3F) hands off to renderer.\n *\n * v0.1 ships ONE reference tool - `visualize_query_result` - that builds a\n * 3D bar-chart composition from rows of {label, value} and returns a\n * `HologramMcpResponse` with content_type `application/holoscript+holo`.\n *\n * Spec: task_1778114362909_zp7u (Hologram return type for MCP).\n *\n * @package @holoscript/mcp-server\n */\n\nimport type { Tool } from '@modelcontextprotocol/sdk/types.js';\nimport {\n  HOLOGRAM_CONTENT_TYPES,\n  buildHologramMcpResponse,\n  type HologramMcpResponse,\n} from '@holoscript/core';\n\n// =============================================================================\n// JSON Schemas\n// =============================================================================\n\nconst QUERY_ROW_SCHEMA = {\n  type: 'object',\n  description: 'A single row in the query result. `value` is rendered as bar height.',\n  properties: {\n    label: { type: 'string', description: 'X-axis label.' },\n    value: { type: 'number', description: 'Bar height (clamped to [0, 100]).' },\n    color: {\n      type: 'string',\n      description: 'Optional hex color. Falls back to a teal/violet gradient.',\n    },\n  },\n  required: ['label', 'value'],\n};\n\n// =============================================================================\n// Tool Definitions\n// =============================================================================\n\nexport const hologramContentToolDefinitions: Tool[] = [\n  {\n    name: 'visualize_query_result',\n    description:\n      'Reference tool for the hologram MCP content_type protocol: accepts query rows {label, value}, builds a .holo composition rendering them as 3D bars, and returns a `HologramMcpResponse` with content_type `application/holoscript+holo`. Hologram-aware clients (Studio, R3F renderer, Quest 3) detect the content_type and hand off to /hologram instead of rendering text. Chat-only clients still see a text summary at content[0].text. See task_1778114362909_zp7u.',\n    inputSchema: {\n      type: 'object',\n      properties: {\n        rows: {\n          type: 'array',\n          description: 'Query result rows. At least one row is required.',\n          items: QUERY_ROW_SCHEMA,\n          minItems: 1,\n        },\n        title: {\n          type: 'string',\n          description: 'Optional chart title shown above the bars.',\n        },\n        scale: {\n          type: 'number',\n          description: 'Y-axis scale multiplier (default 0.02 for value 0-100).',\n        },\n      },\n      required: ['rows'],\n    },\n  },\n];\n\nconst HOLOGRAM_CONTENT_NAMES = new Set(hologramContentToolDefinitions.map((t) => t.name));\n\nexport function isHologramContentToolName(name: string): boolean {\n  return HOLOGRAM_CONTENT_NAMES.has(name);\n}\n\n// =============================================================================\n// Composition Builder\n// =============================================================================\n\nexport interface VisualizeQueryResultRow {\n  label: string;\n  value: number;\n  color?: string;\n}\n\nfunction clampValue(v: unknown): number {\n  if (typeof v !== 'number' || !Number.isFinite(v)) return 0;\n  if (v < 0) return 0;\n  if (v > 100) return 100;\n  return v;\n}\n\nfunction sanitizeLabel(s: unknown): string {\n  if (typeof s !== 'string') return '';\n  // Strip control chars + quote chars that would break the .holo string literal.\n  return s.replace(/[\\x00-\\x1f\"\\\\]/g, '').slice(0, 64);\n}\n\nconst SAFE_COLOR_PATTERN =\n  /^(?:#?[0-9a-fA-F]{3,8}|hsl\\(\\s*\\d{1,3}(?:\\.\\d+)?(?:deg)?\\s*,\\s*\\d{1,3}%\\s*,\\s*\\d{1,3}%\\s*\\))$/;\n\nfunction sanitizeColor(s: unknown): string | undefined {\n  if (typeof s !== 'string') return undefined;\n  const trimmed = s.trim();\n  return SAFE_COLOR_PATTERN.test(trimmed) ? trimmed : undefined;\n}\n\nfunction defaultColor(idx: number, total: number): string {\n  // Teal -> Violet gradient (HSL h: 170 -> 280)\n  const h = total <= 1 ? 200 : 170 + (110 * idx) / (total - 1);\n  return `hsl(${h.toFixed(0)}, 75%, 55%)`;\n}\n\nfunction parseRows(raw: unknown): VisualizeQueryResultRow[] {\n  if (!Array.isArray(raw)) {\n    throw new Error('visualize_query_result: rows must be an array');\n  }\n  if (raw.length === 0) {\n    throw new Error('visualize_query_result: rows must contain at least one row');\n  }\n  const rows: VisualizeQueryResultRow[] = [];\n  for (let i = 0; i < raw.length; i++) {\n    const item = raw[i];\n    if (!item || typeof item !== 'object') {\n      throw new Error(`visualize_query_result: rows[${i}] must be an object`);\n    }\n    const obj = item as Record<string, unknown>;\n    const label = sanitizeLabel(obj.label);\n    if (!label) {\n      throw new Error(`visualize_query_result: rows[${i}].label must be a non-empty string`);\n    }\n    const value = clampValue(obj.value);\n    const color = sanitizeColor(obj.color);\n    rows.push({ label, value, color });\n  }\n  return rows;\n}\n\n/**\n * Build a .holo composition rendering `rows` as 3D bars. The composition is\n * deliberately minimal - anchor object + one bar per row + label billboards -\n * so the renderer can parse + display it without external assets.\n */\nexport function buildVisualizeQueryResultHolo(\n  rows: VisualizeQueryResultRow[],\n  title: string | undefined,\n  scale: number\n): string {\n  const total = rows.length;\n  const spacing = 0.4;\n  const totalWidth = total * spacing;\n  const x0 = -totalWidth / 2 + spacing / 2;\n  const safeTitle = sanitizeLabel(title);\n\n  const lines: string[] = [];\n  lines.push(`composition \"QueryResult${safeTitle ? ` - ${safeTitle}` : ''}\" {`);\n  lines.push('  environment {');\n  lines.push('    skybox: \"studio\"');\n  lines.push('    ambient_light: 0.4');\n  lines.push('  }');\n  lines.push('');\n\n  // Origin / floor\n  lines.push('  object \"QueryFloor\" {');\n  lines.push('    geometry: \"plane\"');\n  lines.push('    position: [0, 0, 0]');\n  lines.push(`    scale: [${(totalWidth + spacing).toFixed(3)}, 0.01, ${spacing.toFixed(3)}]`);\n  lines.push('    color: \"#1a1a2e\"');\n  lines.push('  }');\n  lines.push('');\n\n  // Title billboard\n  if (safeTitle) {\n    lines.push('  object \"QueryTitle\" {');\n    lines.push(`    @text { value: \"${safeTitle}\", size: 0.12 }`);\n    lines.push('    @billboard { mode: \"camera-facing\" }');\n    lines.push(`    position: [0, ${(spacing + 0.6).toFixed(3)}, 0]`);\n    lines.push('  }');\n    lines.push('');\n  }\n\n  // Bars\n  for (let i = 0; i < total; i++) {\n    const r = rows[i];\n    const label = sanitizeLabel(r.label) || `row-${i + 1}`;\n    const value = clampValue(r.value);\n    const x = (x0 + i * spacing).toFixed(3);\n    const height = Math.max(value * scale, 0.01);\n    const h = height.toFixed(3);\n    const halfH = (height / 2).toFixed(3);\n    const color = sanitizeColor(r.color) ?? defaultColor(i, total);\n\n    lines.push(`  object \"QueryBar_${i}\" {`);\n    lines.push('    geometry: \"box\"');\n    lines.push(`    position: [${x}, ${halfH}, 0]`);\n    lines.push(`    scale: [${(spacing * 0.6).toFixed(3)}, ${h}, ${(spacing * 0.6).toFixed(3)}]`);\n    lines.push(`    color: \"${color}\"`);\n    lines.push('  }');\n\n    // Bar label billboard\n    lines.push(`  object \"QueryLabel_${i}\" {`);\n    lines.push(`    @text { value: \"${label}\", size: 0.06 }`);\n    lines.push('    @billboard { mode: \"camera-facing\" }');\n    lines.push(`    position: [${x}, -0.08, 0]`);\n    lines.push('  }');\n\n    // Value billboard above bar\n    lines.push(`  object \"QueryValue_${i}\" {`);\n    lines.push(`    @text { value: \"${value.toFixed(2)}\", size: 0.05 }`);\n    lines.push('    @billboard { mode: \"camera-facing\" }');\n    lines.push(`    position: [${x}, ${(parseFloat(h) + 0.08).toFixed(3)}, 0]`);\n    lines.push('  }');\n  }\n\n  lines.push('}');\n  return lines.join('\\n');\n}\n\nfunction buildSummaryText(rows: VisualizeQueryResultRow[], title: string | undefined): string {\n  const t = title ? `${title}: ` : '';\n  const top = [...rows].sort((a, b) => b.value - a.value).slice(0, 3);\n  const summary = top.map((r) => `${r.label}=${r.value.toFixed(2)}`).join(', ');\n  return `${t}${rows.length} row(s). Top: ${summary}. Hologram-aware clients render this as a 3D bar chart; chat-only clients see this text.`;\n}\n\n// =============================================================================\n// Handler\n// =============================================================================\n\nexport async function handleHologramContentTool(\n  name: string,\n  args: Record<string, unknown>\n): Promise<HologramMcpResponse> {\n  if (name !== 'visualize_query_result') {\n    throw new Error(`Unknown hologram-content tool: ${name}`);\n  }\n\n  const rows = parseRows(args.rows);\n  const title = typeof args.title === 'string' && args.title.trim() ? args.title.trim() : undefined;\n  const scale =\n    typeof args.scale === 'number' && Number.isFinite(args.scale) && args.scale > 0\n      ? args.scale\n      : 0.02;\n\n  const holoCode = buildVisualizeQueryResultHolo(rows, title, scale);\n  const text = buildSummaryText(rows, title);\n\n  return buildHologramMcpResponse({\n    contentType: HOLOGRAM_CONTENT_TYPES.holo,\n    payload: { kind: 'holo-code', holoCode },\n    text,\n    producedBy: 'visualize_query_result',\n    label: title ?? 'Query Result',\n    caption: `${rows.length} row(s) rendered as 3D bars`,\n    hints: { preferredViewer: 'auto', animate: true },\n    extraMeta: { rowCount: rows.length, scale },\n  });\n}\n","/**\n * Skill Resource Discovery — expose ~/.claude/skills/<name>/SKILL.md as MCP resources.\n *\n * PATH B alternative: instead of backend tool-per-skill, surfaces let the client\n * LLM apply the prompt itself. Codex / Copilot / Gemini discover the catalog via\n * standard MCP resources/list + resources/read.\n */\n\nimport fs from 'fs';\nimport path from 'path';\nimport os from 'os';\n\nconst SKILLS_DIR = path.join(os.homedir(), '.claude', 'skills');\n\nexport interface SkillResource {\n  uri: string;\n  name: string;\n  description: string;\n  mimeType: string;\n}\n\n/**\n * Discover every SKILL.md under ~/.claude/skills/<name>/SKILL.md.\n * Returns stable sorted order (alphabetical by skill name).\n */\nexport function listSkillResources(): SkillResource[] {\n  const resources: SkillResource[] = [];\n\n  if (!fs.existsSync(SKILLS_DIR)) {\n    return resources;\n  }\n\n  const entries = fs.readdirSync(SKILLS_DIR, { withFileTypes: true });\n  for (const entry of entries) {\n    if (!entry.isDirectory()) continue;\n    const skillPath = path.join(SKILLS_DIR, entry.name, 'SKILL.md');\n    if (!fs.existsSync(skillPath)) continue;\n\n    // Derive a short description from the first non-empty line\n    let description = `HoloScript skill: ${entry.name}`;\n    try {\n      const raw = fs.readFileSync(skillPath, 'utf-8');\n      const firstLine = raw.split(/\\r?\\n/).find((l) => l.trim().length > 0);\n      if (firstLine) {\n        description = firstLine\n          .trim()\n          .replace(/^#+\\s*/, '')\n          .slice(0, 200);\n      }\n    } catch {\n      // ignore read errors, fall back to generic description\n    }\n\n    resources.push({\n      uri: `skill://${entry.name}`,\n      name: entry.name,\n      description,\n      mimeType: 'text/markdown',\n    });\n  }\n\n  resources.sort((a, b) => a.name.localeCompare(b.name));\n  return resources;\n}\n\n/**\n * Read the contents of a skill://<name> URI.\n * Returns null if the URI is unrecognized or the file cannot be read.\n */\nexport function readSkillResource(uri: string): { text: string; mimeType: string } | null {\n  const prefix = 'skill://';\n  if (!uri.startsWith(prefix)) return null;\n\n  const skillName = uri.slice(prefix.length).split('/')[0];\n  if (!skillName || skillName.includes('..') || skillName.includes(path.sep)) {\n    return null;\n  }\n\n  const skillPath = path.join(SKILLS_DIR, skillName, 'SKILL.md');\n  if (!fs.existsSync(skillPath)) return null;\n\n  try {\n    const text = fs.readFileSync(skillPath, 'utf-8');\n    return { text, mimeType: 'text/markdown' };\n  } catch {\n    return null;\n  }\n}\n","/**\n * tool-call-gate.ts — the single typed gate at the MCP tool-call fold point.\n *\n * WRAP-WITH-RECEIPTS (dependency-sovereignty-ladder, ratified 2026-07-16):\n * every agent-visible tool call funnels through exactly two\n * `setRequestHandler(CallToolRequestSchema)` sites — index.ts (stdio) and\n * http-server.ts (SSE/HTTP). The audit ruled: gate THERE. This module is that\n * gate. Both handlers route through `gateToolCall`, which\n *\n *   1. emits ONE NDJSON receipt per call — tool name, sha256 of the\n *      canonical-JSON args (NEVER the raw args: args may contain secrets),\n *      caller identity when the transport knows it, start/end timestamps,\n *      ok|error, and the error class — and\n *   2. provides the typed seam (`ToolCallCheck`) where FounderGate / x402 /\n *      envelope-validation checks run BEFORE dispatch.\n *\n * WHY THE DEFAULT CHECK IS PASS-THROUGH (a deliberate wiring decision, not a\n * stub): both transports already run their enforcement DOWNSTREAM of this fold\n * point — the HTTP entry runs `runTripleGate` + audit logging inside\n * `securedToolExecution`, and the stdio entry is a trusted local process whose\n * batch inner calls re-check `authorizeToolCall` (see the AUTH MODEL comment\n * above the stdio handler). Re-running those checks here would double-execute\n * them and change happy-path behavior, which this wrap is contractually\n * forbidden to do. The seam exists so the NEXT check (FounderGate, x402 seat\n * verification, envelope validation) lands in one place instead of two\n * handlers. `passThroughToolCallCheck` is the real, executable default.\n *\n * RECEIPT LANE — mirrors the repo's established append-only NDJSON receipt\n * pattern (compute-trace-store.ts / daemon-emergence-store.ts / holomesh\n * state.ts CAEL audit): synchronous `appendFileSync` under HOLOMESH_DATA_DIR,\n * best-effort (a persistence failure must never change a tool result), one\n * JSON object per line. Canonical-JSON hashing mirrors\n * `stableTrustStringify` (packages/core/src/trust/TrustReceipt.ts): keys\n * recursively sorted, `undefined` entries dropped, so equivalent arg payloads\n * hash identically regardless of key order.\n */\n\nimport { createHash } from 'crypto';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport * as os from 'os';\nimport {\n  FRAME_DECLARATION_MCP_META_KEY,\n  type FrameDeclaration,\n  type FrameViolationType,\n} from '@holoscript/core';\n\n// ── Envelope / context types ─────────────────────────────────────────────────\n\n/** The tool-call envelope as received at a transport fold point. */\nexport interface ToolCallEnvelope {\n  /** MCP tool name exactly as the transport received it. */\n  readonly name: string;\n  /** Raw tool arguments. Never persisted — only their canonical-JSON sha256 is. */\n  readonly args: Record<string, unknown>;\n}\n\n/** What the transport knows about the caller at the fold point. */\nexport interface ToolCallGateContext {\n  /** Which transport entry produced this call. */\n  readonly transport: 'stdio' | 'http';\n  /**\n   * Caller identity when available (OAuth agentId/clientId, envelope signer).\n   * `null` for the trusted local stdio process, which has no identity envelope.\n   */\n  readonly callerId?: string | null;\n  /** MCP session id when the transport tracks one. */\n  readonly sessionId?: string;\n  /** Granted scopes (OAuth or signing envelope) when the transport knows them. */\n  readonly scopes?: readonly string[];\n  /** Active brain frame. `null` means the metadata key was present but invalid. */\n  readonly frameDeclaration?: FrameDeclaration | null;\n}\n\n// ── Check seam (FounderGate / x402 / envelope validation plug in here) ───────\n\n/** Decision returned by a pre-dispatch check. */\nexport interface ToolCallCheckDecision {\n  readonly allowed: boolean;\n  /** Stable identifier of the check that produced this decision. */\n  readonly check: string;\n  /** Human-readable denial reason (used in the thrown error when denied). */\n  readonly reason?: string;\n  /** Structured frame denial persisted into the central gate receipt. */\n  readonly violation?: FrameViolationReceipt;\n}\n\n/**\n * A pre-dispatch check. Runs before the tool dispatch; a denial short-circuits\n * dispatch entirely (receipt still written, `ToolCallGateDeniedError` thrown).\n */\nexport type ToolCallCheck = (\n  envelope: ToolCallEnvelope,\n  ctx: ToolCallGateContext\n) => ToolCallCheckDecision | Promise<ToolCallCheckDecision>;\n\n/**\n * The real default check: allow everything. See the module docblock for why\n * this is correct wiring (downstream enforcement already exists per-transport)\n * rather than a placeholder.\n */\nexport const passThroughToolCallCheck: ToolCallCheck = () => ({\n  allowed: true,\n  check: 'pass-through',\n});\n\n/** Thrown when a `ToolCallCheck` denies a call. Propagates to the transport. */\nexport class ToolCallGateDeniedError extends Error {\n  readonly tool: string;\n  readonly check: string;\n\n  constructor(tool: string, check: string, reason?: string) {\n    super(`Tool call gate denied \"${tool}\" (check: ${check})${reason ? `: ${reason}` : ''}`);\n    this.name = 'ToolCallGateDeniedError';\n    this.tool = tool;\n    this.check = check;\n  }\n}\n\n// ── Receipt shape ─────────────────────────────────────────────────────────────\n\n/** One NDJSON line per gated tool call. */\nexport interface ToolCallReceipt {\n  readonly v: 1;\n  readonly tool: string;\n  /** sha256 hex of the canonical-JSON (recursively key-sorted) args. */\n  readonly argsSha256: string;\n  /** Caller identity or null (trusted local stdio / unknown). */\n  readonly caller: string | null;\n  readonly transport: 'stdio' | 'http';\n  readonly sessionId?: string;\n  /** ISO-8601 UTC start/end of the gated span (check + dispatch). */\n  readonly startedAt: string;\n  readonly endedAt: string;\n  readonly durationMs: number;\n  readonly status: 'ok' | 'error';\n  /** Error constructor name when status === 'error'. */\n  readonly errorClass?: string;\n  /** The check that denied the call, when denial (not dispatch) produced the error. */\n  readonly deniedBy?: string;\n  /** Structured frame boundary event when frame enforcement denied the call. */\n  readonly frameViolation?: FrameViolationReceipt;\n}\n\n/** Stable receipt payload for a frame boundary denial. */\nexport interface FrameViolationReceipt {\n  readonly event: 'frame_violation';\n  readonly violationType: FrameViolationType;\n  readonly tool: string;\n  readonly frameDomain?: string;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n  return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\nfunction isFrameTier(value: unknown): value is 0 | 1 | 2 | 3 {\n  return value === 0 || value === 1 || value === 2 || value === 3;\n}\n\nfunction isStringArray(value: unknown): value is string[] {\n  return Array.isArray(value) && value.every((entry) => typeof entry === 'string');\n}\n\n/**\n * Read the namespaced frame from MCP `_meta`.\n * `undefined` means no frame was supplied; `null` means supplied but invalid.\n */\nexport function frameDeclarationFromMcpMeta(\n  meta: unknown\n): FrameDeclaration | null | undefined {\n  if (\n    !isRecord(meta) ||\n    !Object.prototype.hasOwnProperty.call(meta, FRAME_DECLARATION_MCP_META_KEY)\n  ) {\n    return undefined;\n  }\n\n  const value = meta[FRAME_DECLARATION_MCP_META_KEY];\n  if (\n    !isRecord(value) ||\n    typeof value.domain !== 'string' ||\n    typeof value.horizon !== 'string' ||\n    !isFrameTier(value.capability_tier) ||\n    !isFrameTier(value.trust_tier) ||\n    !isStringArray(value.allowed_tools) ||\n    !isStringArray(value.denied_domains)\n  ) {\n    return null;\n  }\n\n  return value as unknown as FrameDeclaration;\n}\n\n// ── Canonical JSON + hashing (pattern: core/trust stableTrustStringify) ──────\n\nfunction canonicalizeValue(value: unknown): unknown {\n  if (Array.isArray(value)) {\n    return value.map((entry) => canonicalizeValue(entry));\n  }\n  if (value && typeof value === 'object') {\n    const record = value as Record<string, unknown>;\n    const sorted: Record<string, unknown> = {};\n    for (const key of Object.keys(record).sort()) {\n      const entry = record[key];\n      if (entry !== undefined) {\n        sorted[key] = canonicalizeValue(entry);\n      }\n    }\n    return sorted;\n  }\n  return value;\n}\n\n/** Canonical JSON: recursively key-sorted, `undefined` entries dropped. */\nexport function canonicalJsonStringify(value: unknown): string {\n  return JSON.stringify(canonicalizeValue(value)) ?? 'undefined';\n}\n\n/** sha256 hex digest of the canonical-JSON encoding of `value`. */\nexport function sha256OfCanonicalJson(value: unknown): string {\n  return createHash('sha256').update(canonicalJsonStringify(value)).digest('hex');\n}\n\n// ── Receipt persistence (pattern: compute-trace-store.ts append lane) ────────\n\nconst DATA_ROOT =\n  process.env.HOLOMESH_DATA_DIR ||\n  path.join(process.env.HOLOSCRIPT_CACHE_DIR || path.join(os.homedir(), '.holoscript'), 'holomesh');\n\nconst DEFAULT_RECEIPT_PATH = path.join(DATA_ROOT, 'tool-call-receipts', 'tool-calls.ndjson');\n\n/**\n * Resolve the receipt NDJSON path. `HOLOSCRIPT_TOOL_CALL_RECEIPT_PATH` wins\n * (read per-call so tests can redirect into a temp dir), else the HoloMesh\n * data-dir lane every other durable mcp-server store uses.\n */\nexport function resolveToolCallReceiptPath(): string {\n  return process.env.HOLOSCRIPT_TOOL_CALL_RECEIPT_PATH || DEFAULT_RECEIPT_PATH;\n}\n\nconst ensuredDirs = new Set<string>();\n\nfunction ensureReceiptDir(filePath: string): void {\n  const dir = path.dirname(filePath);\n  if (ensuredDirs.has(dir)) return;\n  if (!fs.existsSync(dir)) {\n    fs.mkdirSync(dir, { recursive: true });\n  }\n  ensuredDirs.add(dir);\n}\n\n/**\n * Append one receipt line. Best-effort and synchronous, matching\n * appendComputeTrace / appendEmergenceRecord: a persistence failure must never\n * change the tool result, so errors are logged (stderr) and swallowed.\n */\nexport function writeToolCallReceipt(receipt: ToolCallReceipt): void {\n  try {\n    const filePath = resolveToolCallReceiptPath();\n    ensureReceiptDir(filePath);\n    fs.appendFileSync(filePath, `${JSON.stringify(receipt)}\\n`, 'utf8');\n  } catch (err) {\n    console.error(`[ToolCallGate] receipt append failed: ${(err as Error).message}`);\n  }\n}\n\n// ── Result classification ─────────────────────────────────────────────────────\n\n/** How a dispatch result maps onto the receipt's ok|error status. */\nexport interface ToolCallResultClassification {\n  readonly ok: boolean;\n  readonly errorClass?: string;\n}\n\nexport type ToolCallResultClassifier<T> = (result: T) => ToolCallResultClassification;\n\n/**\n * Classifier for MCP result envelopes (`{ content, isError? }`). Both\n * transports catch tool failures and RETURN `isError: true` rather than\n * throwing, so without this the receipt would record every call as ok.\n */\nexport function classifyMcpEnvelopeResult(result: unknown): ToolCallResultClassification {\n  if (\n    result !== null &&\n    typeof result === 'object' &&\n    (result as { isError?: unknown }).isError === true\n  ) {\n    return { ok: false, errorClass: 'ToolResultError' };\n  }\n  return { ok: true };\n}\n\n// ── The gate ──────────────────────────────────────────────────────────────────\n\nexport interface ToolCallGateOptions<T> {\n  /** Pre-dispatch check. Default: `passThroughToolCallCheck` (see module docblock). */\n  readonly check?: ToolCallCheck;\n  /** Maps the dispatch result onto ok|error for the receipt. Default: always ok. */\n  readonly classifyResult?: ToolCallResultClassifier<T>;\n}\n\nfunction errorClassOf(error: unknown): string {\n  if (error instanceof Error) {\n    return error.constructor.name || error.name || 'Error';\n  }\n  return typeof error;\n}\n\n/**\n * Gate one tool call: run the check, dispatch, and emit exactly one receipt.\n *\n * Contract (WRAP-WITH-RECEIPTS):\n * - Happy path is behavior-neutral: the dispatch result is returned unchanged.\n * - A dispatch throw propagates unchanged (the receipt records it first).\n * - A check denial throws `ToolCallGateDeniedError` without dispatching.\n * - Exactly one receipt line is written per call, on every path.\n */\nexport async function gateToolCall<T>(\n  envelope: ToolCallEnvelope,\n  ctx: ToolCallGateContext,\n  dispatch: (envelope: ToolCallEnvelope, ctx: ToolCallGateContext) => Promise<T> | T,\n  options?: ToolCallGateOptions<T>\n): Promise<T> {\n  const check = options?.check ?? passThroughToolCallCheck;\n  const startedAtMs = Date.now();\n\n  const base = {\n    v: 1 as const,\n    tool: envelope.name,\n    argsSha256: sha256OfCanonicalJson(envelope.args ?? {}),\n    caller: ctx.callerId ?? null,\n    transport: ctx.transport,\n    ...(ctx.sessionId !== undefined ? { sessionId: ctx.sessionId } : {}),\n    startedAt: new Date(startedAtMs).toISOString(),\n  };\n\n  const finishReceipt = (\n    status: 'ok' | 'error',\n    extra?: { errorClass?: string; deniedBy?: string; frameViolation?: FrameViolationReceipt }\n  ): void => {\n    const endedAtMs = Date.now();\n    writeToolCallReceipt({\n      ...base,\n      endedAt: new Date(endedAtMs).toISOString(),\n      durationMs: endedAtMs - startedAtMs,\n      status,\n      ...(extra?.errorClass !== undefined ? { errorClass: extra.errorClass } : {}),\n      ...(extra?.deniedBy !== undefined ? { deniedBy: extra.deniedBy } : {}),\n      ...(extra?.frameViolation !== undefined\n        ? { frameViolation: extra.frameViolation }\n        : {}),\n    });\n  };\n\n  const decision = await check(envelope, ctx);\n  if (!decision.allowed) {\n    finishReceipt('error', {\n      errorClass: 'ToolCallGateDeniedError',\n      deniedBy: decision.check,\n      ...(decision.violation !== undefined ? { frameViolation: decision.violation } : {}),\n    });\n    throw new ToolCallGateDeniedError(envelope.name, decision.check, decision.reason);\n  }\n\n  try {\n    const result = await dispatch(envelope, ctx);\n    const classification: ToolCallResultClassification = options?.classifyResult\n      ? options.classifyResult(result)\n      : { ok: true };\n    if (classification.ok) {\n      finishReceipt('ok');\n    } else {\n      finishReceipt('error', { errorClass: classification.errorClass ?? 'ToolResultError' });\n    }\n    return result;\n  } catch (error) {\n    finishReceipt('error', { errorClass: errorClassOf(error) });\n    throw error;\n  }\n}\n","/**\n * tool-call-checks.ts — the REAL pre-dispatch check wired at both CallTool\n * fold points (dependency-sovereignty-ladder follow-up, 2026-07-16: \"wire a\n * real FounderGate/frame/x402 ToolCallCheck at the two gate call sites\").\n *\n * The seam (`ToolCallCheck` in tool-call-gate.ts) was built for exactly this:\n * FounderGate / x402 verification running BEFORE dispatch, in one place\n * instead of two transport handlers. This module composes three real,\n * already-canonical verifications:\n *\n *   1. FOUNDER GATE (exact-four authority routing) — the shared\n *      `deriveFounderReversibility` classifier from @holoscript/framework\n *      (the same pure module the HoloMesh founder-decision route and the\n *      Studio authority projection consume). It classifies the DECLARED\n *      operation — the tool NAME, normalized (underscores/hyphens → spaces) —\n *      and denies when the route is `joseph-exact-four` (spend/custody,\n *      physical-presence, public-identity, governance) or `prohibited-replan`\n *      (force-push / hard-reset are never approvable). The tool name is the\n *      only classified text ON PURPOSE: tool args are caller DATA, and data\n *      must never steer authority routing (prompt-injection separation — a\n *      board message that merely mentions \"trezor seed\" must not deny the\n *      posting call). No tool name registered today classifies as either\n *      denied route (regression-tested in tool-call-checks.test.ts), so this\n *      branch is behavior-neutral for the current surface and a live forcing\n *      function for any future custody-class tool name.\n *\n *   2. ACTIVE BRAIN FRAME — the language-authored `@frame_declaration` is\n *      carried in namespaced MCP metadata by the headless runtime and checked\n *      with core's canonical trait evaluator. Invalid declarations fail closed;\n *      absent declarations preserve legacy clients.\n *\n *   3. X402 SEAT / SCOPE AUTHORIZATION — the same pure Gate-2 authorizer\n *      (`authorizeToolCall`, security/tool-scopes.ts) that x402-seat OAuth\n *      introspection feeds downstream. Running it at the fold point makes two\n *      things true pre-dispatch, on BOTH transports:\n *        • fail-closed on unregistered tool names (a spoofed name is denied\n *          before any dispatch, even with admin:*), and\n *        • scope insufficiency for identified HTTP callers denies before the\n *          handler runs (previously only inside securedToolExecution).\n *      The stdio transport with `callerId: null` is the trusted local process\n *      (no identity envelope — see the AUTH MODEL comment in index.ts); it is\n *      authorized as `admin:*`, which still fail-closes on unregistered names\n *      once the live registry is known. `authorizeToolCall` is pure, so the\n *      downstream triple gate re-running it on HTTP stays behavior-identical\n *      on the happy path.\n *\n * A denial surfaces as `ToolCallGateDeniedError` from `gateToolCall` (receipt\n * written first, with `deniedBy` naming the check that fired).\n */\n\nimport { deriveFounderReversibility } from '@holoscript/framework';\nimport { checkToolAllowed } from '@holoscript/core';\nimport { authorizeToolCall } from './security/tool-scopes';\nimport type { ToolCallCheck, ToolCallCheckDecision } from './tool-call-gate';\n\n/** Check id recorded when the FounderGate branch denies. */\nexport const FOUNDER_GATE_CHECK_ID = 'founder-gate-exact-four';\n\n/** Check id recorded when an active brain frame denies the call. */\nexport const FRAME_DECLARATION_CHECK_ID = 'frame-declaration';\n\n/** Check id recorded when the x402 scope-authorization branch denies. */\nexport const X402_SCOPE_CHECK_ID = 'x402-scope-authorization';\n\n/** Check id recorded on an allowed call (both branches passed). */\nexport const FOUNDER_GATE_X402_CHECK_ID = `${FOUNDER_GATE_CHECK_ID}+${X402_SCOPE_CHECK_ID}`;\n\n/**\n * Trusted local stdio process (no identity envelope): authorized as admin.\n * `authorizeToolCall` still denies unregistered tool names for admin:* once\n * the live registry is known — the fail-closed-on-unregistered invariant.\n */\nconst TRUSTED_LOCAL_SCOPES: readonly string[] = ['admin:*'];\n\n/**\n * Tool names are snake_case; the founder classifier speaks prose. Normalize\n * separators to spaces so e.g. a future `transfer_custody_authority` tool\n * name hits the custody-authority classifier.\n */\nexport function normalizeToolNameForAuthorityRouting(name: string): string {\n  return name.replace(/[_-]+/g, ' ');\n}\n\n/**\n * FounderGate branch: classify the declared operation (tool name only).\n * Returns a denial decision, or undefined when the route is not denied.\n */\nfunction founderGateDenial(toolName: string): ToolCallCheckDecision | undefined {\n  const routing = deriveFounderReversibility(normalizeToolNameForAuthorityRouting(toolName));\n  if (\n    routing.authorityRoute === 'joseph-exact-four' ||\n    routing.authorityRoute === 'prohibited-replan'\n  ) {\n    return {\n      allowed: false,\n      check: FOUNDER_GATE_CHECK_ID,\n      reason: routing.reason,\n    };\n  }\n  return undefined;\n}\n\n/**\n * The real FounderGate/frame/x402 pre-dispatch check — wired as the `check` option\n * at both `gateToolCall` fold points (index.ts stdio, http-server.ts HTTP).\n */\nexport const founderGateX402ToolCallCheck: ToolCallCheck = (envelope, ctx) => {\n  // 1) FounderGate — exact-four / prohibited-operation authority routing.\n  const founderDenial = founderGateDenial(envelope.name);\n  if (founderDenial) {\n    return founderDenial;\n  }\n\n  // 2) Active brain frame — fail closed for invalid metadata, then enforce\n  // the authored tool allowlist using the canonical core trait helper.\n  if (ctx.frameDeclaration === null) {\n    return {\n      allowed: false,\n      check: FRAME_DECLARATION_CHECK_ID,\n      reason: 'frame_violation: undeclared_frame: invalid frame declaration metadata',\n      violation: {\n        event: 'frame_violation',\n        violationType: 'undeclared_frame',\n        tool: envelope.name,\n      },\n    };\n  }\n  if (ctx.frameDeclaration !== undefined) {\n    const frameResult = checkToolAllowed(ctx.frameDeclaration, envelope.name);\n    if (!frameResult.allowed) {\n      return {\n        allowed: false,\n        check: FRAME_DECLARATION_CHECK_ID,\n        reason: `frame_violation: ${frameResult.violation_type}: ${frameResult.detail ?? 'tool denied by active frame'}`,\n        violation: {\n          event: 'frame_violation',\n          violationType: frameResult.violation_type ?? 'tool_not_allowed',\n          tool: envelope.name,\n          frameDomain: ctx.frameDeclaration.domain,\n        },\n      };\n    }\n  }\n\n  // 3) x402 seat/scope authorization (Gate-2 authorizer at the fold point).\n  const scopes =\n    ctx.transport === 'stdio' && (ctx.callerId === null || ctx.callerId === undefined)\n      ? TRUSTED_LOCAL_SCOPES\n      : (ctx.scopes ?? []);\n  const authz = authorizeToolCall(envelope.name, [...scopes]);\n  if (!authz.authorized) {\n    return {\n      allowed: false,\n      check: X402_SCOPE_CHECK_ID,\n      reason: authz.reason,\n    };\n  }\n\n  return { allowed: true, check: FOUNDER_GATE_X402_CHECK_ID };\n};\n","import fs from 'fs';\nimport path from 'path';\nimport { parseHolo } from '@holoscript/core';\nimport {\n  TEAM_AGENT_PROFILES,\n  type TeamAgentProfile,\n  type AgentRole,\n  type AIProvider,\n} from '@holoscript/framework';\n\nexport function loadNativeAgentCompositions() {\n  const rootDir = path.join(__dirname, '..', 'src', 'holomesh');\n  const galleryDir = path.join(rootDir, 'gallery');\n\n  const filesToScan = [\n    path.join(rootDir, 'plaza.hsplus'),\n    path.join(galleryDir, 'glass-cathedral.hsplus'),\n    path.join(galleryDir, 'mycelium-network.hsplus'),\n    path.join(galleryDir, 'orbital-loom.hsplus'),\n  ];\n\n  for (const filePath of filesToScan) {\n    try {\n      if (!fs.existsSync(filePath)) continue;\n\n      const content = fs.readFileSync(filePath, 'utf-8');\n      const parseResult = parseHolo(content);\n      const ast = parseResult.ast;\n\n      if (!ast) continue;\n\n      // Traverse AST to find objects of type \"team_agent\"\n      for (const obj of ast.objects || []) {\n        if (obj.type === 'team_agent') {\n          const profile = extractAgentProfile(obj);\n          if (profile) {\n            TEAM_AGENT_PROFILES.set(profile.id, profile);\n            console.log(\n              `[HoloMesh] Registered native agent composition: ${profile.name} (from ${path.basename(filePath)})`\n            );\n          }\n        }\n      }\n    } catch (err) {\n      console.warn(`[HoloMesh] Failed to parse agent compositions from ${filePath}:`, err);\n    }\n  }\n}\n\nfunction extractAgentProfile(obj: any): TeamAgentProfile | null {\n  try {\n    // Look for traits in directives or traits\n    const allTraits = [...(obj.traits || []), ...(obj.directives || [])];\n\n    const agentTrait = allTraits.find((t: any) => t.name === 'agent');\n    const capabilitiesTrait = allTraits.find((t: any) => t.name === 'capabilities');\n    const claimFilterTrait = allTraits.find((t: any) => t.name === 'claimFilter');\n    const systemPromptTrait = allTraits.find((t: any) => t.name === 'systemPrompt');\n    const knowledgeTrait = allTraits.find((t: any) => t.name === 'knowledge');\n\n    if (!agentTrait) return null;\n\n    const getArg = (trait: any, key: string, defaultValue?: any) => {\n      if (!trait || !trait.config) return defaultValue;\n      const config = trait.config;\n      // Search the config properties for the key\n      for (let i = 0; i < 20; i += 3) {\n        if (config[`_arg${i}`] === key) {\n          return config[`_arg${i + 2}`];\n        }\n      }\n      return defaultValue;\n    };\n\n    return {\n      id: getArg(agentTrait, 'id'),\n      name: getArg(agentTrait, 'name', obj.name || obj.id?.replace('agent_', '')),\n      role: getArg(agentTrait, 'role') as AgentRole,\n      model: getArg(agentTrait, 'model'),\n      provider: getArg(agentTrait, 'provider') as AIProvider,\n      capabilities: getArg(capabilitiesTrait, 'skills') || [],\n      claimFilter: {\n        roles: getArg(claimFilterTrait, 'roles') || [],\n        maxPriority: getArg(claimFilterTrait, 'maxPriority') || 5,\n      },\n      systemPrompt: getArg(systemPromptTrait, 'text') || '',\n      knowledgeDomains: getArg(knowledgeTrait, 'domains') || [],\n    };\n  } catch (err) {\n    console.error(`[HoloMesh] Error extracting agent profile from object: ${obj.name}`, err);\n    return null;\n  }\n}\n","export type McpServerSize =\n  | 'tiny'\n  | 'small'\n  | 'standard'\n  | 'large'\n  | 'xlarge'\n  | 'laptop'\n  | 'jetson'\n  | 'vast'\n  | 'fleet';\n\nexport type McpServerTransportHint = 'stdio' | 'streamable-http' | 'streamable-http+sse';\n\nexport interface McpServerSizing {\n  profile: McpServerSize;\n  useCase: string;\n  recommendedConsumer: string;\n  transport: McpServerTransportHint;\n  requestBodyMaxBytes: number;\n  postgresPoolMax: number;\n  oauthRateLimit: number;\n  publicAnonRateLimit: number;\n  consumerGenRateLimit: number;\n  consumerGenDailyQuota: number;\n  maxConcurrentToolCalls: number;\n  toolTimeoutMs: number;\n  cacheMaxEntries: number;\n  memoryBudgetMb: number;\n}\n\nexport type McpServerSizingInput = Record<string, string | undefined>;\n\ntype McpServerSizingProfile = Omit<McpServerSizing, 'profile'>;\n\nconst MIB = 1024 * 1024;\nconst MIN_REQUEST_BODY_BYTES = 16 * 1024;\nconst MAX_REQUEST_BODY_BYTES = 100 * MIB;\nconst MIN_TOOL_TIMEOUT_MS = 1_000;\nconst MAX_TOOL_TIMEOUT_MS = 10 * 60_000;\n\nexport const MCP_SERVER_SIZING_PROFILES: Record<McpServerSize, McpServerSizingProfile> = {\n  tiny: {\n    useCase: 'constrained local smoke tests and throwaway stdio probes',\n    recommendedConsumer: 'laptop-windows',\n    transport: 'stdio',\n    requestBodyMaxBytes: 1 * MIB,\n    postgresPoolMax: 2,\n    oauthRateLimit: 30,\n    publicAnonRateLimit: 10,\n    consumerGenRateLimit: 2,\n    consumerGenDailyQuota: 5,\n    maxConcurrentToolCalls: 1,\n    toolTimeoutMs: 15_000,\n    cacheMaxEntries: 128,\n    memoryBudgetMb: 384,\n  },\n  small: {\n    useCase: 'legacy low-traffic local HTTP deployment',\n    recommendedConsumer: 'laptop-windows',\n    transport: 'streamable-http',\n    requestBodyMaxBytes: 5 * MIB,\n    postgresPoolMax: 5,\n    oauthRateLimit: 60,\n    publicAnonRateLimit: 20,\n    consumerGenRateLimit: 3,\n    consumerGenDailyQuota: 10,\n    maxConcurrentToolCalls: 2,\n    toolTimeoutMs: 30_000,\n    cacheMaxEntries: 512,\n    memoryBudgetMb: 768,\n  },\n  standard: {\n    useCase: 'backward-compatible hosted default',\n    recommendedConsumer: 'hosted-service',\n    transport: 'streamable-http',\n    requestBodyMaxBytes: 10 * MIB,\n    postgresPoolMax: 10,\n    oauthRateLimit: 100,\n    publicAnonRateLimit: 30,\n    consumerGenRateLimit: 5,\n    consumerGenDailyQuota: 20,\n    maxConcurrentToolCalls: 4,\n    toolTimeoutMs: 45_000,\n    cacheMaxEntries: 1024,\n    memoryBudgetMb: 1536,\n  },\n  large: {\n    useCase: 'legacy high-traffic HTTP deployment',\n    recommendedConsumer: 'hosted-service',\n    transport: 'streamable-http',\n    requestBodyMaxBytes: 20 * MIB,\n    postgresPoolMax: 20,\n    oauthRateLimit: 250,\n    publicAnonRateLimit: 90,\n    consumerGenRateLimit: 15,\n    consumerGenDailyQuota: 100,\n    maxConcurrentToolCalls: 8,\n    toolTimeoutMs: 90_000,\n    cacheMaxEntries: 4096,\n    memoryBudgetMb: 4096,\n  },\n  xlarge: {\n    useCase: 'legacy maximum HTTP deployment',\n    recommendedConsumer: 'hosted-service',\n    transport: 'streamable-http+sse',\n    requestBodyMaxBytes: 50 * MIB,\n    postgresPoolMax: 40,\n    oauthRateLimit: 500,\n    publicAnonRateLimit: 180,\n    consumerGenRateLimit: 30,\n    consumerGenDailyQuota: 250,\n    maxConcurrentToolCalls: 16,\n    toolTimeoutMs: 120_000,\n    cacheMaxEntries: 8192,\n    memoryBudgetMb: 8192,\n  },\n  laptop: {\n    useCase: 'founder laptop and HoloShell local agent tooling',\n    recommendedConsumer: 'laptop-windows',\n    transport: 'streamable-http+sse',\n    requestBodyMaxBytes: 10 * MIB,\n    postgresPoolMax: 6,\n    oauthRateLimit: 120,\n    publicAnonRateLimit: 40,\n    consumerGenRateLimit: 6,\n    consumerGenDailyQuota: 30,\n    maxConcurrentToolCalls: 4,\n    toolTimeoutMs: 60_000,\n    cacheMaxEntries: 2048,\n    memoryBudgetMb: 2048,\n  },\n  jetson: {\n    useCase: 'owned-metal Jetson edge node with tighter memory and fewer DB connections',\n    recommendedConsumer: 'jetson-orin',\n    transport: 'streamable-http',\n    requestBodyMaxBytes: 8 * MIB,\n    postgresPoolMax: 4,\n    oauthRateLimit: 80,\n    publicAnonRateLimit: 20,\n    consumerGenRateLimit: 3,\n    consumerGenDailyQuota: 15,\n    maxConcurrentToolCalls: 2,\n    toolTimeoutMs: 60_000,\n    cacheMaxEntries: 768,\n    memoryBudgetMb: 2048,\n  },\n  vast: {\n    useCase: 'single Vast.ai GPU worker or render/inference utility node',\n    recommendedConsumer: 'vast-linux-gpu',\n    transport: 'streamable-http',\n    requestBodyMaxBytes: 25 * MIB,\n    postgresPoolMax: 16,\n    oauthRateLimit: 300,\n    publicAnonRateLimit: 90,\n    consumerGenRateLimit: 20,\n    consumerGenDailyQuota: 150,\n    maxConcurrentToolCalls: 8,\n    toolTimeoutMs: 120_000,\n    cacheMaxEntries: 4096,\n    memoryBudgetMb: 8192,\n  },\n  fleet: {\n    useCase: 'public coordinator or multi-worker fleet gateway',\n    recommendedConsumer: 'hosted-service',\n    transport: 'streamable-http+sse',\n    requestBodyMaxBytes: 50 * MIB,\n    postgresPoolMax: 40,\n    oauthRateLimit: 500,\n    publicAnonRateLimit: 180,\n    consumerGenRateLimit: 30,\n    consumerGenDailyQuota: 250,\n    maxConcurrentToolCalls: 16,\n    toolTimeoutMs: 180_000,\n    cacheMaxEntries: 8192,\n    memoryBudgetMb: 16384,\n  },\n};\n\nconst PROFILE_NAMES = new Set(Object.keys(MCP_SERVER_SIZING_PROFILES));\n\nfunction parseServerSize(env: McpServerSizingInput): McpServerSize {\n  const raw = (env.MCP_SERVER_SIZE || env.HOLOSCRIPT_MCP_SERVER_SIZE || 'standard')\n    .trim()\n    .toLowerCase();\n  if (PROFILE_NAMES.has(raw)) return raw as McpServerSize;\n  return 'standard';\n}\n\nfunction parsePositiveInt(\n  raw: string | undefined,\n  fallback: number,\n  options: { min?: number; max?: number } = {}\n): number {\n  if (!raw) return fallback;\n  const trimmed = raw.trim();\n  if (!/^\\d+$/.test(trimmed)) return fallback;\n  const parsed = Number.parseInt(trimmed, 10);\n  if (!Number.isFinite(parsed)) return fallback;\n  const min = options.min ?? 1;\n  const max = options.max ?? Number.MAX_SAFE_INTEGER;\n  if (parsed < min || parsed > max) return fallback;\n  return parsed;\n}\n\nexport function getMcpServerSizing(env: McpServerSizingInput = process.env): McpServerSizing {\n  const profile = parseServerSize(env);\n  const base = MCP_SERVER_SIZING_PROFILES[profile];\n\n  return {\n    profile,\n    useCase: base.useCase,\n    recommendedConsumer: base.recommendedConsumer,\n    transport: base.transport,\n    requestBodyMaxBytes: parsePositiveInt(\n      env.MCP_REQUEST_BODY_MAX_BYTES || env.MCP_MAX_REQUEST_BODY_BYTES,\n      base.requestBodyMaxBytes,\n      { min: MIN_REQUEST_BODY_BYTES, max: MAX_REQUEST_BODY_BYTES }\n    ),\n    postgresPoolMax: parsePositiveInt(\n      env.MCP_POSTGRES_POOL_MAX || env.PGPOOL_MAX,\n      base.postgresPoolMax,\n      { min: 1, max: 100 }\n    ),\n    oauthRateLimit: parsePositiveInt(env.OAUTH_RATE_LIMIT, base.oauthRateLimit),\n    publicAnonRateLimit: parsePositiveInt(env.PUBLIC_ANON_RATE_LIMIT, base.publicAnonRateLimit),\n    consumerGenRateLimit: parsePositiveInt(\n      env.HOLOSCRIPT_CONSUMER_GEN_RATE_LIMIT,\n      base.consumerGenRateLimit\n    ),\n    consumerGenDailyQuota: parsePositiveInt(\n      env.HOLOSCRIPT_CONSUMER_GEN_DAILY_QUOTA,\n      base.consumerGenDailyQuota\n    ),\n    maxConcurrentToolCalls: parsePositiveInt(\n      env.MCP_MAX_CONCURRENT_TOOL_CALLS,\n      base.maxConcurrentToolCalls,\n      { min: 1, max: 256 }\n    ),\n    toolTimeoutMs: parsePositiveInt(env.MCP_TOOL_TIMEOUT_MS, base.toolTimeoutMs, {\n      min: MIN_TOOL_TIMEOUT_MS,\n      max: MAX_TOOL_TIMEOUT_MS,\n    }),\n    cacheMaxEntries: parsePositiveInt(env.MCP_CACHE_MAX_ENTRIES, base.cacheMaxEntries, {\n      min: 1,\n      max: 1_000_000,\n    }),\n    memoryBudgetMb: parsePositiveInt(env.MCP_MEMORY_BUDGET_MB, base.memoryBudgetMb, {\n      min: 128,\n      max: 1_048_576,\n    }),\n  };\n}\n","/**\n * A2A (Agent-to-Agent) Protocol Implementation for HoloScript MCP Server\n *\n * Full implementation of the A2A specification (https://a2a-protocol.org/latest/specification/)\n * providing:\n * - Agent Card at /.well-known/agent-card.json (spec-compliant with securitySchemes)\n * - JSON-RPC 2.0 transport (a2a.sendMessage, a2a.getTask, a2a.listTasks, a2a.cancelTask)\n * - Task lifecycle with full state machine (submitted -> working -> completed/failed/canceled/input-required/auth-required/rejected)\n * - Skill mapping from MCP tools to A2A AgentSkill objects with inputSchema/outputSchema\n * - REST fallback endpoints for backwards compatibility\n *\n * Tasks delegate to the existing MCP tool handler pipeline via triple-gate security,\n * bridging A2A interoperability with the full 82+ HoloScript tool surface.\n */\n\nimport { randomUUID } from 'crypto';\nimport type { Tool } from '@modelcontextprotocol/sdk/types.js';\n\n// =============================================================================\n// A2A TYPES (per specification — https://a2a-protocol.org/latest/specification/)\n// =============================================================================\n\n// ── Security Schemes ─────────────────────────────────────────────────────────\n\nexport interface APIKeySecurityScheme {\n  type: 'apiKey';\n  description?: string;\n  name: string;\n  in: 'header' | 'query';\n}\n\nexport interface HTTPAuthSecurityScheme {\n  type: 'http';\n  description?: string;\n  scheme: string; // e.g. 'bearer', 'basic'\n  bearerFormat?: string;\n}\n\nexport interface OAuth2Flow {\n  authorizationUrl?: string;\n  tokenUrl?: string;\n  scopes: Record<string, string>;\n}\n\nexport interface OAuth2SecurityScheme {\n  type: 'oauth2';\n  description?: string;\n  flows: {\n    authorizationCode?: OAuth2Flow;\n    clientCredentials?: OAuth2Flow;\n    implicit?: OAuth2Flow;\n  };\n}\n\nexport interface OpenIdConnectSecurityScheme {\n  type: 'openIdConnect';\n  description?: string;\n  openIdConnectUrl: string;\n}\n\nexport type SecurityScheme =\n  | APIKeySecurityScheme\n  | HTTPAuthSecurityScheme\n  | OAuth2SecurityScheme\n  | OpenIdConnectSecurityScheme;\n\n// ── Agent Card ───────────────────────────────────────────────────────────────\n\nexport interface AgentProvider {\n  organization: string;\n  url: string;\n}\n\nexport interface AgentCapabilities {\n  streaming: boolean;\n  pushNotifications: boolean;\n  stateTransitionHistory: boolean;\n  extendedAgentCard?: boolean;\n}\n\nexport interface AgentSkill {\n  id: string;\n  name: string;\n  description: string;\n  tags: string[];\n  examples?: string[];\n  inputModes: string[];\n  outputModes: string[];\n  /** JSON Schema for skill input parameters (derived from MCP tool inputSchema) */\n  inputSchema?: Record<string, unknown>;\n  /** JSON Schema for skill output (derived from MCP tool output format) */\n  outputSchema?: Record<string, unknown>;\n}\n\nexport interface AgentCard {\n  /** Unique agent identifier */\n  id: string;\n  /** Human-readable agent name */\n  name: string;\n  /** Detailed agent description */\n  description: string;\n  /** Service endpoint URL (JSON-RPC 2.0 transport) */\n  endpoint: string;\n  /** Agent card version */\n  version: string;\n  /** URL to documentation */\n  documentationUrl?: string;\n  /** Agent provider information */\n  provider: AgentProvider;\n  /** Declared capabilities */\n  capabilities: AgentCapabilities;\n  /** Security scheme definitions (referenced by `security`) */\n  securitySchemes: Record<string, SecurityScheme>;\n  /** Default security requirements (references keys in securitySchemes) */\n  security: Record<string, string[]>[];\n  /** Default input content types accepted */\n  defaultInputModes: string[];\n  /** Default output content types produced */\n  defaultOutputModes: string[];\n  /** Skill declarations (mapped from MCP tools) */\n  skills: AgentSkill[];\n\n  // ── Legacy compatibility fields (kept for backwards-compat) ──────────────\n  /** @deprecated Use `endpoint` instead. Kept for legacy consumers. */\n  url?: string;\n  /** @deprecated Use `securitySchemes` instead. */\n  authentication?: {\n    schemes: string[];\n    credentials?: string;\n  };\n}\n\n// ── Task Types ───────────────────────────────────────────────────────────────\n\n/**\n * Full task state machine per A2A spec.\n *\n * Active states: submitted, working, input-required, auth-required\n * Terminal states: completed, failed, canceled, rejected\n */\nexport type TaskState =\n  | 'submitted'\n  | 'working'\n  | 'input-required'\n  | 'auth-required'\n  | 'completed'\n  | 'failed'\n  | 'canceled'\n  | 'rejected';\n\n/** Terminal states that cannot transition further */\nconst TERMINAL_STATES: TaskState[] = ['completed', 'failed', 'canceled', 'rejected'];\n\nexport interface TaskPart {\n  type: 'text' | 'data' | 'file';\n  /** Text content (when type = 'text') */\n  text?: string;\n  /** Structured data (when type = 'data') */\n  data?: unknown;\n  /** MIME type of the content */\n  mimeType?: string;\n  /** File reference (when type = 'file') */\n  fileReference?: {\n    url: string;\n    name?: string;\n    size?: number;\n    mimeType?: string;\n  };\n}\n\nexport interface TaskMessage {\n  role: 'user' | 'agent';\n  parts: TaskPart[];\n  timestamp: string;\n  /** Conversation context identifier for multi-turn */\n  contextId?: string;\n  /** Parent task reference */\n  taskId?: string;\n  /** Related task references */\n  referenceTaskIds?: string[];\n}\n\nexport interface TaskArtifact {\n  /** Unique artifact identifier */\n  id: string;\n  name: string;\n  description?: string;\n  parts: TaskPart[];\n  index: number;\n  /** Primary media type */\n  mediaType?: string;\n  /** Additional artifact metadata */\n  metadata?: Record<string, unknown>;\n}\n\nexport interface A2ATask {\n  id: string;\n  sessionId?: string;\n  contextId?: string;\n  status: {\n    state: TaskState;\n    message?: TaskMessage;\n    timestamp: string;\n  };\n  history: TaskMessage[];\n  artifacts: TaskArtifact[];\n  metadata?: Record<string, unknown>;\n  createdAt: string;\n  updatedAt: string;\n}\n\n// ── Request/Response Types ───────────────────────────────────────────────────\n\nexport interface SendTaskRequest {\n  id?: string;\n  sessionId?: string;\n  contextId?: string;\n  /** Optional idempotency key for duplicate suppression across retries */\n  idempotencyKey?: string;\n  message: TaskMessage;\n  /** Optional: specify which skill (MCP tool) to invoke */\n  skillId?: string;\n  /** Optional: direct tool arguments for skill invocation */\n  arguments?: Record<string, unknown>;\n  metadata?: Record<string, unknown>;\n}\n\nexport interface SendTaskResponse {\n  id: string;\n  sessionId?: string;\n  contextId?: string;\n  status: A2ATask['status'];\n  artifacts: TaskArtifact[];\n  history: TaskMessage[];\n}\n\n// ── JSON-RPC 2.0 Types ──────────────────────────────────────────────────────\n\nexport interface JsonRpcRequest {\n  jsonrpc: '2.0';\n  id: string | number | null;\n  method: string;\n  params?: Record<string, unknown>;\n}\n\nexport interface JsonRpcResponse {\n  jsonrpc: '2.0';\n  id: string | number | null;\n  result?: unknown;\n  error?: {\n    code: number;\n    message: string;\n    data?: unknown;\n  };\n}\n\n// Standard JSON-RPC error codes\nconst _JSONRPC_PARSE_ERROR = -32700;\nconst JSONRPC_INVALID_REQUEST = -32600;\nconst JSONRPC_METHOD_NOT_FOUND = -32601;\nconst JSONRPC_INVALID_PARAMS = -32602;\nconst _JSONRPC_INTERNAL_ERROR = -32603;\n// A2A-specific error codes (application layer: -32000 to -32099)\nconst A2A_TASK_NOT_FOUND = -32001;\nconst A2A_TASK_NOT_CANCELABLE = -32002;\n\n// =============================================================================\n// SKILL CATEGORY MAPPING\n// =============================================================================\n\n/**\n * Maps MCP tool name prefixes/patterns to A2A skill tags for rich discoverability.\n */\nexport function deriveSkillTags(toolName: string): string[] {\n  const tags: string[] = ['holoscript'];\n\n  // Parsing & validation\n  if (toolName.startsWith('parse_') || toolName === 'validate_holoscript') {\n    tags.push('parsing', 'validation', 'language');\n  }\n  // Universal traits (v6)\n  else if (toolName === 'suggest_universal_traits') {\n    tags.push('traits', 'universal', 'service', 'infrastructure');\n  }\n  // Service contracts\n  else if (toolName.includes('service_contract')) {\n    tags.push('contract', 'openapi', 'codegen', 'service');\n  }\n  // Traits\n  else if (toolName.includes('trait')) {\n    tags.push('traits', 'spatial', 'vr');\n  }\n  // Generation\n  else if (toolName.startsWith('generate_') || toolName === 'generate_scene') {\n    tags.push('generation', 'ai', 'codegen');\n  }\n  // Receipt capability query (must come before the holo_query catch-all)\n  else if (toolName.startsWith('holo_query_receipts') || toolName.startsWith('holo_list_receipt')) {\n    tags.push('receipts', 'capability', 'query');\n  }\n  // Codebase intelligence\n  else if (\n    toolName.startsWith('holo_absorb') ||\n    toolName.startsWith('holo_query') ||\n    toolName.startsWith('holo_impact') ||\n    toolName.startsWith('holo_detect') ||\n    toolName.startsWith('holo_graph_status') ||\n    toolName.startsWith('holo_resolve') ||\n    toolName.startsWith('holo_get_absorb')\n  ) {\n    tags.push('codebase', 'analysis', 'intelligence');\n  }\n  // Graph RAG\n  else if (toolName.startsWith('holo_semantic') || toolName.startsWith('holo_ask')) {\n    tags.push('search', 'rag', 'knowledge');\n  }\n  // Graph tools\n  else if (\n    toolName.startsWith('holo_parse_to') ||\n    toolName.startsWith('holo_visualize') ||\n    toolName.startsWith('holo_get_node') ||\n    toolName.startsWith('holo_design') ||\n    toolName.startsWith('holo_diff') ||\n    toolName.startsWith('holo_suggest_connections')\n  ) {\n    tags.push('graph', 'visualization', 'analysis');\n  }\n  // Self-improve / quality\n  else if (\n    toolName.startsWith('holo_self') ||\n    toolName.startsWith('holo_validate') ||\n    toolName.startsWith('holo_quality') ||\n    toolName.startsWith('holo_verify')\n  ) {\n    tags.push('quality', 'self-improvement', 'testing');\n  }\n  // File operations\n  else if (\n    toolName.startsWith('holo_write') ||\n    toolName.startsWith('holo_edit') ||\n    toolName.startsWith('holo_read') ||\n    toolName.startsWith('holo_git')\n  ) {\n    tags.push('filesystem', 'editing', 'git');\n  }\n  // Wisdom/gotcha\n  else if (\n    toolName.startsWith('holo_query_wisdom') ||\n    toolName.startsWith('holo_list_gotchas') ||\n    toolName.startsWith('holo_check_gotchas')\n  ) {\n    tags.push('knowledge', 'wisdom', 'patterns');\n  }\n  // Refactor/codegen\n  else if (toolName.startsWith('holo_generate_refactor') || toolName.startsWith('holo_scaffold')) {\n    tags.push('refactoring', 'codegen', 'architecture');\n  }\n  // IDE tools\n  else if (toolName.startsWith('hs_') && !toolName.startsWith('hs_ai_')) {\n    tags.push('ide', 'lsp', 'editing');\n  }\n  // Brittney-Lite AI\n  else if (toolName.startsWith('hs_ai_')) {\n    tags.push('ai', 'assistant', 'brittney');\n  }\n  // Browser control\n  else if (toolName.startsWith('browser_')) {\n    tags.push('browser', 'preview', 'rendering');\n  }\n  // Compilation\n  else if (\n    toolName.startsWith('compile_') ||\n    toolName === 'compile_holoscript' ||\n    toolName.startsWith('get_compilation') ||\n    toolName === 'list_export_targets' ||\n    toolName.startsWith('get_circuit')\n  ) {\n    tags.push('compilation', 'export', 'multi-target');\n  }\n  // Networking\n  else if (toolName.startsWith('push_state') || toolName.startsWith('fetch_authoritative')) {\n    tags.push('networking', 'multiplayer', 'sync');\n  }\n  // Snapshots / temporal\n  else if (\n    toolName.includes('snapshot') ||\n    toolName.includes('rewind') ||\n    toolName.includes('temporal')\n  ) {\n    tags.push('temporal', 'snapshot', 'versioning');\n  }\n  // Monitoring\n  else if (toolName.includes('telemetry') || toolName.includes('metrics')) {\n    tags.push('monitoring', 'telemetry', 'observability');\n  }\n  // Rendering/sharing\n  else if (toolName.includes('render') || toolName.includes('share')) {\n    tags.push('rendering', 'preview', 'sharing');\n  }\n  // GLTF\n  else if (toolName.includes('gltf')) {\n    tags.push('gltf', 'import', 'export', '3d');\n  }\n  // Agent orchestration\n  else if (\n    toolName === 'discover_agents' ||\n    toolName === 'delegate_task' ||\n    toolName === 'get_task_status' ||\n    toolName === 'compose_workflow' ||\n    toolName === 'execute_workflow'\n  ) {\n    tags.push('agent', 'orchestration', 'delegation', 'workflow');\n  }\n  // Absorb service\n  else if (toolName.startsWith('absorb_')) {\n    tags.push('absorb', 'service', 'pipeline');\n  }\n  // Testing\n  else if (toolName.includes('test') || toolName === 'execute_holotest') {\n    tags.push('testing', 'spatial', 'validation');\n  }\n  // Docs / explanation\n  else if (\n    toolName.includes('syntax') ||\n    toolName.includes('example') ||\n    toolName.includes('explain') ||\n    toolName.includes('analyze') ||\n    toolName.includes('docs')\n  ) {\n    tags.push('documentation', 'learning', 'reference');\n  }\n  // Training data\n  else if (toolName.includes('training') || toolName.includes('hololand')) {\n    tags.push('training', 'dataset', 'fine-tuning');\n  }\n  // 3D object generation\n  else if (toolName === 'generate_3d_object') {\n    tags.push('3d', 'mesh', 'generation');\n  }\n  // Format conversion\n  else if (toolName === 'convert_format' || toolName === 'edit_holo') {\n    tags.push('conversion', 'transformation', 'editing');\n  }\n  // Moltbook social tools\n  else if (toolName.startsWith('moltbook_')) {\n    tags.push('social', 'moltbook', 'engagement');\n  }\n  // Catch-all\n  else {\n    tags.push('utility');\n  }\n\n  return tags;\n}\n\n/**\n * Generate example prompts for a skill based on its tool definition\n */\nfunction deriveSkillExamples(tool: Tool): string[] {\n  const examples: string[] = [];\n  const name = tool.name;\n\n  if (name === 'parse_hs') {\n    examples.push('Parse this HoloScript code: object Cube { position: [0,1,0] }');\n  } else if (name === 'validate_holoscript') {\n    examples.push('Validate my HoloScript composition for errors');\n  } else if (name === 'suggest_traits') {\n    examples.push('Suggest traits for a sword that can be picked up and thrown');\n  } else if (name === 'suggest_universal_traits') {\n    examples.push('Suggest universal traits for a REST API with Redis caching and JWT auth');\n  } else if (name === 'generate_service_contract') {\n    examples.push('Generate .holo composition from this OpenAPI spec');\n  } else if (name === 'explain_service_contract') {\n    examples.push('Explain the contract structure of this .holo service composition');\n  } else if (name === 'validate_composition') {\n    examples.push('Validate this .holo composition for trait constraint violations');\n  } else if (name === 'absorb_typescript') {\n    examples.push('Convert this Express/TypeScript service to a .holo composition');\n  } else if (name === 'generate_scene') {\n    examples.push('Generate a multiplayer VR lobby with teleportation');\n  } else if (name === 'compile_holoscript') {\n    examples.push('Compile this scene to Unity format');\n  } else if (name === 'render_preview') {\n    examples.push('Render a preview of my 3D scene as PNG');\n  } else if (name === 'holo_absorb_repo') {\n    examples.push(\n      'Scan and index this repository for code intelligence (call this before holo_ask_codebase)'\n    );\n    examples.push(\n      'holo_absorb_repo with rootDir set to the monorepo root, then run holo_semantic_search'\n    );\n  } else if (name === 'holo_ask_codebase') {\n    examples.push('After holo_absorb_repo: how does the compiler pipeline work?');\n  }\n\n  return examples;\n}\n\n// =============================================================================\n// MCP TOOL -> A2A SKILL CONVERSION\n// =============================================================================\n\n/**\n * Convert an MCP Tool definition into an A2A AgentSkill.\n *\n * Maps the full MCP inputSchema to A2A's inputSchema field, and generates\n * a standard outputSchema describing the tool's return format.\n */\nexport function mcpToolToA2ASkill(tool: Tool): AgentSkill {\n  const skill: AgentSkill = {\n    id: tool.name,\n    name: tool.name\n      .replace(/_/g, ' ')\n      .replace(/\\b\\w/g, (c) => c.toUpperCase())\n      .replace(/^Hs /, 'HS ')\n      .replace(/^Holo /, 'Holo'),\n    description: tool.description || `HoloScript tool: ${tool.name}`,\n    tags: deriveSkillTags(tool.name),\n    examples: deriveSkillExamples(tool),\n    inputModes: ['text/plain', 'application/json'],\n    outputModes: ['text/plain', 'application/json', 'application/holoscript'],\n  };\n\n  // Map MCP tool inputSchema to A2A skill inputSchema\n  if (tool.inputSchema) {\n    skill.inputSchema = tool.inputSchema as Record<string, unknown>;\n  }\n\n  // Standard output schema for all HoloScript tools\n  skill.outputSchema = {\n    type: 'object',\n    properties: {\n      content: {\n        type: 'array',\n        items: {\n          type: 'object',\n          properties: {\n            type: { type: 'string', enum: ['text'] },\n            text: { type: 'string' },\n          },\n        },\n      },\n    },\n  };\n\n  return skill;\n}\n\n/**\n * Build the complete A2A Agent Card from the current tool inventory.\n *\n * Generates a spec-compliant Agent Card with:\n * - Unique `id` identifier\n * - `endpoint` URL for JSON-RPC 2.0 transport\n * - `securitySchemes` with API key, Bearer token, and OAuth2 definitions\n * - `security` array referencing the scheme keys\n * - All MCP tools mapped to AgentSkill objects with inputSchema/outputSchema\n */\nexport function buildAgentCard(\n  allTools: Tool[],\n  baseUrl: string,\n  apiKeyConfigured: boolean\n): AgentCard {\n  const skills = allTools.map(mcpToolToA2ASkill);\n\n  // Build security schemes based on configuration\n  const securitySchemes: Record<string, SecurityScheme> = {};\n  const security: Record<string, string[]>[] = [];\n\n  if (apiKeyConfigured) {\n    securitySchemes['apiKey'] = {\n      type: 'apiKey',\n      description: 'API key passed via x-api-key header',\n      name: 'x-api-key',\n      in: 'header',\n    };\n    securitySchemes['bearerAuth'] = {\n      type: 'http',\n      description: 'Bearer token (API key or OAuth2 access token) via Authorization header',\n      scheme: 'bearer',\n    };\n    securitySchemes['oauth2'] = {\n      type: 'oauth2',\n      description: 'OAuth 2.1 with PKCE (S256) and client credentials flows',\n      flows: {\n        authorizationCode: {\n          authorizationUrl: `${baseUrl}/oauth/authorize`,\n          tokenUrl: `${baseUrl}/oauth/token`,\n          scopes: {\n            'tools:read': 'Read-only access to tool outputs (parse, validate, list, explain)',\n            'tools:execute': 'Execute tools that produce output (compile, render, generate)',\n            'tasks:read': 'Read A2A task state and history',\n            'tasks:write': 'Create, send, and cancel A2A tasks',\n            admin: 'Full administrative access to all tools and endpoints',\n            // Legacy scope aliases (backwards compatibility)\n            'tools:write': 'Legacy alias for tools:execute',\n            'tools:admin': 'Legacy alias for admin',\n            'admin:*': 'Legacy alias for admin',\n          },\n        },\n        clientCredentials: {\n          tokenUrl: `${baseUrl}/oauth/token`,\n          scopes: {\n            'tools:read': 'Read-only access to tool outputs',\n            'tools:execute': 'Execute tools that produce output',\n            'tasks:read': 'Read A2A task state and history',\n            'tasks:write': 'Create, send, and cancel A2A tasks',\n          },\n        },\n      },\n    };\n    securitySchemes['openIdConnect'] = {\n      type: 'openIdConnect',\n      description: 'OpenID Connect discovery for OAuth 2.1',\n      openIdConnectUrl: `${baseUrl}/.well-known/openid-configuration`,\n    };\n\n    // Any one of these schemes is sufficient\n    security.push({ apiKey: [] });\n    security.push({ bearerAuth: [] });\n    security.push({ oauth2: ['tools:read'] });\n  }\n\n  const card: AgentCard = {\n    id: 'holoscript-agent',\n    name: 'HoloScript Agent',\n    description:\n      `HoloScript v6.0 language tooling agent — parse, validate, compile, render, and generate ` +\n      `spatial computing code (.hs/.hsplus/.holo) across 28+ export targets including Unity, ` +\n      `Unreal, WebGPU, VisionOS, and more. Provides ${allTools.length}+ tools for codebase intelligence, ` +\n      `AI-assisted code generation, graph analysis, multiplayer networking, and browser preview.`,\n    endpoint: `${baseUrl}/a2a`,\n    version: '1.0.0',\n    documentationUrl: 'https://github.com/brianonbased-dev/HoloScript',\n    provider: {\n      organization: 'HoloScript',\n      url: 'https://holoscript.net',\n    },\n    capabilities: {\n      streaming: false,\n      pushNotifications: false,\n      stateTransitionHistory: true,\n      extendedAgentCard: false,\n    },\n    securitySchemes,\n    security,\n    defaultInputModes: ['text/plain', 'application/json'],\n    defaultOutputModes: ['text/plain', 'application/json', 'application/holoscript'],\n    skills,\n\n    // Legacy compatibility\n    url: `${baseUrl}/a2a`,\n    authentication: apiKeyConfigured\n      ? {\n          schemes: ['Bearer', 'ApiKey'],\n          credentials: 'API key via Authorization: Bearer <key> or x-api-key header',\n        }\n      : {\n          schemes: [],\n        },\n  };\n\n  return card;\n}\n\n// =============================================================================\n// IN-MEMORY TASK STORE\n// =============================================================================\n\nconst taskStore = new Map<string, A2ATask>();\nconst idempotencyStore = new Map<string, string>();\nconst MAX_TASKS = 10000;\nconst TASK_TTL_MS = 24 * 60 * 60 * 1000; // 24 hours\n\n/**\n * Evict expired tasks from the store.\n */\nfunction evictExpiredTasks(): void {\n  const now = Date.now();\n  for (const [id, task] of taskStore) {\n    if (now - new Date(task.createdAt).getTime() > TASK_TTL_MS) {\n      taskStore.delete(id);\n      for (const [key, taskId] of idempotencyStore.entries()) {\n        if (taskId === id) idempotencyStore.delete(key);\n      }\n    }\n  }\n}\n\n/**\n * Create a new task in the store.\n */\nexport function createTask(request: SendTaskRequest): A2ATask {\n  evictExpiredTasks();\n\n  // Idempotent create by explicit id\n  if (request.id) {\n    const existing = taskStore.get(request.id);\n    if (existing) return existing;\n  }\n\n  // Idempotent create by idempotency key\n  const key = request.idempotencyKey?.trim();\n  if (key) {\n    const existingId = idempotencyStore.get(key);\n    if (existingId) {\n      const existingTask = taskStore.get(existingId);\n      if (existingTask) return existingTask;\n      idempotencyStore.delete(key);\n    }\n  }\n\n  // Enforce max tasks\n  if (taskStore.size >= MAX_TASKS) {\n    // Remove oldest completed/failed/canceled/rejected tasks first\n    const removable = [...taskStore.entries()]\n      .filter(([, t]) => TERMINAL_STATES.includes(t.status.state))\n      .sort((a, b) => new Date(a[1].createdAt).getTime() - new Date(b[1].createdAt).getTime());\n\n    for (const [id] of removable) {\n      taskStore.delete(id);\n      if (taskStore.size < MAX_TASKS) break;\n    }\n  }\n\n  const now = new Date().toISOString();\n  const task: A2ATask = {\n    id: request.id || randomUUID(),\n    sessionId: request.sessionId,\n    contextId: request.contextId,\n    status: {\n      state: 'submitted',\n      timestamp: now,\n    },\n    history: [request.message],\n    artifacts: [],\n    metadata: request.metadata,\n    createdAt: now,\n    updatedAt: now,\n  };\n\n  taskStore.set(task.id, task);\n  if (key) {\n    idempotencyStore.set(key, task.id);\n  }\n  return task;\n}\n\n/**\n * Get a task by ID.\n */\nexport function getTask(id: string): A2ATask | undefined {\n  return taskStore.get(id);\n}\n\n/**\n * List all tasks, optionally filtered.\n */\nexport function listTasks(filters?: {\n  sessionId?: string;\n  contextId?: string;\n  state?: TaskState;\n  limit?: number;\n  offset?: number;\n}): { tasks: A2ATask[]; total: number } {\n  let tasks = [...taskStore.values()];\n\n  if (filters?.sessionId) {\n    tasks = tasks.filter((t) => t.sessionId === filters.sessionId);\n  }\n  if (filters?.contextId) {\n    tasks = tasks.filter((t) => t.contextId === filters.contextId);\n  }\n  if (filters?.state) {\n    tasks = tasks.filter((t) => t.status.state === filters.state);\n  }\n\n  // Sort by creation time, newest first\n  tasks.sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime());\n\n  const total = tasks.length;\n  const offset = filters?.offset || 0;\n  const limit = filters?.limit || 50;\n  tasks = tasks.slice(offset, offset + limit);\n\n  return { tasks, total };\n}\n\n/**\n * Cancel a task.\n */\nexport function cancelTask(id: string): A2ATask | undefined {\n  const task = taskStore.get(id);\n  if (!task) return undefined;\n\n  // Only cancel if not already in a terminal state\n  if (TERMINAL_STATES.includes(task.status.state)) {\n    return task; // Already terminal, return as-is\n  }\n\n  const now = new Date().toISOString();\n  task.status = {\n    state: 'canceled',\n    timestamp: now,\n  };\n  task.updatedAt = now;\n  return task;\n}\n\n/**\n * Execute a task by routing to the appropriate MCP tool handler.\n *\n * This is the bridge between A2A task semantics and MCP tool execution.\n * It extracts the tool name and arguments from the task message, invokes\n * the handler pipeline, and updates the task with results.\n */\nexport async function executeTask(\n  task: A2ATask,\n  toolHandler: (name: string, args: Record<string, unknown>) => Promise<unknown>\n): Promise<A2ATask> {\n  const now = () => new Date().toISOString();\n\n  // Transition to working\n  task.status = { state: 'working', timestamp: now() };\n  task.updatedAt = now();\n\n  try {\n    // Extract tool invocation from task\n    const { skillId, args } = extractToolInvocation(task);\n\n    if (!skillId) {\n      // No specific tool requested; return guidance\n      task.status = {\n        state: 'input-required',\n        message: {\n          role: 'agent',\n          parts: [\n            {\n              type: 'text',\n              text:\n                'Please specify a skillId (MCP tool name) to invoke. ' +\n                'You can discover available skills via GET /.well-known/agent-card.json ' +\n                'or by calling the a2a.getExtendedAgentCard JSON-RPC method.',\n            },\n          ],\n          timestamp: now(),\n        },\n        timestamp: now(),\n      };\n      task.updatedAt = now();\n      return task;\n    }\n\n    // Execute the MCP tool\n    const result = await toolHandler(skillId, args);\n\n    // Build artifact from result\n    const resultText = typeof result === 'string' ? result : JSON.stringify(result, null, 2);\n    const artifact: TaskArtifact = {\n      id: randomUUID(),\n      name: `${skillId}_result`,\n      description: `Output from ${skillId} tool execution`,\n      parts: [\n        {\n          type: 'text',\n          text: resultText,\n          mimeType: typeof result === 'string' ? 'text/plain' : 'application/json',\n        },\n      ],\n      index: task.artifacts.length,\n      mediaType: typeof result === 'string' ? 'text/plain' : 'application/json',\n    };\n    task.artifacts.push(artifact);\n\n    // Build agent response message\n    const agentMessage: TaskMessage = {\n      role: 'agent',\n      parts: [{ type: 'text', text: resultText }],\n      timestamp: now(),\n      contextId: task.contextId,\n      taskId: task.id,\n    };\n    task.history.push(agentMessage);\n\n    // Transition to completed\n    task.status = {\n      state: 'completed',\n      message: agentMessage,\n      timestamp: now(),\n    };\n    task.updatedAt = now();\n  } catch (error) {\n    const errorMessage = error instanceof Error ? error.message : String(error);\n\n    const agentMessage: TaskMessage = {\n      role: 'agent',\n      parts: [{ type: 'text', text: `Error: ${errorMessage}` }],\n      timestamp: now(),\n      contextId: task.contextId,\n      taskId: task.id,\n    };\n    task.history.push(agentMessage);\n\n    task.status = {\n      state: 'failed',\n      message: agentMessage,\n      timestamp: now(),\n    };\n    task.updatedAt = now();\n  }\n\n  return task;\n}\n\n/**\n * Extract the MCP tool name and arguments from a task's request context.\n *\n * Supports multiple invocation patterns:\n * 1. Explicit skillId + arguments in the task metadata\n * 2. JSON payload in the first message part with { tool, arguments }\n * 3. Data parts with tool invocation\n */\nfunction extractToolInvocation(task: A2ATask): {\n  skillId: string | undefined;\n  args: Record<string, unknown>;\n} {\n  // Pattern 1: metadata.skillId (set from request body)\n  if (task.metadata?.skillId) {\n    return {\n      skillId: task.metadata.skillId as string,\n      args: (task.metadata.arguments as Record<string, unknown>) || {},\n    };\n  }\n\n  // Pattern 2: Parse the first user message for structured invocation\n  const firstMessage = task.history.find((m) => m.role === 'user');\n  if (firstMessage) {\n    for (const part of firstMessage.parts) {\n      // Try parsing as JSON tool invocation\n      if (part.type === 'text' && part.text) {\n        try {\n          const parsed = JSON.parse(part.text);\n          if (parsed.tool || parsed.skillId) {\n            return {\n              skillId: parsed.tool || parsed.skillId,\n              args: parsed.arguments || parsed.args || {},\n            };\n          }\n        } catch {\n          // Not JSON, try other patterns\n        }\n      }\n      // Data parts with tool invocation\n      if (part.type === 'data' && part.data) {\n        const data = part.data as Record<string, unknown>;\n        if (data.tool || data.skillId) {\n          return {\n            skillId: (data.tool || data.skillId) as string,\n            args: (data.arguments || data.args || {}) as Record<string, unknown>,\n          };\n        }\n      }\n    }\n  }\n\n  return { skillId: undefined, args: {} };\n}\n\n// =============================================================================\n// JSON-RPC 2.0 TRANSPORT HANDLER\n// =============================================================================\n\n/**\n * Handle a JSON-RPC 2.0 request per A2A specification.\n *\n * Supported methods:\n * - a2a.sendMessage: Send a message to create/continue a task\n * - a2a.getTask: Get task by ID\n * - a2a.listTasks: List tasks with optional filters\n * - a2a.cancelTask: Cancel a running task\n * - a2a.getExtendedAgentCard: Get agent card (authenticated, may include extra info)\n *\n * @param request The parsed JSON-RPC request\n * @param toolHandler Function to execute MCP tools (routed through triple-gate security)\n * @param agentCardBuilder Function to build the agent card for getExtendedAgentCard\n * @returns JSON-RPC response\n */\nexport async function handleJsonRpcRequest(\n  request: JsonRpcRequest,\n  toolHandler: (name: string, args: Record<string, unknown>) => Promise<unknown>,\n  agentCardBuilder?: () => AgentCard\n): Promise<JsonRpcResponse> {\n  const { id, method, params } = request;\n\n  switch (method) {\n    // ── a2a.sendMessage ────────────────────────────────────────────────────\n    case 'a2a.sendMessage': {\n      if (!params?.message) {\n        return {\n          jsonrpc: '2.0',\n          id,\n          error: {\n            code: JSONRPC_INVALID_PARAMS,\n            message: 'Missing required parameter: message',\n          },\n        };\n      }\n\n      const message: TaskMessage = params.message as TaskMessage;\n      if (!message.parts || !Array.isArray(message.parts) || message.parts.length === 0) {\n        return {\n          jsonrpc: '2.0',\n          id,\n          error: {\n            code: JSONRPC_INVALID_PARAMS,\n            message: 'message.parts must be a non-empty array',\n          },\n        };\n      }\n\n      // Ensure timestamp\n      if (!message.timestamp) {\n        message.timestamp = new Date().toISOString();\n      }\n      if (!message.role) {\n        message.role = 'user';\n      }\n\n      const taskRequest: SendTaskRequest = {\n        id: params.id as string | undefined,\n        sessionId: params.sessionId as string | undefined,\n        contextId: (params.contextId || message.contextId) as string | undefined,\n        idempotencyKey: (params.idempotencyKey as string | undefined) ?? undefined,\n        message,\n        skillId: params.skillId as string | undefined,\n        arguments: params.arguments as Record<string, unknown> | undefined,\n        metadata: {\n          ...((params.metadata as Record<string, unknown>) || {}),\n          ...(params.skillId ? { skillId: params.skillId } : {}),\n          ...(params.arguments ? { arguments: params.arguments } : {}),\n        },\n      };\n\n      // Idempotent short-circuit by explicit task id\n      if (taskRequest.id) {\n        const existingById = getTask(taskRequest.id);\n        if (existingById) {\n          return {\n            jsonrpc: '2.0',\n            id,\n            result: taskToResponse(existingById),\n          };\n        }\n      }\n\n      // Idempotent short-circuit by idempotency key\n      const idemKey = taskRequest.idempotencyKey?.trim();\n      if (idemKey) {\n        const existingTaskId = idempotencyStore.get(idemKey);\n        if (existingTaskId) {\n          const existingTask = getTask(existingTaskId);\n          if (existingTask) {\n            return {\n              jsonrpc: '2.0',\n              id,\n              result: taskToResponse(existingTask),\n            };\n          }\n        }\n      }\n\n      const task = createTask(taskRequest);\n      const executed = await executeTask(task, toolHandler);\n\n      return {\n        jsonrpc: '2.0',\n        id,\n        result: taskToResponse(executed),\n      };\n    }\n\n    // ── a2a.getTask ────────────────────────────────────────────────────────\n    case 'a2a.getTask': {\n      const taskId = params?.id as string;\n      if (!taskId) {\n        return {\n          jsonrpc: '2.0',\n          id,\n          error: {\n            code: JSONRPC_INVALID_PARAMS,\n            message: 'Missing required parameter: id',\n          },\n        };\n      }\n\n      const task = getTask(taskId);\n      if (!task) {\n        return {\n          jsonrpc: '2.0',\n          id,\n          error: {\n            code: A2A_TASK_NOT_FOUND,\n            message: `Task not found: ${taskId}`,\n          },\n        };\n      }\n\n      return {\n        jsonrpc: '2.0',\n        id,\n        result: taskToResponse(task),\n      };\n    }\n\n    // ── a2a.listTasks ──────────────────────────────────────────────────────\n    case 'a2a.listTasks': {\n      const filters: {\n        sessionId?: string;\n        contextId?: string;\n        state?: TaskState;\n        limit?: number;\n        offset?: number;\n      } = {};\n\n      if (params?.sessionId) filters.sessionId = params.sessionId as string;\n      if (params?.contextId) filters.contextId = params.contextId as string;\n      if (params?.state) filters.state = params.state as TaskState;\n      if (params?.limit) filters.limit = params.limit as number;\n      if (params?.offset) filters.offset = params.offset as number;\n\n      const result = listTasks(filters);\n      return {\n        jsonrpc: '2.0',\n        id,\n        result: {\n          tasks: result.tasks.map(taskToResponse),\n          total: result.total,\n        },\n      };\n    }\n\n    // ── a2a.cancelTask ─────────────────────────────────────────────────────\n    case 'a2a.cancelTask': {\n      const taskId = params?.id as string;\n      if (!taskId) {\n        return {\n          jsonrpc: '2.0',\n          id,\n          error: {\n            code: JSONRPC_INVALID_PARAMS,\n            message: 'Missing required parameter: id',\n          },\n        };\n      }\n\n      const task = getTask(taskId);\n      if (!task) {\n        return {\n          jsonrpc: '2.0',\n          id,\n          error: {\n            code: A2A_TASK_NOT_FOUND,\n            message: `Task not found: ${taskId}`,\n          },\n        };\n      }\n\n      if (TERMINAL_STATES.includes(task.status.state)) {\n        return {\n          jsonrpc: '2.0',\n          id,\n          error: {\n            code: A2A_TASK_NOT_CANCELABLE,\n            message: `Task ${taskId} is already in terminal state: ${task.status.state}`,\n          },\n        };\n      }\n\n      const canceled = cancelTask(taskId)!;\n      return {\n        jsonrpc: '2.0',\n        id,\n        result: taskToResponse(canceled),\n      };\n    }\n\n    // ── a2a.getExtendedAgentCard ───────────────────────────────────────────\n    case 'a2a.getExtendedAgentCard': {\n      if (agentCardBuilder) {\n        return {\n          jsonrpc: '2.0',\n          id,\n          result: agentCardBuilder(),\n        };\n      }\n      return {\n        jsonrpc: '2.0',\n        id,\n        error: {\n          code: JSONRPC_METHOD_NOT_FOUND,\n          message: 'Extended agent card not available',\n        },\n      };\n    }\n\n    // ── Unknown method ─────────────────────────────────────────────────────\n    default:\n      return {\n        jsonrpc: '2.0',\n        id,\n        error: {\n          code: JSONRPC_METHOD_NOT_FOUND,\n          message: `Unknown method: ${method}. Supported: a2a.sendMessage, a2a.getTask, a2a.listTasks, a2a.cancelTask, a2a.getExtendedAgentCard`,\n        },\n      };\n  }\n}\n\n/**\n * Validate a raw JSON body as a JSON-RPC 2.0 request.\n * Returns the parsed request or an error response.\n */\nexport function parseJsonRpcRequest(\n  body: Record<string, unknown>\n): { request: JsonRpcRequest } | { error: JsonRpcResponse } {\n  // Validate JSON-RPC 2.0 envelope\n  if (body.jsonrpc !== '2.0') {\n    return {\n      error: {\n        jsonrpc: '2.0',\n        id: (body.id as string | number | null) ?? null,\n        error: {\n          code: JSONRPC_INVALID_REQUEST,\n          message: 'Invalid JSON-RPC: missing or incorrect \"jsonrpc\" field (must be \"2.0\")',\n        },\n      },\n    };\n  }\n\n  if (!body.method || typeof body.method !== 'string') {\n    return {\n      error: {\n        jsonrpc: '2.0',\n        id: (body.id as string | number | null) ?? null,\n        error: {\n          code: JSONRPC_INVALID_REQUEST,\n          message: 'Invalid JSON-RPC: missing or non-string \"method\" field',\n        },\n      },\n    };\n  }\n\n  return {\n    request: {\n      jsonrpc: '2.0',\n      id: (body.id as string | number | null) ?? null,\n      method: body.method as string,\n      params: (body.params as Record<string, unknown>) || undefined,\n    },\n  };\n}\n\n// =============================================================================\n// HTTP REQUEST/RESPONSE HELPERS\n// =============================================================================\n\n/**\n * Format a task as a SendTaskResponse for the API.\n */\nexport function taskToResponse(task: A2ATask): SendTaskResponse {\n  return {\n    id: task.id,\n    sessionId: task.sessionId,\n    contextId: task.contextId,\n    status: task.status,\n    artifacts: task.artifacts,\n    history: task.history,\n  };\n}\n","/**\n * HoloScript MCP Security Module\n *\n * Enterprise-grade security for the MCP server implementing:\n * - OAuth 2.1 authentication (PKCE, token rotation, DPoP)\n * - Triple-gate authorization pattern (prompt → scope → policy)\n * - EU AI Act compliant audit logging\n *\n * Architecture:\n *   Client → Gate 1 (Prompt Validation)\n *     → Gate 2 (Tool Scope Authorization)\n *       → Gate 3 (StdlibPolicy Enforcement)\n *         → Tool Execution → Audit Log\n */\n\n// OAuth 2.1 Token Service\nexport {\n  OAuth21Service,\n  getOAuth21Service,\n  resetOAuth21Service,\n  SCOPE_CATEGORIES,\n  DEFAULT_OAUTH_CONFIG,\n  type OAuth21Config,\n  type OAuthScope,\n  type RegisteredClient,\n  type AccessToken,\n  type RefreshToken,\n  type TokenResponse,\n  type TokenIntrospection,\n  type GrantType,\n} from './oauth21';\n\n// Tool Scope Mapping (Gate 2)\nexport {\n  authorizeToolCall,\n  getToolRiskLevel,\n  getToolScopes,\n  getToolsForScope,\n  resolveRequiredScopes,\n  classifyToolScope,\n  hasExplicitScope,\n  registerKnownTools,\n  isRegisteredTool,\n  isToolRegistryKnown,\n  type AuthorizationResult,\n  type ToolRiskLevel,\n} from './tool-scopes';\n\n// Triple-Gate Security (Gates 1-3)\nexport {\n  gate1ValidateRequest,\n  gate3EnforcePolicy,\n  runTripleGate,\n  DEFAULT_GATE1_CONFIG,\n  type Gate1Config,\n  type Gate1Result,\n  type Gate3Config,\n  type Gate3Result,\n  type TripleGateResult,\n  type StdlibPolicy,\n} from './gates';\n\n// GitHub Token Authentication\nexport { resolveGitHubTokenForMcp } from './github-auth';\n\n// EU AI Act Audit Logging\nexport {\n  getAuditLogger,\n  resetAuditLogger,\n  redactPII,\n  type AuditLogEntry,\n  type AuditEventType,\n  type AuditResultStatus,\n  type AuditLogConfig,\n} from './audit-log';\n\n// Rate-limit bypass heuristics (P.009.02)\nexport {\n  checkRateLimitBypass,\n  analyzeXForwardedFor,\n  ipv4Subnet24,\n  readBearerToken,\n  readXForwardedFor,\n  resetBypassDetectionForTests,\n  type BypassCheckInput,\n  type BypassCheckResult,\n} from './bypass-detection';\n\n// Sandbox Policy (canary task_1778618757735_zpt5)\nexport {\n  resolvePolicy,\n  isSensitiveTool,\n  hashPayload,\n  globalReceiptStore,\n  DEFAULT_SENSITIVE_POLICY,\n  DEFAULT_BENIGN_POLICY,\n  SYSTEM_DEFAULT_BLOCKED_ACTIONS,\n  SENSITIVE_TOOL_PATTERNS,\n  type SandboxPolicy,\n  type CapabilityManifest,\n  type CapabilityAttestation,\n  type PermissionRequirements,\n  type NetworkLimits,\n  type FileLimits,\n  type ResourceCeilings,\n  type DenialReceiptConfig,\n  type SandboxSubject,\n  type SandboxSubjectKind,\n  type SandboxSubjectSource,\n  type DenialReceipt,\n  type SandboxGateResult,\n} from './sandbox-policy';\n\n// Fork Sandbox Gate (canary task_1778618757735_zpt5)\nexport {\n  runForkSandboxGate,\n  gateHoloScriptCode,\n  gateMcpTool,\n  gatePluginRegistration,\n  detectForkedHoloScript,\n  detectForkedPlugin,\n  type ForkDetectionResult,\n  type ForkSandboxGateOptions,\n} from './fork-sandbox-gate';\n\n// HoloLand Fork Admission Gate (task_1778619015439_l51b)\nexport {\n  runHololandForkAdmissionGate,\n  type HoloLandForkAdmissionInput,\n  type HoloLandForkAdmissionReport,\n} from './hololand-fork-admission-gate';\n","/**\n * OAuth 2.1 Token Service for HoloScript MCP Server\n *\n * Implements OAuth 2.1 (draft-ietf-oauth-v2-1) with:\n * - PKCE (RFC 7636) mandatory for all flows\n * - Token rotation with refresh tokens\n * - DPoP (RFC 9449) proof-of-possession binding\n * - Access tokens (1 hour default, configurable via OAUTH_ACCESS_TTL), long-lived refresh (24h)\n * - Client credential registration and management\n *\n * This replaces the legacy Ed25519/API key authentication with\n * standards-based OAuth 2.1 per AAIF enterprise requirements.\n *\n * Backwards-compatible: legacy API key auth is still accepted during\n * migration period (OAUTH_MIGRATION_MODE=permissive).\n */\n\nimport { randomUUID, createHash, createHmac, timingSafeEqual } from 'crypto';\nimport { expandScopes, OAUTH2_SCOPES } from '../auth/oauth2-provider';\n\n// ── Configuration ────────────────────────────────────────────────────────────\n\nexport interface OAuth21Config {\n  /** Issuer identifier (e.g., \"https://mcp.holoscript.net\") */\n  issuer: string;\n  /** Access token TTL in seconds. Default: 3600 (1 hour) */\n  accessTokenTTL: number;\n  /** Refresh token TTL in seconds. Default: 86400 (24h) */\n  refreshTokenTTL: number;\n  /** Authorization code TTL in seconds. Default: 300 (5 min) */\n  authCodeTTL: number;\n  /** HMAC secret for token signing (must be >= 32 bytes) */\n  tokenSecret: string;\n  /** Migration mode: \"strict\" rejects legacy keys, \"permissive\" accepts both */\n  migrationMode: 'strict' | 'permissive';\n  /** Legacy API key (for backwards compat during migration) */\n  legacyApiKey?: string;\n  /** Max clients that can be registered. Default: 1000 */\n  maxClients: number;\n  /** Require DPoP proof-of-possession. Default: false (recommended: true in prod) */\n  requireDPoP: boolean;\n}\n\nexport const DEFAULT_OAUTH_CONFIG: OAuth21Config = {\n  issuer: process.env.OAUTH_ISSUER || 'https://mcp.holoscript.net',\n  accessTokenTTL: parseInt(process.env.OAUTH_ACCESS_TTL || '3600', 10),\n  refreshTokenTTL: 86400,\n  authCodeTTL: 300,\n  tokenSecret: process.env.OAUTH_TOKEN_SECRET || '',\n  migrationMode: (process.env.OAUTH_MIGRATION_MODE as 'strict' | 'permissive') || 'permissive',\n  legacyApiKey: process.env.HOLOSCRIPT_API_KEY || '',\n  maxClients: 1000,\n  requireDPoP: process.env.OAUTH_REQUIRE_DPOP === 'true',\n};\n\n// ── Types ────────────────────────────────────────────────────────────────────\n\nexport type GrantType = 'authorization_code' | 'client_credentials' | 'refresh_token';\n\n/** Scopes follow the pattern: domain:action */\nexport type OAuthScope = string;\n\n/** Pre-defined scope categories for HoloScript MCP tools */\nexport const SCOPE_CATEGORIES = {\n  /** Read-only language operations (parse, validate, explain, list) */\n  'tools:read': 'Read-only tool access (parse, validate, list, explain)',\n  /** Write/mutate operations (generate, compile, render, share) */\n  'tools:write': 'Write tool access (generate, compile, render, edit)',\n  /** Codebase intelligence (absorb, query, impact analysis) */\n  'tools:codebase': 'Codebase intelligence tools (absorb, query, impact)',\n  /** Browser control tools */\n  'tools:browser': 'Browser control (launch, execute, screenshot)',\n  /** Self-improvement and daemon tools */\n  'tools:admin': 'Administrative tools (self-improve, diagnostics)',\n  /** A2A task management */\n  'a2a:tasks': 'A2A task lifecycle (create, list, cancel)',\n  /** Scene management */\n  'scenes:read': 'Read scenes and embeds',\n  'scenes:write': 'Create and store scenes',\n  /** Full access */\n  'admin:*': 'Full administrative access to all tools and endpoints',\n} as const;\n\nexport interface RegisteredClient {\n  clientId: string;\n  clientSecret: string; // hashed\n  clientName: string;\n  redirectUris: string[];\n  scopes: OAuthScope[];\n  createdAt: number;\n  /** Client type per OAuth 2.1: \"confidential\" or \"public\" */\n  clientType: 'confidential' | 'public';\n  /** Rate limit: requests per minute */\n  rateLimit: number;\n}\n\nexport interface AuthorizationCode {\n  code: string;\n  clientId: string;\n  redirectUri: string;\n  scopes: OAuthScope[];\n  codeChallenge: string;\n  codeChallengeMethod: 'S256';\n  expiresAt: number;\n  used: boolean;\n}\n\nexport interface AccessToken {\n  token: string;\n  clientId: string;\n  scopes: OAuthScope[];\n  issuedAt: number;\n  expiresAt: number;\n  /** Agent identity (who is using this token) */\n  agentId?: string;\n  /** DPoP thumbprint if DPoP was used */\n  dpopThumbprint?: string;\n}\n\nexport interface RefreshToken {\n  token: string;\n  clientId: string;\n  scopes: OAuthScope[];\n  issuedAt: number;\n  expiresAt: number;\n  /** Chain ID for token rotation tracking */\n  chainId: string;\n  /** Whether this token has been used (for rotation) */\n  used: boolean;\n}\n\nexport interface TokenResponse {\n  access_token: string;\n  token_type: 'Bearer' | 'DPoP';\n  expires_in: number;\n  refresh_token?: string;\n  scope: string;\n}\n\nexport interface TokenIntrospection {\n  active: boolean;\n  clientId?: string;\n  scopes?: OAuthScope[];\n  agentId?: string;\n  expiresAt?: number;\n  issuedAt?: number;\n}\n\n// ── In-Memory Stores (production would use Redis/PostgreSQL) ─────────────────\n\nconst clients = new Map<string, RegisteredClient>();\nconst authCodes = new Map<string, AuthorizationCode>();\nconst accessTokens = new Map<string, AccessToken>();\nconst refreshTokens = new Map<string, RefreshToken>();\nconst revokedChains = new Set<string>();\n\n// ── Utility Functions ────────────────────────────────────────────────────────\n\nfunction hashSecret(secret: string): string {\n  return createHash('sha256').update(secret).digest('hex');\n}\n\nfunction generateToken(): string {\n  return `hs_${randomUUID().replace(/-/g, '')}${randomUUID().replace(/-/g, '')}`;\n}\n\nfunction verifyS256Challenge(verifier: string, challenge: string): boolean {\n  const computed = createHash('sha256').update(verifier).digest('base64url');\n  return computed === challenge;\n}\n\nfunction safeCompare(a: string, b: string): boolean {\n  if (a.length !== b.length) return false;\n  return timingSafeEqual(Buffer.from(a), Buffer.from(b));\n}\n\n// ── Cleanup Timer ────────────────────────────────────────────────────────────\n\nlet cleanupInterval: ReturnType<typeof setInterval> | null = null;\n\nfunction startCleanupTimer(): void {\n  if (cleanupInterval) return;\n  cleanupInterval = setInterval(() => {\n    const now = Date.now();\n    for (const [key, code] of authCodes) {\n      if (code.expiresAt < now || code.used) authCodes.delete(key);\n    }\n    for (const [key, token] of accessTokens) {\n      if (token.expiresAt < now) accessTokens.delete(key);\n    }\n    for (const [key, token] of refreshTokens) {\n      if (token.expiresAt < now || token.used) refreshTokens.delete(key);\n    }\n  }, 60_000); // Clean up every minute\n}\n\n// ── OAuth 2.1 Token Service ──────────────────────────────────────────────────\n\nexport class OAuth21Service {\n  private config: OAuth21Config;\n\n  /**\n   * Optional async fallback into a durable token registry (the Postgres-backed\n   * OAuth2Provider). Injected by http-server at boot to avoid an import cycle.\n   * Consulted by authenticateRequestAsync when the in-memory maps miss — i.e.\n   * after a deploy wiped them.\n   */\n  private durableIntrospector?: (token: string) => Promise<TokenIntrospection | undefined>;\n\n  setDurableIntrospector(fn: (token: string) => Promise<TokenIntrospection | undefined>): void {\n    this.durableIntrospector = fn;\n  }\n\n  constructor(config: Partial<OAuth21Config> = {}) {\n    this.config = { ...DEFAULT_OAUTH_CONFIG, ...config };\n\n    if (!this.config.tokenSecret) {\n      // Generate ephemeral secret for dev mode (not for production!)\n      this.config.tokenSecret = randomUUID() + randomUUID();\n      console.warn(\n        '[OAuth2.1] WARNING: No OAUTH_TOKEN_SECRET set. Using ephemeral secret. Set this in production!'\n      );\n    }\n\n    startCleanupTimer();\n  }\n\n  // ── Client Registration ──────────────────────────────────────────────────\n\n  registerClient(params: {\n    clientName: string;\n    redirectUris: string[];\n    scopes: OAuthScope[];\n    clientType?: 'confidential' | 'public';\n    rateLimit?: number;\n  }): { clientId: string; clientSecret: string } {\n    if (clients.size >= this.config.maxClients) {\n      throw new Error('Maximum client registration limit reached');\n    }\n\n    const clientId = `hsc_${randomUUID().replace(/-/g, '')}`;\n    const clientSecret = generateToken();\n\n    const client: RegisteredClient = {\n      clientId,\n      clientSecret: hashSecret(clientSecret),\n      clientName: params.clientName,\n      redirectUris: params.redirectUris,\n      scopes: params.scopes,\n      createdAt: Date.now(),\n      clientType: params.clientType || 'confidential',\n      rateLimit: params.rateLimit || 60,\n    };\n\n    clients.set(clientId, client);\n\n    return { clientId, clientSecret };\n  }\n\n  getClient(clientId: string): RegisteredClient | undefined {\n    return clients.get(clientId);\n  }\n\n  /**\n   * Rehydrate a client from a durable registry (e.g. the Postgres-backed\n   * OAuth2Provider store). `clientSecret` must already be the SHA-256 hash.\n   * The module-level maps here are wiped on every deploy; without rehydration\n   * every cached client_id strands with \"Unknown client_id\" — which surfaced\n   * as raw invalid_client JSON tabs in the founder's browser on every Claude\n   * instance start (task_1781078719152_ym9w).\n   */\n  importClient(client: RegisteredClient): void {\n    clients.set(client.clientId, client);\n  }\n\n  /** Rehydrate an access token from a durable registry. */\n  importAccessToken(token: AccessToken): void {\n    accessTokens.set(token.token, token);\n  }\n\n  /** Rehydrate a refresh token from a durable registry. */\n  importRefreshToken(token: RefreshToken): void {\n    refreshTokens.set(token.token, token);\n  }\n\n  /** Read the full refresh-token record (for durable write-through after issuance). */\n  getRefreshTokenRecord(token: string): RefreshToken | undefined {\n    return refreshTokens.get(token);\n  }\n\n  revokeClient(clientId: string): boolean {\n    // Revoke all tokens for this client\n    for (const [key, token] of accessTokens) {\n      if (token.clientId === clientId) accessTokens.delete(key);\n    }\n    for (const [key, token] of refreshTokens) {\n      if (token.clientId === clientId) {\n        revokedChains.add(token.chainId);\n        refreshTokens.delete(key);\n      }\n    }\n    return clients.delete(clientId);\n  }\n\n  // ── Authorization Code Flow (with PKCE) ──────────────────────────────────\n\n  createAuthorizationCode(params: {\n    clientId: string;\n    redirectUri: string;\n    scopes: OAuthScope[];\n    codeChallenge: string;\n    codeChallengeMethod: 'S256';\n  }): string {\n    const client = clients.get(params.clientId);\n    if (!client)\n      throw new Error(\n        `Invalid client_id: '${String(params.clientId).slice(0, 12)}...' is not registered. Register at POST /oauth/register.`\n      );\n\n    if (!client.redirectUris.includes(params.redirectUri)) {\n      throw new Error('Invalid redirect_uri');\n    }\n\n    // Validate requested scopes against client's allowed scopes\n    const invalidScopes = params.scopes.filter(\n      (s) => !client.scopes.includes(s) && !client.scopes.includes('admin:*')\n    );\n    if (invalidScopes.length > 0) {\n      throw new Error(`Scopes not authorized for client: ${invalidScopes.join(', ')}`);\n    }\n\n    if (params.codeChallengeMethod !== 'S256') {\n      throw new Error('Only S256 code challenge method is supported (OAuth 2.1)');\n    }\n\n    const code = generateToken();\n    const authCode: AuthorizationCode = {\n      code,\n      clientId: params.clientId,\n      redirectUri: params.redirectUri,\n      scopes: params.scopes,\n      codeChallenge: params.codeChallenge,\n      codeChallengeMethod: 'S256',\n      expiresAt: Date.now() + this.config.authCodeTTL * 1000,\n      used: false,\n    };\n\n    authCodes.set(code, authCode);\n    return code;\n  }\n\n  // ── Token Exchange ───────────────────────────────────────────────────────\n\n  exchangeAuthorizationCode(params: {\n    code: string;\n    clientId: string;\n    clientSecret: string;\n    redirectUri: string;\n    codeVerifier: string;\n    agentId?: string;\n    dpopThumbprint?: string;\n  }): TokenResponse {\n    const authCode = authCodes.get(params.code);\n    if (!authCode)\n      throw new Error(\n        'Authorization code not found — may have been used already or never issued. Request a new one via GET /oauth/authorize.'\n      );\n    if (authCode.used)\n      throw new Error(\n        'Authorization code already used — each code is single-use. Request a new one.'\n      );\n    if (authCode.expiresAt < Date.now())\n      throw new Error('Authorization code expired. Codes are valid for 60s. Request a new one.');\n    if (authCode.clientId !== params.clientId) throw new Error('Client mismatch');\n    if (authCode.redirectUri !== params.redirectUri) throw new Error('Redirect URI mismatch');\n\n    // Verify client credentials\n    const client = clients.get(params.clientId);\n    if (!client) throw new Error('Invalid client');\n    if (!safeCompare(hashSecret(params.clientSecret), client.clientSecret)) {\n      throw new Error('Invalid client credentials');\n    }\n\n    // Verify PKCE (mandatory in OAuth 2.1)\n    if (!verifyS256Challenge(params.codeVerifier, authCode.codeChallenge)) {\n      throw new Error('PKCE verification failed');\n    }\n\n    // Mark code as used (one-time use)\n    authCode.used = true;\n\n    return this.issueTokenPair(\n      params.clientId,\n      authCode.scopes,\n      params.agentId,\n      params.dpopThumbprint\n    );\n  }\n\n  exchangeClientCredentials(params: {\n    clientId: string;\n    clientSecret: string;\n    scopes?: OAuthScope[];\n    agentId?: string;\n    dpopThumbprint?: string;\n  }): TokenResponse {\n    const client = clients.get(params.clientId);\n    if (!client)\n      throw new Error(\n        `Invalid client_id: '${String(params.clientId).slice(0, 12)}...' is not registered. Register at POST /oauth/register.`\n      );\n    if (client.clientType !== 'confidential') {\n      throw new Error('Client credentials grant requires confidential client');\n    }\n    if (!safeCompare(hashSecret(params.clientSecret), client.clientSecret)) {\n      throw new Error('Invalid client credentials');\n    }\n\n    const requestedScopes = params.scopes || client.scopes;\n    const invalidScopes = requestedScopes.filter(\n      (s) => !client.scopes.includes(s) && !client.scopes.includes('admin:*')\n    );\n    if (invalidScopes.length > 0) {\n      throw new Error(`Scopes not authorized: ${invalidScopes.join(', ')}`);\n    }\n\n    return this.issueTokenPair(\n      params.clientId,\n      requestedScopes,\n      params.agentId,\n      params.dpopThumbprint\n    );\n  }\n\n  refreshAccessToken(params: {\n    refreshToken: string;\n    clientId: string;\n    clientSecret: string;\n    dpopThumbprint?: string;\n  }): TokenResponse {\n    const stored = refreshTokens.get(params.refreshToken);\n    if (!stored)\n      throw new Error(\n        'Refresh token not found — may have been revoked or expired. Re-authenticate via the full OAuth flow.'\n      );\n    if (stored.used) {\n      // Token replay detected -- revoke entire chain\n      revokedChains.add(stored.chainId);\n      throw new Error('Refresh token replay detected. Token chain revoked.');\n    }\n    if (stored.expiresAt < Date.now()) throw new Error('Refresh token expired');\n    if (stored.clientId !== params.clientId) throw new Error('Client mismatch');\n\n    // Check if chain is revoked\n    if (revokedChains.has(stored.chainId)) {\n      throw new Error('Token chain has been revoked');\n    }\n\n    // Verify client\n    const client = clients.get(params.clientId);\n    if (!client) throw new Error('Invalid client');\n    if (!safeCompare(hashSecret(params.clientSecret), client.clientSecret)) {\n      throw new Error('Invalid client credentials');\n    }\n\n    // Mark old refresh token as used (rotation)\n    stored.used = true;\n\n    // Issue new token pair with same chain\n    return this.issueTokenPair(\n      params.clientId,\n      stored.scopes,\n      undefined,\n      params.dpopThumbprint,\n      stored.chainId\n    );\n  }\n\n  // ── Token Introspection ──────────────────────────────────────────────────\n\n  introspect(token: string): TokenIntrospection {\n    const stored = accessTokens.get(token);\n    if (!stored || stored.expiresAt < Date.now()) {\n      return { active: false };\n    }\n\n    return {\n      active: true,\n      clientId: stored.clientId,\n      scopes: stored.scopes,\n      agentId: stored.agentId,\n      expiresAt: stored.expiresAt,\n      issuedAt: stored.issuedAt,\n    };\n  }\n\n  // ── Token Revocation ─────────────────────────────────────────────────────\n\n  revokeToken(token: string): boolean {\n    // Check access tokens\n    if (accessTokens.has(token)) {\n      accessTokens.delete(token);\n      return true;\n    }\n\n    // Check refresh tokens -- revoke entire chain\n    const refresh = refreshTokens.get(token);\n    if (refresh) {\n      revokedChains.add(refresh.chainId);\n      refreshTokens.delete(token);\n      return true;\n    }\n\n    return false;\n  }\n\n  // ── Legacy API Key Validation (migration period) ─────────────────────────\n\n  validateLegacyKey(key: string): TokenIntrospection {\n    if (this.config.migrationMode === 'strict') {\n      return { active: false };\n    }\n\n    if (!this.config.legacyApiKey) {\n      return { active: true, scopes: ['admin:*'], agentId: 'legacy-open-dev' };\n    }\n\n    if (safeCompare(key, this.config.legacyApiKey)) {\n      return {\n        active: true,\n        scopes: ['admin:*'],\n        agentId: 'legacy-api-key',\n        clientId: 'legacy',\n      };\n    }\n\n    return { active: false };\n  }\n\n  // ── HTTP Request Authentication ──────────────────────────────────────────\n\n  /**\n   * Authenticate an HTTP request. Returns token introspection.\n   * Supports: Bearer token (OAuth 2.1), DPoP token, legacy API key.\n   */\n  authenticateRequest(headers: Record<string, string | string[] | undefined>): TokenIntrospection {\n    const authHeader =\n      (typeof headers['authorization'] === 'string' ? headers['authorization'] : '') || '';\n    const apiKey = (typeof headers['x-api-key'] === 'string' ? headers['x-api-key'] : '') || '';\n    const mcpApiKey =\n      (typeof headers['x-mcp-api-key'] === 'string' ? headers['x-mcp-api-key'] : '') || '';\n    const dpopHeader = (typeof headers['dpop'] === 'string' ? headers['dpop'] : '') || '';\n\n    // Try OAuth 2.1 Bearer token\n    if (authHeader.startsWith('Bearer ')) {\n      const token = authHeader.slice(7);\n      const introspection = this.introspect(token);\n\n      if (introspection.active) {\n        // Verify DPoP if required\n        if (this.config.requireDPoP) {\n          const stored = accessTokens.get(token);\n          if (stored?.dpopThumbprint && !dpopHeader) {\n            return { active: false };\n          }\n        }\n        // Expand OAuth2 scopes to internal Gate 2 scopes\n        introspection.scopes = expandScopes(introspection.scopes || []);\n        return introspection;\n      }\n\n      // Fall through to legacy check\n    }\n\n    // Try DPoP token\n    if (authHeader.startsWith('DPoP ')) {\n      const token = authHeader.slice(5);\n      const introspection = this.introspect(token);\n      if (introspection.active) {\n        introspection.scopes = expandScopes(introspection.scopes || []);\n        return introspection;\n      }\n    }\n\n    // Try legacy API key (migration period)\n    if (apiKey) {\n      return this.validateLegacyKey(apiKey);\n    }\n    if (mcpApiKey) {\n      return this.validateLegacyKey(mcpApiKey);\n    }\n\n    // Try legacy Bearer that's actually an API key\n    if (authHeader.startsWith('Bearer ') && this.config.legacyApiKey) {\n      const key = authHeader.slice(7);\n      return this.validateLegacyKey(key);\n    }\n\n    // No auth provided -- check if open dev mode\n    if (!this.config.legacyApiKey && this.config.migrationMode === 'permissive') {\n      return { active: true, scopes: ['admin:*'], agentId: 'open-dev-mode' };\n    }\n\n    return { active: false };\n  }\n\n  // ── Async Request Authentication (with GitHub token fallback) ────────────\n\n  /**\n   * Async variant of authenticateRequest that additionally resolves GitHub tokens.\n   * Tries sync OAuth/legacy paths first, then falls back to GitHub API validation.\n   */\n  async authenticateRequestAsync(\n    headers: Record<string, string | string[] | undefined>\n  ): Promise<TokenIntrospection> {\n    const syncResult = this.authenticateRequest(headers);\n    if (syncResult.active) return syncResult;\n\n    // 1. Try Dynamic Tenant Lookup (PostgreSQL/Upstash)\n    const authHeader =\n      (typeof headers['authorization'] === 'string' ? headers['authorization'] : '') || '';\n    const apiKey = (typeof headers['x-api-key'] === 'string' ? headers['x-api-key'] : '') || '';\n    const mcpApiKey =\n      (typeof headers['x-mcp-api-key'] === 'string' ? headers['x-mcp-api-key'] : '') || '';\n\n    // 0.5 Try the durable token registry (Postgres-backed OAuth2Provider).\n    // The in-memory maps above are wiped on every deploy; tokens written\n    // through to the durable store stay valid, so rehydrate and accept them.\n    if (authHeader.startsWith('Bearer ') && this.durableIntrospector) {\n      const token = authHeader.slice(7);\n      try {\n        const durable = await this.durableIntrospector(token);\n        if (durable?.active) {\n          accessTokens.set(token, {\n            token,\n            clientId: durable.clientId || 'durable-import',\n            scopes: (durable.scopes || []) as OAuthScope[],\n            issuedAt: durable.issuedAt || Date.now(),\n            expiresAt: durable.expiresAt || Date.now() + this.config.accessTokenTTL * 1000,\n            agentId: durable.agentId,\n          });\n          return {\n            ...durable,\n            scopes: expandScopes((durable.scopes || []) as OAuthScope[]),\n          };\n        }\n      } catch {\n        // Durable registry unavailable — fall through to other strategies.\n      }\n    }\n\n    let keyToValidate = apiKey || mcpApiKey;\n    if (!keyToValidate && authHeader.startsWith('Bearer ')) {\n      keyToValidate = authHeader.slice(7);\n    }\n\n    if (keyToValidate) {\n      try {\n        const { validateTenantKey } = await import('./tenant-auth');\n        const tenantResult = await validateTenantKey(keyToValidate);\n        if (tenantResult && tenantResult.active) return tenantResult;\n      } catch (_err) {\n        // Fall through\n      }\n    }\n\n    // 2. Try GitHub token resolution as last-resort fallback\n    if (authHeader.startsWith('Bearer ')) {\n      const token = authHeader.slice(7);\n      try {\n        const { resolveGitHubTokenForMcp } = await import('./github-auth.js');\n        const ghResult = await resolveGitHubTokenForMcp(token);\n        if (ghResult) return ghResult;\n      } catch {\n        // GitHub auth module not available — skip\n      }\n    }\n\n    return syncResult;\n  }\n\n  // ── OpenID Configuration ─────────────────────────────────────────────────\n\n  getOpenIDConfiguration(): Record<string, unknown> {\n    return {\n      issuer: this.config.issuer,\n      authorization_endpoint: `${this.config.issuer}/oauth/authorize`,\n      token_endpoint: `${this.config.issuer}/oauth/token`,\n      device_authorization_endpoint: `${this.config.issuer}/oauth/github/device`,\n      revocation_endpoint: `${this.config.issuer}/oauth/revoke`,\n      introspection_endpoint: `${this.config.issuer}/oauth/introspect`,\n      registration_endpoint: `${this.config.issuer}/oauth/register`,\n      response_types_supported: ['code'],\n      grant_types_supported: [\n        'authorization_code',\n        'client_credentials',\n        'refresh_token',\n        'urn:ietf:params:oauth:grant-type:device_code',\n      ],\n      token_endpoint_auth_methods_supported: ['client_secret_post', 'client_secret_basic'],\n      code_challenge_methods_supported: ['S256'],\n      scopes_supported: Object.keys(OAUTH2_SCOPES),\n      dpop_signing_alg_values_supported: ['ES256', 'RS256'],\n      service_documentation: 'https://github.com/buildwithholoscript/HoloScript',\n    };\n  }\n\n  // ── Stats (for health endpoint) ──────────────────────────────────────────\n\n  getStats(): Record<string, number> {\n    return {\n      registeredClients: clients.size,\n      activeAccessTokens: accessTokens.size,\n      activeRefreshTokens: refreshTokens.size,\n      pendingAuthCodes: authCodes.size,\n      revokedChains: revokedChains.size,\n    };\n  }\n\n  // ── Convenience ─────────────────────────────────────────────────────────\n\n  /** Issue a standalone access token for a pre-authenticated agent (e.g. from GitHub device flow). */\n  issueAccessToken(opts: { clientId: string; agentId?: string; scopes: OAuthScope[] }): {\n    accessToken: string;\n    expiresIn: number;\n  } {\n    const pair = this.issueTokenPair(opts.clientId, opts.scopes, opts.agentId);\n    return { accessToken: pair.access_token, expiresIn: pair.expires_in };\n  }\n\n  // ── Internal ─────────────────────────────────────────────────────────────\n\n  private issueTokenPair(\n    clientId: string,\n    scopes: OAuthScope[],\n    agentId?: string,\n    dpopThumbprint?: string,\n    chainId?: string\n  ): TokenResponse {\n    const now = Date.now();\n    const accessTokenValue = generateToken();\n    const refreshTokenValue = generateToken();\n    const chain = chainId || randomUUID();\n\n    const access: AccessToken = {\n      token: accessTokenValue,\n      clientId,\n      scopes,\n      issuedAt: now,\n      expiresAt: now + this.config.accessTokenTTL * 1000,\n      agentId,\n      dpopThumbprint,\n    };\n\n    const refresh: RefreshToken = {\n      token: refreshTokenValue,\n      clientId,\n      scopes,\n      issuedAt: now,\n      expiresAt: now + this.config.refreshTokenTTL * 1000,\n      chainId: chain,\n      used: false,\n    };\n\n    accessTokens.set(accessTokenValue, access);\n    refreshTokens.set(refreshTokenValue, refresh);\n\n    return {\n      access_token: accessTokenValue,\n      token_type: dpopThumbprint ? 'DPoP' : 'Bearer',\n      expires_in: this.config.accessTokenTTL,\n      refresh_token: refreshTokenValue,\n      scope: scopes.join(' '),\n    };\n  }\n}\n\n// ── Singleton instance ───────────────────────────────────────────────────────\n\nlet _instance: OAuth21Service | null = null;\n\nexport function getOAuth21Service(config?: Partial<OAuth21Config>): OAuth21Service {\n  if (!_instance) {\n    _instance = new OAuth21Service(config);\n  }\n  return _instance;\n}\n\nexport function resetOAuth21Service(): void {\n  _instance = null;\n  clients.clear();\n  authCodes.clear();\n  accessTokens.clear();\n  refreshTokens.clear();\n  revokedChains.clear();\n}\n","/**\n * OAuth 2.1 Provider for HoloScript MCP Server\n *\n * Implements the full OAuth 2.1 server-side flow per draft-ietf-oauth-v2-1:\n *\n * Endpoints:\n *   GET  /oauth/authorize  — Authorization endpoint (renders consent form / redirects)\n *   POST /oauth/authorize  — Authorization endpoint (processes consent)\n *   POST /oauth/token      — Token endpoint (all grant types)\n *   POST /oauth/introspect — Token introspection (RFC 7662)\n *   POST /oauth/revoke     — Token revocation (RFC 7009)\n *   POST /oauth/register   — Dynamic client registration (RFC 7591)\n *\n * Supported grant types:\n *   - authorization_code (with mandatory PKCE S256)\n *   - client_credentials\n *   - refresh_token (with rotation)\n *\n * Scopes (A2A Agent Card aligned):\n *   tools:read     — Read-only tool access (parse, validate, list, explain)\n *   tools:execute  — Execute tools that generate output (compile, render, generate)\n *   tasks:read     — Read A2A tasks\n *   tasks:write    — Create and manage A2A tasks\n *   admin          — Full administrative access\n *\n * This module layers on top of the existing security/oauth21.ts service,\n * adding HTTP endpoint handlers and the GET /oauth/authorize flow.\n * It uses the new TokenStore backend for pluggable storage.\n *\n * Backwards compatibility:\n *   Legacy API key auth (x-api-key header) is still accepted when\n *   migrationMode is 'permissive' (default).\n */\n\nimport { createHash, randomUUID, timingSafeEqual } from 'crypto';\nimport type { IncomingMessage, ServerResponse } from 'http';\nimport {\n  TokenStore,\n  InMemoryTokenStore,\n  DEFAULT_TTL,\n  type TokenStoreTTL,\n  type TokenStoreBackend,\n  type StoredAccessToken,\n  type StoredClient,\n  type StoredRefreshToken,\n} from './token-store';\n\n// ── Configuration ────────────────────────────────────────────────────────────\n\nexport interface OAuth2ProviderConfig {\n  /** Issuer identifier (base URL). Default: https://mcp.holoscript.net */\n  issuer: string;\n  /** Token TTL configuration */\n  ttl: TokenStoreTTL;\n  /** Token store backend (default: in-memory) */\n  backend?: TokenStoreBackend;\n  /** Migration mode: 'strict' rejects legacy keys, 'permissive' accepts both */\n  migrationMode: 'strict' | 'permissive';\n  /** Legacy API key for backwards compatibility */\n  legacyApiKey?: string;\n  /** Max clients. Default: 1000 */\n  maxClients: number;\n  /** Require DPoP proof-of-possession. Default: false */\n  requireDPoP: boolean;\n}\n\nexport const DEFAULT_PROVIDER_CONFIG: OAuth2ProviderConfig = {\n  issuer: process.env.OAUTH_ISSUER || 'https://mcp.holoscript.net',\n  ttl: {\n    accessTokenTTL: parseInt(process.env.OAUTH_ACCESS_TTL || '3600', 10),\n    refreshTokenTTL: parseInt(process.env.OAUTH_REFRESH_TTL || '2592000', 10),\n    authCodeTTL: parseInt(process.env.OAUTH_CODE_TTL || '300', 10),\n  },\n  migrationMode: (process.env.OAUTH_MIGRATION_MODE as 'strict' | 'permissive') || 'permissive',\n  legacyApiKey: process.env.HOLOSCRIPT_API_KEY || '',\n  maxClients: 1000,\n  requireDPoP: process.env.OAUTH_REQUIRE_DPOP === 'true',\n};\n\n// ── Scopes ───────────────────────────────────────────────────────────────────\n\n/**\n * OAuth 2.1 scopes aligned with A2A Agent Card securitySchemes.\n *\n * These scopes map to the scopes declared in the A2A agent card's\n * oauth2 securityScheme flows.\n */\nexport const OAUTH2_SCOPES = {\n  'tools:read': 'Read-only access to tool outputs (parse, validate, list, explain, analyze)',\n  'tools:execute': 'Execute tools that produce output (compile, render, generate, share)',\n  'tasks:read': 'Read A2A task state and history',\n  'tasks:write': 'Create, send, and cancel A2A tasks',\n  admin: 'Full administrative access to all tools and endpoints',\n} as const;\n\nexport type OAuth2Scope = keyof typeof OAUTH2_SCOPES;\n\n/**\n * Maps the new scope names to the existing security/oauth21 scope names.\n * This allows the new provider to coexist with the existing Gate 2 authorization.\n */\nexport const SCOPE_BRIDGE: Record<string, string[]> = {\n  'tools:read': ['tools:read'],\n  'tools:execute': ['tools:write', 'tools:codebase', 'tools:browser'],\n  'tasks:read': ['a2a:tasks', 'scenes:read'],\n  'tasks:write': ['a2a:tasks', 'scenes:write'],\n  admin: ['admin:*', 'tools:admin'],\n};\n\n/**\n * Expand a set of OAuth2 scopes into the internal scope set used by Gate 2.\n */\nexport function expandScopes(scopes: string[]): string[] {\n  const expanded = new Set<string>();\n  for (const scope of scopes) {\n    if (SCOPE_BRIDGE[scope]) {\n      for (const internal of SCOPE_BRIDGE[scope]) {\n        expanded.add(internal);\n      }\n    } else {\n      // Pass through unknown scopes (they may be internal scopes directly)\n      expanded.add(scope);\n    }\n  }\n  return [...expanded];\n}\n\n// ── Token Introspection Result ───────────────────────────────────────────────\n\nexport interface TokenIntrospectionResult {\n  active: boolean;\n  clientId?: string;\n  scopes?: string[];\n  agentId?: string;\n  expiresAt?: number;\n  issuedAt?: number;\n}\n\n// ── Token Response ───────────────────────────────────────────────────────────\n\nexport interface OAuth2TokenResponse {\n  access_token: string;\n  token_type: 'Bearer' | 'DPoP';\n  expires_in: number;\n  refresh_token?: string;\n  scope: string;\n  [key: string]: unknown;\n}\n\n// ── OAuth 2.1 Provider ───────────────────────────────────────────────────────\n\nexport class OAuth2Provider {\n  private config: OAuth2ProviderConfig;\n  private store: TokenStore;\n\n  constructor(config?: Partial<OAuth2ProviderConfig>) {\n    this.config = { ...DEFAULT_PROVIDER_CONFIG, ...config };\n    this.store = new TokenStore({\n      backend: this.config.backend || new InMemoryTokenStore(),\n      ttl: this.config.ttl,\n    });\n  }\n\n  // ══════════════════════════════════════════════════════════════════════════\n  // CLIENT REGISTRATION (POST /oauth/register)\n  // ══════════════════════════════════════════════════════════════════════════\n\n  async registerClient(params: {\n    clientName: string;\n    redirectUris: string[];\n    scopes: string[];\n    clientType?: 'confidential' | 'public';\n    rateLimit?: number;\n    /** Import mode: reuse a legacy-issued identity (see TokenStore.registerClient). */\n    clientId?: string;\n    clientSecret?: string;\n  }): Promise<{ clientId: string; clientSecret: string }> {\n    return this.store.registerClient({\n      ...params,\n      maxClients: this.config.maxClients,\n    });\n  }\n\n  async getClient(clientId: string): Promise<StoredClient | undefined> {\n    return this.store.getClient(clientId);\n  }\n\n  async revokeClient(clientId: string): Promise<boolean> {\n    return this.store.revokeClient(clientId);\n  }\n\n  /**\n   * Write-through tokens issued by the legacy in-memory oauth21 registry so\n   * they survive redeploys. The deploy-wipe of that registry stranded every\n   * cached client_id and live Bearer (founder-reported invalid_client browser\n   * tabs, task_1781078719152_ym9w).\n   */\n  async importAccessToken(token: StoredAccessToken): Promise<void> {\n    await this.store.importAccessToken(token);\n  }\n\n  async importRefreshToken(token: StoredRefreshToken): Promise<void> {\n    await this.store.importRefreshToken(token);\n  }\n\n  async getStoredRefreshToken(token: string): Promise<StoredRefreshToken | undefined> {\n    return this.store.getRefreshToken(token);\n  }\n\n  // ══════════════════════════════════════════════════════════════════════════\n  // AUTHORIZATION ENDPOINT (GET + POST /oauth/authorize)\n  // ══════════════════════════════════════════════════════════════════════════\n\n  /**\n   * Handle GET /oauth/authorize\n   *\n   * In a full implementation this would render an HTML consent page.\n   * For machine-to-machine MCP usage, we return a JSON description\n   * of the authorization request that the client can use to proceed\n   * via POST /oauth/authorize.\n   *\n   * Query parameters:\n   *   response_type=code (required)\n   *   client_id (required)\n   *   redirect_uri (required)\n   *   scope (space-separated)\n   *   state (recommended, opaque to server)\n   *   code_challenge (required, PKCE)\n   *   code_challenge_method=S256 (required)\n   */\n  async handleAuthorizeGet(query: URLSearchParams): Promise<{\n    status: number;\n    body: Record<string, unknown>;\n  }> {\n    const responseType = query.get('response_type');\n    const clientId = query.get('client_id');\n    const redirectUri = query.get('redirect_uri');\n    const scope = query.get('scope') || 'tools:read';\n    const state = query.get('state');\n    const codeChallenge = query.get('code_challenge');\n    const codeChallengeMethod = query.get('code_challenge_method');\n\n    // Validate required parameters\n    if (responseType !== 'code') {\n      return {\n        status: 400,\n        body: {\n          error: 'unsupported_response_type',\n          error_description: 'Only response_type=code is supported (OAuth 2.1)',\n        },\n      };\n    }\n\n    if (!clientId) {\n      return {\n        status: 400,\n        body: {\n          error: 'invalid_request',\n          error_description: 'Missing required parameter: client_id',\n        },\n      };\n    }\n\n    if (!redirectUri) {\n      return {\n        status: 400,\n        body: {\n          error: 'invalid_request',\n          error_description: 'Missing required parameter: redirect_uri',\n        },\n      };\n    }\n\n    if (!codeChallenge || codeChallengeMethod !== 'S256') {\n      return {\n        status: 400,\n        body: {\n          error: 'invalid_request',\n          error_description:\n            'PKCE is mandatory. Provide code_challenge with code_challenge_method=S256',\n        },\n      };\n    }\n\n    // Validate client\n    const client = await this.store.getClient(clientId);\n    if (!client) {\n      return {\n        status: 400,\n        body: {\n          error: 'invalid_client',\n          error_description: 'Unknown client_id. Register via POST /oauth/register first.',\n        },\n      };\n    }\n\n    if (!client.redirectUris.includes(redirectUri)) {\n      return {\n        status: 400,\n        body: {\n          error: 'invalid_request',\n          error_description: `redirect_uri \"${redirectUri}\" is not registered for this client`,\n        },\n      };\n    }\n\n    const requestedScopes = scope.split(' ').filter(Boolean);\n    const invalidScopes = requestedScopes.filter(\n      (s) => !client.scopes.includes(s) && !client.scopes.includes('admin')\n    );\n\n    if (invalidScopes.length > 0) {\n      return {\n        status: 400,\n        body: {\n          error: 'invalid_scope',\n          error_description: `Scopes not authorized for client: ${invalidScopes.join(', ')}`,\n        },\n      };\n    }\n\n    // Return authorization request details\n    // In a browser-based flow this would render HTML.\n    // For MCP/agent usage, return JSON that the client can POST to complete.\n    return {\n      status: 200,\n      body: {\n        authorization_request: {\n          client_id: clientId,\n          client_name: client.clientName,\n          redirect_uri: redirectUri,\n          scope: requestedScopes.join(' '),\n          state: state || undefined,\n          code_challenge: codeChallenge,\n          code_challenge_method: 'S256',\n          available_scopes: Object.entries(OAUTH2_SCOPES).map(([name, description]) => ({\n            name,\n            description,\n            requested: requestedScopes.includes(name),\n          })),\n        },\n        instructions:\n          'POST to /oauth/authorize with the same parameters to obtain an authorization code.',\n        _links: {\n          authorize: `${this.config.issuer}/oauth/authorize`,\n          token: `${this.config.issuer}/oauth/token`,\n          register: `${this.config.issuer}/oauth/register`,\n        },\n      },\n    };\n  }\n\n  /**\n   * Handle POST /oauth/authorize\n   *\n   * Creates an authorization code with PKCE binding.\n   * The client exchanges this code at POST /oauth/token.\n   */\n  async handleAuthorizePost(body: Record<string, unknown>): Promise<{\n    status: number;\n    body: Record<string, unknown>;\n  }> {\n    const clientId = body.client_id as string;\n    const redirectUri = body.redirect_uri as string;\n    const scope = ((body.scope as string) || 'tools:read').split(' ').filter(Boolean);\n    const codeChallenge = body.code_challenge as string;\n    const codeChallengeMethod = body.code_challenge_method as string;\n    const state = body.state as string | undefined;\n\n    if (!clientId || !redirectUri || !codeChallenge) {\n      return {\n        status: 400,\n        body: {\n          error: 'invalid_request',\n          error_description: 'Missing required parameters: client_id, redirect_uri, code_challenge',\n        },\n      };\n    }\n\n    if (codeChallengeMethod && codeChallengeMethod !== 'S256') {\n      return {\n        status: 400,\n        body: {\n          error: 'invalid_request',\n          error_description: 'Only S256 code challenge method is supported (OAuth 2.1)',\n        },\n      };\n    }\n\n    // Validate client\n    const client = await this.store.getClient(clientId);\n    if (!client) {\n      return {\n        status: 400,\n        body: { error: 'invalid_client', error_description: 'Unknown client_id' },\n      };\n    }\n\n    if (!client.redirectUris.includes(redirectUri)) {\n      return {\n        status: 400,\n        body: { error: 'invalid_request', error_description: 'Invalid redirect_uri' },\n      };\n    }\n\n    // Validate scopes\n    const invalidScopes = scope.filter(\n      (s) => !client.scopes.includes(s) && !client.scopes.includes('admin')\n    );\n    if (invalidScopes.length > 0) {\n      return {\n        status: 400,\n        body: {\n          error: 'invalid_scope',\n          error_description: `Scopes not authorized for client: ${invalidScopes.join(', ')}`,\n        },\n      };\n    }\n\n    // Create authorization code\n    const authCode = await this.store.createAuthorizationCode({\n      clientId,\n      redirectUri,\n      scopes: scope,\n      codeChallenge,\n      codeChallengeMethod: 'S256',\n    });\n\n    return {\n      status: 200,\n      body: {\n        code: authCode.code,\n        state: state || undefined,\n      },\n    };\n  }\n\n  // ══════════════════════════════════════════════════════════════════════════\n  // TOKEN ENDPOINT (POST /oauth/token)\n  // ══════════════════════════════════════════════════════════════════════════\n\n  /**\n   * Handle POST /oauth/token\n   *\n   * Supports grant_type:\n   *   - authorization_code (exchanges code + PKCE verifier for tokens)\n   *   - client_credentials (server-to-server, confidential clients only)\n   *   - refresh_token (token rotation)\n   */\n  async handleToken(\n    body: Record<string, unknown>,\n    dpopHeader?: string\n  ): Promise<{\n    status: number;\n    body: Record<string, unknown>;\n    headers?: Record<string, string>;\n  }> {\n    const grantType = body.grant_type as string;\n\n    switch (grantType) {\n      case 'authorization_code':\n        return this.handleAuthorizationCodeGrant(body, dpopHeader);\n      case 'client_credentials':\n        return this.handleClientCredentialsGrant(body, dpopHeader);\n      case 'refresh_token':\n        return this.handleRefreshTokenGrant(body, dpopHeader);\n      default:\n        return {\n          status: 400,\n          body: {\n            error: 'unsupported_grant_type',\n            error_description: `Grant type \"${grantType}\" is not supported. Use authorization_code, client_credentials, or refresh_token.`,\n          },\n        };\n    }\n  }\n\n  private async handleAuthorizationCodeGrant(\n    body: Record<string, unknown>,\n    dpopHeader?: string\n  ): Promise<{ status: number; body: Record<string, unknown>; headers?: Record<string, string> }> {\n    const code = body.code as string;\n    const clientId = body.client_id as string;\n    const clientSecret = body.client_secret as string;\n    const redirectUri = body.redirect_uri as string;\n    const codeVerifier = body.code_verifier as string;\n    const agentId = body.agent_id as string | undefined;\n\n    if (!code || !clientId || !clientSecret || !redirectUri || !codeVerifier) {\n      return {\n        status: 400,\n        body: {\n          error: 'invalid_request',\n          error_description:\n            'Missing required parameters: code, client_id, client_secret, redirect_uri, code_verifier',\n        },\n      };\n    }\n\n    // Validate authorization code\n    const authCode = await this.store.getAuthorizationCode(code);\n    if (!authCode) {\n      return {\n        status: 400,\n        body: { error: 'invalid_grant', error_description: 'Invalid authorization code' },\n      };\n    }\n    if (authCode.used) {\n      return {\n        status: 400,\n        body: { error: 'invalid_grant', error_description: 'Authorization code already used' },\n      };\n    }\n    if (authCode.expiresAt < Date.now()) {\n      return {\n        status: 400,\n        body: { error: 'invalid_grant', error_description: 'Authorization code expired' },\n      };\n    }\n    if (authCode.clientId !== clientId) {\n      return {\n        status: 400,\n        body: { error: 'invalid_grant', error_description: 'Client mismatch' },\n      };\n    }\n    if (authCode.redirectUri !== redirectUri) {\n      return {\n        status: 400,\n        body: { error: 'invalid_grant', error_description: 'Redirect URI mismatch' },\n      };\n    }\n\n    // Verify client credentials\n    const client = await this.store.getClient(clientId);\n    if (!client) {\n      return {\n        status: 400,\n        body: { error: 'invalid_client', error_description: 'Invalid client' },\n      };\n    }\n    if (!this.store.safeCompare(this.store.hashSecret(clientSecret), client.clientSecretHash)) {\n      return {\n        status: 400,\n        body: { error: 'invalid_client', error_description: 'Invalid client credentials' },\n      };\n    }\n\n    // Verify PKCE (mandatory in OAuth 2.1)\n    if (!this.store.verifyS256Challenge(codeVerifier, authCode.codeChallenge)) {\n      return {\n        status: 400,\n        body: { error: 'invalid_grant', error_description: 'PKCE verification failed' },\n      };\n    }\n\n    // Mark code as used\n    await this.store.markAuthorizationCodeUsed(code);\n\n    // Issue token pair\n    const { accessToken, refreshToken } = await this.store.issueTokenPair({\n      clientId,\n      scopes: authCode.scopes,\n      agentId,\n      dpopThumbprint: dpopHeader,\n    });\n\n    const response = this.formatTokenResponse(accessToken, refreshToken, dpopHeader);\n    return {\n      status: 200,\n      body: response,\n      headers: { 'Cache-Control': 'no-store', Pragma: 'no-cache' },\n    };\n  }\n\n  private async handleClientCredentialsGrant(\n    body: Record<string, unknown>,\n    dpopHeader?: string\n  ): Promise<{ status: number; body: Record<string, unknown>; headers?: Record<string, string> }> {\n    const clientId = body.client_id as string;\n    const clientSecret = body.client_secret as string;\n    const requestedScopes = ((body.scope as string) || '').split(' ').filter(Boolean);\n    const agentId = body.agent_id as string | undefined;\n\n    if (!clientId || !clientSecret) {\n      return {\n        status: 400,\n        body: { error: 'invalid_request', error_description: 'Missing client_id or client_secret' },\n      };\n    }\n\n    const client = await this.store.getClient(clientId);\n    if (!client) {\n      return {\n        status: 400,\n        body: { error: 'invalid_client', error_description: 'Unknown client_id' },\n      };\n    }\n    if (client.clientType !== 'confidential') {\n      return {\n        status: 400,\n        body: {\n          error: 'unauthorized_client',\n          error_description: 'Client credentials grant requires confidential client',\n        },\n      };\n    }\n    if (!this.store.safeCompare(this.store.hashSecret(clientSecret), client.clientSecretHash)) {\n      return {\n        status: 400,\n        body: { error: 'invalid_client', error_description: 'Invalid client credentials' },\n      };\n    }\n\n    const scopes = requestedScopes.length > 0 ? requestedScopes : client.scopes;\n    const invalidScopes = scopes.filter(\n      (s) => !client.scopes.includes(s) && !client.scopes.includes('admin')\n    );\n    if (invalidScopes.length > 0) {\n      return {\n        status: 400,\n        body: {\n          error: 'invalid_scope',\n          error_description: `Scopes not authorized: ${invalidScopes.join(', ')}`,\n        },\n      };\n    }\n\n    const { accessToken, refreshToken } = await this.store.issueTokenPair({\n      clientId,\n      scopes,\n      agentId,\n      dpopThumbprint: dpopHeader,\n    });\n\n    const response = this.formatTokenResponse(accessToken, refreshToken, dpopHeader);\n    return {\n      status: 200,\n      body: response,\n      headers: { 'Cache-Control': 'no-store', Pragma: 'no-cache' },\n    };\n  }\n\n  private async handleRefreshTokenGrant(\n    body: Record<string, unknown>,\n    dpopHeader?: string\n  ): Promise<{ status: number; body: Record<string, unknown>; headers?: Record<string, string> }> {\n    const refreshTokenValue = body.refresh_token as string;\n    const clientId = body.client_id as string;\n    const clientSecret = body.client_secret as string;\n\n    if (!refreshTokenValue || !clientId || !clientSecret) {\n      return {\n        status: 400,\n        body: {\n          error: 'invalid_request',\n          error_description: 'Missing refresh_token, client_id, or client_secret',\n        },\n      };\n    }\n\n    const storedRefresh = await this.store.getRefreshToken(refreshTokenValue);\n    if (!storedRefresh) {\n      return {\n        status: 400,\n        body: { error: 'invalid_grant', error_description: 'Invalid refresh token' },\n      };\n    }\n\n    if (storedRefresh.used) {\n      // Token replay detected -- revoke entire chain\n      await this.store.revokeRefreshChain(storedRefresh.chainId);\n      return {\n        status: 400,\n        body: {\n          error: 'invalid_grant',\n          error_description: 'Refresh token replay detected. Token chain revoked.',\n        },\n      };\n    }\n\n    if (storedRefresh.expiresAt < Date.now()) {\n      return {\n        status: 400,\n        body: { error: 'invalid_grant', error_description: 'Refresh token expired' },\n      };\n    }\n\n    if (storedRefresh.clientId !== clientId) {\n      return {\n        status: 400,\n        body: { error: 'invalid_grant', error_description: 'Client mismatch' },\n      };\n    }\n\n    // Check if chain is revoked\n    const chainRevoked = await this.store.isChainRevoked(storedRefresh.chainId);\n    if (chainRevoked) {\n      return {\n        status: 400,\n        body: { error: 'invalid_grant', error_description: 'Token chain has been revoked' },\n      };\n    }\n\n    // Verify client\n    const client = await this.store.getClient(clientId);\n    if (!client) {\n      return {\n        status: 400,\n        body: { error: 'invalid_client', error_description: 'Invalid client' },\n      };\n    }\n    if (!this.store.safeCompare(this.store.hashSecret(clientSecret), client.clientSecretHash)) {\n      return {\n        status: 400,\n        body: { error: 'invalid_client', error_description: 'Invalid client credentials' },\n      };\n    }\n\n    // Mark old refresh token as used (rotation)\n    await this.store.markRefreshTokenUsed(refreshTokenValue);\n\n    // Issue new token pair with same chain\n    const { accessToken, refreshToken } = await this.store.issueTokenPair({\n      clientId,\n      scopes: storedRefresh.scopes,\n      dpopThumbprint: dpopHeader,\n      chainId: storedRefresh.chainId,\n    });\n\n    const response = this.formatTokenResponse(accessToken, refreshToken, dpopHeader);\n    return {\n      status: 200,\n      body: response,\n      headers: { 'Cache-Control': 'no-store', Pragma: 'no-cache' },\n    };\n  }\n\n  // ══════════════════════════════════════════════════════════════════════════\n  // TOKEN INTROSPECTION (POST /oauth/introspect) — RFC 7662\n  // ══════════════════════════════════════════════════════════════════════════\n\n  /**\n   * Handle POST /oauth/introspect\n   *\n   * Returns token metadata per RFC 7662. The response always includes\n   * `active` (boolean). When active=true, also includes client_id,\n   * scope, agent_id, exp, and iat.\n   */\n  async handleIntrospect(body: Record<string, unknown>): Promise<{\n    status: number;\n    body: Record<string, unknown>;\n  }> {\n    const token = body.token as string;\n    if (!token) {\n      return {\n        status: 400,\n        body: { error: 'invalid_request', error_description: 'Missing required parameter: token' },\n      };\n    }\n\n    const result = await this.introspect(token);\n\n    return {\n      status: 200,\n      body: {\n        active: result.active,\n        client_id: result.clientId,\n        scope: result.scopes?.join(' '),\n        agent_id: result.agentId,\n        token_type: 'Bearer',\n        exp: result.expiresAt ? Math.floor(result.expiresAt / 1000) : undefined,\n        iat: result.issuedAt ? Math.floor(result.issuedAt / 1000) : undefined,\n        iss: this.config.issuer,\n      },\n    };\n  }\n\n  /**\n   * Introspect a token (internal API).\n   */\n  async introspect(token: string): Promise<TokenIntrospectionResult> {\n    const stored = await this.store.getAccessToken(token);\n    if (!stored || stored.expiresAt < Date.now()) {\n      return { active: false };\n    }\n\n    return {\n      active: true,\n      clientId: stored.clientId,\n      scopes: stored.scopes,\n      agentId: stored.agentId,\n      expiresAt: stored.expiresAt,\n      issuedAt: stored.issuedAt,\n    };\n  }\n\n  // ══════════════════════════════════════════════════════════════════════════\n  // TOKEN REVOCATION (POST /oauth/revoke) — RFC 7009\n  // ══════════════════════════════════════════════════════════════════════════\n\n  /**\n   * Handle POST /oauth/revoke\n   *\n   * Per RFC 7009, always returns 200 even if the token was not found.\n   */\n  async handleRevoke(body: Record<string, unknown>): Promise<{\n    status: number;\n    body: Record<string, unknown>;\n  }> {\n    const token = body.token as string;\n    if (!token) {\n      return {\n        status: 400,\n        body: { error: 'invalid_request', error_description: 'Missing required parameter: token' },\n      };\n    }\n\n    const revoked = await this.revokeToken(token);\n    return {\n      status: 200,\n      body: { revoked },\n    };\n  }\n\n  /**\n   * Revoke a token (access or refresh).\n   */\n  async revokeToken(token: string): Promise<boolean> {\n    // Try access token\n    const deleted = await this.store.revokeAccessToken(token);\n    if (deleted) return true;\n\n    // Try refresh token -- revoke entire chain\n    const refresh = await this.store.getRefreshToken(token);\n    if (refresh) {\n      await this.store.revokeRefreshChain(refresh.chainId);\n      return true;\n    }\n\n    return false;\n  }\n\n  // ══════════════════════════════════════════════════════════════════════════\n  // HTTP REQUEST AUTHENTICATION\n  // ══════════════════════════════════════════════════════════════════════════\n\n  /**\n   * Authenticate an HTTP request from headers.\n   *\n   * Supports:\n   *   1. OAuth 2.1 Bearer token (Authorization: Bearer <token>)\n   *   2. DPoP token (Authorization: DPoP <token>)\n   *   3. Legacy API key (x-api-key header)\n   *   4. Legacy Bearer API key (Authorization: Bearer <api-key>)\n   *   5. Open dev mode (no auth, permissive mode, no API key configured)\n   */\n  async authenticateRequest(\n    headers: Record<string, string | string[] | undefined>\n  ): Promise<TokenIntrospectionResult> {\n    const authHeader =\n      (typeof headers['authorization'] === 'string' ? headers['authorization'] : '') || '';\n    const apiKey = (typeof headers['x-api-key'] === 'string' ? headers['x-api-key'] : '') || '';\n    const dpopHeader = (typeof headers['dpop'] === 'string' ? headers['dpop'] : '') || '';\n\n    // Try OAuth 2.1 Bearer token\n    if (authHeader.startsWith('Bearer ')) {\n      const token = authHeader.slice(7);\n      const result = await this.introspect(token);\n\n      if (result.active) {\n        // Verify DPoP if required\n        if (this.config.requireDPoP) {\n          const stored = await this.store.getAccessToken(token);\n          if (stored?.dpopThumbprint && !dpopHeader) {\n            return { active: false };\n          }\n        }\n        // Expand scopes for Gate 2 compatibility\n        result.scopes = expandScopes(result.scopes || []);\n        return result;\n      }\n\n      // Fall through to legacy check\n    }\n\n    // Try DPoP token\n    if (authHeader.startsWith('DPoP ')) {\n      const token = authHeader.slice(5);\n      const result = await this.introspect(token);\n      if (result.active) {\n        result.scopes = expandScopes(result.scopes || []);\n        return result;\n      }\n    }\n\n    // Try legacy API key\n    if (apiKey) {\n      return this.validateLegacyKey(apiKey);\n    }\n\n    // Try legacy Bearer that's actually an API key\n    if (authHeader.startsWith('Bearer ') && this.config.legacyApiKey) {\n      const key = authHeader.slice(7);\n      return this.validateLegacyKey(key);\n    }\n\n    // No auth provided - check if open dev mode\n    if (!this.config.legacyApiKey && this.config.migrationMode === 'permissive') {\n      return { active: true, scopes: ['admin:*'], agentId: 'open-dev-mode' };\n    }\n\n    return { active: false };\n  }\n\n  /**\n   * Validate a legacy API key during the migration period.\n   */\n  private validateLegacyKey(key: string): TokenIntrospectionResult {\n    if (this.config.migrationMode === 'strict') {\n      return { active: false };\n    }\n\n    if (!this.config.legacyApiKey) {\n      return { active: true, scopes: ['admin:*'], agentId: 'legacy-open-dev' };\n    }\n\n    if (this.safeCompare(key, this.config.legacyApiKey)) {\n      return {\n        active: true,\n        scopes: ['admin:*'],\n        agentId: 'legacy-api-key',\n        clientId: 'legacy',\n      };\n    }\n\n    return { active: false };\n  }\n\n  private safeCompare(a: string, b: string): boolean {\n    if (a.length !== b.length) return false;\n    return timingSafeEqual(Buffer.from(a), Buffer.from(b));\n  }\n\n  // ══════════════════════════════════════════════════════════════════════════\n  // OPENID CONFIGURATION (GET /.well-known/openid-configuration)\n  // ══════════════════════════════════════════════════════════════════════════\n\n  getOpenIDConfiguration(): Record<string, unknown> {\n    return {\n      issuer: this.config.issuer,\n      authorization_endpoint: `${this.config.issuer}/oauth/authorize`,\n      token_endpoint: `${this.config.issuer}/oauth/token`,\n      revocation_endpoint: `${this.config.issuer}/oauth/revoke`,\n      introspection_endpoint: `${this.config.issuer}/oauth/introspect`,\n      registration_endpoint: `${this.config.issuer}/oauth/register`,\n      response_types_supported: ['code'],\n      grant_types_supported: ['authorization_code', 'client_credentials', 'refresh_token'],\n      token_endpoint_auth_methods_supported: ['client_secret_post', 'client_secret_basic'],\n      code_challenge_methods_supported: ['S256'],\n      scopes_supported: Object.keys(OAUTH2_SCOPES),\n      dpop_signing_alg_values_supported: ['ES256', 'RS256'],\n      service_documentation: 'https://github.com/buildwithholoscript/HoloScript',\n    };\n  }\n\n  // ══════════════════════════════════════════════════════════════════════════\n  // STATS & LIFECYCLE\n  // ══════════════════════════════════════════════════════════════════════════\n\n  async getStats(): Promise<Record<string, number>> {\n    const stats = await this.store.getStats();\n    return {\n      registeredClients: stats.registeredClients,\n      activeAccessTokens: stats.activeAccessTokens,\n      activeRefreshTokens: stats.activeRefreshTokens,\n      pendingAuthCodes: stats.pendingAuthCodes,\n      revokedChains: stats.revokedChains,\n    };\n  }\n\n  /** Expose the underlying store for advanced usage */\n  getStore(): TokenStore {\n    return this.store;\n  }\n\n  /** Clean up resources */\n  destroy(): void {\n    this.store.destroy();\n  }\n\n  // ── Internal Helpers ───────────────────────────────────────────────────\n\n  private formatTokenResponse(\n    accessToken: StoredAccessToken,\n    refreshToken: { token: string },\n    dpopHeader?: string\n  ): OAuth2TokenResponse {\n    return {\n      access_token: accessToken.token,\n      token_type: dpopHeader ? 'DPoP' : 'Bearer',\n      expires_in: this.config.ttl.accessTokenTTL,\n      refresh_token: refreshToken.token,\n      scope: accessToken.scopes.join(' '),\n    };\n  }\n}\n\n// ── Singleton ────────────────────────────────────────────────────────────────\n\nlet _provider: OAuth2Provider | null = null;\n\n/**\n * Get or create the singleton OAuth2Provider instance.\n */\nexport function getOAuth2Provider(config?: Partial<OAuth2ProviderConfig>): OAuth2Provider {\n  if (!_provider) {\n    _provider = new OAuth2Provider(config);\n  }\n  return _provider;\n}\n\n/**\n * Reset the singleton (for tests).\n */\nexport function resetOAuth2Provider(): void {\n  _provider?.destroy();\n  _provider = null;\n}\n","/**\n * Token Store — Pluggable Storage Backend for OAuth 2.1 Tokens\n *\n * Provides an abstraction layer over token storage with:\n * - In-memory implementation (dev/testing)\n * - Interface for pluggable backends (Redis, PostgreSQL)\n * - Token rotation on refresh\n * - Configurable TTL (access: 1hr default, refresh: 30d default)\n * - Automatic cleanup of expired entries\n *\n * The in-memory store is suitable for single-process deployments and tests.\n * Production deployments should use a distributed backend (Redis, PostgreSQL)\n * by implementing the TokenStoreBackend interface.\n */\n\nimport { randomUUID, createHash, timingSafeEqual } from 'crypto';\n\n// ── Configuration ────────────────────────────────────────────────────────────\n\nexport interface TokenStoreTTL {\n  /** Access token TTL in seconds. Default: 3600 (1 hour) */\n  accessTokenTTL: number;\n  /** Refresh token TTL in seconds. Default: 2592000 (30 days) */\n  refreshTokenTTL: number;\n  /** Authorization code TTL in seconds. Default: 300 (5 min) */\n  authCodeTTL: number;\n}\n\nexport const DEFAULT_TTL: TokenStoreTTL = {\n  accessTokenTTL: 3600, // 1 hour\n  refreshTokenTTL: 2592000, // 30 days\n  authCodeTTL: 300, // 5 minutes\n};\n\n// ── Token Types ──────────────────────────────────────────────────────────────\n\nexport interface StoredAccessToken {\n  token: string;\n  clientId: string;\n  scopes: string[];\n  issuedAt: number;\n  expiresAt: number;\n  agentId?: string;\n  dpopThumbprint?: string;\n}\n\nexport interface StoredRefreshToken {\n  token: string;\n  clientId: string;\n  scopes: string[];\n  issuedAt: number;\n  expiresAt: number;\n  /** Chain ID for token rotation tracking */\n  chainId: string;\n  /** Whether this token has been consumed (rotation) */\n  used: boolean;\n}\n\nexport interface StoredAuthorizationCode {\n  code: string;\n  clientId: string;\n  redirectUri: string;\n  scopes: string[];\n  codeChallenge: string;\n  codeChallengeMethod: 'S256';\n  expiresAt: number;\n  used: boolean;\n}\n\nexport interface StoredClient {\n  clientId: string;\n  /** SHA-256 hash of client secret */\n  clientSecretHash: string;\n  clientName: string;\n  redirectUris: string[];\n  scopes: string[];\n  createdAt: number;\n  clientType: 'confidential' | 'public';\n  rateLimit: number;\n}\n\n// ── Backend Interface ────────────────────────────────────────────────────────\n\n/**\n * Pluggable backend interface for token storage.\n *\n * Implement this interface to use Redis, PostgreSQL, or any other\n * distributed storage system. All methods are async to support\n * network-based backends.\n *\n * Example Redis implementation:\n * ```typescript\n * class RedisTokenStore implements TokenStoreBackend {\n *   constructor(private redis: Redis) {}\n *\n *   async getAccessToken(token: string) {\n *     const data = await this.redis.get(`at:${token}`);\n *     return data ? JSON.parse(data) : undefined;\n *   }\n *\n *   async setAccessToken(token: StoredAccessToken) {\n *     const ttl = Math.ceil((token.expiresAt - Date.now()) / 1000);\n *     await this.redis.set(`at:${token.token}`, JSON.stringify(token), 'EX', ttl);\n *   }\n *   // ... etc\n * }\n * ```\n *\n * Example PostgreSQL implementation:\n * ```typescript\n * class PostgresTokenStore implements TokenStoreBackend {\n *   constructor(private pool: Pool) {}\n *\n *   async getAccessToken(token: string) {\n *     const { rows } = await this.pool.query(\n *       'SELECT * FROM access_tokens WHERE token = $1 AND expires_at > NOW()',\n *       [token]\n *     );\n *     return rows[0] || undefined;\n *   }\n *   // ... etc\n * }\n * ```\n */\nexport interface TokenStoreBackend {\n  // ── Access Tokens ─────────────────────────────────────────────────────\n  getAccessToken(token: string): Promise<StoredAccessToken | undefined>;\n  setAccessToken(token: StoredAccessToken): Promise<void>;\n  deleteAccessToken(token: string): Promise<boolean>;\n  deleteAccessTokensByClient(clientId: string): Promise<number>;\n\n  // ── Refresh Tokens ────────────────────────────────────────────────────\n  getRefreshToken(token: string): Promise<StoredRefreshToken | undefined>;\n  setRefreshToken(token: StoredRefreshToken): Promise<void>;\n  deleteRefreshToken(token: string): Promise<boolean>;\n  deleteRefreshTokensByClient(clientId: string): Promise<number>;\n  markRefreshTokenUsed(token: string): Promise<void>;\n\n  // ── Authorization Codes ───────────────────────────────────────────────\n  getAuthorizationCode(code: string): Promise<StoredAuthorizationCode | undefined>;\n  setAuthorizationCode(code: StoredAuthorizationCode): Promise<void>;\n  deleteAuthorizationCode(code: string): Promise<boolean>;\n  markAuthorizationCodeUsed(code: string): Promise<void>;\n\n  // ── Clients ───────────────────────────────────────────────────────────\n  getClient(clientId: string): Promise<StoredClient | undefined>;\n  setClient(client: StoredClient): Promise<void>;\n  deleteClient(clientId: string): Promise<boolean>;\n  countClients(): Promise<number>;\n\n  // ── Revoked Chains ────────────────────────────────────────────────────\n  isChainRevoked(chainId: string): Promise<boolean>;\n  revokeChain(chainId: string): Promise<void>;\n\n  // ── Cleanup ───────────────────────────────────────────────────────────\n  /**\n   * Remove expired tokens and codes. Called periodically by the store.\n   * Returns the number of entries removed.\n   */\n  cleanup(): Promise<number>;\n\n  // ── Stats ─────────────────────────────────────────────────────────────\n  getStats(): Promise<TokenStoreStats>;\n}\n\nexport interface TokenStoreStats {\n  registeredClients: number;\n  activeAccessTokens: number;\n  activeRefreshTokens: number;\n  pendingAuthCodes: number;\n  revokedChains: number;\n}\n\n// ── In-Memory Backend ────────────────────────────────────────────────────────\n\n/**\n * In-memory token store backend for development and testing.\n *\n * This backend stores all tokens in JavaScript Maps. It is NOT suitable for\n * multi-process deployments because state is not shared between workers.\n *\n * For production, implement TokenStoreBackend with Redis or PostgreSQL.\n */\nexport class InMemoryTokenStore implements TokenStoreBackend {\n  private accessTokens = new Map<string, StoredAccessToken>();\n  private refreshTokens = new Map<string, StoredRefreshToken>();\n  private authCodes = new Map<string, StoredAuthorizationCode>();\n  private clients = new Map<string, StoredClient>();\n  private revokedChains = new Set<string>();\n\n  // ── Access Tokens ─────────────────────────────────────────────────────\n\n  async getAccessToken(token: string): Promise<StoredAccessToken | undefined> {\n    const stored = this.accessTokens.get(token);\n    if (stored && stored.expiresAt < Date.now()) {\n      this.accessTokens.delete(token);\n      return undefined;\n    }\n    return stored;\n  }\n\n  async setAccessToken(token: StoredAccessToken): Promise<void> {\n    this.accessTokens.set(token.token, token);\n  }\n\n  async deleteAccessToken(token: string): Promise<boolean> {\n    return this.accessTokens.delete(token);\n  }\n\n  async deleteAccessTokensByClient(clientId: string): Promise<number> {\n    let count = 0;\n    for (const [key, token] of this.accessTokens) {\n      if (token.clientId === clientId) {\n        this.accessTokens.delete(key);\n        count++;\n      }\n    }\n    return count;\n  }\n\n  // ── Refresh Tokens ────────────────────────────────────────────────────\n\n  async getRefreshToken(token: string): Promise<StoredRefreshToken | undefined> {\n    const stored = this.refreshTokens.get(token);\n    if (stored && stored.expiresAt < Date.now()) {\n      this.refreshTokens.delete(token);\n      return undefined;\n    }\n    return stored;\n  }\n\n  async setRefreshToken(token: StoredRefreshToken): Promise<void> {\n    this.refreshTokens.set(token.token, token);\n  }\n\n  async deleteRefreshToken(token: string): Promise<boolean> {\n    return this.refreshTokens.delete(token);\n  }\n\n  async deleteRefreshTokensByClient(clientId: string): Promise<number> {\n    let count = 0;\n    for (const [key, token] of this.refreshTokens) {\n      if (token.clientId === clientId) {\n        this.revokedChains.add(token.chainId);\n        this.refreshTokens.delete(key);\n        count++;\n      }\n    }\n    return count;\n  }\n\n  async markRefreshTokenUsed(token: string): Promise<void> {\n    const stored = this.refreshTokens.get(token);\n    if (stored) {\n      stored.used = true;\n    }\n  }\n\n  // ── Authorization Codes ───────────────────────────────────────────────\n\n  async getAuthorizationCode(code: string): Promise<StoredAuthorizationCode | undefined> {\n    const stored = this.authCodes.get(code);\n    if (stored && stored.expiresAt < Date.now()) {\n      this.authCodes.delete(code);\n      return undefined;\n    }\n    return stored;\n  }\n\n  async setAuthorizationCode(code: StoredAuthorizationCode): Promise<void> {\n    this.authCodes.set(code.code, code);\n  }\n\n  async deleteAuthorizationCode(code: string): Promise<boolean> {\n    return this.authCodes.delete(code);\n  }\n\n  async markAuthorizationCodeUsed(code: string): Promise<void> {\n    const stored = this.authCodes.get(code);\n    if (stored) {\n      stored.used = true;\n    }\n  }\n\n  // ── Clients ───────────────────────────────────────────────────────────\n\n  async getClient(clientId: string): Promise<StoredClient | undefined> {\n    return this.clients.get(clientId);\n  }\n\n  async setClient(client: StoredClient): Promise<void> {\n    this.clients.set(client.clientId, client);\n  }\n\n  async deleteClient(clientId: string): Promise<boolean> {\n    return this.clients.delete(clientId);\n  }\n\n  async countClients(): Promise<number> {\n    return this.clients.size;\n  }\n\n  // ── Revoked Chains ────────────────────────────────────────────────────\n\n  async isChainRevoked(chainId: string): Promise<boolean> {\n    return this.revokedChains.has(chainId);\n  }\n\n  async revokeChain(chainId: string): Promise<void> {\n    this.revokedChains.add(chainId);\n  }\n\n  // ── Cleanup ───────────────────────────────────────────────────────────\n\n  async cleanup(): Promise<number> {\n    const now = Date.now();\n    let removed = 0;\n\n    for (const [key, code] of this.authCodes) {\n      if (code.expiresAt < now || code.used) {\n        this.authCodes.delete(key);\n        removed++;\n      }\n    }\n\n    for (const [key, token] of this.accessTokens) {\n      if (token.expiresAt < now) {\n        this.accessTokens.delete(key);\n        removed++;\n      }\n    }\n\n    for (const [key, token] of this.refreshTokens) {\n      if (token.expiresAt < now || token.used) {\n        this.refreshTokens.delete(key);\n        removed++;\n      }\n    }\n\n    return removed;\n  }\n\n  // ── Stats ─────────────────────────────────────────────────────────────\n\n  async getStats(): Promise<TokenStoreStats> {\n    return {\n      registeredClients: this.clients.size,\n      activeAccessTokens: this.accessTokens.size,\n      activeRefreshTokens: this.refreshTokens.size,\n      pendingAuthCodes: this.authCodes.size,\n      revokedChains: this.revokedChains.size,\n    };\n  }\n\n  // ── Test Helpers ──────────────────────────────────────────────────────\n\n  /** Clear all data (for tests) */\n  clear(): void {\n    this.accessTokens.clear();\n    this.refreshTokens.clear();\n    this.authCodes.clear();\n    this.clients.clear();\n    this.revokedChains.clear();\n  }\n}\n\n// ── Token Store Wrapper ──────────────────────────────────────────────────────\n\n/**\n * TokenStore wraps a backend with TTL configuration and periodic cleanup.\n *\n * Usage:\n * ```typescript\n * // Dev/test (in-memory)\n * const store = new TokenStore();\n *\n * // Production (Redis)\n * const store = new TokenStore({\n *   backend: new RedisTokenStore(redisClient),\n *   ttl: { accessTokenTTL: 3600, refreshTokenTTL: 2592000, authCodeTTL: 300 },\n * });\n * ```\n */\nexport class TokenStore {\n  readonly backend: TokenStoreBackend;\n  readonly ttl: TokenStoreTTL;\n  private cleanupInterval: ReturnType<typeof setInterval> | null = null;\n\n  constructor(options?: {\n    backend?: TokenStoreBackend;\n    ttl?: Partial<TokenStoreTTL>;\n    /** Cleanup interval in ms. Default: 60000 (1 min). Set 0 to disable. */\n    cleanupIntervalMs?: number;\n  }) {\n    this.backend = options?.backend || new InMemoryTokenStore();\n    this.ttl = { ...DEFAULT_TTL, ...options?.ttl };\n\n    const cleanupMs = options?.cleanupIntervalMs ?? 60_000;\n    if (cleanupMs > 0) {\n      this.startCleanup(cleanupMs);\n    }\n  }\n\n  // ── Token Generation ──────────────────────────────────────────────────\n\n  generateToken(): string {\n    return `hs_${randomUUID().replace(/-/g, '')}${randomUUID().replace(/-/g, '')}`;\n  }\n\n  generateClientId(): string {\n    return `hsc_${randomUUID().replace(/-/g, '')}`;\n  }\n\n  hashSecret(secret: string): string {\n    return createHash('sha256').update(secret).digest('hex');\n  }\n\n  safeCompare(a: string, b: string): boolean {\n    if (a.length !== b.length) return false;\n    return timingSafeEqual(Buffer.from(a), Buffer.from(b));\n  }\n\n  verifyS256Challenge(verifier: string, challenge: string): boolean {\n    const computed = createHash('sha256').update(verifier).digest('base64url');\n    return computed === challenge;\n  }\n\n  // ── Access Token CRUD ─────────────────────────────────────────────────\n\n  async createAccessToken(params: {\n    clientId: string;\n    scopes: string[];\n    agentId?: string;\n    dpopThumbprint?: string;\n  }): Promise<StoredAccessToken> {\n    const now = Date.now();\n    const token: StoredAccessToken = {\n      token: this.generateToken(),\n      clientId: params.clientId,\n      scopes: params.scopes,\n      issuedAt: now,\n      expiresAt: now + this.ttl.accessTokenTTL * 1000,\n      agentId: params.agentId,\n      dpopThumbprint: params.dpopThumbprint,\n    };\n    await this.backend.setAccessToken(token);\n    return token;\n  }\n\n  async getAccessToken(token: string): Promise<StoredAccessToken | undefined> {\n    return this.backend.getAccessToken(token);\n  }\n\n  async revokeAccessToken(token: string): Promise<boolean> {\n    return this.backend.deleteAccessToken(token);\n  }\n\n  // ── Refresh Token CRUD ────────────────────────────────────────────────\n\n  async createRefreshToken(params: {\n    clientId: string;\n    scopes: string[];\n    chainId?: string;\n  }): Promise<StoredRefreshToken> {\n    const now = Date.now();\n    const token: StoredRefreshToken = {\n      token: this.generateToken(),\n      clientId: params.clientId,\n      scopes: params.scopes,\n      issuedAt: now,\n      expiresAt: now + this.ttl.refreshTokenTTL * 1000,\n      chainId: params.chainId || randomUUID(),\n      used: false,\n    };\n    await this.backend.setRefreshToken(token);\n    return token;\n  }\n\n  async getRefreshToken(token: string): Promise<StoredRefreshToken | undefined> {\n    return this.backend.getRefreshToken(token);\n  }\n\n  async markRefreshTokenUsed(token: string): Promise<void> {\n    return this.backend.markRefreshTokenUsed(token);\n  }\n\n  /**\n   * Write-through an externally-issued access token (legacy oauth21 registry\n   * parity) so Bearers survive redeploys of the in-memory registry.\n   */\n  async importAccessToken(token: StoredAccessToken): Promise<void> {\n    await this.backend.setAccessToken(token);\n  }\n\n  /** Write-through an externally-issued refresh token (legacy registry parity). */\n  async importRefreshToken(token: StoredRefreshToken): Promise<void> {\n    await this.backend.setRefreshToken(token);\n  }\n\n  async revokeRefreshChain(chainId: string): Promise<void> {\n    return this.backend.revokeChain(chainId);\n  }\n\n  async isChainRevoked(chainId: string): Promise<boolean> {\n    return this.backend.isChainRevoked(chainId);\n  }\n\n  // ── Token Pair Issuance ───────────────────────────────────────────────\n\n  /**\n   * Issue an access + refresh token pair.\n   * Used after successful authorization code exchange, client credentials,\n   * or refresh token rotation.\n   */\n  async issueTokenPair(params: {\n    clientId: string;\n    scopes: string[];\n    agentId?: string;\n    dpopThumbprint?: string;\n    chainId?: string;\n  }): Promise<{ accessToken: StoredAccessToken; refreshToken: StoredRefreshToken }> {\n    const chainId = params.chainId || randomUUID();\n\n    const accessToken = await this.createAccessToken({\n      clientId: params.clientId,\n      scopes: params.scopes,\n      agentId: params.agentId,\n      dpopThumbprint: params.dpopThumbprint,\n    });\n\n    const refreshToken = await this.createRefreshToken({\n      clientId: params.clientId,\n      scopes: params.scopes,\n      chainId,\n    });\n\n    return { accessToken, refreshToken };\n  }\n\n  // ── Authorization Code CRUD ───────────────────────────────────────────\n\n  async createAuthorizationCode(params: {\n    clientId: string;\n    redirectUri: string;\n    scopes: string[];\n    codeChallenge: string;\n    codeChallengeMethod: 'S256';\n  }): Promise<StoredAuthorizationCode> {\n    const now = Date.now();\n    const code: StoredAuthorizationCode = {\n      code: this.generateToken(),\n      clientId: params.clientId,\n      redirectUri: params.redirectUri,\n      scopes: params.scopes,\n      codeChallenge: params.codeChallenge,\n      codeChallengeMethod: params.codeChallengeMethod,\n      expiresAt: now + this.ttl.authCodeTTL * 1000,\n      used: false,\n    };\n    await this.backend.setAuthorizationCode(code);\n    return code;\n  }\n\n  async getAuthorizationCode(code: string): Promise<StoredAuthorizationCode | undefined> {\n    return this.backend.getAuthorizationCode(code);\n  }\n\n  async markAuthorizationCodeUsed(code: string): Promise<void> {\n    return this.backend.markAuthorizationCodeUsed(code);\n  }\n\n  // ── Client CRUD ───────────────────────────────────────────────────────\n\n  async registerClient(params: {\n    clientName: string;\n    redirectUris: string[];\n    scopes: string[];\n    clientType?: 'confidential' | 'public';\n    rateLimit?: number;\n    maxClients?: number;\n    /**\n     * Import mode: reuse an externally-issued identity so parallel registries\n     * (legacy in-memory oauth21 + this durable store) share ONE client_id.\n     * Without this the /oauth/register dual-write diverges and the durable\n     * copy is unreachable by the credentials the caller holds.\n     */\n    clientId?: string;\n    clientSecret?: string;\n  }): Promise<{ clientId: string; clientSecret: string }> {\n    const maxClients = params.maxClients || 1000;\n    const count = await this.backend.countClients();\n    if (count >= maxClients) {\n      throw new Error('Maximum client registration limit reached');\n    }\n\n    const clientId = params.clientId ?? this.generateClientId();\n    const clientSecret = params.clientSecret ?? this.generateToken();\n\n    await this.backend.setClient({\n      clientId,\n      clientSecretHash: this.hashSecret(clientSecret),\n      clientName: params.clientName,\n      redirectUris: params.redirectUris,\n      scopes: params.scopes,\n      createdAt: Date.now(),\n      clientType: params.clientType || 'confidential',\n      rateLimit: params.rateLimit || 60,\n    });\n\n    return { clientId, clientSecret };\n  }\n\n  async getClient(clientId: string): Promise<StoredClient | undefined> {\n    return this.backend.getClient(clientId);\n  }\n\n  async revokeClient(clientId: string): Promise<boolean> {\n    await this.backend.deleteAccessTokensByClient(clientId);\n    await this.backend.deleteRefreshTokensByClient(clientId);\n    return this.backend.deleteClient(clientId);\n  }\n\n  // ── Stats ─────────────────────────────────────────────────────────────\n\n  async getStats(): Promise<TokenStoreStats> {\n    return this.backend.getStats();\n  }\n\n  // ── Cleanup ───────────────────────────────────────────────────────────\n\n  private startCleanup(intervalMs: number): void {\n    if (this.cleanupInterval) return;\n    this.cleanupInterval = setInterval(async () => {\n      try {\n        await this.backend.cleanup();\n      } catch {\n        // Cleanup failure is non-fatal\n      }\n    }, intervalMs);\n\n    // Ensure the interval doesn't keep the process alive\n    if (this.cleanupInterval.unref) {\n      this.cleanupInterval.unref();\n    }\n  }\n\n  /** Stop cleanup timer and release resources */\n  destroy(): void {\n    if (this.cleanupInterval) {\n      clearInterval(this.cleanupInterval);\n      this.cleanupInterval = null;\n    }\n  }\n}\n","/**\n * Triple-Gate Security Pattern for HoloScript MCP Server\n *\n * Gate 1: Client → LLM Prompt Validation\n *   Validates that incoming requests don't contain injection patterns,\n *   are well-formed, and meet size/rate limits before reaching tool dispatch.\n *\n * Gate 2: LLM → MCP Tool Authorization (per-tool scopes)\n *   See tool-scopes.ts — checks OAuth 2.1 scopes against tool requirements.\n *\n * Gate 3: MCP → Downstream API (StdlibPolicy enforcement)\n *   Enforces StdlibPolicy restrictions on tools that interact with\n *   the filesystem, network, shell, or GPU resources.\n */\n\nimport type { TokenIntrospection } from './oauth21';\nimport type { ToolRiskLevel } from './tool-scopes';\nimport { getToolRiskLevel, authorizeToolCall } from './tool-scopes';\n\n/**\n * StdlibPolicy interface (mirrored from @holoscript/core to avoid\n * circular dependency in the security module — identical shape).\n */\nexport interface StdlibPolicy {\n  allowedPaths: string[];\n  maxFileBytes: number;\n  allowShell: boolean;\n  allowedShellCommands: string[];\n  maxShellOutputBytes: number;\n  shellTimeoutMs: number;\n  allowNetwork: boolean;\n  allowedHosts: string[];\n  rootDir: string;\n  allowMediaDecode?: boolean;\n  allowDepthInference?: boolean;\n  allowGpuCompute?: boolean;\n  maxGifFrames?: number;\n  maxVideoDurationSec?: number;\n  maxMediaResolution?: number;\n}\n\n// ── Gate 1: Prompt Validation ────────────────────────────────────────────────\n\nexport interface Gate1Config {\n  /** Maximum request body size in bytes. Default: 1MB */\n  maxBodySize: number;\n  /** Maximum tool argument string length. Default: 100KB */\n  maxArgStringLength: number;\n  /** Maximum number of nested objects in arguments. Default: 10 */\n  maxArgDepth: number;\n  /** Block requests with suspicious injection patterns. Default: true */\n  blockInjectionPatterns: boolean;\n  /** Rate limit: max requests per minute per client. Default: 120 */\n  rateLimitPerMinute: number;\n}\n\nexport const DEFAULT_GATE1_CONFIG: Gate1Config = {\n  maxBodySize: 10 * 1024 * 1024, // 10MB — increased for inline sourceFiles absorb\n  maxArgStringLength: 500 * 1024, // 500KB per string — needed for large source file inline absorb\n  maxArgDepth: 10,\n  blockInjectionPatterns: true,\n  rateLimitPerMinute: 120,\n};\n\n/**\n * Mustache-style `{{ ... }}` binding. Flagged as SSTI on generic arg values, but is\n * legitimate HoloScript @fetch row-template syntax (e.g. founder-console.holo uses\n * {{label}}/{{url}}) — so it is skipped ONLY on HoloScript-source fields of\n * compile/validate tools (see isHoloSourceField / TEMPLATE_EXEMPT_PATTERNS). The\n * compile path feeds `code` to parseHolo(), never to a server-side template engine.\n * Declared above INJECTION_PATTERNS (which references it) to avoid a TDZ error.\n */\nconst MUSTACHE_BINDING_PATTERN = /\\{\\{.*\\}\\}/;\n\n/**\n * Templating-only patterns safe to skip on a verified HoloScript-source field. Every\n * other INJECTION_PATTERN (shell, path traversal, proto-pollution, ${process.},\n * JSON-RPC) stays enforced even on those fields.\n */\nconst TEMPLATE_EXEMPT_PATTERNS: readonly RegExp[] = [MUSTACHE_BINDING_PATTERN];\n\n// Injection patterns that should never appear in tool arguments\nconst INJECTION_PATTERNS = [\n  // Shell injection\n  /;\\s*(rm|del|format|mkfs|dd)\\s/i,\n  /\\|\\|\\s*(rm|del|format)\\s/i,\n  /&&\\s*(rm|del|format)\\s/i,\n  // Backtick command-substitution: tightened from `\\`[^\\`]*\\b(rm|del|format)\\b[^\\`]*\\``\n  // (W.GOLD.039 Sapir-Whorf — overly broad lexical firewall crippled JSDoc/CSS/GLSL\n  // mentions of `format`). Now requires the dangerous command to START the span and\n  // be followed by at least one command-line-shaped arg (flag, path, redirect, pipe,\n  // glob, $(...), drive letter, if=/of=). Allows benign descriptive uses like\n  // `format: rgba`, `format(value)`, `format the matrix`, `del` (HTML element).\n  // See task_1778093521547_vx4i + W.GOLD.035/039/193.\n  /`\\s*(rm|del|format|mkfs|dd)(?:\\.\\w+)?\\s+(?:-{1,2}\\w|[a-z]:|[/\\\\]|\\.{1,2}[/\\\\]|\\$\\(|\\$\\{|>{1,2}|<{1,2}|\\||;|&&?|\\*|if=|of=|\\?[*]|\\S*[/\\\\])[^`]*`/i,\n  /\\$\\([^)]*\\b(rm|del|format)\\b[^)]*\\)/i,\n\n  // Path traversal (../../ etc or deeper)\n  /\\.\\.[/\\\\].*\\.\\.[/\\\\]/,\n  /%2e%2e[/\\\\%]/i,\n\n  // Prototype pollution\n  /__proto__/,\n  /constructor\\s*\\.\\s*prototype/,\n\n  // Server-side template injection. MUSTACHE_BINDING_PATTERN is exempted on\n  // HoloScript-source fields (code/content/source) of compile/validate tools —\n  // `{{field}}` is the canonical @fetch row-template syntax of the HoloScript\n  // language, consumed by parseHolo() (W.GOLD.039 Sapir-Whorf class: don't block\n  // the vocabulary of the language being compiled). `${...process.}` stays armed\n  // on ALL fields — it is never valid HoloScript.\n  MUSTACHE_BINDING_PATTERN,\n  /\\$\\{.*process\\./,\n\n  // MCP protocol injection (attempt to inject JSON-RPC commands)\n  /\"jsonrpc\"\\s*:\\s*\"2\\.0\".*\"method\"\\s*:/,\n];\n\n/**\n * Tools whose HoloScript-source field carries raw .hs/.holo source that the\n * HoloScript parser (not a server-side template engine) consumes — so Mustache\n * bindings are legitimate language syntax there.\n */\nconst HOLO_SOURCE_TOOL_PREFIXES = [\n  'compile_to_',\n  'compile_holoscript',\n  'compile_pipeline',\n  'validate_holoscript',\n];\n\n/** Arg fields known to carry raw HoloScript source. */\nconst HOLO_SOURCE_FIELDS = new Set(['code', 'content', 'source']);\n\nfunction isHoloSourceField(toolName: string, fieldPath: string): boolean {\n  const isHoloSourceTool = HOLO_SOURCE_TOOL_PREFIXES.some(\n    (p) => toolName === p || toolName.startsWith(p)\n  );\n  // Guard on exact top-level field membership so a nested attacker object named\n  // \"code\" deeper in the arg tree is NOT exempted.\n  return isHoloSourceTool && HOLO_SOURCE_FIELDS.has(fieldPath);\n}\n\nfunction isInlineSourceFileContentField(toolName: string, fieldPath: string): boolean {\n  return toolName === 'holo_absorb_repo' && /^sourceFiles\\[\\d+\\]\\.content$/.test(fieldPath);\n}\n\n/** Rate limiter: sliding window per client */\nconst rateLimitWindows = new Map<string, number[]>();\n\nexport interface Gate1Result {\n  passed: boolean;\n  reason?: string;\n  /** Sanitized arguments (with dangerous patterns removed) */\n  sanitizedArgs?: Record<string, unknown>;\n}\n\n/**\n * Gate 1: Validate incoming request before tool dispatch.\n *\n * Checks:\n * 1. Request body size\n * 2. Argument string lengths\n * 3. Argument nesting depth\n * 4. Injection pattern detection\n * 5. Rate limiting per client\n */\nexport function gate1ValidateRequest(\n  toolName: string,\n  args: Record<string, unknown>,\n  clientId: string,\n  config: Gate1Config = DEFAULT_GATE1_CONFIG\n): Gate1Result {\n  // Rate limiting\n  const now = Date.now();\n  const windowStart = now - 60_000;\n  const clientKey = clientId || 'anonymous';\n  let timestamps = rateLimitWindows.get(clientKey) || [];\n  timestamps = timestamps.filter((t) => t > windowStart);\n  timestamps.push(now);\n  rateLimitWindows.set(clientKey, timestamps);\n\n  if (timestamps.length > config.rateLimitPerMinute) {\n    return {\n      passed: false,\n      reason: `Rate limit exceeded: ${timestamps.length}/${config.rateLimitPerMinute} requests per minute`,\n    };\n  }\n\n  // Check argument size\n  const argsJson = JSON.stringify(args);\n  if (argsJson.length > config.maxBodySize) {\n    return {\n      passed: false,\n      reason: `Request body exceeds maximum size (${argsJson.length} > ${config.maxBodySize} bytes)`,\n    };\n  }\n\n  // Check individual string argument lengths\n  const longStrings = findLongStrings(args, config.maxArgStringLength);\n  if (longStrings.length > 0) {\n    return {\n      passed: false,\n      reason: `Argument string(s) exceed maximum length: ${longStrings.map((s) => `${s.path} (${s.length})`).join(', ')}`,\n    };\n  }\n\n  // Check nesting depth\n  const depth = measureDepth(args);\n  if (depth > config.maxArgDepth) {\n    return {\n      passed: false,\n      reason: `Argument nesting depth exceeds maximum (${depth} > ${config.maxArgDepth})`,\n    };\n  }\n\n  // Injection pattern detection\n  if (config.blockInjectionPatterns) {\n    const injections = detectInjectionPatterns(args, toolName);\n    if (injections.length > 0) {\n      return {\n        passed: false,\n        reason: `Suspicious patterns detected in arguments: ${injections.join('; ')}`,\n      };\n    }\n  }\n\n  return { passed: true, sanitizedArgs: args };\n}\n\nfunction findLongStrings(\n  obj: unknown,\n  maxLen: number,\n  path = ''\n): Array<{ path: string; length: number }> {\n  const results: Array<{ path: string; length: number }> = [];\n  if (typeof obj === 'string' && obj.length > maxLen) {\n    results.push({ path: path || 'root', length: obj.length });\n  } else if (Array.isArray(obj)) {\n    obj.forEach((item, i) => {\n      results.push(...findLongStrings(item, maxLen, `${path}[${i}]`));\n    });\n  } else if (obj && typeof obj === 'object') {\n    for (const [key, val] of Object.entries(obj)) {\n      results.push(...findLongStrings(val, maxLen, path ? `${path}.${key}` : key));\n    }\n  }\n  return results;\n}\n\nfunction measureDepth(obj: unknown, current = 0): number {\n  if (!obj || typeof obj !== 'object') return current;\n  if (Array.isArray(obj)) {\n    return Math.max(current + 1, ...obj.map((item) => measureDepth(item, current + 1)));\n  }\n  const values = Object.values(obj);\n  if (values.length === 0) return current + 1;\n  return Math.max(current + 1, ...values.map((val) => measureDepth(val, current + 1)));\n}\n\nfunction detectInjectionPatterns(obj: unknown, toolName = '', path = ''): string[] {\n  const findings: string[] = [];\n  if (typeof obj === 'string') {\n    if (isInlineSourceFileContentField(toolName, path)) return findings;\n\n    // On a verified HoloScript-source field, skip templating-only patterns ({{ }}\n    // bindings) — valid language syntax, not injection. Shell, path traversal,\n    // ${process.}, proto-pollution and JSON-RPC patterns all still apply.\n    const skipTemplate = isHoloSourceField(toolName, path);\n    for (const pattern of INJECTION_PATTERNS) {\n      if (skipTemplate && TEMPLATE_EXEMPT_PATTERNS.includes(pattern)) continue;\n      if (pattern.test(obj)) {\n        findings.push(`Injection pattern in ${path || 'value'}: ${pattern.source}`);\n        break; // One finding per value is enough\n      }\n    }\n  } else if (Array.isArray(obj)) {\n    obj.forEach((item, i) => {\n      findings.push(...detectInjectionPatterns(item, toolName, `${path}[${i}]`));\n    });\n  } else if (obj && typeof obj === 'object') {\n    // Check for prototype pollution keys\n    for (const key of Object.keys(obj)) {\n      if (key === '__proto__' || key === 'constructor' || key === 'prototype') {\n        findings.push(`Prototype pollution attempt via key: ${key}`);\n      }\n      findings.push(\n        ...detectInjectionPatterns(\n          (obj as Record<string, unknown>)[key],\n          toolName,\n          path ? `${path}.${key}` : key\n        )\n      );\n    }\n  }\n  return findings;\n}\n\n// Rate-limit housekeeping must not make a library import own process lifetime.\n// Active stdio/HTTP servers already keep the process alive while this runs.\nconst rateLimitCleanupTimer = setInterval(() => {\n  const cutoff = Date.now() - 120_000;\n  for (const [key, timestamps] of rateLimitWindows) {\n    const filtered = timestamps.filter((t) => t > cutoff);\n    if (filtered.length === 0) {\n      rateLimitWindows.delete(key);\n    } else {\n      rateLimitWindows.set(key, filtered);\n    }\n  }\n}, 60_000);\nrateLimitCleanupTimer.unref();\n\n// ── Gate 3: StdlibPolicy Enforcement ─────────────────────────────────────────\n\nexport interface Gate3Config {\n  /** Default policy for tools that access downstream resources */\n  defaultPolicy: StdlibPolicy;\n  /** Override policies per client ID */\n  clientPolicies: Map<string, Partial<StdlibPolicy>>;\n  /** Tools that require Gate 3 enforcement (filesystem, network, shell, GPU) */\n  enforcedTools: Set<string>;\n}\n\n/** Tools that interact with downstream resources and need Gate 3 */\nconst DOWNSTREAM_TOOLS = new Set([\n  // Browser control (external process)\n  'browser_launch',\n  'browser_execute',\n  'browser_screenshot',\n\n  // Codebase intelligence (filesystem)\n  'holo_absorb_repo',\n  'holo_detect_changes',\n\n  // Render (spawns processes)\n  'render_preview',\n  'holo_hologram_render',\n  'holo_hologram_publish_feed',\n  'holo_hologram_send',\n\n  // Self-improvement (daemon, filesystem, shell)\n  'holo_self_diagnose',\n  'holo_validate_quality',\n\n  // Edit (filesystem write)\n  'edit_holo',\n\n  // GLTF (filesystem I/O)\n  'import_gltf',\n  'compile_to_gltf',\n\n  // Absorb service (network, external API)\n  'absorb_run_absorb',\n  'absorb_run_improve',\n  'absorb_render',\n  'absorb_run_pipeline',\n\n  // HoloTest / Eval (spawns test runner / calls LLM judge)\n  'execute_holotest',\n  'execute_eval',\n\n  // Training data (generates large output)\n  'generate_hololand_training',\n\n  // 3D generation (external API: Meshy/Tripo)\n  'generate_3d_object',\n\n  // World generation (sovereign-3d pipeline — external inference)\n  'generate_world_from_prompt',\n  'generate_world',\n\n  // Networking (external connections)\n  'push_state_delta',\n  'fetch_authoritative_state',\n]);\n\n/** Default StdlibPolicy for MCP tool downstream access */\nconst DEFAULT_MCP_POLICY: StdlibPolicy = {\n  allowedPaths: ['compositions', 'data', 'src', 'packages', 'examples'],\n  maxFileBytes: 5 * 1024 * 1024, // 5MB for MCP\n  allowShell: false,\n  allowedShellCommands: [],\n  maxShellOutputBytes: 256 * 1024,\n  shellTimeoutMs: 30_000,\n  allowNetwork: true, // MCP server needs network for render/share/absorb\n  allowedHosts: [\n    'mcp.holoscript.net',\n    'api.meshy.ai',\n    'api.tripo3d.ai',\n    'holoscript.net',\n    'localhost',\n  ],\n  rootDir: '.',\n  allowMediaDecode: false,\n  allowDepthInference: false,\n  allowGpuCompute: false,\n  maxGifFrames: 200,\n  maxVideoDurationSec: 60,\n  maxMediaResolution: 2048,\n};\n\nexport interface Gate3Result {\n  passed: boolean;\n  reason?: string;\n  appliedPolicy?: StdlibPolicy;\n  enforcedRestrictions?: string[];\n}\n\n/**\n * Gate 3: Enforce StdlibPolicy for downstream resource access.\n *\n * Only applies to tools that interact with external resources\n * (filesystem, network, shell, GPU, external APIs).\n * Pure computation tools (parse, validate, etc.) pass through.\n */\nexport function gate3EnforcePolicy(\n  toolName: string,\n  args: Record<string, unknown>,\n  auth: TokenIntrospection,\n  config?: Partial<Gate3Config>\n): Gate3Result {\n  // Skip enforcement for tools that don't access downstream resources\n  const enforcedTools = config?.enforcedTools || DOWNSTREAM_TOOLS;\n  if (!enforcedTools.has(toolName)) {\n    return { passed: true };\n  }\n\n  const basePolicy = config?.defaultPolicy || DEFAULT_MCP_POLICY;\n  const clientOverrides = config?.clientPolicies?.get(auth.clientId || '') || {};\n  const policy: StdlibPolicy = { ...basePolicy, ...clientOverrides };\n\n  const restrictions: string[] = [];\n\n  // Check filesystem paths in arguments\n  const pathArgs = extractPathArgs(args);\n  for (const pathArg of pathArgs) {\n    const normalized = pathArg.replace(/\\\\/g, '/').replace(/^\\.\\//, '');\n    if (normalized.startsWith('..') || normalized.includes('/../')) {\n      return {\n        passed: false,\n        reason: `Path traversal blocked: \"${pathArg}\"`,\n        appliedPolicy: policy,\n      };\n    }\n\n    const allowed = policy.allowedPaths.some(\n      (root) => normalized === root || normalized.startsWith(`${root}/`)\n    );\n    if (!allowed && pathArgs.length > 0) {\n      restrictions.push(\n        `Path \"${normalized}\" restricted by policy (allowed: ${policy.allowedPaths.join(', ')})`\n      );\n    }\n  }\n\n  // Check network access\n  const urlArgs = extractUrlArgs(args);\n  if (urlArgs.length > 0 && !policy.allowNetwork) {\n    return {\n      passed: false,\n      reason: 'Network access denied by StdlibPolicy',\n      appliedPolicy: policy,\n    };\n  }\n\n  for (const url of urlArgs) {\n    try {\n      const hostname = new URL(url).hostname.toLowerCase();\n      if (policy.allowedHosts.length > 0 && !policy.allowedHosts.includes(hostname)) {\n        return {\n          passed: false,\n          reason: `Host \"${hostname}\" not in allowed hosts (${policy.allowedHosts.join(', ')})`,\n          appliedPolicy: policy,\n        };\n      }\n    } catch {\n      // Invalid URL — let downstream handler deal with it\n    }\n  }\n\n  // Check shell execution\n  if (toolName === 'browser_execute' || toolName === 'execute_holotest') {\n    if (!policy.allowShell) {\n      restrictions.push('Shell execution restricted by policy');\n    }\n  }\n\n  // Check GPU compute\n  if (args.useGpu || args.gpuCompute || args.useGpuCompute) {\n    if (!policy.allowGpuCompute) {\n      return {\n        passed: false,\n        reason: 'GPU compute access denied by StdlibPolicy',\n        appliedPolicy: policy,\n      };\n    }\n  }\n\n  // Check media decode permission\n  if (args.decodeMedia || args.mediaSource || args.gifSource) {\n    if (!policy.allowMediaDecode) {\n      return {\n        passed: false,\n        reason: 'Media decode access denied by StdlibPolicy (allowMediaDecode=false)',\n        appliedPolicy: policy,\n      };\n    }\n  }\n\n  // Check depth inference permission\n  if (args.runDepthInference || args.depthSource || args.estimateDepth) {\n    if (!policy.allowDepthInference) {\n      return {\n        passed: false,\n        reason: 'Depth inference access denied by StdlibPolicy (allowDepthInference=false)',\n        appliedPolicy: policy,\n      };\n    }\n  }\n\n  // Check media processing limits\n  if (args.duration && typeof args.duration === 'number') {\n    if (args.duration > (policy.maxVideoDurationSec || 300) * 1000) {\n      return {\n        passed: false,\n        reason: `Duration ${args.duration}ms exceeds policy limit (${(policy.maxVideoDurationSec || 300) * 1000}ms)`,\n        appliedPolicy: policy,\n      };\n    }\n  }\n\n  // Risk-based additional checks\n  const riskLevel = getToolRiskLevel(toolName);\n  if (riskLevel === 'critical' && auth.agentId === 'open-dev-mode') {\n    return {\n      passed: false,\n      reason: 'Critical-risk tools require authenticated access (not open-dev-mode)',\n      appliedPolicy: policy,\n    };\n  }\n\n  return {\n    passed: true,\n    appliedPolicy: policy,\n    enforcedRestrictions: restrictions.length > 0 ? restrictions : undefined,\n  };\n}\n\nfunction extractPathArgs(args: Record<string, unknown>): string[] {\n  const paths: string[] = [];\n  const pathKeys = [\n    'path',\n    'file',\n    'filePath',\n    'outputPath',\n    'holoscriptFile',\n    'directory',\n    'dir',\n    'output_file',\n  ];\n  for (const key of pathKeys) {\n    if (typeof args[key] === 'string') {\n      paths.push(args[key] as string);\n    }\n  }\n  return paths;\n}\n\nfunction extractUrlArgs(args: Record<string, unknown>): string[] {\n  const urls: string[] = [];\n  for (const [, val] of Object.entries(args)) {\n    if (typeof val === 'string' && (val.startsWith('http://') || val.startsWith('https://'))) {\n      urls.push(val);\n    }\n  }\n  return urls;\n}\n\n// ── Unified Triple-Gate Check ────────────────────────────────────────────────\n\nexport interface TripleGateResult {\n  passed: boolean;\n  gate: 0 | 1 | 2 | 3;\n  reason?: string;\n  gate1?: Gate1Result;\n  gate2?: {\n    authorized: boolean;\n    reason?: string;\n    requiredScopes?: string[];\n    grantedScopes?: string[];\n    riskLevel?: ToolRiskLevel;\n  };\n  gate3?: Gate3Result;\n  riskLevel?: ToolRiskLevel;\n}\n\n/**\n * Run all three gates in sequence. Returns on first failure.\n */\nexport function runTripleGate(\n  toolName: string,\n  args: Record<string, unknown>,\n  auth: TokenIntrospection,\n  gate1Config?: Gate1Config,\n  gate3Config?: Partial<Gate3Config>\n): TripleGateResult {\n  // Must be authenticated\n  if (!auth.active) {\n    return {\n      passed: false,\n      gate: 0,\n      reason: 'Authentication required',\n    };\n  }\n\n  // Gate 1: Prompt validation. Inline source upload can contain strings that\n  // look dangerous inside sourceFiles[*].content, but every other field still\n  // needs Gate 1.\n  const resolvedGate1Config: Gate1Config = gate1Config ?? DEFAULT_GATE1_CONFIG;\n  const g1 = gate1ValidateRequest(toolName, args, auth.clientId || 'unknown', resolvedGate1Config);\n  if (!g1.passed) {\n    return {\n      passed: false,\n      gate: 1,\n      reason: g1.reason,\n      gate1: g1,\n    };\n  }\n\n  // Gate 2: Tool authorization (scope check)\n  const g2 = authorizeToolCall(toolName, auth.scopes || []);\n  if (!g2.authorized) {\n    return {\n      passed: false,\n      gate: 2,\n      reason: g2.reason,\n      gate2: g2,\n      riskLevel: g2.riskLevel,\n    };\n  }\n\n  // Gate 3: StdlibPolicy enforcement\n  const g3 = gate3EnforcePolicy(toolName, args, auth, gate3Config);\n  if (!g3.passed) {\n    return {\n      passed: false,\n      gate: 3,\n      reason: g3.reason,\n      gate3: g3,\n      riskLevel: g2.riskLevel,\n    };\n  }\n\n  return {\n    passed: true,\n    gate: 3,\n    gate1: g1,\n    gate2: g2,\n    gate3: g3,\n    riskLevel: g2.riskLevel,\n  };\n}\n","/**\n * EU AI Act Compliant Audit Logging for HoloScript MCP Server\n *\n * Records all tool invocations with:\n * - ISO 8601 timestamp (UTC)\n * - Agent identity (OAuth 2.1 client ID + agent ID)\n * - Tool name and category\n * - Parameters (PII-redacted per GDPR/EU AI Act Art. 12-14)\n * - Result status (success, error, denied)\n * - Gate results (which of the triple gates passed/failed)\n * - Risk level classification\n * - Request duration\n *\n * EU AI Act Compliance (Articles 12-14):\n * - Art. 12: Automatic logging of AI system operations\n * - Art. 13: Transparency — logs are queryable and exportable\n * - Art. 14: Human oversight — high-risk operations flagged\n *\n * Logs are stored in-memory with configurable rotation and can be\n * exported to external systems (stdout JSON, file, webhook).\n */\n\nimport { randomUUID } from 'crypto';\nimport type { TokenIntrospection } from './oauth21';\nimport type { ToolRiskLevel } from './tool-scopes';\nimport type { TripleGateResult } from './gates';\n\n// ── Types ────────────────────────────────────────────────────────────────────\n\nexport type AuditEventType =\n  | 'tool_invocation'\n  | 'tool_result'\n  | 'auth_success'\n  | 'auth_failure'\n  | 'gate_denied'\n  | 'token_issued'\n  | 'token_revoked'\n  | 'client_registered'\n  | 'client_revoked'\n  | 'rate_limited'\n  | 'session_created'\n  | 'session_closed';\n\nexport type AuditResultStatus = 'success' | 'error' | 'denied' | 'rate_limited';\n\nexport interface AuditLogEntry {\n  /** Unique event ID */\n  id: string;\n  /** ISO 8601 timestamp in UTC */\n  timestamp: string;\n  /** Event type */\n  event: AuditEventType;\n  /** Agent identity */\n  agent: {\n    clientId?: string;\n    agentId?: string;\n    /** IP address (hashed for GDPR) */\n    ipHash?: string;\n    /** Session ID if applicable */\n    sessionId?: string;\n  };\n  /** Tool invocation details (for tool_invocation/tool_result events) */\n  tool?: {\n    name: string;\n    category?: string;\n    riskLevel?: ToolRiskLevel;\n    /** PII-redacted parameter summary */\n    paramSummary?: Record<string, string>;\n    /** Result status */\n    resultStatus?: AuditResultStatus;\n    /** Error message (if applicable, sanitized) */\n    errorMessage?: string;\n  };\n  /** Triple-gate security results */\n  security?: {\n    gate1Passed?: boolean;\n    gate2Passed?: boolean;\n    gate3Passed?: boolean;\n    deniedAtGate?: number;\n    deniedReason?: string;\n    requiredScopes?: string[];\n    grantedScopes?: string[];\n  };\n  /** Request metadata */\n  request?: {\n    /** HTTP method */\n    method?: string;\n    /** Request path */\n    path?: string;\n    /** Request duration in milliseconds */\n    durationMs?: number;\n    /** Request body size in bytes */\n    bodySize?: number;\n  };\n  /** Additional metadata */\n  metadata?: Record<string, unknown>;\n}\n\n// ── PII Redaction ────────────────────────────────────────────────────────────\n\n/** Fields that may contain PII and must be redacted */\nconst PII_FIELDS = new Set([\n  'email',\n  'name',\n  'username',\n  'password',\n  'secret',\n  'token',\n  'apiKey',\n  'api_key',\n  'authorization',\n  'cookie',\n  'session',\n  'phone',\n  'address',\n  'ssn',\n  'credit_card',\n  'ip',\n  'user_agent',\n  'clientSecret',\n  'client_secret',\n  'refresh_token',\n  'access_token',\n  'codeVerifier',\n  'code_verifier',\n  'code_challenge',\n]);\n\n/** Patterns that look like PII values */\nconst PII_PATTERNS = [\n  /\\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Z|a-z]{2,}\\b/, // email\n  /\\b\\d{3}[-.]?\\d{2}[-.]?\\d{4}\\b/, // SSN\n  /\\b(?:\\d{4}[-\\s]?){3}\\d{4}\\b/, // credit card\n  /\\b\\d{10,15}\\b/, // phone number\n];\n\n/**\n * Redact PII from tool arguments for safe audit logging.\n * Returns a summary map with field names and redacted type indicators.\n */\nexport function redactPII(args: Record<string, unknown>): Record<string, string> {\n  const summary: Record<string, string> = {};\n\n  for (const [key, value] of Object.entries(args)) {\n    if (PII_FIELDS.has(key.toLowerCase())) {\n      summary[key] = '[REDACTED]';\n      continue;\n    }\n\n    if (typeof value === 'string') {\n      // Check for PII patterns in value\n      let redacted = false;\n      for (const pattern of PII_PATTERNS) {\n        if (pattern.test(value)) {\n          summary[key] = `[REDACTED:${value.length} chars]`;\n          redacted = true;\n          break;\n        }\n      }\n      if (!redacted) {\n        // Truncate long strings for the summary\n        summary[key] =\n          value.length > 100 ? `${value.substring(0, 50)}...[${value.length} chars]` : value;\n      }\n    } else if (typeof value === 'number' || typeof value === 'boolean') {\n      summary[key] = String(value);\n    } else if (Array.isArray(value)) {\n      summary[key] = `[Array:${value.length} items]`;\n    } else if (value && typeof value === 'object') {\n      summary[key] = `[Object:${Object.keys(value).length} keys]`;\n    } else if (value === null || value === undefined) {\n      summary[key] = String(value);\n    } else {\n      summary[key] = '[unknown type]';\n    }\n  }\n\n  return summary;\n}\n\n/**\n * Hash an IP address for GDPR-compliant logging.\n * Uses a one-way hash so the IP can't be recovered.\n */\nfunction hashIP(ip: string): string {\n  const { createHash } = require('crypto');\n  return createHash('sha256')\n    .update(ip + 'holoscript-audit-salt')\n    .digest('hex')\n    .substring(0, 16);\n}\n\n// ── Tool Category Mapping ────────────────────────────────────────────────────\n\nfunction getToolCategory(toolName: string): string {\n  if (toolName.startsWith('parse_') || toolName.startsWith('validate_')) return 'parsing';\n  if (toolName.startsWith('generate_') || toolName.startsWith('suggest_')) return 'generation';\n  if (toolName.startsWith('compile_')) return 'compilation';\n  if (toolName.startsWith('holo_')) return 'codebase-intelligence';\n  if (toolName.startsWith('hs_ai_')) return 'ai-assistant';\n  if (toolName.startsWith('hs_')) return 'ide';\n  if (toolName.startsWith('browser_')) return 'browser-control';\n  if (toolName.startsWith('absorb_')) return 'absorb-service';\n  if (toolName === 'render_preview' || toolName === 'create_share_link') return 'rendering';\n  if (toolName === 'edit_holo' || toolName === 'convert_format') return 'editing';\n  return 'other';\n}\n\n// ── Audit Log Store ──────────────────────────────────────────────────────────\n\nexport interface AuditLogConfig {\n  /** Maximum entries to keep in memory. Default: 10000 */\n  maxEntries: number;\n  /** Log to stdout as JSON lines. Default: true */\n  stdoutJsonl: boolean;\n  /** Webhook URL to POST audit entries. Default: none */\n  webhookUrl?: string;\n  /** Whether to include full parameter summaries. Default: true */\n  includeParams: boolean;\n  /** Retention period in hours. Default: 168 (7 days) */\n  retentionHours: number;\n  /** Flag high-risk operations for human review. Default: true */\n  flagHighRisk: boolean;\n}\n\nconst DEFAULT_AUDIT_CONFIG: AuditLogConfig = {\n  maxEntries: 10_000,\n  stdoutJsonl: process.env.AUDIT_STDOUT !== 'false',\n  webhookUrl: process.env.AUDIT_WEBHOOK_URL,\n  includeParams: true,\n  retentionHours: 168,\n  flagHighRisk: true,\n};\n\nclass AuditLogger {\n  private entries: AuditLogEntry[] = [];\n  private config: AuditLogConfig;\n  private cleanupInterval: ReturnType<typeof setInterval> | null = null;\n\n  constructor(config: Partial<AuditLogConfig> = {}) {\n    this.config = { ...DEFAULT_AUDIT_CONFIG, ...config };\n    this.startCleanup();\n  }\n\n  // ── Core Logging ───────────────────────────────────────────────────────\n\n  private log(entry: AuditLogEntry): void {\n    this.entries.push(entry);\n\n    // Enforce max entries\n    while (this.entries.length > this.config.maxEntries) {\n      this.entries.shift();\n    }\n\n    // Output to stdout as JSONL\n    if (this.config.stdoutJsonl) {\n      const _line = JSON.stringify({\n        ...entry,\n        _audit: true,\n        _version: '1.0.0',\n        _compliance: 'eu-ai-act',\n      });\n    }\n\n    // Send to webhook (fire-and-forget)\n    if (this.config.webhookUrl) {\n      this.sendToWebhook(entry).catch(() => {\n        // Webhook failure should never block operations\n      });\n    }\n  }\n\n  // ── Convenience Methods ────────────────────────────────────────────────\n\n  /**\n   * Log a tool invocation (before execution).\n   */\n  logToolInvocation(params: {\n    toolName: string;\n    args: Record<string, unknown>;\n    auth: TokenIntrospection;\n    gateResult: TripleGateResult;\n    requestPath?: string;\n    requestMethod?: string;\n    ip?: string;\n    sessionId?: string;\n  }): string {\n    const id = randomUUID();\n    const entry: AuditLogEntry = {\n      id,\n      timestamp: new Date().toISOString(),\n      event: params.gateResult.passed ? 'tool_invocation' : 'gate_denied',\n      agent: {\n        clientId: params.auth.clientId,\n        agentId: params.auth.agentId,\n        ipHash: params.ip ? hashIP(params.ip) : undefined,\n        sessionId: params.sessionId,\n      },\n      tool: {\n        name: params.toolName,\n        category: getToolCategory(params.toolName),\n        riskLevel: params.gateResult.riskLevel,\n        paramSummary: this.config.includeParams ? redactPII(params.args) : undefined,\n        resultStatus: params.gateResult.passed ? undefined : 'denied',\n      },\n      security: {\n        gate1Passed: params.gateResult.gate1?.passed,\n        gate2Passed: params.gateResult.gate2?.authorized,\n        gate3Passed: params.gateResult.gate3?.passed,\n        deniedAtGate: params.gateResult.passed ? undefined : params.gateResult.gate,\n        deniedReason: params.gateResult.reason,\n        requiredScopes: params.gateResult.gate2?.requiredScopes as string[] | undefined,\n        grantedScopes: params.auth.scopes,\n      },\n      request: {\n        method: params.requestMethod,\n        path: params.requestPath,\n      },\n    };\n\n    // Flag high-risk operations for human review (EU AI Act Art. 14)\n    if (this.config.flagHighRisk && params.gateResult.riskLevel === 'critical') {\n      entry.metadata = {\n        ...entry.metadata,\n        humanReviewRequired: true,\n        riskJustification: 'Critical-risk tool invocation per EU AI Act Art. 14',\n      };\n    }\n\n    this.log(entry);\n    return id;\n  }\n\n  /**\n   * Log a tool result (after execution).\n   */\n  logToolResult(params: {\n    invocationId: string;\n    toolName: string;\n    status: AuditResultStatus;\n    durationMs: number;\n    errorMessage?: string;\n    auth: TokenIntrospection;\n    sessionId?: string;\n  }): void {\n    this.log({\n      id: randomUUID(),\n      timestamp: new Date().toISOString(),\n      event: 'tool_result',\n      agent: {\n        clientId: params.auth.clientId,\n        agentId: params.auth.agentId,\n        sessionId: params.sessionId,\n      },\n      tool: {\n        name: params.toolName,\n        category: getToolCategory(params.toolName),\n        resultStatus: params.status,\n        errorMessage: params.errorMessage\n          ? params.errorMessage.substring(0, 500) // Truncate error messages\n          : undefined,\n      },\n      request: {\n        durationMs: params.durationMs,\n      },\n      metadata: {\n        invocationId: params.invocationId,\n      },\n    });\n  }\n\n  /**\n   * Log authentication events.\n   */\n  logAuthEvent(params: {\n    event:\n      | 'auth_success'\n      | 'auth_failure'\n      | 'token_issued'\n      | 'token_revoked'\n      | 'client_registered'\n      | 'client_revoked'\n      | 'rate_limited';\n    clientId?: string;\n    agentId?: string;\n    ip?: string;\n    reason?: string;\n  }): void {\n    this.log({\n      id: randomUUID(),\n      timestamp: new Date().toISOString(),\n      event: params.event,\n      agent: {\n        clientId: params.clientId,\n        agentId: params.agentId,\n        ipHash: params.ip ? hashIP(params.ip) : undefined,\n      },\n      metadata: params.reason ? { reason: params.reason } : undefined,\n    });\n  }\n\n  /**\n   * Log session lifecycle events.\n   */\n  logSessionEvent(params: {\n    event: 'session_created' | 'session_closed';\n    sessionId: string;\n    clientId?: string;\n  }): void {\n    this.log({\n      id: randomUUID(),\n      timestamp: new Date().toISOString(),\n      event: params.event,\n      agent: {\n        clientId: params.clientId,\n        sessionId: params.sessionId,\n      },\n    });\n  }\n\n  // ── Querying (EU AI Act Art. 13: Transparency) ─────────────────────────\n\n  /**\n   * Query audit logs with filters.\n   */\n  query(filters: {\n    event?: AuditEventType;\n    clientId?: string;\n    agentId?: string;\n    toolName?: string;\n    status?: AuditResultStatus;\n    riskLevel?: ToolRiskLevel;\n    since?: string; // ISO 8601\n    until?: string; // ISO 8601\n    limit?: number;\n    offset?: number;\n    humanReviewOnly?: boolean;\n  }): { entries: AuditLogEntry[]; total: number } {\n    let results = this.entries;\n\n    if (filters.event) {\n      results = results.filter((e) => e.event === filters.event);\n    }\n    if (filters.clientId) {\n      results = results.filter((e) => e.agent.clientId === filters.clientId);\n    }\n    if (filters.agentId) {\n      results = results.filter((e) => e.agent.agentId === filters.agentId);\n    }\n    if (filters.toolName) {\n      results = results.filter((e) => e.tool?.name === filters.toolName);\n    }\n    if (filters.status) {\n      results = results.filter((e) => e.tool?.resultStatus === filters.status);\n    }\n    if (filters.riskLevel) {\n      results = results.filter((e) => e.tool?.riskLevel === filters.riskLevel);\n    }\n    if (filters.since) {\n      results = results.filter((e) => e.timestamp >= filters.since!);\n    }\n    if (filters.until) {\n      results = results.filter((e) => e.timestamp <= filters.until!);\n    }\n    if (filters.humanReviewOnly) {\n      results = results.filter(\n        (e) => e.metadata && (e.metadata as Record<string, unknown>).humanReviewRequired === true\n      );\n    }\n\n    const total = results.length;\n    const offset = filters.offset || 0;\n    const limit = filters.limit || 100;\n\n    return {\n      entries: results.slice(offset, offset + limit),\n      total,\n    };\n  }\n\n  /**\n   * Export audit log as JSON (EU AI Act Art. 13: transparency export).\n   */\n  export(format: 'json' | 'jsonl' = 'json'): string {\n    if (format === 'jsonl') {\n      return this.entries.map((e) => JSON.stringify(e)).join('\\n');\n    }\n    return JSON.stringify(\n      {\n        exportedAt: new Date().toISOString(),\n        compliance: 'eu-ai-act-articles-12-14',\n        version: '1.0.0',\n        total: this.entries.length,\n        entries: this.entries,\n      },\n      null,\n      2\n    );\n  }\n\n  /**\n   * Get compliance summary statistics.\n   */\n  getComplianceStats(): Record<string, unknown> {\n    const now = Date.now();\n    const last24h = new Date(now - 86_400_000).toISOString();\n    const last7d = new Date(now - 7 * 86_400_000).toISOString();\n\n    const recent24h = this.entries.filter((e) => e.timestamp >= last24h);\n    const recent7d = this.entries.filter((e) => e.timestamp >= last7d);\n\n    const denials24h = recent24h.filter((e) => e.event === 'gate_denied');\n    const highRisk24h = recent24h.filter((e) => e.tool?.riskLevel === 'critical');\n    const humanReview = recent24h.filter(\n      (e) => e.metadata && (e.metadata as Record<string, unknown>).humanReviewRequired === true\n    );\n\n    return {\n      compliance: 'eu-ai-act-articles-12-14',\n      reporting_period: {\n        last24h: {\n          totalEvents: recent24h.length,\n          toolInvocations: recent24h.filter((e) => e.event === 'tool_invocation').length,\n          denials: denials24h.length,\n          highRiskOperations: highRisk24h.length,\n          pendingHumanReview: humanReview.length,\n          authFailures: recent24h.filter((e) => e.event === 'auth_failure').length,\n        },\n        last7d: {\n          totalEvents: recent7d.length,\n          uniqueClients: new Set(recent7d.map((e) => e.agent.clientId).filter(Boolean)).size,\n          uniqueTools: new Set(recent7d.filter((e) => e.tool).map((e) => e.tool!.name)).size,\n        },\n      },\n      retentionPolicy: {\n        maxEntries: this.config.maxEntries,\n        retentionHours: this.config.retentionHours,\n        currentEntries: this.entries.length,\n      },\n    };\n  }\n\n  // ── Internal ───────────────────────────────────────────────────────────\n\n  private async sendToWebhook(entry: AuditLogEntry): Promise<void> {\n    if (!this.config.webhookUrl) return;\n    try {\n      await fetch(this.config.webhookUrl, {\n        method: 'POST',\n        headers: { 'Content-Type': 'application/json; charset=utf-8' },\n        body: JSON.stringify(entry),\n        signal: AbortSignal.timeout(5000),\n      });\n    } catch {\n      // Silent failure — audit webhook should never block\n    }\n  }\n\n  private startCleanup(): void {\n    if (this.cleanupInterval) return;\n    this.cleanupInterval = setInterval(() => {\n      const cutoff = new Date(Date.now() - this.config.retentionHours * 3_600_000).toISOString();\n      this.entries = this.entries.filter((e) => e.timestamp >= cutoff);\n    }, 3_600_000); // Clean up every hour\n  }\n\n  /** Stop cleanup timer (for tests) */\n  destroy(): void {\n    if (this.cleanupInterval) {\n      clearInterval(this.cleanupInterval);\n      this.cleanupInterval = null;\n    }\n  }\n}\n\n// ── Singleton ────────────────────────────────────────────────────────────────\n\nlet _auditLogger: AuditLogger | null = null;\n\nexport function getAuditLogger(config?: Partial<AuditLogConfig>): AuditLogger {\n  if (!_auditLogger) {\n    _auditLogger = new AuditLogger(config);\n  }\n  return _auditLogger;\n}\n\nexport function resetAuditLogger(): void {\n  _auditLogger?.destroy();\n  _auditLogger = null;\n}\n","/**\n * Heuristic rate-limit bypass / evasion detection (P.009.02).\n *\n * - Many distinct client IPs from the same IPv4 /24 calling the same tool within a short window.\n * - Many distinct bearer tokens from the same direct client IP (rapid key rotation).\n * - Suspicious X-Forwarded-For chains (possible spoofing).\n *\n * Optional env:\n * - BYPASS_DETECTION_ENABLED — set to \"false\" to disable (default: on).\n * - BYPASS_SUBNET_IP_THRESHOLD — default 10 (unique IPs per /24 per tool per minute).\n * - BYPASS_TOKEN_DIVERSITY_THRESHOLD — default 12 distinct tokens per IP per 5 minutes.\n * - BYPASS_BLOCK_SUBNET_MS — default 3_600_000 (1h).\n * - BYPASS_BLOCK_IP_MS — default 3_600_000 (1h) for token-rotation / XFF abuse.\n * - SLACK_SECURITY_WEBHOOK_URL — incoming webhook for alerts (optional).\n */\n\nimport { createHash } from 'crypto';\nimport type http from 'http';\n\nconst TOOL_WINDOW_MS = 60_000;\nconst TOKEN_WINDOW_MS = 300_000;\n\nfunction enabled(): boolean {\n  return process.env.BYPASS_DETECTION_ENABLED !== 'false';\n}\n\nfunction subnetThreshold(): number {\n  const n = parseInt(process.env.BYPASS_SUBNET_IP_THRESHOLD || '10', 10);\n  return Number.isFinite(n) && n >= 2 ? n : 10;\n}\n\nfunction tokenThreshold(): number {\n  const n = parseInt(process.env.BYPASS_TOKEN_DIVERSITY_THRESHOLD || '12', 10);\n  return Number.isFinite(n) && n >= 4 ? n : 12;\n}\n\nfunction subnetBlockMs(): number {\n  const n = parseInt(process.env.BYPASS_BLOCK_SUBNET_MS || String(3_600_000), 10);\n  return Number.isFinite(n) && n > 0 ? n : 3_600_000;\n}\n\nfunction ipBlockMs(): number {\n  const n = parseInt(process.env.BYPASS_BLOCK_IP_MS || String(3_600_000), 10);\n  return Number.isFinite(n) && n > 0 ? n : 3_600_000;\n}\n\n/** subnet /24 -> unblock at */\nconst blockedSubnets = new Map<string, number>();\n/** direct IP -> unblock at */\nconst blockedIps = new Map<string, number>();\n\n/** key: `${tool}:${subnet}` -> ip -> last seen ms */\nconst toolSubnetIps = new Map<string, Map<string, number>>();\n/** key: directIp -> tokenHash -> last seen ms */\nconst ipTokens = new Map<string, Map<string, number>>();\n\nexport function ipv4Subnet24(ip: string): string | null {\n  const m = ip.trim().match(/^(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.\\d{1,3}$/);\n  if (!m) return null;\n  const a = Number(m[1]);\n  const b = Number(m[2]);\n  const c = Number(m[3]);\n  if ([a, b, c].some((x) => x > 255)) return null;\n  return `${a}.${b}.${c}.0/24`;\n}\n\nfunction isPrivateIPv4(ip: string): boolean {\n  const m = ip.trim().match(/^(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})$/);\n  if (!m) return false;\n  const [a, b] = [Number(m[1]), Number(m[2])];\n  if (a === 10) return true;\n  if (a === 172 && b >= 16 && b <= 31) return true;\n  if (a === 192 && b === 168) return true;\n  if (a === 127) return true;\n  return false;\n}\n\n/**\n * Detect implausible XFF chains (spoofing / pen-test noise).\n * `tcpPeer` is the raw remote socket address (optional); compared to claimed client chain.\n */\nexport function analyzeXForwardedFor(\n  xff: string | undefined,\n  tcpPeer?: string\n): { suspicious: boolean; reason?: string } {\n  if (!xff || !xff.trim()) return { suspicious: false };\n  const hops = xff\n    .split(',')\n    .map((s) => s.trim())\n    .filter(Boolean);\n  if (hops.length > 6) {\n    return { suspicious: true, reason: `xff_hop_count_${hops.length}` };\n  }\n  const left = hops[0];\n  const peer = tcpPeer?.replace(/^::ffff:/, '') || '';\n  if (peer && left && /^[\\d.]+$/.test(left) && isPrivateIPv4(left) && !isPrivateIPv4(peer)) {\n    return { suspicious: true, reason: 'xff_private_left_public_peer' };\n  }\n  const uniq = new Set(hops);\n  if (hops.length >= 4 && uniq.size < hops.length - 1) {\n    return { suspicious: true, reason: 'xff_duplicate_hops' };\n  }\n  return { suspicious: false };\n}\n\nfunction tokenFingerprint(raw: string): string {\n  return createHash('sha256').update(raw).digest('hex').slice(0, 20);\n}\n\nfunction pruneMap(m: Map<string, number>, cutoff: number): void {\n  for (const [k, t] of m) {\n    if (t < cutoff) m.delete(k);\n  }\n}\n\nfunction nowBlockReason(ip: string): string | undefined {\n  const t = blockedIps.get(ip);\n  if (t && t > Date.now()) return 'direct_ip_blocked';\n  const sub = ipv4Subnet24(ip);\n  if (sub) {\n    const u = blockedSubnets.get(sub);\n    if (u && u > Date.now()) return 'subnet_blocked';\n  }\n  return undefined;\n}\n\nasync function slackAlert(text: string): Promise<void> {\n  const url = process.env.SLACK_SECURITY_WEBHOOK_URL?.trim();\n  if (!url) return;\n  try {\n    await fetch(url, {\n      method: 'POST',\n      headers: { 'Content-Type': 'application/json; charset=utf-8' },\n      body: JSON.stringify({ text: `[HoloScript MCP] ${text}` }),\n    });\n  } catch {\n    /* ignore */\n  }\n}\n\nexport interface BypassCheckInput {\n  toolName: string;\n  /** Trusted client IP (e.g. first hop from proxy) */\n  directIp?: string;\n  /** Raw TCP peer (for XFF spoof heuristics) */\n  tcpPeerIp?: string;\n  rawXForwardedFor?: string;\n  bearerToken?: string;\n}\n\nexport interface BypassCheckResult {\n  allowed: boolean;\n  reason?: string;\n}\n\n/**\n * Apply heuristics for this tool call. When blocked, callers should deny before gates.\n */\nexport async function checkRateLimitBypass(input: BypassCheckInput): Promise<BypassCheckResult> {\n  if (!enabled()) return { allowed: true };\n\n  const ip = input.directIp?.trim();\n  if (!ip || ip === 'unknown') return { allowed: true };\n\n  const existing = nowBlockReason(ip);\n  if (existing) return { allowed: false, reason: existing };\n\n  const xff = analyzeXForwardedFor(input.rawXForwardedFor, input.tcpPeerIp);\n  if (xff.suspicious) {\n    const until = Date.now() + ipBlockMs();\n    blockedIps.set(ip, until);\n    await slackAlert(`XFF anomaly (${xff.reason}) directIp=${ip} tool=${input.toolName}`);\n    return { allowed: false, reason: `xff_suspicious:${xff.reason}` };\n  }\n\n  const subnet = ipv4Subnet24(ip);\n  if (subnet) {\n    const key = `${input.toolName}:${subnet}`;\n    let m = toolSubnetIps.get(key);\n    const t = Date.now();\n    if (!m) {\n      m = new Map();\n      toolSubnetIps.set(key, m);\n    }\n    m.set(ip, t);\n    pruneMap(m, t - TOOL_WINDOW_MS);\n    if (m.size > subnetThreshold()) {\n      const until = Date.now() + subnetBlockMs();\n      blockedSubnets.set(subnet, until);\n      await slackAlert(\n        `Subnet flood: ${m.size} unique IPs in ${subnet} for tool ${input.toolName} (blocked ${Math.round(subnetBlockMs() / 60000)}m)`\n      );\n      return { allowed: false, reason: 'subnet_rate_bypass_suspected' };\n    }\n  }\n\n  if (input.bearerToken && input.bearerToken.length > 8) {\n    const fp = tokenFingerprint(input.bearerToken);\n    const t = Date.now();\n    let tm = ipTokens.get(ip);\n    if (!tm) {\n      tm = new Map();\n      ipTokens.set(ip, tm);\n    }\n    tm.set(fp, t);\n    pruneMap(tm, t - TOKEN_WINDOW_MS);\n    if (tm.size > tokenThreshold()) {\n      const until = Date.now() + ipBlockMs();\n      blockedIps.set(ip, until);\n      await slackAlert(\n        `Token rotation burst: ${tm.size} distinct tokens from ${ip} in 5m (blocked)`\n      );\n      return { allowed: false, reason: 'token_rotation_burst' };\n    }\n  }\n\n  return { allowed: true };\n}\n\n/** Extract Bearer token from request without logging it. */\nexport function readBearerToken(req: http.IncomingMessage): string | undefined {\n  const a = req.headers.authorization;\n  if (typeof a !== 'string' || !a.startsWith('Bearer ')) return undefined;\n  const t = a.slice(7).trim();\n  return t || undefined;\n}\n\nexport function readXForwardedFor(req: http.IncomingMessage): string | undefined {\n  const x = req.headers['x-forwarded-for'];\n  return typeof x === 'string' ? x : Array.isArray(x) ? x[0] : undefined;\n}\n\n/** @internal */\nexport function resetBypassDetectionForTests(): void {\n  blockedSubnets.clear();\n  blockedIps.clear();\n  toolSubnetIps.clear();\n  ipTokens.clear();\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AACA,OAAO,UAAU;AACjB,SAAS,qBAAqB;AAF9B,IAIM,aACA,YAEO;AAPb;AAAA;AAAA;AAIA,IAAM,cAAc,MAAM,cAAc,YAAY,GAAG;AACvD,IAAM,aAAa,MAAM,KAAK,QAAQ,YAAY,CAAC;AAE5C,IAAM,YAA4B,2BAAW;AAAA;AAAA;;;ACFpD,SAAS,kBAAkB,iBAAiB;AAG5C,SAAS,UAAAA,eAAc;AAoBvB,SAAS,OAAO,GAAmB;AACjC,QAAM,IAAI,KAAK,MAAM,IAAI,GAAM,IAAI;AACnC,MAAI,OAAO,UAAU,CAAC,EAAG,QAAO,OAAO,CAAC;AACxC,SAAO,OAAO,CAAC;AACjB;AAEO,SAAS,iCAAiC,KAA2B;AAC1E,QAAM,MAAM,IAAI,KAAK,EAAE,YAAY;AACnC,MAAI,eAAe,GAAG,EAAG,QAAO,eAAe,GAAG;AAElD,mBAAiB,EAAE,qBAAqB,MAAM,CAAC;AAC/C,QAAM,YAAY,iBAAiB,EAAE,oBAAoB;AACzD,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AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAMA;AAIA,IAAM,4BAAsD;AAAA,MAC1D,aAAa;AAAA,QACX;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,MACF;AAAA,MACA,SAAS;AAAA,QACP;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,MACF;AAAA,MACA,QAAQ;AAAA,QACN;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,MACF;AAAA,MACA,YAAY;AAAA,QACV;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,MACF;AAAA,MACA,UAAU;AAAA,QACR;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,MACF;AAAA,MACA,SAAS;AAAA,QACP;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,MACF;AAAA,MACA,OAAO;AAAA,QACL;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,MACF;AAAA,MACA,OAAO;AAAA,QACL;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,MACF;AAAA,MACA,IAAI;AAAA,QACF;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,MACF;AAAA,MACA,eAAe;AAAA,QACb;AAAA,QACA;AAAA,QACA;AAAA,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QAAQ,SAAS;AAC9B,UAAQ,MAAM,wCAAwC;AACxD;AAGA,IACE,QAAQ,IAAI,oBAAoB,UAChC,QAAQ,KAAK;AAAA,EACX,CAAC,QAAQ,IAAI,SAAS,YAAY,MAAM,IAAI,SAAS,UAAU,KAAK,IAAI,SAAS,UAAU;AAC7F,GACA;AACA,OAAK,EAAE,MAAM,QAAQ,KAAK;AAC5B;","names":["Buffer","z","fileURLToPath","createHash","f","f","fs","path","f","adapter","parseHolo","fs","path","f","handleGraphRagTool","parseHolo","fs","path","z","allTraits","fs","path","status","parseHolo","allTraits","createHash","fs","path","enabled","cached","result","isDryRun","crypto","canonical","json","crypto","promisify","canonical","AgentRole","AgentPermission","WorkflowStep","crypto","crypto","cached","crypto","fs","os","path","asRecord","tools","perm","getDefaultRegistry","otelSpans","registry","buildDomainSimulationReceipt","registerPluginTraits","solveOntoNode","init_runtime","buildDomainSimulationReceipt","registerPluginTraits","solveOntoNode","init_runtime","init_runtime","readdirSync","readFileSync","existsSync","dirname","join","resolve","fileURLToPath","tools","__dirname","registry","z","fs","path","crypto","f","tools","existsSync","readFileSync","readdirSync","writeFileSync","join","resolve","relative","dirname","path","candidates","memberName","parseHolo","stripCodeFences","path","adapter","interactiveLine","traits","code","randomUUID","scene","cached","chromium","playgroundUrl","embedUrl","createHash","createHash","createHash","search","resolver","existsSync","chromium","createHash","z","z","path","status","fs","os","path","fs","path","os","search","f","z","createHash","randomUUID","createHash","anchorSettlement","json","negotiations","spawn","createHash","fs","tmpdir","isAbsolute","join","resolve","chromium","tileWidth","tileHeight","createHash","status","resolve","server","path","json","fs","os","path","isAbsolute","resolve","handleNetworkingTool","createHash","parseHolo","QuiltCompiler","sessions","createHash","stringArg","numberArg","stringArrayArg","hashPayload","status","TOOL_NAMES","existsSync","readFileSync","readdirSync","statSync","homedir","basename","join","resolve","window","path","isRecord","fs","path","createProviderManager","getAIProviderOrder","AI_PROVIDER_PRIORITY","f","fs","path","os","queryKnowledgeStore","search","fs","path","os","Pool","r","fs","path","os","createProviderManager","getAIProviderOrder","AI_PROVIDER_PRIORITY","BUILTIN_TARGETS","tryCompleteWithAI","normalizeVerdict","heuristicParse","existsSync","readdirSync","readFileSync","dirname","join","fileURLToPath","__dirname","optionalString","recordProtocolCreatorRevenue","f","registry","existsSync","readFileSync","createHash","join","dirname","fileURLToPath","HoloScriptPlusParser","__dirname","canonical","randomUUID","lease","built","existsSync","mkdirSync","readFileSync","writeFileSync","homedir","dirname","resolve","path","status","crypto","handleTool","init_postgres_pool_options","Pool","init_postgres_pool_options","Pool","SCHEMA_SQL","init_postgres_pool_options","Pool","SCHEMA_SQL","_a","init_postgres_pool_options","crypto","Pool","SCHEMA_SQL","init_postgres_pool_options","Pool","SCHEMA_SQL","_a","init_postgres_pool_options","fs","path","buildContentPolicyConfig","evaluateContentPolicySync","z","f","f","validateShard","validateZone","LOCAL_DEFAULT_MODEL","buildContentPolicyConfig","evaluateContentPolicySync","toAuditEventInput","stringArg","evaluateAutonomyGuard","runHololandForkAdmissionGate","genId","isPlainRecord","handleHoloMapTool","generateWorldFromPrompt","generateWorldNative","status","z","runAdmissionGate","canonical","simpleHash","createHash","enabled","join","getConformanceRules","getSimulation","_Simulation","canonical","asRecord","asString","z","f","solveLinearSystem","exec","path","fs","handleSimulationTool","status","fs","isRecord","crypto","isRecord","asString","asStringArray","search","path","LoroDoc","fs","path","RECONSOLIDATION_WINDOW_MS","json","window","randomUUID","randomUUID","getUnreadCount","randomUUID","clients","status","getApiKey","status","fs","path","axios","tools","clampNumber","stringOrUndefined","stringArray","isRecord","submolt","status","axios","z","crypto","handleDiscover","handleCollect","search","tools","orchestratorUrl","postBody","built","provenanceHash","KNOWLEDGE_DOMAINS","crypto","fs","os","path","ensureDir","hot","rejected","createHash","canonical","createHash","canonical","stringArray","resolve","createX402SettlementAdapterFromEnv","fs","path","GLB_HEADER_SIZE","GLB_MAGIC","GLB_VERSION","GLB_CHUNK_HEADER_SIZE","GLB_CHUNK_JSON","rgbToHex","quaternionToEulerDeg","z","formatVec3","inferTraits","materialToTraits","getAnimationClipsForNode","extractPhysicsParams","nodeToHolo","allTraits","buildHoloComposition","suggestTraits","adapter","fs","path","sanitizeName","suggestTraits","resolve","HoloScriptPlusParser","parseHolo","parseHoloStrict","VR_TRAITS","handleCodebaseTool","handleProtocolTool","handleSecretsBrokerTool","handleObservabilityTool","handleWorldRenderTool","handleHololandMcpTool","handleServiceContractTool","handleFairnessTool","handleValidationTool","handleCodeHealthTool","handleSimulationTool","handleSimulationBillingTool","handleAgentOrchestrationTool","handleAgentIdentityTool","handlePluginManagementTool","handleEconomyTool","handleDeveloperTool","handleHoloMeshTool","handleTraitTool","handleRigMatchSkeleton","holoshellDownloadRecoveryTools","detectFormat","canonical","allTraits","escapeHoloString","MeshyProvider","TripoProvider","textTo3DToHolo","writeFileSync","resolve","resolve","tools","existsSync","readdirSync","readFileSync","statSync","join","extname","WorkspaceManager","getTelemetryCollector","handleEconomyTool","handleTool","fs","createHash","resolveOrchestratorKey","ORCHESTRATOR_KEY_NAMES","orchestratorUrl","WINDOW_MS","built","role","allTraits","fs","path","fs","os","path","orchestratorUrl","createHash","parseHolo","getExportManager","TraitCompositionCompiler","isRecord","status","output","fs","os","path","HOLO_DIR","parseHolo","HoloScriptPlusParser","createProviderManager","sign","passed","status","extractArrayProp","fs","path","handleGraphRagTool","f","optionalString","os","path","ConsolidationEngine","store","createHash","existsSync","homedir","tmpdir","join","resolve","promisify","stringArg","recordArg","hashPayload","parseJsonRecord","isDryRun","registry","path","status","launch","resolved","res","payload","TOOL_NAMES","pgPool","Pool","cached","codebaseTools","graphRagTools","absorbServiceTools","handleCodebaseTool","handleGraphRagTool","path","fs","exec","promisify","execAsync","errMsg","fs","path","os","DATA_ROOT","pgPool","pgReady","maybeInitPg","Pool","pgAppend","dirEnsured","ensureDir","buildNormalizedRows","buildNormalizedRows","ensureDir","sessions","fs","path","os","createHash","fs","path","os","isRecord","DATA_ROOT","status","fs","path","parseHolo","TEAM_AGENT_PROFILES","allTraits","randomUUID","TERMINAL_STATES","TERMINAL_STATES","randomUUID","randomUUID","createHash","timingSafeEqual","createHash","randomUUID","timingSafeEqual","validateTenantKey","resolveGitHubTokenForMcp","path","randomUUID","createHash","AuditLogger","createHash","tokenFingerprint","absorbServiceTools","codebaseTools","handleCodebaseTool","graphRagTools","handleGraphRagTool","result"]}