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
@@ -127,6 +127,46 @@ An exhausted shutdown budget leaves cleanup incomplete and retains the default
127
127
  Runtime. New mutations remain rejected during draining; immutable local reads
128
128
  remain available under their existing read-only admission rule.
129
129
 
130
+ If a caller leaves a create or purge operation while the commit outcome is
131
+ unknown, the original registry keeps the identity in recovery-required state.
132
+ This includes exceptions and nonlocal exits. If the original outer Store
133
+ transaction confirmed its commit before its reply was lost, the original create
134
+ or purge can finish using that confirmation. Create publishes its original
135
+ Agent and the journal returned by that transaction. An interrupted constructor
136
+ that cannot finish leaves the confirmed root available for ordinary load. A
137
+ confirmed purge invalidates the old Agent even if its caller left.
138
+ Only the original outer Store transaction can supply this confirmation.
139
+ A provisional savepoint result cannot settle a lost reply. A load interrupted during its
140
+ initial reads releases the reservation and may be retried. Once a recovery
141
+ installation may have reached the dispatcher, an interrupted load keeps the
142
+ identity reserved. An explicit dispatch refusal releases it. Quarantine is a
143
+ local fact about ownership and cannot establish whether the database committed. An original receiver that
144
+ rejects admission or rolls back the exact installation before dispatching a
145
+ continuation acknowledges its rejection. A waiting load raises the original
146
+ error and releases that construction for another explicit load. A failed or
147
+ missing rollback acknowledgement keeps the original identity reserved.
148
+
149
+ Stores that register the optional Agent identity receipt resource can also
150
+ recover when the backend itself loses the commit reply. Create and purge save
151
+ the latest operation ID in the same transaction as the root change. A key
152
+ guard orders a fresh read after earlier changes even when the root and receipt
153
+ are both absent. A matching receipt and root establish commit. A matching
154
+ captured pre-state establishes rollback. A failed read keeps the reservation.
155
+ When a different operation has superseded the original receipt, explicit
156
+ reconciliation can report `:superseded` and retire the old reservation;
157
+ this result does not assign a commit outcome to the superseded operation.
158
+ After a failed first read, the same Agent class can call
159
+ `reconcile_identity(agent_id, persistence:)` on the original Store and running
160
+ Runtime. A confirmed abandoned create can then use ordinary `load`.
161
+
162
+ The resource holds one control record per Agent ID, including purged IDs.
163
+ It holds an operation ID and kind, with no transcript, input or output.
164
+ Enable the resource only after all writers for the Store can update it.
165
+ The built-in memory Store registers it by default. Existing Storage drivers
166
+ can keep using the required catalog until they support the optional resource
167
+ and its key guard. Process loss and stopped Runtime management use their own
168
+ recovery contracts.
169
+
130
170
  Live Agent ownership and top-level Execution admission are separate lifetimes.
131
171
  For one live Agent, `Agent::ExecutionRegistry` admits at most one nonterminal
132
172
  top-level Execution on EventLoop.
@@ -179,6 +219,31 @@ Completion callbacks are lightweight bridges that enqueue the result back to the
179
219
  EventLoop. If EventLoop no longer accepts the result, the callback does not fall
180
220
  back to direct live mutation.
181
221
 
222
+ Retained native parent dispatch follows the same split: the native coordinator
223
+ supplies opaque captured persistence effects and current child authority; the
224
+ Agent owns continuation identity and live application. A known committed parent
225
+ barrier does not bypass a fresh child-authority check. Ordered persistence guards
226
+ end before external Provider or Tool work; authoritative settled readback and the
227
+ original-owner admission protocol remain required. See the
228
+ [native parent dispatch contract](architecture/native-parent-dispatch-recovery.md).
229
+
230
+ For example, after losing a parent child-reservation save response, recovery may
231
+ retry the exact captured content, hold and execution records. It does not run the
232
+ participant's commit decision again or start the child while a conflicting child
233
+ execution is active.
234
+
235
+ Retained [native final/wait recovery](architecture/native-parent-outcome-recovery.md)
236
+ uses the same worker/EventLoop ownership split. A confirmed wait releases its
237
+ save-recovery custody without claiming the Agent job finished; a recovered own
238
+ approval wait retains its exact request and cancellation binding. The original
239
+ failed observation stays closed. Existing approval recovery separately checks
240
+ fresh native child authority before applying a captured decision, and admits no
241
+ new decision merely because a wait was saved.
242
+
243
+ For example, recovery can publish the parent's saved publishing approval request
244
+ after its old listener has closed. The caller uses the request from the new
245
+ receipt with existing `approve_async`; the old listener is not replayed.
246
+
182
247
  ## Provider Call result authority
