phronomy 0.37.0 → 0.38.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (211) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +87 -0
  3. data/README.md +24 -2
  4. data/SECURITY.md +1 -1
  5. data/docs/architecture/agent-approval-recovery.md +320 -0
  6. data/docs/architecture/agent-child-approval-recovery.md +387 -0
  7. data/docs/architecture/agent-child-execution-recovery.md +425 -0
  8. data/docs/architecture/agent-dispatch-recovery.md +308 -0
  9. data/docs/architecture/agent-terminal-persistence-evidence.md +360 -0
  10. data/docs/architecture/agent-terminal-recovery.md +298 -0
  11. data/docs/architecture/agent-terminal-submission-recovery.md +275 -0
  12. data/docs/architecture/agent-tool-child-lifetime.md +29 -0
  13. data/docs/architecture/agent-transition-ownership.md +24 -0
  14. data/docs/architecture/backend-groups.md +6 -0
  15. data/docs/architecture/detached-outcome-proof-projection.md +576 -0
  16. data/docs/architecture/execution-abstraction-review.md +5 -0
  17. data/docs/architecture/handoff-dispatch-recovery.md +205 -0
  18. data/docs/architecture/handoff-initial-terminal-application.md +321 -0
  19. data/docs/architecture/initial-preparation-recovery.md +308 -0
  20. data/docs/architecture/multi-agent-handoff.md +17 -0
  21. data/docs/architecture/native-outcome-preparation.md +715 -0
  22. data/docs/architecture/native-parent-dispatch-recovery.md +460 -0
  23. data/docs/architecture/native-parent-outcome-recovery.md +644 -0
  24. data/docs/architecture/parent-child-terminal-acknowledgement.md +297 -0
  25. data/docs/architecture/r8-unit12.md +6 -3
  26. data/docs/architecture/r8-unit4.md +11 -2
  27. data/docs/architecture/recovery-physical-attempt.md +88 -0
  28. data/docs/architecture/recovery-submission-custody.md +247 -0
  29. data/docs/architecture/retained-attempts.md +229 -0
  30. data/docs/architecture/retained-outcome-materialization.md +636 -0
  31. data/docs/architecture/retained-outcome-publication.md +506 -0
  32. data/docs/architecture/storage-execution-boundaries.md +1 -1
  33. data/docs/architecture/structured-output-and-scope.md +15 -0
  34. data/docs/architecture/synchronous-participant-application.md +397 -0
  35. data/docs/architecture/synchronous-participant-contract.md +195 -0
  36. data/docs/architecture/team-admission-rejection.md +91 -0
  37. data/docs/architecture/team-cancellation-delivery.md +245 -0
  38. data/docs/architecture/team-child-retirement.md +104 -0
  39. data/docs/architecture/tracing.md +26 -0
  40. data/docs/architecture/workflow-terminal-ownership-design.md +25 -9
  41. data/docs/architecture/workflow-terminal-reconciliation.md +221 -0
  42. data/docs/architecture.md +16 -9
  43. data/docs/decisions/025-process-local-agent-ownership-and-runtime-admission.md +8 -0
  44. data/docs/features.md +3 -3
  45. data/docs/mcp-client.md +138 -5
  46. data/docs/migrations/orchestrator-subagent-dispatch.md +89 -0
  47. data/docs/migrations/vector-async-clients.md +18 -3
  48. data/docs/persistence-backends.md +30 -4
  49. data/docs/runtime-and-concurrency.md +235 -11
  50. data/lib/phronomy/agent/admission.rb +37 -17
  51. data/lib/phronomy/agent/api/agent.rb +25 -0
  52. data/lib/phronomy/agent/approval_recovery.rb +30 -0
  53. data/lib/phronomy/agent/approval_recovery_api.rb +61 -0
  54. data/lib/phronomy/agent/approval_recovery_error.rb +39 -0
  55. data/lib/phronomy/agent/approval_recovery_result.rb +94 -0
  56. data/lib/phronomy/agent/async_event_api.rb +22 -5
  57. data/lib/phronomy/agent/base.rb +76 -48
  58. data/lib/phronomy/agent/context_preparation.rb +10 -8
  59. data/lib/phronomy/agent/dispatch_recovery.rb +29 -0
  60. data/lib/phronomy/agent/dispatch_recovery_api.rb +84 -0
  61. data/lib/phronomy/agent/dispatch_recovery_error.rb +36 -0
  62. data/lib/phronomy/agent/dispatch_recovery_result.rb +93 -0
  63. data/lib/phronomy/agent/execution/agent_invocation.rb +11 -3
  64. data/lib/phronomy/agent/execution/approval_continuation_plan.rb +131 -0
  65. data/lib/phronomy/agent/execution/approval_parent_evidence.rb +116 -0
  66. data/lib/phronomy/agent/execution/approval_persistence_evidence.rb +111 -0
  67. data/lib/phronomy/agent/execution/approval_recovery_operation.rb +496 -0
  68. data/lib/phronomy/agent/execution/approval_resume_commit.rb +174 -10
  69. data/lib/phronomy/agent/execution/dispatch_continuation_delivery.rb +96 -0
  70. data/lib/phronomy/agent/execution/dispatch_persistence_evidence.rb +147 -0
  71. data/lib/phronomy/agent/execution/dispatch_preparation.rb +63 -7
  72. data/lib/phronomy/agent/execution/dispatch_recovery_operation.rb +495 -0
  73. data/lib/phronomy/agent/execution/execution_coordinator.rb +724 -158
  74. data/lib/phronomy/agent/execution/execution_outcome_committer.rb +312 -39
  75. data/lib/phronomy/agent/execution/execution_registry.rb +508 -13
  76. data/lib/phronomy/agent/execution/initial_persistence_evidence.rb +269 -0
  77. data/lib/phronomy/agent/execution/initial_preparation.rb +132 -40
  78. data/lib/phronomy/agent/execution/initial_preparation_recovery_operation.rb +513 -0
  79. data/lib/phronomy/agent/execution/invocation_transitions.rb +3 -0
  80. data/lib/phronomy/agent/execution/outcome_planning.rb +108 -0
  81. data/lib/phronomy/agent/execution/outcome_preparation.rb +81 -0
  82. data/lib/phronomy/agent/execution/outcome_recovery_operation.rb +609 -0
  83. data/lib/phronomy/agent/execution/outcome_text_projection.rb +73 -0
  84. data/lib/phronomy/agent/execution/outcome_write_plan.rb +48 -0
  85. data/lib/phronomy/agent/execution/runtime_record_encoder.rb +7 -4
  86. data/lib/phronomy/agent/execution/terminal_persistence_evidence.rb +280 -0
  87. data/lib/phronomy/agent/execution/terminal_recovery_operation.rb +38 -0
  88. data/lib/phronomy/agent/execution_change.rb +138 -26
  89. data/lib/phronomy/agent/execution_environment.rb +29 -0
  90. data/lib/phronomy/agent/execution_rejected_error.rb +34 -0
  91. data/lib/phronomy/agent/initial_preparation_recovery.rb +32 -0
  92. data/lib/phronomy/agent/initial_preparation_recovery_api.rb +85 -0
  93. data/lib/phronomy/agent/initial_preparation_recovery_error.rb +41 -0
  94. data/lib/phronomy/agent/initial_preparation_recovery_result.rb +115 -0
  95. data/lib/phronomy/agent/lifecycle/hosted_approval_context.rb +86 -0
  96. data/lib/phronomy/agent/lifecycle/hosted_invocation.rb +42 -10
  97. data/lib/phronomy/agent/lifecycle/identity_write.rb +101 -0
  98. data/lib/phronomy/agent/lifecycle/lifetime_api.rb +28 -0
  99. data/lib/phronomy/agent/lifecycle/ownership_registry.rb +136 -70
  100. data/lib/phronomy/agent/lifecycle/scope.rb +3 -3
  101. data/lib/phronomy/agent/outcome_recovery.rb +47 -0
  102. data/lib/phronomy/agent/outcome_recovery_api.rb +114 -0
  103. data/lib/phronomy/agent/outcome_recovery_error.rb +36 -0
  104. data/lib/phronomy/agent/outcome_recovery_result.rb +92 -0
  105. data/lib/phronomy/agent/output_contract.rb +16 -6
  106. data/lib/phronomy/agent/persistence/identity_receipt_repository.rb +61 -0
  107. data/lib/phronomy/agent/persistence/records.rb +2 -0
  108. data/lib/phronomy/agent/persistence/storage_schema.rb +2 -0
  109. data/lib/phronomy/agent/recovery/invocation_restorer.rb +8 -5
  110. data/lib/phronomy/agent/recovery/recovery_coordinator/continuation.rb +6 -4
  111. data/lib/phronomy/agent/recovery/recovery_coordinator/installation.rb +21 -43
  112. data/lib/phronomy/agent/recovery/recovery_coordinator.rb +19 -6
  113. data/lib/phronomy/agent/runtime_binding/engine_environment.rb +12 -0
  114. data/lib/phronomy/agent/state_writer.rb +4 -3
  115. data/lib/phronomy/agent/store.rb +7 -1
  116. data/lib/phronomy/agent/terminal_recovery.rb +41 -0
  117. data/lib/phronomy/agent/terminal_recovery_api.rb +101 -0
  118. data/lib/phronomy/agent/terminal_recovery_error.rb +36 -0
  119. data/lib/phronomy/agent/terminal_recovery_result.rb +67 -0
  120. data/lib/phronomy/agent/tool_execution/tool_approval_request.rb +25 -1
  121. data/lib/phronomy/common/values/serializable.rb +37 -4
  122. data/lib/phronomy/engine/concurrency/offload_pool.rb +32 -4
  123. data/lib/phronomy/engine/concurrency/pool_registry.rb +6 -0
  124. data/lib/phronomy/engine/event_loop.rb +161 -11
  125. data/lib/phronomy/engine/execution_binding.rb +4 -2
  126. data/lib/phronomy/engine/execution_receiver_binding.rb +5 -0
  127. data/lib/phronomy/engine/runtime/shutdown_result.rb +21 -0
  128. data/lib/phronomy/engine/runtime/timer_queue.rb +7 -2
  129. data/lib/phronomy/engine/runtime.rb +119 -15
  130. data/lib/phronomy/execution/attempt_completion.rb +91 -0
  131. data/lib/phronomy/execution/concurrency/cancellation_token.rb +7 -2
  132. data/lib/phronomy/execution/concurrency/physical_completion_task.rb +7 -2
  133. data/lib/phronomy/execution/execution.rb +17 -2
  134. data/lib/phronomy/execution/execution_receiver.rb +27 -0
  135. data/lib/phronomy/execution/execution_retirement.rb +30 -0
  136. data/lib/phronomy/execution/invocation_controls.rb +2 -2
  137. data/lib/phronomy/execution/retained_attempts.rb +179 -0
  138. data/lib/phronomy/execution/stopped_terminal_custody.rb +99 -0
  139. data/lib/phronomy/llm_adapter/response.rb +7 -1
  140. data/lib/phronomy/multi_agent/admission_registry.rb +6 -0
  141. data/lib/phronomy/multi_agent/durable_subagent_coordinator.rb +175 -39
  142. data/lib/phronomy/multi_agent/handoff_dispatch_evidence.rb +176 -0
  143. data/lib/phronomy/multi_agent/handoff_finalization_error.rb +33 -0
  144. data/lib/phronomy/multi_agent/handoff_history_release.rb +80 -0
  145. data/lib/phronomy/multi_agent/handoff_participant.rb +31 -6
  146. data/lib/phronomy/multi_agent/handoff_runner.rb +195 -21
  147. data/lib/phronomy/multi_agent/handoff_terminal_finalization.rb +176 -0
  148. data/lib/phronomy/multi_agent/native_approval_evidence.rb +26 -0
  149. data/lib/phronomy/multi_agent/native_child_authority.rb +135 -0
  150. data/lib/phronomy/multi_agent/native_dispatch_evidence.rb +43 -0
  151. data/lib/phronomy/multi_agent/native_outcome_evidence.rb +46 -0
  152. data/lib/phronomy/multi_agent/native_persistence_plan.rb +93 -0
  153. data/lib/phronomy/multi_agent/orchestrator.rb +28 -52
  154. data/lib/phronomy/multi_agent/reserved_child_admission.rb +90 -1
  155. data/lib/phronomy/multi_agent/store.rb +5 -34
  156. data/lib/phronomy/multi_agent/subagent_history_release.rb +88 -0
  157. data/lib/phronomy/multi_agent/team_cancellation_delivery_error.rb +21 -0
  158. data/lib/phronomy/multi_agent/team_cancellation_request.rb +134 -0
  159. data/lib/phronomy/multi_agent/team_coordinator.rb +174 -27
  160. data/lib/phronomy/persistence_composition/stores.rb +10 -3
  161. data/lib/phronomy/runtime_composition/execution_defaults.rb +18 -0
  162. data/lib/phronomy/storage/backends/in_memory.rb +3 -1
  163. data/lib/phronomy/storage/resource.rb +10 -1
  164. data/lib/phronomy/tools/agent.rb +7 -1
  165. data/lib/phronomy/tools/mcp.rb +210 -91
  166. data/lib/phronomy/tools/mcp_http_close_response.rb +23 -0
  167. data/lib/phronomy/tools/mcp_transport_registry.rb +210 -0
  168. data/lib/phronomy/tools/vector_search.rb +28 -5
  169. data/lib/phronomy/tracing/automatic.rb +8 -1
  170. data/lib/phronomy/version.rb +1 -1
  171. data/lib/phronomy/workflow/execution/workflow.rb +34 -0
  172. data/lib/phronomy/workflow/execution/workflow_execution_environment.rb +1 -0
  173. data/lib/phronomy/workflow/execution/workflow_execution_registry.rb +106 -7
  174. data/lib/phronomy/workflow/execution/workflow_runner.rb +53 -108
  175. data/lib/phronomy/workflow/execution/workflow_terminal_operation.rb +489 -0
  176. data/lib/phronomy/workflow/execution/workflow_terminal_persistence.rb +81 -0
  177. data/lib/phronomy/workflow/execution/workflow_terminal_recovery.rb +38 -0
  178. data/lib/phronomy/workflow/execution/workflow_terminal_recovery_error.rb +34 -0
  179. data/lib/phronomy/workflow/execution/workflow_terminal_recovery_result.rb +56 -0
  180. data/lib/phronomy/workflow/runtime_binding/workflow_engine_environment.rb +10 -1
  181. data/lib/phronomy/workflow/runtime_binding/workflow_task_session.rb +3 -1
  182. data/lib/phronomy/workflow/runtime_binding/workflow_terminal_policy.rb +2 -1
  183. data/scripts/api_snapshot.rb +46 -1
  184. data/sig/_private/phronomy/multi_agent/team_cancellation_request.rbs +19 -0
  185. data/sig/phronomy/agent/approval_recovery.rbs +54 -0
  186. data/sig/phronomy/agent/dispatch_recovery.rbs +49 -0
  187. data/sig/phronomy/agent/execution_contract.rbs +4 -1
  188. data/sig/phronomy/agent/execution_environment.rbs +2 -0
  189. data/sig/phronomy/agent/initial_preparation_recovery.rbs +48 -0
  190. data/sig/phronomy/agent/outcome_recovery.rbs +51 -0
  191. data/sig/phronomy/agent/store.rbs +1 -0
  192. data/sig/phronomy/agent/terminal_persistence_evidence.rbs +111 -0
  193. data/sig/phronomy/agent/terminal_recovery.rbs +46 -0
  194. data/sig/phronomy/agent.rbs +36 -0
  195. data/sig/phronomy/engine/concurrency/timer_bindings.rbs +2 -0
  196. data/sig/phronomy/engine/execution_binding.rbs +2 -1
  197. data/sig/phronomy/engine/execution_receiver.rbs +4 -0
  198. data/sig/phronomy/engine/observability.rbs +22 -1
  199. data/sig/phronomy/execution/execution.rbs +16 -1
  200. data/sig/phronomy/execution/execution_receiver.rbs +12 -0
  201. data/sig/phronomy/execution/execution_retirement.rbs +18 -0
  202. data/sig/phronomy/execution/stopped_terminal_custody.rbs +19 -0
  203. data/sig/phronomy/handoff.rbs +1 -0
  204. data/sig/phronomy/multi_agent/handoff_finalization_error.rbs +18 -0
  205. data/sig/phronomy/multi_agent/store.rbs +1 -1
  206. data/sig/phronomy/multi_agent/team_cancellation_delivery_error.rbs +9 -0
  207. data/sig/phronomy/persistence_composition.rbs +2 -1
  208. data/sig/phronomy/storage/contracts.rbs +2 -1
  209. data/sig/phronomy/tools/mcp.rbs +27 -0
  210. data/sig/phronomy/workflow.rbs +42 -0
  211. metadata +104 -2
