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

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
@@ -3880,7 +3880,9 @@ defineTable({
3880
3880
  "defaultProjectVisibility": z.enum(["private", "team", "firm", "external", "public"]).optional(),
3881
3881
  "deployments": z.record(z.object({
3882
3882
  "url": z.string(),
3883
- "encryptedDeployKey": z.string()
3883
+ "target": z.enum(["kernelDeployment", "appDeployment"]).optional(),
3884
+ "encryptedDeployKey": z.string().optional(),
3885
+ "credentialRef": z.string().optional()
3884
3886
  })).optional(),
3885
3887
  "metadata": z.record(z.any()).optional(),
3886
3888
  "createdBy": z.string().optional(),
@@ -5077,6 +5079,14 @@ var ADD_WORKTREE = {
5077
5079
  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
5080
  parameters: {
5079
5081
  title: { type: "string", description: "Worktree name/objective" },
5082
+ name: {
5083
+ type: "string",
5084
+ description: "Optional storage-name alias for callers that already use backend naming"
5085
+ },
5086
+ projectId: {
5087
+ type: "string",
5088
+ description: "Legacy topicId alias"
5089
+ },
5080
5090
  topicId: { type: "string", description: "Optional topic scope hint" },
5081
5091
  branchId: {
5082
5092
  type: "string",
@@ -5090,14 +5100,87 @@ var ADD_WORKTREE = {
5090
5100
  type: "string",
5091
5101
  description: "The testable claim this worktree investigates"
5092
5102
  },
5103
+ rationale: {
5104
+ type: "string",
5105
+ description: "Why this worktree exists and why it belongs in the campaign"
5106
+ },
5107
+ worktreeType: {
5108
+ type: "string",
5109
+ description: "Schema-enum worktree type used by the kernel lifecycle and retrieval layers"
5110
+ },
5111
+ gate: {
5112
+ type: "string",
5113
+ description: "Exit gate name for this worktree"
5114
+ },
5115
+ startDate: {
5116
+ type: "number",
5117
+ description: "Planned start timestamp in milliseconds since epoch"
5118
+ },
5119
+ endDate: {
5120
+ type: "number",
5121
+ description: "Planned end timestamp in milliseconds since epoch"
5122
+ },
5123
+ durationWeeks: {
5124
+ type: "number",
5125
+ description: "Planned duration in weeks"
5126
+ },
5127
+ confidenceImpact: {
5128
+ type: "string",
5129
+ description: "Expected confidence impact if the worktree succeeds",
5130
+ enum: ["high", "medium", "low"]
5131
+ },
5132
+ beliefFocus: {
5133
+ type: "string",
5134
+ description: "Natural-language focus spanning the target belief neighborhood"
5135
+ },
5093
5136
  beliefIds: {
5094
5137
  type: "array",
5095
- description: "Beliefs to test in this worktree"
5138
+ description: "Legacy alias for targetBeliefIds"
5139
+ },
5140
+ beliefs: {
5141
+ type: "array",
5142
+ description: "Legacy alias for targetBeliefIds"
5143
+ },
5144
+ targetBeliefIds: {
5145
+ type: "array",
5146
+ description: "Belief node IDs this worktree is expected to test or update"
5147
+ },
5148
+ targetQuestionIds: {
5149
+ type: "array",
5150
+ description: "Question node IDs this worktree is expected to answer"
5151
+ },
5152
+ keyQuestions: {
5153
+ type: "array",
5154
+ description: "Inline key question objects with question, optional status, answer, answerConfidence, and linkedQuestionId"
5155
+ },
5156
+ evidenceSignals: {
5157
+ type: "array",
5158
+ description: "Evidence signal objects with signal, optional collected state, progress, and notes"
5159
+ },
5160
+ decisionGate: {
5161
+ type: "object",
5162
+ description: "Decision gate object with goCriteria, noGoSignals, optional verdict, rationale, decidedAt, and decidedBy"
5163
+ },
5164
+ goCriteria: {
5165
+ type: "array",
5166
+ description: "Shorthand go criteria used to build decisionGate"
5167
+ },
5168
+ noGoSignals: {
5169
+ type: "array",
5170
+ description: "Shorthand no-go signals used to build decisionGate"
5171
+ },
5172
+ proofArtifacts: {
5173
+ type: "array",
5174
+ description: "Expected proof artifacts required to close the worktree"
5096
5175
  },
5097
5176
  autoShape: {
5098
5177
  type: "boolean",
5099
5178
  description: "Whether to invoke inquiry auto-shaping during worktree creation"
5100
5179
  },
5180
+ autoFixPolicy: {
5181
+ type: "object",
5182
+ description: "Policy for permitted automatic remediation inside the worktree"
5183
+ },
5101
5184
  domainPackId: {
5102
5185
  type: "string",
5103
5186
  description: "Optional domain pack whose shaping hooks should influence generated questions and tasks"
@@ -5126,9 +5209,17 @@ var ADD_WORKTREE = {
5126
5209
  type: "array",
5127
5210
  description: "Worktree IDs blocked by this worktree"
5128
5211
  },
5129
- gate: {
5212
+ staffingHint: {
5130
5213
  type: "string",
5131
- description: "Exit gate name for this worktree"
5214
+ description: "Suggested staffing or agent allocation note"
5215
+ },
5216
+ lensId: {
5217
+ type: "string",
5218
+ description: "Lens that scopes this worktree when applicable"
5219
+ },
5220
+ lastReconciledAt: {
5221
+ type: "number",
5222
+ description: "Timestamp when worktree metadata was last reconciled"
5132
5223
  }
5133
5224
  },
5134
5225
  required: ["title", "topicId"],
@@ -5158,7 +5249,7 @@ var MERGE = {
5158
5249
  worktreeId: { type: "string", description: "The worktree to merge" },
5159
5250
  outcomes: {
5160
5251
  type: "array",
5161
- description: "Scoring outcomes for each belief: { beliefId, confidence, rationale }"
5252
+ description: "Merge outcomes as key-finding strings, or scoring outcomes for beliefs: { beliefId, confidence, rationale }"
5162
5253
  },
5163
5254
  summary: { type: "string", description: "Overall findings summary" }
5164
5255
  },
@@ -8177,6 +8268,69 @@ var GENERATE_SESSION_HANDOFF = {
8177
8268
  tier: "showcase",
8178
8269
  internal: true
8179
8270
  };
8271
+ var BEGIN_BUILD_SESSION = {
8272
+ name: "begin_build_session",
8273
+ 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.",
8274
+ parameters: {
8275
+ worktreeId: {
8276
+ type: "string",
8277
+ description: "The Lucern worktree ID to bootstrap."
8278
+ },
8279
+ branch: {
8280
+ type: "string",
8281
+ description: "Optional git branch name. Auto-generated from the worktree name when omitted."
8282
+ },
8283
+ branchBase: {
8284
+ type: "string",
8285
+ description: 'Base branch for the feature branch. Default: "staging".'
8286
+ },
8287
+ prBase: {
8288
+ type: "string",
8289
+ description: 'Target branch for the PR. Default: "staging".'
8290
+ },
8291
+ sessionMode: {
8292
+ type: "string",
8293
+ description: 'Session mode: "async" for Codex/headless or "interactive" for live sessions.',
8294
+ enum: ["async", "interactive"]
8295
+ },
8296
+ activateIfPlanning: {
8297
+ type: "boolean",
8298
+ description: "When true, automatically activate a planning worktree during bootstrap."
8299
+ }
8300
+ },
8301
+ required: ["worktreeId"],
8302
+ response: {
8303
+ description: "A compact build-session packet with worktree metadata, graph anchors, questions, dependencies, and git defaults.",
8304
+ fields: {
8305
+ topicId: "string \u2014 canonical topic scope",
8306
+ topicName: "string \u2014 human-readable topic name",
8307
+ worktreeId: "string \u2014 worktree ID",
8308
+ worktreeName: "string \u2014 human-readable worktree name",
8309
+ branch: "string \u2014 git branch name",
8310
+ branchBase: "string \u2014 base branch",
8311
+ prBase: "string \u2014 PR target branch",
8312
+ campaign: "number | null \u2014 top-level pipeline campaign",
8313
+ lane: "string \u2014 campaign lane",
8314
+ gate: "string \u2014 exit gate",
8315
+ hypothesis: "string \u2014 worktree hypothesis",
8316
+ focus: "string \u2014 session focus",
8317
+ status: "string \u2014 worktree status after optional activation",
8318
+ sessionMode: "string \u2014 async | interactive",
8319
+ targetBeliefIds: "array \u2014 scoped belief IDs",
8320
+ targetQuestionIds: "array \u2014 scoped question IDs",
8321
+ topBeliefs: "array \u2014 highest-confidence scoped beliefs",
8322
+ openQuestions: "array \u2014 open scoped questions",
8323
+ resolvedDecisions: "array \u2014 answered questions summarized for the session",
8324
+ dependencies: "array \u2014 upstream worktrees",
8325
+ unblocks: "array \u2014 downstream worktrees",
8326
+ mergeOrderNotes: "string \u2014 merge ordering advisory"
8327
+ }
8328
+ },
8329
+ ownerModule: "bootstrap",
8330
+ ontologyPrimitive: "worktree",
8331
+ tier: "showcase",
8332
+ internal: true
8333
+ };
8180
8334
  var MCP_TOOL_CONTRACTS = {
8181
8335
  // Belief lifecycle (commit, amend, fork, archive)
8182
8336
  create_belief: CREATE_BELIEF,
@@ -8270,6 +8424,7 @@ var MCP_TOOL_CONTRACTS = {
8270
8424
  get_agent_inbox: GET_AGENT_INBOX,
8271
8425
  claim_files: CLAIM_FILES,
8272
8426
  generate_session_handoff: GENERATE_SESSION_HANDOFF,
8427
+ begin_build_session: BEGIN_BUILD_SESSION,
8273
8428
  // Policy / ACL (workhorse)
8274
8429
  check_permission: CHECK_PERMISSION,
8275
8430
  filter_by_permission: FILTER_BY_PERMISSION,
@@ -8483,6 +8638,7 @@ var PLATFORM_INTERNAL_OPERATION_NAMES = [
8483
8638
  "get_change_history",
8484
8639
  "get_failure_log",
8485
8640
  "record_attempt",
8641
+ "begin_build_session",
8486
8642
  "push",
8487
8643
  "open_pull_request",
8488
8644
  "record_judgment",
@@ -8537,7 +8693,6 @@ var SDK_ONLY_OPERATION_NAMES = [
8537
8693
  "find_semantic_orphans"
8538
8694
  ];
8539
8695
  var MCP_ONLY_INTERNAL_OPERATION_NAMES = [
8540
- "begin_build_session",
8541
8696
  "evaluate_engineering_contract",
8542
8697
  "evaluate_research_contract"
8543
8698
  ];
@@ -8923,8 +9078,31 @@ function assertSurfaceCoverage(contracts) {
8923
9078
  }
8924
9079
  }
8925
9080
  }
8926
-
8927
- // ../contracts/src/function-registry/context.ts
9081
+ var jsonRecordSchema2 = z.record(z.unknown());
9082
+ var observationArgs = z.object({
9083
+ topicId: z.string().optional().describe("Topic scope for the observation."),
9084
+ summary: z.string().describe("Short observation summary."),
9085
+ text: z.string().optional().describe("Canonical observation text alias."),
9086
+ title: z.string().optional().describe("Optional observation title."),
9087
+ content: z.string().optional().describe("Optional rich observation content."),
9088
+ contentType: z.string().optional().describe("Observation content type."),
9089
+ kind: z.string().optional().describe("Evidence kind to store."),
9090
+ observationType: z.string().optional().describe("Observation type."),
9091
+ tags: z.array(z.string()).optional().describe("Observation tags."),
9092
+ source: z.string().optional().describe("Observation source label."),
9093
+ sourceType: z.string().optional().describe("Evidence source type."),
9094
+ externalSourceType: z.string().optional().describe("External source type for imported observations."),
9095
+ sourceUrl: z.string().optional().describe("Canonical source URL."),
9096
+ confidence: z.number().optional().describe("Observation confidence."),
9097
+ metadata: jsonRecordSchema2.optional().describe("Observation metadata."),
9098
+ rationale: z.string().optional().describe("Why this observation should be recorded.")
9099
+ });
9100
+ var observationContextArgs = z.object({
9101
+ topicId: z.string().describe("Topic scope."),
9102
+ query: z.string().optional().describe("Optional context query."),
9103
+ limit: z.number().optional().describe("Maximum observations to return."),
9104
+ status: z.string().optional().describe("Observation status filter.")
9105
+ });
8928
9106
  var observationInput = (input, context) => withUserId(
8929
9107
  compactRecord4({
8930
9108
  projectId: input.projectId,
@@ -8983,7 +9161,8 @@ var contextContracts = [
8983
9161
  observationId: output && typeof output === "object" ? output.nodeId : void 0,
8984
9162
  observationType: input.observationType
8985
9163
  })
8986
- }
9164
+ },
9165
+ args: observationArgs
8987
9166
  }),
8988
9167
  surfaceContract({
8989
9168
  name: "get_observation_context",
@@ -9004,7 +9183,8 @@ var contextContracts = [
9004
9183
  status: input.status,
9005
9184
  userId: input.userId
9006
9185
  })
9007
- }
9186
+ },
9187
+ args: observationContextArgs
9008
9188
  })
9009
9189
  ];
9010
9190
 
@@ -9067,8 +9247,45 @@ var identityContracts = [
9067
9247
  }
9068
9248
  })
9069
9249
  ];
