@lucern/mcp 0.3.0-alpha.0 → 0.3.0-alpha.1

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/index.js CHANGED
@@ -3,6 +3,7 @@ import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/
3
3
  import { McpServer, ResourceTemplate } from '@modelcontextprotocol/sdk/server/mcp.js';
4
4
  import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
5
5
  import { z } from 'zod';
6
+ import { v } from 'convex/values';
6
7
  import 'crypto';
7
8
  import * as fs from 'fs';
8
9
  import { existsSync } from 'fs';
@@ -263,38 +264,6 @@ function scoreObservation(record, terms) {
263
264
  return score;
264
265
  }
265
266
 
266
- // ../sdk/src/opinion.ts
267
- function clamp01(value) {
268
- if (!Number.isFinite(value)) {
269
- return 0;
270
- }
271
- return Math.max(0, Math.min(1, value));
272
- }
273
- function vacuous(baseRate = 0.5) {
274
- return { b: 0, d: 0, u: 1, a: clamp01(baseRate) };
275
- }
276
- function dogmatic(probability, baseRate = 0.5) {
277
- const p = clamp01(probability);
278
- return { b: p, d: 1 - p, u: 0, a: clamp01(baseRate) };
279
- }
280
- function opinionFromBaseRate(probability) {
281
- return vacuous(clamp01(probability));
282
- }
283
- function opinionFromDogmatic(probability, baseRate = 0.5) {
284
- return dogmatic(clamp01(probability), clamp01(baseRate));
285
- }
286
- function opinionFromProjected(probability, uncertainty, baseRate = 0.5) {
287
- const p = clamp01(probability);
288
- const u = clamp01(uncertainty);
289
- const remainingMass = 1 - u;
290
- return {
291
- b: p * remainingMass,
292
- d: (1 - p) * remainingMass,
293
- u,
294
- a: clamp01(baseRate)
295
- };
296
- }
297
-
298
267
  // ../sdk/src/coreClient.ts
