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
@@ -24,6 +24,11 @@ module Phronomy
24
24
  end
25
25
  private_constant :ResolutionOutcomeUnknownError
26
26
 
27
+ # Positive acknowledgement from the original serial receiver that its
28
+ # failed installation has no remaining local execution authority.
29
+ RejectedInstallation = Data.define(:error)
30
+ private_constant :RejectedInstallation
31
+
27
32
  InstallCommand = Data.define(
28
33
  :coordinator, :plan, :completion, :owner_token
29
34
  )
@@ -39,7 +44,7 @@ module Phronomy
39
44
  )
40
45
  ResolutionResult = Data.define(:execution)
41
46
  ResolutionPreparation = Data.define(:execution, :material, :error)
42
- RecoveryMaterial = Data.define(:projection, :messages, :assistant_message, :output, :usage, :response, :cancellation_requested)
47
+ RecoveryMaterial = Data.define(:output_contract, :projection, :messages, :assistant_message, :output, :usage, :response, :cancellation_requested)
43
48
  RecoveryPlan = Data.define(
44
49
  :execution, :root, :manifest, :base_manifest,
45
50
  :projection, :classification, :material
@@ -105,14 +110,20 @@ module Phronomy
105
110
  completion: completion,
106
111
  owner_token: Object.new.freeze
107
112
  )
113
+ yield(agent) if block_given?
108
114
  unless post_control(command)
115
+ yield(nil) if block_given?
109
116
  completion.fail(
110
117
  Phronomy::RuntimeShutdownError.new(
111
118
  "EventLoop rejected Agent Recovery installation"
112
119
  )
113
120
  )
114
121
  end
115
- completion.wait_result
122
+ result = completion.wait_result
123
+ if result.is_a?(RejectedInstallation)
124
+ yield(nil) if block_given?
125
+ raise result.error
126
+ end
116
127
  agent
117
128
  end
118
129
 
@@ -192,10 +203,12 @@ module Phronomy
192
203
  def post_control(command)
193
204
  admission = command.is_a?(InstallCommand) || command.is_a?(ResolveCommand)
194
205
  completion = admission ? command.completion : command.request.completion
195
- @environment.registry.post(command,
196
- admission: admission, completion: completion)
197
- rescue Phronomy::RuntimeShutdownError
198
- false
206
+ begin
207
+ registry = @environment.registry
208
+ rescue Phronomy::RuntimeShutdownError
209
+ return false
210
+ end
211
+ registry.post(command, admission: admission, completion: completion)
199
212
  end
200
213
  end
201
214
  end
@@ -20,8 +20,20 @@ module Phronomy
20
20
  end
21
21
 
22
22
  def existing_ownership = @runtime.__shutdown_participant(key: OwnershipRegistry)
23
+
24
+ # This diagnostic must not initialize or replace the originating Runtime.
25
+ # @api private
26
+ def assert_custody_query_available!
27
+ unless @runtime.equal?(Phronomy::Runtime.__default_if_initialized) && @runtime.state == :running
28
+ raise Phronomy::RuntimeShutdownError, "Agent custody observation requires its current running Runtime"
29
+ end
30
+ true
31
+ end
32
+
23
33
  def executing? = @runtime.event_loop.current?
24
34
  def session_phase(id) = @runtime.event_loop.fsm_session_state(id)
35
+ def session_admitted?(id) = @runtime.event_loop.admitted_fsm_session?(id)
36
+ def supports_submission_rejection? = true
25
37
 
26
38
  def submit(**options, &operation)
27
39
  Phronomy::Execution.submit(runtime: @runtime, **options, &operation)
@@ -14,18 +14,19 @@ module Phronomy
14
14
  @agent_id = agent_id
15
15
  end
16
16
 
