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
@@ -33,6 +33,22 @@ module Phronomy
33
33
  @channel.bound_to?(owner)
34
34
  end
35
35
 
36
+ def stopped_workers_quiescent?
37
+ @channel.respond_to?(:stopped_workers_quiescent?) && @channel.stopped_workers_quiescent?
38
+ end
39
+
40
+ # Called with the channel lock held after dispatcher termination.
41
+ def stopped_cleanup_ready_locked? = false
42
+
43
+ # A domain may identify the exact pending terminal operation of a still
44
+ # registered, started session during teardown under the channel lock.
45
+ def stopped_terminal_owner_locked(_session_id) = nil
46
+
47
+ # Teardown may request a fresh acknowledgement for a retirement whose
48
+ # original reply was lost. Only a receiver retaining the identical object
49
+ # can acknowledge it, before the original dispatcher settles its waiter.
50
+ def acknowledge_retained_retirement(_retirement) = nil
51
+
36
52
  def idle?
37
53
  raise NotImplementedError
38
54
  end
@@ -48,8 +64,19 @@ module Phronomy
48
64
  def session_retired(fsm_session_id, reason:)
49
65
  end
50
66
 
67
+ # Opt-in completion custody. A receiver must retain its domain obligation
68
+ # before returning retirement.acceptance. nil, booleans, and acceptance of
69
+ # another retirement are refusals, not successful adoption.
70
+ def adopt_retirement(retirement)
71
+ ExecutionRetirement::UNSUPPORTED
72
+ end
73
+
51
74
  private
52
75
 
76
+ def transfer_stopped_session(session_id, operation, &block)
77
+ @channel.transfer_stopped_session(self, session_id, operation, &block)
78
+ end
79
+
53
80
  def synchronize(&block)
54
81
  @channel.synchronize(&block)
55
82
  end
@@ -0,0 +1,30 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Phronomy
4
+ # Neutral completion-custody message. Accepting this exact message means the
5
+ # receiver retained responsibility before its transport waiter is detached.
6
+ # It does not establish a domain outcome or authorize domain-owner release.
7
+ # @api private
8
+ class ExecutionRetirement
9
+ UNSUPPORTED = Object.new.freeze
10
+
11
+ Acceptance = Data.define(:retirement)
12
+
13
+ attr_reader :fsm_session_id, :reason, :error
14
+
15
+ def initialize(fsm_session_id:, reason:, error: nil)
16
+ @fsm_session_id = fsm_session_id.to_s.dup.freeze
17
+ @reason = reason
18
+ @error = error
19
+ freeze
20
+ end
21
+
22
+ def acceptance
23
+ Acceptance.new(retirement: self)
24
+ end
25
+
26
+ def accepted_by?(value)
27
+ value.is_a?(Acceptance) && value.retirement.equal?(self)
28
+ end
29
+ end
30
+ end
@@ -45,9 +45,9 @@ module Phronomy
45
45
  end
46
46
  end
47
47
 
48
- def bind(result)
48
+ def bind(result, track_completion: true)
49
49
  result.__bind_execution(@scope)
50
- track(result)
50
+ track(result) if track_completion
51
51
  end
52
52
 
53
53
  def track(result)
