@abelxiaoxing/cadence 2.0.20 → 2.0.21

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.
@@ -3911,7 +3911,348 @@ function decodeModelCatalog(value) {
3911
3911
  withheld
3912
3912
  };
3913
3913
  }
3914
+ // src/service/contracts/workflow.ts
3915
+ var WORKFLOW_LIMITS = {
3916
+ tasks: 16,
3917
+ parallel: 2,
3918
+ checks: 16,
3919
+ repairs: 2,
3920
+ bytes: 256 * 1024,
3921
+ runs: 200,
3922
+ durationMs: 90 * 60 * 1000
3923
+ };
3924
+ function workflowPath(v) {
3925
+ const p = text(v, 1024, true);
3926
+ if (p.startsWith("/") || p.includes("\\") || [...p].some((c) => c.charCodeAt(0) < 32 || c.charCodeAt(0) === 127 || c === ":") || p.split("/").some((s) => !s || s === "." || s === ".." || s.toLowerCase() === ".git") || /(^|\/)\.env(?:\.|$)/iu.test(p))
3927
+ throw new Error("Invalid workflow file path");
3928
+ return p;
3929
+ }
3930
+ var taskId = (v) => {
3931
+ const s = text(v, 64, true);
3932
+ if (!/^[a-z][a-z0-9-]*$/u.test(s))
3933
+ throw new Error("Invalid task id");
3934
+ return s;
3935
+ };
3936
+ function decodeWorkflowCheck(v) {
3937
+ const o = closed(v, ["name", "command", "timeoutMs"]);
3938
+ return {
3939
+ name: text(o.name, 128, true),
3940
+ command: text(o.command, 4096, true),
3941
+ timeoutMs: integer(o.timeoutMs, 100, 1200000)
3942
+ };
3943
+ }
3944
+ function workflowOrder(tasks) {
3945
+ const done = new Set, ordered = [];
3946
+ if (new Set(tasks.map((t) => t.id)).size !== tasks.length)
3947
+ throw new Error("Duplicate task id");
3948
+ while (ordered.length < tasks.length) {
3949
+ const next = tasks.find((t) => !done.has(t.id) && t.after.every((id) => done.has(id)));
3950
+ if (!next)
3951
+ throw new Error("Missing dependency or cyclic plan");
3952
+ ordered.push(next);
3953
+ done.add(next.id);
3954
+ }
3955
+ return ordered;
3956
+ }
3957
+ function workflowAncestors(tasks, id) {
3958
+ const needed = new Set;
3959
+ const visit = (key) => {
3960
+ for (const dep of tasks.find((t) => t.id === key)?.after ?? []) {
3961
+ if (!needed.has(dep)) {
3962
+ needed.add(dep);
3963
+ visit(dep);
3964
+ }
3965
+ }
3966
+ };
3967
+ workflowOrder(tasks);
3968
+ visit(id);
3969
+ return workflowOrder(tasks).filter((t) => needed.has(t.id));
3970
+ }
3971
+ function decodeWorkflowPlan(v) {
3972
+ canonicalJson(v, WORKFLOW_LIMITS.bytes);
3973
+ const o = closed(v, [
3974
+ "goal",
3975
+ "design",
3976
+ "decisions",
3977
+ "acceptance",
3978
+ "projectContext",
3979
+ "tasks",
3980
+ "checks",
3981
+ "setup",
3982
+ "baselineChecks",
3983
+ "repairAttempts",
3984
+ "delivery"
3985
+ ]);
3986
+ const tasks = list(o.tasks, WORKFLOW_LIMITS.tasks, (value) => {
3987
+ const t = closed(value, ["id", "title", "instructions", "writes", "after"]);
3988
+ return {
3989
+ id: taskId(t.id),
3990
+ title: text(t.title, 256, true),
3991
+ instructions: text(t.instructions, 8192, true),
3992
+ writes: list(t.writes, 128, workflowPath),
3993
+ after: list(t.after, WORKFLOW_LIMITS.tasks, taskId)
3994
+ };
3995
+ });
3996
+ if (!tasks.length || tasks.some((t) => !t.writes.length || new Set(t.writes).size !== t.writes.length || new Set(t.after).size !== t.after.length))
3997
+ throw new Error("Empty or duplicate task scope");
3998
+ workflowOrder(tasks);
3999
+ for (const a of tasks)
4000
+ for (const b of tasks) {
4001
+ if (a.id >= b.id || workflowAncestors(tasks, a.id).some((t) => t.id === b.id) || workflowAncestors(tasks, b.id).some((t) => t.id === a.id))
4002
+ continue;
4003
+ if (a.writes.some((p) => b.writes.some((q) => p === q || p.startsWith(`${q}/`) || q.startsWith(`${p}/`))))
4004
+ throw new Error("Independent tasks share write paths; assign an owner and dependency");
4005
+ }
4006
+ const checks = list(o.checks, WORKFLOW_LIMITS.checks, decodeWorkflowCheck);
4007
+ if (!checks.length)
4008
+ throw new Error("At least one real verification command is required");
4009
+ const result = {
4010
+ goal: text(o.goal, 8192, true),
4011
+ design: text(o.design, 32768, true),
4012
+ decisions: text(o.decisions, 16384),
4013
+ acceptance: text(o.acceptance, 16384, true),
4014
+ projectContext: text(o.projectContext, 16384),
4015
+ tasks,
4016
+ checks,
4017
+ setup: list(o.setup, 4, decodeWorkflowCheck),
4018
+ baselineChecks: list(o.baselineChecks, WORKFLOW_LIMITS.checks, decodeWorkflowCheck),
4019
+ repairAttempts: integer(o.repairAttempts, 0, WORKFLOW_LIMITS.repairs),
4020
+ delivery: oneOf(o.delivery, ["local-merge", "working-copy"])
4021
+ };
4022
+ workflowContext(result);
4023
+ text(result.tasks.flatMap((t) => t.writes).join(", "), 16384);
4024
+ for (const value of [
4025
+ result.goal,
4026
+ result.design,
4027
+ result.decisions,
4028
+ result.acceptance,
4029
+ result.projectContext,
4030
+ ...result.tasks.flatMap((t) => [t.title, t.instructions]),
4031
+ ...[...result.checks, ...result.setup, ...result.baselineChecks].flatMap((c) => [c.name, c.command])
4032
+ ])
4033
+ if ([...value].some((c) => c.charCodeAt(0) < 32 && c !== `
4034
+ ` && c !== "\t" || c.charCodeAt(0) === 127 || /[\u202a-\u202e\u2066-\u2069]/u.test(c)))
4035
+ throw new Error("Plan contains invisible terminal controls");
4036
+ return result;
4037
+ }
4038
+ function workflowContext(p) {
4039
+ return text(`# ${p.goal}
4040
+
4041
+ ${p.design}
4042
+
4043
+ Decisions: ${p.decisions}
4044
+
4045
+ Acceptance: ${p.acceptance}`, 32768, true);
4046
+ }
4047
+ function decodeWorkflowProposal(v) {
4048
+ const modern = v !== null && typeof v === "object" && Object.hasOwn(v, "display");
4049
+ const o = closed(v, [
4050
+ "id",
4051
+ "epoch",
4052
+ "digest",
4053
+ "observation",
4054
+ "model",
4055
+ "plan",
4056
+ "cwd",
4057
+ ...modern ? ["display"] : []
4058
+ ]);
4059
+ return {
4060
+ id: decodeId(o.id),
4061
+ epoch: decodeId(o.epoch),
4062
+ digest: decodeHash(o.digest),
4063
+ observation: decodeHash(o.observation),
4064
+ model: decodeChoiceVersion(o.model),
4065
+ plan: decodeWorkflowPlan(o.plan),
4066
+ cwd: text(o.cwd, 4096, true),
4067
+ ...modern ? {
4068
+ display: (() => {
4069
+ const d = closed(o.display, ["model", "branch", "baseCommit"]);
4070
+ return {
4071
+ model: text(d.model, 1024, true),
4072
+ branch: text(d.branch, 1024),
4073
+ baseCommit: text(d.baseCommit, 64)
4074
+ };
4075
+ })()
4076
+ } : {}
4077
+ };
4078
+ }
4079
+ function decodeWorkflowRequest(v) {
4080
+ const action = Object.getOwnPropertyDescriptor(v ?? {}, "action")?.value;
4081
+ if (action === "research") {
4082
+ const o2 = closed(v, ["action", "goal", "questions", "model"]);
4083
+ const questions = list(o2.questions, WORKFLOW_LIMITS.parallel, (q) => text(q, 8192, true));
4084
+ if (!questions.length)
4085
+ throw new Error("Research needs a question");
4086
+ return {
4087
+ action,
4088
+ goal: text(o2.goal, 8192, true),
4089
+ questions,
4090
+ model: decodeChoiceVersion(o2.model)
4091
+ };
4092
+ }
4093
+ if (action === "propose") {
4094
+ const o2 = closed(v, ["action", "plan", "model"]);
4095
+ return {
4096
+ action,
4097
+ plan: decodeWorkflowPlan(o2.plan),
4098
+ model: decodeChoiceVersion(o2.model)
4099
+ };
4100
+ }
4101
+ if (action === "prepare" || action === "execute") {
4102
+ const o2 = closed(v, action === "execute" ? ["action", "proposalId", "digest", "grant"] : ["action", "proposalId", "digest"]);
4103
+ const base = {
4104
+ proposalId: decodeId(o2.proposalId),
4105
+ digest: decodeHash(o2.digest)
4106
+ };
4107
+ return action === "prepare" ? { action, ...base } : { action, ...base, grant: decodeId(o2.grant) };
4108
+ }
4109
+ const o = closed(v, ["action", "runId"]);
4110
+ return { action: oneOf(o.action, ["cancel"]), runId: decodeId(o.runId) };
4111
+ }
4112
+ function decodeWorkflowRun(v) {
4113
+ const o = closed(v, [
4114
+ "id",
4115
+ "epoch",
4116
+ "goal",
4117
+ "status",
4118
+ "phase",
4119
+ "steps",
4120
+ "notice",
4121
+ "mergedCommit",
4122
+ "humanReviewed"
4123
+ ]);
4124
+ const status = (x) => oneOf(x, [
4125
+ "running",
4126
+ "completed",
4127
+ "failed",
4128
+ "canceled",
4129
+ "timeout",
4130
+ "unknown"
4131
+ ]);
4132
+ if (o.humanReviewed !== false)
4133
+ throw new Error("Automatic execution is not human review");
4134
+ return {
4135
+ id: decodeId(o.id),
4136
+ epoch: decodeId(o.epoch),
4137
+ goal: text(o.goal, 8192),
4138
+ status: o.status === "queued" ? "queued" : status(o.status),
4139
+ phase: oneOf(o.phase, [
4140
+ "research",
4141
+ "implementing",
4142
+ "verifying",
4143
+ "reviewing",
4144
+ "integrating",
4145
+ "finished"
4146
+ ]),
4147
+ notice: text(o.notice, 2048),
4148
+ mergedCommit: nullable(o.mergedCommit, (s) => text(s, 64, true)),
4149
+ humanReviewed: false,
4150
+ steps: list(o.steps, 256, (v2) => {
4151
+ const linked = v2 !== null && typeof v2 === "object" && Object.hasOwn(v2, "childRunId");
4152
+ const s = closed(v2, [
4153
+ "id",
4154
+ "kind",
4155
+ "status",
4156
+ "text",
4157
+ "exitCode",
4158
+ "truncated",
4159
+ ...linked ? ["childRunId"] : []
4160
+ ]);
4161
+ return {
4162
+ id: text(s.id, 160, true),
4163
+ ...linked ? { childRunId: decodeId(s.childRunId) } : {},
4164
+ kind: oneOf(s.kind, [
4165
+ "research",
4166
+ "implementation",
4167
+ "review",
4168
+ "check",
4169
+ "git"
4170
+ ]),
4171
+ status: status(s.status),
4172
+ text: text(s.text, 65536),
4173
+ exitCode: nullable(s.exitCode, (n) => integer(n, -2147483648, 2147483647)),
4174
+ truncated: bool(s.truncated)
4175
+ };
4176
+ })
4177
+ };
4178
+ }
4179
+ function decodeWorkflowResponse(v) {
4180
+ const type = Object.getOwnPropertyDescriptor(v ?? {}, "type")?.value;
4181
+ if (type === "run") {
4182
+ const o2 = closed(v, ["type", "run"]);
4183
+ return { type, run: decodeWorkflowRun(o2.run) };
4184
+ }
4185
+ if (type === "proposal") {
4186
+ const o2 = closed(v, ["type", "proposal"]);
4187
+ return { type, proposal: decodeWorkflowProposal(o2.proposal) };
4188
+ }
4189
+ const o = closed(v, ["type", "proposal", "grant", "expiresAt"]);
4190
+ return {
4191
+ type: oneOf(o.type, ["grant"]),
4192
+ proposal: decodeWorkflowProposal(o.proposal),
4193
+ grant: decodeId(o.grant),
4194
+ expiresAt: integer(o.expiresAt, 0)
4195
+ };
4196
+ }
4197
+ function readableWorkflowPlan(p) {
4198
+ return `# ${p.goal}
4199
+
4200
+ ## Design
4201
+ ${p.design}
4202
+
4203
+ ## Decisions
4204
+ ${p.decisions}
4205
+
4206
+ ## Acceptance
4207
+ ${p.acceptance}
4208
+
4209
+ ## Tasks
4210
+ ${workflowOrder(p.tasks).map((t) => `### ${t.id}: ${t.title}
4211
+ Depends on: ${t.after.join(", ") || "none"}
4212
+ Writes: ${t.writes.join(", ")}
4213
+ ${t.instructions}`).join(`
4214
+
4215
+ `)}
4216
+
4217
+ ## Setup (explicitly authorized commands)
4218
+ ${p.setup.map((c) => `${c.name}: ${c.command} (${c.timeoutMs}ms)`).join(`
4219
+ `) || "None; no dependency installation or copying."}
4220
+
4221
+ ## Baseline verification
4222
+ ${p.baselineChecks.map((c) => `${c.name}: ${c.command} (${c.timeoutMs}ms)`).join(`
4223
+ `) || "No separate baseline checks declared."}
4224
+
4225
+ ## Verification
4226
+ ${p.checks.map((c) => `${c.name}: ${c.command} (${c.timeoutMs}ms)`).join(`
4227
+ `)}
4228
+
4229
+ ## Automation boundary
4230
+ At most ${p.repairAttempts} repair rounds. ${p.delivery === "local-merge" ? "Authorize isolated task worktrees, local task commits and fast-forward integration into the current branch." : "Direct working-copy edits; failures leave actual edits for inspection. No Git commit or merge."} No push, publication, deployment, unplanned installation or recursive delegation. Generated project context and workflow Markdown are included. Worktrees/tools are not a sandbox.
4231
+
4232
+ ## Project context
4233
+ ${p.projectContext}
4234
+ `;
4235
+ }
4236
+
3914
4237
  // src/service/contracts/workbench.ts