9070
-
9071
- // ../contracts/src/function-registry/beliefs.ts
9250
+ var jsonRecordSchema3 = z.record(z.unknown());
9251
+ var sourceTypeSchema = z.enum(["human", "ai_extracted", "ai_generated"]);
9252
+ var reversibilitySchema = z.enum([
9253
+ "irreversible",
9254
+ "hard_to_reverse",
9255
+ "reversible",
9256
+ "trivial"
9257
+ ]);
9258
+ var predictionMetaSchema = z.object({
9259
+ isPrediction: z.boolean().describe("Whether this belief is a prediction."),
9260
+ registeredAt: z.number().describe("Timestamp when the prediction was registered."),
9261
+ expectedBy: z.number().optional().describe("Timestamp when the prediction should be evaluated.")
9262
+ });
9263
+ var createBeliefArgs = z.object({
9264
+ canonicalText: z.string().describe("The belief statement the agent holds to be true."),
9265
+ topicId: z.string().optional().describe("Topic scope hint for the belief."),
9266
+ baseRate: z.number().optional().describe("Prior base rate used to seed the vacuous opinion."),
9267
+ beliefType: z.string().optional().describe("Schema belief type."),
9268
+ metadata: jsonRecordSchema3.optional().describe("Extra metadata merged into the belief node."),
9269
+ rationale: z.string().optional().describe("Why this belief should enter the reasoning graph."),
9270
+ pillar: z.string().optional().describe("Innovation pillar or product pillar associated with the belief."),
9271
+ worktreeId: z.string().optional().describe("Worktree responsible for creating or testing this belief."),
9272
+ sourceBeliefIds: z.array(z.string()).optional().describe("Source belief IDs this belief derives from."),
9273
+ sourceType: sourceTypeSchema.optional().describe("Actor/source class that produced the belief."),
9274
+ reversibility: reversibilitySchema.optional().describe("How reversible the belief's implied decision is."),
9275
+ predictionMeta: predictionMetaSchema.optional().describe("Prediction lifecycle metadata when this belief is a forecast.")
9276
+ });
9277
+ var forkBeliefArgs = z.object({
9278
+ nodeId: z.string().describe("The scored belief to fork from."),
9279
+ newFormulation: z.string().describe("The evolved belief statement."),
9280
+ forkReason: z.enum([
9281
+ "refinement",
9282
+ "contradiction_response",
9283
+ "scope_change",
9284
+ "confidence_collapse",
9285
+ "manual"
9286
+ ]).describe("Why this fork was created."),
9287
+ rationale: z.string().optional().describe("Why the fork is warranted.")
9288
+ });
9072
9289
  var beliefLookupInput = (input) => compactRecord4({
9073
9290
  nodeId: input.nodeId ?? input.id ?? input.beliefId,
9074
9291
  beliefId: input.beliefId
@@ -9143,7 +9360,8 @@ var beliefsContracts = [
9143
9360
  functionName: "create",
9144
9361
  kind: "mutation",
9145
9362
  inputProjection: createBeliefInput
9146
- }
9363
+ },
9364
+ args: createBeliefArgs
9147
9365
  }),
9148
9366
  surfaceContract({
9149
9367
  name: "get_belief",
@@ -9234,7 +9452,8 @@ var beliefsContracts = [
9234
9452
  functionName: "forkBelief",
9235
9453
  kind: "mutation",
9236
9454
  inputProjection: forkBeliefInput
9237
- }
9455
+ },
9456
+ args: forkBeliefArgs
9238
9457
  }),
9239
9458
  surfaceContract({
9240
9459
  name: "archive_belief",
@@ -9315,8 +9534,46 @@ var beliefsContracts = [
9315
9534
  }
9316
9535
  })
9317
9536
  ];
9318
-
9319
- // ../contracts/src/function-registry/evidence.ts
9537
+ var jsonRecordSchema4 = z.record(z.unknown());
9538
+ var evidenceRelationSchema = z.enum(["supports", "contradicts", "neutral"]);
9539
+ var createEvidenceArgs = z.object({
9540
+ topicId: z.string().optional().describe("Topic scope for the evidence."),
9541
+ text: z.string().describe("Canonical evidence text."),
9542
+ source: z.string().optional().describe("Source URL or source label."),
9543
+ sourceUrl: z.string().optional().describe("Canonical source URL."),
9544
+ targetId: z.string().optional().describe("Belief or question identifier to link immediately."),
9545
+ linkedBeliefNodeId: z.string().optional().describe("Belief node this evidence bears on."),
9546
+ evidenceRelation: evidenceRelationSchema.optional().describe("How the evidence relates to the linked belief."),
9547
+ confidence: z.number().optional().describe("Confidence in the evidence relation."),
9548
+ weight: z.number().optional().describe("Support weight from -1.0 to +1.0."),
9549
+ metadata: jsonRecordSchema4.optional().describe("Metadata merged into the canonical evidence node."),
9550
+ rationale: z.string().describe("Why this evidence should enter the reasoning graph."),
9551
+ reasoning: z.string().optional().describe("Reasoning note preserved in evidence metadata."),
9552
+ title: z.string().optional().describe("Optional short title."),
9553
+ content: z.string().optional().describe("Optional long-form content."),
9554
+ contentType: z.string().optional().describe("Content format or MIME hint."),
9555
+ kind: z.string().optional().describe("Evidence kind."),
9556
+ tags: z.array(z.string()).optional().describe("Evidence tags."),
9557
+ sourceType: z.string().optional().describe("Evidence source type."),
9558
+ externalSourceType: z.string().optional().describe("External source type for imported evidence."),
9559
+ sourceQuestionId: z.string().optional().describe("Question that sourced this evidence."),
9560
+ methodology: z.string().optional().describe("Collection methodology."),
9561
+ informationAsymmetry: z.string().optional().describe("Information asymmetry class."),
9562
+ sourceDescription: z.string().optional().describe("Human-readable source description.")
9563
+ });
9564
+ var addEvidenceArgs = z.object({
9565
+ canonicalText: z.string().describe("The evidence statement."),
9566
+ text: z.string().optional().describe("Canonical evidence text alias used by newer callers."),
9567
+ topicId: z.string().optional().describe("Topic scope hint."),
9568
+ sourceUrl: z.string().optional().describe("URL of the source material."),
9569
+ targetNodeId: z.string().describe("The belief this evidence bears on."),
9570
+ weight: z.number().optional().describe("Support weight from -1.0 to +1.0."),
9571
+ reasoning: z.string().describe("Why this evidence is relevant to the target belief."),
9572
+ title: z.string().optional().describe("Optional short title."),
9573
+ content: z.string().optional().describe("Optional long-form evidence content."),
9574
+ contentType: z.string().optional().describe("Content format or MIME hint."),
9575
+ metadata: jsonRecordSchema4.optional().describe("Optional metadata merged into the evidence node.")
9576
+ });
9320
9577
  var evidenceIdInput = (input) => compactRecord4({
9321
9578
  evidenceId: input.evidenceId,
9322
9579
  insightId: input.insightId,
@@ -9391,7 +9648,8 @@ var evidenceContracts = [
9391
9648
  functionName: "create",
9392
9649
  kind: "mutation",
9393
9650
  inputProjection: createEvidenceInput
9394
- }
9651
+ },
9652
+ args: createEvidenceArgs
9395
9653
  }),
9396
9654
  surfaceContract({
9397
9655
  name: "add_evidence",
@@ -9427,7 +9685,8 @@ var evidenceContracts = [
9427
9685
  context
9428
9686
  );
9429
9687
  }
9430
- }
9688
+ },
9689
+ args: addEvidenceArgs
9431
9690
  }),
9432
9691
  surfaceContract({
9433
9692
  name: "get_evidence",
@@ -9534,8 +9793,91 @@ var evidenceContracts = [
9534
9793
  }
9535
9794
  })
9536
9795
  ];
9537
-
9538
- // ../contracts/src/function-registry/questions.ts
9796
+ var jsonRecordSchema5 = z.record(z.unknown());
9797
+ var questionPrioritySchema = z.enum(["urgent", "high", "medium", "low"]);
9798
+ var kernelQuestionPrioritySchema = z.enum([
9799
+ "critical",
9800
+ "high",
9801
+ "medium",
9802
+ "low"
9803
+ ]);
9804
+ var questionTypeSchema = z.enum([
9805
+ "validation",
9806
+ "falsification",
9807
+ "assumption_probe",
9808
+ "prediction_test",
9809
+ "counterfactual",
9810
+ "discovery",
9811
+ "clarification",
9812
+ "comparison",
9813
+ "causal",
9814
+ "mechanism",
9815
+ "general"
9816
+ ]);
9817
+ var createQuestionArgs = z.object({
9818
+ text: z.string().describe("The question text."),
9819
+ question: z.string().optional().describe("Backend question text alias for kernel-native callers."),
9820
+ topicId: z.string().optional().describe("Topic scope hint."),
9821
+ priority: questionPrioritySchema.optional().describe("Human-facing question priority."),
9822
+ linkedBeliefId: z.string().optional().describe("Belief this question tests."),
9823
+ linkedBeliefNodeId: z.string().optional().describe("Belief node this question tests."),
9824
+ metadata: jsonRecordSchema5.optional().describe("Optional metadata merged into the question record."),
9825
+ category: z.string().optional().describe("Question category."),
9826
+ source: z.string().optional().describe("Question source."),
9827
+ testType: z.enum(["validates", "invalidates", "clarifies"]).optional().describe("How this question tests its linked belief."),
9828
+ importance: z.number().optional().describe("Numeric importance score."),
9829
+ epistemicUnlock: z.string().optional().describe("What this question unlocks if answered."),
9830
+ sourceQuestionIds: z.array(z.string()).optional().describe("Question IDs this question derives from."),
9831
+ linkedWorktreeId: z.string().optional().describe("Worktree this question belongs to."),
9832
+ questionType: questionTypeSchema.optional().describe("Question type."),
9833
+ questionPriority: kernelQuestionPrioritySchema.optional().describe("Kernel-native question priority.")
9834
+ });
9835
+ var refineQuestionArgs = z.object({
9836
+ id: z.string().describe("The question to refine."),
9837
+ text: z.string().describe("Updated question text."),
9838
+ question: z.string().optional().describe("Backend question text alias for kernel-native callers."),
9839
+ rationale: z.string().optional().describe("Why the question is refined."),
9840
+ category: z.string().optional().describe("Updated question category."),
9841
+ priority: questionPrioritySchema.optional().describe("Updated human-facing priority.")
9842
+ });
9843
+ var createAnswerArgs = z.object({
9844
+ questionNodeId: z.string().describe("The question node ID this answer responds to."),
9845
+ questionId: z.string().optional().describe("Question ID alias accepted by the projection."),
9846
+ answerText: z.string().describe("The answer content."),
9847
+ topicId: z.string().optional().describe("Topic scope for the answer."),
9848
+ confidence: z.string().optional().describe("Answer confidence."),
9849
+ evidenceNodeIds: z.array(z.string()).optional().describe("Evidence node IDs supporting the answer."),
9850
+ answerSource: z.string().optional().describe("How the answer was produced."),
9851
+ worktreeId: z.string().optional().describe("Worktree whose outcome produced this answer."),
9852
+ sprintId: z.string().optional().describe("Legacy sprint identifier.")
9853
+ });
9854
+ var answerQuestionArgs = z.object({
9855
+ id: z.string().describe("Canonical question ID."),
9856
+ topicId: z.string().describe("Topic scope for the answer."),
9857
+ text: z.string().describe("Answer text."),
9858
+ confidence: z.enum(["weak", "medium", "strong"]).optional().describe("Optional answer confidence."),
9859
+ evidenceIds: z.array(z.string()).optional().describe("Canonical evidence IDs supporting the answer."),
9860
+ rationale: z.string().optional().describe("Why this answer is credible."),
9861
+ questionId: z.string().optional().describe("Question ID alias accepted by the projection."),
9862
+ questionNodeId: z.string().optional().describe("Question node ID alias accepted by the projection."),
9863
+ answerText: z.string().optional().describe("Canonical answer text alias accepted by newer callers."),
9864
+ evidenceNodeIds: z.array(z.string()).optional().describe("Evidence node ID alias accepted by newer callers."),
9865
+ answerSource: z.string().optional().describe("How the answer was produced."),
9866
+ worktreeId: z.string().optional().describe("Worktree whose outcome produced this answer."),
9867
+ sprintId: z.string().optional().describe("Legacy sprint identifier.")
9868
+ });
9869
+ var missingQuestionsArgs = z.object({
9870
+ topicId: z.string().describe("Topic scope."),
9871
+ minConfidence: z.number().optional().describe("Minimum confidence threshold for missing-question checks."),
9872
+ status: z.string().optional().describe("Question status filter."),
9873
+ limit: z.number().optional().describe("Maximum questions to inspect.")
9874
+ });
9875
+ var falsificationQuestionsArgs = z.object({
9876
+ topicId: z.string().describe("Topic scope."),
9877
+ beliefIds: z.array(z.string()).optional().describe("Beliefs to generate falsification questions for."),
9878
+ status: z.string().optional().describe("Question status filter."),
9879
+ limit: z.number().optional().describe("Maximum questions to inspect.")
9880
+ });
9539
9881
  var questionNodeInput = (input) => compactRecord4({
9540
9882
  nodeId: input.nodeId ?? input.id ?? input.questionId,
9541
9883
  questionId: input.questionId
@@ -9582,7 +9924,8 @@ var questionsContracts = [
9582
9924
  functionName: "create",
9583
9925
  kind: "mutation",
9584
9926
  inputProjection: createQuestionInput
9585
- }
9927
+ },
9928
+ args: createQuestionArgs
9586
9929
  }),
9587
9930
  surfaceContract({
9588
9931
  name: "get_question",
@@ -9638,7 +9981,8 @@ var questionsContracts = [
9638
9981
  category: input.category,
9639
9982
  priority: input.priority
9640
9983
  })
9641
- }
9984
+ },
9985
+ args: refineQuestionArgs
9642
9986
  }),
9643
9987
  surfaceContract({
9644
9988
  name: "update_question_status",
@@ -9714,7 +10058,8 @@ var questionsContracts = [
9714
10058
  }),
9715
10059
  context
9716
10060
  )
9717
- }
10061
+ },
10062
+ args: createAnswerArgs
9718
10063
  }),
9719
10064
  surfaceContract({
9720
10065
  name: "answer_question",
@@ -9743,7 +10088,8 @@ var questionsContracts = [
9743
10088
  }),
9744
10089
  context
9745
10090
  )
9746
- }
10091
+ },
10092
+ args: answerQuestionArgs
9747
10093
  }),
9748
10094
  surfaceContract({
9749
10095
  name: "get_answer",
@@ -9775,7 +10121,8 @@ var questionsContracts = [
9775
10121
  functionName: "getByTopic",
9776
10122
  kind: "query",
9777
10123
  inputProjection: questionTopicInput
9778
- }
10124
+ },
10125
+ args: missingQuestionsArgs
9779
10126
  }),