17
- def create_root(definition:, context:, knowledge:, metadata:, retention: nil)
17
+ def create_root(definition:, context:, knowledge:, metadata:, retention:, write:)
18
18
  root = Agent::AgentRoot.create(
19
19
  agent_id: agent_id,
20
20
  agent_definition_id: definition.fetch(:id),
21
21
  agent_definition_version: definition.fetch(:version),
22
22
  metadata: metadata
23
23
  )
24
- persistence.transaction do |tx|
24
+ write.perform(persistence) do |tx|
25
25
  tx.agents.create(root)
26
26
  tx.retentions.retain(retention) if retention
27
27
  records = initial_context_records(tx: tx, root: root, context: context)
28
28
  records.concat(initial_knowledge_records(tx: tx, root: root, knowledge: knowledge))
29
+ appended = [].freeze
29
30
  unless records.empty?
30
31
  appended = tx.journals.append(agent_id, expected_position: 0, records: records)
31
32
  root = root.with(
@@ -35,8 +36,8 @@ module Phronomy
35
36
  )
36
37
  tx.agents.save(agent_id, expected_revision: 0, root: root)
37
38
  end
39
+ Update.new(root: root, records: appended)
38
40
  end
39
- root
40
41
  end
41
42
 
42
43
  def add_knowledge(root:, content:, metadata:)
@@ -13,10 +13,11 @@ module Phronomy
13
13
 
14
14
  # Record protocol for Agent-owned framework operations only.
15
15
  # @api private
16
- attr_reader :contents, :agents, :journals, :executions, :retentions
16
+ attr_reader :contents, :agents, :journals, :executions, :retentions, :execution_evidence_identity
17
17
 
18
18
  def initialize(coordinator:, records:)
19
19
  @coordinator, @record_adapter = coordinator, records
20
+ @execution_evidence_identity = Object.new.freeze
20
21
  @records = coordinator.bind(records)
21
22
  @contents = @records.contents
22
23
  @agents = @records.agents
@@ -37,6 +38,11 @@ module Phronomy
37
38
  scope.participate(persistence: coordinator, adapter: @record_adapter, &operation)
38
39
  end
39
40
 
41
+ # @api private
42
+ def identity_receipts?
43
+ coordinator.backend.resources.key?("agent.identity_receipts")
44
+ end
45
+
40
46
  # Authoritative presence only. Failed reads propagate, never mean absent.
41
47
  def exist?(agent_id)
42
48
  assert_observation_thread!
