@caupulican/pi-adaptative 0.86.3 → 0.86.6

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.
Files changed (247) hide show
  1. package/CHANGELOG.md +44 -0
  2. package/dist/core/agent-paths.d.ts +13 -0
  3. package/dist/core/agent-paths.d.ts.map +1 -1
  4. package/dist/core/agent-paths.js +23 -0
  5. package/dist/core/agent-paths.js.map +1 -1
  6. package/dist/core/autonomy/bounded-completion.d.ts +7 -0
  7. package/dist/core/autonomy/bounded-completion.d.ts.map +1 -1
  8. package/dist/core/autonomy/bounded-completion.js +12 -4
  9. package/dist/core/autonomy/bounded-completion.js.map +1 -1
  10. package/dist/core/autonomy/lane-tool-surface.d.ts +2 -0
  11. package/dist/core/autonomy/lane-tool-surface.d.ts.map +1 -1
  12. package/dist/core/autonomy/lane-tool-surface.js +6 -3
  13. package/dist/core/autonomy/lane-tool-surface.js.map +1 -1
  14. package/dist/core/autonomy/subagent-prompt.js +1 -1
  15. package/dist/core/autonomy/subagent-prompt.js.map +1 -1
  16. package/dist/core/background-lane-controller.d.ts +25 -2
  17. package/dist/core/background-lane-controller.d.ts.map +1 -1
  18. package/dist/core/background-lane-controller.js +67 -0
  19. package/dist/core/background-lane-controller.js.map +1 -1
  20. package/dist/core/delegation/replay-safe-mailbox-bounds.d.ts +4 -0
  21. package/dist/core/delegation/replay-safe-mailbox-bounds.d.ts.map +1 -0
  22. package/dist/core/delegation/replay-safe-mailbox-bounds.js +20 -0
  23. package/dist/core/delegation/replay-safe-mailbox-bounds.js.map +1 -0
  24. package/dist/core/delegation/sanitized-context-fork.d.ts +25 -0
  25. package/dist/core/delegation/sanitized-context-fork.d.ts.map +1 -0
  26. package/dist/core/delegation/sanitized-context-fork.js +299 -0
  27. package/dist/core/delegation/sanitized-context-fork.js.map +1 -0
  28. package/dist/core/delegation/session-root-mailbox.d.ts +75 -0
  29. package/dist/core/delegation/session-root-mailbox.d.ts.map +1 -0
  30. package/dist/core/delegation/session-root-mailbox.js +627 -0
  31. package/dist/core/delegation/session-root-mailbox.js.map +1 -0
  32. package/dist/core/delegation/worker-agent-control-coordinator.d.ts +102 -9
  33. package/dist/core/delegation/worker-agent-control-coordinator.d.ts.map +1 -1
  34. package/dist/core/delegation/worker-agent-control-coordinator.js +1307 -125
  35. package/dist/core/delegation/worker-agent-control-coordinator.js.map +1 -1
  36. package/dist/core/delegation/worker-agent-control.d.ts +183 -8
  37. package/dist/core/delegation/worker-agent-control.d.ts.map +1 -1
  38. package/dist/core/delegation/worker-agent-control.js +778 -48
  39. package/dist/core/delegation/worker-agent-control.js.map +1 -1
  40. package/dist/core/delegation/worker-attempt-executor.d.ts +9 -0
  41. package/dist/core/delegation/worker-attempt-executor.d.ts.map +1 -1
  42. package/dist/core/delegation/worker-attempt-executor.js +479 -214
  43. package/dist/core/delegation/worker-attempt-executor.js.map +1 -1
  44. package/dist/core/delegation/worker-authority-resolver.d.ts +9 -0
  45. package/dist/core/delegation/worker-authority-resolver.d.ts.map +1 -1
  46. package/dist/core/delegation/worker-authority-resolver.js +21 -2
  47. package/dist/core/delegation/worker-authority-resolver.js.map +1 -1
  48. package/dist/core/delegation/worker-context-fork-store.d.ts +71 -0
  49. package/dist/core/delegation/worker-context-fork-store.d.ts.map +1 -0
  50. package/dist/core/delegation/worker-context-fork-store.js +437 -0
  51. package/dist/core/delegation/worker-context-fork-store.js.map +1 -0
  52. package/dist/core/delegation/worker-context-inheritance-policy.d.ts +18 -0
  53. package/dist/core/delegation/worker-context-inheritance-policy.d.ts.map +1 -0
  54. package/dist/core/delegation/worker-context-inheritance-policy.js +28 -0
  55. package/dist/core/delegation/worker-context-inheritance-policy.js.map +1 -0
  56. package/dist/core/delegation/worker-conversation-revision.d.ts +31 -0
  57. package/dist/core/delegation/worker-conversation-revision.d.ts.map +1 -0
  58. package/dist/core/delegation/worker-conversation-revision.js +203 -0
  59. package/dist/core/delegation/worker-conversation-revision.js.map +1 -0
  60. package/dist/core/delegation/worker-conversation-store.d.ts +130 -18
  61. package/dist/core/delegation/worker-conversation-store.d.ts.map +1 -1
  62. package/dist/core/delegation/worker-conversation-store.js +1263 -79
  63. package/dist/core/delegation/worker-conversation-store.js.map +1 -1
  64. package/dist/core/delegation/worker-delegation-controller.d.ts +30 -2
  65. package/dist/core/delegation/worker-delegation-controller.d.ts.map +1 -1
  66. package/dist/core/delegation/worker-delegation-controller.js +675 -111
  67. package/dist/core/delegation/worker-delegation-controller.js.map +1 -1
  68. package/dist/core/delegation/worker-delegation-request.d.ts +2 -0
  69. package/dist/core/delegation/worker-delegation-request.d.ts.map +1 -1
  70. package/dist/core/delegation/worker-delegation-request.js.map +1 -1
  71. package/dist/core/delegation/worker-dispatch-scheduler.d.ts +20 -1
  72. package/dist/core/delegation/worker-dispatch-scheduler.d.ts.map +1 -1
  73. package/dist/core/delegation/worker-dispatch-scheduler.js +210 -37
  74. package/dist/core/delegation/worker-dispatch-scheduler.js.map +1 -1
  75. package/dist/core/delegation/worker-execution-policy.d.ts.map +1 -1
  76. package/dist/core/delegation/worker-execution-policy.js +14 -2
  77. package/dist/core/delegation/worker-execution-policy.js.map +1 -1
  78. package/dist/core/delegation/worker-fleet-limits.d.ts +38 -0
  79. package/dist/core/delegation/worker-fleet-limits.d.ts.map +1 -0
  80. package/dist/core/delegation/worker-fleet-limits.js +113 -0
  81. package/dist/core/delegation/worker-fleet-limits.js.map +1 -0
  82. package/dist/core/delegation/worker-lane-projection.d.ts +1 -0
  83. package/dist/core/delegation/worker-lane-projection.d.ts.map +1 -1
  84. package/dist/core/delegation/worker-lane-projection.js +6 -2
  85. package/dist/core/delegation/worker-lane-projection.js.map +1 -1
  86. package/dist/core/delegation/worker-lifecycle.d.ts +20 -3
  87. package/dist/core/delegation/worker-lifecycle.d.ts.map +1 -1
  88. package/dist/core/delegation/worker-lifecycle.js +42 -18
  89. package/dist/core/delegation/worker-lifecycle.js.map +1 -1
  90. package/dist/core/delegation/worker-notification-coordinator.d.ts +4 -0
  91. package/dist/core/delegation/worker-notification-coordinator.d.ts.map +1 -1
  92. package/dist/core/delegation/worker-notification-coordinator.js +45 -4
  93. package/dist/core/delegation/worker-notification-coordinator.js.map +1 -1
  94. package/dist/core/delegation/worker-provider-turn-protocol.d.ts +50 -0
  95. package/dist/core/delegation/worker-provider-turn-protocol.d.ts.map +1 -0
  96. package/dist/core/delegation/worker-provider-turn-protocol.js +185 -0
  97. package/dist/core/delegation/worker-provider-turn-protocol.js.map +1 -0
  98. package/dist/core/delegation/worker-recovery-coordinator.d.ts +45 -4
  99. package/dist/core/delegation/worker-recovery-coordinator.d.ts.map +1 -1
  100. package/dist/core/delegation/worker-recovery-coordinator.js +223 -17
  101. package/dist/core/delegation/worker-recovery-coordinator.js.map +1 -1
  102. package/dist/core/delegation/worker-retry-policy.d.ts +36 -0
  103. package/dist/core/delegation/worker-retry-policy.d.ts.map +1 -0
  104. package/dist/core/delegation/worker-retry-policy.js +41 -0
  105. package/dist/core/delegation/worker-retry-policy.js.map +1 -0
  106. package/dist/core/delegation/worker-runner.d.ts +3 -1
  107. package/dist/core/delegation/worker-runner.d.ts.map +1 -1
  108. package/dist/core/delegation/worker-runner.js +4 -2
  109. package/dist/core/delegation/worker-runner.js.map +1 -1
  110. package/dist/core/delegation/worker-task-view.d.ts +43 -0
  111. package/dist/core/delegation/worker-task-view.d.ts.map +1 -0
  112. package/dist/core/delegation/worker-task-view.js +194 -0
  113. package/dist/core/delegation/worker-task-view.js.map +1 -0
  114. package/dist/core/delegation/worker-terminal-handoff-coordinator.d.ts +55 -0
  115. package/dist/core/delegation/worker-terminal-handoff-coordinator.d.ts.map +1 -0
  116. package/dist/core/delegation/worker-terminal-handoff-coordinator.js +179 -0
  117. package/dist/core/delegation/worker-terminal-handoff-coordinator.js.map +1 -0
  118. package/dist/core/delegation/worker-tree-budget-coordinator.d.ts +2 -2
  119. package/dist/core/delegation/worker-tree-budget-coordinator.d.ts.map +1 -1
  120. package/dist/core/delegation/worker-tree-budget-coordinator.js +12 -46
  121. package/dist/core/delegation/worker-tree-budget-coordinator.js.map +1 -1
  122. package/dist/core/goals/goal-continuation-controller.d.ts.map +1 -1
  123. package/dist/core/goals/goal-continuation-controller.js +15 -0
  124. package/dist/core/goals/goal-continuation-controller.js.map +1 -1
  125. package/dist/core/goals/goal-state.d.ts +6 -0
  126. package/dist/core/goals/goal-state.d.ts.map +1 -1
  127. package/dist/core/goals/goal-state.js +1 -0
  128. package/dist/core/goals/goal-state.js.map +1 -1
  129. package/dist/core/goals/goal-tool-core.d.ts +1 -0
  130. package/dist/core/goals/goal-tool-core.d.ts.map +1 -1
  131. package/dist/core/goals/goal-tool-core.js +25 -3
  132. package/dist/core/goals/goal-tool-core.js.map +1 -1
  133. package/dist/core/keybindings.d.ts +10 -0
  134. package/dist/core/keybindings.d.ts.map +1 -1
  135. package/dist/core/keybindings.js +2 -0
  136. package/dist/core/keybindings.js.map +1 -1
  137. package/dist/core/orchestration/attempt-ordering.d.ts +9 -0
  138. package/dist/core/orchestration/attempt-ordering.d.ts.map +1 -0
  139. package/dist/core/orchestration/attempt-ordering.js +29 -0
  140. package/dist/core/orchestration/attempt-ordering.js.map +1 -0
  141. package/dist/core/orchestration/capability-gateway.d.ts +19 -0
  142. package/dist/core/orchestration/capability-gateway.d.ts.map +1 -1
  143. package/dist/core/orchestration/capability-gateway.js +19 -2
  144. package/dist/core/orchestration/capability-gateway.js.map +1 -1
  145. package/dist/core/orchestration/contracts.d.ts +43 -3
  146. package/dist/core/orchestration/contracts.d.ts.map +1 -1
  147. package/dist/core/orchestration/contracts.js +24 -0
  148. package/dist/core/orchestration/contracts.js.map +1 -1
  149. package/dist/core/orchestration/delegation-ledger.d.ts +8 -3
  150. package/dist/core/orchestration/delegation-ledger.d.ts.map +1 -1
  151. package/dist/core/orchestration/delegation-ledger.js +148 -55
  152. package/dist/core/orchestration/delegation-ledger.js.map +1 -1
  153. package/dist/core/orchestration/event-store.d.ts +6 -3
  154. package/dist/core/orchestration/event-store.d.ts.map +1 -1
  155. package/dist/core/orchestration/event-store.js +228 -30
  156. package/dist/core/orchestration/event-store.js.map +1 -1
  157. package/dist/core/orchestration/task-runtime-codecs.d.ts +31 -0
  158. package/dist/core/orchestration/task-runtime-codecs.d.ts.map +1 -0
  159. package/dist/core/orchestration/task-runtime-codecs.js +1471 -0
  160. package/dist/core/orchestration/task-runtime-codecs.js.map +1 -0
  161. package/dist/core/orchestration/task-runtime-projection.d.ts +30 -0
  162. package/dist/core/orchestration/task-runtime-projection.d.ts.map +1 -0
  163. package/dist/core/orchestration/task-runtime-projection.js +340 -0
  164. package/dist/core/orchestration/task-runtime-projection.js.map +1 -0
  165. package/dist/core/orchestration/task-runtime-reducer.d.ts +38 -0
  166. package/dist/core/orchestration/task-runtime-reducer.d.ts.map +1 -0
  167. package/dist/core/orchestration/task-runtime-reducer.js +1270 -0
  168. package/dist/core/orchestration/task-runtime-reducer.js.map +1 -0
  169. package/dist/core/orchestration/task-runtime-state.d.ts +142 -0
  170. package/dist/core/orchestration/task-runtime-state.d.ts.map +1 -0
  171. package/dist/core/orchestration/task-runtime-state.js +14 -0
  172. package/dist/core/orchestration/task-runtime-state.js.map +1 -0
  173. package/dist/core/orchestration/task-runtime.d.ts +44 -98
  174. package/dist/core/orchestration/task-runtime.d.ts.map +1 -1
  175. package/dist/core/orchestration/task-runtime.js +357 -1113
  176. package/dist/core/orchestration/task-runtime.js.map +1 -1
  177. package/dist/core/orchestration/worker-context-fork-reference.d.ts +20 -0
  178. package/dist/core/orchestration/worker-context-fork-reference.d.ts.map +1 -0
  179. package/dist/core/orchestration/worker-context-fork-reference.js +53 -0
  180. package/dist/core/orchestration/worker-context-fork-reference.js.map +1 -0
  181. package/dist/core/orchestration/worker-execution-contract.d.ts.map +1 -1
  182. package/dist/core/orchestration/worker-execution-contract.js +4 -2
  183. package/dist/core/orchestration/worker-execution-contract.js.map +1 -1
  184. package/dist/core/research/research-runner.d.ts +2 -0
  185. package/dist/core/research/research-runner.d.ts.map +1 -1
  186. package/dist/core/research/research-runner.js +1 -0
  187. package/dist/core/research/research-runner.js.map +1 -1
  188. package/dist/core/runtime-builder.d.ts.map +1 -1
  189. package/dist/core/runtime-builder.js +8 -0
  190. package/dist/core/runtime-builder.js.map +1 -1
  191. package/dist/core/secrets/credential-project.d.ts.map +1 -1
  192. package/dist/core/secrets/credential-project.js +24 -2
  193. package/dist/core/secrets/credential-project.js.map +1 -1
  194. package/dist/core/security/secret-text.d.ts +3 -0
  195. package/dist/core/security/secret-text.d.ts.map +1 -1
  196. package/dist/core/security/secret-text.js +15 -0
  197. package/dist/core/security/secret-text.js.map +1 -1
  198. package/dist/core/settings-manager.d.ts +3 -0
  199. package/dist/core/settings-manager.d.ts.map +1 -1
  200. package/dist/core/settings-manager.js +160 -8
  201. package/dist/core/settings-manager.js.map +1 -1
  202. package/dist/core/tools/delegate.d.ts +33 -15
  203. package/dist/core/tools/delegate.d.ts.map +1 -1
  204. package/dist/core/tools/delegate.js +763 -115
  205. package/dist/core/tools/delegate.js.map +1 -1
  206. package/dist/core/tools/goal.d.ts +1 -0
  207. package/dist/core/tools/goal.d.ts.map +1 -1
  208. package/dist/core/tools/goal.js +9 -1
  209. package/dist/core/tools/goal.js.map +1 -1
  210. package/dist/main.d.ts.map +1 -1
  211. package/dist/main.js +1 -0
  212. package/dist/main.js.map +1 -1
  213. package/dist/modes/interactive/components/activity-lane.d.ts +5 -0
  214. package/dist/modes/interactive/components/activity-lane.d.ts.map +1 -1
  215. package/dist/modes/interactive/components/activity-lane.js +133 -49
  216. package/dist/modes/interactive/components/activity-lane.js.map +1 -1
  217. package/dist/modes/interactive/components/agents-overlay.d.ts +40 -0
  218. package/dist/modes/interactive/components/agents-overlay.d.ts.map +1 -0
  219. package/dist/modes/interactive/components/agents-overlay.js +153 -0
  220. package/dist/modes/interactive/components/agents-overlay.js.map +1 -0
  221. package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -1
  222. package/dist/modes/interactive/components/settings-selector.js +18 -13
  223. package/dist/modes/interactive/components/settings-selector.js.map +1 -1
  224. package/dist/modes/interactive/interactive-event-controller.d.ts +1 -1
  225. package/dist/modes/interactive/interactive-event-controller.d.ts.map +1 -1
  226. package/dist/modes/interactive/interactive-event-controller.js +6 -3
  227. package/dist/modes/interactive/interactive-event-controller.js.map +1 -1
  228. package/dist/modes/interactive/interactive-mode.d.ts +5 -0
  229. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  230. package/dist/modes/interactive/interactive-mode.js +51 -0
  231. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  232. package/dist/modes/interactive/key-handlers.d.ts +1 -0
  233. package/dist/modes/interactive/key-handlers.d.ts.map +1 -1
  234. package/dist/modes/interactive/key-handlers.js +1 -0
  235. package/dist/modes/interactive/key-handlers.js.map +1 -1
  236. package/docs/harness-architecture.md +61 -17
  237. package/docs/settings.md +17 -9
  238. package/docs/worker-profiles.md +6 -2
  239. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  240. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  241. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  242. package/examples/extensions/sandbox/package-lock.json +2 -2
  243. package/examples/extensions/sandbox/package.json +1 -1
  244. package/examples/extensions/with-deps/package-lock.json +2 -2
  245. package/examples/extensions/with-deps/package.json +1 -1
  246. package/npm-shrinkwrap.json +12 -12
  247. package/package.json +4 -4
