phronomy 0.37.0 → 0.38.0

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 (211) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +87 -0
  3. data/README.md +24 -2
  4. data/SECURITY.md +1 -1
  5. data/docs/architecture/agent-approval-recovery.md +320 -0
  6. data/docs/architecture/agent-child-approval-recovery.md +387 -0
  7. data/docs/architecture/agent-child-execution-recovery.md +425 -0
  8. data/docs/architecture/agent-dispatch-recovery.md +308 -0
  9. data/docs/architecture/agent-terminal-persistence-evidence.md +360 -0
  10. data/docs/architecture/agent-terminal-recovery.md +298 -0
  11. data/docs/architecture/agent-terminal-submission-recovery.md +275 -0
  12. data/docs/architecture/agent-tool-child-lifetime.md +29 -0
  13. data/docs/architecture/agent-transition-ownership.md +24 -0
  14. data/docs/architecture/backend-groups.md +6 -0
  15. data/docs/architecture/detached-outcome-proof-projection.md +576 -0
  16. data/docs/architecture/execution-abstraction-review.md +5 -0
  17. data/docs/architecture/handoff-dispatch-recovery.md +205 -0
  18. data/docs/architecture/handoff-initial-terminal-application.md +321 -0
  19. data/docs/architecture/initial-preparation-recovery.md +308 -0
  20. data/docs/architecture/multi-agent-handoff.md +17 -0
  21. data/docs/architecture/native-outcome-preparation.md +715 -0
  22. data/docs/architecture/native-parent-dispatch-recovery.md +460 -0
  23. data/docs/architecture/native-parent-outcome-recovery.md +644 -0
  24. data/docs/architecture/parent-child-terminal-acknowledgement.md +297 -0
  25. data/docs/architecture/r8-unit12.md +6 -3
  26. data/docs/architecture/r8-unit4.md +11 -2
  27. data/docs/architecture/recovery-physical-attempt.md +88 -0
  28. data/docs/architecture/recovery-submission-custody.md +247 -0
  29. data/docs/architecture/retained-attempts.md +229 -0
  30. data/docs/architecture/retained-outcome-materialization.md +636 -0
  31. data/docs/architecture/retained-outcome-publication.md +506 -0
  32. data/docs/architecture/storage-execution-boundaries.md +1 -1
  33. data/docs/architecture/structured-output-and-scope.md +15 -0
  34. data/docs/architecture/synchronous-participant-application.md +397 -0
  35. data/docs/architecture/synchronous-participant-contract.md +195 -0
  36. data/docs/architecture/team-admission-rejection.md +91 -0
  37. data/docs/architecture/team-cancellation-delivery.md +245 -0
  38. data/docs/architecture/team-child-retirement.md +104 -0
  39. data/docs/architecture/tracing.md +26 -0
  40. data/docs/architecture/workflow-terminal-ownership-design.md +25 -9
  41. data/docs/architecture/workflow-terminal-reconciliation.md +221 -0
  42. data/docs/architecture.md +16 -9
  43. data/docs/decisions/025-process-local-agent-ownership-and-runtime-admission.md +8 -0
  44. data/docs/features.md +3 -3
  45. data/docs/mcp-client.md +138 -5
  46. data/docs/migrations/orchestrator-subagent-dispatch.md +89 -0
  47. data/docs/migrations/vector-async-clients.md +18 -3
  48. data/docs/persistence-backends.md +30 -4
  49. data/docs/runtime-and-concurrency.md +235 -11
  50. data/lib/phronomy/agent/admission.rb +37 -17
  51. data/lib/phronomy/agent/api/agent.rb +25 -0
  52. data/lib/phronomy/agent/approval_recovery.rb +30 -0
  53. data/lib/phronomy/agent/approval_recovery_api.rb +61 -0
  54. data/lib/phronomy/agent/approval_recovery_error.rb +39 -0
  55. data/lib/phronomy/agent/approval_recovery_result.rb +94 -0
  56. data/lib/phronomy/agent/async_event_api.rb +22 -5
  57. data/lib/phronomy/agent/base.rb +76 -48
  58. data/lib/phronomy/agent/context_preparation.rb +10 -8
  59. data/lib/phronomy/agent/dispatch_recovery.rb +29 -0
  60. data/lib/phronomy/agent/dispatch_recovery_api.rb +84 -0
  61. data/lib/phronomy/agent/dispatch_recovery_error.rb +36 -0
  62. data/lib/phronomy/agent/dispatch_recovery_result.rb +93 -0
  63. data/lib/phronomy/agent/execution/agent_invocation.rb +11 -3
  64. data/lib/phronomy/agent/execution/approval_continuation_plan.rb +131 -0
  65. data/lib/phronomy/agent/execution/approval_parent_evidence.rb +116 -0
  66. data/lib/phronomy/agent/execution/approval_persistence_evidence.rb +111 -0
  67. data/lib/phronomy/agent/execution/approval_recovery_operation.rb +496 -0
  68. data/lib/phronomy/agent/execution/approval_resume_commit.rb +174 -10
  69. data/lib/phronomy/agent/execution/dispatch_continuation_delivery.rb +96 -0
  70. data/lib/phronomy/agent/execution/dispatch_persistence_evidence.rb +147 -0
  71. data/lib/phronomy/agent/execution/dispatch_preparation.rb +63 -7
  72. data/lib/phronomy/agent/execution/dispatch_recovery_operation.rb +495 -0
  73. data/lib/phronomy/agent/execution/execution_coordinator.rb +724 -158
  74. data/lib/phronomy/agent/execution/execution_outcome_committer.rb +312 -39
  75. data/lib/phronomy/agent/execution/execution_registry.rb +508 -13
  76. data/lib/phronomy/agent/execution/initial_persistence_evidence.rb +269 -0
  77. data/lib/phronomy/agent/execution/initial_preparation.rb +132 -40
  78. data/lib/phronomy/agent/execution/initial_preparation_recovery_operation.rb +513 -0
  79. data/lib/phronomy/agent/execution/invocation_transitions.rb +3 -0
  80. data/lib/phronomy/agent/execution/outcome_planning.rb +108 -0
  81. data/lib/phronomy/agent/execution/outcome_preparation.rb +81 -0
  82. data/lib/phronomy/agent/execution/outcome_recovery_operation.rb +609 -0
  83. data/lib/phronomy/agent/execution/outcome_text_projection.rb +73 -0
  84. data/lib/phronomy/agent/execution/outcome_write_plan.rb +48 -0
  85. data/lib/phronomy/agent/execution/runtime_record_encoder.rb +7 -4
  86. data/lib/phronomy/agent/execution/terminal_persistence_evidence.rb +280 -0
  87. data/lib/phronomy/agent/execution/terminal_recovery_operation.rb +38 -0
  88. data/lib/phronomy/agent/execution_change.rb +138 -26
  89. data/lib/phronomy/agent/execution_environment.rb +29 -0
  90. data/lib/phronomy/agent/execution_rejected_error.rb +34 -0
  91. data/lib/phronomy/agent/initial_preparation_recovery.rb +32 -0
  92. data/lib/phronomy/agent/initial_preparation_recovery_api.rb +85 -0
  93. data/lib/phronomy/agent/initial_preparation_recovery_error.rb +41 -0
  94. data/lib/phronomy/agent/initial_preparation_recovery_result.rb +115 -0
  95. data/lib/phronomy/agent/lifecycle/hosted_approval_context.rb +86 -0
  96. data/lib/phronomy/agent/lifecycle/hosted_invocation.rb +42 -10
  97. data/lib/phronomy/agent/lifecycle/identity_write.rb +101 -0
  98. data/lib/phronomy/agent/lifecycle/lifetime_api.rb +28 -0
  99. data/lib/phronomy/agent/lifecycle/ownership_registry.rb +136 -70
  100. data/lib/phronomy/agent/lifecycle/scope.rb +3 -3
  101. data/lib/phronomy/agent/outcome_recovery.rb +47 -0
  102. data/lib/phronomy/agent/outcome_recovery_api.rb +114 -0
  103. data/lib/phronomy/agent/outcome_recovery_error.rb +36 -0
  104. data/lib/phronomy/agent/outcome_recovery_result.rb +92 -0
  105. data/lib/phronomy/agent/output_contract.rb +16 -6
  106. data/lib/phronomy/agent/persistence/identity_receipt_repository.rb +61 -0
  107. data/lib/phronomy/agent/persistence/records.rb +2 -0
  108. data/lib/phronomy/agent/persistence/storage_schema.rb +2 -0
  109. data/lib/phronomy/agent/recovery/invocation_restorer.rb +8 -5
  110. data/lib/phronomy/agent/recovery/recovery_coordinator/continuation.rb +6 -4
  111. data/lib/phronomy/agent/recovery/recovery_coordinator/installation.rb +21 -43
  112. data/lib/phronomy/agent/recovery/recovery_coordinator.rb +19 -6
  113. data/lib/phronomy/agent/runtime_binding/engine_environment.rb +12 -0
  114. data/lib/phronomy/agent/state_writer.rb +4 -3
  115. data/lib/phronomy/agent/store.rb +7 -1
  116. data/lib/phronomy/agent/terminal_recovery.rb +41 -0
  117. data/lib/phronomy/agent/terminal_recovery_api.rb +101 -0
  118. data/lib/phronomy/agent/terminal_recovery_error.rb +36 -0
  119. data/lib/phronomy/agent/terminal_recovery_result.rb +67 -0
  120. data/lib/phronomy/agent/tool_execution/tool_approval_request.rb +25 -1
  121. data/lib/phronomy/common/values/serializable.rb +37 -4
  122. data/lib/phronomy/engine/concurrency/offload_pool.rb +32 -4
  123. data/lib/phronomy/engine/concurrency/pool_registry.rb +6 -0
  124. data/lib/phronomy/engine/event_loop.rb +161 -11
  125. data/lib/phronomy/engine/execution_binding.rb +4 -2
  126. data/lib/phronomy/engine/execution_receiver_binding.rb +5 -0
  127. data/lib/phronomy/engine/runtime/shutdown_result.rb +21 -0
  128. data/lib/phronomy/engine/runtime/timer_queue.rb +7 -2
  129. data/lib/phronomy/engine/runtime.rb +119 -15
  130. data/lib/phronomy/execution/attempt_completion.rb +91 -0
  131. data/lib/phronomy/execution/concurrency/cancellation_token.rb +7 -2
  132. data/lib/phronomy/execution/concurrency/physical_completion_task.rb +7 -2
  133. data/lib/phronomy/execution/execution.rb +17 -2
  134. data/lib/phronomy/execution/execution_receiver.rb +27 -0
  135. data/lib/phronomy/execution/execution_retirement.rb +30 -0
  136. data/lib/phronomy/execution/invocation_controls.rb +2 -2
  137. data/lib/phronomy/execution/retained_attempts.rb +179 -0
  138. data/lib/phronomy/execution/stopped_terminal_custody.rb +99 -0
  139. data/lib/phronomy/llm_adapter/response.rb +7 -1
  140. data/lib/phronomy/multi_agent/admission_registry.rb +6 -0
  141. data/lib/phronomy/multi_agent/durable_subagent_coordinator.rb +175 -39
  142. data/lib/phronomy/multi_agent/handoff_dispatch_evidence.rb +176 -0
  143. data/lib/phronomy/multi_agent/handoff_finalization_error.rb +33 -0
  144. data/lib/phronomy/multi_agent/handoff_history_release.rb +80 -0
  145. data/lib/phronomy/multi_agent/handoff_participant.rb +31 -6
  146. data/lib/phronomy/multi_agent/handoff_runner.rb +195 -21
  147. data/lib/phronomy/multi_agent/handoff_terminal_finalization.rb +176 -0
  148. data/lib/phronomy/multi_agent/native_approval_evidence.rb +26 -0
  149. data/lib/phronomy/multi_agent/native_child_authority.rb +135 -0
  150. data/lib/phronomy/multi_agent/native_dispatch_evidence.rb +43 -0
  151. data/lib/phronomy/multi_agent/native_outcome_evidence.rb +46 -0
  152. data/lib/phronomy/multi_agent/native_persistence_plan.rb +93 -0
  153. data/lib/phronomy/multi_agent/orchestrator.rb +28 -52
  154. data/lib/phronomy/multi_agent/reserved_child_admission.rb +90 -1
  155. data/lib/phronomy/multi_agent/store.rb +5 -34
  156. data/lib/phronomy/multi_agent/subagent_history_release.rb +88 -0
  157. data/lib/phronomy/multi_agent/team_cancellation_delivery_error.rb +21 -0
  158. data/lib/phronomy/multi_agent/team_cancellation_request.rb +134 -0
  159. data/lib/phronomy/multi_agent/team_coordinator.rb +174 -27
  160. data/lib/phronomy/persistence_composition/stores.rb +10 -3
  161. data/lib/phronomy/runtime_composition/execution_defaults.rb +18 -0
  162. data/lib/phronomy/storage/backends/in_memory.rb +3 -1
  163. data/lib/phronomy/storage/resource.rb +10 -1
  164. data/lib/phronomy/tools/agent.rb +7 -1
  165. data/lib/phronomy/tools/mcp.rb +210 -91
  166. data/lib/phronomy/tools/mcp_http_close_response.rb +23 -0
  167. data/lib/phronomy/tools/mcp_transport_registry.rb +210 -0
  168. data/lib/phronomy/tools/vector_search.rb +28 -5
  169. data/lib/phronomy/tracing/automatic.rb +8 -1
  170. data/lib/phronomy/version.rb +1 -1
  171. data/lib/phronomy/workflow/execution/workflow.rb +34 -0
  172. data/lib/phronomy/workflow/execution/workflow_execution_environment.rb +1 -0
  173. data/lib/phronomy/workflow/execution/workflow_execution_registry.rb +106 -7
  174. data/lib/phronomy/workflow/execution/workflow_runner.rb +53 -108
  175. data/lib/phronomy/workflow/execution/workflow_terminal_operation.rb +489 -0
  176. data/lib/phronomy/workflow/execution/workflow_terminal_persistence.rb +81 -0
  177. data/lib/phronomy/workflow/execution/workflow_terminal_recovery.rb +38 -0
  178. data/lib/phronomy/workflow/execution/workflow_terminal_recovery_error.rb +34 -0
  179. data/lib/phronomy/workflow/execution/workflow_terminal_recovery_result.rb +56 -0
  180. data/lib/phronomy/workflow/runtime_binding/workflow_engine_environment.rb +10 -1
  181. data/lib/phronomy/workflow/runtime_binding/workflow_task_session.rb +3 -1
  182. data/lib/phronomy/workflow/runtime_binding/workflow_terminal_policy.rb +2 -1
  183. data/scripts/api_snapshot.rb +46 -1
  184. data/sig/_private/phronomy/multi_agent/team_cancellation_request.rbs +19 -0
  185. data/sig/phronomy/agent/approval_recovery.rbs +54 -0
  186. data/sig/phronomy/agent/dispatch_recovery.rbs +49 -0
  187. data/sig/phronomy/agent/execution_contract.rbs +4 -1
  188. data/sig/phronomy/agent/execution_environment.rbs +2 -0
  189. data/sig/phronomy/agent/initial_preparation_recovery.rbs +48 -0
  190. data/sig/phronomy/agent/outcome_recovery.rbs +51 -0
  191. data/sig/phronomy/agent/store.rbs +1 -0
  192. data/sig/phronomy/agent/terminal_persistence_evidence.rbs +111 -0
  193. data/sig/phronomy/agent/terminal_recovery.rbs +46 -0
  194. data/sig/phronomy/agent.rbs +36 -0
  195. data/sig/phronomy/engine/concurrency/timer_bindings.rbs +2 -0
  196. data/sig/phronomy/engine/execution_binding.rbs +2 -1
  197. data/sig/phronomy/engine/execution_receiver.rbs +4 -0
  198. data/sig/phronomy/engine/observability.rbs +22 -1
  199. data/sig/phronomy/execution/execution.rbs +16 -1
  200. data/sig/phronomy/execution/execution_receiver.rbs +12 -0
  201. data/sig/phronomy/execution/execution_retirement.rbs +18 -0
  202. data/sig/phronomy/execution/stopped_terminal_custody.rbs +19 -0
  203. data/sig/phronomy/handoff.rbs +1 -0
  204. data/sig/phronomy/multi_agent/handoff_finalization_error.rbs +18 -0
  205. data/sig/phronomy/multi_agent/store.rbs +1 -1
  206. data/sig/phronomy/multi_agent/team_cancellation_delivery_error.rbs +9 -0
  207. data/sig/phronomy/persistence_composition.rbs +2 -1
  208. data/sig/phronomy/storage/contracts.rbs +2 -1
  209. data/sig/phronomy/tools/mcp.rbs +27 -0
  210. data/sig/phronomy/workflow.rbs +42 -0
  211. metadata +104 -2