9780
10127
  surfaceContract({
9781
10128
  name: "get_high_priority_questions",
@@ -9810,11 +10157,22 @@ var questionsContracts = [
9810
10157
  functionName: "getByTopic",
9811
10158
  kind: "query",
9812
10159
  inputProjection: questionTopicInput
9813
- }
10160
+ },
10161
+ args: falsificationQuestionsArgs
9814
10162
  })
9815
10163
  ];
9816
-
9817
- // ../contracts/src/function-registry/topics.ts
10164
+ var updateTopicArgs = z.object({
10165
+ id: z.string().describe("Topic ID."),
10166
+ topicId: z.string().optional().describe("Topic ID alias."),
10167
+ name: z.string().optional().describe("Topic name."),
10168
+ description: z.string().optional().describe("Topic description."),
10169
+ type: z.string().optional().describe("Topic type."),
10170
+ status: z.string().optional().describe("Topic status."),
10171
+ visibility: z.string().optional().describe("Topic visibility."),
10172
+ ontologyId: z.string().optional().describe("Ontology to bind."),
10173
+ clearOntologyId: z.boolean().optional().describe("Whether to clear the ontology binding."),
10174
+ metadata: z.record(z.unknown()).optional().describe("Topic metadata.")
10175
+ });
9818
10176
  var topicIdInput = (input) => compactRecord4({
9819
10177
  id: input.id ?? input.topicId
9820
10178
  });
@@ -9895,7 +10253,8 @@ var topicsContracts = [
9895
10253
  functionName: "update",
9896
10254
  kind: "mutation",
9897
10255
  inputProjection: updateTopicInput
9898
- }
10256
+ },
10257
+ args: updateTopicArgs
9899
10258
  }),
9900
10259
  surfaceContract({
9901
10260
  name: "get_topic_tree",
@@ -9914,8 +10273,27 @@ var topicsContracts = [
9914
10273
  }
9915
10274
  })
9916
10275
  ];
9917
-
9918
- // ../contracts/src/function-registry/lenses.ts
10276
+ var lensPerspectiveSchema = z.enum([
10277
+ "investigation",
10278
+ "monitoring",
10279
+ "analysis",
10280
+ "comparison",
10281
+ "taxonomy"
10282
+ ]);
10283
+ var jsonRecordSchema6 = z.record(z.unknown());
10284
+ var createLensArgs = z.object({
10285
+ name: z.string().describe("Lens name."),
10286
+ workspaceId: z.string().optional().describe("Workspace scope for the lens."),
10287
+ topicId: z.string().optional().describe("Originating topic scope."),
10288
+ description: z.string().optional().describe("What this lens investigates or monitors."),
10289
+ perspectiveType: lensPerspectiveSchema.describe("Perspective type."),
10290
+ promptTemplates: z.array(jsonRecordSchema6).optional().describe("Prompt templates used through this lens."),
10291
+ workflowTemplates: z.array(jsonRecordSchema6).optional().describe("Guided workflow templates."),
10292
+ taskTemplates: z.array(jsonRecordSchema6).optional().describe("Default task templates."),
10293
+ questionTemplates: z.array(jsonRecordSchema6).optional().describe("Default question templates."),
10294
+ filterCriteria: jsonRecordSchema6.optional().describe("Belief/evidence filtering criteria."),
10295
+ metadata: jsonRecordSchema6.optional().describe("Additional lens metadata.")
10296
+ });
9919
10297
  var createLensInput = (input, context) => compactRecord4({
9920
10298
  name: input.name,
9921
10299
  description: input.description,
@@ -9952,7 +10330,8 @@ var lensesContracts = [
9952
10330
  functionName: "create",
9953
10331
  kind: "mutation",
9954
10332
  inputProjection: createLensInput
9955
- }
10333
+ },
10334
+ args: createLensArgs
9956
10335
  }),
9957
10336
  surfaceContract({
9958
10337
  name: "list_lenses",
@@ -10014,8 +10393,18 @@ var lensesContracts = [
10014
10393
  }
10015
10394
  })
10016
10395
  ];
10017
-
10018
- // ../contracts/src/function-registry/ontologies.ts
10396
+ var updateOntologyArgs = z.object({
10397
+ id: z.string().describe("Ontology definition ID."),
10398
+ ontologyId: z.string().optional().describe("Ontology ID alias."),
10399
+ name: z.string().optional().describe("Ontology display name."),
10400
+ description: z.string().optional().describe("Ontology description."),
10401
+ status: z.string().optional().describe("Ontology lifecycle status.")
10402
+ });
10403
+ var ontologyVersionLifecycleArgs = z.object({
10404
+ id: z.string().describe("Ontology version ID."),
10405
+ versionId: z.string().optional().describe("Ontology version ID alias."),
10406
+ ontologyId: z.string().optional().describe("Ontology definition ID.")
10407
+ });
10019
10408
  var ontologyIdInput = (input) => compactRecord4({
10020
10409
  id: input.id ?? input.ontologyId
10021
10410
  });
@@ -10094,11 +10483,11 @@ var ontologiesContracts = [
10094
10483
  id: input.id ?? input.ontologyId,
10095
10484
  name: input.name,
10096
10485
  description: input.description,
10097
- parentOntologyId: input.parentOntologyId,
10098
10486
  status: input.status,
10099
10487
  actorId: input.actorId
10100
10488
  })
10101
- }
10489
+ },
10490
+ args: updateOntologyArgs
10102
10491
  }),
10103
10492
  surfaceContract({
10104
10493
  name: "archive_ontology",
@@ -10181,7 +10570,8 @@ var ontologiesContracts = [
10181
10570
  functionName: "publishOntologyVersion",
10182
10571
  kind: "mutation",
10183
10572
  inputProjection: ontologyVersionIdInput
10184
- }
10573
+ },
10574
+ args: ontologyVersionLifecycleArgs
10185
10575
  }),
10186
10576
  surfaceContract({
10187
10577
  name: "deprecate_ontology_version",
@@ -10197,7 +10587,8 @@ var ontologiesContracts = [
10197
10587
  functionName: "deprecateOntologyVersion",
10198
10588
  kind: "mutation",
10199
10589
  inputProjection: ontologyVersionIdInput
10200
- }
10590
+ },
10591
+ args: ontologyVersionLifecycleArgs
10201
10592
  }),
10202
10593
  surfaceContract({
10203
10594
  name: "resolve_effective_ontology",
@@ -10216,8 +10607,76 @@ var ontologiesContracts = [
10216
10607
  }
10217
10608
  })
10218
10609
  ];
10219
-
10220
- // ../contracts/src/function-registry/worktrees.ts
10610
+ var autoFixPolicyInputSchema = z.object({
10611
+ enabled: z.boolean().optional().describe("Whether automatic remediation is enabled."),
10612
+ mode: z.string().optional().describe("Automation mode for worktree auto-fixes."),
10613
+ maxAttempts: z.number().optional().describe("Maximum number of auto-fix attempts."),
10614
+ reviewer: z.string().optional().describe("Reviewer responsible for auto-fix oversight."),
10615
+ maxActionsPerRun: z.number().optional().describe("Maximum number of auto-fix actions per run."),
10616
+ permittedMutationTiers: z.array(z.enum(["read_only", "low_risk_write", "high_risk_write"])).optional().describe("Mutation tiers the auto-fix worker may execute."),
10617
+ requireAuditTrail: z.boolean().optional().describe("Whether auto-fix actions must write an audit trail."),
10618
+ escalationGate: z.string().optional().describe("Gate to trigger when auto-fix policy requires escalation.")
10619
+ }).passthrough().describe("Policy for permitted automatic remediation inside the worktree.");
10620
+ var worktreeKeyQuestionInputSchema = z.object({
10621
+ question: z.string().describe("Question the worktree must resolve."),
10622
+ status: z.enum(["open", "answered", "forked"]).optional().describe("Current disposition of the key question."),
10623
+ answer: z.string().optional().describe("Captured answer when the key question is resolved."),
10624
+ answerConfidence: z.enum(["high", "medium", "low"]).optional().describe("Confidence in the captured answer."),
10625
+ linkedQuestionId: z.string().optional().describe("Canonical question node linked to this key question.")
10626
+ }).passthrough().describe("Question contract embedded in the worktree plan.");
10627
+ var worktreeEvidenceSignalInputSchema = z.object({
10628
+ signal: z.string().describe("Evidence signal the worktree should collect."),
10629
+ collected: z.boolean().optional().describe("Whether the signal has already been collected."),
10630
+ progress: z.string().optional().describe("Collection progress note for the signal."),
10631
+ notes: z.string().optional().describe("Additional evidence collection notes.")
10632
+ }).passthrough().describe("Evidence signal embedded in the worktree plan.");
10633
+ var worktreeDecisionGateInputSchema = z.object({
10634
+ goCriteria: z.array(z.string()).describe("Criteria that must hold for the worktree to proceed."),
10635
+ noGoSignals: z.array(z.string()).describe("Signals that stop or redirect the worktree."),
10636
+ verdict: z.enum(["go", "no_go", "pivot", "pending"]).optional().describe("Current decision verdict for the worktree gate."),
10637
+ verdictRationale: z.string().optional().describe("Rationale supporting the current gate verdict."),
10638
+ decidedAt: z.number().optional().describe("Timestamp when the gate verdict was decided."),
10639
+ decidedBy: z.string().optional().describe("Actor that decided the gate verdict.")
10640
+ }).passthrough().describe("Decision gate contract for worktree activation or exit.");
10641
+ var addWorktreeArgs = z.object({
10642
+ title: z.string().optional().describe("Human-readable worktree name or objective."),
10643
+ name: z.string().optional().describe("Storage-name alias for callers that already use backend naming."),
10644
+ topicId: z.string().describe("Primary topic scope for the worktree."),
10645
+ projectId: z.string().optional().describe("Legacy topicId alias."),
10646
+ branchId: z.string().optional().describe("Legacy branch identifier for compatibility with workflow callers."),
10647
+ objective: z.string().optional().describe("Reasoning objective this worktree is intended to resolve."),
10648
+ hypothesis: z.string().optional().describe("Testable claim this worktree investigates."),
10649
+ rationale: z.string().optional().describe("Why this worktree exists and why it belongs in the campaign."),
10650
+ worktreeType: z.string().optional().describe("Schema-enum worktree type used for kernel lifecycle behavior."),
10651
+ gate: z.string().optional().describe("Exit gate for this worktree."),
10652
+ startDate: z.number().optional().describe("Planned start timestamp in milliseconds since epoch."),
10653
+ endDate: z.number().optional().describe("Planned end timestamp in milliseconds since epoch."),
10654
+ durationWeeks: z.number().optional().describe("Planned duration in weeks."),
10655
+ confidenceImpact: z.enum(["high", "medium", "low"]).optional().describe("Expected confidence impact if this worktree succeeds."),
10656
+ beliefFocus: z.string().optional().describe("Natural-language focus spanning the target belief neighborhood."),
10657
+ beliefIds: z.array(z.string()).optional().describe("Legacy alias for targetBeliefIds."),
10658
+ beliefs: z.array(z.string()).optional().describe("Legacy alias for targetBeliefIds."),
10659
+ targetBeliefIds: z.array(z.string()).optional().describe("Belief node IDs this worktree is expected to test or update."),
10660
+ targetQuestionIds: z.array(z.string()).optional().describe("Question node IDs this worktree is expected to answer."),
10661
+ keyQuestions: z.array(worktreeKeyQuestionInputSchema).optional().describe("Inline key questions captured as part of the worktree plan."),
10662
+ evidenceSignals: z.array(worktreeEvidenceSignalInputSchema).optional().describe("Evidence signals the worktree needs to collect or validate."),
10663
+ decisionGate: worktreeDecisionGateInputSchema.optional(),
10664
+ goCriteria: z.array(z.string()).optional().describe("Shorthand go criteria used to build decisionGate."),
10665
+ noGoSignals: z.array(z.string()).optional().describe("Shorthand no-go signals used to build decisionGate."),
10666
+ proofArtifacts: z.array(z.unknown()).optional().describe("Expected proof artifacts required to close the worktree."),
10667
+ autoShape: z.boolean().optional().describe("Whether to invoke inquiry auto-shaping during creation."),
10668
+ autoFixPolicy: autoFixPolicyInputSchema.optional(),
10669
+ domainPackId: z.string().optional().describe("Domain pack whose shaping hooks should influence the worktree."),
10670
+ campaign: z.number().optional().describe("Top-level pipeline campaign number."),
10671
+ lane: z.string().optional().describe("Campaign lane for the worktree."),
10672
+ laneOrderInCampaign: z.number().optional().describe("Ordering for this lane within its campaign."),
10673
+ orderInLane: z.number().optional().describe("Position of this worktree inside its lane."),
10674
+ dependsOn: z.array(z.string()).optional().describe("Worktree IDs that must complete before this worktree."),
10675
+ blocks: z.array(z.string()).optional().describe("Worktree IDs blocked by this worktree."),
10676
+ staffingHint: z.string().optional().describe("Suggested staffing or agent allocation note."),
10677
+ lensId: z.string().optional().describe("Lens that scopes this worktree when applicable."),
10678
+ lastReconciledAt: z.number().optional().describe("Timestamp when worktree metadata was last reconciled.")
10679
+ });
10221
10680
  var worktreeIdInput = (input) => compactRecord4({
10222
10681
  worktreeId: input.worktreeId ?? input.id
10223
10682
  });
@@ -10250,6 +10709,50 @@ var worktreeMetadataInput = (input) => compactRecord4({
10250
10709
  autoFixPolicy: input.autoFixPolicy,
10251
10710
  lastReconciledAt: input.lastReconciledAt
10252
10711
  });
