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
@@ -0,0 +1,176 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Phronomy
4
+ module MultiAgent
5
+ # Detached routing and retention facts for one Handoff-owned Agent dispatch.
6
+ # Agent owns the execution write; this adapter preserves Handoff authority
7
+ # without replaying its participant, a transfer, or Target admission.
8
+ # @api private
9
+ class HandoffDispatchEvidence
10
+ def self.capture(values:, persistence:, handoff_persistence:, main_agent_id:, expected_revision:, binding_key:)
11
+ new(values, persistence, handoff_persistence, main_agent_id, expected_revision, binding_key)
12
+ end
13
+
14
+ def initialize(values, persistence, handoff_persistence, main_agent_id, expected_revision, binding_key)
15
+ @persistence_identity = persistence.execution_evidence_identity
16
+ @handoff_persistence = handoff_persistence
17
+ @main_agent_id = main_agent_id.to_s.dup.freeze
18
+ @expected_revision = expected_revision
19
+ @binding_key = binding_key.to_s.dup.freeze
20
+ execution = values.fetch(:result)
21
+ @agent_id, @execution_id = execution.agent_id, execution.execution_id
22
+ @owner = {"kind" => "handoff", "main_agent_id" => @main_agent_id}.freeze
23
+ @owner_key = "handoff:#{@main_agent_id}".freeze
24
+ validate_store!(persistence)
25
+ capture_participation!(values)
26
+ validate_execution!(values.fetch(:before).fetch(0).fetch(1))
27
+ validate_execution!(values.fetch(:after).fetch(0).fetch(1))
28
+ unless values.fetch(:after).fetch(0).fetch(1) == execution.to_h
29
+ raise Phronomy::Persistence::StateConflictError, "Handoff dispatch result differs from captured execution"
30
+ end
31
+ freeze
32
+ end
33
+ private_class_method :new
34
+
35
+ # Match admission, cancellation and commit: routing before Agent guards.
36
+ def guarded_agent_ids(persistence:, scope:)
37
+ validate_store!(persistence)
38
+ @handoff_persistence.participate(scope) { |records| records.handoff_states.load_locked(@main_agent_id) }
39
+ @agent_ids
40
+ end
41
+
42
+ def read(persistence:, scope:)
43
+ validate_store!(persistence)
44
+ routing = @handoff_persistence.participate(scope) { |records| records.handoff_states.load(@main_agent_id) }
45
+ [routing&.to_h, @agent_ids.map { |id|
46
+ persistence.retained_references(agent_id: id, scope: scope).map(&:to_h)
47
+ .sort_by { |hold| Phronomy::CanonicalJSON.dump(hold) }
48
+ }]
49
+ end
50
+
51
+ # The caller first asserts retry authority in the same guarded scope.
52
+ # Dispatch changes no Handoff records; retry writes only Agent's proof.
53
+ def replay(persistence:, scope:)
54
+ validate_store!(persistence)
55
+ nil
56
+ end
57
+
58
+ def assert_retryable!(persistence:, scope:)
59
+ assert_current!(persistence: persistence, scope: scope)
60
+ end
61
+
62
+ def assert_continuable!(persistence:, scope:)
63
+ assert_current!(persistence: persistence, scope: scope)
64
+ end
65
+
66
+ private
67
+
68
+ def capture_participation!(values)
69
+ before, after = values.fetch(:before).fetch(1), values.fetch(:after).fetch(1)
70
+ unless before == after && before.is_a?(Array) && before.length == 2
71
+ raise Phronomy::Persistence::StateConflictError, "Handoff dispatch changed its participant footprint"
72
+ end
73
+ @participation = Phronomy::Values::Immutable.copy(before)
74
+ @routing = HandoffState.from_h(@participation.fetch(0))
75
+ unless @routing.main_agent_id == @main_agent_id
76
+ raise Phronomy::Persistence::StateConflictError, "Handoff dispatch belongs to another anchor"
77
+ end
78
+ ids = [@main_agent_id, @agent_id]
79
+ ids << @routing.metadata["source_agent_id"] unless @routing.phase == "stable"
80
+ @agent_ids = ids.compact.uniq.sort.freeze
81
+ unless @participation.fetch(1).is_a?(Array) && @participation.fetch(1).length == @agent_ids.length
82
+ raise Phronomy::Persistence::StateConflictError, "Handoff dispatch retention footprint is incomplete"
83
+ end
84
+ @agent_ids.zip(@participation.fetch(1)).each do |id, holds|
85
+ unless holds.is_a?(Array) && holds.all? { |hold| hold.fetch("agent_id") == id }
86
+ raise Phronomy::Persistence::StateConflictError, "Handoff dispatch retention identities differ"
87
+ end
88
+ end
89
+ end
90
+
91
+ def validate_execution!(execution)
92
+ metadata = execution.fetch("metadata")
93
+ binding = metadata.fetch("execution_extension")
94
+ unless execution.fetch("agent_id") == @agent_id && execution.fetch("execution_id") == @execution_id &&
95
+ binding.fetch("binding_key") == @binding_key && binding.fetch("binding_version") == 1 &&
96
+ metadata["reservation"] == @owner
97
+ raise Phronomy::Persistence::StateConflictError, "Handoff dispatch execution identity or binding differs"
98
+ end
99
+ end
100
+
101
+ def assert_current!(persistence:, scope:)
102
+ unless read(persistence: persistence, scope: scope) == @participation
103
+ raise Phronomy::Persistence::StateConflictError, "Handoff routing or retention changed before dispatch"
104
+ end
105
+ assert_route!
106
+ assert_execution!(persistence, scope)
107
+ assert_retention!
108
+ assert_target!(persistence, scope) unless @routing.phase == "stable"
109
+ nil
110
+ end
111
+
112
+ def assert_route!
113
+ current = @routing.active_agent_id == @agent_id && @routing.handoff_revision == @expected_revision &&
114
+ (@routing.phase == "stable" || @routing.pending_target_execution_id == @execution_id)
115
+ unless current
116
+ raise Phronomy::Persistence::StateConflictError, "Handoff no longer owns this exact dispatch"
117
+ end
118
+ end
119
+
120
+ def assert_execution!(persistence, scope)
121
+ observed = persistence.observe_execution(agent_id: @agent_id, execution_id: @execution_id, scope: scope)
122
+ reservation = Phronomy::Agent::ReservedExecution.new(agent_id: @agent_id,
123
+ execution_id: @execution_id, correlation: @owner)
124
+ unless observed.status == :active && observed.reservation == reservation
125
+ raise Phronomy::Persistence::StateConflictError, "Handoff dispatch reservation is no longer active"
126
+ end
127
+ if observed.cancellation_requested || Array(@routing.metadata["cancelled_execution_ids"]).include?(@execution_id)
128
+ raise Phronomy::CancellationError, "Handoff dispatch was cancelled"
129
+ end
130
+ end
131
+
132
+ def assert_retention!
133
+ @agent_ids.zip(@participation.fetch(1)).each do |id, holds|
134
+ exact_target = id == @agent_id && @routing.phase != "stable"
135
+ unless holds.any? { |hold|
136
+ hold.fetch("owner_key") == @owner_key &&
137
+ (!exact_target || hold["execution_id"] == @execution_id)
138
+ }
139
+ raise Phronomy::Persistence::StateConflictError, "Handoff dispatch required retention is absent"
140
+ end
141
+ exact_source = id == @routing.metadata["source_agent_id"] && @routing.phase != "stable"
142
+ if exact_source && holds.none? { |hold|
143
+ hold.fetch("owner_key") == @owner_key && hold["execution_id"] == @routing.pending_source_execution_id
144
+ }
145
+ raise Phronomy::Persistence::StateConflictError, "Handoff Source transfer retention is absent"
146
+ end
147
+ end
148
+ end
149
+
150
+ def assert_target!(persistence, scope)
151
+ definition = persistence.definition(agent_id: @agent_id, scope: scope).transform_keys(&:to_s)
152
+ unless definition == @routing.metadata["target_definition"]
153
+ raise Phronomy::Persistence::StateConflictError, "Handoff Target definition changed before dispatch"
154
+ end
155
+ source_id = @routing.pending_source_execution_id
156
+ identity = persistence.execution_identity(source_id, scope: scope)
157
+ source = persistence.observe_execution(agent_id: identity.agent_id, execution_id: source_id, scope: scope)
158
+ receipt = source.transfer_receipt
159
+ unless identity.correlation == @owner && identity.agent_id == @routing.metadata["source_agent_id"] &&
160
+ source.status == :handed_off && receipt && receipt["target_agent_id"] == @agent_id &&
161
+ receipt["target_execution_id"] == @execution_id && receipt["context_ref"] == @routing.active_handoff_context_ref &&
162
+ receipt["owner_key"] == @owner_key
163
+ raise Phronomy::Persistence::StateConflictError, "Handoff Target no longer matches its Source transfer"
164
+ end
165
+ end
166
+
167
+ def validate_store!(persistence)
168
+ unless persistence.execution_evidence_identity.equal?(@persistence_identity) &&
169
+ @handoff_persistence.agent_store.equal?(persistence) &&
170
+ @handoff_persistence.coordinator.equal?(persistence.coordinator)
171
+ raise Phronomy::Persistence::StateConflictError, "Handoff dispatch proof belongs to another Store"
172
+ end
173
+ end
174
+ end
175
+ end
176
+ end
@@ -0,0 +1,33 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Phronomy
4
+ module MultiAgent
5
+ # A saved unsuccessful Target and an unconfirmed parent routing transition.
6
+ # The execution result remains authoritative; this error never changes it.
7
+ # Resolve any original Agent custody, then explicitly resume or cancel the
8
+ # same chain entry to retry only current, guarded routing finalization.
9
+ # @api public
10
+ class HandoffFinalizationError < Phronomy::HandoffError
11
+ attr_reader :main_agent_id, :execution_id, :target_execution_id,
12
+ :execution_result, :execution_error, :finalization_error, :read_error, :disposition
13
+
14
+ # execution_id is the requested chain entry, not necessarily its first root.
15
+ # @api public
16
+ def initialize(main_agent_id:, execution_id:, execution_result:, execution_error:, finalization_error:,
17
+ disposition: :not_attempted, read_error: nil)
18
+ unless %i[not_attempted not_committed unknown].include?(disposition)
19
+ raise ArgumentError, "Unsupported Handoff finalization disposition"
20
+ end
21
+ @main_agent_id, @execution_id = main_agent_id.to_s.dup.freeze, execution_id.to_s.dup.freeze
22
+ @execution_result = Phronomy::Values::Immutable.copy(execution_result)
23
+ @target_execution_id = @execution_result.fetch(:execution_id)
24
+ @execution_error = execution_error
25
+ @finalization_error, @read_error, @disposition = finalization_error, read_error, disposition
26
+ saved = @execution_error&.message || "Saved Target status #{@execution_result.fetch(:status)}"
27
+ super("#{saved}; Handoff finalization for #{@target_execution_id.inspect} is #{disposition}: " \
28
+ "#{finalization_error.message}. Resolve original Agent custody if present, then explicitly " \
29
+ "resume or cancel #{@execution_id.inspect}", code: "handoff.finalization_unconfirmed")
30
+ end
31
+ end
32
+ end
33
+ end
@@ -0,0 +1,80 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Phronomy
4
+ module MultiAgent
5
+ # A stable routing row can be visible before its terminal worker returns.
6
+ # Reserve the routing caller and every retained local Agent before dropping
7
+ # durable history. The final transaction rechecks the complete authority.
8
+ # @api private
9
+ class HandoffHistoryRelease
10
+ def initialize(store, main_agent_id)
11
+ @store, @agent_store, @main_id = store, store.agent_store, main_agent_id
12
+ @owner_key = "handoff:#{@main_id}"
13
+ end
14
+
15
+ def call
16
+ if Phronomy::WaitPolicy.blocking_forbidden?
17
+ raise Phronomy::EventLoopReentrancyError, "Handoff history release requires a host thread"
18
+ end
19
+ route, references = @store.transaction { |records, scope| capture(records, scope) }
20
+ main = Phronomy::Agent::Base.get(@main_id)
21
+ unless main && main.persistence.equal?(@agent_store)
22
+ raise Phronomy::ExecutionRehydrationRequiredError, "Load the Handoff main Agent in its owning Store before removing history"
23
+ end
24
+
25
+ admissions = ExecutionEnvironment.current.admissions
26
+ Thread.handle_interrupt(Object => :never) do
27
+ begin
28
+ admissions.admit!(main)
29
+ rescue Phronomy::HandoffError => error
30
+ raise Phronomy::AgentBusyError, error.message
31
+ end
32
+ begin
33
+ Thread.handle_interrupt(Object => :immediate) do
34
+ executions = references.transform_values { |holds| holds.filter_map(&:execution_id) }
35
+ main.__execution_environment.with_idle_history_owners(persistence: @agent_store, executions: executions, anchor: main) do
36
+ remove(route, references)
37
+ end
38
+ end
39
+ ensure
40
+ admissions.release!(main)
41
+ end
42
+ end
43
+ end
44
+
45
+ private
46
+
47
+ def capture(records, scope)
48
+ unless scope.outermost?
49
+ raise Phronomy::Persistence::TransactionError, "Handoff history release requires an outermost transaction"
50
+ end
51
+ routing = records.handoff_states.load_locked(@main_id)
52
+ raise Phronomy::Persistence::NotFoundError, "Handoff history is absent" unless routing
53
+ ids = (Array(routing.metadata["retained_agent_ids"]) + [@main_id, routing.active_agent_id]).uniq.sort
54
+ @agent_store.guard_agents(scope, agent_ids: ids)
55
+ unless routing.phase == "stable" && ids.all? { |id| @agent_store.active_executions(agent_id: id, scope: scope).empty? }
56
+ raise Phronomy::AgentBusyError, "Handoff history retains unfinished work"
57
+ end
58
+ references = ids.to_h do |id|
59
+ holds = @agent_store.retained_references(agent_id: id, scope: scope)
60
+ .select { |hold| hold.owner_key == @owner_key }.sort_by { |hold| hold.execution_id.to_s }
61
+ raise Phronomy::Persistence::StateConflictError, "Handoff retention is missing" if holds.empty?
62
+ [id, holds]
63
+ end
64
+ [routing.to_h, references]
65
+ end
66
+
67
+ def remove(route, references)
68
+ @store.transaction do |records, scope|
69
+ current, holds = capture(records, scope)
70
+ unless current == route && holds == references
71
+ raise Phronomy::Persistence::StateConflictError, "Handoff history authority changed before release"
72
+ end
73
+ records.handoff_states.delete(@main_id, expected_revision: route.fetch("handoff_revision"))
74
+ holds.each_key { |id| @agent_store.release_retention(agent_id: id, owner_key: @owner_key, scope: scope) }
75
+ end
76
+ true
77
+ end
78
+ end
79
+ end
80
+ end
@@ -8,24 +8,43 @@ module Phronomy
8
8
  # participant sees public semantic values only, never Agent records.