@@ -0,0 +1,41 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Phronomy
4
+ module Agent
5
+ # Process-local reference to one retained Agent terminal operation.
6
+ # Obtain it from a recovery error or pending_terminal_recovery. It neither
7
+ # selects a replacement Runtime nor changes Store. A designated
8
+ # StoppedTerminalCustody can accept a verified standalone terminal fact.
9
+ # @api public
10
+ class TerminalRecovery
11
+ # Diagnostic identities; possession of their strings is not authority.
12
+ # @api public
13
+ attr_reader :agent_id, :execution_id, :recovery_id
14
+
15
+ # @api private
16
+ def initialize(operation)
17
+ @operation = operation
18
+ @agent_id = operation.agent_id.to_s.dup.freeze
19
+ @execution_id = operation.execution_id.to_s.dup.freeze
20
+ @recovery_id = operation.recovery_id.to_s.dup.freeze
21
+ freeze
22
+ end
23
+ private_class_method :new
24
+
25
+ # Designate a fresh in-process recipient for a stopped terminal disposition.
26
+ # Retain the returned recipient before calling its blocking reconcile method.
27
+ # @return [Phronomy::StoppedTerminalCustody] the designated recipient
28
+ # @api public
29
+ def new_stopped_recipient
30
+ unless @operation.is_a?(TerminalRecoveryOperation) && @operation.recovery.equal?(self)
31
+ raise ArgumentError, "recovery is not the exact original terminal capability"
32
+ end
33
+ Phronomy::StoppedTerminalCustody.send(:new, @operation)
34
+ end
35
+
36
+ private
37
+
38
+ attr_reader :operation
39
+ end
40
+ end
41
+ end
@@ -0,0 +1,101 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Phronomy
4
+ module Agent
5
+ # Recovery addresses retained responsibility, including during Runtime drain.
6
+ # These observations do not enter ordinary new-execution admission or create
7
+ # a coordinator, Runtime, replacement Agent or persistence authority.
8
+ # @api private
9
+ module TerminalRecoveryApi
10
+ # Finds uncertain terminal work retained by this exact Agent incarnation.
11
+ # This local lookup performs no persistence I/O and creates no Runtime.
12
+ # Resolved work leaves the index; a held capability keeps its final receipt.
13
+ # @param execution_id [String] nonempty accepted execution identity
14
+ # @return [TerminalRecovery, nil]
15
+ # @api public
16
+ def pending_terminal_recovery(execution_id:)
17
+ unless execution_id.is_a?(String) && !execution_id.empty?
18
+ raise ArgumentError, "execution_id must be a nonempty String"
19
+ end
20
+ @_phronomy_runtime_owner&.existing_registry&.pending_agent_terminal_recovery(execution_id, agent: self)
21
+ end
22
+
23
+ # Classifies terminal persistence and applies a confirmed post-state on
24
+ # the exact original owner. It never retries writes or business actions.
25
+ # Cancelling the returned observation does not cancel retained work.
26
+ # @param recovery [TerminalRecovery] reference from this Agent
27
+ # @return [TaskResult<TerminalRecoveryResult>] a fresh observation
28
+ # @api public
29
+ def reconcile_terminal_async(recovery:)
30
+ _terminal_recovery_operation(recovery).observe(:reconcile)
31
+ end
32
+
33
+ # Waits for reconciliation on a host thread. An earlier failed or cancelled
34
+ # observation is never reopened, even after recovery succeeds.
35
+ # @param recovery [TerminalRecovery] reference from this Agent
36
+ # @return [TerminalRecoveryResult]
37
+ # @raise [EventLoopReentrancyError] when called on EventLoop
38
+ # @api public
39
+ def reconcile_terminal(recovery:)
40
+ _check_event_loop_reentrancy(:reconcile_terminal, :reconcile_terminal_async)
41
+ reconcile_terminal_async(recovery: recovery).wait_result
42
+ end
43
+
44
+ # Explicitly retries only captured terminal persistence writes. The full
45
+ # pre-state is rechecked under the original Store guard and transaction.
46
+ # Provider, Tool, parser, encoder and business callbacks are not replayed.
47
+ # @param recovery [TerminalRecovery] reference from this Agent
48
+ # @return [TaskResult<TerminalRecoveryResult>] a fresh observation
49
+ # @api public
50
+ def retry_terminal_async(recovery:)
51
+ _terminal_recovery_operation(recovery).observe(:retry)
52
+ end
53
+
54
+ # Waits for the explicit persistence-only retry on a host thread.
55
+ # @param recovery [TerminalRecovery] reference from this Agent
56
+ # @return [TerminalRecoveryResult]
57
+ # @raise [EventLoopReentrancyError] when called on EventLoop
58
+ # @api public
59
+ def retry_terminal(recovery:)
60
+ _check_event_loop_reentrancy(:retry_terminal, :retry_terminal_async)
61
+ retry_terminal_async(recovery: recovery).wait_result
62
+ end
63
+
64
+ # Explicitly resubmits terminal work only after the original execution
65
+ # mechanism proved it was not admitted and no handle or worker started.
66
+ # Validation and encoding may run for the first time; provider and Tool
67
+ # work are not repeated. This never broadens captured-write retry.
68
+ # @param recovery [TerminalRecovery] reference from this Agent
69
+ # @return [TaskResult<TerminalRecoveryResult>] a fresh observation
70
+ # @api public
71
+ def retry_terminal_submission_async(recovery:)
72
+ _terminal_recovery_operation(recovery).observe(:submission)
73
+ end
74
+
75
+ # Waits for the explicit first terminal-work submission on a host thread.
76
+ # A previous not_admitted receipt is a fact, not a reusable permission.
77
+ # @param recovery [TerminalRecovery] reference from this Agent
78
+ # @return [TerminalRecoveryResult]
79
+ # @raise [EventLoopReentrancyError] when called on EventLoop
80
+ # @api public
81
+ def retry_terminal_submission(recovery:)
82
+ _check_event_loop_reentrancy(:retry_terminal_submission, :retry_terminal_submission_async)
83
+ retry_terminal_submission_async(recovery: recovery).wait_result
84
+ end
85
+
86
+ private
87
+
88
+ def _terminal_recovery_operation(recovery)
89
+ unless recovery.is_a?(TerminalRecovery)
90
+ raise ArgumentError, "recovery must be an Agent::TerminalRecovery"
91
+ end
92
+ operation = recovery.send(:operation)
93
+ unless operation.is_a?(TerminalRecoveryOperation) &&
94
+ operation.recovery.equal?(recovery) && operation.belongs_to?(self)
95
+ raise ArgumentError, "recovery belongs to another Agent incarnation"
96
+ end
97
+ operation
98
+ end
99
+ end
100
+ end
101
+ end
@@ -0,0 +1,36 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Phronomy
4
+ module Agent
5
+ # The observation ended while its Agent still owns a terminal obligation.
6
+ # This error does not classify the job as failed or cancel its saved work.
7
+ # A later explicit recovery call returns an independent observation.
8
+ # @api public
9
+ class TerminalRecoveryError < Phronomy::Error
10
+ # @api public
11
+ attr_reader :recovery, :agent_id, :execution_id, :recovery_id, :original_error
12
+
13
+ # Constructed only after retaining responsibility for this operation.
14
+ # original_error is the original persistence/operation error, not a
15
+ # diagnostic reconstructed into an arbitrary execution exception.
16
+ # @api private
17
+ def initialize(recovery:, error:, original_error: error)
18
+ @recovery = recovery
19
+ @agent_id = recovery.agent_id.to_s.dup.freeze
20
+ @execution_id = recovery.execution_id.to_s.dup.freeze
21
+ @recovery_id = recovery.recovery_id.to_s.dup.freeze
22
+ @operation_error = error
23
+ @original_error = original_error
24
+ super("Agent #{@agent_id.inspect} execution #{@execution_id.inspect} terminal recovery " \
25
+ "#{@recovery_id.inspect} requires an explicit recovery observation", code: "agent.terminal_recovery")
26
+ end
27
+
28
+ # Preserve the immediate operation error across TaskResult delivery.
29
+ # @return [Exception, nil]
30
+ # @api public
31
+ def cause
32
+ @operation_error || super
33
+ end
34
+ end
35
+ end
36
+ end
@@ -0,0 +1,67 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Phronomy
4
+ module Agent
5
+ # One observation of persistence, original-owner application and release.
6
+ # The saved execution's failure is in execution.error; error describes the
7
+ # recovery operation itself. A confirmed pre-state retains the active job.
8
+ # @api public
9
+ class TerminalRecoveryResult
10
+ OUTCOMES = %i[confirmed_post confirmed_pre unresolved unavailable].freeze
11
+ APPLICATION_STATES = %i[pending applied].freeze
12
+ OWNERSHIP_STATES = %i[retained released transferred].freeze
13
+ SUBMISSION_STATES = %i[not_admitted admitted unknown].freeze
14
+ private_constant :OUTCOMES, :APPLICATION_STATES, :OWNERSHIP_STATES, :SUBMISSION_STATES
15
+
16
+ # @api public
17
+ attr_reader :recovery, :agent_id, :execution_id, :recovery_id, :outcome,
18
+ :application_state, :ownership_state, :revision, :execution, :error, :submission_state
19
+
20
+ # @api private
21
+ def initialize(recovery:, outcome:, application_state:, ownership_state:,
22
+ revision: nil, execution: nil, error: nil, submission_state: :unknown)
23
+ unless OUTCOMES.include?(outcome) && APPLICATION_STATES.include?(application_state) &&
24
+ OWNERSHIP_STATES.include?(ownership_state) && SUBMISSION_STATES.include?(submission_state)
25
+ raise ArgumentError, "unsupported Agent terminal recovery state"
26
+ end
27
+ if submission_state == :not_admitted && %i[confirmed_pre confirmed_post].include?(outcome)
28
+ raise ArgumentError, "unadmitted Agent terminal work cannot have a captured persistence disposition"
29
+ end
30
+ if ownership_state == :transferred && application_state != :pending
31
+ raise ArgumentError, "a stopped transfer cannot apply a live owner transition"
32
+ end
33
+ if ownership_state == :released && application_state != :applied
34
+ raise ArgumentError, "Agent ownership cannot be released before application"
35
+ end
36
+ if outcome != :confirmed_post &&
37
+ (application_state != :pending || ownership_state != :retained)
38
+ raise ArgumentError, "Agent terminal work without confirmed post-state must remain pending and retained"
39
+ end
40
+ if outcome == :confirmed_post
41
+ unless revision.is_a?(Integer) && revision.positive?
42
+ raise ArgumentError, "confirmed Agent persistence requires its positive execution revision"
43
+ end
44
+ if execution && (!execution.is_a?(ExecutionObservation) || !execution.terminal? ||
45
+ execution.agent_id != recovery.agent_id || execution.execution_id != recovery.execution_id)
46
+ raise ArgumentError, "confirmed Agent execution must match the recovery reference"
47
+ end
48
+ elsif !revision.nil? || !execution.nil?
49
+ raise ArgumentError, "only confirmed Agent post-state has a revision or execution"
50
+ end
51
+
52
+ @recovery = recovery
53
+ @agent_id = recovery.agent_id.to_s.dup.freeze
54
+ @execution_id = recovery.execution_id.to_s.dup.freeze
55
+ @recovery_id = recovery.recovery_id.to_s.dup.freeze
56
+ @outcome = outcome
57
+ @application_state = application_state
58
+ @ownership_state = ownership_state
59
+ @revision = revision
60
+ @execution = execution
61
+ @error = error
62
+ @submission_state = submission_state
63
+ freeze
64
+ end
65
+ end
66
+ end
67
+ end
@@ -102,7 +102,7 @@ module Phronomy
102
102
 
