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,10 @@ module Phronomy
13
13
  TerminalView = Data.define(
14
14
  :phase, :output, :usage, :approval_request, :rejected,
15
15
  :input_blocked, :output_blocked, :block_error,
16
- :invocation_error, :handoff, :callback_failure, :source_error, :cancel_requested, :response
16
+ :invocation_error, :handoff, :callback_failure, :source_error, :cancel_requested, :response, :output_contract, :captured_text, :approval_bytes
17
17
  ) do
18
- def initialize(response: nil, **values)
19
- super(**values, response: response)
18
+ def initialize(response: nil, output_contract: nil, captured_text: nil, approval_bytes: nil, **values)
19
+ super(**values, response: response, output_contract: output_contract, captured_text: captured_text, approval_bytes: approval_bytes)
20
20
  end
21
21
  end
22
22
  Command = Data.define(
@@ -28,6 +28,8 @@ module Phronomy
28
28
  :type, :execution, :root, :appended_records,
29
29
  :result, :error, :approval_request
30
30
  )
31
+ ApprovalPreparation = Data.define(:status, :bytes, :request, :error)
32
+ private_constant :ApprovalPreparation
31
33
 
32
34
  # @api private
33
35
  def initialize(agent:, persistence:)
@@ -36,53 +38,238 @@ module Phronomy
36
38
  end
37
39
 
38
40
  # @api private
39
- def commit_outcome(operation)
41
+ def commit_outcome(operation, on_evidence: nil, on_outcome: nil, on_prepared: nil, on_preparation: nil, on_planning: nil, on_observation: nil)
40
42
  view = operation.terminal_view
41
43
  error = view.callback_failure&.to_stream_callback_error || view.source_error ||
42
44
  view.block_error || view.invocation_error
43
45
  if !error && !view.rejected && !view.handoff && view.phase != :suspended
44
- begin
45
- contract = OutputContract.restore(operation.execution, @persistence.contents)
46
- if contract
46
+ contract = if view.output_contract
47
+ view.output_contract.for_execution(operation.execution)
48
+ elsif operation.execution.metadata["output_contract"]
49
+ OutputContract.restore(operation.execution, @persistence.contents)
50
+ end
51
+ if contract
52
+ begin
47
53
  output = contract.validate(view.output, response: view.response, execution_id: operation.execution_id)
48
54
  view = view.with(output: output)
49
55
  operation = operation.with(terminal_view: view)
56
+ rescue OutputError => validation_error
57
+ error = validation_error
50
58
  end
51
- rescue => validation_error
52
- error = validation_error
59
+ end
60
+ end
61
+ participant = operation.wiring[:phronomy_execution_participant]
62
+ capture = on_evidence && outcome_evidence_eligible?(operation, error, participant)
63
+ prepared = capture && participant&.respond_to?(:commit_prepared_outcome, true)
64
+ writes = [] if capture || on_observation
65
+ change = nil
66
+ prepare = terminal_plan_builder(operation, error) if prepared
67
+ approval_selection = native_approval_selection(operation) if prepared && !error && view.phase == :suspended
68
+ prepare_approval = -> { prepare_participant_approval(view.approval_request) } if participant && !prepared && !error && view.phase == :suspended
69
+ capture_preparation = preparation_collector(participant, on_preparation) if prepared
70
+ publish = if prepared
71
+ lambda do |input|
72
+ on_prepared&.call(input)
73
+ on_outcome&.call(input.values.fetch(:result))
74
+ evidence = input.materialize(persistence: @agent.persistence)
75
+ on_evidence.call(evidence) if evidence
76
+ evidence
53
77
  end
54
78
  end
55
79
  change = ExecutionChange.new(agent: @agent, current: operation.execution,
56
- root: operation.root, kind: :terminal, terminal: view, config: operation.wiring) do |tx, state, receipt, pending|
57
- if pending
80
+ root: operation.root, kind: :terminal, terminal: view, config: operation.wiring,
81
+ prepare_outcome: prepare, on_preparation: capture_preparation, on_prepared: publish,
82
+ on_planning: on_planning, on_partial: on_preparation, approval_selection: approval_selection,
83
+ prepare_approval: prepare_approval) do |tx, state, receipt, pending, approval|
84
+ outcome = if pending
58
85
  waiting = operation.execution.with(metadata: extension_metadata(operation.execution, state).merge(
59
86
  "cancellation_requested" => change.cancel_requested || operation.execution.metadata["cancellation_requested"] == true
60
87
  ))