9
9
  # @api private
10
10
  class HandoffParticipant
11
+ BINDING_KEY = "phronomy.handoff"
12
+
11
13
  def initialize(persistence:, main_agent_id:, expected_revision:)
12
14
  @persistence, @main_agent_id, @expected_revision = persistence, main_agent_id, expected_revision
13
15
  end
14
16
 
15
17
  def binding
16
- Phronomy::Agent::ExecutionExtensionState.new(binding_key: "phronomy.handoff", binding_version: 1)
18
+ Phronomy::Agent::ExecutionExtensionState.new(binding_key: BINDING_KEY, binding_version: 1)
19
+ end
20
+
21
+ # Eligibility uses captured identity only; the owner performs no Store I/O.
22
+ private def dispatch_recovery_supported?(execution:, persistence:)
23
+ extension = execution.metadata["execution_extension"]
24
+ persistence.equal?(@persistence.agent_store) &&
25
+ extension&.fetch("binding_key") == BINDING_KEY &&
26
+ extension.fetch("binding_version") == 1 &&
27
+ execution.metadata["reservation"] == {"kind" => "handoff", "main_agent_id" => @main_agent_id}
28
+ end
29
+
30
+ private def capture_dispatch_recovery(values:, persistence:)
31
+ HandoffDispatchEvidence.capture(values: values, persistence: persistence,
32
+ handoff_persistence: @persistence, main_agent_id: @main_agent_id,
33
+ expected_revision: @expected_revision, binding_key: BINDING_KEY)
17
34
  end
