@lucern/mcp 0.3.0-alpha.3 → 0.3.0-alpha.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/gateway.js CHANGED
@@ -11,6 +11,487 @@ function requireActorPrincipalId(authContext) {
11
11
  }
12
12
  throw new Error("Access denied: federated principal context required.");
13
13
  }
14
+
15
+ // ../contracts/src/graph-intelligence.contract.ts
16
+ var GRAPH_INTELLIGENCE_MODE_TOOL_NAMES = {
17
+ core: [
18
+ "get_graph_structure_analysis",
19
+ "get_topic_coverage",
20
+ "get_graph_gaps",
21
+ "list_beliefs",
22
+ "list_questions",
23
+ "search_evidence"
24
+ ],
25
+ bias: [
26
+ "get_graph_structure_analysis",
27
+ "detect_confirmation_bias",
28
+ "find_contradictions",
29
+ "search_evidence",
30
+ "list_beliefs"
31
+ ],
32
+ stress: [
33
+ "get_graph_structure_analysis",
34
+ "get_graph_gaps",
35
+ "find_contradictions",
36
+ "get_falsification_questions",
37
+ "list_beliefs",
38
+ "list_questions"
39
+ ],
40
+ operational: [
41
+ "get_topic_coverage",
42
+ "get_graph_gaps",
43
+ "list_beliefs",
44
+ "list_questions",
45
+ "search_evidence"
46
+ ],
47
+ alpha: [
48
+ "get_graph_structure_analysis",
49
+ "detect_confirmation_bias",
50
+ "find_contradictions",
51
+ "search_beliefs",
52
+ "search_evidence"
53
+ ],
54
+ semantic: [
55
+ "get_graph_structure_analysis",
56
+ "search_beliefs",
57
+ "search_evidence",
58
+ "traverse_graph",
59
+ "query_lineage",
60
+ "get_graph_neighborhood"
61
+ ],
62
+ evidence: [
63
+ "get_graph_structure_analysis",
64
+ "get_topic_coverage",
65
+ "search_evidence",
66
+ "get_falsification_questions",
67
+ "find_contradictions"
68
+ ]
69
+ };
70
+ var byMode = (mode) => GRAPH_INTELLIGENCE_MODE_TOOL_NAMES[mode];
71
+ var GRAPH_INTELLIGENCE_QUERIES = [
72
+ {
73
+ id: "confirmation-bias",
74
+ categoryId: "problems",
75
+ mode: "bias",
76
+ name: "Find Confirmation Bias",
77
+ description: "Find beliefs supported mainly by confirming evidence.",
78
+ prompt: "Find beliefs where supporting evidence overwhelms challenging evidence. Prioritize high-conviction beliefs with few defeaters.",
79
+ highlightStrategy: "bias-risk",
80
+ riskLevel: "high"
81
+ },
82
+ {
83
+ id: "contradiction-map",
84
+ categoryId: "problems",
85
+ mode: "stress",
86
+ name: "Map Contradictions",
87
+ description: "Surface direct and indirect contradiction clusters.",
88
+ prompt: "Map the graph's contradiction clusters and explain which tensions matter most.",
89
+ highlightStrategy: "contradictions",
90
+ riskLevel: "high"
91
+ },
92
+ {
93
+ id: "weak-evidence",
94
+ categoryId: "problems",
95
+ mode: "stress",
96
+ name: "Weak Evidence Chains",
97
+ description: "Find important claims with thin or indirect evidence.",
98
+ prompt: "Find high-importance beliefs whose evidence support is thin, indirect, stale, or low quality.",
99
+ highlightStrategy: "weak-support",
100
+ riskLevel: "medium"
101
+ },
102
+ {
103
+ id: "single-source",
104
+ categoryId: "problems",
105
+ mode: "bias",
106
+ name: "Single-Source Risk",
107
+ description: "Find claims overly dependent on one source or source type.",
108
+ prompt: "Identify beliefs that rely on a single source, one methodology, or one repeated perspective.",
109
+ highlightStrategy: "source-concentration",
110
+ riskLevel: "medium"
111
+ },
112
+ {
113
+ id: "untested-assumptions",
114
+ categoryId: "problems",
115
+ mode: "stress",
116
+ name: "Untested Assumptions",
117
+ description: "Find load-bearing assumptions without falsification paths.",
118
+ prompt: "Find assumptions that appear load-bearing but do not have direct testing questions or falsification evidence.",
119
+ highlightStrategy: "untested",
120
+ riskLevel: "high"
121
+ },
122
+ {
123
+ id: "load-bearing-beliefs",
124
+ categoryId: "problems",
125
+ mode: "stress",
126
+ name: "Load-Bearing Beliefs",
127
+ description: "Find central beliefs whose failure would affect many claims.",
128
+ prompt: "Find the beliefs with the largest downstream impact if they are wrong.",
129
+ highlightStrategy: "load-bearing",
130
+ riskLevel: "high"
131
+ },
132
+ {
133
+ id: "cascade-analysis",
134
+ categoryId: "problems",
135
+ mode: "stress",
136
+ name: "Cascade Analysis",
137
+ description: "Trace what changes if a belief is weakened or invalidated.",
138
+ prompt: "Analyze likely downstream cascades if the most central or uncertain beliefs are weakened.",
139
+ highlightStrategy: "cascade",
140
+ riskLevel: "high"
141
+ },
142
+ {
143
+ id: "unanswered-questions",
144
+ categoryId: "gaps",
145
+ mode: "operational",
146
+ name: "Unanswered Questions",
147
+ description: "Find important open questions that block confidence.",
148
+ prompt: "Identify the most important unanswered questions and explain which beliefs they block.",
149
+ highlightStrategy: "open-questions"
150
+ },
151
+ {
152
+ id: "thin-themes",
153
+ categoryId: "gaps",
154
+ mode: "operational",
155
+ name: "Thin Themes",
156
+ description: "Find topics with shallow belief or evidence coverage.",
157
+ prompt: "Find themes that look underdeveloped relative to their role in the graph.",
158
+ highlightStrategy: "thin-themes"
159
+ },
160
+ {
161
+ id: "missing-evidence",
162
+ categoryId: "gaps",
163
+ mode: "stress",
164
+ name: "Missing Evidence",
165
+ description: "Find beliefs that need specific missing evidence.",
166
+ prompt: "Find the most valuable missing evidence needed to strengthen or falsify the graph.",
167
+ highlightStrategy: "missing-evidence"
168
+ },
169
+ {
170
+ id: "isolated-clusters",
171
+ categoryId: "gaps",
172
+ mode: "operational",
173
+ name: "Isolated Clusters",
174
+ description: "Find clusters not connected to the broader graph.",
175
+ prompt: "Find isolated graph clusters and recommend bridge questions or bridge evidence.",
176
+ highlightStrategy: "isolated-clusters"
177
+ },
178
+ {
179
+ id: "source-contribution",
180
+ categoryId: "gaps",
181
+ mode: "evidence",
182
+ name: "Source Contribution",
183
+ description: "Assess how source mix shapes the graph.",
184
+ prompt: "Assess whether the source mix is balanced enough for the graph's strongest claims.",
185
+ highlightStrategy: "source-mix"
186
+ },
187
+ {
188
+ id: "stale-beliefs",
189
+ categoryId: "gaps",
190
+ mode: "operational",
191
+ name: "Stale Beliefs",
192
+ description: "Find beliefs that need review because they are old or stale.",
193
+ prompt: "Find beliefs that should be revisited because they are stale, unsupported by recent evidence, or contradicted by newer context.",
194
+ highlightStrategy: "staleness"
195
+ },
196
+ {
197
+ id: "assumption-pyramid",
198
+ categoryId: "reasoning",
199
+ mode: "operational",
200
+ name: "Assumption Pyramid",
201
+ description: "Show which conclusions rest on which assumptions.",
202
+ prompt: "Build an assumption pyramid from the graph: foundational assumptions, intermediate claims, and top-level conclusions.",
203
+ highlightStrategy: "assumptions"
204
+ },
205
+ {
206
+ id: "converging-evidence",
207
+ categoryId: "reasoning",
208
+ mode: "evidence",
209
+ name: "Converging Evidence",
210
+ description: "Find claims supported by independent evidence streams.",
211
+ prompt: "Find beliefs with genuinely independent converging evidence and explain why they are robust.",
212
+ highlightStrategy: "convergence"
213
+ },
214
+ {
215
+ id: "weakest-links",
216
+ categoryId: "reasoning",
217
+ mode: "stress",
218
+ name: "Weakest Links",
219
+ description: "Find the weakest links in important reasoning chains.",
220
+ prompt: "Find the weakest links in important reasoning chains and explain how to test them.",
221
+ highlightStrategy: "weak-links",
222
+ riskLevel: "medium"
223
+ },
224
+ {
225
+ id: "challenged-beliefs",
226
+ categoryId: "reasoning",
227
+ mode: "stress",
228
+ name: "Challenged Beliefs",
229
+ description: "Find beliefs with active challenges or defeaters.",
230
+ prompt: "Find beliefs with active challenges, contradiction edges, or unresolved defeaters.",
231
+ highlightStrategy: "challenged"
232
+ },
233
+ {
234
+ id: "contrarian-map",
235
+ categoryId: "strategic",
236
+ mode: "alpha",
237
+ name: "Contrarian Map",
238
+ description: "Find non-consensus beliefs and where they are grounded.",
239
+ prompt: "Find the graph's strongest contrarian or non-consensus beliefs and explain their support.",
240
+ highlightStrategy: "contrarian"
241
+ },
242
+ {
243
+ id: "irreversibility-audit",
244
+ categoryId: "strategic",
245
+ mode: "stress",
246
+ name: "Irreversibility Audit",
247
+ description: "Find irreversible bets and assumptions behind them.",
248
+ prompt: "Audit irreversible decisions or beliefs and identify what must be true before acting.",
249
+ highlightStrategy: "irreversible",
250
+ riskLevel: "high"
251
+ },
252
+ {
253
+ id: "pre-mortem",
254
+ categoryId: "strategic",
255
+ mode: "stress",
256
+ name: "Pre-Mortem",
257
+ description: "Explain how the graph could be wrong.",
258
+ prompt: "Run a pre-mortem: assume the current thesis fails and identify the most plausible failure paths.",
259
+ highlightStrategy: "failure-paths",
260
+ riskLevel: "high"
261
+ },
262
+ {
263
+ id: "devils-advocate",
264
+ categoryId: "strategic",
265
+ mode: "stress",
266
+ name: "Devil's Advocate",
267
+ description: "Generate the strongest critique of the graph.",
268
+ prompt: "Produce the strongest evidence-grounded critique of the current graph and its main thesis.",
269
+ highlightStrategy: "critique"
270
+ },
271
+ {
272
+ id: "falsification-map",
273
+ categoryId: "strategic",
274
+ mode: "stress",
275
+ name: "Falsification Map",
276
+ description: "Find the cheapest tests that would disprove key beliefs.",
277
+ prompt: "Map the cheapest, clearest falsification tests for the graph's key claims.",
278
+ highlightStrategy: "falsification",
279
+ riskLevel: "high"
280
+ },
281
+ {
282
+ id: "prediction-tracker",
283
+ categoryId: "strategic",
284
+ mode: "evidence",
285
+ name: "Prediction Tracker",
286
+ description: "Find beliefs that imply measurable predictions.",
287
+ prompt: "Find beliefs that imply measurable predictions and suggest tracking signals.",
288
+ highlightStrategy: "predictions"
289
+ },
290
+ {
291
+ id: "belief-pagerank",
292
+ categoryId: "deep",
293
+ mode: "semantic",
294
+ name: "Belief PageRank",
295
+ description: "Identify structurally central beliefs.",
296
+ prompt: "Use graph centrality to identify the most structurally important beliefs.",
297
+ highlightStrategy: "centrality"
298
+ },
299
+ {
300
+ id: "underdetermination",
301
+ categoryId: "deep",
302
+ mode: "semantic",
303
+ name: "Underdetermination",
304
+ description: "Find places where evidence supports multiple explanations.",
305
+ prompt: "Find places where the same evidence could support multiple incompatible explanations.",
306
+ highlightStrategy: "underdetermination"
307
+ },
308
+ {
309
+ id: "confidence-propagation",
310
+ categoryId: "deep",
311
+ mode: "semantic",
312
+ name: "Confidence Propagation",
313
+ description: "Assess how uncertainty moves through the graph.",
314
+ prompt: "Explain how uncertainty propagates from weak or contested beliefs through downstream conclusions.",
315
+ highlightStrategy: "confidence-flow"
316
+ },
317
+ {
318
+ id: "argument-depth",
319
+ categoryId: "deep",
320
+ mode: "evidence",
321
+ name: "Argument Depth",
322
+ description: "Assess reasoning depth and chain quality.",
323
+ prompt: "Assess reasoning depth: where claims are shallow, deeply supported, or overextended.",
324
+ highlightStrategy: "depth"
325
+ },
326
+ {
327
+ id: "information-edge",
328
+ categoryId: "deep",
329
+ mode: "alpha",
330
+ name: "Information Edge",
331
+ description: "Find differentiated evidence or signals.",
332
+ prompt: "Find evidence, sources, or beliefs that could represent differentiated information edge.",
333
+ highlightStrategy: "information-edge"
334
+ },
335
+ {
336
+ id: "thesis-summary",
337
+ categoryId: "browse",
338
+ mode: "semantic",
339
+ name: "Thesis Summary",
340
+ description: "Summarize the graph's core thesis and support.",
341
+ prompt: "Summarize the graph's core thesis, strongest support, weakest support, and open questions.",
342
+ highlightStrategy: "summary"
343
+ },
344
+ {
345
+ id: "theme-deep-dive",
346
+ categoryId: "browse",
347
+ mode: "semantic",
348
+ name: "Theme Deep Dive",
349
+ description: "Deep dive into a named theme.",
350
+ prompt: "Deep dive into {input}. Explain the key beliefs, evidence, contradictions, and open questions.",
351
+ inputType: "theme",
352
+ highlightStrategy: "theme"
353
+ },
354
+ {
355
+ id: "belief-detail",
356
+ categoryId: "browse",
357
+ mode: "semantic",
358
+ name: "Belief Detail",
359
+ description: "Explain one belief and its graph neighborhood.",
360
+ prompt: "Explain {input} and its support, challenges, related beliefs, and downstream implications.",
361
+ inputType: "belief",
362
+ highlightStrategy: "belief"
363
+ },
364
+ {
365
+ id: "strongest-beliefs",
366
+ categoryId: "browse",
367
+ mode: "operational",
368
+ name: "Strongest Beliefs",
369
+ description: "Find the graph's strongest current beliefs.",
370
+ prompt: "Find the strongest current beliefs and explain why each one deserves confidence.",
371
+ highlightStrategy: "strongest"
372
+ },
373
+ {
374
+ id: "cross-theme-connection",
375
+ categoryId: "browse",
376
+ mode: "semantic",
377
+ name: "Cross-Theme Connections",
378
+ description: "Find bridges between themes.",
379
+ prompt: "Find meaningful connections across themes and explain which bridge beliefs matter.",
380
+ highlightStrategy: "bridges"
381
+ },
382
+ {
383
+ id: "research-velocity",
384
+ categoryId: "browse",
385
+ mode: "operational",
386
+ name: "Research Velocity",
387
+ description: "Summarize recent graph movement and momentum.",
388
+ prompt: "Assess research velocity: what changed recently, where progress is fastest, and what is stuck.",
389
+ highlightStrategy: "velocity"
390
+ },
391
+ {
392
+ id: "search",
393
+ categoryId: "browse",
394
+ mode: "semantic",
395
+ name: "Graph Search",
396
+ description: "Search the graph with semantic context.",
397
+ prompt: "Search the graph for {input}. Return the most relevant beliefs, evidence, and questions.",
398
+ inputType: "search",
399
+ highlightStrategy: "search"
400
+ },
401
+ {
402
+ id: "expert-coverage",
403
+ categoryId: "browse",
404
+ mode: "semantic",
405
+ name: "Expert Coverage",
406
+ description: "Assess coverage from expert/source perspectives.",
407
+ prompt: "Assess whether the graph has enough expert, primary, and dissenting coverage.",
408
+ highlightStrategy: "expert-coverage"
409
+ },
410
+ {
411
+ id: "value-chain-map",
412
+ categoryId: "browse",
413
+ mode: "semantic",
414
+ name: "Value Chain Map",
415
+ description: "Map entities, dependencies, and value-chain logic.",
416
+ prompt: "Map the value chain implied by this graph: entities, dependencies, pressure points, and missing links.",
417
+ highlightStrategy: "value-chain"
418
+ },
419
+ {
420
+ id: "meeting-brief",
421
+ categoryId: "prep",
422
+ mode: "semantic",
423
+ name: "Meeting Brief",
424
+ description: "Prepare a meeting brief from graph context.",
425
+ prompt: "Prepare a concise meeting brief using the graph: thesis, open questions, risks, and recommended asks.",
426
+ highlightStrategy: "brief"
427
+ },
428
+ {
429
+ id: "open-questions-entity",
430
+ categoryId: "prep",
431
+ mode: "semantic",
432
+ name: "Entity Open Questions",
433
+ description: "Find open questions about a specific entity.",
434
+ prompt: "Find the most important open questions about {input} and the beliefs those questions would unlock.",
435
+ inputType: "entity",
436
+ highlightStrategy: "entity-questions"
437
+ },
438
+ {
439
+ id: "company-context",
440
+ categoryId: "prep",
441
+ mode: "semantic",
442
+ name: "Company Context",
443
+ description: "Summarize graph context about a company.",
444
+ prompt: "Summarize what the graph knows about {input}: thesis relevance, evidence, risks, and open questions.",
445
+ inputType: "company",
446
+ highlightStrategy: "company"
447
+ },
448
+ {
449
+ id: "company-theme-fit",
450
+ categoryId: "prep",
451
+ mode: "semantic",
452
+ name: "Company Theme Fit",
453
+ description: "Assess how a company fits graph themes.",
454
+ prompt: "Assess how {input} fits the graph's themes and where the fit is weak or uncertain.",
455
+ inputType: "company",
456
+ highlightStrategy: "fit"
457
+ },
458
+ {
459
+ id: "company-comparison",
460
+ categoryId: "prep",
461
+ mode: "semantic",
462
+ name: "Company Comparison",
463
+ description: "Compare companies through graph context.",
464
+ prompt: "Compare {input} using graph beliefs, evidence, risks, and open questions.",
465
+ inputType: "company-list",
466
+ highlightStrategy: "comparison"
467
+ },
468
+ {
469
+ id: "questions-to-ask",
470
+ categoryId: "prep",
471
+ mode: "operational",
472
+ name: "Questions to Ask",
473
+ description: "Generate high-signal questions from graph gaps.",
474
+ prompt: "Generate the highest-signal questions to ask next, grounded in current graph gaps.",
475
+ highlightStrategy: "questions"
476
+ },
477
+ {
478
+ id: "beliefs-to-test",
479
+ categoryId: "prep",
480
+ mode: "stress",
481
+ name: "Beliefs to Test",
482
+ description: "Prioritize beliefs that should be tested next.",
483
+ prompt: "Prioritize the beliefs that should be tested next and explain the cheapest test for each.",
484
+ highlightStrategy: "tests",
485
+ riskLevel: "medium"
486
+ }
487
+ ];
488
+ GRAPH_INTELLIGENCE_QUERIES.map((query) => {
489
+ const definition = query;
490
+ return {
491
+ ...definition,
492
+ tools: definition.tools ?? byMode(definition.mode)
493
+ };
494
+ });
14
495
  function inferActorType(args) {
15
496
  if (args.sessionType === "agent") {
16
497
  return "agent";
@@ -62,7 +543,10 @@ function idOf(table) {
62
543
  return schema;
63
544
  }
64
545
  var NODE_TYPE = z.enum(["decision", "belief", "question", "theme", "deal", "topic", "claim", "evidence", "synthesis", "answer", "atomic_fact", "excerpt", "source", "company", "person", "investor", "function", "value_chain"]);
65
- var EDGE_TYPE = z.enum(["supports", "informs", "depends_on", "extracted_from", "contains", "tests", "supersedes", "responds_to", "belongs_to", "relates_to_thesis", "works_at", "invested_in", "competes_with", "participates_in", "founded_by", "evaluates", "performs", "function_in", "impacts", "raised_from", "mentioned_in", "perspective_on", "plays_theme", "answers", "explores", "qualifies", "based_on", "based_on_belief", "based_on_question", "blocked_by_contradiction", "informed_by_theme", "same_as", "reinforces", "parent_of", "child_of", "falsified_by", "exclusive_with", "collapses_if", "cascade_from", "counterfactual_of", "cascade_to", "mutually_exclusive", "correlates_with", "amplifies", "precondition_for", "in_tension_with", "strengthened_by", "weakened_by", "alternative_to", "subsumes", "validated_by", "required_for", "blocks", "prerequisite_for", "parallel_to", "corroborates", "extends", "same_source_as", "same_theme_as", "assumes", "would_predict", "analogous_to", "independent_of", "implements", "violates", "co_changes_with", "migrating_from", "migrating_to", "scoped_by", "about_entity", "entity_referenced_in", "contradicts", "cites", "summarizes", "related_to", "partially_answers", "refines", "branches_from"]);
546
+ var EDGE_TYPE_VALUES = ["supports", "informs", "depends_on", "derived_from", "contains", "tests", "supersedes", "responds_to", "belongs_to", "relates_to_thesis", "works_at", "invested_in", "competes_with", "participates_in", "founded_by", "evaluates", "performs", "function_in", "impacts", "raised_from", "mentioned_in", "perspective_on", "plays_theme", "answers", "explores", "qualifies", "based_on", "based_on_belief", "based_on_question", "blocked_by_contradiction", "informed_by_theme", "same_as", "reinforces", "parent_of", "child_of", "falsified_by", "exclusive_with", "collapses_if", "cascade_from", "counterfactual_of", "cascade_to", "mutually_exclusive", "correlates_with", "amplifies", "precondition_for", "in_tension_with", "strengthened_by", "weakened_by", "alternative_to", "subsumes", "validated_by", "required_for", "blocks", "prerequisite_for", "parallel_to", "corroborates", "extends", "same_source_as", "same_theme_as", "assumes", "would_predict", "analogous_to", "independent_of", "implements", "violates", "co_changes_with", "migrating_from", "migrating_to", "scoped_by", "about_entity", "entity_referenced_in", "contradicts", "cites", "summarizes", "related_to", "partially_answers", "refines", "branches_from"];
547
+ var STORAGE_EDGE_TYPE_VALUES = [...EDGE_TYPE_VALUES, "extracted_from"];
548
+ z.enum(EDGE_TYPE_VALUES);
549
+ var STORAGE_EDGE_TYPE = z.enum(STORAGE_EDGE_TYPE_VALUES);
66
550
  var TOPIC_STATUS = z.enum(["active", "archived", "watching"]);
67
551
  var TOPIC_VISIBILITY = z.enum(["private", "team", "firm", "external", "public"]);
68
552
  defineTable({
@@ -1547,7 +2031,7 @@ defineTable({
1547
2031
  "toNodeId": z.string().optional(),
1548
2032
  "sourceGlobalId": z.string().optional(),
1549
2033
  "targetGlobalId": z.string().optional(),
1550
- "edgeType": EDGE_TYPE,
2034
+ "edgeType": STORAGE_EDGE_TYPE,
1551
2035
  "edgeTier": z.string().optional(),
1552
2036
  "domainNamespace": z.string().optional(),
1553
2037
  "constraint": z.string().optional(),
@@ -3880,7 +4364,9 @@ defineTable({
3880
4364
  "defaultProjectVisibility": z.enum(["private", "team", "firm", "external", "public"]).optional(),
3881
4365
  "deployments": z.record(z.object({
3882
4366
  "url": z.string(),
3883
- "encryptedDeployKey": z.string()
4367
+ "target": z.enum(["kernelDeployment", "appDeployment"]).optional(),
4368
+ "encryptedDeployKey": z.string().optional(),
4369
+ "credentialRef": z.string().optional()
3884
4370
  })).optional(),
3885
4371
  "metadata": z.record(z.any()).optional(),
3886
4372
  "createdBy": z.string().optional(),
@@ -4316,6 +4802,128 @@ var edgePolicyManifest = {
4316
4802
  }
4317
4803
  ]
4318
4804
  };
4805
+
4806
+ // ../contracts/src/tenant-client.contract.ts
4807
+ var TENANT_CLIENT_INSTALLABLE_PACKAGES = [
4808
+ {
4809
+ packageName: "@lucern/access-control",
4810
+ role: "runtime_entrypoint",
4811
+ directTenantImport: true
4812
+ },
4813
+ {
4814
+ packageName: "@lucern/agent",
4815
+ role: "platform_runtime",
4816
+ directTenantImport: false
4817
+ },
4818
+ {
4819
+ packageName: "@lucern/auth",
4820
+ role: "sdk_dependency",
4821
+ directTenantImport: false
4822
+ },
4823
+ {
4824
+ packageName: "@lucern/cli",
4825
+ role: "developer_tool",
4826
+ directTenantImport: false
4827
+ },
4828
+ {
4829
+ packageName: "@lucern/client-core",
4830
+ role: "sdk_dependency",
4831
+ directTenantImport: false
4832
+ },
4833
+ {
4834
+ packageName: "@lucern/confidence",
4835
+ role: "sdk_dependency",
4836
+ directTenantImport: false
4837
+ },
4838
+ {
4839
+ packageName: "@lucern/config",
4840
+ role: "configuration",
4841
+ directTenantImport: false
4842
+ },
4843
+ {
4844
+ packageName: "@lucern/contracts",
4845
+ role: "contract_entrypoint",
4846
+ directTenantImport: true
4847
+ },
4848
+ {
4849
+ packageName: "@lucern/control-plane",
4850
+ role: "platform_runtime",
4851
+ directTenantImport: false
4852
+ },
4853
+ {
4854
+ packageName: "@lucern/developer-kit",
4855
+ role: "developer_tool",
4856
+ directTenantImport: false
4857
+ },
4858
+ {
4859
+ packageName: "@lucern/events",
4860
+ role: "sdk_dependency",
4861
+ directTenantImport: false
4862
+ },
4863
+ {
4864
+ packageName: "@lucern/graph-primitives",
4865
+ role: "sdk_dependency",
4866
+ directTenantImport: false
4867
+ },
4868
+ {
4869
+ packageName: "@lucern/identity",
4870
+ role: "component_runtime",
4871
+ directTenantImport: false
4872
+ },
4873
+ {
4874
+ packageName: "@lucern/mcp",
4875
+ role: "runtime_entrypoint",
4876
+ directTenantImport: true
4877
+ },
4878
+ {
4879
+ packageName: "@lucern/pack-host",
4880
+ role: "platform_runtime",
4881
+ directTenantImport: false
4882
+ },
4883
+ {
4884
+ packageName: "@lucern/pack-installer",
4885
+ role: "developer_tool",
4886
+ directTenantImport: false
4887
+ },
4888
+ {
4889
+ packageName: "@lucern/proof-compiler",
4890
+ role: "developer_tool",
4891
+ directTenantImport: false
4892
+ },
4893
+ {
4894
+ packageName: "@lucern/react",
4895
+ role: "runtime_entrypoint",
4896
+ directTenantImport: true
4897
+ },
4898
+ {
4899
+ packageName: "@lucern/reasoning-kernel",
4900
+ role: "component_runtime",
4901
+ directTenantImport: false
4902
+ },
4903
+ {
4904
+ packageName: "@lucern/sdk",
4905
+ role: "runtime_entrypoint",
4906
+ directTenantImport: true
4907
+ },
4908
+ {
4909
+ packageName: "@lucern/server-core",
4910
+ role: "platform_runtime",
4911
+ directTenantImport: false
4912
+ },
4913
+ {
4914
+ packageName: "@lucern/testing",
4915
+ role: "test_support",
4916
+ directTenantImport: false
4917
+ },
4918
+ {
4919
+ packageName: "@lucern/types",
4920
+ role: "contract_entrypoint",
4921
+ directTenantImport: true
4922
+ }
4923
+ ];
4924
+ TENANT_CLIENT_INSTALLABLE_PACKAGES.map(
4925
+ (entry) => entry.packageName
4926
+ );
4319
4927
  z.object({
4320
4928
  manifestVersion: z.literal("1.0.0"),
4321
4929
  rules: z.array(
@@ -5077,6 +5685,14 @@ var ADD_WORKTREE = {
5077
5685
  description: "Check out a branch into an active worktree for investigation. Like `git worktree add <branch>` \u2014 creates independent working state on a thematic branch. Beliefs committed within the worktree can be freely amended (draft code on a feature branch). When investigation is complete, `merge` integrates findings into main.",
5078
5686
  parameters: {
5079
5687
  title: { type: "string", description: "Worktree name/objective" },
5688
+ name: {
5689
+ type: "string",
5690
+ description: "Optional storage-name alias for callers that already use backend naming"
5691
+ },
5692
+ projectId: {
5693
+ type: "string",
5694
+ description: "Legacy topicId alias"
5695
+ },
5080
5696
  topicId: { type: "string", description: "Optional topic scope hint" },
5081
5697
  branchId: {
5082
5698
  type: "string",
@@ -5090,14 +5706,87 @@ var ADD_WORKTREE = {
5090
5706
  type: "string",
5091
5707
  description: "The testable claim this worktree investigates"
5092
5708
  },
5709
+ rationale: {
5710
+ type: "string",
5711
+ description: "Why this worktree exists and why it belongs in the campaign"
5712
+ },
5713
+ worktreeType: {
5714
+ type: "string",
5715
+ description: "Schema-enum worktree type used by the kernel lifecycle and retrieval layers"
5716
+ },
5717
+ gate: {
5718
+ type: "string",
5719
+ description: "Exit gate name for this worktree"
5720
+ },
5721
+ startDate: {
5722
+ type: "number",
5723
+ description: "Planned start timestamp in milliseconds since epoch"
5724
+ },
5725
+ endDate: {
5726
+ type: "number",
5727
+ description: "Planned end timestamp in milliseconds since epoch"
5728
+ },
5729
+ durationWeeks: {
5730
+ type: "number",
5731
+ description: "Planned duration in weeks"
5732
+ },
5733
+ confidenceImpact: {
5734
+ type: "string",
5735
+ description: "Expected confidence impact if the worktree succeeds",
5736
+ enum: ["high", "medium", "low"]
5737
+ },
5738
+ beliefFocus: {
5739
+ type: "string",
5740
+ description: "Natural-language focus spanning the target belief neighborhood"
5741
+ },
5093
5742
  beliefIds: {
5094
5743
  type: "array",
5095
- description: "Beliefs to test in this worktree"
5744
+ description: "Legacy alias for targetBeliefIds"
5745
+ },
5746
+ beliefs: {
5747
+ type: "array",
5748
+ description: "Legacy alias for targetBeliefIds"
5749
+ },
5750
+ targetBeliefIds: {
5751
+ type: "array",
5752
+ description: "Belief node IDs this worktree is expected to test or update"
5753
+ },
5754
+ targetQuestionIds: {
5755
+ type: "array",
5756
+ description: "Question node IDs this worktree is expected to answer"
5757
+ },
5758
+ keyQuestions: {
5759
+ type: "array",
5760
+ description: "Inline key question objects with question, optional status, answer, answerConfidence, and linkedQuestionId"
5761
+ },
5762
+ evidenceSignals: {
5763
+ type: "array",
5764
+ description: "Evidence signal objects with signal, optional collected state, progress, and notes"
5765
+ },
5766
+ decisionGate: {
5767
+ type: "object",
5768
+ description: "Decision gate object with goCriteria, noGoSignals, optional verdict, rationale, decidedAt, and decidedBy"
5769
+ },
5770
+ goCriteria: {
5771
+ type: "array",
5772
+ description: "Shorthand go criteria used to build decisionGate"
5773
+ },
5774
+ noGoSignals: {
5775
+ type: "array",
5776
+ description: "Shorthand no-go signals used to build decisionGate"
5777
+ },
5778
+ proofArtifacts: {
5779
+ type: "array",
5780
+ description: "Expected proof artifacts required to close the worktree"
5096
5781
  },
5097
5782
  autoShape: {
5098
5783
  type: "boolean",
5099
5784
  description: "Whether to invoke inquiry auto-shaping during worktree creation"
5100
5785
  },
5786
+ autoFixPolicy: {
5787
+ type: "object",
5788
+ description: "Policy for permitted automatic remediation inside the worktree"
5789
+ },
5101
5790
  domainPackId: {
5102
5791
  type: "string",
5103
5792
  description: "Optional domain pack whose shaping hooks should influence generated questions and tasks"
@@ -5126,9 +5815,17 @@ var ADD_WORKTREE = {
5126
5815
  type: "array",
5127
5816
  description: "Worktree IDs blocked by this worktree"
5128
5817
  },
5129
- gate: {
5818
+ staffingHint: {
5130
5819
  type: "string",
5131
- description: "Exit gate name for this worktree"
5820
+ description: "Suggested staffing or agent allocation note"
5821
+ },
5822
+ lensId: {
5823
+ type: "string",
5824
+ description: "Lens that scopes this worktree when applicable"
5825
+ },
5826
+ lastReconciledAt: {
5827
+ type: "number",
5828
+ description: "Timestamp when worktree metadata was last reconciled"
5132
5829
  }
5133
5830
  },
5134
5831
  required: ["title", "topicId"],
@@ -5158,7 +5855,7 @@ var MERGE = {
5158
5855
  worktreeId: { type: "string", description: "The worktree to merge" },
5159
5856
  outcomes: {
5160
5857
  type: "array",
5161
- description: "Scoring outcomes for each belief: { beliefId, confidence, rationale }"
5858
+ description: "Merge outcomes as key-finding strings, or scoring outcomes for beliefs: { beliefId, confidence, rationale }"
5162
5859
  },
5163
5860
  summary: { type: "string", description: "Overall findings summary" }
5164
5861
  },
@@ -5712,6 +6409,74 @@ var GET_GRAPH_STRUCTURE_ANALYSIS = {
5712
6409
  ontologyPrimitive: "graph",
5713
6410
  tier: "showcase"
5714
6411
  };
6412
+ var LIST_GRAPH_INTELLIGENCE_QUERIES = {
6413
+ name: "list_graph_intelligence_queries",
6414
+ description: "List the Graph Intelligence query catalog that powers structural graph analysis experiences. Returns categories, query IDs, prompt templates, modes, and the public tool plan each query can use.",
6415
+ parameters: {
6416
+ categoryId: {
6417
+ type: "string",
6418
+ description: "Optional category filter, such as problems or strategic"
6419
+ },
6420
+ mode: {
6421
+ type: "string",
6422
+ description: "Optional mode filter: core, bias, stress, operational, alpha, semantic, or evidence"
6423
+ }
6424
+ },
6425
+ required: [],
6426
+ response: {
6427
+ description: "Graph Intelligence query catalog and mode-to-tool mapping",
6428
+ fields: {
6429
+ categories: "array \u2014 query categories",
6430
+ queries: "array \u2014 query definitions with prompt templates and tools",
6431
+ quickQueries: "array \u2014 recommended one-click query presets",
6432
+ publicToolNamesByMode: "object \u2014 public tool names available to each Graph Intelligence mode"
6433
+ }
6434
+ },
6435
+ ownerModule: "graph-intelligence",
6436
+ ontologyPrimitive: "graph",
6437
+ tier: "showcase"
6438
+ };
6439
+ var RUN_GRAPH_INTELLIGENCE_QUERY = {
6440
+ name: "run_graph_intelligence_query",
6441
+ description: "Run a named Graph Intelligence query against a tenant topic graph. Returns the selected query, prompt, deterministic graph-analysis bundle, graph context, and public tool plan for model synthesis.",
6442
+ parameters: {
6443
+ topicId: { type: "string", description: "Topic to analyze" },
6444
+ queryId: {
6445
+ type: "string",
6446
+ description: "Graph Intelligence query ID, such as confirmation-bias, pre-mortem, or thesis-summary"
6447
+ },
6448
+ prompt: {
6449
+ type: "string",
6450
+ description: "Optional custom prompt for custom analysis runs"
6451
+ },
6452
+ input: {
6453
+ type: "string",
6454
+ description: "Optional entity, theme, belief, company, or search text for input-driven queries"
6455
+ },
6456
+ mode: {
6457
+ type: "string",
6458
+ description: "Optional mode override: core, bias, stress, operational, alpha, semantic, or evidence"
6459
+ },
6460
+ limit: {
6461
+ type: "number",
6462
+ description: "Maximum graph context rows to return"
6463
+ }
6464
+ },
6465
+ required: ["topicId"],
6466
+ response: {
6467
+ description: "Graph Intelligence query result bundle ready for model or prompt-library synthesis",
6468
+ fields: {
6469
+ query: "object \u2014 selected query definition",
6470
+ prompt: "string \u2014 resolved prompt template",
6471
+ toolPlan: "array \u2014 public tools and args the model can call next",
6472
+ analysis: "object \u2014 structure, coverage, gap, and confirmation-bias analysis",
6473
+ context: "object \u2014 sampled beliefs, questions, evidence, edges, and contradictions"
6474
+ }
6475
+ },
6476
+ ownerModule: "graph-intelligence",
6477
+ ontologyPrimitive: "graph",
6478
+ tier: "showcase"
6479
+ };
5715
6480
  var GET_FALSIFICATION_QUESTIONS = {
5716
6481
  name: "get_falsification_questions",
5717
6482
  description: "Generate Popperian falsification questions for beliefs. Like `git test` \u2014 identifies the questions most likely to disprove current beliefs. Karl Popper as a tool: surfaces what would need to be true to invalidate each belief.",
@@ -8177,6 +8942,69 @@ var GENERATE_SESSION_HANDOFF = {
8177
8942
  tier: "showcase",
8178
8943
  internal: true
8179
8944
  };
8945
+ var BEGIN_BUILD_SESSION = {
8946
+ name: "begin_build_session",
8947
+ description: "Bootstrap a coding build session for a Lucern worktree. Like `git worktree add` plus `git status` \u2014 returns the compact context packet an agent needs before editing.",
8948
+ parameters: {
8949
+ worktreeId: {
8950
+ type: "string",
8951
+ description: "The Lucern worktree ID to bootstrap."
8952
+ },
8953
+ branch: {
8954
+ type: "string",
8955
+ description: "Optional git branch name. Auto-generated from the worktree name when omitted."
8956
+ },
8957
+ branchBase: {
8958
+ type: "string",
8959
+ description: 'Base branch for the feature branch. Default: "staging".'
8960
+ },
8961
+ prBase: {
8962
+ type: "string",
8963
+ description: 'Target branch for the PR. Default: "staging".'
8964
+ },
8965
+ sessionMode: {
8966
+ type: "string",
8967
+ description: 'Session mode: "async" for Codex/headless or "interactive" for live sessions.',
8968
+ enum: ["async", "interactive"]
8969
+ },
8970
+ activateIfPlanning: {
8971
+ type: "boolean",
8972
+ description: "When true, automatically activate a planning worktree during bootstrap."
8973
+ }
8974
+ },
8975
+ required: ["worktreeId"],
8976
+ response: {
8977
+ description: "A compact build-session packet with worktree metadata, graph anchors, questions, dependencies, and git defaults.",
8978
+ fields: {
8979
+ topicId: "string \u2014 canonical topic scope",
8980
+ topicName: "string \u2014 human-readable topic name",
8981
+ worktreeId: "string \u2014 worktree ID",
8982
+ worktreeName: "string \u2014 human-readable worktree name",
8983
+ branch: "string \u2014 git branch name",
8984
+ branchBase: "string \u2014 base branch",
8985
+ prBase: "string \u2014 PR target branch",
8986
+ campaign: "number | null \u2014 top-level pipeline campaign",
8987
+ lane: "string \u2014 campaign lane",
8988
+ gate: "string \u2014 exit gate",
8989
+ hypothesis: "string \u2014 worktree hypothesis",
8990
+ focus: "string \u2014 session focus",
8991
+ status: "string \u2014 worktree status after optional activation",
8992
+ sessionMode: "string \u2014 async | interactive",
8993
+ targetBeliefIds: "array \u2014 scoped belief IDs",
8994
+ targetQuestionIds: "array \u2014 scoped question IDs",
8995
+ topBeliefs: "array \u2014 highest-confidence scoped beliefs",
8996
+ openQuestions: "array \u2014 open scoped questions",
8997
+ resolvedDecisions: "array \u2014 answered questions summarized for the session",
8998
+ dependencies: "array \u2014 upstream worktrees",
8999
+ unblocks: "array \u2014 downstream worktrees",
9000
+ mergeOrderNotes: "string \u2014 merge ordering advisory"
9001
+ }
9002
+ },
9003
+ ownerModule: "bootstrap",
9004
+ ontologyPrimitive: "worktree",
9005
+ tier: "showcase",
9006
+ internal: true
9007
+ };
8180
9008
  var MCP_TOOL_CONTRACTS = {
8181
9009
  // Belief lifecycle (commit, amend, fork, archive)
8182
9010
  create_belief: CREATE_BELIEF,
@@ -8224,6 +9052,8 @@ var MCP_TOOL_CONTRACTS = {
8224
9052
  // Graph intelligence (showcase)
8225
9053
  detect_confirmation_bias: DETECT_CONFIRMATION_BIAS,
8226
9054
  get_graph_structure_analysis: GET_GRAPH_STRUCTURE_ANALYSIS,
9055
+ list_graph_intelligence_queries: LIST_GRAPH_INTELLIGENCE_QUERIES,
9056
+ run_graph_intelligence_query: RUN_GRAPH_INTELLIGENCE_QUERY,
8227
9057
  get_falsification_questions: GET_FALSIFICATION_QUESTIONS,
8228
9058
  // Evidence operations (workhorse)
8229
9059
  search_evidence: SEARCH_EVIDENCE,
@@ -8270,6 +9100,7 @@ var MCP_TOOL_CONTRACTS = {
8270
9100
  get_agent_inbox: GET_AGENT_INBOX,
8271
9101
  claim_files: CLAIM_FILES,
8272
9102
  generate_session_handoff: GENERATE_SESSION_HANDOFF,
9103
+ begin_build_session: BEGIN_BUILD_SESSION,
8273
9104
  // Policy / ACL (workhorse)
8274
9105
  check_permission: CHECK_PERMISSION,
8275
9106
  filter_by_permission: FILTER_BY_PERMISSION,
@@ -8405,6 +9236,8 @@ var MCP_ANALYSIS_PLATFORM_OPERATION_NAMES = [
8405
9236
  "traverse_graph",
8406
9237
  "get_graph_neighborhood",
8407
9238
  "get_graph_structure_analysis",
9239
+ "list_graph_intelligence_queries",
9240
+ "run_graph_intelligence_query",
8408
9241
  "find_contradictions",
8409
9242
  "flag_contradiction",
8410
9243
  "detect_confirmation_bias",
@@ -8483,6 +9316,7 @@ var PLATFORM_INTERNAL_OPERATION_NAMES = [
8483
9316
  "get_change_history",
8484
9317
  "get_failure_log",
8485
9318
  "record_attempt",
9319
+ "begin_build_session",
8486
9320
  "push",
8487
9321
  "open_pull_request",
8488
9322
  "record_judgment",
@@ -8537,7 +9371,6 @@ var SDK_ONLY_OPERATION_NAMES = [
8537
9371
  "find_semantic_orphans"
8538
9372
  ];
8539
9373
  var MCP_ONLY_INTERNAL_OPERATION_NAMES = [
8540
- "begin_build_session",
8541
9374
  "evaluate_engineering_contract",
8542
9375
  "evaluate_research_contract"
8543
9376
  ];
@@ -8923,8 +9756,31 @@ function assertSurfaceCoverage(contracts) {
8923
9756
  }
8924
9757
  }
8925
9758
  }
8926
-
8927
- // ../contracts/src/function-registry/context.ts
9759
+ var jsonRecordSchema2 = z.record(z.unknown());
9760
+ var observationArgs = z.object({
9761
+ topicId: z.string().optional().describe("Topic scope for the observation."),
9762
+ summary: z.string().describe("Short observation summary."),
9763
+ text: z.string().optional().describe("Canonical observation text alias."),
9764
+ title: z.string().optional().describe("Optional observation title."),
9765
+ content: z.string().optional().describe("Optional rich observation content."),
9766
+ contentType: z.string().optional().describe("Observation content type."),
9767
+ kind: z.string().optional().describe("Evidence kind to store."),
9768
+ observationType: z.string().optional().describe("Observation type."),
9769
+ tags: z.array(z.string()).optional().describe("Observation tags."),
9770
+ source: z.string().optional().describe("Observation source label."),
9771
+ sourceType: z.string().optional().describe("Evidence source type."),
9772
+ externalSourceType: z.string().optional().describe("External source type for imported observations."),
9773
+ sourceUrl: z.string().optional().describe("Canonical source URL."),
9774
+ confidence: z.number().optional().describe("Observation confidence."),
9775
+ metadata: jsonRecordSchema2.optional().describe("Observation metadata."),
9776
+ rationale: z.string().optional().describe("Why this observation should be recorded.")
9777
+ });
9778
+ var observationContextArgs = z.object({
9779
+ topicId: z.string().describe("Topic scope."),
9780
+ query: z.string().optional().describe("Optional context query."),
9781
+ limit: z.number().optional().describe("Maximum observations to return."),
9782
+ status: z.string().optional().describe("Observation status filter.")
9783
+ });
8928
9784
  var observationInput = (input, context) => withUserId(
8929
9785
  compactRecord4({
8930
9786
  projectId: input.projectId,
@@ -8983,7 +9839,8 @@ var contextContracts = [
8983
9839
  observationId: output && typeof output === "object" ? output.nodeId : void 0,
8984
9840
  observationType: input.observationType
8985
9841
  })
8986
- }
9842
+ },
9843
+ args: observationArgs
8987
9844
  }),
8988
9845
  surfaceContract({
8989
9846
  name: "get_observation_context",
@@ -9004,7 +9861,8 @@ var contextContracts = [
9004
9861
  status: input.status,
9005
9862
  userId: input.userId
9006
9863
  })
9007
- }
9864
+ },
9865
+ args: observationContextArgs
9008
9866
  })
9009
9867
  ];
9010
9868
 
@@ -9067,8 +9925,45 @@ var identityContracts = [
9067
9925
  }
9068
9926
  })
9069
9927
  ];
9070
-
9071
- // ../contracts/src/function-registry/beliefs.ts
9928
+ var jsonRecordSchema3 = z.record(z.unknown());
9929
+ var sourceTypeSchema = z.enum(["human", "ai_extracted", "ai_generated"]);
9930
+ var reversibilitySchema = z.enum([
9931
+ "irreversible",
9932
+ "hard_to_reverse",
9933
+ "reversible",
9934
+ "trivial"
9935
+ ]);
9936
+ var predictionMetaSchema = z.object({
9937
+ isPrediction: z.boolean().describe("Whether this belief is a prediction."),
9938
+ registeredAt: z.number().describe("Timestamp when the prediction was registered."),
9939
+ expectedBy: z.number().optional().describe("Timestamp when the prediction should be evaluated.")
9940
+ });
9941
+ var createBeliefArgs = z.object({
9942
+ canonicalText: z.string().describe("The belief statement the agent holds to be true."),
9943
+ topicId: z.string().optional().describe("Topic scope hint for the belief."),
9944
+ baseRate: z.number().optional().describe("Prior base rate used to seed the vacuous opinion."),
9945
+ beliefType: z.string().optional().describe("Schema belief type."),
9946
+ metadata: jsonRecordSchema3.optional().describe("Extra metadata merged into the belief node."),
9947
+ rationale: z.string().optional().describe("Why this belief should enter the reasoning graph."),
9948
+ pillar: z.string().optional().describe("Innovation pillar or product pillar associated with the belief."),
9949
+ worktreeId: z.string().optional().describe("Worktree responsible for creating or testing this belief."),
9950
+ sourceBeliefIds: z.array(z.string()).optional().describe("Source belief IDs this belief derives from."),
9951
+ sourceType: sourceTypeSchema.optional().describe("Actor/source class that produced the belief."),
9952
+ reversibility: reversibilitySchema.optional().describe("How reversible the belief's implied decision is."),
9953
+ predictionMeta: predictionMetaSchema.optional().describe("Prediction lifecycle metadata when this belief is a forecast.")
9954
+ });
9955
+ var forkBeliefArgs = z.object({
9956
+ nodeId: z.string().describe("The scored belief to fork from."),
9957
+ newFormulation: z.string().describe("The evolved belief statement."),
9958
+ forkReason: z.enum([
9959
+ "refinement",
9960
+ "contradiction_response",
9961
+ "scope_change",
9962
+ "confidence_collapse",
9963
+ "manual"
9964
+ ]).describe("Why this fork was created."),
9965
+ rationale: z.string().optional().describe("Why the fork is warranted.")
9966
+ });
9072
9967
  var beliefLookupInput = (input) => compactRecord4({
9073
9968
  nodeId: input.nodeId ?? input.id ?? input.beliefId,
9074
9969
  beliefId: input.beliefId
@@ -9143,7 +10038,8 @@ var beliefsContracts = [
9143
10038
  functionName: "create",
9144
10039
  kind: "mutation",
9145
10040
  inputProjection: createBeliefInput
9146
- }
10041
+ },
10042
+ args: createBeliefArgs
9147
10043
  }),
9148
10044
  surfaceContract({
9149
10045
  name: "get_belief",
@@ -9234,7 +10130,8 @@ var beliefsContracts = [
9234
10130
  functionName: "forkBelief",
9235
10131
  kind: "mutation",
9236
10132
  inputProjection: forkBeliefInput
9237
- }
10133
+ },
10134
+ args: forkBeliefArgs
9238
10135
  }),
9239
10136
  surfaceContract({
9240
10137
  name: "archive_belief",
@@ -9315,8 +10212,46 @@ var beliefsContracts = [
9315
10212
  }
9316
10213
  })
9317
10214
  ];
9318
-
9319
- // ../contracts/src/function-registry/evidence.ts
10215
+ var jsonRecordSchema4 = z.record(z.unknown());
10216
+ var evidenceRelationSchema = z.enum(["supports", "contradicts", "neutral"]);
10217
+ var createEvidenceArgs = z.object({
10218
+ topicId: z.string().optional().describe("Topic scope for the evidence."),
10219
+ text: z.string().describe("Canonical evidence text."),
10220
+ source: z.string().optional().describe("Source URL or source label."),
10221
+ sourceUrl: z.string().optional().describe("Canonical source URL."),
10222
+ targetId: z.string().optional().describe("Belief or question identifier to link immediately."),
10223
+ linkedBeliefNodeId: z.string().optional().describe("Belief node this evidence bears on."),
10224
+ evidenceRelation: evidenceRelationSchema.optional().describe("How the evidence relates to the linked belief."),
10225
+ confidence: z.number().optional().describe("Confidence in the evidence relation."),
10226
+ weight: z.number().optional().describe("Support weight from -1.0 to +1.0."),
10227
+ metadata: jsonRecordSchema4.optional().describe("Metadata merged into the canonical evidence node."),
10228
+ rationale: z.string().describe("Why this evidence should enter the reasoning graph."),
10229
+ reasoning: z.string().optional().describe("Reasoning note preserved in evidence metadata."),
10230
+ title: z.string().optional().describe("Optional short title."),
10231
+ content: z.string().optional().describe("Optional long-form content."),
10232
+ contentType: z.string().optional().describe("Content format or MIME hint."),
10233
+ kind: z.string().optional().describe("Evidence kind."),
10234
+ tags: z.array(z.string()).optional().describe("Evidence tags."),
10235
+ sourceType: z.string().optional().describe("Evidence source type."),
10236
+ externalSourceType: z.string().optional().describe("External source type for imported evidence."),
10237
+ sourceQuestionId: z.string().optional().describe("Question that sourced this evidence."),
10238
+ methodology: z.string().optional().describe("Collection methodology."),
10239
+ informationAsymmetry: z.string().optional().describe("Information asymmetry class."),
10240
+ sourceDescription: z.string().optional().describe("Human-readable source description.")
10241
+ });
10242
+ var addEvidenceArgs = z.object({
10243
+ canonicalText: z.string().describe("The evidence statement."),
10244
+ text: z.string().optional().describe("Canonical evidence text alias used by newer callers."),
10245
+ topicId: z.string().optional().describe("Topic scope hint."),
10246
+ sourceUrl: z.string().optional().describe("URL of the source material."),
10247
+ targetNodeId: z.string().describe("The belief this evidence bears on."),
10248
+ weight: z.number().optional().describe("Support weight from -1.0 to +1.0."),
10249
+ reasoning: z.string().describe("Why this evidence is relevant to the target belief."),
10250
+ title: z.string().optional().describe("Optional short title."),
10251
+ content: z.string().optional().describe("Optional long-form evidence content."),
10252
+ contentType: z.string().optional().describe("Content format or MIME hint."),
10253
+ metadata: jsonRecordSchema4.optional().describe("Optional metadata merged into the evidence node.")
10254
+ });
9320
10255
  var evidenceIdInput = (input) => compactRecord4({
9321
10256
  evidenceId: input.evidenceId,
9322
10257
  insightId: input.insightId,
@@ -9391,7 +10326,8 @@ var evidenceContracts = [
9391
10326
  functionName: "create",
9392
10327
  kind: "mutation",
9393
10328
  inputProjection: createEvidenceInput
9394
- }
10329
+ },
10330
+ args: createEvidenceArgs
9395
10331
  }),
9396
10332
  surfaceContract({
9397
10333
  name: "add_evidence",
@@ -9427,7 +10363,8 @@ var evidenceContracts = [
9427
10363
  context
9428
10364
  );
9429
10365
  }
9430
- }
10366
+ },
10367
+ args: addEvidenceArgs
9431
10368
  }),
9432
10369
  surfaceContract({
9433
10370
  name: "get_evidence",
@@ -9534,8 +10471,91 @@ var evidenceContracts = [
9534
10471
  }
9535
10472
  })
9536
10473
  ];
