phronomy 0.35.1 → 0.35.3

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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 2a4e1f6acc08dbb7935eda1e96414206533947e2f058f8bcf5c42edc09476785
4
- data.tar.gz: 6c12e888f0f332c4528a0f7e836549cf9fd0972ba9dbe8e504e6b013f53326e8
3
+ metadata.gz: b18d52aafcaa833cf4ef1bd8d5f937088ca7f51a3dbc46fcd191580817885dfa
4
+ data.tar.gz: 6caea92395e99686a7ecbd051edb36aa48d5ee0abaf25e99f3cc4686ac92aa09
5
5
  SHA512:
6
- metadata.gz: b2c5073c3c843cd35b13af8a6ab4261d3f06fe4a778a4d26515a8ee6e34e529e81098feacb7a73c4f2a9ad8bb5b7c88c825f93b8a8eb166a01638c78ea764b70
7
- data.tar.gz: c454670df102b097412e406422668b0a3055fb6bedb416fac9b1775d4db529973699e5911671afd29dd62862ae1fe2faf4ce8044c8813c0eada5287a47cba9be
6
+ metadata.gz: 237eda3881df9a1b24fbd63a4b980c737acc2739f9006c4ab12030cf3fce3326d801b1c5612f1559b1a1c9dfe1a88d68b3d93bc59b7a3e36cf2db2d558ae0af9
7
+ data.tar.gz: 0c4609068ee6ab89dee9b64ebc53e245cd31c7d39a5d9817722941a25d17bf1fb81d1b82b1f0a54f93aa3ab90f172d6c8107f1f7b66a3898920955c14845aa3f
data/CHANGELOG.md CHANGED
@@ -12,6 +12,63 @@ Release history for 0.14.0 and earlier is archived in
12
12
 
13
13
  ## [Unreleased]
14
14
 
15
+ ## [0.35.3] - 2026-11-19
16
+
17
+ ### Fixed
18
+
19
+ - Allow an already accepted Agent Tool to finish its private child's release
20
+ during graceful Runtime draining. Track that release on the existing Agent
21
+ ownership entry without reopening new admission or adding a cleanup registry.
22
+ A child still awaiting human approval at the finite shutdown deadline leaves
23
+ cleanup incomplete instead of being treated as released.
24
+ - Preserve native subagent registration when `Orchestrator.with_tools` retains
25
+ a child Tool. Tool aliases now remain consistent across durable dispatch,
26
+ replay and hosted approval recovery. Removed Tools lose their registrations;
27
+ ordinary subclass inheritance keeps its existing behavior.
28
+
29
+ ### Compatibility and verification
30
+
31
+ - Public call signatures, dependency requirements and saved representations are
32
+ unchanged. An unresolved private-child approval wait can still leave cleanup
33
+ incomplete at the finite shutdown deadline; the Tool does not automatically
34
+ approve, force-release or recover the child.
35
+ - Candidate-source examples verification passed against the existing
36
+ llama-server with gpt-oss-20b. This does not establish resolution of the
37
+ previously observed PEG-format failure root cause or replace post-release
38
+ verification with the published gem.
39
+
40
+ ## [0.35.2] - 2026-11-18
41
+
42
+ ### Fixed
43
+
44
+ - Release completed member Agents in default SharedState coordination through
45
+ the same lifecycle handling used by custom sharing. Normal approval waits stay
46
+ live; invocation and release failures retain their original causes and the
47
+ member handle when cleanup needs attention.
48
+ - Keep Runtime deadline notifications active while accepted work drains during
49
+ shutdown, including queued Blocking operations and standalone fan-out results.
50
+ A delayed worker result cannot win merely because its timer driver stopped
51
+ before the worker pool drained.
52
+
53
+ ### Changed
54
+
55
+ - Report incomplete Runtime cleanup if the finite shutdown budget expires with
56
+ accepted timer callbacks still pending. No callback fires early to simulate
57
+ cancellation, and no worker thread is forcibly interrupted. Default Runtime
58
+ replacement still requires complete cleanup.
59
+ - Reconcile P5 progress with the published v0.35.0 and examples acceptance, and
60
+ identify the old execution-boundary proposal as historical documentation.
61
+
62
+ ### Compatibility and verification
63
+
64
+ - Public signatures, dependency requirements and current saved formats are
65
+ unchanged. The existing `cleanup_complete?` predicate now remains false when
66
+ the shutdown budget leaves accepted timer callbacks unfinished, so a default
67
+ Runtime cannot be replaced after incomplete cleanup.
68
+ - This core release does not claim new published-gem examples, live LLM or SQL
69
+ acceptance, or resolution of the previously observed LM Studio/gpt-oss
70
+ PEG-format failure root cause. Those checks remain separate follow-up work.
71
+
15
72
  ## [0.35.1] - 2026-11-18