299
268
  var LucernApiError = class extends Error {
300
269
  code;
@@ -1306,7 +1275,7 @@ function readString(value) {
1306
1275
  function readNumber(value) {
1307
1276
  return typeof value === "number" && Number.isFinite(value) ? value : void 0;
1308
1277
  }
1309
- function clamp012(value) {
1278
+ function clamp01(value) {
1310
1279
  return Math.max(0, Math.min(1, value));
1311
1280
  }
1312
1281
  function normalizeOpinionTuple(record) {
@@ -1315,20 +1284,16 @@ function normalizeOpinionTuple(record) {
1315
1284
  const rawDisbelief = readNumber(opinion.d) ?? readNumber(record.disbelief);
1316
1285
  const rawUncertainty = readNumber(opinion.u) ?? readNumber(record.uncertainty);
1317
1286
  const rawBaseRate = readNumber(opinion.a) ?? readNumber(record.baseRate);
1318
- if (rawBelief === void 0 && rawDisbelief === void 0 && rawUncertainty === void 0) {
1319
- const projected = clamp012(readNumber(record.confidence) ?? 0);
1320
- return {
1321
- b: projected,
1322
- d: 1 - projected,
1323
- u: 0,
1324
- a: 0.5
1325
- };
1287
+ if (rawBelief === void 0 || rawDisbelief === void 0 || rawUncertainty === void 0 || rawBaseRate === void 0) {
1288
+ throw new Error(
1289
+ "Gateway opinion history entries must include belief, disbelief, uncertainty, and baseRate."
1290
+ );
1326
1291
  }
1327
1292
  return {
1328
- b: clamp012(rawBelief ?? 0),
1329
- d: clamp012(rawDisbelief ?? 0),
1330
- u: clamp012(rawUncertainty ?? 0),
1331
- a: clamp012(rawBaseRate ?? 0.5)
1293
+ b: clamp01(rawBelief),
1294
+ d: clamp01(rawDisbelief),
1295
+ u: clamp01(rawUncertainty),
1296
+ a: clamp01(rawBaseRate)
1332
1297
  };
1333
1298
  }
1334
1299
  function mapOpinionHistoryEntriesFromGatewayData(payload) {
@@ -1336,28 +1301,28 @@ function mapOpinionHistoryEntriesFromGatewayData(payload) {
1336
1301
  return entries2.map((value) => {
1337
1302
  const record = asRecord2(value);
1338
1303
  const tuple = normalizeOpinionTuple(record);
1339
- const projected = readNumber(record.confidence) ?? clamp012(tuple.b + tuple.a * tuple.u);
1304
+ const projected = readNumber(record.confidence) ?? clamp01(tuple.b + tuple.a * tuple.u);
1340
1305
  const triggeringEvidenceId = readString(record.triggeringEvidenceId);
1306
+ const triggeringQuestionId = readString(record.triggeringQuestionId);
1307
+ const triggeringAnswerId = readString(record.triggeringAnswerId);
1308
+ const triggeringContradictionId = readString(
1309
+ record.triggeringContradictionId
1310
+ );
1341
1311
  const triggeringWorktreeId = readString(record.triggeringWorktreeId);
1312
+ const triggeringRef = triggeringEvidenceId ? { kind: "evidence", id: triggeringEvidenceId } : triggeringQuestionId ? { kind: "question", id: triggeringQuestionId } : triggeringAnswerId ? { kind: "answer", id: triggeringAnswerId } : triggeringContradictionId ? { kind: "contradiction", id: triggeringContradictionId } : triggeringWorktreeId ? { kind: "worktree", id: triggeringWorktreeId } : void 0;
1313
+ const trigger = readString(record.trigger);
1314
+ if (!trigger) {
1315
+ throw new Error("Gateway opinion history entries must include trigger.");
1316
+ }
1342
1317
  return {
1343
1318
  t: readNumber(record.timestamp) ?? readNumber(record.assessedAt) ?? 0,
1344
1319
  b: tuple.b,
1345
1320
  d: tuple.d,
1346
1321
  u: tuple.u,
1347
1322
  a: tuple.a,
1348
- P: clamp012(projected),
1349
- trigger: readString(record.trigger) ?? "manual",
1350
- ...triggeringEvidenceId ? {
1351
- triggeringRef: {
1352
- kind: "evidence",
1353
- id: triggeringEvidenceId
1354
- }
1355
- } : triggeringWorktreeId ? {
1356
- triggeringRef: {
1357
- kind: "worktree",
1358
- id: triggeringWorktreeId
1359
- }
1360
- } : {},
1323
+ P: clamp01(projected),
1324
+ trigger,
1325
+ ...triggeringRef ? { triggeringRef } : {},
1361
1326
  ...readString(record.rationale) ? { rationale: readString(record.rationale) } : {},
1362
1327
  ...readString(record.userId) ? { userId: readString(record.userId) } : {},
1363
1328
  ...readString(record.slOperator) ? { slOperator: readString(record.slOperator) } : {}
@@ -1365,11 +1330,7 @@ function mapOpinionHistoryEntriesFromGatewayData(payload) {
1365
1330
  }).sort((left, right) => left.t - right.t);
1366
1331
  }
1367
1332
  function normalizeModulateConfidenceInput(input) {
1368
- const opinion = "opinion" in input ? input.opinion : input.interpretation === "base_rate" ? opinionFromBaseRate(input.confidence) : input.interpretation === "dogmatic" ? opinionFromDogmatic(input.confidence, input.baseRate) : opinionFromProjected(
1369
- input.confidence,
1370
- input.uncertainty,
1371
- input.baseRate
1372
- );
1333
+ const opinion = input.opinion;
1373
1334
  return {
1374
1335
  belief: opinion.b,
1375
1336
  disbelief: opinion.d,
@@ -1377,20 +1338,23 @@ function normalizeModulateConfidenceInput(input) {
1377
1338
  baseRate: opinion.a,
1378
1339
  trigger: input.trigger,
1379
1340
  rationale: input.rationale,
1341
+ triggeringEvidenceId: input.triggeringEvidenceId,
1342
+ triggeringQuestionId: input.triggeringQuestionId,
1343
+ triggeringAnswerId: input.triggeringAnswerId,
1344
+ triggeringContradictionId: input.triggeringContradictionId,
1345
+ triggeringWorktreeId: input.triggeringWorktreeId,
1380
1346
  maxInlinePropagationTargets: input.maxInlinePropagationTargets
1381
1347
  };
1382
1348
  }
1383
1349
  function createBeliefsClient(config = {}) {
1384
1350
  const gateway = createGatewayRequestClient(config);
1385
- function requireBaseRate2(value) {
1351
+ function normalizeBaseRate(value) {
1386
1352
  const baseRate = readNumber(value);
1387
- if (baseRate === void 0) {
1388
- throw new Error("baseRate is required for belief creation.");
1389
- }
1390
- if (baseRate < 0 || baseRate > 1) {
1353
+ const normalized = baseRate ?? 0.5;
1354
+ if (normalized < 0 || normalized > 1) {
1391
1355
  throw new Error("baseRate must be within [0, 1].");
1392
1356
  }
1393
- return baseRate;
1357
+ return normalized;
1394
1358
  }
1395
1359
  const modulateConfidence = async (beliefId, input, idempotencyKey) => gateway.request({
1396
1360
  path: `/api/platform/v1/beliefs/${encodeURIComponent(beliefId)}/confidence`,
@@ -1409,7 +1373,7 @@ function createBeliefsClient(config = {}) {
1409
1373
  * Create a belief within a topic scope.
1410
1374
  */
1411
1375
  async createBelief(input, idempotencyKey) {
1412
- const baseRate = requireBaseRate2(input.baseRate);
1376
+ const baseRate = normalizeBaseRate(input.baseRate);
1413
1377
  return gateway.request({
1414
1378
  path: "/api/platform/v1/beliefs",
1415
1379
  method: "POST",
@@ -2505,11 +2469,7 @@ function createTopicsClient(config = {}) {
2505
2469
 
2506
2470
  // ../sdk/src/gatewayFacades.ts
2507
2471
  function normalizeBeliefConfidenceInput(input) {
2508
- const opinion = "opinion" in input ? input.opinion : input.interpretation === "base_rate" ? opinionFromBaseRate(input.confidence) : input.interpretation === "dogmatic" ? opinionFromDogmatic(input.confidence, input.baseRate) : opinionFromProjected(
2509
- input.confidence,
2510
- input.uncertainty,
2511
- input.baseRate
2512
- );
2472
+ const opinion = input.opinion;
2513
2473
  return {
2514
2474
  belief: opinion.b,
2515
2475
  disbelief: opinion.d,
@@ -2517,6 +2477,11 @@ function normalizeBeliefConfidenceInput(input) {
2517
2477
  baseRate: opinion.a,
2518
2478
  trigger: input.trigger,
2519
2479
  rationale: input.rationale,
2480
+ triggeringEvidenceId: input.triggeringEvidenceId,
2481
+ triggeringQuestionId: input.triggeringQuestionId,
2482
+ triggeringAnswerId: input.triggeringAnswerId,
2483
+ triggeringContradictionId: input.triggeringContradictionId,
2484
+ triggeringWorktreeId: input.triggeringWorktreeId,
2520
2485
  maxInlinePropagationTargets: input.maxInlinePropagationTargets
2521
2486
  };
2522
2487
  }
@@ -3256,6 +3221,18 @@ function createWorktreesFacade(config = {}) {
3256
3221
  async list(query) {
3257
3222
  return gateway.request({
3258
3223
  path: `/api/platform/v1/worktrees${toQueryString({
3224
+ topicId: query.topicId,
3225
+ status: query.status,
3226
+ groupBy: query.groupBy,
3227
+ lane: query.lane,
3228
+ campaign: query.campaign,
3229
+ limit: query.limit
3230
+ })}`
3231
+ });
3232
+ },
3233
+ async listCampaigns(query = {}) {
3234
+ return gateway.request({
3235
+ path: `/api/platform/v1/worktrees/campaigns${toQueryString({
3259
3236
  topicId: query.topicId,
3260
3237
  status: query.status,
3261
3238
  limit: query.limit
@@ -3278,10 +3255,10 @@ function createWorktreesFacade(config = {}) {
3278
3255
  objective: input.objective,
3279
3256
  hypothesis: input.hypothesis,
3280
3257
  rationale: input.rationale,
3281
- track: input.track,
3282
- trackPosition: input.trackPosition,
3283
- executionBand: input.executionBand,
3284
- executionOrder: input.executionOrder,
3258
+ campaign: input.campaign,
3259
+ lane: input.lane,
3260
+ laneOrderInCampaign: input.laneOrderInCampaign,
3261
+ orderInLane: input.orderInLane,
3285
3262
  dependsOn: input.dependsOn,
3286
3263
  blocks: input.blocks,
3287
3264
  gate: input.gate,
@@ -3947,6 +3924,7 @@ var CONTRACTS = {
3947
3924
  "list_active_sessions": { method: "POST", path: "/coordination/active-sessions", kind: "query", idempotent: false, surfaceIntent: "system" },
3948
3925
  "list_all_worktrees": { method: "GET", path: "/worktrees/all", kind: "query", idempotent: false, surfaceIntent: "mcp_workflow" },
3949
3926
  "list_beliefs": { method: "GET", path: "/beliefs", kind: "query", idempotent: false, surfaceIntent: "mcp_core" },
3927
+ "list_campaigns": { method: "GET", path: "/worktrees/campaigns", kind: "query", idempotent: false, surfaceIntent: "mcp_workflow" },
3950
3928
  "list_evidence": { method: "GET", path: "/evidence", kind: "query", idempotent: false, surfaceIntent: "mcp_core" },
3951
3929
  "list_lenses": { method: "GET", path: "/lenses", kind: "query", idempotent: false, surfaceIntent: "mcp_workflow" },
3952
3930
  "list_ontologies": { method: "GET", path: "/ontologies", kind: "query", idempotent: false, surfaceIntent: "mcp_workflow" },
@@ -4237,6 +4215,9 @@ function createFunctionSurfaceClient(config = {}) {
4237
4215
  listBeliefs(input = {}, idempotencyKey) {
4238
4216
  return execute("list_beliefs", input, idempotencyKey);
4239
4217
  },
4218
+ listCampaigns(input = {}, idempotencyKey) {
4219
+ return execute("list_campaigns", input, idempotencyKey);
4220
+ },
4240
4221
  listEvidence(input = {}, idempotencyKey) {
4241
4222
  return execute("list_evidence", input, idempotencyKey);
4242
4223
  },
@@ -5048,10 +5029,11 @@ function createWorkflowClient(config = {}) {
5048
5029
  async listWorktrees(query) {
5049
5030
  const normalized = normalizeTopicQuery(query);
5050
5031
  return gateway.request({
5051
- path: `/api/platform/v1/worktrees${toQueryString({
5032
+ path: `/api/platform/v1/worktrees/all${toQueryString({
5052
5033
  ...normalized,
5053
- track: query.track,
5054
- executionBand: query.executionBand
5034
+ groupBy: query.groupBy,
5035
+ lane: query.lane,
5036
+ campaign: query.campaign
5055
5037
  })}`
5056
5038
  }).then(
5057
5039
  (response) => mapGatewayData(
@@ -5070,8 +5052,9 @@ function createWorkflowClient(config = {}) {
5070
5052
  return gateway.request({
5071
5053
  path: `/api/platform/v1/worktrees${toQueryString({
5072
5054
  status: query.status,
5073
- track: query.track,
5074
- executionBand: query.executionBand,
5055
+ groupBy: query.groupBy,
5056
+ lane: query.lane,
5057
+ campaign: query.campaign,
5075
5058
  limit: query.limit
5076
5059
  })}`
5077
5060
  }).then(
@@ -5083,12 +5066,22 @@ function createWorkflowClient(config = {}) {
5083
5066
  );
5084
5067
  return {
5085
5068
  ...list,
5086
- ...record.tracks && typeof record.tracks === "object" && !Array.isArray(record.tracks) ? { tracks: record.tracks } : {},
5087
- ...record.bands && typeof record.bands === "object" && !Array.isArray(record.bands) ? { bands: record.bands } : {}
5069
+ ...record.lanes && typeof record.lanes === "object" && !Array.isArray(record.lanes) ? { lanes: record.lanes } : {},
5070
+ ...record.campaigns && typeof record.campaigns === "object" && !Array.isArray(record.campaigns) ? { campaigns: record.campaigns } : {}
5088
5071
  };
5089
5072
  })
5090
5073
  );
5091
5074
  },
5075
+ /**
5076
+ * List compact pipeline campaigns with nested lanes.
5077
+ */
5078
+ async listCampaigns(query = {}) {
5079
+ return gateway.request({
5080
+ path: `/api/platform/v1/worktrees/campaigns${toQueryString(
5081
+ normalizeTopicQuery(query)
5082
+ )}`
5083
+ });
5084
+ },
5092
5085
  /**
5093
5086
  * Create a workflow worktree.
5094
5087
  */
@@ -5414,13 +5407,11 @@ function requireText(args) {
5414
5407
  return text;
5415
5408
  }
5416
5409
  function requireBaseRate(args) {
5417
- if (typeof args.baseRate !== "number" || !Number.isFinite(args.baseRate)) {
5418
- throw new Error("baseRate is required.");
5419
- }
5420
- if (args.baseRate < 0 || args.baseRate > 1) {
5410
+ const baseRate = typeof args.baseRate === "number" && Number.isFinite(args.baseRate) ? args.baseRate : 0.5;
5411
+ if (baseRate < 0 || baseRate > 1) {
5421
5412
  throw new Error("baseRate must be within [0, 1].");
5422
5413
  }
5423
- return args.baseRate;
5414
+ return baseRate;
5424
5415
  }
5425
5416
  function exposeGatewayData(response) {
5426
5417
  return Object.assign({}, response, response.data);
@@ -5538,9 +5529,13 @@ function createLucernClient(config = {}) {
5538
5529
  if (!text) {
5539
5530
  throw new Error("text is required");
5540
5531
  }
5532
+ const rationale = args.rationale ?? args.supports?.reasoning;
5533
+ if (!rationale) {
5534
+ throw new Error("rationale is required");
5535
+ }
5541
5536
  const metadata = {
5542
5537
  ...args.metadata ?? {},
5543
- ...args.supports?.reasoning ? { rationale: args.supports.reasoning } : {}
5538
+ rationale
5544
5539
  };
5545
5540
  return evidenceFacade.create({
5546
5541
  topicId: resolveTopicId(args),
@@ -5548,6 +5543,7 @@ function createLucernClient(config = {}) {
5548
5543
  source: args.source ?? args.sourceUrl,
5549
5544
  targetId: args.targetId ?? args.supports?.nodeId,
5550
5545
  weight: args.weight ?? args.supports?.weight,
5546
+ rationale,
5551
5547
  metadata: Object.keys(metadata).length > 0 ? metadata : void 0,
5552
5548
  title: args.title,
5553
5549
  content: args.content,
@@ -6378,7 +6374,10 @@ function createLucernClient(config = {}) {
6378
6374
  beliefIds: input.beliefIds,
6379
6375
  autoShape: input.autoShape,
6380
6376
  domainPackId: input.domainPackId,
6381
- executionOrder: input.executionOrder,
6377
+ campaign: input.campaign,
6378
+ lane: input.lane,
6379
+ laneOrderInCampaign: input.laneOrderInCampaign,
6380
+ orderInLane: input.orderInLane,
6382
6381
  dependsOn: input.dependsOn,
6383
6382
  blocks: input.blocks,
6384
6383
  gate: input.gate,
@@ -6397,7 +6396,10 @@ function createLucernClient(config = {}) {
6397
6396
  beliefIds: input.beliefIds,
6398
6397
  autoShape: input.autoShape,
6399
6398
  domainPackId: input.domainPackId,
6400
- executionOrder: input.executionOrder,
6399
+ campaign: input.campaign,
6400
+ lane: input.lane,
6401
+ laneOrderInCampaign: input.laneOrderInCampaign,
6402
+ orderInLane: input.orderInLane,
6401
6403
  dependsOn: input.dependsOn,
6402
6404
  blocks: input.blocks,
6403
6405
  gate: input.gate,
@@ -6425,10 +6427,10 @@ function createLucernClient(config = {}) {
6425
6427
  return worktreesFacade.update({
6426
6428
  id: typeof input.worktreeId === "string" ? input.worktreeId : "",
6427
6429
  hypothesis: typeof input.hypothesis === "string" ? input.hypothesis : void 0,
6428
- track: typeof input.track === "string" ? input.track : void 0,
6429
- trackPosition: typeof input.trackPosition === "number" ? input.trackPosition : void 0,
6430
- executionBand: typeof input.executionBand === "number" ? input.executionBand : void 0,
6431
- executionOrder: typeof input.executionOrder === "number" ? input.executionOrder : void 0,
6430
+ campaign: typeof input.campaign === "number" ? input.campaign : void 0,
6431
+ lane: typeof input.lane === "string" ? input.lane : void 0,
6432
+ laneOrderInCampaign: typeof input.laneOrderInCampaign === "number" ? input.laneOrderInCampaign : void 0,
6433
+ orderInLane: typeof input.orderInLane === "number" ? input.orderInLane : void 0,
6432
6434
  dependsOn,
6433
6435
  blocks,
6434
6436
  gate: typeof input.gate === "string" ? input.gate : void 0
@@ -7107,7 +7109,7 @@ var LENS_PERSPECTIVE_TYPES = [
7107
7109
  // ../contracts/src/tool-contracts.ts
7108
7110
  var CREATE_BELIEF = {
7109
7111
  name: "create_belief",
7110
- description: "Commit a new belief (knowledge unit) to the reasoning graph. Like `git commit` \u2014 creates an atomic, traceable knowledge object with a mandatory prior. Creation stores the vacuous opinion `(0, 0, 1, a)`; use modulate_confidence to record the first evidential update.",
7112
+ description: "Commit a new belief (knowledge unit) to the reasoning graph. Like `git commit` \u2014 creates an atomic, traceable knowledge object with a prior. Creation stores the vacuous opinion `(0, 0, 1, a)`; use modulate_confidence to record the first evidential update.",
7111
7113
  parameters: {
7112
7114
  canonicalText: {
7113
7115
  type: "string",
@@ -7119,7 +7121,7 @@ var CREATE_BELIEF = {
7119
7121
  },
7120
7122
  baseRate: {
7121
7123
  type: "number",
7122
- description: "Required prior probability used to seed the vacuous opinion `(0, 0, 1, a)` at creation time."
7124
+ description: "Prior probability used to seed the vacuous opinion `(0, 0, 1, a)` at creation time. Defaults to 0.5 when omitted."
7123
7125
  },
7124
7126
  beliefType: {
7125
7127
  type: "string",
@@ -7130,7 +7132,7 @@ var CREATE_BELIEF = {
7130
7132
  description: "Optional extra metadata merged into the node (e.g., { codeAnchors: ['path/to/file.ts'] } for coding intelligence)"
7131
7133
  }
7132
7134
  },
7133
- required: ["canonicalText", "baseRate"],
7135
+ required: ["canonicalText"],
7134
7136
  response: {
7135
7137
  description: "The created canonical belief record",
7136
7138
  fields: {
@@ -7193,7 +7195,7 @@ var REFINE_BELIEF = {
7193
7195
  };
7194
7196
  var MODULATE_CONFIDENCE = {
7195
7197
  name: "modulate_confidence",
7196
- description: "Record a confidence change for a belief. Like `git commit` to the credence log \u2014 an atomic, append-only write. Each modulation is a new entry in the history, not an overwrite. Scoring happens via merge; this tool records the individual data points. Pass the full subjective-logic tuple (`belief`, `disbelief`, `uncertainty`, `baseRate`) directly. If a caller only has a scalar probability, use `@lucern/sdk` helpers `opinionFromBaseRate`, `opinionFromDogmatic`, or `opinionFromProjected` to name the intended interpretation before calling this tool. Triggers: evidence_added, evidence_removed, contradiction_detected, contradiction_resolved, agent_assessment, worktree_outcome, worktree_completed, fusion, discount, deduction, manual, decay.",
7198
+ description: "Record a confidence change for a belief. Like `git commit` to the credence log \u2014 an atomic, append-only write. Each modulation is a new entry in the history, not an overwrite. Scoring happens via merge; this tool records the individual data points. Pass the full subjective-logic tuple (`belief`, `disbelief`, `uncertainty`, `baseRate`) directly. If a caller only has a scalar probability, use `@lucern/sdk` helpers `opinionFromBaseRate`, `opinionFromDogmatic`, or `opinionFromProjected` to name the intended interpretation before calling this tool. Every modulation must cite a truth-bearing artifact: triggeringEvidenceId, triggeringQuestionId, triggeringAnswerId, triggeringContradictionId, or triggeringWorktreeId. Triggers: evidence_added, evidence_removed, contradiction_detected, contradiction_resolved, agent_assessment, worktree_outcome, worktree_completed, fusion, discount, deduction.",
7197
7199
  parameters: {
7198
7200
  nodeId: { type: "string", description: "The belief to score" },
7199
7201
  belief: {
@@ -7212,9 +7214,9 @@ var MODULATE_CONFIDENCE = {
7212
7214
  type: "number",
7213
7215
  description: "Subjective-logic base rate `a` in [0, 1]. Required for tuple payloads."
7214
7216
  },
7215
- confidence: {
7216
- type: "number",
7217
- description: "Deprecated scalar confidence value in [0, 1]. Scalar-only payloads are rejected as AMBIGUOUS_SCALAR."
7217
+ worktreeId: {
7218
+ type: "string",
7219
+ description: "Completed worktree that tested this belief when confidence policy requires merge-backed scoring."
7218
7220
  },
7219
7221
  trigger: {
7220
7222
  type: "string",
@@ -7229,17 +7231,43 @@ var MODULATE_CONFIDENCE = {
7229
7231
  "worktree_completed",
7230
7232
  "fusion",
7231
7233
  "discount",
7232
- "deduction",
7233
- "manual",
7234
- "decay"
7234
+ "deduction"
7235
7235
  ]
7236
7236
  },
7237
+ triggeringEvidenceId: {
7238
+ type: "string",
7239
+ description: "Evidence node that caused an evidence-triggered modulation"
7240
+ },
7241
+ triggeringQuestionId: {
7242
+ type: "string",
7243
+ description: "Answered question whose resolution supports this modulation"
7244
+ },
7245
+ triggeringAnswerId: {
7246
+ type: "string",
7247
+ description: "Answer node whose content supports this modulation"
7248
+ },
7249
+ triggeringContradictionId: {
7250
+ type: "string",
7251
+ description: "Contradiction record that caused a contradiction-triggered modulation"
7252
+ },
7253
+ triggeringWorktreeId: {
7254
+ type: "string",
7255
+ description: "Completed worktree whose outcome caused a worktree-triggered modulation"
7256
+ },
7237
7257
  rationale: {
7238
7258
  type: "string",
7239
7259
  description: "Human-readable explanation of why confidence changed"
7240
7260
  }
7241
7261
  },
7242
- required: ["nodeId", "trigger", "rationale"],
7262
+ required: [
7263
+ "nodeId",
7264
+ "belief",
7265
+ "disbelief",
7266
+ "uncertainty",
7267
+ "baseRate",
7268
+ "trigger",
7269
+ "rationale"
7270
+ ],
7243
7271
  response: {
7244
7272
  description: "Confidence modulation result",
7245
7273
  fields: {
@@ -7433,7 +7461,7 @@ var ADD_EVIDENCE = {
7433
7461
  description: "Optional extra metadata merged into the node (e.g., { codeAnchors: ['path/to/file.ts'], failedApproach: true } for coding intelligence)"
7434
7462
  }
7435
7463
  },
7436
- required: ["canonicalText", "targetNodeId"],
7464
+ required: ["canonicalText", "targetNodeId", "reasoning"],
7437
7465
  response: {
7438
7466
  description: "The created evidence node and its edge",
7439
7467
  fields: {
@@ -7514,9 +7542,21 @@ var ADD_WORKTREE = {
7514
7542
  type: "string",
7515
7543
  description: "Optional domain pack whose shaping hooks should influence generated questions and tasks"
7516
7544
  },
7517
- executionOrder: {
7545
+ campaign: {
7546
+ type: "number",
7547
+ description: "Top-level pipeline campaign number. Campaigns define the outer execution slice."
7548
+ },
7549
+ lane: {
7550
+ type: "string",
7551
+ description: "GitButler-aligned workstream lane name inside the campaign."
7552
+ },
7553
+ laneOrderInCampaign: {
7554
+ type: "number",
7555
+ description: "Ordering for this lane within its campaign."
7556
+ },
7557
+ orderInLane: {
7518
7558
  type: "number",
7519
- description: "Global execution order for this worktree"
7559
+ description: "Position of this worktree inside its lane."
7520
7560
  },
7521
7561
  dependsOn: {
7522
7562
  type: "array",
@@ -8174,6 +8214,10 @@ var CREATE_EVIDENCE = {
8174
8214
  type: "object",
8175
8215
  description: "Optional metadata merged into the canonical evidence node"
8176
8216
  },
8217
+ rationale: {
8218
+ type: "string",
8219
+ description: "Why this evidence should enter the reasoning graph"
8220
+ },
8177
8221
  title: { type: "string", description: "Optional short title" },
8178
8222
  content: { type: "string", description: "Optional long-form content" },
8179
8223
  contentType: {
@@ -8182,7 +8226,7 @@ var CREATE_EVIDENCE = {
8182
8226
  },
8183
8227
  kind: { type: "string", description: "Optional evidence kind" }
8184
8228
  },
8185
- required: ["text"],
8229
+ required: ["text", "rationale"],
8186
8230
  response: {
8187
8231
  description: "The created canonical evidence record",
8188
8232
  fields: {
@@ -8230,7 +8274,7 @@ var LIST_EVIDENCE = {
8230
8274
  limit: { type: "number", description: "Max results" },
8231
8275
  cursor: { type: "string", description: "Pagination cursor" }
8232
8276
  },
8233
- required: [],
8277
+ required: ["topicId"],
8234
8278
  response: {
8235
8279
  description: "Canonical evidence page",
8236
8280
  fields: {
@@ -8415,6 +8459,7 @@ var ANSWER_QUESTION = {
8415
8459
  description: "Answer a question with optional evidence links. Like `git commit` on the question thread \u2014 records the answer and closes the loop with a canonical answered state.",
8416
8460
  parameters: {
8417
8461
  id: { type: "string", description: "Canonical question ID" },
8462
+ topicId: { type: "string", description: "Topic scope for the answer" },
8418
8463
  text: { type: "string", description: "Answer text" },
8419
8464
  confidence: {
8420
8465
  type: "string",
@@ -8427,7 +8472,7 @@ var ANSWER_QUESTION = {
8427
8472
  },
8428
8473
  rationale: { type: "string", description: "Why this answer is credible" }
8429
8474
  },
8430
- required: ["id", "text"],
8475
+ required: ["id", "topicId", "text"],
8431
8476
  response: {
8432
8477
  description: "Answer result",
8433
8478
  fields: {
@@ -8646,6 +8691,10 @@ var LIST_BELIEFS = {
8646
8691
  minConfidence: {
8647
8692
  type: "number",
8648
8693
  description: "Minimum confidence threshold"
8694
+ },
8695
+ limit: {
8696
+ type: "number",
8697
+ description: "Maximum results"
8649
8698
  }
8650
8699
  },
8651
8700
  required: ["topicId"],
@@ -8662,20 +8711,37 @@ var LIST_BELIEFS = {
8662
8711
  };
8663
8712
  var LIST_WORKTREES = {
8664
8713
  name: "list_worktrees",
8665
- description: "List all worktrees for a topic. Like `git worktree list` \u2014 shows active and completed investigation branches with their phase, status, and belief counts.",
8714
+ description: "List all worktrees for a topic. Like `git worktree list` \u2014 shows active and completed investigation branches with lifecycle phase, pipeline campaign/lane, status, and belief counts.",
8666
8715
  parameters: {
8667
8716
  topicId: { type: "string", description: "Topic scope" },
8668
8717
  status: {
8669
8718
  type: "string",
8670
8719
  description: "Filter: active, merged, abandoned",
8671
8720
  enum: ["active", "merged", "abandoned"]
8721
+ },
8722
+ groupBy: {
8723
+ type: "string",
8724
+ description: "Optional grouping mode for the response.",
8725
+ enum: ["campaign", "lane", "flat"]
8726
+ },
8727
+ lane: {
8728
+ type: "string",
8729
+ description: "Filter by GitButler-aligned lane name."
8730
+ },
8731
+ campaign: {
8732
+ type: "number",
8733
+ description: "Filter by top-level pipeline campaign number."
8734
+ },
8735
+ limit: {
8736
+ type: "number",
8737
+ description: "Maximum results to return."
8672
8738
  }
8673
8739
  },
8674
8740
  required: ["topicId"],
8675
8741
  response: {
8676
- description: "Worktrees with phase, status, belief count, and creation time",
8742
+ description: "Worktrees with lifecycle phase, campaign, lane, status, belief count, and creation time",
8677
8743
  fields: {
8678
- worktrees: "array \u2014 { worktreeId, title, phase, status, beliefCount, createdAt }"
8744
+ worktrees: "array \u2014 { worktreeId, title, phase, campaign, lane, laneOrderInCampaign, orderInLane, status, beliefCount, createdAt }"
8679
8745
  }
8680
8746
  },
8681
8747
  ownerModule: "workflow-engine",
@@ -8684,7 +8750,7 @@ var LIST_WORKTREES = {
8684
8750
  };
8685
8751
  var LIST_ALL_WORKTREES = {
8686
8752
  name: "list_all_worktrees",
8687
- description: "List ALL worktrees across ALL topics in one query. No topic scope required. Like `git worktree list --all` \u2014 returns the complete pipeline inventory with track, trackPosition, executionBand, dependencies, and status. Supports filtering by status, track, and executionBand. This is the PM's primary pipeline query \u2014 one call, full picture.",
8753
+ description: "List ALL worktrees across ALL topics in one query. No topic scope required. Like `git worktree list --all` \u2014 returns the complete pipeline inventory with campaign, lane, lane order, dependencies, and status. Supports filtering by status, lane, and campaign. This is the PM's primary pipeline query \u2014 one call, full picture.",
8688
8754
  parameters: {
8689
8755
  status: {
8690
8756
  type: "string",
@@ -8702,13 +8768,18 @@ var LIST_ALL_WORKTREES = {
8702
8768
  "dismissed"
8703
8769
  ]
8704
8770
  },
8705
- track: {
8771
+ lane: {
8706
8772
  type: "string",
8707
- description: "Filter by track name (e.g., 'ontology', 'tc-scope', 'control-plane', 'dev-portal', 'mcp-sdk-parity')"
8773
+ description: "Filter by lane name (e.g., 'ontology', 'tc-scope', 'control-plane', 'dev-portal', 'mcp-sdk-parity')"
8708
8774
  },
8709
- executionBand: {
8775
+ campaign: {
8710
8776
  type: "number",
8711
- description: "Filter by execution band number (e.g., 1, 2, 3). Returns only worktrees in that parallel execution group."
8777
+ description: "Filter by campaign number (e.g., 1, 2, 3). Returns only worktrees in that campaign."
8778
+ },
8779
+ groupBy: {
8780
+ type: "string",
8781
+ description: "Optional grouping mode for the response.",
8782
+ enum: ["campaign", "lane", "flat"]
8712
8783
  },
8713
8784
  limit: {
8714
8785
  type: "number",
@@ -8719,10 +8790,39 @@ var LIST_ALL_WORKTREES = {
8719
8790
  response: {
8720
8791
  description: "All worktrees across all topics with full pipeline metadata",
8721
8792
  fields: {
8722
- worktrees: "array \u2014 { worktreeId, title, topicId, topicName, phase, status, hypothesis, track, trackPosition, executionBand, executionOrder, dependsOn, blocks, gate, createdAt }",
8793
+ worktrees: "array \u2014 { worktreeId, title, topicId, topicName, phase, status, hypothesis, campaign, lane, laneOrderInCampaign, orderInLane, dependsOn, blocks, gate, createdAt }",
8723
8794
  total: "number \u2014 total count after filtering",
8724
- tracks: "object \u2014 { trackName: count } summary of worktrees per track",
8725
- bands: "object \u2014 { bandNumber: count } summary of worktrees per execution band"
8795
+ lanes: "object \u2014 { laneName: count } summary of worktrees per lane",
8796
+ campaigns: "object \u2014 { campaignNumber: count } summary of worktrees per campaign"
8797
+ }
8798
+ },
8799
+ ownerModule: "workflow-engine",
8800
+ ontologyPrimitive: "worktree",
8801
+ tier: "showcase"
8802
+ };
8803
+ var LIST_CAMPAIGNS = {
8804
+ name: "list_campaigns",
8805
+ description: "List compact pipeline campaigns with their nested lanes. Use this to see the top-level campaign > lane > worktree shape without pulling the full worktree inventory.",
8806
+ parameters: {
8807
+ topicId: {
8808
+ type: "string",
8809
+ description: "Optional topic scope."
8810
+ },
8811
+ status: {
8812
+ type: "string",
8813
+ description: "Optional worktree status filter before grouping campaigns and lanes."
8814
+ },
8815
+ limit: {
8816
+ type: "number",
8817
+ description: "Maximum worktrees to scan before grouping."
8818
+ }
8819
+ },
8820
+ required: [],
8821
+ response: {
8822
+ description: "Pipeline campaigns with nested lane summaries.",
8823
+ fields: {
8824
+ campaigns: "array \u2014 { campaign, lanes: [{ lane, laneOrderInCampaign, worktreeCount, activeCount, readyCount, blockedCount, completedCount, nextWorktree }] }",
8825
+ totalWorktrees: "number \u2014 total worktrees scanned after filtering"
8726
8826
  }
8727
8827
  },
8728
8828
  ownerModule: "workflow-engine",
@@ -8785,16 +8885,28 @@ var UPDATE_WORKTREE_TARGETS = {
8785
8885
  };
8786
8886
  var UPDATE_WORKTREE_METADATA = {
8787
8887
  name: "update_worktree_metadata",
8788
- description: "Update worktree sequencing metadata \u2014 execution order, dependencies, blocking relations, and gates. Like `git config` for a worktree \u2014 sets the scheduling and dependency metadata that determines when this worktree can activate relative to others. Use to backfill or correct sequencing data.",
8888
+ description: "Update worktree sequencing metadata \u2014 campaign, lane, dependencies, blocking relations, and gates. Like `git config` for a worktree \u2014 sets the scheduling and dependency metadata that determines when this worktree can activate relative to others. Use to backfill or correct sequencing data.",
8789
8889
  parameters: {
8790
8890
  worktreeId: { type: "string", description: "The worktree to update" },
8791
8891
  hypothesis: {
8792
8892
  type: "string",
8793
8893
  description: "Testable claim this worktree investigates"
8794
8894
  },
8795
- executionOrder: {
8895
+ campaign: {
8896
+ type: "number",
8897
+ description: "Top-level pipeline campaign number."
8898
+ },
8899
+ lane: {
8900
+ type: "string",
8901
+ description: "GitButler-aligned workstream lane name inside the campaign."
8902
+ },
8903
+ laneOrderInCampaign: {
8904
+ type: "number",
8905
+ description: "Ordering for this lane within the campaign."
8906
+ },
8907
+ orderInLane: {
8796
8908
  type: "number",
8797
- description: "Global execution order (1 = first, higher = later)"
8909
+ description: "Position of this worktree inside its lane."
8798
8910
  },
8799
8911
  dependsOn: {
8800
8912
  type: "array",
@@ -8832,18 +8944,6 @@ var UPDATE_WORKTREE_METADATA = {
8832
8944
  type: "object",
8833
8945
  description: "Calibrated auto-fix policy controlling dry-run vs safe execution, per-run action caps, and permitted mutation tiers."
8834
8946
  },
8835
- track: {
8836
- type: "string",
8837
- description: "Parallel workstream name (e.g., 'ontology', 'tc-scope', 'control-plane', 'dev-portal', 'mcp-sdk-parity', 'execution-program'). Groups worktrees into named lanes for pipeline visualization and PM analysis."
8838
- },
8839
- trackPosition: {
8840
- type: "number",
8841
- description: "Position within the track (1-indexed). E.g., TC-A=1, TC-B=2, TC-C=3 within the 'tc-scope' track."
8842
- },
8843
- executionBand: {
8844
- type: "number",
8845
- description: "Parallel execution band number. All worktrees in the same band can run simultaneously. Band 2 = OE-B + TC-A, Band 3 = TC-B + 11D-R + S2-13A, etc."
8846
- },
8847
8947
  status: {
8848
8948
  type: "string",
8849
8949
  description: "Override the worktree status. Use for lifecycle transitions like marking a worktree superseded, long-term, or as a raw idea.",
@@ -9213,6 +9313,10 @@ var LIST_TASKS = {
9213
9313
  type: "string",
9214
9314
  description: "Filter to tasks linked to this worktree"
9215
9315
  },
9316
+ worktreeId: {
9317
+ type: "string",
9318
+ description: "Alias for linkedWorktreeId"
9319
+ },
9216
9320
  status: {
9217
9321
  type: "string",
9218
9322
  description: "Filter by status: todo, in_progress, blocked, done",
@@ -9300,7 +9404,7 @@ var GET_TOPIC = {
9300
9404
  description: "Legacy alias for topicId"
9301
9405
  }
9302
9406
  },
9303
- required: [],
9407
+ required: ["topicId"],
9304
9408
  response: {
9305
9409
  description: "Single topic record",
9306
9410
  fields: {
@@ -9655,7 +9759,7 @@ var GET_ONTOLOGY = {
9655
9759
  description: "Tenant scope for key lookup. Omit for platform-level."
9656
9760
  }
9657
9761
  },
9658
- required: [],
9762
+ required: ["id"],
9659
9763
  response: {
9660
9764
  description: "Ontology definition with latest published version",
9661
9765
  fields: {
@@ -9722,7 +9826,7 @@ var MATCH_ENTITY_TYPE = {
9722
9826
  description: "Optional maximum number of ranked matches to return"
9723
9827
  }
9724
9828
  },
9725
- required: ["text"],
9829
+ required: ["text", "ontologyId"],
9726
9830
  response: {
9727
9831
  description: "Ranked ontology entity type matches",
9728
9832
  fields: {
@@ -9976,7 +10080,7 @@ var RECORD_SCOPE_LEARNING = {
9976
10080
  };
9977
10081
  var PIPELINE_SNAPSHOT = {
9978
10082
  name: "pipeline_snapshot",
9979
- description: "Summarize a topic's worktree pipeline in band-and-lane form. Like `git status --short` for Lucern execution \u2014 returns the hinge worktree, next planned wave, blockers, critical path, superseded work, and graph hygiene debt.",
10083
+ description: "Summarize a topic's worktree pipeline in campaign-and-lane form. Like `git status --short` for Lucern execution \u2014 returns the hinge worktree, next planned wave, blockers, critical path, superseded work, and graph hygiene debt.",
9980
10084
  parameters: {
9981
10085
  topicId: { type: "string", description: "Topic scope ID" }
9982
10086
  },
@@ -9986,14 +10090,14 @@ var PIPELINE_SNAPSHOT = {
9986
10090
  fields: {
9987
10091
  topicId: "string",
9988
10092
  topicName: "string",
9989
- currentBand: "number | null",
9990
- nextBand: "number | null",
10093
+ currentCampaign: "number | null",
10094
+ nextCampaign: "number | null",
9991
10095
  activeWorktrees: "array \u2014 current hinge worktree(s)",
9992
- nextWave: "array \u2014 worktrees in the next planned band",
10096
+ nextWave: "array \u2014 worktrees in the next planned campaign",
9993
10097
  readyNow: "array \u2014 planning worktrees with dependencies completed",
9994
10098
  blockedBy: "array \u2014 grouped blockers",
9995
10099
  criticalPath: "array \u2014 ordered incomplete worktree chain",
9996
- bands: "array \u2014 incomplete worktrees grouped by executionBand",
10100
+ campaigns: "array \u2014 incomplete worktrees grouped by campaign",
9997
10101
  superseded: "array \u2014 worktrees marked superseded or not for activation",
9998
10102
  graphHygiene: "object \u2014 untargeted and taskless worktree debt",
9999
10103
  riskQuestions: "array \u2014 critical/high open questions",
@@ -10582,6 +10686,7 @@ var MCP_TOOL_CONTRACTS = {
10582
10686
  list_beliefs: LIST_BELIEFS,
10583
10687
  list_worktrees: LIST_WORKTREES,
10584
10688
  list_all_worktrees: LIST_ALL_WORKTREES,
10689
+ list_campaigns: LIST_CAMPAIGNS,
10585
10690
  activate_worktree: ACTIVATE_WORKTREE,
10586
10691
  update_worktree_targets: UPDATE_WORKTREE_TARGETS,
10587
10692
  update_worktree_metadata: UPDATE_WORKTREE_METADATA,
@@ -10765,6 +10870,7 @@ var MCP_WORKFLOW_PLATFORM_OPERATION_NAMES = [
10765
10870
  "activate_worktree",
10766
10871
  "list_worktrees",
10767
10872
  "list_all_worktrees",
10873
+ "list_campaigns",
10768
10874
  "update_worktree_targets",
10769
10875
  "update_worktree_metadata",
10770
10876
  "create_task",
@@ -11243,7 +11349,15 @@ function createBeliefHandlers(context) {
11243
11349
  const result = await beliefs.modulateConfidence(nodeId, {
11244
11350
  opinion,
11245
11351
  trigger: readString2(params, "trigger", { required: true }),
11246
- rationale: readString2(params, "rationale", { required: true })
11352
+ rationale: readString2(params, "rationale", { required: true }),
11353
+ triggeringEvidenceId: readString2(params, "triggeringEvidenceId"),
11354
+ triggeringQuestionId: readString2(params, "triggeringQuestionId"),
11355
+ triggeringAnswerId: readString2(params, "triggeringAnswerId"),
11356
+ triggeringContradictionId: readString2(
11357
+ params,
11358
+ "triggeringContradictionId"
11359
+ ),
11360
+ triggeringWorktreeId: readString2(params, "triggeringWorktreeId")
11247
11361
  });
11248
11362
  return {
11249
11363
  nodeId,
@@ -11891,6 +12005,28 @@ defineTable({
11891
12005
  { kind: "index", name: "by_createdAt", columns: ["createdAt"] }
11892
12006
  ]
11893
12007
  });
12008
+ defineTable({
12009
+ name: "neo4jSyncQueue",
12010
+ component: "kernel",
12011
+ category: "infra",
12012
+ shape: z.object({
12013
+ "entityType": z.enum(["node", "edge"]),
12014
+ "entityId": z.string(),
12015
+ "operation": z.enum(["upsert", "delete"]),
12016
+ "attempts": z.number(),
12017
+ "maxAttempts": z.number(),
12018
+ "lastAttemptAt": z.number().optional(),
12019
+ "lastError": z.string().optional(),
12020
+ "status": z.enum(["pending", "in_progress", "failed", "succeeded"]),
12021
+ "createdAt": z.number(),
12022
+ "updatedAt": z.number()
12023
+ }),
12024
+ indices: [
12025
+ { kind: "index", name: "by_status", columns: ["status"] },
12026
+ { kind: "index", name: "by_entity", columns: ["entityType", "entityId"] },
12027
+ { kind: "index", name: "by_status_attempts", columns: ["status", "attempts"] }
12028
+ ]
12029
+ });
11894
12030
  defineTable({
11895
12031
  name: "backgroundJobRuns",
11896
12032
  component: "kernel",
@@ -11960,9 +12096,9 @@ defineTable({
11960
12096
  category: "epistemic",
11961
12097
  shape: z.object({
11962
12098
  "beliefId": z.string(),
11963
- "belief": z.number().optional(),
11964
- "disbelief": z.number().optional(),
11965
- "uncertainty": z.number().optional(),
12099
+ "belief": z.number(),
12100
+ "disbelief": z.number(),
12101
+ "uncertainty": z.number(),
11966
12102
  "baseRate": z.number(),
11967
12103
  "slOperator": z.string().optional(),
11968
12104
  "confidence": z.number(),
@@ -11971,10 +12107,12 @@ defineTable({
11971
12107
  "certainty": z.number().optional(),
11972
12108
  "assessedAt": z.number(),
11973
12109
  "assessedBy": z.string(),
11974
- "trigger": z.enum(["initial", "evidence_added", "evidence_removed", "contradiction_detected", "contradiction_resolved", "manual", "decay", "propagation", "agent_assessment", "worktree_outcome", "worktree_completed", "fusion", "discount", "deduction", "backfill_synthetic"]),
12110
+ "trigger": z.enum(["initial", "evidence_added", "evidence_removed", "contradiction_detected", "contradiction_resolved", "propagation", "agent_assessment", "worktree_outcome", "worktree_completed", "fusion", "discount", "deduction", "backfill_synthetic"]),
11975
12111
  "rationale": z.string().optional(),
11976
12112
  "triggeringEvidenceId": z.string().optional(),
11977
12113
  "triggeringEvidenceIds": z.array(z.string()).optional(),
12114
+ "triggeringQuestionId": z.string().optional(),
12115
+ "triggeringAnswerId": z.string().optional(),
11978
12116
  "triggeringContradictionId": idOf("contradictions").optional(),
11979
12117
  "triggeringWorktreeId": z.string().optional(),
11980
12118
  "triggeringAgentId": z.string().optional(),
@@ -12657,7 +12795,7 @@ defineTable({
12657
12795
  "credentialRef": z.string(),
12658
12796
  "tenantId": idOf("tenants"),
12659
12797
  "target": z.enum(["kernelDeployment", "appDeployment"]),
12660
- "environment": z.enum(["dev", "prod"]),
12798
+ "environment": z.enum(["dev", "staging", "prod"]),
12661
12799
  "encryptedDeployKey": z.string(),
12662
12800
  "encryptionVersion": z.string(),
12663
12801
  "keyFingerprint": z.string(),
@@ -15326,13 +15464,13 @@ defineTable({
15326
15464
  "rationale": z.string().optional(),
15327
15465
  "confidenceImpact": z.enum(["high", "medium", "low"]).optional(),
15328
15466
  "hypothesis": z.string().optional(),
15329
- "executionOrder": z.number().optional(),
15330
15467
  "dependsOn": z.array(idOf("worktrees")).optional(),
15331
15468
  "blocks": z.array(idOf("worktrees")).optional(),
15332
15469
  "gate": z.string().optional(),
15333
- "track": z.string().optional(),
15334
- "trackPosition": z.number().optional(),
15335
- "executionBand": z.number().optional(),
15470
+ "campaign": z.number().optional(),
15471
+ "lane": z.string().optional(),
15472
+ "laneOrderInCampaign": z.number().optional(),
15473
+ "orderInLane": z.number().optional(),
15336
15474
  "startDate": z.number(),
15337
15475
  "endDate": z.number(),
15338
15476
  "durationWeeks": z.number(),
@@ -15580,11 +15718,471 @@ defineTable({
15580
15718
  { kind: "index", name: "by_topicId_index", columns: ["topicId", "index"] },
15581
15719
  { kind: "index", name: "by_worktreeType", columns: ["topicId", "worktreeType"] },
15582
15720
  { kind: "index", name: "by_topicId_priority", columns: ["topicId", "priority"] },
15721
+ { kind: "index", name: "by_topicId_campaign_lane_order", columns: ["topicId", "campaign", "laneOrderInCampaign", "orderInLane"] },
15722
+ { kind: "index", name: "by_topicId_lane_order", columns: ["topicId", "lane", "orderInLane"] },
15583
15723
  { kind: "index", name: "by_topicId_branch", columns: ["topicId", "targetBranch"] },
15584
15724
  { kind: "index", name: "by_topicId_scope", columns: ["topicId", "worktreeScope"] }
15585
15725
  ]
15586
15726
  });
15727
+ z.object({
15728
+ manifestVersion: z.string(),
15729
+ componentName: z.enum(["kernel", "identity"]),
15730
+ tier: z.enum(["K", "I"]),
15731
+ packageVersion: z.string(),
15732
+ tables: z.array(
15733
+ z.object({
15734
+ name: z.string(),
15735
+ fields: z.array(
15736
+ z.object({
15737
+ name: z.string(),
15738
+ type: z.string(),
15739
+ optional: z.boolean(),
15740
+ validator: z.string().optional()
15741
+ })
15742
+ )
15743
+ })
15744
+ )
15745
+ });
15746
+ var SL_EPSILON = 1e-9;
15747
+ z.object({
15748
+ belief: z.number(),
15749
+ disbelief: z.number(),
15750
+ uncertainty: z.number(),
15751
+ baseRate: z.number()
15752
+ }).refine(
15753
+ (o) => Math.abs(o.belief + o.disbelief + o.uncertainty - 1) < SL_EPSILON,
15754
+ {
15755
+ message: "SL invariant b+d+u=1 violated at API boundary"
15756
+ }
15757
+ );
15758
+ var EpistemicNodeTypeSchema = z.enum([
15759
+ "belief",
15760
+ "evidence",
15761
+ "question",
15762
+ "answer",
15763
+ "topic",
15764
+ "edge",
15765
+ "ontology",
15766
+ "lens",
15767
+ "contradiction"
15768
+ ]);
15769
+ var GraphRefSchema = z.discriminatedUnion("kind", [
15770
+ z.object({
15771
+ kind: z.literal("epistemic_node"),
15772
+ nodeId: z.string(),
15773
+ nodeType: EpistemicNodeTypeSchema
15774
+ }),
15775
+ z.object({
15776
+ kind: z.literal("external_belief"),
15777
+ ref: z.object({
15778
+ tenantId: z.string(),
15779
+ beliefId: z.string()
15780
+ })
15781
+ })
15782
+ ]);
15783
+ var graphRefKind = z.enum(["epistemic_node", "external_belief"]);
15784
+ var EdgePolicyEntrySchema = z.object({
15785
+ edgeType: z.string(),
15786
+ fromKinds: z.array(graphRefKind),
15787
+ fromNodeTypes: z.array(EpistemicNodeTypeSchema).optional(),
15788
+ toKinds: z.array(graphRefKind),
15789
+ toNodeTypes: z.array(EpistemicNodeTypeSchema).optional(),
15790
+ description: z.string()
15791
+ });
15792
+ z.object({
15793
+ manifestVersion: z.literal("1.0.0"),
15794
+ policies: z.array(EdgePolicyEntrySchema)
15795
+ });
15796
+ function findEdgePolicy(manifest, edgeType) {
15797
+ return manifest.policies.find((policy) => policy.edgeType === edgeType);
15798
+ }
15799
+ function nodeTypeAllowed(allowed, ref) {
15800
+ return ref.kind !== "epistemic_node" || !allowed || allowed.includes(ref.nodeType);
15801
+ }
15802
+ function assertEdgePolicyAllowed(manifest, edgeType, from, to) {
15803
+ const policy = findEdgePolicy(manifest, edgeType);
15804
+ const allowed = Boolean(policy) && policy.fromKinds.includes(from.kind) && policy.toKinds.includes(to.kind) && nodeTypeAllowed(policy.fromNodeTypes, from) && nodeTypeAllowed(policy.toNodeTypes, to);
15805
+ if (!allowed) {
15806
+ const error = new Error(
15807
+ `Edge policy violation for ${edgeType}: ${from.kind} -> ${to.kind}`
15808
+ );
15809
+ error.code = "POLICY_VIOLATION";
15810
+ error.details = { code: "POLICY_VIOLATION", edgeType, from, to };
15811
+ throw error;
15812
+ }
15813
+ }
15814
+
15815
+ // ../contracts/src/manifests/edge-policy-manifest.data.ts
15816
+ var edgePolicyManifest = {
15817
+ policies: [
15818
+ {
15819
+ edgeType: "evidence_derived_from_evidence",
15820
+ fromKinds: ["epistemic_node"],
15821
+ fromNodeTypes: ["evidence"],
15822
+ toKinds: ["epistemic_node"],
15823
+ toNodeTypes: ["evidence"],
15824
+ description: "Evidence E2 was synthesized from evidence E1 by a transformation. Provides chain-of-evidence lineage."
15825
+ },
15826
+ {
15827
+ edgeType: "evidence_supports_belief",
15828
+ fromKinds: ["epistemic_node"],
15829
+ fromNodeTypes: ["evidence"],
15830
+ toKinds: ["epistemic_node"],
15831
+ toNodeTypes: ["belief"],
15832
+ description: "Existing link_evidence_to_belief semantics promoted to the create_edge policy source."
15833
+ },
15834
+ {
15835
+ edgeType: "evidence_supports_question",
15836
+ fromKinds: ["epistemic_node"],
15837
+ fromNodeTypes: ["evidence"],
15838
+ toKinds: ["epistemic_node"],
15839
+ toNodeTypes: ["question"],
15840
+ description: "Existing link_evidence_to_question semantics promoted to the create_edge policy source."
15841
+ }
15842
+ ]
15843
+ };
15844
+ z.object({
15845
+ manifestVersion: z.literal("1.0.0"),
15846
+ rules: z.array(
15847
+ z.object({
15848
+ invariant: z.string(),
15849
+ description: z.string(),
15850
+ checker: z.enum(["ast", "manifest", "runtime"]),
15851
+ severity: z.enum(["block_publish", "block_pr", "warn"])
15852
+ })
15853
+ )
15854
+ });
15855
+
15856
+ // ../contracts/src/projections/projection-dsl.ts
15857
+ function defineProjection(def) {
15858
+ return def;
15859
+ }
15860
+
15861
+ // ../contracts/src/projections/create-evidence.projection.ts
15862
+ var jsonRecordSchema = z.record(z.unknown());
15863
+ var createEvidenceInputSchemaBase = z.object({
15864
+ projectId: z.string().optional(),
15865
+ topicId: z.string().optional(),
15866
+ text: z.string().optional(),
15867
+ canonicalText: z.string().optional(),
15868
+ title: z.string().optional(),
15869
+ content: z.string().optional(),
15870
+ contentType: z.string().optional(),
15871
+ kind: z.string().optional(),
15872
+ tags: z.array(z.string()).optional(),
15873
+ source: z.string().optional(),
15874
+ sourceUrl: z.string().optional(),
15875
+ sourceType: z.string().optional(),
15876
+ externalSourceType: z.string().optional(),
15877
+ sourceQuestionId: z.string().optional(),
15878
+ methodology: z.string().optional(),
15879
+ informationAsymmetry: z.string().optional(),
15880
+ sourceDescription: z.string().optional(),
15881
+ targetId: z.string().optional(),
15882
+ targetNodeId: z.string().optional(),
15883
+ linkedBeliefNodeId: z.string().optional(),
15884
+ evidenceRelation: z.enum(["supports", "contradicts", "neutral"]).optional(),
15885
+ confidence: z.number().optional(),
15886
+ weight: z.number().optional(),
15887
+ reasoning: z.string().optional(),
15888
+ rationale: z.string(),
15889
+ metadata: jsonRecordSchema.optional(),
15890
+ trustedBypassAccessCheck: z.boolean().optional()
15891
+ }).passthrough();
15892
+ var createEvidenceInputSchema = createEvidenceInputSchemaBase.refine(
15893
+ (input) => Boolean(input.text ?? input.canonicalText),
15894
+ {
15895
+ message: "create_evidence requires text",
15896
+ path: ["text"]
15897
+ }
15898
+ );
15899
+ function compactRecord(input) {
15900
+ return Object.fromEntries(
15901
+ Object.entries(input).filter(([, value]) => value !== void 0)
15902
+ );
15903
+ }
15904
+ function recordValue(value) {
15905
+ return value && typeof value === "object" && !Array.isArray(value) ? value : {};
15906
+ }
15907
+ var createEvidenceProjection = defineProjection({
15908
+ contractName: "create_evidence",
15909
+ inputSchema: createEvidenceInputSchema,
15910
+ project: (input) => {
15911
+ const text = input.text ?? input.canonicalText;
15912
+ const weight = typeof input.weight === "number" ? input.weight : void 0;
15913
+ return compactRecord({
15914
+ projectId: input.projectId,
15915
+ topicId: input.topicId,
15916
+ text,
15917
+ title: input.title ?? text,
15918
+ content: input.content ?? text,
15919
+ contentType: input.contentType,
15920
+ kind: input.kind,
15921
+ tags: input.tags,
15922
+ sourceType: input.sourceType,
15923
+ externalSourceType: input.externalSourceType,
15924
+ sourceUrl: input.sourceUrl ?? input.source,
15925
+ sourceQuestionId: input.sourceQuestionId,
15926
+ methodology: input.methodology,
15927
+ informationAsymmetry: input.informationAsymmetry,
15928
+ sourceDescription: input.sourceDescription,
15929
+ metadata: compactRecord({
15930
+ ...recordValue(input.metadata),
15931
+ source: input.source,
15932
+ targetId: input.targetId,
15933
+ targetNodeId: input.targetNodeId,
15934
+ weight,
15935
+ reasoning: input.reasoning,
15936
+ rationale: input.rationale
15937
+ }),
15938
+ linkedBeliefNodeId: input.linkedBeliefNodeId ?? input.targetNodeId ?? input.targetId,
15939
+ evidenceRelation: input.evidenceRelation ?? (weight === void 0 ? void 0 : weight < 0 ? "contradicts" : "supports"),
15940
+ confidence: input.confidence ?? (weight === void 0 ? void 0 : Math.min(1, Math.max(0, Math.abs(weight)))),
15941
+ rationale: input.rationale,
15942
+ trustedBypassAccessCheck: input.trustedBypassAccessCheck ?? true
15943
+ });
15944
+ },
15945
+ convexArgsValidator: v.object({
15946
+ projectId: v.optional(v.string()),
15947
+ topicId: v.optional(v.string()),
15948
+ text: v.string(),
15949
+ title: v.optional(v.string()),
15950
+ content: v.optional(v.string()),
15951
+ contentType: v.optional(v.string()),
15952
+ kind: v.optional(v.string()),
15953
+ tags: v.optional(v.array(v.string())),
15954
+ sourceType: v.optional(v.string()),
15955
+ externalSourceType: v.optional(v.string()),
15956
+ sourceUrl: v.optional(v.string()),
15957
+ sourceQuestionId: v.optional(v.string()),
15958
+ methodology: v.optional(v.string()),
15959
+ informationAsymmetry: v.optional(v.string()),
15960
+ sourceDescription: v.optional(v.string()),
15961
+ metadata: v.optional(v.record(v.string(), v.any())),
15962
+ linkedBeliefNodeId: v.optional(v.string()),
15963
+ evidenceRelation: v.optional(
15964
+ v.union(
15965
+ v.literal("supports"),
15966
+ v.literal("contradicts"),
15967
+ v.literal("neutral")
15968
+ )
15969
+ ),
15970
+ confidence: v.optional(v.number()),
15971
+ rationale: v.string(),
15972
+ trustedBypassAccessCheck: v.optional(v.boolean())
15973
+ })
15974
+ });
15975
+ var beliefStatusSchema = z.enum(["active", "superseded", "archived", "unscored", "scored"]).optional().describe("Filter by belief lifecycle or scoring status");
15976
+ var listBeliefsInputSchema = z.object({
15977
+ topicId: z.string().describe("Topic scope"),
15978
+ worktreeId: z.string().optional().describe("Filter to worktree scope"),
15979
+ status: beliefStatusSchema,
15980
+ minConfidence: z.number().optional().describe("Minimum confidence threshold"),
15981
+ limit: z.number().optional().describe("Maximum results"),
15982
+ includeEdgeAssociated: z.boolean().optional().describe("Include beliefs associated to the topic through edges")
15983
+ });
15984
+ function kernelStatus(status) {
15985
+ return status === "active" || status === "superseded" || status === "archived" ? status : void 0;
15986
+ }
15987
+ function compactRecord2(input) {
15988
+ return Object.fromEntries(
15989
+ Object.entries(input).filter(([, value]) => value !== void 0)
15990
+ );
15991
+ }
15992
+ var listBeliefsProjection = defineProjection({
15993
+ contractName: "list_beliefs",
15994
+ inputSchema: listBeliefsInputSchema,
15995
+ project: (input) => compactRecord2({
15996
+ topicId: input.topicId,
15997
+ status: kernelStatus(input.status),
15998
+ limit: input.limit,
15999
+ includeEdgeAssociated: input.includeEdgeAssociated
16000
+ }),
16001
+ convexArgsValidator: v.object({
16002
+ topicId: v.string(),
16003
+ status: v.optional(
16004
+ v.union(
16005
+ v.literal("active"),
16006
+ v.literal("superseded"),
16007
+ v.literal("archived")
16008
+ )
16009
+ ),
16010
+ limit: v.optional(v.number()),
16011
+ includeEdgeAssociated: v.optional(v.boolean())
16012
+ })
16013
+ });
16014
+ var taskStatusSchema = z.enum(["todo", "in_progress", "blocked", "done"]).optional().describe("Filter by task status");
16015
+ var listTasksInputSchema = z.object({
16016
+ topicId: z.string().describe("Topic scope"),
16017
+ worktreeId: z.string().optional().describe("Alias for linkedWorktreeId"),
16018
+ linkedWorktreeId: z.string().optional().describe("Filter to tasks linked to this worktree"),
16019
+ status: taskStatusSchema,
16020
+ limit: z.number().optional().describe("Maximum results")
16021
+ });
16022
+ function compactRecord3(input) {
16023
+ return Object.fromEntries(
16024
+ Object.entries(input).filter(([, value]) => value !== void 0)
16025
+ );
16026
+ }
16027
+ var listTasksProjection = defineProjection({
16028
+ contractName: "list_tasks",
16029
+ inputSchema: listTasksInputSchema,
16030
+ project: (input) => compactRecord3({
16031
+ topicId: input.topicId,
16032
+ status: input.status,
16033
+ userId: void 0,
16034
+ limit: input.limit,
16035
+ linkedWorktreeId: input.linkedWorktreeId ?? input.worktreeId
16036
+ }),
16037
+ convexArgsValidator: v.object({
16038
+ topicId: v.string(),
16039
+ status: v.optional(
16040
+ v.union(
16041
+ v.literal("todo"),
16042
+ v.literal("in_progress"),
16043
+ v.literal("blocked"),
16044
+ v.literal("done")
16045
+ )
16046
+ ),
16047
+ limit: v.optional(v.number()),
16048
+ linkedWorktreeId: v.optional(v.string())
16049
+ })
16050
+ });
16051
+ var confidenceTriggerSchema = z.enum([
16052
+ "evidence_added",
16053
+ "evidence_removed",
16054
+ "contradiction_resolved",
16055
+ "agent_assessment",
16056
+ "worktree_outcome",
16057
+ "worktree_completed",
16058
+ "contradiction_detected",
16059
+ "answer_recorded",
16060
+ "fusion",
16061
+ "discount",
16062
+ "deduction",
16063
+ "backfill_synthetic"
16064
+ ]);
16065
+ var provenanceSchema = z.object({
16066
+ evidence: z.string().optional(),
16067
+ question: z.string().optional(),
16068
+ answer: z.string().optional(),
16069
+ contradiction: z.string().optional(),
16070
+ worktree: z.string().optional()
16071
+ });
16072
+ var slOpinionProjectionSchema = z.object({
16073
+ belief: z.number(),
16074
+ disbelief: z.number(),
16075
+ uncertainty: z.number(),
16076
+ baseRate: z.number()
16077
+ });
16078
+ var modulateConfidenceInputObjectSchema = z.object({
16079
+ nodeId: z.string().optional(),
16080
+ beliefNodeId: z.string().optional(),
16081
+ worktreeId: z.string().optional(),
16082
+ opinion: slOpinionProjectionSchema.optional(),
16083
+ belief: z.number().optional(),
16084
+ disbelief: z.number().optional(),
16085
+ uncertainty: z.number().optional(),
16086
+ baseRate: z.number().optional(),
16087
+ trigger: confidenceTriggerSchema,
16088
+ provenance: provenanceSchema.optional(),
16089
+ triggeringEvidenceId: z.string().optional(),
16090
+ triggeringQuestionId: z.string().optional(),
16091
+ triggeringAnswerId: z.string().optional(),
16092
+ triggeringContradictionId: z.string().optional(),
16093
+ triggeringWorktreeId: z.string().optional(),
16094
+ rationale: z.string(),
16095
+ trustedBypassAccessCheck: z.boolean().optional()
16096
+ });
16097
+ var modulateConfidenceInputSchema = modulateConfidenceInputObjectSchema.superRefine((input, ctx) => {
16098
+ if (hasProvenance(input)) {
16099
+ return;
16100
+ }
16101
+ ctx.addIssue({
16102
+ code: z.ZodIssueCode.custom,
16103
+ message: "modulate_confidence requires evidence, question, answer, contradiction, or worktree provenance",
16104
+ path: ["provenance"]
16105
+ });
16106
+ });
16107
+ var modulateConfidenceProjection = defineProjection({
16108
+ contractName: "modulate_confidence",
16109
+ inputSchema: modulateConfidenceInputSchema,
16110
+ project: (input) => {
16111
+ const nodeId = input.beliefNodeId ?? input.nodeId;
16112
+ if (!nodeId) {
16113
+ throw new Error("modulate_confidence requires beliefNodeId or nodeId");
16114
+ }
16115
+ const opinion = input.opinion ?? {
16116
+ belief: requireNumber(input.belief, "belief"),
16117
+ disbelief: requireNumber(input.disbelief, "disbelief"),
16118
+ uncertainty: requireNumber(input.uncertainty, "uncertainty"),
16119
+ baseRate: requireNumber(input.baseRate, "baseRate")
16120
+ };
16121
+ assertProvenance(input);
16122
+ return {
16123
+ nodeId,
16124
+ worktreeId: input.worktreeId,
16125
+ belief: opinion.belief,
16126
+ disbelief: opinion.disbelief,
16127
+ uncertainty: opinion.uncertainty,
16128
+ baseRate: opinion.baseRate,
16129
+ trigger: input.trigger === "answer_recorded" ? "agent_assessment" : input.trigger,
16130
+ triggeringEvidenceId: input.provenance?.evidence ?? input.triggeringEvidenceId,
16131
+ triggeringQuestionId: input.provenance?.question ?? input.triggeringQuestionId,
16132
+ triggeringAnswerId: input.provenance?.answer ?? input.triggeringAnswerId,
16133
+ triggeringContradictionId: input.provenance?.contradiction ?? input.triggeringContradictionId,
16134
+ triggeringWorktreeId: input.provenance?.worktree ?? input.triggeringWorktreeId,
16135
+ rationale: input.rationale,
16136
+ trustedBypassAccessCheck: input.trustedBypassAccessCheck ?? true
16137
+ };
16138
+ },
16139
+ convexArgsValidator: v.object({
16140
+ nodeId: v.string(),
16141
+ worktreeId: v.optional(v.string()),
16142
+ belief: v.number(),
16143
+ disbelief: v.number(),
16144
+ uncertainty: v.number(),
16145
+ baseRate: v.number(),
16146
+ trigger: v.union(
16147
+ v.literal("evidence_added"),
16148
+ v.literal("evidence_removed"),
16149
+ v.literal("worktree_completed"),
16150
+ v.literal("contradiction_detected"),
16151
+ v.literal("contradiction_resolved"),
16152
+ v.literal("agent_assessment"),
16153
+ v.literal("worktree_outcome"),
16154
+ v.literal("fusion"),
16155
+ v.literal("discount"),
16156
+ v.literal("deduction"),
16157
+ v.literal("backfill_synthetic")
16158
+ ),
16159
+ triggeringEvidenceId: v.optional(v.string()),
16160
+ triggeringQuestionId: v.optional(v.string()),
16161
+ triggeringAnswerId: v.optional(v.string()),
16162
+ triggeringContradictionId: v.optional(v.string()),
16163
+ triggeringWorktreeId: v.optional(v.string()),
16164
+ rationale: v.string(),
16165
+ trustedBypassAccessCheck: v.optional(v.boolean())
16166
+ })
16167
+ });
16168
+ function requireNumber(value, field) {
16169
+ if (value === void 0) {
16170
+ throw new Error(`modulate_confidence requires ${field}`);
16171
+ }
16172
+ return value;
16173
+ }
16174
+ function assertProvenance(input) {
16175
+ if (!hasProvenance(input)) {
16176
+ throw new Error(
16177
+ "modulate_confidence requires evidence, question, answer, contradiction, or worktree provenance"
16178
+ );
16179
+ }
16180
+ }
16181
+ function hasProvenance(input) {
16182
+ return input.trigger === "backfill_synthetic" || Boolean(input.provenance && Object.values(input.provenance).some(Boolean)) || Boolean(input.triggeringEvidenceId) || Boolean(input.triggeringQuestionId) || Boolean(input.triggeringAnswerId) || Boolean(input.triggeringContradictionId) || Boolean(input.triggeringWorktreeId);
16183
+ }
15587
16184
  var jsonObjectSchema = z.record(z.unknown());
16185
+ var sdkSessionIdSchema = z.string().optional();
15588
16186
  function mcpContractShape(contract) {
15589
16187
  const required = new Set(contract.required);
15590
16188
  return Object.fromEntries(
@@ -15619,32 +16217,65 @@ function argsSchemaFromMcpContract(contract) {
15619
16217
  return z.object(mcpContractShape(contract));
15620
16218
  }
15621
16219
  function inputSchemaFromMcpContract(contract) {
15622
- return argsSchemaFromMcpContract(contract).passthrough();
16220
+ return withInternalSurfaceFields(argsSchemaFromMcpContract(contract));
15623
16221
  }
15624
- function getObjectShape(schema) {
15625
- const shape = typeof schema._def.shape === "function" ? schema._def.shape() : schema._def.shape;
15626
- return shape;
16222
+ function withInternalSurfaceFields(schema) {
16223
+ return schema.extend({ __sdkSessionId: sdkSessionIdSchema }).strict();
15627
16224
  }
15628
- function unwrapMcpParameterSchema(schema) {
16225
+ function normalizeInputSchema(schema) {
16226
+ if (schema instanceof z.ZodObject) {
16227
+ return withInternalSurfaceFields(schema);
16228
+ }
16229
+ return schema;
16230
+ }
16231
+ function unwrapObjectSchema(schema) {
15629
16232
  let current = schema;
15630
- let required = true;
15631
- let description = schema.description;
15632
16233
  while (true) {
15633
- description ??= current.description;
15634
16234
  switch (current._def.typeName) {
15635
- case z.ZodFirstPartyTypeKind.ZodOptional:
15636
- case z.ZodFirstPartyTypeKind.ZodDefault:
15637
- required = false;
15638
- current = current._def.innerType;
15639
- continue;
15640
- case z.ZodFirstPartyTypeKind.ZodNullable:
15641
- current = current._def.innerType;
16235
+ case z.ZodFirstPartyTypeKind.ZodEffects:
16236
+ current = current._def.schema;
15642
16237
  continue;
15643
16238
  case z.ZodFirstPartyTypeKind.ZodBranded:
15644
16239
  current = current._def.type;
15645
16240
  continue;
15646
16241
  default:
15647
- return { schema: current, required, description: description ?? current.description };
16242
+ return current instanceof z.ZodObject ? current : void 0;
16243
+ }
16244
+ }
16245
+ }
16246
+ function getObjectShape(schema) {
16247
+ const objectSchema = unwrapObjectSchema(schema);
16248
+ if (!objectSchema) {
16249
+ throw new Error(
16250
+ `Expected a Zod object schema, received ${schema._def.typeName}.`
16251
+ );
16252
+ }
16253
+ const shape = typeof objectSchema._def.shape === "function" ? objectSchema._def.shape() : objectSchema._def.shape;
16254
+ return shape;
16255
+ }
16256
+ function unwrapMcpParameterSchema(schema) {
16257
+ let current = schema;
16258
+ let required = true;
16259
+ let description = schema.description;
16260
+ while (true) {
16261
+ description ??= current.description;
16262
+ switch (current._def.typeName) {
16263
+ case z.ZodFirstPartyTypeKind.ZodOptional:
16264
+ case z.ZodFirstPartyTypeKind.ZodDefault:
16265
+ required = false;
16266
+ current = current._def.innerType;
16267
+ continue;
16268
+ case z.ZodFirstPartyTypeKind.ZodNullable:
16269
+ current = current._def.innerType;
16270
+ continue;
16271
+ case z.ZodFirstPartyTypeKind.ZodBranded:
16272
+ current = current._def.type;
16273
+ continue;
16274
+ case z.ZodFirstPartyTypeKind.ZodEffects:
16275
+ current = current._def.schema;
16276
+ continue;
16277
+ default:
16278
+ return { schema: current, required, description: description ?? current.description };
15648
16279
  }
15649
16280
  }
15650
16281
  }
@@ -15662,6 +16293,7 @@ function mcpParameterFromZod(fieldName, schema, contractName) {
15662
16293
  return { parameter: { type: "array", description }, required };
15663
16294
  case z.ZodFirstPartyTypeKind.ZodObject:
15664
16295
  case z.ZodFirstPartyTypeKind.ZodRecord:
16296
+ case z.ZodFirstPartyTypeKind.ZodDiscriminatedUnion:
15665
16297
  return { parameter: { type: "object", description }, required };
15666
16298
  case z.ZodFirstPartyTypeKind.ZodEnum:
15667
16299
  return {
@@ -15723,6 +16355,14 @@ function withCreatedBy(input, context) {
15723
16355
  createdBy: typeof input.createdBy === "string" ? input.createdBy : authUserId(context)
15724
16356
  };
15725
16357
  }
16358
+ function compactRecord4(input) {
16359
+ return Object.fromEntries(
16360
+ Object.entries(input).filter(([, value]) => value !== void 0)
16361
+ );
16362
+ }
16363
+ function recordValue2(value) {
16364
+ return value && typeof value === "object" && !Array.isArray(value) ? value : {};
16365
+ }
15726
16366
  function surfaceMcpContract(name) {
15727
16367
  const contract = MCP_TOOL_CONTRACTS[name];
15728
16368
  if (!contract) {
@@ -15767,7 +16407,9 @@ function surfaceContract(args) {
15767
16407
  const canonicalArgs = args.args ?? argsSchemaFromMcpContract(baseMcp);
15768
16408
  const mcp = args.args ? mcpContractFromArgsSchema(baseMcp, canonicalArgs, args.name) : baseMcp;
15769
16409
  const canonicalReturns = args.returns ?? jsonObjectSchema;
15770
- const input = args.input ?? inputSchemaFromMcpContract(mcp);
16410
+ const input = normalizeInputSchema(
16411
+ args.input ?? inputSchemaFromMcpContract(mcp)
16412
+ );
15771
16413
  const output = args.output ?? canonicalReturns;
15772
16414
  return defineFunctionContract({
15773
16415
  name: args.name,
@@ -15829,20 +16471,26 @@ function assertSurfaceCoverage(contracts) {
15829
16471
 
15830
16472
  // ../contracts/src/function-registry/context.ts
15831
16473
  var observationInput = (input, context) => withUserId(
15832
- {
15833
- ...input,
16474
+ compactRecord4({
16475
+ projectId: input.projectId,
16476
+ topicId: input.topicId,
15834
16477
  text: input.text ?? input.summary,
15835
16478
  title: input.title ?? input.summary,
15836
16479
  content: input.content ?? input.summary,
16480
+ contentType: input.contentType,
15837
16481
  kind: input.kind ?? input.observationType ?? "observation",
15838
- sourceType: input.sourceType ?? input.source ?? "agent",
15839
- metadata: {
15840
- ...input.metadata && typeof input.metadata === "object" && !Array.isArray(input.metadata) ? input.metadata : {},
16482
+ tags: input.tags,
16483
+ sourceType: input.sourceType,
16484
+ externalSourceType: input.externalSourceType,
16485
+ sourceUrl: input.sourceUrl,
16486
+ metadata: compactRecord4({
16487
+ ...recordValue2(input.metadata),
15841
16488
  observationType: input.observationType,
15842
16489
  source: input.source
15843
- },
16490
+ }),
16491
+ rationale: input.rationale ?? input.reasoning ?? input.summary ?? input.text ?? "Recorded observation",
15844
16492
  trustedBypassAccessCheck: input.trustedBypassAccessCheck ?? true
15845
- },
16493
+ }),
15846
16494
  context
15847
16495
  );
15848
16496
  var contextContracts = [
@@ -15894,7 +16542,13 @@ var contextContracts = [
15894
16542
  convex: {
15895
16543
  module: "evidence",
15896
16544
  functionName: "getByTopic",
15897
- kind: "query"
16545
+ kind: "query",
16546
+ inputProjection: (input) => compactRecord4({
16547
+ topicId: input.topicId,
16548
+ limit: input.limit,
16549
+ status: input.status,
16550
+ userId: input.userId
16551
+ })
15898
16552
  }
15899
16553
  })
15900
16554
  ];
@@ -15960,42 +16614,62 @@ var identityContracts = [
15960
16614
  ];
15961
16615
 
15962
16616
  // ../contracts/src/function-registry/beliefs.ts
15963
- var withBeliefId = (input) => ({
15964
- ...input,
16617
+ var beliefLookupInput = (input) => compactRecord4({
15965
16618
  nodeId: input.nodeId ?? input.id ?? input.beliefId,
15966
- beliefId: input.beliefId ?? input.id ?? input.nodeId
16619
+ beliefId: input.beliefId
15967
16620
  });
15968
- var createBeliefInput = (input, context) => withUserId(
15969
- {
15970
- ...input,
15971
- formulation: input.formulation ?? input.canonicalText,
15972
- baseRate: input.baseRate ?? 0.5,
15973
- trustedBypassAccessCheck: input.trustedBypassAccessCheck ?? true
15974
- },
15975
- context
15976
- );
16621
+ var beliefNodeInput = (input) => compactRecord4({
16622
+ nodeId: input.nodeId ?? input.id ?? input.beliefId
16623
+ });
16624
+ var beliefTopicInput = (input) => {
16625
+ const parsed = listBeliefsProjection.inputSchema.safeParse(input);
16626
+ if (!parsed.success) {
16627
+ throw new Error(
16628
+ `list_beliefs projection input rejected: ${parsed.error.message}`
16629
+ );
16630
+ }
16631
+ return compactRecord4(listBeliefsProjection.project(parsed.data));
16632
+ };
16633
+ var createBeliefInput = (input, context) => {
16634
+ return withUserId(
16635
+ compactRecord4({
16636
+ projectId: input.projectId,
16637
+ topicId: input.topicId,
16638
+ formulation: input.formulation ?? input.canonicalText,
16639
+ beliefType: input.beliefType,
16640
+ rationale: input.rationale,
16641
+ pillar: input.pillar,
16642
+ worktreeId: input.worktreeId,
16643
+ sourceBeliefIds: input.sourceBeliefIds,
16644
+ sourceType: input.sourceType,
16645
+ reversibility: input.reversibility,
16646
+ predictionMeta: input.predictionMeta,
16647
+ baseRate: input.baseRate ?? 0.5,
16648
+ metadata: input.metadata,
16649
+ trustedBypassAccessCheck: input.trustedBypassAccessCheck ?? true
16650
+ }),
16651
+ context
16652
+ );
16653
+ };
15977
16654
  var forkBeliefInput = (input, context) => withUserId(
15978
- {
15979
- ...input,
16655
+ compactRecord4({
15980
16656
  parentNodeId: input.parentNodeId ?? input.nodeId ?? input.id,
16657
+ newFormulation: input.newFormulation,
16658
+ forkReason: input.forkReason,
16659
+ rationale: input.rationale,
15981
16660
  trustedBypassAccessCheck: input.trustedBypassAccessCheck ?? true
15982
- },
16661
+ }),
15983
16662
  context
15984
16663
  );
15985
16664
  var confidenceInput = (input, context) => {
15986
- const confidence = typeof input.confidence === "number" ? input.confidence : void 0;
15987
- const belief = typeof input.belief === "number" ? input.belief : confidence ?? 0.5;
15988
- const disbelief = typeof input.disbelief === "number" ? input.disbelief : 0;
15989
- const uncertainty = typeof input.uncertainty === "number" ? input.uncertainty : Math.max(0, 1 - belief - disbelief);
16665
+ const parsed = modulateConfidenceProjection.inputSchema.safeParse(input);
16666
+ if (!parsed.success) {
16667
+ throw new Error(
16668
+ `modulate_confidence projection input rejected: ${parsed.error.message}`
16669
+ );
16670
+ }
15990
16671
  return withUserId(
15991
- {
15992
- ...input,
15993
- belief,
15994
- disbelief,
15995
- uncertainty,
15996
- baseRate: input.baseRate ?? 0.5,
15997
- trustedBypassAccessCheck: input.trustedBypassAccessCheck ?? true
15998
- },
16672
+ compactRecord4(modulateConfidenceProjection.project(parsed.data)),
15999
16673
  context
16000
16674
  );
16001
16675
  };
@@ -16030,7 +16704,7 @@ var beliefsContracts = [
16030
16704
  module: "beliefs",
16031
16705
  functionName: "getById",
16032
16706
  kind: "query",
16033
- inputProjection: withBeliefId
16707
+ inputProjection: beliefLookupInput
16034
16708
  }
16035
16709
  }),
16036
16710
  surfaceContract({
@@ -16046,8 +16720,10 @@ var beliefsContracts = [
16046
16720
  convex: {
16047
16721
  module: "beliefs",
16048
16722
  functionName: "getByTopic",
16049
- kind: "query"
16050
- }
16723
+ kind: "query",
16724
+ inputProjection: beliefTopicInput
16725
+ },
16726
+ args: listBeliefsInputSchema
16051
16727
  }),
16052
16728
  surfaceContract({
16053
16729
  name: "refine_belief",
@@ -16065,7 +16741,7 @@ var beliefsContracts = [
16065
16741
  kind: "mutation",
16066
16742
  inputProjection: (input, context) => withUserId(
16067
16743
  {
16068
- ...withBeliefId(input),
16744
+ ...beliefLookupInput(input),
16069
16745
  trustedBypassAccessCheck: input.trustedBypassAccessCheck ?? true
16070
16746
  },
16071
16747
  context
@@ -16086,7 +16762,8 @@ var beliefsContracts = [
16086
16762
  functionName: "modulateConfidence",
16087
16763
  kind: "mutation",
16088
16764
  inputProjection: confidenceInput
16089
- }
16765
+ },
16766
+ args: modulateConfidenceInputSchema
16090
16767
  }),
16091
16768
  surfaceContract({
16092
16769
  name: "fork_belief",
@@ -16119,10 +16796,10 @@ var beliefsContracts = [
16119
16796
  functionName: "archive",
16120
16797
  kind: "mutation",
16121
16798
  inputProjection: (input, context) => withUserId(
16122
- {
16123
- ...withBeliefId(input),
16799
+ compactRecord4({
16800
+ ...beliefNodeInput(input),
16124
16801
  reason: input.reason ?? input.rationale
16125
- },
16802
+ }),
16126
16803
  context
16127
16804
  )
16128
16805
  }
@@ -16140,10 +16817,12 @@ var beliefsContracts = [
16140
16817
  module: "nodes",
16141
16818
  functionName: "search",
16142
16819
  kind: "query",
16143
- inputProjection: (input) => ({
16144
- ...input,
16820
+ inputProjection: (input) => compactRecord4({
16145
16821
  searchQuery: input.searchQuery ?? input.query,
16146
- nodeType: "belief"
16822
+ projectId: input.projectId,
16823
+ topicId: input.topicId,
16824
+ nodeType: "belief",
16825
+ limit: input.limit
16147
16826
  })
16148
16827
  }
16149
16828
  }),
@@ -16160,7 +16839,7 @@ var beliefsContracts = [
16160
16839
  module: "beliefs",
16161
16840
  functionName: "getConfidenceHistory",
16162
16841
  kind: "query",
16163
- inputProjection: withBeliefId
16842
+ inputProjection: beliefNodeInput
16164
16843
  }
16165
16844
  }),
16166
16845
  surfaceContract({
@@ -16177,25 +16856,69 @@ var beliefsContracts = [
16177
16856
  module: "beliefs",
16178
16857
  functionName: "getConfidenceHistory",
16179
16858
  kind: "query",
16180
- inputProjection: withBeliefId
16859
+ inputProjection: beliefNodeInput
16181
16860
  }
16182
16861
  })
16183
16862
  ];
16184
16863
 
16185
16864
  // ../contracts/src/function-registry/evidence.ts
16186
- var evidenceIdInput = (input) => ({
16187
- ...input,
16188
- evidenceId: input.evidenceId ?? input.id ?? input.nodeId,
16865
+ var evidenceIdInput = (input) => compactRecord4({
16866
+ evidenceId: input.evidenceId,
16867
+ insightId: input.insightId,
16189
16868
  nodeId: input.nodeId ?? input.id ?? input.evidenceId
16190
16869
  });
16191
- var createEvidenceInput = (input, context) => withUserId(
16192
- {
16193
- ...input,
16194
- title: input.title ?? input.text,
16195
- content: input.content ?? input.text,
16196
- sourceType: input.sourceType ?? input.source ?? "agent",
16870
+ var evidenceTopicInput = (input) => compactRecord4({
16871
+ topicId: input.topicId,
16872
+ status: input.status,
16873
+ userId: input.userId,
16874
+ limit: input.limit
16875
+ });
16876
+ var createEvidenceInput = (input, context) => {
16877
+ const parsed = createEvidenceProjection.inputSchema.safeParse(input);
16878
+ if (!parsed.success) {
16879
+ throw new Error(
16880
+ `create_evidence projection input rejected: ${parsed.error.message}`
16881
+ );
16882
+ }
16883
+ return withUserId(
16884
+ compactRecord4(createEvidenceProjection.project(parsed.data)),
16885
+ context
16886
+ );
16887
+ };
16888
+ var linkEvidenceToBeliefEdgeInput = (input, context) => withCreatedBy(
16889
+ compactRecord4({
16890
+ fromNodeId: input.insightId ?? input.evidenceNodeId ?? input.evidenceId,
16891
+ toNodeId: input.beliefNodeId ?? input.beliefId ?? input.targetId,
16892
+ edgeType: "evidence_supports_belief",
16893
+ globalId: input.globalId ?? `edge:${String(
16894
+ input.insightId ?? input.evidenceNodeId ?? input.evidenceId
16895
+ )}:${String(
16896
+ input.beliefNodeId ?? input.beliefId ?? input.targetId
16897
+ )}:evidence_supports_belief`,
16898
+ weight: typeof input.weight === "number" ? input.weight : input.type === "contradicting" ? -1 : 1,
16899
+ context: input.rationale ?? input.context,
16900
+ skipLayerValidation: true,
16901
+ topicId: input.topicId,
16197
16902
  trustedBypassAccessCheck: input.trustedBypassAccessCheck ?? true
16198
- },
16903
+ }),
16904
+ context
16905
+ );
16906
+ var linkEvidenceToQuestionEdgeInput = (input, context) => withCreatedBy(
16907
+ compactRecord4({
16908
+ fromNodeId: input.insightId ?? input.evidenceNodeId ?? input.evidenceId,
16909
+ toNodeId: input.questionId ?? input.questionNodeId ?? input.targetId,
16910
+ edgeType: "evidence_supports_question",
16911
+ globalId: input.globalId ?? `edge:${String(
16912
+ input.insightId ?? input.evidenceNodeId ?? input.evidenceId
16913
+ )}:${String(
16914
+ input.questionId ?? input.questionNodeId ?? input.targetId
16915
+ )}:evidence_supports_question`,
16916
+ weight: input.impactScore ?? input.weight,
16917
+ context: input.rationale ?? input.context,
16918
+ skipLayerValidation: true,
16919
+ topicId: input.topicId,
16920
+ trustedBypassAccessCheck: input.trustedBypassAccessCheck ?? true
16921
+ }),
16199
16922
  context
16200
16923
  );
16201
16924
  var evidenceContracts = [
@@ -16239,8 +16962,9 @@ var evidenceContracts = [
16239
16962
  linkedBeliefNodeId: input.linkedBeliefNodeId ?? input.targetNodeId ?? input.targetId,
16240
16963
  evidenceRelation: weight < 0 ? "contradicts" : "supports",
16241
16964
  confidence: Math.min(1, Math.max(0, Math.abs(weight))),
16965
+ rationale: input.reasoning,
16242
16966
  metadata: {
16243
- ...input.metadata && typeof input.metadata === "object" && !Array.isArray(input.metadata) ? input.metadata : {},
16967
+ ...recordValue2(input.metadata),
16244
16968
  reasoning: input.reasoning,
16245
16969
  sourceUrl: input.sourceUrl
16246
16970
  }
@@ -16280,7 +17004,8 @@ var evidenceContracts = [
16280
17004
  convex: {
16281
17005
  module: "evidence",
16282
17006
  functionName: "getByTopic",
16283
- kind: "query"
17007
+ kind: "query",
17008
+ inputProjection: evidenceTopicInput
16284
17009
  }
16285
17010
  }),
16286
17011
  surfaceContract({
@@ -16296,10 +17021,12 @@ var evidenceContracts = [
16296
17021
  module: "nodes",
16297
17022
  functionName: "search",
16298
17023
  kind: "query",
16299
- inputProjection: (input) => ({
16300
- ...input,
17024
+ inputProjection: (input) => compactRecord4({
16301
17025
  searchQuery: input.searchQuery ?? input.q ?? input.query,
16302
- nodeType: "evidence"
17026
+ projectId: input.projectId,
17027
+ topicId: input.topicId,
17028
+ nodeType: "evidence",
17029
+ limit: input.limit
16303
17030
  })
16304
17031
  }
16305
17032
  }),
@@ -16313,17 +17040,10 @@ var evidenceContracts = [
16313
17040
  sdkMethod: "linkEvidenceToBelief",
16314
17041
  summary: "Link evidence to a belief.",
16315
17042
  convex: {
16316
- module: "beliefs",
16317
- functionName: "linkEvidence",
17043
+ module: "edges",
17044
+ functionName: "create",
16318
17045
  kind: "mutation",
16319
- inputProjection: (input, context) => withUserId(
16320
- {
16321
- ...input,
16322
- beliefNodeId: input.beliefNodeId ?? input.beliefId ?? input.targetId,
16323
- evidenceNodeId: input.evidenceNodeId ?? input.evidenceId
16324
- },
16325
- context
16326
- )
17046
+ inputProjection: linkEvidenceToBeliefEdgeInput
16327
17047
  }
16328
17048
  }),
16329
17049
  surfaceContract({
@@ -16336,18 +17056,10 @@ var evidenceContracts = [
16336
17056
  sdkMethod: "linkEvidenceToQuestion",
16337
17057
  summary: "Link evidence to a question.",
16338
17058
  convex: {
16339
- module: "questionLinks",
17059
+ module: "edges",
16340
17060
  functionName: "create",
16341
17061
  kind: "mutation",
16342
- inputProjection: (input, context) => withCreatedBy(
16343
- {
16344
- ...input,
16345
- questionId: input.questionId,
16346
- insightId: input.insightId ?? input.evidenceId,
16347
- helpsAnswer: input.helpsAnswer ?? true
16348
- },
16349
- context
16350
- )
17062
+ inputProjection: linkEvidenceToQuestionEdgeInput
16351
17063
  }
16352
17064
  }),
16353
17065
  surfaceContract({
@@ -16360,35 +17072,46 @@ var evidenceContracts = [
16360
17072
  sdkMethod: "linkEvidence",
16361
17073
  summary: "Link evidence to a target node.",
16362
17074
  convex: {
16363
- module: "beliefs",
16364
- functionName: "linkEvidence",
17075
+ module: "edges",
17076
+ functionName: "create",
16365
17077
  kind: "mutation",
16366
- inputProjection: (input, context) => withUserId(
16367
- {
16368
- ...input,
16369
- beliefNodeId: input.beliefNodeId ?? input.targetId,
16370
- evidenceNodeId: input.evidenceNodeId ?? input.evidenceId
16371
- },
16372
- context
16373
- )
17078
+ inputProjection: linkEvidenceToBeliefEdgeInput
16374
17079
  }
16375
17080
  })
16376
17081
  ];
16377
17082
 
16378
17083
  // ../contracts/src/function-registry/questions.ts
16379
- var questionIdInput = (input) => ({
16380
- ...input,
16381
- questionId: input.questionId ?? input.id ?? input.nodeId,
16382
- nodeId: input.nodeId ?? input.id ?? input.questionId
17084
+ var questionNodeInput = (input) => compactRecord4({
17085
+ nodeId: input.nodeId ?? input.id ?? input.questionId,
17086
+ questionId: input.questionId
16383
17087
  });
16384
- var createQuestionInput = (input, context) => withUserId(
16385
- {
16386
- ...input,
16387
- text: input.text ?? input.question,
16388
- trustedBypassAccessCheck: input.trustedBypassAccessCheck ?? true
16389
- },
16390
- context
16391
- );
17088
+ var questionTopicInput = (input) => compactRecord4({
17089
+ topicId: input.topicId,
17090
+ status: input.status,
17091
+ userId: input.userId,
17092
+ limit: input.limit
17093
+ });
17094
+ var createQuestionInput = (input, context) => {
17095
+ const priority = input.priority === "urgent" ? "high" : input.priority;
17096
+ return withUserId(
17097
+ compactRecord4({
17098
+ topicId: input.topicId,
17099
+ question: input.question ?? input.text,
17100
+ category: input.category,
17101
+ priority,
17102
+ source: input.source,
17103
+ linkedBeliefNodeId: input.linkedBeliefNodeId ?? input.linkedBeliefId,
17104
+ testType: input.testType,
17105
+ importance: input.importance,
17106
+ epistemicUnlock: input.epistemicUnlock,
17107
+ sourceQuestionIds: input.sourceQuestionIds,
17108
+ linkedWorktreeId: input.linkedWorktreeId,
17109
+ questionType: input.questionType,
17110
+ questionPriority: input.questionPriority
17111
+ }),
17112
+ context
17113
+ );
17114
+ };
16392
17115
  var questionsContracts = [
16393
17116
  surfaceContract({
16394
17117
  name: "create_question",
@@ -16420,7 +17143,7 @@ var questionsContracts = [
16420
17143
  module: "questions",
16421
17144
  functionName: "getById",
16422
17145
  kind: "query",
16423
- inputProjection: questionIdInput
17146
+ inputProjection: questionNodeInput
16424
17147
  }
16425
17148
  }),
16426
17149
  surfaceContract({
@@ -16436,7 +17159,8 @@ var questionsContracts = [
16436
17159
  convex: {
16437
17160
  module: "questions",
16438
17161
  functionName: "getByTopic",
16439
- kind: "query"
17162
+ kind: "query",
17163
+ inputProjection: questionTopicInput
16440
17164
  }
16441
17165
  }),
16442
17166
  surfaceContract({
@@ -16453,7 +17177,12 @@ var questionsContracts = [
16453
17177
  module: "questions",
16454
17178
  functionName: "updateQuestion",
16455
17179
  kind: "mutation",
16456
- inputProjection: (input, context) => withUserId({ ...questionIdInput(input), text: input.text }, context)
17180
+ inputProjection: (input) => compactRecord4({
17181
+ questionId: input.questionId ?? input.id ?? input.nodeId,
17182
+ question: input.question ?? input.text,
17183
+ category: input.category,
17184
+ priority: input.priority
17185
+ })
16457
17186
  }
16458
17187
  }),
16459
17188
  surfaceContract({
@@ -16470,7 +17199,16 @@ var questionsContracts = [
16470
17199
  module: "questions",
16471
17200
  functionName: "updateStatus",
16472
17201
  kind: "mutation",
16473
- inputProjection: (input, context) => withUserId(questionIdInput(input), context)
17202
+ inputProjection: (input, context) => withUserId(
17203
+ compactRecord4({
17204
+ questionId: input.questionId ?? input.id,
17205
+ nodeId: input.nodeId,
17206
+ status: input.status,
17207
+ answer: input.answer,
17208
+ answerStatus: input.answerStatus
17209
+ }),
17210
+ context
17211
+ )
16474
17212
  }
16475
17213
  }),
16476
17214
  surfaceContract({
@@ -16487,7 +17225,12 @@ var questionsContracts = [
16487
17225
  module: "questions",
16488
17226
  functionName: "deleteQuestion",
16489
17227
  kind: "mutation",
16490
- inputProjection: questionIdInput
17228
+ inputProjection: (input, context) => withUserId(
17229
+ compactRecord4({
17230
+ questionId: input.questionId ?? input.id ?? input.nodeId
17231
+ }),
17232
+ context
17233
+ )
16491
17234
  }
16492
17235
  }),
16493
17236
  surfaceContract({
@@ -16504,10 +17247,16 @@ var questionsContracts = [
16504
17247
  functionName: "create",
16505
17248
  kind: "mutation",
16506
17249
  inputProjection: (input, context) => withUserId(
16507
- {
16508
- ...input,
16509
- questionNodeId: input.questionNodeId ?? input.questionId
16510
- },
17250
+ compactRecord4({
17251
+ topicId: input.topicId,
17252
+ questionNodeId: input.questionNodeId ?? input.questionId,
17253
+ answerText: input.answerText,
17254
+ confidence: input.confidence,
17255
+ evidenceNodeIds: input.evidenceNodeIds,
17256
+ answerSource: input.answerSource,
17257
+ worktreeId: input.worktreeId,
17258
+ sprintId: input.sprintId
17259
+ }),
16511
17260
  context
16512
17261
  )
16513
17262
  }
@@ -16527,13 +17276,16 @@ var questionsContracts = [
16527
17276
  functionName: "create",
16528
17277
  kind: "mutation",
16529
17278
  inputProjection: (input, context) => withUserId(
16530
- {
16531
- ...input,
17279
+ compactRecord4({
17280
+ topicId: input.topicId,
16532
17281
  questionNodeId: input.questionNodeId ?? input.questionId ?? input.id,
16533
17282
  answerText: input.answerText ?? input.text,
16534
17283
  evidenceNodeIds: input.evidenceNodeIds ?? input.evidenceIds,
16535
- answerSource: input.answerSource ?? "human"
16536
- },
17284
+ answerSource: input.answerSource ?? "human",
17285
+ confidence: input.confidence,
17286
+ worktreeId: input.worktreeId,
17287
+ sprintId: input.sprintId
17288
+ }),
16537
17289
  context
16538
17290
  )
16539
17291
  }
@@ -16566,7 +17318,8 @@ var questionsContracts = [
16566
17318
  convex: {
16567
17319
  module: "questions",
16568
17320
  functionName: "getByTopic",
16569
- kind: "query"
17321
+ kind: "query",
17322
+ inputProjection: questionTopicInput
16570
17323
  }
16571
17324
  }),
16572
17325
  surfaceContract({
@@ -16581,7 +17334,11 @@ var questionsContracts = [
16581
17334
  convex: {
16582
17335
  module: "questions",
16583
17336
  functionName: "getByTopic",
16584
- kind: "query"
17337
+ kind: "query",
17338
+ inputProjection: (input) => compactRecord4({
17339
+ ...questionTopicInput(input),
17340
+ status: input.includeAnswered === true ? void 0 : "open"
17341
+ })
16585
17342
  }
16586
17343
  }),
16587
17344
  surfaceContract({
@@ -16596,16 +17353,28 @@ var questionsContracts = [
16596
17353
  convex: {
16597
17354
  module: "questions",
16598
17355
  functionName: "getByTopic",
16599
- kind: "query"
17356
+ kind: "query",
17357
+ inputProjection: questionTopicInput
16600
17358
  }
16601
17359
  })
16602
17360
  ];
16603
17361
 
16604
17362
  // ../contracts/src/function-registry/topics.ts
16605
- var topicIdInput = (input) => ({
16606
- ...input,
17363
+ var topicIdInput = (input) => compactRecord4({
16607
17364
  id: input.id ?? input.topicId
16608
17365
  });
17366
+ var updateTopicInput = (input) => compactRecord4({
17367
+ id: input.id ?? input.topicId,
17368
+ name: input.name,
17369
+ description: input.description,
17370
+ type: input.type,
17371
+ status: input.status,
17372
+ visibility: input.visibility,
17373
+ ontologyId: input.ontologyId,
17374
+ clearOntologyId: input.clearOntologyId,
17375
+ graphScopeProjectId: input.graphScopeProjectId,
17376
+ metadata: input.metadata
17377
+ });
16609
17378
  var topicsContracts = [
16610
17379
  surfaceContract({
16611
17380
  name: "create_topic",
@@ -16670,7 +17439,7 @@ var topicsContracts = [
16670
17439
  module: "topics",
16671
17440
  functionName: "update",
16672
17441
  kind: "mutation",
16673
- inputProjection: topicIdInput
17442
+ inputProjection: updateTopicInput
16674
17443
  }
16675
17444
  }),
16676
17445
  surfaceContract({
@@ -16692,6 +17461,27 @@ var topicsContracts = [
16692
17461
  ];
16693
17462
 
16694
17463
  // ../contracts/src/function-registry/lenses.ts
17464
+ var createLensInput = (input, context) => compactRecord4({
17465
+ name: input.name,
17466
+ description: input.description,
17467
+ workspaceId: input.workspaceId,
17468
+ topicId: input.topicId,
17469
+ perspectiveType: input.perspectiveType,
17470
+ promptTemplates: input.promptTemplates,
17471
+ workflowTemplates: input.workflowTemplates,
17472
+ taskTemplates: input.taskTemplates,
17473
+ questionTemplates: input.questionTemplates,
17474
+ filterCriteria: input.filterCriteria,
17475
+ metadata: input.metadata,
17476
+ createdBy: authUserId(context)
17477
+ });
17478
+ var lensListInput = (input, context) => compactRecord4({
17479
+ actorId: input.actorId ?? authUserId(context),
17480
+ workspaceId: input.workspaceId,
17481
+ topicId: input.topicId,
17482
+ status: input.status,
17483
+ perspectiveType: input.perspectiveType
17484
+ });
16695
17485
  var lensesContracts = [
16696
17486
  surfaceContract({
16697
17487
  name: "create_lens",
@@ -16705,7 +17495,8 @@ var lensesContracts = [
16705
17495
  convex: {
16706
17496
  module: "lenses",
16707
17497
  functionName: "create",
16708
- kind: "mutation"
17498
+ kind: "mutation",
17499
+ inputProjection: createLensInput
16709
17500
  }
16710
17501
  }),
16711
17502
  surfaceContract({
@@ -16721,7 +17512,8 @@ var lensesContracts = [
16721
17512
  convex: {
16722
17513
  module: "lenses",
16723
17514
  functionName: "list",
16724
- kind: "query"
17515
+ kind: "query",
17516
+ inputProjection: lensListInput
16725
17517
  }
16726
17518
  }),
16727
17519
  surfaceContract({
@@ -16736,7 +17528,13 @@ var lensesContracts = [
16736
17528
  convex: {
16737
17529
  module: "lenses",
16738
17530
  functionName: "applyToTopic",
16739
- kind: "mutation"
17531
+ kind: "mutation",
17532
+ inputProjection: (input, context) => compactRecord4({
17533
+ lensId: input.lensId,
17534
+ topicId: input.topicId,
17535
+ metadata: input.metadata,
17536
+ appliedBy: authUserId(context)
17537
+ })
16740
17538
  }
16741
17539
  }),
16742
17540
  surfaceContract({
@@ -16752,12 +17550,28 @@ var lensesContracts = [
16752
17550
  convex: {
16753
17551
  module: "lenses",
16754
17552
  functionName: "removeFromTopic",
16755
- kind: "mutation"
17553
+ kind: "mutation",
17554
+ inputProjection: (input, context) => compactRecord4({
17555
+ lensId: input.lensId,
17556
+ topicId: input.topicId,
17557
+ removedBy: authUserId(context)
17558
+ })
16756
17559
  }
16757
17560
  })
16758
17561
  ];
16759
17562
 
16760
17563
  // ../contracts/src/function-registry/ontologies.ts
17564
+ var ontologyIdInput = (input) => compactRecord4({
17565
+ id: input.id ?? input.ontologyId
17566
+ });
17567
+ var ontologyVersionIdInput = (input) => compactRecord4({
17568
+ id: input.id ?? input.versionId,
17569
+ ontologyId: input.ontologyId,
17570
+ actorId: input.actorId
17571
+ });
17572
+ var effectiveOntologyInput = (input) => compactRecord4({
17573
+ ontologyId: input.ontologyId ?? input.id
17574
+ });
16761
17575
  var ontologiesContracts = [
16762
17576
  surfaceContract({
16763
17577
  name: "create_ontology",
@@ -16788,10 +17602,7 @@ var ontologiesContracts = [
16788
17602
  module: "ontologies",
16789
17603
  functionName: "getOntologyDefinition",
16790
17604
  kind: "query",
16791
- inputProjection: (input) => ({
16792
- ...input,
16793
- id: input.id ?? input.ontologyId
16794
- })
17605
+ inputProjection: ontologyIdInput
16795
17606
  }
16796
17607
  }),
16797
17608
  surfaceContract({
@@ -16824,9 +17635,13 @@ var ontologiesContracts = [
16824
17635
  module: "ontologies",
16825
17636
  functionName: "updateOntologyDefinition",
16826
17637
  kind: "mutation",
16827
- inputProjection: (input) => ({
16828
- ...input,
16829
- id: input.id ?? input.ontologyId
17638
+ inputProjection: (input) => compactRecord4({
17639
+ id: input.id ?? input.ontologyId,
17640
+ name: input.name,
17641
+ description: input.description,
17642
+ parentOntologyId: input.parentOntologyId,
17643
+ status: input.status,
17644
+ actorId: input.actorId
16830
17645
  })
16831
17646
  }
16832
17647
  }),
@@ -16844,10 +17659,7 @@ var ontologiesContracts = [
16844
17659
  module: "ontologies",
16845
17660
  functionName: "archiveOntologyDefinition",
16846
17661
  kind: "mutation",
16847
- inputProjection: (input) => ({
16848
- ...input,
16849
- id: input.id ?? input.ontologyId
16850
- })
17662
+ inputProjection: ontologyIdInput
16851
17663
  }
16852
17664
  }),
16853
17665
  surfaceContract({
@@ -16878,8 +17690,7 @@ var ontologiesContracts = [
16878
17690
  module: "topics",
16879
17691
  functionName: "update",
16880
17692
  kind: "mutation",
16881
- inputProjection: (input) => ({
16882
- ...input,
17693
+ inputProjection: (input) => compactRecord4({
16883
17694
  id: input.topicId ?? input.id,
16884
17695
  ontologyId: input.ontologyId ?? input.id
16885
17696
  })
@@ -16897,7 +17708,8 @@ var ontologiesContracts = [
16897
17708
  convex: {
16898
17709
  module: "ontologies",
16899
17710
  functionName: "resolveEffectiveOntology",
16900
- kind: "query"
17711
+ kind: "query",
17712
+ inputProjection: effectiveOntologyInput
16901
17713
  }
16902
17714
  }),
16903
17715
  surfaceContract({
@@ -16913,10 +17725,7 @@ var ontologiesContracts = [
16913
17725
  module: "ontologies",
16914
17726
  functionName: "publishOntologyVersion",
16915
17727
  kind: "mutation",
16916
- inputProjection: (input) => ({
16917
- ...input,
16918
- id: input.id ?? input.versionId
16919
- })
17728
+ inputProjection: ontologyVersionIdInput
16920
17729
  }
16921
17730
  }),
16922
17731
  surfaceContract({
@@ -16932,10 +17741,7 @@ var ontologiesContracts = [
16932
17741
  module: "ontologies",
16933
17742
  functionName: "deprecateOntologyVersion",
16934
17743
  kind: "mutation",
16935
- inputProjection: (input) => ({
16936
- ...input,
16937
- id: input.id ?? input.versionId
16938
- })
17744
+ inputProjection: ontologyVersionIdInput
16939
17745
  }
16940
17746
  }),
16941
17747
  surfaceContract({
@@ -16950,16 +17756,51 @@ var ontologiesContracts = [
16950
17756
  convex: {
16951
17757
  module: "ontologies",
16952
17758
  functionName: "resolveEffectiveOntology",
16953
- kind: "query"
17759
+ kind: "query",
17760
+ inputProjection: effectiveOntologyInput
16954
17761
  }
16955
17762
  })
16956
17763
  ];
16957
17764
 
16958
17765
  // ../contracts/src/function-registry/worktrees.ts
16959
- var worktreeInput = (input) => ({
16960
- ...input,
17766
+ var worktreeIdInput = (input) => compactRecord4({
16961
17767
  worktreeId: input.worktreeId ?? input.id
16962
17768
  });
17769
+ var activateWorktreeInput = (input, context) => withUserId(worktreeIdInput(input), context);
17770
+ var worktreeTargetsInput = (input) => compactRecord4({
17771
+ worktreeId: input.worktreeId ?? input.id,
17772
+ addBeliefIds: input.addBeliefIds,
17773
+ removeBeliefIds: input.removeBeliefIds,
17774
+ addQuestionIds: input.addQuestionIds,
17775
+ removeQuestionIds: input.removeQuestionIds
17776
+ });
17777
+ var worktreeMetadataInput = (input) => compactRecord4({
17778
+ worktreeId: input.worktreeId ?? input.id,
17779
+ topicId: input.topicId,
17780
+ additionalTopicIds: input.additionalTopicIds,
17781
+ status: input.status,
17782
+ campaign: input.campaign,
17783
+ lane: input.lane,
17784
+ laneOrderInCampaign: input.laneOrderInCampaign,
17785
+ orderInLane: input.orderInLane,
17786
+ gate: input.gate,
17787
+ hypothesis: input.hypothesis,
17788
+ objective: input.objective,
17789
+ rationale: input.rationale,
17790
+ proofArtifacts: input.proofArtifacts,
17791
+ staffingHint: input.staffingHint,
17792
+ blocks: input.blocks,
17793
+ dependsOn: input.dependsOn,
17794
+ lensId: input.lensId,
17795
+ autoFixPolicy: input.autoFixPolicy,
17796
+ lastReconciledAt: input.lastReconciledAt
17797
+ });
17798
+ var listAllWorktreesInput = (input) => compactRecord4({
17799
+ status: input.status,
17800
+ lane: input.lane,
17801
+ campaign: input.campaign,
17802
+ limit: input.limit
17803
+ });
16963
17804
  var worktreesContracts = [
16964
17805
  surfaceContract({
16965
17806
  name: "add_worktree",
@@ -16975,11 +17816,43 @@ var worktreesContracts = [
16975
17816
  functionName: "create",
16976
17817
  kind: "mutation",
16977
17818
  inputProjection: (input, context) => withCreatedBy(
16978
- {
16979
- ...input,
17819
+ compactRecord4({
16980
17820
  name: input.name ?? input.title,
16981
- targetBeliefIds: input.targetBeliefIds ?? input.beliefIds
16982
- },
17821
+ topicId: input.topicId,
17822
+ worktreeType: input.worktreeType,
17823
+ objective: input.objective,
17824
+ gate: input.gate,
17825
+ hypothesis: input.hypothesis,
17826
+ rationale: input.rationale,
17827
+ signal: input.signal,
17828
+ startDate: input.startDate,
17829
+ endDate: input.endDate,
17830
+ durationWeeks: input.durationWeeks,
17831
+ confidenceImpact: input.confidenceImpact,
17832
+ autoShape: input.autoShape,
17833
+ autoFixPolicy: input.autoFixPolicy,
17834
+ beliefFocus: input.beliefFocus,
17835
+ targetQuestionIds: input.targetQuestionIds,
17836
+ targetBeliefIds: input.targetBeliefIds ?? input.beliefIds,
17837
+ keyQuestions: input.keyQuestions,
17838
+ proofArtifacts: input.proofArtifacts,
17839
+ decisionGate: input.decisionGate ?? (input.goCriteria || input.noGoSignals ? compactRecord4({
17840
+ goCriteria: input.goCriteria,
17841
+ noGoSignals: input.noGoSignals
17842
+ }) : void 0),
17843
+ evidenceSignals: input.evidenceSignals,
17844
+ dependsOn: input.dependsOn,
17845
+ blocks: input.blocks,
17846
+ campaign: input.campaign,
17847
+ lane: input.lane,
17848
+ laneOrderInCampaign: input.laneOrderInCampaign,
17849
+ orderInLane: input.orderInLane,
17850
+ staffingHint: input.staffingHint,
17851
+ domainPackId: input.domainPackId,
17852
+ lensId: input.lensId,
17853
+ linkedQuestionId: input.linkedQuestionId,
17854
+ lastReconciledAt: input.lastReconciledAt
17855
+ }),
16983
17856
  context
16984
17857
  )
16985
17858
  }
@@ -16997,7 +17870,7 @@ var worktreesContracts = [
16997
17870
  module: "worktrees",
16998
17871
  functionName: "activate",
16999
17872
  kind: "mutation",
17000
- inputProjection: worktreeInput
17873
+ inputProjection: activateWorktreeInput
17001
17874
  }
17002
17875
  }),
17003
17876
  surfaceContract({
@@ -17013,7 +17886,36 @@ var worktreesContracts = [
17013
17886
  convex: {
17014
17887
  module: "worktrees",
17015
17888
  functionName: "list",
17016
- kind: "query"
17889
+ kind: "query",
17890
+ inputProjection: (input) => compactRecord4({
17891
+ topicId: input.topicId,
17892
+ status: input.status,
17893
+ groupBy: input.groupBy,
17894
+ lane: input.lane,
17895
+ campaign: input.campaign,
17896
+ limit: input.limit
17897
+ })
17898
+ }
17899
+ }),
17900
+ surfaceContract({
17901
+ name: "list_campaigns",
17902
+ kind: "query",
17903
+ domain: "worktrees",
17904
+ surfaceClass: "platform_public",
17905
+ method: "GET",
17906
+ path: "/worktrees/campaigns",
17907
+ sdkNamespace: "worktrees",
17908
+ sdkMethod: "listCampaigns",
17909
+ summary: "List compact pipeline campaigns with nested lanes.",
17910
+ convex: {
17911
+ module: "worktrees",
17912
+ functionName: "listCampaigns",
17913
+ kind: "query",
17914
+ inputProjection: (input) => compactRecord4({
17915
+ topicId: input.topicId,
17916
+ status: input.status,
17917
+ limit: input.limit
17918
+ })
17017
17919
  }
17018
17920
  }),
17019
17921
  surfaceContract({
@@ -17029,7 +17931,8 @@ var worktreesContracts = [
17029
17931
  convex: {
17030
17932
  module: "worktrees",
17031
17933
  functionName: "listAll",
17032
- kind: "query"
17934
+ kind: "query",
17935
+ inputProjection: listAllWorktreesInput
17033
17936
  }
17034
17937
  }),
17035
17938
  surfaceContract({
@@ -17046,7 +17949,7 @@ var worktreesContracts = [
17046
17949
  module: "worktrees",
17047
17950
  functionName: "updateTargets",
17048
17951
  kind: "mutation",
17049
- inputProjection: worktreeInput
17952
+ inputProjection: worktreeTargetsInput
17050
17953
  }
17051
17954
  }),
17052
17955
  surfaceContract({
@@ -17063,7 +17966,7 @@ var worktreesContracts = [
17063
17966
  module: "worktrees",
17064
17967
  functionName: "updateMetadata",
17065
17968
  kind: "mutation",
17066
- inputProjection: worktreeInput
17969
+ inputProjection: worktreeMetadataInput
17067
17970
  }
17068
17971
  }),
17069
17972
  surfaceContract({
@@ -17079,12 +17982,17 @@ var worktreesContracts = [
17079
17982
  module: "worktrees",
17080
17983
  functionName: "complete",
17081
17984
  kind: "mutation",
17082
- inputProjection: (input) => ({
17083
- ...worktreeInput(input),
17084
- keyFindings: input.keyFindings ?? [input.summary ?? "Merged worktree"],
17085
- decisionsReached: input.decisionsReached ?? [],
17086
- nextSteps: input.nextSteps ?? []
17087
- })
17985
+ inputProjection: (input, context) => withUserId(
17986
+ {
17987
+ ...worktreeIdInput(input),
17988
+ keyFindings: input.keyFindings ?? [
17989
+ input.summary ?? "Merged worktree"
17990
+ ],
17991
+ decisionsReached: input.decisionsReached ?? [],
17992
+ nextSteps: input.nextSteps ?? []
17993
+ },
17994
+ context
17995
+ )
17088
17996
  }
17089
17997
  }),
17090
17998
  surfaceContract({
@@ -17100,11 +18008,7 @@ var worktreesContracts = [
17100
18008
  module: "worktrees",
17101
18009
  functionName: "updateMetadata",
17102
18010
  kind: "mutation",
17103
- inputProjection: (input) => ({
17104
- ...worktreeInput(input),
17105
- lastPushTargetContext: input.targetContext,
17106
- lastPushBeliefIds: input.beliefIds
17107
- })
18011
+ inputProjection: worktreeMetadataInput
17108
18012
  }
17109
18013
  }),
17110
18014
  surfaceContract({
@@ -17120,20 +18024,30 @@ var worktreesContracts = [
17120
18024
  module: "worktrees",
17121
18025
  functionName: "updateMetadata",
17122
18026
  kind: "mutation",
17123
- inputProjection: (input) => ({
17124
- ...worktreeInput(input),
17125
- lastPullRequestSummary: input.summary,
17126
- lastPullRequestReviewers: input.reviewers
17127
- })
18027
+ inputProjection: worktreeMetadataInput
17128
18028
  }
17129
18029
  })
17130
18030
  ];
17131
18031
 
17132
18032
  // ../contracts/src/function-registry/tasks.ts
17133
- var taskInput = (input) => ({
18033
+ var taskInput = (input) => compactRecord4({
17134
18034
  ...input,
17135
18035
  taskId: input.taskId ?? input.id
17136
18036
  });
18037
+ var taskTopicInput = (input) => {
18038
+ const parsed = listTasksProjection.inputSchema.safeParse(input);
18039
+ if (!parsed.success) {
18040
+ throw new Error(
18041
+ `list_tasks projection input rejected: ${parsed.error.message}`
18042
+ );
18043
+ }
18044
+ return compactRecord4(listTasksProjection.project(parsed.data));
18045
+ };
18046
+ var completeTaskInput = (input) => compactRecord4({
18047
+ taskId: input.taskId ?? input.id,
18048
+ outputSummary: input.outputSummary ?? input.summary,
18049
+ userId: input.userId
18050
+ });
17137
18051
  var tasksContracts = [
17138
18052
  surfaceContract({
17139
18053
  name: "create_task",
@@ -17163,8 +18077,10 @@ var tasksContracts = [
17163
18077
  convex: {
17164
18078
  module: "tasks",
17165
18079
  functionName: "getByTopic",
17166
- kind: "query"
17167
- }
18080
+ kind: "query",
18081
+ inputProjection: taskTopicInput
18082
+ },
18083
+ args: listTasksInputSchema
17168
18084
  }),
17169
18085
  surfaceContract({
17170
18086
  name: "update_task",
@@ -17196,12 +18112,29 @@ var tasksContracts = [
17196
18112
  module: "tasks",
17197
18113
  functionName: "complete",
17198
18114
  kind: "mutation",
17199
- inputProjection: taskInput
18115
+ inputProjection: completeTaskInput
17200
18116
  }
17201
18117
  })
17202
18118
  ];
17203
-
17204
- // ../contracts/src/function-registry/edges.ts
18119
+ var createEdgeArgs = z.object({
18120
+ from: GraphRefSchema,
18121
+ to: GraphRefSchema,
18122
+ edgeType: z.string(),
18123
+ globalId: z.string().optional(),
18124
+ weight: z.number().optional(),
18125
+ confidence: z.number().optional(),
18126
+ context: z.string().optional(),
18127
+ reasoning: z.string().optional(),
18128
+ derivationType: z.string().optional(),
18129
+ topicId: z.string().optional(),
18130
+ trustedBypassAccessCheck: z.boolean().optional()
18131
+ });
18132
+ function graphRefNodeId(ref) {
18133
+ if (ref.kind === "epistemic_node") {
18134
+ return ref.nodeId;
18135
+ }
18136
+ return `external_belief:${ref.ref.tenantId}:${ref.ref.beliefId}`;
18137
+ }
17205
18138
  var edgesContracts = [
17206
18139
  surfaceContract({
17207
18140
  name: "create_edge",
@@ -17216,16 +18149,35 @@ var edgesContracts = [
17216
18149
  module: "edges",
17217
18150
  functionName: "create",
17218
18151
  kind: "mutation",
17219
- inputProjection: (input, context) => withCreatedBy(
17220
- {
17221
- ...input,
17222
- fromNodeId: input.fromNodeId ?? input.sourceId,
17223
- toNodeId: input.toNodeId ?? input.targetId,
17224
- context: input.context ?? input.reasoning
17225
- },
17226
- context
17227
- )
17228
- }
18152
+ inputProjection: (input, context) => {
18153
+ const parsed = createEdgeArgs.parse(input);
18154
+ assertEdgePolicyAllowed(
18155
+ edgePolicyManifest,
18156
+ parsed.edgeType,
18157
+ parsed.from,
18158
+ parsed.to
18159
+ );
18160
+ const fromNodeId = graphRefNodeId(parsed.from);
18161
+ const toNodeId = graphRefNodeId(parsed.to);
18162
+ return withCreatedBy(
18163
+ compactRecord4({
18164
+ fromNodeId,
18165
+ toNodeId,
18166
+ edgeType: parsed.edgeType,
18167
+ globalId: parsed.globalId ?? `edge:${fromNodeId}:${toNodeId}:${parsed.edgeType}`,
18168
+ weight: parsed.weight,
18169
+ confidence: parsed.confidence,
18170
+ context: parsed.context ?? parsed.reasoning,
18171
+ derivationType: parsed.derivationType,
18172
+ skipLayerValidation: true,
18173
+ topicId: parsed.topicId,
18174
+ trustedBypassAccessCheck: parsed.trustedBypassAccessCheck
18175
+ }),
18176
+ context
18177
+ );
18178
+ }
18179
+ },
18180
+ args: createEdgeArgs
17229
18181
  }),
17230
18182
  surfaceContract({
17231
18183
  name: "query_lineage",
@@ -17240,9 +18192,12 @@ var edgesContracts = [
17240
18192
  module: "edges",
17241
18193
  functionName: "getLineage",
17242
18194
  kind: "query",
17243
- inputProjection: (input) => ({
17244
- ...input,
17245
- maxDepth: input.maxDepth ?? input.depth
18195
+ inputProjection: (input) => compactRecord4({
18196
+ nodeId: input.nodeId ?? input.startNode,
18197
+ maxDepth: input.maxDepth ?? input.depth,
18198
+ mode: input.mode,
18199
+ minLayer: input.minLayer,
18200
+ maxLayer: input.maxLayer
17246
18201
  })
17247
18202
  }
17248
18203
  })
@@ -17262,8 +18217,7 @@ var contradictionSeverity = (value) => {
17262
18217
  return "significant";
17263
18218
  }
17264
18219
  };
17265
- var flagContradictionInput = (input, context) => ({
17266
- ...input,
18220
+ var flagContradictionInput = (input, context) => compactRecord4({
17267
18221
  beliefId: input.beliefId ?? input.beliefA,
17268
18222
  supportingInsightIds: Array.isArray(input.supportingInsightIds) ? input.supportingInsightIds : [],
17269
18223
  contradictingInsightIds: Array.isArray(input.contradictingInsightIds) ? input.contradictingInsightIds : [input.beliefB].filter((value) => typeof value === "string"),
@@ -17277,6 +18231,18 @@ var flagContradictionInput = (input, context) => ({
17277
18231
  },
17278
18232
  createdBy: authUserId(context)
17279
18233
  });
18234
+ var lineageInput = (input) => compactRecord4({
18235
+ nodeId: input.nodeId ?? input.startNode ?? input.entityId,
18236
+ maxDepth: input.maxDepth ?? input.depth,
18237
+ mode: input.mode,
18238
+ minLayer: input.minLayer,
18239
+ maxLayer: input.maxLayer
18240
+ });
18241
+ var topicEdgesInput = (input) => compactRecord4({
18242
+ topicId: input.topicId,
18243
+ userId: input.userId,
18244
+ limit: input.limit
18245
+ });
17280
18246
  var graphContracts = [
17281
18247
  surfaceContract({
17282
18248
  name: "traverse_graph",
@@ -17290,7 +18256,8 @@ var graphContracts = [
17290
18256
  convex: {
17291
18257
  module: "edges",
17292
18258
  functionName: "getLineage",
17293
- kind: "query"
18259
+ kind: "query",
18260
+ inputProjection: lineageInput
17294
18261
  }
17295
18262
  }),
17296
18263
  surfaceContract({
@@ -17305,7 +18272,8 @@ var graphContracts = [
17305
18272
  convex: {
17306
18273
  module: "edges",
17307
18274
  functionName: "getByTopic",
17308
- kind: "query"
18275
+ kind: "query",
18276
+ inputProjection: topicEdgesInput
17309
18277
  }
17310
18278
  }),
17311
18279
  surfaceContract({
@@ -17335,7 +18303,10 @@ var graphContracts = [
17335
18303
  convex: {
17336
18304
  module: "edges",
17337
18305
  functionName: "findContradictions",
17338
- kind: "query"
18306
+ kind: "query",
18307
+ inputProjection: (input) => compactRecord4({
18308
+ nodeId: input.nodeId ?? input.beliefId
18309
+ })
17339
18310
  }
17340
18311
  }),
17341
18312
  surfaceContract({
@@ -17440,8 +18411,9 @@ var graphContracts = [
17440
18411
  summary: "Discover graph connections for an entity.",
17441
18412
  convex: {
17442
18413
  module: "edges",
17443
- functionName: "getByTopic",
17444
- kind: "query"
18414
+ functionName: "getLineage",
18415
+ kind: "query",
18416
+ inputProjection: lineageInput
17445
18417
  }
17446
18418
  }),
17447
18419
  surfaceContract({
@@ -17472,10 +18444,7 @@ var graphContracts = [
17472
18444
  module: "edges",
17473
18445
  functionName: "getLineage",
17474
18446
  kind: "query",
17475
- inputProjection: (input) => ({
17476
- ...input,
17477
- nodeId: input.nodeId ?? input.entityId
17478
- })
18447
+ inputProjection: lineageInput
17479
18448
  }
17480
18449
  })
17481
18450
  ];
@@ -17545,19 +18514,21 @@ var judgmentsContracts = [
17545
18514
  functionName: "create",
17546
18515
  kind: "mutation",
17547
18516
  inputProjection: (input, context) => withUserId(
17548
- {
17549
- ...input,
18517
+ compactRecord4({
18518
+ projectId: input.projectId,
18519
+ topicId: input.topicId,
17550
18520
  text: input.rationale,
17551
18521
  title: input.title,
17552
18522
  content: input.rationale,
17553
18523
  kind: "judgment",
17554
- sourceType: "agent",
17555
- metadata: {
18524
+ sourceType: "ai_generated",
18525
+ metadata: compactRecord4({
17556
18526
  confidence: input.confidence,
17557
18527
  beliefIds: input.beliefIds
17558
- },
18528
+ }),
18529
+ rationale: input.rationale ?? input.reasoning ?? "Recorded judgment evidence",
17559
18530
  trustedBypassAccessCheck: input.trustedBypassAccessCheck ?? true
17560
- },
18531
+ }),
17561
18532
  context
17562
18533
  )
17563
18534
  }
@@ -17575,9 +18546,12 @@ var judgmentsContracts = [
17575
18546
  module: "edges",
17576
18547
  functionName: "getLineage",
17577
18548
  kind: "query",
17578
- inputProjection: (input) => ({
17579
- ...input,
17580
- nodeId: input.nodeId ?? input.id
18549
+ inputProjection: (input) => compactRecord4({
18550
+ nodeId: input.nodeId ?? input.id,
18551
+ maxDepth: input.maxDepth ?? input.depth,
18552
+ mode: input.mode,
18553
+ minLayer: input.minLayer,
18554
+ maxLayer: input.maxLayer
17581
18555
  })
17582
18556
  }
17583
18557
  })
@@ -17703,7 +18677,10 @@ var coordinationContracts = [
17703
18677
  module: "coordination",
17704
18678
  functionName: "getInbox",
17705
18679
  kind: "query",
17706
- injectSessionId: "sessionId"
18680
+ injectSessionId: "sessionId",
18681
+ inputProjection: (input) => compactRecord4({
18682
+ limit: input.limit
18683
+ })
17707
18684
  }
17708
18685
  }),
17709
18686
  surfaceContract({
@@ -17721,7 +18698,6 @@ var coordinationContracts = [
17721
18698
  kind: "mutation",
17722
18699
  injectSessionId: "sessionId",
17723
18700
  inputProjection: (input) => ({
17724
- ...input,
17725
18701
  touchedFiles: stringArray(input.touchedFiles) ?? stringArray(input.files) ?? stringArray(input.paths) ?? []
17726
18702
  })
17727
18703
  }
@@ -17738,7 +18714,10 @@ var coordinationContracts = [
17738
18714
  convex: {
17739
18715
  module: "worktrees",
17740
18716
  functionName: "get",
17741
- kind: "query"
18717
+ kind: "query",
18718
+ inputProjection: (input) => compactRecord4({
18719
+ worktreeId: input.worktreeId ?? input.id
18720
+ })
17742
18721
  }
17743
18722
  })
17744
18723
  ];
@@ -17757,7 +18736,13 @@ var pipelineContracts = [
17757
18736
  convex: {
17758
18737
  module: "worktrees",
17759
18738
  functionName: "listAll",
17760
- kind: "query"
18739
+ kind: "query",
18740
+ inputProjection: (input) => compactRecord4({
18741
+ status: input.status,
18742
+ lane: input.lane,
18743
+ campaign: input.campaign,
18744
+ limit: input.limit
18745
+ })
17761
18746
  }
17762
18747
  }),
17763
18748
  surfaceContract({
@@ -17807,43 +18792,63 @@ var recordScopeLearningArgs = z.object({
17807
18792
  linkedBeliefNodeId: z.string().optional().describe("Optional belief to attach evidence to"),
17808
18793
  evidenceRelation: z.enum(["supports", "contradicts"]).optional().describe("Relation to linked belief"),
17809
18794
  confidence: z.number().optional().describe("Optional confidence in [0,1]"),
18795
+ rationale: z.string().optional().describe("Why this learning should enter the reasoning graph"),
17810
18796
  createQuestionText: z.string().optional().describe("Optional follow-up question text"),
17811
18797
  createBeliefText: z.string().optional().describe("Optional new belief text"),
17812
18798
  beliefType: z.string().optional().describe("Optional belief type for createBeliefText")
17813
18799
  });
17814
- var learningInput = (input, context) => withUserId(
17815
- {
17816
- ...input,
17817
- text: input.summary ?? input.text,
17818
- title: input.title ?? input.summary ?? "Scope learning",
17819
- content: input.body ?? input.content ?? input.summary,
17820
- kind: input.kind ?? input.sourceKind ?? "learning",
17821
- tags: input.tags ?? [],
17822
- metadata: {
17823
- sourceRef: input.sourceRef,
17824
- sourceKind: input.sourceKind,
17825
- touchedPaths: input.touchedPaths
17826
- },
17827
- trustedBypassAccessCheck: input.trustedBypassAccessCheck ?? true
17828
- },
17829
- context
17830
- );
18800
+ var learningInput = (input, context) => {
18801
+ const sourceKind = input.sourceKind ?? input.externalSourceType;
18802
+ return withUserId(
18803
+ compactRecord4({
18804
+ projectId: input.projectId,
18805
+ topicId: input.topicId,
18806
+ text: input.summary ?? input.text,
18807
+ title: input.title ?? input.summary ?? "Scope learning",
18808
+ content: input.body ?? input.content ?? input.summary,
18809
+ contentType: input.contentType,
18810
+ kind: input.kind ?? "learning",
18811
+ tags: input.tags ?? [],
18812
+ sourceType: input.sourceType,
18813
+ externalSourceType: input.externalSourceType ?? input.sourceKind,
18814
+ sourceUrl: input.sourceUrl,
18815
+ metadata: compactRecord4({
18816
+ ...recordValue2(input.metadata),
18817
+ sourceRef: input.sourceRef,
18818
+ sourceKind,
18819
+ touchedPaths: input.touchedPaths,
18820
+ createQuestionText: input.createQuestionText,
18821
+ createBeliefText: input.createBeliefText,
18822
+ beliefType: input.beliefType
18823
+ }),
18824
+ linkedBeliefNodeId: input.linkedBeliefNodeId,
18825
+ evidenceRelation: input.evidenceRelation,
18826
+ confidence: input.confidence,
18827
+ rationale: input.rationale ?? input.reasoning ?? input.summary ?? input.text ?? "Recorded scope learning",
18828
+ trustedBypassAccessCheck: input.trustedBypassAccessCheck ?? true
18829
+ }),
18830
+ context
18831
+ );
18832
+ };
17831
18833
  var attemptInput = (input, context) => withUserId(
17832
- {
17833
- ...input,
18834
+ compactRecord4({
18835
+ projectId: input.projectId,
18836
+ topicId: input.topicId,
17834
18837
  text: input.description,
17835
18838
  title: input.title ?? input.description,
17836
18839
  content: input.errorMessage ?? input.description,
17837
18840
  kind: "code_attempt",
17838
18841
  tags: ["code_attempt"],
17839
- metadata: {
18842
+ metadata: compactRecord4({
18843
+ ...recordValue2(input.metadata),
17840
18844
  filePaths: input.filePaths,
17841
18845
  filePath: input.filePath,
17842
18846
  errorMessage: input.errorMessage,
17843
18847
  linkedBeliefId: input.linkedBeliefId
17844
- },
18848
+ }),
18849
+ rationale: input.rationale ?? input.reasoning ?? input.errorMessage ?? input.description ?? "Recorded implementation attempt",
17845
18850
  trustedBypassAccessCheck: input.trustedBypassAccessCheck ?? true
17846
- },
18851
+ }),
17847
18852
  context
17848
18853
  );
17849
18854
  var codingContracts = [
@@ -17900,7 +18905,13 @@ var codingContracts = [
17900
18905
  convex: {
17901
18906
  module: "evidence",
17902
18907
  functionName: "getByTopic",
17903
- kind: "query"
18908
+ kind: "query",
18909
+ inputProjection: (input) => compactRecord4({
18910
+ topicId: input.topicId,
18911
+ limit: input.limit,
18912
+ status: input.status,
18913
+ userId: input.userId
18914
+ })
17904
18915
  }
17905
18916
  }),
17906
18917
  surfaceContract({
@@ -17915,7 +18926,13 @@ var codingContracts = [
17915
18926
  convex: {
17916
18927
  module: "evidence",
17917
18928
  functionName: "getByTopic",
17918
- kind: "query"
18929
+ kind: "query",
18930
+ inputProjection: (input) => compactRecord4({
18931
+ topicId: input.topicId,
18932
+ limit: input.limit,
18933
+ status: input.status,
18934
+ userId: input.userId
18935
+ })
17919
18936
  }
17920
18937
  }),
17921
18938
  surfaceContract({
@@ -17947,9 +18964,11 @@ var codingContracts = [
17947
18964
  module: "evidence",
17948
18965
  functionName: "getByTopic",
17949
18966
  kind: "query",
17950
- inputProjection: (input) => ({
17951
- ...input,
17952
- topicId: input.topicId ?? input.query
18967
+ inputProjection: (input) => compactRecord4({
18968
+ topicId: input.topicId ?? input.query,
18969
+ limit: input.limit,
18970
+ status: input.status,
18971
+ userId: input.userId
17953
18972
  })
17954
18973
  }
17955
18974
  })
@@ -18926,7 +19945,10 @@ function createWorktreeHandlers(context) {
18926
19945
  beliefIds: readStringArray(params, "beliefIds"),
18927
19946
  autoShape: readBoolean(params, "autoShape"),
18928
19947
  domainPackId: readString2(params, "domainPackId"),
18929
- executionOrder: typeof params.executionOrder === "number" ? params.executionOrder : void 0,
19948
+ campaign: typeof params.campaign === "number" ? params.campaign : void 0,
19949
+ lane: readString2(params, "lane"),
19950
+ laneOrderInCampaign: typeof params.laneOrderInCampaign === "number" ? params.laneOrderInCampaign : void 0,
19951
+ orderInLane: typeof params.orderInLane === "number" ? params.orderInLane : void 0,
18930
19952
  dependsOn: readStringArray(params, "dependsOn"),
18931
19953
  blocks: readStringArray(params, "blocks"),
18932
19954
  gate: readString2(params, "gate")