10712
+ var worktreeMetadataArgs = z.object({
10713
+ worktreeId: z.string().describe("The worktree to update."),
10714
+ id: z.string().optional().describe("Worktree ID alias."),
10715
+ topicId: z.string().optional().describe("Primary topic scope."),
10716
+ additionalTopicIds: z.array(z.string()).optional().describe("Additional topic scopes associated with this worktree."),
10717
+ status: z.string().optional().describe("Worktree lifecycle status."),
10718
+ campaign: z.number().optional().describe("Top-level pipeline campaign."),
10719
+ lane: z.string().optional().describe("Campaign lane."),
10720
+ laneOrderInCampaign: z.number().optional().describe("Ordering for this lane within its campaign."),
10721
+ orderInLane: z.number().optional().describe("Position of this worktree inside its lane."),
10722
+ gate: z.string().optional().describe("Exit gate for this worktree."),
10723
+ hypothesis: z.string().optional().describe("Testable claim this worktree investigates."),
10724
+ objective: z.string().optional().describe("Reasoning objective for the worktree."),
10725
+ rationale: z.string().optional().describe("Why this worktree is sequenced here."),
10726
+ proofArtifacts: z.array(z.unknown()).optional().describe("Proof artifacts required to close the worktree."),
10727
+ staffingHint: z.string().optional().describe("Suggested staffing or agent allocation note."),
10728
+ blocks: z.array(z.string()).optional().describe("Worktree IDs blocked by this worktree."),
10729
+ dependsOn: z.array(z.string()).optional().describe("Worktree IDs this worktree depends on."),
10730
+ lensId: z.string().optional().describe("Lens that scopes this worktree."),
10731
+ autoFixPolicy: autoFixPolicyInputSchema.optional(),
10732
+ lastReconciledAt: z.number().optional().describe("Timestamp of the last deterministic reconciliation pass.")
10733
+ });
10734
+ var pushArgs = worktreeMetadataArgs.extend({
10735
+ targetContext: z.string().describe("Where to push merged findings."),
10736
+ beliefIds: z.array(z.string()).optional().describe("Optional subset of beliefs to push.")
10737
+ });
10738
+ var openPullRequestArgs = worktreeMetadataArgs.extend({
10739
+ reviewers: z.array(z.string()).optional().describe("User IDs of requested reviewers."),
10740
+ summary: z.string().describe("Summary of findings and why they are ready for review.")
10741
+ });
10742
+ var mergeKeyFindingsInput = (input) => {
10743
+ if (Array.isArray(input.keyFindings)) {
10744
+ return input.keyFindings;
10745
+ }
10746
+ if (Array.isArray(input.outcomes)) {
10747
+ const findings = input.outcomes.filter(
10748
+ (outcome) => typeof outcome === "string" && outcome.trim().length > 0
10749
+ );
10750
+ if (findings.length > 0) {
10751
+ return findings;
10752
+ }
10753
+ }
10754
+ return [input.summary ?? "Merged worktree"];
10755
+ };
10253
10756
  var listAllWorktreesInput = (input) => compactRecord4({
10254
10757
  status: input.status,
10255
10758
  lane: input.lane,
@@ -10257,6 +10760,16 @@ var listAllWorktreesInput = (input) => compactRecord4({
10257
10760
  limit: input.limit
10258
10761
  });
10259
10762
  var worktreesContracts = [
10763
+ surfaceContract({
10764
+ name: "begin_build_session",
10765
+ kind: "mutation",
10766
+ domain: "worktrees",
10767
+ surfaceClass: "platform_internal",
10768
+ path: "/mcp/build-session/begin",
10769
+ sdkNamespace: "worktrees",
10770
+ sdkMethod: "beginBuildSession",
10771
+ summary: "Begin a coding build session for a worktree."
10772
+ }),
10260
10773
  surfaceContract({
10261
10774
  name: "add_worktree",
10262
10775
  kind: "mutation",
@@ -10273,13 +10786,12 @@ var worktreesContracts = [
10273
10786
  inputProjection: (input, context) => withCreatedBy(
10274
10787
  compactRecord4({
10275
10788
  name: input.name ?? input.title,
10276
- topicId: input.topicId,
10789
+ topicId: input.topicId ?? input.projectId,
10277
10790
  worktreeType: input.worktreeType,
10278
10791
  objective: input.objective,
10279
10792
  gate: input.gate,
10280
10793
  hypothesis: input.hypothesis,
10281
10794
  rationale: input.rationale,
10282
- signal: input.signal,
10283
10795
  startDate: input.startDate,
10284
10796
  endDate: input.endDate,
10285
10797
  durationWeeks: input.durationWeeks,
@@ -10305,12 +10817,12 @@ var worktreesContracts = [
10305
10817
  staffingHint: input.staffingHint,
10306
10818
  domainPackId: input.domainPackId,
10307
10819
  lensId: input.lensId,
10308
- linkedQuestionId: input.linkedQuestionId,
10309
10820
  lastReconciledAt: input.lastReconciledAt
10310
10821
  }),
10311
10822
  context
10312
10823
  )
10313
- }
10824
+ },
10825
+ args: addWorktreeArgs
10314
10826
  }),
10315
10827
  surfaceContract({
10316
10828
  name: "activate_worktree",
@@ -10422,7 +10934,8 @@ var worktreesContracts = [
10422
10934
  functionName: "updateMetadata",
10423
10935
  kind: "mutation",
10424
10936
  inputProjection: worktreeMetadataInput
10425
- }
10937
+ },
10938
+ args: worktreeMetadataArgs
10426
10939
  }),
10427
10940
  surfaceContract({
10428
10941
  name: "merge",
@@ -10440,9 +10953,7 @@ var worktreesContracts = [
10440
10953
  inputProjection: (input, context) => withUserId(
10441
10954
  {
10442
10955
  ...worktreeIdInput(input),
10443
- keyFindings: input.keyFindings ?? [
10444
- input.summary ?? "Merged worktree"
10445
- ],
10956
+ keyFindings: mergeKeyFindingsInput(input),
10446
10957
  decisionsReached: input.decisionsReached ?? [],
10447
10958
  nextSteps: input.nextSteps ?? []
10448
10959
  },
@@ -10464,7 +10975,8 @@ var worktreesContracts = [
10464
10975
  functionName: "updateMetadata",
10465
10976
  kind: "mutation",
10466
10977
  inputProjection: worktreeMetadataInput
10467
- }
10978
+ },
10979
+ args: pushArgs
10468
10980
  }),
10469
10981
  surfaceContract({
10470
10982
  name: "open_pull_request",
@@ -10480,7 +10992,8 @@ var worktreesContracts = [
10480
10992
  functionName: "updateMetadata",
10481
10993
  kind: "mutation",
10482
10994
  inputProjection: worktreeMetadataInput
10483
- }
10995
+ },
10996
+ args: openPullRequestArgs
10484
10997
  })
10485
10998
  ];
10486
10999
 
@@ -10584,6 +11097,15 @@ var createEdgeArgs = z.object({
10584
11097
  topicId: z.string().optional(),
10585
11098
  trustedBypassAccessCheck: z.boolean().optional()
10586
11099
  });
11100
+ var queryLineageArgs = z.object({
11101
+ nodeId: z.string().describe("Starting node to trace from."),
11102
+ startNode: z.string().optional().describe("Starting node alias accepted by traversal callers."),
11103
+ depth: z.number().optional().describe("Traversal depth alias."),
11104
+ maxDepth: z.number().optional().describe("Maximum traversal depth."),
11105
+ mode: z.string().optional().describe("Traversal mode."),
11106
+ minLayer: z.string().optional().describe("Minimum epistemic layer."),
11107
+ maxLayer: z.string().optional().describe("Maximum epistemic layer.")
11108
+ });
10587
11109
  function graphRefNodeId(ref) {
10588
11110
  if (ref.kind === "epistemic_node") {
10589
11111
  return ref.nodeId;
@@ -10654,11 +11176,59 @@ var edgesContracts = [
10654
11176
  minLayer: input.minLayer,
10655
11177
  maxLayer: input.maxLayer
10656
11178
  })
10657
- }
11179
+ },
11180
+ args: queryLineageArgs
10658
11181
  })
10659
11182
  ];
10660
-
10661
- // ../contracts/src/function-registry/graph.ts
11183
+ var traversalLayerSchema = z.enum([
11184
+ "L4",
11185
+ "L3",
11186
+ "L2",
11187
+ "L1",
11188
+ "ontological",
11189
+ "organizational"
11190
+ ]);
11191
+ var traversalModeSchema = z.enum(["low", "medium", "high", "extra_high"]);
11192
+ var lineageAliasArgs = z.object({
11193
+ nodeId: z.string().optional().describe("Starting node to traverse from."),
11194
+ startNode: z.string().optional().describe("Starting node alias for traversal callers."),
11195
+ entityId: z.string().optional().describe("Entity identifier alias for impact tracing."),
11196
+ depth: z.number().optional().describe("Traversal depth alias."),
11197
+ maxDepth: z.number().optional().describe("Maximum traversal depth."),
11198
+ mode: traversalModeSchema.optional().describe("Traversal mode."),
11199
+ minLayer: traversalLayerSchema.optional().describe("Minimum epistemic layer to include."),
11200
+ maxLayer: traversalLayerSchema.optional().describe("Maximum epistemic layer to include.")
11201
+ });
11202
+ var lineageArgs = lineageAliasArgs.extend({
11203
+ nodeId: z.string().describe("Starting node to traverse from.")
11204
+ });
11205
+ var traverseGraphArgs = lineageAliasArgs.extend({
11206
+ startNode: z.string().describe("Node to start traversal from."),
11207
+ direction: z.enum(["up", "down", "both"]).optional().describe("Traversal direction.")
11208
+ });
11209
+ var graphNeighborhoodArgs = z.object({
11210
+ globalId: z.string().optional().describe("Single root global ID."),
11211
+ globalIds: z.array(z.string()).optional().describe("Root global IDs for the neighborhood."),
11212
+ maxDepth: z.number().optional().describe("Maximum traversal depth."),
11213
+ topicId: z.string().optional().describe("Topic scope for edge lookup."),
11214
+ limit: z.number().optional().describe("Maximum edges to return.")
11215
+ });
11216
+ var flagContradictionArgs = z.object({
11217
+ beliefA: z.string().describe("First belief in tension."),
11218
+ beliefB: z.string().describe("Second belief in tension."),
11219
+ topicId: z.string().optional().describe("Topic scope for the contradiction."),
11220
+ description: z.string().optional().describe("Human-readable contradiction."),
11221
+ severity: z.enum(["critical", "high", "medium", "low"]).optional().describe("Contradiction severity."),
11222
+ defeatType: z.string().optional().describe("Defeat type annotation."),
11223
+ supportingInsightIds: z.array(z.string()).optional().describe("Evidence supporting the primary belief."),
11224
+ contradictingInsightIds: z.array(z.string()).optional().describe("Evidence or beliefs contradicting the primary belief.")
11225
+ });
11226
+ var discoverEntityConnectionsArgs = lineageAliasArgs.extend({
11227
+ nodeId: z.string().describe("Epistemic node ID to find entity connections for."),
11228
+ topicId: z.string().optional().describe("Topic scope override."),
11229
+ minScore: z.number().optional().describe("Minimum match score."),
11230
+ limit: z.number().optional().describe("Maximum candidates to return.")
11231
+ });
10662
11232
  var contradictionSeverity = (value) => {
10663
11233
  switch (value) {
10664
11234
  case "critical":
@@ -10713,7 +11283,8 @@ var graphContracts = [
10713
11283
  functionName: "getLineage",
10714
11284
  kind: "query",
10715
11285
  inputProjection: lineageInput
10716
- }
11286
+ },
11287
+ args: traverseGraphArgs
10717
11288
  }),
10718
11289
  surfaceContract({
10719
11290
  name: "get_graph_neighborhood",
@@ -10729,7 +11300,8 @@ var graphContracts = [
10729
11300
  functionName: "getByTopic",
10730
11301
  kind: "query",
10731
11302
  inputProjection: topicEdgesInput
10732
- }
11303
+ },
11304
+ args: graphNeighborhoodArgs
10733
11305
  }),
10734
11306
  surfaceContract({
10735
11307
  name: "get_graph_structure_analysis",
@@ -10778,7 +11350,8 @@ var graphContracts = [
10778
11350
  functionName: "create",
10779
11351
  kind: "mutation",
10780
11352
  inputProjection: flagContradictionInput
10781
- }
11353
+ },
11354
+ args: flagContradictionArgs
10782
11355
  }),
10783
11356
  surfaceContract({
10784
11357
  name: "detect_confirmation_bias",
@@ -10869,7 +11442,8 @@ var graphContracts = [
10869
11442
  functionName: "getLineage",
10870
11443
  kind: "query",
10871
11444
  inputProjection: lineageInput
10872
- }
11445
+ },
11446
+ args: discoverEntityConnectionsArgs
10873
11447
  }),
10874
11448
  surfaceContract({
10875
11449
  name: "trigger_belief_review",
@@ -10900,7 +11474,8 @@ var graphContracts = [
10900
11474
  functionName: "getLineage",
10901
11475
  kind: "query",
10902
11476
  inputProjection: lineageInput
10903
- }
11477
+ },
11478
+ args: lineageArgs
10904
11479
  })
10905
11480
  ];
10906
11481
 
@@ -10952,8 +11527,16 @@ var contractsContracts = [
10952
11527
  }
10953
11528
  })
10954
11529
  ];
10955
-
10956
- // ../contracts/src/function-registry/judgments.ts
11530
+ var auditTrailArgs = z.object({
11531
+ nodeId: z.string().describe("The node to audit."),
11532
+ id: z.string().optional().describe("Node ID alias."),
11533
+ limit: z.number().optional().describe("Maximum entries to return."),
11534
+ depth: z.number().optional().describe("Traversal depth alias."),
11535
+ maxDepth: z.number().optional().describe("Maximum lineage depth."),
11536
+ mode: z.string().optional().describe("Traversal mode."),
11537
+ minLayer: z.string().optional().describe("Minimum epistemic layer."),
11538
+ maxLayer: z.string().optional().describe("Maximum epistemic layer.")
11539
+ });
10957
11540
  var judgmentsContracts = [
10958
11541
  surfaceContract({
10959
11542
  name: "record_judgment",
@@ -11008,7 +11591,8 @@ var judgmentsContracts = [
11008
11591
  minLayer: input.minLayer,
11009
11592
  maxLayer: input.maxLayer
11010
11593
  })
11011
- }
11594
+ },
11595
+ args: auditTrailArgs
11012
11596
  })
11013
11597
  ];
11014
11598
 
@@ -11176,8 +11760,13 @@ var coordinationContracts = [
11176
11760
  }
11177
11761
  })
11178
11762
  ];
11179
-
11180
- // ../contracts/src/function-registry/pipeline.ts
11763
+ var pipelineSnapshotArgs = z.object({
11764
+ topicId: z.string().describe("Topic scope ID."),
11765
+ status: z.string().optional().describe("Worktree status filter."),
11766
+ lane: z.string().optional().describe("Campaign lane filter."),
11767
+ campaign: z.number().optional().describe("Campaign number filter."),
11768
+ limit: z.number().optional().describe("Maximum worktrees to inspect.")
11769
+ });
11181
11770
  var pipelineContracts = [
11182
11771
  surfaceContract({
11183
11772
  name: "pipeline_snapshot",
@@ -11198,7 +11787,8 @@ var pipelineContracts = [
11198
11787
  campaign: input.campaign,
11199
11788
  limit: input.limit
11200
11789
  })
11201
- }
11790
+ },
11791
+ args: pipelineSnapshotArgs
11202
11792
  }),