@@ -0,0 +1,179 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Phronomy
4
+ # Manages an original attempt, one reserved recovery lane and their observers.
5
+ # The domain owner authorizes work, interprets evidence and grants release.
6
+ # Methods ending in _locked participate in that owner's existing mutex;
7
+ # submission, task methods and notifications always run outside the mutex.
8
+ # @api private
9
+ class RetainedAttempts
10
+ def initialize(mutex:, on_worker_recorded: nil)
11
+ @mutex = mutex
12
+ @on_worker_recorded = on_worker_recorded
13
+ @initial = new_slot(nil, nil)
14
+ @active = nil
15
+ @observers = []
16
+ end
17
+
18
+ # Views contain no mutable slot, completion record or observer collection.
19
+ # Result and error payloads retain their domain's ownership; do not freeze them.
20
+ def snapshot_locked(id)
21
+ slot = slot_locked(id)
22
+ return unless slot
23
+ slot.slice(:id, :kind, :started, :rejection_confirmed, :admission_unknown)
24
+ .merge(slot[:completion].snapshot_locked).freeze
25
+ end
26
+
27
+ def active_snapshot_locked
28
+ snapshot_locked(@active[:id]) if @active
29
+ end
30
+
31
+ def quiescent_locked?
32
+ @initial[:completion].snapshot_locked[:physical] &&
33
+ (!@active || @active[:completion].snapshot_locked[:physical])
34
+ end
35
+
36
+ # Reservation does not submit work or authorize a domain retry.
37
+ def reserve_locked(id, observer:, kind: nil)
38
+ raise Phronomy::Error, "A retained recovery attempt already owns the lane" if @active
39
+ raise ArgumentError, "A recovery attempt requires an identity" unless id
40
+ @active = new_slot(id, kind)
41
+ @active[:observers] << observer
42
+ id
43
+ end
44
+
45
+ def join_locked(id, observer:)
46
+ slot = slot_locked(id)
47
+ return false unless slot
48
+ slot[:observers] << observer
49
+ true
50
+ end
51
+
52
+ def register(observer)
53
+ @mutex.synchronize { @observers << observer }
54
+ observer.on_complete do |_value, _error|
55
+ @mutex.synchronize do
56
+ @observers.delete(observer)
57
+ @active&.fetch(:observers)&.delete(observer)
58
+ end
59
+ end
60
+ observer
61
+ end
62
+
63
+ def observers
64
+ @mutex.synchronize { @observers.dup.freeze }
65
+ end
66
+
67
+ def take_observers_locked(id)
68
+ slot = slot_locked(id)
69
+ slot ? slot[:observers].shift(slot[:observers].length) : []
70
+ end
71
+
72
+ # The owner decides when to detach the lane. Retirement never cancels work.
73
+ def retire_locked(id)
74
+ return [] unless id && @active && @active[:id].equal?(id)
75
+ observers = @active[:observers]
76
+ @active = nil
77
+ observers
78
+ end
79
+
80
+ def retire(id)
81
+ @mutex.synchronize { retire_locked(id) }
82
+ end
83
+
84
+ def worker_started_locked(id)
85
+ slot = slot_locked(id)
86
+ slot[:started] = true if slot
87
+ end
88
+
89
+ def submission_rejected_locked(id)
90
+ slot = slot_locked(id)
91
+ slot[:rejection_confirmed] = true if slot
92
+ end
93
+
94
+ def task_returned_locked(id, task)
95
+ slot = slot_locked(id)
96
+ slot[:completion].attach_locked(task) if slot
97
+ end
98
+
99
+ # Only positive admission evidence permits the caller to declare refusal.
100
+ def submission_failed_locked(id, error, refused:)
101
+ slot = slot_locked(id)
102
+ return unless slot
103
+ slot[:admission_unknown] = !refused
104
+ slot[:completion].submission_failed_locked(error, physical: refused)
105
+ end
106
+
107
+ def record_worker_locked(id, result, error)
108
+ slot = slot_locked(id)
109
+ return false unless slot
110
+ slot[:completion].record_worker_locked(result, error)
111
+ # Optional diagnostic bookkeeping shares the fact's atomic update. The
112
+ # hook must perform no I/O, invoke no tasks and make no domain transition.
113
+ @on_worker_recorded&.call(id, result, error)
114
+ true
115
+ end
116
+
117
+ def release_references_locked(id)
118
+ slot_locked(id)&.fetch(:completion)&.release_references_locked
119
+ end
120
+
121
+ def release_task_locked(id)
122
+ slot_locked(id)&.fetch(:completion)&.release_task_locked
123
+ end
124
+
125
+ def submit(id, submitter:, missing_handle_message:)
126
+ slot = @mutex.synchronize { slot_locked(id) }
127
+ refusal = lambda do |_error|
128
+ @mutex.synchronize { submission_rejected_locked(id) if slot_locked(id).equal?(slot) }
129
+ end
130
+ task = Phronomy::Execution.submit_with_rejection_evidence(submitter,
131
+ on_full: :raise, on_rejected: refusal) do
132
+ @mutex.synchronize { worker_started_locked(id) }
133
+ result = yield
134
+ @mutex.synchronize { record_worker_locked(id, result, nil) }
135
+ result
136
+ rescue Exception => error # rubocop:disable Lint/RescueException
137
+ @mutex.synchronize { record_worker_locked(id, nil, error) }
138
+ raise
139
+ end
140
+ raise Phronomy::Error, missing_handle_message unless task
141
+ @mutex.synchronize { task_returned_locked(id, task) }
142
+ task
143
+ rescue => error
144
+ @mutex.synchronize do
145
+ if slot && slot_locked(id).equal?(slot)
146
+ refused = slot[:rejection_confirmed] && !slot[:started] && !slot[:completion].task
147
+ submission_failed_locked(id, error, refused: refused)
148
+ end
149
+ end
150
+ raise
151
+ end
152
+
153
+ def watch(id, &on_event)
154
+ completion, task = @mutex.synchronize { completion_and_task_locked(id) }
155
+ completion&.watch(task, &on_event)
156
+ end
157
+
158
+ def refresh(id)
159
+ completion, task = @mutex.synchronize { completion_and_task_locked(id) }
160
+ completion ? completion.refresh(task) : false
161
+ end
162
+
163
+ private
164
+
165
+ def slot_locked(id)
166
+ id.nil? ? @initial : (@active if @active && @active[:id].equal?(id))
167
+ end
168
+
169
+ def completion_and_task_locked(id)
170
+ completion = slot_locked(id)&.fetch(:completion)
171
+ [completion, completion&.task]
172
+ end
173
+
174
+ def new_slot(id, kind)
175
+ {id: id, kind: kind, completion: AttemptCompletion.new(mutex: @mutex),
176
+ started: false, observers: [], rejection_confirmed: false, admission_unknown: false}
177
+ end
178
+ end
179
+ end
@@ -0,0 +1,99 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Phronomy
4
+ # The designated in-process recipient of one independently verified terminal
5
+ # disposition. Keep this object across unsuccessful or interrupted calls.
6
+ # @api public
7
+ class StoppedTerminalCustody
8
+ # A detached terminal observation; value is the Agent execution observation
9
+ # or the Workflow snapshot. A confirmed Workflow save failure has no value.
10
+ # @api public
11
+ Receipt = Data.define(:recovery_id, :outcome, :revision, :value, :error)
12
+
13
+ # Only a domain owner holding its original terminal capability issues a
14
+ # recipient. Execution does not evaluate application-supplied token methods.
15
+ # @api private
16
+ def initialize(source)
17
+ @source = source
18
+ end
19
+ private_class_method :new
20
+
21
+ # Read the original backend and accept the verified disposition. A later
22
+ # call by this same recipient returns its existing receipt, without I/O.
23
+ # @return [Receipt] the disposition accepted by this recipient
24
+ # @api public
25
+ def reconcile
26
+ resolve(retry_save: false)
27
+ end
28
+
29
+ # Retry only a complete standalone Agent terminal write on the original
30
+ # Store after its dispatcher and all workers have stopped. An already
31
+ # accepted receipt is returned to this recipient without another write.
32
+ # @return [Receipt]
33
+ # @api public
34
+ def retry_save
35
+ resolve(retry_save: true)
36
+ end
37
+
38
+ private
39
+
40
+ def resolve(retry_save:)
41
+ if Phronomy::WaitPolicy.blocking_forbidden?
42
+ raise Phronomy::EventLoopReentrancyError, "stopped custody reconciliation requires an external thread"
43
+ end
44
+ source = @source
45
+ source ? source.reconcile_stopped_terminal(self, retry_save: retry_save) : @receipt
46
+ end
47
+
48
+ def initialize_copy(_original)
49
+ raise TypeError, "a stopped terminal custody recipient cannot be copied"
50
+ end
51
+
52
+ # Both source and recipient keep the very same receipt before source release.
53
+ def accept(source, receipt)
54
+ raise ArgumentError, "stopped recipient belongs to another operation" unless @source.equal?(source)
55
+ @receipt, @source = receipt, nil
56
+ end
57
+
58
+ # Serializes management of the original operation. Each
59
+ # domain supplies its persistent facts and exact local release predicates.
60
+ # @api private
61
+ module Source
62
+ def reconcile_stopped_terminal(recipient, retry_save: false)
63
+ reservation = Object.new
64
+ begin
65
+ registry = @mutex.synchronize do
66
+ if @stopped_recipient
67
+ return @stopped_receipt if @stopped_recipient.equal?(recipient)
68
+ raise Phronomy::Error, "a different recipient already accepted this terminal disposition"
69
+ end
70
+ if @stopped_read || !@registry || !@uncertain || !@attempts.quiescent_locked?
71
+ raise Phronomy::RuntimeShutdownError, "terminal custody is busy or has no physical completion proof"
72
+ end
73
+ @stopped_read = reservation
74
+ @registry
75
+ end
76
+ unless registry.stopped_workers_quiescent? && registry.owns_terminal_operation?(self)
77
+ raise Phronomy::RuntimeShutdownError, "original dispatcher and workers must have stopped"
78
+ end
79
+ receipt = read_stopped_terminal(retry_save: retry_save)
80
+ Thread.handle_interrupt(Object => :never) do
81
+ registry.transfer_stopped_terminal(self) do
82
+ @mutex.synchronize do
83
+ unless @attempts.quiescent_locked? && @ownership_state == :retained
84
+ raise Phronomy::RuntimeShutdownError, "original terminal authority changed"
85
+ end
86
+ Phronomy::StoppedTerminalCustody.instance_method(:accept).bind_call(recipient, self, receipt)
87
+ @stopped_recipient, @stopped_receipt = recipient, receipt
88
+ end
89
+ end
90
+ released
91
+ end
92
+ receipt
93
+ ensure
94
+ @mutex.synchronize { @stopped_read = nil if @stopped_read.equal?(reservation) }
95
+ end
96
+ end
97
+ end
98
+ end
99
+ end
@@ -10,16 +10,22 @@ module Phronomy
10
10
  class Response < Message
