@productbrain/mcp 0.0.1-beta.3 → 0.0.1-beta.31
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.
- package/.env.mcp.example +8 -13
- package/dist/chunk-3JSR5JCU.js +1785 -0
- package/dist/chunk-3JSR5JCU.js.map +1 -0
- package/dist/chunk-AZHB7KMP.js +6417 -0
- package/dist/chunk-AZHB7KMP.js.map +1 -0
- package/dist/chunk-SJ2ODB3Y.js +128 -0
- package/dist/chunk-SJ2ODB3Y.js.map +1 -0
- package/dist/cli/index.js +1 -1
- package/dist/http.js +402 -0
- package/dist/http.js.map +1 -0
- package/dist/index.js +46 -4222
- package/dist/index.js.map +1 -1
- package/dist/setup-S2B5LCXQ.js +365 -0
- package/dist/setup-S2B5LCXQ.js.map +1 -0
- package/dist/smart-capture-X7BWHT4P.js +26 -0
- package/package.json +4 -1
- package/dist/chunk-DGUM43GV.js +0 -11
- package/dist/setup-V6HIAYXL.js +0 -227
- package/dist/setup-V6HIAYXL.js.map +0 -1
- /package/dist/{chunk-DGUM43GV.js.map → smart-capture-X7BWHT4P.js.map} +0 -0
|
@@ -0,0 +1,1785 @@
|
|
|
1
|
+
import {
|
|
2
|
+
trackQualityVerdict,
|
|
3
|
+
trackToolCall
|
|
4
|
+
} from "./chunk-SJ2ODB3Y.js";
|
|
5
|
+
|
|
6
|
+
// src/tools/smart-capture.ts
|
|
7
|
+
import { z } from "zod";
|
|
8
|
+
|
|
9
|
+
// src/client.ts
|
|
10
|
+
import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
|
|
11
|
+
|
|
12
|
+
// src/auth.ts
|
|
13
|
+
import { AsyncLocalStorage } from "async_hooks";
|
|
14
|
+
var requestStore = new AsyncLocalStorage();
|
|
15
|
+
function runWithAuth(auth, fn) {
|
|
16
|
+
return requestStore.run(auth, fn);
|
|
17
|
+
}
|
|
18
|
+
function getRequestApiKey() {
|
|
19
|
+
return requestStore.getStore()?.apiKey;
|
|
20
|
+
}
|
|
21
|
+
var SESSION_TTL_MS = 30 * 60 * 1e3;
|
|
22
|
+
var MAX_KEYS = 100;
|
|
23
|
+
var keyStateMap = /* @__PURE__ */ new Map();
|
|
24
|
+
function newKeyState() {
|
|
25
|
+
return {
|
|
26
|
+
workspaceId: null,
|
|
27
|
+
workspaceSlug: null,
|
|
28
|
+
workspaceName: null,
|
|
29
|
+
workspaceCreatedAt: null,
|
|
30
|
+
agentSessionId: null,
|
|
31
|
+
apiKeyId: null,
|
|
32
|
+
apiKeyScope: "readwrite",
|
|
33
|
+
sessionOriented: false,
|
|
34
|
+
sessionClosed: false,
|
|
35
|
+
lastAccess: Date.now()
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
function getKeyState(apiKey) {
|
|
39
|
+
let s = keyStateMap.get(apiKey);
|
|
40
|
+
if (!s) {
|
|
41
|
+
s = newKeyState();
|
|
42
|
+
keyStateMap.set(apiKey, s);
|
|
43
|
+
evictStale();
|
|
44
|
+
}
|
|
45
|
+
s.lastAccess = Date.now();
|
|
46
|
+
return s;
|
|
47
|
+
}
|
|
48
|
+
function evictStale() {
|
|
49
|
+
if (keyStateMap.size <= MAX_KEYS) return;
|
|
50
|
+
const now = Date.now();
|
|
51
|
+
for (const [key, s] of keyStateMap) {
|
|
52
|
+
if (now - s.lastAccess > SESSION_TTL_MS) keyStateMap.delete(key);
|
|
53
|
+
}
|
|
54
|
+
if (keyStateMap.size > MAX_KEYS) {
|
|
55
|
+
const sorted = [...keyStateMap.entries()].sort((a, b) => a[1].lastAccess - b[1].lastAccess);
|
|
56
|
+
for (let i = 0; i < sorted.length - MAX_KEYS; i++) {
|
|
57
|
+
keyStateMap.delete(sorted[i][0]);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
// src/client.ts
|
|
63
|
+
var toolContextStore = new AsyncLocalStorage2();
|
|
64
|
+
function runWithToolContext(ctx, fn) {
|
|
65
|
+
return toolContextStore.run(ctx, fn);
|
|
66
|
+
}
|
|
67
|
+
function getToolContext() {
|
|
68
|
+
return toolContextStore.getStore() ?? null;
|
|
69
|
+
}
|
|
70
|
+
var DEFAULT_CLOUD_URL = "https://trustworthy-kangaroo-277.convex.site";
|
|
71
|
+
var CACHE_TTL_MS = 6e4;
|
|
72
|
+
var CACHEABLE_FNS = [
|
|
73
|
+
"chain.getOrientEntries",
|
|
74
|
+
"chain.gatherContext",
|
|
75
|
+
"chain.graphGatherContext",
|
|
76
|
+
"chain.taskAwareGatherContext",
|
|
77
|
+
"chain.assembleBuildContext"
|
|
78
|
+
];
|
|
79
|
+
function isCacheable(fn) {
|
|
80
|
+
return CACHEABLE_FNS.includes(fn);
|
|
81
|
+
}
|
|
82
|
+
var READ_PATTERN = /^(chain\.(get|list|search|batchGet|gather|graph|task|assemble|workspace|score|absence)|maps\.(get|list)|gitchain\.(get|list|diff|history|runGate))/i;
|
|
83
|
+
function isWrite(fn) {
|
|
84
|
+
if (fn.startsWith("agent.")) return false;
|
|
85
|
+
return !READ_PATTERN.test(fn);
|
|
86
|
+
}
|
|
87
|
+
var readCache = /* @__PURE__ */ new Map();
|
|
88
|
+
function cacheKey(fn, args) {
|
|
89
|
+
return `${fn}:${JSON.stringify(args)}`;
|
|
90
|
+
}
|
|
91
|
+
function getCached(fn, args) {
|
|
92
|
+
if (!isCacheable(fn)) return void 0;
|
|
93
|
+
const key = cacheKey(fn, args);
|
|
94
|
+
const entry = readCache.get(key);
|
|
95
|
+
if (!entry || Date.now() > entry.expiresAt) {
|
|
96
|
+
if (entry) readCache.delete(key);
|
|
97
|
+
return void 0;
|
|
98
|
+
}
|
|
99
|
+
return entry.data;
|
|
100
|
+
}
|
|
101
|
+
function setCached(fn, args, data) {
|
|
102
|
+
if (!isCacheable(fn)) return;
|
|
103
|
+
const key = cacheKey(fn, args);
|
|
104
|
+
readCache.set(key, { data, expiresAt: Date.now() + CACHE_TTL_MS });
|
|
105
|
+
}
|
|
106
|
+
function invalidateReadCache() {
|
|
107
|
+
readCache.clear();
|
|
108
|
+
}
|
|
109
|
+
var _stdioState = {
|
|
110
|
+
workspaceId: null,
|
|
111
|
+
workspaceSlug: null,
|
|
112
|
+
workspaceName: null,
|
|
113
|
+
workspaceCreatedAt: null,
|
|
114
|
+
agentSessionId: null,
|
|
115
|
+
apiKeyId: null,
|
|
116
|
+
apiKeyScope: "readwrite",
|
|
117
|
+
sessionOriented: false,
|
|
118
|
+
sessionClosed: false,
|
|
119
|
+
lastAccess: 0
|
|
120
|
+
};
|
|
121
|
+
function state() {
|
|
122
|
+
const reqKey = getRequestApiKey();
|
|
123
|
+
if (reqKey) return getKeyState(reqKey);
|
|
124
|
+
return _stdioState;
|
|
125
|
+
}
|
|
126
|
+
function getActiveApiKey() {
|
|
127
|
+
const fromRequest = getRequestApiKey();
|
|
128
|
+
if (fromRequest) return fromRequest;
|
|
129
|
+
const fromEnv = process.env.PRODUCTBRAIN_API_KEY;
|
|
130
|
+
if (!fromEnv) throw new Error("No API key available \u2014 set PRODUCTBRAIN_API_KEY or provide Bearer token");
|
|
131
|
+
return fromEnv;
|
|
132
|
+
}
|
|
133
|
+
function getAgentSessionId() {
|
|
134
|
+
return state().agentSessionId;
|
|
135
|
+
}
|
|
136
|
+
function isSessionOriented() {
|
|
137
|
+
return state().sessionOriented;
|
|
138
|
+
}
|
|
139
|
+
function setSessionOriented(value) {
|
|
140
|
+
state().sessionOriented = value;
|
|
141
|
+
}
|
|
142
|
+
function getApiKeyScope() {
|
|
143
|
+
return state().apiKeyScope;
|
|
144
|
+
}
|
|
145
|
+
async function startAgentSession() {
|
|
146
|
+
const workspaceId = await getWorkspaceId();
|
|
147
|
+
const s = state();
|
|
148
|
+
if (!s.apiKeyId) {
|
|
149
|
+
throw new Error("Cannot start session: API key ID not resolved. Ensure workspace resolution completed.");
|
|
150
|
+
}
|
|
151
|
+
const result = await mcpCall("agent.startSession", {
|
|
152
|
+
workspaceId,
|
|
153
|
+
apiKeyId: s.apiKeyId
|
|
154
|
+
});
|
|
155
|
+
s.agentSessionId = result.sessionId;
|
|
156
|
+
s.apiKeyScope = result.toolsScope;
|
|
157
|
+
s.sessionOriented = false;
|
|
158
|
+
s.sessionClosed = false;
|
|
159
|
+
resetTouchThrottle();
|
|
160
|
+
return result;
|
|
161
|
+
}
|
|
162
|
+
async function closeAgentSession() {
|
|
163
|
+
const s = state();
|
|
164
|
+
if (!s.agentSessionId) return;
|
|
165
|
+
try {
|
|
166
|
+
await mcpCall("agent.closeSession", {
|
|
167
|
+
sessionId: s.agentSessionId,
|
|
168
|
+
status: "closed"
|
|
169
|
+
});
|
|
170
|
+
} finally {
|
|
171
|
+
s.sessionClosed = true;
|
|
172
|
+
s.agentSessionId = null;
|
|
173
|
+
s.sessionOriented = false;
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
async function orphanAgentSession() {
|
|
177
|
+
const s = state();
|
|
178
|
+
if (!s.agentSessionId) return;
|
|
179
|
+
try {
|
|
180
|
+
await mcpCall("agent.closeSession", {
|
|
181
|
+
sessionId: s.agentSessionId,
|
|
182
|
+
status: "orphaned"
|
|
183
|
+
});
|
|
184
|
+
} catch {
|
|
185
|
+
} finally {
|
|
186
|
+
s.agentSessionId = null;
|
|
187
|
+
s.sessionOriented = false;
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
var _lastTouchAt = 0;
|
|
191
|
+
var TOUCH_THROTTLE_MS = 5e3;
|
|
192
|
+
function touchSessionActivity() {
|
|
193
|
+
const s = state();
|
|
194
|
+
if (!s.agentSessionId) return;
|
|
195
|
+
const now = Date.now();
|
|
196
|
+
if (now - _lastTouchAt < TOUCH_THROTTLE_MS) return;
|
|
197
|
+
_lastTouchAt = now;
|
|
198
|
+
mcpCall("agent.touchSession", {
|
|
199
|
+
sessionId: s.agentSessionId
|
|
200
|
+
}).catch(() => {
|
|
201
|
+
});
|
|
202
|
+
}
|
|
203
|
+
function resetTouchThrottle() {
|
|
204
|
+
_lastTouchAt = 0;
|
|
205
|
+
}
|
|
206
|
+
async function recordSessionActivity(activity) {
|
|
207
|
+
const s = state();
|
|
208
|
+
if (!s.agentSessionId) return;
|
|
209
|
+
try {
|
|
210
|
+
await mcpCall("agent.recordActivity", {
|
|
211
|
+
sessionId: s.agentSessionId,
|
|
212
|
+
...activity
|
|
213
|
+
});
|
|
214
|
+
} catch {
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
var AUDIT_BUFFER_SIZE = 50;
|
|
218
|
+
var auditBuffer = [];
|
|
219
|
+
function bootstrap() {
|
|
220
|
+
const pbKey = process.env.PRODUCTBRAIN_API_KEY;
|
|
221
|
+
if (!pbKey?.startsWith("pb_sk_")) {
|
|
222
|
+
throw new Error(
|
|
223
|
+
"PRODUCTBRAIN_API_KEY is required and must start with 'pb_sk_'. Generate one at Settings > API Keys in the Product OS UI."
|
|
224
|
+
);
|
|
225
|
+
}
|
|
226
|
+
process.env.CONVEX_SITE_URL ??= process.env.PRODUCTBRAIN_URL ?? DEFAULT_CLOUD_URL;
|
|
227
|
+
}
|
|
228
|
+
function bootstrapHttp() {
|
|
229
|
+
process.env.CONVEX_SITE_URL ??= process.env.PRODUCTBRAIN_URL ?? DEFAULT_CLOUD_URL;
|
|
230
|
+
}
|
|
231
|
+
function getEnv(key) {
|
|
232
|
+
const value = process.env[key];
|
|
233
|
+
if (!value) throw new Error(`${key} environment variable is required`);
|
|
234
|
+
return value;
|
|
235
|
+
}
|
|
236
|
+
function shouldLogAudit(status) {
|
|
237
|
+
return status === "error" || process.env.MCP_DEBUG === "1";
|
|
238
|
+
}
|
|
239
|
+
function audit(fn, status, durationMs, errorMsg) {
|
|
240
|
+
const ts = (/* @__PURE__ */ new Date()).toISOString();
|
|
241
|
+
const workspace = state().workspaceId ?? "unresolved";
|
|
242
|
+
const toolCtx = getToolContext();
|
|
243
|
+
const entry = { ts, fn, workspace, status, durationMs };
|
|
244
|
+
if (errorMsg) entry.error = errorMsg;
|
|
245
|
+
if (toolCtx) entry.toolContext = toolCtx;
|
|
246
|
+
auditBuffer.push(entry);
|
|
247
|
+
if (auditBuffer.length > AUDIT_BUFFER_SIZE) auditBuffer.shift();
|
|
248
|
+
trackToolCall(fn, status, durationMs, workspace, errorMsg);
|
|
249
|
+
if (!shouldLogAudit(status)) return;
|
|
250
|
+
const base = `[MCP-AUDIT] ${ts} fn=${fn} workspace=${workspace} status=${status} duration=${durationMs}ms`;
|
|
251
|
+
if (status === "error" && errorMsg) {
|
|
252
|
+
process.stderr.write(`${base} error=${JSON.stringify(errorMsg)}
|
|
253
|
+
`);
|
|
254
|
+
} else {
|
|
255
|
+
process.stderr.write(`${base}
|
|
256
|
+
`);
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
function getAuditLog() {
|
|
260
|
+
return auditBuffer;
|
|
261
|
+
}
|
|
262
|
+
async function mcpCall(fn, args = {}) {
|
|
263
|
+
const cached = getCached(fn, args);
|
|
264
|
+
if (cached !== void 0) {
|
|
265
|
+
return cached;
|
|
266
|
+
}
|
|
267
|
+
const siteUrl = getEnv("CONVEX_SITE_URL").replace(/\/$/, "");
|
|
268
|
+
const apiKey = getActiveApiKey();
|
|
269
|
+
const start = Date.now();
|
|
270
|
+
let res;
|
|
271
|
+
try {
|
|
272
|
+
res = await fetch(`${siteUrl}/api/mcp`, {
|
|
273
|
+
method: "POST",
|
|
274
|
+
headers: {
|
|
275
|
+
"Content-Type": "application/json",
|
|
276
|
+
Authorization: `Bearer ${apiKey}`
|
|
277
|
+
},
|
|
278
|
+
body: JSON.stringify({ fn, args })
|
|
279
|
+
});
|
|
280
|
+
} catch (err) {
|
|
281
|
+
audit(fn, "error", Date.now() - start, err.message);
|
|
282
|
+
throw new Error(`MCP call "${fn}" network error: ${err.message}`);
|
|
283
|
+
}
|
|
284
|
+
const json = await res.json();
|
|
285
|
+
if (!res.ok || json.error) {
|
|
286
|
+
audit(fn, "error", Date.now() - start, json.error);
|
|
287
|
+
throw new Error(`MCP call "${fn}" failed (${res.status}): ${json.error ?? "unknown error"}`);
|
|
288
|
+
}
|
|
289
|
+
audit(fn, "ok", Date.now() - start);
|
|
290
|
+
const data = json.data;
|
|
291
|
+
if (isWrite(fn)) {
|
|
292
|
+
invalidateReadCache();
|
|
293
|
+
} else {
|
|
294
|
+
setCached(fn, args, data);
|
|
295
|
+
}
|
|
296
|
+
const s = state();
|
|
297
|
+
if (s.agentSessionId && fn !== "agent.touchSession" && fn !== "agent.startSession") {
|
|
298
|
+
touchSessionActivity();
|
|
299
|
+
}
|
|
300
|
+
return data;
|
|
301
|
+
}
|
|
302
|
+
var resolveInFlightMap = /* @__PURE__ */ new Map();
|
|
303
|
+
async function getWorkspaceId() {
|
|
304
|
+
const s = state();
|
|
305
|
+
if (s.workspaceId) return s.workspaceId;
|
|
306
|
+
const apiKey = getActiveApiKey();
|
|
307
|
+
const existing = resolveInFlightMap.get(apiKey);
|
|
308
|
+
if (existing) return existing;
|
|
309
|
+
const promise = resolveWorkspaceWithRetry().finally(() => resolveInFlightMap.delete(apiKey));
|
|
310
|
+
resolveInFlightMap.set(apiKey, promise);
|
|
311
|
+
return promise;
|
|
312
|
+
}
|
|
313
|
+
async function resolveWorkspaceWithRetry(maxRetries = 2) {
|
|
314
|
+
let lastError = null;
|
|
315
|
+
for (let attempt = 0; attempt <= maxRetries; attempt++) {
|
|
316
|
+
try {
|
|
317
|
+
const workspace = await mcpCall("resolveWorkspace", {});
|
|
318
|
+
if (!workspace) {
|
|
319
|
+
throw new Error(
|
|
320
|
+
"API key is valid but no workspace is associated. Run `npx productbrain setup` or regenerate your key."
|
|
321
|
+
);
|
|
322
|
+
}
|
|
323
|
+
const s = state();
|
|
324
|
+
s.workspaceId = workspace._id;
|
|
325
|
+
s.workspaceSlug = workspace.slug;
|
|
326
|
+
s.workspaceName = workspace.name;
|
|
327
|
+
s.workspaceCreatedAt = workspace.createdAt ?? null;
|
|
328
|
+
if (workspace.keyScope) s.apiKeyScope = workspace.keyScope;
|
|
329
|
+
if (workspace.keyId) s.apiKeyId = workspace.keyId;
|
|
330
|
+
return s.workspaceId;
|
|
331
|
+
} catch (err) {
|
|
332
|
+
lastError = err;
|
|
333
|
+
const isTransient = /network error|fetch failed|ECONNREFUSED|ETIMEDOUT/i.test(err.message);
|
|
334
|
+
if (!isTransient || attempt === maxRetries) break;
|
|
335
|
+
const delay = 1e3 * (attempt + 1);
|
|
336
|
+
process.stderr.write(
|
|
337
|
+
`[MCP] Workspace resolution failed (attempt ${attempt + 1}/${maxRetries + 1}), retrying in ${delay}ms...
|
|
338
|
+
`
|
|
339
|
+
);
|
|
340
|
+
await new Promise((r) => setTimeout(r, delay));
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
throw lastError;
|
|
344
|
+
}
|
|
345
|
+
async function getWorkspaceContext() {
|
|
346
|
+
const workspaceId = await getWorkspaceId();
|
|
347
|
+
const s = state();
|
|
348
|
+
return {
|
|
349
|
+
workspaceId,
|
|
350
|
+
workspaceSlug: s.workspaceSlug ?? "unknown",
|
|
351
|
+
workspaceName: s.workspaceName ?? "unknown",
|
|
352
|
+
createdAt: s.workspaceCreatedAt
|
|
353
|
+
};
|
|
354
|
+
}
|
|
355
|
+
async function mcpQuery(fn, args = {}) {
|
|
356
|
+
const workspaceId = await getWorkspaceId();
|
|
357
|
+
return mcpCall(fn, { ...args, workspaceId });
|
|
358
|
+
}
|
|
359
|
+
async function mcpMutation(fn, args = {}) {
|
|
360
|
+
const workspaceId = await getWorkspaceId();
|
|
361
|
+
return mcpCall(fn, { ...args, workspaceId });
|
|
362
|
+
}
|
|
363
|
+
function requireActiveSession() {
|
|
364
|
+
const s = state();
|
|
365
|
+
if (!s.agentSessionId) {
|
|
366
|
+
throw new Error(
|
|
367
|
+
"Active session required (SOS-iszqu7). Call `session action=start` then `orient` first."
|
|
368
|
+
);
|
|
369
|
+
}
|
|
370
|
+
if (s.sessionClosed) {
|
|
371
|
+
throw new Error(
|
|
372
|
+
"Session has been closed (SOS-iszqu7). Start a new session with `session action=start`."
|
|
373
|
+
);
|
|
374
|
+
}
|
|
375
|
+
if (!s.sessionOriented) {
|
|
376
|
+
throw new Error(
|
|
377
|
+
"Orientation required before accessing build context (SOS-iszqu7). Call `orient` first."
|
|
378
|
+
);
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
function requireWriteAccess() {
|
|
382
|
+
const s = state();
|
|
383
|
+
if (!s.agentSessionId) {
|
|
384
|
+
throw new Error(
|
|
385
|
+
"Agent session required for write operations. Call `session action=start` first."
|
|
386
|
+
);
|
|
387
|
+
}
|
|
388
|
+
if (s.sessionClosed) {
|
|
389
|
+
throw new Error(
|
|
390
|
+
"Agent session has been closed. Write tools are no longer available."
|
|
391
|
+
);
|
|
392
|
+
}
|
|
393
|
+
if (!s.sessionOriented) {
|
|
394
|
+
throw new Error(
|
|
395
|
+
"Orientation required before writing to the Chain. Call 'orient' first."
|
|
396
|
+
);
|
|
397
|
+
}
|
|
398
|
+
if (s.apiKeyScope === "read") {
|
|
399
|
+
throw new Error(
|
|
400
|
+
"This API key has read-only scope. Write tools are not available."
|
|
401
|
+
);
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
async function recoverSessionState() {
|
|
405
|
+
const s = state();
|
|
406
|
+
if (!s.workspaceId) return;
|
|
407
|
+
try {
|
|
408
|
+
const session = await mcpCall("agent.getActiveSession", { workspaceId: s.workspaceId });
|
|
409
|
+
if (session && session.status === "active") {
|
|
410
|
+
s.agentSessionId = session._id;
|
|
411
|
+
s.sessionOriented = session.oriented;
|
|
412
|
+
s.apiKeyScope = session.toolsScope;
|
|
413
|
+
s.sessionClosed = false;
|
|
414
|
+
}
|
|
415
|
+
} catch {
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
// src/tools/knowledge-helpers.ts
|
|
420
|
+
function extractPreview(data, maxLen) {
|
|
421
|
+
if (!data || typeof data !== "object") return "";
|
|
422
|
+
const d = data;
|
|
423
|
+
const raw = d.description ?? d.canonical ?? d.detail ?? d.rule ?? "";
|
|
424
|
+
if (typeof raw !== "string" || !raw) return "";
|
|
425
|
+
return raw.length > maxLen ? raw.substring(0, maxLen) + "..." : raw;
|
|
426
|
+
}
|
|
427
|
+
var TOOL_NAME_MIGRATIONS = /* @__PURE__ */ new Map([
|
|
428
|
+
["list-entries", 'entries action="list"'],
|
|
429
|
+
["get-entry", 'entries action="get"'],
|
|
430
|
+
["batch-get", 'entries action="batch"'],
|
|
431
|
+
["search", 'entries action="search"'],
|
|
432
|
+
["relate-entries", 'relations action="create"'],
|
|
433
|
+
["batch-relate", 'relations action="batch-create"'],
|
|
434
|
+
["find-related", 'graph action="find"'],
|
|
435
|
+
["suggest-links", 'graph action="suggest"'],
|
|
436
|
+
["gather-context", 'context action="gather"'],
|
|
437
|
+
["get-build-context", 'context action="build"'],
|
|
438
|
+
["list-collections", 'collections action="list"'],
|
|
439
|
+
["create-collection", 'collections action="create"'],
|
|
440
|
+
["update-collection", 'collections action="update"'],
|
|
441
|
+
["agent-start", 'session action="start"'],
|
|
442
|
+
["agent-close", 'session action="close"'],
|
|
443
|
+
["agent-status", 'session action="status"'],
|
|
444
|
+
["workspace-status", 'health action="status"'],
|
|
445
|
+
["mcp-audit", 'health action="audit"'],
|
|
446
|
+
["quality-check", 'quality action="check"'],
|
|
447
|
+
["re-evaluate", 'quality action="re-evaluate"'],
|
|
448
|
+
["list-workflows", 'workflows action="list"'],
|
|
449
|
+
["workflow-checkpoint", 'workflows action="checkpoint"'],
|
|
450
|
+
["wrapup", "session-wrapup"],
|
|
451
|
+
["finish", "session-wrapup"]
|
|
452
|
+
]);
|
|
453
|
+
function translateStaleToolNames(text) {
|
|
454
|
+
const found = [];
|
|
455
|
+
for (const [old, current] of TOOL_NAME_MIGRATIONS) {
|
|
456
|
+
const pattern = new RegExp(`\\b${old.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\b`, "g");
|
|
457
|
+
if (pattern.test(text)) {
|
|
458
|
+
found.push(`\`${old}\` \u2192 \`${current}\``);
|
|
459
|
+
}
|
|
460
|
+
}
|
|
461
|
+
if (found.length === 0) return null;
|
|
462
|
+
return `
|
|
463
|
+
|
|
464
|
+
---
|
|
465
|
+
_Tool name translations (these references use deprecated names):_
|
|
466
|
+
${found.map((f) => `- ${f}`).join("\n")}`;
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
// src/tool-surface.ts
|
|
470
|
+
var _server = null;
|
|
471
|
+
var _writeTools = [];
|
|
472
|
+
function initToolSurface(server) {
|
|
473
|
+
_server = server;
|
|
474
|
+
}
|
|
475
|
+
function trackWriteTool(tool) {
|
|
476
|
+
_writeTools.push(tool);
|
|
477
|
+
}
|
|
478
|
+
function setWriteToolsEnabled(enabled) {
|
|
479
|
+
let changed = false;
|
|
480
|
+
for (const tool of _writeTools) {
|
|
481
|
+
if (tool.enabled !== enabled) {
|
|
482
|
+
tool.enabled = enabled;
|
|
483
|
+
changed = true;
|
|
484
|
+
}
|
|
485
|
+
}
|
|
486
|
+
if (changed && _server) {
|
|
487
|
+
_server.sendToolListChanged();
|
|
488
|
+
}
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
// src/tools/smart-capture.ts
|
|
492
|
+
var AREA_KEYWORDS = {
|
|
493
|
+
"Architecture": ["convex", "schema", "database", "migration", "api", "backend", "infrastructure", "scaling", "performance"],
|
|
494
|
+
"Chain": ["knowledge", "glossary", "entry", "collection", "terminology", "drift", "graph", "chain", "commit"],
|
|
495
|
+
"AI & MCP Integration": ["mcp", "ai", "cursor", "agent", "tool", "llm", "prompt", "context"],
|
|
496
|
+
"Developer Experience": ["dx", "developer", "ide", "workflow", "friction", "ceremony"],
|
|
497
|
+
"Governance & Decision-Making": ["governance", "decision", "rule", "policy", "compliance", "approval"],
|
|
498
|
+
"Analytics & Tracking": ["analytics", "posthog", "tracking", "event", "metric", "funnel"],
|
|
499
|
+
"Security": ["security", "auth", "api key", "permission", "access", "token"]
|
|
500
|
+
};
|
|
501
|
+
function inferArea(text) {
|
|
502
|
+
const lower = text.toLowerCase();
|
|
503
|
+
let bestArea = "";
|
|
504
|
+
let bestScore = 0;
|
|
505
|
+
for (const [area, keywords] of Object.entries(AREA_KEYWORDS)) {
|
|
506
|
+
const score = keywords.filter((kw) => lower.includes(kw)).length;
|
|
507
|
+
if (score > bestScore) {
|
|
508
|
+
bestScore = score;
|
|
509
|
+
bestArea = area;
|
|
510
|
+
}
|
|
511
|
+
}
|
|
512
|
+
return bestArea;
|
|
513
|
+
}
|
|
514
|
+
function inferDomain(text) {
|
|
515
|
+
return inferArea(text) || "";
|
|
516
|
+
}
|
|
517
|
+
var COMMON_CHECKS = {
|
|
518
|
+
clearName: {
|
|
519
|
+
id: "clear-name",
|
|
520
|
+
label: "Clear, specific name (not vague)",
|
|
521
|
+
check: (ctx) => ctx.name.length > 10 && !["new tension", "new entry", "untitled", "test"].includes(ctx.name.toLowerCase()),
|
|
522
|
+
suggestion: () => "Rename to something specific \u2014 describe the actual problem or concept."
|
|
523
|
+
},
|
|
524
|
+
hasDescription: {
|
|
525
|
+
id: "has-description",
|
|
526
|
+
label: "Description provided (>50 chars)",
|
|
527
|
+
check: (ctx) => ctx.description.length > 50,
|
|
528
|
+
suggestion: () => "Add a fuller description explaining context and impact."
|
|
529
|
+
},
|
|
530
|
+
hasRelations: {
|
|
531
|
+
id: "has-relations",
|
|
532
|
+
label: "At least 1 relation created",
|
|
533
|
+
check: (ctx) => ctx.linksCreated.length >= 1,
|
|
534
|
+
suggestion: () => "Use `graph action=suggest` and `relations action=create` to add more connections."
|
|
535
|
+
},
|
|
536
|
+
diverseRelations: {
|
|
537
|
+
id: "diverse-relations",
|
|
538
|
+
label: "Relations span multiple collections",
|
|
539
|
+
check: (ctx) => {
|
|
540
|
+
const colls = new Set(ctx.linksCreated.map((l) => l.targetCollection));
|
|
541
|
+
return colls.size >= 2;
|
|
542
|
+
},
|
|
543
|
+
suggestion: () => "Try linking to entries in different collections (glossary, business-rules, strategy)."
|
|
544
|
+
},
|
|
545
|
+
hasType: {
|
|
546
|
+
id: "has-type",
|
|
547
|
+
label: "Has canonical type",
|
|
548
|
+
check: (ctx) => !!ctx.data?.canonicalKey || !!ctx.canonicalKey,
|
|
549
|
+
suggestion: () => "Classify this entry with a canonical type for better context assembly. Use update-entry to set canonicalKey."
|
|
550
|
+
}
|
|
551
|
+
};
|
|
552
|
+
var PROFILES = /* @__PURE__ */ new Map([
|
|
553
|
+
["tensions", {
|
|
554
|
+
governedDraft: false,
|
|
555
|
+
descriptionField: "description",
|
|
556
|
+
defaults: [
|
|
557
|
+
{ key: "priority", value: "medium" },
|
|
558
|
+
{ key: "date", value: "today" },
|
|
559
|
+
{ key: "raised", value: "infer" },
|
|
560
|
+
{ key: "severity", value: "infer" }
|
|
561
|
+
],
|
|
562
|
+
recommendedRelationTypes: ["surfaces_tension_in", "references", "belongs_to", "related_to"],
|
|
563
|
+
inferField: (ctx) => {
|
|
564
|
+
const fields = {};
|
|
565
|
+
const text = `${ctx.name} ${ctx.description}`;
|
|
566
|
+
const area = inferArea(text);
|
|
567
|
+
if (area) fields.raised = area;
|
|
568
|
+
if (text.toLowerCase().includes("critical") || text.toLowerCase().includes("blocker")) {
|
|
569
|
+
fields.severity = "critical";
|
|
570
|
+
} else if (text.toLowerCase().includes("bottleneck") || text.toLowerCase().includes("scaling") || text.toLowerCase().includes("breaking")) {
|
|
571
|
+
fields.severity = "high";
|
|
572
|
+
} else {
|
|
573
|
+
fields.severity = "medium";
|
|
574
|
+
}
|
|
575
|
+
if (area) fields.affectedArea = area;
|
|
576
|
+
return fields;
|
|
577
|
+
},
|
|
578
|
+
qualityChecks: [
|
|
579
|
+
COMMON_CHECKS.clearName,
|
|
580
|
+
COMMON_CHECKS.hasDescription,
|
|
581
|
+
COMMON_CHECKS.hasRelations,
|
|
582
|
+
COMMON_CHECKS.hasType,
|
|
583
|
+
{
|
|
584
|
+
id: "has-severity",
|
|
585
|
+
label: "Severity specified",
|
|
586
|
+
check: (ctx) => !!ctx.data.severity && ctx.data.severity !== "",
|
|
587
|
+
suggestion: (ctx) => {
|
|
588
|
+
const text = `${ctx.name} ${ctx.description}`.toLowerCase();
|
|
589
|
+
const inferred = text.includes("critical") ? "critical" : text.includes("bottleneck") ? "high" : "medium";
|
|
590
|
+
return `Set severity \u2014 suggest: ${inferred} (based on description keywords).`;
|
|
591
|
+
}
|
|
592
|
+
},
|
|
593
|
+
{
|
|
594
|
+
id: "has-affected-area",
|
|
595
|
+
label: "Affected area identified",
|
|
596
|
+
check: (ctx) => !!ctx.data.affectedArea && ctx.data.affectedArea !== "",
|
|
597
|
+
suggestion: (ctx) => {
|
|
598
|
+
const area = inferArea(`${ctx.name} ${ctx.description}`);
|
|
599
|
+
return area ? `Set affectedArea \u2014 suggest: "${area}" (inferred from content).` : "Specify which product area or domain this tension impacts.";
|
|
600
|
+
}
|
|
601
|
+
}
|
|
602
|
+
]
|
|
603
|
+
}],
|
|
604
|
+
["business-rules", {
|
|
605
|
+
governedDraft: true,
|
|
606
|
+
descriptionField: "description",
|
|
607
|
+
defaults: [
|
|
608
|
+
{ key: "severity", value: "medium" },
|
|
609
|
+
{ key: "domain", value: "infer" }
|
|
610
|
+
],
|
|
611
|
+
recommendedRelationTypes: ["governs", "references", "conflicts_with", "related_to"],
|
|
612
|
+
inferField: (ctx) => {
|
|
613
|
+
const fields = {};
|
|
614
|
+
const domain = inferDomain(`${ctx.name} ${ctx.description}`);
|
|
615
|
+
if (domain) fields.domain = domain;
|
|
616
|
+
return fields;
|
|
617
|
+
},
|
|
618
|
+
qualityChecks: [
|
|
619
|
+
COMMON_CHECKS.clearName,
|
|
620
|
+
COMMON_CHECKS.hasDescription,
|
|
621
|
+
COMMON_CHECKS.hasRelations,
|
|
622
|
+
COMMON_CHECKS.hasType,
|
|
623
|
+
{
|
|
624
|
+
id: "has-rationale",
|
|
625
|
+
label: "Rationale provided",
|
|
626
|
+
check: (ctx) => typeof ctx.data.rationale === "string" && ctx.data.rationale.length > 10,
|
|
627
|
+
suggestion: () => "Add a rationale explaining why this rule exists via `update-entry`."
|
|
628
|
+
},
|
|
629
|
+
{
|
|
630
|
+
id: "has-domain",
|
|
631
|
+
label: "Domain specified",
|
|
632
|
+
check: (ctx) => !!ctx.data.domain && ctx.data.domain !== "",
|
|
633
|
+
suggestion: (ctx) => {
|
|
634
|
+
const domain = inferDomain(`${ctx.name} ${ctx.description}`);
|
|
635
|
+
return domain ? `Set domain \u2014 suggest: "${domain}" (inferred from content).` : "Specify the business domain this rule belongs to.";
|
|
636
|
+
}
|
|
637
|
+
}
|
|
638
|
+
]
|
|
639
|
+
}],
|
|
640
|
+
["glossary", {
|
|
641
|
+
governedDraft: true,
|
|
642
|
+
descriptionField: "canonical",
|
|
643
|
+
defaults: [
|
|
644
|
+
{ key: "category", value: "infer" }
|
|
645
|
+
],
|
|
646
|
+
recommendedRelationTypes: ["defines_term_for", "confused_with", "related_to", "references"],
|
|
647
|
+
inferField: (ctx) => {
|
|
648
|
+
const fields = {};
|
|
649
|
+
const area = inferArea(`${ctx.name} ${ctx.description}`);
|
|
650
|
+
if (area) {
|
|
651
|
+
const categoryMap = {
|
|
652
|
+
"Architecture": "Platform & Architecture",
|
|
653
|
+
"Chain": "Knowledge Management",
|
|
654
|
+
"AI & MCP Integration": "AI & Developer Tools",
|
|
655
|
+
"Developer Experience": "AI & Developer Tools",
|
|
656
|
+
"Governance & Decision-Making": "Governance & Process",
|
|
657
|
+
"Analytics & Tracking": "Platform & Architecture",
|
|
658
|
+
"Security": "Platform & Architecture"
|
|
659
|
+
};
|
|
660
|
+
fields.category = categoryMap[area] ?? "";
|
|
661
|
+
}
|
|
662
|
+
return fields;
|
|
663
|
+
},
|
|
664
|
+
qualityChecks: [
|
|
665
|
+
COMMON_CHECKS.clearName,
|
|
666
|
+
COMMON_CHECKS.hasType,
|
|
667
|
+
{
|
|
668
|
+
id: "has-canonical",
|
|
669
|
+
label: "Canonical definition provided (>20 chars)",
|
|
670
|
+
check: (ctx) => {
|
|
671
|
+
const canonical = ctx.data.canonical;
|
|
672
|
+
return typeof canonical === "string" && canonical.length > 20;
|
|
673
|
+
},
|
|
674
|
+
suggestion: () => "Add a clear canonical definition \u2014 this is the single source of truth for this term."
|
|
675
|
+
},
|
|
676
|
+
COMMON_CHECKS.hasRelations,
|
|
677
|
+
{
|
|
678
|
+
id: "has-category",
|
|
679
|
+
label: "Category assigned",
|
|
680
|
+
check: (ctx) => !!ctx.data.category && ctx.data.category !== "",
|
|
681
|
+
suggestion: () => "Assign a category (e.g., 'Platform & Architecture', 'Governance & Process')."
|
|
682
|
+
}
|
|
683
|
+
]
|
|
684
|
+
}],
|
|
685
|
+
["decisions", {
|
|
686
|
+
governedDraft: false,
|
|
687
|
+
descriptionField: "rationale",
|
|
688
|
+
defaults: [
|
|
689
|
+
{ key: "date", value: "today" },
|
|
690
|
+
{ key: "decidedBy", value: "infer" }
|
|
691
|
+
],
|
|
692
|
+
recommendedRelationTypes: ["informs", "references", "replaces", "related_to"],
|
|
693
|
+
inferField: (ctx) => {
|
|
694
|
+
const fields = {};
|
|
695
|
+
const area = inferArea(`${ctx.name} ${ctx.description}`);
|
|
696
|
+
if (area) fields.decidedBy = area;
|
|
697
|
+
return fields;
|
|
698
|
+
},
|
|
699
|
+
qualityChecks: [
|
|
700
|
+
COMMON_CHECKS.clearName,
|
|
701
|
+
COMMON_CHECKS.hasType,
|
|
702
|
+
{
|
|
703
|
+
id: "has-rationale",
|
|
704
|
+
label: "Rationale provided (>30 chars)",
|
|
705
|
+
check: (ctx) => {
|
|
706
|
+
const rationale = ctx.data.rationale;
|
|
707
|
+
return typeof rationale === "string" && rationale.length > 30;
|
|
708
|
+
},
|
|
709
|
+
suggestion: () => "Explain why this decision was made \u2014 what was considered and rejected?"
|
|
710
|
+
},
|
|
711
|
+
COMMON_CHECKS.hasRelations,
|
|
712
|
+
{
|
|
713
|
+
id: "has-date",
|
|
714
|
+
label: "Decision date recorded",
|
|
715
|
+
check: (ctx) => !!ctx.data.date && ctx.data.date !== "",
|
|
716
|
+
suggestion: () => "Record when this decision was made."
|
|
717
|
+
}
|
|
718
|
+
]
|
|
719
|
+
}],
|
|
720
|
+
["features", {
|
|
721
|
+
governedDraft: false,
|
|
722
|
+
descriptionField: "description",
|
|
723
|
+
defaults: [],
|
|
724
|
+
recommendedRelationTypes: ["belongs_to", "depends_on", "surfaces_tension_in", "related_to"],
|
|
725
|
+
qualityChecks: [
|
|
726
|
+
COMMON_CHECKS.clearName,
|
|
727
|
+
COMMON_CHECKS.hasDescription,
|
|
728
|
+
COMMON_CHECKS.hasRelations,
|
|
729
|
+
COMMON_CHECKS.hasType,
|
|
730
|
+
{
|
|
731
|
+
id: "has-owner",
|
|
732
|
+
label: "Owner assigned",
|
|
733
|
+
check: (ctx) => !!ctx.data.owner && ctx.data.owner !== "",
|
|
734
|
+
suggestion: () => "Assign an owner team or product area."
|
|
735
|
+
},
|
|
736
|
+
{
|
|
737
|
+
id: "has-rationale",
|
|
738
|
+
label: "Rationale documented",
|
|
739
|
+
check: (ctx) => !!ctx.data.rationale && String(ctx.data.rationale).length > 20,
|
|
740
|
+
suggestion: () => "Explain why this feature matters \u2014 what problem does it solve?"
|
|
741
|
+
}
|
|
742
|
+
]
|
|
743
|
+
}],
|
|
744
|
+
["audiences", {
|
|
745
|
+
governedDraft: false,
|
|
746
|
+
descriptionField: "description",
|
|
747
|
+
defaults: [],
|
|
748
|
+
recommendedRelationTypes: ["fills_slot", "informs", "related_to", "references"],
|
|
749
|
+
qualityChecks: [
|
|
750
|
+
COMMON_CHECKS.clearName,
|
|
751
|
+
COMMON_CHECKS.hasDescription,
|
|
752
|
+
COMMON_CHECKS.hasRelations,
|
|
753
|
+
COMMON_CHECKS.hasType,
|
|
754
|
+
{
|
|
755
|
+
id: "has-behaviors",
|
|
756
|
+
label: "Behaviors described",
|
|
757
|
+
check: (ctx) => typeof ctx.data.behaviors === "string" && ctx.data.behaviors.length > 20,
|
|
758
|
+
suggestion: () => "Describe how this audience segment behaves \u2014 what do they do, what tools do they use?"
|
|
759
|
+
}
|
|
760
|
+
]
|
|
761
|
+
}],
|
|
762
|
+
["strategy", {
|
|
763
|
+
governedDraft: true,
|
|
764
|
+
descriptionField: "description",
|
|
765
|
+
defaults: [],
|
|
766
|
+
recommendedRelationTypes: ["informs", "governs", "belongs_to", "related_to"],
|
|
767
|
+
qualityChecks: [
|
|
768
|
+
COMMON_CHECKS.clearName,
|
|
769
|
+
COMMON_CHECKS.hasDescription,
|
|
770
|
+
COMMON_CHECKS.hasRelations,
|
|
771
|
+
COMMON_CHECKS.hasType,
|
|
772
|
+
COMMON_CHECKS.diverseRelations
|
|
773
|
+
]
|
|
774
|
+
}],
|
|
775
|
+
["maps", {
|
|
776
|
+
governedDraft: false,
|
|
777
|
+
descriptionField: "description",
|
|
778
|
+
defaults: [],
|
|
779
|
+
recommendedRelationTypes: ["fills_slot", "references", "related_to"],
|
|
780
|
+
qualityChecks: [
|
|
781
|
+
COMMON_CHECKS.clearName,
|
|
782
|
+
COMMON_CHECKS.hasDescription
|
|
783
|
+
]
|
|
784
|
+
}],
|
|
785
|
+
["chains", {
|
|
786
|
+
governedDraft: false,
|
|
787
|
+
descriptionField: "description",
|
|
788
|
+
defaults: [],
|
|
789
|
+
recommendedRelationTypes: ["informs", "references", "related_to"],
|
|
790
|
+
qualityChecks: [
|
|
791
|
+
COMMON_CHECKS.clearName,
|
|
792
|
+
COMMON_CHECKS.hasDescription
|
|
793
|
+
]
|
|
794
|
+
}],
|
|
795
|
+
["principles", {
|
|
796
|
+
governedDraft: true,
|
|
797
|
+
descriptionField: "description",
|
|
798
|
+
defaults: [
|
|
799
|
+
{ key: "severity", value: "high" },
|
|
800
|
+
{ key: "category", value: "infer" }
|
|
801
|
+
],
|
|
802
|
+
recommendedRelationTypes: ["governs", "informs", "references", "related_to"],
|
|
803
|
+
inferField: (ctx) => {
|
|
804
|
+
const fields = {};
|
|
805
|
+
const area = inferArea(`${ctx.name} ${ctx.description}`);
|
|
806
|
+
if (area) {
|
|
807
|
+
const categoryMap = {
|
|
808
|
+
"Architecture": "Engineering",
|
|
809
|
+
"Chain": "Product",
|
|
810
|
+
"AI & MCP Integration": "Engineering",
|
|
811
|
+
"Developer Experience": "Engineering",
|
|
812
|
+
"Governance & Decision-Making": "Business",
|
|
813
|
+
"Analytics & Tracking": "Product",
|
|
814
|
+
"Security": "Engineering"
|
|
815
|
+
};
|
|
816
|
+
fields.category = categoryMap[area] ?? "Product";
|
|
817
|
+
}
|
|
818
|
+
return fields;
|
|
819
|
+
},
|
|
820
|
+
qualityChecks: [
|
|
821
|
+
COMMON_CHECKS.clearName,
|
|
822
|
+
COMMON_CHECKS.hasDescription,
|
|
823
|
+
COMMON_CHECKS.hasRelations,
|
|
824
|
+
COMMON_CHECKS.hasType,
|
|
825
|
+
{
|
|
826
|
+
id: "has-rationale",
|
|
827
|
+
label: "Rationale provided \u2014 why this principle matters",
|
|
828
|
+
check: (ctx) => typeof ctx.data.rationale === "string" && ctx.data.rationale.length > 20,
|
|
829
|
+
suggestion: () => "Explain why this principle exists and what goes wrong without it."
|
|
830
|
+
}
|
|
831
|
+
]
|
|
832
|
+
}],
|
|
833
|
+
["standards", {
|
|
834
|
+
governedDraft: true,
|
|
835
|
+
descriptionField: "description",
|
|
836
|
+
defaults: [],
|
|
837
|
+
recommendedRelationTypes: ["governs", "defines_term_for", "references", "related_to"],
|
|
838
|
+
qualityChecks: [
|
|
839
|
+
COMMON_CHECKS.clearName,
|
|
840
|
+
COMMON_CHECKS.hasDescription,
|
|
841
|
+
COMMON_CHECKS.hasRelations,
|
|
842
|
+
COMMON_CHECKS.hasType
|
|
843
|
+
]
|
|
844
|
+
}],
|
|
845
|
+
["tracking-events", {
|
|
846
|
+
governedDraft: false,
|
|
847
|
+
descriptionField: "description",
|
|
848
|
+
defaults: [],
|
|
849
|
+
recommendedRelationTypes: ["references", "belongs_to", "related_to"],
|
|
850
|
+
qualityChecks: [
|
|
851
|
+
COMMON_CHECKS.clearName,
|
|
852
|
+
COMMON_CHECKS.hasDescription
|
|
853
|
+
]
|
|
854
|
+
}]
|
|
855
|
+
]);
|
|
856
|
+
var FALLBACK_PROFILE = {
|
|
857
|
+
governedDraft: false,
|
|
858
|
+
descriptionField: "description",
|
|
859
|
+
defaults: [],
|
|
860
|
+
recommendedRelationTypes: ["related_to", "references"],
|
|
861
|
+
qualityChecks: [
|
|
862
|
+
COMMON_CHECKS.clearName,
|
|
863
|
+
COMMON_CHECKS.hasDescription,
|
|
864
|
+
COMMON_CHECKS.hasRelations,
|
|
865
|
+
COMMON_CHECKS.hasType
|
|
866
|
+
]
|
|
867
|
+
};
|
|
868
|
+
function extractSearchTerms(name, description) {
|
|
869
|
+
const text = `${name} ${description}`;
|
|
870
|
+
return text.replace(/[^\w\s]/g, " ").split(/\s+/).filter((w) => w.length > 3).slice(0, 8).join(" ");
|
|
871
|
+
}
|
|
872
|
+
function computeLinkConfidence(candidate, sourceName, sourceDescription, sourceCollection, candidateCollection) {
|
|
873
|
+
const text = `${sourceName} ${sourceDescription}`.toLowerCase();
|
|
874
|
+
const candidateName = candidate.name.toLowerCase();
|
|
875
|
+
let score = 0;
|
|
876
|
+
const reasons = [];
|
|
877
|
+
if (text.includes(candidateName) && candidateName.length > 3) {
|
|
878
|
+
score += 40;
|
|
879
|
+
reasons.push("name match");
|
|
880
|
+
}
|
|
881
|
+
const candidateWords = candidateName.split(/\s+/).filter((w) => w.length > 3);
|
|
882
|
+
const matchingWords = candidateWords.filter((w) => text.includes(w));
|
|
883
|
+
const wordScore = matchingWords.length / Math.max(candidateWords.length, 1) * 30;
|
|
884
|
+
score += wordScore;
|
|
885
|
+
if (matchingWords.length > 0) {
|
|
886
|
+
reasons.push(`word overlap (${matchingWords.slice(0, 3).join(", ")})`);
|
|
887
|
+
}
|
|
888
|
+
const HUB_COLLECTIONS = /* @__PURE__ */ new Set(["strategy", "features"]);
|
|
889
|
+
if (HUB_COLLECTIONS.has(candidateCollection)) {
|
|
890
|
+
score += 15;
|
|
891
|
+
reasons.push("hub collection");
|
|
892
|
+
}
|
|
893
|
+
if (candidateCollection !== sourceCollection) {
|
|
894
|
+
score += 10;
|
|
895
|
+
reasons.push("cross-collection");
|
|
896
|
+
}
|
|
897
|
+
const finalScore = Math.min(score, 100);
|
|
898
|
+
const reason = reasons.length > 0 ? reasons.join(" + ") : "low relevance";
|
|
899
|
+
return { score: finalScore, reason };
|
|
900
|
+
}
|
|
901
|
+
function inferRelationType(sourceCollection, targetCollection, profile) {
|
|
902
|
+
const typeMap = {
|
|
903
|
+
tensions: {
|
|
904
|
+
glossary: "surfaces_tension_in",
|
|
905
|
+
"business-rules": "references",
|
|
906
|
+
strategy: "belongs_to",
|
|
907
|
+
features: "surfaces_tension_in",
|
|
908
|
+
decisions: "references"
|
|
909
|
+
},
|
|
910
|
+
"business-rules": {
|
|
911
|
+
glossary: "references",
|
|
912
|
+
features: "governs",
|
|
913
|
+
strategy: "belongs_to",
|
|
914
|
+
tensions: "references"
|
|
915
|
+
},
|
|
916
|
+
glossary: {
|
|
917
|
+
features: "defines_term_for",
|
|
918
|
+
"business-rules": "references",
|
|
919
|
+
strategy: "references"
|
|
920
|
+
},
|
|
921
|
+
decisions: {
|
|
922
|
+
features: "informs",
|
|
923
|
+
"business-rules": "references",
|
|
924
|
+
strategy: "references",
|
|
925
|
+
tensions: "references"
|
|
926
|
+
}
|
|
927
|
+
};
|
|
928
|
+
const mapped = typeMap[sourceCollection]?.[targetCollection];
|
|
929
|
+
const type = mapped ?? profile.recommendedRelationTypes[0] ?? "related_to";
|
|
930
|
+
const reason = mapped ? `collection pair (${sourceCollection} \u2192 ${targetCollection})` : `profile default (${profile.recommendedRelationTypes[0] ?? "related_to"})`;
|
|
931
|
+
return { type, reason };
|
|
932
|
+
}
|
|
933
|
+
function scoreQuality(ctx, profile) {
|
|
934
|
+
const checks = profile.qualityChecks.map((qc) => {
|
|
935
|
+
const passed2 = qc.check(ctx);
|
|
936
|
+
return {
|
|
937
|
+
id: qc.id,
|
|
938
|
+
label: qc.label,
|
|
939
|
+
passed: passed2,
|
|
940
|
+
suggestion: passed2 ? void 0 : qc.suggestion?.(ctx)
|
|
941
|
+
};
|
|
942
|
+
});
|
|
943
|
+
const passed = checks.filter((c) => c.passed).length;
|
|
944
|
+
const total = checks.length;
|
|
945
|
+
const score = total > 0 ? Math.round(passed / total * 10) : 10;
|
|
946
|
+
return { score, maxScore: 10, checks };
|
|
947
|
+
}
|
|
948
|
+
function formatQualityReport(result) {
|
|
949
|
+
const failed = result.checks.filter((c) => !c.passed);
|
|
950
|
+
const reason = failed.length > 0 ? ` because ${failed.map((c) => c.suggestion ?? c.label.toLowerCase()).join("; ")}` : "";
|
|
951
|
+
const lines = [`## Quality: ${result.score}/${result.maxScore}${reason}`];
|
|
952
|
+
for (const check of result.checks) {
|
|
953
|
+
const icon = check.passed ? "[x]" : "[ ]";
|
|
954
|
+
const suggestion = check.passed ? "" : ` \u2014 ${check.suggestion ?? check.label}`;
|
|
955
|
+
lines.push(`${icon} ${check.label}${suggestion}`);
|
|
956
|
+
}
|
|
957
|
+
return lines.join("\n");
|
|
958
|
+
}
|
|
959
|
+
async function checkEntryQuality(entryId) {
|
|
960
|
+
const entry = await mcpQuery("chain.getEntry", { entryId });
|
|
961
|
+
if (!entry) {
|
|
962
|
+
return {
|
|
963
|
+
text: `Entry \`${entryId}\` not found. Try search to find the right ID.`,
|
|
964
|
+
quality: { score: 0, maxScore: 10, checks: [] }
|
|
965
|
+
};
|
|
966
|
+
}
|
|
967
|
+
const collections = await mcpQuery("chain.listCollections");
|
|
968
|
+
const collMap = /* @__PURE__ */ new Map();
|
|
969
|
+
for (const c of collections) collMap.set(c._id, c.slug);
|
|
970
|
+
const collectionSlug = collMap.get(entry.collectionId) ?? "unknown";
|
|
971
|
+
const profile = PROFILES.get(collectionSlug) ?? FALLBACK_PROFILE;
|
|
972
|
+
const relations = await mcpQuery("chain.listEntryRelations", { entryId });
|
|
973
|
+
const linksCreated = [];
|
|
974
|
+
for (const r of relations) {
|
|
975
|
+
const otherId = r.fromId === entry._id ? r.toId : r.fromId;
|
|
976
|
+
linksCreated.push({
|
|
977
|
+
targetEntryId: otherId,
|
|
978
|
+
targetName: "",
|
|
979
|
+
targetCollection: "",
|
|
980
|
+
relationType: r.type
|
|
981
|
+
});
|
|
982
|
+
}
|
|
983
|
+
const descField = profile.descriptionField;
|
|
984
|
+
const description = typeof entry.data?.[descField] === "string" ? entry.data[descField] : "";
|
|
985
|
+
const ctx = {
|
|
986
|
+
collection: collectionSlug,
|
|
987
|
+
name: entry.name,
|
|
988
|
+
description,
|
|
989
|
+
data: entry.data ?? {},
|
|
990
|
+
entryId: entry.entryId ?? "",
|
|
991
|
+
canonicalKey: entry.canonicalKey,
|
|
992
|
+
linksCreated,
|
|
993
|
+
linksSuggested: [],
|
|
994
|
+
collectionFields: []
|
|
995
|
+
};
|
|
996
|
+
const quality = scoreQuality(ctx, profile);
|
|
997
|
+
const lines = [
|
|
998
|
+
`# Quality Check: ${entry.entryId ?? entry.name}`,
|
|
999
|
+
`**${entry.name}** in \`${collectionSlug}\` [${entry.status}]`,
|
|
1000
|
+
"",
|
|
1001
|
+
formatQualityReport(quality)
|
|
1002
|
+
];
|
|
1003
|
+
if (quality.score < 10) {
|
|
1004
|
+
const failedChecks = quality.checks.filter((c) => !c.passed && c.suggestion);
|
|
1005
|
+
if (failedChecks.length > 0) {
|
|
1006
|
+
lines.push("");
|
|
1007
|
+
lines.push(`_To improve: use \`update-entry\` to fill missing fields, or \`relations action=create\` to add connections._`);
|
|
1008
|
+
}
|
|
1009
|
+
}
|
|
1010
|
+
return { text: lines.join("\n"), quality };
|
|
1011
|
+
}
|
|
1012
|
+
var GOVERNED_COLLECTIONS = /* @__PURE__ */ new Set([
|
|
1013
|
+
"glossary",
|
|
1014
|
+
"business-rules",
|
|
1015
|
+
"principles",
|
|
1016
|
+
"standards",
|
|
1017
|
+
"strategy",
|
|
1018
|
+
"features"
|
|
1019
|
+
]);
|
|
1020
|
+
var AUTO_LINK_CONFIDENCE_THRESHOLD = 35;
|
|
1021
|
+
var MAX_AUTO_LINKS = 5;
|
|
1022
|
+
var MAX_SUGGESTIONS = 5;
|
|
1023
|
+
var captureSchema = z.object({
|
|
1024
|
+
collection: z.string().describe("Collection slug, e.g. 'tensions', 'business-rules', 'glossary', 'decisions'"),
|
|
1025
|
+
name: z.string().describe("Display name \u2014 be specific (e.g. 'Convex adjacency list won't scale for graph traversal')"),
|
|
1026
|
+
description: z.string().describe("Full context \u2014 what's happening, why it matters, what you observed"),
|
|
1027
|
+
context: z.string().optional().describe("Optional additional context (e.g. 'Observed during context gather calls taking 700ms+')"),
|
|
1028
|
+
entryId: z.string().optional().describe("Optional custom entry ID (e.g. 'TEN-my-id'). Auto-generated if omitted."),
|
|
1029
|
+
canonicalKey: z.string().optional().describe("Semantic type (e.g. 'decision', 'tension', 'vision'). Auto-assigned from collection if omitted."),
|
|
1030
|
+
data: z.record(z.unknown()).optional().describe("Explicit field values when you know the schema (e.g. canonical_key, cardinality_rule, required_fields). Merged with inferred values; user-provided wins.")
|
|
1031
|
+
});
|
|
1032
|
+
var batchCaptureSchema = z.object({
|
|
1033
|
+
entries: z.array(z.object({
|
|
1034
|
+
collection: z.string().describe("Collection slug"),
|
|
1035
|
+
name: z.string().describe("Display name"),
|
|
1036
|
+
description: z.string().describe("Full context / definition"),
|
|
1037
|
+
entryId: z.string().optional().describe("Optional custom entry ID")
|
|
1038
|
+
})).min(1).max(50).describe("Array of entries to capture")
|
|
1039
|
+
});
|
|
1040
|
+
var captureOutputSchema = z.object({
|
|
1041
|
+
entryId: z.string(),
|
|
1042
|
+
collection: z.string(),
|
|
1043
|
+
name: z.string(),
|
|
1044
|
+
status: z.literal("draft"),
|
|
1045
|
+
qualityScore: z.number().optional(),
|
|
1046
|
+
qualityVerdict: z.record(z.unknown()).optional()
|
|
1047
|
+
});
|
|
1048
|
+
var batchCaptureOutputSchema = z.object({
|
|
1049
|
+
captured: z.array(z.object({
|
|
1050
|
+
entryId: z.string(),
|
|
1051
|
+
collection: z.string(),
|
|
1052
|
+
name: z.string()
|
|
1053
|
+
})),
|
|
1054
|
+
total: z.number(),
|
|
1055
|
+
failed: z.number()
|
|
1056
|
+
});
|
|
1057
|
+
function registerSmartCaptureTools(server) {
|
|
1058
|
+
const captureTool = server.registerTool(
|
|
1059
|
+
"capture",
|
|
1060
|
+
{
|
|
1061
|
+
title: "Capture",
|
|
1062
|
+
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\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\nAlways creates as 'draft' for governed collections. Use `update-entry` for post-creation adjustments.",
|
|
1063
|
+
inputSchema: captureSchema.shape,
|
|
1064
|
+
annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: false }
|
|
1065
|
+
},
|
|
1066
|
+
async ({ collection, name, description, context, entryId, canonicalKey, data: userData }) => {
|
|
1067
|
+
requireWriteAccess();
|
|
1068
|
+
const profile = PROFILES.get(collection) ?? FALLBACK_PROFILE;
|
|
1069
|
+
const col = await mcpQuery("chain.getCollection", { slug: collection });
|
|
1070
|
+
if (!col) {
|
|
1071
|
+
const displayName = collection.split("-").map((w) => w.charAt(0).toUpperCase() + w.slice(1)).join(" ");
|
|
1072
|
+
return {
|
|
1073
|
+
content: [{
|
|
1074
|
+
type: "text",
|
|
1075
|
+
text: `Collection \`${collection}\` not found.
|
|
1076
|
+
|
|
1077
|
+
**To create it**, run:
|
|
1078
|
+
\`\`\`
|
|
1079
|
+
collections action=create slug="${collection}" name="${displayName}" description="..."
|
|
1080
|
+
\`\`\`
|
|
1081
|
+
|
|
1082
|
+
Or use \`collections action=list\` to see available collections.`
|
|
1083
|
+
}]
|
|
1084
|
+
};
|
|
1085
|
+
}
|
|
1086
|
+
const data = {};
|
|
1087
|
+
const today = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
|
|
1088
|
+
for (const field of col.fields ?? []) {
|
|
1089
|
+
const key = field.key;
|
|
1090
|
+
if (key === profile.descriptionField) {
|
|
1091
|
+
data[key] = description;
|
|
1092
|
+
} else if (field.type === "array" || field.type === "multi-select") {
|
|
1093
|
+
data[key] = [];
|
|
1094
|
+
} else if (field.type === "select") {
|
|
1095
|
+
} else {
|
|
1096
|
+
data[key] = "";
|
|
1097
|
+
}
|
|
1098
|
+
}
|
|
1099
|
+
for (const def of profile.defaults) {
|
|
1100
|
+
if (def.value === "today") {
|
|
1101
|
+
data[def.key] = today;
|
|
1102
|
+
} else if (def.value !== "infer") {
|
|
1103
|
+
data[def.key] = def.value;
|
|
1104
|
+
}
|
|
1105
|
+
}
|
|
1106
|
+
if (profile.inferField) {
|
|
1107
|
+
const inferred = profile.inferField({
|
|
1108
|
+
collection,
|
|
1109
|
+
name,
|
|
1110
|
+
description,
|
|
1111
|
+
context,
|
|
1112
|
+
data,
|
|
1113
|
+
entryId: "",
|
|
1114
|
+
linksCreated: [],
|
|
1115
|
+
linksSuggested: [],
|
|
1116
|
+
collectionFields: col.fields ?? []
|
|
1117
|
+
});
|
|
1118
|
+
for (const [key, val] of Object.entries(inferred)) {
|
|
1119
|
+
if (val !== void 0 && val !== "") {
|
|
1120
|
+
data[key] = val;
|
|
1121
|
+
}
|
|
1122
|
+
}
|
|
1123
|
+
}
|
|
1124
|
+
if (userData && typeof userData === "object") {
|
|
1125
|
+
for (const [key, val] of Object.entries(userData)) {
|
|
1126
|
+
if (key !== "name") data[key] = val;
|
|
1127
|
+
}
|
|
1128
|
+
}
|
|
1129
|
+
data[profile.descriptionField || "description"] = description;
|
|
1130
|
+
const status = GOVERNED_COLLECTIONS.has(collection) ? "draft" : "draft";
|
|
1131
|
+
let finalEntryId;
|
|
1132
|
+
let internalId;
|
|
1133
|
+
try {
|
|
1134
|
+
const agentId = getAgentSessionId();
|
|
1135
|
+
const result = await mcpMutation("chain.createEntry", {
|
|
1136
|
+
collectionSlug: collection,
|
|
1137
|
+
entryId: entryId ?? void 0,
|
|
1138
|
+
name,
|
|
1139
|
+
status,
|
|
1140
|
+
data,
|
|
1141
|
+
canonicalKey,
|
|
1142
|
+
createdBy: agentId ? `agent:${agentId}` : "capture",
|
|
1143
|
+
sessionId: agentId ?? void 0
|
|
1144
|
+
});
|
|
1145
|
+
internalId = result.docId;
|
|
1146
|
+
finalEntryId = result.entryId;
|
|
1147
|
+
await recordSessionActivity({ entryCreated: internalId });
|
|
1148
|
+
} catch (error) {
|
|
1149
|
+
const msg = error instanceof Error ? error.message : String(error);
|
|
1150
|
+
if (msg.includes("Duplicate") || msg.includes("already exists")) {
|
|
1151
|
+
return {
|
|
1152
|
+
content: [{
|
|
1153
|
+
type: "text",
|
|
1154
|
+
text: `# Cannot Capture \u2014 Duplicate Detected
|
|
1155
|
+
|
|
1156
|
+
${msg}
|
|
1157
|
+
|
|
1158
|
+
Use \`entries action=get\` to inspect the existing entry, or \`update-entry\` to modify it.`
|
|
1159
|
+
}]
|
|
1160
|
+
};
|
|
1161
|
+
}
|
|
1162
|
+
throw error;
|
|
1163
|
+
}
|
|
1164
|
+
const linksCreated = [];
|
|
1165
|
+
const linksSuggested = [];
|
|
1166
|
+
const searchQuery = extractSearchTerms(name, description);
|
|
1167
|
+
if (searchQuery) {
|
|
1168
|
+
const [searchResults, allCollections] = await Promise.all([
|
|
1169
|
+
mcpQuery("chain.searchEntries", { query: searchQuery }),
|
|
1170
|
+
mcpQuery("chain.listCollections")
|
|
1171
|
+
]);
|
|
1172
|
+
const collMap = /* @__PURE__ */ new Map();
|
|
1173
|
+
for (const c of allCollections) collMap.set(c._id, c.slug);
|
|
1174
|
+
const candidates = (searchResults ?? []).filter((r) => r.entryId !== finalEntryId && r._id !== internalId).map((r) => {
|
|
1175
|
+
const conf = computeLinkConfidence(r, name, description, collection, collMap.get(r.collectionId) ?? "unknown");
|
|
1176
|
+
return {
|
|
1177
|
+
...r,
|
|
1178
|
+
collSlug: collMap.get(r.collectionId) ?? "unknown",
|
|
1179
|
+
confidence: conf.score,
|
|
1180
|
+
confidenceReason: conf.reason
|
|
1181
|
+
};
|
|
1182
|
+
}).sort((a, b) => b.confidence - a.confidence);
|
|
1183
|
+
for (const c of candidates) {
|
|
1184
|
+
if (linksCreated.length >= MAX_AUTO_LINKS) break;
|
|
1185
|
+
if (c.confidence < AUTO_LINK_CONFIDENCE_THRESHOLD) break;
|
|
1186
|
+
if (!c.entryId || !finalEntryId) continue;
|
|
1187
|
+
const { type: relationType, reason: relationReason } = inferRelationType(collection, c.collSlug, profile);
|
|
1188
|
+
try {
|
|
1189
|
+
await mcpMutation("chain.createEntryRelation", {
|
|
1190
|
+
fromEntryId: finalEntryId,
|
|
1191
|
+
toEntryId: c.entryId,
|
|
1192
|
+
type: relationType
|
|
1193
|
+
});
|
|
1194
|
+
linksCreated.push({
|
|
1195
|
+
targetEntryId: c.entryId,
|
|
1196
|
+
targetName: c.name,
|
|
1197
|
+
targetCollection: c.collSlug,
|
|
1198
|
+
relationType,
|
|
1199
|
+
linkReason: `confidence ${c.confidence} (${c.confidenceReason}) + ${relationReason}`
|
|
1200
|
+
});
|
|
1201
|
+
} catch {
|
|
1202
|
+
}
|
|
1203
|
+
}
|
|
1204
|
+
const linkedIds = new Set(linksCreated.map((l) => l.targetEntryId));
|
|
1205
|
+
for (const c of candidates) {
|
|
1206
|
+
if (linksSuggested.length >= MAX_SUGGESTIONS) break;
|
|
1207
|
+
if (linkedIds.has(c.entryId)) continue;
|
|
1208
|
+
if (c.confidence < 10) continue;
|
|
1209
|
+
const preview = extractPreview(c.data, 80);
|
|
1210
|
+
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`;
|
|
1211
|
+
linksSuggested.push({
|
|
1212
|
+
entryId: c.entryId,
|
|
1213
|
+
name: c.name,
|
|
1214
|
+
collection: c.collSlug,
|
|
1215
|
+
reason,
|
|
1216
|
+
preview
|
|
1217
|
+
});
|
|
1218
|
+
}
|
|
1219
|
+
}
|
|
1220
|
+
const captureCtx = {
|
|
1221
|
+
collection,
|
|
1222
|
+
name,
|
|
1223
|
+
description,
|
|
1224
|
+
context,
|
|
1225
|
+
data,
|
|
1226
|
+
entryId: finalEntryId,
|
|
1227
|
+
canonicalKey,
|
|
1228
|
+
linksCreated,
|
|
1229
|
+
linksSuggested,
|
|
1230
|
+
collectionFields: col.fields ?? []
|
|
1231
|
+
};
|
|
1232
|
+
const quality = scoreQuality(captureCtx, profile);
|
|
1233
|
+
let cardinalityWarning = null;
|
|
1234
|
+
const resolvedCK = canonicalKey ?? captureCtx.canonicalKey;
|
|
1235
|
+
if (resolvedCK) {
|
|
1236
|
+
try {
|
|
1237
|
+
const check = await mcpQuery("chain.checkCardinalityWarning", {
|
|
1238
|
+
canonicalKey: resolvedCK
|
|
1239
|
+
});
|
|
1240
|
+
if (check?.warning) {
|
|
1241
|
+
cardinalityWarning = check.warning;
|
|
1242
|
+
}
|
|
1243
|
+
} catch {
|
|
1244
|
+
}
|
|
1245
|
+
}
|
|
1246
|
+
const contradictionWarnings = await runContradictionCheck(name, description);
|
|
1247
|
+
if (contradictionWarnings.length > 0) {
|
|
1248
|
+
await recordSessionActivity({ contradictionWarning: true });
|
|
1249
|
+
}
|
|
1250
|
+
let coachingSection = "";
|
|
1251
|
+
let verdictResult = null;
|
|
1252
|
+
try {
|
|
1253
|
+
verdictResult = await mcpMutation("quality.evaluateHeuristicAndSchedule", {
|
|
1254
|
+
entryId: finalEntryId,
|
|
1255
|
+
context: "capture"
|
|
1256
|
+
});
|
|
1257
|
+
if (verdictResult?.verdict && verdictResult.verdict.tier !== "passive" && verdictResult.verdict.criteria.length > 0) {
|
|
1258
|
+
coachingSection = formatRubricCoaching(verdictResult);
|
|
1259
|
+
}
|
|
1260
|
+
} catch {
|
|
1261
|
+
}
|
|
1262
|
+
if (verdictResult?.verdict) {
|
|
1263
|
+
try {
|
|
1264
|
+
const wsForTracking = await getWorkspaceContext();
|
|
1265
|
+
const v = verdictResult.verdict;
|
|
1266
|
+
const failedCount = (v.criteria ?? []).filter((c) => !c.passed).length;
|
|
1267
|
+
trackQualityVerdict(wsForTracking.workspaceId, {
|
|
1268
|
+
entry_id: finalEntryId,
|
|
1269
|
+
entry_type: v.canonicalKey ?? collection,
|
|
1270
|
+
tier: v.tier,
|
|
1271
|
+
context: "capture",
|
|
1272
|
+
passed: v.passed,
|
|
1273
|
+
source: verdictResult.source ?? "heuristic",
|
|
1274
|
+
criteria_total: v.criteria?.length ?? 0,
|
|
1275
|
+
criteria_failed: failedCount,
|
|
1276
|
+
llm_scheduled: v.tier !== "passive"
|
|
1277
|
+
});
|
|
1278
|
+
} catch {
|
|
1279
|
+
}
|
|
1280
|
+
}
|
|
1281
|
+
const wsCtx = await getWorkspaceContext();
|
|
1282
|
+
const lines = [
|
|
1283
|
+
`# Captured: ${finalEntryId || name}`,
|
|
1284
|
+
`**${name}** added to \`${collection}\` as \`${status}\``,
|
|
1285
|
+
`**Workspace:** ${wsCtx.workspaceSlug} (${wsCtx.workspaceId})`
|
|
1286
|
+
];
|
|
1287
|
+
if (linksCreated.length > 0) {
|
|
1288
|
+
lines.push("");
|
|
1289
|
+
lines.push(`## Auto-linked (${linksCreated.length})`);
|
|
1290
|
+
for (const link of linksCreated) {
|
|
1291
|
+
const reason = link.linkReason ? ` \u2014 because ${link.linkReason}` : "";
|
|
1292
|
+
lines.push(`- -> **${link.relationType}** ${link.targetEntryId}: ${link.targetName} [${link.targetCollection}]${reason}`);
|
|
1293
|
+
}
|
|
1294
|
+
}
|
|
1295
|
+
if (linksSuggested.length > 0) {
|
|
1296
|
+
lines.push("");
|
|
1297
|
+
lines.push("## Suggested links (review and use `relations action=create`)");
|
|
1298
|
+
for (let i = 0; i < linksSuggested.length; i++) {
|
|
1299
|
+
const s = linksSuggested[i];
|
|
1300
|
+
const preview = s.preview ? ` \u2014 ${s.preview}` : "";
|
|
1301
|
+
lines.push(`${i + 1}. **${s.entryId ?? "(no ID)"}**: ${s.name} [${s.collection}]${preview}`);
|
|
1302
|
+
}
|
|
1303
|
+
}
|
|
1304
|
+
lines.push("");
|
|
1305
|
+
lines.push(formatQualityReport(quality));
|
|
1306
|
+
const failedChecks = quality.checks.filter((c) => !c.passed);
|
|
1307
|
+
if (failedChecks.length > 0) {
|
|
1308
|
+
lines.push("");
|
|
1309
|
+
lines.push(`_To improve: \`update-entry entryId="${finalEntryId}"\` to fill missing fields._`);
|
|
1310
|
+
}
|
|
1311
|
+
const isBetOrGoal = collection === "bets" || resolvedCK === "bet" || resolvedCK === "goal";
|
|
1312
|
+
const hasStrategyLink = linksCreated.some((l) => l.targetCollection === "strategy");
|
|
1313
|
+
if (isBetOrGoal && !hasStrategyLink) {
|
|
1314
|
+
lines.push("");
|
|
1315
|
+
lines.push(
|
|
1316
|
+
`**Strategy link:** This ${collection === "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.`
|
|
1317
|
+
);
|
|
1318
|
+
await recordSessionActivity({ strategyLinkWarnedForEntryId: internalId });
|
|
1319
|
+
}
|
|
1320
|
+
if (cardinalityWarning) {
|
|
1321
|
+
lines.push("");
|
|
1322
|
+
lines.push(`**Cardinality warning:** ${cardinalityWarning}`);
|
|
1323
|
+
}
|
|
1324
|
+
if (contradictionWarnings.length > 0) {
|
|
1325
|
+
lines.push("");
|
|
1326
|
+
lines.push("\u26A0 Contradiction check: proposed entry matched existing governance entries:");
|
|
1327
|
+
for (const w of contradictionWarnings) {
|
|
1328
|
+
lines.push(`- ${w.name} (${w.collection}, ${w.entryId}) \u2014 has 'governs' relation to ${w.governsCount} entries`);
|
|
1329
|
+
}
|
|
1330
|
+
lines.push("Run `context action=gather` on these entries before committing.");
|
|
1331
|
+
}
|
|
1332
|
+
if (coachingSection) {
|
|
1333
|
+
lines.push("");
|
|
1334
|
+
lines.push(coachingSection);
|
|
1335
|
+
}
|
|
1336
|
+
lines.push("");
|
|
1337
|
+
lines.push("## Next Steps");
|
|
1338
|
+
const eid = finalEntryId || "(check entry ID)";
|
|
1339
|
+
lines.push(`1. **Connect it:** \`graph action=suggest entryId="${eid}"\` \u2014 discover what this should link to`);
|
|
1340
|
+
lines.push(`2. **Commit it:** \`commit-entry entryId="${eid}"\` \u2014 promote from draft to SSOT on the Chain`);
|
|
1341
|
+
if (failedChecks.length > 0) {
|
|
1342
|
+
lines.push(`3. **Improve quality:** \`update-entry entryId="${eid}"\` \u2014 fill missing fields`);
|
|
1343
|
+
}
|
|
1344
|
+
try {
|
|
1345
|
+
const readiness = await mcpQuery("chain.workspaceReadiness");
|
|
1346
|
+
if (readiness && readiness.gaps && readiness.gaps.length > 0) {
|
|
1347
|
+
const topGaps = readiness.gaps.slice(0, 2);
|
|
1348
|
+
lines.push("");
|
|
1349
|
+
lines.push(`## Workspace Readiness: ${readiness.score}%`);
|
|
1350
|
+
for (const gap of topGaps) {
|
|
1351
|
+
lines.push(`- _${gap.label}:_ ${gap.guidance}`);
|
|
1352
|
+
}
|
|
1353
|
+
}
|
|
1354
|
+
} catch {
|
|
1355
|
+
}
|
|
1356
|
+
const toolResult = {
|
|
1357
|
+
content: [{ type: "text", text: lines.join("\n") }],
|
|
1358
|
+
structuredContent: {
|
|
1359
|
+
entryId: finalEntryId,
|
|
1360
|
+
collection,
|
|
1361
|
+
name,
|
|
1362
|
+
status: "draft",
|
|
1363
|
+
qualityScore: quality.score,
|
|
1364
|
+
qualityVerdict: verdictResult?.verdict ? { ...verdictResult.verdict, source: verdictResult.source ?? "heuristic" } : void 0
|
|
1365
|
+
}
|
|
1366
|
+
};
|
|
1367
|
+
return toolResult;
|
|
1368
|
+
}
|
|
1369
|
+
);
|
|
1370
|
+
trackWriteTool(captureTool);
|
|
1371
|
+
const batchCaptureTool = server.registerTool(
|
|
1372
|
+
"batch-capture",
|
|
1373
|
+
{
|
|
1374
|
+
title: "Batch Capture",
|
|
1375
|
+
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.",
|
|
1376
|
+
inputSchema: batchCaptureSchema.shape,
|
|
1377
|
+
annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: false }
|
|
1378
|
+
},
|
|
1379
|
+
async ({ entries }) => {
|
|
1380
|
+
requireWriteAccess();
|
|
1381
|
+
const agentId = getAgentSessionId();
|
|
1382
|
+
const createdBy = agentId ? `agent:${agentId}` : "capture";
|
|
1383
|
+
const results = [];
|
|
1384
|
+
await server.sendLoggingMessage({
|
|
1385
|
+
level: "info",
|
|
1386
|
+
data: `Batch capturing ${entries.length} entries...`,
|
|
1387
|
+
logger: "product-brain"
|
|
1388
|
+
});
|
|
1389
|
+
const allCollections = await mcpQuery("chain.listCollections");
|
|
1390
|
+
const collCache = /* @__PURE__ */ new Map();
|
|
1391
|
+
for (const c of allCollections) collCache.set(c.slug, c);
|
|
1392
|
+
const collIdToSlug = /* @__PURE__ */ new Map();
|
|
1393
|
+
for (const c of allCollections) collIdToSlug.set(c._id, c.slug);
|
|
1394
|
+
for (let entryIdx = 0; entryIdx < entries.length; entryIdx++) {
|
|
1395
|
+
const entry = entries[entryIdx];
|
|
1396
|
+
if (entryIdx > 0 && entryIdx % 5 === 0) {
|
|
1397
|
+
await server.sendLoggingMessage({
|
|
1398
|
+
level: "info",
|
|
1399
|
+
data: `Captured ${entryIdx}/${entries.length} entries...`,
|
|
1400
|
+
logger: "product-brain"
|
|
1401
|
+
});
|
|
1402
|
+
}
|
|
1403
|
+
const profile = PROFILES.get(entry.collection) ?? FALLBACK_PROFILE;
|
|
1404
|
+
const col = collCache.get(entry.collection);
|
|
1405
|
+
if (!col) {
|
|
1406
|
+
results.push({ name: entry.name, collection: entry.collection, entryId: "", ok: false, autoLinks: 0, error: `Collection "${entry.collection}" not found` });
|
|
1407
|
+
continue;
|
|
1408
|
+
}
|
|
1409
|
+
const data = {};
|
|
1410
|
+
const today = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
|
|
1411
|
+
for (const field of col.fields ?? []) {
|
|
1412
|
+
const key = field.key;
|
|
1413
|
+
if (key === profile.descriptionField) {
|
|
1414
|
+
data[key] = entry.description;
|
|
1415
|
+
} else if (field.type === "array" || field.type === "multi-select") {
|
|
1416
|
+
data[key] = [];
|
|
1417
|
+
} else if (field.type === "select") {
|
|
1418
|
+
} else {
|
|
1419
|
+
data[key] = "";
|
|
1420
|
+
}
|
|
1421
|
+
}
|
|
1422
|
+
for (const def of profile.defaults) {
|
|
1423
|
+
if (def.value === "today") data[def.key] = today;
|
|
1424
|
+
else if (def.value !== "infer") data[def.key] = def.value;
|
|
1425
|
+
}
|
|
1426
|
+
if (profile.inferField) {
|
|
1427
|
+
const inferred = profile.inferField({
|
|
1428
|
+
collection: entry.collection,
|
|
1429
|
+
name: entry.name,
|
|
1430
|
+
description: entry.description,
|
|
1431
|
+
data,
|
|
1432
|
+
entryId: "",
|
|
1433
|
+
linksCreated: [],
|
|
1434
|
+
linksSuggested: [],
|
|
1435
|
+
collectionFields: col.fields ?? []
|
|
1436
|
+
});
|
|
1437
|
+
for (const [key, val] of Object.entries(inferred)) {
|
|
1438
|
+
if (val !== void 0 && val !== "") data[key] = val;
|
|
1439
|
+
}
|
|
1440
|
+
}
|
|
1441
|
+
if (!data[profile.descriptionField] && !data.description && !data.canonical) {
|
|
1442
|
+
data[profile.descriptionField || "description"] = entry.description;
|
|
1443
|
+
}
|
|
1444
|
+
try {
|
|
1445
|
+
const result = await mcpMutation("chain.createEntry", {
|
|
1446
|
+
collectionSlug: entry.collection,
|
|
1447
|
+
entryId: entry.entryId ?? void 0,
|
|
1448
|
+
name: entry.name,
|
|
1449
|
+
status: "draft",
|
|
1450
|
+
data,
|
|
1451
|
+
createdBy,
|
|
1452
|
+
sessionId: agentId ?? void 0
|
|
1453
|
+
});
|
|
1454
|
+
const internalId = result.docId;
|
|
1455
|
+
const finalEntryId = result.entryId;
|
|
1456
|
+
let autoLinkCount = 0;
|
|
1457
|
+
const searchQuery = extractSearchTerms(entry.name, entry.description);
|
|
1458
|
+
if (searchQuery) {
|
|
1459
|
+
try {
|
|
1460
|
+
const searchResults = await mcpQuery("chain.searchEntries", { query: searchQuery });
|
|
1461
|
+
const candidates = (searchResults ?? []).filter((r) => r.entryId !== finalEntryId).map((r) => {
|
|
1462
|
+
const conf = computeLinkConfidence(r, entry.name, entry.description, entry.collection, collIdToSlug.get(r.collectionId) ?? "unknown");
|
|
1463
|
+
return {
|
|
1464
|
+
...r,
|
|
1465
|
+
collSlug: collIdToSlug.get(r.collectionId) ?? "unknown",
|
|
1466
|
+
confidence: conf.score
|
|
1467
|
+
};
|
|
1468
|
+
}).sort((a, b) => b.confidence - a.confidence);
|
|
1469
|
+
for (const c of candidates) {
|
|
1470
|
+
if (autoLinkCount >= MAX_AUTO_LINKS) break;
|
|
1471
|
+
if (c.confidence < AUTO_LINK_CONFIDENCE_THRESHOLD) break;
|
|
1472
|
+
if (!c.entryId) continue;
|
|
1473
|
+
const { type: relationType } = inferRelationType(entry.collection, c.collSlug, profile);
|
|
1474
|
+
try {
|
|
1475
|
+
await mcpMutation("chain.createEntryRelation", {
|
|
1476
|
+
fromEntryId: finalEntryId,
|
|
1477
|
+
toEntryId: c.entryId,
|
|
1478
|
+
type: relationType
|
|
1479
|
+
});
|
|
1480
|
+
autoLinkCount++;
|
|
1481
|
+
} catch {
|
|
1482
|
+
}
|
|
1483
|
+
}
|
|
1484
|
+
} catch {
|
|
1485
|
+
}
|
|
1486
|
+
}
|
|
1487
|
+
results.push({ name: entry.name, collection: entry.collection, entryId: finalEntryId, ok: true, autoLinks: autoLinkCount });
|
|
1488
|
+
await recordSessionActivity({ entryCreated: internalId });
|
|
1489
|
+
} catch (error) {
|
|
1490
|
+
const msg = error instanceof Error ? error.message : String(error);
|
|
1491
|
+
results.push({ name: entry.name, collection: entry.collection, entryId: "", ok: false, autoLinks: 0, error: msg });
|
|
1492
|
+
}
|
|
1493
|
+
}
|
|
1494
|
+
const created = results.filter((r) => r.ok);
|
|
1495
|
+
const failed = results.filter((r) => !r.ok);
|
|
1496
|
+
await server.sendLoggingMessage({
|
|
1497
|
+
level: "info",
|
|
1498
|
+
data: `Batch complete. ${created.length} succeeded, ${failed.length} failed.`,
|
|
1499
|
+
logger: "product-brain"
|
|
1500
|
+
});
|
|
1501
|
+
const totalAutoLinks = created.reduce((sum, r) => sum + r.autoLinks, 0);
|
|
1502
|
+
const byCollection = /* @__PURE__ */ new Map();
|
|
1503
|
+
for (const r of created) {
|
|
1504
|
+
byCollection.set(r.collection, (byCollection.get(r.collection) ?? 0) + 1);
|
|
1505
|
+
}
|
|
1506
|
+
const lines = [
|
|
1507
|
+
`# Batch Capture Complete`,
|
|
1508
|
+
`**${created.length}** created, **${failed.length}** failed out of ${entries.length} total.`,
|
|
1509
|
+
`**Auto-links created:** ${totalAutoLinks}`,
|
|
1510
|
+
""
|
|
1511
|
+
];
|
|
1512
|
+
if (byCollection.size > 0) {
|
|
1513
|
+
lines.push("## By Collection");
|
|
1514
|
+
for (const [col, count] of byCollection) {
|
|
1515
|
+
lines.push(`- \`${col}\`: ${count} entries`);
|
|
1516
|
+
}
|
|
1517
|
+
lines.push("");
|
|
1518
|
+
}
|
|
1519
|
+
if (created.length > 0) {
|
|
1520
|
+
lines.push("## Created");
|
|
1521
|
+
for (const r of created) {
|
|
1522
|
+
const linkNote = r.autoLinks > 0 ? ` (${r.autoLinks} auto-links)` : "";
|
|
1523
|
+
lines.push(`- **${r.entryId}**: ${r.name} [${r.collection}]${linkNote}`);
|
|
1524
|
+
}
|
|
1525
|
+
}
|
|
1526
|
+
if (failed.length > 0) {
|
|
1527
|
+
lines.push("");
|
|
1528
|
+
lines.push("## Failed");
|
|
1529
|
+
for (const r of failed) {
|
|
1530
|
+
lines.push(`- ${r.name} [${r.collection}]: _${r.error}_`);
|
|
1531
|
+
}
|
|
1532
|
+
}
|
|
1533
|
+
const entryIds = created.map((r) => r.entryId);
|
|
1534
|
+
if (entryIds.length > 0) {
|
|
1535
|
+
lines.push("");
|
|
1536
|
+
lines.push("## Next Steps");
|
|
1537
|
+
lines.push(`- **Connect:** Run \`graph action=suggest\` on key entries to build the knowledge graph`);
|
|
1538
|
+
lines.push(`- **Commit:** Use \`commit-entry\` to promote drafts to SSOT`);
|
|
1539
|
+
lines.push(`- **Quality:** Run \`quality action=check\` on individual entries to assess completeness`);
|
|
1540
|
+
}
|
|
1541
|
+
return {
|
|
1542
|
+
content: [{ type: "text", text: lines.join("\n") }],
|
|
1543
|
+
structuredContent: {
|
|
1544
|
+
captured: created.map((r) => ({ entryId: r.entryId, collection: r.collection, name: r.name })),
|
|
1545
|
+
total: created.length,
|
|
1546
|
+
failed: failed.length
|
|
1547
|
+
}
|
|
1548
|
+
};
|
|
1549
|
+
}
|
|
1550
|
+
);
|
|
1551
|
+
trackWriteTool(batchCaptureTool);
|
|
1552
|
+
}
|
|
1553
|
+
var STOP_WORDS = /* @__PURE__ */ new Set([
|
|
1554
|
+
"the",
|
|
1555
|
+
"and",
|
|
1556
|
+
"for",
|
|
1557
|
+
"are",
|
|
1558
|
+
"but",
|
|
1559
|
+
"not",
|
|
1560
|
+
"you",
|
|
1561
|
+
"all",
|
|
1562
|
+
"can",
|
|
1563
|
+
"has",
|
|
1564
|
+
"her",
|
|
1565
|
+
"was",
|
|
1566
|
+
"one",
|
|
1567
|
+
"our",
|
|
1568
|
+
"out",
|
|
1569
|
+
"day",
|
|
1570
|
+
"had",
|
|
1571
|
+
"hot",
|
|
1572
|
+
"how",
|
|
1573
|
+
"its",
|
|
1574
|
+
"may",
|
|
1575
|
+
"new",
|
|
1576
|
+
"now",
|
|
1577
|
+
"old",
|
|
1578
|
+
"see",
|
|
1579
|
+
"way",
|
|
1580
|
+
"who",
|
|
1581
|
+
"did",
|
|
1582
|
+
"get",
|
|
1583
|
+
"let",
|
|
1584
|
+
"say",
|
|
1585
|
+
"she",
|
|
1586
|
+
"too",
|
|
1587
|
+
"use",
|
|
1588
|
+
"from",
|
|
1589
|
+
"have",
|
|
1590
|
+
"been",
|
|
1591
|
+
"each",
|
|
1592
|
+
"that",
|
|
1593
|
+
"this",
|
|
1594
|
+
"with",
|
|
1595
|
+
"will",
|
|
1596
|
+
"they",
|
|
1597
|
+
"what",
|
|
1598
|
+
"when",
|
|
1599
|
+
"make",
|
|
1600
|
+
"like",
|
|
1601
|
+
"long",
|
|
1602
|
+
"look",
|
|
1603
|
+
"many",
|
|
1604
|
+
"some",
|
|
1605
|
+
"them",
|
|
1606
|
+
"than",
|
|
1607
|
+
"most",
|
|
1608
|
+
"only",
|
|
1609
|
+
"over",
|
|
1610
|
+
"such",
|
|
1611
|
+
"into",
|
|
1612
|
+
"also",
|
|
1613
|
+
"back",
|
|
1614
|
+
"just",
|
|
1615
|
+
"much",
|
|
1616
|
+
"must",
|
|
1617
|
+
"name",
|
|
1618
|
+
"very",
|
|
1619
|
+
"your",
|
|
1620
|
+
"after",
|
|
1621
|
+
"which",
|
|
1622
|
+
"their",
|
|
1623
|
+
"about",
|
|
1624
|
+
"would",
|
|
1625
|
+
"there",
|
|
1626
|
+
"should",
|
|
1627
|
+
"could",
|
|
1628
|
+
"other",
|
|
1629
|
+
"these",
|
|
1630
|
+
"first",
|
|
1631
|
+
"being",
|
|
1632
|
+
"those",
|
|
1633
|
+
"still",
|
|
1634
|
+
"where"
|
|
1635
|
+
]);
|
|
1636
|
+
async function runContradictionCheck(name, description) {
|
|
1637
|
+
const warnings = [];
|
|
1638
|
+
try {
|
|
1639
|
+
const text = `${name} ${description}`.toLowerCase();
|
|
1640
|
+
const keyTerms = text.split(/\s+/).filter((w) => w.length >= 4 && !STOP_WORDS.has(w)).slice(0, 8);
|
|
1641
|
+
if (keyTerms.length === 0) return warnings;
|
|
1642
|
+
const searchQuery = keyTerms.slice(0, 5).join(" ");
|
|
1643
|
+
const [govResults, archResults] = await Promise.all([
|
|
1644
|
+
mcpQuery("chain.searchEntries", { query: searchQuery, collectionSlug: "business-rules" }),
|
|
1645
|
+
mcpQuery("chain.searchEntries", { query: searchQuery, collectionSlug: "architecture" })
|
|
1646
|
+
]);
|
|
1647
|
+
const allGov = [...govResults ?? [], ...archResults ?? []].slice(0, 5);
|
|
1648
|
+
for (const entry of allGov) {
|
|
1649
|
+
const entryText = `${entry.name} ${entry.data?.description ?? ""}`.toLowerCase();
|
|
1650
|
+
const matched = keyTerms.filter((t) => entryText.includes(t));
|
|
1651
|
+
if (matched.length < 3) continue;
|
|
1652
|
+
let governsCount = 0;
|
|
1653
|
+
try {
|
|
1654
|
+
const relations = await mcpQuery("chain.listEntryRelations", {
|
|
1655
|
+
entryId: entry.entryId
|
|
1656
|
+
});
|
|
1657
|
+
governsCount = (relations ?? []).filter((r) => r.type === "governs").length;
|
|
1658
|
+
} catch {
|
|
1659
|
+
}
|
|
1660
|
+
warnings.push({
|
|
1661
|
+
entryId: entry.entryId ?? "",
|
|
1662
|
+
name: entry.name,
|
|
1663
|
+
collection: entry.collectionSlug ?? "",
|
|
1664
|
+
governsCount
|
|
1665
|
+
});
|
|
1666
|
+
}
|
|
1667
|
+
} catch {
|
|
1668
|
+
}
|
|
1669
|
+
return warnings;
|
|
1670
|
+
}
|
|
1671
|
+
function formatRubricCoaching(result) {
|
|
1672
|
+
const { verdict, rogerMartin } = result;
|
|
1673
|
+
if (!verdict || verdict.criteria.length === 0) return "";
|
|
1674
|
+
const lines = ["## Semantic Quality"];
|
|
1675
|
+
const failed = (verdict.criteria ?? []).filter((c) => !c.passed);
|
|
1676
|
+
const total = verdict.criteria?.length ?? 0;
|
|
1677
|
+
const passedCount = total - failed.length;
|
|
1678
|
+
if (verdict.passed) {
|
|
1679
|
+
lines.push(`All ${total} rubric criteria pass for \`${verdict.canonicalKey}\` (${verdict.tier} tier).`);
|
|
1680
|
+
} else {
|
|
1681
|
+
lines.push(`${passedCount}/${total} criteria pass for \`${verdict.canonicalKey}\` (${verdict.tier} tier)`);
|
|
1682
|
+
lines.push("");
|
|
1683
|
+
for (const c of verdict.criteria) {
|
|
1684
|
+
const icon = c.passed ? "[x]" : "[ ]";
|
|
1685
|
+
const extra = c.passed ? "" : ` \u2014 ${c.hint}`;
|
|
1686
|
+
lines.push(`${icon} ${c.id}${extra}`);
|
|
1687
|
+
}
|
|
1688
|
+
if (verdict.weakest) {
|
|
1689
|
+
lines.push("");
|
|
1690
|
+
lines.push(`**Coaching hint:** ${verdict.weakest.hint}`);
|
|
1691
|
+
lines.push(`_Question to consider:_ ${verdict.weakest.questionTemplate}`);
|
|
1692
|
+
}
|
|
1693
|
+
}
|
|
1694
|
+
if (rogerMartin) {
|
|
1695
|
+
lines.push("");
|
|
1696
|
+
lines.push("### Roger Martin Test");
|
|
1697
|
+
if (rogerMartin.isStrategicChoice) {
|
|
1698
|
+
lines.push("This principle passes \u2014 the opposite is a reasonable strategic choice.");
|
|
1699
|
+
} else {
|
|
1700
|
+
lines.push(`This principle may not be a strategic choice. ${rogerMartin.reasoning}`);
|
|
1701
|
+
if (rogerMartin.suggestion) {
|
|
1702
|
+
lines.push(`_Suggestion:_ ${rogerMartin.suggestion}`);
|
|
1703
|
+
}
|
|
1704
|
+
}
|
|
1705
|
+
}
|
|
1706
|
+
return lines.join("\n");
|
|
1707
|
+
}
|
|
1708
|
+
function formatRubricVerdictSection(verdict) {
|
|
1709
|
+
if (!verdict || !verdict.criteria || verdict.criteria.length === 0) return "";
|
|
1710
|
+
const lines = ["## Semantic Quality"];
|
|
1711
|
+
const failed = verdict.criteria.filter((c) => !c.passed);
|
|
1712
|
+
const total = verdict.criteria.length;
|
|
1713
|
+
const passedCount = total - failed.length;
|
|
1714
|
+
const durationSuffix = verdict.llmDurationMs ? ` in ${(verdict.llmDurationMs / 1e3).toFixed(1)}s` : "";
|
|
1715
|
+
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}` : "";
|
|
1716
|
+
if (failed.length === 0) {
|
|
1717
|
+
lines.push(`All ${total} rubric criteria pass for \`${verdict.canonicalKey}\` (${verdict.tier} tier, ${verdict.source} evaluation).${statusNote}`);
|
|
1718
|
+
} else {
|
|
1719
|
+
lines.push(`${passedCount}/${total} criteria pass for \`${verdict.canonicalKey}\` (${verdict.tier} tier, ${verdict.source} evaluation)${statusNote}`);
|
|
1720
|
+
lines.push("");
|
|
1721
|
+
for (const c of verdict.criteria) {
|
|
1722
|
+
const icon = c.passed ? "[x]" : "[ ]";
|
|
1723
|
+
const extra = c.passed ? "" : ` \u2014 ${c.hint}`;
|
|
1724
|
+
lines.push(`${icon} ${c.id}${extra}`);
|
|
1725
|
+
}
|
|
1726
|
+
if (verdict.weakest) {
|
|
1727
|
+
lines.push("");
|
|
1728
|
+
lines.push(`**Top improvement:** ${verdict.weakest.hint}`);
|
|
1729
|
+
}
|
|
1730
|
+
}
|
|
1731
|
+
if (verdict.rogerMartin) {
|
|
1732
|
+
const rm = verdict.rogerMartin;
|
|
1733
|
+
lines.push("");
|
|
1734
|
+
lines.push("### Roger Martin Test");
|
|
1735
|
+
if (rm.isStrategicChoice) {
|
|
1736
|
+
lines.push(`This is a real strategic choice \u2014 the opposite is reasonable. ${rm.reasoning}`);
|
|
1737
|
+
} else {
|
|
1738
|
+
lines.push(`This may not be a strategic choice. ${rm.reasoning}`);
|
|
1739
|
+
if (rm.suggestion) {
|
|
1740
|
+
lines.push(`_Suggestion:_ ${rm.suggestion}`);
|
|
1741
|
+
}
|
|
1742
|
+
}
|
|
1743
|
+
}
|
|
1744
|
+
return lines.join("\n");
|
|
1745
|
+
}
|
|
1746
|
+
|
|
1747
|
+
export {
|
|
1748
|
+
runWithAuth,
|
|
1749
|
+
runWithToolContext,
|
|
1750
|
+
getAgentSessionId,
|
|
1751
|
+
isSessionOriented,
|
|
1752
|
+
setSessionOriented,
|
|
1753
|
+
getApiKeyScope,
|
|
1754
|
+
startAgentSession,
|
|
1755
|
+
closeAgentSession,
|
|
1756
|
+
orphanAgentSession,
|
|
1757
|
+
recordSessionActivity,
|
|
1758
|
+
bootstrap,
|
|
1759
|
+
bootstrapHttp,
|
|
1760
|
+
getAuditLog,
|
|
1761
|
+
mcpCall,
|
|
1762
|
+
getWorkspaceId,
|
|
1763
|
+
getWorkspaceContext,
|
|
1764
|
+
mcpQuery,
|
|
1765
|
+
mcpMutation,
|
|
1766
|
+
requireActiveSession,
|
|
1767
|
+
requireWriteAccess,
|
|
1768
|
+
recoverSessionState,
|
|
1769
|
+
extractPreview,
|
|
1770
|
+
translateStaleToolNames,
|
|
1771
|
+
initToolSurface,
|
|
1772
|
+
trackWriteTool,
|
|
1773
|
+
setWriteToolsEnabled,
|
|
1774
|
+
formatQualityReport,
|
|
1775
|
+
checkEntryQuality,
|
|
1776
|
+
captureSchema,
|
|
1777
|
+
batchCaptureSchema,
|
|
1778
|
+
captureOutputSchema,
|
|
1779
|
+
batchCaptureOutputSchema,
|
|
1780
|
+
registerSmartCaptureTools,
|
|
1781
|
+
runContradictionCheck,
|
|
1782
|
+
formatRubricCoaching,
|
|
1783
|
+
formatRubricVerdictSection
|
|
1784
|
+
};
|
|
1785
|
+
//# sourceMappingURL=chunk-3JSR5JCU.js.map
|