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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1425 @@
1
+ import {
2
+ trackToolCall
3
+ } from "./chunk-XBMI6QHR.js";
4
+
5
+ // src/tools/smart-capture.ts
6
+ import { z } from "zod";
7
+
8
+ // src/auth.ts
9
+ import { AsyncLocalStorage } from "async_hooks";
10
+ var requestStore = new AsyncLocalStorage();
11
+ function runWithAuth(auth, fn) {
12
+ return requestStore.run(auth, fn);
13
+ }
14
+ function getRequestApiKey() {
15
+ return requestStore.getStore()?.apiKey;
16
+ }
17
+ var SESSION_TTL_MS = 30 * 60 * 1e3;
18
+ var MAX_KEYS = 100;
19
+ var keyStateMap = /* @__PURE__ */ new Map();
20
+ function newKeyState() {
21
+ return {
22
+ workspaceId: null,
23
+ workspaceSlug: null,
24
+ workspaceName: null,
25
+ workspaceCreatedAt: null,
26
+ agentSessionId: null,
27
+ apiKeyId: null,
28
+ apiKeyScope: "readwrite",
29
+ sessionOriented: false,
30
+ sessionClosed: false,
31
+ lastAccess: Date.now()
32
+ };
33
+ }
34
+ function getKeyState(apiKey) {
35
+ let s = keyStateMap.get(apiKey);
36
+ if (!s) {
37
+ s = newKeyState();
38
+ keyStateMap.set(apiKey, s);
39
+ evictStale();
40
+ }
41
+ s.lastAccess = Date.now();
42
+ return s;
43
+ }
44
+ function evictStale() {
45
+ if (keyStateMap.size <= MAX_KEYS) return;
46
+ const now = Date.now();
47
+ for (const [key, s] of keyStateMap) {
48
+ if (now - s.lastAccess > SESSION_TTL_MS) keyStateMap.delete(key);
49
+ }
50
+ if (keyStateMap.size > MAX_KEYS) {
51
+ const sorted = [...keyStateMap.entries()].sort((a, b) => a[1].lastAccess - b[1].lastAccess);
52
+ for (let i = 0; i < sorted.length - MAX_KEYS; i++) {
53
+ keyStateMap.delete(sorted[i][0]);
54
+ }
55
+ }
56
+ }
57
+
58
+ // src/client.ts
59
+ var DEFAULT_CLOUD_URL = "https://trustworthy-kangaroo-277.convex.site";
60
+ var _stdioState = {
61
+ workspaceId: null,
62
+ workspaceSlug: null,
63
+ workspaceName: null,
64
+ workspaceCreatedAt: null,
65
+ agentSessionId: null,
66
+ apiKeyId: null,
67
+ apiKeyScope: "readwrite",
68
+ sessionOriented: false,
69
+ sessionClosed: false,
70
+ lastAccess: 0
71
+ };
72
+ function state() {
73
+ const reqKey = getRequestApiKey();
74
+ if (reqKey) return getKeyState(reqKey);
75
+ return _stdioState;
76
+ }
77
+ function getActiveApiKey() {
78
+ const fromRequest = getRequestApiKey();
79
+ if (fromRequest) return fromRequest;
80
+ const fromEnv = process.env.PRODUCTBRAIN_API_KEY;
81
+ if (!fromEnv) throw new Error("No API key available \u2014 set PRODUCTBRAIN_API_KEY or provide Bearer token");
82
+ return fromEnv;
83
+ }
84
+ function getAgentSessionId() {
85
+ return state().agentSessionId;
86
+ }
87
+ function isSessionOriented() {
88
+ return state().sessionOriented;
89
+ }
90
+ function setSessionOriented(value) {
91
+ state().sessionOriented = value;
92
+ }
93
+ async function startAgentSession() {
94
+ const workspaceId = await getWorkspaceId();
95
+ const s = state();
96
+ if (!s.apiKeyId) {
97
+ throw new Error("Cannot start session: API key ID not resolved. Ensure workspace resolution completed.");
98
+ }
99
+ const result = await mcpCall("agent.startSession", {
100
+ workspaceId,
101
+ apiKeyId: s.apiKeyId
102
+ });
103
+ s.agentSessionId = result.sessionId;
104
+ s.apiKeyScope = result.toolsScope;
105
+ s.sessionOriented = false;
106
+ s.sessionClosed = false;
107
+ return result;
108
+ }
109
+ async function closeAgentSession() {
110
+ const s = state();
111
+ if (!s.agentSessionId) return;
112
+ try {
113
+ await mcpCall("agent.closeSession", {
114
+ sessionId: s.agentSessionId,
115
+ status: "closed"
116
+ });
117
+ } finally {
118
+ s.sessionClosed = true;
119
+ s.agentSessionId = null;
120
+ s.sessionOriented = false;
121
+ }
122
+ }
123
+ async function orphanAgentSession() {
124
+ const s = state();
125
+ if (!s.agentSessionId) return;
126
+ try {
127
+ await mcpCall("agent.closeSession", {
128
+ sessionId: s.agentSessionId,
129
+ status: "orphaned"
130
+ });
131
+ } catch {
132
+ } finally {
133
+ s.agentSessionId = null;
134
+ s.sessionOriented = false;
135
+ }
136
+ }
137
+ function touchSessionActivity() {
138
+ const s = state();
139
+ if (!s.agentSessionId) return;
140
+ mcpCall("agent.touchSession", {
141
+ sessionId: s.agentSessionId
142
+ }).catch(() => {
143
+ });
144
+ }
145
+ async function recordSessionActivity(activity) {
146
+ const s = state();
147
+ if (!s.agentSessionId) return;
148
+ try {
149
+ await mcpCall("agent.recordActivity", {
150
+ sessionId: s.agentSessionId,
151
+ ...activity
152
+ });
153
+ } catch {
154
+ }
155
+ }
156
+ var AUDIT_BUFFER_SIZE = 50;
157
+ var auditBuffer = [];
158
+ function bootstrap() {
159
+ const pbKey = process.env.PRODUCTBRAIN_API_KEY;
160
+ if (!pbKey?.startsWith("pb_sk_")) {
161
+ throw new Error(
162
+ "PRODUCTBRAIN_API_KEY is required and must start with 'pb_sk_'. Generate one at Settings > API Keys in the Product OS UI."
163
+ );
164
+ }
165
+ process.env.CONVEX_SITE_URL ??= process.env.PRODUCTBRAIN_URL ?? DEFAULT_CLOUD_URL;
166
+ }
167
+ function bootstrapHttp() {
168
+ process.env.CONVEX_SITE_URL ??= process.env.PRODUCTBRAIN_URL ?? DEFAULT_CLOUD_URL;
169
+ }
170
+ function getEnv(key) {
171
+ const value = process.env[key];
172
+ if (!value) throw new Error(`${key} environment variable is required`);
173
+ return value;
174
+ }
175
+ function shouldLogAudit(status) {
176
+ return status === "error" || process.env.MCP_DEBUG === "1";
177
+ }
178
+ function audit(fn, status, durationMs, errorMsg) {
179
+ const ts = (/* @__PURE__ */ new Date()).toISOString();
180
+ const workspace = state().workspaceId ?? "unresolved";
181
+ const entry = { ts, fn, workspace, status, durationMs };
182
+ if (errorMsg) entry.error = errorMsg;
183
+ auditBuffer.push(entry);
184
+ if (auditBuffer.length > AUDIT_BUFFER_SIZE) auditBuffer.shift();
185
+ trackToolCall(fn, status, durationMs, workspace, errorMsg);
186
+ if (!shouldLogAudit(status)) return;
187
+ const base = `[MCP-AUDIT] ${ts} fn=${fn} workspace=${workspace} status=${status} duration=${durationMs}ms`;
188
+ if (status === "error" && errorMsg) {
189
+ process.stderr.write(`${base} error=${JSON.stringify(errorMsg)}
190
+ `);
191
+ } else {
192
+ process.stderr.write(`${base}
193
+ `);
194
+ }
195
+ }
196
+ function getAuditLog() {
197
+ return auditBuffer;
198
+ }
199
+ async function mcpCall(fn, args = {}) {
200
+ const siteUrl = getEnv("CONVEX_SITE_URL").replace(/\/$/, "");
201
+ const apiKey = getActiveApiKey();
202
+ const start = Date.now();
203
+ let res;
204
+ try {
205
+ res = await fetch(`${siteUrl}/api/mcp`, {
206
+ method: "POST",
207
+ headers: {
208
+ "Content-Type": "application/json",
209
+ Authorization: `Bearer ${apiKey}`
210
+ },
211
+ body: JSON.stringify({ fn, args })
212
+ });
213
+ } catch (err) {
214
+ audit(fn, "error", Date.now() - start, err.message);
215
+ throw new Error(`MCP call "${fn}" network error: ${err.message}`);
216
+ }
217
+ const json = await res.json();
218
+ if (!res.ok || json.error) {
219
+ audit(fn, "error", Date.now() - start, json.error);
220
+ throw new Error(`MCP call "${fn}" failed (${res.status}): ${json.error ?? "unknown error"}`);
221
+ }
222
+ audit(fn, "ok", Date.now() - start);
223
+ const s = state();
224
+ if (s.agentSessionId && fn !== "agent.touchSession" && fn !== "agent.startSession") {
225
+ touchSessionActivity();
226
+ }
227
+ return json.data;
228
+ }
229
+ var resolveInFlightMap = /* @__PURE__ */ new Map();
230
+ async function getWorkspaceId() {
231
+ const s = state();
232
+ if (s.workspaceId) return s.workspaceId;
233
+ const apiKey = getActiveApiKey();
234
+ const existing = resolveInFlightMap.get(apiKey);
235
+ if (existing) return existing;
236
+ const promise = resolveWorkspaceWithRetry().finally(() => resolveInFlightMap.delete(apiKey));
237
+ resolveInFlightMap.set(apiKey, promise);
238
+ return promise;
239
+ }
240
+ async function resolveWorkspaceWithRetry(maxRetries = 2) {
241
+ let lastError = null;
242
+ for (let attempt = 0; attempt <= maxRetries; attempt++) {
243
+ try {
244
+ const workspace = await mcpCall("resolveWorkspace", {});
245
+ if (!workspace) {
246
+ throw new Error(
247
+ "API key is valid but no workspace is associated. Run `npx productbrain setup` or regenerate your key."
248
+ );
249
+ }
250
+ const s = state();
251
+ s.workspaceId = workspace._id;
252
+ s.workspaceSlug = workspace.slug;
253
+ s.workspaceName = workspace.name;
254
+ s.workspaceCreatedAt = workspace.createdAt ?? null;
255
+ if (workspace.keyScope) s.apiKeyScope = workspace.keyScope;
256
+ if (workspace.keyId) s.apiKeyId = workspace.keyId;
257
+ return s.workspaceId;
258
+ } catch (err) {
259
+ lastError = err;
260
+ const isTransient = /network error|fetch failed|ECONNREFUSED|ETIMEDOUT/i.test(err.message);
261
+ if (!isTransient || attempt === maxRetries) break;
262
+ const delay = 1e3 * (attempt + 1);
263
+ process.stderr.write(
264
+ `[MCP] Workspace resolution failed (attempt ${attempt + 1}/${maxRetries + 1}), retrying in ${delay}ms...
265
+ `
266
+ );
267
+ await new Promise((r) => setTimeout(r, delay));
268
+ }
269
+ }
270
+ throw lastError;
271
+ }
272
+ async function getWorkspaceContext() {
273
+ const workspaceId = await getWorkspaceId();
274
+ const s = state();
275
+ return {
276
+ workspaceId,
277
+ workspaceSlug: s.workspaceSlug ?? "unknown",
278
+ workspaceName: s.workspaceName ?? "unknown",
279
+ createdAt: s.workspaceCreatedAt
280
+ };
281
+ }
282
+ async function mcpQuery(fn, args = {}) {
283
+ const workspaceId = await getWorkspaceId();
284
+ return mcpCall(fn, { ...args, workspaceId });
285
+ }
286
+ async function mcpMutation(fn, args = {}) {
287
+ const workspaceId = await getWorkspaceId();
288
+ return mcpCall(fn, { ...args, workspaceId });
289
+ }
290
+ function requireWriteAccess() {
291
+ const s = state();
292
+ if (!s.agentSessionId) {
293
+ throw new Error(
294
+ "Agent session required for write operations. Call `agent-start` first."
295
+ );
296
+ }
297
+ if (s.sessionClosed) {
298
+ throw new Error(
299
+ "Agent session has been closed. Write tools are no longer available."
300
+ );
301
+ }
302
+ if (!s.sessionOriented) {
303
+ throw new Error(
304
+ "Orientation required before writing to the Chain. Call 'orient' first."
305
+ );
306
+ }
307
+ if (s.apiKeyScope === "read") {
308
+ throw new Error(
309
+ "This API key has read-only scope. Write tools are not available."
310
+ );
311
+ }
312
+ }
313
+ async function recoverSessionState() {
314
+ const s = state();
315
+ if (!s.workspaceId) return;
316
+ try {
317
+ const session = await mcpCall("agent.getActiveSession", { workspaceId: s.workspaceId });
318
+ if (session && session.status === "active") {
319
+ s.agentSessionId = session._id;
320
+ s.sessionOriented = session.oriented;
321
+ s.apiKeyScope = session.toolsScope;
322
+ s.sessionClosed = false;
323
+ }
324
+ } catch {
325
+ }
326
+ }
327
+
328
+ // src/tools/smart-capture.ts
329
+ var AREA_KEYWORDS = {
330
+ "Architecture": ["convex", "schema", "database", "migration", "api", "backend", "infrastructure", "scaling", "performance"],
331
+ "Chain": ["knowledge", "glossary", "entry", "collection", "terminology", "drift", "graph", "chain", "commit"],
332
+ "AI & MCP Integration": ["mcp", "ai", "cursor", "agent", "tool", "llm", "prompt", "context"],
333
+ "Developer Experience": ["dx", "developer", "ide", "workflow", "friction", "ceremony"],
334
+ "Governance & Decision-Making": ["governance", "decision", "rule", "policy", "compliance", "approval"],
335
+ "Analytics & Tracking": ["analytics", "posthog", "tracking", "event", "metric", "funnel"],
336
+ "Security": ["security", "auth", "api key", "permission", "access", "token"]
337
+ };
338
+ function inferArea(text) {
339
+ const lower = text.toLowerCase();
340
+ let bestArea = "";
341
+ let bestScore = 0;
342
+ for (const [area, keywords] of Object.entries(AREA_KEYWORDS)) {
343
+ const score = keywords.filter((kw) => lower.includes(kw)).length;
344
+ if (score > bestScore) {
345
+ bestScore = score;
346
+ bestArea = area;
347
+ }
348
+ }
349
+ return bestArea;
350
+ }
351
+ function inferDomain(text) {
352
+ return inferArea(text) || "";
353
+ }
354
+ var COMMON_CHECKS = {
355
+ clearName: {
356
+ id: "clear-name",
357
+ label: "Clear, specific name (not vague)",
358
+ check: (ctx) => ctx.name.length > 10 && !["new tension", "new entry", "untitled", "test"].includes(ctx.name.toLowerCase()),
359
+ suggestion: () => "Rename to something specific \u2014 describe the actual problem or concept."
360
+ },
361
+ hasDescription: {
362
+ id: "has-description",
363
+ label: "Description provided (>50 chars)",
364
+ check: (ctx) => ctx.description.length > 50,
365
+ suggestion: () => "Add a fuller description explaining context and impact."
366
+ },
367
+ hasRelations: {
368
+ id: "has-relations",
369
+ label: "At least 1 relation created",
370
+ check: (ctx) => ctx.linksCreated.length >= 1,
371
+ suggestion: () => "Use `suggest-links` and `relate-entries` to add more connections."
372
+ },
373
+ diverseRelations: {
374
+ id: "diverse-relations",
375
+ label: "Relations span multiple collections",
376
+ check: (ctx) => {
377
+ const colls = new Set(ctx.linksCreated.map((l) => l.targetCollection));
378
+ return colls.size >= 2;
379
+ },
380
+ suggestion: () => "Try linking to entries in different collections (glossary, business-rules, strategy)."
381
+ },
382
+ hasType: {
383
+ id: "has-type",
384
+ label: "Has canonical type",
385
+ check: (ctx) => !!ctx.data?.canonicalKey || !!ctx.canonicalKey,
386
+ suggestion: () => "Classify this entry with a canonical type for better context assembly. Use update-entry to set canonicalKey."
387
+ }
388
+ };
389
+ var PROFILES = /* @__PURE__ */ new Map([
390
+ ["tensions", {
391
+ idPrefix: "TEN",
392
+ governedDraft: false,
393
+ descriptionField: "description",
394
+ defaults: [
395
+ { key: "priority", value: "medium" },
396
+ { key: "date", value: "today" },
397
+ { key: "raised", value: "infer" },
398
+ { key: "severity", value: "infer" }
399
+ ],
400
+ recommendedRelationTypes: ["surfaces_tension_in", "references", "belongs_to", "related_to"],
401
+ inferField: (ctx) => {
402
+ const fields = {};
403
+ const text = `${ctx.name} ${ctx.description}`;
404
+ const area = inferArea(text);
405
+ if (area) fields.raised = area;
406
+ if (text.toLowerCase().includes("critical") || text.toLowerCase().includes("blocker")) {
407
+ fields.severity = "critical";
408
+ } else if (text.toLowerCase().includes("bottleneck") || text.toLowerCase().includes("scaling") || text.toLowerCase().includes("breaking")) {
409
+ fields.severity = "high";
410
+ } else {
411
+ fields.severity = "medium";
412
+ }
413
+ if (area) fields.affectedArea = area;
414
+ return fields;
415
+ },
416
+ qualityChecks: [
417
+ COMMON_CHECKS.clearName,
418
+ COMMON_CHECKS.hasDescription,
419
+ COMMON_CHECKS.hasRelations,
420
+ COMMON_CHECKS.hasType,
421
+ {
422
+ id: "has-severity",
423
+ label: "Severity specified",
424
+ check: (ctx) => !!ctx.data.severity && ctx.data.severity !== "",
425
+ suggestion: (ctx) => {
426
+ const text = `${ctx.name} ${ctx.description}`.toLowerCase();
427
+ const inferred = text.includes("critical") ? "critical" : text.includes("bottleneck") ? "high" : "medium";
428
+ return `Set severity \u2014 suggest: ${inferred} (based on description keywords).`;
429
+ }
430
+ },
431
+ {
432
+ id: "has-affected-area",
433
+ label: "Affected area identified",
434
+ check: (ctx) => !!ctx.data.affectedArea && ctx.data.affectedArea !== "",
435
+ suggestion: (ctx) => {
436
+ const area = inferArea(`${ctx.name} ${ctx.description}`);
437
+ return area ? `Set affectedArea \u2014 suggest: "${area}" (inferred from content).` : "Specify which product area or domain this tension impacts.";
438
+ }
439
+ }
440
+ ]
441
+ }],
442
+ ["business-rules", {
443
+ idPrefix: "SOS",
444
+ governedDraft: true,
445
+ descriptionField: "description",
446
+ defaults: [
447
+ { key: "severity", value: "medium" },
448
+ { key: "domain", value: "infer" }
449
+ ],
450
+ recommendedRelationTypes: ["governs", "references", "conflicts_with", "related_to"],
451
+ inferField: (ctx) => {
452
+ const fields = {};
453
+ const domain = inferDomain(`${ctx.name} ${ctx.description}`);
454
+ if (domain) fields.domain = domain;
455
+ return fields;
456
+ },
457
+ qualityChecks: [
458
+ COMMON_CHECKS.clearName,
459
+ COMMON_CHECKS.hasDescription,
460
+ COMMON_CHECKS.hasRelations,
461
+ COMMON_CHECKS.hasType,
462
+ {
463
+ id: "has-rationale",
464
+ label: "Rationale provided",
465
+ check: (ctx) => typeof ctx.data.rationale === "string" && ctx.data.rationale.length > 10,
466
+ suggestion: () => "Add a rationale explaining why this rule exists via `update-entry`."
467
+ },
468
+ {
469
+ id: "has-domain",
470
+ label: "Domain specified",
471
+ check: (ctx) => !!ctx.data.domain && ctx.data.domain !== "",
472
+ suggestion: (ctx) => {
473
+ const domain = inferDomain(`${ctx.name} ${ctx.description}`);
474
+ return domain ? `Set domain \u2014 suggest: "${domain}" (inferred from content).` : "Specify the business domain this rule belongs to.";
475
+ }
476
+ }
477
+ ]
478
+ }],
479
+ ["glossary", {
480
+ idPrefix: "GT",
481
+ governedDraft: true,
482
+ descriptionField: "canonical",
483
+ defaults: [
484
+ { key: "category", value: "infer" }
485
+ ],
486
+ recommendedRelationTypes: ["defines_term_for", "confused_with", "related_to", "references"],
487
+ inferField: (ctx) => {
488
+ const fields = {};
489
+ const area = inferArea(`${ctx.name} ${ctx.description}`);
490
+ if (area) {
491
+ const categoryMap = {
492
+ "Architecture": "Platform & Architecture",
493
+ "Chain": "Knowledge Management",
494
+ "AI & MCP Integration": "AI & Developer Tools",
495
+ "Developer Experience": "AI & Developer Tools",
496
+ "Governance & Decision-Making": "Governance & Process",
497
+ "Analytics & Tracking": "Platform & Architecture",
498
+ "Security": "Platform & Architecture"
499
+ };
500
+ fields.category = categoryMap[area] ?? "";
501
+ }
502
+ return fields;
503
+ },
504
+ qualityChecks: [
505
+ COMMON_CHECKS.clearName,
506
+ COMMON_CHECKS.hasType,
507
+ {
508
+ id: "has-canonical",
509
+ label: "Canonical definition provided (>20 chars)",
510
+ check: (ctx) => {
511
+ const canonical = ctx.data.canonical;
512
+ return typeof canonical === "string" && canonical.length > 20;
513
+ },
514
+ suggestion: () => "Add a clear canonical definition \u2014 this is the single source of truth for this term."
515
+ },
516
+ COMMON_CHECKS.hasRelations,
517
+ {
518
+ id: "has-category",
519
+ label: "Category assigned",
520
+ check: (ctx) => !!ctx.data.category && ctx.data.category !== "",
521
+ suggestion: () => "Assign a category (e.g., 'Platform & Architecture', 'Governance & Process')."
522
+ }
523
+ ]
524
+ }],
525
+ ["decisions", {
526
+ idPrefix: "DEC",
527
+ governedDraft: false,
528
+ descriptionField: "rationale",
529
+ defaults: [
530
+ { key: "date", value: "today" },
531
+ { key: "decidedBy", value: "infer" }
532
+ ],
533
+ recommendedRelationTypes: ["informs", "references", "replaces", "related_to"],
534
+ inferField: (ctx) => {
535
+ const fields = {};
536
+ const area = inferArea(`${ctx.name} ${ctx.description}`);
537
+ if (area) fields.decidedBy = area;
538
+ return fields;
539
+ },
540
+ qualityChecks: [
541
+ COMMON_CHECKS.clearName,
542
+ COMMON_CHECKS.hasType,
543
+ {
544
+ id: "has-rationale",
545
+ label: "Rationale provided (>30 chars)",
546
+ check: (ctx) => {
547
+ const rationale = ctx.data.rationale;
548
+ return typeof rationale === "string" && rationale.length > 30;
549
+ },
550
+ suggestion: () => "Explain why this decision was made \u2014 what was considered and rejected?"
551
+ },
552
+ COMMON_CHECKS.hasRelations,
553
+ {
554
+ id: "has-date",
555
+ label: "Decision date recorded",
556
+ check: (ctx) => !!ctx.data.date && ctx.data.date !== "",
557
+ suggestion: () => "Record when this decision was made."
558
+ }
559
+ ]
560
+ }],
561
+ ["features", {
562
+ idPrefix: "FEAT",
563
+ governedDraft: false,
564
+ descriptionField: "description",
565
+ defaults: [],
566
+ recommendedRelationTypes: ["belongs_to", "depends_on", "surfaces_tension_in", "related_to"],
567
+ qualityChecks: [
568
+ COMMON_CHECKS.clearName,
569
+ COMMON_CHECKS.hasDescription,
570
+ COMMON_CHECKS.hasRelations,
571
+ COMMON_CHECKS.hasType,
572
+ {
573
+ id: "has-owner",
574
+ label: "Owner assigned",
575
+ check: (ctx) => !!ctx.data.owner && ctx.data.owner !== "",
576
+ suggestion: () => "Assign an owner team or product area."
577
+ },
578
+ {
579
+ id: "has-rationale",
580
+ label: "Rationale documented",
581
+ check: (ctx) => !!ctx.data.rationale && String(ctx.data.rationale).length > 20,
582
+ suggestion: () => "Explain why this feature matters \u2014 what problem does it solve?"
583
+ }
584
+ ]
585
+ }],
586
+ ["audiences", {
587
+ idPrefix: "AUD",
588
+ governedDraft: false,
589
+ descriptionField: "description",
590
+ defaults: [],
591
+ recommendedRelationTypes: ["fills_slot", "informs", "related_to", "references"],
592
+ qualityChecks: [
593
+ COMMON_CHECKS.clearName,
594
+ COMMON_CHECKS.hasDescription,
595
+ COMMON_CHECKS.hasRelations,
596
+ COMMON_CHECKS.hasType,
597
+ {
598
+ id: "has-behaviors",
599
+ label: "Behaviors described",
600
+ check: (ctx) => typeof ctx.data.behaviors === "string" && ctx.data.behaviors.length > 20,
601
+ suggestion: () => "Describe how this audience segment behaves \u2014 what do they do, what tools do they use?"
602
+ }
603
+ ]
604
+ }],
605
+ ["strategy", {
606
+ idPrefix: "STR",
607
+ governedDraft: true,
608
+ descriptionField: "description",
609
+ defaults: [],
610
+ recommendedRelationTypes: ["informs", "governs", "belongs_to", "related_to"],
611
+ qualityChecks: [
612
+ COMMON_CHECKS.clearName,
613
+ COMMON_CHECKS.hasDescription,
614
+ COMMON_CHECKS.hasRelations,
615
+ COMMON_CHECKS.hasType,
616
+ COMMON_CHECKS.diverseRelations
617
+ ]
618
+ }],
619
+ ["maps", {
620
+ idPrefix: "MAP",
621
+ governedDraft: false,
622
+ descriptionField: "description",
623
+ defaults: [],
624
+ recommendedRelationTypes: ["fills_slot", "references", "related_to"],
625
+ qualityChecks: [
626
+ COMMON_CHECKS.clearName,
627
+ COMMON_CHECKS.hasDescription
628
+ ]
629
+ }],
630
+ ["chains", {
631
+ idPrefix: "CHN",
632
+ governedDraft: false,
633
+ descriptionField: "description",
634
+ defaults: [],
635
+ recommendedRelationTypes: ["informs", "references", "related_to"],
636
+ qualityChecks: [
637
+ COMMON_CHECKS.clearName,
638
+ COMMON_CHECKS.hasDescription
639
+ ]
640
+ }],
641
+ ["standards", {
642
+ idPrefix: "STD",
643
+ governedDraft: true,
644
+ descriptionField: "description",
645
+ defaults: [],
646
+ recommendedRelationTypes: ["governs", "defines_term_for", "references", "related_to"],
647
+ qualityChecks: [
648
+ COMMON_CHECKS.clearName,
649
+ COMMON_CHECKS.hasDescription,
650
+ COMMON_CHECKS.hasRelations,
651
+ COMMON_CHECKS.hasType
652
+ ]
653
+ }],
654
+ ["tracking-events", {
655
+ idPrefix: "TE",
656
+ governedDraft: false,
657
+ descriptionField: "description",
658
+ defaults: [],
659
+ recommendedRelationTypes: ["references", "belongs_to", "related_to"],
660
+ qualityChecks: [
661
+ COMMON_CHECKS.clearName,
662
+ COMMON_CHECKS.hasDescription
663
+ ]
664
+ }]
665
+ ]);
666
+ var FALLBACK_PROFILE = {
667
+ idPrefix: "ENT",
668
+ governedDraft: false,
669
+ descriptionField: "description",
670
+ defaults: [],
671
+ recommendedRelationTypes: ["related_to", "references"],
672
+ qualityChecks: [
673
+ COMMON_CHECKS.clearName,
674
+ COMMON_CHECKS.hasDescription,
675
+ COMMON_CHECKS.hasRelations,
676
+ COMMON_CHECKS.hasType
677
+ ]
678
+ };
679
+ function generateEntryId(prefix) {
680
+ const effectivePrefix = prefix || "ENT";
681
+ const chars = "abcdefghijklmnopqrstuvwxyz0123456789";
682
+ let suffix = "";
683
+ for (let i = 0; i < 6; i++) {
684
+ suffix += chars[Math.floor(Math.random() * chars.length)];
685
+ }
686
+ return `${effectivePrefix}-${suffix}`;
687
+ }
688
+ function extractSearchTerms(name, description) {
689
+ const text = `${name} ${description}`;
690
+ return text.replace(/[^\w\s]/g, " ").split(/\s+/).filter((w) => w.length > 3).slice(0, 8).join(" ");
691
+ }
692
+ function computeLinkConfidence(candidate, sourceName, sourceDescription, sourceCollection, candidateCollection) {
693
+ const text = `${sourceName} ${sourceDescription}`.toLowerCase();
694
+ const candidateName = candidate.name.toLowerCase();
695
+ let score = 0;
696
+ if (text.includes(candidateName) && candidateName.length > 3) {
697
+ score += 40;
698
+ }
699
+ const candidateWords = candidateName.split(/\s+/).filter((w) => w.length > 3);
700
+ const matchingWords = candidateWords.filter((w) => text.includes(w));
701
+ score += matchingWords.length / Math.max(candidateWords.length, 1) * 30;
702
+ const HUB_COLLECTIONS = /* @__PURE__ */ new Set(["strategy", "features"]);
703
+ if (HUB_COLLECTIONS.has(candidateCollection)) {
704
+ score += 15;
705
+ }
706
+ if (candidateCollection !== sourceCollection) {
707
+ score += 10;
708
+ }
709
+ return Math.min(score, 100);
710
+ }
711
+ function inferRelationType(sourceCollection, targetCollection, profile) {
712
+ const typeMap = {
713
+ tensions: {
714
+ glossary: "surfaces_tension_in",
715
+ "business-rules": "references",
716
+ strategy: "belongs_to",
717
+ features: "surfaces_tension_in",
718
+ decisions: "references"
719
+ },
720
+ "business-rules": {
721
+ glossary: "references",
722
+ features: "governs",
723
+ strategy: "belongs_to",
724
+ tensions: "references"
725
+ },
726
+ glossary: {
727
+ features: "defines_term_for",
728
+ "business-rules": "references",
729
+ strategy: "references"
730
+ },
731
+ decisions: {
732
+ features: "informs",
733
+ "business-rules": "references",
734
+ strategy: "references",
735
+ tensions: "references"
736
+ }
737
+ };
738
+ return typeMap[sourceCollection]?.[targetCollection] ?? profile.recommendedRelationTypes[0] ?? "related_to";
739
+ }
740
+ function scoreQuality(ctx, profile) {
741
+ const checks = profile.qualityChecks.map((qc) => {
742
+ const passed2 = qc.check(ctx);
743
+ return {
744
+ id: qc.id,
745
+ label: qc.label,
746
+ passed: passed2,
747
+ suggestion: passed2 ? void 0 : qc.suggestion?.(ctx)
748
+ };
749
+ });
750
+ const passed = checks.filter((c) => c.passed).length;
751
+ const total = checks.length;
752
+ const score = total > 0 ? Math.round(passed / total * 10) : 10;
753
+ return { score, maxScore: 10, checks };
754
+ }
755
+ function formatQualityReport(result) {
756
+ const lines = [`## Quality: ${result.score}/${result.maxScore}`];
757
+ for (const check of result.checks) {
758
+ const icon = check.passed ? "[x]" : "[ ]";
759
+ const suggestion = check.passed ? "" : ` -- ${check.suggestion ?? ""}`;
760
+ lines.push(`${icon} ${check.label}${suggestion}`);
761
+ }
762
+ return lines.join("\n");
763
+ }
764
+ async function checkEntryQuality(entryId) {
765
+ const entry = await mcpQuery("chain.getEntry", { entryId });
766
+ if (!entry) {
767
+ return {
768
+ text: `Entry \`${entryId}\` not found. Try search to find the right ID.`,
769
+ quality: { score: 0, maxScore: 10, checks: [] }
770
+ };
771
+ }
772
+ const collections = await mcpQuery("chain.listCollections");
773
+ const collMap = /* @__PURE__ */ new Map();
774
+ for (const c of collections) collMap.set(c._id, c.slug);
775
+ const collectionSlug = collMap.get(entry.collectionId) ?? "unknown";
776
+ const profile = PROFILES.get(collectionSlug) ?? FALLBACK_PROFILE;
777
+ const relations = await mcpQuery("chain.listEntryRelations", { entryId });
778
+ const linksCreated = [];
779
+ for (const r of relations) {
780
+ const otherId = r.fromId === entry._id ? r.toId : r.fromId;
781
+ linksCreated.push({
782
+ targetEntryId: otherId,
783
+ targetName: "",
784
+ targetCollection: "",
785
+ relationType: r.type
786
+ });
787
+ }
788
+ const descField = profile.descriptionField;
789
+ const description = typeof entry.data?.[descField] === "string" ? entry.data[descField] : "";
790
+ const ctx = {
791
+ collection: collectionSlug,
792
+ name: entry.name,
793
+ description,
794
+ data: entry.data ?? {},
795
+ entryId: entry.entryId ?? "",
796
+ canonicalKey: entry.canonicalKey,
797
+ linksCreated,
798
+ linksSuggested: [],
799
+ collectionFields: []
800
+ };
801
+ const quality = scoreQuality(ctx, profile);
802
+ const lines = [
803
+ `# Quality Check: ${entry.entryId ?? entry.name}`,
804
+ `**${entry.name}** in \`${collectionSlug}\` [${entry.status}]`,
805
+ "",
806
+ formatQualityReport(quality)
807
+ ];
808
+ if (quality.score < 10) {
809
+ const failedChecks = quality.checks.filter((c) => !c.passed && c.suggestion);
810
+ if (failedChecks.length > 0) {
811
+ lines.push("");
812
+ lines.push(`_To improve: use \`update-entry\` to fill missing fields, or \`relate-entries\` to add connections._`);
813
+ }
814
+ }
815
+ return { text: lines.join("\n"), quality };
816
+ }
817
+ var GOVERNED_COLLECTIONS = /* @__PURE__ */ new Set([
818
+ "glossary",
819
+ "business-rules",
820
+ "principles",
821
+ "standards",
822
+ "strategy",
823
+ "features"
824
+ ]);
825
+ var AUTO_LINK_CONFIDENCE_THRESHOLD = 35;
826
+ var MAX_AUTO_LINKS = 5;
827
+ var MAX_SUGGESTIONS = 5;
828
+ function registerSmartCaptureTools(server) {
829
+ server.registerTool(
830
+ "capture",
831
+ {
832
+ title: "Capture",
833
+ 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 collection, name, and description \u2014 everything else is inferred or auto-filled.\n\nSupported collections with smart profiles: tensions, business-rules, glossary, decisions, features, audiences, strategy, standards, maps, chains, tracking-events.\nAll other collections get an ENT-{random} ID and sensible defaults.\n\nAlways creates as 'draft' for governed collections. Use `update-entry` for post-creation adjustments.",
834
+ inputSchema: {
835
+ collection: z.string().describe("Collection slug, e.g. 'tensions', 'business-rules', 'glossary', 'decisions'"),
836
+ name: z.string().describe("Display name \u2014 be specific (e.g. 'Convex adjacency list won't scale for graph traversal')"),
837
+ description: z.string().describe("Full context \u2014 what's happening, why it matters, what you observed"),
838
+ context: z.string().optional().describe("Optional additional context (e.g. 'Observed during gather-context calls taking 700ms+')"),
839
+ entryId: z.string().optional().describe("Optional custom entry ID (e.g. 'TEN-my-id'). Auto-generated if omitted."),
840
+ canonicalKey: z.string().optional().describe("Semantic type (e.g. 'decision', 'tension', 'vision'). Auto-assigned from collection if omitted.")
841
+ },
842
+ annotations: { destructiveHint: false }
843
+ },
844
+ async ({ collection, name, description, context, entryId, canonicalKey }) => {
845
+ requireWriteAccess();
846
+ const profile = PROFILES.get(collection) ?? FALLBACK_PROFILE;
847
+ const col = await mcpQuery("chain.getCollection", { slug: collection });
848
+ if (!col) {
849
+ const displayName = collection.split("-").map((w) => w.charAt(0).toUpperCase() + w.slice(1)).join(" ");
850
+ return {
851
+ content: [{
852
+ type: "text",
853
+ text: `Collection \`${collection}\` not found.
854
+
855
+ **To create it**, run:
856
+ \`\`\`
857
+ create-collection slug="${collection}" name="${displayName}" description="..."
858
+ \`\`\`
859
+
860
+ Or use \`list-collections\` to see available collections.`
861
+ }]
862
+ };
863
+ }
864
+ const data = {};
865
+ const today = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
866
+ for (const field of col.fields ?? []) {
867
+ const key = field.key;
868
+ if (key === profile.descriptionField) {
869
+ data[key] = description;
870
+ } else if (field.type === "array" || field.type === "multi-select") {
871
+ data[key] = [];
872
+ } else if (field.type === "select") {
873
+ } else {
874
+ data[key] = "";
875
+ }
876
+ }
877
+ for (const def of profile.defaults) {
878
+ if (def.value === "today") {
879
+ data[def.key] = today;
880
+ } else if (def.value !== "infer") {
881
+ data[def.key] = def.value;
882
+ }
883
+ }
884
+ if (profile.inferField) {
885
+ const inferred = profile.inferField({
886
+ collection,
887
+ name,
888
+ description,
889
+ context,
890
+ data,
891
+ entryId: "",
892
+ linksCreated: [],
893
+ linksSuggested: [],
894
+ collectionFields: col.fields ?? []
895
+ });
896
+ for (const [key, val] of Object.entries(inferred)) {
897
+ if (val !== void 0 && val !== "") {
898
+ data[key] = val;
899
+ }
900
+ }
901
+ }
902
+ if (!data[profile.descriptionField] && !data.description && !data.canonical) {
903
+ data[profile.descriptionField || "description"] = description;
904
+ }
905
+ const status = GOVERNED_COLLECTIONS.has(collection) ? "draft" : "draft";
906
+ const finalEntryId = entryId ?? generateEntryId(profile.idPrefix);
907
+ let internalId;
908
+ try {
909
+ const agentId = getAgentSessionId();
910
+ internalId = await mcpMutation("chain.createEntry", {
911
+ collectionSlug: collection,
912
+ entryId: finalEntryId || void 0,
913
+ name,
914
+ status,
915
+ data,
916
+ canonicalKey,
917
+ createdBy: agentId ? `agent:${agentId}` : "capture",
918
+ sessionId: agentId ?? void 0
919
+ });
920
+ await recordSessionActivity({ entryCreated: internalId });
921
+ } catch (error) {
922
+ const msg = error instanceof Error ? error.message : String(error);
923
+ if (msg.includes("Duplicate") || msg.includes("already exists")) {
924
+ return {
925
+ content: [{
926
+ type: "text",
927
+ text: `# Cannot Capture \u2014 Duplicate Detected
928
+
929
+ ${msg}
930
+
931
+ Use \`get-entry\` to inspect the existing entry, or \`update-entry\` to modify it.`
932
+ }]
933
+ };
934
+ }
935
+ throw error;
936
+ }
937
+ const linksCreated = [];
938
+ const linksSuggested = [];
939
+ const searchQuery = extractSearchTerms(name, description);
940
+ if (searchQuery) {
941
+ const [searchResults, allCollections] = await Promise.all([
942
+ mcpQuery("chain.searchEntries", { query: searchQuery }),
943
+ mcpQuery("chain.listCollections")
944
+ ]);
945
+ const collMap = /* @__PURE__ */ new Map();
946
+ for (const c of allCollections) collMap.set(c._id, c.slug);
947
+ const candidates = (searchResults ?? []).filter((r) => r.entryId !== finalEntryId && r._id !== internalId).map((r) => ({
948
+ ...r,
949
+ collSlug: collMap.get(r.collectionId) ?? "unknown",
950
+ confidence: computeLinkConfidence(r, name, description, collection, collMap.get(r.collectionId) ?? "unknown")
951
+ })).sort((a, b) => b.confidence - a.confidence);
952
+ for (const c of candidates) {
953
+ if (linksCreated.length >= MAX_AUTO_LINKS) break;
954
+ if (c.confidence < AUTO_LINK_CONFIDENCE_THRESHOLD) break;
955
+ if (!c.entryId || !finalEntryId) continue;
956
+ const relationType = inferRelationType(collection, c.collSlug, profile);
957
+ try {
958
+ await mcpMutation("chain.createEntryRelation", {
959
+ fromEntryId: finalEntryId,
960
+ toEntryId: c.entryId,
961
+ type: relationType
962
+ });
963
+ linksCreated.push({
964
+ targetEntryId: c.entryId,
965
+ targetName: c.name,
966
+ targetCollection: c.collSlug,
967
+ relationType
968
+ });
969
+ } catch {
970
+ }
971
+ }
972
+ const linkedIds = new Set(linksCreated.map((l) => l.targetEntryId));
973
+ for (const c of candidates) {
974
+ if (linksSuggested.length >= MAX_SUGGESTIONS) break;
975
+ if (linkedIds.has(c.entryId)) continue;
976
+ if (c.confidence < 10) continue;
977
+ const preview = extractPreview(c.data, 80);
978
+ 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`;
979
+ linksSuggested.push({
980
+ entryId: c.entryId,
981
+ name: c.name,
982
+ collection: c.collSlug,
983
+ reason,
984
+ preview
985
+ });
986
+ }
987
+ }
988
+ const captureCtx = {
989
+ collection,
990
+ name,
991
+ description,
992
+ context,
993
+ data,
994
+ entryId: finalEntryId,
995
+ canonicalKey,
996
+ linksCreated,
997
+ linksSuggested,
998
+ collectionFields: col.fields ?? []
999
+ };
1000
+ const quality = scoreQuality(captureCtx, profile);
1001
+ let cardinalityWarning = null;
1002
+ const resolvedCK = canonicalKey ?? captureCtx.canonicalKey;
1003
+ if (resolvedCK) {
1004
+ try {
1005
+ const check = await mcpQuery("chain.checkCardinalityWarning", {
1006
+ canonicalKey: resolvedCK
1007
+ });
1008
+ if (check?.warning) {
1009
+ cardinalityWarning = check.warning;
1010
+ }
1011
+ } catch {
1012
+ }
1013
+ }
1014
+ const contradictionWarnings = await runContradictionCheck(name, description);
1015
+ if (contradictionWarnings.length > 0) {
1016
+ await recordSessionActivity({ contradictionWarning: true });
1017
+ }
1018
+ const wsCtx = await getWorkspaceContext();
1019
+ const lines = [
1020
+ `# Captured: ${finalEntryId || name}`,
1021
+ `**${name}** added to \`${collection}\` as \`${status}\``,
1022
+ `**Workspace:** ${wsCtx.workspaceSlug} (${wsCtx.workspaceId})`
1023
+ ];
1024
+ if (linksCreated.length > 0) {
1025
+ lines.push("");
1026
+ lines.push(`## Auto-linked (${linksCreated.length})`);
1027
+ for (const link of linksCreated) {
1028
+ lines.push(`- -> **${link.relationType}** ${link.targetEntryId}: ${link.targetName} [${link.targetCollection}]`);
1029
+ }
1030
+ }
1031
+ if (linksSuggested.length > 0) {
1032
+ lines.push("");
1033
+ lines.push("## Suggested links (review and use relate-entries)");
1034
+ for (let i = 0; i < linksSuggested.length; i++) {
1035
+ const s = linksSuggested[i];
1036
+ const preview = s.preview ? ` \u2014 ${s.preview}` : "";
1037
+ lines.push(`${i + 1}. **${s.entryId ?? "(no ID)"}**: ${s.name} [${s.collection}]${preview}`);
1038
+ }
1039
+ }
1040
+ lines.push("");
1041
+ lines.push(formatQualityReport(quality));
1042
+ const failedChecks = quality.checks.filter((c) => !c.passed);
1043
+ if (failedChecks.length > 0) {
1044
+ lines.push("");
1045
+ lines.push(`_To improve: \`update-entry entryId="${finalEntryId}"\` to fill missing fields._`);
1046
+ }
1047
+ if (cardinalityWarning) {
1048
+ lines.push("");
1049
+ lines.push(`**Cardinality warning:** ${cardinalityWarning}`);
1050
+ }
1051
+ if (contradictionWarnings.length > 0) {
1052
+ lines.push("");
1053
+ lines.push("\u26A0 Contradiction check: proposed entry matched existing governance entries:");
1054
+ for (const w of contradictionWarnings) {
1055
+ lines.push(`- ${w.name} (${w.collection}, ${w.entryId}) \u2014 has 'governs' relation to ${w.governsCount} entries`);
1056
+ }
1057
+ lines.push("Run gather-context on these entries before committing.");
1058
+ }
1059
+ lines.push("");
1060
+ lines.push("## Next Steps");
1061
+ const eid = finalEntryId || "(check entry ID)";
1062
+ lines.push(`1. **Connect it:** \`suggest-links entryId="${eid}"\` \u2014 discover what this should link to`);
1063
+ lines.push(`2. **Commit it:** \`commit-entry entryId="${eid}"\` \u2014 promote from draft to SSOT on the Chain`);
1064
+ if (failedChecks.length > 0) {
1065
+ lines.push(`3. **Improve quality:** \`update-entry entryId="${eid}"\` \u2014 fill missing fields`);
1066
+ }
1067
+ try {
1068
+ const readiness = await mcpQuery("chain.workspaceReadiness");
1069
+ if (readiness && readiness.gaps && readiness.gaps.length > 0) {
1070
+ const topGaps = readiness.gaps.slice(0, 2);
1071
+ lines.push("");
1072
+ lines.push(`## Workspace Readiness: ${readiness.score}%`);
1073
+ for (const gap of topGaps) {
1074
+ lines.push(`- _${gap.label}:_ ${gap.guidance}`);
1075
+ }
1076
+ }
1077
+ } catch {
1078
+ }
1079
+ return { content: [{ type: "text", text: lines.join("\n") }] };
1080
+ }
1081
+ );
1082
+ server.registerTool(
1083
+ "batch-capture",
1084
+ {
1085
+ title: "Batch Capture",
1086
+ 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-check` on individual entries afterward if needed.",
1087
+ inputSchema: {
1088
+ entries: z.array(z.object({
1089
+ collection: z.string().describe("Collection slug"),
1090
+ name: z.string().describe("Display name"),
1091
+ description: z.string().describe("Full context / definition"),
1092
+ entryId: z.string().optional().describe("Optional custom entry ID")
1093
+ })).min(1).max(50).describe("Array of entries to capture")
1094
+ },
1095
+ annotations: { destructiveHint: false }
1096
+ },
1097
+ async ({ entries }) => {
1098
+ requireWriteAccess();
1099
+ const agentId = getAgentSessionId();
1100
+ const createdBy = agentId ? `agent:${agentId}` : "capture";
1101
+ const results = [];
1102
+ const allCollections = await mcpQuery("chain.listCollections");
1103
+ const collCache = /* @__PURE__ */ new Map();
1104
+ for (const c of allCollections) collCache.set(c.slug, c);
1105
+ const collIdToSlug = /* @__PURE__ */ new Map();
1106
+ for (const c of allCollections) collIdToSlug.set(c._id, c.slug);
1107
+ for (const entry of entries) {
1108
+ const profile = PROFILES.get(entry.collection) ?? FALLBACK_PROFILE;
1109
+ const col = collCache.get(entry.collection);
1110
+ if (!col) {
1111
+ results.push({ name: entry.name, collection: entry.collection, entryId: "", ok: false, autoLinks: 0, error: `Collection "${entry.collection}" not found` });
1112
+ continue;
1113
+ }
1114
+ const finalEntryId = entry.entryId ?? generateEntryId(profile.idPrefix);
1115
+ const data = {};
1116
+ const today = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
1117
+ for (const field of col.fields ?? []) {
1118
+ const key = field.key;
1119
+ if (key === profile.descriptionField) {
1120
+ data[key] = entry.description;
1121
+ } else if (field.type === "array" || field.type === "multi-select") {
1122
+ data[key] = [];
1123
+ } else if (field.type === "select") {
1124
+ } else {
1125
+ data[key] = "";
1126
+ }
1127
+ }
1128
+ for (const def of profile.defaults) {
1129
+ if (def.value === "today") data[def.key] = today;
1130
+ else if (def.value !== "infer") data[def.key] = def.value;
1131
+ }
1132
+ if (profile.inferField) {
1133
+ const inferred = profile.inferField({
1134
+ collection: entry.collection,
1135
+ name: entry.name,
1136
+ description: entry.description,
1137
+ data,
1138
+ entryId: "",
1139
+ linksCreated: [],
1140
+ linksSuggested: [],
1141
+ collectionFields: col.fields ?? []
1142
+ });
1143
+ for (const [key, val] of Object.entries(inferred)) {
1144
+ if (val !== void 0 && val !== "") data[key] = val;
1145
+ }
1146
+ }
1147
+ if (!data[profile.descriptionField] && !data.description && !data.canonical) {
1148
+ data[profile.descriptionField || "description"] = entry.description;
1149
+ }
1150
+ try {
1151
+ const internalId = await mcpMutation("chain.createEntry", {
1152
+ collectionSlug: entry.collection,
1153
+ entryId: finalEntryId,
1154
+ name: entry.name,
1155
+ status: "draft",
1156
+ data,
1157
+ createdBy,
1158
+ sessionId: agentId ?? void 0
1159
+ });
1160
+ let autoLinkCount = 0;
1161
+ const searchQuery = extractSearchTerms(entry.name, entry.description);
1162
+ if (searchQuery) {
1163
+ try {
1164
+ const searchResults = await mcpQuery("chain.searchEntries", { query: searchQuery });
1165
+ const candidates = (searchResults ?? []).filter((r) => r.entryId !== finalEntryId).map((r) => ({
1166
+ ...r,
1167
+ collSlug: collIdToSlug.get(r.collectionId) ?? "unknown",
1168
+ confidence: computeLinkConfidence(r, entry.name, entry.description, entry.collection, collIdToSlug.get(r.collectionId) ?? "unknown")
1169
+ })).sort((a, b) => b.confidence - a.confidence);
1170
+ for (const c of candidates) {
1171
+ if (autoLinkCount >= MAX_AUTO_LINKS) break;
1172
+ if (c.confidence < AUTO_LINK_CONFIDENCE_THRESHOLD) break;
1173
+ if (!c.entryId) continue;
1174
+ const relationType = inferRelationType(entry.collection, c.collSlug, profile);
1175
+ try {
1176
+ await mcpMutation("chain.createEntryRelation", {
1177
+ fromEntryId: finalEntryId,
1178
+ toEntryId: c.entryId,
1179
+ type: relationType
1180
+ });
1181
+ autoLinkCount++;
1182
+ } catch {
1183
+ }
1184
+ }
1185
+ } catch {
1186
+ }
1187
+ }
1188
+ results.push({ name: entry.name, collection: entry.collection, entryId: finalEntryId, ok: true, autoLinks: autoLinkCount });
1189
+ await recordSessionActivity({ entryCreated: internalId });
1190
+ } catch (error) {
1191
+ const msg = error instanceof Error ? error.message : String(error);
1192
+ results.push({ name: entry.name, collection: entry.collection, entryId: finalEntryId, ok: false, autoLinks: 0, error: msg });
1193
+ }
1194
+ }
1195
+ const created = results.filter((r) => r.ok);
1196
+ const failed = results.filter((r) => !r.ok);
1197
+ const totalAutoLinks = created.reduce((sum, r) => sum + r.autoLinks, 0);
1198
+ const byCollection = /* @__PURE__ */ new Map();
1199
+ for (const r of created) {
1200
+ byCollection.set(r.collection, (byCollection.get(r.collection) ?? 0) + 1);
1201
+ }
1202
+ const lines = [
1203
+ `# Batch Capture Complete`,
1204
+ `**${created.length}** created, **${failed.length}** failed out of ${entries.length} total.`,
1205
+ `**Auto-links created:** ${totalAutoLinks}`,
1206
+ ""
1207
+ ];
1208
+ if (byCollection.size > 0) {
1209
+ lines.push("## By Collection");
1210
+ for (const [col, count] of byCollection) {
1211
+ lines.push(`- \`${col}\`: ${count} entries`);
1212
+ }
1213
+ lines.push("");
1214
+ }
1215
+ if (created.length > 0) {
1216
+ lines.push("## Created");
1217
+ for (const r of created) {
1218
+ const linkNote = r.autoLinks > 0 ? ` (${r.autoLinks} auto-links)` : "";
1219
+ lines.push(`- **${r.entryId}**: ${r.name} [${r.collection}]${linkNote}`);
1220
+ }
1221
+ }
1222
+ if (failed.length > 0) {
1223
+ lines.push("");
1224
+ lines.push("## Failed");
1225
+ for (const r of failed) {
1226
+ lines.push(`- ${r.name} [${r.collection}]: _${r.error}_`);
1227
+ }
1228
+ }
1229
+ const entryIds = created.map((r) => r.entryId);
1230
+ if (entryIds.length > 0) {
1231
+ lines.push("");
1232
+ lines.push("## Next Steps");
1233
+ lines.push(`- **Connect:** Run \`suggest-links\` on key entries to build the knowledge graph`);
1234
+ lines.push(`- **Commit:** Use \`commit-entry\` to promote drafts to SSOT`);
1235
+ lines.push(`- **Quality:** Run \`quality-check\` on individual entries to assess completeness`);
1236
+ }
1237
+ return { content: [{ type: "text", text: lines.join("\n") }] };
1238
+ }
1239
+ );
1240
+ server.registerTool(
1241
+ "quality-check",
1242
+ {
1243
+ title: "Quality Check",
1244
+ description: "Score an existing knowledge entry against collection-specific quality criteria. Returns a scorecard (X/10) with specific, actionable suggestions for improvement \u2014 including concrete link suggestions from graph analysis when relations are missing.\n\nChecks: name clarity, description completeness, relation connectedness, and collection-specific fields.\n\nUse after creating entries to assess their quality, or to audit existing entries.",
1245
+ inputSchema: {
1246
+ entryId: z.string().describe("Entry ID to check, e.g. 'TEN-graph-db', 'GT-019', 'SOS-006'")
1247
+ },
1248
+ annotations: { readOnlyHint: true }
1249
+ },
1250
+ async ({ entryId }) => {
1251
+ const result = await checkEntryQuality(entryId);
1252
+ const needsRelations = result.quality.checks.some(
1253
+ (c) => !c.passed && (c.id === "has-relations" || c.id === "diverse-relations")
1254
+ );
1255
+ if (needsRelations) {
1256
+ try {
1257
+ const suggestions = await mcpQuery("chain.graphSuggestLinks", {
1258
+ entryId,
1259
+ maxHops: 2,
1260
+ limit: 3
1261
+ });
1262
+ if (suggestions?.suggestions?.length > 0) {
1263
+ const linkHints = suggestions.suggestions.map((s) => ` \u2192 \`relate-entries from='${entryId}' to='${s.entryId}' type='${s.recommendedRelationType}'\` \u2014 ${s.name} [${s.collectionSlug}] (${s.score}/100)`).join("\n");
1264
+ result.text += `
1265
+
1266
+ ## Suggested Links to Improve Quality
1267
+ ${linkHints}`;
1268
+ }
1269
+ } catch {
1270
+ }
1271
+ }
1272
+ return { content: [{ type: "text", text: result.text }] };
1273
+ }
1274
+ );
1275
+ }
1276
+ function extractPreview(data, maxLen) {
1277
+ if (!data || typeof data !== "object") return "";
1278
+ const raw = data.description ?? data.canonical ?? data.detail ?? data.rule ?? "";
1279
+ if (typeof raw !== "string" || !raw) return "";
1280
+ return raw.length > maxLen ? raw.substring(0, maxLen) + "..." : raw;
1281
+ }
1282
+ var STOP_WORDS = /* @__PURE__ */ new Set([
1283
+ "the",
1284
+ "and",
1285
+ "for",
1286
+ "are",
1287
+ "but",
1288
+ "not",
1289
+ "you",
1290
+ "all",
1291
+ "can",
1292
+ "has",
1293
+ "her",
1294
+ "was",
1295
+ "one",
1296
+ "our",
1297
+ "out",
1298
+ "day",
1299
+ "had",
1300
+ "hot",
1301
+ "how",
1302
+ "its",
1303
+ "may",
1304
+ "new",
1305
+ "now",
1306
+ "old",
1307
+ "see",
1308
+ "way",
1309
+ "who",
1310
+ "did",
1311
+ "get",
1312
+ "let",
1313
+ "say",
1314
+ "she",
1315
+ "too",
1316
+ "use",
1317
+ "from",
1318
+ "have",
1319
+ "been",
1320
+ "each",
1321
+ "that",
1322
+ "this",
1323
+ "with",
1324
+ "will",
1325
+ "they",
1326
+ "what",
1327
+ "when",
1328
+ "make",
1329
+ "like",
1330
+ "long",
1331
+ "look",
1332
+ "many",
1333
+ "some",
1334
+ "them",
1335
+ "than",
1336
+ "most",
1337
+ "only",
1338
+ "over",
1339
+ "such",
1340
+ "into",
1341
+ "also",
1342
+ "back",
1343
+ "just",
1344
+ "much",
1345
+ "must",
1346
+ "name",
1347
+ "very",
1348
+ "your",
1349
+ "after",
1350
+ "which",
1351
+ "their",
1352
+ "about",
1353
+ "would",
1354
+ "there",
1355
+ "should",
1356
+ "could",
1357
+ "other",
1358
+ "these",
1359
+ "first",
1360
+ "being",
1361
+ "those",
1362
+ "still",
1363
+ "where"
1364
+ ]);
1365
+ async function runContradictionCheck(name, description) {
1366
+ const warnings = [];
1367
+ try {
1368
+ const text = `${name} ${description}`.toLowerCase();
1369
+ const keyTerms = text.split(/\s+/).filter((w) => w.length >= 4 && !STOP_WORDS.has(w)).slice(0, 8);
1370
+ if (keyTerms.length === 0) return warnings;
1371
+ const searchQuery = keyTerms.slice(0, 3).join(" ");
1372
+ const [govResults, archResults] = await Promise.all([
1373
+ mcpQuery("chain.searchEntries", { query: searchQuery, collectionSlug: "business-rules" }),
1374
+ mcpQuery("chain.searchEntries", { query: searchQuery, collectionSlug: "architecture" })
1375
+ ]);
1376
+ const allGov = [...govResults ?? [], ...archResults ?? []].slice(0, 5);
1377
+ for (const entry of allGov) {
1378
+ const entryText = `${entry.name} ${entry.data?.description ?? ""}`.toLowerCase();
1379
+ const matched = keyTerms.filter((t) => entryText.includes(t));
1380
+ if (matched.length < 2) continue;
1381
+ let governsCount = 0;
1382
+ try {
1383
+ const relations = await mcpQuery("chain.listEntryRelations", {
1384
+ entryId: entry.entryId
1385
+ });
1386
+ governsCount = (relations ?? []).filter((r) => r.type === "governs").length;
1387
+ } catch {
1388
+ }
1389
+ warnings.push({
1390
+ entryId: entry.entryId ?? "",
1391
+ name: entry.name,
1392
+ collection: entry.collectionSlug ?? "",
1393
+ governsCount
1394
+ });
1395
+ }
1396
+ } catch {
1397
+ }
1398
+ return warnings;
1399
+ }
1400
+
1401
+ export {
1402
+ runWithAuth,
1403
+ getAgentSessionId,
1404
+ isSessionOriented,
1405
+ setSessionOriented,
1406
+ startAgentSession,
1407
+ closeAgentSession,
1408
+ orphanAgentSession,
1409
+ recordSessionActivity,
1410
+ bootstrap,
1411
+ bootstrapHttp,
1412
+ getAuditLog,
1413
+ mcpCall,
1414
+ getWorkspaceId,
1415
+ getWorkspaceContext,
1416
+ mcpQuery,
1417
+ mcpMutation,
1418
+ requireWriteAccess,
1419
+ recoverSessionState,
1420
+ formatQualityReport,
1421
+ checkEntryQuality,
1422
+ registerSmartCaptureTools,
1423
+ runContradictionCheck
1424
+ };
1425
+ //# sourceMappingURL=chunk-CXYNWTRQ.js.map