11
11
  attr_reader :usage, :finish_reason, :refusal
12
12
 
13
+ # Captures usage counts at response construction, including values from
14
+ # TokenUsage subclasses, before later serialization or aggregation.
13
15
  # @api public
14
16
  def initialize(content: nil, tool_calls: [], usage: Phronomy::LLMAdapter::TokenUsage.new, metadata: {}, role: :assistant,
15
17
  finish_reason: :unknown, refusal: nil)
16
18
  raise ArgumentError, "LLM response must be an assistant message" unless role == :assistant || role == "assistant"
17
19
  raise ArgumentError, "LLM usage must be LLMAdapter::TokenUsage" unless usage.is_a?(Phronomy::LLMAdapter::TokenUsage)
18
- @usage = usage
19
20
  unless %w[stop tool_calls length content_filter refusal unknown].include?(finish_reason.to_s)
20
21
  raise ArgumentError, "invalid LLM finish reason"
21
22
  end
22
23
  raise ArgumentError, "refusal must be a String or nil" unless refusal.nil? || refusal.is_a?(String)
24
+ @usage = if usage.instance_of?(TokenUsage)
25
+ usage
26
+ else
27
+ TokenUsage.new(input: usage.input, output: usage.output, cached: usage.cached, cache_creation: usage.cache_creation)
28
+ end
23
29
  @finish_reason = finish_reason.to_sym
