docs/ez-agent-ruby/lib/ez_agent/workflow.md

EzAgent::Workflow

ruby
1require "ez_agent/workflow"

Workflow declares an in-memory graph, evaluates it once, and returns immutable operation dispositions. Construction performs no service work. eval freezes the initial graph; active on_done callbacks may append finite atomic tails.

EzAgent::Workflow < EzAgent::WorkflowAgent. The Workflow is the root Agent and the only object with eval; children and fanout members use the same recursive Agent interface. For lifecycle timing and examples, read Workflow lifecycle for authors.

Construct and evaluate

ruby
1workflow = EzAgent::Workflow.new(
2 id: "test_survey", title: "Survey and summarize", estimated_phases: 2
3)
4
5survey = workflow.queue(
6 key: ["survey", "v1"], phase: 1, mode: :plan,
7 prompt: "Map the test layout."
8)
9
10summary = workflow.queue(
11 key: ["summary", "v1"], phase: 2, after: survey, mode: :plan
12) { |record| "Summarize:\n\n#{record.final_text}" }
13
14result = workflow.eval
15abort "workflow failed" unless result.success?
16puts result[summary].value.final_text

The root constructor accepts id:, title:, estimated_phases:, nonce:, cwd:, api:, max_parallel:, and default model/profile fields. IDs and titles must be nonempty control-free UTF-8; the nonce is nonnegative; phase and parallel counts are positive; explicit CWD is absolute. Phases group presentation and do not impose order. max_parallel bounds model workers, independently of builtin capability execution.

A nil api: is opened and owned during evaluation. A supplied API is borrowed, supports one Workflow, and remains caller-owned. close is idempotent and requests cancellation plus bounded cleanup.

Recursive Agent interface

ruby
1agent.agent(key:, title: nil, model: nil, thinking: nil, mode: nil,
2 tools: nil, plugins: nil, triggers: nil)
3
4agent.queue(key:, phase:, prompt: nil, after: nil, when: nil,
5 retries: 0, on_success: nil, on_error: nil,
6 buffers: nil, json: nil, repairs: 0, **profile) { |deps| prompt }
7
8agent.fanout(key:, name:, phase:, items:, after: nil, when: nil,
9 retries: 0, on_success: nil, on_error: nil,
10 buffers: nil, json: nil, repairs: 0, **profile)
11
12agent.queue_command(key:, phase:, argv:, label:, description:,
13 after: nil, when: nil, timeout: nil,
14 follow: false, capture_bytes: 16_384)
15
16agent.select(key:, phase:, from:, strategy:) { |value| matches }
17agent.assert(key:, phase:, after:, message:) { |deps| boolean }
18agent.on_done(key:, phase:, after:) { |disposition, tail| ... }

Declarations work at every Agent depth; child Agents do not evaluate independently. A key is a nonempty array of nonempty control-free UTF-8 components. Direct child Agents and operations share one namespace. Profiles inherit root to child to operation; non-nil tools, plugins, and trigger hashes replace their inherited collections. Trigger families are on_preplugin, on_assistant, on_success, on_error, on_idle, and on_background. on_success and on_error notify per-model-run outcomes; on_background notifies stopped model processing with provider owners remaining. on_idle notifies real quiescence. These profile triggers are separate from query result callbacks.

Agents expose these navigation and state readers:

text
1workflow owner key key_path agent_path title base_title tag
2fanout_key fanout_index profile leaf_id head_leaf_id
3agents operations queries initial_query
4sealed? admitted? fanout_member? agent_identifier display_identifier session_base_name

The root has workflow == self and owner == nil; a child's owner is its structural parent. Operations expose workflow, owner, and agent, where agent aliases the receiver. Before admission, leaf readers are nil. Eligible local work or descendant admission materializes owners first. Once admitted, leaf_id remains stable and head_leaf_id follows the latest usable occurrence. Titles and tags affect display, not prompts or replay identity. Put the role in the prompt. Structured title, tag, continuation, and try display fields belong to the ruby.workflow//0.1 contract.

