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
@@ -126,6 +126,7 @@ module Phronomy
126
126
  # @api public
127
127
  def invoke(team_input, config: {})
128
128
  with_admission do
129
+ reject_other_pending_cancellation!
129
130
  execution = admit(team_input.to_s, config)
130
131
  run(execution.team_execution_id, config)
131
132
  end
@@ -135,6 +136,7 @@ module Phronomy
135
136
  # @api public
136
137
  def stream(team_input, config: {}, &block)
137
138
  with_admission do
139
+ reject_other_pending_cancellation!
138
140
  execution = admit(team_input.to_s, config)
139
141
  run(execution.team_execution_id, config, &block)
140
142
  end
@@ -163,12 +165,7 @@ module Phronomy
163
165
  def cancel(team_execution_id)
164
166
  assert_caller!
165
167
  id = team_execution_id.to_s
166
- update(id) do |current, _tx|
167
- next current unless current.active?
168
- current.with(metadata: current.metadata.merge("cancel_requested" => true))
169
- end
170
- token = @tokens_mutex.synchronize { @tokens[id] }
171
- token&.cancel!
168
+ apply_cancellation(id)
172
169
  result(id)
173
170
  end
174
171
 
@@ -177,7 +174,8 @@ module Phronomy
177
174
  def initialize(id, store, metadata, listener, environment, create:)
178
175
  @team_id, @persistence, @listener, @environment = id, store, listener, environment
179
176
  @admissions = @environment.admissions
180
- @tokens_mutex, @tokens = Mutex.new, {}
177
+ @cancellation_mutex = Mutex.new
178
+ @cancellation_request = nil
181
179
  @coordinator_classes = {}
182
180
  definition = self.class.team_definition
183
181
  if create
@@ -242,6 +240,13 @@ module Phronomy
242
240
  end
243
241
 
244
242
  def admit(input, config = {})
243
+ context = nil
244
+ if config.key?(:durable_context)
245
+ unless config[:durable_context].is_a?(Hash)
246
+ raise ArgumentError, "config[:durable_context] must be a canonical JSON-compatible Hash"
247
+ end
248
+ context = Phronomy::CanonicalJSON.load(Phronomy::CanonicalJSON.dump(config.fetch(:durable_context)))
249
+ end
245
250
  definition = definition_snapshot
246
251
  id = SecureRandom.uuid
247
252
  now = Time.now.utc.iso8601(6)
@@ -256,7 +261,7 @@ module Phronomy
256
261
  workers: Array.new(self.class._pool_size) { |i| {"index" => i, "agent_id" => SecureRandom.uuid} },
257
262
  tasks: [], assignments: [], result_ref: nil, error_ref: nil, created_at: now, updated_at: now,
258
263
  metadata: {"definition" => definition, "operations" => {}, "cancel_requested" => false,
259
- "durable_context_ref" => config.key?(:durable_context) ? tx.contents.put_json(config.fetch(:durable_context)) : nil})
264
+ "durable_context_ref" => config.key?(:durable_context) ? tx.contents.put_json(context) : nil})
260
265
  tx.team_executions.create_active(intended)
261
266
  tx.teams.save(team_id, expected_revision: root.team_revision, root: root.with(lifecycle_status: "active"))
262
267
  end
@@ -279,6 +284,7 @@ module Phronomy
279
284
  begin
280
285
  intended = nil
281
286
  persistence.transaction do |tx, scope|
287
+ tx.guard_team!(team_id)
282
288
  current = tx.team_executions.load(id)
283
289
  raise Phronomy::Persistence::StateConflictError, "Team execution owner mismatch" unless current.team_id == team_id
284
290
  intended = yield(current, tx, scope)
@@ -301,27 +307,32 @@ module Phronomy
301
307
  end
302
308
 
303
309
  def run(id, config)
310
+ reject_other_pending_cancellation!(id)
304
311
  current = read_execution(id)
305
- return terminal_value(current) if current.terminal?
312
+ request = cancellation_request(id)
313
+ observations = request.observations
314
+ return terminal_value(current, observations) if current.terminal?
306
315
  unless current.metadata.fetch("definition") == definition_snapshot