24
30
  @refusal = refusal&.dup&.freeze
25
31
  super(role: :assistant, content: content, tool_calls: tool_calls, metadata: metadata)
@@ -43,6 +43,12 @@ module Phronomy
43
43
  @mutex.synchronize { @owners.empty? }
44
44
  end
45
45
 
46
+ # Once entry is closed, the last original owner release is permanent.
47
+ # @api private
48
+ def shutdown_cleanup_ready?
49
+ @mutex.synchronize { @draining && @owners.empty? }
50
+ end
51
+
46
52
  # Close admission atomically with respect to admit!, without waiting for
47
53
  # admitted callers or calling back into Runtime. Repeated closure is safe.
48
54
  def begin_draining
@@ -20,6 +20,43 @@ module Phronomy
20
20
  Phronomy::Agent::ExecutionExtensionState.new(binding_key: BINDING_KEY, binding_version: 1)
21
21
  end
22
22
 
23
+ # Opt in only this binding and its original Agent store. Eligibility runs
24
+ # on the owner thread and must not read persistence or acquire guards.
25
+ private def dispatch_recovery_supported?(execution:, persistence:)
26
+ extension = execution.metadata["execution_extension"]
27
+ persistence.equal?(@persistence.agent_store) &&
28
+ extension&.fetch("binding_key") == BINDING_KEY &&
29
+ extension.fetch("binding_version") == 1
30
+ end
31
+
32
+ # Captured values replace live participant wiring after its single commit.
33
+ # Recovery never calls this coordinator's commit or constructs a child.
34
+ private def capture_dispatch_recovery(values:, persistence:)
35
+ unless persistence.equal?(@persistence.agent_store)
36
+ raise Phronomy::Persistence::TransactionError, "Native dispatch proof belongs to another Agent store"
37
+ end
38
+ NativeDispatchEvidence.capture(values: values, persistence: persistence,
39
+ native_persistence: @persistence, binding_key: BINDING_KEY)
40
+ end
41
+
42
+ private def outcome_recovery_supported?(execution:, persistence:)
43
+ dispatch_recovery_supported?(execution: execution, persistence: persistence)
44
+ end
45
+
46
+ private def capture_outcome_recovery(values:, persistence:)
47
+ NativeOutcomeEvidence.capture(values: values, persistence: persistence,
48
+ native_persistence: @persistence, binding_key: BINDING_KEY)
49
+ end
50
+
51
+ private def approval_recovery_supported?(execution:, persistence:)
52
+ dispatch_recovery_supported?(execution: execution, persistence: persistence)
53
+ end
54
+
55
+ private def capture_approval_recovery(execution:, persistence:)
56
+ NativeApprovalEvidence.capture(execution: execution, persistence: persistence,
57
+ native_persistence: @persistence, binding_key: BINDING_KEY)
58
+ end
59
+
23
60
  def guard_change(change, scope)