18
35
 
19
36
  def guard_change(change, scope)
20
- @persistence.participate(scope) { |records| records.handoff_states.load_locked(@main_agent_id) }
21
- ids = [@main_agent_id, change.agent_id, change.control_request&.target_agent_id].compact
22
- @persistence.agent_store.guard_agents(scope, agent_ids: ids)
37
+ state = @persistence.participate(scope) { |records| records.handoff_states.load_locked(@main_agent_id) }
38
+ @persistence.agent_store.guard_agents(scope, agent_ids: change_agent_ids(change, state))
23
39
  end
24
40
 
25
41
  def change_evidence(change, scope)
26
42
  state = @persistence.participate(scope) { |records| records.handoff_states.load(@main_agent_id) }
27
- ids = [@main_agent_id, change.agent_id, change.control_request&.target_agent_id].compact.uniq.sort
28
- [state&.to_h, ids.map { |id| @persistence.agent_store.retained_references(agent_id: id, scope: scope).map(&:to_h) }]
43
+ ids = change_agent_ids(change, state)
44
+ [state&.to_h, ids.map { |id|
45
+ @persistence.agent_store.retained_references(agent_id: id, scope: scope).map(&:to_h)
46
+ .sort_by { |hold| Phronomy::CanonicalJSON.dump(hold) }
47
+ }]
29
48
  end