61
88
  save_execution(tx, operation.execution, waiting)
62
89
  Outcome.new(type: :coordination_wait, execution: waiting, root: operation.root,
63
90
  appended_records: [].freeze, result: nil,
64
- error: error || Phronomy::ExecutionRehydrationRequiredError.new("Execution retains unfinished participant work"), approval_request: nil)
91
+ error: approval&.error || error || Phronomy::ExecutionRehydrationRequiredError.new("Execution retains unfinished participant work"), approval_request: nil)
65
92
  else
66
93
  raise error if error.is_a?(Phronomy::ExecutionRehydrationRequiredError)
67
- commit_terminal(tx, operation, state, receipt, error)
94
+ records = writes ? TerminalPersistenceEvidence.recording_scope(tx, writes) : tx
95
+ commit_participant_terminal(records, operation, state, receipt, error, approval)
96
+ end
97
+ if on_observation
98
+ # Retain computed facts before later participant evidence/readback
99
+ # can fail. These facts alone never establish a committed result.
100
+ on_outcome&.call(outcome)
101
+ on_observation.call(TerminalPersistenceEvidence.execution_observation(outcome, writes,
102
+ cancellation_requested: change.cancel_requested), cancellation_requested: change.cancel_requested)
68
103
  end
104
+ outcome
69
105
  end
70
- change.perform
106
+ (capture && !prepared) ? perform_with_evidence(change, writes, on_evidence, on_outcome, participant) : change.perform
71
107
  end
72
108
 
73
109
  private
74
110
 
