@productbrain/mcp 0.0.1-beta.205 → 0.0.1-beta.206
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/auth.ts","../src/client.ts","../src/server.ts","../src/tools/knowledge.ts","../src/tools/smart-capture.ts","../src/tools/knowledge-helpers.ts","../src/tool-surface.ts","../src/gap-store.ts","../src/lib/resolveCollection.ts","../src/envelope.ts","../src/errors.ts","../src/lib/fieldTypes.ts","../src/lib/formatFieldGuidance.ts","../src/lib/inferSourceDate.ts","../src/lib/collectionCache.ts","../src/tools/conflict-preflight.ts","../src/tools/entries.ts","../src/tools/graph.ts","../src/tools/relations.ts","../src/tools/context.ts","../src/tools/collections.ts","../src/tools/labels.ts","../src/tools/health.ts","../src/tools/session.ts","../src/tools/wrapup.ts","../src/lib/coherence/data.ts","../src/lib/coherence/engine.ts","../src/lib/coherence/resolver.ts","../src/lib/coherence/git-detection.ts","../src/lib/coherence/index.ts","../src/lib/resolve-project-root.ts","../src/tools/quality.ts","../src/tools/workflows.ts","../src/workflows/descriptor.ts","../src/workflows/definitions.ts","../src/lib/workflowRun.ts","../src/tools/facilitate.ts","../src/tools/verify.ts","../src/tools/start_pb.ts","../src/tools/skills.ts","../src/tools/planned-work.ts","../src/lib/coherence/doc-completeness.ts","../src/tools/orient-shared.ts","../src/lib/gapToPrompt.ts","../src/tools/usage.ts","../src/tools/gitchain.ts","../src/lib/versionDisplay.ts","../src/tools/maps.ts","../src/tools/architecture.ts","../src/tools/orient.ts","../src/tools/record_activation.ts","../src/tools/audit.ts","../src/tools/governance.ts","../src/tools/documents.ts","../src/resources/index.ts","../src/prompts/index.ts","../src/flags.ts","../src/featureFlags.ts"],"sourcesContent":["/**\n * Request-scoped auth for HTTP transport mode.\n *\n * stdio: API key from PRODUCTBRAIN_API_KEY env, one user per process.\n * http: API key from Bearer header per request, many users per process.\n *\n * AsyncLocalStorage propagates the token through the async call chain\n * so client.ts resolves the correct API key and state per request.\n */\n\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport { createHash } from \"node:crypto\";\n\n// ── Key Hashing (Fix 3 — session binding) ───────────────────────────────\n\n/**\n * Short one-way hash of an API key used to bind MCP sessions to a specific key.\n * Not a secret — stored in the session entry to detect session hijacking.\n */\nexport function hashKey(key: string): string {\n return createHash(\"sha256\").update(key).digest(\"hex\").slice(0, 16);\n}\n\n// ── Request Context ─────────────────────────────────────────────────────\n\ninterface RequestAuth {\n apiKey: string;\n}\n\nconst requestStore = new AsyncLocalStorage<RequestAuth>();\n\nexport function runWithAuth<T>(auth: RequestAuth, fn: () => T | Promise<T>): T | Promise<T> {\n return requestStore.run(auth, fn);\n}\n\nexport function getRequestApiKey(): string | undefined {\n return requestStore.getStore()?.apiKey;\n}\n\n// ── Per-Key State (HTTP mode) ───────────────────────────────────────────\n\nexport interface KeyState {\n workspaceId: string | null;\n workspaceSlug: string | null;\n workspaceName: string | null;\n workspaceCreatedAt: number | null;\n /** BET-76 FEAT-111: Cached at workspace resolution time. Defaults to 'open'. */\n workspaceGovernanceMode: \"open\" | \"consensus\" | \"role\" | null;\n agentSessionId: string | null;\n apiKeyId: string | null;\n apiKeyScope: \"read\" | \"readwrite\";\n sessionOriented: boolean;\n sessionClosed: boolean;\n lastAccess: number;\n /** DEC-789 S2: Convex deployment URL this key belongs to, resolved at key-check time. */\n deploymentUrl: string | null;\n}\n\nconst SESSION_TTL_MS = 30 * 60 * 1000;\nconst MAX_KEYS = 100;\nconst keyStateMap = new Map<string, KeyState>();\n\nfunction newKeyState(): KeyState {\n return {\n workspaceId: null,\n workspaceSlug: null,\n workspaceName: null,\n workspaceCreatedAt: null,\n workspaceGovernanceMode: null,\n agentSessionId: null,\n apiKeyId: null,\n apiKeyScope: \"readwrite\",\n sessionOriented: false,\n sessionClosed: false,\n lastAccess: Date.now(),\n deploymentUrl: null,\n };\n}\n\nexport function getKeyState(apiKey: string): KeyState {\n let s = keyStateMap.get(apiKey);\n if (!s) {\n s = newKeyState();\n keyStateMap.set(apiKey, s);\n evictStale();\n }\n s.lastAccess = Date.now();\n return s;\n}\n\nfunction evictStale(): void {\n if (keyStateMap.size <= MAX_KEYS) return;\n const now = Date.now();\n for (const [key, s] of keyStateMap) {\n if (now - s.lastAccess > SESSION_TTL_MS) keyStateMap.delete(key);\n }\n if (keyStateMap.size > MAX_KEYS) {\n const sorted = [...keyStateMap.entries()].sort((a, b) => a[1].lastAccess - b[1].lastAccess);\n for (let i = 0; i < sorted.length - MAX_KEYS; i++) {\n keyStateMap.delete(sorted[i][0]);\n }\n }\n}\n","/**\n * MCP client — communicates with the Convex HTTP Action gateway.\n *\n * Dual mode:\n * stdio — single user, API key from env, module-level state\n * http — multi-user, API key from AsyncLocalStorage, per-key state\n *\n * Configuration:\n * PRODUCTBRAIN_API_KEY — pb_sk_* key (stdio mode; http mode gets it per-request)\n * CONVEX_SITE_URL — (optional) Convex deployment URL, defaults to cloud\n */\n\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport { trackToolCall } from \"./analytics.js\";\nimport { getRequestApiKey, getKeyState, type KeyState } from \"./auth.js\";\nimport type { NextAction } from \"./envelope.js\";\nimport { MCP_NPX_PACKAGE } from \"./cli/config-writer.js\";\n\n// ─── Tool Context (for audit action logging) ─────────────────────────────\n\nconst toolContextStore = new AsyncLocalStorage<{ tool: string; action?: string }>();\n\n/**\n * Run a callback with tool context for audit logging.\n * Compound tools should wrap their handler with this so health action=audit can distinguish\n * e.g. entries action=get from entries action=search.\n */\nexport function runWithToolContext<T>(\n ctx: { tool: string; action?: string },\n fn: () => T | Promise<T>,\n): T | Promise<T> {\n return toolContextStore.run(ctx, fn);\n}\n\nfunction getToolContext(): { tool: string; action?: string } | null {\n return toolContextStore.getStore() ?? null;\n}\n\nexport const DEFAULT_CLOUD_URL = \"https://gateway.productbrain.io\";\n\n/** Convex `/api/aki` error body — 4xx/5xx include `error`; structured codes include `code`. */\nexport class KernelCallError extends Error {\n readonly status: number;\n readonly code?: string;\n /** WP-316 S1a: Structured commit validation — required field keys missing from entry.data. */\n readonly missingRequiredFields?: string[];\n /** WP-316 S1a: Structured commit validation — field-level data errors. */\n readonly fieldErrors?: string[];\n constructor(\n message: string,\n status: number,\n code?: string,\n missingRequiredFields?: string[],\n fieldErrors?: string[],\n ) {\n super(message);\n this.name = \"KernelCallError\";\n this.status = status;\n this.code = code;\n this.missingRequiredFields = missingRequiredFields;\n this.fieldErrors = fieldErrors;\n }\n}\n\n// ─── Read Cache (Batch A: sub-200ms repeat calls) ─────────────────────\n\nconst CACHE_TTL_MS = 60_000; // 60s per plan\nconst CACHEABLE_FNS = [\n \"chain.getOrientEntries\",\n \"chain.gatherContext\",\n \"chain.graphGatherContext\",\n \"chain.taskAwareGatherContext\",\n \"chain.journeyAwareGatherContext\",\n \"chain.assembleBuildContext\",\n] as const;\n\nfunction isCacheable(fn: string): boolean {\n return (CACHEABLE_FNS as readonly string[]).includes(fn);\n}\n\nconst READ_PATTERN =\n /^(chain\\.(get|list|search|batchGet|gather|graph|task|journey|assemble|workspace|score|absence)|chainwork\\.(get|list|score)|maps\\.(get|list)|gitchain\\.(get|list|diff|history|runGate))/i;\n\nfunction isWrite(fn: string): boolean {\n if (fn.startsWith(\"agent.\")) return false;\n return !READ_PATTERN.test(fn);\n}\n\ninterface CacheEntry<T> {\n data: T;\n expiresAt: number;\n}\n\nconst readCache = new Map<string, CacheEntry<unknown>>();\n\nfunction cacheKey(fn: string, args: Record<string, unknown>): string {\n return `${fn}:${JSON.stringify(args)}`;\n}\n\nfunction getCached<T>(fn: string, args: Record<string, unknown>): T | undefined {\n if (!isCacheable(fn)) return undefined;\n const key = cacheKey(fn, args);\n const entry = readCache.get(key) as CacheEntry<T> | undefined;\n if (!entry || Date.now() > entry.expiresAt) {\n if (entry) readCache.delete(key);\n return undefined;\n }\n return entry.data;\n}\n\nfunction setCached<T>(fn: string, args: Record<string, unknown>, data: T): void {\n if (!isCacheable(fn)) return;\n const key = cacheKey(fn, args);\n readCache.set(key, { data, expiresAt: Date.now() + CACHE_TTL_MS });\n}\n\nfunction invalidateReadCache(): void {\n readCache.clear();\n}\n\n// ─── State Management ─────────────────────────────────────────────────\n\nconst _stdioState: KeyState = {\n workspaceId: null,\n workspaceSlug: null,\n workspaceName: null,\n workspaceCreatedAt: null,\n workspaceGovernanceMode: null,\n agentSessionId: null,\n apiKeyId: null,\n apiKeyScope: \"readwrite\",\n sessionOriented: false,\n sessionClosed: false,\n lastAccess: 0,\n deploymentUrl: null,\n};\n\n/**\n * Returns the active client state.\n * stdio: module-level singleton. http: per-API-key state from AsyncLocalStorage.\n */\nfunction state(): KeyState {\n const reqKey = getRequestApiKey();\n if (reqKey) return getKeyState(reqKey);\n return _stdioState;\n}\n\n/**\n * Returns the active API key (request-scoped in HTTP mode, env in stdio mode).\n */\nfunction getActiveApiKey(): string {\n const fromRequest = getRequestApiKey();\n if (fromRequest) return fromRequest;\n const fromEnv = process.env.PRODUCTBRAIN_API_KEY;\n if (!fromEnv) throw new Error(\"No API key available — set PRODUCTBRAIN_API_KEY or provide Bearer token\");\n return fromEnv;\n}\n\n// ─── Agent Session State ──────────────────────────────────────────────\n\nexport function getAgentSessionId(): string | null {\n return state().agentSessionId;\n}\n\nexport function isSessionOriented(): boolean {\n return state().sessionOriented;\n}\n\nexport function setSessionOriented(value: boolean): void {\n state().sessionOriented = value;\n}\n\nexport function getApiKeyScope(): \"read\" | \"readwrite\" {\n return state().apiKeyScope;\n}\n\nexport function isSessionClosed(): boolean {\n return state().sessionClosed;\n}\n\nexport interface AgentSessionStartResult {\n sessionId: string;\n initiatedBy: string;\n toolsScope: \"read\" | \"readwrite\";\n workspaceName: string;\n superseded: {\n previousSessionId: string;\n startedAt: string;\n initiatedBy: string;\n } | null;\n}\n\n/**\n * Start an agent session. Creates a session record in Convex.\n * toolsScope is derived server-side from the API key — not passed as a parameter.\n * If an active session exists, it gets superseded.\n */\nexport async function startAgentSession(): Promise<AgentSessionStartResult> {\n const workspaceId = await getWorkspaceId();\n const s = state();\n if (!s.apiKeyId) {\n throw new Error(\"Cannot start session: API key ID not resolved. Ensure workspace resolution completed.\");\n }\n\n const result = await kernelCall<AgentSessionStartResult>(\"agent.startSession\", {\n workspaceId,\n apiKeyId: s.apiKeyId,\n clientKind: \"mcp\",\n });\n\n if (s.agentSessionId) {\n resetTouchThrottle(s.agentSessionId);\n }\n s.agentSessionId = result.sessionId;\n s.apiKeyScope = result.toolsScope;\n s.sessionOriented = false;\n s.sessionClosed = false;\n resetTouchThrottle(result.sessionId);\n\n return result;\n}\n\n/**\n * Close the current agent session. After this, write tools are blocked\n * even if the MCP connection stays open.\n */\nexport async function closeAgentSession(): Promise<void> {\n const s = state();\n if (!s.agentSessionId) return;\n const sessionId = s.agentSessionId;\n try {\n await kernelCall(\"agent.closeSession\", {\n sessionId,\n status: \"closed\",\n });\n } finally {\n resetTouchThrottle(sessionId);\n s.sessionClosed = true;\n s.agentSessionId = null;\n s.sessionOriented = false;\n }\n}\n\n/**\n * Mark current session as orphaned (used on disconnect/crash).\n */\nexport async function orphanAgentSession(): Promise<void> {\n const s = state();\n if (!s.agentSessionId) return;\n const sessionId = s.agentSessionId;\n try {\n await kernelCall(\"agent.closeSession\", {\n sessionId,\n status: \"orphaned\",\n });\n } catch {\n // Best-effort on disconnect\n } finally {\n resetTouchThrottle(sessionId);\n s.agentSessionId = null;\n s.sessionOriented = false;\n }\n}\n\n/**\n * Touch the session to update lastToolCallAt. Fire-and-forget.\n * Throttled to at most once per 5s to prevent OCC conflicts when\n * multiple tool calls complete in parallel.\n */\nconst _lastTouchAtBySession = new Map<string, number>();\nconst TOUCH_THROTTLE_MS = 5_000;\n\nexport function touchSessionActivity(): void {\n const s = state();\n const sessionId = s.agentSessionId;\n if (!sessionId) return;\n\n const now = Date.now();\n const lastTouchAt = _lastTouchAtBySession.get(sessionId) ?? 0;\n if (now - lastTouchAt < TOUCH_THROTTLE_MS) return;\n _lastTouchAtBySession.set(sessionId, now);\n\n kernelCall(\"agent.touchSession\", {\n sessionId,\n }).catch(() => {});\n}\n\nexport function resetTouchThrottle(sessionId?: string | null): void {\n if (sessionId) {\n _lastTouchAtBySession.delete(sessionId);\n return;\n }\n _lastTouchAtBySession.clear();\n}\n\n/**\n * Record structured activity on the current session.\n */\nexport async function recordSessionActivity(activity: {\n entryCreated?: string;\n entryModified?: string;\n relationCreated?: boolean;\n gateFailure?: boolean;\n contradictionWarning?: boolean;\n strategyLinkWarnedForEntryId?: string;\n}): Promise<void> {\n const s = state();\n if (!s.agentSessionId) return;\n try {\n await kernelCall(\"agent.recordActivity\", {\n sessionId: s.agentSessionId,\n ...activity,\n });\n } catch {\n // Non-critical — don't fail the tool call over activity tracking\n }\n}\n\n// ─── Audit ────────────────────────────────────────────────────────────\n\nexport interface AuditEntry {\n ts: string;\n fn: string;\n workspace: string;\n status: \"ok\" | \"error\";\n durationMs: number;\n error?: string;\n /** For compound tools: tool name and action for audit display */\n toolContext?: { tool: string; action?: string };\n}\n\nconst AUDIT_BUFFER_SIZE = 50;\nconst auditBuffer: AuditEntry[] = [];\n\n/**\n * Bootstrap for stdio mode: set CONVEX_SITE_URL default and warn on missing key.\n * API key is validated lazily on first kernelCall so the server can start and handle\n * signals (SIGTERM) even before credentials are provided (e.g. in tests).\n */\nexport function bootstrap(): void {\n process.env.CONVEX_SITE_URL ??= process.env.PRODUCTBRAIN_URL ?? DEFAULT_CLOUD_URL;\n const pbKey = process.env.PRODUCTBRAIN_API_KEY;\n if (!pbKey?.startsWith(\"pb_sk_\")) {\n process.stderr.write(\n \"[MCP] Warning: PRODUCTBRAIN_API_KEY is not set or invalid. \" +\n \"Tool calls will fail until a valid key is provided.\\n\"\n );\n }\n}\n\n/**\n * Bootstrap for HTTP mode: only set CONVEX_SITE_URL.\n * API key validation happens per-request via Bearer token.\n */\nexport function bootstrapHttp(): void {\n process.env.CONVEX_SITE_URL ??= process.env.PRODUCTBRAIN_URL ?? DEFAULT_CLOUD_URL;\n}\n\n/** @deprecated Use bootstrap() instead. Alias kept for callers in transition. */\nexport const bootstrapCloudMode = bootstrap;\n\nfunction getEnv(key: string): string {\n const value = process.env[key];\n if (!value) throw new Error(`${key} environment variable is required`);\n return value;\n}\n\n/**\n * DEC-789 S2: Parse comma-separated fallback deployment URLs from env.\n * Used by resolveDeploymentUrl() for cold-start probing after Railway restarts.\n */\nfunction parseFallbackUrls(): string[] {\n const raw = process.env.CONVEX_FALLBACK_URLS;\n if (!raw) return [];\n return raw.split(\",\").map((u) => u.trim()).filter(Boolean);\n}\n\n/**\n * DEC-789 S2: Resolve the Convex deployment URL for the active API key.\n *\n * Warm path (normal): key-check already ran during OAuth authorize, so\n * state().deploymentUrl is set — return it immediately.\n *\n * No-fallback path (default / single-deployment): when CONVEX_FALLBACK_URLS\n * is not set, return CONVEX_SITE_URL directly without probing. This preserves\n * the original single-URL behavior and avoids extra fetch calls in tests and\n * stdio mode.\n *\n * Cold-start path (after Railway restart with CONVEX_FALLBACK_URLS configured):\n * keyStateMap was wiped; probe candidate URLs in order until one responds\n * ok:true to /api/key-check, store the result so subsequent calls are instant.\n *\n * Must be called from within a runWithAuth context (state() and\n * getActiveApiKey() both require it).\n */\nasync function resolveDeploymentUrl(): Promise<string> {\n const s = state();\n if (s.deploymentUrl) return s.deploymentUrl;\n\n const primaryUrl = (process.env.CONVEX_SITE_URL ?? DEFAULT_CLOUD_URL).replace(/\\/$/, \"\");\n const fallbacks = parseFallbackUrls();\n\n // No fallbacks configured — single-deployment setup, use primary directly.\n // This is the common case: preserves the original behavior, no extra fetch calls.\n if (fallbacks.length === 0) {\n return primaryUrl;\n }\n\n // Multi-deployment cold-start: probe candidates in order.\n const candidates = [primaryUrl, ...fallbacks.map((u) => u.replace(/\\/$/, \"\"))];\n\n let apiKey: string;\n try {\n apiKey = getActiveApiKey();\n } catch {\n // No API key available — return primary and let the tool call fail normally.\n return primaryUrl;\n }\n\n for (const candidate of candidates) {\n try {\n const probeRes = await fetch(`${candidate}/api/key-check`, {\n method: \"POST\",\n headers: { \"Authorization\": `Bearer ${apiKey}`, \"Content-Type\": \"application/json\" },\n signal: AbortSignal.timeout(3000),\n });\n if (probeRes.ok) {\n const data = await probeRes.json() as { ok: boolean };\n if (data.ok) {\n s.deploymentUrl = candidate;\n return candidate;\n }\n }\n } catch {\n // Probe failed (timeout, network error, etc.) — try next candidate.\n }\n }\n\n // All probes failed — return the first candidate and let the tool call fail with its normal error.\n return candidates[0];\n}\n\nfunction shouldLogAudit(status: \"ok\" | \"error\"): boolean {\n return status === \"error\" || process.env.MCP_DEBUG === \"1\";\n}\n\nfunction audit(fn: string, status: \"ok\" | \"error\", durationMs: number, errorMsg?: string): void {\n const ts = new Date().toISOString();\n const workspace = state().workspaceId ?? \"unresolved\";\n const toolCtx = getToolContext();\n\n const entry: AuditEntry = { ts, fn, workspace, status, durationMs };\n if (errorMsg) entry.error = errorMsg;\n if (toolCtx) entry.toolContext = toolCtx;\n auditBuffer.push(entry);\n if (auditBuffer.length > AUDIT_BUFFER_SIZE) auditBuffer.shift();\n\n trackToolCall(fn, status, durationMs, workspace, errorMsg);\n\n if (!shouldLogAudit(status)) return;\n\n const base = `[MCP-AUDIT] ${ts} fn=${fn} workspace=${workspace} status=${status} duration=${durationMs}ms`;\n if (status === \"error\" && errorMsg) {\n process.stderr.write(`${base} error=${JSON.stringify(errorMsg)}\\n`);\n } else {\n process.stderr.write(`${base}\\n`);\n }\n}\n\nexport function getAuditLog(): readonly AuditEntry[] {\n return auditBuffer;\n}\n\n// ─── HTTP Client ──────────────────────────────────────────────────────\n\n// NextAction imported from ./envelope.js — local MCP-layer definition (mirrors convex/lib/envelopeContract.ts;\n// BR-113 prevents direct convex/ imports from MCP package, so shape is kept in sync manually)\n\ninterface GatewaySuccessResponse<T> {\n ok: true;\n summary: string;\n data: T;\n next?: NextAction[];\n _meta?: { durationMs?: number };\n}\n\ninterface GatewayErrorResponse {\n ok: false;\n code?: string;\n message?: string;\n error?: string;\n missingRequiredFields?: string[];\n fieldErrors?: unknown[];\n}\n\ntype GatewayResponse<T> = GatewaySuccessResponse<T> | GatewayErrorResponse;\n\n// STD-101: Single SSOT for TOUCH_EXCLUDED — shared by kernelCall (callGateway) and kernelCallEnvelope.\n// Exported for testability — tests assert membership to prevent OCC cascade regressions.\nexport const TOUCH_EXCLUDED = new Set([\n \"agent.touchSession\",\n \"agent.startSession\",\n \"agent.markOriented\",\n \"agent.recordActivity\",\n \"agent.recordWrapup\",\n \"agent.closeSession\",\n // WP-376 α.3: orient byte report is itself a heartbeat-equivalent observability\n // write that already patches the same agentSessions row. A follow-up touchSession\n // would create a redundant second write per orient call (DEC-50 OCC anti-pattern).\n \"agent.reportOrientMetric\",\n]);\n\n/**\n * Private: shared HTTP fetch + error handling for kernelCall and kernelCallEnvelope.\n * Returns the parsed envelope fields without touching the read cache or session.\n */\nasync function callGateway<T>(fn: string, args: Record<string, unknown>): Promise<{\n data: T;\n summary: string;\n next?: NextAction[];\n _meta?: { durationMs?: number };\n}> {\n const siteUrl = await resolveDeploymentUrl();\n const apiKey = getActiveApiKey();\n\n const start = Date.now();\n\n let res: Response;\n try {\n res = await fetch(`${siteUrl}/api/aki`, {\n method: \"POST\",\n signal: AbortSignal.timeout(10_000),\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${apiKey}`,\n },\n body: JSON.stringify({ fn, args }),\n });\n } catch (err: any) {\n audit(fn, \"error\", Date.now() - start, err.message);\n throw new Error(`MCP call \"${fn}\" network error: ${err.message}`);\n }\n\n const json = (await res.json()) as GatewayResponse<T>;\n\n if (!res.ok || json.ok === false) {\n const errJson = json as GatewayErrorResponse;\n const msg = errJson.error ?? errJson.message ?? \"unknown error\";\n audit(fn, \"error\", Date.now() - start, errJson.code ? `${msg} [${errJson.code}]` : msg);\n throw new KernelCallError(\n `MCP call \"${fn}\" failed (${res.status}): ${msg}`,\n res.status,\n errJson.code,\n Array.isArray(errJson.missingRequiredFields) ? errJson.missingRequiredFields : undefined,\n Array.isArray(errJson.fieldErrors) ? (errJson.fieldErrors as string[]) : undefined,\n );\n }\n\n audit(fn, \"ok\", Date.now() - start);\n\n const { data, summary, next, _meta } = json as GatewaySuccessResponse<T>;\n return {\n data: data as T,\n summary: summary || fn,\n next,\n _meta,\n };\n}\n\n/**\n * Low-level call to the HTTP Action gateway.\n * Workspace scoping is enforced server-side from the API key — callers\n * don't need to (and can't) override the workspace.\n *\n * Read cache: orient and context-gather responses are cached for 60s.\n * Cache is invalidated on any write (safe-by-default: everything not\n * matching a known read pattern is treated as a write).\n */\nexport async function kernelCall<T>(fn: string, args: Record<string, unknown> = {}): Promise<T> {\n const cached = getCached<T>(fn, args);\n if (cached !== undefined) {\n return cached;\n }\n\n const { data } = await callGateway<T>(fn, args);\n\n if (isWrite(fn)) {\n invalidateReadCache();\n } else {\n setCached(fn, args, data);\n }\n\n const s = state();\n // Exclude session bookkeeping calls from the heartbeat touch. These mutations\n // already target the active session document, so immediately heartbeating after\n // them only adds avoidable OCC pressure on the same row.\n if (s.agentSessionId && !TOUCH_EXCLUDED.has(fn)) {\n touchSessionActivity();\n }\n\n return data;\n}\n\n/**\n * Calls the gateway and returns the kernel success envelope\n * ({ ok: true, summary, data, next?, _meta? }) instead of stripping to just data.\n *\n * Use for MCP tools that need thin passthrough — forwarding summary, next actions,\n * or timing metadata to the MCP client.\n *\n * Note: Throws KernelCallError on gateway errors (non-200 responses). Full\n * envelope error passthrough (ok:false at HTTP 200) deferred to WP-321 S6+\n * when DEC-571 HTTP semantics are activated on error paths.\n *\n * Does NOT use the read cache (kernel _meta.durationMs would be stale from cache;\n * thin passthrough tools need fresh timing). Does NOT call invalidateReadCache\n * (read-only by contract).\n */\nexport async function kernelCallEnvelope<T>(\n fn: string,\n args: Record<string, unknown> = {},\n): Promise<{\n ok: true;\n summary: string;\n data: T;\n next?: NextAction[];\n _meta?: { durationMs?: number };\n}> {\n const { data, summary, next, _meta } = await callGateway<T>(fn, args);\n\n const s = state();\n if (s.agentSessionId && !TOUCH_EXCLUDED.has(fn)) {\n touchSessionActivity();\n }\n\n return { ok: true, summary, data, next, _meta };\n}\n\n// ─── Workspace Resolution ─────────────────────────────────────────────\n\nconst resolveInFlightMap = new Map<string, Promise<string>>();\n\nexport async function getWorkspaceId(): Promise<string> {\n const s = state();\n if (s.workspaceId) return s.workspaceId;\n\n const apiKey = getActiveApiKey();\n const existing = resolveInFlightMap.get(apiKey);\n if (existing) return existing;\n\n const promise = resolveWorkspaceWithRetry().finally(() => resolveInFlightMap.delete(apiKey));\n resolveInFlightMap.set(apiKey, promise);\n return promise;\n}\n\nasync function resolveWorkspaceWithRetry(maxRetries = 2): Promise<string> {\n let lastError: Error | null = null;\n\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n try {\n const workspace = await kernelCall<{\n _id: string;\n name: string;\n slug: string;\n createdAt?: number;\n keyScope?: string;\n keyId?: string;\n governanceMode?: \"open\" | \"consensus\" | \"role\";\n } | null>(\"resolveWorkspace\", {});\n\n if (!workspace) {\n throw new Error(\n \"API key is valid but no workspace is associated. \" +\n `Run \\`npx ${MCP_NPX_PACKAGE} setup\\` or regenerate your key.`\n );\n }\n\n const s = state();\n s.workspaceId = workspace._id;\n s.workspaceSlug = workspace.slug;\n s.workspaceName = workspace.name;\n s.workspaceCreatedAt = workspace.createdAt ?? null;\n s.workspaceGovernanceMode = workspace.governanceMode ?? \"open\";\n if (workspace.keyScope) s.apiKeyScope = workspace.keyScope as \"read\" | \"readwrite\";\n if (workspace.keyId) s.apiKeyId = workspace.keyId;\n return s.workspaceId;\n } catch (err: any) {\n lastError = err;\n const isTransient = /network error|fetch failed|ECONNREFUSED|ETIMEDOUT/i.test(err.message);\n if (!isTransient || attempt === maxRetries) break;\n const delay = 1000 * (attempt + 1);\n process.stderr.write(\n `[MCP] Workspace resolution failed (attempt ${attempt + 1}/${maxRetries + 1}), retrying in ${delay}ms...\\n`\n );\n await new Promise((r) => setTimeout(r, delay));\n }\n }\n\n throw lastError!;\n}\n\nexport interface WorkspaceContext {\n workspaceId: string;\n workspaceSlug: string;\n workspaceName: string;\n createdAt: number | null;\n /** BET-76 FEAT-111: Cached from workspace resolution. Defaults to 'open'. */\n governanceMode: \"open\" | \"consensus\" | \"role\";\n}\n\nexport async function getWorkspaceContext(): Promise<WorkspaceContext> {\n const workspaceId = await getWorkspaceId();\n const s = state();\n return {\n workspaceId,\n workspaceSlug: s.workspaceSlug ?? \"unknown\",\n workspaceName: s.workspaceName ?? \"unknown\",\n createdAt: s.workspaceCreatedAt,\n governanceMode: s.workspaceGovernanceMode ?? \"open\",\n };\n}\n\n/**\n * TEN-1810: Re-fetches only governanceMode from the workspace without invalidating\n * stable identifiers (workspaceId, slug, name). Safe to call before every capture.\n * Single round-trip, no retry loop — workspace is already known at this point.\n */\nexport async function refreshWorkspaceGovernanceMode(): Promise<\"open\" | \"consensus\" | \"role\"> {\n const workspace = await kernelCall<{\n governanceMode?: \"open\" | \"consensus\" | \"role\";\n } | null>(\"resolveWorkspace\", {});\n const mode: \"open\" | \"consensus\" | \"role\" = workspace?.governanceMode ?? \"open\";\n const s = state();\n s.workspaceGovernanceMode = mode;\n return mode;\n}\n\nexport async function kernelQuery<T>(fn: string, args: Record<string, unknown> = {}): Promise<T> {\n const workspaceId = await getWorkspaceId();\n return kernelCall<T>(fn, { ...args, workspaceId });\n}\n\nexport async function kernelMutation<T>(fn: string, args: Record<string, unknown> = {}): Promise<T> {\n const workspaceId = await getWorkspaceId();\n return kernelCall<T>(fn, { ...args, workspaceId });\n}\n\n/**\n * @deprecated Use kernelQuery (reads) or kernelMutation (writes) instead.\n * Kept temporarily for backward compatibility — identical to both.\n */\nexport async function mcpAction<T>(fn: string, args: Record<string, unknown> = {}): Promise<T> {\n const workspaceId = await getWorkspaceId();\n return kernelCall<T>(fn, { ...args, workspaceId });\n}\n\n/**\n * Gate check: throws if no active, oriented session exists.\n *\n * Used for read tools that require session context per SOS-iszqu7:\n * structured Chain data for agent consumption requires an active session.\n * Lighter than requireWriteAccess — does not check key scope.\n */\nexport function requireActiveSession(): void {\n const s = state();\n\n if (!s.agentSessionId) {\n throw new Error(\n \"Active session required (SOS-iszqu7). Call `session action=start` then `orient` first.\"\n );\n }\n\n if (s.sessionClosed) {\n throw new Error(\n \"Session has been closed (SOS-iszqu7). Start a new session with `session action=start`.\"\n );\n }\n\n if (!s.sessionOriented) {\n throw new Error(\n \"Orientation required before accessing build context (SOS-iszqu7). Call `orient` first.\"\n );\n }\n}\n\n/**\n * Gate check: throws if the agent is not allowed to write.\n *\n * Enforces:\n * 1. Session must exist (always required — no REQUIRE_AGENT_SESSION flag)\n * 2. Session must not be closed\n * 3. Session must be oriented\n * 4. Key scope must be readwrite\n */\nexport function requireWriteAccess(): void {\n const s = state();\n\n if (!s.agentSessionId) {\n throw new Error(\n \"Agent session required for write operations. Call `session action=start` first.\"\n );\n }\n\n if (s.sessionClosed) {\n throw new Error(\n \"Agent session has been closed. Write tools are no longer available.\"\n );\n }\n\n if (!s.sessionOriented) {\n throw new Error(\n \"Orientation required before writing to the Chain. Call 'orient' first.\"\n );\n }\n\n if (s.apiKeyScope === \"read\") {\n throw new Error(\n \"This API key has read-only scope. Write tools are not available.\"\n );\n }\n}\n\n/**\n * Recover session orientation state from Convex on restart.\n * If the session is active and oriented in Convex, restore local state.\n */\nexport async function recoverSessionState(): Promise<void> {\n const s = state();\n if (!s.workspaceId) return;\n try {\n const session = await kernelCall<{\n _id: string;\n status: string;\n oriented: boolean;\n toolsScope: string;\n } | null>(\"agent.getActiveSession\", { workspaceId: s.workspaceId });\n\n if (session && session.status === \"active\") {\n s.agentSessionId = session._id;\n s.sessionOriented = session.oriented;\n s.apiKeyScope = session.toolsScope as \"read\" | \"readwrite\";\n s.sessionClosed = false;\n }\n } catch {\n // Recovery is best-effort\n }\n}\n","/**\n * McpServer factory — shared between stdio (index.ts) and HTTP (http.ts) entry points.\n */\n\nimport { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\n\nimport { registerKnowledgeTools } from \"./tools/knowledge.js\";\nimport { registerEntriesTools } from \"./tools/entries.js\";\nimport { registerGraphTools } from \"./tools/graph.js\";\nimport { registerRelationsTools } from \"./tools/relations.js\";\nimport { registerContextTools } from \"./tools/context.js\";\nimport { registerCollectionsTools } from \"./tools/collections.js\";\nimport { registerLabelTools } from \"./tools/labels.js\";\nimport { registerHealthTools } from \"./tools/health.js\";\nimport { registerOrientTool } from \"./tools/orient.js\";\nimport { registerVerifyTools } from \"./tools/verify.js\";\nimport { registerSmartCaptureTools } from \"./tools/smart-capture.js\";\nimport { registerArchitectureTools } from \"./tools/architecture.js\";\nimport { registerWorkflowTools } from \"./tools/workflows.js\";\nimport { registerQualityTools } from \"./tools/quality.js\";\nimport { registerSessionTools } from \"./tools/session.js\";\nimport { registerWrapupTools } from \"./tools/wrapup.js\";\nimport { registerGitChainTools } from \"./tools/gitchain.js\";\nimport { registerMapTools } from \"./tools/maps.js\";\nimport { registerSkillsTools } from \"./tools/skills.js\";\nimport { registerStartPbTools } from \"./tools/start_pb.js\";\nimport { registerRecordActivationTools } from \"./tools/record_activation.js\";\nimport { registerUsageTools } from \"./tools/usage.js\";\nimport { registerFacilitateTools } from \"./tools/facilitate.js\";\nimport { registerAuditTools } from \"./tools/audit.js\";\nimport { registerGovernanceTools } from \"./tools/governance.js\";\nimport { registerDocumentsTools } from \"./tools/documents.js\";\nimport { registerResources } from \"./resources/index.js\";\nimport { registerPrompts } from \"./prompts/index.js\";\nimport { initToolSurface } from \"./tool-surface.js\";\n\nexport const SERVER_VERSION = \"0.7.2\";\n\nconst INSTRUCTIONS = [\n \"Product Brain — the single source of truth for product knowledge.\",\n \"Terminology, standards, and core data all live here — no need to check external docs.\",\n \"\",\n \"## About Product Brain (PB)\",\n \"\",\n \"PB is a knowledge management system used by many product teams.\",\n \"These describe how PB works — not your product.\",\n \"\",\n \"### How PB Organizes Its Tools\",\n \"- **Tools** are for actions with side-effects or dynamic computation (capture, commit, search).\",\n \"- **Resources** are for stable, read-only data (orientation, terminology, collection schemas).\",\n \"- **Prompts** are for multi-step choreography (workflows, guided capture, deep dives).\",\n \"- Every tool, resource, and prompt works for ANY workspace — no bespoke logic.\",\n \"- Resource templates (URI params) provide workspace-specific data through generic patterns.\",\n \"- Tool count stays minimal: compound tools with `action` enums over many single-purpose tools.\",\n \"\",\n \"### How PB Handles Your Data\",\n \"- **Draft-first**: all writes create drafts. Nothing reaches SSOT without explicit user confirmation.\",\n \"- **Empty-workspace safe**: every tool and resource handles zero entries, zero collections, and fresh workspaces.\",\n \"- **Advisory, not blocking**: quality scores, contradiction checks, and coaching are informational. They never prevent an operation.\",\n \"- **Workspace-agnostic**: PB is a product used by many teams. No workspace-specific logic in server code.\",\n \"- **Self-documenting**: orient and server instructions teach agents how PB works. Cursor rules supplement but don't replace.\",\n \"\",\n \"## Your Workspace Principles\",\n \"\",\n \"When you orient or start, PB surfaces active entries from your `principles`, `standards`,\",\n \"and `business-rules` collections. These are YOUR team's guardrails — respect them during implementation.\",\n \"If no principles exist yet, PB will tell you and suggest how to add them.\",\n \"\",\n \"The three governance collections:\",\n \"- **Principles** (`principles`) — beliefs that guide decisions. 'We believe X.' You reason from a principle.\",\n \"- **Standards** (`standards`) — conventions about how work is done. 'We do X this way.' You lint for a standard.\",\n \"- **Business Rules** (`business-rules`) — system constraints. 'The system must do X.' You test for a rule.\",\n \"\",\n \"## Workflow\",\n \"\",\n \" 1. Start: call `start_pb` to begin — it starts a session automatically, detects your workspace stage, and returns the right guidance. Fresh workspaces get the pb-setup skill body; active workspaces get a standup briefing.\",\n \" 2. Re-orient: call `orient` mid-session for task-scoped context or a compact status refresh.\",\n \" 3. Discover: use `entries action=search` to find entries, or `entries action=list` to browse.\",\n \" 4. Drill in: use `entries action=get entryId=\\\"...\\\"` for full details — data, labels, relations, history.\",\n \" 5. Context: use `context action=gather` with an entryId or a task description.\",\n \" 6. Capture: use `capture` to create entries — auto-links and scores in one call.\",\n \" 7. Commit: use `commit-entry` to promote drafts to SSOT — only when the user confirms.\",\n \" 8. Connect: use `graph action=suggest` then `relations action=create` to build the graph.\",\n \" 9. Wrapup: call `session-wrapup` before closing — reviews drafts, coaches quality, suggests links.\",\n \" 10. Close: call `session action=close` when done — records session activity. Auto-nudges if wrapup was skipped.\",\n \"\",\n \"Write tools (capture, update-entry, relations, commit-entry) require:\",\n \" - Call `start_pb` to begin (starts session + loads context). Call `orient` mid-session for a refresh.\",\n \" - A readwrite API key scope\",\n \"\",\n \"Commit-on-confirm: always capture as draft first and show the user what was captured.\",\n \"Only call `commit-entry` when the user explicitly confirms (e.g. 'commit', 'looks good', 'yes').\",\n \"This builds trust — the Chain (main) is SSOT; nothing goes there without user consent.\",\n \"\",\n \"Alignment-first: before proposing or building anything, check orient's Workspace Governance\",\n \"and Active bets sections. These are constraints, not reference material.\",\n \"If the proposal conflicts with a principle, standard, or business rule — stop, flag the conflict,\",\n \"and get explicit user confirmation before proceeding. Do not design around governance.\",\n \"If the work is outside the scope of active bets — stop, name the gap, and ask the user\",\n \"to confirm before designing. Do not propose implementation for out-of-scope work without a go-ahead.\",\n \"\",\n \"Workspace setup: use `collections action=create` and `collections action=update` to shape the workspace\",\n \"structure with the user. Ask what they need to track; presets are starting points, not fixed.\",\n \"\",\n \"Personalization: if you have context about the user from memory (prior work, recent\",\n \"conversations, team context), use it to personalize recommendations. For example,\",\n \"'Based on your recent pitch reviews, the gap most likely to matter is X.'\",\n \"The orient/start output gives you the workspace state; your memory fills in the human context.\",\n].join(\"\\n\");\n\nexport function createProductBrainServer(): McpServer {\n const server = new McpServer(\n { name: \"Product Brain\", version: SERVER_VERSION },\n { capabilities: { logging: {} }, instructions: INSTRUCTIONS },\n );\n\n initToolSurface();\n\n const enabledModules = new Set(\n (process.env.PB_MODULES ?? \"core,gitchain,arch\")\n .split(\",\").map((m) => m.trim().toLowerCase()),\n );\n\n registerSessionTools(server);\n registerWrapupTools(server);\n registerEntriesTools(server);\n registerGraphTools(server);\n registerRelationsTools(server);\n registerContextTools(server);\n registerCollectionsTools(server);\n registerKnowledgeTools(server);\n registerLabelTools(server);\n registerHealthTools(server);\n registerOrientTool(server);\n registerVerifyTools(server);\n registerSmartCaptureTools(server);\n registerQualityTools(server);\n registerWorkflowTools(server);\n\n if (enabledModules.has(\"gitchain\")) registerGitChainTools(server);\n if (enabledModules.has(\"gitchain\")) registerMapTools(server);\n if (enabledModules.has(\"arch\")) registerArchitectureTools(server);\n registerSkillsTools(server);\n registerStartPbTools(server);\n registerRecordActivationTools(server);\n registerUsageTools(server);\n registerFacilitateTools(server);\n registerAuditTools(server);\n registerGovernanceTools(server);\n registerDocumentsTools(server);\n\n registerResources(server);\n registerPrompts(server);\n\n // All 31 tools visible from connection. Write tools are guarded at handler\n // level (requireWriteAccess checks session + orient + key scope). Hiding\n // tools via disable() broke Claude's lazy tool indexing — it never\n // re-indexed after list_changed notifications.\n\n return server;\n}\n","import { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { z } from \"zod\";\nimport { kernelQuery, kernelMutation, getWorkspaceContext, requireWriteAccess, recordSessionActivity, getAgentSessionId } from \"../client.js\";\nimport { formatRubricCoaching } from \"./smart-capture.js\";\nimport { runConflictPreflight } from \"./conflict-preflight.js\";\nimport { trackQualityVerdict, trackQualityCheck, trackChainEntryCommitted, trackFieldQualityWarning, trackCommitErrorByCode } from \"../analytics.js\";\nimport { extractPreview, deriveEpistemicStatus, formatEpistemicLine, toEpistemicInput } from \"./knowledge-helpers.js\";\nimport { trackWriteTool } from \"../tool-surface.js\";\nimport { failureResult, thinWrapper, success, notFoundResult, successResult, type NextAction } from \"../envelope.js\";\n\n// Single source of truth for all collection workflow states.\n// Add new values here — WorkflowStatus type and the zod enum both derive from this array.\n// Source: convex/lib/collectionClassification.ts validWorkflowStatuses per collection.\nconst WORKFLOW_STATUS_VALUES = [\n // Generic / governed collections\n 'open', 'pending', 'proposed', 'accepted', 'needs-amendment',\n 'withdrawn', 'review', 'in-progress', 'decided', 'conflict',\n 'processing', 'closed',\n // Chains (bet type) lifecycle\n 'shaped', 'bet', 'building', 'shipped',\n // Assumptions lifecycle\n 'untested', 'testing', 'validated', 'invalidated',\n // Insights lifecycle\n 'hypothesis', 'evidenced',\n] as const;\n\ntype WorkflowStatus = typeof WORKFLOW_STATUS_VALUES[number];\n\ntype LifecycleStatus = 'draft' | 'active' | 'deprecated' | 'archived';\n\n// Backward-compat shim (BET-68, expires ~2026-09-03)\n// Workflow values passed via `status` are routed to `workflowStatus` with a deprecation warning.\nconst LEGACY_WORKFLOW_STATUSES = new Set<string>(WORKFLOW_STATUS_VALUES);\n\nexport const updateEntrySchema = z.object({\n entryId: z.string().describe(\"Entry ID to update, e.g. 'T-SUPPLIER', 'BR-001'\"),\n name: z.string().optional().describe(\"New display name\"),\n status: z.union([\n z.enum(['draft', 'active', 'deprecated', 'archived']),\n z.enum(WORKFLOW_STATUS_VALUES),\n ]).optional().describe(\"Lifecycle status: draft | active | deprecated | archived. **Workflow values (open, pending, decided…) are deprecated here — use `workflowStatus` instead. Passing a workflow value as `status` will be auto-routed with a warning until 2026-09-03, then hard-errored.**\"),\n workflowStatus: z.enum(WORKFLOW_STATUS_VALUES).optional().describe(\"Collection workflow state. Each collection restricts which values are valid (e.g. bets: 'shaped' | 'building' | 'shipped' | 'dropped'; assumptions: 'untested' | 'testing' | 'validated' | 'invalidated'; decisions: 'pending' | 'decided'; tensions: 'open' | 'processing' | 'decided' | 'closed'). The backend will reject values invalid for the target collection.\"),\n data: z.record(z.unknown()).optional().describe(\"Fields to update (merged with existing data)\"),\n order: z.number().optional().describe(\"New sort order\"),\n canonicalKey: z.string().optional().describe(\"Semantic type (e.g. 'decision', 'tension'). Only changeable on draft/uncommitted entries.\"),\n autoPublish: z.boolean().optional().default(false).describe(\"Only true when user explicitly asks to publish. Default false = draft. Never auto-publish without user confirmation.\"),\n changeNote: z.string().optional().describe(\"Strongly recommended: short human-readable rationale for WHY this change was made (e.g. 'Aligned description with F1-themed copy per BET-238'). Surfaces in activity feed and pb get. If omitted, falls back to session purpose or auto-generated field summary.\"),\n sourceRef: z.string().optional().describe(\"URI or path of the source document backing this entry. Write-once: can only be set if currently empty.\"),\n sourceExcerpt: z.string().optional().describe(\"Verbatim excerpt from the source that backs this entry's claims. Write-once: can only be set if currently empty.\"),\n});\n\nexport const getHistorySchema = z.object({\n entryId: z.string().describe(\"Entry ID, e.g. 'T-SUPPLIER', 'BR-001'\"),\n});\n\nexport const commitEntrySchema = z.object({\n entryId: z.string().describe(\"Entry ID to commit, e.g. 'TEN-abc123', 'GT-019'\"),\n // WP-316 S3: Preview gate — dry-run mode. Returns would-succeed result, no DB writes.\n preview: z.boolean().optional().describe(\"If true, validates the commit without writing. Returns what would happen. Default false.\"),\n});\n\nexport function registerKnowledgeTools(server: McpServer) {\n\n const updateTool = server.registerTool(\n \"update-entry\",\n {\n title: \"Update Entry\",\n description:\n \"Update an existing entry by its human-readable ID. Only provide the fields you want to change — data fields are merged with existing values. \" +\n \"Creates a draft version by default. **Never use autoPublish=true unless the user explicitly asks to publish** — same rule as commit-entry. \" +\n \"Use entries action=get first to see current values.\",\n inputSchema: updateEntrySchema,\n annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: false },\n },\n thinWrapper(async ({ entryId, name, status: rawStatus, workflowStatus: rawWorkflowStatus, data, order, canonicalKey, autoPublish, changeNote, sourceRef, sourceExcerpt }) => {\n requireWriteAccess();\n\n const fieldsProvided: string[] = [];\n if (name !== undefined) fieldsProvided.push('name');\n if (rawStatus !== undefined) fieldsProvided.push('status');\n if (rawWorkflowStatus !== undefined) fieldsProvided.push('workflowStatus');\n if (data !== undefined) fieldsProvided.push('data');\n if (order !== undefined) fieldsProvided.push('order');\n if (canonicalKey !== undefined) fieldsProvided.push('canonicalKey');\n\n let status: LifecycleStatus | undefined = rawStatus as LifecycleStatus | undefined;\n let workflowStatus: WorkflowStatus | undefined = rawWorkflowStatus as WorkflowStatus | undefined;\n let deprecationWarning: string | undefined;\n\n if (rawStatus && LEGACY_WORKFLOW_STATUSES.has(rawStatus)) {\n if (!workflowStatus) {\n workflowStatus = rawStatus as WorkflowStatus;\n }\n status = undefined;\n deprecationWarning = `⚠️ Deprecation: \\`status: '${rawStatus}'\\` — use \\`workflowStatus: '${rawStatus}'\\` instead. Support ends ~2026-09-03.`;\n }\n\n // BET-192 / FEAT-575: chain.updateEntry now returns warnings + normalization breakdown\n const updateResult = await kernelMutation<{\n id: string;\n warnings: string[];\n normalization: { remapped: Record<string, string>; rejected: string[]; accepted: string[] };\n normalizationWarnings: string[];\n validationWarnings: string[];\n }>(\"chain.updateEntry\", {\n entryId,\n name,\n status,\n workflowStatus,\n data,\n order,\n canonicalKey,\n autoPublish,\n changeNote,\n changedBy: getAgentSessionId() ? `agent:${getAgentSessionId()}` : undefined,\n ...(sourceRef ? { sourceRef } : {}),\n ...(sourceExcerpt ? { sourceExcerpt } : {}),\n });\n\n const id = updateResult.id;\n await recordSessionActivity({ entryModified: id });\n\n const wsCtx = await getWorkspaceContext();\n const updated = await kernelQuery<any>(\"chain.getEntry\", { entryId });\n const entryStatus: LifecycleStatus = (updated?.status ?? 'draft') as LifecycleStatus;\n const versionMode = entryStatus === 'active' ? 'published' : `saved as ${entryStatus}`;\n const responseLines = [\n `# Entry Updated`,\n ``,\n `**${entryId}** — ${versionMode}.`,\n ``,\n `Internal ID: ${id}`,\n `**Workspace:** ${wsCtx.workspaceSlug} (${wsCtx.workspaceId})`,\n ];\n\n if (fieldsProvided.length > 0) {\n responseLines.push(`**Fields provided:** ${fieldsProvided.join(', ')}`);\n } else {\n responseLines.push('');\n responseLines.push('⚠️ No fields to update were provided — only `entryId` was set.');\n }\n\n if (deprecationWarning) {\n responseLines.push('');\n responseLines.push(deprecationWarning);\n }\n\n // BET-192 / FEAT-575: Surface normalization warnings (fields silently dropped by normalizeEntryData)\n if (updateResult.normalizationWarnings.length > 0) {\n responseLines.push('');\n responseLines.push('⚠️ **Normalization warnings:**');\n for (const warning of updateResult.normalizationWarnings) {\n responseLines.push(` - ${warning}`);\n }\n }\n\n // BET-192 / FEAT-575: Surface validation warnings (missing required fields, etc.)\n if (updateResult.validationWarnings.length > 0) {\n responseLines.push('');\n responseLines.push('⚠️ **Validation warnings:**');\n for (const warning of updateResult.validationWarnings) {\n responseLines.push(` - ${warning}`);\n }\n }\n\n const summary = `Updated ${entryId} — ${versionMode}. Fields: ${fieldsProvided.join(', ') || 'none'}.`;\n const next: NextAction[] = [\n { tool: \"entries\", description: \"View updated entry\", parameters: { action: \"get\", entryId } },\n { tool: \"commit-entry\", description: \"Commit to Chain\", parameters: { entryId } },\n ];\n\n return {\n content: [{ type: \"text\" as const, text: responseLines.join(\"\\n\") }],\n structuredContent: success(summary, {\n entryId: id,\n versionMode,\n fieldsProvided,\n // BET-192: normalization breakdown in structuredContent — symmetric with capture tool\n ...(updateResult.normalization && (Object.keys(updateResult.normalization.remapped).length > 0 || updateResult.normalization.rejected.length > 0) && {\n normalization: {\n remapped: updateResult.normalization.remapped,\n rejected: updateResult.normalization.rejected,\n },\n }),\n ...(updateResult.normalizationWarnings.length > 0 && {\n normalizationWarnings: updateResult.normalizationWarnings,\n }),\n ...(updateResult.validationWarnings.length > 0 && {\n validationWarnings: updateResult.validationWarnings,\n }),\n }, next),\n };\n })\n );\n trackWriteTool(updateTool);\n\n server.registerTool(\n \"get-history\",\n {\n title: \"Entry Change History\",\n description:\n \"Get the audit trail for an entry — when it was created, updated, status-changed, etc. \" +\n \"Returns timestamped events with change details.\",\n inputSchema: getHistorySchema,\n annotations: { readOnlyHint: true, idempotentHint: true, openWorldHint: false },\n },\n thinWrapper(async ({ entryId }) => {\n const history = await kernelQuery<any[]>(\"chain.listEntryHistory\", { entryId });\n\n if (history.length === 0) {\n return successResult(\n `No history found for ${entryId}.`,\n `No history events recorded for ${entryId}.`,\n { entryId, eventCount: 0, events: [] },\n );\n }\n\n const formatted = history\n .map((h) => {\n const date = new Date(h.timestamp).toISOString();\n const changes = h.changes ? ` — ${JSON.stringify(h.changes)}` : \"\";\n return `- **${date}** ${h.event}${h.changedBy ? ` _(${h.changedBy})_` : \"\"}${changes}`;\n })\n .join(\"\\n\");\n\n return {\n content: [{ type: \"text\" as const, text: `# History for \\`${entryId}\\` (${history.length} events)\\n\\n${formatted}` }],\n structuredContent: success(\n `Found ${history.length} history events for ${entryId}.`,\n { entryId, eventCount: history.length, events: history },\n ),\n };\n })\n );\n\n const commitTool = server.registerTool(\n \"commit-entry\",\n {\n title: \"Commit Entry to Chain\",\n description:\n \"Promote a draft entry to committed status (SSOT on the Chain). \" +\n \"Runs the staging-grade semantic conflict detector before committing and blocks high-confidence contradictions. \" +\n \"Lower-confidence conflicts remain advisory.\\n\\n\" +\n \"Use after capture + graph action=suggest + relations action=create to finalize an entry.\",\n inputSchema: commitEntrySchema,\n annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false },\n },\n thinWrapper(async ({ entryId, preview }) => {\n requireWriteAccess();\n\n const entry = await kernelQuery<any>(\"chain.getEntry\", { entryId });\n if (!entry) {\n return notFoundResult(entryId, `Entry '${entryId}' not found. Try search to find the right ID.`);\n }\n\n const descField = entry.data?.description ?? entry.data?.canonical ?? entry.data?.rationale ?? \"\";\n const preflight = await runConflictPreflight(\n entry.name,\n descField,\n entry.collectionSlug ?? entry.collection?.slug ?? entry.collection?.name,\n );\n const advisoryWarnings = preflight.source === \"semantic\"\n ? preflight.conflicts\n .filter((conflict) => !preflight.blockingContradictions.includes(conflict))\n .map((conflict) => ({\n kind: \"semantic\" as const,\n entryId: conflict.chainEntryId,\n name: conflict.chainEntryName,\n explanation: conflict.explanation,\n }))\n : preflight.advisoryWarnings.map((warning) => ({\n kind: \"heuristic\" as const,\n entryId: warning.entryId,\n name: warning.name,\n collection: warning.collection,\n governsCount: warning.governsCount,\n }));\n\n if (preflight.blockingContradictions.length > 0) {\n await recordSessionActivity({ contradictionWarning: true });\n const conflictLines = preflight.blockingContradictions\n .map((c) => `- ${c.chainEntryName} (${c.chainEntryId}) — ${c.explanation}`)\n .join(\"\\n\");\n\n return failureResult(\n [\n `# Commit blocked: contradiction detected`,\n \"\",\n `\\`${entryId}\\` matches ${preflight.blockingContradictions.length} high-confidence contradiction(s). Resolve the conflict before committing.`,\n \"\",\n conflictLines,\n ].join(\"\\n\"),\n \"CONTRADICTION_BLOCKED\",\n `${preflight.blockingContradictions.length} high-confidence contradiction(s) found.`,\n \"Review the conflicting entry or entries before retrying the commit.\",\n undefined,\n {\n entryId,\n source: preflight.source,\n blockingContradictions: preflight.blockingContradictions,\n advisoryWarnings,\n },\n );\n }\n\n if (advisoryWarnings.length > 0) {\n await recordSessionActivity({ contradictionWarning: true });\n }\n\n let coachingResult: any = null;\n try {\n coachingResult = await kernelMutation<any>(\"quality.evaluateHeuristicAndSchedule\", {\n entryId,\n context: \"commit\",\n });\n } catch {\n // Quality coaching is advisory\n }\n\n let result: any;\n try {\n result = await kernelMutation<any>(\"chain.commitEntry\", {\n entryId,\n author: getAgentSessionId() ? `agent:${getAgentSessionId()}` : undefined,\n sessionId: getAgentSessionId() ?? undefined,\n ...(preview ? { preview: true } : {}),\n });\n } catch (commitErr: unknown) {\n // WP-316 S1a: Fire PostHog event on structured validation failure before re-throwing.\n // The thinWrapper HOF will catch and format the error into diagnostics.\n const errCode = (commitErr as { code?: string })?.code;\n if (errCode === \"VALIDATION_FAILED\") {\n try {\n const wsCtx = await getWorkspaceContext();\n const e = commitErr as { missingRequiredFields?: string[]; fieldErrors?: string[] };\n trackCommitErrorByCode(wsCtx.workspaceId, {\n error_code: errCode,\n missing_field_count: e.missingRequiredFields?.length ?? 0,\n field_error_count: e.fieldErrors?.length ?? 0,\n entry_id: entryId,\n });\n } catch { /* tracking must not break commit error path */ }\n }\n throw commitErr;\n }\n\n // WP-316 S3: Preview gate — return dry-run result without recording activity.\n if (result?.preview) {\n const previewEnvelope = success(\n `Preview: would commit ${entryId} — no DB writes`,\n {\n entryId,\n name: entry.name,\n outcome: \"preview\" as const,\n currentStatus: result.currentStatus,\n wouldSetStatus: result.wouldSetStatus,\n },\n [{ tool: \"commit-entry\", description: \"Commit for real\", parameters: { entryId } }],\n );\n if (result.contract) {\n previewEnvelope.contract = result.contract;\n }\n return {\n content: [{ type: \"text\" as const, text: `# Preview: would commit ${entryId}\\n\\nCurrent status: \\`${result.currentStatus}\\` → would become \\`${result.wouldSetStatus}\\`.\\n\\nNo DB writes — call without \\`preview:true\\` to commit for real.` }],\n structuredContent: previewEnvelope,\n };\n }\n\n const docId = result?._id ?? entry._id;\n const wsCtx = await getWorkspaceContext();\n const isProposal = result?.status === \"proposal_created\";\n if (!isProposal) {\n await recordSessionActivity({ entryModified: docId });\n const coll =\n (entry.collectionSlug as string | undefined) ??\n (entry.collection?.slug as string | undefined);\n trackChainEntryCommitted(wsCtx.workspaceId, {\n entry_id: entry.entryId ?? entryId,\n collection: coll,\n commit_method: \"manual\",\n surface: \"mcp_commit_tool\",\n });\n }\n let lines: string[];\n\n if (isProposal) {\n lines = [\n `# Proposal created: ${result.entryId ?? entryId}`,\n `**${result.name ?? entry.name}** — commit requires consent. A proposal was created instead of committing directly.`,\n `**Workspace:** ${wsCtx.workspaceSlug} (${wsCtx.workspaceId})`,\n \"\",\n result.existing\n ? \"An open proposal for this entry already exists.\"\n : \"Affected owners will be notified. The entry will be committed when the consent window expires with no objections, or when all owners approve.\",\n ];\n } else {\n lines = [\n `# Committed: ${entryId}`,\n `**${entry.name}** promoted to SSOT on the Chain.`,\n `**Workspace:** ${wsCtx.workspaceSlug} (${wsCtx.workspaceId})`,\n ];\n }\n\n if (advisoryWarnings.length > 0) {\n lines.push(\"\");\n lines.push(preflight.source === \"semantic\"\n ? \"⚠ Semantic conflict preflight: advisory conflict(s) found.\"\n : \"⚠ Contradiction check: proposed entry matched existing governance entries:\");\n for (const w of advisoryWarnings) {\n lines.push(w.kind === \"semantic\"\n ? `- ${w.name} (${w.entryId}) — ${w.explanation}`\n : `- ${w.name} (${w.collection}, ${w.entryId}) — has 'governs' relation to ${w.governsCount} entries`);\n }\n lines.push(preflight.source === \"semantic\"\n ? \"Run context action=gather on the conflicting entries before committing.\"\n : \"Run context action=gather on these entries before committing.\");\n }\n\n if (coachingResult?.verdict) {\n try {\n const v = coachingResult.verdict;\n const failedCount = (v.criteria ?? []).filter((c: any) => !c.passed).length;\n trackQualityVerdict(wsCtx.workspaceId, {\n entry_id: entryId,\n entry_type: v.canonicalKey ?? entry.canonicalKey ?? \"\",\n tier: v.tier,\n context: \"commit\",\n passed: v.passed,\n source: coachingResult.source ?? \"heuristic\",\n criteria_total: v.criteria?.length ?? 0,\n criteria_failed: failedCount,\n llm_scheduled: v.tier !== \"passive\",\n });\n } catch { /* tracking is advisory */ }\n }\n\n if (coachingResult?.verdict && coachingResult.verdict.tier !== \"passive\" && coachingResult.verdict.criteria.length > 0) {\n const coaching = formatRubricCoaching(coachingResult);\n if (coaching) {\n lines.push(\"\");\n lines.push(coaching);\n if (!coachingResult.verdict.passed && coachingResult.verdict.tier === \"assertive\") {\n lines.push(\"\");\n lines.push(\"_This entry was committed despite quality concerns. The override has been recorded._\");\n }\n }\n }\n\n // BET-289 S5: Surface advisory guidance warnings from commit result + track\n const guidanceWarnings = result?.guidanceWarnings as Array<{ field: string; message: string; warningType: string }> | undefined;\n if (guidanceWarnings && guidanceWarnings.length > 0) {\n lines.push(\"\");\n lines.push(\"## Field Guidance Warnings (advisory)\");\n for (const w of guidanceWarnings) {\n lines.push(`- **${w.field}:** ${w.message}`);\n }\n lines.push(`_These are advisory — the entry was committed. Use \\`update-entry entryId=\"${entryId}\"\\` to address them._`);\n\n const uniqueTypes = [...new Set(guidanceWarnings.map((w) => w.warningType))];\n trackFieldQualityWarning(wsCtx.workspaceId, {\n warning_count: guidanceWarnings.length,\n warning_types: uniqueTypes,\n });\n }\n\n // Epistemic advisory for insights without evidence (BR-85)\n const epistemic = deriveEpistemicStatus(toEpistemicInput(entry as Record<string, unknown>));\n\n if (epistemic && (epistemic.level === \"hypothesis\" || epistemic.level === \"untested\")) {\n lines.push(\"\");\n lines.push(`⚠ ${formatEpistemicLine(epistemic)}`);\n if (epistemic.action) {\n lines.push(` → ${epistemic.action}`);\n }\n }\n\n // WP-316 S1a: Fetch capture contract so agents know required fields after commit.\n // Advisory — failure must not block the commit response.\n let captureContract: { requiredFields: string[]; allFields: unknown[]; captureExpectation?: string } | undefined;\n try {\n const collSlug =\n (entry.collectionSlug as string | undefined) ??\n (entry.collection?.slug as string | undefined);\n if (collSlug) {\n captureContract = await kernelQuery<{ requiredFields: string[]; allFields: unknown[]; captureExpectation?: string } | null>(\n \"chain.getCaptureContract\",\n { collectionSlug: collSlug },\n ) ?? undefined;\n }\n } catch { /* contract fetch is advisory */ }\n\n // Context-sensitive next: proposal vs. direct commit have different follow-ups\n const next: NextAction[] = isProposal\n ? [\n { tool: \"entries\", description: \"View entry\", parameters: { action: \"get\", entryId } },\n ]\n : [\n { tool: \"graph\", description: \"Discover connections\", parameters: { action: \"suggest\", entryId } },\n { tool: \"entries\", description: \"View committed entry\", parameters: { action: \"get\", entryId } },\n ];\n\n const summary = isProposal\n ? `Proposal created for ${entryId} (${entry.name}). Awaiting consent.`\n : `Committed ${entryId} (${entry.name}) to the Chain.`;\n\n const commitSuccessEnvelope = success(\n summary,\n {\n entryId,\n name: entry.name,\n outcome: isProposal ? \"proposal_created\" as const : \"committed\" as const,\n qualityVerdict: coachingResult?.verdict ?? undefined,\n source: coachingResult?.source ?? undefined,\n contradictions: advisoryWarnings.length,\n ...(epistemic ? { epistemicStatus: epistemic } : {}),\n },\n next,\n );\n // WP-316 S1a: Attach capture contract so agents know required fields for next capture.\n if (captureContract) {\n commitSuccessEnvelope.contract = captureContract;\n }\n\n return {\n content: [{ type: \"text\" as const, text: lines.join(\"\\n\") }],\n structuredContent: commitSuccessEnvelope,\n };\n })\n );\n trackWriteTool(commitTool);\n\n}\n","/**\n * Smart capture — ARCH-node-mcp (Core layer)\n * Chain: FEAT-MCP-001 (MCP Server), ARCH-flow-smart-capture\n * Rules: SOS-016 (governed draft-first), SOS-015 (unique IDs within scope)\n */\n\nimport { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { z } from \"zod\";\nimport { kernelQuery, kernelMutation, kernelCall, getWorkspaceContext, refreshWorkspaceGovernanceMode, requireWriteAccess, recordSessionActivity, getAgentSessionId } from \"../client.js\";\nimport {\n trackCaptureClassifierAutoRouted,\n trackCaptureClassifierEvaluated,\n trackCaptureClassifierFallback,\n trackCaptureQualityHints,\n trackCaptureRelationSuggestions,\n trackQualityVerdict,\n trackQualityCheck,\n trackChainEntryCommitted,\n trackCollectionClassified,\n trackFieldGuidanceApplied,\n trackClassifierDivergence,\n type ClassifierReasonCategory,\n} from \"../analytics.js\";\nimport { extractPreview } from \"./knowledge-helpers.js\";\nimport { trackWriteTool } from \"../tool-surface.js\";\nimport { resolveGapsForEntry } from \"../gap-store.js\";\nimport {\n CLASSIFIABLE_COLLECTIONS,\n type ClassifiableCollectionSlug,\n} from \"./smart-capture-routing.js\";\nimport { resolveCollection, type ResolvedCollection } from \"../lib/resolveCollection.js\";\nimport { thinWrapper, success, failure, type NextAction } from \"../envelope.js\";\nimport { FIELD_TYPE_DEFAULTS, type FieldType } from \"../lib/fieldTypes.js\";\nimport { formatFieldGuidance } from \"../lib/formatFieldGuidance.js\";\nimport { inferSourceDate } from \"../lib/inferSourceDate.js\";\nimport {\n getCollections,\n getCollectionBySlug,\n isGoverned,\n isHubCollection,\n type CollectionDoc,\n} from \"../lib/collectionCache.js\";\n\nexport {\n CLASSIFIER_AUTO_ROUTE_THRESHOLD,\n CLASSIFIABLE_COLLECTIONS,\n isClassificationAmbiguous,\n type ClassifiableCollectionSlug,\n type ClassificationResult,\n} from \"./smart-capture-routing.js\";\n\n// ── Collection Workflow Profiles ────────────────────────────────────────────\n\ninterface FieldDefault {\n key: string;\n value: unknown | \"today\" | \"infer\";\n}\n\ninterface QualityCheck {\n id: string;\n label: string;\n check: (ctx: CaptureContext) => boolean;\n suggestion?: (ctx: CaptureContext) => string;\n}\n\ninterface CollectionProfile {\n governedDraft: boolean;\n defaults: FieldDefault[];\n descriptionField: string;\n recommendedRelationTypes: string[];\n qualityChecks: QualityCheck[];\n inferField?: (ctx: CaptureContext) => Record<string, unknown>;\n}\n\ninterface CaptureContext {\n collection: string;\n name: string;\n description: string;\n context?: string;\n data: Record<string, unknown>;\n entryId: string;\n canonicalKey?: string;\n linksCreated: LinkResult[];\n linksSuggested: LinkSuggestion[];\n collectionFields: Array<{ key: string; type: string; required?: boolean; options?: string[]; label?: string; writingGuidance?: string; writingExamples?: string[] }>;\n}\n\ninterface LinkResult {\n targetEntryId: string;\n targetName: string;\n targetCollection: string;\n relationType: string;\n linkReason?: string;\n}\n\ninterface LinkSuggestion {\n entryId?: string;\n name: string;\n collection: string;\n reason: string;\n preview: string;\n}\n\nfunction normalizeMatchText(value: string): string {\n return value\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \" \")\n .replace(/\\s+/g, \" \")\n .trim();\n}\n\nfunction tokenizeMatchText(value: string): string[] {\n return normalizeMatchText(value)\n .split(\" \")\n .filter((token) => token.length >= 3 && !STOP_WORDS.has(token));\n}\n\nfunction scoreOptionMatch(\n normalizedText: string,\n textTokens: Set<string>,\n option: string,\n): number {\n const normalizedOption = normalizeMatchText(option);\n if (!normalizedOption) return 0;\n if (normalizedText.includes(normalizedOption)) return 100;\n\n const optionTokens = tokenizeMatchText(option);\n if (optionTokens.length === 0) return 0;\n\n const matchedTokens = optionTokens.filter((token) => textTokens.has(token)).length;\n if (matchedTokens === 0) return 0;\n\n const ratio = matchedTokens / optionTokens.length;\n return ratio >= 0.5 ? ratio * 10 : 0;\n}\n\nfunction inferFieldOption(\n text: string,\n collectionFields: Array<{ key: string; type: string; options?: string[] }>,\n fieldKeys: string[],\n): string {\n const normalizedText = normalizeMatchText(text);\n if (!normalizedText) return \"\";\n\n const textTokens = new Set(tokenizeMatchText(text));\n let bestOption = \"\";\n let bestScore = 0;\n\n for (const field of collectionFields) {\n if (!fieldKeys.includes(field.key) || !field.options?.length) continue;\n for (const option of field.options) {\n const score = scoreOptionMatch(normalizedText, textTokens, option);\n if (score > bestScore) {\n bestScore = score;\n bestOption = option;\n }\n }\n }\n\n return bestOption;\n}\n\n\nconst COMMON_CHECKS: Record<string, QualityCheck> = {\n clearName: {\n id: \"clear-name\",\n label: \"Clear, specific name (not vague)\",\n check: (ctx) => ctx.name.length > 10 && ![\"new tension\", \"new entry\", \"untitled\", \"test\"].includes(ctx.name.toLowerCase()),\n suggestion: () => \"Rename to something specific — describe the actual problem or concept.\",\n },\n hasDescription: {\n id: \"has-description\",\n label: \"Description provided (>50 chars)\",\n check: (ctx) => ctx.description.length > 50,\n suggestion: () => \"Add a fuller description explaining context and impact.\",\n },\n hasRelations: {\n id: \"has-relations\",\n label: \"At least 1 relation created\",\n check: (ctx) => ctx.linksCreated.length >= 1,\n suggestion: () => \"Use `graph action=suggest` and `relations action=create` to add more connections.\",\n },\n diverseRelations: {\n id: \"diverse-relations\",\n label: \"Relations span multiple collections\",\n check: (ctx) => {\n const colls = new Set(ctx.linksCreated.map((l) => l.targetCollection));\n return colls.size >= 2;\n },\n suggestion: () => \"Try linking to entries in different collections (glossary, business-rules, strategy).\",\n },\n hasType: {\n id: \"has-type\",\n label: \"Has canonical type\",\n check: (ctx) => !!ctx.data?.canonicalKey || !!ctx.canonicalKey,\n suggestion: () => \"Classify this entry with a canonical type for better context assembly. Use update-entry to set canonicalKey.\",\n },\n};\n\n// ── Strategy Category Inference (FEAT-128) ──────────────────────────────────\n\nconst STRATEGY_CATEGORY_INFERENCE_THRESHOLD = 2;\n\nconst STRATEGY_CATEGORY_SIGNALS: readonly [string, readonly RegExp[]][] = [\n [\"business-model\", [/pricing/, /revenue/, /unit economics/, /cost structure/, /monetiz/, /margin/, /per.?seat/, /subscription/, /freemium/]],\n [\"vision\", [/vision/, /aspirational/, /future state/, /world where/]],\n [\"purpose\", [/purpose/, /why we exist/, /mission/, /reason for being/]],\n [\"goal\", [/goal/, /metric/, /target/, /kpi/, /okr/, /critical number/, /measur/]],\n [\"principle\", [/we believe/, /guiding principle/, /core belief/, /philosophy/]],\n [\"product-area\", [/product area/, /module/, /surface/, /capability area/]],\n [\"audience\", [/audience/, /persona/, /user segment/, /icp/, /target market/]],\n [\"insight\", [/insight/, /we learned/, /we observed/, /pattern/]],\n [\"opportunity\", [/opportunity/, /whitespace/, /gap/, /underserved/]],\n] as const;\n\n/**\n * Infer strategy sub-category from entry text. Returns null when confidence\n * is too low (exactly 1 signal match) — the caller decides how to handle\n * the abstention. Returns \"strategy\" as generic fallback when no signals\n * match at all (entry is in strategy collection but has no sub-type signals).\n *\n * ecosystem-layer is intentionally excluded: too niche to distinguish from\n * product-area by keywords alone — must be set explicitly via data.category.\n */\nexport function inferStrategyCategory(name: string, description: string): string | null {\n const text = `${name} ${description}`.toLowerCase();\n let bestCategory: string | null = null;\n let bestScore = 0;\n for (const [cat, signals] of STRATEGY_CATEGORY_SIGNALS) {\n const score = signals.reduce((s, rx) => s + (rx.test(text) ? 1 : 0), 0);\n if (score > bestScore) { bestScore = score; bestCategory = cat; }\n }\n if (bestCategory && bestScore >= STRATEGY_CATEGORY_INFERENCE_THRESHOLD) return bestCategory;\n if (bestScore === 0) return \"strategy\";\n return null;\n}\n\n// ── Collection Profiles ─────────────────────────────────────────────────────\n// BET-281: Base profile fields (governed, descriptionField) are derived from DB\n// metadata via buildRuntimeProfile(). Collection-specific enrichments\n// (inferField, custom quality checks with contextual suggestions) are kept in\n// PROFILE_ENRICHMENTS — these contain logic that cannot be derived from metadata.\n// getProfile(slug) merges DB-derived base + enrichment + FALLBACK_PROFILE.\n\ntype ProfileEnrichment = Partial<CollectionProfile> & {\n /** Enrichments may override descriptionField when the DB metadata doesn't capture it yet. */\n descriptionField?: string;\n};\n\nconst PROFILE_ENRICHMENTS: Map<string, ProfileEnrichment> = new Map([\n [\"tensions\", {\n governedDraft: false,\n descriptionField: \"description\",\n defaults: [\n { key: \"priority\", value: \"medium\" },\n { key: \"raised\", value: \"infer\" },\n { key: \"severity\", value: \"infer\" },\n ],\n recommendedRelationTypes: [\"surfaces_tension_in\", \"references\", \"belongs_to\", \"related_to\"],\n inferField: (ctx: CaptureContext) => {\n const fields: Record<string, unknown> = {};\n const text = `${ctx.name} ${ctx.description}`;\n const raised = inferFieldOption(text, ctx.collectionFields, [\"raised\"]);\n const affectedArea = inferFieldOption(text, ctx.collectionFields, [\"affectedArea\", \"area\"]);\n if (raised) fields.raised = raised;\n if (text.toLowerCase().includes(\"critical\") || text.toLowerCase().includes(\"blocker\")) {\n fields.severity = \"critical\";\n } else if (text.toLowerCase().includes(\"bottleneck\") || text.toLowerCase().includes(\"scaling\") || text.toLowerCase().includes(\"breaking\")) {\n fields.severity = \"high\";\n } else {\n fields.severity = \"medium\";\n }\n if (affectedArea) fields.affectedArea = affectedArea;\n return fields;\n },\n qualityChecks: [\n COMMON_CHECKS.clearName,\n COMMON_CHECKS.hasDescription,\n COMMON_CHECKS.hasRelations,\n COMMON_CHECKS.hasType,\n {\n id: \"has-severity\",\n label: \"Severity specified\",\n check: (ctx) => !!ctx.data.severity && ctx.data.severity !== \"\",\n suggestion: (ctx) => {\n const text = `${ctx.name} ${ctx.description}`.toLowerCase();\n const inferred = text.includes(\"critical\") ? \"critical\" : text.includes(\"bottleneck\") ? \"high\" : \"medium\";\n return `Set severity — suggest: ${inferred} (based on description keywords).`;\n },\n },\n {\n id: \"has-affected-area\",\n label: \"Affected area identified\",\n check: (ctx) => !!ctx.data.affectedArea && ctx.data.affectedArea !== \"\",\n suggestion: (ctx) => {\n const area = inferFieldOption(`${ctx.name} ${ctx.description}`, ctx.collectionFields, [\"affectedArea\", \"area\"]);\n return area\n ? `Set affectedArea — suggest: \"${area}\" (inferred from content).`\n : \"Specify which product area or domain this tension impacts.\";\n },\n },\n ],\n }],\n\n [\"business-rules\", {\n governedDraft: true,\n descriptionField: \"description\",\n defaults: [\n { key: \"severity\", value: \"medium\" },\n { key: \"domain\", value: \"infer\" },\n ],\n recommendedRelationTypes: [\"governs\", \"references\", \"conflicts_with\", \"related_to\"],\n inferField: (ctx: CaptureContext) => {\n const fields: Record<string, unknown> = {};\n const domain = inferFieldOption(`${ctx.name} ${ctx.description}`, ctx.collectionFields, [\"domain\"]);\n if (domain) fields.domain = domain;\n return fields;\n },\n qualityChecks: [\n COMMON_CHECKS.clearName,\n COMMON_CHECKS.hasDescription,\n COMMON_CHECKS.hasRelations,\n COMMON_CHECKS.hasType,\n {\n id: \"has-rationale\",\n label: \"Rationale provided\",\n check: (ctx) => typeof ctx.data.rationale === \"string\" && ctx.data.rationale.length > 10,\n suggestion: () => \"Add a rationale explaining why this rule exists via `update-entry`.\",\n },\n {\n id: \"has-domain\",\n label: \"Domain specified\",\n check: (ctx) => !!ctx.data.domain && ctx.data.domain !== \"\",\n suggestion: (ctx) => {\n const domain = inferFieldOption(`${ctx.name} ${ctx.description}`, ctx.collectionFields, [\"domain\"]);\n return domain\n ? `Set domain — suggest: \"${domain}\" (inferred from content).`\n : \"Specify the business domain this rule belongs to.\";\n },\n },\n ],\n }],\n\n [\"glossary\", {\n governedDraft: true,\n descriptionField: \"canonical\",\n defaults: [\n { key: \"category\", value: \"infer\" },\n ],\n recommendedRelationTypes: [\"defines_term_for\", \"confused_with\", \"related_to\", \"references\"],\n inferField: (ctx: CaptureContext) => {\n const fields: Record<string, unknown> = {};\n const category = inferFieldOption(`${ctx.name} ${ctx.description}`, ctx.collectionFields, [\"category\"]);\n if (category) fields.category = category;\n return fields;\n },\n qualityChecks: [\n COMMON_CHECKS.clearName,\n COMMON_CHECKS.hasType,\n {\n id: \"has-canonical\",\n label: \"Canonical definition provided (>20 chars)\",\n check: (ctx) => {\n const canonical = ctx.data.canonical;\n return typeof canonical === \"string\" && canonical.length > 20;\n },\n suggestion: () => \"Add a clear canonical definition — this is the single source of truth for this term.\",\n },\n COMMON_CHECKS.hasRelations,\n {\n id: \"has-category\",\n label: \"Category assigned\",\n check: (ctx) => !!ctx.data.category && ctx.data.category !== \"\",\n suggestion: () => \"Assign a category (e.g., 'Platform & Architecture', 'Governance & Process').\",\n },\n ],\n }],\n\n [\"decisions\", {\n governedDraft: false,\n descriptionField: \"rationale\",\n defaults: [\n { key: \"decidedBy\", value: \"infer\" },\n { key: \"confidence\", value: \"exploring\" },\n ],\n recommendedRelationTypes: [\"informs\", \"references\", \"replaces\", \"related_to\"],\n inferField: (ctx: CaptureContext) => {\n const fields: Record<string, unknown> = {};\n const decidedBy = inferFieldOption(`${ctx.name} ${ctx.description}`, ctx.collectionFields, [\"decidedBy\", \"owner\"]);\n if (decidedBy) fields.decidedBy = decidedBy;\n return fields;\n },\n qualityChecks: [\n COMMON_CHECKS.clearName,\n COMMON_CHECKS.hasType,\n {\n id: \"has-rationale\",\n label: \"Rationale provided (>30 chars)\",\n check: (ctx) => {\n const rationale = ctx.data.rationale;\n return typeof rationale === \"string\" && rationale.length > 30;\n },\n suggestion: () => \"Explain why this decision was made — what was considered and rejected?\",\n },\n COMMON_CHECKS.hasRelations,\n {\n id: \"has-date\",\n label: \"Decision date recorded\",\n check: (ctx) => !!ctx.data.date && ctx.data.date !== \"\",\n suggestion: () => \"Record when this decision was made.\",\n },\n ],\n }],\n\n [\"features\", {\n governedDraft: false,\n descriptionField: \"description\",\n defaults: [] as FieldDefault[],\n recommendedRelationTypes: [\"belongs_to\", \"depends_on\", \"surfaces_tension_in\", \"related_to\"],\n qualityChecks: [\n COMMON_CHECKS.clearName,\n COMMON_CHECKS.hasDescription,\n COMMON_CHECKS.hasRelations,\n COMMON_CHECKS.hasType,\n {\n id: \"has-owner\",\n label: \"Owner assigned\",\n check: (ctx: CaptureContext) => !!ctx.data.owner && ctx.data.owner !== \"\",\n suggestion: () => \"Assign an owner team or product area.\",\n },\n {\n id: \"has-rationale\",\n label: \"Rationale documented\",\n check: (ctx: CaptureContext) => !!ctx.data.rationale && String(ctx.data.rationale).length > 20,\n suggestion: () => \"Explain why this feature matters — what problem does it solve?\",\n },\n ],\n } satisfies CollectionProfile],\n\n [\"audiences\", {\n governedDraft: false,\n descriptionField: \"description\",\n defaults: [],\n recommendedRelationTypes: [\"fills_slot\", \"informs\", \"related_to\", \"references\"],\n qualityChecks: [\n COMMON_CHECKS.clearName,\n COMMON_CHECKS.hasDescription,\n COMMON_CHECKS.hasRelations,\n COMMON_CHECKS.hasType,\n {\n id: \"has-behaviors\",\n label: \"Behaviors described\",\n check: (ctx) => typeof ctx.data.behaviors === \"string\" && ctx.data.behaviors.length > 20,\n suggestion: () => \"Describe how this audience segment behaves — what do they do, what tools do they use?\",\n },\n ],\n }],\n\n [\"strategy\", {\n governedDraft: true,\n descriptionField: \"description\",\n defaults: [],\n recommendedRelationTypes: [\"informs\", \"governs\", \"belongs_to\", \"related_to\"],\n inferField: (ctx: CaptureContext) => {\n if (ctx.data?.category) return {};\n const category = inferStrategyCategory(ctx.name, ctx.description);\n return category ? { category } : {};\n },\n qualityChecks: [\n COMMON_CHECKS.clearName,\n COMMON_CHECKS.hasDescription,\n COMMON_CHECKS.hasRelations,\n COMMON_CHECKS.hasType,\n COMMON_CHECKS.diverseRelations,\n ],\n }],\n\n [\"maps\", {\n governedDraft: false,\n descriptionField: \"description\",\n defaults: [],\n recommendedRelationTypes: [\"fills_slot\", \"references\", \"related_to\"],\n qualityChecks: [\n COMMON_CHECKS.clearName,\n COMMON_CHECKS.hasDescription,\n ],\n }],\n\n [\"chains\", {\n governedDraft: false,\n descriptionField: \"description\",\n defaults: [],\n recommendedRelationTypes: [\"informs\", \"references\", \"related_to\"],\n qualityChecks: [\n COMMON_CHECKS.clearName,\n COMMON_CHECKS.hasDescription,\n ],\n }],\n\n [\"work-packages\", {\n governedDraft: false,\n descriptionField: \"description\",\n defaults: [],\n recommendedRelationTypes: [\"part_of\", \"depends_on\", \"blocks\", \"informs\", \"references\", \"related_to\"],\n qualityChecks: [\n COMMON_CHECKS.clearName,\n COMMON_CHECKS.hasDescription,\n COMMON_CHECKS.hasRelations,\n ],\n }],\n\n [\"principles\", {\n governedDraft: true,\n descriptionField: \"description\",\n defaults: [\n { key: \"severity\", value: \"high\" },\n { key: \"category\", value: \"infer\" },\n ],\n recommendedRelationTypes: [\"governs\", \"informs\", \"references\", \"related_to\"],\n inferField: (ctx: CaptureContext) => {\n const fields: Record<string, unknown> = {};\n const category = inferFieldOption(`${ctx.name} ${ctx.description}`, ctx.collectionFields, [\"category\"]);\n if (category) fields.category = category;\n return fields;\n },\n qualityChecks: [\n COMMON_CHECKS.clearName,\n COMMON_CHECKS.hasDescription,\n COMMON_CHECKS.hasRelations,\n COMMON_CHECKS.hasType,\n {\n id: \"has-rationale\",\n label: \"Rationale provided — why this principle matters\",\n check: (ctx) => typeof ctx.data.rationale === \"string\" && ctx.data.rationale.length > 20,\n suggestion: () => \"Explain why this principle exists and what goes wrong without it.\",\n },\n ],\n }],\n\n [\"standards\", {\n governedDraft: true,\n descriptionField: \"description\",\n defaults: [],\n recommendedRelationTypes: [\"governs\", \"defines_term_for\", \"references\", \"related_to\"],\n qualityChecks: [\n COMMON_CHECKS.clearName,\n COMMON_CHECKS.hasDescription,\n COMMON_CHECKS.hasRelations,\n COMMON_CHECKS.hasType,\n ],\n }],\n\n [\"tracking-events\", {\n governedDraft: false,\n descriptionField: \"description\",\n defaults: [],\n recommendedRelationTypes: [\"references\", \"belongs_to\", \"related_to\"],\n qualityChecks: [\n COMMON_CHECKS.clearName,\n COMMON_CHECKS.hasDescription,\n ],\n }],\n\n [\"insights\", {\n governedDraft: false,\n descriptionField: \"description\",\n defaults: [\n { key: \"evidenceStrength\", value: \"anecdotal\" },\n ],\n recommendedRelationTypes: [\"validates\", \"invalidates\", \"informs\", \"related_to\"],\n qualityChecks: [\n COMMON_CHECKS.clearName,\n COMMON_CHECKS.hasDescription,\n COMMON_CHECKS.hasRelations,\n COMMON_CHECKS.hasType,\n {\n id: \"has-evidence-link\",\n label: \"Evidence link exists (validates or invalidates)\",\n check: (ctx) => ctx.linksCreated.some((l) => l.relationType === \"validates\" || l.relationType === \"invalidates\"),\n suggestion: () => \"Link this insight to the assumption or claim it validates/invalidates using `relations action=create type=validates`.\",\n },\n {\n id: \"has-source\",\n label: \"Source documented\",\n check: (ctx) => !!ctx.data?.source && String(ctx.data.source).length > 0,\n suggestion: () => \"Document where this insight came from (research, data, user interview, etc.).\",\n },\n ],\n }],\n\n [\"assumptions\", {\n governedDraft: false,\n descriptionField: \"belief\",\n defaults: [\n { key: \"risk\", value: \"medium\" },\n { key: \"evidenceStrength\", value: \"unvalidated\" },\n ],\n recommendedRelationTypes: [\"depends_on\", \"informs\", \"related_to\", \"validates\", \"invalidates\"],\n qualityChecks: [\n COMMON_CHECKS.clearName,\n {\n id: \"has-belief\",\n label: \"Belief statement provided (>30 chars)\",\n check: (ctx) => !!ctx.data?.belief && String(ctx.data.belief).length > 30,\n suggestion: () => \"Write the assumption as a clear, testable belief statement.\",\n },\n COMMON_CHECKS.hasRelations,\n COMMON_CHECKS.hasType,\n {\n id: \"has-test-method\",\n label: \"Test method described\",\n check: (ctx) => !!ctx.data?.testMethod && String(ctx.data.testMethod).length > 0,\n suggestion: () => \"Describe how this assumption could be tested or validated.\",\n },\n ],\n }],\n\n [\"architecture\", {\n governedDraft: true,\n descriptionField: \"description\",\n defaults: [],\n recommendedRelationTypes: [\"belongs_to\", \"depends_on\", \"governs\", \"references\", \"related_to\"],\n qualityChecks: [\n COMMON_CHECKS.clearName,\n COMMON_CHECKS.hasDescription,\n COMMON_CHECKS.hasRelations,\n COMMON_CHECKS.hasType,\n {\n id: \"has-layer\",\n label: \"Architecture layer identified\",\n check: (ctx) => !!ctx.data?.layer && String(ctx.data.layer).length > 0,\n suggestion: () => \"Specify which architecture layer this belongs to (L1-L7).\",\n },\n ],\n }],\n\n [\"landscape\", {\n governedDraft: false,\n descriptionField: \"description\",\n defaults: [],\n recommendedRelationTypes: [\"references\", \"related_to\", \"fills_slot\"],\n qualityChecks: [\n COMMON_CHECKS.clearName,\n COMMON_CHECKS.hasDescription,\n COMMON_CHECKS.hasRelations,\n COMMON_CHECKS.hasType,\n ],\n }],\n]);\n\nconst FALLBACK_PROFILE: CollectionProfile = {\n governedDraft: false,\n descriptionField: \"description\",\n defaults: [],\n recommendedRelationTypes: [\"related_to\", \"references\"],\n qualityChecks: [\n COMMON_CHECKS.clearName,\n COMMON_CHECKS.hasDescription,\n COMMON_CHECKS.hasRelations,\n COMMON_CHECKS.hasType,\n ],\n};\n\n/**\n * BET-281: Build a runtime profile by merging DB-derived metadata with\n * collection-specific enrichments. The DB provides `governed`,\n * `qualityCriteria`, and field metadata. Enrichments provide inferField,\n * custom quality checks, and descriptionField overrides.\n */\nasync function buildRuntimeProfile(slug: string): Promise<CollectionProfile> {\n const col = await getCollectionBySlug(slug);\n const enrichment = PROFILE_ENRICHMENTS.get(slug);\n\n if (!col && !enrichment) return FALLBACK_PROFILE;\n\n // DB-derived base\n const governedDraft = col?.governed ?? enrichment?.governedDraft ?? false;\n\n // Description field: enrichment override > DB field detection > \"description\"\n let descriptionField = enrichment?.descriptionField ?? \"description\";\n if (!enrichment?.descriptionField && col) {\n // Auto-detect from field metadata: first body/textarea field\n const bodyField = col.fields.find(\n (f) => f.zone === \"body\" || f.displayHint === \"textarea\",\n );\n if (bodyField) descriptionField = bodyField.key;\n }\n\n // Quality checks: DB qualityCriteria merged with enrichment checks\n let qualityChecks: QualityCheck[] = [\n COMMON_CHECKS.clearName,\n COMMON_CHECKS.hasDescription,\n COMMON_CHECKS.hasRelations,\n COMMON_CHECKS.hasType,\n ];\n if (enrichment?.qualityChecks) {\n qualityChecks = enrichment.qualityChecks;\n } else if (col?.qualityCriteria?.length) {\n // Build quality checks from DB qualityCriteria\n const dbChecks: QualityCheck[] = col.qualityCriteria.map((qc) => ({\n id: `db-${qc.field}-${qc.rule}`,\n label: `${qc.field} ${qc.rule === \"required\" ? \"provided\" : qc.rule === \"min_length\" ? `min ${qc.value} chars` : `matches ${qc.value}`}`,\n check: (ctx: CaptureContext) => {\n const val = ctx.data[qc.field];\n if (qc.rule === \"required\") return val !== undefined && val !== null && val !== \"\";\n if (qc.rule === \"min_length\") return typeof val === \"string\" && val.length >= Number(qc.value ?? 0);\n if (qc.rule === \"pattern\") return typeof val === \"string\" && new RegExp(qc.value ?? \"\").test(val);\n return true;\n },\n suggestion: () => `Fill in ${qc.field} (${qc.rule}).`,\n }));\n // Combine common checks with DB-derived checks\n qualityChecks = [\n COMMON_CHECKS.clearName,\n COMMON_CHECKS.hasDescription,\n ...dbChecks,\n COMMON_CHECKS.hasRelations,\n COMMON_CHECKS.hasType,\n ];\n }\n\n return {\n governedDraft,\n descriptionField,\n defaults: enrichment?.defaults ?? [],\n recommendedRelationTypes: enrichment?.recommendedRelationTypes ?? FALLBACK_PROFILE.recommendedRelationTypes,\n qualityChecks,\n inferField: enrichment?.inferField,\n };\n}\n\n/** Per-invocation profile cache — keyed by slug. */\nlet profileCache: Map<string, CollectionProfile> | null = null;\n\n/**\n * Get a collection's profile, cached per-invocation.\n * Merges DB metadata with collection-specific enrichments.\n */\nexport async function getProfile(slug: string): Promise<CollectionProfile> {\n if (!profileCache) profileCache = new Map();\n const cached = profileCache.get(slug);\n if (cached) return cached;\n const profile = await buildRuntimeProfile(slug);\n profileCache.set(slug, profile);\n return profile;\n}\n\n/** Reset profile cache (call with resetCollectionCache for new invocation). */\nexport function resetProfileCache(): void {\n profileCache = null;\n}\n\n// ── Auto-Linking Logic ──────────────────────────────────────────────────────\n\nfunction extractSearchTerms(name: string, description: string): string {\n const text = `${name} ${description}`;\n return text\n .replace(/[^\\w\\s]/g, \" \")\n .split(/\\s+/)\n .filter((w) => w.length > 3)\n .slice(0, 8)\n .join(\" \");\n}\n\ninterface LinkConfidenceResult {\n score: number;\n reason: string;\n}\n\n// BET-281: hubCollectionCache populated lazily from collectionCache.isHubCollection()\n// to avoid async in the hot scoring path. Populated by populateHubCache() before scoring.\nlet hubCollectionCache: Set<string> | null = null;\n\nasync function populateHubCache(): Promise<void> {\n if (hubCollectionCache !== null) return;\n const cols = await getCollections();\n hubCollectionCache = new Set(\n cols\n .filter((c) => c.governanceRole === \"steering\" || c.thinkingLayer === \"strategy\")\n .map((c) => c.slug),\n );\n}\n\nfunction resetHubCache(): void {\n hubCollectionCache = null;\n}\n\nfunction computeLinkConfidence(\n candidate: { name: string; data?: any; entryId?: string },\n sourceName: string,\n sourceDescription: string,\n sourceCollection: string,\n candidateCollection: string,\n): LinkConfidenceResult {\n const text = `${sourceName} ${sourceDescription}`.toLowerCase();\n const candidateName = candidate.name.toLowerCase();\n let score = 0;\n const reasons: string[] = [];\n\n if (text.includes(candidateName) && candidateName.length > 3) {\n score += 40;\n reasons.push(\"name match\");\n }\n\n const candidateWords = candidateName.split(/\\s+/).filter((w) => w.length > 3);\n const matchingWords = candidateWords.filter((w) => text.includes(w));\n const wordScore = (matchingWords.length / Math.max(candidateWords.length, 1)) * 30;\n score += wordScore;\n if (matchingWords.length > 0) {\n reasons.push(`word overlap (${matchingWords.slice(0, 3).join(\", \")})`);\n }\n\n // BET-281: Hub collections derived from thinkingLayer === 'strategy' via collectionCache.\n if (hubCollectionCache?.has(candidateCollection)) {\n score += 15;\n reasons.push(\"hub collection\");\n }\n\n if (candidateCollection !== sourceCollection) {\n score += 10;\n reasons.push(\"cross-collection\");\n }\n\n const finalScore = Math.min(score, 100);\n const reason = reasons.length > 0 ? reasons.join(\" + \") : \"low relevance\";\n return { score: finalScore, reason };\n}\n\ninterface RelationTypeResult {\n type: string;\n reason: string;\n}\n\nfunction inferRelationType(\n sourceCollection: string,\n targetCollection: string,\n profile: CollectionProfile,\n): RelationTypeResult {\n const typeMap: Record<string, Record<string, string>> = {\n tensions: {\n glossary: \"surfaces_tension_in\",\n \"business-rules\": \"references\",\n strategy: \"belongs_to\",\n features: \"surfaces_tension_in\",\n decisions: \"references\",\n },\n \"business-rules\": {\n glossary: \"references\",\n features: \"governs\",\n strategy: \"belongs_to\",\n tensions: \"references\",\n },\n glossary: {\n features: \"defines_term_for\",\n \"business-rules\": \"references\",\n strategy: \"references\",\n },\n decisions: {\n features: \"informs\",\n \"business-rules\": \"references\",\n strategy: \"references\",\n tensions: \"references\",\n },\n };\n\n const mapped = typeMap[sourceCollection]?.[targetCollection];\n const type = mapped ?? profile.recommendedRelationTypes[0] ?? \"related_to\";\n const reason = mapped\n ? `collection pair (${sourceCollection} → ${targetCollection})`\n : `profile default (${profile.recommendedRelationTypes[0] ?? \"related_to\"})`;\n return { type, reason };\n}\n\n// ── Quality Scoring ─────────────────────────────────────────────────────────\n\ninterface QualityResult {\n score: number;\n maxScore: number;\n checks: Array<{ id: string; label: string; passed: boolean; suggestion?: string }>;\n}\n\nfunction scoreQuality(ctx: CaptureContext, profile: CollectionProfile): QualityResult {\n const checks = profile.qualityChecks.map((qc) => {\n const passed = qc.check(ctx);\n return {\n id: qc.id,\n label: qc.label,\n passed,\n suggestion: passed ? undefined : qc.suggestion?.(ctx),\n };\n });\n\n const passed = checks.filter((c) => c.passed).length;\n const total = checks.length;\n const score = total > 0 ? Math.round((passed / total) * 10) : 10;\n\n return { score, maxScore: 10, checks };\n}\n\nexport function formatQualityReport(result: QualityResult): string {\n const failed = result.checks.filter((c) => !c.passed);\n const reason = failed.length > 0\n ? ` because ${failed.map((c) => c.suggestion ?? c.label.toLowerCase()).join(\"; \")}`\n : \"\";\n const lines: string[] = [`## Quality: ${result.score}/${result.maxScore}${reason}`];\n for (const check of result.checks) {\n const icon = check.passed ? \"[x]\" : \"[ ]\";\n const suggestion = check.passed ? \"\" : ` — ${check.suggestion ?? check.label}`;\n lines.push(`${icon} ${check.label}${suggestion}`);\n }\n return lines.join(\"\\n\");\n}\n\n// ── Exported: quality check for existing entries ─────────────────────────────\n\nexport async function checkEntryQuality(entryId: string): Promise<{ text: string; quality: QualityResult }> {\n const entry = await kernelQuery<any>(\"chain.getEntry\", { entryId });\n if (!entry) {\n return {\n text: `Entry \\`${entryId}\\` not found. Try search to find the right ID.`,\n quality: { score: 0, maxScore: 10, checks: [] },\n };\n }\n\n // BET-281: Use collectionCache instead of direct listCollections call.\n const collections = await getCollections();\n const collMap = new Map<string, string>();\n for (const c of collections) collMap.set(c._id, c.slug);\n const collectionSlug = collMap.get(entry.collectionId) ?? \"unknown\";\n\n const profile = await getProfile(collectionSlug);\n\n const relations = await kernelQuery<any[]>(\"chain.listEntryRelations\", { entryId });\n const linksCreated: LinkResult[] = [];\n for (const r of relations) {\n const otherId = r.fromId === entry._id ? r.toId : r.fromId;\n linksCreated.push({\n targetEntryId: otherId,\n targetName: \"\",\n targetCollection: \"\",\n relationType: r.type,\n });\n }\n\n const descField = profile.descriptionField;\n const description = typeof entry.data?.[descField] === \"string\" ? entry.data[descField] : \"\";\n\n const ctx: CaptureContext = {\n collection: collectionSlug,\n name: entry.name,\n description,\n data: entry.data ?? {},\n entryId: entry.entryId ?? \"\",\n canonicalKey: entry.canonicalKey,\n linksCreated,\n linksSuggested: [],\n collectionFields: [],\n };\n\n const quality = scoreQuality(ctx, profile);\n\n const lines: string[] = [\n `# Quality Check: ${entry.entryId ?? entry.name}`,\n `**${entry.name}** in \\`${collectionSlug}\\` [${entry.status}]`,\n \"\",\n formatQualityReport(quality),\n ];\n\n if (quality.score < 10) {\n const failedChecks = quality.checks.filter((c) => !c.passed && c.suggestion);\n if (failedChecks.length > 0) {\n lines.push(\"\");\n lines.push(`_To improve: use \\`update-entry\\` to fill missing fields, or \\`relations action=create\\` to add connections._`);\n }\n }\n\n return { text: lines.join(\"\\n\"), quality };\n}\n\n// ── Tool Registration ───────────────────────────────────────────────────────\n\n// BET-281: GOVERNED_COLLECTIONS replaced by runtime isGoverned() from collectionCache.\n// The `governed` field on each collection doc is the SSOT.\n\nconst AUTO_LINK_CONFIDENCE_THRESHOLD = 35;\nconst MAX_AUTO_LINKS = 5;\nconst MAX_SUGGESTIONS = 5;\n\n/** BR-111: entryId only for business-rules and standards; format BR-NNN or STD-NNN. All other collections use auto-generated IDs. */\nconst BR_STD_ENTRY_ID_REGEX = /^(BR|STD)-\\d+$/;\nconst entryIdSchema = z.string().regex(BR_STD_ENTRY_ID_REGEX).optional().describe(\n \"Only for business-rules and standards. Must match BR-NNN or STD-NNN. Omit for all other collections — IDs are auto-generated.\"\n);\n\nexport const captureSchema = z.object({\n collection: z.string().optional().describe(\"Collection slug, e.g. 'tensions', 'business-rules', 'glossary', 'decisions'. Optional — classifier auto-routes when omitted.\"),\n name: z.string().describe(\"Display name — be specific (e.g. 'Convex adjacency list won't scale for graph traversal')\"),\n description: z.string().describe(\"Full context — what's happening, why it matters, what you observed\"),\n context: z.string().optional().describe(\"Optional additional context (e.g. 'Observed during context gather calls taking 700ms+')\"),\n entryId: entryIdSchema,\n canonicalKey: z.string().optional().describe(\"Semantic type (e.g. 'decision', 'tension', 'vision'). Auto-assigned from collection if omitted.\"),\n data: z.record(z.unknown()).optional().describe(\"Explicit field values when you know the schema (e.g. canonical_key, cardinality_rule, required_fields). Merged with inferred values; user-provided wins.\"),\n links: z.array(z.object({\n to: z.string().describe(\"Target entry ID (e.g. 'BR-64', 'ARCH-8')\"),\n type: z.string().describe(\"Relation type (e.g. 'governs', 'related_to', 'informs')\"),\n })).optional().describe(\"Relations to create after capture. Skips auto-link discovery when provided.\"),\n autoCommit: z.boolean().optional().describe(\n \"If true, commits the entry immediately after capture + linking. \" +\n \"If omitted, Open mode workspaces auto-commit by default and consensus/role modes stay draft-first.\"\n ),\n sourceRef: z.string().optional().describe(\"URI or path of the source document backing this entry (e.g. 'meeting-2026-03-28.md', 'import://batch-5'). Stored as top-level entry field, not in data.\"),\n sourceExcerpt: z.string().optional().describe(\"Verbatim excerpt from the source that backs this entry's claims. Stored as top-level entry field, not in data.\"),\n // WP-316 S3: Preview gate — dry-run mode. Returns what would happen, no DB writes.\n preview: z.boolean().optional().describe(\"If true, validates the capture without writing. Returns what would happen. Default false.\"),\n // WP-318 S2: Pre-write grounding — run link suggestion before creating entry.\n suggestOnly: z.boolean().optional().describe(\n \"If true, runs pre-write grounding (suggestLinksForCapture) and returns a groundingReport WITHOUT creating any entry. \" +\n \"Use to preview graph participation before committing. Default false.\"\n ),\n // WP-318 S2: Format for groundingReport in response.\n format: z.enum([\"agent\", \"human\"]).optional().describe(\n \"Response format for grounding data. 'agent' (default): full JSON groundingReport. \" +\n \"'human': compressed summary string appended to the capture summary.\"\n ),\n});\n\nexport const batchCaptureSchema = z.object({\n entries: z.array(z.object({\n collection: z.string().optional().describe(\"Collection slug. Optional — auto-classified via LLM when omitted (FEAT-160).\"),\n name: z.string().describe(\"Display name\"),\n description: z.string().describe(\"Full context / definition\"),\n entryId: entryIdSchema,\n data: z.record(z.unknown()).optional().describe(\"Explicit field values (e.g. urgency, status, assignee). Merged with inferred values; user-provided wins.\"),\n canonicalKey: z.string().optional().describe(\"Semantic type (e.g. 'decision', 'tension', 'work_package'). Enables work-package redirect in createEntry when collection is 'chains'.\"),\n sourceRef: z.string().optional().describe(\"URI or path of the source document backing this entry (e.g. 'meeting-2026-03-28.md', 'import://batch-5'). Stored as top-level entry field, not in data.\"),\n sourceExcerpt: z.string().optional().describe(\"Verbatim excerpt from the source that backs this entry's claims. Stored as top-level entry field, not in data.\"),\n })).min(1).max(50).describe(\"Array of entries to capture\"),\n autoCommit: z\n .boolean()\n .optional()\n .describe(\n \"If true, commits created entries immediately after linking. \" +\n \"If omitted, Open mode workspaces commit by default and consensus/role modes stay draft-first.\"\n ),\n // WP-316 S3: Preview gate — dry-run mode. Returns what would happen, no DB writes.\n preview: z.boolean().optional().describe(\"If true, validates all captures without writing. Returns what would happen. Default false.\"),\n});\n\nexport const captureClassifierSchema = z.object({\n enabled: z.boolean(),\n autoRouted: z.boolean(),\n agrees: z.boolean(),\n abstained: z.boolean(),\n topConfidence: z.number(),\n confidence: z.number(),\n reasons: z.array(z.string()),\n candidates: z.array(\n z.object({\n collection: z.string(),\n signalScore: z.number().optional(),\n confidence: z.number(),\n /** WP-316 S2: required-field cost — how many fields the agent must supply for this collection. */\n requiredFieldCount: z.number().optional(),\n }),\n ),\n agentProvidedCollection: z.string().optional(),\n overrideCommand: z.string().optional(),\n classifiedBy: z.enum([\"llm\", \"heuristic\", \"explicit\"]).optional(),\n confidenceTier: z.enum([\"high\", \"medium\", \"low\"]).optional(),\n reasoning: z.string().optional(),\n});\n\nexport type CaptureClassifierMetadata = z.infer<typeof captureClassifierSchema>;\n\ntype CaptureToolResult = {\n content: Array<{ type: \"text\"; text: string }>;\n structuredContent?: z.infer<typeof captureOutputSchema>;\n};\n\ntype CollectionResolution = {\n resolvedCollection?: string;\n classifierMeta?: CaptureClassifierMetadata;\n earlyResult?: CaptureToolResult;\n};\n\nfunction trackClassifierTelemetry(params: {\n workspaceId: string;\n predictedCollection: string;\n confidence: number;\n autoRouted: boolean;\n reasonCategory: ClassifierReasonCategory;\n explicitCollectionProvided: boolean;\n outcome: \"auto-routed\" | \"fallback\";\n}): void {\n const telemetry = {\n predicted_collection: params.predictedCollection,\n confidence: params.confidence,\n auto_routed: params.autoRouted,\n reason_category: params.reasonCategory,\n explicit_collection_provided: params.explicitCollectionProvided,\n };\n\n trackCaptureClassifierEvaluated(params.workspaceId, telemetry);\n if (params.outcome === \"auto-routed\") {\n trackCaptureClassifierAutoRouted(params.workspaceId, telemetry);\n return;\n }\n trackCaptureClassifierFallback(params.workspaceId, telemetry);\n}\n\nfunction buildClassifierUnknownResult(): CaptureToolResult {\n return {\n content: [{\n type: \"text\" as const,\n text:\n \"I could not infer a collection confidently from this input.\\n\\n\" +\n \"Please provide `collection`, or rewrite with clearer intent (decision/problem/definition/insight/bet).\",\n }],\n structuredContent: failure(\n \"VALIDATION_ERROR\",\n \"Could not infer collection from input.\",\n \"Provide collection explicitly, or rewrite with clearer intent.\",\n [{ tool: \"collections\", description: \"List available collections\", parameters: { action: \"list\" } }],\n { classifier: { enabled: true, autoRouted: false, agrees: false, abstained: true, topConfidence: 0, confidence: 0, reasons: [], candidates: [] } },\n ),\n };\n}\n\nfunction buildProvisionedCollectionSuggestions(\n candidates: Array<{ collection: string; signalScore?: number; confidence: number }>,\n): string {\n return candidates.length\n ? candidates\n .map((c) => `- \\`${c.collection}\\` (${c.signalScore ?? c.confidence}% confidence)`)\n .join(\"\\n\")\n : \"- No collection candidates were inferred confidently.\";\n}\n\nfunction buildLowConfidenceResult(\n resolved: ResolvedCollection,\n classifierMeta: CaptureClassifierMetadata,\n): CaptureToolResult {\n const allCandidates = [\n { collection: resolved.collection, confidence: resolved.confidence },\n ...resolved.alternatives,\n ];\n // WP-316 S2: enrich suggestions with requiredFieldCount from classifierMeta.candidates\n const candidateFieldCounts = new Map<string, number>();\n for (const c of classifierMeta.candidates) {\n if (c.requiredFieldCount !== undefined) {\n candidateFieldCounts.set(c.collection, c.requiredFieldCount);\n }\n }\n const suggestions = allCandidates\n .map((c) => {\n const fieldCost = candidateFieldCounts.get(c.collection);\n const fieldNote = fieldCost !== undefined ? `, ${fieldCost} required field${fieldCost === 1 ? \"\" : \"s\"}` : \"\";\n return `- \\`${c.collection}\\` (${c.confidence}% confidence${fieldNote})`;\n })\n .join(\"\\n\");\n const textBody =\n `Low confidence classification (${resolved.confidence}%, classified by ${resolved.classifiedBy}).\\n\\n` +\n `Predicted: \\`${resolved.collection}\\`\\n` +\n `Reason: ${resolved.reasoning || \"low signal\"}\\n\\n` +\n \"Choose one of these and retry with `collection`:\\n\" +\n `${suggestions}\\n\\n` +\n \"Correction path: rerun with your chosen `collection`, or capture and use `move-entry` later.\";\n return {\n content: [{ type: \"text\" as const, text: textBody }],\n structuredContent: failure(\n \"VALIDATION_ERROR\",\n `Low confidence routing to '${resolved.collection}' (${resolved.confidence}%, ${resolved.classifiedBy}).`,\n \"Rerun with explicit collection.\",\n allCandidates.map((c) => ({\n tool: \"capture\",\n description: `Capture to ${c.collection}`,\n parameters: { collection: c.collection },\n })),\n { classifier: classifierMeta },\n ),\n };\n}\n\n\nfunction buildClassifierMeta(\n resolved: ResolvedCollection,\n overrides: Partial<CaptureClassifierMetadata> = {},\n): CaptureClassifierMetadata {\n return {\n enabled: true,\n autoRouted: false,\n agrees: true,\n abstained: false,\n topConfidence: resolved.confidence,\n confidence: resolved.confidence,\n reasons: resolved.reasoning ? [resolved.reasoning] : [],\n candidates: [\n { collection: resolved.collection, confidence: resolved.confidence },\n ...resolved.alternatives.map((a) => ({ collection: a.collection, confidence: a.confidence })),\n ].slice(0, 3),\n classifiedBy: resolved.classifiedBy,\n confidenceTier: resolved.tier,\n reasoning: resolved.reasoning,\n ...overrides,\n };\n}\n\n/**\n * WP-316 S3 gap fix: enrich classifier candidates with requiredFieldCount from collection schema.\n * This gives agents a cost signal when choosing between low-confidence candidates.\n * Advisory — never throws, falls back to unmodified candidates.\n */\nasync function enrichCandidatesWithFieldCounts(meta: CaptureClassifierMetadata): Promise<void> {\n try {\n const cols = await getCollections();\n const reqBySlug = new Map(\n cols.map((c) => [c.slug, (c.fields ?? []).filter((f: { required?: boolean }) => f.required === true).length]),\n );\n meta.candidates = meta.candidates.map((c) => ({\n ...c,\n requiredFieldCount: reqBySlug.get(c.collection) ?? 0,\n }));\n } catch {\n // enrichment is advisory; never fail capture for this\n }\n}\n\n/**\n * BET-288 S0: Fire confusion-matrix telemetry on every classification.\n * Called from every code path that produces a ResolvedCollection.\n */\nfunction emitClassificationTelemetry(\n resolved: ResolvedCollection,\n workspaceId: string,\n opts: { explicitCollectionProvided: boolean; autoRouted: boolean },\n): void {\n const topAlt = resolved.alternatives?.[0] ?? null;\n trackCollectionClassified(workspaceId, {\n collection_slug: resolved.collection,\n thinking_layer: resolved.thinkingLayer ?? null,\n confidence: resolved.confidence,\n classified_by: resolved.classifiedBy,\n confidence_tier: resolved.tier,\n alternative_slug: topAlt?.collection ?? null,\n alternative_confidence: topAlt?.confidence ?? null,\n explicit_collection_provided: opts.explicitCollectionProvided,\n auto_routed: opts.autoRouted,\n });\n}\n\nasync function resolveCaptureCollection(params: {\n collection?: string;\n name: string;\n description: string;\n workspaceId: string;\n explicitCollectionProvided: boolean;\n}): Promise<CollectionResolution> {\n const {\n collection,\n name,\n description,\n workspaceId,\n explicitCollectionProvided,\n } = params;\n\n if (collection) {\n const resolved = await resolveCollection({ name, description });\n if (resolved) {\n const agrees = resolved.collection === collection;\n const classifierMeta = buildClassifierMeta(resolved, {\n autoRouted: false,\n agrees,\n agentProvidedCollection: collection,\n ...(!agrees && {\n overrideCommand: `capture collection=\"${resolved.collection}\"`,\n }),\n });\n await enrichCandidatesWithFieldCounts(classifierMeta);\n // BET-288 S0: Fire confusion telemetry on every classification (explicit path)\n emitClassificationTelemetry(resolved, workspaceId, {\n explicitCollectionProvided: true,\n autoRouted: false,\n });\n if (!agrees) {\n trackClassifierTelemetry({\n workspaceId,\n predictedCollection: resolved.collection,\n confidence: resolved.confidence,\n autoRouted: false,\n reasonCategory: \"low-confidence\",\n explicitCollectionProvided: true,\n outcome: \"fallback\",\n });\n // WP-316 S2: track divergence — agent overrode classifier suggestion\n const agentInCandidates =\n resolved.alternatives.some((a) => a.collection === collection) ||\n resolved.collection === collection;\n trackClassifierDivergence(workspaceId, {\n classifier_collection: resolved.collection,\n agent_collection: collection,\n classifier_confidence: resolved.confidence,\n classifier_tier: resolved.tier,\n agent_in_candidates: agentInCandidates,\n });\n }\n return { resolvedCollection: collection, classifierMeta };\n }\n return {\n resolvedCollection: collection,\n classifierMeta: {\n enabled: true,\n autoRouted: false,\n agrees: false,\n abstained: true,\n topConfidence: 0,\n confidence: 0,\n reasons: [],\n candidates: [],\n agentProvidedCollection: collection,\n },\n };\n }\n\n const resolved = await resolveCollection({ name, description });\n if (!resolved) {\n trackClassifierTelemetry({\n workspaceId,\n predictedCollection: \"unknown\",\n confidence: 0,\n autoRouted: false,\n reasonCategory: \"low-confidence\",\n explicitCollectionProvided,\n outcome: \"fallback\",\n });\n return { earlyResult: buildClassifierUnknownResult() };\n }\n\n // FEAT-159: Tier-based routing replaces shouldAutoRouteClassification/isClassificationAmbiguous.\n // High+medium auto-route; low rejects and asks for explicit collection.\n const autoRoute = resolved.tier !== \"low\";\n const classifierMeta = buildClassifierMeta(resolved, { autoRouted: autoRoute });\n await enrichCandidatesWithFieldCounts(classifierMeta);\n\n // BET-288 S0: Fire confusion telemetry on every classification (classifier path)\n emitClassificationTelemetry(resolved, workspaceId, {\n explicitCollectionProvided,\n autoRouted: autoRoute,\n });\n\n if (!autoRoute) {\n trackClassifierTelemetry({\n workspaceId,\n predictedCollection: resolved.collection,\n confidence: resolved.confidence,\n autoRouted: false,\n reasonCategory: \"low-confidence\",\n explicitCollectionProvided,\n outcome: \"fallback\",\n });\n return {\n classifierMeta,\n earlyResult: buildLowConfidenceResult(resolved, classifierMeta),\n };\n }\n\n trackClassifierTelemetry({\n workspaceId,\n predictedCollection: resolved.collection,\n confidence: resolved.confidence,\n autoRouted: true,\n reasonCategory: \"auto-routed\",\n explicitCollectionProvided,\n outcome: \"auto-routed\",\n });\n\n return {\n resolvedCollection: resolved.collection,\n classifierMeta,\n };\n}\n\nconst captureSuccessOutputSchema = z.object({\n entryId: z.string(),\n collection: z.string(),\n name: z.string(),\n status: z.enum([\"draft\", \"committed\", \"proposed\"]),\n qualityScore: z.number(),\n qualityVerdict: z.record(z.unknown()).optional(),\n classifier: captureClassifierSchema.optional(),\n studioUrl: z.string().optional(),\n warnings: z.array(z.string()).optional(),\n normalization: z.object({\n remapped: z.record(z.string()).optional(),\n rejected: z.array(z.string()).optional(),\n }).optional(),\n expectedFields: z.array(z.object({\n key: z.string(),\n type: z.string(),\n required: z.boolean().optional(),\n })).optional(),\n}).strict();\n\nconst captureClassifierOnlyOutputSchema = z.object({\n classifier: captureClassifierSchema,\n}).strict();\n\nexport const captureOutputSchema = z.union([\n captureSuccessOutputSchema,\n captureClassifierOnlyOutputSchema,\n]);\n\nexport const batchCaptureOutputSchema = z.object({\n captured: z.array(z.object({\n entryId: z.string(),\n collection: z.string(),\n name: z.string(),\n status: z.enum([\"draft\", \"committed\", \"proposed\"]),\n classifiedBy: z.enum([\"llm\", \"heuristic\", \"explicit\"]).optional(),\n confidence: z.number().optional(),\n confidenceTier: z.enum([\"high\", \"medium\", \"low\"]).optional(),\n warnings: z.array(z.string()).optional(),\n normalization: z.object({\n remapped: z.record(z.string()).optional(),\n rejected: z.array(z.string()).optional(),\n }).optional(),\n })),\n total: z.number(),\n failed: z.number(),\n committed: z.number(),\n proposed: z.number(),\n drafts: z.number(),\n classified: z.number().optional(),\n autoCommitApplied: z.boolean(),\n skippedLowConfidence: z.array(z.object({\n index: z.number(),\n name: z.string(),\n suggestedCollection: z.string().optional(),\n confidence: z.number().optional(),\n alternatives: z.array(z.object({\n collection: z.string(),\n confidence: z.number(),\n })).optional(),\n })).optional(),\n failedEntries: z.array(z.object({\n index: z.number(),\n collection: z.string(),\n name: z.string(),\n error: z.string(),\n })).optional(),\n});\n\n/**\n * TEN-194: Auto-commit only in Open mode. In consensus/role, draft-first always —\n * ignore autoCommit: true to prevent governance bypass.\n */\nfunction shouldAutoCommitCapture(\n autoCommit: boolean | undefined,\n governanceMode: string | undefined,\n): boolean {\n if (governanceMode !== \"open\") return false;\n return autoCommit === true || autoCommit === undefined;\n}\n\n/**\n * Build initial entry data from collection field definitions using type-aware defaults.\n * Single source of truth: FIELD_TYPE_DEFAULTS from fieldTypes.ts (BET-106, DEC-174).\n * Deduplicates logic previously inlined in both capture and batch-capture (TEN-305).\n */\nfunction buildDataFromFields(\n fields: Array<{ key: string; type: string; [k: string]: unknown }>,\n descriptionField: string,\n descriptionValue: string,\n): Record<string, unknown> {\n const data: Record<string, unknown> = {};\n for (const field of fields) {\n if (field.key === descriptionField) {\n data[field.key] = descriptionValue;\n } else {\n data[field.key] = FIELD_TYPE_DEFAULTS[field.type as FieldType] ?? null;\n }\n }\n return data;\n}\n\n/** Returns true if a value should be considered empty (null, empty array, or blank string). */\nfunction isEmptyValue(v: unknown): boolean {\n return v == null || (Array.isArray(v) ? v.length === 0 : String(v).trim() === \"\");\n}\n\n/** Returns true if a value should be considered non-empty (opposite of isEmptyValue). */\nfunction isNonEmptyValue(v: unknown): boolean {\n return v != null && (Array.isArray(v) ? v.length > 0 : String(v).trim() !== \"\");\n}\n\n/** Levenshtein distance for fuzzy select matching. DEC-173: fix when possible, never silently accept. */\nfunction levenshtein(a: string, b: string): number {\n const m = a.length;\n const n = b.length;\n const dp: number[][] = Array(m + 1)\n .fill(null)\n .map(() => Array(n + 1).fill(0));\n for (let i = 0; i <= m; i++) dp[i][0] = i;\n for (let j = 0; j <= n; j++) dp[0][j] = j;\n for (let i = 1; i <= m; i++) {\n for (let j = 1; j <= n; j++) {\n const cost = a[i - 1] === b[j - 1] ? 0 : 1;\n dp[i][j] = Math.min(dp[i - 1][j] + 1, dp[i][j - 1] + 1, dp[i - 1][j - 1] + cost);\n }\n }\n return dp[m][n];\n}\n\nconst APPETITE_OPTIONS = [\"small\", \"medium\", \"large\"] as const;\n\nfunction findClosestOption(value: string, options: readonly string[]): { opt: string; dist: number } {\n const lower = value.toLowerCase();\n const exact = options.find((o) => o.toLowerCase() === lower);\n if (exact) return { opt: exact, dist: 0 };\n return options.reduce(\n (acc, opt) => {\n const d = levenshtein(lower, opt.toLowerCase());\n return d < acc.dist ? { opt, dist: d } : acc;\n },\n { opt: options[0], dist: Infinity },\n );\n}\n\n/**\n * Canonicalize select fields: if current value is not in options, find closest match.\n * Case-insensitive exact first, then Levenshtein distance. DEC-173: fix when possible.\n * BET-125 Slice 1: appetite (top-level before bet move), horizon, severity, priority from col.fields.\n */\nfunction canonicalizeSelects(\n data: Record<string, unknown>,\n fields: Array<{ key: string; type: string; options?: string[] }>,\n isBet: boolean,\n): void {\n if (isBet && data.appetite != null && typeof data.appetite === \"string\") {\n const val = data.appetite.trim();\n if (val) {\n const { opt, dist } = findClosestOption(val, APPETITE_OPTIONS);\n if (dist <= 4) data.appetite = opt;\n }\n }\n\n for (const field of fields) {\n if (field.type !== \"select\" || !field.options?.length) continue;\n if (field.key === \"appetite\" && isBet) continue;\n const val = data[field.key];\n if (val == null || typeof val !== \"string\") continue;\n const trimmed = val.trim();\n if (!trimmed) continue;\n const { opt, dist } = findClosestOption(trimmed, field.options);\n if (dist <= 4) data[field.key] = opt;\n }\n}\n\nexport function registerSmartCaptureTools(server: McpServer) {\n const captureTool = server.registerTool(\n \"capture\",\n {\n title: \"Capture\",\n description:\n \"The single tool for creating knowledge entries. Creates an entry, auto-links related entries, \" +\n \"and returns a quality scorecard — all in one call. \" +\n \"Provide a name and description; `collection` is optional — the classifier auto-routes when omitted.\\n\\n\" +\n \"Supported collections with smart profiles: tensions, business-rules, glossary, decisions, features, \" +\n \"audiences, strategy, standards, maps, chains, insights, assumptions, principles, tracking-events.\\n\" +\n \"All other collections get an ENT-{random} ID and sensible defaults.\\n\\n\" +\n \"**Explicit data:** When you know the schema, pass `data: { field: value }` to set fields directly. \" +\n \"Top-level `name` and `description` always win for those fields. `data` wins over inference for all other fields.\\n\\n\" +\n \"**Compound capture:** Pass `links` to create relations in the same call (skips auto-link discovery). \" +\n \"In Open mode, entries commit by default when `autoCommit` is omitted. \" +\n \"Pass `autoCommit: true` to promote the entry from draft to SSOT immediately after linking when you want to be explicit. \" +\n \"Governed collections (glossary, business-rules, principles, standards, strategy, features, architecture) \" +\n \"will warn but still commit — use only when you're certain.\\n\\n\" +\n \"Entries are created as `draft` first, then may publish immediately depending on governance and `autoCommit`. Use `update-entry` for post-creation adjustments.\",\n inputSchema: captureSchema.shape,\n annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: false },\n },\n thinWrapper(async ({ collection, name, description, context, entryId, canonicalKey, data: userData, links, autoCommit, sourceRef, sourceExcerpt, preview, suggestOnly, format }) => {\n requireWriteAccess();\n\n const timingStart = Date.now();\n\n const wsCtx = await getWorkspaceContext();\n const explicitCollectionProvided = typeof collection === \"string\" && collection.trim().length > 0;\n\n const resolution = await resolveCaptureCollection({\n collection,\n name,\n description,\n workspaceId: wsCtx.workspaceId,\n explicitCollectionProvided,\n });\n if (resolution.earlyResult) {\n return resolution.earlyResult;\n }\n let resolvedCollection = resolution.resolvedCollection;\n const classifierMeta = resolution.classifierMeta;\n if (!resolvedCollection) {\n return buildClassifierUnknownResult();\n }\n\n // DEC-313 GAP 1: When classifier auto-routes to 'chains' and candidates\n // include 'work-packages', inject canonicalKey='work_package' so createEntry's isBetSignal\n // guard can redirect chains→work-packages. Only fires for classifier-driven routing\n // (not explicit agent choice) and when no canonicalKey was already provided.\n if (\n resolvedCollection === 'chains' &&\n !canonicalKey &&\n !explicitCollectionProvided &&\n classifierMeta?.candidates?.some(\n (c: { collection: string }) => c.collection === 'work-packages'\n )\n ) {\n canonicalKey = 'work_package';\n }\n\n const tAfterClassify = Date.now();\n\n // BR-111: entryId only allowed for business-rules and standards\n if (entryId && resolvedCollection !== \"business-rules\" && resolvedCollection !== \"standards\") {\n return {\n content: [{\n type: \"text\" as const,\n text: `# BR-111: entryId Not Allowed\\n\\n\\`entryId\\` is only valid for \\`business-rules\\` and \\`standards\\` collections. For \\`${resolvedCollection}\\`, omit \\`entryId\\` — IDs are auto-generated.`,\n }],\n structuredContent: failure(\n \"INVALID_ENTRY_ID\",\n `entryId is only allowed for business-rules and standards. Omit for ${resolvedCollection}.`,\n \"Remove entryId from your capture call.\",\n [],\n ),\n };\n }\n\n const profile = await getProfile(resolvedCollection);\n\n const col = await kernelQuery<any>(\"chain.getCollection\", { slug: resolvedCollection });\n if (!col) {\n const displayName = resolvedCollection.split(\"-\").map((w: string) => w.charAt(0).toUpperCase() + w.slice(1)).join(\" \");\n return {\n content: [{\n type: \"text\" as const,\n text:\n `Collection \\`${resolvedCollection}\\` not found.\\n\\n` +\n `**To create it**, run:\\n` +\n `\\`\\`\\`\\ncollections action=create slug=\"${resolvedCollection}\" name=\"${displayName}\" description=\"...\"\\n\\`\\`\\`\\n\\n` +\n `Or use \\`collections action=list\\` to see available collections.`,\n }],\n structuredContent: failure(\n \"NOT_FOUND\",\n `Collection '${resolvedCollection}' not found.`,\n \"Create the collection first, or use collections action=list to see available ones.\",\n [\n { tool: \"collections\", description: \"Create collection\", parameters: { action: \"create\", slug: resolvedCollection, name: displayName } },\n { tool: \"collections\", description: \"List collections\", parameters: { action: \"list\" } },\n ],\n ),\n };\n }\n\n // WP-318 S2 E1: Pre-write grounding — call suggestLinksForCapture in parallel with collection fetch.\n // Graceful degradation: grounding NEVER blocks capture. Any error → null.\n // Only runs when there's searchable content and auto-discovery is not skipped.\n const skipAutoDiscoveryEarly = links && links.length > 0;\n const groundingStart = Date.now();\n const groundingPromise = (!skipAutoDiscoveryEarly && (name || description))\n ? kernelQuery<any[]>(\"chain.suggestLinksForCapture\", {\n entries: [{ name, description: description ?? \"\", collectionHint: resolvedCollection }],\n limit: 5,\n threshold: 2,\n }).catch(() => null)\n : Promise.resolve(null);\n\n // WP-318 S2 E1: Await grounding result — capped at 500ms to preserve fail-open on latency.\n const groundingRaw = await Promise.race([\n groundingPromise,\n new Promise<null>((r) => setTimeout(() => r(null), 500)),\n ]);\n const groundingElapsedMs = Date.now() - groundingStart;\n const groundingEntry = (groundingRaw as any)?.[0] ?? null;\n const groundingRelated: Array<{\n entryId: string; name: string; collectionSlug: string;\n overlapRatio: number; recommendedRelationType: string; reasoning: string;\n }> = groundingEntry?.related ?? [];\n const groundingDuplicates: Array<{\n entryId: string; name: string; collectionSlug: string;\n matchType: \"related\" | \"possible_duplicate\"; overlapRatio: number;\n }> = groundingEntry?.duplicates ?? [];\n\n // WP-319 S2: Consume governance[] from query response (moved from local isGoverned loop).\n // governance[] is pre-computed by suggestLinksForCapture (WP-319 S1) — no async round trips needed.\n // Severity field from the query is ignored here; MCP banner display does not distinguish severity yet.\n const groundingGovernance: Array<{ entryId: string; name: string; collectionSlug: string }> =\n (groundingEntry?.governance ?? []).map((g: any) => ({\n entryId: g.entryId,\n name: g.name,\n collectionSlug: g.collectionSlug,\n }));\n\n const groundingReport = {\n related: groundingRelated.map((r) => ({\n entryId: r.entryId,\n name: r.name,\n collectionSlug: r.collectionSlug,\n overlapRatio: r.overlapRatio,\n recommendedRelationType: r.recommendedRelationType,\n reasoning: r.reasoning,\n })),\n duplicates: groundingDuplicates.map((d) => ({\n entryId: d.entryId,\n name: d.name,\n collectionSlug: d.collectionSlug,\n matchType: d.matchType,\n overlapRatio: d.overlapRatio,\n })),\n governance: groundingGovernance,\n };\n\n // WP-318 S2 E3: suggestOnly — return grounding preview without creating entry\n if (suggestOnly) {\n const hasSuggestions = groundingReport.related.length > 0 || groundingReport.duplicates.length > 0;\n const summaryText = hasSuggestions\n ? `Grounding preview for \"${name}\": ${groundingReport.related.length} related, ${groundingReport.duplicates.length} possible duplicates. No entry created.`\n : `Grounding preview for \"${name}\": no similar entries found. Safe to capture.`;\n return {\n content: [{\n type: \"text\" as const,\n text: `# Grounding Preview — No Entry Created\\n\\n${summaryText}\\n\\n` +\n (groundingReport.related.length > 0\n ? `## Related entries\\n${groundingReport.related.map((r) => `- **${r.entryId}** ${r.name} [${r.collectionSlug}] — ${r.reasoning}`).join(\"\\n\")}\\n\\n`\n : \"\") +\n (groundingReport.duplicates.length > 0\n ? `## Possible duplicates\\n${groundingReport.duplicates.map((d) => `- **${d.entryId}** ${d.name} [${d.collectionSlug}] (${d.matchType}, overlap: ${d.overlapRatio})`).join(\"\\n\")}\\n\\n`\n : \"\") +\n (groundingReport.governance.length > 0\n ? `## Governance entries to review\\n${groundingReport.governance.map((g) => `- **${g.entryId}** ${g.name} [${g.collectionSlug}]`).join(\"\\n\")}\\n\\n`\n : \"\") +\n `_Call \\`capture\\` without \\`suggestOnly\\` to proceed with entry creation._`,\n }],\n structuredContent: {\n ...success(\n summaryText,\n { groundingReport, outcome: \"suggest_only\" as const },\n [{ tool: \"capture\", description: \"Capture for real\", parameters: { collection: resolvedCollection, name, description } }],\n ),\n },\n };\n }\n\n // 2. Build data with profile defaults + inference\n const data = buildDataFromFields(col.fields ?? [], profile.descriptionField, description);\n\n for (const def of profile.defaults) {\n if (def.value !== \"infer\" && def.value !== \"today\") {\n data[def.key] = def.value;\n }\n }\n\n if (profile.inferField) {\n const inferred = profile.inferField({\n collection: resolvedCollection, name, description, context, data, entryId: \"\",\n linksCreated: [], linksSuggested: [], collectionFields: col.fields ?? [],\n });\n for (const [key, val] of Object.entries(inferred)) {\n if (val !== undefined && val !== \"\") {\n data[key] = val;\n }\n }\n }\n\n if (isEmptyValue(data.date)) {\n const inferredSourceDate = inferSourceDate(name, description, context, sourceRef, sourceExcerpt);\n if (inferredSourceDate && (col.fields ?? []).some((field) => field.key === \"date\")) {\n data.date = inferredSourceDate;\n }\n }\n\n // Merge user-provided data (wins over inference for those fields)\n if (userData && typeof userData === \"object\") {\n for (const [key, val] of Object.entries(userData)) {\n if (key !== \"name\") data[key] = val;\n }\n }\n\n // Top-level description always wins\n data[profile.descriptionField || \"description\"] = description;\n\n // BET-281: Identify bet captures via canonicalKey (primary) or collection's defaultCanonicalKey.\n const colMeta = await getCollectionBySlug(resolvedCollection);\n const isBetCapture = canonicalKey === \"work_package\" || colMeta?.defaultCanonicalKey === \"work_package\";\n\n // BET-125: decomposeContent (strategy goals/rationale/scope; bet problem/elements/doneWhen) + canonicalizeSelects\n let entryWarnings: string[] = [];\n // BET-288: derive strategy check from thinkingLayer instead of hardcoded slug\n const isStrategyCapture = colMeta?.thinkingLayer === \"strategy\";\n const shouldDecompose =\n (isStrategyCapture || isBetCapture) &&\n description.trim().length > 0;\n if (shouldDecompose) {\n try {\n const decomposed = await kernelCall<{ decomposed: Record<string, unknown> } | null>(\n \"chain.decomposeContent\",\n {\n collectionSlug: resolvedCollection,\n entryName: name,\n description,\n existingData: data,\n ...(isBetCapture ? { canonicalKey: \"work_package\" } : {}),\n ...(colMeta?.thinkingLayer ? { thinkingLayer: colMeta.thinkingLayer } : {}),\n },\n );\n if (decomposed?.decomposed) {\n for (const [key, val] of Object.entries(decomposed.decomposed)) {\n if (isEmptyValue(data[key]) && isNonEmptyValue(val)) {\n data[key] = val;\n }\n }\n }\n } catch {\n // Non-blocking: capture proceeds without decomposition (BET-125 contract)\n entryWarnings.push(\"Content decomposition skipped (transient error). Entry saved with description only.\");\n }\n }\n canonicalizeSelects(data, col.fields ?? [], isBetCapture);\n\n // BET-132: bet captures keep flat fields (problem, appetite, etc.) — no data.links wrapping\n\n // 3b. Status is now resolved server-side (DEC-896 / BR-76): Open mode → 'active', else 'draft'.\n // Do NOT pass explicit status here so governance mode governs. Callers that need draft can pass it.\n const agentId = getAgentSessionId();\n\n // 4. Create entry (Convex generates sequential ID when entryId not provided)\n let finalEntryId: string;\n let internalId: string;\n let normalizationMeta: { remapped: Record<string, string>; rejected: string[]; accepted: string[] } | undefined;\n // BET-272 S3: Formative quality hints — populated from createEntryWithClassification result (STD-101)\n let formativeHints: Array<{ field: string; hint: string; severity: \"advisory\" }> = [];\n // BET-272 S5: Advisory relation suggestions from graph (BR-144, STD-147)\n let relationSuggestionsFromCreate: Array<{ targetEntryId: string; targetName: string; relationType: string; confidence: number; reasoning: string }> = [];\n // DEC-896 / BR-76 S3: server returned 'active' — skip post-write commitEntry call.\n let wasAutoCommittedServerSide = false;\n try {\n const result = await kernelMutation<{\n preview?: boolean;\n docId: string; entryId: string;\n /** DEC-896 / BR-76: 'active' means server auto-committed (Open mode). Guard skips commitEntry. */\n status?: \"draft\" | \"active\" | \"deprecated\";\n warnings?: string[];\n normalization?: { remapped: Record<string, string>; rejected: string[]; accepted: string[] };\n contract?: { requiredFields: string[]; allFields: unknown[]; captureExpectation?: string };\n // BET-272 S5: Advisory relation suggestions from graph (BR-144, STD-147)\n relationSuggestions?: Array<{ targetEntryId: string; targetName: string; relationType: string; confidence: number; reasoning: string }>;\n // BET-272 S3: Advisory quality hints from collection qualityCriteria (BR-144)\n qualityHints?: Array<{ field: string; hint: string; severity: \"advisory\" }>;\n }>(\"chain.createEntry\", {\n collectionSlug: resolvedCollection,\n entryId: entryId ?? undefined,\n name,\n // DEC-896 / BR-76: omit status — server resolves from governanceMode (Open→active, else draft).\n data,\n canonicalKey,\n createdBy: agentId ? `agent:${agentId}` : \"capture\",\n sessionId: agentId ?? undefined,\n ...(sourceRef ? { sourceRef } : {}),\n ...(sourceExcerpt ? { sourceExcerpt } : {}),\n ...(preview ? { preview: true } : {}),\n });\n\n // WP-316 S3: Preview gate — return dry-run result without recording session activity.\n if (result?.preview) {\n const hasGrounding = groundingReport.related.length > 0 || groundingReport.duplicates.length > 0 || groundingReport.governance.length > 0;\n const groundingSummary = hasGrounding\n ? `\\n\\n**Grounding:** ${[\n groundingReport.duplicates.length > 0 && `${groundingReport.duplicates.length} possible duplicate${groundingReport.duplicates.length > 1 ? \"s\" : \"\"}`,\n groundingReport.related.length > 0 && `${groundingReport.related.length} related entr${groundingReport.related.length > 1 ? \"ies\" : \"y\"}`,\n groundingReport.governance.length > 0 && `${groundingReport.governance[0]?.entryId} may govern this`,\n ].filter(Boolean).join(\", \")}.`\n : \"\";\n const previewEnvelope = success(\n `Preview: would capture \"${name}\" — no DB writes`,\n {\n entryId: result.entryId,\n name,\n collection: resolvedCollection,\n outcome: \"preview\" as const,\n warnings: result.warnings ?? [],\n groundingReport,\n },\n [{ tool: \"capture\", description: \"Capture for real\", parameters: { collection: resolvedCollection, name, description } }],\n );\n if (result.contract) {\n previewEnvelope.contract = result.contract;\n }\n return {\n content: [{ type: \"text\" as const, text: `# Preview: would capture \"${name}\" [${resolvedCollection}]\\n\\nNo DB writes — call without \\`preview:true\\` to capture for real.${result.warnings?.length ? `\\n\\n**Warnings:** ${result.warnings.join(\"; \")}` : \"\"}${groundingSummary}` }],\n structuredContent: previewEnvelope,\n };\n }\n internalId = result.docId;\n finalEntryId = result.entryId;\n entryWarnings.push(...(result.warnings ?? []));\n normalizationMeta = result.normalization;\n // BET-272 S5: Advisory relation suggestions from graph (BR-144, STD-147)\n relationSuggestionsFromCreate = result.relationSuggestions ?? [];\n // BET-272 S3: Quality hints from createEntryWithClassification (STD-101: single source)\n formativeHints = result.qualityHints ?? [];\n resolveGapsForEntry(name, result.entryId);\n // DEC-896 / BR-76 S3: server already committed (Open mode auto-commit). Mark and skip commitEntry.\n if (result.status === \"active\") {\n wasAutoCommittedServerSide = true;\n }\n } catch (error: unknown) {\n const msg = error instanceof Error ? error.message : String(error);\n if (msg.includes(\"Duplicate\") || msg.includes(\"already exists\")) {\n return {\n content: [{\n type: \"text\" as const,\n text: `# Cannot Capture — Duplicate Detected\\n\\n${msg}\\n\\nUse \\`entries action=get\\` to inspect the existing entry, or \\`update-entry\\` to modify it.`,\n }],\n structuredContent: failure(\n \"DUPLICATE\",\n msg,\n \"Use entries action=get to inspect the existing entry.\",\n [\n { tool: \"entries\", description: \"Get existing entry\", parameters: { action: \"get\", entryId: entryId ?? name } },\n { tool: \"update-entry\", description: \"Update existing entry\", parameters: { entryId: entryId ?? \"\" } },\n ],\n ),\n };\n }\n throw error;\n }\n\n const tAfterCreate = Date.now();\n\n // WP-319 S2: Record grounding outcome for observability (STD-155).\n // Fire-and-forget — never block capture on observability failure.\n void kernelMutation(\"chain.recordGroundingOutcome\", {\n surface: \"mcp\",\n promptShown: groundingReport.governance.length > 0,\n highestRatio: Math.max(\n ...groundingReport.duplicates.map((d: any) => d.overlapRatio),\n ...groundingReport.related.map((r: any) => r.overlapRatio),\n 0,\n ),\n hadGovernance: groundingReport.governance.length > 0,\n grounding_ms: groundingElapsedMs,\n }).catch(() => undefined);\n\n // 6. Discover candidates + build batch relations array (BET-105 E4)\n const linksCreated: LinkResult[] = [];\n const linksSuggested: LinkSuggestion[] = [];\n const userLinkResults: Array<{ label: string; ok: boolean }> = [];\n // BET-167: Conflict candidates for pre-commit advisory (populated from search results)\n let conflictCandidates: Array<{ entryId: string; name: string; collection: string }> = [];\n\n type PendingRelation = {\n fromEntryId: string; toEntryId: string; type: string;\n meta: { source: \"auto\" | \"user\"; targetName: string; targetCollection: string; linkReason?: string };\n };\n const pendingRelations: PendingRelation[] = [];\n\n const skipAutoDiscovery = links && links.length > 0;\n const searchQuery = extractSearchTerms(name, description);\n if (searchQuery && !skipAutoDiscovery) {\n // BET-281: Populate hub cache before scoring; uses collectionCache (no extra DB call).\n await populateHubCache();\n const [searchResults, allCollections] = await Promise.all([\n kernelQuery<any[]>(\"chain.searchEntries\", { query: searchQuery }),\n getCollections(),\n ]);\n\n const collMap = new Map<string, string>();\n for (const c of allCollections) collMap.set(c._id, c.slug);\n\n const candidates = (searchResults ?? [])\n .filter((r) => r.entryId !== finalEntryId && r._id !== internalId)\n .map((r) => {\n const conf = computeLinkConfidence(r, name, description, resolvedCollection, collMap.get(r.collectionId) ?? \"unknown\");\n return {\n ...r,\n collSlug: collMap.get(r.collectionId) ?? \"unknown\",\n confidence: conf.score,\n confidenceReason: conf.reason,\n };\n })\n .sort((a, b) => b.confidence - a.confidence);\n\n let autoCount = 0;\n for (const c of candidates) {\n if (autoCount >= MAX_AUTO_LINKS) break;\n if (c.confidence < AUTO_LINK_CONFIDENCE_THRESHOLD) break;\n if (!c.entryId || !finalEntryId) continue;\n\n const { type: relationType, reason: relationReason } = inferRelationType(resolvedCollection, c.collSlug, profile);\n pendingRelations.push({\n fromEntryId: finalEntryId, toEntryId: c.entryId, type: relationType,\n meta: { source: \"auto\", targetName: c.name, targetCollection: c.collSlug,\n linkReason: `confidence ${c.confidence} (${c.confidenceReason}) + ${relationReason}` },\n });\n autoCount++;\n }\n\n const autoTargetIds = new Set(pendingRelations.map(r => r.toEntryId));\n for (const c of candidates) {\n if (linksSuggested.length >= MAX_SUGGESTIONS) break;\n if (autoTargetIds.has(c.entryId)) continue;\n if (c.confidence < 10) continue;\n\n const preview = extractPreview(c.data, 80);\n const reason = c.confidence >= AUTO_LINK_CONFIDENCE_THRESHOLD\n ? \"high relevance (already linked)\"\n : `\"${c.name.toLowerCase().split(/\\s+/).filter((w: string) => `${name} ${description}`.toLowerCase().includes(w) && w.length > 3).slice(0, 2).join('\", \"')}\" appears in content`;\n\n linksSuggested.push({ entryId: c.entryId, name: c.name, collection: c.collSlug, reason, preview });\n }\n\n // BET-167: Collect conflict candidates from auto-link search results for pre-commit advisory.\n // Reuses the search already done — no extra query needed.\n conflictCandidates = candidates\n .filter((c) => c.entryId && c.entryId !== finalEntryId)\n .slice(0, 3)\n .map((c) => ({ entryId: c.entryId as string, name: c.name as string, collection: c.collSlug as string }));\n }\n\n // 6b. Add user-specified links to batch\n if (links && links.length > 0 && finalEntryId) {\n for (const link of links) {\n pendingRelations.push({\n fromEntryId: finalEntryId, toEntryId: link.to, type: link.type,\n meta: { source: \"user\", targetName: link.to, targetCollection: \"unknown\" },\n });\n }\n }\n\n // 7. Parallel post-create: batch relations + cardinality + contradiction + coaching\n const resolvedCK = canonicalKey;\n\n const batchRelationsPromise = pendingRelations.length > 0\n ? kernelMutation<{ results: Array<{ fromEntryId: string; toEntryId: string; type: string; ok: boolean; error?: string }>; created: number; failed: number }>(\n \"chain.createEntryRelations\", {\n relations: pendingRelations.slice(0, 25).map(r => ({ fromEntryId: r.fromEntryId, toEntryId: r.toEntryId, type: r.type })),\n sessionId: agentId ?? undefined,\n },\n ).catch((err) => {\n entryWarnings.push(`Auto-linking partially failed: ${err instanceof Error ? err.message : \"unknown error\"}`);\n return null;\n })\n : Promise.resolve(null);\n\n const cardinalityPromise = resolvedCK\n ? kernelQuery<any>(\"chain.checkCardinalityWarning\", { canonicalKey: resolvedCK }).catch(() => null)\n : Promise.resolve(null);\n\n const contradictionPromise = runContradictionCheck(name, description);\n\n const coachingPromise = kernelMutation<any>(\"quality.evaluateHeuristicAndSchedule\", {\n entryId: finalEntryId, context: \"capture\",\n }).catch(() => null);\n\n const [batchResult, cardinalityCheck, contradictionWarnings, verdictResult] = await Promise.all([\n batchRelationsPromise, cardinalityPromise, contradictionPromise, coachingPromise,\n ]);\n\n const tAfterRelations = Date.now();\n\n // Map batch results back to linksCreated / userLinkResults\n if (batchResult) {\n for (let i = 0; i < pendingRelations.length; i++) {\n const pending = pendingRelations[i];\n const result = batchResult.results[i];\n if (!result) continue;\n\n if (pending.meta.source === \"auto\") {\n if (result.ok) {\n linksCreated.push({\n targetEntryId: pending.toEntryId, targetName: pending.meta.targetName,\n targetCollection: pending.meta.targetCollection, relationType: pending.type,\n linkReason: pending.meta.linkReason,\n });\n }\n } else {\n if (result.ok) {\n userLinkResults.push({ label: `✓ ${pending.type} → ${pending.toEntryId}`, ok: true });\n linksCreated.push({\n targetEntryId: pending.toEntryId, targetName: pending.meta.targetName,\n targetCollection: pending.meta.targetCollection, relationType: pending.type,\n });\n } else {\n userLinkResults.push({ label: `✗ ${pending.type} → ${pending.toEntryId}: ${result.error ?? \"failed\"}`, ok: false });\n }\n }\n }\n }\n\n // 8. Score quality (in-process, uses populated linksCreated)\n const captureCtx: CaptureContext = {\n collection: resolvedCollection, name, description, context, data,\n entryId: finalEntryId, canonicalKey, linksCreated, linksSuggested,\n collectionFields: col.fields ?? [],\n };\n const quality = scoreQuality(captureCtx, profile);\n\n const tAfterQuality = Date.now();\n\n const cardinalityWarning: string | null = cardinalityCheck?.warning ?? null;\n\n if (contradictionWarnings.length > 0) {\n await recordSessionActivity({ contradictionWarning: true });\n }\n\n let coachingSection = \"\";\n if (verdictResult?.verdict && verdictResult.verdict.tier !== \"passive\" && verdictResult.verdict.criteria.length > 0) {\n coachingSection = formatRubricCoaching(verdictResult);\n }\n\n // 11. Track quality verdict\n if (verdictResult?.verdict) {\n try {\n const wsForTracking = await getWorkspaceContext();\n const v = verdictResult.verdict;\n const failedCount = (v.criteria ?? []).filter((c: any) => !c.passed).length;\n trackQualityVerdict(wsForTracking.workspaceId, {\n entry_id: finalEntryId,\n entry_type: v.canonicalKey ?? resolvedCollection,\n tier: v.tier,\n context: \"capture\",\n passed: v.passed,\n source: verdictResult.source ?? \"heuristic\",\n criteria_total: v.criteria?.length ?? 0,\n criteria_failed: failedCount,\n llm_scheduled: v.tier !== \"passive\",\n });\n } catch { /* tracking is advisory */ }\n }\n\n // 12. Auto-commit if requested (or defaulted via Open governance mode).\n // BET-76 FEAT-111: When autoCommit is not explicitly set, default to true for\n // Open mode workspaces. Consensus/role modes retain draft-first behavior.\n // TEN-1810: Refresh governanceMode in case workspace flipped to Open after session start.\n const freshGovernanceMode = await refreshWorkspaceGovernanceMode();\n const shouldAutoCommit = shouldAutoCommitCapture(autoCommit, freshGovernanceMode);\n\n // BET-167 doneWhen #4: Conflict pre-check before auto-commit (advisory, never blocking).\n // When auto-link discovery was skipped (user provided explicit links), run a lightweight\n // search now so conflict candidates are populated before the commit.\n if (shouldAutoCommit && finalEntryId && conflictCandidates.length === 0) {\n try {\n const conflictResults = await kernelQuery<any[]>(\"chain.searchEntries\", { query: name });\n conflictCandidates = (conflictResults ?? [])\n .filter((r: any) => r.entryId && r.entryId !== finalEntryId && r._id !== internalId)\n .slice(0, 3)\n .map((r: any) => ({ entryId: r.entryId as string, name: r.name as string, collection: r.collectionSlug ?? \"unknown\" }));\n } catch {\n // Advisory only — proceed without conflict check on failure\n }\n }\n\n let finalStatus: \"draft\" | \"committed\" | \"proposed\" | \"draft_on_failure\" = \"draft\";\n let commitError: string | null = null;\n // DEC-896 / BR-76 S3: server already committed in Open mode — skip commitEntry entirely.\n if (wasAutoCommittedServerSide) {\n finalStatus = \"committed\";\n await recordSessionActivity({ entryModified: internalId });\n trackChainEntryCommitted(wsCtx.workspaceId, {\n entry_id: finalEntryId,\n collection: resolvedCollection,\n commit_method: \"auto\",\n surface: \"mcp_capture\",\n });\n } else if (shouldAutoCommit && finalEntryId) {\n try {\n const semanticConflicts = await runSemanticConflictPreflight(name, description, resolvedCollection);\n const blockingConflicts = semanticConflicts.filter(\n (conflict) => conflict.type === \"contradiction\" && conflict.confidence >= BLOCKING_CONTRADICTION_THRESHOLD,\n );\n\n if (blockingConflicts.length > 0) {\n commitError = `blocked by semantic contradiction preflight: ${blockingConflicts[0]?.chainEntryId} ${blockingConflicts[0]?.explanation ?? \"\"}`.trim();\n } else {\n const commitResult = await kernelMutation<any>(\"chain.commitEntry\", {\n entryId: finalEntryId,\n author: agentId ? `agent:${agentId}` : undefined,\n sessionId: agentId ?? undefined,\n });\n finalStatus = commitResult?.status === \"proposal_created\" ? \"proposed\" : \"committed\";\n if (finalStatus === \"committed\") {\n await recordSessionActivity({ entryModified: internalId });\n trackChainEntryCommitted(wsCtx.workspaceId, {\n entry_id: finalEntryId,\n collection: resolvedCollection,\n commit_method: \"auto\",\n surface: \"mcp_capture\",\n });\n }\n }\n } catch (e: unknown) {\n // BR-76 S2 — DEC-888: Surface failures via log + payload + session TEN. Never silent.\n commitError = e instanceof Error ? e.message : \"unknown error\";\n finalStatus = \"draft_on_failure\";\n await recordCommitFailure({ entryId: finalEntryId, error: e, sessionId: agentId, server });\n }\n }\n\n // 13. Format response\n const lines: string[] = [\n `# Captured: ${finalEntryId || name}`,\n `**${name}** added to \\`${resolvedCollection}\\` as \\`${finalStatus}\\``,\n `**Workspace:** ${wsCtx.workspaceSlug} (${wsCtx.workspaceId})`,\n ];\n\n if (classifierMeta) {\n lines.push(\"\");\n lines.push(\"## Classification\");\n if (classifierMeta.abstained) {\n lines.push(`No classifier coverage for \\`${resolvedCollection}\\` — entry accepted as-is.`);\n } else if (classifierMeta.autoRouted) {\n lines.push(`Auto-routed to \\`${resolvedCollection}\\` (${classifierMeta.topConfidence}% confidence).`);\n if (classifierMeta.reasons.length > 0) {\n lines.push(`Reason: ${classifierMeta.reasons.join(\"; \")}.`);\n }\n lines.push(`Override: rerun with explicit \\`collection\\` if wrong.`);\n } else if (classifierMeta.agrees) {\n lines.push(`Classifier confirms \\`${resolvedCollection}\\` (${classifierMeta.topConfidence}% confidence).`);\n } else {\n const suggested = classifierMeta.candidates[0]?.collection ?? \"unknown\";\n lines.push(`Classifier suggests \\`${suggested}\\` (${classifierMeta.topConfidence}% confidence) — review classification.`);\n if (classifierMeta.reasons.length > 0) {\n lines.push(`Reason: ${classifierMeta.reasons.join(\"; \")}.`);\n }\n if (classifierMeta.overrideCommand) {\n lines.push(`Override: \\`${classifierMeta.overrideCommand}\\``);\n }\n }\n }\n\n // DEC-70: Cortex link for chain entries (e.g. bets) — structuredContent studioUrl\n const appUrl = process.env.PRODUCTBRAIN_APP_URL ?? \"https://work.productbrain.io\";\n const studioUrl =\n resolvedCollection === \"chains\"\n ? `${appUrl.replace(/\\/$/, \"\")}/w/${wsCtx.workspaceSlug}/legacy/${internalId}`\n : undefined;\n if (studioUrl) {\n lines.push(\"\");\n lines.push(`**View in Cortex:** ${studioUrl}`);\n }\n\n if (linksCreated.length > 0) {\n lines.push(\"\");\n lines.push(`## Auto-linked (${linksCreated.length})`);\n for (const link of linksCreated) {\n const reason = (link as any).linkReason ? ` — because ${(link as any).linkReason}` : \"\";\n lines.push(`- -> **${link.relationType}** ${link.targetEntryId}: ${link.targetName} [${link.targetCollection}]${reason}`);\n }\n }\n\n if (userLinkResults.length > 0) {\n lines.push(\"\");\n lines.push(\"## Requested links\");\n for (const r of userLinkResults) lines.push(`- ${r.label}`);\n }\n\n if (finalStatus === \"committed\") {\n const wasAutoCommitted = autoCommit === undefined && freshGovernanceMode === \"open\";\n lines.push(\"\");\n lines.push(`## Committed: ${finalEntryId}`);\n if (wasAutoCommitted) {\n lines.push(`**${name}** added to your knowledge base.`);\n } else {\n lines.push(`**${name}** promoted to SSOT on the Chain.`);\n }\n if (await isGoverned(resolvedCollection)) {\n lines.push(`_Note: \\`${resolvedCollection}\\` is a governed collection — ensure this entry has been reviewed._`);\n }\n } else if (finalStatus === \"proposed\") {\n lines.push(\"\");\n lines.push(`## Proposal created: ${finalEntryId}`);\n lines.push(`**${name}** requires consent before it can be committed, so a proposal was created instead of publishing directly.`);\n } else if (commitError) {\n lines.push(\"\");\n lines.push(\"## Commit failed\");\n lines.push(`Error: ${commitError}. Entry saved as draft — use \\`commit-entry entryId=\"${finalEntryId}\"\\` to promote when ready.`);\n }\n\n // BET-167: Advisory conflict notice — shown after commit status, never blocking\n if (shouldAutoCommit && conflictCandidates.length > 0) {\n lines.push(\"\");\n lines.push(\"## Potential Overlaps\");\n lines.push(`Auto-committed with advisory: ${conflictCandidates.length} similar ${conflictCandidates.length === 1 ? \"entry\" : \"entries\"} found.`);\n for (const c of conflictCandidates) {\n lines.push(`- \\`${c.entryId}\\`: ${c.name} [${c.collection}]`);\n }\n lines.push(\"Consider reviewing for duplicates.\");\n }\n\n if (linksSuggested.length > 0) {\n lines.push(\"\");\n lines.push(\"## Suggested links (review and use `relations action=create`)\");\n for (let i = 0; i < linksSuggested.length; i++) {\n const s = linksSuggested[i];\n const preview = s.preview ? ` — ${s.preview}` : \"\";\n lines.push(`${i + 1}. **${s.entryId ?? \"(no ID)\"}**: ${s.name} [${s.collection}]${preview}`);\n }\n }\n\n // WP-318 S2 E4: Grounding report — format:human renders compact summary; format:agent exposes via structuredContent only\n if (format === \"human\") {\n const hasDuplicates = groundingReport.duplicates.length > 0;\n const hasRelated = groundingReport.related.length > 0;\n const hasGov = groundingReport.governance.length > 0;\n if (hasDuplicates || hasRelated || hasGov) {\n lines.push(\"\");\n const parts: string[] = [];\n if (hasDuplicates) parts.push(`${groundingReport.duplicates.length} possible duplicate${groundingReport.duplicates.length > 1 ? \"s\" : \"\"}`);\n if (hasRelated) parts.push(`${groundingReport.related.length} related entr${groundingReport.related.length > 1 ? \"ies\" : \"y\"}`);\n if (hasGov) parts.push(`${groundingReport.governance[0]?.entryId} may govern this`);\n lines.push(`_Grounding: ${parts.join(\", \")}. Review and link if relevant._`);\n }\n }\n\n lines.push(\"\");\n lines.push(formatQualityReport(quality));\n\n const failedChecks = quality.checks.filter((c) => !c.passed);\n if (failedChecks.length > 0) {\n lines.push(\"\");\n lines.push(`_To improve: \\`update-entry entryId=\"${finalEntryId}\"\\` to fill missing fields._`);\n }\n\n // BET-289 S2: Field-level writing guidance — shown when collection fields have guidance\n const fieldGuidanceSection = formatFieldGuidance(col.fields ?? []);\n if (fieldGuidanceSection) {\n lines.push(\"\");\n lines.push(fieldGuidanceSection);\n\n // BET-289 S5: Track guidance application for observability (STD-155)\n const guidedFieldCount = (col.fields ?? []).filter((f: { writingGuidance?: string }) => f.writingGuidance).length;\n trackFieldGuidanceApplied(wsCtx.workspaceId, {\n collection: resolvedCollection,\n guided_field_count: guidedFieldCount,\n });\n }\n\n // BET-272 S3: Formative quality hints — advisory, never blocking (BR-144)\n if (formativeHints.length > 0) {\n lines.push(\"\");\n lines.push(\"## Quality Hints (advisory)\");\n for (const hint of formativeHints) {\n lines.push(`- **${hint.field}:** ${hint.hint}`);\n }\n lines.push(`_These hints are advisory — your entry was captured. Use \\`update-entry entryId=\"${finalEntryId}\"\\` to address them._`);\n }\n\n // BET-272 S5: Advisory relation suggestions from graph (BR-144, STD-147)\n if (relationSuggestionsFromCreate.length > 0) {\n lines.push(\"\");\n lines.push(\"## Suggested Relations (advisory)\");\n for (const rs of relationSuggestionsFromCreate) {\n lines.push(`- **${rs.relationType}** → ${rs.targetEntryId} \"${rs.targetName}\" (confidence: ${rs.confidence})`);\n }\n lines.push(`_Create with: \\`relations action=create fromId=\"${finalEntryId}\" toId=\"TARGET-ID\" type=\"TYPE\"\\`_`);\n }\n\n // STD-155: Track capture intelligence observability\n if (formativeHints.length > 0) {\n trackCaptureQualityHints(wsCtx.workspaceId, {\n collection: resolvedCollection,\n hint_count: formativeHints.length,\n hint_fields: formativeHints.map((h) => h.field),\n });\n }\n if (relationSuggestionsFromCreate.length > 0) {\n trackCaptureRelationSuggestions(wsCtx.workspaceId, {\n collection: resolvedCollection,\n suggestion_count: relationSuggestionsFromCreate.length,\n relation_types: relationSuggestionsFromCreate.map((rs) => rs.relationType),\n avg_confidence: Math.round(\n relationSuggestionsFromCreate.reduce((sum, rs) => sum + rs.confidence, 0) /\n relationSuggestionsFromCreate.length,\n ),\n });\n }\n\n // Strategy-link warning for bet/goal (ENT-ldomlr: Intelligence Surface)\n const isBetOrGoal =\n isBetCapture ||\n resolvedCK === \"bet\" ||\n resolvedCK === \"goal\";\n const hasStrategyLink = linksCreated.some((l) => l.targetCollection === \"strategy\");\n if (isBetOrGoal && !hasStrategyLink) {\n lines.push(\"\");\n lines.push(\n `**Strategy link:** This ${isBetCapture ? \"bet\" : \"goal\"} doesn't connect to any strategy entry. Consider linking before commit. Use \\`graph action=suggest entryId=\"${finalEntryId}\"\\` to find strategy entries to connect to.`\n );\n await recordSessionActivity({ strategyLinkWarnedForEntryId: internalId });\n }\n\n // Cardinality warning for singleton types (DEC-zcuhvb)\n if (cardinalityWarning) {\n lines.push(\"\");\n lines.push(`**Cardinality warning:** ${cardinalityWarning}`);\n }\n\n // Contradiction warnings — exact format per spec\n if (contradictionWarnings.length > 0) {\n lines.push(\"\");\n lines.push(\"⚠ Contradiction check: proposed entry matched existing governance entries:\");\n for (const w of contradictionWarnings) {\n lines.push(`- ${w.name} (${w.collection}, ${w.entryId}) — has 'governs' relation to ${w.governsCount} entries`);\n }\n lines.push(\"Run `context action=gather` on these entries before committing.\");\n }\n\n // Validation warnings from createEntry (FEAT-188: MCP Envelope Warnings)\n if (entryWarnings.length > 0) {\n lines.push(\"\");\n lines.push(\"## Validation Warnings\");\n for (const w of entryWarnings) {\n lines.push(`- ${w}`);\n }\n }\n\n // Rubric coaching (assertive/nudge only)\n if (coachingSection) {\n lines.push(\"\");\n lines.push(coachingSection);\n }\n\n // Next steps: adapt based on what was already done\n lines.push(\"\");\n lines.push(\"## Next Steps\");\n const eid = finalEntryId || \"(check entry ID)\";\n if (finalStatus === \"committed\") {\n lines.push(`1. **Connect it:** \\`graph action=suggest entryId=\"${eid}\"\\` — discover additional links`);\n if (failedChecks.length > 0) {\n lines.push(`2. **Improve quality:** \\`update-entry entryId=\"${eid}\"\\` — fill missing fields`);\n }\n } else if (finalStatus === \"proposed\") {\n lines.push(`1. **Connect it:** \\`graph action=suggest entryId=\"${eid}\"\\` — discover additional links to support the proposal`);\n if (failedChecks.length > 0) {\n lines.push(`2. **Improve quality:** \\`update-entry entryId=\"${eid}\"\\` — strengthen the entry before approval`);\n }\n } else {\n if (userLinkResults.length === 0) {\n lines.push(`1. **Connect it:** \\`graph action=suggest entryId=\"${eid}\"\\` — discover what this should link to`);\n }\n lines.push(`${userLinkResults.length === 0 ? \"2\" : \"1\"}. **Commit it:** \\`commit-entry entryId=\"${eid}\"\\` — promote from draft to SSOT on the Chain`);\n if (failedChecks.length > 0) {\n lines.push(`${userLinkResults.length === 0 ? \"3\" : \"2\"}. **Improve quality:** \\`update-entry entryId=\"${eid}\"\\` — fill missing fields`);\n }\n }\n\n // Advisory: workspace readiness hints (never blocking)\n try {\n const readiness = await kernelQuery<any>(\"chain.workspaceReadiness\");\n if (readiness && readiness.gaps && readiness.gaps.length > 0) {\n const topGaps = readiness.gaps.slice(0, 2);\n lines.push(\"\");\n lines.push(`## Workspace Readiness: ${readiness.score}%`);\n for (const gap of topGaps) {\n lines.push(`- _${gap.label}:_ ${gap.guidance}`);\n }\n }\n } catch {\n // Readiness check is advisory — capture works without it\n }\n\n // Context-sensitive next: adapt based on what was already done\n const next: NextAction[] = [];\n if (finalStatus === \"committed\") {\n next.push({ tool: \"graph\", description: \"Discover connections\", parameters: { action: \"suggest\", entryId: finalEntryId } });\n } else if (finalStatus === \"proposed\") {\n next.push({ tool: \"graph\", description: \"Discover connections\", parameters: { action: \"suggest\", entryId: finalEntryId } });\n } else {\n if (userLinkResults.length === 0) {\n next.push({ tool: \"graph\", description: \"Discover links\", parameters: { action: \"suggest\", entryId: finalEntryId } });\n }\n next.push({ tool: \"commit-entry\", description: \"Commit to Chain\", parameters: { entryId: finalEntryId } });\n }\n\n const summary = finalStatus === \"committed\"\n ? `Captured and committed ${finalEntryId} (${name}) to ${resolvedCollection}. Quality ${quality.score}/10.`\n : finalStatus === \"proposed\"\n ? `Captured ${finalEntryId} (${name}) in ${resolvedCollection} and created a proposal for commit. Quality ${quality.score}/10.`\n : `Captured ${finalEntryId} (${name}) as draft in ${resolvedCollection}. Quality ${quality.score}/10.`;\n\n const expectedFields = (col.fields ?? []).map((f: any) => ({\n key: f.key, type: f.type, ...(f.required && { required: true }),\n }));\n\n // WP-316 S1a: Build CaptureContract for the EnvelopeSuccess.contract field.\n // Agents can read required fields upfront without a separate round-trip.\n const captureContractForEnvelope = {\n requiredFields: (col.fields ?? []).filter((f: any) => f.required === true).map((f: any) => f.key as string),\n allFields: (col.fields ?? []).map((f: any) => ({\n key: f.key as string,\n required: f.required === true,\n type: f.type as string,\n ...(f.helpText ? { helpText: f.helpText as string } : {}),\n })),\n ...(col.captureExpectation ? { captureExpectation: col.captureExpectation as string } : {}),\n };\n\n const totalMs = Date.now() - timingStart;\n const timing = {\n classifyMs: tAfterClassify - timingStart,\n createMs: tAfterCreate - tAfterClassify,\n autoLinkMs: tAfterRelations - tAfterCreate,\n qualityMs: tAfterQuality - tAfterRelations,\n totalMs,\n };\n\n const toolResult = {\n content: [{ type: \"text\" as const, text: lines.join(\"\\n\") }],\n structuredContent: {\n ...success(\n summary,\n {\n entryId: finalEntryId,\n collection: resolvedCollection,\n name,\n status: finalStatus,\n qualityScore: quality.score,\n qualityVerdict: verdictResult?.verdict\n ? { ...verdictResult.verdict, source: verdictResult.source ?? \"heuristic\" }\n : undefined,\n ...(classifierMeta && { classifier: classifierMeta }),\n ...(studioUrl && { studioUrl }),\n ...(entryWarnings.length > 0 && { warnings: entryWarnings }),\n ...(normalizationMeta && (Object.keys(normalizationMeta.remapped).length > 0 || normalizationMeta.rejected.length > 0) && {\n normalization: {\n remapped: normalizationMeta.remapped,\n rejected: normalizationMeta.rejected,\n },\n }),\n expectedFields,\n // BET-272 S3: Advisory quality hints — always included (empty array when all criteria pass)\n qualityHints: formativeHints,\n // BET-272 S5: Advisory relation suggestions from graph (BR-144, STD-147)\n relationSuggestions: relationSuggestionsFromCreate,\n // WP-318 S2: Pre-write grounding report — always included (empty arrays when no suggestions)\n groundingReport,\n },\n next,\n ),\n // WP-316 S1a: Populate contract field so agents know required fields upfront.\n contract: captureContractForEnvelope,\n _meta: { timing },\n },\n };\n\n return toolResult;\n })\n );\n trackWriteTool(captureTool);\n\n // ── Batch Capture Tool ─────────────────────────────────────────────────\n\n const batchCaptureTool = server.registerTool(\n \"batch-capture\",\n {\n title: \"Batch Capture\",\n description:\n \"Create multiple knowledge entries in one call. Ideal for workspace setup, document ingestion, \" +\n \"or any scenario where you need to capture many entries at once.\\n\\n\" +\n \"Collection is optional per entry — omit it and the LLM classifier auto-routes (FEAT-160). \" +\n \"High/medium confidence entries are created; low confidence entries are skipped and returned \" +\n \"with suggested collections for manual review.\\n\\n\" +\n \"Each entry is created independently — if one fails, the others still succeed. \" +\n \"Returns a compact summary instead of per-entry quality scorecards.\\n\\n\" +\n \"Auto-linking runs per entry but contradiction checks and readiness hints are skipped for speed. \" +\n \"Use `quality action=check` on individual entries afterward if needed.\\n\\n\" +\n \"Pass `autoCommit: false` to keep the whole batch draft-first. If omitted, \" +\n \"Open mode workspaces commit by default and consensus/role modes keep drafts.\",\n inputSchema: batchCaptureSchema.shape,\n annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: false },\n },\n thinWrapper(async ({ entries, autoCommit, preview }) => {\n requireWriteAccess();\n\n const batchTimingStart = Date.now();\n\n const agentId = getAgentSessionId();\n const createdBy = agentId ? `agent:${agentId}` : \"capture\";\n const wsCtx = await getWorkspaceContext();\n // TEN-1810: Refresh governanceMode in case workspace flipped to Open after session start.\n const freshGovernanceModeForBatch = await refreshWorkspaceGovernanceMode();\n const autoCommitApplied = shouldAutoCommitCapture(autoCommit, freshGovernanceModeForBatch);\n\n // ── FEAT-160: Parallel classification for entries without explicit collection ──\n const needsClassification = entries\n .map((e, i) => ({ ...e, index: i }))\n .filter((e) => !e.collection);\n\n let classificationMap = new Map<number, ResolvedCollection | null>();\n if (needsClassification.length > 0) {\n await server.sendLoggingMessage({\n level: \"info\",\n data: `Classifying ${needsClassification.length}/${entries.length} entries via LLM...`,\n logger: \"product-brain\",\n });\n const classifications = await Promise.all(\n needsClassification.map((e) =>\n resolveCollection({ name: e.name, description: e.description }).catch(() => null),\n ),\n );\n for (let i = 0; i < needsClassification.length; i++) {\n classificationMap.set(needsClassification[i].index, classifications[i]);\n }\n }\n\n type BatchEntryResult = {\n name: string;\n collection: string;\n entryId: string;\n ok: boolean;\n autoLinks: number;\n status: \"draft\" | \"committed\" | \"proposed\" | \"draft_on_failure\";\n classifiedBy?: \"llm\" | \"heuristic\" | \"explicit\";\n confidence?: number;\n confidenceTier?: \"high\" | \"medium\" | \"low\";\n error?: string;\n commitError?: string;\n warnings?: string[];\n normalization?: { remapped: Record<string, string>; rejected: string[] };\n // BET-167: Number of similar entries found during conflict pre-check\n overlapCount?: number;\n };\n const results: BatchEntryResult[] = [];\n type SkippedEntry = {\n index: number;\n name: string;\n suggestedCollection?: string;\n confidence?: number;\n alternatives?: Array<{ collection: string; confidence: number }>;\n };\n const skippedLowConfidence: SkippedEntry[] = [];\n\n await server.sendLoggingMessage({\n level: \"info\",\n data: `Batch capturing ${entries.length} entries...`,\n logger: \"product-brain\",\n });\n\n // BET-281: Use collectionCache instead of direct listCollections call.\n const allCollections = await getCollections();\n await populateHubCache();\n const collCache = new Map<string, any>();\n for (const c of allCollections) collCache.set(c.slug, c);\n const collIdToSlug = new Map<string, string>();\n for (const c of allCollections) collIdToSlug.set(c._id, c.slug);\n\n for (let entryIdx = 0; entryIdx < entries.length; entryIdx++) {\n const entry = entries[entryIdx];\n\n if (entryIdx > 0 && entryIdx % 5 === 0) {\n await server.sendLoggingMessage({\n level: \"info\",\n data: `Captured ${entryIdx}/${entries.length} entries...`,\n logger: \"product-brain\",\n });\n }\n\n // ── Resolve collection: explicit or classified ──\n let resolvedSlug: string | undefined = entry.collection;\n let classifiedBy: \"llm\" | \"heuristic\" | \"explicit\" | undefined;\n let confidence: number | undefined;\n let confidenceTier: \"high\" | \"medium\" | \"low\" | undefined;\n\n if (resolvedSlug) {\n classifiedBy = \"explicit\";\n } else {\n const resolved = classificationMap.get(entryIdx);\n // BET-288 S0: Fire confusion telemetry for batch classifications\n if (resolved) {\n emitClassificationTelemetry(resolved, wsCtx.workspaceId, {\n explicitCollectionProvided: false,\n autoRouted: resolved.tier !== \"low\",\n });\n }\n if (!resolved || resolved.tier === \"low\") {\n skippedLowConfidence.push({\n index: entryIdx,\n name: entry.name,\n suggestedCollection: resolved?.collection,\n confidence: resolved?.confidence,\n alternatives: resolved?.alternatives.slice(0, 3),\n });\n continue;\n }\n resolvedSlug = resolved.collection;\n classifiedBy = resolved.classifiedBy;\n confidence = resolved.confidence;\n confidenceTier = resolved.tier;\n }\n\n const profile = await getProfile(resolvedSlug);\n const col = collCache.get(resolvedSlug);\n\n if (!col) {\n results.push({\n name: entry.name,\n collection: resolvedSlug,\n entryId: \"\",\n ok: false,\n autoLinks: 0,\n status: \"draft\",\n classifiedBy,\n confidence,\n confidenceTier,\n error: `Collection \"${resolvedSlug}\" not found`,\n });\n continue;\n }\n\n // BR-111: entryId only allowed for business-rules and standards\n if (entry.entryId && resolvedSlug !== \"business-rules\" && resolvedSlug !== \"standards\") {\n results.push({\n name: entry.name,\n collection: resolvedSlug,\n entryId: \"\",\n ok: false,\n autoLinks: 0,\n status: \"draft\",\n classifiedBy,\n confidence,\n confidenceTier,\n error: `BR-111: entryId only allowed for business-rules and standards. Omit for ${resolvedSlug}.`,\n });\n continue;\n }\n\n const data = buildDataFromFields(col.fields ?? [], profile.descriptionField, entry.description);\n\n for (const def of profile.defaults) {\n if (def.value !== \"infer\" && def.value !== \"today\") data[def.key] = def.value;\n }\n\n if (profile.inferField) {\n const inferred = profile.inferField({\n collection: resolvedSlug, name: entry.name, description: entry.description,\n data, entryId: \"\", linksCreated: [], linksSuggested: [], collectionFields: col.fields ?? [],\n });\n for (const [key, val] of Object.entries(inferred)) {\n if (val !== undefined && val !== \"\") data[key] = val;\n }\n }\n\n if (isEmptyValue(data.date)) {\n const inferredSourceDate = inferSourceDate(entry.name, entry.description);\n if (inferredSourceDate && (col.fields ?? []).some((field) => field.key === \"date\")) {\n data.date = inferredSourceDate;\n }\n }\n\n if (!data[profile.descriptionField] && !data.description && !data.canonical) {\n data[profile.descriptionField || \"description\"] = entry.description;\n }\n\n if (entry.data && typeof entry.data === \"object\") {\n for (const [k, v] of Object.entries(entry.data)) {\n if (v !== undefined && v !== null && v !== \"\") data[k] = v;\n }\n }\n\n // DEC-231: work-packages collection is canonical — collection slug is the sole discriminator\n // DEC-313 GAP 2: also detect work package via canonicalKey from batch input\n const batchIsBet = resolvedSlug === \"work-packages\" || entry.canonicalKey === \"work_package\";\n // BET-288: derive strategy check from thinkingLayer instead of hardcoded slug\n const batchIsStrategy = col?.thinkingLayer === \"strategy\";\n const shouldDecomposeBatch =\n (batchIsStrategy || batchIsBet) && entry.description?.trim();\n let batchDecomposeWarning: string | undefined;\n if (shouldDecomposeBatch) {\n try {\n const decomposed = await kernelCall<{ decomposed: Record<string, unknown> } | null>(\n \"chain.decomposeContent\",\n {\n collectionSlug: resolvedSlug,\n entryName: entry.name,\n description: entry.description,\n existingData: data,\n ...(batchIsBet ? { canonicalKey: \"work_package\" } : {}),\n ...(col?.thinkingLayer ? { thinkingLayer: col.thinkingLayer } : {}),\n },\n );\n if (decomposed?.decomposed) {\n for (const [key, val] of Object.entries(decomposed.decomposed)) {\n if (isEmptyValue(data[key]) && isNonEmptyValue(val)) {\n data[key] = val;\n }\n }\n }\n } catch {\n batchDecomposeWarning = \"Content decomposition skipped (transient error). Entry saved with description only.\";\n }\n }\n canonicalizeSelects(data, col.fields ?? [], batchIsBet);\n\n // BET-132: bet captures keep flat fields — no data.links wrapping\n\n try {\n const result = await kernelMutation<{\n preview?: boolean;\n docId: string; entryId: string;\n /** DEC-896 / BR-76: 'active' means server auto-committed (Open mode). Guard skips commitEntry. */\n status?: \"draft\" | \"active\" | \"deprecated\";\n warnings?: string[];\n normalization?: { remapped: Record<string, string>; rejected: string[]; accepted: string[] };\n }>(\"chain.createEntry\", {\n collectionSlug: resolvedSlug,\n entryId: entry.entryId ?? undefined,\n name: entry.name,\n // DEC-896 / BR-76: omit status — server resolves from governanceMode (Open→active, else draft).\n data,\n createdBy,\n sessionId: agentId ?? undefined,\n canonicalKey: entry.canonicalKey ?? undefined,\n // BR-76 S2: Distinguish batch provenance in retrospective metrics (path a).\n originDetailOverride: \"mcp-batch-capture\",\n ...(entry.sourceRef ? { sourceRef: entry.sourceRef } : {}),\n ...(entry.sourceExcerpt ? { sourceExcerpt: entry.sourceExcerpt } : {}),\n ...(preview ? { preview: true } : {}),\n });\n const internalId = result.docId;\n const finalEntryId = result.entryId;\n const batchEntryWarnings = [\n ...(batchDecomposeWarning ? [batchDecomposeWarning] : []),\n ...(result.warnings ?? []),\n ];\n resolveGapsForEntry(entry.name, result.entryId);\n // DEC-896 / BR-76 S3: server already committed (Open mode auto-commit). Skip commitEntry.\n const batchWasAutoCommittedServerSide = result.status === \"active\";\n let finalStatus: \"draft\" | \"committed\" | \"proposed\" | \"draft_on_failure\" = batchWasAutoCommittedServerSide ? \"committed\" : \"draft\";\n let commitError: string | undefined;\n if (batchWasAutoCommittedServerSide) {\n await recordSessionActivity({ entryModified: internalId });\n trackChainEntryCommitted(wsCtx.workspaceId, {\n entry_id: finalEntryId,\n collection: resolvedSlug ?? undefined,\n commit_method: \"auto\",\n surface: \"mcp_capture\",\n });\n }\n\n let autoLinkCount = 0;\n // BET-167: Track overlaps from search results for conflict advisory\n let entryOverlapCount = 0;\n const searchQuery = extractSearchTerms(entry.name, entry.description);\n if (searchQuery) {\n try {\n const searchResults = await kernelQuery<any[]>(\"chain.searchEntries\", { query: searchQuery });\n const candidates = (searchResults ?? [])\n .filter((r) => r.entryId !== finalEntryId)\n .map((r) => {\n const conf = computeLinkConfidence(r, entry.name, entry.description, resolvedSlug!, collIdToSlug.get(r.collectionId) ?? \"unknown\");\n return { ...r, collSlug: collIdToSlug.get(r.collectionId) ?? \"unknown\", confidence: conf.score };\n })\n .sort((a, b) => b.confidence - a.confidence);\n\n // BET-167: Count similar entries for conflict pre-check (reuses search, no extra query)\n entryOverlapCount = candidates.filter((c) => c.entryId).length;\n\n const batchAutoLinks: Array<{ fromEntryId: string; toEntryId: string; type: string }> = [];\n for (const c of candidates) {\n if (batchAutoLinks.length >= MAX_AUTO_LINKS) break;\n if (c.confidence < AUTO_LINK_CONFIDENCE_THRESHOLD) break;\n if (!c.entryId) continue;\n const { type: relationType } = inferRelationType(resolvedSlug!, c.collSlug, profile);\n batchAutoLinks.push({ fromEntryId: finalEntryId, toEntryId: c.entryId, type: relationType });\n }\n\n if (batchAutoLinks.length > 0) {\n const batchRes = await kernelMutation<{ created: number }>(\"chain.createEntryRelations\", {\n relations: batchAutoLinks, sessionId: agentId ?? undefined,\n });\n autoLinkCount = batchRes.created;\n }\n } catch { /* search or batch link failed; entry still created */ }\n }\n\n // DEC-896 / BR-76 S3: skip commitEntry when server already returned active.\n if (autoCommitApplied && !batchWasAutoCommittedServerSide) {\n try {\n const semanticConflicts = await runSemanticConflictPreflight(entry.name, entry.description, resolvedSlug);\n const blockingConflicts = semanticConflicts.filter(\n (conflict) => conflict.type === \"contradiction\" && conflict.confidence >= BLOCKING_CONTRADICTION_THRESHOLD,\n );\n\n if (blockingConflicts.length > 0) {\n commitError = `blocked by semantic contradiction preflight: ${blockingConflicts[0]?.chainEntryId} ${blockingConflicts[0]?.explanation ?? \"\"}`.trim();\n } else {\n const commitResult = await kernelMutation<any>(\"chain.commitEntry\", {\n entryId: finalEntryId,\n author: agentId ? `agent:${agentId}` : undefined,\n sessionId: agentId ?? undefined,\n });\n finalStatus = commitResult?.status === \"proposal_created\" ? \"proposed\" : \"committed\";\n if (finalStatus === \"committed\") {\n await recordSessionActivity({ entryModified: internalId });\n trackChainEntryCommitted(wsCtx.workspaceId, {\n entry_id: finalEntryId,\n collection: resolvedSlug ?? undefined,\n commit_method: \"auto\",\n surface: \"mcp_capture\",\n });\n }\n }\n } catch (error: unknown) {\n // BR-76 S2 — DEC-888: Surface failures via log + payload + session TEN. Never silent.\n commitError = error instanceof Error ? error.message : String(error);\n finalStatus = \"draft_on_failure\";\n await recordCommitFailure({ entryId: finalEntryId, error, sessionId: agentId, server });\n }\n }\n\n const entryNorm = result.normalization;\n results.push({\n name: entry.name,\n collection: resolvedSlug,\n entryId: finalEntryId,\n ok: true,\n autoLinks: autoLinkCount,\n status: finalStatus,\n classifiedBy,\n confidence,\n confidenceTier,\n ...(commitError ? { commitError } : {}),\n ...(batchEntryWarnings.length > 0 ? { warnings: batchEntryWarnings } : {}),\n ...(entryNorm && (Object.keys(entryNorm.remapped).length > 0 || entryNorm.rejected.length > 0) && {\n normalization: { remapped: entryNorm.remapped, rejected: entryNorm.rejected },\n }),\n // BET-167: Track overlap count for conflict advisory\n ...(entryOverlapCount > 0 ? { overlapCount: entryOverlapCount } : {}),\n });\n } catch (error: unknown) {\n const msg = error instanceof Error ? error.message : String(error);\n results.push({\n name: entry.name,\n collection: resolvedSlug,\n entryId: \"\",\n ok: false,\n autoLinks: 0,\n status: \"draft\",\n classifiedBy,\n confidence,\n confidenceTier,\n error: msg,\n });\n }\n }\n\n const created = results.filter((r) => r.ok);\n const failed = results.filter((r) => !r.ok);\n const committed = created.filter((r) => r.status === \"committed\");\n const proposed = created.filter((r) => r.status === \"proposed\");\n const drafts = created.filter((r) => r.status === \"draft\");\n const commitFailed = created.filter((r) => r.status === \"draft_on_failure\");\n const classifiedCount = created.filter((r) => r.classifiedBy && r.classifiedBy !== \"explicit\").length;\n\n await server.sendLoggingMessage({\n level: \"info\",\n data: `Batch complete. ${created.length} succeeded, ${failed.length} failed, ${skippedLowConfidence.length} skipped (low confidence).`,\n logger: \"product-brain\",\n });\n\n const totalAutoLinks = created.reduce((sum, r) => sum + r.autoLinks, 0);\n\n const byCollection = new Map<string, number>();\n for (const r of created) {\n byCollection.set(r.collection, (byCollection.get(r.collection) ?? 0) + 1);\n }\n\n const lines: string[] = [\n `# Batch Capture Complete`,\n `**${created.length}** created, **${failed.length}** failed, **${skippedLowConfidence.length}** skipped out of ${entries.length} total.`,\n `**Auto-links created:** ${totalAutoLinks}`,\n \"\",\n ];\n\n if (classifiedCount > 0) {\n lines.push(`**Auto-classified:** ${classifiedCount} entries routed by LLM/heuristic.`);\n lines.push(\"\");\n }\n\n if (created.length > 0) {\n const commitFailedSegment = commitFailed.length > 0 ? `, ${commitFailed.length} commit-failed` : \"\";\n lines.push(\n `**Statuses:** ${committed.length} committed, ${proposed.length} proposed, ${drafts.length} draft${commitFailedSegment}.`,\n );\n lines.push(\"\");\n }\n\n if (byCollection.size > 0) {\n lines.push(\"## By Collection\");\n for (const [col, count] of byCollection) {\n lines.push(`- \\`${col}\\`: ${count} entries`);\n }\n lines.push(\"\");\n }\n\n if (created.length > 0) {\n const highConfidence = created.filter((r) => r.confidenceTier === \"high\" || r.classifiedBy === \"explicit\");\n const mediumConfidence = created.filter((r) => r.confidenceTier === \"medium\");\n\n if (highConfidence.length > 0) {\n lines.push(\"## Created — High Confidence / Explicit\");\n for (const r of highConfidence) {\n const linkNote = r.autoLinks > 0 ? `, ${r.autoLinks} auto-links` : \"\";\n const classNote = r.classifiedBy !== \"explicit\" ? ` (${r.classifiedBy} ${r.confidence}%)` : \"\";\n lines.push(`- **${r.entryId}**: ${r.name} [${r.collection}] — \\`${r.status}\\`${classNote}${linkNote}`);\n }\n }\n\n if (mediumConfidence.length > 0) {\n lines.push(\"\");\n lines.push(\"## Created — Medium Confidence (review recommended)\");\n for (const r of mediumConfidence) {\n const linkNote = r.autoLinks > 0 ? `, ${r.autoLinks} auto-links` : \"\";\n lines.push(`- **${r.entryId}**: ${r.name} [${r.collection}] — \\`${r.status}\\` (${r.classifiedBy} ${r.confidence}%)${linkNote}`);\n }\n lines.push(`\\n_Use \\`move-entry\\` to correct any misclassified entries._`);\n }\n }\n\n if (skippedLowConfidence.length > 0) {\n lines.push(\"\");\n lines.push(\"## Skipped — Low Confidence (needs explicit collection)\");\n for (const s of skippedLowConfidence) {\n const suggestion = s.suggestedCollection\n ? ` — best guess: \\`${s.suggestedCollection}\\` (${s.confidence}%)`\n : \" — no classification available\";\n const alts = s.alternatives?.length\n ? ` | alternatives: ${s.alternatives.map((a) => `\\`${a.collection}\\` (${a.confidence}%)`).join(\", \")}`\n : \"\";\n lines.push(`- **[${s.index}]** ${s.name}${suggestion}${alts}`);\n }\n lines.push(\"\");\n lines.push(\"_Re-capture these with an explicit `collection` or use the suggested collection._\");\n }\n\n if (commitFailed.length > 0) {\n lines.push(\"\");\n lines.push(\"## Saved as draft\");\n for (const r of commitFailed) {\n lines.push(`- **${r.entryId}**: ${r.name} [${r.collection}] — ${r.commitError}`);\n }\n }\n\n // BET-167: Advisory overlap notice for batch entries with potential duplicates\n if (autoCommitApplied) {\n const entriesWithOverlaps = created.filter((r) => r.overlapCount && r.overlapCount > 0);\n if (entriesWithOverlaps.length > 0) {\n lines.push(\"\");\n lines.push(\"## Potential Overlaps\");\n lines.push(`${entriesWithOverlaps.length} ${entriesWithOverlaps.length === 1 ? \"entry has\" : \"entries have\"} similar existing entries. Consider reviewing for duplicates:`);\n for (const r of entriesWithOverlaps) {\n lines.push(`- **${r.entryId}**: ${r.name} — ${r.overlapCount} similar ${r.overlapCount === 1 ? \"entry\" : \"entries\"}`);\n }\n }\n }\n\n const entriesWithWarnings = created.filter((r) => r.warnings && r.warnings.length > 0);\n if (entriesWithWarnings.length > 0) {\n lines.push(\"\");\n lines.push(\"## Validation Warnings\");\n for (const r of entriesWithWarnings) {\n lines.push(`- **${r.entryId}** (${r.name}): ${r.warnings!.join(\"; \")}`);\n }\n }\n\n if (failed.length > 0) {\n lines.push(\"\");\n lines.push(\"## Failed\");\n for (const r of failed) {\n lines.push(`- ${r.name} [${r.collection}]: _${r.error}_`);\n }\n lines.push(\"\");\n lines.push(`_If failed > 0, inspect \\`failedEntries\\` in the structured response and retry individually._`);\n }\n\n const entryIds = created.map((r) => r.entryId);\n if (entryIds.length > 0 || skippedLowConfidence.length > 0) {\n lines.push(\"\");\n lines.push(\"## Next Steps\");\n if (entryIds.length > 0) {\n lines.push(`- **Connect:** Run \\`graph action=suggest\\` on key entries to build the knowledge graph`);\n }\n if (drafts.length > 0) {\n lines.push(`- **Commit:** Use \\`commit-entry\\` to promote remaining drafts to SSOT`);\n }\n if (skippedLowConfidence.length > 0) {\n lines.push(`- **Classify:** Re-capture ${skippedLowConfidence.length} skipped entries with explicit collections`);\n }\n if (entryIds.length > 0) {\n lines.push(`- **Quality:** Run \\`quality action=check\\` on individual entries to assess completeness`);\n }\n }\n\n const skippedNote = skippedLowConfidence.length > 0 ? `, ${skippedLowConfidence.length} skipped (low confidence)` : \"\";\n const classifiedNote = classifiedCount > 0 ? `, ${classifiedCount} auto-classified` : \"\";\n const commitFailedNote = commitFailed.length > 0 ? `, ${commitFailed.length} commit-failed` : \"\";\n const summary =\n failed.length > 0 || skippedLowConfidence.length > 0 || commitFailed.length > 0\n ? `Batch captured ${created.length}/${entries.length} entries (${failed.length} failed${skippedNote}, ${committed.length} committed, ${proposed.length} proposed, ${drafts.length} draft${commitFailedNote}${classifiedNote}).`\n : `Batch captured ${created.length} entries successfully (${committed.length} committed, ${proposed.length} proposed, ${drafts.length} draft${classifiedNote}).`;\n\n const firstDraft = drafts[0];\n\n const next: NextAction[] = [];\n if (created.length > 0) {\n next.push({ tool: \"graph\", description: \"Discover connections\", parameters: { action: \"suggest\", entryId: created[0].entryId } });\n }\n if (firstDraft) {\n next.push({ tool: \"commit-entry\" as const, description: \"Commit first draft\", parameters: { entryId: firstDraft.entryId } });\n }\n if (skippedLowConfidence.length > 0) {\n next.push({ tool: \"capture\", description: `Capture skipped entry with explicit collection`, parameters: { name: skippedLowConfidence[0].name, collection: skippedLowConfidence[0].suggestedCollection ?? \"\" } });\n }\n\n const batchTotalMs = Date.now() - batchTimingStart;\n const batchTiming = {\n totalMs: batchTotalMs,\n perEntryAvgMs: created.length > 0 ? Math.round(batchTotalMs / created.length) : 0,\n };\n\n return {\n content: [{ type: \"text\" as const, text: lines.join(\"\\n\") }],\n structuredContent: {\n ...success(\n summary,\n {\n captured: created.map((r) => ({\n entryId: r.entryId,\n collection: r.collection,\n name: r.name,\n status: r.status,\n ...(r.classifiedBy ? { classifiedBy: r.classifiedBy } : {}),\n ...(r.confidence != null ? { confidence: r.confidence } : {}),\n ...(r.confidenceTier ? { confidenceTier: r.confidenceTier } : {}),\n ...(r.warnings?.length ? { warnings: r.warnings } : {}),\n ...(r.normalization ? { normalization: r.normalization } : {}),\n ...(r.commitError ? { commitError: r.commitError } : {}),\n })),\n total: created.length,\n failed: failed.length,\n committed: committed.length,\n proposed: proposed.length,\n drafts: drafts.length,\n ...(commitFailed.length > 0 ? { commitFailed: commitFailed.length } : {}),\n ...(classifiedCount > 0 ? { classified: classifiedCount } : {}),\n autoCommitApplied,\n ...(skippedLowConfidence.length > 0 && {\n skippedLowConfidence: skippedLowConfidence.map((s) => ({\n index: s.index,\n name: s.name,\n ...(s.suggestedCollection ? { suggestedCollection: s.suggestedCollection } : {}),\n ...(s.confidence != null ? { confidence: s.confidence } : {}),\n ...(s.alternatives?.length ? { alternatives: s.alternatives } : {}),\n })),\n }),\n ...(failed.length > 0 && {\n failedEntries: failed.map((r) => ({\n index: results.indexOf(r),\n collection: r.collection,\n name: r.name,\n error: r.error ?? \"unknown error\",\n })),\n }),\n },\n next,\n ),\n _meta: { timing: batchTiming },\n },\n };\n })\n );\n trackWriteTool(batchCaptureTool);\n\n}\n\n// ── Helpers ────────────────────────────────────────────────────────────────\n\n/**\n * BR-76 S2 — DEC-888: Surface commitEntry failures so they are never silent.\n * Fire-and-forget: each fan-out step has its own try/catch so a failure in one\n * does NOT block the others and does NOT change the caller's finalStatus.\n *\n * Steps:\n * 1. server.sendLoggingMessage (level \"error\") — visible in MCP transcript stream.\n * 2. Session-bound TEN emit via chain.createEntry — persisted to Chain when an\n * active write session (agentId) exists.\n *\n * Persistence to a queryable DB field is deferred (TEN-1811 follow-on).\n */\nasync function recordCommitFailure({\n entryId,\n error,\n sessionId,\n server,\n}: {\n entryId: string;\n error: unknown;\n sessionId: string | null | undefined;\n server: McpServer;\n}): Promise<void> {\n const errorMessage = error instanceof Error ? error.message : String(error);\n const logLine = `commitEntry failed for ${entryId}: ${errorMessage}${sessionId ? ` (session: ${sessionId})` : \"\"}`;\n\n // Step 1: MCP transcript log — level \"error\"\n try {\n await server.sendLoggingMessage({ level: \"error\", data: logLine, logger: \"product-brain\" });\n } catch {\n // Logging must never break the caller\n }\n\n // Step 2: Session-bound TEN emit — only when an active write session exists\n if (sessionId) {\n try {\n const tenName = `commitEntry failed for ${entryId} — ${errorMessage}`.slice(0, 250);\n await kernelMutation(\"chain.createEntry\", {\n collectionSlug: \"tensions\",\n name: tenName,\n // Failure audit TENs intentionally stay draft — they need explicit human review,\n // not auto-commit, even in Open mode.\n status: \"draft\",\n data: {},\n createdBy: `agent:${sessionId}`,\n sessionId,\n });\n } catch {\n // TEN emit is advisory — never propagates\n }\n }\n}\n\n// Stop words excluded from noun phrase extraction\nconst STOP_WORDS = new Set([\n \"the\", \"and\", \"for\", \"are\", \"but\", \"not\", \"you\", \"all\", \"can\", \"has\", \"her\",\n \"was\", \"one\", \"our\", \"out\", \"day\", \"had\", \"hot\", \"how\", \"its\", \"may\", \"new\",\n \"now\", \"old\", \"see\", \"way\", \"who\", \"did\", \"get\", \"let\", \"say\", \"she\", \"too\",\n \"use\", \"from\", \"have\", \"been\", \"each\", \"that\", \"this\", \"with\", \"will\", \"they\",\n \"what\", \"when\", \"make\", \"like\", \"long\", \"look\", \"many\", \"some\", \"them\", \"than\",\n \"most\", \"only\", \"over\", \"such\", \"into\", \"also\", \"back\", \"just\", \"much\", \"must\",\n \"name\", \"very\", \"your\", \"after\", \"which\", \"their\", \"about\", \"would\", \"there\",\n \"should\", \"could\", \"other\", \"these\", \"first\", \"being\", \"those\", \"still\", \"where\",\n]);\n\nfunction tokenizeText(input: string): string[] {\n return input\n .toLowerCase()\n .replace(/[^\\p{L}\\p{N}\\s]+/gu, \" \")\n .split(/\\s+/)\n .filter(Boolean);\n}\n\n/**\n * Keyword contradiction check against governance entries.\n * Extracts terms 4+ chars, searches architecture and business-rules,\n * checks for 'governs' relations, returns formatted warnings.\n * Non-blocking — never throws, never prevents the operation.\n */\nexport interface ContradictionWarning {\n entryId: string;\n name: string;\n collection: string;\n governsCount: number;\n}\n\nexport async function runContradictionCheck(\n name: string,\n description: string,\n): Promise<ContradictionWarning[]> {\n const warnings: ContradictionWarning[] = [];\n try {\n const keyTerms = tokenizeText(`${name} ${description}`)\n .filter((w) => w.length >= 4 && !STOP_WORDS.has(w))\n .slice(0, 8);\n\n if (keyTerms.length === 0) return warnings;\n\n const searchQuery = keyTerms.slice(0, 5).join(\" \");\n const [govResults, archResults] = await Promise.all([\n kernelQuery<any[]>(\"chain.searchEntries\", { query: searchQuery, collectionSlug: \"business-rules\" }),\n kernelQuery<any[]>(\"chain.searchEntries\", { query: searchQuery, collectionSlug: \"architecture\" }),\n ]);\n\n const allGov = [...(govResults ?? []), ...(archResults ?? [])].slice(0, 5);\n\n for (const entry of allGov) {\n const entryTokens = new Set(tokenizeText(`${entry.name} ${entry.data?.description ?? \"\"}`));\n const matched = keyTerms.filter((t) => entryTokens.has(t));\n if (matched.length < 3) continue;\n\n // Check for 'governs' relations\n let governsCount = 0;\n try {\n const relations = await kernelQuery<any[]>(\"chain.listEntryRelations\", {\n entryId: entry.entryId,\n });\n governsCount = (relations ?? []).filter((r: any) => r.type === \"governs\").length;\n } catch { /* non-critical */ }\n\n warnings.push({\n entryId: entry.entryId ?? \"\",\n name: entry.name,\n collection: entry.collectionSlug ?? \"\",\n governsCount,\n });\n }\n } catch {\n // Contradiction check is advisory — never blocks the operation\n }\n return warnings;\n}\n\ninterface SemanticConflictResult {\n chainEntryId: string;\n chainEntryName: string;\n type: \"contradiction\" | \"supersession\" | \"duplicate\" | \"overlap\";\n confidence: number;\n explanation: string;\n}\n\nconst BLOCKING_CONTRADICTION_THRESHOLD = 0.75;\n\nasync function runSemanticConflictPreflight(\n name: string,\n description: string,\n collectionHint?: string,\n): Promise<SemanticConflictResult[]> {\n try {\n const conflicts = await kernelQuery<SemanticConflictResult[] | null>(\"chain.detectSemanticConflicts\", {\n name,\n description,\n ...(collectionHint ? { collectionHint } : {}),\n });\n return conflicts ?? [];\n } catch {\n return [];\n }\n}\n\n// ── Quality Coaching Helpers ──────────────────────────────────────────────\n\nfunction withTimeout<T>(promise: Promise<T>, ms: number): Promise<T> {\n return Promise.race([\n promise,\n new Promise<T>((_, reject) =>\n setTimeout(() => reject(new Error(\"quality coaching timeout\")), ms),\n ),\n ]);\n}\n\n/**\n * Format a full quality coaching result (from evaluateAtCapture / evaluateAtCommit)\n * for inclusion in MCP capture/commit responses.\n */\nexport function formatRubricCoaching(result: any): string {\n const { verdict, rogerMartin } = result;\n if (!verdict || verdict.criteria.length === 0) return \"\";\n\n const lines: string[] = [\"## Semantic Quality\"];\n const failed = (verdict.criteria ?? []).filter((c: any) => !c.passed);\n const total = verdict.criteria?.length ?? 0;\n const passedCount = total - failed.length;\n\n if (verdict.passed) {\n lines.push(`All ${total} rubric criteria pass for \\`${verdict.canonicalKey}\\` (${verdict.tier} tier).`);\n } else {\n lines.push(`${passedCount}/${total} criteria pass for \\`${verdict.canonicalKey}\\` (${verdict.tier} tier)`);\n lines.push(\"\");\n for (const c of verdict.criteria) {\n const icon = c.passed ? \"[x]\" : \"[ ]\";\n const extra = c.passed ? \"\" : ` — ${c.hint}`;\n lines.push(`${icon} ${c.id}${extra}`);\n }\n\n if (verdict.weakest) {\n lines.push(\"\");\n lines.push(`**Coaching hint:** ${verdict.weakest.hint}`);\n lines.push(`_Question to consider:_ ${verdict.weakest.questionTemplate}`);\n }\n }\n\n if (rogerMartin) {\n lines.push(\"\");\n lines.push(\"### Roger Martin Test\");\n if (rogerMartin.isStrategicChoice) {\n lines.push(\"This principle passes — the opposite is a reasonable strategic choice.\");\n } else {\n lines.push(`This principle may not be a strategic choice. ${rogerMartin.reasoning}`);\n if (rogerMartin.suggestion) {\n lines.push(`_Suggestion:_ ${rogerMartin.suggestion}`);\n }\n }\n }\n\n return lines.join(\"\\n\");\n}\n\n/**\n * Format a cached rubric verdict section for quality check responses.\n * SOS-e4r5cn: capability and visibility must ship together.\n */\nexport function formatRubricVerdictSection(verdict: any): string {\n if (!verdict || !verdict.criteria || verdict.criteria.length === 0) return \"\";\n\n const lines: string[] = [\"## Semantic Quality\"];\n const failed = verdict.criteria.filter((c: any) => !c.passed);\n const total = verdict.criteria.length;\n const passedCount = total - failed.length;\n\n const durationSuffix = verdict.llmDurationMs ? ` in ${(verdict.llmDurationMs / 1000).toFixed(1)}s` : '';\n const statusNote = verdict.llmStatus === 'pending'\n ? ' — LLM evaluation in progress...'\n : verdict.llmStatus === 'failed'\n ? ` — LLM evaluation failed${verdict.llmError ? `: ${verdict.llmError}` : ''}, showing heuristic results`\n : verdict.source === 'llm' && durationSuffix\n ? ` — evaluated${durationSuffix}`\n : '';\n\n if (failed.length === 0) {\n lines.push(`All ${total} rubric criteria pass for \\`${verdict.canonicalKey}\\` (${verdict.tier} tier, ${verdict.source} evaluation).${statusNote}`);\n } else {\n lines.push(`${passedCount}/${total} criteria pass for \\`${verdict.canonicalKey}\\` (${verdict.tier} tier, ${verdict.source} evaluation)${statusNote}`);\n lines.push(\"\");\n for (const c of verdict.criteria) {\n const icon = c.passed ? \"[x]\" : \"[ ]\";\n const extra = c.passed ? \"\" : ` — ${c.hint}`;\n lines.push(`${icon} ${c.id}${extra}`);\n }\n\n if (verdict.weakest) {\n lines.push(\"\");\n lines.push(`**Top improvement:** ${verdict.weakest.hint}`);\n }\n }\n\n if (verdict.rogerMartin) {\n const rm = verdict.rogerMartin;\n lines.push(\"\");\n lines.push(\"### Roger Martin Test\");\n if (rm.isStrategicChoice) {\n lines.push(`This is a real strategic choice — the opposite is reasonable. ${rm.reasoning}`);\n } else {\n lines.push(`This may not be a strategic choice. ${rm.reasoning}`);\n if (rm.suggestion) {\n lines.push(`_Suggestion:_ ${rm.suggestion}`);\n }\n }\n }\n\n return lines.join(\"\\n\");\n}\n","/**\n * Shared helpers for knowledge tools. Extracted from knowledge.ts for reuse\n * across entries, relations, graph, context, and collections compound tools.\n */\n\n// ─── Epistemic Status ─────────────────────────────────────────────────\n// Pure derivation of confidence level for claim-carrying entries (BR-85).\n// Used by entries/get, commit-entry, and context/gather to surface trust signals.\n\n// BET-281: Epistemic collections have fundamentally different validation logic\n// (assumptions use untested→testing→validated/invalidated; insights use hypothesis→evidenced→validated).\n// This is intentionally collection-specific (Tier 3 pattern per STD-20).\n// When governanceRole is available, replace with governanceRole === 'epistemic' filter.\nconst EPISTEMIC_COLLECTIONS = new Set([\"insights\", \"assumptions\"]);\n\nexport interface EpistemicStatus {\n level: \"validated\" | \"evidenced\" | \"hypothesis\" | \"untested\" | \"testing\" | \"invalidated\";\n reason: string;\n action?: string;\n}\n\n/**\n * Derives epistemic confidence from entry data + relations.\n * Returns null for non-epistemic entry types.\n */\nexport function deriveEpistemicStatus(entry: {\n collectionName?: string;\n workflowStatus?: string;\n relations?: Array<{ type?: string; direction?: string }>;\n}): EpistemicStatus | null {\n const coll = entry.collectionName?.toLowerCase();\n if (!coll || !EPISTEMIC_COLLECTIONS.has(coll)) return null;\n\n const relations = entry.relations ?? [];\n const hasValidates = relations.some(\n (r) => r.type === \"validates\" && r.direction === \"incoming\",\n );\n const hasInvalidates = relations.some(\n (r) => r.type === \"invalidates\" && r.direction === \"incoming\",\n );\n const evidenceCount = relations.filter(\n (r) => (r.type === \"validates\" || r.type === \"invalidates\") && r.direction === \"incoming\",\n ).length;\n\n if (coll === \"assumptions\") {\n const ws = entry.workflowStatus;\n if (ws === \"invalidated\" || hasInvalidates) {\n return { level: \"invalidated\", reason: \"Disproved by linked counter-evidence\" };\n }\n if (ws === \"validated\" || (hasValidates && ws !== \"untested\")) {\n return { level: \"validated\", reason: `${evidenceCount} evidence link${evidenceCount !== 1 ? \"s\" : \"\"}` };\n }\n if (ws === \"testing\") {\n return { level: \"testing\", reason: \"Experiment in progress\" };\n }\n return { level: \"untested\", reason: \"No evidence linked\", action: \"Link evidence via `relations action=create type=\\\"validates\\\"`\" };\n }\n\n // Insights: derive from workflowStatus first, then from relations (BR-85).\n // Deliberate AND: workflowStatus alone isn't enough — linked evidence is required.\n // Setting ws=\"validated\" without evidence still returns \"hypothesis\" per BR-85.\n const ws = entry.workflowStatus;\n if (ws === \"validated\" && hasValidates) {\n return { level: \"validated\", reason: `${evidenceCount} evidence link${evidenceCount !== 1 ? \"s\" : \"\"}` };\n }\n if (ws === \"evidenced\" || hasValidates) {\n return { level: \"evidenced\", reason: `${evidenceCount} evidence link${evidenceCount !== 1 ? \"s\" : \"\"}` };\n }\n // BR-85: insight without linked evidence defaults to hypothesis\n return {\n level: \"hypothesis\",\n reason: \"No linked evidence\",\n action: \"Link proof via `relations action=create type=\\\"validates\\\"`\",\n };\n}\n\n/** Format epistemic status as a single markdown line for MCP text responses. */\nexport function formatEpistemicLine(es: EpistemicStatus): string {\n const icon = es.level === \"validated\" ? \"✓\"\n : es.level === \"evidenced\" ? \"◎\"\n : es.level === \"hypothesis\" ? \"△\"\n : es.level === \"untested\" ? \"?\"\n : es.level === \"testing\" ? \"◎\"\n : \"✕\";\n const suffix = es.action ? ` ${es.action}` : \"\";\n return `**Confidence:** ${icon} ${es.level} — ${es.reason}.${suffix}`;\n}\n\n/** Adapts a raw entry record into the shape deriveEpistemicStatus expects. */\nexport function toEpistemicInput(entry: Record<string, unknown>) {\n return {\n collectionName: typeof entry.collectionName === \"string\" ? entry.collectionName : undefined,\n workflowStatus: typeof entry.workflowStatus === \"string\" ? entry.workflowStatus : undefined,\n relations: Array.isArray(entry.relations)\n ? (entry.relations as Array<{ direction?: string; type?: string }>).map((r) => ({ type: r.type, direction: r.direction }))\n : undefined,\n };\n}\n\n/** Compact suffix for list/context views. Only emits for low-confidence entries. */\nexport function epistemicSuffix(es: EpistemicStatus | null): string {\n if (!es) return \"\";\n if (es.level === \"validated\") return \"\";\n if (es.level === \"evidenced\") return \"\";\n if (es.level === \"hypothesis\") return \" `△ hypothesis`\";\n if (es.level === \"untested\") return \" `? untested`\";\n if (es.level === \"testing\") return \" `◎ testing`\";\n if (es.level === \"invalidated\") return \" `✕ invalidated`\";\n return \"\";\n}\n\n// ─── General helpers ──────────────────────────────────────────────────\n\nexport function extractPreview(data: unknown, maxLen: number): string {\n if (!data || typeof data !== \"object\") return \"\";\n const d = data as Record<string, unknown>;\n const raw = d.description ?? d.canonical ?? d.detail ?? d.rule ?? \"\";\n if (typeof raw !== \"string\" || !raw) return \"\";\n return raw.length > maxLen ? raw.substring(0, maxLen) + \"...\" : raw;\n}\n\n/**\n * Canonical tool-name translation map.\n * Maps deprecated atomic tool names to their consolidated compound equivalents.\n * Used by context/orient to annotate stale references in historical content\n * (plans, docs, prototypes) without bulk-editing those files.\n */\nexport const TOOL_NAME_MIGRATIONS: ReadonlyMap<string, string> = new Map([\n [\"list-entries\", 'entries action=\"list\"'],\n [\"get-entry\", 'entries action=\"get\"'],\n [\"batch-get\", 'entries action=\"batch\"'],\n [\"search\", 'entries action=\"search\"'],\n [\"relate-entries\", 'relations action=\"create\"'],\n [\"batch-relate\", 'relations action=\"batch-create\"'],\n [\"find-related\", 'graph action=\"find\"'],\n [\"suggest-links\", 'graph action=\"suggest\"'],\n [\"gather-context\", 'context action=\"gather\"'],\n [\"get-build-context\", 'context action=\"build\"'],\n [\"list-collections\", 'collections action=\"list\"'],\n [\"create-collection\", 'collections action=\"create\"'],\n [\"update-collection\", 'collections action=\"update\"'],\n [\"agent-start\", 'session action=\"start\"'],\n [\"agent-close\", 'session action=\"close\"'],\n [\"agent-status\", 'session action=\"status\"'],\n [\"workspace-status\", 'health action=\"status\"'],\n [\"mcp-audit\", 'health action=\"audit\"'],\n [\"quality-check\", 'quality action=\"check\"'],\n [\"re-evaluate\", 'quality action=\"re-evaluate\"'],\n [\"list-workflows\", 'workflows action=\"list\"'],\n [\"workflow-checkpoint\", 'workflows action=\"checkpoint\"'],\n [\"wrapup\", \"session-wrapup\"],\n [\"finish\", \"session-wrapup\"],\n]);\n\n/**\n * Translates any deprecated tool names found in text to their current equivalents.\n * Returns null if no translations were needed, or a footnote string listing them.\n */\nexport function translateStaleToolNames(text: string): string | null {\n const found: string[] = [];\n for (const [old, current] of TOOL_NAME_MIGRATIONS) {\n const pattern = new RegExp(`\\\\b${old.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\")}\\\\b`, \"g\");\n if (pattern.test(text)) {\n found.push(`\\`${old}\\` → \\`${current}\\``);\n }\n }\n if (found.length === 0) return null;\n return `\\n\\n---\\n_Tool name translations (these references use deprecated names):_\\n${found.map(f => `- ${f}`).join(\"\\n\")}`;\n}\n","/**\n * Tool surface module — DEPRECATED, scheduled for removal.\n *\n * Previously controlled write-tool visibility. Write tools are now always\n * visible; handler-level guards (requireWriteAccess) enforce access.\n *\n * Both exports are no-ops retained solely for call-site compatibility.\n * A future cleanup slice should remove all `trackWriteTool` / `initToolSurface`\n * call sites and delete this file.\n */\n\n/** @deprecated No-op. Remove call sites and delete this module. */\nexport function initToolSurface(): void {}\n\n/** @deprecated No-op. Remove call sites and delete this module. */\nexport function trackWriteTool(_tool: unknown): void {}\n","/**\n * Knowledge gap store — tracks what agents searched for and couldn't find.\n * BET-89: Knowledge Gap Sensing.\n *\n * Dual layer:\n * In-memory — session-scoped, fast, used for wrapup/start surfacing.\n * Persistent — fire-and-forget writes to Convex via `gaps.record`.\n * Cross-session, admin-only reads. Survives restarts.\n *\n * Gaps are keyed by agent session ID so concurrent sessions don't leak\n * state across each other. Sessionless callers (e.g. stdio transport)\n * use a fallback \"__sessionless__\" key.\n *\n * Deduplicates within a 60s window to avoid noise from confused agents\n * retrying the same query.\n */\n\nimport { kernelMutation, getAgentSessionId } from \"./client.js\";\n\nexport type GapType =\n | \"search_zero\"\n | \"context_task_empty\"\n | \"context_entry_isolated\"\n | \"context_graph_empty\";\n\nexport interface KnowledgeGap {\n query: string;\n tool: string;\n action: string;\n gapType: GapType;\n collectionScope?: string;\n timestamp: number;\n}\n\nconst SESSIONLESS_KEY = \"__sessionless__\";\nconst sessionGaps = new Map<string, KnowledgeGap[]>();\nconst DEDUP_WINDOW_MS = 60_000;\n\nfunction currentSessionKey(): string {\n return getAgentSessionId() ?? SESSIONLESS_KEY;\n}\n\nfunction getGapsForSession(sessionKey: string): KnowledgeGap[] {\n let gaps = sessionGaps.get(sessionKey);\n if (!gaps) {\n gaps = [];\n sessionGaps.set(sessionKey, gaps);\n }\n return gaps;\n}\n\nfunction isDuplicate(gaps: KnowledgeGap[], gap: KnowledgeGap): boolean {\n const cutoff = gap.timestamp - DEDUP_WINDOW_MS;\n return gaps.some(\n (existing) =>\n existing.query === gap.query &&\n existing.tool === gap.tool &&\n existing.action === gap.action &&\n existing.timestamp >= cutoff,\n );\n}\n\n/**\n * Record a gap in-memory and persist to Convex (fire-and-forget).\n * Returns true if the gap was new (not deduplicated).\n */\nexport function recordGap(gap: Omit<KnowledgeGap, \"timestamp\">): boolean {\n const timestamped: KnowledgeGap = { ...gap, timestamp: Date.now() };\n const sessionKey = currentSessionKey();\n const gaps = getGapsForSession(sessionKey);\n if (isDuplicate(gaps, timestamped)) return false;\n gaps.push(timestamped);\n\n persistGap(gap);\n return true;\n}\n\nfunction persistGap(gap: Omit<KnowledgeGap, \"timestamp\">): void {\n const sessionId = getAgentSessionId();\n kernelMutation(\"gaps.record\", {\n sessionId: sessionId ?? undefined,\n query: gap.query,\n tool: gap.tool,\n action: gap.action,\n gapType: gap.gapType,\n collectionScope: gap.collectionScope,\n }).catch(() => {\n // Persistence is best-effort; in-memory store is the primary path.\n });\n}\n\nexport function getSessionGaps(): readonly KnowledgeGap[] {\n return getGapsForSession(currentSessionKey());\n}\n\n/** Top gaps by frequency — returns unique queries ranked by how often they appeared. */\nexport function getTopGaps(limit = 5): Array<{ query: string; count: number; gapType: GapType }> {\n const gaps = getGapsForSession(currentSessionKey());\n const counts = new Map<string, { count: number; gapType: GapType }>();\n for (const gap of gaps) {\n const key = gap.query.toLowerCase().trim();\n const existing = counts.get(key);\n if (existing) {\n existing.count++;\n } else {\n counts.set(key, { count: 1, gapType: gap.gapType });\n }\n }\n return [...counts.entries()]\n .map(([query, { count, gapType }]) => ({ query, count, gapType }))\n .sort((a, b) => b.count - a.count)\n .slice(0, limit);\n}\n\nexport function clearSessionGaps(): void {\n const sessionKey = currentSessionKey();\n sessionGaps.delete(sessionKey);\n}\n\n/**\n * Remove all gaps for a specific session ID.\n * Called during session teardown to prevent unbounded memory growth.\n */\nexport function cleanupSessionGaps(sessionId: string): void {\n sessionGaps.delete(sessionId);\n}\n\n/**\n * Resolve persistent gaps matching a newly captured entry.\n * Fire-and-forget — called from smart-capture after successful create.\n */\nexport function resolveGapsForEntry(entryName: string, entryId: string): void {\n kernelMutation(\"gaps.resolve\", { entryName, entryId }).catch(() => {\n // Best-effort decay; failure doesn't affect capture flow.\n });\n}\n","/**\n * Unified Collection Routing — FEAT-157 (BET-105 Slice 0)\n *\n * Thin client: delegates to Convex chain.resolveCollection (L5 orchestration).\n * All entry-creation surfaces call this; Convex runs LLM → heuristic → typeHint.\n *\n * Chain: DEC-163 (L5 placement), FEAT-157, FEAT-159 (confidence gating)\n */\n\nimport { kernelCall, getAgentSessionId } from \"../client.js\";\n\n// ── Types (mirror Convex ResolvedCollection contract) ─────────────────────\n\nexport type ConfidenceTier = \"high\" | \"medium\" | \"low\";\n\nexport interface ResolvedCollection {\n collection: string;\n confidence: number;\n tier: ConfidenceTier;\n alternatives: Array<{ collection: string; confidence: number }>;\n classifiedBy: \"llm\" | \"heuristic\";\n reasoning: string;\n /** BET-288 S0: thinkingLayer of the resolved collection for confusion telemetry. */\n thinkingLayer?: string;\n}\n\n// ── Main entry point (thin client) ───────────────────────────────────────\n\nexport async function resolveCollection(params: {\n name: string;\n description: string;\n typeHint?: string;\n allowReviewRouting?: boolean;\n}): Promise<ResolvedCollection | null> {\n const { name, description, typeHint, allowReviewRouting } = params;\n\n const sessionId = getAgentSessionId();\n const result = await kernelCall<ResolvedCollection | null>(\"chain.resolveCollection\", {\n entryName: name,\n entryDescription: description,\n ...(typeHint ? { typeHint } : {}),\n ...(allowReviewRouting ? { allowReviewRouting } : {}),\n ...(sessionId ? { agentSessionId: sessionId } : {}),\n });\n\n return result ?? null;\n}\n","/**\n * Response Envelope — Agent-Native MCP Contract (BET-78)\n *\n * Universal response shape for all MCP tool responses.\n * Lives in structuredContent — zero breaking changes to content[0].text.\n *\n * Design: envelope IS structuredContent, not nested inside it.\n * Discriminated on `ok` for O(1) agent parsing.\n */\n\nimport { z, type ZodTypeAny } from \"zod\";\nimport { classifyError } from \"./errors.js\";\n\n// ─── Types ───────────────────────────────────────────────────────────────\n\nexport interface NextAction {\n tool: string;\n description: string;\n parameters: Record<string, unknown>;\n}\n\n/**\n * Describes the schema contract for a single collection's capture tool.\n * Returned in EnvelopeSuccess.contract for write tools so agents can\n * self-describe required fields without a separate round-trip.\n * WP-316 S0 — downstream slices populate this field on capture responses.\n */\nexport interface CaptureContractField {\n key: string;\n required: boolean;\n type: string;\n helpText?: string;\n}\n\nexport interface CaptureContract {\n requiredFields: string[];\n allFields: CaptureContractField[];\n captureExpectation?: string;\n}\n\n/** Per-step timing for capture pipeline (BET-105, TEN-359). */\nexport interface CaptureTiming {\n classifyMs: number;\n createMs: number;\n autoLinkMs: number;\n userLinksMs: number;\n qualityMs: number;\n totalMs: number;\n}\n\n/** Batch capture timing: wall-clock total and per-entry average. */\nexport interface BatchCaptureTiming {\n totalMs: number;\n perEntryAvgMs: number;\n}\n\nexport interface EnvelopeMeta {\n durationMs?: number;\n /** Per-step timing (single capture) or batch timing (batch-capture). */\n timing?: CaptureTiming | BatchCaptureTiming;\n}\n\nexport interface EnvelopeSuccess<T = Record<string, unknown>> {\n ok: true;\n summary: string;\n data: T;\n next?: NextAction[];\n /** WP-316 S0: Optional capture contract — populated by write tools on create/update responses. */\n contract?: CaptureContract;\n _meta?: EnvelopeMeta;\n}\n\nexport interface EnvelopeError {\n ok: false;\n code: string;\n message: string;\n recovery?: string;\n availableActions?: NextAction[];\n diagnostics?: Record<string, unknown>;\n _meta?: EnvelopeMeta;\n}\n\nexport type Envelope<T = Record<string, unknown>> =\n | EnvelopeSuccess<T>\n | EnvelopeError;\n\n// ─── Builders ────────────────────────────────────────────────────────────\n\nexport function success<T>(\n summary: string,\n data: T,\n next?: NextAction[],\n): EnvelopeSuccess<T> {\n return {\n ok: true,\n summary: summary || \"Operation completed.\",\n data,\n ...(next?.length ? { next } : {}),\n };\n}\n\nexport function failure(\n code: string,\n message: string,\n recovery?: string,\n availableActions?: NextAction[],\n diagnostics?: Record<string, unknown>,\n): EnvelopeError {\n return {\n ok: false,\n code,\n message,\n ...(recovery ? { recovery } : {}),\n ...(availableActions?.length ? { availableActions } : {}),\n ...(diagnostics ? { diagnostics } : {}),\n };\n}\n\n/** Shorthand for NOT_FOUND failures — the most common soft-failure pattern. */\nexport function notFound(id: string, hint?: string): EnvelopeError {\n return failure(\n \"NOT_FOUND\",\n `Entry '${id}' not found.`,\n hint ?? \"Use entries action=search to find the correct ID.\",\n [{ tool: \"entries\", description: \"Search entries\", parameters: { action: \"search\", query: id } }],\n );\n}\n\n/** Shorthand for VALIDATION_ERROR failures. */\nexport function validationError(message: string): EnvelopeError {\n return failure(\"VALIDATION_ERROR\", message);\n}\n\n// ─── Tool Response Helpers ───────────────────────────────────────────────\n\ntype TextContent = { type: \"text\"; text: string };\ntype ToolResult = {\n content: TextContent[];\n structuredContent?: Record<string, unknown>;\n isError?: boolean;\n};\n\n/** Build a `content` array from a single text string. */\nexport function textContent(text: string): TextContent[] {\n return [{ type: \"text\" as const, text }];\n}\n\n/**\n * Parse args against a Zod schema and return a typed result or a ready-to-return\n * validation error ToolResult. Eliminates the 5-line parse+check+format boilerplate.\n */\nexport function parseOrFail<T extends z.ZodTypeAny>(\n schema: T,\n args: unknown,\n): { ok: true; data: z.infer<T> } | { ok: false; result: ToolResult } {\n const parsed = schema.safeParse(args);\n if (parsed.success) return { ok: true, data: parsed.data };\n const issues = parsed.error.issues\n .map((i: z.ZodIssue) => `${i.path.join(\".\")}: ${i.message}`)\n .join(\"; \");\n const msg = `Invalid arguments: ${issues}`;\n return {\n ok: false,\n result: { content: textContent(msg), structuredContent: validationError(msg) },\n };\n}\n\n/** Standard response for unknown compound-tool actions. */\nexport function unknownAction(action: string, valid: readonly string[]): ToolResult {\n const msg = `Unknown action '${action}'. Valid actions: ${valid.join(\", \")}.`;\n return { content: textContent(msg), structuredContent: validationError(msg) };\n}\n\n// ─── Compound Result Builders ─────────────────────────────────────────\n// Eliminate the { content: [...], structuredContent: ... } boilerplate.\n\n/** Success result with human-readable text + structured envelope in one call. */\nexport function successResult<T>(\n text: string,\n summary: string,\n data: T,\n next?: NextAction[],\n): ToolResult {\n return { content: textContent(text), structuredContent: success(summary, data, next) };\n}\n\n/** Failure result with human-readable text + structured error envelope. */\nexport function failureResult(\n text: string,\n code: string,\n message: string,\n recovery?: string,\n availableActions?: NextAction[],\n diagnostics?: Record<string, unknown>,\n): ToolResult {\n return { content: textContent(text), structuredContent: failure(code, message, recovery, availableActions, diagnostics) };\n}\n\n/** Not-found result — the most common soft failure pattern. */\nexport function notFoundResult(id: string, text?: string, hint?: string): ToolResult {\n return { content: textContent(text ?? `Entry '${id}' not found.`), structuredContent: notFound(id, hint) };\n}\n\n/** Validation error result where the text and error message are the same. */\nexport function validationResult(message: string): ToolResult {\n return { content: textContent(message), structuredContent: validationError(message) };\n}\n\n// ─── Zod Schema Helper ──────────────────────────────────────────────────\n\nconst nextActionSchema = z.object({\n tool: z.string(),\n description: z.string(),\n parameters: z.record(z.unknown()),\n});\n\nconst metaSchema = z\n .object({\n durationMs: z.number().optional(),\n timing: z\n .object({\n classifyMs: z.number().optional(),\n createMs: z.number().optional(),\n autoLinkMs: z.number().optional(),\n userLinksMs: z.number().optional(),\n qualityMs: z.number().optional(),\n totalMs: z.number(),\n perEntryAvgMs: z.number().optional(),\n })\n .passthrough()\n .optional(),\n })\n .optional();\n\n/**\n * Wraps any data schema into a discriminated-union envelope schema.\n * Use for contract tests: `envelopeSchema(captureOutputSchema).safeParse(result)`.\n */\nexport function envelopeSchema<T extends ZodTypeAny>(dataSchema: T) {\n return z.discriminatedUnion(\"ok\", [\n z.object({\n ok: z.literal(true),\n summary: z.string().min(1),\n data: dataSchema,\n next: z.array(nextActionSchema).optional(),\n /** WP-316 S1a: capture contract for write tools — optional for backward compat. */\n contract: z.object({\n requiredFields: z.array(z.string()),\n allFields: z.array(z.object({\n key: z.string(),\n required: z.boolean(),\n type: z.string(),\n helpText: z.string().optional(),\n })),\n captureExpectation: z.string().optional(),\n }).optional(),\n _meta: metaSchema,\n }),\n z.object({\n ok: z.literal(false),\n code: z.string().min(1),\n message: z.string().min(1),\n recovery: z.string().optional(),\n availableActions: z.array(nextActionSchema).optional(),\n diagnostics: z.record(z.unknown()).optional(),\n _meta: metaSchema,\n // DEC-798\n class: z.enum(['transient','permanent','auth','notfound','payload','rate_limited']).optional(),\n retryAdvised: z.boolean().optional(),\n }),\n ]);\n}\n\n// ─── withEnvelope HOF ───────────────────────────────────────────────────\n\n/**\n * Wraps a tool handler to guarantee an Envelope in structuredContent.\n *\n * - Catches thrown errors (gates, backend) and classifies them.\n * - If the handler already returns an envelope (ok field present), passes through.\n * - Adds _meta.durationMs to every response.\n * - Owns isError: sets true iff ok===false (RH1 mitigation — TEN-206).\n *\n * @deprecated Use `thinWrapper` for new and migrated tools. `withEnvelope` retains\n * the safety net that auto-wraps non-envelope responses; `thinWrapper` throws instead,\n * making incomplete migrations visible immediately.\n */\nexport function withEnvelope<Args>(\n handler: (args: Args) => Promise<ToolResult>,\n): (args: Args) => Promise<ToolResult> {\n return async (args: Args): Promise<ToolResult> => {\n const start = Date.now();\n try {\n const result = await handler(args);\n const durationMs = Date.now() - start;\n\n const sc = result.structuredContent as Envelope | undefined;\n if (sc && typeof sc === \"object\" && \"ok\" in sc) {\n sc._meta = { ...sc._meta, durationMs };\n return {\n content: result.content ?? [],\n structuredContent: sc,\n ...(sc.ok === false ? { isError: true } : {}),\n };\n }\n\n // Safety net: all tools should be migrated. If this executes, a handler\n // is returning without an envelope — log so it surfaces during development.\n console.warn(`[withEnvelope] Handler returned without envelope shape. Wrapping automatically. Content preview: \"${result.content?.[0]?.text?.slice(0, 60) ?? \"(empty)\"}\"`);\n return {\n content: result.content ?? [],\n structuredContent: {\n ...success(\n result.content?.[0]?.text?.slice(0, 100) ?? \"\",\n sc ?? {},\n ),\n _meta: { durationMs },\n },\n };\n } catch (err) {\n const durationMs = Date.now() - start;\n const classified = classifyError(err);\n const envelope: EnvelopeError = {\n ...failure(\n classified.code,\n classified.message,\n classified.recovery,\n classified.availableActions,\n // WP-316 S1a: pass structured diagnostics (e.g. missingRequiredFields, fieldErrors)\n classified.diagnostics as Record<string, unknown> | undefined,\n ),\n _meta: { durationMs },\n };\n return {\n content: [{\n type: \"text\" as const,\n text: classified.fn\n ? `[${classified.code}/${classified.fn}] ${classified.message}`\n : `[${classified.code}] ${classified.message}`\n }],\n structuredContent: envelope,\n isError: true,\n };\n }\n };\n}\n\n// ─── thinWrapper HOF ────────────────────────────────────────────────────\n\n/**\n * Strict variant of `withEnvelope` for fully-migrated tools (WP-321 E3).\n *\n * Identical to `withEnvelope` EXCEPT the safety net is replaced with a hard\n * throw. If a handler returns without an envelope shape, this surfaces\n * immediately as an error rather than silently wrapping the response.\n *\n * Use this for all new tools and all tools that have been migrated to return\n * envelope-shaped responses directly.\n */\nexport function thinWrapper<Args>(\n handler: (args: Args) => Promise<ToolResult>,\n): (args: Args) => Promise<ToolResult> {\n return async (args: Args): Promise<ToolResult> => {\n const start = Date.now();\n try {\n const result = await handler(args);\n const durationMs = Date.now() - start;\n\n const sc = result.structuredContent as Envelope | undefined;\n if (sc && typeof sc === \"object\" && \"ok\" in sc) {\n sc._meta = { ...sc._meta, durationMs };\n return {\n content: result.content ?? [],\n structuredContent: sc,\n ...(sc.ok === false ? { isError: true } : {}),\n };\n }\n\n throw new Error(`[thinWrapper] Handler '${handler.name || \"<anonymous>\"}' returned without envelope shape — migration incomplete.`);\n } catch (err) {\n const durationMs = Date.now() - start;\n const classified = classifyError(err);\n const envelope: EnvelopeError = {\n ...failure(\n classified.code,\n classified.message,\n classified.recovery,\n classified.availableActions,\n // WP-316 S1a: pass structured diagnostics (e.g. missingRequiredFields, fieldErrors)\n classified.diagnostics as Record<string, unknown> | undefined,\n ),\n _meta: { durationMs },\n };\n return {\n content: [{\n type: \"text\" as const,\n text: classified.fn\n ? `[${classified.code}/${classified.fn}] ${classified.message}`\n : `[${classified.code}] ${classified.message}`\n }],\n structuredContent: envelope,\n isError: true,\n };\n }\n };\n}\n","/**\n * Structured error classification for the Response Envelope (BET-78, FEAT-121).\n *\n * Typed error classes + classifyError pattern-matching.\n * classifyError handles both typed classes (new code) and plain Error\n * messages from client.ts gates (existing code — no modifications needed).\n *\n * BET-191 (FEAT-573): KernelCallError carries a .code from the Convex HTTP gateway\n * (classifyMcpGatewayError). VALIDATION_FAILED errors must surface the clean\n * validation message — not the HTTP wrapper prefix — so agents receive actionable\n * \"Field X must be one of: ...\" text without noise.\n *\n * WP-321 E3a: Output codes emitted by classifyError are registered as the unified\n * error code SSOT in convex/lib/errors.ts::ErrorCodes. The MCP server cannot\n * import from convex/ (monorepo boundary: ARCH-55, BR-154), so the string values\n * are maintained as inline constants here — but they MUST match the corresponding\n * entries in ErrorCodes exactly. Verified output codes:\n * SESSION_REQUIRED, SESSION_CLOSED, ORIENTATION_REQUIRED, READONLY_SCOPE,\n * BACKEND_UNAVAILABLE, BACKEND_ERROR, INTERNAL_ERROR, DUPLICATE,\n * PERMISSION_DENIED, VALIDATION_ERROR, NOT_FOUND\n * The canonical registry lives in convex/lib/errors.ts — update there first\n * if a code name ever needs to change, then update the strings here to match.\n */\n\nimport type { NextAction } from \"./envelope.js\";\n\n// ─── KernelCallError duck-type helpers ──────────────────────────────────────────\n// KernelCallError is defined in client.ts and carries the structured code from the\n// Convex HTTP gateway. We use duck typing to avoid a circular import.\n\n/**\n * Matches `MCP call \"fn\" failed (STATUS): <clean message>` — the KernelCallError\n * message format from client.ts. Group 1 = fn scope, group 2 = clean backend message.\n */\n// DEC-798: group 1 = fn scope, group 2 = clean message\nconst MCP_CALL_ERROR_RE = /^MCP call \"([^\"]+)\" failed \\(\\d+\\): (.+)$/s;\n\n/**\n * If err is a KernelCallError (duck typed via .code and MCP_CALL_ERROR_RE message),\n * extract the structured code, fn scope, clean message, and WP-316 S1a diagnostics.\n * Returns undefined if not a match.\n */\nfunction asKernelCallError(\n err: unknown,\n): {\n code: string;\n fn: string;\n cleanMessage: string;\n missingRequiredFields?: string[];\n fieldErrors?: string[];\n} | undefined {\n if (\n err instanceof Error &&\n typeof (err as { code?: unknown }).code === \"string\"\n ) {\n const code = (err as { code: string }).code;\n const match = MCP_CALL_ERROR_RE.exec(err.message);\n if (match) {\n const e = err as { code: string; missingRequiredFields?: string[]; fieldErrors?: string[] };\n return {\n code,\n fn: match[1],\n cleanMessage: match[2], // NOTE: match[2] not match[1] — group 1 is now fn scope (DEC-798)\n missingRequiredFields: Array.isArray(e.missingRequiredFields) ? e.missingRequiredFields : undefined,\n fieldErrors: Array.isArray(e.fieldErrors) ? e.fieldErrors : undefined,\n };\n }\n }\n return undefined;\n}\n\n// ─── Typed Error Classes ─────────────────────────────────────────────────\n\nexport class GateError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"GateError\";\n }\n}\n\nexport class BackendError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"BackendError\";\n }\n}\n\nexport class ValidationError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"ValidationError\";\n }\n}\n\n// ─── Classification Result ───────────────────────────────────────────────\n\nexport interface ClassifiedError {\n code: string;\n message: string;\n fn?: string; // DEC-798: Convex function scope from KernelCallError\n recovery?: string;\n availableActions?: NextAction[];\n /** WP-316 S1a: Structured commit validation diagnostics when code=VALIDATION_ERROR. */\n diagnostics?: {\n missingRequiredFields?: string[];\n fieldErrors?: string[];\n };\n}\n\n// ─── Gate Patterns (from client.ts requireWriteAccess / requireActiveSession) ─\n\ninterface GatePattern {\n pattern: RegExp;\n code: string;\n recovery: string;\n action: NextAction;\n}\n\nconst GATE_PATTERNS: GatePattern[] = [\n {\n pattern: /session required|no active.*session|call.*session.*start/i,\n code: \"SESSION_REQUIRED\",\n recovery: \"Start an agent session first.\",\n action: { tool: \"session\", description: \"Start session\", parameters: { action: \"start\" } },\n },\n {\n pattern: /session.*closed/i,\n code: \"SESSION_CLOSED\",\n recovery: \"Start a new session.\",\n action: { tool: \"session\", description: \"Start new session\", parameters: { action: \"start\" } },\n },\n {\n pattern: /orientation required|call.*orient/i,\n code: \"ORIENTATION_REQUIRED\",\n recovery: \"Orient before writing.\",\n action: { tool: \"orient\", description: \"Orient session\", parameters: {} },\n },\n {\n pattern: /read.?only.*scope/i,\n code: \"READONLY_SCOPE\",\n recovery: \"This API key cannot write. Use a readwrite key.\",\n action: { tool: \"health\", description: \"Check key scope\", parameters: { action: \"whoami\" } },\n },\n];\n\n// ─── Classification ──────────────────────────────────────────────────────\n\n/**\n * Classify an error into a structured code + recovery path.\n * Handles:\n * 1. Gate errors (from requireWriteAccess / requireActiveSession)\n * 2. KernelCallError with structured Convex codes (VALIDATION_FAILED, NOT_FOUND, DUPLICATE)\n * 3. Backend errors (network/connectivity)\n * 4. Pattern-matched validation / not-found / duplicate messages\n * 5. Fallback to INTERNAL_ERROR\n */\nexport function classifyError(err: unknown): ClassifiedError {\n const message = err instanceof Error ? err.message : String(err);\n\n if (err instanceof GateError) {\n return {\n code: \"PERMISSION_DENIED\",\n message,\n recovery: \"Check permissions or use a readwrite API key.\",\n availableActions: [{ tool: \"health\", description: \"Check key scope\", parameters: { action: \"whoami\" } }],\n };\n }\n\n if (err instanceof BackendError) {\n return { code: \"BACKEND_ERROR\", message, recovery: \"Retry the operation or check backend health.\" };\n }\n\n if (err instanceof ValidationError) {\n return { code: \"VALIDATION_ERROR\", message };\n }\n\n // BET-191 (FEAT-573): KernelCallError carries the structured Convex error code from\n // classifyMcpGatewayError. Use it for clean classification before falling through\n // to regex matching, so agents receive the clean backend message without the\n // \"MCP call ... failed (400):\" HTTP wrapper prefix.\n const mcpErr = asKernelCallError(err);\n if (mcpErr) {\n const { code: convexCode, fn, cleanMessage, missingRequiredFields, fieldErrors } = mcpErr;\n if (convexCode === \"VALIDATION_FAILED\") {\n const hasDiagnostics = missingRequiredFields?.length || fieldErrors?.length;\n return {\n code: \"VALIDATION_ERROR\",\n fn,\n message: cleanMessage,\n ...(hasDiagnostics ? {\n diagnostics: {\n ...(missingRequiredFields?.length ? { missingRequiredFields } : {}),\n ...(fieldErrors?.length ? { fieldErrors } : {}),\n },\n } : {}),\n };\n }\n if (convexCode === \"NOT_FOUND\") {\n return {\n code: \"NOT_FOUND\",\n fn,\n message: cleanMessage,\n recovery: \"Use entries action=search to find the correct ID.\",\n availableActions: [{ tool: \"entries\", description: \"Search entries\", parameters: { action: \"search\" } }],\n };\n }\n if (convexCode === \"WORKSPACE_SLUG_TAKEN\" || convexCode === \"PERSON_ALREADY_EXISTS\") {\n return {\n code: \"DUPLICATE\",\n fn,\n message: cleanMessage,\n recovery: \"Use entries action=get to inspect the existing entry.\",\n availableActions: [{ tool: \"entries\", description: \"Get entry\", parameters: { action: \"get\" } }],\n };\n }\n // Fallthrough for any other convexCode: preserve fn for the prefix format\n return { code: convexCode, fn, message: cleanMessage };\n }\n\n for (const { pattern, code, recovery, action } of GATE_PATTERNS) {\n if (pattern.test(message)) {\n return { code, message, recovery, availableActions: [action] };\n }\n }\n\n if (/network error|fetch failed|ECONNREFUSED|ETIMEDOUT/i.test(message)) {\n return { code: \"BACKEND_UNAVAILABLE\", message, recovery: \"Retry in a few seconds.\" };\n }\n\n return { code: \"INTERNAL_ERROR\", message: message || \"An unexpected error occurred.\" };\n}\n","/**\n * Synced from convex/lib/fieldTypes.ts (BET-106: closed field type system, BR-108: MCP import boundary).\n */\n\n/**\n * Closed field type system — single source of truth for collection field types.\n * BET-106: Makes the collection contract self-enforcing.\n *\n * Adding a new field type requires updating:\n * 1. VALID_FIELD_TYPES + FIELD_TYPE_DEFAULTS + isValidValueForType (this file)\n * 2. validateEntryData switch in convex/lib/guards.ts\n * 3. fieldDefValidator in convex/agentKnowledge/_helpers.ts\n * 4. Run: node scripts/sync-convex-lib-to-mcp.mjs\n * 5. packages/mcp-server/src/lib/fieldTypes.ts (mirror — must stay in sync)\n */\n\nexport const VALID_FIELD_TYPES = [\n\t'string',\n\t'text',\n\t'rich-text',\n\t'number',\n\t'boolean',\n\t'select',\n\t'multi-select',\n\t'array',\n\t'json',\n\t'date',\n\t/** Convex Id<'people'> as string — BR-130 */\n\t'person',\n] as const;\n\nexport type FieldType = (typeof VALID_FIELD_TYPES)[number];\n\n/** Type-aware defaults for smart-capture and entry creation. */\nexport const FIELD_TYPE_DEFAULTS: Record<FieldType, unknown> = {\n\t'string': '',\n\t'text': '',\n\t'rich-text': '',\n\t'number': null,\n\t'boolean': false,\n\t'select': null,\n\t'multi-select': [],\n\t'array': [],\n\t'json': null,\n\t'date': null,\n\t'person': null,\n};\n\nexport function isValidFieldType(type: string): type is FieldType {\n\treturn (VALID_FIELD_TYPES as readonly string[]).includes(type);\n}\n\nexport function isValidValueForType(value: unknown, type: FieldType): boolean {\n\tswitch (type) {\n\t\tcase 'string':\n\t\tcase 'text':\n\t\tcase 'rich-text':\n\t\t\treturn typeof value === 'string';\n\t\tcase 'number':\n\t\t\treturn value === null || typeof value === 'number';\n\t\tcase 'boolean':\n\t\t\treturn typeof value === 'boolean';\n\t\tcase 'select':\n\t\t\treturn value === null || typeof value === 'string';\n\t\tcase 'multi-select':\n\t\tcase 'array':\n\t\t\treturn Array.isArray(value);\n\t\tcase 'json':\n\t\t\treturn true;\n\t\tcase 'date':\n\t\t\treturn value === null || (typeof value === 'string' && /^\\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\\d|3[01])$/.test(value));\n\t\tcase 'person':\n\t\t\treturn value === null || typeof value === 'string';\n\t}\n}\n","/**\n * BET-289 S2: Format field-level writing guidance into a prompt section.\n * Replicated from convex/lib/formatFieldGuidance.ts due to monorepo import boundary (BR-170).\n * Must produce identical output to the convex/ version.\n *\n * Pure function (STD-148). No side effects, no imports beyond types.\n */\n\nexport interface FieldWithGuidance {\n\tkey: string;\n\tlabel?: string;\n\twritingGuidance?: string;\n\twritingExamples?: string[];\n}\n\n/**\n * Format field-level writing guidance into a prompt-injectable section.\n *\n * @param fields - Array of field definitions, potentially with writingGuidance/writingExamples.\n * @returns Formatted string for prompt injection, or empty string if no fields have guidance.\n */\nexport function formatFieldGuidance(fields: FieldWithGuidance[]): string {\n\tconst guidedFields = fields.filter((f) => f.writingGuidance);\n\tif (guidedFields.length === 0) return '';\n\n\tconst lines: string[] = ['## Writing Guidance'];\n\tfor (const field of guidedFields) {\n\t\tconst displayName = field.label || field.key;\n\t\tlines.push(`- ${displayName}: ${field.writingGuidance}`);\n\t\tif (field.writingExamples && field.writingExamples.length > 0) {\n\t\t\tlines.push(` Examples: ${field.writingExamples.join(' | ')}`);\n\t\t}\n\t}\n\n\treturn lines.join('\\n');\n}\n","/**\n * Synced from convex/lib/inferSourceDate.ts (FEAT-885: shared date inference, BR-108: MCP import boundary).\n */\n\n/**\n * Infer an ISO date (YYYY-MM-DD) from free-text values.\n *\n * Canonical source for MCP (packages/mcp-server/src/lib/inferSourceDate.ts)\n * and CLI (packages/cli/src/lib/inferSourceDate.ts) — both are synced copies\n * maintained by scripts/sync-convex-lib-to-mcp.mjs (FEAT-885, BR-108).\n */\n\nexport function inferSourceDate(...values: Array<string | undefined>): string | undefined {\n\tconst combined = values\n\t\t.filter((value): value is string => typeof value === 'string' && value.trim().length > 0)\n\t\t.join('\\n');\n\n\tif (!combined) return undefined;\n\n\tconst isoMatch = combined.match(/\\b(20\\d{2}-\\d{2}-\\d{2})\\b/);\n\tif (isoMatch) return isoMatch[1];\n\n\tconst monthMatch = combined.match(\n\t\t/\\b(january|february|march|april|may|june|july|august|september|october|november|december)\\s+(\\d{1,2})(?:st|nd|rd|th)?(?:,?\\s+(20\\d{2}))?\\b/i,\n\t);\n\tif (!monthMatch) return undefined;\n\n\tconst monthIndex = [\n\t\t'january',\n\t\t'february',\n\t\t'march',\n\t\t'april',\n\t\t'may',\n\t\t'june',\n\t\t'july',\n\t\t'august',\n\t\t'september',\n\t\t'october',\n\t\t'november',\n\t\t'december',\n\t].indexOf(monthMatch[1].toLowerCase());\n\tif (monthIndex < 0) return undefined;\n\n\tconst inferredYear = monthMatch[3] ?? combined.match(/\\b(20\\d{2})\\b/)?.[1] ?? String(new Date().getUTCFullYear());\n\tconst month = String(monthIndex + 1).padStart(2, '0');\n\tconst day = monthMatch[2].padStart(2, '0');\n\treturn `${inferredYear}-${month}-${day}`;\n}\n","/**\n * Per-invocation collection metadata cache — BET-281 Slice 2.\n *\n * Wraps chain.listCollections() with lazy caching: first call within an MCP tool\n * invocation hits Convex; subsequent calls return cached data. The cache is\n * per-import-scope (module singleton) and must be invalidated between logical\n * invocations via `resetCollectionCache()`.\n *\n * Lifecycle: In stdio mode (one tool call per process), cache naturally resets.\n * In HTTP/SSE mode (long-running), callers must call resetCollectionCache() at\n * the start of each tool invocation to prevent stale data. This is a known\n * limitation — wire into tool lifecycle middleware when HTTP mode is primary.\n *\n * Helpers derive runtime behavior from DB fields (classificationCheck, governed,\n * navGroup, thinkingLayer, governanceRole, etc.) so consumers never hardcode\n * collection slugs.\n *\n * Chain: BET-281 (eliminate hardcoded collection constants), STD-101 (derive, don't declare)\n */\n\nimport { kernelQuery } from \"../client.js\";\n\n// ── Types ──────────────────────────────────────────────────────────────────\n\nexport interface CollectionDoc {\n _id: string;\n slug: string;\n name: string;\n description?: string;\n purpose?: string;\n icon?: string;\n navGroup?: \"daily\" | \"strategic\" | \"governance\" | \"reference\" | \"collections\";\n fields: Array<{\n key: string;\n label: string;\n type: string;\n required?: boolean;\n options?: string[];\n relatesTo?: string;\n searchable?: boolean;\n displayHint?: string;\n zone?: string;\n colorMap?: unknown;\n accentSource?: boolean;\n iconMap?: Record<string, string>;\n helpText?: string;\n /** BET-289: Natural language instruction for how to write this field value. */\n writingGuidance?: string;\n /** BET-289: Example strings showing good/bad field values. */\n writingExamples?: string[];\n optionDescriptions?: unknown;\n semanticRole?: string;\n maxLength?: number;\n minLength?: number;\n requiredContext?: string;\n }>;\n stratum: \"system\" | \"domain\" | \"working\";\n defaultCanonicalKey?: string;\n defaultWorkflowStatus?: string;\n governed?: boolean;\n idPrefix?: string;\n validWorkflowStatuses?: string[];\n classificationCheck?: string;\n classificationPriority?: number;\n qualityCriteria?: Array<{\n field: string;\n rule: \"required\" | \"min_length\" | \"pattern\";\n value?: string;\n }>;\n thinkingLayer?: string;\n timelineRole?: string;\n color?: string;\n governanceRole?: string;\n layoutTemplate?: string;\n usageGuidance?: string;\n examples?: Array<{ name: string; description: string }>;\n crossReferences?: Array<{ slug: string; relationship: string; guidance: string }>;\n}\n\n// ── Cache State ────────────────────────────────────────────────────────────\n\nlet cachedCollections: CollectionDoc[] | null = null;\nlet cachedBySlug: Map<string, CollectionDoc> | null = null;\n\n// ── Core ───────────────────────────────────────────────────────────────────\n\n/**\n * Get all workspace collections, cached per-invocation.\n * First call fetches from Convex; subsequent calls return cached data.\n */\nexport async function getCollections(): Promise<CollectionDoc[]> {\n if (cachedCollections !== null) return cachedCollections;\n const result = await kernelQuery<CollectionDoc[]>(\"chain.listCollections\");\n cachedCollections = result ?? [];\n cachedBySlug = new Map(cachedCollections.map((c) => [c.slug, c]));\n return cachedCollections;\n}\n\n/**\n * Get collection by slug from cache.\n */\nexport async function getCollectionBySlug(slug: string): Promise<CollectionDoc | undefined> {\n await getCollections();\n return cachedBySlug!.get(slug);\n}\n\n/**\n * Reset the cache. Call at the start of each MCP tool invocation\n * to ensure fresh data (or let it lazily refresh on next access).\n */\nexport function resetCollectionCache(): void {\n cachedCollections = null;\n cachedBySlug = null;\n}\n\n// ── Derived Queries ────────────────────────────────────────────────────────\n\n/**\n * Check if a collection supports classification (has non-empty classificationCheck).\n * Runtime equivalent of the old CLASSIFIABLE_COLLECTIONS constant.\n */\nexport async function isClassifiable(slug: string): Promise<boolean> {\n const col = await getCollectionBySlug(slug);\n return !!col?.classificationCheck;\n}\n\n/**\n * Get all classifiable collection slugs.\n */\nexport async function getClassifiableSlugs(): Promise<string[]> {\n const cols = await getCollections();\n return cols\n .filter((c) => !!c.classificationCheck)\n .map((c) => c.slug);\n}\n\n/**\n * Check if a collection uses governed draft workflow.\n * Runtime replacement for the GOVERNED_COLLECTIONS set.\n */\nexport async function isGoverned(slug: string): Promise<boolean> {\n const col = await getCollectionBySlug(slug);\n return !!col?.governed;\n}\n\n/**\n * Get collections by navGroup (e.g. 'governance', 'strategic', 'daily').\n */\nexport async function getByNavGroup(navGroup: string): Promise<CollectionDoc[]> {\n const cols = await getCollections();\n return cols.filter((c) => c.navGroup === navGroup);\n}\n\n/**\n * Get collections by thinkingLayer.\n */\nexport async function getByThinkingLayer(layer: string): Promise<CollectionDoc[]> {\n const cols = await getCollections();\n return cols.filter((c) => c.thinkingLayer === layer);\n}\n\n/**\n * Check if a collection is a \"hub\" collection — strategic collections that\n * get higher link confidence scores. Original HUB_COLLECTIONS was strategy + features.\n * Primary: governanceRole === 'steering' (captures both strategy + features).\n * Fallback: thinkingLayer === 'strategy' for workspaces not yet backfilled.\n */\nexport async function isHubCollection(slug: string): Promise<boolean> {\n const col = await getCollectionBySlug(slug);\n if (!col) return false;\n return col.governanceRole === \"steering\" || col.thinkingLayer === \"strategy\";\n}\n\n/**\n * Get the description field key for a collection.\n * Most collections use \"description\"; some use \"rationale\", \"belief\", \"canonical\", etc.\n * Falls back to \"description\" if not specified in the collection's field metadata.\n */\nexport async function getDescriptionFieldKey(slug: string): Promise<string> {\n const col = await getCollectionBySlug(slug);\n if (!col) return \"description\";\n\n // Check for fields with specific semantic roles or known description-like keys\n const descriptionLikeKeys = [\"description\", \"rationale\", \"belief\", \"canonical\"];\n for (const key of descriptionLikeKeys) {\n const field = col.fields.find((f) => f.key === key);\n if (field && (field.displayHint === \"hero\" || field.displayHint === \"textarea\" || field.zone === \"body\")) {\n return key;\n }\n }\n\n // Fallback: check for first field in body zone with textarea hint\n const bodyTextField = col.fields.find(\n (f) => f.zone === \"body\" || f.displayHint === \"textarea\",\n );\n if (bodyTextField) return bodyTextField.key;\n\n return \"description\";\n}\n\n/**\n * Check if collection's navGroup is 'governance' — used for binding governance\n * collections (principles, standards, business-rules).\n */\nexport async function isGovernanceNavGroup(slug: string): Promise<boolean> {\n const col = await getCollectionBySlug(slug);\n return col?.navGroup === \"governance\";\n}\n\n/**\n * Check if a collection belongs to the work planning domain\n * (thinkingLayer is delivery-container, delivery-grouping, or delivery-work).\n * Runtime replacement for checking slug === \"chains\" || slug === \"work-packages\".\n */\nexport async function isWorkPlanningCollection(slug: string): Promise<boolean> {\n const col = await getCollectionBySlug(slug);\n const layer = col?.thinkingLayer;\n return layer === \"delivery-container\" || layer === \"delivery-grouping\" || layer === \"delivery-work\";\n}\n\n/**\n * Check if a collection has a specific defaultCanonicalKey.\n */\nexport async function hasCanonicalKey(slug: string, key: string): Promise<boolean> {\n const col = await getCollectionBySlug(slug);\n return col?.defaultCanonicalKey === key;\n}\n","import { kernelQuery } from \"../client.js\";\nimport { runContradictionCheck, type ContradictionWarning } from \"./smart-capture.js\";\n\nexport interface SemanticConflictResult {\n chainEntryId: string;\n chainEntryName: string;\n chainEntryDescription: string;\n type: \"contradiction\" | \"supersession\" | \"duplicate\" | \"overlap\";\n confidence: number;\n explanation: string;\n}\n\nexport interface ConflictPreflightResult {\n source: \"semantic\" | \"heuristic\";\n conflicts: SemanticConflictResult[];\n blockingContradictions: SemanticConflictResult[];\n advisoryWarnings: ContradictionWarning[];\n}\n\nconst BLOCKING_CONTRADICTION_THRESHOLD = 0.75;\n\nfunction isBlockingContradiction(conflict: SemanticConflictResult): boolean {\n return conflict.type === \"contradiction\" && conflict.confidence >= BLOCKING_CONTRADICTION_THRESHOLD;\n}\n\n/**\n * Run the staging-grade semantic conflict detector when available.\n * Falls back to the existing heuristic warning path if the bridge is unavailable.\n */\nexport async function runConflictPreflight(\n name: string,\n description: string,\n collectionHint?: string,\n): Promise<ConflictPreflightResult> {\n try {\n const conflicts = await kernelQuery<SemanticConflictResult[]>(\"chain.detectSemanticConflicts\", {\n name,\n description,\n ...(collectionHint ? { collectionHint } : {}),\n });\n\n return {\n source: \"semantic\",\n conflicts,\n blockingContradictions: conflicts.filter(isBlockingContradiction),\n advisoryWarnings: [],\n };\n } catch (err) {\n console.error('[conflict-preflight] Semantic conflict detection unavailable, falling back to heuristic:', err instanceof Error ? err.message : String(err));\n const advisoryWarnings = await runContradictionCheck(name, description);\n return {\n source: \"heuristic\",\n conflicts: [],\n blockingContradictions: [],\n advisoryWarnings,\n };\n }\n}\n","/**\n * Entries compound tool — list, get, batch, search.\n * Consolidates list-entries, get-entry, batch-get, search into one tool.\n * BR-72: Compound Tool Standard.\n */\n\nimport { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { z } from \"zod\";\nimport { kernelQuery, kernelMutation, runWithToolContext, getWorkspaceId } from \"../client.js\";\nimport { success, failure, thinWrapper, parseOrFail, unknownAction, validationResult, notFoundResult, failureResult } from \"../envelope.js\";\nimport { extractPreview, deriveEpistemicStatus, formatEpistemicLine, toEpistemicInput } from \"./knowledge-helpers.js\";\nimport { trackKnowledgeGap } from \"../analytics.js\";\nimport { recordGap } from \"../gap-store.js\";\n\nfunction sanitizeEntryData(data: unknown): Record<string, unknown> | undefined {\n if (!data || typeof data !== \"object\") return undefined;\n const filtered = Object.fromEntries(\n Object.entries(data as Record<string, unknown>).filter(([key]) => !key.startsWith(\"_\")),\n );\n return Object.keys(filtered).length > 0 ? filtered : undefined;\n}\n\nconst ENTRIES_ACTIONS = [\"list\", \"get\", \"batch\", \"search\"] as const;\ntype EntriesAction = (typeof ENTRIES_ACTIONS)[number];\n\nexport const entriesSchema = z.object({\n action: z.enum(ENTRIES_ACTIONS).describe(\n \"'list': browse entries with filters. 'get': fetch one entry by ID. 'batch': fetch multiple entries. 'search': full-text search.\",\n ),\n entryId: z.string().optional().describe(\"Entry ID for get action, e.g. 'DEC-42', 'BR-001'\"),\n entryIds: z.array(z.string()).min(1).max(20).optional()\n .describe(\"Entry IDs for batch action, e.g. ['TYPE-strategy', 'STR-jljeg7']\"),\n collection: z.string().optional()\n .describe(\"Collection slug for list/search, e.g. 'glossary', 'tracking-events', 'business-rules'\"),\n status: z.string().optional()\n .describe(\"Filter: draft | active | deprecated | archived\"),\n tag: z.string().optional().describe(\"Filter by internal tag for list\"),\n label: z.string().optional().describe(\"Filter by label slug for list — matches entries across all collections\"),\n query: z.string().optional().describe(\"Search text for search action (min 2 characters)\"),\n});\n\nexport const moveEntrySchema = z.object({\n entryId: z.string().describe(\"Entry ID to move, e.g. 'DEC-42', 'BR-001'\"),\n toCollection: z.string().describe(\"Target collection slug, e.g. 'decisions', 'architecture'\"),\n});\n\nexport const entriesGetOutputSchema = z.object({\n entryId: z.string(),\n name: z.string(),\n collection: z.string(),\n status: z.string(),\n capturedAt: z.number().optional(),\n origin: z.string().optional(),\n originDetail: z.string().optional(),\n verificationStatus: z.string().optional(),\n sourceRef: z.string().optional(),\n sourceExcerpt: z.string().optional(),\n data: z.record(z.unknown()).optional(),\n relations: z.array(z.object({\n entryId: z.string().optional(),\n name: z.string(),\n type: z.string(),\n direction: z.string(),\n })).optional(),\n labels: z.array(z.string()).optional(),\n});\n\nexport const entriesListOutputSchema = z.object({\n entries: z.array(z.object({\n entryId: z.string(),\n name: z.string(),\n collection: z.string(),\n status: z.string(),\n })),\n total: z.number(),\n});\n\nexport const entriesSearchOutputSchema = z.object({\n results: z.array(z.object({\n entryId: z.string(),\n name: z.string(),\n collection: z.string(),\n status: z.string(),\n score: z.number().optional(),\n })),\n total: z.number(),\n query: z.string(),\n});\n\nexport const entriesBatchOutputSchema = z.object({\n entries: z.array(z.object({\n entryId: z.string(),\n name: z.string(),\n collection: z.string(),\n status: z.string(),\n capturedAt: z.number().optional(),\n origin: z.string().optional(),\n originDetail: z.string().optional(),\n verificationStatus: z.string().optional(),\n sourceRef: z.string().optional(),\n sourceExcerpt: z.string().optional(),\n data: z.record(z.unknown()).optional(),\n })),\n total: z.number(),\n});\n\nexport function registerEntriesTools(server: McpServer): void {\n server.registerTool(\n \"entries\",\n {\n title: \"Entries\",\n description:\n \"Read entries from the Chain. One tool for all entry reading.\\n\\n\" +\n \"- **list**: Browse entries with optional filters (collection, status, tag, label). Use collections action=list first to discover slugs.\\n\" +\n \"- **get**: Fetch a single entry by ID — full record with data, labels, relations, history.\\n\" +\n \"- **batch**: Fetch multiple entries (max 20) in one call. Same shape as get per entry.\\n\" +\n \"- **search**: Full-text search across entries. Scope by collection or filter by status.\\n\\n\" +\n \"Use `entries action=get entryId=\\\"...\\\"` to fetch one. Use `entries action=search query=\\\"...\\\"` to discover. To reclassify, use `move-entry`.\",\n inputSchema: entriesSchema,\n annotations: { readOnlyHint: true, idempotentHint: true, openWorldHint: false },\n },\n thinWrapper(async (args) => {\n const parsed = parseOrFail(entriesSchema, args);\n if (!parsed.ok) return parsed.result;\n const { action, entryId, entryIds, collection, status, tag, label, query } = parsed.data;\n\n return runWithToolContext({ tool: \"entries\", action }, async () => {\n if (action === \"get\") {\n if (!entryId) {\n return validationResult(\"entryId is required when action is 'get'.\");\n }\n return handleGet(entryId);\n }\n\n if (action === \"batch\") {\n if (!entryIds || entryIds.length === 0) {\n return validationResult(\"entryIds is required when action is 'batch'.\");\n }\n return handleBatch(entryIds);\n }\n\n if (action === \"search\") {\n if (!query || query.length < 2) {\n return validationResult(\"query is required for search (min 2 characters).\");\n }\n return handleSearch(server, query, collection, status);\n }\n\n if (action === \"list\") {\n return handleList(collection, status, tag, label);\n }\n\n return unknownAction(action, ENTRIES_ACTIONS);\n });\n }),\n );\n\n server.registerTool(\n \"move-entry\",\n {\n title: \"Move Entry\",\n description:\n \"Move an entry to a different collection. Use when the classifier misrouted or the user wants to reclassify.\\n\\n\" +\n \"Example: `move-entry entryId=\\\"DEC-42\\\" toCollection=\\\"tensions\\\"` reclassifies DEC-42 into the tensions collection.\",\n inputSchema: moveEntrySchema,\n annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false },\n },\n thinWrapper(async (args) => {\n const parsed = parseOrFail(moveEntrySchema, args);\n if (!parsed.ok) return parsed.result;\n return runWithToolContext({ tool: \"move-entry\", action: \"move\" }, () =>\n handleMove(parsed.data.entryId, parsed.data.toCollection),\n );\n }),\n );\n}\n\nasync function handleGet(entryId: string) {\n const entry = await kernelQuery<unknown>(\"chain.getEntry\", { entryId });\n\n if (!entry) {\n return notFoundResult(entryId, `Entry '${entryId}' not found. Try search to find the right ID.`);\n }\n\n const e = entry as Record<string, unknown>;\n const epistemic = deriveEpistemicStatus(toEpistemicInput(e));\n\n const lines: string[] = [\n `## Get Result`,\n \"\",\n `# ${e.entryId ? `${e.entryId}: ` : \"\"}${e.name}`,\n \"\",\n `**Status:** ${e.status}${e.workflowStatus ? ` / ${e.workflowStatus}` : \"\"}`,\n `**Type:** ${e.canonicalKey ?? \"untyped\"}`,\n ];\n\n // BET-240 S6: surface trust/provenance fields when present\n if (typeof e.capturedAt === \"number\") lines.push(`**Captured at:** ${new Date(e.capturedAt).toISOString()}`);\n if (e.origin) {\n const detail = e.originDetail ? ` (${e.originDetail})` : \"\";\n lines.push(`**Origin:** ${e.origin}${detail}`);\n }\n if (e.verificationStatus) lines.push(`**Verification:** ${e.verificationStatus}`);\n if (e.sourceRef) lines.push(`**Source ref:** ${e.sourceRef}`);\n if (e.sourceExcerpt) lines.push(`**Source excerpt:** ${e.sourceExcerpt}`);\n\n if (epistemic) {\n lines.push(formatEpistemicLine(epistemic));\n }\n\n const visibleData = sanitizeEntryData(e.data);\n if (visibleData) {\n lines.push(\"\");\n for (const [key, val] of Object.entries(visibleData)) {\n const display = typeof val === \"string\" ? val : JSON.stringify(val);\n lines.push(`**${key}:** ${display}`);\n }\n }\n\n if (Array.isArray(e.tags) && e.tags.length > 0) {\n lines.push(\"\", `**Tags:** ${(e.tags as string[]).join(\", \")}`);\n }\n\n if (Array.isArray(e.labels) && (e.labels as unknown[]).length > 0) {\n const labels = e.labels as { slug?: string; name?: string }[];\n lines.push(\"\", `**Labels:** ${labels.map((l) => `\\`${l.slug ?? l.name}\\``).join(\", \")}`);\n }\n\n if (Array.isArray(e.relations) && (e.relations as unknown[]).length > 0) {\n lines.push(\"\", \"## Relations\");\n for (const r of e.relations as { direction?: string; type?: string; otherEntryId?: string; otherName?: string }[]) {\n const arrow = r.direction === \"outgoing\" ? \"\\u2192\" : \"\\u2190\";\n const other = r.otherEntryId ? `${r.otherEntryId}: ${r.otherName}` : (r.otherName ?? \"unknown\");\n lines.push(`- ${arrow} **${r.type}** ${other}`);\n }\n }\n\n if (Array.isArray(e.history) && (e.history as unknown[]).length > 0) {\n lines.push(\"\", \"## History (last 10)\");\n for (const h of (e.history as { timestamp: string; event: string; changedBy?: string }[]).slice(-10)) {\n const date = new Date(h.timestamp).toISOString().split(\"T\")[0];\n lines.push(`- ${date}: ${h.event}${h.changedBy ? ` _(${h.changedBy})_` : \"\"}`);\n }\n }\n\n const entryData = {\n entryId: String(e.entryId ?? \"\"),\n name: String(e.name ?? \"\"),\n collection: String(e.canonicalKey ?? \"\"),\n status: String(e.status ?? \"\"),\n ...(typeof e.capturedAt === \"number\" ? { capturedAt: e.capturedAt } : {}),\n ...(e.workflowStatus ? { workflowStatus: String(e.workflowStatus) } : {}),\n ...(epistemic ? { epistemicStatus: epistemic } : {}),\n // BET-240 S6: trust/provenance fields\n ...(e.origin ? { origin: String(e.origin) } : {}),\n ...(e.originDetail ? { originDetail: String(e.originDetail) } : {}),\n ...(e.verificationStatus ? { verificationStatus: String(e.verificationStatus) } : {}),\n ...(e.sourceRef ? { sourceRef: String(e.sourceRef) } : {}),\n ...(e.sourceExcerpt ? { sourceExcerpt: String(e.sourceExcerpt) } : {}),\n entries: [{ entryId: e.entryId, name: e.name, status: e.status, ...(e.workflowStatus ? { workflowStatus: e.workflowStatus } : {}), collectionName: String((e as { collectionName?: string }).collectionName ?? e.canonicalKey ?? \"—\") }],\n ...(visibleData ? { data: visibleData } : {}),\n ...(Array.isArray(e.relations) && (e.relations as unknown[]).length > 0\n ? {\n relations: (e.relations as { direction?: string; type?: string; otherEntryId?: string; otherName?: string }[]).map((r) => ({\n ...(r.otherEntryId ? { entryId: r.otherEntryId } : {}),\n name: r.otherName ?? \"unknown\",\n type: r.type ?? \"unknown\",\n direction: r.direction ?? \"unknown\",\n })),\n }\n : {}),\n ...(Array.isArray(e.labels) && (e.labels as unknown[]).length > 0\n ? { labels: (e.labels as { slug?: string; name?: string }[]).map((l) => l.slug ?? l.name ?? \"\") }\n : {}),\n };\n\n return {\n content: [{ type: \"text\" as const, text: lines.join(\"\\n\") }],\n structuredContent: success(\n `Found ${entryId}: ${String(e.name)} [${String(e.canonicalKey ?? \"\")}].`,\n entryData,\n [\n { tool: \"graph\", description: \"Explore connections\", parameters: { action: \"suggest\", entryId } },\n { tool: \"context\", description: \"Gather related context\", parameters: { action: \"gather\", entryId } },\n ],\n ),\n };\n}\n\nasync function handleBatch(entryIds: string[]) {\n const results = await kernelQuery<Array<{ entry?: unknown; error?: string }>>(\"chain.batchGetEntries\", { entryIds });\n\n const lines: string[] = [`## Batch Result`, \"\", `# Batch Get (${results.length} requested)`, \"\"];\n\n for (let i = 0; i < results.length; i++) {\n const r = results[i];\n const requestedId = entryIds[i];\n if (r.error) {\n lines.push(`## ${requestedId}\\n\\n**Error:** ${r.error}\\n`);\n continue;\n }\n const entry = r.entry as Record<string, unknown>;\n lines.push(`## ${entry.entryId ? `${entry.entryId}: ` : \"\"}${entry.name}`);\n lines.push(\"\");\n lines.push(`**Status:** ${entry.status}${entry.workflowStatus ? ` / ${entry.workflowStatus}` : \"\"}`);\n lines.push(`**Type:** ${entry.canonicalKey ?? \"untyped\"}`);\n if (typeof entry.capturedAt === \"number\") {\n lines.push(`**Captured at:** ${new Date(entry.capturedAt).toISOString()}`);\n }\n if (entry.origin) {\n const detail = entry.originDetail ? ` (${entry.originDetail})` : \"\";\n lines.push(`**Origin:** ${entry.origin}${detail}`);\n }\n if (entry.verificationStatus) {\n lines.push(`**Verification:** ${entry.verificationStatus}`);\n }\n if (entry.sourceRef) {\n lines.push(`**Source ref:** ${entry.sourceRef}`);\n }\n if (entry.sourceExcerpt) {\n lines.push(`**Source excerpt:** ${entry.sourceExcerpt}`);\n }\n\n const visibleData = sanitizeEntryData(entry.data);\n if (visibleData) {\n lines.push(\"\");\n for (const [key, val] of Object.entries(visibleData)) {\n const display = typeof val === \"string\" ? val : JSON.stringify(val);\n lines.push(`**${key}:** ${display}`);\n }\n }\n\n if (Array.isArray(entry.tags) && entry.tags.length > 0) {\n lines.push(\"\", `**Tags:** ${(entry.tags as string[]).join(\", \")}`);\n }\n\n if (Array.isArray(entry.labels) && (entry.labels as unknown[]).length > 0) {\n const labels = entry.labels as { slug?: string; name?: string }[];\n lines.push(\"\", `**Labels:** ${labels.map((l) => `\\`${l.slug ?? l.name}\\``).join(\", \")}`);\n }\n\n if (Array.isArray(entry.relations) && (entry.relations as unknown[]).length > 0) {\n lines.push(\"\", \"**Relations:**\");\n for (const rel of entry.relations as { direction?: string; type?: string; otherEntryId?: string; otherName?: string }[]) {\n const dir = rel.direction === \"outgoing\" ? \"→\" : \"←\";\n const other = rel.otherEntryId ?? rel.otherName ?? \"?\";\n lines.push(`- ${dir} [${rel.type}] ${other}`);\n }\n }\n\n if (Array.isArray(entry.history) && (entry.history as unknown[]).length > 0) {\n lines.push(\"\", \"**History (last 5):**\");\n for (const h of (entry.history as { timestamp: string; event: string }[]).slice(-5)) {\n const date = new Date(h.timestamp).toISOString().split(\"T\")[0];\n lines.push(`- ${date}: ${h.event}`);\n }\n }\n\n lines.push(\"\");\n }\n\n const structuredEntries = results\n .filter((r) => !r.error && r.entry)\n .map((r) => {\n const entry = r.entry as Record<string, unknown>;\n return {\n entryId: String(entry.entryId ?? \"\"),\n name: String(entry.name ?? \"\"),\n collection: String(entry.canonicalKey ?? \"\"),\n status: String(entry.status ?? \"\"),\n ...(typeof entry.capturedAt === \"number\" ? { capturedAt: entry.capturedAt } : {}),\n ...(entry.origin ? { origin: String(entry.origin) } : {}),\n ...(entry.originDetail ? { originDetail: String(entry.originDetail) } : {}),\n ...(entry.verificationStatus ? { verificationStatus: String(entry.verificationStatus) } : {}),\n ...(entry.sourceRef ? { sourceRef: String(entry.sourceRef) } : {}),\n ...(entry.sourceExcerpt ? { sourceExcerpt: String(entry.sourceExcerpt) } : {}),\n ...(entry.workflowStatus ? { workflowStatus: String(entry.workflowStatus) } : {}),\n ...(sanitizeEntryData(entry.data) ? { data: sanitizeEntryData(entry.data) } : {}),\n };\n });\n\n const total = structuredEntries.length;\n return {\n content: [{ type: \"text\" as const, text: lines.join(\"\\n\") }],\n structuredContent: success(`Fetched ${total} entries in batch.`, { entries: structuredEntries, total }),\n };\n}\n\nasync function handleList(collection?: string, status?: string, tag?: string, label?: string) {\n let entries: unknown[];\n\n if (label) {\n entries = await kernelQuery<unknown[]>(\"chain.listEntriesByLabel\", { labelSlug: label });\n if (status) {\n entries = (entries as { status?: string }[]).filter((e) => e.status === status);\n }\n } else {\n entries = await kernelQuery<unknown[]>(\"chain.listEntries\", {\n collectionSlug: collection,\n status,\n tag,\n });\n }\n\n if (entries.length === 0) {\n return {\n content: [{ type: \"text\" as const, text: \"No entries match the given filters.\" }],\n structuredContent: success(\n \"No entries match the given filters.\",\n { entries: [], total: 0 },\n [{ tool: \"collections\", description: \"List collections\", parameters: { action: \"list\" } }],\n ),\n };\n }\n\n const formatted = (entries as { entryId?: string; name?: string; status?: string; workflowStatus?: string; data?: unknown }[])\n .map((e) => {\n const id = e.entryId ? `**${e.entryId}:** ` : \"\";\n const statusDisplay = e.workflowStatus ? `${e.status} / ${e.workflowStatus}` : e.status;\n const visibleData = sanitizeEntryData(e.data);\n const dataPreview = visibleData\n ? Object.entries(visibleData)\n .slice(0, 4)\n .map(([k, v]) => ` ${k}: ${typeof v === \"string\" ? v.substring(0, 120) : JSON.stringify(v)}`)\n .join(\"\\n\")\n : \"\";\n return `- ${id}${e.name} \\`${statusDisplay}\\`${dataPreview ? `\\n${dataPreview}` : \"\"}`;\n })\n .join(\"\\n\\n\");\n\n const scope = collection ? ` in \\`${collection}\\`` : \"\";\n\n const structuredEntries = (entries as { entryId?: string; name?: string; status?: string; workflowStatus?: string; canonicalKey?: string }[]).map((e) => ({\n entryId: String(e.entryId ?? \"\"),\n name: String(e.name ?? \"\"),\n collection: String(e.canonicalKey ?? collection ?? \"\"),\n status: String(e.status ?? \"\"),\n ...(e.workflowStatus ? { workflowStatus: e.workflowStatus } : {}),\n }));\n\n const total = structuredEntries.length;\n return {\n content: [{ type: \"text\" as const, text: `## List Result\\n\\n# Entries${scope} (${entries.length})\\n\\n${formatted}` }],\n structuredContent: success(`Found ${total} entries${scope}.`, { entries: structuredEntries, total }),\n };\n}\n\nasync function handleMove(entryId: string, toCollection: string) {\n try {\n const result = await kernelMutation<{\n entryId: string;\n fromCollection: string;\n toCollection: string;\n workflowStatusReset: boolean;\n previousWorkflowStatus?: string;\n }>(\"chain.moveToCollection\", { entryId, toCollectionSlug: toCollection });\n\n const lines = [\n `## Move Result`,\n \"\",\n `Moved **${result.entryId}** from \\`${result.fromCollection}\\` → \\`${result.toCollection}\\``,\n ];\n\n if (result.workflowStatusReset) {\n lines.push(``, `⚠️ Workflow status \\`${result.previousWorkflowStatus}\\` was reset (incompatible with target collection).`);\n }\n\n return {\n content: [{ type: \"text\" as const, text: lines.join(\"\\n\") }],\n structuredContent: success(\n `Moved ${result.entryId} from ${result.fromCollection} to ${result.toCollection}.`,\n result,\n [\n { tool: \"entries\", description: \"View updated entry\", parameters: { action: \"get\", entryId } },\n { tool: \"quality\", description: \"Re-check quality\", parameters: { action: \"check\", entryId } },\n ],\n ),\n };\n } catch (error: unknown) {\n const msg = error instanceof Error ? error.message : String(error);\n const isNotFound = msg.includes(\"not found\");\n if (isNotFound) return notFoundResult(entryId, `Could not move entry: ${msg}`);\n return failureResult(\n `Could not move **${entryId}** to \\`${toCollection}\\`: ${msg}`,\n \"MOVE_FAILED\",\n msg,\n \"Check the entry ID and target collection slug, then retry.\",\n [{ tool: \"entries\", description: \"Search for entry\", parameters: { action: \"search\", query: entryId } }],\n );\n }\n}\n\nasync function handleSearch(\n server: McpServer,\n query: string,\n collection?: string,\n status?: string,\n) {\n const scope = collection ? ` in \\`${collection}\\`` : \"\";\n await server.sendLoggingMessage({\n level: \"info\",\n data: `Searching${scope} for \"${query}\"...`,\n logger: \"product-os\",\n });\n\n const [results, collections] = await Promise.all([\n kernelQuery<unknown[]>(\"chain.searchEntries\", { query, collectionSlug: collection, status }),\n kernelQuery<unknown[]>(\"chain.listCollections\"),\n ]);\n\n if (results.length === 0) {\n const recorded = recordGap({ query, tool: \"entries\", action: \"search\", gapType: \"search_zero\", collectionScope: collection });\n if (recorded) {\n getWorkspaceId()\n .then((wsId) => trackKnowledgeGap(wsId, { query, tool: \"entries\", action: \"search\", gap_type: \"search_zero\", collection_scope: collection }))\n .catch(() => {});\n }\n\n return {\n content: [{\n type: \"text\" as const,\n text: `\"${query}\" is not yet on the Chain${scope}. Try a broader search or use \\`collections action=list\\` to browse available knowledge.`,\n }],\n structuredContent: success(\n `'${query}' is not yet on the Chain${scope}.`,\n { entries: [], total: 0, query },\n [\n { tool: \"entries\", description: \"Try a broader search\", parameters: { action: \"search\", query: query.split(\" \")[0] } },\n { tool: \"collections\", description: \"Browse available collections\", parameters: { action: \"list\" } },\n ],\n ),\n };\n }\n\n const collMap = new Map<string, { name: string; slug: string }>();\n for (const c of collections as { _id: string; name: string; slug: string }[]) {\n collMap.set(c._id, { name: c.name, slug: c.slug });\n }\n\n const countsBySlug = new Map<string, number>();\n for (const e of results as { collectionId: string }[]) {\n const col = collMap.get(e.collectionId);\n const slug = col?.slug ?? \"unknown\";\n countsBySlug.set(slug, (countsBySlug.get(slug) ?? 0) + 1);\n }\n const collSummary = [...countsBySlug.entries()]\n .sort((a, b) => b[1] - a[1])\n .map(([slug, count]) => `${count} ${slug}`)\n .join(\", \");\n\n const formatted = (results as {\n entryId?: string;\n name?: string;\n status?: string;\n workflowStatus?: string;\n collectionId?: string;\n canonicalKey?: string;\n data?: unknown;\n }[])\n .map((e) => {\n const id = e.entryId ? `**${e.entryId}:** ` : \"\";\n const statusDisplay = e.workflowStatus ? `${e.status} / ${e.workflowStatus}` : e.status;\n const col = collMap.get(e.collectionId ?? \"\");\n const colTag = col ? ` [${col.slug}]` : \"\";\n const typeTag = e.canonicalKey ? ` (${e.canonicalKey})` : \"\";\n const desc = extractPreview(e.data, 150);\n const preview = desc ? `\\n ${desc}` : \"\";\n return `- ${id}${e.name} \\`${statusDisplay}\\`${colTag}${typeTag}${preview}`;\n })\n .join(\"\\n\");\n\n const header = `## Search Result\\n\\n# Search Results for \"${query}\"${scope} (${results.length} match${results.length === 1 ? \"\" : \"es\"})\\n\\n**By collection:** ${collSummary}`;\n const footer = `_Tip: Use \\`collection\\` param to scope search. Use entries action=get with an entry ID for full details._`;\n\n const structuredResults = (results as {\n entryId?: string;\n name?: string;\n status?: string;\n workflowStatus?: string;\n collectionId?: string;\n score?: number;\n }[]).map((e) => ({\n entryId: String(e.entryId ?? \"\"),\n name: String(e.name ?? \"\"),\n collection: collMap.get(e.collectionId ?? \"\")?.slug ?? \"unknown\",\n status: String(e.status ?? \"\"),\n ...(e.workflowStatus ? { workflowStatus: e.workflowStatus } : {}),\n ...(e.score != null ? { score: e.score } : {}),\n }));\n\n const entriesForView = structuredResults.map((e) => ({\n entryId: e.entryId,\n name: e.name,\n status: e.status,\n collectionName: e.collection,\n }));\n\n const total = structuredResults.length;\n return {\n content: [{ type: \"text\" as const, text: `${header}\\n\\n${formatted}\\n\\n${footer}` }],\n structuredContent: success(`Found ${total} entries matching '${query}'.`, {\n results: structuredResults,\n entries: entriesForView,\n total,\n query,\n }),\n };\n}\n","/**\n * Graph compound tool — find, suggest.\n * Consolidates find-related and suggest-links into one read-only tool.\n * find: traverses relations from a specific entry (graph walk). NOT full-text search — use entries action=search.\n * suggest: recommends new relations (link discovery).\n */\n\nimport { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { z } from \"zod\";\nimport { kernelQuery, runWithToolContext } from \"../client.js\";\nimport { success, thinWrapper, parseOrFail, unknownAction, notFoundResult, failureResult } from \"../envelope.js\";\n\nconst GRAPH_ACTIONS = [\"find\", \"suggest\"] as const;\n\nexport const graphSchema = z.object({\n action: z.enum(GRAPH_ACTIONS).describe(\n \"'find': traverse relations from an entry (graph walk). 'suggest': discover potential connections for an entry.\",\n ),\n entryId: z.string().describe(\"Entry ID, e.g. 'GT-019', 'FEAT-001'\"),\n direction: z.enum([\"incoming\", \"outgoing\", \"both\"]).default(\"both\").optional()\n .describe(\"For find: 'incoming' = what references this, 'outgoing' = what this references\"),\n limit: z.number().min(1).max(20).default(10).optional()\n .describe(\"For suggest: max suggestions to return\"),\n depth: z.number().min(1).max(3).default(2).optional()\n .describe(\"For suggest: graph traversal depth\"),\n});\n\nexport const graphFindOutputSchema = z.object({\n entryId: z.string(),\n relations: z.array(z.object({\n entryId: z.string().optional(),\n name: z.string(),\n type: z.string(),\n direction: z.enum([\"outgoing\", \"incoming\"]),\n })),\n total: z.number(),\n});\n\nexport const graphSuggestOutputSchema = z.object({\n entryId: z.string(),\n suggestions: z.array(z.object({\n targetEntryId: z.string().optional(),\n targetName: z.string(),\n relationType: z.string(),\n direction: z.string(),\n confidence: z.number(),\n reason: z.string(),\n })),\n total: z.number(),\n});\n\nexport function registerGraphTools(server: McpServer): void {\n server.registerTool(\n \"graph\",\n {\n title: \"Graph\",\n description:\n \"Read from the knowledge graph. Two actions:\\n\\n\" +\n \"- **find**: Traverse relations from a specific entry — shows incoming/outgoing connections. \" +\n \"Use after entries action=get to explore connections. This is NOT full-text search (use entries action=search).\\n\" +\n \"- **suggest**: Discover potential relations for an entry using graph-aware intelligence. \" +\n \"Returns ranked suggestions with confidence scores. Use relations action=create or relations action=batch-create to create the ones that make sense.\",\n inputSchema: graphSchema,\n annotations: { readOnlyHint: true, idempotentHint: true, openWorldHint: false },\n },\n thinWrapper(async (args) => {\n const parsed = parseOrFail(graphSchema, args);\n if (!parsed.ok) return parsed.result;\n const { action, entryId, direction, limit, depth } = parsed.data;\n\n return runWithToolContext({ tool: \"graph\", action }, async () => {\n if (action === \"find\") {\n return handleFind(entryId, direction ?? \"both\");\n }\n\n if (action === \"suggest\") {\n return handleSuggest(entryId, limit ?? 10, depth ?? 2);\n }\n\n return unknownAction(action, GRAPH_ACTIONS);\n });\n }),\n );\n}\n\nasync function handleFind(entryId: string, direction: \"incoming\" | \"outgoing\" | \"both\") {\n const relations = await kernelQuery<Array<{ fromId: string; toId: string; type: string }>>(\"chain.listEntryRelations\", { entryId });\n\n if (relations.length === 0) {\n return {\n content: [{ type: \"text\" as const, text: `No relations found for \\`${entryId}\\`. Use relations action=create to create connections.` }],\n structuredContent: success(\n `No relations found for '${entryId}'.`,\n { entryId, relations: [], nodes: [], edges: [], total: 0 },\n [\n { tool: \"relations\", description: \"Create a relation\", parameters: { action: \"create\", from: entryId } },\n { tool: \"graph\", description: \"Get suggestions\", parameters: { action: \"suggest\", entryId } },\n ],\n ),\n };\n }\n\n const sourceEntry = await kernelQuery<{ _id: string; name: string } | null>(\"chain.getEntry\", { entryId });\n if (!sourceEntry) {\n return notFoundResult(entryId, `Entry '${entryId}' not found. Try entries action=search to find the right ID.`);\n }\n const sourceInternalId = sourceEntry._id;\n\n const MAX_RELATIONS = 25;\n const truncated = relations.length > MAX_RELATIONS;\n const capped = relations.slice(0, MAX_RELATIONS);\n\n const otherIds = new Set<string>();\n for (const r of capped) {\n const otherId = r.fromId === sourceInternalId ? r.toId : r.fromId;\n otherIds.add(otherId);\n }\n\n const otherEntries = new Map<string, { entryId?: string; name: string; collectionId: string }>();\n for (const id of otherIds) {\n const entry = await kernelQuery<{ _id: string; entryId?: string; name: string; collectionId: string } | null>(\"chain.getEntry\", { id });\n if (entry) {\n otherEntries.set(entry._id, { entryId: entry.entryId, name: entry.name, collectionId: entry.collectionId });\n }\n }\n\n const collections = await kernelQuery<Array<{ _id: string; slug: string }>>(\"chain.listCollections\");\n const collMap = new Map<string, string>();\n for (const c of collections) collMap.set(c._id, c.slug);\n\n const lines: string[] = [`## Find Result`, \"\", `# Relations for ${entryId}: ${sourceEntry.name}`, \"\"];\n\n const enriched = capped.map((r) => {\n const isOutgoing = r.fromId === sourceInternalId;\n const otherId = isOutgoing ? r.toId : r.fromId;\n const other = otherEntries.get(otherId);\n const otherLabel = other?.entryId ? `${other.entryId}: ${other.name}` : (other?.name ?? \"(deleted)\");\n const colSlug = other ? (collMap.get(other.collectionId) ?? \"unknown\") : \"unknown\";\n return { isOutgoing, type: r.type, otherLabel, colSlug, otherEntryId: other?.entryId, otherName: other?.name ?? \"(deleted)\" };\n });\n\n const outgoing = enriched.filter((r) => r.isOutgoing);\n const incoming = enriched.filter((r) => !r.isOutgoing);\n\n if ((direction === \"outgoing\" || direction === \"both\") && outgoing.length > 0) {\n lines.push(`## Outgoing (${outgoing.length})`);\n for (const r of outgoing) {\n lines.push(`- → **${r.type}** ${r.otherLabel} [${r.colSlug}]`);\n }\n lines.push(\"\");\n }\n\n if ((direction === \"incoming\" || direction === \"both\") && incoming.length > 0) {\n lines.push(`## Incoming (${incoming.length})`);\n for (const r of incoming) {\n lines.push(`- ← **${r.type}** ${r.otherLabel} [${r.colSlug}]`);\n }\n lines.push(\"\");\n }\n\n const shown = direction === \"outgoing\" ? outgoing : direction === \"incoming\" ? incoming : enriched;\n if (shown.length === 0) {\n lines.push(`No ${direction} relations found for \\`${entryId}\\`.`);\n }\n\n if (truncated) {\n lines.push(`_Showing first ${MAX_RELATIONS} of ${relations.length} relations. Use entries action=get for the full picture._`);\n }\n\n const structuredRelations = shown.map((r) => ({\n entryId: r.otherEntryId,\n name: r.otherName,\n type: r.type,\n direction: (r.isOutgoing ? \"outgoing\" : \"incoming\") as \"outgoing\" | \"incoming\",\n }));\n\n const nodes = [\n { id: entryId, name: sourceEntry.name, collectionName: \"\" },\n ...shown.map((r) => ({\n id: r.otherEntryId ?? String(Math.random()),\n name: r.otherName,\n collectionName: r.colSlug,\n })),\n ];\n const edges = shown\n .filter((r) => r.otherEntryId)\n .map((r) => ({\n source: entryId,\n target: r.otherEntryId!,\n type: r.type,\n }));\n\n return {\n content: [{ type: \"text\" as const, text: lines.join(\"\\n\") }],\n structuredContent: success(\n `Found ${relations.length} relations for ${entryId}.`,\n { entryId, relations: structuredRelations, nodes, edges, total: relations.length },\n [{ tool: \"entries\", description: \"View entry details\", parameters: { action: \"get\", entryId } }],\n ),\n };\n}\n\nasync function handleSuggest(entryId: string, limit: number, depth: number) {\n const result = await kernelQuery<{\n resolvedEntry?: { entryId?: string; name: string };\n suggestions?: Array<{\n entryId?: string;\n name: string;\n collectionSlug: string;\n score: number;\n recommendedRelationType: string;\n reasoning: string;\n preview?: string;\n graphDistance: number;\n }>;\n }>(\"chain.graphSuggestLinks\", {\n entryId,\n maxHops: depth,\n limit,\n });\n\n if (!result?.suggestions || result.suggestions.length === 0) {\n return failureResult(\n `No suggestions found for '${entryId}' — it may already be well-connected, or no similar entries exist.`,\n \"NOT_FOUND\",\n `No suggestions found for '${entryId}'.`,\n \"Entry may already be well-connected.\",\n [{ tool: \"graph\", description: \"Check existing relations\", parameters: { action: \"find\", entryId } }],\n );\n }\n\n const resolved = result.resolvedEntry;\n const resolvedLabel = resolved\n ? `\\`${resolved.entryId ?? resolved.name}\\` (${resolved.name})`\n : `\\`${entryId}\\``;\n\n const suggestions = result.suggestions;\n const graphCount = suggestions.filter((s) => s.graphDistance > 0).length;\n const textCount = suggestions.filter((s) => s.graphDistance === -1).length;\n const sourceId = resolved?.entryId ?? entryId;\n\n const lines = [\n `## Suggest Result`,\n \"\",\n `# Link Suggestions for ${resolvedLabel}`,\n `_${suggestions.length} potential connections (${graphCount} via graph, ${textCount} via text similarity)._`,\n \"\",\n ];\n\n const top3 = suggestions.slice(0, 3);\n lines.push(\"## Quick Wins (top 3)\");\n const batchArgs: string[] = [];\n for (const s of top3) {\n const tid = s.entryId ?? \"(no ID)\";\n const relType = s.recommendedRelationType || \"related_to\";\n lines.push(`- **${tid}**: ${s.name} [${s.collectionSlug}] — ${s.score}/100 → \\`${relType}\\``);\n if (s.entryId) batchArgs.push(`{from:\"${sourceId}\",to:\"${tid}\",type:\"${relType}\"}`);\n }\n lines.push(\"\");\n if (batchArgs.length > 0) {\n lines.push(`**Link all 3:** \\`relations action=batch-create relations=[${batchArgs.join(\",\")}]\\``);\n lines.push(\"\");\n }\n\n if (suggestions.length > 3) {\n lines.push(\"## All Suggestions\");\n for (let i = 0; i < suggestions.length; i++) {\n const s = suggestions[i];\n const scoreBar = \"█\".repeat(Math.round(s.score / 10)) + \"░\".repeat(10 - Math.round(s.score / 10));\n const hopLabel = s.graphDistance > 0 ? `${s.graphDistance}-hop` : \"text\";\n const recType = s.recommendedRelationType !== \"related_to\" ? ` → \\`${s.recommendedRelationType}\\`` : \"\";\n lines.push(`${i + 1}. **${s.entryId ?? \"(no ID)\"}**: ${s.name} [${s.collectionSlug}] (${hopLabel})`);\n lines.push(` ${scoreBar} ${s.score}/100${recType}`);\n if (s.preview) lines.push(` ${s.preview}`);\n lines.push(` _${s.reasoning}_`);\n }\n }\n\n lines.push(\"\");\n lines.push(`**To link one:** \\`relations action=create from=\"${sourceId}\" to=\"{target_id}\" type=\"{type}\"\\``);\n lines.push(`**To dismiss:** \\`relations action=dismiss from=\"${sourceId}\" to=\"{target_id}\" type=\"{type}\"\\``);\n\n const structuredSuggestions = suggestions.map((s) => ({\n targetEntryId: s.entryId,\n targetName: s.name,\n relationType: s.recommendedRelationType || \"related_to\",\n direction: \"outgoing\" as const,\n confidence: s.score,\n reason: s.reasoning,\n }));\n\n const nodes = [\n { id: sourceId, name: resolved?.name ?? entryId, collectionName: \"\" },\n ...suggestions.map((s) => ({\n id: s.entryId ?? String(Math.random()),\n name: s.name,\n collectionName: s.collectionSlug,\n })),\n ];\n const edges = suggestions\n .filter((s) => s.entryId)\n .map((s) => ({\n source: sourceId,\n target: s.entryId!,\n type: s.recommendedRelationType || \"suggested\",\n }));\n\n return {\n content: [{ type: \"text\" as const, text: lines.join(\"\\n\") }],\n structuredContent: success(\n `Found ${suggestions.length} link suggestions for ${resolvedLabel}.`,\n { entryId: sourceId, suggestions: structuredSuggestions, nodes, edges, total: suggestions.length },\n [{ tool: \"relations\", description: \"Create links\", parameters: { action: \"batch-create\" } }],\n ),\n };\n}\n","/**\n * Relations compound tool — create, batch-create, dismiss, delete.\n * Consolidates relate-entries, batch-relate, dismiss-suggestion into one write tool.\n */\n\nimport { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { z } from \"zod\";\nimport { kernelQuery, kernelMutation, getWorkspaceContext, getAgentSessionId, requireWriteAccess, runWithToolContext } from \"../client.js\";\nimport { success, thinWrapper, parseOrFail, unknownAction, validationResult, notFoundResult, successResult, type NextAction } from \"../envelope.js\";\nimport { trackWriteTool } from \"../tool-surface.js\";\n\nconst RELATIONS_ACTIONS = [\"create\", \"batch-create\", \"dismiss\", \"delete\"] as const;\n\nexport const relationsSchema = z.object({\n action: z.enum(RELATIONS_ACTIONS).describe(\n \"'create': link two entries. 'batch-create': create multiple relations. 'dismiss': record that a suggestion was not relevant. 'delete': remove a relation.\",\n ),\n from: z.string().optional().describe(\"Source entry ID for create/dismiss/delete\"),\n to: z.string().optional().describe(\"Target entry ID for create/dismiss/delete\"),\n type: z.string().optional().describe(\"Relation type for create/dismiss/delete\"),\n score: z.number().optional().describe(\"Suggestion score from graph action=suggest (for dismiss)\"),\n relations: z.array(z.object({\n from: z.string(),\n to: z.string(),\n type: z.string(),\n })).min(1).max(20).optional().describe(\"Array of relations for batch-create\"),\n // WP-316 S3: Preview gate — dry-run mode for action=create.\n preview: z.boolean().optional().describe(\"If true, validates the relation without writing. Returns what would happen. Default false. Only applies to action=create.\"),\n});\n\nexport function registerRelationsTools(server: McpServer): void {\n const tool = server.registerTool(\n \"relations\",\n {\n title: \"Relations\",\n description:\n \"Create or manage relations between entries. Write tool — requires active session.\\n\\n\" +\n \"- **create**: Link two entries with a typed relation. Use graph action=suggest to discover connections.\\n\" +\n \"- **batch-create**: Create multiple relations in one call. Use after graph action=suggest.\\n\" +\n \"- **dismiss**: Record that a suggested link was not relevant. Improves future suggestion quality.\\n\" +\n \"- **delete**: Remove a relation by from, to, and type.\",\n inputSchema: relationsSchema,\n annotations: { readOnlyHint: false, destructiveHint: true, openWorldHint: false },\n },\n thinWrapper(async (args) => {\n const parsed = parseOrFail(relationsSchema, args);\n if (!parsed.ok) return parsed.result;\n const { action, from, to, type, score, relations, preview } = parsed.data;\n\n return runWithToolContext({ tool: \"relations\", action }, async () => {\n if (action === \"create\") {\n if (!from || !to || !type) {\n return validationResult(\"from, to, and type are required when action is 'create'.\");\n }\n return handleCreate(from, to, type, score, preview);\n }\n\n if (action === \"batch-create\") {\n if (!relations || relations.length === 0) {\n return validationResult(\"relations is required when action is 'batch-create'.\");\n }\n return handleBatchCreate(relations);\n }\n\n if (action === \"dismiss\") {\n if (!from || !to) {\n return validationResult(\"from and to are required when action is 'dismiss'.\");\n }\n return handleDismiss(from, to, type ?? \"related_to\", score);\n }\n\n if (action === \"delete\") {\n if (!from || !to || !type) {\n return validationResult(\"from, to, and type are required when action is 'delete'.\");\n }\n return handleDelete(from, to, type);\n }\n\n return unknownAction(action, RELATIONS_ACTIONS);\n });\n }),\n );\n trackWriteTool(tool);\n}\n\nasync function handleCreate(from: string, to: string, type: string, score?: number, preview?: boolean) {\n requireWriteAccess();\n const agentSessionId = getAgentSessionId();\n\n type CreateResult = {\n preview?: boolean;\n status?: string;\n chainDebtPrevented?: boolean;\n proposalId?: string;\n originalType?: string;\n suggestedAlternatives?: Array<{ type: string; reason: string }>;\n existing?: boolean;\n fromEntryId?: string;\n toEntryId?: string;\n message?: string;\n relationId?: string;\n suggestedType?: { type: string; confidence: number; reasoning: string; governancePosture?: string };\n };\n const result = await kernelMutation<CreateResult>(\"chain.createEntryRelation\", {\n fromEntryId: from,\n toEntryId: to,\n type,\n suggestionScore: score ?? undefined,\n sessionId: agentSessionId ?? undefined,\n ...(preview ? { preview: true } : {}),\n });\n\n // WP-363 S5: Chain debt prevented — misuse pattern intercepted, agent-proposal created.\n if (result?.chainDebtPrevented) {\n const alts = result.suggestedAlternatives ?? [];\n const altList = alts.map((a) => ` • \\`${a.type}\\`: ${a.reason}`).join(\"\\n\");\n return {\n content: [{\n type: \"text\" as const,\n text: `# Chain Debt Prevented\\n\\n**\"${result.originalType ?? type}\"** was intercepted as a common misuse for this entry pair and converted to an agent sign-off proposal.\\n\\n**Proposal ID:** \\`${result.proposalId}\\`\\n\\n**Suggested alternatives:**\\n${altList}\\n\\nReview at /review in Cortex UI.`,\n }],\n structuredContent: success(\n `Chain debt prevented: \"${result.originalType ?? type}\" was intercepted and converted to an agent sign-off proposal.`,\n {\n chainDebtPrevented: true,\n proposalId: result.proposalId,\n originalType: result.originalType ?? type,\n suggestedAlternatives: result.suggestedAlternatives,\n },\n [\n { tool: \"relations\", description: \"Use correct type (e.g. informed_by)\", parameters: { action: \"create\", from, to, type: alts[0]?.type ?? \"informed_by\" } },\n ],\n ),\n };\n }\n\n // WP-316 S3: Preview gate — return dry-run result without recording session activity.\n if (result?.preview) {\n const suggested = result.suggestedType;\n // WP-316 gap fix: add governance posture so agents know whether the suggested type requires consent.\n const suggestedWithPosture = suggested\n ? { ...suggested, governancePosture: suggested.type === \"governs\" ? \"requires_consent\" : \"direct\" }\n : undefined;\n return {\n content: [{ type: \"text\" as const, text: `# Preview: would relate ${from} → ${to} (${type})\\n\\nNo DB writes — call without \\`preview:true\\` to create for real.${suggestedWithPosture ? `\\n\\n**Type suggestion:** \\`${suggestedWithPosture.type}\\` may be more precise (${suggestedWithPosture.confidence}% confidence). Governance: ${suggestedWithPosture.governancePosture}.` : \"\"}` }],\n structuredContent: success(\n `Preview: would relate ${from} → ${to} (${type}) — no DB writes`,\n {\n status: \"preview\" as const, from, to, type,\n ...(suggestedWithPosture && { suggestedType: suggestedWithPosture }),\n },\n [{ tool: \"relations\", description: \"Create for real\", parameters: { action: \"create\", from, to, type } }],\n ),\n };\n }\n\n const wsCtx = await getWorkspaceContext();\n if (result?.status === \"proposal_created\") {\n const existingNote = result.existing ? \" (existing proposal reused)\" : \"\";\n return {\n content: [{\n type: \"text\" as const,\n text: `# Proposal Created — Governs Relation\\n\\n**${result.fromEntryId ?? from}** —[${type}]→ **${result.toEntryId ?? to}**\\n\\n${result.message ?? \"Governs relation requires async consent. A proposal was created for review.\"}\\n\\n**Proposal ID:** \\`${result.proposalId}\\`${existingNote}\\n**Workspace:** ${wsCtx.workspaceSlug} (${wsCtx.workspaceId})\\n\\nThe relation was **not applied** — it will be created when the proposal is approved.`,\n }],\n structuredContent: success(\n `Proposal created for ${from} → ${to} (${type}). Awaiting consent.`,\n { status: \"proposal_created\" as const, from, to, type, proposalId: result.proposalId },\n ),\n };\n }\n\n const lines = [\n `# Relation Created`,\n \"\",\n `**${from}** —[${type}]→ **${to}**`,\n `**Workspace:** ${wsCtx.workspaceSlug} (${wsCtx.workspaceId})`,\n ];\n\n const suggested = result?.suggestedType;\n // WP-316 gap fix: add governance posture so agents know whether the suggested type requires consent.\n const suggestedWithPosture = suggested\n ? { ...suggested, governancePosture: suggested.type === \"governs\" ? \"requires_consent\" : \"direct\" }\n : undefined;\n if (suggestedWithPosture) {\n lines.push(\"\");\n lines.push(`**Type suggestion:** \\`${suggestedWithPosture.type}\\` may be more precise (${suggestedWithPosture.confidence}% confidence). Governance: ${suggestedWithPosture.governancePosture}.`);\n lines.push(`_${suggestedWithPosture.reasoning}_`);\n lines.push(`To use instead: \\`relations action=create from=\"${from}\" to=\"${to}\" type=\"${suggestedWithPosture.type}\"\\``);\n }\n\n return {\n content: [{ type: \"text\" as const, text: lines.join(\"\\n\") }],\n structuredContent: success(\n `Created relation ${from} → ${to} (${type}).`,\n {\n status: \"created\" as const, from, to, type,\n ...(suggestedWithPosture && { suggestedType: suggestedWithPosture }),\n },\n [{ tool: \"graph\", description: \"See connections\", parameters: { action: \"find\", entryId: from } }],\n ),\n };\n}\n\nasync function handleBatchCreate(relations: Array<{ from: string; to: string; type: string }>) {\n requireWriteAccess();\n const agentSessionId = getAgentSessionId();\n\n type RelResult = { from: string; to: string; type: string; ok: boolean; error?: string; proposalCreated?: boolean; proposalId?: string };\n const results: RelResult[] = [];\n\n // Governs relations need proposal flow — use single mutation\n const governsRels = relations.filter(r => r.type === \"governs\");\n const batchRels = relations.filter(r => r.type !== \"governs\");\n\n // Batch non-governs in one transaction (BET-105 E4)\n if (batchRels.length > 0) {\n try {\n const batchResult = await kernelMutation<{\n results: Array<{ fromEntryId: string; toEntryId: string; type: string; ok: boolean; error?: string }>;\n }>(\"chain.createEntryRelations\", {\n relations: batchRels.map(r => ({ fromEntryId: r.from, toEntryId: r.to, type: r.type })),\n sessionId: agentSessionId ?? undefined,\n });\n for (let i = 0; i < batchRels.length; i++) {\n const rel = batchRels[i];\n const res = batchResult.results[i];\n results.push({ ...rel, ok: res?.ok ?? false, error: res?.error });\n }\n } catch (e: unknown) {\n for (const rel of batchRels) {\n results.push({ ...rel, ok: false, error: e instanceof Error ? e.message : \"Batch failed\" });\n }\n }\n }\n\n // Governs relations individually (proposal flow requires single mutation)\n for (const rel of governsRels) {\n try {\n const result = await kernelMutation<{ status?: string; proposalId?: string }>(\"chain.createEntryRelation\", {\n fromEntryId: rel.from,\n toEntryId: rel.to,\n type: rel.type,\n sessionId: agentSessionId ?? undefined,\n });\n results.push({\n ...rel,\n ok: true,\n proposalCreated: result?.status === \"proposal_created\",\n proposalId: result?.proposalId,\n });\n } catch (e: unknown) {\n results.push({ ...rel, ok: false, error: e instanceof Error ? e.message : \"Unknown error\" });\n }\n }\n\n const created = results.filter((r) => r.ok && !r.proposalCreated);\n const proposals = results.filter((r) => r.ok && r.proposalCreated);\n const failed = results.filter((r) => !r.ok);\n\n const lines = [`# Batch Link Results\\n`];\n lines.push(`**${created.length}** created, **${proposals.length}** proposals, **${failed.length}** failed out of ${relations.length} total.\\n`);\n\n if (created.length > 0) {\n lines.push(\"## Created\");\n for (const r of created) {\n lines.push(`- **${r.from}** —[${r.type}]→ **${r.to}**`);\n }\n }\n\n if (proposals.length > 0) {\n lines.push(\"\");\n lines.push(\"## Proposals (governs — not yet applied)\");\n for (const r of proposals) {\n lines.push(`- **${r.from}** —[${r.type}]→ **${r.to}** — proposal \\`${r.proposalId}\\``);\n }\n }\n\n if (failed.length > 0) {\n lines.push(\"\");\n lines.push(\"## Failed\");\n for (const r of failed) {\n lines.push(`- **${r.from}** → **${r.to}** (${r.type}): _${r.error}_`);\n }\n }\n\n const next: NextAction[] = failed.length === 0\n ? [{ tool: \"graph\", description: \"Check connections\", parameters: { action: \"find\", entryId: relations[0].from } }]\n : [];\n\n return {\n content: [{ type: \"text\" as const, text: lines.join(\"\\n\") }],\n structuredContent: success(\n `Batch: ${created.length} created, ${proposals.length} proposals, ${failed.length} failed of ${relations.length}.`,\n { created: created.length, proposals: proposals.length, failed: failed.length, total: relations.length, results },\n next.length ? next : undefined,\n ),\n };\n}\n\nasync function handleDismiss(from: string, to: string, type: string, score?: number) {\n requireWriteAccess();\n\n const fromEntry = await kernelQuery<{ _id: string } | null>(\"chain.getEntry\", { entryId: from });\n if (!fromEntry) {\n return notFoundResult(from);\n }\n const toEntry = await kernelQuery<{ _id: string } | null>(\"chain.getEntry\", { entryId: to });\n if (!toEntry) {\n return notFoundResult(to);\n }\n\n await kernelMutation(\"chain.dismissSuggestion\", {\n fromEntryId: fromEntry._id,\n suggestedEntryId: toEntry._id,\n recommendedType: type,\n score: score ?? 0,\n });\n\n return successResult(\n `Dismissed suggestion: ${from} → ${to} (${type}). Feedback recorded for scoring improvements.`,\n `Dismissed suggestion ${from} → ${to} (${type}). Feedback recorded.`,\n { from, to, type },\n );\n}\n\nasync function handleDelete(from: string, to: string, type: string) {\n requireWriteAccess();\n\n await kernelMutation(\"chain.removeEntryRelation\", {\n fromEntryId: from,\n toEntryId: to,\n type,\n });\n\n return successResult(\n `Removed relation: ${from} —[${type}]→ ${to}.`,\n `Relation ${from} → ${to} (${type}) removed.`,\n { from, to, type },\n [{ tool: \"graph\", description: \"Check remaining connections\", parameters: { action: \"find\", entryId: from } }],\n );\n}\n","/**\n * Context compound tool — gather, build.\n * Consolidates gather-context and get-build-context into one tool.\n * gather: entry-based graph traversal, task-based auto-load, or graph mode with provenance.\n * build: structured build spec for an entry (requires active session).\n */\n\nimport { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { z } from \"zod\";\nimport { kernelQuery, kernelMutation, getWorkspaceId, requireActiveSession, runWithToolContext } from \"../client.js\";\nimport { success, failure, thinWrapper, parseOrFail, unknownAction, validationResult, notFoundResult } from \"../envelope.js\";\nimport { translateStaleToolNames } from \"./knowledge-helpers.js\";\nimport { trackKnowledgeGap } from \"../analytics.js\";\nimport { recordGap } from \"../gap-store.js\";\n\nfunction annotateStaleNames(text: string): string {\n const footnote = translateStaleToolNames(text);\n return footnote ? text + footnote : text;\n}\n\n/**\n * Collection header hint for epistemic collections in context views.\n * BET-281: When governanceRole field is available on collections, replace\n * name-based checks with governanceRole === 'epistemic'. Currently the\n * collection display name is stable and this is pure UX chrome.\n */\nfunction epistemicCollectionHint(collectionName: string): string {\n const lc = collectionName.toLowerCase();\n if (lc === \"insights\") return \" — _verify confidence with `entries action=get`_\";\n if (lc === \"assumptions\") return \" — _check evidence strength with `entries action=get`_\";\n return \"\";\n}\n\ninterface ContextEntry {\n entryId?: string;\n name: string;\n collectionName: string;\n relationType: string;\n relationDirection: \"outgoing\" | \"incoming\";\n hop: number;\n score?: number;\n scoreFlags?: string[];\n preview?: string;\n /** BET-240 S0: Entry provenance — human, agent, or external. */\n origin?: \"human\" | \"agent\" | \"external\";\n provenance?: Array<{ entryId?: string; name: string; relationType: string }>;\n}\n\ninterface GatherResult {\n root: { entryId: string; name: string } | null;\n related: ContextEntry[];\n totalRelations: number;\n hopsTraversed: number;\n}\n\ninterface GraphGatherResult {\n root: { entryId: string; name: string } | null;\n context: ContextEntry[];\n totalFound: number;\n hopsTraversed: number;\n}\n\ninterface TaskGatherResult {\n groundingStatus: \"grounded\" | \"partial\" | \"missing\";\n totalFound: number;\n confidence: string;\n seeds?: Array<{ entryId?: string | null; name: string; source?: \"vector\" | \"fts\" | \"both\" }>;\n bindingGovernance: {\n principles: Array<{ entryId: string | null; name: string; collectionName?: string | null; collectionSlug?: string | null; score?: number; scoreFlags?: string[]; preview?: string; origin?: \"human\" | \"agent\" | \"external\" }>;\n standards: Array<{ entryId: string | null; name: string; collectionName?: string | null; collectionSlug?: string | null; score?: number; scoreFlags?: string[]; preview?: string; origin?: \"human\" | \"agent\" | \"external\" }>;\n businessRules: Array<{ entryId: string | null; name: string; collectionName?: string | null; collectionSlug?: string | null; score?: number; scoreFlags?: string[]; preview?: string; origin?: \"human\" | \"agent\" | \"external\" }>;\n };\n steeringContext: ContextEntry[];\n supportingContext: ContextEntry[];\n}\n\ntype BindingGovernanceEntry = TaskGatherResult[\"bindingGovernance\"][\"principles\"][number];\n\ninterface JourneyStage {\n slotId: string;\n label: string;\n ingredients: Array<{ entryId: string; name: string; status: string }>;\n}\n\ninterface JourneyGatherResult {\n map: { entryId: string; name: string; templateId: string; templateName: string };\n stages: JourneyStage[];\n context: ContextEntry[];\n totalFound: number;\n seedCount: number;\n truncated: boolean;\n}\n\ninterface BuildResult {\n entry: { name: string; entryId?: string; collectionSlug: string; status: string; data: Record<string, unknown> };\n relatedByCollection: Record<string, Array<{ entryId?: string; name: string; relationType: string }>>;\n businessRules: Array<{ entryId?: string; name: string; description?: string }>;\n glossaryTerms: Array<{ entryId?: string; name: string; definition?: string }>;\n rulesToHonor: unknown[];\n chainRefs: string[];\n contextTruncated: boolean;\n}\n\ninterface NeighborhoodItem {\n entryDocId: string;\n entryId: string | null;\n name: string;\n status?: string;\n hop?: number;\n relationType?: string;\n unresolvedFlag?: boolean;\n openCount?: number;\n blockedCount?: number;\n}\n\ninterface NeighborhoodResult {\n blockingChain: NeighborhoodItem[];\n dependencyChain: NeighborhoodItem[];\n parentContext: (NeighborhoodItem & { openCount: number; blockedCount: number }) | null;\n relatedTensions: NeighborhoodItem[];\n stalenessSignal: { isStale: boolean; daysSinceUpdate: number } | null;\n isolationSignal: boolean;\n}\n\nconst CONTEXT_ACTIONS = [\"gather\", \"build\", \"neighborhood\", \"changes\", \"chain\", \"cross-cut\", \"incremental\", \"brief\"] as const;\n\nexport const contextSchema = z.object({\n action: z.enum(CONTEXT_ACTIONS).describe(\n \"'gather': assemble knowledge context (entry graph, task auto-load, journey mode, or graph mode). \" +\n \"'build': structured build spec for an entry. \" +\n \"'neighborhood': typed graph neighborhood for an entry — blocking chain, dependencies, parent context, tensions, staleness (BET-142). \" +\n \"'changes': entries modified and relations created since a timestamp (BET-239). Requires 'since' parameter. \" +\n \"'chain': directed traversal along one relation type to depth 4 (BET-239). Requires entryId. Optional: direction, relationType, maxHops (1-4). \" +\n \"'cross-cut': structural aggregation — all relations of a given type grouped by source collection (BET-239). Requires 'relationType' parameter. \" +\n \"'incremental': delta since last brief run for a skill (BET-239 E4). Requires 'skill' parameter. Returns only entries changed since the skill's last brief. \" +\n \"'brief': compound intelligence query (BET-239 E6). Requires 'briefType' parameter: 'steering' (changes + structure + delta + readiness), 'confidence' (changes + active bets + tensions), or 'delta' (changes + relations since timestamp). Optional 'since' for delta type.\",\n ),\n entryId: z.string().optional().describe(\"Entry ID for graph traversal or build, e.g. 'FEAT-001', 'GT-019'\"),\n mapEntryId: z.string().optional().describe(\n \"Journey map entry ID for journey-aware context (gather only). Returns context organised by journey stage. \" +\n \"Takes precedence over entryId when both are supplied. Example: 'MAP-1'.\",\n ),\n task: z.string().optional().describe(\"Natural-language task description for loading task-relevant governance, binding constraints, and supporting context (gather only)\"),\n since: z.string().optional().describe(\n \"ISO 8601 timestamp for 'changes' action — returns entries/relations modified since this time. \" +\n \"Example: '2026-03-24T00:00:00Z'.\",\n ),\n direction: z.enum([\"outgoing\", \"incoming\"]).default(\"outgoing\").optional()\n .describe(\"For 'chain' action: traversal direction. 'outgoing' follows relations from source, 'incoming' follows relations to source. Default: outgoing.\"),\n relationType: z.string().optional().describe(\n \"Relation type filter. For 'chain': optional filter to traverse only this relation type. \" +\n \"For 'cross-cut': required — scans all relations of this type across the workspace. \" +\n \"Examples: 'part_of', 'informs', 'governs', 'blocks', 'depends_on'.\",\n ),\n mode: z.enum([\"search\", \"graph\"]).default(\"search\").optional()\n .describe(\"For gather: 'search' (default) or 'graph' (enhanced with provenance paths). Ignored when mapEntryId is provided.\"),\n maxHops: z.number().min(1).max(4).default(2)\n .describe(\"Relation traversal depth (1=direct only, 2=default, 3=wide net, 4=deep chain walk)\"),\n maxResults: z.number().min(1).max(25).default(10).optional()\n .describe(\"Max entries to return in gather task mode (default 10)\"),\n strategy: z.enum([\"hybrid\", \"keyword\"]).default(\"keyword\").optional()\n .describe(\"Seed strategy for task-based gather: 'keyword' (FTS only, default) or 'hybrid' (vector + FTS). Only affects task mode.\"),\n skill: z.string().optional().describe(\n \"Skill name for 'incremental' action — identifies which skill's brief history to compare against. \" +\n \"Examples: 'preflight', 'shaping', 'review'. Required when action is 'incremental'.\",\n ),\n briefType: z.enum([\"steering\", \"confidence\", \"delta\"]).optional().describe(\n \"Compound query type for 'brief' action. \" +\n \"'steering': 7d changes + structural aggregation (part_of, depends_on, constrains) + incremental delta + workspace readiness. \" +\n \"'confidence': 7d changes + active bets summary + active tensions breakdown. \" +\n \"'delta': changes + relations since a custom timestamp (use 'since' param). \" +\n \"Required when action is 'brief'.\",\n ),\n});\n\nexport function registerContextTools(server: McpServer): void {\n server.registerTool(\n \"context\",\n {\n title: \"Context\",\n description:\n \"Assemble knowledge context in one call. Six actions:\\n\\n\" +\n \"- **gather**: Three modes — (1) By entry: traverse the graph around a specific entry. \" +\n \"(2) By task: load task-relevant governance, binding constraints, and supporting domain knowledge for a natural-language task. \" +\n \"(3) Graph mode (entryId + mode='graph'): enhanced traversal with provenance paths.\\n\" +\n \"- **build**: Structured build spec for any entry — data, related entries, business rules, \" +\n \"glossary terms, chain refs. Use when starting a build. Requires active session.\\n\" +\n \"- **neighborhood**: Typed graph neighborhood — blocking chain (what this blocks, 3 hops), \" +\n \"dependency chain (what blocks this), parent context (sibling count), related tensions, \" +\n \"staleness signal, isolation signal. Fast indexed lookups. Requires entryId.\\n\" +\n \"- **changes**: Detect entries modified and relations created since a timestamp. \" +\n \"Use for incremental updates instead of full traversal. Requires 'since' (ISO 8601). \" +\n \"Returns grouped counts by collection. Cap: 200 entries. (BET-239)\\n\" +\n \"- **chain**: Directed deep traversal along one relation type to depth 4 (BET-239). \" +\n \"Use for dependency analysis, governance chains, strategic alignment. Requires entryId. \" +\n \"Optional: direction (outgoing/incoming), relationType, maxHops (1-4). \" +\n \"Cycle detection, fan-out cap 10/hop, total cap 100 nodes. Returns tree + edges.\\n\" +\n \"- **cross-cut**: Structural aggregation — all relations of a given type across the workspace, \" +\n \"grouped by source collection. Use to answer 'show me everything connected by part_of'. \" +\n \"Requires 'relationType'. Cap: 500 entries. (BET-239)\\n\" +\n \"- **incremental**: Delta since last brief run for a skill. Returns only entries changed since \" +\n \"the skill's last brief, filtering out previously surfaced entries. Requires 'skill' parameter. \" +\n \"Use for steering briefs that need incremental awareness. (BET-239 E4)\\n\" +\n \"- **brief**: Compound intelligence query composing multiple primitives. Requires 'briefType': \" +\n \"'steering' (7d changes + structure + delta + readiness), 'confidence' (7d changes + active bets + tensions), \" +\n \"or 'delta' (changes since custom timestamp). Auto-records brief run for steering. (BET-239 E6)\",\n inputSchema: contextSchema,\n annotations: { readOnlyHint: true, idempotentHint: true, openWorldHint: false },\n },\n thinWrapper(async (args) => {\n const parsed = parseOrFail(contextSchema, args);\n if (!parsed.ok) return parsed.result;\n const { action, entryId, mapEntryId, task, since, direction, relationType, mode, maxHops, maxResults, strategy, skill, briefType } = parsed.data;\n\n return runWithToolContext({ tool: \"context\", action }, async () => {\n if (action === \"gather\") {\n // Journey mode takes precedence over entryId when mapEntryId is supplied\n if (mapEntryId) {\n return handleJourneyGather(server, mapEntryId, maxHops ?? 2, maxResults ?? 20);\n }\n return handleGather(server, entryId, task, mode ?? \"search\", maxHops ?? 2, maxResults ?? 10, strategy ?? \"keyword\");\n }\n\n if (action === \"build\") {\n if (!entryId) {\n return validationResult(\"entryId is required when action is 'build'.\");\n }\n return handleBuild(server, entryId, maxHops ?? 2);\n }\n\n if (action === \"neighborhood\") {\n if (!entryId) {\n return validationResult(\"entryId is required when action is 'neighborhood'.\");\n }\n return handleNeighborhood(entryId);\n }\n\n if (action === \"changes\") {\n if (!since) {\n return validationResult(\"'since' (ISO 8601 timestamp) is required when action is 'changes'.\");\n }\n return handleChanges(since);\n }\n\n if (action === \"chain\") {\n if (!entryId) {\n return validationResult(\"entryId is required when action is 'chain'.\");\n }\n return handleChainWalk(entryId, direction ?? \"outgoing\", maxHops ?? 2, relationType);\n }\n\n if (action === \"cross-cut\") {\n if (!relationType) {\n return validationResult(\"'relationType' is required when action is 'cross-cut'. Examples: 'part_of', 'informs', 'governs'.\");\n }\n return handleCrossCut(relationType);\n }\n\n if (action === \"incremental\") {\n if (!skill) {\n return validationResult(\"'skill' is required when action is 'incremental'. Examples: 'preflight', 'shaping', 'review'.\");\n }\n return handleIncremental(skill);\n }\n\n if (action === \"brief\") {\n if (!briefType) {\n return validationResult(\"'briefType' is required when action is 'brief'. Options: 'steering', 'confidence', 'delta'.\");\n }\n const sinceMs = briefType === \"delta\" && since ? Date.parse(since) : undefined;\n if (briefType === \"delta\" && since && (sinceMs === undefined || isNaN(sinceMs))) {\n return validationResult(`Invalid 'since' timestamp: '${since}'. Use ISO 8601 format (e.g. '2026-03-24T00:00:00Z').`);\n }\n return handleBrief(briefType, sinceMs);\n }\n\n return unknownAction(action, CONTEXT_ACTIONS);\n });\n }),\n );\n}\n\nasync function handleGather(\n server: McpServer,\n entryId: string | undefined,\n task: string | undefined,\n mode: \"search\" | \"graph\",\n maxHops: number,\n maxResults: number,\n strategy: \"hybrid\" | \"keyword\" = \"keyword\",\n) {\n if (!entryId && !task) {\n return validationResult(\"Provide either entryId (graph traversal) or task (auto-load context).\");\n }\n\n // Graph mode: enhanced traversal with provenance paths\n if (entryId && mode === \"graph\") {\n await server.sendLoggingMessage({\n level: \"info\",\n data: `Graph traversal for ${entryId} (depth: ${maxHops})...`,\n logger: \"product-brain\",\n });\n\n const result = await kernelQuery<GraphGatherResult>(\"chain.graphGatherContext\", {\n entryId,\n maxHops,\n });\n\n if (!result?.root) {\n return notFoundResult(entryId!, `Entry '${entryId}' not found. Try search to find the right ID.`);\n }\n\n if (result.context.length === 0) {\n const recorded = recordGap({ query: result.root.entryId, tool: \"context\", action: \"gather\", gapType: \"context_graph_empty\" });\n if (recorded) {\n getWorkspaceId()\n .then((wsId) => trackKnowledgeGap(wsId, { query: result.root.entryId, tool: \"context\", action: \"gather\", gap_type: \"context_graph_empty\" }))\n .catch(() => {});\n }\n\n return {\n content: [{\n type: \"text\" as const,\n text: `# Context for ${result.root.entryId}: ${result.root.name}\\n\\n` +\n `_No relations found._ This entry is not yet connected to the knowledge graph.\\n\\n` +\n `Use \\`graph action=suggest\\` to discover potential connections.`,\n }],\n structuredContent: success(\n `No relations found for ${result.root.entryId}. Entry not yet connected.`,\n { root: result.root, context: [], totalFound: 0 },\n [{ tool: \"graph\", description: \"Discover connections\", parameters: { action: \"suggest\", entryId: result.root.entryId } }],\n ),\n };\n }\n\n const byCollection = new Map<string, ContextEntry[]>();\n for (const entry of result.context) {\n const key = entry.collectionName;\n if (!byCollection.has(key)) byCollection.set(key, []);\n byCollection.get(key)!.push(entry);\n }\n\n const lines: string[] = [\n `# Context for ${result.root.entryId}: ${result.root.name} (graph mode)`,\n `_${result.totalFound} related entries across ${byCollection.size} collections (${result.hopsTraversed} hops)_`,\n \"\",\n ];\n\n for (const [collName, entries] of byCollection) {\n lines.push(`## ${collName} (${entries.length})${epistemicCollectionHint(collName)}`);\n for (const e of entries) {\n const arrow = e.relationDirection === \"outgoing\" ? \"→\" : \"←\";\n const id = e.entryId ? `${e.entryId}: ` : \"\";\n const hopLabel = e.hop > 1 ? ` (hop ${e.hop})` : \"\";\n const scoreLabel = typeof e.score === \"number\" ? ` ${e.score}` : \"\";\n const flagsLabel = e.scoreFlags?.length ? ` [${e.scoreFlags.join(\", \")}]` : \"\";\n const originLabel = e.origin ? ` (origin: ${e.origin})` : \"\";\n const provenancePath = e.provenance && e.provenance.length > 1\n ? `\\n _Path: ${e.provenance.map((p) => `${p.entryId ?? p.name} [${p.relationType}]`).join(\" → \")}_`\n : \"\";\n const preview = e.preview ? `\\n ${e.preview.substring(0, 120)}` : \"\";\n lines.push(`- ${arrow} **${e.relationType}** ${id}${e.name}${hopLabel}${scoreLabel}${flagsLabel}${originLabel}${provenancePath}${preview}`);\n }\n lines.push(\"\");\n }\n\n const rootId = result.root.entryId ?? \"root\";\n const nodes = [\n { id: rootId, name: result.root.name, collectionName: \"\" },\n ...result.context.map((e) => ({\n id: e.entryId ?? String(Math.random()),\n name: e.name,\n collectionName: e.collectionName,\n })),\n ];\n const edges = result.context\n .filter((e) => e.entryId)\n .map((e) => ({\n source: rootId,\n target: e.entryId!,\n type: e.relationType,\n }));\n\n return {\n content: [{ type: \"text\" as const, text: lines.join(\"\\n\") }],\n structuredContent: success(\n `Gathered ${result.totalFound} related entries for ${result.root.entryId} (${result.hopsTraversed} hops, graph mode).`,\n { nodes, edges, root: result.root, totalFound: result.totalFound },\n ),\n };\n }\n\n // Task mode: unified search-then-traverse via intelligence layer\n // BET-205 Slice 2: strategy routing — hybrid calls vector+FTS action, keyword uses existing FTS query\n if (task && !entryId) {\n const strategyLabel = strategy === \"hybrid\" ? \"hybrid (vector + FTS)\" : \"keyword (FTS only)\";\n await server.sendLoggingMessage({\n level: \"info\",\n data: `Loading context for task: \"${task.substring(0, 80)}...\" [strategy: ${strategyLabel}]`,\n logger: \"product-brain\",\n });\n\n const result = strategy === \"hybrid\"\n ? await kernelQuery<TaskGatherResult>(\"chain.resolveTaskStartupHybrid\", {\n task,\n maxHops,\n maxResults,\n })\n : await kernelQuery<TaskGatherResult>(\"chain.resolveTaskStartup\", {\n task,\n maxHops,\n maxResults,\n });\n\n if (!result || result.totalFound === 0) {\n const taskQuery = task.slice(0, 200);\n const recorded = recordGap({ query: taskQuery, tool: \"context\", action: \"gather\", gapType: \"context_task_empty\" });\n if (recorded) {\n getWorkspaceId()\n .then((wsId) => trackKnowledgeGap(wsId, { query: taskQuery, tool: \"context\", action: \"gather\", gap_type: \"context_task_empty\" }))\n .catch(() => {});\n }\n\n return {\n content: [{\n type: \"text\" as const,\n text: `# Task Constraints Loaded\\n\\n**Confidence:** None\\n\\n` +\n `No task-relevant governance or supporting context was found yet. If you discover relevant knowledge during this task, ` +\n `use \\`capture\\` with a name and description to add it.\\n\\n` +\n `_This helps future sessions start with better constraints and context._`,\n }],\n structuredContent: failure(\n \"NOT_FOUND\",\n \"No task-relevant governance or supporting context was found yet.\",\n \"If you discover relevant knowledge during this task, capture it with a name and description.\",\n [{ tool: \"entries\", description: \"Search for related terms\", parameters: { action: \"search\", query: task.split(\" \").slice(0, 3).join(\" \") } }],\n ),\n };\n }\n\n const hasBindingGovernance =\n result.bindingGovernance.principles.length > 0 ||\n result.bindingGovernance.standards.length > 0 ||\n result.bindingGovernance.businessRules.length > 0;\n\n const byCollection = new Map<string, ContextEntry[]>();\n for (const entry of result.supportingContext) {\n const key = entry.collectionName;\n if (!byCollection.has(key)) byCollection.set(key, []);\n byCollection.get(key)!.push(entry);\n }\n const steeringCount = result.steeringContext.length;\n const collectionCount = new Set(\n [...result.steeringContext, ...result.supportingContext].map((entry) => entry.collectionName),\n ).size;\n\n // Format seed display — hybrid seeds include source (vector/fts/both), keyword seeds do not\n const seedDisplay = result.seeds?.map((s: any) => {\n const id = s.entryId ?? s.name;\n return s.source ? `${id} [${s.source}]` : id;\n }).join(\", \") ?? \"none\";\n\n const lines: string[] = [\n `# Task Constraints Loaded`,\n `**Confidence:** ${result.confidence.charAt(0).toUpperCase() + result.confidence.slice(1)}`,\n `**Grounding:** ${result.groundingStatus}`,\n `**Strategy:** ${strategyLabel}`,\n `**Matched:** ${result.totalFound} entries across ${collectionCount} collection${collectionCount === 1 ? \"\" : \"s\"}`,\n `**Seeds:** ${seedDisplay}`,\n \"\",\n ];\n\n lines.push(\"_Use this task gather as the live constraint load for the work you are about to do, then open any cited entries for full details._\");\n lines.push(\"\");\n\n if (hasBindingGovernance) {\n lines.push(\"## Binding governance\");\n lines.push(\"_These are the non-optional rules and standards that govern this task._\");\n lines.push(\"\");\n\n const governanceSections: Array<[string, BindingGovernanceEntry[]]> = [\n [\"Principles\", result.bindingGovernance.principles],\n [\"Standards\", result.bindingGovernance.standards],\n [\"Business Rules\", result.bindingGovernance.businessRules],\n ];\n\n for (const [title, entries] of governanceSections) {\n if (entries.length === 0) continue;\n lines.push(`### ${title} (${entries.length})`);\n for (const entry of entries) {\n const id = entry.entryId ? `**${entry.entryId}:** ` : \"\";\n const scoreLabel = typeof entry.score === \"number\" ? ` ${entry.score}` : \"\";\n const flagsLabel = entry.scoreFlags?.length ? ` [${entry.scoreFlags.join(\", \")}]` : \"\";\n const originLabel = entry.origin ? ` (origin: ${entry.origin})` : \"\";\n lines.push(`- ${id}${entry.name}${scoreLabel}${flagsLabel}${originLabel}`);\n if (entry.preview) lines.push(` _${entry.preview}_`);\n }\n lines.push(\"\");\n }\n }\n\n lines.push(\"## Steering context\");\n lines.push(\"_These entries set the frame for the work before you drop into broader supporting detail._\");\n lines.push(\"\");\n if (steeringCount === 0) {\n lines.push(\"_No steering context matched yet._\");\n lines.push(\"\");\n } else {\n for (const entry of result.steeringContext) {\n const id = entry.entryId ? `**${entry.entryId}:** ` : \"\";\n const scoreLabel = typeof entry.score === \"number\" ? ` ${entry.score}` : \"\";\n const flagsLabel = entry.scoreFlags?.length ? ` [${entry.scoreFlags.join(\", \")}]` : \"\";\n const originLabel = entry.origin ? ` (origin: ${entry.origin})` : \"\";\n const hopLabel = entry.hop > 0 ? ` _(hop ${entry.hop}, ${entry.relationDirection === \"outgoing\" ? \"→\" : \"←\"} ${entry.relationType})_` : \"\";\n lines.push(`- ${id}${entry.name}${scoreLabel}${flagsLabel}${originLabel}${hopLabel}`);\n }\n lines.push(\"\");\n }\n\n lines.push(\"## Supporting context\");\n lines.push(\"_These entries add implementation detail, history, and neighboring domain context._\");\n lines.push(\"\");\n\n if (byCollection.size === 0) {\n lines.push(\"_No supporting context matched yet. Open the binding governance entries first._\");\n lines.push(\"\");\n } else {\n for (const [collName, entries] of byCollection) {\n lines.push(`### ${collName} (${entries.length})${epistemicCollectionHint(collName)}`);\n for (const e of entries) {\n const arrow = e.relationDirection === \"outgoing\" ? \"→\" : \"←\";\n const id = e.entryId ? `**${e.entryId}:** ` : \"\";\n const scoreLabel = typeof e.score === \"number\" ? ` ${e.score}` : \"\";\n const flagsLabel = e.scoreFlags?.length ? ` [${e.scoreFlags.join(\", \")}]` : \"\";\n const originLabel = e.origin ? ` (origin: ${e.origin})` : \"\";\n const hopLabel = e.hop > 0 ? ` _(hop ${e.hop}, ${arrow} ${e.relationType})_` : \"\";\n lines.push(`- ${id}${e.name}${scoreLabel}${flagsLabel}${originLabel}${hopLabel}`);\n }\n lines.push(\"\");\n }\n }\n\n lines.push(`_Use \\`entries action=get\\` for full details on any entry._`);\n\n const taskEntries = [...result.steeringContext, ...result.supportingContext].map((e) => ({\n entryId: e.entryId ?? String(Math.random()),\n name: e.name,\n collectionName: e.collectionName,\n }));\n\n return {\n content: [{ type: \"text\" as const, text: lines.join(\"\\n\") }],\n structuredContent: success(\n `Loaded ${result.totalFound} task constraints and related entries (${result.confidence} confidence, ${strategy} strategy).`,\n {\n entries: taskEntries,\n totalFound: result.totalFound,\n confidence: result.confidence,\n groundingStatus: result.groundingStatus,\n strategy,\n bindingGovernance: result.bindingGovernance,\n steeringContext: result.steeringContext.map((entry) => ({\n entryId: entry.entryId ?? null,\n name: entry.name,\n collectionName: entry.collectionName,\n relationType: entry.relationType,\n relationDirection: entry.relationDirection,\n hop: entry.hop,\n score: entry.score,\n scoreFlags: entry.scoreFlags,\n preview: entry.preview,\n origin: entry.origin,\n })),\n supportingContext: result.supportingContext.map((entry) => ({\n entryId: entry.entryId ?? null,\n name: entry.name,\n collectionName: entry.collectionName,\n relationType: entry.relationType,\n relationDirection: entry.relationDirection,\n hop: entry.hop,\n score: entry.score,\n scoreFlags: entry.scoreFlags,\n preview: entry.preview,\n origin: entry.origin,\n })),\n },\n ),\n };\n }\n\n // Entry mode: traverse the knowledge graph around a specific entry\n await server.sendLoggingMessage({\n level: \"info\",\n data: `Gathering context for ${entryId} (depth: ${maxHops})...`,\n logger: \"product-brain\",\n });\n\n const result = await kernelQuery<GatherResult>(\"chain.gatherContext\", { entryId, maxHops });\n\n if (!result?.root) {\n return notFoundResult(entryId!, `Entry '${entryId}' not found. Try search to find the right ID.`);\n }\n\n if (result.related.length === 0) {\n const recorded = recordGap({ query: result.root.entryId, tool: \"context\", action: \"gather\", gapType: \"context_entry_isolated\" });\n if (recorded) {\n getWorkspaceId()\n .then((wsId) => trackKnowledgeGap(wsId, { query: result.root.entryId, tool: \"context\", action: \"gather\", gap_type: \"context_entry_isolated\" }))\n .catch(() => {});\n }\n\n return {\n content: [{\n type: \"text\" as const,\n text: `# Context for ${result.root.entryId}: ${result.root.name}\\n\\n` +\n `_No relations found._ This entry is not yet connected to the knowledge graph.\\n\\n` +\n `Use \\`graph action=suggest\\` to discover potential connections, or \\`relations action=create\\` to link manually.`,\n }],\n structuredContent: success(\n `No relations found for ${result.root.entryId}. Entry not yet connected.`,\n { root: result.root, related: [], totalRelations: 0 },\n [{ tool: \"graph\", description: \"Discover connections\", parameters: { action: \"suggest\", entryId: result.root.entryId } }],\n ),\n };\n }\n\n const byCollection = new Map<string, typeof result.related>();\n for (const entry of result.related) {\n const key = entry.collectionName;\n if (!byCollection.has(key)) byCollection.set(key, []);\n byCollection.get(key)!.push(entry);\n }\n\n const lines: string[] = [\n `# Context for ${result.root.entryId}: ${result.root.name}`,\n `_${result.totalRelations} related entries across ${byCollection.size} collections (${result.hopsTraversed} hops traversed)_`,\n \"\",\n ];\n\n for (const [collName, entries] of byCollection) {\n lines.push(`## ${collName} (${entries.length})${epistemicCollectionHint(collName)}`);\n for (const e of entries) {\n const arrow = e.relationDirection === \"outgoing\" ? \"\\u2192\" : \"\\u2190\";\n const hopLabel = e.hop > 1 ? ` (hop ${e.hop})` : \"\";\n const id = e.entryId ? `${e.entryId}: ` : \"\";\n lines.push(`- ${arrow} **${e.relationType}** ${id}${e.name}${hopLabel}`);\n }\n lines.push(\"\");\n }\n\n const rootId = result.root.entryId ?? \"root\";\n const nodes = [\n { id: rootId, name: result.root.name, collectionName: \"\" },\n ...result.related.map((e) => ({\n id: e.entryId ?? String(Math.random()),\n name: e.name,\n collectionName: e.collectionName,\n })),\n ];\n const edges = result.related\n .filter((e) => e.entryId)\n .map((e) => ({\n source: rootId,\n target: e.entryId!,\n type: e.relationType,\n }));\n\n return {\n content: [{ type: \"text\" as const, text: lines.join(\"\\n\") }],\n structuredContent: success(\n `Gathered ${result.totalRelations} related entries for ${result.root.entryId} (${result.hopsTraversed} hops).`,\n { nodes, edges, root: result.root, totalRelations: result.totalRelations },\n ),\n };\n}\n\nasync function handleJourneyGather(\n server: McpServer,\n mapEntryId: string,\n maxHops: number,\n maxResults: number,\n) {\n await server.sendLoggingMessage({\n level: \"info\",\n data: `Loading journey context for map ${mapEntryId}...`,\n logger: \"product-brain\",\n });\n\n const result = await kernelQuery<JourneyGatherResult | null>(\"chain.journeyAwareGatherContext\", {\n mapEntryId,\n maxHops,\n maxResults,\n });\n\n if (!result) {\n return notFoundResult(\n mapEntryId,\n `Journey map '${mapEntryId}' not found or has no slot data. Verify the map entry ID.`,\n \"Verify the map entry ID is correct.\",\n );\n }\n\n if (result.stages.length === 0 || result.seedCount === 0) {\n return {\n content: [{\n type: \"text\" as const,\n text: `# Journey Context: ${result.map.name}\\n\\n` +\n `_No ingredients found in this journey map._\\n\\n` +\n `Add journey steps via MCP: \\`map-slot action=add mapEntryId=\"${mapEntryId}\" slotId=\"...\" ingredientEntryId=\"...\"\\``,\n }],\n structuredContent: success(\n `Journey map ${result.map.name} has no ingredients.`,\n { map: result.map, stages: result.stages, context: [] },\n ),\n };\n }\n\n const lines: string[] = [\n `# Journey Context: ${result.map.name}`,\n `**Template:** ${result.map.templateName} | **Map ID:** ${result.map.entryId}`,\n `**Steps scanned:** ${result.seedCount}${result.truncated ? ` (capped at 10 — ${result.stages.flatMap((s) => s.ingredients).length} total ingredients)` : \"\"}`,\n `**Related knowledge:** ${result.totalFound} entries`,\n \"\",\n \"## Journey Stages\",\n ];\n\n for (const stage of result.stages) {\n const ingredientList = stage.ingredients.length === 0\n ? \"_empty_\"\n : stage.ingredients.map((i) => `${i.entryId}: ${i.name}`).join(\", \");\n lines.push(`- **${stage.label}**: ${ingredientList}`);\n }\n\n if (result.context.length > 0) {\n lines.push(\"\");\n lines.push(\"## Governance & Intelligence\");\n lines.push(`_Entries from the knowledge graph connected to journey steps:_`);\n lines.push(\"\");\n\n const byCollection = new Map<string, ContextEntry[]>();\n for (const entry of result.context) {\n const key = entry.collectionName;\n if (!byCollection.has(key)) byCollection.set(key, []);\n byCollection.get(key)!.push(entry);\n }\n\n for (const [collName, entries] of byCollection) {\n lines.push(`### ${collName} (${entries.length})`);\n for (const e of entries) {\n const arrow = e.relationDirection === \"outgoing\" ? \"→\" : \"←\";\n const id = e.entryId ? `**${e.entryId}:** ` : \"\";\n const scoreLabel = typeof e.score === \"number\" ? ` ${e.score}` : \"\";\n lines.push(`- ${arrow} ${id}${e.name}${scoreLabel}`);\n }\n lines.push(\"\");\n }\n }\n\n lines.push(`_Use \\`entries action=get\\` for full details. Link governance to steps: \\`relations action=create\\`._`);\n\n return {\n content: [{ type: \"text\" as const, text: lines.join(\"\\n\") }],\n structuredContent: success(\n `Journey context for ${result.map.name}: ${result.totalFound} related entries across ${result.stages.length} stages.`,\n {\n map: result.map,\n stages: result.stages,\n context: result.context.map((e) => ({\n entryId: e.entryId ?? \"\",\n name: e.name,\n collectionName: e.collectionName,\n })),\n },\n ),\n };\n}\n\nasync function handleNeighborhood(entryId: string) {\n const result = await kernelQuery<NeighborhoodResult>(\"chain.getEntryNeighborhood\", { entryId, now: Date.now() });\n\n const lines: string[] = [`# Neighborhood: ${entryId}`, \"\"];\n\n if (result.blockingChain.length > 0) {\n lines.push(`## Blocking Chain (${result.blockingChain.length})`);\n lines.push(`_Entries this one blocks, downstream up to 3 hops:_`);\n for (const item of result.blockingChain) {\n const id = item.entryId ? `**${item.entryId}:** ` : \"\";\n lines.push(`- ${id}${item.name} [status: ${item.status ?? \"unknown\"}, hop ${item.hop}]`);\n }\n lines.push(\"\");\n }\n\n if (result.dependencyChain.length > 0) {\n lines.push(`## Dependency Chain (${result.dependencyChain.length})`);\n lines.push(`_Entries this one depends on or is blocked by:_`);\n for (const item of result.dependencyChain) {\n const id = item.entryId ? `**${item.entryId}:** ` : \"\";\n const unresolved = item.unresolvedFlag ? \" ⚠ unresolved\" : \"\";\n lines.push(`- ${id}${item.name} [${item.relationType ?? \"\"}${unresolved}]`);\n }\n lines.push(\"\");\n }\n\n if (result.parentContext) {\n const p = result.parentContext;\n const id = p.entryId ? `**${p.entryId}:** ` : \"\";\n lines.push(`## Parent Context`);\n lines.push(`- ${id}${p.name} — ${p.openCount} open, ${p.blockedCount} blocked sibling(s)`);\n lines.push(\"\");\n }\n\n if (result.relatedTensions.length > 0) {\n lines.push(`## Related Tensions (${result.relatedTensions.length})`);\n for (const item of result.relatedTensions) {\n const id = item.entryId ? `**${item.entryId}:** ` : \"\";\n lines.push(`- ${id}${item.name} [${item.relationType ?? \"\"}]`);\n }\n lines.push(\"\");\n }\n\n const signals: string[] = [];\n if (result.isolationSignal) signals.push(\"⚠ Isolated (< 2 relations)\");\n if (result.stalenessSignal?.isStale) {\n signals.push(`⚠ Stale (${result.stalenessSignal.daysSinceUpdate} days since update)`);\n }\n if (signals.length > 0) {\n lines.push(`## Signals`);\n for (const s of signals) lines.push(`- ${s}`);\n lines.push(\"\");\n }\n\n const isEmpty = result.blockingChain.length === 0 && result.dependencyChain.length === 0\n && !result.parentContext && result.relatedTensions.length === 0;\n\n if (isEmpty) {\n lines.push(`_No neighborhood data found. Entry may not exist or has no graph connections._`);\n lines.push(`Use \\`graph action=suggest\\` to discover potential connections.`);\n }\n\n return {\n content: [{ type: \"text\" as const, text: lines.join(\"\\n\") }],\n structuredContent: success(\n `Neighborhood for ${entryId}: ${result.blockingChain.length} blocking, ${result.dependencyChain.length} dependencies, ${result.relatedTensions.length} tensions.`,\n result,\n isEmpty ? [{ tool: \"graph\", description: \"Discover connections\", parameters: { action: \"suggest\", entryId } }] : undefined,\n ),\n };\n}\n\nasync function handleBuild(server: McpServer, entryId: string, maxHops: number) {\n requireActiveSession();\n\n await server.sendLoggingMessage({\n level: \"info\",\n data: `Assembling build context for ${entryId}...`,\n logger: \"product-brain\",\n });\n\n const result = await kernelQuery<BuildResult>(\"chain.assembleBuildContext\", {\n entryId,\n maxHops,\n });\n\n const { entry, relatedByCollection, businessRules, glossaryTerms, chainRefs, contextTruncated } = result;\n\n const lines: string[] = [\n `# Build Context: ${entry.name}`,\n `**Entry:** ${entry.entryId ?? entry.name} [${entry.collectionSlug}]`,\n `**Status:** ${entry.status}`,\n \"\",\n ];\n\n if (Object.keys(entry.data).length > 0) {\n lines.push(\"## Entry Data\");\n for (const [key, val] of Object.entries(entry.data)) {\n const str = typeof val === \"string\" ? val : JSON.stringify(val);\n if (str.length > 200) {\n lines.push(`- **${key}:** ${str.slice(0, 200)}...`);\n } else {\n lines.push(`- **${key}:** ${str}`);\n }\n }\n lines.push(\"\");\n }\n\n if (businessRules.length > 0) {\n lines.push(\"## Business Rules to Honor\");\n for (const r of businessRules) {\n const id = r.entryId ?? r.name;\n lines.push(`- **${id}:** ${r.name}`);\n if (r.description) lines.push(` ${r.description.slice(0, 150)}${r.description.length > 150 ? \"...\" : \"\"}`);\n }\n lines.push(\"\");\n }\n\n if (glossaryTerms.length > 0) {\n lines.push(\"## Glossary Terms\");\n for (const t of glossaryTerms.slice(0, 15)) {\n const id = t.entryId ?? t.name;\n lines.push(`- **${id}:** ${t.name}`);\n if (t.definition) lines.push(` ${t.definition.slice(0, 120)}${t.definition.length > 120 ? \"...\" : \"\"}`);\n }\n if (glossaryTerms.length > 15) lines.push(` _...and ${glossaryTerms.length - 15} more_`);\n lines.push(\"\");\n }\n\n const relatedCount = Object.values(relatedByCollection).reduce((sum, arr) => sum + arr.length, 0);\n if (relatedCount > 0) {\n lines.push(\"## Related Entries\");\n for (const [coll, entries] of Object.entries(relatedByCollection)) {\n lines.push(`### ${coll} (${entries.length})`);\n for (const e of entries.slice(0, 5)) {\n lines.push(`- ${e.entryId ?? e.name}: ${e.name} [${e.relationType}]`);\n }\n if (entries.length > 5) lines.push(` _...and ${entries.length - 5} more_`);\n }\n lines.push(\"\");\n }\n\n lines.push(\"## Chain Refs to Consult\");\n lines.push(chainRefs.slice(0, 15).map((r: string) => `- ${r}`).join(\"\\n\"));\n\n if (contextTruncated) {\n lines.push(\"\");\n lines.push(\"_Context was truncated (limits: 50 related, 20 rules, 30 glossary). Use entries action=get for full details._\");\n }\n\n return {\n content: [{ type: \"text\" as const, text: annotateStaleNames(lines.join(\"\\n\")) }],\n structuredContent: success(\n `Build context for ${entry.name}: ${relatedCount} related, ${businessRules.length} rules, ${glossaryTerms.length} terms.`,\n { entry, relatedByCollection, businessRulesCount: businessRules.length, glossaryTermsCount: glossaryTerms.length, contextTruncated },\n ),\n };\n}\n\n// ─── Cross-Cut (BET-239, Slice 3) ───────────────────────────────────────────\n\ninterface StructuralAggregationItem {\n entryId: string | null;\n name: string;\n relatedEntryId: string | null;\n relatedName: string;\n relatedCollectionSlug: string;\n}\n\ninterface StructuralAggregationResult {\n groups: Record<string, StructuralAggregationItem[]>;\n totalCount: number;\n truncated: boolean;\n}\n\nasync function handleCrossCut(relationType: string) {\n const result = await kernelQuery<StructuralAggregationResult>(\"chain.structuralAggregation\", {\n relationType,\n });\n\n const groupKeys = Object.keys(result.groups);\n\n if (result.totalCount === 0) {\n return {\n content: [{\n type: \"text\" as const,\n text: `# Cross-Cut: ${relationType}\\n\\nNo relations of type '${relationType}' found in this workspace.`,\n }],\n structuredContent: success(\n `No '${relationType}' relations found.`,\n { groups: {}, totalCount: 0, truncated: false },\n ),\n };\n }\n\n const lines: string[] = [\n `# Cross-Cut: ${relationType}`,\n `_${result.totalCount} relations across ${groupKeys.length} source collection${groupKeys.length === 1 ? \"\" : \"s\"}${result.truncated ? \" (TRUNCATED — more relations exist)\" : \"\"}_`,\n \"\",\n ];\n\n for (const [sourceSlug, items] of Object.entries(result.groups)) {\n lines.push(`## ${sourceSlug} (${items.length})`);\n for (const item of items) {\n const fromId = item.entryId ? `**${item.entryId}:** ` : \"\";\n const toId = item.relatedEntryId ?? item.relatedName;\n lines.push(`- ${fromId}${item.name} → ${toId} [${item.relatedCollectionSlug}]`);\n }\n lines.push(\"\");\n }\n\n if (result.truncated) {\n lines.push(\"_Results truncated at 500 relations. Filter by collection or use a more specific relation type._\");\n }\n\n return {\n content: [{ type: \"text\" as const, text: lines.join(\"\\n\") }],\n structuredContent: success(\n `${result.totalCount} '${relationType}' relations across ${groupKeys.length} collections.${result.truncated ? \" Truncated.\" : \"\"}`,\n result,\n ),\n };\n}\n\n// ─── Deep Chain Walk (BET-239, Slice 2) ────────────────────────────────────────\n\ninterface ChainWalkNode {\n entryId: string | null;\n name: string;\n collectionSlug: string | null;\n depth: number;\n parentEntryId: string | null;\n}\n\ninterface ChainWalkEdge {\n from: string;\n to: string;\n type: string;\n}\n\ninterface ChainWalkCycle {\n path: string[];\n}\n\ninterface ChainWalkResult {\n nodes: ChainWalkNode[];\n edges: ChainWalkEdge[];\n cycles: ChainWalkCycle[];\n totalNodes: number;\n truncated: boolean;\n snapshotWarning: boolean;\n error?: string;\n}\n\nasync function handleChainWalk(\n entryId: string,\n direction: \"outgoing\" | \"incoming\",\n maxHops: number,\n relationType?: string,\n) {\n // Clamp maxHops for chain action to 1-4\n const clampedHops = Math.max(1, Math.min(4, maxHops));\n\n const result = await kernelQuery<ChainWalkResult>(\"chain.deepChainWalk\", {\n entryId,\n direction,\n maxHops: clampedHops,\n ...(relationType ? { relationType } : {}),\n });\n\n if (result.error) {\n return notFoundResult(entryId, result.error);\n }\n\n if (result.totalNodes <= 1) {\n return {\n content: [{\n type: \"text\" as const,\n text: `# Chain Walk: ${entryId}\\n\\n` +\n `_No ${direction} relations found${relationType ? ` of type '${relationType}'` : \"\"}._\\n\\n` +\n `Try \\`context action=chain entryId=\"${entryId}\" direction=\"${direction === \"outgoing\" ? \"incoming\" : \"outgoing\"}\"\\` ` +\n `or remove the relationType filter.`,\n }],\n structuredContent: success(\n `No ${direction} relations found for ${entryId}.`,\n result,\n ),\n };\n }\n\n const lines: string[] = [\n `# Chain Walk: ${entryId}`,\n `**Direction:** ${direction} | **Depth:** ${clampedHops}${relationType ? ` | **Type filter:** ${relationType}` : \"\"}`,\n `**Nodes:** ${result.totalNodes}${result.truncated ? \" (TRUNCATED at 100)\" : \"\"} | **Edges:** ${result.edges.length} | **Cycles:** ${result.cycles.length}`,\n \"\",\n ];\n\n // Render as tree grouped by depth\n const maxDepth = Math.max(...result.nodes.map((n) => n.depth));\n for (let d = 0; d <= maxDepth; d++) {\n const atDepth = result.nodes.filter((n) => n.depth === d);\n if (atDepth.length === 0) continue;\n\n const label = d === 0 ? \"Root\" : `Depth ${d}`;\n lines.push(`## ${label} (${atDepth.length})`);\n for (const node of atDepth) {\n const indent = \" \".repeat(d);\n const id = node.entryId ? `**${node.entryId}:** ` : \"\";\n const collection = node.collectionSlug ? ` [${node.collectionSlug}]` : \"\";\n const parent = node.parentEntryId ? ` (via ${node.parentEntryId})` : \"\";\n lines.push(`${indent}- ${id}${node.name}${collection}${parent}`);\n }\n lines.push(\"\");\n }\n\n // Show cycles if any\n if (result.cycles.length > 0) {\n lines.push(\"## Cycles Detected\");\n for (const cycle of result.cycles) {\n lines.push(`- ${cycle.path.join(\" -> \")}`);\n }\n lines.push(\"\");\n }\n\n // Snapshot warning\n if (result.snapshotWarning) {\n lines.push(\"_Note: This traversal spans multiple reads (Convex action). Data consistency is not guaranteed across hops (TEN-1029)._\");\n }\n\n if (result.truncated) {\n lines.push(\"_Results truncated at 100 nodes. Narrow with relationType filter or reduce maxHops._\");\n }\n\n return {\n content: [{ type: \"text\" as const, text: lines.join(\"\\n\") }],\n structuredContent: success(\n `Chain walk for ${entryId}: ${result.totalNodes} nodes, ${result.edges.length} edges, ${result.cycles.length} cycles (${direction}, depth ${clampedHops}).`,\n result,\n ),\n };\n}\n\n// ─── Changes (BET-239, FEAT-778) ────────────────────────────────────────────\n\ninterface ChangeDetectionResult {\n entries: Array<{ entryId: string | null; name: string; collectionSlug: string; updatedAt: number }>;\n relations: Array<{ fromEntryId: string | null; toEntryId: string | null; type: string; createdAt: number }>;\n counts: Record<string, number>;\n truncated: boolean;\n}\n\nasync function handleChanges(since: string) {\n const sinceMs = Date.parse(since);\n if (isNaN(sinceMs)) {\n return validationResult(`Invalid 'since' timestamp: '${since}'. Use ISO 8601 format (e.g. '2026-03-24T00:00:00Z').`);\n }\n\n const result = await kernelQuery<ChangeDetectionResult>(\"chain.changeDetection\", { since: sinceMs });\n\n const totalEntries = result.entries.length;\n const totalRelations = result.relations.length;\n\n if (totalEntries === 0 && totalRelations === 0) {\n return {\n content: [{\n type: \"text\" as const,\n text: `# Changes since ${since}\\n\\nNo entries modified or relations created since this timestamp.`,\n }],\n structuredContent: success(\n `No changes detected since ${since}.`,\n { entries: [], relations: [], counts: {}, truncated: false },\n ),\n };\n }\n\n const lines: string[] = [\n `# Changes since ${since}`,\n `_${totalEntries} entries modified, ${totalRelations} relations created${result.truncated ? \" (TRUNCATED — more changes exist)\" : \"\"}_`,\n \"\",\n ];\n\n // Entries grouped by collection\n if (totalEntries > 0) {\n lines.push(\"## Modified Entries\");\n const sortedCounts = Object.entries(result.counts).sort((a, b) => b[1] - a[1]);\n for (const [slug, count] of sortedCounts) {\n lines.push(`### ${slug} (${count})`);\n const slugEntries = result.entries.filter((e) => e.collectionSlug === slug);\n for (const e of slugEntries) {\n const id = e.entryId ? `**${e.entryId}:** ` : \"\";\n const ago = formatTimeAgo(e.updatedAt);\n lines.push(`- ${id}${e.name} _(${ago})_`);\n }\n lines.push(\"\");\n }\n }\n\n // Relations\n if (totalRelations > 0) {\n lines.push(\"## New Relations\");\n for (const r of result.relations) {\n const from = r.fromEntryId ?? \"?\";\n const to = r.toEntryId ?? \"?\";\n const ago = formatTimeAgo(r.createdAt);\n lines.push(`- ${from} **${r.type}** ${to} _(${ago})_`);\n }\n lines.push(\"\");\n }\n\n if (result.truncated) {\n lines.push(\"_Results truncated at 200 entries. Use a more recent timestamp to narrow the window._\");\n }\n\n return {\n content: [{ type: \"text\" as const, text: lines.join(\"\\n\") }],\n structuredContent: success(\n `${totalEntries} entries modified, ${totalRelations} relations created since ${since}.${result.truncated ? \" Truncated.\" : \"\"}`,\n result,\n ),\n };\n}\n\n// ─── Incremental (BET-239 E4) ────────────────────────────────────────────\n\ninterface IncrementalResult {\n newEntries: Array<{ entryId: string | null; name: string; collectionSlug: string; updatedAt: number }>;\n counts: Record<string, number>;\n relations: Array<{ fromEntryId: string | null; toEntryId: string | null; type: string; createdAt: number }>;\n truncated: boolean;\n previousRunTimestamp: number | null;\n isFirstRun: boolean;\n}\n\nasync function handleIncremental(skill: string) {\n const result = await kernelQuery<IncrementalResult>(\"chain.incrementalChanges\", { skill });\n\n const totalEntries = result.newEntries.length;\n\n // Record the brief run so the next call sees an updated \"since last brief\" timestamp.\n // Fire-and-forget: recording failure should not block the response.\n const surfacedIds = result.newEntries\n .map((e) => e.entryId)\n .filter((id): id is string => id !== null);\n kernelMutation(\"chain.recordBriefRun\", {\n skill,\n entriesSurfaced: surfacedIds,\n timestamp: Date.now(),\n }).catch(() => {\n // Best-effort — logging omitted to avoid noise. The next brief run\n // will simply re-surface the same entries.\n });\n\n if (totalEntries === 0 && !result.isFirstRun) {\n return {\n content: [{\n type: \"text\" as const,\n text: `# Incremental Brief — ${skill}\\n\\nNo new entries since last brief run (${formatTimeAgo(result.previousRunTimestamp!)}).`,\n }],\n structuredContent: success(\n `No new entries for skill '${skill}' since last brief.`,\n result,\n ),\n };\n }\n\n const lines: string[] = [\n `# Incremental Brief — ${skill}`,\n ];\n\n if (result.isFirstRun) {\n lines.push(\"_First run — showing all recent entries._\");\n } else {\n lines.push(`_Delta since last brief (${formatTimeAgo(result.previousRunTimestamp!)})_`);\n }\n\n lines.push(`_${totalEntries} new entries${result.truncated ? \" (TRUNCATED)\" : \"\"}_`);\n lines.push(\"\");\n\n if (totalEntries > 0) {\n lines.push(\"## New Entries\");\n\n // Group by collection\n const byCollection: Record<string, typeof result.newEntries> = {};\n for (const e of result.newEntries) {\n const slug = e.collectionSlug;\n if (!byCollection[slug]) byCollection[slug] = [];\n byCollection[slug].push(e);\n }\n\n const sortedSlugs = Object.entries(byCollection)\n .sort((a, b) => b[1].length - a[1].length)\n .map(([slug]) => slug);\n\n for (const slug of sortedSlugs) {\n const entries = byCollection[slug];\n lines.push(`### ${slug} (${entries.length})`);\n for (const e of entries) {\n const id = e.entryId ? `**${e.entryId}:** ` : \"\";\n const ago = formatTimeAgo(e.updatedAt);\n lines.push(`- ${id}${e.name} _(${ago})_`);\n }\n lines.push(\"\");\n }\n }\n\n if (result.truncated) {\n lines.push(\"_Results truncated at 200 entries. Run more frequently to stay within the cap._\");\n }\n\n return {\n content: [{ type: \"text\" as const, text: lines.join(\"\\n\") }],\n structuredContent: success(\n `${totalEntries} new entries for skill '${skill}'${result.isFirstRun ? \" (first run)\" : \"\"}.${result.truncated ? \" Truncated.\" : \"\"}`,\n result,\n ),\n };\n}\n\n// ─── Compound Brief (BET-239 E6) ────────────────────────────────────────────\n\nasync function handleBrief(briefType: \"steering\" | \"confidence\" | \"delta\", sinceMs?: number) {\n const args: Record<string, unknown> = { type: briefType };\n if (sinceMs !== undefined) args.since = sinceMs;\n\n const result = await kernelQuery<any>(\"chain.compoundQuery\", args);\n\n if (briefType === \"steering\") {\n return formatSteeringBrief(result);\n }\n\n if (briefType === \"confidence\") {\n return formatConfidencePass(result);\n }\n\n if (briefType === \"delta\") {\n return formatDeltaSync(result);\n }\n\n return validationResult(`Unknown briefType: ${briefType}`);\n}\n\nfunction formatSteeringBrief(result: any) {\n const changes = result.changes;\n const delta = result.delta;\n const readiness = result.readiness;\n\n const lines: string[] = [\n \"# Steering Brief\",\n \"\",\n `## Changes (last 7 days)`,\n `_${changes.entries.length} entries modified, ${changes.relations.length} relations created${changes.truncated ? \" (TRUNCATED)\" : \"\"}_`,\n \"\",\n ];\n\n // Entry counts by collection\n if (Object.keys(changes.counts).length > 0) {\n const sortedCounts = Object.entries(changes.counts as Record<string, number>).sort((a, b) => b[1] - a[1]);\n for (const [slug, count] of sortedCounts) {\n lines.push(`- **${slug}:** ${count}`);\n }\n lines.push(\"\");\n }\n\n // Structural summary\n lines.push(\"## Structure\");\n for (const [relType, agg] of Object.entries(result.structure as Record<string, any>)) {\n const groupCount = Object.keys(agg.groups).length;\n lines.push(`- **${relType}:** ${agg.totalCount} relations across ${groupCount} collection groups${agg.truncated ? \" (TRUNCATED)\" : \"\"}`);\n }\n lines.push(\"\");\n\n // Delta\n lines.push(\"## Incremental Delta (steering skill)\");\n if (delta.isFirstRun) {\n lines.push(\"_First run — all recent entries included._\");\n }\n lines.push(`${delta.newEntries.length} new entries since last steering brief${delta.truncated ? \" (TRUNCATED)\" : \"\"}`);\n lines.push(\"\");\n\n // Readiness\n lines.push(\"## Workspace Readiness\");\n lines.push(`Score: **${readiness.score}%** (${readiness.passedChecks}/${readiness.totalChecks} checks passed)`);\n if (readiness.gaps.length > 0) {\n lines.push(\"\");\n lines.push(\"**Gaps:**\");\n for (const gap of readiness.gaps.slice(0, 5)) {\n lines.push(`- ${gap.label}: ${gap.current}/${gap.required}${gap.guidance ? ` — ${gap.guidance}` : \"\"}`);\n }\n }\n lines.push(\"\");\n\n // BET-240 S6: trust-awareness note — scoring kernel applies implicit trust weighting\n lines.push(\"## Trust\");\n lines.push(\"_Scoring kernel applies trust weighting: human=1.0, agent+verified=0.7, agent+unverified=0.56, external+unverified=0.64. Scores in context/gather reflect this. Use `orient -b` for workspace trust metrics._\");\n lines.push(\"\");\n\n if (result.snapshotWarning) {\n lines.push(\"_Note: Compound query spans multiple reads. Data consistency is not guaranteed across components (TEN-1029)._\");\n }\n\n return {\n content: [{ type: \"text\" as const, text: lines.join(\"\\n\") }],\n structuredContent: success(\n `Steering brief: ${changes.entries.length} changes, ${delta.newEntries.length} new entries, ${readiness.score}% readiness.`,\n { ...result, trustFilterActive: true },\n ),\n };\n}\n\nfunction formatConfidencePass(result: any) {\n const changes = result.changes;\n\n const lines: string[] = [\n \"# Confidence Pass\",\n \"\",\n `## Changes (last 7 days)`,\n `_${changes.entries.length} entries modified${changes.truncated ? \" (TRUNCATED)\" : \"\"}_`,\n \"\",\n ];\n\n // Active bets\n lines.push(`## Active Bets (${result.betCount})`);\n if (result.activeBets.length > 0) {\n for (const bet of result.activeBets) {\n const id = bet.entryId ? `**${bet.entryId}:** ` : \"\";\n lines.push(`- ${id}${bet.name} [${bet.status}]`);\n }\n } else {\n lines.push(\"_No active bets._\");\n }\n lines.push(\"\");\n\n // Active tensions\n lines.push(`## Active Tensions (${result.tensionCount})`);\n if (result.activeTensions.length > 0) {\n for (const tension of result.activeTensions) {\n const id = tension.entryId ? `**${tension.entryId}:** ` : \"\";\n lines.push(`- ${id}${tension.name}`);\n }\n } else {\n lines.push(\"_No active tensions._\");\n }\n lines.push(\"\");\n\n // BET-240 S6: trust-awareness note for confidence pass\n lines.push(\"## Trust\");\n lines.push(\"_Trust-weighted scoring active: agent-origin and unverified entries receive lower confidence scores (human=1.0, agent+verified=0.7, agent+unverified=0.56). Use `entries action=get` to inspect individual entry origin/verification. Use `orient -b` for workspace trust metrics._\");\n lines.push(\"\");\n\n if (result.snapshotWarning) {\n lines.push(\"_Note: Compound query spans multiple reads. Data consistency is not guaranteed across components (TEN-1029)._\");\n }\n\n return {\n content: [{ type: \"text\" as const, text: lines.join(\"\\n\") }],\n structuredContent: success(\n `Confidence pass: ${changes.entries.length} changes, ${result.betCount} active bets, ${result.tensionCount} active tensions.`,\n { ...result, trustFilterActive: true },\n ),\n };\n}\n\nfunction formatDeltaSync(result: any) {\n const changes = result.changes;\n const sinceDate = new Date(result.since).toISOString();\n\n const lines: string[] = [\n `# Delta Sync since ${sinceDate}`,\n `_${changes.entries.length} entries modified, ${changes.relations.length} relations created${changes.truncated ? \" (TRUNCATED)\" : \"\"}_`,\n \"\",\n ];\n\n if (changes.entries.length > 0) {\n lines.push(\"## Modified Entries\");\n const sortedCounts = Object.entries(changes.counts as Record<string, number>).sort((a, b) => b[1] - a[1]);\n for (const [slug, count] of sortedCounts) {\n lines.push(`### ${slug} (${count})`);\n const slugEntries = changes.entries.filter((e: any) => e.collectionSlug === slug);\n for (const e of slugEntries) {\n const id = e.entryId ? `**${e.entryId}:** ` : \"\";\n const ago = formatTimeAgo(e.updatedAt);\n lines.push(`- ${id}${e.name} _(${ago})_`);\n }\n lines.push(\"\");\n }\n }\n\n if (changes.relations.length > 0) {\n lines.push(\"## New Relations\");\n for (const r of changes.relations) {\n const from = r.fromEntryId ?? \"?\";\n const to = r.toEntryId ?? \"?\";\n const ago = formatTimeAgo(r.createdAt);\n lines.push(`- ${from} **${r.type}** ${to} _(${ago})_`);\n }\n lines.push(\"\");\n }\n\n if (result.snapshotWarning) {\n lines.push(\"_Note: Compound query spans multiple reads. Data consistency is not guaranteed across components (TEN-1029)._\");\n }\n\n return {\n content: [{ type: \"text\" as const, text: lines.join(\"\\n\") }],\n structuredContent: success(\n `Delta sync since ${sinceDate}: ${changes.entries.length} entries, ${changes.relations.length} relations.${changes.truncated ? \" Truncated.\" : \"\"}`,\n result,\n ),\n };\n}\n\n/** Format a timestamp as a human-readable relative time. */\nfunction formatTimeAgo(ms: number): string {\n const diff = Date.now() - ms;\n if (diff < 60_000) return \"just now\";\n if (diff < 3_600_000) return `${Math.floor(diff / 60_000)}m ago`;\n if (diff < 86_400_000) return `${Math.floor(diff / 3_600_000)}h ago`;\n return `${Math.floor(diff / 86_400_000)}d ago`;\n}\n","/**\n * Collections compound tool — list, create, update.\n * Consolidates list-collections, create-collection, update-collection into one tool.\n */\n\nimport { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { z } from \"zod\";\nimport { kernelQuery, kernelMutation, requireWriteAccess, getAgentSessionId, runWithToolContext } from \"../client.js\";\nimport { trackWriteTool } from \"../tool-surface.js\";\nimport { thinWrapper, success, failureResult, validationResult, successResult, parseOrFail, unknownAction } from \"../envelope.js\";\n\ninterface CollectionField {\n key: string;\n type: string;\n required?: boolean;\n searchable?: boolean;\n displayHint?: 'hero' | 'badge' | 'meta' | 'section' | 'hidden' | 'inline-meta';\n zone?: 'header' | 'body' | 'meta';\n colorMap?: Record<string, string>;\n accentSource?: boolean;\n iconMap?: Record<string, string>;\n /** BET-196: Content constraints — maximum character length for field values. */\n maxLength?: number;\n /** BET-196: Content constraints — minimum character length for field values. */\n minLength?: number;\n}\n\ninterface CollectionRecord {\n slug: string;\n name: string;\n description?: string;\n purpose?: string;\n navGroup?: string;\n icon?: string;\n fields: CollectionField[];\n}\n\nconst COLLECTIONS_ACTIONS = [\"list\", \"create\", \"update\", \"describe\", \"audit\", \"export\"] as const;\n\nconst qualityCriterionSchema = z.object({\n field: z.string().describe(\"Entry data field key this criterion applies to, e.g. 'description', 'owner'\"),\n rule: z.enum(['required', 'min_length', 'pattern'])\n .describe(\"'required': field must be non-empty (blocks commit). 'min_length': minimum string length (warns). 'pattern': regex match (warns).\"),\n value: z.string().optional()\n .describe(\"For min_length: the minimum length as a string integer. For pattern: the regex string. Unused for 'required'.\"),\n});\n\nconst fieldSchema = z.object({\n key: z.string().describe(\"Field key, e.g. 'description', 'severity', 'status'\"),\n label: z.string().describe(\"Display label, e.g. 'Description', 'Severity'\"),\n type: z.string().describe(\"Field type: 'string', 'select', 'array', 'number', 'boolean'\"),\n required: z.boolean().optional().describe(\"Whether this field is required\"),\n options: z.array(z.string()).optional().describe(\"Options for 'select' type fields\"),\n searchable: z.boolean().optional().describe(\"Whether this field is included in full-text search\"),\n displayHint: z.enum(['hero', 'badge', 'meta', 'section', 'hidden', 'inline-meta']).optional()\n .describe(\"V2 rendering hint: how the field should be displayed in Cortex\"),\n zone: z.enum(['header', 'body', 'meta']).optional()\n .describe(\"V2 layout zone: where the field appears in the entry view\"),\n colorMap: z.record(z.string()).optional()\n .describe(\"V2 value-to-semantic-color mapping, e.g. { critical: 'danger', low: 'success' }\"),\n accentSource: z.boolean().optional()\n .describe(\"ENT-61: when true, this field's colorMap value drives the card-level accent styling\"),\n iconMap: z.record(z.string(), z.string()).optional()\n .describe(\"ENT-61: maps field values to icons (emoji/symbol), prepended to badge text\"),\n helpText: z.string().optional()\n .describe(\"Help text shown in editors and describe output\"),\n optionDescriptions: z.record(z.string()).optional()\n .describe(\"Per-option guidance for select fields\"),\n semanticRole: z.enum(['problem', 'appetite', 'elements', 'architecture', 'done_when', 'risks', 'exclusions']).optional()\n .describe(\"BET-136: Semantic role for schema-driven consumers — enables field-key-independent validation and rendering\"),\n maxLength: z.number().optional()\n .describe(\"BET-196: Maximum character length for field values. Three-tier resolution: explicit > displayHint > type fallback.\"),\n minLength: z.number().optional()\n .describe(\"BET-196: Minimum character length for field values. Only explicit — no defaults.\"),\n});\n\nexport const collectionsSchema = z.object({\n action: z.enum(COLLECTIONS_ACTIONS).describe(\n \"'list': browse all collections. 'create': create a new collection. 'update': update an existing collection. 'describe': full documentation for one collection — fields, option guides, usage guidance, examples. 'audit': health report for all collections — missing classification, icon, displayHint coverage, and field schema gaps. 'export': full system_collection_definitions export with classification metadata (thinkingLayer, classificationPriority, classificationCheck, classificationSignals, governanceRole, timelineRole, canBeElementOf, descriptionFieldKey). Admin only.\",\n ),\n slug: z.string().optional().describe(\"URL-safe identifier for create/update, e.g. 'glossary', 'tech-debt'\"),\n name: z.string().optional().describe(\"Display name for create, or new name for update\"),\n description: z.string().optional().describe(\"What this collection is for\"),\n purpose: z.string().optional().describe(\"Why this collection exists — strategic reason\"),\n icon: z.string().optional().describe(\"Emoji icon for the collection\"),\n navGroup: z.enum([\"daily\", \"strategic\", \"governance\", \"reference\", \"collections\"]).optional()\n .describe(\"Sidebar placement: 'daily', 'strategic', 'governance', 'reference', 'collections'\"),\n fields: z.array(fieldSchema).optional()\n .describe(\"Field definitions for create, or replacement schema for update (replaces all fields)\"),\n defaultCanonicalKey: z.string().optional()\n .describe(\"ENT-62: The canonical_key entries in this collection default to (e.g. 'decision', 'insight'). Consumers read from collection doc; code map is fallback.\"),\n defaultWorkflowStatus: z.string().optional()\n .describe(\"ENT-67: Default workflowStatus for new entries. Must be in validWorkflowStatuses when set (e.g. 'hypothesis' for insights).\"),\n validWorkflowStatuses: z.array(z.string()).optional()\n .describe(\"ENT-65: The allowed workflowStatus values for entries in this collection. New entries are validated against this list. Empty array means no constraint.\"),\n classificationCheck: z.string().optional()\n .describe(\"ENT-65 FEAT-200: LLM decision-tree check for this collection (3–500 chars). Guides the classifier in routing entries here.\"),\n classificationPriority: z.number().optional()\n .describe(\"ENT-65 FEAT-200: Classifier priority (1–9, lower = higher priority). Used with classificationCheck to order the decision tree.\"),\n // FEAT-301 Slice 2: quality gate criteria and usage guidance.\n qualityCriteria: z.array(qualityCriterionSchema).optional()\n .describe(\"FEAT-257: Per-collection commit gate rules. 'required' rule hard-blocks commits on empty fields; 'min_length'/'pattern' rules warn. Pass an empty array to clear all criteria.\"),\n usageGuidance: z.string().optional()\n .describe(\"Plain-text guidance shown to agents and users: when to use this collection, when not to, and what makes a good entry.\"),\n});\n\nexport function registerCollectionsTools(server: McpServer): void {\n const tool = server.registerTool(\n \"collections\",\n {\n title: \"Collections\",\n description:\n \"Manage knowledge collections. Four actions:\\n\\n\" +\n \"- **list**: Browse all collections — glossary, business rules, tracking events, etc. \" +\n \"Returns slug, name, description, and field schema. Use before capture to see what exists.\\n\" +\n \"- **describe**: Full documentation for a single collection. Returns field help text, \" +\n \"option decision guides, usage guidance, examples, and cross-references. Use when you need to \" +\n \"understand a collection's purpose, field semantics, or option values.\\n\" +\n \"- **create**: Create a new collection. Provide slug, name, and field schema. \" +\n \"Use when setting up a workspace or tracking a new type of knowledge.\\n\" +\n \"- **update**: Update an existing collection's name, description, purpose, icon, navGroup, or fields. \" +\n \"Only provide the fields you want to change.\\n\" +\n \"- **audit**: Health report for all workspace collections. Checks classification metadata, icon presence, \" +\n \"displayHint coverage per field, and field schema gaps vs system definitions. \" +\n \"Returns total collections, count with issues, and per-collection issue list.\\n\" +\n \"- **export**: Full system_collection_definitions export as JSON. Includes all classification metadata \" +\n \"(thinkingLayer, classificationPriority, classificationCheck, timelineRole, governanceRole, etc.). Admin only.\",\n inputSchema: collectionsSchema,\n annotations: { readOnlyHint: false, destructiveHint: true, openWorldHint: false },\n },\n thinWrapper(async (args) => {\n const parsed = parseOrFail(collectionsSchema, args);\n if (!parsed.ok) return parsed.result;\n\n const { action, slug, name, description, purpose, icon, navGroup, fields, defaultCanonicalKey, defaultWorkflowStatus, validWorkflowStatuses, classificationCheck, classificationPriority, qualityCriteria, usageGuidance } = parsed.data;\n\n return runWithToolContext({ tool: \"collections\", action }, async () => {\n if (action === \"list\") {\n return handleList();\n }\n\n if (action === \"describe\") {\n if (!slug) {\n return validationResult(\"slug is required when action is 'describe'.\");\n }\n return handleDescribe(slug);\n }\n\n if (action === \"create\") {\n if (!slug || !name || !fields || fields.length === 0) {\n return validationResult(\"slug, name, and fields are required when action is 'create'.\");\n }\n return handleCreate(slug, name, description, purpose, icon, navGroup ?? \"collections\", fields, { defaultCanonicalKey, defaultWorkflowStatus, validWorkflowStatuses, classificationCheck, classificationPriority });\n }\n\n if (action === \"update\") {\n if (!slug) {\n return validationResult(\"slug is required when action is 'update'.\");\n }\n const hasChanges = name || description || purpose || icon || navGroup || fields || defaultCanonicalKey !== undefined || defaultWorkflowStatus !== undefined || validWorkflowStatuses !== undefined || classificationCheck !== undefined || classificationPriority !== undefined || qualityCriteria !== undefined || usageGuidance !== undefined;\n if (!hasChanges) {\n return validationResult(\"Provide at least one field to update (name, description, purpose, icon, navGroup, fields, defaultCanonicalKey, defaultWorkflowStatus, validWorkflowStatuses, classificationCheck, classificationPriority, qualityCriteria, or usageGuidance).\");\n }\n return handleUpdate(slug, name, description, purpose, icon, navGroup, fields, { defaultCanonicalKey, defaultWorkflowStatus, validWorkflowStatuses, classificationCheck, classificationPriority, qualityCriteria, usageGuidance });\n }\n\n if (action === \"audit\") {\n return handleAudit();\n }\n\n if (action === \"export\") {\n return handleExport();\n }\n\n return unknownAction(action, COLLECTIONS_ACTIONS);\n });\n }),\n );\n trackWriteTool(tool);\n}\n\ninterface DescribeCollectionRecord {\n slug: string;\n name: string;\n description?: string;\n purpose?: string;\n usageGuidance?: string;\n navGroup?: string;\n governed?: boolean;\n icon?: string;\n idPrefix?: string;\n stratum?: string;\n fields: Array<CollectionField & {\n label?: string;\n options?: string[];\n helpText?: string;\n optionDescriptions?: Record<string, string>;\n }>;\n examples?: Array<{ name: string; description: string }>;\n crossReferences?: Array<{ slug: string; relationship: string; guidance: string }>;\n}\n\nasync function handleDescribe(slug: string) {\n const col = await kernelQuery<DescribeCollectionRecord | null>(\"chain.getCollection\", { slug });\n\n if (!col) {\n return failureResult(\n `Collection '${slug}' not found.`,\n \"NOT_FOUND\",\n `No collection with slug '${slug}' in this workspace.`,\n \"Use `collections action=list` to see available collections.\",\n );\n }\n\n const sections: string[] = [];\n\n sections.push(`# ${col.name} (\\`${col.slug}\\`)`);\n if (col.description) sections.push(col.description);\n\n const meta = [\n col.governed ? \"**Governed**\" : null,\n col.navGroup ? `**Nav group:** ${col.navGroup}` : null,\n col.idPrefix ? `**Prefix:** ${col.idPrefix}-*` : null,\n col.stratum ? `**Stratum:** ${col.stratum}` : null,\n ].filter(Boolean).join(\" · \");\n if (meta) sections.push(meta);\n\n if (col.usageGuidance) {\n sections.push(`\\n## When to Use\\n\\n${col.usageGuidance}`);\n } else if (col.purpose) {\n sections.push(`\\n## Purpose\\n\\n${col.purpose}`);\n }\n\n if (col.fields.length > 0) {\n const fieldDocs = col.fields.map((f) => {\n const parts: string[] = [];\n const typeInfo = `${f.type}${f.required ? \", required\" : \"\"}`;\n parts.push(`### \\`${f.key}\\` — ${f.label ?? f.key} (${typeInfo})`);\n if (f.helpText) parts.push(f.helpText);\n if (f.options && f.options.length > 0) {\n const optLines = f.options.map((opt) => {\n const desc = f.optionDescriptions?.[opt];\n return desc ? ` - **${opt}**: ${desc}` : ` - ${opt}`;\n });\n parts.push(`\\nOptions:\\n${optLines.join(\"\\n\")}`);\n }\n return parts.join(\"\\n\");\n });\n sections.push(`\\n## Fields\\n\\n${fieldDocs.join(\"\\n\\n\")}`);\n }\n\n if (col.examples && col.examples.length > 0) {\n const exList = col.examples.map((ex) => `- **${ex.name}** — ${ex.description}`).join(\"\\n\");\n sections.push(`\\n## Examples\\n\\n${exList}`);\n }\n\n if (col.crossReferences && col.crossReferences.length > 0) {\n const refList = col.crossReferences.map((r) =>\n `- **${r.slug}** (${r.relationship}): ${r.guidance}`\n ).join(\"\\n\");\n sections.push(`\\n## Related Collections\\n\\n${refList}`);\n }\n\n return {\n content: [{ type: \"text\" as const, text: sections.join(\"\\n\\n\") }],\n structuredContent: success(\n `Documentation for collection '${col.name}' (${col.slug}).`,\n {\n slug: col.slug,\n name: col.name,\n description: col.description,\n usageGuidance: col.usageGuidance ?? null,\n fieldCount: col.fields.length,\n fields: col.fields.map((f) => ({\n key: f.key,\n type: f.type,\n required: f.required,\n helpText: f.helpText ?? null,\n options: f.options ?? null,\n optionDescriptions: f.optionDescriptions ?? null,\n })),\n examples: col.examples ?? [],\n crossReferences: col.crossReferences ?? [],\n },\n ),\n };\n}\n\nasync function handleList() {\n const collections = await kernelQuery<CollectionRecord[]>(\"chain.listCollections\");\n\n if (collections.length === 0) {\n return successResult(\n \"No collections found in this workspace.\",\n \"No collections found yet.\",\n { collections: [], total: 0 },\n [{ tool: \"collections\", description: \"Create collection\", parameters: { action: \"create\" } }],\n );\n }\n\n const formatted = collections\n .map((c) => {\n const fieldList = c.fields\n .map((f) => ` - \\`${f.key}\\` (${f.type}${f.required ? \", required\" : \"\"}${f.searchable ? \", searchable\" : \"\"})`)\n .join(\"\\n\");\n const meta = [\n c.description || \"_No description_\",\n c.purpose ? `**Purpose:** ${c.purpose}` : null,\n c.navGroup ? `**Nav group:** ${c.navGroup}` : null,\n ].filter(Boolean).join(\"\\n\");\n return `## ${c.name} (\\`${c.slug}\\`)\\n${meta}\\n\\n**Fields:**\\n${fieldList}`;\n })\n .join(\"\\n\\n---\\n\\n\");\n\n return {\n content: [{ type: \"text\" as const, text: `# Knowledge Collections (${collections.length})\\n\\n${formatted}` }],\n structuredContent: success(\n `Found ${collections.length} collections.`,\n {\n collections: collections.map((c) => ({\n slug: c.slug,\n name: c.name,\n description: c.description,\n fieldCount: c.fields.length,\n })),\n total: collections.length,\n },\n ),\n };\n}\n\ninterface CollectionMetaArgs {\n defaultCanonicalKey?: string;\n defaultWorkflowStatus?: string;\n validWorkflowStatuses?: string[];\n classificationCheck?: string;\n classificationPriority?: number;\n // FEAT-301 Slice 2\n qualityCriteria?: z.infer<typeof qualityCriterionSchema>[];\n usageGuidance?: string;\n}\n\nasync function handleCreate(\n slug: string,\n name: string,\n description: string | undefined,\n purpose: string | undefined,\n icon: string | undefined,\n navGroup: string,\n fields: z.infer<typeof fieldSchema>[],\n meta: CollectionMetaArgs = {},\n) {\n requireWriteAccess();\n\n try {\n await kernelMutation(\"chain.createCollection\", {\n slug,\n name,\n description,\n purpose,\n icon,\n navGroup,\n fields,\n ...(meta.defaultCanonicalKey !== undefined && { defaultCanonicalKey: meta.defaultCanonicalKey }),\n ...(meta.defaultWorkflowStatus !== undefined && { defaultWorkflowStatus: meta.defaultWorkflowStatus }),\n ...(meta.validWorkflowStatuses !== undefined && { validWorkflowStatuses: meta.validWorkflowStatuses }),\n ...(meta.classificationCheck !== undefined && { classificationCheck: meta.classificationCheck }),\n ...(meta.classificationPriority !== undefined && { classificationPriority: meta.classificationPriority }),\n createdBy: getAgentSessionId() ? `agent:${getAgentSessionId()}` : \"mcp\",\n });\n\n const fieldList = fields\n .map((f) => ` - \\`${f.key}\\` (${f.type}${f.required ? \", required\" : \"\"}${f.searchable ? \", searchable\" : \"\"})`)\n .join(\"\\n\");\n\n return {\n content: [{\n type: \"text\" as const,\n text: `# Collection Created: ${name}\\n\\n` +\n `**Slug:** \\`${slug}\\`\\n` +\n (description ? `**Description:** ${description}\\n` : \"\") +\n (purpose ? `**Purpose:** ${purpose}\\n` : \"\") +\n `**Nav group:** ${navGroup}\\n` +\n `\\n**Fields:**\\n${fieldList}\\n\\n` +\n `You can now capture entries: \\`capture collection=\"${slug}\" name=\"...\" description=\"...\"\\``,\n }],\n structuredContent: success(\n `Created collection '${name}' (${slug}) with ${fields.length} fields.`,\n { slug, name, description, purpose, navGroup, fieldCount: fields.length },\n [{ tool: \"capture\", description: \"Capture an entry\", parameters: { collection: slug } }],\n ),\n };\n } catch (error: unknown) {\n const msg = error instanceof Error ? error.message : String(error);\n if (msg.includes(\"already exists\")) {\n return failureResult(\n `Collection '${slug}' already exists. Use collections action=update to modify it, or choose a different slug.`,\n \"DUPLICATE\",\n `Collection '${slug}' already exists.`,\n \"Use collections action=update to modify it.\",\n [{ tool: \"collections\", description: \"Update collection\", parameters: { action: \"update\", slug } }],\n );\n }\n const code = (error as { code?: string }).code ?? (error as { data?: { code?: string } }).data?.code;\n if (code === \"COLLECTION_PREFIX_TAKEN\" || msg.includes(\"already used by collection\")) {\n return failureResult(\n msg,\n \"DUPLICATE\",\n msg,\n \"Choose a different prefix by passing the idPrefix parameter, or let the system derive one from a different slug.\",\n [{ tool: \"collections\", description: \"List collections to see taken prefixes\", parameters: { action: \"list\" } }],\n );\n }\n throw error;\n }\n}\n\nasync function handleUpdate(\n slug: string,\n name: string | undefined,\n description: string | undefined,\n purpose: string | undefined,\n icon: string | undefined,\n navGroup: string | undefined,\n fields: z.infer<typeof fieldSchema>[] | undefined,\n meta: CollectionMetaArgs = {},\n) {\n requireWriteAccess();\n\n await kernelMutation(\"chain.updateCollection\", {\n slug,\n ...(name !== undefined && { name }),\n ...(description !== undefined && { description }),\n ...(purpose !== undefined && { purpose }),\n ...(icon !== undefined && { icon }),\n ...(navGroup !== undefined && { navGroup }),\n ...(fields !== undefined && { fields }),\n ...(meta.defaultCanonicalKey !== undefined && { defaultCanonicalKey: meta.defaultCanonicalKey }),\n ...(meta.defaultWorkflowStatus !== undefined && { defaultWorkflowStatus: meta.defaultWorkflowStatus }),\n ...(meta.validWorkflowStatuses !== undefined && { validWorkflowStatuses: meta.validWorkflowStatuses }),\n ...(meta.classificationCheck !== undefined && { classificationCheck: meta.classificationCheck }),\n ...(meta.classificationPriority !== undefined && { classificationPriority: meta.classificationPriority }),\n ...(meta.qualityCriteria !== undefined && { qualityCriteria: meta.qualityCriteria }),\n ...(meta.usageGuidance !== undefined && { usageGuidance: meta.usageGuidance }),\n });\n\n const changes = [name && \"name\", description && \"description\", purpose && \"purpose\", icon && \"icon\", navGroup && \"navGroup\", fields && \"fields\", meta.defaultCanonicalKey !== undefined && \"defaultCanonicalKey\", meta.defaultWorkflowStatus !== undefined && \"defaultWorkflowStatus\", meta.validWorkflowStatuses !== undefined && \"validWorkflowStatuses\", meta.classificationCheck !== undefined && \"classificationCheck\", meta.classificationPriority !== undefined && \"classificationPriority\", meta.qualityCriteria !== undefined && \"qualityCriteria\", meta.usageGuidance !== undefined && \"usageGuidance\"]\n .filter(Boolean).join(\", \");\n\n return {\n content: [{\n type: \"text\" as const,\n text: `# Collection Updated: \\`${slug}\\`\\n\\nChanged: ${changes || \"no changes\"}.\\n\\n` +\n `Use \\`collections action=list\\` to verify the result.`,\n }],\n structuredContent: success(\n `Updated collection '${slug}'. Changed: ${changes || \"no changes\"}.`,\n { slug, changes },\n ),\n };\n}\n\ninterface AuditIssue {\n code: string;\n message: string;\n fieldKey?: string;\n}\n\ninterface AuditCollectionResult {\n slug: string;\n name: string;\n icon?: string;\n fieldCount: number;\n issues: AuditIssue[];\n}\n\ninterface AuditCollectionsData {\n total: number;\n healthy: number;\n withIssues: number;\n collections: AuditCollectionResult[];\n}\n\nasync function handleAudit() {\n const data = await kernelQuery<AuditCollectionsData>(\"chain.auditCollections\");\n\n const lines: string[] = [];\n lines.push(`# Collection Audit Report`);\n lines.push(`\\n**Total:** ${data.total} · **Healthy:** ${data.healthy} · **With issues:** ${data.withIssues}`);\n\n if (data.withIssues === 0) {\n lines.push(`\\nAll collections are healthy.`);\n } else {\n const problematic = data.collections.filter((c) => c.issues.length > 0);\n lines.push(`\\n## Collections With Issues\\n`);\n for (const col of problematic) {\n const icon = col.icon ?? \"—\";\n lines.push(`### ${icon} ${col.name} (\\`${col.slug}\\`) — ${col.issues.length} issue(s)`);\n for (const issue of col.issues) {\n lines.push(`- **[${issue.code}]** ${issue.message}`);\n }\n lines.push(\"\");\n }\n }\n\n const healthyCollections = data.collections.filter((c) => c.issues.length === 0);\n if (healthyCollections.length > 0) {\n lines.push(`\\n## Healthy Collections\\n`);\n lines.push(healthyCollections.map((c) => `- ${c.icon ?? \"—\"} \\`${c.slug}\\``).join(\"\\n\"));\n }\n\n return {\n content: [{ type: \"text\" as const, text: lines.join(\"\\n\") }],\n structuredContent: success(\n `Audit complete. ${data.total} collections: ${data.healthy} healthy, ${data.withIssues} with issues.`,\n data,\n ),\n };\n}\n\n/**\n * BET-288 Slice 5: Export all system_collection_definitions with full classification metadata.\n * Returns the complete definition for every system collection, including fields not in \"describe\":\n * thinkingLayer, classificationPriority, classificationCheck, classificationSignals,\n * governanceRole, timelineRole, canBeElementOf, descriptionFieldKey.\n * Admin only (enforced by the HTTP route).\n */\nasync function handleExport() {\n const definitions = await kernelQuery<Record<string, unknown>[]>(\"chain.exportDefinitions\");\n\n return {\n content: [{ type: \"text\" as const, text: JSON.stringify(definitions, null, 2) }],\n structuredContent: success(\n `Exported ${definitions.length} system collection definitions with full classification metadata.`,\n { definitions, total: definitions.length },\n ),\n };\n}\n","import { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { z } from \"zod\";\nimport { kernelQuery, kernelMutation } from \"../client.js\";\nimport { trackWriteTool } from \"../tool-surface.js\";\nimport { thinWrapper, success, successResult, failureResult, validationResult } from \"../envelope.js\";\n\nexport const labelsSchema = z.object({\n action: z.enum([\"list\", \"create\", \"update\", \"delete\", \"apply\", \"remove\"])\n .describe(\"Action: list all labels, create/update/delete a label, or apply/remove a label on an entry\"),\n slug: z.string().optional().describe(\"Label slug (required for create/update/delete/apply/remove)\"),\n name: z.string().optional().describe(\"Display name (required for create)\"),\n color: z.string().optional().describe(\"Hex color, e.g. '#ef4444'\"),\n description: z.string().optional().describe(\"What this label means\"),\n parentSlug: z.string().optional().describe(\"Parent group slug for label hierarchy\"),\n isGroup: z.boolean().optional().describe(\"True if this is a group container, not a taggable label\"),\n order: z.number().optional().describe(\"Sort order within its group\"),\n entryId: z.string().optional().describe(\"Entry ID for apply/remove actions\"),\n});\n\nexport function registerLabelTools(server: McpServer) {\n\n const tool = server.registerTool(\n \"labels\",\n {\n title: \"Labels\",\n description:\n \"Manage workspace labels — list, create, update, delete, apply to entries, or remove from entries. \" +\n \"Labels can be applied to any entry across any collection for cross-domain filtering. \" +\n \"Similar to labels in Linear or GitHub. Labels support hierarchy (groups with children).\",\n inputSchema: labelsSchema,\n annotations: { readOnlyHint: false, destructiveHint: true, openWorldHint: false },\n },\n thinWrapper(async ({ action, slug, name, color, description, parentSlug, isGroup, order, entryId }) => {\n if (action === \"list\") {\n const labels = await kernelQuery<any[]>(\"chain.listLabels\");\n\n if (labels.length === 0) {\n return successResult(\n \"No labels defined in this workspace yet.\",\n \"No labels defined yet.\",\n { labels: [], total: 0 },\n [{ tool: \"labels\", description: \"Create a label\", parameters: { action: \"create\" } }],\n );\n }\n\n const groups = labels.filter((l) => l.isGroup);\n const ungrouped = labels.filter((l) => !l.isGroup && !l.parentId);\n const children = (parentId: string) => labels.filter((l) => l.parentId === parentId);\n\n const lines: string[] = [\"# Workspace Labels\"];\n\n for (const group of groups) {\n lines.push(`\\n## ${group.name}`);\n if (group.description) lines.push(`_${group.description}_`);\n for (const child of children(group._id)) {\n const c = child.color ? ` ${child.color}` : \"\";\n lines.push(` - \\`${child.slug}\\` ${child.name}${c}`);\n }\n }\n\n if (ungrouped.length > 0) {\n lines.push(\"\\n## Ungrouped\");\n for (const label of ungrouped) {\n const c = label.color ? ` ${label.color}` : \"\";\n lines.push(`- \\`${label.slug}\\` ${label.name}${c}${label.description ? ` — _${label.description}_` : \"\"}`);\n }\n }\n\n return {\n content: [{ type: \"text\" as const, text: lines.join(\"\\n\") }],\n structuredContent: success(\n `Found ${labels.length} labels in ${groups.length} groups.`,\n { labels, total: labels.length },\n ),\n };\n }\n\n if (!slug) {\n return validationResult(\"A slug is required for this action.\");\n }\n\n if (action === \"create\") {\n if (!name) {\n return validationResult(\"Cannot create a label without a name.\");\n }\n\n let parentId: string | undefined;\n if (parentSlug) {\n const labels = await kernelQuery<any[]>(\"chain.listLabels\");\n const parent = labels.find((l: any) => l.slug === parentSlug);\n if (!parent) {\n return failureResult(\n `Parent label '${parentSlug}' not found. Use labels action=list to see available groups.`,\n \"NOT_FOUND\",\n `Parent label '${parentSlug}' not found.`,\n \"Use labels action=list to see available groups.\",\n [{ tool: \"labels\", description: \"List labels\", parameters: { action: \"list\" } }],\n );\n }\n parentId = parent._id;\n }\n\n await kernelMutation(\"chain.createLabel\", { slug, name, color, description, parentId, isGroup, order });\n return successResult(\n `Label '${name}' (${slug}) created.`,\n `Created label '${name}' (${slug}).`,\n { slug, name, color, parentSlug },\n [{ tool: \"labels\", description: \"List labels\", parameters: { action: \"list\" } }],\n );\n }\n\n if (action === \"update\") {\n await kernelMutation(\"chain.updateLabel\", { slug, name, color, description, isGroup, order });\n return successResult(\n `Label '${slug}' updated.`,\n `Updated label '${slug}'.`,\n { slug },\n [{ tool: \"labels\", description: \"List labels\", parameters: { action: \"list\" } }],\n );\n }\n\n if (action === \"delete\") {\n await kernelMutation(\"chain.deleteLabel\", { slug });\n return successResult(\n `Label '${slug}' removed from all entries and deleted.`,\n `Deleted label '${slug}'.`,\n { slug },\n );\n }\n\n if (action === \"apply\" || action === \"remove\") {\n if (!entryId) {\n return validationResult(\"An entryId is required for apply/remove actions.\");\n }\n\n if (action === \"apply\") {\n await kernelMutation(\"chain.applyLabel\", { entryId, labelSlug: slug });\n return successResult(`Label '${slug}' applied to ${entryId}.`, `Applied label '${slug}' to ${entryId}.`, { slug, entryId });\n }\n\n await kernelMutation(\"chain.removeLabel\", { entryId, labelSlug: slug });\n return successResult(`Label '${slug}' removed from ${entryId}.`, `Removed label '${slug}' from ${entryId}.`, { slug, entryId });\n }\n\n return validationResult(\"Unknown action.\");\n })\n );\n trackWriteTool(tool);\n}\n","import { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { z } from \"zod\";\nimport { kernelQuery, getWorkspaceId, getWorkspaceContext, getAuditLog, getAgentSessionId, getApiKeyScope, isSessionOriented, runWithToolContext, type AuditEntry } from \"../client.js\";\nimport { success, thinWrapper, parseOrFail, unknownAction, successResult } from \"../envelope.js\";\nimport { entriesSchema } from \"./entries.js\";\nimport { relationsSchema } from \"./relations.js\";\nimport { graphSchema } from \"./graph.js\";\nimport { contextSchema } from \"./context.js\";\nimport { collectionsSchema } from \"./collections.js\";\nimport { sessionSchema } from \"./session.js\";\nimport { qualitySchema } from \"./quality.js\";\nimport { workflowsSchema } from \"./workflows.js\";\nimport { wrapupSchema } from \"./wrapup.js\";\nimport { facilitateSchema } from \"./facilitate.js\";\nimport { labelsSchema } from \"./labels.js\";\nimport { verifySchema, verifyEntrySchema } from \"./verify.js\";\nimport { captureSchema, batchCaptureSchema } from \"./smart-capture.js\";\nimport { updateEntrySchema, getHistorySchema, commitEntrySchema } from \"./knowledge.js\";\nimport { startPbSchema } from \"./start_pb.js\";\nimport { usageSummarySchema } from \"./usage.js\";\nimport { chainSchema, chainVersionSchema, chainBranchSchema, chainReviewSchema } from \"./gitchain.js\";\nimport { createAudienceMapSetSchema, mapSchema, mapSlotSchema, mapVersionSchema, mapSuggestSchema } from \"./maps.js\";\nimport { architectureSchema, architectureAdminSchema } from \"./architecture.js\";\nimport { orientSchema } from \"./orient.js\";\n\ntype CallCategory = \"read\" | \"search\" | \"write\" | \"label\" | \"meta\";\n\nconst CALL_CATEGORIES: Record<string, CallCategory> = {\n \"chain.getEntry\": \"read\",\n \"chain.batchGetEntries\": \"read\",\n \"chain.listEntries\": \"read\",\n \"chain.listEntryHistory\": \"read\",\n \"chain.listEntryRelations\": \"read\",\n \"chain.listEntriesByLabel\": \"read\",\n \"chain.searchEntries\": \"search\",\n \"chain.createEntry\": \"write\",\n \"chain.updateEntry\": \"write\",\n \"chain.moveToCollection\": \"write\",\n \"chain.createEntryRelation\": \"write\",\n \"chain.applyLabel\": \"label\",\n \"chain.removeLabel\": \"label\",\n \"chain.createLabel\": \"label\",\n \"chain.updateLabel\": \"label\",\n \"chain.deleteLabel\": \"label\",\n \"chain.createCollection\": \"write\",\n \"chain.updateCollection\": \"write\",\n \"chain.listCollections\": \"meta\",\n \"chain.getCollection\": \"meta\",\n \"chain.listLabels\": \"meta\",\n \"resolveWorkspace\": \"meta\",\n};\n\nfunction categorize(fn: string): CallCategory {\n return CALL_CATEGORIES[fn] ?? \"meta\";\n}\n\nfunction formatDuration(ms: number): string {\n if (ms < 60_000) return `${Math.round(ms / 1000)}s`;\n const mins = Math.floor(ms / 60_000);\n const secs = Math.round((ms % 60_000) / 1000);\n return `${mins}m ${secs}s`;\n}\n\nfunction buildSessionSummary(log: readonly AuditEntry[]): string {\n if (log.length === 0) return \"\";\n\n const byCategory = new Map<CallCategory, Map<string, number>>();\n let errorCount = 0;\n let writeCreates = 0;\n let writeUpdates = 0;\n\n for (const entry of log) {\n const cat = categorize(entry.fn);\n if (!byCategory.has(cat)) byCategory.set(cat, new Map());\n const fnCounts = byCategory.get(cat)!;\n fnCounts.set(entry.fn, (fnCounts.get(entry.fn) ?? 0) + 1);\n\n if (entry.status === \"error\") errorCount++;\n if (entry.fn === \"chain.createEntry\" && entry.status === \"ok\") writeCreates++;\n if (entry.fn === \"chain.updateEntry\" && entry.status === \"ok\") writeUpdates++;\n }\n\n const firstTs = new Date(log[0].ts).getTime();\n const lastTs = new Date(log[log.length - 1].ts).getTime();\n const duration = formatDuration(lastTs - firstTs);\n\n const lines: string[] = [`# Session Summary (${duration})\\n`];\n\n const categoryLabels: [CallCategory, string][] = [\n [\"read\", \"Reads\"],\n [\"search\", \"Searches\"],\n [\"write\", \"Writes\"],\n [\"label\", \"Labels\"],\n [\"meta\", \"Meta\"],\n ];\n\n for (const [cat, label] of categoryLabels) {\n const fnCounts = byCategory.get(cat);\n if (!fnCounts || fnCounts.size === 0) continue;\n const total = [...fnCounts.values()].reduce((a, b) => a + b, 0);\n const detail = [...fnCounts.entries()]\n .sort((a, b) => b[1] - a[1])\n .map(([fn, count]) => `${fn.replace(\"chain.\", \"\")} x${count}`)\n .join(\", \");\n lines.push(`- **${label}:** ${total} call${total === 1 ? \"\" : \"s\"} (${detail})`);\n }\n\n lines.push(`- **Errors:** ${errorCount}`);\n\n if (writeCreates > 0 || writeUpdates > 0) {\n lines.push(\"\");\n lines.push(\"## Knowledge Contribution\");\n if (writeCreates > 0) lines.push(`- ${writeCreates} entr${writeCreates === 1 ? \"y\" : \"ies\"} created`);\n if (writeUpdates > 0) lines.push(`- ${writeUpdates} entr${writeUpdates === 1 ? \"y\" : \"ies\"} updated`);\n }\n\n return lines.join(\"\\n\");\n}\n\n// ─── Organisation Health (FEAT-129) ─────────────────────────────────────────\n\nexport type OrgHealthFlag = {\n collection: string;\n count: number;\n suggestedCollection: string;\n};\n\nexport type OrgHealthResult = {\n reviewed: number;\n agreements: number;\n disagreements: number;\n abstentions: number;\n agreementRate: number;\n flags: OrgHealthFlag[];\n};\n\n/**\n * Compute org health from pre-classified results (from Convex batch heuristic).\n * TEN-174 resolution: classification runs in Convex with DB-driven signals,\n * not locally with a stale copy. Zero drift risk.\n */\nexport function computeOrganisationHealth(\n entries: Array<{ collectionSlug?: string; collection?: string }>,\n classifications: Array<{ collection: string | null; confidence: number }>,\n): OrgHealthResult {\n let agreements = 0;\n let disagreements = 0;\n let abstentions = 0;\n const flagMap = new Map<string, Map<string, number>>();\n\n for (let i = 0; i < entries.length; i++) {\n const slug = entries[i].collectionSlug ?? entries[i].collection ?? \"unknown\";\n const result = classifications[i];\n\n if (!result?.collection) {\n abstentions++;\n continue;\n }\n\n if (result.collection === slug) {\n agreements++;\n } else {\n disagreements++;\n if (!flagMap.has(slug)) flagMap.set(slug, new Map());\n const suggestions = flagMap.get(slug)!;\n suggestions.set(result.collection, (suggestions.get(result.collection) ?? 0) + 1);\n }\n }\n\n const opinionated = agreements + disagreements;\n const agreementRate = opinionated > 0 ? Math.round((agreements / opinionated) * 100) : 100;\n\n const flags = [...flagMap.entries()]\n .map(([collection, suggestions]) => {\n const total = [...suggestions.values()].reduce((a, b) => a + b, 0);\n const topSuggested = [...suggestions.entries()].sort((a, b) => b[1] - a[1])[0];\n return { collection, count: total, suggestedCollection: topSuggested?.[0] ?? \"unknown\" };\n })\n .sort((a, b) => b.count - a.count)\n .slice(0, 3);\n\n return { reviewed: entries.length, agreements, disagreements, abstentions, agreementRate, flags };\n}\n\nexport function formatOrgHealthLines(orgHealth: OrgHealthResult, maxFlags = 3): string[] {\n const lines: string[] = [];\n if (orgHealth.disagreements > 0) {\n lines.push(\n `${orgHealth.disagreements} of ${orgHealth.reviewed} entries flagged for review (${orgHealth.agreementRate}% classifier agreement).`,\n );\n for (const flag of orgHealth.flags.slice(0, maxFlags)) {\n lines.push(`- **${flag.collection}**: ${flag.count} entries may belong in \\`${flag.suggestedCollection}\\``);\n }\n } else if (orgHealth.reviewed > 0) {\n lines.push(`All ${orgHealth.reviewed - orgHealth.abstentions} classified entries agree with stored collection (${orgHealth.abstentions} without coverage).`);\n }\n return lines;\n}\n\nasync function fetchOrganisationHealth(): Promise<OrgHealthResult | null> {\n try {\n const allEntries = await kernelQuery<any[]>(\"chain.listEntries\", { status: \"active\" });\n if (!allEntries || allEntries.length === 0) return null;\n\n // TEN-174 resolution: classify via Convex (DB-driven signals) instead of local copy.\n const classifyInput = allEntries.map((e) => ({\n name: e.name ?? \"\",\n description: typeof e.data?.description === \"string\" ? e.data.description : \"\",\n }));\n const classifications = await kernelQuery<Array<{ collection: string | null; confidence: number; scoreMargin: number }>>(\n \"chain.batchClassifyHeuristic\",\n { entries: classifyInput },\n );\n\n return computeOrganisationHealth(allEntries, classifications);\n } catch (err) {\n process.stderr.write(`[MCP] fetchOrganisationHealth failed: ${(err as Error).message}\\n`);\n return null;\n }\n}\n\nasync function handleHealthCheck() {\n const start = Date.now();\n const errors: string[] = [];\n\n let workspaceId: string | undefined;\n try {\n workspaceId = await getWorkspaceId();\n } catch (e: unknown) {\n errors.push(`Workspace resolution failed: ${e instanceof Error ? e.message : String(e)}`);\n }\n\n let collections: unknown[] = [];\n try {\n collections = await kernelQuery<unknown[]>(\"chain.listCollections\");\n } catch (e: unknown) {\n errors.push(`Collection fetch failed: ${e instanceof Error ? e.message : String(e)}`);\n }\n\n let totalEntries = 0;\n if (collections.length > 0) {\n try {\n const entries = await kernelQuery<unknown[]>(\"chain.listEntries\", {});\n totalEntries = entries.length;\n } catch (e: unknown) {\n errors.push(`Entry count failed: ${e instanceof Error ? e.message : String(e)}`);\n }\n }\n\n let wsCtx: { workspaceSlug: string; workspaceName: string } | null = null;\n try {\n wsCtx = await getWorkspaceContext();\n } catch { /* already captured workspace error above */ }\n\n const durationMs = Date.now() - start;\n const healthy = errors.length === 0;\n\n const lines = [\n `# ${healthy ? \"Healthy\" : \"Degraded\"}`,\n \"\",\n `**Workspace:** ${workspaceId ?? \"unresolved\"}`,\n `**Workspace Slug:** ${wsCtx?.workspaceSlug ?? \"unknown\"}`,\n `**Workspace Name:** ${wsCtx?.workspaceName ?? \"unknown\"}`,\n `**Collections:** ${collections.length}`,\n `**Entries:** ${totalEntries}`,\n `**Latency:** ${durationMs}ms`,\n ];\n\n if (errors.length > 0) {\n lines.push(\"\", \"## Errors\");\n for (const err of errors) {\n lines.push(`- ${err}`);\n }\n }\n\n const healthData = {\n healthy,\n collections: collections.length,\n entries: totalEntries,\n latencyMs: durationMs,\n workspace: workspaceId ?? \"unresolved\",\n };\n\n return {\n content: [{ type: \"text\" as const, text: lines.join(\"\\n\") }],\n structuredContent: success(\n healthy ? `Healthy. ${collections.length} collections, ${totalEntries} entries, ${durationMs}ms.` : `Degraded. ${errors.length} error(s).`,\n healthData,\n ),\n };\n}\n\nasync function handleWhoami() {\n const ctx = await getWorkspaceContext();\n const sessionId = getAgentSessionId();\n const scope = getApiKeyScope();\n const oriented = isSessionOriented();\n const lines = [\n `# Session Identity`,\n \"\",\n `**Workspace ID:** ${ctx.workspaceId}`,\n `**Workspace Slug:** ${ctx.workspaceSlug}`,\n `**Workspace Name:** ${ctx.workspaceName}`,\n ];\n return {\n content: [{ type: \"text\" as const, text: lines.join(\"\\n\") }],\n structuredContent: success(\n `Session: ${ctx.workspaceName} (${scope}). ${oriented ? \"Oriented.\" : \"Not oriented.\"}`,\n { workspaceId: ctx.workspaceId, workspaceName: ctx.workspaceName, scope, sessionId, oriented },\n ),\n };\n}\n\nconst STAGE_LABELS: Record<string, string> = {\n blank: \"Blank\",\n seeded: \"Seeded\",\n grounded: \"Grounded\",\n connected: \"Connected\",\n};\n\nconst STAGE_DESCRIPTIONS: Record<string, string> = {\n blank: \"No knowledge captured yet.\",\n seeded: \"Early knowledge is in place — keep building.\",\n grounded: \"Solid foundations — a few gaps remain.\",\n connected: \"Well-connected knowledge graph — your Brain is useful.\",\n};\n\nasync function handleWorkspaceStatus() {\n const result = await kernelQuery<{\n score: number;\n totalChecks: number;\n passedChecks: number;\n scoringVersion: \"v1\" | \"v2\";\n stage: \"blank\" | \"seeded\" | \"grounded\" | \"connected\";\n checks: Array<{\n passed: boolean;\n label: string;\n current: number;\n required: number;\n capabilityLabel?: string;\n }>;\n gaps: Array<{\n id: string;\n label: string;\n description: string;\n current: number;\n required: number;\n guidance: string;\n capabilityGuidance?: string;\n }>;\n stats: {\n totalEntries: number;\n activeCount: number;\n draftCount: number;\n totalRelations: number;\n collectionCount: number;\n orphanedCount: number;\n };\n governanceMode?: string;\n }>(\"chain.workspaceReadiness\");\n\n const { score, totalChecks, passedChecks, checks, gaps, stats, governanceMode } = result;\n // Guard against older backends that predate v2 scoring.\n const scoringVersion: \"v1\" | \"v2\" = result.scoringVersion ?? \"v1\";\n const stage: \"blank\" | \"seeded\" | \"grounded\" | \"connected\" = result.stage ?? \"seeded\";\n\n const stageLabel = STAGE_LABELS[stage] ?? stage;\n const stageDescription = STAGE_DESCRIPTIONS[stage] ?? \"\";\n const scoreBar = \"█\".repeat(Math.round(score / 10)) + \"░\".repeat(10 - Math.round(score / 10));\n\n const lines = [\n `# Brain Status: ${stageLabel}`,\n `_${stageDescription}_`,\n \"\",\n `${scoreBar} ${stageLabel} · ${score}%`,\n `**Governance:** ${governanceMode ?? \"open\"}${(governanceMode ?? \"open\") !== \"open\" ? \" (commits require proposal)\" : \"\"}`,\n \"\",\n \"## Stats\",\n `- **Entries:** ${stats.totalEntries} (${stats.activeCount} active, ${stats.draftCount} draft)`,\n `- **Relations:** ${stats.totalRelations}`,\n `- **Collections:** ${stats.collectionCount}`,\n `- **Orphaned:** ${stats.orphanedCount} committed entries with no relations`,\n \"\",\n ];\n\n if (gaps.length > 0) {\n lines.push(\"## Gaps\");\n for (const gap of gaps) {\n // capabilityGuidance is plain English (v2); fall back to guidance for backward compat\n const action = gap.capabilityGuidance ?? gap.guidance;\n lines.push(`- [ ] **${gap.label}**`);\n lines.push(` _${action}_`);\n }\n lines.push(\"\");\n }\n\n const passed = checks.filter((c) => c.passed);\n if (passed.length > 0) {\n lines.push(\"## Passing checks\");\n for (const check of passed) {\n lines.push(`- [x] ${check.label} (${check.current}/${check.required})`);\n }\n lines.push(\"\");\n }\n\n const orgHealth = await fetchOrganisationHealth();\n if (orgHealth && orgHealth.reviewed > 0) {\n lines.push(\"## Organisation Health\");\n lines.push(...formatOrgHealthLines(orgHealth));\n lines.push(\"\");\n }\n\n const statusData: Record<string, unknown> = {\n stage,\n scoringVersion,\n readinessScore: score,\n activeEntries: stats.activeCount,\n totalRelations: stats.totalRelations,\n orphanedEntries: stats.orphanedCount,\n gaps: gaps.map((g) => ({\n id: g.id,\n label: g.label,\n guidance: g.capabilityGuidance ?? g.guidance,\n })),\n ...(orgHealth && { organisationHealth: orgHealth }),\n };\n\n return {\n content: [{ type: \"text\" as const, text: lines.join(\"\\n\") }],\n structuredContent: success(\n `Brain: ${stageLabel} (${score}%). ${stats.activeCount} active entries, ${gaps.length} gap(s).`,\n statusData,\n ),\n };\n}\n\nasync function handleAudit(limit: number) {\n const log = getAuditLog();\n const recent = log.slice(-limit);\n\n if (recent.length === 0) {\n return successResult(\"No calls recorded yet this session.\", \"No calls recorded yet this session.\", { totalCalls: 0, calls: [] });\n }\n\n const summary = buildSessionSummary(log);\n\n const logLines = [`# Audit Log (last ${recent.length} of ${log.length} total)\\n`];\n for (const entry of recent) {\n const icon = entry.status === \"ok\" ? \"\\u2713\" : \"\\u2717\";\n const errPart = entry.error ? ` \\u2014 ${entry.error}` : \"\";\n const toolPart = entry.toolContext\n ? ` [${entry.toolContext.tool}${entry.toolContext.action ? ` action=${entry.toolContext.action}` : \"\"}]`\n : \"\";\n logLines.push(`${icon} \\`${entry.fn}\\`${toolPart} ${entry.durationMs}ms ${entry.status}${errPart}`);\n }\n\n const auditData = {\n totalCalls: log.length,\n calls: recent.map((entry) => ({\n tool: entry.fn,\n ...(entry.toolContext?.action && { action: entry.toolContext.action }),\n timestamp: entry.ts,\n ...(entry.durationMs != null && { durationMs: entry.durationMs }),\n })),\n };\n\n return {\n content: [{ type: \"text\" as const, text: `${summary}\\n\\n---\\n\\n${logLines.join(\"\\n\")}` }],\n structuredContent: success(\n `Audit: ${log.length} total calls, showing last ${recent.length}.`,\n auditData,\n ),\n };\n}\n\nconst HEALTH_ACTIONS = [\"check\", \"whoami\", \"status\", \"audit\", \"self-test\"] as const;\ntype HealthAction = (typeof HEALTH_ACTIONS)[number];\n\nexport const healthSchema = z.object({\n action: z.enum(HEALTH_ACTIONS).describe(\n \"'check': connectivity and workspace stats. 'whoami': session identity. 'status': workspace readiness. 'audit': session audit log. 'self-test': validate all tool schemas.\",\n ),\n limit: z.number().min(1).max(50).default(20).optional()\n .describe(\"For audit: how many recent calls to show (max 50)\"),\n});\n\nexport { orientSchema } from \"./orient.js\";\n\nexport const healthCheckOutputSchema = z.object({\n healthy: z.boolean(),\n collections: z.number(),\n entries: z.number(),\n latencyMs: z.number(),\n workspace: z.string(),\n});\n\nconst organisationHealthSchema = z.object({\n reviewed: z.number(),\n agreements: z.number(),\n disagreements: z.number(),\n abstentions: z.number(),\n agreementRate: z.number(),\n flags: z.array(z.object({\n collection: z.string(),\n count: z.number(),\n suggestedCollection: z.string(),\n })),\n});\n\nexport const healthStatusOutputSchema = z.object({\n stage: z.enum([\"blank\", \"seeded\", \"grounded\", \"connected\"]).optional().default(\"seeded\"),\n scoringVersion: z.enum([\"v1\", \"v2\"]).optional().default(\"v1\"),\n readinessScore: z.number(),\n activeEntries: z.number(),\n totalRelations: z.number(),\n orphanedEntries: z.number(),\n gaps: z.array(z.object({ id: z.string(), label: z.string(), guidance: z.string() })),\n organisationHealth: organisationHealthSchema.optional(),\n});\n\nexport const healthAuditOutputSchema = z.object({\n totalCalls: z.number(),\n calls: z.array(z.object({\n tool: z.string(),\n action: z.string().optional(),\n timestamp: z.string(),\n durationMs: z.number().optional(),\n })),\n});\n\nexport const healthWhoamiOutputSchema = z.object({\n workspaceId: z.string(),\n workspaceName: z.string(),\n scope: z.string(),\n sessionId: z.union([z.string(), z.null()]),\n oriented: z.boolean(),\n});\n\nconst ALL_TOOL_SCHEMAS: ReadonlyArray<{ name: string; schema: z.ZodTypeAny }> = [\n { name: \"entries\", schema: entriesSchema },\n { name: \"relations\", schema: relationsSchema },\n { name: \"graph\", schema: graphSchema },\n { name: \"context\", schema: contextSchema },\n { name: \"collections\", schema: collectionsSchema },\n { name: \"session\", schema: sessionSchema },\n { name: \"health\", schema: healthSchema },\n { name: \"orient\", schema: orientSchema },\n { name: \"quality\", schema: qualitySchema },\n { name: \"workflows\", schema: workflowsSchema },\n { name: \"session-wrapup\", schema: wrapupSchema },\n { name: \"labels\", schema: labelsSchema },\n { name: \"verify\", schema: verifySchema },\n { name: \"verify-entry\", schema: verifyEntrySchema },\n { name: \"capture\", schema: captureSchema },\n { name: \"batch-capture\", schema: batchCaptureSchema },\n { name: \"update-entry\", schema: updateEntrySchema },\n { name: \"get-history\", schema: getHistorySchema },\n { name: \"commit-entry\", schema: commitEntrySchema },\n { name: \"start_pb\", schema: startPbSchema },\n { name: \"get-usage-summary\", schema: usageSummarySchema },\n { name: \"chain\", schema: chainSchema },\n { name: \"chain-version\", schema: chainVersionSchema },\n { name: \"chain-branch\", schema: chainBranchSchema },\n { name: \"chain-review\", schema: chainReviewSchema },\n { name: \"create-audience-map-set\", schema: createAudienceMapSetSchema },\n { name: \"map\", schema: mapSchema },\n { name: \"map-slot\", schema: mapSlotSchema },\n { name: \"map-version\", schema: mapVersionSchema },\n { name: \"map-suggest\", schema: mapSuggestSchema },\n { name: \"architecture\", schema: architectureSchema },\n { name: \"architecture-admin\", schema: architectureAdminSchema },\n { name: \"facilitate\", schema: facilitateSchema },\n];\n\nexport const selfTestOutputSchema = z.object({\n passed: z.number(),\n failed: z.number(),\n total: z.number(),\n results: z.array(z.object({\n tool: z.string(),\n valid: z.boolean(),\n error: z.string().optional(),\n })),\n});\n\nfunction handleSelfTest() {\n const results: Array<{ tool: string; valid: boolean; error?: string }> = [];\n\n for (const { name, schema } of ALL_TOOL_SCHEMAS) {\n try {\n if (!schema || typeof schema.safeParse !== \"function\") {\n results.push({ tool: name, valid: false, error: \"Schema is not a valid Zod object\" });\n continue;\n }\n const test = schema.safeParse({});\n // Even if parse fails (expected for required fields), the schema itself is valid\n if (test.success || test.error) {\n results.push({ tool: name, valid: true });\n }\n } catch (e: unknown) {\n results.push({ tool: name, valid: false, error: e instanceof Error ? e.message : String(e) });\n }\n }\n\n const passed = results.filter((r) => r.valid).length;\n const failed = results.filter((r) => !r.valid).length;\n const total = results.length;\n\n const lines: string[] = [\n `# Self-Test: Tool Schema Validation`,\n `**Result:** ${failed === 0 ? \"ALL PASS\" : `${failed} FAILED`}`,\n `**Schemas validated:** ${passed}/${total}`,\n \"\",\n ];\n\n if (failed > 0) {\n lines.push(\"## Failures\");\n for (const r of results.filter((r) => !r.valid)) {\n lines.push(`- **${r.tool}**: ${r.error}`);\n }\n lines.push(\"\");\n }\n\n lines.push(\"## All Tools\");\n for (const r of results) {\n lines.push(`- ${r.valid ? \"PASS\" : \"FAIL\"} \\`${r.tool}\\``);\n }\n\n return {\n content: [{ type: \"text\" as const, text: lines.join(\"\\n\") }],\n structuredContent: success(\n failed === 0 ? `Self-test: all ${total} schemas valid.` : `Self-test: ${failed}/${total} schemas failed.`,\n { passed, failed, total, results },\n ),\n };\n}\n\nexport function registerHealthTools(server: McpServer) {\n\n server.registerTool(\n \"health\",\n {\n title: \"Health\",\n description:\n \"Diagnostics and session identity. Four actions:\\n\\n\" +\n \"- **check**: Verify connectivity — workspace, collections, entries, latency.\\n\" +\n \"- **whoami**: Session identity — workspace ID, slug, name.\\n\" +\n \"- **status**: Workspace readiness — score, gaps, stats (entries, relations, orphans).\\n\" +\n \"- **audit**: Session audit log — last N backend calls with summary.\",\n inputSchema: healthSchema,\n annotations: { readOnlyHint: true, idempotentHint: true, openWorldHint: false },\n },\n thinWrapper(async (args) => {\n const parsed = parseOrFail(healthSchema, args);\n if (!parsed.ok) return parsed.result;\n const { action, limit } = parsed.data;\n\n return runWithToolContext({ tool: \"health\", action }, async () => {\n if (action === \"check\") return handleHealthCheck();\n if (action === \"whoami\") return handleWhoami();\n if (action === \"status\") return handleWorkspaceStatus();\n if (action === \"audit\") return handleAudit(limit ?? 20);\n if (action === \"self-test\") return handleSelfTest();\n\n return unknownAction(action, HEALTH_ACTIONS);\n });\n })\n );\n\n}\n","/**\n * Session compound tool — start, close, status.\n * Consolidates agent-start, agent-close, agent-status into one tool.\n * Chain: PB-TEN-001 (AI starts from zero every session)\n */\n\nimport { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { z } from \"zod\";\nimport {\n getWorkspaceContext,\n startAgentSession,\n closeAgentSession,\n getAgentSessionId,\n isSessionOriented,\n kernelCall,\n runWithToolContext,\n} from \"../client.js\";\nimport { runWrapupReview } from \"./wrapup.js\";\nimport { thinWrapper, success, failureResult, parseOrFail, unknownAction } from \"../envelope.js\";\nimport { clearSessionGaps } from \"../gap-store.js\";\nimport { trackSessionCaptureRate } from \"../analytics.js\";\n\nconst SESSION_ACTIONS = [\"start\", \"close\", \"status\"] as const;\ntype SessionAction = (typeof SESSION_ACTIONS)[number];\n\nexport const sessionSchema = z.object({\n action: z.enum(SESSION_ACTIONS).describe(\n \"'start': begin a tracked session. 'close': end the session and record activity. 'status': check current session state.\",\n ),\n});\n\nexport function registerSessionTools(server: McpServer): void {\n server.registerTool(\n \"session\",\n {\n title: \"Session\",\n description:\n \"Manage agent session lifecycle. Three actions:\\n\\n\" +\n \"- **start**: Begin a tracked session. Creates attribution for this workspace. \" +\n \"If a session is already active, it gets superseded. Write tools available after orient.\\n\" +\n \"- **close**: End the current session. Records structured data (entries created, modified, relations). \" +\n \"If uncommitted drafts exist and wrapup hasn't run, shows a review summary. Run session-wrapup before closing.\\n\" +\n \"- **status**: Check current session — active or not, oriented, activity counts.\",\n inputSchema: sessionSchema,\n annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: false },\n },\n thinWrapper(async (args) => {\n const parsed = parseOrFail(sessionSchema, args);\n if (!parsed.ok) return parsed.result;\n\n const { action } = parsed.data;\n\n return runWithToolContext({ tool: \"session\", action }, async () => {\n if (action === \"start\") {\n return handleStart();\n }\n if (action === \"close\") {\n return handleClose();\n }\n if (action === \"status\") {\n return handleStatus();\n }\n\n return unknownAction(action, SESSION_ACTIONS);\n });\n }),\n );\n}\n\nasync function handleStart() {\n const result = await startAgentSession();\n\n const lines: string[] = [];\n\n if (result.superseded) {\n lines.push(\n `Previous session superseded. Session ${result.superseded.previousSessionId} ` +\n `(started ${result.superseded.startedAt}, initiated by ${result.superseded.initiatedBy}) was closed.`,\n \"\",\n );\n }\n\n lines.push(\n `Session ${result.sessionId} active. ` +\n `Initiated by ${result.initiatedBy}. ` +\n `Workspace ${result.workspaceName}. ` +\n `Scope: ${result.toolsScope}. ` +\n `Write tools available after orient.`,\n );\n\n const summary = `Session ${result.sessionId} active. Workspace ${result.workspaceName}. Write tools available after orient.`;\n return {\n content: [{ type: \"text\" as const, text: lines.join(\"\\n\") }],\n structuredContent: success(summary, {\n sessionId: result.sessionId,\n initiatedBy: result.initiatedBy,\n workspaceName: result.workspaceName,\n toolsScope: result.toolsScope,\n superseded: !!result.superseded,\n }, [{ tool: \"orient\", description: \"Orient session\", parameters: {} }]),\n };\n}\n\nasync function handleClose() {\n const sessionId = getAgentSessionId();\n if (!sessionId) {\n return failureResult(\n \"No active agent session to close.\",\n \"SESSION_REQUIRED\",\n \"No active agent session to close.\",\n \"Start a session first.\",\n [{ tool: \"session\", description: \"Start a session\", parameters: { action: \"start\" } }],\n );\n }\n\n const session = await kernelCall<Record<string, unknown>>(\"agent.getSession\", {\n sessionId,\n });\n\n let wrapupNudge = \"\";\n if (session && !(session.wrapupCompletedAt as number)) {\n try {\n const { text, data } = await runWrapupReview();\n if (data && data.drafts.length > 0) {\n wrapupNudge = [\n \"## Session Wrapup\",\n \"\",\n text,\n \"\",\n `> **${data.drafts.length} uncommitted draft(s) remain.** ` +\n \"Run `session-wrapup` with action `commit-all` before closing next time.\",\n \"\",\n \"---\",\n \"\",\n ].join(\"\\n\");\n }\n } catch {\n // Non-critical — proceed with close even if wrapup review fails\n }\n }\n\n await closeAgentSession();\n clearSessionGaps();\n\n // WP-306 S3: Emit capture rate event for PostHog measurement (STD-155)\n const created = (session?.entriesCreated as string[])?.length ?? 0;\n const modified = (session?.entriesModified as string[])?.length ?? 0;\n const relations = (session?.relationsCreated as number) ?? 0;\n\n const wsCtx = await getWorkspaceContext();\n if (wsCtx) {\n trackSessionCaptureRate(wsCtx.workspaceId, {\n entries_created: created,\n entries_modified: modified,\n relations_created: relations,\n had_captures: created > 0,\n });\n }\n\n const lines: string[] = [\n `Session ${sessionId} closed.`,\n \"\",\n ];\n const gates = (session?.gateFailures as number) ?? 0;\n const warnings = (session?.contradictionWarnings as number) ?? 0;\n\n if (session) {\n lines.push(\n `| Metric | Count |`,\n `|--------|-------|`,\n `| Entries created | ${created} |`,\n `| Entries modified | ${modified} |`,\n `| Relations created | ${relations} |`,\n `| Gate failures | ${gates} |`,\n `| Contradiction warnings | ${warnings} |`,\n );\n }\n\n lines.push(\"\", \"Write tools are now blocked. Session data saved for future orientation.\");\n\n const fullResponse = wrapupNudge + lines.join(\"\\n\");\n const summary = `Session ${sessionId} closed. ${created} created, ${modified} modified.`;\n return {\n content: [{ type: \"text\" as const, text: fullResponse }],\n structuredContent: success(summary, {\n sessionId,\n entriesCreated: created,\n entriesModified: modified,\n relationsCreated: relations,\n gateFailures: gates,\n contradictionWarnings: warnings,\n wrapupNudge: wrapupNudge.length > 0,\n }),\n };\n}\n\nasync function handleStatus() {\n const sessionId = getAgentSessionId();\n if (!sessionId) {\n return failureResult(\n \"No active agent session. Call session action=start to begin.\",\n \"SESSION_REQUIRED\",\n \"No active agent session.\",\n \"Call session action=start to begin.\",\n [{ tool: \"session\", description: \"Start a session\", parameters: { action: \"start\" } }],\n );\n }\n\n const session = await kernelCall<Record<string, unknown>>(\"agent.getSession\", {\n sessionId,\n });\n\n if (!session) {\n return failureResult(\n \"Session not found in Convex. Call session action=start to create a new session.\",\n \"NOT_FOUND\",\n \"Session not found in Convex.\",\n \"Call session action=start to create a new session.\",\n [{ tool: \"session\", description: \"Start a session\", parameters: { action: \"start\" } }],\n );\n }\n\n const oriented = isSessionOriented();\n const created = (session.entriesCreated as string[])?.length ?? 0;\n const modified = (session.entriesModified as string[])?.length ?? 0;\n\n const lines = [\n `Session ${sessionId} ${session.status}.`,\n `Initiated by ${session.initiatedBy}.`,\n `Scope: ${session.toolsScope}.`,\n `Oriented: ${oriented ? \"yes\" : \"no\"}.`,\n \"\",\n `| Metric | Value |`,\n `|--------|-------|`,\n `| Entries created | ${created} |`,\n `| Entries modified | ${modified} |`,\n `| Relations created | ${session.relationsCreated ?? 0} |`,\n `| Started | ${new Date(session.startedAt as number).toISOString()} |`,\n `| Expires | ${new Date(session.expiresAt as number).toISOString()} |`,\n ];\n\n const summary = `Session ${sessionId} ${session.status}. ${created} created, ${modified} modified.`;\n return {\n content: [{ type: \"text\" as const, text: lines.join(\"\\n\") }],\n structuredContent: success(summary, {\n sessionId,\n status: session.status,\n initiatedBy: session.initiatedBy,\n toolsScope: session.toolsScope,\n oriented,\n entriesCreated: created,\n entriesModified: modified,\n relationsCreated: session.relationsCreated ?? 0,\n }),\n };\n}\n","/**\n * Session wrapup tools — the closing ceremony for agent sessions.\n * Chain: GLO-47 (Wrapup), GLO-48 (Draft Harvest), ENT-33 (Session Wrapup Ceremony)\n *\n * session-wrapup: Reviews session drafts, quality coaches, suggests links, offers batch commit.\n * Aliases wrapup/finish were removed — \"Also known as\" is in the description for discoverability.\n *\n * Wrapup must run BEFORE session action=close (BR-8: active session required for writes).\n * Commit-on-confirm: wrapup surfaces drafts but only commits when explicitly asked.\n */\n\nimport { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { z } from \"zod\";\nimport { thinWrapper, parseOrFail, failureResult, successResult } from \"../envelope.js\";\nimport {\n getAgentSessionId,\n getApiKeyScope,\n getWorkspaceContext,\n kernelCall,\n kernelCallEnvelope,\n kernelQuery,\n kernelMutation,\n requireWriteAccess,\n recordSessionActivity,\n runWithToolContext,\n} from \"../client.js\";\nimport { trackChainEntryCommitted, trackZeroCaptureAuditFired } from \"../analytics.js\";\nimport { trackWriteTool } from \"../tool-surface.js\";\nimport { getTopGaps, getSessionGaps } from \"../gap-store.js\";\nimport {\n detectTouchedRegistries,\n runCoherenceCheck,\n toSnapshot,\n computeDelta,\n renderCoherenceDelta,\n findPersistentGaps,\n renderPersistentGapOffers,\n type CoherenceSnapshot,\n type CoherenceVerdict,\n type PersistentGap,\n} from \"../lib/coherence/index.js\";\nimport { resolveProjectRoot } from \"../lib/resolve-project-root.js\";\n\ninterface WrapupEntry {\n docId: string;\n entryId: string;\n name: string;\n collection: string;\n status: string;\n canonicalKey: string | null;\n wasCreated: boolean;\n}\n\ninterface WrapupVerdict {\n passed: boolean;\n tier: string;\n weakest: { criterion: string; hint: string } | null;\n source: string;\n}\n\ninterface LinkSuggestion {\n fromEntryId: string;\n toEntryId: string;\n type: string;\n label: string;\n}\n\nexport interface WrapupData {\n drafts: WrapupEntry[];\n committed: WrapupEntry[];\n qualityVerdicts: Record<string, WrapupVerdict>;\n connectionCounts: Record<string, number>;\n summary: { created: number; modified: number; uncommitted: number; totalReviewed: number };\n overflow: number;\n wrapupCompletedAt: number | null;\n closeNudge: string;\n captureAudit: {\n message: string;\n suggestions: Array<{ collectionSlug: string; hint: string }>;\n } | null;\n}\n\ninterface SuggestLinksResult {\n resolvedEntry: { entryId: string; name: string; docId: string };\n suggestions: {\n entryId: string;\n name: string;\n collectionSlug: string;\n score: number;\n recommendedRelationType: string;\n reasoning: string;\n }[];\n}\n\ninterface WrapupReviewResult {\n text: string;\n data: WrapupData | null;\n suggestions: LinkSuggestion[];\n /** Set on early exits so the caller doesn't need to derive codes from text. */\n failureCode?: string;\n /** BET-89: number of knowledge gaps detected this session. */\n gapCount?: number;\n /** FEAT-184: coherence verdict when registry files were touched. */\n coherenceVerdict?: CoherenceVerdict;\n /** BET-101: persistent gaps eligible for Chain capture as tensions. */\n persistentGaps?: PersistentGap[];\n /** WP-321: kernel envelope fields surfaced for thin passthrough. */\n kernelSummary?: string;\n kernelNext?: import(\"../envelope.js\").NextAction[];\n kernelMeta?: { durationMs?: number };\n}\n\n// ─── Concurrency helper ──────────────────────────────────────────────────────\n\nasync function mapWithConcurrency<T, U>(\n items: T[],\n mapper: (item: T) => Promise<U>,\n concurrency = 3,\n): Promise<PromiseSettledResult<U>[]> {\n const results: PromiseSettledResult<U>[] = new Array(items.length);\n let index = 0;\n\n async function runNext(): Promise<void> {\n while (index < items.length) {\n const i = index++;\n try {\n const value = await mapper(items[i]);\n results[i] = { status: \"fulfilled\", value };\n } catch (reason) {\n results[i] = { status: \"rejected\", reason };\n }\n }\n }\n\n await Promise.all(\n Array.from({ length: Math.min(concurrency, items.length) }, () => runNext()),\n );\n return results;\n}\n\n// ─── Coherence snapshot retrieval (FEAT-184) ────────────────────────────────\n\ninterface SessionResponse {\n status: string;\n oriented: boolean;\n coherenceSnapshot?: {\n checkedAt: unknown;\n totalGaps: unknown;\n topGaps: unknown;\n };\n}\n\nfunction isValidTopGap(g: unknown): g is { registry: string; slug: string; severity: string } {\n if (typeof g !== \"object\" || g === null) return false;\n const obj = g as Record<string, unknown>;\n return (\n typeof obj.registry === \"string\" &&\n typeof obj.slug === \"string\" &&\n typeof obj.severity === \"string\" &&\n (obj.severity === \"error\" || obj.severity === \"warning\" || obj.severity === \"info\")\n );\n}\n\nasync function fetchSessionCoherenceSnapshot(\n sessionId: string,\n): Promise<CoherenceSnapshot | null> {\n try {\n const session = await kernelCall<SessionResponse>(\"agent.getSession\", {\n sessionId,\n });\n const raw = session?.coherenceSnapshot;\n if (\n raw &&\n typeof raw.checkedAt === \"number\" &&\n typeof raw.totalGaps === \"number\" &&\n Array.isArray(raw.topGaps) &&\n raw.topGaps.every(isValidTopGap)\n ) {\n return raw as unknown as CoherenceSnapshot;\n }\n } catch (err) {\n if (process.env.DEBUG_COHERENCE) {\n console.debug(\"[coherence] Snapshot fetch failed:\", err instanceof Error ? err.message : err);\n }\n }\n return null;\n}\n\n// ─── Suggest links with concurrency ──────────────────────────────────────────\n\nasync function suggestLinksForEntries(entries: WrapupEntry[]): Promise<LinkSuggestion[]> {\n const suggestions: LinkSuggestion[] = [];\n\n const results = await mapWithConcurrency(\n entries,\n async (entry) => {\n const result = await kernelQuery<SuggestLinksResult>(\"chain.graphSuggestLinks\", {\n entryId: entry.entryId,\n limit: 3,\n });\n return { entry, suggestions: result.suggestions ?? [] };\n },\n 3,\n );\n\n for (const result of results) {\n if (result.status !== \"fulfilled\") continue;\n const { entry, suggestions: entrySuggestions } = result.value;\n for (const s of entrySuggestions.slice(0, 2)) {\n suggestions.push({\n fromEntryId: entry.entryId,\n toEntryId: s.entryId,\n type: s.recommendedRelationType,\n label: `${entry.entryId} → ${s.entryId} (${s.name}) [${s.recommendedRelationType}]`,\n });\n }\n }\n\n return suggestions;\n}\n\n// ─── Core review logic ───────────────────────────────────────────────────────\n\nasync function runWrapupReview(): Promise<WrapupReviewResult> {\n const sessionId = getAgentSessionId();\n if (!sessionId) {\n return { text: \"No active agent session. Call `session action=start` first.\", data: null, suggestions: [], failureCode: \"SESSION_REQUIRED\" };\n }\n\n if (getApiKeyScope() === \"read\") {\n return { text: \"Read-only session — nothing to review.\", data: null, suggestions: [], failureCode: \"READONLY_SCOPE\" };\n }\n\n const { workspaceId } = await getWorkspaceContext();\n // WP-321 E3: delegate to kernel action; auth injected server-side via injectSessionAuth in http.ts\n const kernelEnvelope = await kernelCallEnvelope<WrapupData>(\"agentKnowledge.wrapupEnvelope\", {\n workspaceId,\n sessionId,\n action: \"review\",\n });\n const data = kernelEnvelope.data;\n\n if (data.wrapupCompletedAt) {\n return { text: \"Wrapup already completed this session.\", data, suggestions: [], failureCode: \"ALREADY_COMPLETED\" };\n }\n\n if (data.drafts.length === 0 && data.committed.length === 0) {\n return { text: \"Empty session — no entries to review.\", data, suggestions: [], failureCode: \"NOT_FOUND\" };\n }\n\n const lines: string[] = [];\n\n lines.push(\n `**Session activity:** ${data.summary.created} created, ${data.summary.modified} modified, ` +\n `${data.summary.uncommitted} uncommitted drafts.`,\n );\n if (data.overflow > 0) {\n lines.push(`_...and ${data.overflow} more entries not shown._`);\n }\n lines.push(\"\");\n\n if (data.drafts.length > 0) {\n lines.push(\"### Uncommitted Drafts\", \"\");\n lines.push(\"| Entry | Collection | Quality | Connections | Coaching |\");\n lines.push(\"|-------|------------|---------|-------------|----------|\");\n\n for (const draft of data.drafts) {\n const verdict = data.qualityVerdicts[draft.entryId];\n const conns = data.connectionCounts[draft.entryId] ?? 0;\n const qualityStr = verdict\n ? `${verdict.passed ? \"Pass\" : \"Needs work\"} (${verdict.source})`\n : \"—\";\n const coaching = verdict?.weakest\n ? verdict.weakest.hint\n : \"—\";\n\n lines.push(`| \\`${draft.entryId}\\` ${draft.name} | ${draft.collection} | ${qualityStr} | ${conns} | ${coaching} |`);\n }\n lines.push(\"\");\n }\n\n if (data.committed.length > 0) {\n lines.push(`### Already Committed (${data.committed.length})`, \"\");\n for (const entry of data.committed) {\n const conns = data.connectionCounts[entry.entryId] ?? 0;\n lines.push(`- \\`${entry.entryId}\\` [${entry.collection}] ${entry.name} (${conns} connections)`);\n }\n lines.push(\"\");\n }\n\n // Suggest links for low-connection entries (bounded concurrency)\n const lowConnEntries = [...data.drafts, ...data.committed].filter(\n (e) => (data.connectionCounts[e.entryId] ?? 0) < 2,\n );\n\n const suggestions = lowConnEntries.length > 0\n ? await suggestLinksForEntries(lowConnEntries.slice(0, 10))\n : [];\n\n if (suggestions.length > 0) {\n lines.push(\"### Suggested Links\", \"\");\n for (const s of suggestions) {\n lines.push(`- ${s.label}`);\n }\n lines.push(\"\");\n }\n\n const topGaps = getTopGaps(5);\n if (topGaps.length > 0) {\n lines.push(\"### Learning Opportunities\", \"\");\n lines.push(`This session, agents looked for ${topGaps.length} topic${topGaps.length === 1 ? \"\" : \"s\"} not yet on the Chain:`, \"\");\n for (const gap of topGaps) {\n const freq = gap.count > 1 ? ` _(${gap.count}x)_` : \"\";\n lines.push(`- **${gap.query}** — not yet captured${freq}`);\n }\n lines.push(\"\");\n lines.push(\"_Capturing these will make future sessions more effective._\");\n lines.push(\"\");\n }\n\n // ── FEAT-184 + BET-101: Coherence delta + persistent gap offers ─────────\n let coherenceVerdict: CoherenceVerdict | undefined;\n let persistentGaps: PersistentGap[] | undefined;\n try {\n const projectRoot = resolveProjectRoot();\n if (projectRoot) {\n const touchedFiles = detectTouchedRegistries(projectRoot);\n const sessionSnapshot = await fetchSessionCoherenceSnapshot(sessionId);\n const shouldCheck = touchedFiles.size > 0 || sessionSnapshot !== null;\n\n if (shouldCheck) {\n const report = runCoherenceCheck(projectRoot);\n if (report) {\n const afterSnapshot = toSnapshot(report);\n\n if (sessionSnapshot) {\n const delta = computeDelta(sessionSnapshot, afterSnapshot);\n coherenceVerdict = delta.verdict;\n const deltaLines = renderCoherenceDelta(delta);\n lines.push(...deltaLines);\n\n if (touchedFiles.size > 0) {\n lines.push(\n `_This session touched ${touchedFiles.size} registry file${touchedFiles.size === 1 ? \"\" : \"s\"}: ` +\n `${[...touchedFiles].slice(0, 3).map((f) => `\\`${f}\\``).join(\", \")}` +\n `${touchedFiles.size > 3 ? ` and ${touchedFiles.size - 3} more` : \"\"}._`,\n );\n lines.push(\"\");\n }\n\n // BET-101: offer to capture persistent gaps as Chain tensions\n persistentGaps = findPersistentGaps(delta, report.violations);\n if (persistentGaps.length > 0) {\n lines.push(...renderPersistentGapOffers(persistentGaps));\n }\n } else if (touchedFiles.size > 0) {\n lines.push(\"### Coherence Check\");\n lines.push(\n `This session touched ${touchedFiles.size} registry file${touchedFiles.size === 1 ? \"\" : \"s\"} ` +\n `but no session-start snapshot exists — showing absolute state.`,\n );\n const { summary } = report;\n if (summary.total === 0) {\n lines.push(\"All registries aligned — no gaps.\");\n } else {\n lines.push(`**${summary.total} gap${summary.total === 1 ? \"\" : \"s\"}**: ${summary.errors} error${summary.errors === 1 ? \"\" : \"s\"}, ${summary.warnings} warning${summary.warnings === 1 ? \"\" : \"s\"}, ${summary.infos} info.`);\n }\n lines.push(\"\");\n }\n }\n }\n }\n } catch (err) {\n if (process.env.DEBUG_COHERENCE) {\n console.debug(\"[coherence] Wrapup coherence check failed:\", err instanceof Error ? err.message : err);\n }\n }\n\n if (data.drafts.length > 0) {\n const draftIds = data.drafts.map((d) => `\\`${d.entryId}\\``).join(\", \");\n lines.push(\"### Actions\", \"\");\n lines.push(`Uncommitted: ${draftIds}`);\n lines.push(\"- **Commit all:** call \\`session-wrapup\\` with action `commit-all`\");\n lines.push(\"- **Skip:** call \\`session action=close\\` — drafts remain for next session's orient recovery.\");\n }\n\n // WP-306 S2: Render captureAudit (zero-capture sessions with activity) and closeNudge.\n if (data.captureAudit) {\n lines.push(\"\");\n lines.push(\"### Capture Audit\");\n lines.push(\"\");\n lines.push(`_${data.captureAudit.message}_`);\n if (data.captureAudit.suggestions.length > 0) {\n lines.push(\"\");\n lines.push(\"**What to consider capturing:**\");\n for (const s of data.captureAudit.suggestions) {\n lines.push(`- **${s.collectionSlug}**: ${s.hint}`);\n }\n }\n lines.push(\"\");\n }\n\n lines.push(\"\");\n lines.push(`> **${data.closeNudge}**`);\n\n // WP-306 S3: Emit zero_capture_audit_fired event (STD-155)\n if (data.captureAudit) {\n const wsCtx = await getWorkspaceContext();\n if (wsCtx) {\n trackZeroCaptureAuditFired(wsCtx.workspaceId, {\n suggestion_count: data.captureAudit.suggestions.length,\n });\n }\n }\n\n const gapCount = getSessionGaps().length;\n return {\n text: lines.join(\"\\n\"),\n data,\n suggestions,\n gapCount,\n coherenceVerdict,\n persistentGaps,\n kernelSummary: kernelEnvelope.summary,\n kernelNext: kernelEnvelope.next,\n kernelMeta: kernelEnvelope._meta,\n };\n}\n\n// ─── Commit flow ─────────────────────────────────────────────────────────────\n\nasync function runWrapupCommitAll(\n data: WrapupData,\n cachedSuggestions: LinkSuggestion[],\n): Promise<{ text: string; committed: number; proposalsCreated: number; linksCreated: number; linksFailed: number; failed: number }> {\n requireWriteAccess();\n\n const sessionId = getAgentSessionId();\n if (!sessionId) {\n return { text: \"No active session.\", committed: 0, proposalsCreated: 0, linksCreated: 0, linksFailed: 0, failed: 0 };\n }\n\n const wsCtx = await getWorkspaceContext();\n\n const results: { entryId: string; ok: boolean; proposed?: boolean; error?: string }[] = [];\n let linksCreated = 0;\n let linksFailed = 0;\n const linkFailureDetails: string[] = [];\n let proposalsCreated = 0;\n\n for (const draft of data.drafts) {\n try {\n const result = await kernelMutation<{ status?: string }>(\"chain.commitEntry\", {\n entryId: draft.entryId,\n author: `agent:${sessionId}`,\n sessionId,\n });\n const proposed = result?.status === \"proposal_created\";\n if (!proposed) {\n await recordSessionActivity({ entryModified: draft.docId });\n trackChainEntryCommitted(wsCtx.workspaceId, {\n entry_id: draft.entryId,\n commit_method: \"manual\",\n surface: \"mcp_wrapup\",\n });\n }\n if (proposed) {\n proposalsCreated++;\n }\n results.push({ entryId: draft.entryId, ok: true, proposed });\n } catch (err: unknown) {\n const msg = err instanceof Error ? err.message : String(err);\n results.push({ entryId: draft.entryId, ok: false, error: msg });\n }\n }\n\n // Use cached suggestions from review phase, or fetch fresh if none\n const suggestionsToApply = cachedSuggestions.length > 0\n ? cachedSuggestions\n : await suggestLinksForEntries(\n [...data.drafts, ...data.committed].filter(\n (e) => (data.connectionCounts[e.entryId] ?? 0) < 2,\n ).slice(0, 10),\n );\n const linkableSourceIds = new Set([\n ...data.committed.map((entry) => entry.entryId),\n ...results.filter((r) => r.ok && !r.proposed).map((r) => r.entryId),\n ]);\n\n const toApply = suggestionsToApply\n .filter((s) => linkableSourceIds.has(s.fromEntryId))\n .slice(0, 15);\n const governsRels = toApply.filter((s) => s.type === \"governs\");\n const batchRels = toApply.filter((s) => s.type !== \"governs\");\n\n if (batchRels.length > 0) {\n try {\n const batchResult = await kernelMutation<{\n results: Array<{ ok: boolean; error?: string }>;\n created: number;\n failed: number;\n }>(\"chain.createEntryRelations\", {\n relations: batchRels.map((s) => ({\n fromEntryId: s.fromEntryId,\n toEntryId: s.toEntryId,\n type: s.type,\n })),\n sessionId,\n });\n linksCreated += batchResult?.created ?? 0;\n\n // Surface per-relation failures so the user knows which links weren't created\n if (batchResult && batchResult.failed > 0) {\n linksFailed += batchResult.failed;\n const failedResults = batchResult.results\n .map((r, i) => ({ ...r, index: i }))\n .filter((r) => !r.ok);\n for (const fr of failedResults) {\n const rel = batchRels[fr.index];\n if (rel) {\n linkFailureDetails.push(\n `${rel.fromEntryId} → ${rel.toEntryId} [${rel.type}]: ${fr.error ?? \"unknown error\"}`,\n );\n }\n }\n }\n } catch (err) {\n // Total batch failure — count all as failed\n linksFailed += batchRels.length;\n const msg = err instanceof Error ? err.message : String(err);\n linkFailureDetails.push(`Batch creation failed (${batchRels.length} relations): ${msg}`);\n }\n }\n\n for (const s of governsRels) {\n try {\n const result = await kernelMutation<{ status?: string }>(\"chain.createEntryRelation\", {\n fromEntryId: s.fromEntryId,\n toEntryId: s.toEntryId,\n type: s.type,\n sessionId,\n });\n if (result?.status !== \"proposal_created\") {\n linksCreated++;\n }\n } catch (err) {\n linksFailed++;\n const msg = err instanceof Error ? err.message : String(err);\n linkFailureDetails.push(`${s.fromEntryId} → ${s.toEntryId} [${s.type}]: ${msg}`);\n }\n }\n\n const committed = results.filter((r) => r.ok && !r.proposed).length;\n const failed = results.filter((r) => !r.ok);\n\n await kernelCall(\"agent.recordWrapup\", {\n sessionId,\n draftsReviewed: data.drafts.length,\n draftsCommitted: committed,\n linksCreated,\n });\n\n const lines: string[] = [\n \"## Wrapup Complete\",\n \"\",\n `**${committed}** drafts committed, **${proposalsCreated}** proposals created, **${linksCreated}** links created.`,\n ];\n\n if (linksFailed > 0) {\n lines.push(`**${linksFailed}** link${linksFailed === 1 ? \"\" : \"s\"} failed to create.`);\n }\n\n if (failed.length > 0) {\n lines.push(\"\");\n lines.push(\"### Failed to commit\");\n for (const f of failed) {\n lines.push(`- \\`${f.entryId}\\`: ${f.error}`);\n }\n lines.push(\"_These remain as drafts for next session._\");\n }\n\n if (linkFailureDetails.length > 0) {\n lines.push(\"\");\n lines.push(\"### Failed to create links\");\n for (const detail of linkFailureDetails) {\n lines.push(`- ${detail}`);\n }\n lines.push(\"_You can create these links manually with `entries action=create-relation`._\");\n }\n\n return {\n text: lines.join(\"\\n\"),\n committed,\n proposalsCreated,\n linksCreated,\n linksFailed,\n failed: failed.length,\n };\n}\n\n// ─── Tool registration ───────────────────────────────────────────────────────\n\nconst WRAPUP_TOOL_DESCRIPTION =\n \"Review your session before closing. Shows uncommitted drafts with quality scores, \" +\n \"suggests links for low-connection entries, and offers batch commit. \" +\n \"Run this before `session action=close` to ensure nothing is left behind. \" +\n \"If you call `session action=close` without running wrapup first, you'll get a review-only nudge.\";\n\nexport const wrapupSchema = z.object({\n action: z.enum([\"review\", \"commit-all\"]).optional().describe(\n \"Action to perform. 'review' (default) shows the wrapup summary. 'commit-all' commits all uncommitted drafts and creates suggested links.\",\n ),\n});\n\nexport function registerWrapupTools(server: McpServer): void {\n let lastReviewData: WrapupData | null = null;\n let lastReviewSuggestions: LinkSuggestion[] = [];\n let lastReviewSessionId: string | null = null;\n\n const wrapupHandler = async ({ action }: { action?: \"review\" | \"commit-all\" }) => {\n if (action === \"commit-all\") {\n const sessionId = getAgentSessionId();\n if (!sessionId) {\n return failureResult(\n \"No active agent session.\",\n \"SESSION_REQUIRED\",\n \"No active agent session.\",\n \"Start a session first.\",\n [{ tool: \"session\", description: \"Start a session\", parameters: { action: \"start\" } }],\n );\n }\n\n const useCachedReview = lastReviewSessionId === sessionId;\n let data: WrapupData;\n if (useCachedReview && lastReviewData) {\n data = lastReviewData;\n } else {\n const { workspaceId } = await getWorkspaceContext();\n // WP-321 E3: delegate to kernel action; auth injected server-side via injectSessionAuth in http.ts\n data = (await kernelCallEnvelope<WrapupData>(\"agentKnowledge.wrapupEnvelope\", {\n workspaceId,\n sessionId,\n action: \"review\",\n })).data;\n }\n if (data.drafts.length === 0) {\n return failureResult(\"No uncommitted drafts to commit.\", \"NOT_FOUND\", \"No uncommitted drafts to commit.\", \"Nothing to commit.\");\n }\n\n const result = await runWrapupCommitAll(data, useCachedReview ? lastReviewSuggestions : []);\n lastReviewData = null;\n lastReviewSuggestions = [];\n lastReviewSessionId = null;\n const linkWarnSuffix = result.linksFailed > 0 ? `, ${result.linksFailed} link(s) failed` : \"\";\n return successResult(\n result.text,\n `Wrapup processed: ${result.committed} committed, ${result.proposalsCreated} proposals, ${result.linksCreated} links${linkWarnSuffix}.`,\n {\n committed: result.committed,\n proposalsCreated: result.proposalsCreated,\n linksCreated: result.linksCreated,\n linksFailed: result.linksFailed,\n failed: result.failed,\n },\n );\n }\n\n const { text, data, suggestions, failureCode, gapCount, coherenceVerdict, persistentGaps, kernelSummary, kernelNext, kernelMeta } = await runWrapupReview();\n lastReviewData = data;\n lastReviewSuggestions = suggestions;\n lastReviewSessionId = getAgentSessionId();\n\n const fullText = data && (data.drafts.length > 0 || data.committed.length > 0)\n ? `## Session Wrapup\\n\\n${text}`\n : text;\n\n if (failureCode) {\n return failureResult(fullText, failureCode, text);\n }\n\n const localNext =\n data!.drafts.length > 0\n ? [{ tool: \"session-wrapup\", description: \"Commit all drafts\", parameters: { action: \"commit-all\" } }]\n : undefined;\n const next = kernelNext || localNext;\n\n const gapsSummary = gapCount ? `, ${gapCount} knowledge gaps detected` : \"\";\n const coherenceSummary = coherenceVerdict ? `, coherence: ${coherenceVerdict}` : \"\";\n const persistentSummary = persistentGaps?.length ? `, ${persistentGaps.length} persistent coherence gaps` : \"\";\n const summaryText = `Session review: ${data!.drafts.length} uncommitted, ${data!.committed.length} committed, ${suggestions.length} link suggestions${gapsSummary}${coherenceSummary}${persistentSummary}.`;\n return {\n content: [{ type: \"text\" as const, text: fullText }],\n structuredContent: {\n ok: true as const,\n summary: kernelSummary || summaryText,\n data: {\n drafts: data!.drafts.length,\n committed: data!.committed.length,\n uncommitted: data!.summary.uncommitted,\n suggestedLinks: suggestions.length,\n knowledgeGaps: gapCount ?? 0,\n ...(coherenceVerdict ? { coherenceVerdict } : {}),\n ...(persistentGaps?.length ? { persistentCoherenceGaps: persistentGaps.length } : {}),\n },\n next,\n _meta: kernelMeta,\n },\n };\n };\n\n const tool = server.registerTool(\"session-wrapup\", {\n title: \"Session Wrapup\",\n description: WRAPUP_TOOL_DESCRIPTION + \" Also known as: wrapup, finish.\",\n annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: false },\n inputSchema: wrapupSchema,\n }, thinWrapper(async (args) => {\n const parsed = parseOrFail(wrapupSchema, args);\n if (!parsed.ok) return parsed.result;\n\n const act = parsed.data.action ?? \"review\";\n return runWithToolContext({ tool: \"session-wrapup\", action: act }, () =>\n wrapupHandler({ action: act }),\n );\n }));\n trackWriteTool(tool);\n}\n\nexport { runWrapupReview, type WrapupReviewResult };\n","/**\n * Registry Manifest + Rules — synced configuration data.\n * BET-99 / ARCH-16 / ARCH-19\n *\n * ⚠ SYNCED from src/lib/coherence/registry-manifest.ts and\n * src/lib/coherence/rules/collection-registries.ts — do not edit here.\n * Run `npm run sync:coherence` to refresh.\n *\n * ENT-65 (FEAT-201): Cross-registry sync rules for CLASSIFICATION_MAP ↔ DEFAULT_COLLECTIONS\n * and CLASSIFICATION_MAP ↔ CLASSIFICATION_META were removed. These constants are seed-only.\n */\n\nimport type { CoherenceRule, RegistryRef } from \"./types.js\";\n\nexport const REGISTRY_MANIFEST: readonly RegistryRef[] = [\n // ── Canonical UI registries ──────────────────────────────────────\n // BET-143 Slice 4: ui-colors removed — color is now a field on collection docs (schema.ts).\n {\n id: \"routes\",\n path: \"src/lib/navigation.ts\",\n exportName: \"COLLECTION_ROUTES\",\n description: \"Collection slug to dedicated route path\",\n expectedCoverage: \"curated\",\n keyExtraction: \"object-keys\",\n },\n {\n id: \"gap-paths\",\n path: \"src/lib/navigation.ts\",\n exportName: \"GAP_PATHS\",\n description: \"Readiness gap ID to workspace-relative route path\",\n expectedCoverage: \"curated\",\n keyExtraction: \"object-keys\",\n },\n // BET-280 S3: display-fields removed — DISPLAY_FIELDS constant deleted, field display is now schema-driven.\n // BET-280 S3: brain-icons removed — COLLECTION_ICONS unexported, getCollectionIcon() is a local rendering fallback only.\n\n // ── Graph visualization registries ───────────────────────────────\n // BET-143 Slice 4: graph-colors and graph-type-colors removed.\n // Graph rendering uses local fallback palettes (canvas needs resolved hex/CSS vars, not DB reads).\n\n // ── Cortex registries ────────────────────────────────────────────\n {\n id: \"renderers\",\n path: \"src/lib/components/studio/renderers/index.ts\",\n exportName: \"COLLECTION_RENDERERS\",\n description: \"Custom Svelte renderer component per collection\",\n expectedCoverage: \"subset\",\n keyExtraction: \"object-keys\",\n },\n\n // ── Backend registries ───────────────────────────────────────────\n {\n id: \"classification-map\",\n path: \"convex/lib/seedClassificationRegistry.ts\",\n exportName: \"SEED_CLASSIFICATION_REGISTRY\",\n description: \"Seed-only (ENT-65): governance, nav group, ID prefix. Runtime reads from DB collection doc.\",\n expectedCoverage: \"curated\",\n keyExtraction: \"array-slug\",\n },\n // TEN-598: default-collections removed. Collection definitions live in system_collection_definitions (DB).\n] as const;\n\nexport const COLLECTION_REGISTRY_RULES: readonly CoherenceRule[] = [\n // ── Subset: specialized registries should only reference known collections ──\n // BET-143 Slice 4: brain-colors, graph-colors, graph-type-colors rules removed —\n // those registries were deleted when color moved to collection docs.\n // BET-280 S3: brain-icons rule removed — COLLECTION_ICONS unexported, no longer a registry.\n // BET-280 S3: display-fields rule removed — DISPLAY_FIELDS deleted, field display is schema-driven.\n {\n id: \"subset-renderers\",\n type: \"subset\",\n description: \"Renderers should only reference classified collections\",\n subject: \"renderers\",\n reference: \"classification-map\",\n },\n] as const;\n","/**\n * Coherence Engine — evaluates registry rules against resolved data (MCP sync).\n * BET-99 / ARCH-16 / ARCH-19\n *\n * ⚠ SYNCED from src/lib/coherence/engine.ts — do not edit here.\n * Run `npm run sync:coherence` to refresh.\n */\n\nimport type {\n CoherenceReport,\n CoherenceRule,\n CoherenceSnapshot,\n CoherenceViolation,\n ExpectedCoverage,\n RegistryRef,\n ResolvedRegistries,\n RuleSeverity,\n RuleType,\n} from './types.js';\n\nconst MAX_VIOLATIONS = 50; // RH6: cap to prevent snapshot bloat\n\nconst SEVERITY_RANK: Record<RuleSeverity, number> = { error: 0, warning: 1, info: 2 };\n\nfunction severityFromCoverage(coverage: ExpectedCoverage): RuleSeverity {\n switch (coverage) {\n case 'all':\n return 'error';\n case 'curated':\n return 'warning';\n case 'subset':\n return 'info';\n }\n}\n\ntype EvaluatorArgs = {\n rule: CoherenceRule;\n subjectRef: RegistryRef;\n subjectKeys: ReadonlySet<string>;\n referenceRef: RegistryRef;\n referenceKeys: ReadonlySet<string>;\n};\n\nfunction evaluateCoverage(args: EvaluatorArgs): CoherenceViolation[] {\n const { rule, subjectRef, subjectKeys, referenceKeys } = args;\n const severity = rule.severityOverride ?? severityFromCoverage(subjectRef.expectedCoverage);\n const violations: CoherenceViolation[] = [];\n\n for (const slug of referenceKeys) {\n if (!subjectKeys.has(slug)) {\n violations.push({\n ruleId: rule.id,\n ruleType: 'coverage',\n registryId: rule.subject,\n collectionSlug: slug,\n message: `\"${slug}\" missing from ${subjectRef.exportName} (${subjectRef.path})`,\n severity,\n fix: `Add \"${slug}\" to ${subjectRef.exportName} in ${subjectRef.path}`,\n });\n }\n }\n\n return violations;\n}\n\nfunction evaluateSync(args: EvaluatorArgs): CoherenceViolation[] {\n const { rule, subjectRef, subjectKeys, referenceRef, referenceKeys } = args;\n const violations: CoherenceViolation[] = [];\n\n for (const slug of referenceKeys) {\n if (!subjectKeys.has(slug)) {\n violations.push({\n ruleId: rule.id,\n ruleType: 'sync',\n registryId: rule.subject,\n collectionSlug: slug,\n message: `\"${slug}\" in ${referenceRef.exportName} but missing from ${subjectRef.exportName}`,\n severity: 'error',\n fix: `Add \"${slug}\" to ${subjectRef.exportName} in ${subjectRef.path}`,\n });\n }\n }\n\n for (const slug of subjectKeys) {\n if (!referenceKeys.has(slug)) {\n violations.push({\n ruleId: rule.id,\n ruleType: 'sync',\n registryId: referenceRef.id,\n collectionSlug: slug,\n message: `\"${slug}\" in ${subjectRef.exportName} but missing from ${referenceRef.exportName}`,\n severity: 'error',\n fix: `Add \"${slug}\" to ${referenceRef.exportName} in ${referenceRef.path}`,\n });\n }\n }\n\n return violations;\n}\n\nfunction evaluateSubset(args: EvaluatorArgs): CoherenceViolation[] {\n const { rule, subjectRef, subjectKeys, referenceRef, referenceKeys } = args;\n const severity = rule.severityOverride ?? severityFromCoverage(subjectRef.expectedCoverage);\n const violations: CoherenceViolation[] = [];\n\n for (const slug of subjectKeys) {\n if (!referenceKeys.has(slug)) {\n violations.push({\n ruleId: rule.id,\n ruleType: 'subset',\n registryId: rule.subject,\n collectionSlug: slug,\n message: `\"${slug}\" in ${subjectRef.exportName} is not a classified collection`,\n severity,\n fix: `Remove \"${slug}\" from ${subjectRef.exportName}, or add it to ${referenceRef.exportName}`,\n });\n }\n }\n\n return violations;\n}\n\nfunction evaluateImplication(args: EvaluatorArgs): CoherenceViolation[] {\n const { rule, subjectRef, subjectKeys, referenceRef, referenceKeys } = args;\n const severity = rule.severityOverride ?? severityFromCoverage(referenceRef.expectedCoverage);\n const violations: CoherenceViolation[] = [];\n\n for (const slug of subjectKeys) {\n if (!referenceKeys.has(slug)) {\n violations.push({\n ruleId: rule.id,\n ruleType: 'implication',\n registryId: referenceRef.id,\n collectionSlug: slug,\n message: `\"${slug}\" has ${subjectRef.description} but no ${referenceRef.description}`,\n severity,\n fix: `Add \"${slug}\" to ${referenceRef.exportName} in ${referenceRef.path}`,\n });\n }\n }\n\n return violations;\n}\n\nconst EVALUATORS: Record<RuleType, (args: EvaluatorArgs) => CoherenceViolation[]> = {\n coverage: evaluateCoverage,\n sync: evaluateSync,\n subset: evaluateSubset,\n implication: evaluateImplication,\n};\n\n/**\n * Evaluate coherence rules against resolved registry data.\n * Returns a structured report suitable for any renderer.\n *\n * Pass `checkedAt` explicitly for deterministic tests; defaults to Date.now().\n */\nexport function evaluateCoherence(\n manifest: readonly RegistryRef[],\n rules: readonly CoherenceRule[],\n resolved: ResolvedRegistries,\n checkedAt?: number,\n): CoherenceReport {\n const registryMap = new Map(manifest.map((r) => [r.id, r]));\n const allViolations: CoherenceViolation[] = [];\n\n for (const rule of rules) {\n const subjectRef = registryMap.get(rule.subject);\n if (!subjectRef) continue;\n\n const subjectKeys = resolved[rule.subject];\n if (!subjectKeys) continue;\n\n if (!rule.reference) continue;\n const referenceRef = registryMap.get(rule.reference);\n if (!referenceRef) continue;\n const referenceKeys = resolved[rule.reference];\n if (!referenceKeys) continue;\n\n allViolations.push(\n ...EVALUATORS[rule.type]({ rule, subjectRef, subjectKeys, referenceRef, referenceKeys }),\n );\n }\n\n allViolations.sort((a, b) => SEVERITY_RANK[a.severity] - SEVERITY_RANK[b.severity]);\n const capped = allViolations.slice(0, MAX_VIOLATIONS);\n\n return {\n checkedAt: checkedAt ?? Date.now(),\n totalRegistries: manifest.length,\n totalRules: rules.length,\n violations: capped,\n summary: {\n errors: capped.filter((v) => v.severity === 'error').length,\n warnings: capped.filter((v) => v.severity === 'warning').length,\n infos: capped.filter((v) => v.severity === 'info').length,\n total: capped.length,\n },\n };\n}\n\n/** Compress a full report into a compact snapshot for session persistence. */\nexport function toSnapshot(report: CoherenceReport, maxTopGaps = 10): CoherenceSnapshot {\n const topGaps = report.violations\n .filter((v) => v.severity !== 'info')\n .slice(0, maxTopGaps)\n .map((v) => ({\n registry: v.registryId,\n slug: v.collectionSlug,\n severity: v.severity,\n }));\n\n return {\n checkedAt: report.checkedAt,\n totalGaps: report.summary.total,\n topGaps,\n };\n}\n","/**\n * Filesystem Registry Resolver — MCP-specific.\n * BET-99 / FEAT-182 / ARCH-19\n *\n * Reads source files from the project root and extracts collection slug sets\n * using the keyExtraction hints from the registry manifest.\n *\n * Design constraints:\n * - Dev-time only. Synchronous I/O is acceptable — this runs in orient/wrapup/review,\n * not in response to user actions or page loads (BET-99 no-go #5).\n * - Heuristic parser, not AST-based (BET-99 no-go #8). Template literals with\n * expression interpolation are not supported; backtick strings are treated as\n * opaque (skipped to closing backtick). This is sufficient for the structured\n * registries in the manifest.\n * - Gracefully skips unreadable files — never throws to callers.\n */\n\nimport { readFileSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\nimport type { KeyExtraction, RegistryRef, ResolvedRegistries } from \"./types.js\";\n\n/**\n * Resolve all registries from source files, returning slug sets keyed by registry ID.\n * Silently skips registries whose files can't be read or parsed.\n */\nexport function resolveRegistries(\n projectRoot: string,\n manifest: readonly RegistryRef[],\n): ResolvedRegistries {\n if (!projectRoot) return {};\n\n const resolved: Record<string, ReadonlySet<string>> = {};\n\n for (const ref of manifest) {\n try {\n const filePath = resolve(projectRoot, ref.path);\n const content = readFileSync(filePath, \"utf-8\");\n const block = extractBlock(content, ref.exportName);\n if (!block) continue;\n\n const keys = extractKeys(block, ref.keyExtraction);\n if (keys.size > 0) {\n resolved[ref.id] = keys;\n }\n } catch (err) {\n if (process.env.DEBUG_COHERENCE) {\n console.debug(`[coherence] Skipping ${ref.id} (${ref.path}):`, err instanceof Error ? err.message : err);\n }\n }\n }\n\n return resolved;\n}\n\n// ── Block extraction ──────────────────────────────────────────────────────────\n\nfunction extractBlock(content: string, exportName: string): string | null {\n const escaped = exportName.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n const pattern = new RegExp(\n `(?:export\\\\s+)?(?:const|let|var)\\\\s+${escaped}\\\\b[^=]*=\\\\s*`,\n );\n const match = pattern.exec(content);\n if (!match) return null;\n\n let pos = match.index + match[0].length;\n while (pos < content.length && /\\s/.test(content[pos]!)) pos++;\n\n const ch = content[pos];\n\n if (ch === \"{\" || ch === \"[\") {\n return extractBalanced(content, pos, ch, ch === \"{\" ? \"}\" : \"]\");\n }\n\n // new Set([...])\n if (content.slice(pos).startsWith(\"new Set\") || content.slice(pos).startsWith(\"new\\nSet\") || content.slice(pos).startsWith(\"new\\n\\tSet\")) {\n const setMatch = content.slice(pos).match(/^new\\s+Set\\s*\\(\\s*\\[/);\n if (setMatch) {\n return extractBalanced(content, pos + setMatch[0].length - 1, \"[\", \"]\");\n }\n }\n\n return null;\n}\n\nfunction extractBalanced(\n content: string,\n openPos: number,\n openChar: string,\n closeChar: string,\n): string | null {\n let depth = 1;\n let i = openPos + 1;\n\n while (i < content.length && depth > 0) {\n const ch = content[i]!;\n\n if (ch === \"'\" || ch === '\"' || ch === \"`\") {\n i = skipString(content, i, ch);\n continue;\n }\n if (ch === \"/\" && i + 1 < content.length && content[i + 1] === \"/\") {\n while (i < content.length && content[i] !== \"\\n\") i++;\n continue;\n }\n if (ch === \"/\" && i + 1 < content.length && content[i + 1] === \"*\") {\n i += 2;\n while (i < content.length) {\n if (content[i] === \"/\" && i > 0 && content[i - 1] === \"*\") { i++; break; }\n i++;\n }\n continue;\n }\n\n if (ch === openChar) depth++;\n else if (ch === closeChar) depth--;\n i++;\n }\n\n if (depth !== 0) return null;\n return content.slice(openPos + 1, i - 1);\n}\n\n/**\n * Skip past a string literal. Handles single/double quotes with backslash escapes.\n * Template literals: skips to closing backtick but does NOT handle ${} interpolation —\n * nested braces inside template expressions may cause early termination. Acceptable\n * because registry files use simple string literals, not template expressions.\n */\nfunction skipString(content: string, start: number, quote: string): number {\n let i = start + 1;\n while (i < content.length) {\n const ch = content[i]!;\n if (ch === \"\\\\\") {\n i += 2;\n continue;\n }\n if (ch === quote) return i + 1;\n i++;\n }\n return i;\n}\n\n// ── Key extraction ────────────────────────────────────────────────────────────\n\nfunction extractKeys(block: string, extraction: KeyExtraction): Set<string> {\n switch (extraction) {\n case \"object-keys\":\n return extractObjectKeys(block);\n case \"array-slug\":\n return extractArraySlugs(block);\n case \"set-values\":\n return extractSetValues(block);\n }\n}\n\n/**\n * Extract top-level keys from an object literal block.\n * Tracks brace/bracket depth so nested property names are ignored.\n */\nfunction extractObjectKeys(block: string): Set<string> {\n const keys = new Set<string>();\n let depth = 0;\n let i = 0;\n\n while (i < block.length) {\n const ch = block[i]!;\n\n if (ch === \"/\" && i + 1 < block.length && block[i + 1] === \"/\") {\n while (i < block.length && block[i] !== \"\\n\") i++;\n continue;\n }\n if (ch === \"/\" && i + 1 < block.length && block[i + 1] === \"*\") {\n i += 2;\n while (i < block.length) {\n if (block[i] === \"/\" && i > 0 && block[i - 1] === \"*\") { i++; break; }\n i++;\n }\n continue;\n }\n\n // At depth 0, try matching quoted keys before consuming strings as values\n if (depth === 0) {\n const rest = block.slice(i);\n const quoted = rest.match(/^(['\"])([\\w-]+)\\1\\s*:/);\n if (quoted) {\n keys.add(quoted[2]!);\n i += quoted[0].length;\n continue;\n }\n const ident = rest.match(/^([\\w-]+)\\s*:/);\n if (ident) {\n keys.add(ident[1]!);\n i += ident[0].length;\n continue;\n }\n }\n\n if (ch === \"'\" || ch === '\"' || ch === \"`\") {\n i = skipString(block, i, ch);\n continue;\n }\n\n if (ch === \"{\" || ch === \"[\" || ch === \"(\") { depth++; i++; continue; }\n if (ch === \"}\" || ch === \"]\" || ch === \")\") { depth--; i++; continue; }\n\n i++;\n }\n\n return keys;\n}\n\nfunction extractArraySlugs(block: string): Set<string> {\n const slugs = new Set<string>();\n for (const m of block.matchAll(/slug:\\s*['\"](\\w[\\w-]*)['\"]/g)) {\n slugs.add(m[1]!);\n }\n return slugs;\n}\n\nfunction extractSetValues(block: string): Set<string> {\n const values = new Set<string>();\n for (const m of block.matchAll(/['\"](\\w[\\w-]*)['\"]/g)) {\n values.add(m[1]!);\n }\n return values;\n}\n","/**\n * Git-diff registry detection — FEAT-184 / BET-99.\n *\n * Detects whether files listed in the registry manifest were modified\n * since a given ref (or within the working tree). Uses conservative matching:\n * any change to a manifest-listed file triggers a coherence check.\n * False positives are cheap; false negatives are the failure mode (RH2).\n *\n * Dev-time only: uses synchronous `execSync` with a 5s timeout. Acceptable\n * because this runs at wrapup time, not in response to user actions (no-go #5).\n */\n\nimport { execSync } from \"node:child_process\";\nimport { REGISTRY_MANIFEST } from \"./data.js\";\n\n/**\n * Get the set of manifest file paths that have been modified.\n * Checks both staged and unstaged changes against the working tree.\n * Returns an empty set if git is unavailable or the command fails.\n */\nexport function detectTouchedRegistries(projectRoot: string): Set<string> {\n if (!projectRoot) return new Set();\n\n const manifestPaths = new Set(REGISTRY_MANIFEST.map((r) => r.path));\n const touched = new Set<string>();\n\n try {\n const raw = execSync(\"git diff --name-only HEAD 2>/dev/null || git diff --name-only\", {\n cwd: projectRoot,\n encoding: \"utf-8\",\n timeout: 5_000,\n });\n\n for (const line of raw.split(\"\\n\")) {\n const trimmed = line.trim();\n if (trimmed && manifestPaths.has(trimmed)) {\n touched.add(trimmed);\n }\n }\n } catch (err) {\n if (process.env.DEBUG_COHERENCE) {\n console.debug(\"[coherence] Git detection failed:\", err instanceof Error ? err.message : err);\n }\n }\n\n return touched;\n}\n\n/**\n * Quick boolean check: did this session's working tree touch any registry file?\n */\nexport function hasRegistryChanges(projectRoot: string): boolean {\n return detectTouchedRegistries(projectRoot).size > 0;\n}\n","/**\n * Codebase Coherence Check — MCP Integration Module.\n * BET-99 / FEAT-182 / ARCH-19\n *\n * Orchestrates the coherence pipeline: resolve registries from source files,\n * evaluate rules, produce markdown for orient/start, snapshot for persistence.\n *\n * Canonical engine: src/lib/coherence/ (ARCH-16).\n * This module syncs types, engine, and data; adds the filesystem resolver\n * and rendering that are MCP-specific.\n */\n\nimport { REGISTRY_MANIFEST, COLLECTION_REGISTRY_RULES } from \"./data.js\";\nimport { evaluateCoherence, toSnapshot } from \"./engine.js\";\nimport { resolveRegistries } from \"./resolver.js\";\nimport type { CoherenceReport, CoherenceSnapshot, CoherenceViolation, RuleSeverity } from \"./types.js\";\n\nexport type { CoherenceReport, CoherenceSnapshot, CoherenceViolation } from \"./types.js\";\nexport { toSnapshot } from \"./engine.js\";\nexport { detectTouchedRegistries, hasRegistryChanges } from \"./git-detection.js\";\n\n/**\n * Run the full coherence check pipeline.\n * Returns null if resolution fails (e.g. running outside a workspace).\n */\nexport function runCoherenceCheck(projectRoot: string): CoherenceReport | null {\n const resolved = resolveRegistries(projectRoot, REGISTRY_MANIFEST);\n\n // Need at least 2 resolved registries for any rule to evaluate\n if (Object.keys(resolved).length < 2) return null;\n\n return evaluateCoherence(REGISTRY_MANIFEST, COLLECTION_REGISTRY_RULES, resolved);\n}\n\n// ── Orient / Start rendering ──────────────────────────────────────────────────\n\nexport function renderCoherenceLines(report: CoherenceReport): string[] {\n const lines: string[] = [\"## Codebase Coherence\"];\n\n if (report.summary.total === 0) {\n lines.push(\"All registries aligned — no gaps detected.\");\n lines.push(\"\");\n return lines;\n }\n\n const parts: string[] = [];\n if (report.summary.errors > 0) parts.push(`${report.summary.errors} error${report.summary.errors === 1 ? \"\" : \"s\"}`);\n if (report.summary.warnings > 0) parts.push(`${report.summary.warnings} warning${report.summary.warnings === 1 ? \"\" : \"s\"}`);\n if (report.summary.infos > 0) parts.push(`${report.summary.infos} info`);\n lines.push(`**${report.summary.total} gap${report.summary.total === 1 ? \"\" : \"s\"}** across ${report.totalRegistries} registries (${parts.join(\", \")})`);\n\n const errors = report.violations.filter((v) => v.severity === \"error\");\n const warnings = report.violations.filter((v) => v.severity === \"warning\");\n\n if (errors.length > 0) {\n lines.push(\"\");\n lines.push(\"**Errors** (must fix):\");\n for (const v of errors.slice(0, 5)) {\n lines.push(`- ${v.message}`);\n }\n if (errors.length > 5) lines.push(`- ...and ${errors.length - 5} more`);\n }\n\n if (warnings.length > 0) {\n lines.push(\"\");\n lines.push(\"**Warnings**:\");\n for (const v of warnings.slice(0, 3)) {\n lines.push(`- ${v.message}`);\n }\n if (warnings.length > 3) lines.push(`- ...and ${warnings.length - 3} more`);\n }\n\n lines.push(\"\");\n return lines;\n}\n\n/**\n * One-call convenience: check + render + snapshot.\n * Returns null when coherence can't be checked (no filesystem access).\n */\nexport function checkAndRender(projectRoot: string): {\n lines: string[];\n snapshot: CoherenceSnapshot;\n} | null {\n const report = runCoherenceCheck(projectRoot);\n if (!report) return null;\n\n return {\n lines: renderCoherenceLines(report),\n snapshot: toSnapshot(report),\n };\n}\n\n// ── Delta rendering (FEAT-183 / FEAT-184) ────────────────────────────────────\n\nexport type CoherenceVerdict = \"improved\" | \"degraded\" | \"unchanged\";\n\nexport interface CoherenceDelta {\n before: CoherenceSnapshot;\n after: CoherenceSnapshot;\n gapsFixed: number;\n gapsIntroduced: number;\n netChange: number;\n verdict: CoherenceVerdict;\n}\n\n/**\n * Compare two snapshots to produce a delta with verdict.\n * Used by review workflow (FEAT-183) and session wrapup (FEAT-184).\n *\n * Note: `gapsFixed`/`gapsIntroduced` are derived from topGaps (capped at 10),\n * while `netChange` uses totalGaps (uncapped). When many gaps exist, the\n * itemized counts are a lower bound — the render copy reflects this.\n */\nexport function computeDelta(before: CoherenceSnapshot, after: CoherenceSnapshot): CoherenceDelta {\n const beforeSet = new Set(before.topGaps.map((g) => `${g.registry}::${g.slug}`));\n const afterSet = new Set(after.topGaps.map((g) => `${g.registry}::${g.slug}`));\n\n let gapsFixed = 0;\n for (const key of beforeSet) {\n if (!afterSet.has(key)) gapsFixed++;\n }\n let gapsIntroduced = 0;\n for (const key of afterSet) {\n if (!beforeSet.has(key)) gapsIntroduced++;\n }\n\n const netChange = after.totalGaps - before.totalGaps;\n const verdict: CoherenceVerdict =\n netChange < 0 ? \"improved\" : netChange > 0 ? \"degraded\" : \"unchanged\";\n\n return { before, after, gapsFixed, gapsIntroduced, netChange, verdict };\n}\n\n/**\n * Render a coherence delta as markdown lines for review or wrapup.\n * Gate logic: degraded → warning flag, improved → celebration, unchanged → neutral.\n */\nexport function renderCoherenceDelta(delta: CoherenceDelta): string[] {\n const lines: string[] = [\"### Coherence Delta\"];\n\n const p = (n: number) => n === 1 ? \"\" : \"s\";\n const absNet = Math.abs(delta.netChange);\n const approx = absNet > delta.gapsFixed + delta.gapsIntroduced;\n const prefix = approx ? \"at least \" : \"\";\n\n if (delta.verdict === \"improved\") {\n lines.push(\n `Registry coherence **improved**: ${prefix}${delta.gapsFixed} gap${p(delta.gapsFixed)} fixed` +\n (delta.gapsIntroduced > 0 ? `, ${delta.gapsIntroduced} introduced` : \"\") +\n ` (net ${delta.netChange}). ${delta.after.totalGaps} gap${p(delta.after.totalGaps)} remain${delta.after.totalGaps === 1 ? \"s\" : \"\"}.`,\n );\n } else if (delta.verdict === \"degraded\") {\n lines.push(\n `**Registry coherence degraded**: ${prefix}${delta.gapsIntroduced} new gap${p(delta.gapsIntroduced)} introduced` +\n (delta.gapsFixed > 0 ? `, ${delta.gapsFixed} fixed` : \"\") +\n ` (net +${delta.netChange}). ${delta.after.totalGaps} gap${p(delta.after.totalGaps)} total.`,\n );\n } else {\n lines.push(\n `Registry coherence unchanged. ${delta.after.totalGaps} gap${p(delta.after.totalGaps)} remain${delta.after.totalGaps === 1 ? \"s\" : \"\"}` +\n (delta.gapsFixed > 0 ? ` (${delta.gapsFixed} fixed, ${delta.gapsIntroduced} introduced)` : \"\") +\n \".\",\n );\n }\n\n lines.push(\"\");\n return lines;\n}\n\n/**\n * Coherence gate for review workflow Round 02 (FEAT-183).\n * Produces a pass/fail section comparing session-start snapshot against current state.\n * Gracefully degrades to absolute report when no prior snapshot exists.\n */\nexport function renderCoherenceGate(\n projectRoot: string,\n sessionSnapshot: CoherenceSnapshot | null,\n): { lines: string[]; verdict: CoherenceVerdict | \"no-baseline\"; afterSnapshot: CoherenceSnapshot | null } {\n const report = runCoherenceCheck(projectRoot);\n if (!report) {\n return {\n lines: [\"### Coherence Gate\", \"Could not run coherence check (filesystem unavailable).\", \"\"],\n verdict: \"no-baseline\",\n afterSnapshot: null,\n };\n }\n\n const afterSnapshot = toSnapshot(report);\n\n if (!sessionSnapshot) {\n const absolute = renderCoherenceLines(report);\n absolute[0] = \"### Coherence Gate (no baseline)\";\n absolute.splice(1, 0, \"_No session-start snapshot available — showing absolute state._\");\n return { lines: absolute, verdict: \"no-baseline\", afterSnapshot };\n }\n\n const delta = computeDelta(sessionSnapshot, afterSnapshot);\n const lines = renderCoherenceDelta(delta);\n\n if (delta.verdict === \"degraded\") {\n lines.push(\"**Gate: WARN** — This implementation introduced registry drift. Review the new gaps before shipping.\");\n\n const newGaps = delta.after.topGaps.filter(\n (g) => !delta.before.topGaps.some((b) => b.registry === g.registry && b.slug === g.slug),\n );\n if (newGaps.length > 0) {\n lines.push(\"\");\n lines.push(\"New gaps:\");\n for (const g of newGaps.slice(0, 5)) {\n lines.push(`- \\`${g.slug}\\` missing from \\`${g.registry}\\` (${g.severity})`);\n }\n if (newGaps.length > 5) lines.push(`- ...and ${newGaps.length - 5} more`);\n }\n lines.push(\"\");\n } else if (delta.verdict === \"improved\") {\n lines.push(\"**Gate: PASS** — Nice work, coherence improved this session.\");\n lines.push(\"\");\n } else {\n lines.push(\"**Gate: PASS** — No coherence change.\");\n lines.push(\"\");\n }\n\n return { lines, verdict: delta.verdict, afterSnapshot };\n}\n\n// ── Persistent gap detection + tension offers (BET-101 / Phase 6) ────────────\n\nexport interface PersistentGap {\n registry: string;\n slug: string;\n severity: RuleSeverity;\n violation: CoherenceViolation | null;\n}\n\n/**\n * Find gaps that persisted across the session (present in both before and after).\n * These are candidates for Chain capture as tensions — the session didn't fix them,\n * so they represent structural drift worth tracking.\n */\nexport function findPersistentGaps(\n delta: CoherenceDelta,\n currentViolations: CoherenceViolation[],\n): PersistentGap[] {\n const beforeSet = new Set(delta.before.topGaps.map((g) => `${g.registry}::${g.slug}`));\n const afterSet = new Set(delta.after.topGaps.map((g) => `${g.registry}::${g.slug}`));\n\n const persistentKeys = new Set<string>();\n for (const key of beforeSet) {\n if (afterSet.has(key)) persistentKeys.add(key);\n }\n\n if (persistentKeys.size === 0) return [];\n\n const violationMap = new Map<string, CoherenceViolation>();\n for (const v of currentViolations) {\n violationMap.set(`${v.registryId}::${v.collectionSlug}`, v);\n }\n\n return [...persistentKeys].map((key) => {\n const [registry = \"\", slug = \"\"] = key.split(\"::\", 2);\n return {\n registry,\n slug,\n severity: (delta.after.topGaps.find((g) => g.registry === registry && g.slug === slug)?.severity ?? \"warning\") as RuleSeverity,\n violation: violationMap.get(key) ?? null,\n };\n });\n}\n\n/**\n * Render offer-to-capture section for persistent gaps.\n * Lists each gap with a ready-to-use `capture` command template.\n * BET-101 no-go #3: never auto-create — this is an offer, not an action.\n */\nexport function renderPersistentGapOffers(gaps: PersistentGap[]): string[] {\n if (gaps.length === 0) return [];\n\n const lines: string[] = [\n \"### Persistent Coherence Gaps\",\n \"\",\n \"These gaps existed before and after this session — they represent structural registry drift.\",\n \"Want me to capture them as tensions on the Chain?\",\n \"\",\n ];\n\n const SEVERITY_RANK: Record<RuleSeverity, number> = { error: 0, warning: 1, info: 2 };\n const errorsFirst = [...gaps].sort((a, b) =>\n SEVERITY_RANK[a.severity] - SEVERITY_RANK[b.severity],\n );\n\n for (const gap of errorsFirst.slice(0, 5)) {\n const v = gap.violation;\n const fixHint = v?.fix ? ` — ${v.fix}` : \"\";\n lines.push(\n `- **\\`${gap.slug}\\`** missing from \\`${gap.registry}\\` (${gap.severity})${fixHint}`,\n );\n }\n\n if (errorsFirst.length > 5) {\n lines.push(`- ...and ${errorsFirst.length - 5} more`);\n }\n\n lines.push(\"\");\n lines.push(\n '_Say \"capture these as tensions\" to commit them to the Chain, or skip to continue._',\n );\n lines.push(\"\");\n\n return lines;\n}\n","/**\n * Shared project root resolution for MCP tools.\n *\n * Checks WORKSPACE_PATH, cwd, and parent of cwd for a Convex project\n * (convex/schema.ts marker). Returns null if no valid root is found.\n */\n\nimport { existsSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\n\nexport function resolveProjectRoot(): string | null {\n const candidates = [\n process.env.WORKSPACE_PATH,\n process.cwd(),\n // Parent of cwd: handles monorepo subpackages (e.g. packages/mcp-server)\n // where the Convex schema lives one level up.\n resolve(process.cwd(), \"..\"),\n ].filter(Boolean) as string[];\n\n for (const dir of candidates) {\n const resolved = resolve(dir);\n if (existsSync(resolve(resolved, \"convex/schema.ts\"))) return resolved;\n }\n return null;\n}\n","/**\n * Quality compound tool — check, re-evaluate.\n * Consolidates quality-check and re-evaluate into one tool.\n */\n\nimport { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { z } from \"zod\";\nimport { thinWrapper, success, failureResult, parseOrFail, unknownAction } from \"../envelope.js\";\nimport { kernelQuery, kernelMutation, getWorkspaceContext, requireWriteAccess, runWithToolContext } from \"../client.js\";\nimport { trackQualityCheck, trackQualityVerdict } from \"../analytics.js\";\nimport { trackWriteTool } from \"../tool-surface.js\";\nimport { checkEntryQuality, formatRubricVerdictSection } from \"./smart-capture.js\";\n\nconst QUALITY_ACTIONS = [\"check\", \"re-evaluate\"] as const;\n\nexport const qualitySchema = z.object({\n action: z.enum(QUALITY_ACTIONS).describe(\n \"'check': score an entry against quality criteria. 're-evaluate': trigger fresh evaluation.\",\n ),\n entryId: z.string().describe(\"Entry ID, e.g. 'TEN-graph-db', 'GT-019', 'SOS-006'\"),\n context: z.enum([\"capture\", \"commit\", \"review\"]).default(\"review\").optional()\n .describe(\"For re-evaluate: evaluation context\"),\n});\n\nexport const qualityCheckOutputSchema = z.object({\n entryId: z.string(),\n score: z.number(),\n maxScore: z.number(),\n criteria: z.array(z.object({\n name: z.string(),\n score: z.number(),\n maxScore: z.number(),\n met: z.boolean(),\n })),\n});\n\nexport const qualityReevaluateOutputSchema = z.object({\n entryId: z.string(),\n context: z.string(),\n score: z.number(),\n maxScore: z.number(),\n improved: z.boolean(),\n});\n\nexport function registerQualityTools(server: McpServer): void {\n const qualityTool = server.registerTool(\n \"quality\",\n {\n title: \"Quality\",\n description:\n \"Assess and re-evaluate entry quality. Two actions:\\n\\n\" +\n \"- **check**: Score an entry against collection-specific quality criteria. \" +\n \"Returns a scorecard with actionable suggestions. Includes link suggestions when relations are missing.\\n\" +\n \"- **re-evaluate**: Trigger a fresh quality evaluation. Returns heuristic verdict immediately, \" +\n \"schedules LLM evaluation in background.\",\n inputSchema: qualitySchema,\n annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false },\n },\n thinWrapper(async (args) => {\n const parsed = parseOrFail(qualitySchema, args);\n if (!parsed.ok) return parsed.result;\n\n const { action, entryId, context } = parsed.data;\n\n return runWithToolContext({ tool: \"quality\", action }, async () => {\n if (action === \"check\") {\n return handleCheck(entryId);\n }\n if (action === \"re-evaluate\") {\n return handleReEvaluate(entryId, context ?? \"review\");\n }\n\n return unknownAction(action, QUALITY_ACTIONS);\n });\n }),\n );\n trackWriteTool(qualityTool);\n}\n\nasync function handleCheck(entryId: string) {\n const result = await checkEntryQuality(entryId);\n\n const needsRelations = result.quality.checks.some(\n (c) => !c.passed && (c.id === \"has-relations\" || c.id === \"diverse-relations\"),\n );\n\n if (needsRelations) {\n try {\n const suggestions = await kernelQuery<{ suggestions?: Array<{ entryId: string; name: string; collectionSlug: string; recommendedRelationType: string; score: number }> }>(\"chain.graphSuggestLinks\", {\n entryId,\n maxHops: 2,\n limit: 3,\n });\n\n if ((suggestions?.suggestions?.length ?? 0) > 0) {\n const linkHints = (suggestions.suggestions ?? [])\n .map((s) => ` → \\`relations action=create from=\"${entryId}\" to=\"${s.entryId}\" type=\"${s.recommendedRelationType}\"\\` — ${s.name} [${s.collectionSlug}] (${s.score}/100)`)\n .join(\"\\n\");\n\n result.text += `\\n\\n## Suggested Links to Improve Quality\\n${linkHints}`;\n }\n } catch {\n // Graph suggestions failed — quality check still works without them\n }\n }\n\n try {\n const verdict = await kernelQuery<{ criteria?: unknown[]; canonicalKey?: string; tier?: string; passed?: boolean; source?: string; llmStatus?: string; llmDurationMs?: number; llmError?: string; rogerMartin?: unknown } | null>(\"quality.getLatestVerdictForEntry\", { entryId });\n if (verdict && verdict.criteria && verdict.criteria.length > 0) {\n result.text += \"\\n\\n\" + formatRubricVerdictSection(verdict);\n\n try {\n const wsForTracking = await getWorkspaceContext();\n trackQualityCheck(wsForTracking.workspaceId, {\n entry_id: entryId,\n entry_type: verdict.canonicalKey ?? \"\",\n tier: verdict.tier ?? \"\",\n passed: verdict.passed ?? false,\n source: verdict.source ?? \"\",\n llm_status: verdict.llmStatus,\n llm_duration_ms: verdict.llmDurationMs,\n llm_error: verdict.llmError,\n has_roger_martin: !!verdict.rogerMartin,\n });\n } catch { /* tracking is advisory */ }\n }\n } catch {\n // Rubric verdicts are advisory — quality check works without them\n }\n\n return {\n content: [{ type: \"text\" as const, text: result.text }],\n structuredContent: success(\n `Quality check for ${entryId}: ${result.quality.score}/${result.quality.maxScore}.`,\n {\n entryId,\n score: result.quality.score,\n maxScore: result.quality.maxScore,\n criteria: result.quality.checks.map((c) => ({\n name: c.label,\n score: c.passed ? 1 : 0,\n maxScore: 1,\n met: c.passed,\n })),\n },\n [\n { tool: \"graph\", description: \"Suggest connections\", parameters: { action: \"suggest\", entryId } },\n ],\n ),\n };\n}\n\nasync function handleReEvaluate(entryId: string, context: \"capture\" | \"commit\" | \"review\") {\n requireWriteAccess();\n const ws = await getWorkspaceContext();\n const result = await kernelMutation<{\n verdict: { canonicalKey?: string; tier?: string; passed?: boolean; criteria?: Array<{ passed: boolean; id: string; hint?: string }> };\n source?: string;\n } | null>(\"quality.reEvaluateEntry\", {\n entryId,\n context,\n });\n\n if (!result) {\n return failureResult(\n `Entry '${entryId}' not found or has no rubric.`,\n \"NOT_FOUND\",\n `Entry '${entryId}' not found or has no rubric.`,\n \"Use entries action=search to find the correct ID.\",\n [{ tool: \"entries\", description: \"Search entries\", parameters: { action: \"search\", query: entryId } }],\n );\n }\n\n const llmScheduled = result.verdict.tier !== \"passive\";\n const lines: string[] = [`Re-evaluated \\`${entryId}\\` in \\`${context}\\` context.`];\n lines.push(\"\");\n lines.push(formatRubricVerdictSection({\n ...result.verdict,\n source: result.source,\n llmStatus: llmScheduled ? \"pending\" : \"skipped\",\n }));\n\n try {\n trackQualityVerdict(ws.workspaceId, {\n entry_id: entryId,\n entry_type: result.verdict.canonicalKey ?? \"\",\n tier: result.verdict.tier ?? \"\",\n context,\n passed: result.verdict.passed ?? false,\n source: \"heuristic\",\n criteria_total: result.verdict.criteria?.length ?? 0,\n criteria_failed: result.verdict.criteria?.filter((c) => !c.passed).length ?? 0,\n llm_scheduled: llmScheduled,\n });\n } catch { /* tracking is advisory */ }\n\n const criteria = result.verdict.criteria ?? [];\n const reEvalScore = criteria.filter((c) => c.passed).length;\n const reEvalMaxScore = criteria.length;\n\n return {\n content: [{ type: \"text\" as const, text: lines.join(\"\\n\") }],\n structuredContent: success(\n `Re-evaluated ${entryId} in ${context} context. Score: ${reEvalScore}/${reEvalMaxScore}.`,\n {\n entryId,\n context,\n score: reEvalScore,\n maxScore: reEvalMaxScore,\n improved: result.verdict.passed ?? false,\n },\n ),\n };\n}\n","/**\n * Workflows compound tool — list, checkpoint, get-run.\n * Consolidates workflow discovery, checkpoint persistence, and run inspection.\n * Chain: FEAT-MCP-001 (MCP Server), BET-85\n */\n\nimport { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { z } from \"zod\";\nimport {\n getAgentSessionId,\n kernelQuery,\n kernelMutation,\n requireActiveSession,\n runWithToolContext,\n requireWriteAccess,\n} from \"../client.js\";\nimport { trackWriteTool } from \"../tool-surface.js\";\nimport { resolveCollection } from \"../lib/resolveCollection.js\";\nimport { thinWrapper, success, failure, validationResult, successResult, parseOrFail, unknownAction, type NextAction } from \"../envelope.js\";\nimport {\n getWorkflowDescriptor,\n getWorkflow,\n listWorkflows,\n type WorkflowDefinition,\n} from \"../workflows/definitions.js\";\nimport {\n describeWorkflowPrimaryOutput,\n getWorkflowSummaryCaptureDefinition,\n getWorkflowTemplateMetadata,\n} from \"../workflows/descriptor.js\";\nimport type {\n JsonValue,\n WorkflowRunOutput,\n WorkflowRunRenderProjection,\n} from \"../workflows/run-model.js\";\nimport { workflowRunOutputToText } from \"../workflows/run-model.js\";\n\nconst WORKFLOWS_ACTIONS = [\"list\", \"start\", \"checkpoint\", \"get-run\"] as const;\ntype WorkflowsAction = (typeof WORKFLOWS_ACTIONS)[number];\ntype WorkflowCheckpointOutputInput = string | WorkflowRunOutput;\n\nconst jsonValueSchema: z.ZodType<JsonValue> = z.lazy(() =>\n z.union([\n z.string(),\n z.number(),\n z.boolean(),\n z.null(),\n z.array(jsonValueSchema),\n z.record(jsonValueSchema),\n ]),\n);\n\nconst workflowRunOutputInputSchema: z.ZodType<WorkflowRunOutput> = z.union([\n z.object({\n format: z.literal(\"freetext\"),\n value: z.string(),\n }),\n z.object({\n format: z.literal(\"list\"),\n value: z.array(z.string()),\n }),\n z.object({\n format: z.literal(\"choice\"),\n value: z.union([z.string(), z.array(z.string())]),\n }),\n z.object({\n format: z.literal(\"structured\"),\n value: jsonValueSchema,\n }),\n]);\n\nexport const workflowsSchema = z.object({\n action: z.enum(WORKFLOWS_ACTIONS).describe(\n \"'list': browse available workflows. 'start': start or resume a workflow — returns first (or current) round and next-step checkpoint call. 'checkpoint': record round output or final summary. 'get-run': inspect a persisted workflow run.\",\n ),\n workflowId: z.string().optional().describe(\"Workflow ID for start, checkpoint, or get-run, e.g. 'retro', 'implementation-review'\"),\n runId: z.string().optional().describe(\"Workflow run ID: for get-run, which run to load; for checkpoint, target this run (avoids session drift — pass runId from get-run).\"),\n roundId: z.string().optional().describe(\"Round ID for checkpoint, e.g. 'what-went-well'\"),\n output: z.union([z.string(), workflowRunOutputInputSchema]).optional().describe(\n \"The round's output — either legacy synthesized text or a typed workflow run payload.\",\n ),\n isFinal: z.boolean().optional().describe(\"If true, finalize an existing durable workflow run from its terminal round and create the summary chain entry.\"),\n restart: z.boolean().optional().describe(\"If true, start a new durable run from the workflow's first round in the current session.\"),\n summaryName: z.string().optional().describe(\"Optional name for final chain entry. If omitted, the workflow summary template is used.\"),\n summaryDescription: z.string().optional().describe(\"Optional override for the final chain entry description. Defaults to the final round output text.\"),\n summaryEntryId: z.string().optional().describe(\"Link an existing entry as the run's summary instead of creating one. Used by facilitated workflows (e.g. shape) where the primary record is created by the specialized tool.\"),\n});\n\nfunction formatWorkflowCard(wf: WorkflowDefinition): string {\n const roundList = wf.rounds\n .map((r) => ` ${r.num}. ${r.label} (${r.type}, ~${r.maxDurationHint ?? \"?\"})`)\n .join(\"\\n\");\n const descriptor = getWorkflowDescriptor(wf.id);\n const outputDescription = descriptor\n ? describeWorkflowPrimaryOutput(descriptor)\n : wf.kbOutputCollection\n ? `Primary record routes to \\`${wf.kbOutputCollection}\\`.`\n : \"Primary output routing is resolved at runtime.\";\n\n return (\n `## ${wf.icon} ${wf.name}\\n` +\n `**ID**: \\`${wf.id}\\`\\n` +\n `${wf.shortDescription}\\n\\n` +\n `**Rounds** (${wf.rounds.length}):\\n${roundList}\\n\\n` +\n `**Output**: ${outputDescription}\\n` +\n `_Trigger via Facilitator Mode: say \"run retro\", \"shape this\", \"review implementation\", or \"process change\" in Cursor._`\n );\n}\n\n/**\n * Thin-wrapper contract for MCP workflow tools (TEN-667).\n *\n * MCP handles ONLY:\n * 1. Workflow definition lookup — definitions are MCP-local code (packages/mcp-server/src/workflows/)\n * 2. Round validation against the definition — requires local definition access\n * 3. Argument translation — coerce MCP text/string inputs to typed WorkflowRunOutput\n * 4. Collection pre-resolution — classifier mode requires an LLM action (cannot run in a mutation)\n * 5. Response formatting — MCP tool protocol envelope\n *\n * Everything else lives in Convex:\n * - Run state machine (create, advance, complete): lib/workflowRun.ts\n * - Persistence: chainwork/engine.ts (internal mutations, MCP gateway path)\n * - Public write surface for Brain/non-MCP consumers: chainwork/mutations.ts (TEN-667)\n * - Auth: requirePerson (public) or requireActiveWorkflowSession (internal/MCP)\n *\n * Do NOT add state machine logic, run lifecycle checks, or persistence here.\n */\n\nexport function validateFinalWorkflowCheckpoint(\n workflow: WorkflowDefinition,\n roundId: string,\n): string | null {\n const finalRound = workflow.rounds.at(-1);\n\n if (!finalRound) {\n return `Workflow '${workflow.id}' has no rounds and cannot create a final summary.`;\n }\n\n if (roundId !== finalRound.id) {\n return (\n `Workflow '${workflow.id}' can only create a final summary from its terminal round ` +\n `'${finalRound.id}' (${finalRound.label}).`\n );\n }\n\n return null;\n}\n\n// ─── Closest-match helpers (used for round ID self-correction) ──────────────\n// BET-78 (response envelope): errors must carry next-step commands agents can\n// execute directly. INS-61: design for the dumbest agent — if a round ID typo\n// causes a silent \"not found\", the agent retries blindly. Suggesting the\n// closest round turns a dead-end into a one-shot recovery.\n\nfunction levenshtein(a: string, b: string): number {\n const m = a.length;\n const n = b.length;\n const dp: number[][] = Array.from({ length: m + 1 }, (_, i) =>\n Array.from({ length: n + 1 }, (_, j) => (i === 0 ? j : j === 0 ? i : 0)),\n );\n for (let i = 1; i <= m; i++) {\n for (let j = 1; j <= n; j++) {\n dp[i][j] =\n a[i - 1] === b[j - 1]\n ? dp[i - 1][j - 1]\n : 1 + Math.min(dp[i - 1][j]!, dp[i][j - 1]!, dp[i - 1][j - 1]!);\n }\n }\n return dp[m][n]!;\n}\n\n/**\n * Returns the closest matching round for a given input ID, or null if no round\n * is similar enough to confidently suggest. Prioritises substring containment\n * over edit distance so \"orient-scope\" → \"orient\" works without needing a low\n * edit-distance threshold.\n */\nfunction findClosestRound(\n input: string,\n rounds: WorkflowDefinition[\"rounds\"],\n): WorkflowDefinition[\"rounds\"][number] | null {\n if (rounds.length === 0) return null;\n\n // Prefer substring containment (either direction) — catches truncations and\n // common over-hyphenation mistakes before paying for edit-distance.\n const substringMatch = rounds.find(\n (r) => r.id.includes(input) || input.includes(r.id),\n );\n if (substringMatch) return substringMatch;\n\n // Fall back to edit distance. Only suggest if distance ≤ half the longer\n // string — avoids wild guesses on completely unrelated IDs.\n let best = rounds[0]!;\n let bestDist = levenshtein(input, best.id);\n for (const r of rounds.slice(1)) {\n const dist = levenshtein(input, r.id);\n if (dist < bestDist) {\n bestDist = dist;\n best = r;\n }\n }\n\n const threshold = Math.ceil(Math.max(input.length, best.id.length) / 2);\n return bestDist <= threshold ? best : null;\n}\n\nexport function registerWorkflowTools(server: McpServer): void {\n const workflowsTool = server.registerTool(\n \"workflows\",\n {\n title: \"Workflows\",\n description:\n \"Chainwork workflow discovery, start/resume, checkpointing, and run inspection. Four actions:\\n\\n\" +\n \"- **list**: Browse available workflows — retro, shape-a-bet, implementation-review, process-change.\\n\" +\n \"- **start**: Start or resume a workflow. Call with workflowId (e.g. 'implementation-review', 'retro', 'shape', 'process-change'). \" +\n \"Returns the first (or current) round instructions and the exact checkpoint call to use when the round is complete. \" +\n \"Use this when the user says 'run implementation review', 'run retro', 'shape this', or 'process change' — it is the tool entry point for running a workflow.\\n\" +\n \"- **checkpoint**: Record round output during Facilitator Mode. Persists progress. \" +\n \"At completion, some workflows support isFinal=true to create the summary chain entry.\\n\" +\n \"- **get-run**: Inspect a persisted workflow run by run ID or by workflow ID in the current session.\",\n inputSchema: workflowsSchema,\n annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false },\n },\n thinWrapper(async (args) => {\n const parsed = parseOrFail(workflowsSchema, args);\n if (!parsed.ok) return parsed.result;\n\n const {\n action,\n workflowId,\n runId,\n roundId,\n output,\n isFinal,\n restart,\n summaryName,\n summaryDescription,\n summaryEntryId,\n } = parsed.data;\n\n return runWithToolContext({ tool: \"workflows\", action }, async () => {\n if (action === \"list\") {\n return handleList();\n }\n if (action === \"get-run\") {\n if (!runId && !workflowId) {\n return validationResult(\n \"runId or workflowId is required when action is 'get-run'.\",\n );\n }\n return handleGetRun(runId, workflowId);\n }\n if (action === \"start\") {\n if (!workflowId) {\n return validationResult(\n \"workflowId is required when action is 'start'. Use workflows action=list to see available workflow IDs.\",\n );\n }\n return handleStart(workflowId);\n }\n if (action === \"checkpoint\") {\n if (!workflowId || !roundId || output === undefined) {\n return validationResult(\n \"workflowId, roundId, and output are required when action is 'checkpoint'.\",\n );\n }\n return handleCheckpoint(\n workflowId,\n roundId,\n output,\n isFinal,\n restart,\n summaryName,\n summaryDescription,\n summaryEntryId,\n runId,\n );\n }\n\n return unknownAction(action, WORKFLOWS_ACTIONS);\n });\n }),\n );\n trackWriteTool(workflowsTool);\n}\n\nasync function handleList() {\n const workflows = listWorkflows();\n\n if (workflows.length === 0) {\n return successResult(\n \"No workflows registered yet. Check back after the workflow definitions are configured.\",\n \"No workflows registered yet.\",\n { workflows: [], total: 0 },\n );\n }\n\n const cards = workflows.map(formatWorkflowCard).join(\"\\n\\n---\\n\\n\");\n\n return {\n content: [{\n type: \"text\" as const,\n text:\n `# Available Chainwork Workflows\\n\\n` +\n `${workflows.length} workflow(s) available. Trigger via Facilitator Mode in Cursor (say \"run retro\", \"shape this\", \"review implementation\", or \"process change\").\\n\\n` +\n `---\\n\\n${cards}`,\n }],\n structuredContent: success(\n `Found ${workflows.length} workflow(s).`,\n {\n workflows: workflows.map((w) => ({\n id: w.id,\n name: w.name,\n rounds: w.rounds.length,\n outputCollection: w.kbOutputCollection ?? null,\n })),\n total: workflows.length,\n },\n ),\n };\n}\n\n/** TEN-244: Bridge for \"run workflow\" — start returns first (or current) round so agents have a tool entry point. */\nexport async function handleStart(workflowId: string) {\n requireActiveSession();\n const agentSessionId = getAgentSessionId();\n if (!agentSessionId) {\n return validationResult(\n \"Active agent session required to start a workflow. Ensure the client has an active session.\",\n );\n }\n\n const wf = getWorkflow(workflowId);\n if (!wf) {\n const available = listWorkflows().map((w) => w.id).join(\", \");\n return {\n content: [{\n type: \"text\" as const,\n text:\n `Workflow \"${workflowId}\" not found. Available: ${available}.\\n\\n` +\n `Use workflows action=list to see workflow names and round structure.`,\n }],\n structuredContent: failure(\n \"NOT_FOUND\",\n `Workflow '${workflowId}' not found.`,\n `Available: ${available}`,\n [{ tool: \"workflows\", description: \"List workflows\", parameters: { action: \"list\" } }],\n ),\n };\n }\n\n const firstRound = wf.rounds[0];\n if (!firstRound) {\n return validationResult(\n `Workflow '${workflowId}' has no rounds. Use workflows action=list to choose another workflow.`,\n );\n }\n\n // Resume: if there is an active run for this session+workflow, return current round and runId\n let run: PersistedWorkflowRun | null = null;\n try {\n run = await kernelQuery<PersistedWorkflowRun | null>(\"chainwork.getLatestWorkflowRun\", {\n agentSessionId,\n workflowId: wf.id,\n });\n } catch {\n // Proceed with start (no run yet)\n }\n\n const isResume = run?.status === \"active\" && run.currentRoundId != null;\n const round = isResume\n ? wf.rounds.find((r) => r.id === run!.currentRoundId) ?? firstRound\n : firstRound;\n\n const skillHint =\n wf.id === \"implementation-review\"\n ? \"Read the implementation-review skill (.cursor/skills/implementation-review/SKILL.md) for full facilitation instructions.\"\n : wf.id === \"shape\"\n ? \"Read the shaping skill (.cursor/skills/shaping/SKILL.md) for full facilitation instructions.\"\n : null;\n\n const nextStep =\n `When this round is complete, call \\`workflows\\` with \\`action=checkpoint\\`, \\`workflowId=\"${wf.id}\"\\`, \\`roundId=\"${round.id}\"\\`, and \\`output\\` set to the round's synthesized output.` +\n (run?.runId ? ` Pass \\`runId=\"${run.runId}\"\\` to checkpoint into the existing run.` : \"\");\n\n const lines = [\n isResume ? `# Resume: ${wf.name} (\\`${wf.id}\\`)` : `# Start: ${wf.name} (\\`${wf.id}\\`)`,\n \"\",\n `**Round ${round.num} — ${round.label}** (\\`${round.id}\\`)`,\n \"\",\n round.instruction,\n \"\",\n \"**Facilitator guidance:**\",\n round.facilitatorGuidance,\n \"\",\n \"**Next step:**\",\n nextStep,\n ...(skillHint ? [\"\", skillHint] : []),\n ];\n\n return {\n content: [{ type: \"text\" as const, text: lines.join(\"\\n\") }],\n structuredContent: success(\n isResume\n ? `Resume workflow ${wf.id} at round ${round.num} (${round.label}).`\n : `Start workflow ${wf.id} — round ${round.num} (${round.label}).`,\n {\n workflowId: wf.id,\n workflowName: wf.name,\n runId: run?.runId ?? null,\n round: {\n id: round.id,\n num: round.num,\n label: round.label,\n instruction: round.instruction,\n facilitatorGuidance: round.facilitatorGuidance,\n outputFormat: round.outputSchema.format,\n },\n nextStep: {\n action: \"checkpoint\",\n workflowId: wf.id,\n roundId: round.id,\n ...(run?.runId ? { runId: run.runId } : {}),\n },\n },\n [\n {\n tool: \"workflows\",\n description: `Checkpoint round ${round.num} when complete`,\n parameters: {\n action: \"checkpoint\",\n workflowId: wf.id,\n roundId: round.id,\n ...(run?.runId ? { runId: run.runId } : {}),\n },\n },\n ],\n ),\n };\n}\n\ninterface PersistedWorkflowRun {\n runId: string;\n agentSessionId: string;\n workflowId: string;\n workflowName: string;\n templateSlug: string;\n templateName: string;\n status: \"active\" | \"completed\";\n startedAt: string;\n completedAt: string | null;\n currentRoundId: string | null;\n checkpoints: Array<{\n roundId: string;\n output: WorkflowRunOutput;\n recordedAt: string;\n }>;\n summary: {\n docId: string | null;\n entryId: string;\n collection: string | null;\n capturedAt: string | null;\n } | null;\n projection: WorkflowRunRenderProjection;\n}\n\nexport async function handleGetRun(\n runId?: string,\n workflowId?: string,\n) {\n let run: PersistedWorkflowRun | null;\n if (runId) {\n run = await kernelQuery<PersistedWorkflowRun | null>(\"chainwork.getWorkflowRun\", {\n runId,\n });\n } else {\n requireActiveSession();\n\n const agentSessionId = getAgentSessionId();\n if (!agentSessionId) {\n return validationResult(\n \"Active session required for workflow run inspection by workflowId.\",\n );\n }\n\n run = await kernelQuery<PersistedWorkflowRun | null>(\"chainwork.getLatestWorkflowRun\", {\n agentSessionId,\n workflowId,\n });\n }\n\n if (!run) {\n const target = runId\n ? `workflow run '${runId}'`\n : `workflow '${workflowId}' in the current session`;\n return validationResult(`No persisted run found for ${target}.`);\n }\n\n if (workflowId && run.workflowId !== workflowId) {\n return validationResult(\n `Workflow run '${run.runId}' belongs to workflow '${run.workflowId}', not '${workflowId}'.`,\n );\n }\n\n const stepLines = run.projection.steps.map((step) => {\n const status = step.status.toUpperCase();\n const outputSummary = step.output\n ? ` — ${workflowRunOutputToText(step.output)}`\n : \"\";\n return `- ${step.num}. ${step.label} [${status}]${outputSummary}`;\n });\n\n const lines = [\n `# Workflow Run: ${run.workflowName}`,\n \"\",\n `- Run ID: \\`${run.runId}\\``,\n `- Workflow ID: \\`${run.workflowId}\\``,\n `- Status: ${run.status}`,\n `- Progress: ${run.projection.completedCount}/${run.projection.totalCount}`,\n `- Current round: ${run.currentRoundId ? `\\`${run.currentRoundId}\\`` : \"complete\"}`,\n `- Renderable sections: ${Object.keys(run.projection.render.links).length}/${run.projection.render.sections.length}`,\n `- Started: ${run.startedAt}`,\n ...(run.completedAt ? [`- Completed: ${run.completedAt}`] : []),\n ...(run.summary\n ? [`- Summary entry: \\`${run.summary.entryId}\\``]\n : []),\n \"\",\n \"## Steps\",\n ...stepLines,\n ];\n\n return {\n content: [{ type: \"text\" as const, text: lines.join(\"\\n\") }],\n structuredContent: success(\n `Loaded workflow run ${run.runId} (${run.workflowName}).`,\n run,\n run.summary\n ? [\n {\n tool: \"graph\",\n description: \"Discover connections for the summary entry\",\n parameters: { action: \"suggest\", entryId: run.summary.entryId },\n },\n ]\n : undefined,\n ),\n };\n}\n\nexport async function handleCheckpoint(\n workflowId: string,\n roundId: string,\n output: WorkflowCheckpointOutputInput,\n isFinal?: boolean,\n restart?: boolean,\n summaryName?: string,\n summaryDescription?: string,\n summaryEntryId?: string,\n runId?: string | null,\n) {\n const wf = getWorkflow(workflowId);\n if (!wf) {\n return {\n content: [{\n type: \"text\" as const,\n text:\n `Workflow \"${workflowId}\" not found. ` +\n `Available: ${listWorkflows().map((w) => w.id).join(\", \")}.\\n\\n` +\n `This checkpoint was NOT saved. Continue the conversation — the facilitator has the context.`,\n }],\n structuredContent: failure(\n \"NOT_FOUND\",\n `Workflow '${workflowId}' not found.`,\n \"Use workflows action=list to see available workflows.\",\n [{ tool: \"workflows\", description: \"List workflows\", parameters: { action: \"list\" } }],\n ),\n };\n }\n\n const round = wf.rounds.find((r) => r.id === roundId);\n if (!round) {\n const availableRounds = wf.rounds.map((r) => r.id).join(\", \");\n const closest = findClosestRound(roundId, wf.rounds);\n\n const correctionActions: NextAction[] = closest\n ? [\n {\n tool: \"workflows\",\n description: `Retry with corrected round ID '${closest.id}'`,\n parameters: { action: \"checkpoint\", workflowId, roundId: closest.id },\n },\n ]\n : [\n {\n tool: \"workflows\",\n description: \"List workflows to inspect round IDs\",\n parameters: { action: \"list\" },\n },\n ];\n\n const suggestionHint = closest ? ` Did you mean '${closest.id}'?` : \"\";\n\n return {\n content: [{\n type: \"text\" as const,\n text:\n `Round \"${roundId}\" not found in workflow \"${workflowId}\".${suggestionHint} ` +\n `Available rounds: ${availableRounds}.\\n\\n` +\n `This checkpoint was NOT saved. The conversation context is preserved — continue facilitating.`,\n }],\n structuredContent: failure(\n \"NOT_FOUND\",\n `Round '${roundId}' not found in workflow '${workflowId}'.`,\n closest\n ? `Did you mean '${closest.id}'? Available rounds: ${availableRounds}`\n : `Available rounds: ${availableRounds}`,\n correctionActions,\n ),\n };\n }\n\n const lines: string[] = [\n `## Checkpoint: Round ${round.num} — ${round.label}`,\n `Workflow: ${wf.name} (\\`${wf.id}\\`)`,\n \"\",\n ];\n\n if (restart && isFinal) {\n return validationResult(\n \"restart cannot be combined with isFinal. Restart from the first round, then continue the workflow normally.\",\n );\n }\n\n let normalizedOutput: WorkflowRunOutput;\n try {\n normalizedOutput = coerceWorkflowRunOutput(round, output);\n } catch (error: unknown) {\n const message = error instanceof Error ? error.message : String(error);\n return validationResult(message);\n }\n\n const outputPreview = workflowRunOutputToText(normalizedOutput);\n\n if (isFinal) {\n const finalCheckpointValidationError = validateFinalWorkflowCheckpoint(\n wf,\n roundId,\n );\n if (finalCheckpointValidationError) {\n return validationResult(finalCheckpointValidationError);\n }\n\n const descriptor = getWorkflowDescriptor(workflowId);\n const template = descriptor\n ? getWorkflowTemplateMetadata(descriptor)\n : { slug: wf.id, name: wf.name };\n const summaryCapture = descriptor\n ? getWorkflowSummaryCaptureDefinition(descriptor)\n : wf.kbOutputCollection && wf.kbOutputTemplate\n ? {\n routing: {\n mode: \"fixed\" as const,\n collection: wf.kbOutputCollection,\n },\n nameTemplate: wf.kbOutputTemplate.nameTemplate,\n descriptionField: wf.kbOutputTemplate.descriptionField,\n descriptionSource: \"final-output-text\" as const,\n }\n : null;\n\n if (!summaryCapture && !summaryEntryId) {\n return validationResult(\n `Workflow '${workflowId}' does not support final summary capture through workflows.checkpoint. Follow the workflow guidance and use capture directly for its primary record, or pass summaryEntryId to link an existing entry.`,\n );\n }\n\n requireWriteAccess();\n const agentSessionId = getAgentSessionId();\n if (!agentSessionId) {\n return validationResult(\n \"Active agent session required for workflow checkpoint persistence.\",\n );\n }\n\n if (summaryEntryId && !summaryCapture) {\n return handleFacilitatedFinalization(\n wf, descriptor, roundId, normalizedOutput, agentSessionId, summaryEntryId, lines, runId,\n );\n }\n\n // After the guards above, summaryCapture is guaranteed non-null:\n // - Line 523: both null → early return\n // - Line 537: summaryEntryId truthy + summaryCapture null → early return\n const resolvedSummaryCapture = summaryCapture!;\n\n\n const existingRun = await kernelQuery<PersistedWorkflowRun | null>(\n \"chainwork.getLatestWorkflowRun\",\n {\n agentSessionId,\n workflowId: wf.id,\n },\n );\n if (!existingRun) {\n return validationResult(\n `Workflow '${workflowId}' has no durable run to finalize yet. Record checkpoints for the earlier rounds first.`,\n );\n }\n\n try {\n // FEAT-157: Pre-resolve collection for classifier-mode workflows (two-call pattern, DEC-163).\n // The Convex mutation can't call the LLM action, so MCP orchestrates.\n let resolvedCollectionSlug: string | undefined;\n if (resolvedSummaryCapture.routing.mode === \"classifier\") {\n const classifyName = summaryName ?? wf.name;\n const classifyDesc = summaryDescription ?? outputPreview;\n const resolved = await resolveCollection({ name: classifyName, description: classifyDesc });\n if (resolved && resolved.tier !== \"low\") {\n resolvedCollectionSlug = resolved.collection;\n }\n }\n\n const result = await kernelMutation<{\n runId: string;\n summary: {\n docId: string;\n entryId: string;\n name: string;\n created: boolean;\n collection: string | null;\n };\n }>(\"chainwork.finalizeWorkflowRun\", {\n agentSessionId,\n workflowId: wf.id,\n workflowName: wf.name,\n templateSlug: template.slug,\n templateName: template.name,\n steps: wf.rounds.map((workflowRound) => ({\n roundId: workflowRound.id,\n num: workflowRound.num,\n label: workflowRound.label,\n type: workflowRound.type,\n outputField: workflowRound.outputSchema.field,\n outputFormat: workflowRound.outputSchema.format,\n })),\n finalRoundId: roundId,\n finalOutput: normalizedOutput,\n summaryCapture: {\n routing:\n resolvedSummaryCapture.routing.mode === \"fixed\"\n ? {\n mode: \"fixed\" as const,\n collection: resolvedSummaryCapture.routing.collection,\n }\n : {\n mode: \"classifier\" as const,\n },\n nameTemplate: resolvedSummaryCapture.nameTemplate,\n descriptionField: resolvedSummaryCapture.descriptionField,\n descriptionSource: resolvedSummaryCapture.descriptionSource,\n },\n summaryDescription,\n summaryName,\n resolvedCollectionSlug,\n });\n\n lines.push(\n result.summary.created\n ? `**Draft Created**: \\`${result.summary.entryId}\\``\n : `**Draft Already Exists**: \\`${result.summary.entryId}\\``,\n `Collection: \\`${result.summary.collection ?? (resolvedSummaryCapture.routing.mode === \"fixed\" ? resolvedSummaryCapture.routing.collection : \"classifier-routed\")}\\``,\n `Name: ${result.summary.name}`,\n \"\",\n `The summary is captured as a draft. Use \\`commit-entry entryId=\"${result.summary.entryId}\"\\` to promote it to the Chain.`,\n `Use \\`graph action=suggest entryId=\"${result.summary.entryId}\"\\` to discover connections.`,\n );\n\n return {\n content: [{ type: \"text\" as const, text: lines.join(\"\\n\") }],\n structuredContent: success(\n `Draft '${result.summary.name}' ${result.summary.created ? \"created\" : \"reused\"} (${result.summary.entryId}) for workflow ${workflowId}.`,\n {\n entryId: result.summary.entryId,\n workflowId,\n roundId,\n collection:\n result.summary.collection ??\n (resolvedSummaryCapture.routing.mode === \"fixed\"\n ? resolvedSummaryCapture.routing.collection\n : null),\n isFinal: true,\n runId: result.runId,\n created: result.summary.created,\n },\n [\n {\n tool: \"commit-entry\",\n description: \"Promote draft to Chain\",\n parameters: { entryId: result.summary.entryId },\n },\n {\n tool: \"graph\",\n description: \"Discover connections\",\n parameters: { action: \"suggest\", entryId: result.summary.entryId },\n },\n ],\n ),\n };\n } catch (err: unknown) {\n const msg = err instanceof Error ? err.message : String(err);\n lines.push(\n `**Chain commit failed**: ${msg}`,\n \"\",\n `The workflow output is preserved in this conversation. `,\n `You can manually create the entry later using \\`capture\\` with:`,\n `- Collection: \\`${resolvedSummaryCapture.routing.mode === \"fixed\" ? resolvedSummaryCapture.routing.collection : \"classifier-routed\"}\\``,\n `- Name: ${summaryName ?? resolvedSummaryCapture.nameTemplate}`,\n `- Description: ${summaryDescription ?? outputPreview}`,\n );\n\n return {\n content: [{ type: \"text\" as const, text: lines.join(\"\\n\") }],\n structuredContent: failure(\n \"BACKEND_ERROR\",\n `Chain commit failed: ${msg}.`,\n \"Capture manually with the capture tool.\",\n [{ tool: \"capture\", description: \"Capture manually\", parameters: {} }],\n ),\n };\n }\n } else {\n requireWriteAccess();\n const agentSessionId = getAgentSessionId();\n if (!agentSessionId) {\n return validationResult(\n \"Active agent session required for workflow checkpoint persistence.\",\n );\n }\n\n try {\n const descriptor = getWorkflowDescriptor(workflowId);\n const template = descriptor\n ? getWorkflowTemplateMetadata(descriptor)\n : { slug: wf.id, name: wf.name };\n const checkpointResult = await kernelMutation<{\n runId: string;\n run: { status: \"active\" | \"completed\"; currentRoundId: string | null };\n projection: {\n currentRoundId: string | null;\n completedCount: number;\n totalCount: number;\n };\n summary?: { entryId: string; linked: boolean };\n }>(\"chainwork.recordWorkflowCheckpoint\", {\n agentSessionId,\n workflowId: wf.id,\n workflowName: wf.name,\n templateSlug: template.slug,\n templateName: template.name,\n steps: wf.rounds.map((workflowRound) => ({\n roundId: workflowRound.id,\n num: workflowRound.num,\n label: workflowRound.label,\n type: workflowRound.type,\n outputField: workflowRound.outputSchema.field,\n outputFormat: workflowRound.outputSchema.format,\n })),\n checkpoint: {\n roundId,\n output: normalizedOutput,\n recordedAt: new Date().toISOString(),\n },\n restart,\n ...(runId ? { runId } : {}),\n ...(summaryEntryId ? { summaryEntryId } : {}),\n });\n\n lines.push(\n `Round ${round.num} output recorded.`,\n `Output: ${outputPreview.substring(0, 200)}${outputPreview.length > 200 ? \"...\" : \"\"}`,\n `Progress: ${checkpointResult.projection.completedCount}/${checkpointResult.projection.totalCount} rounds completed.`,\n );\n\n const nextWorkflowRound = checkpointResult.projection.currentRoundId\n ? wf.rounds.find((workflowRound) => workflowRound.id === checkpointResult.projection.currentRoundId)\n : undefined;\n const nextRound = nextWorkflowRound\n ? { id: nextWorkflowRound.id, num: nextWorkflowRound.num, label: nextWorkflowRound.label }\n : undefined;\n\n if (checkpointResult.summary?.linked) {\n lines.push(\n \"\",\n `**Run completed.** Summary linked to existing entry \\`${checkpointResult.summary.entryId}\\`.`,\n );\n } else if (nextWorkflowRound) {\n lines.push(\n \"\",\n `**Next**: Round ${nextWorkflowRound.num} — ${nextWorkflowRound.label}`,\n `_${nextWorkflowRound.instruction}_`,\n );\n } else {\n lines.push(\n \"\",\n `**All rounds complete.** Call this tool again with \\`isFinal: true\\` to commit to the Chain.`,\n );\n }\n\n return {\n content: [{ type: \"text\" as const, text: lines.join(\"\\n\") }],\n structuredContent: success(\n `Round ${round.num} (${round.label}) output recorded for workflow ${workflowId}.`,\n {\n workflowId,\n roundId,\n roundNum: round.num,\n roundLabel: round.label,\n isFinal: false,\n nextRound,\n runId: checkpointResult.runId,\n runStatus: checkpointResult.run.status,\n progress: {\n completedCount: checkpointResult.projection.completedCount,\n totalCount: checkpointResult.projection.totalCount,\n },\n },\n ),\n };\n } catch (err: unknown) {\n const msg = err instanceof Error ? err.message : String(err);\n lines.push(\n `**Checkpoint persistence failed**: ${msg}`,\n \"\",\n `The conversation context is preserved, but this round was not saved as a durable workflow checkpoint.`,\n );\n\n return {\n content: [{ type: \"text\" as const, text: lines.join(\"\\n\") }],\n structuredContent: failure(\n \"BACKEND_ERROR\",\n `Workflow checkpoint persistence failed: ${msg}.`,\n \"Continue the workflow in conversation or retry the checkpoint.\",\n ),\n };\n }\n }\n}\n\nasync function handleFacilitatedFinalization(\n wf: WorkflowDefinition,\n descriptor: ReturnType<typeof getWorkflowDescriptor>,\n roundId: string,\n normalizedOutput: WorkflowRunOutput,\n agentSessionId: string,\n summaryEntryId: string,\n lines: string[],\n runId?: string | null,\n) {\n const template = descriptor\n ? getWorkflowTemplateMetadata(descriptor)\n : { slug: wf.id, name: wf.name };\n\n try {\n const checkpointResult = await kernelMutation<{\n runId: string;\n run: { status: \"active\" | \"completed\"; currentRoundId: string | null };\n projection: {\n currentRoundId: string | null;\n completedCount: number;\n totalCount: number;\n };\n summary?: { entryId: string; linked: boolean };\n }>(\"chainwork.recordWorkflowCheckpoint\", {\n agentSessionId,\n workflowId: wf.id,\n workflowName: wf.name,\n templateSlug: template.slug,\n templateName: template.name,\n steps: wf.rounds.map((workflowRound) => ({\n roundId: workflowRound.id,\n num: workflowRound.num,\n label: workflowRound.label,\n type: workflowRound.type,\n outputField: workflowRound.outputSchema.field,\n outputFormat: workflowRound.outputSchema.format,\n })),\n checkpoint: {\n roundId,\n output: normalizedOutput,\n recordedAt: new Date().toISOString(),\n },\n summaryEntryId,\n ...(runId ? { runId } : {}),\n });\n\n const linked = checkpointResult.summary?.linked ?? false;\n lines.push(\n `**Run finalized**: Linked to existing entry \\`${summaryEntryId}\\`.`,\n `Status: ${checkpointResult.run.status}`,\n `Progress: ${checkpointResult.projection.completedCount}/${checkpointResult.projection.totalCount}`,\n );\n\n if (!linked && checkpointResult.run.status !== \"completed\") {\n lines.push(\n \"\",\n `Note: The run is not yet completed — the summary will be linked when all rounds are checkpointed.`,\n );\n }\n\n return {\n content: [{ type: \"text\" as const, text: lines.join(\"\\n\") }],\n structuredContent: success(\n `Workflow ${wf.id} finalized with linked entry ${summaryEntryId}.`,\n {\n entryId: summaryEntryId,\n workflowId: wf.id,\n roundId,\n isFinal: true,\n runId: checkpointResult.runId,\n linked,\n runStatus: checkpointResult.run.status,\n },\n [\n {\n tool: \"graph\",\n description: \"Discover connections\",\n parameters: { action: \"suggest\", entryId: summaryEntryId },\n },\n ],\n ),\n };\n } catch (err: unknown) {\n const msg = err instanceof Error ? err.message : String(err);\n lines.push(\n `**Finalization failed**: ${msg}`,\n \"\",\n `The workflow output is preserved in this conversation.`,\n );\n\n return {\n content: [{ type: \"text\" as const, text: lines.join(\"\\n\") }],\n structuredContent: failure(\n \"BACKEND_ERROR\",\n `Facilitated finalization failed: ${msg}.`,\n \"The facilitate tool's state is preserved — retry the checkpoint or continue in conversation.\",\n ),\n };\n }\n}\n\nexport function coerceWorkflowRunOutput(\n round: WorkflowDefinition[\"rounds\"][number],\n output: WorkflowCheckpointOutputInput,\n): WorkflowRunOutput {\n if (typeof output !== \"string\") {\n assertWorkflowRunOutputMatchesRound(round, output);\n return output;\n }\n\n const trimmed = output.trim();\n\n switch (round.outputSchema.format) {\n case \"freetext\":\n return { format: \"freetext\", value: trimmed };\n case \"list\":\n return { format: \"list\", value: parseListOutput(trimmed) };\n case \"choice\":\n return { format: \"choice\", value: trimmed };\n case \"structured\":\n return { format: \"structured\", value: { text: trimmed } };\n }\n}\n\nfunction assertWorkflowRunOutputMatchesRound(\n round: WorkflowDefinition[\"rounds\"][number],\n output: WorkflowRunOutput,\n): void {\n if (output.format !== round.outputSchema.format) {\n throw new Error(\n `Round '${round.id}' expects '${round.outputSchema.format}' output, received '${output.format}'.`,\n );\n }\n}\n\nexport function parseListOutput(output: string): string[] {\n const lines = output\n .split(\"\\n\")\n .map((line) => line.trim())\n .filter(Boolean)\n .map((line) => line.replace(/^[-*]\\s+/, \"\").replace(/^\\d+\\.\\s+/, \"\").trim())\n .filter(Boolean);\n\n return lines.length > 0 ? lines : [output];\n}\n","/**\n * BET-85 — Canonical workflow descriptor for ChainWork workflows.\n *\n * The MCP runtime still consumes `WorkflowDefinition`, but built-in workflows\n * are authored as `WorkflowDescriptor` objects and compiled to the runtime\n * shape. The descriptor is the authoring contract; the compiled definition is a\n * backward-compatible runtime view for existing MCP surfaces.\n */\n\nexport type WorkflowOutputFormat =\n | \"freetext\"\n | \"list\"\n | \"choice\"\n | \"structured\";\n\nexport interface WorkflowRound {\n id: string;\n num: string;\n label: string;\n type: \"open\" | \"choice\" | \"synthesis\" | \"commit\" | \"close\";\n instruction: string;\n facilitatorGuidance: string;\n questions?: WorkflowQuestion[];\n outputSchema: {\n field: string;\n description: string;\n format: WorkflowOutputFormat;\n };\n kbCollection?: string;\n maxDurationHint?: string;\n}\n\nexport interface WorkflowQuestion {\n id: string;\n prompt: string;\n options?: { id: string; label: string }[];\n allowMultiple?: boolean;\n required?: boolean;\n}\n\nexport interface WorkflowDefinition {\n id: string;\n name: string;\n shortDescription: string;\n icon: string;\n facilitatorPreamble: string;\n rounds: WorkflowRound[];\n kbOutputCollection?: string;\n kbOutputTemplate?: {\n nameTemplate: string;\n descriptionField: string;\n };\n errorRecovery: string;\n}\n\nexport type WorkflowPrimaryRecordRouting =\n | { mode: \"fixed\"; collection: string }\n | { mode: \"classifier\" };\n\nexport type WorkflowSummaryDescriptionSource =\n | \"final-output-text\"\n | { mode: \"step-output-field\"; field: string };\n\nexport interface WorkflowSummaryCapture {\n createsPrimaryRecord: boolean;\n nameTemplate: string;\n descriptionField?: string;\n descriptionSource?: WorkflowSummaryDescriptionSource;\n}\n\nexport interface WorkflowEmittedArtifact {\n kind: \"entry\" | \"update\";\n collection?: string;\n description: string;\n}\n\nexport interface WorkflowDescriptor {\n id: string;\n name: string;\n shortDescription: string;\n icon: string;\n facilitatorPreamble: string;\n rounds: WorkflowRound[];\n template: {\n slug: string;\n name: string;\n };\n output: {\n primaryRecord: {\n routing: WorkflowPrimaryRecordRouting;\n };\n summaryCapture?: WorkflowSummaryCapture;\n emits?: WorkflowEmittedArtifact[];\n };\n runtime: {\n kind: \"guided\" | \"facilitated\";\n primaryTool?: string;\n };\n errorRecovery: string;\n}\n\nfunction cloneWorkflowQuestion(question: WorkflowQuestion): WorkflowQuestion {\n return {\n ...question,\n options: question.options?.map((option) => ({ ...option })),\n };\n}\n\nfunction cloneWorkflowRound(round: WorkflowRound): WorkflowRound {\n return {\n ...round,\n questions: round.questions?.map(cloneWorkflowQuestion),\n outputSchema: { ...round.outputSchema },\n };\n}\n\nexport function cloneWorkflowDescriptor(\n descriptor: WorkflowDescriptor,\n): WorkflowDescriptor {\n return {\n ...descriptor,\n rounds: descriptor.rounds.map(cloneWorkflowRound),\n template: { ...descriptor.template },\n output: {\n primaryRecord: {\n routing:\n descriptor.output.primaryRecord.routing.mode === \"fixed\"\n ? {\n mode: \"fixed\",\n collection: descriptor.output.primaryRecord.routing.collection,\n }\n : { mode: \"classifier\" },\n },\n summaryCapture: descriptor.output.summaryCapture\n ? { ...descriptor.output.summaryCapture }\n : undefined,\n emits: descriptor.output.emits?.map((emitted) => ({ ...emitted })),\n },\n runtime: { ...descriptor.runtime },\n };\n}\n\nexport function cloneWorkflowDefinition(\n definition: WorkflowDefinition,\n): WorkflowDefinition {\n return {\n ...definition,\n rounds: definition.rounds.map(cloneWorkflowRound),\n kbOutputTemplate: definition.kbOutputTemplate\n ? { ...definition.kbOutputTemplate }\n : undefined,\n };\n}\n\nexport function validateWorkflowDescriptor(\n descriptor: WorkflowDescriptor,\n): void {\n if (descriptor.rounds.length === 0) {\n throw new Error(`Workflow '${descriptor.id}' must define at least one round.`);\n }\n\n const roundIds = new Set<string>();\n for (const [index, round] of descriptor.rounds.entries()) {\n if (roundIds.has(round.id)) {\n throw new Error(`Workflow '${descriptor.id}' has duplicate round id '${round.id}'.`);\n }\n roundIds.add(round.id);\n\n const expectedNum = String(index + 1).padStart(2, \"0\");\n if (round.num !== expectedNum) {\n throw new Error(\n `Workflow '${descriptor.id}' round '${round.id}' has num '${round.num}', expected '${expectedNum}'.`,\n );\n }\n\n const questionIds = new Set<string>();\n for (const question of round.questions ?? []) {\n if (questionIds.has(question.id)) {\n throw new Error(\n `Workflow '${descriptor.id}' round '${round.id}' has duplicate question id '${question.id}'.`,\n );\n }\n questionIds.add(question.id);\n }\n }\n\n if (\n descriptor.runtime.kind === \"facilitated\" &&\n !descriptor.runtime.primaryTool\n ) {\n throw new Error(\n `Workflow '${descriptor.id}' is facilitated and must define runtime.primaryTool.`,\n );\n }\n\n if (\n descriptor.output.summaryCapture?.createsPrimaryRecord &&\n descriptor.output.primaryRecord.routing.mode === \"fixed\" &&\n descriptor.output.summaryCapture.descriptionField === \"\"\n ) {\n throw new Error(\n `Workflow '${descriptor.id}' summaryCapture.descriptionField cannot be empty.`,\n );\n }\n}\n\nexport function getWorkflowSummaryCaptureDefinition(\n descriptor: WorkflowDescriptor,\n): {\n routing: WorkflowPrimaryRecordRouting;\n nameTemplate: string;\n descriptionField?: string;\n descriptionSource: WorkflowSummaryDescriptionSource;\n} | null {\n const { summaryCapture } = descriptor.output;\n const { routing } = descriptor.output.primaryRecord;\n\n if (!summaryCapture || !summaryCapture.createsPrimaryRecord) {\n return null;\n }\n\n return {\n routing:\n routing.mode === \"fixed\"\n ? { mode: \"fixed\", collection: routing.collection }\n : { mode: \"classifier\" },\n nameTemplate: summaryCapture.nameTemplate,\n descriptionField: summaryCapture.descriptionField,\n descriptionSource: summaryCapture.descriptionSource ?? \"final-output-text\",\n };\n}\n\nexport function getWorkflowPrimaryRecordCollection(\n descriptor: WorkflowDescriptor,\n): string | null {\n const { routing } = descriptor.output.primaryRecord;\n return routing.mode === \"fixed\" ? routing.collection : null;\n}\n\nexport function getWorkflowTemplateMetadata(\n descriptor: WorkflowDescriptor,\n): { slug: string; name: string } {\n return {\n slug: descriptor.template.slug,\n name: descriptor.template.name,\n };\n}\n\nexport function getWorkflowContextCollection(\n descriptor: WorkflowDescriptor,\n): string | null {\n return getWorkflowPrimaryRecordCollection(descriptor);\n}\n\nexport function describeWorkflowPrimaryOutput(\n descriptor: WorkflowDescriptor,\n): string {\n const { routing } = descriptor.output.primaryRecord;\n\n if (routing.mode === \"fixed\") {\n return `Primary record routes to \\`${routing.collection}\\`.`;\n }\n\n return \"Primary record is classifier-routed at runtime.\";\n}\n\nexport function compileWorkflowDefinition(\n descriptor: WorkflowDescriptor,\n): WorkflowDefinition {\n validateWorkflowDescriptor(descriptor);\n const clonedDescriptor = cloneWorkflowDescriptor(descriptor);\n const primaryRecordCollection = getWorkflowPrimaryRecordCollection(\n clonedDescriptor,\n );\n const summaryCapture = getWorkflowSummaryCaptureDefinition(clonedDescriptor);\n\n return {\n id: clonedDescriptor.id,\n name: clonedDescriptor.name,\n shortDescription: clonedDescriptor.shortDescription,\n icon: clonedDescriptor.icon,\n facilitatorPreamble: clonedDescriptor.facilitatorPreamble,\n rounds: clonedDescriptor.rounds,\n kbOutputCollection: primaryRecordCollection ?? undefined,\n kbOutputTemplate:\n summaryCapture && summaryCapture.routing.mode === \"fixed\"\n ? {\n nameTemplate: summaryCapture.nameTemplate,\n descriptionField: summaryCapture.descriptionField ?? \"description\",\n }\n : undefined,\n errorRecovery: clonedDescriptor.errorRecovery,\n };\n}\n","/**\n * Chainwork Workflow Definitions — ARCH-node-mcp (Core layer)\n * Chain: GT-006 (MCP), FEAT-MCP-001, BET-85\n *\n * Built-in workflows are authored as canonical descriptors, then compiled to the\n * current WorkflowDefinition runtime shape. This keeps runtime behavior stable\n * while giving BET-85 a single registry contract to build on.\n */\n\nimport {\n cloneWorkflowDefinition,\n cloneWorkflowDescriptor,\n compileWorkflowDefinition,\n type WorkflowDefinition,\n type WorkflowDescriptor,\n} from \"./descriptor.js\";\n\nexport type {\n WorkflowDefinition,\n WorkflowDescriptor,\n WorkflowQuestion,\n WorkflowRound,\n} from \"./descriptor.js\";\n\n// ── Retro Workflow ──────────────────────────────────────────────────────────\n\nconst RETRO_WORKFLOW_DESCRIPTOR: WorkflowDescriptor = {\n id: \"retro\",\n name: \"Retrospective\",\n shortDescription:\n \"Structured team retrospective — reflect, surface patterns, commit to actions. Commits a decision entry to the Chain.\",\n template: {\n slug: \"retro\",\n name: \"Retrospective\",\n },\n icon: \"◎\",\n facilitatorPreamble: `You are now in **Facilitator Mode**. You are not a coding assistant — you are a facilitator running a structured retrospective.\n\n## Your Behavior\n\n1. **Guide, don't solve.** Ask questions, reflect back, synthesize. Never jump to solutions.\n2. **One round at a time.** Complete each round fully before moving to the next. No skipping.\n3. **Use structured questions** (AskQuestion tool) for choices and multi-select. Use open conversation for reflection.\n4. **Create a Plan** at the start showing all rounds as tasks. Update it as you progress.\n5. **Synthesize between rounds.** After collecting input, reflect back what you heard before moving on.\n6. **Never go silent.** If something fails, say what happened and what to do next.\n7. **Finalize through the workflow substrate.** Complete the terminal round with \\`workflows action=checkpoint ... isFinal=true\\` so the durable run creates the retro draft record.\n8. **Session before checkpoint (default).** Before the **first** \\`workflows action=checkpoint\\` in this run, ensure an **active** agent write session: MCP \\`session action=start\\` or \\`pb session start\\` (DEC-9, STD-135). Inactive or superseded sessions commonly return **400** on checkpoint — durable progress is lost unless the chat record or a **handoff block** preserves it (see handoff skill: Facilitated workflow handoff).\n9. **Hand off mid-flight.** If the user switches agents or checkpoint keeps failing, emit the **Facilitated workflow handoff** package from \\`.productbrain/skills/handoff.md\\` (copy-paste block). Another agent resumes from that block + \\`workflows get-run\\` or \\`start\\` with \\`restart=true\\` — see workflow \\`errorRecovery\\`.\n10. **Match the energy.** Be warm but structured. This is a ceremony, not a checklist.\n\n## Communication Style\n\n- Start each round with its number, name, and a brief instruction\n- Use quotes and emphasis to reflect back what the participant said\n- End each round with a brief synthesis before transitioning\n- When a round is complete, mark it as done in the Plan\n- If the participant seems stuck, offer prompts — never pressure\n- If a tool call fails, explain what happened and offer an alternative path\n\n## Error Recovery\n\nIf at any point a tool call or MCP operation fails:\n1. Tell the participant what you were trying to do\n2. Explain what went wrong (briefly, no stack traces)\n3. Offer a manual alternative (e.g., \"I'll capture this in the conversation instead\")\n4. Continue the workflow — never halt completely\n\n## Plan Structure\n\nCreate a Cursor Plan with these rounds as tasks. Mark each in_progress as you enter it, completed when done.`,\n\n rounds: [\n {\n id: \"set-stage\",\n num: \"01\",\n label: \"Set the Stage\",\n type: \"choice\",\n instruction:\n \"Before we dive in, let's frame what we're reflecting on. What's the scope of this retro?\",\n facilitatorGuidance:\n \"Start warm. Ask the participant to pick or describe what they're retro-ing. Confirm the scope before proceeding. If they gave context already in their initial message, use it — don't make them repeat.\",\n questions: [\n {\n id: \"scope\",\n prompt:\n \"What are we reflecting on? Pick one or describe your own.\",\n options: [\n { id: \"last-week\", label: \"Last week's work\" },\n { id: \"last-sprint\", label: \"Last sprint/cycle\" },\n { id: \"specific-project\", label: \"A specific project or feature\" },\n { id: \"process\", label: \"A process or workflow\" },\n { id: \"custom\", label: \"Something else — let me describe it\" },\n ],\n },\n ],\n outputSchema: {\n field: \"scope\",\n description: \"What timeframe or project is being retro'd\",\n format: \"freetext\",\n },\n maxDurationHint: \"2 min\",\n },\n {\n id: \"what-went-well\",\n num: \"02\",\n label: \"What Went Well\",\n type: \"open\",\n instruction:\n \"Let's start with the good. What went well? What are you proud of? What should we do more of?\",\n facilitatorGuidance:\n \"Celebrate. Reflect back each win with genuine emphasis. Ask follow-ups like 'What made that work?' or 'Who else contributed to that?' Collect at least 3 items before synthesizing. Don't rush past the positive — teams skip this too fast.\",\n outputSchema: {\n field: \"wentWell\",\n description: \"List of things that went well\",\n format: \"list\",\n },\n maxDurationHint: \"5 min\",\n },\n {\n id: \"what-didnt-go-well\",\n num: \"03\",\n label: \"What Didn't Go Well\",\n type: \"open\",\n instruction:\n \"Now the harder part. What didn't go well? What frustrated you? Where did things break down?\",\n facilitatorGuidance:\n \"Create safety. Acknowledge that this is harder. Don't judge or immediately problem-solve — just listen and capture. Ask 'What was the impact of that?' and 'When did you first notice it?'. Reflect back without softening. Collect at least 3 items.\",\n outputSchema: {\n field: \"didntGoWell\",\n description: \"List of things that didn't go well\",\n format: \"list\",\n },\n maxDurationHint: \"5 min\",\n },\n {\n id: \"patterns\",\n num: \"04\",\n label: \"Patterns & Insights\",\n type: \"synthesis\",\n instruction:\n \"Looking at what went well and what didn't — what patterns do you see? What's the deeper insight?\",\n facilitatorGuidance:\n \"This is YOUR moment as facilitator. Synthesize what you've heard across rounds 2 and 3. Surface themes, connections, and contradictions. Propose 2-3 patterns and ask the participant to react. This round transforms raw observations into actionable insights. Don't let the participant skip the 'why' — push for root causes.\",\n outputSchema: {\n field: \"patterns\",\n description: \"Synthesized patterns and insights\",\n format: \"structured\",\n },\n maxDurationHint: \"5 min\",\n },\n {\n id: \"actions\",\n num: \"05\",\n label: \"Actions & Commitments\",\n type: \"commit\",\n instruction:\n \"Based on these patterns, what will we actually change? Be specific — who does what, by when?\",\n facilitatorGuidance:\n \"Push for specificity. 'Be better at X' is not an action. 'Randy will set up a 15-min weekly check-in by Friday' is. Each action needs an owner and a deadline. Aim for 2-4 concrete actions. Use AskQuestion to confirm the final list. These become the retro's output.\",\n questions: [\n {\n id: \"action-confirm\",\n prompt: \"Are these actions concrete enough to actually happen?\",\n options: [\n { id: \"yes\", label: \"Yes — these are clear and actionable\" },\n { id: \"refine\", label: \"Let me refine some of these\" },\n { id: \"add\", label: \"I want to add more\" },\n ],\n },\n ],\n outputSchema: {\n field: \"actions\",\n description: \"Committed actions with owners and deadlines\",\n format: \"structured\",\n },\n maxDurationHint: \"5 min\",\n },\n {\n id: \"close\",\n num: \"06\",\n label: \"Close & Capture\",\n type: \"close\",\n instruction:\n \"One last thing — in one sentence, what's the single most important thing you're taking away from this retro?\",\n facilitatorGuidance:\n \"Keep it brief. One sentence reflection. Then summarize the entire retro: scope, key wins, key pain points, patterns identified, actions committed. Finalize the durable run through \\`workflows action=checkpoint\\` with \\`isFinal=true\\` so the retro draft record is created via the workflow substrate. Then ask if they want to commit that draft to the Chain. Thank them for the retro.\",\n outputSchema: {\n field: \"takeaway\",\n description: \"Single-sentence takeaway\",\n format: \"freetext\",\n },\n kbCollection: \"decisions\",\n maxDurationHint: \"2 min\",\n },\n ],\n\n output: {\n primaryRecord: {\n routing: {\n mode: \"fixed\",\n collection: \"decisions\",\n },\n },\n summaryCapture: {\n createsPrimaryRecord: true,\n nameTemplate: \"Retro: {scope} — {date}\",\n descriptionField: \"rationale\",\n },\n },\n runtime: {\n kind: \"guided\",\n },\n\n errorRecovery: `If anything goes wrong during the retro:\n\n1. **MCP tool failure**: Skip the workflow finalization step. Summarize everything in the conversation instead. Suggest retrying \\`workflows action=checkpoint\\` later or capturing manually if needed.\n2. **AskQuestion not available**: Fall back to numbered options in plain text. \"Reply with 1, 2, or 3.\"\n3. **Plan creation fails**: Continue without the Plan. The conversation IS the record.\n4. **Participant goes off-topic**: Gently redirect: \"That's valuable — let's capture it. For now, let's stay with [current round].\"\n5. **Participant wants to stop**: Respect it. Summarize what you have so far. Offer to commit partial results to the Chain.\n6. **Checkpoint failed (e.g. 400, superseded session)**: Say so in one line. **Start or refresh session** (\\`session action=start\\` / \\`pb session start\\`), then \\`workflows action=get-run\\` with the \\`runId\\` you were given. If the run is **incomplete**, retry \\`checkpoint\\` with that \\`runId\\`. If the run is **complete** or **missing**, treat server state as unreliable: run \\`workflows action=start workflowId=retro restart=true\\` and **paste the Facilitated workflow handoff block** from the prior chat into round 1 so scope and completed rounds are explicit — do not assume partial server progress exists.\n7. **Cross-agent resume (default expectation)**: Receiving agent reads the handoff block first. Prefer \\`get-run\\` to verify status; otherwise **restart** and continue from the **next round** named in the handoff. The conversation + handoff block are valid SSOT when ChainWork did not persist checkpoints (TEN-917).\n\nThe retro must never fail silently. Always communicate state.`,\n};\n\n// ── Shape Workflow ──────────────────────────────────────────────────────────\n\nconst SHAPE_WORKFLOW_DESCRIPTOR: WorkflowDescriptor = {\n id: \"shape\",\n name: \"Shape a Bet\",\n shortDescription:\n \"Integration-aware shaping: maps the system before designing, traces five paths per element, \" +\n \"surfaces governance conflicts at design time. Scoring is in the shaping skill; uses capture and facilitate action=commit-constellation for Chain capture.\",\n template: {\n slug: \"shape-a-bet\",\n name: \"Shape a Bet\",\n },\n icon: \"◆\",\n facilitatorPreamble: `You are now in **Shaping Mode**. The shaping skill owns the facilitation loop end-to-end — read it for scoring rubrics, investigation patterns, and the capture flow.\n\nUse \\`capture\\` to create constellation entries (elements, risks, decisions, glossary terms) linked to the bet.\nUse \\`facilitate action=commit-constellation\\` to atomically commit the bet and all linked entries when the shape is complete.\nUse \\`workflows action=checkpoint\\` after each round to persist progress to the durable run.`,\n\n rounds: [\n {\n id: \"context\",\n num: \"01\",\n label: \"Gather Context\",\n type: \"open\",\n instruction:\n \"Before shaping, let's see what the Chain already knows. Search for related entries, business rules, and existing decisions.\",\n facilitatorGuidance:\n \"**Investigate proactively.** Spawn sub-agents in parallel: \" +\n \"(1) `explore` agent to search the codebase for code related to the bet topic — find modules, patterns, and pain points. \" +\n \"(2) `generalPurpose` agent to search the Chain: call `orient`, use `entries action=search` with keywords, surface related tensions, active bets, and applicable business rules. \" +\n \"Synthesize both into a 3-5 line context brief: what the codebase reveals, what the Chain knows, what governance applies. \" +\n \"Present with IDs and file paths. Build a system map: what modules, data flows, and contracts exist in this area today? \" +\n \"Check governance: do any principles, standards, or business rules constrain this design space? \" +\n \"Then transition: 'Here's what I found. Does this match the problem you're seeing?'\",\n outputSchema: {\n field: \"context\",\n description: \"System map, Chain context, governance constraints, related entries\",\n format: \"structured\",\n },\n maxDurationHint: \"5 min\",\n },\n {\n id: \"framing\",\n num: \"02\",\n label: \"Frame the Problem\",\n type: \"open\",\n instruction:\n \"What's the problem? Who's affected? What's the workaround today? How much time is this worth?\",\n facilitatorGuidance:\n \"This round covers problem clarity AND appetite. \" +\n \"Search the codebase for workarounds, TODOs, and hacks related to the problem — cite what you find as evidence. \" +\n \"Push with evidence: 'I found 3 workaround patterns in the codebase — this suggests the problem is bigger than it looks.' \" +\n \"Use AskQuestion for appetite: Small Batch (1-2 weeks) or Big Batch (6 weeks). \" +\n \"When both dimensions are well-covered, present the frame and ask for Frame Go confirmation. \" +\n \"If new terms surfaced, capture them to the glossary via `capture`. If tensions surfaced, capture them too.\",\n questions: [\n {\n id: \"appetite\",\n prompt: \"How much time is this idea worth? Not how long it'll take — how much are you willing to invest?\",\n options: [\n { id: \"small\", label: \"Small Batch — 1-2 weeks, focused scope\" },\n { id: \"big\", label: \"Big Batch — 6 weeks, full treatment\" },\n ],\n },\n {\n id: \"frame-go\",\n prompt: \"Frame Go — the problem is tight enough to shape a solution. Proceed to elements?\",\n options: [\n { id: \"go\", label: \"Frame Go — move to elements\" },\n { id: \"refine\", label: \"Refine the frame — something's not right\" },\n ],\n },\n ],\n outputSchema: {\n field: \"framing\",\n description: \"Confirmed problem statement and appetite\",\n format: \"structured\",\n },\n kbCollection: \"work-packages\",\n maxDurationHint: \"10 min\",\n },\n {\n id: \"elements\",\n num: \"03\",\n label: \"Find the Elements\",\n type: \"open\",\n instruction:\n \"What are the solution elements? Think breadboard level — places, affordances, connections. What's the architecture?\",\n facilitatorGuidance:\n \"**Investigate first.** Spawn sub-agents to search the codebase for affected modules, existing architecture patterns, and API boundaries. \" +\n \"Synthesize findings into 3-5 proposed solution elements at breadboard level, citing specific files and modules. \" +\n \"**Five-path trace per element:** For each element, trace: (1) what data flows through it, (2) what contracts it relies on, \" +\n \"(3) what contracts it alters, (4) what second-order effects downstream, (5) what happens at boundaries (batch, error, empty, scale). \" +\n \"Present proposals for user reaction: 'Based on the codebase, here are the elements I'd suggest.' \" +\n \"For each confirmed element, use `capture` with collection='features' to create a features entry linked to the bet via part_of. \" +\n \"For Big Batch: also investigate architecture — search for layer boundaries and dependency directions, then propose architecture. \" +\n \"Check business rules: do any elements conflict with governance surfaced in Round 1? \" +\n \"Capture new glossary terms and decisions as they surface. \" +\n \"Aim for 3-5 elements. When elements and architecture are well-covered, present for confirmation.\",\n outputSchema: {\n field: \"elements\",\n description: \"Core solution elements and architecture\",\n format: \"structured\",\n },\n kbCollection: \"features\",\n maxDurationHint: \"15 min\",\n },\n {\n id: \"derisking\",\n num: \"04\",\n label: \"De-risk — Rabbit Holes & No-Gos\",\n type: \"open\",\n instruction:\n \"What could go wrong? What are we NOT building? Walk through the solution slowly and find the risks.\",\n facilitatorGuidance:\n \"**Investigate first.** Spawn sub-agents to search the codebase for fragile code, tight coupling, missing tests, performance-sensitive paths, and external dependencies near the affected modules. \" +\n \"Propose risks with evidence: 'I found that X module has no tests and is tightly coupled to Y — this is a rabbit hole.' \" +\n \"Every confirmed risk MUST be captured using `capture` with collection='tensions' — each becomes a tensions entry linked to the bet via constrains. \" +\n \"Push for mitigations — every risk needs a patch or explicit acceptance. \" +\n \"Then declare no-gos: 'Based on what I've seen, I'd suggest these no-gos.' Every no-go MUST also be captured. \" +\n \"**Counter-Metric Mandate (STD-19):** If the derisking references any quantitative gates or metrics (accuracy targets, performance budgets, adoption thresholds), \" +\n \"stress-test them: 'What's the denominator? What gets excluded? What counter-metric would expose a false positive?' \" +\n \"A metric gate that can be gamed by abstaining or cherry-picking the population is not a gate — name the compound metric that can't be gamed. \" +\n \"When risks and boundaries are well-covered, present Shape Go gate: 'Is this buildable within the appetite?'\",\n questions: [\n {\n id: \"shape-go\",\n prompt: \"Shape Go — the solution fits the appetite and risks are managed. Proceed to validation?\",\n options: [\n { id: \"go\", label: \"Shape Go — move to validation\" },\n { id: \"cut\", label: \"Cut scope — this grew beyond appetite\" },\n { id: \"refine\", label: \"Refine — more de-risking needed\" },\n ],\n },\n ],\n outputSchema: {\n field: \"derisking\",\n description: \"Rabbit holes with patches, explicit no-gos\",\n format: \"structured\",\n },\n kbCollection: \"tensions\",\n maxDurationHint: \"10 min\",\n },\n {\n id: \"validation\",\n num: \"05\",\n label: \"Validate & Build Contract\",\n type: \"synthesis\",\n instruction:\n \"Check completeness. Generate the build contract. Review the full scorecard.\",\n facilitatorGuidance:\n \"Review the scorecard from the shaping skill's scoring rubric. Present it as a table. \" +\n \"Verify the 5 core ingredients: Problem, Appetite, Solution elements, Rabbit Holes, No-Gos. \" +\n \"For Big Batch: also verify Architecture, narrative hook, and value-flow annotations. \" +\n \"**System coherence confirmation:** Were all five paths traced for each element? State which interaction risks remain unverified — \" +\n \"these become explicit risks in the bet, not surprises during implementation. \" +\n \"**Vision narrative (TEN-281):** Write one paragraph — how does this bet serve the product vision? \" +\n \"**Test plan (TEN-281):** How will we know this is done? Concrete scenarios, not 'when tests pass.' \" +\n \"**Counter-Metric Mandate (STD-19):** If the scorecard or build contract contains metrics or gates, verify each has a denominator, a coverage rate, \" +\n \"and a counter-metric. Flag any gate that can be satisfied by abstaining or excluding the hard cases. \" +\n \"Present the build contract. Ask: 'Anything to adjust before we capture to the Chain?'\",\n outputSchema: {\n field: \"validation\",\n description: \"Completeness check result and build contract\",\n format: \"structured\",\n },\n maxDurationHint: \"5 min\",\n },\n {\n id: \"capture\",\n num: \"06\",\n label: \"Capture & Commit\",\n type: \"close\",\n instruction:\n \"Capture the pitch to the Chain. Commit draft entries. Connect the constellation.\",\n facilitatorGuidance:\n \"List all draft entries created during shaping (elements, risks, decisions, glossary terms). \" +\n \"Ask the user to confirm: 'Ready to commit these to the Chain?' \" +\n \"Call `facilitate action=commit-constellation` to atomically commit the bet and all linked entries. \" +\n \"Then `graph action=suggest entryId='<betId>'` to discover connections. \" +\n \"Create the top 3 suggested relations via `relations action=batch-create`. \" +\n \"Thank the user. State: what was shaped, how many constellation entries captured, what the implementer inherits.\",\n outputSchema: {\n field: \"capture\",\n description: \"Final capture summary — entries committed, relations created\",\n format: \"structured\",\n },\n kbCollection: \"work-packages\",\n maxDurationHint: \"5 min\",\n },\n ],\n\n output: {\n primaryRecord: {\n routing: {\n // BET-145 E6 / FEAT-468: shape workflow outputs route to work-packages collection (DEC-245, BET-230 S5).\n mode: \"fixed\",\n collection: \"work-packages\",\n },\n },\n emits: [\n {\n kind: \"entry\",\n collection: \"features\",\n description: \"Solution elements captured during shaping.\",\n },\n {\n kind: \"entry\",\n collection: \"tensions\",\n description: \"Risks and rabbit holes captured during shaping.\",\n },\n {\n kind: \"entry\",\n collection: \"decisions\",\n description: \"Decisions captured inline when they surface.\",\n },\n {\n kind: \"entry\",\n collection: \"glossary\",\n description: \"Glossary terms captured inline when they surface.\",\n },\n {\n kind: \"update\",\n collection: \"work-packages\",\n description: \"Work package status and no-go updates during finalize.\",\n },\n ],\n },\n runtime: {\n kind: \"guided\",\n },\n\n errorRecovery: `If anything goes wrong during shaping:\n\n1. **facilitate tool failure**: Continue the conversation. The shaping knowledge is in the chat. Suggest retrying the tool call or capturing manually later.\n2. **Chain capture failure (duplicate)**: The tool handles duplicates by linking existing entries. If it still fails, note the entry name and move on — capture manually after the session.\n3. **Score seems wrong**: Scoring is local to the shaping skill — re-apply the scoring rubric from the shaping SKILL.md against the conversation context. Scores are heuristic; the agent's judgment matters more than the number.\n4. **User wants to stop mid-session**: Respect it. Everything captured so far is on the Chain as drafts. Use \\`facilitate action=resume\\` to pick up later.\n5. **MCP server unreachable**: Run the shaping from conversation knowledge. Skip chain capture. Say: \"Product Brain is temporarily unavailable — I'll shape from our conversation and we can commit afterward.\"\n\nThe shaping must never fail silently. Always communicate state.`,\n};\n\n// ── Implementation Review Workflow ───────────────────────────────────────────\n//\n// Migration-ready: Same WorkflowDefinition structure as retro/shape.\n// When ChainBuilder/processTemplates Phase B adds facilitator workflows,\n// this becomes a built-in seed — no redesign needed (DEC-83, TEN-68).\n// PRI-5: Workspace-agnostic — uses generic tools (orient, quality, verify,\n// library docs via Context7 CLI) that work for any workspace. Not Product-OS-specific.\n\nconst IMPLEMENTATION_REVIEW_WORKFLOW_DESCRIPTOR: WorkflowDescriptor = {\n id: \"implementation-review\",\n name: \"Implementation Review\",\n shortDescription:\n \"Fix-as-you-go implementation review: finds issues, fixes them immediately, verifies, then proceeds. \" +\n \"Three expert lenses (Staff+ Engineer, CTO, Chain Coherence). Spawns sub-agents for code and test review. \" +\n \"Extracts learnings into standards/rules. Ends with BET/chain IDs. Commits an insight to the Chain.\",\n template: {\n slug: \"implementation-review\",\n name: \"Implementation Review\",\n },\n icon: \"✓\",\n facilitatorPreamble: `You are now in **Implementation Review Mode**. You orchestrate a structured review of work that was just built — not a conversation, but a tool-driven audit with sub-agent support.\n\n## Review scope (CRITICAL)\n\n- **Default scope is this conversation only.** Only the work discussed or produced in this conversation is in scope. Do not review or touch files, BETs, or work outside that scope unless the user explicitly expands it (e.g. \"also review the auth module\").\n- **Every file touched must be explicit.** Scope is not complete until you have listed every file that was touched (created, modified, or deleted) in the work under review. Use git status/diff and conversation context to enumerate them. The review then assesses holistic coherence: does this set of changes fit our system, bring us closer to our vision, and make our code and architecture cleaner?\n- **Infer scope first.** Use conversation context, git status/diff, and recent edits to determine which BET, feature, or files are in scope. Call orient/start and \\`context action=gather\\` with the inferred scope; do not ask the user to pick what to review unless it's ambiguous.\n- **Ask only to clarify boundaries.** If scope is ambiguous after inference, ask a single, focused question to clarify (e.g. \"Should this review include only the changes we just made, or the whole feature?\"). Do not ask open-ended \"what should we review?\" or \"which work area?\" unless inference failed.\n- **State scope explicitly in Round 01.** After orient and context gather, state in one sentence what is in scope (e.g. \"Scope: changes in this conversation for BET-72\" or \"Scope: files X, Y and BET-72\"). Confirm only if the user might reasonably expect something else.\n- **Sub-agents and tools are scope-bound.** When spawning sub-agents or calling verify/review-against-rules, restrict attention to the scoped work only. Do not audit or suggest changes to code outside the stated scope.\n\n## Your Behavior\n\n1. **Tool-heavy, not chat-heavy.** Each round calls specific tools: orient, quality, verify, chain-review, context action=gather, review-against-rules. Use Context7 **CLI** (\\`npx ctx7 library\\` then \\`npx ctx7 docs\\` — project-local after \\`npm install\\`; avoid cold \\`npx ctx7@latest\\` in short-timeout shells) for relevant testing and framework docs — not for Chain truth. Do not use Context7 MCP.\n2. **Spawn sub-agents** for parallel review: (a) code/architecture review, (b) test honesty (did we edit tests to pass or do they validate real behavior?). Max 2 agents in parallel, 30s budget each. **Constrain each sub-agent to the stated review scope only.**\n3. **Fix-as-you-go (FEAT-172).** When you find a HIGH or MEDIUM issue: fix it immediately, verify (lints, types), then proceed. The user sees clean work, not a list of issues. Only defer if estimated >5 min — capture deferred items as tensions. If user says \"skip\", capture as tension and continue.\n4. **Chain is SSOT.** Call orient or start first. Use entries action=search and context action=gather to load relevant BETs, DECs, BRs. If findings conflict with Chain entries, report the conflict and cite the entry ID.\n5. **One round at a time.** Complete each round before moving to the next. Checkpoint progress.\n6. **Extract learnings (FEAT-174).** After fixing issues, ask: is this a recurring pattern? Offer to capture structural patterns as standards or business rules so future reviews check automatically.\n7. **CRITICAL: End with BET/chain IDs.** The final output MUST include a single sentence: \"BET/feature IDs reviewed: [IDs]. [One-line summary of findings].\"\n8. **Never go silent.** If a tool fails, explain and continue. The conversation IS the backup.\n\n## Tool Usage\n\n- \\`orient\\` or \\`start\\` — governance, active bets, stale entries\n- \\`quality action=check entryId=\"<BET-ID>\"\\` — score against collection criteria\n- \\`chain-review action=gate chainEntryId=\"<id>\"\\` — coherence gate for chains\n- \\`verify\\` — glossary code mappings, cross-references vs codebase\n- \\`review-against-rules\\` (domain) — business rule compliance\n- \\`context action=gather task=\"implementation review for [BET-ID]\"\\` — related knowledge\n- Context7 CLI — \\`npx ctx7 library\\` then \\`npx ctx7 docs\\` for framework/testing docs (not Chain truth); prefer local \\`ctx7\\` from \\`node_modules\\` in this monorepo\n- \\`session-wrapup\\` — before close\n\n## Sub-Agent Classification (for test failures)\n\nWhen reviewing test results: (a) test staleness — code changed, test not updated; (b) regression — code broke behavior; (c) flaky/bad test — harness or timing issue.\n\n## Structured Verdict (CRITICAL)\n\nRound 05 MUST end with a structured verdict block containing exactly these five items:\n1. **Verdict:** Y (ship) or N (do not ship) — one word, no hedging.\n2. **What shipped:** One sentence describing what was built.\n3. **Why it matters:** One sentence on the problem this solves.\n4. **User benefit:** One sentence on the value for users.\n5. **How to validate:** One sentence on how to verify it works as intended.\n\nThis block is the final deliverable of the review. Everything else is supporting evidence.`,\n\n rounds: [\n {\n id: \"orient\",\n num: \"01\",\n label: \"Orient & Scope\",\n type: \"open\",\n instruction:\n \"Apply the Review scope rules: infer scope from this conversation, git diff, and recent edits (default = work in this conversation only). Enumerate every file touched (created, modified, deleted). Call orient or start, then context action=gather for the inferred BET/feature. State scope in one explicit sentence and list all files in scope. Only ask the participant if scope is ambiguous. The review will assess: holistic coherence with our system, whether this brings us closer to our vision, and whether it makes our code and architecture cleaner.\",\n facilitatorGuidance:\n \"Infer scope from conversation context, git status/diff, and recent edits — default is work in this conversation only. \" +\n \"List every file touched (created, modified, or deleted) in the work under review; scope is not complete without this list. \" +\n \"Call orient or start to load governance and active bets. \" +\n \"Use context action=gather task='implementation review for [inferred-BET-or-feature]' to load related entries. \" +\n \"State scope explicitly in one sentence (e.g. 'Scope: changes in this conversation for BET-72'). \" +\n \"Present: stated scope, the full list of files touched, relevant BETs/DECs/BRs, and any stale entries orient surfaces. \" +\n \"Frame the review: we will assess holistic coherence with our system, whether this brings us closer to our vision, and whether it makes our code and architecture cleaner. \" +\n \"Ask the participant only if scope is ambiguous (e.g. 'Only the files we changed, or the whole feature?'). \" +\n \"Note vision anchors (principles, strategy, active bet constraints) — you will reference these in Rounds 02–05.\",\n outputSchema: {\n field: \"scope\",\n description: \"Explicit scope statement, every file touched, BET/feature IDs, related Chain context, vision anchors\",\n format: \"structured\",\n },\n maxDurationHint: \"2 min\",\n },\n {\n id: \"standards-review\",\n num: \"02\",\n label: \"Standards & Chain Coherence\",\n type: \"open\",\n instruction:\n \"Run quality check, chain-review gate (if applicable), review-against-rules, and codebase coherence gate. \" +\n \"Is the implementation coherent with the Chain SSOT? Did it introduce or fix registry drift?\",\n facilitatorGuidance:\n \"For the BET/entry: quality action=check entryId='<ID>'. \" +\n \"If the work produced a chain artifact: chain-review action=gate. \" +\n \"Call review-against-rules with the relevant domain (e.g. 'Governance & Decision-Making'). \" +\n \"**Codebase Coherence Gate (BET-99/FEAT-183):** Compare the Codebase Coherence section from Round 01's orient output \" +\n \"against the current state. If orient showed coherence gaps and this implementation touched registry files \" +\n \"(collection colors, routes, classification, renderers, etc.), check whether gaps increased or decreased. \" +\n \"Gaps increased → flag as 'Coherence: WARN — N new gaps introduced' and list them. \" +\n \"Gaps decreased → celebrate as 'Coherence: PASS — N gaps fixed.' \" +\n \"No change → note as 'Coherence: PASS — no change.' \" +\n \"If Round 01 did not show a coherence section, skip the gate — do not block on missing baseline. \" +\n \"Present: quality score, gate result, rule compliance, coherence gate verdict.\",\n outputSchema: {\n field: \"standards\",\n description:\n \"Quality score, gate result, rule compliance, coherence gate verdict (improved/degraded/unchanged)\",\n format: \"structured\",\n },\n maxDurationHint: \"5 min\",\n },\n {\n id: \"code-and-tests\",\n num: \"03\",\n label: \"Code & Test Honesty\",\n type: \"open\",\n instruction:\n \"Spawn sub-agents to review implementation and tests for the stated scope only. Fix every HIGH/MEDIUM finding before proceeding. Did we meet high standards? Are tests validating real behavior or did we edit them just to pass?\",\n facilitatorGuidance:\n \"Restrict all review to the scope stated in Round 01 (by default, work in this conversation only). \" +\n \"Spawn 1–2 sub-agents in parallel: (1) explore agent — code review, architecture boundaries, type-safety for scoped files only. \" +\n \"(2) explore agent — test review for scoped code: are tests asserting real behavior or were they edited to pass? \" +\n \"Pass the scope (files/BET) explicitly to sub-agents so they do not touch other work. \" +\n \"Use Context7 CLI (npx ctx7 library/docs) for relevant testing and framework best practices if needed. \" +\n \"Classify any test failures: staleness, regression, or flaky. \" +\n \"**Fix-as-you-go (FEAT-172):** For every HIGH/MEDIUM finding: fix immediately, run lints, verify types. \" +\n \"Only defer fixes estimated >5 min — capture deferred items as tensions on the Chain. \" +\n \"After fixing, do a boy-scout pass on each scoped file: clean imports, improve naming, remove dead code. \" +\n \"**Counter-Metric Mandate (STD-19):** When reporting test coverage, accuracy, or any quantitative result, \" +\n \"include the denominator, what was excluded, and at least one counter-metric. \" +\n \"Never report accuracy without recall. Never report pass rate without coverage. \" +\n \"Synthesize: findings, fixes applied, implementation grade, test honesty verdict.\",\n outputSchema: {\n field: \"codeAndTests\",\n description: \"Implementation grade, test honesty, refactor suggestions\",\n format: \"structured\",\n },\n maxDurationHint: \"10 min\",\n },\n {\n id: \"chain-validation\",\n num: \"04\",\n label: \"Chain Validation & Learning Extraction\",\n type: \"synthesis\",\n instruction:\n \"Run verify. Check orient for stale entries. Is the Chain current with the codebase? \" +\n \"Then extract learnings: did this review surface structural patterns that should become standards or rules?\",\n facilitatorGuidance:\n \"**Chain validation:** Call verify (report mode) — checks glossary code mappings and cross-references. \" +\n \"Orient surfaces stale entries (per workspace governance). Present trust score and any drift. \" +\n \"If drift found: fix immediately via update-entry (with changeNote). \" +\n \"**Learning extraction (FEAT-174, TEN-272):** Review all findings from Rounds 02 and 03. \" +\n \"Ask: did this review surface a structural pattern that could recur? \" +\n \"For each pattern: could it be a standard ('We always do X this way'), a business rule ('The system must do X'), \" +\n \"or a lint rule (automated check)? Offer to capture. \" +\n \"Also offer to capture any decisions, tensions, or new terms surfaced during the review. \" +\n \"The goal: today's bug becomes tomorrow's automated check (TEN-272).\",\n outputSchema: {\n field: \"chainValidation\",\n description: \"Verify trust score, drift fixes, extracted learnings (patterns → standards/rules)\",\n format: \"structured\",\n },\n maxDurationHint: \"5 min\",\n },\n {\n id: \"synthesis\",\n num: \"05\",\n label: \"Synthesis & Sign-Off\",\n type: \"commit\",\n instruction:\n \"Synthesize the review. Answer: Does this bring us closer to our vision and make our code and architecture cleaner? \" +\n \"With fix-as-you-go, most issues are already resolved — summarize what was fixed, not what's left. End with BET/chain IDs.\",\n facilitatorGuidance:\n \"Present the full synthesis: standards pass/fail, code grade, test honesty, chain validation, fixes applied. \" +\n \"**Vision delta:** Cite specific principles/strategy entries from Round 01. Answer: does this bring us closer to [cited vision]? \" +\n \"**Counter-Metric Mandate (STD-19):** For EVERY quantitative result you present, you MUST include: \" +\n \"(1) the denominator — what is the total population measured, (2) the coverage/abstention rate — what was excluded, \" +\n \"(3) at least one counter-metric that tells the opposite story (recall vs precision, error rate vs success rate), \" +\n \"(4) the 'student exam' reframe — score on the full exam, not just questions answered. \" +\n \"**Red-team your own synthesis:** Before presenting, ask yourself: 'What's the worst honest interpretation of these numbers? \" +\n \"What metric looks good but hides a real problem? What would a skeptic challenge?' Present that alongside the headline. \" +\n \"Recommend: ship, ship with conditions, or do not ship. \" +\n \"CRITICAL: The output MUST end with one sentence: 'BET/feature IDs reviewed: [IDs]. [One-line summary].' \" +\n \"Example: 'BET-xxx, STD-xxx reviewed. Conditional ship — fix [specific issues] and add [missing tests].' \" +\n \"**Structured Verdict Block (REQUIRED):** After the full synthesis, present the verdict block with exactly 5 items: \" +\n \"(1) Verdict: Y or N — one word. (2) What shipped: one sentence. (3) Why it matters: one sentence on the problem solved. \" +\n \"(4) User benefit: one sentence on value for users. (5) How to validate: one sentence on verification. \" +\n \"This block is the final deliverable. Everything else is supporting evidence.\",\n outputSchema: {\n field: \"synthesis\",\n description: \"Full review synthesis with vision delta, fixes applied, BET/chain IDs, and structured verdict block\",\n format: \"structured\",\n },\n maxDurationHint: \"3 min\",\n },\n {\n id: \"capture\",\n num: \"06\",\n label: \"Capture & Close\",\n type: \"close\",\n instruction:\n \"Finalize the review as an insight draft. Connect new entries from learning extraction. Use session-wrapup. Thank the participant.\",\n facilitatorGuidance:\n \"Summarize the review for finalization. Complete the terminal round through \\`workflows action=checkpoint\\` with \\`isFinal=true\\` so the workflow substrate creates the draft insight record. \" +\n \"Include: BET/feature IDs, verdict, key findings, fixes applied, and the structured verdict block from Round 05. \" +\n \"The insight description MUST include the 5-item verdict block (verdict Y/N, what shipped, why it matters, user benefit, how to validate). \" +\n \"If learnings were captured in Round 04: run graph action=suggest for each new entry, then relations action=batch-create. \" +\n \"Run session-wrapup before closing. \" +\n \"Thank the participant. State what was fixed, what was captured, what was deferred.\",\n outputSchema: {\n field: \"capture\",\n description: \"Insight entry created, BET IDs referenced, learnings connected\",\n format: \"structured\",\n },\n kbCollection: \"insights\",\n maxDurationHint: \"3 min\",\n },\n ],\n\n output: {\n primaryRecord: {\n routing: {\n mode: \"fixed\",\n collection: \"insights\",\n },\n },\n summaryCapture: {\n createsPrimaryRecord: true,\n nameTemplate: \"Implementation Review — {date}\",\n descriptionField: \"description\",\n descriptionSource: {\n mode: \"step-output-field\",\n field: \"synthesis\",\n },\n },\n },\n runtime: {\n kind: \"guided\",\n },\n\n errorRecovery: `If anything goes wrong during implementation review:\n\n1. **Tool failure**: Explain what failed. Continue with what you have. The conversation is the record.\n2. **Sub-agent timeout**: Proceed without that agent's output. Note what wasn't checked.\n3. **Context7 CLI unavailable** (e.g. auth/network): Skip library doc validation. Rely on Chain and codebase review.\n4. **MCP unreachable**: Run from conversation knowledge. Summarize findings. Offer to capture manually later.\n\nThe review must never fail silently. Always end with BET/chain IDs.`,\n};\n\n// ── Process Change Workflow ──────────────────────────────────────────────────\n//\n// BET-84: The lightweight everyday workflow for work that isn't shaping.\n// Bug fixes, change requests, improvements, prerequisite tasks.\n// Captures why/who/when without a full shaping ceremony.\n//\n// Migration-ready: Same WorkflowDefinition structure (DEC-83 Phase A).\n// PRI-5: Workspace-agnostic — uses only generic tools (orient, capture,\n// checkpoint). No workspace-specific logic or entry IDs.\n// DEC-149: No facilitate dependency — generic tools only.\n\nconst PROCESS_CHANGE_WORKFLOW_DESCRIPTOR: WorkflowDescriptor = {\n id: \"process-change\",\n name: \"Process a Change\",\n shortDescription:\n \"Lightweight workflow for everyday changes — bug fixes, improvements, change requests. \" +\n \"Captures what changed, why, and what's affected without a full shaping ceremony. \" +\n \"Routes output to the right collection via the classifier.\",\n template: {\n slug: \"process-change\",\n name: \"Process a Change\",\n },\n icon: \"↻\",\n facilitatorPreamble: `You are now in **Change Processing Mode**. You are a lightweight facilitator helping the user capture the context around a change they're making or just made — a bug fix, improvement, change request, or prerequisite task.\n\n## Your Behavior\n\n1. **Be fast.** This is a 5-minute workflow, not a 45-minute ceremony. Respect the user's flow state.\n2. **Orient first.** Call orient to load workspace context — but present only what's relevant to the change, not the full briefing.\n3. **Capture the why.** The single most important thing: why is this change happening? The what is usually obvious from the code. The why is what evaporates.\n4. **Link to what exists.** Search the Chain for related entries. If this change was triggered by a tension, bet, or decision — link it. If it creates a new decision or surfaces a new tension — capture that too.\n5. **Finalize through the workflow substrate.** Complete the terminal round with \\`workflows action=checkpoint ... isFinal=true\\`. The substrate will classifier-route the primary record and attach it to the durable run.\n6. **Don't over-process.** If the user gives you everything in one message, move quickly through the required checkpoints in order, then finalize. Not every round needs a conversation.\n7. **End with the link.** Always finish by connecting the new entry to related Chain knowledge via graph suggest.\n\n## Tool Usage\n\n- \\`orient\\` — load workspace context (governance, active bets, stale entries)\n- \\`entries action=search\\` — find related entries\n- \\`capture\\` — manual fallback only if workflow finalization cannot safely route the entry\n- \\`graph action=suggest\\` — discover connections\n- \\`relations action=create\\` or \\`relations action=batch-create\\` — link to related entries\n- \\`commit-entry\\` — promote to SSOT (only on user confirmation)\n- \\`workflows action=checkpoint\\` — save progress if needed\n\n## Communication Style\n\n- **Conversational, not ceremonial.** No round headers needed unless the user wants structure.\n- **One question at a time.** Ask what you need, checkpoint, move on.\n- **If the user gives rich context upfront**, checkpoint the answered rounds in order, then finalize and link. Don't ask questions they already answered.\n- **Show what you captured.** Always confirm what went to the Chain before closing.`,\n\n rounds: [\n {\n id: \"orient\",\n num: \"01\",\n label: \"Quick Context\",\n type: \"open\",\n instruction:\n \"What are you working on? Orient to load relevant Chain context.\",\n facilitatorGuidance:\n \"Call orient to get workspace context. Ask what the user is changing — or infer from their initial message. \" +\n \"Search the Chain for related entries: entries action=search with keywords from their description. \" +\n \"Present only the 2-3 most relevant entries, not a full briefing. If the user already described the change, skip the question and confirm what you understood.\",\n outputSchema: {\n field: \"context\",\n description: \"What's being changed and relevant Chain context\",\n format: \"structured\",\n },\n maxDurationHint: \"1 min\",\n },\n {\n id: \"what-and-why\",\n num: \"02\",\n label: \"What & Why\",\n type: \"open\",\n instruction:\n \"What's changing and why? What triggered this — a bug, a request, an observation?\",\n facilitatorGuidance:\n \"This is the core capture moment. Get two things: (1) what changed or will change, (2) why — the trigger, the reasoning, the context that will evaporate. \" +\n \"If the user's initial message already contains both, reflect it back for confirmation rather than re-asking. \" +\n \"Classify the change type mentally: bug fix → tension, decision made → decision, new capability → feature, lesson learned → insight. \" +\n \"The classifier will handle routing, but understanding the type helps you ask the right follow-up.\",\n outputSchema: {\n field: \"whatAndWhy\",\n description: \"The change and its rationale\",\n format: \"freetext\",\n },\n maxDurationHint: \"2 min\",\n },\n {\n id: \"impact-and-links\",\n num: \"03\",\n label: \"Impact & Links\",\n type: \"synthesis\",\n instruction:\n \"What's affected? Are there existing Chain entries that relate to this change?\",\n facilitatorGuidance:\n \"Search the Chain for entries that should be linked: entries action=search with keywords from the change. \" +\n \"Check: does this change affect an active bet? Does it resolve a known tension? Does it supersede an existing decision? \" +\n \"If the change is small and self-contained, this round can be brief — just confirm there's nothing obvious to link. \" +\n \"If there are stale entries that this change invalidates, flag them for reconfirmation.\",\n outputSchema: {\n field: \"impact\",\n description: \"Affected entries and proposed links\",\n format: \"structured\",\n },\n maxDurationHint: \"1 min\",\n },\n {\n id: \"capture-and-close\",\n num: \"04\",\n label: \"Capture & Close\",\n type: \"close\",\n instruction:\n \"Capture to the Chain. Link to related entries. Confirm with the user.\",\n facilitatorGuidance:\n \"Finalize through workflows action=checkpoint with isFinal=true, passing a summaryName when you have a clean title. \" +\n \"The workflow substrate will create the primary record as a draft and attach it to the durable run. \" +\n \"After finalization, call graph action=suggest to find connections. Create the top 2-3 relevant relations. \" +\n \"Show the user what was captured: entry ID, collection it landed in, relations created. \" +\n \"Ask if they want to commit now or leave as draft. If they confirm, commit-entry. \" +\n \"If there are stale entries to reconfirm, mention them. \" +\n \"Thank the user briefly and exit — don't linger.\",\n outputSchema: {\n field: \"capture\",\n description: \"Entry captured, relations created, commit status\",\n format: \"structured\",\n },\n maxDurationHint: \"1 min\",\n },\n ],\n\n output: {\n primaryRecord: {\n routing: {\n mode: \"classifier\",\n },\n },\n summaryCapture: {\n createsPrimaryRecord: true,\n nameTemplate: \"{whatAndWhy}\",\n descriptionSource: {\n mode: \"step-output-field\",\n field: \"whatAndWhy\",\n },\n },\n },\n runtime: {\n kind: \"guided\",\n },\n\n errorRecovery: `If anything goes wrong during change processing:\n\n1. **Tool failure**: Explain briefly. Capture in the conversation. Offer to retry or commit manually later.\n2. **Classifier misroutes**: Use update-entry to move the entry to the correct collection. Mention this to the user.\n3. **No related entries found**: That's fine — not every change connects to existing knowledge. Capture it standalone.\n4. **MCP unreachable**: Note the change in conversation. Offer to capture when PB is back.\n\nNever block the user's real work. This workflow serves the work — it doesn't replace it.`,\n};\n\n// ── Workflow Registry ───────────────────────────────────────────────────────\n\nconst WORKFLOW_DESCRIPTORS = new Map<string, WorkflowDescriptor>([\n [\"retro\", RETRO_WORKFLOW_DESCRIPTOR],\n [\"shape\", SHAPE_WORKFLOW_DESCRIPTOR],\n [\"implementation-review\", IMPLEMENTATION_REVIEW_WORKFLOW_DESCRIPTOR],\n [\"process-change\", PROCESS_CHANGE_WORKFLOW_DESCRIPTOR],\n]);\n\nconst WORKFLOWS = new Map<string, WorkflowDefinition>(\n Array.from(WORKFLOW_DESCRIPTORS.entries(), ([id, descriptor]) => [\n id,\n compileWorkflowDefinition(descriptor),\n ]),\n);\n\nexport function getWorkflow(id: string): WorkflowDefinition | undefined {\n const workflow = WORKFLOWS.get(id);\n return workflow ? cloneWorkflowDefinition(workflow) : undefined;\n}\n\nexport function listWorkflows(): WorkflowDefinition[] {\n return Array.from(WORKFLOWS.values(), (workflow) =>\n cloneWorkflowDefinition(workflow),\n );\n}\n\nexport function getWorkflowDescriptor(id: string): WorkflowDescriptor | undefined {\n const descriptor = WORKFLOW_DESCRIPTORS.get(id);\n return descriptor ? cloneWorkflowDescriptor(descriptor) : undefined;\n}\n\nexport function listWorkflowDescriptors(): WorkflowDescriptor[] {\n return Array.from(WORKFLOW_DESCRIPTORS.values(), (descriptor) =>\n cloneWorkflowDescriptor(descriptor),\n );\n}\n\nexport function getWorkflowIds(): string[] {\n return Array.from(WORKFLOWS.keys());\n}\n","/**\n * Synced from convex/lib/workflowRun.ts (TEN-174: MCP separate build, cannot import Convex lib).\n */\n\nimport {\n\tunknownWorkflowRoundMessage,\n\tworkflowMustDefineStepMessage,\n\tworkflowOutputFormatMismatchMessage,\n\tworkflowRunNoActiveRoundMessage,\n\tworkflowRunNotActiveMessage,\n\tworkflowRunRoundMismatchMessage,\n\tworkflowRunRoundNotActiveMessage,\n} from './mcpGatewayClientMessages';\nimport { mcpGatewayClientError } from './errors';\n\n/**\n * BET-85 Slice 2 — canonical workflow run domain model.\n *\n * Pure domain state for workflow execution. Persistence belongs in Convex\n * feature modules; MCP and UI consumers should adapt to this model rather than\n * inventing parallel run contracts.\n */\n\nexport type WorkflowRoundType =\n | \"open\"\n | \"choice\"\n | \"synthesis\"\n | \"commit\"\n | \"close\";\n\nexport type WorkflowOutputFormat =\n | \"freetext\"\n | \"list\"\n | \"choice\"\n | \"structured\";\n\ntype JsonPrimitive = string | number | boolean | null;\nexport type JsonValue =\n | JsonPrimitive\n | JsonValue[]\n | { [key: string]: JsonValue };\n\nexport type WorkflowRunOutput =\n | { format: \"freetext\"; value: string }\n | { format: \"list\"; value: string[] }\n | { format: \"choice\"; value: string | string[] }\n | { format: \"structured\"; value: JsonValue };\n\nexport type WorkflowRunStatus = \"active\" | \"completed\";\nexport type WorkflowRunStepStatus = \"pending\" | \"active\" | \"completed\";\n\nexport interface WorkflowRunStepDefinition {\n roundId: string;\n num: string;\n label: string;\n type: WorkflowRoundType;\n outputField: string;\n outputFormat: WorkflowOutputFormat;\n}\n\nexport interface WorkflowRunCheckpoint {\n roundId: string;\n output: WorkflowRunOutput;\n recordedAt: string;\n}\n\nexport interface WorkflowRunStepState extends WorkflowRunStepDefinition {\n status: WorkflowRunStepStatus;\n output?: WorkflowRunOutput;\n lastCheckpointAt?: string;\n}\n\nexport interface WorkflowRunState {\n runSchemaVersion: 1;\n workflowId: string;\n workflowName: string;\n templateSlug: string;\n templateName: string;\n status: WorkflowRunStatus;\n startedAt: string;\n completedAt?: string;\n currentRoundId: string | null;\n steps: WorkflowRunStepState[];\n checkpoints: WorkflowRunCheckpoint[];\n}\n\n// BET-85 + STA-3: one shared mapping from persisted workflow run docs to the\n// canonical run-state contract used by tools, queries, and future UI surfaces.\nexport interface PersistedWorkflowRunRecord {\n runSchemaVersion: number;\n workflowId: string;\n workflowName: string;\n templateSlug?: string;\n templateName?: string;\n status: WorkflowRunStatus;\n startedAt: string;\n completedAt?: string;\n currentRoundId?: string;\n steps: WorkflowRunState[\"steps\"];\n checkpoints: WorkflowRunState[\"checkpoints\"];\n}\n\nexport interface WorkflowRunRenderProjection {\n workflowId: string;\n workflowName: string;\n templateSlug: string;\n templateName: string;\n status: WorkflowRunStatus;\n currentRoundId: string | null;\n completedCount: number;\n totalCount: number;\n steps: Array<{\n roundId: string;\n num: string;\n label: string;\n type: WorkflowRoundType;\n status: WorkflowRunStepStatus;\n outputField: string;\n outputFormat: WorkflowOutputFormat;\n output?: WorkflowRunOutput;\n }>;\n render: {\n title: string;\n subtitle: string;\n template: {\n slug: string;\n name: string;\n stratum: \"system\";\n stageMode: \"fixed\";\n stages: Array<{\n id: string;\n fieldKey: string;\n label: string;\n prompt: string;\n color?: string;\n }>;\n outputFormats: Array<{\n id: string;\n label: string;\n }>;\n audiencePresets: Array<{\n id: string;\n label: string;\n }>;\n };\n links: Record<string, string>;\n sections: Array<{\n key: string;\n fieldKey: string;\n label: string;\n color: string;\n content: string;\n status: WorkflowRunStepStatus;\n roundId: string;\n roundNum: string;\n roundType: WorkflowRoundType;\n outputFormat: WorkflowOutputFormat;\n output?: WorkflowRunOutput;\n }>;\n };\n}\n\nexport function createWorkflowRunState(args: {\n workflowId: string;\n workflowName: string;\n templateSlug?: string;\n templateName?: string;\n steps: WorkflowRunStepDefinition[];\n startedAt?: string;\n}): WorkflowRunState {\n if (args.steps.length === 0) {\n throw mcpGatewayClientError(workflowMustDefineStepMessage(args.workflowId));\n }\n\n return {\n runSchemaVersion: 1,\n workflowId: args.workflowId,\n workflowName: args.workflowName,\n templateSlug: args.templateSlug ?? args.workflowId,\n templateName: args.templateName ?? args.workflowName,\n status: \"active\",\n startedAt: args.startedAt ?? new Date().toISOString(),\n currentRoundId: args.steps[0]?.roundId ?? null,\n steps: args.steps.map((step, index) => ({\n ...step,\n status: index === 0 ? \"active\" : \"pending\",\n })),\n checkpoints: [],\n };\n}\n\nexport function applyWorkflowCheckpoint(\n run: WorkflowRunState,\n checkpoint: WorkflowRunCheckpoint,\n): WorkflowRunState {\n if (run.status !== \"active\") {\n throw mcpGatewayClientError(workflowRunNotActiveMessage(run.workflowId));\n }\n\n if (!run.currentRoundId) {\n throw mcpGatewayClientError(workflowRunNoActiveRoundMessage(run.workflowId));\n }\n\n if (checkpoint.roundId !== run.currentRoundId) {\n throw mcpGatewayClientError(\n workflowRunRoundMismatchMessage(\n run.workflowId,\n run.currentRoundId,\n checkpoint.roundId,\n ),\n );\n }\n\n const stepIndex = run.steps.findIndex((step) => step.roundId === checkpoint.roundId);\n if (stepIndex === -1) {\n throw mcpGatewayClientError(unknownWorkflowRoundMessage(checkpoint.roundId));\n }\n\n const step = run.steps[stepIndex];\n if (step.status !== \"active\") {\n throw mcpGatewayClientError(\n workflowRunRoundNotActiveMessage(run.workflowId, checkpoint.roundId),\n );\n }\n\n validateWorkflowRunOutput(step.outputFormat, checkpoint.output);\n\n const isLastStep = stepIndex === run.steps.length - 1;\n const willCompleteRun = isLastStep;\n\n const updatedSteps = run.steps.map((currentStep, index) => {\n if (index === stepIndex) {\n return {\n ...currentStep,\n status: \"completed\" as const,\n output: checkpoint.output,\n lastCheckpointAt: checkpoint.recordedAt,\n };\n }\n\n if (index === stepIndex + 1 && !willCompleteRun) {\n return {\n ...currentStep,\n status: \"active\" as const,\n };\n }\n\n return currentStep;\n });\n\n return {\n ...run,\n status: willCompleteRun ? \"completed\" : \"active\",\n completedAt: willCompleteRun ? checkpoint.recordedAt : run.completedAt,\n currentRoundId: willCompleteRun ? null : updatedSteps[stepIndex + 1]?.roundId ?? null,\n steps: updatedSteps,\n checkpoints: [...run.checkpoints, checkpoint],\n };\n}\n\nexport function replayWorkflowRunState(args: {\n workflowId: string;\n workflowName: string;\n templateSlug?: string;\n templateName?: string;\n steps: WorkflowRunStepDefinition[];\n checkpoints: WorkflowRunCheckpoint[];\n startedAt?: string;\n}): WorkflowRunState {\n let run = createWorkflowRunState({\n workflowId: args.workflowId,\n workflowName: args.workflowName,\n templateSlug: args.templateSlug,\n templateName: args.templateName,\n steps: args.steps,\n startedAt: args.startedAt,\n });\n\n for (const checkpoint of args.checkpoints) {\n run = applyWorkflowCheckpoint(run, checkpoint);\n }\n\n return run;\n}\n\nexport function buildWorkflowRunRenderProjection(\n run: WorkflowRunState,\n): WorkflowRunRenderProjection {\n const completedCount = run.steps.filter((step) => step.status === \"completed\").length;\n const renderSections = run.steps.map((step) => {\n const content = step.output ? workflowRunOutputToText(step.output) : \"\";\n\n return {\n key: step.roundId,\n fieldKey: step.outputField,\n label: step.label,\n color: getWorkflowRunStepColor(step.type),\n content,\n status: step.status,\n roundId: step.roundId,\n roundNum: step.num,\n roundType: step.type,\n outputFormat: step.outputFormat,\n output: step.output,\n };\n });\n const renderLinks = Object.fromEntries(\n renderSections\n .filter((section) => section.content.length > 0)\n .map((section) => [section.key, section.content]),\n );\n const subtitle =\n run.status === \"completed\"\n ? `${completedCount}/${run.steps.length} rounds completed`\n : `${completedCount}/${run.steps.length} rounds completed · current ${run.currentRoundId ?? \"none\"}`;\n\n return {\n workflowId: run.workflowId,\n workflowName: run.workflowName,\n templateSlug: run.templateSlug,\n templateName: run.templateName,\n status: run.status,\n currentRoundId: run.currentRoundId,\n completedCount,\n totalCount: run.steps.length,\n steps: run.steps.map((step) => ({\n roundId: step.roundId,\n num: step.num,\n label: step.label,\n type: step.type,\n status: step.status,\n outputField: step.outputField,\n outputFormat: step.outputFormat,\n output: step.output,\n })),\n render: {\n title: run.workflowName,\n subtitle,\n template: {\n slug: run.templateSlug,\n name: run.templateName,\n stratum: \"system\",\n stageMode: \"fixed\",\n stages: run.steps.map((step) => ({\n id: step.roundId,\n fieldKey: step.outputField,\n label: step.label,\n prompt: `Round ${step.num}: ${step.label}`,\n color: getWorkflowRunStepColor(step.type),\n })),\n outputFormats: [\n {\n id: \"workflow-run\",\n label: \"Workflow Run\",\n },\n ],\n audiencePresets: [],\n },\n links: renderLinks,\n sections: renderSections,\n },\n };\n}\n\nexport function toWorkflowRunState(\n run: PersistedWorkflowRunRecord,\n): WorkflowRunState {\n return {\n runSchemaVersion: run.runSchemaVersion as 1,\n workflowId: run.workflowId,\n workflowName: run.workflowName,\n templateSlug: run.templateSlug ?? run.workflowId,\n templateName: run.templateName ?? run.workflowName,\n status: run.status,\n startedAt: run.startedAt,\n completedAt: run.completedAt,\n currentRoundId: run.currentRoundId ?? null,\n steps: run.steps,\n checkpoints: run.checkpoints,\n };\n}\n\nexport function workflowRunOutputToText(output: WorkflowRunOutput): string {\n switch (output.format) {\n case \"freetext\":\n return output.value;\n case \"list\":\n return output.value.join(\", \");\n case \"choice\":\n return Array.isArray(output.value) ? output.value.join(\", \") : output.value;\n case \"structured\":\n if (output.value && typeof output.value === \"object\" && \"text\" in output.value) {\n const textValue = (output.value as { text?: unknown }).text;\n if (typeof textValue === \"string\") {\n return textValue;\n }\n }\n return JSON.stringify(output.value);\n }\n}\n\nexport function workflowRunOutputsEqual(\n left: WorkflowRunOutput,\n right: WorkflowRunOutput,\n): boolean {\n if (left.format !== right.format) {\n return false;\n }\n\n return stableSerializeJsonValue(left.value) === stableSerializeJsonValue(right.value);\n}\n\nfunction validateWorkflowRunOutput(\n expectedFormat: WorkflowOutputFormat,\n output: WorkflowRunOutput,\n): void {\n if (output.format !== expectedFormat) {\n throw mcpGatewayClientError(\n workflowOutputFormatMismatchMessage(expectedFormat, output.format),\n );\n }\n\n switch (output.format) {\n case \"freetext\":\n if (typeof output.value !== \"string\") {\n throw mcpGatewayClientError(\"Freetext workflow output must be a string.\");\n }\n return;\n case \"list\":\n if (!Array.isArray(output.value) || output.value.some((item) => typeof item !== \"string\")) {\n throw mcpGatewayClientError(\"List workflow output must be a string array.\");\n }\n return;\n case \"choice\":\n if (\n typeof output.value !== \"string\" &&\n (!Array.isArray(output.value) ||\n output.value.some((item) => typeof item !== \"string\"))\n ) {\n throw mcpGatewayClientError(\"Choice workflow output must be a string or string array.\");\n }\n return;\n case \"structured\":\n if (!isJsonValue(output.value)) {\n throw mcpGatewayClientError(\"Structured workflow output must be JSON-serializable.\");\n }\n return;\n }\n}\n\nfunction getWorkflowRunStepColor(type: WorkflowRoundType): string {\n switch (type) {\n case \"open\":\n return \"var(--link-problem)\";\n case \"choice\":\n return \"var(--link-choice)\";\n case \"synthesis\":\n return \"var(--link-insight)\";\n case \"commit\":\n return \"var(--link-action)\";\n case \"close\":\n return \"var(--link-outcome)\";\n }\n}\n\nfunction stableSerializeJsonValue(value: JsonValue): string {\n if (value === null || typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\") {\n return JSON.stringify(value);\n }\n\n if (Array.isArray(value)) {\n return `[${value.map((item) => stableSerializeJsonValue(item)).join(\",\")}]`;\n }\n\n const entries = Object.entries(value).sort(([leftKey], [rightKey]) =>\n leftKey.localeCompare(rightKey),\n );\n\n return `{${entries\n .map(([key, entryValue]) =>\n `${JSON.stringify(key)}:${stableSerializeJsonValue(entryValue)}`,\n )\n .join(\",\")}}`;\n}\n\nfunction isJsonValue(value: unknown): value is JsonValue {\n if (\n value === null ||\n typeof value === \"string\" ||\n typeof value === \"number\" ||\n typeof value === \"boolean\"\n ) {\n return true;\n }\n\n if (Array.isArray(value)) {\n return value.every((item) => isJsonValue(item));\n }\n\n if (typeof value === \"object\") {\n const prototype = Object.getPrototypeOf(value);\n if (prototype !== Object.prototype && prototype !== null) {\n return false;\n }\n\n return Object.values(value as Record<string, unknown>).every((item) =>\n isJsonValue(item),\n );\n }\n\n return false;\n}\n","/**\n * Facilitate compound tool — session resume and constellation commit.\n *\n * Actions: resume, commit-constellation\n *\n * Scoring, coaching, and facilitation loop moved to agent-side skills (BET-106).\n * This tool retains only session-state loading and atomic constellation commit.\n * WP-321 E3: Delegates to kernel actions (agentKnowledge.facilitateEnvelope) —\n * MCP layer is a thin passthrough with presentation-only enrichment (cortexUrl).\n *\n * Chain: ENT-37 (Facilitate v1), DEC-56 (PB judges, agents coach),\n * STA-1 (Constellation Capture Pattern)\n * Rules: BR-8 (session required), BR-22 (single impl), BR-25 (MCP layer),\n * BR-70 (audit trail)\n */\n\nimport { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { z } from \"zod\";\nimport {\n kernelCallEnvelope,\n getWorkspaceContext,\n requireWriteAccess,\n recordSessionActivity,\n getAgentSessionId,\n runWithToolContext,\n} from \"../client.js\";\nimport { runConflictPreflight } from \"./conflict-preflight.js\";\nimport { thinWrapper, failure, validationResult } from \"../envelope.js\";\n\n// ── Schema ─────────────────────────────────────────────────────────────────\n\nconst FACILITATE_ACTIONS = [\"resume\", \"commit-constellation\"] as const;\n\nexport const facilitateSchema = z.object({\n action: z.enum(FACILITATE_ACTIONS).describe(\n \"'resume': load session state from an existing bet entry. \" +\n \"'commit-constellation': atomically commit a bet and all its linked draft entries in one call. Requires betEntryId.\",\n ),\n betEntryId: z.string().optional()\n .describe(\"Bet entry ID. Required for both actions.\"),\n operationId: z.string().optional()\n .describe(\"Optional idempotency key for commit-constellation retries.\"),\n});\n\n// ── Types ──────────────────────────────────────────────────────────────────\n\ninterface SessionDraft {\n entryId: string;\n name: string;\n collection: string;\n relationType: string;\n status: string;\n}\n\ninterface ConstellationState {\n elementCount: number;\n riskCount: number;\n decisionCount: number;\n}\n\ninterface BetEntryData {\n betEntryId: string;\n name: string;\n status: string;\n data: Record<string, unknown>;\n}\n\ninterface ResumeData {\n betEntry: BetEntryData;\n constellation: ConstellationState;\n sessionDrafts: SessionDraft[];\n}\n\ninterface ConstellationCommitResult {\n operationId: string;\n committedIds: string[];\n alreadyCommittedIds: string[];\n proposedIds: string[];\n failedIds: Array<{ entryId: string; name: string; error: string }>;\n conflictIds: Array<{ entryId: string; name: string; reason: string }>;\n totalRelations: number;\n proposalCreated?: boolean;\n}\n\ninterface CommitConstellationData {\n result: ConstellationCommitResult;\n}\n\n// ── Helpers ────────────────────────────────────────────────────────────────\n\nfunction buildCortexUrl(workspaceSlug: string, entryId: string): string {\n const appUrl = process.env.PRODUCTBRAIN_APP_URL ?? \"https://work.productbrain.io\";\n return `${appUrl}/${workspaceSlug}/legacy/entries/${entryId}`;\n}\n\n// ── Registration ───────────────────────────────────────────────────────────\n\nexport function registerFacilitateTools(server: McpServer): void {\n server.registerTool(\n \"facilitate\",\n {\n title: \"Facilitate — Session Resume & Constellation Commit\",\n description:\n \"Session state loading and atomic constellation commit for shaped bets.\\n\\n\" +\n \"- **resume**: Load session state (bet data, constellation, drafts) from an existing bet entry.\\n\" +\n \"- **commit-constellation**: Atomically commit a bet and all its linked draft entries \" +\n \"(features, tensions, decisions) in one call. Validates strategy link and required \" +\n \"fields before committing anything. Replaces sequential commit-entry calls.\\n\\n\" +\n \"Scoring, coaching, and the facilitation loop are handled by the agent-side shaping skill.\",\n inputSchema: facilitateSchema,\n annotations: {\n readOnlyHint: false,\n destructiveHint: false,\n idempotentHint: false,\n openWorldHint: false,\n },\n },\n thinWrapper(async (args) => {\n const parsed = facilitateSchema.safeParse(args);\n if (!parsed.success) {\n const issues = parsed.error.issues\n .map((i) => `${i.path.join(\".\")}: ${i.message}`)\n .join(\"; \");\n return validationResult(`Invalid arguments: ${issues}`);\n }\n\n const { action } = parsed.data;\n\n return runWithToolContext({ tool: \"facilitate\", action }, async () => {\n switch (action) {\n case \"resume\":\n return handleResume(parsed.data);\n case \"commit-constellation\":\n return handleCommitConstellation(parsed.data);\n default:\n return validationResult(`Unknown action '${action}'. Valid: ${FACILITATE_ACTIONS.join(\", \")}.`);\n }\n });\n }),\n );\n}\n\n// ── Action Handlers ────────────────────────────────────────────────────────\n\nasync function handleResume(args: z.infer<typeof facilitateSchema>) {\n const betId = args.betEntryId;\n if (!betId) {\n return validationResult(\"`betEntryId` is required for resume action.\");\n }\n\n const { workspaceId, workspaceSlug } = await getWorkspaceContext();\n\n // Delegate to kernel action\n const envelope = await kernelCallEnvelope<ResumeData>(\"agentKnowledge.facilitateEnvelope\", {\n workspaceId,\n action: \"resume\",\n betEntryId: betId,\n });\n\n // MCP-layer enrichment: add cortexUrl (kernel doesn't build Cortex URLs — that's MCP presentation)\n const enrichedData = {\n ...envelope.data,\n cortexUrl: buildCortexUrl(workspaceSlug, betId),\n };\n\n // Rebuild rich markdown briefing (presentation concern — kernel stays semantic)\n const bet = enrichedData.betEntry;\n const cx = enrichedData.constellation;\n const constellationParts: string[] = [];\n if (cx.elementCount > 0) constellationParts.push(`${cx.elementCount} element(s)`);\n if (cx.riskCount > 0) constellationParts.push(`${cx.riskCount} risk(s)`);\n if (cx.decisionCount > 0) constellationParts.push(`${cx.decisionCount} decision(s)`);\n const constellationSummary = constellationParts.length > 0\n ? constellationParts.join(\", \")\n : \"no entries captured yet\";\n\n const draftLines = enrichedData.sessionDrafts.slice(0, 10).map(\n (d: SessionDraft) => `- \\`${d.entryId}\\` ${d.name} [${d.collection}] (${d.status})`,\n );\n const textLines = [\n `# ${bet.name}`,\n \"\",\n `**ID:** \\`${bet.betEntryId}\\` · **Status:** ${bet.status}`,\n enrichedData.cortexUrl ? `**Cortex:** ${enrichedData.cortexUrl}` : \"\",\n \"\",\n `**Constellation:** ${constellationSummary}`,\n ...(draftLines.length > 0 ? [\"\", \"**Session drafts:**\", ...draftLines] : []),\n ].filter((l) => l !== undefined);\n\n return {\n content: [{ type: \"text\" as const, text: textLines.join(\"\\n\") }],\n structuredContent: {\n ok: true as const,\n summary: envelope.summary,\n data: enrichedData,\n next: envelope.next,\n _meta: envelope._meta,\n },\n };\n}\n\n// ── Commit Constellation ────────────────────────────────────────────────\n\nexport async function handleCommitConstellation(args: z.infer<typeof facilitateSchema>) {\n requireWriteAccess();\n\n const betId = args.betEntryId;\n if (!betId) {\n return validationResult(\"`betEntryId` is required for commit-constellation action.\");\n }\n\n const { workspaceId } = await getWorkspaceContext();\n const sessionId = getAgentSessionId();\n const operationId = args.operationId ?? `${betId}:${sessionId ?? \"sessionless\"}:${Date.now()}`;\n\n // ── MCP-layer conflict preflight (pre-condition check, stays in MCP layer) ──\n // We need the bet name and description for the conflict check. Load minimally.\n let betName = betId;\n let betDesc = \"\";\n let betCollectionHint: string | undefined;\n try {\n type BetEntryShape = {\n name: string;\n data?: Record<string, unknown>;\n collectionSlug?: string;\n collection?: { slug?: string; name?: string };\n };\n const betEnvelope = await kernelCallEnvelope<BetEntryShape>(\"chain.getEntry\", { entryId: betId });\n const entry = betEnvelope.data;\n if (entry) {\n betName = entry.name ?? betId;\n const d = entry.data ?? {};\n const links = d[\"links\"] as Record<string, unknown> | undefined;\n betDesc = (d.problem as string) ?? (links?.problem as string) ?? (d.description as string) ?? \"\";\n betCollectionHint = entry.collectionSlug ?? entry.collection?.slug ?? entry.collection?.name;\n }\n } catch {\n // If we can't load the bet entry, the kernel will handle the NOT_FOUND case\n }\n\n const preflight = await runConflictPreflight(betName, betDesc, betCollectionHint);\n\n if (preflight.blockingContradictions.length > 0) {\n await recordSessionActivity({ contradictionWarning: true });\n const conflictLines = preflight.blockingContradictions\n .map((c) => `- ${c.chainEntryName} (${c.chainEntryId}) — ${c.explanation}`)\n .join(\"\\n\");\n\n return {\n content: [{\n type: \"text\" as const,\n text: [\n `# Commit blocked: contradiction detected`,\n \"\",\n `\\`${betId}\\` matches ${preflight.blockingContradictions.length} high-confidence contradiction(s). Resolve the conflict before committing the constellation.`,\n \"\",\n conflictLines,\n ].join(\"\\n\"),\n }],\n structuredContent: failure(\n \"CONTRADICTION_BLOCKED\",\n `${preflight.blockingContradictions.length} high-confidence contradiction(s) found.`,\n \"Review the conflicting entry or entries before retrying the commit.\",\n undefined,\n {\n betEntryId: betId,\n source: preflight.source,\n blockingContradictions: preflight.blockingContradictions,\n advisoryWarnings: preflight.advisoryWarnings,\n },\n ),\n };\n }\n\n if (preflight.source === \"semantic\" ? preflight.conflicts.length > 0 : preflight.advisoryWarnings.length > 0) {\n await recordSessionActivity({ contradictionWarning: true });\n }\n\n // ── Delegate to kernel action ───────────────────────────────────────────\n let envelope: Awaited<ReturnType<typeof kernelCallEnvelope<CommitConstellationData>>>;\n try {\n envelope = await kernelCallEnvelope<CommitConstellationData>(\"agentKnowledge.facilitateEnvelope\", {\n workspaceId,\n action: \"commit-constellation\",\n betEntryId: betId,\n operationId,\n sessionId: sessionId ?? undefined,\n author: sessionId ? `agent:${sessionId}` : \"kernel:facilitate\",\n });\n } catch (err: unknown) {\n const msg = err instanceof Error ? err.message : String(err);\n const diagnostics = (err as { diagnostics?: Record<string, unknown> })?.diagnostics;\n return {\n content: [{\n type: \"text\" as const,\n text: `# Bet commit failed\\n\\n\\`${betId}\\` could not be committed: ${msg}\\n\\nNo constellation entries were committed.`,\n }],\n structuredContent: failure(\n \"BACKEND_ERROR\",\n `Bet commit failed: ${msg}`,\n \"Retry or check for commit blockers.\",\n [{ tool: \"facilitate\", description: \"Resume session\", parameters: { action: \"resume\", betEntryId: betId } }],\n diagnostics,\n ),\n };\n }\n\n // Advisory: record session activity (best-effort, non-blocking)\n await recordSessionActivity({ contradictionWarning: preflight.blockingContradictions.length > 0 });\n // Per-entry audit trail — record each committed doc in session activity (BR-70)\n for (const docId of (envelope.data?.result?.committedIds ?? [])) {\n try {\n await recordSessionActivity({ entryModified: docId });\n } catch {\n // Advisory — non-blocking\n }\n }\n\n // Build text output from kernel result\n const result = envelope.data.result;\n const suggestions = { conflictPreflightSource: preflight.source };\n\n const lines: string[] = [];\n const hasIssues = (result.failedIds?.length ?? 0) > 0 || (result.conflictIds?.length ?? 0) > 0;\n if (result.proposalCreated) {\n lines.push(\n hasIssues ? `# Proposal created with issues` : `# Proposal created`,\n \"\",\n `Workspace uses consent-based governance. \\`${betId}\\` was submitted as a proposal — it will be committed when approved.`,\n `No linked entries were committed because the bet itself is still awaiting approval.`,\n );\n } else {\n lines.push(\n hasIssues ? `# Published with issues` : `# Published`,\n \"\",\n `**${result.committedIds?.length ?? 0} entries** committed to the Chain, **${result.totalRelations} connections** preserved.`,\n hasIssues\n ? `\\`${betId}\\` was partially committed. Review conflicts/failed entries below before considering the constellation complete.`\n : `\\`${betId}\\` and its full constellation are now source of truth.`,\n );\n }\n\n if (preflight.source === \"semantic\" && preflight.conflicts.length > 0) {\n lines.push(\n \"\",\n `⚠ **Semantic conflict preflight** (advisory):`,\n ...preflight.conflicts.map((c) => `- \\`${c.chainEntryId}\\` ${c.chainEntryName}: ${c.explanation}`),\n );\n } else if (preflight.source === \"heuristic\" && preflight.advisoryWarnings.length > 0) {\n lines.push(\n \"\",\n `⚠ **Contradiction warnings** (advisory):`,\n ...preflight.advisoryWarnings.map(\n (w) => `- \\`${w.entryId}\\` ${w.name} [${w.collection}] (${w.governsCount} governs relation${w.governsCount === 1 ? \"\" : \"s\"})`,\n ),\n );\n }\n\n if ((result.committedIds?.length ?? 0) > 0) {\n lines.push(\"\", `**Committed:** ${result.committedIds.join(\", \")}`);\n }\n if ((result.alreadyCommittedIds?.length ?? 0) > 0) {\n lines.push(\"\", `**Already committed:** ${result.alreadyCommittedIds.join(\", \")}`);\n }\n if ((result.proposedIds?.length ?? 0) > 0) {\n lines.push(\"\", `**Proposed (not yet committed):** ${result.proposedIds.join(\", \")}`);\n }\n if ((result.conflictIds?.length ?? 0) > 0) {\n lines.push(\"\", `**${result.conflictIds.length} conflicts:**`);\n for (const c of result.conflictIds) {\n lines.push(`- \\`${c.entryId}\\` ${c.name}: ${c.reason}`);\n }\n }\n if ((result.failedIds?.length ?? 0) > 0) {\n lines.push(\"\", `**${result.failedIds.length} failed:**`);\n for (const f of result.failedIds) {\n lines.push(`- \\`${f.entryId}\\` ${f.name}: ${f.error}`);\n }\n }\n\n return {\n content: [{ type: \"text\" as const, text: lines.join(\"\\n\") }],\n structuredContent: {\n ok: true as const,\n summary: envelope.summary,\n data: { result, suggestions },\n next: envelope.next,\n _meta: envelope._meta,\n },\n };\n}\n","import { existsSync, readFileSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\nimport { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { z } from \"zod\";\nimport { kernelQuery, kernelMutation } from \"../client.js\";\nimport { trackWriteTool } from \"../tool-surface.js\";\nimport { thinWrapper, success, failureResult } from \"../envelope.js\";\nimport { resolveProjectRoot } from \"../lib/resolve-project-root.js\";\n\n// ── Types ──────────────────────────────────────────────────────────────\n\ntype MappingKind = \"file\" | \"schema\" | \"conceptual\";\ntype CheckResult = \"verified\" | \"drifted\" | \"unverifiable\";\n\ninterface MappingCheck {\n entryId: string;\n entryName: string;\n field: string;\n kind: MappingKind;\n result: CheckResult;\n reason: string;\n currentStatus: string;\n}\n\ninterface RefCheck {\n entryId: string;\n entryName: string;\n refValue: string;\n found: boolean;\n}\n\n// ── Schema Parser ──────────────────────────────────────────────────────\n\nfunction parseConvexSchema(schemaPath: string): Map<string, Set<string>> {\n const content = readFileSync(schemaPath, \"utf-8\");\n const tables = new Map<string, Set<string>>();\n let currentTable: string | null = null;\n\n for (const line of content.split(\"\\n\")) {\n const tableMatch = line.match(/^\\t(\\w+):\\s*defineTable\\(/);\n if (tableMatch) {\n currentTable = tableMatch[1];\n tables.set(currentTable, new Set());\n continue;\n }\n\n if (currentTable && /^\\t[}\\)]/.test(line) && !/^\\t\\t/.test(line)) {\n currentTable = null;\n continue;\n }\n\n if (currentTable) {\n const fieldMatch = line.match(/^\\t\\t(\\w+):\\s*v\\./);\n if (fieldMatch) tables.get(currentTable)!.add(fieldMatch[1]);\n }\n }\n\n return tables;\n}\n\n// ── Code Mapping Classifiers ───────────────────────────────────────────\n\nfunction cleanFieldRef(field: string): string {\n return field\n .replace(/\\s*\\(.*\\)\\s*$/, \"\")\n .replace(/\\s*=\\s*.*$/, \"\")\n .trim();\n}\n\nfunction splitMultiRefs(field: string): string[] {\n if (field.includes(\" + \")) return field.split(/\\s*\\+\\s*/);\n return [field];\n}\n\nconst FILE_EXT_RE = /\\.(ts|js|svelte|json|css|md|jsx|tsx|mjs|cjs)(?:\\s|$)/i;\n\nfunction classifyRef(cleaned: string): MappingKind {\n if (cleaned.includes(\"/\") || FILE_EXT_RE.test(cleaned) || /^\\.\\w+/.test(cleaned)) {\n return \"file\";\n }\n if (/^\\w+\\.\\w+$/.test(cleaned)) return \"schema\";\n if (/^\\w+\\s+table$/i.test(cleaned)) return \"schema\";\n return \"conceptual\";\n}\n\n// ── Verification Checkers ──────────────────────────────────────────────\n\nfunction checkFileRef(ref: string, root: string): { result: CheckResult; reason: string } {\n const filePart = ref.split(/\\s+/)[0];\n const fullPath = resolve(root, filePart);\n if (existsSync(fullPath)) return { result: \"verified\", reason: \"exists\" };\n return { result: \"drifted\", reason: `not found: ${filePart}` };\n}\n\nfunction checkSchemaRef(\n ref: string,\n schema: Map<string, Set<string>>,\n): { result: CheckResult; reason: string } {\n const tableOnlyMatch = ref.match(/^(\\w+)\\s+table$/i);\n if (tableOnlyMatch) {\n const table = tableOnlyMatch[1];\n if (schema.has(table)) return { result: \"verified\", reason: `table \"${table}\" exists` };\n return { result: \"drifted\", reason: `table \"${table}\" not found in schema` };\n }\n\n const dotIdx = ref.indexOf(\".\");\n if (dotIdx > 0) {\n const table = ref.slice(0, dotIdx);\n const field = ref.slice(dotIdx + 1);\n if (!schema.has(table)) return { result: \"drifted\", reason: `table \"${table}\" not found in schema` };\n if (!schema.get(table)!.has(field)) return { result: \"drifted\", reason: `field \"${field}\" not found in table \"${table}\"` };\n return { result: \"verified\", reason: `${table}.${field} exists` };\n }\n\n return { result: \"unverifiable\", reason: \"could not parse schema reference\" };\n}\n\n// ── Trust Report Formatter ─────────────────────────────────────────────\n\nfunction formatTrustReport(\n collection: string,\n entryCount: number,\n mappings: MappingCheck[],\n refs: RefCheck[],\n fixes: string[],\n mode: string,\n schemaTableCount: number,\n projectRoot: string,\n): string {\n const verified = mappings.filter((c) => c.result === \"verified\").length;\n const drifted = mappings.filter((c) => c.result === \"drifted\").length;\n const unverifiable = mappings.filter((c) => c.result === \"unverifiable\").length;\n\n const refsValid = refs.filter((c) => c.found).length;\n const refsBroken = refs.filter((c) => !c.found).length;\n\n const totalChecks = mappings.length + refs.length;\n const totalPassed = verified + refsValid;\n const trustScore = totalChecks > 0 ? Math.round((totalPassed / totalChecks) * 100) : 100;\n\n const lines: string[] = [\n `# Trust Report: ${collection} (${entryCount} entries scanned)`,\n \"\",\n ];\n\n if (mappings.length > 0) {\n lines.push(\n \"## Code Mapping Verification\",\n `- ${mappings.length} mappings checked`,\n `- ${verified} verified (${Math.round((verified / mappings.length) * 100)}%)`,\n `- ${drifted} drifted (file/schema not found)`,\n `- ${unverifiable} unverifiable (conceptual — skipped)`,\n \"\",\n );\n }\n\n if (drifted > 0) {\n lines.push(\"### Drifted Mappings\");\n for (const mc of mappings.filter((c) => c.result === \"drifted\")) {\n lines.push(`- **${mc.entryId}** (${mc.entryName}): \\`${mc.field}\\` — ${mc.reason}`);\n }\n lines.push(\"\");\n }\n\n if (unverifiable > 0) {\n lines.push(\"### Unverifiable (Conceptual)\");\n for (const mc of mappings.filter((c) => c.result === \"unverifiable\")) {\n lines.push(`- **${mc.entryId}** (${mc.entryName}): \\`${mc.field}\\``);\n }\n lines.push(\"\");\n }\n\n if (refs.length > 0) {\n lines.push(\n \"## Cross-Reference Verification\",\n `- ${refs.length} references checked`,\n `- ${refsValid} valid (${refs.length > 0 ? Math.round((refsValid / refs.length) * 100) : 0}%)`,\n `- ${refsBroken} broken`,\n \"\",\n );\n }\n\n if (refsBroken > 0) {\n lines.push(\"### Broken References\");\n for (const rc of refs.filter((c) => !c.found)) {\n lines.push(`- **${rc.entryId}** (${rc.entryName}): relatedRules \\`${rc.refValue}\\` — entry not found`);\n }\n lines.push(\"\");\n }\n\n lines.push(`## Trust Score: ${trustScore}% (${totalPassed} of ${totalChecks} checks passed)`);\n\n if (mode === \"fix\" && fixes.length > 0) {\n lines.push(\n \"\",\n \"## Applied Fixes\",\n `Updated codeMapping status from \\`aligned\\` → \\`drifted\\` on ${fixes.length} entr${fixes.length === 1 ? \"y\" : \"ies\"}:`,\n );\n for (const eid of fixes) lines.push(`- ${eid}`);\n } else if (mode === \"report\" && drifted > 0) {\n const fixable = mappings.filter((c) => c.result === \"drifted\" && c.currentStatus === \"aligned\").length;\n if (fixable > 0) {\n lines.push(\"\", `_${fixable} mapping(s) marked \"aligned\" but actually drifted. Run with mode=\"fix\" to update._`);\n }\n }\n\n lines.push(\"\", \"---\", `_Schema: ${schemaTableCount} tables parsed from convex/schema.ts. Project root: ${projectRoot}_`);\n\n return lines.join(\"\\n\");\n}\n\n// ── Tool Registration ──────────────────────────────────────────────────\n\nexport const verifySchema = z.object({\n collection: z.string().default(\"glossary\")\n .describe(\"Collection slug to verify (default: glossary)\"),\n mode: z.enum([\"report\", \"fix\"]).default(\"report\")\n .describe(\"'report' = read-only trust report. 'fix' = also update drifted codeMapping statuses.\"),\n});\n\nexport const verifyEntrySchema = z.object({\n entryId: z.string().describe(\"Human entry ID (e.g. 'INS-33') to mark as verified\"),\n});\n\nexport function registerVerifyTools(server: McpServer) {\n const verifyTool = server.registerTool(\n \"verify\",\n {\n title: \"Verify the Chain\",\n description:\n \"Verify knowledge entries against the actual codebase. Checks glossary code mappings \" +\n \"(do referenced files and schema fields still exist?) and validates cross-references \" +\n \"(do relatedRules point to real entries?). Produces a trust report with a trust score. \" +\n \"Use mode='fix' to auto-update drifted codeMapping statuses.\",\n inputSchema: verifySchema,\n annotations: { readOnlyHint: false, destructiveHint: true, openWorldHint: false },\n },\n thinWrapper(async ({ collection, mode }) => {\n const projectRoot = resolveProjectRoot();\n if (!projectRoot) {\n return failureResult(\n \"# Verification Failed\\n\\n\" +\n \"Cannot find project root (looked for `convex/schema.ts` in cwd and parent directory).\\n\\n\" +\n \"Set `WORKSPACE_PATH` in `.env.mcp` to the absolute path of the Product Brain project root.\",\n \"VALIDATION_ERROR\",\n \"Cannot find project root. Set WORKSPACE_PATH in .env.mcp.\",\n );\n }\n\n const schema = parseConvexSchema(resolve(projectRoot, \"convex/schema.ts\"));\n\n await server.sendLoggingMessage({\n level: \"info\",\n data: `Verifying \"${collection}\" against ${schema.size} schema tables at ${projectRoot}`,\n logger: \"product-os\",\n });\n\n const scopedEntries = await kernelQuery<any[]>(\"chain.listEntries\", { collectionSlug: collection });\n\n if (scopedEntries.length === 0) {\n return failureResult(\n `No entries found in '${collection}'. Nothing to verify.`,\n \"NOT_FOUND\",\n `No entries found in '${collection}'. Nothing to verify.`,\n \"Capture entries first, then verify.\",\n [{ tool: \"capture\", description: \"Capture an entry\", parameters: {} }],\n );\n }\n\n await server.sendLoggingMessage({\n level: \"info\",\n data: `Scanning ${scopedEntries.length} entries in ${collection}...`,\n logger: \"product-brain\",\n });\n\n // Build cross-reference lookup: fetch all entries to check relatedRules\n let allEntryIds: Set<string>;\n try {\n const allEntries = await kernelQuery<any[]>(\"chain.listEntries\", {});\n allEntryIds = new Set(allEntries.map((e: any) => e.entryId).filter(Boolean));\n } catch {\n allEntryIds = new Set(scopedEntries.map((e: any) => e.entryId).filter(Boolean));\n }\n\n const mappingChecks: MappingCheck[] = [];\n const refChecks: RefCheck[] = [];\n\n for (let idx = 0; idx < scopedEntries.length; idx++) {\n const entry = scopedEntries[idx];\n\n if (idx > 0 && idx % 10 === 0) {\n await server.sendLoggingMessage({\n level: \"info\",\n data: `Scanned ${idx}/${scopedEntries.length} entries...`,\n logger: \"product-brain\",\n });\n }\n\n const eid = entry.entryId ?? entry.name;\n const ename = entry.name;\n\n // ── Code mapping verification ──\n const codeMappings: any[] = entry.data?.codeMapping ?? [];\n for (const cm of codeMappings) {\n const rawField: string = cm.field ?? \"\";\n for (const rawRef of splitMultiRefs(rawField)) {\n const cleaned = cleanFieldRef(rawRef);\n if (!cleaned) continue;\n\n const kind = classifyRef(cleaned);\n let result: CheckResult;\n let reason: string;\n\n if (kind === \"file\") {\n ({ result, reason } = checkFileRef(cleaned, projectRoot));\n } else if (kind === \"schema\") {\n ({ result, reason } = checkSchemaRef(cleaned, schema));\n } else {\n result = \"unverifiable\";\n reason = \"conceptual reference\";\n }\n\n mappingChecks.push({\n entryId: eid, entryName: ename, field: rawRef.trim(),\n kind, result, reason, currentStatus: cm.status ?? \"unknown\",\n });\n }\n }\n\n // ── Cross-reference verification (relatedRules only) ──\n const MAX_CROSS_REFS = 50;\n const relatedRules: string[] = entry.data?.relatedRules ?? [];\n for (const ruleId of relatedRules) {\n if (refChecks.length >= MAX_CROSS_REFS) break;\n refChecks.push({\n entryId: eid, entryName: ename, refValue: ruleId,\n found: allEntryIds.has(ruleId),\n });\n }\n }\n\n await server.sendLoggingMessage({\n level: \"info\",\n data: `Scan complete. Building trust report...`,\n logger: \"product-brain\",\n });\n\n // ── Fix mode: update aligned → drifted ──\n const fixes: string[] = [];\n const fixUpdateWarnings: Array<{ entryId: string; normalizationWarnings: string[]; validationWarnings: string[] }> = [];\n if (mode === \"fix\") {\n const driftedByEntry = new Map<string, Set<string>>();\n for (const mc of mappingChecks) {\n if (mc.result === \"drifted\" && mc.currentStatus === \"aligned\") {\n if (!driftedByEntry.has(mc.entryId)) driftedByEntry.set(mc.entryId, new Set());\n driftedByEntry.get(mc.entryId)!.add(mc.field);\n }\n }\n\n for (const [eid, driftedFields] of driftedByEntry) {\n const entry = scopedEntries.find((e: any) => (e.entryId ?? e.name) === eid);\n if (!entry?.entryId) continue;\n\n const updated = (entry.data?.codeMapping ?? []).map((cm: any) =>\n cm.status === \"aligned\" && driftedFields.has(cm.field)\n ? { ...cm, status: \"drifted\" }\n : cm,\n );\n\n const updateResult = await kernelMutation<{\n id: string;\n warnings: string[];\n normalization: { remapped: Record<string, string>; rejected: string[]; accepted: string[] };\n normalizationWarnings: string[];\n validationWarnings: string[];\n }>(\"chain.updateEntry\", {\n entryId: entry.entryId,\n data: { codeMapping: updated },\n });\n if (updateResult.normalizationWarnings.length > 0 || updateResult.validationWarnings.length > 0) {\n fixUpdateWarnings.push({\n entryId: entry.entryId,\n normalizationWarnings: updateResult.normalizationWarnings,\n validationWarnings: updateResult.validationWarnings,\n });\n }\n fixes.push(entry.entryId);\n }\n }\n\n const verified = mappingChecks.filter((c) => c.result === \"verified\").length;\n const drifted = mappingChecks.filter((c) => c.result === \"drifted\").length;\n const unverifiable = mappingChecks.filter((c) => c.result === \"unverifiable\").length;\n const refsValid = refChecks.filter((c) => c.found).length;\n const refsBroken = refChecks.filter((c) => !c.found).length;\n const totalChecks = mappingChecks.length + refChecks.length;\n const totalPassed = verified + refsValid;\n const trustScore = totalChecks > 0 ? Math.round((totalPassed / totalChecks) * 100) : 100;\n\n const report = formatTrustReport(\n collection, scopedEntries.length,\n mappingChecks, refChecks, fixes, mode,\n schema.size, projectRoot,\n );\n\n let reportText = report;\n if (fixUpdateWarnings.length > 0) {\n reportText += '\\n\\n---\\n\\n⚠️ **Fix update warnings:**';\n for (const w of fixUpdateWarnings) {\n for (const nw of w.normalizationWarnings) {\n reportText += `\\n - **${w.entryId}** (normalization): ${nw}`;\n }\n for (const vw of w.validationWarnings) {\n reportText += `\\n - **${w.entryId}** (validation): ${vw}`;\n }\n }\n }\n\n return {\n content: [{ type: \"text\" as const, text: reportText }],\n structuredContent: success(\n `Trust report for ${collection}: ${totalPassed}/${totalChecks} checks passed (${trustScore}%).`,\n {\n collection,\n entryCount: scopedEntries.length,\n trustScore,\n totalChecks,\n totalPassed,\n verified,\n drifted,\n unverifiable,\n refsValid,\n refsBroken,\n fixesApplied: fixes.length,\n mode,\n },\n ),\n };\n }),\n );\n trackWriteTool(verifyTool);\n\n // ── TEN-1125: Lightweight entry verification (no codebase required) ──\n\n const verifyEntryTool = server.registerTool(\n \"verify-entry\",\n {\n title: \"Verify Entry\",\n description:\n \"Mark a single entry as verified. Required for agent-origin entries before they can be committed. \" +\n \"Unlike the 'verify' tool (which scans code mappings against the codebase), this tool only sets \" +\n \"verificationStatus to 'verified'. Works in any context — no codebase required.\",\n inputSchema: verifyEntrySchema,\n annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: false },\n },\n thinWrapper(async ({ entryId }) => {\n const result = await kernelMutation(\"chain.verifyEntry\", { entryId });\n return success(`Entry ${entryId} verified.`, result);\n }),\n );\n trackWriteTool(verifyEntryTool);\n}\n","/**\n * `start_pb` MCP tool — universal session opener implementing PAT-227.\n *\n * WP-433 S3 (FEAT-1296) — collapses `start` + `start_pb` into ONE tool.\n *\n * Canonical name decision: keeping `start_pb` (Option A, DEC supersedes DEC-997).\n * Rationale: user trigger is literally \"Start PB\" — `start_pb` is the closest\n * natural match. Avoids renaming cascade across rules/docs. \"start\" alone is\n * too generic and may attract unrelated intents. See proposed DEC in report.\n *\n * Stage-branched delivery (PAT-227):\n * blank / seeded → SKILL-pb-setup body verbatim via loadSkillBody (DEC-1016 SSOT)\n * grounded / connected → orient-style standup briefing from start.ts buildOrientResponse\n * readiness failure → orient-style (safest degraded path — never show setup on active ws)\n *\n * TEN-2028: surfaceCapability self-declaration removed from recordSetupInvocation call.\n * The mutation requires surfaceCapability as a required arg; removing the call entirely\n * (it was best-effort / wrapped in try-catch) is the correct approach per TEN-2028.\n * stampMcpOnlySurface is preserved for blank/seeded workspaces only (DEC-993 / STD-235).\n */\n\nimport { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { z } from \"zod\";\nimport {\n kernelQuery,\n kernelMutation,\n kernelCall,\n getWorkspaceContext,\n getAgentSessionId,\n setSessionOriented,\n} from \"../client.js\";\nimport { thinWrapper, success, failure, textContent, type NextAction } from \"../envelope.js\";\nimport { loadSkillBody, type SkillBodyResult } from \"./skills.js\";\nimport { queryPlannedWork, hasPlannedWork, buildPlannedWorkSection, formatRecoveryBlock, type PriorSession } from \"./planned-work.js\";\nimport { buildOperatingProtocol, buildCoherenceSection, buildDocCompletenessSection, type ActiveBet, type CoherenceSnapshot, type StandardEntry, type CollectionDocFields } from \"./orient-shared.js\";\nimport { getTopGaps } from \"../gap-store.js\";\nimport { formatTopGapPrompt, formatGapList, type ReadinessGap, type GapContext } from \"../lib/gapToPrompt.js\";\nimport { getByNavGroup } from \"../lib/collectionCache.js\";\n\nexport const startPbSchema = z.object({\n task: z\n .string()\n .optional()\n .describe(\n \"What you're about to work on (e.g. 'implementing auth middleware'). \" +\n \"Grounded/connected workspaces: filters governance to show relevant principles, standards, and business rules. \" +\n \"Blank/seeded workspaces: ignored (setup flow takes over).\",\n ),\n});\n\nconst PB_SETUP_SKILL_ENTRY_ID = \"SKILL-pb-setup\";\n\n/** Shape returned by chain.workspaceReadiness — local mirror of Convex type. */\ninterface WorkspaceReadiness {\n score: number;\n totalChecks: number;\n passedChecks: number;\n checks: Array<{ passed: boolean; label: string; current: number; required: number }>;\n gaps: ReadinessGap[];\n stats: {\n totalEntries: number;\n activeCount: number;\n draftCount: number;\n totalRelations: number;\n collectionCount: number;\n orphanedCount: number;\n };\n stage: \"blank\" | \"seeded\" | \"grounded\" | \"connected\";\n scoringVersion: \"v1\" | \"v2\";\n governanceMode?: string;\n}\n\nasync function tryMarkOriented(\n agentSessionId: string | null,\n coherenceSnapshot?: CoherenceSnapshot,\n): Promise<{\n oriented: boolean;\n orientationStatus: \"complete\" | \"failed\" | \"no_session\";\n}> {\n if (!agentSessionId) return { oriented: false, orientationStatus: \"no_session\" };\n try {\n await kernelCall(\"agent.markOriented\", {\n sessionId: agentSessionId,\n ...(coherenceSnapshot ? { coherenceSnapshot } : {}),\n });\n setSessionOriented(true);\n return { oriented: true, orientationStatus: \"complete\" };\n } catch {\n if (!coherenceSnapshot) {\n return { oriented: false, orientationStatus: \"failed\" };\n }\n try {\n await kernelCall(\"agent.markOriented\", { sessionId: agentSessionId });\n setSessionOriented(true);\n return { oriented: true, orientationStatus: \"complete\" };\n } catch {\n return { oriented: false, orientationStatus: \"failed\" };\n }\n }\n}\n\n/** TEN-547: Bets collection filter — status at top-level or in data. */\nfunction isActiveNowBet(e: { status?: string; data?: Record<string, unknown> }): boolean {\n const status = e.status ?? (e.data as { status?: string } | undefined)?.status;\n const horizon = (e.data as { horizon?: string } | undefined)?.horizon;\n return status === \"active\" && horizon === \"now\";\n}\n\nfunction computeWorkspaceAge(createdAt: number | null): { ageDays: number; isNeglected: boolean } {\n if (!createdAt) return { ageDays: 0, isNeglected: false };\n const ageDays = Math.floor((Date.now() - createdAt) / (1000 * 60 * 60 * 24));\n return { ageDays, isNeglected: ageDays >= 30 };\n}\n\nfunction pickNextTensionPrompt(\n openTensions: Array<{ name: string }>,\n): { action: string; cta: string } | null {\n if (openTensions.length === 0) return null;\n const t = openTensions[0];\n return {\n action: `Open tension: ${t.name}`,\n cta: \"Want to discuss this tension or capture a decision about it?\",\n };\n}\n\n/**\n * Blank/seeded stage: return SKILL-pb-setup body verbatim (DEC-1016 SSOT).\n * Also stamps the MCP-only surface for chat-only callers (DEC-993 / STD-235).\n *\n * TEN-2028: recordSetupInvocation call removed — it required surfaceCapability\n * as a required argument, which would constitute self-declaration of surface\n * capability. The invocation receipt can be recorded by the CLI path or a\n * dedicated record_activation call post-onboarding.\n */\nasync function buildSetupResponse(\n agentSessionId: string | null,\n): Promise<{ text: string; structuredContent: Record<string, unknown> }> {\n // DEC-993 / STD-235: stamp manifest.surfaces with mcp-only (forward-only union)\n await kernelMutation<{ stamped: boolean; surfaces: string[] }>(\n \"setup.stampMcpOnlySurface\",\n {},\n );\n\n const skill: SkillBodyResult = await loadSkillBody(PB_SETUP_SKILL_ENTRY_ID);\n\n const { oriented, orientationStatus } = await tryMarkOriented(agentSessionId);\n\n return {\n text: skill.body,\n structuredContent: success(\n `pb-setup ready. Delivering SKILL-pb-setup body (${skill.body.length} chars).`,\n {\n bootstrap: \"pb-setup\",\n skillEntryId: skill.entryId,\n skillBody: skill.body,\n stage: \"setup\",\n oriented,\n orientationStatus,\n ...(agentSessionId ? { sessionId: agentSessionId } : {}),\n instructions: \"Read skillBody and follow it; use commit-entry/entries/orient MCP tools per PAT-227.\",\n },\n ),\n };\n}\n\n/**\n * Grounded/connected stage: return orient-style standup briefing.\n * Mirrors buildOrientResponse from the former start.ts.\n */\nasync function buildOrientResponse(\n wsCtx: { workspaceName: string; workspaceSlug: string; workspaceId: string; createdAt?: number | null; governanceMode?: string },\n agentSessionId: string | null,\n errors: string[],\n task?: string,\n): Promise<{ text: string; structuredContent: Record<string, unknown> }> {\n const { ageDays, isNeglected } = computeWorkspaceAge(wsCtx.createdAt ?? null);\n\n let priorSessions: PriorSession[] = [];\n let recoveryBlock: Record<string, unknown> | null = null;\n try {\n const sessionsResult = await kernelQuery<{ sessions: PriorSession[]; recoveryBlock: Record<string, unknown> | null }>(\"agent.recentSessions\", { limit: 3 });\n priorSessions = sessionsResult?.sessions ?? [];\n recoveryBlock = sessionsResult?.recoveryBlock ?? null;\n } catch { /* non-critical */ }\n\n let openTensions: Array<{ name: string; entryId?: string }> = [];\n try {\n const tensions = await kernelQuery<Array<{ name: string; entryId?: string; workflowStatus?: string }>>(\"chain.listEntries\", { collectionSlug: \"tensions\" });\n openTensions = (tensions ?? []).filter((e) => e.workflowStatus === \"open\");\n } catch { /* non-critical */ }\n\n let readiness: WorkspaceReadiness | null = null;\n try {\n readiness = await kernelQuery<WorkspaceReadiness>(\"chain.workspaceReadiness\");\n } catch (e: unknown) {\n errors.push(`Readiness: ${e instanceof Error ? e.message : String(e)}`);\n }\n\n const lines: string[] = [];\n const isLowReadiness = readiness !== null && readiness.score < 50;\n const isHighReadiness = readiness !== null && readiness.score >= 50;\n const stage: string | null = readiness?.stage ?? null;\n const captureBehaviorNote =\n wsCtx.governanceMode === \"open\"\n ? \"_In Open mode, user-authored captures commit immediately unless you ask me to keep them as drafts._\"\n : \"_Everything I capture stays pending until you confirm._\";\n\n const coherence = buildCoherenceSection();\n\n let allCollections: CollectionDocFields[] = [];\n try {\n allCollections = (await kernelQuery<CollectionDocFields[]>(\"chain.listCollections\")) ?? [];\n } catch { /* non-critical */ }\n\n lines.push(`# ${wsCtx.workspaceName}`);\n lines.push(\"_Product Brain is ready._\");\n lines.push(\"\");\n\n if (isLowReadiness && isNeglected) {\n const stageNote = stage ? ` and is still at the **${stage}** stage` : \"\";\n lines.push(`Your workspace has been around for ${ageDays} days${stageNote}.`);\n lines.push(\"Let's close the gaps — or if the current structure doesn't fit, we can reshape it.\");\n lines.push(\"\");\n } else if (isLowReadiness) {\n lines.push(\"Let's get your workspace active.\");\n lines.push(\"\");\n }\n\n if (isLowReadiness && readiness) {\n const gaps: ReadinessGap[] = readiness.gaps ?? [];\n if (gaps.length > 0) {\n const gapCtx: GapContext = {\n stage: stage ?? \"seeded\",\n passedChecks: readiness.passedChecks ?? 0,\n totalChecks: readiness.totalChecks ?? 0,\n score: readiness.score ?? 0,\n };\n\n lines.push(formatTopGapPrompt(gaps[0], gaps.length - 1, gapCtx));\n lines.push(\"\");\n lines.push(captureBehaviorNote);\n lines.push(\"\");\n\n const remainingGaps = gaps.length - 1;\n if (remainingGaps > 0 || openTensions.length > 0) {\n const parts: string[] = [];\n if (remainingGaps > 0) parts.push(`${remainingGaps} more area${remainingGaps === 1 ? \"\" : \"s\"} to cover`);\n if (openTensions.length > 0) parts.push(`${openTensions.length} open tension${openTensions.length === 1 ? \"\" : \"s\"}`);\n lines.push(`_${parts.join(\" and \")} — ask for full status to see everything._`);\n lines.push(\"\");\n }\n } else {\n const tensionPrompt = pickNextTensionPrompt(openTensions);\n if (tensionPrompt) {\n lines.push(`**${tensionPrompt.action}**`);\n lines.push(tensionPrompt.cta);\n lines.push(\"\");\n }\n }\n\n lines.push(\"_Need a collection that doesn't exist yet? Just ask — I'll set it up._\");\n lines.push(\"\");\n } else if (isHighReadiness) {\n let activeBets: ActiveBet[] = [];\n try {\n const betsEntries = await kernelQuery<Array<ActiveBet & { data?: { horizon?: string; status?: string }; status?: string }>>(\"chain.listEntries\", { collectionSlug: \"work-packages\" });\n activeBets = (betsEntries ?? [])\n .filter((e) => isActiveNowBet(e))\n .map((e) => ({ name: e.name, entryId: e.entryId ?? null }))\n .slice(0, 8);\n } catch { /* non-critical */ }\n\n if (task) {\n if (activeBets.length > 0) {\n lines.push(\"\");\n lines.push(\"## Active bets — current scope\");\n lines.push(\"_Work outside these bets requires explicit user confirmation._\");\n lines.push(\"\");\n for (const e of activeBets) {\n lines.push(`- \\`${e.entryId ?? e.name}\\` ${e.name}`);\n }\n lines.push(\"\");\n }\n\n let wsPrinciples: StandardEntry[] = [];\n let wsStandards: StandardEntry[] = [];\n let wsBusinessRules: StandardEntry[] = [];\n try {\n const govCollections = await getByNavGroup(\"governance\");\n const govSlugs = govCollections.map((c) => c.slug);\n for (const slug of govSlugs) {\n const entries = await kernelQuery<Array<StandardEntry & { status?: string; data?: { description?: string } }>>(\"chain.listEntries\", { collectionSlug: slug });\n const active = (entries ?? []).filter((e) => e.status === \"active\");\n const colDef = govCollections.find((c) => c.slug === slug);\n const ck = colDef?.defaultCanonicalKey;\n if (ck === \"principle\") wsPrinciples = [...wsPrinciples, ...active];\n else if (ck === \"standard\") wsStandards = [...wsStandards, ...active];\n else if (ck === \"business_rule\") wsBusinessRules = [...wsBusinessRules, ...active];\n }\n } catch { /* non-critical */ }\n\n const mapGovEntry = (e: StandardEntry & { data?: { description?: string } }): StandardEntry => ({\n entryId: e.entryId,\n name: e.name,\n description: typeof e.data?.description === \"string\" ? e.data.description : (typeof e.description === \"string\" ? e.description : undefined),\n });\n lines.push(...buildOperatingProtocol({\n principles: wsPrinciples.map(mapGovEntry),\n standards: wsStandards.map(mapGovEntry),\n businessRules: wsBusinessRules.map(mapGovEntry),\n }, task));\n\n if (coherence) {\n lines.push(...coherence.lines);\n }\n\n if (allCollections.length > 0) {\n const docCompleteness = buildDocCompletenessSection(allCollections);\n if (docCompleteness.errorCount > 0 || docCompleteness.warningCount > 0) {\n lines.push(...docCompleteness.lines);\n }\n }\n\n const plannedWork = await queryPlannedWork();\n\n if (hasPlannedWork(plannedWork)) {\n lines.push(\"\");\n lines.push(...buildPlannedWorkSection(plannedWork, priorSessions, recoveryBlock));\n } else if (recoveryBlock) {\n lines.push(\"\");\n lines.push(...formatRecoveryBlock(recoveryBlock as Parameters<typeof formatRecoveryBlock>[0]));\n }\n\n try {\n const allEntries = await kernelQuery<Array<{ status?: string; seededByPlatform?: boolean; collectionId?: string; collection?: string }>>(\"chain.listEntries\", {});\n const committed = (allEntries ?? []).filter(\n (e) => e.status === \"active\" && !e.seededByPlatform,\n );\n const committedCollections = new Set(committed.map((e) => e.collectionId ?? e.collection));\n\n if (committed.length >= 10 && committedCollections.size >= 3) {\n lines.push(\"\");\n lines.push(`_${committed.length} entries across ${committedCollections.size} collections on the Chain._`);\n }\n } catch { /* non-critical */ }\n\n lines.push(\"\");\n lines.push(`Working on: **${task}**`);\n lines.push(\"\");\n } else {\n if (activeBets.length > 0) {\n lines.push(\"\");\n lines.push(\"## Active bets — current scope\");\n lines.push(\"_Work outside these bets requires explicit user confirmation._\");\n lines.push(\"\");\n for (const e of activeBets) {\n lines.push(`- \\`${e.entryId ?? e.name}\\` ${e.name}`);\n }\n lines.push(\"\");\n }\n\n lines.push(...buildOperatingProtocol());\n\n if (coherence) {\n lines.push(...coherence.lines);\n }\n\n if (allCollections.length > 0) {\n const docCompleteness = buildDocCompletenessSection(allCollections);\n if (docCompleteness.errorCount > 0 || docCompleteness.warningCount > 0) {\n lines.push(...docCompleteness.lines);\n }\n }\n\n if (priorSessions.length > 0 && !recoveryBlock) {\n const last = priorSessions[0];\n const date = last.startedAt ? new Date(last.startedAt).toISOString().split(\"T\")[0] : \"unknown\";\n const created = Array.isArray(last.entriesCreated) ? last.entriesCreated.length : last.entriesCreated ?? 0;\n const modified = Array.isArray(last.entriesModified) ? last.entriesModified.length : last.entriesModified ?? 0;\n lines.push(`_Last session (${date}): ${created} created, ${modified} modified._`);\n lines.push(\"\");\n }\n\n if (recoveryBlock) {\n lines.push(\"\");\n lines.push(...formatRecoveryBlock(recoveryBlock as Parameters<typeof formatRecoveryBlock>[0]));\n }\n\n lines.push(\"**What are you working on?** Tell me and I'll load relevant governance and context.\");\n lines.push(\"\");\n }\n }\n\n if (errors.length > 0) {\n lines.push(\"## Errors\");\n for (const err of errors) lines.push(`- ${err}`);\n lines.push(\"\");\n }\n\n const { oriented, orientationStatus } = await tryMarkOriented(agentSessionId, coherence?.snapshot);\n\n const stageLabel = stage ?? \"active\";\n const gapCount = readiness?.gaps?.length ?? 0;\n const summaryParts = [`Product Brain ready. Stage: ${stageLabel}.`];\n if (gapCount > 0) summaryParts.push(`${gapCount} gap${gapCount === 1 ? \"\" : \"s\"}.`);\n if (openTensions.length > 0) summaryParts.push(`${openTensions.length} open tension${openTensions.length === 1 ? \"\" : \"s\"}.`);\n\n const next: NextAction[] = [];\n if (gapCount > 0) {\n next.push({ tool: \"capture\", description: \"Fill a gap\", parameters: {} });\n }\n if (openTensions.length > 0) {\n next.push({ tool: \"entries\", description: \"View open tensions\", parameters: { action: \"list\", collection: \"tensions\" } });\n }\n\n return {\n text: lines.join(\"\\n\"),\n structuredContent: success(\n summaryParts.join(\" \"),\n {\n stage,\n readinessScore: readiness?.score ?? null,\n totalGaps: gapCount,\n openTensions: openTensions.length,\n oriented,\n orientationStatus,\n ...(agentSessionId ? { sessionId: agentSessionId } : {}),\n },\n next.length > 0 ? next : undefined,\n ),\n };\n}\n\nexport function registerStartPbTools(server: McpServer) {\n server.registerTool(\n \"start_pb\",\n {\n title: \"Start Product Brain\",\n description:\n \"Universal session opener — say 'Start PB' to begin every session (PAT-227).\\n\\n\" +\n \"Stage-aware delivery:\\n\" +\n \"- **Fresh workspace (blank/seeded)**: returns the canonical SKILL-pb-setup body verbatim. The skill drives the install-to-activation flow.\\n\" +\n \"- **Active workspace (grounded/connected)**: standup briefing with active bets, governance, and recent activity.\\n\\n\" +\n \"Always call this first. It starts a session, stamps the surface, and loads the right guidance for your stage. \" +\n \"Replaces both the former `start` tool and the former chat-only `start_pb` bootstrap.\",\n inputSchema: startPbSchema,\n annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false },\n },\n thinWrapper(async ({ task }) => {\n const errors: string[] = [];\n const agentSessionId = getAgentSessionId();\n\n let wsCtx: Awaited<ReturnType<typeof getWorkspaceContext>> | null = null;\n try {\n wsCtx = await getWorkspaceContext();\n } catch (e: unknown) {\n errors.push(`Workspace: ${e instanceof Error ? e.message : String(e)}`);\n }\n\n if (!wsCtx) {\n const text =\n \"# Could not connect to Product Brain\\n\\n\" +\n (errors.length > 0 ? errors.map((e) => `- ${e}`).join(\"\\n\") : \"Check your API key and CONVEX_SITE_URL.\");\n return {\n content: [{ type: \"text\" as const, text }],\n structuredContent: failure(\n \"BACKEND_UNAVAILABLE\",\n \"Could not connect to Product Brain.\",\n \"Check your API key and CONVEX_SITE_URL.\",\n ),\n };\n }\n\n // Branch on readiness stage (PAT-227).\n // Do NOT default to \"blank\" on readiness failure — an active workspace\n // seeing setup instructions on a transient error would be actively harmful.\n let stage: string | null = null;\n try {\n const readiness = await kernelQuery<WorkspaceReadiness>(\"chain.workspaceReadiness\");\n stage = readiness?.stage ?? \"blank\";\n } catch {\n errors.push(\"Readiness check unavailable — showing workspace summary.\");\n }\n\n if (stage === \"blank\" || stage === \"seeded\") {\n // DEC-993 / STD-235: stamp surface + return setup skill body verbatim\n const result = await buildSetupResponse(agentSessionId);\n return {\n content: textContent(result.text),\n structuredContent: result.structuredContent,\n };\n }\n\n // grounded, connected, or readiness failed → orient-style standup\n if (stage === \"grounded\" || stage === \"connected\") {\n void kernelMutation(\"chain.setOnboardingCompleted\", {}).catch(() => { /* non-critical */ });\n }\n\n const orientResult = await buildOrientResponse(wsCtx, agentSessionId, errors, task);\n return {\n content: [{ type: \"text\" as const, text: orientResult.text }],\n structuredContent: orientResult.structuredContent,\n };\n }),\n );\n}\n","/**\n * `skills` MCP tool — generic workspace skill-body loader (WP-431 S5, DEC-998).\n *\n * Pure entryId-keyed retrieval: no allow-list, no pb-setup-specific code path.\n * Any caller passing a SKILL-* entryId for their workspace gets the skill body\n * back. The chat-only `start_pb` bootstrap calls this tool internally so the\n * load path stays single-source (S6 contract test pins that).\n *\n * Auth perimeter mirrors `recordTransition` (STD-234): the AKI gateway injects\n * `apiKeyId | personId | clerkUserId` server-side; this tool just calls the\n * gateway via `kernelQuery` and lets the server resolve identity.\n */\n\nimport { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { z } from \"zod\";\nimport { kernelQuery, getWorkspaceId } from \"../client.js\";\nimport { thinWrapper, success, textContent } from \"../envelope.js\";\n\nexport const skillsSchema = z.object({\n entryId: z\n .string()\n .min(1)\n .describe(\n \"Workspace-scoped skill entry id (e.g. 'SKILL-pb-setup'). The tool refuses \" +\n \"non-skill entries (canonicalKey !== 'skill') with INVALID_KIND.\",\n ),\n});\n\nexport interface SkillBodyResult {\n entryId: string;\n name: string;\n body: string;\n contentType: \"text/markdown\";\n retrievedAt: number;\n}\n\n/**\n * Load a SKILL-* entry's body for the caller's workspace. Internal helper used\n * by both the `skills` tool registration and `start_pb` (which routes through\n * the same loader by contract — DEC-997).\n */\nexport async function loadSkillBody(entryId: string): Promise<SkillBodyResult> {\n const workspaceId = await getWorkspaceId();\n return await kernelQuery<SkillBodyResult>(\"setup.getSkillBody\", {\n workspaceId,\n entryId,\n });\n}\n\nexport function registerSkillsTools(server: McpServer) {\n server.registerTool(\n \"skills\",\n {\n title: \"Load workspace skill body\",\n description:\n \"Loads the markdown body of a SKILL-* entry from the current workspace. \" +\n \"Generic loader: works for ANY skill in your workspace — no allow-list, \" +\n \"no pb-setup-specific behavior. Use this when an agent or MCP client \" +\n \"needs the canonical body of a skill (e.g. SKILL-pb-setup, SKILL-shape, \" +\n \"SKILL-review). Returns markdown plus name + retrievedAt for caching.\",\n inputSchema: skillsSchema,\n annotations: { readOnlyHint: true, idempotentHint: true, openWorldHint: false },\n },\n thinWrapper(async ({ entryId }) => {\n const result = await loadSkillBody(entryId);\n const summary = `Loaded ${result.entryId} (${result.body.length} chars).`;\n return {\n content: textContent(result.body),\n structuredContent: success(summary, result),\n };\n }),\n );\n}\n","/**\n * Shared \"planned work\" query and formatting for orient/start.\n *\n * Surfaces uncommitted drafts, in-progress features/decisions, and\n * open tensions as a single \"Continue from\" section with a concrete CTA.\n */\n\nimport { kernelQuery } from \"../client.js\";\n\n/** Loosely-typed session record returned by agent.recentSessions. */\nexport interface PriorSession {\n startedAt?: string | number;\n entriesCreated?: string[] | number;\n entriesModified?: string[] | number;\n [key: string]: unknown;\n}\n\nexport interface PlannedWork {\n uncommittedDrafts: Array<{ name: string; collection: string }>;\n inProgressEntries: Array<{ name: string; collection: string; entryId: string }>;\n openTensions: Array<{ name: string; entryId: string }>;\n}\n\nexport function buildPlannedWork(allEntries: any[]): PlannedWork {\n const result: PlannedWork = {\n uncommittedDrafts: [],\n inProgressEntries: [],\n openTensions: [],\n };\n\n for (const entry of allEntries) {\n if (entry.stratum === 'system') continue;\n\n const collection = entry.collectionSlug ?? entry.collection ?? \"unknown\";\n\n if (entry.status === \"draft\") {\n result.uncommittedDrafts.push({ name: entry.name, collection });\n }\n\n // BET-281: Use canonicalKey to identify tensions instead of hardcoded slug.\n // canonicalKey is optional on entries, so fall back to slug for backward compat.\n const isTension = entry.canonicalKey === \"tension\" || collection === \"tensions\";\n if (isTension && entry.workflowStatus === \"open\") {\n result.openTensions.push({ name: entry.name, entryId: entry.entryId ?? entry._id });\n }\n\n if (entry.workflowStatus === \"in-progress\") {\n result.inProgressEntries.push({\n name: entry.name,\n collection,\n entryId: entry.entryId ?? entry._id,\n });\n }\n }\n\n return result;\n}\n\nexport async function queryPlannedWork(): Promise<PlannedWork> {\n try {\n const allEntries = await kernelQuery<any[]>(\"chain.listEntries\", {});\n if (!allEntries) return { uncommittedDrafts: [], inProgressEntries: [], openTensions: [] };\n return buildPlannedWork(allEntries);\n } catch {\n return { uncommittedDrafts: [], inProgressEntries: [], openTensions: [] };\n }\n}\n\nexport function hasPlannedWork(work: PlannedWork): boolean {\n return (\n work.uncommittedDrafts.length > 0 ||\n work.inProgressEntries.length > 0 ||\n work.openTensions.length > 0\n );\n}\n\n/** ENT-yaic53: Format recovery block from Convex structured data. */\nexport function formatRecoveryBlock(block: {\n sessionId: string;\n status: 'timed_out' | 'completed';\n date: string;\n duration: string;\n created: { entryId: string; collection: string; name: string }[];\n modified: { entryId: string; collection: string; name: string }[];\n draftsNeedingAttention: { entryId: string; collection: string; name: string }[];\n relationsCreated: number;\n createdOverflow?: number;\n modifiedOverflow?: number;\n draftsOverflow?: number;\n}): string[] {\n const fmt = (items: { entryId: string; collection: string; name: string }[], overflow?: number) =>\n items.map((e) => `${e.entryId} [${e.collection}] ${e.name}`).join(', ') +\n (overflow && overflow > 0 ? ` (+${overflow} more)` : '');\n\n const lines: string[] = [\n '## Previous Session Recovery',\n '',\n `Previous session — ${block.date}, ${block.duration}, status: ${block.status}`,\n `Created (${block.created.length + (block.createdOverflow ?? 0)}): ${fmt(block.created, block.createdOverflow)}`,\n `Modified (${block.modified.length + (block.modifiedOverflow ?? 0)}): ${fmt(block.modified, block.modifiedOverflow)}`,\n `Items pending review (${block.draftsNeedingAttention.length + (block.draftsOverflow ?? 0)}): ${fmt(block.draftsNeedingAttention, block.draftsOverflow)}`,\n `Relations created: ${block.relationsCreated}`,\n '',\n ];\n return lines;\n}\n\nexport function buildPlannedWorkSection(\n work: PlannedWork,\n priorSessions: PriorSession[],\n recoveryBlock?: { sessionId: string; status: 'timed_out' | 'completed'; date: string; duration: string; created: { entryId: string; collection: string; name: string }[]; modified: { entryId: string; collection: string; name: string }[]; draftsNeedingAttention: { entryId: string; collection: string; name: string }[]; relationsCreated: number; createdOverflow?: number; modifiedOverflow?: number; draftsOverflow?: number } | null,\n): string[] {\n if (!hasPlannedWork(work) && priorSessions.length === 0) return [];\n\n const lines: string[] = [];\n lines.push(\"## Continue from where you left off\");\n lines.push(\"\");\n\n if (work.inProgressEntries.length > 0) {\n const top = work.inProgressEntries[0];\n lines.push(`- **Active: ${top.name}** (${top.collection}) — want to continue?`);\n for (const entry of work.inProgressEntries.slice(1, 3)) {\n lines.push(`- ${entry.name} (${entry.collection})`);\n }\n if (work.inProgressEntries.length > 3) {\n lines.push(`- _...and ${work.inProgressEntries.length - 3} more in progress_`);\n }\n }\n\n if (work.uncommittedDrafts.length > 0) {\n const count = work.uncommittedDrafts.length;\n const label = count === 1 ? \"1 item pending\" : `${count} items pending`;\n const topNames = work.uncommittedDrafts\n .slice(0, 3)\n .map((d) => d.name)\n .join(\", \");\n lines.push(`- **${label}** — ${topNames}${count > 3 ? \", ...\" : \"\"}`);\n }\n\n if (work.openTensions.length > 0) {\n const top = work.openTensions[0];\n const count = work.openTensions.length;\n if (count === 1) {\n lines.push(`- **Open tension: ${top.name}** — discuss or capture a decision?`);\n } else {\n lines.push(`- **${count} open tensions** — top: ${top.name}`);\n }\n }\n\n if (priorSessions.length > 0 && !hasPlannedWork(work) && !recoveryBlock) {\n const last = priorSessions[0];\n const date = new Date(last.startedAt).toISOString().split(\"T\")[0];\n const created = Array.isArray(last.entriesCreated) ? last.entriesCreated.length : last.entriesCreated ?? 0;\n const modified = Array.isArray(last.entriesModified) ? last.entriesModified.length : last.entriesModified ?? 0;\n if (created > 0 || modified > 0) {\n lines.push(`- **Last session** (${date}): ${created} created, ${modified} modified`);\n }\n }\n\n if (recoveryBlock) {\n lines.push('');\n lines.push(...formatRecoveryBlock(recoveryBlock));\n }\n\n lines.push(\"\");\n return lines;\n}\n","/**\n * Doc-Completeness Check — ENT-65 / FEAT-201\n * BET-99: Complements the code-based coherence engine with DB-sourced field checks.\n *\n * Checks that collection documents have the required fields populated after the\n * DB-first migration. These checks replace the removed cross-registry sync rules\n * (sync-classification-defaults, sync-classification-classifier) which produced\n * false positives once CLASSIFICATION_MAP and CLASSIFICATION_META became seed-only.\n *\n * Rules:\n * - All collections: idPrefix, governed must be set\n * - Classifier collections (classificationCheck present): classificationPriority required\n * - Workflow collections (validWorkflowStatuses present): array must be non-empty\n */\n\nexport interface CollectionDocFields {\n slug: string;\n governed?: boolean | null;\n navGroup?: string | null;\n idPrefix?: string | null;\n validWorkflowStatuses?: string[] | null;\n classificationCheck?: string | null;\n classificationPriority?: number | null;\n}\n\nexport interface DocCompletenessViolation {\n slug: string;\n field: string;\n message: string;\n severity: \"error\" | \"warning\";\n fix: string;\n}\n\nexport interface DocCompletenessReport {\n checkedAt: number;\n totalChecked: number;\n violations: DocCompletenessViolation[];\n summary: { errors: number; warnings: number; total: number };\n}\n\n/**\n * Check collection docs for required field completeness.\n * Pure function — accepts pre-fetched collection data, no I/O.\n */\nexport function checkDocCompleteness(\n collections: CollectionDocFields[],\n checkedAt?: number,\n): DocCompletenessReport {\n const violations: DocCompletenessViolation[] = [];\n\n for (const col of collections) {\n const { slug } = col;\n\n // governed must be set (boolean)\n if (col.governed === undefined || col.governed === null) {\n violations.push({\n slug,\n field: \"governed\",\n message: `\"${slug}\" is missing the governed flag`,\n severity: \"warning\",\n fix: `Set governed on the \"${slug}\" collection document`,\n });\n }\n\n // idPrefix must be set\n if (!col.idPrefix) {\n violations.push({\n slug,\n field: \"idPrefix\",\n message: `\"${slug}\" is missing idPrefix`,\n severity: \"warning\",\n fix: `Set idPrefix on the \"${slug}\" collection document`,\n });\n }\n\n // Classifier fields must be consistent: check ↔ priority together\n const hasCheck = typeof col.classificationCheck === \"string\" && col.classificationCheck.length >= 3;\n const hasPriority = col.classificationPriority != null;\n\n if (hasCheck && !hasPriority) {\n violations.push({\n slug,\n field: \"classificationPriority\",\n message: `\"${slug}\" has classificationCheck but missing classificationPriority (1–9)`,\n severity: \"error\",\n fix: `Set classificationPriority (1–9) on the \"${slug}\" collection document`,\n });\n }\n\n if (hasPriority && !hasCheck) {\n violations.push({\n slug,\n field: \"classificationCheck\",\n message: `\"${slug}\" has classificationPriority but missing classificationCheck`,\n severity: \"error\",\n fix: `Set classificationCheck (3–500 chars) on the \"${slug}\" collection document`,\n });\n }\n\n // validWorkflowStatuses must be non-empty when present\n if (Array.isArray(col.validWorkflowStatuses) && col.validWorkflowStatuses.length === 0) {\n violations.push({\n slug,\n field: \"validWorkflowStatuses\",\n message: `\"${slug}\" has an empty validWorkflowStatuses array`,\n severity: \"error\",\n fix: `Add at least one status to validWorkflowStatuses on \"${slug}\", or remove the field`,\n });\n }\n }\n\n const errors = violations.filter((v) => v.severity === \"error\").length;\n const warnings = violations.filter((v) => v.severity === \"warning\").length;\n\n return {\n checkedAt: checkedAt ?? Date.now(),\n totalChecked: collections.length,\n violations,\n summary: { errors, warnings, total: violations.length },\n };\n}\n\n/**\n * Render doc-completeness report as orient section lines.\n * Returns empty array when there are no violations (clean state).\n */\nexport function renderDocCompletenessLines(report: DocCompletenessReport): string[] {\n const lines: string[] = [\"## Classification Doc-Completeness\"];\n\n if (report.summary.total === 0) {\n lines.push(`All ${report.totalChecked} collection docs have required fields populated.`);\n lines.push(\"\");\n return lines;\n }\n\n const parts: string[] = [];\n if (report.summary.errors > 0) parts.push(`${report.summary.errors} error${report.summary.errors === 1 ? \"\" : \"s\"}`);\n if (report.summary.warnings > 0) parts.push(`${report.summary.warnings} warning${report.summary.warnings === 1 ? \"\" : \"s\"}`);\n lines.push(`**${report.summary.total} gap${report.summary.total === 1 ? \"\" : \"s\"}** across ${report.totalChecked} collections (${parts.join(\", \")})`);\n\n const errors = report.violations.filter((v) => v.severity === \"error\");\n const warnings = report.violations.filter((v) => v.severity === \"warning\");\n\n if (errors.length > 0) {\n lines.push(\"\");\n lines.push(\"**Errors** (must fix):\");\n for (const v of errors.slice(0, 5)) {\n lines.push(`- ${v.message} — ${v.fix}`);\n }\n if (errors.length > 5) lines.push(`- ...and ${errors.length - 5} more`);\n }\n\n if (warnings.length > 0) {\n lines.push(\"\");\n lines.push(\"**Warnings**:\");\n for (const v of warnings.slice(0, 3)) {\n lines.push(`- ${v.message}`);\n }\n if (warnings.length > 3) lines.push(`- ...and ${warnings.length - 3} more`);\n }\n\n lines.push(\"\");\n return lines;\n}\n","/**\n * Shared functions for orient and start tools.\n * Single code path for alignment checks, operating protocol (STA-3),\n * codebase coherence (BET-99 / FEAT-182), and doc-completeness (ENT-65 / FEAT-201).\n */\n\nimport { checkAndRender, renderCoherenceGate, type CoherenceSnapshot, type CoherenceVerdict } from \"../lib/coherence/index.js\";\nimport { checkDocCompleteness, renderDocCompletenessLines, type CollectionDocFields } from \"../lib/coherence/doc-completeness.js\";\nimport { resolveProjectRoot } from \"../lib/resolve-project-root.js\";\nimport { isWorkPlanningCollection } from \"../lib/collectionCache.js\";\n\nexport type { CoherenceSnapshot, CoherenceVerdict } from \"../lib/coherence/index.js\";\nexport { renderCoherenceGate } from \"../lib/coherence/index.js\";\n\nexport interface CoherenceResult {\n lines: string[];\n snapshot: CoherenceSnapshot;\n}\n\n/**\n * Run codebase coherence check and produce orient/start section lines.\n * Returns null when check can't run (e.g. no filesystem access).\n * DEC-169: respects orient performance budget via early-exit on resolution failure.\n */\nexport function buildCoherenceSection(projectRoot?: string): CoherenceResult | null {\n try {\n const root = projectRoot ?? resolveProjectRoot() ?? process.cwd();\n return checkAndRender(root);\n } catch (err) {\n if (process.env.DEBUG_COHERENCE) {\n console.debug(\"[coherence] buildCoherenceSection failed:\", err instanceof Error ? err.message : err);\n }\n return null;\n }\n}\n\nexport { type CollectionDocFields } from \"../lib/coherence/doc-completeness.js\";\n\nexport interface DocCompletenessResult {\n lines: string[];\n errorCount: number;\n warningCount: number;\n}\n\n/**\n * Run doc-completeness check against fetched collection docs.\n * ENT-65 / FEAT-201: Replaces the removed cross-registry sync rules.\n * Caller is responsible for fetching collections — this is a pure rendering wrapper.\n */\nexport function buildDocCompletenessSection(\n collections: CollectionDocFields[],\n): DocCompletenessResult {\n const report = checkDocCompleteness(collections);\n const lines = renderDocCompletenessLines(report);\n return { lines, errorCount: report.summary.errors, warningCount: report.summary.warnings };\n}\n\nexport interface ActiveBet {\n name: string;\n entryId?: string | null;\n _id?: string;\n}\n\nexport interface AlignmentCheckResult {\n aligned: boolean;\n matchedBet: string | null;\n matchSource: \"active_bet\" | \"task_context\" | null;\n betNames: string[];\n}\n\nexport async function runAlignmentCheck(\n task: string,\n activeBets: ActiveBet[],\n taskContextHits?: Array<{ collectionSlug?: string; name?: string }>,\n): Promise<AlignmentCheckResult> {\n const betNames = activeBets.map((b) => b.name);\n const taskWords = extractKeywords(task);\n\n const matchingBet = activeBets.find((b) => {\n const words = (b.name ?? \"\").toLowerCase().split(/\\s+/);\n return taskWords.some((tw) => words.some((w) => w === tw || w.startsWith(tw + \"-\")));\n });\n\n if (matchingBet) {\n return { aligned: true, matchedBet: matchingBet.name, matchSource: \"active_bet\", betNames };\n }\n\n // BET-281: Derive work-planning collections from thinkingLayer instead of hardcoded slugs.\n // BET-132 TEN-510: Accept bets from any work-planning collection.\n const betHits: Array<{ collectionSlug?: string; name?: string }> = [];\n for (const e of taskContextHits ?? []) {\n if (e.collectionSlug && await isWorkPlanningCollection(e.collectionSlug)) {\n betHits.push(e);\n }\n }\n\n if (betHits.length > 0) {\n return { aligned: true, matchedBet: betHits[0]?.name ?? null, matchSource: \"task_context\", betNames };\n }\n\n return { aligned: false, matchedBet: null, matchSource: null, betNames };\n}\n\nexport function buildAlignmentCheckLines(\n result: AlignmentCheckResult,\n): string[] {\n const lines: string[] = [\"## Alignment Check\"];\n\n if (result.aligned && result.matchSource === \"active_bet\" && result.matchedBet) {\n lines.push(\n `Task aligns with active bet: **${result.matchedBet}**. Proceed.`,\n );\n } else if (result.aligned && result.matchSource === \"task_context\" && result.matchedBet) {\n const noActiveBets = result.betNames.length === 0;\n lines.push(\n `Task related to **${result.matchedBet}** via task context${noActiveBets ? \" (no active bets in horizon=now)\" : \"\"}. Proceed with caution — confirm scope with the user if uncertain.`,\n );\n } else if (result.betNames.length === 0) {\n lines.push(\n \"No active bets in workspace. Consider shaping a bet before building.\",\n );\n } else {\n lines.push(\"**This task does not match any active bet.**\");\n lines.push(`Active bets: ${result.betNames.join(\", \")}`);\n lines.push(\n \"Stop and confirm with the user before designing. This may be out of scope.\",\n );\n }\n\n lines.push(\"\");\n return lines;\n}\n\nconst CORE_PROTOCOL_BASE = [\n \"**Search before proposing.** Before suggesting new features, architecture, or changes, \" +\n \"search the Chain: `entries action=search query=\\\"<relevant terms>\\\"`. Build on what exists.\",\n \"**Reference by ID.** When discussing a topic that has Chain entries, cite them by entry ID \" +\n \"(e.g. `DEC-50`, `PRI-3`). This keeps conversations grounded in shared knowledge.\",\n \"**Check scope.** If the proposed work doesn't fall under an active bet, stop and say so. \" +\n \"Do not design implementation for out-of-scope work without explicit user go-ahead.\",\n \"**Capture continuously.** When a decision, tension, insight, or new term surfaces during \" +\n \"work, capture it as a draft immediately. Don't defer to \\\"later.\\\"\",\n];\n\nconst RULE5_WITH_GOVERNANCE =\n \"**Validate against governance.** Before proposing any solution, check it against the \" +\n \"Workspace Governance directives below. If your proposal conflicts with a principle, standard, \" +\n \"or business rule — stop, name the conflict, and get explicit user confirmation before proceeding.\";\n\nconst RULE5_COMPACT =\n \"**Validate against governance.** Before proposing or building anything, call \" +\n \"`orient task=\\\"<your task>\\\"` to load relevant governance. If your proposal conflicts with a \" +\n \"principle, standard, or business rule — stop, name the conflict, and get explicit user confirmation.\";\n\nexport interface StandardEntry {\n entryId?: string | null;\n name: string;\n description?: string;\n /** DEC-446: Relevance tier from backend (1=direct/org, 2=domain, 3=contextual/fallback) */\n tier?: number;\n}\n\nexport interface GovernanceEntries {\n principles?: StandardEntry[];\n standards?: StandardEntry[];\n businessRules?: StandardEntry[];\n}\n\nconst MAX_ENTRIES_NO_TASK = 3;\nconst MAX_ENTRIES_WITH_TASK = 5;\n\nfunction extractKeywords(text: string): string[] {\n const normalized = text.toLowerCase().replace(/[^\\w\\s-]/g, \" \");\n const tokens: string[] = [];\n for (const raw of normalized.split(/\\s+/)) {\n if (!raw) continue;\n // Split hyphenated/underscored compounds (\"auth-middleware\" → \"auth\", \"middleware\")\n // but keep the original compound too so \"auth-middleware\" matches entries containing it.\n const parts = raw.split(/[-_]/);\n if (parts.length > 1) tokens.push(raw.replace(/[-_]/g, \"\"));\n for (const p of parts) if (p) tokens.push(p);\n }\n return [...new Set(tokens.filter((w) => w.length > 2))];\n}\n\nfunction scoreEntry(entry: StandardEntry, keywords: string[]): number {\n const text = `${entry.name} ${entry.description ?? \"\"}`.toLowerCase();\n return keywords.filter((kw) => text.includes(kw)).length;\n}\n\nfunction formatGovernanceEntry(entry: StandardEntry): string {\n const id = entry.entryId ?? entry.name;\n const desc = entry.description\n ? ` — ${entry.description.slice(0, 120)}${entry.description.length > 120 ? \"...\" : \"\"}`\n : \"\";\n // DEC-446: Show tier label when backend provides relevance ranking\n const tierLabel = entry.tier === 1 ? \" `[direct]`\" : entry.tier === 2 ? \" `[domain]`\" : \"\";\n return `- **[${id}]** ${entry.name}${tierLabel}${desc}`;\n}\n\n/**\n * Build the Operating Protocol section for orient/start output.\n *\n * Two modes:\n * - With governance entries: full mode — rule 5 says \"check directives below\"\n * - Without governance (compact): rule 5 says \"call orient task=... to load governance\"\n *\n * Accepts either the new GovernanceEntries object or a plain StandardEntry[]\n * for backward compatibility.\n */\nexport function buildOperatingProtocol(\n governanceOrStandards?: GovernanceEntries | StandardEntry[],\n task?: string,\n): string[] {\n const governance: GovernanceEntries = Array.isArray(governanceOrStandards)\n ? { standards: governanceOrStandards }\n : governanceOrStandards ?? {};\n\n const { principles = [], standards = [], businessRules = [] } = governance;\n const hasGovernance =\n principles.length > 0 || standards.length > 0 || businessRules.length > 0;\n\n const rule5 = hasGovernance ? RULE5_WITH_GOVERNANCE : RULE5_COMPACT;\n const protocol = [...CORE_PROTOCOL_BASE, rule5];\n\n const lines: string[] = [\n \"## Operating Protocol\",\n \"_How to work in this workspace. Follow these before and during every task._\",\n \"\",\n ];\n\n for (let i = 0; i < protocol.length; i++) {\n lines.push(`${i + 1}. ${protocol[i]}`);\n }\n\n if (hasGovernance) {\n lines.push(\"\");\n lines.push(\"### Workspace governance directives\");\n\n const types: Array<{\n header: string;\n entries: StandardEntry[];\n }> = [\n { header: \"**Active principles:**\", entries: principles },\n { header: \"**Active business rules:**\", entries: businessRules },\n { header: \"**Active standards:**\", entries: standards },\n ];\n\n if (task) {\n // DEC-446: When backend provides tier labels, use tier as primary sort\n // and skip keyword re-scoring. Fall back to keyword scoring only when\n // no entries have tier labels (backward compat with older backends).\n const hasTiers = types.some((t) => t.entries.some((e) => e.tier !== undefined));\n const keywords = hasTiers ? [] : extractKeywords(task);\n let shownCount = 0;\n let totalGovernance = 0;\n\n for (const type of types) {\n if (type.entries.length === 0) continue;\n totalGovernance += type.entries.length;\n\n let sorted: StandardEntry[];\n if (hasTiers) {\n // Backend already ranked by relevance tier — respect that order\n sorted = [...type.entries].sort((a, b) => (a.tier ?? 99) - (b.tier ?? 99));\n } else {\n // Legacy: keyword scoring when backend doesn't provide tiers\n const scored = type.entries\n .map((e) => ({ entry: e, score: scoreEntry(e, keywords) }))\n .filter((s) => s.score > 0)\n .sort((a, b) => b.score - a.score);\n sorted = scored.length > 0\n ? scored.map((s) => s.entry)\n : type.entries.slice(0, MAX_ENTRIES_NO_TASK);\n }\n\n const capped = sorted.slice(0, MAX_ENTRIES_WITH_TASK);\n if (capped.length > 0) {\n shownCount += capped.length;\n lines.push(type.header);\n for (const e of capped) {\n lines.push(formatGovernanceEntry(e));\n }\n lines.push(\"\");\n }\n }\n\n const filterNote = hasTiers ? \"ranked by relevance\" : \"filtered by task keywords\";\n lines.push(\n `_${shownCount} of ${totalGovernance} governance entries shown, ${filterNote}._`,\n );\n } else {\n for (const type of types) {\n if (type.entries.length === 0) continue;\n lines.push(type.header);\n for (const e of type.entries.slice(0, MAX_ENTRIES_NO_TASK)) {\n lines.push(formatGovernanceEntry(e));\n }\n lines.push(\"\");\n }\n lines.push(\n '_Showing top governance entries. Use `orient task=\"...\"` for task-relevant filtering._',\n );\n }\n }\n\n lines.push(\"\");\n return lines;\n}\n\n// ─── BET-126 Slice 2: Hierarchy-aware orient sections ────────────────────────\n\n/** Initiative status item from getOrientEntries (BET-126). */\nexport interface InitiativeStatusItem {\n id: string;\n entryId: string;\n name: string;\n targetDate: number | null;\n daysRemaining: number | null;\n}\n\n/** Workstream health item from getOrientEntries (BET-126). */\nexport interface WorkstreamHealthItem {\n id: string;\n name: string;\n betCount: number;\n activeBetNames: string[];\n}\n\n/** WP-383 S3: Advisory signal — bet with a validates relation to a KR whose outcome verification is overdue. */\nexport interface OverdueOutcomeBlocker {\n betId: string;\n betName: string;\n krId: string;\n krName: string;\n scheduledVerificationDate: string;\n daysOverdue: number;\n}\n\n/** What needs attention from getOrientEntries (BET-126). */\nexport interface WhatNeedsAttention {\n overdueBets: string[];\n blockedBets: string[];\n criticalPathBets: string[];\n /** WP-383 S3: Advisory — bets whose validates-linked KR verification window has passed. */\n overdueOutcomeBlockers?: OverdueOutcomeBlocker[];\n}\n\n/** Constellation entry item from getOrientEntries (BET-126 Slice 3). */\nexport interface ConstellationEntryItem {\n entryId: string;\n name: string;\n collectionSlug: string;\n canonicalKey: string | null;\n}\n\n/**\n * Format Bet Constellation section for full-mode orient (BET-126 Slice 3).\n * Returns empty array if constellationEntries is empty — no empty headers.\n */\nexport function formatBetConstellationLines(\n constellationEntries: ConstellationEntryItem[] | undefined | null,\n constellationBetName?: string,\n): string[] {\n if (!constellationEntries?.length) return [];\n const betName = constellationBetName ?? \"Matched bet\";\n const lines: string[] = [\n `## Bet Constellation — ${betName}`,\n \"_Decisions, tensions, and features related to the matched bet._\",\n \"\",\n ];\n const bySlug = new Map<string, ConstellationEntryItem[]>();\n for (const e of constellationEntries) {\n const list = bySlug.get(e.collectionSlug) ?? [];\n list.push(e);\n bySlug.set(e.collectionSlug, list);\n }\n const order = [\"decisions\", \"tensions\", \"features\"];\n for (const slug of order) {\n const entries = bySlug.get(slug);\n if (!entries?.length) continue;\n const label = slug.charAt(0).toUpperCase() + slug.slice(1);\n lines.push(`**${label}:**`);\n for (const e of entries) {\n lines.push(`- \\`${e.entryId}\\` — ${e.name}`);\n }\n lines.push(\"\");\n }\n return lines;\n}\n\n/**\n * Format Initiative Status section for full-mode orient.\n * Returns empty array if initiatives is empty — no empty headers.\n */\nexport function formatInitiativeStatusLines(\n initiatives: InitiativeStatusItem[] | undefined | null,\n): string[] {\n if (!initiatives?.length) return [];\n const lines: string[] = [\"## Initiative Status\", \"\"];\n for (const i of initiatives) {\n const dateStr =\n i.targetDate != null\n ? new Date(i.targetDate).toISOString().split(\"T\")[0]\n : null;\n const daysPart =\n i.daysRemaining != null && dateStr\n ? `${i.daysRemaining} days to ${dateStr}`\n : dateStr\n ? `Target: ${dateStr}`\n : \"\";\n lines.push(`- \\`${i.entryId}\\` ${i.name}${daysPart ? ` — ${daysPart}` : \"\"}`);\n }\n lines.push(\"\");\n return lines;\n}\n\n/**\n * Format Workstream Health section for full-mode orient.\n * Returns empty array if workstreams is empty — no empty headers.\n */\nexport function formatWorkstreamHealthLines(\n workstreams: WorkstreamHealthItem[] | undefined | null,\n): string[] {\n if (!workstreams?.length) return [];\n const lines: string[] = [\"## Workstream Health\", \"\"];\n for (const ws of workstreams) {\n const betDetail = ws.activeBetNames?.length\n ? ws.activeBetNames.join(\", \")\n : `${ws.betCount} bet(s)`;\n lines.push(`- ${ws.name} — ${betDetail}`);\n }\n lines.push(\"\");\n return lines;\n}\n\n/**\n * Format What Needs Attention section for full-mode orient.\n * Returns empty array if nothing needs attention — no empty headers.\n */\nexport function formatWhatNeedsAttentionLines(\n wna: WhatNeedsAttention | undefined | null,\n): string[] {\n if (!wna) return [];\n const hasOverdue = (wna.overdueBets?.length ?? 0) > 0;\n const hasBlocked = (wna.blockedBets?.length ?? 0) > 0;\n const hasCritical = (wna.criticalPathBets?.length ?? 0) > 0;\n const hasOutcomeBlockers = (wna.overdueOutcomeBlockers?.length ?? 0) > 0;\n if (!hasOverdue && !hasBlocked && !hasCritical && !hasOutcomeBlockers) return [];\n const lines: string[] = [\"## What Needs Attention\", \"\"];\n if (hasOverdue) {\n lines.push(\"**Overdue:**\");\n for (const id of wna.overdueBets ?? []) lines.push(`- \\`${id}\\``);\n lines.push(\"\");\n }\n if (hasBlocked) {\n lines.push(\"**Blocked:**\");\n for (const id of wna.blockedBets ?? []) lines.push(`- \\`${id}\\``);\n lines.push(\"\");\n }\n if (hasCritical) {\n lines.push(\"**Critical path:**\");\n for (const id of wna.criticalPathBets ?? []) lines.push(`- \\`${id}\\``);\n lines.push(\"\");\n }\n if (hasOutcomeBlockers) {\n lines.push(\"**Overdue outcome verifications (advisory):**\");\n for (const b of wna.overdueOutcomeBlockers ?? []) {\n lines.push(`- \\`${b.betId}\\` → \\`${b.krId}\\` (${b.daysOverdue}d overdue — ${b.scheduledVerificationDate})`);\n }\n lines.push(\"\");\n }\n return lines;\n}\n\n/**\n * Compact \"What needs attention\" block for brief mode (1–3 bullets: overdue, blocked).\n * Returns empty array if nothing needs attention.\n */\nexport function formatWhatNeedsAttentionBrief(\n wna: WhatNeedsAttention | undefined | null,\n): string[] {\n if (!wna) return [];\n const overdue = wna.overdueBets ?? [];\n const blocked = wna.blockedBets ?? [];\n const critical = wna.criticalPathBets ?? [];\n const outcomeBlockers = wna.overdueOutcomeBlockers ?? [];\n if (overdue.length === 0 && blocked.length === 0 && critical.length === 0 && outcomeBlockers.length === 0) return [];\n const bullets: string[] = [\n ...overdue.slice(0, 2).map((id) => `\\`${id}\\` (overdue)`),\n ...blocked.slice(0, 2).map((id) => `\\`${id}\\` (blocked)`),\n ...critical.slice(0, 1).map((id) => `\\`${id}\\` (critical path)`),\n ...(outcomeBlockers.length > 0\n ? [`${outcomeBlockers.length} bet${outcomeBlockers.length > 1 ? \"s\" : \"\"} with overdue outcome verification`]\n : []),\n ].slice(0, 3);\n if (bullets.length === 0) return [];\n const lines: string[] = [\"**What needs attention:**\", ...bullets.map((b) => `- ${b}`), \"\"];\n return lines;\n}\n","/**\n * gapToPrompt.ts — Readiness gaps as conversation, not compliance.\n *\n * FEAT-62 (BET-64 Slice 1): Translates raw readiness gap data into\n * natural-language prompts with contextual framing. The user should\n * hear a collaborator suggesting what to work on — never a checklist.\n *\n * Consumed by orient (health.ts) and start (start.ts).\n * Source prompts come from collection.readinessGuidance (DB).\n */\n\n// ── Types ────────────────────────────────────────────────────────────────────\n\nexport interface ReadinessGap {\n id: string;\n label: string;\n guidance: string;\n capabilityGuidance?: string;\n canonicalKey?: string;\n current: number;\n required: number;\n}\n\nexport interface GapContext {\n stage: string;\n passedChecks: number;\n totalChecks: number;\n score: number;\n}\n\n// ── Label cleanup ────────────────────────────────────────────────────────────\n// Raw gap labels come through as \"Glossary has entries\" or \"Strategy — your\n// product vision\". Strip the mechanical suffixes to get a clean noun.\n\nfunction cleanLabel(label: string): string {\n return label\n .replace(/ has entries$/i, \"\")\n .replace(/ coverage$/i, \"\")\n .replace(/^Strategy — /i, \"\");\n}\n\n// ── Progress framing ─────────────────────────────────────────────────────────\n// One sentence that grounds the user in where they are. Warm, not clinical.\n\nfunction progressFrame(ctx: GapContext): string {\n if (ctx.passedChecks === 0) {\n return \"Your Brain is just getting started.\";\n }\n if (ctx.passedChecks === 1) {\n return \"Your Brain has one area covered so far.\";\n }\n if (ctx.score >= 70) {\n return `Your Brain covers ${ctx.passedChecks} areas — almost there.`;\n }\n return `Your Brain covers ${ctx.passedChecks} of ${ctx.totalChecks} areas.`;\n}\n\n// ── Single gap prompt ────────────────────────────────────────────────────────\n\n/**\n * Format the most impactful gap as a conversational next-step prompt.\n * Used in orient (low-readiness) and start (orient-style) responses.\n */\nexport function formatTopGapPrompt(\n gap: ReadinessGap,\n remaining: number,\n ctx: GapContext,\n): string {\n const prompt = gap.capabilityGuidance ?? gap.guidance;\n const label = cleanLabel(gap.label);\n\n const lines = [\n progressFrame(ctx),\n remaining > 0\n ? `The biggest gap right now: **${label}**.`\n : `One area would strengthen it: **${label}**.`,\n \"\",\n prompt,\n ];\n\n return lines.join(\"\\n\");\n}\n\n// ── Multi-gap list ───────────────────────────────────────────────────────────\n\n/**\n * Format multiple gaps as natural suggestions (not a checklist).\n * Used in start seeded response and orient full mode.\n */\nexport function formatGapList(\n gaps: ReadinessGap[],\n limit = 3,\n): string[] {\n const topGaps = gaps.slice(0, limit);\n if (topGaps.length === 0) return [];\n\n const lines: string[] = [\n \"Here's where your Brain would benefit most:\",\n \"\",\n ];\n\n for (let i = 0; i < topGaps.length; i++) {\n const gap = topGaps[i];\n const prompt = gap.capabilityGuidance ?? gap.guidance;\n const label = cleanLabel(gap.label);\n lines.push(`${i + 1}. **${label}** — ${prompt}`);\n }\n\n return lines;\n}\n\n// ── Brief-mode one-liner ─────────────────────────────────────────────────────\n\n/**\n * One-line gap summary for brief orient mode.\n * Returns null if no gaps.\n */\nexport function formatGapOneLiner(gap: ReadinessGap | undefined): string | null {\n if (!gap) return null;\n const prompt = gap.capabilityGuidance ?? gap.guidance;\n return `Next gap: ${prompt}`;\n}\n","/**\n * LLM Usage MCP tools — STR-23 (MCP before UI)\n * Chain: DEC-61, TEN-65\n *\n * AI agents can query their own workspace spend, model breakdown,\n * and session economics before the Settings UI ships.\n */\nimport { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { z } from \"zod\";\nimport { thinWrapper, success, failureResult } from \"../envelope.js\";\nimport { kernelQuery, getWorkspaceContext, getAgentSessionId } from \"../client.js\";\n\nexport const usageSummarySchema = z.object({\n periodDays: z\n .number()\n .min(1)\n .max(90)\n .optional()\n .describe(\"Number of days to look back (default 30, max 90)\"),\n});\n\nexport function registerUsageTools(server: McpServer) {\n server.registerTool(\n \"get-usage-summary\",\n {\n title: \"Get Usage Summary\",\n description:\n \"Returns LLM usage and cost summary for the current workspace. \" +\n \"Includes total spend, token counts, model breakdown, and feature breakdown \" +\n \"for the specified period. If called within an agent session, also includes \" +\n \"the current session's cost. Use this to understand AI spend, check budgets, \" +\n \"or analyze which features and models drive cost.\",\n inputSchema: usageSummarySchema,\n annotations: { readOnlyHint: true, idempotentHint: true, openWorldHint: false },\n },\n thinWrapper(async ({ periodDays }) => {\n const ws = await getWorkspaceContext();\n const sessionId = getAgentSessionId();\n\n const summary = await kernelQuery<{\n periodDays: number;\n totalTokens: number;\n totalCostUsd: number;\n totalCostCredits: number;\n totalRequests: number;\n cachedTokens: number;\n reasoningTokens: number;\n cacheHitRate: number;\n modelBreakdown: Array<{ model: string; requests: number; costUsd: number }>;\n featureBreakdown: Array<{ feature: string; requests: number; costUsd: number }>;\n }>(\"usage.getWorkspaceSummary\", {\n periodDays: periodDays ?? 30,\n });\n\n if (!summary) {\n return failureResult(\n \"No usage data available yet. LLM tracking may not be active or no calls have been made in this period.\",\n \"NOT_FOUND\",\n \"No usage data available yet.\",\n \"LLM tracking may not be active or no calls have been made in this period.\",\n );\n }\n\n const lines: string[] = [\n `## Usage Summary — ${ws.workspaceName}`,\n `Period: last ${summary.periodDays} days`,\n \"\",\n `**Total spend:** $${summary.totalCostUsd.toFixed(4)} USD (${summary.totalRequests} requests)`,\n `**Total tokens:** ${summary.totalTokens.toLocaleString()} (cached: ${summary.cachedTokens.toLocaleString()}, reasoning: ${summary.reasoningTokens.toLocaleString()})`,\n `**Cache hit rate:** ${(summary.cacheHitRate * 100).toFixed(1)}%`,\n ];\n\n if (summary.modelBreakdown.length > 0) {\n lines.push(\"\", \"### Model Breakdown\");\n for (const m of summary.modelBreakdown) {\n lines.push(`- **${m.model}**: $${m.costUsd.toFixed(4)} (${m.requests} requests)`);\n }\n }\n\n if (summary.featureBreakdown.length > 0) {\n lines.push(\"\", \"### Feature Breakdown\");\n for (const f of summary.featureBreakdown) {\n lines.push(`- **${f.feature}**: $${f.costUsd.toFixed(4)} (${f.requests} requests)`);\n }\n }\n\n if (sessionId) {\n lines.push(\"\", `_Current agent session: ${sessionId}_`);\n }\n\n return {\n content: [\n {\n type: \"text\" as const,\n text: lines.join(\"\\n\"),\n },\n ],\n structuredContent: success(\n `Usage for ${ws.workspaceName}: $${summary.totalCostUsd.toFixed(4)} over ${summary.periodDays} days, ${summary.totalRequests} requests.`,\n {\n periodDays: summary.periodDays,\n totalTokens: summary.totalTokens,\n totalCostUsd: summary.totalCostUsd,\n totalRequests: summary.totalRequests,\n cacheHitRate: summary.cacheHitRate,\n modelBreakdown: summary.modelBreakdown,\n featureBreakdown: summary.featureBreakdown,\n },\n ),\n };\n }),\n );\n}\n","/**\n * GitChain MCP tools — consolidated chain lifecycle operations.\n *\n * 4 tools (down from 14) covering CRUD, versioning, branching, and review.\n * Backend calls are unchanged — same Convex `gitchain.*` namespace.\n *\n * Chain: GT-vaw0re (Git Chain), FEAT-CW-001 (ChainWork Engine)\n */\n\nimport { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { z } from \"zod\";\nimport { kernelQuery, kernelMutation, getWorkspaceContext } from \"../client.js\";\nimport { trackWriteTool } from \"../tool-surface.js\";\nimport { thinWrapper, success, failure, validationResult, successResult, unknownAction } from \"../envelope.js\";\nimport { toVersionDisplay } from \"../lib/versionDisplay.js\";\n\nexport const chainSchema = z.object({\n action: z.enum([\"create\", \"get\", \"list\", \"edit\"])\n .describe(\"Action: create a process, get process details, list all processes, or edit a process link\"),\n chainEntryId: z.string().optional()\n .describe(\"Chain entry ID (required for get/edit)\"),\n title: z.string().optional()\n .describe(\"Process title (required for create)\"),\n chainTypeId: z.string().optional().default(\"strategy-coherence\")\n .describe(\"Process template slug for create: 'strategy-coherence', 'idm-proposal', or any custom template slug\"),\n description: z.string().optional()\n .describe(\"Description (for create)\"),\n linkId: z.string().optional()\n .describe(\"Link to edit (for edit action): problem, insight, choice, action, outcome\"),\n content: z.string().optional()\n .describe(\"New content for the link (for edit action)\"),\n status: z.string().optional()\n .describe(\"Filter by status for list: 'draft' or 'active'\"),\n author: z.string().optional()\n .describe(\"Who is performing the action. Defaults to 'mcp'.\"),\n});\n\nexport const chainVersionSchema = z.object({\n action: z.enum([\"commit\", \"list\", \"diff\", \"revert\", \"history\"])\n .describe(\"Action: commit a snapshot, list commits, diff two versions, revert to a version, or view history\"),\n chainEntryId: z.string().describe(\"The chain's entry ID\"),\n commitMessage: z.string().optional()\n .describe(\"Commit message (required for commit). Convention: type(link): description\"),\n versionA: z.number().optional().describe(\"Earlier version for diff\"),\n versionB: z.number().optional().describe(\"Later version for diff\"),\n toVersion: z.number().optional().describe(\"Version number to revert to\"),\n author: z.string().optional().describe(\"Who is performing the action. Defaults to 'mcp'.\"),\n});\n\nexport const chainBranchSchema = z.object({\n action: z.enum([\"create\", \"list\", \"merge\", \"conflicts\"])\n .describe(\"Action: create a branch, list branches, merge a branch, or check for conflicts\"),\n chainEntryId: z.string().describe(\"The chain's entry ID\"),\n branchName: z.string().optional()\n .describe(\"Branch name (required for merge/conflicts, optional for create)\"),\n strategy: z.enum([\"merge_commit\", \"squash\"]).optional()\n .describe(\"Merge strategy: 'merge_commit' (default) or 'squash'\"),\n author: z.string().optional().describe(\"Who is performing the action. Defaults to 'mcp'.\"),\n});\n\nexport const chainReviewSchema = z.object({\n action: z.enum([\"gate\", \"comment\", \"resolve-comment\", \"list-comments\"])\n .describe(\"Action: run coherence gate, add a comment, resolve a comment, or list comments\"),\n chainEntryId: z.string().describe(\"The chain's entry ID\"),\n commitMessage: z.string().optional()\n .describe(\"Commit message to lint (for gate action)\"),\n versionNumber: z.number().optional()\n .describe(\"Version to comment on or list comments for\"),\n linkId: z.string().optional()\n .describe(\"Link this comment targets (optional for comment)\"),\n body: z.string().optional()\n .describe(\"Comment text (required for comment action)\"),\n commentId: z.string().optional()\n .describe(\"Comment ID (required for resolve-comment)\"),\n author: z.string().optional().describe(\"Who is performing the action. Defaults to 'mcp'.\"),\n});\n\nfunction linkSummary(links: Record<string, string>): string {\n return Object.entries(links)\n .map(([id, content]) => {\n const filled = typeof content === \"string\" && content.length > 0;\n const preview = filled\n ? content.substring(0, 80) + (content.length > 80 ? \"...\" : \"\")\n : \"(empty)\";\n return ` - **${id}**: ${preview}`;\n })\n .join(\"\\n\");\n}\n\nexport function registerGitChainTools(server: McpServer) {\n\n // ─── chain: CRUD operations ─────────────────────────────────────────\n\n const chainTool = server.registerTool(\n \"chain\",\n {\n title: \"Chain\",\n description:\n \"Manage processes — create, get, list, or edit process links. \" +\n \"Processes are versioned knowledge artifacts that follow a process template \" +\n \"(e.g. Strategy Coherence: Problem → Insight → Choice → Action → Outcome).\",\n inputSchema: chainSchema,\n annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: false },\n },\n thinWrapper(async ({ action, chainEntryId, title, chainTypeId, description, linkId, content, status, author }) => {\n if (action === \"create\") {\n if (!title) {\n return validationResult(\"A `title` is required to create a process.\");\n }\n\n const result = await kernelMutation<{ _id: string; entryId: string }>(\n \"gitchain.createChain\",\n { title, chainTypeId, description, author }\n );\n\n return {\n content: [{\n type: \"text\" as const,\n text:\n `# Process Created\\n\\n` +\n `- **Entry ID:** \\`${result.entryId}\\`\\n` +\n `- **Title:** ${title}\\n` +\n `- **Type:** ${chainTypeId}\\n` +\n `- **Status:** draft\\n\\n` +\n `Use \\`chain action=edit chainEntryId=\"${result.entryId}\" linkId=\"problem\" content=\"...\"\\` to start filling in links.`,\n }],\n structuredContent: success(\n `Created process '${title}' (${result.entryId}), type: ${chainTypeId}.`,\n { entryId: result.entryId, title, chainTypeId, status: \"draft\" },\n [{ tool: \"chain\", description: \"Edit a link\", parameters: { action: \"edit\", chainEntryId: result.entryId, linkId: \"problem\" } }],\n ),\n };\n }\n\n if (action === \"get\") {\n if (!chainEntryId) {\n return validationResult(\"A `chainEntryId` is required.\");\n }\n\n const chain = await kernelQuery<any>(\"gitchain.getChain\", { chainEntryId });\n if (!chain) {\n return {\n content: [{ type: \"text\" as const, text: `Process \"${chainEntryId}\" not found.` }],\n structuredContent: failure(\n \"NOT_FOUND\",\n `Process \"${chainEntryId}\" not found.`,\n \"Use chain action=list to find available processes.\",\n [{ tool: \"chain\", description: \"List processes\", parameters: { action: \"list\" } }],\n ),\n };\n }\n\n const scoreSection = chain.scores\n ? `\\n## Coherence: ${chain.coherenceScore}%\\n\\n` +\n chain.scores.sections\n .map((s: any) => `- **${s.key}**: ${s.power}/100 (${\"★\".repeat(Math.min(s.stars ?? 0, 5))}${\"☆\".repeat(Math.max(0, 5 - (s.stars ?? 0)))})`)\n .join(\"\\n\")\n : \"\";\n\n return {\n content: [{\n type: \"text\" as const,\n text:\n `# ${chain.name}\\n\\n` +\n `- **Entry ID:** \\`${chain.entryId}\\`\\n` +\n `- **Type:** ${chain.chainTypeName}\\n` +\n `- **Status:** ${chain.status}\\n` +\n `- **Links filled:** ${chain.filledCount}/${chain.totalCount}\\n` +\n `- **Version:** ${toVersionDisplay(chain.currentVersion)}\\n` +\n `- **Created by:** ${chain.createdBy ?? \"unknown\"}\\n` +\n `- **History events:** ${chain.historyCount}\\n` +\n scoreSection +\n `\\n\\n## Links\\n\\n` +\n linkSummary(chain.links),\n }],\n structuredContent: success(\n `${chain.name}: ${chain.filledCount}/${chain.totalCount} links, coherence ${chain.coherenceScore}%, ${toVersionDisplay(chain.currentVersion)}.`,\n { entryId: chain.entryId, name: chain.name, status: chain.status, filledCount: chain.filledCount, totalCount: chain.totalCount, coherenceScore: chain.coherenceScore, version: chain.currentVersion ?? null, versionDisplay: toVersionDisplay(chain.currentVersion) },\n ),\n };\n }\n\n if (action === \"list\") {\n const chains = await kernelQuery<any[]>(\"gitchain.listChains\", { chainTypeId, status });\n\n if (chains.length === 0) {\n return {\n content: [{ type: \"text\" as const, text: \"No processes found. Use `chain action=create` to create one.\" }],\n structuredContent: success(\n \"No processes found.\",\n { chains: [], total: 0 },\n [{ tool: \"chain\", description: \"Create a process\", parameters: { action: \"create\" } }],\n ),\n };\n }\n\n const formatted = chains\n .map((c) =>\n `- **\\`${c.entryId}\\`** ${c.name} — ${c.chainTypeId} · ` +\n `${c.filledCount}/${c.totalCount} links · ` +\n `coherence: ${c.coherenceScore}% · status: ${c.status}`\n )\n .join(\"\\n\");\n\n return {\n content: [{ type: \"text\" as const, text: `# Chains (${chains.length})\\n\\n${formatted}` }],\n structuredContent: success(\n `Found ${chains.length} process(es).`,\n { total: chains.length },\n ),\n };\n }\n\n if (action === \"edit\") {\n if (!chainEntryId) {\n return validationResult(\"A `chainEntryId` is required.\");\n }\n if (!linkId) {\n return validationResult(\"A `linkId` is required (e.g. problem, insight, choice, action, outcome).\");\n }\n if (!content) {\n return validationResult(\"The `content` for the link is required.\");\n }\n\n const result = await kernelMutation<{\n _id: string; entryId: string; linkId: string; status: string;\n }>(\"gitchain.editLink\", { chainEntryId, linkId, content, author });\n\n return {\n content: [{\n type: \"text\" as const,\n text:\n `# Link Updated\\n\\n` +\n `- **Chain:** \\`${result.entryId}\\`\\n` +\n `- **Link:** ${result.linkId}\\n` +\n `- **Chain status:** ${result.status}\\n` +\n `- **Content length:** ${content.length} chars\\n\\n` +\n `Use \\`chain action=get\\` to see the full chain with updated scores.`,\n }],\n structuredContent: success(\n `Updated link \"${result.linkId}\" on ${result.entryId}. Status: ${result.status}.`,\n { entryId: result.entryId, linkId: result.linkId, status: result.status, contentLength: content.length },\n [{ tool: \"chain\", description: \"View full chain\", parameters: { action: \"get\", chainEntryId } }],\n ),\n };\n }\n\n return unknownAction(action, [\"create\", \"get\", \"list\", \"edit\"]);\n })\n );\n trackWriteTool(chainTool);\n\n // ─── chain-version: versioning operations ───────────────────────────\n\n const chainVersionTool = server.registerTool(\n \"chain-version\",\n {\n title: \"Chain Version\",\n description:\n \"Manage process versions — commit snapshots, list commits, view history, diff versions, or revert. \" +\n \"Commits record all link content, compute coherence scores, and track changes.\",\n inputSchema: chainVersionSchema,\n annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: false },\n },\n thinWrapper(async ({ action, chainEntryId, commitMessage, versionA, versionB, toVersion, author }) => {\n if (action === \"commit\") {\n if (!commitMessage) {\n return validationResult(\"A `commitMessage` is required.\");\n }\n\n const result = await kernelMutation<{\n entryId: string; version: number; coherenceScore: number;\n linksModified: string[]; commitLintWarning: string | null;\n }>(\"gitchain.commitChain\", { chainEntryId, commitMessage, author });\n\n const warning = result.commitLintWarning\n ? `\\n\\n> **Lint warning:** ${result.commitLintWarning}`\n : \"\";\n\n return {\n content: [{\n type: \"text\" as const,\n text:\n `# Committed v${result.version}\\n\\n` +\n `- **Chain:** \\`${result.entryId}\\`\\n` +\n `- **Version:** ${result.version}\\n` +\n `- **Message:** ${commitMessage}\\n` +\n `- **Coherence:** ${result.coherenceScore}%\\n` +\n `- **Links modified:** ${result.linksModified.length > 0 ? result.linksModified.join(\", \") : \"none\"}\\n` +\n warning,\n }],\n structuredContent: success(\n `Committed v${result.version} on ${result.entryId}. Coherence: ${result.coherenceScore}%.`,\n { entryId: result.entryId, version: result.version, versionDisplay: toVersionDisplay(result.version), coherenceScore: result.coherenceScore, linksModified: result.linksModified, lintWarning: result.commitLintWarning },\n ),\n };\n }\n\n if (action === \"list\") {\n const commits = await kernelQuery<any[]>(\"gitchain.listCommits\", { chainEntryId });\n\n if (commits.length === 0) {\n return {\n content: [{ type: \"text\" as const, text: `No commits found for chain \"${chainEntryId}\". Use \\`chain-version action=commit\\` to create the first snapshot.` }],\n structuredContent: success(\n `No commits for ${chainEntryId}.`,\n { chainEntryId, commits: [], total: 0 },\n [{ tool: \"chain-version\", description: \"Commit chain\", parameters: { action: \"commit\", chainEntryId } }],\n ),\n };\n }\n\n const formatted = commits\n .map((c: any) => {\n const date = new Date(c.createdAt).toISOString().replace(\"T\", \" \").substring(0, 19);\n const msg = c.commitMessage ?? c.changeNote ?? \"(no message)\";\n const links = c.linksModified?.length > 0 ? ` [${c.linksModified.join(\", \")}]` : \"\";\n return `- **v${c.version}** ${date} by ${c.author} — ${msg}${links} (${c.versionStatus})`;\n })\n .join(\"\\n\");\n\n return {\n content: [{ type: \"text\" as const, text: `# Commits for ${chainEntryId} (${commits.length})\\n\\n${formatted}` }],\n structuredContent: success(\n `${commits.length} commit(s) for ${chainEntryId}.`,\n { chainEntryId, total: commits.length },\n ),\n };\n }\n\n if (action === \"diff\") {\n if (versionA == null || versionB == null) {\n return validationResult(\"Both `versionA` and `versionB` are required for diff.\");\n }\n\n const diff = await kernelMutation<any>(\"gitchain.diffVersions\", { chainEntryId, versionA, versionB });\n\n let text =\n `# Diff: v${versionA} → v${versionB}\\n\\n` +\n `- **Chain:** \\`${diff.chainEntryId}\\`\\n` +\n `- **Coherence:** ${diff.coherenceBefore}% → ${diff.coherenceAfter}% (${diff.coherenceDelta >= 0 ? \"+\" : \"\"}${diff.coherenceDelta})\\n` +\n `- **Links changed:** ${diff.linksChanged.length > 0 ? diff.linksChanged.join(\", \") : \"none\"}\\n`;\n\n for (const ld of diff.linkDiffs) {\n if (ld.status === \"unchanged\") continue;\n text += `\\n## ${ld.linkId} (${ld.status})\\n\\n`;\n const wordDiff = diff.wordDiffs[ld.linkId];\n if (wordDiff?.length > 0) {\n for (const w of wordDiff) {\n if (w.type === \"delete\") text += `~~${w.value.substring(0, 200)}~~`;\n else if (w.type === \"insert\") text += `**${w.value.substring(0, 200)}**`;\n else text += w.value.substring(0, 200);\n }\n text += \"\\n\";\n }\n }\n\n return {\n content: [{ type: \"text\" as const, text }],\n structuredContent: success(\n `Diff v${versionA} → v${versionB}: coherence ${diff.coherenceBefore}% → ${diff.coherenceAfter}%, ${diff.linksChanged.length} link(s) changed.`,\n { chainEntryId: diff.chainEntryId, versionA, versionB, coherenceBefore: diff.coherenceBefore, coherenceAfter: diff.coherenceAfter, coherenceDelta: diff.coherenceDelta, linksChanged: diff.linksChanged },\n ),\n };\n }\n\n if (action === \"revert\") {\n if (toVersion == null) {\n return validationResult(\"A `toVersion` is required for revert.\");\n }\n\n const result = await kernelMutation<{\n entryId: string; revertedTo: number; newVersion: number; linksModified: string[];\n }>(\"gitchain.revertChain\", { chainEntryId, toVersion, author });\n\n return {\n content: [{\n type: \"text\" as const,\n text:\n `# Reverted\\n\\n` +\n `- **Chain:** \\`${result.entryId}\\`\\n` +\n `- **Reverted to:** v${result.revertedTo}\\n` +\n `- **New version:** v${result.newVersion}\\n` +\n `- **Links affected:** ${result.linksModified.length > 0 ? result.linksModified.join(\", \") : \"none\"}\\n\\n` +\n `History is preserved — this created a new version, not a destructive reset.`,\n }],\n structuredContent: success(\n `Reverted ${result.entryId} to v${result.revertedTo}. New version: v${result.newVersion}.`,\n { entryId: result.entryId, revertedTo: result.revertedTo, revertedToDisplay: toVersionDisplay(result.revertedTo), newVersion: result.newVersion, newVersionDisplay: toVersionDisplay(result.newVersion), linksModified: result.linksModified },\n ),\n };\n }\n\n if (action === \"history\") {\n const history = await kernelQuery<any[]>(\"gitchain.getHistory\", { chainEntryId });\n\n if (history.length === 0) {\n return {\n content: [{ type: \"text\" as const, text: `No history found for chain \"${chainEntryId}\".` }],\n structuredContent: success(\n `No history for ${chainEntryId}.`,\n { chainEntryId, events: [], total: 0 },\n ),\n };\n }\n\n const formatted = history\n .sort((a: any, b: any) => b.timestamp - a.timestamp)\n .map((h: any) => {\n const date = new Date(h.timestamp).toISOString().replace(\"T\", \" \").substring(0, 19);\n return `- **${date}** [${h.event}] by ${h.changedBy ?? \"unknown\"} — ${h.note ?? \"\"}`;\n })\n .join(\"\\n\");\n\n return {\n content: [{ type: \"text\" as const, text: `# History for ${chainEntryId} (${history.length} events)\\n\\n${formatted}` }],\n structuredContent: success(\n `${history.length} history event(s) for ${chainEntryId}.`,\n { chainEntryId, total: history.length },\n ),\n };\n }\n\n return unknownAction(action, [\"commit\", \"list\", \"diff\", \"revert\", \"history\"]);\n })\n );\n trackWriteTool(chainVersionTool);\n\n // ─── chain-branch: branching operations ─────────────────────────────\n\n const chainBranchTool = server.registerTool(\n \"chain-branch\",\n {\n title: \"Chain Branch\",\n description:\n \"Manage process branches — create a branch for isolated editing, list branches, \" +\n \"merge a branch back into main, or check for conflicts.\",\n inputSchema: chainBranchSchema,\n annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: false },\n },\n thinWrapper(async ({ action, chainEntryId, branchName, strategy, author }) => {\n if (action === \"create\") {\n const result = await kernelMutation<{\n branchId: string; name: string; baseVersion: number;\n }>(\"gitchain.createBranch\", { chainEntryId, name: branchName, author });\n\n return {\n content: [{\n type: \"text\" as const,\n text:\n `# Branch Created\\n\\n` +\n `- **Name:** ${result.name}\\n` +\n `- **Based on:** v${result.baseVersion}\\n` +\n `- **Chain:** \\`${chainEntryId}\\`\\n\\n` +\n `Edit links and commit on this branch, then use \\`chain-branch action=merge\\` to land changes.`,\n }],\n structuredContent: success(\n `Created branch \"${result.name}\" based on v${result.baseVersion}.`,\n { branchId: result.branchId, name: result.name, baseVersion: result.baseVersion, chainEntryId },\n [{ tool: \"chain-branch\", description: \"Merge branch\", parameters: { action: \"merge\", chainEntryId, branchName: result.name } }],\n ),\n };\n }\n\n if (action === \"list\") {\n const branches = await kernelMutation<any[]>(\"gitchain.listBranches\", { chainEntryId });\n\n if (branches.length === 0) {\n return {\n content: [{ type: \"text\" as const, text: `No branches found for chain \"${chainEntryId}\".` }],\n structuredContent: success(\n `No branches for ${chainEntryId}.`,\n { chainEntryId, branches: [], total: 0 },\n [{ tool: \"chain-branch\", description: \"Create a branch\", parameters: { action: \"create\", chainEntryId } }],\n ),\n };\n }\n\n const formatted = branches\n .map((b: any) => `- **${b.name}** (${b.status}) — based on v${b.baseVersion}, by ${b.createdBy}`)\n .join(\"\\n\");\n\n return {\n content: [{ type: \"text\" as const, text: `# Branches for ${chainEntryId} (${branches.length})\\n\\n${formatted}` }],\n structuredContent: success(\n `${branches.length} branch(es) for ${chainEntryId}.`,\n { chainEntryId, total: branches.length },\n ),\n };\n }\n\n if (action === \"merge\") {\n if (!branchName) {\n return validationResult(\"A `branchName` is required for merge.\");\n }\n\n const result = await kernelMutation<{\n entryId: string; branchName: string; version: number; strategy: string;\n }>(\"gitchain.mergeBranch\", { chainEntryId, branchName, strategy, author });\n\n return {\n content: [{\n type: \"text\" as const,\n text:\n `# Branch Merged\\n\\n` +\n `- **Chain:** \\`${result.entryId}\\`\\n` +\n `- **Branch:** ${result.branchName} (now closed)\\n` +\n `- **Version:** v${result.version}\\n` +\n `- **Strategy:** ${result.strategy}\\n\\n` +\n `Main is now at v${result.version}. The branch has been closed.`,\n }],\n structuredContent: success(\n `Merged branch \"${result.branchName}\" into ${result.entryId} at v${result.version}.`,\n { entryId: result.entryId, branchName: result.branchName, version: result.version, versionDisplay: toVersionDisplay(result.version), strategy: result.strategy },\n ),\n };\n }\n\n if (action === \"conflicts\") {\n if (!branchName) {\n return validationResult(\"A `branchName` is required for conflict check.\");\n }\n\n const result = await kernelMutation<any>(\"gitchain.checkConflicts\", { chainEntryId, branchName });\n\n if (!result.hasConflicts) {\n return {\n content: [{\n type: \"text\" as const,\n text: `# No Conflicts\\n\\nBranch \"${branchName}\" on \\`${chainEntryId}\\` has no conflicts. Safe to merge.`,\n }],\n structuredContent: success(\n `No conflicts on branch \"${branchName}\". Safe to merge.`,\n { chainEntryId, branchName, hasConflicts: false },\n [{ tool: \"chain-branch\", description: \"Merge branch\", parameters: { action: \"merge\", chainEntryId, branchName } }],\n ),\n };\n }\n\n const conflictLines = result.conflicts\n .map((c: any) =>\n `- **${c.linkId}** — modified by: ${c.branches.map((b: any) => `${b.branchName} (${b.author})`).join(\", \")}`\n )\n .join(\"\\n\");\n\n return {\n content: [{\n type: \"text\" as const,\n text:\n `# Conflicts Detected\\n\\n` +\n `Branch \"${branchName}\" conflicts with other branches on these links:\\n\\n` +\n conflictLines +\n `\\n\\nResolve conflicts before merging.`,\n }],\n structuredContent: failure(\n \"CONFLICT\",\n `Branch \"${branchName}\" has ${result.conflicts.length} conflict(s).`,\n \"Resolve conflicts on the conflicting links before merging.\",\n ),\n };\n }\n\n return unknownAction(action, [\"create\", \"list\", \"merge\", \"conflicts\"]);\n })\n );\n trackWriteTool(chainBranchTool);\n\n // ─── chain-review: quality gate and comments ────────────────────────\n\n const chainReviewTool = server.registerTool(\n \"chain-review\",\n {\n title: \"Chain Review\",\n description:\n \"Review process quality — run the coherence gate or manage comments on process versions. \" +\n \"The gate checks: coherence score >= 70%, all links filled, commit message convention.\",\n inputSchema: chainReviewSchema,\n annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false },\n },\n thinWrapper(async ({ action, chainEntryId, commitMessage, versionNumber, linkId, body, commentId, author }) => {\n if (action === \"gate\") {\n const gate = await kernelQuery<any>(\"gitchain.runGate\", { chainEntryId, commitMessage });\n\n const checkLines = gate.checks\n .map((c: any) => `- ${c.pass ? \"PASS\" : \"FAIL\"} **${c.name}**: ${c.detail}`)\n .join(\"\\n\");\n\n const icon = gate.pass ? \"PASS\" : \"BLOCKED\";\n\n return {\n content: [{\n type: \"text\" as const,\n text:\n `# Gate: ${icon}\\n\\n` +\n `- **Score:** ${gate.score}%\\n` +\n `- **Threshold:** ${gate.threshold}%\\n\\n` +\n `## Checks\\n\\n${checkLines}`,\n }],\n structuredContent: success(\n `Gate ${icon}: ${gate.score}% (threshold ${gate.threshold}%).`,\n { pass: gate.pass, score: gate.score, threshold: gate.threshold, checks: gate.checks },\n ),\n };\n }\n\n if (action === \"comment\") {\n if (!versionNumber) {\n return validationResult(\"A `versionNumber` is required.\");\n }\n if (!body) {\n return validationResult(\"A `body` is required.\");\n }\n\n const result = await kernelMutation<any>(\"gitchain.addComment\", {\n chainEntryId, versionNumber, linkId, body, author,\n });\n\n return {\n content: [{\n type: \"text\" as const,\n text:\n `# Comment Added\\n\\n` +\n `- **Chain:** \\`${result.chainEntryId}\\`\\n` +\n `- **Version:** v${result.versionNumber}\\n` +\n (result.linkId ? `- **Link:** ${result.linkId}\\n` : \"\") +\n `- **Body:** ${body.substring(0, 200)}`,\n }],\n structuredContent: success(\n `Comment added on ${result.chainEntryId} v${result.versionNumber}${result.linkId ? ` [${result.linkId}]` : \"\"}.`,\n { chainEntryId: result.chainEntryId, versionNumber: result.versionNumber, linkId: result.linkId },\n ),\n };\n }\n\n if (action === \"resolve-comment\") {\n if (!commentId) {\n return validationResult(\"A `commentId` is required.\");\n }\n await kernelMutation(\"gitchain.resolveComment\", { commentId });\n return successResult(\"Comment resolved.\", `Comment ${commentId} resolved.`, { commentId, resolved: true });\n }\n\n if (action === \"list-comments\") {\n const comments = await kernelMutation<any[]>(\"gitchain.listComments\", {\n chainEntryId, versionNumber,\n });\n\n if (comments.length === 0) {\n return {\n content: [{ type: \"text\" as const, text: `No comments found for chain \"${chainEntryId}\"${versionNumber ? ` v${versionNumber}` : \"\"}.` }],\n structuredContent: success(\n `No comments for ${chainEntryId}${versionNumber ? ` v${versionNumber}` : \"\"}.`,\n { chainEntryId, comments: [], total: 0, unresolved: 0 },\n ),\n };\n }\n\n const formatted = comments\n .map((c: any) => {\n const date = new Date(c.createdAt).toISOString().replace(\"T\", \" \").substring(0, 19);\n const resolved = c.resolved ? \" (RESOLVED)\" : \"\";\n const link = c.linkId ? ` [${c.linkId}]` : \"\";\n return `- **v${c.version}${link}** ${date} by ${c.author}${resolved}: ${c.body.substring(0, 150)}`;\n })\n .join(\"\\n\");\n\n const unresolvedCount = comments.filter((c: any) => !c.resolved).length;\n\n return {\n content: [{\n type: \"text\" as const,\n text: `# Comments for ${chainEntryId} (${comments.length}, ${unresolvedCount} unresolved)\\n\\n${formatted}`,\n }],\n structuredContent: success(\n `${comments.length} comment(s) for ${chainEntryId}, ${unresolvedCount} unresolved.`,\n { chainEntryId, total: comments.length, unresolved: unresolvedCount },\n ),\n };\n }\n\n return unknownAction(action, [\"gate\", \"comment\", \"resolve-comment\", \"list-comments\"]);\n })\n );\n trackWriteTool(chainReviewTool);\n}\n","/**\n * versionDisplay — human-readable version string for MCP responses (BET-112, FEAT-287, STD-60)\n *\n * Agents receive versionDisplay ('Draft' or 'vN') alongside raw version (number | null)\n * so they don't assume version is always a number. Drafts have no committed version.\n */\n\n/**\n * Returns 'Draft' when version is null, undefined, or 0 (no commits yet).\n * Returns 'vN' for committed versions (1, 2, 3, ...).\n */\nexport function toVersionDisplay(version: number | null | undefined): string {\n if (version == null || version === 0) return \"Draft\";\n return `v${version}`;\n}\n","/**\n * Map Composition MCP tools — CRUD, slot management, versioning, and suggestion.\n *\n * Maps are composed frameworks (e.g. Lean Canvas) assembled from shared\n * ingredient entries across collections. Each slot holds references to\n * ingredients; committing pins versions to create an immutable snapshot.\n */\n\nimport { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { z } from \"zod\";\nimport { kernelQuery, kernelMutation, getWorkspaceContext } from \"../client.js\";\nimport { trackWriteTool } from \"../tool-surface.js\";\nimport { thinWrapper, success, failure, validationResult, unknownAction } from \"../envelope.js\";\nimport { toVersionDisplay } from \"../lib/versionDisplay.js\";\n\nexport const createAudienceMapSetSchema = z.object({\n audienceEntryId: z.string().describe(\"Entry ID of the audience (e.g. STR-fb7hje)\"),\n});\n\nexport const mapSchema = z.object({\n action: z\n .enum([\"create\", \"get\", \"list\"])\n .describe(\"Action: create a map, get map details, or list all maps\"),\n mapEntryId: z.string().optional().describe(\"Map entry ID (for get)\"),\n title: z.string().optional().describe(\"Map title (for create)\"),\n templateId: z\n .string()\n .optional()\n .default(\"lean-canvas\")\n .describe(\"Template slug for create: 'lean-canvas' or any composed template\"),\n description: z.string().optional().describe(\"Description (for create)\"),\n slotIds: z\n .array(z.string())\n .optional()\n .describe(\"Slot IDs to initialize (for create; auto-populated from template if omitted)\"),\n status: z.string().optional().describe(\"Filter by status for list\"),\n});\n\nexport const mapSlotSchema = z.object({\n action: z\n .enum([\"add\", \"remove\", \"replace\", \"list\"])\n .describe(\"Action: add/remove/replace an ingredient in a slot, or list slot contents\"),\n mapEntryId: z.string().describe(\"Map entry ID\"),\n slotId: z.string().optional().describe(\"Slot ID (e.g. 'problem', 'customer-segments')\"),\n ingredientEntryId: z\n .string()\n .optional()\n .describe(\"Ingredient entry ID to add/remove\"),\n newIngredientEntryId: z\n .string()\n .optional()\n .describe(\"New ingredient entry ID (for replace)\"),\n label: z.string().optional().describe(\"Display label override\"),\n author: z.string().optional().describe(\"Who is performing the action\"),\n});\n\nexport const mapVersionSchema = z.object({\n action: z\n .enum([\"commit\", \"list\", \"history\"])\n .describe(\"Action: commit the map, list commits, or view commit history\"),\n mapEntryId: z.string().describe(\"Map entry ID\"),\n commitMessage: z\n .string()\n .optional()\n .describe(\"Commit message (for commit action)\"),\n author: z.string().optional().describe(\"Who is committing\"),\n});\n\nexport const mapSuggestSchema = z.object({\n mapEntryId: z.string().describe(\"Map entry ID to suggest ingredients for\"),\n slotId: z\n .string()\n .optional()\n .describe(\"Specific slot to find ingredients for (or all empty slots)\"),\n query: z\n .string()\n .optional()\n .describe(\"Optional search query to narrow ingredient suggestions\"),\n});\n\nfunction slotSummary(slots: Record<string, any[]>): string {\n return Object.entries(slots)\n .map(([id, refs]) => {\n if (!refs || refs.length === 0) return ` - **${id}**: (empty)`;\n const items = refs\n .map((r: any) => {\n const name = r.ingredientName ?? r.label ?? r.entryId;\n const version = r.pinnedVersion ? ` v${r.pinnedVersion}` : \"\";\n const status = r.ingredientStatus ? ` [${r.ingredientStatus}]` : \"\";\n return `${name}${version}${status}`;\n })\n .join(\", \");\n return ` - **${id}**: ${items}`;\n })\n .join(\"\\n\");\n}\n\nexport function registerMapTools(server: McpServer) {\n // ─── create-audience-map-set: convenience for audience intelligence ──\n\n const createAudienceMapSetTool = server.registerTool(\n \"create-audience-map-set\",\n {\n title: \"Create Audience Map Set\",\n description:\n \"Create all three audience intelligence maps (Empathy, Narrowing, Jobs & Alternatives) \" +\n \"anchored to one audience entry. The audience is pre-slotted in the anchor position of each map.\",\n inputSchema: createAudienceMapSetSchema,\n annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: false },\n },\n thinWrapper(async ({ audienceEntryId }) => {\n const result = await kernelMutation<{ audienceEntryId: string; maps: Array<{ templateId: string; mapEntryId: string }> }>(\n \"maps.createAudienceMapSet\",\n { audienceEntryId }\n );\n\n const wsCtx = await getWorkspaceContext();\n const lines = result.maps.map(\n (m) => `- **${m.templateId}**: \\`${m.mapEntryId}\\``\n );\n return {\n content: [\n {\n type: \"text\" as const,\n text:\n `# Audience Map Set Created\\n\\n` +\n `**Audience:** \\`${result.audienceEntryId}\\`\\n` +\n `**Workspace:** ${wsCtx.workspaceSlug}\\n\\n` +\n `## Maps\\n\\n${lines.join(\"\\n\")}\\n\\n` +\n `Use map-slot to add ingredients. View at /empathy, /narrowing, and /jobs.`,\n },\n ],\n structuredContent: success(\n `Created ${result.maps.length} audience maps for ${result.audienceEntryId}.`,\n { audienceEntryId: result.audienceEntryId, maps: result.maps },\n result.maps.map((m) => ({\n tool: \"map-slot\",\n description: `Add ingredients to ${m.templateId}`,\n parameters: { action: \"add\", mapEntryId: m.mapEntryId },\n })),\n ),\n };\n })\n );\n trackWriteTool(createAudienceMapSetTool);\n\n // ─── map: CRUD operations ──────────────────────────────────────────\n\n const mapTool = server.registerTool(\n \"map\",\n {\n title: \"Map\",\n description:\n \"Manage composed framework maps — create, get, or list. \" +\n \"Maps assemble ingredient entries into framework slots (e.g. Lean Canvas). \" +\n \"Use map-slot to add/remove ingredients, map-version to commit and view history.\",\n inputSchema: mapSchema,\n annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: false },\n },\n thinWrapper(async ({ action, mapEntryId, title, templateId, description, slotIds, status }) => {\n if (action === \"create\") {\n if (!title) {\n return validationResult(\"A `title` is required to create a map.\");\n }\n\n const result = await kernelMutation<{ _id: string; entryId: string }>(\n \"maps.createMap\",\n { title, templateId, description, slotIds }\n );\n\n const wsCtx = await getWorkspaceContext();\n return {\n content: [\n {\n type: \"text\" as const,\n text:\n `# Map Created\\n\\n` +\n `- **Entry ID:** \\`${result.entryId}\\`\\n` +\n `- **Title:** ${title}\\n` +\n `- **Template:** ${templateId}\\n` +\n `- **Status:** draft\\n` +\n `- **Workspace:** ${wsCtx.workspaceSlug} (${wsCtx.workspaceId})\\n\\n` +\n `Use \\`map-slot action=add mapEntryId=\"${result.entryId}\" slotId=\"problem\" ingredientEntryId=\"...\"\\` to start filling slots.`,\n },\n ],\n structuredContent: success(\n `Created map '${title}' (${result.entryId}) using ${templateId} template.`,\n { entryId: result.entryId, title, templateId, status: \"draft\" },\n [{ tool: \"map-slot\", description: \"Add ingredient to slot\", parameters: { action: \"add\", mapEntryId: result.entryId } }],\n ),\n };\n }\n\n if (action === \"get\") {\n if (!mapEntryId) {\n return validationResult(\"A `mapEntryId` is required.\");\n }\n\n const map = await kernelQuery<any>(\"maps.getMap\", { mapEntryId });\n if (!map) {\n return {\n content: [{ type: \"text\" as const, text: `Map \"${mapEntryId}\" not found.` }],\n structuredContent: failure(\n \"NOT_FOUND\",\n `Map \"${mapEntryId}\" not found.`,\n \"Use map action=list to find available maps.\",\n [{ tool: \"map\", description: \"List maps\", parameters: { action: \"list\" } }],\n ),\n };\n }\n\n return {\n content: [\n {\n type: \"text\" as const,\n text:\n `# ${map.name}\\n\\n` +\n `- **Entry ID:** \\`${map.entryId}\\`\\n` +\n `- **Template:** ${map.templateName}\\n` +\n `- **Status:** ${map.status}\\n` +\n `- **Version:** ${toVersionDisplay(map.currentVersion)}\\n` +\n `- **Completion:** ${map.completionScore}% (${map.filledSlots}/${map.totalSlots} slots)\\n\\n` +\n `## Slots\\n\\n` +\n slotSummary(map.slots),\n },\n ],\n structuredContent: success(\n `${map.name}: ${map.completionScore}% complete (${map.filledSlots}/${map.totalSlots} slots), ${toVersionDisplay(map.currentVersion)}.`,\n { entryId: map.entryId, name: map.name, templateName: map.templateName, status: map.status, completionScore: map.completionScore, filledSlots: map.filledSlots, totalSlots: map.totalSlots, version: map.currentVersion ?? null, versionDisplay: toVersionDisplay(map.currentVersion) },\n [{ tool: \"map-slot\", description: \"Manage slot ingredients\", parameters: { action: \"list\", mapEntryId } }],\n ),\n };\n }\n\n if (action === \"list\") {\n const maps = await kernelQuery<any[]>(\"maps.listMaps\", {\n templateId: templateId !== \"lean-canvas\" ? templateId : undefined,\n status,\n });\n\n if (!maps || maps.length === 0) {\n return {\n content: [{ type: \"text\" as const, text: \"No maps found. Create one with `map action=create title=\\\"My Canvas\\\"`.\" }],\n structuredContent: success(\n \"No maps found.\",\n { maps: [], total: 0 },\n [{ tool: \"map\", description: \"Create a map\", parameters: { action: \"create\" } }],\n ),\n };\n }\n\n const lines = maps.map(\n (m: any) =>\n `- **${m.name}** (\\`${m.entryId}\\`) — ${m.templateId}, ${m.completionScore}% complete, ${toVersionDisplay(m.currentVersion)}`\n );\n\n return {\n content: [{ type: \"text\" as const, text: `# Maps (${maps.length})\\n\\n${lines.join(\"\\n\")}` }],\n structuredContent: success(\n `Found ${maps.length} map(s).`,\n { maps: maps.map((m: any) => ({ entryId: m.entryId, name: m.name, templateId: m.templateId, completionScore: m.completionScore })), total: maps.length },\n ),\n };\n }\n\n return unknownAction(action, [\"create\", \"get\", \"list\"]);\n })\n );\n trackWriteTool(mapTool);\n\n // ─── map-slot: manage ingredients in slots ─────────────────────────\n\n const mapSlotTool = server.registerTool(\n \"map-slot\",\n {\n title: \"Map Slot\",\n description:\n \"Add, remove, or replace ingredient references in a map's slots. \" +\n \"Ingredients are entries from any collection that fill a framework position.\",\n inputSchema: mapSlotSchema,\n annotations: { readOnlyHint: false, destructiveHint: true, openWorldHint: false },\n },\n thinWrapper(async ({\n action,\n mapEntryId,\n slotId,\n ingredientEntryId,\n newIngredientEntryId,\n label,\n author,\n }) => {\n if (action === \"list\") {\n const map = await kernelQuery<any>(\"maps.getMap\", { mapEntryId });\n if (!map) {\n return {\n content: [{ type: \"text\" as const, text: `Map \"${mapEntryId}\" not found.` }],\n structuredContent: failure(\n \"NOT_FOUND\",\n `Map \"${mapEntryId}\" not found.`,\n \"Use map action=list to find available maps.\",\n [{ tool: \"map\", description: \"List maps\", parameters: { action: \"list\" } }],\n ),\n };\n }\n\n if (slotId && map.slots[slotId]) {\n const refs = map.slots[slotId];\n return {\n content: [\n {\n type: \"text\" as const,\n text:\n `# Slot: ${slotId}\\n\\n` +\n (refs.length === 0\n ? \"(empty)\"\n : refs\n .map(\n (r: any) =>\n `- **${r.ingredientName ?? r.entryId}** (\\`${r.entryId}\\`)${r.pinnedVersion ? ` v${r.pinnedVersion}` : \"\"}`\n )\n .join(\"\\n\")),\n },\n ],\n structuredContent: success(\n refs.length === 0 ? `Slot \"${slotId}\" is empty.` : `Slot \"${slotId}\": ${refs.length} ingredient(s).`,\n { mapEntryId, slotId, ingredients: refs, count: refs.length },\n ),\n };\n }\n\n return {\n content: [{ type: \"text\" as const, text: `## All Slots\\n\\n${slotSummary(map.slots)}` }],\n structuredContent: success(\n `${map.name}: ${Object.keys(map.slots).length} slots.`,\n { mapEntryId, slotCount: Object.keys(map.slots).length },\n ),\n };\n }\n\n if (action === \"add\") {\n if (!slotId || !ingredientEntryId) {\n return validationResult(\"Both `slotId` and `ingredientEntryId` are required for add.\");\n }\n\n await kernelMutation(\"maps.addToSlot\", { mapEntryId, slotId, ingredientEntryId, label, author });\n\n return {\n content: [{ type: \"text\" as const, text: `Added \\`${ingredientEntryId}\\` to slot \"${slotId}\" on map \\`${mapEntryId}\\`.` }],\n structuredContent: success(\n `Added ${ingredientEntryId} to slot \"${slotId}\".`,\n { mapEntryId, slotId, ingredientEntryId },\n [{ tool: \"map\", description: \"View updated map\", parameters: { action: \"get\", mapEntryId } }],\n ),\n };\n }\n\n if (action === \"remove\") {\n if (!slotId || !ingredientEntryId) {\n return validationResult(\"Both `slotId` and `ingredientEntryId` are required for remove.\");\n }\n\n await kernelMutation(\"maps.removeFromSlot\", { mapEntryId, slotId, ingredientEntryId, author });\n\n return {\n content: [{ type: \"text\" as const, text: `Removed \\`${ingredientEntryId}\\` from slot \"${slotId}\" on map \\`${mapEntryId}\\`.` }],\n structuredContent: success(\n `Removed ${ingredientEntryId} from slot \"${slotId}\".`,\n { mapEntryId, slotId, ingredientEntryId },\n [{ tool: \"map\", description: \"View updated map\", parameters: { action: \"get\", mapEntryId } }],\n ),\n };\n }\n\n if (action === \"replace\") {\n if (!slotId || !ingredientEntryId || !newIngredientEntryId) {\n return validationResult(\"`slotId`, `ingredientEntryId`, and `newIngredientEntryId` are required for replace.\");\n }\n\n await kernelMutation(\"maps.replaceInSlot\", { mapEntryId, slotId, oldIngredientEntryId: ingredientEntryId, newIngredientEntryId, label, author });\n\n return {\n content: [{ type: \"text\" as const, text: `Replaced \\`${ingredientEntryId}\\` with \\`${newIngredientEntryId}\\` in slot \"${slotId}\".` }],\n structuredContent: success(\n `Replaced ${ingredientEntryId} with ${newIngredientEntryId} in slot \"${slotId}\".`,\n { mapEntryId, slotId, removed: ingredientEntryId, added: newIngredientEntryId },\n [{ tool: \"map\", description: \"View updated map\", parameters: { action: \"get\", mapEntryId } }],\n ),\n };\n }\n\n return unknownAction(action, [\"add\", \"remove\", \"replace\", \"list\"]);\n })\n );\n trackWriteTool(mapSlotTool);\n\n // ─── map-version: commit, list history, diff ───────────────────────\n\n const mapVersionTool = server.registerTool(\n \"map-version\",\n {\n title: \"Map Version\",\n description:\n \"Commit a map (pins ingredient versions), list commit history, or view a specific commit.\",\n inputSchema: mapVersionSchema,\n annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: false },\n },\n thinWrapper(async ({ action, mapEntryId, commitMessage, author }) => {\n if (action === \"commit\") {\n const result = await kernelMutation<any>(\"maps.commitMap\", {\n mapEntryId,\n commitMessage: commitMessage ?? \"Map committed\",\n author,\n });\n\n return {\n content: [\n {\n type: \"text\" as const,\n text:\n `# Map Committed\\n\\n` +\n `- **Version:** ${result.version}\\n` +\n `- **Completion:** ${result.completionScore}%\\n` +\n `- **Slots modified:** ${result.slotsModified.length > 0 ? result.slotsModified.join(\", \") : \"(none)\"}\\n\\n` +\n `All ingredient references have been pinned at their current versions.`,\n },\n ],\n structuredContent: success(\n `Committed map ${mapEntryId} at v${result.version} (${result.completionScore}% complete).`,\n { mapEntryId, version: result.version, versionDisplay: toVersionDisplay(result.version), completionScore: result.completionScore, slotsModified: result.slotsModified },\n ),\n };\n }\n\n if (action === \"list\" || action === \"history\") {\n const commits = await kernelQuery<any[]>(\"maps.listMapCommits\", { mapEntryId });\n\n if (!commits || commits.length === 0) {\n return {\n content: [{ type: \"text\" as const, text: `No commits yet for map \\`${mapEntryId}\\`. Use \\`map-version action=commit\\` to create the first snapshot.` }],\n structuredContent: success(\n `No commits yet for ${mapEntryId}.`,\n { mapEntryId, commits: [], total: 0 },\n [{ tool: \"map-version\", description: \"Commit the map\", parameters: { action: \"commit\", mapEntryId } }],\n ),\n };\n }\n\n const lines = commits.map(\n (c: any) =>\n `- **v${c.version}** (${new Date(c.createdAt).toLocaleDateString()}) — ${c.commitMessage ?? \"(no message)\"} — by ${c.author}` +\n (c.slotsModified.length > 0 ? `\\n Slots changed: ${c.slotsModified.join(\", \")}` : \"\")\n );\n\n return {\n content: [{ type: \"text\" as const, text: `# Map History: \\`${mapEntryId}\\` (${commits.length} commits)\\n\\n${lines.join(\"\\n\")}` }],\n structuredContent: success(\n `${commits.length} commit(s) for ${mapEntryId}.`,\n { mapEntryId, total: commits.length },\n ),\n };\n }\n\n return unknownAction(action, [\"commit\", \"list\", \"history\"]);\n })\n );\n trackWriteTool(mapVersionTool);\n\n // ─── map-suggest: find ingredients to fill slots ───────────────────\n\n server.registerTool(\n \"map-suggest\",\n {\n title: \"Map Suggest\",\n description:\n \"Given a map with empty slots, search the Chain for ingredients that could fill them. \" +\n \"Uses keyword search and collection matching based on the template's suggested collections.\",\n inputSchema: mapSuggestSchema,\n annotations: { readOnlyHint: true, idempotentHint: true, openWorldHint: false },\n },\n thinWrapper(async ({ mapEntryId, slotId, query }) => {\n const map = await kernelQuery<any>(\"maps.getMap\", { mapEntryId });\n if (!map) {\n return {\n content: [{ type: \"text\" as const, text: `Map \"${mapEntryId}\" not found.` }],\n structuredContent: failure(\n \"NOT_FOUND\",\n `Map \"${mapEntryId}\" not found.`,\n \"Use map action=list to find available maps.\",\n [{ tool: \"map\", description: \"List maps\", parameters: { action: \"list\" } }],\n ),\n };\n }\n\n const emptySlots = slotId\n ? [slotId].filter((id) => (map.slots[id]?.length ?? 0) === 0)\n : Object.entries(map.slots as Record<string, any[]>)\n .filter(([, refs]) => refs.length === 0)\n .map(([id]) => id);\n\n if (emptySlots.length === 0) {\n const msg = slotId\n ? `Slot \"${slotId}\" already has ingredients.`\n : \"All slots have ingredients. Nothing to suggest.\";\n return {\n content: [{ type: \"text\" as const, text: msg }],\n structuredContent: success(msg, { mapEntryId, emptySlots: 0 }),\n };\n }\n\n const slotDefs = map.slotDefs ?? [];\n const suggestions: string[] = [];\n\n for (const sid of emptySlots) {\n const def = slotDefs.find((s: any) => s.id === sid);\n const searchQuery = query ?? def?.label ?? sid;\n\n const results = await kernelQuery<any[]>(\"knowledge.search\", {\n query: searchQuery,\n limit: 5,\n });\n\n if (results && results.length > 0) {\n const items = results.map(\n (r: any) =>\n ` - **${r.name}** (\\`${r.entryId}\\`, ${r.collectionName ?? \"unknown\"}) — ${r.status}`\n );\n suggestions.push(\n `### ${def?.label ?? sid}\\n${def?.description ?? \"\"}\\n\\n${items.join(\"\\n\")}`\n );\n } else {\n suggestions.push(\n `### ${def?.label ?? sid}\\n_No matching entries found. Create ingredients first._`\n );\n }\n }\n\n return {\n content: [\n {\n type: \"text\" as const,\n text:\n `# Ingredient Suggestions for \"${map.name}\"\\n\\n` +\n suggestions.join(\"\\n\\n\") +\n `\\n\\nUse \\`map-slot action=add mapEntryId=\"${mapEntryId}\" slotId=\"...\" ingredientEntryId=\"...\"\\` to add ingredients.`,\n },\n ],\n structuredContent: success(\n `Suggestions for ${emptySlots.length} empty slot(s) on \"${map.name}\".`,\n { mapEntryId, emptySlots: emptySlots.length },\n [{ tool: \"map-slot\", description: \"Add ingredient\", parameters: { action: \"add\", mapEntryId } }],\n ),\n };\n })\n );\n}\n","/**\n * Architecture tools — ARCH-node-mcp (Core layer)\n *\n * Tools: architecture (show/explore/flow), architecture-admin (seed/check)\n * Chain refs: FEAT-ARCH-001 (Architecture Explorer), FEAT-dep-health (Dep Health Scanner),\n * SOS-dbl1n9 (dependency direction rule), GT-wk426u (Fitness Function)\n */\n\nimport { existsSync, readFileSync, readdirSync, statSync } from \"node:fs\";\nimport { resolve, relative, dirname, normalize } from \"node:path\";\nimport { resolveProjectRoot } from \"../lib/resolve-project-root.js\";\nimport { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { z } from \"zod\";\nimport { kernelQuery, kernelMutation } from \"../client.js\";\nimport { trackWriteTool } from \"../tool-surface.js\";\nimport { thinWrapper, success, failure, validationResult, unknownAction } from \"../envelope.js\";\nconst COLLECTION_SLUG = \"architecture\";\n\nconst COLLECTION_FIELDS = [\n { key: \"archType\", label: \"Architecture Type\", type: \"select\", required: true, options: [\"template\", \"layer\", \"node\", \"flow\"], searchable: true },\n { key: \"templateRef\", label: \"Template Entry ID\", type: \"text\", searchable: false },\n { key: \"layerRef\", label: \"Layer Entry ID\", type: \"text\", searchable: false },\n { key: \"description\", label: \"Description\", type: \"text\", searchable: true },\n { key: \"color\", label: \"Color\", type: \"text\" },\n { key: \"icon\", label: \"Icon\", type: \"text\" },\n { key: \"sourceNode\", label: \"Source Node (flows)\", type: \"text\" },\n { key: \"targetNode\", label: \"Target Node (flows)\", type: \"text\" },\n { key: \"filePaths\", label: \"File Paths\", type: \"text\", searchable: true },\n { key: \"owner\", label: \"Owner (circle/role)\", type: \"text\", searchable: true },\n { key: \"layerOrder\", label: \"Layer Order (for templates)\", type: \"text\" },\n { key: \"rationale\", label: \"Why Here? (placement rationale)\", type: \"text\", searchable: true },\n { key: \"dependsOn\", label: \"Allowed Dependencies (layers this can import from)\", type: \"text\" },\n];\n\ninterface ArchEntry {\n _id: string;\n entryId: string;\n name: string;\n status: string;\n order: number;\n data: Record<string, unknown>;\n tags?: string[];\n}\n\nconst ARCHITECTURE_CANONICAL_KEY = \"architecture_note\";\n\nasync function ensureCollection(): Promise<void> {\n const collections = await kernelQuery<any[]>(\"chain.listCollections\");\n const existing = collections.find((c: any) => c.slug === COLLECTION_SLUG);\n\n if (existing) {\n if (!existing.defaultCanonicalKey) {\n await kernelMutation(\"chain.updateCollection\", {\n slug: COLLECTION_SLUG,\n defaultCanonicalKey: ARCHITECTURE_CANONICAL_KEY,\n });\n }\n return;\n }\n\n await kernelMutation(\"chain.createCollection\", {\n slug: COLLECTION_SLUG,\n name: \"Architecture\",\n icon: \"🏗️\",\n description:\n \"System architecture map — templates, layers, nodes, and flows. \" +\n \"Visualized in the Architecture Explorer and via MCP architecture tools.\",\n fields: COLLECTION_FIELDS,\n });\n}\n\nasync function listArchEntries(): Promise<ArchEntry[]> {\n return kernelQuery<ArchEntry[]>(\"chain.listEntries\", { collectionSlug: COLLECTION_SLUG });\n}\n\nfunction byTag(entries: ArchEntry[], archType: string): ArchEntry[] {\n return entries\n .filter((e) => e.tags?.includes(`archType:${archType}`) || e.data?.archType === archType)\n .sort((a, b) => (a.order ?? 0) - (b.order ?? 0));\n}\n\n// ── HTML renderer for MCP Apps ──────────────────────────────────────────────\n\nfunction renderArchitectureHtml(\n layers: ArchEntry[],\n nodes: ArchEntry[],\n flows: ArchEntry[],\n templateName: string,\n): string {\n const layerHtml = layers.map((layer) => {\n const layerNodes = nodes.filter(\n (n) => n.data?.layerRef === layer.entryId\n );\n const nodeCards = layerNodes.map((n) => `\n <div class=\"node\" title=\"${escHtml(String(n.data?.description ?? ''))}\">\n <span class=\"node-icon\">${escHtml(String(n.data?.icon ?? '◻'))}</span>\n <span class=\"node-name\">${escHtml(n.name)}</span>\n </div>\n `).join(\"\");\n\n return `\n <div class=\"layer\" style=\"--layer-color: ${escHtml(String(layer.data?.color ?? '#666'))}\">\n <div class=\"layer-label\">\n <span class=\"layer-dot\"></span>\n <span class=\"layer-name\">${escHtml(layer.name)}</span>\n <span class=\"layer-count\">${layerNodes.length}</span>\n </div>\n <div class=\"layer-desc\">${escHtml(String(layer.data?.description ?? ''))}</div>\n <div class=\"nodes\">${nodeCards || '<span class=\"empty\">No components</span>'}</div>\n </div>\n `;\n }).join(\"\");\n\n return `<!DOCTYPE html>\n<html><head><meta charset=\"utf-8\"><style>\n*{margin:0;padding:0;box-sizing:border-box}\nbody{font-family:-apple-system,system-ui,sans-serif;background:#1a1a2e;color:#e0e0e0;padding:16px}\nh1{font-size:14px;font-weight:600;color:#a0a0c0;margin-bottom:12px;letter-spacing:.04em}\n.layer{border-left:3px solid var(--layer-color);padding:8px 12px;margin-bottom:8px;background:rgba(255,255,255,.03);border-radius:0 6px 6px 0}\n.layer-label{display:flex;align-items:center;gap:8px;margin-bottom:4px}\n.layer-dot{width:8px;height:8px;border-radius:50%;background:var(--layer-color)}\n.layer-name{font-size:12px;font-weight:600;color:#fff;letter-spacing:.03em}\n.layer-count{font-size:10px;color:var(--layer-color);background:rgba(255,255,255,.06);padding:1px 6px;border-radius:8px}\n.layer-desc{font-size:11px;color:#888;margin-bottom:6px}\n.nodes{display:flex;flex-wrap:wrap;gap:6px}\n.node{display:flex;align-items:center;gap:4px;background:rgba(255,255,255,.06);border:1px solid rgba(255,255,255,.08);border-radius:4px;padding:4px 8px;font-size:11px;cursor:default;transition:border-color .15s}\n.node:hover{border-color:var(--layer-color)}\n.node-icon{font-size:12px}\n.node-name{color:#ddd}\n.empty{font-size:11px;color:#555;font-style:italic}\n.flows{margin-top:12px;border-top:1px solid rgba(255,255,255,.06);padding-top:8px}\n.flow{font-size:11px;color:#888;padding:2px 0}\n.flow-arrow{color:#6366f1;margin:0 4px}\n</style></head><body>\n<h1>${escHtml(templateName)}</h1>\n${layerHtml}\n${flows.length > 0 ? `<div class=\"flows\"><div style=\"font-size:10px;color:#666;margin-bottom:4px;letter-spacing:.06em\">DATA FLOWS</div>${flows.map((f) => `<div class=\"flow\">${escHtml(f.name)}<span class=\"flow-arrow\">→</span><span style=\"color:#aaa\">${escHtml(String(f.data?.description ?? ''))}</span></div>`).join(\"\")}</div>` : \"\"}\n</body></html>`;\n}\n\nfunction escHtml(s: string): string {\n return s.replace(/&/g, \"&\").replace(/</g, \"<\").replace(/>/g, \">\").replace(/\"/g, \""\");\n}\n\nfunction formatLayerText(layer: ArchEntry, nodes: ArchEntry[]): string {\n const layerNodes = nodes.filter((n) => n.data?.layerRef === layer.entryId);\n const nodeList = layerNodes.map((n) => {\n const desc = n.data?.description ? ` — ${n.data.description}` : \"\";\n const owner = n.data?.owner ? ` (${n.data.owner})` : \"\";\n return ` - ${n.data?.icon ?? \"◻\"} **${n.name}**${desc}${owner}`;\n }).join(\"\\n\");\n return `### ${layer.name}\\n${layer.data?.description ?? \"\"}\\n\\n${nodeList || \" _No components_\"}`;\n}\n\n// ── Seed data: Product OS default architecture ──────────────────────────────\n\nconst SEED_TEMPLATE = {\n entryId: \"ARCH-tpl-product-os\",\n name: \"Product OS Default\",\n data: {\n archType: \"template\",\n description: \"Default 4-layer architecture: Auth → Infrastructure → Core → Features, with an outward Integration layer\",\n layerOrder: JSON.stringify([\"auth\", \"infrastructure\", \"core\", \"features\", \"integration\"]),\n },\n};\n\nconst SEED_LAYERS = [\n { entryId: \"ARCH-layer-auth\", name: \"Auth\", order: 0, data: { archType: \"layer\", templateRef: \"ARCH-tpl-product-os\", color: \"#22c55e\", description: \"Authentication, user management, and workspace-scoped access control\", icon: \"🔐\", dependsOn: \"none\", rationale: \"Foundation layer. Auth depends on nothing — it is the first gate. No layer may bypass auth. All other layers depend on auth to know who the user is and which workspace they belong to.\" } },\n { entryId: \"ARCH-layer-infra\", name: \"Infrastructure\", order: 1, data: { archType: \"layer\", templateRef: \"ARCH-tpl-product-os\", color: \"#ec4899\", description: \"Real-time data, event tracking, and AI model infrastructure\", icon: \"⚙️\", dependsOn: \"Auth\", rationale: \"Infrastructure sits on top of Auth. It provides the database, analytics, and AI plumbing that Core and Features consume. Infra may import from Auth (needs workspace context) but never from Core or Features.\" } },\n { entryId: \"ARCH-layer-core\", name: \"Core\", order: 2, data: { archType: \"layer\", templateRef: \"ARCH-tpl-product-os\", color: \"#8b5cf6\", description: \"Business logic, knowledge graph, workflow engines, and MCP tooling\", icon: \"🧠\", dependsOn: \"Auth, Infrastructure\", rationale: \"Core contains business logic and engines that are UI-agnostic. It may import from Auth and Infra. Features depend on Core, but Core must never depend on Features — this is what keeps engines reusable across different UIs.\" } },\n { entryId: \"ARCH-layer-features\", name: \"Features\", order: 3, data: { archType: \"layer\", templateRef: \"ARCH-tpl-product-os\", color: \"#6366f1\", description: \"User-facing pages, components, and feature modules\", icon: \"✦\", dependsOn: \"Auth, Infrastructure, Core\", rationale: \"Features are the user-facing layer — SvelteKit routes, components, and page-level logic. Features may import from any lower layer but nothing above may import from Features. This is the outermost application layer.\" } },\n { entryId: \"ARCH-layer-integration\", name: \"Integration\", order: 4, data: { archType: \"layer\", templateRef: \"ARCH-tpl-product-os\", color: \"#f59e0b\", description: \"Outward connections to external tools, IDEs, and services\", icon: \"🔌\", dependsOn: \"Core\", rationale: \"Integration is a lateral/outward layer — it connects to external systems (IDE, GitHub, Linear). It depends on Core (to expose knowledge) but sits outside the main stack. External tools call into Core via Integration, never directly into Features.\" } },\n];\n\nconst SEED_NODES = [\n // Auth layer\n { entryId: \"ARCH-node-clerk\", name: \"Clerk\", order: 0, data: { archType: \"node\", layerRef: \"ARCH-layer-auth\", color: \"#22c55e\", icon: \"🔑\", description: \"Authentication provider — sign-in/sign-up pages, session management, organization-level access control. UserSync.svelte is cross-cutting layout glue (not mapped here).\", filePaths: \"src/routes/sign-in/, src/routes/sign-up/\", owner: \"Platform\", rationale: \"Auth layer because Clerk is the identity gate. Every request flows through auth first. No other layer provides identity.\" } },\n { entryId: \"ARCH-node-workspace\", name: \"Workspace Scoping\", order: 1, data: { archType: \"node\", layerRef: \"ARCH-layer-auth\", color: \"#22c55e\", icon: \"🏢\", description: \"Multi-tenancy anchor — all data is workspace-scoped via workspaceId\", filePaths: \"src/lib/stores/workspace.ts, convex/workspaces.ts\", owner: \"Platform\", rationale: \"Auth layer because workspace scoping is the second gate after identity. All queries require workspaceId, making this foundational.\" } },\n\n // Infrastructure layer\n { entryId: \"ARCH-node-convex\", name: \"Convex\", order: 0, data: { archType: \"node\", layerRef: \"ARCH-layer-infra\", color: \"#ec4899\", icon: \"⚡\", description: \"Reactive database with real-time sync, serverless functions, and type-safe API generation. Unified Collections + Entries model\", filePaths: \"convex/schema.ts, convex/entries.ts, convex/http.ts\", owner: \"Platform\", rationale: \"Infrastructure because Convex is raw persistence and reactivity plumbing. It stores data but has no business logic opinions. Core and Features consume it.\" } },\n { entryId: \"ARCH-node-posthog\", name: \"PostHog\", order: 1, data: { archType: \"node\", layerRef: \"ARCH-layer-infra\", color: \"#ec4899\", icon: \"📊\", description: \"Product analytics — workspace-scoped events, feature flags, session replay\", filePaths: \"src/lib/analytics.ts, src/lib/components/PostHogWorkspaceSync.svelte\", owner: \"Platform\", rationale: \"Infrastructure because PostHog is analytics plumbing — event collection and aggregation. It has no knowledge of business domains.\" } },\n { entryId: \"ARCH-node-openrouter\", name: \"OpenRouter\", order: 2, data: { archType: \"node\", layerRef: \"ARCH-layer-infra\", color: \"#ec4899\", icon: \"🤖\", description: \"AI model routing for ChainWork artifact generation — streaming responses with format-aware prompts\", filePaths: \"src/routes/api/chainwork/generate/+server.ts\", owner: \"ChainWork\", rationale: \"Infrastructure because OpenRouter is an AI model gateway — it routes prompts to models. The strategy logic lives in ChainWork Engine (Core); this is just the pipe.\" } },\n\n // Core layer\n { entryId: \"ARCH-node-mcp\", name: \"MCP Server\", order: 0, data: { archType: \"node\", layerRef: \"ARCH-layer-core\", color: \"#8b5cf6\", icon: \"🔧\", description: \"~19 modular tools exposing the knowledge graph as AI-consumable operations — capture, context assembly, verification, quality checks\", filePaths: \"packages/mcp-server/src/index.ts, packages/mcp-server/src/tools/\", owner: \"AI DX\", rationale: \"Core layer because the MCP server encodes business operations — capture with auto-linking, quality scoring, governance rules. It depends on Infra (Convex) but never touches UI routes. Why not Infrastructure? Because it has domain opinions. Why not Features? Because it has no UI — any client (Cursor, CLI, API) can call it.\" } },\n { entryId: \"ARCH-node-knowledge-graph\", name: \"Knowledge Graph\", order: 1, data: { archType: \"node\", layerRef: \"ARCH-layer-core\", color: \"#8b5cf6\", icon: \"🕸️\", description: \"20 collections, 170+ entries with typed cross-collection relations. Smart capture, auto-linking, quality scoring\", filePaths: \"convex/agentKnowledge/*, convex/entries.ts\", owner: \"Knowledge\", rationale: \"Core layer because the knowledge graph IS the domain model — collections, entries, relations, versioning, quality scoring. Glossary DATA, business rules DATA, tension DATA all live here. Why not Features? Because the data model exists independently of any page. The Glossary page in Features is just one way to visualize terms that Core owns. Think: Core owns the dictionary, Features owns the dictionary app.\" } },\n { entryId: \"ARCH-node-governance\", name: \"Governance Engine\", order: 2, data: { archType: \"node\", layerRef: \"ARCH-layer-core\", color: \"#8b5cf6\", icon: \"⚖️\", description: \"Circles, roles, consent-based decision-making, tension processing with IDM-inspired async workflows\", filePaths: \"convex/versioning.ts, src/lib/components/versioning/\", owner: \"Governance\", rationale: \"Core layer because governance logic (draft→publish workflows, consent-based decisions, tension status rules) is business process that multiple UIs consume. Why not Features? Because the versioning system and proposal flow are reusable engines — the Governance Pages in Features are just one rendering of these rules.\" } },\n { entryId: \"ARCH-node-chainwork-engine\", name: \"ChainWork Engine\", order: 3, data: { archType: \"node\", layerRef: \"ARCH-layer-core\", color: \"#8b5cf6\", icon: \"⛓\", description: \"Guided strategy creation through 5-step coherence chain — AI-generated artifacts with scoring and achievements\", filePaths: \"src/lib/components/chainwork/config.ts, src/lib/components/chainwork/scoring.ts\", owner: \"ChainWork\", rationale: \"Core layer because the coherence chain logic, scoring algorithm, and quality gates are business rules. config.ts defines chain steps, scoring.ts computes quality — these could power a CLI or API. Why not Features? Because the ChainWork UI wizard in Features is just one skin over this engine.\" } },\n\n // Features layer\n { entryId: \"ARCH-node-command-center\", name: \"Command Center\", order: 0, data: { archType: \"node\", layerRef: \"ARCH-layer-features\", color: \"#6366f1\", icon: \"⬡\", description: \"Calm home screen — daily orientation, triage mode, pulse metrics, momentum tracking\", filePaths: \"src/routes/+page.svelte, src/lib/components/command-center/\", owner: \"Command Center\", rationale: \"Features layer because the Command Center is a SvelteKit page — PulseMetrics, NeedsAttention, DailyBriefing are UI components that assemble data from Core queries. Why not Core? Because it has no reusable business logic or engines — it is pure layout and presentation. If you deleted this page, no business rule would break.\" } },\n { entryId: \"ARCH-node-chainwork-ui\", name: \"ChainWork UI\", order: 1, data: { archType: \"node\", layerRef: \"ARCH-layer-features\", color: \"#6366f1\", icon: \"⛓\", description: \"Multi-step wizard for strategy artifact creation — setup, chain steps, quality gates, output\", filePaths: \"src/routes/chainwork/, src/lib/components/chainwork/\", owner: \"ChainWork\", rationale: \"Features layer because the ChainWork UI is the wizard interface — step navigation, form inputs, output rendering. Why not Core? Because the scoring logic and chain config ARE in Core (ChainWork Engine). This is the presentation skin over that engine. Delete this page and the engine still works via MCP.\" } },\n { entryId: \"ARCH-node-glossary\", name: \"Glossary\", order: 2, data: { archType: \"node\", layerRef: \"ARCH-layer-features\", color: \"#6366f1\", icon: \"Aa\", description: \"Canonical vocabulary management — term detail, code drift detection, inline term linking\", filePaths: \"src/routes/glossary/, src/lib/components/glossary/\", owner: \"Knowledge\", rationale: \"Features layer — NOT Core or Infrastructure — because this is the Glossary PAGE: the SvelteKit route for browsing, editing, and viewing terms. Why not Core? Because Core owns the glossary DATA (Knowledge Graph) and term-linking logic. The MCP server also accesses glossary terms without any page. Why not Infrastructure? Because glossary is domain-specific vocabulary, not generic plumbing. The page is one consumer of the data — Core owns the dictionary, Features owns the dictionary app.\" } },\n { entryId: \"ARCH-node-tensions\", name: \"Tensions\", order: 3, data: { archType: \"node\", layerRef: \"ARCH-layer-features\", color: \"#6366f1\", icon: \"⚡\", description: \"Tension capture and processing — raise, triage, resolve through governance workflow\", filePaths: \"src/routes/tensions/, src/lib/components/tensions/\", owner: \"Governance\", rationale: \"Features layer because this is the Tensions PAGE — the UI for raising, listing, and viewing tensions. Why not Core? Because tension data, status rules (SOS-020), and processing logic already live in Core (Governance Engine). This page is a form + list view that reads from and writes to Core. Delete it and the governance engine still processes tensions via MCP.\" } },\n { entryId: \"ARCH-node-strategy\", name: \"Strategy\", order: 4, data: { archType: \"node\", layerRef: \"ARCH-layer-features\", color: \"#6366f1\", icon: \"▣\", description: \"Product strategy pages — vision, ecosystem, product areas, decision frameworks, sequencing\", filePaths: \"src/routes/strategy/, src/routes/bridge/, src/routes/topology/\", owner: \"Strategy\", rationale: \"Features layer because Strategy is a set of SvelteKit pages (strategy, bridge, topology) that visualize strategy entries. Why not Core? Because the strategy data (vision, principles, ecosystem layers) lives in the Knowledge Graph (Core). These pages render and allow inline editing — they consume Core downward.\" } },\n { entryId: \"ARCH-node-governance-ui\", name: \"Governance Pages\", order: 5, data: { archType: \"node\", layerRef: \"ARCH-layer-features\", color: \"#6366f1\", icon: \"◈\", description: \"Roles, teams, principles, policies, decisions, proposals, business rules\", filePaths: \"src/routes/roles/, src/routes/teams/, src/routes/decisions/, src/routes/proposals/\", owner: \"Governance\", rationale: \"Features layer because these are governance PAGES — list views and detail views for roles, teams, decisions, proposals. Why not Core? Because the governance ENGINE (versioning, consent, IDM) IS in Core. These pages are the user-facing window into governance data. The logic doesn't live here, only the rendering.\" } },\n { entryId: \"ARCH-node-artifacts\", name: \"Artifacts\", order: 6, data: { archType: \"node\", layerRef: \"ARCH-layer-features\", color: \"#6366f1\", icon: \"📄\", description: \"Strategy artifacts from ChainWork — pitches, briefs, one-pagers linked to the knowledge graph\", filePaths: \"src/routes/artifacts/\", owner: \"ChainWork\", rationale: \"Features layer because the Artifacts page is a list/detail view for strategy artifacts produced by ChainWork. Why not Core? Because artifact data and scoring live in Core (ChainWork Engine). This page just renders the output and links back to the knowledge graph.\" } },\n\n // Integration layer\n { entryId: \"ARCH-node-cursor\", name: \"Cursor IDE\", order: 0, data: { archType: \"node\", layerRef: \"ARCH-layer-integration\", color: \"#f59e0b\", icon: \"🖥️\", description: \"AI-assisted development with MCP-powered knowledge context — smart capture, verification, context assembly in the editor\", filePaths: \".cursor/mcp.json, .cursor/rules/\", owner: \"AI DX\", rationale: \"Integration layer because Cursor is an external tool that connects INTO our system via MCP. Why not Core or Features? Because Cursor itself is not our code — it's a consumer. The .cursor/ config files define how it talks to us, but Cursor lives outside our deployment boundary.\" } },\n { entryId: \"ARCH-node-github\", name: \"GitHub\", order: 1, data: { archType: \"node\", layerRef: \"ARCH-layer-integration\", color: \"#f59e0b\", icon: \"🐙\", description: \"Code repository, PR reviews with governance context, CI/CD\", owner: \"Platform\", rationale: \"Integration layer because GitHub is an external service. Why not Infrastructure? Because Infra is about plumbing we control (database, analytics). GitHub is a third-party that hooks into our Core (PR reviews checking governance rules) but is not part of our deployed application.\" } },\n { entryId: \"ARCH-node-linear\", name: \"Linear (planned)\", order: 2, data: { archType: \"node\", layerRef: \"ARCH-layer-integration\", color: \"#f59e0b\", icon: \"📐\", description: \"Issue tracking, roadmap sync, tension-to-issue pipeline (planned integration)\", owner: \"Platform\", rationale: \"Integration layer because Linear is an external issue tracker. Why not Infrastructure? Because Infra is generic plumbing we run. Linear is a third-party tool we connect to. The planned pipeline bridges tensions (Core) to Linear issues — a classic outward integration pattern.\" } },\n];\n\nconst SEED_FLOWS = [\n { entryId: \"ARCH-flow-smart-capture\", name: \"Capture Flow\", order: 0, data: { archType: \"flow\", sourceNode: \"ARCH-node-cursor\", targetNode: \"ARCH-node-knowledge-graph\", description: \"Developer/AI calls capture via MCP → entry created with auto-linking and quality score → stored in Knowledge Graph\", color: \"#8b5cf6\" } },\n { entryId: \"ARCH-flow-governance\", name: \"Governance Flow\", order: 1, data: { archType: \"flow\", sourceNode: \"ARCH-node-tensions\", targetNode: \"ARCH-node-governance\", description: \"Tension raised → appears in Command Center → triaged → processed via IDM → decision logged\", color: \"#6366f1\" } },\n { entryId: \"ARCH-flow-chainwork\", name: \"ChainWork Strategy Flow\", order: 2, data: { archType: \"flow\", sourceNode: \"ARCH-node-chainwork-ui\", targetNode: \"ARCH-node-artifacts\", description: \"Leader opens ChainWork → walks coherence chain → AI generates artifact → scored and published to knowledge graph\", color: \"#f59e0b\" } },\n { entryId: \"ARCH-flow-knowledge-trust\", name: \"Knowledge Trust Flow\", order: 3, data: { archType: \"flow\", sourceNode: \"ARCH-node-mcp\", targetNode: \"ARCH-node-glossary\", description: \"MCP verify tool checks entries against codebase → file existence, schema references validated → trust scores updated\", color: \"#22c55e\" } },\n { entryId: \"ARCH-flow-analytics\", name: \"Analytics Flow\", order: 4, data: { archType: \"flow\", sourceNode: \"ARCH-node-command-center\", targetNode: \"ARCH-node-posthog\", description: \"Feature views and actions tracked → workspace-scoped events → PostHog group analytics → Command Center metrics\", color: \"#ec4899\" } },\n];\n\n// ── Tool Registration ───────────────────────────────────────────────────────\n\nexport const architectureSchema = z.object({\n action: z.enum([\"show\", \"explore\", \"flow\"])\n .describe(\"Action: show full map, explore a layer, or visualize a flow\"),\n template: z.string().optional().describe(\"Template entry ID to filter by (for show)\"),\n layer: z.string().optional().describe(\"Layer name or entry ID (for explore), e.g. 'Core' or 'ARCH-layer-core'\"),\n flow: z.string().optional().describe(\"Flow name or entry ID (for flow), e.g. 'Smart Capture Flow'\"),\n});\n\nexport const architectureAdminSchema = z.object({\n action: z.enum([\"seed\", \"check\"])\n .describe(\"Action: seed default architecture data, or check dependency health\"),\n});\n\nexport function registerArchitectureTools(server: McpServer) {\n\n // ─── architecture: viewing operations ───────────────────────────────\n\n server.registerTool(\n \"architecture\",\n {\n title: \"Architecture\",\n description:\n \"Explore the system architecture — show the full map, explore a specific layer, or visualize a data flow.\\n\\n\" +\n \"Actions:\\n\" +\n \"- `show`: Render the layered architecture map (Auth → Infra → Core → Features → Integration)\\n\" +\n \"- `explore`: Drill into a layer to see nodes, ownership, file paths\\n\" +\n \"- `flow`: Visualize a data flow path between nodes\",\n inputSchema: architectureSchema,\n annotations: { readOnlyHint: true, idempotentHint: true, openWorldHint: false },\n },\n thinWrapper(async ({ action, template, layer, flow }) => {\n await ensureCollection();\n const all = await listArchEntries();\n\n if (action === \"show\") {\n const templates = byTag(all, \"template\");\n const activeTemplate = template\n ? templates.find((t) => t.entryId === template)\n : templates[0];\n\n const templateName = activeTemplate?.name ?? \"System Architecture\";\n const templateId = activeTemplate?.entryId;\n\n const layers = byTag(all, \"layer\")\n .filter((l) => !templateId || l.data?.templateRef === templateId);\n const nodes = byTag(all, \"node\");\n const flows = byTag(all, \"flow\");\n\n if (layers.length === 0) {\n return {\n content: [{\n type: \"text\" as const,\n text: \"# Architecture Explorer\\n\\nNo architecture data found. Use `architecture-admin action=seed` to populate the default architecture.\",\n }],\n structuredContent: failure(\n \"NOT_FOUND\",\n \"No architecture data found.\",\n \"Seed the default architecture first.\",\n [{ tool: \"architecture-admin\", description: \"Seed architecture\", parameters: { action: \"seed\" } }],\n ),\n };\n }\n\n const textLayers = layers.map((l) => formatLayerText(l, nodes)).join(\"\\n\\n\");\n const textFlows = flows.length > 0\n ? \"\\n\\n---\\n\\n## Data Flows\\n\\n\" + flows.map((f) =>\n `- **${f.name}**: ${f.data?.description ?? \"\"}`\n ).join(\"\\n\")\n : \"\";\n\n const text = `# ${templateName}\\n\\n${textLayers}${textFlows}`;\n\n return {\n content: [{ type: \"text\" as const, text }],\n structuredContent: success(\n `Showing ${templateName}: ${layers.length} layers, ${nodes.length} nodes, ${flows.length} flows.`,\n { templateName, layerCount: layers.length, nodeCount: nodes.length, flowCount: flows.length },\n ),\n };\n }\n\n if (action === \"explore\") {\n if (!layer) {\n return validationResult(\"A `layer` is required for explore.\");\n }\n\n const layers = byTag(all, \"layer\");\n const target = layers.find(\n (l) => l.name.toLowerCase() === layer.toLowerCase() || l.entryId === layer\n );\n\n if (!target) {\n const available = layers.map((l) => `\\`${l.name}\\``).join(\", \");\n return {\n content: [{ type: \"text\" as const, text: `Layer \"${layer}\" not found. Available layers: ${available}` }],\n structuredContent: failure(\n \"NOT_FOUND\",\n `Layer \"${layer}\" not found.`,\n `Available layers: ${available}`,\n ),\n };\n }\n\n const nodes = byTag(all, \"node\").filter((n) => n.data?.layerRef === target.entryId);\n const flows = byTag(all, \"flow\").filter(\n (f) => nodes.some((n) => n.entryId === f.data?.sourceNode || n.entryId === f.data?.targetNode)\n );\n\n const depRule = target.data?.dependsOn\n ? `\\n**Dependency rule:** May import from ${target.data.dependsOn === \"none\" ? \"nothing (foundation layer)\" : target.data.dependsOn}.\\n`\n : \"\";\n const layerRationale = target.data?.rationale ? `\\n> ${target.data.rationale}\\n` : \"\";\n\n const nodeDetail = nodes.map((n) => {\n const lines = [`#### ${n.data?.icon ?? \"◻\"} ${n.name}`];\n if (n.data?.description) lines.push(String(n.data.description));\n if (n.data?.owner) lines.push(`**Owner:** ${n.data.owner}`);\n if (n.data?.filePaths) lines.push(`**Files:** \\`${n.data.filePaths}\\``);\n if (n.data?.rationale) lines.push(`\\n**Why here?** ${n.data.rationale}`);\n return lines.join(\"\\n\");\n }).join(\"\\n\\n\");\n\n const flowLines = flows.length > 0\n ? \"\\n\\n### Connected Flows\\n\\n\" + flows.map((f) => `- ${f.name}: ${f.data?.description ?? \"\"}`).join(\"\\n\")\n : \"\";\n\n return {\n content: [{\n type: \"text\" as const,\n text: `# ${target.data?.icon ?? \"\"} ${target.name} Layer\\n\\n${target.data?.description ?? \"\"}${depRule}${layerRationale}\\n**${nodes.length} components**\\n\\n${nodeDetail}${flowLines}`,\n }],\n structuredContent: success(\n `${target.name} layer: ${nodes.length} components, ${flows.length} connected flows.`,\n { layerName: target.name, entryId: target.entryId, nodeCount: nodes.length, flowCount: flows.length },\n ),\n };\n }\n\n if (action === \"flow\") {\n if (!flow) {\n return validationResult(\"A `flow` name or entry ID is required.\");\n }\n\n const flows = byTag(all, \"flow\");\n const target = flows.find(\n (f) => f.name.toLowerCase() === flow.toLowerCase() || f.entryId === flow\n );\n\n if (!target) {\n const available = flows.map((f) => `\\`${f.name}\\``).join(\", \");\n return {\n content: [{ type: \"text\" as const, text: `Flow \"${flow}\" not found. Available flows: ${available}` }],\n structuredContent: failure(\n \"NOT_FOUND\",\n `Flow \"${flow}\" not found.`,\n `Available flows: ${available}`,\n ),\n };\n }\n\n const nodes = byTag(all, \"node\");\n const source = nodes.find((n) => n.entryId === target.data?.sourceNode);\n const dest = nodes.find((n) => n.entryId === target.data?.targetNode);\n\n const lines = [\n `# ${target.name}`,\n \"\",\n `**${source?.data?.icon ?? \"?\"} ${source?.name ?? \"Unknown\"}** → **${dest?.data?.icon ?? \"?\"} ${dest?.name ?? \"Unknown\"}**`,\n \"\",\n String(target.data?.description ?? \"\"),\n ];\n\n if (source) {\n lines.push(\"\", `### Source: ${source.name}`, String(source.data?.description ?? \"\"));\n if (source.data?.filePaths) lines.push(`Files: \\`${source.data.filePaths}\\``);\n }\n if (dest) {\n lines.push(\"\", `### Target: ${dest.name}`, String(dest.data?.description ?? \"\"));\n if (dest.data?.filePaths) lines.push(`Files: \\`${dest.data.filePaths}\\``);\n }\n\n return {\n content: [{ type: \"text\" as const, text: lines.join(\"\\n\") }],\n structuredContent: success(\n `${target.name}: ${source?.name ?? \"?\"} → ${dest?.name ?? \"?\"}.`,\n { flowName: target.name, entryId: target.entryId, source: source?.name, target: dest?.name },\n ),\n };\n }\n\n return unknownAction(action, [\"show\", \"explore\", \"flow\"]);\n })\n );\n\n // ─── architecture-admin: seed and health check (PB_INTERNAL only) ──\n // TEN-2023: architecture-admin description contains \"seed\" which collides with\n // workspace setup intent. Gate behind PB_INTERNAL=true so it only appears in\n // Product OS internal environments. Full deprecation tracked by TEN-2029.\n\n if (process.env.PB_INTERNAL === \"true\") {\n const archAdminTool = server.registerTool(\n \"architecture-admin\",\n {\n title: \"Architecture Admin\",\n description:\n \"Architecture maintenance — seed the default architecture data or run a dependency health check.\\n\\n\" +\n \"Actions:\\n\" +\n \"- `seed`: Populate the architecture collection with the default Product OS map. Safe to re-run.\\n\" +\n \"- `check`: Scan the codebase for dependency direction violations against layer rules.\",\n inputSchema: architectureAdminSchema,\n annotations: { readOnlyHint: false, destructiveHint: true, openWorldHint: false },\n },\n thinWrapper(async ({ action }) => {\n if (action === \"seed\") {\n await ensureCollection();\n const existing = await listArchEntries();\n const existingIds = new Set(existing.map((e) => e.entryId));\n\n let created = 0;\n let updated = 0;\n let unchanged = 0;\n const allWarnings: Array<{ entryId: string; normalizationWarnings: string[]; validationWarnings: string[] }> = [];\n\n const allSeeds = [\n { ...SEED_TEMPLATE, order: 0, status: \"active\" },\n ...SEED_LAYERS.map((l) => ({ ...l, status: \"active\" as const })),\n ...SEED_NODES.map((n) => ({ ...n, status: \"active\" as const })),\n ...SEED_FLOWS.map((f) => ({ ...f, status: \"active\" as const })),\n ];\n\n for (const seed of allSeeds) {\n if (existingIds.has(seed.entryId)) {\n const existingEntry = existing.find((e) => e.entryId === seed.entryId);\n const existingData = (existingEntry?.data ?? {}) as Record<string, unknown>;\n const seedData = seed.data as Record<string, unknown>;\n const hasChanges = Object.keys(seedData).some(\n (k) => seedData[k] !== undefined && existingData[k] !== seedData[k],\n );\n if (hasChanges) {\n const mergedData = { ...existingData, ...seedData };\n const updateResult = await kernelMutation<{\n id: string;\n warnings: string[];\n normalization: { remapped: Record<string, string>; rejected: string[]; accepted: string[] };\n normalizationWarnings: string[];\n validationWarnings: string[];\n }>(\"chain.updateEntry\", { entryId: seed.entryId, data: mergedData });\n if (updateResult.normalizationWarnings.length > 0 || updateResult.validationWarnings.length > 0) {\n allWarnings.push({\n entryId: seed.entryId,\n normalizationWarnings: updateResult.normalizationWarnings,\n validationWarnings: updateResult.validationWarnings,\n });\n }\n updated++;\n } else {\n unchanged++;\n }\n continue;\n }\n const createResult = await kernelMutation<{\n docId: string;\n entryId: string;\n warnings: string[];\n normalization: { remapped: Record<string, string>; rejected: string[]; accepted: string[] };\n normalizationWarnings: string[];\n validationWarnings: string[];\n }>(\"chain.createEntry\", {\n collectionSlug: COLLECTION_SLUG,\n entryId: seed.entryId,\n name: seed.name,\n status: seed.status,\n data: seed.data,\n order: seed.order ?? 0,\n });\n if (createResult.normalizationWarnings.length > 0 || createResult.validationWarnings.length > 0) {\n allWarnings.push({\n entryId: seed.entryId,\n normalizationWarnings: createResult.normalizationWarnings,\n validationWarnings: createResult.validationWarnings,\n });\n }\n created++;\n }\n\n let responseText = `# Architecture Seeded\\n\\n**Created:** ${created} entries\\n**Updated:** ${updated} (merged new fields)\\n**Unchanged:** ${unchanged}\\n\\nUse \\`architecture action=show\\` to view the map.`;\n\n if (allWarnings.length > 0) {\n responseText += '\\n\\n---\\n\\n⚠️ **Seed warnings:**';\n for (const w of allWarnings) {\n for (const nw of w.normalizationWarnings) {\n responseText += `\\n - **${w.entryId}** (normalization): ${nw}`;\n }\n for (const vw of w.validationWarnings) {\n responseText += `\\n - **${w.entryId}** (validation): ${vw}`;\n }\n }\n }\n\n return {\n content: [{\n type: \"text\" as const,\n text: responseText,\n }],\n structuredContent: success(\n `Architecture seeded: ${created} created, ${updated} updated, ${unchanged} unchanged.`,\n { created, updated, unchanged },\n [{ tool: \"architecture\", description: \"View the map\", parameters: { action: \"show\" } }],\n ),\n };\n }\n\n if (action === \"check\") {\n const projectRoot = resolveProjectRoot();\n if (!projectRoot) {\n return {\n content: [{\n type: \"text\" as const,\n text: \"# Scan Failed\\n\\nCannot find project root (looked for `convex/schema.ts` in cwd and parent). \" +\n \"Set `WORKSPACE_PATH` env var to the absolute path of the Product OS project root.\",\n }],\n structuredContent: failure(\n \"VALIDATION_ERROR\",\n \"Cannot find project root.\",\n \"Set WORKSPACE_PATH env var to the absolute path of the Product OS project root.\",\n ),\n };\n }\n\n await ensureCollection();\n const all = await listArchEntries();\n const layers = byTag(all, \"layer\");\n const nodes = byTag(all, \"node\");\n\n const result = scanDependencies(projectRoot, layers, nodes);\n\n return {\n content: [{ type: \"text\" as const, text: formatScanReport(result) }],\n structuredContent: success(\n result.violations.length === 0\n ? `Health check passed: 0 violations across ${result.filesScanned} files.`\n : `Health check found ${result.violations.length} violation(s) across ${result.filesScanned} files.`,\n {\n violations: result.violations.length,\n filesScanned: result.filesScanned,\n importsChecked: result.importsChecked,\n unmappedImports: result.unmappedImports,\n },\n ),\n };\n }\n\n return unknownAction(action, [\"seed\", \"check\"]);\n })\n );\n trackWriteTool(archAdminTool);\n } // end PB_INTERNAL gate\n}\n\n// ── Scanner Engine — FEAT-dep-health, enforces SOS-dbl1n9 (dependency direction) ──\n\ninterface Violation {\n sourceNode: string;\n sourceLayer: string;\n sourceFile: string;\n importPath: string;\n targetNode: string;\n targetLayer: string;\n rule: string;\n}\n\ninterface ScanResult {\n violations: Violation[];\n filesScanned: number;\n importsChecked: number;\n unmappedImports: number;\n nodeResults: Map<string, { violations: Violation[]; filesScanned: number }>;\n}\n\nfunction scanDependencies(\n projectRoot: string,\n layers: ArchEntry[],\n nodes: ArchEntry[],\n): ScanResult {\n const layerMap = new Map<string, ArchEntry>();\n for (const l of layers) layerMap.set(l.entryId, l);\n\n const allowedDeps = buildAllowedDeps(layers);\n const nodePathPrefixes = buildNodePrefixes(nodes);\n\n const violations: Violation[] = [];\n const nodeResults = new Map<string, { violations: Violation[]; filesScanned: number }>();\n let totalFiles = 0;\n let totalImports = 0;\n let unmapped = 0;\n\n for (const node of nodes) {\n const layerRef = String(node.data?.layerRef ?? \"\");\n const layer = layerMap.get(layerRef);\n if (!layer) continue;\n\n const filePaths = parseFilePaths(node);\n const nodeViolations: Violation[] = [];\n let nodeFileCount = 0;\n\n for (const fp of filePaths) {\n const absPath = resolve(projectRoot, fp);\n const files = collectFiles(absPath);\n\n for (const file of files) {\n nodeFileCount++;\n totalFiles++;\n const relFile = relative(projectRoot, file);\n const imports = parseImports(file);\n\n for (const imp of imports) {\n totalImports++;\n const resolved = resolveImport(imp, file, projectRoot);\n if (!resolved) { unmapped++; continue; }\n\n const targetNode = findNodeByPath(resolved, nodePathPrefixes);\n if (!targetNode) { unmapped++; continue; }\n\n const targetLayerRef = String(targetNode.data?.layerRef ?? \"\");\n const targetLayer = layerMap.get(targetLayerRef);\n if (!targetLayer) continue;\n\n if (targetLayerRef === layerRef) continue;\n\n const allowed = allowedDeps.get(layerRef);\n if (allowed && !allowed.has(targetLayerRef)) {\n const v: Violation = {\n sourceNode: node.name,\n sourceLayer: layer.name,\n sourceFile: relFile,\n importPath: imp,\n targetNode: targetNode.name,\n targetLayer: targetLayer.name,\n rule: `${layer.name} cannot import from ${targetLayer.name}`,\n };\n violations.push(v);\n nodeViolations.push(v);\n }\n }\n }\n }\n\n nodeResults.set(node.entryId, { violations: nodeViolations, filesScanned: nodeFileCount });\n }\n\n return { violations, filesScanned: totalFiles, importsChecked: totalImports, unmappedImports: unmapped, nodeResults };\n}\n\nfunction buildAllowedDeps(layers: ArchEntry[]): Map<string, Set<string>> {\n const nameToId = new Map<string, string>();\n for (const l of layers) nameToId.set(l.name.toLowerCase(), l.entryId);\n\n const allowed = new Map<string, Set<string>>();\n for (const layer of layers) {\n const deps = String(layer.data?.dependsOn ?? \"none\");\n const set = new Set<string>();\n if (deps !== \"none\") {\n for (const dep of deps.split(\",\").map((d) => d.trim().toLowerCase())) {\n const id = nameToId.get(dep);\n if (id) set.add(id);\n }\n }\n allowed.set(layer.entryId, set);\n }\n return allowed;\n}\n\nfunction buildNodePrefixes(nodes: ArchEntry[]): { prefix: string; node: ArchEntry }[] {\n const entries: { prefix: string; node: ArchEntry }[] = [];\n for (const node of nodes) {\n for (const fp of parseFilePaths(node)) {\n entries.push({ prefix: normalize(fp), node });\n }\n }\n entries.sort((a, b) => b.prefix.length - a.prefix.length);\n return entries;\n}\n\nfunction parseFilePaths(node: ArchEntry): string[] {\n const raw = node.data?.filePaths;\n if (!raw || typeof raw !== \"string\") return [];\n return raw.split(\",\").map((p) => p.trim()).filter(Boolean);\n}\n\nfunction collectFiles(absPath: string): string[] {\n if (!existsSync(absPath)) return [];\n const stat = statSync(absPath);\n if (stat.isFile()) {\n return isScannableFile(absPath) ? [absPath] : [];\n }\n if (!stat.isDirectory()) return [];\n\n const results: string[] = [];\n const walk = (dir: string) => {\n for (const entry of readdirSync(dir, { withFileTypes: true })) {\n if (entry.name.startsWith(\".\") || entry.name === \"node_modules\") continue;\n const full = resolve(dir, entry.name);\n if (entry.isDirectory()) walk(full);\n else if (isScannableFile(full)) results.push(full);\n }\n };\n walk(absPath);\n return results;\n}\n\nfunction isScannableFile(p: string): boolean {\n return /\\.(ts|js|svelte)$/.test(p) && !p.endsWith(\".d.ts\");\n}\n\nfunction parseImports(filePath: string): string[] {\n try {\n const content = readFileSync(filePath, \"utf-8\");\n const re = /(?:^|\\n)\\s*import\\s+(?:[\\s\\S]*?\\s+from\\s+)?['\"]([^'\"]+)['\"]/g;\n const imports: string[] = [];\n let match: RegExpExecArray | null;\n while ((match = re.exec(content)) !== null) {\n imports.push(match[1]);\n }\n return imports;\n } catch {\n return [];\n }\n}\n\nconst EXTENSIONS = [\".ts\", \".js\", \".svelte\", \"/index.ts\", \"/index.js\", \"/index.svelte\"];\n\nfunction tryResolveWithExtension(absPath: string): string | null {\n if (existsSync(absPath) && statSync(absPath).isFile()) return absPath;\n for (const ext of EXTENSIONS) {\n const withExt = absPath + ext;\n if (existsSync(withExt)) return withExt;\n }\n return null;\n}\n\nfunction resolveImport(imp: string, fromFile: string, root: string): string | null {\n let rel: string | null = null;\n if (imp.startsWith(\"$lib/\")) rel = imp.replace(\"$lib/\", \"src/lib/\");\n else if (imp.startsWith(\"$convex/\")) rel = imp.replace(\"$convex/\", \"convex/\");\n else if (imp.startsWith(\"$env/\") || imp.startsWith(\"$app/\")) return null;\n else if (imp.startsWith(\"./\") || imp.startsWith(\"../\")) {\n const fromDir = dirname(fromFile);\n const abs = resolve(fromDir, imp);\n rel = relative(root, abs);\n }\n if (!rel) return null;\n\n const abs = resolve(root, rel);\n const actual = tryResolveWithExtension(abs);\n return actual ? relative(root, actual) : rel;\n}\n\nfunction findNodeByPath(\n filePath: string,\n prefixes: { prefix: string; node: ArchEntry }[],\n): ArchEntry | null {\n const normalized = normalize(filePath);\n for (const { prefix, node } of prefixes) {\n if (normalized.startsWith(prefix)) return node;\n }\n return null;\n}\n\nfunction formatScanReport(result: ScanResult): string {\n const lines: string[] = [];\n\n if (result.violations.length === 0) {\n lines.push(\n `# Architecture Health Check Passed`,\n \"\",\n `**0 violations** across ${result.filesScanned} files (${result.importsChecked} imports checked, ${result.unmappedImports} unmapped).`,\n \"\",\n \"All imports respect the layer dependency rules.\",\n );\n } else {\n lines.push(\n `# Architecture Health Check — ${result.violations.length} Violation${result.violations.length === 1 ? \"\" : \"s\"}`,\n \"\",\n `Scanned ${result.filesScanned} files, checked ${result.importsChecked} imports, found **${result.violations.length} violation${result.violations.length === 1 ? \"\" : \"s\"}** (${result.unmappedImports} unmapped).`,\n \"\",\n );\n\n const byNode = new Map<string, Violation[]>();\n for (const v of result.violations) {\n if (!byNode.has(v.sourceNode)) byNode.set(v.sourceNode, []);\n byNode.get(v.sourceNode)!.push(v);\n }\n\n for (const [nodeName, vs] of byNode) {\n lines.push(`## ${nodeName} (${vs[0].sourceLayer})`);\n for (const v of vs) {\n lines.push(`- \\`${v.sourceFile}\\` imports \\`${v.importPath}\\` → **${v.targetNode}** (${v.targetLayer}) — ${v.rule}`);\n }\n lines.push(\"\");\n }\n }\n\n lines.push(\"---\", \"\");\n\n const nodeEntries = [...result.nodeResults.entries()];\n const cleanCount = nodeEntries.filter(([, r]) => r.violations.length === 0 && r.filesScanned > 0).length;\n const dirtyCount = nodeEntries.filter(([, r]) => r.violations.length > 0).length;\n const emptyCount = nodeEntries.filter(([, r]) => r.filesScanned === 0).length;\n\n lines.push(\n `**Summary:** ${cleanCount} clean nodes, ${dirtyCount} with violations, ${emptyCount} with no files.`,\n );\n\n return lines.join(\"\\n\");\n}\n","/**\n * Orient tool — workspace orientation and session bootstrapping.\n *\n * Extracted from health.ts to isolate the orient tool registration\n * into its own module. The orient handler is the primary entry point\n * for agents to load workspace context, governance, and active work.\n */\nimport { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { z } from \"zod\";\nimport { kernelQuery, kernelMutation, kernelCall, getWorkspaceContext, getAgentSessionId, setSessionOriented, isSessionOriented, type WorkspaceContext } from \"../client.js\";\nimport { trackWriteBackHintServed } from \"../analytics.js\";\nimport { success, thinWrapper } from \"../envelope.js\";\nimport { buildPlannedWork, hasPlannedWork, buildPlannedWorkSection, formatRecoveryBlock, type PriorSession } from \"./planned-work.js\";\nimport {\n runAlignmentCheck,\n buildAlignmentCheckLines,\n buildOperatingProtocol,\n buildCoherenceSection,\n buildDocCompletenessSection,\n formatInitiativeStatusLines,\n formatWorkstreamHealthLines,\n formatWhatNeedsAttentionLines,\n formatWhatNeedsAttentionBrief,\n formatBetConstellationLines,\n type CoherenceSnapshot,\n type CollectionDocFields,\n} from \"./orient-shared.js\";\nimport { formatTopGapPrompt, formatGapOneLiner, type ReadinessGap, type GapContext } from \"../lib/gapToPrompt.js\";\n\n/** Must match PURPOSE_GAP_PREFIX in convex/lib/constants.ts — kept in sync manually. */\nconst PURPOSE_GAP_PREFIX = \"purpose-gap-\";\n\ntype BudgetFlags = {\n advisory?: boolean;\n warning?: boolean;\n emergencyCapped?: boolean;\n truncated?: boolean;\n overflowed?: boolean;\n breachTier?: \"none\" | \"advisory\" | \"warning\" | \"emergency\";\n queryName?: string;\n attribution?: { feature?: string; route?: string };\n};\n\n/**\n * WP-376 α.3: measure assembled MCP tool output bytes for orient and report\n * fire-and-forget to the gateway. The number captured here is the byte size\n * of the full MCP `tool_result` payload (content array JSON-serialized) — the\n * surface-side counterpart to the gateway's envelope-bytes measurement.\n *\n * Errors are swallowed: observability must never block the orient response or\n * affect the user-visible output. The gateway resolves workspaceId / apiKeyId\n * from the API-key context (BR-18 + injectSessionAuth).\n *\n * Skipped when `truncated` cannot be determined AND no orient view returned\n * (e.g. the early `Already oriented` return path with no orient data).\n */\nfunction reportOrientWrapperBytes(\n toolResult: { content: Array<{ type: string; text: string }>; structuredContent?: unknown },\n truncated: boolean,\n): void {\n try {\n const fullToolOutput = JSON.stringify({ content: toolResult.content ?? [] });\n const bytes = Buffer.byteLength(fullToolOutput, \"utf8\");\n void kernelMutation(\"agent.reportOrientMetric\", { bytes, truncated }).catch(() => {\n // Best-effort observability — silently swallow.\n });\n } catch {\n // Even building the byte count failed (e.g. circular structuredContent in\n // an unexpected shape) — never let it surface to the caller.\n }\n}\n\n/**\n * Mark session oriented in Convex. If persistence fails with an optional coherence snapshot\n * (schema drift / validation), retry without it so orientation can still complete.\n */\nasync function markOrientedWithSnapshotFallback(\n agentSessionId: string,\n coherenceSnapshot?: CoherenceSnapshot,\n): Promise<boolean> {\n try {\n await kernelCall(\"agent.markOriented\", {\n sessionId: agentSessionId,\n ...(coherenceSnapshot ? { coherenceSnapshot } : {}),\n });\n setSessionOriented(true);\n return true;\n } catch {\n if (!coherenceSnapshot) return false;\n try {\n await kernelCall(\"agent.markOriented\", { sessionId: agentSessionId });\n setSessionOriented(true);\n return true;\n } catch {\n return false;\n }\n }\n}\n\n/**\n * Extract entry IDs from prior sessions for contextual priming.\n * - all: deduplicated from all sessions, capped at 10 (for scoring)\n * - lastSessionOnly: from most recent session only, capped at 5 (for temporal thread)\n */\nfunction extractSessionEntryIds(priorSessions: PriorSession[]): {\n all: string[];\n lastSessionOnly: string[];\n} {\n const allSeen = new Set<string>();\n const all: string[] = [];\n let lastSessionOnly: string[] = [];\n for (let i = 0; i < priorSessions.length; i++) {\n const s = priorSessions[i];\n const created = Array.isArray(s.entriesCreated) ? s.entriesCreated : [];\n const modified = Array.isArray(s.entriesModified) ? s.entriesModified : [];\n const ids = [...created, ...modified].filter((id): id is string => typeof id === \"string\" && id.length > 0);\n if (i === 0) {\n lastSessionOnly = [...new Set(ids)].slice(0, 5);\n }\n for (const id of ids) {\n if (!allSeen.has(id)) {\n allSeen.add(id);\n all.push(id);\n if (all.length >= 10) break;\n }\n }\n if (all.length >= 10) break;\n }\n return { all, lastSessionOnly };\n}\n\n/**\n * SYNC: Must match TaskDomain in convex/agentKnowledge/startupResolver.ts.\n * These are maintained as separate lists because the MCP server package\n * cannot import directly from the Convex package.\n */\nconst VALID_TASK_DOMAINS = [\n \"auth\",\n \"strategy\",\n \"governance\",\n \"architecture\",\n \"product\",\n \"product-design\",\n \"product-design/ux\",\n \"engineering\",\n \"engineering/frontend\",\n \"engineering/backend\",\n \"data\",\n \"data/analytics\",\n \"go-to-market\",\n \"go-to-market/sales\",\n \"strategy/outcomes\",\n \"product/roadmap\",\n \"governance/principles\",\n \"data-foundation\",\n \"chainwork\",\n \"capture-pipeline\",\n \"ingestion\",\n \"intelligence-and-operations\",\n \"review-and-learning\",\n \"general\",\n] as const;\n\nexport const orientSchema = z.object({\n mode: z.enum([\"full\", \"brief\"]).optional().default(\"full\").describe(\"full = full context (default). brief = compact summary for mid-session re-orientation. Prefer using the `tier` param for depth control.\"),\n tier: z.enum([\"summary\", \"standard\", \"full\"]).optional().describe(\n \"Payload depth. summary = ~10 KB compact. standard = ~256 KB default. full = complete payload (large). Defaults to standard.\",\n ),\n task: z.string().optional().describe(\"Natural-language task description for task-scoped context. When provided, orient returns scored, relevant entries for the task.\"),\n scope: z.enum(VALID_TASK_DOMAINS).optional().describe(`Optional domain scope to filter governance to entries relevant for this domain. Valid values: ${VALID_TASK_DOMAINS.join(\", \")}.`),\n});\n\nfunction taskGroundingWarningLines(task?: string, hasTaskGrounding = false): string[] {\n if (hasTaskGrounding) return [];\n if (task) {\n return [\n \"## Task grounding incomplete\",\n \"_A task was provided, but task-scoped governance/context did not load. Write tools stay locked until the task produces grounded context._\",\n \"\",\n 'Refine the task and rerun `orient task=\"describe the work\"` or use `context action=\"gather\"` for deeper task context.',\n \"\",\n ];\n }\n return [\n \"## Task grounding required\",\n \"_This is workspace orientation only. Do not start implementation, review, diagnosis, auth, security, or governance-sensitive work until you run task-shaped orient._\",\n \"\",\n 'Run `orient task=\"describe the work\"` to load binding governance and supporting context for the actual task.',\n \"\",\n ];\n}\n\nexport function registerOrientTool(server: McpServer) {\n server.registerTool(\n \"orient\",\n {\n title: \"Orient — Start Here\",\n description:\n \"The single entry point for starting a session. Returns workspace context with a \" +\n \"single recommended next action for low-readiness workspaces, or a standup-style \" +\n \"briefing for established workspaces.\\n\\n\" +\n \"Use this FIRST. One call to orient replaces 3–5 individual tool calls.\\n\\n\" +\n \"Completing orientation unlocks write tools for the active session.\\n\\n\" +\n \"**tier:** Controls payload depth. `standard` (default, ~256 KB) is the recommended default. `summary` (~10 KB) for quick mid-session re-orientation. `full` for complete payload when deep context is needed.\\n\\n\" +\n \"**mode:** `full` (default) returns full context. `brief` returns compact summary — mapped to tier=summary internally. Prefer `tier` for explicit depth control.\\n\\n\" +\n \"**task:** Optional natural-language task description. When provided, returns task-scoped context (scored, relevant entries) in addition to standard orient sections.\\n\\n\" +\n \"**scope:** Optional domain scope. Filters governance entries to those relevant for the specified domain. Authority roots include strategy, product, product-design, engineering, architecture, data, governance, and go-to-market. Child scopes such as product-design/ux, engineering/frontend, data/analytics, and governance/principles are accepted. Legacy internal scopes remain accepted.\",\n inputSchema: orientSchema,\n annotations: { readOnlyHint: true, idempotentHint: true, openWorldHint: false },\n },\n thinWrapper(async ({ mode = \"full\", tier, task, scope }) => {\n const errors: string[] = [];\n // BET-β S3b: resolve effective tier. Explicit `tier` param overrides mode mapping.\n // mode='brief' maps to tier='summary'; mode='full' (default) maps to tier='standard'.\n const effectiveTier: 'summary' | 'standard' | 'full' =\n tier ?? (mode === 'brief' ? 'summary' : 'standard');\n\n // BET-279: --scope without --task is a silent no-op — warn the caller.\n if (scope && !task) {\n errors.push(\"--scope requires --task to filter governance. Scope was ignored.\");\n }\n const agentSessionId = getAgentSessionId();\n\n if (isSessionOriented() && mode === \"brief\" && !task) {\n return {\n content: [{\n type: \"text\" as const,\n text:\n \"Already oriented. Session active, writes unlocked.\\n\\n\" +\n taskGroundingWarningLines().join(\"\\n\") +\n \"Use `orient mode='full'` for workspace context or `orient task='...'` before substantive work.\",\n }],\n structuredContent: success(\n \"Already oriented. Session active, writes unlocked.\",\n {\n alreadyOriented: true,\n sessionId: agentSessionId,\n taskGroundingStatus: \"workspace_only\",\n taskGroundingRequired: true,\n nextStep: 'Run `orient task=\"describe the work\"` before substantive work.',\n },\n ),\n };\n }\n\n let wsCtx: WorkspaceContext | null = null;\n try {\n wsCtx = await getWorkspaceContext();\n } catch (e: unknown) {\n errors.push(`Workspace: ${e instanceof Error ? e.message : String(e)}`);\n }\n\n let priorSessions: PriorSession[] = [];\n let recoveryBlock: Record<string, unknown> | null = null;\n\n // TEN-1740: inline structural type covering fields MCP reads from OrientViewModel.\n // TODO: extract to a shared package once workspace/packages/shared-types exists.\n type MCPOrientView = {\n stage: string;\n _truncated?: boolean;\n _budget?: { bytes: number; truncated: boolean; truncationReasons: string[]; overflowed: boolean };\n strategicContext?: Record<string, unknown>;\n governance?: { principles: unknown[]; standards: unknown[]; businessRules: unknown[] };\n activeBets?: Array<{ entryId: string | null; _id?: string; name: string; origin?: string; linkedTensions?: Array<{ entryId: string | null; name: string; severity?: string; priority?: string }> }>; tensions?: unknown[]; architectureNotes?: unknown[]; proposals?: unknown[]; absenceSignals?: unknown[];\n startup?: { groundingStatus: string; confidence: string; totalFound: number; seeds: unknown[]; bindingGovernance: { principles: unknown[]; standards: unknown[]; businessRules: unknown[] }; domainRetrieval: Record<string, unknown>; steeringContext: unknown[]; supportingContext: unknown[]; taskProfile: { workType: string; domain: string; keywords: string[] } };\n taskContext?: { seeds: unknown[]; context: unknown[]; totalFound: number; confidence: string; constellationEntries?: Array<{ entryId: string | null; name: string; collectionSlug: string | null; canonicalKey: string | null }>; constellationBetName?: string };\n plannedWork?: { uncommittedDrafts: unknown[]; inProgressEntries: unknown[]; openTensions: unknown[] };\n priorSessions?: unknown[]; recoveryBlock?: Record<string, unknown> | null;\n writeBackHints?: Array<{ collectionSlug: string; hint: string }>;\n activeGoals?: unknown[]; strategyHighlights?: unknown[]; playingField?: unknown[];\n recentDecisions?: unknown[]; recentlySuperseded?: unknown[]; staleEntries?: unknown[];\n continuingFrom?: unknown[]; lastSessionTouched?: unknown[];\n initiativeStatus?: unknown[]; workstreamHealth?: unknown[];\n whatNeedsAttention?: { overdueBets: string[]; blockedBets: string[]; criticalPathBets: string[]; overdueOutcomeBlockers?: unknown[] };\n trustMetrics?: { verified: number; unverified: number; noStatus: number; total: number; scannedCap: boolean };\n stalenessThresholdDays?: number;\n };\n let orientView: MCPOrientView | null = null;\n try {\n const orientArgs: { task?: string; scope?: string; tier?: 'summary' | 'standard' | 'full' } = {};\n if (task) orientArgs.task = task;\n if (scope) orientArgs.scope = scope;\n orientArgs.tier = effectiveTier;\n orientView = await kernelQuery<MCPOrientView>(\"chain.getOrientView\", orientArgs);\n } catch { /* non-critical */ }\n\n if (orientView) {\n priorSessions = orientView.priorSessions ?? [];\n recoveryBlock = orientView.recoveryBlock ?? null;\n }\n const hasTaskGrounding = Boolean(task && orientView?.taskContext?.context?.length > 0);\n\n // WP-306 S3: Emit write_back_hint_served event (STD-155)\n if (wsCtx && hasTaskGrounding && orientView?.writeBackHints) {\n const hints = Array.isArray(orientView.writeBackHints) ? orientView.writeBackHints : [];\n if (hints.length > 0) {\n trackWriteBackHintServed(wsCtx.workspaceId, {\n hint_count: hints.length,\n has_task: !!task,\n });\n }\n }\n\n let openTensions: any[] = [];\n try {\n const tensions = await kernelQuery<any[]>(\"chain.listEntries\", { collectionSlug: \"tensions\" });\n openTensions = (tensions ?? []).filter((e: { workflowStatus?: string }) => e.workflowStatus === \"open\");\n } catch { /* non-critical */ }\n\n let allCollections: CollectionDocFields[] = [];\n try {\n allCollections = (await kernelQuery<CollectionDocFields[]>(\"chain.listCollections\")) ?? [];\n } catch { /* non-critical — doc-completeness section is optional */ }\n\n let readiness: any = null;\n try {\n readiness = await kernelQuery<any>(\"chain.workspaceReadiness\");\n } catch (e: unknown) {\n errors.push(`Readiness: ${e instanceof Error ? e.message : String(e)}`);\n }\n\n // BET-76 safety net: if workspace is blank, redirect to the start tool's\n // project scan flow. orient is kept for backward compat but start is the\n // correct entry point for fresh workspaces.\n if (readiness?.stage === \"blank\") {\n const scanLines = [\n `# Welcome to ${wsCtx?.workspaceName ?? \"your workspace\"}`,\n \"\",\n \"Your workspace is fresh — let's set it up.\",\n \"\",\n \"**Recommended:** call the `start` tool instead of `orient` for the best first-run experience.\",\n \"It will guide you through setting up your workspace — you can tell me about your product, scan your codebase, or use a preset.\",\n \"\",\n \"Or tell me about your product and I'll start capturing knowledge directly.\",\n ];\n\n // Blank workspaces still route into guided setup; mark oriented so start can proceed smoothly.\n let oriented = false;\n let orientationStatus: \"complete\" | \"failed\" | \"no_session\" = \"no_session\";\n if (agentSessionId) {\n try {\n await kernelCall(\"agent.markOriented\", { sessionId: agentSessionId });\n setSessionOriented(true);\n oriented = true;\n orientationStatus = \"complete\";\n } catch {\n orientationStatus = \"failed\";\n }\n }\n\n const blankResult = {\n content: [{ type: \"text\" as const, text: scanLines.join(\"\\n\") }],\n structuredContent: success(\n \"Workspace is blank. Use the start_pb tool for guided setup.\",\n { stage: \"blank\", readinessScore: readiness?.score ?? 0, oriented, orientationStatus, redirectHint: \"Use the `start_pb` tool for the full guided setup experience.\" },\n [{ tool: \"start_pb\", description: \"Guided workspace setup\", parameters: {} }],\n ),\n };\n // WP-376 α.3: blank workspaces don't run the truncatable orient view; treat as not truncated.\n reportOrientWrapperBytes(blankResult, false);\n return blankResult;\n }\n\n const lines: string[] = [];\n const isLowReadiness = readiness && readiness.score < 50;\n\n // --- Identity ---\n if (wsCtx) {\n lines.push(`# ${wsCtx.workspaceName}`);\n lines.push(`_Workspace \\`${wsCtx.workspaceSlug}\\` — Product Brain is healthy._`);\n } else {\n lines.push(\"# Workspace\");\n lines.push(\"_Could not resolve workspace._\");\n }\n lines.push(\"\");\n lines.push(...taskGroundingWarningLines(task, hasTaskGrounding));\n\n // --- Brief mode: compact output only ---\n if (mode === \"brief\") {\n const briefStage = readiness?.stage ?? (readiness?.score != null ? (readiness.score < 50 ? \"seeded\" : \"grounded\") : \"unknown\");\n lines.push(`Brain stage: ${briefStage}`);\n if (orientView?.strategicContext) {\n const sc = orientView.strategicContext;\n if (sc.vision) lines.push(`Vision: ${sc.vision}`);\n if (sc.purpose) lines.push(`Purpose: ${sc.purpose}`);\n if (sc.productAreaCount != null && sc.productAreaCount > 0) {\n lines.push(`Product areas (${sc.productAreaCount}): ${(sc.productAreas ?? []).join(\", \")}`);\n }\n if (sc.playingFieldCount != null && sc.playingFieldCount > 0) {\n lines.push(`Playing field (${sc.playingFieldCount}): ${(sc.playingField ?? []).join(\", \")}`);\n }\n lines.push(`${sc.activeBetCount} active bet(s), ${sc.activeTensionCount} tension(s).`);\n }\n if (orientView?.taskContext && orientView.taskContext.context.length > 0) {\n lines.push(`Task context: ${orientView.taskContext.totalFound} relevant entries (${orientView.taskContext.confidence} confidence).`);\n }\n if (orientView?.startup?.domainRetrieval) {\n const retrieval = orientView.startup.domainRetrieval;\n const scopedTo = retrieval.resolvedDomainSlug ? ` (${retrieval.resolvedDomainSlug})` : \"\";\n lines.push(`Domain retrieval: ${retrieval.state}${scopedTo}`);\n if (retrieval.activeSource) lines.push(`Active source: ${retrieval.activeSource}`);\n if (retrieval.fallbackReason) lines.push(`Fallback: ${retrieval.fallbackReason}`);\n if (retrieval.fallbackAction) lines.push(`Action: ${retrieval.fallbackAction}`);\n if (retrieval.evidenceGap) lines.push(`Evidence gap: ${retrieval.evidenceGap}`);\n if (retrieval.directRatifiedCount != null || retrieval.inheritedRatifiedCount != null || retrieval.orgFallbackCount != null) {\n lines.push(`Domain relation evidence: ${retrieval.directRatifiedCount ?? 0} direct, ${retrieval.inheritedRatifiedCount ?? 0} inherited, ${retrieval.orgFallbackCount ?? 0} org fallback`);\n }\n }\n if (orientView?.writeBackHints && orientView.writeBackHints.length > 0) {\n lines.push(\"\");\n lines.push(\"Write-back hints (what to capture this session):\");\n for (const h of orientView.writeBackHints) {\n lines.push(` ${h.collectionSlug}: ${h.hint}`);\n }\n }\n if (orientView?.activeBets?.length > 0) {\n for (const e of orientView.activeBets) {\n const tensions = e.linkedTensions;\n const tensionPart = tensions?.length\n ? ` — ${tensions.map((t) => `${t.entryId ?? t.name} (${t.severity ?? \"—\"})`).join(\", \")}`\n : \"\";\n const originPart = e.origin ? ` (origin: ${e.origin})` : \"\";\n lines.push(`- \\`${e.entryId ?? e._id}\\` ${e.name}${originPart}${tensionPart}`);\n }\n }\n // BET-240 S5: trust metrics in brief mode\n if (orientView?.trustMetrics) {\n const tm = orientView.trustMetrics;\n if (tm.unverified > 0 || tm.verified > 0) {\n const capNote = tm.scannedCap ? \"+\" : \"\";\n lines.push(`Trust: ${tm.verified} verified, ${tm.unverified} unverified, ${tm.noStatus} no-status (${tm.total}${capNote} scanned).`);\n }\n }\n // BET-126: compact What needs attention in brief mode\n const briefWna = formatWhatNeedsAttentionBrief(orientView?.whatNeedsAttention);\n if (briefWna.length > 0) {\n lines.push(\"\");\n lines.push(...briefWna);\n }\n // FEAT-62: surface top gap in brief mode\n const briefGaps: ReadinessGap[] = readiness?.gaps ?? [];\n if (briefGaps.length > 0) {\n const oneLiner = formatGapOneLiner(briefGaps[0]);\n if (oneLiner) lines.push(oneLiner);\n }\n const briefClassificationGaps = briefGaps.filter((g) => g.id?.startsWith?.(PURPOSE_GAP_PREFIX));\n if (briefClassificationGaps.length > 0) {\n lines.push(`${briefClassificationGaps.length} collection(s) with weak purpose — classification may be inaccurate.`);\n }\n if (recoveryBlock) {\n lines.push(\"\");\n lines.push(...formatRecoveryBlock(recoveryBlock as Parameters<typeof formatRecoveryBlock>[0]));\n } else if (priorSessions.length > 0) {\n const last = priorSessions[0];\n const date = last.startedAt ? new Date(last.startedAt).toISOString().split(\"T\")[0] : \"unknown\";\n const created = Array.isArray(last.entriesCreated) ? last.entriesCreated.length : last.entriesCreated ?? 0;\n const modified = Array.isArray(last.entriesModified) ? last.entriesModified.length : last.entriesModified ?? 0;\n lines.push(`Last session (${date}): ${created} created, ${modified} modified`);\n }\n let coherenceSnapshot: CoherenceSnapshot | undefined;\n const coherence = buildCoherenceSection();\n if (coherence) {\n lines.push(\"\");\n lines.push(...coherence.lines);\n coherenceSnapshot = coherence.snapshot;\n }\n\n if (allCollections.length > 0) {\n const docCompleteness = buildDocCompletenessSection(allCollections);\n if (docCompleteness.errorCount > 0 || docCompleteness.warningCount > 0) {\n lines.push(...docCompleteness.lines);\n }\n }\n\n if (orientView) {\n lines.push(\"\");\n if (task) {\n const mapGovernanceEntry = (e: any) => ({\n entryId: e.entryId,\n name: e.name,\n description: typeof e.preview === \"string\" ? e.preview : undefined,\n tier: typeof e.tier === \"number\" ? e.tier : undefined,\n });\n const gov = orientView.governance ?? { principles: [], standards: [], businessRules: [] };\n lines.push(...buildOperatingProtocol({\n principles: (gov.principles ?? []).map(mapGovernanceEntry),\n standards: (gov.standards ?? []).map(mapGovernanceEntry),\n businessRules: (gov.businessRules ?? []).map(mapGovernanceEntry),\n }, task));\n } else {\n lines.push(...buildOperatingProtocol());\n }\n }\n\n let orientationStatus: \"complete\" | \"task_required\" | \"failed\" | \"no_session\" = \"no_session\";\n if (agentSessionId && hasTaskGrounding) {\n const orientedOk = await markOrientedWithSnapshotFallback(agentSessionId, coherenceSnapshot);\n if (orientedOk) {\n orientationStatus = \"complete\";\n lines.push(\"---\");\n lines.push(`Orientation complete. Session ${agentSessionId}. Write tools available.`);\n } else {\n orientationStatus = \"failed\";\n lines.push(\"---\");\n lines.push(\"_Warning: Could not mark session as oriented. Write tools may be restricted._\");\n }\n } else if (agentSessionId) {\n orientationStatus = \"task_required\";\n lines.push(\"---\");\n lines.push('Workspace orientation loaded. Write tools stay locked until you run `orient task=\"describe the work\"`.');\n } else {\n lines.push(\"---\");\n lines.push(\"_No active agent session. Call `session action=start` to begin._\");\n }\n // BET-β S3b: prefer _budget.truncated; fall back to _truncated for backward compat.\n const briefTruncated = orientView?._budget?.truncated ?? orientView?._truncated ?? false;\n if (briefTruncated) {\n const reasons = orientView?._budget?.truncationReasons;\n lines.push(\"\");\n if (reasons && reasons.length > 0) {\n lines.push(`_Context truncated to fit tier budget: ${reasons.join(', ')}. Use tier=full for complete payload._`);\n } else {\n lines.push(\"_Context truncated to fit tier budget. Use tier=full for complete payload._\");\n }\n }\n if (errors.length > 0) {\n lines.push(\"\");\n for (const err of errors) lines.push(`- ${err}`);\n }\n const briefResult = {\n content: [{ type: \"text\" as const, text: lines.join(\"\\n\") }],\n structuredContent: success(\n `Oriented (brief). Stage: ${readiness?.stage ?? \"unknown\"}.`,\n {\n mode: \"brief\",\n stage: readiness?.stage ?? \"unknown\",\n oriented: hasTaskGrounding ? isSessionOriented() : false,\n sessionId: agentSessionId,\n taskGroundingStatus: hasTaskGrounding ? \"task_scoped\" : task ? \"missing_task_context\" : \"workspace_only\",\n taskGroundingRequired: !hasTaskGrounding,\n orientationStatus,\n nextStep: hasTaskGrounding ? undefined : 'Run `orient task=\"describe the work\"` before substantive work.',\n ...(orientView?._budget ? { _budget: orientView._budget } : {}),\n },\n ),\n };\n // WP-376 α.3: surface-side bytes — full assembled MCP tool output.\n reportOrientWrapperBytes(briefResult, briefTruncated);\n return briefResult;\n }\n\n const orientStage: string = readiness?.stage ?? \"seeded\";\n\n // --- Full mode: New vs neglected framing ---\n if (isLowReadiness && wsCtx?.createdAt) {\n const ageDays = Math.floor((Date.now() - wsCtx.createdAt) / (1000 * 60 * 60 * 24));\n if (ageDays >= 30) {\n lines.push(`Your workspace has been around for ${ageDays} days and is still at the **${orientStage}** stage.`);\n lines.push(\"Let's close the gaps — or if the current structure doesn't fit, we can reshape it.\");\n lines.push(\"\");\n }\n }\n // --- Single next action for low-readiness (FEAT-62: conversational gap prompts) ---\n let fullCoherenceSnapshot: CoherenceSnapshot | undefined;\n if (isLowReadiness) {\n const captureBehaviorNote =\n (readiness?.governanceMode ?? wsCtx?.governanceMode ?? \"open\") === \"open\"\n ? \"_In Open mode, captures commit automatically unless you ask me to keep them as drafts._\"\n : \"_Everything stays as a draft until you confirm._\";\n\n const gaps: ReadinessGap[] = readiness.gaps ?? [];\n if (gaps.length > 0) {\n const gapCtx: GapContext = {\n stage: orientStage,\n passedChecks: readiness.passedChecks ?? 0,\n totalChecks: readiness.totalChecks ?? 0,\n score: readiness.score ?? 0,\n };\n\n lines.push(formatTopGapPrompt(gaps[0], gaps.length - 1, gapCtx));\n lines.push(\"\");\n lines.push(captureBehaviorNote);\n lines.push(\"\");\n\n const remainingGaps = gaps.length - 1;\n if (remainingGaps > 0 || openTensions.length > 0) {\n const parts: string[] = [];\n if (remainingGaps > 0) parts.push(`${remainingGaps} more area${remainingGaps === 1 ? \"\" : \"s\"} to cover`);\n if (openTensions.length > 0) parts.push(`${openTensions.length} open tension${openTensions.length === 1 ? \"\" : \"s\"}`);\n lines.push(`_${parts.join(\" and \")} — ask for full status to see everything._`);\n lines.push(\"\");\n }\n }\n\n lines.push(\"_Need a collection that doesn't exist yet? Just ask — I'll set it up._\");\n lines.push(\"\");\n } else if (readiness) {\n const fmt = (e: any) => {\n const type = e.canonicalKey ?? 'generic';\n const stratum = e.stratum ?? '?';\n // BET-222 E3: show confidence + review overdue for decisions\n const confidencePart = e.confidence ? ` [confidence: ${e.confidence}]` : '';\n const reviewOverdue = e.reviewAt && new Date(e.reviewAt).getTime() < Date.now();\n const overduePart = reviewOverdue ? ' [review overdue]' : '';\n // BET-240 S0: surface origin for trust visibility\n const originPart = e.origin ? ` (origin: ${e.origin})` : '';\n return `- \\`${e.entryId ?? e._id}\\` [${type} · ${stratum}] ${e.name}${originPart}${confidencePart}${overduePart}`;\n };\n\n // BET-99 / FEAT-182: Codebase coherence check (runs once, shared across branches)\n const fullCoherence = buildCoherenceSection();\n if (fullCoherence) {\n fullCoherenceSnapshot = fullCoherence.snapshot;\n }\n\n if (task) {\n // ── FULL LAYER: task provided → rich, task-scoped context ──────────\n lines.push(`**Brain stage: ${orientStage}.** Working on: **${task}**`);\n lines.push(\"\");\n\n if (orientView?.strategicContext) {\n const sc = orientView.strategicContext;\n lines.push(\"## Strategic Context\");\n if (sc.vision) lines.push(`**Vision:** ${sc.vision}`);\n if (sc.purpose) lines.push(`**Purpose:** ${sc.purpose}`);\n if (sc.productAreaCount != null && sc.productAreaCount > 0) {\n lines.push(`**Product areas (${sc.productAreaCount}):** ${(sc.productAreas ?? []).join(\", \")}`);\n }\n if (sc.playingFieldCount != null && sc.playingFieldCount > 0) {\n lines.push(`**Playing field (${sc.playingFieldCount}):** ${(sc.playingField ?? []).join(\", \")}`);\n }\n const betLine = sc.currentBet\n ? `**Current bet:** ${sc.currentBet}. ${sc.activeBetCount} active bet(s).`\n : \"No active bets.\";\n lines.push(`${betLine} ${sc.activeTensionCount} open tension(s).`);\n lines.push(\"\");\n }\n\n if (orientView?.continuingFrom && orientView.continuingFrom.length > 0) {\n lines.push(\"## Continuing from\");\n lines.push(\"_Prior-session entries most relevant to your task._\");\n lines.push(\"\");\n for (const e of orientView.continuingFrom) {\n const id = e.entryId ?? e.name;\n const type = e.canonicalKey ?? \"generic\";\n const coll = e.collectionSlug ? ` [${e.collectionSlug}]` : \"\";\n lines.push(`- \\`${id}\\` (score ${e.score}) [${type}]${coll} — ${e.name}`);\n if (e.reasoning) lines.push(` _${e.reasoning}_`);\n if (\"primer\" in e && typeof e.primer === \"string\" && e.primer.length > 0) {\n const PRIMER_MAX = 1200;\n const primerText = e.primer.length > PRIMER_MAX\n ? e.primer.slice(0, PRIMER_MAX) + \"\\n… (truncated — use entries action=get for full primer)\"\n : e.primer;\n lines.push(\"\");\n lines.push(\" **Primer (paste when starting implementation):**\");\n lines.push(\" ```\");\n for (const line of primerText.split(\"\\n\")) lines.push(\" \" + line);\n lines.push(\" ```\");\n lines.push(\"\");\n }\n }\n lines.push(\"\");\n }\n\n if (orientView?.lastSessionTouched && orientView.lastSessionTouched.length > 0) {\n lines.push(\"## Last session touched\");\n lines.push(\"_Entries created or modified in your most recent session._\");\n lines.push(\"\");\n for (const e of orientView.lastSessionTouched) {\n const id = e.entryId ?? e.name;\n const type = e.canonicalKey ?? \"generic\";\n const coll = e.collectionSlug ? ` [${e.collectionSlug}]` : \"\";\n lines.push(`- \\`${id}\\` [${type}]${coll} — ${e.name}`);\n if (\"primer\" in e && typeof e.primer === \"string\" && e.primer.length > 0) {\n const PRIMER_MAX = 1200;\n const primerText = e.primer.length > PRIMER_MAX\n ? e.primer.slice(0, PRIMER_MAX) + \"\\n… (truncated — use entries action=get for full primer)\"\n : e.primer;\n lines.push(\"\");\n lines.push(\" **Primer:**\");\n lines.push(\" ```\");\n for (const line of primerText.split(\"\\n\")) lines.push(\" \" + line);\n lines.push(\" ```\");\n lines.push(\"\");\n }\n }\n lines.push(\"\");\n }\n\n if (orientView?.taskContext && orientView.taskContext.context.length > 0) {\n const tc = orientView.taskContext;\n lines.push(\"## Task Context\");\n if (orientView.startup?.domainRetrieval) {\n const retrieval = orientView.startup.domainRetrieval;\n const scopedTo = retrieval.resolvedDomainSlug ? ` (${retrieval.resolvedDomainSlug})` : \"\";\n lines.push(`_Domain retrieval: ${retrieval.state}${scopedTo}_`);\n if (retrieval.activeSource) lines.push(`_Active source: ${retrieval.activeSource}_`);\n if (retrieval.fallbackReason) lines.push(`_${retrieval.fallbackReason}_`);\n if (retrieval.fallbackAction) lines.push(`_${retrieval.fallbackAction}_`);\n if (retrieval.evidenceGap) lines.push(`_Evidence gap: ${retrieval.evidenceGap}_`);\n lines.push(\"\");\n }\n lines.push(`_Task-scoped entries (${tc.confidence} confidence, ${tc.totalFound} relevant)`);\n lines.push(\"\");\n for (const e of tc.context) {\n const id = e.entryId ?? e.name;\n const coll = e.collectionSlug ? ` [${e.collectionSlug}]` : \"\";\n const originTag = e.origin ? ` (origin: ${e.origin})` : \"\";\n lines.push(`- \\`${id}\\` (score ${e.score})${coll}${originTag}${e.name !== id ? ` — ${e.name}` : \"\"}`);\n if (e.preview) lines.push(` _${e.preview}_`);\n }\n lines.push(\"\");\n }\n\n if (orientView?.taskContext?.constellationEntries && orientView.taskContext.constellationEntries.length > 0) {\n lines.push(...formatBetConstellationLines(\n orientView.taskContext.constellationEntries,\n orientView.taskContext.constellationBetName,\n ));\n }\n\n if (orientView?.writeBackHints && orientView.writeBackHints.length > 0) {\n lines.push(\"\");\n lines.push(\"## Write-Back Hints\");\n lines.push(\"_What to capture this session (derived from task context):_\");\n lines.push(\"\");\n for (const h of orientView.writeBackHints) {\n lines.push(`- **${h.collectionSlug}**: ${h.hint}`);\n }\n lines.push(\"\");\n }\n\n if (orientView) {\n const result = await runAlignmentCheck(\n task,\n orientView.activeBets ?? [],\n orientView.taskContext?.context,\n );\n lines.push(...buildAlignmentCheckLines(result));\n // BET-126: Initiative Status, Workstream Health, What Needs Attention (full, with task)\n lines.push(...formatInitiativeStatusLines(orientView.initiativeStatus));\n lines.push(...formatWorkstreamHealthLines(orientView.workstreamHealth));\n lines.push(...formatWhatNeedsAttentionLines(orientView.whatNeedsAttention));\n // BET-240 S5: trust metrics (full, with task)\n if (orientView.trustMetrics) {\n const tm = orientView.trustMetrics;\n if (tm.verified > 0 || tm.unverified > 0) {\n const capNote = tm.scannedCap ? \" (capped at 500)\" : \"\";\n lines.push(\"## Trust metrics\");\n lines.push(`_Entry verification status across workspace${capNote}._`);\n lines.push(\"\");\n lines.push(`- **Verified:** ${tm.verified}`);\n lines.push(`- **Unverified:** ${tm.unverified}`);\n lines.push(`- **No status (pre-BET-240):** ${tm.noStatus}`);\n lines.push(`- **Total scanned:** ${tm.total}`);\n lines.push(\"\");\n }\n }\n }\n\n if (fullCoherence) {\n lines.push(...fullCoherence.lines);\n }\n\n if (allCollections.length > 0) {\n const docCompleteness = buildDocCompletenessSection(allCollections);\n if (docCompleteness.errorCount > 0 || docCompleteness.warningCount > 0) {\n lines.push(...docCompleteness.lines);\n }\n }\n\n if (orientView) {\n if (orientView.activeBets?.length > 0) {\n lines.push(\"## Active bets — current scope\");\n lines.push(\"_Work outside these bets requires explicit user confirmation._\");\n lines.push(\"\");\n for (const e of orientView.activeBets) {\n lines.push(fmt(e));\n const tensions = e.linkedTensions;\n if (tensions?.length) {\n const tensionLines = tensions.map((t) => {\n const meta = [t.severity, t.priority].filter(Boolean).join(\", \");\n return `\\`${t.entryId ?? t.name}\\` (${t.name}${meta ? `, ${meta}` : \"\"})`;\n });\n lines.push(` Tensions: ${tensionLines.join(\"; \")}`);\n }\n }\n lines.push(\"\");\n }\n if (orientView.activeGoals?.length > 0) {\n lines.push(\"## Active goals\");\n orientView.activeGoals.forEach((e) => lines.push(fmt(e)));\n lines.push(\"\");\n }\n if (orientView.strategyHighlights?.length > 0) {\n lines.push(\"## Strategy highlights\");\n lines.push(\"_One-sentence strategy, positioning, moat, business model, GTM — high-level strategic context._\");\n lines.push(\"\");\n orientView.strategyHighlights.forEach((e) => lines.push(fmt(e)));\n lines.push(\"\");\n }\n if (orientView.playingField?.length > 0) {\n lines.push(\"## Playing field\");\n lines.push(\"_Products and opportunities in the strategic landscape._\");\n lines.push(\"\");\n orientView.playingField.forEach((e) => lines.push(fmt(e)));\n lines.push(\"\");\n }\n if (orientView.recentDecisions?.length > 0) {\n lines.push(\"## Recent decisions\");\n orientView.recentDecisions.forEach((e) => lines.push(fmt(e)));\n lines.push(\"\");\n }\n if (orientView.recentlySuperseded?.length > 0) {\n lines.push(\"## Recently superseded\");\n orientView.recentlySuperseded.forEach((e) => lines.push(fmt(e)));\n lines.push(\"\");\n }\n if (orientView.staleEntries?.length > 0) {\n lines.push(\"## Needs confirmation\");\n lines.push(`_Domain stratum entries not confirmed in ${orientView.stalenessThresholdDays} days._`);\n orientView.staleEntries.forEach((e) => lines.push(fmt(e)));\n lines.push(\"\");\n }\n if (orientView.architectureNotes?.length > 0) {\n lines.push(\"## Architecture notes\");\n orientView.architectureNotes.forEach((e) => lines.push(fmt(e)));\n lines.push(\"\");\n }\n\n const mapGovernanceEntry = (e: any) => ({\n entryId: e.entryId,\n name: e.name,\n description: typeof e.preview === \"string\" ? e.preview : undefined,\n tier: typeof e.tier === \"number\" ? e.tier : undefined,\n });\n const gov = orientView.governance ?? { principles: [], standards: [], businessRules: [] };\n lines.push(...buildOperatingProtocol({\n principles: (gov.principles ?? []).map(mapGovernanceEntry),\n standards: (gov.standards ?? []).map(mapGovernanceEntry),\n businessRules: (gov.businessRules ?? []).map(mapGovernanceEntry),\n }, task));\n }\n\n let allEntries: any[] = [];\n try {\n allEntries = await kernelQuery<any[]>(\"chain.listEntries\", {}) ?? [];\n } catch { /* non-critical */ }\n\n const plannedWork = buildPlannedWork(allEntries);\n\n if (hasPlannedWork(plannedWork)) {\n lines.push(...buildPlannedWorkSection(plannedWork, priorSessions, recoveryBlock));\n } else if (recoveryBlock) {\n lines.push(...formatRecoveryBlock(recoveryBlock as Parameters<typeof formatRecoveryBlock>[0]));\n }\n } else {\n // ── COMPACT LAYER: no task → standup only ─────────────────────────\n // Identity + active bets + OP (compact) + session continuity + CTA.\n // Everything else loads on demand when agent states a task.\n lines.push(`**Brain stage: ${orientStage}.**`);\n lines.push(\"\");\n\n if (orientView?.activeBets?.length) {\n lines.push(\"## Active bets — current scope\");\n lines.push(\"_Work outside these bets requires explicit user confirmation._\");\n lines.push(\"\");\n for (const e of orientView.activeBets) {\n lines.push(fmt(e));\n }\n lines.push(\"\");\n }\n\n // BET-126: Initiative Status, Workstream Health, What Needs Attention (full, no task)\n lines.push(...formatInitiativeStatusLines(orientView?.initiativeStatus));\n lines.push(...formatWorkstreamHealthLines(orientView?.workstreamHealth));\n lines.push(...formatWhatNeedsAttentionLines(orientView?.whatNeedsAttention));\n\n // BET-240 S5: trust metrics (full, no task)\n if (orientView?.trustMetrics) {\n const tm = orientView.trustMetrics;\n if (tm.verified > 0 || tm.unverified > 0) {\n const capNote = tm.scannedCap ? \" (capped at 500)\" : \"\";\n lines.push(\"## Trust metrics\");\n lines.push(`_Entry verification status across workspace${capNote}._`);\n lines.push(\"\");\n lines.push(`- **Verified:** ${tm.verified}`);\n lines.push(`- **Unverified:** ${tm.unverified}`);\n lines.push(`- **No status (pre-BET-240):** ${tm.noStatus}`);\n lines.push(`- **Total scanned:** ${tm.total}`);\n lines.push(\"\");\n }\n }\n\n lines.push(...buildOperatingProtocol());\n\n if (fullCoherence) {\n lines.push(...fullCoherence.lines);\n }\n\n if (allCollections.length > 0) {\n const docCompleteness = buildDocCompletenessSection(allCollections);\n if (docCompleteness.errorCount > 0 || docCompleteness.warningCount > 0) {\n lines.push(...docCompleteness.lines);\n }\n }\n\n if (priorSessions.length > 0 && !recoveryBlock) {\n const last = priorSessions[0];\n const date = last.startedAt ? new Date(last.startedAt).toISOString().split(\"T\")[0] : \"unknown\";\n const created = Array.isArray(last.entriesCreated) ? last.entriesCreated.length : last.entriesCreated ?? 0;\n const modified = Array.isArray(last.entriesModified) ? last.entriesModified.length : last.entriesModified ?? 0;\n lines.push(`_Last session (${date}): ${created} created, ${modified} modified._`);\n lines.push(\"\");\n }\n\n if (recoveryBlock) {\n lines.push(...formatRecoveryBlock(recoveryBlock as Parameters<typeof formatRecoveryBlock>[0]));\n }\n\n lines.push(\"**What are you working on?** Tell me and I'll load relevant governance and context.\");\n lines.push(\"\");\n }\n }\n\n // --- Classification gaps (INS-116) ---\n const classificationGaps = readiness?.gaps?.filter((g: { id?: string }) => g.id?.startsWith?.(PURPOSE_GAP_PREFIX)) ?? [];\n if (classificationGaps.length > 0) {\n lines.push(\"## Classification gaps\");\n lines.push(\"_Collections with weak purpose — entry classification may be inaccurate._\");\n lines.push(\"\");\n for (const g of classificationGaps) {\n lines.push(`- ${(g as { label?: string }).label ?? g.id?.replace?.(\"purpose-gap-\", \"\") ?? \"unknown\"}`);\n }\n lines.push(\"\");\n }\n\n if (errors.length > 0) {\n lines.push(\"## Errors\");\n for (const err of errors) lines.push(`- ${err}`);\n lines.push(\"\");\n }\n\n // --- Mark session as oriented ---\n let orientationStatus: \"complete\" | \"task_required\" | \"failed\" | \"no_session\" = \"no_session\";\n if (agentSessionId && hasTaskGrounding) {\n const orientedOk = await markOrientedWithSnapshotFallback(agentSessionId, fullCoherenceSnapshot);\n if (orientedOk) {\n orientationStatus = \"complete\";\n\n lines.push(\"---\");\n lines.push(`Orientation complete. Session ${agentSessionId}. Write tools available.`);\n } else {\n orientationStatus = \"failed\";\n lines.push(\"---\");\n lines.push(\"_Warning: Could not mark session as oriented. Write tools may be restricted._\");\n }\n\n // Record session signal: orient was called (implicit feedback for the intelligence kernel)\n try {\n await kernelMutation(\"chain.recordSessionSignal\", {\n sessionId: agentSessionId,\n signalType: \"immediate_context_load\",\n metadata: { source: \"orient\" },\n });\n } catch (err) {\n process.stderr.write(`[MCP] recordSessionSignal failed: ${(err as Error).message}\\n`);\n // Non-fatal: orient still succeeds; signal is for analytics\n }\n } else if (agentSessionId) {\n orientationStatus = \"task_required\";\n lines.push(\"---\");\n lines.push('Workspace orientation loaded. Write tools stay locked until you run `orient task=\"describe the work\"`.');\n } else {\n lines.push(\"---\");\n lines.push(\"_No active agent session. Call `session action=start` to begin a tracked session._\");\n }\n\n // BET-β S3b: prefer _budget.truncated; fall back to _truncated for backward compat.\n const fullTruncated = orientView?._budget?.truncated ?? orientView?._truncated ?? false;\n if (fullTruncated) {\n const reasons = orientView?._budget?.truncationReasons;\n lines.push(\"\");\n if (reasons && reasons.length > 0) {\n lines.push(`_Context truncated to fit tier budget: ${reasons.join(', ')}. Use tier=full for complete payload._`);\n } else {\n lines.push(\"_Context truncated to fit tier budget. Use tier=full for complete payload._\");\n }\n }\n\n const fullResult = {\n content: [{ type: \"text\" as const, text: lines.join(\"\\n\") }],\n structuredContent: success(\n `Oriented (full). Stage: ${orientStage}. ${isLowReadiness ? \"Low readiness — gaps remain.\" : \"Ready.\"}`,\n {\n mode: \"full\",\n stage: orientStage,\n oriented: hasTaskGrounding ? isSessionOriented() : false,\n sessionId: agentSessionId,\n taskGroundingStatus: hasTaskGrounding ? \"task_scoped\" : task ? \"missing_task_context\" : \"workspace_only\",\n taskGroundingRequired: !hasTaskGrounding,\n domainRetrieval: orientView?.startup?.domainRetrieval,\n orientationStatus,\n nextStep: hasTaskGrounding ? undefined : 'Run `orient task=\"describe the work\"` before substantive work.',\n ...(orientView?._budget ? { _budget: orientView._budget } : {}),\n },\n ),\n };\n // WP-376 α.3: surface-side bytes — full assembled MCP tool output.\n reportOrientWrapperBytes(fullResult, fullTruncated);\n return fullResult;\n })\n );\n}\n","/**\n * `record_activation` MCP tool — chat-only activation receipt writer (WP-431\n * final pre-ship fix).\n *\n * Why this exists:\n * The pb-setup skill's Phase 5 needs a path for chat-only agents to call\n * `setup.recordActivationReceipt`. Before this tool, the skill body told\n * chat-only agents to use `commit-entry` — but `commit-entry` writes to the\n * `entries` table (chain.commitEntry), not to `setup_receipt`. That meant\n * chat-only users could reach Phase 5 readiness yet never write the\n * activation receipt, leaving KEY-32-chat unmeasurable and doneWhen #6 of\n * WP-431 violated for the chat-only surface.\n *\n * Contract:\n * - Caller passes the activation evidence (confirmedEntryCount,\n * entriesAcrossCollections, retrievalDemoConfirmed). The tool HARDCODES\n * `surfaceCapability='chat-only'` because this tool exists exclusively for\n * chat-only paths — CLI agents have shell access and call the gateway\n * directly. Allowing the caller to override surfaceCapability would defeat\n * the whole purpose of the dual-threshold KEY-32 metric.\n * - Calls `setup.recordActivationReceipt` via `kernelMutation` (which routes\n * through the AKI gateway with `injectSessionAuth: true`, mirroring how\n * S5's `start_pb` calls `setup.stampMcpOnlySurface`). The gateway injects\n * `apiKeyId | personId | clerkUserId` server-side; this tool never sees\n * identity material.\n * - Returns `{ activated, alreadyActivated, receiptId }` — the\n * `alreadyActivated` flag is forwarded directly from the mutation so\n * re-runs short-circuit cleanly (DEC-957 re-run-safe).\n */\n\nimport { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { z } from \"zod\";\nimport { kernelMutation } from \"../client.js\";\nimport { thinWrapper, success, textContent } from \"../envelope.js\";\n\nexport const recordActivationSchema = z.object({\n confirmedEntryCount: z\n .number()\n .int()\n .min(0)\n .describe(\n \"Confirmed-entry count from the Phase 4 capture loop. The mutation enforces >=10 (DEC-994).\",\n ),\n entriesAcrossCollections: z\n .number()\n .int()\n .min(0)\n .describe(\n \"Number of distinct collections those entries span. The mutation enforces >=2 (DEC-994 diversity soft-gate).\",\n ),\n retrievalDemoConfirmed: z\n .boolean()\n .describe(\n \"True if the BR-141 retrieval round-trip ran successfully in Phase 4. The mutation rejects false.\",\n ),\n});\n\ninterface RecordActivationResult {\n activated: boolean;\n alreadyActivated: boolean;\n receiptId: string | null;\n}\n\ninterface RecordActivationMutationResponse {\n alreadyActivated: boolean;\n receiptId: string;\n}\n\nexport function registerRecordActivationTools(server: McpServer) {\n server.registerTool(\n \"record_activation\",\n {\n title: \"Record activation receipt — chat-only\",\n description:\n \"Writes the per-user activation receipt that closes the WP-431 install-to-activation arc \" +\n \"for chat-only surfaces (Cursor Desktop, Claude Desktop, ChatGPT). The skill body's \" +\n \"Phase 5 calls this AFTER Phase 4 gates pass: confirmedEntryCount>=10, \" +\n \"entriesAcrossCollections>=2, retrievalDemoConfirmed=true. surfaceCapability is \" +\n \"hardcoded to 'chat-only' — this tool is NOT for CLI agents (CLI uses the gateway \" +\n \"directly). Idempotent: a re-run after activation returns alreadyActivated=true.\",\n inputSchema: recordActivationSchema,\n annotations: { readOnlyHint: false, idempotentHint: true, openWorldHint: false, destructiveHint: false },\n },\n thinWrapper(async ({ confirmedEntryCount, entriesAcrossCollections, retrievalDemoConfirmed }) => {\n const mutationResult = await kernelMutation<RecordActivationMutationResponse>(\n \"setup.recordActivationReceipt\",\n {\n surfaceCapability: \"chat-only\",\n confirmedEntryCount,\n entriesAcrossCollections,\n retrievalDemoConfirmed,\n },\n );\n\n const result: RecordActivationResult = {\n activated: true,\n alreadyActivated: mutationResult.alreadyActivated,\n receiptId: mutationResult.receiptId ?? null,\n };\n\n const summary = mutationResult.alreadyActivated\n ? \"Activation receipt already recorded — chat-only flow short-circuits.\"\n : \"Activation recorded — chat-only flow complete.\";\n\n return {\n content: textContent(summary),\n structuredContent: success(summary, result),\n };\n }),\n );\n}\n","/**\n * Audit tool — pb audit <BET-ID> as an MCP tool.\n *\n * BET-182 Slice 1: MCP tool wrapper around the auditBet Convex query.\n * Thin client — all gate logic lives in convex/agentKnowledge/audit.ts.\n *\n * Chain: BET-182, STD-113, STD-65 (structured output)\n */\n\nimport { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { z } from \"zod\";\nimport { kernelQuery, runWithToolContext } from \"../client.js\";\nimport { thinWrapper, success, failureResult, parseOrFail } from \"../envelope.js\";\n\n// ─── Schema ─────────────────────────────────────────────────────────────────\n\nconst AUDIT_ACTIONS = [\"run\"] as const;\n\nexport const auditSchema = z.object({\n action: z.enum(AUDIT_ACTIONS).describe(\n \"'run': run the STD-113 hygiene audit for a bet entry.\",\n ),\n entryId: z.string().describe(\"Bet entry ID to audit, e.g. 'BET-182'\"),\n phase: z.enum([\"shaping\", \"handoff\"]).default(\"shaping\").optional()\n .describe(\n \"'shaping': check shaping-phase fields only. 'handoff': check all required fields including buildContract/buildSequence/exclusions/risks. Default: shaping.\",\n ),\n});\n\n// ─── Output types (mirrors AuditOutput from convex/agentKnowledge/audit.ts) ───\n\ninterface GateResult {\n gate: string;\n status: \"pass\" | \"fail\" | \"warn\";\n blocking: boolean;\n detail: string;\n fix?: string;\n fixType?: \"exact\" | \"template\" | \"manual\";\n hint?: string;\n}\n\ninterface AuditResult {\n entryId: string;\n entryName: string;\n phase: string;\n clean: boolean;\n verdict: \"pass\" | \"fail\" | \"warn\";\n gates: GateResult[];\n summary: {\n total: number;\n passed: number;\n failed: number;\n warned: number;\n };\n elapsed_ms: number;\n}\n\n// ─── Tool registration ───────────────────────────────────────────────────────\n\nexport function registerAuditTools(server: McpServer): void {\n server.registerTool(\n \"audit\",\n {\n title: \"Audit\",\n description:\n \"Run STD-113 hygiene audit on a bet entry. Checks 13 gates (shaping) / 18 gates (handoff) covering:\\n\\n\" +\n \"- **Relations**: intentional links, no auto-link noise, strategic anchoring\\n\" +\n \"- **Risk/Tension**: risks in correct collection, tensions linked\\n\" +\n \"- **Field completeness**: mandatory fields populated for current phase\\n\" +\n \"- **Elements**: correct collection, committed status\\n\" +\n \"- **Acceptance criteria**: doneWhen populated and verifiable\\n\" +\n \"- **Structural**: no circular relations, appetite consistency\\n\\n\" +\n \"Use `phase=shaping` (default) before starting implementation. Use `phase=handoff` before handing off to AI Engineer.\",\n inputSchema: auditSchema,\n annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },\n },\n thinWrapper(async (args) => {\n const parsed = parseOrFail(auditSchema, args);\n if (!parsed.ok) return parsed.result;\n\n const { entryId, phase = \"shaping\" } = parsed.data;\n\n return runWithToolContext({ tool: \"audit\", action: \"run\" }, async () => {\n return handleAuditRun(entryId, phase ?? \"shaping\");\n });\n }),\n );\n}\n\n// ─── Handler ─────────────────────────────────────────────────────────────────\n\nasync function handleAuditRun(entryId: string, phase: \"shaping\" | \"handoff\") {\n let result: AuditResult;\n\n try {\n result = await kernelQuery<AuditResult>(\"chain.auditBet\", { entryId, phase });\n } catch (err: unknown) {\n const msg = err instanceof Error ? err.message : String(err);\n if (msg.includes(\"not found\") || msg.includes(\"NOT_FOUND\")) {\n return failureResult(\n `Entry '${entryId}' not found.`,\n \"NOT_FOUND\",\n `Entry '${entryId}' not found.`,\n \"Use entries action=search to find the correct BET-ID.\",\n [{ tool: \"entries\", description: \"Search entries\", parameters: { action: \"search\", query: entryId } }],\n );\n }\n throw err;\n }\n\n const { verdict, gates, summary, entryName, elapsed_ms } = result;\n\n // ── Format human-readable text ───────────────────────────────────────────\n const verdictIcon = verdict === \"pass\" ? \"✓\" : verdict === \"fail\" ? \"✗\" : \"⚠\";\n const verdictLabel = verdict.toUpperCase();\n\n const lines: string[] = [\n `## Audit: ${entryId} — ${entryName}`,\n `Phase: ${phase} | Verdict: ${verdictIcon} ${verdictLabel} | ${elapsed_ms}ms`,\n `Gates: ${summary.passed}/${summary.total} passed · ${summary.failed} failed · ${summary.warned} warned`,\n \"\",\n ];\n\n // Group by status for readability\n const failed = gates.filter((g) => g.status === \"fail\");\n const warned = gates.filter((g) => g.status === \"warn\");\n const passed = gates.filter((g) => g.status === \"pass\");\n\n if (failed.length > 0) {\n lines.push(\"### ✗ Failed Gates (blocking)\");\n for (const gate of failed) {\n lines.push(`**${gate.gate}**: ${gate.detail}`);\n if (gate.fix) lines.push(` → Fix: ${gate.fix}`);\n if (gate.hint) lines.push(` → Note: ${gate.hint}`);\n }\n lines.push(\"\");\n }\n\n if (warned.length > 0) {\n lines.push(\"### ⚠ Warnings (non-blocking)\");\n for (const gate of warned) {\n lines.push(`**${gate.gate}**: ${gate.detail}`);\n if (gate.fix) lines.push(` → Fix: ${gate.fix}`);\n if (gate.hint) lines.push(` → Note: ${gate.hint}`);\n }\n lines.push(\"\");\n }\n\n if (passed.length > 0 && verdict === \"pass\") {\n lines.push(\"### ✓ All Gates Passed\");\n for (const gate of passed) {\n lines.push(` ${gate.gate}: ${gate.detail}`);\n }\n } else if (passed.length > 0) {\n lines.push(`### ✓ Passed (${passed.length}): ${passed.map((g) => g.gate).join(\", \")}`);\n }\n\n // Next actions\n const nextActions = [];\n if (verdict !== \"pass\") {\n nextActions.push({\n tool: \"entries\",\n description: \"View full entry details\",\n parameters: { action: \"get\", entryId },\n });\n nextActions.push({\n tool: \"relations\",\n description: \"Manage entry relations\",\n parameters: { action: \"list\", entryId },\n });\n }\n\n return {\n content: [{ type: \"text\" as const, text: lines.join(\"\\n\") }],\n structuredContent: success(\n `Audit ${entryId} (${phase}): ${verdictLabel} — ${summary.passed}/${summary.total} gates passed.`,\n {\n entryId: result.entryId,\n entryName: result.entryName,\n phase: result.phase,\n clean: result.clean,\n verdict: result.verdict,\n gates: result.gates,\n summary: result.summary,\n elapsed_ms: result.elapsed_ms,\n },\n nextActions.length > 0 ? nextActions : undefined,\n ),\n };\n}\n","/**\n * Governance Proposals Tool — MCP surface for consent proposal lifecycle.\n *\n * Chain: BET-221 (Governance at Scale), BR-7 (async consent required),\n * TEN-967 (consent proposals only)\n *\n * Actions:\n * list — List open consent proposals with expiry countdown\n * respond — Approve or reject a proposal (with reason for rejections)\n * count — Count open proposals (for badge/notification)\n */\n\nimport { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { z } from \"zod\";\nimport { kernelQuery, kernelMutation, requireWriteAccess } from \"../client.js\";\nimport { trackWriteTool } from \"../tool-surface.js\";\nimport { thinWrapper, successResult, failureResult, validationResult } from \"../envelope.js\";\n\nconst governanceSchema = z.object({\n action: z.enum([\"list\", \"respond\", \"count\"])\n .describe(\"Action: list open proposals, respond to a proposal, or count open proposals\"),\n proposalId: z.string().optional()\n .describe(\"Proposal ID (required for respond action)\"),\n verdict: z.enum([\"approve\", \"reject\"]).optional()\n .describe(\"Verdict for respond action: approve or reject\"),\n reason: z.string().optional()\n .describe(\"Reason for the verdict (required when rejecting)\"),\n status: z.enum([\"open\", \"approved\", \"objected\", \"expired\"]).optional()\n .describe(\"Filter proposals by status (default: open). Only used with list action.\"),\n});\n\nexport function registerGovernanceTools(server: McpServer) {\n const tool = server.registerTool(\n \"governance-proposals\",\n {\n title: \"Governance Proposals\",\n description:\n \"Manage consent proposals — list open proposals awaiting review, respond with approve/reject, \" +\n \"or count open proposals. Consent proposals are created when a governs relation is proposed \" +\n \"and require explicit approval before the relation is created. \" +\n \"Use list to see what needs attention, respond to act on proposals, and count for badge display.\",\n inputSchema: governanceSchema,\n annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: false },\n },\n thinWrapper(async ({ action, proposalId, verdict, reason, status }) => {\n\n // DEC-701 Phase 2: bet-221-governance-at-scale flag deleted — governance proposals\n // always enabled. Workspace scoping happens inside kernelQuery / kernelMutation.\n\n // ── List action ───────────────────────────────────────────────────\n if (action === \"list\") {\n const proposals = await kernelQuery<any[]>(\"governance.listProposals\", {\n ...(status ? { status } : {}),\n });\n\n if (proposals.length === 0) {\n const statusLabel = status ?? \"open\";\n return successResult(\n `No ${statusLabel} consent proposals in this workspace.`,\n `No ${statusLabel} consent proposals found.`,\n { proposals: [], count: 0 },\n );\n }\n\n const lines: string[] = [\"# Consent Proposals\", \"\"];\n\n for (const p of proposals) {\n const urgency = p.isExpired\n ? \"EXPIRED\"\n : p.hoursRemaining < 1\n ? `< 1h remaining`\n : `${p.hoursRemaining}h remaining`;\n\n lines.push(`## ${p.targetEntryName} → ${p.toEntryName ?? \"unknown\"}`);\n lines.push(`- **ID:** \\`${p._id}\\``);\n lines.push(`- **Status:** ${p.status} (${urgency})`);\n lines.push(`- **Operation:** ${p.proposedOperation}`);\n lines.push(`- **Reasoning:** ${p.reasoning}`);\n lines.push(`- **Proposed by:** ${p.proposedBy}`);\n if (p.objectionReason) {\n lines.push(`- **Objection:** ${p.objectionReason}`);\n }\n lines.push(\"\");\n }\n\n return successResult(\n lines.join(\"\\n\"),\n `Found ${proposals.length} consent proposal(s).`,\n { proposals, count: proposals.length },\n [\n {\n tool: \"governance-proposals\",\n description: \"Respond to a proposal\",\n parameters: { action: \"respond\" },\n },\n ],\n );\n }\n\n // ── Count action ──────────────────────────────────────────────────\n if (action === \"count\") {\n const result = await kernelQuery<{ count: number }>(\"governance.countOpenProposals\");\n\n return successResult(\n result.count === 0\n ? \"No open consent proposals.\"\n : `${result.count} open consent proposal(s) awaiting review.`,\n `${result.count} open consent proposal(s).`,\n result,\n result.count > 0\n ? [{\n tool: \"governance-proposals\",\n description: \"List open proposals\",\n parameters: { action: \"list\" },\n }]\n : undefined,\n );\n }\n\n // ── Respond action ────────────────────────────────────────────────\n if (action === \"respond\") {\n requireWriteAccess();\n if (!proposalId) {\n return validationResult(\n \"A proposalId is required for the respond action. Use list action to find proposal IDs.\",\n );\n }\n if (!verdict) {\n return validationResult(\n \"A verdict (approve or reject) is required for the respond action.\",\n );\n }\n if (verdict === \"reject\" && !reason) {\n return validationResult(\n \"A reason is required when rejecting a proposal. Explain what harm this change would cause.\",\n );\n }\n\n try {\n const result = await kernelMutation<{ status: string; proposalId: string; message: string }>(\n \"governance.respondToProposal\",\n {\n proposalId,\n verdict,\n ...(reason ? { reason } : {}),\n },\n );\n\n return successResult(\n result.message,\n result.message,\n result,\n [\n {\n tool: \"governance-proposals\",\n description: \"List remaining proposals\",\n parameters: { action: \"list\" },\n },\n ],\n );\n } catch (err: any) {\n const msg = err?.message ?? String(err);\n return failureResult(\n msg,\n \"PROPOSAL_ERROR\",\n msg,\n \"Use governance-proposals action=list to check proposal status.\",\n [\n {\n tool: \"governance-proposals\",\n description: \"List proposals\",\n parameters: { action: \"list\" },\n },\n ],\n );\n }\n }\n\n return validationResult(\"Unknown action. Valid actions: list, respond, count.\");\n }),\n );\n trackWriteTool(tool);\n}\n","/**\n * Documents tool — MCP read surface for verified brief snapshots.\n *\n * WP-371 S4 (Seam Slice — agent surface side). Compound tool with action-enum\n * dispatch (BR-72 / STD-86). Currently exposes a single read action;\n * additional read actions (e.g. list-recent-verified, get-by-runId) can join\n * the same `documents` surface as the kernel grows.\n *\n * Read-only. v1.1 explicitly excludes any mutation from MCP — agents observe\n * the verification audit trail; they do not write to it.\n *\n * Workspace context is enforced by the HTTP gateway from the API key (BR-18).\n * The MCP tool never accepts or forwards a workspaceId — `kernelQuery`\n * injects it server-side.\n *\n * Chain: WP-371, BR-72 (compound action enum), STD-86 (compound tool standard),\n * BR-18 (gateway enforces workspace from credential), BR-150 (no slug branching).\n */\n\nimport { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { z } from \"zod\";\nimport { kernelQuery, runWithToolContext } from \"../client.js\";\nimport { thinWrapper, success, parseOrFail } from \"../envelope.js\";\n\n// ─── Schema ──────────────────────────────────────────────────────────────────\n\nconst DOCUMENTS_ACTIONS = [\"get-last-verified-brief\"] as const;\n\nexport const documentsSchema = z.object({\n action: z.enum(DOCUMENTS_ACTIONS).describe(\n \"'get-last-verified-brief': fetch the most recent verified brief snapshot for a (templateId, scopeKey) pair. Returns the verified summary so agents can build delta narratives ('since you last verified, X workstreams advanced').\",\n ),\n templateId: z.string().describe(\n \"Brief template identifier — currently 'steering-brief' is the only registered template.\",\n ),\n scopeKey: z.string().describe(\n \"Canonical scope key. Use 'workspace:<workspaceId>' for the full workspace brief, or 'initiative:<INI-ID>' for an initiative-scoped brief. The same formula is applied at write time (chainwork/docKernel/scopeKey.ts), so passing the wrong shape returns exists:false.\",\n ),\n});\n\n// ─── Output types (mirrors getLastVerifiedBrief return shape) ───────────────\n\ninterface VerifiedWorkstreamSnapshot {\n entryId: string;\n name: string;\n status: string;\n whatChanged: string;\n updatedAtAtVerify: number;\n}\n\ninterface VerifiedSummary {\n verifiedAtGlance: string;\n verifiedWorkstreams: VerifiedWorkstreamSnapshot[];\n citedEntryIds: string[];\n chainSyncedAt: number;\n verifiedAt: number;\n verifiedBy: string;\n}\n\n/**\n * Discriminated read result. Matches the chainwork query return shape exactly.\n * Agents key on `exists` first, then on `summary` presence to decide whether\n * a delta narrative is possible.\n */\ntype LastVerifiedBriefResult =\n | { exists: false }\n | {\n exists: true;\n summary: VerifiedSummary | undefined;\n verifiedAt: number;\n };\n\n// ─── Tool registration ──────────────────────────────────────────────────────\n\nexport function registerDocumentsTools(server: McpServer): void {\n server.registerTool(\n \"documents\",\n {\n title: \"Documents\",\n description:\n \"Read agent-facing snapshots of verified briefs.\\n\\n\" +\n \"**Actions:**\\n\" +\n \"- `get-last-verified-brief`: returns the most recent verified-brief snapshot for a (templateId, scopeKey) pair, including the at-a-glance markdown, workstream snapshots, cited entry IDs, and verification timestamp.\\n\\n\" +\n \"Use this to build delta narratives ('since the last verified brief on Tuesday, two workstreams advanced and one new tension was captured').\\n\\n\" +\n \"Returns `{ exists: false }` when no row matches. Returns `{ exists: true, summary: <snapshot>, verifiedAt }` when an S4 row is found, or `{ exists: true, summary: undefined, verifiedAt }` for legacy backfilled rows that pre-date snapshot capture.\",\n inputSchema: documentsSchema,\n annotations: {\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n },\n },\n thinWrapper(async (args) => {\n const parsed = parseOrFail(documentsSchema, args);\n if (!parsed.ok) return parsed.result;\n\n const { action, templateId, scopeKey } = parsed.data;\n\n // Single action today. Future actions on the `documents` surface\n // dispatch by the `action` discriminator (BR-72 compound action enum).\n return runWithToolContext({ tool: \"documents\", action }, () =>\n handleGetLastVerifiedBrief(templateId, scopeKey),\n );\n }),\n );\n}\n\n// ─── Handler ────────────────────────────────────────────────────────────────\n\nasync function handleGetLastVerifiedBrief(\n templateId: string,\n scopeKey: string,\n) {\n // kernelQuery injects workspaceId from the API-key context (BR-18).\n const result = await kernelQuery<LastVerifiedBriefResult>(\n \"chainwork.getLastVerifiedBrief\",\n { templateId, scopeKey },\n );\n\n if (!result.exists) {\n const text =\n `No verified brief found for template '${templateId}', scope '${scopeKey}'.\\n\\n` +\n `This is normal for a never-verified initiative or workspace. ` +\n `If you expected a row here, check that the scope key matches the format ` +\n `produced at write time: 'workspace:<workspaceId>' or 'initiative:<INI-ID>'.`;\n return {\n content: [{ type: \"text\" as const, text }],\n structuredContent: success(\n `No verified brief found for ${templateId} / ${scopeKey}.`,\n { exists: false },\n ),\n };\n }\n\n const verifiedAtIso = new Date(result.verifiedAt).toISOString();\n\n if (result.summary === undefined) {\n // Legacy backfilled row — no snapshot data was captured at write time.\n const text =\n `Verified brief found for template '${templateId}', scope '${scopeKey}', ` +\n `verified at ${verifiedAtIso}.\\n\\n` +\n `This row pre-dates snapshot capture (legacy backfill), so no summary is ` +\n `available. The verification timestamp itself is still authoritative — ` +\n `you can reason about staleness, just not delta narratives.`;\n return {\n content: [{ type: \"text\" as const, text }],\n structuredContent: success(\n `Legacy verified brief at ${verifiedAtIso} (no summary).`,\n { exists: true, summary: undefined, verifiedAt: result.verifiedAt },\n ),\n };\n }\n\n // Full S4 row with snapshot.\n const summary = result.summary;\n const lines: string[] = [\n `## Last verified brief — ${templateId} / ${scopeKey}`,\n `Verified at: ${verifiedAtIso} by ${summary.verifiedBy}`,\n `Chain synced at: ${new Date(summary.chainSyncedAt).toISOString()}`,\n \"\",\n `### At a glance (verbatim)`,\n summary.verifiedAtGlance || \"(empty)\",\n \"\",\n `### Workstreams at verification (${summary.verifiedWorkstreams.length})`,\n ];\n for (const ws of summary.verifiedWorkstreams) {\n lines.push(\n `- **${ws.entryId}** ${ws.name} — status: ${ws.status}` +\n (ws.whatChanged ? ` — ${ws.whatChanged}` : \"\"),\n );\n }\n if (summary.citedEntryIds.length > 0) {\n lines.push(\"\");\n lines.push(`### Cited entries (${summary.citedEntryIds.length})`);\n lines.push(summary.citedEntryIds.join(\", \"));\n }\n\n return {\n content: [{ type: \"text\" as const, text: lines.join(\"\\n\") }],\n structuredContent: success(\n `Verified brief found at ${verifiedAtIso} with ${summary.verifiedWorkstreams.length} workstream snapshot(s).`,\n {\n exists: true,\n summary,\n verifiedAt: result.verifiedAt,\n },\n ),\n };\n}\n","import { existsSync } from \"node:fs\";\nimport { dirname, join, resolve } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { McpServer, ResourceTemplate } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { kernelQuery, getWorkspaceContext } from \"../client.js\";\nimport { trackCaptureContractMiss } from \"../analytics.js\";\n\n/** MCP App View HTML bundles — served so Cursor/Claude can render tool UIs */\nconst UI_VIEWS: Record<string, string> = {\n \"ui://entries/entry-cards.html\": \"src/entry-cards/index.html\",\n \"ui://graph/constellation.html\": \"src/graph-constellation/index.html\",\n};\n\nexport const UI_RESOURCE_MIME_TYPE = \"text/html;profile=mcp-app\";\nconst MODULE_DIR = dirname(fileURLToPath(import.meta.url));\nconst UI_VIEW_BASE_CANDIDATES = [\n resolve(MODULE_DIR, \"views\"),\n resolve(MODULE_DIR, \"..\", \"views\"),\n resolve(MODULE_DIR, \"..\", \"..\", \"dist\", \"views\"),\n resolve(MODULE_DIR, \"..\", \"..\", \"..\", \"mcp-views\", \"dist\"),\n];\n\nexport function resolveUiViewPath(\n filePath: string,\n options?: {\n moduleDir?: string;\n pathExists?: (path: string) => boolean;\n },\n): string | null {\n const moduleDir = options?.moduleDir ?? MODULE_DIR;\n const pathExists = options?.pathExists ?? existsSync;\n const candidateBases = options?.moduleDir\n ? [\n resolve(moduleDir, \"views\"),\n resolve(moduleDir, \"..\", \"views\"),\n resolve(moduleDir, \"..\", \"..\", \"dist\", \"views\"),\n resolve(moduleDir, \"..\", \"..\", \"..\", \"mcp-views\", \"dist\"),\n ]\n : UI_VIEW_BASE_CANDIDATES;\n\n for (const candidateBase of candidateBases) {\n const candidatePath = join(candidateBase, filePath);\n if (pathExists(candidatePath)) {\n return candidatePath;\n }\n }\n\n return null;\n}\n\nfunction renderMissingUiView(uri: string): string {\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\" />\n <title>Product Brain View Unavailable</title>\n <style>\n body {\n margin: 0;\n padding: 20px;\n font-family: system-ui, sans-serif;\n background: #0f172a;\n color: #e2e8f0;\n }\n .panel {\n max-width: 720px;\n margin: 0 auto;\n padding: 20px;\n border: 1px solid #334155;\n border-radius: 12px;\n background: #111827;\n }\n h1 {\n margin: 0 0 12px;\n font-size: 18px;\n }\n p {\n margin: 0 0 10px;\n line-height: 1.5;\n }\n code {\n font-family: ui-monospace, SFMono-Regular, Menlo, monospace;\n color: #93c5fd;\n }\n </style>\n</head>\n<body>\n <main class=\"panel\">\n <h1>Product Brain view unavailable</h1>\n <p>The UI resource <code>${uri}</code> could not be loaded.</p>\n <p>If this is a local checkout, rebuild the MCP views bundle. If this is an installed package, the published package is missing its bundled views.</p>\n </main>\n</body>\n</html>`;\n}\n\n// ─── Response Types ──────────────────────────────────────────────────\n\ninterface EntryListItem {\n _id: string;\n entryId?: string;\n name: string;\n status: string;\n collectionName?: string;\n collectionSlug?: string;\n data?: Record<string, unknown>;\n}\n\ninterface EntryRelation {\n type: string;\n direction: \"outgoing\" | \"incoming\";\n otherEntryId: string | null;\n otherName: string | null;\n}\n\ninterface EntryDetail extends EntryListItem {\n relations?: EntryRelation[];\n labels?: Array<{ name: string; slug: string; color?: string }>;\n history?: Array<{ action: string; timestamp: number; actor?: string }>;\n}\n\ninterface Collection {\n _id: string;\n name: string;\n slug: string;\n description?: string;\n icon?: string;\n fields: Array<{ key: string; type: string; required?: boolean; searchable?: boolean }>;\n}\n\ninterface LabelRecord {\n _id: string;\n name: string;\n slug: string;\n color?: string;\n isGroup?: boolean;\n parentId?: string;\n}\n\ninterface CaptureContractField {\n key: string;\n required: boolean;\n type: string;\n helpText?: string;\n}\n\ninterface CaptureContractResult {\n collectionSlug: string;\n requiredFields: string[];\n allFields: CaptureContractField[];\n captureExpectation?: string;\n}\n\ninterface ContextResult {\n root: { entryId: string; name: string } | null;\n related?: Array<{\n entryId?: string;\n name: string;\n collectionName: string;\n relationType: string;\n relationDirection: string;\n hop: number;\n }>;\n totalRelations: number;\n hopsTraversed: number;\n}\n\n// ─── Helpers ─────────────────────────────────────────────────────────\n\nfunction formatEntryMarkdown(entry: EntryListItem): string {\n const id = entry.entryId ? `${entry.entryId}: ` : \"\";\n const lines = [`## ${id}${entry.name} [${entry.status}]`];\n if (entry.data && typeof entry.data === \"object\") {\n for (const [key, val] of Object.entries(entry.data)) {\n if (val && key !== \"rawData\") {\n lines.push(`**${key}**: ${typeof val === \"string\" ? val : JSON.stringify(val)}`);\n }\n }\n }\n return lines.join(\"\\n\");\n}\n\nfunction buildOrientationMarkdown(\n collections: Collection[] | null,\n trackingEvents: EntryListItem[] | null,\n standards: EntryListItem[] | null,\n businessRules: EntryListItem[] | null,\n principles: EntryListItem[] | null,\n): string {\n const sections: string[] = [\"# Product Brain — Orientation\"];\n\n // About Product Brain (the tool)\n sections.push(\n \"## About Product Brain (PB)\\n\" +\n \"PB is a knowledge management system used by many product teams. \" +\n \"This section describes how PB works — not your product.\\n\\n\" +\n \"### How PB Organizes Its Tools\\n\" +\n \"- **Tools** = actions with side-effects or dynamic computation (capture, commit, search).\\n\" +\n \"- **Resources** = stable, read-only data (orientation, terminology, collection schemas).\\n\" +\n \"- **Prompts** = multi-step choreography (workflows, guided capture, deep dives).\\n\" +\n \"- Every tool, resource, and prompt works for ANY workspace — no bespoke logic.\\n\" +\n \"- Resource templates (URI params) serve workspace-specific data through generic patterns.\\n\" +\n \"- Compound tools with `action` enums keep the tool count minimal.\\n\\n\" +\n \"### How PB Handles Your Data\\n\" +\n \"- **Draft-first**: all writes create drafts. SSOT requires explicit user confirmation.\\n\" +\n \"- **Empty-workspace safe**: every operation handles zero entries and fresh workspaces.\\n\" +\n \"- **Advisory, not blocking**: quality scores, contradiction checks, and coaching never prevent operations.\\n\" +\n \"- **Workspace-agnostic**: PB is a product for many teams — no workspace-specific logic.\\n\" +\n \"- **Self-documenting**: orient and server instructions teach agents how PB works.\",\n );\n\n // Workspace principles, standards, and rules from the Chain\n const wsRules: Array<{ id: string; name: string; severity?: string; source: string }> = [];\n\n for (const p of (principles ?? []).filter((e) => e.status === \"active\" || e.status === \"verified\")) {\n wsRules.push({ id: p.entryId ?? \"\", name: p.name, severity: (p.data?.severity as string) ?? undefined, source: \"principles\" });\n }\n for (const s of (standards ?? []).filter((e) => e.status === \"active\" || e.status === \"verified\")) {\n wsRules.push({ id: s.entryId ?? \"\", name: s.name, severity: (s.data?.severity as string) ?? undefined, source: \"standards\" });\n }\n for (const r of (businessRules ?? []).filter((e) => e.status === \"active\" || e.status === \"verified\")) {\n wsRules.push({ id: r.entryId ?? \"\", name: r.name, severity: (r.data?.severity as string) ?? undefined, source: \"business-rules\" });\n }\n\n if (wsRules.length > 0) {\n const ruleLines = wsRules\n .map((r) => {\n const sev = r.severity ? ` [${r.severity}]` : \"\";\n return `- **${r.id}**: ${r.name}${sev}`;\n })\n .join(\"\\n\");\n sections.push(\n `## Your Workspace Principles & Rules (${wsRules.length} active)\\n` +\n \"These are principles, standards, and rules your team has committed to the Chain. \" +\n \"Respect them during implementation.\\n\\n\" +\n ruleLines + \"\\n\\n\" +\n 'Use `entries action=get entryId=\"<ID>\"` to drill into any rule before making changes in that area.',\n );\n } else {\n sections.push(\n \"## Your Workspace Principles & Rules\\n\" +\n \"No active principles, standards, or business rules on the Chain yet.\\n\" +\n \"Use `capture` with collection `principles`, `standards`, or `business-rules` to add your team's guardrails.\\n\" +\n \"Once committed, they appear here at orient time — so every agent session starts with your rules visible.\",\n );\n }\n\n // Core Product Architecture (the three primitives)\n sections.push(\n \"## Core Product Architecture\\n\" +\n \"The Chain is a versioned, connected, compounding knowledge base — the SSOT for a product team.\\n\" +\n \"Everything on the Chain is one of **three primitives**:\\n\\n\" +\n \"- **Entry** (atom) — a discrete knowledge unit: target audience, business rule, glossary term, metric, tension. Lives in a collection.\\n\" +\n \"- **Process** (authored) — a narrative chain with named links (Strategy Coherence, IDM Proposal). Content is inline text. Collection: `chains`.\\n\" +\n \"- **Map** (composed) — a framework assembled by reference (Lean Canvas, Empathy Map). Slots point to ingredient entries. Collection: `maps`.\\n\\n\" +\n \"Entries are atoms. Processes author narrative from atoms. Maps compose frameworks from atoms.\\n\" +\n \"All three share the same versioning, branching, gating, and relation system.\\n\\n\" +\n \"The Chain compounds: each new relation makes entries discoverable from more starting points → \" +\n \"context gathering returns richer results → AI processes have more context → quality scores improve → \" +\n \"next commit is smarter than the last.\",\n );\n\n // Architecture\n sections.push(\n \"## Architecture\\n\" +\n \"```\\n\" +\n \"Cursor (stdio) → MCP Server (mcp-server/src/index.ts)\\n\" +\n \" → POST /api/aki with Bearer token\\n\" +\n \" → Convex HTTP Action (convex/http.ts)\\n\" +\n \" → internalQuery / internalMutation (convex/agentKnowledge/*)\\n\" +\n \" → Convex DB (workspace-scoped)\\n\" +\n \"```\\n\" +\n \"Security: API key auth on every request, workspace-scoped data, internal functions blocked from external clients.\\n\" +\n \"Key files: `packages/mcp-server/src/client.ts` (HTTP client + audit), `convex/schema.ts` (schema).\",\n );\n\n // Data model\n if (collections) {\n const collList = collections\n .map((c) => {\n const prefix = c.icon ? `${c.icon} ` : \"\";\n return `- ${prefix}**${c.name}** (\\`${c.slug}\\`) — ${c.description || \"no description\"}`;\n })\n .join(\"\\n\");\n sections.push(\n `## Data Model (${collections.length} collections)\\n` +\n \"Unified entries model: collections define field schemas, entries hold data in a flexible `data` field.\\n\" +\n \"The `data` field is polymorphic: plain fields for generic entries, `ChainData` (chainTypeId + links) for processes, `MapData` (templateId + slots) for maps.\\n\" +\n \"Tags for filtering (e.g. `severity:high`), relations via `entryRelations`, versions via `entryVersions`, labels via `labels` + `entryLabels`.\\n\\n\" +\n collList + \"\\n\\n\" +\n \"Use `collections action=list` for field schemas, `entries action=get` for full records.\",\n );\n } else {\n sections.push(\n \"## Data Model\\n\" +\n \"Could not load collections — use `collections action=list` to browse manually.\",\n );\n }\n\n // Business rules\n const rulesCount = businessRules ? `${businessRules.length} entries` : \"not loaded — collection may not exist yet\";\n sections.push(\n \"## Business Rules\\n\" +\n `Collection: \\`business-rules\\` (${rulesCount}).\\n` +\n \"Find rules: `entries action=search` for text search, `entries action=list collection=business-rules` to browse.\\n\" +\n \"Check compliance: use the `review-against-rules` prompt (pass a domain).\\n\" +\n \"Draft a new rule: use the `draft-rule-from-context` prompt.\",\n );\n\n // Analytics / tracking\n const eventsCount = trackingEvents ? `${trackingEvents.length} events` : \"not loaded — collection may not exist yet\";\n const conventionNote = standards\n ? \"Naming convention: `object_action` in snake_case with past-tense verbs (from standards collection).\"\n : \"Naming convention: `object_action` in snake_case with past-tense verbs.\";\n sections.push(\n \"## Analytics & Tracking\\n\" +\n `Event catalog: \\`tracking-events\\` collection (${eventsCount}).\\n` +\n `${conventionNote}\\n` +\n \"Implementation: `src/lib/analytics.ts`. Workspace-scoped events MUST use `withWorkspaceGroup()`.\\n\" +\n \"Browse: `entries action=list collection=tracking-events`.\",\n );\n\n // Knowledge Graph\n sections.push(\n \"## Knowledge Graph\\n\" +\n \"Entries are connected via typed relations (`entryRelations` table). Relations are bidirectional and collection-agnostic — any entry can link to any other entry.\\n\\n\" +\n \"**Recommended relation types** (extensible — any string accepted):\\n\" +\n \"- `governs` — a rule constrains behavior of a feature\\n\" +\n \"- `defines_term_for` — a glossary term is canonical vocabulary for a feature/area\\n\" +\n \"- `belongs_to` — a feature belongs to a product area or parent concept\\n\" +\n \"- `informs` — a decision or insight informs a feature\\n\" +\n \"- `fills_slot` — an ingredient entry fills a slot in a map\\n\" +\n \"- `surfaces_tension_in` — a tension exists within a feature area\\n\" +\n \"- `related_to`, `depends_on`, `replaces`, `conflicts_with`, `references`, `confused_with`\\n\\n\" +\n \"Each relation type is defined as a glossary entry (prefix `GT-REL-*`) to prevent terminology drift.\\n\\n\" +\n \"**Tools:**\\n\" +\n \"- `context action=gather` — get the full context around any entry (multi-hop graph traversal)\\n\" +\n \"- `graph action=suggest` — discover potential connections for an entry\\n\" +\n \"- `relations action=create` — create a typed link between two entries\\n\" +\n \"- `graph action=find` — list direct relations for an entry\\n\\n\" +\n \"**Convention:** When creating or updating entries in governed collections, always use `graph action=suggest` to discover and create relevant relations.\",\n );\n\n // Creating Knowledge\n sections.push(\n \"## Creating Knowledge\\n\" +\n \"**Entries:** Use `capture` as the primary tool for creating new entries. It handles the full workflow in one call:\\n\" +\n \"1. Creates the entry with collection-aware defaults (auto-fills dates, infers domains, sets priority)\\n\" +\n \"2. Auto-links related entries from across the chain (up to 5 confident matches)\\n\" +\n \"3. Returns a quality scorecard (X/10) with actionable improvement suggestions\\n\\n\" +\n \"**Smart profiles** exist for: `tensions`, `business-rules`, `glossary`, `decisions`, `features`, `audiences`, `strategy`, `standards`, `maps`, `chains`, `tracking-events`.\\n\" +\n \"All other collections use the `ENT-{random}` fallback profile.\\n\\n\" +\n \"**Processes:** Use `chain action=create` with a template (e.g., `strategy-coherence`, `idm-proposal`). Fill links with `chain action=edit`.\\n\\n\" +\n \"**Maps:** Use `map action=create` with a template (e.g., `lean-canvas`). Fill slots with `map-slot action=add`. Commit with `map-version action=commit`.\\n\" +\n \"Note: committing a map version creates a snapshot but does NOT change the entry status. To activate: `update-entry entryId=MAP-xxx status=active autoPublish=true`.\\n\" +\n \"Use `map-suggest` to discover ingredients for empty slots.\\n\\n\" +\n \"**Prompts** (invoke via MCP prompt protocol):\\n\" +\n \"- `name-check` — verify a name against glossary conventions\\n\" +\n \"- `draft-decision-record` — scaffold a decision entry\\n\" +\n \"- `review-against-rules` — check work against business rules for a domain\\n\" +\n \"- `draft-rule-from-context` — create a new business rule from context\\n\\n\" +\n \"Use `quality action=check` to score existing entries retroactively.\\n\" +\n \"Use `update-entry` for post-creation adjustments (status changes, field updates, deprecation).\",\n );\n\n // Where to go next\n sections.push(\n \"## Where to Go Next\\n\" +\n \"- **Create entry** → `capture` tool (auto-links + quality score in one call)\\n\" +\n \"- **Full context** → `context action=gather` (by entry ID or task description)\\n\" +\n \"- **Discover links** → `graph action=suggest`\\n\" +\n \"- **Quality audit** → `quality action=check`\\n\" +\n \"- **Terminology** → `name-check` prompt or `productbrain://terminology` resource\\n\" +\n \"- **Schema details** → `productbrain://collections` resource or `collections action=list`\\n\" +\n \"- **Labels** → `productbrain://labels` resource or `labels` tool\\n\" +\n \"- **Any collection** → `productbrain://{slug}/entries` resource\\n\" +\n \"- **Log a decision** → `draft-decision-record` prompt\\n\" +\n \"- **Build a map** → `map action=create` + `map-slot action=add` + `map-version action=commit`\\n\" +\n \"- **Architecture map** → `architecture action=show` tool (layered system visualization)\\n\" +\n \"- **Explore a layer** → `architecture action=explore` tool (drill into Auth, Core, Features, etc.)\\n\" +\n \"- **Growth funnel** → `productbrain://growth-funnel` resource or `entries action=list collection=strategy status=draft`\\n\" +\n \"- **Audiences** → `productbrain://audiences/entries` resource or `entries action=list collection=audiences`\\n\" +\n \"- **Session identity** → `health action=whoami`\\n\" +\n \"- **Health check** → `health action=check`\\n\" +\n \"- **Debug MCP calls** → `health action=audit`\",\n );\n\n return sections.join(\"\\n\\n---\\n\\n\");\n}\n\nconst AGENT_CHEATSHEET = `# Product Brain — Agent Cheatsheet\n\n## Core Tools\n| Tool | Purpose | Key params |\n|---|---|---|\n| \\`orient\\` | Workspace context, governance, active bets | — (call at session start) |\n| \\`capture\\` | Create entry (draft) | \\`collection\\`, \\`name\\`, \\`description\\`, optional \\`data\\` |\n| \\`entries\\` | List / get / batch / search entries | \\`action\\` + \\`entryId\\` / \\`query\\` / \\`collection\\` |\n| \\`update-entry\\` | Update fields on an entry | \\`entryId\\`, optional \\`name\\`, \\`status\\`, \\`workflowStatus\\`, \\`data\\`, \\`changeNote\\` |\n| \\`commit-entry\\` | Promote draft → SSOT | \\`entryId\\` |\n| \\`graph\\` | Suggest / find relations | \\`action\\` + \\`entryId\\` |\n| \\`relations\\` | Create / batch-create / delete links | \\`from\\`, \\`to\\`, \\`type\\` |\n| \\`context\\` | Gather related knowledge | \\`entryId\\` or \\`task\\` |\n| \\`collections\\` | List / create / update collections | \\`action\\` |\n| \\`labels\\` | List / create / apply / remove labels | \\`action\\` |\n| \\`quality\\` | Score an entry | \\`entryId\\` |\n| \\`session\\` | Start / close agent session | \\`action\\` |\n| \\`health\\` | Check / audit / whoami | \\`action\\` |\n| \\`facilitate\\` | Session resume & constellation commit | \\`action\\`: resume, commit-constellation |\n\n## Collection Prefixes\nGLO (glossary), BR (business-rules), PRI (principles), STD (standards),\nDEC (decisions), STR (strategy), TEN (tensions), FEAT (features),\nBET (bets), INS (insights), ARCH (architecture), TEAM (teams),\nROL (roles), MAP (maps), MTRC (tracking-events), ST (semantic-types)\n\n## Valid Relation Types (21)\ninforms, governs, surfaces_tension_in, defines_term_for, belongs_to,\nreferences, related_to, fills_slot, commits_to, informed_by, depends_on,\nconflicts_with, confused_with, replaces, part_of, constrains,\ngoverned_by, alternative_to, has_proposal, requests_promotion_of, resolves\n\n## Lifecycle Status\nAll entries: \\`draft\\` | \\`active\\` | \\`deprecated\\` | \\`archived\\`\n\n## Workflow Status (per collection)\n- **tensions:** open → processing → decided → closed\n- **decisions:** pending → decided\n- **bets:** shaped → bet → building → shipped\n- **business-rules:** active | conflict | review\n\n## Key Patterns\n- **Capture flow:** \\`capture\\` → \\`graph action=suggest\\` → \\`relations action=batch-create\\` → \\`commit-entry\\`\n- Use \\`workflowStatus\\` (not \\`status\\`) for domain workflow state\n- \\`data\\` param is merged (not replaced) — safe for partial updates\n`;\n\nexport function registerResources(server: McpServer) {\n // Agent cheatsheet: compact tool/schema reference (~500 tokens)\n server.resource(\n \"agent-cheatsheet\",\n \"productbrain://agent-cheatsheet\",\n async (uri) => ({\n contents: [{\n uri: uri.href,\n text: AGENT_CHEATSHEET,\n mimeType: \"text/markdown\",\n }],\n })\n );\n\n // Orientation: single-call system map for AI developers\n server.resource(\n \"chain-orientation\",\n \"productbrain://orientation\",\n async (uri) => {\n const [collectionsResult, eventsResult, standardsResult, rulesResult, principlesResult] = await Promise.allSettled([\n kernelQuery<Collection[]>(\"chain.listCollections\"),\n kernelQuery<EntryListItem[]>(\"chain.listEntries\", { collectionSlug: \"tracking-events\" }),\n kernelQuery<EntryListItem[]>(\"chain.listEntries\", { collectionSlug: \"standards\" }),\n kernelQuery<EntryListItem[]>(\"chain.listEntries\", { collectionSlug: \"business-rules\" }),\n kernelQuery<EntryListItem[]>(\"chain.listEntries\", { collectionSlug: \"principles\" }),\n ]);\n\n const collections = collectionsResult.status === \"fulfilled\" ? collectionsResult.value : null;\n const trackingEvents = eventsResult.status === \"fulfilled\" ? eventsResult.value : null;\n const standards = standardsResult.status === \"fulfilled\" ? standardsResult.value : null;\n const businessRules = rulesResult.status === \"fulfilled\" ? rulesResult.value : null;\n const principles = principlesResult.status === \"fulfilled\" ? principlesResult.value : null;\n\n return {\n contents: [{\n uri: uri.href,\n text: buildOrientationMarkdown(collections, trackingEvents, standards, businessRules, principles),\n mimeType: \"text/markdown\",\n }],\n };\n }\n );\n\n // Terminology: glossary + standards summary for deep-dives\n server.resource(\n \"chain-terminology\",\n \"productbrain://terminology\",\n async (uri) => {\n const [glossaryResult, standardsResult] = await Promise.allSettled([\n kernelQuery<EntryListItem[]>(\"chain.listEntries\", { collectionSlug: \"glossary\" }),\n kernelQuery<EntryListItem[]>(\"chain.listEntries\", { collectionSlug: \"standards\" }),\n ]);\n\n const lines: string[] = [\"# Product Brain — Terminology\"];\n\n if (glossaryResult.status === \"fulfilled\") {\n const glossary = glossaryResult.value ?? [];\n if (glossary.length > 0) {\n const terms = glossary\n .map((t) => `- **${t.name}** (${t.entryId ?? \"—\"}) [${t.status}]: ${t.data?.canonical ?? t.data?.description ?? \"\"}`)\n .join(\"\\n\");\n lines.push(`## Glossary (${glossary.length} terms)\\n\\n${terms}`);\n } else {\n lines.push(\"## Glossary\\n\\nNo glossary terms yet. Use `capture` with collection `glossary` to add terms.\");\n }\n } else {\n lines.push(\"## Glossary\\n\\nCould not load glossary — use `entries action=list collection=glossary` to browse manually.\");\n }\n\n if (standardsResult.status === \"fulfilled\") {\n const standards = standardsResult.value ?? [];\n if (standards.length > 0) {\n const stds = standards\n .map((s) => `- **${s.name}** (${s.entryId ?? \"—\"}) [${s.status}]: ${s.data?.description ?? \"\"}`)\n .join(\"\\n\");\n lines.push(`## Standards (${standards.length} entries)\\n\\n${stds}`);\n } else {\n lines.push(\"## Standards\\n\\nNo standards yet. Use `capture` with collection `standards` to add standards.\");\n }\n } else {\n lines.push(\"## Standards\\n\\nCould not load standards — use `entries action=list collection=standards` to browse manually.\");\n }\n\n return {\n contents: [{ uri: uri.href, text: lines.join(\"\\n\\n---\\n\\n\"), mimeType: \"text/markdown\" }],\n };\n }\n );\n\n server.resource(\n \"chain-collections\",\n \"productbrain://collections\",\n async (uri) => {\n const collections = (await kernelQuery<Collection[]>(\"chain.listCollections\")) ?? [];\n\n if (collections.length === 0) {\n return { contents: [{ uri: uri.href, text: \"No collections in this workspace. Use `collections action=create` or `start` with a preset to get started.\", mimeType: \"text/markdown\" }] };\n }\n\n const formatted = collections\n .map((c) => {\n const fieldList = (c.fields ?? [])\n .map((f) => ` - \\`${f.key}\\` (${f.type}${f.required ? \", required\" : \"\"}${f.searchable ? \", searchable\" : \"\"})`)\n .join(\"\\n\");\n return `## ${c.icon ?? \"\"} ${c.name} (\\`${c.slug}\\`)\\n${c.description || \"\"}\\n\\n**Fields:**\\n${fieldList}`;\n })\n .join(\"\\n\\n---\\n\\n\");\n\n return {\n contents: [{ uri: uri.href, text: `# Knowledge Collections (${collections.length})\\n\\n${formatted}`, mimeType: \"text/markdown\" }],\n };\n }\n );\n\n server.resource(\n \"chain-collection-entries\",\n new ResourceTemplate(\"productbrain://{slug}/entries\", {\n list: async () => {\n const collections = (await kernelQuery<Collection[]>(\"chain.listCollections\")) ?? [];\n return {\n resources: collections.map((c) => ({\n uri: `productbrain://${c.slug}/entries`,\n name: `${c.icon ?? \"\"} ${c.name}`.trim(),\n })),\n };\n },\n }),\n async (uri, { slug }) => {\n const entries = (await kernelQuery<EntryListItem[]>(\"chain.listEntries\", { collectionSlug: slug as string })) ?? [];\n const formatted = entries.map(formatEntryMarkdown).join(\"\\n\\n---\\n\\n\");\n\n return {\n contents: [{\n uri: uri.href,\n text: formatted || \"No entries in this collection.\",\n mimeType: \"text/markdown\",\n }],\n };\n }\n );\n\n server.resource(\n \"chain-labels\",\n \"productbrain://labels\",\n async (uri) => {\n const labels = (await kernelQuery<LabelRecord[]>(\"chain.listLabels\")) ?? [];\n\n if (labels.length === 0) {\n return { contents: [{ uri: uri.href, text: \"No labels in this workspace.\", mimeType: \"text/markdown\" }] };\n }\n\n const groups = labels.filter((l) => l.isGroup);\n const ungrouped = labels.filter((l) => !l.isGroup && !l.parentId);\n const children = (parentId: string) => labels.filter((l) => l.parentId === parentId);\n\n const lines: string[] = [];\n for (const group of groups) {\n lines.push(`## ${group.name}`);\n for (const child of children(group._id)) {\n lines.push(`- \\`${child.slug}\\` ${child.name}${child.color ? ` (${child.color})` : \"\"}`);\n }\n }\n if (ungrouped.length > 0) {\n lines.push(\"## Ungrouped\");\n for (const l of ungrouped) {\n lines.push(`- \\`${l.slug}\\` ${l.name}${l.color ? ` (${l.color})` : \"\"}`);\n }\n }\n\n return {\n contents: [{ uri: uri.href, text: `# Workspace Labels (${labels.length})\\n\\n${lines.join(\"\\n\")}`, mimeType: \"text/markdown\" }],\n };\n }\n );\n\n server.resource(\n \"chain-entry\",\n new ResourceTemplate(\"productbrain://entries/{entryId}\", {\n complete: {\n entryId: async (value) => {\n if (!value || value.length < 1) return [];\n const entries = (await kernelQuery<EntryListItem[]>(\"chain.searchEntries\", { query: value })) ?? [];\n return entries.slice(0, 10).map((e) => e.entryId ?? e._id);\n },\n },\n }),\n async (uri, { entryId }) => {\n const [entry, collections] = await Promise.all([\n kernelQuery<EntryDetail | null>(\"chain.getEntry\", { entryId: entryId as string }),\n kernelQuery<Collection[]>(\"chain.listCollections\"),\n ]);\n if (!entry) {\n return { contents: [{ uri: uri.href, text: `Entry \"${entryId}\" not found.`, mimeType: \"text/markdown\" }] };\n }\n\n const collectionMap = new Map((collections ?? []).map((c) => [c._id, c]));\n const col = collectionMap.get((entry as any).collectionId);\n const collLabel = col?.name ?? entry.collectionName ?? entry.collectionSlug ?? \"unknown\";\n\n const lines: string[] = [\n `# ${entry.entryId}: ${entry.name}`,\n `**Collection:** ${collLabel}`,\n `**Status:** ${entry.status}`,\n \"\",\n ];\n\n if (entry.data && typeof entry.data === \"object\") {\n lines.push(\"## Data\");\n for (const [key, val] of Object.entries(entry.data)) {\n if (val && key !== \"rawData\") {\n const str = typeof val === \"string\" ? val : JSON.stringify(val, null, 2);\n lines.push(`**${key}:** ${str}`);\n }\n }\n lines.push(\"\");\n }\n\n if (entry.relations && entry.relations.length > 0) {\n lines.push(\"## Relations\");\n for (const rel of entry.relations) {\n const arrow = rel.direction === \"outgoing\" ? \"→\" : \"←\";\n const id = rel.otherEntryId ?? \"\";\n const name = rel.otherName ?? \"(unknown)\";\n lines.push(`- ${arrow} **${rel.type}** ${id}: ${name}`);\n }\n lines.push(\"\");\n }\n\n if (entry.labels && entry.labels.length > 0) {\n lines.push(`## Labels\\n${entry.labels.map((l) => `- ${l.name ?? l.slug}`).join(\"\\n\")}`);\n }\n\n return {\n contents: [{ uri: uri.href, text: lines.join(\"\\n\"), mimeType: \"text/markdown\" }],\n };\n }\n );\n\n server.resource(\n \"chain-context\",\n new ResourceTemplate(\"productbrain://context/{entryId}\", {\n complete: {\n entryId: async (value) => {\n if (!value || value.length < 1) return [];\n const entries = (await kernelQuery<EntryListItem[]>(\"chain.searchEntries\", { query: value })) ?? [];\n return entries.slice(0, 10).map((e) => e.entryId ?? e._id);\n },\n },\n }),\n async (uri, { entryId }) => {\n const result = await kernelQuery<ContextResult>(\"chain.gatherContext\", {\n entryId: entryId as string,\n maxHops: 2,\n });\n\n if (!result?.root) {\n return { contents: [{ uri: uri.href, text: `Entry \"${entryId}\" not found.`, mimeType: \"text/markdown\" }] };\n }\n\n const lines: string[] = [\n `# Context: ${result.root.entryId}: ${result.root.name}`,\n `_${result.totalRelations} related entries (${result.hopsTraversed} hops)_`,\n \"\",\n ];\n\n const byCollection = new Map<string, NonNullable<ContextResult[\"related\"]>>();\n for (const entry of result.related ?? []) {\n const key = entry.collectionName;\n if (!byCollection.has(key)) byCollection.set(key, []);\n byCollection.get(key)!.push(entry);\n }\n\n for (const [collName, entries] of byCollection) {\n lines.push(`## ${collName} (${entries.length})`);\n for (const e of entries) {\n const arrow = e.relationDirection === \"outgoing\" ? \"→\" : \"←\";\n const hopLabel = e.hop > 1 ? ` (hop ${e.hop})` : \"\";\n const id = e.entryId ? `${e.entryId}: ` : \"\";\n lines.push(`- ${arrow} **${e.relationType}** ${id}${e.name}${hopLabel}`);\n }\n lines.push(\"\");\n }\n\n return {\n contents: [{ uri: uri.href, text: lines.join(\"\\n\"), mimeType: \"text/markdown\" }],\n };\n }\n );\n\n // WP-316 S1b: Capture contract resource — returns required fields and guidance for a collection.\n // Calls chain.getCaptureContract (registered in http.ts by S1a as internal.agentKnowledge.captureContracts.getCaptureContract).\n server.resource(\n \"chain-collection-capture-contract\",\n new ResourceTemplate(\"productbrain://collections/{slug}/capture-contract\", {\n list: async () => {\n // Enumerate known collections so clients can auto-complete the slug\n const collections = (await kernelQuery<Collection[]>(\"chain.listCollections\")) ?? [];\n return {\n resources: collections.map((c) => ({\n uri: `productbrain://collections/${c.slug}/capture-contract`,\n name: `${c.icon ?? \"\"} ${c.name} — capture contract`.trim(),\n })),\n };\n },\n }),\n async (uri, { slug }) => {\n const collectionSlug = slug as string;\n\n // Resolve workspaceId for PostHog miss event; non-fatal if resolution fails\n let workspaceId: string | null = null;\n try {\n const ctx = await getWorkspaceContext();\n workspaceId = ctx.workspaceId;\n } catch {\n // Workspace resolution failure must not block the resource response\n }\n\n let contract: Omit<CaptureContractResult, \"collectionSlug\"> | null = null;\n try {\n contract = await kernelQuery<Omit<CaptureContractResult, \"collectionSlug\"> | null>(\n \"chain.getCaptureContract\",\n { collectionSlug },\n );\n } catch {\n // Query error — fall through to not-found response\n contract = null;\n }\n\n if (!contract) {\n // WP-316 E5: emit capture_contract_miss event for observability\n if (workspaceId) {\n trackCaptureContractMiss(workspaceId, { slug: collectionSlug });\n }\n\n return {\n contents: [{\n uri: uri.href,\n mimeType: \"application/json\",\n text: JSON.stringify({\n ok: false,\n error: `Collection '${collectionSlug}' not found in this workspace.`,\n hint: \"Use `collections action=list` to see available collections and their slugs.\",\n }),\n }],\n };\n }\n\n const result: CaptureContractResult = {\n collectionSlug,\n requiredFields: contract.requiredFields,\n allFields: contract.allFields,\n captureExpectation: contract.captureExpectation,\n };\n\n return {\n contents: [{\n uri: uri.href,\n mimeType: \"application/json\",\n text: JSON.stringify(result),\n }],\n };\n }\n );\n\n server.resource(\n \"chain-search\",\n new ResourceTemplate(\"productbrain://search/{query}\", {\n complete: {\n query: async (value) => {\n if (!value) return [\"glossary:\", \"business-rules:\", \"decisions:\", \"tensions:\"];\n return [];\n },\n },\n }),\n async (uri, { query }) => {\n const results = await kernelQuery<EntryListItem[]>(\"chain.searchEntries\", { query: query as string });\n\n if (!results || results.length === 0) {\n return { contents: [{ uri: uri.href, text: `No results for \"${query}\".`, mimeType: \"text/markdown\" }] };\n }\n\n const lines: string[] = [\n `# Search: \"${query}\"`,\n `_${results.length} results_`,\n \"\",\n ];\n\n for (const entry of results) {\n const id = entry.entryId ? `**${entry.entryId}:** ` : \"\";\n const coll = entry.collectionName ?? entry.collectionSlug ?? \"\";\n lines.push(`- ${id}${entry.name} [${coll}] (${entry.status})`);\n }\n\n return {\n contents: [{ uri: uri.href, text: lines.join(\"\\n\"), mimeType: \"text/markdown\" }],\n };\n }\n );\n}\n","import { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { z } from \"zod\";\nimport { kernelQuery } from \"../client.js\";\n\nexport function registerPrompts(server: McpServer) {\n server.prompt(\n \"review-against-rules\",\n \"Review code or a design decision against all business rules for a given domain. Fetches the rules and asks you to do a structured compliance review.\",\n { domain: z.string().describe(\"Business rule domain (e.g. 'Identity & Access', 'Governance & Decision-Making')\") },\n async ({ domain }) => {\n const entries = await kernelQuery<any[]>(\"chain.listEntries\", { collectionSlug: \"business-rules\" });\n const rules = entries.filter((e) => e.data?.domain === domain);\n\n if (rules.length === 0) {\n return {\n messages: [\n {\n role: \"user\" as const,\n content: {\n type: \"text\" as const,\n text: `No business rules found for domain \"${domain}\". Use \\`entries action=list collection=business-rules\\` to see available domains.`,\n },\n },\n ],\n };\n }\n\n const rulesText = rules\n .map(\n (r) =>\n `### ${r.entryId ?? \"\"}: ${r.name}\\n` +\n `Status: ${r.status} | Severity: ${r.data?.severity ?? \"unknown\"}\\n` +\n `Description: ${r.data?.description ?? \"\"}\\n` +\n `Data Impact: ${r.data?.dataImpact ?? \"\"}\\n` +\n `Platforms: ${(r.data?.platforms ?? []).join(\", \")}\\n` +\n (r.data?.conflictWith ? `CONFLICT: ${r.data.conflictWith.rule} — ${r.data.conflictWith.nature}\\n` : \"\")\n )\n .join(\"\\n---\\n\\n\");\n\n return {\n messages: [\n {\n role: \"user\" as const,\n content: {\n type: \"text\" as const,\n text:\n `Review the current code or design against the following business rules for the \"${domain}\" domain.\\n\\n` +\n `For each rule, assess:\\n` +\n `1. Is the current implementation compliant?\\n` +\n `2. Are there potential violations or edge cases?\\n` +\n `3. What specific changes would be needed for compliance?\\n\\n` +\n `Business Rules:\\n\\n${rulesText}\\n\\n` +\n `Provide a structured review with a compliance status for each rule (COMPLIANT / AT RISK / VIOLATION / NOT APPLICABLE).`,\n },\n },\n ],\n };\n }\n );\n\n server.prompt(\n \"name-check\",\n \"Check variable names, field names, or API names against the glossary for terminology alignment. Flags drift from canonical terms.\",\n { names: z.string().describe(\"Comma-separated list of names to check (e.g. 'vendor_id, compliance_level, formulator_type')\") },\n async ({ names }) => {\n const terms = await kernelQuery<any[]>(\"chain.listEntries\", { collectionSlug: \"glossary\" });\n\n const glossaryContext = terms\n .map(\n (t) =>\n `${t.name} (${t.entryId ?? \"\"}) [${t.status}]: ${t.data?.canonical ?? \"\"}` +\n (t.data?.confusedWith?.length > 0 ? ` — Often confused with: ${t.data.confusedWith.join(\", \")}` : \"\") +\n (t.data?.codeMapping?.length > 0\n ? `\\n Code mappings: ${t.data.codeMapping.map((m: any) => `${m.platform}:${m.field}`).join(\", \")}`\n : \"\")\n )\n .join(\"\\n\");\n\n return {\n messages: [\n {\n role: \"user\" as const,\n content: {\n type: \"text\" as const,\n text:\n `Check the following names against the glossary for terminology alignment:\\n\\n` +\n `Names to check: ${names}\\n\\n` +\n `Glossary (canonical terms):\\n${glossaryContext}\\n\\n` +\n `For each name:\\n` +\n `1. Does it match a canonical term? If so, which one?\\n` +\n `2. Is there terminology drift? (e.g. using \"vendor\" instead of \"supplier\", \"compliance\" instead of \"conformance\")\\n` +\n `3. Suggest the canonical alternative if drift is detected.\\n` +\n `4. Flag any names that don't have a corresponding glossary term (might need one).\\n\\n` +\n `Format as a table: Name | Status | Canonical Form | Action Needed`,\n },\n },\n ],\n };\n }\n );\n\n server.prompt(\n \"draft-decision-record\",\n \"Draft a structured decision record from a description of what was decided. Includes context from recent decisions and relevant rules.\",\n { context: z.string().describe(\"Description of the decision (e.g. 'We decided to use MRSL v3.1 as the conformance baseline because...')\") },\n async ({ context }) => {\n const recentDecisions = await kernelQuery<any[]>(\"chain.listEntries\", { collectionSlug: \"decisions\" });\n const sorted = [...recentDecisions]\n .sort((a, b) => ((b.data?.date ?? \"\") > (a.data?.date ?? \"\") ? 1 : -1))\n .slice(0, 5);\n\n const recentContext = sorted.length > 0\n ? sorted.map((d) => `- [${d.status}] ${d.name} (${d.data?.date ?? \"no date\"})`).join(\"\\n\")\n : \"No previous decisions recorded.\";\n\n return {\n messages: [\n {\n role: \"user\" as const,\n content: {\n type: \"text\" as const,\n text:\n `Draft a structured decision record from the following context:\\n\\n` +\n `\"${context}\"\\n\\n` +\n `Recent decisions for reference:\\n${recentContext}\\n\\n` +\n `Structure the decision record with:\\n` +\n `1. **Title**: Concise decision statement\\n` +\n `2. **Decided by**: Who made or approved this decision\\n` +\n `3. **Date**: When it was decided\\n` +\n `4. **Status**: decided / proposed / revisited\\n` +\n `5. **Rationale**: Why this decision was made, including trade-offs considered\\n` +\n `6. **Alternatives considered**: What else was on the table\\n` +\n `7. **Related rules or tensions**: Any business rules or tensions this connects to\\n\\n` +\n `After drafting, I can log it using the capture tool with collection \"decisions\".`,\n },\n },\n ],\n };\n }\n );\n\n server.prompt(\n \"draft-rule-from-context\",\n \"Draft a new business rule from an observation or discovery made while coding. Fetches existing rules for the domain to ensure consistency.\",\n {\n observation: z.string().describe(\"What you observed or discovered (e.g. 'Suppliers can have multiple org types in Gateway')\"),\n domain: z.string().describe(\"Which domain this rule belongs to (e.g. 'Governance & Decision-Making')\"),\n },\n async ({ observation, domain }) => {\n const allRules = await kernelQuery<any[]>(\"chain.listEntries\", { collectionSlug: \"business-rules\" });\n const existingRules = allRules.filter((r) => r.data?.domain === domain);\n\n const existingContext =\n existingRules.length > 0\n ? existingRules.map((r) => `${r.entryId ?? \"\"}: ${r.name} [${r.status}] — ${r.data?.description ?? \"\"}`).join(\"\\n\")\n : \"No existing rules for this domain.\";\n\n return {\n messages: [\n {\n role: \"user\" as const,\n content: {\n type: \"text\" as const,\n text:\n `Draft a business rule based on this observation:\\n\\n` +\n `\"${observation}\"\\n\\n` +\n `Domain: ${domain}\\n\\n` +\n `Existing rules in this domain:\\n${existingContext}\\n\\n` +\n `Draft the rule with these fields (do not specify entryId — Convex assigns sequential IDs automatically, e.g. SOS-7):\\n` +\n `1. **name**: Concise rule title\\n` +\n `2. **data.description**: What the rule states\\n` +\n `3. **data.rationale**: Why this rule matters\\n` +\n `4. **data.dataImpact**: How this affects data models, APIs, or storage\\n` +\n `5. **data.severity**: high / medium / low\\n` +\n `6. **data.platforms**: Which platforms are affected\\n` +\n `7. **data.relatedRules**: Any related existing rules\\n\\n` +\n `Make sure the rule is consistent with existing rules and doesn't contradict them. ` +\n `After drafting, I can create it using the capture tool with collection \"business-rules\".`,\n },\n },\n ],\n };\n }\n );\n}\n","// convex/lib/flags_core.ts — single source of truth for feature flags.\n// (Underscore path: Convex module names disallow hyphens in path segments.)\n// Chain: DEC-701 (pre-production flag simplification), STA-5 (amended),\n// BR-79 (kebab-case), BR-83 (amended), STD-35 (dead flag cleanup).\n//\n// This file lives in `convex/lib/` to keep the Convex tsconfig (which does\n// not include `src/`) and the SvelteKit tsconfig in the same type graph.\n// The MCP `prebuild` script copies this file into\n// `packages/mcp-server/src/flags.ts` so that the MCP package sees the\n// authoritative resolver without reaching across the monorepo boundary at\n// runtime.\n\nexport type FlagCtx = {\n\tworkspaceId?: string;\n\tclerkUserId?: string;\n};\n\nexport type FlagRule =\n\t| boolean\n\t| {\n\t\t\tdefault: boolean;\n\t\t\tworkspaceAllow?: readonly string[];\n\t\t\tworkspaceDeny?: readonly string[];\n\t\t\tuserAllow?: readonly string[];\n\t\t\tuserDeny?: readonly string[];\n\t\t\tposthog?: boolean;\n\t };\n\n/**\n * Kill switch — resolves flag-first in every environment.\n * - Vite/browser: `VITE_FEATURE_KILL_SWITCH=true`\n * - Node (MCP/Convex action/test): `FEATURE_KILL_SWITCH=true`\n *\n * Runtime-safe: both checks are guarded with typeof + optional chaining so\n * missing globals (Convex runtime lacks `import.meta.env`; browsers lack\n * `process`) do not throw.\n */\nfunction readViteEnvFlag(name: string): string | undefined {\n\ttry {\n\t\t// `import.meta` exists everywhere but `.env` is Vite-only.\n\t\tconst env = (import.meta as { env?: Record<string, string | undefined> }).env;\n\t\treturn env?.[name];\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction readProcessEnvFlag(name: string): string | undefined {\n\ttry {\n\t\tif (typeof process !== 'undefined' && process.env) {\n\t\t\treturn process.env[name];\n\t\t}\n\t} catch {\n\t\t// fall through\n\t}\n\treturn undefined;\n}\n\nconst KILL =\n\treadViteEnvFlag('VITE_FEATURE_KILL_SWITCH') === 'true' ||\n\treadProcessEnvFlag('FEATURE_KILL_SWITCH') === 'true';\n\n/**\n * FEAT-1139 — Query budget kill-switch.\n * When true, `cappedQuery` bypasses tiered row caps and returns full unbounded\n * result sets while preserving the `_budget` telemetry envelope.\n * - Vite/browser: `VITE_PB_QUERY_BUDGET_KILL=true`\n * - Node (MCP/Convex action/test): `PB_QUERY_BUDGET_KILL=true`\n */\nconst QUERY_BUDGET_KILL =\n\treadViteEnvFlag('VITE_PB_QUERY_BUDGET_KILL') === 'true' ||\n\treadProcessEnvFlag('PB_QUERY_BUDGET_KILL') === 'true';\n\n// Named IDs — dev + prod coexist per DEC-701. Convex deployment-prefix\n// namespacing (p57... dev, mx78... prod) makes the sets disjoint at runtime.\n// Clerk IDs shared when a single Clerk app serves both envs.\nexport const WS = {\n\tRANDY_DEV_PRIMARY: 'p5796jhec0nhyp417ekrt8x4w181t41f',\n\tRANDY_DEV_SECONDARY: 'p5791wr86cj0thx2vxpqavj0mn82rssd',\n\tRANDY_PROD_PRIMARY: 'mx784e9jjdqhsk2r0098bpvtes84e792',\n\tRANDY_PROD_SECONDARY: 'mx74q0mkwn4r920q2837qk7dsx84pq60',\n} as const;\n\nexport const USR = {\n\tRANDY: 'user_3C31UK8CWugoDXUj2RGu1HDudas',\n\t/** Niels — full MVP unlock in any workspace (Clerk JWT `sub` / `FlagCtx.clerkUserId`). */\n\tNIELS: 'user_3DOKRUaiY9KS3RKtC7shak3nB0N',\n} as const;\n\n/**\n * DEC-701 Phase 3: registry stays empty after Phase 2 because pre-production\n * products have no users to protect. Add flags here when genuinely needed —\n * shape is `boolean` for trivial toggles, or the FlagRule object for the\n * allowlist precedence described in DEC-701 Clause 3.\n *\n * WP-355 (MVP Surface Lock): five mvp-unlock-* flags gate Spine, Bridge, Rail,\n * Import, and Brain Chat. Default off; `workspaceAllow` lists Randy's dev/prod\n * workspaces; optional `userAllow` can grant the same unlocks to specific\n * Clerk user ids in any workspace (see USR.NIELS).\n */\nexport const FLAGS = {\n\t// WP-355 — MVP unlock: full Spine navigation (all modes + access patterns visible)\n\t'mvp-unlock-spine': {\n\t\tdefault: false,\n\t\tworkspaceAllow: [\n\t\t\tWS.RANDY_DEV_PRIMARY,\n\t\t\tWS.RANDY_DEV_SECONDARY,\n\t\t\tWS.RANDY_PROD_PRIMARY,\n\t\t\tWS.RANDY_PROD_SECONDARY,\n\t\t],\n\t\tuserAllow: [USR.NIELS],\n\t},\n\t// WP-355 — MVP unlock: Bridge full view (beyond locked /bridge dashboard)\n\t'mvp-unlock-bridge-full': {\n\t\tdefault: false,\n\t\tworkspaceAllow: [\n\t\t\tWS.RANDY_DEV_PRIMARY,\n\t\t\tWS.RANDY_DEV_SECONDARY,\n\t\t\tWS.RANDY_PROD_PRIMARY,\n\t\t\tWS.RANDY_PROD_SECONDARY,\n\t\t],\n\t\tuserAllow: [USR.NIELS],\n\t},\n\t// WP-355 — MVP unlock: Rail full context (beyond Rail context-only mode)\n\t'mvp-unlock-rail-full': {\n\t\tdefault: false,\n\t\tworkspaceAllow: [\n\t\t\tWS.RANDY_DEV_PRIMARY,\n\t\t\tWS.RANDY_DEV_SECONDARY,\n\t\t\tWS.RANDY_PROD_PRIMARY,\n\t\t\tWS.RANDY_PROD_SECONDARY,\n\t\t],\n\t\tuserAllow: [USR.NIELS],\n\t},\n\t// WP-355 — MVP unlock: Import surface enabled\n\t'mvp-unlock-import': {\n\t\tdefault: false,\n\t\tworkspaceAllow: [\n\t\t\tWS.RANDY_DEV_PRIMARY,\n\t\t\tWS.RANDY_DEV_SECONDARY,\n\t\t\tWS.RANDY_PROD_PRIMARY,\n\t\t\tWS.RANDY_PROD_SECONDARY,\n\t\t],\n\t\tuserAllow: [USR.NIELS],\n\t},\n\t// WP-355 — Brain Chat: off by default; same workspace + user allowlists as other mvp-unlock flags.\n\t'mvp-unlock-brain-chat': {\n\t\tdefault: false,\n\t\tworkspaceAllow: [\n\t\t\tWS.RANDY_DEV_PRIMARY,\n\t\t\tWS.RANDY_DEV_SECONDARY,\n\t\t\tWS.RANDY_PROD_PRIMARY,\n\t\t\tWS.RANDY_PROD_SECONDARY,\n\t\t],\n\t\tuserAllow: [USR.NIELS],\n\t},\n\t// WP-373 E3 — Routing Resolver SSOT killswitch.\n\t// When true, the new pure resolver short-circuits and mount sites execute the\n\t// legacy inline redirect/error logic verbatim. Default false: resolver runs.\n\t// FEATURE_KILL_SWITCH env beats this flag (precedence per .claude/rules/feature-flags.md).\n\t'routing-resolver-killswitch': false,\n\t// WP-384 S3: Child-domain creation affordance. OFF by default — \"Coming soon\" tooltip per DEC-97 / STA-11.\n\t'custom-authority-domains': false,\n\t// FEAT-1139 — Query budget kill-switch.\n\t// When true, `cappedQuery` reverts to raw `.collect()` behavior (no row caps)\n\t// while still populating `_budget` for WP-380 telemetry. Default false.\n\t'query-budget-kill': {\n\t\tdefault: QUERY_BUDGET_KILL,\n\t},\n} as const satisfies Record<string, FlagRule>;\n\n// Keys removed from FLAGS but not yet swept from all call sites (STD-35).\nexport const DEPRECATED_FLAG_KEYS: readonly string[] = [];\n\nexport type FlagKey = keyof typeof FLAGS;\n\ntype PosthogResolver = (flag: string) => boolean | undefined;\n\n/**\n * @internal — exported for tests only. Do not consume from production code\n * (use `isFeatureEnabled` instead). Tests use this to exercise precedence\n * without mutating the real FLAGS registry.\n *\n * Precedence (DEC-701 Clause 3, top wins):\n * kill switch > userAllow > userDeny > workspaceDeny > workspaceAllow\n * > default > posthog fallback (opt-in)\n */\nexport function _resolve(\n\tflag: string,\n\trule: FlagRule | undefined,\n\tctx: FlagCtx,\n\tkill: boolean,\n\tposthog?: PosthogResolver,\n): boolean {\n\tif (kill) return false;\n\tif (rule === undefined) return false;\n\tif (typeof rule === 'boolean') return rule;\n\n\tconst { workspaceId, clerkUserId } = ctx;\n\tif (clerkUserId && rule.userAllow?.includes(clerkUserId)) return true;\n\tif (clerkUserId && rule.userDeny?.includes(clerkUserId)) return false;\n\tif (workspaceId && rule.workspaceDeny?.includes(workspaceId)) return false;\n\tif (workspaceId && rule.workspaceAllow?.includes(workspaceId)) return true;\n\n\tif (rule.posthog && posthog) {\n\t\ttry {\n\t\t\tconst hit = posthog(flag);\n\t\t\tif (typeof hit === 'boolean') return hit;\n\t\t} catch {\n\t\t\t// fall through to rule.default on any PostHog error\n\t\t}\n\t}\n\treturn rule.default;\n}\n\nfunction defaultPosthog(flag: string): boolean | undefined {\n\ttry {\n\t\ttype PosthogLike = { isFeatureEnabled(k: string): boolean | undefined };\n\t\tconst g = globalThis as unknown as { __posthog?: PosthogLike };\n\t\treturn g.__posthog?.isFeatureEnabled(flag);\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nexport function isFeatureEnabled(flag: FlagKey, ctx: FlagCtx = {}): boolean {\n\tconst rule = (FLAGS as Record<string, FlagRule>)[flag as string];\n\treturn _resolve(flag as string, rule, ctx, KILL, defaultPosthog);\n}\n","// packages/mcp-server/src/featureFlags.ts — thin wrapper over the\n// authoritative resolver in `./flags.ts` (byte copy of `convex/lib/flags_core.ts`\n// via `npm run prebuild`; file is committed for Railway package-scoped Docker).\n//\n// Chain: DEC-701.\n//\n// `initFeatureFlags` is retained as a no-op for compatibility with the\n// existing MCP bootstrap call sites (index.ts, http.ts). It used to create\n// a PostHog client; with the DEC-701 allowlist registry PostHog is a\n// per-flag opt-in via globalThis.__posthog, so no initialization is\n// required at startup.\nimport type { PostHog } from \"posthog-node\";\nimport { isFeatureEnabled as coreIsFeatureEnabled, type FlagKey } from \"./flags.js\";\n\nexport type { FlagKey };\n\nexport function initFeatureFlags(_posthogClient: PostHog | null): void {\n // no-op — DEC-701 registry does not require a PostHog client at startup.\n // Retained so existing MCP boot code (index.ts, http.ts) keeps working.\n}\n\nexport function isFeatureEnabled(\n flag: FlagKey,\n ctx: { workspaceId?: string; clerkUserId?: string } = {},\n): boolean {\n return coreIsFeatureEnabled(flag, ctx);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAUA,SAAS,yBAAyB;AAClC,SAAS,kBAAkB;AAQpB,SAAS,QAAQ,KAAqB;AAC3C,SAAO,WAAW,QAAQ,EAAE,OAAO,GAAG,EAAE,OAAO,KAAK,EAAE,MAAM,GAAG,EAAE;AACnE;AAQA,IAAM,eAAe,IAAI,kBAA+B;AAEjD,SAAS,YAAe,MAAmB,IAA0C;AAC1F,SAAO,aAAa,IAAI,MAAM,EAAE;AAClC;AAEO,SAAS,mBAAuC;AACrD,SAAO,aAAa,SAAS,GAAG;AAClC;AAqBA,IAAM,iBAAiB,KAAK,KAAK;AACjC,IAAM,WAAW;AACjB,IAAM,cAAc,oBAAI,IAAsB;AAE9C,SAAS,cAAwB;AAC/B,SAAO;AAAA,IACL,aAAa;AAAA,IACb,eAAe;AAAA,IACf,eAAe;AAAA,IACf,oBAAoB;AAAA,IACpB,yBAAyB;AAAA,IACzB,gBAAgB;AAAA,IAChB,UAAU;AAAA,IACV,aAAa;AAAA,IACb,iBAAiB;AAAA,IACjB,eAAe;AAAA,IACf,YAAY,KAAK,IAAI;AAAA,IACrB,eAAe;AAAA,EACjB;AACF;AAEO,SAAS,YAAY,QAA0B;AACpD,MAAI,IAAI,YAAY,IAAI,MAAM;AAC9B,MAAI,CAAC,GAAG;AACN,Q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olved","classifierMeta","z","preview","BLOCKING_CONTRADICTION_THRESHOLD","z","wsCtx","z","z","z","z","z","z","suggested","suggestedWithPosture","z","z","result","byCollection","lines","rootId","nodes","edges","z","z","handleList","handleCreate","z","z","z","z","z","SEVERITY_RANK","resolve","z","data","z","z","z","z","z","levenshtein","_","handleList","handleStart","z","z","existsSync","readFileSync","resolve","z","readFileSync","resolve","existsSync","z","z","z","z","z","z","z","z","z","z","z","existsSync","readFileSync","resolve","z","z","resolve","existsSync","readFileSync","abs","z","z","orientationStatus","handleAudit","z","r","z","z","z","z","z","z","z","z","existsSync","dirname","resolve","dirname","resolve","z","z","McpServer"]}
|