183
248
 
184
249
  Provider Call identity is purpose-specific semantic provenance. EventLoop
@@ -675,6 +740,131 @@ Once shutdown returns incomplete, future deadline delivery is not guaranteed;
675
740
  the application must not treat that result as completed work or a safe handoff.
676
741
  Repeated shutdown retains the original result rather than silently upgrading it.
677
742
 
743
+ An external management thread can call `runtime.reconcile_shutdown` on the
744
+ original Runtime after shutdown returns. For example, an admitted MultiAgent
745
+ call can miss the shutdown deadline and later release its original admission.
746
+ Until that release, `report.participant_states` identifies the pending
747
+ participant by its registration key. A later check can finish the deferred
748
+ finalizers. Every report retains the original result in `original_shutdown`.
749
+
750
+ ```ruby
751
+ original = runtime.shutdown(timeout: 0)
752
+ report = runtime.reconcile_shutdown
753
+ report.original_shutdown.equal?(original) # true, including after late cleanup
754
+ report.cleanup_complete? # observed cleanup of this Runtime
755
+ report.blockers # outstanding conditions
756
+ ```
757
+
758
+ Management verifies physical termination of every original pool before it
759
+ accepts a participant's affirmative `shutdown_cleanup_ready?` observation.
760
+ An opted-in participant must close admission and verify that earlier obligations
761
+ were released or accepted by an identified successor. Its observation must
762
+ acquire its own synchronization, perform no I/O, and remain true after closure.
763
+ An exception is recorded under its registration key in `read_errors`. A later
764
+ observation may try that read again. Missing independent evidence appears as
765
+ `:unsupported`. The ordinary drain predicate can allow retained recovery.
766
+
767
+ Management runs deferred finalizers together under the original shutdown order
768
+ only after every required condition is satisfied. A failed finalizer is
769
+ reported in `participant_error` and retained for further management. Lost
770
+ timer delivery, discarded transport or domain custody, an inconclusive dispatcher
771
+ shutdown, and receivers without a positive stopped-custody observation block
772
+ finalization. Agent and Workflow registries check their remaining local authority
773
+ after their shutdown hooks finish. Retained Agents permit read-only inspection
774
+ after a timeout. Just before an eligible finalization, Agent ownership checks
775
+ its outstanding leases and closes diagnostic admission under the same lock.
776
+ A racing read delays detachment until its lease finishes and management retries.
777
+ During an ordinary successful drain, passive execution observers may still hold
778
+ their completion leases for a durably suspended approval after physical work and
779
+ receiver shutdown have settled. Read leases continue to guard access. Deferred
780
+ finalization after an incomplete shutdown additionally requires every original
781
+ operation lease, including passive observers, to have settled.
782
+ Repeated checks preserve the first failure and avoid repeating finalizers.
783
+ If the finalizer sequence unwinds through an interrupt or another nonlocal
784
+ exit, management retains the unconfirmed release and lets the interrupt or exit
785
+ reach its caller. Loss of the management reply after confirmed finalization
786
+ can be observed again without running the release hooks a second time.
787
+ This operation keeps the original Runtime stopped and the default binding
788
+ intact. A separate terminal management operation can transfer a verified
789
+ Agent or Workflow disposition to a designated in-process recipient.
790
+
791
+ ### Transfer a stopped terminal disposition
792
+
793
+ A host retaining the exact terminal recovery capability can give one management
794
+ recipient responsibility for the confirmed terminal fact. For example, a report
795
+ Workflow may have committed its final snapshot while losing the save reply and
796
+ the first readback. After shutdown, the recipient can read the original Workflow
797
+ repository, accept the exact revision and snapshot, and let the old registry
798
+ retire the corresponding segment. The original execution observation stays
799
+ settled with its earlier diagnostic.
800
+
801
+ ```ruby
802
+ # A serial host management service keeps this table through a lost reply.
803
+ recipients = {}
804
+ recipients[recovery.recovery_id] = recovery.new_stopped_recipient
805
+ receipt = recipients.fetch(recovery.recovery_id).reconcile
806
+ receipt.outcome # :confirmed_post or, for a definitive Workflow save failure, :confirmed_pre
807
+ ```
808
+
809
+ A service that can lose its reply should retain the recipient in its own
810
+ per-operation state **before** calling `reconcile`. On the same recipient a
811
+ second call retrieves the accepted receipt without using the source or backend.
812
+ A separate recipient is refused after acceptance. A read error, busy read,
813
+ active original dispatcher, pool or domain attempt, or a changed owner leaves
814
+ the source responsible. Each call must run on an external management thread.
815
+ The operation performs a read on the original backend and assumes authoritative
816
+ reads ordered after prior transactions. It never writes business records.
817
+
818
+ | Domain | Transferable evidence | Recipient value |
819
+ | --- | --- | --- |
820
+ | Standalone Agent terminal | Complete captured proof of the committed target, with matching execution and no child reservation or participant | Immutable `ExecutionObservation` and execution revision |
821
+ | Native Agent terminal | Complete captured proof of the parent result and current guarded authority for its original child slots | Immutable parent `ExecutionObservation` and execution revision |
822
+ | Workflow terminal | Exact intended snapshot at the expected next revision and original session custody | Immutable snapshot and revision |
823
+ | Workflow terminal save definitively failed | Exact authoritative pre-revision, including absence for initial creation | Original failure and `confirmed_pre` |
824
+ | Agent pre-state with a captured standalone terminal write | Explicit `retry_save` on the same recipient compares the original pre/post evidence and retries only the captured write | A confirmed post-state can transfer |
825
+ | Conflicting or unreadable records, and active continuations | Original retains custody | No transfer |
826
+
827
+ For a stopped standalone Agent, `recipient.retry_save` can commit the exact
828
+ captured terminal write if the original Store still matches the saved pre-state.
829
+ The host calls this explicitly. Reconciliation remains read-only. The retry
830
+ does not issue provider requests, run Tools, recompute the result, or choose
831
+ another Store. An uncertain reply is compared against the same pre/post evidence.
832
+ The same recipient can read its accepted receipt after a lost reply.
833
+
834
+ A host obtains a native recipient with `Agent::OutcomeRecovery#new_stopped_recipient`.
835
+ The stopped read compares the original parent revision, journal, retained
836
+ references and captured content. The native domain also checks the original
837
+ child authorities and their terminal dispositions. An unimported slot without
838
+ a terminal acknowledgement can instead be authoritatively absent under its
839
+ guard. For example, a completed parent and child may outlive a
840
+ lost terminal-save reply. The recipient accepts the parent result and releases
841
+ its exact local execution ownership while the persisted parent and child
842
+ history holds stay in place. A pending wait, rolled-back save, changed child
843
+ authority or unavailable evidence keeps its source. Native transfer is
844
+ read-only. A transfer clears only its own blocker from shutdown management.
845
+ The host can replace the default Runtime after management confirms all original
846
+ owners and the other shutdown participants are ready.
847
+
848
+ Workflow can establish session custody by an acknowledged live retirement. When
849
+ shutdown overtakes the initial save, the dispatcher instead records its exact
850
+ started session, registered receiver and retained terminal operation before
851
+ disposing of its transport waiter. Management consumes only that record after
852
+ the source and recipient verify the durable disposition. A different abandoned
853
+ session or queued delivery continues to block Runtime cleanup. If the original
854
+ retirement acknowledgement was lost after the domain recorded its exact
855
+ retirement, teardown can request a fresh acknowledgement for that same object
856
+ and deliver it to the original transport waiter on the original dispatcher.
857
+ A missing or mismatched domain record keeps the unaccepted retirement.
858
+
859
+ Existing terminal reconciliation can observe `ownership_state == :transferred`.
860
+ Its `application_state` stays `:pending` because the stopped dispatcher did not
861
+ apply the fact to its former live object. The independent recipient retains the
862
+ durable observation. An Agent confirmed pre-state still calls for an execution
863
+ decision, while Workflow already treats a confirmed pre-state as a failed
864
+ terminal save. This procedure needs the original process, capability, and
865
+ persisted evidence. It cannot recreate lost process state, re-run callbacks,
866
+ bind the default Runtime, or transfer approval or dispatch work.
867
+
678
868
  Internal subsystems can register one shutdown participant per Runtime-local key