75
- def commit_terminal(tx, operation, state, receipt, error)
111
+ def prepare_participant_approval(request)
112
+ bytes = serialize_approval_request(request).freeze
113
+ prepared = ToolApprovalRequest.from_h(Phronomy::CanonicalJSON.load(bytes))
114
+ unless approval_subject(prepared) == approval_subject(request) &&
115
+ prepared.items.all? { |item| [item.arguments, item.facts, item.metadata].all?(Hash) }
116
+ raise Phronomy::ConfigurationError, "Prepared approval does not match the original request"
117
+ end
118
+ ApprovalPreparation.new(status: :ready, bytes: bytes, request: prepared, error: nil)
119
+ rescue Phronomy::Values::Serializable::DuplicateKeyError
120
+ ApprovalPreparation.new(status: :invalid, bytes: nil, request: nil, error: ToolApprovalRequest.duplicate_display_error)
121
+ rescue => error
122
+ ApprovalPreparation.new(status: :unavailable, bytes: nil, request: nil, error: error)
123
+ end
124
+
125
+ def approval_subject(request)
126
+ [request.id, request.execution_id, request.items.map { |item|
127
+ [item.tool_invocation_id, item.tool_call_id, item.tool_name, item.origin]
128
+ }]
129
+ end
130
+
131
+ def commit_participant_terminal(records, operation, state, receipt, error, approval)
132
+ if approval&.bytes
133
+ operation = operation.with(terminal_view: operation.terminal_view.with(approval_request: approval.request, approval_bytes: approval.bytes))
134
+ end
135
+ error = case approval&.status
136
+ when :invalid then approval.error
137
+ when :unavailable then unavailable_approval_failure(approval.error)
138
+ else error
139
+ end
140
+ commit_terminal(records, operation, state, receipt, error)
141
+ end
142
+
143
+ def unavailable_approval_failure(error)
144
+ raise Phronomy::ConfigurationError.new("Approval display preparation failed",
145
+ code: "agent.approval_preparation_failed"), cause: error
146
+ rescue Phronomy::ConfigurationError => failure
147
+ failure
148
+ end
149
+
150
+ # Keep retained preparation independent of the synchronous transaction's
151
+ # call frame, including the original thread-bound ExecutionChange.
152
+ def terminal_plan_builder(operation, error)
153
+ view = operation.terminal_view
154
+ if !error && !view.handoff && view.phase != :suspended && String === view.output
155
+ # A plain text value has known bytes already, even when its caller
156
+ # later mutates it. Opaque conversion keeps its original method and
157
+ # identity until an authorized first attempt. Keep ordinary output
158
+ # identity separate from the value supplied to persistence.
159
+ text = built_in_text(view.output)
160
+ operation = operation.with(terminal_view: view.with(captured_text: text)) if text
161
+ end
162
+ ->(records, state, pending, cancelled) { prepare_terminal_outcome(records, operation, state, pending, error, cancelled) }
163
+ end
164
+
165
+ # This runs on the retained worker after the exact parent and child
166
+ # observations, before native selection decides whether to keep custody.
167
+ def native_approval_selection(operation)
168
+ view = operation.terminal_view
169
+ lambda do |subject|
170
+ bytes = serialize_approval_request(view.approval_request).freeze
171
+ bound = operation.with(terminal_view: view.with(approval_bytes: bytes))
172
+ [subject, terminal_plan_builder(bound, nil)]
173
+ rescue Phronomy::Values::Serializable::DuplicateKeyError
174
+ error = ToolApprovalRequest.duplicate_display_error
175
+ # An unresolved child keeps the parent held; the error grants no
176
+ # authority to acknowledge or release unfinished child work.
177
+ [subject.with(finishing: true, recovery_required: true), terminal_plan_builder(operation, error)]
178
+ end
179
+ end
180
+
181
+ def built_in_text(value)
182
+ return if Kernel.instance_method(:frozen?).bind_call(value)
183
+ # Class lookup cannot invoke an application's respond_to_missing? before
184
+ # native selection. Frozen strings already preserve their original bytes.
185
+ lookup = Kernel.instance_method(:singleton_class).bind_call(value)
186
+ method = Module.instance_method(:public_instance_method).bind_call(lookup, :to_s)
187
+ String.new(value).freeze if method.owner == String
188
+ rescue NameError
189
+ nil
190
+ end
191
+
192
+ def preparation_collector(participant, collector)
193
+ lambda do |values, plan|
194
+ preparation = OutcomePreparation.new(values, plan.writes, journal_records: plan.journal_records,
195
+ persistence: @persistence, participant: participant)
196
+ collector&.call(preparation)
197
+ preparation
198
+ end
199
+ end
200
+
201
+ def outcome_evidence_eligible?(operation, error, participant)
202
+ return false unless operation.state_required && !operation.terminal_view.handoff
203
+ if participant
204
+ %i[active suspended].include?(operation.execution.status) && participant.respond_to?(:outcome_recovery_supported?, true) &&
205
+ participant.send(:outcome_recovery_supported?, execution: operation.execution, persistence: @persistence)
206
+ else
207
+ operation.execution.status == :active && operation.terminal_view.phase != :suspended && !error.is_a?(Phronomy::ExecutionRehydrationRequiredError) &&
208
+ !operation.execution.metadata["execution_extension"]
209
+ end
210
+ end
211
+
212
+ def perform_with_evidence(change, writes, collector, outcome_collector, participant)
213
+ result = change.perform
214
+ rescue => original_error
215
+ begin
216
+ publish_evidence(change, writes, collector, outcome_collector, participant)
217
+ rescue => capture_error
218
+ begin
219
+ Phronomy::RuntimeSettings.current.logger&.warn(
220
+ "[Phronomy] Agent outcome evidence collector failed: #{capture_error.class}: #{capture_error.message}"
221
+ )
222
+ rescue
223
+ nil
224
+ end
225
+ end
226
+ raise original_error
227
+ else
228
+ # Collector failure after a successful commit propagates; the collector
229
+ # must not interpret its own failure as proof that persistence failed.
230
+ publish_evidence(change, writes, collector, outcome_collector, participant)
231
+ result
232
+ end
233
+
234
+ def publish_evidence(change, writes, collector, outcome_collector, participant)
235
+ values = change.captured_evidence
236
+ outcome_collector&.call(values.fetch(:result)) if values
237
+ evidence = TerminalPersistenceEvidence.capture(change, writes, persistence: @agent.persistence, participant: participant)
238
+ collector.call(evidence) if evidence
239
+ end
240
+
241
+ def prepare_terminal_outcome(records, operation, state, pending, error, cancellation_requested)
242
+ contents = OutcomeWritePlan::Contents.new(records.contents, write_class: TerminalPersistenceEvidence::ContentWrite)
243
+ view = OutcomeWritePlan::ContentView.new(contents: contents)
244
+ outcome = if pending
245
+ waiting = operation.execution.with(metadata: extension_metadata(operation.execution, state).merge(
246
+ "cancellation_requested" => cancellation_requested || operation.execution.metadata["cancellation_requested"] == true
247
+ ))
248
+ Outcome.new(type: :coordination_wait, execution: waiting, root: operation.root,
249
+ appended_records: [].freeze, result: nil,
250
+ error: error || Phronomy::ExecutionRehydrationRequiredError.new("Execution retains unfinished participant work"), approval_request: nil)
251
+ else
252
+ raise error if error.is_a?(Phronomy::ExecutionRehydrationRequiredError)
253
+ commit_terminal(view, operation, state, nil, error, prepare: true)
254
+ end
255
+ journal_records = operation.journal_records + outcome.appended_records if outcome.type == :completed
256
+ OutcomeWritePlan.new(outcome: outcome, writes: contents.writes, journal_records: journal_records)
257
+ end
258
+
259
+ def commit_terminal(tx, operation, state, receipt, error, prepare: false)
76
260
  view = operation.terminal_view