24
61
  snapshot = state_for(change.extension)
25
62
  ids = [change.agent_id] + snapshot.fetch("children").filter_map do |child|
@@ -30,53 +67,133 @@ module Phronomy
30
67
 
31
68
  # The referenced content is immutable and is part of Agent's commit proof.
32
69
  def change_evidence(change, scope)
33
- persistence.agent_store.retained_references(agent_id: change.agent_id, scope: scope).map(&:to_h)
70
+ NativePersistencePlan.retention_facts(persistence.agent_store.retained_references(agent_id: change.agent_id, scope: scope).map(&:to_h))
34
71
  end
35
72
 
36
73
  def commit(change)
37
74
  persistence.coordinator.atomic do |scope|
38
75
  guard_change(change, scope)
39
76
  change.prepare_in(scope)
40
- snapshot = state_for(change.extension)
41
- children = snapshot.fetch("children").map(&:dup)
42
- cancelled = snapshot["cancel_requested"] || change.cancel_requested ||
43
- persistence.agent_store.cancellation_requested?(agent_id: change.agent_id, execution_id: change.execution_id, scope: scope)
44
- children.each do |child|
45
- observed = persistence.agent_store.observe_execution(agent_id: child.fetch("agent_id"), execution_id: child.fetch("execution_id"), scope: scope)
46
- # This is import progress, not a replicated child execution state.
47
- child["imported"] = true if observed.terminal? && change.kind == :dispatch && change.operations.empty?
77
+ data, pending = prepare_native_change(change, scope)
78
+ unless data.fetch("children").empty?
79
+ persistence.agent_store.retain(parent_retention(change), scope: scope)
48
80
  end