11203
11793
  surfaceContract({
11204
11794
  name: "seed_belief_lattice",
@@ -11250,7 +11840,31 @@ var recordScopeLearningArgs = z.object({
11250
11840
  rationale: z.string().optional().describe("Why this learning should enter the reasoning graph"),
11251
11841
  createQuestionText: z.string().optional().describe("Optional follow-up question text"),
11252
11842
  createBeliefText: z.string().optional().describe("Optional new belief text"),
11253
- beliefType: z.string().optional().describe("Optional belief type for createBeliefText")
11843
+ beliefType: z.string().optional().describe("Optional belief type for createBeliefText"),
11844
+ text: z.string().optional().describe("Canonical learning text alias."),
11845
+ content: z.string().optional().describe("Canonical learning content alias."),
11846
+ kind: z.string().optional().describe("Evidence kind to store."),
11847
+ sourceType: z.string().optional().describe("Evidence source type."),
11848
+ externalSourceType: z.string().optional().describe("External source type alias."),
11849
+ metadata: z.record(z.unknown()).optional().describe("Learning metadata.")
11850
+ });
11851
+ var codeContextArgs = z.object({
11852
+ topicId: z.string().optional().describe("Topic scope."),
11853
+ filePath: z.string().optional().describe("File path anchor."),
11854
+ includeFailures: z.boolean().optional().describe("Whether to include failed attempts."),
11855
+ limit: z.number().optional().describe("Maximum records to return."),
11856
+ status: z.string().optional().describe("Evidence status filter.")
11857
+ });
11858
+ var recordAttemptArgs = z.object({
11859
+ topicId: z.string().optional().describe("Topic scope."),
11860
+ description: z.string().describe("Attempt description."),
11861
+ errorMessage: z.string().optional().describe("Failure or error message."),
11862
+ filePaths: z.array(z.string()).optional().describe("Files involved in the attempt."),
11863
+ filePath: z.string().optional().describe("Single file path alias."),
11864
+ linkedBeliefId: z.string().optional().describe("Linked belief ID."),
11865
+ metadata: z.record(z.unknown()).optional().describe("Attempt metadata."),
11866
+ rationale: z.string().optional().describe("Why this attempt should be recorded."),
11867
+ title: z.string().optional().describe("Attempt evidence title.")
11254
11868
  });
11255
11869
  var learningInput = (input, context) => {
11256
11870
  const sourceKind = input.sourceKind ?? input.externalSourceType;
@@ -11367,7 +11981,8 @@ var codingContracts = [
11367
11981
  status: input.status,
11368
11982
  userId: input.userId
11369
11983
  })
11370
- }
11984
+ },
11985
+ args: codeContextArgs
11371
11986
  }),
11372
11987
  surfaceContract({
11373
11988
  name: "get_change_history",
@@ -11404,7 +12019,8 @@ var codingContracts = [
11404
12019
  functionName: "create",
11405
12020
  kind: "mutation",
11406
12021
  inputProjection: attemptInput
11407
- }
12022
+ },
12023
+ args: recordAttemptArgs
11408
12024
  }),
