@lucern/mcp 0.2.0-alpha.1 → 0.2.0-alpha.10

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,2915 @@
1
+ import * as fs from 'fs';
2
+ import * as path2 from 'path';
3
+ import { api, components, internal } from '@lucern/reasoning-kernel/_generated/api';
4
+ import 'stream';
5
+ import { AsyncLocalStorage } from 'async_hooks';
6
+ import { ConvexHttpClient } from 'convex/browser';
7
+ import 'crypto';
8
+ import * as os from 'os';
9
+
10
+ // ../../apps/mcp-server/src/handlers/sdk.ts
11
+ var handlerSdkClientCache = /* @__PURE__ */ new WeakMap();
12
+ async function resolveOntologyFromLookup(baseClient, input) {
13
+ const id = readString(input.id ?? input.ontologyId);
14
+ if (id) {
15
+ return baseClient.ontologies.get(id);
16
+ }
17
+ const ontologyKey = readString(input.ontologyKey);
18
+ if (!ontologyKey) {
19
+ return {
20
+ error: "Either id or ontologyKey is required."
21
+ };
22
+ }
23
+ const listResult = await baseClient.ontologies.list({
24
+ tenantId: readString(input.tenantId),
25
+ tier: readString(input.tier),
26
+ status: readString(input.status)
27
+ });
28
+ const payload = asRecord(listResult);
29
+ const rows = Array.isArray(payload.ontologies) ? payload.ontologies : Array.isArray(payload.definitions) ? payload.definitions : [];
30
+ const tenantId = readString(input.tenantId);
31
+ const match = rows.find((row) => {
32
+ const record = asRecord(row);
33
+ if (readString(record.ontologyKey) !== ontologyKey) {
34
+ return false;
35
+ }
36
+ if (!tenantId) {
37
+ return true;
38
+ }
39
+ return readString(record.tenantId) === tenantId;
40
+ });
41
+ return match ? asRecord(match) : {
42
+ error: `Ontology not found: ${ontologyKey}`
43
+ };
44
+ }
45
+ function buildHandlerSdkClient(ctx) {
46
+ const baseClient = ctx.lucernClient;
47
+ return {
48
+ ...baseClient,
49
+ ontologies: {
50
+ ...baseClient.ontologies,
51
+ get(input) {
52
+ return typeof input === "string" ? baseClient.ontologies.get(input) : resolveOntologyFromLookup(baseClient, input ?? {});
53
+ }
54
+ }
55
+ };
56
+ }
57
+ function getSdkClient(ctx) {
58
+ if (!ctx.lucernClient) {
59
+ throw new Error("Lucern SDK client is not available for this MCP runtime.");
60
+ }
61
+ const cached = handlerSdkClientCache.get(ctx);
62
+ if (cached) {
63
+ return cached;
64
+ }
65
+ const wrappedClient = buildHandlerSdkClient(ctx);
66
+ handlerSdkClientCache.set(ctx, wrappedClient);
67
+ return wrappedClient;
68
+ }
69
+ function formatSdkResult(value) {
70
+ if (value && typeof value === "object" && !Array.isArray(value) && "data" in value) {
71
+ const envelope = value;
72
+ if (envelope.data && typeof envelope.data === "object" && !Array.isArray(envelope.data)) {
73
+ return envelope.data;
74
+ }
75
+ }
76
+ if (value && typeof value === "object" && !Array.isArray(value)) {
77
+ return value;
78
+ }
79
+ return { value };
80
+ }
81
+ function asRecord(value) {
82
+ return value && typeof value === "object" && !Array.isArray(value) ? value : {};
83
+ }
84
+ function asJsonObject(value) {
85
+ const record = asRecord(value);
86
+ return Object.keys(record).length > 0 ? record : void 0;
87
+ }
88
+ function readString(value) {
89
+ if (typeof value !== "string") {
90
+ return void 0;
91
+ }
92
+ const normalized = value.trim();
93
+ return normalized.length > 0 ? normalized : void 0;
94
+ }
95
+ function readNumber(value) {
96
+ if (typeof value === "number" && Number.isFinite(value)) {
97
+ return value;
98
+ }
99
+ if (typeof value === "string") {
100
+ const parsed = Number(value.trim());
101
+ return Number.isFinite(parsed) ? parsed : void 0;
102
+ }
103
+ return void 0;
104
+ }
105
+ function readBoolean(value) {
106
+ if (typeof value === "boolean") {
107
+ return value;
108
+ }
109
+ if (typeof value === "string") {
110
+ const normalized = value.trim().toLowerCase();
111
+ if (normalized === "true") {
112
+ return true;
113
+ }
114
+ if (normalized === "false") {
115
+ return false;
116
+ }
117
+ }
118
+ return void 0;
119
+ }
120
+ function readStringArray(value) {
121
+ if (Array.isArray(value)) {
122
+ const items = value.map((entry) => readString(entry)).filter((entry) => Boolean(entry));
123
+ return items.length > 0 ? items : void 0;
124
+ }
125
+ if (typeof value === "string") {
126
+ const normalized = value.trim();
127
+ if (normalized.startsWith("[")) {
128
+ try {
129
+ const parsed = JSON.parse(normalized);
130
+ if (Array.isArray(parsed)) {
131
+ return readStringArray(parsed);
132
+ }
133
+ } catch {
134
+ }
135
+ }
136
+ }
137
+ return void 0;
138
+ }
139
+ function readTimeRange(value) {
140
+ const record = asRecord(value);
141
+ const start = readNumber(record.start);
142
+ const end = readNumber(record.end);
143
+ if (start === void 0 && end === void 0) {
144
+ return void 0;
145
+ }
146
+ return {
147
+ start: start ?? Number.NaN,
148
+ end: end ?? Number.NaN
149
+ };
150
+ }
151
+
152
+ // ../../apps/mcp-server/src/handlers/answers.ts
153
+ var answerHandlers = {
154
+ async create_answer(args, ctx) {
155
+ return formatSdkResult(
156
+ await getSdkClient(ctx).answers.create({
157
+ questionNodeId: args.questionNodeId,
158
+ answerText: args.answerText,
159
+ confidence: args.confidence || "moderate",
160
+ evidenceNodeIds: args.evidenceNodeIds || [],
161
+ answerSource: args.answerSource || "ai_generated"
162
+ })
163
+ );
164
+ },
165
+ async get_answer(args, ctx) {
166
+ return formatSdkResult(
167
+ await getSdkClient(ctx).answers.get({
168
+ questionNodeId: args.questionNodeId
169
+ })
170
+ );
171
+ }
172
+ };
173
+
174
+ // ../../apps/mcp-server/src/handlers/auto-branching.ts
175
+ var autoBranchingHandlers = {
176
+ async analyze_topic_density(args, ctx) {
177
+ return formatSdkResult(
178
+ await getSdkClient(ctx).context.analyzeTopicDensity(args)
179
+ );
180
+ },
181
+ async apply_auto_branching(args, ctx) {
182
+ return formatSdkResult(
183
+ await getSdkClient(ctx).context.applyAutoBranching(args)
184
+ );
185
+ }
186
+ };
187
+
188
+ // ../contracts/src/ids.contract.ts
189
+ var PREFIXED_ID_PATTERN = /^([a-z][a-z0-9]*)_(.+)$/;
190
+ function encodePrefixedId(prefix, value) {
191
+ const normalizedPrefix = prefix.trim();
192
+ const normalizedValue = value.trim();
193
+ if (!normalizedPrefix || !normalizedValue) {
194
+ throw new Error("Both prefix and value are required to encode a prefixed ID.");
195
+ }
196
+ return `${normalizedPrefix}_${normalizedValue}`;
197
+ }
198
+ function decodePrefixedId(id) {
199
+ const normalized = id.trim();
200
+ const match = PREFIXED_ID_PATTERN.exec(normalized);
201
+ if (!match) {
202
+ throw new Error(`Invalid prefixed ID: ${id}`);
203
+ }
204
+ return {
205
+ prefix: match[1],
206
+ value: match[2]
207
+ };
208
+ }
209
+
210
+ // ../contracts/src/lens-filter.contract.ts
211
+ function isLensFilterCriteria(value) {
212
+ if (!value || typeof value !== "object") return false;
213
+ const obj = value;
214
+ return typeof obj.version === "number" && typeof obj.kind === "string";
215
+ }
216
+ function isTaxonomyFilterCriteriaV1(value) {
217
+ if (!isLensFilterCriteria(value)) return false;
218
+ return value.version === 1 && value.kind === "taxonomy";
219
+ }
220
+ function validateFilterCriteria(value) {
221
+ if (value === void 0 || value === null) {
222
+ return { valid: true };
223
+ }
224
+ if (!isLensFilterCriteria(value)) {
225
+ return {
226
+ valid: false,
227
+ errors: [
228
+ 'filterCriteria must have numeric "version" and string "kind" fields'
229
+ ]
230
+ };
231
+ }
232
+ if (isTaxonomyFilterCriteriaV1(value)) {
233
+ return validateTaxonomyFilterV1(value);
234
+ }
235
+ const raw = value;
236
+ return {
237
+ valid: false,
238
+ errors: [
239
+ `Unsupported filter criteria: version=${raw.version}, kind=${raw.kind}`
240
+ ]
241
+ };
242
+ }
243
+ function validateTaxonomyFilterV1(criteria) {
244
+ const errors = [];
245
+ if (!Array.isArray(criteria.entityTypeFilters)) {
246
+ errors.push("entityTypeFilters must be an array");
247
+ return { valid: false, errors };
248
+ }
249
+ if (criteria.entityTypeFilters.length === 0) {
250
+ errors.push("entityTypeFilters must contain at least one entry");
251
+ return { valid: false, errors };
252
+ }
253
+ for (let i = 0; i < criteria.entityTypeFilters.length; i++) {
254
+ const filter = criteria.entityTypeFilters[i];
255
+ if (!filter || typeof filter.entityTypeValue !== "string") {
256
+ errors.push(
257
+ `entityTypeFilters[${i}].entityTypeValue must be a non-empty string`
258
+ );
259
+ continue;
260
+ }
261
+ if (filter.entityTypeValue.trim().length === 0) {
262
+ errors.push(
263
+ `entityTypeFilters[${i}].entityTypeValue must be a non-empty string`
264
+ );
265
+ }
266
+ if (filter.subtypeValues !== void 0 && !Array.isArray(filter.subtypeValues)) {
267
+ errors.push(`entityTypeFilters[${i}].subtypeValues must be an array`);
268
+ }
269
+ }
270
+ if (criteria.ontologyScope !== void 0) {
271
+ if (typeof criteria.ontologyScope !== "object" || criteria.ontologyScope === null) {
272
+ errors.push("ontologyScope must be an object");
273
+ }
274
+ }
275
+ return errors.length === 0 ? { valid: true } : { valid: false, errors };
276
+ }
277
+
278
+ // ../contracts/src/v1/topics/v1.ts
279
+ var ROOT_TOPIC_ID = "n17tm38rwet7wqgzrmwahyt1z582590y";
280
+
281
+ // ../server-core/src/kernelApi.ts
282
+ var binding = null;
283
+ function registerKernelApi(nextBinding) {
284
+ binding = nextBinding;
285
+ }
286
+ function getBinding() {
287
+ if (!binding) {
288
+ throw new Error(
289
+ "Server-core kernelApi not registered. Call registerKernelApi({api, components, internal}) at host boot."
290
+ );
291
+ }
292
+ return binding;
293
+ }
294
+ function makeProxy(which) {
295
+ return new Proxy({}, {
296
+ get(_target, prop) {
297
+ return getBinding()[which][prop];
298
+ }
299
+ });
300
+ }
301
+ makeProxy("api");
302
+ makeProxy("components");
303
+ makeProxy("internal");
304
+
305
+ // ../../apps/mcp-server/src/kernelApi.ts
306
+ registerKernelApi({
307
+ api: api,
308
+ components: components,
309
+ internal: internal
310
+ });
311
+ var api2 = api;
312
+ var components2 = components;
313
+ function isQuietMcpBoot() {
314
+ return process.env.LUCERN_MCP_QUIET === "1";
315
+ }
316
+ function logMcpInfo(message) {
317
+ if (!isQuietMcpBoot()) {
318
+ console.error(message);
319
+ }
320
+ }
321
+
322
+ // ../../apps/mcp-server/src/convex-client.ts
323
+ var _requestScopedClient = new AsyncLocalStorage();
324
+ function runWithScopedClient(client, fn) {
325
+ return _requestScopedClient.run(client, fn);
326
+ }
327
+ function createAdminClient(url, deployKey) {
328
+ const client = new ConvexHttpClient(url);
329
+ client.setAdminAuth(deployKey);
330
+ return client;
331
+ }
332
+ var _lucernClient = null;
333
+ function getLucernClient() {
334
+ const scoped = _requestScopedClient.getStore();
335
+ if (scoped) {
336
+ return scoped;
337
+ }
338
+ if (_lucernClient) {
339
+ return _lucernClient;
340
+ }
341
+ const url = process.env.LUCERN_CONVEX_URL;
342
+ const key = process.env.LUCERN_DEPLOY_KEY;
343
+ if (!url) {
344
+ throw new Error(
345
+ "LUCERN_CONVEX_URL is required. Ensure LUCERN_API_KEY is set in .env.lucern"
346
+ );
347
+ }
348
+ if (!key) {
349
+ throw new Error(
350
+ "LUCERN_DEPLOY_KEY is required. Ensure LUCERN_API_KEY is set in .env.lucern"
351
+ );
352
+ }
353
+ _lucernClient = new ConvexHttpClient(url);
354
+ _lucernClient.setAdminAuth(key);
355
+ logMcpInfo(`[lucern-graph] Lucern client initialized \u2192 ${url}`);
356
+ return _lucernClient;
357
+ }
358
+ var MCP_META_KEYS = [
359
+ "mcpSessionId",
360
+ "mcpToolName",
361
+ "runtimeToolName",
362
+ "runtimePackKey",
363
+ "runtimePackInstallScope"
364
+ ];
365
+ var mutationRuntimeCache = /* @__PURE__ */ new Map();
366
+ var packInstallScopeCache = /* @__PURE__ */ new Map();
367
+ async function resolvePackInstallScope(packKey) {
368
+ const normalizedPackKey = packKey.trim();
369
+ if (!normalizedPackKey) {
370
+ return;
371
+ }
372
+ let cached = packInstallScopeCache.get(normalizedPackKey);
373
+ if (!cached) {
374
+ cached = (async () => {
375
+ const packDefinition = await mcAdminQuery(
376
+ "packs:getPackDefinition",
377
+ {
378
+ packKey: normalizedPackKey
379
+ }
380
+ );
381
+ const installScope = packDefinition?.installScope;
382
+ if (installScope === "tenant" || installScope === "workspace") {
383
+ return installScope;
384
+ }
385
+ throw new Error(
386
+ `[mcp-runtime] Pack "${normalizedPackKey}" is missing a valid installScope`
387
+ );
388
+ })();
389
+ packInstallScopeCache.set(normalizedPackKey, cached);
390
+ }
391
+ return await cached;
392
+ }
393
+ async function resolveMutationRuntimeFields(toolName) {
394
+ if (typeof toolName !== "string" || toolName.trim().length === 0) {
395
+ return null;
396
+ }
397
+ const normalizedToolName = toolName.trim();
398
+ let cached = mutationRuntimeCache.get(normalizedToolName);
399
+ if (!cached) {
400
+ cached = (async () => {
401
+ const tools = await getLucernClient().query(
402
+ api2.toolAccess.getExecutableTools,
403
+ {}
404
+ );
405
+ const tool = tools.find(
406
+ (candidate) => candidate?.toolName === normalizedToolName && candidate?.isActive !== false && candidate?.status !== "deprecated" && candidate?.status !== "disabled"
407
+ );
408
+ const packKey = typeof tool?.packKey === "string" ? tool.packKey.trim() : "";
409
+ if (!packKey) {
410
+ return { runtimeToolName: normalizedToolName };
411
+ }
412
+ return {
413
+ runtimeToolName: normalizedToolName,
414
+ runtimePackKey: packKey,
415
+ runtimePackInstallScope: await resolvePackInstallScope(packKey)
416
+ };
417
+ })();
418
+ mutationRuntimeCache.set(normalizedToolName, cached);
419
+ }
420
+ return await cached;
421
+ }
422
+ async function adminMutation(fn, args) {
423
+ const cleanArgs = { ...args };
424
+ if (cleanArgs.runtimeToolName === void 0 && cleanArgs.runtimePackKey === void 0 && cleanArgs.runtimePackInstallScope === void 0) {
425
+ const runtimeFields = await resolveMutationRuntimeFields(args?.mcpToolName);
426
+ if (runtimeFields) {
427
+ Object.assign(cleanArgs, runtimeFields);
428
+ }
429
+ }
430
+ for (const key of MCP_META_KEYS) {
431
+ delete cleanArgs[key];
432
+ }
433
+ return getLucernClient().mutation(fn, cleanArgs);
434
+ }
435
+ async function adminQuery(fn, args) {
436
+ return getLucernClient().query(fn, args);
437
+ }
438
+ var _mcClient = null;
439
+ var _mcClientChecked = false;
440
+ function getMcClient() {
441
+ if (_mcClientChecked) {
442
+ return _mcClient;
443
+ }
444
+ const url = process.env.MC_CONVEX_URL;
445
+ const key = process.env.MC_DEPLOY_KEY;
446
+ if (url && key) {
447
+ _mcClient = new ConvexHttpClient(url);
448
+ _mcClient.setAdminAuth(key);
449
+ logMcpInfo(`[lucern-graph] Master Control client initialized \u2192 ${url}`);
450
+ } else {
451
+ logMcpInfo(
452
+ "[lucern-graph] Master Control client not configured (no MC_CONVEX_URL). Methodology packs will use hardcoded fallback."
453
+ );
454
+ }
455
+ _mcClientChecked = true;
456
+ return _mcClient;
457
+ }
458
+ async function mcAdminQuery(fn, args) {
459
+ const c = getMcClient();
460
+ if (!c) {
461
+ throw new Error(
462
+ "Master Control client not configured (set MC_CONVEX_URL + MC_DEPLOY_KEY)"
463
+ );
464
+ }
465
+ return c.query(fn, args);
466
+ }
467
+ process.env.LUCERN_AGENT_IDENTITY || "agent:claude-code";
468
+ crypto.randomUUID();
469
+
470
+ // ../../apps/mcp-server/src/scope.ts
471
+ var defaultTopicId = null;
472
+ var PUBLIC_TOPIC_PREFIX = "top_";
473
+ function decodePublicTopicId(topicId) {
474
+ if (!isNonEmptyString(topicId)) {
475
+ return void 0;
476
+ }
477
+ return topicId.startsWith(PUBLIC_TOPIC_PREFIX) ? topicId.slice(PUBLIC_TOPIC_PREFIX.length) : topicId;
478
+ }
479
+ function readTopicIdArg(args) {
480
+ const topicId = args.topicId;
481
+ const legacyProjectId = args.projectId;
482
+ return topicId || legacyProjectId || void 0;
483
+ }
484
+ var LUCERN_JSON_PATH = path2.resolve(process.cwd(), ".lucern.json");
485
+ function readLucernJson() {
486
+ try {
487
+ const raw = fs.readFileSync(LUCERN_JSON_PATH, "utf-8");
488
+ const parsed = JSON.parse(raw);
489
+ return {
490
+ ...parsed,
491
+ topicId: parsed.topicId,
492
+ topicName: parsed.topicName
493
+ };
494
+ } catch {
495
+ return null;
496
+ }
497
+ }
498
+ function isNonEmptyString(value) {
499
+ return typeof value === "string" && value.trim().length > 0;
500
+ }
501
+ function readTopicMappedProjectId(topic) {
502
+ const metadata = topic.metadata || {};
503
+ const candidate = metadata.legacyProjectId || metadata.projectId || metadata.scopeProjectId;
504
+ return isNonEmptyString(candidate) ? candidate : void 0;
505
+ }
506
+ async function tryGetTopicById(topicId) {
507
+ const normalizedTopicId = decodePublicTopicId(topicId);
508
+ if (!normalizedTopicId) {
509
+ return null;
510
+ }
511
+ try {
512
+ const topic = await adminQuery(components2.lucern.topics.get, {
513
+ id: normalizedTopicId
514
+ });
515
+ return topic || null;
516
+ } catch {
517
+ return null;
518
+ }
519
+ }
520
+ async function tryGetNodeById(nodeId) {
521
+ try {
522
+ const node = await adminQuery(components2.lucern.epistemicNodes.getInternal, {
523
+ nodeId
524
+ });
525
+ return node || null;
526
+ } catch {
527
+ return null;
528
+ }
529
+ }
530
+ async function findTopicByMappedProjectId(legacyScopeId) {
531
+ try {
532
+ const topics = await adminQuery(components2.lucern.topics.list, {});
533
+ return topics.find((topic) => readTopicMappedProjectId(topic) === legacyScopeId) || null;
534
+ } catch {
535
+ return null;
536
+ }
537
+ }
538
+ async function resolveTopicScopeId(scopeId, toolName) {
539
+ let resolved;
540
+ const normalizedScopeId = decodePublicTopicId(scopeId);
541
+ if (!isNonEmptyString(scopeId)) {
542
+ if (isNonEmptyString(defaultTopicId)) {
543
+ resolved = defaultTopicId;
544
+ } else {
545
+ const lucernContext = readLucernJson();
546
+ const ambientTopicId = decodePublicTopicId(lucernContext?.topicId);
547
+ if (isNonEmptyString(ambientTopicId)) {
548
+ resolved = ambientTopicId;
549
+ }
550
+ }
551
+ if (!resolved) {
552
+ throw new Error(
553
+ `[${toolName}] Missing topic scope. Provide topicId.`
554
+ );
555
+ }
556
+ }
557
+ if (!resolved) {
558
+ const topic = normalizedScopeId ? await tryGetTopicById(normalizedScopeId) : null;
559
+ if (topic) {
560
+ resolved = String(topic._id);
561
+ }
562
+ }
563
+ if (!resolved) {
564
+ const mappedTopic = normalizedScopeId ? await findTopicByMappedProjectId(normalizedScopeId) : null;
565
+ if (mappedTopic) {
566
+ resolved = String(mappedTopic._id);
567
+ }
568
+ }
569
+ if (!resolved) {
570
+ const node = normalizedScopeId ? await tryGetNodeById(normalizedScopeId) : null;
571
+ if (node && isNonEmptyString(node.topicId)) {
572
+ resolved = node.topicId;
573
+ }
574
+ }
575
+ if (!resolved) {
576
+ throw new Error(
577
+ `[${toolName}] Scope "${scopeId}" is not a topic and has no mapped topic.`
578
+ );
579
+ }
580
+ return resolved;
581
+ }
582
+ function getDefaultScopeContext() {
583
+ const lucernContext = readLucernJson();
584
+ const ambientTopicId = decodePublicTopicId(lucernContext?.topicId);
585
+ if (ambientTopicId) {
586
+ return { topicId: ambientTopicId };
587
+ }
588
+ return { topicId: null };
589
+ }
590
+
591
+ // ../../apps/mcp-server/src/handlers/beliefs.ts
592
+ var AMBIGUOUS_SCALAR_SUGGESTION = "Use opinion tuple (b, d, u, a) or an @lucern/sdk opinionFromBaseRate/opinionFromDogmatic/opinionFromProjected helper.";
593
+ function readOpinionTuple(args) {
594
+ const belief = readNumber(args.belief);
595
+ const disbelief = readNumber(args.disbelief);
596
+ const uncertainty = readNumber(args.uncertainty);
597
+ const baseRate = readNumber(args.baseRate);
598
+ const tupleValues = [belief, disbelief, uncertainty, baseRate];
599
+ const providedCount = tupleValues.filter(
600
+ (value) => value !== void 0
601
+ ).length;
602
+ if (providedCount === 0 && readNumber(args.confidence ?? args.newConfidence) !== void 0) {
603
+ throw new Error(
604
+ JSON.stringify({
605
+ code: "AMBIGUOUS_SCALAR",
606
+ message: "Scalar confidence input is ambiguous without an explicit subjective-logic interpretation.",
607
+ suggestion: AMBIGUOUS_SCALAR_SUGGESTION
608
+ })
609
+ );
610
+ }
611
+ if (providedCount !== tupleValues.length) {
612
+ throw new Error(
613
+ "belief, disbelief, uncertainty, and baseRate must all be provided together."
614
+ );
615
+ }
616
+ return {
617
+ b: belief ?? 0,
618
+ d: disbelief ?? 0,
619
+ u: uncertainty ?? 0,
620
+ a: baseRate ?? 0.5
621
+ };
622
+ }
623
+ var beliefHandlers = {
624
+ async create_belief(args, ctx) {
625
+ const baseRate = readNumber(args.baseRate);
626
+ if (baseRate === void 0) {
627
+ throw new Error("baseRate is required for create_belief.");
628
+ }
629
+ if (baseRate < 0 || baseRate > 1) {
630
+ throw new Error("baseRate must be within [0, 1].");
631
+ }
632
+ return formatSdkResult(
633
+ await getSdkClient(ctx).beliefs.create({
634
+ topicId: readString(readTopicIdArg(args)) ?? "",
635
+ text: readString(args.text ?? args.canonicalText ?? args.formulation) ?? "",
636
+ baseRate,
637
+ rationale: readString(args.rationale),
638
+ worktreeId: readString(args.worktreeId),
639
+ pillar: readString(args.pillar),
640
+ sourceBeliefIds: readStringArray(args.sourceBeliefIds),
641
+ sourceType: readString(args.sourceType),
642
+ beliefType: readString(args.beliefType),
643
+ reversibility: readString(args.reversibility),
644
+ predictionMeta: asJsonObject(args.predictionMeta),
645
+ metadata: asJsonObject(args.metadata)
646
+ })
647
+ );
648
+ },
649
+ async get_belief(args, ctx) {
650
+ return formatSdkResult(
651
+ await getSdkClient(ctx).beliefs.get(
652
+ readString(args.id ?? args.nodeId ?? args.beliefId) ?? ""
653
+ )
654
+ );
655
+ },
656
+ async list_beliefs(args, ctx) {
657
+ return formatSdkResult(
658
+ await getSdkClient(ctx).beliefs.list({
659
+ topicId: readString(readTopicIdArg(args)),
660
+ status: readString(args.status),
661
+ worktreeId: readString(args.worktreeId),
662
+ minConfidence: readNumber(args.minConfidence),
663
+ limit: readNumber(args.limit),
664
+ cursor: readString(args.cursor)
665
+ })
666
+ );
667
+ },
668
+ async refine_belief(args, ctx) {
669
+ return formatSdkResult(
670
+ await getSdkClient(ctx).beliefs.refine(
671
+ readString(args.id ?? args.nodeId ?? args.beliefId) ?? "",
672
+ {
673
+ text: readString(args.canonicalText ?? args.text ?? args.formulation) ?? "",
674
+ rationale: readString(args.rationale)
675
+ }
676
+ )
677
+ );
678
+ },
679
+ async modulate_confidence(args, ctx) {
680
+ const opinion = readOpinionTuple(args);
681
+ return formatSdkResult(
682
+ await getSdkClient(ctx).beliefs.modulateConfidence(
683
+ readString(args.id ?? args.nodeId ?? args.beliefId) ?? "",
684
+ {
685
+ opinion,
686
+ trigger: readString(args.trigger),
687
+ rationale: readString(args.rationale) ?? "",
688
+ maxInlinePropagationTargets: readNumber(
689
+ args.maxInlinePropagationTargets
690
+ )
691
+ }
692
+ )
693
+ );
694
+ },
695
+ async fork_belief(args, ctx) {
696
+ return formatSdkResult(
697
+ await getSdkClient(ctx).beliefs.fork(
698
+ readString(args.id ?? args.nodeId ?? args.beliefId) ?? "",
699
+ {
700
+ text: readString(args.text ?? args.newFormulation ?? args.formulation) ?? "",
701
+ forkReason: readString(args.forkReason),
702
+ rationale: readString(args.rationale)
703
+ }
704
+ )
705
+ );
706
+ },
707
+ async archive_belief(args, ctx) {
708
+ return formatSdkResult(
709
+ await getSdkClient(ctx).beliefs.archive(
710
+ readString(args.id ?? args.nodeId ?? args.beliefId) ?? "",
711
+ {
712
+ reason: readString(args.reason ?? args.rationale)
713
+ }
714
+ )
715
+ );
716
+ },
717
+ async query_lineage(args, ctx) {
718
+ return formatSdkResult(
719
+ await getSdkClient(ctx).beliefs.lineage(
720
+ readString(args.id ?? args.nodeId ?? args.beliefId) ?? ""
721
+ )
722
+ );
723
+ },
724
+ async get_confidence_history(args, ctx) {
725
+ return formatSdkResult(
726
+ await getSdkClient(ctx).beliefs.confidenceHistory(
727
+ readString(args.id ?? args.nodeId ?? args.beliefId) ?? ""
728
+ )
729
+ );
730
+ },
731
+ async create_epistemic_contract(args, ctx) {
732
+ return formatSdkResult(
733
+ await getSdkClient(ctx).beliefs.createContract(
734
+ readString(
735
+ args.id ?? args.nodeId ?? args.beliefId ?? args.beliefNodeId
736
+ ) ?? "",
737
+ {
738
+ title: readString(args.title) ?? "",
739
+ description: readString(args.description),
740
+ conditionType: readString(args.conditionType),
741
+ direction: readString(args.direction),
742
+ condition: asRecord(args.condition),
743
+ deadline: readNumber(args.deadline),
744
+ compositeOf: readStringArray(args.compositeOf),
745
+ compositeOperator: readString(args.compositeOperator),
746
+ modulation: asRecord(args.modulation),
747
+ evaluationSchedule: readString(
748
+ args.evaluationSchedule ?? args.schedule
749
+ ),
750
+ periodicIntervalMs: readNumber(args.periodicIntervalMs)
751
+ }
752
+ )
753
+ );
754
+ },
755
+ async bisect_confidence(args, ctx) {
756
+ return formatSdkResult(
757
+ await getSdkClient(ctx).beliefs.bisect(
758
+ readString(args.id ?? args.nodeId ?? args.beliefId) ?? "",
759
+ {
760
+ expectedDirection: readString(args.expectedDirection),
761
+ timeRange: readTimeRange(args.timeRange)
762
+ }
763
+ )
764
+ );
765
+ }
766
+ };
767
+
768
+ // ../../apps/mcp-server/src/handlers/bootstrap-session.ts
769
+ function slugify(name) {
770
+ return name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 40);
771
+ }
772
+ async function resolveBeliefs(nodeIds) {
773
+ const results = [];
774
+ for (const nodeId of nodeIds) {
775
+ try {
776
+ const node = await adminQuery(components2.lucern.epistemicNodes.get, {
777
+ nodeId
778
+ });
779
+ if (!node) {
780
+ continue;
781
+ }
782
+ results.push({
783
+ nodeId,
784
+ text: String(node.canonicalText || "").slice(0, 200),
785
+ confidence: typeof node.confidence === "number" ? node.confidence : null
786
+ });
787
+ } catch {
788
+ }
789
+ }
790
+ return results;
791
+ }
792
+ async function resolveQuestions(nodeIds) {
793
+ const results = [];
794
+ for (const nodeId of nodeIds) {
795
+ try {
796
+ const node = await adminQuery(components2.lucern.epistemicNodes.get, {
797
+ nodeId
798
+ });
799
+ if (!node) {
800
+ continue;
801
+ }
802
+ const metadata = node.metadata || {};
803
+ results.push({
804
+ nodeId,
805
+ text: String(node.canonicalText || "").slice(0, 200),
806
+ status: String(metadata.questionStatus || node.status || "open"),
807
+ priority: String(metadata.priority || "medium")
808
+ });
809
+ } catch {
810
+ }
811
+ }
812
+ return results;
813
+ }
814
+ async function beginBuildSession(args) {
815
+ const worktreeId = typeof args.worktreeId === "string" ? args.worktreeId : void 0;
816
+ if (!worktreeId) {
817
+ throw new Error("[begin_build_session] worktreeId is required");
818
+ }
819
+ const branch = typeof args.branch === "string" && args.branch.trim().length > 0 ? args.branch.trim() : void 0;
820
+ const branchBase = typeof args.branchBase === "string" && args.branchBase.trim().length > 0 ? args.branchBase.trim() : "staging";
821
+ const prBase = typeof args.prBase === "string" && args.prBase.trim().length > 0 ? args.prBase.trim() : "staging";
822
+ const sessionMode = typeof args.sessionMode === "string" && args.sessionMode.trim().length > 0 ? args.sessionMode.trim() : "async";
823
+ const activateIfPlanning = args.activateIfPlanning !== false;
824
+ const worktree = await adminQuery(components2.lucern.worktrees.get, {
825
+ worktreeId
826
+ });
827
+ if (!worktree) {
828
+ throw new Error(`Worktree ${worktreeId} not found`);
829
+ }
830
+ const worktreeName = String(worktree.name || "Untitled");
831
+ const topicId = String(worktree.topicId || "");
832
+ const track = String(worktree.track || "untracked");
833
+ const trackPosition = worktree.trackPosition ?? 0;
834
+ const executionBand = worktree.executionBand ?? 0;
835
+ const gate = String(worktree.gate || "");
836
+ const hypothesis = String(worktree.hypothesis || worktree.beliefFocus || "");
837
+ let status = String(worktree.status || "planning");
838
+ const dependsOn = worktree.dependsOn || [];
839
+ const blocks = worktree.blocks || [];
840
+ const targetBeliefIds = worktree.targetBeliefIds || [];
841
+ const targetQuestionIds = worktree.targetQuestionIds || [];
842
+ if (activateIfPlanning && status === "planning") {
843
+ try {
844
+ await adminMutation(components2.lucern.worktrees.activate, {
845
+ worktreeId
846
+ });
847
+ status = "active";
848
+ } catch {
849
+ }
850
+ }
851
+ let topicName = "Unknown";
852
+ try {
853
+ const topic = await adminQuery(components2.lucern.topics.get, {
854
+ id: topicId
855
+ });
856
+ if (topic) {
857
+ topicName = String(topic.name || "Unknown");
858
+ }
859
+ } catch {
860
+ }
861
+ const allBeliefs = await resolveBeliefs(targetBeliefIds);
862
+ const topBeliefs = allBeliefs.slice().sort((left, right) => (right.confidence ?? -1) - (left.confidence ?? -1)).slice(0, 8);
863
+ const allQuestions = await resolveQuestions(targetQuestionIds);
864
+ const openQuestions = [];
865
+ const resolvedDecisions = [];
866
+ for (const question of allQuestions) {
867
+ const questionStatus = question.status.toLowerCase();
868
+ if (questionStatus === "answered" || questionStatus === "resolved") {
869
+ let decision = "(decision recorded \u2014 call get_answer for details)";
870
+ try {
871
+ const answer = await adminQuery(
872
+ api2.epistemicAnswers.getLatestForQuestion,
873
+ {
874
+ questionNodeId: question.nodeId
875
+ }
876
+ );
877
+ if (answer) {
878
+ decision = String(
879
+ answer.answerText || answer.canonicalText || decision
880
+ ).slice(0, 200);
881
+ }
882
+ } catch {
883
+ try {
884
+ const node = await adminQuery(components2.lucern.epistemicNodes.get, {
885
+ nodeId: question.nodeId
886
+ });
887
+ if (node?._id) {
888
+ const answer = await adminQuery(
889
+ api2.epistemicAnswers.getLatestForQuestion,
890
+ {
891
+ questionNodeId: node._id
892
+ }
893
+ );
894
+ if (answer) {
895
+ decision = String(
896
+ answer.answerText || answer.canonicalText || decision
897
+ ).slice(0, 200);
898
+ }
899
+ }
900
+ } catch {
901
+ }
902
+ }
903
+ resolvedDecisions.push({
904
+ question: question.text.slice(0, 150),
905
+ decision
906
+ });
907
+ continue;
908
+ }
909
+ openQuestions.push({
910
+ nodeId: question.nodeId,
911
+ text: question.text,
912
+ priority: question.priority
913
+ });
914
+ }
915
+ try {
916
+ const topicQuestions = await adminQuery(components2.lucern.epistemicQuestions.getByTopic, {
917
+ topicId,
918
+ userId: "system",
919
+ limit: 20
920
+ }).catch(() => []);
921
+ for (const question of Array.isArray(topicQuestions) ? topicQuestions : []) {
922
+ const metadata = question.metadata || {};
923
+ const questionStatus = String(
924
+ metadata.questionStatus || question.status || "open"
925
+ ).toLowerCase();
926
+ if ((questionStatus === "open" || questionStatus === "in_progress") && !targetQuestionIds.includes(String(question._id))) {
927
+ openQuestions.push({
928
+ nodeId: String(question._id),
929
+ text: String(question.canonicalText || "").slice(0, 200),
930
+ priority: String(metadata.priority || "medium")
931
+ });
932
+ }
933
+ }
934
+ } catch {
935
+ }
936
+ const dependencies = [];
937
+ for (const dependencyId of dependsOn.slice(0, 5)) {
938
+ try {
939
+ const dependency = await adminQuery(components2.lucern.worktrees.get, {
940
+ worktreeId: dependencyId
941
+ });
942
+ dependencies.push({
943
+ worktreeId: dependencyId,
944
+ title: String(dependency?.name || "Unknown"),
945
+ status: String(dependency?.status || "unknown")
946
+ });
947
+ } catch {
948
+ dependencies.push({
949
+ worktreeId: dependencyId,
950
+ title: "Unknown",
951
+ status: "unknown"
952
+ });
953
+ }
954
+ }
955
+ const unblocks = [];
956
+ for (const blockedId of blocks.slice(0, 5)) {
957
+ try {
958
+ const blocked = await adminQuery(components2.lucern.worktrees.get, {
959
+ worktreeId: blockedId
960
+ });
961
+ unblocks.push({
962
+ worktreeId: blockedId,
963
+ title: String(blocked?.name || "Unknown")
964
+ });
965
+ } catch {
966
+ unblocks.push({
967
+ worktreeId: blockedId,
968
+ title: "Unknown"
969
+ });
970
+ }
971
+ }
972
+ const effectiveBranch = branch || `codex/${slugify(worktreeName)}`;
973
+ const incompleteDependencies = dependencies.filter(
974
+ (dependency) => dependency.status !== "completed" && dependency.status !== "merged"
975
+ );
976
+ const mergeOrderNotes = incompleteDependencies.length > 0 ? `Blocked by: ${incompleteDependencies.map((dependency) => dependency.title).join(", ")}` : "none";
977
+ const requiredDocs = [
978
+ "docs/api/EK-13-api-sdk-architecture.md",
979
+ "docs/api/EK-13.1.5-repo-architecture-blueprint.md",
980
+ "docs/api/EK-13.1-contract-authority.md",
981
+ "docs/development/handoff-contract.md"
982
+ ];
983
+ const focus = hypothesis ? `${hypothesis.split(".")[0]}.` : `Complete ${worktreeName}`;
984
+ const exitCriteria = gate ? [`Gate: ${gate}`] : [];
985
+ exitCriteria.push(
986
+ "All namespace surfaces end-to-end: contract \u2192 domain \u2192 HTTP \u2192 SDK \u2192 MCP \u2192 test",
987
+ "All code lands in target-state paths under lucern/",
988
+ "PR targets staging, not main"
989
+ );
990
+ const keyFiles = [
991
+ "app/api/platform/v1/_lib/gateway.ts",
992
+ "modules/access-control/src/principalContext.ts",
993
+ "lucern/packages/sdk/src/coreClient.ts",
994
+ "lucern/packages/sdk/src/identityClient.ts",
995
+ "lucern/contracts/src/sdk-methods.contract.ts",
996
+ "app/api/platform/v1/identity/"
997
+ ];
998
+ const pillarKeywords = [
999
+ "Pillar 1",
1000
+ "Pillar 2",
1001
+ "Pillar 3",
1002
+ "Pillar 4",
1003
+ "Pillar 5",
1004
+ "Pillar 6",
1005
+ "Pillar 7",
1006
+ "Pillar 8",
1007
+ "8 innovation pillars"
1008
+ ];
1009
+ const pillarBeliefs = [];
1010
+ for (const belief of allBeliefs) {
1011
+ for (const keyword of pillarKeywords) {
1012
+ if (!belief.text.includes(keyword)) {
1013
+ continue;
1014
+ }
1015
+ const pillarMatch = belief.text.match(/Pillar \d+ \([^)]+\)/);
1016
+ pillarBeliefs.push({
1017
+ pillar: pillarMatch ? pillarMatch[0] : keyword,
1018
+ text: belief.text.slice(0, 250),
1019
+ nodeId: belief.nodeId
1020
+ });
1021
+ break;
1022
+ }
1023
+ }
1024
+ const visionDocs = [
1025
+ {
1026
+ path: "docs/product/core-value-propositions.md",
1027
+ description: "8 innovation pillars through developer, marketing, and investor lenses"
1028
+ },
1029
+ {
1030
+ path: "docs/product/five-domains.md",
1031
+ description: "5 product domains: MC, Tenant, Developer, Reasoning Control, Reasoning"
1032
+ },
1033
+ {
1034
+ path: "docs/product/innovation-pillars.md",
1035
+ description: "The 8 pillars that define what makes Lucern unique"
1036
+ },
1037
+ {
1038
+ path: "docs/product/vision-to-roadmap-bridge.md",
1039
+ description: "Where each pillar is today vs. where it goes \u2014 the north star trajectory"
1040
+ }
1041
+ ];
1042
+ return {
1043
+ topicId,
1044
+ topicName,
1045
+ worktreeId,
1046
+ worktreeName,
1047
+ branch: effectiveBranch,
1048
+ branchBase,
1049
+ prBase,
1050
+ track,
1051
+ trackPosition,
1052
+ executionBand,
1053
+ gate,
1054
+ hypothesis,
1055
+ focus,
1056
+ status,
1057
+ sessionMode,
1058
+ targetBeliefIds,
1059
+ targetQuestionIds,
1060
+ topBeliefs,
1061
+ openQuestions,
1062
+ resolvedDecisions,
1063
+ exitCriteria,
1064
+ requiredDocs,
1065
+ keyFiles,
1066
+ pillarBeliefs,
1067
+ visionDocs,
1068
+ dependencies,
1069
+ unblocks,
1070
+ mergeOrderNotes
1071
+ };
1072
+ }
1073
+
1074
+ // ../../apps/mcp-server/src/handlers/bootstrap.ts
1075
+ var bootstrapHandlers = {
1076
+ async generate_session_handoff(args, ctx) {
1077
+ return formatSdkResult(
1078
+ await getSdkClient(ctx).bootstrap.generateSessionHandoff(args)
1079
+ );
1080
+ },
1081
+ async begin_build_session(args, ctx) {
1082
+ return beginBuildSession(args);
1083
+ }
1084
+ };
1085
+
1086
+ // ../../apps/mcp-server/src/handlers/coding.ts
1087
+ var codingHandlers = {
1088
+ async get_code_context(args, ctx) {
1089
+ return formatSdkResult(await getSdkClient(ctx).coding.getCodeContext(args));
1090
+ },
1091
+ async get_change_history(args, ctx) {
1092
+ return formatSdkResult(
1093
+ await getSdkClient(ctx).coding.getChangeHistory(args)
1094
+ );
1095
+ },
1096
+ async record_attempt(args, ctx) {
1097
+ return formatSdkResult(await getSdkClient(ctx).coding.recordAttempt(args));
1098
+ },
1099
+ async get_failure_log(args, ctx) {
1100
+ return formatSdkResult(await getSdkClient(ctx).coding.getFailureLog(args));
1101
+ }
1102
+ };
1103
+
1104
+ // ../../apps/mcp-server/src/handlers/contracts.ts
1105
+ var contractHandlers = {
1106
+ async create_epistemic_contract(args, ctx) {
1107
+ return formatSdkResult(
1108
+ await getSdkClient(ctx).contracts.create(args)
1109
+ );
1110
+ },
1111
+ async evaluate_contract(args, ctx) {
1112
+ return formatSdkResult(
1113
+ await getSdkClient(ctx).contracts.evaluate({
1114
+ contractId: readString(args.contractId),
1115
+ trigger: args.trigger,
1116
+ topicId: readString(args.topicId)
1117
+ })
1118
+ );
1119
+ },
1120
+ async get_contract_status(args, ctx) {
1121
+ if (!args.beliefNodeId && !args.contractId) {
1122
+ throw new Error(
1123
+ "get_contract_status requires either beliefNodeId or contractId."
1124
+ );
1125
+ }
1126
+ return formatSdkResult(
1127
+ await getSdkClient(ctx).contracts.getStatus({
1128
+ beliefNodeId: readString(args.beliefNodeId),
1129
+ contractId: readString(args.contractId),
1130
+ status: args.status
1131
+ })
1132
+ );
1133
+ }
1134
+ };
1135
+
1136
+ // ../../apps/mcp-server/src/handlers/contradictions.ts
1137
+ function normalizeBeliefId(value) {
1138
+ try {
1139
+ const decoded = decodePrefixedId(value);
1140
+ return encodePrefixedId("bel", decoded.value);
1141
+ } catch {
1142
+ return encodePrefixedId("bel", value);
1143
+ }
1144
+ }
1145
+ var contradictionHandlers = {
1146
+ async flag_contradiction(args, ctx) {
1147
+ const topicId = await resolveTopicScopeId(
1148
+ readTopicIdArg(args),
1149
+ "flag_contradiction"
1150
+ );
1151
+ return formatSdkResult(
1152
+ await getSdkClient(ctx).contradictions.flag({
1153
+ beliefA: readString(args.beliefA) ?? "",
1154
+ beliefB: readString(args.beliefB) ?? "",
1155
+ description: readString(args.description) ?? "",
1156
+ topicId,
1157
+ severity: readString(args.severity),
1158
+ defeatType: readString(args.defeatType)
1159
+ })
1160
+ );
1161
+ },
1162
+ async find_contradictions(args, ctx) {
1163
+ const topicId = await resolveTopicScopeId(
1164
+ readTopicIdArg(args) ?? readString(args.nodeId),
1165
+ "find_contradictions"
1166
+ );
1167
+ const beliefId = readString(args.nodeId);
1168
+ const payload = formatSdkResult(
1169
+ await getSdkClient(ctx).contradictions.list({
1170
+ topicId,
1171
+ status: readString(args.status),
1172
+ limit: readNumber(args.limit)
1173
+ })
1174
+ );
1175
+ if (!beliefId) {
1176
+ return payload;
1177
+ }
1178
+ const normalizedBeliefId = normalizeBeliefId(beliefId);
1179
+ return {
1180
+ ...payload,
1181
+ contradictions: (Array.isArray(payload.contradictions) ? payload.contradictions : []).filter(
1182
+ (entry) => entry.beliefA === normalizedBeliefId || entry.beliefB === normalizedBeliefId
1183
+ )
1184
+ };
1185
+ },
1186
+ async list_contradictions(args, ctx) {
1187
+ const topicId = await resolveTopicScopeId(
1188
+ readTopicIdArg(args),
1189
+ "list_contradictions"
1190
+ );
1191
+ return formatSdkResult(
1192
+ await getSdkClient(ctx).contradictions.list({
1193
+ topicId,
1194
+ status: readString(args.status),
1195
+ limit: readNumber(args.limit)
1196
+ })
1197
+ );
1198
+ },
1199
+ async get_contradiction(args, ctx) {
1200
+ return formatSdkResult(
1201
+ await getSdkClient(ctx).contradictions.get(
1202
+ readString(args.id ?? args.contradictionId) ?? ""
1203
+ )
1204
+ );
1205
+ }
1206
+ };
1207
+
1208
+ // ../../apps/mcp-server/src/handlers/coordination.ts
1209
+ var coordinationHandlers = {
1210
+ async register_session(args, ctx) {
1211
+ return formatSdkResult(
1212
+ await getSdkClient(ctx).coordination.registerSession(args)
1213
+ );
1214
+ },
1215
+ async heartbeat_session(args, ctx) {
1216
+ return formatSdkResult(
1217
+ await getSdkClient(ctx).coordination.heartbeatSession(args)
1218
+ );
1219
+ },
1220
+ async end_session(args, ctx) {
1221
+ return formatSdkResult(await getSdkClient(ctx).coordination.endSession(args));
1222
+ },
1223
+ async list_active_sessions(args, ctx) {
1224
+ return formatSdkResult(
1225
+ await getSdkClient(ctx).coordination.listActiveSessions(args)
1226
+ );
1227
+ },
1228
+ async send_agent_message(args, ctx) {
1229
+ return formatSdkResult(
1230
+ await getSdkClient(ctx).coordination.sendAgentMessage(args)
1231
+ );
1232
+ },
1233
+ async broadcast_message(args, ctx) {
1234
+ return formatSdkResult(
1235
+ await getSdkClient(ctx).coordination.broadcastMessage(args)
1236
+ );
1237
+ },
1238
+ async get_agent_inbox(args, ctx) {
1239
+ return formatSdkResult(await getSdkClient(ctx).coordination.getInbox(args));
1240
+ },
1241
+ async claim_files(args, ctx) {
1242
+ return formatSdkResult(await getSdkClient(ctx).coordination.claimFiles(args));
1243
+ }
1244
+ };
1245
+
1246
+ // ../../apps/mcp-server/src/handlers/edges.ts
1247
+ var edgeHandlers = {
1248
+ async create_edge(args, ctx) {
1249
+ return formatSdkResult(
1250
+ await getSdkClient(ctx).edges.create({
1251
+ sourceId: readString(args.sourceId) ?? "",
1252
+ targetId: readString(args.targetId) ?? "",
1253
+ edgeType: readString(args.edgeType) ?? "",
1254
+ topicId: readString(args.topicId ?? args.projectId),
1255
+ confidence: readNumber(args.confidence),
1256
+ weight: readNumber(args.weight),
1257
+ context: readString(args.context) ?? readString(args.reasoning)
1258
+ })
1259
+ );
1260
+ },
1261
+ async list_edges(args, ctx) {
1262
+ return formatSdkResult(
1263
+ await getSdkClient(ctx).edges.list({
1264
+ sourceId: readString(args.sourceId) ?? "",
1265
+ edgeType: readString(args.edgeType),
1266
+ limit: readNumber(args.limit),
1267
+ cursor: readString(args.cursor)
1268
+ })
1269
+ );
1270
+ },
1271
+ async traverse_graph(args, ctx) {
1272
+ return formatSdkResult(
1273
+ await getSdkClient(ctx).edges.traverse({
1274
+ startNode: readString(args.startNode) ?? "",
1275
+ direction: readString(args.direction),
1276
+ maxDepth: readNumber(args.maxDepth),
1277
+ topicId: readString(args.topicId ?? args.projectId)
1278
+ })
1279
+ );
1280
+ }
1281
+ };
1282
+
1283
+ // ../../apps/mcp-server/src/handlers/graph.ts
1284
+ var graphHandlers = {
1285
+ async traverse_graph(args, ctx) {
1286
+ return edgeHandlers.traverse_graph(args, ctx);
1287
+ },
1288
+ async search_beliefs(args, ctx) {
1289
+ const topicId = await resolveTopicScopeId(
1290
+ readTopicIdArg(args),
1291
+ "search_beliefs"
1292
+ );
1293
+ return formatSdkResult(
1294
+ await getSdkClient(ctx).beliefs.search({
1295
+ query: typeof args.query === "string" ? args.query : "",
1296
+ topicId,
1297
+ status: typeof args.status === "string" ? args.status : void 0,
1298
+ minConfidence: typeof args.minConfidence === "number" ? args.minConfidence : void 0,
1299
+ limit: typeof args.limit === "number" ? args.limit : void 0
1300
+ })
1301
+ );
1302
+ },
1303
+ async find_contradictions(args, ctx) {
1304
+ return contradictionHandlers.find_contradictions(args, ctx);
1305
+ },
1306
+ async bisect_confidence(args, ctx) {
1307
+ return beliefHandlers.bisect_confidence(args, ctx);
1308
+ },
1309
+ async trace_entity_impact(args, ctx) {
1310
+ const topicId = await resolveTopicScopeId(
1311
+ readTopicIdArg(args),
1312
+ "trace_entity_impact"
1313
+ ).catch(() => void 0);
1314
+ return formatSdkResult(
1315
+ await getSdkClient(ctx).graph.traceEntityImpact({
1316
+ nodeId: typeof args.nodeId === "string" ? args.nodeId : "",
1317
+ topicId
1318
+ })
1319
+ );
1320
+ }
1321
+ };
1322
+
1323
+ // ../../apps/mcp-server/src/handlers/topics.ts
1324
+ var topicHandlers = {
1325
+ async create_topic(args, ctx) {
1326
+ return formatSdkResult(
1327
+ await getSdkClient(ctx).topics.create({
1328
+ name: readString(args.name) ?? "",
1329
+ description: readString(args.description),
1330
+ type: readString(args.type),
1331
+ parentTopicId: readString(args.parentTopicId),
1332
+ ontologyId: readString(args.ontologyId),
1333
+ tenantId: readString(args.tenantId),
1334
+ workspaceId: readString(args.workspaceId),
1335
+ visibility: readString(args.visibility),
1336
+ createdBy: readString(args.createdBy)
1337
+ })
1338
+ );
1339
+ },
1340
+ async list_topics(args, ctx) {
1341
+ return formatSdkResult(
1342
+ await getSdkClient(ctx).topics.list({
1343
+ ontologyId: readString(args.ontologyId),
1344
+ parentTopicId: readString(args.parentTopicId),
1345
+ status: readString(args.status),
1346
+ type: readString(args.type)
1347
+ })
1348
+ );
1349
+ },
1350
+ async get_topic(args, ctx) {
1351
+ return formatSdkResult(
1352
+ await getSdkClient(ctx).topics.get(
1353
+ readString(args.topicId ?? args.id) ?? ""
1354
+ )
1355
+ );
1356
+ },
1357
+ async update_topic(args, ctx) {
1358
+ const topicId = readString(args.topicId ?? args.id) ?? "";
1359
+ if (!topicId) {
1360
+ throw new Error("topicId is required.");
1361
+ }
1362
+ return formatSdkResult(
1363
+ await getSdkClient(ctx).topics.update(topicId, {
1364
+ name: readString(args.name),
1365
+ description: readString(args.description),
1366
+ type: readString(args.type),
1367
+ ontologyId: readString(args.ontologyId),
1368
+ clearOntologyId: readBoolean(args.clearOntologyId),
1369
+ status: readString(args.status),
1370
+ visibility: readString(args.visibility)
1371
+ })
1372
+ );
1373
+ },
1374
+ async get_topic_tree(args, ctx) {
1375
+ return formatSdkResult(
1376
+ await getSdkClient(ctx).topics.getTree({
1377
+ rootId: readString(args.rootId ?? args.topicId ?? args.id) ?? "",
1378
+ maxDepth: readNumber(args.maxDepth)
1379
+ })
1380
+ );
1381
+ },
1382
+ async get_topic_coverage(args, ctx) {
1383
+ return formatSdkResult(
1384
+ await getSdkClient(ctx).topics.coverage(
1385
+ readString(args.topicId ?? args.id) ?? "",
1386
+ {
1387
+ includeDescendants: readBoolean(args.includeDescendants),
1388
+ maxDepth: readNumber(args.maxDepth)
1389
+ }
1390
+ )
1391
+ );
1392
+ }
1393
+ };
1394
+
1395
+ // ../../apps/mcp-server/src/handlers/coverage.ts
1396
+ var coverageHandlers = {
1397
+ async get_topic_coverage(args, ctx) {
1398
+ return topicHandlers.get_topic_coverage(
1399
+ {
1400
+ topicId: args.topicId ?? args.id,
1401
+ includeDescendants: args.includeDescendants,
1402
+ maxDepth: args.maxDepth
1403
+ },
1404
+ ctx
1405
+ );
1406
+ },
1407
+ async get_graph_gaps(args, ctx) {
1408
+ return graphHandlers.get_graph_gaps(
1409
+ {
1410
+ topicId: args.topicId ?? args.projectId,
1411
+ minConfidence: args.minConfidence
1412
+ },
1413
+ ctx
1414
+ );
1415
+ }
1416
+ };
1417
+
1418
+ // ../../apps/mcp-server/src/handlers/discovery.ts
1419
+ var discoveryHandlers = {
1420
+ async discover(args, ctx) {
1421
+ return formatSdkResult(
1422
+ await getSdkClient(ctx).context.discover({
1423
+ query: readString(args.query) ?? "",
1424
+ topK: readNumber(args.topK),
1425
+ includeNeighborhood: readBoolean(args.includeNeighborhood)
1426
+ })
1427
+ );
1428
+ }
1429
+ };
1430
+
1431
+ // ../../apps/mcp-server/src/handlers/engineering-verification.ts
1432
+ function hasVerificationPayload(args) {
1433
+ return args.testOutput !== void 0 || args.tscOutput !== void 0 || args.lintOutput !== void 0 || args.sentryData !== void 0;
1434
+ }
1435
+ var engineeringVerificationHandlers = {
1436
+ async evaluate_engineering_contract(args, ctx) {
1437
+ if (!hasVerificationPayload(args)) {
1438
+ throw new Error(
1439
+ "evaluate_engineering_contract requires at least one verification payload."
1440
+ );
1441
+ }
1442
+ const result = await adminMutation(
1443
+ "epistemicContracts:evaluateEngineeringContracts",
1444
+ {
1445
+ beliefNodeId: args.beliefNodeId,
1446
+ trigger: args.trigger,
1447
+ testOutput: args.testOutput,
1448
+ tscOutput: args.tscOutput,
1449
+ lintOutput: args.lintOutput,
1450
+ sentryData: args.sentryData,
1451
+ authenticatedUserId: ctx.userId
1452
+ }
1453
+ );
1454
+ return result;
1455
+ }
1456
+ };
1457
+
1458
+ // ../../apps/mcp-server/src/handlers/evidence.ts
1459
+ var evidenceHandlers = {
1460
+ async create_evidence(args, ctx) {
1461
+ return formatSdkResult(
1462
+ await getSdkClient(ctx).evidence.create({
1463
+ topicId: readString(readTopicIdArg(args)) ?? "",
1464
+ text: readString(args.text) ?? "",
1465
+ source: readString(args.source),
1466
+ targetId: readString(args.targetId),
1467
+ weight: readNumber(args.weight),
1468
+ metadata: asJsonObject(args.metadata),
1469
+ title: readString(args.title),
1470
+ content: readString(args.content),
1471
+ contentType: readString(args.contentType),
1472
+ kind: readString(args.kind)
1473
+ })
1474
+ );
1475
+ },
1476
+ async get_evidence(args, ctx) {
1477
+ return formatSdkResult(
1478
+ await getSdkClient(ctx).evidence.get(
1479
+ readString(args.id ?? args.evidenceId) ?? ""
1480
+ )
1481
+ );
1482
+ },
1483
+ async list_evidence(args, ctx) {
1484
+ return formatSdkResult(
1485
+ await getSdkClient(ctx).evidence.list({
1486
+ topicId: readString(readTopicIdArg(args)),
1487
+ targetId: readString(args.targetId),
1488
+ limit: readNumber(args.limit),
1489
+ cursor: readString(args.cursor)
1490
+ })
1491
+ );
1492
+ },
1493
+ async link_evidence(args, ctx) {
1494
+ return formatSdkResult(
1495
+ await getSdkClient(ctx).evidence.link({
1496
+ evidenceId: readString(args.evidenceId) ?? "",
1497
+ targetId: readString(args.targetId ?? args.beliefId ?? args.questionId) ?? "",
1498
+ targetType: readString(args.targetType),
1499
+ weight: readNumber(args.weight ?? args.relevance),
1500
+ rationale: readString(args.rationale)
1501
+ })
1502
+ );
1503
+ },
1504
+ async search_evidence(args, ctx) {
1505
+ return formatSdkResult(
1506
+ await getSdkClient(ctx).evidence.search({
1507
+ q: readString(args.q ?? args.query) ?? "",
1508
+ topicId: readString(readTopicIdArg(args)),
1509
+ targetId: readString(args.targetId),
1510
+ limit: readNumber(args.limit),
1511
+ cursor: readString(args.cursor)
1512
+ })
1513
+ );
1514
+ },
1515
+ async add_evidence(args, ctx) {
1516
+ return formatSdkResult(
1517
+ await getSdkClient(ctx).evidence.add({
1518
+ topicId: readString(readTopicIdArg(args)) ?? "",
1519
+ text: readString(args.text ?? args.canonicalText) ?? "",
1520
+ source: readString(args.source ?? args.sourceUrl),
1521
+ targetId: readString(args.targetId ?? args.targetNodeId),
1522
+ weight: readNumber(args.weight),
1523
+ metadata: {
1524
+ ...asRecord(args.metadata),
1525
+ ...readString(args.reasoning) ? { rationale: readString(args.reasoning) } : {}
1526
+ },
1527
+ title: readString(args.title),
1528
+ content: readString(args.content),
1529
+ contentType: readString(args.contentType),
1530
+ kind: readString(args.kind)
1531
+ })
1532
+ );
1533
+ },
1534
+ async link_evidence_to_belief(args, ctx) {
1535
+ return formatSdkResult(
1536
+ await getSdkClient(ctx).evidence.linkToBelief({
1537
+ evidenceId: readString(args.evidenceId) ?? "",
1538
+ beliefId: readString(args.beliefId) ?? "",
1539
+ weight: readNumber(args.weight) ?? 1,
1540
+ rationale: readString(args.rationale)
1541
+ })
1542
+ );
1543
+ }
1544
+ };
1545
+
1546
+ // ../../apps/mcp-server/src/handlers/identity.ts
1547
+ var identityHandlers = {
1548
+ async identity_whoami(_args, ctx) {
1549
+ return formatSdkResult(await getSdkClient(ctx).identity.whoami());
1550
+ }
1551
+ };
1552
+
1553
+ // ../../apps/mcp-server/src/handlers/intelligence.ts
1554
+ var intelligenceHandlers = {
1555
+ detect_confirmation_bias: graphHandlers.detect_confirmation_bias,
1556
+ get_graph_structure_analysis: graphHandlers.get_graph_structure_analysis,
1557
+ get_falsification_questions: graphHandlers.get_falsification_questions
1558
+ };
1559
+
1560
+ // ../../apps/mcp-server/src/handlers/judgments.ts
1561
+ var judgmentHandlers = {
1562
+ async record_judgment(args, ctx) {
1563
+ const topicId = await resolveTopicScopeId(
1564
+ readTopicIdArg(args),
1565
+ "record_judgment"
1566
+ );
1567
+ if (topicId === ROOT_TOPIC_ID) {
1568
+ throw new Error(
1569
+ "[record_judgment] Resolved topic is Root \u2014 epistemic nodes must belong to a child topic. Provide a valid topicId for this judgment."
1570
+ );
1571
+ }
1572
+ return formatSdkResult(
1573
+ await getSdkClient(ctx).judgments.record({
1574
+ title: readString(args.title) ?? "",
1575
+ rationale: readString(args.rationale) ?? "",
1576
+ topicId,
1577
+ confidence: readNumber(args.confidence) ?? 0.7,
1578
+ beliefIds: readStringArray(args.beliefIds)
1579
+ })
1580
+ );
1581
+ }
1582
+ };
1583
+
1584
+ // ../../apps/mcp-server/src/handlers/lenses.ts
1585
+ function readWorkspaceIdArg(args) {
1586
+ return readString(args.workspaceId);
1587
+ }
1588
+ var lensHandlers = {
1589
+ async create_lens(args, ctx) {
1590
+ const filterCriteria = args.filterCriteria && typeof args.filterCriteria === "object" ? args.filterCriteria : void 0;
1591
+ if (filterCriteria !== void 0) {
1592
+ const validation = validateFilterCriteria(filterCriteria);
1593
+ if (!validation.valid) {
1594
+ throw new Error(
1595
+ `Invalid filterCriteria: ${validation.errors.join("; ")}`
1596
+ );
1597
+ }
1598
+ }
1599
+ return formatSdkResult(
1600
+ await getSdkClient(ctx).worktrees.createLens({
1601
+ name: readString(args.name) ?? "",
1602
+ topicId: readTopicIdArg(args),
1603
+ workspaceId: readWorkspaceIdArg(args),
1604
+ description: readString(args.description),
1605
+ perspectiveType: readString(args.perspectiveType),
1606
+ promptTemplates: Array.isArray(args.promptTemplates) ? args.promptTemplates : void 0,
1607
+ workflowTemplates: Array.isArray(args.workflowTemplates) ? args.workflowTemplates : void 0,
1608
+ taskTemplates: Array.isArray(args.taskTemplates) ? args.taskTemplates : void 0,
1609
+ questionTemplates: Array.isArray(args.questionTemplates) ? args.questionTemplates : void 0,
1610
+ filterCriteria
1611
+ })
1612
+ );
1613
+ },
1614
+ async list_lenses(args, ctx) {
1615
+ try {
1616
+ return formatSdkResult(
1617
+ await getSdkClient(ctx).worktrees.listLenses({
1618
+ workspaceId: readWorkspaceIdArg(args),
1619
+ topicId: readTopicIdArg(args),
1620
+ status: readString(args.status),
1621
+ perspectiveType: readString(args.perspectiveType)
1622
+ })
1623
+ );
1624
+ } catch (error) {
1625
+ if (error instanceof Error && error.message.includes(
1626
+ "workspaceId is required unless topicId resolves to a workspace-scoped topic"
1627
+ )) {
1628
+ return {
1629
+ lenses: [],
1630
+ note: "workspaceId is required unless topicId resolves to a workspace-scoped topic"
1631
+ };
1632
+ }
1633
+ throw error;
1634
+ }
1635
+ },
1636
+ async apply_lens_to_topic(args, ctx) {
1637
+ const topicId = readTopicIdArg(args);
1638
+ if (!topicId) {
1639
+ throw new Error("topicId is required");
1640
+ }
1641
+ return formatSdkResult(
1642
+ await getSdkClient(ctx).worktrees.applyLensToTopic({
1643
+ lensId: readString(args.lensId) ?? "",
1644
+ topicId,
1645
+ metadata: args.metadata && typeof args.metadata === "object" ? args.metadata : void 0
1646
+ })
1647
+ );
1648
+ },
1649
+ async remove_lens_from_topic(args, ctx) {
1650
+ const topicId = readTopicIdArg(args);
1651
+ if (!topicId) {
1652
+ throw new Error("topicId is required");
1653
+ }
1654
+ return formatSdkResult(
1655
+ await getSdkClient(ctx).worktrees.removeLensFromTopic({
1656
+ lensId: readString(args.lensId) ?? "",
1657
+ topicId
1658
+ })
1659
+ );
1660
+ }
1661
+ };
1662
+
1663
+ // ../../apps/mcp-server/src/handlers/lineage.ts
1664
+ var lineageHandlers = {
1665
+ async query_lineage(args, ctx) {
1666
+ return formatSdkResult(
1667
+ await getSdkClient(ctx).graph.queryLineage(
1668
+ readString(args.id ?? args.nodeId ?? args.beliefId) ?? ""
1669
+ )
1670
+ );
1671
+ },
1672
+ async get_confidence_history(args, ctx) {
1673
+ return formatSdkResult(
1674
+ await getSdkClient(ctx).graph.getConfidenceHistory(
1675
+ readString(args.id ?? args.nodeId ?? args.beliefId) ?? ""
1676
+ )
1677
+ );
1678
+ },
1679
+ async get_audit_trail(args, ctx) {
1680
+ return formatSdkResult(
1681
+ await getSdkClient(ctx).graph.getAuditTrail(
1682
+ args.nodeId,
1683
+ args.limit ?? 50
1684
+ )
1685
+ );
1686
+ }
1687
+ };
1688
+
1689
+ // ../../apps/mcp-server/src/handlers/observations.ts
1690
+ var observationStore = /* @__PURE__ */ new Map();
1691
+ function tokenize(input) {
1692
+ return input.toLowerCase().split(/[^a-z0-9]+/).map((token) => token.trim()).filter(Boolean);
1693
+ }
1694
+ function scoreSemanticMatch(record, query) {
1695
+ const queryTokens = new Set(tokenize(query));
1696
+ if (queryTokens.size === 0) {
1697
+ return 0;
1698
+ }
1699
+ const haystack = [record.summary, record.source || "", ...record.tags || []].join(" ").toLowerCase();
1700
+ let score = 0;
1701
+ for (const token of queryTokens) {
1702
+ if (haystack.includes(token)) {
1703
+ score += 1;
1704
+ }
1705
+ }
1706
+ return score;
1707
+ }
1708
+ var observationHandlers = {
1709
+ async ingest_observation(args, _ctx) {
1710
+ const topicId = await resolveTopicScopeId(
1711
+ readTopicIdArg(args),
1712
+ "ingest_observation"
1713
+ );
1714
+ const observationType = args.observationType;
1715
+ const summary = args.summary;
1716
+ const source = args.source || void 0;
1717
+ const confidence = args.confidence || void 0;
1718
+ const tags = (args.tags || []).filter(
1719
+ (tag) => typeof tag === "string" && tag.trim().length > 0
1720
+ );
1721
+ const metadata = args.metadata || void 0;
1722
+ const createdAt = Date.now();
1723
+ const observationId = typeof crypto !== "undefined" && "randomUUID" in crypto ? crypto.randomUUID() : `obs_${createdAt}_${Math.random().toString(36).slice(2)}`;
1724
+ const record = {
1725
+ observationId,
1726
+ topicId,
1727
+ observationType,
1728
+ summary,
1729
+ source,
1730
+ confidence,
1731
+ tags,
1732
+ metadata,
1733
+ createdAt
1734
+ };
1735
+ const existing = observationStore.get(topicId) || [];
1736
+ existing.push(record);
1737
+ observationStore.set(topicId, existing.slice(-500));
1738
+ return {
1739
+ observationId,
1740
+ topicId,
1741
+ observationType,
1742
+ createdAt,
1743
+ contextResourceUri: `lucern://observations/${topicId}`
1744
+ };
1745
+ },
1746
+ async get_observation_context(args, _ctx) {
1747
+ const topicId = await resolveTopicScopeId(
1748
+ readTopicIdArg(args),
1749
+ "get_observation_context"
1750
+ );
1751
+ const query = args.query || "";
1752
+ const limit = Math.max(1, Math.min(args.limit || 25, 200));
1753
+ const records = observationStore.get(topicId) || [];
1754
+ const latest = records.slice(-limit).reverse();
1755
+ const semanticMatches = query ? records.map((record) => ({
1756
+ record,
1757
+ score: scoreSemanticMatch(record, query)
1758
+ })).filter((row) => row.score > 0).sort((a, b) => b.score - a.score).slice(0, limit).map((row) => row.record) : [];
1759
+ const byType = {};
1760
+ for (const row of records) {
1761
+ byType[row.observationType] = (byType[row.observationType] || 0) + 1;
1762
+ }
1763
+ return {
1764
+ topicId,
1765
+ totalObservations: records.length,
1766
+ latest,
1767
+ semanticMatches,
1768
+ byType,
1769
+ generatedAt: Date.now()
1770
+ };
1771
+ }
1772
+ };
1773
+
1774
+ // ../../apps/mcp-server/src/handlers/ontologies.ts
1775
+ var ontologyHandlers = {
1776
+ async list_ontologies(args, ctx) {
1777
+ return formatSdkResult(
1778
+ await getSdkClient(ctx).ontologies.list({
1779
+ tenantId: readString(args.tenantId),
1780
+ tier: readString(args.tier),
1781
+ status: readString(args.status)
1782
+ })
1783
+ );
1784
+ },
1785
+ async get_ontology(args, ctx) {
1786
+ return formatSdkResult(
1787
+ await getSdkClient(ctx).ontologies.get({
1788
+ id: readString(args.id ?? args.ontologyId),
1789
+ ontologyKey: readString(args.ontologyKey),
1790
+ tenantId: readString(args.tenantId),
1791
+ tier: readString(args.tier),
1792
+ status: readString(args.status)
1793
+ })
1794
+ );
1795
+ },
1796
+ async apply_ontology(args, ctx) {
1797
+ return formatSdkResult(
1798
+ await getSdkClient(ctx).ontologies.bind({
1799
+ ontologyId: readString(args.ontologyId ?? args.id) ?? "",
1800
+ topicId: readString(args.topicId) ?? ""
1801
+ })
1802
+ );
1803
+ },
1804
+ async match_entity_type(args, ctx) {
1805
+ return formatSdkResult(
1806
+ await getSdkClient(ctx).ontologies.match({
1807
+ text: readString(args.text) ?? "",
1808
+ topicId: readString(args.topicId),
1809
+ ontologyId: readString(args.ontologyId),
1810
+ minScore: readNumber(args.minScore),
1811
+ limit: readNumber(args.limit)
1812
+ })
1813
+ );
1814
+ },
1815
+ async create_ontology(args, ctx) {
1816
+ return formatSdkResult(
1817
+ await getSdkClient(ctx).ontologies.create({
1818
+ ontologyKey: readString(args.ontologyKey) ?? "",
1819
+ name: readString(args.name) ?? "",
1820
+ description: readString(args.description),
1821
+ tenantId: readString(args.tenantId),
1822
+ tier: readString(args.tier) ?? "platform",
1823
+ parentOntologyId: readString(args.parentOntologyId)
1824
+ })
1825
+ );
1826
+ },
1827
+ async update_ontology(args, ctx) {
1828
+ return formatSdkResult(
1829
+ await getSdkClient(ctx).ontologies.update({
1830
+ id: readString(args.id) ?? "",
1831
+ name: readString(args.name),
1832
+ description: readString(args.description),
1833
+ status: readString(args.status)
1834
+ })
1835
+ );
1836
+ },
1837
+ async archive_ontology(args, ctx) {
1838
+ return formatSdkResult(
1839
+ await getSdkClient(ctx).ontologies.archive({
1840
+ id: readString(args.id) ?? ""
1841
+ })
1842
+ );
1843
+ },
1844
+ async create_ontology_version(args, ctx) {
1845
+ return formatSdkResult(
1846
+ await getSdkClient(ctx).ontologies.createVersion({
1847
+ ontologyId: readString(args.ontologyId) ?? "",
1848
+ version: readString(args.version) ?? "",
1849
+ entityTypes: Array.isArray(args.entityTypes) ? args.entityTypes : [],
1850
+ edgeTypes: Array.isArray(args.edgeTypes) ? args.edgeTypes : [],
1851
+ releaseNotes: readString(args.releaseNotes)
1852
+ })
1853
+ );
1854
+ },
1855
+ async publish_ontology_version(args, ctx) {
1856
+ return formatSdkResult(
1857
+ await getSdkClient(ctx).ontologies.publishVersion({
1858
+ id: readString(args.id) ?? ""
1859
+ })
1860
+ );
1861
+ },
1862
+ async deprecate_ontology_version(args, ctx) {
1863
+ return formatSdkResult(
1864
+ await getSdkClient(ctx).ontologies.deprecateVersion({
1865
+ id: readString(args.id) ?? ""
1866
+ })
1867
+ );
1868
+ },
1869
+ async resolve_effective_ontology(args, ctx) {
1870
+ return formatSdkResult(
1871
+ await getSdkClient(ctx).ontologies.resolveEffective({
1872
+ ontologyId: readString(args.ontologyId) ?? ""
1873
+ })
1874
+ );
1875
+ }
1876
+ };
1877
+
1878
+ // ../../apps/mcp-server/src/handlers/ontology-matching.ts
1879
+ var ontologyMatchingHandlers = {
1880
+ async match_entity_type(args, ctx) {
1881
+ return ontologyHandlers.match_entity_type(args, ctx);
1882
+ },
1883
+ async discover_entity_connections(args, ctx) {
1884
+ return formatSdkResult(
1885
+ await getSdkClient(ctx).context.discoverEntityConnections({
1886
+ nodeId: readString(args.nodeId) ?? "",
1887
+ topicId: readString(args.topicId),
1888
+ minScore: readNumber(args.minScore),
1889
+ limit: readNumber(args.limit)
1890
+ })
1891
+ );
1892
+ },
1893
+ async trigger_belief_review(args, ctx) {
1894
+ return formatSdkResult(
1895
+ await getSdkClient(ctx).context.triggerBeliefReview({
1896
+ entityNodeId: readString(args.entityNodeId) ?? "",
1897
+ changeDescription: readString(args.changeDescription),
1898
+ maxQuestions: readNumber(args.maxQuestions)
1899
+ })
1900
+ );
1901
+ }
1902
+ };
1903
+
1904
+ // ../../apps/mcp-server/src/handlers/policy.ts
1905
+ var policyHandlers = {
1906
+ async check_permission(args, ctx) {
1907
+ return formatSdkResult(
1908
+ await getSdkClient(ctx).policy.checkPermission(args)
1909
+ );
1910
+ },
1911
+ async filter_by_permission(args, ctx) {
1912
+ return formatSdkResult(
1913
+ await getSdkClient(ctx).policy.filterByPermission(args)
1914
+ );
1915
+ },
1916
+ async manage_write_policy(args, ctx) {
1917
+ return formatSdkResult(
1918
+ await getSdkClient(ctx).policy.manageWritePolicy(args)
1919
+ );
1920
+ }
1921
+ };
1922
+
1923
+ // ../../apps/mcp-server/src/handlers/questions.ts
1924
+ var questionHandlers = {
1925
+ async create_question(args, ctx) {
1926
+ return formatSdkResult(
1927
+ await getSdkClient(ctx).questions.create({
1928
+ topicId: readString(args.topicId) ?? "",
1929
+ text: readString(args.text) ?? "",
1930
+ priority: readString(args.priority),
1931
+ linkedBeliefId: readString(args.linkedBeliefId),
1932
+ metadata: asRecord(args.metadata)
1933
+ })
1934
+ );
1935
+ },
1936
+ async get_question(args, ctx) {
1937
+ return formatSdkResult(
1938
+ await getSdkClient(ctx).questions.get(
1939
+ readString(args.id ?? args.questionId) ?? ""
1940
+ )
1941
+ );
1942
+ },
1943
+ async list_questions(args, ctx) {
1944
+ return formatSdkResult(
1945
+ await getSdkClient(ctx).questions.list({
1946
+ topicId: readString(args.topicId),
1947
+ status: readString(args.status),
1948
+ priority: readString(args.priority),
1949
+ worktreeId: readString(args.worktreeId),
1950
+ limit: readNumber(args.limit),
1951
+ cursor: readString(args.cursor)
1952
+ })
1953
+ );
1954
+ },
1955
+ async answer_question(args, ctx) {
1956
+ return formatSdkResult(
1957
+ await getSdkClient(ctx).questions.answer(
1958
+ readString(args.id ?? args.questionId) ?? "",
1959
+ {
1960
+ text: readString(args.text) ?? "",
1961
+ confidence: readString(args.confidence),
1962
+ evidenceIds: readStringArray(args.evidenceIds),
1963
+ rationale: readString(args.rationale)
1964
+ }
1965
+ )
1966
+ );
1967
+ },
1968
+ async refine_question(args, ctx) {
1969
+ return formatSdkResult(
1970
+ await getSdkClient(ctx).questions.refine(
1971
+ readString(args.id ?? args.questionId) ?? "",
1972
+ readString(args.text) ?? "",
1973
+ readString(args.rationale ?? args.refinementReason)
1974
+ )
1975
+ );
1976
+ },
1977
+ async update_question_status(args, ctx) {
1978
+ return formatSdkResult(
1979
+ await getSdkClient(ctx).questions.updateStatus(
1980
+ readString(args.id ?? args.questionId) ?? "",
1981
+ readString(args.status) ?? "",
1982
+ readString(args.rationale)
1983
+ )
1984
+ );
1985
+ },
1986
+ async archive_question(args, ctx) {
1987
+ return formatSdkResult(
1988
+ await getSdkClient(ctx).questions.archive(
1989
+ readString(args.id ?? args.questionId) ?? "",
1990
+ readString(args.reason ?? args.rationale)
1991
+ )
1992
+ );
1993
+ },
1994
+ async link_evidence_to_question(args, ctx) {
1995
+ const result = await evidenceHandlers.link_evidence(
1996
+ {
1997
+ evidenceId: readString(args.evidenceId) ?? "",
1998
+ targetId: readString(args.questionId) ?? "",
1999
+ weight: readNumber(args.relevance),
2000
+ rationale: readString(args.rationale)
2001
+ },
2002
+ ctx
2003
+ );
2004
+ return {
2005
+ ...result,
2006
+ questionId: readString(args.questionId) ?? result.targetId,
2007
+ relevance: readNumber(args.relevance)
2008
+ };
2009
+ },
2010
+ async get_high_priority_questions(args, ctx) {
2011
+ return formatSdkResult(
2012
+ await getSdkClient(ctx).questions.getHighPriority({
2013
+ topicId: readString(args.topicId),
2014
+ limit: readNumber(args.limit),
2015
+ includeAnswered: readBoolean(args.includeAnswered)
2016
+ })
2017
+ );
2018
+ },
2019
+ async find_missing_questions(args, ctx) {
2020
+ return formatSdkResult(
2021
+ await getSdkClient(ctx).questions.findMissing({
2022
+ topicId: readString(args.topicId) ?? "",
2023
+ minConfidence: readNumber(args.minConfidence)
2024
+ })
2025
+ );
2026
+ }
2027
+ };
2028
+
2029
+ // ../../apps/mcp-server/src/handlers/research.ts
2030
+ var researchHandlers = {
2031
+ async search_sources(args, ctx) {
2032
+ return formatSdkResult(await getSdkClient(ctx).research.searchSources(args));
2033
+ },
2034
+ async execute_deep_research(args, ctx) {
2035
+ return formatSdkResult(
2036
+ await getSdkClient(ctx).research.executeDeepResearch(args)
2037
+ );
2038
+ }
2039
+ };
2040
+
2041
+ // ../../apps/mcp-server/src/handlers/research-verification.ts
2042
+ function buildInputData(args) {
2043
+ const entries = Object.entries({
2044
+ metricData: args.metricData,
2045
+ referenceCheckData: args.referenceCheckData,
2046
+ marketIndexData: args.marketIndexData,
2047
+ temporalData: args.temporalData
2048
+ }).filter(([, value]) => value !== void 0);
2049
+ return entries.length > 0 ? Object.fromEntries(entries) : void 0;
2050
+ }
2051
+ var researchVerificationHandlers = {
2052
+ async evaluate_research_contract(args, ctx) {
2053
+ const inputData = buildInputData(args);
2054
+ const result = await adminMutation(
2055
+ api2.epistemicContracts.evaluateContractsForTrigger,
2056
+ {
2057
+ beliefNodeId: args.beliefNodeId,
2058
+ trigger: typeof args.trigger === "string" && args.trigger.length > 0 ? args.trigger : "event_driven",
2059
+ ...inputData ? { inputData } : {},
2060
+ authenticatedUserId: ctx.userId
2061
+ }
2062
+ );
2063
+ return result;
2064
+ }
2065
+ };
2066
+
2067
+ // ../server-core/src/domain/context/compile.ts
2068
+ function cleanString(value) {
2069
+ return typeof value === "string" && value.trim().length > 0 ? value.trim() : void 0;
2070
+ }
2071
+ function prefixId(prefix, value) {
2072
+ const cleaned = cleanString(value);
2073
+ if (!cleaned) {
2074
+ return `${prefix}_unknown`;
2075
+ }
2076
+ try {
2077
+ const decoded = decodePrefixedId(cleaned);
2078
+ if (decoded.prefix === prefix) {
2079
+ return cleaned;
2080
+ }
2081
+ } catch {
2082
+ }
2083
+ return encodePrefixedId(prefix, cleaned);
2084
+ }
2085
+ function mapSelectedIds(value) {
2086
+ return {
2087
+ invariants: (value.invariants ?? []).map((id) => prefixId("bel", id)),
2088
+ activeBeliefs: (value.activeBeliefs ?? []).map((id) => prefixId("bel", id)),
2089
+ openQuestions: (value.openQuestions ?? []).map((id) => prefixId("que", id)),
2090
+ recentEvidence: (value.recentEvidence ?? []).map((id) => prefixId("evi", id)),
2091
+ contradictions: (value.contradictions ?? []).map((id) => prefixId("con", id))
2092
+ };
2093
+ }
2094
+ function mapExcludedId(section, id) {
2095
+ if (section === "invariants" || section === "activeBeliefs") {
2096
+ return prefixId("bel", id);
2097
+ }
2098
+ if (section === "openQuestions") {
2099
+ return prefixId("que", id);
2100
+ }
2101
+ if (section === "recentEvidence") {
2102
+ return prefixId("evi", id);
2103
+ }
2104
+ if (section === "contradictions") {
2105
+ return prefixId("con", id);
2106
+ }
2107
+ return id;
2108
+ }
2109
+ function toPublicCompiledContext(pack) {
2110
+ return {
2111
+ schemaVersion: pack.schemaVersion,
2112
+ topicId: prefixId("top", pack.topicId),
2113
+ topicName: pack.topicName,
2114
+ scopedTopicIds: (pack.scopedTopicIds ?? []).map((id) => prefixId("top", id)),
2115
+ generatedAt: pack.generatedAt,
2116
+ ranking: pack.rankingProfile,
2117
+ summary: pack.summary,
2118
+ invariants: (pack.invariants ?? []).map((belief) => ({
2119
+ beliefId: prefixId("bel", belief.nodeId),
2120
+ text: belief.canonicalText,
2121
+ confidence: belief.confidence ?? null,
2122
+ beliefType: belief.beliefType ?? null,
2123
+ score: belief.score,
2124
+ ...belief.justification ? { justification: belief.justification } : {}
2125
+ })),
2126
+ activeBeliefs: (pack.activeBeliefs ?? []).map((belief) => ({
2127
+ beliefId: prefixId("bel", belief.nodeId),
2128
+ text: belief.canonicalText,
2129
+ confidence: belief.confidence ?? null,
2130
+ beliefType: belief.beliefType ?? null,
2131
+ status: belief.status,
2132
+ updatedAt: belief.updatedAt ?? null,
2133
+ score: belief.score,
2134
+ ...belief.justification ? { justification: belief.justification } : {}
2135
+ })),
2136
+ openQuestions: (pack.openQuestions ?? []).map((question) => ({
2137
+ questionId: prefixId("que", question.questionId),
2138
+ text: question.text,
2139
+ status: question.status,
2140
+ priority: question.priority,
2141
+ updatedAt: question.updatedAt ?? null,
2142
+ score: question.score,
2143
+ ...question.justification ? { justification: question.justification } : {}
2144
+ })),
2145
+ recentEvidence: (pack.recentEvidence ?? []).map((evidence) => ({
2146
+ evidenceId: prefixId("evi", evidence.nodeId),
2147
+ text: evidence.canonicalText,
2148
+ kind: evidence.kind,
2149
+ sourceUrl: evidence.sourceUrl ?? null,
2150
+ createdAt: evidence.createdAt ?? null,
2151
+ score: evidence.score,
2152
+ ...evidence.justification ? { justification: evidence.justification } : {}
2153
+ })),
2154
+ contradictions: (pack.contradictions ?? []).map((contradiction) => ({
2155
+ contradictionId: prefixId("con", contradiction.contradictionId),
2156
+ severity: contradiction.severity,
2157
+ status: contradiction.status,
2158
+ description: contradiction.description,
2159
+ score: contradiction.score,
2160
+ ...contradiction.justification ? { justification: contradiction.justification } : {}
2161
+ })),
2162
+ ...pack.relatedEntities ? {
2163
+ relatedEntities: pack.relatedEntities.map((entity) => ({
2164
+ entityId: cleanString(entity.nodeId) ?? "",
2165
+ entityType: entity.entityType,
2166
+ title: entity.title,
2167
+ text: cleanString(entity.canonicalText),
2168
+ connectedBeliefCount: entity.connectedBeliefCount,
2169
+ connectedEvidenceCount: entity.connectedEvidenceCount,
2170
+ score: entity.score,
2171
+ ...entity.metadata ? { metadata: entity.metadata } : {}
2172
+ }))
2173
+ } : {},
2174
+ contextNarrative: pack.contextNarrative ?? [],
2175
+ injectionPolicy: {
2176
+ tokenBudget: pack.injectionPolicy.tokenBudget,
2177
+ estimatedTokens: pack.injectionPolicy.estimatedTokens,
2178
+ sectionBudgets: pack.injectionPolicy.sectionBudgets,
2179
+ sectionUsage: pack.injectionPolicy.sectionUsage,
2180
+ selected: mapSelectedIds(pack.injectionPolicy.selected),
2181
+ ...pack.injectionPolicy.excludedItems ? {
2182
+ excludedItems: pack.injectionPolicy.excludedItems.map((item) => ({
2183
+ ...item,
2184
+ id: mapExcludedId(item.section, item.id)
2185
+ }))
2186
+ } : {}
2187
+ },
2188
+ diagnostics: pack.diagnostics,
2189
+ ...pack.compilationMode ? { compilationMode: pack.compilationMode } : {},
2190
+ ...pack.failureContext ? {
2191
+ failureContext: {
2192
+ failures: pack.failureContext.failures.map((failure) => ({
2193
+ ...failure,
2194
+ attemptId: prefixId("evi", failure.attemptId)
2195
+ })),
2196
+ suppressedIds: pack.failureContext.suppressedIds.map(
2197
+ (id) => prefixId("evi", id)
2198
+ )
2199
+ }
2200
+ } : {},
2201
+ ...pack.deltaReport ? {
2202
+ deltaReport: {
2203
+ changedItems: pack.deltaReport.changedItems.map((item) => ({
2204
+ ...item,
2205
+ id: mapExcludedId(item.section, item.id)
2206
+ })),
2207
+ verificationObligations: pack.deltaReport.verificationObligations,
2208
+ referencePoint: prefixId("wt", pack.deltaReport.referencePoint)
2209
+ }
2210
+ } : {},
2211
+ ...pack.appliedWeightOverrides ? { appliedWeightOverrides: pack.appliedWeightOverrides } : {}
2212
+ };
2213
+ }
2214
+
2215
+ // ../../apps/mcp-server/src/handlers/scope-context.ts
2216
+ var scopeContextHandlers = {
2217
+ async compile_context(args, ctx) {
2218
+ const requestedScope = readTopicIdArg(args);
2219
+ if (!requestedScope) {
2220
+ throw new Error("[compile_context] topicId is required.");
2221
+ }
2222
+ const topicId = await resolveTopicScopeId(requestedScope, "compile_context");
2223
+ if (ctx.sessionType === "user" && Array.isArray(ctx.allowedTopics) && (!ctx.allowedTopics.includes(topicId) || ctx.allowedTopics.length === 0)) {
2224
+ throw new Error(
2225
+ `[compile_context] Access denied to compile context for topic ${topicId}.`
2226
+ );
2227
+ }
2228
+ const compiled = formatSdkResult(
2229
+ await getSdkClient(ctx).context.compile(topicId, {
2230
+ query: readString(args.query),
2231
+ budget: readNumber(args.budget ?? args.tokenBudget),
2232
+ ranking: readString(args.ranking ?? args.rankingProfile),
2233
+ limit: readNumber(args.limit),
2234
+ maxDepth: readNumber(args.maxDepth),
2235
+ includeEntities: readBoolean(args.includeEntities),
2236
+ mode: readString(args.mode),
2237
+ includeFailures: readBoolean(args.includeFailures),
2238
+ worktreeId: readString(args.worktreeId),
2239
+ sessionId: readString(args.sessionId),
2240
+ packWeightOverrides: Array.isArray(args.packWeightOverrides) ? args.packWeightOverrides : void 0
2241
+ })
2242
+ );
2243
+ return toPublicCompiledContext(compiled);
2244
+ },
2245
+ async record_scope_learning(args, ctx) {
2246
+ return formatSdkResult(
2247
+ await getSdkClient(ctx).context.recordScopeLearning(args)
2248
+ );
2249
+ },
2250
+ async seed_belief_lattice(args, ctx) {
2251
+ return formatSdkResult(
2252
+ await getSdkClient(ctx).context.seedBeliefLattice(args)
2253
+ );
2254
+ },
2255
+ async get_lattice_coverage(args, ctx) {
2256
+ return formatSdkResult(
2257
+ await getSdkClient(ctx).context.getLatticeCoverage(args)
2258
+ );
2259
+ }
2260
+ };
2261
+
2262
+ // ../../apps/mcp-server/src/handlers/search.ts
2263
+ var searchHandlers = {
2264
+ async search_resources(args, ctx) {
2265
+ const topicId = readString(args.topicId) ?? readString(args.projectId) ?? "";
2266
+ if (!topicId) {
2267
+ throw new Error("search_resources requires a topicId parameter");
2268
+ }
2269
+ return formatSdkResult(
2270
+ await getSdkClient(ctx).search(readString(args.q) ?? readString(args.query) ?? "", {
2271
+ topicId,
2272
+ types: readStringArray(args.types),
2273
+ status: readString(args.status),
2274
+ minConfidence: readNumber(args.minConfidence),
2275
+ limit: readNumber(args.limit),
2276
+ cursor: readString(args.cursor)
2277
+ })
2278
+ );
2279
+ }
2280
+ };
2281
+
2282
+ // ../../apps/mcp-server/src/handlers/tasks.ts
2283
+ var taskHandlers = {
2284
+ async create_task(args, ctx) {
2285
+ return formatSdkResult(
2286
+ await getSdkClient(ctx).tasks.create({
2287
+ topicId: readString(args.topicId ?? args.projectId) ?? "",
2288
+ title: readString(args.title) ?? "",
2289
+ description: readString(args.description),
2290
+ taskType: readString(args.taskType),
2291
+ priority: readString(args.priority),
2292
+ linkedBeliefId: readString(args.linkedBeliefId),
2293
+ linkedQuestionId: readString(args.linkedQuestionId),
2294
+ linkedWorktreeId: readString(args.linkedWorktreeId)
2295
+ })
2296
+ );
2297
+ },
2298
+ async complete_task(args, ctx) {
2299
+ return formatSdkResult(
2300
+ await getSdkClient(ctx).tasks.complete(
2301
+ readString(args.taskId ?? args.id) ?? "",
2302
+ {
2303
+ outputSummary: readString(args.outputSummary) ?? ""
2304
+ }
2305
+ )
2306
+ );
2307
+ },
2308
+ async update_task(args, ctx) {
2309
+ return formatSdkResult(
2310
+ await getSdkClient(ctx).tasks.update(
2311
+ readString(args.taskId ?? args.id) ?? "",
2312
+ {
2313
+ title: readString(args.title),
2314
+ description: readString(args.description),
2315
+ priority: readString(args.priority),
2316
+ status: readString(args.status),
2317
+ linkedBeliefId: readString(args.linkedBeliefId),
2318
+ linkedQuestionId: readString(args.linkedQuestionId),
2319
+ linkedWorktreeId: readString(args.linkedWorktreeId)
2320
+ }
2321
+ )
2322
+ );
2323
+ },
2324
+ async list_tasks(args, ctx) {
2325
+ return formatSdkResult(
2326
+ await getSdkClient(ctx).tasks.list({
2327
+ topicId: readString(args.topicId ?? args.projectId),
2328
+ worktreeId: readString(args.worktreeId) ?? readString(args.linkedWorktreeId),
2329
+ status: readString(args.status),
2330
+ limit: readNumber(args.limit)
2331
+ })
2332
+ );
2333
+ }
2334
+ };
2335
+
2336
+ // ../../apps/mcp-server/src/handlers/thesis-artifacts.ts
2337
+ function stripHtml(value) {
2338
+ return value.replace(/<[^>]+>/g, " ").replace(/&nbsp;/g, " ").replace(/&amp;/g, "&").replace(/\s+/g, " ").trim();
2339
+ }
2340
+ function truncateText(value, maxChars = 320) {
2341
+ if (!value) {
2342
+ return null;
2343
+ }
2344
+ if (value.length <= maxChars) {
2345
+ return value;
2346
+ }
2347
+ return `${value.slice(0, maxChars - 3).trimEnd()}...`;
2348
+ }
2349
+ function normalizeThesis(worktree) {
2350
+ const thesis = worktree.branchThesis && typeof worktree.branchThesis === "object" ? worktree.branchThesis : worktree.pillarThesis && typeof worktree.pillarThesis === "object" ? worktree.pillarThesis : null;
2351
+ return thesis ?? null;
2352
+ }
2353
+ function hasThesisArtifact(worktree) {
2354
+ const thesis = normalizeThesis(worktree);
2355
+ return Boolean(
2356
+ typeof thesis?.content === "string" && thesis.content.trim().length > 0
2357
+ );
2358
+ }
2359
+ function normalizeWorktreeId(worktree) {
2360
+ if (typeof worktree.worktreeId === "string") {
2361
+ return worktree.worktreeId;
2362
+ }
2363
+ if (typeof worktree._id === "string") {
2364
+ return worktree._id;
2365
+ }
2366
+ return null;
2367
+ }
2368
+ function normalizeTopicId(worktree) {
2369
+ return typeof worktree.topicId === "string" ? worktree.topicId : null;
2370
+ }
2371
+ function rankWorktreesByArtifact(left, right) {
2372
+ const leftThesis = normalizeThesis(left);
2373
+ const rightThesis = normalizeThesis(right);
2374
+ const leftRank = leftThesis?.status === "final" || typeof leftThesis?.approvedAt === "number" ? 2 : 1;
2375
+ const rightRank = rightThesis?.status === "final" || typeof rightThesis?.approvedAt === "number" ? 2 : 1;
2376
+ if (leftRank !== rightRank) {
2377
+ return rightRank - leftRank;
2378
+ }
2379
+ const leftTimestamp = leftThesis?.approvedAt ?? leftThesis?.generatedAt ?? left.updatedAt ?? left.createdAt ?? left._creationTime ?? 0;
2380
+ const rightTimestamp = rightThesis?.approvedAt ?? rightThesis?.generatedAt ?? right.updatedAt ?? right.createdAt ?? right._creationTime ?? 0;
2381
+ return rightTimestamp - leftTimestamp;
2382
+ }
2383
+ function summarizeQuestionPayload(questions) {
2384
+ const normalized = Array.isArray(questions) ? questions : [];
2385
+ const answered = normalized.filter((question) => {
2386
+ const status = question && typeof question === "object" && "status" in question ? String(question.status ?? "").toLowerCase() : "";
2387
+ return status === "answered" || status === "final";
2388
+ }).length;
2389
+ const open = normalized.filter((question) => {
2390
+ const status = question && typeof question === "object" && "status" in question ? String(question.status ?? "").toLowerCase() : "";
2391
+ return status === "open" || status === "in_progress" || status === "active";
2392
+ }).length;
2393
+ return {
2394
+ total: normalized.length,
2395
+ answered,
2396
+ open
2397
+ };
2398
+ }
2399
+ async function buildWorktreeArtifact(args) {
2400
+ const worktreeId = normalizeWorktreeId(args.worktree);
2401
+ if (!worktreeId) {
2402
+ return null;
2403
+ }
2404
+ const thesis = normalizeThesis(args.worktree);
2405
+ const thesisHtml = typeof thesis?.content === "string" && thesis.content.trim().length > 0 ? thesis.content : null;
2406
+ const memoHtml = typeof thesis?.memoContent === "string" && thesis.memoContent.trim().length > 0 ? thesis.memoContent : null;
2407
+ const thesisText = thesisHtml ? stripHtml(thesisHtml) : null;
2408
+ const memoText = memoHtml ? stripHtml(memoHtml) : null;
2409
+ const [beliefs, qa, recentEvidence, openQuestions, versionHistory] = await Promise.all([
2410
+ adminQuery(components2.lucern.epistemicBeliefs.getByWorktree, {
2411
+ worktreeId
2412
+ }).catch(() => []),
2413
+ args.topicId ? adminQuery(api2.worktrees.getWorktreeQAForReport, {
2414
+ worktreeId,
2415
+ topicId: args.topicId,
2416
+ userId: args.userId
2417
+ }).catch(() => null) : Promise.resolve(null),
2418
+ args.topicId ? adminQuery(components2.lucern.epistemicEvidence.getByTopic, {
2419
+ topicId: args.topicId,
2420
+ userId: args.userId,
2421
+ limit: 8
2422
+ }).catch(() => []) : Promise.resolve([]),
2423
+ args.topicId ? adminQuery(components2.lucern.epistemicQuestions.getByTopic, {
2424
+ topicId: args.topicId,
2425
+ userId: args.userId,
2426
+ limit: 8,
2427
+ status: "open"
2428
+ }).catch(() => []) : Promise.resolve([]),
2429
+ args.includeVersions ? adminQuery(api2.worktrees.getPillarThesisVersions, {
2430
+ worktreeId
2431
+ }).catch(() => []) : Promise.resolve([])
2432
+ ]);
2433
+ const supportingBeliefs = (Array.isArray(beliefs) ? beliefs : []).slice().sort((left, right) => {
2434
+ const leftConfidence = typeof left?.confidence === "number" ? left.confidence : typeof left?.currentConfidence === "number" ? left.currentConfidence : 0;
2435
+ const rightConfidence = typeof right?.confidence === "number" ? right.confidence : typeof right?.currentConfidence === "number" ? right.currentConfidence : 0;
2436
+ return rightConfidence - leftConfidence;
2437
+ }).slice(0, 8).map((belief) => ({
2438
+ nodeId: String(belief?._id ?? belief?.nodeId ?? ""),
2439
+ canonicalText: String(
2440
+ belief?.canonicalText ?? belief?.text ?? belief?.title ?? ""
2441
+ ),
2442
+ confidence: typeof belief?.confidence === "number" ? belief.confidence : typeof belief?.currentConfidence === "number" ? belief.currentConfidence : null,
2443
+ status: belief?.status ?? null,
2444
+ criticality: belief?.criticality ?? belief?.metadata?.criticality ?? null
2445
+ }));
2446
+ const reportQuestions = Array.isArray(qa?.questions) ? qa.questions : Array.isArray(openQuestions) ? openQuestions : [];
2447
+ return {
2448
+ artifactState: thesisHtml || memoHtml ? "ready" : "missing",
2449
+ worktreeId,
2450
+ worktreeName: typeof args.worktree.name === "string" ? args.worktree.name : typeof args.worktree.title === "string" ? args.worktree.title : "Untitled worktree",
2451
+ topicId: args.topicId,
2452
+ topicName: args.topicName,
2453
+ status: args.worktree.status ?? null,
2454
+ phase: args.worktree.phase ?? null,
2455
+ track: args.worktree.track ?? null,
2456
+ executionBand: typeof args.worktree.executionBand === "number" ? args.worktree.executionBand : null,
2457
+ hypothesis: typeof args.worktree.hypothesis === "string" ? args.worktree.hypothesis : null,
2458
+ thesisStatus: thesis?.status ?? null,
2459
+ generatedAt: typeof thesis?.generatedAt === "number" ? thesis.generatedAt : null,
2460
+ approvedAt: typeof thesis?.approvedAt === "number" ? thesis.approvedAt : null,
2461
+ thesisHtml,
2462
+ thesisText,
2463
+ memoHtml,
2464
+ memoText,
2465
+ preferredArtifact: memoText && memoText.length > 0 ? { format: "text", text: memoText, source: "memo" } : thesisText && thesisText.length > 0 ? { format: "text", text: thesisText, source: "thesis" } : null,
2466
+ preview: truncateText(memoText) ?? truncateText(thesisText) ?? truncateText(
2467
+ typeof args.worktree.hypothesis === "string" ? args.worktree.hypothesis : null
2468
+ ),
2469
+ questionSummary: summarizeQuestionPayload(reportQuestions),
2470
+ supportingBeliefs,
2471
+ openQuestions: reportQuestions.slice(0, 8).map((question) => ({
2472
+ questionId: String(question?.questionId ?? question?._id ?? ""),
2473
+ question: String(question?.question ?? question?.canonicalText ?? ""),
2474
+ status: question?.status ?? null,
2475
+ importance: typeof question?.importance === "number" ? question.importance : null,
2476
+ answer: typeof question?.answer === "string" && question.answer.trim().length > 0 ? question.answer : null
2477
+ })),
2478
+ recentEvidence: (Array.isArray(recentEvidence) ? recentEvidence : []).slice(0, 6).map((evidence) => ({
2479
+ nodeId: String(evidence?._id ?? evidence?.nodeId ?? ""),
2480
+ title: String(evidence?.title ?? evidence?.canonicalText ?? ""),
2481
+ canonicalText: String(evidence?.canonicalText ?? evidence?.text ?? ""),
2482
+ sourceUrl: typeof evidence?.sourceUrl === "string" ? evidence.sourceUrl : null
2483
+ })),
2484
+ versionHistory: Array.isArray(versionHistory) ? versionHistory.map((version) => ({
2485
+ version: typeof version?.version === "number" ? version.version : null,
2486
+ status: version?.status ?? null,
2487
+ changeType: version?.changeType ?? null,
2488
+ changeDescription: version?.changeDescription ?? null,
2489
+ createdAt: typeof version?.createdAt === "number" ? version.createdAt : null
2490
+ })) : []
2491
+ };
2492
+ }
2493
+ var thesisArtifactHandlers = {
2494
+ async get_thesis_artifacts(args, ctx) {
2495
+ const defaultTopicId2 = getDefaultScopeContext().topicId ?? void 0;
2496
+ const requestedTopicId = readTopicIdArg(args) || defaultTopicId2 || void 0;
2497
+ const worktreeId = typeof args.worktreeId === "string" && args.worktreeId.trim().length > 0 ? args.worktreeId.trim() : void 0;
2498
+ const includeVersions = args.includeVersions === true;
2499
+ const limit = typeof args.limit === "number" && Number.isFinite(args.limit) ? Math.max(1, Math.min(10, Math.floor(args.limit))) : 5;
2500
+ let selectedWorktree = null;
2501
+ if (worktreeId) {
2502
+ selectedWorktree = await adminQuery(components2.lucern.worktrees.get, {
2503
+ worktreeId
2504
+ }).catch(() => null);
2505
+ }
2506
+ const resolvedTopicId = requestedTopicId || normalizeTopicId(selectedWorktree ?? {}) || null;
2507
+ let topicName = null;
2508
+ if (resolvedTopicId) {
2509
+ const topic = await adminQuery(components2.lucern.topics.get, {
2510
+ id: resolvedTopicId
2511
+ }).catch(() => null);
2512
+ topicName = typeof topic?.name === "string" ? topic.name : null;
2513
+ }
2514
+ const topicWorktrees = resolvedTopicId ? await adminQuery(components2.lucern.worktrees.getByTopic, {
2515
+ topicId: resolvedTopicId
2516
+ }).catch(() => []) : [];
2517
+ const rankedTopicArtifacts = topicWorktrees.filter(hasThesisArtifact).sort(rankWorktreesByArtifact);
2518
+ const selectedArtifact = selectedWorktree ? await buildWorktreeArtifact({
2519
+ worktree: selectedWorktree,
2520
+ topicId: resolvedTopicId,
2521
+ topicName,
2522
+ userId: ctx.userId,
2523
+ includeVersions
2524
+ }) : rankedTopicArtifacts.length > 0 ? await buildWorktreeArtifact({
2525
+ worktree: rankedTopicArtifacts[0],
2526
+ topicId: resolvedTopicId,
2527
+ topicName,
2528
+ userId: ctx.userId,
2529
+ includeVersions
2530
+ }) : null;
2531
+ const topicArtifacts = await Promise.all(
2532
+ rankedTopicArtifacts.slice(0, limit).map(
2533
+ (worktree) => buildWorktreeArtifact({
2534
+ worktree,
2535
+ topicId: resolvedTopicId,
2536
+ topicName,
2537
+ userId: ctx.userId,
2538
+ includeVersions: false
2539
+ })
2540
+ )
2541
+ );
2542
+ return {
2543
+ scope: {
2544
+ topicId: resolvedTopicId,
2545
+ topicName,
2546
+ worktreeId: worktreeId ?? null
2547
+ },
2548
+ selectedArtifact,
2549
+ topicArtifacts: topicArtifacts.filter(Boolean),
2550
+ availableArtifactCount: rankedTopicArtifacts.length,
2551
+ recommendedUses: [
2552
+ "Draft a meeting agenda grounded in the latest worktree thesis and open questions.",
2553
+ "Turn the memo text into a one-pager, partner update, or investment note.",
2554
+ "Use the thesis plus supporting beliefs as slide-outline raw material for a deck.",
2555
+ "Seed blog-post or email drafts from the narrative artifact without re-querying the graph."
2556
+ ]
2557
+ };
2558
+ }
2559
+ };
2560
+
2561
+ // ../../apps/mcp-server/src/handlers/worktrees.ts
2562
+ var worktreeHandlers = {
2563
+ async add_worktree(args, ctx) {
2564
+ return formatSdkResult(
2565
+ await getSdkClient(ctx).worktrees.add({
2566
+ title: readString(args.title) ?? "",
2567
+ topicId: readString(args.topicId ?? args.projectId) ?? "",
2568
+ objective: readString(args.objective),
2569
+ hypothesis: readString(args.hypothesis),
2570
+ beliefIds: readStringArray(args.beliefIds) ?? readStringArray(args.beliefs),
2571
+ autoShape: typeof args.autoShape === "boolean" ? args.autoShape : void 0,
2572
+ domainPackId: readString(args.domainPackId),
2573
+ executionOrder: readNumber(args.executionOrder),
2574
+ dependsOn: readStringArray(args.dependsOn),
2575
+ blocks: readStringArray(args.blocks),
2576
+ gate: readString(args.gate),
2577
+ proofArtifacts: Array.isArray(args.proofArtifacts) ? args.proofArtifacts : void 0,
2578
+ staffingHint: readString(args.staffingHint),
2579
+ lastReconciledAt: readNumber(args.lastReconciledAt),
2580
+ autoFixPolicy: args.autoFixPolicy && typeof args.autoFixPolicy === "object" && !Array.isArray(args.autoFixPolicy) ? args.autoFixPolicy : void 0
2581
+ })
2582
+ );
2583
+ },
2584
+ async list_worktrees(args, ctx) {
2585
+ return formatSdkResult(
2586
+ await getSdkClient(ctx).worktrees.list({
2587
+ topicId: readString(args.topicId ?? args.projectId) ?? "",
2588
+ status: readString(args.status),
2589
+ limit: readNumber(args.limit)
2590
+ })
2591
+ );
2592
+ },
2593
+ async activate_worktree(args, ctx) {
2594
+ return formatSdkResult(
2595
+ await getSdkClient(ctx).worktrees.activate(
2596
+ readString(args.worktreeId ?? args.id) ?? ""
2597
+ )
2598
+ );
2599
+ },
2600
+ async update_worktree_metadata(args, ctx) {
2601
+ return formatSdkResult(
2602
+ await getSdkClient(ctx).worktrees.updateMetadata({
2603
+ worktreeId: readString(args.worktreeId ?? args.id) ?? "",
2604
+ objective: readString(args.objective),
2605
+ hypothesis: readString(args.hypothesis),
2606
+ rationale: readString(args.rationale),
2607
+ track: readString(args.track),
2608
+ trackPosition: readNumber(args.trackPosition),
2609
+ executionBand: readNumber(args.executionBand),
2610
+ executionOrder: readNumber(args.executionOrder),
2611
+ dependsOn: readStringArray(args.dependsOn),
2612
+ blocks: readStringArray(args.blocks),
2613
+ gate: readString(args.gate),
2614
+ status: readString(args.status),
2615
+ topicId: readString(args.topicId),
2616
+ additionalTopicIds: readStringArray(args.additionalTopicIds),
2617
+ proofArtifacts: Array.isArray(args.proofArtifacts) ? args.proofArtifacts : void 0,
2618
+ staffingHint: readString(args.staffingHint),
2619
+ lastReconciledAt: readNumber(args.lastReconciledAt),
2620
+ autoFixPolicy: args.autoFixPolicy && typeof args.autoFixPolicy === "object" && !Array.isArray(args.autoFixPolicy) ? args.autoFixPolicy : void 0
2621
+ })
2622
+ );
2623
+ },
2624
+ async merge(args, ctx) {
2625
+ const record = asRecord(args);
2626
+ const outcomes = Array.isArray(record.outcomes) ? record.outcomes : [];
2627
+ return formatSdkResult(
2628
+ await getSdkClient(ctx).worktrees.merge(
2629
+ readString(record.worktreeId ?? record.id) ?? "",
2630
+ {
2631
+ summary: readString(record.summary),
2632
+ outcomes: outcomes.map((entry) => {
2633
+ const row = asRecord(entry);
2634
+ return {
2635
+ beliefId: readString(row.beliefId) ?? "",
2636
+ confidence: readNumber(row.confidence) ?? Number.NaN,
2637
+ rationale: readString(row.rationale) ?? ""
2638
+ };
2639
+ })
2640
+ }
2641
+ )
2642
+ );
2643
+ },
2644
+ async list_all_worktrees(args, ctx) {
2645
+ return formatSdkResult(
2646
+ await getSdkClient(ctx).worktrees.listAll({
2647
+ status: readString(args.status),
2648
+ track: readString(args.track),
2649
+ executionBand: readNumber(args.executionBand),
2650
+ limit: readNumber(args.limit)
2651
+ })
2652
+ );
2653
+ },
2654
+ async pipeline_snapshot(args, ctx) {
2655
+ const topicId = readString(args.topicId) ?? "";
2656
+ if (!topicId) {
2657
+ return { error: "topicId is required" };
2658
+ }
2659
+ return formatSdkResult(
2660
+ await getSdkClient(ctx).worktrees.pipelineSnapshot(topicId)
2661
+ );
2662
+ },
2663
+ async push(args, ctx) {
2664
+ return formatSdkResult(
2665
+ await getSdkClient(ctx).worktrees.push(
2666
+ readString(args.worktreeId ?? args.id) ?? "",
2667
+ {
2668
+ targetContext: readString(args.targetContext) ?? "",
2669
+ beliefIds: readStringArray(args.beliefIds)
2670
+ }
2671
+ )
2672
+ );
2673
+ },
2674
+ async open_pull_request(args, ctx) {
2675
+ return formatSdkResult(
2676
+ await getSdkClient(ctx).worktrees.openPullRequest(
2677
+ readString(args.worktreeId ?? args.id) ?? "",
2678
+ {
2679
+ summary: readString(args.summary) ?? "",
2680
+ reviewers: readStringArray(args.reviewers)
2681
+ }
2682
+ )
2683
+ );
2684
+ },
2685
+ async update_worktree_targets(args, ctx) {
2686
+ return formatSdkResult(
2687
+ await getSdkClient(ctx).worktrees.updateTargets({
2688
+ worktreeId: readString(args.worktreeId ?? args.id) ?? "",
2689
+ addBeliefIds: readStringArray(args.addBeliefIds),
2690
+ addQuestionIds: readStringArray(args.addQuestionIds),
2691
+ removeBeliefIds: readStringArray(args.removeBeliefIds),
2692
+ removeQuestionIds: readStringArray(args.removeQuestionIds)
2693
+ })
2694
+ );
2695
+ }
2696
+ };
2697
+
2698
+ // ../../apps/mcp-server/src/handlers/index.ts
2699
+ function buildHandlerMap() {
2700
+ return {
2701
+ ...evidenceHandlers,
2702
+ ...questionHandlers,
2703
+ ...searchHandlers,
2704
+ ...answerHandlers,
2705
+ ...worktreeHandlers,
2706
+ ...lensHandlers,
2707
+ ...edgeHandlers,
2708
+ ...judgmentHandlers,
2709
+ ...graphHandlers,
2710
+ ...identityHandlers,
2711
+ ...lineageHandlers,
2712
+ ...intelligenceHandlers,
2713
+ ...researchHandlers,
2714
+ ...researchVerificationHandlers,
2715
+ ...taskHandlers,
2716
+ ...topicHandlers,
2717
+ ...contradictionHandlers,
2718
+ ...contractHandlers,
2719
+ ...engineeringVerificationHandlers,
2720
+ ...policyHandlers,
2721
+ ...observationHandlers,
2722
+ ...scopeContextHandlers,
2723
+ ...codingHandlers,
2724
+ ...coordinationHandlers,
2725
+ ...coverageHandlers,
2726
+ ...discoveryHandlers,
2727
+ ...thesisArtifactHandlers,
2728
+ ...bootstrapHandlers,
2729
+ ...autoBranchingHandlers,
2730
+ ...ontologyHandlers,
2731
+ ...ontologyMatchingHandlers,
2732
+ ...beliefHandlers
2733
+ };
2734
+ }
2735
+
2736
+ // ../../apps/mcp-server/src/write-policy.ts
2737
+ var MUTATION_TOOL_NAMES = /* @__PURE__ */ new Set([
2738
+ "create_belief",
2739
+ "refine_belief",
2740
+ "modulate_confidence",
2741
+ "fork_belief",
2742
+ "archive_belief",
2743
+ "create_evidence",
2744
+ "link_evidence",
2745
+ "add_evidence",
2746
+ "link_evidence_to_belief",
2747
+ "record_scope_learning",
2748
+ "record_attempt",
2749
+ "create_question",
2750
+ "answer_question",
2751
+ "refine_question",
2752
+ "update_question_status",
2753
+ "archive_question",
2754
+ "link_evidence_to_question",
2755
+ "create_answer",
2756
+ "create_edge",
2757
+ "flag_contradiction",
2758
+ "add_worktree",
2759
+ "merge",
2760
+ "activate_worktree",
2761
+ "update_worktree_metadata",
2762
+ "update_worktree_targets",
2763
+ "create_lens",
2764
+ "apply_lens_to_topic",
2765
+ "remove_lens_from_topic",
2766
+ "create_task",
2767
+ "complete_task",
2768
+ "record_judgment",
2769
+ "register_session",
2770
+ "heartbeat_session",
2771
+ "end_session",
2772
+ "send_agent_message",
2773
+ "broadcast_message",
2774
+ "claim_files",
2775
+ "create_topic",
2776
+ "open_pull_request",
2777
+ "apply_auto_branching",
2778
+ "seed_belief_lattice",
2779
+ "trigger_belief_review",
2780
+ "create_epistemic_contract",
2781
+ "evaluate_contract",
2782
+ "create_ontology",
2783
+ "update_ontology",
2784
+ "archive_ontology",
2785
+ "create_ontology_version",
2786
+ "publish_ontology_version",
2787
+ "deprecate_ontology_version",
2788
+ "manage_write_policy"
2789
+ ]);
2790
+ function isMutationTool(toolName) {
2791
+ return MUTATION_TOOL_NAMES.has(toolName);
2792
+ }
2793
+ var sessionWritesBySession = /* @__PURE__ */ new Map();
2794
+ function recordWrite(toolName, topicId, sessionId = "default") {
2795
+ const record = {
2796
+ toolName,
2797
+ timestamp: Date.now(),
2798
+ topicId
2799
+ };
2800
+ const existing = sessionWritesBySession.get(sessionId) ?? [];
2801
+ existing.push(record);
2802
+ sessionWritesBySession.set(sessionId, existing);
2803
+ }
2804
+ function buildRateLimitExplanation(args) {
2805
+ const summary = `Denied ${args.toolName}: session write limit ${args.currentCount}/${args.maxWritesPerSession} reached for the matched write policy.`;
2806
+ return {
2807
+ summary,
2808
+ matchedReasonCode: "RATE_LIMIT_EXCEEDED",
2809
+ toolName: args.toolName,
2810
+ toolCategory: args.toolCategory ?? null,
2811
+ role: args.authRole,
2812
+ topicId: args.topicId ?? null,
2813
+ policy: args.policy ?? null,
2814
+ steps: [
2815
+ {
2816
+ stage: "policy_lookup",
2817
+ outcome: "passed",
2818
+ reasonCode: "WRITE_POLICY_MATCHED",
2819
+ detail: "A matching write policy was found before evaluating the session limit."
2820
+ },
2821
+ {
2822
+ stage: "rate_limit",
2823
+ outcome: "failed",
2824
+ reasonCode: "RATE_LIMIT_EXCEEDED",
2825
+ detail: `This session has already recorded ${args.currentCount} writes and the matched rule caps it at ${args.maxWritesPerSession}.`
2826
+ },
2827
+ {
2828
+ stage: "decision",
2829
+ outcome: "failed",
2830
+ reasonCode: "RATE_LIMIT_EXCEEDED",
2831
+ detail: summary
2832
+ }
2833
+ ]
2834
+ };
2835
+ }
2836
+ async function checkWritePolicy(toolName, topicId, authCtx) {
2837
+ if (!isMutationTool(toolName)) {
2838
+ return { allowed: true, permission: "allow", reason: "read_only_tool" };
2839
+ }
2840
+ try {
2841
+ const result = await adminQuery(api2.mcpWritePolicy.checkAccess, {
2842
+ topicId: topicId ?? void 0,
2843
+ role: authCtx.role,
2844
+ toolName
2845
+ });
2846
+ if (!result) {
2847
+ return {
2848
+ allowed: true,
2849
+ permission: "allow",
2850
+ toolCategory: null,
2851
+ policy: null,
2852
+ reason: "no_policy_response"
2853
+ };
2854
+ }
2855
+ if (result.allowed && typeof result.maxWritesPerSession === "number" && Number.isFinite(result.maxWritesPerSession)) {
2856
+ const currentCount = sessionWritesBySession.get(authCtx.sessionId)?.length ?? 0;
2857
+ if (currentCount >= result.maxWritesPerSession) {
2858
+ return {
2859
+ allowed: false,
2860
+ permission: "deny",
2861
+ rationale: `Session write limit reached (${currentCount}/${result.maxWritesPerSession})`,
2862
+ maxWritesPerSession: result.maxWritesPerSession,
2863
+ toolCategory: typeof result.toolCategory === "string" ? result.toolCategory : null,
2864
+ policy: result.policy && typeof result.policy === "object" ? result.policy : null,
2865
+ explanation: buildRateLimitExplanation({
2866
+ toolName,
2867
+ toolCategory: typeof result.toolCategory === "string" ? result.toolCategory : null,
2868
+ authRole: authCtx.role,
2869
+ topicId,
2870
+ maxWritesPerSession: result.maxWritesPerSession,
2871
+ currentCount,
2872
+ policy: result.policy && typeof result.policy === "object" ? result.policy : null
2873
+ }),
2874
+ reason: "rate_limit_exceeded"
2875
+ };
2876
+ }
2877
+ }
2878
+ return result;
2879
+ } catch (err) {
2880
+ console.error(
2881
+ `[write-policy] Policy check failed for ${toolName}: ${err instanceof Error ? err.message : err}. Allowing (fail-open).`
2882
+ );
2883
+ return {
2884
+ allowed: true,
2885
+ permission: "allow",
2886
+ toolCategory: null,
2887
+ policy: null,
2888
+ explanation: {
2889
+ summary: "Allowed because write-policy evaluation failed and the runtime fell back to fail-open behavior.",
2890
+ matchedReasonCode: "WRITE_POLICY_CHECK_ERROR",
2891
+ steps: [
2892
+ {
2893
+ stage: "policy_lookup",
2894
+ outcome: "failed",
2895
+ reasonCode: "WRITE_POLICY_CHECK_ERROR",
2896
+ detail: err instanceof Error ? err.message : "Unknown policy evaluation error."
2897
+ },
2898
+ {
2899
+ stage: "decision",
2900
+ outcome: "bypassed",
2901
+ reasonCode: "WRITE_POLICY_CHECK_ERROR",
2902
+ detail: "Write-policy infrastructure error did not block the mutation because this runtime is fail-open on evaluation errors."
2903
+ }
2904
+ ]
2905
+ },
2906
+ reason: "policy_check_error"
2907
+ };
2908
+ }
2909
+ }
2910
+ var LUCERN_HOME = path2.join(os.homedir(), ".lucern");
2911
+ path2.join(LUCERN_HOME, "credentials");
2912
+
2913
+ export { buildHandlerMap, checkWritePolicy, createAdminClient, isMutationTool, recordWrite, runWithScopedClient };
2914
+ //# sourceMappingURL=runtime.js.map
2915
+ //# sourceMappingURL=runtime.js.map