Queries and dependencies

queue returns a WorkflowQuery, not an Agent. It takes exactly one static prompt or lazy block producing a String or text-user API::PendingTurn. Optional boolean PendingTurn.steer carries input-timing context through admission and plugins, not a scheduling command; see PendingTurn context. Static prompt expressions run during construction. A lazy block runs inside an admitted worker only when fresh preparation is needed; replay skips it and a retry may invoke it again.

after: accepts operations from the same Workflow. One dependency passes its value; one fanout passes ordered initial-member results; several dependencies pass an ordered array with fanout results nested. Without dependencies, a lazy block receives no arguments. Required dependencies must succeed. when: may be nil, boolean, or callable and runs after dependencies and before admission. Later queues on one Agent automatically continue that Agent's prior local query; callers do not select ancestry. That automatic edge waits for settlement and valid ancestry, without treating a failed prior response as success.

Generation zero, try zero uses the stable Agent leaf. Later generations and retries are siblings beneath it. A new generation forks the prior trusted tip; a retry forks that generation's captured source. Structured-output repairs stay on one occurrence. Workflow records their exact accepted turn IDs in the workflow.query_repairs leaf config entry. It ties the record to the admitted query identity, leaf, conversation root, boundary, and repair limit. Replay uses those IDs, not repair prompt wording, to allow another run after an intermediate terminal answer. Compaction still validates original ancestry and retained copies; repair bookkeeping does not make a copied answer terminal. External repair-shaped prompts do not acquire this ownership. Structural children always attach to the owner's stable leaf_id, not its moving head. A skipped prior query leaves no ancestry for a later one. An eligible failed model or exhausted structured-output query may retain a validated terminal tip for a later generation while remaining failed.

Operations expose key, full key, phase, sequence, dependencies, kind, condition, Workflow, and owner. Query readers additionally expose prompt, source, generation, required dependencies, retries, buffers, JSON/repair settings, profile, callbacks, occurrence placement, attempt, candidate leaves, and result. Exact reader names and value types live in the implementation and public surface tests.

Fanout

fanout creates ordered real member Agents plus one no-leaf aggregate over their initial queries. Each item supplies prompt: and may override tag, retry, callback, buffer, JSON, repair, and profile fields. Members retain the full Agent interface.

members, initial_queries, and the alias queries are frozen and preserve item order. The fanout is Enumerable; indexing and slicing use normal Array semantics, and each, size, and length expose the collection. The aggregate depends only on initial queries, not later member followups, and creates no model task. Successful aggregation yields ordered values. Mixed outcomes are unsuccessful and partial?; successful sibling values and ordered member_dispositions remain available.

Retries and structured output

retries: bounds extra occurrences. on_error: receives WorkflowQueryFailure after a committed failed try and before settlement; return exactly :retry to authorize an eligible retry. Live non-abort transients may consume the remaining budget automatically regardless of callback return; use retries: 0 when a live retry is unacceptable. Historical model errors and exhausted structured-output errors require explicit callback approval. Cancellation, setup, identity, dependency, preparation, and transport-integrity failures do not retry. Failure readers include Workflow, query, Agent/owner, error, occurrence, retries used/remaining, and retry_available?.

Ordinary retries restart from the generation's captured source. They do not resume a provider request or undo filesystem effects. Increasing retries: alone does not restart historical model errors. Temporary-provider authorization requires typed prior evidence, never words in a terminal message, and no fallback model is selected automatically.

One-shot interruption recovery

A live abort stops the operation without retrying. On a later authorized eval, an exact durable ABORT or a validated inactive operation without a terminal result gets one recovery operation by default, independently of retries:. Keep the Workflow ID, nonce, Agent path, and operation key unchanged. Workflow forks the validated interrupted canonical tip and submits the operation instructions with that context. Existing partial filesystem effects remain. This is not a provider-native request resume or an undo of edits. The original interruption remains durable history, never SUCCESS; downstream work unblocks only after recovery succeeds. Completed branches are reused.