@@ -1,11 +1,25 @@
1
+ import { createHash } from "node:crypto";
2
+ import { isDeepStrictEqual } from "node:util";
1
3
  import { deriveWorkerTaskLabel } from "../delegation/worker-task-label.js";
2
4
  import { hasGoalAcceptanceOverride } from "../goals/goal-acceptance.js";
5
+ import { latestAgentAttemptByDurableOrder } from "./attempt-ordering.js";
6
+ import { MAX_ORCHESTRATION_IDENTIFIER_LENGTH } from "./contracts.js";
3
7
  import { OrchestrationEventStore } from "./event-store.js";
4
- import { DurableTaskRuntime, DurableTaskRuntimeError } from "./task-runtime.js";
8
+ import { DurableTaskRuntime, DurableTaskRuntimeError, validateTaskDependencyIds, } from "./task-runtime.js";
5
9
  import { goalObjectiveId, projectGoalAcceptanceEvidence, projectGoalObjective } from "./work-state-projection.js";
10
+ import { normalizeWorkerContextForkReference, } from "./worker-context-fork-reference.js";
6
11
  function activeAttempt(attempt) {
7
12
  return attempt.status === "queued" || attempt.status === "leased" || attempt.status === "running";
8
13
  }
14
+ function mailboxTurnTaskId(agentId, controlMessageId) {
15
+ return `mailbox-turn-${createHash("sha256")
16
+ .update("pi-worker-agent-mailbox-turn-v1")
17
+ .update("\0")
18
+ .update(agentId)
19
+ .update("\0")
20
+ .update(controlMessageId)
21
+ .digest("hex")}`;
22
+ }
9
23
  /**
10
24
  * Durable adapter for in-process delegated completions. It records the dispatch before execution,
11
25
  * fences interrupted completions on restart, and returns queued work for event-driven re-dispatch.
@@ -15,7 +29,7 @@ export class DelegationOrchestrationLedger {
15
29
  constructor(options) {
16
30
  this.sessionId = options.sessionId;
17
31
  this.runtime = new DurableTaskRuntime({
18
- store: new OrchestrationEventStore({ agentDir: options.agentDir, sessionId: options.sessionId }),
32
+ store: options.store ?? new OrchestrationEventStore({ agentDir: options.agentDir, sessionId: options.sessionId }),
19
33
  now: options.now,
20
34
  });
21
35
  }
@@ -33,7 +47,10 @@ export class DelegationOrchestrationLedger {
33
47
  ...(input.goal ? { goal: input.goal } : {}),
34
48
  ...(input.verificationOfTaskId ? { verificationOfTaskId: input.verificationOfTaskId } : {}),
35
49
  ...(input.taskContext ? { taskContext: input.taskContext } : {}),
36
- dispatchMetadata: { logicalLaneId: input.laneId },
50
+ dispatchMetadata: {
51
+ logicalLaneId: input.laneId,
52
+ ...(input.birthContextForkReference ? { birthContextForkReference: input.birthContextForkReference } : {}),
53
+ },
37
54
  });
38
55
  }
39
56
  prepareManaged(input) {
@@ -62,24 +79,30 @@ export class DelegationOrchestrationLedger {
62
79
  }
63
80
  /**
64
81
  * Queue one new turn for an existing logical agent. The agent identity and its immutable
65
- * execution contract are inherited from the last bound turn; the durable task and attempt ids
66
- * are intentionally new so retries, leases, and terminal evidence never collide across turns.
82
+ * execution contract are inherited from the last bound turn. Each distinct control message owns
83
+ * one deterministic task/attempt identity; exact retries adopt it instead of minting new work.
67
84
  */