9537
-
9538
- // ../contracts/src/function-registry/questions.ts
10474
+ var jsonRecordSchema5 = z.record(z.unknown());
10475
+ var questionPrioritySchema = z.enum(["urgent", "high", "medium", "low"]);
10476
+ var kernelQuestionPrioritySchema = z.enum([
10477
+ "critical",
10478
+ "high",
10479
+ "medium",
10480
+ "low"
10481
+ ]);
10482
+ var questionTypeSchema = z.enum([
10483
+ "validation",
10484
+ "falsification",
10485
+ "assumption_probe",
10486
+ "prediction_test",
10487
+ "counterfactual",
10488
+ "discovery",
10489
+ "clarification",
10490
+ "comparison",
10491
+ "causal",
10492
+ "mechanism",
10493
+ "general"
10494
+ ]);
10495
+ var createQuestionArgs = z.object({
10496
+ text: z.string().describe("The question text."),
10497
+ question: z.string().optional().describe("Backend question text alias for kernel-native callers."),
10498
+ topicId: z.string().optional().describe("Topic scope hint."),
10499
+ priority: questionPrioritySchema.optional().describe("Human-facing question priority."),
10500
+ linkedBeliefId: z.string().optional().describe("Belief this question tests."),
10501
+ linkedBeliefNodeId: z.string().optional().describe("Belief node this question tests."),
10502
+ metadata: jsonRecordSchema5.optional().describe("Optional metadata merged into the question record."),
10503
+ category: z.string().optional().describe("Question category."),
10504
+ source: z.string().optional().describe("Question source."),
10505
+ testType: z.enum(["validates", "invalidates", "clarifies"]).optional().describe("How this question tests its linked belief."),
10506
+ importance: z.number().optional().describe("Numeric importance score."),
10507
+ epistemicUnlock: z.string().optional().describe("What this question unlocks if answered."),
10508
+ sourceQuestionIds: z.array(z.string()).optional().describe("Question IDs this question derives from."),
10509
+ linkedWorktreeId: z.string().optional().describe("Worktree this question belongs to."),
10510
+ questionType: questionTypeSchema.optional().describe("Question type."),
10511
+ questionPriority: kernelQuestionPrioritySchema.optional().describe("Kernel-native question priority.")
10512
+ });
10513
+ var refineQuestionArgs = z.object({
10514
+ id: z.string().describe("The question to refine."),
10515
+ text: z.string().describe("Updated question text."),
10516
+ question: z.string().optional().describe("Backend question text alias for kernel-native callers."),
10517
+ rationale: z.string().optional().describe("Why the question is refined."),
10518
+ category: z.string().optional().describe("Updated question category."),
10519
+ priority: questionPrioritySchema.optional().describe("Updated human-facing priority.")
10520
+ });
10521
+ var createAnswerArgs = z.object({
10522
+ questionNodeId: z.string().describe("The question node ID this answer responds to."),
10523
+ questionId: z.string().optional().describe("Question ID alias accepted by the projection."),
10524
+ answerText: z.string().describe("The answer content."),
10525
+ topicId: z.string().optional().describe("Topic scope for the answer."),
10526
+ confidence: z.string().optional().describe("Answer confidence."),
10527
+ evidenceNodeIds: z.array(z.string()).optional().describe("Evidence node IDs supporting the answer."),
10528
+ answerSource: z.string().optional().describe("How the answer was produced."),
10529
+ worktreeId: z.string().optional().describe("Worktree whose outcome produced this answer."),
10530
+ sprintId: z.string().optional().describe("Legacy sprint identifier.")
10531
+ });
10532
+ var answerQuestionArgs = z.object({
10533
+ id: z.string().describe("Canonical question ID."),
10534
+ topicId: z.string().describe("Topic scope for the answer."),
10535
+ text: z.string().describe("Answer text."),
10536
+ confidence: z.enum(["weak", "medium", "strong"]).optional().describe("Optional answer confidence."),
10537
+ evidenceIds: z.array(z.string()).optional().describe("Canonical evidence IDs supporting the answer."),
10538
+ rationale: z.string().optional().describe("Why this answer is credible."),
10539
+ questionId: z.string().optional().describe("Question ID alias accepted by the projection."),
10540
+ questionNodeId: z.string().optional().describe("Question node ID alias accepted by the projection."),
10541
+ answerText: z.string().optional().describe("Canonical answer text alias accepted by newer callers."),
10542
+ evidenceNodeIds: z.array(z.string()).optional().describe("Evidence node ID alias accepted by newer callers."),
10543
+ answerSource: z.string().optional().describe("How the answer was produced."),
10544
+ worktreeId: z.string().optional().describe("Worktree whose outcome produced this answer."),
10545
+ sprintId: z.string().optional().describe("Legacy sprint identifier.")
10546
+ });
10547
+ var missingQuestionsArgs = z.object({
10548
+ topicId: z.string().describe("Topic scope."),
10549
+ minConfidence: z.number().optional().describe("Minimum confidence threshold for missing-question checks."),
10550
+ status: z.string().optional().describe("Question status filter."),
10551
+ limit: z.number().optional().describe("Maximum questions to inspect.")
10552
+ });
10553
+ var falsificationQuestionsArgs = z.object({
10554
+ topicId: z.string().describe("Topic scope."),
10555
+ beliefIds: z.array(z.string()).optional().describe("Beliefs to generate falsification questions for."),
10556
+ status: z.string().optional().describe("Question status filter."),
10557
+ limit: z.number().optional().describe("Maximum questions to inspect.")
10558
+ });
9539
10559
  var questionNodeInput = (input) => compactRecord4({
9540
10560
  nodeId: input.nodeId ?? input.id ?? input.questionId,
9541
10561
  questionId: input.questionId
@@ -9582,7 +10602,8 @@ var questionsContracts = [
9582
10602
  functionName: "create",
9583
10603
  kind: "mutation",
9584
10604
  inputProjection: createQuestionInput
9585
- }
10605
+ },
10606
+ args: createQuestionArgs
9586
10607
  }),