@@ -0,0 +1,81 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Phronomy
4
+ module Agent
5
+ # Exact staged records and content before fallible transcript hydration.
6
+ # This is not a complete semantic outcome or permission to replay preparation.
7
+ # Only transcript hydration is repeatable; complete input construction is single-use.
8
+ # @api private
9
+ class OutcomePreparation
10
+ class ReadContents < Phronomy::ContentStore::Base
11
+ def initialize(contents, writes)
12
+ @contents = contents
13
+ @writes = writes.to_h { |write| [write.reference, write.bytes] }
14
+ end
15
+
16
+ def fetch(reference)
17
+ value = @writes.fetch(reference) { @contents.fetch(reference) }
18
+ unless content_id_for(value) == reference
19
+ raise Phronomy::ContentStore::IntegrityError, "Prepared transcript content digest mismatch: #{reference}"
20
+ end
21
+ value.dup
22
+ end
23
+ end
24
+ private_constant :ReadContents
25
+
26
+ def initialize(values, writes, journal_records:, persistence:, participant:)
27
+ if values.fetch(:result).type == :completed && journal_records.nil?
28
+ raise ArgumentError, "Completed outcome preparation requires captured transcript records"
29
+ end
30
+ @values = {before: Phronomy::Values::Immutable.copy(values.fetch(:before)),
31
+ after: Phronomy::Values::Immutable.copy(values.fetch(:after)),
32
+ result: values.fetch(:result)}.freeze
33
+ @writes = writes.dup.freeze
34
+ @journal_records = journal_records&.dup&.freeze
35
+ @identity, @participant = persistence.execution_evidence_identity, participant
36
+ @materialized = {}
37
+ @mutex = Mutex.new
38
+ freeze
39
+ end
40
+
41
+ def materialize(persistence:)
42
+ unless persistence.execution_evidence_identity.equal?(@identity)
43
+ raise Phronomy::Persistence::StateConflictError, "Agent outcome preparation belongs to another Store"
44
+ end
45
+ @mutex.synchronize do
46
+ # Keep complete input construction single-use, including failures,
47
+ # after successful transcript hydration. Never retain the fresh content
48
+ # port or its transaction-local views.
49
+ @materialized[:outcome] ||= materialize_outcome(persistence)
50
+ return @materialized[:input] if @materialized[:input]
51
+ raise @materialized[:input_error] if @materialized[:input_error]
52
+ if @materialized[:input_attempted]
53
+ raise Phronomy::Error, "Agent outcome input construction did not complete"
54
+ end
55
+ @materialized[:input_attempted] = true
56
+ begin
57
+ @materialized[:input] = TerminalPersistenceEvidence::CapturedInput.new(
58
+ @values.merge(result: @materialized.fetch(:outcome)), @writes,
59
+ persistence: persistence, participant: @participant
60
+ )
61
+ rescue Exception => error # rubocop:disable Lint/RescueException
62
+ @materialized[:input_error] = error
63
+ raise
64
+ end
65
+ end
66
+ end
67
+
68
+ private
69
+
70
+ def materialize_outcome(persistence)
71
+ outcome = @values.fetch(:result)
72
+ return outcome unless @journal_records
73
+ contents = ReadContents.new(persistence.contents, @writes)
74
+ view = OutcomeWritePlan::ContentView.new(contents: contents)
75
+ messages = RuntimeInput.new(agent: nil, persistence: view)
76
+ .materialize_transcript(root: outcome.root, records: @journal_records)
77
+ outcome.with(result: outcome.result.merge(messages: messages).freeze)
78
+ end
79
+ end
80
+ end
81
+ end
@@ -0,0 +1,609 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "securerandom"
4
+ require "weakref"
5
+
6
+ module Phronomy
7
+ module Agent
8
+ # Owns one accepted Agent outcome save and its recovery observations.
9
+ # Workers publish facts into mailboxes; only the captured EventLoop may apply
10
+ # them. A closed observer never relinquishes the accepted Agent execution.
11
+ # @api private
12
+ class OutcomeRecoveryOperation
13
+ include Phronomy::StoppedTerminalCustody::Source
14
+
15
+ Observe = Data.define(:operation, :observer, :kind)
16
+ Ready = Data.define(:operation, :attempt_id)
17
+
18
+ attr_reader :agent, :coordinator, :environment, :agent_id, :execution_id, :fsm_session_id,
19
+ :expected_execution_revision, :recovery_id, :recovery, :command, :delivery, :live_execution_before, :admission_token
20
+
21
+ def initialize(agent:, coordinator:, environment:, command:, delivery:, committer:, admission_token: nil)
22
+ @agent = agent
23
+ @agent_reference = WeakRef.new(agent)
24
+ @coordinator, @environment, @registry = coordinator, environment, environment.registry
25
+ @persistence, @committer = agent.persistence, committer
26
+ @command, @delivery, @admission_token = command, delivery, admission_token
27
+ @agent_id, @execution_id = agent.agent_id.to_s.freeze, command.execution_id
28
+ # Suspension adds the completed Tool batch to the durable command. Its
29
+ # exact local pre-state is the still-installed execution, before staging.
30
+ @live_execution_before = @registry.agent_execution_state(@execution_id)&.execution
31
+ @fsm_session_id, @expected_execution_revision = command.fsm_session_id, command.expected_execution_revision
32
+ @recovery_id = SecureRandom.uuid.freeze
33
+ @recovery = recovery_class.send(:new, self)
34
+ @mutex = Mutex.new
35
+ @attempts = Phronomy::RetainedAttempts.new(mutex: @mutex)
36
+ @original_waiters = [delivery.result_task]
37
+ @evidence = @planning = @preparation = @prepared_input = @intended = @confirmation = @execution_observation = @captured_observation = nil
38
+ @saved_outcome = @approval_request = @suspension_task = nil
39
+ @original_error = @last_error = nil
40
+ @uncertain = @initial_delivered = @captured_cancellation_requested = false
41
+ @submission_state = :unknown
42
+ @application_state, @ownership_state = :pending, :retained
43
+ end
44
+
45
+ def recovery_kind = :outcome
46
+
47
+ def captured_cancellation_requested?
48
+ @mutex.synchronize do
49
+ @evidence&.after&.fetch(0)&.fetch(4) == true || @captured_cancellation_requested ||
50
+ @intended&.execution&.metadata&.fetch("cancellation_requested", false) == true
51
+ end
52
+ end
53
+
54
+ # A recovered wait cannot bind cancellation to its already-closed caller.
55
+ # This private task follows the still-owned logical execution instead.
56
+ def suspension_task
57
+ @mutex.synchronize do
58
+ @suspension_task ||= Phronomy::TaskResult.deferred(name: "recovered-approval-wait:#{recovery_id}")
59
+ end
60
+ end
61
+
62
+ def belongs_to?(candidate)
63
+ @agent_reference.__getobj__.equal?(candidate)
64
+ rescue WeakRef::RefError
65
+ false
66
+ end
67
+
68
+ def pending?
69
+ @mutex.synchronize { @uncertain && @ownership_state == :retained }
70
+ end
71
+
72
+ def output_text_required?
73
+ @mutex.synchronize { @ownership_state == :retained && @preparation.is_a?(OutcomeTextProjection) && @preparation.missing? }
74
+ end
75
+
76
+ def supply_output_text(expected_revision:, text:)
77
+ unless Integer === expected_revision && expected_execution_revision == expected_revision
78
+ raise ArgumentError, "Supplied outcome revision does not identify this retained execution"
79
+ end
80
+ raise ArgumentError, "Supplied outcome must be text" unless String === text
81
+ value = String.new(text).encode(Encoding::UTF_8).freeze
82
+ raise ArgumentError, "Supplied outcome must be valid UTF-8 text" unless value.valid_encoding?
83
+ @mutex.synchronize do
84
+ unless @uncertain && @ownership_state == :retained && @preparation.is_a?(OutcomeTextProjection) &&
85
+ @attempts.quiescent_locked? && !@attempts.active_snapshot_locked
86
+ raise Phronomy::Error, "This retained outcome cannot accept a text projection now"
87
+ end
88
+ @preparation.supply(value)
89
+ end
90
+ end
91
+
92
+ def applied?
93
+ @mutex.synchronize { @application_state == :applied }
94
+ end
95
+
96
+ def released?
97
+ @mutex.synchronize { @ownership_state == :released }
98
+ end
99
+
100
+ def ordinary_delivery?
101
+ @mutex.synchronize { !@uncertain }
102
+ end
103
+
104
+ def application_applied!
105
+ @mutex.synchronize { @application_state = :applied }
106
+ end
107
+
108
+ def release_permitted?
109
+ @mutex.synchronize do
110
+ @application_state == :applied && @attempts.quiescent_locked?
111
+ end
112
+ end
113
+
114
+ def released
115
+ @mutex.synchronize do
116
+ @ownership_state = :released
117
+ @agent = @coordinator = @environment = @registry = @persistence = @committer = nil
118
+ @command = @delivery = @intended = @evidence = @planning = @preparation = @prepared_input = @suspension_task = @live_execution_before = @admission_token = @captured_observation = nil
119
+ @attempts.release_references_locked(nil)
120
+ @original_waiters = []
121
+ @original_error = @last_error = nil
122
+ end
123
+ end
124
+
125
+ def start
126
+ @registry.retain_terminal_operation(self)
127
+ task = submit_terminal_worker(nil)
128
+ watch(nil)
129
+ self
130
+ rescue => error
131
+ if task
132
+ mark_uncertain_on_owner(error)
133
+ else
134
+ @mutex.synchronize do
135
+ @attempts.submission_failed_locked(nil, error, refused: @submission_state == :not_admitted)
136
+ end
137
+ signal(nil)
138
+ end
139
+ self
140
+ end
141
+
142
+ def observe(kind = :reconcile)
143
+ raise ArgumentError, "unsupported Agent #{recovery_kind} recovery operation" unless %i[reconcile retry submission].include?(kind)
144
+ observer = Phronomy::TaskResult.deferred(name: "agent-#{recovery_kind}-#{kind}:#{@recovery_id}")
145
+ @attempts.register(observer)
146
+ registry, settled = @mutex.synchronize { [@registry, @stopped_receipt || @ownership_state == :released] }
147
+ if settled
148
+ observer.complete(build_result)
149
+ elsif !registry || !registry.post(Observe.new(operation: self, observer: observer, kind: kind),
150
+ completion: delivery_observer(observer))
151
+ observer.complete(unavailable_result(Phronomy::RuntimeShutdownError.new("Original Agent owner is unavailable")))
152
+ end
153
+ observer
154
+ rescue => error
155
+ observer&.complete(unavailable_result(error))
156
+ observer || raise
157
+ end
158
+
159
+ def shutdown(error)
160
+ failure = fail_original(error)
161
+ observers = @attempts.observers
162
+ observers.each { |observer| observer.complete(unavailable_result(error)) }
163
+ failure
164
+ end
165
+
166
+ def deliver(message)
167
+ case message
168
+ when Observe then observe_on_owner(message.observer, message.kind)
169
+ when Ready
170
+ message.attempt_id ? finish_attempt(message.attempt_id) : deliver_initial
171
+ else
172
+ raise Phronomy::Error, "unsupported Agent #{recovery_kind} recovery message"
173
+ end
174
+ end
175
+
176
+ # Safe outside EventLoop: only the original observation is settled here.
177
+ # Registry ownership and live execution state remain untouched.
178
+ def fail_original(error)
179
+ task, failure = @mutex.synchronize do
180
+ @uncertain = true
181
+ @last_error = error
182
+ @original_error ||= error
183
+ [@delivery&.result_task, diagnostic_locked(error)]
184
+ end
185
+ task&.fail(failure)
186
+ acknowledge_original_if_quiet
187
+ failure
188
+ end
189
+
190
+ def retain_original_waiters(waiters)
191
+ @mutex.synchronize { @original_waiters |= waiters }
192
+ acknowledge_original_if_quiet
193
+ end
194
+
195
+ private
196
+
197
+ def acknowledge_original_if_quiet
198
+ waiters = @mutex.synchronize { (@uncertain && @attempts.snapshot_locked(nil)[:physical]) ? @original_waiters.dup : [] }
199
+ waiters.each { |task| task.finish_operation! if task.respond_to?(:finish_operation!) }
200
+ end
201
+
202
+ def submit_terminal_worker(id)
203
+ @mutex.synchronize { @submission_state = :unknown }
204
+ refusal = lambda do |_error|
205
+ @mutex.synchronize { @attempts.submission_rejected_locked(id) }
206
+ end
207
+ task = Phronomy::Execution.submit_with_rejection_evidence(@environment, on_full: :raise, on_rejected: refusal) do
208
+ @mutex.synchronize do
209
+ @submission_state = :admitted
210
+ @attempts.worker_started_locked(id)
211
+ end
212
+ result = @committer.commit_outcome(@command,
213
+ on_evidence: method(:capture_evidence), on_outcome: method(:capture_outcome),
214
+ on_prepared: method(:capture_prepared_input), on_preparation: method(:capture_preparation),
215
+ on_planning: method(:capture_planning),
216
+ on_observation: method(:capture_observation))
217
+ capture_worker(id, result, nil)
218
+ result
219
+ rescue Exception => error # rubocop:disable Lint/RescueException
220
+ capture_worker(id, nil, error)
221
+ raise
222
+ end
223
+ # An admitted queued task consumes authority even before its block starts.
224
+ @mutex.synchronize do
225
+ @submission_state = :admitted
226
+ @attempts.task_returned_locked(id, task)
227
+ end
228
+ task
229
+ rescue => error
230
+ @mutex.synchronize do
231
+ slot = @attempts.snapshot_locked(id)
232
+ if slot
233
+ proven_refusal = slot[:rejection_confirmed] && !slot[:started] && @submission_state != :admitted
234
+ @submission_state = :not_admitted if proven_refusal
235
+ @attempts.submission_failed_locked(id, error, refused: proven_refusal)
236
+ end
237
+ end
238
+ raise
239
+ end
240
+
241
+ def capture_evidence(value)
242
+ @mutex.synchronize { @evidence = value }
243
+ end
244
+
245
+ def capture_prepared_input(value)
246
+ @mutex.synchronize do
247
+ if @prepared_input && !@prepared_input.equal?(value)
248
+ raise Phronomy::Error, "Agent outcome cannot replace its complete captured proposal"
249
+ end
250
+ @prepared_input = value
251
+ @intended = value.values.fetch(:result)
252
+ end
253
+ end
254
+
255
+ def capture_planning(value)
256
+ @mutex.synchronize { @planning = value }
257
+ end
258
+
259
+ def capture_preparation(value)
260
+ @mutex.synchronize do
261
+ if @preparation && !@preparation.equal?(value)
262
+ raise Phronomy::Error, "Agent outcome cannot replace its staged preparation"
263
+ end
264
+ @preparation = value
265
+ @planning = nil
266
+ end
267
+ end
268
+
269
+ # Readback and captured-write retry own the same physical lane as first
270
+ # submission. A lost handle cannot establish that their work was refused.
271
+ # This fact belongs to the attempt; it does not change submission_state,
272
+ # which describes the original terminal worker's admission.
273
+ def submit_recovery_worker(id, &work)
274
+ @attempts.submit(id, submitter: @environment,
275
+ missing_handle_message: "Agent #{recovery_kind} recovery submission returned no task handle", &work)
276
+ end
277
+
278
+ def capture_observation(value, cancellation_requested:)
279
+ @mutex.synchronize do
280
+ @captured_observation = value
281
+ @captured_cancellation_requested = cancellation_requested == true
282
+ end
283
+ end
284
+
285
+ def capture_outcome(value)
286
+ @mutex.synchronize { @intended = value }
287
+ end
288
+
289
+ def capture_worker(id, result, error)
290
+ @mutex.synchronize do
291
+ return unless @attempts.record_worker_locked(id, result, error)
292
+ @original_error ||= error if id.nil?
293
+ end
294
+ end
295
+
296
+ def watch(id)
297
+ @attempts.watch(id) do |event|
298
+ acknowledge_original_if_quiet if id.nil? && event == :physical
299
+ signal(id)
300
+ end
301
+ end
302
+
303
+ def refresh_attempt(id)
304
+ acknowledge_original_if_quiet if @attempts.refresh(id) && id.nil?
305
+ end
306
+
307
+ def signal(id)
308
+ registry = @mutex.synchronize { @registry }
309
+ return unless registry
310
+ return if registry.post(Ready.new(operation: self, attempt_id: id))
311
+ delivery_failed(id, Phronomy::RuntimeShutdownError.new("Agent owner rejected terminal evidence"))
312
+ rescue => error
313
+ delivery_failed(id, error)
314
+ end
315
+
316
+ def delivery_failed(id, error)
317
+ return fail_original(error) unless id
318
+ observers = @mutex.synchronize do
319
+ @attempts.take_observers_locked(id)
320
+ end
321
+ observers.each { |observer| observer.complete(unavailable_result(error)) }
322
+ end
323
+
324
+ def delivery_observer(observer)
325
+ Phronomy::TaskResult.deferred(name: "agent-#{recovery_kind}-delivery:#{@recovery_id}").tap do |delivery|
326
+ delivery.on_complete do |_value, error|
327
+ observer.complete(unavailable_result(error)) if error
328
+ end
329
+ end
330
+ end
331
+
332
+ def deliver_initial
333
+ refresh_attempt(nil)
334
+ slot, uncertain = @mutex.synchronize { [@attempts.snapshot_locked(nil), @uncertain] }
335
+ return unless slot[:logical]
336
+ return if @mutex.synchronize { @initial_delivered || @ownership_state == :released }
337
+ return if !slot[:physical] && !slot[:error] && !uncertain
338
+ if slot[:error] || uncertain
339
+ error = slot[:error] || @last_error || Phronomy::Error.new("Agent #{recovery_kind} save requires explicit recovery")
340
+ mark_uncertain_on_owner(error)
341
+ @mutex.synchronize { @initial_delivered = true }
342
+ return
343
+ end
344
+ @mutex.synchronize { @initial_delivered = true }
345
+ remember_post(slot[:result])
346
+ apply_confirmation
347
+ rescue => error
348
+ mark_uncertain_on_owner(error)
349
+ end
350
+
351
+ def mark_uncertain_on_owner(error)
352
+ failure = fail_original(error)
353
+ coordinator = @mutex.synchronize { @coordinator }
354
+ coordinator&.send(:terminal_recovery_failed_on_event_loop, self, failure)
355
+ failure
356
+ end
357
+
358
+ def observe_on_owner(observer, kind)
359
+ return if observer.done?
360
+ refresh_attempt(nil)
361
+ registry, released, physical, active = @mutex.synchronize do
362
+ [@registry, @ownership_state == :released, @attempts.snapshot_locked(nil)[:physical], @attempts.active_snapshot_locked]
363
+ end
364
+ return observer.complete(build_result) if released
365
+ unless registry&.owns_terminal_operation?(self)
366
+ return observer.complete(unavailable_result(Phronomy::Error.new("Agent #{recovery_kind} recovery owner no longer matches")))
367
+ end
368
+ unless physical
369
+ return observer.complete(unavailable_result(Phronomy::Error.new("Original Agent save is still physically active")))
370
+ end
371
+ return observe_active_attempt(observer, active, kind) if active
372
+ if @mutex.synchronize { @confirmation == :committed }
373
+ return observer.complete(apply_confirmation)
374
+ end
375
+ # A successful late worker result is stronger than its abandoned task.
376
+ outcome = @mutex.synchronize do
377
+ initial = @attempts.snapshot_locked(nil)
378
+ initial[:physical] && initial[:result]
379
+ end
380
+ if outcome
381
+ remember_post(outcome)
382
+ return observer.complete(apply_confirmation)
383
+ end
384
+ if kind == :submission
385
+ unless @mutex.synchronize { @submission_state == :not_admitted }
386
+ return observer.complete(unavailable_result(Phronomy::Error.new("Agent #{recovery_kind} submission was not authoritatively refused")))
387
+ end
388
+ return begin_submission_retry(observer)
389
+ end
390
+ begin_recovery_attempt(observer, kind)
391
+ rescue => error
392
+ observer.complete(unavailable_result(error))
393
+ end
394
+
395
+ def observe_active_attempt(observer, active, kind)
396
+ if active[:admission_unknown]
397
+ return observer.complete(unavailable_result(active[:error] || Phronomy::Error.new("Agent #{recovery_kind} submission has no authoritative admission receipt")))
398
+ end
399
+ if active[:watch_error]
400
+ refresh_attempt(active[:id])
401
+ active = @mutex.synchronize { @attempts.snapshot_locked(active[:id]) }
402
+ completion_observable = active && ((active[:logical] && active[:physical]) || active[:physical_watch])
403
+ return observer.complete(unavailable_result(active&.fetch(:watch_error))) unless completion_observable
404
+ end
405
+ if active[:kind] != kind
406
+ return observer.complete(unavailable_result(Phronomy::Error.new("A different Agent #{recovery_kind} recovery operation is physically active")))
407
+ end
408
+ @mutex.synchronize { @attempts.join_locked(active[:id], observer: observer) }
409
+ finish_attempt(active[:id])
410
+ nil
411
+ end
412
+
413
+ def begin_recovery_attempt(observer, kind)
414
+ evidence, prepared_input, preparation, planning, persistence = @mutex.synchronize do
415
+ [@evidence, @prepared_input, @preparation, @planning, @persistence]
416
+ end
417
+ unless evidence || prepared_input || preparation || planning
418
+ message = if @command.wiring[:phronomy_execution_participant]
419
+ "Synchronous participant has no supported retained outcome proof; callback replay is unavailable"
420
+ else
421
+ "Agent #{recovery_kind} save has no complete captured proposal"
422
+ end
423
+ return observer.complete(unavailable_result(Phronomy::Error.new(message)))
424
+ end
425
+ id = Object.new.freeze
426
+ @mutex.synchronize do
427
+ @attempts.reserve_locked(id, kind: kind, observer: observer)
428
+ end
429
+ task = submit_recovery_worker(id) do
430
+ # The prefix has no encoded proposal. Reconciliation may inspect its
431
+ # guarded source; only an explicit retry may start the first decision.
432
+ next planning.reconcile(persistence: persistence) if planning && kind == :reconcile
433
+ unless evidence
434
+ unless prepared_input
435
+ prepared_input = (preparation || planning).materialize(persistence: persistence)
436
+ capture_prepared_input(prepared_input)
437
+ end
438
+ evidence = prepared_input.materialize(persistence: persistence)
439
+ raise Phronomy::Error, "Complete Agent outcome proposal could not construct its persistence proof" unless evidence
440
+ capture_evidence(evidence)
441
+ end
442
+ evidence.public_send(kind, persistence: persistence, original_error: @original_error)
443
+ end
444
+ watch(id)
445
+ rescue => error
446
+ if task || (id && @mutex.synchronize { @attempts.snapshot_locked(id)&.fetch(:admission_unknown) })
447
+ delivery_failed(id, error)
448
+ else
449
+ observers = @attempts.retire(defined?(id) && id)
450
+ (observers.empty? ? [observer] : observers).each { |item| item.complete(unavailable_result(error)) }
451
+ end
452
+ end
453
+
454
+ def begin_submission_retry(observer)
455
+ id = Object.new.freeze
456
+ @mutex.synchronize do
457
+ @attempts.reserve_locked(id, kind: :submission, observer: observer)
458
+ end
459
+ task = submit_terminal_worker(id)
460
+ watch(id)
461
+ rescue => error
462
+ if task || @mutex.synchronize { @attempts.snapshot_locked(id)&.fetch(:admission_unknown) }
463
+ # A returned handle can be polled later. Without one, physical completion
464
+ # remains unknown even if a hidden worker eventually publishes a value.
465
+ delivery_failed(id, error)
466
+ else
467
+ @attempts.retire(id).each { |item| item.complete(unavailable_result(error)) }
468
+ end
469
+ end
470
+
471
+ def finish_attempt(id)
472
+ refresh_attempt(id)
473
+ slot = @mutex.synchronize { @attempts.snapshot_locked(id) }
474
+ return unless slot && slot[:logical] && slot[:physical]
475
+ if slot[:error] && !slot[:error].is_a?(StandardError)
476
+ @attempts.retire(id).each { |observer| observer.fail(slot[:error]) }
477
+ return
478
+ end
479
+ result = slot[:result]
480
+ observation = if slot[:kind] == :submission
481
+ if result
482
+ remember_post(result)
483
+ apply_confirmation
484
+ else
485
+ unavailable_result(slot[:error] || Phronomy::Error.new("Agent #{recovery_kind} submission produced no confirmed outcome"))
486
+ end
487
+ elsif result&.disposition == :committed
488
+ intended = @mutex.synchronize { @intended }
489
+ if intended
490
+ remember_post(intended)
491
+ apply_confirmation
492
+ else
493
+ unavailable_result(Phronomy::Error.new("Agent #{recovery_kind} proof has no retained semantic outcome"))
494
+ end
495
+ elsif result&.disposition == :not_committed
496
+ build_result(outcome: :confirmed_pre, error: result.read_error && diagnostic(result.read_error))
497
+ else
498
+ error = slot[:error] || result&.read_error
499
+ build_result(outcome: error ? :unavailable : :unresolved, error: error && diagnostic(error))
500
+ end
501
+ @attempts.retire(id).each_with_index do |observer, index|
502
+ observer.complete(index.zero? ? observation : build_result(outcome: observation.outcome, error: observation.error))
503
+ end
504
+ rescue => error
505
+ @attempts.retire(id).each { |observer| observer.complete(unavailable_result(error)) }
506
+ end
507
+
508
+ def remember_post(outcome)
509
+ raise Phronomy::Error, "Agent #{recovery_kind} save returned no semantic outcome" unless outcome
510
+ execution = outcome.execution
511
+ observation = if execution.terminal?
512
+ # The worker already decoded this observation from the exact captured
513
+ # content. Publication must not revisit mutable output or exception code.
514
+ @mutex.synchronize { @evidence&.outcome&.execution_observation || @captured_observation } ||
515
+ raise(Phronomy::Error, "Agent #{recovery_kind} save has no captured execution observation")
516
+ end
517
+ @mutex.synchronize do
518
+ @confirmation = :committed
519
+ @intended = outcome
520
+ @revision = execution.execution_revision
521
+ @execution_observation = observation
522
+ @saved_outcome = case outcome.type
523
+ when :completed, :failed, :handed_off then :terminal
524
+ when :coordination_wait then :coordination_wait
525
+ when :suspended then :approval_wait
526
+ else raise Phronomy::Error, "Unsupported captured outcome: #{outcome.type.inspect}"
527
+ end
528
+ @approval_request = outcome.approval_request if outcome.type == :suspended
529
+ end
530
+ end
531
+
532
+ def apply_confirmation
533
+ coordinator, outcome = @mutex.synchronize { [@coordinator, @intended] }
534
+ return build_result if @mutex.synchronize { @ownership_state == :released }
535
+ apply_to_owner(coordinator, outcome)
536
+ build_result
537
+ rescue => error
538
+ mark_uncertain_on_owner(error)
539
+ build_result(error: diagnostic(error))
540
+ end
541
+
542
+ def unavailable_result(error)
543
+ build_result(outcome: :unavailable, error: diagnostic(error))
544
+ end
545
+
546
+ def build_result(outcome: nil, error: nil)
547
+ state = @mutex.synchronize do
548
+ [@confirmation, @application_state, @ownership_state, @revision, @execution_observation,
549
+ @submission_state, @saved_outcome, @approval_request, @stopped_receipt]
550
+ end
551
+ confirmation, application, ownership, revision, execution, submission, saved_outcome, approval_request, stopped = state
552
+ if stopped
553
+ return recovery_result_class.new(recovery: @recovery, outcome: stopped.outcome,
554
+ application_state: :pending, ownership_state: :transferred, revision: stopped.revision,
555
+ execution: stopped.value, submission_state: :admitted, **receipt_details(:terminal, nil))
556
+ end
557
+ outcome = :confirmed_post if confirmation == :committed
558
+ recovery_result_class.new(recovery: @recovery, outcome: outcome || :unavailable,
559
+ application_state: application, ownership_state: ownership,
560
+ revision: revision, execution: execution && ExecutionObservation.new(**execution.to_h),
561
+ submission_state: submission, error: error, **receipt_details(saved_outcome, approval_request))
562
+ end
563
+
564
+ def read_stopped_terminal(retry_save:)
565
+ raise Phronomy::Error, "stopped participant outcome recovery is read-only" if retry_save
566
+
567
+ evidence, store, failure = stopped_read_context
568
+ unless evidence&.outcome&.execution_observation&.terminal?
569
+ raise Phronomy::Error, "stopped Agent outcome transfer requires complete terminal evidence"
570
+ end
571
+ proof = evidence.reconcile(persistence: store, original_error: failure, stopped_outcome: true)
572
+ stopped_terminal_receipt(evidence, proof)
573
+ end
574
+
575
+ def stopped_read_context
576
+ @mutex.synchronize { [@evidence, @persistence, @original_error] }
577
+ end
578
+
579
+ def stopped_terminal_receipt(evidence, proof)
580
+ unless proof.disposition == :committed
581
+ raise(proof.read_error || Phronomy::Error.new("original Agent terminal post-state is unconfirmed"))
582
+ end
583
+ Phronomy::StoppedTerminalCustody::Receipt.new(recovery_id: recovery_id, outcome: :confirmed_post,
584
+ revision: evidence.outcome.execution.execution_revision, value: evidence.outcome.execution_observation, error: nil)
585
+ end
586
+
587
+ def recovery_class = OutcomeRecovery
588
+ def recovery_result_class = OutcomeRecoveryResult
589
+ def recovery_error_class = OutcomeRecoveryError
590
+
591
+ def receipt_details(saved_outcome, approval_request) = {saved_outcome: saved_outcome, approval_request: approval_request}
592
+
593
+ def apply_to_owner(coordinator, outcome)
594
+ coordinator.send(:apply_retained_outcome_on_event_loop, self, outcome)
595
+ end
596
+
597
+ def diagnostic(error)
598
+ @mutex.synchronize { diagnostic_locked(error) }
599
+ end
600
+
601
+ def diagnostic_locked(error)
602
+ return error if error.is_a?(recovery_error_class) && error.recovery.equal?(@recovery)
603
+ recovery_error_class.new(recovery: @recovery,
604
+ error: error || Phronomy::Error.new("Agent #{recovery_kind} outcome requires reconciliation"),
605
+ original_error: @original_error || error)
606
+ end
607
+ end
608
+ end
609
+ end