@productbrain/mcp 0.0.1-beta.2 → 0.0.1-beta.21

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/server.ts","../src/tools/knowledge.ts","../src/tools/labels.ts","../src/tools/health.ts","../src/tools/planned-work.ts","../src/tools/verify.ts","../src/tools/architecture.ts","../src/tools/workflows.ts","../src/workflows/definitions.ts","../src/tools/session.ts","../src/tools/gitchain.ts","../src/tools/maps.ts","../src/tools/start.ts","../src/presets/collections.ts","../src/resources/index.ts","../src/prompts/index.ts"],"sourcesContent":["/**\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 { registerLabelTools } from \"./tools/labels.js\";\nimport { registerHealthTools } from \"./tools/health.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 { registerSessionTools } from \"./tools/session.js\";\nimport { registerGitChainTools } from \"./tools/gitchain.js\";\nimport { registerMapTools } from \"./tools/maps.js\";\nimport { registerStartTools } from \"./tools/start.js\";\nimport { registerResources } from \"./resources/index.js\";\nimport { registerPrompts } from \"./prompts/index.js\";\n\nexport const SERVER_VERSION = \"0.0.1-beta\";\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 \"Workflow:\",\n \" 1. Start: call `agent-start` to begin a tracked session.\",\n \" 2. Orient: call `orient` to load workspace context and unlock write tools.\",\n \" 3. Discover: use `search` to find entries, or `list-entries` to browse.\",\n \" 4. Drill in: use `get-entry` for full details — data, labels, relations, history.\",\n \" 5. Context: use `gather-context` 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 `suggest-links` then `relate-entries` to build the graph.\",\n \" 9. Close: call `agent-close` when done — records session activity.\",\n \"\",\n \"Write tools (capture, update-entry, relate-entries, commit-entry) require:\",\n \" - An active agent session (call agent-start)\",\n \" - Completed orientation (call orient)\",\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 \"Workspace setup: use `create-collection` and `update-collection` 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 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 registerKnowledgeTools(server);\n registerLabelTools(server);\n registerHealthTools(server);\n registerVerifyTools(server);\n registerSmartCaptureTools(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 registerStartTools(server);\n\n registerResources(server);\n registerPrompts(server);\n\n return server;\n}\n","import { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { z } from \"zod\";\nimport { mcpQuery, mcpMutation, getWorkspaceContext, requireWriteAccess, recordSessionActivity, getAgentSessionId } from \"../client.js\";\n\nfunction extractPreview(data: any, maxLen: number): string {\n if (!data || typeof data !== \"object\") return \"\";\n const raw = data.description ?? data.canonical ?? data.detail ?? \"\";\n if (typeof raw !== \"string\" || !raw) return \"\";\n return raw.length > maxLen ? raw.substring(0, maxLen) + \"...\" : raw;\n}\n\nexport function registerKnowledgeTools(server: McpServer) {\n\n server.registerTool(\n \"list-collections\",\n {\n title: \"Browse Collections\",\n description:\n \"List every knowledge collection in the workspace — glossary, business rules, tracking events, standards, etc. \" +\n \"Returns each collection's slug, name, description, and field schema. \" +\n \"Start here before capture so you know which collections exist and what fields they expect.\",\n annotations: { readOnlyHint: true },\n },\n async () => {\n const collections = await mcpQuery<any[]>(\"chain.listCollections\");\n\n if (collections.length === 0) {\n return { content: [{ type: \"text\" as const, text: \"No collections found in this workspace.\" }] };\n }\n\n const formatted = collections\n .map((c) => {\n const fieldList = c.fields\n .map((f: any) => ` - \\`${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 };\n }\n );\n\n server.registerTool(\n \"list-entries\",\n {\n title: \"Browse Entries\",\n description:\n \"List entries in a collection, with optional filters for status, tag, or label. \" +\n \"Returns entry IDs, names, status, and a data preview. \" +\n \"Use list-collections first to discover available collection slugs.\",\n inputSchema: {\n collection: z.string().optional().describe(\"Collection slug, e.g. 'glossary', 'tracking-events', 'business-rules'\"),\n status: z.string().optional().describe(\"Filter: draft | active | verified | deprecated\"),\n tag: z.string().optional().describe(\"Filter by internal tag, e.g. 'health:ambiguous'\"),\n label: z.string().optional().describe(\"Filter by label slug — matches entries across all collections\"),\n },\n annotations: { readOnlyHint: true },\n },\n async ({ collection, status, tag, label }) => {\n let entries: any[];\n\n if (label) {\n entries = await mcpQuery<any[]>(\"chain.listEntriesByLabel\", { labelSlug: label });\n if (status) entries = entries.filter((e: any) => e.status === status);\n } else {\n entries = await mcpQuery<any[]>(\"chain.listEntries\", {\n collectionSlug: collection,\n status,\n tag,\n });\n }\n\n if (entries.length === 0) {\n return { content: [{ type: \"text\" as const, text: \"No entries match the given filters.\" }] };\n }\n\n const formatted = entries\n .map((e) => {\n const id = e.entryId ? `**${e.entryId}:** ` : \"\";\n const dataPreview = e.data\n ? Object.entries(e.data)\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} \\`${e.status}\\`${dataPreview ? `\\n${dataPreview}` : \"\"}`;\n })\n .join(\"\\n\\n\");\n\n const scope = collection ? ` in \\`${collection}\\`` : \"\";\n return {\n content: [{ type: \"text\" as const, text: `# Entries${scope} (${entries.length})\\n\\n${formatted}` }],\n };\n }\n );\n\n server.registerTool(\n \"get-entry\",\n {\n title: \"Look Up Entry\",\n description:\n \"Retrieve a single knowledge entry by its human-readable ID (e.g. 'T-SUPPLIER', 'BR-001', 'EVT-workspace_created'). \" +\n \"Returns the full record: all data fields, labels, relations, and change history. \" +\n \"Use search or list-entries first to discover entry IDs.\",\n inputSchema: {\n entryId: z.string().describe(\"Entry ID, e.g. 'T-SUPPLIER', 'BR-001', 'EVT-workspace_created'\"),\n },\n annotations: { readOnlyHint: true },\n },\n async ({ entryId }) => {\n const entry = await mcpQuery<any>(\"chain.getEntry\", { entryId });\n\n if (!entry) {\n return { content: [{ type: \"text\" as const, text: `Entry \\`${entryId}\\` not found. Try search to find the right ID.` }] };\n }\n\n const lines: string[] = [\n `# ${entry.entryId ? `${entry.entryId}: ` : \"\"}${entry.name}`,\n \"\",\n `**Status:** ${entry.status}`,\n `**Type:** ${entry.canonicalKey ?? \"untyped\"}`,\n ];\n\n if (entry.data && typeof entry.data === \"object\") {\n lines.push(\"\");\n for (const [key, val] of Object.entries(entry.data)) {\n const display = typeof val === \"string\" ? val : JSON.stringify(val);\n lines.push(`**${key}:** ${display}`);\n }\n }\n\n if (entry.tags?.length > 0) {\n lines.push(\"\", `**Tags:** ${entry.tags.join(\", \")}`);\n }\n\n if (entry.labels?.length > 0) {\n lines.push(\"\", `**Labels:** ${entry.labels.map((l: any) => `\\`${l.slug ?? l.name}\\``).join(\", \")}`);\n }\n\n if (entry.relations?.length > 0) {\n lines.push(\"\", \"## Relations\");\n for (const r of entry.relations) {\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 (entry.history?.length > 0) {\n lines.push(\"\", \"## History (last 10)\");\n for (const h of entry.history.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 return { content: [{ type: \"text\" as const, text: lines.join(\"\\n\") }] };\n }\n );\n\n 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 get-entry first to see current values.\",\n inputSchema: {\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.string().optional().describe(\"New status: draft | active | verified | deprecated\"),\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(\"Short human-readable summary for history (e.g. 'Updated description to F1-themed copy'). If omitted, a friendly default is generated from fields changed.\"),\n },\n annotations: { idempotentHint: true, destructiveHint: false },\n },\n async ({ entryId, name, status, data, order, canonicalKey, autoPublish, changeNote }) => {\n requireWriteAccess();\n\n const id = await mcpMutation<string>(\"chain.updateEntry\", {\n entryId,\n name,\n status,\n data,\n order,\n canonicalKey,\n autoPublish,\n changeNote,\n changedBy: getAgentSessionId() ? `agent:${getAgentSessionId()}` : undefined,\n });\n\n await recordSessionActivity({ entryModified: id });\n\n const wsCtx = await getWorkspaceContext();\n const mode = autoPublish ? 'published' : 'saved as draft';\n return {\n content: [{ type: \"text\" as const, text: `# Entry Updated\\n\\n**${entryId}** has been ${mode}.\\n\\nInternal ID: ${id}\\n**Workspace:** ${wsCtx.workspaceSlug} (${wsCtx.workspaceId})` }],\n };\n }\n );\n\n server.registerTool(\n \"search\",\n {\n title: \"Search the Chain\",\n description:\n \"Full-text search across all entries on the Chain. Returns entry names, collection, status, and a description preview. \" +\n \"Scope results to a specific collection (e.g. collection='business-rules') or filter by status (e.g. status='active'). \" +\n \"Use this to discover entries before calling get-entry for full details.\",\n inputSchema: {\n query: z.string().describe(\"Search text (min 2 characters)\"),\n collection: z.string().optional().describe(\"Scope to a collection slug, e.g. 'business-rules', 'glossary', 'tracking-events'\"),\n status: z.string().optional().describe(\"Filter by status: draft | active | verified | deprecated\"),\n },\n annotations: { readOnlyHint: true, openWorldHint: true },\n },\n async ({ query, collection, status }) => {\n const scope = collection ? ` in \\`${collection}\\`` : \"\";\n await server.sendLoggingMessage({ level: \"info\", data: `Searching${scope} for \"${query}\"...`, logger: \"product-os\" });\n\n const [results, collections] = await Promise.all([\n mcpQuery<any[]>(\"chain.searchEntries\", { query, collectionSlug: collection, status }),\n mcpQuery<any[]>(\"chain.listCollections\"),\n ]);\n\n if (results.length === 0) {\n return { content: [{ type: \"text\" as const, text: `No results for \"${query}\"${scope}. Try a broader search or check list-collections for available data.` }] };\n }\n\n const collMap = new Map<string, { name: string; slug: string }>();\n for (const c of collections) {\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) {\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\n .map((e) => {\n const id = e.entryId ? `**${e.entryId}:** ` : \"\";\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} \\`${e.status}\\`${colTag}${typeTag}${preview}`;\n })\n .join(\"\\n\");\n\n const header = `# 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 get-entry with an entry ID for full details._`;\n\n return {\n content: [{ type: \"text\" as const, text: `${header}\\n\\n${formatted}\\n\\n${footer}` }],\n };\n }\n );\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: {\n entryId: z.string().describe(\"Entry ID, e.g. 'T-SUPPLIER', 'BR-001'\"),\n },\n annotations: { readOnlyHint: true },\n },\n async ({ entryId }) => {\n const history = await mcpQuery<any[]>(\"chain.listEntryHistory\", { entryId });\n\n if (history.length === 0) {\n return { content: [{ type: \"text\" as const, text: `No history found for \\`${entryId}\\`.` }] };\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 };\n }\n );\n\n server.registerTool(\n \"relate-entries\",\n {\n title: \"Link Two Entries\",\n description:\n \"Create a typed relation between two entries, building the knowledge graph. \" +\n \"Use get-entry to see existing relations before adding new ones.\\n\\n\" +\n \"Recommended relation types (extensible — any string is accepted):\\n\" +\n \"- related_to, depends_on, replaces, conflicts_with, references, confused_with\\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 \"- surfaces_tension_in — a tension exists within a feature area\\n\\n\" +\n \"Check glossary for relation type definitions if unsure which to use.\",\n inputSchema: {\n from: z.string().describe(\"Source entry ID, e.g. 'T-SUPPLIER'\"),\n to: z.string().describe(\"Target entry ID, e.g. 'BR-001'\"),\n type: z.string().describe(\"Relation type — use a recommended type or any descriptive string\"),\n score: z.number().optional().describe(\"Suggestion score from suggest-links (improves feedback for weight tuning)\"),\n },\n annotations: { destructiveHint: false },\n },\n async ({ from, to, type, score }) => {\n requireWriteAccess();\n\n const result = await mcpMutation<{ status?: string; proposalId?: string; existing?: boolean; fromEntryId?: string; toEntryId?: string; message?: string }>(\"chain.createEntryRelation\", {\n fromEntryId: from,\n toEntryId: to,\n type,\n suggestionScore: score ?? undefined,\n });\n\n await recordSessionActivity({ relationCreated: result?.status !== \"proposal_created\" });\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 };\n }\n return {\n content: [{ type: \"text\" as const, text: `# Relation Created\\n\\n**${from}** \\u2014[${type}]\\u2192 **${to}**\\n**Workspace:** ${wsCtx.workspaceSlug} (${wsCtx.workspaceId})` }],\n };\n }\n );\n\n server.registerTool(\n \"batch-relate\",\n {\n title: \"Batch Link Entries\",\n description:\n \"Create multiple relations in one call. Accepts an array of {from, to, type} objects. \" +\n \"Use after suggest-links to apply several suggestions at once instead of calling relate-entries repeatedly.\\n\\n\" +\n \"Each relation is created independently — if one fails, the others still succeed. \" +\n \"Returns a summary of created and failed relations.\",\n inputSchema: {\n relations: z.array(z.object({\n from: z.string().describe(\"Source entry ID\"),\n to: z.string().describe(\"Target entry ID\"),\n type: z.string().describe(\"Relation type\"),\n })).min(1).max(20).describe(\"Array of relations to create\"),\n },\n annotations: { destructiveHint: false },\n },\n async ({ relations }) => {\n requireWriteAccess();\n\n type RelResult = { from: string; to: string; type: string; ok: boolean; error?: string; proposalCreated?: boolean; proposalId?: string };\n const results: RelResult[] = [];\n\n for (const rel of relations) {\n try {\n const result = await mcpMutation<{ status?: string; proposalId?: string }>(\"chain.createEntryRelation\", {\n fromEntryId: rel.from,\n toEntryId: rel.to,\n type: rel.type,\n });\n results.push({\n ...rel,\n ok: true,\n proposalCreated: result?.status === \"proposal_created\",\n proposalId: result?.proposalId,\n });\n } catch (e: any) {\n results.push({ ...rel, ok: false, 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 return { content: [{ type: \"text\" as const, text: lines.join(\"\\n\") }] };\n }\n );\n\n server.registerTool(\n \"find-related\",\n {\n title: \"Find Related Entries\",\n description:\n \"Navigate the knowledge graph — find all entries related to a given entry. \" +\n \"Shows incoming references (what points to this entry), outgoing references (what this entry points to), or both. \" +\n \"Use after get-entry to explore connections, or to answer 'what depends on X?' or 'what references Y?'\",\n inputSchema: {\n entryId: z.string().describe(\"Entry ID, e.g. 'GT-019', 'SOS-006'\"),\n direction: z.enum([\"incoming\", \"outgoing\", \"both\"]).default(\"both\")\n .describe(\"Filter: 'incoming' = what references this entry, 'outgoing' = what this entry references\"),\n },\n annotations: { readOnlyHint: true },\n },\n async ({ entryId, direction }) => {\n const relations = await mcpQuery<any[]>(\"chain.listEntryRelations\", { entryId });\n\n if (relations.length === 0) {\n return { content: [{ type: \"text\" as const, text: `No relations found for \\`${entryId}\\`. Use relate-entries to create connections.` }] };\n }\n\n const sourceEntry = await mcpQuery<any>(\"chain.getEntry\", { entryId });\n if (!sourceEntry) {\n return { content: [{ type: \"text\" as const, text: `Entry \\`${entryId}\\` not found. Try 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 mcpQuery<any>(\"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 mcpQuery<any[]>(\"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[] = [`# 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 };\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(`- \\u2192 **${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(`- \\u2190 **${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 get-entry for the full picture._`);\n }\n\n return { content: [{ type: \"text\" as const, text: lines.join(\"\\n\") }] };\n }\n );\n\n server.registerTool(\n \"gather-context\",\n {\n title: \"Gather Context\",\n description:\n \"Assemble knowledge context in one call. Three modes:\\n\\n\" +\n \"1. **By entry** (entryId): Traverse the knowledge graph around a specific entry. \" +\n \"Returns all related entries grouped by collection.\\n\" +\n \"2. **By task** (task): Auto-load relevant domain knowledge for a natural-language task. \" +\n \"Searches the chain, traverses the graph, and returns ranked entries with confidence scores.\\n\" +\n \"3. **Graph mode** (entryId + mode='graph'): Enhanced graph traversal with provenance — \" +\n \"each entry includes the full path that led to it (via what relations, from what starting point).\\n\\n\" +\n \"Use mode 1/3 when you have a specific entry ID. Use mode 2 at the start of a conversation \" +\n \"to ground the agent in domain context before writing code or making recommendations.\",\n inputSchema: {\n entryId: z.string().optional().describe(\"Entry ID for graph traversal, e.g. 'FEAT-001', 'GT-019'\"),\n task: z.string().optional().describe(\"Natural-language task description for auto-loading relevant context\"),\n mode: z.enum([\"search\", \"graph\"]).default(\"search\").optional()\n .describe(\"'search' (default, backward-compatible) or 'graph' (enhanced with provenance paths)\"),\n maxHops: z.number().min(1).max(3).default(2)\n .describe(\"How many relation hops to traverse (1=direct only, 2=default, 3=wide net)\"),\n maxResults: z.number().min(1).max(25).default(10).optional()\n .describe(\"Max entries to return in task mode (default 10)\"),\n },\n annotations: { readOnlyHint: true },\n },\n async ({ entryId, task, mode, maxHops, maxResults }) => {\n if (!entryId && !task) {\n return { content: [{ type: \"text\" as const, text: \"Provide either `entryId` (graph traversal) or `task` (auto-load context for a task).\" }] };\n }\n\n // Graph mode: enhanced traversal with provenance paths\n if (entryId && mode === \"graph\") {\n const result = await mcpQuery<any>(\"chain.graphGatherContext\", {\n entryId,\n maxHops: maxHops ?? 2,\n });\n\n if (!result?.root) {\n return { content: [{ type: \"text\" as const, text: `Entry \\`${entryId}\\` not found. Try search to find the right ID.` }] };\n }\n\n if (result.context.length === 0) {\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 \\`suggest-links\\` to discover potential connections.`,\n }],\n };\n }\n\n const byCollection = new Map<string, any[]>();\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})`);\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 provenancePath = e.provenance && e.provenance.length > 1\n ? `\\n _Path: ${e.provenance.map((p: any) => `${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}${provenancePath}${preview}`);\n }\n lines.push(\"\");\n }\n\n return { content: [{ type: \"text\" as const, text: lines.join(\"\\n\") }] };\n }\n\n // Task mode: unified search-then-traverse via intelligence layer\n if (task && !entryId) {\n await server.sendLoggingMessage({\n level: \"info\",\n data: `Loading context for task: \"${task.substring(0, 80)}...\"`,\n logger: \"product-brain\",\n });\n\n const result = await mcpQuery<any>(\"chain.taskAwareGatherContext\", {\n task,\n maxHops: maxHops ?? 2,\n maxResults: maxResults ?? 15,\n });\n\n if (!result || result.totalFound === 0) {\n return {\n content: [{\n type: \"text\" as const,\n text: `# Context Loaded\\n\\n**Confidence:** None\\n\\n` +\n `No context found for this task. The chain may not cover this area yet.\\n\\n` +\n `_Consider capturing domain knowledge discovered during this task via \\`capture\\`._`,\n }],\n };\n }\n\n const byCollection = new Map<string, any[]>();\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 Loaded`,\n `**Confidence:** ${(result.confidence as string).charAt(0).toUpperCase() + (result.confidence as string).slice(1)}`,\n `**Matched:** ${result.totalFound} entries across ${byCollection.size} collection${byCollection.size === 1 ? \"\" : \"s\"}`,\n `**Seeds:** ${result.seeds?.map((s: any) => s.entryId ?? s.name).join(\", \") ?? \"none\"}`,\n \"\",\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 const flagsLabel = e.scoreFlags?.length ? ` [${e.scoreFlags.join(\", \")}]` : \"\";\n const hopLabel = e.hop > 0 ? ` _(hop ${e.hop}, ${arrow} ${e.relationType})_` : \"\";\n lines.push(`- ${id}${e.name}${scoreLabel}${flagsLabel}${hopLabel}`);\n }\n lines.push(\"\");\n }\n\n lines.push(`_Use \\`get-entry\\` for full details on any entry._`);\n\n return { content: [{ type: \"text\" as const, text: lines.join(\"\\n\") }] };\n }\n\n // Entry mode: traverse the knowledge graph around a specific entry\n const result = await mcpQuery<any>(\"chain.gatherContext\", { entryId, maxHops });\n\n if (!result?.root) {\n return { content: [{ type: \"text\" as const, text: `Entry \\`${entryId}\\` not found. Try search to find the right ID.` }] };\n }\n\n if (result.related.length === 0) {\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 \\`suggest-links\\` to discover potential connections, or \\`relate-entries\\` to link manually.`,\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})`);\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 return { content: [{ type: \"text\" as const, text: lines.join(\"\\n\") }] };\n }\n );\n\n server.registerTool(\n \"suggest-links\",\n {\n title: \"Suggest Links\",\n description:\n \"Discover potential connections for an entry using graph-aware intelligence. \" +\n \"Accepts an entry ID (e.g. 'FEAT-001') OR an entry name (e.g. 'Chain Intelligence'). \" +\n \"Traverses the knowledge graph (2-hop BFS) and scores candidates by graph distance, \" +\n \"text similarity, and relation type fit. Also finds text-similar entries not yet in the graph.\\n\\n\" +\n \"Returns ranked suggestions with confidence scores, recommended relation types, and \" +\n \"graph-path reasoning explaining WHY each connection matters.\\n\\n\" +\n \"This is a discovery tool — review suggestions and use relate-entries to create the ones that make sense.\",\n inputSchema: {\n entryId: z.string().describe(\"Entry ID (e.g. 'FEAT-001') or entry name (e.g. 'Chain Intelligence') to find suggestions for\"),\n limit: z.number().min(1).max(20).default(10)\n .describe(\"Max number of suggestions to return\"),\n depth: z.number().min(1).max(3).default(2)\n .describe(\"Graph traversal depth: 1=direct neighbors only, 2=default, 3=wide net\"),\n },\n annotations: { readOnlyHint: true },\n },\n async ({ entryId, limit, depth }) => {\n const result = await mcpQuery<any>(\"chain.graphSuggestLinks\", {\n entryId,\n maxHops: depth ?? 2,\n limit: limit ?? 10,\n });\n\n if (!result || !result.suggestions || result.suggestions.length === 0) {\n return { content: [{ type: \"text\" as const, text: `No suggestions found for \\`${entryId}\\` — it may already be well-connected, or no similar entries exist.` }] };\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: any) => s.graphDistance > 0).length;\n const textCount = suggestions.filter((s: any) => s.graphDistance === -1).length;\n const sourceId = resolved?.entryId ?? entryId;\n\n const lines = [\n `# Link Suggestions for ${resolvedLabel}`,\n `_${suggestions.length} potential connections (${graphCount} via graph, ${textCount} via text similarity)._`,\n \"\",\n ];\n\n // Quick Wins — top 3 highest-scoring, actionable at a glance\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:** \\`batch-relate relations=[${batchArgs.join(\",\")}]\\``);\n lines.push(\"\");\n }\n\n // Full list\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) {\n lines.push(` ${s.preview}`);\n }\n lines.push(` _${s.reasoning}_`);\n }\n }\n\n lines.push(\"\");\n lines.push(`**To link one:** \\`relate-entries from=\"${sourceId}\" to=\"{target_id}\" type=\"{type}\"\\``);\n lines.push(`**To dismiss:** \\`dismiss-suggestion from=\"${sourceId}\" to=\"{target_id}\" type=\"{type}\"\\``);\n\n return { content: [{ type: \"text\" as const, text: lines.join(\"\\n\") }] };\n }\n );\n\n server.registerTool(\n \"dismiss-suggestion\",\n {\n title: \"Dismiss Link Suggestion\",\n description:\n \"Record that a suggested link is not relevant. This negative feedback improves \" +\n \"future suggestion quality through the weekly weight-tuning cron.\\n\\n\" +\n \"Use after reviewing suggest-links output when a suggestion doesn't make sense.\",\n inputSchema: {\n from: z.string().describe(\"Source entry ID\"),\n to: z.string().describe(\"Suggested target entry ID that was not relevant\"),\n type: z.string().default(\"related_to\").describe(\"The recommended relation type that was dismissed\"),\n score: z.number().optional().describe(\"The suggestion score (from suggest-links output)\"),\n },\n annotations: { destructiveHint: false },\n },\n async ({ from, to, type, score }) => {\n requireWriteAccess();\n\n const fromEntry = await mcpQuery<any>(\"chain.getEntry\", { entryId: from });\n if (!fromEntry) {\n return { content: [{ type: \"text\" as const, text: `Entry \\`${from}\\` not found.` }] };\n }\n const toEntry = await mcpQuery<any>(\"chain.getEntry\", { entryId: to });\n if (!toEntry) {\n return { content: [{ type: \"text\" as const, text: `Entry \\`${to}\\` not found.` }] };\n }\n\n await mcpMutation(\"chain.dismissSuggestion\", {\n fromEntryId: fromEntry._id,\n suggestedEntryId: toEntry._id,\n recommendedType: type ?? \"related_to\",\n score: score ?? 0,\n });\n\n return {\n content: [{\n type: \"text\" as const,\n text: `Dismissed suggestion: ${from} → ${to} (${type}). Feedback recorded for scoring improvements.`,\n }],\n };\n }\n );\n\n server.registerTool(\n \"create-collection\",\n {\n title: \"Create Collection\",\n description:\n \"Create a new knowledge collection in the workspace. Collections define the structure \" +\n \"for entries (like Notion databases or Capacity boards). Provide a slug, name, and field schema.\\n\\n\" +\n \"Use this when setting up a workspace or when the user wants to track a new type of knowledge. \" +\n \"Use `list-collections` first to see what already exists.\\n\\n\" +\n \"**Tip:** Provide `purpose` and `navGroup` to improve sidebar placement and AI retrieval quality.\",\n inputSchema: {\n slug: z.string().describe(\"URL-safe identifier, e.g. 'glossary', 'tech-debt', 'api-endpoints'\"),\n name: z.string().describe(\"Display name, e.g. 'Glossary', 'Tech Debt', 'API Endpoints'\"),\n description: z.string().optional().describe(\"What this collection is for — helps humans and AI understand the collection\"),\n purpose: z.string().optional().describe(\"Why this collection exists — the strategic reason for tracking this knowledge\"),\n icon: z.string().optional().describe(\"Emoji icon for the collection\"),\n navGroup: z.enum([\"daily\", \"strategic\", \"governance\", \"reference\", \"collections\"]).default(\"collections\")\n .describe(\"Sidebar placement: 'daily' (operational), 'strategic' (planning), 'governance' (authority), 'reference' (lookup), 'collections' (default)\"),\n fields: z.array(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 })).describe(\"Field definitions for the collection schema\"),\n },\n annotations: { destructiveHint: false },\n },\n async ({ slug, name, description, purpose, icon, navGroup, fields }) => {\n requireWriteAccess();\n\n try {\n await mcpMutation(\"chain.createCollection\", {\n slug,\n name,\n description,\n purpose,\n icon,\n navGroup: navGroup ?? \"collections\",\n fields,\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 ?? \"collections\"}\\n` +\n `\\n**Fields:**\\n${fieldList}\\n\\n` +\n `You can now capture entries: \\`capture collection=\"${slug}\" name=\"...\" description=\"...\"\\``,\n }],\n };\n } catch (error: unknown) {\n const msg = error instanceof Error ? error.message : String(error);\n if (msg.includes(\"already exists\")) {\n return {\n content: [{\n type: \"text\" as const,\n text: `Collection \\`${slug}\\` already exists. Use \\`update-collection\\` to modify it, or choose a different slug.`,\n }],\n };\n }\n throw error;\n }\n }\n );\n\n server.registerTool(\n \"update-collection\",\n {\n title: \"Update Collection\",\n description:\n \"Update an existing collection's name, description, purpose, icon, navGroup, or field schema. \" +\n \"Only provide the fields you want to change. Use `list-collections` to see current state.\",\n inputSchema: {\n slug: z.string().describe(\"Collection slug to update, e.g. 'glossary', 'tech-debt'\"),\n name: z.string().optional().describe(\"New display name\"),\n description: z.string().optional().describe(\"New description\"),\n purpose: z.string().optional().describe(\"New purpose — why this collection exists\"),\n icon: z.string().optional().describe(\"New emoji icon\"),\n navGroup: z.enum([\"daily\", \"strategic\", \"governance\", \"reference\", \"collections\"]).optional()\n .describe(\"New sidebar placement\"),\n fields: z.array(z.object({\n key: z.string(),\n label: z.string(),\n type: z.string(),\n required: z.boolean().optional(),\n options: z.array(z.string()).optional(),\n searchable: z.boolean().optional(),\n })).optional().describe(\"Replacement field schema (replaces all fields — include existing fields you want to keep)\"),\n },\n annotations: { destructiveHint: false },\n },\n async ({ slug, name, description, purpose, icon, navGroup, fields }) => {\n requireWriteAccess();\n\n await mcpMutation(\"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 });\n\n const changes = [name && \"name\", description && \"description\", purpose && \"purpose\", icon && \"icon\", navGroup && \"navGroup\", fields && \"fields\"]\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 \\`list-collections\\` to verify the result.`,\n }],\n };\n }\n );\n\n 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 a keyword contradiction check against governance entries before committing. \" +\n \"Warnings are advisory — they do not block the commit.\\n\\n\" +\n \"Use after capture + suggest-links + relate-entries to finalize an entry.\",\n inputSchema: {\n entryId: z.string().describe(\"Entry ID to commit, e.g. 'TEN-abc123', 'GT-019'\"),\n },\n annotations: { destructiveHint: false },\n },\n async ({ entryId }) => {\n requireWriteAccess();\n\n const { runContradictionCheck } = await import(\"./smart-capture.js\");\n\n const entry = await mcpQuery<any>(\"chain.getEntry\", { entryId });\n if (!entry) {\n return {\n content: [{ type: \"text\" as const, text: `Entry \\`${entryId}\\` not found. Try search to find the right ID.` }],\n };\n }\n\n // Run contradiction check before committing\n const descField = entry.data?.description ?? entry.data?.canonical ?? entry.data?.rationale ?? \"\";\n const warnings = await runContradictionCheck(entry.name, descField);\n\n if (warnings.length > 0) {\n await recordSessionActivity({ contradictionWarning: true });\n }\n\n const result = await mcpMutation<any>(\"chain.commitEntry\", {\n entryId,\n author: getAgentSessionId() ? `agent:${getAgentSessionId()}` : undefined,\n });\n\n const docId = result?._id ?? entry._id;\n await recordSessionActivity({ entryModified: docId });\n\n const wsCtx = await getWorkspaceContext();\n let lines: string[];\n\n if (result?.status === \"proposal_created\") {\n // Consensus/role mode: proposal created, entry not yet committed\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 (warnings.length > 0) {\n lines.push(\"\");\n lines.push(\"⚠ Contradiction check: proposed entry matched existing governance entries:\");\n for (const w of warnings) {\n lines.push(`- ${w.name} (${w.collection}, ${w.entryId}) — has 'governs' relation to ${w.governsCount} entries`);\n }\n lines.push(\"Run gather-context on these entries before committing.\");\n }\n\n return { content: [{ type: \"text\" as const, text: lines.join(\"\\n\") }] };\n }\n );\n\n}\n","import { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { z } from \"zod\";\nimport { mcpQuery, mcpMutation } from \"../client.js\";\n\nexport function registerLabelTools(server: McpServer) {\n\n 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: {\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 },\n async ({ action, slug, name, color, description, parentSlug, isGroup, order, entryId }) => {\n if (action === \"list\") {\n const labels = await mcpQuery<any[]>(\"chain.listLabels\");\n\n if (labels.length === 0) {\n return { content: [{ type: \"text\" as const, text: \"No labels defined in this workspace yet.\" }] };\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 { content: [{ type: \"text\" as const, text: lines.join(\"\\n\") }] };\n }\n\n if (!slug) {\n return { content: [{ type: \"text\" as const, text: \"A `slug` is required for this action.\" }] };\n }\n\n if (action === \"create\") {\n if (!name) {\n return { content: [{ type: \"text\" as const, text: \"Cannot create a label without a name.\" }] };\n }\n\n let parentId: string | undefined;\n if (parentSlug) {\n const labels = await mcpQuery<any[]>(\"chain.listLabels\");\n const parent = labels.find((l: any) => l.slug === parentSlug);\n if (!parent) {\n return { content: [{ type: \"text\" as const, text: `Parent label \\`${parentSlug}\\` not found. Use \\`labels action=list\\` to see available groups.` }] };\n }\n parentId = parent._id;\n }\n\n await mcpMutation(\"chain.createLabel\", { slug, name, color, description, parentId, isGroup, order });\n return { content: [{ type: \"text\" as const, text: `# Label Created\\n\\n**${name}** (\\`${slug}\\`)` }] };\n }\n\n if (action === \"update\") {\n await mcpMutation(\"chain.updateLabel\", { slug, name, color, description, isGroup, order });\n return { content: [{ type: \"text\" as const, text: `# Label Updated\\n\\n\\`${slug}\\` has been updated.` }] };\n }\n\n if (action === \"delete\") {\n await mcpMutation(\"chain.deleteLabel\", { slug });\n return { content: [{ type: \"text\" as const, text: `# Label Deleted\\n\\n\\`${slug}\\` removed from all entries and deleted.` }] };\n }\n\n if (action === \"apply\" || action === \"remove\") {\n if (!entryId) {\n return { content: [{ type: \"text\" as const, text: \"An `entryId` is required for apply/remove actions.\" }] };\n }\n\n if (action === \"apply\") {\n await mcpMutation(\"chain.applyLabel\", { entryId, labelSlug: slug });\n return { content: [{ type: \"text\" as const, text: `Label \\`${slug}\\` applied to **${entryId}**.` }] };\n }\n\n await mcpMutation(\"chain.removeLabel\", { entryId, labelSlug: slug });\n return { content: [{ type: \"text\" as const, text: `Label \\`${slug}\\` removed from **${entryId}**.` }] };\n }\n\n return { content: [{ type: \"text\" as const, text: \"Unknown action.\" }] };\n }\n );\n}\n","import { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { z } from \"zod\";\nimport { mcpQuery, mcpMutation, mcpCall, getWorkspaceId, getWorkspaceContext, getAuditLog, getAgentSessionId, setSessionOriented, type AuditEntry } from \"../client.js\";\nimport { queryPlannedWork, hasPlannedWork, buildPlannedWorkSection } from \"./planned-work.js\";\n\ntype CallCategory = \"read\" | \"search\" | \"write\" | \"label\" | \"meta\";\n\nconst CALL_CATEGORIES: Record<string, CallCategory> = {\n \"chain.getEntry\": \"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.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\nexport function registerHealthTools(server: McpServer) {\n\n server.registerTool(\n \"health\",\n {\n title: \"Health Check\",\n description:\n \"Verify that Product Brain is running and can reach its backend. \" +\n \"Returns workspace status, collection count, entry count, and latency. \" +\n \"Use this to confirm connectivity before doing real work.\",\n annotations: { readOnlyHint: true },\n },\n async () => {\n const start = Date.now();\n const errors: string[] = [];\n\n let workspaceId: string | undefined;\n try {\n workspaceId = await getWorkspaceId();\n } catch (e: any) {\n errors.push(`Workspace resolution failed: ${e.message}`);\n }\n\n let collections: any[] = [];\n try {\n collections = await mcpQuery<any[]>(\"chain.listCollections\");\n } catch (e: any) {\n errors.push(`Collection fetch failed: ${e.message}`);\n }\n\n let totalEntries = 0;\n if (collections.length > 0) {\n try {\n const entries = await mcpQuery<any[]>(\"chain.listEntries\", {});\n totalEntries = entries.length;\n } catch (e: any) {\n errors.push(`Entry count failed: ${e.message}`);\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 return { content: [{ type: \"text\" as const, text: lines.join(\"\\n\") }] };\n }\n );\n\n server.registerTool(\n \"whoami\",\n {\n title: \"Session Identity\",\n description:\n \"Returns the current workspace and auth context for this MCP session. \" +\n \"Use at the start of a session to confirm you're operating on the right workspace before making writes.\",\n annotations: { readOnlyHint: true },\n },\n async () => {\n const ctx = await getWorkspaceContext();\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 { content: [{ type: \"text\" as const, text: lines.join(\"\\n\") }] };\n }\n );\n\n server.registerTool(\n \"workspace-status\",\n {\n title: \"Workspace Status\",\n description:\n \"The 'Monday morning' tool — returns workspace readiness score, specific gaps with \" +\n \"suggested next actions, and workspace stats (entries, relations, orphans, drafts).\\n\\n\" +\n \"Use this to understand how ready the workspace is, what foundational knowledge is missing, \" +\n \"and what to work on next. Great for starting a session or planning knowledge work.\",\n annotations: { readOnlyHint: true },\n },\n async () => {\n const result = await mcpQuery<any>(\"chain.workspaceReadiness\");\n\n const { score, totalChecks, passedChecks, checks, gaps, stats, governanceMode } = result;\n\n const scoreBar = \"█\".repeat(Math.round(score / 10)) + \"░\".repeat(10 - Math.round(score / 10));\n\n const lines = [\n `# Workspace Readiness: ${score}%`,\n `${scoreBar} ${passedChecks}/${totalChecks} requirements met`,\n `\\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 (action required)\");\n for (const gap of gaps) {\n lines.push(`- [ ] **${gap.label}** — ${gap.description}`);\n lines.push(` ${gap.current}/${gap.required} | _${gap.guidance}_`);\n }\n lines.push(\"\");\n }\n\n const passed = checks.filter((c: any) => c.passed);\n if (passed.length > 0) {\n lines.push(\"## Passed\");\n for (const check of passed) {\n lines.push(`- [x] **${check.label}** (${check.current}/${check.required})`);\n }\n }\n\n return { content: [{ type: \"text\" as const, text: lines.join(\"\\n\") }] };\n }\n );\n\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 annotations: { readOnlyHint: true },\n },\n async () => {\n const errors: string[] = [];\n const agentSessionId = getAgentSessionId();\n\n let wsCtx: { workspaceSlug: string; workspaceName: string; workspaceId: string; createdAt: number | null } | null = null;\n try {\n wsCtx = await getWorkspaceContext();\n } catch (e: any) {\n errors.push(`Workspace: ${e.message}`);\n }\n\n let priorSessions: any[] = [];\n if (wsCtx) {\n try {\n priorSessions = await mcpQuery<any[]>(\"agent.recentSessions\", { limit: 3 });\n } catch { /* non-critical */ }\n }\n\n let orientEntries: {\n activeGoals: any[];\n recentDecisions: any[];\n recentlySuperseded: any[];\n staleEntries: any[];\n businessRules: any[];\n architectureNotes: any[];\n activeBets: any[];\n stalenessThresholdDays: number;\n } | null = null;\n try {\n orientEntries = await mcpQuery<any>(\"chain.getOrientEntries\");\n } catch { /* non-critical */ }\n\n let openTensions: any[] = [];\n try {\n const tensions = await mcpQuery<any[]>(\"chain.listEntries\", { collectionSlug: \"tensions\" });\n openTensions = (tensions ?? []).filter((e: any) => e.status === \"draft\");\n } catch { /* non-critical */ }\n\n let readiness: any = null;\n try {\n readiness = await mcpQuery<any>(\"chain.workspaceReadiness\");\n } catch (e: any) {\n errors.push(`Readiness: ${e.message}`);\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\n // --- 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 but is only ${readiness.score}% ready.`);\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\n // --- Single next action for low-readiness ---\n if (isLowReadiness) {\n lines.push(`Readiness: ${readiness.score}% (${readiness.passedChecks}/${readiness.totalChecks}).`);\n lines.push(\"\");\n\n const gaps = readiness.gaps ?? [];\n if (gaps.length > 0) {\n const gap = gaps[0];\n const ctaMap: Record<string, string> = {\n \"strategy-vision\": \"Tell me what you're building — your vision, mission, and north star — and I'll capture it.\",\n \"architecture-layers\": \"Describe your architecture in a few sentences and I'll capture it.\",\n \"glossary-foundation\": \"What are the key terms your team uses? Tell me a few and I'll add them to the glossary.\",\n \"decisions-documented\": \"What's a recent significant decision your team made? I'll document it with the rationale.\",\n \"tensions-tracked\": \"What's a friction point or pain point you're dealing with? I'll capture it as a tension.\",\n };\n const cta = ctaMap[gap.id] ?? `Tell me about your ${gap.label.toLowerCase()} and I'll capture it.`;\n\n lines.push(\"## Recommended next step\");\n lines.push(`**${gap.label}** (${gap.current}/${gap.required})`);\n lines.push(\"\");\n lines.push(cta);\n lines.push(\"\");\n lines.push(\"_Everything stays as a draft until you confirm. Say \\\"commit\\\" or \\\"looks good\\\" to promote to the Chain._\");\n lines.push(\"\");\n\n const remainingGaps = gaps.length - 1;\n if (remainingGaps > 0 || openTensions.length > 0) {\n lines.push(`_${remainingGaps > 0 ? `${remainingGaps} more gap${remainingGaps === 1 ? \"\" : \"s\"}` : \"\"}${remainingGaps > 0 && openTensions.length > 0 ? \" and \" : \"\"}${openTensions.length > 0 ? `${openTensions.length} open tension${openTensions.length === 1 ? \"\" : \"s\"}` : \"\"} — ask \\\"show full status\\\" for details._`);\n lines.push(\"\");\n }\n }\n\n lines.push(\"_Need a collection that doesn't exist yet (e.g. audiences, personas, metrics)?_\");\n lines.push(\"_Use `create-collection` to add it, or ask me to propose collections for your domain._\");\n lines.push(\"\");\n } else if (readiness) {\n lines.push(`Readiness: ${readiness.score}% (${readiness.passedChecks}/${readiness.totalChecks}).`);\n lines.push(\"\");\n\n // Stratum-aware orient sections (priority order, ~5 entries max each)\n if (orientEntries) {\n const fmt = (e: any) => {\n const type = e.canonicalKey ?? 'generic';\n const stratum = e.stratum ?? '?';\n return `- \\`${e.entryId ?? e._id}\\` [${type} · ${stratum}] ${e.name}`;\n };\n if (orientEntries.activeBets?.length > 0) {\n lines.push(\"## Active bets\");\n orientEntries.activeBets.forEach((e) => lines.push(fmt(e)));\n lines.push(\"\");\n }\n if (orientEntries.activeGoals.length > 0) {\n lines.push(\"## Active goals\");\n orientEntries.activeGoals.forEach((e) => lines.push(fmt(e)));\n lines.push(\"\");\n }\n if (orientEntries.recentDecisions.length > 0) {\n lines.push(\"## Recent decisions\");\n orientEntries.recentDecisions.forEach((e) => lines.push(fmt(e)));\n lines.push(\"\");\n }\n if (orientEntries.recentlySuperseded.length > 0) {\n lines.push(\"## Recently superseded\");\n orientEntries.recentlySuperseded.forEach((e) => lines.push(fmt(e)));\n lines.push(\"\");\n }\n if (orientEntries.staleEntries.length > 0) {\n lines.push(\"## Needs confirmation\");\n lines.push(`_Domain stratum entries not confirmed in ${orientEntries.stalenessThresholdDays} days._`);\n orientEntries.staleEntries.forEach((e) => lines.push(fmt(e)));\n lines.push(\"\");\n }\n if (orientEntries.businessRules.length > 0) {\n lines.push(\"## Business rules\");\n orientEntries.businessRules.forEach((e) => lines.push(fmt(e)));\n lines.push(\"\");\n }\n if (orientEntries.architectureNotes.length > 0) {\n lines.push(\"## Architecture notes\");\n orientEntries.architectureNotes.forEach((e) => lines.push(fmt(e)));\n lines.push(\"\");\n }\n }\n\n const plannedWork = await queryPlannedWork();\n\n if (hasPlannedWork(plannedWork)) {\n lines.push(...buildPlannedWorkSection(plannedWork, priorSessions));\n } else {\n const briefingItems: string[] = [];\n\n if (priorSessions.length > 0) {\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 briefingItems.push(`**Last session** (${date}): ${created} created, ${modified} modified`);\n }\n\n if (readiness.gaps?.length > 0) {\n briefingItems.push(`**${readiness.gaps.length} gap${readiness.gaps.length === 1 ? \"\" : \"s\"}** remaining`);\n }\n\n if (briefingItems.length > 0) {\n lines.push(\"## Briefing\");\n for (const item of briefingItems) {\n lines.push(`- ${item}`);\n }\n lines.push(\"\");\n }\n }\n\n lines.push(\"What would you like to work on?\");\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 if (agentSessionId) {\n try {\n await mcpCall(\"agent.markOriented\", { sessionId: agentSessionId });\n setSessionOriented(true);\n\n lines.push(\"---\");\n lines.push(`Orientation complete. Session ${agentSessionId}. Write tools available.`);\n } catch {\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 mcpMutation(\"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 {\n lines.push(\"---\");\n lines.push(\"_No active agent session. Call `agent-start` to begin a tracked session._\");\n }\n\n return { content: [{ type: \"text\" as const, text: lines.join(\"\\n\") }] };\n }\n );\n\n server.registerTool(\n \"mcp-audit\",\n {\n title: \"Session Audit Log\",\n description:\n \"Show a session summary (reads, writes, searches, contributions) and the last N backend calls. \" +\n \"Useful for debugging, tracing tool behavior, and seeing what you contributed to the chain.\",\n inputSchema: {\n limit: z.number().min(1).max(50).default(20).describe(\"How many recent calls to show (max 50)\"),\n },\n annotations: { readOnlyHint: true },\n },\n async ({ limit }) => {\n const log = getAuditLog();\n const recent = log.slice(-limit);\n\n if (recent.length === 0) {\n return { content: [{ type: \"text\" as const, text: \"No calls recorded yet this session.\" }] };\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 logLines.push(`${icon} \\`${entry.fn}\\` ${entry.durationMs}ms ${entry.status}${errPart}`);\n }\n\n return {\n content: [{ type: \"text\" as const, text: `${summary}\\n\\n---\\n\\n${logLines.join(\"\\n\")}` }],\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 { mcpQuery } from \"../client.js\";\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 async function queryPlannedWork(): Promise<PlannedWork> {\n const result: PlannedWork = {\n uncommittedDrafts: [],\n inProgressEntries: [],\n openTensions: [],\n };\n\n try {\n const allEntries = await mcpQuery<any[]>(\"chain.listEntries\", {});\n if (!allEntries) return result;\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 if (collection === \"tensions\") {\n result.openTensions.push({ name: entry.name, entryId: entry.entryId ?? entry._id });\n } else {\n result.uncommittedDrafts.push({ name: entry.name, collection });\n }\n }\n\n if (entry.status === \"in-progress\" || entry.status === \"in_progress\") {\n result.inProgressEntries.push({\n name: entry.name,\n collection,\n entryId: entry.entryId ?? entry._id,\n });\n }\n }\n } catch {\n // Non-critical — return empty planned work\n }\n\n return result;\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\nexport function buildPlannedWorkSection(\n work: PlannedWork,\n priorSessions: any[],\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 uncommitted draft\" : `${count} uncommitted drafts`;\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)) {\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 lines.push(\"\");\n return lines;\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 { mcpQuery, mcpMutation } from \"../client.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// ── Project Root Resolution ────────────────────────────────────────────\n\nfunction resolveProjectRoot(): string | null {\n const candidates = [\n process.env.WORKSPACE_PATH,\n process.cwd(),\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// ── 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 function registerVerifyTools(server: McpServer) {\n 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: {\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 annotations: { readOnlyHint: false },\n },\n async ({ collection, mode }) => {\n const projectRoot = resolveProjectRoot();\n if (!projectRoot) {\n return {\n content: [{\n type: \"text\" as const,\n text: \"# 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 }],\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 mcpQuery<any[]>(\"chain.listEntries\", { collectionSlug: collection });\n\n if (scopedEntries.length === 0) {\n return {\n content: [{ type: \"text\" as const, text: `No entries found in \\`${collection}\\`. Nothing to verify.` }],\n };\n }\n\n // Build cross-reference lookup: fetch all entries to check relatedRules\n let allEntryIds: Set<string>;\n try {\n const allEntries = await mcpQuery<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 (const entry of scopedEntries) {\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 // ── Fix mode: update aligned → drifted ──\n const fixes: 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 await mcpMutation(\"chain.updateEntry\", {\n entryId: entry.entryId,\n data: { codeMapping: updated },\n });\n fixes.push(entry.entryId);\n }\n }\n\n const report = formatTrustReport(\n collection, scopedEntries.length,\n mappingChecks, refChecks, fixes, mode,\n schema.size, projectRoot,\n );\n\n return { content: [{ type: \"text\" as const, text: report }] };\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 { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { z } from \"zod\";\nimport { mcpQuery, mcpMutation } from \"../client.js\";\n\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 mcpQuery<any[]>(\"chain.listCollections\");\n const existing = collections.find((c: any) => c.slug === COLLECTION_SLUG);\n\n if (existing) {\n if (!existing.defaultCanonicalKey) {\n await mcpMutation(\"chain.updateCollection\", {\n slug: COLLECTION_SLUG,\n defaultCanonicalKey: ARCHITECTURE_CANONICAL_KEY,\n });\n }\n return;\n }\n\n await mcpMutation(\"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 mcpQuery<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, \"&amp;\").replace(/</g, \"&lt;\").replace(/>/g, \"&gt;\").replace(/\"/g, \"&quot;\");\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/mcpKnowledge.ts, 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, circles, principles, policies, decisions, proposals, business rules\", filePaths: \"src/routes/roles/, src/routes/circles/, src/routes/decisions/, src/routes/proposals/\", owner: \"Governance\", rationale: \"Features layer because these are governance PAGES — list views and detail views for roles, circles, 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 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: {\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 annotations: { readOnlyHint: true },\n },\n 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 };\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 const html = renderArchitectureHtml(layers, nodes, flows, templateName);\n\n return {\n content: [\n { type: \"text\" as const, text },\n { type: \"resource\" as const, resource: { uri: `ui://product-os/architecture`, mimeType: \"text/html\", text: html } },\n ],\n };\n }\n\n if (action === \"explore\") {\n if (!layer) return { content: [{ type: \"text\" as const, text: \"A `layer` is required for explore.\" }] };\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 { content: [{ type: \"text\" as const, text: `Layer \"${layer}\" not found. Available layers: ${available}` }] };\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 };\n }\n\n if (action === \"flow\") {\n if (!flow) return { content: [{ type: \"text\" as const, text: \"A `flow` name or entry ID is required.\" }] };\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 { content: [{ type: \"text\" as const, text: `Flow \"${flow}\" not found. Available flows: ${available}` }] };\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 { content: [{ type: \"text\" as const, text: lines.join(\"\\n\") }] };\n }\n\n return { content: [{ type: \"text\" as const, text: \"Unknown action.\" }] };\n }\n );\n\n // ─── architecture-admin: seed and health check ──────────────────────\n\n 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: {\n action: z.enum([\"seed\", \"check\"])\n .describe(\"Action: seed default architecture data, or check dependency health\"),\n },\n },\n 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\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 await mcpMutation(\"chain.updateEntry\", { entryId: seed.entryId, data: mergedData });\n updated++;\n } else {\n unchanged++;\n }\n continue;\n }\n await mcpMutation(\"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 created++;\n }\n\n return {\n content: [{\n type: \"text\" as const,\n text: `# 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 };\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 };\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 { content: [{ type: \"text\" as const, text: formatScanReport(result) }] };\n }\n\n return { content: [{ type: \"text\" as const, text: \"Unknown action.\" }] };\n }\n );\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 resolveProjectRoot(): string | null {\n const candidates = [\n process.env.WORKSPACE_PATH,\n process.cwd(),\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\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 * Workflow tools — ARCH-node-mcp (Core layer)\n * Chain: FEAT-MCP-001 (MCP Server)\n *\n * Tools for discovering and running Chainwork workflows via MCP.\n * The actual facilitation happens in the agent — these tools provide\n * the definitions, state tracking, and chain integration.\n */\n\nimport { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { z } from \"zod\";\nimport { mcpMutation } from \"../client.js\";\nimport {\n getWorkflow,\n listWorkflows,\n type WorkflowDefinition,\n} from \"../workflows/definitions.js\";\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\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**: Creates entries in \\`${wf.kbOutputCollection}\\` collection.\\n` +\n `_Use the \\`run-workflow\\` prompt with workflow=\"${wf.id}\" to start._`\n );\n}\n\nexport function registerWorkflowTools(server: McpServer) {\n\n server.registerTool(\n \"list-workflows\",\n {\n title: \"List Workflows\",\n description:\n \"List all available Chainwork workflows — retro, shape-a-bet, IDM, etc. \" +\n \"Each workflow is a structured multi-round facilitation ceremony that the agent runs in Facilitator Mode. \" +\n \"Use the `run-workflow` prompt to actually launch one.\",\n annotations: { readOnlyHint: true },\n },\n async () => {\n const workflows = listWorkflows();\n\n if (workflows.length === 0) {\n return {\n content: [{\n type: \"text\" as const,\n text: \"No workflows registered yet. Check back after the workflow definitions are configured.\",\n }],\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. Use the \\`run-workflow\\` prompt to launch one.\\n\\n` +\n `---\\n\\n${cards}`,\n }],\n };\n },\n );\n\n server.registerTool(\n \"workflow-checkpoint\",\n {\n title: \"Workflow Checkpoint\",\n description:\n \"Record the output of a workflow round. Captures the round's data to the Chain \" +\n \"as a structured entry. Use this during Facilitator Mode after completing each round \" +\n \"to persist progress — so if the conversation is interrupted, work is not lost.\\n\\n\" +\n \"At workflow completion, this tool can also generate the final summary entry.\",\n inputSchema: {\n workflowId: z.string().describe(\"Workflow ID (e.g., 'retro')\"),\n roundId: z.string().describe(\"Round ID (e.g., 'what-went-well')\"),\n output: z.string().describe(\"The round's output — synthesized by the facilitator from the conversation\"),\n isFinal: z.boolean().optional().describe(\n \"If true, this is the final checkpoint and triggers the summary chain entry creation\",\n ),\n summaryName: z.string().optional().describe(\n \"Name for the final chain entry (required when isFinal=true)\",\n ),\n summaryDescription: z.string().optional().describe(\n \"Full description/rationale for the final chain entry (required when isFinal=true)\",\n ),\n },\n annotations: { destructiveHint: false },\n },\n async ({ workflowId, roundId, output, isFinal, summaryName, summaryDescription }) => {\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 };\n }\n\n const round = wf.rounds.find((r) => r.id === roundId);\n if (!round) {\n return {\n content: [{\n type: \"text\" as const,\n text:\n `Round \"${roundId}\" not found in workflow \"${workflowId}\". ` +\n `Available rounds: ${wf.rounds.map((r) => r.id).join(\", \")}.\\n\\n` +\n `This checkpoint was NOT saved. The conversation context is preserved — continue facilitating.`,\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 (isFinal && summaryName && summaryDescription) {\n try {\n const entryId = await mcpMutation<string>(\"chain.createEntry\", {\n collectionSlug: wf.kbOutputCollection,\n name: summaryName,\n status: \"draft\",\n data: {\n [wf.kbOutputTemplate.descriptionField]: summaryDescription,\n workflowType: wf.id,\n completedRound: roundId,\n date: new Date().toISOString().split(\"T\")[0],\n },\n createdBy: `workflow:${wf.id}`,\n });\n\n lines.push(\n `**Entry Committed**: \\`${entryId}\\``,\n `Collection: \\`${wf.kbOutputCollection}\\``,\n `Name: ${summaryName}`,\n \"\",\n `The retro is now committed to the Chain. `,\n `Use \\`suggest-links\\` on this entry to connect it to related knowledge.`,\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 retro output is preserved in this conversation. `,\n `You can manually create the entry later using \\`capture\\` with:`,\n `- Collection: \\`${wf.kbOutputCollection}\\``,\n `- Name: ${summaryName}`,\n `- Description: (copy from the conversation summary above)`,\n );\n }\n } else {\n lines.push(\n `Round ${round.num} output recorded.`,\n `Output: ${output.substring(0, 200)}${output.length > 200 ? \"...\" : \"\"}`,\n );\n\n const currentIdx = wf.rounds.findIndex((r) => r.id === roundId);\n if (currentIdx < wf.rounds.length - 1) {\n const next = wf.rounds[currentIdx + 1];\n lines.push(\n \"\",\n `**Next**: Round ${next.num} — ${next.label}`,\n `_${next.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\n return { content: [{ type: \"text\" as const, text: lines.join(\"\\n\") }] };\n },\n );\n}\n","/**\n * Chainwork Workflow Definitions — ARCH-node-mcp (Core layer)\n * Chain: GT-006 (MCP), FEAT-MCP-001\n *\n * Each workflow is a typed chain of rounds with facilitation instructions.\n * The agent uses these to drive structured conversations in Facilitator Mode.\n */\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: \"freetext\" | \"list\" | \"choice\" | \"structured\";\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\n// ── Retro Workflow ──────────────────────────────────────────────────────────\n\nconst RETRO_WORKFLOW: WorkflowDefinition = {\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 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. **Commit to the Chain** at the end using the Product OS capture tool.\n8. **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. Ask if they want to commit this to the Chain. If yes, use capture to create a decision/tension entry. 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 kbOutputCollection: \"decisions\",\n kbOutputTemplate: {\n nameTemplate: \"Retro: {scope} — {date}\",\n descriptionField: \"rationale\",\n },\n\n errorRecovery: `If anything goes wrong during the retro:\n\n1. **MCP tool failure**: Skip the chain commit step. Summarize everything in the conversation instead. Suggest the participant runs \\`capture\\` manually later.\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.\n\nThe retro must never fail silently. Always communicate state.`,\n};\n\n// ── Workflow Registry ───────────────────────────────────────────────────────\n\nconst WORKFLOWS = new Map<string, WorkflowDefinition>([\n [\"retro\", RETRO_WORKFLOW],\n]);\n\nexport function getWorkflow(id: string): WorkflowDefinition | undefined {\n return WORKFLOWS.get(id);\n}\n\nexport function listWorkflows(): WorkflowDefinition[] {\n return Array.from(WORKFLOWS.values());\n}\n\nexport function getWorkflowIds(): string[] {\n return Array.from(WORKFLOWS.keys());\n}\n","/**\n * Agent session tools — lifecycle management for agent persistent memory.\n * Chain: PB-TEN-001 (AI starts from zero every session)\n *\n * agent-start: Explicit session start. Returns identity string.\n * agent-close: Explicit session close. Blocks writes after close.\n * agent-status: Check current session state.\n */\n\nimport { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport {\n getWorkspaceContext,\n startAgentSession,\n closeAgentSession,\n getAgentSessionId,\n isSessionOriented,\n getApiKeyScope,\n mcpCall,\n} from \"../client.js\";\n\nexport function registerSessionTools(server: McpServer): void {\n server.registerTool(\n \"agent-start\",\n {\n title: \"Start Agent Session\",\n description:\n \"Start an agent session. Creates a tracked session for this workspace with full attribution. \" +\n \"If a session is already active, it gets superseded (graceful handover). \" +\n \"Write tools are available after calling orient.\",\n annotations: { readOnlyHint: false },\n },\n async () => {\n try {\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 return { content: [{ type: \"text\" as const, text: lines.join(\"\\n\") }] };\n } catch (err: any) {\n return {\n content: [{ type: \"text\" as const, text: `Failed to start agent session: ${err.message}` }],\n isError: true,\n };\n }\n },\n );\n\n server.registerTool(\n \"agent-close\",\n {\n title: \"Close Agent Session\",\n description:\n \"Close the current agent session. Records structured session data (entries created, \" +\n \"modified, relations, gate results). After this, write tools are blocked even if \" +\n \"the MCP connection stays open.\",\n annotations: { readOnlyHint: false },\n },\n async () => {\n try {\n const sessionId = getAgentSessionId();\n if (!sessionId) {\n return {\n content: [{ type: \"text\" as const, text: \"No active agent session to close.\" }],\n };\n }\n\n const session = await mcpCall<Record<string, unknown>>(\"agent.getSession\", {\n sessionId,\n });\n\n await closeAgentSession();\n\n const lines: string[] = [\n `Session ${sessionId} closed.`,\n \"\",\n ];\n\n if (session) {\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 const gates = (session.gateFailures as number) ?? 0;\n const warnings = (session.contradictionWarnings as number) ?? 0;\n\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 return { content: [{ type: \"text\" as const, text: lines.join(\"\\n\") }] };\n } catch (err: any) {\n return {\n content: [{ type: \"text\" as const, text: `Failed to close agent session: ${err.message}` }],\n isError: true,\n };\n }\n },\n );\n\n server.registerTool(\n \"agent-status\",\n {\n title: \"Agent Session Status\",\n description:\n \"Check the current agent session status — whether a session is active, \" +\n \"whether orientation is complete, and session activity so far.\",\n annotations: { readOnlyHint: true },\n },\n async () => {\n try {\n const sessionId = getAgentSessionId();\n if (!sessionId) {\n return {\n content: [{ type: \"text\" as const, text: \"No active agent session. Call `agent-start` to begin.\" }],\n };\n }\n\n const session = await mcpCall<Record<string, unknown>>(\"agent.getSession\", {\n sessionId,\n });\n\n if (!session) {\n return {\n content: [{ type: \"text\" as const, text: \"Session ID cached but not found in Convex. Call `agent-start` to create a new session.\" }],\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 return { content: [{ type: \"text\" as const, text: lines.join(\"\\n\") }] };\n } catch (err: any) {\n return {\n content: [{ type: \"text\" as const, text: `Failed to get session status: ${err.message}` }],\n isError: true,\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 { mcpQuery, mcpMutation, getWorkspaceContext } from \"../client.js\";\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 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: {\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 },\n async ({ action, chainEntryId, title, chainTypeId, description, linkId, content, status, author }) => {\n if (action === \"create\") {\n if (!title) return { content: [{ type: \"text\" as const, text: \"A `title` is required to create a process.\" }] };\n\n const result = await mcpMutation<{ _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 };\n }\n\n if (action === \"get\") {\n if (!chainEntryId) return { content: [{ type: \"text\" as const, text: \"A `chainEntryId` is required.\" }] };\n\n const chain = await mcpQuery<any>(\"gitchain.getChain\", { chainEntryId });\n if (!chain) {\n return { content: [{ type: \"text\" as const, text: `Process \"${chainEntryId}\" not found.` }] };\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:** ${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 };\n }\n\n if (action === \"list\") {\n const chains = await mcpQuery<any[]>(\"gitchain.listChains\", {\n chainTypeId,\n status,\n });\n\n if (chains.length === 0) {\n return { content: [{ type: \"text\" as const, text: \"No processes found. Use `chain action=create` to create one.\" }] };\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 { content: [{ type: \"text\" as const, text: `# Chains (${chains.length})\\n\\n${formatted}` }] };\n }\n\n if (action === \"edit\") {\n if (!chainEntryId) return { content: [{ type: \"text\" as const, text: \"A `chainEntryId` is required.\" }] };\n if (!linkId) return { content: [{ type: \"text\" as const, text: \"A `linkId` is required (e.g. problem, insight, choice, action, outcome).\" }] };\n if (!content) return { content: [{ type: \"text\" as const, text: \"The `content` for the link is required.\" }] };\n\n const result = await mcpMutation<{\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 };\n }\n\n return { content: [{ type: \"text\" as const, text: \"Unknown action.\" }] };\n }\n );\n\n // ─── chain-version: versioning operations ───────────────────────────\n\n 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: {\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 annotations: { readOnlyHint: false },\n },\n async ({ action, chainEntryId, commitMessage, versionA, versionB, toVersion, author }) => {\n if (action === \"commit\") {\n if (!commitMessage) return { content: [{ type: \"text\" as const, text: \"A `commitMessage` is required.\" }] };\n\n const result = await mcpMutation<{\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 };\n }\n\n if (action === \"list\") {\n const commits = await mcpQuery<any[]>(\"gitchain.listCommits\", { chainEntryId });\n\n if (commits.length === 0) {\n return { content: [{ type: \"text\" as const, text: `No commits found for chain \"${chainEntryId}\". Use \\`chain-version action=commit\\` to create the first snapshot.` }] };\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 { content: [{ type: \"text\" as const, text: `# Commits for ${chainEntryId} (${commits.length})\\n\\n${formatted}` }] };\n }\n\n if (action === \"diff\") {\n if (versionA == null || versionB == null) {\n return { content: [{ type: \"text\" as const, text: \"Both `versionA` and `versionB` are required for diff.\" }] };\n }\n\n const diff = await mcpMutation<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 { content: [{ type: \"text\" as const, text }] };\n }\n\n if (action === \"revert\") {\n if (toVersion == null) return { content: [{ type: \"text\" as const, text: \"A `toVersion` is required for revert.\" }] };\n\n const result = await mcpMutation<{\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 };\n }\n\n if (action === \"history\") {\n const history = await mcpQuery<any[]>(\"gitchain.getHistory\", { chainEntryId });\n\n if (history.length === 0) {\n return { content: [{ type: \"text\" as const, text: `No history found for chain \"${chainEntryId}\".` }] };\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 { content: [{ type: \"text\" as const, text: `# History for ${chainEntryId} (${history.length} events)\\n\\n${formatted}` }] };\n }\n\n return { content: [{ type: \"text\" as const, text: \"Unknown action.\" }] };\n }\n );\n\n // ─── chain-branch: branching operations ─────────────────────────────\n\n 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: {\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 },\n async ({ action, chainEntryId, branchName, strategy, author }) => {\n if (action === \"create\") {\n const result = await mcpMutation<{\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 };\n }\n\n if (action === \"list\") {\n const branches = await mcpMutation<any[]>(\"gitchain.listBranches\", { chainEntryId });\n\n if (branches.length === 0) {\n return { content: [{ type: \"text\" as const, text: `No branches found for chain \"${chainEntryId}\".` }] };\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 { content: [{ type: \"text\" as const, text: `# Branches for ${chainEntryId} (${branches.length})\\n\\n${formatted}` }] };\n }\n\n if (action === \"merge\") {\n if (!branchName) return { content: [{ type: \"text\" as const, text: \"A `branchName` is required for merge.\" }] };\n\n const result = await mcpMutation<{\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 };\n }\n\n if (action === \"conflicts\") {\n if (!branchName) return { content: [{ type: \"text\" as const, text: \"A `branchName` is required for conflict check.\" }] };\n\n const result = await mcpMutation<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 };\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 };\n }\n\n return { content: [{ type: \"text\" as const, text: \"Unknown action.\" }] };\n }\n );\n\n // ─── chain-review: quality gate and comments ────────────────────────\n\n 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: {\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 annotations: { readOnlyHint: false },\n },\n async ({ action, chainEntryId, commitMessage, versionNumber, linkId, body, commentId, author }) => {\n if (action === \"gate\") {\n const gate = await mcpQuery<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 };\n }\n\n if (action === \"comment\") {\n if (!versionNumber) return { content: [{ type: \"text\" as const, text: \"A `versionNumber` is required.\" }] };\n if (!body) return { content: [{ type: \"text\" as const, text: \"A `body` is required.\" }] };\n\n const result = await mcpMutation<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 };\n }\n\n if (action === \"resolve-comment\") {\n if (!commentId) return { content: [{ type: \"text\" as const, text: \"A `commentId` is required.\" }] };\n await mcpMutation(\"gitchain.resolveComment\", { commentId });\n return { content: [{ type: \"text\" as const, text: `Comment resolved.` }] };\n }\n\n if (action === \"list-comments\") {\n const comments = await mcpMutation<any[]>(\"gitchain.listComments\", {\n chainEntryId, versionNumber,\n });\n\n if (comments.length === 0) {\n return { content: [{ type: \"text\" as const, text: `No comments found for chain \"${chainEntryId}\"${versionNumber ? ` v${versionNumber}` : \"\"}.` }] };\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 };\n }\n\n return { content: [{ type: \"text\" as const, text: \"Unknown action.\" }] };\n }\n );\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 { mcpQuery, mcpMutation, getWorkspaceContext } from \"../client.js\";\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 // ─── map: CRUD operations ──────────────────────────────────────────\n\n 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: {\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 },\n async ({ action, mapEntryId, title, templateId, description, slotIds, status }) => {\n if (action === \"create\") {\n if (!title) {\n return {\n content: [\n { type: \"text\" as const, text: \"A `title` is required to create a map.\" },\n ],\n };\n }\n\n const result = await mcpMutation<{ _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 };\n }\n\n if (action === \"get\") {\n if (!mapEntryId) {\n return {\n content: [{ type: \"text\" as const, text: \"A `mapEntryId` is required.\" }],\n };\n }\n\n const map = await mcpQuery<any>(\"maps.getMap\", { mapEntryId });\n if (!map) {\n return {\n content: [{ type: \"text\" as const, text: `Map \"${mapEntryId}\" not found.` }],\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:** ${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 };\n }\n\n if (action === \"list\") {\n const maps = await mcpQuery<any[]>(\"maps.listMaps\", {\n templateId: templateId !== \"lean-canvas\" ? templateId : undefined,\n status,\n });\n\n if (!maps || maps.length === 0) {\n return {\n content: [\n {\n type: \"text\" as const,\n text: \"No maps found. Create one with `map action=create title=\\\"My Canvas\\\"`.\",\n },\n ],\n };\n }\n\n const lines = maps.map(\n (m: any) =>\n `- **${m.name}** (\\`${m.entryId}\\`) — ${m.templateId}, ${m.completionScore}% complete, v${m.currentVersion}`\n );\n\n return {\n content: [\n {\n type: \"text\" as const,\n text: `# Maps (${maps.length})\\n\\n${lines.join(\"\\n\")}`,\n },\n ],\n };\n }\n\n return {\n content: [{ type: \"text\" as const, text: `Unknown action: ${action}` }],\n };\n }\n );\n\n // ─── map-slot: manage ingredients in slots ─────────────────────────\n\n 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: {\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 },\n async ({\n action,\n mapEntryId,\n slotId,\n ingredientEntryId,\n newIngredientEntryId,\n label,\n author,\n }) => {\n if (action === \"list\") {\n const map = await mcpQuery<any>(\"maps.getMap\", { mapEntryId });\n if (!map) {\n return {\n content: [{ type: \"text\" as const, text: `Map \"${mapEntryId}\" not found.` }],\n };\n }\n\n if (slotId && map.slots[slotId]) {\n return {\n content: [\n {\n type: \"text\" as const,\n text:\n `# Slot: ${slotId}\\n\\n` +\n (map.slots[slotId].length === 0\n ? \"(empty)\"\n : map.slots[slotId]\n .map(\n (r: any) =>\n `- **${r.ingredientName ?? r.entryId}** (\\`${r.entryId}\\`)${r.pinnedVersion ? ` v${r.pinnedVersion}` : \"\"}`\n )\n .join(\"\\n\")),\n },\n ],\n };\n }\n\n return {\n content: [\n { type: \"text\" as const, text: `## All Slots\\n\\n${slotSummary(map.slots)}` },\n ],\n };\n }\n\n if (action === \"add\") {\n if (!slotId || !ingredientEntryId) {\n return {\n content: [\n {\n type: \"text\" as const,\n text: \"Both `slotId` and `ingredientEntryId` are required for add.\",\n },\n ],\n };\n }\n\n await mcpMutation(\"maps.addToSlot\", {\n mapEntryId,\n slotId,\n ingredientEntryId,\n label,\n author,\n });\n\n return {\n content: [\n {\n type: \"text\" as const,\n text: `Added \\`${ingredientEntryId}\\` to slot \"${slotId}\" on map \\`${mapEntryId}\\`.`,\n },\n ],\n };\n }\n\n if (action === \"remove\") {\n if (!slotId || !ingredientEntryId) {\n return {\n content: [\n {\n type: \"text\" as const,\n text: \"Both `slotId` and `ingredientEntryId` are required for remove.\",\n },\n ],\n };\n }\n\n await mcpMutation(\"maps.removeFromSlot\", {\n mapEntryId,\n slotId,\n ingredientEntryId,\n author,\n });\n\n return {\n content: [\n {\n type: \"text\" as const,\n text: `Removed \\`${ingredientEntryId}\\` from slot \"${slotId}\" on map \\`${mapEntryId}\\`.`,\n },\n ],\n };\n }\n\n if (action === \"replace\") {\n if (!slotId || !ingredientEntryId || !newIngredientEntryId) {\n return {\n content: [\n {\n type: \"text\" as const,\n text: \"`slotId`, `ingredientEntryId`, and `newIngredientEntryId` are required for replace.\",\n },\n ],\n };\n }\n\n await mcpMutation(\"maps.replaceInSlot\", {\n mapEntryId,\n slotId,\n oldIngredientEntryId: ingredientEntryId,\n newIngredientEntryId,\n label,\n author,\n });\n\n return {\n content: [\n {\n type: \"text\" as const,\n text: `Replaced \\`${ingredientEntryId}\\` with \\`${newIngredientEntryId}\\` in slot \"${slotId}\".`,\n },\n ],\n };\n }\n\n return {\n content: [{ type: \"text\" as const, text: `Unknown action: ${action}` }],\n };\n }\n );\n\n // ─── map-version: commit, list history, diff ───────────────────────\n\n 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: {\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 },\n async ({ action, mapEntryId, commitMessage, author }) => {\n if (action === \"commit\") {\n const result = await mcpMutation<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 };\n }\n\n if (action === \"list\" || action === \"history\") {\n const commits = await mcpQuery<any[]>(\"maps.listMapCommits\", {\n mapEntryId,\n });\n\n if (!commits || commits.length === 0) {\n return {\n content: [\n {\n type: \"text\" as const,\n text: `No commits yet for map \\`${mapEntryId}\\`. Use \\`map-version action=commit\\` to create the first snapshot.`,\n },\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 ? `\\n Slots changed: ${c.slotsModified.join(\", \")}`\n : \"\")\n );\n\n return {\n content: [\n {\n type: \"text\" as const,\n text: `# Map History: \\`${mapEntryId}\\` (${commits.length} commits)\\n\\n${lines.join(\"\\n\")}`,\n },\n ],\n };\n }\n\n return {\n content: [{ type: \"text\" as const, text: `Unknown action: ${action}` }],\n };\n }\n );\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: {\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 },\n async ({ mapEntryId, slotId, query }) => {\n const map = await mcpQuery<any>(\"maps.getMap\", { mapEntryId });\n if (!map) {\n return {\n content: [{ type: \"text\" as const, text: `Map \"${mapEntryId}\" not found.` }],\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 return {\n content: [\n {\n type: \"text\" as const,\n text: slotId\n ? `Slot \"${slotId}\" already has ingredients.`\n : \"All slots have ingredients. Nothing to suggest.\",\n },\n ],\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 mcpQuery<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 };\n }\n );\n}\n","/**\n * `start` tool — the unified MCP entry point for Product Brain.\n *\n * Freshness detection:\n * - Workspace is set up (has non-system entries): runs orient-style response\n * - Workspace is fresh (no entries or only system entries): runs guided setup\n *\n * `orient` continues to exist unchanged for backward compatibility.\n * `start` calls orient internally for the \"set up\" path.\n */\n\nimport { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { z } from \"zod\";\nimport {\n mcpQuery,\n mcpCall,\n getWorkspaceContext,\n getAgentSessionId,\n setSessionOriented,\n} from \"../client.js\";\nimport { listPresets, getPreset } from \"../presets/collections.js\";\nimport { queryPlannedWork, hasPlannedWork, buildPlannedWorkSection } from \"./planned-work.js\";\n\nexport function registerStartTools(server: McpServer) {\n server.registerTool(\n \"start\",\n {\n title: \"Start Product Brain\",\n description:\n \"The zero-friction entry point. Say 'start PB' to begin.\\n\\n\" +\n \"- **Fresh workspace**: asks what you're building, seeds tailored collections, \" +\n \"and gets you ready to capture knowledge immediately.\\n\" +\n \"- **Existing workspace**: returns readiness score, recent activity, open tensions, \" +\n \"and suggested next actions (same as orient).\\n\\n\" +\n \"Use this as your first call. Replaces the need to call orient, workspace-status, \" +\n \"or health separately.\",\n inputSchema: {\n preset: z\n .string()\n .optional()\n .describe(\n \"Collection preset ID to seed (e.g. 'software-product', 'content-business', 'agency', 'saas-api', 'general'). \" +\n \"Only used for fresh workspaces. If omitted on a fresh workspace, returns the preset menu.\"\n ),\n },\n annotations: { readOnlyHint: false },\n },\n async ({ preset }) => {\n const errors: string[] = [];\n const agentSessionId = getAgentSessionId();\n\n let wsCtx: {\n workspaceSlug: string;\n workspaceName: string;\n workspaceId: string;\n } | null = null;\n try {\n wsCtx = await getWorkspaceContext();\n } catch (e: any) {\n errors.push(`Workspace: ${e.message}`);\n }\n\n if (!wsCtx) {\n return {\n content: [\n {\n type: \"text\" as const,\n 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 },\n ],\n };\n }\n\n const isFresh = await detectFreshWorkspace();\n\n if (isFresh && !preset) {\n return { content: [{ type: \"text\" as const, text: buildPresetMenu(wsCtx) }] };\n }\n\n if (isFresh && preset) {\n return { content: [{ type: \"text\" as const, text: await seedPreset(wsCtx, preset, agentSessionId) }] };\n }\n\n // Workspace is set up — run orient-style response\n return { content: [{ type: \"text\" as const, text: await buildOrientResponse(wsCtx, agentSessionId, errors) }] };\n }\n );\n}\n\nasync function detectFreshWorkspace(): Promise<boolean> {\n try {\n const entries = await mcpQuery<any[]>(\"chain.listEntries\", {});\n const nonSystem = (entries ?? []).filter((e: any) => e.stratum !== 'system');\n return nonSystem.length === 0;\n } catch {\n return false;\n }\n}\n\nfunction buildPresetMenu(wsCtx: { workspaceName: string; workspaceSlug: string }): string {\n const presets = listPresets();\n const lines = [\n `# Welcome to ${wsCtx.workspaceName}`,\n \"\",\n \"Your workspace is fresh — let's get it set up together.\",\n \"\",\n \"**Tell me: what are you building?** Describe it in a sentence or two and I'll help you \" +\n \"pick the right structure. Or choose a preset to start from:\",\n \"\",\n ];\n\n for (const p of presets) {\n lines.push(`- **${p.name}** (\\`${p.id}\\`) — ${p.description} (${p.collectionCount} collections)`);\n }\n\n lines.push(\n \"\",\n 'Call `start` again with your choice, e.g.: `start preset=\"software-product\"`',\n \"\",\n \"_These are starting points. You can add, remove, or customize collections at any time \" +\n \"using `create-collection` and `update-collection`._\",\n );\n\n return lines.join(\"\\n\");\n}\n\nasync function seedPreset(\n wsCtx: { workspaceName: string; workspaceSlug: string },\n presetId: string,\n agentSessionId: string | null,\n): Promise<string> {\n const preset = getPreset(presetId);\n if (!preset) {\n return (\n `Preset \"${presetId}\" not found.\\n\\n` +\n `Available presets: ${listPresets().map((p) => `\\`${p.id}\\``).join(\", \")}`\n );\n }\n\n const seeded: string[] = [];\n const skipped: string[] = [];\n\n for (const col of preset.collections) {\n try {\n await mcpCall(\"chain.createCollection\", {\n slug: col.slug,\n name: col.name,\n description: col.description,\n icon: col.icon,\n fields: col.fields,\n stratum: 'working',\n createdBy: \"preset:\" + presetId,\n });\n seeded.push(col.name);\n } catch {\n skipped.push(`${col.name} (already exists)`);\n }\n }\n\n if (agentSessionId) {\n try {\n await mcpCall(\"agent.markOriented\", { sessionId: agentSessionId });\n setSessionOriented(true);\n } catch { /* non-critical */ }\n }\n\n const lines = [\n `# ${wsCtx.workspaceName} is ready`,\n \"\",\n `Seeded **${preset.name}** preset with ${seeded.length} collection${seeded.length === 1 ? \"\" : \"s\"}:`,\n \"\",\n ];\n\n for (const name of seeded) {\n lines.push(`- ${name}`);\n }\n\n if (skipped.length > 0) {\n lines.push(\"\", \"Skipped (already exist):\");\n for (const name of skipped) {\n lines.push(`- ${name}`);\n }\n }\n\n lines.push(\n \"\",\n \"## Let's activate your workspace\",\n \"\",\n \"I'll help you load knowledge step by step. Everything stays as a draft until you confirm it.\",\n \"\",\n \"**First:** Tell me what you're building in one or two sentences. I'll capture it as your product vision.\",\n \"\",\n \"_After that, we'll add a few key terms to your glossary and any important decisions. \" +\n \"Each entry is a draft — say \\\"commit\\\" or \\\"looks good\\\" when you're happy with it, \" +\n \"and I'll promote it to the Chain (SSOT)._\",\n \"\",\n \"You can also customize your structure anytime: `create-collection`, `update-collection`, or `list-collections`.\",\n \"\",\n \"---\",\n \"Orientation complete. Write tools are available.\",\n );\n\n return lines.join(\"\\n\");\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 pickNextAction(\n gaps: any[],\n openTensions: any[],\n priorSessions: any[],\n): { action: string; cta: string } | null {\n if (gaps.length === 0 && openTensions.length === 0) return null;\n\n // Prioritize: first gap is the highest-impact action\n if (gaps.length > 0) {\n const gap = gaps[0];\n const ctaMap: Record<string, string> = {\n \"strategy-vision\": \"Tell me what you're building — your vision, mission, and north star — and I'll capture it.\",\n \"architecture-layers\": \"Describe your architecture in a few sentences and I'll capture it.\",\n \"glossary-foundation\": \"What are the key terms your team uses? Tell me a few and I'll add them to the glossary.\",\n \"decisions-documented\": \"What's a recent significant decision your team made? I'll document it with the rationale.\",\n \"tensions-tracked\": \"What's a friction point or pain point you're dealing with? I'll capture it as a tension.\",\n };\n\n const cta = ctaMap[gap.id] ?? `Tell me about your ${gap.label.toLowerCase()} and I'll capture it.`;\n return { action: gap.label, cta };\n }\n\n if (openTensions.length > 0) {\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 return null;\n}\n\nasync function buildOrientResponse(\n wsCtx: { workspaceName: string; workspaceSlug: string; workspaceId: string },\n agentSessionId: string | null,\n errors: string[],\n): Promise<string> {\n const wsFullCtx = await getWorkspaceContext();\n const { ageDays, isNeglected } = computeWorkspaceAge(wsFullCtx.createdAt);\n\n let priorSessions: any[] = [];\n try {\n priorSessions = await mcpQuery<any[]>(\"agent.recentSessions\", { limit: 3 });\n } catch { /* non-critical */ }\n\n let openTensions: any[] = [];\n try {\n const tensions = await mcpQuery<any[]>(\"chain.listEntries\", { collectionSlug: \"tensions\" });\n openTensions = (tensions ?? []).filter((e: any) => e.status === \"draft\");\n } catch { /* non-critical */ }\n\n let readiness: any = null;\n try {\n readiness = await mcpQuery<any>(\"chain.workspaceReadiness\");\n } catch (e: any) {\n errors.push(`Readiness: ${e.message}`);\n }\n\n const lines: string[] = [];\n const isLowReadiness = readiness && readiness.score < 50;\n const isHighReadiness = readiness && readiness.score >= 50;\n\n // --- Identity ---\n lines.push(`# ${wsCtx.workspaceName}`);\n lines.push(`_Workspace \\`${wsCtx.workspaceSlug}\\` — Product Brain is healthy._`);\n lines.push(\"\");\n\n // --- New vs neglected framing ---\n if (isLowReadiness && isNeglected) {\n lines.push(`Your workspace has been around for ${ageDays} days but is only ${readiness.score}% ready.`);\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(`Readiness: ${readiness.score}%. Let's get your workspace active.`);\n lines.push(\"\");\n }\n\n // --- Single next action (low-readiness) or standup briefing (high-readiness) ---\n if (isLowReadiness) {\n const nextAction = pickNextAction(readiness.gaps ?? [], openTensions, priorSessions);\n if (nextAction) {\n lines.push(\"## Recommended next step\");\n lines.push(`**${nextAction.action}**`);\n lines.push(\"\");\n lines.push(nextAction.cta);\n lines.push(\"\");\n lines.push(\"_Everything stays as a draft until you confirm. Say \\\"commit\\\" or \\\"looks good\\\" to promote to the Chain._\");\n lines.push(\"\");\n\n const remainingGaps = (readiness.gaps ?? []).length - 1;\n if (remainingGaps > 0 || openTensions.length > 0) {\n lines.push(`_${remainingGaps > 0 ? `${remainingGaps} more gap${remainingGaps === 1 ? \"\" : \"s\"}` : \"\"}${remainingGaps > 0 && openTensions.length > 0 ? \" and \" : \"\"}${openTensions.length > 0 ? `${openTensions.length} open tension${openTensions.length === 1 ? \"\" : \"s\"}` : \"\"} — ask \\\"show full status\\\" for details._`);\n lines.push(\"\");\n }\n }\n\n lines.push(\"_Need a collection that doesn't exist yet (e.g. audiences, personas, metrics)?_\");\n lines.push(\"_Use `create-collection` to add it, or ask me to propose collections for your domain._\");\n lines.push(\"\");\n } else if (isHighReadiness) {\n if (readiness) {\n lines.push(`Readiness: ${readiness.score}% (${readiness.passedChecks}/${readiness.totalChecks}).`);\n }\n\n const plannedWork = await queryPlannedWork();\n\n if (hasPlannedWork(plannedWork)) {\n lines.push(\"\");\n lines.push(...buildPlannedWorkSection(plannedWork, priorSessions));\n } else {\n const briefingItems: string[] = [];\n\n if (priorSessions.length > 0) {\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 briefingItems.push(`**Last session** (${date}): ${created} created, ${modified} modified`);\n }\n\n if (readiness?.gaps?.length > 0) {\n briefingItems.push(`**${readiness.gaps.length} gap${readiness.gaps.length === 1 ? \"\" : \"s\"}** remaining`);\n }\n\n if (briefingItems.length > 0) {\n lines.push(\"\");\n lines.push(\"## Briefing\");\n for (const item of briefingItems) {\n lines.push(`- ${item}`);\n }\n lines.push(\"\");\n }\n }\n\n lines.push(\"What would you like to work on?\");\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 if (agentSessionId) {\n try {\n await mcpCall(\"agent.markOriented\", { sessionId: agentSessionId });\n setSessionOriented(true);\n\n lines.push(\"---\");\n lines.push(\n `Orientation complete. Session ${agentSessionId}. Write tools available.`,\n );\n } catch {\n lines.push(\"---\");\n lines.push(\"_Warning: Could not mark session as oriented. Write tools may be restricted._\");\n }\n } else {\n lines.push(\"---\");\n lines.push(\"_No active agent session. Call `agent-start` to begin a tracked session._\");\n }\n\n return lines.join(\"\\n\");\n}\n","/**\n * Collection presets — curated starter sets for common workspace types.\n * Each preset is a list of collection definitions that can be seeded\n * into a fresh workspace via the `start` flow.\n *\n * These are the seed of a future collection marketplace.\n */\n\nexport interface CollectionPresetField {\n key: string;\n label: string;\n type: string;\n required?: boolean;\n options?: string[];\n searchable?: boolean;\n}\n\nexport interface CollectionPresetDef {\n slug: string;\n name: string;\n description: string;\n icon?: string;\n fields: CollectionPresetField[];\n}\n\nexport interface CollectionPreset {\n id: string;\n name: string;\n description: string;\n collections: CollectionPresetDef[];\n}\n\nexport const COLLECTION_PRESETS: CollectionPreset[] = [\n {\n id: \"software-product\",\n name: \"Software Product\",\n description: \"For teams building software products — glossary, features, architecture, tech debt, and API endpoints\",\n collections: [\n { slug: \"glossary\", name: \"Glossary\", description: \"Canonical terminology for the product domain\", fields: [{ key: \"canonical\", label: \"Canonical\", type: \"string\", required: true, searchable: true }, { key: \"category\", label: \"Category\", type: \"select\", options: [\"Platform & Architecture\", \"Knowledge Management\", \"AI & Developer Tools\", \"Governance & Process\"] }, { key: \"confusedWith\", label: \"Confused With\", type: \"array\" }] },\n { slug: \"features\", name: \"Features\", description: \"Product features and capabilities\", fields: [{ key: \"description\", label: \"Description\", type: \"string\", required: true, searchable: true }, { key: \"scope\", label: \"Scope\", type: \"string\" }, { key: \"area\", label: \"Area\", type: \"string\" }, { key: \"status\", label: \"Status\", type: \"select\", options: [\"proposed\", \"in-progress\", \"shipped\", \"deprecated\"] }] },\n { slug: \"architecture\", name: \"Architecture\", description: \"System architecture layers and components\", fields: [{ key: \"description\", label: \"Description\", type: \"string\", required: true, searchable: true }, { key: \"layer\", label: \"Layer\", type: \"string\" }, { key: \"dependencies\", label: \"Dependencies\", type: \"array\" }] },\n { slug: \"tech-debt\", name: \"Tech Debt\", description: \"Technical debt items to track and address\", fields: [{ key: \"description\", label: \"Description\", type: \"string\", required: true, searchable: true }, { key: \"severity\", label: \"Severity\", type: \"select\", options: [\"low\", \"medium\", \"high\", \"critical\"] }, { key: \"area\", label: \"Area\", type: \"string\" }, { key: \"effort\", label: \"Effort\", type: \"select\", options: [\"small\", \"medium\", \"large\"] }] },\n { slug: \"api-endpoints\", name: \"API Endpoints\", description: \"REST/GraphQL endpoints and their contracts\", fields: [{ key: \"description\", label: \"Description\", type: \"string\", required: true, searchable: true }, { key: \"method\", label: \"Method\", type: \"select\", options: [\"GET\", \"POST\", \"PUT\", \"PATCH\", \"DELETE\"] }, { key: \"path\", label: \"Path\", type: \"string\" }, { key: \"auth\", label: \"Auth Required\", type: \"select\", options: [\"none\", \"api-key\", \"bearer\", \"session\"] }] },\n { slug: \"decisions\", name: \"Decisions\", description: \"Significant decisions with rationale and context\", fields: [{ key: \"rationale\", label: \"Rationale\", type: \"string\", required: true, searchable: true }, { key: \"date\", label: \"Date\", type: \"string\" }, { key: \"decidedBy\", label: \"Decided By\", type: \"string\" }, { key: \"alternatives\", label: \"Alternatives\", type: \"string\" }] },\n { slug: \"tensions\", name: \"Tensions\", description: \"Friction points, pain points, and unmet needs\", fields: [{ key: \"description\", label: \"Description\", type: \"string\", required: true, searchable: true }, { key: \"priority\", label: \"Priority\", type: \"select\", options: [\"low\", \"medium\", \"high\", \"critical\"] }, { key: \"severity\", label: \"Severity\", type: \"select\", options: [\"low\", \"medium\", \"high\", \"critical\"] }] },\n ],\n },\n {\n id: \"content-business\",\n name: \"Content Business\",\n description: \"For content creators, publishers, and media companies — topics, audience segments, content calendar, and brand voice\",\n collections: [\n { slug: \"glossary\", name: \"Glossary\", description: \"Industry terminology and brand language\", fields: [{ key: \"canonical\", label: \"Canonical\", type: \"string\", required: true, searchable: true }, { key: \"category\", label: \"Category\", type: \"string\" }] },\n { slug: \"topics\", name: \"Topics\", description: \"Content topics and themes\", fields: [{ key: \"description\", label: \"Description\", type: \"string\", required: true, searchable: true }, { key: \"pillar\", label: \"Content Pillar\", type: \"string\" }, { key: \"stage\", label: \"Stage\", type: \"select\", options: [\"idea\", \"researching\", \"drafting\", \"published\", \"evergreen\"] }] },\n { slug: \"audience-segments\", name: \"Audience Segments\", description: \"Target reader/viewer personas\", fields: [{ key: \"description\", label: \"Description\", type: \"string\", required: true, searchable: true }, { key: \"painPoints\", label: \"Pain Points\", type: \"string\" }, { key: \"channels\", label: \"Channels\", type: \"array\" }] },\n { slug: \"brand-voice\", name: \"Brand Voice\", description: \"Tone, style, and voice guidelines\", fields: [{ key: \"description\", label: \"Description\", type: \"string\", required: true, searchable: true }, { key: \"doThis\", label: \"Do This\", type: \"string\" }, { key: \"notThis\", label: \"Not This\", type: \"string\" }] },\n { slug: \"decisions\", name: \"Decisions\", description: \"Editorial and strategic decisions\", fields: [{ key: \"rationale\", label: \"Rationale\", type: \"string\", required: true, searchable: true }, { key: \"date\", label: \"Date\", type: \"string\" }, { key: \"decidedBy\", label: \"Decided By\", type: \"string\" }] },\n { slug: \"tensions\", name: \"Tensions\", description: \"Content gaps, audience friction, and unmet needs\", fields: [{ key: \"description\", label: \"Description\", type: \"string\", required: true, searchable: true }, { key: \"priority\", label: \"Priority\", type: \"select\", options: [\"low\", \"medium\", \"high\", \"critical\"] }] },\n ],\n },\n {\n id: \"agency\",\n name: \"Agency\",\n description: \"For agencies managing multiple clients — client profiles, project scopes, deliverables, and processes\",\n collections: [\n { slug: \"glossary\", name: \"Glossary\", description: \"Agency and client terminology\", fields: [{ key: \"canonical\", label: \"Canonical\", type: \"string\", required: true, searchable: true }, { key: \"category\", label: \"Category\", type: \"string\" }] },\n { slug: \"clients\", name: \"Clients\", description: \"Client profiles and relationship context\", fields: [{ key: \"description\", label: \"Description\", type: \"string\", required: true, searchable: true }, { key: \"industry\", label: \"Industry\", type: \"string\" }, { key: \"contact\", label: \"Primary Contact\", type: \"string\" }] },\n { slug: \"deliverables\", name: \"Deliverables\", description: \"Standard deliverable types and templates\", fields: [{ key: \"description\", label: \"Description\", type: \"string\", required: true, searchable: true }, { key: \"type\", label: \"Type\", type: \"string\" }, { key: \"estimatedHours\", label: \"Estimated Hours\", type: \"string\" }] },\n { slug: \"processes\", name: \"Processes\", description: \"Standard operating procedures and workflows\", fields: [{ key: \"description\", label: \"Description\", type: \"string\", required: true, searchable: true }, { key: \"steps\", label: \"Steps\", type: \"string\" }, { key: \"owner\", label: \"Owner\", type: \"string\" }] },\n { slug: \"decisions\", name: \"Decisions\", description: \"Strategic and operational decisions\", fields: [{ key: \"rationale\", label: \"Rationale\", type: \"string\", required: true, searchable: true }, { key: \"date\", label: \"Date\", type: \"string\" }] },\n { slug: \"tensions\", name: \"Tensions\", description: \"Process bottlenecks and client friction\", fields: [{ key: \"description\", label: \"Description\", type: \"string\", required: true, searchable: true }, { key: \"priority\", label: \"Priority\", type: \"select\", options: [\"low\", \"medium\", \"high\", \"critical\"] }] },\n ],\n },\n {\n id: \"saas-api\",\n name: \"SaaS API\",\n description: \"For API-first SaaS products — endpoints, schemas, rate limits, changelog, and integration guides\",\n collections: [\n { slug: \"glossary\", name: \"Glossary\", description: \"API and domain terminology\", fields: [{ key: \"canonical\", label: \"Canonical\", type: \"string\", required: true, searchable: true }, { key: \"category\", label: \"Category\", type: \"string\" }] },\n { slug: \"api-endpoints\", name: \"API Endpoints\", description: \"API routes and contracts\", fields: [{ key: \"description\", label: \"Description\", type: \"string\", required: true, searchable: true }, { key: \"method\", label: \"Method\", type: \"select\", options: [\"GET\", \"POST\", \"PUT\", \"PATCH\", \"DELETE\"] }, { key: \"path\", label: \"Path\", type: \"string\" }, { key: \"auth\", label: \"Auth\", type: \"select\", options: [\"none\", \"api-key\", \"bearer\", \"oauth\"] }] },\n { slug: \"schemas\", name: \"Schemas\", description: \"Data models and API schemas\", fields: [{ key: \"description\", label: \"Description\", type: \"string\", required: true, searchable: true }, { key: \"format\", label: \"Format\", type: \"select\", options: [\"json\", \"protobuf\", \"graphql\", \"openapi\"] }, { key: \"version\", label: \"Version\", type: \"string\" }] },\n { slug: \"rate-limits\", name: \"Rate Limits\", description: \"Rate limiting policies and tiers\", fields: [{ key: \"description\", label: \"Description\", type: \"string\", required: true, searchable: true }, { key: \"tier\", label: \"Tier\", type: \"string\" }, { key: \"limit\", label: \"Limit\", type: \"string\" }] },\n { slug: \"changelog\", name: \"Changelog\", description: \"API version history and breaking changes\", fields: [{ key: \"description\", label: \"Description\", type: \"string\", required: true, searchable: true }, { key: \"version\", label: \"Version\", type: \"string\" }, { key: \"date\", label: \"Date\", type: \"string\" }, { key: \"breaking\", label: \"Breaking\", type: \"select\", options: [\"yes\", \"no\"] }] },\n { slug: \"decisions\", name: \"Decisions\", description: \"API design decisions and rationale\", fields: [{ key: \"rationale\", label: \"Rationale\", type: \"string\", required: true, searchable: true }, { key: \"date\", label: \"Date\", type: \"string\" }] },\n ],\n },\n {\n id: \"general\",\n name: \"General\",\n description: \"A minimal starter set — glossary, decisions, and tensions. Add more collections as you need them.\",\n collections: [\n { slug: \"glossary\", name: \"Glossary\", description: \"Canonical terminology\", fields: [{ key: \"canonical\", label: \"Canonical\", type: \"string\", required: true, searchable: true }, { key: \"category\", label: \"Category\", type: \"string\" }] },\n { slug: \"decisions\", name: \"Decisions\", description: \"Decisions with rationale\", fields: [{ key: \"rationale\", label: \"Rationale\", type: \"string\", required: true, searchable: true }, { key: \"date\", label: \"Date\", type: \"string\" }, { key: \"decidedBy\", label: \"Decided By\", type: \"string\" }] },\n { slug: \"tensions\", name: \"Tensions\", description: \"Friction points and unmet needs\", fields: [{ key: \"description\", label: \"Description\", type: \"string\", required: true, searchable: true }, { key: \"priority\", label: \"Priority\", type: \"select\", options: [\"low\", \"medium\", \"high\", \"critical\"] }] },\n ],\n },\n];\n\nexport function getPreset(id: string): CollectionPreset | undefined {\n return COLLECTION_PRESETS.find((p) => p.id === id);\n}\n\nexport function listPresets(): Array<{ id: string; name: string; description: string; collectionCount: number }> {\n return COLLECTION_PRESETS.map((p) => ({\n id: p.id,\n name: p.name,\n description: p.description,\n collectionCount: p.collections.length,\n }));\n}\n","import { McpServer, ResourceTemplate } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { mcpQuery } from \"../client.js\";\n\nfunction formatEntryMarkdown(entry: any): 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: any[] | null,\n trackingEvents: any[] | null,\n standards: any[] | null,\n businessRules: any[] | null,\n): string {\n const sections: string[] = [\"# Product Brain — Orientation\"];\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 \"gather-context 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/mcp with Bearer token\\n\" +\n \" → Convex HTTP Action (convex/http.ts)\\n\" +\n \" → internalQuery / internalMutation (convex/mcpKnowledge.ts)\\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 `list-collections` for field schemas, `get-entry` for full records.\",\n );\n } else {\n sections.push(\n \"## Data Model\\n\" +\n \"Could not load collections — use `list-collections` 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: `search` for text search, `list-entries 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: `list-entries 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 \"- `gather-context` — get the full context around any entry (multi-hop graph traversal)\\n\" +\n \"- `suggest-links` — discover potential connections for an entry\\n\" +\n \"- `relate-entries` — create a typed link between two entries\\n\" +\n \"- `find-related` — list direct relations for an entry\\n\\n\" +\n \"**Convention:** When creating or updating entries in governed collections, always use `suggest-links` 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 \"- `run-workflow` — run a structured ceremony (e.g., retrospective)\\n\\n\" +\n \"Use `quality-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** → `gather-context` tool (by entry ID or task description)\\n\" +\n \"- **Discover links** → `suggest-links` tool\\n\" +\n \"- **Quality audit** → `quality-check` tool\\n\" +\n \"- **Terminology** → `name-check` prompt or `productbrain://terminology` resource\\n\" +\n \"- **Schema details** → `productbrain://collections` resource or `list-collections` tool\\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 `list-entries collection=strategy status=draft`\\n\" +\n \"- **Audiences** → `productbrain://audiences/entries` resource or `list-entries collection=audiences`\\n\" +\n \"- **Session identity** → `whoami` tool (workspace + auth context)\\n\" +\n \"- **Health check** → `health` tool\\n\" +\n \"- **Debug MCP calls** → `mcp-audit` tool\",\n );\n\n return sections.join(\"\\n\\n---\\n\\n\");\n}\n\nexport function registerResources(server: McpServer) {\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] = await Promise.allSettled([\n mcpQuery<any[]>(\"chain.listCollections\"),\n mcpQuery<any[]>(\"chain.listEntries\", { collectionSlug: \"tracking-events\" }),\n mcpQuery<any[]>(\"chain.listEntries\", { collectionSlug: \"standards\" }),\n mcpQuery<any[]>(\"chain.listEntries\", { collectionSlug: \"business-rules\" }),\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\n return {\n contents: [{\n uri: uri.href,\n text: buildOrientationMarkdown(collections, trackingEvents, standards, businessRules),\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 mcpQuery<any[]>(\"chain.listEntries\", { collectionSlug: \"glossary\" }),\n mcpQuery<any[]>(\"chain.listEntries\", { collectionSlug: \"standards\" }),\n ]);\n\n const lines: string[] = [\"# Product Brain — Terminology\"];\n\n if (glossaryResult.status === \"fulfilled\") {\n if (glossaryResult.value.length > 0) {\n const terms = glossaryResult.value\n .map((t) => `- **${t.name}** (${t.entryId ?? \"—\"}) [${t.status}]: ${t.data?.canonical ?? t.data?.description ?? \"\"}`)\n .join(\"\\n\");\n lines.push(`## Glossary (${glossaryResult.value.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 `list-entries collection=glossary` to browse manually.\");\n }\n\n if (standardsResult.status === \"fulfilled\") {\n if (standardsResult.value.length > 0) {\n const stds = standardsResult.value\n .map((s) => `- **${s.name}** (${s.entryId ?? \"—\"}) [${s.status}]: ${s.data?.description ?? \"\"}`)\n .join(\"\\n\");\n lines.push(`## Standards (${standardsResult.value.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 `list-entries 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 mcpQuery<any[]>(\"chain.listCollections\");\n\n if (collections.length === 0) {\n return { contents: [{ uri: uri.href, text: \"No collections in this workspace.\", mimeType: \"text/markdown\" }] };\n }\n\n const formatted = collections\n .map((c) => {\n const fieldList = c.fields\n .map((f: any) => ` - \\`${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 mcpQuery<any[]>(\"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 mcpQuery<any[]>(\"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 mcpQuery<any[]>(\"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","import { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { z } from \"zod\";\nimport { mcpQuery } from \"../client.js\";\nimport { getWorkflow, listWorkflows } from \"../workflows/definitions.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 mcpQuery<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 the list-entries tool with 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 mcpQuery<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 mcpQuery<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 mcpQuery<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 const highestRuleNum = allRules\n .map((r) => parseInt((r.entryId ?? \"\").replace(/^[A-Z]+-/, \"\"), 10))\n .filter((n) => !isNaN(n))\n .sort((a, b) => b - a)[0] || 0;\n const nextRuleId = `SOS-${String(highestRuleNum + 1).padStart(3, \"0\")}`;\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 `Suggested rule ID: ${nextRuleId}\\n\\n` +\n `Existing rules in this domain:\\n${existingContext}\\n\\n` +\n `Draft the rule with these fields:\\n` +\n `1. **entryId**: ${nextRuleId}\\n` +\n `2. **name**: Concise rule title\\n` +\n `3. **data.description**: What the rule states\\n` +\n `4. **data.rationale**: Why this rule matters\\n` +\n `5. **data.dataImpact**: How this affects data models, APIs, or storage\\n` +\n `6. **data.severity**: high / medium / low\\n` +\n `7. **data.platforms**: Which platforms are affected\\n` +\n `8. **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 // ── Run Workflow Prompt ──────────────────────────────────────────────────\n\n server.prompt(\n \"run-workflow\",\n \"Launch a Chainwork workflow (retro, shape, IDM) in Facilitator Mode. \" +\n \"Returns the full workflow definition, facilitation instructions, and round structure. \" +\n \"The agent enters Facilitator Mode and guides the participant through each round.\",\n {\n workflow: z.string().describe(\n \"Workflow ID to run. Available: \" +\n listWorkflows().map((w) => `'${w.id}' (${w.name})`).join(\", \"),\n ),\n context: z.string().optional().describe(\n \"Optional context from the participant (e.g., 'retro on last sprint', 'shape the Chainwork API bet')\",\n ),\n },\n async ({ workflow: workflowId, context }) => {\n const wf = getWorkflow(workflowId);\n\n if (!wf) {\n const available = listWorkflows()\n .map((w) => `- **${w.id}**: ${w.name} — ${w.shortDescription}`)\n .join(\"\\n\");\n return {\n messages: [\n {\n role: \"user\" as const,\n content: {\n type: \"text\" as const,\n text:\n `Workflow \"${workflowId}\" not found.\\n\\n` +\n `Available workflows:\\n${available}\\n\\n` +\n `Use one of these IDs to run a workflow.`,\n },\n },\n ],\n };\n }\n\n // Fetch recent chain context for richer facilitation\n let kbContext = \"\";\n try {\n const recentDecisions = await mcpQuery<any[]>(\"chain.listEntries\", {\n collectionSlug: wf.kbOutputCollection,\n });\n const sorted = [...recentDecisions]\n .sort((a, b) => ((b.data?.date ?? \"\") > (a.data?.date ?? \"\") ? 1 : -1))\n .slice(0, 5);\n if (sorted.length > 0) {\n kbContext =\n `\\n## Recent ${wf.kbOutputCollection} entries (for context)\\n` +\n sorted.map((d) => `- ${d.entryId ?? \"\"}: ${d.name} [${d.status}]`).join(\"\\n\");\n }\n } catch {\n kbContext = \"\\n_Could not load chain context — proceed without it._\";\n }\n\n const roundsPlan = wf.rounds\n .map((r) =>\n `### Round ${r.num}: ${r.label}\\n` +\n `**Type**: ${r.type} | **Duration**: ~${r.maxDurationHint ?? \"5 min\"}\\n` +\n `**Instruction**: ${r.instruction}\\n` +\n `**Facilitator guidance**: ${r.facilitatorGuidance}\\n` +\n (r.questions\n ? r.questions.map((q) =>\n `**Question**: ${q.prompt}\\n` +\n (q.options\n ? q.options.map((o) => ` - ${o.id}: ${o.label}`).join(\"\\n\")\n : \" _(open response)_\"),\n ).join(\"\\n\")\n : \"\") +\n `\\n**Output**: Capture to \\`${r.outputSchema.field}\\` (${r.outputSchema.format})`,\n )\n .join(\"\\n\\n---\\n\\n\");\n\n const contextLine = context\n ? `\\nThe participant provided this context: \"${context}\"\\nUse it — don't make them repeat themselves.\\n`\n : \"\";\n\n return {\n messages: [\n {\n role: \"user\" as const,\n content: {\n type: \"text\" as const,\n text:\n `# ${wf.icon} ${wf.name} Workflow — Facilitator Mode\\n\\n` +\n `${wf.shortDescription}\\n` +\n contextLine +\n `\\n---\\n\\n` +\n `## Facilitator Instructions\\n\\n${wf.facilitatorPreamble}\\n\\n` +\n `---\\n\\n` +\n `## Rounds\\n\\n${roundsPlan}\\n\\n` +\n `---\\n\\n` +\n `## Error Recovery\\n\\n${wf.errorRecovery}\\n\\n` +\n `---\\n\\n` +\n `## Chain Output\\n\\n` +\n `When complete, use \\`capture\\` to create a \\`${wf.kbOutputCollection}\\` entry.\\n` +\n `Name template: ${wf.kbOutputTemplate.nameTemplate}\\n` +\n `Description field: ${wf.kbOutputTemplate.descriptionField}\\n` +\n kbContext +\n `\\n\\n---\\n\\n` +\n `**BEGIN THE WORKFLOW NOW.** Start with Round 01. Create a Plan first.`,\n },\n },\n ],\n };\n },\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAIA,SAAS,aAAAA,kBAAiB;;;ACH1B,SAAS,SAAS;AAGlB,SAAS,eAAe,MAAW,QAAwB;AACzD,MAAI,CAAC,QAAQ,OAAO,SAAS,SAAU,QAAO;AAC9C,QAAM,MAAM,KAAK,eAAe,KAAK,aAAa,KAAK,UAAU;AACjE,MAAI,OAAO,QAAQ,YAAY,CAAC,IAAK,QAAO;AAC5C,SAAO,IAAI,SAAS,SAAS,IAAI,UAAU,GAAG,MAAM,IAAI,QAAQ;AAClE;AAEO,SAAS,uBAAuB,QAAmB;AAExD,SAAO;AAAA,IACL;AAAA,IACA;AAAA,MACE,OAAO;AAAA,MACP,aACE;AAAA,MAGF,aAAa,EAAE,cAAc,KAAK;AAAA,IACpC;AAAA,IACA,YAAY;AACV,YAAM,cAAc,MAAM,SAAgB,uBAAuB;AAEjE,UAAI,YAAY,WAAW,GAAG;AAC5B,eAAO,EAAE,SAAS,CAAC,EAAE,MAAM,QAAiB,MAAM,0CAA0C,CAAC,EAAE;AAAA,MACjG;AAEA,YAAM,YAAY,YACf,IAAI,CAAC,MAAM;AACV,cAAM,YA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A;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,EAAE,KAAK,IAAI;AAEJ,SAAS,2BAAsC;AACpD,QAAM,SAAS,IAAIC;AAAA,IACjB,EAAE,MAAM,iBAAiB,SAAS,eAAe;AAAA,IACjD,EAAE,cAAc,EAAE,SAAS,CAAC,EAAE,GAAG,cAAc,aAAa;AAAA,EAC9D;AAEA,QAAM,iBAAiB,IAAI;AAAA,KACxB,QAAQ,IAAI,cAAc,sBACxB,MAAM,GAAG,EAAE,IAAI,CAAC,MAAM,EAAE,KAAK,EAAE,YAAY,CAAC;AAAA,EACjD;AAEA,uBAAqB,MAAM;AAC3B,yBAAuB,MAAM;AAC7B,qBAAmB,MAAM;AACzB,sBAAoB,MAAM;AAC1B,sBAAoB,MAAM;AAC1B,4BAA0B,MAAM;AAChC,wBAAsB,MAAM;AAE5B,MAAI,eAAe,IAAI,UAAU,EAAG,uBAAsB,MAAM;AAChE,MAAI,eAAe,IAAI,UAAU,EAAG,kBAAiB,MAAM;AAC3D,MAAI,eAAe,IAAI,MAAM,EAAG,2BAA0B,MAAM;AAChE,qBAAmB,MAAM;AAEzB,oBAAkB,MAAM;AACxB,kBAAgB,MAAM;AAEtB,SAAO;AACT;","names":["McpServer","result","byCollection","lines","z","z","z","z","z","z","existsSync","readFileSync","resolve","z","z","resolveProjectRoot","resolve","existsSync","readFileSync","abs","z","z","z","z","z","z","z","z","z","z","McpServer"]}