30
49
 
31
50
  def commit(change)
@@ -70,6 +89,12 @@ module Phronomy
70
89
 
71
90
  private
72
91
 
92
+ def change_agent_ids(change, state)
93
+ ids = [@main_agent_id, change.agent_id, change.control_request&.target_agent_id]
94
+ ids << state.metadata["source_agent_id"] if state && state.phase != "stable"
95
+ ids.compact.uniq.sort
96
+ end
97
+
73
98
  def retain(scope, id, execution_id)
74
99
  @persistence.agent_store.retain(Phronomy::Agent::Retention.new(agent_id: id, execution_id: execution_id,
75
100
  owner_key: "handoff:#{@main_agent_id}"), scope: scope)
@@ -26,46 +26,34 @@ module Phronomy
26
26
  end
27
27
 
28
28
  def invoke(input, config: {})
29
- raise Phronomy::EventLoopReentrancyError, "HandoffRunner#invoke cannot block EventLoop" if Phronomy::WaitPolicy.blocking_forbidden?
30
- raise Phronomy::RuntimeShutdownError, "HandoffRunner belongs to a previous Runtime" unless @environment.current?
29
+ assert_execution_thread!(:invoke)
31
30
  trace = Phronomy::Tracing::Automatic.start("multi_agent.turn", input: input, main_agent_id: main_agent.agent_id)
