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
@@ -13,10 +13,13 @@ module Phronomy
13
13
 
14
14
  # Agent execution constructs changes; applications implement participants.
15
15
  # @api private
16
- def initialize(agent:, current:, root:, kind:, updated: nil, terminal: nil, config: {}, &write)
16
+ def initialize(agent:, current:, root:, kind:, updated: nil, terminal: nil, config: {}, prepare_outcome: nil, on_preparation: nil, on_prepared: nil, on_planning: nil, on_partial: nil, approval_selection: nil, prepare_approval: nil, &write)
17
17
  @agent, @store, @current, @root = agent, agent.persistence, current, root
18
18
  @coordinator = @store.coordinator
19
19
  @kind, @updated, @write = kind, updated, write
20
+ @prepare_outcome, @on_preparation, @on_prepared = prepare_outcome, on_preparation, on_prepared
21
+ @on_planning, @on_partial, @approval_selection = on_planning, on_partial, approval_selection
22
+ @prepare_approval = prepare_approval
20
23
  @agent_id, @execution_id = current.agent_id, current.execution_id
21
24
  @extension = current.metadata["execution_extension"] && ExecutionExtensionState.from_h(current.metadata["execution_extension"])
22
25
  @correlation = Phronomy::Values::Immutable.copy(current.metadata["reservation"])
@@ -31,9 +34,11 @@ module Phronomy
31
34
  Store::AuthorizedOperation.new(invocation_id: entry.fetch("tool_invocation_id"), name: entry.fetch("tool_name"),
32
35
  arguments: Phronomy::Values::Immutable.copy(entry.fetch("arguments").compact))
33
36
  end.freeze
34
- ref = current.metadata["durable_context_ref"]
35
- @durable_context = ref && Phronomy::Values::Immutable.copy(@store.contents.fetch_json(ref))
36
37
  @participant = config[:phronomy_execution_participant]
38
+ ref = current.metadata["durable_context_ref"]
39
+ # The public participant receives its durable context. Native terminal
40
+ # planning never allocates a new child, so it consumes no dispatch context.
41
+ @durable_context = Phronomy::Values::Immutable.copy(@store.contents.fetch_json(ref)) if @participant && ref && !@prepare_outcome
37
42
  @thread = Thread.current
38
43
  validate_binding!
39
44
  end
@@ -45,13 +50,21 @@ module Phronomy
45
50
  # @api private
46
51
  def perform
47
52
  raise Phronomy::ConfigurationError, "Execution change is single-use" if @performed
53
+ assert_original_thread!
48
54
  @performed = true
49
- perform_once
55
+ @performing = true
56
+ begin
57
+ perform_once
58
+ ensure
59
+ @performing = false
60
+ end
50
61
  end
51
62
 
52
63
  # @api private
53
64
  def perform_once
54
- if @participant
65
+ if @prepare_outcome
66
+ @participant.__send__(:commit_prepared_outcome, self)
67
+ elsif @participant
55
68
  @participant.commit(self)
56
69
  else
