@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/gateway.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { z } from 'zod';
2
+ import { v } from 'convex/values';
2
3
  import { basename, extname } from 'path';
3
4
  import { randomUUID } from 'crypto';
4
5
 
@@ -445,6 +446,28 @@ defineTable({
445
446
  { kind: "index", name: "by_createdAt", columns: ["createdAt"] }
446
447
  ]
447
448
  });
449
+ defineTable({
450
+ name: "neo4jSyncQueue",
451
+ component: "kernel",
452
+ category: "infra",
453
+ shape: z.object({
454
+ "entityType": z.enum(["node", "edge"]),
455
+ "entityId": z.string(),
456
+ "operation": z.enum(["upsert", "delete"]),
457
+ "attempts": z.number(),
458
+ "maxAttempts": z.number(),
459
+ "lastAttemptAt": z.number().optional(),
460
+ "lastError": z.string().optional(),
461
+ "status": z.enum(["pending", "in_progress", "failed", "succeeded"]),
462
+ "createdAt": z.number(),
463
+ "updatedAt": z.number()
464
+ }),
465
+ indices: [
466
+ { kind: "index", name: "by_status", columns: ["status"] },
467
+ { kind: "index", name: "by_entity", columns: ["entityType", "entityId"] },
468
+ { kind: "index", name: "by_status_attempts", columns: ["status", "attempts"] }
469
+ ]
470
+ });
448
471
  defineTable({
449
472
  name: "backgroundJobRuns",
450
473
  component: "kernel",
@@ -514,9 +537,9 @@ defineTable({
514
537
  category: "epistemic",
515
538
  shape: z.object({
516
539
  "beliefId": z.string(),
517
- "belief": z.number().optional(),
518
- "disbelief": z.number().optional(),
519
- "uncertainty": z.number().optional(),
540
+ "belief": z.number(),
541
+ "disbelief": z.number(),
542
+ "uncertainty": z.number(),
520
543
  "baseRate": z.number(),
521
544
  "slOperator": z.string().optional(),
522
545
  "confidence": z.number(),
@@ -525,10 +548,12 @@ defineTable({
525
548
  "certainty": z.number().optional(),
526
549
  "assessedAt": z.number(),
527
550
  "assessedBy": z.string(),
528
- "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"]),
551
+ "trigger": z.enum(["initial", "evidence_added", "evidence_removed", "contradiction_detected", "contradiction_resolved", "propagation", "agent_assessment", "worktree_outcome", "worktree_completed", "fusion", "discount", "deduction", "backfill_synthetic"]),
529
552
  "rationale": z.string().optional(),
530
553
  "triggeringEvidenceId": z.string().optional(),
531
554
  "triggeringEvidenceIds": z.array(z.string()).optional(),
555
+ "triggeringQuestionId": z.string().optional(),
556
+ "triggeringAnswerId": z.string().optional(),
532
557
  "triggeringContradictionId": idOf("contradictions").optional(),
533
558
  "triggeringWorktreeId": z.string().optional(),
534
559
  "triggeringAgentId": z.string().optional(),
@@ -1211,7 +1236,7 @@ defineTable({
1211
1236
  "credentialRef": z.string(),
1212
1237
  "tenantId": idOf("tenants"),
1213
1238
  "target": z.enum(["kernelDeployment", "appDeployment"]),
1214
- "environment": z.enum(["dev", "prod"]),
1239
+ "environment": z.enum(["dev", "staging", "prod"]),
1215
1240
  "encryptedDeployKey": z.string(),
1216
1241
  "encryptionVersion": z.string(),
1217
1242
  "keyFingerprint": z.string(),
@@ -3880,13 +3905,13 @@ defineTable({
3880
3905
  "rationale": z.string().optional(),
3881
3906
  "confidenceImpact": z.enum(["high", "medium", "low"]).optional(),
3882
3907
  "hypothesis": z.string().optional(),
3883
- "executionOrder": z.number().optional(),
3884
3908
  "dependsOn": z.array(idOf("worktrees")).optional(),
3885
3909
  "blocks": z.array(idOf("worktrees")).optional(),
3886
3910
  "gate": z.string().optional(),
3887
- "track": z.string().optional(),
3888
- "trackPosition": z.number().optional(),
3889
- "executionBand": z.number().optional(),
3911
+ "campaign": z.number().optional(),
3912
+ "lane": z.string().optional(),
3913
+ "laneOrderInCampaign": z.number().optional(),
3914
+ "orderInLane": z.number().optional(),
3890
3915
  "startDate": z.number(),
3891
3916
  "endDate": z.number(),
3892
3917
  "durationWeeks": z.number(),
@@ -4134,10 +4159,469 @@ defineTable({
4134
4159
  { kind: "index", name: "by_topicId_index", columns: ["topicId", "index"] },
4135
4160
  { kind: "index", name: "by_worktreeType", columns: ["topicId", "worktreeType"] },
4136
4161
  { kind: "index", name: "by_topicId_priority", columns: ["topicId", "priority"] },
4162
+ { kind: "index", name: "by_topicId_campaign_lane_order", columns: ["topicId", "campaign", "laneOrderInCampaign", "orderInLane"] },
4163
+ { kind: "index", name: "by_topicId_lane_order", columns: ["topicId", "lane", "orderInLane"] },
4137
4164
  { kind: "index", name: "by_topicId_branch", columns: ["topicId", "targetBranch"] },
4138
4165
  { kind: "index", name: "by_topicId_scope", columns: ["topicId", "worktreeScope"] }
4139
4166
  ]
4140
4167
  });
4168
+ z.object({
4169
+ manifestVersion: z.string(),
4170
+ componentName: z.enum(["kernel", "identity"]),
4171
+ tier: z.enum(["K", "I"]),
4172
+ packageVersion: z.string(),
4173
+ tables: z.array(
4174
+ z.object({
4175
+ name: z.string(),
4176
+ fields: z.array(
4177
+ z.object({
4178
+ name: z.string(),
4179
+ type: z.string(),
4180
+ optional: z.boolean(),
4181
+ validator: z.string().optional()
4182
+ })
4183
+ )
4184
+ })
4185
+ )
4186
+ });
4187
+ var SL_EPSILON = 1e-9;
4188
+ z.object({
4189
+ belief: z.number(),
4190
+ disbelief: z.number(),
4191
+ uncertainty: z.number(),
4192
+ baseRate: z.number()
4193
+ }).refine(
4194
+ (o) => Math.abs(o.belief + o.disbelief + o.uncertainty - 1) < SL_EPSILON,
4195
+ {
4196
+ message: "SL invariant b+d+u=1 violated at API boundary"
4197
+ }
4198
+ );
4199
+ var EpistemicNodeTypeSchema = z.enum([
4200
+ "belief",
4201
+ "evidence",
4202
+ "question",
4203
+ "answer",
4204
+ "topic",
4205
+ "edge",
4206
+ "ontology",
4207
+ "lens",
4208
+ "contradiction"
4209
+ ]);
4210
+ var GraphRefSchema = z.discriminatedUnion("kind", [
4211
+ z.object({
4212
+ kind: z.literal("epistemic_node"),
4213
+ nodeId: z.string(),
4214
+ nodeType: EpistemicNodeTypeSchema
4215
+ }),
4216
+ z.object({
4217
+ kind: z.literal("external_belief"),
4218
+ ref: z.object({
4219
+ tenantId: z.string(),
4220
+ beliefId: z.string()
4221
+ })
4222
+ })
4223
+ ]);
4224
+ var graphRefKind = z.enum(["epistemic_node", "external_belief"]);
4225
+ var EdgePolicyEntrySchema = z.object({
4226
+ edgeType: z.string(),
4227
+ fromKinds: z.array(graphRefKind),
4228
+ fromNodeTypes: z.array(EpistemicNodeTypeSchema).optional(),
4229
+ toKinds: z.array(graphRefKind),
4230
+ toNodeTypes: z.array(EpistemicNodeTypeSchema).optional(),
4231
+ description: z.string()
4232
+ });
4233
+ z.object({
4234
+ manifestVersion: z.literal("1.0.0"),
4235
+ policies: z.array(EdgePolicyEntrySchema)
4236
+ });
4237
+ function findEdgePolicy(manifest, edgeType) {
4238
+ return manifest.policies.find((policy) => policy.edgeType === edgeType);
4239
+ }
4240
+ function nodeTypeAllowed(allowed, ref) {
4241
+ return ref.kind !== "epistemic_node" || !allowed || allowed.includes(ref.nodeType);
4242
+ }
4243
+ function assertEdgePolicyAllowed(manifest, edgeType, from, to) {
4244
+ const policy = findEdgePolicy(manifest, edgeType);
4245
+ const allowed = Boolean(policy) && policy.fromKinds.includes(from.kind) && policy.toKinds.includes(to.kind) && nodeTypeAllowed(policy.fromNodeTypes, from) && nodeTypeAllowed(policy.toNodeTypes, to);
4246
+ if (!allowed) {
4247
+ const error = new Error(
4248
+ `Edge policy violation for ${edgeType}: ${from.kind} -> ${to.kind}`
4249
+ );
4250
+ error.code = "POLICY_VIOLATION";
4251
+ error.details = { code: "POLICY_VIOLATION", edgeType, from, to };
4252
+ throw error;
4253
+ }
4254
+ }
4255
+
4256
+ // ../contracts/src/manifests/edge-policy-manifest.data.ts
4257
+ var edgePolicyManifest = {
4258
+ policies: [
4259
+ {
4260
+ edgeType: "evidence_derived_from_evidence",
4261
+ fromKinds: ["epistemic_node"],
4262
+ fromNodeTypes: ["evidence"],
4263
+ toKinds: ["epistemic_node"],
4264
+ toNodeTypes: ["evidence"],
4265
+ description: "Evidence E2 was synthesized from evidence E1 by a transformation. Provides chain-of-evidence lineage."
4266
+ },
4267
+ {
4268
+ edgeType: "evidence_supports_belief",
4269
+ fromKinds: ["epistemic_node"],
4270
+ fromNodeTypes: ["evidence"],
4271
+ toKinds: ["epistemic_node"],
4272
+ toNodeTypes: ["belief"],
4273
+ description: "Existing link_evidence_to_belief semantics promoted to the create_edge policy source."
4274
+ },
4275
+ {
4276
+ edgeType: "evidence_supports_question",
4277
+ fromKinds: ["epistemic_node"],
4278
+ fromNodeTypes: ["evidence"],
4279
+ toKinds: ["epistemic_node"],
4280
+ toNodeTypes: ["question"],
4281
+ description: "Existing link_evidence_to_question semantics promoted to the create_edge policy source."
4282
+ }
4283
+ ]
4284
+ };
4285
+ z.object({
4286
+ manifestVersion: z.literal("1.0.0"),
4287
+ rules: z.array(
4288
+ z.object({
4289
+ invariant: z.string(),
4290
+ description: z.string(),
4291
+ checker: z.enum(["ast", "manifest", "runtime"]),
4292
+ severity: z.enum(["block_publish", "block_pr", "warn"])
4293
+ })
4294
+ )
4295
+ });
4296
+
4297
+ // ../contracts/src/projections/projection-dsl.ts
4298
+ function defineProjection(def) {
4299
+ return def;
4300
+ }
4301
+
4302
+ // ../contracts/src/projections/create-evidence.projection.ts
4303
+ var jsonRecordSchema = z.record(z.unknown());
4304
+ var createEvidenceInputSchemaBase = z.object({
4305
+ projectId: z.string().optional(),
4306
+ topicId: z.string().optional(),
4307
+ text: z.string().optional(),
4308
+ canonicalText: z.string().optional(),
4309
+ title: z.string().optional(),
4310
+ content: z.string().optional(),
4311
+ contentType: z.string().optional(),
4312
+ kind: z.string().optional(),
4313
+ tags: z.array(z.string()).optional(),
4314
+ source: z.string().optional(),
4315
+ sourceUrl: z.string().optional(),
4316
+ sourceType: z.string().optional(),
4317
+ externalSourceType: z.string().optional(),
4318
+ sourceQuestionId: z.string().optional(),
4319
+ methodology: z.string().optional(),
4320
+ informationAsymmetry: z.string().optional(),
4321
+ sourceDescription: z.string().optional(),
4322
+ targetId: z.string().optional(),
4323
+ targetNodeId: z.string().optional(),
4324
+ linkedBeliefNodeId: z.string().optional(),
4325
+ evidenceRelation: z.enum(["supports", "contradicts", "neutral"]).optional(),
4326
+ confidence: z.number().optional(),
4327
+ weight: z.number().optional(),
4328
+ reasoning: z.string().optional(),
4329
+ rationale: z.string(),
4330
+ metadata: jsonRecordSchema.optional(),
4331
+ trustedBypassAccessCheck: z.boolean().optional()
4332
+ }).passthrough();
4333
+ var createEvidenceInputSchema = createEvidenceInputSchemaBase.refine(
4334
+ (input) => Boolean(input.text ?? input.canonicalText),
4335
+ {
4336
+ message: "create_evidence requires text",
4337
+ path: ["text"]
4338
+ }
4339
+ );
4340
+ function compactRecord(input) {
4341
+ return Object.fromEntries(
4342
+ Object.entries(input).filter(([, value]) => value !== void 0)
4343
+ );
4344
+ }
4345
+ function recordValue(value) {
4346
+ return value && typeof value === "object" && !Array.isArray(value) ? value : {};
4347
+ }
4348
+ var createEvidenceProjection = defineProjection({
4349
+ contractName: "create_evidence",
4350
+ inputSchema: createEvidenceInputSchema,
4351
+ project: (input) => {
4352
+ const text = input.text ?? input.canonicalText;
4353
+ const weight = typeof input.weight === "number" ? input.weight : void 0;
4354
+ return compactRecord({
4355
+ projectId: input.projectId,
4356
+ topicId: input.topicId,
4357
+ text,
4358
+ title: input.title ?? text,
4359
+ content: input.content ?? text,
4360
+ contentType: input.contentType,
4361
+ kind: input.kind,
4362
+ tags: input.tags,
4363
+ sourceType: input.sourceType,
4364
+ externalSourceType: input.externalSourceType,
4365
+ sourceUrl: input.sourceUrl ?? input.source,
4366
+ sourceQuestionId: input.sourceQuestionId,
4367
+ methodology: input.methodology,
4368
+ informationAsymmetry: input.informationAsymmetry,
4369
+ sourceDescription: input.sourceDescription,
4370
+ metadata: compactRecord({
4371
+ ...recordValue(input.metadata),
4372
+ source: input.source,
4373
+ targetId: input.targetId,
4374
+ targetNodeId: input.targetNodeId,
4375
+ weight,
4376
+ reasoning: input.reasoning,
4377
+ rationale: input.rationale
4378
+ }),
4379
+ linkedBeliefNodeId: input.linkedBeliefNodeId ?? input.targetNodeId ?? input.targetId,
4380
+ evidenceRelation: input.evidenceRelation ?? (weight === void 0 ? void 0 : weight < 0 ? "contradicts" : "supports"),
4381
+ confidence: input.confidence ?? (weight === void 0 ? void 0 : Math.min(1, Math.max(0, Math.abs(weight)))),
4382
+ rationale: input.rationale,
4383
+ trustedBypassAccessCheck: input.trustedBypassAccessCheck ?? true
4384
+ });
4385
+ },
4386
+ convexArgsValidator: v.object({
4387
+ projectId: v.optional(v.string()),
4388
+ topicId: v.optional(v.string()),
4389
+ text: v.string(),
4390
+ title: v.optional(v.string()),
4391
+ content: v.optional(v.string()),
4392
+ contentType: v.optional(v.string()),
4393
+ kind: v.optional(v.string()),
4394
+ tags: v.optional(v.array(v.string())),
4395
+ sourceType: v.optional(v.string()),
4396
+ externalSourceType: v.optional(v.string()),
4397
+ sourceUrl: v.optional(v.string()),
4398
+ sourceQuestionId: v.optional(v.string()),
4399
+ methodology: v.optional(v.string()),
4400
+ informationAsymmetry: v.optional(v.string()),
4401
+ sourceDescription: v.optional(v.string()),
4402
+ metadata: v.optional(v.record(v.string(), v.any())),
4403
+ linkedBeliefNodeId: v.optional(v.string()),
4404
+ evidenceRelation: v.optional(
4405
+ v.union(
4406
+ v.literal("supports"),
4407
+ v.literal("contradicts"),
4408
+ v.literal("neutral")
4409
+ )
4410
+ ),
4411
+ confidence: v.optional(v.number()),
4412
+ rationale: v.string(),
4413
+ trustedBypassAccessCheck: v.optional(v.boolean())
4414
+ })
4415
+ });
4416
+ var beliefStatusSchema = z.enum(["active", "superseded", "archived", "unscored", "scored"]).optional().describe("Filter by belief lifecycle or scoring status");
4417
+ var listBeliefsInputSchema = z.object({
4418
+ topicId: z.string().describe("Topic scope"),
4419
+ worktreeId: z.string().optional().describe("Filter to worktree scope"),
4420
+ status: beliefStatusSchema,
4421
+ minConfidence: z.number().optional().describe("Minimum confidence threshold"),
4422
+ limit: z.number().optional().describe("Maximum results"),
4423
+ includeEdgeAssociated: z.boolean().optional().describe("Include beliefs associated to the topic through edges")
4424
+ });
4425
+ function kernelStatus(status) {
4426
+ return status === "active" || status === "superseded" || status === "archived" ? status : void 0;
4427
+ }
4428
+ function compactRecord2(input) {
4429
+ return Object.fromEntries(
4430
+ Object.entries(input).filter(([, value]) => value !== void 0)
4431
+ );
4432
+ }
4433
+ var listBeliefsProjection = defineProjection({
4434
+ contractName: "list_beliefs",
4435
+ inputSchema: listBeliefsInputSchema,
4436
+ project: (input) => compactRecord2({
4437
+ topicId: input.topicId,
4438
+ status: kernelStatus(input.status),
4439
+ limit: input.limit,
4440
+ includeEdgeAssociated: input.includeEdgeAssociated
4441
+ }),
4442
+ convexArgsValidator: v.object({
4443
+ topicId: v.string(),
4444
+ status: v.optional(
4445
+ v.union(
4446
+ v.literal("active"),
4447
+ v.literal("superseded"),
4448
+ v.literal("archived")
4449
+ )
4450
+ ),
4451
+ limit: v.optional(v.number()),
4452
+ includeEdgeAssociated: v.optional(v.boolean())
4453
+ })
4454
+ });
4455
+ var taskStatusSchema = z.enum(["todo", "in_progress", "blocked", "done"]).optional().describe("Filter by task status");
4456
+ var listTasksInputSchema = z.object({
4457
+ topicId: z.string().describe("Topic scope"),
4458
+ worktreeId: z.string().optional().describe("Alias for linkedWorktreeId"),
4459
+ linkedWorktreeId: z.string().optional().describe("Filter to tasks linked to this worktree"),
4460
+ status: taskStatusSchema,
4461
+ limit: z.number().optional().describe("Maximum results")
4462
+ });
4463
+ function compactRecord3(input) {
4464
+ return Object.fromEntries(
4465
+ Object.entries(input).filter(([, value]) => value !== void 0)
4466
+ );
4467
+ }
4468
+ var listTasksProjection = defineProjection({
4469
+ contractName: "list_tasks",
4470
+ inputSchema: listTasksInputSchema,
4471
+ project: (input) => compactRecord3({
4472
+ topicId: input.topicId,
4473
+ status: input.status,
4474
+ userId: void 0,
4475
+ limit: input.limit,
4476
+ linkedWorktreeId: input.linkedWorktreeId ?? input.worktreeId
4477
+ }),
4478
+ convexArgsValidator: v.object({
4479
+ topicId: v.string(),
4480
+ status: v.optional(
4481
+ v.union(
4482
+ v.literal("todo"),
4483
+ v.literal("in_progress"),
4484
+ v.literal("blocked"),
4485
+ v.literal("done")
4486
+ )
4487
+ ),
4488
+ limit: v.optional(v.number()),
4489
+ linkedWorktreeId: v.optional(v.string())
4490
+ })
4491
+ });
4492
+ var confidenceTriggerSchema = z.enum([
4493
+ "evidence_added",
4494
+ "evidence_removed",
4495
+ "contradiction_resolved",
4496
+ "agent_assessment",
4497
+ "worktree_outcome",
4498
+ "worktree_completed",
4499
+ "contradiction_detected",
4500
+ "answer_recorded",
4501
+ "fusion",
4502
+ "discount",
4503
+ "deduction",
4504
+ "backfill_synthetic"
4505
+ ]);
4506
+ var provenanceSchema = z.object({
4507
+ evidence: z.string().optional(),
4508
+ question: z.string().optional(),
4509
+ answer: z.string().optional(),
4510
+ contradiction: z.string().optional(),
4511
+ worktree: z.string().optional()
4512
+ });
4513
+ var slOpinionProjectionSchema = z.object({
4514
+ belief: z.number(),
4515
+ disbelief: z.number(),
4516
+ uncertainty: z.number(),
4517
+ baseRate: z.number()
4518
+ });
4519
+ var modulateConfidenceInputObjectSchema = z.object({
4520
+ nodeId: z.string().optional(),
4521
+ beliefNodeId: z.string().optional(),
4522
+ worktreeId: z.string().optional(),
4523
+ opinion: slOpinionProjectionSchema.optional(),
4524
+ belief: z.number().optional(),
4525
+ disbelief: z.number().optional(),
4526
+ uncertainty: z.number().optional(),
4527
+ baseRate: z.number().optional(),
4528
+ trigger: confidenceTriggerSchema,
4529
+ provenance: provenanceSchema.optional(),
4530
+ triggeringEvidenceId: z.string().optional(),
4531
+ triggeringQuestionId: z.string().optional(),
4532
+ triggeringAnswerId: z.string().optional(),
4533
+ triggeringContradictionId: z.string().optional(),
4534
+ triggeringWorktreeId: z.string().optional(),
4535
+ rationale: z.string(),
4536
+ trustedBypassAccessCheck: z.boolean().optional()
4537
+ });
4538
+ var modulateConfidenceInputSchema = modulateConfidenceInputObjectSchema.superRefine((input, ctx) => {
4539
+ if (hasProvenance(input)) {
4540
+ return;
4541
+ }
4542
+ ctx.addIssue({
4543
+ code: z.ZodIssueCode.custom,
4544
+ message: "modulate_confidence requires evidence, question, answer, contradiction, or worktree provenance",
4545
+ path: ["provenance"]
4546
+ });
4547
+ });
4548
+ var modulateConfidenceProjection = defineProjection({
4549
+ contractName: "modulate_confidence",
4550
+ inputSchema: modulateConfidenceInputSchema,
4551
+ project: (input) => {
4552
+ const nodeId = input.beliefNodeId ?? input.nodeId;
4553
+ if (!nodeId) {
4554
+ throw new Error("modulate_confidence requires beliefNodeId or nodeId");
4555
+ }
4556
+ const opinion = input.opinion ?? {
4557
+ belief: requireNumber(input.belief, "belief"),
4558
+ disbelief: requireNumber(input.disbelief, "disbelief"),
4559
+ uncertainty: requireNumber(input.uncertainty, "uncertainty"),
4560
+ baseRate: requireNumber(input.baseRate, "baseRate")
4561
+ };
4562
+ assertProvenance(input);
4563
+ return {
4564
+ nodeId,
4565
+ worktreeId: input.worktreeId,
4566
+ belief: opinion.belief,
4567
+ disbelief: opinion.disbelief,
4568
+ uncertainty: opinion.uncertainty,
4569
+ baseRate: opinion.baseRate,
4570
+ trigger: input.trigger === "answer_recorded" ? "agent_assessment" : input.trigger,
4571
+ triggeringEvidenceId: input.provenance?.evidence ?? input.triggeringEvidenceId,
4572
+ triggeringQuestionId: input.provenance?.question ?? input.triggeringQuestionId,
4573
+ triggeringAnswerId: input.provenance?.answer ?? input.triggeringAnswerId,
4574
+ triggeringContradictionId: input.provenance?.contradiction ?? input.triggeringContradictionId,
4575
+ triggeringWorktreeId: input.provenance?.worktree ?? input.triggeringWorktreeId,
4576
+ rationale: input.rationale,
4577
+ trustedBypassAccessCheck: input.trustedBypassAccessCheck ?? true
4578
+ };
4579
+ },
4580
+ convexArgsValidator: v.object({
4581
+ nodeId: v.string(),
4582
+ worktreeId: v.optional(v.string()),
4583
+ belief: v.number(),
4584
+ disbelief: v.number(),
4585
+ uncertainty: v.number(),
4586
+ baseRate: v.number(),
4587
+ trigger: v.union(
4588
+ v.literal("evidence_added"),
4589
+ v.literal("evidence_removed"),
4590
+ v.literal("worktree_completed"),
4591
+ v.literal("contradiction_detected"),
4592
+ v.literal("contradiction_resolved"),
4593
+ v.literal("agent_assessment"),
4594
+ v.literal("worktree_outcome"),
4595
+ v.literal("fusion"),
4596
+ v.literal("discount"),
4597
+ v.literal("deduction"),
4598
+ v.literal("backfill_synthetic")
4599
+ ),
4600
+ triggeringEvidenceId: v.optional(v.string()),
4601
+ triggeringQuestionId: v.optional(v.string()),
4602
+ triggeringAnswerId: v.optional(v.string()),
4603
+ triggeringContradictionId: v.optional(v.string()),
4604
+ triggeringWorktreeId: v.optional(v.string()),
4605
+ rationale: v.string(),
4606
+ trustedBypassAccessCheck: v.optional(v.boolean())
4607
+ })
4608
+ });
4609
+ function requireNumber(value, field) {
4610
+ if (value === void 0) {
4611
+ throw new Error(`modulate_confidence requires ${field}`);
4612
+ }
4613
+ return value;
4614
+ }
4615
+ function assertProvenance(input) {
4616
+ if (!hasProvenance(input)) {
4617
+ throw new Error(
4618
+ "modulate_confidence requires evidence, question, answer, contradiction, or worktree provenance"
4619
+ );
4620
+ }
4621
+ }
4622
+ function hasProvenance(input) {
4623
+ 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);
4624
+ }
4141
4625
 
4142
4626
  // ../contracts/src/lens-workflow.contract.ts
4143
4627
  var LENS_PERSPECTIVE_TYPES = [
@@ -4151,7 +4635,7 @@ var LENS_PERSPECTIVE_TYPES = [
4151
4635
  // ../contracts/src/tool-contracts.ts
4152
4636
  var CREATE_BELIEF = {
4153
4637
  name: "create_belief",
4154
- 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.",
4638
+ 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.",
4155
4639
  parameters: {
4156
4640
  canonicalText: {
4157
4641
  type: "string",
@@ -4163,7 +4647,7 @@ var CREATE_BELIEF = {
4163
4647
  },
4164
4648
  baseRate: {
4165
4649
  type: "number",
4166
- description: "Required prior probability used to seed the vacuous opinion `(0, 0, 1, a)` at creation time."
4650
+ description: "Prior probability used to seed the vacuous opinion `(0, 0, 1, a)` at creation time. Defaults to 0.5 when omitted."
4167
4651
  },
4168
4652
  beliefType: {
4169
4653
  type: "string",
@@ -4174,7 +4658,7 @@ var CREATE_BELIEF = {
4174
4658
  description: "Optional extra metadata merged into the node (e.g., { codeAnchors: ['path/to/file.ts'] } for coding intelligence)"
4175
4659
  }
4176
4660
  },
4177
- required: ["canonicalText", "baseRate"],
4661
+ required: ["canonicalText"],
4178
4662
  response: {
4179
4663
  description: "The created canonical belief record",
4180
4664
  fields: {
@@ -4237,7 +4721,7 @@ var REFINE_BELIEF = {
4237
4721
  };
4238
4722
  var MODULATE_CONFIDENCE = {
4239
4723
  name: "modulate_confidence",
4240
- 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.",
4724
+ 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.",
4241
4725
  parameters: {
4242
4726
  nodeId: { type: "string", description: "The belief to score" },
4243
4727
  belief: {
@@ -4256,9 +4740,9 @@ var MODULATE_CONFIDENCE = {
4256
4740
  type: "number",
4257
4741
  description: "Subjective-logic base rate `a` in [0, 1]. Required for tuple payloads."
4258
4742
  },
4259
- confidence: {
4260
- type: "number",
4261
- description: "Deprecated scalar confidence value in [0, 1]. Scalar-only payloads are rejected as AMBIGUOUS_SCALAR."
4743
+ worktreeId: {
4744
+ type: "string",
4745
+ description: "Completed worktree that tested this belief when confidence policy requires merge-backed scoring."
4262
4746
  },
4263
4747
  trigger: {
4264
4748
  type: "string",
@@ -4273,17 +4757,43 @@ var MODULATE_CONFIDENCE = {
4273
4757
  "worktree_completed",
4274
4758
  "fusion",
4275
4759
  "discount",
4276
- "deduction",
4277
- "manual",
4278
- "decay"
4760
+ "deduction"
4279
4761
  ]
4280
4762
  },
4763
+ triggeringEvidenceId: {
4764
+ type: "string",
4765
+ description: "Evidence node that caused an evidence-triggered modulation"
4766
+ },
4767
+ triggeringQuestionId: {
4768
+ type: "string",
4769
+ description: "Answered question whose resolution supports this modulation"
4770
+ },
4771
+ triggeringAnswerId: {
4772
+ type: "string",
4773
+ description: "Answer node whose content supports this modulation"
4774
+ },
4775
+ triggeringContradictionId: {
4776
+ type: "string",
4777
+ description: "Contradiction record that caused a contradiction-triggered modulation"
4778
+ },
4779
+ triggeringWorktreeId: {
4780
+ type: "string",
4781
+ description: "Completed worktree whose outcome caused a worktree-triggered modulation"
4782
+ },
4281
4783
  rationale: {
4282
4784
  type: "string",
4283
4785
  description: "Human-readable explanation of why confidence changed"
4284
4786
  }
4285
4787
  },
4286
- required: ["nodeId", "trigger", "rationale"],
4788
+ required: [
4789
+ "nodeId",
4790
+ "belief",
4791
+ "disbelief",
4792
+ "uncertainty",
4793
+ "baseRate",
4794
+ "trigger",
4795
+ "rationale"
4796
+ ],
4287
4797
  response: {
4288
4798
  description: "Confidence modulation result",
4289
4799
  fields: {
@@ -4477,7 +4987,7 @@ var ADD_EVIDENCE = {
4477
4987
  description: "Optional extra metadata merged into the node (e.g., { codeAnchors: ['path/to/file.ts'], failedApproach: true } for coding intelligence)"
4478
4988
  }
4479
4989
  },
4480
- required: ["canonicalText", "targetNodeId"],
4990
+ required: ["canonicalText", "targetNodeId", "reasoning"],
4481
4991
  response: {
4482
4992
  description: "The created evidence node and its edge",
4483
4993
  fields: {
@@ -4558,9 +5068,21 @@ var ADD_WORKTREE = {
4558
5068
  type: "string",
4559
5069
  description: "Optional domain pack whose shaping hooks should influence generated questions and tasks"
4560
5070
  },
4561
- executionOrder: {
5071
+ campaign: {
5072
+ type: "number",
5073
+ description: "Top-level pipeline campaign number. Campaigns define the outer execution slice."
5074
+ },
5075
+ lane: {
5076
+ type: "string",
5077
+ description: "GitButler-aligned workstream lane name inside the campaign."
5078
+ },
5079
+ laneOrderInCampaign: {
5080
+ type: "number",
5081
+ description: "Ordering for this lane within its campaign."
5082
+ },
5083
+ orderInLane: {
4562
5084
  type: "number",
4563
- description: "Global execution order for this worktree"
5085
+ description: "Position of this worktree inside its lane."
4564
5086
  },
4565
5087
  dependsOn: {
4566
5088
  type: "array",
@@ -5218,6 +5740,10 @@ var CREATE_EVIDENCE = {
5218
5740
  type: "object",
5219
5741
  description: "Optional metadata merged into the canonical evidence node"
5220
5742
  },
5743
+ rationale: {
5744
+ type: "string",
5745
+ description: "Why this evidence should enter the reasoning graph"
5746
+ },
5221
5747
  title: { type: "string", description: "Optional short title" },
5222
5748
  content: { type: "string", description: "Optional long-form content" },
5223
5749
  contentType: {
@@ -5226,7 +5752,7 @@ var CREATE_EVIDENCE = {
5226
5752
  },
5227
5753
  kind: { type: "string", description: "Optional evidence kind" }
5228
5754
  },
5229
- required: ["text"],
5755
+ required: ["text", "rationale"],
5230
5756
  response: {
5231
5757
  description: "The created canonical evidence record",
5232
5758
  fields: {
@@ -5274,7 +5800,7 @@ var LIST_EVIDENCE = {
5274
5800
  limit: { type: "number", description: "Max results" },
5275
5801
  cursor: { type: "string", description: "Pagination cursor" }
5276
5802
  },
5277
- required: [],
5803
+ required: ["topicId"],
5278
5804
  response: {
5279
5805
  description: "Canonical evidence page",
5280
5806
  fields: {
@@ -5459,6 +5985,7 @@ var ANSWER_QUESTION = {
5459
5985
  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.",
5460
5986
  parameters: {
5461
5987
  id: { type: "string", description: "Canonical question ID" },
5988
+ topicId: { type: "string", description: "Topic scope for the answer" },
5462
5989
  text: { type: "string", description: "Answer text" },
5463
5990
  confidence: {
5464
5991
  type: "string",
@@ -5471,7 +5998,7 @@ var ANSWER_QUESTION = {
5471
5998
  },
5472
5999
  rationale: { type: "string", description: "Why this answer is credible" }
5473
6000
  },
5474
- required: ["id", "text"],
6001
+ required: ["id", "topicId", "text"],
5475
6002
  response: {
5476
6003
  description: "Answer result",
5477
6004
  fields: {
@@ -5690,6 +6217,10 @@ var LIST_BELIEFS = {
5690
6217
  minConfidence: {
5691
6218
  type: "number",
5692
6219
  description: "Minimum confidence threshold"
6220
+ },
6221
+ limit: {
6222
+ type: "number",
6223
+ description: "Maximum results"
5693
6224
  }
5694
6225
  },
5695
6226
  required: ["topicId"],
@@ -5706,20 +6237,37 @@ var LIST_BELIEFS = {
5706
6237
  };
5707
6238
  var LIST_WORKTREES = {
5708
6239
  name: "list_worktrees",
5709
- 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.",
6240
+ 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.",
5710
6241
  parameters: {
5711
6242
  topicId: { type: "string", description: "Topic scope" },
5712
6243
  status: {
5713
6244
  type: "string",
5714
6245
  description: "Filter: active, merged, abandoned",
5715
6246
  enum: ["active", "merged", "abandoned"]
6247
+ },
6248
+ groupBy: {
6249
+ type: "string",
6250
+ description: "Optional grouping mode for the response.",
6251
+ enum: ["campaign", "lane", "flat"]
6252
+ },
6253
+ lane: {
6254
+ type: "string",
6255
+ description: "Filter by GitButler-aligned lane name."
6256
+ },
6257
+ campaign: {
6258
+ type: "number",
6259
+ description: "Filter by top-level pipeline campaign number."
6260
+ },
6261
+ limit: {
6262
+ type: "number",
6263
+ description: "Maximum results to return."
5716
6264
  }
5717
6265
  },
5718
6266
  required: ["topicId"],
5719
6267
  response: {
5720
- description: "Worktrees with phase, status, belief count, and creation time",
6268
+ description: "Worktrees with lifecycle phase, campaign, lane, status, belief count, and creation time",
5721
6269
  fields: {
5722
- worktrees: "array \u2014 { worktreeId, title, phase, status, beliefCount, createdAt }"
6270
+ worktrees: "array \u2014 { worktreeId, title, phase, campaign, lane, laneOrderInCampaign, orderInLane, status, beliefCount, createdAt }"
5723
6271
  }
5724
6272
  },
5725
6273
  ownerModule: "workflow-engine",
@@ -5728,7 +6276,7 @@ var LIST_WORKTREES = {
5728
6276
  };
5729
6277
  var LIST_ALL_WORKTREES = {
5730
6278
  name: "list_all_worktrees",
5731
- 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.",
6279
+ 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.",
5732
6280
  parameters: {
5733
6281
  status: {
5734
6282
  type: "string",
@@ -5746,13 +6294,18 @@ var LIST_ALL_WORKTREES = {
5746
6294
  "dismissed"
5747
6295
  ]
5748
6296
  },
5749
- track: {
6297
+ lane: {
5750
6298
  type: "string",
5751
- description: "Filter by track name (e.g., 'ontology', 'tc-scope', 'control-plane', 'dev-portal', 'mcp-sdk-parity')"
6299
+ description: "Filter by lane name (e.g., 'ontology', 'tc-scope', 'control-plane', 'dev-portal', 'mcp-sdk-parity')"
5752
6300
  },
5753
- executionBand: {
6301
+ campaign: {
5754
6302
  type: "number",
5755
- description: "Filter by execution band number (e.g., 1, 2, 3). Returns only worktrees in that parallel execution group."
6303
+ description: "Filter by campaign number (e.g., 1, 2, 3). Returns only worktrees in that campaign."
6304
+ },
6305
+ groupBy: {
6306
+ type: "string",
6307
+ description: "Optional grouping mode for the response.",
6308
+ enum: ["campaign", "lane", "flat"]
5756
6309
  },
5757
6310
  limit: {
5758
6311
  type: "number",
@@ -5763,10 +6316,39 @@ var LIST_ALL_WORKTREES = {
5763
6316
  response: {
5764
6317
  description: "All worktrees across all topics with full pipeline metadata",
5765
6318
  fields: {
5766
- worktrees: "array \u2014 { worktreeId, title, topicId, topicName, phase, status, hypothesis, track, trackPosition, executionBand, executionOrder, dependsOn, blocks, gate, createdAt }",
6319
+ worktrees: "array \u2014 { worktreeId, title, topicId, topicName, phase, status, hypothesis, campaign, lane, laneOrderInCampaign, orderInLane, dependsOn, blocks, gate, createdAt }",
5767
6320
  total: "number \u2014 total count after filtering",
5768
- tracks: "object \u2014 { trackName: count } summary of worktrees per track",
5769
- bands: "object \u2014 { bandNumber: count } summary of worktrees per execution band"
6321
+ lanes: "object \u2014 { laneName: count } summary of worktrees per lane",
6322
+ campaigns: "object \u2014 { campaignNumber: count } summary of worktrees per campaign"
6323
+ }
6324
+ },
6325
+ ownerModule: "workflow-engine",
6326
+ ontologyPrimitive: "worktree",
6327
+ tier: "showcase"
6328
+ };
6329
+ var LIST_CAMPAIGNS = {
6330
+ name: "list_campaigns",
6331
+ 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.",
6332
+ parameters: {
6333
+ topicId: {
6334
+ type: "string",
6335
+ description: "Optional topic scope."
6336
+ },
6337
+ status: {
6338
+ type: "string",
6339
+ description: "Optional worktree status filter before grouping campaigns and lanes."
6340
+ },
6341
+ limit: {
6342
+ type: "number",
6343
+ description: "Maximum worktrees to scan before grouping."
6344
+ }
6345
+ },
6346
+ required: [],
6347
+ response: {
6348
+ description: "Pipeline campaigns with nested lane summaries.",
6349
+ fields: {
6350
+ campaigns: "array \u2014 { campaign, lanes: [{ lane, laneOrderInCampaign, worktreeCount, activeCount, readyCount, blockedCount, completedCount, nextWorktree }] }",
6351
+ totalWorktrees: "number \u2014 total worktrees scanned after filtering"
5770
6352
  }
5771
6353
  },
5772
6354
  ownerModule: "workflow-engine",
@@ -5829,16 +6411,28 @@ var UPDATE_WORKTREE_TARGETS = {
5829
6411
  };
5830
6412
  var UPDATE_WORKTREE_METADATA = {
5831
6413
  name: "update_worktree_metadata",
5832
- 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.",
6414
+ 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.",
5833
6415
  parameters: {
5834
6416
  worktreeId: { type: "string", description: "The worktree to update" },
5835
6417
  hypothesis: {
5836
6418
  type: "string",
5837
6419
  description: "Testable claim this worktree investigates"
5838
6420
  },
5839
- executionOrder: {
6421
+ campaign: {
6422
+ type: "number",
6423
+ description: "Top-level pipeline campaign number."
6424
+ },
6425
+ lane: {
6426
+ type: "string",
6427
+ description: "GitButler-aligned workstream lane name inside the campaign."
6428
+ },
6429
+ laneOrderInCampaign: {
6430
+ type: "number",
6431
+ description: "Ordering for this lane within the campaign."
6432
+ },
6433
+ orderInLane: {
5840
6434
  type: "number",
5841
- description: "Global execution order (1 = first, higher = later)"
6435
+ description: "Position of this worktree inside its lane."
5842
6436
  },
5843
6437
  dependsOn: {
5844
6438
  type: "array",
@@ -5876,18 +6470,6 @@ var UPDATE_WORKTREE_METADATA = {
5876
6470
  type: "object",
5877
6471
  description: "Calibrated auto-fix policy controlling dry-run vs safe execution, per-run action caps, and permitted mutation tiers."
5878
6472
  },
5879
- track: {
5880
- type: "string",
5881
- 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."
5882
- },
5883
- trackPosition: {
5884
- type: "number",
5885
- description: "Position within the track (1-indexed). E.g., TC-A=1, TC-B=2, TC-C=3 within the 'tc-scope' track."
5886
- },
5887
- executionBand: {
5888
- type: "number",
5889
- 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."
5890
- },
5891
6473
  status: {
5892
6474
  type: "string",
5893
6475
  description: "Override the worktree status. Use for lifecycle transitions like marking a worktree superseded, long-term, or as a raw idea.",
@@ -6257,6 +6839,10 @@ var LIST_TASKS = {
6257
6839
  type: "string",
6258
6840
  description: "Filter to tasks linked to this worktree"
6259
6841
  },
6842
+ worktreeId: {
6843
+ type: "string",
6844
+ description: "Alias for linkedWorktreeId"
6845
+ },
6260
6846
  status: {
6261
6847
  type: "string",
6262
6848
  description: "Filter by status: todo, in_progress, blocked, done",
@@ -6344,7 +6930,7 @@ var GET_TOPIC = {
6344
6930
  description: "Legacy alias for topicId"
6345
6931
  }
6346
6932
  },
6347
- required: [],
6933
+ required: ["topicId"],
6348
6934
  response: {
6349
6935
  description: "Single topic record",
6350
6936
  fields: {
@@ -6699,7 +7285,7 @@ var GET_ONTOLOGY = {
6699
7285
  description: "Tenant scope for key lookup. Omit for platform-level."
6700
7286
  }
6701
7287
  },
6702
- required: [],
7288
+ required: ["id"],
6703
7289
  response: {
6704
7290
  description: "Ontology definition with latest published version",
6705
7291
  fields: {
@@ -6766,7 +7352,7 @@ var MATCH_ENTITY_TYPE = {
6766
7352
  description: "Optional maximum number of ranked matches to return"
6767
7353
  }
6768
7354
  },
6769
- required: ["text"],
7355
+ required: ["text", "ontologyId"],
6770
7356
  response: {
6771
7357
  description: "Ranked ontology entity type matches",
6772
7358
  fields: {
@@ -7020,7 +7606,7 @@ var RECORD_SCOPE_LEARNING = {
7020
7606
  };
7021
7607
  var PIPELINE_SNAPSHOT = {
7022
7608
  name: "pipeline_snapshot",
7023
- 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.",
7609
+ 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.",
7024
7610
  parameters: {
7025
7611
  topicId: { type: "string", description: "Topic scope ID" }
7026
7612
  },
@@ -7030,14 +7616,14 @@ var PIPELINE_SNAPSHOT = {
7030
7616
  fields: {
7031
7617
  topicId: "string",
7032
7618
  topicName: "string",
7033
- currentBand: "number | null",
7034
- nextBand: "number | null",
7619
+ currentCampaign: "number | null",
7620
+ nextCampaign: "number | null",
7035
7621
  activeWorktrees: "array \u2014 current hinge worktree(s)",
7036
- nextWave: "array \u2014 worktrees in the next planned band",
7622
+ nextWave: "array \u2014 worktrees in the next planned campaign",
7037
7623
  readyNow: "array \u2014 planning worktrees with dependencies completed",
7038
7624
  blockedBy: "array \u2014 grouped blockers",
7039
7625
  criticalPath: "array \u2014 ordered incomplete worktree chain",
7040
- bands: "array \u2014 incomplete worktrees grouped by executionBand",
7626
+ campaigns: "array \u2014 incomplete worktrees grouped by campaign",
7041
7627
  superseded: "array \u2014 worktrees marked superseded or not for activation",
7042
7628
  graphHygiene: "object \u2014 untargeted and taskless worktree debt",
7043
7629
  riskQuestions: "array \u2014 critical/high open questions",
@@ -7626,6 +8212,7 @@ var MCP_TOOL_CONTRACTS = {
7626
8212
  list_beliefs: LIST_BELIEFS,
7627
8213
  list_worktrees: LIST_WORKTREES,
7628
8214
  list_all_worktrees: LIST_ALL_WORKTREES,
8215
+ list_campaigns: LIST_CAMPAIGNS,
7629
8216
  activate_worktree: ACTIVATE_WORKTREE,
7630
8217
  update_worktree_targets: UPDATE_WORKTREE_TARGETS,
7631
8218
  update_worktree_metadata: UPDATE_WORKTREE_METADATA,
@@ -7808,6 +8395,7 @@ var MCP_WORKFLOW_PLATFORM_OPERATION_NAMES = [
7808
8395
  "activate_worktree",
7809
8396
  "list_worktrees",
7810
8397
  "list_all_worktrees",
8398
+ "list_campaigns",
7811
8399
  "update_worktree_targets",
7812
8400
  "update_worktree_metadata",
7813
8401
  "create_task",
@@ -8015,6 +8603,7 @@ var LUCERN_OPERATION_MANIFEST = {
8015
8603
 
8016
8604
  // ../contracts/src/function-registry/helpers.ts
8017
8605
  var jsonObjectSchema = z.record(z.unknown());
8606
+ var sdkSessionIdSchema = z.string().optional();
8018
8607
  function mcpContractShape(contract) {
8019
8608
  const required = new Set(contract.required);
8020
8609
  return Object.fromEntries(
@@ -8049,10 +8638,40 @@ function argsSchemaFromMcpContract(contract) {
8049
8638
  return z.object(mcpContractShape(contract));
8050
8639
  }
8051
8640
  function inputSchemaFromMcpContract(contract) {
8052
- return argsSchemaFromMcpContract(contract).passthrough();
8641
+ return withInternalSurfaceFields(argsSchemaFromMcpContract(contract));
8642
+ }
8643
+ function withInternalSurfaceFields(schema) {
8644
+ return schema.extend({ __sdkSessionId: sdkSessionIdSchema }).strict();
8645
+ }
8646
+ function normalizeInputSchema(schema) {
8647
+ if (schema instanceof z.ZodObject) {
8648
+ return withInternalSurfaceFields(schema);
8649
+ }
8650
+ return schema;
8651
+ }
8652
+ function unwrapObjectSchema(schema) {
8653
+ let current = schema;
8654
+ while (true) {
8655
+ switch (current._def.typeName) {
8656
+ case z.ZodFirstPartyTypeKind.ZodEffects:
8657
+ current = current._def.schema;
8658
+ continue;
8659
+ case z.ZodFirstPartyTypeKind.ZodBranded:
8660
+ current = current._def.type;
8661
+ continue;
8662
+ default:
8663
+ return current instanceof z.ZodObject ? current : void 0;
8664
+ }
8665
+ }
8053
8666
  }
8054
8667
  function getObjectShape(schema) {
8055
- const shape = typeof schema._def.shape === "function" ? schema._def.shape() : schema._def.shape;
8668
+ const objectSchema = unwrapObjectSchema(schema);
8669
+ if (!objectSchema) {
8670
+ throw new Error(
8671
+ `Expected a Zod object schema, received ${schema._def.typeName}.`
8672
+ );
8673
+ }
8674
+ const shape = typeof objectSchema._def.shape === "function" ? objectSchema._def.shape() : objectSchema._def.shape;
8056
8675
  return shape;
8057
8676
  }
8058
8677
  function unwrapMcpParameterSchema(schema) {
@@ -8073,6 +8692,9 @@ function unwrapMcpParameterSchema(schema) {
8073
8692
  case z.ZodFirstPartyTypeKind.ZodBranded:
8074
8693
  current = current._def.type;
8075
8694
  continue;
8695
+ case z.ZodFirstPartyTypeKind.ZodEffects:
8696
+ current = current._def.schema;
8697
+ continue;
8076
8698
  default:
8077
8699
  return { schema: current, required, description: description ?? current.description };
8078
8700
  }
@@ -8092,6 +8714,7 @@ function mcpParameterFromZod(fieldName, schema, contractName) {
8092
8714
  return { parameter: { type: "array", description }, required };
8093
8715
  case z.ZodFirstPartyTypeKind.ZodObject:
8094
8716
  case z.ZodFirstPartyTypeKind.ZodRecord:
8717
+ case z.ZodFirstPartyTypeKind.ZodDiscriminatedUnion:
8095
8718
  return { parameter: { type: "object", description }, required };
8096
8719
  case z.ZodFirstPartyTypeKind.ZodEnum:
8097
8720
  return {
@@ -8153,6 +8776,14 @@ function withCreatedBy(input, context) {
8153
8776
  createdBy: typeof input.createdBy === "string" ? input.createdBy : authUserId(context)
8154
8777
  };
8155
8778
  }
8779
+ function compactRecord4(input) {
8780
+ return Object.fromEntries(
8781
+ Object.entries(input).filter(([, value]) => value !== void 0)
8782
+ );
8783
+ }
8784
+ function recordValue2(value) {
8785
+ return value && typeof value === "object" && !Array.isArray(value) ? value : {};
8786
+ }
8156
8787
  function surfaceMcpContract(name) {
8157
8788
  const contract = MCP_TOOL_CONTRACTS[name];
8158
8789
  if (!contract) {
@@ -8197,7 +8828,9 @@ function surfaceContract(args) {
8197
8828
  const canonicalArgs = args.args ?? argsSchemaFromMcpContract(baseMcp);
8198
8829
  const mcp = args.args ? mcpContractFromArgsSchema(baseMcp, canonicalArgs, args.name) : baseMcp;
8199
8830
  const canonicalReturns = args.returns ?? jsonObjectSchema;
8200
- const input = args.input ?? inputSchemaFromMcpContract(mcp);
8831
+ const input = normalizeInputSchema(
8832
+ args.input ?? inputSchemaFromMcpContract(mcp)
8833
+ );
8201
8834
  const output = args.output ?? canonicalReturns;
8202
8835
  return defineFunctionContract({
8203
8836
  name: args.name,
@@ -8259,20 +8892,26 @@ function assertSurfaceCoverage(contracts) {
8259
8892
 
8260
8893
  // ../contracts/src/function-registry/context.ts
8261
8894
  var observationInput = (input, context) => withUserId(
8262
- {
8263
- ...input,
8895
+ compactRecord4({
8896
+ projectId: input.projectId,
8897
+ topicId: input.topicId,
8264
8898
  text: input.text ?? input.summary,
8265
8899
  title: input.title ?? input.summary,
8266
8900
  content: input.content ?? input.summary,
8901
+ contentType: input.contentType,
8267
8902
  kind: input.kind ?? input.observationType ?? "observation",
8268
- sourceType: input.sourceType ?? input.source ?? "agent",
8269
- metadata: {
8270
- ...input.metadata && typeof input.metadata === "object" && !Array.isArray(input.metadata) ? input.metadata : {},
8903
+ tags: input.tags,
8904
+ sourceType: input.sourceType,
8905
+ externalSourceType: input.externalSourceType,
8906
+ sourceUrl: input.sourceUrl,
8907
+ metadata: compactRecord4({
8908
+ ...recordValue2(input.metadata),
8271
8909
  observationType: input.observationType,
8272
8910
  source: input.source
8273
- },
8911
+ }),
8912
+ rationale: input.rationale ?? input.reasoning ?? input.summary ?? input.text ?? "Recorded observation",
8274
8913
  trustedBypassAccessCheck: input.trustedBypassAccessCheck ?? true
8275
- },
8914
+ }),
8276
8915
  context
8277
8916
  );
8278
8917
  var contextContracts = [
@@ -8324,7 +8963,13 @@ var contextContracts = [
8324
8963
  convex: {
8325
8964
  module: "evidence",
8326
8965
  functionName: "getByTopic",
8327
- kind: "query"
8966
+ kind: "query",
8967
+ inputProjection: (input) => compactRecord4({
8968
+ topicId: input.topicId,
8969
+ limit: input.limit,
8970
+ status: input.status,
8971
+ userId: input.userId
8972
+ })
8328
8973
  }
8329
8974
  })
8330
8975
  ];
@@ -8390,42 +9035,62 @@ var identityContracts = [
8390
9035
  ];
8391
9036
 
8392
9037
  // ../contracts/src/function-registry/beliefs.ts
8393
- var withBeliefId = (input) => ({
8394
- ...input,
9038
+ var beliefLookupInput = (input) => compactRecord4({
8395
9039
  nodeId: input.nodeId ?? input.id ?? input.beliefId,
8396
- beliefId: input.beliefId ?? input.id ?? input.nodeId
9040
+ beliefId: input.beliefId
8397
9041
  });
8398
- var createBeliefInput = (input, context) => withUserId(
8399
- {
8400
- ...input,
8401
- formulation: input.formulation ?? input.canonicalText,
8402
- baseRate: input.baseRate ?? 0.5,
8403
- trustedBypassAccessCheck: input.trustedBypassAccessCheck ?? true
8404
- },
8405
- context
8406
- );
9042
+ var beliefNodeInput = (input) => compactRecord4({
9043
+ nodeId: input.nodeId ?? input.id ?? input.beliefId
9044
+ });
9045
+ var beliefTopicInput = (input) => {
9046
+ const parsed = listBeliefsProjection.inputSchema.safeParse(input);
9047
+ if (!parsed.success) {
9048
+ throw new Error(
9049
+ `list_beliefs projection input rejected: ${parsed.error.message}`
9050
+ );
9051
+ }
9052
+ return compactRecord4(listBeliefsProjection.project(parsed.data));
9053
+ };
9054
+ var createBeliefInput = (input, context) => {
9055
+ return withUserId(
9056
+ compactRecord4({
9057
+ projectId: input.projectId,
9058
+ topicId: input.topicId,
9059
+ formulation: input.formulation ?? input.canonicalText,
9060
+ beliefType: input.beliefType,
9061
+ rationale: input.rationale,
9062
+ pillar: input.pillar,
9063
+ worktreeId: input.worktreeId,
9064
+ sourceBeliefIds: input.sourceBeliefIds,
9065
+ sourceType: input.sourceType,
9066
+ reversibility: input.reversibility,
9067
+ predictionMeta: input.predictionMeta,
9068
+ baseRate: input.baseRate ?? 0.5,
9069
+ metadata: input.metadata,
9070
+ trustedBypassAccessCheck: input.trustedBypassAccessCheck ?? true
9071
+ }),
9072
+ context
9073
+ );
9074
+ };
8407
9075
  var forkBeliefInput = (input, context) => withUserId(
8408
- {
8409
- ...input,
9076
+ compactRecord4({
8410
9077
  parentNodeId: input.parentNodeId ?? input.nodeId ?? input.id,
9078
+ newFormulation: input.newFormulation,
9079
+ forkReason: input.forkReason,
9080
+ rationale: input.rationale,
8411
9081
  trustedBypassAccessCheck: input.trustedBypassAccessCheck ?? true
8412
- },
9082
+ }),
8413
9083
  context
8414
9084
  );
8415
9085
  var confidenceInput = (input, context) => {
8416
- const confidence = typeof input.confidence === "number" ? input.confidence : void 0;
8417
- const belief = typeof input.belief === "number" ? input.belief : confidence ?? 0.5;
8418
- const disbelief = typeof input.disbelief === "number" ? input.disbelief : 0;
8419
- const uncertainty = typeof input.uncertainty === "number" ? input.uncertainty : Math.max(0, 1 - belief - disbelief);
9086
+ const parsed = modulateConfidenceProjection.inputSchema.safeParse(input);
9087
+ if (!parsed.success) {
9088
+ throw new Error(
9089
+ `modulate_confidence projection input rejected: ${parsed.error.message}`
9090
+ );
9091
+ }
8420
9092
  return withUserId(
8421
- {
8422
- ...input,
8423
- belief,
8424
- disbelief,
8425
- uncertainty,
8426
- baseRate: input.baseRate ?? 0.5,
8427
- trustedBypassAccessCheck: input.trustedBypassAccessCheck ?? true
8428
- },
9093
+ compactRecord4(modulateConfidenceProjection.project(parsed.data)),
8429
9094
  context
8430
9095
  );
8431
9096
  };
@@ -8460,7 +9125,7 @@ var beliefsContracts = [
8460
9125
  module: "beliefs",
8461
9126
  functionName: "getById",
8462
9127
  kind: "query",
8463
- inputProjection: withBeliefId
9128
+ inputProjection: beliefLookupInput
8464
9129
  }
8465
9130
  }),
8466
9131
  surfaceContract({
@@ -8476,8 +9141,10 @@ var beliefsContracts = [
8476
9141
  convex: {
8477
9142
  module: "beliefs",
8478
9143
  functionName: "getByTopic",
8479
- kind: "query"
8480
- }
9144
+ kind: "query",
9145
+ inputProjection: beliefTopicInput
9146
+ },
9147
+ args: listBeliefsInputSchema
8481
9148
  }),
8482
9149
  surfaceContract({
8483
9150
  name: "refine_belief",
@@ -8495,7 +9162,7 @@ var beliefsContracts = [
8495
9162
  kind: "mutation",
8496
9163
  inputProjection: (input, context) => withUserId(
8497
9164
  {
8498
- ...withBeliefId(input),
9165
+ ...beliefLookupInput(input),
8499
9166
  trustedBypassAccessCheck: input.trustedBypassAccessCheck ?? true
8500
9167
  },
8501
9168
  context
@@ -8516,7 +9183,8 @@ var beliefsContracts = [
8516
9183
  functionName: "modulateConfidence",
8517
9184
  kind: "mutation",
8518
9185
  inputProjection: confidenceInput
8519
- }
9186
+ },
9187
+ args: modulateConfidenceInputSchema
8520
9188
  }),
8521
9189
  surfaceContract({
8522
9190
  name: "fork_belief",
@@ -8549,10 +9217,10 @@ var beliefsContracts = [
8549
9217
  functionName: "archive",
8550
9218
  kind: "mutation",
8551
9219
  inputProjection: (input, context) => withUserId(
8552
- {
8553
- ...withBeliefId(input),
9220
+ compactRecord4({
9221
+ ...beliefNodeInput(input),
8554
9222
  reason: input.reason ?? input.rationale
8555
- },
9223
+ }),
8556
9224
  context
8557
9225
  )
8558
9226
  }
@@ -8570,10 +9238,12 @@ var beliefsContracts = [
8570
9238
  module: "nodes",
8571
9239
  functionName: "search",
8572
9240
  kind: "query",
8573
- inputProjection: (input) => ({
8574
- ...input,
9241
+ inputProjection: (input) => compactRecord4({
8575
9242
  searchQuery: input.searchQuery ?? input.query,
8576
- nodeType: "belief"
9243
+ projectId: input.projectId,
9244
+ topicId: input.topicId,
9245
+ nodeType: "belief",
9246
+ limit: input.limit
8577
9247
  })
8578
9248
  }
8579
9249
  }),
@@ -8590,7 +9260,7 @@ var beliefsContracts = [
8590
9260
  module: "beliefs",
8591
9261
  functionName: "getConfidenceHistory",
8592
9262
  kind: "query",
8593
- inputProjection: withBeliefId
9263
+ inputProjection: beliefNodeInput
8594
9264
  }
8595
9265
  }),
8596
9266
  surfaceContract({
@@ -8607,25 +9277,69 @@ var beliefsContracts = [
8607
9277
  module: "beliefs",
8608
9278
  functionName: "getConfidenceHistory",
8609
9279
  kind: "query",
8610
- inputProjection: withBeliefId
9280
+ inputProjection: beliefNodeInput
8611
9281
  }
8612
9282
  })
8613
9283
  ];
8614
9284
 
8615
9285
  // ../contracts/src/function-registry/evidence.ts
8616
- var evidenceIdInput = (input) => ({
8617
- ...input,
8618
- evidenceId: input.evidenceId ?? input.id ?? input.nodeId,
9286
+ var evidenceIdInput = (input) => compactRecord4({
9287
+ evidenceId: input.evidenceId,
9288
+ insightId: input.insightId,
8619
9289
  nodeId: input.nodeId ?? input.id ?? input.evidenceId
8620
9290
  });
8621
- var createEvidenceInput = (input, context) => withUserId(
8622
- {
8623
- ...input,
8624
- title: input.title ?? input.text,
8625
- content: input.content ?? input.text,
8626
- sourceType: input.sourceType ?? input.source ?? "agent",
9291
+ var evidenceTopicInput = (input) => compactRecord4({
9292
+ topicId: input.topicId,
9293
+ status: input.status,
9294
+ userId: input.userId,
9295
+ limit: input.limit
9296
+ });
9297
+ var createEvidenceInput = (input, context) => {
9298
+ const parsed = createEvidenceProjection.inputSchema.safeParse(input);
9299
+ if (!parsed.success) {
9300
+ throw new Error(
9301
+ `create_evidence projection input rejected: ${parsed.error.message}`
9302
+ );
9303
+ }
9304
+ return withUserId(
9305
+ compactRecord4(createEvidenceProjection.project(parsed.data)),
9306
+ context
9307
+ );
9308
+ };
9309
+ var linkEvidenceToBeliefEdgeInput = (input, context) => withCreatedBy(
9310
+ compactRecord4({
9311
+ fromNodeId: input.insightId ?? input.evidenceNodeId ?? input.evidenceId,
9312
+ toNodeId: input.beliefNodeId ?? input.beliefId ?? input.targetId,
9313
+ edgeType: "evidence_supports_belief",
9314
+ globalId: input.globalId ?? `edge:${String(
9315
+ input.insightId ?? input.evidenceNodeId ?? input.evidenceId
9316
+ )}:${String(
9317
+ input.beliefNodeId ?? input.beliefId ?? input.targetId
9318
+ )}:evidence_supports_belief`,
9319
+ weight: typeof input.weight === "number" ? input.weight : input.type === "contradicting" ? -1 : 1,
9320
+ context: input.rationale ?? input.context,
9321
+ skipLayerValidation: true,
9322
+ topicId: input.topicId,
8627
9323
  trustedBypassAccessCheck: input.trustedBypassAccessCheck ?? true
8628
- },
9324
+ }),
9325
+ context
9326
+ );
9327
+ var linkEvidenceToQuestionEdgeInput = (input, context) => withCreatedBy(
9328
+ compactRecord4({
9329
+ fromNodeId: input.insightId ?? input.evidenceNodeId ?? input.evidenceId,
9330
+ toNodeId: input.questionId ?? input.questionNodeId ?? input.targetId,
9331
+ edgeType: "evidence_supports_question",
9332
+ globalId: input.globalId ?? `edge:${String(
9333
+ input.insightId ?? input.evidenceNodeId ?? input.evidenceId
9334
+ )}:${String(
9335
+ input.questionId ?? input.questionNodeId ?? input.targetId
9336
+ )}:evidence_supports_question`,
9337
+ weight: input.impactScore ?? input.weight,
9338
+ context: input.rationale ?? input.context,
9339
+ skipLayerValidation: true,
9340
+ topicId: input.topicId,
9341
+ trustedBypassAccessCheck: input.trustedBypassAccessCheck ?? true
9342
+ }),
8629
9343
  context
8630
9344
  );
8631
9345
  var evidenceContracts = [
@@ -8669,8 +9383,9 @@ var evidenceContracts = [
8669
9383
  linkedBeliefNodeId: input.linkedBeliefNodeId ?? input.targetNodeId ?? input.targetId,
8670
9384
  evidenceRelation: weight < 0 ? "contradicts" : "supports",
8671
9385
  confidence: Math.min(1, Math.max(0, Math.abs(weight))),
9386
+ rationale: input.reasoning,
8672
9387
  metadata: {
8673
- ...input.metadata && typeof input.metadata === "object" && !Array.isArray(input.metadata) ? input.metadata : {},
9388
+ ...recordValue2(input.metadata),
8674
9389
  reasoning: input.reasoning,
8675
9390
  sourceUrl: input.sourceUrl
8676
9391
  }
@@ -8710,7 +9425,8 @@ var evidenceContracts = [
8710
9425
  convex: {
8711
9426
  module: "evidence",
8712
9427
  functionName: "getByTopic",
8713
- kind: "query"
9428
+ kind: "query",
9429
+ inputProjection: evidenceTopicInput
8714
9430
  }
8715
9431
  }),
8716
9432
  surfaceContract({
@@ -8726,10 +9442,12 @@ var evidenceContracts = [
8726
9442
  module: "nodes",
8727
9443
  functionName: "search",
8728
9444
  kind: "query",
8729
- inputProjection: (input) => ({
8730
- ...input,
9445
+ inputProjection: (input) => compactRecord4({
8731
9446
  searchQuery: input.searchQuery ?? input.q ?? input.query,
8732
- nodeType: "evidence"
9447
+ projectId: input.projectId,
9448
+ topicId: input.topicId,
9449
+ nodeType: "evidence",
9450
+ limit: input.limit
8733
9451
  })
8734
9452
  }
8735
9453
  }),
@@ -8743,17 +9461,10 @@ var evidenceContracts = [
8743
9461
  sdkMethod: "linkEvidenceToBelief",
8744
9462
  summary: "Link evidence to a belief.",
8745
9463
  convex: {
8746
- module: "beliefs",
8747
- functionName: "linkEvidence",
9464
+ module: "edges",
9465
+ functionName: "create",
8748
9466
  kind: "mutation",
8749
- inputProjection: (input, context) => withUserId(
8750
- {
8751
- ...input,
8752
- beliefNodeId: input.beliefNodeId ?? input.beliefId ?? input.targetId,
8753
- evidenceNodeId: input.evidenceNodeId ?? input.evidenceId
8754
- },
8755
- context
8756
- )
9467
+ inputProjection: linkEvidenceToBeliefEdgeInput
8757
9468
  }
8758
9469
  }),
8759
9470
  surfaceContract({
@@ -8766,18 +9477,10 @@ var evidenceContracts = [
8766
9477
  sdkMethod: "linkEvidenceToQuestion",
8767
9478
  summary: "Link evidence to a question.",
8768
9479
  convex: {
8769
- module: "questionLinks",
9480
+ module: "edges",
8770
9481
  functionName: "create",
8771
9482
  kind: "mutation",
8772
- inputProjection: (input, context) => withCreatedBy(
8773
- {
8774
- ...input,
8775
- questionId: input.questionId,
8776
- insightId: input.insightId ?? input.evidenceId,
8777
- helpsAnswer: input.helpsAnswer ?? true
8778
- },
8779
- context
8780
- )
9483
+ inputProjection: linkEvidenceToQuestionEdgeInput
8781
9484
  }
8782
9485
  }),
8783
9486
  surfaceContract({
@@ -8790,35 +9493,46 @@ var evidenceContracts = [
8790
9493
  sdkMethod: "linkEvidence",
8791
9494
  summary: "Link evidence to a target node.",
8792
9495
  convex: {
8793
- module: "beliefs",
8794
- functionName: "linkEvidence",
9496
+ module: "edges",
9497
+ functionName: "create",
8795
9498
  kind: "mutation",
8796
- inputProjection: (input, context) => withUserId(
8797
- {
8798
- ...input,
8799
- beliefNodeId: input.beliefNodeId ?? input.targetId,
8800
- evidenceNodeId: input.evidenceNodeId ?? input.evidenceId
8801
- },
8802
- context
8803
- )
9499
+ inputProjection: linkEvidenceToBeliefEdgeInput
8804
9500
  }
8805
9501
  })
8806
9502
  ];
8807
9503
 
8808
9504
  // ../contracts/src/function-registry/questions.ts
8809
- var questionIdInput = (input) => ({
8810
- ...input,
8811
- questionId: input.questionId ?? input.id ?? input.nodeId,
8812
- nodeId: input.nodeId ?? input.id ?? input.questionId
9505
+ var questionNodeInput = (input) => compactRecord4({
9506
+ nodeId: input.nodeId ?? input.id ?? input.questionId,
9507
+ questionId: input.questionId
8813
9508
  });
8814
- var createQuestionInput = (input, context) => withUserId(
8815
- {
8816
- ...input,
8817
- text: input.text ?? input.question,
8818
- trustedBypassAccessCheck: input.trustedBypassAccessCheck ?? true
8819
- },
8820
- context
8821
- );
9509
+ var questionTopicInput = (input) => compactRecord4({
9510
+ topicId: input.topicId,
9511
+ status: input.status,
9512
+ userId: input.userId,
9513
+ limit: input.limit
9514
+ });
9515
+ var createQuestionInput = (input, context) => {
9516
+ const priority = input.priority === "urgent" ? "high" : input.priority;
9517
+ return withUserId(
9518
+ compactRecord4({
9519
+ topicId: input.topicId,
9520
+ question: input.question ?? input.text,
9521
+ category: input.category,
9522
+ priority,
9523
+ source: input.source,
9524
+ linkedBeliefNodeId: input.linkedBeliefNodeId ?? input.linkedBeliefId,
9525
+ testType: input.testType,
9526
+ importance: input.importance,
9527
+ epistemicUnlock: input.epistemicUnlock,
9528
+ sourceQuestionIds: input.sourceQuestionIds,
9529
+ linkedWorktreeId: input.linkedWorktreeId,
9530
+ questionType: input.questionType,
9531
+ questionPriority: input.questionPriority
9532
+ }),
9533
+ context
9534
+ );
9535
+ };
8822
9536
  var questionsContracts = [
8823
9537
  surfaceContract({
8824
9538
  name: "create_question",
@@ -8850,7 +9564,7 @@ var questionsContracts = [
8850
9564
  module: "questions",
8851
9565
  functionName: "getById",
8852
9566
  kind: "query",
8853
- inputProjection: questionIdInput
9567
+ inputProjection: questionNodeInput
8854
9568
  }
8855
9569
  }),
8856
9570
  surfaceContract({
@@ -8866,7 +9580,8 @@ var questionsContracts = [
8866
9580
  convex: {
8867
9581
  module: "questions",
8868
9582
  functionName: "getByTopic",
8869
- kind: "query"
9583
+ kind: "query",
9584
+ inputProjection: questionTopicInput
8870
9585
  }
8871
9586
  }),
8872
9587
  surfaceContract({
@@ -8883,7 +9598,12 @@ var questionsContracts = [
8883
9598
  module: "questions",
8884
9599
  functionName: "updateQuestion",
8885
9600
  kind: "mutation",
8886
- inputProjection: (input, context) => withUserId({ ...questionIdInput(input), text: input.text }, context)
9601
+ inputProjection: (input) => compactRecord4({
9602
+ questionId: input.questionId ?? input.id ?? input.nodeId,
9603
+ question: input.question ?? input.text,
9604
+ category: input.category,
9605
+ priority: input.priority
9606
+ })
8887
9607
  }
8888
9608
  }),
8889
9609
  surfaceContract({
@@ -8900,7 +9620,16 @@ var questionsContracts = [
8900
9620
  module: "questions",
8901
9621
  functionName: "updateStatus",
8902
9622
  kind: "mutation",
8903
- inputProjection: (input, context) => withUserId(questionIdInput(input), context)
9623
+ inputProjection: (input, context) => withUserId(
9624
+ compactRecord4({
9625
+ questionId: input.questionId ?? input.id,
9626
+ nodeId: input.nodeId,
9627
+ status: input.status,
9628
+ answer: input.answer,
9629
+ answerStatus: input.answerStatus
9630
+ }),
9631
+ context
9632
+ )
8904
9633
  }
8905
9634
  }),
8906
9635
  surfaceContract({
@@ -8917,7 +9646,12 @@ var questionsContracts = [
8917
9646
  module: "questions",
8918
9647
  functionName: "deleteQuestion",
8919
9648
  kind: "mutation",
8920
- inputProjection: questionIdInput
9649
+ inputProjection: (input, context) => withUserId(
9650
+ compactRecord4({
9651
+ questionId: input.questionId ?? input.id ?? input.nodeId
9652
+ }),
9653
+ context
9654
+ )
8921
9655
  }
8922
9656
  }),
8923
9657
  surfaceContract({
@@ -8934,10 +9668,16 @@ var questionsContracts = [
8934
9668
  functionName: "create",
8935
9669
  kind: "mutation",
8936
9670
  inputProjection: (input, context) => withUserId(
8937
- {
8938
- ...input,
8939
- questionNodeId: input.questionNodeId ?? input.questionId
8940
- },
9671
+ compactRecord4({
9672
+ topicId: input.topicId,
9673
+ questionNodeId: input.questionNodeId ?? input.questionId,
9674
+ answerText: input.answerText,
9675
+ confidence: input.confidence,
9676
+ evidenceNodeIds: input.evidenceNodeIds,
9677
+ answerSource: input.answerSource,
9678
+ worktreeId: input.worktreeId,
9679
+ sprintId: input.sprintId
9680
+ }),
8941
9681
  context
8942
9682
  )
8943
9683
  }
@@ -8957,13 +9697,16 @@ var questionsContracts = [
8957
9697
  functionName: "create",
8958
9698
  kind: "mutation",
8959
9699
  inputProjection: (input, context) => withUserId(
8960
- {
8961
- ...input,
9700
+ compactRecord4({
9701
+ topicId: input.topicId,
8962
9702
  questionNodeId: input.questionNodeId ?? input.questionId ?? input.id,
8963
9703
  answerText: input.answerText ?? input.text,
8964
9704
  evidenceNodeIds: input.evidenceNodeIds ?? input.evidenceIds,
8965
- answerSource: input.answerSource ?? "human"
8966
- },
9705
+ answerSource: input.answerSource ?? "human",
9706
+ confidence: input.confidence,
9707
+ worktreeId: input.worktreeId,
9708
+ sprintId: input.sprintId
9709
+ }),
8967
9710
  context
8968
9711
  )
8969
9712
  }
@@ -8996,7 +9739,8 @@ var questionsContracts = [
8996
9739
  convex: {
8997
9740
  module: "questions",
8998
9741
  functionName: "getByTopic",
8999
- kind: "query"
9742
+ kind: "query",
9743
+ inputProjection: questionTopicInput
9000
9744
  }
9001
9745
  }),
9002
9746
  surfaceContract({
@@ -9011,7 +9755,11 @@ var questionsContracts = [
9011
9755
  convex: {
9012
9756
  module: "questions",
9013
9757
  functionName: "getByTopic",
9014
- kind: "query"
9758
+ kind: "query",
9759
+ inputProjection: (input) => compactRecord4({
9760
+ ...questionTopicInput(input),
9761
+ status: input.includeAnswered === true ? void 0 : "open"
9762
+ })
9015
9763
  }
9016
9764
  }),
9017
9765
  surfaceContract({
@@ -9026,16 +9774,28 @@ var questionsContracts = [
9026
9774
  convex: {
9027
9775
  module: "questions",
9028
9776
  functionName: "getByTopic",
9029
- kind: "query"
9777
+ kind: "query",
9778
+ inputProjection: questionTopicInput
9030
9779
  }
9031
9780
  })
9032
9781
  ];
9033
9782
 
9034
9783
  // ../contracts/src/function-registry/topics.ts
9035
- var topicIdInput = (input) => ({
9036
- ...input,
9784
+ var topicIdInput = (input) => compactRecord4({
9037
9785
  id: input.id ?? input.topicId
9038
9786
  });
9787
+ var updateTopicInput = (input) => compactRecord4({
9788
+ id: input.id ?? input.topicId,
9789
+ name: input.name,
9790
+ description: input.description,
9791
+ type: input.type,
9792
+ status: input.status,
9793
+ visibility: input.visibility,
9794
+ ontologyId: input.ontologyId,
9795
+ clearOntologyId: input.clearOntologyId,
9796
+ graphScopeProjectId: input.graphScopeProjectId,
9797
+ metadata: input.metadata
9798
+ });
9039
9799
  var topicsContracts = [
9040
9800
  surfaceContract({
9041
9801
  name: "create_topic",
@@ -9100,7 +9860,7 @@ var topicsContracts = [
9100
9860
  module: "topics",
9101
9861
  functionName: "update",
9102
9862
  kind: "mutation",
9103
- inputProjection: topicIdInput
9863
+ inputProjection: updateTopicInput
9104
9864
  }
9105
9865
  }),
9106
9866
  surfaceContract({
@@ -9122,6 +9882,27 @@ var topicsContracts = [
9122
9882
  ];
9123
9883
 
9124
9884
  // ../contracts/src/function-registry/lenses.ts
9885
+ var createLensInput = (input, context) => compactRecord4({
9886
+ name: input.name,
9887
+ description: input.description,
9888
+ workspaceId: input.workspaceId,
9889
+ topicId: input.topicId,
9890
+ perspectiveType: input.perspectiveType,
9891
+ promptTemplates: input.promptTemplates,
9892
+ workflowTemplates: input.workflowTemplates,
9893
+ taskTemplates: input.taskTemplates,
9894
+ questionTemplates: input.questionTemplates,
9895
+ filterCriteria: input.filterCriteria,
9896
+ metadata: input.metadata,
9897
+ createdBy: authUserId(context)
9898
+ });
9899
+ var lensListInput = (input, context) => compactRecord4({
9900
+ actorId: input.actorId ?? authUserId(context),
9901
+ workspaceId: input.workspaceId,
9902
+ topicId: input.topicId,
9903
+ status: input.status,
9904
+ perspectiveType: input.perspectiveType
9905
+ });
9125
9906
  var lensesContracts = [
9126
9907
  surfaceContract({
9127
9908
  name: "create_lens",
@@ -9135,7 +9916,8 @@ var lensesContracts = [
9135
9916
  convex: {
9136
9917
  module: "lenses",
9137
9918
  functionName: "create",
9138
- kind: "mutation"
9919
+ kind: "mutation",
9920
+ inputProjection: createLensInput
9139
9921
  }
9140
9922
  }),
9141
9923
  surfaceContract({
@@ -9151,7 +9933,8 @@ var lensesContracts = [
9151
9933
  convex: {
9152
9934
  module: "lenses",
9153
9935
  functionName: "list",
9154
- kind: "query"
9936
+ kind: "query",
9937
+ inputProjection: lensListInput
9155
9938
  }
9156
9939
  }),
9157
9940
  surfaceContract({
@@ -9166,7 +9949,13 @@ var lensesContracts = [
9166
9949
  convex: {
9167
9950
  module: "lenses",
9168
9951
  functionName: "applyToTopic",
9169
- kind: "mutation"
9952
+ kind: "mutation",
9953
+ inputProjection: (input, context) => compactRecord4({
9954
+ lensId: input.lensId,
9955
+ topicId: input.topicId,
9956
+ metadata: input.metadata,
9957
+ appliedBy: authUserId(context)
9958
+ })
9170
9959
  }
9171
9960
  }),
9172
9961
  surfaceContract({
@@ -9182,12 +9971,28 @@ var lensesContracts = [
9182
9971
  convex: {
9183
9972
  module: "lenses",
9184
9973
  functionName: "removeFromTopic",
9185
- kind: "mutation"
9974
+ kind: "mutation",
9975
+ inputProjection: (input, context) => compactRecord4({
9976
+ lensId: input.lensId,
9977
+ topicId: input.topicId,
9978
+ removedBy: authUserId(context)
9979
+ })
9186
9980
  }
9187
9981
  })
9188
9982
  ];
9189
9983
 
9190
9984
  // ../contracts/src/function-registry/ontologies.ts
9985
+ var ontologyIdInput = (input) => compactRecord4({
9986
+ id: input.id ?? input.ontologyId
9987
+ });
9988
+ var ontologyVersionIdInput = (input) => compactRecord4({
9989
+ id: input.id ?? input.versionId,
9990
+ ontologyId: input.ontologyId,
9991
+ actorId: input.actorId
9992
+ });
9993
+ var effectiveOntologyInput = (input) => compactRecord4({
9994
+ ontologyId: input.ontologyId ?? input.id
9995
+ });
9191
9996
  var ontologiesContracts = [
9192
9997
  surfaceContract({
9193
9998
  name: "create_ontology",
@@ -9218,10 +10023,7 @@ var ontologiesContracts = [
9218
10023
  module: "ontologies",
9219
10024
  functionName: "getOntologyDefinition",
9220
10025
  kind: "query",
9221
- inputProjection: (input) => ({
9222
- ...input,
9223
- id: input.id ?? input.ontologyId
9224
- })
10026
+ inputProjection: ontologyIdInput
9225
10027
  }
9226
10028
  }),
9227
10029
  surfaceContract({
@@ -9254,9 +10056,13 @@ var ontologiesContracts = [
9254
10056
  module: "ontologies",
9255
10057
  functionName: "updateOntologyDefinition",
9256
10058
  kind: "mutation",
9257
- inputProjection: (input) => ({
9258
- ...input,
9259
- id: input.id ?? input.ontologyId
10059
+ inputProjection: (input) => compactRecord4({
10060
+ id: input.id ?? input.ontologyId,
10061
+ name: input.name,
10062
+ description: input.description,
10063
+ parentOntologyId: input.parentOntologyId,
10064
+ status: input.status,
10065
+ actorId: input.actorId
9260
10066
  })
9261
10067
  }
9262
10068
  }),
@@ -9274,10 +10080,7 @@ var ontologiesContracts = [
9274
10080
  module: "ontologies",
9275
10081
  functionName: "archiveOntologyDefinition",
9276
10082
  kind: "mutation",
9277
- inputProjection: (input) => ({
9278
- ...input,
9279
- id: input.id ?? input.ontologyId
9280
- })
10083
+ inputProjection: ontologyIdInput
9281
10084
  }
9282
10085
  }),
9283
10086
  surfaceContract({
@@ -9308,8 +10111,7 @@ var ontologiesContracts = [
9308
10111
  module: "topics",
9309
10112
  functionName: "update",
9310
10113
  kind: "mutation",
9311
- inputProjection: (input) => ({
9312
- ...input,
10114
+ inputProjection: (input) => compactRecord4({
9313
10115
  id: input.topicId ?? input.id,
9314
10116
  ontologyId: input.ontologyId ?? input.id
9315
10117
  })
@@ -9327,7 +10129,8 @@ var ontologiesContracts = [
9327
10129
  convex: {
9328
10130
  module: "ontologies",
9329
10131
  functionName: "resolveEffectiveOntology",
9330
- kind: "query"
10132
+ kind: "query",
10133
+ inputProjection: effectiveOntologyInput
9331
10134
  }
9332
10135
  }),
9333
10136
  surfaceContract({
@@ -9343,10 +10146,7 @@ var ontologiesContracts = [
9343
10146
  module: "ontologies",
9344
10147
  functionName: "publishOntologyVersion",
9345
10148
  kind: "mutation",
9346
- inputProjection: (input) => ({
9347
- ...input,
9348
- id: input.id ?? input.versionId
9349
- })
10149
+ inputProjection: ontologyVersionIdInput
9350
10150
  }
9351
10151
  }),
9352
10152
  surfaceContract({
@@ -9362,10 +10162,7 @@ var ontologiesContracts = [
9362
10162
  module: "ontologies",
9363
10163
  functionName: "deprecateOntologyVersion",
9364
10164
  kind: "mutation",
9365
- inputProjection: (input) => ({
9366
- ...input,
9367
- id: input.id ?? input.versionId
9368
- })
10165
+ inputProjection: ontologyVersionIdInput
9369
10166
  }
9370
10167
  }),
9371
10168
  surfaceContract({
@@ -9380,16 +10177,51 @@ var ontologiesContracts = [
9380
10177
  convex: {
9381
10178
  module: "ontologies",
9382
10179
  functionName: "resolveEffectiveOntology",
9383
- kind: "query"
10180
+ kind: "query",
10181
+ inputProjection: effectiveOntologyInput
9384
10182
  }
9385
10183
  })
9386
10184
  ];
9387
10185
 
9388
10186
  // ../contracts/src/function-registry/worktrees.ts
9389
- var worktreeInput = (input) => ({
9390
- ...input,
10187
+ var worktreeIdInput = (input) => compactRecord4({
9391
10188
  worktreeId: input.worktreeId ?? input.id
9392
10189
  });
10190
+ var activateWorktreeInput = (input, context) => withUserId(worktreeIdInput(input), context);
10191
+ var worktreeTargetsInput = (input) => compactRecord4({
10192
+ worktreeId: input.worktreeId ?? input.id,
10193
+ addBeliefIds: input.addBeliefIds,
10194
+ removeBeliefIds: input.removeBeliefIds,
10195
+ addQuestionIds: input.addQuestionIds,
10196
+ removeQuestionIds: input.removeQuestionIds
10197
+ });
10198
+ var worktreeMetadataInput = (input) => compactRecord4({
10199
+ worktreeId: input.worktreeId ?? input.id,
10200
+ topicId: input.topicId,
10201
+ additionalTopicIds: input.additionalTopicIds,
10202
+ status: input.status,
10203
+ campaign: input.campaign,
10204
+ lane: input.lane,
10205
+ laneOrderInCampaign: input.laneOrderInCampaign,
10206
+ orderInLane: input.orderInLane,
10207
+ gate: input.gate,
10208
+ hypothesis: input.hypothesis,
10209
+ objective: input.objective,
10210
+ rationale: input.rationale,
10211
+ proofArtifacts: input.proofArtifacts,
10212
+ staffingHint: input.staffingHint,
10213
+ blocks: input.blocks,
10214
+ dependsOn: input.dependsOn,
10215
+ lensId: input.lensId,
10216
+ autoFixPolicy: input.autoFixPolicy,
10217
+ lastReconciledAt: input.lastReconciledAt
10218
+ });
10219
+ var listAllWorktreesInput = (input) => compactRecord4({
10220
+ status: input.status,
10221
+ lane: input.lane,
10222
+ campaign: input.campaign,
10223
+ limit: input.limit
10224
+ });
9393
10225
  var worktreesContracts = [
9394
10226
  surfaceContract({
9395
10227
  name: "add_worktree",
@@ -9405,11 +10237,43 @@ var worktreesContracts = [
9405
10237
  functionName: "create",
9406
10238
  kind: "mutation",
9407
10239
  inputProjection: (input, context) => withCreatedBy(
9408
- {
9409
- ...input,
10240
+ compactRecord4({
9410
10241
  name: input.name ?? input.title,
9411
- targetBeliefIds: input.targetBeliefIds ?? input.beliefIds
9412
- },
10242
+ topicId: input.topicId,
10243
+ worktreeType: input.worktreeType,
10244
+ objective: input.objective,
10245
+ gate: input.gate,
10246
+ hypothesis: input.hypothesis,
10247
+ rationale: input.rationale,
10248
+ signal: input.signal,
10249
+ startDate: input.startDate,
10250
+ endDate: input.endDate,
10251
+ durationWeeks: input.durationWeeks,
10252
+ confidenceImpact: input.confidenceImpact,
10253
+ autoShape: input.autoShape,
10254
+ autoFixPolicy: input.autoFixPolicy,
10255
+ beliefFocus: input.beliefFocus,
10256
+ targetQuestionIds: input.targetQuestionIds,
10257
+ targetBeliefIds: input.targetBeliefIds ?? input.beliefIds,
10258
+ keyQuestions: input.keyQuestions,
10259
+ proofArtifacts: input.proofArtifacts,
10260
+ decisionGate: input.decisionGate ?? (input.goCriteria || input.noGoSignals ? compactRecord4({
10261
+ goCriteria: input.goCriteria,
10262
+ noGoSignals: input.noGoSignals
10263
+ }) : void 0),
10264
+ evidenceSignals: input.evidenceSignals,
10265
+ dependsOn: input.dependsOn,
10266
+ blocks: input.blocks,
10267
+ campaign: input.campaign,
10268
+ lane: input.lane,
10269
+ laneOrderInCampaign: input.laneOrderInCampaign,
10270
+ orderInLane: input.orderInLane,
10271
+ staffingHint: input.staffingHint,
10272
+ domainPackId: input.domainPackId,
10273
+ lensId: input.lensId,
10274
+ linkedQuestionId: input.linkedQuestionId,
10275
+ lastReconciledAt: input.lastReconciledAt
10276
+ }),
9413
10277
  context
9414
10278
  )
9415
10279
  }
@@ -9427,7 +10291,7 @@ var worktreesContracts = [
9427
10291
  module: "worktrees",
9428
10292
  functionName: "activate",
9429
10293
  kind: "mutation",
9430
- inputProjection: worktreeInput
10294
+ inputProjection: activateWorktreeInput
9431
10295
  }
9432
10296
  }),
9433
10297
  surfaceContract({
@@ -9443,7 +10307,36 @@ var worktreesContracts = [
9443
10307
  convex: {
9444
10308
  module: "worktrees",
9445
10309
  functionName: "list",
9446
- kind: "query"
10310
+ kind: "query",
10311
+ inputProjection: (input) => compactRecord4({
10312
+ topicId: input.topicId,
10313
+ status: input.status,
10314
+ groupBy: input.groupBy,
10315
+ lane: input.lane,
10316
+ campaign: input.campaign,
10317
+ limit: input.limit
10318
+ })
10319
+ }
10320
+ }),
10321
+ surfaceContract({
10322
+ name: "list_campaigns",
10323
+ kind: "query",
10324
+ domain: "worktrees",
10325
+ surfaceClass: "platform_public",
10326
+ method: "GET",
10327
+ path: "/worktrees/campaigns",
10328
+ sdkNamespace: "worktrees",
10329
+ sdkMethod: "listCampaigns",
10330
+ summary: "List compact pipeline campaigns with nested lanes.",
10331
+ convex: {
10332
+ module: "worktrees",
10333
+ functionName: "listCampaigns",
10334
+ kind: "query",
10335
+ inputProjection: (input) => compactRecord4({
10336
+ topicId: input.topicId,
10337
+ status: input.status,
10338
+ limit: input.limit
10339
+ })
9447
10340
  }
9448
10341
  }),
9449
10342
  surfaceContract({
@@ -9459,7 +10352,8 @@ var worktreesContracts = [
9459
10352
  convex: {
9460
10353
  module: "worktrees",
9461
10354
  functionName: "listAll",
9462
- kind: "query"
10355
+ kind: "query",
10356
+ inputProjection: listAllWorktreesInput
9463
10357
  }
9464
10358
  }),
9465
10359
  surfaceContract({
@@ -9476,7 +10370,7 @@ var worktreesContracts = [
9476
10370
  module: "worktrees",
9477
10371
  functionName: "updateTargets",
9478
10372
  kind: "mutation",
9479
- inputProjection: worktreeInput
10373
+ inputProjection: worktreeTargetsInput
9480
10374
  }
9481
10375
  }),
9482
10376
  surfaceContract({
@@ -9493,7 +10387,7 @@ var worktreesContracts = [
9493
10387
  module: "worktrees",
9494
10388
  functionName: "updateMetadata",
9495
10389
  kind: "mutation",
9496
- inputProjection: worktreeInput
10390
+ inputProjection: worktreeMetadataInput
9497
10391
  }
9498
10392
  }),
9499
10393
  surfaceContract({
@@ -9509,12 +10403,17 @@ var worktreesContracts = [
9509
10403
  module: "worktrees",
9510
10404
  functionName: "complete",
9511
10405
  kind: "mutation",
9512
- inputProjection: (input) => ({
9513
- ...worktreeInput(input),
9514
- keyFindings: input.keyFindings ?? [input.summary ?? "Merged worktree"],
9515
- decisionsReached: input.decisionsReached ?? [],
9516
- nextSteps: input.nextSteps ?? []
9517
- })
10406
+ inputProjection: (input, context) => withUserId(
10407
+ {
10408
+ ...worktreeIdInput(input),
10409
+ keyFindings: input.keyFindings ?? [
10410
+ input.summary ?? "Merged worktree"
10411
+ ],
10412
+ decisionsReached: input.decisionsReached ?? [],
10413
+ nextSteps: input.nextSteps ?? []
10414
+ },
10415
+ context
10416
+ )
9518
10417
  }
9519
10418
  }),
9520
10419
  surfaceContract({
@@ -9530,11 +10429,7 @@ var worktreesContracts = [
9530
10429
  module: "worktrees",
9531
10430
  functionName: "updateMetadata",
9532
10431
  kind: "mutation",
9533
- inputProjection: (input) => ({
9534
- ...worktreeInput(input),
9535
- lastPushTargetContext: input.targetContext,
9536
- lastPushBeliefIds: input.beliefIds
9537
- })
10432
+ inputProjection: worktreeMetadataInput
9538
10433
  }
9539
10434
  }),
9540
10435
  surfaceContract({
@@ -9550,20 +10445,30 @@ var worktreesContracts = [
9550
10445
  module: "worktrees",
9551
10446
  functionName: "updateMetadata",
9552
10447
  kind: "mutation",
9553
- inputProjection: (input) => ({
9554
- ...worktreeInput(input),
9555
- lastPullRequestSummary: input.summary,
9556
- lastPullRequestReviewers: input.reviewers
9557
- })
10448
+ inputProjection: worktreeMetadataInput
9558
10449
  }
9559
10450
  })
9560
10451
  ];
9561
10452
 
9562
10453
  // ../contracts/src/function-registry/tasks.ts
9563
- var taskInput = (input) => ({
10454
+ var taskInput = (input) => compactRecord4({
9564
10455
  ...input,
9565
10456
  taskId: input.taskId ?? input.id
9566
10457
  });
10458
+ var taskTopicInput = (input) => {
10459
+ const parsed = listTasksProjection.inputSchema.safeParse(input);
10460
+ if (!parsed.success) {
10461
+ throw new Error(
10462
+ `list_tasks projection input rejected: ${parsed.error.message}`
10463
+ );
10464
+ }
10465
+ return compactRecord4(listTasksProjection.project(parsed.data));
10466
+ };
10467
+ var completeTaskInput = (input) => compactRecord4({
10468
+ taskId: input.taskId ?? input.id,
10469
+ outputSummary: input.outputSummary ?? input.summary,
10470
+ userId: input.userId
10471
+ });
9567
10472
  var tasksContracts = [
9568
10473
  surfaceContract({
9569
10474
  name: "create_task",
@@ -9593,8 +10498,10 @@ var tasksContracts = [
9593
10498
  convex: {
9594
10499
  module: "tasks",
9595
10500
  functionName: "getByTopic",
9596
- kind: "query"
9597
- }
10501
+ kind: "query",
10502
+ inputProjection: taskTopicInput
10503
+ },
10504
+ args: listTasksInputSchema
9598
10505
  }),
9599
10506
  surfaceContract({
9600
10507
  name: "update_task",
@@ -9626,12 +10533,29 @@ var tasksContracts = [
9626
10533
  module: "tasks",
9627
10534
  functionName: "complete",
9628
10535
  kind: "mutation",
9629
- inputProjection: taskInput
10536
+ inputProjection: completeTaskInput
9630
10537
  }
9631
10538
  })
9632
10539
  ];
9633
-
9634
- // ../contracts/src/function-registry/edges.ts
10540
+ var createEdgeArgs = z.object({
10541
+ from: GraphRefSchema,
10542
+ to: GraphRefSchema,
10543
+ edgeType: z.string(),
10544
+ globalId: z.string().optional(),
10545
+ weight: z.number().optional(),
10546
+ confidence: z.number().optional(),
10547
+ context: z.string().optional(),
10548
+ reasoning: z.string().optional(),
10549
+ derivationType: z.string().optional(),
10550
+ topicId: z.string().optional(),
10551
+ trustedBypassAccessCheck: z.boolean().optional()
10552
+ });
10553
+ function graphRefNodeId(ref) {
10554
+ if (ref.kind === "epistemic_node") {
10555
+ return ref.nodeId;
10556
+ }
10557
+ return `external_belief:${ref.ref.tenantId}:${ref.ref.beliefId}`;
10558
+ }
9635
10559
  var edgesContracts = [
9636
10560
  surfaceContract({
9637
10561
  name: "create_edge",
@@ -9646,16 +10570,35 @@ var edgesContracts = [
9646
10570
  module: "edges",
9647
10571
  functionName: "create",
9648
10572
  kind: "mutation",
9649
- inputProjection: (input, context) => withCreatedBy(
9650
- {
9651
- ...input,
9652
- fromNodeId: input.fromNodeId ?? input.sourceId,
9653
- toNodeId: input.toNodeId ?? input.targetId,
9654
- context: input.context ?? input.reasoning
9655
- },
9656
- context
9657
- )
9658
- }
10573
+ inputProjection: (input, context) => {
10574
+ const parsed = createEdgeArgs.parse(input);
10575
+ assertEdgePolicyAllowed(
10576
+ edgePolicyManifest,
10577
+ parsed.edgeType,
10578
+ parsed.from,
10579
+ parsed.to
10580
+ );
10581
+ const fromNodeId = graphRefNodeId(parsed.from);
10582
+ const toNodeId = graphRefNodeId(parsed.to);
10583
+ return withCreatedBy(
10584
+ compactRecord4({
10585
+ fromNodeId,
10586
+ toNodeId,
10587
+ edgeType: parsed.edgeType,
10588
+ globalId: parsed.globalId ?? `edge:${fromNodeId}:${toNodeId}:${parsed.edgeType}`,
10589
+ weight: parsed.weight,
10590
+ confidence: parsed.confidence,
10591
+ context: parsed.context ?? parsed.reasoning,
10592
+ derivationType: parsed.derivationType,
10593
+ skipLayerValidation: true,
10594
+ topicId: parsed.topicId,
10595
+ trustedBypassAccessCheck: parsed.trustedBypassAccessCheck
10596
+ }),
10597
+ context
10598
+ );
10599
+ }
10600
+ },
10601
+ args: createEdgeArgs
9659
10602
  }),
9660
10603
  surfaceContract({
9661
10604
  name: "query_lineage",
@@ -9670,9 +10613,12 @@ var edgesContracts = [
9670
10613
  module: "edges",
9671
10614
  functionName: "getLineage",
9672
10615
  kind: "query",
9673
- inputProjection: (input) => ({
9674
- ...input,
9675
- maxDepth: input.maxDepth ?? input.depth
10616
+ inputProjection: (input) => compactRecord4({
10617
+ nodeId: input.nodeId ?? input.startNode,
10618
+ maxDepth: input.maxDepth ?? input.depth,
10619
+ mode: input.mode,
10620
+ minLayer: input.minLayer,
10621
+ maxLayer: input.maxLayer
9676
10622
  })
9677
10623
  }
9678
10624
  })
@@ -9692,8 +10638,7 @@ var contradictionSeverity = (value) => {
9692
10638
  return "significant";
9693
10639
  }
9694
10640
  };
9695
- var flagContradictionInput = (input, context) => ({
9696
- ...input,
10641
+ var flagContradictionInput = (input, context) => compactRecord4({
9697
10642
  beliefId: input.beliefId ?? input.beliefA,
9698
10643
  supportingInsightIds: Array.isArray(input.supportingInsightIds) ? input.supportingInsightIds : [],
9699
10644
  contradictingInsightIds: Array.isArray(input.contradictingInsightIds) ? input.contradictingInsightIds : [input.beliefB].filter((value) => typeof value === "string"),
@@ -9707,6 +10652,18 @@ var flagContradictionInput = (input, context) => ({
9707
10652
  },
9708
10653
  createdBy: authUserId(context)
9709
10654
  });
10655
+ var lineageInput = (input) => compactRecord4({
10656
+ nodeId: input.nodeId ?? input.startNode ?? input.entityId,
10657
+ maxDepth: input.maxDepth ?? input.depth,
10658
+ mode: input.mode,
10659
+ minLayer: input.minLayer,
10660
+ maxLayer: input.maxLayer
10661
+ });
10662
+ var topicEdgesInput = (input) => compactRecord4({
10663
+ topicId: input.topicId,
10664
+ userId: input.userId,
10665
+ limit: input.limit
10666
+ });
9710
10667
  var graphContracts = [
9711
10668
  surfaceContract({
9712
10669
  name: "traverse_graph",
@@ -9720,7 +10677,8 @@ var graphContracts = [
9720
10677
  convex: {
9721
10678
  module: "edges",
9722
10679
  functionName: "getLineage",
9723
- kind: "query"
10680
+ kind: "query",
10681
+ inputProjection: lineageInput
9724
10682
  }
9725
10683
  }),
9726
10684
  surfaceContract({
@@ -9735,7 +10693,8 @@ var graphContracts = [
9735
10693
  convex: {
9736
10694
  module: "edges",
9737
10695
  functionName: "getByTopic",
9738
- kind: "query"
10696
+ kind: "query",
10697
+ inputProjection: topicEdgesInput
9739
10698
  }
9740
10699
  }),
9741
10700
  surfaceContract({
@@ -9765,7 +10724,10 @@ var graphContracts = [
9765
10724
  convex: {
9766
10725
  module: "edges",
9767
10726
  functionName: "findContradictions",
9768
- kind: "query"
10727
+ kind: "query",
10728
+ inputProjection: (input) => compactRecord4({
10729
+ nodeId: input.nodeId ?? input.beliefId
10730
+ })
9769
10731
  }
9770
10732
  }),
9771
10733
  surfaceContract({
@@ -9870,8 +10832,9 @@ var graphContracts = [
9870
10832
  summary: "Discover graph connections for an entity.",
9871
10833
  convex: {
9872
10834
  module: "edges",
9873
- functionName: "getByTopic",
9874
- kind: "query"
10835
+ functionName: "getLineage",
10836
+ kind: "query",
10837
+ inputProjection: lineageInput
9875
10838
  }
9876
10839
  }),
9877
10840
  surfaceContract({
@@ -9902,10 +10865,7 @@ var graphContracts = [
9902
10865
  module: "edges",
9903
10866
  functionName: "getLineage",
9904
10867
  kind: "query",
9905
- inputProjection: (input) => ({
9906
- ...input,
9907
- nodeId: input.nodeId ?? input.entityId
9908
- })
10868
+ inputProjection: lineageInput
9909
10869
  }
9910
10870
  })
9911
10871
  ];
@@ -9975,19 +10935,21 @@ var judgmentsContracts = [
9975
10935
  functionName: "create",
9976
10936
  kind: "mutation",
9977
10937
  inputProjection: (input, context) => withUserId(
9978
- {
9979
- ...input,
10938
+ compactRecord4({
10939
+ projectId: input.projectId,
10940
+ topicId: input.topicId,
9980
10941
  text: input.rationale,
9981
10942
  title: input.title,
9982
10943
  content: input.rationale,
9983
10944
  kind: "judgment",
9984
- sourceType: "agent",
9985
- metadata: {
10945
+ sourceType: "ai_generated",
10946
+ metadata: compactRecord4({
9986
10947
  confidence: input.confidence,
9987
10948
  beliefIds: input.beliefIds
9988
- },
10949
+ }),
10950
+ rationale: input.rationale ?? input.reasoning ?? "Recorded judgment evidence",
9989
10951
  trustedBypassAccessCheck: input.trustedBypassAccessCheck ?? true
9990
- },
10952
+ }),
9991
10953
  context
9992
10954
  )
9993
10955
  }
@@ -10005,9 +10967,12 @@ var judgmentsContracts = [
10005
10967
  module: "edges",
10006
10968
  functionName: "getLineage",
10007
10969
  kind: "query",
10008
- inputProjection: (input) => ({
10009
- ...input,
10010
- nodeId: input.nodeId ?? input.id
10970
+ inputProjection: (input) => compactRecord4({
10971
+ nodeId: input.nodeId ?? input.id,
10972
+ maxDepth: input.maxDepth ?? input.depth,
10973
+ mode: input.mode,
10974
+ minLayer: input.minLayer,
10975
+ maxLayer: input.maxLayer
10011
10976
  })
10012
10977
  }
10013
10978
  })
@@ -10133,7 +11098,10 @@ var coordinationContracts = [
10133
11098
  module: "coordination",
10134
11099
  functionName: "getInbox",
10135
11100
  kind: "query",
10136
- injectSessionId: "sessionId"
11101
+ injectSessionId: "sessionId",
11102
+ inputProjection: (input) => compactRecord4({
11103
+ limit: input.limit
11104
+ })
10137
11105
  }
10138
11106
  }),
10139
11107
  surfaceContract({
@@ -10151,7 +11119,6 @@ var coordinationContracts = [
10151
11119
  kind: "mutation",
10152
11120
  injectSessionId: "sessionId",
10153
11121
  inputProjection: (input) => ({
10154
- ...input,
10155
11122
  touchedFiles: stringArray(input.touchedFiles) ?? stringArray(input.files) ?? stringArray(input.paths) ?? []
10156
11123
  })
10157
11124
  }
@@ -10168,7 +11135,10 @@ var coordinationContracts = [
10168
11135
  convex: {
10169
11136
  module: "worktrees",
10170
11137
  functionName: "get",
10171
- kind: "query"
11138
+ kind: "query",
11139
+ inputProjection: (input) => compactRecord4({
11140
+ worktreeId: input.worktreeId ?? input.id
11141
+ })
10172
11142
  }
10173
11143
  })
10174
11144
  ];
@@ -10187,7 +11157,13 @@ var pipelineContracts = [
10187
11157
  convex: {
10188
11158
  module: "worktrees",
10189
11159
  functionName: "listAll",
10190
- kind: "query"
11160
+ kind: "query",
11161
+ inputProjection: (input) => compactRecord4({
11162
+ status: input.status,
11163
+ lane: input.lane,
11164
+ campaign: input.campaign,
11165
+ limit: input.limit
11166
+ })
10191
11167
  }
10192
11168
  }),
10193
11169
  surfaceContract({
@@ -10237,43 +11213,63 @@ var recordScopeLearningArgs = z.object({
10237
11213
  linkedBeliefNodeId: z.string().optional().describe("Optional belief to attach evidence to"),
10238
11214
  evidenceRelation: z.enum(["supports", "contradicts"]).optional().describe("Relation to linked belief"),
10239
11215
  confidence: z.number().optional().describe("Optional confidence in [0,1]"),
11216
+ rationale: z.string().optional().describe("Why this learning should enter the reasoning graph"),
10240
11217
  createQuestionText: z.string().optional().describe("Optional follow-up question text"),
10241
11218
  createBeliefText: z.string().optional().describe("Optional new belief text"),
10242
11219
  beliefType: z.string().optional().describe("Optional belief type for createBeliefText")
10243
11220
  });
10244
- var learningInput = (input, context) => withUserId(
10245
- {
10246
- ...input,
10247
- text: input.summary ?? input.text,
10248
- title: input.title ?? input.summary ?? "Scope learning",
10249
- content: input.body ?? input.content ?? input.summary,
10250
- kind: input.kind ?? input.sourceKind ?? "learning",
10251
- tags: input.tags ?? [],
10252
- metadata: {
10253
- sourceRef: input.sourceRef,
10254
- sourceKind: input.sourceKind,
10255
- touchedPaths: input.touchedPaths
10256
- },
10257
- trustedBypassAccessCheck: input.trustedBypassAccessCheck ?? true
10258
- },
10259
- context
10260
- );
11221
+ var learningInput = (input, context) => {
11222
+ const sourceKind = input.sourceKind ?? input.externalSourceType;
11223
+ return withUserId(
11224
+ compactRecord4({
11225
+ projectId: input.projectId,
11226
+ topicId: input.topicId,
11227
+ text: input.summary ?? input.text,
11228
+ title: input.title ?? input.summary ?? "Scope learning",
11229
+ content: input.body ?? input.content ?? input.summary,
11230
+ contentType: input.contentType,
11231
+ kind: input.kind ?? "learning",
11232
+ tags: input.tags ?? [],
11233
+ sourceType: input.sourceType,
11234
+ externalSourceType: input.externalSourceType ?? input.sourceKind,
11235
+ sourceUrl: input.sourceUrl,
11236
+ metadata: compactRecord4({
11237
+ ...recordValue2(input.metadata),
11238
+ sourceRef: input.sourceRef,
11239
+ sourceKind,
11240
+ touchedPaths: input.touchedPaths,
11241
+ createQuestionText: input.createQuestionText,
11242
+ createBeliefText: input.createBeliefText,
11243
+ beliefType: input.beliefType
11244
+ }),
11245
+ linkedBeliefNodeId: input.linkedBeliefNodeId,
11246
+ evidenceRelation: input.evidenceRelation,
11247
+ confidence: input.confidence,
11248
+ rationale: input.rationale ?? input.reasoning ?? input.summary ?? input.text ?? "Recorded scope learning",
11249
+ trustedBypassAccessCheck: input.trustedBypassAccessCheck ?? true
11250
+ }),
11251
+ context
11252
+ );
11253
+ };
10261
11254
  var attemptInput = (input, context) => withUserId(
10262
- {
10263
- ...input,
11255
+ compactRecord4({
11256
+ projectId: input.projectId,
11257
+ topicId: input.topicId,
10264
11258
  text: input.description,
10265
11259
  title: input.title ?? input.description,
10266
11260
  content: input.errorMessage ?? input.description,
10267
11261
  kind: "code_attempt",
10268
11262
  tags: ["code_attempt"],
10269
- metadata: {
11263
+ metadata: compactRecord4({
11264
+ ...recordValue2(input.metadata),
10270
11265
  filePaths: input.filePaths,
10271
11266
  filePath: input.filePath,
10272
11267
  errorMessage: input.errorMessage,
10273
11268
  linkedBeliefId: input.linkedBeliefId
10274
- },
11269
+ }),
11270
+ rationale: input.rationale ?? input.reasoning ?? input.errorMessage ?? input.description ?? "Recorded implementation attempt",
10275
11271
  trustedBypassAccessCheck: input.trustedBypassAccessCheck ?? true
10276
- },
11272
+ }),
10277
11273
  context
10278
11274
  );
10279
11275
  var codingContracts = [
@@ -10330,7 +11326,13 @@ var codingContracts = [
10330
11326
  convex: {
10331
11327
  module: "evidence",
10332
11328
  functionName: "getByTopic",
10333
- kind: "query"
11329
+ kind: "query",
11330
+ inputProjection: (input) => compactRecord4({
11331
+ topicId: input.topicId,
11332
+ limit: input.limit,
11333
+ status: input.status,
11334
+ userId: input.userId
11335
+ })
10334
11336
  }
10335
11337
  }),
10336
11338
  surfaceContract({
@@ -10345,7 +11347,13 @@ var codingContracts = [
10345
11347
  convex: {
10346
11348
  module: "evidence",
10347
11349
  functionName: "getByTopic",
10348
- kind: "query"
11350
+ kind: "query",
11351
+ inputProjection: (input) => compactRecord4({
11352
+ topicId: input.topicId,
11353
+ limit: input.limit,
11354
+ status: input.status,
11355
+ userId: input.userId
11356
+ })
10349
11357
  }
10350
11358
  }),
10351
11359
  surfaceContract({
@@ -10377,9 +11385,11 @@ var codingContracts = [
10377
11385
  module: "evidence",
10378
11386
  functionName: "getByTopic",
10379
11387
  kind: "query",
10380
- inputProjection: (input) => ({
10381
- ...input,
10382
- topicId: input.topicId ?? input.query
11388
+ inputProjection: (input) => compactRecord4({
11389
+ topicId: input.topicId ?? input.query,
11390
+ limit: input.limit,
11391
+ status: input.status,
11392
+ userId: input.userId
10383
11393
  })
10384
11394
  }
10385
11395
  })
@@ -10926,8 +11936,6 @@ function errorResponse(args) {
10926
11936
  }
10927
11937
  );
10928
11938
  }
10929
-
10930
- // ../server-core/src/kernelApi.ts
10931
11939
  var GLOBAL_KEY = "__LUCERN_SERVER_CORE_KERNEL_API_BINDING__";
10932
11940
  function store() {
10933
11941
  return globalThis;
@@ -10941,10 +11949,28 @@ function getBinding() {
10941
11949
  }
10942
11950
  return current;
10943
11951
  }
10944
- function makeProxy(which) {
11952
+ function readPath(root, path) {
11953
+ let cursor = root;
11954
+ for (const part of path) {
11955
+ if (cursor == null || typeof cursor !== "object") {
11956
+ return void 0;
11957
+ }
11958
+ cursor = cursor[part];
11959
+ }
11960
+ return cursor;
11961
+ }
11962
+ function resolveApiPath(binding, which, path) {
11963
+ return readPath(binding[which], path);
11964
+ }
11965
+ function makeProxy(which, path = []) {
10945
11966
  return new Proxy({}, {
10946
11967
  get(_target, prop) {
10947
- return getBinding()[which][prop];
11968
+ if (typeof prop !== "string") {
11969
+ return void 0;
11970
+ }
11971
+ const nextPath = [...path, prop];
11972
+ const resolved = resolveApiPath(getBinding(), which, nextPath);
11973
+ return resolved === void 0 ? makeProxy(which, nextPath) : resolved;
10948
11974
  }
10949
11975
  });
10950
11976
  }
@@ -10969,6 +11995,7 @@ var allowAlwaysPolicy = {
10969
11995
  };
10970
11996
 
10971
11997
  // ../server-core/src/domain/beliefs.ts
11998
+ var DEFAULT_BELIEF_BASE_RATE = 0.5;
10972
11999
  function asRecord(value) {
10973
12000
  return value && typeof value === "object" && !Array.isArray(value) ? value : {};
10974
12001
  }
@@ -11006,17 +12033,8 @@ function normalizeRequiredString(value, field) {
11006
12033
  }
11007
12034
  return normalized;
11008
12035
  }
11009
- function normalizeRequiredBaseRate(value) {
11010
- const baseRate = readNumber(value);
11011
- if (baseRate === void 0) {
11012
- throwBeliefsError({
11013
- message: "[beliefs] baseRate is required.",
11014
- status: 400,
11015
- code: "INVALID_REQUEST",
11016
- invariantCode: "request.valid_shape",
11017
- suggestion: "Provide baseRate in the request payload."
11018
- });
11019
- }
12036
+ function normalizeBaseRate(value) {
12037
+ const baseRate = readNumber(value) ?? DEFAULT_BELIEF_BASE_RATE;
11020
12038
  validateOpinionComponent(baseRate, "baseRate");
11021
12039
  return baseRate;
11022
12040
  }
@@ -11093,18 +12111,21 @@ function normalizeConfidenceTrigger(value) {
11093
12111
  case "evidence_removed":
11094
12112
  case "contradiction_detected":
11095
12113
  case "contradiction_resolved":
11096
- case "manual":
11097
- case "decay":
11098
12114
  case "agent_assessment":
11099
12115
  case "worktree_outcome":
11100
12116
  case "worktree_completed":
11101
12117
  case "fusion":
11102
12118
  case "discount":
11103
12119
  case "deduction":
11104
- case "backfill_synthetic":
11105
12120
  return normalized;
11106
12121
  default:
11107
- return "manual";
12122
+ throwBeliefsError({
12123
+ message: "[beliefs] trigger must name an evidence-bearing cause.",
12124
+ status: 400,
12125
+ code: "INVALID_REQUEST",
12126
+ invariantCode: "belief.confidence_append_only",
12127
+ suggestion: "Use evidence_added, evidence_removed, contradiction_detected, contradiction_resolved, agent_assessment, worktree_outcome, worktree_completed, fusion, discount, or deduction."
12128
+ });
11108
12129
  }
11109
12130
  }
11110
12131
  function normalizeConditionType(value) {
@@ -11273,12 +12294,17 @@ function normalizeHistoryEntry(value) {
11273
12294
  opinion.a = baseRate;
11274
12295
  }
11275
12296
  const triggeringEvidenceRawId = readString(record.triggeringEvidenceId) ?? readStringArray(record.triggeringEvidenceIds)?.[0];
12297
+ const triggeringQuestionRawId = readString(record.triggeringQuestionId);
12298
+ const triggeringAnswerRawId = readString(record.triggeringAnswerId);
12299
+ const triggeringContradictionRawId = readString(
12300
+ record.triggeringContradictionId
12301
+ );
11276
12302
  const triggeringWorktreeRawId = readString(record.triggeringWorktreeId);
11277
12303
  const slOperator = readString(record.slOperator);
11278
12304
  return {
11279
12305
  ...readString(record._id) ? { id: readString(record._id) } : {},
11280
12306
  confidence: clampNumber(readNumber(record.confidence) ?? 0, 0, 1),
11281
- trigger: readString(record.trigger) ?? "manual",
12307
+ trigger: normalizeRequiredString(record.trigger, "trigger"),
11282
12308
  ...readString(record.rationale) ? { rationale: readString(record.rationale) } : {},
11283
12309
  ...readNumber(record.assessedAt) ?? readNumber(record.timestamp) ? {
11284
12310
  timestamp: readNumber(record.assessedAt) ?? readNumber(record.timestamp)
@@ -11293,6 +12319,24 @@ function normalizeHistoryEntry(value) {
11293
12319
  triggeringEvidenceRawId
11294
12320
  )
11295
12321
  } : {},
12322
+ ...triggeringQuestionRawId ? {
12323
+ triggeringQuestionId: encodeHistoryReferenceId(
12324
+ "que",
12325
+ triggeringQuestionRawId
12326
+ )
12327
+ } : {},
12328
+ ...triggeringAnswerRawId ? {
12329
+ triggeringAnswerId: encodeHistoryReferenceId(
12330
+ "ans",
12331
+ triggeringAnswerRawId
12332
+ )
12333
+ } : {},
12334
+ ...triggeringContradictionRawId ? {
12335
+ triggeringContradictionId: encodeHistoryReferenceId(
12336
+ "con",
12337
+ triggeringContradictionRawId
12338
+ )
12339
+ } : {},
11296
12340
  ...triggeringWorktreeRawId ? {
11297
12341
  triggeringWorktreeId: encodeHistoryReferenceId(
11298
12342
  "wt",
@@ -11441,19 +12485,6 @@ function normalizeRelationships(relationships) {
11441
12485
  }
11442
12486
  return [...deduped.values()];
11443
12487
  }
11444
- function toOpinion(confidence, certainty) {
11445
- const boundedConfidence = clampNumber(confidence, 0, 1);
11446
- const boundedCertainty = certainty === void 0 ? boundedConfidence === 0.5 ? 0.75 : 1 : clampNumber(certainty, 0, 1);
11447
- const belief = boundedConfidence * boundedCertainty;
11448
- const disbelief = (1 - boundedConfidence) * boundedCertainty;
11449
- const uncertainty = clampNumber(1 - boundedCertainty, 0, 1);
11450
- return {
11451
- b: belief,
11452
- d: disbelief,
11453
- u: uncertainty,
11454
- a: 0.5
11455
- };
11456
- }
11457
12488
  function validateOpinionComponent(value, field) {
11458
12489
  if (value < 0 || value > 1) {
11459
12490
  throwBeliefsError({
@@ -11474,53 +12505,108 @@ function normalizeOpinionTuple(input) {
11474
12505
  const providedTupleCount = tupleValues.filter(
11475
12506
  (value) => value !== void 0
11476
12507
  ).length;
11477
- if (providedTupleCount > 0) {
11478
- if (providedTupleCount !== tupleValues.length) {
11479
- throwBeliefsError({
11480
- message: "[beliefs] belief, disbelief, uncertainty, and baseRate must all be provided together.",
11481
- status: 400,
11482
- code: "INVALID_REQUEST",
11483
- invariantCode: "belief.confidence_append_only",
11484
- suggestion: "Provide the full subjective-logic tuple or fall back to scalar confidence + certainty."
11485
- });
11486
- }
11487
- validateOpinionComponent(belief, "belief");
11488
- validateOpinionComponent(disbelief, "disbelief");
11489
- validateOpinionComponent(uncertainty, "uncertainty");
11490
- validateOpinionComponent(baseRate, "baseRate");
11491
- return {
11492
- b: belief,
11493
- d: disbelief,
11494
- u: uncertainty,
11495
- a: baseRate
11496
- };
11497
- }
11498
- const confidence = readNumber(input.confidence);
11499
- if (confidence === void 0) {
11500
- throwBeliefsError({
11501
- message: "[beliefs] confidence is required when no subjective-logic tuple is provided.",
11502
- status: 400,
11503
- code: "INVALID_REQUEST",
11504
- invariantCode: "belief.confidence_append_only",
11505
- suggestion: "Provide either confidence in [0, 1] or the full belief/disbelief/uncertainty/baseRate tuple."
11506
- });
11507
- }
11508
- if (confidence < 0 || confidence > 1) {
12508
+ if (providedTupleCount !== tupleValues.length) {
11509
12509
  throwBeliefsError({
11510
- message: "[beliefs] confidence must be within [0, 1].",
12510
+ message: "[beliefs] belief, disbelief, uncertainty, and baseRate must all be provided together.",
11511
12511
  status: 400,
11512
12512
  code: "INVALID_REQUEST",
11513
12513
  invariantCode: "belief.confidence_append_only",
11514
- suggestion: "Clamp confidence into the inclusive [0, 1] interval."
12514
+ suggestion: "Provide the full subjective-logic tuple; scalar confidence payloads are not accepted."
11515
12515
  });
11516
12516
  }
11517
- return toOpinion(confidence, readNumber(input.certainty));
12517
+ validateOpinionComponent(belief, "belief");
12518
+ validateOpinionComponent(disbelief, "disbelief");
12519
+ validateOpinionComponent(uncertainty, "uncertainty");
12520
+ validateOpinionComponent(baseRate, "baseRate");
12521
+ return {
12522
+ b: belief,
12523
+ d: disbelief,
12524
+ u: uncertainty,
12525
+ a: baseRate
12526
+ };
11518
12527
  }
11519
12528
  function projectOpinion(opinion) {
11520
12529
  return opinion.b + opinion.a * opinion.u;
11521
12530
  }
12531
+ function normalizeEvidenceReference(value) {
12532
+ return readString(value) ? decodeExternalId(readString(value), "evi") : void 0;
12533
+ }
12534
+ function normalizeQuestionReference(value) {
12535
+ return readString(value) ? decodeExternalId(readString(value), "que") : void 0;
12536
+ }
12537
+ function normalizeAnswerReference(value) {
12538
+ return readString(value) ? decodeExternalId(readString(value), "ans") : void 0;
12539
+ }
12540
+ function normalizeContradictionReference(value) {
12541
+ return readString(value) ? decodeExternalId(readString(value), "con") : void 0;
12542
+ }
12543
+ function normalizeWorktreeReference(value) {
12544
+ return readString(value) ? decodeExternalId(readString(value), "wt") : void 0;
12545
+ }
12546
+ function requireModulationProvenance(trigger, input) {
12547
+ const provenance = {
12548
+ triggeringEvidenceId: normalizeEvidenceReference(input.triggeringEvidenceId),
12549
+ triggeringQuestionId: normalizeQuestionReference(input.triggeringQuestionId),
12550
+ triggeringAnswerId: normalizeAnswerReference(input.triggeringAnswerId),
12551
+ triggeringContradictionId: normalizeContradictionReference(
12552
+ input.triggeringContradictionId
12553
+ ),
12554
+ triggeringWorktreeId: normalizeWorktreeReference(
12555
+ input.triggeringWorktreeId
12556
+ )
12557
+ };
12558
+ const hasTruthBearingArtifact = Object.values(provenance).some(Boolean);
12559
+ const fail = (message, suggestion) => throwBeliefsError({
12560
+ message,
12561
+ status: 400,
12562
+ code: "INVALID_REQUEST",
12563
+ invariantCode: "belief.confidence_append_only",
12564
+ suggestion
12565
+ });
12566
+ switch (trigger) {
12567
+ case "evidence_added":
12568
+ case "evidence_removed":
12569
+ if (!provenance.triggeringEvidenceId) {
12570
+ fail(
12571
+ "[beliefs] Evidence-triggered confidence modulation requires triggeringEvidenceId.",
12572
+ "Create or link the evidence first, then pass its evidence ID."
12573
+ );
12574
+ }
12575
+ break;
12576
+ case "contradiction_detected":
12577
+ case "contradiction_resolved":
12578
+ if (!provenance.triggeringContradictionId) {
12579
+ fail(
12580
+ "[beliefs] Contradiction-triggered confidence modulation requires triggeringContradictionId.",
12581
+ "Create or resolve the contradiction first, then pass its contradiction ID."
12582
+ );
12583
+ }
12584
+ break;
12585
+ case "worktree_outcome":
12586
+ case "worktree_completed":
12587
+ if (!provenance.triggeringWorktreeId) {
12588
+ fail(
12589
+ "[beliefs] Worktree-triggered confidence modulation requires triggeringWorktreeId.",
12590
+ "Complete the worktree first, then pass its worktree ID."
12591
+ );
12592
+ }
12593
+ break;
12594
+ case "agent_assessment":
12595
+ case "fusion":
12596
+ case "discount":
12597
+ case "deduction":
12598
+ if (!hasTruthBearingArtifact) {
12599
+ fail(
12600
+ "[beliefs] Confidence modulation requires evidence, answered question, answer, contradiction, or worktree provenance.",
12601
+ "Pass triggeringEvidenceId, triggeringQuestionId, triggeringAnswerId, triggeringContradictionId, or triggeringWorktreeId."
12602
+ );
12603
+ }
12604
+ break;
12605
+ }
12606
+ return provenance;
12607
+ }
11522
12608
  async function createBelief(port, input) {
11523
- const baseRate = normalizeRequiredBaseRate(input.baseRate);
12609
+ const baseRate = normalizeBaseRate(input.baseRate);
11524
12610
  const created = await port.createBelief({
11525
12611
  topicId: normalizeRequiredString(input.topicId, "topicId"),
11526
12612
  text: normalizeRequiredString(input.text, "text"),
@@ -11635,6 +12721,8 @@ async function updateBeliefConfidence(port, input, options) {
11635
12721
  );
11636
12722
  const opinion = normalizeOpinionTuple(input);
11637
12723
  const projectedConfidence = projectOpinion(opinion);
12724
+ const trigger = normalizeConfidenceTrigger(input.trigger);
12725
+ const provenance = requireModulationProvenance(trigger, input);
11638
12726
  const existing = await port.fetchBelief(rawId);
11639
12727
  const policy = allowAlwaysPolicy;
11640
12728
  const decision = await policy.canScore({
@@ -11653,13 +12741,13 @@ async function updateBeliefConfidence(port, input, options) {
11653
12741
  details: { beliefId: encodeId("bel", rawId) }
11654
12742
  });
11655
12743
  }
11656
- const trigger = normalizeConfidenceTrigger(input.trigger);
11657
12744
  const rationale = normalizeRequiredString(input.rationale, "rationale");
11658
12745
  const result = await port.modulateConfidence({
11659
12746
  beliefRawId: rawId,
11660
12747
  opinion,
11661
12748
  trigger,
11662
- rationale
12749
+ rationale,
12750
+ ...provenance
11663
12751
  });
11664
12752
  const requestId = createRequestId();
11665
12753
  const relationships = normalizeRelationships(await port.getRelationships(rawId));
@@ -12508,7 +13596,12 @@ function createGatewayBeliefPort(authContext) {
12508
13596
  belief: input.opinion.b,
12509
13597
  disbelief: input.opinion.d,
12510
13598
  uncertainty: input.opinion.u,
12511
- baseRate: input.opinion.a
13599
+ baseRate: input.opinion.a,
13600
+ triggeringEvidenceId: input.triggeringEvidenceId,
13601
+ triggeringQuestionId: input.triggeringQuestionId,
13602
+ triggeringAnswerId: input.triggeringAnswerId,
13603
+ triggeringContradictionId: input.triggeringContradictionId,
13604
+ triggeringWorktreeId: input.triggeringWorktreeId
12512
13605
  });
12513
13606
  },
12514
13607
  archiveBelief(input) {
@@ -13826,6 +14919,7 @@ async function createEvidence(deps, input) {
13826
14919
  ...input,
13827
14920
  topicId: normalizeRequiredString4(input.topicId, "topicId"),
13828
14921
  text: normalizeRequiredString4(input.text, "text"),
14922
+ rationale: normalizeRequiredString4(input.rationale, "rationale"),
13829
14923
  weight: normalizeWeight(input.weight, 1),
13830
14924
  target
13831
14925
  });
@@ -13965,7 +15059,11 @@ function createGatewayEvidencePort(authContext) {
13965
15059
  contentType: input.contentType,
13966
15060
  kind: input.kind,
13967
15061
  sourceUrl: input.source,
13968
- metadata: input.metadata,
15062
+ metadata: {
15063
+ ...input.metadata ?? {},
15064
+ rationale: input.rationale
15065
+ },
15066
+ rationale: input.rationale,
13969
15067
  userId: authContext.userId
13970
15068
  });
13971
15069
  const createdRecord = created && typeof created === "object" ? created : {};
@@ -17180,6 +18278,24 @@ function readString19(value) {
17180
18278
  function readNumber13(value) {
17181
18279
  return typeof value === "number" && Number.isFinite(value) ? value : void 0;
17182
18280
  }
18281
+ function normalizeGroupBy(value) {
18282
+ if (value === "lane" || value === "flat") {
18283
+ return value;
18284
+ }
18285
+ return "campaign";
18286
+ }
18287
+ function readCampaign(record) {
18288
+ return readNumber13(record.campaign);
18289
+ }
18290
+ function readLane(record) {
18291
+ return readString19(record.lane);
18292
+ }
18293
+ function readLaneOrderInCampaign(record) {
18294
+ return readNumber13(record.laneOrderInCampaign);
18295
+ }
18296
+ function readOrderInLane(record) {
18297
+ return readNumber13(record.orderInLane);
18298
+ }
17183
18299
  function readStringArray9(value) {
17184
18300
  if (!Array.isArray(value)) {
17185
18301
  return void 0;
@@ -17187,6 +18303,9 @@ function readStringArray9(value) {
17187
18303
  const normalized = value.map((entry) => readString19(entry)).filter((entry) => Boolean(entry));
17188
18304
  return normalized.length > 0 ? normalized : void 0;
17189
18305
  }
18306
+ function compareNullableNumber(left, right, fallback = 9999) {
18307
+ return (left ?? fallback) - (right ?? fallback);
18308
+ }
17190
18309
  function requireString3(value, field) {
17191
18310
  const normalized = readString19(value);
17192
18311
  if (!normalized) {
@@ -17246,21 +18365,25 @@ function normalizeWorktreeRecord(value) {
17246
18365
  }
17247
18366
  const worktreeId = encodeWorktreeId(rawId);
17248
18367
  const topicRawId = readString19(record.topicId);
18368
+ const campaign = readCampaign(record);
18369
+ const lane = readLane(record);
18370
+ const laneOrderInCampaign = readLaneOrderInCampaign(record);
18371
+ const orderInLane = readOrderInLane(record);
17249
18372
  return {
17250
18373
  worktreeId,
17251
18374
  id: worktreeId,
17252
18375
  ...topicRawId ? { topicId: encodeTopicId3(topicRawId) } : {},
17253
18376
  title: readString19(record.title) ?? readString19(record.name) ?? "Untitled",
17254
18377
  ...readString19(record.status) ? { status: readString19(record.status) } : {},
18378
+ ...campaign !== void 0 ? { campaign } : {},
17255
18379
  ...readString19(record.phase) ? { phase: readString19(record.phase) } : {},
17256
18380
  ...readString19(record.branchId) !== void 0 ? { branchId: readString19(record.branchId) ?? null } : {},
17257
18381
  ...readString19(record.objective) ? { objective: readString19(record.objective) } : {},
17258
18382
  ...readString19(record.hypothesis) ? { hypothesis: readString19(record.hypothesis) } : {},
17259
18383
  ...readString19(record.gate) ? { gate: readString19(record.gate) } : {},
17260
- ...readString19(record.track) ? { track: readString19(record.track) } : {},
17261
- ...readNumber13(record.trackPosition) !== void 0 ? { trackPosition: readNumber13(record.trackPosition) } : {},
17262
- ...readNumber13(record.executionBand) !== void 0 ? { executionBand: readNumber13(record.executionBand) } : {},
17263
- ...readNumber13(record.executionOrder) !== void 0 ? { executionOrder: readNumber13(record.executionOrder) } : {},
18384
+ ...lane ? { lane } : {},
18385
+ ...laneOrderInCampaign !== void 0 ? { laneOrderInCampaign } : {},
18386
+ ...orderInLane !== void 0 ? { orderInLane } : {},
17264
18387
  ...readStringArray9(record.dependsOn) ? {
17265
18388
  dependsOn: readStringArray9(record.dependsOn).map(
17266
18389
  (id) => encodeWorktreeId(id)
@@ -17304,6 +18427,124 @@ function dedupeWorktrees(records) {
17304
18427
  }
17305
18428
  return [...byId.values()];
17306
18429
  }
18430
+ function sortWorktreeRecords(records) {
18431
+ return [...records].sort((left, right) => {
18432
+ const campaignDiff = compareNullableNumber(left.campaign, right.campaign);
18433
+ if (campaignDiff !== 0) {
18434
+ return campaignDiff;
18435
+ }
18436
+ const laneOrderDiff = compareNullableNumber(
18437
+ left.laneOrderInCampaign,
18438
+ right.laneOrderInCampaign
18439
+ );
18440
+ if (laneOrderDiff !== 0) {
18441
+ return laneOrderDiff;
18442
+ }
18443
+ const laneDiff = (left.lane ?? "~").localeCompare(right.lane ?? "~");
18444
+ if (laneDiff !== 0) {
18445
+ return laneDiff;
18446
+ }
18447
+ const orderDiff = compareNullableNumber(
18448
+ left.orderInLane,
18449
+ right.orderInLane
18450
+ );
18451
+ if (orderDiff !== 0) {
18452
+ return orderDiff;
18453
+ }
18454
+ return left.title.localeCompare(right.title);
18455
+ });
18456
+ }
18457
+ function groupWorktreesByLane(records) {
18458
+ const groups2 = /* @__PURE__ */ new Map();
18459
+ for (const worktree of sortWorktreeRecords(records)) {
18460
+ const lane = worktree.lane ?? null;
18461
+ const key = lane ?? "__unlaned__";
18462
+ const group = groups2.get(key) ?? {
18463
+ lane,
18464
+ laneOrderInCampaign: worktree.laneOrderInCampaign ?? null,
18465
+ worktrees: []
18466
+ };
18467
+ group.laneOrderInCampaign = group.laneOrderInCampaign ?? worktree.laneOrderInCampaign ?? null;
18468
+ group.worktrees.push(worktree);
18469
+ groups2.set(key, group);
18470
+ }
18471
+ return [...groups2.values()].sort((left, right) => {
18472
+ const orderDiff = compareNullableNumber(
18473
+ left.laneOrderInCampaign,
18474
+ right.laneOrderInCampaign
18475
+ );
18476
+ if (orderDiff !== 0) {
18477
+ return orderDiff;
18478
+ }
18479
+ return (left.lane ?? "~").localeCompare(right.lane ?? "~");
18480
+ });
18481
+ }
18482
+ function groupWorktreesByCampaign(records) {
18483
+ const campaignGroups = /* @__PURE__ */ new Map();
18484
+ for (const worktree of sortWorktreeRecords(records)) {
18485
+ const campaign = worktree.campaign ?? null;
18486
+ const rows = campaignGroups.get(campaign) ?? [];
18487
+ rows.push(worktree);
18488
+ campaignGroups.set(campaign, rows);
18489
+ }
18490
+ return [...campaignGroups.entries()].sort(([left], [right]) => compareNullableNumber(left, right)).map(([campaign, rows]) => ({
18491
+ campaign,
18492
+ lanes: groupWorktreesByLane(rows)
18493
+ }));
18494
+ }
18495
+ function decorateWorktreeListResult(worktrees2, groupBy) {
18496
+ const result = {
18497
+ worktrees: sortWorktreeRecords(worktrees2),
18498
+ total: worktrees2.length,
18499
+ groupBy
18500
+ };
18501
+ if (groupBy === "campaign") {
18502
+ result.campaigns = groupWorktreesByCampaign(worktrees2);
18503
+ } else if (groupBy === "lane") {
18504
+ result.lanes = groupWorktreesByLane(worktrees2);
18505
+ }
18506
+ return result;
18507
+ }
18508
+ function buildWorktreeCampaignList(records) {
18509
+ const campaigns = groupWorktreesByCampaign(records).map((campaignGroup) => ({
18510
+ campaign: campaignGroup.campaign,
18511
+ lanes: campaignGroup.lanes.map((laneGroup) => {
18512
+ const worktrees2 = laneGroup.worktrees;
18513
+ const nextWorktree = worktrees2.find(
18514
+ (worktree) => worktree.status !== "completed" && worktree.status !== "merged" && worktree.status !== "dismissed" && worktree.status !== "abandoned"
18515
+ );
18516
+ const blockedCount = worktrees2.filter(
18517
+ (worktree) => (worktree.dependsOn ?? []).length > 0
18518
+ ).length;
18519
+ return {
18520
+ lane: laneGroup.lane,
18521
+ laneOrderInCampaign: laneGroup.laneOrderInCampaign,
18522
+ worktreeCount: worktrees2.length,
18523
+ activeCount: worktrees2.filter((worktree) => worktree.status === "active").length,
18524
+ readyCount: worktrees2.filter(
18525
+ (worktree) => (worktree.status === "planning" || worktree.status === "suggested") && (worktree.dependsOn ?? []).length === 0
18526
+ ).length,
18527
+ blockedCount,
18528
+ completedCount: worktrees2.filter(
18529
+ (worktree) => worktree.status === "completed" || worktree.status === "merged"
18530
+ ).length,
18531
+ ...nextWorktree ? {
18532
+ nextWorktree: {
18533
+ worktreeId: nextWorktree.worktreeId,
18534
+ title: nextWorktree.title,
18535
+ status: nextWorktree.status,
18536
+ orderInLane: nextWorktree.orderInLane,
18537
+ gate: nextWorktree.gate
18538
+ }
18539
+ } : {}
18540
+ };
18541
+ })
18542
+ }));
18543
+ return {
18544
+ campaigns,
18545
+ totalWorktrees: records.length
18546
+ };
18547
+ }
17307
18548
  async function createWorktree(deps, input) {
17308
18549
  const topicRawId = decodeExternalId9(input.topicId, "top", "topicId");
17309
18550
  const created = await deps.createWorktree({
@@ -17316,7 +18557,10 @@ async function createWorktree(deps, input) {
17316
18557
  ),
17317
18558
  autoShape: typeof input.autoShape === "boolean" ? input.autoShape : void 0,
17318
18559
  domainPackId: readString19(input.domainPackId),
17319
- executionOrder: typeof input.executionOrder === "number" && Number.isFinite(input.executionOrder) ? input.executionOrder : void 0,
18560
+ campaign: typeof input.campaign === "number" && Number.isFinite(input.campaign) ? input.campaign : void 0,
18561
+ lane: readString19(input.lane),
18562
+ laneOrderInCampaign: typeof input.laneOrderInCampaign === "number" && Number.isFinite(input.laneOrderInCampaign) ? input.laneOrderInCampaign : void 0,
18563
+ orderInLane: typeof input.orderInLane === "number" && Number.isFinite(input.orderInLane) ? input.orderInLane : void 0,
17320
18564
  dependsOn: input.dependsOn?.map(
17321
18565
  (id) => decodeExternalId9(id, "wt", "dependsOn")
17322
18566
  ),
@@ -17341,15 +18585,43 @@ async function listWorktrees(deps, query) {
17341
18585
  limit: typeof query.limit === "number" && Number.isFinite(query.limit) ? query.limit : void 0
17342
18586
  });
17343
18587
  const statusFilter = readString19(query.status)?.toLowerCase();
18588
+ const laneFilter = readString19(query.lane);
18589
+ const campaignFilter = typeof query.campaign === "number" && Number.isFinite(query.campaign) ? query.campaign : void 0;
17344
18590
  const normalized = dedupeWorktrees(
17345
18591
  (Array.isArray(worktrees2) ? worktrees2 : []).map((worktree) => normalizeWorktreeRecord(worktree)).filter(
17346
18592
  (worktree) => statusFilter ? String(worktree.status ?? "").toLowerCase() === statusFilter : true
18593
+ ).filter(
18594
+ (worktree) => laneFilter ? worktree.lane === laneFilter : true
18595
+ ).filter(
18596
+ (worktree) => campaignFilter !== void 0 ? worktree.campaign === campaignFilter : true
17347
18597
  )
17348
18598
  );
17349
- return {
17350
- worktrees: normalized,
17351
- total: normalized.length
17352
- };
18599
+ return decorateWorktreeListResult(normalized, normalizeGroupBy(query.groupBy));
18600
+ }
18601
+ async function listCampaigns(deps, query = {}) {
18602
+ const listAll = deps.listAllWorktrees;
18603
+ if (!listAll) {
18604
+ const worktrees2 = query.topicId ? await deps.listWorktreesByTopic({
18605
+ topicId: decodeExternalId9(query.topicId, "top", "topicId"),
18606
+ limit: query.limit
18607
+ }) : [];
18608
+ return buildWorktreeCampaignList(
18609
+ (Array.isArray(worktrees2) ? worktrees2 : []).map(
18610
+ (worktree) => normalizeWorktreeRecord(worktree)
18611
+ )
18612
+ );
18613
+ }
18614
+ const rows = await listAll({
18615
+ status: readString19(query.status),
18616
+ limit: typeof query.limit === "number" && Number.isFinite(query.limit) ? query.limit : void 0
18617
+ });
18618
+ const topicFilter = query.topicId ? decodeExternalId9(query.topicId, "top", "topicId") : void 0;
18619
+ const normalized = dedupeWorktrees(
18620
+ (Array.isArray(rows) ? rows : []).map((worktree) => normalizeWorktreeRecord(worktree)).filter(
18621
+ (worktree) => topicFilter ? worktree.topicId === encodeTopicId3(topicFilter) : true
18622
+ )
18623
+ );
18624
+ return buildWorktreeCampaignList(normalized);
17353
18625
  }
17354
18626
  async function activateWorktree(deps, input) {
17355
18627
  const rawId = decodeExternalId9(input.id, "wt", "id");
@@ -17367,10 +18639,10 @@ async function updateWorktree(deps, input) {
17367
18639
  objective: readString19(input.objective),
17368
18640
  hypothesis: readString19(input.hypothesis),
17369
18641
  rationale: readString19(input.rationale),
17370
- track: readString19(input.track),
17371
- trackPosition: typeof input.trackPosition === "number" && Number.isFinite(input.trackPosition) ? input.trackPosition : void 0,
17372
- executionBand: typeof input.executionBand === "number" && Number.isFinite(input.executionBand) ? input.executionBand : void 0,
17373
- executionOrder: typeof input.executionOrder === "number" && Number.isFinite(input.executionOrder) ? input.executionOrder : void 0,
18642
+ campaign: typeof input.campaign === "number" && Number.isFinite(input.campaign) ? input.campaign : void 0,
18643
+ lane: readString19(input.lane),
18644
+ laneOrderInCampaign: typeof input.laneOrderInCampaign === "number" && Number.isFinite(input.laneOrderInCampaign) ? input.laneOrderInCampaign : void 0,
18645
+ orderInLane: typeof input.orderInLane === "number" && Number.isFinite(input.orderInLane) ? input.orderInLane : void 0,
17374
18646
  dependsOn: input.dependsOn?.map(
17375
18647
  (id) => decodeExternalId9(id, "wt", "dependsOn")
17376
18648
  ),
@@ -17421,6 +18693,7 @@ async function mergeWorktree(deps, input) {
17421
18693
  for (const outcome of input.outcomes) {
17422
18694
  try {
17423
18695
  await deps.scoreBeliefOutcome({
18696
+ worktreeRawId: rawId,
17424
18697
  beliefRawId: decodeExternalId9(outcome.beliefId, "bel", "beliefId"),
17425
18698
  confidence: outcome.confidence,
17426
18699
  rationale: requireString3(outcome.rationale, "rationale")
@@ -17471,23 +18744,23 @@ function resolveExternalId5(value, prefix) {
17471
18744
  }
17472
18745
  function summarizeWorktreeCollection(rows) {
17473
18746
  const worktrees2 = Array.isArray(rows) ? rows : [];
17474
- const tracks = {};
17475
- const bands = {};
18747
+ const lanes = {};
18748
+ const campaigns = {};
17476
18749
  for (const row of worktrees2) {
17477
18750
  if (!row || typeof row !== "object" || Array.isArray(row)) {
17478
18751
  continue;
17479
18752
  }
17480
18753
  const record = row;
17481
- const track = typeof record.track === "string" && record.track.trim().length > 0 ? record.track.trim() : "untracked";
17482
- tracks[track] = (tracks[track] ?? 0) + 1;
17483
- const bandValue = typeof record.executionBand === "number" ? String(record.executionBand) : "unbanded";
17484
- bands[bandValue] = (bands[bandValue] ?? 0) + 1;
18754
+ const lane = typeof record.lane === "string" && record.lane.trim().length > 0 ? record.lane.trim() : "unlaned";
18755
+ lanes[lane] = (lanes[lane] ?? 0) + 1;
18756
+ const campaignValue = typeof record.campaign === "number" ? String(record.campaign) : "uncampaigned";
18757
+ campaigns[campaignValue] = (campaigns[campaignValue] ?? 0) + 1;
17485
18758
  }
17486
18759
  return {
17487
18760
  worktrees: worktrees2,
17488
18761
  total: worktrees2.length,
17489
- tracks,
17490
- bands
18762
+ lanes,
18763
+ campaigns
17491
18764
  };
17492
18765
  }
17493
18766
  function buildCreateMutationArgs(input, userId) {
@@ -17502,7 +18775,10 @@ function buildCreateMutationArgs(input, userId) {
17502
18775
  ...objective ? { objective } : {},
17503
18776
  ...hypothesis ? { hypothesis } : {},
17504
18777
  ...objective || hypothesis ? { beliefFocus: hypothesis ?? objective } : {},
17505
- ...typeof input.executionOrder === "number" ? { executionOrder: input.executionOrder } : {},
18778
+ ...typeof input.campaign === "number" ? { campaign: input.campaign } : {},
18779
+ ...input.lane ? { lane: input.lane } : {},
18780
+ ...typeof input.laneOrderInCampaign === "number" ? { laneOrderInCampaign: input.laneOrderInCampaign } : {},
18781
+ ...typeof input.orderInLane === "number" ? { orderInLane: input.orderInLane } : {},
17506
18782
  ...Array.isArray(input.dependsOn) && input.dependsOn.length > 0 ? { dependsOn: input.dependsOn.map((id) => id) } : {},
17507
18783
  ...Array.isArray(input.blocks) && input.blocks.length > 0 ? { blocks: input.blocks.map((id) => id) } : {},
17508
18784
  ...gate ? { gate } : {},
@@ -17564,6 +18840,14 @@ function createGatewayWorktreesPort(authContext) {
17564
18840
  limit: args.limit
17565
18841
  });
17566
18842
  },
18843
+ listAllWorktrees(args = {}) {
18844
+ return authContext.convex.query(api.worktrees.listAll, {
18845
+ ...args.status ? { status: args.status } : {},
18846
+ ...args.lane ? { lane: args.lane } : {},
18847
+ ...typeof args.campaign === "number" ? { campaign: args.campaign } : {},
18848
+ ...typeof args.limit === "number" ? { limit: args.limit } : {}
18849
+ });
18850
+ },
17567
18851
  async createWorktree(input) {
17568
18852
  const shouldAutoShape = input.autoShape === true || Boolean(input.domainPackId?.trim());
17569
18853
  const created = shouldAutoShape ? await authContext.convex.mutation(api.worktrees.createShaped, {
@@ -17628,6 +18912,7 @@ function createGatewayWorktreesPort(authContext) {
17628
18912
  trigger: "worktree_outcome",
17629
18913
  rationale: args.rationale,
17630
18914
  userId: authContext.userId,
18915
+ triggeringWorktreeId: args.worktreeRawId,
17631
18916
  ...opinion
17632
18917
  });
17633
18918
  },
@@ -17637,10 +18922,10 @@ function createGatewayWorktreesPort(authContext) {
17637
18922
  ...input.objective ? { objective: input.objective } : {},
17638
18923
  ...input.hypothesis ? { hypothesis: input.hypothesis } : {},
17639
18924
  ...input.rationale ? { rationale: input.rationale } : {},
17640
- ...input.track ? { track: input.track } : {},
17641
- ...typeof input.trackPosition === "number" ? { trackPosition: input.trackPosition } : {},
17642
- ...typeof input.executionBand === "number" ? { executionBand: input.executionBand } : {},
17643
- ...typeof input.executionOrder === "number" ? { executionOrder: input.executionOrder } : {},
18925
+ ...typeof input.campaign === "number" ? { campaign: input.campaign } : {},
18926
+ ...input.lane ? { lane: input.lane } : {},
18927
+ ...typeof input.laneOrderInCampaign === "number" ? { laneOrderInCampaign: input.laneOrderInCampaign } : {},
18928
+ ...typeof input.orderInLane === "number" ? { orderInLane: input.orderInLane } : {},
17644
18929
  ...input.dependsOn ? { dependsOn: input.dependsOn.map((id) => id) } : {},
17645
18930
  ...input.blocks ? { blocks: input.blocks.map((id) => id) } : {},
17646
18931
  ...input.gate ? { gate: input.gate } : {},
@@ -17681,7 +18966,10 @@ async function createWorktreeFromGatewayAuth(authContext, input) {
17681
18966
  objective: payload.objective,
17682
18967
  hypothesis: payload.hypothesis,
17683
18968
  gate: payload.gate,
17684
- executionOrder: payload.executionOrder,
18969
+ campaign: payload.campaign,
18970
+ lane: payload.lane,
18971
+ laneOrderInCampaign: payload.laneOrderInCampaign,
18972
+ orderInLane: payload.orderInLane,
17685
18973
  dependsOn: payload.dependsOn ?? [],
17686
18974
  blocks: payload.blocks ?? [],
17687
18975
  targetBeliefIds: payload.targetBeliefIds ?? [],
@@ -17699,12 +18987,15 @@ function listWorktreesFromGatewayAuth(authContext, query) {
17699
18987
  async function listAllWorktreesFromGatewayAuth(authContext, query = {}) {
17700
18988
  const rows = await authContext.convex.query(api.worktrees.listAll, {
17701
18989
  ...query.status ? { status: query.status } : {},
17702
- ...query.track ? { track: query.track } : {},
17703
- ...typeof query.executionBand === "number" ? { executionBand: query.executionBand } : {},
18990
+ ...query.lane ? { lane: query.lane } : {},
18991
+ ...typeof query.campaign === "number" ? { campaign: query.campaign } : {},
17704
18992
  ...typeof query.limit === "number" ? { limit: query.limit } : {}
17705
18993
  });
17706
18994
  return summarizeWorktreeCollection(rows);
17707
18995
  }
18996
+ async function listCampaignsFromGatewayAuth(authContext, query = {}) {
18997
+ return listCampaigns(createGatewayWorktreesPort(authContext), query);
18998
+ }
17708
18999
  async function activateWorktreeFromGatewayAuth(authContext, input) {
17709
19000
  const payload = await activateWorktree(createGatewayWorktreesPort(authContext), input);
17710
19001
  await emitWorktreeEventFromGatewayAuth(authContext, {
@@ -17727,10 +19018,10 @@ async function updateWorktreeFromGatewayAuth(authContext, input) {
17727
19018
  resourceId: payload.worktreeId,
17728
19019
  data: {
17729
19020
  hypothesis: payload.hypothesis,
17730
- track: payload.track,
17731
- trackPosition: payload.trackPosition,
17732
- executionBand: payload.executionBand,
17733
- executionOrder: payload.executionOrder,
19021
+ campaign: payload.campaign,
19022
+ lane: payload.lane,
19023
+ laneOrderInCampaign: payload.laneOrderInCampaign,
19024
+ orderInLane: payload.orderInLane,
17734
19025
  dependsOn: payload.dependsOn ?? [],
17735
19026
  blocks: payload.blocks ?? [],
17736
19027
  gate: payload.gate
@@ -17970,10 +19261,17 @@ async function handleBeliefUpdateConfidence(args) {
17970
19261
  args.authContext,
17971
19262
  {
17972
19263
  id: args.beliefId,
17973
- confidence: readNumber14(body.confidence) ?? Number.NaN,
19264
+ belief: readNumber14(body.belief) ?? Number.NaN,
19265
+ disbelief: readNumber14(body.disbelief) ?? Number.NaN,
19266
+ uncertainty: readNumber14(body.uncertainty) ?? Number.NaN,
19267
+ baseRate: readNumber14(body.baseRate) ?? Number.NaN,
17974
19268
  trigger: readString21(body.trigger),
17975
19269
  rationale: readString21(body.rationale) ?? "",
17976
- certainty: readNumber14(body.certainty),
19270
+ triggeringEvidenceId: readString21(body.triggeringEvidenceId),
19271
+ triggeringQuestionId: readString21(body.triggeringQuestionId),
19272
+ triggeringAnswerId: readString21(body.triggeringAnswerId),
19273
+ triggeringContradictionId: readString21(body.triggeringContradictionId),
19274
+ triggeringWorktreeId: readString21(body.triggeringWorktreeId) ?? readString21(body.worktreeId),
17977
19275
  maxInlinePropagationTargets: readNumber14(body.maxInlinePropagationTargets)
17978
19276
  }
17979
19277
  );
@@ -18769,6 +20067,7 @@ async function handleEvidenceCreate(args) {
18769
20067
  targetId: readString24(body.targetId),
18770
20068
  targetType: readString24(body.targetType),
18771
20069
  weight: readNumber16(body.weight),
20070
+ rationale: readString24(body.rationale) ?? "",
18772
20071
  metadata: asRecord19(body.metadata),
18773
20072
  title: readString24(body.title),
18774
20073
  content: readString24(body.content),
@@ -20663,7 +21962,10 @@ async function handleWorktreeCreate(args) {
20663
21962
  beliefIds: readStringArray17(body.beliefIds) ?? readStringArray17(body.beliefs),
20664
21963
  autoShape: typeof body.autoShape === "boolean" ? body.autoShape : void 0,
20665
21964
  domainPackId: readString33(body.domainPackId),
20666
- executionOrder: readNumber22(body.executionOrder),
21965
+ campaign: readNumber22(body.campaign),
21966
+ lane: readString33(body.lane),
21967
+ laneOrderInCampaign: readNumber22(body.laneOrderInCampaign),
21968
+ orderInLane: readNumber22(body.orderInLane),
20667
21969
  dependsOn: readStringArray17(body.dependsOn),
20668
21970
  blocks: readStringArray17(body.blocks),
20669
21971
  gate: readString33(body.gate),
@@ -20692,6 +21994,9 @@ async function handleWorktreeList(args) {
20692
21994
  const payload = await listWorktreesFromGatewayAuth(args.authContext, {
20693
21995
  topicId: readString33(args.query.topicId) ?? "",
20694
21996
  status: readString33(args.query.status),
21997
+ groupBy: readString33(args.query.groupBy),
21998
+ lane: readString33(args.query.lane),
21999
+ campaign: readNumber22(args.query.campaign),
20695
22000
  limit: readNumber22(args.query.limit)
20696
22001
  });
20697
22002
  return successResponse(payload, {
@@ -20711,8 +22016,9 @@ async function handleWorktreeListAll(args) {
20711
22016
  try {
20712
22017
  const payload = await listAllWorktreesFromGatewayAuth(args.authContext, {
20713
22018
  status: readString33(args.query.status),
20714
- track: readString33(args.query.track),
20715
- executionBand: readNumber22(args.query.executionBand),
22019
+ lane: readString33(args.query.lane),
22020
+ campaign: readNumber22(args.query.campaign),
22021
+ groupBy: readString33(args.query.groupBy),
20716
22022
  limit: readNumber22(args.query.limit)
20717
22023
  });
20718
22024
  return successResponse(payload, {
@@ -20728,6 +22034,26 @@ async function handleWorktreeListAll(args) {
20728
22034
  );
20729
22035
  }
20730
22036
  }
22037
+ async function handleWorktreeListCampaigns(args) {
22038
+ try {
22039
+ const payload = await listCampaignsFromGatewayAuth(args.authContext, {
22040
+ topicId: readString33(args.query.topicId),
22041
+ status: readString33(args.query.status),
22042
+ limit: readNumber22(args.query.limit)
22043
+ });
22044
+ return successResponse(payload, {
22045
+ correlationId: args.correlationId,
22046
+ policyTraceId: args.policyTraceId
22047
+ });
22048
+ } catch (error) {
22049
+ return handleWorktreesError(
22050
+ error,
22051
+ "Failed to list pipeline campaigns.",
22052
+ args.correlationId,
22053
+ args.policyTraceId
22054
+ );
22055
+ }
22056
+ }
20731
22057
  async function handleWorktreeActivate(args) {
20732
22058
  try {
20733
22059
  const payload = await activateWorktreeFromGatewayAuth(args.authContext, {
@@ -20754,10 +22080,10 @@ async function handleWorktreeUpdate(args) {
20754
22080
  objective: readString33(body.objective),
20755
22081
  hypothesis: readString33(body.hypothesis),
20756
22082
  rationale: readString33(body.rationale),
20757
- track: readString33(body.track),
20758
- trackPosition: readNumber22(body.trackPosition),
20759
- executionBand: readNumber22(body.executionBand),
20760
- executionOrder: readNumber22(body.executionOrder),
22083
+ campaign: readNumber22(body.campaign),
22084
+ lane: readString33(body.lane),
22085
+ laneOrderInCampaign: readNumber22(body.laneOrderInCampaign),
22086
+ orderInLane: readNumber22(body.orderInLane),
20761
22087
  dependsOn: readStringArray17(body.dependsOn),
20762
22088
  blocks: readStringArray17(body.blocks),
20763
22089
  gate: readString33(body.gate),
@@ -20944,6 +22270,6 @@ async function handleWorktreeBulkCreate(args) {
20944
22270
  }
20945
22271
  }
20946
22272
 
20947
- export { handleBeliefArchive, handleBeliefBatchUpdateCriticality, handleBeliefBisect, handleBeliefConfidenceHistory, handleBeliefCreate, handleBeliefCreateContract, handleBeliefFork, handleBeliefGet, handleBeliefLineage, handleBeliefLink, handleBeliefList, handleBeliefReassignTopic, handleBeliefRefine, handleBeliefRelationships, handleBeliefUnlinkEvidence, handleBeliefUpdateConfidence, handleBeliefUpdateCriticality, handleBeliefUpdateRationale, handleBeliefUpdateStatus, handleContradictionFlag, handleContradictionGet, handleContradictionList, handleEdgeBatchCreate, handleEdgeCreate, handleEdgeDelete, handleEdgeList, handleEdgeRemove, handleEdgeTraverse, handleEdgeUpdate, handleEdgesRemoveBetween, handleEventsList, handleEventsReplay, handleEvidenceClassify, handleEvidenceClassifyBatch, handleEvidenceCreate, handleEvidenceFlagIncorrect, handleEvidenceGet, handleEvidenceLink, handleEvidenceList, handleEvidenceRemove, handleEvidenceSearch, handleEvidenceUpdate, handleEvidenceUpdateStatus, handleEvidenceUpdateVerificationStatus, handleGraphAnalyze, handleGraphBias, handleGraphFalsify, handleGraphGaps, handleGraphNeighborhood, handleGraphTraverse, handleIdentityWhoami, handleOntologyBind, handleOntologyGet, handleOntologyList, handleOntologyMatch, handleQuestionAdd, handleQuestionAdvanceToConviction, handleQuestionAnswer, handleQuestionArchive, handleQuestionBatchCreate, handleQuestionCreate, handleQuestionDelete, handleQuestionFinalizeConviction, handleQuestionGet, handleQuestionGetAnswer, handleQuestionList, handleQuestionRefine, handleQuestionUpdate, handleQuestionUpdateConviction, handleQuestionUpdatePriority, handleQuestionUpdateStatus, handleSearchResources, handleSourceGet, handleSourceUpsert, handleTaskComplete, handleTaskCreate, handleTaskList, handleTaskUpdate, handleTopicBulkCreate, handleTopicCoverage, handleTopicCreate, handleTopicGet, handleTopicList, handleTopicRemove, handleTopicTree, handleTopicUpdate, handleWebhookCreate, handleWebhookDelete, handleWebhookDeliveries, handleWebhookGet, handleWebhookHealth, handleWebhookList, handleWebhookTest, handleWebhookUpdate, handleWorktreeActivate, handleWorktreeAdvancePhase, handleWorktreeBulkCreate, handleWorktreeComplete, handleWorktreeCreate, handleWorktreeList, handleWorktreeListAll, handleWorktreeMerge, handleWorktreePatchState, handleWorktreeSetPhase, handleWorktreeUpdate, handleWorktreeUpdateTargets };
22273
+ export { handleBeliefArchive, handleBeliefBatchUpdateCriticality, handleBeliefBisect, handleBeliefConfidenceHistory, handleBeliefCreate, handleBeliefCreateContract, handleBeliefFork, handleBeliefGet, handleBeliefLineage, handleBeliefLink, handleBeliefList, handleBeliefReassignTopic, handleBeliefRefine, handleBeliefRelationships, handleBeliefUnlinkEvidence, handleBeliefUpdateConfidence, handleBeliefUpdateCriticality, handleBeliefUpdateRationale, handleBeliefUpdateStatus, handleContradictionFlag, handleContradictionGet, handleContradictionList, handleEdgeBatchCreate, handleEdgeCreate, handleEdgeDelete, handleEdgeList, handleEdgeRemove, handleEdgeTraverse, handleEdgeUpdate, handleEdgesRemoveBetween, handleEventsList, handleEventsReplay, handleEvidenceClassify, handleEvidenceClassifyBatch, handleEvidenceCreate, handleEvidenceFlagIncorrect, handleEvidenceGet, handleEvidenceLink, handleEvidenceList, handleEvidenceRemove, handleEvidenceSearch, handleEvidenceUpdate, handleEvidenceUpdateStatus, handleEvidenceUpdateVerificationStatus, handleGraphAnalyze, handleGraphBias, handleGraphFalsify, handleGraphGaps, handleGraphNeighborhood, handleGraphTraverse, handleIdentityWhoami, handleOntologyBind, handleOntologyGet, handleOntologyList, handleOntologyMatch, handleQuestionAdd, handleQuestionAdvanceToConviction, handleQuestionAnswer, handleQuestionArchive, handleQuestionBatchCreate, handleQuestionCreate, handleQuestionDelete, handleQuestionFinalizeConviction, handleQuestionGet, handleQuestionGetAnswer, handleQuestionList, handleQuestionRefine, handleQuestionUpdate, handleQuestionUpdateConviction, handleQuestionUpdatePriority, handleQuestionUpdateStatus, handleSearchResources, handleSourceGet, handleSourceUpsert, handleTaskComplete, handleTaskCreate, handleTaskList, handleTaskUpdate, handleTopicBulkCreate, handleTopicCoverage, handleTopicCreate, handleTopicGet, handleTopicList, handleTopicRemove, handleTopicTree, handleTopicUpdate, handleWebhookCreate, handleWebhookDelete, handleWebhookDeliveries, handleWebhookGet, handleWebhookHealth, handleWebhookList, handleWebhookTest, handleWebhookUpdate, handleWorktreeActivate, handleWorktreeAdvancePhase, handleWorktreeBulkCreate, handleWorktreeComplete, handleWorktreeCreate, handleWorktreeList, handleWorktreeListAll, handleWorktreeListCampaigns, handleWorktreeMerge, handleWorktreePatchState, handleWorktreeSetPhase, handleWorktreeUpdate, handleWorktreeUpdateTargets };
20948
22274
  //# sourceMappingURL=gateway.js.map
20949
22275
  //# sourceMappingURL=gateway.js.map