Consumption is written to workflow.query_recovery in the original occurrence's existing config metadata before setup or prompt admission. It binds the next occurrence identity and interrupted tip. A later eval may reuse a completed recovery but cannot launch another after recovery failure, interruption, ambiguous admission, or setup failure. Manual on_error: :retry and typed temporary errors cannot override this veto. The original interruption is reported to on_error: with retry_available? == false, and retained in a successful disposition's attempt_failures.

on_success: runs once after final success. Callback order is each failed-try on_error, then one final on_success, then operation on_done. Callback failures are advisory and enter callback_diagnostics.

json: accepts true or the loose schema fields top_level, required, types, and enum. repairs: bounds same-occurrence corrective prompts; parsed output is record.data. A fallback model is a new finite local generation, commonly appended from on_done to the same Agent. It uses the failed query's validated tip and does not erase the failed disposition it follows.

Commands and evidence

Commands run direct argv in the Workflow CWD, always rerun, and share one sequential lane even while model work is parallel. Use an explicit positive timeout in seconds for bounded operational commands. Full output goes to a no-follow regular-file buffer; captured UTF-8 is bounded. Timeout and output failure terminate the process group with TERM then KILL. follow: true streams attributed bytes to stderr. WorkflowCommandResult reports argv, CWD, exit status/signal, timeout, truncation, buffer identity, captured/output bytes, timing, label, description, and success/failure predicates.

buffer and write_buffer return resources, not operations. Derived buffers add their after: operations as dependencies; command buffers also require command success. Fresh consumers receive ordered physical attachments with a manifest mapping identities to labels, or raw String names to unlabeled evidence. Capability-owned embed:, meta:, and skill: resources remain available on demand through the buffer tool.

Replay does not rerun buffer blocks, allocate anonymous buffers, read files, or build attachments. Admission rejects traversal, symlink escapes, non-regular files, identity changes, unsupported media, and limit violations. Each prompt accepts at most 64 generated physical files; UTF-8 evidence is capped at 256 KiB per file within a 32 MiB decoded budget. JPEG, PNG, GIF, WebP, and PDF require valid signatures.

Buffers do not invalidate replay, and model records do not recreate filesystem edits. Serialize shared-worktree writers and gate delivery with commands and assertions. Version affected keys or the Workflow nonce when mutation must run again.

Selection, assertions, and steering

select(strategy: :first_matching_or_last) chooses the first successful match or the last successful candidate. Failed or cancelled candidates fail selection; skipped candidates are absent. A fanout selects across its initial queries. Assertions require dependencies, have no when:, and fail when false or unreachable.

query.steer(key:, phase:, text:, after: nil, on_accepted: nil, on_error: nil) is a scheduled, live-only dependency handle. It persists no replay value and marks its causal path fresh. Acceptance does not prove provider consumption. WorkflowSteerResult exposes Workflow, leaf ID, turn IDs, tip ID, and optional request ID.

Done callbacks and append-only tails

on_done observes every final disposition, including failure, skip, cancellation, and reconstructed replay error. It runs synchronously and serially after query callbacks. Its WorkflowTail may append queue, queue_command, select, assert, and write_buffer operations to predeclared Agents. Tail queries require explicit agent: and use that Agent's existing lineage; command and control declarations default to the Workflow. It cannot add Agents, fanouts, external buffers, or steers. Dependencies may reference settled operations or earlier nodes in the transaction.

During an active callback thread, another workflow.on_done declaration joins that transaction, allowing a bounded correction loop to register its next decision. Validation and commit are atomic; one invalid declaration rejects the whole transaction even if callback code rescues the exception. Every tail must be finite. Recursive callbacks need a round/cost limit, terminating branch, deterministic caller-owned keys, and explicit routing for failed or malformed decisions. The lifecycle page owns the bounded-correction example and callback timing.