307
316
  raise Phronomy::ConfigurationError, "Team execution #{id} pool/definition mismatch"
308
317
  end
309
- token = Phronomy::Concurrency::CancellationToken.new
310
- @tokens_mutex.synchronize { @tokens[id] = token }
318
+ token = request.token
311
319
  cancellation_subscriptions = Phronomy::Concurrency::ResultSubscriptions.new
312
- callback = proc { @environment.submit(on_full: :raise) { cancel(id) } }
313
- cancellation_subscriptions.explicit_cancellation(config[:cancellation_token], &callback)
314
- token.cancel! if current.metadata["cancel_requested"]
320
+ registration = nil
315
321
  begin
322
+ registration = request.attach
323
+ callback = proc { request.request(registration) }
324
+ cancellation_subscriptions.explicit_cancellation(config[:cancellation_token], &callback)
325
+ request.confirm(cancel: true) if current.metadata["cancel_requested"]
316
326
  loop do
327
+ deliver_cancellation(request)
317
328
  current = read_execution(id)
318
- return terminal_value(current) if current.terminal?
329
+ return terminal_value(current, observations) if current.terminal?
319
330
  token.cancel! if cancellation_requested?(current)
320
331
  action, subject = next_run_action(current)
321
332
  case action
322
333
  when :coordinator
323
334
  outcome = run_child(current, current.coordinator, coordinator_class(id),
324
- persistence.contents.fetch_text(current.input_ref), "coordinator", config, token)
335
+ persistence.contents.fetch_text(current.input_ref), "coordinator", config, token, observations, request)
325
336
  update(id) do |fresh, _tx|