4238
+ function decodeCadenceConversation(v) {
4239
+ const o = closed(v, [
4240
+ "id",
4241
+ "revision",
4242
+ "enabled",
4243
+ "head",
4244
+ "proposal",
4245
+ "runs"
4246
+ ]);
4247
+ return {
4248
+ id: decodeId(o.id),
4249
+ revision: integer(o.revision, 0),
4250
+ enabled: bool(o.enabled),
4251
+ head: nullable(o.head, decodeId),
4252
+ proposal: nullable(o.proposal, decodeWorkflowProposal),
4253
+ runs: list(o.runs, 200, decodeId)
4254
+ };
4255
+ }
3915
4256
  var statuses = [
3916
4257
  "queued",
3917
4258
  "running",
@@ -3924,6 +4265,22 @@ var statuses = [
3924
4265
  function decodeWorkbenchRead(v) {
3925
4266
  const kind = Object.getOwnPropertyDescriptor(v ?? {}, "kind")?.value;
3926
4267
  switch (kind) {
4268
+ case "cadence-conversation": {
4269
+ const o = closed(v, ["kind", "id"]);
4270
+ return { kind, id: decodeId(o.id) };
4271
+ }
4272
+ case "workflow-active":
4273
+ closed(v, ["kind"]);
4274
+ return { kind };
4275
+ case "workflow-transcript":
4276
+ case "workflow-detail": {
4277
+ const o = closed(v, ["kind", "id", "stepId"]);
4278
+ return { kind, id: decodeId(o.id), stepId: text(o.stepId, 160, true) };
4279
+ }
4280
+ case "workflow": {
4281
+ const o = closed(v, ["kind", "id"]);
4282
+ return { kind, id: decodeId(o.id) };
4283
+ }
3927
4284
  case "conversations":
3928
4285
  case "projects":
3929
4286
  closed(v, ["kind"]);
@@ -3947,6 +4304,77 @@ function decodeWorkbenchRead(v) {
3947
4304
  }
3948
4305
  function decodeWorkbenchCommand(v) {
3949
4306
  const kind = Object.getOwnPropertyDescriptor(v ?? {}, "kind")?.value;
4307
+ if (kind === "restore-model" || kind === "workflow-cancel") {
4308
+ const o2 = closed(v, kind === "restore-model" ? ["kind", "commandId", "epoch"] : ["kind", "commandId", "epoch", "runId"]);
4309
+ const base = { commandId: decodeId(o2.commandId), epoch: decodeId(o2.epoch) };
4310
+ return kind === "restore-model" ? { kind, ...base } : { kind, ...base, runId: decodeId(o2.runId) };
4311
+ }
4312
+ if (kind === "cadence-exit") {
4313
+ const o2 = closed(v, [
4314
+ "kind",
4315
+ "commandId",
4316
+ "conversationId",
4317
+ "head",
4318
+ "revision"
4319
+ ]);
4320
+ return {
4321
+ kind,
4322
+ commandId: decodeId(o2.commandId),
4323
+ conversationId: decodeId(o2.conversationId),
4324
+ head: nullable(o2.head, decodeId),
4325
+ revision: integer(o2.revision, 0)
4326
+ };
4327
+ }
4328
+ if (kind === "cadence-send") {
4329
+ const o2 = closed(v, [
4330
+ "kind",
4331
+ "commandId",
4332
+ "conversationId",
4333
+ "head",
4334
+ "text",
4335
+ "model",
4336
+ "revision",
4337
+ "intent"
4338
+ ]);
4339
+ return {
4340
+ kind,
4341
+ commandId: decodeId(o2.commandId),
4342
+ conversationId: decodeId(o2.conversationId),
4343
+ head: nullable(o2.head, decodeId),
4344
+ text: text(o2.text, 16384, true),
4345
+ model: decodeChoiceVersion(o2.model),
4346
+ revision: integer(o2.revision, 0),
4347
+ intent: oneOf(o2.intent, ["message", "enter", "exit"])
4348
+ };
4349
+ }
4350
+ if (kind === "cadence-prepare" || kind === "cadence-approve") {
4351
+ const keys2 = [
4352
+ "kind",
4353
+ "commandId",
4354
+ "conversationId",
4355
+ "revision",
4356
+ "proposalId",
4357
+ "digest"
4358
+ ];
4359
+ const o2 = closed(v, kind === "cadence-approve" ? [...keys2, "grant"] : keys2);
4360
+ const base = {
4361
+ commandId: decodeId(o2.commandId),
4362
+ conversationId: decodeId(o2.conversationId),
4363
+ revision: integer(o2.revision, 0),
4364
+ proposalId: decodeId(o2.proposalId),
4365
+ digest: decodeHash(o2.digest)
4366
+ };
4367
+ return kind === "cadence-prepare" ? { kind, ...base } : { kind, ...base, grant: decodeId(o2.grant) };
4368
+ }
4369
+ if (kind === "workflow") {
4370
+ const o2 = closed(v, ["kind", "commandId", "epoch", "request"]);
4371
+ return {
4372
+ kind,
4373
+ commandId: decodeId(o2.commandId),
4374
+ epoch: decodeId(o2.epoch),
4375
+ request: decodeWorkflowRequest(o2.request)
4376
+ };
4377
+ }
3950
4378
  if (kind === "link-task") {
3951
4379
  const o2 = closed(v, [
3952
4380
  "kind",
@@ -4034,18 +4462,71 @@ function decodeChatTurn(v) {
4034
4462
  };
4035
4463
  }
4036
4464
  function decodeChatSummary(v) {
4037
- const o = closed(v, ["id", "title", "head", "status", "updatedAt"]);
4465
+ const modern = v !== null && typeof v === "object" && Object.hasOwn(v, "cadence");
4466
+ const o = closed(v, [
4467
+ "id",
4468
+ "title",
4469
+ "head",
4470
+ "status",
4471
+ "updatedAt",
4472
+ ...modern ? ["cadence"] : []
4473
+ ]);
4038
4474
  return {
4039
4475
  id: decodeId(o.id),
4040
4476
  title: text(o.title, 512, true),
4041
4477
  head: decodeId(o.head),
4042
4478
  status: oneOf(o.status, statuses),
4043
- updatedAt: integer(o.updatedAt, 0)
4479
+ updatedAt: integer(o.updatedAt, 0),
4480
+ ...modern ? { cadence: bool(o.cadence) } : {}
4044
4481
  };
4045
4482
  }
4046
4483
  function decodeWorkbenchResult(v) {
4047
4484
  canonicalJson(v, 512 * 1024);
4485
+ const k = Object.getOwnPropertyDescriptor(v ?? {}, "kind")?.value;
4486
+ if (k === "workflow-transcript") {
4487
+ const o2 = closed(v, ["kind", "runId", "stepId", "turn"]);
4488
+ return {
4489
+ kind: k,
4490
+ runId: decodeId(o2.runId),
4491
+ stepId: text(o2.stepId, 160, true),
4492
+ turn: nullable(o2.turn, decodeChatTurn)
4493
+ };
4494
+ }
4495
+ if (k === "cadence-conversation") {
4496
+ const o2 = closed(v, ["kind", "state"]);
4497
+ return { kind: k, state: decodeCadenceConversation(o2.state) };
4498
+ }
4499
+ if (k === "workflow-active") {
4500
+ const o2 = closed(v, ["kind", "runs"]);
4501
+ return { kind: k, runs: list(o2.runs, 4, decodeWorkflowRun) };
4502
+ }
4503
+ if (k === "cadence-grant") {
4504
+ const o2 = closed(v, [
4505
+ "kind",
4506
+ "commandId",
4507
+ "grant",
4508
+ "expiresAt",
4509
+ "revision",
4510
+ "proposal"
4511
+ ]);
4512
+ return {
4513
+ kind: k,
4514
+ commandId: decodeId(o2.commandId),
4515
+ grant: decodeId(o2.grant),
4516
+ expiresAt: integer(o2.expiresAt, 0),
4517
+ revision: integer(o2.revision, 0),
4518
+ proposal: decodeWorkflowProposal(o2.proposal)
4519
+ };
4520
+ }
4048
4521
  const kind = Object.getOwnPropertyDescriptor(v ?? {}, "kind")?.value;
4522
+ if (kind === "workflow") {
4523
+ const o2 = closed(v, ["kind", "commandId", "response"]);
4524
+ return {
4525
+ kind,
4526
+ commandId: nullable(o2.commandId, decodeId),
4527
+ response: decodeWorkflowResponse(o2.response)
4528
+ };
4529
+ }
4049
4530
  if (kind === "task-origin") {
4050
4531
  const o2 = closed(v, ["kind", "taskId", "conversationId"]);
4051
4532
  return {
@@ -5563,7 +6044,9 @@ class ServiceCoordination {
5563
6044
  "access.json",
5564
6045
  "host-config.json",
5565
6046
  "history-v2",
5566
- "conversations-v1"
6047
+ "conversations-v1",
6048
+ "conversation-workflows-v1",
6049
+ "workflows-v1"
5567
6050
  ]);
5568
6051
  this.files.directory(join6(directory, "history-v2"), false, walks);
5569
6052
  }
@@ -7664,9 +8147,9 @@ class TaskPublicationLineage {
7664
8147
  };
7665
8148
  endpoint = null;
7666
8149
  graphIdentity = null;
7667
- apply(row, seq, taskId, savedGraphIdentity) {
8150
+ apply(row, seq, taskId2, savedGraphIdentity) {
7668
8151
  const v = row.value;
7669
- if (v.kind === "admission" && v.intent.identity.kind === "action" && v.intent.identity.expected.task?.id === taskId) {
8152
+ if (v.kind === "admission" && v.intent.identity.kind === "action" && v.intent.identity.expected.task?.id === taskId2) {
7670
8153
  const i2 = v.intent.identity;
7671
8154
  requireFact(i2.expected.task);
7672
8155
  if (i2.action.kind === "save-plan") {
@@ -7689,7 +8172,7 @@ class TaskPublicationLineage {
7689
8172
  for (const e of v.events) {
7690
8173
  if (e.kind !== "owner" || e.value.kind !== "fact" || e.value.fact.kind !== "publication-intent" && e.value.fact.kind !== "publication-settled")
7691
8174
  continue;
7692
- requireFact(v.link.taskId === taskId && v.link.epoch === i.expected.epoch && v.link.runId === this.operation.runId);
8175
+ requireFact(v.link.taskId === taskId2 && v.link.epoch === i.expected.epoch && v.link.runId === this.operation.runId);
7693
8176
  this.state = publicationTransition(this.state, i.expected.task, e.value.fact, seq);
7694
8177
  if (this.state.status === "published" && this.state.intent)
7695
8178
  this.endpoint = {
@@ -8917,6 +9400,12 @@ import {
8917
9400
  createServer
8918
9401
  } from "node:http";
8919
9402
  import { WebSocketServer } from "ws";
9403
+
9404
+ // src/service/workbench-send-refusal.ts
9405
+ class UnacceptedConversationCommand extends ContractError {
9406
+ }
9407
+
9408
+ // src/service/http.ts
8920
9409
  function refusal(code2 = "invalid", uncertain = false) {
8921
9410
  return {
8922
9411
  kind: "error",
@@ -9332,7 +9821,7 @@ Content-Length: 0\r
9332
9821
  else {
9333
9822
  const code2 = e instanceof ContractError ? e.code : "unavailable";
9334
9823
  res.setHeader("Connection", "close");
9335
- send(res, errorStatus(code2), refusal(code2, dispatched));
9824
+ send(res, errorStatus(code2), refusal(code2, dispatched && !(e instanceof UnacceptedConversationCommand)));
9336
9825
  }
9337
9826
  } finally {
9338
9827
  clearTimeout(timer);
@@ -9397,13 +9886,17 @@ Content-Length: 0\r
9397
9886
  kind: "ok",
9398
9887
  value: a.workbench.read(decodeWorkbenchRead(input))
9399
9888
  };
9400
- case "workbenchCommand":
9889
+ case "workbenchCommand": {
9401
9890
  if (!a.workbench)
9402
9891
  unavailable();
9892
+ const command = decodeWorkbenchCommand(input);
9893
+ if (command.kind === "workflow" && caller.authority !== "local")
9894
+ throw new ContractError("forbidden");
9403
9895
  return {
9404
9896
  kind: "ok",
9405
- value: await a.workbench.command(decodeWorkbenchCommand(input))
9897
+ value: await a.workbench.command(command, caller)
9406
9898
  };
9899
+ }
9407
9900
  case "current":
9408
9901
  if (!a.current)
9409
9902
  unavailable();
@@ -9786,6 +10279,81 @@ import { dirname as dirname10, isAbsolute as isAbsolute6, join as join12, relati
9786
10279
  // src/worker-redaction.mjs
9787
10280
  var marker = "[redacted]";
9788
10281
  var sensitive = /^(?:authorization|proxy-authorization|cookie|set-cookie|password|passwd|secret|token|api[-_]?key|access[-_]?token|refresh[-_]?token|credentials|headers|env)$/i;
10282
+ function own(value, name) {
10283
+ if (!value || typeof value !== "object")
10284
+ throw new ContractError;
10285
+ const d = Object.getOwnPropertyDescriptor(value, name);
10286
+ if (!d)
10287
+ return;
10288
+ if (!("value" in d))
10289
+ throw new ContractError;
10290
+ return d.value;
10291
+ }
10292
+ function ownArray(value, maximum = LIMITS.dataFrames) {
10293
+ if (!Array.isArray(value))
10294
+ throw new ContractError;
10295
+ const length = own(value, "length");
10296
+ if (!Number.isSafeInteger(length) || length > maximum)
10297
+ throw new ContractError("oversize");
10298
+ return Array.from({ length }, (_, index) => own(value, String(index)));
10299
+ }
10300
+ function sourceBytes(value) {
10301
+ let bytes = 0;
10302
+ for (let i = 0;i < value.length; i++) {
10303
+ const code2 = value.charCodeAt(i);
10304
+ if (code2 < 128)
10305
+ bytes++;
10306
+ else if (code2 < 2048)
10307
+ bytes += 2;
10308
+ else if (code2 >= 55296 && code2 <= 56319 && value.charCodeAt(i + 1) >= 56320 && value.charCodeAt(i + 1) <= 57343) {
10309
+ bytes += 4;
10310
+ i++;
10311
+ } else if (code2 >= 55296 && code2 <= 57343)
10312
+ throw new ContractError;
10313
+ else
10314
+ bytes += 3;
10315
+ }
10316
+ return bytes;
10317
+ }
10318
+ function measureData(value, maximum = LIMITS.workerQueueBytes) {
10319
+ let bytes = 0;
10320
+ let nodes = 0;
10321
+ const seen = new Set;
10322
+ function visit(v, depth) {
10323
+ if (++nodes > LIMITS.dataFrames || depth > 64)
10324
+ throw new ContractError("oversize");
10325
+ if (typeof v === "string")
10326
+ bytes += sourceBytes(v) * 6 + 2;
10327
+ else if (v === null || typeof v === "boolean")
10328
+ bytes += 5;
10329
+ else if (typeof v === "number" && Number.isFinite(v))
10330
+ bytes += 32;
10331
+ else if (v && typeof v === "object") {
10332
+ if (seen.has(v) || ![Object.prototype, Array.prototype, null].includes(Object.getPrototypeOf(v)))
10333
+ throw new ContractError;
10334
+ seen.add(v);
10335
+ bytes += 2;
10336
+ const names2 = Reflect.ownKeys(v);
10337
+ if (names2.length > LIMITS.dataFrames)
10338
+ throw new ContractError("oversize");
10339
+ for (const key of names2) {
10340
+ if (Array.isArray(v) && key === "length")
10341
+ continue;
10342
+ if (typeof key !== "string")
10343
+ throw new ContractError;
10344
+ bytes += sourceBytes(key) * 6 + 4;
10345
+ visit(own(v, key), depth + 1);
10346
+ }
10347
+ seen.delete(v);
10348
+ } else
10349
+ throw new ContractError;
10350
+ if (bytes > maximum)
10351
+ throw new ContractError("oversize");
10352
+ }
10353
+ visit(value, 0);
10354
+ return bytes;
10355
+ }
10356
+
9789
10357
  class TextSanitizer {
9790
10358
  constructor(secrets = []) {
9791
10359
  if (secrets.some((s) => typeof s !== "string") || secrets.reduce((n, s) => n + utf8Bytes(s), 0) > LIMITS.workerRequestBytes * 2)
@@ -9931,6 +10499,27 @@ function sanitizeText(value, secrets = []) {
9931
10499
  const sanitizer = new TextSanitizer(secrets);
9932
10500
  return sanitizer.write(value, true);
9933
10501
  }
10502
+ function sanitizeData(value, secrets = []) {
10503
+ measureData(value);
10504
+ function visit(v) {
10505
+ if (typeof v === "string")
10506
+ return sanitizeText(v, secrets);
10507
+ if (v === null || typeof v !== "object")
10508
+ return v;
10509
+ if (Array.isArray(v))
10510
+ return ownArray(v).map(visit);
10511
+ const result = Object.create(null);
10512
+ for (const key of Object.keys(v).sort()) {
10513
+ const safeKey = sanitizeText(key, secrets);
10514
+ if (Object.hasOwn(result, safeKey))
10515
+ throw new ContractError;
10516
+ result[safeKey] = sensitive.test(key) ? marker : visit(own(v, key));
10517
+ }
10518
+ return result;
10519
+ }
10520
+ return canonicalJson(visit(value), LIMITS.workerQueueBytes);
10521
+ }
10522
+
9934
10523
  class DetailSanitizer {
9935
10524
  constructor(encoding, secrets = [], partial = false) {
9936
10525
  this.encoding = encoding;
@@ -10293,7 +10882,7 @@ async function createGateway(value, hostUrl, source) {
10293
10882
  const input = decodeGatewayInput(value), store = new GatewayStore(input.serverConfig, input.stateHome);
10294
10883
  const web = loadWebAssets(source?.webDirectory);
10295
10884
  const build2 = {
10296
- contractHash: "83a2720c0a5a61f9e18e4f67e9738f184dee61cf07e75d9b98b5728577daaa6d",
10885
+ contractHash: "d19e63723270a27a4c00776d8301849e08480e054bc832ca455f889d061c65c9",
10297
10886
  assets: {
10298
10887
  sourceHash: web.manifest.sourceHash,
10299
10888
  contractHash: web.manifest.contractHash,
@@ -10862,8 +11451,8 @@ Content-Length: 0\r
10862
11451
  }
10863
11452
 
10864
11453
  // src/service/host.ts
10865
- import { lstatSync as lstatSync14, opendirSync as opendirSync9 } from "node:fs";
10866
- import { join as join24 } from "node:path";
11454
+ import { lstatSync as lstatSync16, opendirSync as opendirSync11 } from "node:fs";
11455
+ import { join as join28 } from "node:path";
10867
11456
 
10868
11457
  // src/agent-registry.ts
10869
11458
  import { createHash as createHash10 } from "node:crypto";
@@ -10890,6 +11479,43 @@ function loadAgentDefinitions() {
10890
11479
  });
10891
11480
  }
10892
11481
 
11482
+ // src/cadence-preferences.ts
11483
+ import { join as join13 } from "node:path";
11484
+ class CadencePreferences {
11485
+ path;
11486
+ files;
11487
+ constructor(agentDir) {
11488
+ this.path = join13(agentDir, "cadence", "settings.json");
11489
+ this.files = new PrivateFiles(agentDir, false);
11490
+ }
11491
+ read() {
11492
+ const saved = this.files.read(this.path);
11493
+ if (!saved)
11494
+ return null;
11495
+ const o = closed(parseWireJson(saved.bytes.toString("utf8")), [
11496
+ "schema",
11497
+ "model"
11498
+ ]);
11499
+ if (o.schema !== "cadence-preferences/1")
11500
+ throw new Error("Unsupported Cadence preferences");
11501
+ return decodeModelSelector(o.model);
11502
+ }
11503
+ save(model) {
11504
+ const selected2 = decodeModelSelector(model);
11505
+ const previous = this.files.read(this.path);
11506
+ if (previous && canonicalJson(this.read()) === canonicalJson(selected2))
11507
+ return;
11508
+ const bytes = canonicalJson({
11509
+ schema: "cadence-preferences/1",
11510
+ model: selected2
11511
+ });
11512
+ if (previous)
11513
+ this.files.replace(this.path, previous, bytes);
11514
+ else
11515
+ this.files.create(this.path, bytes);
11516
+ }
11517
+ }
11518
+
10893
11519
  // src/history/live.ts
10894
11520
  function scopedSnapshot(source, scope) {
10895
11521
  if (scope.kind === "task" || source.scope.kind === "child")
@@ -11140,11 +11766,11 @@ class HistoryLive {
11140
11766
  // src/history/navigation.ts
11141
11767
  import { createHash as createHash11 } from "node:crypto";
11142
11768
  import { lstatSync as lstatSync10 } from "node:fs";
11143
- import { dirname as dirname11, join as join14 } from "node:path";
11769
+ import { dirname as dirname11, join as join15 } from "node:path";
11144
11770
 
11145
11771
  // src/history/index-tree.ts
11146
11772
  import { lstatSync as lstatSync9 } from "node:fs";
11147
- import { join as join13 } from "node:path";
11773
+ import { join as join14 } from "node:path";
11148
11774
  var MAX_NODE = 16 * 1024;
11149
11775
  var ACTIVE_KEY = "active";
11150
11776
  function chainHash(seq, previous, previousHash) {
@@ -11187,7 +11813,7 @@ class IndexTree {
11187
11813
  this.files = files;
11188
11814
  }
11189
11815
  path(id) {
11190
- return join13(this.files.directory, "indexes", "nodes", id.slice(0, 2), `${id}.json`);
11816
+ return join14(this.files.directory, "indexes", "nodes", id.slice(0, 2), `${id}.json`);
11191
11817
  }
11192
11818
  load(id, budget, unit) {
11193
11819
  decodeHash(id);
@@ -11520,7 +12146,7 @@ class HistoryNavigation {
11520
12146
  }
11521
12147
  }
11522
12148
  indexPath(group, id) {
11523
- return join14(this.files.directory, "indexes", group, `${id}.json`);
12149
+ return join15(this.files.directory, "indexes", group, `${id}.json`);
11524
12150
  }
11525
12151
  hintKey(group, id) {
11526
12152
  return `${this.files.directory}/${this.files.format.storeId}/${group}/${id}`;
@@ -11687,17 +12313,17 @@ class HistoryNavigation {
11687
12313
  continue;
11688
12314
  this.write(lease, "run-locators", runId, { pointers: [...pointers, p] }, charge, true);
11689
12315
  }
11690
- for (const taskId of rosters) {
11691
- const head = prepared?.heads.get(`roster:${taskId}`);
11692
- const old = head ? undefined : this.files.files.read(this.indexPath("rosters", taskId));
12316
+ for (const taskId2 of rosters) {
12317
+ const head = prepared?.heads.get(`roster:${taskId2}`);
12318
+ const old = head ? undefined : this.files.files.read(this.indexPath("rosters", taskId2));
11693
12319
  const previous = head ? head.previous : old ? decodeSequence(closed(parseWireJson(old.bytes.toString("utf8")), ["seq"]).seq) : null;
11694
- this.write(lease, "roster-links", `${taskId}/${p.seq}`, {
12320
+ this.write(lease, "roster-links", `${taskId2}/${p.seq}`, {
11695
12321
  pointer: p,
11696
12322
  previous,
11697
12323
  ...head ? { hash: head.hash, previousHash: head.previousHash } : {}
11698
12324
  }, charge);
11699
12325
  if (!head)
11700
- this.write(lease, "rosters", taskId, { seq: p.seq }, charge, true);
12326
+ this.write(lease, "rosters", taskId2, { seq: p.seq }, charge, true);
11701
12327
  }
11702
12328
  this.write(lease, "heads", "latest", p, charge, true);
11703
12329
  }
@@ -12106,16 +12732,16 @@ class HistoryNavigation {
12106
12732
  previous: previous !== null && previousHash !== null ? { seq: previous, hash: previousHash } : null
12107
12733
  };
12108
12734
  }
12109
- taskSuffix(taskId, snapshot, budget, accept) {
12110
- decodeId(taskId);
12735
+ taskSuffix(taskId2, snapshot, budget, accept) {
12736
+ decodeId(taskId2);
12111
12737
  try {
12112
- let head = this.anchoredHead(taskId, snapshot, budget) ?? null;
12738
+ let head = this.anchoredHead(taskId2, snapshot, budget) ?? null;
12113
12739
  const newer = [];
12114
12740
  while (head) {
12115
12741
  const base = accept(head);
12116
12742
  if (base !== undefined)
12117
12743
  return { base, batches: newer.reverse() };
12118
- const link = this.link("entity-links", taskId, head, budget);
12744
+ const link = this.link("entity-links", taskId2, head, budget);
12119
12745
  newer.push(this.batch(link.pointer, budget));
12120
12746
  head = link.previous;
12121
12747
  }
@@ -12315,16 +12941,16 @@ var STATES = 8;
12315
12941
 
12316
12942
  class TaskFoldMemory {
12317
12943
  tasks = new Map;
12318
- has(taskId) {
12319
- return this.tasks.has(taskId);
12944
+ has(taskId2) {
12945
+ return this.tasks.has(taskId2);
12320
12946
  }
12321
- remember(taskId, anchor, state) {
12322
- let states = this.tasks.get(taskId);
12947
+ remember(taskId2, anchor, state) {
12948
+ let states = this.tasks.get(taskId2);
12323
12949
  if (!states) {
12324
12950
  if (this.tasks.size >= TASKS)
12325
12951
  this.tasks.delete(this.tasks.keys().next().value ?? "");
12326
12952
  states = new Map;
12327
- this.tasks.set(taskId, states);
12953
+ this.tasks.set(taskId2, states);
12328
12954
  }
12329
12955
  states.delete(anchor.seq);
12330
12956
  states.set(anchor.seq, {
@@ -12334,8 +12960,8 @@ class TaskFoldMemory {
12334
12960
  if (states.size > STATES)
12335
12961
  states.delete(states.keys().next().value ?? "");
12336
12962
  }
12337
- recall(taskId, anchor) {
12338
- const entry = this.tasks.get(taskId)?.get(anchor.seq);
12963
+ recall(taskId2, anchor) {
12964
+ const entry = this.tasks.get(taskId2)?.get(anchor.seq);
12339
12965
  return entry?.hash === anchor.hash ? structuredClone(entry.state) : undefined;
12340
12966
  }
12341
12967
  }
@@ -12349,10 +12975,10 @@ function taskFoldMemory(files) {
12349
12975
  }
12350
12976
  return memory;
12351
12977
  }
12352
- function resumeTaskFold(files, navigation, taskId, snapshot, budget, resume) {
12978
+ function resumeTaskFold(files, navigation, taskId2, snapshot, budget, resume) {
12353
12979
  const memory = taskFoldMemory(files);
12354
- const suffix = memory.has(taskId) ? navigation.taskSuffix(taskId, snapshot, budget, (head) => {
12355
- const state = memory.recall(taskId, head);
12980
+ const suffix = memory.has(taskId2) ? navigation.taskSuffix(taskId2, snapshot, budget, (head) => {
12981
+ const state = memory.recall(taskId2, head);
12356
12982
  if (!state)
12357
12983
  return;
12358
12984
  try {
@@ -12364,7 +12990,7 @@ function resumeTaskFold(files, navigation, taskId, snapshot, budget, resume) {
12364
12990
  }) : undefined;
12365
12991
  return suffix ?? {
12366
12992
  base: undefined,
12367
- batches: navigation.entityBatches(taskId, snapshot, budget) ?? navigation.scanSnapshot(snapshot, budget)
12993
+ batches: navigation.entityBatches(taskId2, snapshot, budget) ?? navigation.scanSnapshot(snapshot, budget)
12368
12994
  };
12369
12995
  }
12370
12996
 
@@ -12376,10 +13002,10 @@ class CheckFold {
12376
13002
  this.starts = new Map(state?.starts);
12377
13003
  this.settled = new Map(state?.settled);
12378
13004
  }
12379
- apply(batch, taskId) {
13005
+ apply(batch, taskId2) {
12380
13006
  for (const row of batch.rows) {
12381
13007
  const v = row.value;
12382
- if (v.kind !== "owner" || v.link.taskId !== taskId)
13008
+ if (v.kind !== "owner" || v.link.taskId !== taskId2)
12383
13009
  continue;
12384
13010
  for (const e of v.events) {
12385
13011
  if (e.kind !== "owner" || e.value.kind !== "fact")
@@ -12420,7 +13046,7 @@ class CheckFold {
12420
13046
  settled: [...this.settled]
12421
13047
  };
12422
13048
  }
12423
- evaluate(taskId, configured, current) {
13049
+ evaluate(taskId2, configured, current) {
12424
13050
  const results = new Map;
12425
13051
  const incomplete = new Map;
12426
13052
  for (const [key, s] of this.settled) {
@@ -12438,7 +13064,7 @@ class CheckFold {
12438
13064
  throw new ContractError("receipt-inconclusive");
12439
13065
  return {
12440
13066
  checks: decodeCheckObligations({
12441
- taskId,
13067
+ taskId: taskId2,
12442
13068
  revision: configured.revision,
12443
13069
  definitions: configured.selections.map((selection) => results.get(canonicalJson(selection)) ?? {
12444
13070
  selection,
@@ -12451,18 +13077,18 @@ class CheckFold {
12451
13077
  };
12452
13078
  }
12453
13079
  }
12454
- function checkFold(files, taskId, snapshot, budget, navigation = new HistoryNavigation(files)) {
13080
+ function checkFold(files, taskId2, snapshot, budget, navigation = new HistoryNavigation(files)) {
12455
13081
  navigation.snapshot(snapshot, budget);
12456
- const { base, batches } = resumeTaskFold(files, navigation, taskId, snapshot, budget, (state) => state.checks);
13082
+ const { base, batches } = resumeTaskFold(files, navigation, taskId2, snapshot, budget, (state) => state.checks);
12457
13083
  const fold = new CheckFold(base);
12458
13084
  for (const b of batches)
12459
- fold.apply(b, taskId);
13085
+ fold.apply(b, taskId2);
12460
13086
  return fold;
12461
13087
  }
12462
- function currentChecks(files, taskId, configured, current, snapshotSeq) {
13088
+ function currentChecks(files, taskId2, configured, current, snapshotSeq) {
12463
13089
  const budget = HistoryReadBudget.authority(), navigation = new HistoryNavigation(files);
12464
13090
  const snapshot = snapshotSeq ?? navigation.latest(budget);
12465
- return checkFold(files, taskId, snapshot, budget, navigation).evaluate(taskId, configured, current);
13091
+ return checkFold(files, taskId2, snapshot, budget, navigation).evaluate(taskId2, configured, current);
12466
13092
  }
12467
13093
 
12468
13094
  // src/history/entity-state.ts
@@ -16255,16 +16881,16 @@ class HistoryProjection {
16255
16881
  };
16256
16882
  }
16257
16883
  };
16258
- checkObligations = async (taskId) => this.environment.checkObligations?.(taskId) ?? currentChecks(this.reader.files, taskId, this.environment.checks(taskId), this.environment.context(taskId)).checks;
16884
+ checkObligations = async (taskId2) => this.environment.checkObligations?.(taskId2) ?? currentChecks(this.reader.files, taskId2, this.environment.checks(taskId2), this.environment.context(taskId2)).checks;
16259
16885
  snapshot = async (input) => {
16260
16886
  const scope = decodeScope(input), budget = new HistoryReadBudget, seq2 = this.navigation.latest(budget), epoch = this.readEpoch();
16261
16887
  this.navigation.snapshot(seq2, budget);
16262
- let taskId = scope.kind === "task" ? scope.id : null;
16888
+ let taskId2 = scope.kind === "task" ? scope.id : null;
16263
16889
  const active = this.navigation.active(seq2, budget), groups = [], seen = new Set;
16264
16890
  const selected2 = (id) => {
16265
16891
  const group = this.runState(id, seq2, budget).projections(epoch).filter((r) => fits2(r, scope));
16266
16892
  if (group.length) {
16267
- taskId = group[0].taskId;
16893
+ taskId2 = group[0].taskId;
16268
16894
  seen.add(id);
16269
16895
  }
16270
16896
  return group;
@@ -16275,7 +16901,7 @@ class HistoryProjection {
16275
16901
  if (group.length)
16276
16902
  groups.push(group);
16277
16903
  }
16278
- if (!taskId) {
16904
+ if (!taskId2) {
16279
16905
  for (const b of this.navigation.reverseBatches(scope.id, seq2, budget)) {
16280
16906
  for (const row of b.rows)
16281
16907
  if (row.value.kind === "owner") {
@@ -16288,11 +16914,11 @@ class HistoryProjection {
16288
16914
  }
16289
16915
  }
16290
16916
  }
16291
- if (taskId)
16917
+ if (taskId2)
16292
16918
  break;
16293
16919
  }
16294
16920
  }
16295
- if (!taskId)
16921
+ if (!taskId2)
16296
16922
  fail();
16297
16923
  const runs = groups.flat();
16298
16924
  const base = {
@@ -16330,8 +16956,8 @@ class HistoryProjection {
16330
16956
  runs.push(...group);
16331
16957
  }
16332
16958
  }
16333
- const context = decodeControlContext(this.environment.context(taskId));
16334
- if (controlWorkspace(context) !== this.reader.files.format.workspaceId || controlTask(context) !== taskId)
16959
+ const context = decodeControlContext(this.environment.context(taskId2));
16960
+ if (controlWorkspace(context) !== this.reader.files.format.workspaceId || controlTask(context) !== taskId2)
16335
16961
  fail();
16336
16962
  const snapshot = decodeSnapshot({ ...base, context, runs });
16337
16963
  for (const observer of this.snapshotObservers) {
@@ -16350,7 +16976,7 @@ class HistoryProjection {
16350
16976
  // src/history/reader.ts
16351
16977
  import { createHash as createHash18 } from "node:crypto";
16352
16978
  import { existsSync as existsSync2 } from "node:fs";
16353
- import { join as join15 } from "node:path";
16979
+ import { join as join16 } from "node:path";
16354
16980
 
16355
16981
  // src/history/saved-graph-state.ts
16356
16982
  var freshSavedGraph = () => ({
@@ -16573,10 +17199,10 @@ class PlanFold {
16573
17199
  constructor(lineage) {
16574
17200
  this.lineage = lineage;
16575
17201
  }
16576
- apply(batch, taskId) {
17202
+ apply(batch, taskId2) {
16577
17203
  batch.rows.forEach((row, index) => {
16578
17204
  const value = row.value;
16579
- if (value.kind === "admission" && value.intent.identity.kind === "action" && value.intent.identity.action.kind === "save-plan" && value.intent.identity.action.taskId === taskId) {
17205
+ if (value.kind === "admission" && value.intent.identity.kind === "action" && value.intent.identity.action.kind === "save-plan" && value.intent.identity.action.taskId === taskId2) {
16580
17206
  if (value.intent.runId !== null)
16581
17207
  throw new ContractError("corrupt-selected");
16582
17208
  this.operation = new OperationState(value.intent.operationId);
@@ -16586,7 +17212,7 @@ class PlanFold {
16586
17212
  this.operation?.apply(row, batch.pointer.seq);
16587
17213
  if (!this.lineage)
16588
17214
  return;
16589
- this.lineage.apply(row, batch.pointer.seq, taskId, this.graphIdentity);
17215
+ this.lineage.apply(row, batch.pointer.seq, taskId2, this.graphIdentity);
16590
17216
  if (value.kind === "admission" && this.lineage.operationId === value.intent.operationId)
16591
17217
  this.lineageAt = { pointer: batch.pointer, row: index };
16592
17218
  });
@@ -16624,7 +17250,7 @@ class PlanFold {
16624
17250
  return fold;
16625
17251
  }
16626
17252
  }
16627
- function planFold(files, taskId, snapshot, budget, navigation, withLineage) {
17253
+ function planFold(files, taskId2, snapshot, budget, navigation, withLineage) {
16628
17254
  navigation.snapshot(snapshot, budget);
16629
17255
  const read2 = (at) => {
16630
17256
  if (BigInt(at.pointer.seq) > BigInt(snapshot))
@@ -16634,20 +17260,20 @@ function planFold(files, taskId, snapshot, budget, navigation, withLineage) {
16634
17260
  throw new ContractError("invalid");
16635
17261
  return row;
16636
17262
  };
16637
- const { base, batches } = resumeTaskFold(files, navigation, taskId, snapshot, budget, (state) => PlanFold.resumed(state.plan, withLineage, read2));
17263
+ const { base, batches } = resumeTaskFold(files, navigation, taskId2, snapshot, budget, (state) => PlanFold.resumed(state.plan, withLineage, read2));
16638
17264
  const fold = base ?? new PlanFold(withLineage ? new TaskPublicationLineage : null);
16639
17265
  for (const batch of batches)
16640
- fold.apply(batch, taskId);
17266
+ fold.apply(batch, taskId2);
16641
17267
  return fold;
16642
17268
  }
16643
- function latestTaskRun(files, taskId, snapshot, budget, navigation = new HistoryNavigation(files)) {
17269
+ function latestTaskRun(files, taskId2, snapshot, budget, navigation = new HistoryNavigation(files)) {
16644
17270
  navigation.snapshot(snapshot, budget);
16645
- const { base, batches } = resumeTaskFold(files, navigation, taskId, snapshot, budget, (state) => state.run);
17271
+ const { base, batches } = resumeTaskFold(files, navigation, taskId2, snapshot, budget, (state) => state.run);
16646
17272
  let latest = base ?? null;
16647
17273
  for (const batch of batches)
16648
17274
  for (const row of batch.rows) {
16649
17275
  const v = row.value;
16650
- if (v.kind === "admission" && v.intent.identity.kind === "action" && v.intent.identity.expected.task?.id === taskId && (v.intent.identity.action.kind === "start" || v.intent.identity.action.kind === "generate-plan"))
17276
+ if (v.kind === "admission" && v.intent.identity.kind === "action" && v.intent.identity.expected.task?.id === taskId2 && (v.intent.identity.action.kind === "start" || v.intent.identity.action.kind === "generate-plan"))
16651
17277
  latest = v.intent.runId;
16652
17278
  }
16653
17279
  return latest;
@@ -16680,11 +17306,11 @@ class HistoryReader {
16680
17306
  throw new ContractError("corrupt-selected");
16681
17307
  return this.files.readAdmission(runId, state.admission, budget);
16682
17308
  }
16683
- publishedPlan(taskId, snapshotSeq, current2) {
16684
- decodeId(taskId);
17309
+ publishedPlan(taskId2, snapshotSeq, current2) {
17310
+ decodeId(taskId2);
16685
17311
  decodeSequence(snapshotSeq);
16686
17312
  const budget = HistoryReadBudget.authority();
16687
- const fold = planFold(this.files, taskId, snapshotSeq, budget, this.navigation, !!current2);
17313
+ const fold = planFold(this.files, taskId2, snapshotSeq, budget, this.navigation, !!current2);
16688
17314
  const { operation, lineage } = fold;
16689
17315
  if (!operation)
16690
17316
  return null;
@@ -16698,7 +17324,7 @@ class HistoryReader {
16698
17324
  const ref = graph.plan;
16699
17325
  const { detail, bytes: text2 } = this.planText({
16700
17326
  storeId: this.storeId,
16701
- scope: { kind: "task", id: taskId },
17327
+ scope: { kind: "task", id: taskId2 },
16702
17328
  snapshotSeq,
16703
17329
  query: null,
16704
17330
  recordId: ref.recordId,
@@ -16706,7 +17332,7 @@ class HistoryReader {
16706
17332
  field: "plan",
16707
17333
  offset: 0
16708
17334
  }, budget);
16709
- if (canonicalJson(detail.content) !== canonicalJson(ref) || detail.origin.kind !== "owner" || detail.origin.id !== operation.operationId || detail.owner.taskId !== taskId || detail.owner.runId !== null || detail.owner.childRunId !== null || detail.owner.entity.kind !== "task" || detail.owner.entity.id !== taskId || detail.owner.entity.version !== graph.planRevision || ref.bytes > 32768)
17335
+ if (canonicalJson(detail.content) !== canonicalJson(ref) || detail.origin.kind !== "owner" || detail.origin.id !== operation.operationId || detail.owner.taskId !== taskId2 || detail.owner.runId !== null || detail.owner.childRunId !== null || detail.owner.entity.kind !== "task" || detail.owner.entity.id !== taskId2 || detail.owner.entity.version !== graph.planRevision || ref.bytes > 32768)
16710
17336
  throw new ContractError("corrupt-selected");
16711
17337
  if (text2.toString("utf8") !== plan)
16712
17338
  throw new ContractError("corrupt-selected");
@@ -16730,11 +17356,11 @@ class HistoryReader {
16730
17356
  committedSeq: receipt.receipt.committedSeq
16731
17357
  };
16732
17358
  }
16733
- reviewRun(taskId, runId, snapshotSeq, budget = HistoryReadBudget.authority()) {
16734
- decodeId(taskId);
17359
+ reviewRun(taskId2, runId, snapshotSeq, budget = HistoryReadBudget.authority()) {
17360
+ decodeId(taskId2);
16735
17361
  decodeId(runId);
16736
17362
  decodeSequence(snapshotSeq);
16737
- const latest = latestTaskRun(this.files, taskId, snapshotSeq, budget, this.navigation);
17363
+ const latest = latestTaskRun(this.files, taskId2, snapshotSeq, budget, this.navigation);
16738
17364
  if (latest !== runId)
16739
17365
  throw new ContractError("stale");
16740
17366
  const state = new RunState(runId);
@@ -16742,14 +17368,14 @@ class HistoryReader {
16742
17368
  for (const batch of runBatches)
16743
17369
  for (const row of batch.rows)
16744
17370
  state.apply(row, batch.pointer.seq);
16745
- if (!state.admission || state.admission.context.task?.id !== taskId || !state.drained || state.publication !== "published")
17371
+ if (!state.admission || state.admission.context.task?.id !== taskId2 || !state.drained || state.publication !== "published")
16746
17372
  throw new ContractError("conflict");
16747
17373
  this.files.readAdmission(runId, state.admission, budget);
16748
17374
  return state;
16749
17375
  }
16750
- reviewSelection(taskId, runId, snapshotSeq) {
17376
+ reviewSelection(taskId2, runId, snapshotSeq) {
16751
17377
  const budget = HistoryReadBudget.authority();
16752
- const run = this.reviewRun(taskId, runId, snapshotSeq, budget);
17378
+ const run = this.reviewRun(taskId2, runId, snapshotSeq, budget);
16753
17379
  if (!run.admission)
16754
17380
  throw new ContractError("corrupt-selected");
16755
17381
  const { graph } = this.files.readAdmission(runId, run.admission, budget);
@@ -16758,7 +17384,7 @@ class HistoryReader {
16758
17384
  const ref = graph.plan;
16759
17385
  const { detail, bytes } = this.planText({
16760
17386
  storeId: this.storeId,
16761
- scope: { kind: "task", id: taskId },
17387
+ scope: { kind: "task", id: taskId2 },
16762
17388
  snapshotSeq,
16763
17389
  query: null,
16764
17390
  recordId: ref.recordId,
@@ -16766,7 +17392,7 @@ class HistoryReader {
16766
17392
  field: "plan",
16767
17393
  offset: 0
16768
17394
  }, budget);
16769
- if (ref.bytes > 32768 || canonicalJson(detail.content) !== canonicalJson(ref) || detail.owner.taskId !== taskId || detail.owner.runId !== null || detail.owner.childRunId !== null || detail.owner.entity.kind !== "task" || detail.owner.entity.id !== taskId || detail.owner.entity.version !== graph.planRevision)
17395
+ if (ref.bytes > 32768 || canonicalJson(detail.content) !== canonicalJson(ref) || detail.owner.taskId !== taskId2 || detail.owner.runId !== null || detail.owner.childRunId !== null || detail.owner.entity.kind !== "task" || detail.owner.entity.id !== taskId2 || detail.owner.entity.version !== graph.planRevision)
16770
17396
  throw new ContractError("corrupt-selected");
16771
17397
  return { run, graph, readablePlan: bytes.toString("utf8") };
16772
17398
  }
@@ -17118,7 +17744,7 @@ class HistoryReader {
17118
17744
  }
17119
17745
  async readDetail(value) {
17120
17746
  const cursor = decodeCursor(value);
17121
- if (cursor.navigation !== undefined || this.files.format.schema === FORMAT && !existsSync2(join15(this.files.directory, "indexes", "heads", "latest.json")))
17747
+ if (cursor.navigation !== undefined || this.files.format.schema === FORMAT && !existsSync2(join16(this.files.directory, "indexes", "heads", "latest.json")))
17122
17748
  return readRetainedDetail(this, cursor);
17123
17749
  if (this.files.format.schema !== FORMAT)
17124
17750
  return this.detail(cursor);
@@ -17320,7 +17946,7 @@ class HistoryReader {
17320
17946
 
17321
17947
  // src/history/writer.ts
17322
17948
  import { createHash as createHash20, randomUUID as randomUUID12 } from "node:crypto";
17323
- import { join as join17 } from "node:path";
17949
+ import { join as join18 } from "node:path";
17324
17950
 
17325
17951
  // src/history/plans.ts
17326
17952
  import { createHash as createHash19, randomUUID as randomUUID11 } from "node:crypto";
@@ -17399,7 +18025,7 @@ import {
17399
18025
  openSync as openSync6,
17400
18026
  realpathSync as realpathSync4
17401
18027
  } from "node:fs";
17402
- import { dirname as dirname12, isAbsolute as isAbsolute7, join as join16, relative as relative6, sep as sep5 } from "node:path";
18028
+ import { dirname as dirname12, isAbsolute as isAbsolute7, join as join17, relative as relative6, sep as sep5 } from "node:path";
17403
18029
  function summary(text2, maximum, runId) {
17404
18030
  const label = `[Cadence summary${runId ? `; run ${runId}` : ""}; retained history is separate]
17405
18031
  `;
@@ -17581,10 +18207,10 @@ ${result}`;
17581
18207
  throw new ContractError("capacity");
17582
18208
  return record2;
17583
18209
  }
17584
- function syncTaskPublication(store, taskId) {
18210
+ function syncTaskPublication(store, taskId2) {
17585
18211
  if (process.platform === "win32")
17586
18212
  return;
17587
- for (let path = join16(store.tasks, taskId);; path = dirname12(path)) {
18213
+ for (let path = join17(store.tasks, taskId2);; path = dirname12(path)) {
17588
18214
  if (!safeDirectory(path))
17589
18215
  throw new ContractError("conflict");
17590
18216
  const fd = openSync6(path, constants6.O_RDONLY | constants6.O_DIRECTORY);
@@ -17883,11 +18509,11 @@ class HistoryWriter {
17883
18509
  this.reviews.set(operationId, { taskId: identity.action.taskId });
17884
18510
  return this.ownerPort();
17885
18511
  }
17886
- controlRevision(taskId) {
17887
- return this.revisions.get(taskId ?? "workspace") ?? 1;
18512
+ controlRevision(taskId2) {
18513
+ return this.revisions.get(taskId2 ?? "workspace") ?? 1;
17888
18514
  }
17889
- currentContext(taskId) {
17890
- const v = this.contexts.get(taskId ?? "workspace");
18515
+ currentContext(taskId2) {
18516
+ const v = this.contexts.get(taskId2 ?? "workspace");
17891
18517
  return v ? decodeContext(v) : null;
17892
18518
  }
17893
18519
  fence() {
@@ -17917,13 +18543,13 @@ class HistoryWriter {
17917
18543
  const last = operation.publication;
17918
18544
  if (last?.kind === "publication-settled" && (last.status === "uncertain" || last.status === "conflict"))
17919
18545
  return;
17920
- const taskId = intent.createdTaskId ?? intent.identity.expected.task?.id;
17921
- if (!taskId)
18546
+ const taskId2 = intent.createdTaskId ?? intent.identity.expected.task?.id;
18547
+ if (!taskId2)
17922
18548
  throw new ContractError("conflict");
17923
18549
  return this.ownerValue({
17924
18550
  link: {
17925
18551
  epoch: intent.identity.expected.epoch,
17926
- taskId,
18552
+ taskId: taskId2,
17927
18553
  runId: intent.runId,
17928
18554
  operationId
17929
18555
  },
@@ -18337,7 +18963,7 @@ class HistoryWriter {
18337
18963
  try {
18338
18964
  const budget = HistoryReadBudget.authority();
18339
18965
  const intent = this.files.readCommand(commandId, budget);
18340
- const directoryExists = this.files.files.directory(join17(this.files.directory, "commands", commandId));
18966
+ const directoryExists = this.files.files.directory(join18(this.files.directory, "commands", commandId));
18341
18967
  const wanted = intent ? decodeAdmissionIntent(json(intent, RECORD_BYTES)) : null;
18342
18968
  let found = null;
18343
18969
  let run = null;
@@ -18483,8 +19109,8 @@ class HistoryWriter {
18483
19109
  this.assertOrdinary();
18484
19110
  const bytes = encoded(intent);
18485
19111
  this.charge(Buffer.byteLength(bytes), intent.runId, true);
18486
- this.files.files.create(join17(this.files.directory, "commands", intent.commandId, "intent.json"), bytes, RECORD_BYTES);
18487
- this.files.syncParents(join17(this.files.directory, "commands", intent.commandId, "intent.json"));
19112
+ this.files.files.create(join18(this.files.directory, "commands", intent.commandId, "intent.json"), bytes, RECORD_BYTES);
19113
+ this.files.syncParents(join18(this.files.directory, "commands", intent.commandId, "intent.json"));
18488
19114
  await this.options.observeWrite?.("intent");
18489
19115
  const policy = this.resourcePolicy(intent.identity.kind === "action" ? intent.identity.expected.configRev : 1);
18490
19116
  return { kind: "admission", intent, record: record2, policy };
@@ -18612,15 +19238,15 @@ class HistoryWriter {
18612
19238
  for (const { value: v } of rows)
18613
19239
  if (v.kind === "owner" && v.events.some((e) => e.kind === "owner" && e.value.kind === "fact" && e.value.fact.kind === "publication-settled"))
18614
19240
  tasks.add(v.link.taskId);
18615
- for (const taskId of tasks) {
18616
- const head = prepared.heads.get(taskId);
19241
+ for (const taskId2 of tasks) {
19242
+ const head = prepared.heads.get(taskId2);
18617
19243
  if (!head || head.seq !== this.state.committedSeq)
18618
19244
  continue;
18619
19245
  try {
18620
- const checks = checkFold(this.files, taskId, head.seq, HistoryReadBudget.authority()).state();
18621
- const run = latestTaskRun(this.files, taskId, head.seq, HistoryReadBudget.authority());
18622
- const plan = planFold(this.files, taskId, head.seq, HistoryReadBudget.authority(), new HistoryNavigation(this.files), true).state();
18623
- taskFoldMemory(this.files).remember(taskId, head, {
19246
+ const checks = checkFold(this.files, taskId2, head.seq, HistoryReadBudget.authority()).state();
19247
+ const run = latestTaskRun(this.files, taskId2, head.seq, HistoryReadBudget.authority());
19248
+ const plan = planFold(this.files, taskId2, head.seq, HistoryReadBudget.authority(), new HistoryNavigation(this.files), true).state();
19249
+ taskFoldMemory(this.files).remember(taskId2, head, {
18624
19250
  checks,
18625
19251
  run,
18626
19252
  plan
@@ -18665,8 +19291,8 @@ class HistoryWriter {
18665
19291
  throw new ContractError("stale");
18666
19292
  if (intent.identity.kind !== "action" || intent.identity.expected.epoch !== this.lease.registration.epoch)
18667
19293
  throw new ContractError("stale");
18668
- const identity = intent.identity, taskId = intent.createdTaskId ?? identity.expected.task?.id;
18669
- if (!taskId)
19294
+ const identity = intent.identity, taskId2 = intent.createdTaskId ?? identity.expected.task?.id;
19295
+ if (!taskId2)
18670
19296
  throw new ContractError("conflict");
18671
19297
  const current2 = this.contexts.get(identity.expected.task?.id ?? "workspace");
18672
19298
  if (!current2 || current2.epoch !== identity.expected.epoch || current2.controlRev !== identity.expected.controlRev + 1)
@@ -18676,7 +19302,7 @@ class HistoryWriter {
18676
19302
  if (!latest || canonicalJson(latest) !== canonicalJson(current2))
18677
19303
  throw new ContractError("stale");
18678
19304
  if (identity.action.kind === "review") {
18679
- const review = this.options.reviewContext?.(taskId, this.reviews.get(request3.operationId)?.published);
19305
+ const review = this.options.reviewContext?.(taskId2, this.reviews.get(request3.operationId)?.published);
18680
19306
  if (!review || review.observation.identity !== identity.action.changesIdentity || review.checks.revision !== identity.action.checksRevision)
18681
19307
  throw new ContractError("stale");
18682
19308
  }
@@ -18688,7 +19314,7 @@ class HistoryWriter {
18688
19314
  expected = run ? run.publicationExpected() : operation.state.publicationExpected();
18689
19315
  link = {
18690
19316
  epoch: identity.expected.epoch,
18691
- taskId,
19317
+ taskId: taskId2,
18692
19318
  runId: intent.runId,
18693
19319
  operationId: intent.operationId
18694
19320
  };
@@ -19128,13 +19754,13 @@ class HistoryWriter {
19128
19754
  }
19129
19755
  return { kind: "capture", link: input.link, source: input.source, events };
19130
19756
  }
19131
- assertContent(content, taskId, runId, entity, operationId) {
19757
+ assertContent(content, taskId2, runId, entity, operationId) {
19132
19758
  const reader = HistoryReader.open(this.lease.coordination);
19133
19759
  if (!reader)
19134
19760
  throw new ContractError("corrupt-selected");
19135
19761
  const detail = reader.selected({
19136
19762
  storeId: reader.storeId,
19137
- scope: { kind: "task", id: taskId },
19763
+ scope: { kind: "task", id: taskId2 },
19138
19764
  snapshotSeq: this.state.committedSeq,
19139
19765
  recordId: content.recordId,
19140
19766
  recordVersion: content.version,
@@ -19142,7 +19768,7 @@ class HistoryWriter {
19142
19768
  offset: 0,
19143
19769
  query: null
19144
19770
  });
19145
- if (canonicalJson(detail.content) !== canonicalJson(content) || detail.owner.taskId !== taskId || detail.owner.runId !== runId || detail.owner.entity.id !== entity.id || detail.owner.entity.kind !== entity.kind || operationId !== undefined && (detail.origin.kind !== "owner" || detail.origin.id !== operationId) || "version" in entity && detail.owner.entity.version !== entity.version)
19771
+ if (canonicalJson(detail.content) !== canonicalJson(content) || detail.owner.taskId !== taskId2 || detail.owner.runId !== runId || detail.owner.entity.id !== entity.id || detail.owner.entity.kind !== entity.kind || operationId !== undefined && (detail.origin.kind !== "owner" || detail.origin.id !== operationId) || "version" in entity && detail.owner.entity.version !== entity.version)
19146
19772
  throw new ContractError("corrupt-selected");
19147
19773
  for (const _ of reader.parts(detail, this.state.committedSeq)) {}
19148
19774
  }
@@ -19518,6 +20144,7 @@ class OwnerModelChoice {
19518
20144
  this.catalogId = randomUUID13();
19519
20145
  this.options.owner.configurationInstalled();
19520
20146
  }
20147
+ this.options.remember?.(request3.choice);
19521
20148
  return this.snapshot();
19522
20149
  } finally {
19523
20150
  this.installing = false;
@@ -19527,7 +20154,7 @@ class OwnerModelChoice {
19527
20154
 
19528
20155
  // src/service/model-config.ts
19529
20156
  import { lstatSync as lstatSync11, realpathSync as realpathSync5 } from "node:fs";
19530
- import { dirname as dirname13, isAbsolute as isAbsolute8, join as join18, resolve as resolve7 } from "node:path";
20157
+ import { dirname as dirname13, isAbsolute as isAbsolute8, join as join19, resolve as resolve7 } from "node:path";
19531
20158
  var CONFIG_BYTES2 = 1024 * 1024;
19532
20159
  var ENTRY_LIMIT = 256;
19533
20160
  function refuse2() {
@@ -19594,13 +20221,13 @@ function captureEnvironment(value) {
19594
20221
  function piSource(agentDir, home, cwd, env) {
19595
20222
  if (!isAbsolute8(home) || !isAbsolute8(cwd))
19596
20223
  refuse2();
19597
- let selected2 = agentDir ?? env.PI_CODING_AGENT_DIR ?? join18(home, ".pi", "agent");
20224
+ let selected2 = agentDir ?? env.PI_CODING_AGENT_DIR ?? join19(home, ".pi", "agent");
19598
20225
  if (!selected2 || selected2.includes("\x00"))
19599
20226
  refuse2();
19600
20227
  if (selected2 === "~" || selected2.startsWith("~/"))
19601
20228
  selected2 = home + selected2.slice(1);
19602
20229
  selected2 = resolve7(cwd, selected2);
19603
- const directory = join18(realpathSync5(dirname13(selected2)), selected2.slice(dirname13(selected2).length + 1));
20230
+ const directory = join19(realpathSync5(dirname13(selected2)), selected2.slice(dirname13(selected2).length + 1));
19604
20231
  if (!lstatSync11(directory).isDirectory() || lstatSync11(directory).isSymbolicLink())
19605
20232
  refuse2();
19606
20233
  const files = new PrivateFiles(directory, false);
@@ -19609,8 +20236,8 @@ function piSource(agentDir, home, cwd, env) {
19609
20236
  return {
19610
20237
  directory,
19611
20238
  files,
19612
- authPath: join18(directory, "auth.json"),
19613
- modelsPath: join18(directory, "models.json")
20239
+ authPath: join19(directory, "auth.json"),
20240
+ modelsPath: join19(directory, "models.json")
19614
20241
  };
19615
20242
  }
19616
20243
  function templateNames(value) {
@@ -21044,7 +21671,7 @@ import { realpathSync as realpathSync6 } from "node:fs";
21044
21671
  import { spawnSync as spawnSync2 } from "node:child_process";
21045
21672
  import { createHash as createHash21 } from "node:crypto";
21046
21673
  import { lstatSync as lstatSync12, readdirSync as readdirSync3, readlinkSync } from "node:fs";
21047
- import { join as join19, relative as relative7 } from "node:path";
21674
+ import { join as join20, relative as relative7 } from "node:path";
21048
21675
  var admin = (path) => path === ".cadence/assistant/tasks" || path.startsWith(".cadence/assistant/tasks/");
21049
21676
  var GIT_OUTPUT_BYTES = 16 * 1024 * 1024;
21050
21677
  function captureChanges(root, outputBytes = GIT_OUTPUT_BYTES) {
@@ -21087,7 +21714,7 @@ function captureChanges(root, outputBytes = GIT_OUTPUT_BYTES) {
21087
21714
  return;
21088
21715
  }
21089
21716
  try {
21090
- const path = join19(root, name);
21717
+ const path = join20(root, name);
21091
21718
  const st = lstatSync12(path);
21092
21719
  add(name, `${st.mode}:${st.size}`);
21093
21720
  if (st.isSymbolicLink()) {
@@ -21228,7 +21855,7 @@ ${data2.toString("utf8")}`);
21228
21855
  return;
21229
21856
  }
21230
21857
  for (const name of names2) {
21231
- const path = join19(dir, name);
21858
+ const path = join20(dir, name);
21232
21859
  const rel = relative7(root, path).split("\\").join("/");
21233
21860
  if (rel === ".git" || admin(rel))
21234
21861
  continue;
@@ -21791,7 +22418,7 @@ class ActionAdmission {
21791
22418
 
21792
22419
  // src/service/graph.ts
21793
22420
  import { createHash as createHash22 } from "node:crypto";
21794
- import { join as join20 } from "node:path";
22421
+ import { join as join21 } from "node:path";
21795
22422
  var hash3 = (text2) => createHash22("sha256").update(text2).digest("hex");
21796
22423
 
21797
22424
  class GraphContext {
@@ -21801,7 +22428,7 @@ class GraphContext {
21801
22428
  identity;
21802
22429
  constructor(root) {
21803
22430
  this.root = root;
21804
- const bytes = readBounded(join20(root, "AGENTS.md"), 32768);
22431
+ const bytes = readBounded(join21(root, "AGENTS.md"), 32768);
21805
22432
  this.hints = bytes ? new TextDecoder("utf-8", { fatal: true }).decode(bytes) : "";
21806
22433
  this.identity = hash3(canonicalJson({
21807
22434
  hints: bytes === undefined ? null : hash3(bytes),
@@ -21938,7 +22565,7 @@ import { randomUUID as randomUUID17 } from "node:crypto";
21938
22565
 
21939
22566
  // src/subagent-process.ts
21940
22567
  import { spawn as spawn2 } from "node:child_process";
21941
- import { join as join21 } from "node:path";
22568
+ import { join as join22 } from "node:path";
21942
22569
  import { StringDecoder } from "node:string_decoder";
21943
22570
  import { fileURLToPath as fileURLToPath4 } from "node:url";
21944
22571
 
@@ -21952,7 +22579,7 @@ function argumentsData(value, secrets) {
21952
22579
  throw new Error("Unsupported context arguments");
21953
22580
  return parseWireJson(source, 64 * 1024);
21954
22581
  }
21955
- function own(value, key2) {
22582
+ function own2(value, key2) {
21956
22583
  const d = value && typeof value === "object" ? Object.getOwnPropertyDescriptor(value, key2) : undefined;
21957
22584
  if (!d || !("value" in d))
21958
22585
  throw new Error("Invalid usage");
@@ -21961,7 +22588,7 @@ function own(value, key2) {
21961
22588
  function counts(value, keys3) {
21962
22589
  const out = Object.create(null);
21963
22590
  for (const key2 of keys3) {
21964
- const n = own(value, key2);
22591
+ const n = own2(value, key2);
21965
22592
  if (typeof n !== "number" || !Number.isFinite(n) || n < 0)
21966
22593
  throw new Error("Invalid usage");
21967
22594
  out[key2] = n;
@@ -22004,7 +22631,7 @@ function conversationMessages(messages, secrets = []) {
22004
22631
  "cacheWrite",
22005
22632
  "totalTokens"
22006
22633
  ]);
22007
- usage.cost = counts(own(message.usage, "cost"), [
22634
+ usage.cost = counts(own2(message.usage, "cost"), [
22008
22635
  "input",
22009
22636
  "output",
22010
22637
  "cacheRead",
@@ -22611,7 +23238,7 @@ class WorkerRecording {
22611
23238
  // src/subagent-process.ts
22612
23239
  function terminateWindowsTree(pid, fallback) {
22613
23240
  const root = process.env.SystemRoot;
22614
- const taskkill = spawn2(root ? join21(root, "System32", "taskkill.exe") : "taskkill.exe", ["/F", "/T", "/PID", String(pid)], { stdio: "ignore", windowsHide: true });
23241
+ const taskkill = spawn2(root ? join22(root, "System32", "taskkill.exe") : "taskkill.exe", ["/F", "/T", "/PID", String(pid)], { stdio: "ignore", windowsHide: true });
22615
23242
  taskkill.once("error", fallback);
22616
23243
  taskkill.once("close", (code2) => {
22617
23244
  if (code2 !== 0)
@@ -22656,7 +23283,8 @@ function runProcess(spec) {
22656
23283
  spec.input === undefined ? "ignore" : "pipe",
22657
23284
  "pipe",
22658
23285
  "pipe",
22659
- ...spec.onContext ? ["pipe"] : []
23286
+ ...spec.onContext || spec.onCoordinator ? [spec.onContext ? "pipe" : "ignore"] : [],
23287
+ ...spec.onCoordinator ? ["ipc"] : []
22660
23288
  ]
22661
23289
  });
22662
23290
  const contextStream = spec.onContext ? child.stdio[3] : null;
@@ -22736,6 +23364,8 @@ function runProcess(spec) {
22736
23364
  child.stderr.destroy();
22737
23365
  child.stdin?.destroy();
22738
23366
  contextStream?.destroy();
23367
+ if (child.connected)
23368
+ child.disconnect();
22739
23369
  }
22740
23370
  };
22741
23371
  const signalChild = (signal) => {
@@ -22761,6 +23391,40 @@ function runProcess(spec) {
22761
23391
  killTimer = setTimeout(() => signalChild("SIGKILL"), 1000);
22762
23392
  unknownTimer = setTimeout(() => finish(false, null, null), 3000);
22763
23393
  };
23394
+ let bridgeCalls = 0;
23395
+ let bridgeBusy = false;
23396
+ if (spec.onCoordinator)
23397
+ child.on("message", (message) => {
23398
+ if (settled || stopping)
23399
+ return;
23400
+ (async () => {
23401
+ let id;
23402
+ try {
23403
+ const body = JSON.stringify(message);
23404
+ if (++bridgeCalls > 16 || bridgeBusy || Buffer.byteLength(body) > 65536 || sanitizeText(body, spec.secrets ?? []) !== body)
23405
+ throw new Error("Invalid coordinator frame");
23406
+ const row = closed(message, ["id", "name", "args"]);
23407
+ if (!Number.isSafeInteger(row.id) || row.id < 1 || typeof row.name !== "string")
23408
+ throw new Error("Invalid coordinator frame");
23409
+ id = row.id;
23410
+ bridgeBusy = true;
23411
+ const value = await spec.onCoordinator?.(row.name, row.args, ingressStop.signal);
23412
+ const text2 = sanitizeText(JSON.stringify(value), spec.secrets ?? []);
23413
+ const reply = { id, ok: true, text: text2 };
23414
+ if (Buffer.byteLength(JSON.stringify(reply)) > 65536)
23415
+ throw new Error("Coordinator result exceeds bound");
23416
+ if (!settled && !stopping && child.connected)
23417
+ child.send(reply, () => {});
23418
+ } catch {
23419
+ if (id !== undefined && child.connected && !settled && !stopping)
23420
+ child.send({ id, ok: false }, () => {});
23421
+ else
23422
+ stop("failed");
23423
+ } finally {
23424
+ bridgeBusy = false;
23425
+ }
23426
+ })();
23427
+ });
22764
23428
  const abort = () => stop("canceled");
22765
23429
  const timeout = setTimeout(() => stop("timeout"), spec.timeoutMs);
22766
23430
  spec.signal.addEventListener("abort", abort, { once: true });
@@ -23084,6 +23748,7 @@ function launchConversation(prepared, conversation, signal, options) {
23084
23748
  return launchEncoded(encoded2, signal, options.timeoutMs, {
23085
23749
  maySignal: options.maySignal,
23086
23750
  onNative: options.onNative,
23751
+ onCoordinator: options.onCoordinator,
23087
23752
  onFrame: (frame) => options.onFrame(frame, secrets),
23088
23753
  onContext: (source) => {
23089
23754
  const value = closed(parseWireJson(source, CONTEXT_BYTES), [
@@ -23100,8 +23765,29 @@ function launchConversation(prepared, conversation, signal, options) {
23100
23765
  });
23101
23766
  });
23102
23767
  }
23103
- function runCheck(check, cwd, signal, service) {
23104
- return runProcess({
23768
+ function launchWorkflowWorker(prepared, cwd, signal, options) {
23769
+ let encoded2;
23770
+ return prepared.consume((material) => {
23771
+ encoded2 = encodeEnvelope({
23772
+ ...material,
23773
+ cwd,
23774
+ model: { ...material.model }
23775
+ });
23776
+ return encoded2.input;
23777
+ }, (input) => {
23778
+ if (!encoded2 || encoded2.input !== input)
23779
+ throw new Error("Invalid workflow launch");
23780
+ const secrets = [...encoded2.secrets, ...options.ownerSecrets];
23781
+ return launchEncoded(encoded2, signal, options.timeoutMs, {
23782
+ secrets,
23783
+ maySignal: options.maySignal,
23784
+ onNative: (native, capture) => options.onNative(native, capture?.selected?.messageId),
23785
+ onFrame: (frame) => options.onFrame(frame, secrets)
23786
+ });
23787
+ });
23788
+ }
23789
+ function runCheck(check, cwd, signal, service) {
23790
+ return runProcess({
23105
23791
  command: process.platform === "win32" ? (service?.environment ?? process.env).COMSPEC ?? "cmd.exe" : "/bin/sh",
23106
23792
  args: process.platform === "win32" ? ["/d", "/s", "/c", `"${check.command}"`] : ["-c", check.command],
23107
23793
  windowsVerbatimArguments: process.platform === "win32" ? true : undefined,
@@ -23465,8 +24151,8 @@ class TaskScheduler {
23465
24151
  stage: e.reason || e.settling || this.closed ? "draining" : e.allocated ? "active" : "accepted-unallocated"
23466
24152
  }));
23467
24153
  }
23468
- activeTask(taskId) {
23469
- return [...this.episodes.values()].find((e) => e.link.taskId === taskId)?.target.runId ?? null;
24154
+ activeTask(taskId2) {
24155
+ return [...this.episodes.values()].find((e) => e.link.taskId === taskId2)?.target.runId ?? null;
23470
24156
  }
23471
24157
  async settled(runId) {
23472
24158
  await this.episodes.get(runId)?.done;
@@ -24256,8 +24942,8 @@ class TaskActions {
24256
24942
  lookupForAdmission: (id) => options.host.writer.lookupForAdmission(id),
24257
24943
  commit: (intent) => this.commit(intent)
24258
24944
  }, this, { now: () => Date.now(), uuid: () => randomUUID18() });
24259
- options.host.writer.bindReviewContext((taskId, published) => {
24260
- const current2 = this.reviewing.get(taskId);
24945
+ options.host.writer.bindReviewContext((taskId2, published) => {
24946
+ const current2 = this.reviewing.get(taskId2);
24261
24947
  if (!current2)
24262
24948
  throw new ContractError("unavailable");
24263
24949
  return current2(published);
@@ -24384,11 +25070,11 @@ class TaskActions {
24384
25070
  if (canonicalJson(choice.selection) !== canonicalJson(version.model) || choice.configRev !== version.configRev || choice.checkEnvGeneration !== version.checkEnvGeneration)
24385
25071
  throw new ContractError("stale");
24386
25072
  }
24387
- savedGraph(taskId, snapshot = this.options.host.writer.committedSeq) {
24388
- const h = this.options.host, saved = h.coordination.store.loadSnapshot(taskId);
25073
+ savedGraph(taskId2, snapshot = this.options.host.writer.committedSeq) {
25074
+ const h = this.options.host, saved = h.coordination.store.loadSnapshot(taskId2);
24389
25075
  if (!saved)
24390
25076
  throw new ContractError("stale");
24391
- return h.reader.publishedPlan(taskId, snapshot, {
25077
+ return h.reader.publishedPlan(taskId2, snapshot, {
24392
25078
  identity: saved.identity,
24393
25079
  revision: saved.record.revision,
24394
25080
  plan: saved.record.plan
@@ -24428,8 +25114,8 @@ class TaskActions {
24428
25114
  this.drafts.set(record2.id, { identity: identity2, graph });
24429
25115
  return graph;
24430
25116
  }
24431
- checks(taskId) {
24432
- if (!this.options.host.coordination.store.loadSnapshot(taskId))
25117
+ checks(taskId2) {
25118
+ if (!this.options.host.coordination.store.loadSnapshot(taskId2))
24433
25119
  throw new ContractError("stale");
24434
25120
  const selections = this.configuredChecks();
24435
25121
  const identity2 = canonicalJson(selections);
@@ -24464,12 +25150,12 @@ class TaskActions {
24464
25150
  ...h.models.redactionLiterals(selection)
24465
25151
  ];
24466
25152
  }
24467
- observeCurrent(taskId, snapshot, legacyStart = false) {
25153
+ observeCurrent(taskId2, snapshot, legacyStart = false) {
24468
25154
  this.alive();
24469
25155
  const h = this.options.host, choice = this.choiceSnapshot();
24470
25156
  const access = this.currentAccess();
24471
25157
  const committedSeq = snapshot ?? h.writer.committedSeq;
24472
- const selected2 = taskId ? h.coordination.store.loadSnapshot(taskId) : null;
25158
+ const selected2 = taskId2 ? h.coordination.store.loadSnapshot(taskId2) : null;
24473
25159
  if (selected2 && realpathSync6(selected2.record.cwd) !== this.cwd)
24474
25160
  throw new ContractError("unsupported-context");
24475
25161
  const secrets = this.viewSecrets();
@@ -24482,7 +25168,7 @@ class TaskActions {
24482
25168
  const plan = selected2 ? sanitizeText(selected2.record.plan, secrets) : null;
24483
25169
  const editable = selected2 ? plan === selected2.record.plan : true;
24484
25170
  let descriptor = null;
24485
- let unavailable2 = taskId && !selected2 ? publicError("unavailable") : null;
25171
+ let unavailable2 = taskId2 && !selected2 ? publicError("unavailable") : null;
24486
25172
  let saved = { status: "none" };
24487
25173
  if (selected2) {
24488
25174
  try {
@@ -24519,7 +25205,7 @@ class TaskActions {
24519
25205
  version: {
24520
25206
  ...access,
24521
25207
  configRev: choice.configRev,
24522
- controlRev: h.writer.controlRevision(taskId),
25208
+ controlRev: h.writer.controlRevision(taskId2),
24523
25209
  workspaceId: h.reader.files.format.workspaceId,
24524
25210
  cwdId: this.cwdId,
24525
25211
  model: choice.selection,
@@ -24541,11 +25227,11 @@ class TaskActions {
24541
25227
  } : {
24542
25228
  status: "unavailable",
24543
25229
  workspaceId: h.reader.files.format.workspaceId,
24544
- taskId,
25230
+ taskId: taskId2,
24545
25231
  error: unavailable2 ?? publicError("unavailable")
24546
25232
  };
24547
25233
  const view = decodeCurrentView({
24548
- request: { storeId: h.reader.storeId, taskId },
25234
+ request: { storeId: h.reader.storeId, taskId: taskId2 },
24549
25235
  workspaceId: h.reader.files.format.workspaceId,
24550
25236
  epoch: access.epoch,
24551
25237
  committedSeq,
@@ -24576,8 +25262,8 @@ class TaskActions {
24576
25262
  throw new ContractError("stale");
24577
25263
  if (choice.selection)
24578
25264
  h.models.assertCurrent(choice.selection);
24579
- const latest = taskId ? h.coordination.store.loadSnapshot(taskId) : null;
24580
- if (latest?.identity !== selected2?.identity || canonicalJson(choice) !== canonicalJson(this.choiceSnapshot()) || canonicalJson(access) !== canonicalJson(this.currentAccess()) || context.status === "available" && (h.writer.controlRevision(taskId) !== context.version.controlRev || this.generation !== context.version.checkoutGeneration))
25265
+ const latest = taskId2 ? h.coordination.store.loadSnapshot(taskId2) : null;
25266
+ if (latest?.identity !== selected2?.identity || canonicalJson(choice) !== canonicalJson(this.choiceSnapshot()) || canonicalJson(access) !== canonicalJson(this.currentAccess()) || context.status === "available" && (h.writer.controlRevision(taskId2) !== context.version.controlRev || this.generation !== context.version.checkoutGeneration))
24581
25267
  throw new ContractError("stale");
24582
25268
  };
24583
25269
  assertCurrent();
@@ -24663,8 +25349,8 @@ class TaskActions {
24663
25349
  }
24664
25350
  return decodeActiveRuns({ ...base, status: "complete", runs });
24665
25351
  }
24666
- context(taskId) {
24667
- return this.current({ storeId: this.options.host.reader.storeId, taskId }).context;
25352
+ context(taskId2) {
25353
+ return this.current({ storeId: this.options.host.reader.storeId, taskId: taskId2 }).context;
24668
25354
  }
24669
25355
  workspace() {
24670
25356
  const { view, secrets } = this.observeCurrent(null);
@@ -24675,11 +25361,11 @@ class TaskActions {
24675
25361
  activeRuns: this.activeRuns()
24676
25362
  };
24677
25363
  }
24678
- checkObligations(taskId) {
24679
- const { view, assertCurrent } = this.observeCurrent(taskId);
25364
+ checkObligations(taskId2) {
25365
+ const { view, assertCurrent } = this.observeCurrent(taskId2);
24680
25366
  if (!view.task)
24681
25367
  throw new ContractError("unavailable");
24682
- const checks = this.obligationsFor(taskId, view.task.kind, view.context, view.committedSeq).checks;
25368
+ const checks = this.obligationsFor(taskId2, view.task.kind, view.context, view.committedSeq).checks;
24683
25369
  assertCurrent();
24684
25370
  return checks;
24685
25371
  }
@@ -24688,41 +25374,41 @@ class TaskActions {
24688
25374
  throw new ContractError("stale");
24689
25375
  return this.obligationsFor(version.task.id, version.task.kind, { status: "available", version }, snapshot, reads);
24690
25376
  }
24691
- obligationsFor(taskId, kind, context, snapshot, reads) {
24692
- const configured = this.checks(taskId);
25377
+ obligationsFor(taskId2, kind, context, snapshot, reads) {
25378
+ const configured = this.checks(taskId2);
24693
25379
  const selections = kind === "code" ? configured : { revision: configured.revision, selections: [] };
24694
- const fold = () => currentChecks(this.options.host.reader.files, taskId, selections, context, snapshot);
24695
- const state = reads ? reads(`checks:${canonicalJson({ taskId, selections, context, snapshot })}`, fold) : fold();
24696
- if (canonicalJson(configured) !== canonicalJson(this.checks(taskId)))
25380
+ const fold = () => currentChecks(this.options.host.reader.files, taskId2, selections, context, snapshot);
25381
+ const state = reads ? reads(`checks:${canonicalJson({ taskId: taskId2, selections, context, snapshot })}`, fold) : fold();
25382
+ if (canonicalJson(configured) !== canonicalJson(this.checks(taskId2)))
24697
25383
  throw new ContractError("stale");
24698
25384
  if (context.status !== "available")
24699
25385
  return {
24700
25386
  ...state,
24701
25387
  checks: {
24702
25388
  ...state.checks,
24703
- revision: this.reviewVersions.get(taskId)?.revision ?? configured.revision
25389
+ revision: this.reviewVersions.get(taskId2)?.revision ?? configured.revision
24704
25390
  }
24705
25391
  };
24706
25392
  const signature = canonicalJson({ configured, ...state });
24707
- let prior = this.reviewVersions.get(taskId);
25393
+ let prior = this.reviewVersions.get(taskId2);
24708
25394
  if (!prior || prior.signature !== signature) {
24709
25395
  if (this.reviewVersions.size >= 16 && !prior)
24710
25396
  this.reviewVersions.delete(this.reviewVersions.keys().next().value ?? "");
24711
25397
  if (!Number.isSafeInteger(this.reviewRevision + 1))
24712
25398
  throw new ContractError("capacity");
24713
25399
  prior = { signature, revision: ++this.reviewRevision };
24714
- this.reviewVersions.set(taskId, prior);
25400
+ this.reviewVersions.set(taskId2, prior);
24715
25401
  }
24716
25402
  return { ...state, checks: { ...state.checks, revision: prior.revision } };
24717
25403
  }
24718
25404
  async observe(action) {
24719
25405
  const h = this.options.host;
24720
- const taskId = action.kind === "create" ? null : action.taskId;
24721
- if (this.metadata.size >= 16 || this.metadata.has(taskId ?? "workspace"))
25406
+ const taskId2 = action.kind === "create" ? null : action.taskId;
25407
+ if (this.metadata.size >= 16 || this.metadata.has(taskId2 ?? "workspace"))
24722
25408
  throw new ContractError("conflict");
24723
25409
  const pending = this.committed;
24724
25410
  const ownAcceptance = pending?.intent.identity.kind === "action" && canonicalJson(pending.intent.identity.action) === canonicalJson(action);
24725
- const current2 = this.observeCurrent(taskId, ownAcceptance ? pending.previousSeq : undefined, action.kind === "start");
25411
+ const current2 = this.observeCurrent(taskId2, ownAcceptance ? pending.previousSeq : undefined, action.kind === "start");
24726
25412
  const { selected: selected2, graph, changes } = current2;
24727
25413
  if (current2.view.context.status !== "available")
24728
25414
  throw new ContractError(current2.view.context.error.code);
@@ -24759,7 +25445,7 @@ class TaskActions {
24759
25445
  for (const assignment of graph.assignments)
24760
25446
  this.sources.request(selected2.record, graph, randomUUID18(), randomUUID18(), assignment, { graphRevision: graph.revision, inputs: [] });
24761
25447
  }
24762
- const checks = taskId ? this.checks(taskId).selections : this.configuredChecks();
25448
+ const checks = taskId2 ? this.checks(taskId2).selections : this.configuredChecks();
24763
25449
  if (sanitizeText(canonicalJson(checks), current2.secrets) !== canonicalJson(checks))
24764
25450
  throw new ContractError("unsupported-context");
24765
25451
  const review = action.kind === "review" ? this.reviewObservation(action.runId, version) : null;
@@ -24770,14 +25456,14 @@ class TaskActions {
24770
25456
  cwdLabel: diagnosticText(sanitizeText(this.cwd, current2.secrets), 4096),
24771
25457
  readablePlan: action.kind === "save-plan" ? action.plan : review?.readablePlan ?? selected2?.record.plan ?? "",
24772
25458
  graph: action.kind === "save-plan" ? action.graph : action.kind === "generate-plan" ? null : review ? review.graph : graph,
24773
- activeRunId: taskId ? this.scheduler.activeTask(taskId) : null,
25459
+ activeRunId: taskId2 ? this.scheduler.activeTask(taskId2) : null,
24774
25460
  issues: review?.issues ?? (changes.complete ? [] : ["incomplete-observation"]),
24775
25461
  configuredChecks: checks,
24776
25462
  ...action.kind === "check" ? { checkEnvironmentPolicy: "service-launch-ordinary/1" } : {},
24777
- checksRevision: review?.checks.revision ?? (taskId && this.options.choice ? this.obligations(version, current2.view.committedSeq).checks.revision : taskId ? this.checks(taskId).revision : 0),
25463
+ checksRevision: review?.checks.revision ?? (taskId2 && this.options.choice ? this.obligations(version, current2.view.committedSeq).checks.revision : taskId2 ? this.checks(taskId2).revision : 0),
24778
25464
  reviewRunId: action.kind === "review" ? action.runId : null
24779
25465
  });
24780
- const latestChecks = taskId ? this.checks(taskId).selections : this.configuredChecks();
25466
+ const latestChecks = taskId2 ? this.checks(taskId2).selections : this.configuredChecks();
24781
25467
  if (canonicalJson(checks) !== canonicalJson(latestChecks))
24782
25468
  throw new ContractError("stale");
24783
25469
  current2.assertCurrent();
@@ -24935,9 +25621,9 @@ class TaskActions {
24935
25621
  reviewObservation(runId, version, snapshot = this.options.host.writer.committedSeq, reads) {
24936
25622
  if (!version.task)
24937
25623
  throw new ContractError("stale");
24938
- const h = this.options.host, taskId = version.task.id;
24939
- const select = () => h.reader.reviewSelection(taskId, runId, snapshot);
24940
- const selection = reads ? reads(`selection:${taskId}:${runId}:${snapshot}`, select) : select();
25624
+ const h = this.options.host, taskId2 = version.task.id;
25625
+ const select = () => h.reader.reviewSelection(taskId2, runId, snapshot);
25626
+ const selection = reads ? reads(`selection:${taskId2}:${runId}:${snapshot}`, select) : select();
24941
25627
  const { run } = selection;
24942
25628
  const state = this.obligations(version, snapshot, reads);
24943
25629
  const current2 = {
@@ -25133,8 +25819,8 @@ class TaskActions {
25133
25819
  lease.reservation.release();
25134
25820
  }
25135
25821
  }
25136
- async settled(taskId) {
25137
- await this.metadata.get(taskId ?? "workspace");
25822
+ async settled(taskId2) {
25823
+ await this.metadata.get(taskId2 ?? "workspace");
25138
25824
  }
25139
25825
  requestCancel(command) {
25140
25826
  this.scheduler.cancel(command.runId);
@@ -25156,13 +25842,335 @@ class TaskActions {
25156
25842
  }
25157
25843
 
25158
25844
  // src/service/workbench.ts
25159
- import { opendirSync as opendirSync8 } from "node:fs";
25160
- import { join as join23 } from "node:path";
25845
+ import { opendirSync as opendirSync10 } from "node:fs";
25846
+ import { join as join27 } from "node:path";
25161
25847
 
25162
- // src/service/conversations.ts
25848
+ // src/service/conversation-workflow.ts
25163
25849
  import { randomUUID as randomUUID19 } from "node:crypto";
25164
- import { lstatSync as lstatSync13, opendirSync as opendirSync7, realpathSync as realpathSync7, statfsSync as statfsSync2 } from "node:fs";
25165
- import { dirname as dirname14, join as join22 } from "node:path";
25850
+ import { opendirSync as opendirSync7 } from "node:fs";
25851
+ import { dirname as dirname14, join as join23 } from "node:path";
25852
+
25853
+ // src/cadence-instructions.ts
25854
+ var CADENCE_INSTRUCTIONS = `CADENCE CONVERSATION MODE — stays enabled for this entire conversation, including after a goal completes, until the user explicitly exits.
25855
+ You are the sole user-facing coordinator. Continue normal conversation, not a task-manager UI. Do not ask the user to manage tasks, IDs, JSON, service ports, Save/Start/check menus or agent assignments.
25856
+ For each new goal: inspect relevant project evidence through cadence_research (up to two independent readonly subagents); read existing AGENTS/docs/.cadence/project.md before proposing conventions. Reuse still-current findings; do not rescan the entire repository or spawn agents merely to fill slots. Aggregate questions yourself. Investigate discoverable facts and ask focused, frequent questions only for unresolved product/technical decisions. Preserve confirmed decisions across turns. Diagnosis/research alone never imply implementation.
25857
+ Once material decisions and acceptance criteria are aligned, use cadence_plan with a readable design, explicit non-goals/decisions, exact file scopes, a finite dependency DAG, real verification commands, worktree prerequisites and a bounded repair budget. Independent writes may run concurrently; shared files need a single owner or dependency. Investigate local tool/dependency prerequisites BEFORE finalizing: isolated worktrees do not inherit ignored node_modules. Setup commands require inclusion in the final approval; never silently install/download/copy dependencies or credentials. local-merge needs an existing Git branch and commit identity; working-copy is explicit direct editing without Git mutation and is serialized.
25858
+ Present the returned complete plan and invite a single clear execution approval (the user can type 按计划实施). cadence_start binds the exact displayed plan and obtains fresh user consent; never interpret a vague acknowledgement as approval. No further confirmations are needed for the approved bounded pipeline. No push, publication, deployment, recursive delegation or scope expansion. If a material decision changes, revise the plan and seek fresh approval.
25859
+ During accepted work answer questions, report actual retained progress, and let the service execute. cadence_cancel is explicit cancellation, not navigation/exit. Never claim a worker's prose is a passing check or automatic review is human review. Failed/unknown/blocked outcomes are not success. A completed goal leaves Cadence ON and ready for the next goal; do not require /cadence again. Unrelated discussion is still ordinary conversation within this mode, not implicit permission to start another implementation. Tools operate on the host; this is not a sandbox.`;
25860
+
25861
+ // src/service/conversation-workflow.ts
25862
+ var BYTES = 384 * 1024;
25863
+
25864
+ class ConversationWorkflow {
25865
+ o;
25866
+ root;
25867
+ activeTurn = null;
25868
+ grants = new Map;
25869
+ constructor(o) {
25870
+ this.o = o;
25871
+ this.root = join23(o.coordination.directory, "conversation-workflows-v1");
25872
+ }
25873
+ path(id) {
25874
+ return join23(this.root, decodeId(id), "state.json");
25875
+ }
25876
+ read(id) {
25877
+ this.o.owner.lease.assert();
25878
+ const file = this.o.coordination.files.read(this.path(id), BYTES);
25879
+ if (!file) {
25880
+ if (this.o.conversations.controlBound(id) || this.o.coordination.files.directory(dirname14(this.path(id))))
25881
+ throw new ContractError("corrupt-selected");
25882
+ return {
25883
+ state: {
25884
+ id,
25885
+ revision: 0,
25886
+ enabled: false,
25887
+ head: null,
25888
+ proposal: null,
25889
+ runs: []
25890
+ }
25891
+ };
25892
+ }
25893
+ const record2 = closed(parseWireJson(file.bytes.toString("utf8"), BYTES), [
25894
+ "schema",
25895
+ "state"
25896
+ ]);
25897
+ if (record2.schema !== "cadence-conversation-workflow/1")
25898
+ throw new ContractError("corrupt-selected");
25899
+ const state = decodeCadenceConversation(record2.state);
25900
+ if (!this.o.conversations.controlBound(id) || state.id !== id || state.head && !this.o.conversations.hasTurn(id, state.head))
25901
+ throw new ContractError("corrupt-selected");
25902
+ return { state, file };
25903
+ }
25904
+ save(state, file) {
25905
+ this.o.owner.lease.assert();
25906
+ if (!Number.isSafeInteger(state.revision))
25907
+ throw new ContractError("capacity");
25908
+ const body = canonicalJson({
25909
+ schema: "cadence-conversation-workflow/1",
25910
+ state: decodeCadenceConversation(state)
25911
+ }, BYTES);
25912
+ try {
25913
+ if (file)
25914
+ this.o.coordination.files.replace(this.path(state.id), file, body, BYTES);
25915
+ else
25916
+ this.o.coordination.files.create(this.path(state.id), body, BYTES);
25917
+ } catch (e) {
25918
+ this.o.owner.quarantine();
25919
+ throw e;
25920
+ }
25921
+ }
25922
+ assertRecords() {
25923
+ if (!this.o.coordination.files.directory(this.root))
25924
+ return;
25925
+ const dir = opendirSync7(this.root);
25926
+ let count2 = 0;
25927
+ try {
25928
+ for (let e = dir.readSync();e; e = dir.readSync()) {
25929
+ if (!e.isDirectory() || ++count2 > 200)
25930
+ throw new ContractError("capacity");
25931
+ this.read(decodeId(e.name));
25932
+ }
25933
+ } finally {
25934
+ dir.closeSync();
25935
+ }
25936
+ }
25937
+ state(id) {
25938
+ return this.read(id).state;
25939
+ }
25940
+ run(id) {
25941
+ const view = this.o.workflows.view(id);
25942
+ if (view.kind !== "workflow" || view.response.type !== "run")
25943
+ throw new ContractError("unavailable");
25944
+ return view.response.run;
25945
+ }
25946
+ preview(run, bytes, steps) {
25947
+ const clip = (value, maximum) => diagnosticText(value, maximum, this.o.secrets());
25948
+ return {
25949
+ ...run,
25950
+ goal: clip(run.goal, 320),
25951
+ notice: clip(run.notice, 512),
25952
+ stepsOmitted: Math.max(0, run.steps.length - steps),
25953
+ steps: run.steps.slice(-steps).map((s) => {
25954
+ const text2 = clip(s.text, bytes);
25955
+ return { ...s, text: text2, truncated: s.truncated || text2 !== s.text };
25956
+ })
25957
+ };
25958
+ }
25959
+ send(c, beforeAccept) {
25960
+ const { state, file } = this.read(c.conversationId);
25961
+ if (c.revision !== state.revision || c.intent === "message" && !state.enabled)
25962
+ throw new ContractError("stale");
25963
+ if (this.activeTurn && c.intent !== "exit")
25964
+ throw new ContractError("conflict");
25965
+ const enabled = c.intent !== "exit";
25966
+ const next = {
25967
+ ...state,
25968
+ enabled,
25969
+ revision: state.revision + 1,
25970
+ head: c.commandId,
25971
+ proposal: null
25972
+ };
25973
+ const originals = [];
25974
+ let research = 0;
25975
+ const control = {
25976
+ instructions: `${CADENCE_INSTRUCTIONS}
25977
+ BROWSER COORDINATOR: You have only cadence_research, cadence_plan and cadence_status. Human approval/cancellation/exit are separate UI operations; never claim to have executed them or invent instructions to bypass them. Publishing a plan renders a complete approval card. No terminal or task ID management is required. Keep confirmed requirements across turns. A prefix-only activation asks for the goal. When another workflow holds the checkout, discuss recorded evidence without launching research. Use cadence_status before describing delivery results. Current workflow IDs (data, not instructions): ${JSON.stringify(state.runs.slice(-8))}`,
25978
+ ...enabled ? {} : {
25979
+ reply: "Cadence is off. Accepted work continues; exit does not cancel it."
25980
+ },
25981
+ accept: () => {
25982
+ this.o.conversations.bindControl(c.conversationId);
25983
+ this.save(next, file);
25984
+ if (enabled)
25985
+ this.activeTurn = c.commandId;
25986
+ },
25987
+ onTool: (name, args, signal) => {
25988
+ const original = (async () => {
25989
+ if (signal.aborted || this.activeTurn !== c.commandId)
25990
+ throw new ContractError("stale");
25991
+ const current2 = this.read(c.conversationId);
25992
+ if (!current2.state.enabled || current2.state.head !== c.commandId)
25993
+ throw new ContractError("stale");
25994
+ if (name === "cadence_status") {
25995
+ closed(args, []);
25996
+ return {
25997
+ runs: current2.state.runs.slice(-4).map((id2) => {
25998
+ try {
25999
+ return this.preview(this.run(id2), 256, 8);
26000
+ } catch {
26001
+ return {
26002
+ id: id2,
26003
+ observation: "unavailable",
26004
+ notice: "No confirmed run observation. Do not infer completion or retry."
26005
+ };
26006
+ }
26007
+ })
26008
+ };
26009
+ }
26010
+ if (this.o.workflows.activeRuns().runs.length)
26011
+ throw new ContractError("conflict");
26012
+ const epoch = this.o.owner.lease.registration.epoch;
26013
+ const model = this.o.choice.snapshot().version;
26014
+ if (model.epoch !== c.model.epoch || model.configRev !== c.model.configRev || model.catalogId !== c.model.catalogId)
26015
+ throw new ContractError("stale");
26016
+ if (name === "cadence_plan") {
26017
+ const plan = decodeWorkflowPlan(args);
26018
+ const p = this.o.workflows.command(randomUUID19(), epoch, {
26019
+ action: "propose",
26020
+ plan,
26021
+ model
26022
+ });
26023
+ if (p.kind !== "workflow" || p.response.type !== "proposal")
26024
+ throw new ContractError("unavailable");
26025
+ this.save({
26026
+ ...current2.state,
26027
+ revision: current2.state.revision + 1,
26028
+ proposal: p.response.proposal
26029
+ }, current2.file);
26030
+ return {
26031
+ proposalId: p.response.proposal.id,
26032
+ digest: p.response.proposal.digest,
26033
+ notice: "Complete plan displayed for human approval. No execution has been authorized."
26034
+ };
26035
+ }
26036
+ if (name !== "cadence_research" || ++research > 2 || current2.state.runs.length >= 200)
26037
+ throw new ContractError("capacity");
26038
+ const a = closed(args, ["goal", "questions"]);
26039
+ const goal = text(a.goal, 8192, true), questions = list(a.questions, 2, (q) => text(q, 8192, true));
26040
+ if (!questions.length)
26041
+ throw new ContractError("invalid");
26042
+ const id = randomUUID19();
26043
+ this.save({
26044
+ ...current2.state,
26045
+ revision: current2.state.revision + 1,
26046
+ runs: [...current2.state.runs, id]
26047
+ }, current2.file);
26048
+ this.o.workflows.command(id, epoch, {
26049
+ action: "research",
26050
+ goal,
26051
+ questions,
26052
+ model
26053
+ });
26054
+ const cancel = () => {
26055
+ try {
26056
+ this.o.workflows.command(randomUUID19(), epoch, {
26057
+ action: "cancel",
26058
+ runId: id
26059
+ });
26060
+ } catch {}
26061
+ };
26062
+ signal.addEventListener("abort", cancel, { once: true });
26063
+ if (signal.aborted)
26064
+ cancel();
26065
+ try {
26066
+ await this.o.workflows.join(id);
26067
+ } finally {
26068
+ signal.removeEventListener("abort", cancel);
26069
+ }
26070
+ return this.preview(this.run(id), 4096, 2);
26071
+ })();
26072
+ originals.push(original);
26073
+ return original;
26074
+ },
26075
+ settle: async () => {
26076
+ try {
26077
+ await Promise.allSettled(originals);
26078
+ } finally {
26079
+ if (this.activeTurn === c.commandId)
26080
+ this.activeTurn = null;
26081
+ }
26082
+ }
26083
+ };
26084
+ const userText = enabled ? sanitizeText(c.text, this.o.secrets()) : "exit cadence";
26085
+ return this.o.conversations.send({
26086
+ kind: "send",
26087
+ commandId: c.commandId,
26088
+ conversationId: c.conversationId,
26089
+ head: c.head,
26090
+ text: userText,
26091
+ model: c.model
26092
+ }, control, beforeAccept);
26093
+ }
26094
+ approval(c, caller) {
26095
+ if (!caller)
26096
+ throw new ContractError("forbidden");
26097
+ const { state, file } = this.read(c.conversationId);
26098
+ const view = this.o.conversations.view(c.conversationId, null);
26099
+ if (!state.enabled || c.revision !== state.revision || !state.proposal || state.proposal.id !== c.proposalId || state.proposal.digest !== c.digest || view.kind !== "conversation" || view.summary?.head !== state.head || view.summary.status !== "completed" || this.activeTurn)
26100
+ throw new ContractError("stale");
26101
+ const epoch = this.o.owner.lease.registration.epoch;
26102
+ if (c.kind === "cadence-prepare") {
26103
+ for (const [id, g2] of this.grants)
26104
+ if (g2.expiresAt < Date.now())
26105
+ this.grants.delete(id);
26106
+ if (this.grants.size >= 16)
26107
+ throw new ContractError("capacity");
26108
+ const prepared = this.o.workflows.command(c.commandId, epoch, {
26109
+ action: "prepare",
26110
+ proposalId: c.proposalId,
26111
+ digest: c.digest
26112
+ });
26113
+ if (prepared.kind !== "workflow" || prepared.response.type !== "grant")
26114
+ throw new ContractError("unavailable");
26115
+ const g = prepared.response, grant2 = randomUUID19();
26116
+ this.grants.set(grant2, {
26117
+ caller: canonicalJson(caller),
26118
+ revision: c.revision,
26119
+ conversationId: c.conversationId,
26120
+ proposalId: c.proposalId,
26121
+ digest: c.digest,
26122
+ expiresAt: g.expiresAt,
26123
+ nativeGrant: g.grant
26124
+ });
26125
+ return {
26126
+ kind: "cadence-grant",
26127
+ commandId: c.commandId,
26128
+ grant: grant2,
26129
+ expiresAt: g.expiresAt,
26130
+ revision: c.revision,
26131
+ proposal: g.proposal
26132
+ };
26133
+ }
26134
+ const grant = this.grants.get(c.grant);
26135
+ this.grants.delete(c.grant);
26136
+ if (!grant || grant.caller !== canonicalJson(caller) || grant.expiresAt < Date.now() || grant.revision !== c.revision || grant.conversationId !== c.conversationId || grant.proposalId !== c.proposalId || grant.digest !== c.digest)
26137
+ throw new ContractError("expired-grant");
26138
+ if (state.runs.length >= 200)
26139
+ throw new ContractError("capacity");
26140
+ try {
26141
+ this.o.coordination.files.create(join23(this.root, state.id, "approvals", `${c.commandId}.json`), canonicalJson({
26142
+ commandId: c.commandId,
26143
+ conversationId: state.id,
26144
+ revision: c.revision,
26145
+ proposalId: c.proposalId,
26146
+ digest: c.digest,
26147
+ caller,
26148
+ epoch,
26149
+ at: Date.now()
26150
+ }, 16384), 16384);
26151
+ } catch (e) {
26152
+ this.o.owner.quarantine();
26153
+ throw e;
26154
+ }
26155
+ this.save({
26156
+ ...state,
26157
+ revision: state.revision + 1,
26158
+ proposal: null,
26159
+ runs: [...state.runs, c.commandId]
26160
+ }, file);
26161
+ return this.o.workflows.command(c.commandId, epoch, {
26162
+ action: "execute",
26163
+ proposalId: c.proposalId,
26164
+ digest: c.digest,
26165
+ grant: grant.nativeGrant
26166
+ });
26167
+ }
26168
+ }
26169
+
26170
+ // src/service/conversations.ts
26171
+ import { randomUUID as randomUUID20 } from "node:crypto";
26172
+ import { lstatSync as lstatSync13, opendirSync as opendirSync8, realpathSync as realpathSync7, statfsSync as statfsSync2 } from "node:fs";
26173
+ import { dirname as dirname15, join as join24 } from "node:path";
25166
26174
  var TURN_BYTES = 384 * 1024;
25167
26175
  var META_BYTES = 64 * 1024;
25168
26176
  var SESSION_LIMIT = 200;
@@ -25286,7 +26294,7 @@ class Conversations {
25286
26294
  active = new Map;
25287
26295
  constructor(o) {
25288
26296
  this.o = o;
25289
- this.root = join22(o.coordination.directory, "conversations-v1");
26297
+ this.root = join24(o.coordination.directory, "conversations-v1");
25290
26298
  this.cwd = realpathSync7(o.cwd);
25291
26299
  }
25292
26300
  currentDirectory() {
@@ -25297,13 +26305,13 @@ class Conversations {
25297
26305
  return this.o.coordination.files;
25298
26306
  }
25299
26307
  path(id, name) {
25300
- return join22(this.root, "turns", decodeId(id), name);
26308
+ return join24(this.root, "turns", decodeId(id), name);
25301
26309
  }
25302
26310
  identityPath(id) {
25303
- return join22(this.root, "identities", `${decodeId(id)}.json`);
26311
+ return join24(this.root, "identities", `${decodeId(id)}.json`);
25304
26312
  }
25305
26313
  metadataPath(id) {
25306
- return join22(this.root, "sessions", `${decodeId(id)}.json`);
26314
+ return join24(this.root, "sessions", `${decodeId(id)}.json`);
25307
26315
  }
25308
26316
  read(path, max) {
25309
26317
  const value = this.files.read(path, max);
@@ -25352,6 +26360,23 @@ class Conversations {
25352
26360
  notice: "Original work is not observed. No automatic replay."
25353
26361
  } : turn;
25354
26362
  }
26363
+ controlBound(id) {
26364
+ const path = join24(this.root, "control-links", `${decodeId(id)}.json`);
26365
+ const value = this.read(path, META_BYTES);
26366
+ if (value === undefined)
26367
+ return false;
26368
+ const record2 = closed(value, ["schema", "conversationId"]);
26369
+ if (record2.schema !== "cadence-conversation-control/1" || record2.conversationId !== id)
26370
+ throw new ContractError("corrupt-selected");
26371
+ return true;
26372
+ }
26373
+ bindControl(id) {
26374
+ if (!this.controlBound(id))
26375
+ this.write(join24(this.root, "control-links", `${decodeId(id)}.json`), { schema: "cadence-conversation-control/1", conversationId: id }, META_BYTES);
26376
+ }
26377
+ hasTurn(id, turnId) {
26378
+ return this.metadata(id)?.turns.includes(turnId) ?? false;
26379
+ }
25355
26380
  summary(meta) {
25356
26381
  const head = meta.turns.at(-1), turn = this.turn(head);
25357
26382
  const accepted2 = closed(this.read(this.path(head, "accepted.json"), META_BYTES), ["command", "at"]);
@@ -25377,13 +26402,13 @@ class Conversations {
25377
26402
  }
25378
26403
  list() {
25379
26404
  this.o.owner.lease.assert();
25380
- const dir = join22(this.root, "sessions");
26405
+ const dir = join24(this.root, "sessions");
25381
26406
  if (!this.files.directory(dir))
25382
26407
  return {
25383
26408
  kind: "conversations",
25384
26409
  entries: [...this.active.values()].map((live) => this.liveSummary(live))
25385
26410
  };
25386
- const entries = [], opened = opendirSync7(dir);
26411
+ const entries = [], opened = opendirSync8(dir);
25387
26412
  try {
25388
26413
  for (let e = opened.readSync();e; e = opened.readSync()) {
25389
26414
  if (!e.isFile() || !e.name.endsWith(".json") || entries.length >= SESSION_LIMIT)
@@ -25454,12 +26479,12 @@ class Conversations {
25454
26479
  const visit = (directory, depth) => {
25455
26480
  if (depth > 4 || !this.files.directory(directory))
25456
26481
  return;
25457
- const dir = opendirSync7(directory);
26482
+ const dir = opendirSync8(directory);
25458
26483
  try {
25459
26484
  for (let entry = dir.readSync();entry; entry = dir.readSync()) {
25460
26485
  if (++count2 > 1e4)
25461
26486
  throw new ContractError("capacity");
25462
- const path = join22(directory, entry.name);
26487
+ const path = join24(directory, entry.name);
25463
26488
  if (entry.isDirectory())
25464
26489
  visit(path, depth + 1);
25465
26490
  else if (entry.isFile())
@@ -25475,11 +26500,16 @@ class Conversations {
25475
26500
  };
25476
26501
  visit(this.root, 0);
25477
26502
  }
25478
- send(input) {
26503
+ attempted(conversationId, commandId) {
26504
+ this.o.owner.lease.assert();
26505
+ const meta = this.metadata(conversationId);
26506
+ return this.active.has(commandId) || this.files.directory(dirname15(this.path(commandId, "accepted.json"))) || !!meta?.turns.includes(commandId) || !meta && !!this.files.read(this.identityPath(conversationId), META_BYTES);
26507
+ }
26508
+ send(input, control, beforeAccept) {
25479
26509
  this.o.owner.lease.assert();
25480
26510
  const command = {
25481
26511
  ...input,
25482
- text: sanitizeText(input.text, this.o.secrets())
26512
+ text: control?.reply ? "exit cadence" : sanitizeText(input.text, this.o.secrets())
25483
26513
  };
25484
26514
  const prior = this.read(this.path(input.commandId, "accepted.json"), META_BYTES);
25485
26515
  if (prior !== undefined) {
@@ -25488,14 +26518,15 @@ class Conversations {
25488
26518
  throw new ContractError("conflict");
25489
26519
  return { kind: "accepted", commandId: input.commandId };
25490
26520
  }
25491
- if (this.files.directory(dirname14(this.path(input.commandId, "accepted.json"))))
26521
+ if (this.files.directory(dirname15(this.path(input.commandId, "accepted.json"))))
25492
26522
  throw new ContractError("corrupt-selected");
25493
26523
  if (this.o.owner.state !== "idle")
25494
26524
  throw new ContractError("quarantine");
25495
26525
  const choice = this.o.choice.snapshot();
25496
- if (!choice.selected || canonicalJson(choice.version) !== canonicalJson(input.model))
26526
+ if (!choice.selected && !control?.reply || canonicalJson(choice.version) !== canonicalJson(input.model))
25497
26527
  throw new ContractError("stale");
25498
- this.o.models.assertCurrent(choice.selected);
26528
+ if (choice.selected && !control?.reply)
26529
+ this.o.models.assertCurrent(choice.selected);
25499
26530
  if (!this.currentDirectory())
25500
26531
  throw new ContractError("stale");
25501
26532
  const beforeMeta = this.files.read(this.metadataPath(input.conversationId), META_BYTES);
@@ -25505,7 +26536,7 @@ class Conversations {
25505
26536
  throw new ContractError("corrupt-selected");
25506
26537
  if ((meta?.turns.at(-1) ?? null) !== input.head)
25507
26538
  throw new ContractError("stale");
25508
- if (meta && this.turn(input.head).status !== "completed")
26539
+ if (meta && this.turn(input.head).status !== "completed" && (!control || ["queued", "running", "unknown"].includes(this.turn(input.head).status)))
25509
26540
  throw new ContractError("conflict");
25510
26541
  if (this.active.size >= 8 || (meta?.turns.length ?? 0) >= 1000 || !meta && this.list().entries.length >= SESSION_LIMIT)
25511
26542
  throw new ContractError("capacity");
@@ -25549,7 +26580,7 @@ class Conversations {
25549
26580
  const ready2 = new Promise((resolve8) => {
25550
26581
  begin = resolve8;
25551
26582
  });
25552
- const original = ready2.then(() => this.run(command, turn, previous, previousFile, next, abort));
26583
+ const original = ready2.then(() => this.run(command, turn, previous, previousFile, next, abort, control));
25553
26584
  const live = {
25554
26585
  turn,
25555
26586
  abort,
@@ -25560,9 +26591,11 @@ class Conversations {
25560
26591
  turnFile: null,
25561
26592
  metaFile: null
25562
26593
  };
26594
+ beforeAccept?.();
25563
26595
  this.active.set(turn.id, live);
25564
26596
  this.o.owner.trackConversation(original, () => abort.abort());
25565
26597
  try {
26598
+ control?.accept();
25566
26599
  if (!meta)
25567
26600
  this.write(this.identityPath(next.id), { schema: "cadence-conversation/1", id: next.id, cwd: this.cwd }, META_BYTES);
25568
26601
  this.write(this.path(turn.id, "accepted.json"), { command, at: live.acceptedAt }, META_BYTES);
@@ -25577,29 +26610,29 @@ class Conversations {
25577
26610
  begin();
25578
26611
  return { kind: "accepted", commandId: turn.id };
25579
26612
  }
25580
- origin(taskId) {
26613
+ origin(taskId2) {
25581
26614
  this.o.owner.lease.assert();
25582
- const value = this.read(join22(this.root, "task-links", `${decodeId(taskId)}.json`), META_BYTES);
26615
+ const value = this.read(join24(this.root, "task-links", `${decodeId(taskId2)}.json`), META_BYTES);
25583
26616
  if (value === undefined)
25584
- return { kind: "task-origin", taskId, conversationId: null };
26617
+ return { kind: "task-origin", taskId: taskId2, conversationId: null };
25585
26618
  const row = closed(value, ["conversationId"]);
25586
26619
  return {
25587
26620
  kind: "task-origin",
25588
- taskId,
26621
+ taskId: taskId2,
25589
26622
  conversationId: decodeId(row.conversationId)
25590
26623
  };
25591
26624
  }
25592
- link(taskId, conversationId, epoch) {
26625
+ link(taskId2, conversationId, epoch) {
25593
26626
  this.o.owner.lease.assert();
25594
26627
  if (epoch !== this.o.owner.lease.registration.epoch || this.o.owner.state !== "idle")
25595
26628
  throw new ContractError("stale");
25596
- if (!this.metadata(conversationId) || !this.o.coordination.store.load(taskId))
26629
+ if (!this.metadata(conversationId) || !this.o.coordination.store.load(taskId2))
25597
26630
  throw new ContractError("unavailable");
25598
- const existing = this.origin(taskId).conversationId;
26631
+ const existing = this.origin(taskId2).conversationId;
25599
26632
  if (existing !== null && existing !== conversationId)
25600
26633
  throw new ContractError("conflict");
25601
26634
  if (existing === null)
25602
- this.write(join22(this.root, "task-links", `${decodeId(taskId)}.json`), { conversationId }, META_BYTES);
26635
+ this.write(join24(this.root, "task-links", `${decodeId(taskId2)}.json`), { conversationId }, META_BYTES);
25603
26636
  }
25604
26637
  interrupt(id, turnId, epoch) {
25605
26638
  this.o.owner.lease.assert();
@@ -25617,7 +26650,7 @@ class Conversations {
25617
26650
  throw new ContractError("stale");
25618
26651
  this.active.get(turnId)?.abort.abort();
25619
26652
  }
25620
- async run(command, turn, previous, previousFile, meta, abort) {
26653
+ async run(command, turn, previous, previousFile, meta, abort, control) {
25621
26654
  let barrier;
25622
26655
  let authSettled;
25623
26656
  let uncertain = false;
@@ -25653,9 +26686,16 @@ class Conversations {
25653
26686
  try {
25654
26687
  if (!current2())
25655
26688
  throw new ContractError("stale");
25656
- barrier = await this.o.actions.scheduler.conversationBarrier(turn.id, abort.signal);
25657
- barrier.assertHeld();
25658
- this.o.actions.conversationBoundary(barrier);
26689
+ if (control?.reply) {
26690
+ turn.status = "completed";
26691
+ turn.notice = control.reply;
26692
+ return { status: "settled" };
26693
+ }
26694
+ if (!control) {
26695
+ barrier = await this.o.actions.scheduler.conversationBarrier(turn.id, abort.signal);
26696
+ barrier.assertHeld();
26697
+ this.o.actions.conversationBoundary(barrier);
26698
+ }
25659
26699
  if (!current2())
25660
26700
  throw new ContractError("stale");
25661
26701
  const choice = this.o.choice.snapshot(), selected2 = choice.selected;
@@ -25664,24 +26704,24 @@ class Conversations {
25664
26704
  const request3 = decodeWorkerPublicRequest({
25665
26705
  protocol: 2,
25666
26706
  taskId: meta.id,
25667
- taskKind: "code",
26707
+ taskKind: control ? "research" : "code",
25668
26708
  runId: turn.id,
25669
- childRunId: randomUUID19(),
26709
+ childRunId: randomUUID20(),
25670
26710
  assignmentId: "conversation",
25671
- purpose: "edit",
26711
+ purpose: control ? "research" : "edit",
25672
26712
  model: selected2,
25673
26713
  role: {
25674
- role: "implementation-worker",
25675
- sha256: hash2("Ordinary conversation.")
26714
+ role: control ? "design-explorer" : "implementation-worker",
26715
+ sha256: hash2(control?.instructions ?? "Ordinary conversation.")
25676
26716
  },
25677
26717
  context: "",
25678
- instructions: "Ordinary conversation.",
26718
+ instructions: control?.instructions ?? "Ordinary conversation.",
25679
26719
  prompt: command.text,
25680
26720
  handoff: { graphRevision: 1, inputs: [] }
25681
26721
  });
25682
26722
  const auth = this.o.models.prepareTracked({
25683
26723
  request: request3,
25684
- operationId: randomUUID19(),
26724
+ operationId: randomUUID20(),
25685
26725
  epoch: turn.epoch,
25686
26726
  timeoutMs: this.o.timeoutMs ?? LIMITS.workerMs,
25687
26727
  signal: abort.signal,
@@ -25706,10 +26746,12 @@ class Conversations {
25706
26746
  ]);
25707
26747
  const running = Promise.resolve().then(() => launchConversation(prepared.prepared, {
25708
26748
  previous,
25709
- agentDir: this.o.agentDir
26749
+ agentDir: this.o.agentDir,
26750
+ ...control ? { coordinator: true } : {}
25710
26751
  }, abort.signal, {
25711
26752
  timeoutMs: this.o.timeoutMs ?? LIMITS.workerMs,
25712
26753
  ownerSecrets: this.o.secrets,
26754
+ onCoordinator: control?.onTool,
25713
26755
  onContext: (messages) => {
25714
26756
  checkpoint = messages;
25715
26757
  },
@@ -25748,6 +26790,7 @@ class Conversations {
25748
26790
  turn.status = uncertain ? "unknown" : abort.signal.aborted ? "canceled" : "failed";
25749
26791
  turn.notice ||= error2 instanceof ContractError ? error2.code : "Conversation failed.";
25750
26792
  } finally {
26793
+ await control?.settle();
25751
26794
  await authSettled;
25752
26795
  uncertain ||= this.o.owner.state === "quarantined";
25753
26796
  if (uncertain)
@@ -25759,7 +26802,7 @@ class Conversations {
25759
26802
  if (turn.status !== "completed")
25760
26803
  turn.notice = [
25761
26804
  turn.notice,
25762
- "Start a new conversation; incomplete context is not replayed."
26805
+ control ? "Incomplete work is not replayed. A new explicit message may continue from the last complete checkpoint." : "Start a new conversation; incomplete context is not replayed."
25763
26806
  ].filter(Boolean).join(`
25764
26807
  `);
25765
26808
  save();
@@ -25776,29 +26819,1085 @@ class Conversations {
25776
26819
  }
25777
26820
  }
25778
26821
 
26822
+ // src/service/workflows.ts
26823
+ import { randomUUID as randomUUID21 } from "node:crypto";
26824
+ import {
26825
+ lstatSync as lstatSync15,
26826
+ opendirSync as opendirSync9,
26827
+ realpathSync as realpathSync8,
26828
+ statfsSync as statfsSync3,
26829
+ writeFileSync as writeFileSync3
26830
+ } from "node:fs";
26831
+ import { dirname as dirname17, join as join26 } from "node:path";
26832
+
26833
+ // src/service/workflow-git.ts
26834
+ import { spawnSync as spawnSync3 } from "node:child_process";
26835
+ import { lstatSync as lstatSync14, readFileSync as readFileSync2 } from "node:fs";
26836
+ import { dirname as dirname16, join as join25, relative as relative8, resolve as resolve8 } from "node:path";
26837
+ function gitRead(cwd, args) {
26838
+ const r = spawnSync3("git", gitArguments(args), {
26839
+ cwd,
26840
+ env: gitEnvironment(),
26841
+ encoding: "utf8",
26842
+ timeout: 1e4,
26843
+ maxBuffer: 16 * 1024 * 1024,
26844
+ windowsHide: true
26845
+ });
26846
+ if (r.error || r.status !== 0)
26847
+ throw new ContractError("unavailable");
26848
+ return r.stdout;
26849
+ }
26850
+ function safeWorkflowFile(cwd, name) {
26851
+ workflowPath(name);
26852
+ const p = resolve8(cwd, name);
26853
+ if (relative8(cwd, p).startsWith(".."))
26854
+ throw new ContractError("forbidden");
26855
+ safeDirectory(dirname16(p));
26856
+ try {
26857
+ const st = lstatSync14(p);
26858
+ if (!st.isFile() || st.isSymbolicLink() || st.nlink !== 1)
26859
+ throw new ContractError("forbidden");
26860
+ } catch (e) {
26861
+ if (!(e instanceof Error && ("code" in e) && e.code === "ENOENT"))
26862
+ throw e;
26863
+ }
26864
+ return p;
26865
+ }
26866
+ function workflowChanged(cwd) {
26867
+ return [
26868
+ ...new Set([
26869
+ ...gitRead(cwd, [
26870
+ "diff",
26871
+ "--name-only",
26872
+ "-z",
26873
+ "--no-renames",
26874
+ "--no-ext-diff",
26875
+ "--no-textconv",
26876
+ "HEAD",
26877
+ "--"
26878
+ ]).split("\x00").filter(Boolean),
26879
+ ...gitRead(cwd, [
26880
+ "diff",
26881
+ "--cached",
26882
+ "--name-only",
26883
+ "-z",
26884
+ "--no-renames",
26885
+ "--no-ext-diff",
26886
+ "--no-textconv",
26887
+ "HEAD",
26888
+ "--"
26889
+ ]).split("\x00").filter(Boolean),
26890
+ ...gitRead(cwd, ["ls-files", "--others", "--exclude-standard", "-z"]).split("\x00").filter(Boolean)
26891
+ ])
26892
+ ];
26893
+ }
26894
+ function assertWorkflowScope(cwd, allowed) {
26895
+ const changes = workflowChanged(cwd);
26896
+ for (const name of changes) {
26897
+ if (!allowed.includes(name))
26898
+ throw new ContractError("forbidden");
26899
+ safeWorkflowFile(cwd, name);
26900
+ }
26901
+ return changes;
26902
+ }
26903
+ function assertWorkflowCommit(cwd, before, commit, allowed) {
26904
+ if (gitRead(cwd, ["show", "-s", "--format=%P", commit]).trim() !== before)
26905
+ throw new ContractError("stale");
26906
+ const names2 = gitRead(cwd, [
26907
+ "diff",
26908
+ "--name-only",
26909
+ "-z",
26910
+ "--no-renames",
26911
+ "--no-ext-diff",
26912
+ "--no-textconv",
26913
+ before,
26914
+ commit,
26915
+ "--"
26916
+ ]).split("\x00").filter(Boolean);
26917
+ for (const name of names2) {
26918
+ if (!allowed.includes(name))
26919
+ throw new ContractError("forbidden");
26920
+ safeWorkflowFile(cwd, name);
26921
+ }
26922
+ }
26923
+ function workflowObservation(cwd, plan) {
26924
+ const paths = [
26925
+ ...new Set([
26926
+ ".cadence/project.md",
26927
+ "AGENTS.md",
26928
+ ...plan?.tasks.flatMap((t) => t.writes) ?? []
26929
+ ])
26930
+ ];
26931
+ const contents = paths.map((p) => {
26932
+ const file = safeWorkflowFile(cwd, p);
26933
+ const bytes = readBounded(file, 1024 * 1024);
26934
+ return [p, bytes ? hash2(bytes) : null];
26935
+ });
26936
+ if (plan?.delivery === "working-copy") {
26937
+ return { identity: hash2(JSON.stringify(contents)), head: "", branch: "" };
26938
+ }
26939
+ const head = gitRead(cwd, ["rev-parse", "--verify", "HEAD"]).trim();
26940
+ const branch = gitRead(cwd, ["symbolic-ref", "HEAD"]).trim();
26941
+ if (!/^refs\/heads\//u.test(branch) || !/^[a-f0-9]{40,64}$/u.test(head))
26942
+ throw new ContractError("invalid");
26943
+ if (plan) {
26944
+ const dirty = workflowChanged(cwd);
26945
+ if (dirty.some((p) => paths.some((q) => p === q || p.startsWith(`${q}/`) || q.startsWith(`${p}/`))))
26946
+ throw new ContractError("conflict");
26947
+ gitRead(cwd, ["var", "GIT_AUTHOR_IDENT"]);
26948
+ gitRead(cwd, ["var", "GIT_COMMITTER_IDENT"]);
26949
+ }
26950
+ return {
26951
+ head,
26952
+ branch,
26953
+ identity: hash2(JSON.stringify({
26954
+ head,
26955
+ branch,
26956
+ contents,
26957
+ status: gitRead(cwd, ["status", "--porcelain=v1", "-uall"]),
26958
+ index: gitRead(cwd, [
26959
+ "diff",
26960
+ "--cached",
26961
+ "--binary",
26962
+ "--no-ext-diff",
26963
+ "--no-textconv"
26964
+ ]),
26965
+ worktree: gitRead(cwd, [
26966
+ "diff",
26967
+ "--binary",
26968
+ "--no-ext-diff",
26969
+ "--no-textconv"
26970
+ ])
26971
+ }))
26972
+ };
26973
+ }
26974
+ function projectMarkdown(cwd, context) {
26975
+ const file = safeWorkflowFile(cwd, ".cadence/project.md");
26976
+ const previous = readBounded(file, 128 * 1024)?.toString("utf8") ?? `# Cadence project context
26977
+ `;
26978
+ const start = "<!-- CADENCE:PROJECT:START -->", end = "<!-- CADENCE:PROJECT:END -->";
26979
+ if (previous.split(start).length !== previous.split(end).length || previous.split(start).length > 2)
26980
+ throw new ContractError("conflict");
26981
+ const block = `${start}
26982
+ ${context}
26983
+ ${end}`;
26984
+ if (!previous.includes(start))
26985
+ return `${previous.trimEnd()}
26986
+
26987
+ ${block}
26988
+ `;
26989
+ if (previous.indexOf(end) < previous.indexOf(start))
26990
+ throw new ContractError("conflict");
26991
+ return previous.slice(0, previous.indexOf(start)) + block + previous.slice(previous.indexOf(end) + end.length);
26992
+ }
26993
+ function assertWorktree(root, cwd) {
26994
+ if (!safeDirectory(cwd) || resolve8(gitRead(cwd, ["rev-parse", "--show-toplevel"]).trim()) !== resolve8(cwd))
26995
+ throw new ContractError("stale");
26996
+ const common = (p) => resolve8(p, gitRead(p, ["rev-parse", "--git-common-dir"]).trim());
26997
+ if (common(root) !== common(cwd))
26998
+ throw new ContractError("stale");
26999
+ const marker2 = join25(cwd, ".git");
27000
+ if (!lstatSync14(marker2).isFile() || !readFileSync2(marker2, "utf8").startsWith("gitdir: "))
27001
+ throw new ContractError("stale");
27002
+ }
27003
+
27004
+ // src/service/workflows.ts
27005
+ var RECORD_BYTES2 = 384 * 1024;
27006
+
27007
+ class WorkflowFailure extends Error {
27008
+ outcome;
27009
+ constructor(outcome, message) {
27010
+ super(message);
27011
+ this.outcome = outcome;
27012
+ }
27013
+ }
27014
+
27015
+ class Workflows {
27016
+ o;
27017
+ root;
27018
+ cwd;
27019
+ active = new Map;
27020
+ grants = new Map;
27021
+ constructor(o) {
27022
+ this.o = o;
27023
+ this.root = join26(o.coordination.directory, "workflows-v1");
27024
+ this.cwd = realpathSync8(o.coordination.store.root);
27025
+ const runs = join26(this.root, "runs");
27026
+ if (this.files.directory(runs)) {
27027
+ const dir = opendirSync9(runs);
27028
+ try {
27029
+ let count2 = 0;
27030
+ for (let e = dir.readSync();e; e = dir.readSync()) {
27031
+ if (++count2 > WORKFLOW_LIMITS.runs || !e.isDirectory())
27032
+ throw new ContractError("capacity");
27033
+ const id = decodeId(e.name);
27034
+ const state = this.files.read(this.path(id, "state.json"), RECORD_BYTES2);
27035
+ if (!state)
27036
+ throw new ContractError("quarantine");
27037
+ const run = decodeWorkflowRun(parseWireJson(state.bytes.toString("utf8"), RECORD_BYTES2));
27038
+ if (["queued", "running", "unknown"].includes(run.status))
27039
+ throw new ContractError("quarantine");
27040
+ }
27041
+ } finally {
27042
+ dir.closeSync();
27043
+ }
27044
+ }
27045
+ }
27046
+ get files() {
27047
+ return this.o.coordination.files;
27048
+ }
27049
+ path(id, name) {
27050
+ return join26(this.root, "runs", decodeId(id), name);
27051
+ }
27052
+ write(path, value, expected, max = RECORD_BYTES2) {
27053
+ this.o.owner.lease.assert();
27054
+ const body = canonicalJson(value, max);
27055
+ try {
27056
+ return expected ? this.files.replace(path, expected, body, max) : this.files.create(path, body, max);
27057
+ } catch (e) {
27058
+ this.o.owner.quarantine();
27059
+ throw e;
27060
+ }
27061
+ }
27062
+ current() {
27063
+ this.o.owner.lease.assert();
27064
+ if (this.o.owner.state !== "idle" || resolveWorkspace(this.o.cwd).root !== this.cwd)
27065
+ throw new ContractError("quarantine");
27066
+ }
27067
+ model(version, admitted = false) {
27068
+ const state = this.o.choice.snapshot();
27069
+ if (!state.selected || (admitted ? state.version.epoch !== version.epoch || state.version.configRev !== version.configRev || state.version.catalogId !== version.catalogId : canonicalJson(state.version) !== canonicalJson(version)))
27070
+ throw new ContractError("stale");
27071
+ this.o.models.assertCurrent(state.selected);
27072
+ return state.selected;
27073
+ }
27074
+ observation(plan, source = workflowObservation(this.cwd, plan)) {
27075
+ return hash2(canonicalJson({
27076
+ source,
27077
+ working: plan.delivery === "working-copy" ? captureChanges(this.cwd).fingerprint : null
27078
+ }));
27079
+ }
27080
+ proposal(id) {
27081
+ const file = this.files.read(join26(this.root, "proposals", `${decodeId(id)}.json`), RECORD_BYTES2);
27082
+ if (!file)
27083
+ throw new ContractError("unavailable");
27084
+ return decodeWorkflowProposal(parseWireJson(file.bytes.toString("utf8"), RECORD_BYTES2));
27085
+ }
27086
+ assertProposal(p, digest, admitted = false) {
27087
+ this.current();
27088
+ this.model(p.model, admitted);
27089
+ if (p.epoch !== this.o.owner.lease.registration.epoch || p.digest !== digest || p.cwd !== this.cwd || this.observation(p.plan) !== p.observation)
27090
+ throw new ContractError("stale");
27091
+ }
27092
+ activeRuns() {
27093
+ this.o.owner.lease.assert();
27094
+ return {
27095
+ kind: "workflow-active",
27096
+ runs: [...this.active.values()].map(({ run }) => ({
27097
+ ...structuredClone(run),
27098
+ goal: run.goal.slice(0, 320),
27099
+ steps: []
27100
+ }))
27101
+ };
27102
+ }
27103
+ async join(id) {
27104
+ await this.active.get(id)?.original;
27105
+ }
27106
+ view(id) {
27107
+ this.o.owner.lease.assert();
27108
+ const live = this.active.get(id);
27109
+ const file = live ? undefined : this.files.read(this.path(id, "state.json"), RECORD_BYTES2);
27110
+ if (!live && !file)
27111
+ throw new ContractError("unavailable");
27112
+ const run = decodeWorkflowRun(live ? live.run : parseWireJson(file ? file.bytes.toString("utf8") : "null", RECORD_BYTES2));
27113
+ if (!live && ["running", "queued"].includes(run.status))
27114
+ run.status = "unknown";
27115
+ return {
27116
+ kind: "workflow",
27117
+ commandId: null,
27118
+ response: { type: "run", run }
27119
+ };
27120
+ }
27121
+ transcript(id, stepId) {
27122
+ const view = this.view(id);
27123
+ if (view.kind !== "workflow" || view.response.type !== "run")
27124
+ throw new ContractError("unavailable");
27125
+ const run = view.response.run, step = run.steps.find((s) => s.id === stepId);
27126
+ if (!step?.childRunId)
27127
+ throw new ContractError("unavailable");
27128
+ const file = this.files.read(this.path(id, `transcripts/${step.childRunId}.json`), RECORD_BYTES2);
27129
+ const turn = file ? decodeChatTurn(parseWireJson(file.bytes.toString("utf8"), RECORD_BYTES2)) : null;
27130
+ if (turn && (turn.id !== step.childRunId || turn.epoch !== run.epoch))
27131
+ throw new ContractError("corrupt-selected");
27132
+ if (turn && turn.status === "running" && step.status !== "running") {
27133
+ turn.status = "unknown";
27134
+ turn.notice = "Retained transcript is incomplete; original activity is not inferred.";
27135
+ }
27136
+ return { kind: "workflow-transcript", runId: id, stepId, turn };
27137
+ }
27138
+ detail(id, stepId) {
27139
+ const view = this.view(id);
27140
+ if (view.kind !== "workflow" || view.response.type !== "run" || !view.response.run.steps.some((s) => s.id === stepId))
27141
+ throw new ContractError("invalid");
27142
+ const file = this.files.read(this.path(id, `results/${hash2(stepId)}.json`), RECORD_BYTES2);
27143
+ if (!file)
27144
+ throw new ContractError("unavailable");
27145
+ return {
27146
+ kind: "file",
27147
+ path: `workflow/${id}/${stepId}`,
27148
+ text: sanitizeData(parseWireJson(file.bytes.toString("utf8"), RECORD_BYTES2), this.o.secrets()),
27149
+ limited: false
27150
+ };
27151
+ }
27152
+ command(commandId, epoch, r) {
27153
+ this.current();
27154
+ if (epoch !== this.o.owner.lease.registration.epoch)
27155
+ throw new ContractError("stale");
27156
+ if (r.action === "cancel") {
27157
+ const live2 = this.active.get(r.runId);
27158
+ if (live2)
27159
+ live2.abort.abort();
27160
+ const view = this.view(r.runId);
27161
+ return { ...view, commandId };
27162
+ }
27163
+ const encoded2 = canonicalJson(r, RECORD_BYTES2);
27164
+ if (sanitizeText(encoded2, this.o.secrets()) !== encoded2)
27165
+ throw new ContractError("forbidden");
27166
+ if (r.action === "propose") {
27167
+ this.model(r.model);
27168
+ this.capacity();
27169
+ const plan = decodeWorkflowPlan(r.plan);
27170
+ if (sanitizeText(canonicalJson(plan), this.o.secrets()) !== canonicalJson(plan))
27171
+ throw new ContractError("forbidden");
27172
+ const source = workflowObservation(this.cwd, plan);
27173
+ const selected2 = this.model(r.model);
27174
+ const p = {
27175
+ id: commandId,
27176
+ epoch,
27177
+ model: r.model,
27178
+ plan,
27179
+ cwd: this.cwd,
27180
+ observation: this.observation(plan, source),
27181
+ display: {
27182
+ model: `${selected2.provider}/${selected2.model} · ${selected2.thinking}`,
27183
+ branch: source.branch,
27184
+ baseCommit: source.head
27185
+ },
27186
+ digest: hash2(canonicalJson(plan))
27187
+ };
27188
+ if (sanitizeText(canonicalJson(p), this.o.secrets()) !== canonicalJson(p))
27189
+ throw new ContractError("forbidden");
27190
+ const target2 = join26(this.root, "proposals", `${commandId}.json`);
27191
+ const previous = this.files.read(target2, RECORD_BYTES2);
27192
+ if (previous) {
27193
+ if (previous.bytes.toString("utf8") !== canonicalJson(p))
27194
+ throw new ContractError("conflict");
27195
+ } else
27196
+ this.write(target2, p);
27197
+ return {
27198
+ kind: "workflow",
27199
+ commandId,
27200
+ response: { type: "proposal", proposal: p }
27201
+ };
27202
+ }
27203
+ if (r.action === "prepare") {
27204
+ const p = this.proposal(r.proposalId);
27205
+ this.assertProposal(p, r.digest);
27206
+ for (const [key2, v] of this.grants)
27207
+ if (v.expiresAt < Date.now())
27208
+ this.grants.delete(key2);
27209
+ if (this.grants.size >= 16)
27210
+ throw new ContractError("capacity");
27211
+ const grant = randomUUID21(), expiresAt = Date.now() + 120000;
27212
+ this.grants.set(grant, { proposalId: p.id, digest: p.digest, expiresAt });
27213
+ return {
27214
+ kind: "workflow",
27215
+ commandId,
27216
+ response: { type: "grant", proposal: p, grant, expiresAt }
27217
+ };
27218
+ }
27219
+ const acceptedPath = this.path(commandId, "accepted.json");
27220
+ const prior = this.files.read(acceptedPath, RECORD_BYTES2);
27221
+ if (prior) {
27222
+ if (prior.bytes.toString("utf8") !== canonicalJson({ epoch, request: r }))
27223
+ throw new ContractError("conflict");
27224
+ return { ...this.view(commandId), commandId };
27225
+ }
27226
+ if (this.files.directory(dirname17(acceptedPath)))
27227
+ throw new ContractError("quarantine");
27228
+ let proposal;
27229
+ if (r.action === "execute") {
27230
+ proposal = this.proposal(r.proposalId);
27231
+ this.assertProposal(proposal, r.digest);
27232
+ const grant = this.grants.get(r.grant);
27233
+ this.grants.delete(r.grant);
27234
+ if (!grant || grant.expiresAt < Date.now() || grant.proposalId !== proposal.id || grant.digest !== proposal.digest)
27235
+ throw new ContractError("expired-grant");
27236
+ } else
27237
+ this.model(r.model);
27238
+ this.capacity();
27239
+ if (this.active.size >= 4)
27240
+ throw new ContractError("capacity");
27241
+ const run = {
27242
+ id: commandId,
27243
+ epoch,
27244
+ goal: proposal?.plan.goal ?? (r.action === "research" ? r.goal : ""),
27245
+ status: "queued",
27246
+ phase: r.action === "research" ? "research" : "implementing",
27247
+ steps: [],
27248
+ notice: "",
27249
+ mergedCommit: null,
27250
+ humanReviewed: false
27251
+ };
27252
+ const abort = new AbortController;
27253
+ let begin;
27254
+ const ready2 = new Promise((resolve9) => {
27255
+ begin = resolve9;
27256
+ });
27257
+ const live = {
27258
+ run,
27259
+ abort,
27260
+ original: ready2.then(() => this.execute(live, r, proposal)),
27261
+ plan: proposal?.plan
27262
+ };
27263
+ this.active.set(commandId, live);
27264
+ this.o.owner.trackConversation(live.original, () => abort.abort());
27265
+ try {
27266
+ this.write(acceptedPath, { epoch, request: r });
27267
+ live.file = this.write(this.path(commandId, "state.json"), run);
27268
+ } catch (e) {
27269
+ abort.abort();
27270
+ begin();
27271
+ throw e;
27272
+ }
27273
+ begin();
27274
+ return {
27275
+ kind: "workflow",
27276
+ commandId,
27277
+ response: { type: "run", run: structuredClone(run) }
27278
+ };
27279
+ }
27280
+ capacity() {
27281
+ let bytes = 0, count2 = 0;
27282
+ const visit = (path, depth) => {
27283
+ if (depth > 5 || !this.files.directory(path))
27284
+ return;
27285
+ const dir = opendirSync9(path);
27286
+ try {
27287
+ for (let e = dir.readSync();e; e = dir.readSync()) {
27288
+ if (++count2 > 1e4)
27289
+ throw new ContractError("capacity");
27290
+ const p = join26(path, e.name);
27291
+ if (e.isDirectory())
27292
+ visit(p, depth + 1);
27293
+ else if (e.isFile())
27294
+ bytes += lstatSync15(p).size;
27295
+ else
27296
+ throw new ContractError("forbidden");
27297
+ if (bytes > 512 * 1024 * 1024)
27298
+ throw new ContractError("capacity");
27299
+ }
27300
+ } finally {
27301
+ dir.closeSync();
27302
+ }
27303
+ };
27304
+ visit(join26(this.root, "runs"), 0);
27305
+ visit(join26(this.root, "proposals"), 0);
27306
+ const runDirectory = join26(this.root, "runs");
27307
+ if (this.files.directory(runDirectory)) {
27308
+ const dir = opendirSync9(runDirectory);
27309
+ try {
27310
+ let runs = 0;
27311
+ while (dir.readSync())
27312
+ if (++runs >= WORKFLOW_LIMITS.runs)
27313
+ throw new ContractError("capacity");
27314
+ } finally {
27315
+ dir.closeSync();
27316
+ }
27317
+ }
27318
+ const space = statfsSync3(this.o.coordination.directory);
27319
+ if (space.bavail * space.bsize < LIMITS.freeSpaceFloorBytes)
27320
+ throw new ContractError("capacity");
27321
+ }
27322
+ save(live) {
27323
+ if (!live.file)
27324
+ throw new ContractError("corrupt-selected");
27325
+ live.file = this.write(this.path(live.run.id, "state.json"), live.run, live.file);
27326
+ }
27327
+ assertRunning(live) {
27328
+ this.current();
27329
+ const space = statfsSync3(this.o.coordination.directory);
27330
+ if (space.bavail * space.bsize < LIMITS.freeSpaceFloorBytes)
27331
+ throw new ContractError("capacity");
27332
+ if (live.abort.signal.aborted)
27333
+ throw new ContractError("stale");
27334
+ }
27335
+ step(live, id, kind, childRunId) {
27336
+ if (live.run.steps.length >= 256)
27337
+ throw new ContractError("capacity");
27338
+ const s = {
27339
+ id: `${id.slice(0, 80)}-${randomUUID21()}`,
27340
+ ...childRunId ? { childRunId } : {},
27341
+ kind,
27342
+ status: "running",
27343
+ text: "",
27344
+ exitCode: null,
27345
+ truncated: false
27346
+ };
27347
+ live.run.steps.push(s);
27348
+ this.save(live);
27349
+ return s;
27350
+ }
27351
+ sanitizeResult(result) {
27352
+ const secrets = this.o.secrets();
27353
+ return {
27354
+ ...result,
27355
+ text: sanitizeText(result.text, secrets),
27356
+ output: sanitizeText(result.output, secrets)
27357
+ };
27358
+ }
27359
+ finishStep(live, s, original) {
27360
+ const result = this.sanitizeResult(original);
27361
+ this.write(this.path(live.run.id, `results/${hash2(s.id)}.json`), {
27362
+ stepId: s.id,
27363
+ result
27364
+ });
27365
+ s.status = result.outcome;
27366
+ s.text = diagnosticText(result.text || result.output, s.kind === "research" ? 16384 : 1024, this.o.secrets());
27367
+ s.exitCode = result.exitCode;
27368
+ s.truncated = result.truncated || Buffer.byteLength(result.text || result.output) > Buffer.byteLength(s.text);
27369
+ if (!result.closed)
27370
+ this.o.owner.quarantine();
27371
+ this.save(live);
27372
+ }
27373
+ async worker(live, cwd, id, prompt, readonly, version) {
27374
+ this.assertRunning(live);
27375
+ const model = this.model(version, true);
27376
+ const role2 = loadAgentDefinitions().find((r) => r.role === (readonly ? "design-explorer" : "implementation-worker"));
27377
+ if (!role2)
27378
+ throw new ContractError("unavailable");
27379
+ const childRunId = randomUUID21(), op = randomUUID21();
27380
+ const request3 = decodeWorkerPublicRequest({
27381
+ protocol: 2,
27382
+ taskId: live.run.id,
27383
+ taskKind: readonly ? "research" : "code",
27384
+ runId: live.run.id,
27385
+ childRunId,
27386
+ assignmentId: id,
27387
+ purpose: readonly ? "research" : "edit",
27388
+ model,
27389
+ role: { role: role2.role, sha256: role2.sha256 },
27390
+ context: live.plan ? workflowContext(live.plan) : "Read applicable AGENTS.md and existing project documentation, including .cadence/project.md. Cite evidence and separate observations from assumptions.",
27391
+ instructions: `${role2.content}
27392
+ Read applicable AGENTS.md, existing project conventions and relevant tests before work. Do not delegate, retry, mutate Git, install dependencies, publish or deploy. Report actual work and uncertainty. Do not weaken tests to manufacture success. Worker completion is not verification.`,
27393
+ prompt: text(prompt, 32768, true),
27394
+ handoff: { graphRevision: 1, inputs: [] }
27395
+ });
27396
+ const step = this.step(live, id, readonly ? live.run.phase === "research" ? "research" : "review" : "implementation", childRunId);
27397
+ const current2 = () => {
27398
+ try {
27399
+ this.assertRunning(live);
27400
+ if (cwd !== this.cwd)
27401
+ assertWorktree(this.cwd, cwd);
27402
+ return true;
27403
+ } catch {
27404
+ return false;
27405
+ }
27406
+ };
27407
+ let native;
27408
+ let selectedMessageId;
27409
+ const auth = this.o.models.prepareTracked({
27410
+ request: request3,
27411
+ operationId: op,
27412
+ epoch: live.run.epoch,
27413
+ timeoutMs: this.o.timeoutMs ?? LIMITS.workerMs,
27414
+ signal: live.abort.signal,
27415
+ current: current2,
27416
+ journal: {
27417
+ preparation: (v) => {
27418
+ this.write(this.path(live.run.id, `auth/${op}-intent.json`), v);
27419
+ },
27420
+ settlement: (v) => {
27421
+ this.write(this.path(live.run.id, `auth/${op}-settled.json`), v);
27422
+ }
27423
+ }
27424
+ });
27425
+ try {
27426
+ const result = await auth.result;
27427
+ if (result.status !== "prepared" || !current2())
27428
+ throw new ContractError("auth-unavailable");
27429
+ this.write(this.path(live.run.id, `launches/${childRunId}.json`), {
27430
+ cwd,
27431
+ request: request3
27432
+ });
27433
+ const transcript = {
27434
+ id: childRunId,
27435
+ epoch: live.run.epoch,
27436
+ status: "running",
27437
+ items: [],
27438
+ notice: "",
27439
+ omitted: { thinking: false, media: false, other: false }
27440
+ };
27441
+ let transcriptFile;
27442
+ let credentials = [];
27443
+ const saveTranscript = () => {
27444
+ transcriptFile = this.write(this.path(live.run.id, `transcripts/${childRunId}.json`), transcript, transcriptFile);
27445
+ };
27446
+ const capture = new ConversationCapture(transcript, saveTranscript, () => [...this.o.secrets(), ...credentials]);
27447
+ const running = Promise.resolve().then(() => launchWorkflowWorker(result.prepared, cwd, live.abort.signal, {
27448
+ timeoutMs: this.o.timeoutMs ?? LIMITS.workerMs,
27449
+ ownerSecrets: this.o.secrets(),
27450
+ maySignal: () => {
27451
+ try {
27452
+ this.o.owner.lease.assert();
27453
+ return true;
27454
+ } catch {
27455
+ return false;
27456
+ }
27457
+ },
27458
+ onNative: (v, messageId) => {
27459
+ native = v;
27460
+ selectedMessageId = messageId;
27461
+ },
27462
+ onFrame: (frame, secrets) => {
27463
+ credentials = secrets;
27464
+ capture.accept(frame);
27465
+ }
27466
+ }));
27467
+ this.o.owner.trackConversationProcess(running.then(() => {
27468
+ if (!native)
27469
+ throw new ContractError("quarantine");
27470
+ return native;
27471
+ }), () => live.abort.abort());
27472
+ const completed = this.sanitizeResult(await running);
27473
+ if (completed.outcome === "completed") {
27474
+ const selected2 = transcript.items.find((item) => item.id === selectedMessageId && item.role === "assistant");
27475
+ if (!selected2)
27476
+ throw new ContractError("corrupt-selected");
27477
+ const text2 = sanitizeText(selected2.text, [
27478
+ ...this.o.secrets(),
27479
+ ...credentials
27480
+ ]);
27481
+ completed.text = diagnosticText(text2, 16384);
27482
+ completed.truncated ||= Buffer.byteLength(text2) > 16384;
27483
+ }
27484
+ transcript.status = completed.outcome;
27485
+ saveTranscript();
27486
+ this.finishStep(live, step, completed);
27487
+ return completed;
27488
+ } finally {
27489
+ await auth.settled;
27490
+ if (step.status === "running") {
27491
+ step.status = this.o.owner.state === "quarantined" ? "unknown" : live.abort.signal.aborted ? "canceled" : "failed";
27492
+ step.text = "Worker did not produce a completed native/recorded result.";
27493
+ this.save(live);
27494
+ }
27495
+ }
27496
+ }
27497
+ async process(live, cwd, args, title) {
27498
+ this.assertRunning(live);
27499
+ if (cwd !== this.cwd && !Array.isArray(args))
27500
+ assertWorktree(this.cwd, cwd);
27501
+ const id = randomUUID21();
27502
+ this.write(this.path(live.run.id, `operations/${id}-intent.json`), {
27503
+ cwd,
27504
+ args
27505
+ });
27506
+ let native;
27507
+ const shell = !Array.isArray(args);
27508
+ const step = shell ? this.step(live, title, "check") : undefined;
27509
+ const environment2 = {
27510
+ ...this.o.checkEnvironment ?? {},
27511
+ CADENCE_SUBAGENT_CHILD: "1"
27512
+ };
27513
+ const running = Promise.resolve().then(() => runProcess({
27514
+ command: shell ? process.platform === "win32" ? environment2.COMSPEC ?? "cmd.exe" : "/bin/sh" : "git",
27515
+ args: shell ? process.platform === "win32" ? ["/d", "/s", "/c", `"${args.command}"`] : ["-c", args.command] : gitArguments([
27516
+ "-c",
27517
+ `core.hooksPath=${join26(this.root, "empty-hooks")}`,
27518
+ "-c",
27519
+ "commit.gpgsign=false",
27520
+ "-c",
27521
+ "gc.auto=0",
27522
+ "-c",
27523
+ "maintenance.auto=false",
27524
+ ...args
27525
+ ]),
27526
+ windowsVerbatimArguments: shell && process.platform === "win32" ? true : undefined,
27527
+ cwd,
27528
+ env: shell ? environment2 : gitEnvironment(),
27529
+ signal: live.abort.signal,
27530
+ timeoutMs: shell ? args.timeoutMs : 30000,
27531
+ secrets: [...this.o.secrets()],
27532
+ maySignal: () => {
27533
+ try {
27534
+ this.o.owner.lease.assert();
27535
+ return true;
27536
+ } catch {
27537
+ return false;
27538
+ }
27539
+ },
27540
+ onCheckNative: (v) => {
27541
+ native = v;
27542
+ }
27543
+ }));
27544
+ this.o.owner.trackCheck(running.then(() => {
27545
+ if (!native)
27546
+ throw new ContractError("quarantine");
27547
+ return native;
27548
+ }), () => live.abort.abort());
27549
+ const result = this.sanitizeResult(await running);
27550
+ this.write(this.path(live.run.id, `operations/${id}-settled.json`), {
27551
+ result,
27552
+ native
27553
+ });
27554
+ if (!result.closed)
27555
+ this.o.owner.quarantine();
27556
+ if (step)
27557
+ this.finishStep(live, step, result);
27558
+ return result;
27559
+ }
27560
+ success(result) {
27561
+ if (result.outcome !== "completed" || !result.closed || result.exitCode !== 0)
27562
+ throw new WorkflowFailure(result.outcome, `Operation ${result.outcome}: ${diagnosticText(result.text || result.output, 512, this.o.secrets())}`);
27563
+ }
27564
+ async git(live, cwd, args) {
27565
+ this.success(await this.process(live, cwd, args, "git"));
27566
+ }
27567
+ async setup(live, cwd, plan) {
27568
+ for (const c of plan.setup)
27569
+ this.success(await this.process(live, cwd, c, `setup: ${c.name}`));
27570
+ }
27571
+ async checks(live, cwd, plan, baseline = false) {
27572
+ live.run.phase = "verifying";
27573
+ this.save(live);
27574
+ let passed = true;
27575
+ for (const c of baseline ? plan.baselineChecks : plan.checks) {
27576
+ const r = await this.process(live, cwd, c, c.name);
27577
+ if (!r.closed || r.outcome === "canceled" || r.outcome === "timeout")
27578
+ this.success(r);
27579
+ passed &&= r.outcome === "completed" && r.exitCode === 0;
27580
+ }
27581
+ return passed;
27582
+ }
27583
+ unchangedHead(cwd, before) {
27584
+ if (gitRead(cwd, ["rev-parse", "HEAD"]).trim() !== before)
27585
+ throw new ContractError("stale");
27586
+ }
27587
+ async commit(live, cwd, allowed, message, before) {
27588
+ this.unchangedHead(cwd, before);
27589
+ const changes = assertWorkflowScope(cwd, allowed);
27590
+ if (!changes.length)
27591
+ return null;
27592
+ await this.git(live, cwd, ["add", "--", ...changes]);
27593
+ assertWorkflowScope(cwd, allowed);
27594
+ this.unchangedHead(cwd, before);
27595
+ if (!gitRead(cwd, [
27596
+ "diff",
27597
+ "--cached",
27598
+ "--name-only",
27599
+ "-z",
27600
+ "--no-ext-diff",
27601
+ "--no-textconv",
27602
+ "HEAD",
27603
+ "--"
27604
+ ]))
27605
+ return null;
27606
+ await this.git(live, cwd, ["commit", "--no-verify", "-m", message]);
27607
+ const commit = gitRead(cwd, ["rev-parse", "HEAD"]).trim();
27608
+ assertWorkflowCommit(cwd, before, commit, allowed);
27609
+ return commit;
27610
+ }
27611
+ async review(live, cwd, p) {
27612
+ live.run.phase = "reviewing";
27613
+ this.save(live);
27614
+ const r = await this.worker(live, cwd, `review-${randomUUID21()}`, `Independently inspect the implemented files against the approved plan and acceptance. Look for missing behavior, regressions, weakened tests and scope violations. Do not edit or run commands. Reply with exactly JSON {"approved":true|false,"summary":"...","blockingIssues":["..."]}. Automatic review is not human review.
27615
+ Files: ${p.plan.tasks.flatMap((t) => t.writes).join(", ")}`, true, p.model);
27616
+ this.success(r);
27617
+ try {
27618
+ const raw = r.text.trim().replace(/^```(?:json)?\s*/u, "").replace(/\s*```$/u, "");
27619
+ const verdict = JSON.parse(raw);
27620
+ return verdict.approved === true && Array.isArray(verdict.blockingIssues) && verdict.blockingIssues.length === 0;
27621
+ } catch {
27622
+ return false;
27623
+ }
27624
+ }
27625
+ async verifyAndRepair(live, cwd, p, git) {
27626
+ const allowed = p.plan.tasks.flatMap((t) => t.writes);
27627
+ for (let attempt = 0;attempt <= p.plan.repairAttempts; attempt++) {
27628
+ const beforeChecks = git ? gitRead(cwd, ["rev-parse", "HEAD"]).trim() : "";
27629
+ const reviewed = await this.review(live, cwd, p);
27630
+ const checked2 = await this.checks(live, cwd, p.plan);
27631
+ if (git) {
27632
+ this.unchangedHead(cwd, beforeChecks);
27633
+ assertWorkflowScope(cwd, allowed);
27634
+ }
27635
+ if (reviewed && checked2)
27636
+ return;
27637
+ if (attempt === p.plan.repairAttempts)
27638
+ throw new Error("Verification/review failed; repair budget exhausted. Artifacts preserved; nothing merged.");
27639
+ const failures = live.run.steps.filter((s) => s.kind === "check" || s.kind === "review").slice(-8);
27640
+ const beforeRepair = git ? gitRead(cwd, ["rev-parse", "HEAD"]).trim() : "";
27641
+ const repair = await this.worker(live, cwd, `repair-${attempt + 1}`, `Repair only within approved paths and acceptance. Do not remove or weaken tests, install dependencies, change scope or Git. If a product decision is missing, stop and report it.
27642
+ Allowed files: ${allowed.join(", ")}
27643
+ Observed failures/review: ${canonicalJson(failures, 65536)}`, false, p.model);
27644
+ this.success(repair);
27645
+ if (git)
27646
+ await this.commit(live, cwd, allowed, `Cadence: bounded repair ${attempt + 1}`, beforeRepair);
27647
+ }
27648
+ }
27649
+ publish(live, cwd, plan) {
27650
+ const base = `.cadence/assistant/workflows/${live.run.id}`;
27651
+ const documents = new Map([
27652
+ [`${base}/plan.md`, readableWorkflowPlan(plan)],
27653
+ [
27654
+ `${base}/result.md`,
27655
+ `# Verified candidate
27656
+
27657
+ ${live.run.steps.map((s) => `- ${s.kind} ${s.id}: ${s.status}${s.exitCode === null ? "" : ` (exit ${s.exitCode})`}`).join(`
27658
+ `)}
27659
+
27660
+ Automatic review, not human review. Final integration/native outcomes are retained by the owner.
27661
+ `
27662
+ ]
27663
+ ]);
27664
+ if (plan.projectContext)
27665
+ documents.set(".cadence/project.md", projectMarkdown(cwd, plan.projectContext));
27666
+ for (const [name, body] of documents) {
27667
+ const file = safeWorkflowFile(cwd, name);
27668
+ if (!safeDirectory(dirname17(file), true))
27669
+ throw new ContractError("forbidden");
27670
+ writeFileSync3(file, body, {
27671
+ flag: name === ".cadence/project.md" ? "w" : "wx"
27672
+ });
27673
+ }
27674
+ return [...documents.keys()];
27675
+ }
27676
+ async implement(live, p) {
27677
+ const plan = p.plan;
27678
+ if (plan.delivery === "working-copy") {
27679
+ await this.setup(live, this.cwd, plan);
27680
+ if (!await this.checks(live, this.cwd, plan, true))
27681
+ throw new Error("Baseline checks failed; no implementation started.");
27682
+ for (const task of workflowOrder(plan.tasks)) {
27683
+ live.run.phase = "implementing";
27684
+ this.save(live);
27685
+ this.success(await this.worker(live, this.cwd, task.id, `${task.instructions}
27686
+ Write only these exact files: ${task.writes.join(", ")}`, false, p.model));
27687
+ }
27688
+ await this.verifyAndRepair(live, this.cwd, p, false);
27689
+ this.publish(live, this.cwd, plan);
27690
+ if (!await this.checks(live, this.cwd, plan))
27691
+ throw new Error("Post-publication checks failed; direct working-copy edits preserved.");
27692
+ return;
27693
+ }
27694
+ const initial4 = workflowObservation(this.cwd, plan);
27695
+ const home = join26(this.root, "worktrees", live.run.id);
27696
+ this.files.directory(home, true);
27697
+ const taskHome = join26(home, "tasks");
27698
+ this.files.directory(taskHome, true);
27699
+ const integration = join26(home, "integration");
27700
+ await this.git(live, this.cwd, [
27701
+ "worktree",
27702
+ "add",
27703
+ "--detach",
27704
+ integration,
27705
+ initial4.head
27706
+ ]);
27707
+ assertWorktree(this.cwd, integration);
27708
+ await this.setup(live, integration, plan);
27709
+ assertWorkflowScope(integration, []);
27710
+ if (!await this.checks(live, integration, plan, true))
27711
+ throw new Error("Candidate baseline checks failed. Configure worktree prerequisites in the plan; no implicit dependency installation or copying.");
27712
+ this.unchangedHead(integration, initial4.head);
27713
+ const commits = new Map, pending = new Set(plan.tasks.map((t) => t.id));
27714
+ while (pending.size) {
27715
+ this.assertRunning(live);
27716
+ const batch = workflowOrder(plan.tasks).filter((t) => pending.has(t.id) && t.after.every((d) => commits.has(d))).slice(0, WORKFLOW_LIMITS.parallel);
27717
+ if (!batch.length)
27718
+ throw new ContractError("invalid");
27719
+ live.run.phase = "implementing";
27720
+ this.save(live);
27721
+ const outcomes2 = await Promise.allSettled(batch.map(async (task) => {
27722
+ const cwd = join26(taskHome, task.id);
27723
+ await this.git(live, this.cwd, [
27724
+ "worktree",
27725
+ "add",
27726
+ "--detach",
27727
+ cwd,
27728
+ initial4.head
27729
+ ]);
27730
+ for (const dep of workflowAncestors(plan.tasks, task.id)) {
27731
+ const commit2 = commits.get(dep.id);
27732
+ if (commit2)
27733
+ await this.git(live, cwd, ["cherry-pick", "--no-edit", commit2]);
27734
+ }
27735
+ const beforeWorker = gitRead(cwd, ["rev-parse", "HEAD"]).trim();
27736
+ await this.setup(live, cwd, plan);
27737
+ this.unchangedHead(cwd, beforeWorker);
27738
+ assertWorkflowScope(cwd, []);
27739
+ this.success(await this.worker(live, cwd, task.id, `${task.instructions}
27740
+ Write only these exact files: ${task.writes.join(", ")}. Dependencies are already applied to this worktree.`, false, p.model));
27741
+ const commit = await this.commit(live, cwd, task.writes, `Cadence: ${task.title}`, beforeWorker);
27742
+ commits.set(task.id, commit);
27743
+ pending.delete(task.id);
27744
+ }));
27745
+ const failed = outcomes2.find((r) => r.status === "rejected");
27746
+ if (failed?.status === "rejected")
27747
+ throw failed.reason;
27748
+ }
27749
+ for (const task of workflowOrder(plan.tasks)) {
27750
+ const commit = commits.get(task.id);
27751
+ if (commit)
27752
+ await this.git(live, integration, ["cherry-pick", "--no-edit", commit]);
27753
+ }
27754
+ await this.verifyAndRepair(live, integration, p, true);
27755
+ const documentNames = [
27756
+ `.cadence/assistant/workflows/${live.run.id}/plan.md`,
27757
+ `.cadence/assistant/workflows/${live.run.id}/result.md`,
27758
+ ...plan.projectContext ? [".cadence/project.md"] : []
27759
+ ];
27760
+ const documentBefore = new Map(documentNames.map((p2) => [
27761
+ p2,
27762
+ readBounded(safeWorkflowFile(this.cwd, p2), 128 * 1024)
27763
+ ]));
27764
+ const beforePublication = gitRead(integration, [
27765
+ "rev-parse",
27766
+ "HEAD"
27767
+ ]).trim();
27768
+ const documents = this.publish(live, integration, plan);
27769
+ await this.commit(live, integration, documents, "Cadence: project context and delivery notes", beforePublication);
27770
+ const head = gitRead(integration, ["rev-parse", "HEAD"]).trim();
27771
+ if (!await this.checks(live, integration, plan))
27772
+ throw new Error("Final candidate checks failed; nothing merged.");
27773
+ this.unchangedHead(integration, head);
27774
+ assertWorkflowScope(integration, []);
27775
+ this.assertProposal(p, p.digest, true);
27776
+ live.run.phase = "integrating";
27777
+ this.save(live);
27778
+ await this.git(live, this.cwd, ["merge", "--ff-only", "--no-edit", head]);
27779
+ live.run.mergedCommit = head;
27780
+ this.save(live);
27781
+ for (const name of documents) {
27782
+ if (gitRead(this.cwd, ["ls-files", "--", name]).trim())
27783
+ continue;
27784
+ const file = safeWorkflowFile(this.cwd, name), before = documentBefore.get(name), now = readBounded(file, 128 * 1024);
27785
+ if ((before ? hash2(before) : null) !== (now ? hash2(now) : null))
27786
+ throw new ContractError("conflict");
27787
+ const content = name === ".cadence/project.md" ? projectMarkdown(this.cwd, plan.projectContext) : readBounded(safeWorkflowFile(integration, name), 128 * 1024);
27788
+ if (content === undefined || !safeDirectory(dirname17(file), true))
27789
+ throw new ContractError("unavailable");
27790
+ writeFileSync3(file, content, { flag: before ? "w" : "wx" });
27791
+ }
27792
+ if (!await this.checks(live, this.cwd, plan))
27793
+ throw new Error("Local merge completed, but post-merge checks failed. No reset or rollback was attempted.");
27794
+ this.unchangedHead(this.cwd, head);
27795
+ }
27796
+ async execute(live, request3, proposal) {
27797
+ let barrier;
27798
+ let budgetExpired = false;
27799
+ const timer = setTimeout(() => {
27800
+ budgetExpired = true;
27801
+ live.abort.abort();
27802
+ }, WORKFLOW_LIMITS.durationMs);
27803
+ try {
27804
+ this.assertRunning(live);
27805
+ barrier = await this.o.actions.scheduler.conversationBarrier(live.run.id, live.abort.signal);
27806
+ barrier.assertHeld();
27807
+ this.o.actions.conversationBoundary(barrier);
27808
+ if (proposal)
27809
+ this.assertProposal(proposal, proposal.digest, true);
27810
+ live.run.status = "running";
27811
+ this.save(live);
27812
+ if (request3.action === "research") {
27813
+ const answers = await Promise.allSettled(request3.questions.map((q, i) => this.worker(live, this.cwd, `research-${i + 1}`, `Goal: ${request3.goal}
27814
+ Investigation: ${q}
27815
+ Read only. Cite paths and distinguish evidence, assumptions, user decisions and environment prerequisites.`, true, request3.model)));
27816
+ for (const a of answers) {
27817
+ if (a.status === "rejected")
27818
+ throw a.reason;
27819
+ this.success(a.value);
27820
+ }
27821
+ } else if (proposal)
27822
+ await this.implement(live, proposal);
27823
+ else
27824
+ throw new ContractError("invalid");
27825
+ live.run.status = "completed";
27826
+ } catch (error2) {
27827
+ live.run.status = this.o.owner.state === "quarantined" ? "unknown" : budgetExpired ? "timeout" : live.abort.signal.aborted ? "canceled" : error2 instanceof WorkflowFailure && error2.outcome !== "completed" ? error2.outcome : "failed";
27828
+ live.run.notice = diagnosticText(error2 instanceof ContractError ? error2.code : error2 instanceof Error ? error2.message : "Workflow failed", 2048, this.o.secrets());
27829
+ } finally {
27830
+ clearTimeout(timer);
27831
+ live.run.phase = "finished";
27832
+ try {
27833
+ if (barrier && this.o.owner.state === "idle")
27834
+ this.o.actions.conversationBoundary(barrier);
27835
+ this.save(live);
27836
+ } catch {
27837
+ this.o.owner.quarantine();
27838
+ }
27839
+ if (this.o.owner.state === "idle")
27840
+ barrier?.release();
27841
+ this.active.delete(live.run.id);
27842
+ }
27843
+ return {
27844
+ status: this.o.owner.state === "quarantined" ? "uncertain" : "settled"
27845
+ };
27846
+ }
27847
+ }
27848
+
25779
27849
  // src/service/workbench.ts
25780
27850
  class Workbench {
25781
27851
  o;
25782
27852
  conversations;
25783
27853
  files;
27854
+ workflows;
27855
+ cadence;
25784
27856
  projectRoot;
25785
27857
  opening = new Map;
25786
27858
  constructor(o) {
25787
27859
  this.o = o;
25788
27860
  this.conversations = new Conversations(o);
27861
+ this.workflows = new Workflows(o);
27862
+ this.cadence = new ConversationWorkflow({
27863
+ ...o,
27864
+ conversations: this.conversations,
27865
+ workflows: this.workflows
27866
+ });
27867
+ this.cadence.assertRecords();
27868
+ for (const entry of this.conversations.list().entries)
27869
+ this.cadence.state(entry.id);
25789
27870
  if (this.conversations.list().entries.some((entry) => entry.status === "unknown"))
25790
27871
  throw new ContractError("quarantine");
25791
27872
  this.files = new WorkbenchFiles(o.cwd, [o.coordination.files.namespace, o.agentDir], o.secrets);
25792
- this.projectRoot = join23(o.coordination.files.namespace, "workbench-projects-v1");
27873
+ this.projectRoot = join27(o.coordination.files.namespace, "workbench-projects-v1");
25793
27874
  }
25794
27875
  read(value) {
25795
27876
  const request3 = decodeWorkbenchRead(value);
25796
27877
  this.o.owner.lease.assert();
25797
27878
  switch (request3.kind) {
27879
+ case "cadence-conversation":
27880
+ return { kind: request3.kind, state: this.cadence.state(request3.id) };
27881
+ case "workflow-active":
27882
+ return this.workflows.activeRuns();
27883
+ case "workflow-transcript":
27884
+ return this.workflows.transcript(request3.id, request3.stepId);
27885
+ case "workflow-detail":
27886
+ return this.workflows.detail(request3.id, request3.stepId);
27887
+ case "workflow":
27888
+ return this.workflows.view(request3.id);
25798
27889
  case "task-origin":
25799
27890
  return this.conversations.origin(request3.taskId);
25800
- case "conversations":
25801
- return this.conversations.list();
27891
+ case "conversations": {
27892
+ const value2 = this.conversations.list();
27893
+ return {
27894
+ ...value2,
27895
+ entries: value2.entries.map((entry) => ({
27896
+ ...entry,
27897
+ cadence: this.cadence.state(entry.id).enabled
27898
+ }))
27899
+ };
27900
+ }
25802
27901
  case "conversation":
25803
27902
  return this.conversations.view(request3.id, request3.before);
25804
27903
  case "files":
@@ -25811,6 +27910,34 @@ class Workbench {
25811
27910
  return this.projects();
25812
27911
  }
25813
27912
  }
27913
+ send(request3) {
27914
+ let mayHaveEffects = true;
27915
+ try {
27916
+ const state = this.cadence.state(request3.conversationId);
27917
+ mayHaveEffects = this.o.owner.state !== "idle" || state.head === request3.commandId || this.conversations.attempted(request3.conversationId, request3.commandId);
27918
+ const accepting = () => {
27919
+ mayHaveEffects = true;
27920
+ };
27921
+ if (request3.kind === "send") {
27922
+ if (state.enabled)
27923
+ throw new ContractError("conflict");
27924
+ return this.conversations.send(request3, undefined, accepting);
27925
+ }
27926
+ if (request3.kind === "cadence-exit")
27927
+ return this.cadence.send({
27928
+ ...request3,
27929
+ kind: "cadence-send",
27930
+ text: "exit cadence",
27931
+ model: this.o.choice.snapshot().version,
27932
+ intent: "exit"
27933
+ }, accepting);
27934
+ return this.cadence.send(request3, accepting);
27935
+ } catch (error2) {
27936
+ if (!mayHaveEffects && error2 instanceof ContractError)
27937
+ throw new UnacceptedConversationCommand(error2.code);
27938
+ throw error2;
27939
+ }
27940
+ }
25814
27941
  projects() {
25815
27942
  const secrets = this.o.secrets();
25816
27943
  if (sanitizeText(this.o.cwd, secrets) !== this.o.cwd)
@@ -25818,12 +27945,12 @@ class Workbench {
25818
27945
  const entries = [{ path: this.o.cwd, current: true }], files = this.o.coordination.files;
25819
27946
  if (!files.directory(this.projectRoot))
25820
27947
  return { kind: "projects", entries };
25821
- const directory = opendirSync8(this.projectRoot);
27948
+ const directory = opendirSync10(this.projectRoot);
25822
27949
  try {
25823
27950
  for (let e = directory.readSync();e; e = directory.readSync()) {
25824
27951
  if (!e.isFile() || !/^[a-f0-9]{64}\.json$/.test(e.name) || entries.length > 128)
25825
27952
  throw new ContractError("corrupt-selected");
25826
- const saved = files.read(join23(this.projectRoot, e.name));
27953
+ const saved = files.read(join27(this.projectRoot, e.name));
25827
27954
  if (!saved)
25828
27955
  throw new ContractError("corrupt-selected");
25829
27956
  const row = closed(parseWireJson(saved.bytes.toString("utf8")), [
@@ -25839,10 +27966,34 @@ class Workbench {
25839
27966
  }
25840
27967
  return { kind: "projects", entries };
25841
27968
  }
25842
- command(value) {
27969
+ command(value, caller) {
25843
27970
  const request3 = decodeWorkbenchCommand(value);
25844
- if (request3.kind === "send")
25845
- return this.conversations.send(request3);
27971
+ if (request3.kind === "restore-model") {
27972
+ if (request3.epoch !== this.o.owner.lease.registration.epoch)
27973
+ throw new ContractError("stale");
27974
+ const before = this.o.choice.snapshot();
27975
+ if (!before.selected) {
27976
+ const choice = new CadencePreferences(this.o.agentDir).read();
27977
+ if (!choice)
27978
+ throw new ContractError("unavailable");
27979
+ this.o.choice.choose({ expected: before.version, choice });
27980
+ }
27981
+ return { kind: "accepted", commandId: request3.commandId };
27982
+ }
27983
+ if (request3.kind === "send" || request3.kind === "cadence-send" || request3.kind === "cadence-exit")
27984
+ return this.send(request3);
27985
+ if (request3.kind === "cadence-prepare" || request3.kind === "cadence-approve")
27986
+ return this.cadence.approval(request3, caller);
27987
+ if (request3.kind === "workflow-cancel") {
27988
+ if (!caller)
27989
+ throw new ContractError("forbidden");
27990
+ return this.workflows.command(request3.commandId, request3.epoch, {
27991
+ action: "cancel",
27992
+ runId: request3.runId
27993
+ });
27994
+ }
27995
+ if (request3.kind === "workflow")
27996
+ return this.workflows.command(request3.commandId, request3.epoch, request3.request);
25846
27997
  if (request3.kind === "link-task") {
25847
27998
  this.conversations.link(request3.taskId, request3.conversationId, request3.epoch);
25848
27999
  return { kind: "accepted", commandId: request3.commandId };
@@ -25867,7 +28018,7 @@ class Workbench {
25867
28018
  if (this.opening.size >= 64)
25868
28019
  throw new ContractError("capacity");
25869
28020
  const path = this.files.directory(request3.path);
25870
- const marker2 = join23(this.o.coordination.directory, "conversations-v1", "project-commands", `${request3.commandId}.json`);
28021
+ const marker2 = join27(this.o.coordination.directory, "conversations-v1", "project-commands", `${request3.commandId}.json`);
25871
28022
  const files = this.o.coordination.files;
25872
28023
  if (files.read(marker2))
25873
28024
  throw new ContractError("receipt-inconclusive");
@@ -25885,7 +28036,7 @@ class Workbench {
25885
28036
  }
25886
28037
  const opened = await openProjectDirectory(path, this.o.coordination.stateHome, this.o.agentDir, this.o.hostUrl);
25887
28038
  for (const root of [this.o.cwd, opened.path]) {
25888
- const entry = join23(this.projectRoot, `${hash2(root)}.json`);
28039
+ const entry = join27(this.projectRoot, `${hash2(root)}.json`);
25889
28040
  const saved = files.read(entry);
25890
28041
  if (!saved)
25891
28042
  files.create(entry, canonicalJson({ path: root }));
@@ -25916,7 +28067,7 @@ function legacy(store, budget, reader) {
25916
28067
  throw new ContractError("capacity");
25917
28068
  }
25918
28069
  }
25919
- const dir = opendirSync9(store.tasks), records = [];
28070
+ const dir = opendirSync11(store.tasks), records = [];
25920
28071
  let entries = 0;
25921
28072
  try {
25922
28073
  for (let entry = dir.readSync();entry; entry = dir.readSync()) {
@@ -25925,8 +28076,8 @@ function legacy(store, budget, reader) {
25925
28076
  decodeId(entry.name);
25926
28077
  if (created.has(entry.name))
25927
28078
  continue;
25928
- const path = join24(store.tasks, entry.name, "task.json");
25929
- const size = lstatSync14(path).size;
28079
+ const path = join28(store.tasks, entry.name, "task.json");
28080
+ const size = lstatSync16(path).size;
25930
28081
  if (size > 128 * 1024)
25931
28082
  throw new ContractError("corrupt-selected");
25932
28083
  budget.reserve(size);
@@ -25948,7 +28099,7 @@ function refuseAt(stage, step) {
25948
28099
  }
25949
28100
  }
25950
28101
  async function createServiceHost(value, sourceBuild) {
25951
- const embedded = "83a2720c0a5a61f9e18e4f67e9738f184dee61cf07e75d9b98b5728577daaa6d";
28102
+ const embedded = "d19e63723270a27a4c00776d8301849e08480e054bc832ca455f889d061c65c9";
25952
28103
  if (embedded && sourceBuild)
25953
28104
  throw new ContractError("unsupported-context");
25954
28105
  const contractHash = decodeHash(embedded ?? sourceBuild?.contractHash);
@@ -26060,7 +28211,14 @@ async function createServiceHost(value, sourceBuild) {
26060
28211
  cwd: input.config.cwd,
26061
28212
  environment: launch
26062
28213
  });
26063
- const choice = new OwnerModelChoice({ owner, writer, models, access });
28214
+ const preferences = new CadencePreferences(input.config.agentDir);
28215
+ const choice = new OwnerModelChoice({
28216
+ owner,
28217
+ writer,
28218
+ models,
28219
+ access,
28220
+ remember: (value2) => preferences.save(value2)
28221
+ });
26064
28222
  const { PI_OFFLINE: _offline, ...ordinary } = launch;
26065
28223
  const checkEnvironment = Object.freeze(ordinary);
26066
28224
  const actions = sourceBuild?.deferActions ? null : new TaskActions({
@@ -26091,6 +28249,7 @@ async function createServiceHost(value, sourceBuild) {
26091
28249
  cwd: input.config.cwd,
26092
28250
  agentDir: input.config.agentDir,
26093
28251
  projectsEnabled: !input.config.http.proxy,
28252
+ checkEnvironment,
26094
28253
  hostUrl: new URL(sourceBuild ? "../service-host.mjs" : "./service-host.mjs", import.meta.url),
26095
28254
  secrets: () => [
26096
28255
  ...access.redactionLiterals(),
@@ -26100,10 +28259,10 @@ async function createServiceHost(value, sourceBuild) {
26100
28259
  ],
26101
28260
  timeoutMs: sourceBuild?.workerTimeoutMs
26102
28261
  }) : null;
26103
- const unavailable2 = (taskId) => ({
28262
+ const unavailable2 = (taskId2) => ({
26104
28263
  status: "unavailable",
26105
28264
  workspaceId: reader.files.format.workspaceId,
26106
- taskId,
28265
+ taskId: taskId2,
26107
28266
  error: publicError(owner?.state === "idle" ? "unavailable" : "quarantine")
26108
28267
  });
26109
28268
  const projection = new HistoryProjection(reader, {