Replay identity and lifecycle

Workflow uses version-3 identities. An occurrence is identified by:

  1. Workflow id and nonce;
  2. typed structural Agent path;
  3. receiver-local operation key;
  4. automatic generation;
  5. try.

Titles, tags, prompts, dependencies, profiles, callbacks, retries, repairs, and buffers are absent. Admission verifies exact identity, parentage, ancestry, CWD, markers, query boundary, and canonical history. Duplicate, malformed, detached, or ambiguous candidates fail closed.

Creation uses a random opaque staging name. Its strict ASCII envelope contains only a fresh token and a SHA-256 digest binding it to setup identity, not raw Workflow, structural, leaf, or turn identifiers. The first config write persists the exact staged identity; the stable Agent/query identity is the final commit marker. Interrupted setup may finish only its exact staged leaf when envelope or persisted setup identity, parent, root, CWD, boundary, and canonical source history still match. A staged query is validated before lazy prompt/evidence work, then again before setup writes and prompt admission.

Workflow refreshes raw exact-identity and envelope/setup-marker candidates immediately before the occurrence identity write, after that write, after staging cleanup, and before provider admission. Any visible competitor prevents admission. The current leaf/config API provides no compare-and-swap, lease, or cross-connection claim, so these checks are not a linearizable lock. Recovery and admission markers use the same contract. Run one evaluator per Workflow ID/nonce; use another nonce for intentional concurrency.

Interrupted and terminal history

Replay reconstructs marked success, structured failure, model error, and interruption. Adoption proves identity and start independently of terminal results. An inactive operation without a terminal endpoint qualifies as interrupted only when its exact workflow.query_admission marker, operation prompt, canonical ancestry, sent turns, and inactivity at the same tip are validated. Its tip may be a prompt, partial inference, or tool output. Compacted history also qualifies, even a summary-only tip, when physical ancestry proves the original prompt. Active runs, missing/changed markers, unsent work, earlier terminal markers, and uncertain ancestry do not qualify.

A sent canonical kind: "error" tip after the operation prompt is a durable failure even without assistant exit_message; exact ABORT is an interruption. An early accepted abort may delete its draft/ready prompt. That narrow prompt-less shape qualifies only when exact Workflow/Agent/query identities and the admission marker match, and the sole operation turn is a sent assistant with exit_message: "ABORT" and stop_reason: "interrupted", or a sent error with content exactly ABORT. It must be directly parented by the validated captured boundary and equal the canonical tip. Root identity, ordered ancestry, and terminal stats must agree. Stable-leaf and sibling adoption use the same checks; other prompt-less errors, extra turns, detached tips, missing markers, and unprovable compacted boundaries fail closed.

Both interruption shapes consume the same single recovery allowance, not a second one. They supply neither successful results nor direct next-generation continuation. A validated ABORT tip can source the recovery fork. Eligible failed assistant output or exhausted structured-output history may retain a validated terminal tip for a later generation; incomplete or ambiguous history never fabricates success or ancestry.

Compaction validation

A virtual root with "continuation": true in JSON other_meta lets request ancestry follow physical parents beyond that boundary. Workflow validates the system, synthetic user prompt, and unmarked assistant summary prefix without depending on human-facing wording. Hidden source turns are read with turns.get, and retained copies must match the preceding canonical suffix.

Optional pivot_turn_id names the last summarized source turn. Workflow verifies that cutoff and the suffix after it. A held prompt may follow an empty suffix without being copied. Accepted prompt IDs bound live copy matching; the pivot fixes suffix length. Repeated summarized content alone does not make a new prompt or answer a copy. Without a pivot, copies must match unambiguously; a marked continuation may summarize all source history and continue without retained copies. Unknown metadata keys are ignored. If continuation is absent, older automatic/manual reason recognition, including Anchor: prose, remains available. False/invalid flags, malformed metadata, and invalid supplied pivots never fall back to prose.