326
337
  fresh.with(phase: "workers", coordinator: fresh.coordinator.merge(
327
338
  "state" => outcome[:status].to_s, "result_ref" => outcome[:result_ref], "error_ref" => outcome[:error_ref]
@@ -333,46 +344,56 @@ module Phronomy
333
344
  worker = current.workers.fetch(unfinished.fetch("worker"))
334
345
  task = current.tasks.find { |item| item.fetch("id") == unfinished.fetch("task_id") }
335
346
  outcome = run_child(current, worker.merge("execution_id" => unfinished.fetch("execution_id")),
336
- self.class._worker_agent, task.fetch("description"), unfinished.fetch("task_id"), config, token)
347
+ self.class._worker_agent, task.fetch("description"), unfinished.fetch("task_id"), config, token, observations, request)
337
348
  saved = record_assignment(id, unfinished, outcome)
338
349
  entry = assignment_values(saved).find { |item| item.fetch(:task).fetch(:id) == task.fetch("id") }
339
350
  yield entry.merge(type: outcome[:error] ? :task_failed : :task_completed) if block_given?
340
351
  next
341
352
  when :failed
342
- return terminal_value(finish_error(id, persistence.contents.fetch_json(subject.fetch("error_ref"))))
353
+ return terminal_value(finish_error(id, persistence.contents.fetch_json(subject.fetch("error_ref"))), observations)
343
354
  when :cancelled
344
- return terminal_value(finish_error(id, {"class" => "Phronomy::CancellationError", "message" => "Team run cancelled"}, status: "cancelled"))
355
+ return terminal_value(finish_error(id, {"class" => "Phronomy::CancellationError", "message" => "Team run cancelled"}, status: "cancelled"), observations)
345
356
  when :reserve
346
357
  reserve_assignment(current, subject)
347
358
  next
348
359
  end
349
360
  values = assignment_values(current)
350
361
  aggregate = self.class._aggregator
362
+ next if deliver_cancellation(request)
351
363
  begin
352
364
  output = Phronomy::Values::Serializable.convert(aggregate ? aggregate.call(values) : values, unsupported_message: "Team result is not canonically serializable")
353
365
  Phronomy::CanonicalJSON.dump(output)
354
366
  rescue => error
355
- return terminal_value(finish_error(id, Phronomy::Error.diagnostic(error)))
367
+ return terminal_value(finish_error(id, Phronomy::Error.diagnostic(error)), observations)
356
368
  end
369
+ next if deliver_cancellation(request)
357
370
  # Aggregate may be replayed only until the canonical outcome commits.
358
371
  completed = update(id) do |fresh, tx, scope|
359
372
  next fresh if fresh.terminal? || fresh.metadata["cancel_requested"]
360
373
  fresh.with(status: "completed", phase: "completed", result_ref: tx.contents.put_json(output))
361
374
  end
362
375
  next if completed.active?
363
- return terminal_value(completed)
376
+ return terminal_value(completed, observations)
364
377
  end
378
+ rescue Phronomy::Agent::ExecutionRejectedError => error
379
+ terminal_value(finish_rejected_child(id, error), observations)
365
380
  rescue Phronomy::CancellationError
366
381
  # An absent reserved child is not started just to cancel it. Keep its
367
382
  # identity in the terminal Team record for discovery.
368
383
  if (failed = failed_child(read_execution(id)))
369
- terminal_value(finish_error(id, persistence.contents.fetch_json(failed.fetch("error_ref"))))
384
+ terminal_value(finish_error(id, persistence.contents.fetch_json(failed.fetch("error_ref"))), observations)
370
385
  else
371
- terminal_value(finish_error(id, {"class" => "Phronomy::CancellationError", "message" => "Team run cancelled"}, status: "cancelled"))
386
+ terminal_value(finish_error(id, {"class" => "Phronomy::CancellationError", "message" => "Team run cancelled"}, status: "cancelled"), observations)
372
387
  end
373
388
  ensure
389
+ failure = $!
374
390
  cancellation_subscriptions.close
375
- @tokens_mutex.synchronize { @tokens.delete(id) }
391
+ pending = request.detach(registration) if registration
392
+ if pending && request.pending? && (!failure || failure.is_a?(StandardError)) &&
393
+ !failure.is_a?(TeamCancellationDeliveryError)
394
+ request.failed(failure) if failure
395
+ raise_cancellation_delivery_error(request, failure || request.failure)
396
+ end
376
397
  end
377
398
  end
378
399
 
@@ -405,7 +426,57 @@ module Phronomy
405
426
  execution.assignments.any? { |entry| entry.fetch("state") == "cancelled" }
406
427
  end
407
428
 
408
- def run_child(current, slot, klass, input, purpose, config, token)
429
+ def cancellation_request(id)
430
+ @cancellation_mutex.synchronize do
431
+ unless @cancellation_request&.team_execution_id == id
432
+ @cancellation_request = TeamCancellationRequest.new(team_execution_id: id, admissions: @admissions)
433
+ end
434
+ @cancellation_request
435
+ end
436
+ end
437
+
438
+ def matching_cancellation_request(id)
439
+ @cancellation_mutex.synchronize do
440
+ @cancellation_request if @cancellation_request&.team_execution_id == id
441
+ end
442
+ end
443
+
444
+ def reject_other_pending_cancellation!(id = nil)
445
+ request = @cancellation_mutex.synchronize { @cancellation_request }
446
+ return unless request&.pending? && request.team_execution_id != id
447
+
448
+ raise_cancellation_delivery_error(request, request.failure)
449
+ end
450
+
451
+ def raise_cancellation_delivery_error(request, cause)
452
+ raise TeamCancellationDeliveryError.new(team_id: team_id,
453
+ team_execution_id: request.team_execution_id), cause: cause
454
+ end
455
+
456
+ def apply_cancellation(id)
457
+ confirmed = update(id) do |current, _tx|
458
+ next current unless current.active?
459
+ current.with(metadata: current.metadata.merge("cancel_requested" => true))
460
+ end
461
+ # Confirm before a public result query: its read failure cannot undo the
462
+ # authoritative cancellation write or retain a discharged local request.
463
+ matching_cancellation_request(id)&.confirm(cancel: true, terminal: confirmed.terminal?)
464
+ confirmed
465
+ end
466
+
467
+ def deliver_cancellation(request)
468
+ return unless request.pending?
469
+
470
+ apply_cancellation(request.team_execution_id)
471
+ rescue => error
472
+ return unless request.pending?
473
+
474
+ request.failed(error)
475
+ raise_cancellation_delivery_error(request, error)
476
+ end
477
+
478
+ def run_child(current, slot, klass, input, purpose, config, token, observations, request)
479
+ deliver_cancellation(request)
409
480
  id = slot.fetch("agent_id")
410
481
  child = klass.get(id)
411
482
  unless child
@@ -425,7 +496,9 @@ module Phronomy
425
496
  if (context_ref = current.metadata["durable_context_ref"])
426
497
  child_config = child_config.merge(durable_context: persistence.contents.fetch_json(context_ref))
427
498
  end
428
- child.start_reserved_async(reservation: Phronomy::Agent::ReservedExecution.new(agent_id: id, execution_id: slot.fetch("execution_id"), correlation: child_config.fetch(:phronomy_reservation)), input: input, config: child_config).wait_result
499
+ operation = child.start_reserved_async(reservation: Phronomy::Agent::ReservedExecution.new(agent_id: id, execution_id: slot.fetch("execution_id"), correlation: child_config.fetch(:phronomy_reservation)), input: input, config: child_config)
500
+ (observations[id] ||= []) << operation
501
+ request.wait(operation) { deliver_cancellation(request) }
429
502
  end
430
503
 
431
504
  def reserve_assignment(current, task)
@@ -472,13 +545,87 @@ module Phronomy
472
545
  end
473
546
  end
474
547
 
475
- def terminal_value(execution)
548
+ # The Agent owns rejection classification. Team owns the parent outcome.
549
+ # Its admission guard also fences a competing reserved child start, so an
550
+ # absence observation and the Team terminal write share one decision.
551
+ def finish_rejected_child(id, error)
552
+ update(id) do |fresh, tx, scope|
553
+ next fresh if fresh.terminal?
554
+ slots = [fresh.coordinator] + fresh.assignments.map do |assignment|
555
+ fresh.workers.fetch(assignment.fetch("worker")).merge("execution_id" => assignment.fetch("execution_id"))
556
+ end
557
+ unless slots.any? { |slot| slot.fetch("agent_id") == error.agent_id && slot.fetch("execution_id") == error.execution_id }
558
+ raise Phronomy::Persistence::StateConflictError, "Rejected child does not belong to Team execution #{id}"
559
+ end
560
+ observed = persistence.agent_store.observe_execution(agent_id: error.agent_id,
561
+ execution_id: error.execution_id, scope: scope)
562
+ unless observed.absent?
563
+ raise Phronomy::ExecutionRehydrationRequiredError,
564
+ "Rejected start overlaps an existing child execution #{error.execution_id}; resume the Team"
565
+ end
566
+ fresh.with(status: "failed", phase: "failed", error_ref: tx.contents.put_json(Phronomy::Error.diagnostic(error)))
567
+ end
568
+ end
569
+
570
+ def terminal_value(execution, observations)
571
+ matching_cancellation_request(execution.team_execution_id)&.terminal
476
572
  raise Phronomy::CancellationError, "Team run #{execution.team_execution_id} cancelled" if execution.status == "cancelled"
477
573
  if execution.error_ref
478
574
  failure = persistence.contents.fetch_json(execution.error_ref)
479
575
  raise Phronomy::Error.from_diagnostic(failure)
480
576
  end
481
577
  persistence.contents.fetch_json(execution.result_ref)
578
+ ensure
579
+ retire_terminal_children(execution, observations)
580
+ observations.clear if execution.terminal?
581
+ end
582
+
583
+ # A confirmed Team terminal result ends ownership of its execution-only
584
+ # children, not their durable histories. Cleanup cannot replace that result.
585
+ def retire_terminal_children(execution, observations)
586
+ return unless execution.terminal?
587
+
588
+ id = execution.team_execution_id
589
+ @coordinator_classes.delete(id)
590
+ ([execution.coordinator] + execution.workers).map { |slot| slot.fetch("agent_id") }.uniq.each do |agent_id|
591
+ child = begin
592
+ Phronomy::Agent::Base.get(agent_id)
593
+ rescue Phronomy::AgentBusyError
594
+ # Another terminal observer may already have started its release.
595
+ # get only reports an ownership transition, not an active operation.
596
+ next
597
+ end
598
+ next unless child
599
+ unless child.persistence.equal?(persistence.agent_store)
600
+ raise Phronomy::ConfigurationError, "Team child #{agent_id} Persistence mismatch during release"
601
+ end
602
+
603
+ # all_settled observes logical completion. Finalize each observation
604
+ # first so reused workers retain every outstanding physical boundary.
605
+ settled = Array(observations[agent_id]).map do |operation|
606
+ Phronomy::AsyncOperation.finalize(name: "team-child-quiescence",
607
+ cleanup: -> { Phronomy::TaskResult.completed(nil) },
608
+ on_cleanup_error: ->(_value, _primary, error) { error }) { operation }
609
+ end
610
+ Phronomy::AsyncOperation.finalize(name: "team-child-release",
611
+ cleanup: -> { child.unload_async },
612
+ on_cleanup_error: ->(_value, _primary, error) {
613
+ report_child_release_failure(id, agent_id, error)
614
+ error
615
+ }) { Phronomy::TaskResult.all_settled(settled) }
616
+ rescue => error
617
+ report_child_release_failure(id, agent_id, error)
618
+ end
619
+ end
620
+
621
+ def report_child_release_failure(id, agent_id, error)
622
+ message = "[Phronomy] Team child release failed team_id=#{team_id.inspect} team_execution_id=#{id.inspect} agent_id=#{agent_id.inspect}: #{error.class}: #{error.message}"
623
+ logger = Phronomy::RuntimeSettings.current.logger
624
+ logger ? logger.error(message) : warn(message)
625
+ rescue
626
+ # Reporting failure cannot change a committed Team result or a retained
627
+ # Agent owner. A later terminal resume can retry the existing public API.
628
+ nil
482
629
  end
483
630
 
484
631
  def coordinator_class(id)
@@ -18,11 +18,17 @@ module Phronomy
18
18
  # @api public
19
19
  def self.agent_resources = StorageSchema.agent_resources
20
20
 
21
+ # Optional resource for resolving unconfirmed Agent create and purge writes.
22
+ # Drivers must serialize its guards even when an Agent key has no receipt.
23
+ # @return [Storage::Resource]
24
+ # @api public
25
+ def self.identity_receipt_resource = Agent::Persistence::StorageSchema::IDENTITY_RECEIPTS
26
+
21
27
  # An ordinary Agent needs only its own records and content. Do not load or
22
28
  # instantiate Team/Workflow implementations merely to construct an Agent.
23
29
  def self.agent(backend: nil)
24
30
  resources = agent_resources
25
- backend ||= Phronomy::Storage::Backends::InMemory.new(resources: resources)
31
+ backend ||= Phronomy::Storage::Backends::InMemory.new(resources: resources + [identity_receipt_resource])
26
32
  coordinator = Phronomy::Persistence.new(backend: backend)
27
33
  Phronomy::Persistence::StorageBoundary.call do
28
34
  resources.each { |resource| backend.view.public_send(resource.kind, resource) }
@@ -39,8 +45,9 @@ module Phronomy
39
45
  Stores.new(coordinator: coordinator, agent: agent, multi_agent: multi_agent, workflow: workflow)
40
46
  end
41
47
 
42
- def self.in_memory
43
- build(backend: Phronomy::Storage::Backends::InMemory.new(resources: resources))
48
+ def self.in_memory(identity_receipts: true)
49
+ catalog = identity_receipts ? resources + [identity_receipt_resource] : resources
50
+ build(backend: Phronomy::Storage::Backends::InMemory.new(resources: catalog))
44
51
  end
45
52
  end
46
53
  end
@@ -3,3 +3,21 @@
3
3
  Phronomy::Execution.backend_provider = -> { Phronomy::ExecutionBinding }
4
4
 
5
5
  Phronomy::ExecutionReceiver.install_binding(-> { Phronomy::ExecutionReceiverBinding })
6
+
7
+ # Bind cleanup before discovery. Keep SDK code lazy and pin submission and
8
+ # shutdown custody to the same Runtime even after the default changes.
9
+ Phronomy::Tools::McpTransportRegistry.provider = lambda {
10
+ runtime = Phronomy::Runtime.instance
11
+ key = Phronomy::Tools::McpTransportRegistry
12
+ runtime.__shutdown_participant(key: key) || runtime.__register_shutdown_participant(
13
+ key: key, participant: key.new { |&operation|
14
+ Phronomy::Execution.submit(runtime: runtime, pool_name: :mcp_cleanup,
15
+ size: 2, queue_size: 100, on_full: :raise, &operation)
16
+ }
17
+ )
18
+ }
19
+ Phronomy::Tools::McpTransportRegistry.lookup = lambda { |runtime|
20
+ (runtime || Phronomy::Runtime.__default_if_initialized)&.__shutdown_participant(
21
+ key: Phronomy::Tools::McpTransportRegistry
22
+ )
23
+ }
@@ -42,7 +42,9 @@ module Phronomy
42
42
  end
43
43
 
44
44
  def lock_guard(state, resource, key:)
45
- raise NotFoundError, "guard record not found: #{resource.id}/#{key}" unless bucket(state, resource).key?(key)
45
+ unless resource.guard_missing? || bucket(state, resource).key?(key)
46
+ raise NotFoundError, "guard record not found: #{resource.id}/#{key}"
47
+ end
46
48
  true
47
49
  end
48
50
 
@@ -8,6 +8,10 @@ module Phronomy
8
8
  TYPES = [:string, :integer, :boolean, :nullable_string, :nullable_integer, :nullable_boolean].freeze
9
9
  attr_reader :id, :kind, :attributes, :immutable_attributes, :indexes, :unique, :guard
10
10
 
11
+ # A key remains lockable while its record is absent.
12
+ # @api public
13
+ def guard_missing? = @guard_missing
14
+
11
15
  # Normalize a schema object or ID before constructing guards and conditions.
12
16
  # @api private
13
17
  def self.normalize_reference(value)
@@ -15,7 +19,7 @@ module Phronomy
15
19
  end
16
20
 
17
21
  # @api public
18
- def initialize(id:, kind:, attributes: {}, immutable_attributes: [], indexes: {}, unique: [], guard: nil)
22
+ def initialize(id:, kind:, attributes: {}, immutable_attributes: [], indexes: {}, unique: [], guard: nil, guard_missing: false)
19
23
  @id = Validation.key(id)
20
24
  @kind = kind
21
25
  @attributes = Validation.immutable(attributes)
@@ -23,6 +27,11 @@ module Phronomy
23
27
  @indexes = Validation.immutable(indexes)
24
28
  @unique = Validation.immutable(unique)
25
29
  @guard = Validation.immutable(guard)
30
+ valid_key_guard = guard_missing == false || (kind == :records && guard_missing == true)
31
+ unless valid_key_guard
32
+ raise ArgumentError, "only record resources can allow guards on missing keys"
33
+ end
34
+ @guard_missing = guard_missing
26
35
  validate_shape!
27
36
  validate_indexes!
28
37
  validate_guard!
@@ -66,7 +66,13 @@ module Phronomy
66
66
  unless config.nil? || config.is_a?(Hash)
67
67
  raise ArgumentError, "Agent Tool config must be a Hash"
68
68
  end
69
- task_config = (config || {}).dup
69
+ # A private child owns a new execution. Keep application context and
70
+ # shared controls, not the parent's reservation, observers or runtime
71
+ # wiring. The existing hook deadline is a shared time budget.
72
+ task_config = (config || {}).reject do |key, _value|
73
+ name = key.to_s
74
+ name == "execution_id" || (name.start_with?("phronomy_") && name != "phronomy_timeout_deadline")
75
+ end
70
76
  if cancellation_token && !task_config[:cancellation_token]
71
77
  task_config[:cancellation_token] = cancellation_token
72
78
  end