9587
10608
  surfaceContract({
9588
10609
  name: "get_question",
@@ -9638,7 +10659,8 @@ var questionsContracts = [
9638
10659
  category: input.category,
9639
10660
  priority: input.priority
9640
10661
  })
9641
- }
10662
+ },
10663
+ args: refineQuestionArgs
9642
10664
  }),
9643
10665
  surfaceContract({
9644
10666
  name: "update_question_status",
@@ -9714,7 +10736,8 @@ var questionsContracts = [
9714
10736
  }),
9715
10737
  context
9716
10738
  )
9717
- }
10739
+ },
10740
+ args: createAnswerArgs
9718
10741
  }),
9719
10742
  surfaceContract({
9720
10743
  name: "answer_question",
@@ -9743,7 +10766,8 @@ var questionsContracts = [
9743
10766
  }),
9744
10767
  context
9745
10768
  )
9746
- }
10769
+ },
10770
+ args: answerQuestionArgs
9747
10771
  }),
9748
10772
  surfaceContract({
9749
10773
  name: "get_answer",
@@ -9775,7 +10799,8 @@ var questionsContracts = [
9775
10799
  functionName: "getByTopic",
9776
10800
  kind: "query",
9777
10801
  inputProjection: questionTopicInput
9778
- }
10802
+ },
10803
+ args: missingQuestionsArgs
9779
10804
  }),