Copy comparison preserves content, attachments, model/tool fields, thinking, and nonterminal metadata. It permits stripping exit_message and rebasing the newest retained assistant's input usage estimate. It also permits virtual-root admission to remove boolean background_progress: true from a retained user copy. This exception is directional: copies cannot add or change provenance, and unrelated metadata must still match. Internal progress is derived from validated original ancestry, not the scrubbed copy. Synthetic prompts and verified copies do not count as new submissions, including repeated compactions. Results retain the original operation prompt ID and exclude summaries and assistant turns originating before it.

Live substitution also requires completion to match accepted request, leaf, and root, and end at the current canonical assistant tip with its own terminal mark. Trusted internal follow-ups may add user-kind turns and intermediate model SUCCESS markers. Workflow accepts the service-generated boolean other_meta.background_progress: true, or an existing background_bash object with a nonempty String task_id. The service validates provider ownership at steer admission. Legacy Bash correlation relies on daemon ingress controls; Workflow cannot authenticate a stored task ID by itself. Mode tags, prose, string-valued flags, and calling steer alone do not prove internal progress. Compaction ancestry and retained-copy validation still reject additional external submissions, including those hidden by compaction. An old successful ancestor is not a substitute. Post-success manual compaction leaves its terminal clone unmarked and invalidates replay; it does not recover old SUCCESS. Make manual changes on a separate fork from the successful turn when the original occurrence must remain replayable.

Prompt/profile edits do not change identity. Version affected operation and downstream keys or the nonce when work must run fresh. Commands rerun, and steering is the automatic fresh barrier. See virtual-root metadata.

Results and dependency handles

eval returns WorkflowResult. Index it with an operation, not an Agent. Queries, fanout aggregates, commands, selectors, assertions, done controls, and steers are dependency handles; Agents and buffers are not. result[agent] raises ArgumentError; use a member's initial_query for its initial result.

Each disposition reports operation, Agent, state, value, error, attempt failures, and member dispositions. States are :executed, :reused, :volatile, :failed, :skipped, and :cancelled. success? means no unresolved failure or cancellation; recovered? records eventual query success after a failed try; clean? means success without a failed query try. failure_origins, dependency_blocked?, and root_failure? distinguish causal failures from propagated blocked work, including continuation sources and failed-target steers. Diagnostic summaries and print_summary, with optional io:, are bounded and omit prompts, payloads, IDs, timing, provider data, and error text while reporting root and blocked counts.

Monitoring timeout recovery

A TimeoutError from read-only terminal_fallback or terminal_signal_stats does not immediately fail or abort an accepted prompt. Workflow records phase, leaf, request ID, and consecutive timeout count in lifecycle_diagnostics, then returns to the completion/cancellation wait. A successful reply resets the count and saved timeout. The third consecutive timeout fails with the first timeout in that streak and invokes owned-prompt abort cleanup unless quiescence was already observed. A newly arrived correlated completion permits one status check before exhaustion, not an unlimited timeout exemption. This per-prompt budget neither resubmits model work nor extends the five-second stats RPC timeout. Connection, decode, service, and lifecycle errors still fail immediately.

Identity, CWD, final stats, canonical history, hidden compaction ancestry, staged turn-tree validation, and dynamic-tail candidate reads have a separate three-attempt read-only reconciliation bound, checking cancellation before each attempt. Only typed API::TimeoutError permits another read; exhaustion preserves the first timeout. Unavailable evidence is not a negative identity predicate.

A rename timeout is never blindly resent. Workflow reads back the selected leaf's desired name and phase-specific identity. Committed-query proof requires exact occurrence and operation boundary; staged-query proof requires setup identity, boundary, and an absent committed query marker. Workflow/Agent identity alone is insufficient. Reused occurrences are inspected again after presentation changes, so changed tips or identities cannot return old results. Setup markers remain until setup finishes. Missing, contradictory, or failed read-back preserves the exact primary rename timeout. Non-timeout read-back errors are separately recorded at reconciliation.rb:rename:2 with fixed labels, never their text or classes. Only timeout read failures permit another read. Process-control exceptions outside StandardError propagate unchanged. No mutation or prompt is resubmitted on timeout.