77
261
  if !error && view.phase == :suspended
78
262
  suspended = encode_suspension(tx, operation)
79
- suspended = with_extension(suspended, state)
80
- save_execution(tx, operation.execution, suspended)
81
- root = save_suspended_root(tx, operation.root)
82
- return Outcome.new(type: :suspended, execution: suspended, root: root,
83
- appended_records: [].freeze,
84
- result: result_base(suspended, root).merge(suspended: true, approval_request: view.approval_request).freeze,
85
- error: nil, approval_request: view.approval_request)
263
+ if suspended
264
+ suspended = with_extension(suspended, state)
265
+ save_execution(tx, operation.execution, suspended) unless prepare
266
+ root = prepare ? suspended_root(operation.root) : save_suspended_root(tx, operation.root)
267
+ return Outcome.new(type: :suspended, execution: suspended, root: root,
268
+ appended_records: [].freeze,
269
+ result: result_base(suspended, root).merge(suspended: true, approval_request: view.approval_request).freeze,
270
+ error: nil, approval_request: view.approval_request)
271
+ end
272
+ error = ToolApprovalRequest.duplicate_display_error
86
273
  end
87
274
  records, execution = if error
88
275
  encode_failure(tx, operation, error)
@@ -90,12 +277,17 @@ module Phronomy
90
277
  raise Phronomy::ConfigurationError, "Control transfer needs a transaction participant" unless receipt
91
278
  encode_transfer(tx, operation, receipt)
92
279
  else
93
- encode_completion(tx, operation)
280
+ encode_completion(tx, operation, state: state, prepare: prepare)
94
281
  end
282
+ finish_terminal(tx, operation, state, records, execution, error, prepare: prepare)
283
+ end
284
+
285
+ def finish_terminal(tx, operation, state, records, execution, error, prepare:)
286
+ view = operation.terminal_view
95
287
  execution = with_extension(execution, state)
96
- appended = append_journal(tx, operation.root, records)
97
- save_execution(tx, operation.execution, execution)
98
- root = save_terminal_root(tx, operation.root, appended)
288
+ appended = prepare ? records.each_with_index.map { |record, index| record.with_sequence(operation.root.journal_position + index + 1) } : append_journal(tx, operation.root, records)
289
+ save_execution(tx, operation.execution, execution) unless prepare
290
+ root = prepare ? terminal_root(operation.root, appended) : save_terminal_root(tx, operation.root, appended)
99
291
  if error
100
292
  Outcome.new(type: :failed, execution: execution, root: root, appended_records: appended.freeze,
101
293
  result: nil, error: error, approval_request: nil)
@@ -103,7 +295,7 @@ module Phronomy
103
295
  Outcome.new(type: :handed_off, execution: execution, root: root, appended_records: appended.freeze,
104
296
  result: result_base(execution, root).freeze, error: nil, approval_request: nil)
105
297
  else
106
- messages = transcript_messages(root, operation.journal_records + appended, persistence: tx)
298
+ messages = transcript_messages(root, operation.journal_records + appended, persistence: tx) unless prepare
107
299
  completed_outcome(view, execution, root, appended, messages)
108
300
  end
109
301
  end
@@ -139,8 +331,15 @@ module Phronomy
139
331
  def encode_suspension(tx, operation)
140
332
  current = operation.execution