9780
10805
  surfaceContract({
9781
10806
  name: "get_high_priority_questions",
@@ -9810,11 +10835,22 @@ var questionsContracts = [
9810
10835
  functionName: "getByTopic",
9811
10836
  kind: "query",
9812
10837
  inputProjection: questionTopicInput
9813
- }
10838
+ },
10839
+ args: falsificationQuestionsArgs
9814
10840
  })
9815
10841
  ];
9816
-
9817
- // ../contracts/src/function-registry/topics.ts
10842
+ var updateTopicArgs = z.object({
10843
+ id: z.string().describe("Topic ID."),
10844
+ topicId: z.string().optional().describe("Topic ID alias."),
10845
+ name: z.string().optional().describe("Topic name."),
10846
+ description: z.string().optional().describe("Topic description."),
10847
+ type: z.string().optional().describe("Topic type."),
10848
+ status: z.string().optional().describe("Topic status."),
10849
+ visibility: z.string().optional().describe("Topic visibility."),
10850
+ ontologyId: z.string().optional().describe("Ontology to bind."),
10851
+ clearOntologyId: z.boolean().optional().describe("Whether to clear the ontology binding."),
10852
+ metadata: z.record(z.unknown()).optional().describe("Topic metadata.")
10853
+ });
9818
10854
  var topicIdInput = (input) => compactRecord4({
9819
10855
  id: input.id ?? input.topicId
9820
10856
  });
@@ -9895,7 +10931,8 @@ var topicsContracts = [
9895
10931
  functionName: "update",
9896
10932
  kind: "mutation",
9897
10933
  inputProjection: updateTopicInput
9898
- }
10934
+ },
10935
+ args: updateTopicArgs
9899
10936
  }),
9900
10937
  surfaceContract({
9901
10938
  name: "get_topic_tree",
@@ -9914,8 +10951,27 @@ var topicsContracts = [
9914
10951
  }
9915
10952
  })
9916
10953
  ];
9917
-
9918
- // ../contracts/src/function-registry/lenses.ts
10954
+ var lensPerspectiveSchema = z.enum([
10955
+ "investigation",
10956
+ "monitoring",
10957
+ "analysis",
10958
+ "comparison",
10959
+ "taxonomy"
10960
+ ]);
10961
+ var jsonRecordSchema6 = z.record(z.unknown());
10962
+ var createLensArgs = z.object({
10963
+ name: z.string().describe("Lens name."),
10964
+ workspaceId: z.string().optional().describe("Workspace scope for the lens."),
10965
+ topicId: z.string().optional().describe("Originating topic scope."),
10966
+ description: z.string().optional().describe("What this lens investigates or monitors."),
10967
+ perspectiveType: lensPerspectiveSchema.describe("Perspective type."),
10968
+ promptTemplates: z.array(jsonRecordSchema6).optional().describe("Prompt templates used through this lens."),
10969
+ workflowTemplates: z.array(jsonRecordSchema6).optional().describe("Guided workflow templates."),
10970
+ taskTemplates: z.array(jsonRecordSchema6).optional().describe("Default task templates."),
10971
+ questionTemplates: z.array(jsonRecordSchema6).optional().describe("Default question templates."),
10972
+ filterCriteria: jsonRecordSchema6.optional().describe("Belief/evidence filtering criteria."),
10973
+ metadata: jsonRecordSchema6.optional().describe("Additional lens metadata.")
10974
+ });
9919
10975
  var createLensInput = (input, context) => compactRecord4({
9920
10976
  name: input.name,
9921
10977
  description: input.description,
@@ -9952,7 +11008,8 @@ var lensesContracts = [
9952
11008
  functionName: "create",
9953
11009
  kind: "mutation",
9954
11010
  inputProjection: createLensInput
9955
- }
11011
+ },
11012
+ args: createLensArgs
9956
11013
  }),
9957
11014
  surfaceContract({
9958
11015
  name: "list_lenses",
@@ -10014,8 +11071,18 @@ var lensesContracts = [
10014
11071
  }
10015
11072
  })
10016
11073
  ];
10017
-
10018
- // ../contracts/src/function-registry/ontologies.ts
11074
+ var updateOntologyArgs = z.object({
11075
+ id: z.string().describe("Ontology definition ID."),
11076
+ ontologyId: z.string().optional().describe("Ontology ID alias."),
11077
+ name: z.string().optional().describe("Ontology display name."),
11078
+ description: z.string().optional().describe("Ontology description."),
11079
+ status: z.string().optional().describe("Ontology lifecycle status.")
11080
+ });
11081
+ var ontologyVersionLifecycleArgs = z.object({
11082
+ id: z.string().describe("Ontology version ID."),
11083
+ versionId: z.string().optional().describe("Ontology version ID alias."),
11084
+ ontologyId: z.string().optional().describe("Ontology definition ID.")
11085
+ });
10019
11086
  var ontologyIdInput = (input) => compactRecord4({
10020
11087
  id: input.id ?? input.ontologyId
10021
11088
  });
@@ -10094,11 +11161,11 @@ var ontologiesContracts = [
10094
11161
  id: input.id ?? input.ontologyId,
10095
11162
  name: input.name,
10096
11163
  description: input.description,
10097
- parentOntologyId: input.parentOntologyId,
10098
11164
  status: input.status,
10099
11165
  actorId: input.actorId
10100
11166
  })
10101
- }
11167
+ },
11168
+ args: updateOntologyArgs
10102
11169
  }),
10103
11170
  surfaceContract({
10104
11171
  name: "archive_ontology",
@@ -10181,7 +11248,8 @@ var ontologiesContracts = [
10181
11248
  functionName: "publishOntologyVersion",
10182
11249
  kind: "mutation",
10183
11250
  inputProjection: ontologyVersionIdInput
10184
- }
11251
+ },
11252
+ args: ontologyVersionLifecycleArgs
10185
11253
  }),
10186
11254
  surfaceContract({
10187
11255
  name: "deprecate_ontology_version",
@@ -10197,7 +11265,8 @@ var ontologiesContracts = [
10197
11265
  functionName: "deprecateOntologyVersion",
10198
11266
  kind: "mutation",
10199
11267
  inputProjection: ontologyVersionIdInput
10200
- }
11268
+ },
11269
+ args: ontologyVersionLifecycleArgs
10201
11270
  }),
10202
11271
  surfaceContract({
10203
11272
  name: "resolve_effective_ontology",
@@ -10216,8 +11285,76 @@ var ontologiesContracts = [
10216
11285
  }
10217
11286
  })
10218
11287
  ];
10219
-
10220
- // ../contracts/src/function-registry/worktrees.ts
11288
+ var autoFixPolicyInputSchema = z.object({
11289
+ enabled: z.boolean().optional().describe("Whether automatic remediation is enabled."),
11290
+ mode: z.string().optional().describe("Automation mode for worktree auto-fixes."),
11291
+ maxAttempts: z.number().optional().describe("Maximum number of auto-fix attempts."),
11292
+ reviewer: z.string().optional().describe("Reviewer responsible for auto-fix oversight."),
11293
+ maxActionsPerRun: z.number().optional().describe("Maximum number of auto-fix actions per run."),
11294
+ permittedMutationTiers: z.array(z.enum(["read_only", "low_risk_write", "high_risk_write"])).optional().describe("Mutation tiers the auto-fix worker may execute."),
11295
+ requireAuditTrail: z.boolean().optional().describe("Whether auto-fix actions must write an audit trail."),
11296
+ escalationGate: z.string().optional().describe("Gate to trigger when auto-fix policy requires escalation.")
11297
+ }).passthrough().describe("Policy for permitted automatic remediation inside the worktree.");
11298
+ var worktreeKeyQuestionInputSchema = z.object({
11299
+ question: z.string().describe("Question the worktree must resolve."),
11300
+ status: z.enum(["open", "answered", "forked"]).optional().describe("Current disposition of the key question."),
11301
+ answer: z.string().optional().describe("Captured answer when the key question is resolved."),
11302
+ answerConfidence: z.enum(["high", "medium", "low"]).optional().describe("Confidence in the captured answer."),
11303
+ linkedQuestionId: z.string().optional().describe("Canonical question node linked to this key question.")
11304
+ }).passthrough().describe("Question contract embedded in the worktree plan.");
11305
+ var worktreeEvidenceSignalInputSchema = z.object({
11306
+ signal: z.string().describe("Evidence signal the worktree should collect."),
11307
+ collected: z.boolean().optional().describe("Whether the signal has already been collected."),
11308
+ progress: z.string().optional().describe("Collection progress note for the signal."),
11309
+ notes: z.string().optional().describe("Additional evidence collection notes.")
11310
+ }).passthrough().describe("Evidence signal embedded in the worktree plan.");
11311
+ var worktreeDecisionGateInputSchema = z.object({
11312
+ goCriteria: z.array(z.string()).describe("Criteria that must hold for the worktree to proceed."),
11313
+ noGoSignals: z.array(z.string()).describe("Signals that stop or redirect the worktree."),
11314
+ verdict: z.enum(["go", "no_go", "pivot", "pending"]).optional().describe("Current decision verdict for the worktree gate."),
11315
+ verdictRationale: z.string().optional().describe("Rationale supporting the current gate verdict."),
11316
+ decidedAt: z.number().optional().describe("Timestamp when the gate verdict was decided."),
11317
+ decidedBy: z.string().optional().describe("Actor that decided the gate verdict.")
11318
+ }).passthrough().describe("Decision gate contract for worktree activation or exit.");
11319
+ var addWorktreeArgs = z.object({
11320
+ title: z.string().optional().describe("Human-readable worktree name or objective."),
11321
+ name: z.string().optional().describe("Storage-name alias for callers that already use backend naming."),
11322
+ topicId: z.string().describe("Primary topic scope for the worktree."),
11323
+ projectId: z.string().optional().describe("Legacy topicId alias."),
11324
+ branchId: z.string().optional().describe("Legacy branch identifier for compatibility with workflow callers."),
11325
+ objective: z.string().optional().describe("Reasoning objective this worktree is intended to resolve."),
11326
+ hypothesis: z.string().optional().describe("Testable claim this worktree investigates."),
11327
+ rationale: z.string().optional().describe("Why this worktree exists and why it belongs in the campaign."),
11328
+ worktreeType: z.string().optional().describe("Schema-enum worktree type used for kernel lifecycle behavior."),
11329
+ gate: z.string().optional().describe("Exit gate for this worktree."),
11330
+ startDate: z.number().optional().describe("Planned start timestamp in milliseconds since epoch."),
11331
+ endDate: z.number().optional().describe("Planned end timestamp in milliseconds since epoch."),
11332
+ durationWeeks: z.number().optional().describe("Planned duration in weeks."),
11333
+ confidenceImpact: z.enum(["high", "medium", "low"]).optional().describe("Expected confidence impact if this worktree succeeds."),
11334
+ beliefFocus: z.string().optional().describe("Natural-language focus spanning the target belief neighborhood."),
11335
+ beliefIds: z.array(z.string()).optional().describe("Legacy alias for targetBeliefIds."),
11336
+ beliefs: z.array(z.string()).optional().describe("Legacy alias for targetBeliefIds."),
11337
+ targetBeliefIds: z.array(z.string()).optional().describe("Belief node IDs this worktree is expected to test or update."),
11338
+ targetQuestionIds: z.array(z.string()).optional().describe("Question node IDs this worktree is expected to answer."),
11339
+ keyQuestions: z.array(worktreeKeyQuestionInputSchema).optional().describe("Inline key questions captured as part of the worktree plan."),
11340
+ evidenceSignals: z.array(worktreeEvidenceSignalInputSchema).optional().describe("Evidence signals the worktree needs to collect or validate."),
11341
+ decisionGate: worktreeDecisionGateInputSchema.optional(),
11342
+ goCriteria: z.array(z.string()).optional().describe("Shorthand go criteria used to build decisionGate."),
11343
+ noGoSignals: z.array(z.string()).optional().describe("Shorthand no-go signals used to build decisionGate."),
11344
+ proofArtifacts: z.array(z.unknown()).optional().describe("Expected proof artifacts required to close the worktree."),
11345
+ autoShape: z.boolean().optional().describe("Whether to invoke inquiry auto-shaping during creation."),
11346
+ autoFixPolicy: autoFixPolicyInputSchema.optional(),
11347
+ domainPackId: z.string().optional().describe("Domain pack whose shaping hooks should influence the worktree."),
11348
+ campaign: z.number().optional().describe("Top-level pipeline campaign number."),
11349
+ lane: z.string().optional().describe("Campaign lane for the worktree."),
11350
+ laneOrderInCampaign: z.number().optional().describe("Ordering for this lane within its campaign."),
11351
+ orderInLane: z.number().optional().describe("Position of this worktree inside its lane."),
11352
+ dependsOn: z.array(z.string()).optional().describe("Worktree IDs that must complete before this worktree."),
11353
+ blocks: z.array(z.string()).optional().describe("Worktree IDs blocked by this worktree."),
11354
+ staffingHint: z.string().optional().describe("Suggested staffing or agent allocation note."),
11355
+ lensId: z.string().optional().describe("Lens that scopes this worktree when applicable."),
11356
+ lastReconciledAt: z.number().optional().describe("Timestamp when worktree metadata was last reconciled.")
11357
+ });
10221
11358
  var worktreeIdInput = (input) => compactRecord4({
10222
11359
  worktreeId: input.worktreeId ?? input.id
10223
11360
  });
@@ -10250,6 +11387,50 @@ var worktreeMetadataInput = (input) => compactRecord4({
10250
11387
  autoFixPolicy: input.autoFixPolicy,
10251
11388
  lastReconciledAt: input.lastReconciledAt
10252
11389
  });
11390
+ var worktreeMetadataArgs = z.object({
11391
+ worktreeId: z.string().describe("The worktree to update."),
11392
+ id: z.string().optional().describe("Worktree ID alias."),
11393
+ topicId: z.string().optional().describe("Primary topic scope."),
11394
+ additionalTopicIds: z.array(z.string()).optional().describe("Additional topic scopes associated with this worktree."),
11395
+ status: z.string().optional().describe("Worktree lifecycle status."),
11396
+ campaign: z.number().optional().describe("Top-level pipeline campaign."),
11397
+ lane: z.string().optional().describe("Campaign lane."),
11398
+ laneOrderInCampaign: z.number().optional().describe("Ordering for this lane within its campaign."),
11399
+ orderInLane: z.number().optional().describe("Position of this worktree inside its lane."),
11400
+ gate: z.string().optional().describe("Exit gate for this worktree."),
11401
+ hypothesis: z.string().optional().describe("Testable claim this worktree investigates."),
11402
+ objective: z.string().optional().describe("Reasoning objective for the worktree."),
11403
+ rationale: z.string().optional().describe("Why this worktree is sequenced here."),
11404
+ proofArtifacts: z.array(z.unknown()).optional().describe("Proof artifacts required to close the worktree."),
11405
+ staffingHint: z.string().optional().describe("Suggested staffing or agent allocation note."),
11406
+ blocks: z.array(z.string()).optional().describe("Worktree IDs blocked by this worktree."),
11407
+ dependsOn: z.array(z.string()).optional().describe("Worktree IDs this worktree depends on."),
11408
+ lensId: z.string().optional().describe("Lens that scopes this worktree."),
11409
+ autoFixPolicy: autoFixPolicyInputSchema.optional(),
11410
+ lastReconciledAt: z.number().optional().describe("Timestamp of the last deterministic reconciliation pass.")
11411
+ });
11412
+ var pushArgs = worktreeMetadataArgs.extend({
11413
+ targetContext: z.string().describe("Where to push merged findings."),
11414
+ beliefIds: z.array(z.string()).optional().describe("Optional subset of beliefs to push.")
11415
+ });
11416
+ var openPullRequestArgs = worktreeMetadataArgs.extend({
11417
+ reviewers: z.array(z.string()).optional().describe("User IDs of requested reviewers."),
11418
+ summary: z.string().describe("Summary of findings and why they are ready for review.")
11419
+ });
11420
+ var mergeKeyFindingsInput = (input) => {
11421
+ if (Array.isArray(input.keyFindings)) {
11422
+ return input.keyFindings;
11423
+ }
11424
+ if (Array.isArray(input.outcomes)) {
11425
+ const findings = input.outcomes.filter(
11426
+ (outcome) => typeof outcome === "string" && outcome.trim().length > 0
11427
+ );
11428
+ if (findings.length > 0) {
11429
+ return findings;
11430
+ }
11431
+ }
11432
+ return [input.summary ?? "Merged worktree"];
11433
+ };
10253
11434
  var listAllWorktreesInput = (input) => compactRecord4({
10254
11435
  status: input.status,
10255
11436
  lane: input.lane,
@@ -10257,6 +11438,16 @@ var listAllWorktreesInput = (input) => compactRecord4({
10257
11438
  limit: input.limit
10258
11439
  });
10259
11440
  var worktreesContracts = [
11441
+ surfaceContract({
11442
+ name: "begin_build_session",
11443
+ kind: "mutation",
11444
+ domain: "worktrees",
11445
+ surfaceClass: "platform_internal",
11446
+ path: "/mcp/build-session/begin",
11447
+ sdkNamespace: "worktrees",
11448
+ sdkMethod: "beginBuildSession",
11449
+ summary: "Begin a coding build session for a worktree."
11450
+ }),
10260
11451
  surfaceContract({
10261
11452
  name: "add_worktree",
10262
11453
  kind: "mutation",
@@ -10273,13 +11464,12 @@ var worktreesContracts = [
10273
11464
  inputProjection: (input, context) => withCreatedBy(
10274
11465
  compactRecord4({
10275
11466
  name: input.name ?? input.title,
10276
- topicId: input.topicId,
11467
+ topicId: input.topicId ?? input.projectId,
10277
11468
  worktreeType: input.worktreeType,
10278
11469
  objective: input.objective,
10279
11470
  gate: input.gate,
10280
11471
  hypothesis: input.hypothesis,
10281
11472
  rationale: input.rationale,
10282
- signal: input.signal,
10283
11473
  startDate: input.startDate,
10284
11474
  endDate: input.endDate,
10285
11475
  durationWeeks: input.durationWeeks,
@@ -10305,12 +11495,12 @@ var worktreesContracts = [
10305
11495
  staffingHint: input.staffingHint,
10306
11496
  domainPackId: input.domainPackId,
10307
11497
  lensId: input.lensId,
10308
- linkedQuestionId: input.linkedQuestionId,
10309
11498
  lastReconciledAt: input.lastReconciledAt
10310
11499
  }),
10311
11500
  context
10312
11501
  )
10313
- }
11502
+ },
11503
+ args: addWorktreeArgs
10314
11504
  }),
10315
11505
  surfaceContract({
10316
11506
  name: "activate_worktree",
@@ -10422,7 +11612,8 @@ var worktreesContracts = [
10422
11612
  functionName: "updateMetadata",
10423
11613
  kind: "mutation",
10424
11614
  inputProjection: worktreeMetadataInput
10425
- }
11615
+ },
11616
+ args: worktreeMetadataArgs
10426
11617
  }),
10427
11618
  surfaceContract({
10428
11619
  name: "merge",
@@ -10440,9 +11631,7 @@ var worktreesContracts = [
10440
11631
  inputProjection: (input, context) => withUserId(
10441
11632
  {
10442
11633
  ...worktreeIdInput(input),
10443
- keyFindings: input.keyFindings ?? [
10444
- input.summary ?? "Merged worktree"
10445
- ],
11634
+ keyFindings: mergeKeyFindingsInput(input),
10446
11635
  decisionsReached: input.decisionsReached ?? [],
10447
11636
  nextSteps: input.nextSteps ?? []
10448
11637
  },
@@ -10464,7 +11653,8 @@ var worktreesContracts = [
10464
11653
  functionName: "updateMetadata",
10465
11654
  kind: "mutation",
10466
11655
  inputProjection: worktreeMetadataInput
10467
- }
11656
+ },
11657
+ args: pushArgs
10468
11658
  }),
10469
11659
  surfaceContract({
10470
11660
  name: "open_pull_request",
@@ -10480,7 +11670,8 @@ var worktreesContracts = [
10480
11670
  functionName: "updateMetadata",
10481
11671
  kind: "mutation",
10482
11672
  inputProjection: worktreeMetadataInput
10483
- }
11673
+ },
11674
+ args: openPullRequestArgs
10484
11675
  })
10485
11676
  ];
10486
11677
 
@@ -10584,6 +11775,15 @@ var createEdgeArgs = z.object({
10584
11775
  topicId: z.string().optional(),
10585
11776
  trustedBypassAccessCheck: z.boolean().optional()
10586
11777
  });
11778
+ var queryLineageArgs = z.object({
11779
+ nodeId: z.string().describe("Starting node to trace from."),
11780
+ startNode: z.string().optional().describe("Starting node alias accepted by traversal callers."),
11781
+ depth: z.number().optional().describe("Traversal depth alias."),
11782
+ maxDepth: z.number().optional().describe("Maximum traversal depth."),
11783
+ mode: z.string().optional().describe("Traversal mode."),
11784
+ minLayer: z.string().optional().describe("Minimum epistemic layer."),
11785
+ maxLayer: z.string().optional().describe("Maximum epistemic layer.")
11786
+ });
10587
11787
  function graphRefNodeId(ref) {
10588
11788
  if (ref.kind === "epistemic_node") {
10589
11789
  return ref.nodeId;
@@ -10654,11 +11854,84 @@ var edgesContracts = [
10654
11854
  minLayer: input.minLayer,
10655
11855
  maxLayer: input.maxLayer
10656
11856
  })
10657
- }
11857
+ },
11858
+ args: queryLineageArgs
10658
11859
  })
