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,715 @@
1
+ # Prepare native outcome evidence before storage writes
2
+
3
+ Agent owns the records and local delivery of one accepted execution outcome. MultiAgent owns the native child relationships that determine whether that outcome is final, waiting for coordination, or waiting for approval. Persistence owns the real transaction and authoritative readback. G3i moves complete outcome preparation ahead of the physical writes within these existing responsibilities; it adds no public API or new job owner.
4
+
5
+ For example, a report parent first waits for its reviewer, then asks permission to publish, then completes the report. A storage fault at any of those three parent saves must not repeat the review, the publication Tool, or a Provider response. Capturing the exact save proposal before writing gives the original owner enough evidence to use its existing reconciliation and explicit persistence-only retry operations.
6
+
7
+ This document compares applied G3h `cfef5fc0b961e8e29868e0fa15b03326dc1d7629` with G3i. Contract concept v55 and foundation v48 are the responsibility references. The preceding [native outcome and approval recovery account](native-parent-outcome-recovery.md) defines the public protocol; this change repairs a bounded preparation gap within it. An arbitrary encoder or conversion failure before a complete proposal remains unresolved and is not counted as a completed recovery.
8
+
9
+ ## Responsibility and the capture boundary
10
+
11
+ The original native worker prepares Agent values and native values under the existing guarded transaction. It retains complete detached input, constructs the proof object, and only then applies the captured physical writes. A content-only buffer holds encoded bytes; it is neither a replacement Store nor a committed transaction.
12
+
13
+ For example, an approval-wait proposal includes the exact approval request, suspended execution and root, encoded Agent content, native extension content and permitted retention changes. If its first content write fails, the proposal is already complete. If proof construction itself fails after complete raw capture, later recovery may rebuild that proof without reconstructing the approval request.
14
+
15
+ | Owner | Preparation responsibility | Physical or publication responsibility |
16
+ | --- | --- | --- |
17
+ | Agent | Validate output once; prepare content, record identities, timestamps, journal sequences, root/execution values and semantic outcome; retain complete before/after values. | Apply captured Agent writes through Persistence; publish the confirmed saved kind on the original owner. |
18
+ | MultiAgent | Interpret native child acknowledgements, pending work, cancellation, extension content and allowed retention changes. | Supply current native authority for captured-write retry; preserve the native relationship and saved-kind meaning. |
19
+ | Persistence | Supply the guarded outer scope, identity and authoritative read views. | Atomically apply captured content, records, extension and retention effects; expose exact pre/post or conflicting state. |
20
+ | Application | Select whether a confirmed pre-state should be retried and whether a restored approval request should receive a new decision. | Observe fresh recovery results; keep unresolved responsibility alive; submit later approval or resume separately. |
21
+
22
+ The principal implementation points are `ExecutionOutcomeCommitter#prepare_terminal_outcome`, the private `ExecutionChange#commit_prepared_outcome_in`, `OutcomeWritePlan`, `TerminalPersistenceEvidence::CapturedInput`, and the native coordinator's private `commit_prepared_outcome`. The native coordinator supplies this private opt-in; existing custom participants and Handoff are not made repeatable by it.
23
+
24
+ Complete raw input contains detached proof outcome values as well as before/after footprints and captured content. Error diagnostics, approval hashes and result copying occur before that input is retained. Later `CapturedInput#materialize` uses those retained values and the original Store identity; it does not call output validation, the runtime encoder, participant commit, Provider or Tool work again. Failure while producing those complete values is still an incomplete-preparation failure.
25
+
26
+ ## Unchanged public operations and distinct lifetimes
27
+
28
+ Recovery acts on an exact capability retained by the original Agent incarnation. The existing method families distinguish read-only reconciliation, explicit captured-write retry and first-submission retry. Each asynchronous call returns a fresh observation; the synchronous form waits for that observation on a host thread.
29
+
30
+ For example, `parent.reconcile_outcome(recovery: recovery)` can confirm that an approval wait was saved and publish its request. It cannot approve the request. `parent.retry_outcome(recovery: recovery)` can save a complete retained proposal only when current pre-state and native authority permit it; it cannot regenerate an incomplete proposal.
31
+
32
+ | Operation or family | Arguments and defaults | Result and sync/async symmetry | Lifetime and boundary |
33
+ | --- | --- | --- | --- |
34
+ | `pending_outcome_recovery` | Required `execution_id:`; nonempty String. | Exact `OutcomeRecovery` or `nil`; local lookup has no async partner because it performs no I/O. | Original incarnation only; resolved recovery leaves the pending index. |
35
+ | `reconcile_outcome` / `reconcile_outcome_async` | Required exact `recovery:`; no retry flag or timeout argument. | `OutcomeRecoveryResult` / fresh `TaskResult<OutcomeRecoveryResult>`. | Reads persistence and may apply a confirmed fact locally; never retries storage or business work. Pure proof reconstruction is permitted after physical settlement. |
36
+ | `retry_outcome` / `retry_outcome_async` | Required exact `recovery:`; no implicit application-policy default. | Same receipt family / fresh task. | Explicit captured-write permission only; rechecks exact pre-state and current native authority. |
37
+ | `retry_outcome_submission` / `retry_outcome_submission_async` | Required exact `recovery:`; no new preparation-retry option. | Same receipt family / fresh task. | Only positive first-submission refusal authorizes submission. An admitted preparation failure does not qualify. |
38
+ | `TerminalRecovery` | Existing terminal-only family. | Existing final-result semantics. | Native waits do not become terminal results; the native preparation opt-in does not broaden standalone preparation recovery. |
39
+ | `ApprovalRecovery` | Existing exact decision capability and reconciliation operations. | Existing decision and continuation receipts. | Read-only recovery of a decision; restoring a pre-state wait does not submit approval again. |
40
+
41
+ The synchronous recovery methods reject EventLoop reentrancy. Observation timeout and cancellation belong to `TaskResult`; they do not terminate the physical operation, transfer ownership or authorize a concurrent write. The original failed observation stays failed even after a later recovery succeeds.
42
+
43
+ | Confirmed saved kind | Meaning of recovery-owner release | Remaining job responsibility |
44
+ | --- | --- | --- |
45
+ | Terminal | The exact final result has been applied and local execution admission can end. | Durable history and explicit relationship cleanup still follow their existing contracts. |
46
+ | Coordination wait | Publication of the captured wait ends this save-recovery responsibility and its local execution admission. | The durable parent job remains active with its native child relationship; later ordinary resume is separate. |
47
+ | Approval wait | Publication of the exact request ends this save-recovery responsibility. | Suspended execution admission and cancellation binding remain live until the approval protocol advances. |
48
+
49
+ A generic preparation retry API was rejected because a frozen command or an unchanged Store does not prove arbitrary conversion or participant code is safe to run twice. A generic virtual Store was unnecessary because the required reusable input is a bounded native and Agent persistence plan. The application keeps explicit policy rather than hiding automatic retry or automatic approval in a helper.
50
+
51
+ ## Equivalence and intentional failure behavior changes
52
+
53
+ Ordinary report execution preserves the same input, approval order, outputs, business effects and release behavior. Fault behavior is intentionally different only where a complete proposal can be prepared before a storage failure; this is a recovery improvement, not observational equivalence under failure.
54
+
55
+ For example, the normal report performs five offline Provider calls, one review Tool and one publication Tool. With a terminal native-content fault, G3h retains an unavailable recovery owner. G3i preserves the complete proposal, classifies exact pre-state, and permits an explicitly requested captured-write retry without a sixth Provider call or a second publication.
56
+
57
+ | Condition | Before: applied G3h | After: G3i contract |
58
+ | --- | --- | --- |
59
+ | Normal workflow | Two explicit approvals; child output `review ready`; parent output `report ready`; five Provider calls and one effect per Tool; both jobs complete and explicit unload releases the local owner pair while durable history remains. | The same ordinary application function and observable business contract. |
60
+ | Selected physical content, journal, execution or root write fails during the original save | In the characterized cases, the owner remains retained and reconciliation is unavailable because the complete proposal was not retained. | Complete raw input and proof precede the write. Reconciliation classifies exact state; explicit captured-write retry can finish from an eligible pre-state. |
61
+ | Proof wrapper fails after complete raw capture | No separate retained raw-input materialization path. | Retain complete input and responsibility; after original physical settlement, materialize the proof read-only, then reconcile or explicitly retry. No initial write is admitted without the proof. |
62
+ | Application declines captured-write retry | Retained unavailable recovery in the characterized pre-capture fault cases. | A confirmed pre-state remains retained. No Provider, Tool or persistence write is automatically repeated. |
63
+ | A recovered approval decision restores its pre-state wait | The separate approval protocol requires a new application decision. | Same requirement; `approve_after_restore: false` leaves the exact wait pending. |
64
+ | Encoder, conversion, diagnostic detachment or other preparation fails before complete input | Incomplete evidence and unresolved ownership. | Still unresolved; do not replay opaque preparation or describe a retained owner as successful cleanup. |
65
+ | Current cancellation, native child authority or durable state conflicts | Existing evidence and ownership must be preserved. | No forced captured write and no substituted relationship. Historical confirmed post-state remains a fact; new write authority is checked separately. |
66
+ | Observer closes while physical work continues | Observer completion does not establish physical settlement. | Same custody and overlap rules. |
67
+
68
+ The physical fixture below raises immediately before or after one repository call inside the original outer transaction. An after-write injection can still roll that transaction back; it is not by itself evidence of a committed post-state. Lost committed acknowledgements, conflicting readback and physical overlap require their separate implementation tests.
69
+
70
+ ## Shared application setup
71
+
72
+ The report application uses the actual Runtime, native parent/child orchestration, approval APIs and in-memory Persistence. Only the Provider is deterministic and offline. The shared setup defines every business class and dependency used by both versions of the functions below.
73
+
74
+ For example, the Provider first dispatches the reviewer, later asks the parent to publish, and raises if the workflow requests any unexpected sixth response. Both Tools require independent explicit approval and record their effects so repeated business work is visible. This example declares no output schema: its zero output-validator counter is not evidence about parser replay. The independent [Runtime acceptance suite](../../spec/phronomy/multi_agent/native_outcome_preparation_recovery_spec.rb) separately supplies a real output schema, observes one validation and one encoding before a content failure, and verifies that reconciliation and captured-write retry leave those counts at one.
75
+
76
+ Copy this setup once, one selected column of each function comparison, the shared recovery helpers, the complete fixture and the shared driver into a single Ruby file in that order. The helpers may be defined after the normal function; all definitions are loaded before the driver runs. No external application helper or omitted policy is required. The fixture intentionally instruments the process, so run each example in a fresh Ruby process with the chosen Phronomy checkout on the load path.
77
+
78
+ <!-- g3i-code:shared-setup -->
79
+ ```ruby
80
+ require "phronomy"
81
+ require "json"
82
+ require "timeout"
83
+ class G3iReviewTool < Phronomy::Tool::Base
84
+ tool_name "review_one_report"
85
+ description "Review the approved report once"
86
+ requires_approval true
87
+
88
+ class << self
89
+ attr_accessor :effects
90
+ end
91
+
92
+ def execute(query:)
93
+ self.class.effects << query
94
+ "reviewed #{query}"
95
+ end
96
+ end
97
+
98
+ class G3iPublishTool < Phronomy::Tool::Base
99
+ tool_name "publish_one_report"
100
+ description "Publish the approved report once"
101
+ requires_approval true
102
+
103
+ class << self
104
+ attr_accessor :effects
105
+ end
106
+
107
+ def execute(query:)
108
+ self.class.effects << query
109
+ "published #{query}"
110
+ end
111
+ end
112
+
113
+ class G3iReviewAgent < Phronomy::Agent::Base
114
+ agent_definition id: "native-outcome-reviewer", version: 1
115
+ model "offline-model"
116
+ tools G3iReviewTool => nil
117
+ end
118
+
119
+ class G3iReportParent < Phronomy::MultiAgent::Orchestrator
120
+ agent_definition id: "native-outcome-parent", version: 1
121
+ model "offline-model"
122
+ tools G3iPublishTool => nil
123
+ subagent :reviewer, G3iReviewAgent
124
+ end
125
+
126
+ class G3iReportAdapter < Phronomy::LLMAdapter::Base
127
+ attr_reader :calls
128
+
129
+ def initialize
130
+ @calls = 0
131
+ end
132
+
133
+ def perform_complete(_request, cancellation_token:)
134
+ cancellation_token&.raise_if_cancelled!
135
+ @calls += 1
136
+ name, arguments = case @calls
137
+ when 1 then ["dispatch_to_reviewer", {input: "Review the report"}]
138
+ when 2 then ["review_one_report", {query: "quarterly report"}]
139
+ when 3
140
+ return Phronomy::LLMAdapter::Response.new(content: "review ready", finish_reason: :stop)
141
+ when 4 then ["publish_one_report", {query: "quarterly report"}]
142
+ when 5
143
+ return Phronomy::LLMAdapter::Response.new(content: "report ready", finish_reason: :stop)
144
+ else
145
+ raise "Unexpected repeated Provider work"
146
+ end
147
+ Phronomy::LLMAdapter::Response.new(tool_calls: [
148
+ Phronomy::Tool::CallRequest.new(id: "call-#{@calls}", name: name, arguments: arguments)
149
+ ], finish_reason: :tool_calls)
150
+ end
151
+ end
152
+
153
+ def build_report_service
154
+ G3iReviewTool.effects = []
155
+ G3iPublishTool.effects = []
156
+ adapter = G3iReportAdapter.new
157
+ Phronomy.configure { |configuration| configuration.llm_adapter = adapter }
158
+ stores = Phronomy::PersistenceComposition.in_memory
159
+ approvals = Queue.new
160
+ parent = G3iReportParent.create(agent_id: "native-outcome-parent", persistence: stores.agent,
161
+ coordination_store: stores.multi_agent,
162
+ on_event: ->(event) { approvals << event.payload.fetch(:request) if event.type == :approval_required })
163
+ [adapter, stores, approvals, parent]
164
+ end
165
+ ```
166
+ <!-- /g3i-code:shared-setup -->
167
+
168
+ ## Complete ordinary function before and after
169
+
170
+ The normal application function directly names each approval owner, observes the two known waiting points and explicitly unloads the completed parent/child local owner pair. Both columns are complete and identical because G3i changes preparation within the framework rather than requiring a new normal application protocol.
171
+
172
+ For example, the first request identifies the reviewer execution and is approved on that child. The second request must identify the parent execution before publication is approved. The returned values expose outputs, effects, job statuses, revisions and remaining history holds for comparison. Normal execution returns revisions `[9, 6]` and history holds `[1, 1]` in both versions; successful local unload does not erase those durable holds.
173
+
174
+ <table>
175
+ <thead><tr><th>Before: applied G3h</th><th>After: G3i</th></tr></thead>
176
+ <tbody><tr>
177
+ <td><pre><code class="language-ruby" data-g3i-unit="normal-before"># The exact approval request identifies which entity may accept the decision.
178
+ def run_report
179
+ adapter, stores, approvals, parent = build_report_service
180
+ parent_id = "native-report-execution"
181
+ reservation = Phronomy::Agent::ReservedExecution.new(agent_id: parent.agent_id, execution_id: parent_id)
182
+ original = parent.start_hosted(reservation: reservation, input: "Prepare and publish the report")
183
+ child_request = Timeout.timeout(5) { approvals.pop }
184
+ begin
185
+ original.wait_result(timeout: 5)
186
+ rescue Phronomy::ExecutionRehydrationRequiredError
187
+ # The parent waits for this approval-driven child.
188
+ end
189
+ child = Phronomy::Agent::Base.live_for_execution(child_request.execution_id)
190
+ child_result = child.approve_async(child_request.execution_id,
191
+ approval_request_id: child_request.id, approved: true).wait_result(timeout: 5)
192
+ continued = parent.resume_async(parent_id)
193
+ parent_request = Timeout.timeout(5) { approvals.pop }
194
+ raise "Expected the parent's own approval" unless parent_request.execution_id == parent_id
195
+ begin
196
+ continued.wait_result(timeout: 5)
197
+ rescue Phronomy::ExecutionRehydrationRequiredError
198
+ # The parent now waits for its own publication decision.
199
+ end
200
+ parent_result = parent.approve_async(parent_id,
201
+ approval_request_id: parent_request.id, approved: true).wait_result(timeout: 5)
202
+ released = parent.unload_with_completed_child!(parent_id, execution_id: child_request.execution_id)
203
+ {
204
+ child_output: child_result.fetch(:output), parent_output: parent_result.fetch(:output),
205
+ review_effects: G3iReviewTool.effects, publication_effects: G3iPublishTool.effects,
206
+ provider_calls: adapter.calls, released: released,
207
+ statuses: [parent_id, child_request.execution_id].map { |id| stores.agent.executions.load(id).status },
208
+ revisions: [parent_id, child_request.execution_id].map { |id| stores.agent.executions.load(id).execution_revision },
209
+ history_holds: [parent.agent_id, child.agent_id].map { |id| stores.agent.retained_references(agent_id: id).size }
210
+ }
211
+ end
212
+ </code></pre></td>
213
+ <td><pre><code class="language-ruby" data-g3i-unit="normal-after"># The exact approval request identifies which entity may accept the decision.
214
+ def run_report
215
+ adapter, stores, approvals, parent = build_report_service
216
+ parent_id = "native-report-execution"
217
+ reservation = Phronomy::Agent::ReservedExecution.new(agent_id: parent.agent_id, execution_id: parent_id)
218
+ original = parent.start_hosted(reservation: reservation, input: "Prepare and publish the report")
219
+ child_request = Timeout.timeout(5) { approvals.pop }
220
+ begin
221
+ original.wait_result(timeout: 5)
222
+ rescue Phronomy::ExecutionRehydrationRequiredError
223
+ # The parent waits for this approval-driven child.
224
+ end
225
+ child = Phronomy::Agent::Base.live_for_execution(child_request.execution_id)
226
+ child_result = child.approve_async(child_request.execution_id,
227
+ approval_request_id: child_request.id, approved: true).wait_result(timeout: 5)
228
+ continued = parent.resume_async(parent_id)
229
+ parent_request = Timeout.timeout(5) { approvals.pop }
230
+ raise "Expected the parent's own approval" unless parent_request.execution_id == parent_id
231
+ begin
232
+ continued.wait_result(timeout: 5)
233
+ rescue Phronomy::ExecutionRehydrationRequiredError
234
+ # The parent now waits for its own publication decision.
235
+ end
236
+ parent_result = parent.approve_async(parent_id,
237
+ approval_request_id: parent_request.id, approved: true).wait_result(timeout: 5)
238
+ released = parent.unload_with_completed_child!(parent_id, execution_id: child_request.execution_id)
239
+ {
240
+ child_output: child_result.fetch(:output), parent_output: parent_result.fetch(:output),
241
+ review_effects: G3iReviewTool.effects, publication_effects: G3iPublishTool.effects,
242
+ provider_calls: adapter.calls, released: released,
243
+ statuses: [parent_id, child_request.execution_id].map { |id| stores.agent.executions.load(id).status },
244
+ revisions: [parent_id, child_request.execution_id].map { |id| stores.agent.executions.load(id).execution_revision },
245
+ history_holds: [parent.agent_id, child.agent_id].map { |id| stores.agent.retained_references(agent_id: id).size }
246
+ }
247
+ end
248
+ </code></pre></td>
249
+ </tr></tbody>
250
+ </table>
251
+
252
+ ## Shared explicit recovery policy
253
+
254
+ The recovery helpers separate an observed failure from application permission to retry its captured persistence. They verify the exact retained capability and never reopen the original failed task. Approval decision recovery remains a separate branch with its own explicit permission to submit a restored request again.
255
+
256
+ For example, `retry_confirmed_pre: false` returns a pending owner after a confirmed pre-state instead of repairing it automatically. If approval reconciliation restores a wait, `approve_after_restore: false` returns that wait instead of sending another approval. A production service must retain the returned parent, capability and receipt while responsibility is pending.
257
+
258
+ <!-- g3i-code:recovery-helper -->
259
+ ```ruby
260
+ # This example retries only captured outcome persistence when its application
261
+ # explicitly permits that action. Wait recovery is not job completion.
262
+ def settle_parent_outcome(parent:, failure:, retry_confirmed_pre:, recoveries:)
263
+ recovery = parent.pending_outcome_recovery(execution_id: failure.recovery.execution_id)
264
+ raise "The exact outcome owner was not retained" unless recovery.equal?(failure.recovery)
265
+ receipt = parent.reconcile_outcome(recovery: recovery)
266
+ if retry_confirmed_pre && receipt.outcome == :confirmed_pre
267
+ receipt = parent.retry_outcome(recovery: recovery)
268
+ end
269
+ applied = receipt.outcome == :confirmed_post && receipt.application_state == :applied && receipt.ownership_state == :released
270
+ return {state: :recovery_pending, parent: parent, recovery: recovery, receipt: receipt} unless applied
271
+
272
+ recoveries << {operation: :outcome, saved_outcome: receipt.saved_outcome, outcome: receipt.outcome}
273
+ case receipt.saved_outcome
274
+ when :coordination_wait then {state: :coordination_wait}
275
+ when :approval_wait then {state: :approval_wait, request: receipt.approval_request}
276
+ when :terminal
277
+ execution = receipt.execution
278
+ raise "Report failed: #{execution.error.inspect}" unless execution.status == :completed
279
+ {state: :completed, result: {output: execution.result}}
280
+ end
281
+ end
282
+
283
+ # expected_wait describes this report's two known waiting points. It is not a
284
+ # general classification of every ExecutionRehydrationRequiredError.
285
+ def await_parent_outcome(parent:, task:, expected_wait:, retry_confirmed_pre:, recoveries:)
286
+ {state: :completed, result: task.wait_result(timeout: 5)}
287
+ rescue Phronomy::Agent::OutcomeRecoveryError => failure
288
+ observed = settle_parent_outcome(parent: parent, failure: failure,
289
+ retry_confirmed_pre: retry_confirmed_pre, recoveries: recoveries)
290
+ begin
291
+ task.wait_result(timeout: 5)
292
+ raise "The earlier failed observation reopened"
293
+ rescue Phronomy::Agent::OutcomeRecoveryError => repeated
294
+ raise "The earlier failure changed" unless repeated.equal?(failure)
295
+ end
296
+ observed
297
+ rescue Phronomy::ExecutionRehydrationRequiredError
298
+ {state: expected_wait}
299
+ end
300
+
301
+ # Approval recovery only reconciles the old decision. A confirmed pre-state
302
+ # restores the exact wait; sending an approval again is a separate user policy.
303
+ def approve_report(parent:, execution_id:, request:, approve_after_restore:, retry_confirmed_pre:, recoveries:)
304
+ task = parent.approve_async(execution_id, approval_request_id: request.id, approved: true)
305
+ begin
306
+ await_parent_outcome(parent: parent, task: task, expected_wait: :approval_wait,
307
+ retry_confirmed_pre: retry_confirmed_pre, recoveries: recoveries)
308
+ rescue Phronomy::Agent::ApprovalRecoveryError => failure
309
+ recovery = parent.pending_approval_recovery(execution_id: execution_id)
310
+ raise "The exact approval owner was not retained" unless recovery.equal?(failure.recovery)
311
+ receipt = parent.reconcile_approval(recovery: recovery)
312
+ unless receipt.resolved?
313
+ return {state: :recovery_pending, parent: parent, recovery: recovery, receipt: receipt}
314
+ end
315
+ begin
316
+ task.wait_result(timeout: 5)
317
+ raise "The earlier failed decision reopened"
318
+ rescue Phronomy::Agent::ApprovalRecoveryError => repeated
319
+ raise "The earlier decision failure changed" unless repeated.equal?(failure)
320
+ end
321
+ recoveries << {operation: :approval, outcome: receipt.outcome, continuation_state: receipt.continuation_state}
322
+ if receipt.continuation_state == :restored
323
+ unless approve_after_restore
324
+ return {state: :approval_wait, parent: parent, request: request, receipt: receipt}
325
+ end
326
+ next_task = parent.approve_async(execution_id, approval_request_id: request.id, approved: true)
327
+ else
328
+ next_task = receipt.execution_task
329
+ end
330
+ await_parent_outcome(parent: parent, task: next_task, expected_wait: :approval_wait,
331
+ retry_confirmed_pre: retry_confirmed_pre, recoveries: recoveries)
332
+ end
333
+ end
334
+ ```
335
+ <!-- /g3i-code:recovery-helper -->
336
+
337
+ ## Complete recovery function before and after
338
+
339
+ The same complete recovery function uses only existing public operations on both versions. It preserves the same business process as the ordinary function while exposing unresolved responsibility and policy choices as explicit return values. The columns are source-identical; the storage-fault results are intentionally different under the capture-before-write implementation.
340
+
341
+ For example, a failure at the first coordination-wait save can return before the reviewer is approved. A failure at the parent's own approval wait can return after review but before publication. A final-save failure can recover the already computed report without either Tool executing twice.
342
+
343
+ <table>
344
+ <thead><tr><th>Before: applied G3h</th><th>After: G3i</th></tr></thead>
345
+ <tbody><tr>
346
+ <td><pre><code class="language-ruby" data-g3i-unit="recovery-before"># The same business process has two independent application approvals. Neither
347
+ # persistence recovery nor a recovered wait silently supplies either decision.
348
+ def run_report_with_recovery(fault:, retry_confirmed_pre: false, approve_after_restore: false)
349
+ adapter, stores, approvals, parent = build_report_service
350
+ parent_id = "native-report-execution"
351
+ fault.call(stores.agent, parent_id)
352
+ reservation = Phronomy::Agent::ReservedExecution.new(agent_id: parent.agent_id, execution_id: parent_id)
353
+ recoveries = []
354
+ original = parent.start_hosted(reservation: reservation, input: "Prepare and publish the report")
355
+ first = await_parent_outcome(parent: parent, task: original, expected_wait: :coordination_wait,
356
+ retry_confirmed_pre: retry_confirmed_pre, recoveries: recoveries)
357
+ return first.merge(stores: stores, execution_id: parent_id, provider_calls: adapter.calls) if first.fetch(:state) == :recovery_pending
358
+ raise "Expected the child coordination wait" unless first.fetch(:state) == :coordination_wait
359
+ child_request = Timeout.timeout(5) { approvals.pop }
360
+ child = Phronomy::Agent::Base.live_for_execution(child_request.execution_id)
361
+ child_result = child.approve_async(child_request.execution_id,
362
+ approval_request_id: child_request.id, approved: true).wait_result(timeout: 5)
363
+ continued = parent.resume_async(parent_id)
364
+ second = await_parent_outcome(parent: parent, task: continued, expected_wait: :approval_wait,
365
+ retry_confirmed_pre: retry_confirmed_pre, recoveries: recoveries)
366
+ return second.merge(stores: stores, child: child, execution_id: parent_id, provider_calls: adapter.calls) if second.fetch(:state) == :recovery_pending
367
+ raise "Expected the parent's own approval" unless second.fetch(:state) == :approval_wait
368
+ parent_request = second[:request] || Timeout.timeout(5) { approvals.pop }
369
+ raise "Approval identifies another execution" unless parent_request.execution_id == parent_id
370
+ final = approve_report(parent: parent, execution_id: parent_id, request: parent_request,
371
+ approve_after_restore: approve_after_restore, retry_confirmed_pre: retry_confirmed_pre, recoveries: recoveries)
372
+ unless final.fetch(:state) == :completed
373
+ return final.merge(stores: stores, child: child, execution_id: parent_id, provider_calls: adapter.calls)
374
+ end
375
+ released = parent.unload_with_completed_child!(parent_id, execution_id: child_request.execution_id)
376
+ {
377
+ state: :observed, child_output: child_result.fetch(:output), parent_output: final.fetch(:result).fetch(:output),
378
+ review_effects: G3iReviewTool.effects, publication_effects: G3iPublishTool.effects,
379
+ provider_calls: adapter.calls, released: released,
380
+ statuses: [parent_id, child_request.execution_id].map { |id| stores.agent.executions.load(id).status },
381
+ history_holds: [parent.agent_id, child.agent_id].map { |id| stores.agent.retained_references(agent_id: id).size },
382
+ recoveries: recoveries
383
+ }
384
+ end
385
+ </code></pre></td>
386
+ <td><pre><code class="language-ruby" data-g3i-unit="recovery-after"># The same business process has two independent application approvals. Neither
387
+ # persistence recovery nor a recovered wait silently supplies either decision.
388
+ def run_report_with_recovery(fault:, retry_confirmed_pre: false, approve_after_restore: false)
389
+ adapter, stores, approvals, parent = build_report_service
390
+ parent_id = "native-report-execution"
391
+ fault.call(stores.agent, parent_id)
392
+ reservation = Phronomy::Agent::ReservedExecution.new(agent_id: parent.agent_id, execution_id: parent_id)
393
+ recoveries = []
394
+ original = parent.start_hosted(reservation: reservation, input: "Prepare and publish the report")
395
+ first = await_parent_outcome(parent: parent, task: original, expected_wait: :coordination_wait,
396
+ retry_confirmed_pre: retry_confirmed_pre, recoveries: recoveries)
397
+ return first.merge(stores: stores, execution_id: parent_id, provider_calls: adapter.calls) if first.fetch(:state) == :recovery_pending
398
+ raise "Expected the child coordination wait" unless first.fetch(:state) == :coordination_wait
399
+ child_request = Timeout.timeout(5) { approvals.pop }
400
+ child = Phronomy::Agent::Base.live_for_execution(child_request.execution_id)
401
+ child_result = child.approve_async(child_request.execution_id,
402
+ approval_request_id: child_request.id, approved: true).wait_result(timeout: 5)
403
+ continued = parent.resume_async(parent_id)
404
+ second = await_parent_outcome(parent: parent, task: continued, expected_wait: :approval_wait,
405
+ retry_confirmed_pre: retry_confirmed_pre, recoveries: recoveries)
406
+ return second.merge(stores: stores, child: child, execution_id: parent_id, provider_calls: adapter.calls) if second.fetch(:state) == :recovery_pending
407
+ raise "Expected the parent's own approval" unless second.fetch(:state) == :approval_wait
408
+ parent_request = second[:request] || Timeout.timeout(5) { approvals.pop }
409
+ raise "Approval identifies another execution" unless parent_request.execution_id == parent_id
410
+ final = approve_report(parent: parent, execution_id: parent_id, request: parent_request,
411
+ approve_after_restore: approve_after_restore, retry_confirmed_pre: retry_confirmed_pre, recoveries: recoveries)
412
+ unless final.fetch(:state) == :completed
413
+ return final.merge(stores: stores, child: child, execution_id: parent_id, provider_calls: adapter.calls)
414
+ end
415
+ released = parent.unload_with_completed_child!(parent_id, execution_id: child_request.execution_id)
416
+ {
417
+ state: :observed, child_output: child_result.fetch(:output), parent_output: final.fetch(:result).fetch(:output),
418
+ review_effects: G3iReviewTool.effects, publication_effects: G3iPublishTool.effects,
419
+ provider_calls: adapter.calls, released: released,
420
+ statuses: [parent_id, child_request.execution_id].map { |id| stores.agent.executions.load(id).status },
421
+ history_holds: [parent.agent_id, child.agent_id].map { |id| stores.agent.retained_references(agent_id: id).size },
422
+ recoveries: recoveries
423
+ }
424
+ end
425
+ </code></pre></td>
426
+ </tr></tbody>
427
+ </table>
428
+
429
+ ## Complete physical fault fixture
430
+
431
+ The fixture wraps actual committer and repository methods to select one parent outcome and one physical write. It counts committer, encoder, legacy participant-commit and output-validation calls across both the original worker and recovery worker. It does not replace Persistence or replay application work.
432
+
433
+ For example, `parent_storage_fault(boundary: :approval_wait, site: :agent_content, mode: :after)` injects exactly one failure after the parent's Agent content call. Native content and execution writes apply to all three outcomes; Agent content and root writes apply to terminal and approval-wait saves; a terminal journal write applies only to a terminal save. These eleven sites each have before/after variants, giving twenty-two fault cases. The G3i private native preparation path bypasses the legacy participant `commit` method, so its zero participant-commit count does not mean no native preparation occurred; direct private-preparation call counts belong to the independent Runtime acceptance tests.
434
+
435
+ <!-- g3i-code:fault-fixture -->
436
+ ```ruby
437
+ # The fault fixture observes the real committer and physical repositories.
438
+ # It does not substitute a persistence implementation or replay application work.
439
+ module G3iOutcomeInstrumentation
440
+ class << self
441
+ attr_accessor :fault
442
+
443
+ def selected?(command)
444
+ return false unless fault && command.execution_id == fault.fetch(:execution_id)
445
+
446
+ view = command.terminal_view
447
+ error = view.callback_failure&.to_stream_callback_error || view.source_error ||
448
+ view.block_error || view.invocation_error
449
+ case fault.fetch(:boundary)
450
+ when :coordination_wait then error.is_a?(Phronomy::ExecutionRehydrationRequiredError)
451
+ when :approval_wait then !error && view.phase == :suspended
452
+ when :terminal then !error && !view.rejected && !view.handoff && view.phase != :suspended
453
+ else false
454
+ end
455
+ end
456
+
457
+ def context = Thread.current[:g3i_outcome_fault]
458
+
459
+ def count(key)
460
+ current = context
461
+ current[key] += 1 if current
462
+ end
463
+
464
+ def around_write(site)
465
+ current = context
466
+ return yield unless current && current[:armed] && current.fetch(:site) == site
467
+
468
+ current[:armed] = false
469
+ current[:hits] += 1
470
+ current[:hit_site] = site
471
+ raise IOError, "Injected physical #{site} failure before write" if current.fetch(:mode) == :before
472
+
473
+ value = yield
474
+ raise IOError, "Injected physical #{site} failure after write" if current.fetch(:mode) == :after
475
+
476
+ value
477
+ end
478
+
479
+ def report
480
+ return {enabled: false} unless fault
481
+
482
+ fault.reject { |key, _| %i[execution_id armed].include?(key) }
483
+ end
484
+ end
485
+ end
486
+
487
+ module G3iOutcomeFaultScope
488
+ def commit_outcome(command, **options)
489
+ previous = Thread.current[:g3i_outcome_fault]
490
+ current = G3iOutcomeInstrumentation.selected?(command) ? G3iOutcomeInstrumentation.fault : nil
491
+ Thread.current[:g3i_outcome_fault] = current
492
+ G3iOutcomeInstrumentation.count(:committer_calls)
493
+ super
494
+ ensure
495
+ Thread.current[:g3i_outcome_fault] = previous
496
+ end
497
+ end
498
+
499
+ module G3iPhysicalContentFault
500
+ def put(bytes, **options)
501
+ current = G3iOutcomeInstrumentation.context
502
+ return super unless current
503
+
504
+ value = begin
505
+ JSON.parse(bytes)
506
+ rescue JSON::ParserError
507
+ nil
508
+ end
509
+ site = value.is_a?(Hash) && value.key?("children") && value.key?("cancel_requested") ? :native_content : :agent_content
510
+ G3iOutcomeInstrumentation.around_write(site) { super }
511
+ end
512
+ end
513
+
514
+ module G3iRecoveryWorkScope
515
+ private
516
+
517
+ def submit_recovery_worker(id, &work)
518
+ current = G3iOutcomeInstrumentation.fault
519
+ selected = current && current.fetch(:execution_id) == execution_id
520
+ super(id) do
521
+ previous = Thread.current[:g3i_outcome_fault]
522
+ Thread.current[:g3i_outcome_fault] = selected ? current : nil
523
+ begin
524
+ work.call
525
+ ensure
526
+ Thread.current[:g3i_outcome_fault] = previous
527
+ end
528
+ end
529
+ end
530
+ end
531
+
532
+ module G3iPhysicalJournalFault
533
+ def append(*args, **options)
534
+ G3iOutcomeInstrumentation.around_write(:journal) { super }
535
+ end
536
+ end
537
+
538
+ module G3iPhysicalExecutionFault
539
+ def save(*args, **options)
540
+ G3iOutcomeInstrumentation.around_write(:execution) { super }
541
+ end
542
+ end
543
+
544
+ module G3iPhysicalRootFault
545
+ def save(*args, **options)
546
+ G3iOutcomeInstrumentation.around_write(:root) { super }
547
+ end
548
+ end
549
+
550
+ module G3iEncoderCounter
551
+ def encode(*args, **options)
552
+ G3iOutcomeInstrumentation.count(:encoder_calls)
553
+ super
554
+ end
555
+ end
556
+
557
+ module G3iParticipantCounter
558
+ def commit(*args, **options)
559
+ G3iOutcomeInstrumentation.count(:participant_calls)
560
+ super
561
+ end
562
+ end
563
+
564
+ module G3iOutputValidationCounter
565
+ def validate(*args, **options)
566
+ G3iOutcomeInstrumentation.count(:output_validation_calls)
567
+ super
568
+ end
569
+ end
570
+
571
+ Phronomy::Agent::ExecutionOutcomeCommitter.prepend(G3iOutcomeFaultScope)
572
+ Phronomy::Agent::OutcomeRecoveryOperation.prepend(G3iRecoveryWorkScope)
573
+ Phronomy::ContentStore::StoredContents.prepend(G3iPhysicalContentFault)
574
+ Phronomy::Agent::Persistence::JournalRepository.prepend(G3iPhysicalJournalFault)
575
+ Phronomy::Agent::Persistence::ExecutionRepository.prepend(G3iPhysicalExecutionFault)
576
+ Phronomy::Agent::Persistence::AgentRepository.prepend(G3iPhysicalRootFault)
577
+ Phronomy::Agent::RuntimeRecordEncoder.singleton_class.prepend(G3iEncoderCounter)
578
+ Phronomy::MultiAgent::DurableSubagentCoordinator.prepend(G3iParticipantCounter)
579
+ Phronomy::Agent::OutputContract.prepend(G3iOutputValidationCounter)
580
+
581
+ def parent_storage_fault(boundary:, site:, mode:)
582
+ raise ArgumentError, "Unsupported outcome boundary" unless %i[terminal coordination_wait approval_wait].include?(boundary)
583
+ raise ArgumentError, "Unsupported physical write" unless %i[native_content agent_content journal execution root].include?(site)
584
+ raise ArgumentError, "Unsupported write failure" unless %i[before after].include?(mode)
585
+
586
+ lambda do |_store, execution_id|
587
+ G3iOutcomeInstrumentation.fault = {
588
+ boundary: boundary, site: site, mode: mode, execution_id: execution_id,
589
+ armed: true, hits: 0, committer_calls: 0, encoder_calls: 0,
590
+ participant_calls: 0, output_validation_calls: 0
591
+ }
592
+ end
593
+ end
594
+
595
+ ```
596
+ <!-- /g3i-code:fault-fixture -->
597
+
598
+ ## Shared driver and visible cleanup
599
+
600
+ The driver chooses the normal or fault scenario, reports durable status and retained responsibility, and executes the same explicit Runtime cleanup in both versions. It is a one-shot demonstration, not a process-loss recovery service. A cleanup failure is reported rather than treated as successful release.
601
+
602
+ For example, with retries disabled a recovered pre-state remains pending and can prevent complete shutdown cleanup. An actual service must keep the returned capability and original owner alive; ending this demonstration process does not establish that the unfinished job was safely transferred or recovered.
603
+
604
+ <!-- g3i-code:shared-driver -->
605
+ ```ruby
606
+ # A running service keeps the returned parent, capability and receipt when
607
+ # recovery is pending. This one-shot demonstration reports that state and its
608
+ # cleanup result before the process ends; it is not a crash recovery service.
609
+ def run_report_example(scenario:, boundary: :terminal, site: :native_content, mode: :before,
610
+ retry_confirmed_pre: false, approve_after_restore: false)
611
+ raise ArgumentError, "Unknown report scenario" unless %i[normal recovery].include?(scenario)
612
+ begin
613
+ value = if scenario == :normal
614
+ run_report
615
+ else
616
+ run_report_with_recovery(fault: parent_storage_fault(boundary: boundary, site: site, mode: mode),
617
+ retry_confirmed_pre: retry_confirmed_pre, approve_after_restore: approve_after_restore)
618
+ end
619
+ if %i[recovery_pending approval_wait].include?(value[:state])
620
+ receipt = value.fetch(:receipt)
621
+ report = {state: value.fetch(:state), outcome: receipt.outcome,
622
+ application_state: receipt.application_state,
623
+ saved_outcome: (receipt.saved_outcome if receipt.respond_to?(:saved_outcome)),
624
+ ownership_state: (receipt.ownership_state if receipt.respond_to?(:ownership_state)),
625
+ continuation_state: (receipt.continuation_state if receipt.respond_to?(:continuation_state)),
626
+ provider_calls: value.fetch(:provider_calls),
627
+ durable_status: value.fetch(:stores).agent.executions.load(value.fetch(:execution_id)).status,
628
+ review_effects: G3iReviewTool.effects.dup, publication_effects: G3iPublishTool.effects.dup}
629
+ else
630
+ report = value
631
+ end
632
+ ensure
633
+ Phronomy::Runtime.instance.shutdown(timeout: 0.03, cancel_grace: 0.2)
634
+ begin
635
+ Phronomy.reset_runtime!
636
+ cleanup_incomplete = false
637
+ rescue Phronomy::RuntimeShutdownError
638
+ cleanup_incomplete = true
639
+ end
640
+ end
641
+ report.merge(cleanup_incomplete: cleanup_incomplete, fault: G3iOutcomeInstrumentation.report)
642
+ end
643
+
644
+ if $PROGRAM_NAME == __FILE__
645
+ puts JSON.pretty_generate(run_report_example(
646
+ scenario: ENV.fetch("G3I_SCENARIO", "normal").to_sym,
647
+ boundary: ENV.fetch("G3I_BOUNDARY", "terminal").to_sym,
648
+ site: ENV.fetch("G3I_SITE", "native_content").to_sym,
649
+ mode: ENV.fetch("G3I_MODE", "before").to_sym,
650
+ retry_confirmed_pre: ENV["G3I_RETRY_CAPTURED_OUTCOME"] == "true",
651
+ approve_after_restore: ENV["G3I_APPROVE_RESTORED_WAIT"] == "true"
652
+ ))
653
+ end
654
+ ```
655
+ <!-- /g3i-code:shared-driver -->
656
+
657
+ Save the assembled file as `native_outcome_report.rb` and execute it from the selected checkout:
658
+
659
+ ```sh
660
+ bundle exec ruby -Ilib /absolute/path/native_outcome_report.rb
661
+ G3I_SCENARIO=recovery G3I_BOUNDARY=terminal G3I_SITE=native_content G3I_MODE=before \
662
+ G3I_RETRY_CAPTURED_OUTCOME=true G3I_APPROVE_RESTORED_WAIT=true \
663
+ bundle exec ruby -Ilib /absolute/path/native_outcome_report.rb
664
+ G3I_SCENARIO=recovery G3I_BOUNDARY=approval_wait G3I_SITE=agent_content G3I_MODE=before \
665
+ bundle exec ruby -Ilib /absolute/path/native_outcome_report.rb
666
+ ```
667
+
668
+ The two environment policy switches default to false. The second command explicitly permits both captured-write retry and a new approval after restoration. The third command permits neither; pending responsibility is an intended observable result, not a completed report.
669
+
670
+ ## State model and model-checking boundary
671
+
672
+ The preparation prefix extends the existing native parent outcome/approval recovery model. It changes how complete evidence becomes available before the existing recovery protocol begins. It does not merge the parent, child and client-observer state machines into one execution state.
673
+
674
+ For example, proof construction may fail while complete raw input survives and no write has begun. After the original worker physically settles, read-only materialization can restore the evidence needed to classify pre-state. If the encoder failed before complete capture, the prefix instead retains an opaque failure with no generic replay transition.
675
+
676
+ ![Native outcome preparation prefix](../../spec/models/native_parent_outcome_recovery/preparation-prefix.svg)
677
+
678
+ The [model README](../../spec/models/native_parent_outcome_recovery/README.md) gives the independent parent outcome, parent approval decision, child and observer views and the implementation mapping. The prefix checks complete capture before write, retained identity, read-only and physically settled materialization, opaque-preparation non-replay, ownership and conditional progress.
679
+
680
+ | Checked family | Configurations | Required outcome |
681
+ | --- | ---: | --- |
682
+ | Safety and conditional progress properties | 66 | Selected properties hold under stated bounds and premises. |
683
+ | Deliberate safety mutations | 48 | The named safety violation is detected. |
684
+ | Deliberate progress mutations | 2 | The expected temporal counterexample is detected. |
685
+ | Missing-premise cases | 10 | The specified safety or temporal counterexample is detected. |
686
+ | Reachability witnesses | 13 | The intended state is reachable, detected by the negated witness invariant. |
687
+ | Total | 139 | Every result matches its declared expectation. |
688
+
689
+ All 139 configurations passed their declared expectations. The original 99 scenarios, properties and legacy defaults were preserved; 40 configurations add 21 property checks, ten mutations, four missing-premise cases and five witnesses. These are configuration counts, not coverage percentages or independent proofs of the Ruby implementation. This remains one model family.
690
+
691
+ The finite bounds are one parent operation, one representative child relationship, three management attempts, two observers and one relevant external change. Atomic authoritative storage, existing-root guards, original-owner availability and physical settlement remain explicit premises. Conditional progress additionally requires complete preparation, readable storage, an eligible caller, explicit retry where needed, publication/cleanup availability and materializable proof. There is no promise of progress from arbitrary incomplete preparation, future approval, child completion or later parent resume.
692
+
693
+ ## Validation evidence and remaining obligations
694
+
695
+ Application evidence, finite protocol checks and implementation regression tests answer different questions. The complete before/after source permits ordinary workflow equivalence and intentional failure changes to be checked separately. Source-file hashes identify the tested implementation; a baseline HEAD value alone cannot identify an uncommitted candidate.
696
+
697
+ For example, the baseline matrix reproduces unavailable recovery for twenty-two selected storage faults. The candidate recovers those same twenty-two faults with the original business outputs and effect counts, and separately preserves three pending states when application policy declines retry. The application has no output schema, so its zero validator count does not replace schema-bearing implementation tests.
698
+
699
+ | Evidence | Verified result | Limit |
700
+ | --- | --- | --- |
701
+ | Applied G3h application matrix | 23 of 23 expected results: one normal plus twenty-two selected physical-write faults. | Characterization of the selected fault sites, not all methods or all Stores. |
702
+ | Candidate application matrix | 26 of 26 expected results: identical normal report, twenty-two physical-write recoveries and three explicit-policy holds. | Actual Runtime and in-memory transaction behavior with an offline Provider; no production backend or live LLM. |
703
+ | Source provenance | All 406 baseline library Ruby files match their exact Git blobs. All 407 candidate library Ruby files match the recorded candidate digests; all per-case maps agree. | The tested candidate is identified by these digests, not by the unchanged baseline HEAD. |
704
+ | Complete example source | Eight complete units match the application source; both before/after columns are identical and both assembled files pass Ruby syntax checks. | Executable example coverage remains distinct from private preparation and backend acceptance. |
705
+ | Combined focused implementation regression | 73 examples, zero failures and zero pending, including the fourteen Runtime examples below. | Terminal evidence, native parent outcome/dispatch recovery, custody, write-plan and actual-Runtime coverage. |
706
+ | Independent actual-Runtime acceptance | 14 examples, zero failures; included in the combined total above. | Includes real output-schema validation once, physical overlap, a cancelled coalesced observer, proof/readback failure, conflicting state, retention ordering and revoked child custody; uses in-memory Persistence. |
707
+ | Hosted child integration | 15 examples, zero failures. | Native hosted-child lifecycle and outcome-recovery compatibility. |
708
+ | Native outcome model | 139 of 139 expected results, including deliberate negative cases. | Bounded protocol abstraction, not a refinement proof of Ruby or a backend conformance certificate. |
709
+ | Complete-document English check | One file scanned, zero findings and zero errors. | Language validation is separate from behavioral acceptance. |
710
+
711
+ Repository-wide regression, final source manifests and Contract dependency comparison are recorded with the delivery acceptance evidence. This document does not infer those results from the focused suites or the finite model.
712
+
713
+ The complete-input boundary leaves a real residual in completion group 1: arbitrary encoder, conversion, diagnostic or input-materialization failure before complete capture still has no supported general non-replaying resolution or termination path. Holding that owner safely is not equivalent to resolving it. A later change must either define such a resolution policy or justify a narrower repeatable preparation contract and test it.
714
+
715
+ Handoff routing, arbitrary custom participants, stopped-Runtime recovery, process-loss takeover and an absent-child distributed fence remain outside this increment. Native staging does not prove external Store atomicity or make unchanged storage a license to repeat user code. No additional public preparation method, approval decision retry, business retry or hidden automatic cleanup is introduced.