@@ -24,11 +24,25 @@ module Phronomy
24
24
  # A resumed approval must never be adopted by the original start handle.
25
25
  # Only a hosted decision owns the right to detach its next suspension.
26
26
  class ApprovalOperation < OperationResult
27
- attr_reader :parent_wait
27
+ attr_reader :parent_wait, :hosted_context
28
28
 
29
- def initialize(agent:, name:, parent_wait:)
29
+ def initialize(agent:, name:, parent_wait:, hosted_context: nil)
30
30
  super(agent: agent, name: name)
31
- @parent_wait = parent_wait
31
+ @parent_wait, @hosted_context = parent_wait, hosted_context
32
+ on_physical_complete do
33
+ @parent_wait = @hosted_context = nil
34
+ end
35
+ on_complete { |_value, _error| @hosted_continuation_task = nil }
36
+ end
37
+
38
+ def bind_hosted_continuation(task)
39
+ @hosted_continuation_task = task unless done?
40
+ end
41
+
42
+ # The normal hosted handle may follow its still-open observation into
43
+ # the retained continuation. A failed or cancelled observation cannot.
44
+ def hosted_detach_task
45
+ done? ? self : (@hosted_continuation_task || self)
32
46
  end
33
47
  end
34
48
 
@@ -42,6 +56,12 @@ module Phronomy
42
56
  RecoveredCoordinationWait = Data.define(:coordinator, :execution_id, :revision) do
43
57
  def current? = coordinator.current_coordination_wait?(self)
44
58
  end
59
+ # A local setup failure may transfer to the existing terminal protocol only
60
+ # after it retained an operation or returned an accepted worker handle.
61
+ TerminalCustody = Data.define(:coordinator, :operation, :task, :retained_owner, :error) do
62
+ def accepted? = !retained_owner.nil? || task.is_a?(Phronomy::TaskResult)
63
+ end
64
+ private_constant :TerminalCustody
45
65
  private_constant :ApprovalOperation, :RecoveredCoordinationWait
46
66
  attr_reader :recovered_coordination_wait
47
67
 
@@ -85,9 +105,6 @@ module Phronomy
85
105
  ResumeCommitResult = ApprovalResumeCommit::Result
86
106
  TerminalOutcome = ExecutionOutcomeCommitter::Outcome
87
107
 