141
333
  request = operation.terminal_view.approval_request
334
+ begin
335
+ approval_bytes = operation.terminal_view.approval_bytes || serialize_approval_request(request)
336
+ rescue Phronomy::Values::Serializable::DuplicateKeyError
337
+ # The public synchronous participant already selected a wait plan.
338
+ raise if operation.wiring[:phronomy_execution_participant]
339
+ return
340
+ end
142
341
  encoded_records, call_records = encode_runtime_records(tx, operation, context_candidate: true)
143
- request_ref = tx.contents.put_json(RuntimeRecordEncoder.json_value(request.to_h))
342
+ request_ref = tx.contents.put(approval_bytes, canonicalization_version: Phronomy::CanonicalJSON::VERSION)
144
343
  approval_record = JournalRecord.new(
145
344
  agent_id: @agent.agent_id,
146
345
  execution_id: current.execution_id,
@@ -155,17 +354,56 @@ module Phronomy
155
354
  phase: :approval,
156
355
  working_records: current.working_records + encoded_records + [approval_record],
157
356
  llm_calls: current.llm_calls + call_records,
158
- approval_request: RuntimeRecordEncoder.json_value(request.to_h)
357
+ approval_request: Phronomy::CanonicalJSON.load(approval_bytes)
159
358
  )
160
359
  end
161
360
 
162
- def encode_completion(tx, operation)
361
+ def serialize_approval_request(request)
362
+ payload = Phronomy::Values::Serializable.convert(request.persistence_payload,
363
+ unsupported_message: "unsupported approval request value", reject_duplicate_keys: true)
364
+ Phronomy::CanonicalJSON.dump(payload)
365
+ end
366
+
367
+ def encode_completion(tx, operation, state:, prepare:)
163
368
  current = operation.execution
164
369
  view = operation.terminal_view
165
370
  encoded_records, call_records = encode_runtime_records(tx, operation, context_candidate: true)
166
371
  structured = current.metadata.key?("output_contract") && !view.rejected
167
- output_ref = tx.contents.put_text(structured ? JSON.generate(view.output) : view.output.to_s)
372
+ text = if structured
373
+ JSON.generate(view.output)
374
+ else
375
+ begin
376
+ view.captured_text || view.output.to_s
377
+ rescue => error
378
+ raise unless prepare && !view.rejected
379
+ # Only the failed projection may be supplied. Earlier work already
380
+ # chose record identities, timestamps and exact content bytes.
381
+ prefix = OutcomeTextProjection.new(committer: self, operation: operation, state: state,
382
+ records: encoded_records, calls: call_records, writes: tx.contents.writes)
383
+ raise OutcomeTextProjection::Required.new(prefix), cause: error
384
+ end
385
+ end
386
+ output_ref = tx.contents.put_text(text)
168
387
  output_metadata = structured ? {"result_format" => "json", "raw_output_ref" => tx.contents.put_text(view.response.content)} : {}
388
+ complete_encoded_records(operation, encoded_records, call_records, output_ref, output_metadata)
389
+ end
390
+
391
+ # Finish the native text suffix from captured records without a transaction,
392
+ # an application output conversion, a policy callback or an external effect.
393
+ def finish_supplied_output(prefix, text)
394
+ contents = OutcomeWritePlan::Contents.new(nil, write_class: TerminalPersistenceEvidence::ContentWrite)
395
+ view = OutcomeWritePlan::ContentView.new(contents: contents)
396
+ operation = prefix.operation.with(terminal_view: prefix.operation.terminal_view.with(output: text))
397
+ records, execution = complete_encoded_records(operation, prefix.records, prefix.calls, contents.put_text(text),
398
+ {"outcome_text_source" => "application"})
399
+ outcome = finish_terminal(view, operation, prefix.state, records, execution, nil, prepare: true)
400
+ OutcomeWritePlan.new(outcome: outcome, writes: prefix.writes + contents.writes,
401
+ journal_records: operation.journal_records + outcome.appended_records)
402
+ end
403
+
404
+ def complete_encoded_records(operation, encoded_records, call_records, output_ref, output_metadata)
405
+ current = operation.execution
406
+ view = operation.terminal_view
169
407
  records = current.working_records + encoded_records + completion_records(operation, output_ref)