32
31
  error = result = nil
33
32
  config = config.merge(cancellation_token: config[:cancellation_token] || Phronomy::Concurrency::CancellationToken.new)
34
33
  @admissions.admit!(main_agent)
35
34
  admitted = true
36
35
  state = load_state
36
+ chain_entry = state.pending_source_execution_id unless state.phase == "stable"
37
37
  count = 0
38
38
  loop do
39
- active = @agents.fetch(state.active_agent_id) { raise Phronomy::ExecutionRehydrationRequiredError, "Handoff graph lacks active Agent #{state.active_agent_id}" }
40
- context = state.active_handoff_context_ref && Phronomy::Agent::TransferContext.from_h(@persistence.contents.fetch_json(state.active_handoff_context_ref))
41
- owner = {"kind" => "handoff", "main_agent_id" => main_agent.agent_id}.freeze
42
- wiring = config.merge(phronomy_control_bindings: @bindings.fetch(active.agent_id, []), phronomy_transfer_context: context,
43
- phronomy_execution_participant: HandoffParticipant.new(persistence: @persistence, main_agent_id: main_agent.agent_id, expected_revision: state.handoff_revision),
44
- phronomy_reservation: owner, phronomy_admission: ReservedChildAdmission.new(persistence: @persistence, owner: owner))
39
+ active = agent_for(state.active_agent_id)
40
+ wiring = execution_config(active, state, config)
45
41
  result = if state.phase == "stable"
46
42
  unfinished = @persistence.agent_store.active_executions(agent_id: active.agent_id)
47
43
  if unfinished.empty?
48
44
  active.invoke(input, config: wiring)
49
45
  else
50
46
  exact = unfinished.fetch(0)
51
- unless unfinished.size == 1 && exact.reservation&.correlation == owner
47
+ unless unfinished.size == 1 && exact.reservation&.correlation == handoff_owner
52
48
  raise Phronomy::Persistence::StateConflictError, "Active execution belongs to another turn"
53
49
  end
54
50
  wiring[:cancellation_token].cancel! if Array(state.metadata["cancelled_execution_ids"]).include?(exact.execution_id)
55
51
  active.resume_async(exact.execution_id, config: wiring).wait_result
56
52
  end
57
53
  else
58
- source = @persistence.agent_store.execution_identity(state.pending_source_execution_id)
59
- unless @handoffs.any? { |edge| edge.source_agent.agent_id == source.agent_id && edge.target_agent.agent_id == state.active_agent_id }
60
- raise Phronomy::ExecutionRehydrationRequiredError, "Handoff graph lacks committed Source/Target edge"
61
- end
62
- unless active.class.agent_definition == state.metadata.fetch("target_definition").transform_keys(&:to_sym)
63
- raise Phronomy::ConfigurationError, "Handoff Target definition mismatch"
64
- end
65
- wiring[:cancellation_token].cancel! if Array(state.metadata["cancelled_execution_ids"]).include?(state.pending_target_execution_id)
66
- reservation = Phronomy::Agent::ReservedExecution.new(agent_id: active.agent_id, execution_id: state.pending_target_execution_id, correlation: owner)
67
- active.start_reserved_async(reservation: reservation, input: context.responsibility, config: wiring).wait_result
54
+ start_target(active, state, wiring)
68
55
  end
