docs/agent-api/ruby-workflow-lifecycle.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Ruby Workflow lifecycle for authors | EzAgent</title>
<style>
:root{color-scheme:light dark;--bg:#f4f7fb;--panel:#fff;--panel2:#edf3f8;--text:#172230;--muted:#58677a;--line:#d4deea;--accent:#5b4bc4;--accent2:#0b7199;--good:#16794b;--warn:#996300;--danger:#b42318;--code:#101722;--codet:#e5edf7}@media(prefers-color-scheme:dark){:root{--bg:#0c1118;--panel:#141b24;--panel2:#1b2531;--text:#e6edf3;--muted:#9cabbe;--line:#303c4a;--accent:#a997ff;--accent2:#69d2ff;--good:#57cc8a;--warn:#e8b84d;--danger:#ff7b72;--code:#090e14;--codet:#dce7f3}}*{box-sizing:border-box}html{scroll-behavior:smooth}body{margin:0;background:var(--bg);color:var(--text);font:16px/1.58 system-ui,-apple-system,"Segoe UI",sans-serif}.layout{display:grid;grid-template-columns:minmax(225px,280px) minmax(0,1050px);gap:26px;max-width:1380px;margin:auto;padding:28px}aside{position:sticky;top:20px;align-self:start;max-height:calc(100vh - 40px);overflow:auto;background:var(--panel);border:1px solid var(--line);border-radius:14px;padding:18px}aside strong{display:block;margin-bottom:8px}aside a{display:block;padding:4px 7px;color:var(--muted);text-decoration:none}aside a:hover{color:var(--accent)}main{min-width:0}header,section{background:var(--panel);border:1px solid var(--line);border-radius:14px;padding:26px 30px;margin-bottom:22px}h1{font-size:clamp(34px,5vw,48px);line-height:1.08;margin:0 0 12px}h2{font-size:28px;line-height:1.2;border-bottom:1px solid var(--line);padding-bottom:9px}h3{font-size:21px;margin-top:27px}a{color:var(--accent)}code,pre{font-family:ui-monospace,SFMono-Regular,Menlo,monospace}code{overflow-wrap:anywhere}pre{overflow:auto;background:var(--code);color:var(--codet);padding:15px;border-radius:9px;line-height:1.45}.lede,.muted{color:var(--muted)}.scope,.note,.warning,.good{background:var(--panel2);border-left:4px solid var(--accent);border-radius:8px;padding:12px 16px;margin:16px 0}.warning{border-left-color:var(--warn)}.good{border-left-color:var(--good)}.scope strong{color:var(--text)}table{width:100%;border-collapse:collapse;margin:14px 0;font-size:15px}th,td{border:1px solid var(--line);padding:9px;vertical-align:top;text-align:left}th{background:var(--panel2)}.yes{color:var(--good);font-weight:700}.no{color:var(--muted)}.conditional{color:var(--warn);font-weight:700}.timeline{counter-reset:stage;list-style:none;padding:0;margin:22px 0}.timeline>li{position:relative;margin:0 0 14px 42px;padding:15px 18px;background:var(--panel2);border:1px solid var(--line);border-radius:10px}.timeline>li::before{counter-increment:stage;content:counter(stage);position:absolute;left:-43px;top:13px;width:30px;height:30px;border-radius:50%;display:grid;place-items:center;background:var(--accent);color:white;font-weight:800}.timeline>li:not(:last-child)::after{content:"";position:absolute;left:-29px;top:43px;width:2px;height:calc(100% + 15px);background:var(--line)}.timeline h3{font-size:18px;margin:0 0 5px}.timeline p{margin:5px 0}.branch{display:grid;grid-template-columns:1fr 1fr;gap:12px;margin-top:10px}.branch>div{padding:11px;border:1px solid var(--line);border-radius:8px;background:var(--panel)}.branch strong{display:block}.sequence{display:grid;grid-template-columns:9rem minmax(0,1fr);border:1px solid var(--line);border-radius:10px;overflow:hidden;margin:16px 0}.sequence>*{padding:10px 12px;border-bottom:1px solid var(--line)}.sequence>*:nth-last-child(-n+2){border-bottom:0}.actor{font-weight:700;background:var(--panel2);color:var(--accent2)}.event{background:var(--panel)}.channels{display:grid;grid-template-columns:repeat(3,1fr);gap:12px}.channel{border:1px solid var(--line);border-radius:10px;padding:15px;background:var(--panel2)}.channel h3{margin:0 0 5px;font-size:18px}.ruby{border-left:4px solid var(--accent2)}li+li{margin-top:5px}footer{color:var(--muted);font-size:14px;padding:4px 8px 30px}@media(max-width:900px){.layout{display:block;padding:14px}aside{position:static;max-height:none;margin-bottom:18px}.branch,.channels{grid-template-columns:1fr}header,section{padding:20px}.sequence{grid-template-columns:7rem minmax(0,1fr)}}
</style>
</head>
<body>
<div class="layout">
<aside>
<strong>Workflow lifecycle for authors</strong>
<a href="#scope">Purpose and authority</a>
<a href="#model">Root and recursive Agents</a>
<a href="#topology">Leaves and names</a>
<a href="#taxonomy">Operations and resources</a>
<a href="#lifecycle">Whole lifecycle</a>
<a href="#query">One query generation</a>
<a href="#fanout">Fanout and counting</a>
<a href="#connections">Dependencies and evidence</a>
<a href="#callbacks">Callback timing</a>
<a href="#tails">Dynamic tails</a>
<a href="#replay">Replay and recovery</a>
<a href="#results">Results and navigation</a>
<a href="#references">Exact references</a>
</aside>
<main>
<header id="scope">
<h1>Ruby Workflow lifecycle for authors</h1>
<p class="lede">A guide to recursive Agents, scheduled operations, stable leaves, automatic conversation generations, replay, and append-only runtime tails.</p>
<div class="scope"><strong>This page explains the lifecycle.</strong> Exact signatures and edge cases are in the <a href="../ez-agent-ruby/lib/ez_agent/workflow.md">Workflow reference</a>. The <a href="ruby-workflow-0.1.html"><code>ruby.workflow//0.1</code> page</a> defines only the lossy visualizer payload.</div>
</header>
<section id="model">
<h2>The root and recursive Agents</h2>
<p><code>EzAgent::Workflow < EzAgent::WorkflowAgent</code>. The Workflow is the root Agent and the only object with <code>eval</code>. Explicit child Agents, nested Agents, and fanout members use the same interface.</p>
<pre>workflow.workflow == workflow
workflow.owner == nil
child.workflow == workflow
child.owner == workflow
nested.owner == child</pre>
<p>Every Agent may declare <code>agent</code>, <code>queue</code>, <code>fanout</code>, <code>queue_command</code>, <code>select</code>, <code>assert</code>, and <code>on_done</code>. Declare the graph at any level, then call <code>workflow.eval</code> once. There is no child or partial eval.</p>
<p>An Agent declaration is lazy. It makes no model call and gets no leaf until eligible local work or descendant admission requires it. Once admitted, <code>leaf_id</code> is stable and <code>head_leaf_id</code> tracks the latest usable conversation occurrence.</p>
<div class="note"><strong>Counting rule.</strong> Count queued model work, not Agent declarations. <code>workflow.agent</code> alone is zero model tasks.</div>
</section>
<section id="topology">
<h2>Stable leaves, conversation siblings, and display names</h2>
<p>Every Agent owns one declaration-ordered conversation. Generation zero runs on its stable leaf. Later generations and retries use sibling leaves grouped beneath that stable leaf. Their fork ancestry still follows the prior trusted head or captured source. Repairs stay on the same occurrence leaf.</p>
<pre>Workflow title stable root, generation 0 if queued
├── Workflow title continue-1 later root generation
├── Writer stable child, generation 0
│ ├── Writer continue-1 later Writer generation
│ ├── Writer continue-1 try-2 first retry of that generation
│ └── Nested verifier structural child of Writer's stable leaf
├── Reviewer - security fanout member
└── Reviewer - 2 untagged fanout member</pre>
<p>Structural children always attach to <code>owner.leaf_id</code>, not the moving head. This keeps nested Agents stable while conversations advance.</p>
<p>The Workflow title names the root. An ordinary Agent uses its title or key fallback. Queries have no title. Fanout <code>name:</code> supplies the base title, and an optional item <code>tag:</code> or one-based index supplies the suffix. Structured display fields are title, tag, continuation, and try. Keys are not UI fields.</p>
<div class="warning"><strong>Prompts still need roles.</strong> Titles and tags are presentation metadata. Workflow does not inject them into prompts. Say “You are the security reviewer” in the prompt even when the TUI says <code>Reviewer - security</code>.</div>
</section>
<section id="taxonomy">
<h2>Operations, Agents, and resources</h2>
<table>
<thead><tr><th>Public object</th><th>What it represents</th><th>Dependency handle?</th></tr></thead>
<tbody>
<tr><td><code>WorkflowAgent</code></td><td>A stable structural and conversation owner. The root is also the evaluator.</td><td class="no">No</td></tr>
<tr><td><code>WorkflowQuery</code></td><td>One model operation scheduled on its receiving Agent.</td><td class="yes">Yes</td></tr>
<tr><td><code>WorkflowFanout</code></td><td>A no-leaf aggregate over exactly the ordered initial queries of real member Agents.</td><td class="yes">Yes</td></tr>
<tr><td>Command, selection, assertion, done, steer</td><td>Scheduled operations with final dispositions. Commands use a separate sequential lane; controls run inline.</td><td class="yes">Yes</td></tr>
<tr><td><code>WorkflowBuffer</code></td><td>External, inline, or result-derived evidence. It has no key, phase, or disposition.</td><td class="no">No</td></tr>
<tr><td><code>WorkflowTail</code></td><td>A temporary builder capability available only inside an active <code>on_done</code> callback.</td><td class="no">No</td></tr>
</tbody>
</table>
<p>Every operation and every public result or builder handle documented by the API exposes <code>workflow</code> where source defines it. Operations also expose <code>owner</code>, with <code>agent</code> as the receiver alias.</p>
</section>
<section id="lifecycle">
<h2>Whole Workflow lifecycle</h2>
<ol class="timeline">
<li><h3>Ruby declares the graph</h3><p><code>Workflow.new</code> and recursive Agent calls build in-memory objects. Queue, fanout, command, control, steer, and initial done calls return handles. Static prompt expressions run now. No model or command runs.</p></li>
<li><h3><code>eval</code> seals the initial graph</h3><p>The root opens or borrows the API, resolves its external parent and stable version-3 identity, and creates or strictly adopts the root leaf. Ordinary graph mutation is now closed.</p></li>
<li><h3>The scheduler follows dependencies</h3><p>Phases are display groups. Explicit dependencies and automatic local lineage determine readiness. <code>max_parallel</code> bounds model workers; commands use one sequential lane.</p></li>
<li><h3>Eligible Agents materialize lazily</h3><p>Owners materialize first. A skipped child query does not create its Agent leaf. A descendant can require admission of its owner chain.</p></li>
<li><h3>A query worker inspects replay</h3><p>Workflow looks up the exact Agent path, operation key, generation, and try. Reusable history skips prompt and evidence generation. Fresh work retains a model slot while it prepares input and admits the prompt.</p></li>
<li><h3>Fresh work reaches terminal release</h3><p>Prompt acceptance is not completion. Workflow correlates request, leaf, root, terminal evidence, trigger completion, and idle release before freeing the model slot.</p></li>
<li><h3>Repairs and retries finish</h3><p>Structured repairs stay on the same occurrence. Eligible query errors invoke <code>on_error</code>; <code>:retry</code> may consume the next bounded try. Final success invokes <code>on_success</code>.</p></li>
<li><h3>Done controls may append</h3><p><code>on_done</code> receives the final disposition, including failure or skip. It may publish one finite atomic transaction to existing Agents.</p></li>
<li><h3>Quiescence returns one result</h3><p>Evaluation waits until initial and appended operations settle. <code>WorkflowResult</code> includes all committed operations.</p></li>
</ol>
</section>
<section id="query">
<h2>One Agent's query generations</h2>
<pre>writer = workflow.agent(key: ["writer"], title: "Writer")
draft = writer.queue(key: ["draft"], phase: 1, prompt: "You are the writer. ...")
revision = writer.queue(key: ["revision"], phase: 2, after: review,
prompt: "You are the same writer. Apply the review. ...")</pre>
<p>The second queue automatically depends on the first for settlement and conversation ancestry. The author does not select an ancestry handle. <code>after: review</code> adds a separate success-gated dependency.</p>
<div class="sequence" role="table" aria-label="Fresh query sequence">
<div class="actor">Scheduler</div><div class="event">Required dependencies succeeded, the prior local generation settled with usable ancestry, and the condition passed.</div>
<div class="actor">Query worker</div><div class="event">Inspect exact replay candidates for this generation and try. Stop if canonical history is reusable.</div>
<div class="actor">Ruby</div><div class="event">For fresh work only, invoke the lazy prompt and required evidence generators.</div>
<div class="actor">Workflow/API</div><div class="event">Prepare the stable or sibling occurrence leaf, apply profile and display config, attach evidence, and admit the prompt.</div>
<div class="actor">Agent/model</div><div class="event">Run model and tool cycles. Correlate terminal state and lifecycle release.</div>
<div class="actor">Workflow</div><div class="event">Validate structured output, repair in place if allowed, retry from the captured source if authorized, then settle.</div>
</div>
<p>If the previous local query was skipped, the next generation skips rather than inventing history. An eligible failed model or exhausted structured response may retain a validated tip for a later generation, but its original disposition stays failed.</p>
</section>
<section id="fanout">
<h2>Fanout and model-task counting</h2>
<pre>research = workflow.fanout(
key: ["research"], name: "Researcher", phase: 1,
items: scopes.map { |scope| {prompt: "You are a researcher. Scope: #{scope}"} }
)
summary = workflow.queue(key: ["summary"], phase: 2, after: research) do |records|
"You are the summary writer. Reconcile:\n\n" +
records.map(&:final_text).join("\n\n")
end</pre>
<p><code>research.members</code> is a frozen Array of real Agents. The fanout is also an ordered <code>Enumerable</code>: use <code>research[index]</code> for normal Array-style indexing and slicing, plus <code>each</code>, <code>size</code>, and <code>length</code>. Each member has <code>initial_query</code> and the full Agent interface. The aggregate has no leaf. <code>after: research</code> joins exactly the ordered initial queries, not later work declared on members.</p>
<p>Three items plus the root summary are four model tasks. The root itself is the summary Agent, so the shallow tree has one root and three fanout member children. Do not add an ordinary summary child just to host that queue.</p>
</section>
<section id="connections">
<h2>Dependencies, evidence, and lineage</h2>
<div class="channels">
<div class="channel"><h3><code>after:</code></h3><p>Orders and success-gates an operation. A lazy block receives dependency values, but Workflow does not inject them into a static prompt.</p></div>
<div class="channel"><h3><code>buffers:</code></h3><p>Attaches ordered physical evidence to fresh prompts. A command buffer adds an implicit success edge. Replay-only consumers attach nothing.</p></div>
<div class="channel"><h3>Agent lineage</h3><p>Queue order on one receiver supplies conversation ancestry automatically. Use another Agent for an independent conversation.</p></div>
</div>
<pre>findings = workflow.write_buffer(label: "Review findings", after: review) do |record|
record.final_text
end
fix = writer.queue(
key: ["fix"], phase: 2, after: review, buffers: [findings],
prompt: "You are the same writer. Apply every attached finding."
)</pre>
<p>Replay restores model records, not edits. Shared-worktree writers must not be concurrently ready. Use command and assertion gates for artifacts and tests.</p>
</section>
<section id="callbacks">
<h2>Callback timing and authority</h2>
<table>
<thead><tr><th>Ruby form</th><th>When it runs</th><th>Can append?</th></tr></thead>
<tbody>
<tr><td>Static <code>prompt:</code></td><td>During declaration.</td><td class="no">No</td></tr>
<tr><td><code>queue { ... }</code></td><td>Inside an admitted query worker when fresh work needs input. Replay can skip it; retries can call it again.</td><td class="no">No</td></tr>
<tr><td><code>write_buffer(after:) { ... }</code></td><td>Inside a fresh consuming query worker, once per evaluation for a shared handle.</td><td class="no">No</td></tr>
<tr><td><code>when:</code>, selector, assertion</td><td>Synchronously in scheduler control flow after dependencies.</td><td class="no">No</td></tr>
<tr><td>Query <code>on_error</code></td><td>After a committed failed try, before retry or settlement.</td><td class="no">No</td></tr>
<tr><td>Query <code>on_success</code></td><td>Once after final first-try or recovered success.</td><td class="no">No</td></tr>
<tr><td><code>on_done</code></td><td>After one operation's final disposition, including replay, failure, skip, or cancellation.</td><td class="yes">One finite tail transaction</td></tr>
<tr><td>Post-eval Ruby</td><td>After quiescence.</td><td class="no">Evaluation is complete</td></tr>
</tbody>
</table>
</section>
<section id="tails">
<h2>Dynamic tails stay on existing Agents</h2>
<pre>workflow.on_done(key: ["review-route"], phase: 2, after: review) do |entry, tail|
next unless entry.succeeded?
next unless entry.value.data.fetch("verdict") == "issues"
findings = tail.write_buffer(label: "Findings", after: review) do |record|
JSON.pretty_generate(record.data)
end
fix = tail.queue(
agent: writer, key: ["fix", "round-2"], phase: 2,
after: review, buffers: [findings],
prompt: "You are the same writer. Apply every attached finding."
)
workflow.on_done(key: ["recheck-route", "round-2"], phase: 2,
after: fix) { |next_entry, next_tail| ... }
end</pre>
<ul>
<li><code>tail.queue</code> requires a predeclared <code>agent:</code>. Its source and generation follow that Agent's local lineage.</li>
<li>Tails may add queues, commands, selectors, assertions, inline or derived buffers, and another done control.</li>
<li>They cannot add Agents, fanouts, external buffers, or steers.</li>
<li>Dependencies may name settled operations or earlier declarations in the same transaction.</li>
<li>Validation and publication are atomic. One invalid declaration rejects the batch.</li>
<li>Each transaction is finite. Recursive correction needs a finite round or cost bound and an explicit stop branch.</li>
</ul>
</section>
<section id="replay">
<h2>Version-3 replay and staged recovery</h2>
<p>Replay identity uses Workflow ID/nonce, typed structural Agent path, receiver-local operation key, generation, and try. Child and fanout-member path segments have distinct types. Titles, tags, prompts, profiles, dependencies, callbacks, retries, repairs, and buffers are absent.</p>
<p>Generation zero and try zero occupy the stable Agent leaf. Other generations and tries are siblings under it. Human display uses <code>try-2</code> for the first retry.</p>
<p>A live abort stops the operation. A later authorized evaluation with the same identity may launch one recovery from the validated interrupted canonical tip, preserving conversation ancestry and filesystem effects. Consumption is durable before preparation or admission; a failed or interrupted recovery cannot renew it. Completed recovery is reusable, and the original ABORT remains failure history. Early abort before input publication is supported only when exact occurrence/admission metadata and a sent ABORT directly after the validated boundary prove the rolled-back prompt case. This does not authorize recovery from arbitrary incomplete history. Dependents unblock only after recovery succeeds.</p>
<p>Adoption proves ownership and the admitted start separately from completion. An exact admission marker, a validated operation prompt and canonical ancestry, sent operation turns, and service-confirmed inactivity at the same tip permit recovery when the terminal endpoint is absent. The tip may be a prompt, partial assistant output, tool output, or a validated compaction summary whose original operation prompt remains provable. This consumes the same one-shot recovery allowance without inventing an ABORT or success.</p>
<p>Adoption otherwise fails closed. Exact Workflow, Agent, query, parent, CWD, boundary, marker, and canonical history must agree. Duplicate or ambiguous candidates fail. Active runs, missing or changed admission markers, unsent work, earlier terminal markers, altered history, and wrong-parent leaves do not authorize endpoint-less recovery.</p>
<p>Creation begins with a random opaque ASCII staging name containing only a fresh token and a SHA-256 digest that binds the token to the expected setup identity. It embeds no raw Workflow, structural, leaf, or turn identifiers. The first setup config write persists the exact setup identity; the stable Agent or query identity is the final commit marker. After a crash between create and commit, a later evaluation may finish only the exact staged leaf with matching envelope or config identity, ancestry, root, CWD, boundary, and canonical source history. Staged query validation runs before lazy prompt, buffer, allocation, or evidence preparation and repeats immediately before setup writes and prompt admission. Multiple staged matches fail.</p>
<p>Immediately before an occurrence identity write, Workflow refreshes raw exact-identity matches and the union of matching envelopes and setup markers from the service. It requires no competitor and repeats that authoritative check after identity commit, after staging cleanup, and immediately before provider admission. Any conflict visible at those checks blocks admission. The leaf/config API has no compare-and-swap, conditional write, lease, or cross-connection claim, so this is not a linearizable cross-process lock: two same-nonce evaluators could each finish a final read before the other's write is visible. Run one evaluator per Workflow ID/nonce, or use distinct nonces for concurrent runs.</p>
<table>
<thead><tr><th>Change</th><th>Forces model replay?</th><th>Action when fresh work is required</th></tr></thead>
<tbody>
<tr><td>Prompt, callback, dependency, profile, or buffer content</td><td class="no">No</td><td>Version the operation key and affected downstream keys.</td></tr>
<tr><td>Workflow nonce</td><td class="yes">Yes</td><td>Use only when a wholly fresh root is intended.</td></tr>
<tr><td>Command reached again</td><td class="yes">Commands always rerun</td><td>Inspect its disposition and assertion gates.</td></tr>
<tr><td>Declared steer causal path</td><td class="yes">Yes</td><td>No extra barrier is needed for that path.</td></tr>
</tbody>
</table>
</section>
<section id="results">
<h2>Results and navigation</h2>
<pre>result[query]
result[fanout]
result[fanout[0].initial_query]
result[command]
# Rejected because an Agent can own many operations:
result[fanout[0]]</pre>
<p><code>WorkflowResult#[]</code> accepts operation handles, not Agents. The fanout aggregate is the natural dependency and result handle for its ordered initial queries. Its disposition has ordered <code>member_dispositions</code>. Later member generations have their own query handles.</p>
<p>Dispositions expose operation, state, value, error, attempts, member dispositions, workflow, agent, and owner. <code>success?</code> means no unresolved failure or cancellation. <code>recovered?</code> means some query succeeded after a failed try. <code>clean?</code> means success with no failed query try.</p>
<p>Query result, assistant turn, command result, steer result, query failure, disposition, buffer, tail, and WorkflowResult handles expose <code>workflow</code> where defined by source.</p>
</section>
<section id="references">
<h2>Exact references</h2>
<table>
<thead><tr><th>Need</th><th>Authority</th></tr></thead>
<tbody>
<tr><td>Signatures, validation, replay, and results</td><td><a href="../ez-agent-ruby/lib/ez_agent/workflow.md"><code>EzAgent::Workflow</code> reference</a></td></tr>
<tr><td>Agent-facing reviewed repository builder</td><td><a href="../../cmd/ez-agent-builtin/internal/builtin/skills/skills/workflow/patterns/builder.md"><code>builder.md</code></a></td></tr>
<tr><td>Typed service lifecycle</td><td><a href="jsonl-api.html">JSONL API</a></td></tr>
<tr><td>Visualizer payload</td><td><a href="ruby-workflow-0.1.html"><code>ruby.workflow//0.1</code></a></td></tr>
<tr><td>CSV encoding</td><td><a href="ez-agent-csv.html">EzAgent CSV</a></td></tr>
<tr><td>Ruby addon overview</td><td><a href="../ez-agent-ruby.md">Ruby addon</a></td></tr>
</tbody>
</table>
</section>
<footer>Human author guide. Source, exact API documentation, and persistent tests remain the detail authorities.</footer>
</main>
</div>
</body>
</html>