49
- change.operations.each do |operation|
50
- entry = @definitions.find { |name, _| @agent_class.__subagent_tool_name(name) == operation.name }
51
- next unless entry
52
- next if children.any? { |child| child.fetch("slot") == operation.invocation_id }
53
- name, settings = entry
54
- digest = Digest::SHA256.hexdigest(Phronomy::CanonicalJSON.dump(
55
- ["phronomy-subagent-v1", change.agent_id, change.execution_id, operation.invocation_id]
56
- ))
57
- knowledge = settings.fetch(:inherit_knowledge) ? persistence.agent_store.knowledge_snapshot(agent_id: change.agent_id, scope: scope) : []
58
- children << {"slot" => operation.invocation_id, "name" => name.to_s,
59
- "definition" => settings.fetch(:agent_class).agent_definition.transform_keys(&:to_s),
60
- "agent_id" => "subagent-#{digest}", "execution_id" => "subagent-execution-#{digest}",
61
- "input" => operation.arguments.fetch("input"), "durable_context" => change.durable_context,
62
- "knowledge" => knowledge.map { |item| {"content" => item.content, "metadata" => item.metadata} },
63
- "on_error" => settings.fetch(:on_error).to_s, "imported" => false}
81
+ persistence.participate(scope) do |records|
82
+ ref = records.contents.put_json(data)
83
+ state = Phronomy::Agent::ExecutionExtensionState.new(binding_key: BINDING_KEY, binding_version: 1, state_ref: ref)
84
+ change.commit_in(scope, state: state, pending: pending)
64
85
  end
65
- unless children.empty?
66
- persistence.agent_store.retain(Phronomy::Agent::Retention.new(agent_id: change.agent_id,
67
- execution_id: change.execution_id, owner_key: "subagent:#{change.execution_id}"), scope: scope)
86
+ end
87
+ end
88
+
89
+ # Only native outcome recovery opts into this preparation protocol. The
90
+ # full Agent/native intended save is retained before the first write.
91
+ private def commit_prepared_outcome(change)
92
+ planning = change.__send__(:prepared_outcome_planning, read_facts: method(:read_terminal_facts), select_plan: method(:terminal_outcome_plan))
93
+ persistence.coordinator.atomic do |scope|
94
+ input = planning.materialize_in(scope)
95
+ change.__send__(:apply_prepared_outcome_in, scope, input)
96
+ end
97
+ end
98
+
99
+ private def read_terminal_facts(change, scope, retentions, recovering:)
100
+ facts = read_change_facts(change, scope)
101
+ children = facts.fetch(0).fetch("children")
102
+ if recovering && !children.empty?
103
+ unless retentions.include?(parent_retention(change).to_h)
104
+ raise Phronomy::Persistence::StateConflictError, "Native parent custody changed before outcome preparation"
68
105
  end
69
- unresolved = children.any? do |child|
70
- observed = persistence.agent_store.observe_execution(agent_id: child.fetch("agent_id"), execution_id: child.fetch("execution_id"), scope: scope)
71
- observed.active? || (observed.absent? && !cancelled)
106
+ # A resumed first decision may run the application's first conversion.
107
+ # Check current custody before that boundary, under the same guards
108
+ # and with the same observations used for selection.
109
+ authority = NativeChildAuthority.new(agent_id: change.agent_id, execution_id: change.execution_id,
110
+ children: children, prior_slots: children.map { |child| child.fetch("slot") }, persistence: persistence.agent_store)
111
+ observations = facts.fetch(2)
112
+ authority.assert_current!(persistence: persistence.agent_store, scope: scope, outcome: true) do |id, execution_id|
113
+ observations.fetch([id, execution_id])
72
114
  end