57
70
  coordinator.atomic { |scope|
@@ -64,7 +77,7 @@ module Phronomy
64
77
  end
65
78
  @result
66
79
  rescue => error
67
- raise unless @after && @scope&.outermost?
80
+ raise unless @after && @result && @scope&.outermost?
68
81
  outcome = Phronomy::Persistence::SaveOutcome.compare(before: @before, after: @after, original_error: error) do
69
82
  coordinator.atomic do |scope|
70
83
  @participant&.guard_change(self, scope)
@@ -78,15 +91,39 @@ module Phronomy
78
91
  ensure
79
92
  # A completed synchronous change may remain on a worker's native stack.
80
93
  # Release live execution wiring only after commit/readback has finished.
81
- @agent = @write = @participant = nil
94
+ @agent = @write = @participant = @prepare_outcome = @on_preparation = @on_prepared = @on_planning = @on_partial = @approval_selection = nil
95
+ @prepare_approval = @prepared_approval = nil
82
96
  end
83
97
 
84
98
  private :perform_once
85
99
 
100
+ # Detached values for an opt-in domain persistence proof. The original
101
+ # synchronous change and participant wiring are never replayable.
102
+ # @api private
103
+ def captured_evidence
104
+ return unless @scope&.outermost? && @before && @after && @result
105
+ {before: Phronomy::Values::Immutable.copy(@before),
106
+ after: Phronomy::Values::Immutable.copy(@after), result: @result}.freeze
107
+ end
108
+
109
+ # Agent's complete guarded comparison footprint, shared with explicit
110
+ # persistence-only reconciliation. The caller owns the outer transaction.
111
+ # @api private
112
+ def self.read_agent_evidence(store:, agent_id:, execution_id:, journal_position:, scope:)
113
+ store.participate(scope) do |records|
114
+ root = records.agents.load(agent_id)
115
+ execution = records.executions.load(execution_id)
116
+ journal = records.journals.read(agent_id, after: journal_position,
117
+ limit: [root.journal_position - journal_position, 1].max)
118
+ ref = execution.metadata.dig("execution_extension", "state_ref")
119
+ [root.to_h, execution.to_h, journal.map(&:to_h), ref && records.contents.fetch_json(ref), records.cancellations.requested?(agent_id, execution_id)]
120
+ end
121
+ end
122
+
86
123
  # Capture the complete pre-state after the participant has acquired its
87
124
  # ordered guards, before it changes its own records.
88
125
  def prepare_in(scope)
89
- raise Phronomy::Persistence::TransactionError, "Execution change belongs to another thread" unless @thread.equal?(Thread.current)
126
+ assert_active_context!
90
127
  raise Phronomy::ConfigurationError, "Execution change is single-use" if @scope
91
128
  @store.guard_agents(scope, agent_ids: [agent_id])
92
129
  @before = snapshot(scope)
@@ -95,11 +132,34 @@ module Phronomy
95
132
  nil
96
133
  end
97
134
 
135
+ # Validate one approval display before the participant chooses an outcome.
136
+ # The caller must hold its domain guards and use the original outer scope.
137
+ # @return [Symbol] :not_requested, :ready, :invalid, or :unavailable
138
+ # @api public
139
+ def prepare_approval_in(scope)
140
+ assert_prepared_scope!(scope)
141
+ return :not_requested unless @prepare_approval
142
+ return @prepared_approval.status if @prepared_approval
143
+ unless scope.outermost?
144
+ raise Phronomy::Persistence::TransactionError, "Approval preparation requires the original outer transaction"
145
+ end
146
+ @store.participate(scope) do |records|
147
+ assert_current_execution!(records)
148
+ evidence = Phronomy::Values::Immutable.json(@participant.change_evidence(self, scope))
149
+ unless evidence == @before.last
150
+ raise Phronomy::Persistence::StateConflictError, "Participant evidence changed before approval preparation"
151
+ end
152
+ @prepared_approval = @prepare_approval.call
153
+ end
154
+ @finishing = true if @prepared_approval.status == :invalid
155
+ @recovery_required = true if @prepared_approval.error
156
+ @prepared_approval.status
157
+ end
158
+
98
159
  # Must be called once in the participant's original synchronous context.
99
160
  # No arbitrary execution setter or callback is exposed to the participant.
100
- def commit_in(scope, state: extension, transfer_receipt: nil, pending: false)
101
- raise Phronomy::Persistence::TransactionError, "Execution change belongs to another thread" unless @thread.equal?(Thread.current)
102
- raise Phronomy::ConfigurationError, "Execution change must use its prepared scope exactly once" unless @scope.equal?(scope) && !@used
161
+ def commit_in(scope, state: extension, transfer_receipt: nil, pending: false, fail_unavailable_approval: false)
162
+ assert_prepared_scope!(scope)
103
163
  @used = true
104
164
  if state && (!extension || state.binding_key != extension.binding_key || state.binding_version != extension.binding_version)
105
165
  raise Phronomy::ConfigurationError, "Execution extension identity cannot change"
@@ -107,18 +167,19 @@ module Phronomy
107
167
  raise ArgumentError, "dispatch cannot choose a terminal outcome" if kind == :dispatch && (transfer_receipt || pending)
108
168
  raise ArgumentError, "only a control request can transfer responsibility" if transfer_receipt && !control_request
109
169
  raise ArgumentError, "pending work requires cancellation or recovery" if pending && !(cancel_requested || recovery_required)
170
+ unavailable = @prepared_approval&.status == :unavailable
171
+ if fail_unavailable_approval && (!unavailable || pending)
172
+ raise ArgumentError, "only an unavailable approval can be explicitly completed as a failure"
173
+ end
174
+ raise @prepared_approval.error if unavailable && !pending && !fail_unavailable_approval
110
175
  @store.participate(scope) do |records|
111
- records.assert_agent_watermark!(agent_id: agent_id, agent_revision: @root.agent_revision, journal_position: @root.journal_position)
112
- observed = records.executions.load(execution_id)
113
- unless observed.agent_id == agent_id && observed.execution_revision == @current.execution_revision
114
- raise Phronomy::Persistence::StateConflictError, "Execution changed before participation"
115
- end
176
+ assert_current_execution!(records)
116
177
  if kind == :dispatch
117
178
  updated = attach_state(@updated, state)
118
179
  records.executions.save(execution_id, expected_revision: @current.execution_revision, execution: updated)
119
180
  @result = updated
120
181
  else
121
- @result = @write.call(records, state, transfer_receipt, pending)
182
+ @result = @write.call(records, state, transfer_receipt, pending, @prepared_approval)
122
183
  end
123
184
  end
124
185
  @after = snapshot(scope)
@@ -127,6 +188,7 @@ module Phronomy
127
188
 
128
189
  # Finalized input material; policies are interpreted by the participant.
129
190
  def transfer_context(scope)
191
+ assert_active_context!
130
192
  raise ArgumentError, "there is no control request" unless control_request
131
193
  @store.participate(scope) do |records|
132
194
  manifest = SavedContextReader.manifest_from_ref(@agent, @current.metadata.fetch("manifest_ref"))
@@ -136,6 +198,59 @@ module Phronomy
136
198
 
137
199
  private
138
200
 
201
+ def assert_prepared_scope!(scope)
202
+ assert_active_context!
203
+ unless @scope&.equal?(scope) && !@used
204
+ raise Phronomy::ConfigurationError, "Execution change must use its prepared scope exactly once"
205
+ end
206
+ end
207
+
208
+ def assert_current_execution!(records)
209
+ records.assert_agent_watermark!(agent_id: agent_id, agent_revision: @root.agent_revision, journal_position: @root.journal_position)
210
+ observed = records.executions.load(execution_id)
211
+ unless observed.agent_id == agent_id && observed.execution_revision == @current.execution_revision
212
+ raise Phronomy::Persistence::StateConflictError, "Execution changed before participation"
213
+ end
214
+ end
215
+
216
+ def assert_original_thread!
217
+ raise Phronomy::Persistence::TransactionError, "Execution change belongs to another thread" unless @thread.equal?(Thread.current)
218
+ end
219
+
220
+ def assert_active_context!
221
+ assert_original_thread!
222
+ unless @performing
223
+ raise Phronomy::ConfigurationError, "Execution change is outside its active synchronous call"
224
+ end
225
+ end
226
+
227
+ # Capture the validated native subject before the first guard/read. The
228
+ # recovery lane retains neither this thread-bound change nor its scope.
229
+ def prepared_outcome_planning(read_facts:, select_plan:)
230
+ assert_active_context!
231
+ unless @prepare_outcome && kind == :terminal && !@used
232
+ raise Phronomy::ConfigurationError, "Expected one native terminal preparation"
233
+ end
234
+ @used = true
235
+ subject = OutcomePlanning::Subject.new(agent_id: agent_id, execution_id: execution_id,
236
+ extension: extension, cancel_requested: cancel_requested, recovery_required: recovery_required, finishing: finishing?)
237
+ planning = OutcomePlanning.new(subject, root: @root, current: @current, store: @store,
238
+ participant: @participant, prepare_outcome: @prepare_outcome, on_preparation: @on_preparation, on_partial: @on_partial, read_facts: read_facts, select_plan: select_plan, approval_selection: @approval_selection)
239
+ @on_planning&.call(planning)
240
+ planning
241
+ end
242
+
243
+ def apply_prepared_outcome_in(scope, input)
244
+ assert_active_context!
245
+ @scope = scope
246
+ @before, @after, @result = input.values.fetch_values(:before, :after, :result)
247
+ evidence = @on_prepared.call(input)
248
+ unless evidence
249
+ raise Phronomy::Persistence::StateConflictError, "Prepared Agent outcome has no retained proof"
250
+ end
251
+ evidence.__send__(:apply_prepared_in, persistence: @store, scope: scope)
252
+ end
253
+
139
254
  def validate_binding!
140
255
  return unless extension
141
256
  binding = @participant&.binding
@@ -150,15 +265,12 @@ module Phronomy
150
265
  end
151
266
 
152
267
  def snapshot(scope)
153
- agent_state = @store.participate(scope) do |records|
154
- root = records.agents.load(agent_id)
155
- execution = records.executions.load(execution_id)
156
- journal = records.journals.read(agent_id, after: @root.journal_position,
157
- limit: [root.journal_position - @root.journal_position, 1].max)
158
- ref = execution.metadata.dig("execution_extension", "state_ref")
159
- [root.to_h, execution.to_h, journal.map(&:to_h), ref && records.contents.fetch_json(ref), records.cancellations.requested?(agent_id, execution_id)]
160
- end
161
- [agent_state, @participant&.change_evidence(self, scope)]
268
+ agent_state = self.class.read_agent_evidence(store: @store, agent_id: agent_id,
269
+ execution_id: execution_id, journal_position: @root.journal_position, scope: scope)
270
+ # A participant may reuse its JSON buffer. Each proof must keep the value
271
+ # observed under these guards, independently of all later reads.
272
+ participation = Phronomy::Values::Immutable.json(@participant&.change_evidence(self, scope))
273
+ [Phronomy::Values::Immutable.copy(agent_state), participation].freeze
162
274
  end
163
275
  end
164
276
  end
@@ -19,10 +19,39 @@ module Phronomy
19
19
  end
20
20
  end
21
21
 
22
+ # Coordinated history removal must exclude both new admissions and
23
+ # accepted work, including when all identified Agents have been unloaded.
24
+ # The caller supplies the exact executions and validates durable authority
25
+ # in a separate transaction while these identity reservations remain held.
26
+ # @api private
27
+ def with_idle_history_owners(persistence:, executions:, anchor: nil)
28
+ if Phronomy::WaitPolicy.blocking_forbidden?
29
+ raise Phronomy::EventLoopReentrancyError, "History release requires a host thread"
30
+ end
31
+ assert_custody_query_available!
32
+ ownership.with_idle_owners(anchor, executions.keys) do |owners|
33
+ registry = existing_registry
34
+ owners.each do |id, owner|
35
+ if owner && !owner.persistence.equal?(persistence)
36
+ raise Phronomy::Persistence::StateConflictError, "History Agent belongs to another Store"
37
+ end
38
+ next unless registry
39
+ if registry.agent_execution_admitted?(id) || executions.fetch(id).any? { |execution_id|
40
+ registry.observe_execution_custody(agent_id: id, execution_id: execution_id, environment: self).wait_result
41
+ }
42
+ raise Phronomy::AgentBusyError, "Agent #{id.inspect} retains local execution custody"
43
+ end
44
+ end
45
+ assert_custody_query_available!
46
+ yield
47
+ end
48
+ end
49
+
22
50
  def registry = raise(NotImplementedError)
23
51
  def existing_registry = raise(NotImplementedError)
24
52
  def ownership = raise(NotImplementedError)
25
53
  def existing_ownership = raise(NotImplementedError)
54
+ def assert_custody_query_available! = raise(NotImplementedError)
26
55
  def executing? = raise(NotImplementedError)
27
56
  def session_phase(id) = raise(NotImplementedError)
28
57
  def submit(**options, &operation) = raise(NotImplementedError)
@@ -0,0 +1,34 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Phronomy
4
+ module Agent
5
+ # This reserved start was rejected before durable admission was attempted.
6
+ # Another caller may have started the same identity; coordinating owners
7
+ # must observe it under their reservation guard before ending their own run.
8
+ # @api public
9
+ class ExecutionRejectedError < Phronomy::Error
10
+ attr_reader :agent_id, :execution_id
11
+
12
+ def initialize(message, agent_id:, execution_id:)
13
+ @agent_id = agent_id.to_s.dup.freeze
14
+ @execution_id = execution_id.to_s.dup.freeze
15
+ super(message, code: "agent.execution_rejected")
16
+ end
17
+
18
+ # Preserve the original validation diagnostic without changing ordinary
19
+ # invocation errors or treating cancellation as an input rejection.
20
+ # @api private
21
+ def self.from_error(error, agent_id:, execution_id:)
22
+ return error unless execution_id
23
+ return error if error.is_a?(Phronomy::CancellationError) || error.is_a?(Phronomy::TimeoutError)
24
+
25
+ begin
26
+ raise new(error.message, agent_id: agent_id, execution_id: execution_id), cause: error
27
+ rescue ExecutionRejectedError => rejected
28
+ rejected.set_backtrace(error.backtrace)
29
+ rejected
30
+ end
31
+ end
32
+ end
33
+ end
34
+ end
@@ -0,0 +1,32 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Phronomy
4
+ module Agent
5
+ # A process-local capability for one initial request and its original owner.
6
+ # The same capability spans admission, activation and failure-save stages.
7
+ # Its execution identity does not by itself prove durable admission or confer
8
+ # authority on another Agent incarnation, Runtime or process.
9
+ # @api public
10
+ class InitialPreparationRecovery
11
+ # @api public
12
+ attr_reader :agent_id, :execution_id, :recovery_id
13
+
14
+ # @api private
15
+ def initialize(operation)
16
+ @operation = operation
17
+ @agent_id = operation.agent_id.to_s.dup.freeze
18
+ @execution_id = operation.execution_id.to_s.dup.freeze
19
+ @recovery_id = operation.recovery_id.to_s.dup.freeze
20
+ if [@agent_id, @execution_id, @recovery_id].any?(&:empty?)
21
+ raise ArgumentError, "Initial preparation recovery identities must not be empty"
22
+ end
23
+ freeze
24
+ end
25
+ private_class_method :new
26
+
27
+ private
28
+
29
+ attr_reader :operation
30
+ end
31
+ end
32
+ end
@@ -0,0 +1,85 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Phronomy
4
+ module Agent
5
+ # Recovers the initial request already held by this Agent's original owner.
6
+ # Persistence confirmation, permitted first preparation and local handover
7
+ # remain distinct from a new invocation or replay of earlier callbacks.
8
+ # @api private
9
+ module InitialPreparationRecoveryApi
10
+ # Finds the one initial request retained by this exact Agent incarnation,
11
+ # including a request whose durable admission has not been established.
12
+ # Lookup performs no persistence I/O and creates no Runtime. Resolved work
13
+ # leaves the index; an already held capability can return its final receipt.
14
+ # @return [InitialPreparationRecovery, nil]
15
+ # @api public
16
+ def pending_initial_preparation_recovery
17
+ @_phronomy_runtime_owner&.existing_registry&.pending_initial_preparation_recovery(agent: self)
18
+ end
19
+
20
+ # Classifies the captured stage and lets its original owner adopt confirmed
21
+ # facts. It does not retry that stage's writes. Confirmed admission can run
22
+ # preparation for the first time, including hooks, Policy and later initial
23
+ # activation or failure saves; this method is not globally read-only.
24
+ # Previously begun callbacks, Provider calls and Tool effects are not
25
+ # replayed. Incomplete captured work remains unavailable for generic retry.
26
+ # Cancelling this observation does not cancel the retained initial request.
27
+ # @param recovery [InitialPreparationRecovery] reference from this Agent
28
+ # @return [TaskResult<InitialPreparationRecoveryResult>] a fresh observation
29
+ # @api public
30
+ def reconcile_initial_preparation_async(recovery:)
31
+ _initial_preparation_recovery_operation(recovery).observe(:reconcile)
32
+ end
33
+
34
+ # Waits for the initial recovery receipt on a host thread. The earlier
35
+ # failed observation stays closed. A resolved receipt supplies a fresh
36
+ # exact-execution observation, or a failed task for unadmitted work.
37
+ # @param recovery [InitialPreparationRecovery] reference from this Agent
38
+ # @return [InitialPreparationRecoveryResult]
39
+ # @raise [EventLoopReentrancyError] when called on EventLoop
40
+ # @api public
41
+ def reconcile_initial_preparation(recovery:)
42
+ _check_event_loop_reentrancy(:reconcile_initial_preparation, :reconcile_initial_preparation_async)
43
+ reconcile_initial_preparation_async(recovery: recovery).wait_result
44
+ end
45
+
46
+ # Authorizes retry of the current stage's exact captured writes after
47
+ # guarded pre-state and ownership checks. A confirmed post-state is adopted
48
+ # without rewriting it. Confirmed admission may then begin preparation for
49
+ # the first time and save a later stage, as in reconciliation.
50
+ # This is not permission to reconstruct an incomplete proposal, repeat
51
+ # hooks or Policy, resubmit an uncertain worker, or repeat Provider/Tool work.
52
+ # @param recovery [InitialPreparationRecovery] reference from this Agent
53
+ # @return [TaskResult<InitialPreparationRecoveryResult>] a fresh observation
54
+ # @api public
55
+ def retry_initial_preparation_async(recovery:)
56
+ _initial_preparation_recovery_operation(recovery).observe(:retry)
57
+ end
58
+
59
+ # Waits for the captured-stage retry and permitted handover receipt on a
60
+ # host thread. Job completion is observed through the receipt's fresh task.
61
+ # @param recovery [InitialPreparationRecovery] reference from this Agent
62
+ # @return [InitialPreparationRecoveryResult]
63
+ # @raise [EventLoopReentrancyError] when called on EventLoop
64
+ # @api public
65
+ def retry_initial_preparation(recovery:)
66
+ _check_event_loop_reentrancy(:retry_initial_preparation, :retry_initial_preparation_async)
67
+ retry_initial_preparation_async(recovery: recovery).wait_result
68
+ end
69
+
70
+ private
71
+
72
+ def _initial_preparation_recovery_operation(recovery)
73
+ unless recovery.is_a?(InitialPreparationRecovery)
74
+ raise ArgumentError, "recovery must be an Agent::InitialPreparationRecovery"
75
+ end
76
+ operation = recovery.send(:operation)
77
+ unless operation.is_a?(InitialPreparationRecoveryOperation) &&
78
+ operation.recovery.equal?(recovery) && operation.belongs_to?(self)
79
+ raise ArgumentError, "recovery belongs to another Agent incarnation"
80
+ end
81
+ operation
82
+ end
83
+ end
84
+ end
85
+ end
@@ -0,0 +1,41 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Phronomy
4
+ module Agent
5
+ # The initial request's observation ended while its original Agent retained
6
+ # responsibility. This error proves neither durable admission nor job failure
7
+ # nor a Provider request. A later recovery call creates a new observation.
8
+ # @api public
9
+ class InitialPreparationRecoveryError < Phronomy::Error
10
+ # @api public
11
+ attr_reader :recovery, :agent_id, :execution_id, :recovery_id,
12
+ :original_error
13
+
14
+ # @api private
15
+ def initialize(recovery:, error:, original_error: error)
16
+ unless recovery.is_a?(InitialPreparationRecovery)
17
+ raise ArgumentError, "recovery must be an Agent::InitialPreparationRecovery"
18
+ end
19
+ unless [error, original_error].all? { |value| value.nil? || value.is_a?(Exception) }
20
+ raise ArgumentError, "initial preparation recovery causes must be exceptions or nil"
21
+ end
22
+ @recovery = recovery
23
+ @agent_id = recovery.agent_id.to_s.dup.freeze
24
+ @execution_id = recovery.execution_id.to_s.dup.freeze
25
+ @recovery_id = recovery.recovery_id.to_s.dup.freeze
26
+ @operation_error = error
27
+ @original_error = original_error
28
+ super("Agent #{@agent_id.inspect} execution #{@execution_id.inspect} " \
29
+ "initial preparation recovery #{@recovery_id.inspect} requires an explicit " \
30
+ "recovery observation", code: "agent.initial_preparation_recovery")
31
+ end
32
+
33
+ # Preserve the immediate operation error across TaskResult delivery.
34
+ # @return [Exception, nil]
35
+ # @api public
36
+ def cause
37
+ @operation_error || super
38
+ end
39
+ end
40
+ end
41
+ end
@@ -0,0 +1,115 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Phronomy
4
+ module Agent
5
+ # One immutable observation of an initial stage and its original handover.
6
+ # error describes recovery, not a failed job. A resolved receipt supplies a
7
+ # fresh exact-execution task; its saved failed/cancelled status is a fulfilled
8
+ # result. Unadmitted work instead supplies a failed observation task.
9
+ # @api public
10
+ class InitialPreparationRecoveryResult
11
+ OUTCOMES = %i[confirmed_pre confirmed_post not_prepared unresolved unavailable].freeze
12
+ APPLICATION_STATES = %i[pending applied].freeze
13
+ CONTINUATION_STATES = %i[pending resumed stopped].freeze
14
+ STAGES = %i[admission activation failure].freeze
15
+ private_constant :OUTCOMES, :APPLICATION_STATES, :CONTINUATION_STATES, :STAGES
16
+
17
+ # revision is the saved revision for confirmed_post and the preceding
18
+ # revision for confirmed_pre. Admission uses zero for both; confirmed_pre
19
+ # then proves exact absence, not an existing revision-zero record.
20
+ # An unclassified or not_prepared receipt has no confirmed revision.
21
+ # @api public
22
+ attr_reader :recovery, :agent_id, :execution_id, :recovery_id, :stage,
23
+ :outcome, :application_state, :continuation_state, :revision, :execution_task, :error
24
+
25
+ # @api private
26
+ def initialize(recovery:, outcome:, application_state:, continuation_state:,
27
+ physical_complete:, stage:, revision: nil, execution_task: nil, error: nil)
28
+ unless recovery.is_a?(InitialPreparationRecovery)
29
+ raise ArgumentError, "recovery must be an Agent::InitialPreparationRecovery"
30
+ end
31
+ unless error.nil? || error.is_a?(Exception)
32
+ raise ArgumentError, "initial preparation recovery error must be an exception or nil"
33
+ end
34
+ unless OUTCOMES.include?(outcome) && APPLICATION_STATES.include?(application_state) &&
35
+ CONTINUATION_STATES.include?(continuation_state) && STAGES.include?(stage)
36
+ raise ArgumentError, "unsupported Agent initial preparation recovery state"
37
+ end
38
+ unless physical_complete.equal?(true) || physical_complete.equal?(false)
39
+ raise ArgumentError, "initial preparation physical completion must be a boolean"
40
+ end
41
+ if %i[confirmed_pre confirmed_post].include?(outcome)
42
+ unless revision.is_a?(Integer) && revision >= 0
43
+ raise ArgumentError, "confirmed initial preparation persistence requires its nonnegative execution revision"
44
+ end
45
+ if stage == :admission && revision != 0
46
+ raise ArgumentError, "confirmed initial admission uses revision zero"
47
+ end
48
+ if stage != :admission && outcome == :confirmed_post && revision.zero?
49
+ raise ArgumentError, "confirmed activation or failure requires an advanced execution revision"
50
+ end
51
+ elsif !revision.nil?
52
+ raise ArgumentError, "unclassified or unprepared initial preparation work has no confirmed revision"
53
+ end
54
+ if outcome == :not_prepared && stage != :admission
55
+ raise ArgumentError, "only initial admission can be positively unprepared"
56
+ end
57
+ stopped_before_admission = outcome == :confirmed_pre && stage == :admission && continuation_state == :stopped
58
+ unless %i[confirmed_post not_prepared].include?(outcome) || stopped_before_admission
59
+ if application_state != :pending || continuation_state != :pending
60
+ raise ArgumentError, "unconfirmed initial preparation must remain pending"
61
+ end
62
+ end
63
+ if %i[resumed stopped].include?(continuation_state)
64
+ allowed = if continuation_state == :resumed
65
+ outcome == :confirmed_post && stage == :activation
66
+ else
67
+ (outcome == :confirmed_post && stage == :failure) ||
68
+ (%i[confirmed_pre not_prepared].include?(outcome) && stage == :admission)
69
+ end
70
+ unless allowed
71
+ raise ArgumentError, "initial preparation continuation contradicts its confirmed stage"
72
+ end
73
+ unless application_state == :applied && physical_complete && execution_task.is_a?(Phronomy::TaskResult)
74
+ raise ArgumentError, "initial preparation continuation requires application, physical completion and an execution observation"
75
+ end
76
+ elsif !execution_task.nil?
77
+ raise ArgumentError, "only resumed or stopped initial preparation work has an execution observation"
78
+ end
79
+
80
+ @recovery = recovery
81
+ @agent_id = recovery.agent_id.to_s.dup.freeze
82
+ @execution_id = recovery.execution_id.to_s.dup.freeze
83
+ @recovery_id = recovery.recovery_id.to_s.dup.freeze
84
+ @stage = stage
85
+ @outcome = outcome
86
+ @application_state = application_state
87
+ @continuation_state = continuation_state
88
+ @physical_complete = physical_complete
89
+ @revision = revision
90
+ @execution_task = execution_task
91
+ @error = error
92
+ freeze
93
+ end
94
+
95
+ # True only after the original preparation and recovery workers stopped.
96
+ # Continued Provider/Tool work and the overall Agent job may still run.
97
+ # @return [Boolean]
98
+ # @api public
99
+ def physical_complete?
100
+ @physical_complete
101
+ end
102
+
103
+ # True after confirmed activation was handed to the execution owner, or
104
+ # confirmed failure/unadmitted work was handed to its stopped observation.
105
+ # Cancelled admission with confirmed pre-state stops without creating a job.
106
+ # Admission confirmation alone is unresolved. Resolution does not imply
107
+ # successful job completion or permit preparation to be replayed.
108
+ # @return [Boolean]
109
+ # @api public
110
+ def resolved?
111
+ @physical_complete && @application_state == :applied && %i[resumed stopped].include?(@continuation_state)
112
+ end
113
+ end
114
+ end
115
+ end