88
- InitialPreparationReady = Data.define(
89
- :coordinator, :request, :result, :error
90
- )
91
108
  InitialPreparationRecoveryReady = Data.define(
92
109
  :coordinator, :execution_id, :expected_execution_revision,
93
110
  :result_task, :load_completion, :result, :error
@@ -128,10 +145,13 @@ module Phronomy
128
145
  @agent.send(:__assert_live_agent!)
129
146
  @agent.send(:_reject_removed_generic_identity_keys!, config)
130
147
  result_task = OperationResult.new(agent: @agent, name: "agent-#{@agent.agent_id}-#{mode}")
131
- controls = Phronomy::InvocationControls.attach(result_task,
148
+ controls = Phronomy::InvocationControls.new(
132
149
  invocation_context: config[:invocation_context],
133
- cancellation_token: config[:cancellation_token])
134
- config = config.merge(cancellation_token: controls.token)
150
+ cancellation_token: config[:cancellation_token]
151
+ )
152
+ controls.bind(result_task, track_completion: false)
153
+ config = config.merge(cancellation_token: controls.token,
154
+ phronomy_reserved_execution_id: config[:phronomy_reserved_execution_id] || SecureRandom.uuid.freeze)
135
155
  command = StartCommand.new(
136
156
  coordinator: self,
137
157
  input: input,
@@ -145,10 +165,12 @@ module Phronomy
145
165
  controls: controls
146
166
  )
147
167
  unless post_control(@agent.__execution_environment, command)
168
+ controls.close
148
169
  fail_task(result_task, runtime_rejected_error(:start))
149
170
  end
150
171
  result_task
151
172
  rescue => error
173
+ controls&.close
152
174
  fail_task(result_task, error) if defined?(result_task) && result_task
153
175
  result_task
154
176
  end
@@ -157,11 +179,11 @@ module Phronomy
157
179
  execution_id,
158
180
  approval_request_id:,
159
181
  approved:,
160
- config: {}, parent_wait: nil
182
+ config: {}, parent_wait: nil, hosted_context: nil
161
183
  )
162
184
  @agent.send(:__assert_live_agent!)
163
185
  @agent.send(:_reject_removed_generic_identity_keys!, config)