73
- persistence.participate(scope) do |records|
74
- ref = records.contents.put_json(snapshot.merge("children" => children, "cancel_requested" => !!cancelled))
75
- state = Phronomy::Agent::ExecutionExtensionState.new(binding_key: BINDING_KEY, binding_version: 1, state_ref: ref)
76
- change.commit_in(scope, state: state,
77
- pending: change.kind == :terminal && unresolved && (change.cancel_requested || change.recovery_required))
115
+ end
116
+ facts
117
+ end
118
+
119
+ private def terminal_outcome_plan(change, scope, facts, retentions, &select_approval)
120
+ data, pending = prepare_native_change(change, scope, facts, &select_approval)
121
+ bytes = Phronomy::CanonicalJSON.dump(data)
122
+ reference = "sha256:#{Digest::SHA256.hexdigest(bytes)}"
123
+ state = Phronomy::Agent::ExecutionExtensionState.new(binding_key: BINDING_KEY, binding_version: 1, state_ref: reference)
124
+ holds = retentions.dup
125
+ holds |= [parent_retention(change).to_h] unless data.fetch("children").empty?
126
+ [state, pending, data, NativePersistencePlan.retention_facts(holds)]
127
+ end
128
+
129
+ private def parent_retention(change)
130
+ Phronomy::Agent::Retention.new(agent_id: change.agent_id,
131
+ execution_id: change.execution_id, owner_key: "subagent:#{change.execution_id}")
132
+ end
133
+
134
+ private def read_change_facts(change, scope)
135
+ snapshot = state_for(change.extension)
136
+ cancelled = snapshot["cancel_requested"] || change.cancel_requested ||
137
+ persistence.agent_store.cancellation_requested?(agent_id: change.agent_id, execution_id: change.execution_id, scope: scope)
138
+ observations = {}
139
+ snapshot.fetch("children").each { |child| observe_child(child, observations, scope) }
140
+ [snapshot, cancelled, observations]
141
+ end
142
+
143
+ private def observe_child(child, observations, scope)
144
+ identity = child.fetch_values("agent_id", "execution_id")
145
+ observations[identity] ||= persistence.agent_store.observe_execution(
146
+ agent_id: identity.first, execution_id: identity.last, scope: scope
147
+ )
148
+ end
149
+
150
+ private def prepare_native_change(change, scope, facts = nil)
151
+ snapshot, cancelled, observations = facts || read_change_facts(change, scope)
152
+ children = snapshot.fetch("children").map(&:dup)
153
+ children.each do |child|
154
+ observed = observe_child(child, observations, scope)
155
+ # This is import progress, not a replicated child execution state.
156
+ child["imported"] = true if observed.terminal? && change.kind == :dispatch && change.operations.empty?
157
+ end
158
+ change.operations.each do |operation|
159
+ entry = @definitions.find { |name, _| @agent_class.__subagent_tool_name(name) == operation.name }
160
+ next unless entry
161
+ next if children.any? { |child| child.fetch("slot") == operation.invocation_id }
162
+ name, settings = entry
163
+ digest = Digest::SHA256.hexdigest(Phronomy::CanonicalJSON.dump(
164
+ ["phronomy-subagent-v1", change.agent_id, change.execution_id, operation.invocation_id]
165
+ ))
166
+ knowledge = settings.fetch(:inherit_knowledge) ? persistence.agent_store.knowledge_snapshot(agent_id: change.agent_id, scope: scope) : []
167
+ children << {"slot" => operation.invocation_id, "name" => name.to_s,
168
+ "definition" => settings.fetch(:agent_class).agent_definition.transform_keys(&:to_s),
169
+ "agent_id" => "subagent-#{digest}", "execution_id" => "subagent-execution-#{digest}",
170
+ "input" => operation.arguments.fetch("input"), "durable_context" => change.durable_context,
171
+ "knowledge" => knowledge.map { |item| {"content" => item.content, "metadata" => item.metadata} },
172
+ "on_error" => settings.fetch(:on_error).to_s, "imported" => false}
173
+ end
174
+ unresolved = children.any? do |child|
175
+ observed = observe_child(child, observations, scope)
176
+ observed.active? || (observed.absent? && !cancelled)
177
+ end
178
+ pending = change.kind == :terminal && unresolved && (change.cancel_requested || change.recovery_required)
179
+ # A parent already waiting for its children must not prepare an approval.
180
+ if block_given? && !pending
181
+ change = yield change
182
+ pending = unresolved && change.recovery_required
183
+ end
184
+ if change.finishing? && !pending
185
+ children.each do |child|
186
+ next if child.fetch("imported")
187
+
188
+ # A final parent can adopt an exact durable child outcome even
189
+ # when its Tool callback did not reach the ordinary import path.
190
+ # Keep that custody acknowledgement distinct from business import.
191
+ observed = observe_child(child, observations, scope)
192
+ receipt = terminal_acknowledgement(change.agent_id, change.execution_id, child, observed)
193
+ child["terminal_acknowledgement"] = receipt if receipt
78
194
  end