11409
12025
  surfaceContract({
11410
12026
  name: "get_failure_log",
@@ -11768,6 +12384,604 @@ function rankEntityTypeMatches(inputText, entityTypes, options) {
11768
12384
  return matches;
11769
12385
  }
11770
12386
 
12387
+ // ../contracts/src/tenant-bootstrap-seed.contract.ts
12388
+ function isCopyableSeedRequirement(entry) {
12389
+ 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;
12390
+ }
12391
+ var TENANT_BOOTSTRAP_TABLE_REQUIREMENTS = [
12392
+ {
12393
+ component: "kernel",
12394
+ table: "agentMessages",
12395
+ prepopulation: "runtime_data",
12396
+ copyMode: "none",
12397
+ description: "Agent coordination messages are session data, not template data."
12398
+ },
12399
+ {
12400
+ component: "kernel",
12401
+ table: "agentSessions",
12402
+ prepopulation: "runtime_data",
12403
+ copyMode: "none",
12404
+ description: "Agent coordination sessions are created by active clients."
12405
+ },
12406
+ {
12407
+ component: "kernel",
12408
+ table: "autofixJobs",
12409
+ prepopulation: "runtime_queue",
12410
+ copyMode: "none",
12411
+ description: "Autofix work items are runtime queue rows."
12412
+ },
12413
+ {
12414
+ component: "kernel",
12415
+ table: "backgroundJobRuns",
12416
+ prepopulation: "runtime_log",
12417
+ copyMode: "none",
12418
+ description: "Background job executions are runtime logs."
12419
+ },
12420
+ {
12421
+ component: "kernel",
12422
+ table: "backgroundJobSettings",
12423
+ prepopulation: "required_template",
12424
+ copyMode: "template_global",
12425
+ scope: "global",
12426
+ uniqueKey: ["jobKey"],
12427
+ description: "Default job enablement settings must come from the K template."
12428
+ },
12429
+ {
12430
+ component: "kernel",
12431
+ table: "beliefConfidence",
12432
+ prepopulation: "runtime_data",
12433
+ copyMode: "none",
12434
+ description: "Belief confidence rows are created with tenant graph facts."
12435
+ },
12436
+ {
12437
+ component: "kernel",
12438
+ table: "beliefEvidenceLinks",
12439
+ prepopulation: "runtime_data",
12440
+ copyMode: "none",
12441
+ description: "Belief-to-evidence links are tenant graph data."
12442
+ },
12443
+ {
12444
+ component: "kernel",
12445
+ table: "beliefHistory",
12446
+ prepopulation: "runtime_data",
12447
+ copyMode: "none",
12448
+ description: "Belief history is append-only tenant graph data."
12449
+ },
12450
+ {
12451
+ component: "kernel",
12452
+ table: "beliefScenarios",
12453
+ prepopulation: "runtime_data",
12454
+ copyMode: "none",
12455
+ description: "Scenario rows are tenant-authored reasoning data."
12456
+ },
12457
+ {
12458
+ component: "kernel",
12459
+ table: "beliefVotes",
12460
+ prepopulation: "runtime_data",
12461
+ copyMode: "none",
12462
+ description: "Decision belief votes are tenant-authored data."
12463
+ },
12464
+ {
12465
+ component: "kernel",
12466
+ table: "calibrationScores",
12467
+ prepopulation: "runtime_derived",
12468
+ copyMode: "none",
12469
+ description: "Calibration scores are computed from tenant outcomes."
12470
+ },
12471
+ {
12472
+ component: "kernel",
12473
+ table: "contractEvaluations",
12474
+ prepopulation: "runtime_log",
12475
+ copyMode: "none",
12476
+ description: "Contract evaluation rows are runtime computation logs."
12477
+ },
12478
+ {
12479
+ component: "kernel",
12480
+ table: "contradictions",
12481
+ prepopulation: "runtime_data",
12482
+ copyMode: "none",
12483
+ description: "Contradictions are tenant graph facts."
12484
+ },
12485
+ {
12486
+ component: "kernel",
12487
+ table: "crossProjectConnections",
12488
+ prepopulation: "runtime_data",
12489
+ copyMode: "none",
12490
+ description: "Cross-topic connections are tenant graph facts."
12491
+ },
12492
+ {
12493
+ component: "kernel",
12494
+ table: "decisionComputedSummaries",
12495
+ prepopulation: "runtime_derived",
12496
+ copyMode: "none",
12497
+ description: "Decision summaries are derived tenant outputs."
12498
+ },
12499
+ {
12500
+ component: "kernel",
12501
+ table: "decisionEvents",
12502
+ prepopulation: "runtime_data",
12503
+ copyMode: "none",
12504
+ description: "Decision events are lifecycle data."
12505
+ },
12506
+ {
12507
+ component: "kernel",
12508
+ table: "decisionParticipants",
12509
+ prepopulation: "runtime_data",
12510
+ copyMode: "none",
12511
+ description: "Decision participants are tenant-selected actors."
12512
+ },
12513
+ {
12514
+ component: "kernel",
12515
+ table: "decisionRiskLedger",
12516
+ prepopulation: "runtime_data",
12517
+ copyMode: "none",
12518
+ description: "Decision risk rows are tenant decision data."
12519
+ },
12520
+ {
12521
+ component: "kernel",
12522
+ table: "decisionSnapshots",
12523
+ prepopulation: "runtime_derived",
12524
+ copyMode: "none",
12525
+ description: "Decision snapshots are derived from tenant state."
12526
+ },
12527
+ {
12528
+ component: "kernel",
12529
+ table: "deliberationContributions",
12530
+ prepopulation: "runtime_data",
12531
+ copyMode: "none",
12532
+ description: "Deliberation contributions are tenant-authored data."
12533
+ },
12534
+ {
12535
+ component: "kernel",
12536
+ table: "deliberationSessions",
12537
+ prepopulation: "runtime_data",
12538
+ copyMode: "none",
12539
+ description: "Deliberation sessions are created by tenant workflows."
12540
+ },
12541
+ {
12542
+ component: "kernel",
12543
+ table: "epistemicAudit",
12544
+ prepopulation: "runtime_log",
12545
+ copyMode: "none",
12546
+ description: "Epistemic audit rows are append-only runtime audit data."
12547
+ },
12548
+ {
12549
+ component: "kernel",
12550
+ table: "epistemicContracts",
12551
+ prepopulation: "runtime_data",
12552
+ copyMode: "none",
12553
+ description: "Epistemic contracts are tenant-authored governance data."
12554
+ },
12555
+ {
12556
+ component: "kernel",
12557
+ table: "epistemicEdges",
12558
+ prepopulation: "runtime_data",
12559
+ copyMode: "none",
12560
+ description: "Edges are tenant reasoning graph data."
12561
+ },
12562
+ {
12563
+ component: "kernel",
12564
+ table: "epistemicNodeEmbeddings",
12565
+ prepopulation: "runtime_derived",
12566
+ copyMode: "none",
12567
+ description: "Embeddings are derived from tenant graph nodes."
12568
+ },
12569
+ {
12570
+ component: "kernel",
12571
+ table: "epistemicNodes",
12572
+ prepopulation: "runtime_data",
12573
+ copyMode: "none",
12574
+ description: "Nodes are tenant reasoning graph data."
12575
+ },
12576
+ {
12577
+ component: "kernel",
12578
+ table: "graphAnalysisCache",
12579
+ prepopulation: "runtime_derived",
12580
+ copyMode: "none",
12581
+ description: "Graph analysis cache rows are derived from tenant graph state."
12582
+ },
12583
+ {
12584
+ component: "kernel",
12585
+ table: "graphAnalysisResults",
12586
+ prepopulation: "runtime_derived",
12587
+ copyMode: "none",
12588
+ description: "Graph analysis result rows are derived tenant outputs."
12589
+ },
12590
+ {
12591
+ component: "kernel",
12592
+ table: "graphSuggestions",
12593
+ prepopulation: "runtime_derived",
12594
+ copyMode: "none",
12595
+ description: "Graph suggestions are derived recommendations."
12596
+ },
12597
+ {
12598
+ component: "kernel",
12599
+ table: "harnessReplays",
12600
+ prepopulation: "runtime_log",
12601
+ copyMode: "none",
12602
+ description: "Harness replay rows are runtime verification logs."
12603
+ },
12604
+ {
12605
+ component: "kernel",
12606
+ table: "harnessRuns",
12607
+ prepopulation: "runtime_log",
12608
+ copyMode: "none",
12609
+ description: "Harness run rows are runtime verification logs."
12610
+ },
12611
+ {
12612
+ component: "kernel",
12613
+ table: "idempotencyTokens",
12614
+ prepopulation: "runtime_log",
12615
+ copyMode: "none",
12616
+ description: "Idempotency tokens are request-scoped runtime guards."
12617
+ },
12618
+ {
12619
+ component: "kernel",
12620
+ table: "lenses",
12621
+ prepopulation: "optional_template",
12622
+ copyMode: "none",
12623
+ description: "Reusable lens templates may live in K templates, but workspace-specific copies are not required for core SDK boot."
12624
+ },
12625
+ {
12626
+ component: "kernel",
12627
+ table: "lensTopicBindings",
12628
+ prepopulation: "runtime_data",
12629
+ copyMode: "none",
12630
+ description: "Lens bindings attach runtime topics to runtime/workspace lenses."
12631
+ },
12632
+ {
12633
+ component: "kernel",
12634
+ table: "neo4jSyncQueue",
12635
+ prepopulation: "runtime_queue",
12636
+ copyMode: "none",
12637
+ description: "Neo4j sync queue rows are runtime work items."
12638
+ },
12639
+ {
12640
+ component: "kernel",
12641
+ table: "ontologyDefinitions",
12642
+ prepopulation: "required_template",
12643
+ copyMode: "template_global",
12644
+ scope: "global",
12645
+ uniqueKey: ["ontologyKey"],
12646
+ description: "Platform ontology definitions power taxonomy reads and effective ontology resolution."
12647
+ },
12648
+ {
12649
+ component: "kernel",
12650
+ table: "ontologyVersions",
12651
+ prepopulation: "required_template",
12652
+ copyMode: "template_reference_remap",
12653
+ scope: "global",
12654
+ uniqueKey: ["ontologyKey", "version"],
12655
+ dependsOn: ["ontologyDefinitions"],
12656
+ description: "Ontology versions must be copied with ontologyDefinition ID remapping."
12657
+ },
12658
+ {
12659
+ component: "kernel",
12660
+ table: "platformAgentRunPolicyDecisions",
12661
+ prepopulation: "runtime_log",
12662
+ copyMode: "none",
12663
+ description: "Agent-run policy decisions are audit logs."
12664
+ },
12665
+ {
12666
+ component: "kernel",
12667
+ table: "platformAgentRunPromptResolutions",
12668
+ prepopulation: "runtime_log",
12669
+ copyMode: "none",
12670
+ description: "Agent-run prompt resolution rows are runtime logs."
12671
+ },
12672
+ {
12673
+ component: "kernel",
12674
+ table: "platformAgentRuns",
12675
+ prepopulation: "runtime_log",
12676
+ copyMode: "none",
12677
+ description: "Agent runs are runtime execution records."
12678
+ },
12679
+ {
12680
+ component: "kernel",
12681
+ table: "platformAgentRunToolCalls",
12682
+ prepopulation: "runtime_log",
12683
+ copyMode: "none",
12684
+ description: "Agent-run tool calls are runtime execution records."
12685
+ },
12686
+ {
12687
+ component: "kernel",
12688
+ table: "platformHarnessShadowAudit",
12689
+ prepopulation: "runtime_log",
12690
+ copyMode: "none",
12691
+ description: "Harness shadow audit rows are runtime audit records."
12692
+ },
12693
+ {
12694
+ component: "kernel",
12695
+ table: "publicationRules",
12696
+ prepopulation: "required_template",
12697
+ copyMode: "template_tenant_rewrite",
12698
+ scope: "tenant",
12699
+ uniqueKey: ["tenantId", "workspaceId", "name"],
12700
+ description: "Default publication policy rules are rewritten into each tenant."
12701
+ },
12702
+ {
12703
+ component: "kernel",
12704
+ table: "questionEvidenceLinks",
12705
+ prepopulation: "runtime_data",
12706
+ copyMode: "none",
12707
+ description: "Question-to-evidence links are tenant graph data."
12708
+ },
12709
+ {
12710
+ component: "kernel",
12711
+ table: "researchJobs",
12712
+ prepopulation: "runtime_queue",
12713
+ copyMode: "none",
12714
+ description: "Research job rows are runtime queue items."
12715
+ },
12716
+ {
12717
+ component: "kernel",
12718
+ table: "schemaEnumConfig",
12719
+ prepopulation: "required_template",
12720
+ copyMode: "template_global",
12721
+ scope: "global",
12722
+ uniqueKey: ["category", "value"],
12723
+ description: "Runtime-extensible enum defaults required by SDK graph APIs."
12724
+ },
12725
+ {
12726
+ component: "kernel",
12727
+ table: "stakeholderGroups",
12728
+ prepopulation: "runtime_data",
12729
+ copyMode: "none",
12730
+ description: "Stakeholder groups are tenant decision data."
12731
+ },
12732
+ {
12733
+ component: "kernel",
12734
+ table: "systemLogs",
12735
+ prepopulation: "runtime_log",
12736
+ copyMode: "none",
12737
+ description: "System logs are runtime telemetry."
12738
+ },
12739
+ {
12740
+ component: "kernel",
12741
+ table: "tasks",
12742
+ prepopulation: "runtime_data",
12743
+ copyMode: "none",
12744
+ description: "Tasks are tenant-authored work items."
12745
+ },
12746
+ {
12747
+ component: "kernel",
12748
+ table: "topics",
12749
+ prepopulation: "runtime_bootstrap",
12750
+ copyMode: "none",
12751
+ description: "Default topics are created by tenant provisioning, not copied from templates."
12752
+ },
12753
+ {
12754
+ component: "kernel",
12755
+ table: "workflowDefinitions",
12756
+ prepopulation: "optional_template",
12757
+ copyMode: "none",
12758
+ description: "Table-driven workflow definitions can be template data after the workflow engine leaves legacy mode."
12759
+ },
12760
+ {
12761
+ component: "kernel",
12762
+ table: "workflowPullRequests",
12763
+ prepopulation: "runtime_data",
12764
+ copyMode: "none",
12765
+ description: "Workflow pull requests are tenant workflow data."
12766
+ },
12767
+ {
12768
+ component: "kernel",
12769
+ table: "workflowStages",
12770
+ prepopulation: "optional_template",
12771
+ copyMode: "none",
12772
+ dependsOn: ["workflowDefinitions"],
12773
+ description: "Workflow stages can be template data after workflowDefinitions are enabled for bootstrap copying."
12774
+ },
12775
+ {
12776
+ component: "kernel",
12777
+ table: "worktreeBeliefCluster",
12778
+ prepopulation: "runtime_data",
12779
+ copyMode: "none",
12780
+ description: "Worktree cluster rows link runtime worktrees to runtime beliefs."
12781
+ },
12782
+ {
12783
+ component: "kernel",
12784
+ table: "worktrees",
12785
+ prepopulation: "runtime_data",
12786
+ copyMode: "none",
12787
+ description: "Worktrees are tenant/runtime planning data."
12788
+ },
12789
+ {
12790
+ component: "identity",
12791
+ table: "agents",
12792
+ prepopulation: "runtime_bootstrap",
12793
+ copyMode: "none",
12794
+ description: "Service agents are provisioned per tenant or service, not copied."
12795
+ },
12796
+ {
12797
+ component: "identity",
12798
+ table: "mcpWritePolicy",
12799
+ prepopulation: "required_template",
12800
+ copyMode: "template_global",
12801
+ scope: "global",
12802
+ uniqueKey: ["topicId", "role", "toolCategory"],
12803
+ description: "Global write policy defaults govern service and interactive MCP writes."
12804
+ },
12805
+ {
12806
+ component: "identity",
12807
+ table: "modelCallLogs",
12808
+ prepopulation: "runtime_log",
12809
+ copyMode: "none",
12810
+ description: "Model call logs are runtime telemetry."
12811
+ },
12812
+ {
12813
+ component: "identity",
12814
+ table: "modelFunctionSlots",
12815
+ prepopulation: "required_template",
12816
+ copyMode: "template_global",
12817
+ scope: "global",
12818
+ uniqueKey: ["slot"],
12819
+ description: "Function-to-model slots are required by model runtime resolution."
12820
+ },
12821
+ {
12822
+ component: "identity",
12823
+ table: "modelRegistry",
12824
+ prepopulation: "required_template",
12825
+ copyMode: "template_global",
12826
+ scope: "global",
12827
+ uniqueKey: ["key"],
12828
+ description: "Model catalog defaults are required by model runtime clients."
12829
+ },
12830
+ {
12831
+ component: "identity",
12832
+ table: "modelSlotConfigs",
12833
+ prepopulation: "required_template",
12834
+ copyMode: "template_global",
12835
+ scope: "global",
12836
+ uniqueKey: ["slot"],
12837
+ description: "Slot-level defaults are required before tenant overrides exist."
12838
+ },
12839
+ {
12840
+ component: "identity",
12841
+ table: "platformAudienceGrants",
12842
+ prepopulation: "runtime_data",
12843
+ copyMode: "none",
12844
+ description: "Audience grants are principal/group-specific access rows."
12845
+ },
12846
+ {
12847
+ component: "identity",
12848
+ table: "platformAudiences",
12849
+ prepopulation: "required_template",
12850
+ copyMode: "template_tenant_rewrite",
12851
+ scope: "tenant",
12852
+ uniqueKey: ["tenantId", "workspaceId", "audienceKey"],
12853
+ description: "Default tenant audience taxonomy rows are rewritten into each tenant."
12854
+ },
12855
+ {
12856
+ component: "identity",
12857
+ table: "platformPolicyDecisionLogs",
12858
+ prepopulation: "runtime_log",
12859
+ copyMode: "none",
12860
+ description: "Policy decisions are runtime audit logs."
12861
+ },
12862
+ {
12863
+ component: "identity",
12864
+ table: "projectGrants",
12865
+ prepopulation: "runtime_data",
12866
+ copyMode: "none",
12867
+ description: "Project/topic grants are principal or group-specific access rows."
12868
+ },
12869
+ {
12870
+ component: "identity",
12871
+ table: "reasoningPermissions",
12872
+ prepopulation: "runtime_data",
12873
+ copyMode: "none",
12874
+ description: "Reasoning permissions are principal-specific policy rows."
12875
+ },
12876
+ {
12877
+ component: "identity",
12878
+ table: "tenantApiKeys",
12879
+ prepopulation: "runtime_secret",
12880
+ copyMode: "none",
12881
+ description: "API keys are tenant credentials and must never be copied."
12882
+ },
12883
+ {
12884
+ component: "identity",
12885
+ table: "tenantConfig",
12886
+ prepopulation: "required_template",
12887
+ copyMode: "template_tenant_rewrite",
12888
+ scope: "tenant",
12889
+ uniqueKey: ["tenantId"],
12890
+ description: "Tenant-local config defaults are rewritten during bootstrap."
12891
+ },
12892
+ {
12893
+ component: "identity",
12894
+ table: "tenantIntegrations",
12895
+ prepopulation: "required_template",
12896
+ copyMode: "template_tenant_rewrite",
12897
+ scope: "tenant",
12898
+ uniqueKey: ["tenantId", "integrationKey"],
12899
+ description: "Non-secret integration descriptors are rewritten into each tenant."
12900
+ },
12901
+ {
12902
+ component: "identity",
12903
+ table: "tenantModelSlotBindings",
12904
+ prepopulation: "runtime_secret",
12905
+ copyMode: "none",
12906
+ description: "Tenant model slot bindings reference provider secrets and are runtime-only."
12907
+ },
12908
+ {
12909
+ component: "identity",
12910
+ table: "tenantPolicies",
12911
+ prepopulation: "required_template",
12912
+ copyMode: "template_tenant_rewrite",
12913
+ scope: "tenant",
12914
+ uniqueKey: ["tenantId", "workspaceId", "roleName"],
12915
+ description: "Default tenant policy roles are rewritten during bootstrap."
12916
+ },
12917
+ {
12918
+ component: "identity",
12919
+ table: "tenantProviderSecrets",
12920
+ prepopulation: "runtime_secret",
12921
+ copyMode: "none",
12922
+ description: "Provider secrets are credentials and must never be copied."
12923
+ },
12924
+ {
12925
+ component: "identity",
12926
+ table: "tenantProxyGatewayUsage",
12927
+ prepopulation: "runtime_log",
12928
+ copyMode: "none",
12929
+ description: "Proxy gateway usage rows are runtime telemetry."
12930
+ },
12931
+ {
12932
+ component: "identity",
12933
+ table: "tenantProxyTokenMints",
12934
+ prepopulation: "runtime_secret",
12935
+ copyMode: "none",
12936
+ description: "Proxy token mints are ephemeral secret-bearing runtime rows."
12937
+ },
12938
+ {
12939
+ component: "identity",
12940
+ table: "tenantSandboxAuditEvents",
12941
+ prepopulation: "runtime_log",
12942
+ copyMode: "none",
12943
+ description: "Sandbox audit rows are runtime security logs."
12944
+ },
12945
+ {
12946
+ component: "identity",
12947
+ table: "tenantSecrets",
12948
+ prepopulation: "runtime_secret",
12949
+ copyMode: "none",
12950
+ description: "Tenant secrets are credentials and must never be copied."
12951
+ },
12952
+ {
12953
+ component: "identity",
12954
+ table: "toolAcls",
12955
+ prepopulation: "required_template",
12956
+ copyMode: "template_global",
12957
+ scope: "global",
12958
+ uniqueKey: ["role", "toolName"],
12959
+ description: "Default role-to-tool grants are required for SDK/MCP tool access."
12960
+ },
12961
+ {
12962
+ component: "identity",
12963
+ table: "toolRegistry",
12964
+ prepopulation: "required_template",
12965
+ copyMode: "template_global",
12966
+ scope: "global",
12967
+ uniqueKey: ["toolName"],
12968
+ description: "Core tool catalog rows are required before pack or tenant tools exist."
12969
+ },
12970
+ {
12971
+ component: "identity",
12972
+ table: "users",
12973
+ prepopulation: "runtime_bootstrap",
12974
+ copyMode: "none",
12975
+ description: "Users are created from Clerk/MC principal resolution, not copied."
12976
+ }
12977
+ ];
12978
+ TENANT_BOOTSTRAP_TABLE_REQUIREMENTS.filter(
12979
+ isCopyableSeedRequirement
12980
+ );
12981
+ TENANT_BOOTSTRAP_TABLE_REQUIREMENTS.filter(
12982
+ (entry) => !isCopyableSeedRequirement(entry)
12983
+ ).map((entry) => entry.table);
12984
+
11771
12985
  // ../contracts/src/v1/topics/v1.ts
11772
12986
  var ROOT_TOPIC_ID = "n17tm38rwet7wqgzrmwahyt1z582590y";
11773
12987
 
@@ -13374,11 +14588,32 @@ function pushTrace(trace, topic, score) {
13374
14588
  score
13375
14589
  });
13376
14590
  }