Before prompt submission Workflow durably sets workflow.query_admission to the occurrence identity. If acceptance is lost and history still looks prepared, that marker prevents duplicate admission. Accepted/terminal history is reconciled normally. Recovery checks old runtime release and unchanged canonical tip before consuming its allowance and again before admission. Active, uncertain, moved, incomplete, or ambiguous old work blocks recovery.

Workflow follows an accepted query through running, background, and owned internal follow-up runs until idle, unloaded, or closed. Per-run terminal macros and correlated prompt_completed are consumed wakeup/outcome evidence, not unconditional leaf completion. The initial outcome does not contradict a later internal run's different outcome. Retired/completed tip evidence is tracked independently of successful result projection, so a later ABORT or error remains the primary failure even when its draft user boundary was rolled back. Such a failure does not supply unvalidated context for a continuation. Workflow reconstructs the final result from the validated canonical tip, not an intermediate SUCCESS. The existing fallback polls cover final task removal without a follow-up turn or completion frame.

Background history cannot settle replay or authorize interrupted recovery or duplicate prompt admission. An evaluation never gains abort ownership merely by inspecting historical work. Ordinary stopped-model history operations on background leaves remain allowed by the service; Workflow does not turn those permissions into query completion. Scheduled external Workflow steering still rejects background targets.

Cancellation and cleanup

While Workflow owns signal handlers, INT and TERM stop admission and request aborts for accepted unfinished operations, including background work after the initial model run completes. Abort ownership lasts until observed quiescence. Failure cancels remaining owned work once and preserves the primary error through cleanup. An owned API stays open while pending prompt RPCs settle within their normal 10-second timeout, with a separate one-second abort budget and short local drain allowance. Scheduler/evaluator drains respect that settlement interval. Late acceptance after cancellation triggers explicit abort before owned close; requester disconnect does not cancel accepted daemon work. Reentrant close from a prompt caller defers close until that caller settles. After owned close, API threads have six seconds to join, leaving margin over the reader's two-second polling interval. Deadline expiry records an incident and lifecycle diagnostic; ordinary polling delay does not.

Cleanup is bounded and cooperative, not a delivery guarantee. Ambiguous prompt admission or failed aborts may leave work active. Unconfirmed cleanup remains in lifecycle_diagnostics; Workflow eventually closes/drains rather than waiting forever. Cleanup preserves the primary operational error, attempts remaining cleanup, and records failures through the shared incident recorder. Overlay installation, rollback, hydration, and both trigger-key cleanups have distinct fixed indexed sites. Failure cleaning one key does not prevent the other attempt; the first error is raised after both. Failed shared config reads permit neither mutation.

Incidents cover expired admission/abort settlement, owned-API interruption, worker-drain deadlines, injected cancellation, and last-resort thread kill. They use fixed sites and labels, validated IDs, and integer elapsed/budget milliseconds or pending counts, never thread names, stage prose, or exception text. Cooperative cleanup alone creates no incident file. Tombstones never authorize recovery; detailed lifecycle diagnostics remain separate.

SIGKILL cannot run cleanup. Abort targets a leaf rather than a request identity, so a completed request followed by another on the same leaf can race an in-flight abort. Workflow does not deliberately abort setup-only, completed, or unrelated calls; atomic protection would require a request-scoped wire contract.

Errors

Graph construction and freeze errors derive from WorkflowGraphError, an ArgumentError; WorkflowFrozenError covers sealed mutation. Replay, visibility, parent, and ambiguity failures use the materialization family. Post-create identity, CWD, metadata, config, or profile failures use fatal WorkflowSetupError and stop later admission. Ordinary branch failures settle dispositions while independent work drains.