10659
11860
  ];
10660
-
10661
- // ../contracts/src/function-registry/graph.ts
11861
+ var graphIntelligenceQueryModes = [
11862
+ "core",
11863
+ "bias",
11864
+ "stress",
11865
+ "operational",
11866
+ "alpha",
11867
+ "semantic",
11868
+ "evidence"
11869
+ ];
11870
+ var traversalLayerSchema = z.enum([
11871
+ "L4",
11872
+ "L3",
11873
+ "L2",
11874
+ "L1",
11875
+ "ontological",
11876
+ "organizational"
11877
+ ]);
11878
+ var traversalModeSchema = z.enum(["low", "medium", "high", "extra_high"]);
11879
+ var lineageAliasArgs = z.object({
11880
+ nodeId: z.string().optional().describe("Starting node to traverse from."),
11881
+ startNode: z.string().optional().describe("Starting node alias for traversal callers."),
11882
+ entityId: z.string().optional().describe("Entity identifier alias for impact tracing."),
11883
+ depth: z.number().optional().describe("Traversal depth alias."),
11884
+ maxDepth: z.number().optional().describe("Maximum traversal depth."),
11885
+ mode: traversalModeSchema.optional().describe("Traversal mode."),
11886
+ minLayer: traversalLayerSchema.optional().describe("Minimum epistemic layer to include."),
11887
+ maxLayer: traversalLayerSchema.optional().describe("Maximum epistemic layer to include.")
11888
+ });
11889
+ var lineageArgs = lineageAliasArgs.extend({
11890
+ nodeId: z.string().describe("Starting node to traverse from.")
11891
+ });
11892
+ var traverseGraphArgs = lineageAliasArgs.extend({
11893
+ startNode: z.string().describe("Node to start traversal from."),
11894
+ direction: z.enum(["up", "down", "both"]).optional().describe("Traversal direction.")
11895
+ });
11896
+ var graphNeighborhoodArgs = z.object({
11897
+ globalId: z.string().optional().describe("Single root global ID."),
11898
+ globalIds: z.array(z.string()).optional().describe("Root global IDs for the neighborhood."),
11899
+ maxDepth: z.number().optional().describe("Maximum traversal depth."),
11900
+ topicId: z.string().optional().describe("Topic scope for edge lookup."),
11901
+ limit: z.number().optional().describe("Maximum edges to return.")
11902
+ });
11903
+ var graphIntelligenceModeSchema = z.enum([
11904
+ graphIntelligenceQueryModes[0],
11905
+ ...graphIntelligenceQueryModes.slice(1)
11906
+ ]);
11907
+ var graphIntelligenceCatalogArgs = z.object({
11908
+ categoryId: z.string().optional().describe("Optional query category filter."),
11909
+ mode: graphIntelligenceModeSchema.optional().describe("Optional Graph Intelligence query mode filter.")
11910
+ });
11911
+ var graphIntelligenceRunArgs = z.object({
11912
+ topicId: z.string().describe("Topic to analyze."),
11913
+ queryId: z.string().optional().describe("Catalog query ID to run, such as pre-mortem."),
11914
+ prompt: z.string().optional().describe("Custom prompt when queryId is omitted or overridden."),
11915
+ input: z.string().optional().describe("Optional entity, theme, belief, company, or search text."),
11916
+ mode: graphIntelligenceModeSchema.optional().describe("Optional query mode override for custom prompts."),
11917
+ limit: z.number().optional().describe("Maximum graph context rows to return.")
11918
+ });
11919
+ var flagContradictionArgs = z.object({
11920
+ beliefA: z.string().describe("First belief in tension."),
11921
+ beliefB: z.string().describe("Second belief in tension."),
11922
+ topicId: z.string().optional().describe("Topic scope for the contradiction."),
11923
+ description: z.string().optional().describe("Human-readable contradiction."),
11924
+ severity: z.enum(["critical", "high", "medium", "low"]).optional().describe("Contradiction severity."),
11925
+ defeatType: z.string().optional().describe("Defeat type annotation."),
11926
+ supportingInsightIds: z.array(z.string()).optional().describe("Evidence supporting the primary belief."),
11927
+ contradictingInsightIds: z.array(z.string()).optional().describe("Evidence or beliefs contradicting the primary belief.")
11928
+ });
11929
+ var discoverEntityConnectionsArgs = lineageAliasArgs.extend({
11930
+ nodeId: z.string().describe("Epistemic node ID to find entity connections for."),
11931
+ topicId: z.string().optional().describe("Topic scope override."),
11932
+ minScore: z.number().optional().describe("Minimum match score."),
11933
+ limit: z.number().optional().describe("Maximum candidates to return.")
11934
+ });
10662
11935
  var contradictionSeverity = (value) => {
10663
11936
  switch (value) {
10664
11937
  case "critical":
@@ -10713,7 +11986,8 @@ var graphContracts = [
10713
11986
  functionName: "getLineage",
10714
11987
  kind: "query",
10715
11988
  inputProjection: lineageInput
10716
- }
11989
+ },
11990
+ args: traverseGraphArgs
10717
11991
  }),
10718
11992
  surfaceContract({
10719
11993
  name: "get_graph_neighborhood",
@@ -10729,7 +12003,8 @@ var graphContracts = [
10729
12003
  functionName: "getByTopic",
10730
12004
  kind: "query",
10731
12005
  inputProjection: topicEdgesInput
10732
- }
12006
+ },
12007
+ args: graphNeighborhoodArgs
10733
12008
  }),
10734
12009
  surfaceContract({
10735
12010
  name: "get_graph_structure_analysis",
@@ -10746,6 +12021,38 @@ var graphContracts = [
10746
12021
  kind: "query"
10747
12022
  }
10748
12023
  }),
12024
+ surfaceContract({
12025
+ name: "list_graph_intelligence_queries",
12026
+ kind: "query",
12027
+ domain: "graph",
12028
+ surfaceClass: "platform_public",
12029
+ path: "/graph-intelligence/queries",
12030
+ sdkNamespace: "graphAnalysis",
12031
+ sdkMethod: "listGraphIntelligenceQueries",
12032
+ summary: "List Graph Intelligence query catalog entries.",
12033
+ convex: {
12034
+ module: "contextCompiler",
12035
+ functionName: "listGraphIntelligenceQueries",
12036
+ kind: "query"
12037
+ },
12038
+ args: graphIntelligenceCatalogArgs
12039
+ }),
12040
+ surfaceContract({
12041
+ name: "run_graph_intelligence_query",
12042
+ kind: "query",
12043
+ domain: "graph",
12044
+ surfaceClass: "platform_public",
12045
+ path: "/graph-intelligence/run",
12046
+ sdkNamespace: "graphAnalysis",
12047
+ sdkMethod: "runGraphIntelligenceQuery",
12048
+ summary: "Run a Graph Intelligence query against a topic graph.",
12049
+ convex: {
12050
+ module: "contextCompiler",
12051
+ functionName: "runGraphIntelligenceQuery",
12052
+ kind: "query"
12053
+ },
12054
+ args: graphIntelligenceRunArgs
12055
+ }),
10749
12056
  surfaceContract({
10750
12057
  name: "find_contradictions",
10751
12058
  kind: "query",
@@ -10778,7 +12085,8 @@ var graphContracts = [
10778
12085
  functionName: "create",
10779
12086
  kind: "mutation",
10780
12087
  inputProjection: flagContradictionInput
10781
- }
12088
+ },
12089
+ args: flagContradictionArgs
10782
12090
  }),
10783
12091
  surfaceContract({
10784
12092
  name: "detect_confirmation_bias",
@@ -10869,7 +12177,8 @@ var graphContracts = [
10869
12177
  functionName: "getLineage",
10870
12178
  kind: "query",
10871
12179
  inputProjection: lineageInput
10872
- }
12180
+ },
12181
+ args: discoverEntityConnectionsArgs
10873
12182
  }),
10874
12183
  surfaceContract({
10875
12184
  name: "trigger_belief_review",
@@ -10900,7 +12209,8 @@ var graphContracts = [
10900
12209
  functionName: "getLineage",
10901
12210
  kind: "query",
10902
12211
  inputProjection: lineageInput
10903
- }
12212
+ },
12213
+ args: lineageArgs
10904
12214
  })
10905
12215
  ];
10906
12216
 
@@ -10952,8 +12262,16 @@ var contractsContracts = [
10952
12262
  }
10953
12263
  })
10954
12264
  ];
10955
-
10956
- // ../contracts/src/function-registry/judgments.ts
12265
+ var auditTrailArgs = z.object({
12266
+ nodeId: z.string().describe("The node to audit."),
12267
+ id: z.string().optional().describe("Node ID alias."),
12268
+ limit: z.number().optional().describe("Maximum entries to return."),
12269
+ depth: z.number().optional().describe("Traversal depth alias."),
12270
+ maxDepth: z.number().optional().describe("Maximum lineage depth."),
12271
+ mode: z.string().optional().describe("Traversal mode."),
12272
+ minLayer: z.string().optional().describe("Minimum epistemic layer."),
12273
+ maxLayer: z.string().optional().describe("Maximum epistemic layer.")
12274
+ });
10957
12275
  var judgmentsContracts = [
10958
12276
  surfaceContract({
10959
12277
  name: "record_judgment",
@@ -11008,7 +12326,8 @@ var judgmentsContracts = [
11008
12326
  minLayer: input.minLayer,
11009
12327
  maxLayer: input.maxLayer
11010
12328
  })
11011
- }
12329
+ },
12330
+ args: auditTrailArgs
11012
12331
  })
11013
12332
  ];
11014
12333
 
@@ -11176,8 +12495,13 @@ var coordinationContracts = [
11176
12495
  }
11177
12496
  })
11178
12497
  ];
11179
-
11180
- // ../contracts/src/function-registry/pipeline.ts
12498
+ var pipelineSnapshotArgs = z.object({
12499
+ topicId: z.string().describe("Topic scope ID."),
12500
+ status: z.string().optional().describe("Worktree status filter."),
12501
+ lane: z.string().optional().describe("Campaign lane filter."),
12502
+ campaign: z.number().optional().describe("Campaign number filter."),
12503
+ limit: z.number().optional().describe("Maximum worktrees to inspect.")
12504
+ });
11181
12505
  var pipelineContracts = [
11182
12506
  surfaceContract({
11183
12507
  name: "pipeline_snapshot",
@@ -11198,7 +12522,8 @@ var pipelineContracts = [
11198
12522
  campaign: input.campaign,
11199
12523
  limit: input.limit
11200
12524
  })
11201
- }
12525
+ },
12526
+ args: pipelineSnapshotArgs
11202
12527
  }),
11203
12528
  surfaceContract({
11204
12529
  name: "seed_belief_lattice",
@@ -11250,7 +12575,31 @@ var recordScopeLearningArgs = z.object({
11250
12575
  rationale: z.string().optional().describe("Why this learning should enter the reasoning graph"),
11251
12576
  createQuestionText: z.string().optional().describe("Optional follow-up question text"),
11252
12577
  createBeliefText: z.string().optional().describe("Optional new belief text"),
11253
- beliefType: z.string().optional().describe("Optional belief type for createBeliefText")
12578
+ beliefType: z.string().optional().describe("Optional belief type for createBeliefText"),
12579
+ text: z.string().optional().describe("Canonical learning text alias."),
12580
+ content: z.string().optional().describe("Canonical learning content alias."),
12581
+ kind: z.string().optional().describe("Evidence kind to store."),
12582
+ sourceType: z.string().optional().describe("Evidence source type."),
12583
+ externalSourceType: z.string().optional().describe("External source type alias."),
12584
+ metadata: z.record(z.unknown()).optional().describe("Learning metadata.")
12585
+ });
12586
+ var codeContextArgs = z.object({
12587
+ topicId: z.string().optional().describe("Topic scope."),
12588
+ filePath: z.string().optional().describe("File path anchor."),
12589
+ includeFailures: z.boolean().optional().describe("Whether to include failed attempts."),
12590
+ limit: z.number().optional().describe("Maximum records to return."),
12591
+ status: z.string().optional().describe("Evidence status filter.")
12592
+ });
12593
+ var recordAttemptArgs = z.object({
12594
+ topicId: z.string().optional().describe("Topic scope."),
12595
+ description: z.string().describe("Attempt description."),
12596
+ errorMessage: z.string().optional().describe("Failure or error message."),
12597
+ filePaths: z.array(z.string()).optional().describe("Files involved in the attempt."),
12598
+ filePath: z.string().optional().describe("Single file path alias."),
12599
+ linkedBeliefId: z.string().optional().describe("Linked belief ID."),
12600
+ metadata: z.record(z.unknown()).optional().describe("Attempt metadata."),
12601
+ rationale: z.string().optional().describe("Why this attempt should be recorded."),
12602
+ title: z.string().optional().describe("Attempt evidence title.")
11254
12603
  });
11255
12604
  var learningInput = (input, context) => {
11256
12605
  const sourceKind = input.sourceKind ?? input.externalSourceType;
@@ -11367,7 +12716,8 @@ var codingContracts = [
11367
12716
  status: input.status,
11368
12717
  userId: input.userId
11369
12718
  })
11370
- }
12719
+ },
12720
+ args: codeContextArgs
11371
12721
  }),
11372
12722
  surfaceContract({
11373
12723
  name: "get_change_history",
@@ -11404,7 +12754,8 @@ var codingContracts = [
11404
12754
  functionName: "create",
11405
12755
  kind: "mutation",
11406
12756
  inputProjection: attemptInput
11407
- }
12757
+ },
12758
+ args: recordAttemptArgs
11408
12759
  }),