14591
+ function pickBestTopic(topics2, input) {
14592
+ const ranked = topics2.filter((topic) => topic.status !== "archived").map((topic) => ({
14593
+ topic,
14594
+ score: scoreTopicMatch(topic, input)
14595
+ })).sort((left, right) => {
14596
+ if (right.score !== left.score) {
14597
+ return right.score - left.score;
14598
+ }
14599
+ const leftName = left.topic.name.trim().toLowerCase();
14600
+ const rightName = right.topic.name.trim().toLowerCase();
14601
+ return leftName.localeCompare(rightName);
14602
+ });
14603
+ return ranked[0]?.topic ?? null;
14604
+ }
14605
+ function pickFallbackRootTopic(topics2, input) {
14606
+ const parentless = topics2.filter((topic) => !topic.parentTopicId);
14607
+ return pickBestTopic(parentless, input) ?? pickBestTopic(topics2, input);
14608
+ }
13377
14609
  async function loadTopicUniverse(ctx, input) {
13378
14610
  const desiredTenantId = ctx.tenantId;
13379
14611
  const desiredWorkspaceId = readString2(input.workspaceId) ?? ctx.workspaceId;
13380
14612
  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;
14613
+ const scopedTopics = rawTopics.filter(
14614
+ (topic) => topicMatchesScope(topic, desiredTenantId, desiredWorkspaceId)
14615
+ );
14616
+ const root = rawTopics.find((topic) => topic.rawId === ROOT_TOPIC_ID) ?? await fetchTopicById(ctx, ROOT_TOPIC_ID) ?? pickFallbackRootTopic(scopedTopics, input) ?? null;
13382
14617
  if (!root) {
13383
14618
  throw new Error("[topic-resolver] Root topic not found.");
13384
14619
  }
@@ -16607,7 +17842,8 @@ function resolveGatewayClaims(authContext) {
16607
17842
  principalType: "human",
16608
17843
  tenantId: authContext.tenantId ?? authContext.servicePrincipalTenantId ?? "unknown",
16609
17844
  workspaceId: authContext.workspaceId ?? authContext.servicePrincipalWorkspaceId,
16610
- roles: [],
17845
+ roles: authContext.roles ?? [],
17846
+ membershipId: authContext.membershipId,
16611
17847
  scopes: [...authContext.grantedScopes],
16612
17848
  authMode: "interactive_user",
16613
17849
  sessionId: authContext.sessionId,
@@ -16622,6 +17858,7 @@ function resolveGatewayClaims(authContext) {
16622
17858
  tenantId: authContext.tenantId ?? authContext.servicePrincipalTenantId ?? "unknown",
16623
17859
  workspaceId: authContext.workspaceId ?? authContext.servicePrincipalWorkspaceId,
16624
17860
  roles: ["service_agent"],
17861
+ membershipId: authContext.membershipId,
16625
17862
  scopes: [...authContext.grantedScopes],
16626
17863
  authMode: "service_principal",
16627
17864
  sessionId: authContext.sessionId,
@@ -16636,6 +17873,7 @@ function resolveGatewayClaims(authContext) {
16636
17873
  tenantId: authContext.tenantId ?? authContext.servicePrincipalTenantId ?? "unknown",
16637
17874
  workspaceId: authContext.workspaceId ?? authContext.servicePrincipalWorkspaceId,
16638
17875
  roles: ["service_agent"],
17876
+ membershipId: authContext.membershipId,
16639
17877
  scopes: [...authContext.grantedScopes],
16640
17878
  authMode: "tenant_api_key",
16641
17879
  sessionId: authContext.sessionId,
@@ -16650,6 +17888,7 @@ function resolveGatewayClaims(authContext) {
16650
17888
  tenantId: authContext.tenantId ?? "unknown",
16651
17889
  workspaceId: authContext.workspaceId,
16652
17890
  roles: authContext.roles ?? [],
17891
+ membershipId: authContext.membershipId,
16653
17892
  scopes: [...authContext.grantedScopes],
16654
17893
  authMode: "session_token",
16655
17894
  sessionId: authContext.sessionId,
@@ -18432,6 +19671,101 @@ function readStringArray9(value) {
18432
19671
  const normalized = value.map((entry) => readString19(entry)).filter((entry) => Boolean(entry));
18433
19672
  return normalized.length > 0 ? normalized : void 0;
18434
19673
  }
19674
+ function normalizeKeyQuestions(keyQuestions) {
19675
+ if (!Array.isArray(keyQuestions)) {
19676
+ return void 0;
19677
+ }
19678
+ const normalized = keyQuestions.map((entry) => {
19679
+ const question = readString19(entry.question);
19680
+ if (!question) {
19681
+ return void 0;
19682
+ }
19683
+ return {
19684
+ question,
19685
+ ...entry.status ? { status: entry.status } : {},
19686
+ ...readString19(entry.answer) ? { answer: readString19(entry.answer) } : {},
19687
+ ...entry.answerConfidence ? { answerConfidence: entry.answerConfidence } : {},
19688
+ ...readString19(entry.linkedQuestionId) ? {
19689
+ linkedQuestionId: decodeExternalId9(
19690
+ readString19(entry.linkedQuestionId),
19691
+ "que",
19692
+ "keyQuestions.linkedQuestionId"
19693
+ )
19694
+ } : {}
19695
+ };
19696
+ }).filter((entry) => Boolean(entry));
19697
+ return normalized.length > 0 ? normalized : void 0;
19698
+ }
19699
+ function normalizeEvidenceSignals(evidenceSignals) {
19700
+ if (!Array.isArray(evidenceSignals)) {
19701
+ return void 0;
19702
+ }
19703
+ const normalized = evidenceSignals.map((entry) => {
19704
+ const signal = readString19(entry.signal);
19705
+ if (!signal) {
19706
+ return void 0;
19707
+ }
19708
+ return {
19709
+ signal,
19710
+ ...typeof entry.collected === "boolean" ? { collected: entry.collected } : {},
19711
+ ...readString19(entry.progress) ? { progress: readString19(entry.progress) } : {},
19712
+ ...readString19(entry.notes) ? { notes: readString19(entry.notes) } : {}
19713
+ };
19714
+ }).filter((entry) => Boolean(entry));
19715
+ return normalized.length > 0 ? normalized : void 0;
19716
+ }
19717
+ function normalizeDecisionGate(input) {
19718
+ const source = input.decisionGate ?? (input.goCriteria || input.noGoSignals ? {
19719
+ goCriteria: input.goCriteria ?? [],
19720
+ noGoSignals: input.noGoSignals ?? []
19721
+ } : void 0);
19722
+ if (!source) {
19723
+ return void 0;
19724
+ }
19725
+ return {
19726
+ goCriteria: readStringArray9(source.goCriteria) ?? [],
19727
+ noGoSignals: readStringArray9(source.noGoSignals) ?? [],
19728
+ ...source.verdict ? { verdict: source.verdict } : {},
19729
+ ...readString19(source.verdictRationale) ? { verdictRationale: readString19(source.verdictRationale) } : {},
19730
+ ...typeof source.decidedAt === "number" && Number.isFinite(source.decidedAt) ? { decidedAt: source.decidedAt } : {},
19731
+ ...readString19(source.decidedBy) ? { decidedBy: readString19(source.decidedBy) } : {}
19732
+ };
19733
+ }
19734
+ function normalizeMergeOutcomes(outcomes) {
19735
+ const keyFindings = [];
19736
+ const scoringOutcomes = [];
19737
+ for (const outcome of outcomes) {
19738
+ const finding = readString19(outcome);
19739
+ if (finding) {
19740
+ keyFindings.push(finding);
19741
+ continue;
19742
+ }
19743
+ const record = asRecord15(outcome);
19744
+ if (!Object.keys(record).length) {
19745
+ throw createWorktreesError({
19746
+ message: "[worktrees] merge outcomes must be strings or { beliefId, confidence, rationale } objects.",
19747
+ status: 400,
19748
+ code: "INVALID_REQUEST",
19749
+ invariantCode: "request.valid_shape",
19750
+ suggestion: "Pass string outcomes for key findings, or scoring objects for belief confidence outcomes."
19751
+ });
19752
+ }
19753
+ scoringOutcomes.push({
19754
+ beliefId: requireString3(record.beliefId, "outcomes[].beliefId"),
19755
+ confidence: readNumber13(record.confidence) ?? (() => {
19756
+ throw createWorktreesError({
19757
+ message: "[worktrees] outcomes[].confidence must be a finite number.",
19758
+ status: 400,
19759
+ code: "INVALID_REQUEST",
19760
+ invariantCode: "request.valid_shape",
19761
+ suggestion: "Provide confidence as a number when scoring a belief outcome."
19762
+ });
19763
+ })(),
19764
+ rationale: requireString3(record.rationale, "outcomes[].rationale")
19765
+ });
19766
+ }
19767
+ return { keyFindings, scoringOutcomes };
19768
+ }
18435
19769
  function compareNullableNumber(left, right, fallback = 9999) {
18436
19770
  return (left ?? fallback) - (right ?? fallback);
18437
19771
  }
@@ -18676,14 +20010,33 @@ function buildWorktreeCampaignList(records) {
18676
20010
  }
18677
20011
  async function createWorktree(deps, input) {
18678
20012
  const topicRawId = decodeExternalId9(input.topicId, "top", "topicId");
20013
+ const targetBeliefIds = input.targetBeliefIds ?? input.beliefIds;
18679
20014
  const created = await deps.createWorktree({
18680
20015
  title: requireString3(input.title, "title"),
18681
20016
  topicRawId,
18682
20017
  objective: readString19(input.objective),
18683
20018
  hypothesis: readString19(input.hypothesis),
18684
- beliefRawIds: input.beliefIds?.map(
20019
+ rationale: readString19(input.rationale),
20020
+ worktreeType: readString19(input.worktreeType),
20021
+ startDate: typeof input.startDate === "number" && Number.isFinite(input.startDate) ? input.startDate : void 0,
20022
+ endDate: typeof input.endDate === "number" && Number.isFinite(input.endDate) ? input.endDate : void 0,
20023
+ durationWeeks: typeof input.durationWeeks === "number" && Number.isFinite(input.durationWeeks) ? input.durationWeeks : void 0,
20024
+ confidenceImpact: input.confidenceImpact,
20025
+ beliefFocus: readString19(input.beliefFocus),
20026
+ beliefRawIds: targetBeliefIds?.map(
18685
20027
  (id) => decodeExternalId9(id, "bel", "beliefIds")
18686
20028
  ),
20029
+ targetBeliefRawIds: input.targetBeliefIds?.map(
20030
+ (id) => decodeExternalId9(id, "bel", "targetBeliefIds")
20031
+ ),
20032
+ targetQuestionRawIds: input.targetQuestionIds?.map(
20033
+ (id) => decodeExternalId9(id, "que", "targetQuestionIds")
20034
+ ),
20035
+ keyQuestions: normalizeKeyQuestions(input.keyQuestions),
20036
+ evidenceSignals: normalizeEvidenceSignals(input.evidenceSignals),
20037
+ decisionGate: normalizeDecisionGate(input),
20038
+ goCriteria: readStringArray9(input.goCriteria),
20039
+ noGoSignals: readStringArray9(input.noGoSignals),
18687
20040
  autoShape: typeof input.autoShape === "boolean" ? input.autoShape : void 0,
18688
20041
  domainPackId: readString19(input.domainPackId),
18689
20042
  campaign: typeof input.campaign === "number" && Number.isFinite(input.campaign) ? input.campaign : void 0,
@@ -18815,11 +20168,45 @@ async function updateWorktreeTargets(deps, input) {
18815
20168
  }
18816
20169
  async function mergeWorktree(deps, input) {
18817
20170
  const rawId = decodeExternalId9(input.id, "wt", "id");
18818
- const summary = readString19(input.summary) ?? "Worktree merged.";
18819
- await deps.completeWorktree({ worktreeRawId: rawId, summary });
20171
+ const { keyFindings, scoringOutcomes } = normalizeMergeOutcomes(input.outcomes);
20172
+ const summary = readString19(input.summary) ?? keyFindings[0] ?? "Worktree merged.";
20173
+ const completeKeyFindings = keyFindings.length > 0 ? keyFindings : [summary];
20174
+ const worktree = await deps.fetchWorktree(rawId);
20175
+ if (!worktree) {
20176
+ throw createWorktreesError({
20177
+ message: `[worktrees] Worktree not found: ${rawId}.`,
20178
+ status: 404,
20179
+ code: "NOT_FOUND",
20180
+ invariantCode: "resource.exists"
20181
+ });
20182
+ }
20183
+ const worktreeStatus = readString19(asRecord15(worktree).status);
20184
+ if (worktreeStatus === "planning") {
20185
+ await deps.activateWorktree({ worktreeRawId: rawId });
20186
+ await deps.completeWorktree({
20187
+ worktreeRawId: rawId,
20188
+ summary,
20189
+ keyFindings: completeKeyFindings
20190
+ });
20191
+ } else if (!worktreeStatus || worktreeStatus === "active") {
20192
+ await deps.completeWorktree({
20193
+ worktreeRawId: rawId,
20194
+ summary,
20195
+ keyFindings: completeKeyFindings
20196
+ });
20197
+ } else if (worktreeStatus !== "completed" && worktreeStatus !== "merged") {
20198
+ throw createWorktreesError({
20199
+ message: `[worktrees] Cannot merge worktree in status "${worktreeStatus}".`,
20200
+ status: 409,
20201
+ code: "CONFLICT",
20202
+ invariantCode: "worktree.mergeable_status",
20203
+ suggestion: "Merge only planning, active, completed, or already-merged worktrees.",
20204
+ details: { worktreeId: encodeWorktreeId(rawId), status: worktreeStatus }
20205
+ });
20206
+ }
18820
20207
  const failedBeliefs = [];
18821
20208
  let beliefsScored = 0;
18822
- for (const outcome of input.outcomes) {
20209
+ for (const outcome of scoringOutcomes) {
18823
20210
  try {
18824
20211
  await deps.scoreBeliefOutcome({
18825
20212
  worktreeRawId: rawId,
@@ -18895,15 +20282,35 @@ function summarizeWorktreeCollection(rows) {
18895
20282
  function buildCreateMutationArgs(input, userId) {
18896
20283
  const objective = input.objective?.trim();
18897
20284
  const hypothesis = input.hypothesis?.trim();
20285
+ const rationale = input.rationale?.trim();
20286
+ const worktreeType = input.worktreeType?.trim();
20287
+ const beliefFocus = input.beliefFocus?.trim();
18898
20288
  const gate = input.gate?.trim();
18899
20289
  const lensId = input.lensId?.trim();
20290
+ const targetBeliefIds = input.targetBeliefIds && input.targetBeliefIds.length > 0 ? input.targetBeliefIds : input.beliefIds;
18900
20291
  return {
18901
20292
  name: input.title,
18902
20293
  topicId: input.topicId,
18903
20294
  createdBy: userId,
18904
20295
  ...objective ? { objective } : {},
18905
20296
  ...hypothesis ? { hypothesis } : {},
18906
- ...objective || hypothesis ? { beliefFocus: hypothesis ?? objective } : {},
20297
+ ...rationale ? { rationale } : {},
20298
+ ...worktreeType ? { worktreeType } : {},
20299
+ ...typeof input.startDate === "number" ? { startDate: input.startDate } : {},
20300
+ ...typeof input.endDate === "number" ? { endDate: input.endDate } : {},
20301
+ ...typeof input.durationWeeks === "number" ? { durationWeeks: input.durationWeeks } : {},
20302
+ ...input.confidenceImpact ? { confidenceImpact: input.confidenceImpact } : {},
20303
+ ...beliefFocus || objective || hypothesis ? { beliefFocus: beliefFocus ?? hypothesis ?? objective } : {},
20304
+ ...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) } : {},
20305
+ ...Array.isArray(targetBeliefIds) && targetBeliefIds.length > 0 ? { targetBeliefIds: targetBeliefIds.map((id) => id) } : {},
20306
+ ...Array.isArray(input.keyQuestions) && input.keyQuestions.length > 0 ? { keyQuestions: input.keyQuestions } : {},
20307
+ ...Array.isArray(input.evidenceSignals) && input.evidenceSignals.length > 0 ? { evidenceSignals: input.evidenceSignals } : {},
20308
+ ...input.decisionGate ? { decisionGate: input.decisionGate } : input.goCriteria || input.noGoSignals ? {
20309
+ decisionGate: {
20310
+ goCriteria: input.goCriteria ?? [],
20311
+ noGoSignals: input.noGoSignals ?? []
20312
+ }
20313
+ } : {},
18907
20314
  ...typeof input.campaign === "number" ? { campaign: input.campaign } : {},
18908
20315
  ...input.lane ? { lane: input.lane } : {},
18909
20316
  ...typeof input.laneOrderInCampaign === "number" ? { laneOrderInCampaign: input.laneOrderInCampaign } : {},
@@ -18912,7 +20319,10 @@ function buildCreateMutationArgs(input, userId) {
18912
20319
  ...Array.isArray(input.blocks) && input.blocks.length > 0 ? { blocks: input.blocks.map((id) => id) } : {},
18913
20320
  ...gate ? { gate } : {},
18914
20321
  ...lensId ? { lensId } : {},
18915
- ...Array.isArray(input.beliefIds) && input.beliefIds.length > 0 ? { targetBeliefIds: input.beliefIds.map((id) => id) } : {}
20322
+ ...Array.isArray(input.proofArtifacts) ? { proofArtifacts: input.proofArtifacts } : {},
20323
+ ...input.staffingHint?.trim() ? { staffingHint: input.staffingHint.trim() } : {},
20324
+ ...typeof input.lastReconciledAt === "number" ? { lastReconciledAt: input.lastReconciledAt } : {},
20325
+ ...input.autoFixPolicy ? { autoFixPolicy: input.autoFixPolicy } : {}
18916
20326
  };
18917
20327
  }
18918
20328
  function readString20(value) {
@@ -18985,7 +20395,9 @@ function createGatewayWorktreesPort(authContext) {
18985
20395
  ...input,
18986
20396
  topicId: input.topicRawId,
18987
20397
  title: input.title,
18988
- beliefIds: input.beliefRawIds
20398
+ beliefIds: input.beliefRawIds,
20399
+ targetBeliefIds: input.targetBeliefRawIds,
20400
+ targetQuestionIds: input.targetQuestionRawIds
18989
20401
  },
18990
20402
  authContext.userId
18991
20403
  ),
@@ -19000,7 +20412,9 @@ function createGatewayWorktreesPort(authContext) {
19000
20412
  ...input,
19001
20413
  topicId: input.topicRawId,
19002
20414
  title: input.title,
19003
- beliefIds: input.beliefRawIds
20415
+ beliefIds: input.beliefRawIds,
20416
+ targetBeliefIds: input.targetBeliefRawIds,
20417
+ targetQuestionIds: input.targetQuestionRawIds
19004
20418
  },
19005
20419
  authContext.userId
19006
20420
  ));
@@ -19028,7 +20442,7 @@ function createGatewayWorktreesPort(authContext) {
19028
20442
  completeWorktree(args) {
19029
20443
  return authContext.convex.mutation(api.worktrees.complete, {
19030
20444
  worktreeId: args.worktreeRawId,
19031
- keyFindings: [args.summary],
20445
+ keyFindings: args.keyFindings?.length ? args.keyFindings : [args.summary],
19032
20446
  decisionsReached: [],
19033
20447
  nextSteps: [],
19034
20448
  userId: authContext.userId
@@ -20846,6 +22260,40 @@ function normalizeRecommendation(row) {
20846
22260
  recommendationId: cleanString(suggestion.recommendationId) ?? cleanString(suggestion.suggestionId)
20847
22261
  };
20848
22262
  }
22263
+ function readChangeTimestamp(row) {
22264
+ return cleanNumber(row.updatedAt) ?? cleanNumber(row.actedAt) ?? cleanNumber(row.createdAt);
22265
+ }
22266
+ function includesAny(value, expected) {
22267
+ if (!expected || expected.length === 0) {
22268
+ return true;
22269
+ }
22270
+ if (Array.isArray(value)) {
22271
+ return value.some((entry) => expected.includes(String(entry)));
22272
+ }
22273
+ return typeof value === "string" && expected.includes(value);
22274
+ }
22275
+ function normalizeGraphChange(row, kind) {
22276
+ const metadata = asRecord21(row.metadata);
22277
+ const sourceNodeIds = cleanStringArray(row.sourceNodeIds) ?? cleanStringArray(row.targetNodeIds) ?? [
22278
+ cleanString(row.targetNodeId),
22279
+ cleanString(row.secondaryNodeId),
22280
+ cleanString(row.resultNodeId)
22281
+ ].filter((value) => Boolean(value));
22282
+ const sourceEdgeIds = cleanStringArray(row.sourceEdgeIds) ?? [];
22283
+ return {
22284
+ changeId: cleanString(row.changeId) ?? cleanString(row.suggestionId) ?? cleanString(row.analysisId) ?? cleanString(row.recommendationId) ?? cleanString(row._id),
22285
+ analysisId: cleanString(row.analysisId) ?? cleanString(row.analysisResultId) ?? cleanString(row._id),
22286
+ suggestionId: cleanString(row.suggestionId),
22287
+ topicId: cleanString(row.topicId),
22288
+ workspaceId: cleanString(row.workspaceId),
22289
+ changeType: cleanString(row.changeType) ?? kind,
22290
+ nodeIds: sourceNodeIds,
22291
+ edgeIds: sourceEdgeIds,
22292
+ summary: cleanString(row.summary) ?? cleanString(row.title) ?? cleanString(row.analysisText) ?? cleanString(row.rationale),
22293
+ metadata,
22294
+ createdAt: readChangeTimestamp(row)
22295
+ };
22296
+ }
20849
22297
  function normalizeNodeResult(row, input) {
20850
22298
  const metadata = asRecord21(row.metadata);
20851
22299
  const confidence = cleanNumber(row.confidence) ?? cleanNumber(metadata.confidence) ?? cleanNumber(row.baseRate);
@@ -20952,6 +22400,37 @@ async function listGraphSuggestionsFromGatewayAuth(authContext, input) {
20952
22400
  suggestions: Array.isArray(suggestions) ? suggestions.map((row) => normalizeSuggestion(asRecord21(row))) : []
20953
22401
  };
20954
22402
  }
22403
+ async function listGraphChangesFromGatewayAuth(authContext, input) {
22404
+ const minimumCreatedAt = cleanNumber(input.minimumCreatedAt) ?? cleanNumber(input.since) ?? cleanNumber(input.createdAt) ?? cleanNumber(input.analysisCreatedAt);
22405
+ if (minimumCreatedAt === void 0) {
22406
+ throw new Error("minimumCreatedAt is required");
22407
+ }
22408
+ const sourceNodeIds = cleanStringArray(input.sourceNodeIds) ?? (cleanString(input.nodeId) ? [cleanString(input.nodeId)] : void 0);
22409
+ const sourceEdgeIds = cleanStringArray(input.sourceEdgeIds) ?? (cleanString(input.edgeId) ? [cleanString(input.edgeId)] : void 0);
22410
+ const limit = readLimit(input.limit) ?? 100;
22411
+ const [{ analyses }, { suggestions }] = await Promise.all([
22412
+ listGraphAnalysesFromGatewayAuth(authContext, input),
22413
+ listGraphSuggestionsFromGatewayAuth(authContext, input)
22414
+ ]);
22415
+ const analysisChanges = analyses.map((row) => normalizeGraphChange(asRecord21(row), "analysis_recorded")).filter((row) => {
22416
+ const createdAt = cleanNumber(row.createdAt);
22417
+ return createdAt !== void 0 && createdAt >= minimumCreatedAt && includesAny(row.nodeIds, sourceNodeIds) && includesAny(row.edgeIds, sourceEdgeIds);
22418
+ });
22419
+ const suggestionChanges = suggestions.map((row) => normalizeGraphChange(asRecord21(row), "suggestion_recorded")).filter((row) => {
22420
+ const createdAt = cleanNumber(row.createdAt);
22421
+ return createdAt !== void 0 && createdAt >= minimumCreatedAt && includesAny(row.nodeIds, sourceNodeIds) && includesAny(row.edgeIds, sourceEdgeIds);
22422
+ });
22423
+ const changes = [...analysisChanges, ...suggestionChanges].sort((left, right) => {
22424
+ const leftAt = cleanNumber(left.createdAt) ?? 0;
22425
+ const rightAt = cleanNumber(right.createdAt) ?? 0;
22426
+ return rightAt - leftAt;
22427
+ }).slice(0, limit);
22428
+ return {
22429
+ changes,
22430
+ items: changes,
22431
+ total: changes.length
22432
+ };
22433
+ }
20955
22434
  async function updateGraphSuggestionStatusFromGatewayAuth(authContext, input) {
20956
22435
  const suggestion = await authContext.convex.mutation(
20957
22436
  api.graphAnalysisResults.updateSuggestionStatus,
@@ -21121,6 +22600,13 @@ async function handleGraphAnalysisListSuggestions(args) {
21121
22600
  run: () => listGraphSuggestionsFromGatewayAuth(args.authContext, args.query)
21122
22601
  });
21123
22602
  }
22603
+ async function handleGraphAnalysisListChanges(args) {
22604
+ return withGraphRoute({
22605
+ ...args,
22606
+ fallbackMessage: "Failed to list graph analysis changes.",
22607
+ run: () => listGraphChangesFromGatewayAuth(args.authContext, args.query)
22608
+ });
22609
+ }
21124
22610
  async function handleGraphAnalysisUpdateSuggestion(args) {
21125
22611
  return withGraphRoute({
21126
22612
  ...args,
@@ -22543,6 +24029,36 @@ function readStringArray17(value) {
22543
24029
  const normalized = value.map((entry) => readString33(entry)).filter((entry) => Boolean(entry));
22544
24030
  return normalized.length > 0 ? normalized : void 0;
22545
24031
  }
24032
+ function readObjectArray(value) {
24033
+ if (!Array.isArray(value)) {
24034
+ return void 0;
24035
+ }
24036
+ const normalized = value.map((entry) => asRecord30(entry)).filter((entry) => Object.keys(entry).length > 0);
24037
+ return normalized.length > 0 ? normalized : void 0;
24038
+ }
24039
+ function readConfidenceImpact(value) {
24040
+ return value === "high" || value === "medium" || value === "low" ? value : void 0;
24041
+ }
24042
+ function normalizeMergeOutcomes2(value) {
24043
+ if (!Array.isArray(value)) {
24044
+ return [];
24045
+ }
24046
+ return value.map((entry) => {
24047
+ const finding = readString33(entry);
24048
+ if (finding) {
24049
+ return finding;
24050
+ }
24051
+ const row = asRecord30(entry);
24052
+ if (!Object.keys(row).length) {
24053
+ return null;
24054
+ }
24055
+ return {
24056
+ beliefId: readString33(row.beliefId) ?? "",
24057
+ confidence: readNumber22(row.confidence) ?? Number.NaN,
24058
+ rationale: readString33(row.rationale) ?? ""
24059
+ };
24060
+ }).filter((entry) => entry !== null);
24061
+ }
22546
24062
  function handleWorktreesError(error, fallbackMessage, correlationId, policyTraceId) {
22547
24063
  const resolved = resolveServerCoreError(error, fallbackMessage);
22548
24064
  return errorResponse({
@@ -22559,12 +24075,29 @@ function handleWorktreesError(error, fallbackMessage, correlationId, policyTrace
22559
24075
  async function handleWorktreeCreate(args) {
22560
24076
  try {
22561
24077
  const body = asRecord30(args.body);
24078
+ const goCriteria = readStringArray17(body.goCriteria);
24079
+ const noGoSignals = readStringArray17(body.noGoSignals);
22562
24080
  const payload = await createWorktreeFromGatewayAuth(args.authContext, {
22563
- title: readString33(body.title) ?? "",
24081
+ title: readString33(body.title) ?? readString33(body.name) ?? "",
22564
24082
  topicId: readString33(body.topicId ?? body.projectId) ?? "",
22565
24083
  objective: readString33(body.objective),
22566
24084
  hypothesis: readString33(body.hypothesis),
22567
- beliefIds: readStringArray17(body.beliefIds) ?? readStringArray17(body.beliefs),
24085
+ rationale: readString33(body.rationale),
24086
+ worktreeType: readString33(body.worktreeType),
24087
+ startDate: readNumber22(body.startDate),
24088
+ endDate: readNumber22(body.endDate),
24089
+ durationWeeks: readNumber22(body.durationWeeks),
24090
+ confidenceImpact: readConfidenceImpact(body.confidenceImpact),
24091
+ beliefFocus: readString33(body.beliefFocus),
24092
+ beliefIds: readStringArray17(body.targetBeliefIds) ?? readStringArray17(body.beliefIds) ?? readStringArray17(body.beliefs),
24093
+ targetBeliefIds: readStringArray17(body.targetBeliefIds),
24094
+ targetQuestionIds: readStringArray17(body.targetQuestionIds),
24095
+ keyQuestions: readObjectArray(body.keyQuestions),
24096
+ evidenceSignals: readObjectArray(body.evidenceSignals),
24097
+ decisionGate: body.decisionGate && typeof body.decisionGate === "object" && !Array.isArray(body.decisionGate) ? body.decisionGate : goCriteria || noGoSignals ? {
24098
+ goCriteria: goCriteria ?? [],
24099
+ noGoSignals: noGoSignals ?? []
24100
+ } : void 0,
22568
24101
  autoShape: typeof body.autoShape === "boolean" ? body.autoShape : void 0,
22569
24102
  domainPackId: readString33(body.domainPackId),
22570
24103
  campaign: readNumber22(body.campaign),
@@ -22717,12 +24250,7 @@ async function handleWorktreeUpdate(args) {
22717
24250
  async function handleWorktreeMerge(args) {
22718
24251
  try {
22719
24252
  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
- }));
24253
+ const outcomes = normalizeMergeOutcomes2(body.outcomes);
22726
24254
  const payload = await mergeWorktreeFromGatewayAuth(args.authContext, {
22727
24255
  id: args.worktreeId,
22728
24256
  summary: readString33(body.summary),
@@ -22875,6 +24403,6 @@ async function handleWorktreeBulkCreate(args) {
22875
24403
  }
22876
24404
  }
22877
24405
 
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 };
24406
+ 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
24407
  //# sourceMappingURL=gateway.js.map
22880
24408
  //# sourceMappingURL=gateway.js.map