170
408
  completed = current.with(
171
409
  status: view.rejected ? :rejected : :completed,
@@ -205,9 +443,17 @@ module Phronomy
205
443
 
206
444
  def encode_failure(tx, operation, error)
207
445
  current = operation.execution
208
- encoded_records, call_records = encode_runtime_records(tx, operation, context_candidate: false)
209
- error_ref = tx.contents.put_json(error.is_a?(OutputError) ? error.diagnostic : Phronomy::Error.diagnostic(error))
210
446
  terminal_status = ExecutionFailure.status_for(error)
447
+ diagnostic_for = confirmed_failure_diagnostic(error) if terminal_status == :failed && !error.is_a?(OutputError)
448
+ encoded_records, call_records = encode_runtime_records(tx, operation, context_candidate: false, &diagnostic_for)
449
+ diagnostic = if diagnostic_for
450
+ diagnostic_for.call(error)
451
+ elsif error.is_a?(OutputError)
452
+ error.diagnostic
453
+ else
454
+ Phronomy::Error.diagnostic(error)
455
+ end
456
+ error_ref = tx.contents.put_json(diagnostic)
211
457
  records = failure_records(operation, encoded_records, terminal_status, error_ref)
212
458
  failed = current.with(
213
459
  status: terminal_status,
@@ -220,6 +466,25 @@ module Phronomy
220
466
  [records, failed]
221
467
  end
222
468
 
469
+ def confirmed_failure_diagnostic(error)
470
+ diagnostic = nil
471
+ lambda do |call_error|
472
+ if error.equal?(call_error)
473
+ diagnostic ||= failure_diagnostic(error)
474
+ else
475
+ Phronomy::Error.diagnostic(call_error)
476
+ end
477
+ end
478
+ end
479
+
480
+ def failure_diagnostic(error)
481
+ Phronomy::Error.diagnostic(error)
482
+ rescue
483
+ # Failure is already established. Persist the known class and the
484
+ # absence of its report without asking the original exception again.
485
+ {"class" => error.class.name, "diagnostic_status" => "unavailable"}
486
+ end
487
+
223
488
  def failure_records(operation, encoded_records, status, error_ref)
224
489
  audit_records = (operation.execution.working_records + encoded_records).map do |record|
225
490
  JournalRecord.from_h(record.to_h.merge("context_candidate" => false))
@@ -235,10 +500,10 @@ module Phronomy
235
500
  )
236
501
  end
237
502
 
238
- def encode_runtime_records(tx, operation, context_candidate:)
503
+ def encode_runtime_records(tx, operation, context_candidate:, &diagnostic)
239
504
  RuntimeRecordEncoder.encode(operation.execution,
240
505
  agent_id: @agent.agent_id, tx: tx, snapshot: operation.runtime_snapshot,
241
- context_candidate: context_candidate, agent_root: operation.root)
506
+ context_candidate: context_candidate, agent_root: operation.root, &diagnostic)
242
507
  end
243
508
 
244
509
  def append_journal(tx, root, records)
@@ -252,20 +517,28 @@ module Phronomy
252
517
  end
253
518
 
254
519
  def save_suspended_root(tx, root)
255
- updated = root.with(agent_revision: root.agent_revision + 1, lifecycle_status: :suspended)
520
+ updated = suspended_root(root)
256
521
  tx.agents.save(root.agent_id, expected_revision: root.agent_revision, root: updated)
257
522
  updated
258
523
  end
259
524
 
260
525
  def save_terminal_root(tx, root, appended)
261
- updated = root.with(
526
+ updated = terminal_root(root, appended)
527
+ tx.agents.save(root.agent_id, expected_revision: root.agent_revision, root: updated)
528
+ updated
529
+ end
530
+
531
+ def suspended_root(root)
532
+ root.with(agent_revision: root.agent_revision + 1, lifecycle_status: :suspended)
533
+ end
534
+
535
+ def terminal_root(root, appended)
536
+ root.with(
262
537
  agent_revision: root.agent_revision + 1,
263
538
  context_revision: root.context_revision + (appended.any?(&:context_candidate) ? 1 : 0),
264
539
  journal_position: root.journal_position + appended.length,
265
540
  lifecycle_status: :idle
266
541
  )
267
- tx.agents.save(root.agent_id, expected_revision: root.agent_revision, root: updated)
268
- updated
269
542
  end
270
543
 
271
544
  def completed_outcome(view, execution, root, appended, messages)