679
869
  through `Runtime#__register_shutdown_participant`. This is an internal lifecycle
680
870
  contract, not a public extension API or an execution registry. Runtime does not
@@ -686,6 +876,7 @@ Each participant implements two required operations:
686
876
  must be idempotent, short and nonblocking, and must not call back into Runtime.
687
877
  Runtime invokes it under its lifecycle lock when shutdown starts or EventLoop
688
878
  fails, so no participant can be registered after closure begins.
879
+ - Optional `close_stopped_admission(deferred:)` atomically rechecks outstanding leases and seals diagnostic admission immediately before an eligible finalization. It returns true after closure or false when a racing read keeps the gate open. It must be short, idempotent, nonblocking and free of callbacks into Runtime.
689
880
  - `wait_until_idle(deadline)` returns whether admitted calls have finished before
690
881
  the shared absolute monotonic deadline. Runtime closes every participant before
691
882
  waiting, and waits without holding its lifecycle lock. A timeout or failed hook
@@ -699,7 +890,7 @@ short, and perform no I/O; its return value is ignored. A hook exception marks
699
890
  cleanup incomplete, retains the first failure, and does not skip later hooks.
700
891
  Completed releases are not rolled back; repeated shutdown returns its cached
701
892
  result without retrying hooks. A prior closure/wait failure, timeout, or worker