11409
12760
  surfaceContract({
11410
12761
  name: "get_failure_log",
@@ -11753,20 +13104,618 @@ function scoreEntityTypeMatch(inputText, entityType) {
11753
13104
  if (subtypeBonus > 0.05) {
11754
13105
  reasons.push("subtype match");
11755
13106
  }
11756
- const reason = reasons.length > 0 ? reasons.join(", ") : "low similarity";
11757
- return {
11758
- entityType: entityType.value,
11759
- label: entityType.label,
11760
- score,
11761
- reason
11762
- };
11763
- }
11764
- function rankEntityTypeMatches(inputText, entityTypes, options) {
11765
- const minScore = options?.minScore ?? 0.05;
11766
- const limit = options?.limit ?? 10;
11767
- const matches = entityTypes.map((et) => scoreEntityTypeMatch(inputText, et)).filter((m) => m.score >= minScore).sort((a, b) => b.score - a.score).slice(0, limit);
11768
- return matches;
11769
- }
13107
+ const reason = reasons.length > 0 ? reasons.join(", ") : "low similarity";
13108
+ return {
13109
+ entityType: entityType.value,
13110
+ label: entityType.label,
13111
+ score,
13112
+ reason
13113
+ };
13114
+ }
13115
+ function rankEntityTypeMatches(inputText, entityTypes, options) {
13116
+ const minScore = options?.minScore ?? 0.05;
13117
+ const limit = options?.limit ?? 10;
13118
+ const matches = entityTypes.map((et) => scoreEntityTypeMatch(inputText, et)).filter((m) => m.score >= minScore).sort((a, b) => b.score - a.score).slice(0, limit);
13119
+ return matches;
13120
+ }
13121
+
13122
+ // ../contracts/src/tenant-bootstrap-seed.contract.ts
13123
+ function isCopyableSeedRequirement(entry) {
13124
+ return (entry.copyMode === "template_global" || entry.copyMode === "template_tenant_rewrite" || entry.copyMode === "template_reference_remap") && Boolean(entry.scope) && Array.isArray(entry.uniqueKey) && entry.uniqueKey.length > 0;
13125
+ }
13126
+ var TENANT_BOOTSTRAP_TABLE_REQUIREMENTS = [
13127
+ {
13128
+ component: "kernel",
13129
+ table: "agentMessages",
13130
+ prepopulation: "runtime_data",
13131
+ copyMode: "none",
13132
+ description: "Agent coordination messages are session data, not template data."
13133
+ },
13134
+ {
13135
+ component: "kernel",
13136
+ table: "agentSessions",
13137
+ prepopulation: "runtime_data",
13138
+ copyMode: "none",
13139
+ description: "Agent coordination sessions are created by active clients."
13140
+ },
13141
+ {
13142
+ component: "kernel",
13143
+ table: "autofixJobs",
13144
+ prepopulation: "runtime_queue",
13145
+ copyMode: "none",
13146
+ description: "Autofix work items are runtime queue rows."
13147
+ },
13148
+ {
13149
+ component: "kernel",
13150
+ table: "backgroundJobRuns",
13151
+ prepopulation: "runtime_log",
13152
+ copyMode: "none",
13153
+ description: "Background job executions are runtime logs."
13154
+ },
13155
+ {
13156
+ component: "kernel",
13157
+ table: "backgroundJobSettings",
13158
+ prepopulation: "required_template",
13159
+ copyMode: "template_global",
13160
+ scope: "global",
13161
+ uniqueKey: ["jobKey"],
13162
+ description: "Default job enablement settings must come from the K template."
13163
+ },
13164
+ {
13165
+ component: "kernel",
13166
+ table: "beliefConfidence",
13167
+ prepopulation: "runtime_data",
13168
+ copyMode: "none",
13169
+ description: "Belief confidence rows are created with tenant graph facts."
13170
+ },
13171
+ {
13172
+ component: "kernel",
13173
+ table: "beliefEvidenceLinks",
13174
+ prepopulation: "runtime_data",
13175
+ copyMode: "none",
13176
+ description: "Belief-to-evidence links are tenant graph data."
13177
+ },
13178
+ {
13179
+ component: "kernel",
13180
+ table: "beliefHistory",
13181
+ prepopulation: "runtime_data",
13182
+ copyMode: "none",
13183
+ description: "Belief history is append-only tenant graph data."
13184
+ },
13185
+ {
13186
+ component: "kernel",
13187
+ table: "beliefScenarios",
13188
+ prepopulation: "runtime_data",
13189
+ copyMode: "none",
13190
+ description: "Scenario rows are tenant-authored reasoning data."
13191
+ },
13192
+ {
13193
+ component: "kernel",
13194
+ table: "beliefVotes",
13195
+ prepopulation: "runtime_data",
13196
+ copyMode: "none",
13197
+ description: "Decision belief votes are tenant-authored data."
13198
+ },
13199
+ {
13200
+ component: "kernel",
13201
+ table: "calibrationScores",
13202
+ prepopulation: "runtime_derived",
13203
+ copyMode: "none",
13204
+ description: "Calibration scores are computed from tenant outcomes."
13205
+ },
13206
+ {
13207
+ component: "kernel",
13208
+ table: "contractEvaluations",
13209
+ prepopulation: "runtime_log",
13210
+ copyMode: "none",
13211
+ description: "Contract evaluation rows are runtime computation logs."
13212
+ },
13213
+ {
13214
+ component: "kernel",
13215
+ table: "contradictions",
13216
+ prepopulation: "runtime_data",
13217
+ copyMode: "none",
13218
+ description: "Contradictions are tenant graph facts."
13219
+ },
13220
+ {
13221
+ component: "kernel",
13222
+ table: "crossProjectConnections",
13223
+ prepopulation: "runtime_data",
13224
+ copyMode: "none",
13225
+ description: "Cross-topic connections are tenant graph facts."
13226
+ },
13227
+ {
13228
+ component: "kernel",
13229
+ table: "decisionComputedSummaries",
13230
+ prepopulation: "runtime_derived",
13231
+ copyMode: "none",
13232
+ description: "Decision summaries are derived tenant outputs."
13233
+ },
13234
+ {
13235
+ component: "kernel",
13236
+ table: "decisionEvents",
13237
+ prepopulation: "runtime_data",
13238
+ copyMode: "none",
13239
+ description: "Decision events are lifecycle data."
13240
+ },
13241
+ {
13242
+ component: "kernel",
13243
+ table: "decisionParticipants",
13244
+ prepopulation: "runtime_data",
13245
+ copyMode: "none",
13246
+ description: "Decision participants are tenant-selected actors."
13247
+ },
13248
+ {
13249
+ component: "kernel",
13250
+ table: "decisionRiskLedger",
13251
+ prepopulation: "runtime_data",
13252
+ copyMode: "none",
13253
+ description: "Decision risk rows are tenant decision data."
13254
+ },
13255
+ {
13256
+ component: "kernel",
13257
+ table: "decisionSnapshots",
13258
+ prepopulation: "runtime_derived",
13259
+ copyMode: "none",
13260
+ description: "Decision snapshots are derived from tenant state."
13261
+ },
13262
+ {
13263
+ component: "kernel",
13264
+ table: "deliberationContributions",
13265
+ prepopulation: "runtime_data",
13266
+ copyMode: "none",
13267
+ description: "Deliberation contributions are tenant-authored data."
13268
+ },
13269
+ {
13270
+ component: "kernel",
13271
+ table: "deliberationSessions",
13272
+ prepopulation: "runtime_data",
13273
+ copyMode: "none",
13274
+ description: "Deliberation sessions are created by tenant workflows."
13275
+ },
13276
+ {
13277
+ component: "kernel",
13278
+ table: "epistemicAudit",
13279
+ prepopulation: "runtime_log",
13280
+ copyMode: "none",
13281
+ description: "Epistemic audit rows are append-only runtime audit data."
13282
+ },
13283
+ {
13284
+ component: "kernel",
13285
+ table: "epistemicContracts",
13286
+ prepopulation: "runtime_data",
13287
+ copyMode: "none",
13288
+ description: "Epistemic contracts are tenant-authored governance data."
13289
+ },
13290
+ {
13291
+ component: "kernel",
13292
+ table: "epistemicEdges",
13293
+ prepopulation: "runtime_data",
13294
+ copyMode: "none",
13295
+ description: "Edges are tenant reasoning graph data."
13296
+ },
13297
+ {
13298
+ component: "kernel",
13299
+ table: "epistemicNodeEmbeddings",
13300
+ prepopulation: "runtime_derived",
13301
+ copyMode: "none",
13302
+ description: "Embeddings are derived from tenant graph nodes."
13303
+ },
13304
+ {
13305
+ component: "kernel",
13306
+ table: "epistemicNodes",
13307
+ prepopulation: "runtime_data",
13308
+ copyMode: "none",
13309
+ description: "Nodes are tenant reasoning graph data."
13310
+ },
13311
+ {
13312
+ component: "kernel",
13313
+ table: "graphAnalysisCache",
13314
+ prepopulation: "runtime_derived",
13315
+ copyMode: "none",
13316
+ description: "Graph analysis cache rows are derived from tenant graph state."
13317
+ },
13318
+ {
13319
+ component: "kernel",
13320
+ table: "graphAnalysisResults",
13321
+ prepopulation: "runtime_derived",
13322
+ copyMode: "none",
13323
+ description: "Graph analysis result rows are derived tenant outputs."
13324
+ },
13325
+ {
13326
+ component: "kernel",
13327
+ table: "graphSuggestions",
13328
+ prepopulation: "runtime_derived",
13329
+ copyMode: "none",
13330
+ description: "Graph suggestions are derived recommendations."
13331
+ },
13332
+ {
13333
+ component: "kernel",
13334
+ table: "harnessReplays",
13335
+ prepopulation: "runtime_log",
13336
+ copyMode: "none",
13337
+ description: "Harness replay rows are runtime verification logs."
13338
+ },
13339
+ {
13340
+ component: "kernel",
13341
+ table: "harnessRuns",
13342
+ prepopulation: "runtime_log",
13343
+ copyMode: "none",
13344
+ description: "Harness run rows are runtime verification logs."
13345
+ },
13346
+ {
13347
+ component: "kernel",
13348
+ table: "idempotencyTokens",
13349
+ prepopulation: "runtime_log",
13350
+ copyMode: "none",
13351
+ description: "Idempotency tokens are request-scoped runtime guards."
13352
+ },
13353
+ {
13354
+ component: "kernel",
13355
+ table: "lenses",
13356
+ prepopulation: "optional_template",
13357
+ copyMode: "none",
13358
+ description: "Reusable lens templates may live in K templates, but workspace-specific copies are not required for core SDK boot."
13359
+ },
13360
+ {
13361
+ component: "kernel",
13362
+ table: "lensTopicBindings",
13363
+ prepopulation: "runtime_data",
13364
+ copyMode: "none",
13365
+ description: "Lens bindings attach runtime topics to runtime/workspace lenses."
13366
+ },
13367
+ {
13368
+ component: "kernel",
13369
+ table: "neo4jSyncQueue",
13370
+ prepopulation: "runtime_queue",
13371
+ copyMode: "none",
13372
+ description: "Neo4j sync queue rows are runtime work items."
13373
+ },
13374
+ {
13375
+ component: "kernel",
13376
+ table: "ontologyDefinitions",
13377
+ prepopulation: "required_template",
13378
+ copyMode: "template_global",
13379
+ scope: "global",
13380
+ uniqueKey: ["ontologyKey"],
13381
+ description: "Platform ontology definitions power taxonomy reads and effective ontology resolution."
13382
+ },
13383
+ {
13384
+ component: "kernel",
13385
+ table: "ontologyVersions",
13386
+ prepopulation: "required_template",
13387
+ copyMode: "template_reference_remap",
13388
+ scope: "global",
13389
+ uniqueKey: ["ontologyKey", "version"],
13390
+ dependsOn: ["ontologyDefinitions"],
13391
+ description: "Ontology versions must be copied with ontologyDefinition ID remapping."
13392
+ },
13393
+ {
13394
+ component: "kernel",
13395
+ table: "platformAgentRunPolicyDecisions",
13396
+ prepopulation: "runtime_log",
13397
+ copyMode: "none",
13398
+ description: "Agent-run policy decisions are audit logs."
13399
+ },
13400
+ {
13401
+ component: "kernel",
13402
+ table: "platformAgentRunPromptResolutions",
13403
+ prepopulation: "runtime_log",
13404
+ copyMode: "none",
13405
+ description: "Agent-run prompt resolution rows are runtime logs."
13406
+ },
13407
+ {
13408
+ component: "kernel",
13409
+ table: "platformAgentRuns",
13410
+ prepopulation: "runtime_log",
13411
+ copyMode: "none",
13412
+ description: "Agent runs are runtime execution records."
13413
+ },
13414
+ {
13415
+ component: "kernel",
13416
+ table: "platformAgentRunToolCalls",
13417
+ prepopulation: "runtime_log",
13418
+ copyMode: "none",
13419
+ description: "Agent-run tool calls are runtime execution records."
13420
+ },
13421
+ {
13422
+ component: "kernel",
13423
+ table: "platformHarnessShadowAudit",
13424
+ prepopulation: "runtime_log",
13425
+ copyMode: "none",
13426
+ description: "Harness shadow audit rows are runtime audit records."
13427
+ },
13428
+ {
13429
+ component: "kernel",
13430
+ table: "publicationRules",
13431
+ prepopulation: "required_template",
13432
+ copyMode: "template_tenant_rewrite",
13433
+ scope: "tenant",
13434
+ uniqueKey: ["tenantId", "workspaceId", "name"],
13435
+ description: "Default publication policy rules are rewritten into each tenant."
13436
+ },
13437
+ {
13438
+ component: "kernel",
13439
+ table: "questionEvidenceLinks",
13440
+ prepopulation: "runtime_data",
13441
+ copyMode: "none",
13442
+ description: "Question-to-evidence links are tenant graph data."
13443
+ },
13444
+ {
13445
+ component: "kernel",
13446
+ table: "researchJobs",
13447
+ prepopulation: "runtime_queue",
13448
+ copyMode: "none",
13449
+ description: "Research job rows are runtime queue items."
13450
+ },
13451
+ {
13452
+ component: "kernel",
13453
+ table: "schemaEnumConfig",
13454
+ prepopulation: "required_template",
13455
+ copyMode: "template_global",
13456
+ scope: "global",
13457
+ uniqueKey: ["category", "value"],
13458
+ description: "Runtime-extensible enum defaults required by SDK graph APIs."
13459
+ },
13460
+ {
13461
+ component: "kernel",
13462
+ table: "stakeholderGroups",
13463
+ prepopulation: "runtime_data",
13464
+ copyMode: "none",
13465
+ description: "Stakeholder groups are tenant decision data."
13466
+ },
13467
+ {
13468
+ component: "kernel",
13469
+ table: "systemLogs",
13470
+ prepopulation: "runtime_log",
13471
+ copyMode: "none",
13472
+ description: "System logs are runtime telemetry."
13473
+ },
13474
+ {
13475
+ component: "kernel",
13476
+ table: "tasks",
13477
+ prepopulation: "runtime_data",
13478
+ copyMode: "none",
13479
+ description: "Tasks are tenant-authored work items."
13480
+ },
13481
+ {
13482
+ component: "kernel",
13483
+ table: "topics",
13484
+ prepopulation: "runtime_bootstrap",
13485
+ copyMode: "none",
13486
+ description: "Default topics are created by tenant provisioning, not copied from templates."
13487
+ },
13488
+ {
13489
+ component: "kernel",
13490
+ table: "workflowDefinitions",
13491
+ prepopulation: "optional_template",
13492
+ copyMode: "none",
13493
+ description: "Table-driven workflow definitions can be template data after the workflow engine leaves legacy mode."
13494
+ },
13495
+ {
13496
+ component: "kernel",
13497
+ table: "workflowPullRequests",
13498
+ prepopulation: "runtime_data",
13499
+ copyMode: "none",
13500
+ description: "Workflow pull requests are tenant workflow data."
13501
+ },
13502
+ {
13503
+ component: "kernel",
13504
+ table: "workflowStages",
13505
+ prepopulation: "optional_template",
13506
+ copyMode: "none",
13507
+ dependsOn: ["workflowDefinitions"],
13508
+ description: "Workflow stages can be template data after workflowDefinitions are enabled for bootstrap copying."
13509
+ },
13510
+ {
13511
+ component: "kernel",
13512
+ table: "worktreeBeliefCluster",
13513
+ prepopulation: "runtime_data",
13514
+ copyMode: "none",
13515
+ description: "Worktree cluster rows link runtime worktrees to runtime beliefs."
13516
+ },
13517
+ {
13518
+ component: "kernel",
13519
+ table: "worktrees",
13520
+ prepopulation: "runtime_data",
13521
+ copyMode: "none",
13522
+ description: "Worktrees are tenant/runtime planning data."
13523
+ },
13524
+ {
13525
+ component: "identity",
13526
+ table: "agents",
13527
+ prepopulation: "runtime_bootstrap",
13528
+ copyMode: "none",
13529
+ description: "Service agents are provisioned per tenant or service, not copied."
13530
+ },
13531
+ {
13532
+ component: "identity",
13533
+ table: "mcpWritePolicy",
13534
+ prepopulation: "required_template",
13535
+ copyMode: "template_global",
13536
+ scope: "global",
13537
+ uniqueKey: ["topicId", "role", "toolCategory"],
13538
+ description: "Global write policy defaults govern service and interactive MCP writes."
13539
+ },
13540
+ {
13541
+ component: "identity",
13542
+ table: "modelCallLogs",
13543
+ prepopulation: "runtime_log",
13544
+ copyMode: "none",
13545
+ description: "Model call logs are runtime telemetry."
13546
+ },
13547
+ {
13548
+ component: "identity",
13549
+ table: "modelFunctionSlots",
13550
+ prepopulation: "required_template",
13551
+ copyMode: "template_global",
13552
+ scope: "global",
13553
+ uniqueKey: ["slot"],
13554
+ description: "Function-to-model slots are required by model runtime resolution."
13555
+ },
13556
+ {
13557
+ component: "identity",
13558
+ table: "modelRegistry",
13559
+ prepopulation: "required_template",
13560
+ copyMode: "template_global",
13561
+ scope: "global",
13562
+ uniqueKey: ["key"],
13563
+ description: "Model catalog defaults are required by model runtime clients."
13564
+ },
13565
+ {
13566
+ component: "identity",
13567
+ table: "modelSlotConfigs",
13568
+ prepopulation: "required_template",
13569
+ copyMode: "template_global",
13570
+ scope: "global",
13571
+ uniqueKey: ["slot"],
13572
+ description: "Slot-level defaults are required before tenant overrides exist."
13573
+ },
13574
+ {
13575
+ component: "identity",
13576
+ table: "platformAudienceGrants",
13577
+ prepopulation: "runtime_data",
13578
+ copyMode: "none",
13579
+ description: "Audience grants are principal/group-specific access rows."
13580
+ },
13581
+ {
13582
+ component: "identity",
13583
+ table: "platformAudiences",
13584
+ prepopulation: "required_template",
13585
+ copyMode: "template_tenant_rewrite",
13586
+ scope: "tenant",
13587
+ uniqueKey: ["tenantId", "workspaceId", "audienceKey"],
13588
+ description: "Default tenant audience taxonomy rows are rewritten into each tenant."
13589
+ },
13590
+ {
13591
+ component: "identity",
13592
+ table: "platformPolicyDecisionLogs",
13593
+ prepopulation: "runtime_log",
13594
+ copyMode: "none",
13595
+ description: "Policy decisions are runtime audit logs."
13596
+ },
13597
+ {
13598
+ component: "identity",
13599
+ table: "projectGrants",
13600
+ prepopulation: "runtime_data",
13601
+ copyMode: "none",
13602
+ description: "Project/topic grants are principal or group-specific access rows."
13603
+ },
13604
+ {
13605
+ component: "identity",
13606
+ table: "reasoningPermissions",
13607
+ prepopulation: "runtime_data",
13608
+ copyMode: "none",
13609
+ description: "Reasoning permissions are principal-specific policy rows."
13610
+ },
13611
+ {
13612
+ component: "identity",
13613
+ table: "tenantApiKeys",
13614
+ prepopulation: "runtime_secret",
13615
+ copyMode: "none",
13616
+ description: "API keys are tenant credentials and must never be copied."
13617
+ },
13618
+ {
13619
+ component: "identity",
13620
+ table: "tenantConfig",
13621
+ prepopulation: "required_template",
13622
+ copyMode: "template_tenant_rewrite",
13623
+ scope: "tenant",
13624
+ uniqueKey: ["tenantId"],
13625
+ description: "Tenant-local config defaults are rewritten during bootstrap."
13626
+ },
13627
+ {
13628
+ component: "identity",
13629
+ table: "tenantIntegrations",
13630
+ prepopulation: "required_template",
13631
+ copyMode: "template_tenant_rewrite",
13632
+ scope: "tenant",
13633
+ uniqueKey: ["tenantId", "integrationKey"],
13634
+ description: "Non-secret integration descriptors are rewritten into each tenant."
13635
+ },
13636
+ {
13637
+ component: "identity",
13638
+ table: "tenantModelSlotBindings",
13639
+ prepopulation: "runtime_secret",
13640
+ copyMode: "none",
13641
+ description: "Tenant model slot bindings reference provider secrets and are runtime-only."
13642
+ },
13643
+ {
13644
+ component: "identity",
13645
+ table: "tenantPolicies",
13646
+ prepopulation: "required_template",
13647
+ copyMode: "template_tenant_rewrite",
13648
+ scope: "tenant",
13649
+ uniqueKey: ["tenantId", "workspaceId", "roleName"],
13650
+ description: "Default tenant policy roles are rewritten during bootstrap."
13651
+ },
13652
+ {
13653
+ component: "identity",
13654
+ table: "tenantProviderSecrets",
13655
+ prepopulation: "runtime_secret",
13656
+ copyMode: "none",
13657
+ description: "Provider secrets are credentials and must never be copied."
13658
+ },
13659
+ {
13660
+ component: "identity",
13661
+ table: "tenantProxyGatewayUsage",
13662
+ prepopulation: "runtime_log",
13663
+ copyMode: "none",
13664
+ description: "Proxy gateway usage rows are runtime telemetry."
13665
+ },
13666
+ {
13667
+ component: "identity",
13668
+ table: "tenantProxyTokenMints",
13669
+ prepopulation: "runtime_secret",
13670
+ copyMode: "none",
13671
+ description: "Proxy token mints are ephemeral secret-bearing runtime rows."
13672
+ },
13673
+ {
13674
+ component: "identity",
13675
+ table: "tenantSandboxAuditEvents",
13676
+ prepopulation: "runtime_log",
13677
+ copyMode: "none",
13678
+ description: "Sandbox audit rows are runtime security logs."
13679
+ },
13680
+ {
13681
+ component: "identity",
13682
+ table: "tenantSecrets",
13683
+ prepopulation: "runtime_secret",
13684
+ copyMode: "none",
13685
+ description: "Tenant secrets are credentials and must never be copied."
13686
+ },
13687
+ {
13688
+ component: "identity",
13689
+ table: "toolAcls",
13690
+ prepopulation: "required_template",
13691
+ copyMode: "template_global",
13692
+ scope: "global",
13693
+ uniqueKey: ["role", "toolName"],
13694
+ description: "Default role-to-tool grants are required for SDK/MCP tool access."
13695
+ },
13696
+ {
13697
+ component: "identity",
13698
+ table: "toolRegistry",
13699
+ prepopulation: "required_template",
13700
+ copyMode: "template_global",
13701
+ scope: "global",
13702
+ uniqueKey: ["toolName"],
13703
+ description: "Core tool catalog rows are required before pack or tenant tools exist."
13704
+ },
13705
+ {
13706
+ component: "identity",
13707
+ table: "users",
13708
+ prepopulation: "runtime_bootstrap",
13709
+ copyMode: "none",
13710
+ description: "Users are created from Clerk/MC principal resolution, not copied."
13711
+ }
13712
+ ];
13713
+ TENANT_BOOTSTRAP_TABLE_REQUIREMENTS.filter(
13714
+ isCopyableSeedRequirement
13715
+ );
13716
+ TENANT_BOOTSTRAP_TABLE_REQUIREMENTS.filter(
13717
+ (entry) => !isCopyableSeedRequirement(entry)
13718
+ ).map((entry) => entry.table);
11770
13719
 
11771
13720
  // ../contracts/src/v1/topics/v1.ts
11772
13721
  var ROOT_TOPIC_ID = "n17tm38rwet7wqgzrmwahyt1z582590y";
@@ -13374,11 +15323,32 @@ function pushTrace(trace, topic, score) {
13374
15323
  score
13375
15324
  });