56
+ chain_entry ||= result.fetch(:execution_id)
69
57
  observed = @persistence.agent_store.observe_execution(agent_id: active.agent_id, execution_id: result.fetch(:execution_id))
70
58
  if observed.status == :handed_off
71
59
  count += 1
@@ -74,6 +62,7 @@ module Phronomy
74
62
  next
75
63
  end
76
64
  raise Phronomy::ExecutionRehydrationRequiredError, "Handoff requires approval or recovery" if observed.active?
65
+ finalize_terminal(observed, chain_entry)
77
66
  observed.value!
78
67
  return result.reject { |key, _| key.to_s.start_with?("_phronomy_") || key == :handoff_request }.merge(agent: active)
79
68
  end
@@ -89,8 +78,71 @@ module Phronomy
89
78
  Phronomy::Tracing::Automatic.finish(trace, output: result && result[:output], error: error) if trace
90
79
  end
91
80
 
81
+ # Continues only the recorded chain rooted at this execution identity.
82
+ # Terminal history is returned without invoking another turn. An exact
83
+ # unsuccessful pending Target first finalizes its parent routing; a saved
84
+ # failure remains a failure. result is the read-only observation API. A retained
85
+ # dispatch save must be reconciled explicitly through its original Agent
86
+ # before this method can continue; resume never chooses a retry policy.
87
+ # The result contains durable execution fields plus the terminal Agent,
88
+ # not transient fields from the original live invocation. Saved failures
89
+ # keep the Runner's existing exception semantics. MAX_HANDOFFS limits the
90
+ # newly driven segment; already recorded links are only read and checked.
91
+ # @param execution_id [String] an execution belonging to this Handoff anchor
92
+ # @return [Hash] the saved leaf result and its Agent
93
+ # @raise [ExecutionRehydrationRequiredError] when explicit recovery is needed
94
+ # @api public
95
+ def resume(execution_id, config: {})
96
+ assert_execution_thread!(:resume)
97
+ unless execution_id.is_a?(String) && !execution_id.empty?
98
+ raise ArgumentError, "execution_id must be a nonempty String"
99
+ end
100
+ trace = Phronomy::Tracing::Automatic.start("multi_agent.resume", execution_id: execution_id, main_agent_id: main_agent.agent_id)
101
+ error = result = nil
102
+ config = config.merge(cancellation_token: config[:cancellation_token] || Phronomy::Concurrency::CancellationToken.new)
103
+ saved = @persistence.handoff_leaf(execution_id, main_agent_id: main_agent.agent_id)
104
+ if saved.terminal?
105
+ finalize_terminal(saved, execution_id)
106
+ return result = saved.value!.merge(agent: agent_for(saved.agent_id))
107
+ end
108
+ @admissions.admit!(main_agent)
109
+ admitted = true
110
+ count = 0
111
+ loop do
112
+ state, leaf = resumable_turn(execution_id)
113
+ active = agent_for(leaf.agent_id)
114
+ if leaf.terminal?
115
+ finalize_terminal(leaf, execution_id)
116
+ return result = leaf.value!.merge(agent: active)
117
+ end
118
+ require_dispatch_recovery_resolved!(active, leaf.execution_id)
119
+ wiring = execution_config(active, state, config)
120
+ result = if leaf.absent?
121
+ start_target(active, state, wiring)
122
+ else
123
+ active.resume_async(leaf.execution_id, config: wiring).wait_result
124
+ end
125
+ observed = @persistence.agent_store.observe_execution(agent_id: active.agent_id, execution_id: result.fetch(:execution_id))
126
+ raise Phronomy::ExecutionRehydrationRequiredError, "Handoff requires approval or recovery" if observed.active?
127
+ if observed.status == :handed_off
128
+ count += 1
129
+ raise Phronomy::HandoffError, "Exceeded maximum Handoffs in one continuation segment" if count > MAX_HANDOFFS
130
+ end
131
+ end
132
+ rescue Phronomy::CancellationError => caught
133
+ error = caught
134
+ cancel(execution_id) if admitted && config[:cancellation_token].cancelled?
135
+ raise
136
+ rescue => caught
137
+ error = caught
138
+ raise
139
+ ensure
140
+ @admissions.release!(main_agent) if admitted
141
+ Phronomy::Tracing::Automatic.finish(trace, output: result && result[:output], error: error) if trace
142
+ end
143
+
92
144
  def cancel(execution_id)
93
- raise Phronomy::EventLoopReentrancyError, "HandoffRunner#cancel cannot block EventLoop" if Phronomy::WaitPolicy.blocking_forbidden?
145
+ assert_execution_thread!(:cancel)
94
146
  leaf = intended = nil