702
- shutdown failure skips finalization entirely.
893
+ shutdown failure skips finalization during the original shutdown.
703
894
 
704
895
  `Runtime#__shutdown_participant(key:)` only retrieves an existing participant,
705
896
  including during/after shutdown. Registration still requires a running Runtime,
@@ -733,7 +924,13 @@ do not by themselves keep Runtime shutdown waiting. Runtime/process loss does no
733
924
  imply durable Agent continuation reconstruction.
734
925
 
735
926
  `Phronomy.reset_runtime!` exists primarily for test isolation and performs a real
736
- Runtime shutdown before resetting configuration.
927
+ Runtime shutdown before resetting configuration. When the first shutdown was
928
+ incomplete, explicitly reconcile that original Runtime before calling reset.
929
+ A successful deferred finalization permits the explicit reset to detach that
930
+ same default. Reset checks the recorded finalization without running participant
931
+ hooks again. Its return value is the original shutdown report, including its
932
+ historical cleanup status. The separate management report records the subsequent
933
+ confirmation. A new default is created by its next user.
737
934
 
738
935
  ## Hosting a standalone Agent through approval
739
936
 
@@ -752,6 +949,10 @@ Worker B loads the Agent with an `on_event:` listener, checks the restored reque
752
949
 
753
950
  ## Hosting an Orchestrator through a child approval
754
951
 
952
+ A Tool generated by `Orchestrator.subagent` requires a parent execution with a
953
+ reserved Tool invocation. Standalone callers can use a dedicated Agent Tool or
954
+ the direct subagent helper. [Migration and working examples](migrations/orchestrator-subagent-dispatch.md)
955
+
755
956
  A hosted Orchestrator can release its local Agent and one direct subagent when
756
957
  the subagent is waiting for Tool approval. The parent execution has one reserved
757
958
  child slot and its current Tool batch contains only the dispatch for that slot.
@@ -832,10 +1033,12 @@ recovery and acknowledgement.
832
1033
 
833
1034
  ## Releasing a completed Orchestrator and child
834
1035
 
835
- A host can release the local owners once the parent has imported its direct
836
- child's outcome and both executions have finished. Phronomy keeps the durable
837
- reservation, execution results and both Agents' transcripts. A later worker
838
- can load the parent by its Agent ID and use that conversation for another turn.
1036
+ A host can release the local owners once the parent has accounted for its direct
1037
+ child's outcome and both executions have finished. Ordinary result import or a
1038
+ separate acknowledgement recorded by the terminal parent establishes that
1039
+ custody disposition. Phronomy keeps the durable reservation, execution results
1040
+ and both Agents' transcripts. A later worker can load the parent by its Agent
1041
+ ID and use that conversation for another turn.
839
1042
 
840
1043
  For example, after answering the last approval, the worker first lets the
841
1044
  parent import the child's result. It then passes both execution IDs to the
@@ -858,14 +1061,35 @@ loading either Agent, use the Agent Store.
858
1061
  A child may be complete while the parent is still waiting to import its result.
859
1062
  In that case release is premature. Keep the host claim, finish the parent and
860
1063
  then release. Active operations, a scoped owner or a conflicting retention can
861
- also prevent release. The method covers one imported, directly registered child
862
- of the specified execution. It does not sweep other child instances that the
863
- application previously left resident.
1064
+ also prevent release. The method covers one directly registered child with an
1065
+ imported result or a matching terminal-parent acknowledgement. It does not sweep
1066
+ other child instances that the application previously left resident.
1067
+
1068
+ Under the existing `on_error: :raise` policy, a failed or cancelled required
1069
+ child can fail its parent before ordinary import. The final parent transaction
1070
+ can instead read and acknowledge that exact saved terminal outcome. This does
1071
+ not mark the child imported, rewrite either failure or release durable holds.
1072
+ The same unload call can then release the pair once both local owners are free;
1073
+ a pending child recovery operation still blocks release. See the
1074
+ [parent acknowledgement contract](architecture/parent-child-terminal-acknowledgement.md).
1075
+
1076
+ This acknowledgement is created during new parent terminal commits. Historical
1077
+ terminal parents with an unimported child and no acknowledgement are not
1078
+ backfilled by `resume` or unload.
864
1079
 