Unexpected evaluation and scheduler failures create best-effort incident-only tombstones. Observation does not retry work, replace exceptions, or turn failure into success. Graph failures use invariant; other unexpected failures use unexpected with outcome fail. Selected sites cover evaluation/materialization, operation admission, worker and control execution, dead/unreachable settlement, command output, and launch. Fixed source indices distinguish typed-carrier and generic worker catches, reconciliation decisions, abort budgets, recovery, and monitoring; they are not attempt counts or runtime-derived labels.

Worker exit without a result wakes the scheduler and settles as failed unless cancellation or fatal drain is underway. A 100-ms fallback sweep finds workers killed before notification and drains queued results before settling the dead snapshot. Typed query-error carriers preserve exact primary errors and attempt history. Dependency propagation does not emit duplicate root incidents. Expected assertion/review findings, command exit failures, typed query failures, and normal cancellation do not heat these sites. Owned-API materialization reports before cleanup cancellation, without losing or duplicating the failure.

Audit data includes only validated machine leaf IDs and a machine-only operation_id, hashed from process ID, in-memory Workflow identity, and operation sequence, or evaluation identity without a sequence. It is stable within one evaluation, not across restarts. Workflow IDs and user operation keys, exception messages/classes, thread names, prompts, and responses never enter audit data. These are selected failure boundaries, not broad stack coverage.

Visualization, examples, and authority

An owned Workflow projects initial and appended query/command workload through the existing lossy ruby.workflow//0.1 visualizer. Structured display fields drive TUI names; replay keys are not shown. Borrowed Workflows do not register that macro and emit fallback progress. materialization_diagnostics, callback_diagnostics, lifecycle_diagnostics, and execution_phase_durations provide bounded inspection without prompts or response text.

While evaluation is active, one progress reporter checks the external parent's current-branch history every 500 ms, with a 500 ms request timeout. Delivered parent leaf_updated events also wake the reporter; it does not subscribe to or hold the parent leaf. Graph changes check the target immediately. The target is the latest sent history turn, even when the parent is background or idle and its tip is draft or ready. With no sent turn, the producer waits rather than promoting unsent input.

When the sent turn changes, the producer re-advertises the same update ID and visualizer descriptor even if the graph has not changed. It does not clear first. The daemon still expires old-turn progress; a lookup/report race may drop a report, and the next check follows the current authority. Failed lookups never send positive reports to a cached target. The reporter stops and removes its event handler before publishing terminal state to a freshly resolved target. Close then clears the last reported target while the final macro is still callable, before closing an owned API. Borrowed API ownership is unchanged, and progress failures remain display-only diagnostics rather than evaluation errors.

  • Agent guidance: cmd/ez-agent-builtin/internal/builtin/skills/skills/workflow/SKILL.md
  • Reviewed patterns: cmd/ez-agent-builtin/internal/builtin/skills/skills/workflow/patterns/
  • Public surface checks: ez-agent-ruby/test/release_surface_test.rb
  • Construction and runtime tests: ez-agent-ruby/test/workflow_construction_test.rb, workflow_runtime_test.rb, and workflow_recursive_runtime_test.rb
  • Audit source-site/index coverage: ez-agent-ruby/test/workflow_readiness_test.rb
  • Lifecycle and display contracts: lifecycle, ruby.workflow//0.1

The offline regression tests/suites/test_ruby_workflow.py::test_early_abort_recovers_once_across_real_service_restart holds a real preplugin gate, aborts accepted draft/ready input, and observes only the stable boundary and sent interrupted assistant ABORT. Fresh Ruby clients across test-daemon restarts verify recovery then reuse, or a second abort then permanent allowance consumption. A deterministic local HTTP provider verifies no initial or duplicate provider admission. This supplements malformed-history and resident/continuation coverage in workflow_abort_cleanup_test.rb.