@productbrain/mcp 0.0.1-beta.4 → 0.0.1-beta.40

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2324 @@
1
+ import {
2
+ trackCaptureClassifierAutoRouted,
3
+ trackCaptureClassifierEvaluated,
4
+ trackCaptureClassifierFallback,
5
+ trackQualityVerdict,
6
+ trackToolCall
7
+ } from "./chunk-P7ABQEFK.js";
8
+
9
+ // src/tools/smart-capture.ts
10
+ import { z } from "zod";
11
+
12
+ // src/client.ts
13
+ import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
14
+
15
+ // src/auth.ts
16
+ import { AsyncLocalStorage } from "async_hooks";
17
+ var requestStore = new AsyncLocalStorage();
18
+ function runWithAuth(auth, fn) {
19
+ return requestStore.run(auth, fn);
20
+ }
21
+ function getRequestApiKey() {
22
+ return requestStore.getStore()?.apiKey;
23
+ }
24
+ var SESSION_TTL_MS = 30 * 60 * 1e3;
25
+ var MAX_KEYS = 100;
26
+ var keyStateMap = /* @__PURE__ */ new Map();
27
+ function newKeyState() {
28
+ return {
29
+ workspaceId: null,
30
+ workspaceSlug: null,
31
+ workspaceName: null,
32
+ workspaceCreatedAt: null,
33
+ workspaceGovernanceMode: null,
34
+ agentSessionId: null,
35
+ apiKeyId: null,
36
+ apiKeyScope: "readwrite",
37
+ sessionOriented: false,
38
+ sessionClosed: false,
39
+ lastAccess: Date.now()
40
+ };
41
+ }
42
+ function getKeyState(apiKey) {
43
+ let s = keyStateMap.get(apiKey);
44
+ if (!s) {
45
+ s = newKeyState();
46
+ keyStateMap.set(apiKey, s);
47
+ evictStale();
48
+ }
49
+ s.lastAccess = Date.now();
50
+ return s;
51
+ }
52
+ function evictStale() {
53
+ if (keyStateMap.size <= MAX_KEYS) return;
54
+ const now = Date.now();
55
+ for (const [key, s] of keyStateMap) {
56
+ if (now - s.lastAccess > SESSION_TTL_MS) keyStateMap.delete(key);
57
+ }
58
+ if (keyStateMap.size > MAX_KEYS) {
59
+ const sorted = [...keyStateMap.entries()].sort((a, b) => a[1].lastAccess - b[1].lastAccess);
60
+ for (let i = 0; i < sorted.length - MAX_KEYS; i++) {
61
+ keyStateMap.delete(sorted[i][0]);
62
+ }
63
+ }
64
+ }
65
+
66
+ // src/client.ts
67
+ var toolContextStore = new AsyncLocalStorage2();
68
+ function runWithToolContext(ctx, fn) {
69
+ return toolContextStore.run(ctx, fn);
70
+ }
71
+ function getToolContext() {
72
+ return toolContextStore.getStore() ?? null;
73
+ }
74
+ var DEFAULT_CLOUD_URL = "https://trustworthy-kangaroo-277.convex.site";
75
+ var CACHE_TTL_MS = 6e4;
76
+ var CACHEABLE_FNS = [
77
+ "chain.getOrientEntries",
78
+ "chain.gatherContext",
79
+ "chain.graphGatherContext",
80
+ "chain.taskAwareGatherContext",
81
+ "chain.journeyAwareGatherContext",
82
+ "chain.assembleBuildContext"
83
+ ];
84
+ function isCacheable(fn) {
85
+ return CACHEABLE_FNS.includes(fn);
86
+ }
87
+ var READ_PATTERN = /^(chain\.(get|list|search|batchGet|gather|graph|task|journey|assemble|workspace|score|absence)|maps\.(get|list)|gitchain\.(get|list|diff|history|runGate))/i;
88
+ function isWrite(fn) {
89
+ if (fn.startsWith("agent.")) return false;
90
+ return !READ_PATTERN.test(fn);
91
+ }
92
+ var readCache = /* @__PURE__ */ new Map();
93
+ function cacheKey(fn, args) {
94
+ return `${fn}:${JSON.stringify(args)}`;
95
+ }
96
+ function getCached(fn, args) {
97
+ if (!isCacheable(fn)) return void 0;
98
+ const key = cacheKey(fn, args);
99
+ const entry = readCache.get(key);
100
+ if (!entry || Date.now() > entry.expiresAt) {
101
+ if (entry) readCache.delete(key);
102
+ return void 0;
103
+ }
104
+ return entry.data;
105
+ }
106
+ function setCached(fn, args, data) {
107
+ if (!isCacheable(fn)) return;
108
+ const key = cacheKey(fn, args);
109
+ readCache.set(key, { data, expiresAt: Date.now() + CACHE_TTL_MS });
110
+ }
111
+ function invalidateReadCache() {
112
+ readCache.clear();
113
+ }
114
+ var _stdioState = {
115
+ workspaceId: null,
116
+ workspaceSlug: null,
117
+ workspaceName: null,
118
+ workspaceCreatedAt: null,
119
+ workspaceGovernanceMode: null,
120
+ agentSessionId: null,
121
+ apiKeyId: null,
122
+ apiKeyScope: "readwrite",
123
+ sessionOriented: false,
124
+ sessionClosed: false,
125
+ lastAccess: 0
126
+ };
127
+ function state() {
128
+ const reqKey = getRequestApiKey();
129
+ if (reqKey) return getKeyState(reqKey);
130
+ return _stdioState;
131
+ }
132
+ function getActiveApiKey() {
133
+ const fromRequest = getRequestApiKey();
134
+ if (fromRequest) return fromRequest;
135
+ const fromEnv = process.env.PRODUCTBRAIN_API_KEY;
136
+ if (!fromEnv) throw new Error("No API key available \u2014 set PRODUCTBRAIN_API_KEY or provide Bearer token");
137
+ return fromEnv;
138
+ }
139
+ function getAgentSessionId() {
140
+ return state().agentSessionId;
141
+ }
142
+ function isSessionOriented() {
143
+ return state().sessionOriented;
144
+ }
145
+ function setSessionOriented(value) {
146
+ state().sessionOriented = value;
147
+ }
148
+ function getApiKeyScope() {
149
+ return state().apiKeyScope;
150
+ }
151
+ async function startAgentSession() {
152
+ const workspaceId = await getWorkspaceId();
153
+ const s = state();
154
+ if (!s.apiKeyId) {
155
+ throw new Error("Cannot start session: API key ID not resolved. Ensure workspace resolution completed.");
156
+ }
157
+ const result = await mcpCall("agent.startSession", {
158
+ workspaceId,
159
+ apiKeyId: s.apiKeyId
160
+ });
161
+ s.agentSessionId = result.sessionId;
162
+ s.apiKeyScope = result.toolsScope;
163
+ s.sessionOriented = false;
164
+ s.sessionClosed = false;
165
+ resetTouchThrottle();
166
+ return result;
167
+ }
168
+ async function closeAgentSession() {
169
+ const s = state();
170
+ if (!s.agentSessionId) return;
171
+ try {
172
+ await mcpCall("agent.closeSession", {
173
+ sessionId: s.agentSessionId,
174
+ status: "closed"
175
+ });
176
+ } finally {
177
+ s.sessionClosed = true;
178
+ s.agentSessionId = null;
179
+ s.sessionOriented = false;
180
+ }
181
+ }
182
+ async function orphanAgentSession() {
183
+ const s = state();
184
+ if (!s.agentSessionId) return;
185
+ try {
186
+ await mcpCall("agent.closeSession", {
187
+ sessionId: s.agentSessionId,
188
+ status: "orphaned"
189
+ });
190
+ } catch {
191
+ } finally {
192
+ s.agentSessionId = null;
193
+ s.sessionOriented = false;
194
+ }
195
+ }
196
+ var _lastTouchAt = 0;
197
+ var TOUCH_THROTTLE_MS = 5e3;
198
+ function touchSessionActivity() {
199
+ const s = state();
200
+ if (!s.agentSessionId) return;
201
+ const now = Date.now();
202
+ if (now - _lastTouchAt < TOUCH_THROTTLE_MS) return;
203
+ _lastTouchAt = now;
204
+ mcpCall("agent.touchSession", {
205
+ sessionId: s.agentSessionId
206
+ }).catch(() => {
207
+ });
208
+ }
209
+ function resetTouchThrottle() {
210
+ _lastTouchAt = 0;
211
+ }
212
+ async function recordSessionActivity(activity) {
213
+ const s = state();
214
+ if (!s.agentSessionId) return;
215
+ try {
216
+ await mcpCall("agent.recordActivity", {
217
+ sessionId: s.agentSessionId,
218
+ ...activity
219
+ });
220
+ } catch {
221
+ }
222
+ }
223
+ var AUDIT_BUFFER_SIZE = 50;
224
+ var auditBuffer = [];
225
+ function bootstrap() {
226
+ process.env.CONVEX_SITE_URL ??= process.env.PRODUCTBRAIN_URL ?? DEFAULT_CLOUD_URL;
227
+ const pbKey = process.env.PRODUCTBRAIN_API_KEY;
228
+ if (!pbKey?.startsWith("pb_sk_")) {
229
+ process.stderr.write(
230
+ "[MCP] Warning: PRODUCTBRAIN_API_KEY is not set or invalid. Tool calls will fail until a valid key is provided.\n"
231
+ );
232
+ }
233
+ }
234
+ function bootstrapHttp() {
235
+ process.env.CONVEX_SITE_URL ??= process.env.PRODUCTBRAIN_URL ?? DEFAULT_CLOUD_URL;
236
+ }
237
+ function getEnv(key) {
238
+ const value = process.env[key];
239
+ if (!value) throw new Error(`${key} environment variable is required`);
240
+ return value;
241
+ }
242
+ function shouldLogAudit(status) {
243
+ return status === "error" || process.env.MCP_DEBUG === "1";
244
+ }
245
+ function audit(fn, status, durationMs, errorMsg) {
246
+ const ts = (/* @__PURE__ */ new Date()).toISOString();
247
+ const workspace = state().workspaceId ?? "unresolved";
248
+ const toolCtx = getToolContext();
249
+ const entry = { ts, fn, workspace, status, durationMs };
250
+ if (errorMsg) entry.error = errorMsg;
251
+ if (toolCtx) entry.toolContext = toolCtx;
252
+ auditBuffer.push(entry);
253
+ if (auditBuffer.length > AUDIT_BUFFER_SIZE) auditBuffer.shift();
254
+ trackToolCall(fn, status, durationMs, workspace, errorMsg);
255
+ if (!shouldLogAudit(status)) return;
256
+ const base = `[MCP-AUDIT] ${ts} fn=${fn} workspace=${workspace} status=${status} duration=${durationMs}ms`;
257
+ if (status === "error" && errorMsg) {
258
+ process.stderr.write(`${base} error=${JSON.stringify(errorMsg)}
259
+ `);
260
+ } else {
261
+ process.stderr.write(`${base}
262
+ `);
263
+ }
264
+ }
265
+ function getAuditLog() {
266
+ return auditBuffer;
267
+ }
268
+ async function mcpCall(fn, args = {}) {
269
+ const cached = getCached(fn, args);
270
+ if (cached !== void 0) {
271
+ return cached;
272
+ }
273
+ const siteUrl = getEnv("CONVEX_SITE_URL").replace(/\/$/, "");
274
+ const apiKey = getActiveApiKey();
275
+ const start = Date.now();
276
+ let res;
277
+ try {
278
+ res = await fetch(`${siteUrl}/api/mcp`, {
279
+ method: "POST",
280
+ signal: AbortSignal.timeout(1e4),
281
+ headers: {
282
+ "Content-Type": "application/json",
283
+ Authorization: `Bearer ${apiKey}`
284
+ },
285
+ body: JSON.stringify({ fn, args })
286
+ });
287
+ } catch (err) {
288
+ audit(fn, "error", Date.now() - start, err.message);
289
+ throw new Error(`MCP call "${fn}" network error: ${err.message}`);
290
+ }
291
+ const json = await res.json();
292
+ if (!res.ok || json.error) {
293
+ audit(fn, "error", Date.now() - start, json.error);
294
+ throw new Error(`MCP call "${fn}" failed (${res.status}): ${json.error ?? "unknown error"}`);
295
+ }
296
+ audit(fn, "ok", Date.now() - start);
297
+ const data = json.data;
298
+ if (isWrite(fn)) {
299
+ invalidateReadCache();
300
+ } else {
301
+ setCached(fn, args, data);
302
+ }
303
+ const s = state();
304
+ const TOUCH_EXCLUDED = /* @__PURE__ */ new Set(["agent.touchSession", "agent.startSession", "agent.markOriented"]);
305
+ if (s.agentSessionId && !TOUCH_EXCLUDED.has(fn)) {
306
+ touchSessionActivity();
307
+ }
308
+ return data;
309
+ }
310
+ var resolveInFlightMap = /* @__PURE__ */ new Map();
311
+ async function getWorkspaceId() {
312
+ const s = state();
313
+ if (s.workspaceId) return s.workspaceId;
314
+ const apiKey = getActiveApiKey();
315
+ const existing = resolveInFlightMap.get(apiKey);
316
+ if (existing) return existing;
317
+ const promise = resolveWorkspaceWithRetry().finally(() => resolveInFlightMap.delete(apiKey));
318
+ resolveInFlightMap.set(apiKey, promise);
319
+ return promise;
320
+ }
321
+ async function resolveWorkspaceWithRetry(maxRetries = 2) {
322
+ let lastError = null;
323
+ for (let attempt = 0; attempt <= maxRetries; attempt++) {
324
+ try {
325
+ const workspace = await mcpCall("resolveWorkspace", {});
326
+ if (!workspace) {
327
+ throw new Error(
328
+ "API key is valid but no workspace is associated. Run `npx productbrain setup` or regenerate your key."
329
+ );
330
+ }
331
+ const s = state();
332
+ s.workspaceId = workspace._id;
333
+ s.workspaceSlug = workspace.slug;
334
+ s.workspaceName = workspace.name;
335
+ s.workspaceCreatedAt = workspace.createdAt ?? null;
336
+ s.workspaceGovernanceMode = workspace.governanceMode ?? "open";
337
+ if (workspace.keyScope) s.apiKeyScope = workspace.keyScope;
338
+ if (workspace.keyId) s.apiKeyId = workspace.keyId;
339
+ return s.workspaceId;
340
+ } catch (err) {
341
+ lastError = err;
342
+ const isTransient = /network error|fetch failed|ECONNREFUSED|ETIMEDOUT/i.test(err.message);
343
+ if (!isTransient || attempt === maxRetries) break;
344
+ const delay = 1e3 * (attempt + 1);
345
+ process.stderr.write(
346
+ `[MCP] Workspace resolution failed (attempt ${attempt + 1}/${maxRetries + 1}), retrying in ${delay}ms...
347
+ `
348
+ );
349
+ await new Promise((r) => setTimeout(r, delay));
350
+ }
351
+ }
352
+ throw lastError;
353
+ }
354
+ async function getWorkspaceContext() {
355
+ const workspaceId = await getWorkspaceId();
356
+ const s = state();
357
+ return {
358
+ workspaceId,
359
+ workspaceSlug: s.workspaceSlug ?? "unknown",
360
+ workspaceName: s.workspaceName ?? "unknown",
361
+ createdAt: s.workspaceCreatedAt,
362
+ governanceMode: s.workspaceGovernanceMode ?? "open"
363
+ };
364
+ }
365
+ async function mcpQuery(fn, args = {}) {
366
+ const workspaceId = await getWorkspaceId();
367
+ return mcpCall(fn, { ...args, workspaceId });
368
+ }
369
+ async function mcpMutation(fn, args = {}) {
370
+ const workspaceId = await getWorkspaceId();
371
+ return mcpCall(fn, { ...args, workspaceId });
372
+ }
373
+ function requireActiveSession() {
374
+ const s = state();
375
+ if (!s.agentSessionId) {
376
+ throw new Error(
377
+ "Active session required (SOS-iszqu7). Call `session action=start` then `orient` first."
378
+ );
379
+ }
380
+ if (s.sessionClosed) {
381
+ throw new Error(
382
+ "Session has been closed (SOS-iszqu7). Start a new session with `session action=start`."
383
+ );
384
+ }
385
+ if (!s.sessionOriented) {
386
+ throw new Error(
387
+ "Orientation required before accessing build context (SOS-iszqu7). Call `orient` first."
388
+ );
389
+ }
390
+ }
391
+ function requireWriteAccess() {
392
+ const s = state();
393
+ if (!s.agentSessionId) {
394
+ throw new Error(
395
+ "Agent session required for write operations. Call `session action=start` first."
396
+ );
397
+ }
398
+ if (s.sessionClosed) {
399
+ throw new Error(
400
+ "Agent session has been closed. Write tools are no longer available."
401
+ );
402
+ }
403
+ if (!s.sessionOriented) {
404
+ throw new Error(
405
+ "Orientation required before writing to the Chain. Call 'orient' first."
406
+ );
407
+ }
408
+ if (s.apiKeyScope === "read") {
409
+ throw new Error(
410
+ "This API key has read-only scope. Write tools are not available."
411
+ );
412
+ }
413
+ }
414
+ async function recoverSessionState() {
415
+ const s = state();
416
+ if (!s.workspaceId) return;
417
+ try {
418
+ const session = await mcpCall("agent.getActiveSession", { workspaceId: s.workspaceId });
419
+ if (session && session.status === "active") {
420
+ s.agentSessionId = session._id;
421
+ s.sessionOriented = session.oriented;
422
+ s.apiKeyScope = session.toolsScope;
423
+ s.sessionClosed = false;
424
+ }
425
+ } catch {
426
+ }
427
+ }
428
+
429
+ // src/tools/knowledge-helpers.ts
430
+ function extractPreview(data, maxLen) {
431
+ if (!data || typeof data !== "object") return "";
432
+ const d = data;
433
+ const raw = d.description ?? d.canonical ?? d.detail ?? d.rule ?? "";
434
+ if (typeof raw !== "string" || !raw) return "";
435
+ return raw.length > maxLen ? raw.substring(0, maxLen) + "..." : raw;
436
+ }
437
+ var TOOL_NAME_MIGRATIONS = /* @__PURE__ */ new Map([
438
+ ["list-entries", 'entries action="list"'],
439
+ ["get-entry", 'entries action="get"'],
440
+ ["batch-get", 'entries action="batch"'],
441
+ ["search", 'entries action="search"'],
442
+ ["relate-entries", 'relations action="create"'],
443
+ ["batch-relate", 'relations action="batch-create"'],
444
+ ["find-related", 'graph action="find"'],
445
+ ["suggest-links", 'graph action="suggest"'],
446
+ ["gather-context", 'context action="gather"'],
447
+ ["get-build-context", 'context action="build"'],
448
+ ["list-collections", 'collections action="list"'],
449
+ ["create-collection", 'collections action="create"'],
450
+ ["update-collection", 'collections action="update"'],
451
+ ["agent-start", 'session action="start"'],
452
+ ["agent-close", 'session action="close"'],
453
+ ["agent-status", 'session action="status"'],
454
+ ["workspace-status", 'health action="status"'],
455
+ ["mcp-audit", 'health action="audit"'],
456
+ ["quality-check", 'quality action="check"'],
457
+ ["re-evaluate", 'quality action="re-evaluate"'],
458
+ ["list-workflows", 'workflows action="list"'],
459
+ ["workflow-checkpoint", 'workflows action="checkpoint"'],
460
+ ["wrapup", "session-wrapup"],
461
+ ["finish", "session-wrapup"]
462
+ ]);
463
+ function translateStaleToolNames(text) {
464
+ const found = [];
465
+ for (const [old, current] of TOOL_NAME_MIGRATIONS) {
466
+ const pattern = new RegExp(`\\b${old.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\b`, "g");
467
+ if (pattern.test(text)) {
468
+ found.push(`\`${old}\` \u2192 \`${current}\``);
469
+ }
470
+ }
471
+ if (found.length === 0) return null;
472
+ return `
473
+
474
+ ---
475
+ _Tool name translations (these references use deprecated names):_
476
+ ${found.map((f) => `- ${f}`).join("\n")}`;
477
+ }
478
+
479
+ // src/tool-surface.ts
480
+ function initToolSurface(_server) {
481
+ }
482
+ function trackWriteTool(_tool) {
483
+ }
484
+
485
+ // src/featureFlags.ts
486
+ import { PostHog } from "posthog-node";
487
+ var client = null;
488
+ var LOCAL_OVERRIDES = {
489
+ // Uncomment for local dev without PostHog:
490
+ // "workspace-full-surface": false,
491
+ // "chainwork-enabled": true,
492
+ // "active-intelligence-shaping": true, // ENT-59: Opus-powered investigation during shaping
493
+ // "capture-without-thinking": true, // BET-73: collection-optional capture classifier
494
+ };
495
+ function initFeatureFlags(posthogClient) {
496
+ if (posthogClient) {
497
+ client = posthogClient;
498
+ return;
499
+ }
500
+ const apiKey = process.env.POSTHOG_MCP_KEY || process.env.PUBLIC_POSTHOG_KEY;
501
+ if (!apiKey) {
502
+ client = null;
503
+ return;
504
+ }
505
+ client = new PostHog(apiKey, {
506
+ host: process.env.PUBLIC_POSTHOG_HOST || "https://eu.i.posthog.com",
507
+ flushAt: 1,
508
+ flushInterval: 5e3,
509
+ featureFlagsPollingInterval: 3e4
510
+ });
511
+ }
512
+ async function isFeatureEnabled(flag, workspaceId, workspaceSlug) {
513
+ if (process.env.FEATURE_KILL_SWITCH === "true") return false;
514
+ if (flag in LOCAL_OVERRIDES) return LOCAL_OVERRIDES[flag];
515
+ if (!client) return false;
516
+ try {
517
+ const primary = await client.isFeatureEnabled(flag, workspaceId, {
518
+ groups: { workspace: workspaceId },
519
+ groupProperties: {
520
+ workspace: {
521
+ workspace_id: workspaceId,
522
+ slug: workspaceSlug ?? ""
523
+ }
524
+ }
525
+ });
526
+ if (primary) return true;
527
+ if (workspaceSlug && workspaceSlug !== workspaceId) {
528
+ const secondary = await client.isFeatureEnabled(flag, workspaceSlug, {
529
+ groups: { workspace: workspaceSlug },
530
+ groupProperties: {
531
+ workspace: {
532
+ workspace_id: workspaceId,
533
+ slug: workspaceSlug
534
+ }
535
+ }
536
+ });
537
+ return secondary ?? false;
538
+ }
539
+ return primary ?? false;
540
+ } catch {
541
+ return false;
542
+ }
543
+ }
544
+
545
+ // src/tools/smart-capture-routing.ts
546
+ var CLASSIFIER_AUTO_ROUTE_THRESHOLD = 70;
547
+ var CLASSIFIER_AMBIGUITY_MARGIN = 15;
548
+ var STARTER_COLLECTIONS = ["decisions", "tensions", "glossary", "insights", "bets"];
549
+ var SIGNAL_WEIGHT = 10;
550
+ var MAX_MATCHES_PER_SIGNAL = 2;
551
+ var MAX_REASON_COUNT = 3;
552
+ var STARTER_COLLECTION_SIGNALS = {
553
+ decisions: [
554
+ "decide",
555
+ "decision",
556
+ "chose",
557
+ "chosen",
558
+ "choice",
559
+ "resolved",
560
+ "we will",
561
+ "we should",
562
+ "approved"
563
+ ],
564
+ tensions: [
565
+ "problem",
566
+ "issue",
567
+ "blocked",
568
+ "blocker",
569
+ "friction",
570
+ "pain",
571
+ "risk",
572
+ "constraint",
573
+ "bottleneck",
574
+ "struggle"
575
+ ],
576
+ glossary: [
577
+ "definition",
578
+ "define",
579
+ "term",
580
+ "means",
581
+ "refers to",
582
+ "is called",
583
+ "vocabulary",
584
+ "terminology"
585
+ ],
586
+ insights: [
587
+ "insight",
588
+ "learned",
589
+ "observed",
590
+ "pattern",
591
+ "trend",
592
+ "signal",
593
+ "found that",
594
+ "evidence"
595
+ ],
596
+ bets: [
597
+ "bet",
598
+ "appetite",
599
+ "scope",
600
+ "elements",
601
+ "rabbit hole",
602
+ "no-go",
603
+ "shape",
604
+ "shaping",
605
+ "done when"
606
+ ]
607
+ };
608
+ function escapeRegExp(text) {
609
+ return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
610
+ }
611
+ function countSignalMatches(text, signal) {
612
+ const trimmed = signal.trim().toLowerCase();
613
+ if (!trimmed) return 0;
614
+ const words = trimmed.split(/\s+/).map(escapeRegExp);
615
+ const pattern = `\\b${words.join("\\s+")}\\b`;
616
+ const regex = new RegExp(pattern, "g");
617
+ const matches = text.match(regex);
618
+ return matches?.length ?? 0;
619
+ }
620
+ function classifyStarterCollection(name, description) {
621
+ const text = `${name} ${description}`.toLowerCase();
622
+ const rawScores = [];
623
+ for (const collection of STARTER_COLLECTIONS) {
624
+ const signals = STARTER_COLLECTION_SIGNALS[collection];
625
+ const reasons = [];
626
+ let score = 0;
627
+ for (const signal of signals) {
628
+ const matches = countSignalMatches(text, signal);
629
+ if (matches <= 0) continue;
630
+ const cappedMatches = Math.min(matches, MAX_MATCHES_PER_SIGNAL);
631
+ score += cappedMatches * SIGNAL_WEIGHT;
632
+ if (reasons.length < MAX_REASON_COUNT) {
633
+ const capNote = matches > cappedMatches ? ` (capped at ${cappedMatches})` : "";
634
+ reasons.push(`matched "${signal}" x${matches}${capNote}`);
635
+ }
636
+ }
637
+ rawScores.push({ collection, score, reasons });
638
+ }
639
+ rawScores.sort((a, b) => b.score - a.score);
640
+ const top = rawScores[0];
641
+ const second = rawScores[1];
642
+ if (!top || top.score <= 0) return null;
643
+ const margin = Math.max(0, top.score - (second?.score ?? 0));
644
+ const baseConfidence = Math.min(90, top.score);
645
+ const confidence = Math.min(99, baseConfidence + Math.min(20, margin));
646
+ return {
647
+ collection: top.collection,
648
+ topConfidence: confidence,
649
+ confidence,
650
+ reasons: top.reasons,
651
+ scoreMargin: margin,
652
+ candidates: rawScores.filter((candidate) => candidate.score > 0).slice(0, 3).map((candidate) => ({
653
+ collection: candidate.collection,
654
+ signalScore: Math.min(99, candidate.score),
655
+ confidence: Math.min(99, candidate.score)
656
+ }))
657
+ };
658
+ }
659
+ function shouldAutoRouteClassification(result) {
660
+ if (result.confidence < CLASSIFIER_AUTO_ROUTE_THRESHOLD) return false;
661
+ if (result.scoreMargin < CLASSIFIER_AMBIGUITY_MARGIN) return false;
662
+ return true;
663
+ }
664
+ function isClassificationAmbiguous(result) {
665
+ return result.scoreMargin < CLASSIFIER_AMBIGUITY_MARGIN;
666
+ }
667
+
668
+ // src/tools/smart-capture.ts
669
+ var AREA_KEYWORDS = {
670
+ "Architecture": ["convex", "schema", "database", "migration", "api", "backend", "infrastructure", "scaling", "performance"],
671
+ "Chain": ["knowledge", "glossary", "entry", "collection", "terminology", "drift", "graph", "chain", "commit"],
672
+ "AI & MCP Integration": ["mcp", "ai", "cursor", "agent", "tool", "llm", "prompt", "context"],
673
+ "Developer Experience": ["dx", "developer", "ide", "workflow", "friction", "ceremony"],
674
+ "Governance & Decision-Making": ["governance", "decision", "rule", "policy", "compliance", "approval"],
675
+ "Analytics & Tracking": ["analytics", "posthog", "tracking", "event", "metric", "funnel"],
676
+ "Security": ["security", "auth", "api key", "permission", "access", "token"]
677
+ };
678
+ function inferArea(text) {
679
+ const lower = text.toLowerCase();
680
+ let bestArea = "";
681
+ let bestScore = 0;
682
+ for (const [area, keywords] of Object.entries(AREA_KEYWORDS)) {
683
+ const score = keywords.filter((kw) => lower.includes(kw)).length;
684
+ if (score > bestScore) {
685
+ bestScore = score;
686
+ bestArea = area;
687
+ }
688
+ }
689
+ return bestArea;
690
+ }
691
+ function inferDomain(text) {
692
+ return inferArea(text) || "";
693
+ }
694
+ var COMMON_CHECKS = {
695
+ clearName: {
696
+ id: "clear-name",
697
+ label: "Clear, specific name (not vague)",
698
+ check: (ctx) => ctx.name.length > 10 && !["new tension", "new entry", "untitled", "test"].includes(ctx.name.toLowerCase()),
699
+ suggestion: () => "Rename to something specific \u2014 describe the actual problem or concept."
700
+ },
701
+ hasDescription: {
702
+ id: "has-description",
703
+ label: "Description provided (>50 chars)",
704
+ check: (ctx) => ctx.description.length > 50,
705
+ suggestion: () => "Add a fuller description explaining context and impact."
706
+ },
707
+ hasRelations: {
708
+ id: "has-relations",
709
+ label: "At least 1 relation created",
710
+ check: (ctx) => ctx.linksCreated.length >= 1,
711
+ suggestion: () => "Use `graph action=suggest` and `relations action=create` to add more connections."
712
+ },
713
+ diverseRelations: {
714
+ id: "diverse-relations",
715
+ label: "Relations span multiple collections",
716
+ check: (ctx) => {
717
+ const colls = new Set(ctx.linksCreated.map((l) => l.targetCollection));
718
+ return colls.size >= 2;
719
+ },
720
+ suggestion: () => "Try linking to entries in different collections (glossary, business-rules, strategy)."
721
+ },
722
+ hasType: {
723
+ id: "has-type",
724
+ label: "Has canonical type",
725
+ check: (ctx) => !!ctx.data?.canonicalKey || !!ctx.canonicalKey,
726
+ suggestion: () => "Classify this entry with a canonical type for better context assembly. Use update-entry to set canonicalKey."
727
+ }
728
+ };
729
+ var PROFILES = /* @__PURE__ */ new Map([
730
+ ["tensions", {
731
+ governedDraft: false,
732
+ descriptionField: "description",
733
+ defaults: [
734
+ { key: "priority", value: "medium" },
735
+ { key: "date", value: "today" },
736
+ { key: "raised", value: "infer" },
737
+ { key: "severity", value: "infer" }
738
+ ],
739
+ recommendedRelationTypes: ["surfaces_tension_in", "references", "belongs_to", "related_to"],
740
+ inferField: (ctx) => {
741
+ const fields = {};
742
+ const text = `${ctx.name} ${ctx.description}`;
743
+ const area = inferArea(text);
744
+ if (area) fields.raised = area;
745
+ if (text.toLowerCase().includes("critical") || text.toLowerCase().includes("blocker")) {
746
+ fields.severity = "critical";
747
+ } else if (text.toLowerCase().includes("bottleneck") || text.toLowerCase().includes("scaling") || text.toLowerCase().includes("breaking")) {
748
+ fields.severity = "high";
749
+ } else {
750
+ fields.severity = "medium";
751
+ }
752
+ if (area) fields.affectedArea = area;
753
+ return fields;
754
+ },
755
+ qualityChecks: [
756
+ COMMON_CHECKS.clearName,
757
+ COMMON_CHECKS.hasDescription,
758
+ COMMON_CHECKS.hasRelations,
759
+ COMMON_CHECKS.hasType,
760
+ {
761
+ id: "has-severity",
762
+ label: "Severity specified",
763
+ check: (ctx) => !!ctx.data.severity && ctx.data.severity !== "",
764
+ suggestion: (ctx) => {
765
+ const text = `${ctx.name} ${ctx.description}`.toLowerCase();
766
+ const inferred = text.includes("critical") ? "critical" : text.includes("bottleneck") ? "high" : "medium";
767
+ return `Set severity \u2014 suggest: ${inferred} (based on description keywords).`;
768
+ }
769
+ },
770
+ {
771
+ id: "has-affected-area",
772
+ label: "Affected area identified",
773
+ check: (ctx) => !!ctx.data.affectedArea && ctx.data.affectedArea !== "",
774
+ suggestion: (ctx) => {
775
+ const area = inferArea(`${ctx.name} ${ctx.description}`);
776
+ return area ? `Set affectedArea \u2014 suggest: "${area}" (inferred from content).` : "Specify which product area or domain this tension impacts.";
777
+ }
778
+ }
779
+ ]
780
+ }],
781
+ ["business-rules", {
782
+ governedDraft: true,
783
+ descriptionField: "description",
784
+ defaults: [
785
+ { key: "severity", value: "medium" },
786
+ { key: "domain", value: "infer" }
787
+ ],
788
+ recommendedRelationTypes: ["governs", "references", "conflicts_with", "related_to"],
789
+ inferField: (ctx) => {
790
+ const fields = {};
791
+ const domain = inferDomain(`${ctx.name} ${ctx.description}`);
792
+ if (domain) fields.domain = domain;
793
+ return fields;
794
+ },
795
+ qualityChecks: [
796
+ COMMON_CHECKS.clearName,
797
+ COMMON_CHECKS.hasDescription,
798
+ COMMON_CHECKS.hasRelations,
799
+ COMMON_CHECKS.hasType,
800
+ {
801
+ id: "has-rationale",
802
+ label: "Rationale provided",
803
+ check: (ctx) => typeof ctx.data.rationale === "string" && ctx.data.rationale.length > 10,
804
+ suggestion: () => "Add a rationale explaining why this rule exists via `update-entry`."
805
+ },
806
+ {
807
+ id: "has-domain",
808
+ label: "Domain specified",
809
+ check: (ctx) => !!ctx.data.domain && ctx.data.domain !== "",
810
+ suggestion: (ctx) => {
811
+ const domain = inferDomain(`${ctx.name} ${ctx.description}`);
812
+ return domain ? `Set domain \u2014 suggest: "${domain}" (inferred from content).` : "Specify the business domain this rule belongs to.";
813
+ }
814
+ }
815
+ ]
816
+ }],
817
+ ["glossary", {
818
+ governedDraft: true,
819
+ descriptionField: "canonical",
820
+ defaults: [
821
+ { key: "category", value: "infer" }
822
+ ],
823
+ recommendedRelationTypes: ["defines_term_for", "confused_with", "related_to", "references"],
824
+ inferField: (ctx) => {
825
+ const fields = {};
826
+ const area = inferArea(`${ctx.name} ${ctx.description}`);
827
+ if (area) {
828
+ const categoryMap = {
829
+ "Architecture": "Platform & Architecture",
830
+ "Chain": "Knowledge Management",
831
+ "AI & MCP Integration": "AI & Developer Tools",
832
+ "Developer Experience": "AI & Developer Tools",
833
+ "Governance & Decision-Making": "Governance & Process",
834
+ "Analytics & Tracking": "Platform & Architecture",
835
+ "Security": "Platform & Architecture"
836
+ };
837
+ fields.category = categoryMap[area] ?? "";
838
+ }
839
+ return fields;
840
+ },
841
+ qualityChecks: [
842
+ COMMON_CHECKS.clearName,
843
+ COMMON_CHECKS.hasType,
844
+ {
845
+ id: "has-canonical",
846
+ label: "Canonical definition provided (>20 chars)",
847
+ check: (ctx) => {
848
+ const canonical = ctx.data.canonical;
849
+ return typeof canonical === "string" && canonical.length > 20;
850
+ },
851
+ suggestion: () => "Add a clear canonical definition \u2014 this is the single source of truth for this term."
852
+ },
853
+ COMMON_CHECKS.hasRelations,
854
+ {
855
+ id: "has-category",
856
+ label: "Category assigned",
857
+ check: (ctx) => !!ctx.data.category && ctx.data.category !== "",
858
+ suggestion: () => "Assign a category (e.g., 'Platform & Architecture', 'Governance & Process')."
859
+ }
860
+ ]
861
+ }],
862
+ ["decisions", {
863
+ governedDraft: false,
864
+ descriptionField: "rationale",
865
+ defaults: [
866
+ { key: "date", value: "today" },
867
+ { key: "decidedBy", value: "infer" }
868
+ ],
869
+ recommendedRelationTypes: ["informs", "references", "replaces", "related_to"],
870
+ inferField: (ctx) => {
871
+ const fields = {};
872
+ const area = inferArea(`${ctx.name} ${ctx.description}`);
873
+ if (area) fields.decidedBy = area;
874
+ return fields;
875
+ },
876
+ qualityChecks: [
877
+ COMMON_CHECKS.clearName,
878
+ COMMON_CHECKS.hasType,
879
+ {
880
+ id: "has-rationale",
881
+ label: "Rationale provided (>30 chars)",
882
+ check: (ctx) => {
883
+ const rationale = ctx.data.rationale;
884
+ return typeof rationale === "string" && rationale.length > 30;
885
+ },
886
+ suggestion: () => "Explain why this decision was made \u2014 what was considered and rejected?"
887
+ },
888
+ COMMON_CHECKS.hasRelations,
889
+ {
890
+ id: "has-date",
891
+ label: "Decision date recorded",
892
+ check: (ctx) => !!ctx.data.date && ctx.data.date !== "",
893
+ suggestion: () => "Record when this decision was made."
894
+ }
895
+ ]
896
+ }],
897
+ ["features", {
898
+ governedDraft: false,
899
+ descriptionField: "description",
900
+ defaults: [],
901
+ recommendedRelationTypes: ["belongs_to", "depends_on", "surfaces_tension_in", "related_to"],
902
+ qualityChecks: [
903
+ COMMON_CHECKS.clearName,
904
+ COMMON_CHECKS.hasDescription,
905
+ COMMON_CHECKS.hasRelations,
906
+ COMMON_CHECKS.hasType,
907
+ {
908
+ id: "has-owner",
909
+ label: "Owner assigned",
910
+ check: (ctx) => !!ctx.data.owner && ctx.data.owner !== "",
911
+ suggestion: () => "Assign an owner team or product area."
912
+ },
913
+ {
914
+ id: "has-rationale",
915
+ label: "Rationale documented",
916
+ check: (ctx) => !!ctx.data.rationale && String(ctx.data.rationale).length > 20,
917
+ suggestion: () => "Explain why this feature matters \u2014 what problem does it solve?"
918
+ }
919
+ ]
920
+ }],
921
+ ["audiences", {
922
+ governedDraft: false,
923
+ descriptionField: "description",
924
+ defaults: [],
925
+ recommendedRelationTypes: ["fills_slot", "informs", "related_to", "references"],
926
+ qualityChecks: [
927
+ COMMON_CHECKS.clearName,
928
+ COMMON_CHECKS.hasDescription,
929
+ COMMON_CHECKS.hasRelations,
930
+ COMMON_CHECKS.hasType,
931
+ {
932
+ id: "has-behaviors",
933
+ label: "Behaviors described",
934
+ check: (ctx) => typeof ctx.data.behaviors === "string" && ctx.data.behaviors.length > 20,
935
+ suggestion: () => "Describe how this audience segment behaves \u2014 what do they do, what tools do they use?"
936
+ }
937
+ ]
938
+ }],
939
+ ["strategy", {
940
+ governedDraft: true,
941
+ descriptionField: "description",
942
+ defaults: [],
943
+ recommendedRelationTypes: ["informs", "governs", "belongs_to", "related_to"],
944
+ qualityChecks: [
945
+ COMMON_CHECKS.clearName,
946
+ COMMON_CHECKS.hasDescription,
947
+ COMMON_CHECKS.hasRelations,
948
+ COMMON_CHECKS.hasType,
949
+ COMMON_CHECKS.diverseRelations
950
+ ]
951
+ }],
952
+ ["bets", {
953
+ // BET-chain-native-constellation, DEC-70 (structuredContent), STA-1 (constellation pattern)
954
+ governedDraft: false,
955
+ descriptionField: "problem",
956
+ defaults: [],
957
+ recommendedRelationTypes: ["part_of", "constrains", "informs", "depends_on", "related_to"],
958
+ qualityChecks: [
959
+ COMMON_CHECKS.clearName,
960
+ COMMON_CHECKS.hasDescription,
961
+ COMMON_CHECKS.hasRelations,
962
+ COMMON_CHECKS.hasType
963
+ ]
964
+ }],
965
+ ["maps", {
966
+ governedDraft: false,
967
+ descriptionField: "description",
968
+ defaults: [],
969
+ recommendedRelationTypes: ["fills_slot", "references", "related_to"],
970
+ qualityChecks: [
971
+ COMMON_CHECKS.clearName,
972
+ COMMON_CHECKS.hasDescription
973
+ ]
974
+ }],
975
+ ["chains", {
976
+ governedDraft: false,
977
+ descriptionField: "description",
978
+ defaults: [],
979
+ recommendedRelationTypes: ["informs", "references", "related_to"],
980
+ qualityChecks: [
981
+ COMMON_CHECKS.clearName,
982
+ COMMON_CHECKS.hasDescription
983
+ ]
984
+ }],
985
+ ["principles", {
986
+ governedDraft: true,
987
+ descriptionField: "description",
988
+ defaults: [
989
+ { key: "severity", value: "high" },
990
+ { key: "category", value: "infer" }
991
+ ],
992
+ recommendedRelationTypes: ["governs", "informs", "references", "related_to"],
993
+ inferField: (ctx) => {
994
+ const fields = {};
995
+ const area = inferArea(`${ctx.name} ${ctx.description}`);
996
+ if (area) {
997
+ const categoryMap = {
998
+ "Architecture": "Engineering",
999
+ "Chain": "Product",
1000
+ "AI & MCP Integration": "Engineering",
1001
+ "Developer Experience": "Engineering",
1002
+ "Governance & Decision-Making": "Business",
1003
+ "Analytics & Tracking": "Product",
1004
+ "Security": "Engineering"
1005
+ };
1006
+ fields.category = categoryMap[area] ?? "Product";
1007
+ }
1008
+ return fields;
1009
+ },
1010
+ qualityChecks: [
1011
+ COMMON_CHECKS.clearName,
1012
+ COMMON_CHECKS.hasDescription,
1013
+ COMMON_CHECKS.hasRelations,
1014
+ COMMON_CHECKS.hasType,
1015
+ {
1016
+ id: "has-rationale",
1017
+ label: "Rationale provided \u2014 why this principle matters",
1018
+ check: (ctx) => typeof ctx.data.rationale === "string" && ctx.data.rationale.length > 20,
1019
+ suggestion: () => "Explain why this principle exists and what goes wrong without it."
1020
+ }
1021
+ ]
1022
+ }],
1023
+ ["standards", {
1024
+ governedDraft: true,
1025
+ descriptionField: "description",
1026
+ defaults: [],
1027
+ recommendedRelationTypes: ["governs", "defines_term_for", "references", "related_to"],
1028
+ qualityChecks: [
1029
+ COMMON_CHECKS.clearName,
1030
+ COMMON_CHECKS.hasDescription,
1031
+ COMMON_CHECKS.hasRelations,
1032
+ COMMON_CHECKS.hasType
1033
+ ]
1034
+ }],
1035
+ ["tracking-events", {
1036
+ governedDraft: false,
1037
+ descriptionField: "description",
1038
+ defaults: [],
1039
+ recommendedRelationTypes: ["references", "belongs_to", "related_to"],
1040
+ qualityChecks: [
1041
+ COMMON_CHECKS.clearName,
1042
+ COMMON_CHECKS.hasDescription
1043
+ ]
1044
+ }]
1045
+ ]);
1046
+ var FALLBACK_PROFILE = {
1047
+ governedDraft: false,
1048
+ descriptionField: "description",
1049
+ defaults: [],
1050
+ recommendedRelationTypes: ["related_to", "references"],
1051
+ qualityChecks: [
1052
+ COMMON_CHECKS.clearName,
1053
+ COMMON_CHECKS.hasDescription,
1054
+ COMMON_CHECKS.hasRelations,
1055
+ COMMON_CHECKS.hasType
1056
+ ]
1057
+ };
1058
+ function extractSearchTerms(name, description) {
1059
+ const text = `${name} ${description}`;
1060
+ return text.replace(/[^\w\s]/g, " ").split(/\s+/).filter((w) => w.length > 3).slice(0, 8).join(" ");
1061
+ }
1062
+ function computeLinkConfidence(candidate, sourceName, sourceDescription, sourceCollection, candidateCollection) {
1063
+ const text = `${sourceName} ${sourceDescription}`.toLowerCase();
1064
+ const candidateName = candidate.name.toLowerCase();
1065
+ let score = 0;
1066
+ const reasons = [];
1067
+ if (text.includes(candidateName) && candidateName.length > 3) {
1068
+ score += 40;
1069
+ reasons.push("name match");
1070
+ }
1071
+ const candidateWords = candidateName.split(/\s+/).filter((w) => w.length > 3);
1072
+ const matchingWords = candidateWords.filter((w) => text.includes(w));
1073
+ const wordScore = matchingWords.length / Math.max(candidateWords.length, 1) * 30;
1074
+ score += wordScore;
1075
+ if (matchingWords.length > 0) {
1076
+ reasons.push(`word overlap (${matchingWords.slice(0, 3).join(", ")})`);
1077
+ }
1078
+ const HUB_COLLECTIONS = /* @__PURE__ */ new Set(["strategy", "features"]);
1079
+ if (HUB_COLLECTIONS.has(candidateCollection)) {
1080
+ score += 15;
1081
+ reasons.push("hub collection");
1082
+ }
1083
+ if (candidateCollection !== sourceCollection) {
1084
+ score += 10;
1085
+ reasons.push("cross-collection");
1086
+ }
1087
+ const finalScore = Math.min(score, 100);
1088
+ const reason = reasons.length > 0 ? reasons.join(" + ") : "low relevance";
1089
+ return { score: finalScore, reason };
1090
+ }
1091
+ function inferRelationType(sourceCollection, targetCollection, profile) {
1092
+ const typeMap = {
1093
+ tensions: {
1094
+ glossary: "surfaces_tension_in",
1095
+ "business-rules": "references",
1096
+ strategy: "belongs_to",
1097
+ features: "surfaces_tension_in",
1098
+ decisions: "references"
1099
+ },
1100
+ "business-rules": {
1101
+ glossary: "references",
1102
+ features: "governs",
1103
+ strategy: "belongs_to",
1104
+ tensions: "references"
1105
+ },
1106
+ glossary: {
1107
+ features: "defines_term_for",
1108
+ "business-rules": "references",
1109
+ strategy: "references"
1110
+ },
1111
+ decisions: {
1112
+ features: "informs",
1113
+ "business-rules": "references",
1114
+ strategy: "references",
1115
+ tensions: "references"
1116
+ }
1117
+ };
1118
+ const mapped = typeMap[sourceCollection]?.[targetCollection];
1119
+ const type = mapped ?? profile.recommendedRelationTypes[0] ?? "related_to";
1120
+ const reason = mapped ? `collection pair (${sourceCollection} \u2192 ${targetCollection})` : `profile default (${profile.recommendedRelationTypes[0] ?? "related_to"})`;
1121
+ return { type, reason };
1122
+ }
1123
+ function scoreQuality(ctx, profile) {
1124
+ const checks = profile.qualityChecks.map((qc) => {
1125
+ const passed2 = qc.check(ctx);
1126
+ return {
1127
+ id: qc.id,
1128
+ label: qc.label,
1129
+ passed: passed2,
1130
+ suggestion: passed2 ? void 0 : qc.suggestion?.(ctx)
1131
+ };
1132
+ });
1133
+ const passed = checks.filter((c) => c.passed).length;
1134
+ const total = checks.length;
1135
+ const score = total > 0 ? Math.round(passed / total * 10) : 10;
1136
+ return { score, maxScore: 10, checks };
1137
+ }
1138
+ function formatQualityReport(result) {
1139
+ const failed = result.checks.filter((c) => !c.passed);
1140
+ const reason = failed.length > 0 ? ` because ${failed.map((c) => c.suggestion ?? c.label.toLowerCase()).join("; ")}` : "";
1141
+ const lines = [`## Quality: ${result.score}/${result.maxScore}${reason}`];
1142
+ for (const check of result.checks) {
1143
+ const icon = check.passed ? "[x]" : "[ ]";
1144
+ const suggestion = check.passed ? "" : ` \u2014 ${check.suggestion ?? check.label}`;
1145
+ lines.push(`${icon} ${check.label}${suggestion}`);
1146
+ }
1147
+ return lines.join("\n");
1148
+ }
1149
+ async function checkEntryQuality(entryId) {
1150
+ const entry = await mcpQuery("chain.getEntry", { entryId });
1151
+ if (!entry) {
1152
+ return {
1153
+ text: `Entry \`${entryId}\` not found. Try search to find the right ID.`,
1154
+ quality: { score: 0, maxScore: 10, checks: [] }
1155
+ };
1156
+ }
1157
+ const collections = await mcpQuery("chain.listCollections");
1158
+ const collMap = /* @__PURE__ */ new Map();
1159
+ for (const c of collections) collMap.set(c._id, c.slug);
1160
+ const collectionSlug = collMap.get(entry.collectionId) ?? "unknown";
1161
+ const profile = PROFILES.get(collectionSlug) ?? FALLBACK_PROFILE;
1162
+ const relations = await mcpQuery("chain.listEntryRelations", { entryId });
1163
+ const linksCreated = [];
1164
+ for (const r of relations) {
1165
+ const otherId = r.fromId === entry._id ? r.toId : r.fromId;
1166
+ linksCreated.push({
1167
+ targetEntryId: otherId,
1168
+ targetName: "",
1169
+ targetCollection: "",
1170
+ relationType: r.type
1171
+ });
1172
+ }
1173
+ const descField = profile.descriptionField;
1174
+ const description = typeof entry.data?.[descField] === "string" ? entry.data[descField] : "";
1175
+ const ctx = {
1176
+ collection: collectionSlug,
1177
+ name: entry.name,
1178
+ description,
1179
+ data: entry.data ?? {},
1180
+ entryId: entry.entryId ?? "",
1181
+ canonicalKey: entry.canonicalKey,
1182
+ linksCreated,
1183
+ linksSuggested: [],
1184
+ collectionFields: []
1185
+ };
1186
+ const quality = scoreQuality(ctx, profile);
1187
+ const lines = [
1188
+ `# Quality Check: ${entry.entryId ?? entry.name}`,
1189
+ `**${entry.name}** in \`${collectionSlug}\` [${entry.status}]`,
1190
+ "",
1191
+ formatQualityReport(quality)
1192
+ ];
1193
+ if (quality.score < 10) {
1194
+ const failedChecks = quality.checks.filter((c) => !c.passed && c.suggestion);
1195
+ if (failedChecks.length > 0) {
1196
+ lines.push("");
1197
+ lines.push(`_To improve: use \`update-entry\` to fill missing fields, or \`relations action=create\` to add connections._`);
1198
+ }
1199
+ }
1200
+ return { text: lines.join("\n"), quality };
1201
+ }
1202
+ var GOVERNED_COLLECTIONS = /* @__PURE__ */ new Set([
1203
+ "glossary",
1204
+ "business-rules",
1205
+ "principles",
1206
+ "standards",
1207
+ "strategy",
1208
+ "features"
1209
+ ]);
1210
+ var AUTO_LINK_CONFIDENCE_THRESHOLD = 35;
1211
+ var MAX_AUTO_LINKS = 5;
1212
+ var MAX_SUGGESTIONS = 5;
1213
+ var CAPTURE_WITHOUT_THINKING_FLAG = "capture-without-thinking";
1214
+ var captureSchema = z.object({
1215
+ collection: z.string().optional().describe("Collection slug, e.g. 'tensions', 'business-rules', 'glossary', 'decisions'. Optional when `capture-without-thinking` is enabled."),
1216
+ name: z.string().describe("Display name \u2014 be specific (e.g. 'Convex adjacency list won't scale for graph traversal')"),
1217
+ description: z.string().describe("Full context \u2014 what's happening, why it matters, what you observed"),
1218
+ context: z.string().optional().describe("Optional additional context (e.g. 'Observed during context gather calls taking 700ms+')"),
1219
+ entryId: z.string().optional().describe("Optional custom entry ID (e.g. 'TEN-my-id'). Auto-generated if omitted."),
1220
+ canonicalKey: z.string().optional().describe("Semantic type (e.g. 'decision', 'tension', 'vision'). Auto-assigned from collection if omitted."),
1221
+ 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."),
1222
+ links: z.array(z.object({
1223
+ to: z.string().describe("Target entry ID (e.g. 'BR-64', 'ARCH-8')"),
1224
+ type: z.string().describe("Relation type (e.g. 'governs', 'related_to', 'informs')")
1225
+ })).optional().describe("Relations to create after capture. Skips auto-link discovery when provided."),
1226
+ autoCommit: z.boolean().optional().describe("If true, commits the entry immediately after capture + linking. Use for ungoverned collections or when you're certain.")
1227
+ });
1228
+ var batchCaptureSchema = z.object({
1229
+ entries: z.array(z.object({
1230
+ collection: z.string().describe("Collection slug"),
1231
+ name: z.string().describe("Display name"),
1232
+ description: z.string().describe("Full context / definition"),
1233
+ entryId: z.string().optional().describe("Optional custom entry ID")
1234
+ })).min(1).max(50).describe("Array of entries to capture")
1235
+ });
1236
+ var captureClassifierSchema = z.object({
1237
+ enabled: z.boolean(),
1238
+ autoRouted: z.boolean(),
1239
+ topConfidence: z.number(),
1240
+ // Backward-compatible alias for topConfidence.
1241
+ confidence: z.number(),
1242
+ reasons: z.array(z.string()),
1243
+ candidates: z.array(
1244
+ z.object({
1245
+ collection: z.enum(STARTER_COLLECTIONS),
1246
+ signalScore: z.number(),
1247
+ // Backward-compatible alias for signalScore.
1248
+ confidence: z.number()
1249
+ })
1250
+ )
1251
+ });
1252
+ function trackClassifierTelemetry(params) {
1253
+ const telemetry = {
1254
+ predicted_collection: params.predictedCollection,
1255
+ confidence: params.confidence,
1256
+ auto_routed: params.autoRouted,
1257
+ reason_category: params.reasonCategory,
1258
+ explicit_collection_provided: params.explicitCollectionProvided
1259
+ };
1260
+ trackCaptureClassifierEvaluated(params.workspaceId, telemetry);
1261
+ if (params.outcome === "auto-routed") {
1262
+ trackCaptureClassifierAutoRouted(params.workspaceId, telemetry);
1263
+ return;
1264
+ }
1265
+ trackCaptureClassifierFallback(params.workspaceId, telemetry);
1266
+ }
1267
+ function buildCollectionRequiredResult() {
1268
+ return {
1269
+ content: [{
1270
+ type: "text",
1271
+ text: "Collection is required unless `capture-without-thinking` is enabled.\n\nProvide `collection` explicitly, or enable the feature flag for this workspace."
1272
+ }]
1273
+ };
1274
+ }
1275
+ function buildClassifierUnknownResult() {
1276
+ return {
1277
+ content: [{
1278
+ type: "text",
1279
+ text: "I could not infer a collection confidently from this input.\n\nPlease provide `collection`, or rewrite with clearer intent (decision/problem/definition/insight/bet)."
1280
+ }],
1281
+ structuredContent: {
1282
+ classifier: {
1283
+ enabled: true,
1284
+ autoRouted: false,
1285
+ topConfidence: 0,
1286
+ confidence: 0,
1287
+ reasons: [],
1288
+ candidates: []
1289
+ }
1290
+ }
1291
+ };
1292
+ }
1293
+ function buildProvisionedCollectionSuggestions(candidates) {
1294
+ return candidates.length ? candidates.map((c) => `- \`${c.collection}\` (${c.signalScore}% signal score)`).join("\n") : "- No provisioned starter collection candidates were inferred confidently.";
1295
+ }
1296
+ function buildUnsupportedProvisioningResult(classified, provisionedCandidates) {
1297
+ const suggestions = buildProvisionedCollectionSuggestions(provisionedCandidates);
1298
+ return {
1299
+ content: [{
1300
+ type: "text",
1301
+ text: `Collection inference is not safe to auto-route yet.
1302
+
1303
+ Predicted collection \`${classified.collection}\` is not provisioned/supported for auto-routing in this workspace.
1304
+ Reason: ${classified.reasons.join("; ") || "low signal"}
1305
+
1306
+ Choose one of these provisioned starter collections and retry with \`collection\`:
1307
+ ${suggestions}
1308
+
1309
+ Correction path: rerun with explicit \`collection\`.`
1310
+ }],
1311
+ structuredContent: {
1312
+ classifier: {
1313
+ enabled: true,
1314
+ autoRouted: false,
1315
+ topConfidence: classified.topConfidence,
1316
+ confidence: classified.confidence,
1317
+ reasons: classified.reasons,
1318
+ candidates: provisionedCandidates
1319
+ }
1320
+ }
1321
+ };
1322
+ }
1323
+ function buildAmbiguousRouteResult(classified, classifierMeta, ambiguousRoute) {
1324
+ const suggestions = buildProvisionedCollectionSuggestions(classifierMeta.candidates);
1325
+ return {
1326
+ content: [{
1327
+ type: "text",
1328
+ text: "Collection inference is not safe to auto-route yet.\n\n" + (ambiguousRoute ? "Routing held because intent is ambiguous across top candidates.\n\n" : "") + `Predicted: \`${classified.collection}\` (${classified.topConfidence}% top confidence)
1329
+ Reason: ${classified.reasons.join("; ") || "low signal"}
1330
+
1331
+ Choose one of these and retry with \`collection\`:
1332
+ ${suggestions}
1333
+
1334
+ Correction path: if this was close, rerun with your chosen \`collection\`.`
1335
+ }],
1336
+ structuredContent: {
1337
+ classifier: classifierMeta
1338
+ }
1339
+ };
1340
+ }
1341
+ async function getProvisionedStarterCollectionCandidates(classified, supportedStarterCollections) {
1342
+ const allCollections = await mcpQuery("chain.listCollections");
1343
+ const provisionedStarterCollections = new Set(
1344
+ (allCollections ?? []).map((collection) => collection.slug).filter(
1345
+ (slug) => supportedStarterCollections.has(slug)
1346
+ )
1347
+ );
1348
+ const provisionedCandidates = classified.candidates.filter(
1349
+ (candidate) => provisionedStarterCollections.has(candidate.collection)
1350
+ );
1351
+ return { provisionedStarterCollections, provisionedCandidates };
1352
+ }
1353
+ async function resolveCaptureCollection(params) {
1354
+ const {
1355
+ collection,
1356
+ name,
1357
+ description,
1358
+ classifierFlagOn,
1359
+ supportedStarterCollections,
1360
+ workspaceId,
1361
+ explicitCollectionProvided
1362
+ } = params;
1363
+ if (collection) {
1364
+ return { resolvedCollection: collection };
1365
+ }
1366
+ if (!classifierFlagOn) {
1367
+ return { earlyResult: buildCollectionRequiredResult() };
1368
+ }
1369
+ const classified = classifyStarterCollection(name, description);
1370
+ if (!classified) {
1371
+ trackClassifierTelemetry({
1372
+ workspaceId,
1373
+ predictedCollection: "unknown",
1374
+ confidence: 0,
1375
+ autoRouted: false,
1376
+ reasonCategory: "low-confidence",
1377
+ explicitCollectionProvided,
1378
+ outcome: "fallback"
1379
+ });
1380
+ return { earlyResult: buildClassifierUnknownResult() };
1381
+ }
1382
+ const { provisionedStarterCollections, provisionedCandidates } = await getProvisionedStarterCollectionCandidates(classified, supportedStarterCollections);
1383
+ if (!provisionedStarterCollections.has(classified.collection)) {
1384
+ trackClassifierTelemetry({
1385
+ workspaceId,
1386
+ predictedCollection: classified.collection,
1387
+ confidence: classified.confidence,
1388
+ autoRouted: false,
1389
+ reasonCategory: "non-provisioned",
1390
+ explicitCollectionProvided,
1391
+ outcome: "fallback"
1392
+ });
1393
+ return {
1394
+ earlyResult: buildUnsupportedProvisioningResult(classified, provisionedCandidates)
1395
+ };
1396
+ }
1397
+ const autoRoute = shouldAutoRouteClassification(classified);
1398
+ const ambiguousRoute = isClassificationAmbiguous(classified);
1399
+ const classifierMeta = {
1400
+ enabled: true,
1401
+ autoRouted: autoRoute,
1402
+ topConfidence: classified.topConfidence,
1403
+ confidence: classified.confidence,
1404
+ reasons: classified.reasons,
1405
+ candidates: provisionedCandidates
1406
+ };
1407
+ if (!autoRoute) {
1408
+ trackClassifierTelemetry({
1409
+ workspaceId,
1410
+ predictedCollection: classified.collection,
1411
+ confidence: classified.confidence,
1412
+ autoRouted: false,
1413
+ reasonCategory: ambiguousRoute ? "ambiguous" : "low-confidence",
1414
+ explicitCollectionProvided,
1415
+ outcome: "fallback"
1416
+ });
1417
+ return {
1418
+ classifierMeta,
1419
+ earlyResult: buildAmbiguousRouteResult(classified, classifierMeta, ambiguousRoute)
1420
+ };
1421
+ }
1422
+ trackClassifierTelemetry({
1423
+ workspaceId,
1424
+ predictedCollection: classified.collection,
1425
+ confidence: classified.confidence,
1426
+ autoRouted: true,
1427
+ reasonCategory: "auto-routed",
1428
+ explicitCollectionProvided,
1429
+ outcome: "auto-routed"
1430
+ });
1431
+ return {
1432
+ resolvedCollection: classified.collection,
1433
+ classifierMeta
1434
+ };
1435
+ }
1436
+ var captureSuccessOutputSchema = z.object({
1437
+ entryId: z.string(),
1438
+ collection: z.string(),
1439
+ name: z.string(),
1440
+ status: z.enum(["draft", "committed"]),
1441
+ qualityScore: z.number(),
1442
+ qualityVerdict: z.record(z.unknown()).optional(),
1443
+ classifier: captureClassifierSchema.optional(),
1444
+ studioUrl: z.string().optional()
1445
+ }).strict();
1446
+ var captureClassifierOnlyOutputSchema = z.object({
1447
+ classifier: captureClassifierSchema
1448
+ }).strict();
1449
+ var captureOutputSchema = z.union([
1450
+ captureSuccessOutputSchema,
1451
+ captureClassifierOnlyOutputSchema
1452
+ ]);
1453
+ var batchCaptureOutputSchema = z.object({
1454
+ captured: z.array(z.object({
1455
+ entryId: z.string(),
1456
+ collection: z.string(),
1457
+ name: z.string()
1458
+ })),
1459
+ total: z.number(),
1460
+ failed: z.number(),
1461
+ failedEntries: z.array(z.object({
1462
+ index: z.number(),
1463
+ collection: z.string(),
1464
+ name: z.string(),
1465
+ error: z.string()
1466
+ })).optional()
1467
+ });
1468
+ function registerSmartCaptureTools(server) {
1469
+ const supportedStarterCollections = new Set(
1470
+ STARTER_COLLECTIONS.filter((slug) => PROFILES.has(slug))
1471
+ );
1472
+ const captureTool = server.registerTool(
1473
+ "capture",
1474
+ {
1475
+ title: "Capture",
1476
+ description: "The single tool for creating knowledge entries. Creates an entry, auto-links related entries, and returns a quality scorecard \u2014 all in one call. Provide a name and description; `collection` is optional when `capture-without-thinking` is enabled.\n\nSupported collections with smart profiles: tensions, business-rules, glossary, decisions, features, audiences, strategy, standards, maps, chains, tracking-events.\nAll other collections get an ENT-{random} ID and sensible defaults.\n\n**Explicit data:** When you know the schema, pass `data: { field: value }` to set fields directly. Top-level `name` and `description` always win for those fields. `data` wins over inference for all other fields.\n\n**Compound capture:** Pass `links` to create relations in the same call (skips auto-link discovery). Pass `autoCommit: true` to promote the entry from draft to SSOT immediately after linking. Governed collections (glossary, business-rules, principles, standards, strategy, features) will warn but still commit \u2014 use only when you're certain.\n\nAlways creates as 'draft' unless `autoCommit` is true. Use `update-entry` for post-creation adjustments.",
1477
+ inputSchema: captureSchema.shape,
1478
+ annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: false }
1479
+ },
1480
+ async ({ collection, name, description, context, entryId, canonicalKey, data: userData, links, autoCommit }) => {
1481
+ requireWriteAccess();
1482
+ const wsCtx = await getWorkspaceContext();
1483
+ const explicitCollectionProvided = typeof collection === "string" && collection.trim().length > 0;
1484
+ const classifierFlagOn = await isFeatureEnabled(
1485
+ CAPTURE_WITHOUT_THINKING_FLAG,
1486
+ wsCtx.workspaceId,
1487
+ wsCtx.workspaceSlug
1488
+ );
1489
+ const resolution = await resolveCaptureCollection({
1490
+ collection,
1491
+ name,
1492
+ description,
1493
+ classifierFlagOn,
1494
+ supportedStarterCollections,
1495
+ workspaceId: wsCtx.workspaceId,
1496
+ explicitCollectionProvided
1497
+ });
1498
+ if (resolution.earlyResult) {
1499
+ return resolution.earlyResult;
1500
+ }
1501
+ const resolvedCollection = resolution.resolvedCollection;
1502
+ const classifierMeta = resolution.classifierMeta;
1503
+ if (!resolvedCollection) {
1504
+ return buildCollectionRequiredResult();
1505
+ }
1506
+ const profile = PROFILES.get(resolvedCollection) ?? FALLBACK_PROFILE;
1507
+ const col = await mcpQuery("chain.getCollection", { slug: resolvedCollection });
1508
+ if (!col) {
1509
+ const displayName = resolvedCollection.split("-").map((w) => w.charAt(0).toUpperCase() + w.slice(1)).join(" ");
1510
+ return {
1511
+ content: [{
1512
+ type: "text",
1513
+ text: `Collection \`${resolvedCollection}\` not found.
1514
+
1515
+ **To create it**, run:
1516
+ \`\`\`
1517
+ collections action=create slug="${resolvedCollection}" name="${displayName}" description="..."
1518
+ \`\`\`
1519
+
1520
+ Or use \`collections action=list\` to see available collections.`
1521
+ }]
1522
+ };
1523
+ }
1524
+ const data = {};
1525
+ const today = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
1526
+ for (const field of col.fields ?? []) {
1527
+ const key = field.key;
1528
+ if (key === profile.descriptionField) {
1529
+ data[key] = description;
1530
+ } else if (field.type === "array" || field.type === "multi-select") {
1531
+ data[key] = [];
1532
+ } else if (field.type === "select") {
1533
+ } else {
1534
+ data[key] = "";
1535
+ }
1536
+ }
1537
+ for (const def of profile.defaults) {
1538
+ if (def.value === "today") {
1539
+ data[def.key] = today;
1540
+ } else if (def.value !== "infer") {
1541
+ data[def.key] = def.value;
1542
+ }
1543
+ }
1544
+ if (profile.inferField) {
1545
+ const inferred = profile.inferField({
1546
+ collection: resolvedCollection,
1547
+ name,
1548
+ description,
1549
+ context,
1550
+ data,
1551
+ entryId: "",
1552
+ linksCreated: [],
1553
+ linksSuggested: [],
1554
+ collectionFields: col.fields ?? []
1555
+ });
1556
+ for (const [key, val] of Object.entries(inferred)) {
1557
+ if (val !== void 0 && val !== "") {
1558
+ data[key] = val;
1559
+ }
1560
+ }
1561
+ }
1562
+ if (userData && typeof userData === "object") {
1563
+ for (const [key, val] of Object.entries(userData)) {
1564
+ if (key !== "name") data[key] = val;
1565
+ }
1566
+ }
1567
+ data[profile.descriptionField || "description"] = description;
1568
+ const status = "draft";
1569
+ let finalEntryId;
1570
+ let internalId;
1571
+ try {
1572
+ const agentId = getAgentSessionId();
1573
+ const result = await mcpMutation("chain.createEntry", {
1574
+ collectionSlug: resolvedCollection,
1575
+ entryId: entryId ?? void 0,
1576
+ name,
1577
+ status,
1578
+ data,
1579
+ canonicalKey,
1580
+ createdBy: agentId ? `agent:${agentId}` : "capture",
1581
+ sessionId: agentId ?? void 0
1582
+ });
1583
+ internalId = result.docId;
1584
+ finalEntryId = result.entryId;
1585
+ await recordSessionActivity({ entryCreated: internalId });
1586
+ } catch (error) {
1587
+ const msg = error instanceof Error ? error.message : String(error);
1588
+ if (msg.includes("Duplicate") || msg.includes("already exists")) {
1589
+ return {
1590
+ content: [{
1591
+ type: "text",
1592
+ text: `# Cannot Capture \u2014 Duplicate Detected
1593
+
1594
+ ${msg}
1595
+
1596
+ Use \`entries action=get\` to inspect the existing entry, or \`update-entry\` to modify it.`
1597
+ }]
1598
+ };
1599
+ }
1600
+ throw error;
1601
+ }
1602
+ const linksCreated = [];
1603
+ const linksSuggested = [];
1604
+ const userLinkResults = [];
1605
+ const skipAutoDiscovery = links && links.length > 0;
1606
+ const searchQuery = extractSearchTerms(name, description);
1607
+ if (searchQuery && !skipAutoDiscovery) {
1608
+ const [searchResults, allCollections] = await Promise.all([
1609
+ mcpQuery("chain.searchEntries", { query: searchQuery }),
1610
+ mcpQuery("chain.listCollections")
1611
+ ]);
1612
+ const collMap = /* @__PURE__ */ new Map();
1613
+ for (const c of allCollections) collMap.set(c._id, c.slug);
1614
+ const candidates = (searchResults ?? []).filter((r) => r.entryId !== finalEntryId && r._id !== internalId).map((r) => {
1615
+ const conf = computeLinkConfidence(r, name, description, resolvedCollection, collMap.get(r.collectionId) ?? "unknown");
1616
+ return {
1617
+ ...r,
1618
+ collSlug: collMap.get(r.collectionId) ?? "unknown",
1619
+ confidence: conf.score,
1620
+ confidenceReason: conf.reason
1621
+ };
1622
+ }).sort((a, b) => b.confidence - a.confidence);
1623
+ for (const c of candidates) {
1624
+ if (linksCreated.length >= MAX_AUTO_LINKS) break;
1625
+ if (c.confidence < AUTO_LINK_CONFIDENCE_THRESHOLD) break;
1626
+ if (!c.entryId || !finalEntryId) continue;
1627
+ const { type: relationType, reason: relationReason } = inferRelationType(resolvedCollection, c.collSlug, profile);
1628
+ try {
1629
+ await mcpMutation("chain.createEntryRelation", {
1630
+ fromEntryId: finalEntryId,
1631
+ toEntryId: c.entryId,
1632
+ type: relationType
1633
+ });
1634
+ linksCreated.push({
1635
+ targetEntryId: c.entryId,
1636
+ targetName: c.name,
1637
+ targetCollection: c.collSlug,
1638
+ relationType,
1639
+ linkReason: `confidence ${c.confidence} (${c.confidenceReason}) + ${relationReason}`
1640
+ });
1641
+ } catch {
1642
+ }
1643
+ }
1644
+ const linkedIds = new Set(linksCreated.map((l) => l.targetEntryId));
1645
+ for (const c of candidates) {
1646
+ if (linksSuggested.length >= MAX_SUGGESTIONS) break;
1647
+ if (linkedIds.has(c.entryId)) continue;
1648
+ if (c.confidence < 10) continue;
1649
+ const preview = extractPreview(c.data, 80);
1650
+ const reason = c.confidence >= AUTO_LINK_CONFIDENCE_THRESHOLD ? "high relevance (already linked)" : `"${c.name.toLowerCase().split(/\s+/).filter((w) => `${name} ${description}`.toLowerCase().includes(w) && w.length > 3).slice(0, 2).join('", "')}" appears in content`;
1651
+ linksSuggested.push({
1652
+ entryId: c.entryId,
1653
+ name: c.name,
1654
+ collection: c.collSlug,
1655
+ reason,
1656
+ preview
1657
+ });
1658
+ }
1659
+ }
1660
+ if (links && links.length > 0 && finalEntryId) {
1661
+ for (const link of links) {
1662
+ try {
1663
+ await mcpMutation("chain.createEntryRelation", {
1664
+ fromEntryId: finalEntryId,
1665
+ toEntryId: link.to,
1666
+ type: link.type
1667
+ });
1668
+ userLinkResults.push({ label: `\u2713 ${link.type} \u2192 ${link.to}`, ok: true });
1669
+ linksCreated.push({
1670
+ targetEntryId: link.to,
1671
+ targetName: link.to,
1672
+ targetCollection: "unknown",
1673
+ relationType: link.type
1674
+ });
1675
+ } catch (e) {
1676
+ const msg = e instanceof Error ? e.message : "failed";
1677
+ userLinkResults.push({ label: `\u2717 ${link.type} \u2192 ${link.to}: ${msg}`, ok: false });
1678
+ }
1679
+ }
1680
+ }
1681
+ const captureCtx = {
1682
+ collection: resolvedCollection,
1683
+ name,
1684
+ description,
1685
+ context,
1686
+ data,
1687
+ entryId: finalEntryId,
1688
+ canonicalKey,
1689
+ linksCreated,
1690
+ linksSuggested,
1691
+ collectionFields: col.fields ?? []
1692
+ };
1693
+ const quality = scoreQuality(captureCtx, profile);
1694
+ let cardinalityWarning = null;
1695
+ const resolvedCK = canonicalKey ?? captureCtx.canonicalKey;
1696
+ if (resolvedCK) {
1697
+ try {
1698
+ const check = await mcpQuery("chain.checkCardinalityWarning", {
1699
+ canonicalKey: resolvedCK
1700
+ });
1701
+ if (check?.warning) {
1702
+ cardinalityWarning = check.warning;
1703
+ }
1704
+ } catch {
1705
+ }
1706
+ }
1707
+ const contradictionWarnings = await runContradictionCheck(name, description);
1708
+ if (contradictionWarnings.length > 0) {
1709
+ await recordSessionActivity({ contradictionWarning: true });
1710
+ }
1711
+ let coachingSection = "";
1712
+ let verdictResult = null;
1713
+ try {
1714
+ verdictResult = await mcpMutation("quality.evaluateHeuristicAndSchedule", {
1715
+ entryId: finalEntryId,
1716
+ context: "capture"
1717
+ });
1718
+ if (verdictResult?.verdict && verdictResult.verdict.tier !== "passive" && verdictResult.verdict.criteria.length > 0) {
1719
+ coachingSection = formatRubricCoaching(verdictResult);
1720
+ }
1721
+ } catch {
1722
+ }
1723
+ if (verdictResult?.verdict) {
1724
+ try {
1725
+ const wsForTracking = await getWorkspaceContext();
1726
+ const v = verdictResult.verdict;
1727
+ const failedCount = (v.criteria ?? []).filter((c) => !c.passed).length;
1728
+ trackQualityVerdict(wsForTracking.workspaceId, {
1729
+ entry_id: finalEntryId,
1730
+ entry_type: v.canonicalKey ?? resolvedCollection,
1731
+ tier: v.tier,
1732
+ context: "capture",
1733
+ passed: v.passed,
1734
+ source: verdictResult.source ?? "heuristic",
1735
+ criteria_total: v.criteria?.length ?? 0,
1736
+ criteria_failed: failedCount,
1737
+ llm_scheduled: v.tier !== "passive"
1738
+ });
1739
+ } catch {
1740
+ }
1741
+ }
1742
+ const shouldAutoCommit = autoCommit === true || autoCommit === void 0 && wsCtx.governanceMode === "open";
1743
+ let finalStatus = "draft";
1744
+ let commitError = null;
1745
+ if (shouldAutoCommit && finalEntryId) {
1746
+ try {
1747
+ await mcpMutation("chain.commitEntry", { entryId: finalEntryId });
1748
+ finalStatus = "committed";
1749
+ await recordSessionActivity({ entryModified: internalId });
1750
+ } catch (e) {
1751
+ commitError = e instanceof Error ? e.message : "unknown error";
1752
+ }
1753
+ }
1754
+ const lines = [
1755
+ `# Captured: ${finalEntryId || name}`,
1756
+ `**${name}** added to \`${resolvedCollection}\` as \`${finalStatus}\``,
1757
+ `**Workspace:** ${wsCtx.workspaceSlug} (${wsCtx.workspaceId})`
1758
+ ];
1759
+ if (classifierMeta?.autoRouted) {
1760
+ lines.push("");
1761
+ lines.push("## Collection routing");
1762
+ lines.push(`Auto-routed to \`${resolvedCollection}\` (${classifierMeta.topConfidence}% top confidence).`);
1763
+ if (classifierMeta.reasons.length > 0) {
1764
+ lines.push(`Reason: ${classifierMeta.reasons.join("; ")}.`);
1765
+ }
1766
+ lines.push("Correction path: rerun capture with explicit `collection` if this routing is wrong.");
1767
+ }
1768
+ const appUrl = process.env.PRODUCTBRAIN_APP_URL ?? "https://productbrain.io";
1769
+ const studioUrl = resolvedCollection === "bets" ? `${appUrl.replace(/\/$/, "")}/w/${wsCtx.workspaceSlug}/studio/${internalId}` : void 0;
1770
+ if (studioUrl) {
1771
+ lines.push("");
1772
+ lines.push(`**View in Studio:** ${studioUrl}`);
1773
+ }
1774
+ if (linksCreated.length > 0) {
1775
+ lines.push("");
1776
+ lines.push(`## Auto-linked (${linksCreated.length})`);
1777
+ for (const link of linksCreated) {
1778
+ const reason = link.linkReason ? ` \u2014 because ${link.linkReason}` : "";
1779
+ lines.push(`- -> **${link.relationType}** ${link.targetEntryId}: ${link.targetName} [${link.targetCollection}]${reason}`);
1780
+ }
1781
+ }
1782
+ if (userLinkResults.length > 0) {
1783
+ lines.push("");
1784
+ lines.push("## Requested links");
1785
+ for (const r of userLinkResults) lines.push(`- ${r.label}`);
1786
+ }
1787
+ if (finalStatus === "committed") {
1788
+ const wasAutoCommitted = autoCommit === void 0 && wsCtx.governanceMode === "open";
1789
+ lines.push("");
1790
+ lines.push(`## Committed: ${finalEntryId}`);
1791
+ if (wasAutoCommitted) {
1792
+ lines.push(`**${name}** added to your knowledge base.`);
1793
+ } else {
1794
+ lines.push(`**${name}** promoted to SSOT on the Chain.`);
1795
+ }
1796
+ if (GOVERNED_COLLECTIONS.has(resolvedCollection)) {
1797
+ lines.push(`_Note: \`${resolvedCollection}\` is a governed collection \u2014 ensure this entry has been reviewed._`);
1798
+ }
1799
+ } else if (commitError) {
1800
+ lines.push("");
1801
+ lines.push("## Commit failed");
1802
+ lines.push(`Error: ${commitError}. Entry saved as draft \u2014 use \`commit-entry entryId="${finalEntryId}"\` to promote when ready.`);
1803
+ }
1804
+ if (linksSuggested.length > 0) {
1805
+ lines.push("");
1806
+ lines.push("## Suggested links (review and use `relations action=create`)");
1807
+ for (let i = 0; i < linksSuggested.length; i++) {
1808
+ const s = linksSuggested[i];
1809
+ const preview = s.preview ? ` \u2014 ${s.preview}` : "";
1810
+ lines.push(`${i + 1}. **${s.entryId ?? "(no ID)"}**: ${s.name} [${s.collection}]${preview}`);
1811
+ }
1812
+ }
1813
+ lines.push("");
1814
+ lines.push(formatQualityReport(quality));
1815
+ const failedChecks = quality.checks.filter((c) => !c.passed);
1816
+ if (failedChecks.length > 0) {
1817
+ lines.push("");
1818
+ lines.push(`_To improve: \`update-entry entryId="${finalEntryId}"\` to fill missing fields._`);
1819
+ }
1820
+ const isBetOrGoal = resolvedCollection === "bets" || resolvedCK === "bet" || resolvedCK === "goal";
1821
+ const hasStrategyLink = linksCreated.some((l) => l.targetCollection === "strategy");
1822
+ if (isBetOrGoal && !hasStrategyLink) {
1823
+ lines.push("");
1824
+ lines.push(
1825
+ `**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.`
1826
+ );
1827
+ await recordSessionActivity({ strategyLinkWarnedForEntryId: internalId });
1828
+ }
1829
+ if (cardinalityWarning) {
1830
+ lines.push("");
1831
+ lines.push(`**Cardinality warning:** ${cardinalityWarning}`);
1832
+ }
1833
+ if (contradictionWarnings.length > 0) {
1834
+ lines.push("");
1835
+ lines.push("\u26A0 Contradiction check: proposed entry matched existing governance entries:");
1836
+ for (const w of contradictionWarnings) {
1837
+ lines.push(`- ${w.name} (${w.collection}, ${w.entryId}) \u2014 has 'governs' relation to ${w.governsCount} entries`);
1838
+ }
1839
+ lines.push("Run `context action=gather` on these entries before committing.");
1840
+ }
1841
+ if (coachingSection) {
1842
+ lines.push("");
1843
+ lines.push(coachingSection);
1844
+ }
1845
+ lines.push("");
1846
+ lines.push("## Next Steps");
1847
+ const eid = finalEntryId || "(check entry ID)";
1848
+ if (finalStatus === "committed") {
1849
+ lines.push(`1. **Connect it:** \`graph action=suggest entryId="${eid}"\` \u2014 discover additional links`);
1850
+ if (failedChecks.length > 0) {
1851
+ lines.push(`2. **Improve quality:** \`update-entry entryId="${eid}"\` \u2014 fill missing fields`);
1852
+ }
1853
+ } else {
1854
+ if (userLinkResults.length === 0) {
1855
+ lines.push(`1. **Connect it:** \`graph action=suggest entryId="${eid}"\` \u2014 discover what this should link to`);
1856
+ }
1857
+ lines.push(`${userLinkResults.length === 0 ? "2" : "1"}. **Commit it:** \`commit-entry entryId="${eid}"\` \u2014 promote from draft to SSOT on the Chain`);
1858
+ if (failedChecks.length > 0) {
1859
+ lines.push(`${userLinkResults.length === 0 ? "3" : "2"}. **Improve quality:** \`update-entry entryId="${eid}"\` \u2014 fill missing fields`);
1860
+ }
1861
+ }
1862
+ try {
1863
+ const readiness = await mcpQuery("chain.workspaceReadiness");
1864
+ if (readiness && readiness.gaps && readiness.gaps.length > 0) {
1865
+ const topGaps = readiness.gaps.slice(0, 2);
1866
+ lines.push("");
1867
+ lines.push(`## Workspace Readiness: ${readiness.score}%`);
1868
+ for (const gap of topGaps) {
1869
+ lines.push(`- _${gap.label}:_ ${gap.guidance}`);
1870
+ }
1871
+ }
1872
+ } catch {
1873
+ }
1874
+ const toolResult = {
1875
+ content: [{ type: "text", text: lines.join("\n") }],
1876
+ structuredContent: {
1877
+ entryId: finalEntryId,
1878
+ collection: resolvedCollection,
1879
+ name,
1880
+ status: finalStatus,
1881
+ qualityScore: quality.score,
1882
+ qualityVerdict: verdictResult?.verdict ? { ...verdictResult.verdict, source: verdictResult.source ?? "heuristic" } : void 0,
1883
+ ...classifierMeta && { classifier: classifierMeta },
1884
+ ...studioUrl && { studioUrl }
1885
+ }
1886
+ };
1887
+ return toolResult;
1888
+ }
1889
+ );
1890
+ trackWriteTool(captureTool);
1891
+ const batchCaptureTool = server.registerTool(
1892
+ "batch-capture",
1893
+ {
1894
+ title: "Batch Capture",
1895
+ description: "Create multiple knowledge entries in one call. Ideal for workspace setup, document ingestion, or any scenario where you need to capture many entries at once.\n\nEach entry is created independently \u2014 if one fails, the others still succeed. Returns a compact summary instead of per-entry quality scorecards.\n\nAuto-linking runs per entry but contradiction checks and readiness hints are skipped for speed. Use `quality action=check` on individual entries afterward if needed.",
1896
+ inputSchema: batchCaptureSchema.shape,
1897
+ annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: false }
1898
+ },
1899
+ async ({ entries }) => {
1900
+ requireWriteAccess();
1901
+ const agentId = getAgentSessionId();
1902
+ const createdBy = agentId ? `agent:${agentId}` : "capture";
1903
+ const results = [];
1904
+ await server.sendLoggingMessage({
1905
+ level: "info",
1906
+ data: `Batch capturing ${entries.length} entries...`,
1907
+ logger: "product-brain"
1908
+ });
1909
+ const allCollections = await mcpQuery("chain.listCollections");
1910
+ const collCache = /* @__PURE__ */ new Map();
1911
+ for (const c of allCollections) collCache.set(c.slug, c);
1912
+ const collIdToSlug = /* @__PURE__ */ new Map();
1913
+ for (const c of allCollections) collIdToSlug.set(c._id, c.slug);
1914
+ for (let entryIdx = 0; entryIdx < entries.length; entryIdx++) {
1915
+ const entry = entries[entryIdx];
1916
+ if (entryIdx > 0 && entryIdx % 5 === 0) {
1917
+ await server.sendLoggingMessage({
1918
+ level: "info",
1919
+ data: `Captured ${entryIdx}/${entries.length} entries...`,
1920
+ logger: "product-brain"
1921
+ });
1922
+ }
1923
+ const profile = PROFILES.get(entry.collection) ?? FALLBACK_PROFILE;
1924
+ const col = collCache.get(entry.collection);
1925
+ if (!col) {
1926
+ results.push({ name: entry.name, collection: entry.collection, entryId: "", ok: false, autoLinks: 0, error: `Collection "${entry.collection}" not found` });
1927
+ continue;
1928
+ }
1929
+ const data = {};
1930
+ const today = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
1931
+ for (const field of col.fields ?? []) {
1932
+ const key = field.key;
1933
+ if (key === profile.descriptionField) {
1934
+ data[key] = entry.description;
1935
+ } else if (field.type === "array" || field.type === "multi-select") {
1936
+ data[key] = [];
1937
+ } else if (field.type === "select") {
1938
+ } else {
1939
+ data[key] = "";
1940
+ }
1941
+ }
1942
+ for (const def of profile.defaults) {
1943
+ if (def.value === "today") data[def.key] = today;
1944
+ else if (def.value !== "infer") data[def.key] = def.value;
1945
+ }
1946
+ if (profile.inferField) {
1947
+ const inferred = profile.inferField({
1948
+ collection: entry.collection,
1949
+ name: entry.name,
1950
+ description: entry.description,
1951
+ data,
1952
+ entryId: "",
1953
+ linksCreated: [],
1954
+ linksSuggested: [],
1955
+ collectionFields: col.fields ?? []
1956
+ });
1957
+ for (const [key, val] of Object.entries(inferred)) {
1958
+ if (val !== void 0 && val !== "") data[key] = val;
1959
+ }
1960
+ }
1961
+ if (!data[profile.descriptionField] && !data.description && !data.canonical) {
1962
+ data[profile.descriptionField || "description"] = entry.description;
1963
+ }
1964
+ try {
1965
+ const result = await mcpMutation("chain.createEntry", {
1966
+ collectionSlug: entry.collection,
1967
+ entryId: entry.entryId ?? void 0,
1968
+ name: entry.name,
1969
+ status: "draft",
1970
+ data,
1971
+ createdBy,
1972
+ sessionId: agentId ?? void 0
1973
+ });
1974
+ const internalId = result.docId;
1975
+ const finalEntryId = result.entryId;
1976
+ let autoLinkCount = 0;
1977
+ const searchQuery = extractSearchTerms(entry.name, entry.description);
1978
+ if (searchQuery) {
1979
+ try {
1980
+ const searchResults = await mcpQuery("chain.searchEntries", { query: searchQuery });
1981
+ const candidates = (searchResults ?? []).filter((r) => r.entryId !== finalEntryId).map((r) => {
1982
+ const conf = computeLinkConfidence(r, entry.name, entry.description, entry.collection, collIdToSlug.get(r.collectionId) ?? "unknown");
1983
+ return {
1984
+ ...r,
1985
+ collSlug: collIdToSlug.get(r.collectionId) ?? "unknown",
1986
+ confidence: conf.score
1987
+ };
1988
+ }).sort((a, b) => b.confidence - a.confidence);
1989
+ for (const c of candidates) {
1990
+ if (autoLinkCount >= MAX_AUTO_LINKS) break;
1991
+ if (c.confidence < AUTO_LINK_CONFIDENCE_THRESHOLD) break;
1992
+ if (!c.entryId) continue;
1993
+ const { type: relationType } = inferRelationType(entry.collection, c.collSlug, profile);
1994
+ try {
1995
+ await mcpMutation("chain.createEntryRelation", {
1996
+ fromEntryId: finalEntryId,
1997
+ toEntryId: c.entryId,
1998
+ type: relationType
1999
+ });
2000
+ autoLinkCount++;
2001
+ } catch {
2002
+ }
2003
+ }
2004
+ } catch {
2005
+ }
2006
+ }
2007
+ results.push({ name: entry.name, collection: entry.collection, entryId: finalEntryId, ok: true, autoLinks: autoLinkCount });
2008
+ await recordSessionActivity({ entryCreated: internalId });
2009
+ } catch (error) {
2010
+ const msg = error instanceof Error ? error.message : String(error);
2011
+ results.push({ name: entry.name, collection: entry.collection, entryId: "", ok: false, autoLinks: 0, error: msg });
2012
+ }
2013
+ }
2014
+ const created = results.filter((r) => r.ok);
2015
+ const failed = results.filter((r) => !r.ok);
2016
+ await server.sendLoggingMessage({
2017
+ level: "info",
2018
+ data: `Batch complete. ${created.length} succeeded, ${failed.length} failed.`,
2019
+ logger: "product-brain"
2020
+ });
2021
+ const totalAutoLinks = created.reduce((sum, r) => sum + r.autoLinks, 0);
2022
+ const byCollection = /* @__PURE__ */ new Map();
2023
+ for (const r of created) {
2024
+ byCollection.set(r.collection, (byCollection.get(r.collection) ?? 0) + 1);
2025
+ }
2026
+ const lines = [
2027
+ `# Batch Capture Complete`,
2028
+ `**${created.length}** created, **${failed.length}** failed out of ${entries.length} total.`,
2029
+ `**Auto-links created:** ${totalAutoLinks}`,
2030
+ ""
2031
+ ];
2032
+ if (byCollection.size > 0) {
2033
+ lines.push("## By Collection");
2034
+ for (const [col, count] of byCollection) {
2035
+ lines.push(`- \`${col}\`: ${count} entries`);
2036
+ }
2037
+ lines.push("");
2038
+ }
2039
+ if (created.length > 0) {
2040
+ lines.push("## Created");
2041
+ for (const r of created) {
2042
+ const linkNote = r.autoLinks > 0 ? ` (${r.autoLinks} auto-links)` : "";
2043
+ lines.push(`- **${r.entryId}**: ${r.name} [${r.collection}]${linkNote}`);
2044
+ }
2045
+ }
2046
+ if (failed.length > 0) {
2047
+ lines.push("");
2048
+ lines.push("## Failed");
2049
+ for (const r of failed) {
2050
+ lines.push(`- ${r.name} [${r.collection}]: _${r.error}_`);
2051
+ }
2052
+ lines.push("");
2053
+ lines.push(`_If failed > 0, inspect \`failedEntries\` in the structured response and retry individually._`);
2054
+ }
2055
+ const entryIds = created.map((r) => r.entryId);
2056
+ if (entryIds.length > 0) {
2057
+ lines.push("");
2058
+ lines.push("## Next Steps");
2059
+ lines.push(`- **Connect:** Run \`graph action=suggest\` on key entries to build the knowledge graph`);
2060
+ lines.push(`- **Commit:** Use \`commit-entry\` to promote drafts to SSOT`);
2061
+ lines.push(`- **Quality:** Run \`quality action=check\` on individual entries to assess completeness`);
2062
+ }
2063
+ return {
2064
+ content: [{ type: "text", text: lines.join("\n") }],
2065
+ structuredContent: {
2066
+ captured: created.map((r) => ({ entryId: r.entryId, collection: r.collection, name: r.name })),
2067
+ total: created.length,
2068
+ failed: failed.length,
2069
+ // failedEntries provides enough detail for the agent to retry individually.
2070
+ // Only populated when failures occurred — avoids noise in the happy path.
2071
+ ...failed.length > 0 && {
2072
+ failedEntries: failed.map((r, i) => ({
2073
+ index: results.indexOf(r),
2074
+ collection: r.collection,
2075
+ name: r.name,
2076
+ error: r.error ?? "unknown error"
2077
+ }))
2078
+ }
2079
+ }
2080
+ };
2081
+ }
2082
+ );
2083
+ trackWriteTool(batchCaptureTool);
2084
+ }
2085
+ var STOP_WORDS = /* @__PURE__ */ new Set([
2086
+ "the",
2087
+ "and",
2088
+ "for",
2089
+ "are",
2090
+ "but",
2091
+ "not",
2092
+ "you",
2093
+ "all",
2094
+ "can",
2095
+ "has",
2096
+ "her",
2097
+ "was",
2098
+ "one",
2099
+ "our",
2100
+ "out",
2101
+ "day",
2102
+ "had",
2103
+ "hot",
2104
+ "how",
2105
+ "its",
2106
+ "may",
2107
+ "new",
2108
+ "now",
2109
+ "old",
2110
+ "see",
2111
+ "way",
2112
+ "who",
2113
+ "did",
2114
+ "get",
2115
+ "let",
2116
+ "say",
2117
+ "she",
2118
+ "too",
2119
+ "use",
2120
+ "from",
2121
+ "have",
2122
+ "been",
2123
+ "each",
2124
+ "that",
2125
+ "this",
2126
+ "with",
2127
+ "will",
2128
+ "they",
2129
+ "what",
2130
+ "when",
2131
+ "make",
2132
+ "like",
2133
+ "long",
2134
+ "look",
2135
+ "many",
2136
+ "some",
2137
+ "them",
2138
+ "than",
2139
+ "most",
2140
+ "only",
2141
+ "over",
2142
+ "such",
2143
+ "into",
2144
+ "also",
2145
+ "back",
2146
+ "just",
2147
+ "much",
2148
+ "must",
2149
+ "name",
2150
+ "very",
2151
+ "your",
2152
+ "after",
2153
+ "which",
2154
+ "their",
2155
+ "about",
2156
+ "would",
2157
+ "there",
2158
+ "should",
2159
+ "could",
2160
+ "other",
2161
+ "these",
2162
+ "first",
2163
+ "being",
2164
+ "those",
2165
+ "still",
2166
+ "where"
2167
+ ]);
2168
+ function tokenizeText(input) {
2169
+ return input.toLowerCase().replace(/[^\p{L}\p{N}\s]+/gu, " ").split(/\s+/).filter(Boolean);
2170
+ }
2171
+ async function runContradictionCheck(name, description) {
2172
+ const warnings = [];
2173
+ try {
2174
+ const keyTerms = tokenizeText(`${name} ${description}`).filter((w) => w.length >= 4 && !STOP_WORDS.has(w)).slice(0, 8);
2175
+ if (keyTerms.length === 0) return warnings;
2176
+ const searchQuery = keyTerms.slice(0, 5).join(" ");
2177
+ const [govResults, archResults] = await Promise.all([
2178
+ mcpQuery("chain.searchEntries", { query: searchQuery, collectionSlug: "business-rules" }),
2179
+ mcpQuery("chain.searchEntries", { query: searchQuery, collectionSlug: "architecture" })
2180
+ ]);
2181
+ const allGov = [...govResults ?? [], ...archResults ?? []].slice(0, 5);
2182
+ for (const entry of allGov) {
2183
+ const entryTokens = new Set(tokenizeText(`${entry.name} ${entry.data?.description ?? ""}`));
2184
+ const matched = keyTerms.filter((t) => entryTokens.has(t));
2185
+ if (matched.length < 3) continue;
2186
+ let governsCount = 0;
2187
+ try {
2188
+ const relations = await mcpQuery("chain.listEntryRelations", {
2189
+ entryId: entry.entryId
2190
+ });
2191
+ governsCount = (relations ?? []).filter((r) => r.type === "governs").length;
2192
+ } catch {
2193
+ }
2194
+ warnings.push({
2195
+ entryId: entry.entryId ?? "",
2196
+ name: entry.name,
2197
+ collection: entry.collectionSlug ?? "",
2198
+ governsCount
2199
+ });
2200
+ }
2201
+ } catch {
2202
+ }
2203
+ return warnings;
2204
+ }
2205
+ function formatRubricCoaching(result) {
2206
+ const { verdict, rogerMartin } = result;
2207
+ if (!verdict || verdict.criteria.length === 0) return "";
2208
+ const lines = ["## Semantic Quality"];
2209
+ const failed = (verdict.criteria ?? []).filter((c) => !c.passed);
2210
+ const total = verdict.criteria?.length ?? 0;
2211
+ const passedCount = total - failed.length;
2212
+ if (verdict.passed) {
2213
+ lines.push(`All ${total} rubric criteria pass for \`${verdict.canonicalKey}\` (${verdict.tier} tier).`);
2214
+ } else {
2215
+ lines.push(`${passedCount}/${total} criteria pass for \`${verdict.canonicalKey}\` (${verdict.tier} tier)`);
2216
+ lines.push("");
2217
+ for (const c of verdict.criteria) {
2218
+ const icon = c.passed ? "[x]" : "[ ]";
2219
+ const extra = c.passed ? "" : ` \u2014 ${c.hint}`;
2220
+ lines.push(`${icon} ${c.id}${extra}`);
2221
+ }
2222
+ if (verdict.weakest) {
2223
+ lines.push("");
2224
+ lines.push(`**Coaching hint:** ${verdict.weakest.hint}`);
2225
+ lines.push(`_Question to consider:_ ${verdict.weakest.questionTemplate}`);
2226
+ }
2227
+ }
2228
+ if (rogerMartin) {
2229
+ lines.push("");
2230
+ lines.push("### Roger Martin Test");
2231
+ if (rogerMartin.isStrategicChoice) {
2232
+ lines.push("This principle passes \u2014 the opposite is a reasonable strategic choice.");
2233
+ } else {
2234
+ lines.push(`This principle may not be a strategic choice. ${rogerMartin.reasoning}`);
2235
+ if (rogerMartin.suggestion) {
2236
+ lines.push(`_Suggestion:_ ${rogerMartin.suggestion}`);
2237
+ }
2238
+ }
2239
+ }
2240
+ return lines.join("\n");
2241
+ }
2242
+ function formatRubricVerdictSection(verdict) {
2243
+ if (!verdict || !verdict.criteria || verdict.criteria.length === 0) return "";
2244
+ const lines = ["## Semantic Quality"];
2245
+ const failed = verdict.criteria.filter((c) => !c.passed);
2246
+ const total = verdict.criteria.length;
2247
+ const passedCount = total - failed.length;
2248
+ const durationSuffix = verdict.llmDurationMs ? ` in ${(verdict.llmDurationMs / 1e3).toFixed(1)}s` : "";
2249
+ const statusNote = verdict.llmStatus === "pending" ? " \u2014 LLM evaluation in progress..." : verdict.llmStatus === "failed" ? ` \u2014 LLM evaluation failed${verdict.llmError ? `: ${verdict.llmError}` : ""}, showing heuristic results` : verdict.source === "llm" && durationSuffix ? ` \u2014 evaluated${durationSuffix}` : "";
2250
+ if (failed.length === 0) {
2251
+ lines.push(`All ${total} rubric criteria pass for \`${verdict.canonicalKey}\` (${verdict.tier} tier, ${verdict.source} evaluation).${statusNote}`);
2252
+ } else {
2253
+ lines.push(`${passedCount}/${total} criteria pass for \`${verdict.canonicalKey}\` (${verdict.tier} tier, ${verdict.source} evaluation)${statusNote}`);
2254
+ lines.push("");
2255
+ for (const c of verdict.criteria) {
2256
+ const icon = c.passed ? "[x]" : "[ ]";
2257
+ const extra = c.passed ? "" : ` \u2014 ${c.hint}`;
2258
+ lines.push(`${icon} ${c.id}${extra}`);
2259
+ }
2260
+ if (verdict.weakest) {
2261
+ lines.push("");
2262
+ lines.push(`**Top improvement:** ${verdict.weakest.hint}`);
2263
+ }
2264
+ }
2265
+ if (verdict.rogerMartin) {
2266
+ const rm = verdict.rogerMartin;
2267
+ lines.push("");
2268
+ lines.push("### Roger Martin Test");
2269
+ if (rm.isStrategicChoice) {
2270
+ lines.push(`This is a real strategic choice \u2014 the opposite is reasonable. ${rm.reasoning}`);
2271
+ } else {
2272
+ lines.push(`This may not be a strategic choice. ${rm.reasoning}`);
2273
+ if (rm.suggestion) {
2274
+ lines.push(`_Suggestion:_ ${rm.suggestion}`);
2275
+ }
2276
+ }
2277
+ }
2278
+ return lines.join("\n");
2279
+ }
2280
+
2281
+ export {
2282
+ runWithAuth,
2283
+ runWithToolContext,
2284
+ getAgentSessionId,
2285
+ isSessionOriented,
2286
+ setSessionOriented,
2287
+ getApiKeyScope,
2288
+ startAgentSession,
2289
+ closeAgentSession,
2290
+ orphanAgentSession,
2291
+ recordSessionActivity,
2292
+ bootstrap,
2293
+ bootstrapHttp,
2294
+ getAuditLog,
2295
+ mcpCall,
2296
+ getWorkspaceId,
2297
+ getWorkspaceContext,
2298
+ mcpQuery,
2299
+ mcpMutation,
2300
+ requireActiveSession,
2301
+ requireWriteAccess,
2302
+ recoverSessionState,
2303
+ extractPreview,
2304
+ translateStaleToolNames,
2305
+ initToolSurface,
2306
+ trackWriteTool,
2307
+ initFeatureFlags,
2308
+ CLASSIFIER_AUTO_ROUTE_THRESHOLD,
2309
+ STARTER_COLLECTIONS,
2310
+ classifyStarterCollection,
2311
+ isClassificationAmbiguous,
2312
+ formatQualityReport,
2313
+ checkEntryQuality,
2314
+ captureSchema,
2315
+ batchCaptureSchema,
2316
+ captureClassifierSchema,
2317
+ captureOutputSchema,
2318
+ batchCaptureOutputSchema,
2319
+ registerSmartCaptureTools,
2320
+ runContradictionCheck,
2321
+ formatRubricCoaching,
2322
+ formatRubricVerdictSection
2323
+ };
2324
+ //# sourceMappingURL=chunk-M264FY2V.js.map