865
1080
  Generic `unload!` and durable deletion continue to honor retention. Use
866
1081
  `forget_subagents` only when the application intends to remove the stored
867
- coordination history. Once a host no longer needs an unloaded Agent, it can
868
- drop its own references to that instance and its operation handles.
1082
+ coordination history. A host that requires business import calls
1083
+ `forget_subagents(agent_id:, execution_id:, require_import: true)`. Every
1084
+ child must have a matching terminal reservation and an imported slot. A
1085
+ terminal acknowledgement alone keeps the history and raises `AgentBusyError`.
1086
+ The default is the existing explicit history removal policy, which the host
1087
+ can select once it no longer needs the coordination records. Both policies
1088
+ retain the extension and its holds while an identified local Agent has unfinished
1089
+ physical work. Retry after that work settles. Coordinated pair unload can precede
1090
+ history removal. During removal the current Runtime reserves absent owners
1091
+ against fresh materialization and rechecks the stored evidence under the guards.
1092
+ The host can then drop its references to the unloaded Agent and its handles.
869
1093
 
870
1094
  ## Delivering an event to a saved Workflow wait
871
1095
 
@@ -13,8 +13,9 @@ module Phronomy
13
13
 
14
14
  # Constructed by Agent execution, never restored from a durable record.
15
15
  # @api private
16
- def initialize(persistence:, root:, input:, config:, preparation_metadata:)
16
+ def initialize(persistence:, root:, input:, config:, preparation_metadata:, recovery_owner: nil)
17
17
  @persistence, @root, @input, @config = persistence, root, input, config
18
+ @recovery_owner = recovery_owner
18
19
  @preparation_metadata = preparation_metadata
19
20
  @agent_id = root.agent_id
20
21
  @execution_id = (config[:phronomy_reserved_execution_id] || SecureRandom.uuid).to_s.freeze
@@ -37,22 +38,23 @@ module Phronomy
37
38
  @scope = scope
38
39
  @persistence.participate(scope) do |records|
39
40
  raise Phronomy::Error, "agent is closed: #{agent_id}" if @root.lifecycle_status == :closed
40
- input_ref = records.contents.put_text(@input)
41
- context_ref = records.contents.put_json(@config.fetch(:durable_context)) if @config.key?(:durable_context)
42
- input_record = JournalRecord.new(agent_id: agent_id, kind: :input_received,
43
- channel: :external, role: :user, content_ref: input_ref,
44
- context_generation: @root.transcript_generation, context_candidate: false)
45
- execution = AgentExecution.start(agent_root: @root, input_record: input_record,
46
- execution_id: execution_id, metadata: {
47
- "reservation" => correlation, "current_input_ref" => input_ref,
48
- "durable_context_ref" => context_ref,
49
- "execution_extension" => @config[:phronomy_execution_participant]&.binding&.to_h
50
- }.merge(@preparation_metadata).merge(@config[:phronomy_output_contract]&.metadata(records.contents) || {}).compact)
51
- input_record = JournalRecord.from_h(input_record.to_h.merge("execution_id" => execution_id))
52
- execution = execution.with(execution_revision: 0, working_records: [input_record])
53
- records.executions.create_active(execution)
54
- next_root = @root.with(agent_revision: @root.agent_revision + 1, lifecycle_status: :active)
55
- records.agents.save(agent_id, expected_revision: @root.agent_revision, root: next_root)
41
+ if @recovery_owner&.capture_supported?
42
+ contents = InitialPersistenceEvidence::Contents.new(records.contents)
43
+ execution, next_root = prepare_acceptance(contents)
44
+ authority = @recovery_owner.capture_authority(self, scope)
45
+ evidence = InitialPersistenceEvidence.capture(stage: :admission,
46
+ persistence: @persistence, scope: scope, root: @root,
47
+ current_execution: nil, execution: execution, next_root: next_root,
48
+ content_writes: contents.writes, authority: authority)
49
+ @recovery_owner.capture(evidence)
50
+ @recovery_owner.save_entered!
51
+ evidence.apply_in(persistence: @persistence, scope: scope)
52
+ else
53
+ execution, next_root = prepare_acceptance(records.contents)
54
+ @recovery_owner&.save_entered!
55
+ records.executions.create_active(execution)
56
+ records.agents.save(agent_id, expected_revision: @root.agent_revision, root: next_root)
57
+ end
56
58
  @result = [execution, next_root].freeze
57
59
  end
58
60
  nil
@@ -70,6 +72,24 @@ module Phronomy
70
72
 
71
73
  private
72
74
 