68
85
  prepareAgentTurn(input) {
69
86
  const agentId = input.agentId.trim();
70
87
  const instructions = input.instructions.trim();
88
+ const controlMessageId = input.controlMessageId?.trim();
71
89
  if (!agentId)
72
90
  throw new DurableTaskRuntimeError("Logical worker agent id is required.");
73
91
  if (!instructions)
74
92
  throw new DurableTaskRuntimeError("Worker follow-up instructions are required.");
93
+ if (input.controlMessageId !== undefined &&
94
+ (!controlMessageId || controlMessageId.length > MAX_ORCHESTRATION_IDENTIFIER_LENGTH)) {
95
+ throw new DurableTaskRuntimeError("Worker control message id is invalid.");
96
+ }
75
97
  const snapshot = this.runtime.getSnapshot();
76
98
  const agent = snapshot.agents[agentId];
77
99
  if (!agent)
78
100
  throw new DurableTaskRuntimeError(`Unknown logical worker agent '${agentId}'.`);
79
- if (agent.status !== "registered") {
80
- throw new DurableTaskRuntimeError(`Logical worker agent '${agentId}' is not idle.`);
81
- }
82
- const prior = this.latestAgentAttempt(snapshot, agent);
101
+ const agentAttempts = Object.values(snapshot.attempts).filter((attempt) => attempt.agentId === agentId || attempt.dispatch.logicalLaneId === agentId);
102
+ const sequence = agentAttempts.length + 1;
103
+ const taskId = controlMessageId ? mailboxTurnTaskId(agentId, controlMessageId) : `${agentId}:turn:${sequence}`;
104
+ const existingTask = snapshot.tasks[taskId]?.task;
105
+ const prior = latestAgentAttemptByDurableOrder(snapshot, agent.agentId);
83
106
  const contract = prior?.dispatch.executionContract;
84
107
  if (!prior || !contract) {
85
108
  throw new DurableTaskRuntimeError(`Logical worker agent '${agentId}' has no immutable execution contract.`);
@@ -87,9 +110,31 @@ export class DelegationOrchestrationLedger {
87
110
  const priorTask = snapshot.tasks[prior.taskId]?.task;
88
111
  if (!priorTask)
89
112
  throw new DurableTaskRuntimeError(`Logical worker agent '${agentId}' has no prior durable task.`);
90
- const sequence = Object.values(snapshot.attempts).filter((attempt) => attempt.agentId === agentId).length + 1;
91
- const taskId = `${agentId}:turn:${sequence}`;
92
- if (snapshot.tasks[taskId]) {
113
+ const dependencyTaskIds = validateTaskDependencyIds(snapshot.tasks, existingTask?.objectiveId ?? priorTask.objectiveId, input.dependsOnTaskIds);
114
+ if (existingTask && controlMessageId) {
115
+ if (existingTask.description !== instructions ||
116
+ existingTask.role !== agent.role ||
117
+ existingTask.dependsOn.length !== dependencyTaskIds.length ||
118
+ existingTask.dependsOn.some((dependencyId, index) => dependencyId !== dependencyTaskIds[index])) {
119
+ throw new DurableTaskRuntimeError(`Worker control message '${controlMessageId}' has conflicting task identity.`);
120
+ }
121
+ const existingAttempts = (snapshot.tasks[taskId]?.attemptIds ?? []).map((attemptId) => snapshot.attempts[attemptId]);
122
+ for (const attempt of existingAttempts) {
123
+ if (!attempt ||
124
+ attempt.dispatch.logicalLaneId !== agentId ||
125
+ attempt.dispatch.controlMessageId !== controlMessageId ||
126
+ attempt.dispatch.instructions !== instructions) {
127
+ throw new DurableTaskRuntimeError(`Worker control message '${controlMessageId}' has conflicting dispatch evidence.`);
128
+ }
129
+ }
130
+ const existingAttempt = existingAttempts.at(-1);
131
+ if (existingAttempt)
132
+ return existingAttempt;
133
+ }
134
+ if (agent.status !== "registered") {
135
+ throw new DurableTaskRuntimeError(`Logical worker agent '${agentId}' is not idle.`);
136
+ }
137
+ if (existingTask && !controlMessageId) {
93
138
  throw new DurableTaskRuntimeError(`Logical worker agent '${agentId}' already has turn ${sequence}.`);
94
139
  }
95
140
  return this.prepareNormalized({
@@ -99,9 +144,10 @@ export class DelegationOrchestrationLedger {
99
144
  role: agent.role,
100
145
  requiredCapabilities: contract.worker.authority.capabilities,
101
146
  riskBudget: contract.worker.profile.budget,
147
+ ...(priorTask.objectiveId.startsWith("goal:") ? { goalId: priorTask.objectiveId.slice("goal:".length) } : {}),
102
148
  taskContext: {
103
149
  requirementIds: prior.dispatch.requirementIds ?? [],
104
- dependsOnTaskIds: priorTask.dependsOn,
150
+ dependsOnTaskIds: dependencyTaskIds,
105
151
  acceptanceCriterionIds: priorTask.acceptanceCriterionIds,
106
152
  resourcePointerIds: prior.dispatch.resourcePointerIds,
107
153
  },
@@ -109,16 +155,24 @@ export class DelegationOrchestrationLedger {
109
155
  dispatchMetadata: {
110
156
  logicalLaneId: agentId,
111
157
  dispatchSequence: sequence,
158
+ ...(controlMessageId ? { controlMessageId } : {}),
159
+ ...(prior.dispatch.birthContextForkReference
160
+ ? { birthContextForkReference: prior.dispatch.birthContextForkReference }
161
+ : {}),
112
162
  },
113
163
  });
114
164
  }
115
- latestAgentAttempt(snapshot, agent) {
116
- return Object.values(snapshot.attempts)
117
- .filter((attempt) => attempt.agentId === agent.agentId)
118
- .sort((left, right) => left.createdAt.localeCompare(right.createdAt))
119
- .at(-1);
120
- }
121
165
  prepareNormalized(input) {
166
+ let birthContextForkReference;
167
+ try {
168
+ birthContextForkReference =
169
+ input.dispatchMetadata?.birthContextForkReference === undefined
170
+ ? undefined
171
+ : normalizeWorkerContextForkReference(input.dispatchMetadata.birthContextForkReference);
172
+ }
173
+ catch (error) {
174
+ throw new DurableTaskRuntimeError(error instanceof Error ? error.message : String(error));
175
+ }
122
176
  let snapshot = this.runtime.getSnapshot();
123
177
  const existingVerificationSubject = input.verificationOfTaskId
124
178
  ? snapshot.tasks[input.verificationOfTaskId]
@@ -130,6 +184,34 @@ export class DelegationOrchestrationLedger {
130
184
  const objectiveId = existingVerificationSubject?.task.objectiveId ??
131
185
  projectedGoal?.objectiveId ??
132
186
  (input.goalId ? goalObjectiveId(input.goalId) : `session:${this.sessionId}`);
187
+ const dependencyTaskIds = validateTaskDependencyIds(snapshot.tasks, objectiveId, input.taskContext?.dependsOnTaskIds);
188
+ const existingTask = snapshot.tasks[input.laneId]?.task;
189
+ if (existingTask &&
190
+ (existingTask.objectiveId !== objectiveId ||
191
+ existingTask.description !== input.instructions ||
192
+ existingTask.role !== input.role ||
193
+ existingTask.dependsOn.length !== dependencyTaskIds.length ||
194
+ existingTask.dependsOn.some((dependencyId, index) => dependencyId !== dependencyTaskIds[index]))) {
195
+ throw new DurableTaskRuntimeError(`Task '${input.laneId}' has conflicting durable dispatch identity.`);
196
+ }
197
+ const taskStateBeforeWrites = snapshot.tasks[input.laneId];
198
+ const activeAttemptBeforeWrites = taskStateBeforeWrites?.attemptIds
199
+ .map((attemptId) => snapshot.attempts[attemptId])
200
+ .find((attempt) => attempt !== undefined && activeAttempt(attempt));
201
+ for (const attemptId of taskStateBeforeWrites?.attemptIds ?? []) {
202
+ const durableReference = snapshot.attempts[attemptId]?.dispatch.birthContextForkReference;
203
+ if (!isDeepStrictEqual(durableReference, birthContextForkReference)) {
204
+ throw new DurableTaskRuntimeError(`Task '${input.laneId}' has a conflicting birth context fork reference.`);
205
+ }
206
+ }
207
+ const projectedEvidence = input.goal && objectiveId === projectedGoal?.objectiveId ? projectGoalAcceptanceEvidence(input.goal) : [];
208
+ if (projectedGoal)
209
+ this.runtime.assertObjectiveSynchronizationHeadroom(projectedGoal, projectedEvidence);
210
+ this.runtime.assertProjectionHeadroom({
211
+ objectives: snapshot.objectives[objectiveId] ? 0 : 1,
212
+ tasks: taskStateBeforeWrites ? 0 : 1,
213
+ attempts: activeAttemptBeforeWrites ? 0 : 1,
214
+ });
133
215
  if (input.goal && objectiveId === projectedGoal?.objectiveId) {
134
216
  this.synchronizeGoalState(input.goal);
135
217
  snapshot = this.runtime.getSnapshot();
@@ -142,39 +224,25 @@ export class DelegationOrchestrationLedger {
142
224
  });
143
225
  snapshot = this.runtime.getSnapshot();
144
226
  }
145
- if (!snapshot.tasks[input.laneId]) {
146
- const verificationSubject = input.verificationOfTaskId
147
- ? snapshot.tasks[input.verificationOfTaskId]
148
- : undefined;
149
- this.runtime.createTask({
150
- taskId: input.laneId,
151
- objectiveId,
152
- title: deriveWorkerTaskLabel(input.instructions, `Delegated ${input.role} work`),
153
- description: input.instructions,
154
- role: input.role,
155
- dependsOn: input.taskContext?.dependsOnTaskIds ?? [],
156
- requiredCapabilities: input.requiredCapabilities,
157
- acceptanceCriterionIds: input.taskContext?.acceptanceCriterionIds ?? [],
158
- riskBudget: input.riskBudget,
159
- ...(input.verificationOfTaskId
160
- ? {
161
- verificationOfTaskId: input.verificationOfTaskId,
162
- acceptanceCriterionIds: verificationSubject?.task.acceptanceCriterionIds ?? [],
163
- }
164
- : {}),
165
- });
166
- snapshot = this.runtime.getSnapshot();
167
- }
168
- const task = snapshot.tasks[input.laneId];
169
- if (!task)
170
- throw new DurableTaskRuntimeError(`Failed to create task '${input.laneId}'.`);
171
- const existing = [...task.attemptIds]
172
- .reverse()
173
- .map((attemptId) => snapshot.attempts[attemptId])
174
- .find((attempt) => attempt !== undefined && activeAttempt(attempt));
175
- if (existing)
176
- return existing;
177
- return this.runtime.queueAttempt(input.laneId, {
227
+ const verificationSubject = input.verificationOfTaskId ? snapshot.tasks[input.verificationOfTaskId] : undefined;
228
+ const taskInput = {
229
+ taskId: input.laneId,
230
+ objectiveId,
231
+ title: deriveWorkerTaskLabel(input.instructions, `Delegated ${input.role} work`),
232
+ description: input.instructions,
233
+ role: input.role,
234
+ dependsOn: dependencyTaskIds,
235
+ requiredCapabilities: input.requiredCapabilities,
236
+ acceptanceCriterionIds: input.taskContext?.acceptanceCriterionIds ?? [],
237
+ riskBudget: input.riskBudget,
238
+ ...(input.verificationOfTaskId
239
+ ? {
240
+ verificationOfTaskId: input.verificationOfTaskId,
241
+ acceptanceCriterionIds: verificationSubject?.task.acceptanceCriterionIds ?? [],
242
+ }
243
+ : {}),
244
+ };
245
+ const dispatch = {
178
246
  taskId: input.laneId,
179
247
  profileId: input.profileId,
180
248
  instructions: input.instructions,
@@ -183,13 +251,38 @@ export class DelegationOrchestrationLedger {
183
251
  requirementIds: input.taskContext?.requirementIds ?? [],
184
252
  ...(input.executionContract ? { executionContract: input.executionContract } : {}),
185
253
  ...input.dispatchMetadata,
186
- });
254
+ ...(birthContextForkReference ? { birthContextForkReference } : {}),
255
+ };
256
+ if (existingTask &&
257
+ (existingTask.title !== taskInput.title ||
258
+ existingTask.verificationOfTaskId !== taskInput.verificationOfTaskId ||
259
+ !isDeepStrictEqual(existingTask.requiredCapabilities, [...new Set(taskInput.requiredCapabilities)]) ||
260
+ !isDeepStrictEqual(existingTask.acceptanceCriterionIds, [...new Set(taskInput.acceptanceCriterionIds)]) ||
261
+ !isDeepStrictEqual(existingTask.riskBudget, taskInput.riskBudget))) {
262
+ throw new DurableTaskRuntimeError(`Task '${input.laneId}' has conflicting durable task identity.`);
263
+ }
264
+ if (activeAttemptBeforeWrites && !isDeepStrictEqual(activeAttemptBeforeWrites.dispatch, dispatch)) {
265
+ throw new DurableTaskRuntimeError(`Task '${input.laneId}' has conflicting durable dispatch identity.`);
266
+ }
267
+ if (!snapshot.tasks[input.laneId]) {
268
+ return this.runtime.prepareTaskAttempt({
269
+ ...taskInput,
270
+ }, dispatch).attempt;
271
+ }
272
+ const task = snapshot.tasks[input.laneId];
273
+ if (!task)
274
+ throw new DurableTaskRuntimeError(`Failed to create task '${input.laneId}'.`);
275
+ if (activeAttemptBeforeWrites)
276
+ return activeAttemptBeforeWrites;
277
+ return this.runtime.queueAttempt(input.laneId, dispatch);
187
278
  }
188
279
  synchronizeGoalState(goal) {
189
280
  const objective = projectGoalObjective(goal);
281
+ const evidence = projectGoalAcceptanceEvidence(goal);
282
+ this.runtime.assertObjectiveSynchronizationHeadroom(objective, evidence);
190
283
  this.runtime.ensureObjective(objective);
191
- for (const evidence of projectGoalAcceptanceEvidence(goal)) {
192
- this.runtime.recordObjectiveEvidence(objective.objectiveId, evidence);
284
+ for (const item of evidence) {
285
+ this.runtime.recordObjectiveEvidence(objective.objectiveId, item);
193
286
  }
194
287
  const status = this.runtime.getSnapshot().objectives[goalObjectiveId(goal.goalId)]?.objective.status;
195
288
  switch (goal.status) {
@@ -1 +1 @@
1
- {"version":3,"file":"delegation-ledger.js","sourceRoot":"","sources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AAE,CAAC,OAAO,CAAC,MAAM,KAAK,QAAQ,IAAI,OAAO,CAAC,QAAQ,CAAC,aAAa,KAAK,iBAAiB,CAChG,CAAC;IACH,CAAC;CACD","sourcesContent":["import type { WorkerDelegationTaskContext } from \"../delegation/worker-delegation-request.ts\";\nimport { deriveWorkerTaskLabel } from \"../delegation/worker-task-label.ts\";\nimport { hasGoalAcceptanceOverride } from \"../goals/goal-acceptance.ts\";\nimport type { GoalState } from \"../goals/goal-state.ts\";\nimport type {\n\tAgentBindingContract,\n\tAttemptUsageSnapshot,\n\tHarnessCapability,\n\tOrchestrationDispatchRequest,\n\tRiskBudget,\n\tWorkerExecutionContract,\n\tWorkerRole,\n} from \"./contracts.ts\";\nimport { OrchestrationEventStore } from \"./event-store.ts\";\nimport { type AttemptRuntimeState, DurableTaskRuntime, DurableTaskRuntimeError } from \"./task-runtime.ts\";\nimport { goalObjectiveId, projectGoalAcceptanceEvidence, projectGoalObjective } from \"./work-state-projection.ts\";\n\nexport interface DelegationLedgerOptions {\n\tagentDir: string;\n\tsessionId: string;\n\tnow?: () => number;\n}\n\nexport interface PrepareDelegationInput {\n\tlaneId: string;\n\tinstructions: string;\n\tparentAgentId?: string;\n\texecutionContract: WorkerExecutionContract;\n\trequiredCapabilities: readonly HarnessCapability[];\n\tgoal?: GoalState;\n\tverificationOfTaskId?: string;\n\ttaskContext?: WorkerDelegationTaskContext;\n}\n\nexport interface PrepareManagedDelegationInput {\n\tlaneId: string;\n\tdispatchSequence: number;\n\tinstructions: string;\n\tprofileId: string;\n\tprovider: string;\n\tauthorizationId: string;\n\trole: WorkerRole;\n\triskBudget: RiskBudget;\n\tgoal?: GoalState;\n\tgoalId?: string;\n\tworktreeLaneKey?: string;\n}\n\nexport interface StartedDelegationAttempt {\n\tobjectiveId: string;\n\ttaskId: string;\n\tattemptId: string;\n\tleaseId: string;\n\tfencingToken: number;\n\texpiresAt: string;\n}\n\nexport interface PrepareAgentTurnInput {\n\tagentId: string;\n\tinstructions: string;\n}\n\nfunction activeAttempt(attempt: AttemptRuntimeState): boolean {\n\treturn attempt.status === \"queued\" || attempt.status === \"leased\" || attempt.status === \"running\";\n}\n\n/**\n * Durable adapter for in-process delegated completions. It records the dispatch before execution,\n * fences interrupted completions on restart, and returns queued work for event-driven re-dispatch.\n * It deliberately does not pretend an isolated completion has a resumable model transcript.\n */\nexport class DelegationOrchestrationLedger {\n\treadonly runtime: DurableTaskRuntime;\n\tprivate readonly sessionId: string;\n\n\tconstructor(options: DelegationLedgerOptions) {\n\t\tthis.sessionId = options.sessionId;\n\t\tthis.runtime = new DurableTaskRuntime({\n\t\t\tstore: new OrchestrationEventStore({ agentDir: options.agentDir, sessionId: options.sessionId }),\n\t\t\tnow: options.now,\n\t\t});\n\t}\n\n\tprepare(input: PrepareDelegationInput): AttemptRuntimeState {\n\t\tconst profile = input.executionContract.worker.profile;\n\t\treturn this.prepareNormalized({\n\t\t\tlaneId: input.laneId,\n\t\t\tinstructions: input.instructions,\n\t\t\tprofileId: profile.profileId,\n\t\t\trole: profile.role,\n\t\t\trequiredCapabilities: input.requiredCapabilities,\n\t\t\triskBudget: profile.budget,\n\t\t\t...(input.parentAgentId ? { parentAgentId: input.parentAgentId } : {}),\n\t\t\texecutionContract: input.executionContract,\n\t\t\t...(input.goal ? { goal: input.goal } : {}),\n\t\t\t...(input.verificationOfTaskId ? { verificationOfTaskId: input.verificationOfTaskId } : {}),\n\t\t\t...(input.taskContext ? { taskContext: input.taskContext } : {}),\n\t\t\tdispatchMetadata: { logicalLaneId: input.laneId },\n\t\t});\n\t}\n\n\tprepareManaged(input: PrepareManagedDelegationInput): AttemptRuntimeState {\n\t\tif (!Number.isSafeInteger(input.dispatchSequence) || input.dispatchSequence < 1) {\n\t\t\tthrow new DurableTaskRuntimeError(\"Managed dispatch sequence must be a positive integer.\");\n\t\t}\n\t\tconst taskId = `${input.laneId}:turn:${input.dispatchSequence}`;\n\t\treturn this.prepareNormalized({\n\t\t\tlaneId: taskId,\n\t\t\tinstructions: input.instructions,\n\t\t\tprofileId: input.profileId,\n\t\t\trole: input.role,\n\t\t\trequiredCapabilities: [],\n\t\t\triskBudget: input.riskBudget,\n\t\t\t...(input.goal ? { goal: input.goal } : {}),\n\t\t\t...(input.goalId ? { goalId: input.goalId } : {}),\n\t\t\tdispatchMetadata: {\n\t\t\t\texecutionKind: \"managed-process\",\n\t\t\t\tlogicalLaneId: input.laneId,\n\t\t\t\tdispatchSequence: input.dispatchSequence,\n\t\t\t\tprovider: input.provider,\n\t\t\t\tauthorizationId: input.authorizationId,\n\t\t\t\t...(input.worktreeLaneKey ? { worktreeLaneKey: input.worktreeLaneKey } : {}),\n\t\t\t},\n\t\t});\n\t}\n\n\t/**\n\t * Queue one new turn for an existing logical agent. The agent identity and its immutable\n\t * execution contract are inherited from the last bound turn; the durable task and attempt ids\n\t * are intentionally new so retries, leases, and terminal evidence never collide across turns.\n\t */\n\tprepareAgentTurn(input: PrepareAgentTurnInput): AttemptRuntimeState {\n\t\tconst agentId = input.agentId.trim();\n\t\tconst instructions = input.instructions.trim();\n\t\tif (!agentId) throw new DurableTaskRuntimeError(\"Logical worker agent id is required.\");\n\t\tif (!instructions) throw new DurableTaskRuntimeError(\"Worker follow-up instructions are required.\");\n\t\tconst snapshot = this.runtime.getSnapshot();\n\t\tconst agent = snapshot.agents[agentId];\n\t\tif (!agent) throw new DurableTaskRuntimeError(`Unknown logical worker agent '${agentId}'.`);\n\t\tif (agent.status !== \"registered\") {\n\t\t\tthrow new DurableTaskRuntimeError(`Logical worker agent '${agentId}' is not idle.`);\n\t\t}\n\t\tconst prior = this.latestAgentAttempt(snapshot, agent);\n\t\tconst contract = prior?.dispatch.executionContract;\n\t\tif (!prior || !contract) {\n\t\t\tthrow new DurableTaskRuntimeError(`Logical worker agent '${agentId}' has no immutable execution contract.`);\n\t\t}\n\t\tconst priorTask = snapshot.tasks[prior.taskId]?.task;\n\t\tif (!priorTask) throw new DurableTaskRuntimeError(`Logical worker agent '${agentId}' has no prior durable task.`);\n\t\tconst sequence = Object.values(snapshot.attempts).filter((attempt) => attempt.agentId === agentId).length + 1;\n\t\tconst taskId = `${agentId}:turn:${sequence}`;\n\t\tif (snapshot.tasks[taskId]) {\n\t\t\tthrow new DurableTaskRuntimeError(`Logical worker agent '${agentId}' already has turn ${sequence}.`);\n\t\t}\n\t\treturn this.prepareNormalized({\n\t\t\tlaneId: taskId,\n\t\t\tinstructions,\n\t\t\tprofileId: contract.worker.profile.profileId,\n\t\t\trole: agent.role,\n\t\t\trequiredCapabilities: contract.worker.authority.capabilities,\n\t\t\triskBudget: contract.worker.profile.budget,\n\t\t\ttaskContext: {\n\t\t\t\trequirementIds: prior.dispatch.requirementIds ?? [],\n\t\t\t\tdependsOnTaskIds: priorTask.dependsOn,\n\t\t\t\tacceptanceCriterionIds: priorTask.acceptanceCriterionIds,\n\t\t\t\tresourcePointerIds: prior.dispatch.resourcePointerIds,\n\t\t\t},\n\t\t\texecutionContract: contract,\n\t\t\tdispatchMetadata: {\n\t\t\t\tlogicalLaneId: agentId,\n\t\t\t\tdispatchSequence: sequence,\n\t\t\t},\n\t\t});\n\t}\n\n\tprivate latestAgentAttempt(\n\t\tsnapshot: ReturnType<DurableTaskRuntime[\"getSnapshot\"]>,\n\t\tagent: AgentBindingContract,\n\t): AttemptRuntimeState | undefined {\n\t\treturn Object.values(snapshot.attempts)\n\t\t\t.filter((attempt) => attempt.agentId === agent.agentId)\n\t\t\t.sort((left, right) => left.createdAt.localeCompare(right.createdAt))\n\t\t\t.at(-1);\n\t}\n\n\tprivate prepareNormalized(input: {\n\t\tlaneId: string;\n\t\tinstructions: string;\n\t\tprofileId: string;\n\t\trole: WorkerRole;\n\t\trequiredCapabilities: readonly HarnessCapability[];\n\t\triskBudget: RiskBudget;\n\t\tparentAgentId?: string;\n\t\tgoal?: GoalState;\n\t\tgoalId?: string;\n\t\tverificationOfTaskId?: string;\n\t\ttaskContext?: WorkerDelegationTaskContext;\n\t\texecutionContract?: WorkerExecutionContract;\n\t\tdispatchMetadata?: Pick<\n\t\t\tOrchestrationDispatchRequest,\n\t\t\t\"executionKind\" | \"logicalLaneId\" | \"dispatchSequence\" | \"provider\" | \"authorizationId\" | \"worktreeLaneKey\"\n\t\t>;\n\t}): AttemptRuntimeState {\n\t\tlet snapshot = this.runtime.getSnapshot();\n\t\tconst existingVerificationSubject = input.verificationOfTaskId\n\t\t\t? snapshot.tasks[input.verificationOfTaskId]\n\t\t\t: undefined;\n\t\tif (input.verificationOfTaskId && !existingVerificationSubject) {\n\t\t\tthrow new DurableTaskRuntimeError(`Unknown verification subject '${input.verificationOfTaskId}'.`);\n\t\t}\n\t\tconst projectedGoal = input.goal ? projectGoalObjective(input.goal) : undefined;\n\t\tconst objectiveId =\n\t\t\texistingVerificationSubject?.task.objectiveId ??\n\t\t\tprojectedGoal?.objectiveId ??\n\t\t\t(input.goalId ? goalObjectiveId(input.goalId) : `session:${this.sessionId}`);\n\t\tif (input.goal && objectiveId === projectedGoal?.objectiveId) {\n\t\t\tthis.synchronizeGoalState(input.goal);\n\t\t\tsnapshot = this.runtime.getSnapshot();\n\t\t} else if (!snapshot.objectives[objectiveId]) {\n\t\t\tthis.runtime.createObjective({\n\t\t\t\tobjectiveId,\n\t\t\t\ttitle: input.goalId ? `Goal ${input.goalId}` : `Session ${this.sessionId}`,\n\t\t\t\tdescription: input.goalId ? \"Externally managed goal work\" : \"Session-scoped delegated work\",\n\t\t\t});\n\t\t\tsnapshot = this.runtime.getSnapshot();\n\t\t}\n\n\t\tif (!snapshot.tasks[input.laneId]) {\n\t\t\tconst verificationSubject = input.verificationOfTaskId\n\t\t\t\t? snapshot.tasks[input.verificationOfTaskId]\n\t\t\t\t: undefined;\n\t\t\tthis.runtime.createTask({\n\t\t\t\ttaskId: input.laneId,\n\t\t\t\tobjectiveId,\n\t\t\t\ttitle: deriveWorkerTaskLabel(input.instructions, `Delegated ${input.role} work`),\n\t\t\t\tdescription: input.instructions,\n\t\t\t\trole: input.role,\n\t\t\t\tdependsOn: input.taskContext?.dependsOnTaskIds ?? [],\n\t\t\t\trequiredCapabilities: input.requiredCapabilities,\n\t\t\t\tacceptanceCriterionIds: input.taskContext?.acceptanceCriterionIds ?? [],\n\t\t\t\triskBudget: input.riskBudget,\n\t\t\t\t...(input.verificationOfTaskId\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tverificationOfTaskId: input.verificationOfTaskId,\n\t\t\t\t\t\t\tacceptanceCriterionIds: verificationSubject?.task.acceptanceCriterionIds ?? [],\n\t\t\t\t\t\t}\n\t\t\t\t\t: {}),\n\t\t\t});\n\t\t\tsnapshot = this.runtime.getSnapshot();\n\t\t}\n\n\t\tconst task = snapshot.tasks[input.laneId];\n\t\tif (!task) throw new DurableTaskRuntimeError(`Failed to create task '${input.laneId}'.`);\n\t\tconst existing = [...task.attemptIds]\n\t\t\t.reverse()\n\t\t\t.map((attemptId) => snapshot.attempts[attemptId])\n\t\t\t.find((attempt): attempt is AttemptRuntimeState => attempt !== undefined && activeAttempt(attempt));\n\t\tif (existing) return existing;\n\n\t\treturn this.runtime.queueAttempt(input.laneId, {\n\t\t\ttaskId: input.laneId,\n\t\t\tprofileId: input.profileId,\n\t\t\tinstructions: input.instructions,\n\t\t\tresourcePointerIds: input.taskContext?.resourcePointerIds ?? [],\n\t\t\t...(input.parentAgentId ? { parentAgentId: input.parentAgentId } : {}),\n\t\t\trequirementIds: input.taskContext?.requirementIds ?? [],\n\t\t\t...(input.executionContract ? { executionContract: input.executionContract } : {}),\n\t\t\t...input.dispatchMetadata,\n\t\t});\n\t}\n\n\tsynchronizeGoalState(goal: GoalState): void {\n\t\tconst objective = projectGoalObjective(goal);\n\t\tthis.runtime.ensureObjective(objective);\n\t\tfor (const evidence of projectGoalAcceptanceEvidence(goal)) {\n\t\t\tthis.runtime.recordObjectiveEvidence(objective.objectiveId, evidence);\n\t\t}\n\t\tconst status = this.runtime.getSnapshot().objectives[goalObjectiveId(goal.goalId)]?.objective.status;\n\t\tswitch (goal.status) {\n\t\t\tcase \"active\":\n\t\t\t\tif (status === \"paused\") this.runtime.resumeObjective(objective.objectiveId);\n\t\t\t\tbreak;\n\t\t\tcase \"paused\":\n\t\t\tcase \"blocked\":\n\t\t\tcase \"usage_limited\":\n\t\t\tcase \"budget_limited\":\n\t\t\t\tif (status === \"active\") this.runtime.pauseObjective(objective.objectiveId);\n\t\t\t\tbreak;\n\t\t\tcase \"cancelled\":\n\t\t\t\tif (status !== \"cancelled\") this.runtime.cancelObjective(objective.objectiveId);\n\t\t\t\tbreak;\n\t\t\tcase \"completed\":\n\t\t\t\tif (status !== \"completed\") {\n\t\t\t\t\tthis.runtime.completeObjectiveFromOwner(objective.objectiveId, hasGoalAcceptanceOverride(goal));\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\tstart(\n\t\tattemptId: string,\n\t\tleaseTtlMs: number,\n\t\townerId = `in-process:${this.sessionId}`,\n\t\tagentId?: string,\n\t): StartedDelegationAttempt {\n\t\tconst snapshot = this.runtime.getSnapshot();\n\t\tconst attempt = snapshot.attempts[attemptId];\n\t\tif (!attempt) throw new DurableTaskRuntimeError(`Unknown attempt '${attemptId}'.`);\n\t\tconst task = snapshot.tasks[attempt.taskId];\n\t\tif (!task) throw new DurableTaskRuntimeError(`Unknown task '${attempt.taskId}'.`);\n\t\tconst lease = this.runtime.leaseAttempt(attemptId, ownerId, leaseTtlMs, agentId);\n\t\tthis.runtime.startAttempt(attemptId, lease.leaseId, lease.fencingToken);\n\t\treturn {\n\t\t\tobjectiveId: task.task.objectiveId,\n\t\t\ttaskId: task.task.taskId,\n\t\t\tattemptId,\n\t\t\tleaseId: lease.leaseId,\n\t\t\tfencingToken: lease.fencingToken,\n\t\t\texpiresAt: lease.expiresAt,\n\t\t};\n\t}\n\n\tcancel(attemptId: string, reasonCode: string): void {\n\t\tthis.runtime.cancelAttempt(attemptId, reasonCode);\n\t}\n\n\t/** Latest fenced cumulative usage, if this attempt has crossed a durable checkpoint boundary. */\n\tgetAttemptUsage(attemptId: string): AttemptUsageSnapshot | undefined {\n\t\tconst snapshot = this.runtime.getSnapshot();\n\t\tconst attempt = snapshot.attempts[attemptId];\n\t\tif (!attempt) throw new DurableTaskRuntimeError(`Unknown attempt '${attemptId}'.`);\n\t\tfor (const checkpointId of [...attempt.checkpointIds].reverse()) {\n\t\t\tconst usage = snapshot.checkpoints[checkpointId]?.usage;\n\t\t\tif (usage) return structuredClone(usage);\n\t\t}\n\t\treturn undefined;\n\t}\n\n\t/** Fence interrupted isolated completions and queue one replacement attempt per task. */\n\trecoverQueuedDispatches(): AttemptRuntimeState[] {\n\t\tthis.runtime.recoverInterruptedUnboundAttempts((attempt) => attempt.dispatch.executionKind !== \"managed-process\");\n\t\tlet snapshot = this.runtime.getSnapshot();\n\t\tfor (const task of Object.values(snapshot.tasks)) {\n\t\t\tconst attempts = task.attemptIds.map((attemptId) => snapshot.attempts[attemptId]).filter(Boolean);\n\t\t\tif (attempts.some((attempt) => attempt && activeAttempt(attempt))) continue;\n\t\t\tconst interrupted = [...attempts].reverse().find((attempt) => attempt?.status === \"expired\");\n\t\t\tif (!interrupted || task.task.status !== \"ready\") continue;\n\t\t\tconst maxAttempts = task.task.riskBudget.maxAttempts;\n\t\t\tif (maxAttempts !== undefined && task.attemptIds.length >= maxAttempts) {\n\t\t\t\tthis.runtime.failTask(task.task.taskId, \"attempt_budget_exhausted\");\n\t\t\t\tsnapshot = this.runtime.getSnapshot();\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tthis.runtime.queueAttempt(task.task.taskId, interrupted.dispatch);\n\t\t\tsnapshot = this.runtime.getSnapshot();\n\t\t}\n\t\treturn Object.values(snapshot.attempts).filter(\n\t\t\t(attempt) => attempt.status === \"queued\" && attempt.dispatch.executionKind !== \"managed-process\",\n\t\t);\n\t}\n}\n"]}
1
+ {"version":3,"file":"delegation-ledger.js","sourceRoot":"","sources":["../../../src/core/orchestration/delegation-ledger.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAA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W,CAAC;YACrD,IAAI,WAAW,KAAK,SAAS,IAAI,IAAI,CAAC,UAAU,CAAC,MAAM,IAAI,WAAW,EAAE,CAAC;gBACxE,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE,0BAA0B,CAAC,CAAC;gBACpE,QAAQ,GAAG,IAAI,CAAC,OAAO,CAAC,WAAW,EAAE,CAAC;gBACtC,SAAS;YACV,CAAC;YACD,IAAI,CAAC,OAAO,CAAC,YAAY,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE,WAAW,CAAC,QAAQ,CAAC,CAAC;YAClE,QAAQ,GAAG,IAAI,CAAC,OAAO,CAAC,WAAW,EAAE,CAAC;QACvC,CAAC;QACD,OAAO,MAAM,CAAC,MAAM,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC,MAAM,CAC7C,CAAC,OAAO,EAAE,EAAE,CAAC,OAAO,CAAC,MAAM,KAAK,QAAQ,IAAI,OAAO,CAAC,QAAQ,CAAC,aAAa,KAAK,iBAAiB,CAChG,CAAC;IACH,CAAC;CACD","sourcesContent":["import { createHash } from \"node:crypto\";\nimport { isDeepStrictEqual } from \"node:util\";\nimport type { WorkerDelegationTaskContext } from \"../delegation/worker-delegation-request.ts\";\nimport { deriveWorkerTaskLabel } from \"../delegation/worker-task-label.ts\";\nimport { hasGoalAcceptanceOverride } from \"../goals/goal-acceptance.ts\";\nimport type { GoalState } from \"../goals/goal-state.ts\";\nimport { latestAgentAttemptByDurableOrder } from \"./attempt-ordering.ts\";\nimport type {\n\tAttemptUsageSnapshot,\n\tHarnessCapability,\n\tOrchestrationDispatchRequest,\n\tRiskBudget,\n\tWorkerExecutionContract,\n\tWorkerRole,\n} from \"./contracts.ts\";\nimport { MAX_ORCHESTRATION_IDENTIFIER_LENGTH } from \"./contracts.ts\";\nimport { OrchestrationEventStore } from \"./event-store.ts\";\nimport {\n\ttype AttemptRuntimeState,\n\tDurableTaskRuntime,\n\tDurableTaskRuntimeError,\n\tvalidateTaskDependencyIds,\n} from \"./task-runtime.ts\";\nimport { goalObjectiveId, projectGoalAcceptanceEvidence, projectGoalObjective } from \"./work-state-projection.ts\";\nimport {\n\tnormalizeWorkerContextForkReference,\n\ttype WorkerContextForkReference,\n} from \"./worker-context-fork-reference.ts\";\n\nexport interface DelegationLedgerOptions {\n\tagentDir: string;\n\tsessionId: string;\n\tnow?: () => number;\n\tstore?: OrchestrationEventStore;\n}\n\nexport interface PrepareDelegationInput {\n\tlaneId: string;\n\tinstructions: string;\n\tparentAgentId?: string;\n\texecutionContract: WorkerExecutionContract;\n\trequiredCapabilities: readonly HarnessCapability[];\n\tgoal?: GoalState;\n\tverificationOfTaskId?: string;\n\ttaskContext?: WorkerDelegationTaskContext;\n\tbirthContextForkReference?: WorkerContextForkReference;\n}\n\nexport interface PrepareManagedDelegationInput {\n\tlaneId: string;\n\tdispatchSequence: number;\n\tinstructions: string;\n\tprofileId: string;\n\tprovider: string;\n\tauthorizationId: string;\n\trole: WorkerRole;\n\triskBudget: RiskBudget;\n\tgoal?: GoalState;\n\tgoalId?: string;\n\tworktreeLaneKey?: string;\n}\n\nexport interface StartedDelegationAttempt {\n\tobjectiveId: string;\n\ttaskId: string;\n\tattemptId: string;\n\tleaseId: string;\n\tfencingToken: number;\n\texpiresAt: string;\n}\n\nexport interface PrepareAgentTurnInput {\n\tagentId: string;\n\tinstructions: string;\n\tcontrolMessageId?: string;\n\tdependsOnTaskIds?: readonly string[];\n}\n\nfunction activeAttempt(attempt: AttemptRuntimeState): boolean {\n\treturn attempt.status === \"queued\" || attempt.status === \"leased\" || attempt.status === \"running\";\n}\n\nfunction mailboxTurnTaskId(agentId: string, controlMessageId: string): string {\n\treturn `mailbox-turn-${createHash(\"sha256\")\n\t\t.update(\"pi-worker-agent-mailbox-turn-v1\")\n\t\t.update(\"\\0\")\n\t\t.update(agentId)\n\t\t.update(\"\\0\")\n\t\t.update(controlMessageId)\n\t\t.digest(\"hex\")}`;\n}\n\n/**\n * Durable adapter for in-process delegated completions. It records the dispatch before execution,\n * fences interrupted completions on restart, and returns queued work for event-driven re-dispatch.\n * It deliberately does not pretend an isolated completion has a resumable model transcript.\n */\nexport class DelegationOrchestrationLedger {\n\treadonly runtime: DurableTaskRuntime;\n\tprivate readonly sessionId: string;\n\n\tconstructor(options: DelegationLedgerOptions) {\n\t\tthis.sessionId = options.sessionId;\n\t\tthis.runtime = new DurableTaskRuntime({\n\t\t\tstore:\n\t\t\t\toptions.store ?? new OrchestrationEventStore({ agentDir: options.agentDir, sessionId: options.sessionId }),\n\t\t\tnow: options.now,\n\t\t});\n\t}\n\n\tprepare(input: PrepareDelegationInput): AttemptRuntimeState {\n\t\tconst profile = input.executionContract.worker.profile;\n\t\treturn this.prepareNormalized({\n\t\t\tlaneId: input.laneId,\n\t\t\tinstructions: input.instructions,\n\t\t\tprofileId: profile.profileId,\n\t\t\trole: profile.role,\n\t\t\trequiredCapabilities: input.requiredCapabilities,\n\t\t\triskBudget: profile.budget,\n\t\t\t...(input.parentAgentId ? { parentAgentId: input.parentAgentId } : {}),\n\t\t\texecutionContract: input.executionContract,\n\t\t\t...(input.goal ? { goal: input.goal } : {}),\n\t\t\t...(input.verificationOfTaskId ? { verificationOfTaskId: input.verificationOfTaskId } : {}),\n\t\t\t...(input.taskContext ? { taskContext: input.taskContext } : {}),\n\t\t\tdispatchMetadata: {\n\t\t\t\tlogicalLaneId: input.laneId,\n\t\t\t\t...(input.birthContextForkReference ? { birthContextForkReference: input.birthContextForkReference } : {}),\n\t\t\t},\n\t\t});\n\t}\n\n\tprepareManaged(input: PrepareManagedDelegationInput): AttemptRuntimeState {\n\t\tif (!Number.isSafeInteger(input.dispatchSequence) || input.dispatchSequence < 1) {\n\t\t\tthrow new DurableTaskRuntimeError(\"Managed dispatch sequence must be a positive integer.\");\n\t\t}\n\t\tconst taskId = `${input.laneId}:turn:${input.dispatchSequence}`;\n\t\treturn this.prepareNormalized({\n\t\t\tlaneId: taskId,\n\t\t\tinstructions: input.instructions,\n\t\t\tprofileId: input.profileId,\n\t\t\trole: input.role,\n\t\t\trequiredCapabilities: [],\n\t\t\triskBudget: input.riskBudget,\n\t\t\t...(input.goal ? { goal: input.goal } : {}),\n\t\t\t...(input.goalId ? { goalId: input.goalId } : {}),\n\t\t\tdispatchMetadata: {\n\t\t\t\texecutionKind: \"managed-process\",\n\t\t\t\tlogicalLaneId: input.laneId,\n\t\t\t\tdispatchSequence: input.dispatchSequence,\n\t\t\t\tprovider: input.provider,\n\t\t\t\tauthorizationId: input.authorizationId,\n\t\t\t\t...(input.worktreeLaneKey ? { worktreeLaneKey: input.worktreeLaneKey } : {}),\n\t\t\t},\n\t\t});\n\t}\n\n\t/**\n\t * Queue one new turn for an existing logical agent. The agent identity and its immutable\n\t * execution contract are inherited from the last bound turn. Each distinct control message owns\n\t * one deterministic task/attempt identity; exact retries adopt it instead of minting new work.\n\t */\n\tprepareAgentTurn(input: PrepareAgentTurnInput): AttemptRuntimeState {\n\t\tconst agentId = input.agentId.trim();\n\t\tconst instructions = input.instructions.trim();\n\t\tconst controlMessageId = input.controlMessageId?.trim();\n\t\tif (!agentId) throw new DurableTaskRuntimeError(\"Logical worker agent id is required.\");\n\t\tif (!instructions) throw new DurableTaskRuntimeError(\"Worker follow-up instructions are required.\");\n\t\tif (\n\t\t\tinput.controlMessageId !== undefined &&\n\t\t\t(!controlMessageId || controlMessageId.length > MAX_ORCHESTRATION_IDENTIFIER_LENGTH)\n\t\t) {\n\t\t\tthrow new DurableTaskRuntimeError(\"Worker control message id is invalid.\");\n\t\t}\n\t\tconst snapshot = this.runtime.getSnapshot();\n\t\tconst agent = snapshot.agents[agentId];\n\t\tif (!agent) throw new DurableTaskRuntimeError(`Unknown logical worker agent '${agentId}'.`);\n\t\tconst agentAttempts = Object.values(snapshot.attempts).filter(\n\t\t\t(attempt) => attempt.agentId === agentId || attempt.dispatch.logicalLaneId === agentId,\n\t\t);\n\t\tconst sequence = agentAttempts.length + 1;\n\t\tconst taskId = controlMessageId ? mailboxTurnTaskId(agentId, controlMessageId) : `${agentId}:turn:${sequence}`;\n\t\tconst existingTask = snapshot.tasks[taskId]?.task;\n\t\tconst prior = latestAgentAttemptByDurableOrder(snapshot, agent.agentId);\n\t\tconst contract = prior?.dispatch.executionContract;\n\t\tif (!prior || !contract) {\n\t\t\tthrow new DurableTaskRuntimeError(`Logical worker agent '${agentId}' has no immutable execution contract.`);\n\t\t}\n\t\tconst priorTask = snapshot.tasks[prior.taskId]?.task;\n\t\tif (!priorTask) throw new DurableTaskRuntimeError(`Logical worker agent '${agentId}' has no prior durable task.`);\n\t\tconst dependencyTaskIds = validateTaskDependencyIds(\n\t\t\tsnapshot.tasks,\n\t\t\texistingTask?.objectiveId ?? priorTask.objectiveId,\n\t\t\tinput.dependsOnTaskIds,\n\t\t);\n\t\tif (existingTask && controlMessageId) {\n\t\t\tif (\n\t\t\t\texistingTask.description !== instructions ||\n\t\t\t\texistingTask.role !== agent.role ||\n\t\t\t\texistingTask.dependsOn.length !== dependencyTaskIds.length ||\n\t\t\t\texistingTask.dependsOn.some((dependencyId, index) => dependencyId !== dependencyTaskIds[index])\n\t\t\t) {\n\t\t\t\tthrow new DurableTaskRuntimeError(\n\t\t\t\t\t`Worker control message '${controlMessageId}' has conflicting task identity.`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst existingAttempts = (snapshot.tasks[taskId]?.attemptIds ?? []).map(\n\t\t\t\t(attemptId) => snapshot.attempts[attemptId],\n\t\t\t);\n\t\t\tfor (const attempt of existingAttempts) {\n\t\t\t\tif (\n\t\t\t\t\t!attempt ||\n\t\t\t\t\tattempt.dispatch.logicalLaneId !== agentId ||\n\t\t\t\t\tattempt.dispatch.controlMessageId !== controlMessageId ||\n\t\t\t\t\tattempt.dispatch.instructions !== instructions\n\t\t\t\t) {\n\t\t\t\t\tthrow new DurableTaskRuntimeError(\n\t\t\t\t\t\t`Worker control message '${controlMessageId}' has conflicting dispatch evidence.`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst existingAttempt = existingAttempts.at(-1);\n\t\t\tif (existingAttempt) return existingAttempt;\n\t\t}\n\t\tif (agent.status !== \"registered\") {\n\t\t\tthrow new DurableTaskRuntimeError(`Logical worker agent '${agentId}' is not idle.`);\n\t\t}\n\t\tif (existingTask && !controlMessageId) {\n\t\t\tthrow new DurableTaskRuntimeError(`Logical worker agent '${agentId}' already has turn ${sequence}.`);\n\t\t}\n\t\treturn this.prepareNormalized({\n\t\t\tlaneId: taskId,\n\t\t\tinstructions,\n\t\t\tprofileId: contract.worker.profile.profileId,\n\t\t\trole: agent.role,\n\t\t\trequiredCapabilities: contract.worker.authority.capabilities,\n\t\t\triskBudget: contract.worker.profile.budget,\n\t\t\t...(priorTask.objectiveId.startsWith(\"goal:\") ? { goalId: priorTask.objectiveId.slice(\"goal:\".length) } : {}),\n\t\t\ttaskContext: {\n\t\t\t\trequirementIds: prior.dispatch.requirementIds ?? [],\n\t\t\t\tdependsOnTaskIds: dependencyTaskIds,\n\t\t\t\tacceptanceCriterionIds: priorTask.acceptanceCriterionIds,\n\t\t\t\tresourcePointerIds: prior.dispatch.resourcePointerIds,\n\t\t\t},\n\t\t\texecutionContract: contract,\n\t\t\tdispatchMetadata: {\n\t\t\t\tlogicalLaneId: agentId,\n\t\t\t\tdispatchSequence: sequence,\n\t\t\t\t...(controlMessageId ? { controlMessageId } : {}),\n\t\t\t\t...(prior.dispatch.birthContextForkReference\n\t\t\t\t\t? { birthContextForkReference: prior.dispatch.birthContextForkReference }\n\t\t\t\t\t: {}),\n\t\t\t},\n\t\t});\n\t}\n\n\tprivate prepareNormalized(input: {\n\t\tlaneId: string;\n\t\tinstructions: string;\n\t\tprofileId: string;\n\t\trole: WorkerRole;\n\t\trequiredCapabilities: readonly HarnessCapability[];\n\t\triskBudget: RiskBudget;\n\t\tparentAgentId?: string;\n\t\tgoal?: GoalState;\n\t\tgoalId?: string;\n\t\tverificationOfTaskId?: string;\n\t\ttaskContext?: WorkerDelegationTaskContext;\n\t\texecutionContract?: WorkerExecutionContract;\n\t\tdispatchMetadata?: Pick<\n\t\t\tOrchestrationDispatchRequest,\n\t\t\t| \"executionKind\"\n\t\t\t| \"logicalLaneId\"\n\t\t\t| \"dispatchSequence\"\n\t\t\t| \"controlMessageId\"\n\t\t\t| \"provider\"\n\t\t\t| \"authorizationId\"\n\t\t\t| \"worktreeLaneKey\"\n\t\t\t| \"birthContextForkReference\"\n\t\t>;\n\t}): AttemptRuntimeState {\n\t\tlet birthContextForkReference: WorkerContextForkReference | undefined;\n\t\ttry {\n\t\t\tbirthContextForkReference =\n\t\t\t\tinput.dispatchMetadata?.birthContextForkReference === undefined\n\t\t\t\t\t? undefined\n\t\t\t\t\t: normalizeWorkerContextForkReference(input.dispatchMetadata.birthContextForkReference);\n\t\t} catch (error) {\n\t\t\tthrow new DurableTaskRuntimeError(error instanceof Error ? error.message : String(error));\n\t\t}\n\t\tlet snapshot = this.runtime.getSnapshot();\n\t\tconst existingVerificationSubject = input.verificationOfTaskId\n\t\t\t? snapshot.tasks[input.verificationOfTaskId]\n\t\t\t: undefined;\n\t\tif (input.verificationOfTaskId && !existingVerificationSubject) {\n\t\t\tthrow new DurableTaskRuntimeError(`Unknown verification subject '${input.verificationOfTaskId}'.`);\n\t\t}\n\t\tconst projectedGoal = input.goal ? projectGoalObjective(input.goal) : undefined;\n\t\tconst objectiveId =\n\t\t\texistingVerificationSubject?.task.objectiveId ??\n\t\t\tprojectedGoal?.objectiveId ??\n\t\t\t(input.goalId ? goalObjectiveId(input.goalId) : `session:${this.sessionId}`);\n\t\tconst dependencyTaskIds = validateTaskDependencyIds(\n\t\t\tsnapshot.tasks,\n\t\t\tobjectiveId,\n\t\t\tinput.taskContext?.dependsOnTaskIds,\n\t\t);\n\t\tconst existingTask = snapshot.tasks[input.laneId]?.task;\n\t\tif (\n\t\t\texistingTask &&\n\t\t\t(existingTask.objectiveId !== objectiveId ||\n\t\t\t\texistingTask.description !== input.instructions ||\n\t\t\t\texistingTask.role !== input.role ||\n\t\t\t\texistingTask.dependsOn.length !== dependencyTaskIds.length ||\n\t\t\t\texistingTask.dependsOn.some((dependencyId, index) => dependencyId !== dependencyTaskIds[index]))\n\t\t) {\n\t\t\tthrow new DurableTaskRuntimeError(`Task '${input.laneId}' has conflicting durable dispatch identity.`);\n\t\t}\n\t\tconst taskStateBeforeWrites = snapshot.tasks[input.laneId];\n\t\tconst activeAttemptBeforeWrites = taskStateBeforeWrites?.attemptIds\n\t\t\t.map((attemptId) => snapshot.attempts[attemptId])\n\t\t\t.find((attempt): attempt is AttemptRuntimeState => attempt !== undefined && activeAttempt(attempt));\n\t\tfor (const attemptId of taskStateBeforeWrites?.attemptIds ?? []) {\n\t\t\tconst durableReference = snapshot.attempts[attemptId]?.dispatch.birthContextForkReference;\n\t\t\tif (!isDeepStrictEqual(durableReference, birthContextForkReference)) {\n\t\t\t\tthrow new DurableTaskRuntimeError(`Task '${input.laneId}' has a conflicting birth context fork reference.`);\n\t\t\t}\n\t\t}\n\t\tconst projectedEvidence =\n\t\t\tinput.goal && objectiveId === projectedGoal?.objectiveId ? projectGoalAcceptanceEvidence(input.goal) : [];\n\t\tif (projectedGoal) this.runtime.assertObjectiveSynchronizationHeadroom(projectedGoal, projectedEvidence);\n\t\tthis.runtime.assertProjectionHeadroom({\n\t\t\tobjectives: snapshot.objectives[objectiveId] ? 0 : 1,\n\t\t\ttasks: taskStateBeforeWrites ? 0 : 1,\n\t\t\tattempts: activeAttemptBeforeWrites ? 0 : 1,\n\t\t});\n\t\tif (input.goal && objectiveId === projectedGoal?.objectiveId) {\n\t\t\tthis.synchronizeGoalState(input.goal);\n\t\t\tsnapshot = this.runtime.getSnapshot();\n\t\t} else if (!snapshot.objectives[objectiveId]) {\n\t\t\tthis.runtime.createObjective({\n\t\t\t\tobjectiveId,\n\t\t\t\ttitle: input.goalId ? `Goal ${input.goalId}` : `Session ${this.sessionId}`,\n\t\t\t\tdescription: input.goalId ? \"Externally managed goal work\" : \"Session-scoped delegated work\",\n\t\t\t});\n\t\t\tsnapshot = this.runtime.getSnapshot();\n\t\t}\n\n\t\tconst verificationSubject = input.verificationOfTaskId ? snapshot.tasks[input.verificationOfTaskId] : undefined;\n\t\tconst taskInput = {\n\t\t\ttaskId: input.laneId,\n\t\t\tobjectiveId,\n\t\t\ttitle: deriveWorkerTaskLabel(input.instructions, `Delegated ${input.role} work`),\n\t\t\tdescription: input.instructions,\n\t\t\trole: input.role,\n\t\t\tdependsOn: dependencyTaskIds,\n\t\t\trequiredCapabilities: input.requiredCapabilities,\n\t\t\tacceptanceCriterionIds: input.taskContext?.acceptanceCriterionIds ?? [],\n\t\t\triskBudget: input.riskBudget,\n\t\t\t...(input.verificationOfTaskId\n\t\t\t\t? {\n\t\t\t\t\t\tverificationOfTaskId: input.verificationOfTaskId,\n\t\t\t\t\t\tacceptanceCriterionIds: verificationSubject?.task.acceptanceCriterionIds ?? [],\n\t\t\t\t\t}\n\t\t\t\t: {}),\n\t\t} as const;\n\t\tconst dispatch = {\n\t\t\ttaskId: input.laneId,\n\t\t\tprofileId: input.profileId,\n\t\t\tinstructions: input.instructions,\n\t\t\tresourcePointerIds: input.taskContext?.resourcePointerIds ?? [],\n\t\t\t...(input.parentAgentId ? { parentAgentId: input.parentAgentId } : {}),\n\t\t\trequirementIds: input.taskContext?.requirementIds ?? [],\n\t\t\t...(input.executionContract ? { executionContract: input.executionContract } : {}),\n\t\t\t...input.dispatchMetadata,\n\t\t\t...(birthContextForkReference ? { birthContextForkReference } : {}),\n\t\t} as const;\n\t\tif (\n\t\t\texistingTask &&\n\t\t\t(existingTask.title !== taskInput.title ||\n\t\t\t\texistingTask.verificationOfTaskId !== taskInput.verificationOfTaskId ||\n\t\t\t\t!isDeepStrictEqual(existingTask.requiredCapabilities, [...new Set(taskInput.requiredCapabilities)]) ||\n\t\t\t\t!isDeepStrictEqual(existingTask.acceptanceCriterionIds, [...new Set(taskInput.acceptanceCriterionIds)]) ||\n\t\t\t\t!isDeepStrictEqual(existingTask.riskBudget, taskInput.riskBudget))\n\t\t) {\n\t\t\tthrow new DurableTaskRuntimeError(`Task '${input.laneId}' has conflicting durable task identity.`);\n\t\t}\n\t\tif (activeAttemptBeforeWrites && !isDeepStrictEqual(activeAttemptBeforeWrites.dispatch, dispatch)) {\n\t\t\tthrow new DurableTaskRuntimeError(`Task '${input.laneId}' has conflicting durable dispatch identity.`);\n\t\t}\n\t\tif (!snapshot.tasks[input.laneId]) {\n\t\t\treturn this.runtime.prepareTaskAttempt(\n\t\t\t\t{\n\t\t\t\t\t...taskInput,\n\t\t\t\t},\n\t\t\t\tdispatch,\n\t\t\t).attempt;\n\t\t}\n\n\t\tconst task = snapshot.tasks[input.laneId];\n\t\tif (!task) throw new DurableTaskRuntimeError(`Failed to create task '${input.laneId}'.`);\n\t\tif (activeAttemptBeforeWrites) return activeAttemptBeforeWrites;\n\n\t\treturn this.runtime.queueAttempt(input.laneId, dispatch);\n\t}\n\n\tsynchronizeGoalState(goal: GoalState): void {\n\t\tconst objective = projectGoalObjective(goal);\n\t\tconst evidence = projectGoalAcceptanceEvidence(goal);\n\t\tthis.runtime.assertObjectiveSynchronizationHeadroom(objective, evidence);\n\t\tthis.runtime.ensureObjective(objective);\n\t\tfor (const item of evidence) {\n\t\t\tthis.runtime.recordObjectiveEvidence(objective.objectiveId, item);\n\t\t}\n\t\tconst status = this.runtime.getSnapshot().objectives[goalObjectiveId(goal.goalId)]?.objective.status;\n\t\tswitch (goal.status) {\n\t\t\tcase \"active\":\n\t\t\t\tif (status === \"paused\") this.runtime.resumeObjective(objective.objectiveId);\n\t\t\t\tbreak;\n\t\t\tcase \"paused\":\n\t\t\tcase \"blocked\":\n\t\t\tcase \"usage_limited\":\n\t\t\tcase \"budget_limited\":\n\t\t\t\tif (status === \"active\") this.runtime.pauseObjective(objective.objectiveId);\n\t\t\t\tbreak;\n\t\t\tcase \"cancelled\":\n\t\t\t\tif (status !== \"cancelled\") this.runtime.cancelObjective(objective.objectiveId);\n\t\t\t\tbreak;\n\t\t\tcase \"completed\":\n\t\t\t\tif (status !== \"completed\") {\n\t\t\t\t\tthis.runtime.completeObjectiveFromOwner(objective.objectiveId, hasGoalAcceptanceOverride(goal));\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\tstart(\n\t\tattemptId: string,\n\t\tleaseTtlMs: number,\n\t\townerId = `in-process:${this.sessionId}`,\n\t\tagentId?: string,\n\t): StartedDelegationAttempt {\n\t\tconst snapshot = this.runtime.getSnapshot();\n\t\tconst attempt = snapshot.attempts[attemptId];\n\t\tif (!attempt) throw new DurableTaskRuntimeError(`Unknown attempt '${attemptId}'.`);\n\t\tconst task = snapshot.tasks[attempt.taskId];\n\t\tif (!task) throw new DurableTaskRuntimeError(`Unknown task '${attempt.taskId}'.`);\n\t\tconst lease = this.runtime.leaseAttempt(attemptId, ownerId, leaseTtlMs, agentId);\n\t\tthis.runtime.startAttempt(attemptId, lease.leaseId, lease.fencingToken);\n\t\treturn {\n\t\t\tobjectiveId: task.task.objectiveId,\n\t\t\ttaskId: task.task.taskId,\n\t\t\tattemptId,\n\t\t\tleaseId: lease.leaseId,\n\t\t\tfencingToken: lease.fencingToken,\n\t\t\texpiresAt: lease.expiresAt,\n\t\t};\n\t}\n\n\tcancel(attemptId: string, reasonCode: string): void {\n\t\tthis.runtime.cancelAttempt(attemptId, reasonCode);\n\t}\n\n\t/** Latest fenced cumulative usage, if this attempt has crossed a durable checkpoint boundary. */\n\tgetAttemptUsage(attemptId: string): AttemptUsageSnapshot | undefined {\n\t\tconst snapshot = this.runtime.getSnapshot();\n\t\tconst attempt = snapshot.attempts[attemptId];\n\t\tif (!attempt) throw new DurableTaskRuntimeError(`Unknown attempt '${attemptId}'.`);\n\t\tfor (const checkpointId of [...attempt.checkpointIds].reverse()) {\n\t\t\tconst usage = snapshot.checkpoints[checkpointId]?.usage;\n\t\t\tif (usage) return structuredClone(usage);\n\t\t}\n\t\treturn undefined;\n\t}\n\n\t/** Fence interrupted isolated completions and queue one replacement attempt per task. */\n\trecoverQueuedDispatches(): AttemptRuntimeState[] {\n\t\tthis.runtime.recoverInterruptedUnboundAttempts((attempt) => attempt.dispatch.executionKind !== \"managed-process\");\n\t\tlet snapshot = this.runtime.getSnapshot();\n\t\tfor (const task of Object.values(snapshot.tasks)) {\n\t\t\tconst attempts = task.attemptIds.map((attemptId) => snapshot.attempts[attemptId]).filter(Boolean);\n\t\t\tif (attempts.some((attempt) => attempt && activeAttempt(attempt))) continue;\n\t\t\tconst interrupted = [...attempts].reverse().find((attempt) => attempt?.status === \"expired\");\n\t\t\tif (!interrupted || task.task.status !== \"ready\") continue;\n\t\t\tconst maxAttempts = task.task.riskBudget.maxAttempts;\n\t\t\tif (maxAttempts !== undefined && task.attemptIds.length >= maxAttempts) {\n\t\t\t\tthis.runtime.failTask(task.task.taskId, \"attempt_budget_exhausted\");\n\t\t\t\tsnapshot = this.runtime.getSnapshot();\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tthis.runtime.queueAttempt(task.task.taskId, interrupted.dispatch);\n\t\t\tsnapshot = this.runtime.getSnapshot();\n\t\t}\n\t\treturn Object.values(snapshot.attempts).filter(\n\t\t\t(attempt) => attempt.status === \"queued\" && attempt.dispatch.executionKind !== \"managed-process\",\n\t\t);\n\t}\n}\n"]}
@@ -9,6 +9,11 @@ export interface OrchestrationEventStoreOptions {
9
9
  maxTailBytes?: number;
10
10
  maxIdempotencyEvents?: number;
11
11
  }
12
+ export interface AppendOrchestrationEventOptions {
13
+ expectedLastOrdinal?: number;
14
+ /** Exact event admission under the append lock, before any durable file is written. */
15
+ validateBeforeCommit?: (event: OrchestrationEvent) => void;
16
+ }
12
17
  export declare class OrchestrationEventStoreError extends Error {
13
18
  constructor(message: string);
14
19
  }
@@ -44,9 +49,7 @@ export declare class OrchestrationEventStore {
44
49
  private verifiedSnapshotBaseline;
45
50
  private synchronizedIndexes;
46
51
  constructor(options: OrchestrationEventStoreOptions);
47
- append(input: AppendOrchestrationEventInput, options?: {
48
- expectedLastOrdinal?: number;
49
- }): OrchestrationEvent;
52
+ append(input: AppendOrchestrationEventInput, options?: AppendOrchestrationEventOptions): OrchestrationEvent;
50
53
  readAll(): OrchestrationEvent[];
51
54
  readAfter(ordinal: number): OrchestrationEvent[];
52
55
  readProjectionSnapshot(): {
@@ -1 +1 @@
1
- {"version":3,"file":"event-store.d.ts","sourceRoot":"","sources":["../../../src/core/orchestration/event-store.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,0BAA0B,CAAC;AAG3D,OAAO,EACN,KAAK,6BAA6B,EAGlC,KAAK,kBAAkB,EACvB,MAAM,gBAAgB,CAAC;AAgExB,MAAM,WAAW,8BAA8B;IAC9C,QAAQ,EAAE,MAAM,CAAC;IACjB,SAAS,EAAE,MAAM,CAAC;IAClB,GAAG,CAAC,EAAE,MAAM,MAAM,CAAC;IACnB,aAAa,CAAC,EAAE,MAAM,MAAM,CAAC;IAC7B,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,oBAAoB,CAAC,EAAE,MAAM,CAAC;CAC9B;AAED,qBAAa,4BAA6B,SAAQ,KAAK;IACtD,YAAY,OAAO,EAAE,MAAM,EAG1B;CACD;AAED,qBAAa,6BAA8B,SAAQ,4BAA4B;IAC9E,YAAY,QAAQ,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAG3C;CACD;AAED,qBAAa,kCAAmC,SAAQ,4BAA4B;IACnF,QAAQ,CAAC,cAAc,EAAE,MAAM,CAAC;IAEhC,YAAY,cAAc,EAAE,MAAM,EAIjC;CACD;AAkED;;;;;;;;GAQG;AACH,qBAAa,uBAAuB;IACnC,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,QAAQ,CAAC,cAAc,EAAE,MAAM,CAAC;IAChC,QAAQ,C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