13376
15325
  }
15326
+ function pickBestTopic(topics2, input) {
15327
+ const ranked = topics2.filter((topic) => topic.status !== "archived").map((topic) => ({
15328
+ topic,
15329
+ score: scoreTopicMatch(topic, input)
15330
+ })).sort((left, right) => {
15331
+ if (right.score !== left.score) {
15332
+ return right.score - left.score;
15333
+ }
15334
+ const leftName = left.topic.name.trim().toLowerCase();
15335
+ const rightName = right.topic.name.trim().toLowerCase();
15336
+ return leftName.localeCompare(rightName);
15337
+ });
15338
+ return ranked[0]?.topic ?? null;
15339
+ }
15340
+ function pickFallbackRootTopic(topics2, input) {
15341
+ const parentless = topics2.filter((topic) => !topic.parentTopicId);
15342
+ return pickBestTopic(parentless, input) ?? pickBestTopic(topics2, input);
15343
+ }
13377
15344
  async function loadTopicUniverse(ctx, input) {
13378
15345
  const desiredTenantId = ctx.tenantId;
13379
15346
  const desiredWorkspaceId = readString2(input.workspaceId) ?? ctx.workspaceId;
13380
15347
  const rawTopics = await fetchTopicTree(ctx);
13381
- const root = rawTopics.find((topic) => topic.rawId === ROOT_TOPIC_ID) ?? await fetchTopicById(ctx, ROOT_TOPIC_ID) ?? rawTopics.find((topic) => !topic.parentTopicId) ?? null;
15348
+ const scopedTopics = rawTopics.filter(
15349
+ (topic) => topicMatchesScope(topic, desiredTenantId, desiredWorkspaceId)
15350
+ );
15351
+ const root = rawTopics.find((topic) => topic.rawId === ROOT_TOPIC_ID) ?? await fetchTopicById(ctx, ROOT_TOPIC_ID) ?? pickFallbackRootTopic(scopedTopics, input) ?? null;
13382
15352
  if (!root) {
13383
15353
  throw new Error("[topic-resolver] Root topic not found.");
13384
15354
  }
@@ -16607,7 +18577,8 @@ function resolveGatewayClaims(authContext) {
16607
18577
  principalType: "human",
16608
18578
  tenantId: authContext.tenantId ?? authContext.servicePrincipalTenantId ?? "unknown",
16609
18579
  workspaceId: authContext.workspaceId ?? authContext.servicePrincipalWorkspaceId,
16610
- roles: [],
18580
+ roles: authContext.roles ?? [],
18581
+ membershipId: authContext.membershipId,
16611
18582
  scopes: [...authContext.grantedScopes],
16612
18583
  authMode: "interactive_user",
16613
18584
  sessionId: authContext.sessionId,
@@ -16622,6 +18593,7 @@ function resolveGatewayClaims(authContext) {
16622
18593
  tenantId: authContext.tenantId ?? authContext.servicePrincipalTenantId ?? "unknown",
16623
18594
  workspaceId: authContext.workspaceId ?? authContext.servicePrincipalWorkspaceId,
16624
18595
  roles: ["service_agent"],
18596
+ membershipId: authContext.membershipId,
16625
18597
  scopes: [...authContext.grantedScopes],
16626
18598
  authMode: "service_principal",
16627
18599
  sessionId: authContext.sessionId,
@@ -16636,6 +18608,7 @@ function resolveGatewayClaims(authContext) {
16636
18608
  tenantId: authContext.tenantId ?? authContext.servicePrincipalTenantId ?? "unknown",
16637
18609
  workspaceId: authContext.workspaceId ?? authContext.servicePrincipalWorkspaceId,
16638
18610
  roles: ["service_agent"],
18611
+ membershipId: authContext.membershipId,
16639
18612
  scopes: [...authContext.grantedScopes],
16640
18613
  authMode: "tenant_api_key",
16641
18614
  sessionId: authContext.sessionId,
@@ -16650,6 +18623,7 @@ function resolveGatewayClaims(authContext) {
16650
18623
  tenantId: authContext.tenantId ?? "unknown",
16651
18624
  workspaceId: authContext.workspaceId,
16652
18625
  roles: authContext.roles ?? [],
18626
+ membershipId: authContext.membershipId,
16653
18627
  scopes: [...authContext.grantedScopes],
16654
18628
  authMode: "session_token",
16655
18629
  sessionId: authContext.sessionId,
@@ -18432,6 +20406,101 @@ function readStringArray9(value) {
18432
20406
  const normalized = value.map((entry) => readString19(entry)).filter((entry) => Boolean(entry));
18433
20407
  return normalized.length > 0 ? normalized : void 0;
18434
20408
  }
20409
+ function normalizeKeyQuestions(keyQuestions) {
20410
+ if (!Array.isArray(keyQuestions)) {
20411
+ return void 0;
20412
+ }
20413
+ const normalized = keyQuestions.map((entry) => {
20414
+ const question = readString19(entry.question);
20415
+ if (!question) {
20416
+ return void 0;
20417
+ }
20418
+ return {
20419
+ question,
20420
+ ...entry.status ? { status: entry.status } : {},
20421
+ ...readString19(entry.answer) ? { answer: readString19(entry.answer) } : {},
20422
+ ...entry.answerConfidence ? { answerConfidence: entry.answerConfidence } : {},
20423
+ ...readString19(entry.linkedQuestionId) ? {
20424
+ linkedQuestionId: decodeExternalId9(
20425
+ readString19(entry.linkedQuestionId),
20426
+ "que",
20427
+ "keyQuestions.linkedQuestionId"
20428
+ )
20429
+ } : {}
20430
+ };
20431
+ }).filter((entry) => Boolean(entry));
20432
+ return normalized.length > 0 ? normalized : void 0;
20433
+ }
20434
+ function normalizeEvidenceSignals(evidenceSignals) {
20435
+ if (!Array.isArray(evidenceSignals)) {
20436
+ return void 0;
20437
+ }
20438
+ const normalized = evidenceSignals.map((entry) => {
20439
+ const signal = readString19(entry.signal);
20440
+ if (!signal) {
20441
+ return void 0;
20442
+ }
20443
+ return {
20444
+ signal,
20445
+ ...typeof entry.collected === "boolean" ? { collected: entry.collected } : {},
20446
+ ...readString19(entry.progress) ? { progress: readString19(entry.progress) } : {},
20447
+ ...readString19(entry.notes) ? { notes: readString19(entry.notes) } : {}
20448
+ };
20449
+ }).filter((entry) => Boolean(entry));
20450
+ return normalized.length > 0 ? normalized : void 0;
20451
+ }
20452
+ function normalizeDecisionGate(input) {
20453
+ const source = input.decisionGate ?? (input.goCriteria || input.noGoSignals ? {
20454
+ goCriteria: input.goCriteria ?? [],
20455
+ noGoSignals: input.noGoSignals ?? []
20456
+ } : void 0);
20457
+ if (!source) {
20458
+ return void 0;
20459
+ }
20460
+ return {
20461
+ goCriteria: readStringArray9(source.goCriteria) ?? [],
20462
+ noGoSignals: readStringArray9(source.noGoSignals) ?? [],
20463
+ ...source.verdict ? { verdict: source.verdict } : {},
20464
+ ...readString19(source.verdictRationale) ? { verdictRationale: readString19(source.verdictRationale) } : {},
20465
+ ...typeof source.decidedAt === "number" && Number.isFinite(source.decidedAt) ? { decidedAt: source.decidedAt } : {},
20466
+ ...readString19(source.decidedBy) ? { decidedBy: readString19(source.decidedBy) } : {}
20467
+ };
20468
+ }
20469
+ function normalizeMergeOutcomes(outcomes) {
20470
+ const keyFindings = [];
20471
+ const scoringOutcomes = [];
20472
+ for (const outcome of outcomes) {
20473
+ const finding = readString19(outcome);
20474
+ if (finding) {
20475
+ keyFindings.push(finding);
20476
+ continue;
20477
+ }
20478
+ const record = asRecord15(outcome);
20479
+ if (!Object.keys(record).length) {
20480
+ throw createWorktreesError({
20481
+ message: "[worktrees] merge outcomes must be strings or { beliefId, confidence, rationale } objects.",
20482
+ status: 400,
20483
+ code: "INVALID_REQUEST",
20484
+ invariantCode: "request.valid_shape",
20485
+ suggestion: "Pass string outcomes for key findings, or scoring objects for belief confidence outcomes."
20486
+ });
20487
+ }
20488
+ scoringOutcomes.push({
20489
+ beliefId: requireString3(record.beliefId, "outcomes[].beliefId"),
20490
+ confidence: readNumber13(record.confidence) ?? (() => {
20491
+ throw createWorktreesError({
20492
+ message: "[worktrees] outcomes[].confidence must be a finite number.",
20493
+ status: 400,
20494
+ code: "INVALID_REQUEST",
20495
+ invariantCode: "request.valid_shape",
20496
+ suggestion: "Provide confidence as a number when scoring a belief outcome."
20497
+ });
20498
+ })(),
20499
+ rationale: requireString3(record.rationale, "outcomes[].rationale")
20500
+ });
20501
+ }
20502
+ return { keyFindings, scoringOutcomes };
20503
+ }
18435
20504
  function compareNullableNumber(left, right, fallback = 9999) {
18436
20505
  return (left ?? fallback) - (right ?? fallback);
18437
20506
  }
@@ -18676,14 +20745,33 @@ function buildWorktreeCampaignList(records) {
18676
20745
  }
18677
20746
  async function createWorktree(deps, input) {
18678
20747
  const topicRawId = decodeExternalId9(input.topicId, "top", "topicId");
20748
+ const targetBeliefIds = input.targetBeliefIds ?? input.beliefIds;
18679
20749
  const created = await deps.createWorktree({
18680
20750
  title: requireString3(input.title, "title"),
18681
20751
  topicRawId,
18682
20752
  objective: readString19(input.objective),
18683
20753
  hypothesis: readString19(input.hypothesis),
18684
- beliefRawIds: input.beliefIds?.map(
20754
+ rationale: readString19(input.rationale),
20755
+ worktreeType: readString19(input.worktreeType),
20756
+ startDate: typeof input.startDate === "number" && Number.isFinite(input.startDate) ? input.startDate : void 0,
20757
+ endDate: typeof input.endDate === "number" && Number.isFinite(input.endDate) ? input.endDate : void 0,
20758
+ durationWeeks: typeof input.durationWeeks === "number" && Number.isFinite(input.durationWeeks) ? input.durationWeeks : void 0,
20759
+ confidenceImpact: input.confidenceImpact,
20760
+ beliefFocus: readString19(input.beliefFocus),
20761
+ beliefRawIds: targetBeliefIds?.map(
18685
20762
  (id) => decodeExternalId9(id, "bel", "beliefIds")
18686
20763
  ),
20764
+ targetBeliefRawIds: input.targetBeliefIds?.map(
20765
+ (id) => decodeExternalId9(id, "bel", "targetBeliefIds")
20766
+ ),
20767
+ targetQuestionRawIds: input.targetQuestionIds?.map(
20768
+ (id) => decodeExternalId9(id, "que", "targetQuestionIds")
20769
+ ),
20770
+ keyQuestions: normalizeKeyQuestions(input.keyQuestions),
20771
+ evidenceSignals: normalizeEvidenceSignals(input.evidenceSignals),
20772
+ decisionGate: normalizeDecisionGate(input),
20773
+ goCriteria: readStringArray9(input.goCriteria),
20774
+ noGoSignals: readStringArray9(input.noGoSignals),
18687
20775
  autoShape: typeof input.autoShape === "boolean" ? input.autoShape : void 0,
18688
20776
  domainPackId: readString19(input.domainPackId),
18689
20777
  campaign: typeof input.campaign === "number" && Number.isFinite(input.campaign) ? input.campaign : void 0,
@@ -18815,11 +20903,45 @@ async function updateWorktreeTargets(deps, input) {
18815
20903
  }
18816
20904
  async function mergeWorktree(deps, input) {
18817
20905
  const rawId = decodeExternalId9(input.id, "wt", "id");
18818
- const summary = readString19(input.summary) ?? "Worktree merged.";
18819
- await deps.completeWorktree({ worktreeRawId: rawId, summary });
20906
+ const { keyFindings, scoringOutcomes } = normalizeMergeOutcomes(input.outcomes);
20907
+ const summary = readString19(input.summary) ?? keyFindings[0] ?? "Worktree merged.";
20908
+ const completeKeyFindings = keyFindings.length > 0 ? keyFindings : [summary];
20909
+ const worktree = await deps.fetchWorktree(rawId);
20910
+ if (!worktree) {
20911
+ throw createWorktreesError({
20912
+ message: `[worktrees] Worktree not found: ${rawId}.`,
20913
+ status: 404,
20914
+ code: "NOT_FOUND",
20915
+ invariantCode: "resource.exists"
20916
+ });
20917
+ }
20918
+ const worktreeStatus = readString19(asRecord15(worktree).status);
20919
+ if (worktreeStatus === "planning") {
20920
+ await deps.activateWorktree({ worktreeRawId: rawId });
20921
+ await deps.completeWorktree({
20922
+ worktreeRawId: rawId,
20923
+ summary,
20924
+ keyFindings: completeKeyFindings
20925
+ });
20926
+ } else if (!worktreeStatus || worktreeStatus === "active") {
20927
+ await deps.completeWorktree({
20928
+ worktreeRawId: rawId,
20929
+ summary,
20930
+ keyFindings: completeKeyFindings
20931
+ });
20932
+ } else if (worktreeStatus !== "completed" && worktreeStatus !== "merged") {
20933
+ throw createWorktreesError({
20934
+ message: `[worktrees] Cannot merge worktree in status "${worktreeStatus}".`,
20935
+ status: 409,
20936
+ code: "CONFLICT",
20937
+ invariantCode: "worktree.mergeable_status",
20938
+ suggestion: "Merge only planning, active, completed, or already-merged worktrees.",
20939
+ details: { worktreeId: encodeWorktreeId(rawId), status: worktreeStatus }
20940
+ });
20941
+ }
18820
20942
  const failedBeliefs = [];
18821
20943
  let beliefsScored = 0;
18822
- for (const outcome of input.outcomes) {
20944
+ for (const outcome of scoringOutcomes) {
18823
20945
  try {
18824
20946
  await deps.scoreBeliefOutcome({
18825
20947
  worktreeRawId: rawId,
@@ -18895,15 +21017,35 @@ function summarizeWorktreeCollection(rows) {
18895
21017
  function buildCreateMutationArgs(input, userId) {
18896
21018
  const objective = input.objective?.trim();
18897
21019
  const hypothesis = input.hypothesis?.trim();
21020
+ const rationale = input.rationale?.trim();
21021
+ const worktreeType = input.worktreeType?.trim();
21022
+ const beliefFocus = input.beliefFocus?.trim();
18898
21023
  const gate = input.gate?.trim();
18899
21024
  const lensId = input.lensId?.trim();
21025
+ const targetBeliefIds = input.targetBeliefIds && input.targetBeliefIds.length > 0 ? input.targetBeliefIds : input.beliefIds;
18900
21026
  return {
18901
21027
  name: input.title,
18902
21028
  topicId: input.topicId,
18903
21029
  createdBy: userId,
18904
21030
  ...objective ? { objective } : {},
18905
21031
  ...hypothesis ? { hypothesis } : {},
18906
- ...objective || hypothesis ? { beliefFocus: hypothesis ?? objective } : {},
21032
+ ...rationale ? { rationale } : {},
21033
+ ...worktreeType ? { worktreeType } : {},
21034
+ ...typeof input.startDate === "number" ? { startDate: input.startDate } : {},
21035
+ ...typeof input.endDate === "number" ? { endDate: input.endDate } : {},
21036
+ ...typeof input.durationWeeks === "number" ? { durationWeeks: input.durationWeeks } : {},
21037
+ ...input.confidenceImpact ? { confidenceImpact: input.confidenceImpact } : {},
21038
+ ...beliefFocus || objective || hypothesis ? { beliefFocus: beliefFocus ?? hypothesis ?? objective } : {},
21039
+ ...Array.isArray(input.targetQuestionIds) && input.targetQuestionIds.length > 0 ? { targetQuestionIds: input.targetQuestionIds.map((id) => id) } : Array.isArray(input.questionRawIds) && input.questionRawIds.length > 0 ? { targetQuestionIds: input.questionRawIds.map((id) => id) } : {},
21040
+ ...Array.isArray(targetBeliefIds) && targetBeliefIds.length > 0 ? { targetBeliefIds: targetBeliefIds.map((id) => id) } : {},
21041
+ ...Array.isArray(input.keyQuestions) && input.keyQuestions.length > 0 ? { keyQuestions: input.keyQuestions } : {},
21042
+ ...Array.isArray(input.evidenceSignals) && input.evidenceSignals.length > 0 ? { evidenceSignals: input.evidenceSignals } : {},
21043
+ ...input.decisionGate ? { decisionGate: input.decisionGate } : input.goCriteria || input.noGoSignals ? {
21044
+ decisionGate: {
21045
+ goCriteria: input.goCriteria ?? [],
21046
+ noGoSignals: input.noGoSignals ?? []
21047
+ }
21048
+ } : {},
18907
21049
  ...typeof input.campaign === "number" ? { campaign: input.campaign } : {},
18908
21050
  ...input.lane ? { lane: input.lane } : {},
18909
21051
  ...typeof input.laneOrderInCampaign === "number" ? { laneOrderInCampaign: input.laneOrderInCampaign } : {},
@@ -18912,7 +21054,10 @@ function buildCreateMutationArgs(input, userId) {
18912
21054
  ...Array.isArray(input.blocks) && input.blocks.length > 0 ? { blocks: input.blocks.map((id) => id) } : {},
18913
21055
  ...gate ? { gate } : {},
18914
21056
  ...lensId ? { lensId } : {},
18915
- ...Array.isArray(input.beliefIds) && input.beliefIds.length > 0 ? { targetBeliefIds: input.beliefIds.map((id) => id) } : {}
21057
+ ...Array.isArray(input.proofArtifacts) ? { proofArtifacts: input.proofArtifacts } : {},
21058
+ ...input.staffingHint?.trim() ? { staffingHint: input.staffingHint.trim() } : {},
21059
+ ...typeof input.lastReconciledAt === "number" ? { lastReconciledAt: input.lastReconciledAt } : {},
21060
+ ...input.autoFixPolicy ? { autoFixPolicy: input.autoFixPolicy } : {}
18916
21061
  };
18917
21062
  }
18918
21063
  function readString20(value) {
@@ -18985,7 +21130,9 @@ function createGatewayWorktreesPort(authContext) {
18985
21130
  ...input,
18986
21131
  topicId: input.topicRawId,
18987
21132
  title: input.title,
18988
- beliefIds: input.beliefRawIds
21133
+ beliefIds: input.beliefRawIds,
21134
+ targetBeliefIds: input.targetBeliefRawIds,
21135
+ targetQuestionIds: input.targetQuestionRawIds
18989
21136
  },
18990
21137
  authContext.userId
18991
21138
  ),
@@ -19000,7 +21147,9 @@ function createGatewayWorktreesPort(authContext) {
19000
21147
  ...input,
19001
21148
  topicId: input.topicRawId,
19002
21149
  title: input.title,
19003
- beliefIds: input.beliefRawIds
21150
+ beliefIds: input.beliefRawIds,
21151
+ targetBeliefIds: input.targetBeliefRawIds,
21152
+ targetQuestionIds: input.targetQuestionRawIds
19004
21153
  },
19005
21154
  authContext.userId
19006
21155
  ));
@@ -19028,7 +21177,7 @@ function createGatewayWorktreesPort(authContext) {
19028
21177
  completeWorktree(args) {
19029
21178
  return authContext.convex.mutation(api.worktrees.complete, {
19030
21179
  worktreeId: args.worktreeRawId,
19031
- keyFindings: [args.summary],
21180
+ keyFindings: args.keyFindings?.length ? args.keyFindings : [args.summary],
19032
21181
  decisionsReached: [],
19033
21182
  nextSteps: [],
19034
21183
  userId: authContext.userId
@@ -20846,6 +22995,40 @@ function normalizeRecommendation(row) {
20846
22995
  recommendationId: cleanString(suggestion.recommendationId) ?? cleanString(suggestion.suggestionId)
20847
22996
  };
20848
22997
  }
22998
+ function readChangeTimestamp(row) {
22999
+ return cleanNumber(row.updatedAt) ?? cleanNumber(row.actedAt) ?? cleanNumber(row.createdAt);
23000
+ }
23001
+ function includesAny(value, expected) {
23002
+ if (!expected || expected.length === 0) {
23003
+ return true;
23004
+ }
23005
+ if (Array.isArray(value)) {
23006
+ return value.some((entry) => expected.includes(String(entry)));
23007
+ }
23008
+ return typeof value === "string" && expected.includes(value);
23009
+ }
23010
+ function normalizeGraphChange(row, kind) {
23011
+ const metadata = asRecord21(row.metadata);
23012
+ const sourceNodeIds = cleanStringArray(row.sourceNodeIds) ?? cleanStringArray(row.targetNodeIds) ?? [
23013
+ cleanString(row.targetNodeId),
23014
+ cleanString(row.secondaryNodeId),
23015
+ cleanString(row.resultNodeId)
23016
+ ].filter((value) => Boolean(value));
23017
+ const sourceEdgeIds = cleanStringArray(row.sourceEdgeIds) ?? [];
23018
+ return {
23019
+ changeId: cleanString(row.changeId) ?? cleanString(row.suggestionId) ?? cleanString(row.analysisId) ?? cleanString(row.recommendationId) ?? cleanString(row._id),
23020
+ analysisId: cleanString(row.analysisId) ?? cleanString(row.analysisResultId) ?? cleanString(row._id),
23021
+ suggestionId: cleanString(row.suggestionId),
23022
+ topicId: cleanString(row.topicId),
23023
+ workspaceId: cleanString(row.workspaceId),
23024
+ changeType: cleanString(row.changeType) ?? kind,
23025
+ nodeIds: sourceNodeIds,
23026
+ edgeIds: sourceEdgeIds,
23027
+ summary: cleanString(row.summary) ?? cleanString(row.title) ?? cleanString(row.analysisText) ?? cleanString(row.rationale),
23028
+ metadata,
23029
+ createdAt: readChangeTimestamp(row)
23030
+ };
23031
+ }
20849
23032
  function normalizeNodeResult(row, input) {
20850
23033
  const metadata = asRecord21(row.metadata);
20851
23034
  const confidence = cleanNumber(row.confidence) ?? cleanNumber(metadata.confidence) ?? cleanNumber(row.baseRate);
@@ -20952,6 +23135,37 @@ async function listGraphSuggestionsFromGatewayAuth(authContext, input) {
20952
23135
  suggestions: Array.isArray(suggestions) ? suggestions.map((row) => normalizeSuggestion(asRecord21(row))) : []
20953
23136
  };
20954
23137
  }
23138
+ async function listGraphChangesFromGatewayAuth(authContext, input) {
23139
+ const minimumCreatedAt = cleanNumber(input.minimumCreatedAt) ?? cleanNumber(input.since) ?? cleanNumber(input.createdAt) ?? cleanNumber(input.analysisCreatedAt);
23140
+ if (minimumCreatedAt === void 0) {
23141
+ throw new Error("minimumCreatedAt is required");
23142
+ }
23143
+ const sourceNodeIds = cleanStringArray(input.sourceNodeIds) ?? (cleanString(input.nodeId) ? [cleanString(input.nodeId)] : void 0);
23144
+ const sourceEdgeIds = cleanStringArray(input.sourceEdgeIds) ?? (cleanString(input.edgeId) ? [cleanString(input.edgeId)] : void 0);
23145
+ const limit = readLimit(input.limit) ?? 100;
23146
+ const [{ analyses }, { suggestions }] = await Promise.all([
23147
+ listGraphAnalysesFromGatewayAuth(authContext, input),
23148
+ listGraphSuggestionsFromGatewayAuth(authContext, input)
23149
+ ]);
23150
+ const analysisChanges = analyses.map((row) => normalizeGraphChange(asRecord21(row), "analysis_recorded")).filter((row) => {
23151
+ const createdAt = cleanNumber(row.createdAt);
23152
+ return createdAt !== void 0 && createdAt >= minimumCreatedAt && includesAny(row.nodeIds, sourceNodeIds) && includesAny(row.edgeIds, sourceEdgeIds);
23153
+ });
23154
+ const suggestionChanges = suggestions.map((row) => normalizeGraphChange(asRecord21(row), "suggestion_recorded")).filter((row) => {
23155
+ const createdAt = cleanNumber(row.createdAt);
23156
+ return createdAt !== void 0 && createdAt >= minimumCreatedAt && includesAny(row.nodeIds, sourceNodeIds) && includesAny(row.edgeIds, sourceEdgeIds);
23157
+ });
23158
+ const changes = [...analysisChanges, ...suggestionChanges].sort((left, right) => {
23159
+ const leftAt = cleanNumber(left.createdAt) ?? 0;
23160
+ const rightAt = cleanNumber(right.createdAt) ?? 0;
23161
+ return rightAt - leftAt;
23162
+ }).slice(0, limit);
23163
+ return {
23164
+ changes,
23165
+ items: changes,
23166
+ total: changes.length
23167
+ };
23168
+ }
20955
23169
  async function updateGraphSuggestionStatusFromGatewayAuth(authContext, input) {
20956
23170
  const suggestion = await authContext.convex.mutation(
20957
23171
  api.graphAnalysisResults.updateSuggestionStatus,
@@ -21121,6 +23335,13 @@ async function handleGraphAnalysisListSuggestions(args) {
21121
23335
  run: () => listGraphSuggestionsFromGatewayAuth(args.authContext, args.query)
21122
23336
  });
21123
23337
  }
23338
+ async function handleGraphAnalysisListChanges(args) {
23339
+ return withGraphRoute({
23340
+ ...args,
23341
+ fallbackMessage: "Failed to list graph analysis changes.",
23342
+ run: () => listGraphChangesFromGatewayAuth(args.authContext, args.query)
23343
+ });
23344
+ }
21124
23345
  async function handleGraphAnalysisUpdateSuggestion(args) {
21125
23346
  return withGraphRoute({
21126
23347
  ...args,
@@ -22543,6 +24764,36 @@ function readStringArray17(value) {
22543
24764
  const normalized = value.map((entry) => readString33(entry)).filter((entry) => Boolean(entry));
22544
24765
  return normalized.length > 0 ? normalized : void 0;
22545
24766
  }
24767
+ function readObjectArray(value) {
24768
+ if (!Array.isArray(value)) {
24769
+ return void 0;
24770
+ }
24771
+ const normalized = value.map((entry) => asRecord30(entry)).filter((entry) => Object.keys(entry).length > 0);
24772
+ return normalized.length > 0 ? normalized : void 0;
24773
+ }
24774
+ function readConfidenceImpact(value) {
24775
+ return value === "high" || value === "medium" || value === "low" ? value : void 0;
24776
+ }
24777
+ function normalizeMergeOutcomes2(value) {
24778
+ if (!Array.isArray(value)) {
24779
+ return [];
24780
+ }
24781
+ return value.map((entry) => {
24782
+ const finding = readString33(entry);
24783
+ if (finding) {
24784
+ return finding;
24785
+ }
24786
+ const row = asRecord30(entry);
24787
+ if (!Object.keys(row).length) {
24788
+ return null;
24789
+ }
24790
+ return {
24791
+ beliefId: readString33(row.beliefId) ?? "",
24792
+ confidence: readNumber22(row.confidence) ?? Number.NaN,
24793
+ rationale: readString33(row.rationale) ?? ""
24794
+ };
24795
+ }).filter((entry) => entry !== null);
24796
+ }
22546
24797
  function handleWorktreesError(error, fallbackMessage, correlationId, policyTraceId) {
22547
24798
  const resolved = resolveServerCoreError(error, fallbackMessage);
22548
24799
  return errorResponse({
@@ -22559,12 +24810,29 @@ function handleWorktreesError(error, fallbackMessage, correlationId, policyTrace
22559
24810
  async function handleWorktreeCreate(args) {
22560
24811
  try {
22561
24812
  const body = asRecord30(args.body);
24813
+ const goCriteria = readStringArray17(body.goCriteria);
24814
+ const noGoSignals = readStringArray17(body.noGoSignals);
22562
24815
  const payload = await createWorktreeFromGatewayAuth(args.authContext, {
22563
- title: readString33(body.title) ?? "",
24816
+ title: readString33(body.title) ?? readString33(body.name) ?? "",
22564
24817
  topicId: readString33(body.topicId ?? body.projectId) ?? "",
22565
24818
  objective: readString33(body.objective),
22566
24819
  hypothesis: readString33(body.hypothesis),
22567
- beliefIds: readStringArray17(body.beliefIds) ?? readStringArray17(body.beliefs),
24820
+ rationale: readString33(body.rationale),
24821
+ worktreeType: readString33(body.worktreeType),
24822
+ startDate: readNumber22(body.startDate),
24823
+ endDate: readNumber22(body.endDate),
24824
+ durationWeeks: readNumber22(body.durationWeeks),
24825
+ confidenceImpact: readConfidenceImpact(body.confidenceImpact),
24826
+ beliefFocus: readString33(body.beliefFocus),
24827
+ beliefIds: readStringArray17(body.targetBeliefIds) ?? readStringArray17(body.beliefIds) ?? readStringArray17(body.beliefs),
24828
+ targetBeliefIds: readStringArray17(body.targetBeliefIds),
24829
+ targetQuestionIds: readStringArray17(body.targetQuestionIds),
24830
+ keyQuestions: readObjectArray(body.keyQuestions),
24831
+ evidenceSignals: readObjectArray(body.evidenceSignals),
24832
+ decisionGate: body.decisionGate && typeof body.decisionGate === "object" && !Array.isArray(body.decisionGate) ? body.decisionGate : goCriteria || noGoSignals ? {
24833
+ goCriteria: goCriteria ?? [],
24834
+ noGoSignals: noGoSignals ?? []
24835
+ } : void 0,
22568
24836
  autoShape: typeof body.autoShape === "boolean" ? body.autoShape : void 0,
22569
24837
  domainPackId: readString33(body.domainPackId),
22570
24838
  campaign: readNumber22(body.campaign),
@@ -22717,12 +24985,7 @@ async function handleWorktreeUpdate(args) {
22717
24985
  async function handleWorktreeMerge(args) {
22718
24986
  try {
22719
24987
  const body = asRecord30(args.body);
22720
- const rawOutcomes = Array.isArray(body.outcomes) ? body.outcomes : [];
22721
- const outcomes = rawOutcomes.map((entry) => asRecord30(entry)).map((entry) => ({
22722
- beliefId: readString33(entry.beliefId) ?? "",
22723
- confidence: readNumber22(entry.confidence) ?? Number.NaN,
22724
- rationale: readString33(entry.rationale) ?? ""
22725
- }));
24988
+ const outcomes = normalizeMergeOutcomes2(body.outcomes);
22726
24989
  const payload = await mergeWorktreeFromGatewayAuth(args.authContext, {
22727
24990
  id: args.worktreeId,
22728
24991
  summary: readString33(body.summary),
@@ -22875,6 +25138,6 @@ async function handleWorktreeBulkCreate(args) {
22875
25138
  }
22876
25139
  }
22877
25140
 
22878
- export { handleBeliefArchive, handleBeliefBatchUpdateCriticality, handleBeliefBisect, handleBeliefConfidenceHistory, handleBeliefCreate, handleBeliefCreateContract, handleBeliefFork, handleBeliefGet, handleBeliefLineage, handleBeliefLink, handleBeliefList, handleBeliefReassignTopic, handleBeliefRefine, handleBeliefRelationships, handleBeliefUnlinkEvidence, handleBeliefUpdateConfidence, handleBeliefUpdateCriticality, handleBeliefUpdateRationale, handleBeliefUpdateStatus, handleContradictionFlag, handleContradictionGet, handleContradictionList, handleEdgeBatchCreate, handleEdgeCreate, handleEdgeDelete, handleEdgeList, handleEdgeRemove, handleEdgeTraverse, handleEdgeUpdate, handleEdgesRemoveBetween, handleEventsList, handleEventsReplay, handleEvidenceClassify, handleEvidenceClassifyBatch, handleEvidenceCreate, handleEvidenceFlagIncorrect, handleEvidenceGet, handleEvidenceLink, handleEvidenceList, handleEvidenceRemove, handleEvidenceSearch, handleEvidenceUpdate, handleEvidenceUpdateStatus, handleEvidenceUpdateVerificationStatus, handleGraphAnalysisCompute, handleGraphAnalysisLatest, handleGraphAnalysisList, handleGraphAnalysisListSuggestions, handleGraphAnalysisSave, handleGraphAnalysisSaveSuggestions, handleGraphAnalysisUpdateSuggestion, handleGraphAnalyze, handleGraphBias, handleGraphEdgeList, handleGraphFalsify, handleGraphGaps, handleGraphNeighborhood, handleGraphNodeList, handleGraphRecommendationGet, handleGraphRecommendationStatus, handleGraphRecommendationsList, handleGraphTraverse, handleIdentityWhoami, handleOntologyBind, handleOntologyGet, handleOntologyList, handleOntologyMatch, handleOrgGraphByProvenance, handleOrgGraphNodeGet, handleOrgGraphPublished, handleOrgGraphSearch, handleQuestionAdd, handleQuestionAdvanceToConviction, handleQuestionAnswer, handleQuestionArchive, handleQuestionBatchCreate, handleQuestionCreate, handleQuestionDelete, handleQuestionFinalizeConviction, handleQuestionGet, handleQuestionGetAnswer, handleQuestionList, handleQuestionRefine, handleQuestionUpdate, handleQuestionUpdateConviction, handleQuestionUpdatePriority, handleQuestionUpdateStatus, handleSearchResources, handleSourceGet, handleSourceUpsert, handleTaskComplete, handleTaskCreate, handleTaskList, handleTaskUpdate, handleTopicBulkCreate, handleTopicCoverage, handleTopicCreate, handleTopicGet, handleTopicList, handleTopicRemove, handleTopicTree, handleTopicUpdate, handleWebhookCreate, handleWebhookDelete, handleWebhookDeliveries, handleWebhookGet, handleWebhookHealth, handleWebhookList, handleWebhookTest, handleWebhookUpdate, handleWorktreeActivate, handleWorktreeAdvancePhase, handleWorktreeBulkCreate, handleWorktreeComplete, handleWorktreeCreate, handleWorktreeList, handleWorktreeListAll, handleWorktreeListCampaigns, handleWorktreeMerge, handleWorktreePatchState, handleWorktreeSetPhase, handleWorktreeUpdate, handleWorktreeUpdateTargets };
25141
+ export { handleBeliefArchive, handleBeliefBatchUpdateCriticality, handleBeliefBisect, handleBeliefConfidenceHistory, handleBeliefCreate, handleBeliefCreateContract, handleBeliefFork, handleBeliefGet, handleBeliefLineage, handleBeliefLink, handleBeliefList, handleBeliefReassignTopic, handleBeliefRefine, handleBeliefRelationships, handleBeliefUnlinkEvidence, handleBeliefUpdateConfidence, handleBeliefUpdateCriticality, handleBeliefUpdateRationale, handleBeliefUpdateStatus, handleContradictionFlag, handleContradictionGet, handleContradictionList, handleEdgeBatchCreate, handleEdgeCreate, handleEdgeDelete, handleEdgeList, handleEdgeRemove, handleEdgeTraverse, handleEdgeUpdate, handleEdgesRemoveBetween, handleEventsList, handleEventsReplay, handleEvidenceClassify, handleEvidenceClassifyBatch, handleEvidenceCreate, handleEvidenceFlagIncorrect, handleEvidenceGet, handleEvidenceLink, handleEvidenceList, handleEvidenceRemove, handleEvidenceSearch, handleEvidenceUpdate, handleEvidenceUpdateStatus, handleEvidenceUpdateVerificationStatus, handleGraphAnalysisCompute, handleGraphAnalysisLatest, handleGraphAnalysisList, handleGraphAnalysisListChanges, handleGraphAnalysisListSuggestions, handleGraphAnalysisSave, handleGraphAnalysisSaveSuggestions, handleGraphAnalysisUpdateSuggestion, handleGraphAnalyze, handleGraphBias, handleGraphEdgeList, handleGraphFalsify, handleGraphGaps, handleGraphNeighborhood, handleGraphNodeList, handleGraphRecommendationGet, handleGraphRecommendationStatus, handleGraphRecommendationsList, handleGraphTraverse, handleIdentityWhoami, handleOntologyBind, handleOntologyGet, handleOntologyList, handleOntologyMatch, handleOrgGraphByProvenance, handleOrgGraphNodeGet, handleOrgGraphPublished, handleOrgGraphSearch, handleQuestionAdd, handleQuestionAdvanceToConviction, handleQuestionAnswer, handleQuestionArchive, handleQuestionBatchCreate, handleQuestionCreate, handleQuestionDelete, handleQuestionFinalizeConviction, handleQuestionGet, handleQuestionGetAnswer, handleQuestionList, handleQuestionRefine, handleQuestionUpdate, handleQuestionUpdateConviction, handleQuestionUpdatePriority, handleQuestionUpdateStatus, handleSearchResources, handleSourceGet, handleSourceUpsert, handleTaskComplete, handleTaskCreate, handleTaskList, handleTaskUpdate, handleTopicBulkCreate, handleTopicCoverage, handleTopicCreate, handleTopicGet, handleTopicList, handleTopicRemove, handleTopicTree, handleTopicUpdate, handleWebhookCreate, handleWebhookDelete, handleWebhookDeliveries, handleWebhookGet, handleWebhookHealth, handleWebhookList, handleWebhookTest, handleWebhookUpdate, handleWorktreeActivate, handleWorktreeAdvancePhase, handleWorktreeBulkCreate, handleWorktreeComplete, handleWorktreeCreate, handleWorktreeList, handleWorktreeListAll, handleWorktreeListCampaigns, handleWorktreeMerge, handleWorktreePatchState, handleWorktreeSetPhase, handleWorktreeUpdate, handleWorktreeUpdateTargets };
22879
25142
  //# sourceMappingURL=gateway.js.map
22880
25143
  //# sourceMappingURL=gateway.js.map