75
+ def prepare_acceptance(contents)
76
+ input_ref = contents.put_text(@input)
77
+ context_ref = contents.put_json(@config.fetch(:durable_context)) if @config.key?(:durable_context)
78
+ input_record = JournalRecord.new(agent_id: agent_id, kind: :input_received,
79
+ channel: :external, role: :user, content_ref: input_ref,
80
+ context_generation: @root.transcript_generation, context_candidate: false)
81
+ execution = AgentExecution.start(agent_root: @root, input_record: input_record,
82
+ execution_id: execution_id, metadata: {
83
+ "reservation" => correlation, "current_input_ref" => input_ref,
84
+ "durable_context_ref" => context_ref,
85
+ "execution_extension" => @config[:phronomy_execution_participant]&.binding&.to_h
86
+ }.merge(@preparation_metadata).merge(@config[:phronomy_output_contract]&.metadata(contents) || {}).compact)
87
+ input_record = JournalRecord.from_h(input_record.to_h.merge("execution_id" => execution_id))
88
+ execution = execution.with(execution_revision: 0, working_records: [input_record])
89
+ next_root = @root.with(agent_revision: @root.agent_revision + 1, lifecycle_status: :active)
90
+ [execution, next_root]
91
+ end
92
+
73
93
  def check_thread!
74
94
  raise Phronomy::Persistence::TransactionError, "Agent admission belongs to another execution context" unless @thread.equal?(Thread.current)
75
95
  end
@@ -18,13 +18,38 @@ module Phronomy
18
18
  end
19
19
 
20
20
  require_relative "../async_event_api"
21
+ require_relative "../terminal_recovery_api"
22
+ require_relative "../outcome_recovery_api"
23
+ require_relative "../approval_recovery_api"
24
+ require_relative "../dispatch_recovery_api"
25
+ require_relative "../initial_preparation_recovery_api"
21
26
 
22
27
  unless Phronomy::Agent::Base < Phronomy::Agent::AsyncEventApi
23
28
  Phronomy::Agent::Base.prepend(Phronomy::Agent::AsyncEventApi)
24
29
  end
25
30
 
31
+ unless Phronomy::Agent::Base < Phronomy::Agent::TerminalRecoveryApi
32
+ Phronomy::Agent::Base.prepend(Phronomy::Agent::TerminalRecoveryApi)
33
+ end
34
+
35
+ unless Phronomy::Agent::Base < Phronomy::Agent::OutcomeRecoveryApi
36
+ Phronomy::Agent::Base.prepend(Phronomy::Agent::OutcomeRecoveryApi)
37
+ end
38
+
39
+ unless Phronomy::Agent::Base < Phronomy::Agent::ApprovalRecoveryApi
40
+ Phronomy::Agent::Base.prepend(Phronomy::Agent::ApprovalRecoveryApi)
41
+ end
42
+
43
+ unless Phronomy::Agent::Base < Phronomy::Agent::DispatchRecoveryApi
44
+ Phronomy::Agent::Base.prepend(Phronomy::Agent::DispatchRecoveryApi)
45
+ end
46
+
26
47
  # Durable Agent Recovery and Agent-incarnation event binding.
27
48
  require_relative "../recovery/recovery_support"
28
49
  require_relative "../recovery/recovery_coordinator"
29
50
 
30
51
  Phronomy::Agent::Base.prepend(Phronomy::Agent::LifetimeApi)