164
- result_task = ApprovalOperation.new(agent: @agent, parent_wait: parent_wait,
186
+ result_task = ApprovalOperation.new(agent: @agent, parent_wait: parent_wait, hosted_context: hosted_context,
165
187
  name: "agent-approval-resume:#{execution_id}")
166
188
  command = ResumeCommand.new(
167
189
  coordinator: self,
@@ -195,6 +217,7 @@ module Phronomy
195
217
  # and sends only that snapshot to OffloadPool.
196
218
  # @api private
197
219
  def prepare_provider_dispatch(invocation, event_sink:, streaming:)
220
+ complete_prior_dispatch_continuation(invocation, event_sink)
198
221
  state = dispatch_preparation_state!(
199
222
  invocation, event_sink, phase: :calling_llm, kind: "Provider"
200
223
  )
@@ -210,6 +233,7 @@ module Phronomy
210
233
 
211
234
  # @api private
212
235
  def prepare_tool_dispatch(invocation, event_sink:)
236
+ complete_prior_dispatch_continuation(invocation, event_sink)
213
237
  state = dispatch_preparation_state!(
214
238
  invocation, event_sink, phase: :dispatching_tools, kind: "Tool"
215
239
  )
@@ -225,6 +249,8 @@ module Phronomy
225
249
 
226
250
  def submit_provider_dispatch_preparation(operation)
227
251
  environment = @agent.__execution_environment
252
+ return retain_dispatch_preparation(operation, :provider) if retained_dispatch_eligible?(operation)
253
+
228
254
  task = environment.submit(on_full: :raise) do
229
255
  @dispatch_preparation.prepare_provider(operation)
230
256
  end
@@ -246,6 +272,8 @@ module Phronomy
246
272
 
247
273
  def submit_tool_dispatch_preparation(operation)
248
274
  environment = @agent.__execution_environment
275
+ return retain_dispatch_preparation(operation, :tool) if retained_dispatch_eligible?(operation)
276
+
249
277
  task = environment.submit(on_full: :raise) do
250
278
  @dispatch_preparation.prepare_tools(operation)
251
279
  end
@@ -282,8 +310,6 @@ module Phronomy
282
310
  when SessionFinishedCommand
283
311
  finish_on_event_loop(command.execution_id, command.result_task,
284
312
  command.invocation, command.error, fsm_session_id: command.fsm_session_id)
285
- when InitialPreparationReady
286
- apply_initial_preparation_on_event_loop(command)
287
313
  when InitialPreparationRecoveryReady
288
314
  apply_initial_preparation_recovery_on_event_loop(command)
289
315
  when ProviderDispatchPreparationReady
@@ -315,9 +341,10 @@ module Phronomy
315
341
  registry = environment.registry
316
342
  state = registry.agent_execution_state(wait.execution_id)
317
343
  binding = @suspended_cancellation
318
- task = command.task || binding&.fetch(2)
344
+ source_task = command.task || binding&.fetch(2)
345
+ task = source_task.is_a?(ApprovalOperation) ? source_task.hosted_detach_task : source_task
319
346
  parent = command.parent
320
- if task.is_a?(ApprovalOperation) && (!command.task.equal?(task) || !task.parent_wait&.current?)
347
+ if task.is_a?(ApprovalOperation) && (!command.task || !task.parent_wait&.current?)
321
348
  raise Phronomy::AgentBusyError, "This handle does not own the resumed child wait"
322
349
  end
323
350
  if parent && registry.agent_execution_admitted?(parent.agent_id)
@@ -359,6 +386,7 @@ module Phronomy
359
386
  request.controls.check_start!
360
387
  root = @agent.send(:__root_for_operation)
361
388
  if root.lifecycle_status == :closed
389
+ request.controls.close
362
390
  deliver_start_failure_on_event_loop(
363
391
  request,
364
392
  Phronomy::Error.new("agent is closed: #{@agent.agent_id}")
@@ -368,7 +396,6 @@ module Phronomy
368
396
 
369
397
  @agent.send(:__assert_live_agent!)
370
398
  admitted = false
371
- submitted = false
372
399
  environment.registry.admit_agent_execution(
373
400
  @agent.agent_id,
374
401
  owner_token: request.admission_token
@@ -383,36 +410,72 @@ module Phronomy
383
410
 
384
411
  @recovered_coordination_wait = nil
385
412
  operation = capture_initial_preparation(request, root)
386
- task = environment.submit(on_full: :raise) do
387
- @initial_preparation.prepare(operation)
413
+ owner = InitialPreparationRecoveryOperation.new(agent: @agent, coordinator: self,
414
+ environment: environment, command: operation, request: request)
415
+ owner.start
416
+ rescue => error
417
+ if owner && environment.registry.owns_initial_preparation?(owner)
418
+ owner.shutdown(error)
419
+ else
420
+ if admitted
421
+ environment.registry.release_agent_execution_admission(@agent.agent_id,
422
+ owner_token: request.admission_token)
423
+ end
424
+ request.controls.close
425
+ deliver_start_failure_on_event_loop(request, error)
388
426
  end
389
- submitted = true
390
- request.result_task.track(task) if request.result_task.respond_to?(:track)
391
- task.on_complete do |result, error|
392
- ready = InitialPreparationReady.new(
393
- coordinator: self,
394
- request: request,
395
- result: result,
396
- error: error
397
- )
398
- fail_task(request.result_task, runtime_rejected_error(:initial_preparation)) unless
399
- post_control(environment, ready)
427
+ end
428
+
429
+ def apply_retained_initial_preparation_on_event_loop(owner, result)
430
+ environment = @agent.__execution_environment
431
+ assert_event_loop!(environment)
432
+ unless environment.registry.owns_initial_preparation?(owner)
433
+ raise Phronomy::Error, "Initial preparation no longer owns its admission"
400
434
  end
401
- rescue => error
402
- if admitted
403
- if submitted
404
- environment.registry.mark_agent_admission_recovery_required(
405
- @agent.agent_id,
406
- owner_token: request.admission_token
407
- )
408
- else
409
- environment.registry.release_agent_execution_admission(
410
- @agent.agent_id,
411
- owner_token: request.admission_token
412
- )
435
+ @agent.send(:__assert_live_agent!)
436
+ request = (result.admission_outcome == :active) ? owner.application_request : owner.request
437
+ if result.admission_outcome == :active
438
+ owner.controls.check_start!
439
+ owner.controls.token&.raise_if_cancelled!
440
+ end
441
+ environment.registry.bind_initial_preparation(owner)
442
+ apply_initial_live_state(result)
443
+ if result.admission_outcome == :terminal
444
+ discard_unadmitted_initial_projection(owner, environment)
445
+ callback_error = unless request.result_task.done?
446
+ @agent.send(:_deliver_stream_event, request.on_event,
447
+ StreamEvent.new(type: terminal_event_type(result.error), payload: {error: result.error}))
448
+ end
449
+ settle_execution_waiters(environment, result.execution.execution_id,
450
+ request.result_task, callback_error, terminal_event_type(result.error), nil, result.error)
451
+ else
452
+ register_initial_session_on_event_loop(request, result, owner: owner)
453
+ end
454
+ end
455
+
456
+ def discard_unadmitted_initial_projection(owner, environment)
457
+ state = environment.registry.agent_execution_state(owner.execution_id)
458
+ return unless state
459
+ session = owner.initial_session
460
+ known_unadmitted = session && (!owner.session_registration_attempted ||
461
+ (environment.respond_to?(:session_admitted?) && !environment.session_admitted?(session.id)))
462
+ unless known_unadmitted && environment.registry.discard_initial_projection(owner)
463
+ raise Phronomy::Error, "Initial terminal cleanup cannot discard an admitted or unknown session"
464
+ end
465
+ end
466
+
467
+ # Local application can lose its response too. Reuse the same saved
468
+ # journal identities instead of appending a terminal audit twice.
469
+ def apply_initial_live_state(result)
470
+ existing = @agent.send(:_journal_records_snapshot).to_h { |record| [record.record_id, record] }
471
+ missing = result.appended_records.reject do |record|
472
+ prior = existing[record.record_id]
473
+ if prior && prior.to_h != record.to_h
474
+ raise Phronomy::Error, "Initial journal application conflicts with its captured record"
413
475
  end
476
+ prior
414
477
  end
415
- deliver_start_failure_on_event_loop(request, error)
478
+ apply_agent_live_state(root: result.root, appended_records: missing)
416
479
  end
417
480
 
418
481
  def capture_initial_preparation(request, root)
@@ -446,75 +509,7 @@ module Phronomy
446
509
  end
447
510
  end
448
511
 
449
- def apply_initial_preparation_on_event_loop(ready)
450
- request = ready.request
451
- environment = @agent.__execution_environment
452
- if ready.error
453
- environment.registry.mark_agent_admission_recovery_required(
454
- @agent.agent_id,
455
- owner_token: request.admission_token
456
- )
457
- deliver_start_failure_on_event_loop(request, ready.error)
458
- return
459
- end
460
-
461
- result = ready.result
462
- case result.admission_outcome
463
- when :not_established
464
- environment.registry.release_agent_execution_admission(
465
- @agent.agent_id,
466
- owner_token: request.admission_token
467
- )
468
- deliver_start_failure_on_event_loop(request, result.error)
469
- return
470
- when :outcome_unknown, :recovery_required
471
- environment.registry.mark_agent_admission_recovery_required(
472
- @agent.agent_id,
473
- owner_token: request.admission_token
474
- )
475
- deliver_start_failure_on_event_loop(request, result.error)
476
- return
477
- when :active, :terminal
478
- environment.registry.bind_agent_execution_admission(
479
- @agent.agent_id,
480
- owner_token: request.admission_token,
481
- execution_id: result.execution.execution_id
482
- )
483
- else
484
- environment.registry.mark_agent_admission_recovery_required(
485
- @agent.agent_id,
486
- owner_token: request.admission_token
487
- )
488
- raise Phronomy::Error,
489
- "unknown initial admission outcome: #{result.admission_outcome.inspect}"
490
- end
491
-
492
- apply_agent_live_state(
493
- root: result.root,
494
- appended_records: result.appended_records
495
- )
496
- if result.admission_outcome == :terminal
497
- environment.registry.release_agent_execution_admission(
498
- @agent.agent_id,
499
- execution_id: result.execution.execution_id
500
- )
501
- deliver_start_failure_on_event_loop(request, result.error)
502
- return
503
- end
504
-
505
- register_initial_session_on_event_loop(request, result)
506
- rescue => error
507
- # Preparation may already be durably active. Terminalize through another
508
- # offloaded durable operation rather than releasing the admission blindly.
509
- begin_terminal_without_session_on_event_loop(
510
- request: request,
511
- prepared: ready.result,
512
- error: error
513
- )
514
- end
515
-
516
- def register_initial_session_on_event_loop(request, prepared)
517
- environment = @agent.__execution_environment
512
+ def build_initial_session(request, prepared, environment)
518
513
  Phronomy::Tracing::Automatic.observe_task(
519
514
  request.result_task,
520
515
  "agent.execution",
@@ -540,31 +535,69 @@ module Phronomy
540
535
  mode: request.mode,
541
536
  event_listener: request.on_event
542
537
  )
543
- session = environment.build_agent_session(invocation: invocation)
544
- environment.registry.install_agent_execution(
545
- execution_id: prepared.execution.execution_id,
546
- agent: @agent,
547
- coordinator: self,
548
- execution: prepared.execution,
549
- runtime_projection: prepared.runtime_projection,
550
- base_manifest: prepared.runtime_projection.manifest,
551
- invocation: session.context,
552
- fsm_session_id: session.id
553
- )
538
+ environment.build_agent_session(invocation: invocation)
539
+ end
540
+
541
+ def register_initial_session_on_event_loop(request, prepared, owner: nil)
542
+ environment = @agent.__execution_environment
543
+ setup_step = :build
544
+ session = owner&.initial_session || build_initial_session(request, prepared, environment)
545
+ owner.initial_session = session if owner
546
+ setup_step = :install
547
+ state = environment.registry.agent_execution_state(prepared.execution.execution_id)
548
+ if state
549
+ unless owner && state.agent.equal?(@agent) && state.coordinator.equal?(self) &&
550
+ state.fsm_session_id == session.id && state.invocation.equal?(session.context)
551
+ raise Phronomy::Error, "Agent execution #{prepared.execution.execution_id.inspect} is already live"
552
+ end
553
+ else
554
+ environment.registry.install_agent_execution(
555
+ execution_id: prepared.execution.execution_id,
556
+ agent: @agent,
557
+ coordinator: self,
558
+ execution: prepared.execution,
559
+ runtime_projection: prepared.runtime_projection,
560
+ base_manifest: prepared.runtime_projection.manifest,
561
+ invocation: session.context,
562
+ fsm_session_id: session.id
563
+ )
564
+ end
565
+ setup_step = :waiter
554
566
  environment.registry.register_agent_completion_waiter(
555
567
  prepared.execution.execution_id,
556
568
  request.result_task
557
569
  )
558
- execution_session_runner(environment).register(
559
- session, request.result_task
560
- )
561
- # simplecov:disable
562
- rescue => _error
563
- environment.registry.release_agent_execution(prepared.execution.execution_id) if
564
- environment&.executing? && environment.registry.agent_execution_state(prepared.execution.execution_id)
565
- raise
570
+ return if owner && environment.respond_to?(:session_admitted?) && environment.session_admitted?(session.id)
571
+ if owner&.session_registration_attempted && !environment.respond_to?(:session_admitted?)
572
+ raise Phronomy::Error, "Initial session registration has no authoritative admission observation"
573
+ end
574
+ owner.session_registration_attempted = true if owner
575
+ setup_step = :register
576
+ begin
577
+ execution_session_runner(environment).register(session, request.result_task)
578
+ rescue
579
+ # A lost registration response cannot authorize another session.
580
+ # The same EventLoop can positively confirm this exact admission.
581
+ raise unless owner && environment.respond_to?(:session_admitted?) && environment.session_admitted?(session.id)
582
+ end
583
+ rescue => error
584
+ raise unless owner&.original_delivery? && initial_setup_rejected?(owner, environment, setup_step)
585
+ owner.handover_setup_failure(prepared, error)
586
+ end
587
+
588
+ def initial_setup_rejected?(owner, environment, step)
589
+ case step
590
+ when :build
591
+ !owner.initial_session && !owner.session_registration_attempted
592
+ when :install
593
+ state = environment.registry.agent_execution_state(owner.execution_id)
594
+ !state || !state.agent.equal?(@agent) || !state.coordinator.equal?(self)
595
+ when :register
596
+ environment.respond_to?(:session_admitted?) && !environment.session_admitted?(owner.initial_session.id)
597
+ else
598
+ false
599
+ end
566
600
  end
567
- # simplecov:enable
568
601
 
569
602
  def deliver_start_failure_on_event_loop(request, error)
570
603
  callback_error = @agent.send(
@@ -747,6 +780,8 @@ module Phronomy
747
780
  root: result.root,
748
781
  appended_records: result.appended_records
749
782
  )
783
+ admission_token = environment.registry.agent_execution_admission_token(ready.execution_id,
784
+ agent: @agent, coordinator: self)
750
785
  environment.registry.release_agent_execution(ready.execution_id)
751
786
  mode = (
752
787
  result.execution.metadata[ExecutionMetadata::INVOCATION_MODE_KEY] ||
@@ -761,13 +796,13 @@ module Phronomy
761
796
  approval_listener: nil,
762
797
  on_event: @agent.send(:_phronomy_event_listener),
763
798
  result_task: ready.result_task,
764
- admission_token: Object.new.freeze,
799
+ admission_token: admission_token,
765
800
  controls: nil
766
801
  )
767
802
  begin
768
803
  register_initial_session_on_event_loop(request, result)
769
804
  rescue => error
770
- begin_terminal_without_session_on_event_loop(
805
+ begin_terminal_after_start_failure_on_event_loop(
771
806
  request: request,
772
807
  prepared: result,
773
808
  error: error
@@ -919,10 +954,14 @@ module Phronomy
919
954
  return
920
955
  end
921
956
 
957
+ dispatch_prepared_provider_on_event_loop(operation, result, state)
958
+ end
959
+
960
+ def dispatch_prepared_provider_on_event_loop(operation, result, state, event_sink: state.invocation.event_sink)
922
961
  Agent::InvocationActions.start_prepared_provider_call(
923
962
  agent: @agent,
924
963
  environment: @agent.__execution_environment,
925
- event_sink: state.invocation.event_sink,
964
+ event_sink: event_sink,
926
965
  invocation: state.invocation,
927
966
  projection: result.runtime_projection,
928
967
  streaming: operation.streaming
@@ -940,9 +979,13 @@ module Phronomy
940
979
  execution: result.execution
941
980
  )
942
981
  state.invocation.acknowledge_runtime_snapshot(operation.runtime_snapshot)
982
+ dispatch_prepared_tools_on_event_loop(state)
983
+ end
984
+
985
+ def dispatch_prepared_tools_on_event_loop(state, event_sink: state.invocation.event_sink)
943
986
  Agent::InvocationActions.start_prepared_tool_dispatch(
944
987
  environment: @agent.__execution_environment,
945
- event_sink: state.invocation.event_sink,
988
+ event_sink: event_sink,
946
989
  invocation: state.invocation
947
990
  )
948
991
  end
@@ -960,6 +1003,152 @@ module Phronomy
960
1003
  )
961
1004
  end
962
1005
 
1006
+ def retained_dispatch_eligible?(command)
1007
+ command.invocation_config[:phronomy_execution_participant] || !command.execution.metadata["execution_extension"]
1008
+ end
1009
+
1010
+ def retain_dispatch_preparation(command, kind)
1011
+ environment = @agent.__execution_environment
1012
+ state = environment.registry.agent_execution_state(command.execution_id)
1013
+ DispatchRecoveryOperation.new(agent: @agent, coordinator: self, environment: environment,
1014
+ command: command, invocation: state.invocation, dispatch_kind: kind,
1015
+ original_waiters: environment.registry.agent_completion_waiters(command.execution_id),
1016
+ preparer: @dispatch_preparation).start
1017
+ end
1018
+
1019
+ # Reaching a later dispatch entry through the same FSM proves its previous
1020
+ # continuation progressed, even if that handoff's local reply was lost.
1021
+ def complete_prior_dispatch_continuation(invocation, event_sink)
1022
+ owner = @agent.__execution_environment.registry.dispatch_operation(invocation.execution_id)
1023
+ return unless owner && owner.invocation.equal?(invocation) &&
1024
+ owner.fsm_session_id.to_s == event_sink.fsm_session_id.to_s && owner.continuation_authorized?
1025
+ owner.continuation_completed!
1026
+ owner.retire_after_delivery
1027
+ end
1028
+
1029
+ def dispatch_recovery_failed_on_event_loop(owner, _failure)
1030
+ assert_event_loop!(owner.environment)
1031
+ return unless owner.environment.registry.owns_dispatch_operation?(owner)
1032
+ owner.environment.registry.mark_agent_execution_admission(@agent.agent_id,
1033
+ execution_id: owner.execution_id, state: :recovery_required)
1034
+ # The original stream observation is closed. The recovery receipt exposes
1035
+ # a fresh execution observation rather than reviving its old callbacks.
1036
+ owner.invocation.event_listener = nil
1037
+ end
1038
+
1039
+ def stop_retained_dispatch_on_event_loop(owner, error)
1040
+ environment = owner.environment
1041
+ registry = environment.registry
1042
+ assert_event_loop!(environment)
1043
+ state = retained_dispatch_state!(owner)
1044
+ dispatch_recovery_failed_on_event_loop(owner, nil) if owner.pending?
1045
+ unless state.execution.to_h == owner.command.execution.to_h &&
1046
+ @agent.send(:__root_for_operation).to_h == owner.command.root.to_h
1047
+ raise Phronomy::Persistence::StateConflictError, "Live state changed before preparation failure handoff"
1048
+ end
1049
+ owner.prepare_failed_continuation!
1050
+ owner.application_applied!
1051
+ owner.prepare_continuation
1052
+ registry.register_agent_completion_waiter(owner.execution_id, owner.continuation_task)
1053
+ delivery = owner.prepare_continuation_delivery
1054
+ if owner.continuation_authorized?
1055
+ unless owner.continuation_returned? && delivery.retry_rejected! && delivery.finish_handoff?
1056
+ raise runtime_rejected_error(:dispatch_preparation_failure)
1057
+ end
1058
+ else
1059
+ owner.authorize_continuation!
1060
+ event = (owner.dispatch_kind == :provider) ? :llm_setup_failed : :tool_setup_failed
1061
+ delivery.post(event, error)
1062
+ owner.continuation_returned!
1063
+ raise runtime_rejected_error(:dispatch_preparation_failure) unless delivery.finish_handoff?
1064
+ end
1065
+ registry.mark_agent_execution_admission(@agent.agent_id,
1066
+ execution_id: owner.execution_id, state: :executing)
1067
+ owner.continuation_completed!(:stopped)
1068
+ end
1069
+
1070
+ def retained_dispatch_state!(owner)
1071
+ registry = owner.environment.registry
1072
+ state = registry.agent_execution_state(owner.execution_id)
1073
+ unless registry.owns_dispatch_operation?(owner) && state.invocation.equal?(owner.invocation) &&
1074
+ state.fsm_session_id.to_s == owner.command.fsm_session_id.to_s
1075
+ raise Phronomy::Error, "Original dispatch preparation owner changed"
1076
+ end
1077
+ state
1078
+ end
1079
+
1080
+ def apply_retained_dispatch_on_event_loop(owner, outcome)
1081
+ environment = owner.environment
1082
+ registry = environment.registry
1083
+ assert_event_loop!(environment)
1084
+ state = retained_dispatch_state!(owner)
1085
+ dispatch_recovery_failed_on_event_loop(owner, nil) if owner.pending?
1086
+ command = owner.command
1087
+ if owner.continuation_authorized?
1088
+ unless state.execution.to_h == outcome.execution.to_h &&
1089
+ @agent.send(:__root_for_operation).to_h == command.root.to_h
1090
+ raise Phronomy::Persistence::StateConflictError, "Applied dispatch state changed before notification repair"
1091
+ end
1092
+ delivery = owner.continuation_delivery
1093
+ if owner.continuation_returned? && delivery&.retry_rejected! && delivery.finish_handoff?
1094
+ registry.mark_agent_execution_admission(@agent.agent_id,
1095
+ execution_id: owner.execution_id, state: :executing)
1096
+ owner.continuation_completed!
1097
+ return
1098
+ end
1099
+ raise Phronomy::ExecutionRehydrationRequiredError, "Dispatch continuation already authorized; it cannot be replayed"
1100
+ end
1101
+ phase = (owner.dispatch_kind == :provider) ? :calling_llm : :dispatching_tools
1102
+ unless environment.session_phase(command.fsm_session_id) == phase &&
1103
+ [command.execution.to_h, outcome.execution.to_h].include?(state.execution.to_h) &&
1104
+ @agent.send(:__root_for_operation).to_h == command.root.to_h
1105
+ raise Phronomy::Persistence::StateConflictError, "Original live dispatch pre/post state changed"
1106
+ end
1107
+ unless owner.applied?
1108
+ projection = outcome.respond_to?(:runtime_projection) && outcome.runtime_projection
1109
+ if projection
1110
+ registry.replace_agent_execution(owner.execution_id,
1111
+ execution: outcome.execution, runtime_projection: projection)
1112
+ else
1113
+ registry.replace_agent_execution(owner.execution_id, execution: outcome.execution)
1114
+ end
1115
+ state.invocation.acknowledge_runtime_snapshot(command.runtime_snapshot)
1116
+ owner.application_applied!
1117
+ end
1118
+ registry.mark_agent_execution_admission(@agent.agent_id,
1119
+ execution_id: owner.execution_id, state: :executing)
1120
+ owner.prepare_continuation
1121
+ registry.register_agent_completion_waiter(owner.execution_id, owner.continuation_task)
1122
+ delivery = owner.prepare_continuation_delivery
1123
+ error = outcome.respond_to?(:error) && outcome.error
1124
+ begin
1125
+ if owner.captured_cancellation_requested?
1126
+ raise Phronomy::CancellationError, "Agent execution cancellation was recorded before dispatch"
1127
+ end
1128
+ @agent.send(:check_cancellation!, state.invocation.config, "invocation cancelled before recovered dispatch")
1129
+ rescue Phronomy::CancellationError, Phronomy::TimeoutError => cancellation
1130
+ error = cancellation
1131
+ end
1132
+ # The local notification bridge can resend a positively rejected event,
1133
+ # but never restores the external dispatch authorization.
1134
+ return unless owner.authorize_continuation!
1135
+ if error
1136
+ event = (owner.dispatch_kind == :provider) ? :llm_setup_failed : :tool_setup_failed
1137
+ delivery.post(event, error)
1138
+ else
1139
+ # Authorization precedes the external admission edge. A raised call
1140
+ # does not prove rejection and cannot authorize business replay.
1141
+ if owner.dispatch_kind == :provider
1142
+ dispatch_prepared_provider_on_event_loop(command, outcome, state, event_sink: delivery)
1143
+ else
1144
+ dispatch_prepared_tools_on_event_loop(state, event_sink: delivery)
1145
+ end
1146
+ end
1147
+ owner.continuation_returned!
1148
+ raise runtime_rejected_error(:dispatch_continuation) unless delivery.finish_handoff?
1149
+ owner.continuation_completed!
1150
+ end
1151
+
963
1152
  # ----------------------------------------------------------------------
964
1153
  # Approval resume
965
1154
  # ----------------------------------------------------------------------
@@ -991,6 +1180,7 @@ module Phronomy
991
1180
  unless parent_wait.current? && !@suspended_cancellation
992
1181
  return fail_task(request.result_task, Phronomy::AgentBusyError.new("Hosted decision requires a restored child wait"))
993
1182
  end
1183
+ request.result_task.hosted_context&.validate_live!
994
1184
  end
995
1185
 
996
1186
  approval = state.execution.approval_request || {}
@@ -1006,6 +1196,7 @@ module Phronomy
1006
1196
  end
1007
1197
 
1008
1198
  operation = capture_approval_resume(state, request)
1199
+ retained_approval = retained_approval_eligible?(state, request)
1009
1200
  resume_transition_started = false
1010
1201
  submitted = false
1011
1202
  begin
@@ -1020,6 +1211,12 @@ module Phronomy
1020
1211
  end
1021
1212
  suspended_cancellation = clear_suspended_cancellation
1022
1213
  resume_transition_started = true
1214
+ if retained_approval
1215
+ return ApprovalRecoveryOperation.new(agent: @agent, coordinator: self,
1216
+ environment: environment, command: operation, request: request,
1217
+ invocation: state.invocation, suspended_cancellation: suspended_cancellation,
1218
+ committer: @approval_resume_commit).start
1219
+ end
1023
1220
  task = environment.submit(on_full: :raise) do
1024
1221
  @approval_resume_commit.commit(operation)
1025
1222
  end
@@ -1051,6 +1248,117 @@ module Phronomy
1051
1248
  raise unless resume_transition_started
1052
1249
  end
1053
1250
 
1251
+ # A live wait keeps its original cancellation authority. A restored hosted
1252
+ # child instead carries the exact parent's committed wait and saved proof.
1253
+ # Reservation content remains opaque to Agent and is compared in full.
1254
+ def retained_approval_eligible?(state, request)
1255
+ return false unless state.invocation && state.fsm_session_id.nil?
1256
+ participant = state.invocation.config[:phronomy_execution_participant]
1257
+ supported = if participant
1258
+ participant.respond_to?(:approval_recovery_supported?, true) &&
1259
+ participant.send(:approval_recovery_supported?, execution: state.execution, persistence: @agent.persistence)
1260
+ else
1261
+ !state.execution.metadata["execution_extension"]
1262
+ end
1263
+ return false unless supported
1264
+ binding = @suspended_cancellation
1265
+ task = request.result_task
1266
+ if task.is_a?(ApprovalOperation) && task.parent_wait
1267
+ !binding && task.hosted_context && task.parent_wait.current?
1268
+ else
1269
+ # Rehydration installs the exact suspended invocation and admission
1270
+ # without an original observation to bind. Preserve that distinction.
1271
+ !binding || (binding[0].to_s == state.execution_id.to_s && binding[1].equal?(state.invocation))
1272
+ end
1273
+ end
1274
+
1275
+ def approval_recovery_failed_on_event_loop(owner, _failure)
1276
+ environment = owner.environment
1277
+ assert_event_loop!(environment)
1278
+ return unless environment.registry.owns_approval_operation?(owner)
1279
+ environment.registry.mark_agent_execution_admission(@agent.agent_id,
1280
+ execution_id: owner.execution_id, state: :recovery_required)
1281
+ end
1282
+
1283
+ def restore_retained_approval_on_event_loop(owner)
1284
+ environment = owner.environment
1285
+ registry = environment.registry
1286
+ assert_event_loop!(environment)
1287
+ state = registry.agent_execution_state(owner.execution_id)
1288
+ unless registry.owns_approval_operation?(owner) && state.fsm_session_id.nil? &&
1289
+ state.execution.to_h == owner.command.execution.to_h &&
1290
+ @agent.send(:__root_for_operation).to_h == owner.command.root.to_h
1291
+ raise Phronomy::Persistence::StateConflictError, "Original approval wait changed before restoration"
1292
+ end
1293
+ owner.validate_hosted_authority!
1294
+ registry.mark_agent_execution_admission(@agent.agent_id,
1295
+ execution_id: owner.execution_id, state: :suspended)
1296
+ binding = owner.suspended_cancellation
1297
+ bind_suspended_cancellation(*binding.first(3)) if binding
1298
+ owner.application_applied!
1299
+ owner.continuation_completed!(:restored)
1300
+ if owner.captured_cancellation_requested?
1301
+ if binding
1302
+ cancel_suspended_on_event_loop(owner.execution_id)
1303
+ else
1304
+ # A restored wait has no original observation or cancellation
1305
+ # subscription. Its captured durable cancellation still owns the
1306
+ # same terminal continuation; do not fabricate a new live wait.
1307
+ finish_on_event_loop(owner.execution_id, owner.request.result_task,
1308
+ owner.invocation, Phronomy::CancellationError.new("Agent execution cancelled during approval"),
1309
+ fsm_session_id: nil)
1310
+ end
1311
+ end
1312
+ end
1313
+
1314
+ def build_retained_approval_task(name:, parent_wait:, hosted_context:)
1315
+ ApprovalOperation.new(agent: @agent, name: name,
1316
+ parent_wait: parent_wait, hosted_context: hosted_context).tap do |task|
1317
+ task.on_physical_complete { hosted_context&.release! }
1318
+ end
1319
+ end
1320
+
1321
+ def apply_retained_approval_on_event_loop(owner, outcome)
1322
+ environment = owner.environment
1323
+ registry = environment.registry
1324
+ assert_event_loop!(environment)
1325
+ state = registry.agent_execution_state(owner.execution_id)
1326
+ unless registry.owns_approval_operation?(owner) && state.invocation.equal?(owner.invocation)
1327
+ raise Phronomy::Error, "Original approval continuation owner changed"
1328
+ end
1329
+ owner.validate_hosted_authority!
1330
+ plan = owner.prepare_continuation
1331
+ unless state.fsm_session_id.nil? || state.fsm_session_id.to_s == plan.parent_id.to_s
1332
+ raise Phronomy::Error, "Original approval continuation session changed"
1333
+ end
1334
+ unless owner.applied?
1335
+ unless [owner.command.execution.to_h, outcome.execution.to_h].include?(state.execution.to_h) &&
1336
+ [owner.command.root.to_h, outcome.root.to_h].include?(@agent.send(:__root_for_operation).to_h)
1337
+ raise Phronomy::Persistence::StateConflictError, "Agent live approval pre/post state changed"
1338
+ end
1339
+ apply_agent_live_state(root: outcome.root, appended_records: [])
1340
+ registry.replace_agent_execution(owner.execution_id, execution: outcome.execution)
1341
+ registry.mark_agent_execution_admission(@agent.agent_id,
1342
+ execution_id: owner.execution_id, state: :executing)
1343
+ owner.application_applied!
1344
+ end
1345
+ # Terminal publication may synchronously unload the Agent. Include the
1346
+ # ordinary decision lease in the existing finish-all-waiters barrier.
1347
+ registry.register_agent_completion_waiter(owner.execution_id, owner.request.result_task)
1348
+ registry.register_agent_completion_waiter(owner.execution_id, owner.continuation_task)
1349
+ owner.observe_continuation_once do
1350
+ request = owner.request.with(result_task: owner.continuation_task)
1351
+ ready = ResumeCommitReady.new(coordinator: self, request: request,
1352
+ operation: owner.command, result: outcome, error: nil)
1353
+ observe_resumed_execution(ready, state)
1354
+ end
1355
+ registry.mark_agent_execution_admission(@agent.agent_id,
1356
+ execution_id: owner.execution_id, state: :executing)
1357
+ plan.resume
1358
+ owner.continuation_completed!(:resumed) if plan.complete?
1359
+ owner.continue_terminal_if_ready
1360
+ end
1361
+
1054
1362
  def capture_approval_resume(state, request)
1055
1363
  snapshot = if state.invocation
1056
1364
  Phronomy::Values::Immutable.copy(
@@ -1280,6 +1588,23 @@ module Phronomy
1280
1588
  )
1281
1589
  end
1282
1590
 
1591
+ if (dispatch_owner = environment.registry.dispatch_operation(execution_id))
1592
+ # An accepted continuation may finish after its admission reply was
1593
+ # lost. The matching session's completion proves the handoff occurred;
1594
+ # do not replay dispatch merely to repair the receipt.
1595
+ return unless dispatch_owner.continuation_authorized?
1596
+ dispatch_owner.continuation_completed!
1597
+ dispatch_owner.retire_after_delivery
1598
+ end
1599
+
1600
+ if (approval_owner = environment.registry.approval_operation(execution_id))
1601
+ handed_off = approval_owner.parent_finished(fsm_session_id) do
1602
+ finish_on_event_loop(execution_id, result_task, invocation, error,
1603
+ fsm_session_id: fsm_session_id)
1604
+ end
1605
+ return unless handed_off
1606
+ end
1607
+
1283
1608
  terminal_error = error || invocation&.error
1284
1609
  unless environment.registry.agent_execution_quiescent?(execution_id)
1285
1610
  wait_state = quiescence_sensitive_terminal_error?(terminal_error) ?
@@ -1380,9 +1705,19 @@ module Phronomy
1380
1705
  submit_terminal_operation(operation, delivery)
1381
1706
  end
1382
1707
 
1383
- def begin_terminal_without_session_on_event_loop(request:, prepared:, error:)
1708
+ def begin_terminal_after_start_failure_on_event_loop(request:, prepared:, error:)
1384
1709
  return deliver_start_failure_on_event_loop(request, error) unless prepared&.execution
1385
1710
 
1711
+ environment = @agent.__execution_environment
1712
+ state = environment.registry.agent_execution_state(prepared.execution.execution_id)
1713
+ if state && state.agent.equal?(@agent) && state.coordinator.equal?(self)
1714
+ # Installation succeeded before session entry failed. Preserve its
1715
+ # waiters and physical work until the ordinary terminal barrier ends.
1716
+ return finish_on_event_loop(state.execution_id, request.result_task,
1717
+ state.invocation, error, fsm_session_id: state.fsm_session_id)
1718
+ end
1719
+
1720
+ # A rejected installation does not own a same-ID state or its observers.
1386
1721
  operation = build_terminal_operation(
1387
1722
  execution: prepared.execution,
1388
1723
  root: prepared.root,
@@ -1390,7 +1725,8 @@ module Phronomy
1390
1725
  invocation: nil,
1391
1726
  source_error: error,
1392
1727
  fsm_session_id: nil,
1393
- state_required: false
1728
+ state_required: false,
1729
+ wiring: prepared.config
1394
1730
  )
1395
1731
  delivery = TerminalDelivery.new(
1396
1732
  result_task: request.result_task,
@@ -1399,7 +1735,7 @@ module Phronomy
1399
1735
  handoff_request: nil,
1400
1736
  handoff_manifest: nil
1401
1737
  )
1402
- submit_terminal_operation(operation, delivery)
1738
+ submit_terminal_operation(operation, delivery, admission_token: request.admission_token)
1403
1739
  end
1404
1740
 
1405
1741
  def build_terminal_operation(
@@ -1409,7 +1745,8 @@ module Phronomy
1409
1745
  invocation:,
1410
1746
  source_error:,
1411
1747
  fsm_session_id:,
1412
- state_required:
1748
+ state_required:,
1749
+ wiring: nil
1413
1750
  )
1414
1751
  TerminalCommitCommand.new(
1415
1752
  execution_id: execution.execution_id.to_s.freeze,
@@ -1421,7 +1758,7 @@ module Phronomy
1421
1758
  runtime_snapshot: invocation ? invocation.runtime_snapshot : empty_runtime_snapshot,
1422
1759
  terminal_view: terminal_view(invocation, source_error),
1423
1760
  state_required: state_required,
1424
- wiring: (invocation ? invocation.config : @agent.__execution_wiring).dup.freeze
1761
+ wiring: (wiring || (invocation ? invocation.config : @agent.__execution_wiring)).dup.freeze
1425
1762
  )
1426
1763
  end
1427
1764
 
@@ -1429,7 +1766,7 @@ module Phronomy
1429
1766
  ExecutionOutcomeCommitter.new(agent: @agent, persistence: @agent.persistence)
1430
1767
  end
1431
1768
 
1432
- def submit_terminal_operation(operation, delivery)
1769
+ def submit_terminal_operation(operation, delivery, admission_token: nil)
1433
1770
  environment = @agent.__execution_environment
1434
1771
  terminal_transition_started = false
1435
1772
  environment.registry.mark_agent_execution_admission(
@@ -1438,10 +1775,24 @@ module Phronomy
1438
1775
  state: :terminalizing
1439
1776
  )
1440
1777
  terminal_transition_started = true
1441
- environment.registry.register_agent_completion_waiter(
1442
- operation.execution_id,
1443
- delivery.result_task
1444
- )
1778
+ if operation.state_required
1779
+ environment.registry.register_agent_completion_waiter(
1780
+ operation.execution_id,
1781
+ delivery.result_task
1782
+ )
1783
+ end
1784
+ recovery_owner = if outcome_recovery_eligible?(operation)
1785
+ OutcomeRecoveryOperation
1786
+ elsif terminal_recovery_eligible?(operation)
1787
+ TerminalRecoveryOperation
1788
+ end
1789
+ if recovery_owner
1790
+ retained = recovery_owner.new(agent: @agent, coordinator: self,
1791
+ environment: environment, command: operation, delivery: delivery,
1792
+ committer: @outcome_committer, admission_token: admission_token).start
1793
+ return TerminalCustody.new(coordinator: self, operation: operation,
1794
+ task: nil, retained_owner: retained, error: nil)
1795
+ end
1445
1796
  task = environment.submit(on_full: :raise) do
1446
1797
  # Only the operation-specific immutable durable snapshot crosses the
1447
1798
  # worker boundary. TaskResult/listener delivery state stays outside it.
@@ -1459,6 +1810,8 @@ module Phronomy
1459
1810
  fail_task(delivery.result_task, runtime_rejected_error(:terminal_apply)) unless
1460
1811
  post_control(environment, ready)
1461
1812
  end
1813
+ TerminalCustody.new(coordinator: self, operation: operation,
1814
+ task: task, retained_owner: nil, error: nil)
1462
1815
  rescue => error
1463
1816
  if terminal_transition_started
1464
1817
  environment.registry.mark_agent_execution_admission(
@@ -1466,22 +1819,229 @@ module Phronomy
1466
1819
  execution_id: operation.execution_id,
1467
1820
  state: :recovery_required
1468
1821
  )
1822
+ fail_task(delivery.result_task, error) unless operation.state_required
1469
1823
  Phronomy::RuntimeSettings.current.logger&.warn(
1470
1824
  "[Phronomy] Agent terminal transition requires recovery for " \
1471
1825
  "#{operation.execution_id}: #{error.class}: #{error.message}"
1472
1826
  )
1473
- return
1827
+ return TerminalCustody.new(coordinator: self, operation: operation,
1828
+ task: nil, retained_owner: nil, error: error)
1474
1829
  end
1475
1830
 
1476
1831
  fail_task(delivery.result_task, error)
1477
1832
  raise
1478
1833
  end
1479
1834
 
1835
+ def terminal_recovery_eligible?(operation)
1836
+ view = operation.terminal_view
1837
+ error = view.source_error || view.block_error || view.invocation_error
1838
+ operation.state_required && operation.execution.status == :active &&
1839
+ view.phase != :suspended && !view.handoff &&
1840
+ !error.is_a?(Phronomy::ExecutionRehydrationRequiredError) &&
1841
+ !operation.execution.metadata["execution_extension"] &&
1842
+ !operation.wiring[:phronomy_execution_participant]
1843
+ end
1844
+
1845
+ # Accepted custody is independent of a participant's private replay
1846
+ # capability. The committer alone decides whether proof can be captured.
1847
+ def outcome_recovery_eligible?(operation)
1848
+ !!operation.wiring[:phronomy_execution_participant]
1849
+ end
1850
+
1851
+ # Observation completion is distinct from releasing the retained job.
1852
+ def terminal_recovery_failed_on_event_loop(owner, failure)
1853
+ environment = owner.environment
1854
+ assert_event_loop!(environment)
1855
+ return unless environment.registry.owns_terminal_operation?(owner)
1856
+ environment.registry.mark_agent_execution_admission(@agent.agent_id,
1857
+ execution_id: owner.execution_id, state: :recovery_required)
1858
+ if owner.recovery_kind == :outcome
1859
+ state = environment.registry.agent_execution_state(owner.execution_id)
1860
+ state.invocation.event_listener = nil if state&.invocation
1861
+ end
1862
+ waiters = terminal_waiters(environment, owner.execution_id, owner.delivery.result_task, registered: owner.command.state_required)
1863
+ owner.retain_original_waiters(waiters)
1864
+ waiters.each { |task| task.fail(failure) }
1865
+ begin
1866
+ cause = failure.cause || failure
1867
+ Phronomy::RuntimeSettings.current.logger&.warn(
1868
+ "[Phronomy] Agent #{owner.recovery_kind} durable outcome requires recovery for " \
1869
+ "#{owner.execution_id}: #{cause.class}: #{cause.message}"
1870
+ )
1871
+ rescue
1872
+ # Reporting cannot replace the recovery diagnostic or relinquish custody.
1873
+ nil
1874
+ end
1875
+ end
1876
+
1877
+ # A recovery receipt is applied only to the exact retained incarnation.
1878
+ # Local pre/post comparisons make a partial apply or release retry safe;
1879
+ # journal records and old application callbacks are never replayed.
1880
+ def apply_retained_terminal_on_event_loop(owner, outcome)
1881
+ environment = owner.environment
1882
+ registry = environment.registry
1883
+ command, delivery = owner.command, owner.delivery
1884
+ ordinary_delivery = owner.ordinary_delivery?
1885
+ apply_retained_outcome_state(owner, outcome, environment)
1886
+ unless registry.release_terminal_operation(owner)
1887
+ raise Phronomy::Error, "Agent terminal recovery ownership could not be released"
1888
+ end
1889
+ clear_suspended_cancellation if @suspended_cancellation&.first == command.execution_id
1890
+ event_type, result = retained_terminal_delivery(outcome, delivery)
1891
+ callback_error = if ordinary_delivery
1892
+ payload = (outcome.type == :failed) ? {error: outcome.error} : result
1893
+ deliver_terminal(delivery.application_listener, event_type, payload)
1894
+ end
1895
+ # A closed observer is never reopened; only ordinary delivery invokes
1896
+ # its application listener, including the original Handoff payload.
1897
+ settle_execution_waiters(environment, command.execution_id, delivery.result_task,
1898
+ callback_error, event_type, result, outcome.error, registered: command.state_required)
1899
+ end
1900
+
1901
+ def retained_terminal_delivery(outcome, delivery)
1902
+ case outcome.type
1903
+ when :failed then [terminal_event_type(outcome.error), nil]
1904
+ when :handed_off
1905
+ [:handoff, outcome.result.merge(handoff_request: delivery.handoff_request,
1906
+ _phronomy_handoff_manifest: delivery.handoff_manifest).freeze]
1907
+ else [:done, outcome.result]
1908
+ end
1909
+ end
1910
+
1911
+ def apply_retained_outcome_on_event_loop(owner, outcome)
1912
+ return apply_retained_terminal_on_event_loop(owner, outcome) if %i[completed failed handed_off].include?(outcome.type)
1913
+ unless %i[coordination_wait suspended].include?(outcome.type)
1914
+ raise Phronomy::Error, "Unsupported retained Agent outcome: #{outcome.type.inspect}"
1915
+ end
1916
+ environment = owner.environment
1917
+ command, delivery = owner.command, owner.delivery
1918
+ ordinary_delivery = owner.ordinary_delivery?
1919
+ state = apply_retained_outcome_state(owner, outcome, environment)
1920
+ if outcome.type == :coordination_wait
1921
+ begin
1922
+ unless environment.registry.release_terminal_operation(owner)
1923
+ raise Phronomy::Error, "Agent coordination wait recovery ownership could not be released"
1924
+ end
1925
+ rescue => error
1926
+ # Positive atomic release still requires publication of the saved
1927
+ # wait authority when only the local release reply was lost.
1928
+ raise error unless owner.released?
1929
+ end
1930
+ if ordinary_delivery && delivery.result_task.is_a?(OperationResult)
1931
+ delivery.result_task.coordination_wait_execution_id = command.execution_id
1932
+ end
1933
+ if !ordinary_delivery || delivery.result_task.is_a?(FrameworkRecoveryTask)
1934
+ @recovered_coordination_wait = RecoveredCoordinationWait.new(self, command.execution_id, outcome.execution.execution_revision)
1935
+ end
1936
+ terminal_waiters(environment, command.execution_id, delivery.result_task,
1937
+ registered: true).each { |task| fail_task(task, outcome.error) }
1938
+ else
1939
+ apply_retained_approval_wait(owner, outcome, state, environment, command, delivery, ordinary_delivery)
1940
+ end
1941
+ end
1942
+
1943
+ def apply_retained_approval_wait(owner, outcome, state, environment, command, delivery, ordinary_delivery)
1944
+ cancelled = owner.captured_cancellation_requested?
1945
+ wait_task = ordinary_delivery ? delivery.result_task : owner.suspension_task
1946
+ environment.registry.register_agent_completion_waiter(command.execution_id, wait_task)
1947
+ bind_suspended_cancellation(command.execution_id, state.invocation, wait_task)
1948
+ begin
1949
+ unless environment.registry.resolve_outcome_approval_wait(owner)
1950
+ raise Phronomy::Error, "Agent approval wait save ownership could not be resolved"
1951
+ end
1952
+ rescue => error
1953
+ # The registry may have completed its atomic save-owner resolution
1954
+ # before a wrapper lost the reply. Still connect captured cancellation
1955
+ # to the installed suspended execution in that case.
1956
+ raise error unless owner.released?
1957
+ end
1958
+ if ordinary_delivery
1959
+ dispatch_approval_listener(delivery.approval_listener, outcome.approval_request)
1960
+ callback_error = deliver_terminal(delivery.application_listener, :approval_required, request: outcome.approval_request)
1961
+ report_nonterminal_callback_error(callback_error, :approval_required, outcome.result)
1962
+ Array(state.invocation.config[:phronomy_exact_observers]).each do |task|
1963
+ fail_task(task, Phronomy::ExecutionRehydrationRequiredError.new("Execution #{command.execution_id} requires approval"))
1964
+ end
1965
+ end
1966
+ cancel_suspended_on_event_loop(command.execution_id) if cancelled
1967
+ end
1968
+
1969
+ def apply_retained_outcome_state(owner, outcome, environment)
1970
+ registry = environment.registry
1971
+ assert_event_loop!(environment)
1972
+ unless registry.owns_terminal_operation?(owner) && registry.agent_execution_quiescent?(owner.execution_id)
1973
+ raise Phronomy::Error, "Agent #{owner.recovery_kind} recovery ownership or physical quiescence changed"
1974
+ end
1975
+ command = owner.command
1976
+ state = registry.agent_execution_state(owner.execution_id)
1977
+ unless command.state_required
1978
+ raise Phronomy::Error, "Sessionless outcome acquired a different live session" if state
1979
+ apply_retained_sessionless_outcome(owner, outcome)
1980
+ return nil
1981
+ end
1982
+ unless state && state.agent.equal?(@agent) && state.coordinator.equal?(self) &&
1983
+ state.fsm_session_id.to_s == owner.fsm_session_id.to_s
1984
+ raise Phronomy::Error, "Agent #{owner.recovery_kind} recovery no longer owns the original session"
1985
+ end
1986
+ if owner.applied?
1987
+ unless state.execution.to_h == outcome.execution.to_h &&
1988
+ @agent.send(:__root_for_operation).to_h == outcome.root.to_h &&
1989
+ @agent.send(:_journal_records_snapshot) == command.journal_records + outcome.appended_records
1990
+ raise Phronomy::Persistence::StateConflictError, "Agent live post-state changed before outcome recovery release"
1991
+ end
1992
+ else
1993
+ apply_retained_terminal_state(owner, outcome, state, environment)
1994
+ owner.application_applied!
1995
+ end
1996
+ state
1997
+ end
1998
+
1999
+ def apply_retained_sessionless_outcome(owner, outcome)
2000
+ command = owner.command
2001
+ current_root = @agent.send(:__root_for_operation)
2002
+ current_records = @agent.send(:_journal_records_snapshot)
2003
+ after_records = command.journal_records + outcome.appended_records
2004
+ valid = if owner.applied?
2005
+ current_root.to_h == outcome.root.to_h && current_records == after_records
2006
+ else
2007
+ [command.root.to_h, outcome.root.to_h].include?(current_root.to_h) &&
2008
+ [command.journal_records, after_records].include?(current_records)
2009
+ end
2010
+ unless valid
2011
+ raise Phronomy::Persistence::StateConflictError, "Sessionless Agent root or journal changed before outcome apply"
2012
+ end
2013
+ return if owner.applied?
2014
+ apply_agent_live_state(root: outcome.root,
2015
+ appended_records: (current_records == command.journal_records) ? outcome.appended_records : [])
2016
+ owner.application_applied!
2017
+ end
2018
+
2019
+ def apply_retained_terminal_state(owner, outcome, state, environment)
2020
+ command = owner.command
2021
+ unless state.execution.to_h == owner.live_execution_before.to_h || state.execution.to_h == outcome.execution.to_h
2022
+ raise Phronomy::Persistence::StateConflictError, "Agent live execution changed before terminal recovery apply"
2023
+ end
2024
+ before_records = command.journal_records
2025
+ after_records = before_records + outcome.appended_records
2026
+ current_records = @agent.send(:_journal_records_snapshot)
2027
+ current_root = @agent.send(:__root_for_operation)
2028
+ unless [before_records, after_records].include?(current_records) &&
2029
+ [command.root.to_h, outcome.root.to_h].include?(current_root.to_h)
2030
+ raise Phronomy::Persistence::StateConflictError, "Agent live root or journal changed before terminal recovery apply"
2031
+ end
2032
+ apply_agent_live_state(root: outcome.root,
2033
+ appended_records: (current_records == before_records) ? outcome.appended_records : [])
2034
+ state.invocation&.acknowledge_runtime_snapshot(command.runtime_snapshot)
2035
+ environment.registry.replace_agent_execution(command.execution_id,
2036
+ execution: outcome.execution, fsm_session_id: state.fsm_session_id)
2037
+ end
2038
+
1480
2039
  def terminal_view(invocation, source_error)
1481
2040
  TerminalView.new(
1482
2041
  phase: invocation&.phase,
1483
2042
  output: invocation&.output,
1484
2043
  response: invocation&.final_response,
2044
+ output_contract: invocation&.output_contract,
1485
2045
  usage: invocation&.usage,
1486
2046
  approval_request: invocation&.approval_request,
1487
2047
  rejected: invocation ? !!invocation.rejected : false,
@@ -1506,7 +2066,7 @@ module Phronomy
1506
2066
  operation = ready.operation
1507
2067
  delivery = ready.delivery
1508
2068
  environment = @agent.__execution_environment
1509
- state = environment.registry.agent_execution_state(operation.execution_id)
2069
+ state = environment.registry.agent_execution_state(operation.execution_id) if operation.state_required
1510
2070
 
1511
2071
  if operation.state_required
1512
2072
  unless state && state.agent.equal?(@agent) &&
@@ -1550,7 +2110,8 @@ module Phronomy
1550
2110
  delivery = ready.delivery
1551
2111
  if operation.execution.metadata["reservation"] || operation.execution.metadata["execution_extension"]
1552
2112
  release_terminal_ownership(environment, operation.execution_id, state)
1553
- environment.registry.take_agent_completion_waiters(operation.execution_id, fallback: delivery.result_task).each do |task|
2113
+ terminal_waiters(environment, operation.execution_id, delivery.result_task,
2114
+ registered: operation.state_required).each do |task|
1554
2115
  fail_task(task, ready.error)
1555
2116
  end
1556
2117
  return
@@ -1560,6 +2121,7 @@ module Phronomy
1560
2121
  execution_id: operation.execution_id,
1561
2122
  state: :recovery_required
1562
2123
  )
2124
+ fail_task(delivery.result_task, ready.error) unless operation.state_required
1563
2125
  Phronomy::RuntimeSettings.current.logger&.warn(
1564
2126
  "[Phronomy] Agent terminal durable outcome requires recovery for " \
1565
2127
  "#{operation.execution_id}: #{ready.error.class}: #{ready.error.message}"
@@ -1593,7 +2155,8 @@ module Phronomy
1593
2155
  elsif delivery.result_task.is_a?(FrameworkRecoveryTask)
1594
2156
  @recovered_coordination_wait = RecoveredCoordinationWait.new(self, operation.execution_id, outcome.execution.execution_revision)
1595
2157
  end
1596
- environment.registry.take_agent_completion_waiters(operation.execution_id, fallback: delivery.result_task).each { |task| fail_task(task, outcome.error) }
2158
+ terminal_waiters(environment, operation.execution_id, delivery.result_task,
2159
+ registered: operation.state_required).each { |task| fail_task(task, outcome.error) }
1597
2160
  end
1598
2161
 
1599
2162
  def suspend_execution_on_event_loop(ready, state, environment)
@@ -1670,7 +2233,7 @@ module Phronomy
1670
2233
  callback_error = deliver_terminal(delivery.application_listener, :done, outcome.result)
1671
2234
  settle_execution_waiters(
1672
2235
  environment, operation.execution_id, delivery.result_task,
1673
- callback_error, :done, outcome.result
2236
+ callback_error, :done, outcome.result, registered: operation.state_required
1674
2237
  )
1675
2238
  end
1676
2239
 
@@ -1686,7 +2249,7 @@ module Phronomy
1686
2249
  callback_error = deliver_terminal(delivery.application_listener, :handoff, result)
1687
2250
  settle_execution_waiters(
1688
2251
  environment, operation.execution_id, delivery.result_task,
1689
- callback_error, :handoff, result
2252
+ callback_error, :handoff, result, registered: operation.state_required
1690
2253
  )
1691
2254
  end
1692
2255
 
@@ -1703,7 +2266,7 @@ module Phronomy
1703
2266
  )
1704
2267
  settle_execution_waiters(
1705
2268
  environment, operation.execution_id, delivery.result_task,
1706
- callback_error, type, nil, outcome.error
2269
+ callback_error, type, nil, outcome.error, registered: operation.state_required
1707
2270
  )
1708
2271
  end
1709
2272
 
@@ -1795,12 +2358,9 @@ module Phronomy
1795
2358
 
1796
2359
  def settle_execution_waiters(
1797
2360
  environment, execution_id, fallback_task, callback_error, event_type,
1798
- result, execution_error = nil
2361
+ result, execution_error = nil, registered: true
1799
2362
  )
1800
- waiters = environment.registry.take_agent_completion_waiters(
1801
- execution_id,
1802
- fallback: fallback_task
1803
- )
2363
+ waiters = terminal_waiters(environment, execution_id, fallback_task, registered: registered)
1804
2364
  # All these waiters observe the same terminal execution. A synchronous
1805
2365
  # completion callback may request unload immediately, so acknowledge
1806
2366
  # every finished operation before publishing any logical result. Each
@@ -1814,6 +2374,12 @@ module Phronomy
1814
2374
  end
1815
2375
  end
1816
2376
 
2377
+ def terminal_waiters(environment, execution_id, fallback_task, registered:)
2378
+ return [fallback_task] unless registered
2379
+
2380
+ environment.registry.take_agent_completion_waiters(execution_id, fallback: fallback_task)
2381
+ end
2382
+
1817
2383
  def report_nonterminal_callback_error(callback_error, event_type, result)
1818
2384
  return unless callback_error
1819
2385
 
@@ -1880,7 +2446,7 @@ module Phronomy
1880
2446
  admission = command.is_a?(StartCommand) || command.is_a?(ResumeCommand)
1881
2447
  completion = case command
1882
2448
  when StartCommand, ResumeCommand then command.result_task
1883
- when InitialPreparationReady, ResumeCommitReady then command.request.result_task
2449
+ when ResumeCommitReady then command.request.result_task
1884
2450
  when InitialPreparationRecoveryReady then command.load_completion
1885
2451
  when TerminalCommitReady then command.delivery.result_task
1886
2452
  when DeferredTerminalCommand then command.result_task