@productbrain/mcp 0.0.1-beta.55 → 0.0.1-beta.57

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.
@@ -615,7 +615,7 @@ async function isFeatureEnabled(flag, workspaceId, workspaceSlug) {
615
615
  }
616
616
  }
617
617
 
618
- // ../../convex/lib/collectionRoutingClassifier.ts
618
+ // src/lib/collectionRoutingClassifier.ts
619
619
  var CLASSIFIER_AUTO_ROUTE_THRESHOLD = 70;
620
620
  var CLASSIFIER_AMBIGUITY_MARGIN = 15;
621
621
  var CLASSIFIABLE_COLLECTIONS = [
@@ -3026,4 +3026,4 @@ export {
3026
3026
  formatRubricCoaching,
3027
3027
  formatRubricVerdictSection
3028
3028
  };
3029
- //# sourceMappingURL=chunk-U4ABXFUT.js.map
3029
+ //# sourceMappingURL=chunk-65BMTVNQ.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/tools/smart-capture.ts","../src/client.ts","../src/auth.ts","../src/tools/knowledge-helpers.ts","../src/tool-surface.ts","../src/featureFlags.ts","../src/lib/collectionRoutingClassifier.ts","../src/tools/smart-capture-routing.ts","../src/envelope.ts","../src/errors.ts"],"sourcesContent":["/**\n * Smart capture — ARCH-node-mcp (Core layer)\n * Chain: FEAT-MCP-001 (MCP Server), ARCH-flow-smart-capture\n * Rules: SOS-016 (governed draft-first), SOS-015 (unique IDs within scope)\n */\n\nimport { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { z } from \"zod\";\nimport { mcpQuery, mcpMutation, getWorkspaceContext, requireWriteAccess, recordSessionActivity, getAgentSessionId } from \"../client.js\";\nimport {\n trackCaptureClassifierAutoRouted,\n trackCaptureClassifierEvaluated,\n trackCaptureClassifierFallback,\n trackQualityVerdict,\n trackQualityCheck,\n type ClassifierReasonCategory,\n} from \"../analytics.js\";\nimport { extractPreview } from \"./knowledge-helpers.js\";\nimport { trackWriteTool } from \"../tool-surface.js\";\nimport { isFeatureEnabled } from \"../featureFlags.js\";\nimport {\n CLASSIFIABLE_COLLECTIONS,\n classifyCollection,\n isClassificationAmbiguous,\n shouldAutoRouteClassification,\n type ClassifiableCollectionSlug,\n type ClassificationResult,\n} from \"./smart-capture-routing.js\";\nimport { withEnvelope, success, failure, type NextAction } from \"../envelope.js\";\n\nexport {\n CLASSIFIER_AUTO_ROUTE_THRESHOLD,\n CLASSIFIABLE_COLLECTIONS,\n STARTER_COLLECTIONS,\n classifyCollection,\n classifyStarterCollection,\n isClassificationAmbiguous,\n type ClassifiableCollectionSlug,\n type StarterCollectionSlug,\n type ClassificationResult,\n} from \"./smart-capture-routing.js\";\n\n// ── Collection Workflow Profiles ────────────────────────────────────────────\n\ninterface FieldDefault {\n key: string;\n value: unknown | \"today\" | \"infer\";\n}\n\ninterface QualityCheck {\n id: string;\n label: string;\n check: (ctx: CaptureContext) => boolean;\n suggestion?: (ctx: CaptureContext) => string;\n}\n\ninterface CollectionProfile {\n governedDraft: boolean;\n defaults: FieldDefault[];\n descriptionField: string;\n recommendedRelationTypes: string[];\n qualityChecks: QualityCheck[];\n inferField?: (ctx: CaptureContext) => Record<string, unknown>;\n}\n\ninterface CaptureContext {\n collection: string;\n name: string;\n description: string;\n context?: string;\n data: Record<string, unknown>;\n entryId: string;\n canonicalKey?: string;\n linksCreated: LinkResult[];\n linksSuggested: LinkSuggestion[];\n collectionFields: Array<{ key: string; type: string; required?: boolean }>;\n}\n\ninterface LinkResult {\n targetEntryId: string;\n targetName: string;\n targetCollection: string;\n relationType: string;\n linkReason?: string;\n}\n\ninterface LinkSuggestion {\n entryId?: string;\n name: string;\n collection: string;\n reason: string;\n preview: string;\n}\n\nconst AREA_KEYWORDS: Record<string, string[]> = {\n \"Architecture\": [\"convex\", \"schema\", \"database\", \"migration\", \"api\", \"backend\", \"infrastructure\", \"scaling\", \"performance\"],\n \"Chain\": [\"knowledge\", \"glossary\", \"entry\", \"collection\", \"terminology\", \"drift\", \"graph\", \"chain\", \"commit\"],\n \"AI & MCP Integration\": [\"mcp\", \"ai\", \"cursor\", \"agent\", \"tool\", \"llm\", \"prompt\", \"context\"],\n \"Developer Experience\": [\"dx\", \"developer\", \"ide\", \"workflow\", \"friction\", \"ceremony\"],\n \"Governance & Decision-Making\": [\"governance\", \"decision\", \"rule\", \"policy\", \"compliance\", \"approval\"],\n \"Analytics & Tracking\": [\"analytics\", \"posthog\", \"tracking\", \"event\", \"metric\", \"funnel\"],\n \"Security\": [\"security\", \"auth\", \"api key\", \"permission\", \"access\", \"token\"],\n};\n\nfunction inferArea(text: string): string {\n const lower = text.toLowerCase();\n let bestArea = \"\";\n let bestScore = 0;\n for (const [area, keywords] of Object.entries(AREA_KEYWORDS)) {\n const score = keywords.filter((kw) => lower.includes(kw)).length;\n if (score > bestScore) {\n bestScore = score;\n bestArea = area;\n }\n }\n return bestArea;\n}\n\nfunction inferDomain(text: string): string {\n return inferArea(text) || \"\";\n}\n\nconst COMMON_CHECKS: Record<string, QualityCheck> = {\n clearName: {\n id: \"clear-name\",\n label: \"Clear, specific name (not vague)\",\n check: (ctx) => ctx.name.length > 10 && ![\"new tension\", \"new entry\", \"untitled\", \"test\"].includes(ctx.name.toLowerCase()),\n suggestion: () => \"Rename to something specific — describe the actual problem or concept.\",\n },\n hasDescription: {\n id: \"has-description\",\n label: \"Description provided (>50 chars)\",\n check: (ctx) => ctx.description.length > 50,\n suggestion: () => \"Add a fuller description explaining context and impact.\",\n },\n hasRelations: {\n id: \"has-relations\",\n label: \"At least 1 relation created\",\n check: (ctx) => ctx.linksCreated.length >= 1,\n suggestion: () => \"Use `graph action=suggest` and `relations action=create` to add more connections.\",\n },\n diverseRelations: {\n id: \"diverse-relations\",\n label: \"Relations span multiple collections\",\n check: (ctx) => {\n const colls = new Set(ctx.linksCreated.map((l) => l.targetCollection));\n return colls.size >= 2;\n },\n suggestion: () => \"Try linking to entries in different collections (glossary, business-rules, strategy).\",\n },\n hasType: {\n id: \"has-type\",\n label: \"Has canonical type\",\n check: (ctx) => !!ctx.data?.canonicalKey || !!ctx.canonicalKey,\n suggestion: () => \"Classify this entry with a canonical type for better context assembly. Use update-entry to set canonicalKey.\",\n },\n};\n\n// ── Strategy Category Inference (FEAT-128) ──────────────────────────────────\n\nconst STRATEGY_CATEGORY_INFERENCE_THRESHOLD = 2;\n\nconst STRATEGY_CATEGORY_SIGNALS: readonly [string, readonly RegExp[]][] = [\n [\"business-model\", [/pricing/, /revenue/, /unit economics/, /cost structure/, /monetiz/, /margin/, /per.?seat/, /subscription/, /freemium/]],\n [\"vision\", [/vision/, /aspirational/, /future state/, /world where/]],\n [\"purpose\", [/purpose/, /why we exist/, /mission/, /reason for being/]],\n [\"goal\", [/goal/, /metric/, /target/, /kpi/, /okr/, /critical number/, /measur/]],\n [\"principle\", [/we believe/, /guiding principle/, /core belief/, /philosophy/]],\n [\"product-area\", [/product area/, /module/, /surface/, /capability area/]],\n [\"audience\", [/audience/, /persona/, /user segment/, /icp/, /target market/]],\n [\"insight\", [/insight/, /we learned/, /we observed/, /pattern/]],\n [\"opportunity\", [/opportunity/, /whitespace/, /gap/, /underserved/]],\n] as const;\n\n/**\n * Infer strategy sub-category from entry text. Returns null when confidence\n * is too low (exactly 1 signal match) — the caller decides how to handle\n * the abstention. Returns \"strategy\" as generic fallback when no signals\n * match at all (entry is in strategy collection but has no sub-type signals).\n *\n * ecosystem-layer is intentionally excluded: too niche to distinguish from\n * product-area by keywords alone — must be set explicitly via data.category.\n */\nexport function inferStrategyCategory(name: string, description: string): string | null {\n const text = `${name} ${description}`.toLowerCase();\n let bestCategory: string | null = null;\n let bestScore = 0;\n for (const [cat, signals] of STRATEGY_CATEGORY_SIGNALS) {\n const score = signals.reduce((s, rx) => s + (rx.test(text) ? 1 : 0), 0);\n if (score > bestScore) { bestScore = score; bestCategory = cat; }\n }\n if (bestCategory && bestScore >= STRATEGY_CATEGORY_INFERENCE_THRESHOLD) return bestCategory;\n if (bestScore === 0) return \"strategy\";\n return null;\n}\n\n// ── Collection Profiles ─────────────────────────────────────────────────────\n\nconst PROFILES: Map<string, CollectionProfile> = new Map([\n [\"tensions\", {\n governedDraft: false,\n descriptionField: \"description\",\n defaults: [\n { key: \"priority\", value: \"medium\" },\n { key: \"date\", value: \"today\" },\n { key: \"raised\", value: \"infer\" },\n { key: \"severity\", value: \"infer\" },\n ],\n recommendedRelationTypes: [\"surfaces_tension_in\", \"references\", \"belongs_to\", \"related_to\"],\n inferField: (ctx: CaptureContext) => {\n const fields: Record<string, unknown> = {};\n const text = `${ctx.name} ${ctx.description}`;\n const area = inferArea(text);\n if (area) fields.raised = area;\n if (text.toLowerCase().includes(\"critical\") || text.toLowerCase().includes(\"blocker\")) {\n fields.severity = \"critical\";\n } else if (text.toLowerCase().includes(\"bottleneck\") || text.toLowerCase().includes(\"scaling\") || text.toLowerCase().includes(\"breaking\")) {\n fields.severity = \"high\";\n } else {\n fields.severity = \"medium\";\n }\n if (area) fields.affectedArea = area;\n return fields;\n },\n qualityChecks: [\n COMMON_CHECKS.clearName,\n COMMON_CHECKS.hasDescription,\n COMMON_CHECKS.hasRelations,\n COMMON_CHECKS.hasType,\n {\n id: \"has-severity\",\n label: \"Severity specified\",\n check: (ctx) => !!ctx.data.severity && ctx.data.severity !== \"\",\n suggestion: (ctx) => {\n const text = `${ctx.name} ${ctx.description}`.toLowerCase();\n const inferred = text.includes(\"critical\") ? \"critical\" : text.includes(\"bottleneck\") ? \"high\" : \"medium\";\n return `Set severity — suggest: ${inferred} (based on description keywords).`;\n },\n },\n {\n id: \"has-affected-area\",\n label: \"Affected area identified\",\n check: (ctx) => !!ctx.data.affectedArea && ctx.data.affectedArea !== \"\",\n suggestion: (ctx) => {\n const area = inferArea(`${ctx.name} ${ctx.description}`);\n return area\n ? `Set affectedArea — suggest: \"${area}\" (inferred from content).`\n : \"Specify which product area or domain this tension impacts.\";\n },\n },\n ],\n }],\n\n [\"business-rules\", {\n governedDraft: true,\n descriptionField: \"description\",\n defaults: [\n { key: \"severity\", value: \"medium\" },\n { key: \"domain\", value: \"infer\" },\n ],\n recommendedRelationTypes: [\"governs\", \"references\", \"conflicts_with\", \"related_to\"],\n inferField: (ctx: CaptureContext) => {\n const fields: Record<string, unknown> = {};\n const domain = inferDomain(`${ctx.name} ${ctx.description}`);\n if (domain) fields.domain = domain;\n return fields;\n },\n qualityChecks: [\n COMMON_CHECKS.clearName,\n COMMON_CHECKS.hasDescription,\n COMMON_CHECKS.hasRelations,\n COMMON_CHECKS.hasType,\n {\n id: \"has-rationale\",\n label: \"Rationale provided\",\n check: (ctx) => typeof ctx.data.rationale === \"string\" && ctx.data.rationale.length > 10,\n suggestion: () => \"Add a rationale explaining why this rule exists via `update-entry`.\",\n },\n {\n id: \"has-domain\",\n label: \"Domain specified\",\n check: (ctx) => !!ctx.data.domain && ctx.data.domain !== \"\",\n suggestion: (ctx) => {\n const domain = inferDomain(`${ctx.name} ${ctx.description}`);\n return domain\n ? `Set domain — suggest: \"${domain}\" (inferred from content).`\n : \"Specify the business domain this rule belongs to.\";\n },\n },\n ],\n }],\n\n [\"glossary\", {\n governedDraft: true,\n descriptionField: \"canonical\",\n defaults: [\n { key: \"category\", value: \"infer\" },\n ],\n recommendedRelationTypes: [\"defines_term_for\", \"confused_with\", \"related_to\", \"references\"],\n inferField: (ctx: CaptureContext) => {\n const fields: Record<string, unknown> = {};\n const area = inferArea(`${ctx.name} ${ctx.description}`);\n if (area) {\n const categoryMap: Record<string, string> = {\n \"Architecture\": \"Platform & Architecture\",\n \"Chain\": \"Knowledge Management\",\n \"AI & MCP Integration\": \"AI & Developer Tools\",\n \"Developer Experience\": \"AI & Developer Tools\",\n \"Governance & Decision-Making\": \"Governance & Process\",\n \"Analytics & Tracking\": \"Platform & Architecture\",\n \"Security\": \"Platform & Architecture\",\n };\n fields.category = categoryMap[area] ?? \"\";\n }\n return fields;\n },\n qualityChecks: [\n COMMON_CHECKS.clearName,\n COMMON_CHECKS.hasType,\n {\n id: \"has-canonical\",\n label: \"Canonical definition provided (>20 chars)\",\n check: (ctx) => {\n const canonical = ctx.data.canonical;\n return typeof canonical === \"string\" && canonical.length > 20;\n },\n suggestion: () => \"Add a clear canonical definition — this is the single source of truth for this term.\",\n },\n COMMON_CHECKS.hasRelations,\n {\n id: \"has-category\",\n label: \"Category assigned\",\n check: (ctx) => !!ctx.data.category && ctx.data.category !== \"\",\n suggestion: () => \"Assign a category (e.g., 'Platform & Architecture', 'Governance & Process').\",\n },\n ],\n }],\n\n [\"decisions\", {\n governedDraft: false,\n descriptionField: \"rationale\",\n defaults: [\n { key: \"date\", value: \"today\" },\n { key: \"decidedBy\", value: \"infer\" },\n ],\n recommendedRelationTypes: [\"informs\", \"references\", \"replaces\", \"related_to\"],\n inferField: (ctx: CaptureContext) => {\n const fields: Record<string, unknown> = {};\n const area = inferArea(`${ctx.name} ${ctx.description}`);\n if (area) fields.decidedBy = area;\n return fields;\n },\n qualityChecks: [\n COMMON_CHECKS.clearName,\n COMMON_CHECKS.hasType,\n {\n id: \"has-rationale\",\n label: \"Rationale provided (>30 chars)\",\n check: (ctx) => {\n const rationale = ctx.data.rationale;\n return typeof rationale === \"string\" && rationale.length > 30;\n },\n suggestion: () => \"Explain why this decision was made — what was considered and rejected?\",\n },\n COMMON_CHECKS.hasRelations,\n {\n id: \"has-date\",\n label: \"Decision date recorded\",\n check: (ctx) => !!ctx.data.date && ctx.data.date !== \"\",\n suggestion: () => \"Record when this decision was made.\",\n },\n ],\n }],\n\n [\"features\", {\n governedDraft: false,\n descriptionField: \"description\",\n defaults: [] as FieldDefault[],\n recommendedRelationTypes: [\"belongs_to\", \"depends_on\", \"surfaces_tension_in\", \"related_to\"],\n qualityChecks: [\n COMMON_CHECKS.clearName,\n COMMON_CHECKS.hasDescription,\n COMMON_CHECKS.hasRelations,\n COMMON_CHECKS.hasType,\n {\n id: \"has-owner\",\n label: \"Owner assigned\",\n check: (ctx: CaptureContext) => !!ctx.data.owner && ctx.data.owner !== \"\",\n suggestion: () => \"Assign an owner team or product area.\",\n },\n {\n id: \"has-rationale\",\n label: \"Rationale documented\",\n check: (ctx: CaptureContext) => !!ctx.data.rationale && String(ctx.data.rationale).length > 20,\n suggestion: () => \"Explain why this feature matters — what problem does it solve?\",\n },\n ],\n } satisfies CollectionProfile],\n\n [\"audiences\", {\n governedDraft: false,\n descriptionField: \"description\",\n defaults: [],\n recommendedRelationTypes: [\"fills_slot\", \"informs\", \"related_to\", \"references\"],\n qualityChecks: [\n COMMON_CHECKS.clearName,\n COMMON_CHECKS.hasDescription,\n COMMON_CHECKS.hasRelations,\n COMMON_CHECKS.hasType,\n {\n id: \"has-behaviors\",\n label: \"Behaviors described\",\n check: (ctx) => typeof ctx.data.behaviors === \"string\" && ctx.data.behaviors.length > 20,\n suggestion: () => \"Describe how this audience segment behaves — what do they do, what tools do they use?\",\n },\n ],\n }],\n\n [\"strategy\", {\n governedDraft: true,\n descriptionField: \"description\",\n defaults: [],\n recommendedRelationTypes: [\"informs\", \"governs\", \"belongs_to\", \"related_to\"],\n inferField: (ctx: CaptureContext) => {\n if (ctx.data?.category) return {};\n const category = inferStrategyCategory(ctx.name, ctx.description);\n return category ? { category } : {};\n },\n qualityChecks: [\n COMMON_CHECKS.clearName,\n COMMON_CHECKS.hasDescription,\n COMMON_CHECKS.hasRelations,\n COMMON_CHECKS.hasType,\n COMMON_CHECKS.diverseRelations,\n ],\n }],\n\n [\"bets\", { // BET-chain-native-constellation, DEC-70 (structuredContent), STA-1 (constellation pattern)\n governedDraft: false,\n descriptionField: \"problem\",\n defaults: [],\n recommendedRelationTypes: [\"part_of\", \"constrains\", \"informs\", \"depends_on\", \"related_to\"],\n qualityChecks: [\n COMMON_CHECKS.clearName,\n COMMON_CHECKS.hasDescription,\n COMMON_CHECKS.hasRelations,\n COMMON_CHECKS.hasType,\n ],\n }],\n\n [\"maps\", {\n governedDraft: false,\n descriptionField: \"description\",\n defaults: [],\n recommendedRelationTypes: [\"fills_slot\", \"references\", \"related_to\"],\n qualityChecks: [\n COMMON_CHECKS.clearName,\n COMMON_CHECKS.hasDescription,\n ],\n }],\n\n [\"chains\", {\n governedDraft: false,\n descriptionField: \"description\",\n defaults: [],\n recommendedRelationTypes: [\"informs\", \"references\", \"related_to\"],\n qualityChecks: [\n COMMON_CHECKS.clearName,\n COMMON_CHECKS.hasDescription,\n ],\n }],\n\n [\"principles\", {\n governedDraft: true,\n descriptionField: \"description\",\n defaults: [\n { key: \"severity\", value: \"high\" },\n { key: \"category\", value: \"infer\" },\n ],\n recommendedRelationTypes: [\"governs\", \"informs\", \"references\", \"related_to\"],\n inferField: (ctx: CaptureContext) => {\n const fields: Record<string, unknown> = {};\n const area = inferArea(`${ctx.name} ${ctx.description}`);\n if (area) {\n const categoryMap: Record<string, string> = {\n \"Architecture\": \"Engineering\",\n \"Chain\": \"Product\",\n \"AI & MCP Integration\": \"Engineering\",\n \"Developer Experience\": \"Engineering\",\n \"Governance & Decision-Making\": \"Business\",\n \"Analytics & Tracking\": \"Product\",\n \"Security\": \"Engineering\",\n };\n fields.category = categoryMap[area] ?? \"Product\";\n }\n return fields;\n },\n qualityChecks: [\n COMMON_CHECKS.clearName,\n COMMON_CHECKS.hasDescription,\n COMMON_CHECKS.hasRelations,\n COMMON_CHECKS.hasType,\n {\n id: \"has-rationale\",\n label: \"Rationale provided — why this principle matters\",\n check: (ctx) => typeof ctx.data.rationale === \"string\" && ctx.data.rationale.length > 20,\n suggestion: () => \"Explain why this principle exists and what goes wrong without it.\",\n },\n ],\n }],\n\n [\"standards\", {\n governedDraft: true,\n descriptionField: \"description\",\n defaults: [],\n recommendedRelationTypes: [\"governs\", \"defines_term_for\", \"references\", \"related_to\"],\n qualityChecks: [\n COMMON_CHECKS.clearName,\n COMMON_CHECKS.hasDescription,\n COMMON_CHECKS.hasRelations,\n COMMON_CHECKS.hasType,\n ],\n }],\n\n [\"tracking-events\", {\n governedDraft: false,\n descriptionField: \"description\",\n defaults: [],\n recommendedRelationTypes: [\"references\", \"belongs_to\", \"related_to\"],\n qualityChecks: [\n COMMON_CHECKS.clearName,\n COMMON_CHECKS.hasDescription,\n ],\n }],\n\n [\"insights\", {\n governedDraft: false,\n descriptionField: \"description\",\n defaults: [\n { key: \"evidenceStrength\", value: \"anecdotal\" },\n ],\n recommendedRelationTypes: [\"validates\", \"invalidates\", \"informs\", \"related_to\"],\n qualityChecks: [\n COMMON_CHECKS.clearName,\n COMMON_CHECKS.hasDescription,\n COMMON_CHECKS.hasRelations,\n COMMON_CHECKS.hasType,\n {\n id: \"has-evidence-link\",\n label: \"Evidence link exists (validates or invalidates)\",\n check: (ctx) => ctx.linksCreated.some((l) => l.relationType === \"validates\" || l.relationType === \"invalidates\"),\n suggestion: () => \"Link this insight to the assumption or claim it validates/invalidates using `relations action=create type=validates`.\",\n },\n {\n id: \"has-source\",\n label: \"Source documented\",\n check: (ctx) => !!ctx.data?.source && String(ctx.data.source).length > 0,\n suggestion: () => \"Document where this insight came from (research, data, user interview, etc.).\",\n },\n ],\n }],\n\n [\"assumptions\", {\n governedDraft: false,\n descriptionField: \"belief\",\n defaults: [\n { key: \"risk\", value: \"medium\" },\n { key: \"evidenceStrength\", value: \"unvalidated\" },\n ],\n recommendedRelationTypes: [\"depends_on\", \"informs\", \"related_to\", \"validates\", \"invalidates\"],\n qualityChecks: [\n COMMON_CHECKS.clearName,\n {\n id: \"has-belief\",\n label: \"Belief statement provided (>30 chars)\",\n check: (ctx) => !!ctx.data?.belief && String(ctx.data.belief).length > 30,\n suggestion: () => \"Write the assumption as a clear, testable belief statement.\",\n },\n COMMON_CHECKS.hasRelations,\n COMMON_CHECKS.hasType,\n {\n id: \"has-test-method\",\n label: \"Test method described\",\n check: (ctx) => !!ctx.data?.testMethod && String(ctx.data.testMethod).length > 0,\n suggestion: () => \"Describe how this assumption could be tested or validated.\",\n },\n ],\n }],\n\n [\"architecture\", {\n governedDraft: true,\n descriptionField: \"description\",\n defaults: [],\n recommendedRelationTypes: [\"belongs_to\", \"depends_on\", \"governs\", \"references\", \"related_to\"],\n qualityChecks: [\n COMMON_CHECKS.clearName,\n COMMON_CHECKS.hasDescription,\n COMMON_CHECKS.hasRelations,\n COMMON_CHECKS.hasType,\n {\n id: \"has-layer\",\n label: \"Architecture layer identified\",\n check: (ctx) => !!ctx.data?.layer && String(ctx.data.layer).length > 0,\n suggestion: () => \"Specify which architecture layer this belongs to (L1-L7).\",\n },\n ],\n }],\n\n [\"landscape\", {\n governedDraft: false,\n descriptionField: \"description\",\n defaults: [],\n recommendedRelationTypes: [\"references\", \"related_to\", \"fills_slot\"],\n qualityChecks: [\n COMMON_CHECKS.clearName,\n COMMON_CHECKS.hasDescription,\n COMMON_CHECKS.hasRelations,\n COMMON_CHECKS.hasType,\n ],\n }],\n]);\n\nconst FALLBACK_PROFILE: CollectionProfile = {\n governedDraft: false,\n descriptionField: \"description\",\n defaults: [],\n recommendedRelationTypes: [\"related_to\", \"references\"],\n qualityChecks: [\n COMMON_CHECKS.clearName,\n COMMON_CHECKS.hasDescription,\n COMMON_CHECKS.hasRelations,\n COMMON_CHECKS.hasType,\n ],\n};\n\n// ── Auto-Linking Logic ──────────────────────────────────────────────────────\n\nfunction extractSearchTerms(name: string, description: string): string {\n const text = `${name} ${description}`;\n return text\n .replace(/[^\\w\\s]/g, \" \")\n .split(/\\s+/)\n .filter((w) => w.length > 3)\n .slice(0, 8)\n .join(\" \");\n}\n\ninterface LinkConfidenceResult {\n score: number;\n reason: string;\n}\n\nfunction computeLinkConfidence(\n candidate: { name: string; data?: any; entryId?: string },\n sourceName: string,\n sourceDescription: string,\n sourceCollection: string,\n candidateCollection: string,\n): LinkConfidenceResult {\n const text = `${sourceName} ${sourceDescription}`.toLowerCase();\n const candidateName = candidate.name.toLowerCase();\n let score = 0;\n const reasons: string[] = [];\n\n if (text.includes(candidateName) && candidateName.length > 3) {\n score += 40;\n reasons.push(\"name match\");\n }\n\n const candidateWords = candidateName.split(/\\s+/).filter((w) => w.length > 3);\n const matchingWords = candidateWords.filter((w) => text.includes(w));\n const wordScore = (matchingWords.length / Math.max(candidateWords.length, 1)) * 30;\n score += wordScore;\n if (matchingWords.length > 0) {\n reasons.push(`word overlap (${matchingWords.slice(0, 3).join(\", \")})`);\n }\n\n const HUB_COLLECTIONS = new Set([\"strategy\", \"features\"]);\n if (HUB_COLLECTIONS.has(candidateCollection)) {\n score += 15;\n reasons.push(\"hub collection\");\n }\n\n if (candidateCollection !== sourceCollection) {\n score += 10;\n reasons.push(\"cross-collection\");\n }\n\n const finalScore = Math.min(score, 100);\n const reason = reasons.length > 0 ? reasons.join(\" + \") : \"low relevance\";\n return { score: finalScore, reason };\n}\n\ninterface RelationTypeResult {\n type: string;\n reason: string;\n}\n\nfunction inferRelationType(\n sourceCollection: string,\n targetCollection: string,\n profile: CollectionProfile,\n): RelationTypeResult {\n const typeMap: Record<string, Record<string, string>> = {\n tensions: {\n glossary: \"surfaces_tension_in\",\n \"business-rules\": \"references\",\n strategy: \"belongs_to\",\n features: \"surfaces_tension_in\",\n decisions: \"references\",\n },\n \"business-rules\": {\n glossary: \"references\",\n features: \"governs\",\n strategy: \"belongs_to\",\n tensions: \"references\",\n },\n glossary: {\n features: \"defines_term_for\",\n \"business-rules\": \"references\",\n strategy: \"references\",\n },\n decisions: {\n features: \"informs\",\n \"business-rules\": \"references\",\n strategy: \"references\",\n tensions: \"references\",\n },\n };\n\n const mapped = typeMap[sourceCollection]?.[targetCollection];\n const type = mapped ?? profile.recommendedRelationTypes[0] ?? \"related_to\";\n const reason = mapped\n ? `collection pair (${sourceCollection} → ${targetCollection})`\n : `profile default (${profile.recommendedRelationTypes[0] ?? \"related_to\"})`;\n return { type, reason };\n}\n\n// ── Quality Scoring ─────────────────────────────────────────────────────────\n\ninterface QualityResult {\n score: number;\n maxScore: number;\n checks: Array<{ id: string; label: string; passed: boolean; suggestion?: string }>;\n}\n\nfunction scoreQuality(ctx: CaptureContext, profile: CollectionProfile): QualityResult {\n const checks = profile.qualityChecks.map((qc) => {\n const passed = qc.check(ctx);\n return {\n id: qc.id,\n label: qc.label,\n passed,\n suggestion: passed ? undefined : qc.suggestion?.(ctx),\n };\n });\n\n const passed = checks.filter((c) => c.passed).length;\n const total = checks.length;\n const score = total > 0 ? Math.round((passed / total) * 10) : 10;\n\n return { score, maxScore: 10, checks };\n}\n\nexport function formatQualityReport(result: QualityResult): string {\n const failed = result.checks.filter((c) => !c.passed);\n const reason = failed.length > 0\n ? ` because ${failed.map((c) => c.suggestion ?? c.label.toLowerCase()).join(\"; \")}`\n : \"\";\n const lines: string[] = [`## Quality: ${result.score}/${result.maxScore}${reason}`];\n for (const check of result.checks) {\n const icon = check.passed ? \"[x]\" : \"[ ]\";\n const suggestion = check.passed ? \"\" : ` — ${check.suggestion ?? check.label}`;\n lines.push(`${icon} ${check.label}${suggestion}`);\n }\n return lines.join(\"\\n\");\n}\n\n// ── Exported: quality check for existing entries ─────────────────────────────\n\nexport async function checkEntryQuality(entryId: string): Promise<{ text: string; quality: QualityResult }> {\n const entry = await mcpQuery<any>(\"chain.getEntry\", { entryId });\n if (!entry) {\n return {\n text: `Entry \\`${entryId}\\` not found. Try search to find the right ID.`,\n quality: { score: 0, maxScore: 10, checks: [] },\n };\n }\n\n 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 const collectionSlug = collMap.get(entry.collectionId) ?? \"unknown\";\n\n const profile = PROFILES.get(collectionSlug) ?? FALLBACK_PROFILE;\n\n const relations = await mcpQuery<any[]>(\"chain.listEntryRelations\", { entryId });\n const linksCreated: LinkResult[] = [];\n for (const r of relations) {\n const otherId = r.fromId === entry._id ? r.toId : r.fromId;\n linksCreated.push({\n targetEntryId: otherId,\n targetName: \"\",\n targetCollection: \"\",\n relationType: r.type,\n });\n }\n\n const descField = profile.descriptionField;\n const description = typeof entry.data?.[descField] === \"string\" ? entry.data[descField] : \"\";\n\n const ctx: CaptureContext = {\n collection: collectionSlug,\n name: entry.name,\n description,\n data: entry.data ?? {},\n entryId: entry.entryId ?? \"\",\n canonicalKey: entry.canonicalKey,\n linksCreated,\n linksSuggested: [],\n collectionFields: [],\n };\n\n const quality = scoreQuality(ctx, profile);\n\n const lines: string[] = [\n `# Quality Check: ${entry.entryId ?? entry.name}`,\n `**${entry.name}** in \\`${collectionSlug}\\` [${entry.status}]`,\n \"\",\n formatQualityReport(quality),\n ];\n\n if (quality.score < 10) {\n const failedChecks = quality.checks.filter((c) => !c.passed && c.suggestion);\n if (failedChecks.length > 0) {\n lines.push(\"\");\n lines.push(`_To improve: use \\`update-entry\\` to fill missing fields, or \\`relations action=create\\` to add connections._`);\n }\n }\n\n return { text: lines.join(\"\\n\"), quality };\n}\n\n// ── Tool Registration ───────────────────────────────────────────────────────\n\nconst GOVERNED_COLLECTIONS = new Set([\n \"glossary\", \"business-rules\", \"principles\", \"standards\", \"strategy\", \"features\", \"architecture\",\n]);\n\nconst AUTO_LINK_CONFIDENCE_THRESHOLD = 35;\nconst MAX_AUTO_LINKS = 5;\nconst MAX_SUGGESTIONS = 5;\nconst CAPTURE_WITHOUT_THINKING_FLAG = \"capture-without-thinking\";\n\nexport const captureSchema = z.object({\n collection: z.string().optional().describe(\"Collection slug, e.g. 'tensions', 'business-rules', 'glossary', 'decisions'. Optional when `capture-without-thinking` is enabled.\"),\n name: z.string().describe(\"Display name — be specific (e.g. 'Convex adjacency list won't scale for graph traversal')\"),\n description: z.string().describe(\"Full context — what's happening, why it matters, what you observed\"),\n context: z.string().optional().describe(\"Optional additional context (e.g. 'Observed during context gather calls taking 700ms+')\"),\n entryId: z.string().optional().describe(\"Optional custom entry ID (e.g. 'TEN-my-id'). Auto-generated if omitted.\"),\n canonicalKey: z.string().optional().describe(\"Semantic type (e.g. 'decision', 'tension', 'vision'). Auto-assigned from collection if omitted.\"),\n data: z.record(z.unknown()).optional().describe(\"Explicit field values when you know the schema (e.g. canonical_key, cardinality_rule, required_fields). Merged with inferred values; user-provided wins.\"),\n links: z.array(z.object({\n to: z.string().describe(\"Target entry ID (e.g. 'BR-64', 'ARCH-8')\"),\n type: z.string().describe(\"Relation type (e.g. 'governs', 'related_to', 'informs')\"),\n })).optional().describe(\"Relations to create after capture. Skips auto-link discovery when provided.\"),\n autoCommit: z.boolean().optional().describe(\"If true, commits the entry immediately after capture + linking. Use for ungoverned collections or when you're certain.\"),\n});\n\nexport const batchCaptureSchema = z.object({\n entries: z.array(z.object({\n collection: z.string().describe(\"Collection slug\"),\n name: z.string().describe(\"Display name\"),\n description: z.string().describe(\"Full context / definition\"),\n entryId: z.string().optional().describe(\"Optional custom entry ID\"),\n })).min(1).max(50).describe(\"Array of entries to capture\"),\n});\n\nexport const captureClassifierSchema = z.object({\n enabled: z.boolean(),\n autoRouted: z.boolean(),\n agrees: z.boolean(),\n abstained: z.boolean(),\n topConfidence: z.number(),\n confidence: z.number(),\n reasons: z.array(z.string()),\n candidates: z.array(\n z.object({\n collection: z.enum(CLASSIFIABLE_COLLECTIONS),\n signalScore: z.number(),\n confidence: z.number(),\n }),\n ),\n agentProvidedCollection: z.string().optional(),\n overrideCommand: z.string().optional(),\n});\n\nexport type CaptureClassifierMetadata = z.infer<typeof captureClassifierSchema>;\n\ntype CaptureToolResult = {\n content: Array<{ type: \"text\"; text: string }>;\n structuredContent?: z.infer<typeof captureOutputSchema>;\n};\n\ntype CollectionResolution = {\n resolvedCollection?: string;\n classifierMeta?: CaptureClassifierMetadata;\n earlyResult?: CaptureToolResult;\n};\n\nfunction trackClassifierTelemetry(params: {\n workspaceId: string;\n predictedCollection: string;\n confidence: number;\n autoRouted: boolean;\n reasonCategory: ClassifierReasonCategory;\n explicitCollectionProvided: boolean;\n outcome: \"auto-routed\" | \"fallback\";\n}): void {\n const telemetry = {\n predicted_collection: params.predictedCollection,\n confidence: params.confidence,\n auto_routed: params.autoRouted,\n reason_category: params.reasonCategory,\n explicit_collection_provided: params.explicitCollectionProvided,\n };\n\n trackCaptureClassifierEvaluated(params.workspaceId, telemetry);\n if (params.outcome === \"auto-routed\") {\n trackCaptureClassifierAutoRouted(params.workspaceId, telemetry);\n return;\n }\n trackCaptureClassifierFallback(params.workspaceId, telemetry);\n}\n\nfunction buildCollectionRequiredResult(): CaptureToolResult {\n return {\n content: [{\n type: \"text\" as const,\n text:\n \"Collection is required unless `capture-without-thinking` is enabled.\\n\\n\" +\n \"Provide `collection` explicitly, or enable the feature flag for this workspace.\",\n }],\n structuredContent: failure(\n \"VALIDATION_ERROR\",\n \"Collection is required unless capture-without-thinking is enabled.\",\n \"Provide collection explicitly, or enable the feature flag.\",\n [{ tool: \"collections\", description: \"List available collections\", parameters: { action: \"list\" } }],\n ),\n };\n}\n\nfunction buildClassifierUnknownResult(): CaptureToolResult {\n return {\n content: [{\n type: \"text\" as const,\n text:\n \"I could not infer a collection confidently from this input.\\n\\n\" +\n \"Please provide `collection`, or rewrite with clearer intent (decision/problem/definition/insight/bet).\",\n }],\n structuredContent: failure(\n \"VALIDATION_ERROR\",\n \"Could not infer collection from input.\",\n \"Provide collection explicitly, or rewrite with clearer intent.\",\n [{ tool: \"collections\", description: \"List available collections\", parameters: { action: \"list\" } }],\n { classifier: { enabled: true, autoRouted: false, agrees: false, abstained: true, topConfidence: 0, confidence: 0, reasons: [], candidates: [] } },\n ),\n };\n}\n\nfunction buildProvisionedCollectionSuggestions(\n candidates: Array<{ collection: ClassifiableCollectionSlug; signalScore: number; confidence: number }>,\n): string {\n return candidates.length\n ? candidates\n .map((c) => `- \\`${c.collection}\\` (${c.signalScore}% signal score)`)\n .join(\"\\n\")\n : \"- No provisioned collection candidates were inferred confidently.\";\n}\n\nfunction buildUnsupportedProvisioningResult(\n classified: ClassificationResult,\n provisionedCandidates: Array<{ collection: ClassifiableCollectionSlug; signalScore: number; confidence: number }>,\n): CaptureToolResult {\n const suggestions = buildProvisionedCollectionSuggestions(provisionedCandidates);\n const textBody =\n `Collection inference is not safe to auto-route yet.\\n\\n` +\n `Predicted collection \\`${classified.collection}\\` is not provisioned/supported for auto-routing in this workspace.\\n` +\n `Reason: ${classified.reasons.join(\"; \") || \"low signal\"}\\n\\n` +\n \"Choose one of these provisioned starter collections and retry with `collection`:\\n\" +\n `${suggestions}\\n\\n` +\n \"Correction path: rerun with explicit `collection`.\";\n return {\n content: [{ type: \"text\" as const, text: textBody }],\n structuredContent: failure(\n \"VALIDATION_ERROR\",\n `Collection '${classified.collection}' is not provisioned for auto-routing.`,\n \"Rerun with explicit collection.\",\n [{ tool: \"collections\", description: \"List available collections\", parameters: { action: \"list\" } }],\n {\n classifier: {\n enabled: true,\n autoRouted: false,\n agrees: false,\n abstained: false,\n topConfidence: classified.topConfidence,\n confidence: classified.confidence,\n reasons: classified.reasons,\n candidates: provisionedCandidates.map((c) => ({ collection: c.collection, signalScore: c.signalScore, confidence: c.confidence })),\n },\n },\n ),\n };\n}\n\nfunction buildAmbiguousRouteResult(\n classified: ClassificationResult,\n classifierMeta: CaptureClassifierMetadata,\n ambiguousRoute: boolean,\n): CaptureToolResult {\n const suggestions = buildProvisionedCollectionSuggestions(classifierMeta.candidates);\n const textBody =\n \"Collection inference is not safe to auto-route yet.\\n\\n\" +\n (ambiguousRoute ? \"Routing held because intent is ambiguous across top candidates.\\n\\n\" : \"\") +\n `Predicted: \\`${classified.collection}\\` (${classified.topConfidence}% top confidence)\\n` +\n `Reason: ${classified.reasons.join(\"; \") || \"low signal\"}\\n\\n` +\n \"Choose one of these and retry with `collection`:\\n\" +\n `${suggestions}\\n\\n` +\n \"Correction path: if this was close, rerun with your chosen `collection`.\";\n return {\n content: [{ type: \"text\" as const, text: textBody }],\n structuredContent: failure(\n \"VALIDATION_ERROR\",\n ambiguousRoute\n ? `Ambiguous routing — top candidates too close (${classified.topConfidence}% confidence).`\n : `Low confidence routing to '${classified.collection}' (${classified.topConfidence}%).`,\n \"Rerun with explicit collection.\",\n classifierMeta.candidates.map((c) => ({\n tool: \"capture\",\n description: `Capture to ${c.collection}`,\n parameters: { collection: c.collection },\n })),\n { classifier: classifierMeta },\n ),\n };\n}\n\nasync function getProvisionedCollectionCandidates(\n classified: ClassificationResult,\n supportedCollections: Set<ClassifiableCollectionSlug>,\n): Promise<{\n provisionedCollections: Set<ClassifiableCollectionSlug>;\n provisionedCandidates: Array<{ collection: ClassifiableCollectionSlug; signalScore: number; confidence: number }>;\n}> {\n const allCollections = await mcpQuery<any[]>(\"chain.listCollections\");\n const provisionedCollections = new Set<ClassifiableCollectionSlug>(\n (allCollections ?? [])\n .map((collection) => collection.slug)\n .filter(\n (slug): slug is ClassifiableCollectionSlug =>\n supportedCollections.has(slug as ClassifiableCollectionSlug),\n ),\n );\n const provisionedCandidates = classified.candidates.filter((candidate) =>\n provisionedCollections.has(candidate.collection),\n );\n return { provisionedCollections, provisionedCandidates };\n}\n\nasync function resolveCaptureCollection(params: {\n collection?: string;\n name: string;\n description: string;\n classifierFlagOn: boolean;\n supportedCollections: Set<ClassifiableCollectionSlug>;\n workspaceId: string;\n explicitCollectionProvided: boolean;\n}): Promise<CollectionResolution> {\n const {\n collection,\n name,\n description,\n classifierFlagOn,\n supportedCollections,\n workspaceId,\n explicitCollectionProvided,\n } = params;\n if (collection) {\n // FEAT-125/126: Run classifier as advisory validation even when collection is explicit.\n // Never changes routing — only populates receipt metadata.\n const classified = classifyCollection(name, description);\n if (classified) {\n const agrees = classified.collection === collection;\n const classifierMeta: CaptureClassifierMetadata = {\n enabled: true,\n autoRouted: false,\n agrees,\n abstained: false,\n topConfidence: classified.topConfidence,\n confidence: classified.confidence,\n reasons: classified.reasons,\n candidates: classified.candidates.slice(0, 3),\n agentProvidedCollection: collection,\n ...(!agrees && {\n overrideCommand: `capture collection=\"${classified.collection}\"`,\n }),\n };\n if (!agrees) {\n trackClassifierTelemetry({\n workspaceId,\n predictedCollection: classified.collection,\n confidence: classified.confidence,\n autoRouted: false,\n reasonCategory: \"low-confidence\",\n explicitCollectionProvided: true,\n outcome: \"fallback\",\n });\n }\n return { resolvedCollection: collection, classifierMeta };\n }\n // Classifier abstained — no signals matched. Don't claim agreement.\n return {\n resolvedCollection: collection,\n classifierMeta: {\n enabled: true,\n autoRouted: false,\n agrees: false,\n abstained: true,\n topConfidence: 0,\n confidence: 0,\n reasons: [],\n candidates: [],\n agentProvidedCollection: collection,\n },\n };\n }\n if (!classifierFlagOn) {\n return { earlyResult: buildCollectionRequiredResult() };\n }\n\n const classified = classifyCollection(name, description);\n if (!classified) {\n trackClassifierTelemetry({\n workspaceId,\n predictedCollection: \"unknown\",\n confidence: 0,\n autoRouted: false,\n reasonCategory: \"low-confidence\",\n explicitCollectionProvided,\n outcome: \"fallback\",\n });\n return { earlyResult: buildClassifierUnknownResult() };\n }\n\n const { provisionedCollections, provisionedCandidates } =\n await getProvisionedCollectionCandidates(classified, supportedCollections);\n\n if (!provisionedCollections.has(classified.collection)) {\n trackClassifierTelemetry({\n workspaceId,\n predictedCollection: classified.collection,\n confidence: classified.confidence,\n autoRouted: false,\n reasonCategory: \"non-provisioned\",\n explicitCollectionProvided,\n outcome: \"fallback\",\n });\n return {\n earlyResult: buildUnsupportedProvisioningResult(classified, provisionedCandidates),\n };\n }\n\n const autoRoute = shouldAutoRouteClassification(classified);\n const ambiguousRoute = isClassificationAmbiguous(classified);\n const classifierMeta: CaptureClassifierMetadata = {\n enabled: true,\n autoRouted: autoRoute,\n agrees: true,\n abstained: false,\n topConfidence: classified.topConfidence,\n confidence: classified.confidence,\n reasons: classified.reasons,\n candidates: provisionedCandidates,\n };\n\n if (!autoRoute) {\n trackClassifierTelemetry({\n workspaceId,\n predictedCollection: classified.collection,\n confidence: classified.confidence,\n autoRouted: false,\n reasonCategory: ambiguousRoute ? \"ambiguous\" : \"low-confidence\",\n explicitCollectionProvided,\n outcome: \"fallback\",\n });\n return {\n classifierMeta,\n earlyResult: buildAmbiguousRouteResult(classified, classifierMeta, ambiguousRoute),\n };\n }\n\n trackClassifierTelemetry({\n workspaceId,\n predictedCollection: classified.collection,\n confidence: classified.confidence,\n autoRouted: true,\n reasonCategory: \"auto-routed\",\n explicitCollectionProvided,\n outcome: \"auto-routed\",\n });\n\n return {\n resolvedCollection: classified.collection,\n classifierMeta,\n };\n}\n\nconst captureSuccessOutputSchema = z.object({\n entryId: z.string(),\n collection: z.string(),\n name: z.string(),\n status: z.enum([\"draft\", \"committed\", \"proposed\"]),\n qualityScore: z.number(),\n qualityVerdict: z.record(z.unknown()).optional(),\n classifier: captureClassifierSchema.optional(),\n studioUrl: z.string().optional(),\n}).strict();\n\nconst captureClassifierOnlyOutputSchema = z.object({\n classifier: captureClassifierSchema,\n}).strict();\n\nexport const captureOutputSchema = z.union([\n captureSuccessOutputSchema,\n captureClassifierOnlyOutputSchema,\n]);\n\nexport const batchCaptureOutputSchema = z.object({\n captured: z.array(z.object({\n entryId: z.string(),\n collection: z.string(),\n name: z.string(),\n })),\n total: z.number(),\n failed: z.number(),\n failedEntries: z.array(z.object({\n index: z.number(),\n collection: z.string(),\n name: z.string(),\n error: z.string(),\n })).optional(),\n});\n\nexport function registerSmartCaptureTools(server: McpServer) {\n const supportedCollections = new Set<ClassifiableCollectionSlug>(\n CLASSIFIABLE_COLLECTIONS.filter((slug) => PROFILES.has(slug)),\n );\n\n const captureTool = server.registerTool(\n \"capture\",\n {\n title: \"Capture\",\n description:\n \"The single tool for creating knowledge entries. Creates an entry, auto-links related entries, \" +\n \"and returns a quality scorecard — all in one call. \" +\n \"Provide a name and description; `collection` is optional when `capture-without-thinking` is enabled.\\n\\n\" +\n \"Supported collections with smart profiles: tensions, business-rules, glossary, decisions, features, \" +\n \"audiences, strategy, standards, maps, bets, insights, assumptions, principles, tracking-events.\\n\" +\n \"All other collections get an ENT-{random} ID and sensible defaults.\\n\\n\" +\n \"**Explicit data:** When you know the schema, pass `data: { field: value }` to set fields directly. \" +\n \"Top-level `name` and `description` always win for those fields. `data` wins over inference for all other fields.\\n\\n\" +\n \"**Compound capture:** Pass `links` to create relations in the same call (skips auto-link discovery). \" +\n \"Pass `autoCommit: true` to promote the entry from draft to SSOT immediately after linking. \" +\n \"Governed collections (glossary, business-rules, principles, standards, strategy, features, architecture) \" +\n \"will warn but still commit — use only when you're certain.\\n\\n\" +\n \"Always creates as 'draft' unless `autoCommit` is true. Use `update-entry` for post-creation adjustments.\",\n inputSchema: captureSchema.shape,\n annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: false },\n },\n withEnvelope(async ({ collection, name, description, context, entryId, canonicalKey, data: userData, links, autoCommit }) => {\n requireWriteAccess();\n\n const wsCtx = await getWorkspaceContext();\n const explicitCollectionProvided = typeof collection === \"string\" && collection.trim().length > 0;\n const classifierFlagOn = await isFeatureEnabled(\n CAPTURE_WITHOUT_THINKING_FLAG,\n wsCtx.workspaceId,\n wsCtx.workspaceSlug,\n );\n\n const resolution = await resolveCaptureCollection({\n collection,\n name,\n description,\n classifierFlagOn,\n supportedCollections,\n workspaceId: wsCtx.workspaceId,\n explicitCollectionProvided,\n });\n if (resolution.earlyResult) {\n return resolution.earlyResult;\n }\n const resolvedCollection = resolution.resolvedCollection;\n const classifierMeta = resolution.classifierMeta;\n if (!resolvedCollection) {\n return buildCollectionRequiredResult();\n }\n\n const profile = PROFILES.get(resolvedCollection) ?? FALLBACK_PROFILE;\n\n const col = await mcpQuery<any>(\"chain.getCollection\", { slug: resolvedCollection });\n if (!col) {\n const displayName = resolvedCollection.split(\"-\").map((w: string) => w.charAt(0).toUpperCase() + w.slice(1)).join(\" \");\n return {\n content: [{\n type: \"text\" as const,\n text:\n `Collection \\`${resolvedCollection}\\` not found.\\n\\n` +\n `**To create it**, run:\\n` +\n `\\`\\`\\`\\ncollections action=create slug=\"${resolvedCollection}\" name=\"${displayName}\" description=\"...\"\\n\\`\\`\\`\\n\\n` +\n `Or use \\`collections action=list\\` to see available collections.`,\n }],\n structuredContent: failure(\n \"NOT_FOUND\",\n `Collection '${resolvedCollection}' not found.`,\n \"Create the collection first, or use collections action=list to see available ones.\",\n [\n { tool: \"collections\", description: \"Create collection\", parameters: { action: \"create\", slug: resolvedCollection, name: displayName } },\n { tool: \"collections\", description: \"List collections\", parameters: { action: \"list\" } },\n ],\n ),\n };\n }\n\n // 2. Build data with profile defaults + inference\n const data: Record<string, unknown> = {};\n const today = new Date().toISOString().split(\"T\")[0];\n\n for (const field of col.fields ?? []) {\n const key = field.key as string;\n if (key === profile.descriptionField) {\n data[key] = description;\n } else if (field.type === \"array\" || field.type === \"multi-select\") {\n data[key] = [];\n } else if (field.type === \"select\") {\n // Skip — empty string is not a valid option for select fields\n } else {\n data[key] = \"\";\n }\n }\n\n for (const def of profile.defaults) {\n if (def.value === \"today\") {\n data[def.key] = today;\n } else if (def.value !== \"infer\") {\n data[def.key] = def.value;\n }\n }\n\n if (profile.inferField) {\n const inferred = profile.inferField({\n collection: resolvedCollection, name, description, context, data, entryId: \"\",\n linksCreated: [], linksSuggested: [], collectionFields: col.fields ?? [],\n });\n for (const [key, val] of Object.entries(inferred)) {\n if (val !== undefined && val !== \"\") {\n data[key] = val;\n }\n }\n }\n\n // Merge user-provided data (wins over inference for those fields)\n if (userData && typeof userData === \"object\") {\n for (const [key, val] of Object.entries(userData)) {\n if (key !== \"name\") data[key] = val;\n }\n }\n\n // Top-level description always wins\n data[profile.descriptionField || \"description\"] = description;\n\n // 3. Determine status\n const status = \"draft\";\n const agentId = getAgentSessionId();\n\n // 4. Create entry (Convex generates sequential ID when entryId not provided)\n let finalEntryId: string;\n let internalId: string;\n try {\n const result = await mcpMutation<{ docId: string; entryId: string }>(\"chain.createEntry\", {\n collectionSlug: resolvedCollection,\n entryId: entryId ?? undefined,\n name,\n status,\n data,\n canonicalKey,\n createdBy: agentId ? `agent:${agentId}` : \"capture\",\n sessionId: agentId ?? undefined,\n });\n internalId = result.docId;\n finalEntryId = result.entryId;\n } catch (error: unknown) {\n const msg = error instanceof Error ? error.message : String(error);\n if (msg.includes(\"Duplicate\") || msg.includes(\"already exists\")) {\n return {\n content: [{\n type: \"text\" as const,\n text: `# Cannot Capture — Duplicate Detected\\n\\n${msg}\\n\\nUse \\`entries action=get\\` to inspect the existing entry, or \\`update-entry\\` to modify it.`,\n }],\n structuredContent: failure(\n \"DUPLICATE\",\n msg,\n \"Use entries action=get to inspect the existing entry.\",\n [\n { tool: \"entries\", description: \"Get existing entry\", parameters: { action: \"get\", entryId: entryId ?? name } },\n { tool: \"update-entry\", description: \"Update existing entry\", parameters: { entryId: entryId ?? \"\" } },\n ],\n ),\n };\n }\n throw error;\n }\n\n // 6. Discover and auto-link related entries\n const linksCreated: LinkResult[] = [];\n const linksSuggested: LinkSuggestion[] = [];\n const userLinkResults: Array<{ label: string; ok: boolean }> = [];\n\n const skipAutoDiscovery = links && links.length > 0;\n const searchQuery = extractSearchTerms(name, description);\n if (searchQuery && !skipAutoDiscovery) {\n const [searchResults, allCollections] = await Promise.all([\n mcpQuery<any[]>(\"chain.searchEntries\", { query: searchQuery }),\n mcpQuery<any[]>(\"chain.listCollections\"),\n ]);\n\n const collMap = new Map<string, string>();\n for (const c of allCollections) collMap.set(c._id, c.slug);\n\n const candidates = (searchResults ?? [])\n .filter((r) => r.entryId !== finalEntryId && r._id !== internalId)\n .map((r) => {\n const conf = computeLinkConfidence(r, name, description, resolvedCollection, collMap.get(r.collectionId) ?? \"unknown\");\n return {\n ...r,\n collSlug: collMap.get(r.collectionId) ?? \"unknown\",\n confidence: conf.score,\n confidenceReason: conf.reason,\n };\n })\n .sort((a, b) => b.confidence - a.confidence);\n\n // Auto-link high-confidence matches\n for (const c of candidates) {\n if (linksCreated.length >= MAX_AUTO_LINKS) break;\n if (c.confidence < AUTO_LINK_CONFIDENCE_THRESHOLD) break;\n if (!c.entryId || !finalEntryId) continue;\n\n const { type: relationType, reason: relationReason } = inferRelationType(resolvedCollection, c.collSlug, profile);\n try {\n await mcpMutation(\"chain.createEntryRelation\", {\n fromEntryId: finalEntryId,\n toEntryId: c.entryId,\n type: relationType,\n sessionId: agentId ?? undefined,\n });\n linksCreated.push({\n targetEntryId: c.entryId,\n targetName: c.name,\n targetCollection: c.collSlug,\n relationType,\n linkReason: `confidence ${c.confidence} (${(c as any).confidenceReason}) + ${relationReason}`,\n });\n } catch {\n // Relation creation failed (e.g. entry not found) — skip silently\n }\n }\n\n // Collect suggestions for remaining candidates\n const linkedIds = new Set(linksCreated.map((l) => l.targetEntryId));\n for (const c of candidates) {\n if (linksSuggested.length >= MAX_SUGGESTIONS) break;\n if (linkedIds.has(c.entryId)) continue;\n if (c.confidence < 10) continue;\n\n const preview = extractPreview(c.data, 80);\n const reason = c.confidence >= AUTO_LINK_CONFIDENCE_THRESHOLD\n ? \"high relevance (already linked)\"\n : `\"${c.name.toLowerCase().split(/\\s+/).filter((w: string) => `${name} ${description}`.toLowerCase().includes(w) && w.length > 3).slice(0, 2).join('\", \"')}\" appears in content`;\n\n linksSuggested.push({\n entryId: c.entryId,\n name: c.name,\n collection: c.collSlug,\n reason,\n preview,\n });\n }\n }\n\n // 6b. Create user-specified links\n if (links && links.length > 0 && finalEntryId) {\n for (const link of links) {\n try {\n await mcpMutation(\"chain.createEntryRelation\", {\n fromEntryId: finalEntryId,\n toEntryId: link.to,\n type: link.type,\n sessionId: agentId ?? undefined,\n });\n userLinkResults.push({ label: `✓ ${link.type} → ${link.to}`, ok: true });\n linksCreated.push({\n targetEntryId: link.to,\n targetName: link.to,\n targetCollection: \"unknown\",\n relationType: link.type,\n });\n } catch (e: unknown) {\n const msg = e instanceof Error ? e.message : \"failed\";\n userLinkResults.push({ label: `✗ ${link.type} → ${link.to}: ${msg}`, ok: false });\n }\n }\n }\n\n // 7. Score quality\n const captureCtx: CaptureContext = {\n collection: resolvedCollection,\n name,\n description,\n context,\n data,\n entryId: finalEntryId,\n canonicalKey,\n linksCreated,\n linksSuggested,\n collectionFields: col.fields ?? [],\n };\n const quality = scoreQuality(captureCtx, profile);\n\n // 8. Cardinality check for singleton types\n let cardinalityWarning: string | null = null;\n const resolvedCK = canonicalKey ?? (captureCtx as any).canonicalKey;\n if (resolvedCK) {\n try {\n const check = await mcpQuery<any>(\"chain.checkCardinalityWarning\", {\n canonicalKey: resolvedCK,\n });\n if (check?.warning) {\n cardinalityWarning = check.warning;\n }\n } catch {\n // Advisory — capture succeeds without cardinality check\n }\n }\n\n // 9. Keyword contradiction check against governance entries\n const contradictionWarnings = await runContradictionCheck(name, description);\n if (contradictionWarnings.length > 0) {\n await recordSessionActivity({ contradictionWarning: true });\n }\n\n // 10. Quality coaching (heuristic instant, LLM scheduled in background)\n let coachingSection = \"\";\n let verdictResult: any = null;\n try {\n verdictResult = await mcpMutation<any>(\"quality.evaluateHeuristicAndSchedule\", {\n entryId: finalEntryId,\n context: \"capture\",\n });\n if (verdictResult?.verdict && verdictResult.verdict.tier !== \"passive\" && verdictResult.verdict.criteria.length > 0) {\n coachingSection = formatRubricCoaching(verdictResult);\n }\n } catch {\n // Quality coaching is advisory — capture succeeds without it\n }\n\n // 11. Track quality verdict\n if (verdictResult?.verdict) {\n try {\n const wsForTracking = await getWorkspaceContext();\n const v = verdictResult.verdict;\n const failedCount = (v.criteria ?? []).filter((c: any) => !c.passed).length;\n trackQualityVerdict(wsForTracking.workspaceId, {\n entry_id: finalEntryId,\n entry_type: v.canonicalKey ?? resolvedCollection,\n tier: v.tier,\n context: \"capture\",\n passed: v.passed,\n source: verdictResult.source ?? \"heuristic\",\n criteria_total: v.criteria?.length ?? 0,\n criteria_failed: failedCount,\n llm_scheduled: v.tier !== \"passive\",\n });\n } catch { /* tracking is advisory */ }\n }\n\n // 12. Auto-commit if requested (or defaulted via Open governance mode).\n // BET-76 FEAT-111: When autoCommit is not explicitly set, default to true for\n // Open mode workspaces. Consensus/role modes retain draft-first behavior.\n // Agent-inferred entries (e.g. project scan) should pass autoCommit=false explicitly.\n const shouldAutoCommit =\n autoCommit === true ||\n (autoCommit === undefined && wsCtx.governanceMode === \"open\");\n\n let finalStatus: \"draft\" | \"committed\" | \"proposed\" = \"draft\";\n let commitError: string | null = null;\n if (shouldAutoCommit && finalEntryId) {\n try {\n const commitResult = await mcpMutation<any>(\"chain.commitEntry\", {\n entryId: finalEntryId,\n author: agentId ? `agent:${agentId}` : undefined,\n sessionId: agentId ?? undefined,\n });\n finalStatus = commitResult?.status === \"proposal_created\" ? \"proposed\" : \"committed\";\n if (finalStatus === \"committed\") {\n await recordSessionActivity({ entryModified: internalId });\n }\n } catch (e: unknown) {\n commitError = e instanceof Error ? e.message : \"unknown error\";\n // Store as draft with error flag — do not throw silently (BET-76 RH4)\n }\n }\n\n // 13. Format response\n const lines: string[] = [\n `# Captured: ${finalEntryId || name}`,\n `**${name}** added to \\`${resolvedCollection}\\` as \\`${finalStatus}\\``,\n `**Workspace:** ${wsCtx.workspaceSlug} (${wsCtx.workspaceId})`,\n ];\n\n if (classifierMeta) {\n lines.push(\"\");\n lines.push(\"## Classification\");\n if (classifierMeta.abstained) {\n lines.push(`No classifier coverage for \\`${resolvedCollection}\\` — entry accepted as-is.`);\n } else if (classifierMeta.autoRouted) {\n lines.push(`Auto-routed to \\`${resolvedCollection}\\` (${classifierMeta.topConfidence}% confidence).`);\n if (classifierMeta.reasons.length > 0) {\n lines.push(`Reason: ${classifierMeta.reasons.join(\"; \")}.`);\n }\n lines.push(`Override: rerun with explicit \\`collection\\` if wrong.`);\n } else if (classifierMeta.agrees) {\n lines.push(`Classifier confirms \\`${resolvedCollection}\\` (${classifierMeta.topConfidence}% confidence).`);\n } else {\n const suggested = classifierMeta.candidates[0]?.collection ?? \"unknown\";\n lines.push(`Classifier suggests \\`${suggested}\\` (${classifierMeta.topConfidence}% confidence) — review classification.`);\n if (classifierMeta.reasons.length > 0) {\n lines.push(`Reason: ${classifierMeta.reasons.join(\"; \")}.`);\n }\n if (classifierMeta.overrideCommand) {\n lines.push(`Override: \\`${classifierMeta.overrideCommand}\\``);\n }\n }\n }\n\n // BET-chain-native-constellation: Studio link for bets — DEC-70 (structuredContent studioUrl)\n const appUrl = process.env.PRODUCTBRAIN_APP_URL ?? \"https://productbrain.io\";\n const studioUrl =\n resolvedCollection === \"bets\"\n ? `${appUrl.replace(/\\/$/, \"\")}/w/${wsCtx.workspaceSlug}/studio/${internalId}`\n : undefined;\n if (studioUrl) {\n lines.push(\"\");\n lines.push(`**View in Studio:** ${studioUrl}`);\n }\n\n if (linksCreated.length > 0) {\n lines.push(\"\");\n lines.push(`## Auto-linked (${linksCreated.length})`);\n for (const link of linksCreated) {\n const reason = (link as any).linkReason ? ` — because ${(link as any).linkReason}` : \"\";\n lines.push(`- -> **${link.relationType}** ${link.targetEntryId}: ${link.targetName} [${link.targetCollection}]${reason}`);\n }\n }\n\n if (userLinkResults.length > 0) {\n lines.push(\"\");\n lines.push(\"## Requested links\");\n for (const r of userLinkResults) lines.push(`- ${r.label}`);\n }\n\n if (finalStatus === \"committed\") {\n const wasAutoCommitted = autoCommit === undefined && wsCtx.governanceMode === \"open\";\n lines.push(\"\");\n lines.push(`## Committed: ${finalEntryId}`);\n if (wasAutoCommitted) {\n lines.push(`**${name}** added to your knowledge base.`);\n } else {\n lines.push(`**${name}** promoted to SSOT on the Chain.`);\n }\n if (GOVERNED_COLLECTIONS.has(resolvedCollection)) {\n lines.push(`_Note: \\`${resolvedCollection}\\` is a governed collection — ensure this entry has been reviewed._`);\n }\n } else if (finalStatus === \"proposed\") {\n lines.push(\"\");\n lines.push(`## Proposal created: ${finalEntryId}`);\n lines.push(`**${name}** requires consent before it can be committed, so a proposal was created instead of publishing directly.`);\n } else if (commitError) {\n lines.push(\"\");\n lines.push(\"## Commit failed\");\n lines.push(`Error: ${commitError}. Entry saved as draft — use \\`commit-entry entryId=\"${finalEntryId}\"\\` to promote when ready.`);\n }\n\n if (linksSuggested.length > 0) {\n lines.push(\"\");\n lines.push(\"## Suggested links (review and use `relations action=create`)\");\n for (let i = 0; i < linksSuggested.length; i++) {\n const s = linksSuggested[i];\n const preview = s.preview ? ` — ${s.preview}` : \"\";\n lines.push(`${i + 1}. **${s.entryId ?? \"(no ID)\"}**: ${s.name} [${s.collection}]${preview}`);\n }\n }\n\n lines.push(\"\");\n lines.push(formatQualityReport(quality));\n\n const failedChecks = quality.checks.filter((c) => !c.passed);\n if (failedChecks.length > 0) {\n lines.push(\"\");\n lines.push(`_To improve: \\`update-entry entryId=\"${finalEntryId}\"\\` to fill missing fields._`);\n }\n\n // Strategy-link warning for bet/goal (ENT-ldomlr: Intelligence Surface)\n const isBetOrGoal =\n resolvedCollection === \"bets\" ||\n resolvedCK === \"bet\" ||\n resolvedCK === \"goal\";\n const hasStrategyLink = linksCreated.some((l) => l.targetCollection === \"strategy\");\n if (isBetOrGoal && !hasStrategyLink) {\n lines.push(\"\");\n lines.push(\n `**Strategy link:** This ${resolvedCollection === \"bets\" ? \"bet\" : \"goal\"} doesn't connect to any strategy entry. Consider linking before commit. Use \\`graph action=suggest entryId=\"${finalEntryId}\"\\` to find strategy entries to connect to.`\n );\n await recordSessionActivity({ strategyLinkWarnedForEntryId: internalId });\n }\n\n // Cardinality warning for singleton types (DEC-zcuhvb)\n if (cardinalityWarning) {\n lines.push(\"\");\n lines.push(`**Cardinality warning:** ${cardinalityWarning}`);\n }\n\n // Contradiction warnings — exact format per spec\n if (contradictionWarnings.length > 0) {\n lines.push(\"\");\n lines.push(\"⚠ Contradiction check: proposed entry matched existing governance entries:\");\n for (const w of contradictionWarnings) {\n lines.push(`- ${w.name} (${w.collection}, ${w.entryId}) — has 'governs' relation to ${w.governsCount} entries`);\n }\n lines.push(\"Run `context action=gather` on these entries before committing.\");\n }\n\n // Rubric coaching (assertive/nudge only)\n if (coachingSection) {\n lines.push(\"\");\n lines.push(coachingSection);\n }\n\n // Next steps: adapt based on what was already done\n lines.push(\"\");\n lines.push(\"## Next Steps\");\n const eid = finalEntryId || \"(check entry ID)\";\n if (finalStatus === \"committed\") {\n lines.push(`1. **Connect it:** \\`graph action=suggest entryId=\"${eid}\"\\` — discover additional links`);\n if (failedChecks.length > 0) {\n lines.push(`2. **Improve quality:** \\`update-entry entryId=\"${eid}\"\\` — fill missing fields`);\n }\n } else if (finalStatus === \"proposed\") {\n lines.push(`1. **Connect it:** \\`graph action=suggest entryId=\"${eid}\"\\` — discover additional links to support the proposal`);\n if (failedChecks.length > 0) {\n lines.push(`2. **Improve quality:** \\`update-entry entryId=\"${eid}\"\\` — strengthen the entry before approval`);\n }\n } else {\n if (userLinkResults.length === 0) {\n lines.push(`1. **Connect it:** \\`graph action=suggest entryId=\"${eid}\"\\` — discover what this should link to`);\n }\n lines.push(`${userLinkResults.length === 0 ? \"2\" : \"1\"}. **Commit it:** \\`commit-entry entryId=\"${eid}\"\\` — promote from draft to SSOT on the Chain`);\n if (failedChecks.length > 0) {\n lines.push(`${userLinkResults.length === 0 ? \"3\" : \"2\"}. **Improve quality:** \\`update-entry entryId=\"${eid}\"\\` — fill missing fields`);\n }\n }\n\n // Advisory: workspace readiness hints (never blocking)\n try {\n const readiness = await mcpQuery<any>(\"chain.workspaceReadiness\");\n if (readiness && readiness.gaps && readiness.gaps.length > 0) {\n const topGaps = readiness.gaps.slice(0, 2);\n lines.push(\"\");\n lines.push(`## Workspace Readiness: ${readiness.score}%`);\n for (const gap of topGaps) {\n lines.push(`- _${gap.label}:_ ${gap.guidance}`);\n }\n }\n } catch {\n // Readiness check is advisory — capture works without it\n }\n\n // Context-sensitive next: adapt based on what was already done\n const next: NextAction[] = [];\n if (finalStatus === \"committed\") {\n next.push({ tool: \"graph\", description: \"Discover connections\", parameters: { action: \"suggest\", entryId: finalEntryId } });\n } else if (finalStatus === \"proposed\") {\n next.push({ tool: \"graph\", description: \"Discover connections\", parameters: { action: \"suggest\", entryId: finalEntryId } });\n } else {\n if (userLinkResults.length === 0) {\n next.push({ tool: \"graph\", description: \"Discover links\", parameters: { action: \"suggest\", entryId: finalEntryId } });\n }\n next.push({ tool: \"commit-entry\", description: \"Commit to Chain\", parameters: { entryId: finalEntryId } });\n }\n\n const summary = finalStatus === \"committed\"\n ? `Captured and committed ${finalEntryId} (${name}) to ${resolvedCollection}. Quality ${quality.score}/10.`\n : finalStatus === \"proposed\"\n ? `Captured ${finalEntryId} (${name}) in ${resolvedCollection} and created a proposal for commit. Quality ${quality.score}/10.`\n : `Captured ${finalEntryId} (${name}) as draft in ${resolvedCollection}. Quality ${quality.score}/10.`;\n\n const toolResult = {\n content: [{ type: \"text\" as const, text: lines.join(\"\\n\") }],\n structuredContent: success(\n summary,\n {\n entryId: finalEntryId,\n collection: resolvedCollection,\n name,\n status: finalStatus,\n qualityScore: quality.score,\n qualityVerdict: verdictResult?.verdict\n ? { ...verdictResult.verdict, source: verdictResult.source ?? \"heuristic\" }\n : undefined,\n ...(classifierMeta && { classifier: classifierMeta }),\n ...(studioUrl && { studioUrl }),\n },\n next,\n ),\n };\n\n return toolResult;\n })\n );\n trackWriteTool(captureTool);\n\n // ── Batch Capture Tool ─────────────────────────────────────────────────\n\n const batchCaptureTool = server.registerTool(\n \"batch-capture\",\n {\n title: \"Batch Capture\",\n description:\n \"Create multiple knowledge entries in one call. Ideal for workspace setup, document ingestion, \" +\n \"or any scenario where you need to capture many entries at once.\\n\\n\" +\n \"Each entry is created independently — if one fails, the others still succeed. \" +\n \"Returns a compact summary instead of per-entry quality scorecards.\\n\\n\" +\n \"Auto-linking runs per entry but contradiction checks and readiness hints are skipped for speed. \" +\n \"Use `quality action=check` on individual entries afterward if needed.\",\n inputSchema: batchCaptureSchema.shape,\n annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: false },\n },\n withEnvelope(async ({ entries }) => {\n requireWriteAccess();\n\n const agentId = getAgentSessionId();\n const createdBy = agentId ? `agent:${agentId}` : \"capture\";\n\n const results: Array<{\n name: string;\n collection: string;\n entryId: string;\n ok: boolean;\n autoLinks: number;\n error?: string;\n }> = [];\n\n await server.sendLoggingMessage({\n level: \"info\",\n data: `Batch capturing ${entries.length} entries...`,\n logger: \"product-brain\",\n });\n\n const allCollections = await mcpQuery<any[]>(\"chain.listCollections\");\n const collCache = new Map<string, any>();\n for (const c of allCollections) collCache.set(c.slug, c);\n const collIdToSlug = new Map<string, string>();\n for (const c of allCollections) collIdToSlug.set(c._id, c.slug);\n\n for (let entryIdx = 0; entryIdx < entries.length; entryIdx++) {\n const entry = entries[entryIdx];\n\n if (entryIdx > 0 && entryIdx % 5 === 0) {\n await server.sendLoggingMessage({\n level: \"info\",\n data: `Captured ${entryIdx}/${entries.length} entries...`,\n logger: \"product-brain\",\n });\n }\n const profile = PROFILES.get(entry.collection) ?? FALLBACK_PROFILE;\n const col = collCache.get(entry.collection);\n\n if (!col) {\n results.push({ name: entry.name, collection: entry.collection, entryId: \"\", ok: false, autoLinks: 0, error: `Collection \"${entry.collection}\" not found` });\n continue;\n }\n\n const data: Record<string, unknown> = {};\n const today = new Date().toISOString().split(\"T\")[0];\n\n for (const field of col.fields ?? []) {\n const key = field.key as string;\n if (key === profile.descriptionField) {\n data[key] = entry.description;\n } else if (field.type === \"array\" || field.type === \"multi-select\") {\n data[key] = [];\n } else if (field.type === \"select\") {\n // Skip — empty string is not a valid option for select fields\n } else {\n data[key] = \"\";\n }\n }\n\n for (const def of profile.defaults) {\n if (def.value === \"today\") data[def.key] = today;\n else if (def.value !== \"infer\") data[def.key] = def.value;\n }\n\n if (profile.inferField) {\n const inferred = profile.inferField({\n collection: entry.collection, name: entry.name, description: entry.description,\n data, entryId: \"\", linksCreated: [], linksSuggested: [], collectionFields: col.fields ?? [],\n });\n for (const [key, val] of Object.entries(inferred)) {\n if (val !== undefined && val !== \"\") data[key] = val;\n }\n }\n\n if (!data[profile.descriptionField] && !data.description && !data.canonical) {\n data[profile.descriptionField || \"description\"] = entry.description;\n }\n\n try {\n const result = await mcpMutation<{ docId: string; entryId: string }>(\"chain.createEntry\", {\n collectionSlug: entry.collection,\n entryId: entry.entryId ?? undefined,\n name: entry.name,\n status: \"draft\",\n data,\n createdBy,\n sessionId: agentId ?? undefined,\n });\n const internalId = result.docId;\n const finalEntryId = result.entryId;\n\n let autoLinkCount = 0;\n const searchQuery = extractSearchTerms(entry.name, entry.description);\n if (searchQuery) {\n try {\n const searchResults = await mcpQuery<any[]>(\"chain.searchEntries\", { query: searchQuery });\n const candidates = (searchResults ?? [])\n .filter((r) => r.entryId !== finalEntryId)\n .map((r) => {\n const conf = computeLinkConfidence(r, entry.name, entry.description, entry.collection, collIdToSlug.get(r.collectionId) ?? \"unknown\");\n return {\n ...r,\n collSlug: collIdToSlug.get(r.collectionId) ?? \"unknown\",\n confidence: conf.score,\n };\n })\n .sort((a, b) => b.confidence - a.confidence);\n\n for (const c of candidates) {\n if (autoLinkCount >= MAX_AUTO_LINKS) break;\n if (c.confidence < AUTO_LINK_CONFIDENCE_THRESHOLD) break;\n if (!c.entryId) continue;\n const { type: relationType } = inferRelationType(entry.collection, c.collSlug, profile);\n try {\n await mcpMutation(\"chain.createEntryRelation\", {\n fromEntryId: finalEntryId,\n toEntryId: c.entryId,\n type: relationType,\n sessionId: agentId ?? undefined,\n });\n autoLinkCount++;\n } catch { /* skip failed link */ }\n }\n } catch { /* search failed; entry still created */ }\n }\n\n results.push({ name: entry.name, collection: entry.collection, entryId: finalEntryId, ok: true, autoLinks: autoLinkCount });\n } catch (error: unknown) {\n const msg = error instanceof Error ? error.message : String(error);\n results.push({ name: entry.name, collection: entry.collection, entryId: \"\", ok: false, autoLinks: 0, error: msg });\n }\n }\n\n const created = results.filter((r) => r.ok);\n const failed = results.filter((r) => !r.ok);\n\n await server.sendLoggingMessage({\n level: \"info\",\n data: `Batch complete. ${created.length} succeeded, ${failed.length} failed.`,\n logger: \"product-brain\",\n });\n\n const totalAutoLinks = created.reduce((sum, r) => sum + r.autoLinks, 0);\n\n const byCollection = new Map<string, number>();\n for (const r of created) {\n byCollection.set(r.collection, (byCollection.get(r.collection) ?? 0) + 1);\n }\n\n const lines: string[] = [\n `# Batch Capture Complete`,\n `**${created.length}** created, **${failed.length}** failed out of ${entries.length} total.`,\n `**Auto-links created:** ${totalAutoLinks}`,\n \"\",\n ];\n\n if (byCollection.size > 0) {\n lines.push(\"## By Collection\");\n for (const [col, count] of byCollection) {\n lines.push(`- \\`${col}\\`: ${count} entries`);\n }\n lines.push(\"\");\n }\n\n if (created.length > 0) {\n lines.push(\"## Created\");\n for (const r of created) {\n const linkNote = r.autoLinks > 0 ? ` (${r.autoLinks} auto-links)` : \"\";\n lines.push(`- **${r.entryId}**: ${r.name} [${r.collection}]${linkNote}`);\n }\n }\n\n if (failed.length > 0) {\n lines.push(\"\");\n lines.push(\"## Failed\");\n for (const r of failed) {\n lines.push(`- ${r.name} [${r.collection}]: _${r.error}_`);\n }\n lines.push(\"\");\n lines.push(`_If failed > 0, inspect \\`failedEntries\\` in the structured response and retry individually._`);\n }\n\n const entryIds = created.map((r) => r.entryId);\n if (entryIds.length > 0) {\n lines.push(\"\");\n lines.push(\"## Next Steps\");\n lines.push(`- **Connect:** Run \\`graph action=suggest\\` on key entries to build the knowledge graph`);\n lines.push(`- **Commit:** Use \\`commit-entry\\` to promote drafts to SSOT`);\n lines.push(`- **Quality:** Run \\`quality action=check\\` on individual entries to assess completeness`);\n }\n\n const summary = failed.length > 0\n ? `Batch captured ${created.length}/${entries.length} entries (${failed.length} failed).`\n : `Batch captured ${created.length} entries successfully.`;\n\n const next: NextAction[] = created.length > 0\n ? [\n { tool: \"graph\", description: \"Discover connections\", parameters: { action: \"suggest\", entryId: created[0].entryId } },\n { tool: \"commit-entry\", description: \"Commit first entry\", parameters: { entryId: created[0].entryId } },\n ]\n : [];\n\n return {\n content: [{ type: \"text\" as const, text: lines.join(\"\\n\") }],\n structuredContent: success(\n summary,\n {\n captured: created.map((r) => ({ entryId: r.entryId, collection: r.collection, name: r.name })),\n total: created.length,\n failed: failed.length,\n ...(failed.length > 0 && {\n failedEntries: failed.map((r) => ({\n index: results.indexOf(r),\n collection: r.collection,\n name: r.name,\n error: r.error ?? \"unknown error\",\n })),\n }),\n },\n next,\n ),\n };\n })\n );\n trackWriteTool(batchCaptureTool);\n\n}\n\n// ── Helpers ────────────────────────────────────────────────────────────────\n\n\n// Stop words excluded from noun phrase extraction\nconst STOP_WORDS = new Set([\n \"the\", \"and\", \"for\", \"are\", \"but\", \"not\", \"you\", \"all\", \"can\", \"has\", \"her\",\n \"was\", \"one\", \"our\", \"out\", \"day\", \"had\", \"hot\", \"how\", \"its\", \"may\", \"new\",\n \"now\", \"old\", \"see\", \"way\", \"who\", \"did\", \"get\", \"let\", \"say\", \"she\", \"too\",\n \"use\", \"from\", \"have\", \"been\", \"each\", \"that\", \"this\", \"with\", \"will\", \"they\",\n \"what\", \"when\", \"make\", \"like\", \"long\", \"look\", \"many\", \"some\", \"them\", \"than\",\n \"most\", \"only\", \"over\", \"such\", \"into\", \"also\", \"back\", \"just\", \"much\", \"must\",\n \"name\", \"very\", \"your\", \"after\", \"which\", \"their\", \"about\", \"would\", \"there\",\n \"should\", \"could\", \"other\", \"these\", \"first\", \"being\", \"those\", \"still\", \"where\",\n]);\n\nfunction tokenizeText(input: string): string[] {\n return input\n .toLowerCase()\n .replace(/[^\\p{L}\\p{N}\\s]+/gu, \" \")\n .split(/\\s+/)\n .filter(Boolean);\n}\n\n/**\n * Keyword contradiction check against governance entries.\n * Extracts terms 4+ chars, searches architecture and business-rules,\n * checks for 'governs' relations, returns formatted warnings.\n * Non-blocking — never throws, never prevents the operation.\n */\nexport interface ContradictionWarning {\n entryId: string;\n name: string;\n collection: string;\n governsCount: number;\n}\n\nexport async function runContradictionCheck(\n name: string,\n description: string,\n): Promise<ContradictionWarning[]> {\n const warnings: ContradictionWarning[] = [];\n try {\n const keyTerms = tokenizeText(`${name} ${description}`)\n .filter((w) => w.length >= 4 && !STOP_WORDS.has(w))\n .slice(0, 8);\n\n if (keyTerms.length === 0) return warnings;\n\n const searchQuery = keyTerms.slice(0, 5).join(\" \");\n const [govResults, archResults] = await Promise.all([\n mcpQuery<any[]>(\"chain.searchEntries\", { query: searchQuery, collectionSlug: \"business-rules\" }),\n mcpQuery<any[]>(\"chain.searchEntries\", { query: searchQuery, collectionSlug: \"architecture\" }),\n ]);\n\n const allGov = [...(govResults ?? []), ...(archResults ?? [])].slice(0, 5);\n\n for (const entry of allGov) {\n const entryTokens = new Set(tokenizeText(`${entry.name} ${entry.data?.description ?? \"\"}`));\n const matched = keyTerms.filter((t) => entryTokens.has(t));\n if (matched.length < 3) continue;\n\n // Check for 'governs' relations\n let governsCount = 0;\n try {\n const relations = await mcpQuery<any[]>(\"chain.listEntryRelations\", {\n entryId: entry.entryId,\n });\n governsCount = (relations ?? []).filter((r: any) => r.type === \"governs\").length;\n } catch { /* non-critical */ }\n\n warnings.push({\n entryId: entry.entryId ?? \"\",\n name: entry.name,\n collection: entry.collectionSlug ?? \"\",\n governsCount,\n });\n }\n } catch {\n // Contradiction check is advisory — never blocks the operation\n }\n return warnings;\n}\n\n// ── Quality Coaching Helpers ──────────────────────────────────────────────\n\nfunction withTimeout<T>(promise: Promise<T>, ms: number): Promise<T> {\n return Promise.race([\n promise,\n new Promise<T>((_, reject) =>\n setTimeout(() => reject(new Error(\"quality coaching timeout\")), ms),\n ),\n ]);\n}\n\n/**\n * Format a full quality coaching result (from evaluateAtCapture / evaluateAtCommit)\n * for inclusion in MCP capture/commit responses.\n */\nexport function formatRubricCoaching(result: any): string {\n const { verdict, rogerMartin } = result;\n if (!verdict || verdict.criteria.length === 0) return \"\";\n\n const lines: string[] = [\"## Semantic Quality\"];\n const failed = (verdict.criteria ?? []).filter((c: any) => !c.passed);\n const total = verdict.criteria?.length ?? 0;\n const passedCount = total - failed.length;\n\n if (verdict.passed) {\n lines.push(`All ${total} rubric criteria pass for \\`${verdict.canonicalKey}\\` (${verdict.tier} tier).`);\n } else {\n lines.push(`${passedCount}/${total} criteria pass for \\`${verdict.canonicalKey}\\` (${verdict.tier} tier)`);\n lines.push(\"\");\n for (const c of verdict.criteria) {\n const icon = c.passed ? \"[x]\" : \"[ ]\";\n const extra = c.passed ? \"\" : ` — ${c.hint}`;\n lines.push(`${icon} ${c.id}${extra}`);\n }\n\n if (verdict.weakest) {\n lines.push(\"\");\n lines.push(`**Coaching hint:** ${verdict.weakest.hint}`);\n lines.push(`_Question to consider:_ ${verdict.weakest.questionTemplate}`);\n }\n }\n\n if (rogerMartin) {\n lines.push(\"\");\n lines.push(\"### Roger Martin Test\");\n if (rogerMartin.isStrategicChoice) {\n lines.push(\"This principle passes — the opposite is a reasonable strategic choice.\");\n } else {\n lines.push(`This principle may not be a strategic choice. ${rogerMartin.reasoning}`);\n if (rogerMartin.suggestion) {\n lines.push(`_Suggestion:_ ${rogerMartin.suggestion}`);\n }\n }\n }\n\n return lines.join(\"\\n\");\n}\n\n/**\n * Format a cached rubric verdict section for quality check responses.\n * SOS-e4r5cn: capability and visibility must ship together.\n */\nexport function formatRubricVerdictSection(verdict: any): string {\n if (!verdict || !verdict.criteria || verdict.criteria.length === 0) return \"\";\n\n const lines: string[] = [\"## Semantic Quality\"];\n const failed = verdict.criteria.filter((c: any) => !c.passed);\n const total = verdict.criteria.length;\n const passedCount = total - failed.length;\n\n const durationSuffix = verdict.llmDurationMs ? ` in ${(verdict.llmDurationMs / 1000).toFixed(1)}s` : '';\n const statusNote = verdict.llmStatus === 'pending'\n ? ' — LLM evaluation in progress...'\n : verdict.llmStatus === 'failed'\n ? ` — LLM evaluation failed${verdict.llmError ? `: ${verdict.llmError}` : ''}, showing heuristic results`\n : verdict.source === 'llm' && durationSuffix\n ? ` — evaluated${durationSuffix}`\n : '';\n\n if (failed.length === 0) {\n lines.push(`All ${total} rubric criteria pass for \\`${verdict.canonicalKey}\\` (${verdict.tier} tier, ${verdict.source} evaluation).${statusNote}`);\n } else {\n lines.push(`${passedCount}/${total} criteria pass for \\`${verdict.canonicalKey}\\` (${verdict.tier} tier, ${verdict.source} evaluation)${statusNote}`);\n lines.push(\"\");\n for (const c of verdict.criteria) {\n const icon = c.passed ? \"[x]\" : \"[ ]\";\n const extra = c.passed ? \"\" : ` — ${c.hint}`;\n lines.push(`${icon} ${c.id}${extra}`);\n }\n\n if (verdict.weakest) {\n lines.push(\"\");\n lines.push(`**Top improvement:** ${verdict.weakest.hint}`);\n }\n }\n\n if (verdict.rogerMartin) {\n const rm = verdict.rogerMartin;\n lines.push(\"\");\n lines.push(\"### Roger Martin Test\");\n if (rm.isStrategicChoice) {\n lines.push(`This is a real strategic choice — the opposite is reasonable. ${rm.reasoning}`);\n } else {\n lines.push(`This may not be a strategic choice. ${rm.reasoning}`);\n if (rm.suggestion) {\n lines.push(`_Suggestion:_ ${rm.suggestion}`);\n }\n }\n }\n\n return lines.join(\"\\n\");\n}\n","/**\n * MCP client — communicates with the Convex HTTP Action gateway.\n *\n * Dual mode:\n * stdio — single user, API key from env, module-level state\n * http — multi-user, API key from AsyncLocalStorage, per-key state\n *\n * Configuration:\n * PRODUCTBRAIN_API_KEY — pb_sk_* key (stdio mode; http mode gets it per-request)\n * CONVEX_SITE_URL — (optional) Convex deployment URL, defaults to cloud\n */\n\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport { trackToolCall } from \"./analytics.js\";\nimport { getRequestApiKey, getKeyState, type KeyState } from \"./auth.js\";\nimport { MCP_NPX_PACKAGE } from \"./cli/config-writer.js\";\n\n// ─── Tool Context (for audit action logging) ─────────────────────────────\n\nconst toolContextStore = new AsyncLocalStorage<{ tool: string; action?: string }>();\n\n/**\n * Run a callback with tool context for audit logging.\n * Compound tools should wrap their handler with this so health action=audit can distinguish\n * e.g. entries action=get from entries action=search.\n */\nexport function runWithToolContext<T>(\n ctx: { tool: string; action?: string },\n fn: () => T | Promise<T>,\n): T | Promise<T> {\n return toolContextStore.run(ctx, fn);\n}\n\nfunction getToolContext(): { tool: string; action?: string } | null {\n return toolContextStore.getStore() ?? null;\n}\n\nconst DEFAULT_CLOUD_URL = \"https://trustworthy-kangaroo-277.convex.site\";\n\n// ─── Read Cache (Batch A: sub-200ms repeat calls) ─────────────────────\n\nconst CACHE_TTL_MS = 60_000; // 60s per plan\nconst CACHEABLE_FNS = [\n \"chain.getOrientEntries\",\n \"chain.gatherContext\",\n \"chain.graphGatherContext\",\n \"chain.taskAwareGatherContext\",\n \"chain.journeyAwareGatherContext\",\n \"chain.assembleBuildContext\",\n] as const;\n\nfunction isCacheable(fn: string): boolean {\n return (CACHEABLE_FNS as readonly string[]).includes(fn);\n}\n\nconst READ_PATTERN =\n /^(chain\\.(get|list|search|batchGet|gather|graph|task|journey|assemble|workspace|score|absence)|chainwork\\.(get|list|score)|maps\\.(get|list)|gitchain\\.(get|list|diff|history|runGate))/i;\n\nfunction isWrite(fn: string): boolean {\n if (fn.startsWith(\"agent.\")) return false;\n return !READ_PATTERN.test(fn);\n}\n\ninterface CacheEntry<T> {\n data: T;\n expiresAt: number;\n}\n\nconst readCache = new Map<string, CacheEntry<unknown>>();\n\nfunction cacheKey(fn: string, args: Record<string, unknown>): string {\n return `${fn}:${JSON.stringify(args)}`;\n}\n\nfunction getCached<T>(fn: string, args: Record<string, unknown>): T | undefined {\n if (!isCacheable(fn)) return undefined;\n const key = cacheKey(fn, args);\n const entry = readCache.get(key) as CacheEntry<T> | undefined;\n if (!entry || Date.now() > entry.expiresAt) {\n if (entry) readCache.delete(key);\n return undefined;\n }\n return entry.data;\n}\n\nfunction setCached<T>(fn: string, args: Record<string, unknown>, data: T): void {\n if (!isCacheable(fn)) return;\n const key = cacheKey(fn, args);\n readCache.set(key, { data, expiresAt: Date.now() + CACHE_TTL_MS });\n}\n\nfunction invalidateReadCache(): void {\n readCache.clear();\n}\n\n// ─── State Management ─────────────────────────────────────────────────\n\nconst _stdioState: KeyState = {\n workspaceId: null,\n workspaceSlug: null,\n workspaceName: null,\n workspaceCreatedAt: null,\n workspaceGovernanceMode: null,\n agentSessionId: null,\n apiKeyId: null,\n apiKeyScope: \"readwrite\",\n sessionOriented: false,\n sessionClosed: false,\n lastAccess: 0,\n};\n\n/**\n * Returns the active client state.\n * stdio: module-level singleton. http: per-API-key state from AsyncLocalStorage.\n */\nfunction state(): KeyState {\n const reqKey = getRequestApiKey();\n if (reqKey) return getKeyState(reqKey);\n return _stdioState;\n}\n\n/**\n * Returns the active API key (request-scoped in HTTP mode, env in stdio mode).\n */\nfunction getActiveApiKey(): string {\n const fromRequest = getRequestApiKey();\n if (fromRequest) return fromRequest;\n const fromEnv = process.env.PRODUCTBRAIN_API_KEY;\n if (!fromEnv) throw new Error(\"No API key available — set PRODUCTBRAIN_API_KEY or provide Bearer token\");\n return fromEnv;\n}\n\n// ─── Agent Session State ──────────────────────────────────────────────\n\nexport function getAgentSessionId(): string | null {\n return state().agentSessionId;\n}\n\nexport function isSessionOriented(): boolean {\n return state().sessionOriented;\n}\n\nexport function setSessionOriented(value: boolean): void {\n state().sessionOriented = value;\n}\n\nexport function getApiKeyScope(): \"read\" | \"readwrite\" {\n return state().apiKeyScope;\n}\n\nexport function isSessionClosed(): boolean {\n return state().sessionClosed;\n}\n\nexport interface AgentSessionStartResult {\n sessionId: string;\n initiatedBy: string;\n toolsScope: \"read\" | \"readwrite\";\n workspaceName: string;\n superseded: {\n previousSessionId: string;\n startedAt: string;\n initiatedBy: string;\n } | null;\n}\n\n/**\n * Start an agent session. Creates a session record in Convex.\n * toolsScope is derived server-side from the API key — not passed as a parameter.\n * If an active session exists, it gets superseded.\n */\nexport async function startAgentSession(): Promise<AgentSessionStartResult> {\n const workspaceId = await getWorkspaceId();\n const s = state();\n if (!s.apiKeyId) {\n throw new Error(\"Cannot start session: API key ID not resolved. Ensure workspace resolution completed.\");\n }\n\n const result = await mcpCall<AgentSessionStartResult>(\"agent.startSession\", {\n workspaceId,\n apiKeyId: s.apiKeyId,\n });\n\n if (s.agentSessionId) {\n resetTouchThrottle(s.agentSessionId);\n }\n s.agentSessionId = result.sessionId;\n s.apiKeyScope = result.toolsScope;\n s.sessionOriented = false;\n s.sessionClosed = false;\n resetTouchThrottle(result.sessionId);\n\n return result;\n}\n\n/**\n * Close the current agent session. After this, write tools are blocked\n * even if the MCP connection stays open.\n */\nexport async function closeAgentSession(): Promise<void> {\n const s = state();\n if (!s.agentSessionId) return;\n const sessionId = s.agentSessionId;\n try {\n await mcpCall(\"agent.closeSession\", {\n sessionId,\n status: \"closed\",\n });\n } finally {\n resetTouchThrottle(sessionId);\n s.sessionClosed = true;\n s.agentSessionId = null;\n s.sessionOriented = false;\n }\n}\n\n/**\n * Mark current session as orphaned (used on disconnect/crash).\n */\nexport async function orphanAgentSession(): Promise<void> {\n const s = state();\n if (!s.agentSessionId) return;\n const sessionId = s.agentSessionId;\n try {\n await mcpCall(\"agent.closeSession\", {\n sessionId,\n status: \"orphaned\",\n });\n } catch {\n // Best-effort on disconnect\n } finally {\n resetTouchThrottle(sessionId);\n s.agentSessionId = null;\n s.sessionOriented = false;\n }\n}\n\n/**\n * Touch the session to update lastToolCallAt. Fire-and-forget.\n * Throttled to at most once per 5s to prevent OCC conflicts when\n * multiple tool calls complete in parallel.\n */\nconst _lastTouchAtBySession = new Map<string, number>();\nconst TOUCH_THROTTLE_MS = 5_000;\n\nexport function touchSessionActivity(): void {\n const s = state();\n const sessionId = s.agentSessionId;\n if (!sessionId) return;\n\n const now = Date.now();\n const lastTouchAt = _lastTouchAtBySession.get(sessionId) ?? 0;\n if (now - lastTouchAt < TOUCH_THROTTLE_MS) return;\n _lastTouchAtBySession.set(sessionId, now);\n\n mcpCall(\"agent.touchSession\", {\n sessionId,\n }).catch(() => {});\n}\n\nexport function resetTouchThrottle(sessionId?: string | null): void {\n if (sessionId) {\n _lastTouchAtBySession.delete(sessionId);\n return;\n }\n _lastTouchAtBySession.clear();\n}\n\n/**\n * Record structured activity on the current session.\n */\nexport async function recordSessionActivity(activity: {\n entryCreated?: string;\n entryModified?: string;\n relationCreated?: boolean;\n gateFailure?: boolean;\n contradictionWarning?: boolean;\n strategyLinkWarnedForEntryId?: string;\n}): Promise<void> {\n const s = state();\n if (!s.agentSessionId) return;\n try {\n await mcpCall(\"agent.recordActivity\", {\n sessionId: s.agentSessionId,\n ...activity,\n });\n } catch {\n // Non-critical — don't fail the tool call over activity tracking\n }\n}\n\n// ─── Audit ────────────────────────────────────────────────────────────\n\nexport interface AuditEntry {\n ts: string;\n fn: string;\n workspace: string;\n status: \"ok\" | \"error\";\n durationMs: number;\n error?: string;\n /** For compound tools: tool name and action for audit display */\n toolContext?: { tool: string; action?: string };\n}\n\nconst AUDIT_BUFFER_SIZE = 50;\nconst auditBuffer: AuditEntry[] = [];\n\n/**\n * Bootstrap for stdio mode: set CONVEX_SITE_URL default and warn on missing key.\n * API key is validated lazily on first mcpCall so the server can start and handle\n * signals (SIGTERM) even before credentials are provided (e.g. in tests).\n */\nexport function bootstrap(): void {\n process.env.CONVEX_SITE_URL ??= process.env.PRODUCTBRAIN_URL ?? DEFAULT_CLOUD_URL;\n const pbKey = process.env.PRODUCTBRAIN_API_KEY;\n if (!pbKey?.startsWith(\"pb_sk_\")) {\n process.stderr.write(\n \"[MCP] Warning: PRODUCTBRAIN_API_KEY is not set or invalid. \" +\n \"Tool calls will fail until a valid key is provided.\\n\"\n );\n }\n}\n\n/**\n * Bootstrap for HTTP mode: only set CONVEX_SITE_URL.\n * API key validation happens per-request via Bearer token.\n */\nexport function bootstrapHttp(): void {\n process.env.CONVEX_SITE_URL ??= process.env.PRODUCTBRAIN_URL ?? DEFAULT_CLOUD_URL;\n}\n\n/** @deprecated Use bootstrap() instead. Alias kept for callers in transition. */\nexport const bootstrapCloudMode = bootstrap;\n\nfunction getEnv(key: string): string {\n const value = process.env[key];\n if (!value) throw new Error(`${key} environment variable is required`);\n return value;\n}\n\nfunction shouldLogAudit(status: \"ok\" | \"error\"): boolean {\n return status === \"error\" || process.env.MCP_DEBUG === \"1\";\n}\n\nfunction audit(fn: string, status: \"ok\" | \"error\", durationMs: number, errorMsg?: string): void {\n const ts = new Date().toISOString();\n const workspace = state().workspaceId ?? \"unresolved\";\n const toolCtx = getToolContext();\n\n const entry: AuditEntry = { ts, fn, workspace, status, durationMs };\n if (errorMsg) entry.error = errorMsg;\n if (toolCtx) entry.toolContext = toolCtx;\n auditBuffer.push(entry);\n if (auditBuffer.length > AUDIT_BUFFER_SIZE) auditBuffer.shift();\n\n trackToolCall(fn, status, durationMs, workspace, errorMsg);\n\n if (!shouldLogAudit(status)) return;\n\n const base = `[MCP-AUDIT] ${ts} fn=${fn} workspace=${workspace} status=${status} duration=${durationMs}ms`;\n if (status === \"error\" && errorMsg) {\n process.stderr.write(`${base} error=${JSON.stringify(errorMsg)}\\n`);\n } else {\n process.stderr.write(`${base}\\n`);\n }\n}\n\nexport function getAuditLog(): readonly AuditEntry[] {\n return auditBuffer;\n}\n\n// ─── HTTP Client ──────────────────────────────────────────────────────\n\n/**\n * Low-level call to the HTTP Action gateway.\n * Workspace scoping is enforced server-side from the API key — callers\n * don't need to (and can't) override the workspace.\n *\n * Read cache: orient and context-gather responses are cached for 60s.\n * Cache is invalidated on any write (safe-by-default: everything not\n * matching a known read pattern is treated as a write).\n */\nexport async function mcpCall<T>(fn: string, args: Record<string, unknown> = {}): Promise<T> {\n const cached = getCached<T>(fn, args);\n if (cached !== undefined) {\n return cached;\n }\n\n const siteUrl = getEnv(\"CONVEX_SITE_URL\").replace(/\\/$/, \"\");\n const apiKey = getActiveApiKey();\n\n const start = Date.now();\n\n let res: Response;\n try {\n res = await fetch(`${siteUrl}/api/mcp`, {\n method: \"POST\",\n signal: AbortSignal.timeout(10_000),\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${apiKey}`,\n },\n body: JSON.stringify({ fn, args }),\n });\n } catch (err: any) {\n audit(fn, \"error\", Date.now() - start, err.message);\n throw new Error(`MCP call \"${fn}\" network error: ${err.message}`);\n }\n\n const json = (await res.json()) as { data?: T; error?: string };\n\n if (!res.ok || json.error) {\n audit(fn, \"error\", Date.now() - start, json.error);\n throw new Error(`MCP call \"${fn}\" failed (${res.status}): ${json.error ?? \"unknown error\"}`);\n }\n\n audit(fn, \"ok\", Date.now() - start);\n\n const data = json.data as T;\n if (isWrite(fn)) {\n invalidateReadCache();\n } else {\n setCached(fn, args, data);\n }\n\n const s = state();\n // Exclude session bookkeeping calls from the heartbeat touch. These mutations\n // already target the active session document, so immediately heartbeating after\n // them only adds avoidable OCC pressure on the same row.\n const TOUCH_EXCLUDED = new Set([\n \"agent.touchSession\",\n \"agent.startSession\",\n \"agent.markOriented\",\n \"agent.recordActivity\",\n \"agent.recordWrapup\",\n \"agent.closeSession\",\n ]);\n if (s.agentSessionId && !TOUCH_EXCLUDED.has(fn)) {\n touchSessionActivity();\n }\n\n return data;\n}\n\n// ─── Workspace Resolution ─────────────────────────────────────────────\n\nconst resolveInFlightMap = new Map<string, Promise<string>>();\n\nexport async function getWorkspaceId(): Promise<string> {\n const s = state();\n if (s.workspaceId) return s.workspaceId;\n\n const apiKey = getActiveApiKey();\n const existing = resolveInFlightMap.get(apiKey);\n if (existing) return existing;\n\n const promise = resolveWorkspaceWithRetry().finally(() => resolveInFlightMap.delete(apiKey));\n resolveInFlightMap.set(apiKey, promise);\n return promise;\n}\n\nasync function resolveWorkspaceWithRetry(maxRetries = 2): Promise<string> {\n let lastError: Error | null = null;\n\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n try {\n const workspace = await mcpCall<{\n _id: string;\n name: string;\n slug: string;\n createdAt?: number;\n keyScope?: string;\n keyId?: string;\n governanceMode?: \"open\" | \"consensus\" | \"role\";\n } | null>(\"resolveWorkspace\", {});\n\n if (!workspace) {\n throw new Error(\n \"API key is valid but no workspace is associated. \" +\n `Run \\`npx ${MCP_NPX_PACKAGE} setup\\` or regenerate your key.`\n );\n }\n\n const s = state();\n s.workspaceId = workspace._id;\n s.workspaceSlug = workspace.slug;\n s.workspaceName = workspace.name;\n s.workspaceCreatedAt = workspace.createdAt ?? null;\n s.workspaceGovernanceMode = workspace.governanceMode ?? \"open\";\n if (workspace.keyScope) s.apiKeyScope = workspace.keyScope as \"read\" | \"readwrite\";\n if (workspace.keyId) s.apiKeyId = workspace.keyId;\n return s.workspaceId;\n } catch (err: any) {\n lastError = err;\n const isTransient = /network error|fetch failed|ECONNREFUSED|ETIMEDOUT/i.test(err.message);\n if (!isTransient || attempt === maxRetries) break;\n const delay = 1000 * (attempt + 1);\n process.stderr.write(\n `[MCP] Workspace resolution failed (attempt ${attempt + 1}/${maxRetries + 1}), retrying in ${delay}ms...\\n`\n );\n await new Promise((r) => setTimeout(r, delay));\n }\n }\n\n throw lastError!;\n}\n\nexport interface WorkspaceContext {\n workspaceId: string;\n workspaceSlug: string;\n workspaceName: string;\n createdAt: number | null;\n /** BET-76 FEAT-111: Cached from workspace resolution. Defaults to 'open'. */\n governanceMode: \"open\" | \"consensus\" | \"role\";\n}\n\nexport async function getWorkspaceContext(): Promise<WorkspaceContext> {\n const workspaceId = await getWorkspaceId();\n const s = state();\n return {\n workspaceId,\n workspaceSlug: s.workspaceSlug ?? \"unknown\",\n workspaceName: s.workspaceName ?? \"unknown\",\n createdAt: s.workspaceCreatedAt,\n governanceMode: s.workspaceGovernanceMode ?? \"open\",\n };\n}\n\nexport async function mcpQuery<T>(fn: string, args: Record<string, unknown> = {}): Promise<T> {\n const workspaceId = await getWorkspaceId();\n return mcpCall<T>(fn, { ...args, workspaceId });\n}\n\nexport async function mcpMutation<T>(fn: string, args: Record<string, unknown> = {}): Promise<T> {\n const workspaceId = await getWorkspaceId();\n return mcpCall<T>(fn, { ...args, workspaceId });\n}\n\n/**\n * Gate check: throws if no active, oriented session exists.\n *\n * Used for read tools that require session context per SOS-iszqu7:\n * structured Chain data for agent consumption requires an active session.\n * Lighter than requireWriteAccess — does not check key scope.\n */\nexport function requireActiveSession(): void {\n const s = state();\n\n if (!s.agentSessionId) {\n throw new Error(\n \"Active session required (SOS-iszqu7). Call `session action=start` then `orient` first.\"\n );\n }\n\n if (s.sessionClosed) {\n throw new Error(\n \"Session has been closed (SOS-iszqu7). Start a new session with `session action=start`.\"\n );\n }\n\n if (!s.sessionOriented) {\n throw new Error(\n \"Orientation required before accessing build context (SOS-iszqu7). Call `orient` first.\"\n );\n }\n}\n\n/**\n * Gate check: throws if the agent is not allowed to write.\n *\n * Enforces:\n * 1. Session must exist (always required — no REQUIRE_AGENT_SESSION flag)\n * 2. Session must not be closed\n * 3. Session must be oriented\n * 4. Key scope must be readwrite\n */\nexport function requireWriteAccess(): void {\n const s = state();\n\n if (!s.agentSessionId) {\n throw new Error(\n \"Agent session required for write operations. Call `session action=start` first.\"\n );\n }\n\n if (s.sessionClosed) {\n throw new Error(\n \"Agent session has been closed. Write tools are no longer available.\"\n );\n }\n\n if (!s.sessionOriented) {\n throw new Error(\n \"Orientation required before writing to the Chain. Call 'orient' first.\"\n );\n }\n\n if (s.apiKeyScope === \"read\") {\n throw new Error(\n \"This API key has read-only scope. Write tools are not available.\"\n );\n }\n}\n\n/**\n * Recover session orientation state from Convex on restart.\n * If the session is active and oriented in Convex, restore local state.\n */\nexport async function recoverSessionState(): Promise<void> {\n const s = state();\n if (!s.workspaceId) return;\n try {\n const session = await mcpCall<{\n _id: string;\n status: string;\n oriented: boolean;\n toolsScope: string;\n } | null>(\"agent.getActiveSession\", { workspaceId: s.workspaceId });\n\n if (session && session.status === \"active\") {\n s.agentSessionId = session._id;\n s.sessionOriented = session.oriented;\n s.apiKeyScope = session.toolsScope as \"read\" | \"readwrite\";\n s.sessionClosed = false;\n }\n } catch {\n // Recovery is best-effort\n }\n}\n","/**\n * Request-scoped auth for HTTP transport mode.\n *\n * stdio: API key from PRODUCTBRAIN_API_KEY env, one user per process.\n * http: API key from Bearer header per request, many users per process.\n *\n * AsyncLocalStorage propagates the token through the async call chain\n * so client.ts resolves the correct API key and state per request.\n */\n\nimport { AsyncLocalStorage } from \"node:async_hooks\";\n\n// ── Request Context ─────────────────────────────────────────────────────\n\ninterface RequestAuth {\n apiKey: string;\n}\n\nconst requestStore = new AsyncLocalStorage<RequestAuth>();\n\nexport function runWithAuth<T>(auth: RequestAuth, fn: () => T | Promise<T>): T | Promise<T> {\n return requestStore.run(auth, fn);\n}\n\nexport function getRequestApiKey(): string | undefined {\n return requestStore.getStore()?.apiKey;\n}\n\n// ── Per-Key State (HTTP mode) ───────────────────────────────────────────\n\nexport interface KeyState {\n workspaceId: string | null;\n workspaceSlug: string | null;\n workspaceName: string | null;\n workspaceCreatedAt: number | null;\n /** BET-76 FEAT-111: Cached at workspace resolution time. Defaults to 'open'. */\n workspaceGovernanceMode: \"open\" | \"consensus\" | \"role\" | null;\n agentSessionId: string | null;\n apiKeyId: string | null;\n apiKeyScope: \"read\" | \"readwrite\";\n sessionOriented: boolean;\n sessionClosed: boolean;\n lastAccess: number;\n}\n\nconst SESSION_TTL_MS = 30 * 60 * 1000;\nconst MAX_KEYS = 100;\nconst keyStateMap = new Map<string, KeyState>();\n\nfunction newKeyState(): KeyState {\n return {\n workspaceId: null,\n workspaceSlug: null,\n workspaceName: null,\n workspaceCreatedAt: null,\n workspaceGovernanceMode: null,\n agentSessionId: null,\n apiKeyId: null,\n apiKeyScope: \"readwrite\",\n sessionOriented: false,\n sessionClosed: false,\n lastAccess: Date.now(),\n };\n}\n\nexport function getKeyState(apiKey: string): KeyState {\n let s = keyStateMap.get(apiKey);\n if (!s) {\n s = newKeyState();\n keyStateMap.set(apiKey, s);\n evictStale();\n }\n s.lastAccess = Date.now();\n return s;\n}\n\nfunction evictStale(): void {\n if (keyStateMap.size <= MAX_KEYS) return;\n const now = Date.now();\n for (const [key, s] of keyStateMap) {\n if (now - s.lastAccess > SESSION_TTL_MS) keyStateMap.delete(key);\n }\n if (keyStateMap.size > MAX_KEYS) {\n const sorted = [...keyStateMap.entries()].sort((a, b) => a[1].lastAccess - b[1].lastAccess);\n for (let i = 0; i < sorted.length - MAX_KEYS; i++) {\n keyStateMap.delete(sorted[i][0]);\n }\n }\n}\n","/**\n * Shared helpers for knowledge tools. Extracted from knowledge.ts for reuse\n * across entries, relations, graph, context, and collections compound tools.\n */\n\n// ─── Epistemic Status ─────────────────────────────────────────────────\n// Pure derivation of confidence level for claim-carrying entries (BR-85).\n// Used by entries/get, commit-entry, and context/gather to surface trust signals.\n\nconst EPISTEMIC_COLLECTIONS = new Set([\"insights\", \"assumptions\"]);\n\nexport interface EpistemicStatus {\n level: \"validated\" | \"evidenced\" | \"hypothesis\" | \"untested\" | \"testing\" | \"invalidated\";\n reason: string;\n action?: string;\n}\n\n/**\n * Derives epistemic confidence from entry data + relations.\n * Returns null for non-epistemic entry types.\n */\nexport function deriveEpistemicStatus(entry: {\n collectionName?: string;\n workflowStatus?: string;\n relations?: Array<{ type?: string; direction?: string }>;\n}): EpistemicStatus | null {\n const coll = entry.collectionName?.toLowerCase();\n if (!coll || !EPISTEMIC_COLLECTIONS.has(coll)) return null;\n\n const relations = entry.relations ?? [];\n const hasValidates = relations.some(\n (r) => r.type === \"validates\" && r.direction === \"incoming\",\n );\n const hasInvalidates = relations.some(\n (r) => r.type === \"invalidates\" && r.direction === \"incoming\",\n );\n const evidenceCount = relations.filter(\n (r) => (r.type === \"validates\" || r.type === \"invalidates\") && r.direction === \"incoming\",\n ).length;\n\n if (coll === \"assumptions\") {\n const ws = entry.workflowStatus;\n if (ws === \"invalidated\" || hasInvalidates) {\n return { level: \"invalidated\", reason: \"Disproved by linked counter-evidence\" };\n }\n if (ws === \"validated\" || (hasValidates && ws !== \"untested\")) {\n return { level: \"validated\", reason: `${evidenceCount} evidence link${evidenceCount !== 1 ? \"s\" : \"\"}` };\n }\n if (ws === \"testing\") {\n return { level: \"testing\", reason: \"Experiment in progress\" };\n }\n return { level: \"untested\", reason: \"No evidence linked\", action: \"Link evidence via `relations action=create type=\\\"validates\\\"`\" };\n }\n\n // Insights: derive from workflowStatus first, then from relations (BR-85).\n // Deliberate AND: workflowStatus alone isn't enough — linked evidence is required.\n // Setting ws=\"validated\" without evidence still returns \"hypothesis\" per BR-85.\n const ws = entry.workflowStatus;\n if (ws === \"validated\" && hasValidates) {\n return { level: \"validated\", reason: `${evidenceCount} evidence link${evidenceCount !== 1 ? \"s\" : \"\"}` };\n }\n if (ws === \"evidenced\" || hasValidates) {\n return { level: \"evidenced\", reason: `${evidenceCount} evidence link${evidenceCount !== 1 ? \"s\" : \"\"}` };\n }\n // BR-85: insight without linked evidence defaults to hypothesis\n return {\n level: \"hypothesis\",\n reason: \"No linked evidence\",\n action: \"Link proof via `relations action=create type=\\\"validates\\\"`\",\n };\n}\n\n/** Format epistemic status as a single markdown line for MCP text responses. */\nexport function formatEpistemicLine(es: EpistemicStatus): string {\n const icon = es.level === \"validated\" ? \"✓\"\n : es.level === \"evidenced\" ? \"◎\"\n : es.level === \"hypothesis\" ? \"△\"\n : es.level === \"untested\" ? \"?\"\n : es.level === \"testing\" ? \"◎\"\n : \"✕\";\n const suffix = es.action ? ` ${es.action}` : \"\";\n return `**Confidence:** ${icon} ${es.level} — ${es.reason}.${suffix}`;\n}\n\n/** Adapts a raw entry record into the shape deriveEpistemicStatus expects. */\nexport function toEpistemicInput(entry: Record<string, unknown>) {\n return {\n collectionName: typeof entry.collectionName === \"string\" ? entry.collectionName : undefined,\n workflowStatus: typeof entry.workflowStatus === \"string\" ? entry.workflowStatus : undefined,\n relations: Array.isArray(entry.relations)\n ? (entry.relations as Array<{ direction?: string; type?: string }>).map((r) => ({ type: r.type, direction: r.direction }))\n : undefined,\n };\n}\n\n/** Compact suffix for list/context views. Only emits for low-confidence entries. */\nexport function epistemicSuffix(es: EpistemicStatus | null): string {\n if (!es) return \"\";\n if (es.level === \"validated\") return \"\";\n if (es.level === \"evidenced\") return \"\";\n if (es.level === \"hypothesis\") return \" `△ hypothesis`\";\n if (es.level === \"untested\") return \" `? untested`\";\n if (es.level === \"testing\") return \" `◎ testing`\";\n if (es.level === \"invalidated\") return \" `✕ invalidated`\";\n return \"\";\n}\n\n// ─── General helpers ──────────────────────────────────────────────────\n\nexport function extractPreview(data: unknown, maxLen: number): string {\n if (!data || typeof data !== \"object\") return \"\";\n const d = data as Record<string, unknown>;\n const raw = d.description ?? d.canonical ?? d.detail ?? d.rule ?? \"\";\n if (typeof raw !== \"string\" || !raw) return \"\";\n return raw.length > maxLen ? raw.substring(0, maxLen) + \"...\" : raw;\n}\n\n/**\n * Canonical tool-name translation map.\n * Maps deprecated atomic tool names to their consolidated compound equivalents.\n * Used by context/orient to annotate stale references in historical content\n * (plans, docs, prototypes) without bulk-editing those files.\n */\nexport const TOOL_NAME_MIGRATIONS: ReadonlyMap<string, string> = new Map([\n [\"list-entries\", 'entries action=\"list\"'],\n [\"get-entry\", 'entries action=\"get\"'],\n [\"batch-get\", 'entries action=\"batch\"'],\n [\"search\", 'entries action=\"search\"'],\n [\"relate-entries\", 'relations action=\"create\"'],\n [\"batch-relate\", 'relations action=\"batch-create\"'],\n [\"find-related\", 'graph action=\"find\"'],\n [\"suggest-links\", 'graph action=\"suggest\"'],\n [\"gather-context\", 'context action=\"gather\"'],\n [\"get-build-context\", 'context action=\"build\"'],\n [\"list-collections\", 'collections action=\"list\"'],\n [\"create-collection\", 'collections action=\"create\"'],\n [\"update-collection\", 'collections action=\"update\"'],\n [\"agent-start\", 'session action=\"start\"'],\n [\"agent-close\", 'session action=\"close\"'],\n [\"agent-status\", 'session action=\"status\"'],\n [\"workspace-status\", 'health action=\"status\"'],\n [\"mcp-audit\", 'health action=\"audit\"'],\n [\"quality-check\", 'quality action=\"check\"'],\n [\"re-evaluate\", 'quality action=\"re-evaluate\"'],\n [\"list-workflows\", 'workflows action=\"list\"'],\n [\"workflow-checkpoint\", 'workflows action=\"checkpoint\"'],\n [\"wrapup\", \"session-wrapup\"],\n [\"finish\", \"session-wrapup\"],\n]);\n\n/**\n * Translates any deprecated tool names found in text to their current equivalents.\n * Returns null if no translations were needed, or a footnote string listing them.\n */\nexport function translateStaleToolNames(text: string): string | null {\n const found: string[] = [];\n for (const [old, current] of TOOL_NAME_MIGRATIONS) {\n const pattern = new RegExp(`\\\\b${old.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\")}\\\\b`, \"g\");\n if (pattern.test(text)) {\n found.push(`\\`${old}\\` → \\`${current}\\``);\n }\n }\n if (found.length === 0) return null;\n return `\\n\\n---\\n_Tool name translations (these references use deprecated names):_\\n${found.map(f => `- ${f}`).join(\"\\n\")}`;\n}\n","/**\n * Tool surface module — originally controlled write-tool visibility.\n *\n * Write tools are now always visible (all 31 from connection). Handler-level\n * guards (requireWriteAccess) enforce session + orient + key scope.\n *\n * Hiding tools via disable() broke Claude's lazy tool indexing — it never\n * re-indexed after list_changed notifications. The MCP spec says clients\n * SHOULD handle list_changed, but not all do.\n *\n * trackWriteTool() is kept as a no-op so existing registrations don't need\n * import changes. The module can be fully removed in a future cleanup pass.\n */\n\nimport type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\n\nexport function initToolSurface(_server: McpServer): void {\n // Retained for call-site compatibility; no longer manages state.\n}\n\nexport function trackWriteTool(_tool: unknown): void {\n // No-op — tools stay enabled. Handler guards do the real protection.\n}\n","/**\n * Feature flag resolution — STD-feature-flag-hierarchy\n * Three-tier check: env kill switch > local dev override > PostHog remote.\n * Fail-closed: returns false when PostHog is unavailable or flag is unknown.\n */\nimport { PostHog } from \"posthog-node\";\n\nlet client: PostHog | null = null;\n\nconst LOCAL_OVERRIDES: Record<string, boolean> = {\n // Uncomment for local dev without PostHog:\n // \"workspace-full-surface\": false,\n // \"chainwork-enabled\": true,\n // \"active-intelligence-shaping\": true, // ENT-59: Opus-powered investigation during shaping\n // \"capture-without-thinking\": true, // BET-73: collection-optional capture classifier\n};\n\nexport function initFeatureFlags(posthogClient: PostHog | null): void {\n if (posthogClient) {\n client = posthogClient;\n return;\n }\n\n // Fallback: allow feature flags even when analytics tracking key is absent.\n const apiKey = process.env.POSTHOG_MCP_KEY || process.env.PUBLIC_POSTHOG_KEY;\n if (!apiKey) {\n client = null;\n return;\n }\n\n client = new PostHog(apiKey, {\n host: process.env.PUBLIC_POSTHOG_HOST || \"https://eu.i.posthog.com\",\n flushAt: 1,\n flushInterval: 5000,\n featureFlagsPollingInterval: 30_000,\n });\n}\n\nexport async function isFeatureEnabled(\n flag: string,\n workspaceId: string,\n workspaceSlug?: string,\n): Promise<boolean> {\n if (process.env.FEATURE_KILL_SWITCH === \"true\") return false;\n if (flag in LOCAL_OVERRIDES) return LOCAL_OVERRIDES[flag];\n if (!client) return false;\n try {\n const primary = await client.isFeatureEnabled(flag, workspaceId, {\n groups: { workspace: workspaceId },\n groupProperties: {\n workspace: {\n workspace_id: workspaceId,\n slug: workspaceSlug ?? \"\",\n },\n },\n });\n if (primary) return true;\n\n // Support slug-keyed group targeting used in dogfood rollout conditions.\n if (workspaceSlug && workspaceSlug !== workspaceId) {\n const secondary = await client.isFeatureEnabled(flag, workspaceSlug, {\n groups: { workspace: workspaceSlug },\n groupProperties: {\n workspace: {\n workspace_id: workspaceId,\n slug: workspaceSlug,\n },\n },\n });\n return secondary ?? false;\n }\n\n return primary ?? false;\n } catch {\n return false;\n }\n}\n","/**\n * Synced from convex/lib/collectionRoutingClassifier.ts (TEN-174: MCP separate build, cannot import Convex lib).\n */\nexport const CLASSIFIER_AUTO_ROUTE_THRESHOLD = 70;\nexport const CLASSIFIER_AMBIGUITY_MARGIN = 15;\n\nexport const CLASSIFIABLE_COLLECTIONS = [\n \"decisions\",\n \"tensions\",\n \"glossary\",\n \"insights\",\n \"bets\",\n \"features\",\n \"architecture\",\n \"business-rules\",\n \"tracking-events\",\n \"landscape\",\n \"standards\",\n \"principles\",\n \"assumptions\",\n] as const;\n\nexport type ClassifiableCollectionSlug =\n (typeof CLASSIFIABLE_COLLECTIONS)[number];\n\nexport type ClassificationResult = {\n collection: ClassifiableCollectionSlug;\n topConfidence: number;\n confidence: number;\n reasons: string[];\n candidates: Array<{\n collection: ClassifiableCollectionSlug;\n confidence: number;\n signalScore: number;\n }>;\n scoreMargin: number;\n};\n\nconst SIGNAL_WEIGHT = 10;\nconst MIN_SCORE_FLOOR = 10;\nconst MAX_MATCHES_PER_SIGNAL = 2;\nconst MAX_REASON_COUNT = 3;\nconst ENTRY_ID_PATTERN = /\\b[A-Z]{2,}-\\d+\\b/g;\n\nconst COLLECTION_SIGNALS: Record<ClassifiableCollectionSlug, string[]> = {\n decisions: [\n \"decide\",\n \"decision\",\n \"chose\",\n \"chosen\",\n \"choice\",\n \"resolved\",\n \"we will\",\n \"we should\",\n \"approved\",\n \"replaces\",\n \"instead of\",\n \"go with\",\n \"criteria\",\n \"adopted\",\n \"reposition\",\n \"scoring framework\",\n \"review\",\n ],\n tensions: [\n \"problem\",\n \"issue\",\n \"blocked\",\n \"blocker\",\n \"friction\",\n \"pain\",\n \"bottleneck\",\n \"struggle\",\n \"missing\",\n \"breaks\",\n \"regression\",\n \"unclear\",\n \"no way to\",\n \"scope creep\",\n \"coupled\",\n \"trapped\",\n \"ambiguous\",\n \"no batch\",\n \"undetectable\",\n \"coordination gap\",\n ],\n glossary: [\n \"definition\",\n \"define\",\n \"term\",\n \"means\",\n \"refers to\",\n \"is called\",\n \"vocabulary\",\n \"terminology\",\n \"a governance mechanism\",\n \"a workspace\",\n \"a tracked\",\n \"the atom\",\n \"the action of\",\n \"the versioned\",\n \"a field on\",\n \"one of the\",\n \"a constraint on\",\n \"a hard data\",\n \"a single\",\n ],\n insights: [\n \"insight\",\n \"learned\",\n \"observed\",\n \"trend\",\n \"found that\",\n \"discovery\",\n \"validates\",\n \"saturates\",\n \"convergence\",\n \"signals from\",\n \"converge\",\n \"tam\",\n ],\n bets: [\n \"appetite\",\n \"rabbit hole\",\n \"no-go\",\n \"shape up\",\n \"done when\",\n \"shaping session\",\n \"from static\",\n \"from storage\",\n \"from passive\",\n \"the chain learns\",\n \"stage-aware\",\n \"commit friction\",\n \"interactive knowledge\",\n \"capture without\",\n \"front door\",\n \"response envelope\",\n \"knowledge organisation\",\n \"graveyard\",\n \"remote mcp\",\n \"coaching service\",\n ],\n features: [\n \"feature\",\n \"capability\",\n \"user can\",\n \"navigation\",\n \"palette\",\n \"modal\",\n \"smart capture\",\n \"suggest-links\",\n \"command palette\",\n \"auto-commit\",\n \"collection-optional\",\n \"organisation intelligence\",\n \"consolidation\",\n ],\n architecture: [\n \"architecture\",\n \"layer\",\n \"data model\",\n \"infrastructure\",\n \"system design\",\n \"l1\",\n \"l2\",\n \"l3\",\n \"l4\",\n \"l5\",\n \"l6\",\n \"l7\",\n \"guard infrastructure\",\n \"data layer\",\n \"intelligence layer\",\n \"mcp layer\",\n \"core layer\",\n ],\n \"business-rules\": [\n \"guard\",\n \"enforce\",\n \"integrity\",\n \"prevents\",\n \"excludes\",\n \"permitted\",\n \"policy\",\n \"feature gate\",\n \"must not\",\n \"only permitted\",\n \"closed enum\",\n \"write guard\",\n \"never imports\",\n \"requires active session\",\n \"readiness excludes\",\n ],\n \"tracking-events\": [\n \"track\",\n \"tracking\",\n \"analytics\",\n \"trigger\",\n \"posthog\",\n \"instrument\",\n \"fires when\",\n ],\n landscape: [\n \"competitor\",\n \"alternative tool\",\n \"alternative platform\",\n \"competing product\",\n \"landscape\",\n \"comparison\",\n ],\n standards: [\n \"standard\",\n \"convention\",\n \"trunk-based\",\n \"alignment-first\",\n \"structured bet\",\n \"system fixes\",\n \"patches\",\n ],\n principles: [\n \"we believe\",\n \"principle\",\n \"compounds\",\n \"philosophy\",\n \"simplicity compounds\",\n \"trust through\",\n \"evidence over\",\n \"compensate for\",\n \"honest by default\",\n ],\n assumptions: [\n \"assume\",\n \"assumption\",\n \"hypothesis\",\n \"untested\",\n \"we think\",\n \"we assume\",\n \"needs validation\",\n ],\n};\n\nfunction escapeRegExp(text: string): string {\n return text.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\nfunction countSignalMatches(text: string, signal: string): number {\n const trimmed = signal.trim().toLowerCase();\n if (!trimmed) return 0;\n\n const words = trimmed.split(/\\s+/).map(escapeRegExp);\n const pattern = `\\\\b${words.join(\"\\\\s+\")}\\\\b`;\n const regex = new RegExp(pattern, \"g\");\n const matches = text.match(regex);\n return matches?.length ?? 0;\n}\n\nexport function classifyCollection(\n name: string,\n description: string,\n): ClassificationResult | null {\n const text = `${name} ${description}`.replace(ENTRY_ID_PATTERN, \"\").toLowerCase();\n const rawScores: Array<{\n collection: ClassifiableCollectionSlug;\n score: number;\n reasons: string[];\n }> = [];\n\n for (const collection of CLASSIFIABLE_COLLECTIONS) {\n const signals = COLLECTION_SIGNALS[collection];\n const reasons: string[] = [];\n let score = 0;\n\n for (const signal of signals) {\n const matches = countSignalMatches(text, signal);\n if (matches <= 0) continue;\n\n const cappedMatches = Math.min(matches, MAX_MATCHES_PER_SIGNAL);\n score += cappedMatches * SIGNAL_WEIGHT;\n\n if (reasons.length < MAX_REASON_COUNT) {\n const capNote =\n matches > cappedMatches ? ` (capped at ${cappedMatches})` : \"\";\n reasons.push(`matched \"${signal}\" x${matches}${capNote}`);\n }\n }\n\n rawScores.push({ collection, score, reasons });\n }\n\n rawScores.sort((left, right) => right.score - left.score);\n const top = rawScores[0];\n const second = rawScores[1];\n\n if (!top || top.score < MIN_SCORE_FLOOR) return null;\n\n const margin = Math.max(0, top.score - (second?.score ?? 0));\n if (margin === 0 && top.score <= MIN_SCORE_FLOOR) return null;\n\n const baseConfidence = Math.min(90, top.score);\n const confidence = Math.min(99, baseConfidence + Math.min(20, margin));\n\n return {\n collection: top.collection,\n topConfidence: confidence,\n confidence,\n reasons: top.reasons,\n scoreMargin: margin,\n candidates: rawScores\n .filter((candidate) => candidate.score > 0)\n .slice(0, 3)\n .map((candidate) => ({\n collection: candidate.collection,\n signalScore: Math.min(99, candidate.score),\n confidence: Math.min(99, candidate.score),\n })),\n };\n}\n\nexport function shouldAutoRouteClassification(\n result: ClassificationResult,\n): boolean {\n if (result.confidence < CLASSIFIER_AUTO_ROUTE_THRESHOLD) return false;\n if (result.scoreMargin < CLASSIFIER_AMBIGUITY_MARGIN) return false;\n return true;\n}\n\nexport function isClassificationAmbiguous(\n result: ClassificationResult,\n): boolean {\n return result.scoreMargin < CLASSIFIER_AMBIGUITY_MARGIN;\n}\n","export {\n CLASSIFIABLE_COLLECTIONS,\n CLASSIFIER_AMBIGUITY_MARGIN,\n CLASSIFIER_AUTO_ROUTE_THRESHOLD,\n classifyCollection,\n isClassificationAmbiguous,\n shouldAutoRouteClassification,\n type ClassifiableCollectionSlug,\n type ClassificationResult,\n} from \"../lib/collectionRoutingClassifier.js\";\n\nimport { CLASSIFIABLE_COLLECTIONS } from \"../lib/collectionRoutingClassifier.js\";\n\n/** @deprecated Use CLASSIFIABLE_COLLECTIONS */\nexport const STARTER_COLLECTIONS = CLASSIFIABLE_COLLECTIONS;\n\n/** @deprecated Use ClassifiableCollectionSlug */\nexport type StarterCollectionSlug =\n import(\"../lib/collectionRoutingClassifier.js\").ClassifiableCollectionSlug;\n\n/** @deprecated Use classifyCollection */\nexport { classifyCollection as classifyStarterCollection } from \"../lib/collectionRoutingClassifier.js\";\n","/**\n * Response Envelope — Agent-Native MCP Contract (BET-78)\n *\n * Universal response shape for all MCP tool responses.\n * Lives in structuredContent — zero breaking changes to content[0].text.\n *\n * Design: envelope IS structuredContent, not nested inside it.\n * Discriminated on `ok` for O(1) agent parsing.\n */\n\nimport { z, type ZodTypeAny } from \"zod\";\nimport { classifyError } from \"./errors.js\";\n\n// ─── Types ───────────────────────────────────────────────────────────────\n\nexport interface NextAction {\n tool: string;\n description: string;\n parameters: Record<string, unknown>;\n}\n\nexport interface EnvelopeMeta {\n durationMs?: number;\n}\n\nexport interface EnvelopeSuccess<T = Record<string, unknown>> {\n ok: true;\n summary: string;\n data: T;\n next?: NextAction[];\n _meta?: EnvelopeMeta;\n}\n\nexport interface EnvelopeError {\n ok: false;\n code: string;\n message: string;\n recovery?: string;\n availableActions?: NextAction[];\n diagnostics?: Record<string, unknown>;\n _meta?: EnvelopeMeta;\n}\n\nexport type Envelope<T = Record<string, unknown>> =\n | EnvelopeSuccess<T>\n | EnvelopeError;\n\n// ─── Builders ────────────────────────────────────────────────────────────\n\nexport function success<T>(\n summary: string,\n data: T,\n next?: NextAction[],\n): EnvelopeSuccess<T> {\n return {\n ok: true,\n summary: summary || \"Operation completed.\",\n data,\n ...(next?.length ? { next } : {}),\n };\n}\n\nexport function failure(\n code: string,\n message: string,\n recovery?: string,\n availableActions?: NextAction[],\n diagnostics?: Record<string, unknown>,\n): EnvelopeError {\n return {\n ok: false,\n code,\n message,\n ...(recovery ? { recovery } : {}),\n ...(availableActions?.length ? { availableActions } : {}),\n ...(diagnostics ? { diagnostics } : {}),\n };\n}\n\n/** Shorthand for NOT_FOUND failures — the most common soft-failure pattern. */\nexport function notFound(id: string, hint?: string): EnvelopeError {\n return failure(\n \"NOT_FOUND\",\n `Entry '${id}' not found.`,\n hint ?? \"Use entries action=search to find the correct ID.\",\n [{ tool: \"entries\", description: \"Search entries\", parameters: { action: \"search\", query: id } }],\n );\n}\n\n/** Shorthand for VALIDATION_ERROR failures. */\nexport function validationError(message: string): EnvelopeError {\n return failure(\"VALIDATION_ERROR\", message);\n}\n\n// ─── Tool Response Helpers ───────────────────────────────────────────────\n\ntype TextContent = { type: \"text\"; text: string };\ntype ToolResult = {\n content: TextContent[];\n structuredContent?: Record<string, unknown>;\n isError?: boolean;\n};\n\n/** Build a `content` array from a single text string. */\nexport function textContent(text: string): TextContent[] {\n return [{ type: \"text\" as const, text }];\n}\n\n/**\n * Parse args against a Zod schema and return a typed result or a ready-to-return\n * validation error ToolResult. Eliminates the 5-line parse+check+format boilerplate.\n */\nexport function parseOrFail<T extends z.ZodTypeAny>(\n schema: T,\n args: unknown,\n): { ok: true; data: z.infer<T> } | { ok: false; result: ToolResult } {\n const parsed = schema.safeParse(args);\n if (parsed.success) return { ok: true, data: parsed.data };\n const issues = parsed.error.issues\n .map((i: z.ZodIssue) => `${i.path.join(\".\")}: ${i.message}`)\n .join(\"; \");\n const msg = `Invalid arguments: ${issues}`;\n return {\n ok: false,\n result: { content: textContent(msg), structuredContent: validationError(msg) },\n };\n}\n\n/** Standard response for unknown compound-tool actions. */\nexport function unknownAction(action: string, valid: readonly string[]): ToolResult {\n const msg = `Unknown action '${action}'. Valid actions: ${valid.join(\", \")}.`;\n return { content: textContent(msg), structuredContent: validationError(msg) };\n}\n\n// ─── Compound Result Builders ─────────────────────────────────────────\n// Eliminate the { content: [...], structuredContent: ... } boilerplate.\n\n/** Success result with human-readable text + structured envelope in one call. */\nexport function successResult<T>(\n text: string,\n summary: string,\n data: T,\n next?: NextAction[],\n): ToolResult {\n return { content: textContent(text), structuredContent: success(summary, data, next) };\n}\n\n/** Failure result with human-readable text + structured error envelope. */\nexport function failureResult(\n text: string,\n code: string,\n message: string,\n recovery?: string,\n availableActions?: NextAction[],\n diagnostics?: Record<string, unknown>,\n): ToolResult {\n return { content: textContent(text), structuredContent: failure(code, message, recovery, availableActions, diagnostics) };\n}\n\n/** Not-found result — the most common soft failure pattern. */\nexport function notFoundResult(id: string, text?: string, hint?: string): ToolResult {\n return { content: textContent(text ?? `Entry '${id}' not found.`), structuredContent: notFound(id, hint) };\n}\n\n/** Validation error result where the text and error message are the same. */\nexport function validationResult(message: string): ToolResult {\n return { content: textContent(message), structuredContent: validationError(message) };\n}\n\n// ─── Zod Schema Helper ──────────────────────────────────────────────────\n\nconst nextActionSchema = z.object({\n tool: z.string(),\n description: z.string(),\n parameters: z.record(z.unknown()),\n});\n\nconst metaSchema = z.object({\n durationMs: z.number().optional(),\n}).optional();\n\n/**\n * Wraps any data schema into a discriminated-union envelope schema.\n * Use for contract tests: `envelopeSchema(captureOutputSchema).safeParse(result)`.\n */\nexport function envelopeSchema<T extends ZodTypeAny>(dataSchema: T) {\n return z.discriminatedUnion(\"ok\", [\n z.object({\n ok: z.literal(true),\n summary: z.string().min(1),\n data: dataSchema,\n next: z.array(nextActionSchema).optional(),\n _meta: metaSchema,\n }),\n z.object({\n ok: z.literal(false),\n code: z.string().min(1),\n message: z.string().min(1),\n recovery: z.string().optional(),\n availableActions: z.array(nextActionSchema).optional(),\n diagnostics: z.record(z.unknown()).optional(),\n _meta: metaSchema,\n }),\n ]);\n}\n\n// ─── withEnvelope HOF ───────────────────────────────────────────────────\n\n/**\n * Wraps a tool handler to guarantee an Envelope in structuredContent.\n *\n * - Catches thrown errors (gates, backend) and classifies them.\n * - If the handler already returns an envelope (ok field present), passes through.\n * - Adds _meta.durationMs to every response.\n * - Owns isError: sets true iff ok===false (RH1 mitigation — TEN-206).\n */\nexport function withEnvelope<Args>(\n handler: (args: Args) => Promise<ToolResult>,\n): (args: Args) => Promise<ToolResult> {\n return async (args: Args): Promise<ToolResult> => {\n const start = Date.now();\n try {\n const result = await handler(args);\n const durationMs = Date.now() - start;\n\n const sc = result.structuredContent as Envelope | undefined;\n if (sc && typeof sc === \"object\" && \"ok\" in sc) {\n sc._meta = { ...sc._meta, durationMs };\n return {\n content: result.content ?? [],\n structuredContent: sc,\n ...(sc.ok === false ? { isError: true } : {}),\n };\n }\n\n // Safety net: all tools should be migrated. If this executes, a handler\n // is returning without an envelope — log so it surfaces during development.\n console.warn(`[withEnvelope] Handler returned without envelope shape. Wrapping automatically. Content preview: \"${result.content?.[0]?.text?.slice(0, 60) ?? \"(empty)\"}\"`);\n return {\n content: result.content ?? [],\n structuredContent: {\n ...success(\n result.content?.[0]?.text?.slice(0, 100) ?? \"\",\n sc ?? {},\n ),\n _meta: { durationMs },\n },\n };\n } catch (err) {\n const durationMs = Date.now() - start;\n const classified = classifyError(err);\n const envelope: EnvelopeError = {\n ...failure(\n classified.code,\n classified.message,\n classified.recovery,\n classified.availableActions,\n ),\n _meta: { durationMs },\n };\n return {\n content: [{ type: \"text\" as const, text: classified.message }],\n structuredContent: envelope,\n isError: true,\n };\n }\n };\n}\n","/**\n * Structured error classification for the Response Envelope (BET-78, FEAT-121).\n *\n * Typed error classes + classifyError pattern-matching.\n * classifyError handles both typed classes (new code) and plain Error\n * messages from client.ts gates (existing code — no modifications needed).\n */\n\nimport type { NextAction } from \"./envelope.js\";\n\n// ─── Typed Error Classes ─────────────────────────────────────────────────\n\nexport class GateError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"GateError\";\n }\n}\n\nexport class BackendError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"BackendError\";\n }\n}\n\nexport class ValidationError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"ValidationError\";\n }\n}\n\n// ─── Classification Result ───────────────────────────────────────────────\n\nexport interface ClassifiedError {\n code: string;\n message: string;\n recovery?: string;\n availableActions?: NextAction[];\n}\n\n// ─── Gate Patterns (from client.ts requireWriteAccess / requireActiveSession) ─\n\ninterface GatePattern {\n pattern: RegExp;\n code: string;\n recovery: string;\n action: NextAction;\n}\n\nconst GATE_PATTERNS: GatePattern[] = [\n {\n pattern: /session required|no active.*session|call.*session.*start/i,\n code: \"SESSION_REQUIRED\",\n recovery: \"Start an agent session first.\",\n action: { tool: \"session\", description: \"Start session\", parameters: { action: \"start\" } },\n },\n {\n pattern: /session.*closed/i,\n code: \"SESSION_CLOSED\",\n recovery: \"Start a new session.\",\n action: { tool: \"session\", description: \"Start new session\", parameters: { action: \"start\" } },\n },\n {\n pattern: /orientation required|call.*orient/i,\n code: \"ORIENTATION_REQUIRED\",\n recovery: \"Orient before writing.\",\n action: { tool: \"orient\", description: \"Orient session\", parameters: {} },\n },\n {\n pattern: /read.?only.*scope/i,\n code: \"READONLY_SCOPE\",\n recovery: \"This API key cannot write. Use a readwrite key.\",\n action: { tool: \"health\", description: \"Check key scope\", parameters: { action: \"whoami\" } },\n },\n];\n\n// ─── Classification ──────────────────────────────────────────────────────\n\n/**\n * Classify an error into a structured code + recovery path.\n * Handles:\n * 1. Gate errors (from requireWriteAccess / requireActiveSession)\n * 2. Backend errors (network/connectivity)\n * 3. Not-found errors\n * 4. Validation errors\n * 5. Duplicate/conflict errors\n * 6. Fallback to INTERNAL_ERROR\n */\nexport function classifyError(err: unknown): ClassifiedError {\n const message = err instanceof Error ? err.message : String(err);\n\n if (err instanceof GateError) {\n return {\n code: \"PERMISSION_DENIED\",\n message,\n recovery: \"Check permissions or use a readwrite API key.\",\n availableActions: [{ tool: \"health\", description: \"Check key scope\", parameters: { action: \"whoami\" } }],\n };\n }\n\n if (err instanceof BackendError) {\n return { code: \"BACKEND_ERROR\", message, recovery: \"Retry the operation or check backend health.\" };\n }\n\n if (err instanceof ValidationError) {\n return { code: \"VALIDATION_ERROR\", message };\n }\n\n for (const { pattern, code, recovery, action } of GATE_PATTERNS) {\n if (pattern.test(message)) {\n return { code, message, recovery, availableActions: [action] };\n }\n }\n\n if (/network error|fetch failed|ECONNREFUSED|ETIMEDOUT/i.test(message)) {\n return { code: \"BACKEND_UNAVAILABLE\", message, recovery: \"Retry in a few seconds.\" };\n }\n\n if (/not found/i.test(message)) {\n return {\n code: \"NOT_FOUND\",\n message,\n recovery: \"Use entries action=search to find the correct ID.\",\n availableActions: [{ tool: \"entries\", description: \"Search entries\", parameters: { action: \"search\" } }],\n };\n }\n\n if (/duplicate|already exists/i.test(message)) {\n return {\n code: \"DUPLICATE\",\n message,\n recovery: \"Use entries action=get to inspect the existing entry.\",\n availableActions: [{ tool: \"entries\", description: \"Get entry\", parameters: { action: \"get\" } }],\n };\n }\n\n if (/invalid|validation|required field/i.test(message)) {\n return { code: \"VALIDATION_ERROR\", message };\n }\n\n return { code: \"INTERNAL_ERROR\", message: message || \"An unexpected error occurred.\" };\n}\n"],"mappings":";;;;;;;;;;AAOA,SAAS,KAAAA,UAAS;;;ACKlB,SAAS,qBAAAC,0BAAyB;;;ACFlC,SAAS,yBAAyB;AAQlC,IAAM,eAAe,IAAI,kBAA+B;AAEjD,SAAS,YAAe,MAAmB,IAA0C;AAC1F,SAAO,aAAa,IAAI,MAAM,EAAE;AAClC;AAEO,SAAS,mBAAuC;AACrD,SAAO,aAAa,SAAS,GAAG;AAClC;AAmBA,IAAM,iBAAiB,KAAK,KAAK;AACjC,IAAM,WAAW;AACjB,IAAM,cAAc,oBAAI,IAAsB;AAE9C,SAAS,cAAwB;AAC/B,SAAO;AAAA,IACL,aAAa;AAAA,IACb,eAAe;AAAA,IACf,eAAe;AAAA,IACf,oBAAoB;AAAA,IACpB,yBAAyB;AAAA,IACzB,gBAAgB;AAAA,IAChB,UAAU;AAAA,IACV,aAAa;AAAA,IACb,iBAAiB;AAAA,IACjB,eAAe;AAAA,IACf,YAAY,KAAK,IAAI;AAAA,EACvB;AACF;AAEO,SAAS,YAAY,QAA0B;AACpD,MAAI,IAAI,YAAY,IAAI,MAAM;AAC9B,MAAI,CAAC,GAAG;AACN,QAAI,YAAY;AAChB,gBAAY,IAAI,QAAQ,CAAC;AACzB,eAAW;AAAA,EAC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A,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AAAA,EACA,UAAU;AAAA,IACR;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AAAA,EACA,UAAU;AAAA,IACR;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AAAA,EACA,UAAU;AAAA,IACR;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AAAA,EACA,MAAM;AAAA,IACJ;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AAAA,EACA,UAAU;AAAA,IACR;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AAAA,EACA,cAAc;AAAA,IACZ;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,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