52
+
53
+ unless Phronomy::Agent::Base < Phronomy::Agent::InitialPreparationRecoveryApi
54
+ Phronomy::Agent::Base.prepend(Phronomy::Agent::InitialPreparationRecoveryApi)
55
+ end
@@ -0,0 +1,30 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Phronomy
4
+ module Agent
5
+ # A process-local capability for one retained approval decision on the exact
6
+ # original Agent incarnation. Its identities are diagnostic, not authority
7
+ # to reconstruct the capability in another Runtime or process.
8
+ # @api public
9
+ class ApprovalRecovery
10
+ # @api public
11
+ attr_reader :agent_id, :execution_id, :approval_request_id, :recovery_id, :approved
12
+
13
+ # @api private
14
+ def initialize(operation)
15
+ @operation = operation
16
+ @agent_id = operation.agent_id.to_s.dup.freeze
17
+ @execution_id = operation.execution_id.to_s.dup.freeze
18
+ @approval_request_id = operation.approval_request_id.to_s.dup.freeze
19
+ @recovery_id = operation.recovery_id.to_s.dup.freeze
20
+ @approved = operation.approved
21
+ freeze
22
+ end
23
+ private_class_method :new
24
+
25
+ private
26
+
27
+ attr_reader :operation
28
+ end
29
+ end
30
+ end
@@ -0,0 +1,61 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Phronomy
4
+ module Agent
5
+ # Recovery observes responsibility already retained by this Agent, including
6
+ # during Runtime drain. It does not enter ordinary execution admission or
7
+ # create a replacement owner, Runtime or persistence authority.
8
+ # @api private
9
+ module ApprovalRecoveryApi
10
+ # Finds uncertain approval work retained by this exact Agent incarnation.
11
+ # This local lookup performs no persistence I/O and creates no Runtime.
12
+ # Resolved work leaves the index; a held capability keeps its final receipt.
13
+ # @param execution_id [String] nonempty accepted execution identity
14
+ # @return [ApprovalRecovery, nil]
15
+ # @api public
16
+ def pending_approval_recovery(execution_id:)
17
+ unless execution_id.is_a?(String) && !execution_id.empty?
18
+ raise ArgumentError, "execution_id must be a nonempty String"
19
+ end
20
+ @_phronomy_runtime_owner&.existing_registry&.pending_agent_approval_recovery(execution_id, agent: self)
21
+ end
22
+
23
+ # Reads approval persistence and applies the confirmed state on its original
24
+ # owner. A confirmed pre-state restores the same approval wait; a confirmed
25
+ # post-state can start the first execution of the authorized continuation.
26
+ # This does not retry approval writes. Cancelling the returned observation
27
+ # does not cancel retained work or its continuation.
28
+ # @param recovery [ApprovalRecovery] reference from this Agent
29
+ # @return [TaskResult<ApprovalRecoveryResult>] a fresh observation
30
+ # @api public
31
+ def reconcile_approval_async(recovery:)
32
+ _approval_recovery_operation(recovery).observe
33
+ end
34
+
35
+ # Waits for reconciliation on a host thread. The earlier failed approval
36
+ # observation remains closed, even if recovery restores or resumes the job.
37
+ # @param recovery [ApprovalRecovery] reference from this Agent
38
+ # @return [ApprovalRecoveryResult]
39
+ # @raise [EventLoopReentrancyError] when called on EventLoop
40
+ # @api public
41
+ def reconcile_approval(recovery:)
42
+ _check_event_loop_reentrancy(:reconcile_approval, :reconcile_approval_async)
43
+ reconcile_approval_async(recovery: recovery).wait_result
44
+ end
45
+
46
+ private
47
+
48
+ def _approval_recovery_operation(recovery)
49
+ unless recovery.is_a?(ApprovalRecovery)
50
+ raise ArgumentError, "recovery must be an Agent::ApprovalRecovery"
51
+ end
52
+ operation = recovery.send(:operation)
53
+ unless operation.is_a?(ApprovalRecoveryOperation) &&
54
+ operation.recovery.equal?(recovery) && operation.belongs_to?(self)
55
+ raise ArgumentError, "recovery belongs to another Agent incarnation"
56
+ end
57
+ operation
58
+ end
59
+ end
60
+ end
61
+ end
@@ -0,0 +1,39 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Phronomy
4
+ module Agent
5
+ # The approval observation ended while its original owner retained uncertain
6
+ # work. This does not classify the execution as failed or release the job.
7
+ # A later explicit recovery call returns an independent observation.
8
+ # @api public
9
+ class ApprovalRecoveryError < Phronomy::Error
10
+ # @api public
11
+ attr_reader :recovery, :agent_id, :execution_id, :approval_request_id,
12
+ :recovery_id, :approved, :original_error
13
+
14
+ # Retains the initial operation error separately from the immediate cause
15
+ # of this observation; neither is reconstructed from saved diagnostics.
16
+ # @api private
17
+ def initialize(recovery:, error:, original_error: error)
18
+ @recovery = recovery
19
+ @agent_id = recovery.agent_id.to_s.dup.freeze
20
+ @execution_id = recovery.execution_id.to_s.dup.freeze
21
+ @approval_request_id = recovery.approval_request_id.to_s.dup.freeze
22
+ @recovery_id = recovery.recovery_id.to_s.dup.freeze
23
+ @approved = recovery.approved
24
+ @operation_error = error
25
+ @original_error = original_error
26
+ super("Agent #{@agent_id.inspect} execution #{@execution_id.inspect} approval " \
27
+ "#{@approval_request_id.inspect} recovery #{@recovery_id.inspect} requires an explicit " \
28
+ "recovery observation", code: "agent.approval_recovery")
29
+ end
30
+
31
+ # Preserve the immediate operation error across TaskResult delivery.
32
+ # @return [Exception, nil]
33
+ # @api public
34
+ def cause
35
+ @operation_error || super
36
+ end
37
+ end
38
+ end
39
+ end
@@ -0,0 +1,94 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Phronomy
4
+ module Agent
5
+ # One immutable observation of an approval decision and its continuation.
6
+ # Restoring a wait or resuming approved work does not release the Agent job.
7
+ # error describes recovery; execution_task separately observes resumed work.
8
+ # @api public
9
+ class ApprovalRecoveryResult
10
+ OUTCOMES = %i[confirmed_pre confirmed_post unresolved unavailable].freeze
11
+ APPLICATION_STATES = %i[pending applied].freeze
12
+ CONTINUATION_STATES = %i[pending restored resumed].freeze
13
+ private_constant :OUTCOMES, :APPLICATION_STATES, :CONTINUATION_STATES
14
+
15
+ # revision identifies the confirmed execution record: the original wait
16
+ # revision for pre-state, or the saved approval revision for post-state.
17
+ # execution_task is a fresh observation, never the owner's canonical task.
18
+ # hosted_invocation has its own observation and exact next-wait detach
19
+ # authority. It is nil once that hosted authority has physically finished.
20
+ # @api public
21
+ attr_reader :recovery, :agent_id, :execution_id, :approval_request_id, :recovery_id,
22
+ :approved, :outcome, :application_state, :continuation_state, :revision,
23
+ :execution_task, :hosted_invocation, :error
24
+
25
+ # @api private
26
+ def initialize(recovery:, outcome:, application_state:, continuation_state:,
27
+ physical_complete:, revision: nil, execution_task: nil, hosted_invocation: nil, error: nil)
28
+ unless OUTCOMES.include?(outcome) && APPLICATION_STATES.include?(application_state) &&
29
+ CONTINUATION_STATES.include?(continuation_state)
30
+ raise ArgumentError, "unsupported Agent approval recovery state"
31
+ end
32
+ unless physical_complete.equal?(true) || physical_complete.equal?(false)
33
+ raise ArgumentError, "approval physical completion must be a boolean"
34
+ end
35
+ if %i[confirmed_pre confirmed_post].include?(outcome)
36
+ unless revision.is_a?(Integer) && revision >= 0
37
+ raise ArgumentError, "confirmed approval persistence requires its nonnegative execution revision"
38
+ end
39
+ elsif !revision.nil? || application_state != :pending || continuation_state != :pending
40
+ raise ArgumentError, "unclassified approval work must remain pending without a revision"
41
+ end
42
+ if continuation_state != :pending && (application_state != :applied || !physical_complete)
43
+ raise ArgumentError, "approval continuation requires application and physical completion"
44
+ end
45
+ if continuation_state == :restored && outcome != :confirmed_pre
46
+ raise ArgumentError, "only confirmed approval pre-state can restore the wait"
47
+ end
48
+ if continuation_state == :resumed
49
+ unless outcome == :confirmed_post && execution_task.is_a?(Phronomy::TaskResult)
50
+ raise ArgumentError, "resumed approval requires confirmed post-state and an execution observation"
51
+ end
52
+ elsif !execution_task.nil?
53
+ raise ArgumentError, "only resumed approval work has an execution observation"
54
+ end
55
+ if !hosted_invocation.nil? &&
56
+ (continuation_state != :resumed || !hosted_invocation.is_a?(HostedInvocation))
57
+ raise ArgumentError, "only resumed hosted approval work has a hosted invocation"
58
+ end
59
+
60
+ @recovery = recovery
61
+ @agent_id = recovery.agent_id.to_s.dup.freeze
62
+ @execution_id = recovery.execution_id.to_s.dup.freeze
63
+ @approval_request_id = recovery.approval_request_id.to_s.dup.freeze
64
+ @recovery_id = recovery.recovery_id.to_s.dup.freeze
65
+ @approved = recovery.approved
66
+ @outcome = outcome
67
+ @application_state = application_state
68
+ @continuation_state = continuation_state
69
+ @physical_complete = physical_complete
70
+ @revision = revision
71
+ @execution_task = execution_task
72
+ @hosted_invocation = hosted_invocation
73
+ @error = error
74
+ freeze
75
+ end
76
+
77
+ # True only when the approval save and recovery read workers have stopped.
78
+ # The resumed Tool, provider or overall Agent execution can still be active.
79
+ # @return [Boolean]
80
+ # @api public
81
+ def physical_complete?
82
+ @physical_complete
83
+ end
84
+
85
+ # True when the owner applied the proof and restored the same approval wait
86
+ # or resumed its continuation. The execution itself need not be terminal.
87
+ # @return [Boolean]
88
+ # @api public
89
+ def resolved?
90
+ @physical_complete && @application_state == :applied && %i[restored resumed].include?(@continuation_state)
91
+ end
92
+ end
93
+ end
94
+ end