103
103
  def self.build_item(invocation)
104
104
  display = invocation.approval_display
105
- Item.new(
105
+ item = Item.new(
106
106
  tool_invocation_id: invocation.id,
107
107
  tool_call_id: invocation.tool_call_id,
108
108
  tool_name: invocation.tool_name,
@@ -112,9 +112,19 @@ module Phronomy
112
112
  origin: invocation.origin,
113
113
  metadata: invocation.metadata
114
114
  )
115
+ if Phronomy::Values::Serializable.known_duplicate_keys?([item.arguments, item.facts, item.metadata])
116
+ raise duplicate_display_error
117
+ end
118
+ item
115
119
  end
116
120
  private_class_method :build_item
117
121
 
122
+ # @api private
123
+ def self.duplicate_display_error
124
+ Phronomy::ConfigurationError.new("Approval display has duplicate JSON object names",
125
+ code: "agent.approval_display_duplicate_key")
126
+ end
127
+
118
128
  def initialize(execution_id:, items:, id: SecureRandom.uuid, created_at: Time.now.utc)
119
129
  raise ArgumentError, "ToolApprovalRequest requires at least one item" if items.empty?
120
130
  if execution_id.nil? || execution_id.to_s.empty?
@@ -129,6 +139,20 @@ module Phronomy
129
139
  end
130
140
 
131
141
  def to_h
142
+ request_fields
143
+ end
144
+
145
+ # Project the framework-owned subject for durable approval and its journal.
146
+ # Exact requests built by the Agent bypass public notification export.
147
+ # Extension subclasses retain their existing serialization behavior.
148
+ # @api private
149
+ def persistence_payload
150
+ instance_of?(ToolApprovalRequest) ? request_fields : to_h
151
+ end
152
+
153
+ private
154
+
155
+ def request_fields
132
156
  {
133
157
  id: @id,
134
158
  execution_id: @execution_id,
@@ -7,21 +7,54 @@ module Phronomy
7
7
  # This neither freezes values nor validates canonical JSON numbers/encoding.
8
8
  # @api private
9
9
  module Serializable
10
+ # @api private
11
+ class DuplicateKeyError < ArgumentError; end
12
+
10
13
  module_function
11
14
 
12
- def convert(value, unsupported_message:)
15
+ # Inspect copied containers without calling custom key or value projections.
16
+ # Only duplicate names already known from ordinary Strings and Symbols
17
+ # constitute a positive observation at this boundary.
18
+ # @api private
19
+ def known_duplicate_keys?(value)
20
+ if value.instance_of?(Hash)
21
+ seen = {}
22
+ value.any? do |key, child|
23
+ if key.instance_of?(String) || key.instance_of?(Symbol)
24
+ name = key.to_s
25
+ return true if seen.key?(name)
26
+ seen[name] = true
27
+ end
28
+ known_duplicate_keys?(child)
29
+ end
30
+ elsif value.instance_of?(Array)
31
+ value.any? { |child| known_duplicate_keys?(child) }
32
+ else
33
+ false
34
+ end
35
+ end
36
+
37
+ def convert(value, unsupported_message:, reject_duplicate_keys: false)
13
38
  case value
14
39
  when Hash
15
- value.to_h { |key, child| [key.to_s, convert(child, unsupported_message: unsupported_message)] }
40
+ seen = {} if reject_duplicate_keys
41
+ value.to_h do |key, child|
42
+ name = key.to_s
43
+ if seen
44
+ raise DuplicateKeyError, "duplicate JSON object key after normalization" if seen.key?(name)
45
+ seen[name] = true
46
+ end
47
+ [name, convert(child, unsupported_message: unsupported_message, reject_duplicate_keys: reject_duplicate_keys)]
48
+ end
16
49
  when Array
17
- value.map { |child| convert(child, unsupported_message: unsupported_message) }
50
+ value.map { |child| convert(child, unsupported_message: unsupported_message, reject_duplicate_keys: reject_duplicate_keys) }
18
51
  when String, Integer, Float, TrueClass, FalseClass, NilClass
19
52
  value
20
53
  when Symbol
21
54
  value.to_s
22
55
  else
23
56
  if value.respond_to?(:to_h)
24
- convert(value.to_h, unsupported_message: unsupported_message)
57
+ convert(value.to_h, unsupported_message: unsupported_message, reject_duplicate_keys: reject_duplicate_keys)
25
58
  else
26
59
  raise ArgumentError, "#{unsupported_message}: #{value.class}"
27
60
  end
@@ -328,6 +328,10 @@ module Phronomy
328
328
  @workers = Array.new(pool_size) { |i| spawn_worker(i) }
329
329
  end
330
330
 
331
+ # Declares the optional definite-refusal callback without acquiring work.
332
+ # @api private
333
+ def supports_submission_rejection? = true
334
+
331
335
  # Submits synchronous off-EventLoop work to the pool.
332
336
  #
333
337
  # Returns a {Phronomy::TaskResult} immediately after queue admission; the block
@@ -356,10 +360,18 @@ module Phronomy
356
360
  # operation, timer, or cancellation subscription is created. Application
357
361
  # code should use Phronomy::Blocking.call_async.
358
362
  #
363
+ # The optional rejection callback reports only a definite refusal before
364
+ # queue admission: a full nonblocking queue, a closed queue, or an already
365
+ # stopped pool. It runs synchronously before the submission exception is
366
+ # raised. No callback means no admission conclusion. Returned tasks,
367
+ # worker failures and unknown exceptions never produce this evidence.
368
+ # Callback failure cannot replace the original submission exception.
369
+ #
359
370
  # @param timeout [Numeric, nil] operation-wide deadline in seconds
360
371
  # @param cancellation_token [CancellationToken, nil] operation-wide token
361
372
  # @param on_full [Symbol] +:wait+, +:raise+, or +:timeout+
362
373
  # @param full_timeout [Numeric, nil] queue-admission timeout for +on_full: :timeout+
374
+ # @param on_rejected [Proc, nil] receives the definite submission refusal
363
375
  # @yield block containing synchronous work
364
376
  # @return [Phronomy::TaskResult]
365
377
  # @raise [Phronomy::ConfigurationError] when a timer is required but no
@@ -374,13 +386,18 @@ module Phronomy
374
386
  cancellation_token: nil,
375
387
  on_full: :wait,
376
388
  full_timeout: nil,
389
+ on_rejected: nil,
377
390
  &block
378
391
  )
379
392
  if Phronomy::WaitPolicy.blocking_forbidden? && on_full != :raise
380
393
  raise Phronomy::EventLoopReentrancyError,
381
394
  "OffloadPool admission cannot wait on EventLoop; use on_full: :raise"
382
395
  end
383
- raise Phronomy::PoolShutdownError, "pool has been shut down" if @shutdown
396
+ if @shutdown
397
+ error = Phronomy::PoolShutdownError.new("pool has been shut down")
398
+ notify_submission_rejection(on_rejected, error)
399
+ raise error
400
+ end
384
401
 
385
402
  submitted_at = Process.clock_gettime(Process::CLOCK_MONOTONIC)
386
403
  already_cancelled = cancellation_token&.cancelled? || false
@@ -448,8 +465,9 @@ module Phronomy
448
465
  begin
449
466
  @queue.push(operation, true)
450
467
  rescue ThreadError
451
- raise Phronomy::BackpressureError,
452
- "OffloadPool queue is full (depth: #{@queue_size})"
468
+ error = Phronomy::BackpressureError.new("OffloadPool queue is full (depth: #{@queue_size})")
469
+ notify_submission_rejection(on_rejected, error)
470
+ raise error
453
471
  end
454
472
  when :timeout
455
473
  deadline = full_timeout ?
@@ -474,7 +492,9 @@ module Phronomy
474
492
  rescue ClosedQueueError => e
475
493
  # Shutdown raced with this submit — preserve the existing public error.
476
494
  operation.fail_submission!(e)
477
- raise Phronomy::PoolShutdownError, "pool has been shut down"
495
+ error = Phronomy::PoolShutdownError.new("pool has been shut down")
496
+ notify_submission_rejection(on_rejected, error)
497
+ raise error
478
498
  rescue => e
479
499
  operation.fail_submission!(e)
480
500
  raise
@@ -576,6 +596,14 @@ module Phronomy
576
596
  SENTINEL = :shutdown
577
597
  private_constant :SENTINEL
578
598
 
599
+ def notify_submission_rejection(callback, error)
600
+ callback&.call(error)
601
+ rescue => _callback_error
602
+ # A failed evidence receiver grants no recovery authority. Preserve the
603
+ # actual queue refusal for the existing submission caller.
604
+ nil
605
+ end
606
+
579
607
  def offload_task_name
580
608
  @name ? "offload-#{@name}" : "offload"
581
609
  end
@@ -43,6 +43,12 @@ module Phronomy
43
43
  @mutex.synchronize { @default }
44
44
  end
45
45
 
46
+ # Inspect every original pool without opening admission or joining workers.
47
+ # @api private
48
+ def terminated?
49
+ @mutex.synchronize { @closed && (!@default || @default.terminated?) && @pools.values.all?(&:terminated?) }
50
+ end
51
+
46
52
  # Returns (or lazily creates) a named pool.
47
53
  # @param name [Symbol, String]
48
54
  # @param size [Integer]