79
195
  end
196
+ [snapshot.merge("children" => children, "cancel_requested" => !!cancelled), pending]
80
197
  end
81
198
 
82
199
  def state_for(extension)
@@ -114,17 +231,20 @@ module Phronomy
114
231
  end
115
232
  end
116
233
 
117
- # A terminal record alone does not show that its result reached the
118
- # parent. Check the native slot, exact reservation and holds together.
234
+ # Local release requires ordinary import or a separately recorded final
235
+ # parent acknowledgement. Neither disposition releases durable history.
119
236
  def completed_child_pair?(parent_id, parent_execution_id, child, live_child:, scope:)
120
237
  store = persistence.agent_store
121
238
  return false unless store.terminal_execution?(agent_id: parent_id, execution_id: parent_execution_id, scope: scope)
122
239
  children = stored_children(parent_id, parent_execution_id, scope)
123
240
  return false unless children&.size == 1
124
241
  slot = children.first
125
- return false unless slot.fetch("imported") == true && slot.fetch("agent_id") == child.agent_id &&
242
+ return false unless slot.fetch("agent_id") == child.agent_id &&
126
243
  slot.fetch("execution_id") == child.execution_id && matching_child_class?(slot, live_child)
127
244
 
245
+ return false unless slot.fetch("imported") == true ||
246
+ terminal_acknowledged?(parent_id, parent_execution_id, slot, scope)
247
+
128
248
  owner = {"kind" => "subagent", "parent_agent_id" => parent_id, "parent_execution_id" => parent_execution_id,
129
249
  "slot" => slot.fetch("slot")}
130
250
  return false unless store.terminal_execution?(agent_id: child.agent_id, execution_id: child.execution_id,
@@ -135,10 +255,26 @@ module Phronomy
135
255
 
136
256
  hosted_retentions?(parent_id, parent_execution_id, scope) do |prior_id|
137
257
  prior = stored_children(parent_id, prior_id, scope)
138
- prior && !prior.empty? && prior.all? { |entry| entry.fetch("imported") == true }
258
+ prior && !prior.empty? && prior.all? do |entry|
259
+ entry.fetch("imported") == true || terminal_acknowledged?(parent_id, prior_id, entry, scope)
260
+ end
139
261
  end
140
262
  end
141
263
 
264
+ private def terminal_acknowledged?(parent_id, parent_execution_id, child, scope)
265
+ saved = child["terminal_acknowledgement"]
266
+ return false unless saved
267
+
268
+ observed = persistence.agent_store.observe_execution(agent_id: child.fetch("agent_id"),
269
+ execution_id: child.fetch("execution_id"), scope: scope)
270
+ expected = terminal_acknowledgement(parent_id, parent_execution_id, child, observed)
271
+ expected && saved == expected
272
+ end
273
+
274
+ private def terminal_acknowledgement(parent_id, parent_execution_id, child, observed)
275
+ NativeChildAuthority.terminal_acknowledgement(parent_id, parent_execution_id, child, observed)
276
+ end
277
+
142
278
  private def stored_children(parent_id, execution_id, scope)
143
279
  extension = persistence.agent_store.execution_extension(agent_id: parent_id, execution_id: execution_id,
144
280
  binding_key: BINDING_KEY, scope: scope)