16
73
 
17
74
  ### Fixed
data/README.md CHANGED
@@ -37,7 +37,7 @@ tracking `main` directly.
37
37
 
38
38
  See [Features and Application Programming Interface (API) stability](docs/features.md) for the full feature matrix.
39
39
 
40
- The following table describes the application APIs available in v0.35.1.
40
+ The following table describes the application APIs available in v0.35.3.
41
41
  The public persistence resource catalogs are available starting with v0.35.0.
42
42
  The sharing, Tool composition and Context budgeting operations remain
43
43
  Experimental; their introduction version is shown below.
@@ -59,8 +59,8 @@ the current saved representation.
59
59
  | `PersistenceComposition.resources` and `.agent_resources` | Beta (since v0.35.0) | Supply canonical frozen resource catalogs to an application-selected backend for `.build(backend:)` or `.agent(backend:)`, without creating a backend, stores or Runtime. [Backend catalog](docs/persistence-backends.md#supplying-a-backend-catalog) |
60
60
  | `Persistence::Migration::InitialFormatMigration` | Removed (v0.34.0) | The pre-S3 conversion API is retired without a replacement. Current domain codecs and the separate Unit4 snapshot migration remain. [Legacy-format cleanup](docs/migrations/legacy-format-removal.md) |
61
61
  | `Context::ContextPolicyInput#input_token_limit / #with_input_token_limit` and protected `ContextPolicy#estimate_tokens` | Experimental (since v0.33.0) | Inspect and constrain selection budgets and estimate candidate content through Context-owned operations. [Policy budgeting](docs/context-policy-budgeting.md) |
62
- | `Agent::Base.with_tools(definitions, id:, version:)` | Experimental (since v0.33.0) | Derive an Agent class with a complete replacement Tool map and explicit definition identity while preserving Phronomy authoring settings and filters. [Tool composition](docs/shared-state-sharing.md#deriving-an-agent-with-a-complete-tool-set) |
63
- | `MultiAgent::SharedState.sharing(provider, id:, version:)`, `SharedState::Binding` and `SharedState::MemberLifecycleError` | Experimental (since v0.33.0) | Connect application-owned shared data and Tools to sequential coordination through a synchronous invocation-scoped provider. [Custom sharing contract and example](docs/shared-state-sharing.md) |
62
+ | `Agent::Base.with_tools(definitions, id:, version:)` | Experimental (since v0.33.0) | Derive an Agent class with a complete replacement Tool map and explicit definition identity while preserving Phronomy authoring settings and filters. Orchestrator derivation also preserves native subagent registrations for retained child Tools, including their aliases. [Tool composition](docs/shared-state-sharing.md#deriving-an-agent-with-a-complete-tool-set) |
63
+ | `MultiAgent::SharedState.sharing(provider, id:, version:)`, `SharedState::Binding` and `SharedState::MemberLifecycleError` | Experimental (since v0.33.0) | Sequential coordination releases its terminal member Agents in both default and custom modes; an optional invocation-scoped provider supplies application-owned data and Tools. [Sharing and member lifetime contract](docs/shared-state-sharing.md) |
64
64
  | `Tool::Base#approval_display(arguments:, facts:)` | Beta (since v0.33.0) | The Tool selects the arguments and derived facts a person can see in an approval request. [Approval display](docs/runtime-and-concurrency.md#tool-approval-display) |
65
65
  | `Runtime#shutdown` result predicates `cleanup_complete?` and `clean?` | Beta | Check resource release with `cleanup_complete?`; `clean?` additionally requires a graceful shutdown. The obsolete `success?` alias is removed in v0.34.0. [Cleanup migration](docs/migrations/cleanup-audit.md#runtime-cleanup-completion) |
66
66
  | `Phronomy::EventLoopReentrancyError` | Beta | Raised when a synchronous operation would block the EventLoop control thread. The obsolete `SchedulerReentrancyError` subclass is removed in v0.34.0. [Cleanup migration](docs/migrations/cleanup-audit.md#eventloop-reentrancy-errors) |
data/SECURITY.md CHANGED
@@ -4,7 +4,7 @@
4
4
 
5
5
  | Version | Supported |
6
6
  |---------|-----------|
7
- | 0.35.1 (latest release) | ✅ |
7
+ | 0.35.3 (latest release) | ✅ |
8
8
  | Older versions | ❌ — please upgrade |
9
9
 
10
10
  Only the latest released version of `phronomy` receives security patches. If you
@@ -23,6 +23,27 @@ used merely to wait for the child or its release. The existing Agent release can
23
23
  perform its ordinary asynchronous persistence checks. Records are not purged,
24
24
  and unrelated Agents or shared stores are not shut down.
25
25
 
26
+ ## Graceful Runtime shutdown
27
+
28
+ An accepted private child's final release is part of its existing Agent
29
+ ownership entry. Runtime waits for that release within the drain budget, and
30
+ Agent can transfer the pending release to its ordinary unload transition after
31
+ new admission closes. This adds no separate cleanup registry or application
32
+ lifetime handle. Ordinary application-requested unloads do not gain admission
33
+ during draining.
34
+
35
+ For example, if shutdown begins while an Agent Tool waits for an LLM response,
36
+ a successful response can still finish the child's release and return its normal
37
+ output. Provider failure keeps its original error after release, and cancelling
38
+ only the observer does not abandon physical cleanup. New Agent creation and
39
+ invocation remain rejected once draining starts.
40
+
41
+ The finite drain budget still applies. If a child remains suspended for human
42
+ approval, shutdown reports incomplete cleanup rather than treating the retained
43
+ child as released. The Tool result can remain pending; shutdown does not supply
44
+ approval or promise later finalization after incomplete shutdown. The existing
45
+ incomplete-cleanup rule prevents replacement of that default Runtime.
46
+
26
47
  ## Cancellation and approval
27
48
 
28
49
  Logical result settlement does not prove that physical work has ended. The
@@ -1,7 +1,22 @@
1
- # Execution boundary candidate (unapplied)
1
+ # Execution boundary prototype (historical)
2
2
 
3
- Base: main 653e255a34fe4062d4beca47530e084fdd3a6ba9.
4
- This is an unpublished prototype for source-derived architecture review.
3
+ This document preserves an earlier source-derived design proposal, including
4
+ its original group names and compatibility decisions. It is not a pending
5
+ implementation plan or the authority for the current source layout.
6
+
7
+ For example, the Workflow phase compiler and neutral execution values are
8
+ present in the current implementation, while later refinements changed the
9
+ prototype's grouping and placement. Use [Phronomy Architecture](architecture.md)
10
+ and the current source diagram for the reconciled responsibilities.
11
+
12
+ Original prototype base: main 653e255a34fe4062d4beca47530e084fdd3a6ba9.
13
+ The proposal below is retained as history, not a current public API guide.
14
+
15
+ ## Recorded proposal
16
+
17
+ The prototype separated result values from concrete execution connections.
18
+ For example, Engine and Services could share TaskResult without making those
19
+ values acquire Runtime or invoke operation-submission services.
5
20
 
6
21
  TaskResult, Outcome, result composition, physical completion and ScopeState
7
22
  belong to Execution Results. They depend on Contracts and Common, without
@@ -16,7 +31,11 @@ terminal state. FSMSession retains terminal detection and persistence gating.
16
31
  TerminalDecision is an execution contract, independent of Workflow and FSM
17
32
  state vocabulary.
18
33
 
19
- ## Intentional compatibility changes
34
+ ## Compatibility decisions recorded in the prototype
35
+
36
+ The prototype moved execution-control adaptation out of shared values and
37
+ removed obsolete internal entry points. For example, InvocationContext kept
38
+ the supplied deadline value while the invoking service attached its timer.
20
39
 
21
40
  * InvocationContext#effective_timeout_token and #effective_cancellation_token
22
41
  are removed. Although annotated private, both occurred in the Stable API
@@ -637,9 +637,31 @@ been cancelled or timed out. It does not forcefully interrupt worker threads.
637
637
  See [R8 unit19](architecture/r8-unit19.md) and its
638
638
  [migration notes](migrations/r8-unit19.md) for the shutdown budget and result rules.
639
639
 
640
- `Runtime#shutdown` is terminal for that Runtime. It drains/terminates the
641
- Runtime-owned EventLoop, then closes pools and timers according to the Runtime
642
- shutdown contract.
640
+ `Runtime#shutdown` is terminal for that Runtime. During the drain phase it waits
641
+ for registered owners and pending timer notifications. During the stop phase it
642
+ closes pool admission and waits for workers while EventLoop continues delivering
643
+ existing deadlines. It then stops EventLoop and closes the timer service. Timer
644
+ callbacks continue to run on EventLoop, not on the shutdown caller's thread.
645
+
646
+ For example, a Blocking operation with a 50 ms timeout that takes 200 ms still
647
+ reports `TimeoutError` when shutdown begins immediately after submission, if the
648
+ shutdown budget permits that deadline to be delivered. The worker is allowed to
649
+ finish physically. A queued operation whose timeout settles before it starts is
650
+ skipped, just as during ordinary operation. Standalone fan-out deadlines also
651
+ remain active even when their pending results do not occupy a pool worker.
652
+
653
+ Complete cleanup requires accepted timer notifications to finish or be removed
654
+ by their owners before the timer service closes. If the finite shutdown budget
655
+ expires while notifications remain, Runtime reports incomplete cleanup even
656
+ when no worker thread remains. It does not fire future callbacks early or create
657
+ a background timer service to preserve deadlines after shutdown returns.
658
+
659
+ For example, a notification scheduled far beyond both shutdown phases is not
660
+ executed early merely to empty the timer queue. Discarding that notification at
661
+ closure makes `cleanup_complete?` false and prevents default Runtime replacement.
662
+ Once shutdown returns incomplete, future deadline delivery is not guaranteed;
663
+ the application must not treat that result as completed work or a safe handoff.
664
+ Repeated shutdown retains the original result rather than silently upgrading it.
643
665
 
644
666
  Internal subsystems can register one shutdown participant per Runtime-local key
645
667
  through `Runtime#__register_shutdown_participant`. This is an internal lifecycle
@@ -132,6 +132,18 @@ The original class is unchanged. This explicit factory does not change general
132
132
  Agent subclass inheritance or define copying rules for application-specific
133
133
  class state.
134
134
 
135
+ For an Orchestrator, this explicit factory also preserves native subagent
136
+ registrations for the child Tools kept in the replacement map. Removed child
137
+ Tools lose their registrations, and retained child Tools use their effective
138
+ aliases for durable dispatch, replay and hosted approval recovery. Registration
139
+ settings are independent of the original class. Ordinary subclass inheritance
140
+ still starts with no native subagent registrations.
141
+
142
+ For example, keeping a `dispatch_to_worker` Tool under the alias `consult_worker`
143
+ still runs the registered child through the Orchestrator's coordination Store.
144
+ Replacing that Tool with an unrelated application Tool removes the child
145
+ registration; it does not keep an unreachable coordination entry.
146
+
135
147
  The default findings-store mode now preserves these settings through the same
136
148
  factory. For example, a member configured with `max_iterations 3` and
137
149
  `temperature 0.25` keeps those settings when SharedState adds `read_store` and
@@ -185,12 +197,21 @@ and verifies provider cleanup. It uses the real Tool argument-validation path.
185
197
  It does not exercise the SharedState Agent loop or establish live-model,
186
198
  database or multi-process acceptance.
187
199
 
188
- In custom mode, SharedState releases terminal member instances through the
189
- Agent's public `unload!` operation. A normal Agent approval wait keeps the public
190
- `invoke` call pending. SharedState consequently stays inside the provider's
191
- `open` block and retains its resources; it does not return a suspended result or
192
- close the provider merely because an internal execution reaches an approval
193
- wait. The application remains responsible for answering or cancelling approvals.
200
+ In both default and custom sharing modes, SharedState releases terminal member
201
+ instances through the Agent's public `unload!` operation. It owns the lifetime of
202
+ the members it creates, including successful calls, early coordination stops and
203
+ invocation failures. Releasing a member does not delete its saved history.
204
+
205
+ For example, two members running two cycles create four temporary Agents. Each
206
+ Agent is released after its invocation finishes, while the shared findings stay
207
+ available to later members and the final aggregation. Repeated coordination does
208
+ not accumulate completed member owners in the Runtime.
209
+
210
+ A normal Agent approval wait keeps the public `invoke` call pending. In custom
211
+ mode, SharedState consequently stays inside the provider's `open` block and
212
+ retains its resources; it does not return a suspended result or close the
213
+ provider merely because an internal execution reaches an approval wait. The
214
+ application remains responsible for answering or cancelling approvals.
194
215
 
195
216
  For example, when a member waits for approval of `record_issue`, the board stays
196
217
  open while that invocation waits. An approval allows the Tool and member to
@@ -207,7 +228,8 @@ during the wait; after a public approval response, the Tool writes its record,
207
228
  aggregation runs, the provider closes and the member is released. Fixed
208
229
  responses verify the execution path, not a live model's Tool-selection behavior.
209
230
 
210
- The lifecycle guard also detects a custom `invoke` override that returns a Hash
231
+ In either sharing mode, the lifecycle guard also detects a custom `invoke`
232
+ override that returns a Hash
211
233
  with a suspended status before reaching completion. That exceptional early
212
234
  return raises `SharedState::MemberLifecycleError` with `reason: :suspended` and
213
235
  stops coordination before later members or aggregation. It is not the behavior
@@ -165,6 +165,34 @@ module Phronomy
165
165
  true
166
166
  end
167
167
 
168
+ # A private child already owned by this Runtime must finish its final
169
+ # release before the shutdown participant can become idle. Keep that
170
+ # obligation on the existing owner entry, not in a second registry.
171
+ def expect_unload(agent)
172
+ @mutex.synchronize do
173
+ ensure_running!
174
+ entry = @entries[agent.agent_id]
175
+ unless entry&.state == :live && entry.agent.equal?(agent) && entry.token.nil?
176
+ raise Phronomy::AgentBusyError, "Agent is not available for owned release"
177
+ end
178
+ @entries[agent.agent_id] = Entry.new(state: :live, agent: agent, token: :pending_unload)
179
+ end
180
+ true
181
+ end
182
+
183
+ # A failed finalizer leaves the child with its existing error owner. Never
184
+ # clear an accepted transition or a newer owner while removing the marker.
185
+ def cancel_expected_unload(agent)
186
+ @mutex.synchronize do
187
+ entry = @entries[agent.agent_id]
188
+ if entry&.state == :live && entry.agent.equal?(agent) && entry.token == :pending_unload
189
+ @entries[agent.agent_id] = Entry.new(state: :live, agent: agent, token: nil)
190
+ @condition.broadcast
191
+ end
192
+ end
193
+ true
194
+ end
195
+
168
196
  # Transfer only the single outstanding hosting operation, atomically with
169
197
  # the same admission gate used by all other Agent operations.
170
198
  def reserve_approval_detach!(agent, operation_token, transition, parent: nil)
@@ -191,8 +219,10 @@ module Phronomy
191
219
  # Returns the already accepted transition for duplicate callers.
192
220
  def reserve_unload(agent)
193
221
  @mutex.synchronize do
194
- ensure_running!
195
222
  entry = @entries[agent.agent_id]
223
+ accepted_release = @state == :draining && entry&.state == :live &&
224
+ entry.agent.equal?(agent) && entry.token == :pending_unload
225
+ ensure_running! unless accepted_release
196
226
  if entry&.state == :unloading && entry.agent.equal?(agent)
197
227
  unless entry.token.is_a?(UnloadTransition)
198
228
  raise Phronomy::AgentBusyError, "Agent has a coordinated release in progress"
@@ -320,11 +350,15 @@ module Phronomy
320
350
  self
321
351
  end
322
352
 
323
- # Live/recovery-required entries do not prevent Runtime shutdown. Only an
324
- # ownership transition that is still actively changing state must settle.
353
+ # Ordinary live/recovery-required entries do not prevent Runtime shutdown.
354
+ # Accepted final releases stay pending through their atomic transition to
355
+ # unloading, so shutdown cannot observe an idle gap between the two.
325
356
  def wait_until_idle(deadline)
326
357
  @mutex.synchronize do
327
- while @entries.values.any? { |entry| %i[constructing purging unloading].include?(entry.state) }
358
+ while @entries.values.any? { |entry|
359
+ %i[constructing purging unloading].include?(entry.state) ||
360
+ (entry.state == :live && entry.token == :pending_unload)
361
+ }
328
362
  remaining = deadline - monotonic_now
329
363
  # :nocov:
330
364
  return false if remaining <= 0
@@ -39,7 +39,8 @@ module Phronomy
39
39
  freeze
40
40
  end
41
41
 
42
- # Returns true when every Runtime-owned resource is known to have stopped.
42
+ # Returns true when owned resources stopped and pending timer notifications
43
+ # settled within the shutdown budget rather than being discarded.
43
44
  def cleanup_complete?
44
45
  @cleanup_status == :complete
45
46
  end
@@ -8,6 +8,8 @@ module Phronomy
8
8
  @clock = clock
9
9
  @heap = []
10
10
  @mutex = Mutex.new
11
+ @idle = ConditionVariable.new
12
+ @firing = 0
11
13
  @stopped = false
12
14
  @wake = nil
13
15
  end
@@ -51,10 +53,26 @@ module Phronomy
51
53
  @mutex.synchronize do
52
54
  before = @heap.length
53
55
  @heap.delete_if { |(_, registered)| registered == callback }
56
+ @idle.broadcast if idle_locked?
54
57
  before != @heap.length
55
58
  end
56
59
  end
57
60
 
61
+ # Wait without driving callbacks on the shutdown caller's thread. Both
62
+ # registrations and callbacks already removed from the heap must finish.
63
+ # @api private
64
+ def wait_until_idle(deadline)
65
+ @mutex.synchronize do
66
+ until idle_locked?
67
+ remaining = deadline - Process.clock_gettime(Process::CLOCK_MONOTONIC)
68
+ return false if remaining <= 0
69
+
70
+ @idle.wait(@mutex, remaining)
71
+ end
72
+ true
73
+ end
74
+ end
75
+
58
76
  # Executes all callbacks whose deadline is due. Must be called by EventLoop.
59
77
  def fire_due
60
78
  callbacks = @mutex.synchronize do
@@ -62,7 +80,9 @@ module Phronomy
62
80
 
63
81
  now = @clock.call
64
82
  due_count = @heap.bsearch_index { |(fire_at, _)| fire_at > now } || @heap.length
65
- @heap.shift(due_count).map(&:last)
83
+ callbacks = @heap.shift(due_count).map(&:last)
84
+ @firing += callbacks.length
85
+ callbacks
66
86
  end
67
87
 
68
88
  callbacks.each do |callback|
@@ -71,6 +91,11 @@ module Phronomy
71
91
  Phronomy::RuntimeSettings.current.logger&.error do
72
92
  "[TimerQueue] callback raised #{error.class}: #{error.message}"
73
93
  end
94
+ ensure
95
+ @mutex.synchronize do
96
+ @firing -= 1
97
+ @idle.broadcast if idle_locked?
98
+ end
74
99
  end
75
100
  callbacks.length
76
101
  end
@@ -82,13 +107,28 @@ module Phronomy
82
107
  def shutdown
83
108
  wake = @mutex.synchronize do
84
109
  return self if @stopped
110
+ @drained_on_shutdown = idle_locked?
85
111
  @stopped = true
86
112
  @heap.clear
113
+ @idle.broadcast if idle_locked?
87
114
  @wake
88
115
  end
89
116
  wake&.call
90
117
  self
91
118
  end
119
+
120
+ # Capture the first closure rather than a preceding idle observation:
121
+ # a caller holding this queue may register after that observation.
122
+ # @api private
123
+ def drained_on_shutdown?
124
+ @mutex.synchronize { @stopped && @drained_on_shutdown }
125
+ end
126
+
127
+ private
128
+
129
+ def idle_locked?
130
+ @heap.empty? && @firing.zero?
131
+ end
92
132
  end
93
133
  end
94
134
  end
@@ -27,7 +27,20 @@ module Phronomy
27
27
  end
28
28
 
29
29
  def shutdown
30
- @mutex.synchronize { @timer&.shutdown }
30
+ @mutex.synchronize do
31
+ return true unless @timer
32
+
33
+ @timer.shutdown
34
+ @timer.drained_on_shutdown?
35
+ end
36
+ end
37
+
38
+ # Capture the timer without holding the service lock during callbacks:
39
+ # an admitted continuation may acquire this same service while draining.
40
+ # @api private
41
+ def wait_until_idle(deadline)
42
+ timer = @mutex.synchronize { @timer }
43
+ !timer || timer.wait_until_idle(deadline)
31
44
  end
32
45
  end
33
46
  end
@@ -210,6 +210,7 @@ module Phronomy
210
210
  loop_instance&.begin_draining
211
211
 
212
212
  participants_idle = wait_for_participants(participants, drain_deadline)
213
+ @timer_service.wait_until_idle(drain_deadline)
213
214
  loop_idle = !loop_instance || loop_instance.wait_until_idle(drain_deadline)
214
215
 
215
216
  @lifecycle_mutex.synchronize do
@@ -217,13 +218,8 @@ module Phronomy
217
218
  end
218
219
 
219
220
  stop_deadline = monotonic_now + [cancel_grace.to_f, 0.2].max
220
- event_loop_status = if loop_instance
221
- loop_instance.stop_and_join(deadline: stop_deadline)
222
- else
223
- :not_started
224
- end
225
-
226
- pools_stopped, subsystem_error = shutdown_pools_and_timer(deadline: stop_deadline)
221
+ event_loop_status, pools_stopped, timers_idle, subsystem_error =
222
+ shutdown_resources(loop_instance, deadline: stop_deadline)
227
223
  participant_error = @lifecycle_mutex.synchronize { @shutdown_participant_error }
228
224
  cleanup_complete = participants_idle && participant_error.nil? &&
229
225
  loop_idle &&
@@ -231,6 +227,7 @@ module Phronomy
231
227
  event_loop_status != :cancel_timeout &&
232
228
  (!loop_instance || loop_instance.__receiver_cleanup_complete?) &&
233
229
  pools_stopped &&
230
+ timers_idle &&
234
231
  subsystem_error.nil?
235
232
 
236
233
  cleanup_complete = finalize_participants(participants) if cleanup_complete
@@ -306,21 +303,38 @@ module Phronomy
306
303
  "Runtime is #{current_state}; new work is not accepted"
307
304
  end
308
305
 
309
- def shutdown_pools_and_timer(deadline:)
306
+ # EventLoop must keep delivering existing deadlines while accepted pool
307
+ # operations drain. Its thread remains the only timer callback executor.
308
+ # Future registrations beyond the shared budget make cleanup incomplete.
309
+ def shutdown_resources(loop_instance, deadline:)
310
310
  error = nil
311
311
  pools_stopped = false
312
+ timers_idle = false
313
+ event_loop_status = :not_started
312
314
  begin
313
315
  pools_stopped = @pool_registry.shutdown(deadline: deadline)
314
316
  rescue => caught
315
317
  error ||= caught
318
+ end
319
+ begin
320
+ timers_idle = @timer_service.wait_until_idle(deadline)
321
+ rescue => caught
322
+ error ||= caught
323
+ end
324
+ begin
325
+ event_loop_status = loop_instance.stop_and_join(deadline: deadline) if loop_instance
326
+ rescue => caught
327
+ event_loop_status = :failed
328
+ error ||= caught
316
329
  ensure
317
330
  begin
318
- @timer_service.shutdown
331
+ timers_drained_on_shutdown = @timer_service.shutdown
332
+ timers_idle &&= timers_drained_on_shutdown
319
333
  rescue => caught
320
334
  error ||= caught
321
335
  end
322
336
  end
323
- [pools_stopped, error]
337
+ [event_loop_status, pools_stopped, timers_idle, error]
324
338
  end
325
339
 
326
340
  def validate_timeout!(value, name)
@@ -47,7 +47,7 @@ module Phronomy
47
47
  child["imported"] = true if observed.terminal? && change.kind == :dispatch && change.operations.empty?
48
48
  end
49
49
  change.operations.each do |operation|
50
- entry = @definitions.find { |name, _| "dispatch_to_#{name}" == operation.name }
50
+ entry = @definitions.find { |name, _| @agent_class.__subagent_tool_name(name) == operation.name }
51
51
  next unless entry
52
52
  next if children.any? { |child| child.fetch("slot") == operation.invocation_id }
53
53
  name, settings = entry
@@ -97,8 +97,10 @@ module Phronomy
97
97
  child = children.first
98
98
  next unless !child.fetch("imported") && child.fetch("execution_id") == execution_id
99
99
  next unless matching_child_class?(child, live_child)
100
+ tool_name = @agent_class.__subagent_tool_name(child.fetch("name"))
101
+ next unless tool_name
100
102
  next unless store.single_dispatch_wait?(agent_id: parent_id, execution_id: parent_execution_id,
101
- invocation_id: child.fetch("slot"), name: "dispatch_to_#{child.fetch("name")}", expected_revision: parent_revision, scope: scope)
103
+ invocation_id: child.fetch("slot"), name: tool_name, expected_revision: parent_revision, scope: scope)
102
104
  next unless hosted_retentions?(parent_id, parent_execution_id, scope)
103
105
 
104
106
  child_id = child.fetch("agent_id")
@@ -20,6 +20,19 @@ module Phronomy
20
20
  super(agent_id, persistence: persistence, execution_wiring: {phronomy_execution_participant: participant}, **options, &block)
21
21
  end
22
22
 
23
+ # Preserve native child ownership when explicitly replacing the Tool map.
24
+ # Ordinary subclass inheritance still starts with no subagent registrations.
25
+ def self.with_tools(definitions, id:, version:)
26
+ derived = super
27
+ retained = _subagent_tool_classes & derived.tools
28
+ registrations = registered_subagents.select do |name, _|
29
+ retained.any? { |tool| tool.tool_name == "dispatch_to_#{name}" }
30
+ end.transform_values(&:dup)
31
+ derived.instance_variable_set(:@_subagent_tool_classes, retained)
32
+ derived.instance_variable_set(:@registered_subagents, registrations)
33
+ derived
34
+ end
35
+
23
36
  def initialize(coordination_store: nil, execution_wiring: {}, **options, &block)
24
37
  @coordination_store = coordination_store || execution_wiring[:phronomy_execution_participant]&.persistence || Phronomy::MultiAgent::Store.configured
25
38
  super(execution_wiring: execution_wiring, **options, &block)
@@ -156,6 +169,13 @@ module Phronomy
156
169
  @registered_subagents ||= {}
157
170
  end
158
171
 
172
+ # @api private
173
+ def self.__subagent_tool_name(name)
174
+ native_name = "dispatch_to_#{name}"
175
+ tool = _subagent_tool_classes.find { |candidate| candidate.tool_name == native_name }
176
+ tool && (tool_aliases[tool] || native_name)
177
+ end
178
+
159
179
  def dispatch_parallel(
160
180
  *tasks,
161
181
  max_concurrency: nil,
@@ -237,7 +257,7 @@ module Phronomy
237
257
 
238
258
  # @api private
239
259
  def __framework_tool_replayable?(name)
240
- self.class.registered_subagents.keys.any? { |key| "dispatch_to_#{key}" == name.to_s }
260
+ self.class.registered_subagents.keys.any? { |key| self.class.__subagent_tool_name(key) == name.to_s }
241
261
  end
242
262
 
243
263
  private
@@ -221,11 +221,11 @@ module Phronomy
221
221
  definitions = shared_tool_definitions(member, binding, cycle)
222
222
  instrumented = build_shared_researcher(member, definitions, sharing)
223
223
  prompt = shared_prompt(input, member_config[:instruction])
224
- invoke_shared_researcher(instrumented, prompt)
224
+ invoke_member_agent(instrumented, prompt)
225
225
  end
226
226
  end
227
227
 
228
- def invoke_shared_researcher(instrumented, prompt)
228
+ def invoke_member_agent(instrumented, prompt)
229
229
  agent = instrumented.new
230
230
  suspended = false
231
231
  result = agent.invoke(prompt)
@@ -235,10 +235,10 @@ module Phronomy
235
235
  end
236
236
  result
237
237
  ensure
238
- release_shared_member(agent, result, $!) if agent && !suspended
238
+ release_member_agent(agent, result, $!) if agent && !suspended
239
239
  end
240
240
 
241
- def release_shared_member(agent, result, primary_error)
241
+ def release_member_agent(agent, result, primary_error)
242
242
  agent.unload!
243
243
  rescue => release_error
244
244
  error = MemberLifecycleError.new(agent: agent, result: result, reason: :release_failed,
@@ -298,7 +298,7 @@ module Phronomy
298
298
  extra_tools: extra_tools,
299
299
  per_agent_instruction: per_agent_instruction
300
300
  )
301
- instrumented.new.invoke(prompt)
301
+ invoke_member_agent(instrumented, prompt)
302
302
  end
303
303
 
304
304
  def build_instrumented_researcher(researcher_class, store, cycle)
@@ -73,9 +73,14 @@ module Phronomy
73
73
 
74
74
  persistence = Phronomy::Agent::DefaultPersistence.build
75
75
  agent = agent_class.create(persistence: persistence)
76
+ ownership = Phronomy::Agent::OwnershipRegistry.current
77
+ ownership.expect_unload(agent)
76
78
  Phronomy::AsyncOperation.finalize(name: "agent-tool-#{name}-release",
77
79
  cleanup: -> { agent.unload_async },
78
- on_cleanup_error: ->(value, primary, cleanup) { child_cleanup_failed(agent, value, primary, cleanup) }) do
80
+ on_cleanup_error: ->(value, primary, cleanup) {
81
+ ownership.cancel_expected_unload(agent)
82
+ child_cleanup_failed(agent, value, primary, cleanup)
83
+ }) do
79
84
  Phronomy::AsyncOperation.call(name: "agent-tool-#{name}-invoke",
80
85
  transform: ->(result) { result[:output].to_s }) do
81
86
  agent.invoke_async(input, config: task_config)
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Phronomy
4
- VERSION = "0.35.1"
4
+ VERSION = "0.35.3"
5
5
  end
@@ -46,6 +46,7 @@ module Phronomy
46
46
  attr_reader coordination_store: Store?
47
47
  def self.create: (?coordination_store: Store?, **Object options) ?{ (Object) -> void } -> instance
48
48
  def self.load: (String agent_id, persistence: Agent::Store, coordination_store: Store, **Object options) ?{ (Object) -> void } -> instance
49
+ def self.with_tools: (Hash[Class, String?] definitions, id: String, version: Integer) -> singleton(Orchestrator)
49
50
  def self.subagent: (Symbol | String name, singleton(::Phronomy::Agent::Base) agent_class, ?on_error: Symbol, ?inherit_knowledge: bool) -> untyped
50
51
  def unload_with_completed_child!: (String parent_execution_id, execution_id: String) -> bool
51
52
  def approve_hosted_child: (String parent_execution_id, execution_id: String, approval_request_id: String, ?approved: bool, ?config: Hash[Symbol, untyped]) -> ::Phronomy::Agent::HostedInvocation
metadata CHANGED
@@ -1,14 +1,14 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: phronomy
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.35.1
4
+ version: 0.35.3
5
5
  platform: ruby
6
6
  authors:
7
7
  - Raizo T.C.S
8
8
  autorequire:
9
9
  bindir: exe
10
10
  cert_chain: []
11
- date: 2026-11-17 00:00:00.000000000 Z
11
+ date: 2026-11-18 00:00:00.000000000 Z
12
12
  dependencies:
13
13
  - !ruby/object:Gem::Dependency
14
14
  name: ruby_llm