@productbrain/mcp 0.0.1-beta.6 → 0.0.1-beta.60

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,3029 @@
1
+ import {
2
+ MCP_NPX_PACKAGE,
3
+ trackCaptureClassifierAutoRouted,
4
+ trackCaptureClassifierEvaluated,
5
+ trackCaptureClassifierFallback,
6
+ trackQualityVerdict,
7
+ trackToolCall
8
+ } from "./chunk-MRIO53BY.js";
9
+
10
+ // src/tools/smart-capture.ts
11
+ import { z as z2 } from "zod";
12
+
13
+ // src/client.ts
14
+ import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
15
+
16
+ // src/auth.ts
17
+ import { AsyncLocalStorage } from "async_hooks";
18
+ var requestStore = new AsyncLocalStorage();
19
+ function runWithAuth(auth, fn) {
20
+ return requestStore.run(auth, fn);
21
+ }
22
+ function getRequestApiKey() {
23
+ return requestStore.getStore()?.apiKey;
24
+ }
25
+ var SESSION_TTL_MS = 30 * 60 * 1e3;
26
+ var MAX_KEYS = 100;
27
+ var keyStateMap = /* @__PURE__ */ new Map();
28
+ function newKeyState() {
29
+ return {
30
+ workspaceId: null,
31
+ workspaceSlug: null,
32
+ workspaceName: null,
33
+ workspaceCreatedAt: null,
34
+ workspaceGovernanceMode: null,
35
+ agentSessionId: null,
36
+ apiKeyId: null,
37
+ apiKeyScope: "readwrite",
38
+ sessionOriented: false,
39
+ sessionClosed: false,
40
+ lastAccess: Date.now()
41
+ };
42
+ }
43
+ function getKeyState(apiKey) {
44
+ let s = keyStateMap.get(apiKey);
45
+ if (!s) {
46
+ s = newKeyState();
47
+ keyStateMap.set(apiKey, s);
48
+ evictStale();
49
+ }
50
+ s.lastAccess = Date.now();
51
+ return s;
52
+ }
53
+ function evictStale() {
54
+ if (keyStateMap.size <= MAX_KEYS) return;
55
+ const now = Date.now();
56
+ for (const [key, s] of keyStateMap) {
57
+ if (now - s.lastAccess > SESSION_TTL_MS) keyStateMap.delete(key);
58
+ }
59
+ if (keyStateMap.size > MAX_KEYS) {
60
+ const sorted = [...keyStateMap.entries()].sort((a, b) => a[1].lastAccess - b[1].lastAccess);
61
+ for (let i = 0; i < sorted.length - MAX_KEYS; i++) {
62
+ keyStateMap.delete(sorted[i][0]);
63
+ }
64
+ }
65
+ }
66
+
67
+ // src/client.ts
68
+ var toolContextStore = new AsyncLocalStorage2();
69
+ function runWithToolContext(ctx, fn) {
70
+ return toolContextStore.run(ctx, fn);
71
+ }
72
+ function getToolContext() {
73
+ return toolContextStore.getStore() ?? null;
74
+ }
75
+ var DEFAULT_CLOUD_URL = "https://trustworthy-kangaroo-277.convex.site";
76
+ var CACHE_TTL_MS = 6e4;
77
+ var CACHEABLE_FNS = [
78
+ "chain.getOrientEntries",
79
+ "chain.gatherContext",
80
+ "chain.graphGatherContext",
81
+ "chain.taskAwareGatherContext",
82
+ "chain.journeyAwareGatherContext",
83
+ "chain.assembleBuildContext"
84
+ ];
85
+ function isCacheable(fn) {
86
+ return CACHEABLE_FNS.includes(fn);
87
+ }
88
+ var READ_PATTERN = /^(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;
89
+ function isWrite(fn) {
90
+ if (fn.startsWith("agent.")) return false;
91
+ return !READ_PATTERN.test(fn);
92
+ }
93
+ var readCache = /* @__PURE__ */ new Map();
94
+ function cacheKey(fn, args) {
95
+ return `${fn}:${JSON.stringify(args)}`;
96
+ }
97
+ function getCached(fn, args) {
98
+ if (!isCacheable(fn)) return void 0;
99
+ const key = cacheKey(fn, args);
100
+ const entry = readCache.get(key);
101
+ if (!entry || Date.now() > entry.expiresAt) {
102
+ if (entry) readCache.delete(key);
103
+ return void 0;
104
+ }
105
+ return entry.data;
106
+ }
107
+ function setCached(fn, args, data) {
108
+ if (!isCacheable(fn)) return;
109
+ const key = cacheKey(fn, args);
110
+ readCache.set(key, { data, expiresAt: Date.now() + CACHE_TTL_MS });
111
+ }
112
+ function invalidateReadCache() {
113
+ readCache.clear();
114
+ }
115
+ var _stdioState = {
116
+ workspaceId: null,
117
+ workspaceSlug: null,
118
+ workspaceName: null,
119
+ workspaceCreatedAt: null,
120
+ workspaceGovernanceMode: null,
121
+ agentSessionId: null,
122
+ apiKeyId: null,
123
+ apiKeyScope: "readwrite",
124
+ sessionOriented: false,
125
+ sessionClosed: false,
126
+ lastAccess: 0
127
+ };
128
+ function state() {
129
+ const reqKey = getRequestApiKey();
130
+ if (reqKey) return getKeyState(reqKey);
131
+ return _stdioState;
132
+ }
133
+ function getActiveApiKey() {
134
+ const fromRequest = getRequestApiKey();
135
+ if (fromRequest) return fromRequest;
136
+ const fromEnv = process.env.PRODUCTBRAIN_API_KEY;
137
+ if (!fromEnv) throw new Error("No API key available \u2014 set PRODUCTBRAIN_API_KEY or provide Bearer token");
138
+ return fromEnv;
139
+ }
140
+ function getAgentSessionId() {
141
+ return state().agentSessionId;
142
+ }
143
+ function isSessionOriented() {
144
+ return state().sessionOriented;
145
+ }
146
+ function setSessionOriented(value) {
147
+ state().sessionOriented = value;
148
+ }
149
+ function getApiKeyScope() {
150
+ return state().apiKeyScope;
151
+ }
152
+ async function startAgentSession() {
153
+ const workspaceId = await getWorkspaceId();
154
+ const s = state();
155
+ if (!s.apiKeyId) {
156
+ throw new Error("Cannot start session: API key ID not resolved. Ensure workspace resolution completed.");
157
+ }
158
+ const result = await mcpCall("agent.startSession", {
159
+ workspaceId,
160
+ apiKeyId: s.apiKeyId
161
+ });
162
+ if (s.agentSessionId) {
163
+ resetTouchThrottle(s.agentSessionId);
164
+ }
165
+ s.agentSessionId = result.sessionId;
166
+ s.apiKeyScope = result.toolsScope;
167
+ s.sessionOriented = false;
168
+ s.sessionClosed = false;
169
+ resetTouchThrottle(result.sessionId);
170
+ return result;
171
+ }
172
+ async function closeAgentSession() {
173
+ const s = state();
174
+ if (!s.agentSessionId) return;
175
+ const sessionId = s.agentSessionId;
176
+ try {
177
+ await mcpCall("agent.closeSession", {
178
+ sessionId,
179
+ status: "closed"
180
+ });
181
+ } finally {
182
+ resetTouchThrottle(sessionId);
183
+ s.sessionClosed = true;
184
+ s.agentSessionId = null;
185
+ s.sessionOriented = false;
186
+ }
187
+ }
188
+ async function orphanAgentSession() {
189
+ const s = state();
190
+ if (!s.agentSessionId) return;
191
+ const sessionId = s.agentSessionId;
192
+ try {
193
+ await mcpCall("agent.closeSession", {
194
+ sessionId,
195
+ status: "orphaned"
196
+ });
197
+ } catch {
198
+ } finally {
199
+ resetTouchThrottle(sessionId);
200
+ s.agentSessionId = null;
201
+ s.sessionOriented = false;
202
+ }
203
+ }
204
+ var _lastTouchAtBySession = /* @__PURE__ */ new Map();
205
+ var TOUCH_THROTTLE_MS = 5e3;
206
+ function touchSessionActivity() {
207
+ const s = state();
208
+ const sessionId = s.agentSessionId;
209
+ if (!sessionId) return;
210
+ const now = Date.now();
211
+ const lastTouchAt = _lastTouchAtBySession.get(sessionId) ?? 0;
212
+ if (now - lastTouchAt < TOUCH_THROTTLE_MS) return;
213
+ _lastTouchAtBySession.set(sessionId, now);
214
+ mcpCall("agent.touchSession", {
215
+ sessionId
216
+ }).catch(() => {
217
+ });
218
+ }
219
+ function resetTouchThrottle(sessionId) {
220
+ if (sessionId) {
221
+ _lastTouchAtBySession.delete(sessionId);
222
+ return;
223
+ }
224
+ _lastTouchAtBySession.clear();
225
+ }
226
+ async function recordSessionActivity(activity) {
227
+ const s = state();
228
+ if (!s.agentSessionId) return;
229
+ try {
230
+ await mcpCall("agent.recordActivity", {
231
+ sessionId: s.agentSessionId,
232
+ ...activity
233
+ });
234
+ } catch {
235
+ }
236
+ }
237
+ var AUDIT_BUFFER_SIZE = 50;
238
+ var auditBuffer = [];
239
+ function bootstrap() {
240
+ process.env.CONVEX_SITE_URL ??= process.env.PRODUCTBRAIN_URL ?? DEFAULT_CLOUD_URL;
241
+ const pbKey = process.env.PRODUCTBRAIN_API_KEY;
242
+ if (!pbKey?.startsWith("pb_sk_")) {
243
+ process.stderr.write(
244
+ "[MCP] Warning: PRODUCTBRAIN_API_KEY is not set or invalid. Tool calls will fail until a valid key is provided.\n"
245
+ );
246
+ }
247
+ }
248
+ function bootstrapHttp() {
249
+ process.env.CONVEX_SITE_URL ??= process.env.PRODUCTBRAIN_URL ?? DEFAULT_CLOUD_URL;
250
+ }
251
+ function getEnv(key) {
252
+ const value = process.env[key];
253
+ if (!value) throw new Error(`${key} environment variable is required`);
254
+ return value;
255
+ }
256
+ function shouldLogAudit(status) {
257
+ return status === "error" || process.env.MCP_DEBUG === "1";
258
+ }
259
+ function audit(fn, status, durationMs, errorMsg) {
260
+ const ts = (/* @__PURE__ */ new Date()).toISOString();
261
+ const workspace = state().workspaceId ?? "unresolved";
262
+ const toolCtx = getToolContext();
263
+ const entry = { ts, fn, workspace, status, durationMs };
264
+ if (errorMsg) entry.error = errorMsg;
265
+ if (toolCtx) entry.toolContext = toolCtx;
266
+ auditBuffer.push(entry);
267
+ if (auditBuffer.length > AUDIT_BUFFER_SIZE) auditBuffer.shift();
268
+ trackToolCall(fn, status, durationMs, workspace, errorMsg);
269
+ if (!shouldLogAudit(status)) return;
270
+ const base = `[MCP-AUDIT] ${ts} fn=${fn} workspace=${workspace} status=${status} duration=${durationMs}ms`;
271
+ if (status === "error" && errorMsg) {
272
+ process.stderr.write(`${base} error=${JSON.stringify(errorMsg)}
273
+ `);
274
+ } else {
275
+ process.stderr.write(`${base}
276
+ `);
277
+ }
278
+ }
279
+ function getAuditLog() {
280
+ return auditBuffer;
281
+ }
282
+ async function mcpCall(fn, args = {}) {
283
+ const cached = getCached(fn, args);
284
+ if (cached !== void 0) {
285
+ return cached;
286
+ }
287
+ const siteUrl = getEnv("CONVEX_SITE_URL").replace(/\/$/, "");
288
+ const apiKey = getActiveApiKey();
289
+ const start = Date.now();
290
+ let res;
291
+ try {
292
+ res = await fetch(`${siteUrl}/api/mcp`, {
293
+ method: "POST",
294
+ signal: AbortSignal.timeout(1e4),
295
+ headers: {
296
+ "Content-Type": "application/json",
297
+ Authorization: `Bearer ${apiKey}`
298
+ },
299
+ body: JSON.stringify({ fn, args })
300
+ });
301
+ } catch (err) {
302
+ audit(fn, "error", Date.now() - start, err.message);
303
+ throw new Error(`MCP call "${fn}" network error: ${err.message}`);
304
+ }
305
+ const json = await res.json();
306
+ if (!res.ok || json.error) {
307
+ audit(fn, "error", Date.now() - start, json.error);
308
+ throw new Error(`MCP call "${fn}" failed (${res.status}): ${json.error ?? "unknown error"}`);
309
+ }
310
+ audit(fn, "ok", Date.now() - start);
311
+ const data = json.data;
312
+ if (isWrite(fn)) {
313
+ invalidateReadCache();
314
+ } else {
315
+ setCached(fn, args, data);
316
+ }
317
+ const s = state();
318
+ const TOUCH_EXCLUDED = /* @__PURE__ */ new Set([
319
+ "agent.touchSession",
320
+ "agent.startSession",
321
+ "agent.markOriented",
322
+ "agent.recordActivity",
323
+ "agent.recordWrapup",
324
+ "agent.closeSession"
325
+ ]);
326
+ if (s.agentSessionId && !TOUCH_EXCLUDED.has(fn)) {
327
+ touchSessionActivity();
328
+ }
329
+ return data;
330
+ }
331
+ var resolveInFlightMap = /* @__PURE__ */ new Map();
332
+ async function getWorkspaceId() {
333
+ const s = state();
334
+ if (s.workspaceId) return s.workspaceId;
335
+ const apiKey = getActiveApiKey();
336
+ const existing = resolveInFlightMap.get(apiKey);
337
+ if (existing) return existing;
338
+ const promise = resolveWorkspaceWithRetry().finally(() => resolveInFlightMap.delete(apiKey));
339
+ resolveInFlightMap.set(apiKey, promise);
340
+ return promise;
341
+ }
342
+ async function resolveWorkspaceWithRetry(maxRetries = 2) {
343
+ let lastError = null;
344
+ for (let attempt = 0; attempt <= maxRetries; attempt++) {
345
+ try {
346
+ const workspace = await mcpCall("resolveWorkspace", {});
347
+ if (!workspace) {
348
+ throw new Error(
349
+ `API key is valid but no workspace is associated. Run \`npx ${MCP_NPX_PACKAGE} setup\` or regenerate your key.`
350
+ );
351
+ }
352
+ const s = state();
353
+ s.workspaceId = workspace._id;
354
+ s.workspaceSlug = workspace.slug;
355
+ s.workspaceName = workspace.name;
356
+ s.workspaceCreatedAt = workspace.createdAt ?? null;
357
+ s.workspaceGovernanceMode = workspace.governanceMode ?? "open";
358
+ if (workspace.keyScope) s.apiKeyScope = workspace.keyScope;
359
+ if (workspace.keyId) s.apiKeyId = workspace.keyId;
360
+ return s.workspaceId;
361
+ } catch (err) {
362
+ lastError = err;
363
+ const isTransient = /network error|fetch failed|ECONNREFUSED|ETIMEDOUT/i.test(err.message);
364
+ if (!isTransient || attempt === maxRetries) break;
365
+ const delay = 1e3 * (attempt + 1);
366
+ process.stderr.write(
367
+ `[MCP] Workspace resolution failed (attempt ${attempt + 1}/${maxRetries + 1}), retrying in ${delay}ms...
368
+ `
369
+ );
370
+ await new Promise((r) => setTimeout(r, delay));
371
+ }
372
+ }
373
+ throw lastError;
374
+ }
375
+ async function getWorkspaceContext() {
376
+ const workspaceId = await getWorkspaceId();
377
+ const s = state();
378
+ return {
379
+ workspaceId,
380
+ workspaceSlug: s.workspaceSlug ?? "unknown",
381
+ workspaceName: s.workspaceName ?? "unknown",
382
+ createdAt: s.workspaceCreatedAt,
383
+ governanceMode: s.workspaceGovernanceMode ?? "open"
384
+ };
385
+ }
386
+ async function mcpQuery(fn, args = {}) {
387
+ const workspaceId = await getWorkspaceId();
388
+ return mcpCall(fn, { ...args, workspaceId });
389
+ }
390
+ async function mcpMutation(fn, args = {}) {
391
+ const workspaceId = await getWorkspaceId();
392
+ return mcpCall(fn, { ...args, workspaceId });
393
+ }
394
+ function requireActiveSession() {
395
+ const s = state();
396
+ if (!s.agentSessionId) {
397
+ throw new Error(
398
+ "Active session required (SOS-iszqu7). Call `session action=start` then `orient` first."
399
+ );
400
+ }
401
+ if (s.sessionClosed) {
402
+ throw new Error(
403
+ "Session has been closed (SOS-iszqu7). Start a new session with `session action=start`."
404
+ );
405
+ }
406
+ if (!s.sessionOriented) {
407
+ throw new Error(
408
+ "Orientation required before accessing build context (SOS-iszqu7). Call `orient` first."
409
+ );
410
+ }
411
+ }
412
+ function requireWriteAccess() {
413
+ const s = state();
414
+ if (!s.agentSessionId) {
415
+ throw new Error(
416
+ "Agent session required for write operations. Call `session action=start` first."
417
+ );
418
+ }
419
+ if (s.sessionClosed) {
420
+ throw new Error(
421
+ "Agent session has been closed. Write tools are no longer available."
422
+ );
423
+ }
424
+ if (!s.sessionOriented) {
425
+ throw new Error(
426
+ "Orientation required before writing to the Chain. Call 'orient' first."
427
+ );
428
+ }
429
+ if (s.apiKeyScope === "read") {
430
+ throw new Error(
431
+ "This API key has read-only scope. Write tools are not available."
432
+ );
433
+ }
434
+ }
435
+ async function recoverSessionState() {
436
+ const s = state();
437
+ if (!s.workspaceId) return;
438
+ try {
439
+ const session = await mcpCall("agent.getActiveSession", { workspaceId: s.workspaceId });
440
+ if (session && session.status === "active") {
441
+ s.agentSessionId = session._id;
442
+ s.sessionOriented = session.oriented;
443
+ s.apiKeyScope = session.toolsScope;
444
+ s.sessionClosed = false;
445
+ }
446
+ } catch {
447
+ }
448
+ }
449
+
450
+ // src/tools/knowledge-helpers.ts
451
+ var EPISTEMIC_COLLECTIONS = /* @__PURE__ */ new Set(["insights", "assumptions"]);
452
+ function deriveEpistemicStatus(entry) {
453
+ const coll = entry.collectionName?.toLowerCase();
454
+ if (!coll || !EPISTEMIC_COLLECTIONS.has(coll)) return null;
455
+ const relations = entry.relations ?? [];
456
+ const hasValidates = relations.some(
457
+ (r) => r.type === "validates" && r.direction === "incoming"
458
+ );
459
+ const hasInvalidates = relations.some(
460
+ (r) => r.type === "invalidates" && r.direction === "incoming"
461
+ );
462
+ const evidenceCount = relations.filter(
463
+ (r) => (r.type === "validates" || r.type === "invalidates") && r.direction === "incoming"
464
+ ).length;
465
+ if (coll === "assumptions") {
466
+ const ws2 = entry.workflowStatus;
467
+ if (ws2 === "invalidated" || hasInvalidates) {
468
+ return { level: "invalidated", reason: "Disproved by linked counter-evidence" };
469
+ }
470
+ if (ws2 === "validated" || hasValidates && ws2 !== "untested") {
471
+ return { level: "validated", reason: `${evidenceCount} evidence link${evidenceCount !== 1 ? "s" : ""}` };
472
+ }
473
+ if (ws2 === "testing") {
474
+ return { level: "testing", reason: "Experiment in progress" };
475
+ }
476
+ return { level: "untested", reason: "No evidence linked", action: 'Link evidence via `relations action=create type="validates"`' };
477
+ }
478
+ const ws = entry.workflowStatus;
479
+ if (ws === "validated" && hasValidates) {
480
+ return { level: "validated", reason: `${evidenceCount} evidence link${evidenceCount !== 1 ? "s" : ""}` };
481
+ }
482
+ if (ws === "evidenced" || hasValidates) {
483
+ return { level: "evidenced", reason: `${evidenceCount} evidence link${evidenceCount !== 1 ? "s" : ""}` };
484
+ }
485
+ return {
486
+ level: "hypothesis",
487
+ reason: "No linked evidence",
488
+ action: 'Link proof via `relations action=create type="validates"`'
489
+ };
490
+ }
491
+ function formatEpistemicLine(es) {
492
+ const icon = es.level === "validated" ? "\u2713" : es.level === "evidenced" ? "\u25CE" : es.level === "hypothesis" ? "\u25B3" : es.level === "untested" ? "?" : es.level === "testing" ? "\u25CE" : "\u2715";
493
+ const suffix = es.action ? ` ${es.action}` : "";
494
+ return `**Confidence:** ${icon} ${es.level} \u2014 ${es.reason}.${suffix}`;
495
+ }
496
+ function toEpistemicInput(entry) {
497
+ return {
498
+ collectionName: typeof entry.collectionName === "string" ? entry.collectionName : void 0,
499
+ workflowStatus: typeof entry.workflowStatus === "string" ? entry.workflowStatus : void 0,
500
+ relations: Array.isArray(entry.relations) ? entry.relations.map((r) => ({ type: r.type, direction: r.direction })) : void 0
501
+ };
502
+ }
503
+ function extractPreview(data, maxLen) {
504
+ if (!data || typeof data !== "object") return "";
505
+ const d = data;
506
+ const raw = d.description ?? d.canonical ?? d.detail ?? d.rule ?? "";
507
+ if (typeof raw !== "string" || !raw) return "";
508
+ return raw.length > maxLen ? raw.substring(0, maxLen) + "..." : raw;
509
+ }
510
+ var TOOL_NAME_MIGRATIONS = /* @__PURE__ */ new Map([
511
+ ["list-entries", 'entries action="list"'],
512
+ ["get-entry", 'entries action="get"'],
513
+ ["batch-get", 'entries action="batch"'],
514
+ ["search", 'entries action="search"'],
515
+ ["relate-entries", 'relations action="create"'],
516
+ ["batch-relate", 'relations action="batch-create"'],
517
+ ["find-related", 'graph action="find"'],
518
+ ["suggest-links", 'graph action="suggest"'],
519
+ ["gather-context", 'context action="gather"'],
520
+ ["get-build-context", 'context action="build"'],
521
+ ["list-collections", 'collections action="list"'],
522
+ ["create-collection", 'collections action="create"'],
523
+ ["update-collection", 'collections action="update"'],
524
+ ["agent-start", 'session action="start"'],
525
+ ["agent-close", 'session action="close"'],
526
+ ["agent-status", 'session action="status"'],
527
+ ["workspace-status", 'health action="status"'],
528
+ ["mcp-audit", 'health action="audit"'],
529
+ ["quality-check", 'quality action="check"'],
530
+ ["re-evaluate", 'quality action="re-evaluate"'],
531
+ ["list-workflows", 'workflows action="list"'],
532
+ ["workflow-checkpoint", 'workflows action="checkpoint"'],
533
+ ["wrapup", "session-wrapup"],
534
+ ["finish", "session-wrapup"]
535
+ ]);
536
+ function translateStaleToolNames(text) {
537
+ const found = [];
538
+ for (const [old, current] of TOOL_NAME_MIGRATIONS) {
539
+ const pattern = new RegExp(`\\b${old.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\b`, "g");
540
+ if (pattern.test(text)) {
541
+ found.push(`\`${old}\` \u2192 \`${current}\``);
542
+ }
543
+ }
544
+ if (found.length === 0) return null;
545
+ return `
546
+
547
+ ---
548
+ _Tool name translations (these references use deprecated names):_
549
+ ${found.map((f) => `- ${f}`).join("\n")}`;
550
+ }
551
+
552
+ // src/tool-surface.ts
553
+ function initToolSurface(_server) {
554
+ }
555
+ function trackWriteTool(_tool) {
556
+ }
557
+
558
+ // src/featureFlags.ts
559
+ import { PostHog } from "posthog-node";
560
+ var client = null;
561
+ var LOCAL_OVERRIDES = {
562
+ // Uncomment for local dev without PostHog:
563
+ // "workspace-full-surface": false,
564
+ // "chainwork-enabled": true,
565
+ // "active-intelligence-shaping": true, // ENT-59: Opus-powered investigation during shaping
566
+ // "capture-without-thinking": true, // BET-73: collection-optional capture classifier
567
+ };
568
+ function initFeatureFlags(posthogClient) {
569
+ if (posthogClient) {
570
+ client = posthogClient;
571
+ return;
572
+ }
573
+ const apiKey = process.env.POSTHOG_MCP_KEY || process.env.PUBLIC_POSTHOG_KEY;
574
+ if (!apiKey) {
575
+ client = null;
576
+ return;
577
+ }
578
+ client = new PostHog(apiKey, {
579
+ host: process.env.PUBLIC_POSTHOG_HOST || "https://eu.i.posthog.com",
580
+ flushAt: 1,
581
+ flushInterval: 5e3,
582
+ featureFlagsPollingInterval: 3e4
583
+ });
584
+ }
585
+ async function isFeatureEnabled(flag, workspaceId, workspaceSlug) {
586
+ if (process.env.FEATURE_KILL_SWITCH === "true") return false;
587
+ if (flag in LOCAL_OVERRIDES) return LOCAL_OVERRIDES[flag];
588
+ if (!client) return false;
589
+ try {
590
+ const primary = await client.isFeatureEnabled(flag, workspaceId, {
591
+ groups: { workspace: workspaceId },
592
+ groupProperties: {
593
+ workspace: {
594
+ workspace_id: workspaceId,
595
+ slug: workspaceSlug ?? ""
596
+ }
597
+ }
598
+ });
599
+ if (primary) return true;
600
+ if (workspaceSlug && workspaceSlug !== workspaceId) {
601
+ const secondary = await client.isFeatureEnabled(flag, workspaceSlug, {
602
+ groups: { workspace: workspaceSlug },
603
+ groupProperties: {
604
+ workspace: {
605
+ workspace_id: workspaceId,
606
+ slug: workspaceSlug
607
+ }
608
+ }
609
+ });
610
+ return secondary ?? false;
611
+ }
612
+ return primary ?? false;
613
+ } catch {
614
+ return false;
615
+ }
616
+ }
617
+
618
+ // src/lib/collectionRoutingClassifier.ts
619
+ var CLASSIFIER_AUTO_ROUTE_THRESHOLD = 70;
620
+ var CLASSIFIER_AMBIGUITY_MARGIN = 15;
621
+ var CLASSIFIABLE_COLLECTIONS = [
622
+ "decisions",
623
+ "tensions",
624
+ "glossary",
625
+ "insights",
626
+ "bets",
627
+ "features",
628
+ "architecture",
629
+ "business-rules",
630
+ "tracking-events",
631
+ "landscape",
632
+ "standards",
633
+ "principles",
634
+ "assumptions"
635
+ ];
636
+ var SIGNAL_WEIGHT = 10;
637
+ var MIN_SCORE_FLOOR = 10;
638
+ var MAX_MATCHES_PER_SIGNAL = 2;
639
+ var MAX_REASON_COUNT = 3;
640
+ var ENTRY_ID_PATTERN = /\b[A-Z]{2,}-\d+\b/g;
641
+ var COLLECTION_SIGNALS = {
642
+ decisions: [
643
+ "decide",
644
+ "decision",
645
+ "chose",
646
+ "chosen",
647
+ "choice",
648
+ "resolved",
649
+ "we will",
650
+ "we should",
651
+ "approved",
652
+ "replaces",
653
+ "instead of",
654
+ "go with",
655
+ "criteria",
656
+ "adopted",
657
+ "reposition",
658
+ "scoring framework",
659
+ "review"
660
+ ],
661
+ tensions: [
662
+ "problem",
663
+ "issue",
664
+ "blocked",
665
+ "blocker",
666
+ "friction",
667
+ "pain",
668
+ "bottleneck",
669
+ "struggle",
670
+ "missing",
671
+ "breaks",
672
+ "regression",
673
+ "unclear",
674
+ "no way to",
675
+ "scope creep",
676
+ "coupled",
677
+ "trapped",
678
+ "ambiguous",
679
+ "no batch",
680
+ "undetectable",
681
+ "coordination gap"
682
+ ],
683
+ glossary: [
684
+ "definition",
685
+ "define",
686
+ "term",
687
+ "means",
688
+ "refers to",
689
+ "is called",
690
+ "vocabulary",
691
+ "terminology",
692
+ "a governance mechanism",
693
+ "a workspace",
694
+ "a tracked",
695
+ "the atom",
696
+ "the action of",
697
+ "the versioned",
698
+ "a field on",
699
+ "one of the",
700
+ "a constraint on",
701
+ "a hard data",
702
+ "a single"
703
+ ],
704
+ insights: [
705
+ "insight",
706
+ "learned",
707
+ "observed",
708
+ "trend",
709
+ "found that",
710
+ "discovery",
711
+ "validates",
712
+ "saturates",
713
+ "convergence",
714
+ "signals from",
715
+ "converge",
716
+ "tam"
717
+ ],
718
+ bets: [
719
+ "appetite",
720
+ "rabbit hole",
721
+ "no-go",
722
+ "shape up",
723
+ "done when",
724
+ "shaping session",
725
+ "from static",
726
+ "from storage",
727
+ "from passive",
728
+ "the chain learns",
729
+ "stage-aware",
730
+ "commit friction",
731
+ "interactive knowledge",
732
+ "capture without",
733
+ "front door",
734
+ "response envelope",
735
+ "knowledge organisation",
736
+ "graveyard",
737
+ "remote mcp",
738
+ "coaching service"
739
+ ],
740
+ features: [
741
+ "feature",
742
+ "capability",
743
+ "user can",
744
+ "navigation",
745
+ "palette",
746
+ "modal",
747
+ "smart capture",
748
+ "suggest-links",
749
+ "command palette",
750
+ "auto-commit",
751
+ "collection-optional",
752
+ "organisation intelligence",
753
+ "consolidation"
754
+ ],
755
+ architecture: [
756
+ "architecture",
757
+ "layer",
758
+ "data model",
759
+ "infrastructure",
760
+ "system design",
761
+ "l1",
762
+ "l2",
763
+ "l3",
764
+ "l4",
765
+ "l5",
766
+ "l6",
767
+ "l7",
768
+ "guard infrastructure",
769
+ "data layer",
770
+ "intelligence layer",
771
+ "mcp layer",
772
+ "core layer"
773
+ ],
774
+ "business-rules": [
775
+ "guard",
776
+ "enforce",
777
+ "integrity",
778
+ "prevents",
779
+ "excludes",
780
+ "permitted",
781
+ "policy",
782
+ "feature gate",
783
+ "must not",
784
+ "only permitted",
785
+ "closed enum",
786
+ "write guard",
787
+ "never imports",
788
+ "requires active session",
789
+ "readiness excludes"
790
+ ],
791
+ "tracking-events": [
792
+ "track",
793
+ "tracking",
794
+ "analytics",
795
+ "trigger",
796
+ "posthog",
797
+ "instrument",
798
+ "fires when"
799
+ ],
800
+ landscape: [
801
+ "competitor",
802
+ "alternative tool",
803
+ "alternative platform",
804
+ "competing product",
805
+ "landscape",
806
+ "comparison"
807
+ ],
808
+ standards: [
809
+ "standard",
810
+ "convention",
811
+ "trunk-based",
812
+ "alignment-first",
813
+ "structured bet",
814
+ "system fixes",
815
+ "patches"
816
+ ],
817
+ principles: [
818
+ "we believe",
819
+ "principle",
820
+ "compounds",
821
+ "philosophy",
822
+ "simplicity compounds",
823
+ "trust through",
824
+ "evidence over",
825
+ "compensate for",
826
+ "honest by default"
827
+ ],
828
+ assumptions: [
829
+ "assume",
830
+ "assumption",
831
+ "hypothesis",
832
+ "untested",
833
+ "we think",
834
+ "we assume",
835
+ "needs validation"
836
+ ]
837
+ };
838
+ function escapeRegExp(text) {
839
+ return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
840
+ }
841
+ function countSignalMatches(text, signal) {
842
+ const trimmed = signal.trim().toLowerCase();
843
+ if (!trimmed) return 0;
844
+ const words = trimmed.split(/\s+/).map(escapeRegExp);
845
+ const pattern = `\\b${words.join("\\s+")}\\b`;
846
+ const regex = new RegExp(pattern, "g");
847
+ const matches = text.match(regex);
848
+ return matches?.length ?? 0;
849
+ }
850
+ function classifyCollection(name, description) {
851
+ const text = `${name} ${description}`.replace(ENTRY_ID_PATTERN, "").toLowerCase();
852
+ const rawScores = [];
853
+ for (const collection of CLASSIFIABLE_COLLECTIONS) {
854
+ const signals = COLLECTION_SIGNALS[collection];
855
+ const reasons = [];
856
+ let score = 0;
857
+ for (const signal of signals) {
858
+ const matches = countSignalMatches(text, signal);
859
+ if (matches <= 0) continue;
860
+ const cappedMatches = Math.min(matches, MAX_MATCHES_PER_SIGNAL);
861
+ score += cappedMatches * SIGNAL_WEIGHT;
862
+ if (reasons.length < MAX_REASON_COUNT) {
863
+ const capNote = matches > cappedMatches ? ` (capped at ${cappedMatches})` : "";
864
+ reasons.push(`matched "${signal}" x${matches}${capNote}`);
865
+ }
866
+ }
867
+ rawScores.push({ collection, score, reasons });
868
+ }
869
+ rawScores.sort((left, right) => right.score - left.score);
870
+ const top = rawScores[0];
871
+ const second = rawScores[1];
872
+ if (!top || top.score < MIN_SCORE_FLOOR) return null;
873
+ const margin = Math.max(0, top.score - (second?.score ?? 0));
874
+ if (margin === 0 && top.score <= MIN_SCORE_FLOOR) return null;
875
+ const baseConfidence = Math.min(90, top.score);
876
+ const confidence = Math.min(99, baseConfidence + Math.min(20, margin));
877
+ return {
878
+ collection: top.collection,
879
+ topConfidence: confidence,
880
+ confidence,
881
+ reasons: top.reasons,
882
+ scoreMargin: margin,
883
+ candidates: rawScores.filter((candidate) => candidate.score > 0).slice(0, 3).map((candidate) => ({
884
+ collection: candidate.collection,
885
+ signalScore: Math.min(99, candidate.score),
886
+ confidence: Math.min(99, candidate.score)
887
+ }))
888
+ };
889
+ }
890
+ function shouldAutoRouteClassification(result) {
891
+ if (result.confidence < CLASSIFIER_AUTO_ROUTE_THRESHOLD) return false;
892
+ if (result.scoreMargin < CLASSIFIER_AMBIGUITY_MARGIN) return false;
893
+ return true;
894
+ }
895
+ function isClassificationAmbiguous(result) {
896
+ return result.scoreMargin < CLASSIFIER_AMBIGUITY_MARGIN;
897
+ }
898
+
899
+ // src/tools/smart-capture-routing.ts
900
+ var STARTER_COLLECTIONS = CLASSIFIABLE_COLLECTIONS;
901
+
902
+ // src/envelope.ts
903
+ import { z } from "zod";
904
+
905
+ // src/errors.ts
906
+ var GateError = class extends Error {
907
+ constructor(message) {
908
+ super(message);
909
+ this.name = "GateError";
910
+ }
911
+ };
912
+ var BackendError = class extends Error {
913
+ constructor(message) {
914
+ super(message);
915
+ this.name = "BackendError";
916
+ }
917
+ };
918
+ var ValidationError = class extends Error {
919
+ constructor(message) {
920
+ super(message);
921
+ this.name = "ValidationError";
922
+ }
923
+ };
924
+ var GATE_PATTERNS = [
925
+ {
926
+ pattern: /session required|no active.*session|call.*session.*start/i,
927
+ code: "SESSION_REQUIRED",
928
+ recovery: "Start an agent session first.",
929
+ action: { tool: "session", description: "Start session", parameters: { action: "start" } }
930
+ },
931
+ {
932
+ pattern: /session.*closed/i,
933
+ code: "SESSION_CLOSED",
934
+ recovery: "Start a new session.",
935
+ action: { tool: "session", description: "Start new session", parameters: { action: "start" } }
936
+ },
937
+ {
938
+ pattern: /orientation required|call.*orient/i,
939
+ code: "ORIENTATION_REQUIRED",
940
+ recovery: "Orient before writing.",
941
+ action: { tool: "orient", description: "Orient session", parameters: {} }
942
+ },
943
+ {
944
+ pattern: /read.?only.*scope/i,
945
+ code: "READONLY_SCOPE",
946
+ recovery: "This API key cannot write. Use a readwrite key.",
947
+ action: { tool: "health", description: "Check key scope", parameters: { action: "whoami" } }
948
+ }
949
+ ];
950
+ function classifyError(err) {
951
+ const message = err instanceof Error ? err.message : String(err);
952
+ if (err instanceof GateError) {
953
+ return {
954
+ code: "PERMISSION_DENIED",
955
+ message,
956
+ recovery: "Check permissions or use a readwrite API key.",
957
+ availableActions: [{ tool: "health", description: "Check key scope", parameters: { action: "whoami" } }]
958
+ };
959
+ }
960
+ if (err instanceof BackendError) {
961
+ return { code: "BACKEND_ERROR", message, recovery: "Retry the operation or check backend health." };
962
+ }
963
+ if (err instanceof ValidationError) {
964
+ return { code: "VALIDATION_ERROR", message };
965
+ }
966
+ for (const { pattern, code, recovery, action } of GATE_PATTERNS) {
967
+ if (pattern.test(message)) {
968
+ return { code, message, recovery, availableActions: [action] };
969
+ }
970
+ }
971
+ if (/network error|fetch failed|ECONNREFUSED|ETIMEDOUT/i.test(message)) {
972
+ return { code: "BACKEND_UNAVAILABLE", message, recovery: "Retry in a few seconds." };
973
+ }
974
+ if (/not found/i.test(message)) {
975
+ return {
976
+ code: "NOT_FOUND",
977
+ message,
978
+ recovery: "Use entries action=search to find the correct ID.",
979
+ availableActions: [{ tool: "entries", description: "Search entries", parameters: { action: "search" } }]
980
+ };
981
+ }
982
+ if (/duplicate|already exists/i.test(message)) {
983
+ return {
984
+ code: "DUPLICATE",
985
+ message,
986
+ recovery: "Use entries action=get to inspect the existing entry.",
987
+ availableActions: [{ tool: "entries", description: "Get entry", parameters: { action: "get" } }]
988
+ };
989
+ }
990
+ if (/invalid|validation|required field/i.test(message)) {
991
+ return { code: "VALIDATION_ERROR", message };
992
+ }
993
+ return { code: "INTERNAL_ERROR", message: message || "An unexpected error occurred." };
994
+ }
995
+
996
+ // src/envelope.ts
997
+ function success(summary, data, next) {
998
+ return {
999
+ ok: true,
1000
+ summary: summary || "Operation completed.",
1001
+ data,
1002
+ ...next?.length ? { next } : {}
1003
+ };
1004
+ }
1005
+ function failure(code, message, recovery, availableActions, diagnostics) {
1006
+ return {
1007
+ ok: false,
1008
+ code,
1009
+ message,
1010
+ ...recovery ? { recovery } : {},
1011
+ ...availableActions?.length ? { availableActions } : {},
1012
+ ...diagnostics ? { diagnostics } : {}
1013
+ };
1014
+ }
1015
+ function notFound(id, hint) {
1016
+ return failure(
1017
+ "NOT_FOUND",
1018
+ `Entry '${id}' not found.`,
1019
+ hint ?? "Use entries action=search to find the correct ID.",
1020
+ [{ tool: "entries", description: "Search entries", parameters: { action: "search", query: id } }]
1021
+ );
1022
+ }
1023
+ function validationError(message) {
1024
+ return failure("VALIDATION_ERROR", message);
1025
+ }
1026
+ function textContent(text) {
1027
+ return [{ type: "text", text }];
1028
+ }
1029
+ function parseOrFail(schema, args) {
1030
+ const parsed = schema.safeParse(args);
1031
+ if (parsed.success) return { ok: true, data: parsed.data };
1032
+ const issues = parsed.error.issues.map((i) => `${i.path.join(".")}: ${i.message}`).join("; ");
1033
+ const msg = `Invalid arguments: ${issues}`;
1034
+ return {
1035
+ ok: false,
1036
+ result: { content: textContent(msg), structuredContent: validationError(msg) }
1037
+ };
1038
+ }
1039
+ function unknownAction(action, valid) {
1040
+ const msg = `Unknown action '${action}'. Valid actions: ${valid.join(", ")}.`;
1041
+ return { content: textContent(msg), structuredContent: validationError(msg) };
1042
+ }
1043
+ function successResult(text, summary, data, next) {
1044
+ return { content: textContent(text), structuredContent: success(summary, data, next) };
1045
+ }
1046
+ function failureResult(text, code, message, recovery, availableActions, diagnostics) {
1047
+ return { content: textContent(text), structuredContent: failure(code, message, recovery, availableActions, diagnostics) };
1048
+ }
1049
+ function notFoundResult(id, text, hint) {
1050
+ return { content: textContent(text ?? `Entry '${id}' not found.`), structuredContent: notFound(id, hint) };
1051
+ }
1052
+ function validationResult(message) {
1053
+ return { content: textContent(message), structuredContent: validationError(message) };
1054
+ }
1055
+ var nextActionSchema = z.object({
1056
+ tool: z.string(),
1057
+ description: z.string(),
1058
+ parameters: z.record(z.unknown())
1059
+ });
1060
+ var metaSchema = z.object({
1061
+ durationMs: z.number().optional()
1062
+ }).optional();
1063
+ function withEnvelope(handler) {
1064
+ return async (args) => {
1065
+ const start = Date.now();
1066
+ try {
1067
+ const result = await handler(args);
1068
+ const durationMs = Date.now() - start;
1069
+ const sc = result.structuredContent;
1070
+ if (sc && typeof sc === "object" && "ok" in sc) {
1071
+ sc._meta = { ...sc._meta, durationMs };
1072
+ return {
1073
+ content: result.content ?? [],
1074
+ structuredContent: sc,
1075
+ ...sc.ok === false ? { isError: true } : {}
1076
+ };
1077
+ }
1078
+ console.warn(`[withEnvelope] Handler returned without envelope shape. Wrapping automatically. Content preview: "${result.content?.[0]?.text?.slice(0, 60) ?? "(empty)"}"`);
1079
+ return {
1080
+ content: result.content ?? [],
1081
+ structuredContent: {
1082
+ ...success(
1083
+ result.content?.[0]?.text?.slice(0, 100) ?? "",
1084
+ sc ?? {}
1085
+ ),
1086
+ _meta: { durationMs }
1087
+ }
1088
+ };
1089
+ } catch (err) {
1090
+ const durationMs = Date.now() - start;
1091
+ const classified = classifyError(err);
1092
+ const envelope = {
1093
+ ...failure(
1094
+ classified.code,
1095
+ classified.message,
1096
+ classified.recovery,
1097
+ classified.availableActions
1098
+ ),
1099
+ _meta: { durationMs }
1100
+ };
1101
+ return {
1102
+ content: [{ type: "text", text: classified.message }],
1103
+ structuredContent: envelope,
1104
+ isError: true
1105
+ };
1106
+ }
1107
+ };
1108
+ }
1109
+
1110
+ // src/tools/smart-capture.ts
1111
+ var AREA_KEYWORDS = {
1112
+ "Architecture": ["convex", "schema", "database", "migration", "api", "backend", "infrastructure", "scaling", "performance"],
1113
+ "Chain": ["knowledge", "glossary", "entry", "collection", "terminology", "drift", "graph", "chain", "commit"],
1114
+ "AI & MCP Integration": ["mcp", "ai", "cursor", "agent", "tool", "llm", "prompt", "context"],
1115
+ "Developer Experience": ["dx", "developer", "ide", "workflow", "friction", "ceremony"],
1116
+ "Governance & Decision-Making": ["governance", "decision", "rule", "policy", "compliance", "approval"],
1117
+ "Analytics & Tracking": ["analytics", "posthog", "tracking", "event", "metric", "funnel"],
1118
+ "Security": ["security", "auth", "api key", "permission", "access", "token"]
1119
+ };
1120
+ function inferArea(text) {
1121
+ const lower = text.toLowerCase();
1122
+ let bestArea = "";
1123
+ let bestScore = 0;
1124
+ for (const [area, keywords] of Object.entries(AREA_KEYWORDS)) {
1125
+ const score = keywords.filter((kw) => lower.includes(kw)).length;
1126
+ if (score > bestScore) {
1127
+ bestScore = score;
1128
+ bestArea = area;
1129
+ }
1130
+ }
1131
+ return bestArea;
1132
+ }
1133
+ function inferDomain(text) {
1134
+ return inferArea(text) || "";
1135
+ }
1136
+ var COMMON_CHECKS = {
1137
+ clearName: {
1138
+ id: "clear-name",
1139
+ label: "Clear, specific name (not vague)",
1140
+ check: (ctx) => ctx.name.length > 10 && !["new tension", "new entry", "untitled", "test"].includes(ctx.name.toLowerCase()),
1141
+ suggestion: () => "Rename to something specific \u2014 describe the actual problem or concept."
1142
+ },
1143
+ hasDescription: {
1144
+ id: "has-description",
1145
+ label: "Description provided (>50 chars)",
1146
+ check: (ctx) => ctx.description.length > 50,
1147
+ suggestion: () => "Add a fuller description explaining context and impact."
1148
+ },
1149
+ hasRelations: {
1150
+ id: "has-relations",
1151
+ label: "At least 1 relation created",
1152
+ check: (ctx) => ctx.linksCreated.length >= 1,
1153
+ suggestion: () => "Use `graph action=suggest` and `relations action=create` to add more connections."
1154
+ },
1155
+ diverseRelations: {
1156
+ id: "diverse-relations",
1157
+ label: "Relations span multiple collections",
1158
+ check: (ctx) => {
1159
+ const colls = new Set(ctx.linksCreated.map((l) => l.targetCollection));
1160
+ return colls.size >= 2;
1161
+ },
1162
+ suggestion: () => "Try linking to entries in different collections (glossary, business-rules, strategy)."
1163
+ },
1164
+ hasType: {
1165
+ id: "has-type",
1166
+ label: "Has canonical type",
1167
+ check: (ctx) => !!ctx.data?.canonicalKey || !!ctx.canonicalKey,
1168
+ suggestion: () => "Classify this entry with a canonical type for better context assembly. Use update-entry to set canonicalKey."
1169
+ }
1170
+ };
1171
+ var STRATEGY_CATEGORY_INFERENCE_THRESHOLD = 2;
1172
+ var STRATEGY_CATEGORY_SIGNALS = [
1173
+ ["business-model", [/pricing/, /revenue/, /unit economics/, /cost structure/, /monetiz/, /margin/, /per.?seat/, /subscription/, /freemium/]],
1174
+ ["vision", [/vision/, /aspirational/, /future state/, /world where/]],
1175
+ ["purpose", [/purpose/, /why we exist/, /mission/, /reason for being/]],
1176
+ ["goal", [/goal/, /metric/, /target/, /kpi/, /okr/, /critical number/, /measur/]],
1177
+ ["principle", [/we believe/, /guiding principle/, /core belief/, /philosophy/]],
1178
+ ["product-area", [/product area/, /module/, /surface/, /capability area/]],
1179
+ ["audience", [/audience/, /persona/, /user segment/, /icp/, /target market/]],
1180
+ ["insight", [/insight/, /we learned/, /we observed/, /pattern/]],
1181
+ ["opportunity", [/opportunity/, /whitespace/, /gap/, /underserved/]]
1182
+ ];
1183
+ function inferStrategyCategory(name, description) {
1184
+ const text = `${name} ${description}`.toLowerCase();
1185
+ let bestCategory = null;
1186
+ let bestScore = 0;
1187
+ for (const [cat, signals] of STRATEGY_CATEGORY_SIGNALS) {
1188
+ const score = signals.reduce((s, rx) => s + (rx.test(text) ? 1 : 0), 0);
1189
+ if (score > bestScore) {
1190
+ bestScore = score;
1191
+ bestCategory = cat;
1192
+ }
1193
+ }
1194
+ if (bestCategory && bestScore >= STRATEGY_CATEGORY_INFERENCE_THRESHOLD) return bestCategory;
1195
+ if (bestScore === 0) return "strategy";
1196
+ return null;
1197
+ }
1198
+ var PROFILES = /* @__PURE__ */ new Map([
1199
+ ["tensions", {
1200
+ governedDraft: false,
1201
+ descriptionField: "description",
1202
+ defaults: [
1203
+ { key: "priority", value: "medium" },
1204
+ { key: "date", value: "today" },
1205
+ { key: "raised", value: "infer" },
1206
+ { key: "severity", value: "infer" }
1207
+ ],
1208
+ recommendedRelationTypes: ["surfaces_tension_in", "references", "belongs_to", "related_to"],
1209
+ inferField: (ctx) => {
1210
+ const fields = {};
1211
+ const text = `${ctx.name} ${ctx.description}`;
1212
+ const area = inferArea(text);
1213
+ if (area) fields.raised = area;
1214
+ if (text.toLowerCase().includes("critical") || text.toLowerCase().includes("blocker")) {
1215
+ fields.severity = "critical";
1216
+ } else if (text.toLowerCase().includes("bottleneck") || text.toLowerCase().includes("scaling") || text.toLowerCase().includes("breaking")) {
1217
+ fields.severity = "high";
1218
+ } else {
1219
+ fields.severity = "medium";
1220
+ }
1221
+ if (area) fields.affectedArea = area;
1222
+ return fields;
1223
+ },
1224
+ qualityChecks: [
1225
+ COMMON_CHECKS.clearName,
1226
+ COMMON_CHECKS.hasDescription,
1227
+ COMMON_CHECKS.hasRelations,
1228
+ COMMON_CHECKS.hasType,
1229
+ {
1230
+ id: "has-severity",
1231
+ label: "Severity specified",
1232
+ check: (ctx) => !!ctx.data.severity && ctx.data.severity !== "",
1233
+ suggestion: (ctx) => {
1234
+ const text = `${ctx.name} ${ctx.description}`.toLowerCase();
1235
+ const inferred = text.includes("critical") ? "critical" : text.includes("bottleneck") ? "high" : "medium";
1236
+ return `Set severity \u2014 suggest: ${inferred} (based on description keywords).`;
1237
+ }
1238
+ },
1239
+ {
1240
+ id: "has-affected-area",
1241
+ label: "Affected area identified",
1242
+ check: (ctx) => !!ctx.data.affectedArea && ctx.data.affectedArea !== "",
1243
+ suggestion: (ctx) => {
1244
+ const area = inferArea(`${ctx.name} ${ctx.description}`);
1245
+ return area ? `Set affectedArea \u2014 suggest: "${area}" (inferred from content).` : "Specify which product area or domain this tension impacts.";
1246
+ }
1247
+ }
1248
+ ]
1249
+ }],
1250
+ ["business-rules", {
1251
+ governedDraft: true,
1252
+ descriptionField: "description",
1253
+ defaults: [
1254
+ { key: "severity", value: "medium" },
1255
+ { key: "domain", value: "infer" }
1256
+ ],
1257
+ recommendedRelationTypes: ["governs", "references", "conflicts_with", "related_to"],
1258
+ inferField: (ctx) => {
1259
+ const fields = {};
1260
+ const domain = inferDomain(`${ctx.name} ${ctx.description}`);
1261
+ if (domain) fields.domain = domain;
1262
+ return fields;
1263
+ },
1264
+ qualityChecks: [
1265
+ COMMON_CHECKS.clearName,
1266
+ COMMON_CHECKS.hasDescription,
1267
+ COMMON_CHECKS.hasRelations,
1268
+ COMMON_CHECKS.hasType,
1269
+ {
1270
+ id: "has-rationale",
1271
+ label: "Rationale provided",
1272
+ check: (ctx) => typeof ctx.data.rationale === "string" && ctx.data.rationale.length > 10,
1273
+ suggestion: () => "Add a rationale explaining why this rule exists via `update-entry`."
1274
+ },
1275
+ {
1276
+ id: "has-domain",
1277
+ label: "Domain specified",
1278
+ check: (ctx) => !!ctx.data.domain && ctx.data.domain !== "",
1279
+ suggestion: (ctx) => {
1280
+ const domain = inferDomain(`${ctx.name} ${ctx.description}`);
1281
+ return domain ? `Set domain \u2014 suggest: "${domain}" (inferred from content).` : "Specify the business domain this rule belongs to.";
1282
+ }
1283
+ }
1284
+ ]
1285
+ }],
1286
+ ["glossary", {
1287
+ governedDraft: true,
1288
+ descriptionField: "canonical",
1289
+ defaults: [
1290
+ { key: "category", value: "infer" }
1291
+ ],
1292
+ recommendedRelationTypes: ["defines_term_for", "confused_with", "related_to", "references"],
1293
+ inferField: (ctx) => {
1294
+ const fields = {};
1295
+ const area = inferArea(`${ctx.name} ${ctx.description}`);
1296
+ if (area) {
1297
+ const categoryMap = {
1298
+ "Architecture": "Platform & Architecture",
1299
+ "Chain": "Knowledge Management",
1300
+ "AI & MCP Integration": "AI & Developer Tools",
1301
+ "Developer Experience": "AI & Developer Tools",
1302
+ "Governance & Decision-Making": "Governance & Process",
1303
+ "Analytics & Tracking": "Platform & Architecture",
1304
+ "Security": "Platform & Architecture"
1305
+ };
1306
+ fields.category = categoryMap[area] ?? "";
1307
+ }
1308
+ return fields;
1309
+ },
1310
+ qualityChecks: [
1311
+ COMMON_CHECKS.clearName,
1312
+ COMMON_CHECKS.hasType,
1313
+ {
1314
+ id: "has-canonical",
1315
+ label: "Canonical definition provided (>20 chars)",
1316
+ check: (ctx) => {
1317
+ const canonical = ctx.data.canonical;
1318
+ return typeof canonical === "string" && canonical.length > 20;
1319
+ },
1320
+ suggestion: () => "Add a clear canonical definition \u2014 this is the single source of truth for this term."
1321
+ },
1322
+ COMMON_CHECKS.hasRelations,
1323
+ {
1324
+ id: "has-category",
1325
+ label: "Category assigned",
1326
+ check: (ctx) => !!ctx.data.category && ctx.data.category !== "",
1327
+ suggestion: () => "Assign a category (e.g., 'Platform & Architecture', 'Governance & Process')."
1328
+ }
1329
+ ]
1330
+ }],
1331
+ ["decisions", {
1332
+ governedDraft: false,
1333
+ descriptionField: "rationale",
1334
+ defaults: [
1335
+ { key: "date", value: "today" },
1336
+ { key: "decidedBy", value: "infer" }
1337
+ ],
1338
+ recommendedRelationTypes: ["informs", "references", "replaces", "related_to"],
1339
+ inferField: (ctx) => {
1340
+ const fields = {};
1341
+ const area = inferArea(`${ctx.name} ${ctx.description}`);
1342
+ if (area) fields.decidedBy = area;
1343
+ return fields;
1344
+ },
1345
+ qualityChecks: [
1346
+ COMMON_CHECKS.clearName,
1347
+ COMMON_CHECKS.hasType,
1348
+ {
1349
+ id: "has-rationale",
1350
+ label: "Rationale provided (>30 chars)",
1351
+ check: (ctx) => {
1352
+ const rationale = ctx.data.rationale;
1353
+ return typeof rationale === "string" && rationale.length > 30;
1354
+ },
1355
+ suggestion: () => "Explain why this decision was made \u2014 what was considered and rejected?"
1356
+ },
1357
+ COMMON_CHECKS.hasRelations,
1358
+ {
1359
+ id: "has-date",
1360
+ label: "Decision date recorded",
1361
+ check: (ctx) => !!ctx.data.date && ctx.data.date !== "",
1362
+ suggestion: () => "Record when this decision was made."
1363
+ }
1364
+ ]
1365
+ }],
1366
+ ["features", {
1367
+ governedDraft: false,
1368
+ descriptionField: "description",
1369
+ defaults: [],
1370
+ recommendedRelationTypes: ["belongs_to", "depends_on", "surfaces_tension_in", "related_to"],
1371
+ qualityChecks: [
1372
+ COMMON_CHECKS.clearName,
1373
+ COMMON_CHECKS.hasDescription,
1374
+ COMMON_CHECKS.hasRelations,
1375
+ COMMON_CHECKS.hasType,
1376
+ {
1377
+ id: "has-owner",
1378
+ label: "Owner assigned",
1379
+ check: (ctx) => !!ctx.data.owner && ctx.data.owner !== "",
1380
+ suggestion: () => "Assign an owner team or product area."
1381
+ },
1382
+ {
1383
+ id: "has-rationale",
1384
+ label: "Rationale documented",
1385
+ check: (ctx) => !!ctx.data.rationale && String(ctx.data.rationale).length > 20,
1386
+ suggestion: () => "Explain why this feature matters \u2014 what problem does it solve?"
1387
+ }
1388
+ ]
1389
+ }],
1390
+ ["audiences", {
1391
+ governedDraft: false,
1392
+ descriptionField: "description",
1393
+ defaults: [],
1394
+ recommendedRelationTypes: ["fills_slot", "informs", "related_to", "references"],
1395
+ qualityChecks: [
1396
+ COMMON_CHECKS.clearName,
1397
+ COMMON_CHECKS.hasDescription,
1398
+ COMMON_CHECKS.hasRelations,
1399
+ COMMON_CHECKS.hasType,
1400
+ {
1401
+ id: "has-behaviors",
1402
+ label: "Behaviors described",
1403
+ check: (ctx) => typeof ctx.data.behaviors === "string" && ctx.data.behaviors.length > 20,
1404
+ suggestion: () => "Describe how this audience segment behaves \u2014 what do they do, what tools do they use?"
1405
+ }
1406
+ ]
1407
+ }],
1408
+ ["strategy", {
1409
+ governedDraft: true,
1410
+ descriptionField: "description",
1411
+ defaults: [],
1412
+ recommendedRelationTypes: ["informs", "governs", "belongs_to", "related_to"],
1413
+ inferField: (ctx) => {
1414
+ if (ctx.data?.category) return {};
1415
+ const category = inferStrategyCategory(ctx.name, ctx.description);
1416
+ return category ? { category } : {};
1417
+ },
1418
+ qualityChecks: [
1419
+ COMMON_CHECKS.clearName,
1420
+ COMMON_CHECKS.hasDescription,
1421
+ COMMON_CHECKS.hasRelations,
1422
+ COMMON_CHECKS.hasType,
1423
+ COMMON_CHECKS.diverseRelations
1424
+ ]
1425
+ }],
1426
+ ["bets", {
1427
+ // BET-chain-native-constellation, DEC-70 (structuredContent), STA-1 (constellation pattern)
1428
+ governedDraft: false,
1429
+ descriptionField: "problem",
1430
+ defaults: [],
1431
+ recommendedRelationTypes: ["part_of", "constrains", "informs", "depends_on", "related_to"],
1432
+ qualityChecks: [
1433
+ COMMON_CHECKS.clearName,
1434
+ COMMON_CHECKS.hasDescription,
1435
+ COMMON_CHECKS.hasRelations,
1436
+ COMMON_CHECKS.hasType
1437
+ ]
1438
+ }],
1439
+ ["maps", {
1440
+ governedDraft: false,
1441
+ descriptionField: "description",
1442
+ defaults: [],
1443
+ recommendedRelationTypes: ["fills_slot", "references", "related_to"],
1444
+ qualityChecks: [
1445
+ COMMON_CHECKS.clearName,
1446
+ COMMON_CHECKS.hasDescription
1447
+ ]
1448
+ }],
1449
+ ["chains", {
1450
+ governedDraft: false,
1451
+ descriptionField: "description",
1452
+ defaults: [],
1453
+ recommendedRelationTypes: ["informs", "references", "related_to"],
1454
+ qualityChecks: [
1455
+ COMMON_CHECKS.clearName,
1456
+ COMMON_CHECKS.hasDescription
1457
+ ]
1458
+ }],
1459
+ ["principles", {
1460
+ governedDraft: true,
1461
+ descriptionField: "description",
1462
+ defaults: [
1463
+ { key: "severity", value: "high" },
1464
+ { key: "category", value: "infer" }
1465
+ ],
1466
+ recommendedRelationTypes: ["governs", "informs", "references", "related_to"],
1467
+ inferField: (ctx) => {
1468
+ const fields = {};
1469
+ const area = inferArea(`${ctx.name} ${ctx.description}`);
1470
+ if (area) {
1471
+ const categoryMap = {
1472
+ "Architecture": "Engineering",
1473
+ "Chain": "Product",
1474
+ "AI & MCP Integration": "Engineering",
1475
+ "Developer Experience": "Engineering",
1476
+ "Governance & Decision-Making": "Business",
1477
+ "Analytics & Tracking": "Product",
1478
+ "Security": "Engineering"
1479
+ };
1480
+ fields.category = categoryMap[area] ?? "Product";
1481
+ }
1482
+ return fields;
1483
+ },
1484
+ qualityChecks: [
1485
+ COMMON_CHECKS.clearName,
1486
+ COMMON_CHECKS.hasDescription,
1487
+ COMMON_CHECKS.hasRelations,
1488
+ COMMON_CHECKS.hasType,
1489
+ {
1490
+ id: "has-rationale",
1491
+ label: "Rationale provided \u2014 why this principle matters",
1492
+ check: (ctx) => typeof ctx.data.rationale === "string" && ctx.data.rationale.length > 20,
1493
+ suggestion: () => "Explain why this principle exists and what goes wrong without it."
1494
+ }
1495
+ ]
1496
+ }],
1497
+ ["standards", {
1498
+ governedDraft: true,
1499
+ descriptionField: "description",
1500
+ defaults: [],
1501
+ recommendedRelationTypes: ["governs", "defines_term_for", "references", "related_to"],
1502
+ qualityChecks: [
1503
+ COMMON_CHECKS.clearName,
1504
+ COMMON_CHECKS.hasDescription,
1505
+ COMMON_CHECKS.hasRelations,
1506
+ COMMON_CHECKS.hasType
1507
+ ]
1508
+ }],
1509
+ ["tracking-events", {
1510
+ governedDraft: false,
1511
+ descriptionField: "description",
1512
+ defaults: [],
1513
+ recommendedRelationTypes: ["references", "belongs_to", "related_to"],
1514
+ qualityChecks: [
1515
+ COMMON_CHECKS.clearName,
1516
+ COMMON_CHECKS.hasDescription
1517
+ ]
1518
+ }],
1519
+ ["insights", {
1520
+ governedDraft: false,
1521
+ descriptionField: "description",
1522
+ defaults: [
1523
+ { key: "evidenceStrength", value: "anecdotal" }
1524
+ ],
1525
+ recommendedRelationTypes: ["validates", "invalidates", "informs", "related_to"],
1526
+ qualityChecks: [
1527
+ COMMON_CHECKS.clearName,
1528
+ COMMON_CHECKS.hasDescription,
1529
+ COMMON_CHECKS.hasRelations,
1530
+ COMMON_CHECKS.hasType,
1531
+ {
1532
+ id: "has-evidence-link",
1533
+ label: "Evidence link exists (validates or invalidates)",
1534
+ check: (ctx) => ctx.linksCreated.some((l) => l.relationType === "validates" || l.relationType === "invalidates"),
1535
+ suggestion: () => "Link this insight to the assumption or claim it validates/invalidates using `relations action=create type=validates`."
1536
+ },
1537
+ {
1538
+ id: "has-source",
1539
+ label: "Source documented",
1540
+ check: (ctx) => !!ctx.data?.source && String(ctx.data.source).length > 0,
1541
+ suggestion: () => "Document where this insight came from (research, data, user interview, etc.)."
1542
+ }
1543
+ ]
1544
+ }],
1545
+ ["assumptions", {
1546
+ governedDraft: false,
1547
+ descriptionField: "belief",
1548
+ defaults: [
1549
+ { key: "risk", value: "medium" },
1550
+ { key: "evidenceStrength", value: "unvalidated" }
1551
+ ],
1552
+ recommendedRelationTypes: ["depends_on", "informs", "related_to", "validates", "invalidates"],
1553
+ qualityChecks: [
1554
+ COMMON_CHECKS.clearName,
1555
+ {
1556
+ id: "has-belief",
1557
+ label: "Belief statement provided (>30 chars)",
1558
+ check: (ctx) => !!ctx.data?.belief && String(ctx.data.belief).length > 30,
1559
+ suggestion: () => "Write the assumption as a clear, testable belief statement."
1560
+ },
1561
+ COMMON_CHECKS.hasRelations,
1562
+ COMMON_CHECKS.hasType,
1563
+ {
1564
+ id: "has-test-method",
1565
+ label: "Test method described",
1566
+ check: (ctx) => !!ctx.data?.testMethod && String(ctx.data.testMethod).length > 0,
1567
+ suggestion: () => "Describe how this assumption could be tested or validated."
1568
+ }
1569
+ ]
1570
+ }],
1571
+ ["architecture", {
1572
+ governedDraft: true,
1573
+ descriptionField: "description",
1574
+ defaults: [],
1575
+ recommendedRelationTypes: ["belongs_to", "depends_on", "governs", "references", "related_to"],
1576
+ qualityChecks: [
1577
+ COMMON_CHECKS.clearName,
1578
+ COMMON_CHECKS.hasDescription,
1579
+ COMMON_CHECKS.hasRelations,
1580
+ COMMON_CHECKS.hasType,
1581
+ {
1582
+ id: "has-layer",
1583
+ label: "Architecture layer identified",
1584
+ check: (ctx) => !!ctx.data?.layer && String(ctx.data.layer).length > 0,
1585
+ suggestion: () => "Specify which architecture layer this belongs to (L1-L7)."
1586
+ }
1587
+ ]
1588
+ }],
1589
+ ["landscape", {
1590
+ governedDraft: false,
1591
+ descriptionField: "description",
1592
+ defaults: [],
1593
+ recommendedRelationTypes: ["references", "related_to", "fills_slot"],
1594
+ qualityChecks: [
1595
+ COMMON_CHECKS.clearName,
1596
+ COMMON_CHECKS.hasDescription,
1597
+ COMMON_CHECKS.hasRelations,
1598
+ COMMON_CHECKS.hasType
1599
+ ]
1600
+ }]
1601
+ ]);
1602
+ var FALLBACK_PROFILE = {
1603
+ governedDraft: false,
1604
+ descriptionField: "description",
1605
+ defaults: [],
1606
+ recommendedRelationTypes: ["related_to", "references"],
1607
+ qualityChecks: [
1608
+ COMMON_CHECKS.clearName,
1609
+ COMMON_CHECKS.hasDescription,
1610
+ COMMON_CHECKS.hasRelations,
1611
+ COMMON_CHECKS.hasType
1612
+ ]
1613
+ };
1614
+ function extractSearchTerms(name, description) {
1615
+ const text = `${name} ${description}`;
1616
+ return text.replace(/[^\w\s]/g, " ").split(/\s+/).filter((w) => w.length > 3).slice(0, 8).join(" ");
1617
+ }
1618
+ function computeLinkConfidence(candidate, sourceName, sourceDescription, sourceCollection, candidateCollection) {
1619
+ const text = `${sourceName} ${sourceDescription}`.toLowerCase();
1620
+ const candidateName = candidate.name.toLowerCase();
1621
+ let score = 0;
1622
+ const reasons = [];
1623
+ if (text.includes(candidateName) && candidateName.length > 3) {
1624
+ score += 40;
1625
+ reasons.push("name match");
1626
+ }
1627
+ const candidateWords = candidateName.split(/\s+/).filter((w) => w.length > 3);
1628
+ const matchingWords = candidateWords.filter((w) => text.includes(w));
1629
+ const wordScore = matchingWords.length / Math.max(candidateWords.length, 1) * 30;
1630
+ score += wordScore;
1631
+ if (matchingWords.length > 0) {
1632
+ reasons.push(`word overlap (${matchingWords.slice(0, 3).join(", ")})`);
1633
+ }
1634
+ const HUB_COLLECTIONS = /* @__PURE__ */ new Set(["strategy", "features"]);
1635
+ if (HUB_COLLECTIONS.has(candidateCollection)) {
1636
+ score += 15;
1637
+ reasons.push("hub collection");
1638
+ }
1639
+ if (candidateCollection !== sourceCollection) {
1640
+ score += 10;
1641
+ reasons.push("cross-collection");
1642
+ }
1643
+ const finalScore = Math.min(score, 100);
1644
+ const reason = reasons.length > 0 ? reasons.join(" + ") : "low relevance";
1645
+ return { score: finalScore, reason };
1646
+ }
1647
+ function inferRelationType(sourceCollection, targetCollection, profile) {
1648
+ const typeMap = {
1649
+ tensions: {
1650
+ glossary: "surfaces_tension_in",
1651
+ "business-rules": "references",
1652
+ strategy: "belongs_to",
1653
+ features: "surfaces_tension_in",
1654
+ decisions: "references"
1655
+ },
1656
+ "business-rules": {
1657
+ glossary: "references",
1658
+ features: "governs",
1659
+ strategy: "belongs_to",
1660
+ tensions: "references"
1661
+ },
1662
+ glossary: {
1663
+ features: "defines_term_for",
1664
+ "business-rules": "references",
1665
+ strategy: "references"
1666
+ },
1667
+ decisions: {
1668
+ features: "informs",
1669
+ "business-rules": "references",
1670
+ strategy: "references",
1671
+ tensions: "references"
1672
+ }
1673
+ };
1674
+ const mapped = typeMap[sourceCollection]?.[targetCollection];
1675
+ const type = mapped ?? profile.recommendedRelationTypes[0] ?? "related_to";
1676
+ const reason = mapped ? `collection pair (${sourceCollection} \u2192 ${targetCollection})` : `profile default (${profile.recommendedRelationTypes[0] ?? "related_to"})`;
1677
+ return { type, reason };
1678
+ }
1679
+ function scoreQuality(ctx, profile) {
1680
+ const checks = profile.qualityChecks.map((qc) => {
1681
+ const passed2 = qc.check(ctx);
1682
+ return {
1683
+ id: qc.id,
1684
+ label: qc.label,
1685
+ passed: passed2,
1686
+ suggestion: passed2 ? void 0 : qc.suggestion?.(ctx)
1687
+ };
1688
+ });
1689
+ const passed = checks.filter((c) => c.passed).length;
1690
+ const total = checks.length;
1691
+ const score = total > 0 ? Math.round(passed / total * 10) : 10;
1692
+ return { score, maxScore: 10, checks };
1693
+ }
1694
+ function formatQualityReport(result) {
1695
+ const failed = result.checks.filter((c) => !c.passed);
1696
+ const reason = failed.length > 0 ? ` because ${failed.map((c) => c.suggestion ?? c.label.toLowerCase()).join("; ")}` : "";
1697
+ const lines = [`## Quality: ${result.score}/${result.maxScore}${reason}`];
1698
+ for (const check of result.checks) {
1699
+ const icon = check.passed ? "[x]" : "[ ]";
1700
+ const suggestion = check.passed ? "" : ` \u2014 ${check.suggestion ?? check.label}`;
1701
+ lines.push(`${icon} ${check.label}${suggestion}`);
1702
+ }
1703
+ return lines.join("\n");
1704
+ }
1705
+ async function checkEntryQuality(entryId) {
1706
+ const entry = await mcpQuery("chain.getEntry", { entryId });
1707
+ if (!entry) {
1708
+ return {
1709
+ text: `Entry \`${entryId}\` not found. Try search to find the right ID.`,
1710
+ quality: { score: 0, maxScore: 10, checks: [] }
1711
+ };
1712
+ }
1713
+ const collections = await mcpQuery("chain.listCollections");
1714
+ const collMap = /* @__PURE__ */ new Map();
1715
+ for (const c of collections) collMap.set(c._id, c.slug);
1716
+ const collectionSlug = collMap.get(entry.collectionId) ?? "unknown";
1717
+ const profile = PROFILES.get(collectionSlug) ?? FALLBACK_PROFILE;
1718
+ const relations = await mcpQuery("chain.listEntryRelations", { entryId });
1719
+ const linksCreated = [];
1720
+ for (const r of relations) {
1721
+ const otherId = r.fromId === entry._id ? r.toId : r.fromId;
1722
+ linksCreated.push({
1723
+ targetEntryId: otherId,
1724
+ targetName: "",
1725
+ targetCollection: "",
1726
+ relationType: r.type
1727
+ });
1728
+ }
1729
+ const descField = profile.descriptionField;
1730
+ const description = typeof entry.data?.[descField] === "string" ? entry.data[descField] : "";
1731
+ const ctx = {
1732
+ collection: collectionSlug,
1733
+ name: entry.name,
1734
+ description,
1735
+ data: entry.data ?? {},
1736
+ entryId: entry.entryId ?? "",
1737
+ canonicalKey: entry.canonicalKey,
1738
+ linksCreated,
1739
+ linksSuggested: [],
1740
+ collectionFields: []
1741
+ };
1742
+ const quality = scoreQuality(ctx, profile);
1743
+ const lines = [
1744
+ `# Quality Check: ${entry.entryId ?? entry.name}`,
1745
+ `**${entry.name}** in \`${collectionSlug}\` [${entry.status}]`,
1746
+ "",
1747
+ formatQualityReport(quality)
1748
+ ];
1749
+ if (quality.score < 10) {
1750
+ const failedChecks = quality.checks.filter((c) => !c.passed && c.suggestion);
1751
+ if (failedChecks.length > 0) {
1752
+ lines.push("");
1753
+ lines.push(`_To improve: use \`update-entry\` to fill missing fields, or \`relations action=create\` to add connections._`);
1754
+ }
1755
+ }
1756
+ return { text: lines.join("\n"), quality };
1757
+ }
1758
+ var GOVERNED_COLLECTIONS = /* @__PURE__ */ new Set([
1759
+ "glossary",
1760
+ "business-rules",
1761
+ "principles",
1762
+ "standards",
1763
+ "strategy",
1764
+ "features",
1765
+ "architecture"
1766
+ ]);
1767
+ var AUTO_LINK_CONFIDENCE_THRESHOLD = 35;
1768
+ var MAX_AUTO_LINKS = 5;
1769
+ var MAX_SUGGESTIONS = 5;
1770
+ var CAPTURE_WITHOUT_THINKING_FLAG = "capture-without-thinking";
1771
+ var captureSchema = z2.object({
1772
+ collection: z2.string().optional().describe("Collection slug, e.g. 'tensions', 'business-rules', 'glossary', 'decisions'. Optional when `capture-without-thinking` is enabled."),
1773
+ name: z2.string().describe("Display name \u2014 be specific (e.g. 'Convex adjacency list won't scale for graph traversal')"),
1774
+ description: z2.string().describe("Full context \u2014 what's happening, why it matters, what you observed"),
1775
+ context: z2.string().optional().describe("Optional additional context (e.g. 'Observed during context gather calls taking 700ms+')"),
1776
+ entryId: z2.string().optional().describe("Optional custom entry ID (e.g. 'TEN-my-id'). Auto-generated if omitted."),
1777
+ canonicalKey: z2.string().optional().describe("Semantic type (e.g. 'decision', 'tension', 'vision'). Auto-assigned from collection if omitted."),
1778
+ data: z2.record(z2.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."),
1779
+ links: z2.array(z2.object({
1780
+ to: z2.string().describe("Target entry ID (e.g. 'BR-64', 'ARCH-8')"),
1781
+ type: z2.string().describe("Relation type (e.g. 'governs', 'related_to', 'informs')")
1782
+ })).optional().describe("Relations to create after capture. Skips auto-link discovery when provided."),
1783
+ autoCommit: z2.boolean().optional().describe("If true, commits the entry immediately after capture + linking. Use for ungoverned collections or when you're certain.")
1784
+ });
1785
+ var batchCaptureSchema = z2.object({
1786
+ entries: z2.array(z2.object({
1787
+ collection: z2.string().describe("Collection slug"),
1788
+ name: z2.string().describe("Display name"),
1789
+ description: z2.string().describe("Full context / definition"),
1790
+ entryId: z2.string().optional().describe("Optional custom entry ID")
1791
+ })).min(1).max(50).describe("Array of entries to capture")
1792
+ });
1793
+ var captureClassifierSchema = z2.object({
1794
+ enabled: z2.boolean(),
1795
+ autoRouted: z2.boolean(),
1796
+ agrees: z2.boolean(),
1797
+ abstained: z2.boolean(),
1798
+ topConfidence: z2.number(),
1799
+ confidence: z2.number(),
1800
+ reasons: z2.array(z2.string()),
1801
+ candidates: z2.array(
1802
+ z2.object({
1803
+ collection: z2.enum(CLASSIFIABLE_COLLECTIONS),
1804
+ signalScore: z2.number(),
1805
+ confidence: z2.number()
1806
+ })
1807
+ ),
1808
+ agentProvidedCollection: z2.string().optional(),
1809
+ overrideCommand: z2.string().optional()
1810
+ });
1811
+ function trackClassifierTelemetry(params) {
1812
+ const telemetry = {
1813
+ predicted_collection: params.predictedCollection,
1814
+ confidence: params.confidence,
1815
+ auto_routed: params.autoRouted,
1816
+ reason_category: params.reasonCategory,
1817
+ explicit_collection_provided: params.explicitCollectionProvided
1818
+ };
1819
+ trackCaptureClassifierEvaluated(params.workspaceId, telemetry);
1820
+ if (params.outcome === "auto-routed") {
1821
+ trackCaptureClassifierAutoRouted(params.workspaceId, telemetry);
1822
+ return;
1823
+ }
1824
+ trackCaptureClassifierFallback(params.workspaceId, telemetry);
1825
+ }
1826
+ function buildCollectionRequiredResult() {
1827
+ return {
1828
+ content: [{
1829
+ type: "text",
1830
+ text: "Collection is required unless `capture-without-thinking` is enabled.\n\nProvide `collection` explicitly, or enable the feature flag for this workspace."
1831
+ }],
1832
+ structuredContent: failure(
1833
+ "VALIDATION_ERROR",
1834
+ "Collection is required unless capture-without-thinking is enabled.",
1835
+ "Provide collection explicitly, or enable the feature flag.",
1836
+ [{ tool: "collections", description: "List available collections", parameters: { action: "list" } }]
1837
+ )
1838
+ };
1839
+ }
1840
+ function buildClassifierUnknownResult() {
1841
+ return {
1842
+ content: [{
1843
+ type: "text",
1844
+ 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)."
1845
+ }],
1846
+ structuredContent: failure(
1847
+ "VALIDATION_ERROR",
1848
+ "Could not infer collection from input.",
1849
+ "Provide collection explicitly, or rewrite with clearer intent.",
1850
+ [{ tool: "collections", description: "List available collections", parameters: { action: "list" } }],
1851
+ { classifier: { enabled: true, autoRouted: false, agrees: false, abstained: true, topConfidence: 0, confidence: 0, reasons: [], candidates: [] } }
1852
+ )
1853
+ };
1854
+ }
1855
+ function buildProvisionedCollectionSuggestions(candidates) {
1856
+ return candidates.length ? candidates.map((c) => `- \`${c.collection}\` (${c.signalScore}% signal score)`).join("\n") : "- No provisioned collection candidates were inferred confidently.";
1857
+ }
1858
+ function buildUnsupportedProvisioningResult(classified, provisionedCandidates) {
1859
+ const suggestions = buildProvisionedCollectionSuggestions(provisionedCandidates);
1860
+ const textBody = `Collection inference is not safe to auto-route yet.
1861
+
1862
+ Predicted collection \`${classified.collection}\` is not provisioned/supported for auto-routing in this workspace.
1863
+ Reason: ${classified.reasons.join("; ") || "low signal"}
1864
+
1865
+ Choose one of these provisioned starter collections and retry with \`collection\`:
1866
+ ${suggestions}
1867
+
1868
+ Correction path: rerun with explicit \`collection\`.`;
1869
+ return {
1870
+ content: [{ type: "text", text: textBody }],
1871
+ structuredContent: failure(
1872
+ "VALIDATION_ERROR",
1873
+ `Collection '${classified.collection}' is not provisioned for auto-routing.`,
1874
+ "Rerun with explicit collection.",
1875
+ [{ tool: "collections", description: "List available collections", parameters: { action: "list" } }],
1876
+ {
1877
+ classifier: {
1878
+ enabled: true,
1879
+ autoRouted: false,
1880
+ agrees: false,
1881
+ abstained: false,
1882
+ topConfidence: classified.topConfidence,
1883
+ confidence: classified.confidence,
1884
+ reasons: classified.reasons,
1885
+ candidates: provisionedCandidates.map((c) => ({ collection: c.collection, signalScore: c.signalScore, confidence: c.confidence }))
1886
+ }
1887
+ }
1888
+ )
1889
+ };
1890
+ }
1891
+ function buildAmbiguousRouteResult(classified, classifierMeta, ambiguousRoute) {
1892
+ const suggestions = buildProvisionedCollectionSuggestions(classifierMeta.candidates);
1893
+ const textBody = "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)
1894
+ Reason: ${classified.reasons.join("; ") || "low signal"}
1895
+
1896
+ Choose one of these and retry with \`collection\`:
1897
+ ${suggestions}
1898
+
1899
+ Correction path: if this was close, rerun with your chosen \`collection\`.`;
1900
+ return {
1901
+ content: [{ type: "text", text: textBody }],
1902
+ structuredContent: failure(
1903
+ "VALIDATION_ERROR",
1904
+ ambiguousRoute ? `Ambiguous routing \u2014 top candidates too close (${classified.topConfidence}% confidence).` : `Low confidence routing to '${classified.collection}' (${classified.topConfidence}%).`,
1905
+ "Rerun with explicit collection.",
1906
+ classifierMeta.candidates.map((c) => ({
1907
+ tool: "capture",
1908
+ description: `Capture to ${c.collection}`,
1909
+ parameters: { collection: c.collection }
1910
+ })),
1911
+ { classifier: classifierMeta }
1912
+ )
1913
+ };
1914
+ }
1915
+ async function getProvisionedCollectionCandidates(classified, supportedCollections) {
1916
+ const allCollections = await mcpQuery("chain.listCollections");
1917
+ const provisionedCollections = new Set(
1918
+ (allCollections ?? []).map((collection) => collection.slug).filter(
1919
+ (slug) => supportedCollections.has(slug)
1920
+ )
1921
+ );
1922
+ const provisionedCandidates = classified.candidates.filter(
1923
+ (candidate) => provisionedCollections.has(candidate.collection)
1924
+ );
1925
+ return { provisionedCollections, provisionedCandidates };
1926
+ }
1927
+ async function resolveCaptureCollection(params) {
1928
+ const {
1929
+ collection,
1930
+ name,
1931
+ description,
1932
+ classifierFlagOn,
1933
+ supportedCollections,
1934
+ workspaceId,
1935
+ explicitCollectionProvided
1936
+ } = params;
1937
+ if (collection) {
1938
+ const classified2 = classifyCollection(name, description);
1939
+ if (classified2) {
1940
+ const agrees = classified2.collection === collection;
1941
+ const classifierMeta2 = {
1942
+ enabled: true,
1943
+ autoRouted: false,
1944
+ agrees,
1945
+ abstained: false,
1946
+ topConfidence: classified2.topConfidence,
1947
+ confidence: classified2.confidence,
1948
+ reasons: classified2.reasons,
1949
+ candidates: classified2.candidates.slice(0, 3),
1950
+ agentProvidedCollection: collection,
1951
+ ...!agrees && {
1952
+ overrideCommand: `capture collection="${classified2.collection}"`
1953
+ }
1954
+ };
1955
+ if (!agrees) {
1956
+ trackClassifierTelemetry({
1957
+ workspaceId,
1958
+ predictedCollection: classified2.collection,
1959
+ confidence: classified2.confidence,
1960
+ autoRouted: false,
1961
+ reasonCategory: "low-confidence",
1962
+ explicitCollectionProvided: true,
1963
+ outcome: "fallback"
1964
+ });
1965
+ }
1966
+ return { resolvedCollection: collection, classifierMeta: classifierMeta2 };
1967
+ }
1968
+ return {
1969
+ resolvedCollection: collection,
1970
+ classifierMeta: {
1971
+ enabled: true,
1972
+ autoRouted: false,
1973
+ agrees: false,
1974
+ abstained: true,
1975
+ topConfidence: 0,
1976
+ confidence: 0,
1977
+ reasons: [],
1978
+ candidates: [],
1979
+ agentProvidedCollection: collection
1980
+ }
1981
+ };
1982
+ }
1983
+ if (!classifierFlagOn) {
1984
+ return { earlyResult: buildCollectionRequiredResult() };
1985
+ }
1986
+ const classified = classifyCollection(name, description);
1987
+ if (!classified) {
1988
+ trackClassifierTelemetry({
1989
+ workspaceId,
1990
+ predictedCollection: "unknown",
1991
+ confidence: 0,
1992
+ autoRouted: false,
1993
+ reasonCategory: "low-confidence",
1994
+ explicitCollectionProvided,
1995
+ outcome: "fallback"
1996
+ });
1997
+ return { earlyResult: buildClassifierUnknownResult() };
1998
+ }
1999
+ const { provisionedCollections, provisionedCandidates } = await getProvisionedCollectionCandidates(classified, supportedCollections);
2000
+ if (!provisionedCollections.has(classified.collection)) {
2001
+ trackClassifierTelemetry({
2002
+ workspaceId,
2003
+ predictedCollection: classified.collection,
2004
+ confidence: classified.confidence,
2005
+ autoRouted: false,
2006
+ reasonCategory: "non-provisioned",
2007
+ explicitCollectionProvided,
2008
+ outcome: "fallback"
2009
+ });
2010
+ return {
2011
+ earlyResult: buildUnsupportedProvisioningResult(classified, provisionedCandidates)
2012
+ };
2013
+ }
2014
+ const autoRoute = shouldAutoRouteClassification(classified);
2015
+ const ambiguousRoute = isClassificationAmbiguous(classified);
2016
+ const classifierMeta = {
2017
+ enabled: true,
2018
+ autoRouted: autoRoute,
2019
+ agrees: true,
2020
+ abstained: false,
2021
+ topConfidence: classified.topConfidence,
2022
+ confidence: classified.confidence,
2023
+ reasons: classified.reasons,
2024
+ candidates: provisionedCandidates
2025
+ };
2026
+ if (!autoRoute) {
2027
+ trackClassifierTelemetry({
2028
+ workspaceId,
2029
+ predictedCollection: classified.collection,
2030
+ confidence: classified.confidence,
2031
+ autoRouted: false,
2032
+ reasonCategory: ambiguousRoute ? "ambiguous" : "low-confidence",
2033
+ explicitCollectionProvided,
2034
+ outcome: "fallback"
2035
+ });
2036
+ return {
2037
+ classifierMeta,
2038
+ earlyResult: buildAmbiguousRouteResult(classified, classifierMeta, ambiguousRoute)
2039
+ };
2040
+ }
2041
+ trackClassifierTelemetry({
2042
+ workspaceId,
2043
+ predictedCollection: classified.collection,
2044
+ confidence: classified.confidence,
2045
+ autoRouted: true,
2046
+ reasonCategory: "auto-routed",
2047
+ explicitCollectionProvided,
2048
+ outcome: "auto-routed"
2049
+ });
2050
+ return {
2051
+ resolvedCollection: classified.collection,
2052
+ classifierMeta
2053
+ };
2054
+ }
2055
+ var captureSuccessOutputSchema = z2.object({
2056
+ entryId: z2.string(),
2057
+ collection: z2.string(),
2058
+ name: z2.string(),
2059
+ status: z2.enum(["draft", "committed", "proposed"]),
2060
+ qualityScore: z2.number(),
2061
+ qualityVerdict: z2.record(z2.unknown()).optional(),
2062
+ classifier: captureClassifierSchema.optional(),
2063
+ studioUrl: z2.string().optional()
2064
+ }).strict();
2065
+ var captureClassifierOnlyOutputSchema = z2.object({
2066
+ classifier: captureClassifierSchema
2067
+ }).strict();
2068
+ var captureOutputSchema = z2.union([
2069
+ captureSuccessOutputSchema,
2070
+ captureClassifierOnlyOutputSchema
2071
+ ]);
2072
+ var batchCaptureOutputSchema = z2.object({
2073
+ captured: z2.array(z2.object({
2074
+ entryId: z2.string(),
2075
+ collection: z2.string(),
2076
+ name: z2.string()
2077
+ })),
2078
+ total: z2.number(),
2079
+ failed: z2.number(),
2080
+ failedEntries: z2.array(z2.object({
2081
+ index: z2.number(),
2082
+ collection: z2.string(),
2083
+ name: z2.string(),
2084
+ error: z2.string()
2085
+ })).optional()
2086
+ });
2087
+ function registerSmartCaptureTools(server) {
2088
+ const supportedCollections = new Set(
2089
+ CLASSIFIABLE_COLLECTIONS.filter((slug) => PROFILES.has(slug))
2090
+ );
2091
+ const captureTool = server.registerTool(
2092
+ "capture",
2093
+ {
2094
+ title: "Capture",
2095
+ 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, bets, insights, assumptions, principles, 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, architecture) 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.",
2096
+ inputSchema: captureSchema.shape,
2097
+ annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: false }
2098
+ },
2099
+ withEnvelope(async ({ collection, name, description, context, entryId, canonicalKey, data: userData, links, autoCommit }) => {
2100
+ requireWriteAccess();
2101
+ const wsCtx = await getWorkspaceContext();
2102
+ const explicitCollectionProvided = typeof collection === "string" && collection.trim().length > 0;
2103
+ const classifierFlagOn = await isFeatureEnabled(
2104
+ CAPTURE_WITHOUT_THINKING_FLAG,
2105
+ wsCtx.workspaceId,
2106
+ wsCtx.workspaceSlug
2107
+ );
2108
+ const resolution = await resolveCaptureCollection({
2109
+ collection,
2110
+ name,
2111
+ description,
2112
+ classifierFlagOn,
2113
+ supportedCollections,
2114
+ workspaceId: wsCtx.workspaceId,
2115
+ explicitCollectionProvided
2116
+ });
2117
+ if (resolution.earlyResult) {
2118
+ return resolution.earlyResult;
2119
+ }
2120
+ const resolvedCollection = resolution.resolvedCollection;
2121
+ const classifierMeta = resolution.classifierMeta;
2122
+ if (!resolvedCollection) {
2123
+ return buildCollectionRequiredResult();
2124
+ }
2125
+ const profile = PROFILES.get(resolvedCollection) ?? FALLBACK_PROFILE;
2126
+ const col = await mcpQuery("chain.getCollection", { slug: resolvedCollection });
2127
+ if (!col) {
2128
+ const displayName = resolvedCollection.split("-").map((w) => w.charAt(0).toUpperCase() + w.slice(1)).join(" ");
2129
+ return {
2130
+ content: [{
2131
+ type: "text",
2132
+ text: `Collection \`${resolvedCollection}\` not found.
2133
+
2134
+ **To create it**, run:
2135
+ \`\`\`
2136
+ collections action=create slug="${resolvedCollection}" name="${displayName}" description="..."
2137
+ \`\`\`
2138
+
2139
+ Or use \`collections action=list\` to see available collections.`
2140
+ }],
2141
+ structuredContent: failure(
2142
+ "NOT_FOUND",
2143
+ `Collection '${resolvedCollection}' not found.`,
2144
+ "Create the collection first, or use collections action=list to see available ones.",
2145
+ [
2146
+ { tool: "collections", description: "Create collection", parameters: { action: "create", slug: resolvedCollection, name: displayName } },
2147
+ { tool: "collections", description: "List collections", parameters: { action: "list" } }
2148
+ ]
2149
+ )
2150
+ };
2151
+ }
2152
+ const data = {};
2153
+ const today = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
2154
+ for (const field of col.fields ?? []) {
2155
+ const key = field.key;
2156
+ if (key === profile.descriptionField) {
2157
+ data[key] = description;
2158
+ } else if (field.type === "array" || field.type === "multi-select") {
2159
+ data[key] = [];
2160
+ } else if (field.type === "select") {
2161
+ } else {
2162
+ data[key] = "";
2163
+ }
2164
+ }
2165
+ for (const def of profile.defaults) {
2166
+ if (def.value === "today") {
2167
+ data[def.key] = today;
2168
+ } else if (def.value !== "infer") {
2169
+ data[def.key] = def.value;
2170
+ }
2171
+ }
2172
+ if (profile.inferField) {
2173
+ const inferred = profile.inferField({
2174
+ collection: resolvedCollection,
2175
+ name,
2176
+ description,
2177
+ context,
2178
+ data,
2179
+ entryId: "",
2180
+ linksCreated: [],
2181
+ linksSuggested: [],
2182
+ collectionFields: col.fields ?? []
2183
+ });
2184
+ for (const [key, val] of Object.entries(inferred)) {
2185
+ if (val !== void 0 && val !== "") {
2186
+ data[key] = val;
2187
+ }
2188
+ }
2189
+ }
2190
+ if (userData && typeof userData === "object") {
2191
+ for (const [key, val] of Object.entries(userData)) {
2192
+ if (key !== "name") data[key] = val;
2193
+ }
2194
+ }
2195
+ data[profile.descriptionField || "description"] = description;
2196
+ const status = "draft";
2197
+ const agentId = getAgentSessionId();
2198
+ let finalEntryId;
2199
+ let internalId;
2200
+ try {
2201
+ const result = await mcpMutation("chain.createEntry", {
2202
+ collectionSlug: resolvedCollection,
2203
+ entryId: entryId ?? void 0,
2204
+ name,
2205
+ status,
2206
+ data,
2207
+ canonicalKey,
2208
+ createdBy: agentId ? `agent:${agentId}` : "capture",
2209
+ sessionId: agentId ?? void 0
2210
+ });
2211
+ internalId = result.docId;
2212
+ finalEntryId = result.entryId;
2213
+ } catch (error) {
2214
+ const msg = error instanceof Error ? error.message : String(error);
2215
+ if (msg.includes("Duplicate") || msg.includes("already exists")) {
2216
+ return {
2217
+ content: [{
2218
+ type: "text",
2219
+ text: `# Cannot Capture \u2014 Duplicate Detected
2220
+
2221
+ ${msg}
2222
+
2223
+ Use \`entries action=get\` to inspect the existing entry, or \`update-entry\` to modify it.`
2224
+ }],
2225
+ structuredContent: failure(
2226
+ "DUPLICATE",
2227
+ msg,
2228
+ "Use entries action=get to inspect the existing entry.",
2229
+ [
2230
+ { tool: "entries", description: "Get existing entry", parameters: { action: "get", entryId: entryId ?? name } },
2231
+ { tool: "update-entry", description: "Update existing entry", parameters: { entryId: entryId ?? "" } }
2232
+ ]
2233
+ )
2234
+ };
2235
+ }
2236
+ throw error;
2237
+ }
2238
+ const linksCreated = [];
2239
+ const linksSuggested = [];
2240
+ const userLinkResults = [];
2241
+ const skipAutoDiscovery = links && links.length > 0;
2242
+ const searchQuery = extractSearchTerms(name, description);
2243
+ if (searchQuery && !skipAutoDiscovery) {
2244
+ const [searchResults, allCollections] = await Promise.all([
2245
+ mcpQuery("chain.searchEntries", { query: searchQuery }),
2246
+ mcpQuery("chain.listCollections")
2247
+ ]);
2248
+ const collMap = /* @__PURE__ */ new Map();
2249
+ for (const c of allCollections) collMap.set(c._id, c.slug);
2250
+ const candidates = (searchResults ?? []).filter((r) => r.entryId !== finalEntryId && r._id !== internalId).map((r) => {
2251
+ const conf = computeLinkConfidence(r, name, description, resolvedCollection, collMap.get(r.collectionId) ?? "unknown");
2252
+ return {
2253
+ ...r,
2254
+ collSlug: collMap.get(r.collectionId) ?? "unknown",
2255
+ confidence: conf.score,
2256
+ confidenceReason: conf.reason
2257
+ };
2258
+ }).sort((a, b) => b.confidence - a.confidence);
2259
+ for (const c of candidates) {
2260
+ if (linksCreated.length >= MAX_AUTO_LINKS) break;
2261
+ if (c.confidence < AUTO_LINK_CONFIDENCE_THRESHOLD) break;
2262
+ if (!c.entryId || !finalEntryId) continue;
2263
+ const { type: relationType, reason: relationReason } = inferRelationType(resolvedCollection, c.collSlug, profile);
2264
+ try {
2265
+ await mcpMutation("chain.createEntryRelation", {
2266
+ fromEntryId: finalEntryId,
2267
+ toEntryId: c.entryId,
2268
+ type: relationType,
2269
+ sessionId: agentId ?? void 0
2270
+ });
2271
+ linksCreated.push({
2272
+ targetEntryId: c.entryId,
2273
+ targetName: c.name,
2274
+ targetCollection: c.collSlug,
2275
+ relationType,
2276
+ linkReason: `confidence ${c.confidence} (${c.confidenceReason}) + ${relationReason}`
2277
+ });
2278
+ } catch {
2279
+ }
2280
+ }
2281
+ const linkedIds = new Set(linksCreated.map((l) => l.targetEntryId));
2282
+ for (const c of candidates) {
2283
+ if (linksSuggested.length >= MAX_SUGGESTIONS) break;
2284
+ if (linkedIds.has(c.entryId)) continue;
2285
+ if (c.confidence < 10) continue;
2286
+ const preview = extractPreview(c.data, 80);
2287
+ 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`;
2288
+ linksSuggested.push({
2289
+ entryId: c.entryId,
2290
+ name: c.name,
2291
+ collection: c.collSlug,
2292
+ reason,
2293
+ preview
2294
+ });
2295
+ }
2296
+ }
2297
+ if (links && links.length > 0 && finalEntryId) {
2298
+ for (const link of links) {
2299
+ try {
2300
+ await mcpMutation("chain.createEntryRelation", {
2301
+ fromEntryId: finalEntryId,
2302
+ toEntryId: link.to,
2303
+ type: link.type,
2304
+ sessionId: agentId ?? void 0
2305
+ });
2306
+ userLinkResults.push({ label: `\u2713 ${link.type} \u2192 ${link.to}`, ok: true });
2307
+ linksCreated.push({
2308
+ targetEntryId: link.to,
2309
+ targetName: link.to,
2310
+ targetCollection: "unknown",
2311
+ relationType: link.type
2312
+ });
2313
+ } catch (e) {
2314
+ const msg = e instanceof Error ? e.message : "failed";
2315
+ userLinkResults.push({ label: `\u2717 ${link.type} \u2192 ${link.to}: ${msg}`, ok: false });
2316
+ }
2317
+ }
2318
+ }
2319
+ const captureCtx = {
2320
+ collection: resolvedCollection,
2321
+ name,
2322
+ description,
2323
+ context,
2324
+ data,
2325
+ entryId: finalEntryId,
2326
+ canonicalKey,
2327
+ linksCreated,
2328
+ linksSuggested,
2329
+ collectionFields: col.fields ?? []
2330
+ };
2331
+ const quality = scoreQuality(captureCtx, profile);
2332
+ let cardinalityWarning = null;
2333
+ const resolvedCK = canonicalKey ?? captureCtx.canonicalKey;
2334
+ if (resolvedCK) {
2335
+ try {
2336
+ const check = await mcpQuery("chain.checkCardinalityWarning", {
2337
+ canonicalKey: resolvedCK
2338
+ });
2339
+ if (check?.warning) {
2340
+ cardinalityWarning = check.warning;
2341
+ }
2342
+ } catch {
2343
+ }
2344
+ }
2345
+ const contradictionWarnings = await runContradictionCheck(name, description);
2346
+ if (contradictionWarnings.length > 0) {
2347
+ await recordSessionActivity({ contradictionWarning: true });
2348
+ }
2349
+ let coachingSection = "";
2350
+ let verdictResult = null;
2351
+ try {
2352
+ verdictResult = await mcpMutation("quality.evaluateHeuristicAndSchedule", {
2353
+ entryId: finalEntryId,
2354
+ context: "capture"
2355
+ });
2356
+ if (verdictResult?.verdict && verdictResult.verdict.tier !== "passive" && verdictResult.verdict.criteria.length > 0) {
2357
+ coachingSection = formatRubricCoaching(verdictResult);
2358
+ }
2359
+ } catch {
2360
+ }
2361
+ if (verdictResult?.verdict) {
2362
+ try {
2363
+ const wsForTracking = await getWorkspaceContext();
2364
+ const v = verdictResult.verdict;
2365
+ const failedCount = (v.criteria ?? []).filter((c) => !c.passed).length;
2366
+ trackQualityVerdict(wsForTracking.workspaceId, {
2367
+ entry_id: finalEntryId,
2368
+ entry_type: v.canonicalKey ?? resolvedCollection,
2369
+ tier: v.tier,
2370
+ context: "capture",
2371
+ passed: v.passed,
2372
+ source: verdictResult.source ?? "heuristic",
2373
+ criteria_total: v.criteria?.length ?? 0,
2374
+ criteria_failed: failedCount,
2375
+ llm_scheduled: v.tier !== "passive"
2376
+ });
2377
+ } catch {
2378
+ }
2379
+ }
2380
+ const shouldAutoCommit = autoCommit === true || autoCommit === void 0 && wsCtx.governanceMode === "open";
2381
+ let finalStatus = "draft";
2382
+ let commitError = null;
2383
+ if (shouldAutoCommit && finalEntryId) {
2384
+ try {
2385
+ const commitResult = await mcpMutation("chain.commitEntry", {
2386
+ entryId: finalEntryId,
2387
+ author: agentId ? `agent:${agentId}` : void 0,
2388
+ sessionId: agentId ?? void 0
2389
+ });
2390
+ finalStatus = commitResult?.status === "proposal_created" ? "proposed" : "committed";
2391
+ if (finalStatus === "committed") {
2392
+ await recordSessionActivity({ entryModified: internalId });
2393
+ }
2394
+ } catch (e) {
2395
+ commitError = e instanceof Error ? e.message : "unknown error";
2396
+ }
2397
+ }
2398
+ const lines = [
2399
+ `# Captured: ${finalEntryId || name}`,
2400
+ `**${name}** added to \`${resolvedCollection}\` as \`${finalStatus}\``,
2401
+ `**Workspace:** ${wsCtx.workspaceSlug} (${wsCtx.workspaceId})`
2402
+ ];
2403
+ if (classifierMeta) {
2404
+ lines.push("");
2405
+ lines.push("## Classification");
2406
+ if (classifierMeta.abstained) {
2407
+ lines.push(`No classifier coverage for \`${resolvedCollection}\` \u2014 entry accepted as-is.`);
2408
+ } else if (classifierMeta.autoRouted) {
2409
+ lines.push(`Auto-routed to \`${resolvedCollection}\` (${classifierMeta.topConfidence}% confidence).`);
2410
+ if (classifierMeta.reasons.length > 0) {
2411
+ lines.push(`Reason: ${classifierMeta.reasons.join("; ")}.`);
2412
+ }
2413
+ lines.push(`Override: rerun with explicit \`collection\` if wrong.`);
2414
+ } else if (classifierMeta.agrees) {
2415
+ lines.push(`Classifier confirms \`${resolvedCollection}\` (${classifierMeta.topConfidence}% confidence).`);
2416
+ } else {
2417
+ const suggested = classifierMeta.candidates[0]?.collection ?? "unknown";
2418
+ lines.push(`Classifier suggests \`${suggested}\` (${classifierMeta.topConfidence}% confidence) \u2014 review classification.`);
2419
+ if (classifierMeta.reasons.length > 0) {
2420
+ lines.push(`Reason: ${classifierMeta.reasons.join("; ")}.`);
2421
+ }
2422
+ if (classifierMeta.overrideCommand) {
2423
+ lines.push(`Override: \`${classifierMeta.overrideCommand}\``);
2424
+ }
2425
+ }
2426
+ }
2427
+ const appUrl = process.env.PRODUCTBRAIN_APP_URL ?? "https://productbrain.io";
2428
+ const studioUrl = resolvedCollection === "bets" ? `${appUrl.replace(/\/$/, "")}/w/${wsCtx.workspaceSlug}/studio/${internalId}` : void 0;
2429
+ if (studioUrl) {
2430
+ lines.push("");
2431
+ lines.push(`**View in Studio:** ${studioUrl}`);
2432
+ }
2433
+ if (linksCreated.length > 0) {
2434
+ lines.push("");
2435
+ lines.push(`## Auto-linked (${linksCreated.length})`);
2436
+ for (const link of linksCreated) {
2437
+ const reason = link.linkReason ? ` \u2014 because ${link.linkReason}` : "";
2438
+ lines.push(`- -> **${link.relationType}** ${link.targetEntryId}: ${link.targetName} [${link.targetCollection}]${reason}`);
2439
+ }
2440
+ }
2441
+ if (userLinkResults.length > 0) {
2442
+ lines.push("");
2443
+ lines.push("## Requested links");
2444
+ for (const r of userLinkResults) lines.push(`- ${r.label}`);
2445
+ }
2446
+ if (finalStatus === "committed") {
2447
+ const wasAutoCommitted = autoCommit === void 0 && wsCtx.governanceMode === "open";
2448
+ lines.push("");
2449
+ lines.push(`## Committed: ${finalEntryId}`);
2450
+ if (wasAutoCommitted) {
2451
+ lines.push(`**${name}** added to your knowledge base.`);
2452
+ } else {
2453
+ lines.push(`**${name}** promoted to SSOT on the Chain.`);
2454
+ }
2455
+ if (GOVERNED_COLLECTIONS.has(resolvedCollection)) {
2456
+ lines.push(`_Note: \`${resolvedCollection}\` is a governed collection \u2014 ensure this entry has been reviewed._`);
2457
+ }
2458
+ } else if (finalStatus === "proposed") {
2459
+ lines.push("");
2460
+ lines.push(`## Proposal created: ${finalEntryId}`);
2461
+ lines.push(`**${name}** requires consent before it can be committed, so a proposal was created instead of publishing directly.`);
2462
+ } else if (commitError) {
2463
+ lines.push("");
2464
+ lines.push("## Commit failed");
2465
+ lines.push(`Error: ${commitError}. Entry saved as draft \u2014 use \`commit-entry entryId="${finalEntryId}"\` to promote when ready.`);
2466
+ }
2467
+ if (linksSuggested.length > 0) {
2468
+ lines.push("");
2469
+ lines.push("## Suggested links (review and use `relations action=create`)");
2470
+ for (let i = 0; i < linksSuggested.length; i++) {
2471
+ const s = linksSuggested[i];
2472
+ const preview = s.preview ? ` \u2014 ${s.preview}` : "";
2473
+ lines.push(`${i + 1}. **${s.entryId ?? "(no ID)"}**: ${s.name} [${s.collection}]${preview}`);
2474
+ }
2475
+ }
2476
+ lines.push("");
2477
+ lines.push(formatQualityReport(quality));
2478
+ const failedChecks = quality.checks.filter((c) => !c.passed);
2479
+ if (failedChecks.length > 0) {
2480
+ lines.push("");
2481
+ lines.push(`_To improve: \`update-entry entryId="${finalEntryId}"\` to fill missing fields._`);
2482
+ }
2483
+ const isBetOrGoal = resolvedCollection === "bets" || resolvedCK === "bet" || resolvedCK === "goal";
2484
+ const hasStrategyLink = linksCreated.some((l) => l.targetCollection === "strategy");
2485
+ if (isBetOrGoal && !hasStrategyLink) {
2486
+ lines.push("");
2487
+ lines.push(
2488
+ `**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.`
2489
+ );
2490
+ await recordSessionActivity({ strategyLinkWarnedForEntryId: internalId });
2491
+ }
2492
+ if (cardinalityWarning) {
2493
+ lines.push("");
2494
+ lines.push(`**Cardinality warning:** ${cardinalityWarning}`);
2495
+ }
2496
+ if (contradictionWarnings.length > 0) {
2497
+ lines.push("");
2498
+ lines.push("\u26A0 Contradiction check: proposed entry matched existing governance entries:");
2499
+ for (const w of contradictionWarnings) {
2500
+ lines.push(`- ${w.name} (${w.collection}, ${w.entryId}) \u2014 has 'governs' relation to ${w.governsCount} entries`);
2501
+ }
2502
+ lines.push("Run `context action=gather` on these entries before committing.");
2503
+ }
2504
+ if (coachingSection) {
2505
+ lines.push("");
2506
+ lines.push(coachingSection);
2507
+ }
2508
+ lines.push("");
2509
+ lines.push("## Next Steps");
2510
+ const eid = finalEntryId || "(check entry ID)";
2511
+ if (finalStatus === "committed") {
2512
+ lines.push(`1. **Connect it:** \`graph action=suggest entryId="${eid}"\` \u2014 discover additional links`);
2513
+ if (failedChecks.length > 0) {
2514
+ lines.push(`2. **Improve quality:** \`update-entry entryId="${eid}"\` \u2014 fill missing fields`);
2515
+ }
2516
+ } else if (finalStatus === "proposed") {
2517
+ lines.push(`1. **Connect it:** \`graph action=suggest entryId="${eid}"\` \u2014 discover additional links to support the proposal`);
2518
+ if (failedChecks.length > 0) {
2519
+ lines.push(`2. **Improve quality:** \`update-entry entryId="${eid}"\` \u2014 strengthen the entry before approval`);
2520
+ }
2521
+ } else {
2522
+ if (userLinkResults.length === 0) {
2523
+ lines.push(`1. **Connect it:** \`graph action=suggest entryId="${eid}"\` \u2014 discover what this should link to`);
2524
+ }
2525
+ lines.push(`${userLinkResults.length === 0 ? "2" : "1"}. **Commit it:** \`commit-entry entryId="${eid}"\` \u2014 promote from draft to SSOT on the Chain`);
2526
+ if (failedChecks.length > 0) {
2527
+ lines.push(`${userLinkResults.length === 0 ? "3" : "2"}. **Improve quality:** \`update-entry entryId="${eid}"\` \u2014 fill missing fields`);
2528
+ }
2529
+ }
2530
+ try {
2531
+ const readiness = await mcpQuery("chain.workspaceReadiness");
2532
+ if (readiness && readiness.gaps && readiness.gaps.length > 0) {
2533
+ const topGaps = readiness.gaps.slice(0, 2);
2534
+ lines.push("");
2535
+ lines.push(`## Workspace Readiness: ${readiness.score}%`);
2536
+ for (const gap of topGaps) {
2537
+ lines.push(`- _${gap.label}:_ ${gap.guidance}`);
2538
+ }
2539
+ }
2540
+ } catch {
2541
+ }
2542
+ const next = [];
2543
+ if (finalStatus === "committed") {
2544
+ next.push({ tool: "graph", description: "Discover connections", parameters: { action: "suggest", entryId: finalEntryId } });
2545
+ } else if (finalStatus === "proposed") {
2546
+ next.push({ tool: "graph", description: "Discover connections", parameters: { action: "suggest", entryId: finalEntryId } });
2547
+ } else {
2548
+ if (userLinkResults.length === 0) {
2549
+ next.push({ tool: "graph", description: "Discover links", parameters: { action: "suggest", entryId: finalEntryId } });
2550
+ }
2551
+ next.push({ tool: "commit-entry", description: "Commit to Chain", parameters: { entryId: finalEntryId } });
2552
+ }
2553
+ const summary = finalStatus === "committed" ? `Captured and committed ${finalEntryId} (${name}) to ${resolvedCollection}. Quality ${quality.score}/10.` : finalStatus === "proposed" ? `Captured ${finalEntryId} (${name}) in ${resolvedCollection} and created a proposal for commit. Quality ${quality.score}/10.` : `Captured ${finalEntryId} (${name}) as draft in ${resolvedCollection}. Quality ${quality.score}/10.`;
2554
+ const toolResult = {
2555
+ content: [{ type: "text", text: lines.join("\n") }],
2556
+ structuredContent: success(
2557
+ summary,
2558
+ {
2559
+ entryId: finalEntryId,
2560
+ collection: resolvedCollection,
2561
+ name,
2562
+ status: finalStatus,
2563
+ qualityScore: quality.score,
2564
+ qualityVerdict: verdictResult?.verdict ? { ...verdictResult.verdict, source: verdictResult.source ?? "heuristic" } : void 0,
2565
+ ...classifierMeta && { classifier: classifierMeta },
2566
+ ...studioUrl && { studioUrl }
2567
+ },
2568
+ next
2569
+ )
2570
+ };
2571
+ return toolResult;
2572
+ })
2573
+ );
2574
+ trackWriteTool(captureTool);
2575
+ const batchCaptureTool = server.registerTool(
2576
+ "batch-capture",
2577
+ {
2578
+ title: "Batch Capture",
2579
+ 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.",
2580
+ inputSchema: batchCaptureSchema.shape,
2581
+ annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: false }
2582
+ },
2583
+ withEnvelope(async ({ entries }) => {
2584
+ requireWriteAccess();
2585
+ const agentId = getAgentSessionId();
2586
+ const createdBy = agentId ? `agent:${agentId}` : "capture";
2587
+ const results = [];
2588
+ await server.sendLoggingMessage({
2589
+ level: "info",
2590
+ data: `Batch capturing ${entries.length} entries...`,
2591
+ logger: "product-brain"
2592
+ });
2593
+ const allCollections = await mcpQuery("chain.listCollections");
2594
+ const collCache = /* @__PURE__ */ new Map();
2595
+ for (const c of allCollections) collCache.set(c.slug, c);
2596
+ const collIdToSlug = /* @__PURE__ */ new Map();
2597
+ for (const c of allCollections) collIdToSlug.set(c._id, c.slug);
2598
+ for (let entryIdx = 0; entryIdx < entries.length; entryIdx++) {
2599
+ const entry = entries[entryIdx];
2600
+ if (entryIdx > 0 && entryIdx % 5 === 0) {
2601
+ await server.sendLoggingMessage({
2602
+ level: "info",
2603
+ data: `Captured ${entryIdx}/${entries.length} entries...`,
2604
+ logger: "product-brain"
2605
+ });
2606
+ }
2607
+ const profile = PROFILES.get(entry.collection) ?? FALLBACK_PROFILE;
2608
+ const col = collCache.get(entry.collection);
2609
+ if (!col) {
2610
+ results.push({ name: entry.name, collection: entry.collection, entryId: "", ok: false, autoLinks: 0, error: `Collection "${entry.collection}" not found` });
2611
+ continue;
2612
+ }
2613
+ const data = {};
2614
+ const today = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
2615
+ for (const field of col.fields ?? []) {
2616
+ const key = field.key;
2617
+ if (key === profile.descriptionField) {
2618
+ data[key] = entry.description;
2619
+ } else if (field.type === "array" || field.type === "multi-select") {
2620
+ data[key] = [];
2621
+ } else if (field.type === "select") {
2622
+ } else {
2623
+ data[key] = "";
2624
+ }
2625
+ }
2626
+ for (const def of profile.defaults) {
2627
+ if (def.value === "today") data[def.key] = today;
2628
+ else if (def.value !== "infer") data[def.key] = def.value;
2629
+ }
2630
+ if (profile.inferField) {
2631
+ const inferred = profile.inferField({
2632
+ collection: entry.collection,
2633
+ name: entry.name,
2634
+ description: entry.description,
2635
+ data,
2636
+ entryId: "",
2637
+ linksCreated: [],
2638
+ linksSuggested: [],
2639
+ collectionFields: col.fields ?? []
2640
+ });
2641
+ for (const [key, val] of Object.entries(inferred)) {
2642
+ if (val !== void 0 && val !== "") data[key] = val;
2643
+ }
2644
+ }
2645
+ if (!data[profile.descriptionField] && !data.description && !data.canonical) {
2646
+ data[profile.descriptionField || "description"] = entry.description;
2647
+ }
2648
+ try {
2649
+ const result = await mcpMutation("chain.createEntry", {
2650
+ collectionSlug: entry.collection,
2651
+ entryId: entry.entryId ?? void 0,
2652
+ name: entry.name,
2653
+ status: "draft",
2654
+ data,
2655
+ createdBy,
2656
+ sessionId: agentId ?? void 0
2657
+ });
2658
+ const internalId = result.docId;
2659
+ const finalEntryId = result.entryId;
2660
+ let autoLinkCount = 0;
2661
+ const searchQuery = extractSearchTerms(entry.name, entry.description);
2662
+ if (searchQuery) {
2663
+ try {
2664
+ const searchResults = await mcpQuery("chain.searchEntries", { query: searchQuery });
2665
+ const candidates = (searchResults ?? []).filter((r) => r.entryId !== finalEntryId).map((r) => {
2666
+ const conf = computeLinkConfidence(r, entry.name, entry.description, entry.collection, collIdToSlug.get(r.collectionId) ?? "unknown");
2667
+ return {
2668
+ ...r,
2669
+ collSlug: collIdToSlug.get(r.collectionId) ?? "unknown",
2670
+ confidence: conf.score
2671
+ };
2672
+ }).sort((a, b) => b.confidence - a.confidence);
2673
+ for (const c of candidates) {
2674
+ if (autoLinkCount >= MAX_AUTO_LINKS) break;
2675
+ if (c.confidence < AUTO_LINK_CONFIDENCE_THRESHOLD) break;
2676
+ if (!c.entryId) continue;
2677
+ const { type: relationType } = inferRelationType(entry.collection, c.collSlug, profile);
2678
+ try {
2679
+ await mcpMutation("chain.createEntryRelation", {
2680
+ fromEntryId: finalEntryId,
2681
+ toEntryId: c.entryId,
2682
+ type: relationType,
2683
+ sessionId: agentId ?? void 0
2684
+ });
2685
+ autoLinkCount++;
2686
+ } catch {
2687
+ }
2688
+ }
2689
+ } catch {
2690
+ }
2691
+ }
2692
+ results.push({ name: entry.name, collection: entry.collection, entryId: finalEntryId, ok: true, autoLinks: autoLinkCount });
2693
+ } catch (error) {
2694
+ const msg = error instanceof Error ? error.message : String(error);
2695
+ results.push({ name: entry.name, collection: entry.collection, entryId: "", ok: false, autoLinks: 0, error: msg });
2696
+ }
2697
+ }
2698
+ const created = results.filter((r) => r.ok);
2699
+ const failed = results.filter((r) => !r.ok);
2700
+ await server.sendLoggingMessage({
2701
+ level: "info",
2702
+ data: `Batch complete. ${created.length} succeeded, ${failed.length} failed.`,
2703
+ logger: "product-brain"
2704
+ });
2705
+ const totalAutoLinks = created.reduce((sum, r) => sum + r.autoLinks, 0);
2706
+ const byCollection = /* @__PURE__ */ new Map();
2707
+ for (const r of created) {
2708
+ byCollection.set(r.collection, (byCollection.get(r.collection) ?? 0) + 1);
2709
+ }
2710
+ const lines = [
2711
+ `# Batch Capture Complete`,
2712
+ `**${created.length}** created, **${failed.length}** failed out of ${entries.length} total.`,
2713
+ `**Auto-links created:** ${totalAutoLinks}`,
2714
+ ""
2715
+ ];
2716
+ if (byCollection.size > 0) {
2717
+ lines.push("## By Collection");
2718
+ for (const [col, count] of byCollection) {
2719
+ lines.push(`- \`${col}\`: ${count} entries`);
2720
+ }
2721
+ lines.push("");
2722
+ }
2723
+ if (created.length > 0) {
2724
+ lines.push("## Created");
2725
+ for (const r of created) {
2726
+ const linkNote = r.autoLinks > 0 ? ` (${r.autoLinks} auto-links)` : "";
2727
+ lines.push(`- **${r.entryId}**: ${r.name} [${r.collection}]${linkNote}`);
2728
+ }
2729
+ }
2730
+ if (failed.length > 0) {
2731
+ lines.push("");
2732
+ lines.push("## Failed");
2733
+ for (const r of failed) {
2734
+ lines.push(`- ${r.name} [${r.collection}]: _${r.error}_`);
2735
+ }
2736
+ lines.push("");
2737
+ lines.push(`_If failed > 0, inspect \`failedEntries\` in the structured response and retry individually._`);
2738
+ }
2739
+ const entryIds = created.map((r) => r.entryId);
2740
+ if (entryIds.length > 0) {
2741
+ lines.push("");
2742
+ lines.push("## Next Steps");
2743
+ lines.push(`- **Connect:** Run \`graph action=suggest\` on key entries to build the knowledge graph`);
2744
+ lines.push(`- **Commit:** Use \`commit-entry\` to promote drafts to SSOT`);
2745
+ lines.push(`- **Quality:** Run \`quality action=check\` on individual entries to assess completeness`);
2746
+ }
2747
+ const summary = failed.length > 0 ? `Batch captured ${created.length}/${entries.length} entries (${failed.length} failed).` : `Batch captured ${created.length} entries successfully.`;
2748
+ const next = created.length > 0 ? [
2749
+ { tool: "graph", description: "Discover connections", parameters: { action: "suggest", entryId: created[0].entryId } },
2750
+ { tool: "commit-entry", description: "Commit first entry", parameters: { entryId: created[0].entryId } }
2751
+ ] : [];
2752
+ return {
2753
+ content: [{ type: "text", text: lines.join("\n") }],
2754
+ structuredContent: success(
2755
+ summary,
2756
+ {
2757
+ captured: created.map((r) => ({ entryId: r.entryId, collection: r.collection, name: r.name })),
2758
+ total: created.length,
2759
+ failed: failed.length,
2760
+ ...failed.length > 0 && {
2761
+ failedEntries: failed.map((r) => ({
2762
+ index: results.indexOf(r),
2763
+ collection: r.collection,
2764
+ name: r.name,
2765
+ error: r.error ?? "unknown error"
2766
+ }))
2767
+ }
2768
+ },
2769
+ next
2770
+ )
2771
+ };
2772
+ })
2773
+ );
2774
+ trackWriteTool(batchCaptureTool);
2775
+ }
2776
+ var STOP_WORDS = /* @__PURE__ */ new Set([
2777
+ "the",
2778
+ "and",
2779
+ "for",
2780
+ "are",
2781
+ "but",
2782
+ "not",
2783
+ "you",
2784
+ "all",
2785
+ "can",
2786
+ "has",
2787
+ "her",
2788
+ "was",
2789
+ "one",
2790
+ "our",
2791
+ "out",
2792
+ "day",
2793
+ "had",
2794
+ "hot",
2795
+ "how",
2796
+ "its",
2797
+ "may",
2798
+ "new",
2799
+ "now",
2800
+ "old",
2801
+ "see",
2802
+ "way",
2803
+ "who",
2804
+ "did",
2805
+ "get",
2806
+ "let",
2807
+ "say",
2808
+ "she",
2809
+ "too",
2810
+ "use",
2811
+ "from",
2812
+ "have",
2813
+ "been",
2814
+ "each",
2815
+ "that",
2816
+ "this",
2817
+ "with",
2818
+ "will",
2819
+ "they",
2820
+ "what",
2821
+ "when",
2822
+ "make",
2823
+ "like",
2824
+ "long",
2825
+ "look",
2826
+ "many",
2827
+ "some",
2828
+ "them",
2829
+ "than",
2830
+ "most",
2831
+ "only",
2832
+ "over",
2833
+ "such",
2834
+ "into",
2835
+ "also",
2836
+ "back",
2837
+ "just",
2838
+ "much",
2839
+ "must",
2840
+ "name",
2841
+ "very",
2842
+ "your",
2843
+ "after",
2844
+ "which",
2845
+ "their",
2846
+ "about",
2847
+ "would",
2848
+ "there",
2849
+ "should",
2850
+ "could",
2851
+ "other",
2852
+ "these",
2853
+ "first",
2854
+ "being",
2855
+ "those",
2856
+ "still",
2857
+ "where"
2858
+ ]);
2859
+ function tokenizeText(input) {
2860
+ return input.toLowerCase().replace(/[^\p{L}\p{N}\s]+/gu, " ").split(/\s+/).filter(Boolean);
2861
+ }
2862
+ async function runContradictionCheck(name, description) {
2863
+ const warnings = [];
2864
+ try {
2865
+ const keyTerms = tokenizeText(`${name} ${description}`).filter((w) => w.length >= 4 && !STOP_WORDS.has(w)).slice(0, 8);
2866
+ if (keyTerms.length === 0) return warnings;
2867
+ const searchQuery = keyTerms.slice(0, 5).join(" ");
2868
+ const [govResults, archResults] = await Promise.all([
2869
+ mcpQuery("chain.searchEntries", { query: searchQuery, collectionSlug: "business-rules" }),
2870
+ mcpQuery("chain.searchEntries", { query: searchQuery, collectionSlug: "architecture" })
2871
+ ]);
2872
+ const allGov = [...govResults ?? [], ...archResults ?? []].slice(0, 5);
2873
+ for (const entry of allGov) {
2874
+ const entryTokens = new Set(tokenizeText(`${entry.name} ${entry.data?.description ?? ""}`));
2875
+ const matched = keyTerms.filter((t) => entryTokens.has(t));
2876
+ if (matched.length < 3) continue;
2877
+ let governsCount = 0;
2878
+ try {
2879
+ const relations = await mcpQuery("chain.listEntryRelations", {
2880
+ entryId: entry.entryId
2881
+ });
2882
+ governsCount = (relations ?? []).filter((r) => r.type === "governs").length;
2883
+ } catch {
2884
+ }
2885
+ warnings.push({
2886
+ entryId: entry.entryId ?? "",
2887
+ name: entry.name,
2888
+ collection: entry.collectionSlug ?? "",
2889
+ governsCount
2890
+ });
2891
+ }
2892
+ } catch {
2893
+ }
2894
+ return warnings;
2895
+ }
2896
+ function formatRubricCoaching(result) {
2897
+ const { verdict, rogerMartin } = result;
2898
+ if (!verdict || verdict.criteria.length === 0) return "";
2899
+ const lines = ["## Semantic Quality"];
2900
+ const failed = (verdict.criteria ?? []).filter((c) => !c.passed);
2901
+ const total = verdict.criteria?.length ?? 0;
2902
+ const passedCount = total - failed.length;
2903
+ if (verdict.passed) {
2904
+ lines.push(`All ${total} rubric criteria pass for \`${verdict.canonicalKey}\` (${verdict.tier} tier).`);
2905
+ } else {
2906
+ lines.push(`${passedCount}/${total} criteria pass for \`${verdict.canonicalKey}\` (${verdict.tier} tier)`);
2907
+ lines.push("");
2908
+ for (const c of verdict.criteria) {
2909
+ const icon = c.passed ? "[x]" : "[ ]";
2910
+ const extra = c.passed ? "" : ` \u2014 ${c.hint}`;
2911
+ lines.push(`${icon} ${c.id}${extra}`);
2912
+ }
2913
+ if (verdict.weakest) {
2914
+ lines.push("");
2915
+ lines.push(`**Coaching hint:** ${verdict.weakest.hint}`);
2916
+ lines.push(`_Question to consider:_ ${verdict.weakest.questionTemplate}`);
2917
+ }
2918
+ }
2919
+ if (rogerMartin) {
2920
+ lines.push("");
2921
+ lines.push("### Roger Martin Test");
2922
+ if (rogerMartin.isStrategicChoice) {
2923
+ lines.push("This principle passes \u2014 the opposite is a reasonable strategic choice.");
2924
+ } else {
2925
+ lines.push(`This principle may not be a strategic choice. ${rogerMartin.reasoning}`);
2926
+ if (rogerMartin.suggestion) {
2927
+ lines.push(`_Suggestion:_ ${rogerMartin.suggestion}`);
2928
+ }
2929
+ }
2930
+ }
2931
+ return lines.join("\n");
2932
+ }
2933
+ function formatRubricVerdictSection(verdict) {
2934
+ if (!verdict || !verdict.criteria || verdict.criteria.length === 0) return "";
2935
+ const lines = ["## Semantic Quality"];
2936
+ const failed = verdict.criteria.filter((c) => !c.passed);
2937
+ const total = verdict.criteria.length;
2938
+ const passedCount = total - failed.length;
2939
+ const durationSuffix = verdict.llmDurationMs ? ` in ${(verdict.llmDurationMs / 1e3).toFixed(1)}s` : "";
2940
+ 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}` : "";
2941
+ if (failed.length === 0) {
2942
+ lines.push(`All ${total} rubric criteria pass for \`${verdict.canonicalKey}\` (${verdict.tier} tier, ${verdict.source} evaluation).${statusNote}`);
2943
+ } else {
2944
+ lines.push(`${passedCount}/${total} criteria pass for \`${verdict.canonicalKey}\` (${verdict.tier} tier, ${verdict.source} evaluation)${statusNote}`);
2945
+ lines.push("");
2946
+ for (const c of verdict.criteria) {
2947
+ const icon = c.passed ? "[x]" : "[ ]";
2948
+ const extra = c.passed ? "" : ` \u2014 ${c.hint}`;
2949
+ lines.push(`${icon} ${c.id}${extra}`);
2950
+ }
2951
+ if (verdict.weakest) {
2952
+ lines.push("");
2953
+ lines.push(`**Top improvement:** ${verdict.weakest.hint}`);
2954
+ }
2955
+ }
2956
+ if (verdict.rogerMartin) {
2957
+ const rm = verdict.rogerMartin;
2958
+ lines.push("");
2959
+ lines.push("### Roger Martin Test");
2960
+ if (rm.isStrategicChoice) {
2961
+ lines.push(`This is a real strategic choice \u2014 the opposite is reasonable. ${rm.reasoning}`);
2962
+ } else {
2963
+ lines.push(`This may not be a strategic choice. ${rm.reasoning}`);
2964
+ if (rm.suggestion) {
2965
+ lines.push(`_Suggestion:_ ${rm.suggestion}`);
2966
+ }
2967
+ }
2968
+ }
2969
+ return lines.join("\n");
2970
+ }
2971
+
2972
+ export {
2973
+ runWithAuth,
2974
+ runWithToolContext,
2975
+ getAgentSessionId,
2976
+ isSessionOriented,
2977
+ setSessionOriented,
2978
+ getApiKeyScope,
2979
+ startAgentSession,
2980
+ closeAgentSession,
2981
+ orphanAgentSession,
2982
+ recordSessionActivity,
2983
+ bootstrap,
2984
+ bootstrapHttp,
2985
+ getAuditLog,
2986
+ mcpCall,
2987
+ getWorkspaceId,
2988
+ getWorkspaceContext,
2989
+ mcpQuery,
2990
+ mcpMutation,
2991
+ requireActiveSession,
2992
+ requireWriteAccess,
2993
+ recoverSessionState,
2994
+ deriveEpistemicStatus,
2995
+ formatEpistemicLine,
2996
+ toEpistemicInput,
2997
+ extractPreview,
2998
+ translateStaleToolNames,
2999
+ initToolSurface,
3000
+ trackWriteTool,
3001
+ initFeatureFlags,
3002
+ CLASSIFIER_AUTO_ROUTE_THRESHOLD,
3003
+ CLASSIFIABLE_COLLECTIONS,
3004
+ classifyCollection,
3005
+ isClassificationAmbiguous,
3006
+ STARTER_COLLECTIONS,
3007
+ success,
3008
+ failure,
3009
+ parseOrFail,
3010
+ unknownAction,
3011
+ successResult,
3012
+ failureResult,
3013
+ notFoundResult,
3014
+ validationResult,
3015
+ withEnvelope,
3016
+ inferStrategyCategory,
3017
+ formatQualityReport,
3018
+ checkEntryQuality,
3019
+ captureSchema,
3020
+ batchCaptureSchema,
3021
+ captureClassifierSchema,
3022
+ captureOutputSchema,
3023
+ batchCaptureOutputSchema,
3024
+ registerSmartCaptureTools,
3025
+ runContradictionCheck,
3026
+ formatRubricCoaching,
3027
+ formatRubricVerdictSection
3028
+ };
3029
+ //# sourceMappingURL=chunk-4M3SUZHX.js.map