95
147
  begin
96
148
  @persistence.transaction do |records, scope|
@@ -118,7 +170,10 @@ module Phronomy
118
170
  end
119
171
  raise failure unless proof.disposition == :committed
120
172
  end
121
- return leaf.to_result if leaf.terminal?
173
+ if leaf.terminal?
174
+ finalize_terminal(leaf, execution_id)
175
+ return leaf.to_result
176
+ end
122
177
  @agents[leaf.agent_id]&.cancel_async(leaf.execution_id)&.wait_result if leaf.active?
123
178
  {execution_id: leaf.execution_id, cancellation_requested: true}.freeze
124
179
  end
@@ -129,11 +184,130 @@ module Phronomy
129
184
 
130
185
  # Explicit history removal releases references before Agent purge is allowed.
131
186
  def forget_history!
187
+ assert_execution_thread!(:forget_history!)
188
+ main_agent.send(:__assert_live_agent!)
132
189
  @persistence.forget_handoff(main_agent.agent_id)
133
190
  end
134
191
 
135
192
  private
136
193
 
194
+ def assert_execution_thread!(operation)
195
+ if Phronomy::WaitPolicy.blocking_forbidden?
196
+ raise Phronomy::EventLoopReentrancyError, "HandoffRunner##{operation} cannot block EventLoop"
197
+ end
198
+ raise Phronomy::RuntimeShutdownError, "HandoffRunner belongs to a previous Runtime" unless @environment.current?
199
+ end
200
+
201
+ def agent_for(agent_id)
202
+ @agents.fetch(agent_id) { raise Phronomy::ExecutionRehydrationRequiredError, "Handoff graph lacks Agent #{agent_id}" }
203
+ end
204
+
205
+ # Cancellation and terminal-history progress may run beside an admitted
206
+ # invocation. The routing transaction serializes this idempotent effect.
207
+ def finalize_terminal(target, execution_id)
208
+ HandoffTerminalFinalization.new(persistence: @persistence,
209
+ main_agent_id: main_agent.agent_id, agents: @agents).call(execution_id: execution_id, target: target)
210
+ end
211
+
212
+ def handoff_owner
213
+ {"kind" => "handoff", "main_agent_id" => main_agent.agent_id}.freeze
214
+ end
215
+
216
+ def execution_config(active, state, config)
217
+ context = state.active_handoff_context_ref && Phronomy::Agent::TransferContext.from_h(@persistence.contents.fetch_json(state.active_handoff_context_ref))
218
+ config.merge(phronomy_control_bindings: @bindings.fetch(active.agent_id, []), phronomy_transfer_context: context,
219
+ phronomy_execution_participant: HandoffParticipant.new(persistence: @persistence, main_agent_id: main_agent.agent_id, expected_revision: state.handoff_revision),
220
+ phronomy_reservation: handoff_owner, phronomy_admission: ReservedChildAdmission.new(persistence: @persistence, owner: handoff_owner))
221
+ end
222
+
223
+ def start_target(active, state, wiring)
224
+ saved = @persistence.agent_store.observe_execution(agent_id: active.agent_id,
225
+ execution_id: state.pending_target_execution_id)
226
+ # A saved failure needs parent cleanup, not current business wiring.
227
+ return saved.to_result if %i[failed cancelled blocked].include?(saved.status)
228
+
229
+ source = @persistence.agent_store.execution_identity(state.pending_source_execution_id)
230
+ require_target_definition!(active, source.agent_id, state)
231
+ wiring[:cancellation_token].cancel! if Array(state.metadata["cancelled_execution_ids"]).include?(state.pending_target_execution_id)
232
+ reservation = Phronomy::Agent::ReservedExecution.new(agent_id: active.agent_id, execution_id: state.pending_target_execution_id, correlation: handoff_owner)
233
+ active.start_reserved_async(reservation: reservation,
234
+ input: wiring.fetch(:phronomy_transfer_context).responsibility, config: wiring).wait_result
235
+ end
236
+
237
+ def require_target_definition!(active, source_agent_id, state)
238
+ unless @handoffs.any? { |edge| edge.source_agent.agent_id == source_agent_id && edge.target_agent.agent_id == active.agent_id }
239
+ raise Phronomy::ExecutionRehydrationRequiredError, "Handoff graph lacks committed Source/Target edge"
240
+ end
241
+ unless active.class.agent_definition == state.metadata.fetch("target_definition").transform_keys(&:to_sym)
242
+ raise Phronomy::ConfigurationError, "Handoff Target definition mismatch"
243
+ end
244
+ end
245
+
246
+ # Routing is locked before Agent guards, as in cancellation and admission.
247
+ # These reads classify an exact chain; dispatch still requires the existing
248
+ # authority stability premise until the Agent accepts its continuation.
249
+ def resumable_turn(execution_id)
250
+ @persistence.transaction do |records, scope|
251
+ state = records.handoff_states.load_locked(main_agent.agent_id)
252
+ leaf = @persistence.handoff_leaf(execution_id, main_agent_id: main_agent.agent_id, scope: scope)
253
+ next [state, leaf] if leaf.terminal?
254
+ source = @persistence.agent_store.execution_identity(state.pending_source_execution_id, scope: scope) unless state.phase == "stable"
255
+ @persistence.agent_store.guard_agents(scope, agent_ids: [main_agent.agent_id, leaf.agent_id, source&.agent_id].compact)
256
+ require_current_turn!(state, leaf, scope)
257
+ require_pending_target!(state, leaf, source, scope) unless state.phase == "stable"
258
+ [state, leaf]
259
+ end
260
+ end
261
+
262
+ def require_current_turn!(state, leaf, scope)
263
+ if leaf.cancellation_requested || Array(state.metadata["cancelled_execution_ids"]).include?(leaf.execution_id)
264
+ raise Phronomy::CancellationError, "Handoff turn was cancelled"
265
+ end
266
+ if state.active_agent_id != leaf.agent_id || (leaf.absent? && state.phase == "stable")
267
+ raise Phronomy::Persistence::StateConflictError, "Handoff routing no longer owns this exact turn"
268
+ end
269
+ require_retention!(main_agent.agent_id, scope)
270
+ require_retention!(leaf.agent_id, scope)
271
+ return if leaf.absent?
272
+ unless leaf.reservation&.correlation == handoff_owner
273
+ raise Phronomy::Persistence::StateConflictError, "Handoff execution reservation does not match"
274
+ end
275
+ active = @persistence.agent_store.active_executions(agent_id: leaf.agent_id, scope: scope)
276
+ unless active.one? && active.first.execution_id == leaf.execution_id
277
+ raise Phronomy::Persistence::StateConflictError, "Handoff active execution does not match the requested turn"
278
+ end
279
+ end
280
+
281
+ def require_pending_target!(state, leaf, source, scope)
282
+ unless source && state.pending_target_execution_id == leaf.execution_id && source.correlation == handoff_owner
283
+ raise Phronomy::Persistence::StateConflictError, "Handoff pending Source/Target identity mismatch"
284
+ end
285
+ observed = @persistence.agent_store.observe_execution(agent_id: source.agent_id, execution_id: source.execution_id, scope: scope)
286
+ expected = {"target_agent_id" => leaf.agent_id, "target_execution_id" => leaf.execution_id,
287
+ "context_ref" => state.active_handoff_context_ref, "owner_key" => "handoff:#{main_agent.agent_id}"}
288
+ unless observed.status == :handed_off && observed.transfer_receipt == expected && state.metadata["source_agent_id"] == source.agent_id
289
+ raise Phronomy::Persistence::StateConflictError, "Handoff transfer receipt no longer matches pending routing"
290
+ end
291
+ require_target_definition!(agent_for(leaf.agent_id), source.agent_id, state)
292
+ require_retention!(source.agent_id, scope, execution_id: source.execution_id)
293
+ require_retention!(leaf.agent_id, scope, execution_id: leaf.execution_id)
294
+ end
295
+
296
+ def require_retention!(agent_id, scope, execution_id: nil)
297
+ references = @persistence.agent_store.retained_references(agent_id: agent_id, scope: scope)
298
+ unless references.any? { |reference| reference.owner_key == "handoff:#{main_agent.agent_id}" && (!execution_id || reference.execution_id == execution_id) }
299
+ raise Phronomy::Persistence::StateConflictError, "Handoff no longer retains this execution"
300
+ end
301
+ end
302
+
303
+ def require_dispatch_recovery_resolved!(active, execution_id)
304
+ recovery = active.pending_dispatch_recovery(execution_id: execution_id)
305
+ return unless recovery
306
+ raise Phronomy::ExecutionRehydrationRequiredError,
307
+ "Agent #{active.agent_id.inspect} execution #{execution_id.inspect} retains dispatch recovery #{recovery.recovery_id.inspect}; " \
308
+ "use pending_dispatch_recovery and explicit Agent reconciliation before Handoff resume"
309
+ end
310
+
137
311
  def load_state
138
312
  state = @persistence.handoff_states.load(main_agent.agent_id)
139
313
  return state if state