Maintainer notes on src/workflow/. The workflow file format and the driver contract are in the Workflows and Advanced workflows guide pages.
Each rule below spans more than one file. The rule names the code that owns it, so you can read the details there.
-
A run ends only in
settleRun. The sharedfinishRunpath calls it when settling reaches the top workflow's result, before it hands any lease back or out, and on a call that takes no lease too.reportAttemptfirst reconciles earlier reports, so an end cancels a later report before it can advance the revision. It records an accepted outcome and never ends the run. After a failed report, the nextnextskips the dependents and ends the run. Respond, cancel and retry inrun-controls.ts, and next inengine.ts, share that path. Whole-run cancel settles directly ascancelled, without reconciling another round. To run code when a run ends, hook intofinishRun. Do network I/O only afterwithRunreleases the run lock. That path queues the end record, a local write, under the lock, and saves whether it did in the run'sendRecordQueuedfield. WhenupdateRunthen fails to save the run file, the queue is one save ahead of the run file, and the nextnextsettles the run again and overwrites the queued<run>.end.json. A laternextreports a record state only for a run whose field is true (runRecordStateinrecords.ts). -
Reconcile the latest report before applying another or handing out a lease.
reconcileRun, shared byleaseNextandreportAttempt, settles every driverless transition to a fixpoint at the run's current revision, throughsettleScopeandsettleItems, including workflow starts, fan-out expansion, render failures and bound exhaustion.reportAttemptadvances the revision only after it, so only the latest revision can be unreconciled. A reached end applies before a loop decision. Only after reconciliation doesleaseNexthand back an omitted open lease or issue the first ready leaf in declaration order that this driver can take. A running workflow occupies its parent's position in that order. Settling returns every ready leaf in that order (ready), andleaseNextwalks it. A ready item does not count againstmax_paralleluntil it is leased, and onenextleases at most one step, so a held-back item leaves its room to the next one without exceeding the cap.canTakeLease: falsestill reconciles driverless transitions. Every changed run is saved, including await. -
A report is checked against the revision of its own lease.
reportAttemptandretryStepincrementrevision; skips,if,end, and the creation of child steps insidenextnever do. A lease keeps the run revision it was handed out at, andreportAttemptcompares a report with that, so the report of a parallel lease does not make it stale. An attempt that is not an open lease keeps the older answers:stale_revisionwhen its revision is not the run's, otherwisewrong_attempt. -
An end or break stops what is still open under its workflow.
stopWherecancels every leased step under the workflow that reached the end, its sub-workflows included, and keeps the attempt on the step and incancelledAttempts. It cancels running workflow steps there and skips pending and waiting ones. The walk takes a path predicate and failure. End and break construct their own end_reached failure; manual cancel and retry supply theirs. Step descendants use the sameisUnderpredicate asarchiveUnderinloop.ts. Cancel records the ids this walk changed before reconciliation can settle or skip other steps.reportAttemptanswers a cancelled attemptlease_cancelledbefore it checks the driver;cancelledAttemptsis never trimmed. Everynextanswer lists incancelledthe attempts the driver says it runs that are no longer its open leases, so the driver learns of a cancellation from any answer,doneincluded. -
The local driver overlaps steps that do not share a checkout.
runLocalDriverruns up toworkflows.max_parallelsteps (local config, default 1) and sends the ones it has started asrunning. A command with no workspace, and a prompt in the current checkout, share that checkout, so only one of them runs there at a time. A prompt earlier in the queue for that checkout blocks a later command there. The driver starts the prompt when the checkout is free and fewer thanmax_parallelsteps are in flight; commands in other worktrees keep running. A prompt with its own worktree does not take the checkout. A headless prompt takes one of the slots, and the driver keeps leasing steps for the others while it runs. An interactive prompt uses the terminal, starts only when no command is running, and no step is leased while it runs. Oncancelled, it drops a held lease, and it stops a running command with SIGTERM, then SIGKILL after 5 s while any captured descendant or process in a detached group remains, even after its command exited. Attached commands snapshot their descendant tree and start times before stopping, then probe and send SIGKILL only to descendants whose start times still match. If the identity snapshot fails, only the shell is stopped; detached commands use their process group. It does not send a stopping command asrunningagain, sonextdoes not cancel it twice. Dying commands still take a slot, and a new attempt of their step waits until they are gone. The signal policy followsmax_parallel. At 1, a command runs in teamai's process group, asenv execruns one (src/env-exec.ts): the terminal's Ctrl-C reaches it, and it can read/dev/tty. A signalenv execwould pass on (SIGTERM or SIGHUP, and SIGINT or SIGQUIT when the terminal does not reach the command) makes the driver stop the command, wait for it, and exit with that signal. Above 1, each command runs detached in a process group of its own, with no terminal, and SIGINT, SIGQUIT, SIGTERM or SIGHUP makes the driver stop every group, wait for them, and exit with that signal. Windows usestaskkill /T /Fin place of the group kill. Staging runs inside the attempt at everymax_parallel(stageThenStart), so the driver keeps polling while it stages, and a cancel aborts staging. A step whose attempt was cancelled, or whose lease expired, while it staged never starts.stageLeasecallsrunSetup(setup.ts) last, only in a workspace it just created, with setup's own keys, and removes the worktree when setup fails. -
A workspace is a git contract on the lease, and the driver is the only code that touches git.
planWorkspaceinworkspace.tschooses the mode. An explicitworkspacewins. A command that omits it is read-only, even inside a copy; when it exits 0 and changed the checkout, the driver fails itread_only_dirty. That includes a commit that leaves the worktree clean, a switch to another branch or a detach at the same commit, a change that only stages an existing edit, another staged hunk that leaves the status mixed, a permission change on a file that was already dirty, an edit to a quoted non-ASCII path, a symlink whose target changes while the file it names stays the same, and an edit to the destination of a staged rename, and a change inside a submodule that was already dirty. An interactive prompt that setsworkspace: read-onlyis checked the same way. An interactive prompt that does not may change the checkout, and those edits stay. Conflict paths, including agent files, are read without Git's quoting, so a non-ASCII name is still checked for leftover markers. A prompt that omits it continues the nearest enclosingneworcontinueworkflow, and afor_eachancestor makes thatnew, so items do not share a worktree.leaseNextputs the contract on the lease fornewandcontinue, and for a read-only step inside a copy (mode: 'read-only',merge: []). That reader's branch is the one its declaredneedswrote or read (changesorread, through items and children, but notafteritems or inherited needs), or the enclosing copy's when they touched none; needs on several branches failworkspace_base. It needscontinueincan.workspaceand the copy's owner, ascontinuedoes. A read-only step outside any copy gets no contract and runs in the active checkout. The local driver stages a reader without merges, takes its snapshot over the base overlay, and afterwards restores the overlay; when the step changed the copy or left its branch, it keeps the state onrefs/teamai/kept/<attempt>(git add -A, thenwrite-treeandcommit-treeon HEAD; not the stash list, which every worktree shares), and pushes each submodule commit that tree records and the read commit does not into the checkout's git dir asrefs/teamai/kept-modules/<attempt>/<commit>(at any depth, without the user's push hooks orpush.recurseSubmodules), since a gitlink does not keep its commit reachable once the copy is removed, then runsgit checkout -f <branch>,git reset --hardto the commit it read,git clean -fd, andgit submodule update --checkout --recursiveon the submodules it changed, so a later writer never commits a reader's edits. It resets nothing when a repository among the changed paths has uncommitted or untracked files, or a nested submodule commit its parent does not record, which the keep cannot hold. The copy counts as put back only when HEAD isrefs/heads/<branch>at that commit andgit status --porcelain --untracked-files=all --ignore-submodules=noneprints the same lines it printed when the reader was staged; ignored files are left in place. Otherwise the reader failsworkspace_base.stageLeasewrites ateamai-unrestoredmarker, with that status, in the worktree's git dir before the reader's overlay, and the driver removes it once the copy is put back or left untouched, so a driver killed mid-reader still leaves it.stageLeaserefuses later leases in a marked copy until the copy is back, when it removes the marker. A status line does not show content, so a marker whose status was not empty stays until the person who puts the copy back deletes it.ensureWorktreealso refuses an existing worktree whose HEAD is not on its branch or a directory that is not a worktree, and prunes and recreates one whose directory was deleted. The reader reportsread(branch,base,commit) and neverchanges.reportreturnsinvalid_reportforreadon any other lease, and forchangesor a success withoutreadon a reader's lease.run.copies[].commitand fan-outbranchesfollowchangesonly.cleanupcomes from the lease's contract, so a reader that was the copy's last user removes it too.leaseNextholds a step back for this driver, and tries the next ready leaf, when the driver'scan.workspacelacks that mode, or when acontinuecopy belongs to another driver (run.copies). It answerswait, with every held step's reason joined by;, only when every ready leaf is held back. Driver capabilities stay out ofreconcileRun, whichreportAttemptand the run controls also call. It failsworkspace_basewhencontinuehas no enclosingnew, or when the run has no base.workflow startin a git checkout records the base (commit, and the branch unless HEAD is detached); otherwise the firstnextthat sendsbasesets it, and a laterbasenever changes it. The local driver fails a lease whoseworkspaceit cannot read withworkspace_baseinstead of running it in the active checkout. The branch isteamai/<runId>/<path-safe step path>/p<pass>(branchName); a[n]in the path becomes-n. The first branch inneedsorder is where the step starts, and the rest are merged in that order. An item'safterbranches come first. The local driver (local-driver.ts,worktree.ts) adds the worktree under<checkout>/.teamai/workflow-worktrees/, pointscore.hooksPathat an empty directory, and replacesAGENT_PATHS(AGENTS.md,CLAUDE.md,.agents,.githooks, and each defaulttoolPathsentry's project directory, project MCP file and Copilot.githubpaths) with the run's base commit. An agent path under a symlinked parent failsbase_configbefore anything is copied or removed, since both would follow the link. It then gives the worktree the inlinepulla new worktree gets (prepareCheckout), which delivers the team's skills, rules, agents and MCP and records that checkout's team revision. The overlay is taken after that delivery, so those files are not the step's commit. A path the step edits is committed. A step that left HEAD off the leased branch failsworkspace_basebefore anything is committed, reported aschanges, or pushed, and the worktree stays as it left it. A path it leaves untouched is put back from the branch. A merge conflict stops the merge: a command failsmerge_conflict, and a prompt is told the branches that remain. Snapshots and commits read submodules with--ignore-submodules=none, and aftergit add -A, which skips a submodule whoseignoreisall, each submodule is staged by name, sosubmodule.<name>.ignoreanddiff.ignoreSubmoduleshide no change from a reader's check, its keep, or a writer's commit. The driver commits asTeamAI <teamai@localhost>and reportschanges(branch,base,from,to,commits). It pushes whenoriginexists and this step made commits, whether the step succeeded or failed, and also when a later attempt adds no commit but this branch has commitsorigindoes not have, including a first push that never landed and an origin with no tracking refs yet. A failed push fails a step that succeeded withpush_failed, and the worktree stays.reportsetscleanuponly when the step succeeded and no step that can still run uses that branch, judged on the run as the nextnextsettles it: steps a loop runs again count, and a workflow orfor_eachstep that has not started counts by the branchplannedBranchgives, the one around it unless it opens its own; only then does the driver rungit worktree remove --force. It does not delete the branch, and it never resets, cleans, or switches the active checkout. A command that starts its own sandbox, such asdocker, stays read-only. What it writes does not feednew,branches, or a later step.session: continueandsession.fromare step reads. The engine puts{ tool, id }on the lease, withearlier, the sessions that one continued, newest first, and never copies a session. The driver resumes Claude and Codex by that id, copies another tool throughAgentSession.copy, restores a copy from the team session archive when neither works, and tries eachearliersession the same way before it starts fresh. OpenCode has no resume flag, so it starts fresh. A driver that continued the lease's session or an earlier one, by that id or in a copy, echoes the one it continued asresumedin its report. One that started a new session leavesresumedout.reportAttemptanswersinvalid_reportfor aresumedon a step that resumes no session, and for one that no pass of the run reported and no link continued (knowsSession). When the reportedtoolandsessiondiffer fromresumed,reportAttemptappends{ from: resumed, to }torun.sessionContinuations.sessionOffollows those links from the session a step would resume, taking the latest link from each session, so a later step resumes the copy that holds the last turns, whichever machine or tool made it. The snapshot publishes the links, soresumableSessionson this machine and the claim on the next one both see them. A step that resumed by the same id adds no link, so a run on one machine with one tool leases the same sessions as without links. -
A driver pushes the commits it reports, and fetches the commits it is leased. Every driver keeps these two git rules, so a run another driver or another machine continues finds each commit on
origin. Wheneveroriginexists, a driver pushes the commits it reports inchangesbefore it reports them, failed steps included; the local driver'sfinishWorkspacepushes for every outcome. A push that fails still reports the commits. A step that succeeded failspush_failed. A step that failed keeps its own failure, and the push sentence is added to its message: a retry must fix the step first, and apush_failedin its place would hide that cause from the person and from the run record. Before it starts from, merges, or applies a lease commit (start, eachmerge[]entry,configCommit), a driver checks it withgit cat-file -e <c>^{commit}. For a missing one it fetches+refs/heads/teamai/<run>/*:refs/remotes/origin/teamai/<run>/*, and checks again, since a refspec fetch that matches no branch exits 0. A fetch by commit id is not used: a server can refuse it, and a fetched commit no ref holds can be collected later. A commit still missing failsworkspace_basenaming the commit and its branch, before anything merges or runs, so it is never a file-lessmerge_conflictor a prompt told to resolve one. The local driver does this instageLeasethroughfetchMissingCommits.workflowGitConformanceScenariosinconformance.tschecks both rules against a bare origin, andworkflow-git-conformance.test.tsruns them against the local driver. -
A run changes machines only through
handoff.ts.publishRunand the claim behindclaimRunandresumeRunare the only writers ofworkflows/runs/<run>/state.jsononteamai-reports, and they write it insideupdateReports. A publish writes only while origin shows this install (installOwner, from<dataHome>/workflows/owner.json) and the state revision this machine last saw (acknowledged). An unchanged body writes nothing. A publish checks the business origin without a lock, then answersstate_movedwhen, under the locks, the run's base, a copy's commit, or the sessions it archived differ from what it checked (checkedOutsideLocks). Anything else that moved meanwhile is published as the locks find it, so a run a driver is still advancing can be published.resumeRuncontinues a run locally when origin has no snapshot and this machine never saw one acknowledged (stateRevision0), since no other install can have claimed it. A claim reads origin under the reports lock and releases it, decides outside the lock (definitionsOfcan fetch and sync a shared clone, andcheckOriginrunsls-remote, only for a running run: a settled one leases nothing until a retry reopens it, and the local driver'sreconcileTakenCopieswaits for that too), then writes only while origin still holds thewriteid it read (replaceSnapshot). The compare key is thewriteid, not the revision, because two claims of one revision both writestateRevision + 1. A moved or missing snapshot answersstate_moved. Everynextthat answersdone, and every run control, callspublishRunEnd, which runspublishRunwhen the run was published and has ended, so origin never hands out a run its owner finished. A publish drains the run's records first, so none lands after its end. The drain (publishPendingRecords) drops the records of a run whose snapshot on origin names another install, so an install that ends its copy of a run it lost never replaces the owner's record. Once the end is on origin, a repeat writes nothing, so an end that a process saved but stopped before publishing reaches origin on the next request. A claim changes steps only throughtakeOverinstep-state.ts: it releases a lease, and repends a lease in anewstep so its next pass gets a new branch.handoff.tsnever imports the engine. The engine callsclaimRunfor theclaimfield ofnext, andworkflow publish --sessionspasses the engine'sresumableSessionsin. What the snapshot carries is a rule table per type insnapshot.ts(publish,drop, orrewrite), so a new run or step field does not compile until it has a rule, andparseSnapshotrefuses a field it would drop. -
The end reached first wins. A reported step's
settledAtis the revision its report made. Every terminal transition, including a skip or cancellation, carriessettledAt. A step the engine settles takes the run's current revision, which is that of the report that caused it, because every earlier revision was reconciled before that report was accepted. An open lease it fails takes the revision it was leased at, and a cancellation the winning end's revision.reportAttemptaccepts a report only afterreconcileRunhas applied every end reached before it, so an end a later report reaches never competes with an earlier one. Every endsettleScopehas yet to apply was reached at the run's current revision, and it applies the one declared first. The winner therefore does not depend on whennextruns between reports. -
A break is a nameless succeeded end. A succeeded step whose
breakholds competes with the steps that reached an end by the same rule. It ends its workflow, or that workflow's loop, as success. Its value cannot change after its step succeeds, because pull rejectsbreakinside a step loop's range, where a previous-pass read could change. -
A workflow loop is decided when a round has nothing left. Once every step of a looping workflow has settled and no end or break was reached,
decideRoundinloop.tsevaluates the workflow'sloop.while. When it is false, the workflow ends with the round's outcome and outputs. Otherwise every step of the workflow repends for the next round, unless the workflow has runmax_iterationsrounds: then it failsloop_exhausted(WorkflowResult.failure, andrun.failure, shown indone, at the top). A failed step alone does not stop the loop. The round is kept on the step that runs the workflow (Scope.runner), sorependresets it with that step, or on the run at the top. Pull rejects a step loop in a looping workflow. -
A step waits for every step it reads.
readsOfcollects the steps that the step's expressions (stepExpressions), templates, andwithread. For a step that runs an inline workflow, it also collects the outer steps that the inline steps read.skipUnreachableuses that set to decide readiness. If a new field reads steps, add it tostepExpressionsortemplatedTexts. Otherwise the step can read a value before it exists, or an inline workflow can wait forever. A step outside a loop that needs or reads a step inside it also waits until the loop owner is settled (waitsForinloop.ts), and is neither skipped nor ready before. -
A read of a later step in the same loop is a previous-pass read, and never waits.
previousinloop.tsclassifies it: the target is in the reader's loop range and needs the reader, directly or not. For an inline step, the reader is the step that runs its workflow. Pull allows the read, the engine leaves it out of the reads a step waits for, andexpressionStepsgives the reader the target's latest archived pass (previousPass), which holds no pass fields on pass 1. Classify a new kind of read throughprevioustoo, or pull and the engine disagree on it. -
A step loop is decided once per run of its owner. After checking for an end,
settleScopecallsdecideStepLoopfor each succeeded owner withoutloopFinal. A falsewhilesetsloopFinal. Otherwise the range runs again throughrepend, unless awhileowner has runmax_iterationstimes, which fails itloop_exhausted. A loop withoutwhileis bounded where the owner's action would start, after the skip rule andif, for a leaf and a workflow step alike (exhaustedAtStart). The owner counts its runs initeration. Pull rejects ranges that share a step and loops that wait for each other (loopProblems), so the engine does not check them again. -
A pass id is never reused.
rependmoves a step's current pass into itspassesand bumpspass.archiveUndermoves what a repended workflow orfor_eachstep ran intorun.archive, each pass stampedwithinwith the step path and pass that archived it, andfirstPassstarts a new instance after every archived pass of its path. The full record of a run isrun.steps, with each step'spasses, plusrun.archive; a run record, scorer, or budget reads both.steps.<id>.passesis a step'spassesplus its current pass once it settled (passesOf). The expression projection keepsresultsfor afor_eachpass, including inpreviousPass. Pull checks the same outputs-or-results shape in step reads and workflow output aliases. -
An expression reads its absolute paths, wherever they are.
expressionPathsreturns everyinputsandstepspath, including those inside function arguments and predicates, and never a relative path such as.size, which reads the current element of a predicate.readsOf,skipUnreachableand the pull read checks use it, so a new kind of expression must return its paths there. -
Expression types are checked in two places, through
typeProblems.parseExpressionrejects what an expression shows by itself, such asx < 'a'orany(...) < 1.readDiagnosticschecks paths against the types the workflow declares. It checks each path only in the workflow that owns it, so a predicate an inline step runs over an enclosing step is reported once. -
Pull and the engine share one list of templated fields, one list of step expressions, and one list of actions. The templated fields are in
templatedTextsand the expressions, such asifandbreak, instepExpressions, both intemplate.ts. HITL declarations normalize inparse-hitl.ts. The actions are inSTEP_ACTIONSintypes.ts. Add a new field or action there, not to a copy inparse.tsorengine.ts. Pull, the cache'sprompt_filecheck, the lease render andreadsOfall split a template withparseTemplate, which decides which{{ … }}is a template, and the render evaluates it withevaluateExpression, as for anif.parseReadsinengine.tsand the step parse inparse.tskey a table by each expression, so a new one does not compile until both say how to read it. -
A new step status must fit
stopped(),settled()andstopWhere(). All three are instep-state.ts.stopped()decides which dependents are skipped, which steps can recover, and the run outcome.settled()decides readiness.stopWhere()decides what an end or a break does to each step under it. Each switches over every status, so a status added toStepStateSchemadoes not compile until all three place it. -
Only the transitions in
step-state.tswrite step fields.waitForAnswer,answerHitl,resetPending,resetIteration,skip,lease,release,start,succeed,fail,cancel,repend,nextRound,endLoopandexhaustchange a step in place and drop the fields its new status does not have.readRunparses every step throughStepStateSchema, which gives a run file from an older teamai its defaults:settledAt0,outcomefromstatus, and no fields its status does not have. -
run.stepsis replaced, never changed in place. Its type isreadonly, soaddItems,insertChildrenandarchiveUnderadd or remove instances by assigning a new array. An instance'sidisreadonlytoo, so an instance cannot move to another scope's group.statesIninscope.tskeeps the instances of every scope per array, in aWeakMap, so settling a scope reads its own instances without scanning every step. A new array starts a new index, except thatinsertChildren, which adds the instances of a workflow a step starts, carries the old index over. -
A pull check that changes what a file means carries a
code.dropsKeptVersionincache.tsremoves the cached copy when a diagnostic has acode. An older definition then cannot keep running with the new meaning. A diagnostic without acodekeeps the last valid version, but only aftercheckReferenceschecks that version again against what the workflows it runs settle to in the same sync. -
The workflow cache holds only what one sync settled.
checkReferenceschecks each file's version against the versions the other files settle to, anddropUnsettledremoves every other cache entry.startRunrelies on this: it reads the workflows a run uses from the cache and does not check them against each other again. A new way for a file to keep or lose its version goes throughcheckReferences. -
The items of a
for_eachstep settle like a workflow. When settling reaches afor_eachstep,advanceInstanceevaluates its list andaddItemsputs an instance per item right after the step; the step isrunninguntil every item settled.settleRunningsettles a runningfor_eachstep throughsettleItems, the way it settles a workflow step throughsettleScope. An item waits for the items itsafternames and is skipped when one of them stopped (afterStanding). It starts only while fewer thanmax_parallelitems are leased or running (startedItems, counted once per scan). A failed item cancels nothing; the step fails once every item settled (itemsSettled). The rules that decide the items are infan-out.ts, the settling inengine.ts. Pull rejectsfor_eachwithloop,endorbreak(loopProblems). -
itemis bound per instance, in the engine and in pull alike.contextOfgives an item its own value and any other instance its workflow's (Scope.item), whichchildScopepasses into the inline workflow an item runs. Afor_eachstep's ownifandfor_eachtherefore read the enclosing item, never their own. Pull checks the same binding:ReadSite.itemmarks the templates of afor_eachstep, andReadScope.itema workflow that runs per item. A template readsitemonly where it is bound:parseTemplatetakes the binding, which pull decides from the step and the engine from whether the context holds an item, so elsewhere{{ item }}stays text in both. A new place that readsitemmust decide its binding in both. -
Step ids are paths. A step inside a sub-workflow has an id such as
ship.check.classify, an item of afor_eachstep one such asbuild[2], and a step inside the workflow an item runs one such asbuild[2].verify.parseStepPathinstep-path.tsreads them all; don't split ids by hand. A child step exists in the run only after the engine reaches it. To find a step's definition, usestepDefinitionsinscope.ts, which reads the definitions alone, so it also finds the step of an archived pass.locateStepinengine.tsalso gives the step's scope, and needs the instances along the path. Don't look a step up by top-level id. -
What a step requires is decided once per lease, in
negotiate.offerTermsinengine.tsbuilds the offer for the ready loop and the hand-back alike, andnegotiateinrequirements.tsanswers grant, hold or fail.ENFORCEMENTclassifies every requirement as strict, which holds the step for a driver whosecandeclares it (wait.held), or best effort, which grants it and records the gap inunenforcedon the lease, the step and the record. A copy is used once an accepted report shows its step ran there: a success, anexitCode,changesorread(run.copies[].used); a staging or setup failure leaves it unused. Every lease on a copy in a workflow that declaressetupcarries it, socan.setupholds the lease, and the driver decides whether setup runs: when it creates the copy, or finds its setup unfinished (stageLease's marker in the local driver). A held hand-back cancels the attempt and releases the step; on an unused copy the driver also gives the copy up, so a capable driver can take the step, unless the driver still holds another lease in it, while a used copy keeps its owner, whose work lives there. A granted hand-back keeps its driver as the copy's owner (rememberCopy). The member'sworkflows.allowholds before any capability. Env values never enter the run: the lease carries key names inenvScope(andsetup.envScope), and the driver resolves them. Deadlines and budgets settle inreconcileRun(run, now), which runsexpire(limits.ts) first; the run deadline and the run's budget count fromrun.limitsFrom, which a retry sets when it reopens the run or finds it ended, or else fromcreatedAtwith nothing spent; a workflow step's budget counts from thelimitsFromitsstartrecords (startLimits); afor_eachstep spends its budget over all its items together (itemsSpentinsettleItems), and each item keeps only the budget of the workflow file it runs. An attempt the engine stops goes throughstopAttempt, which records it inrun.stoppedAttemptswith its step, driver and stop time, whatever its step becomes later; a late report from that driver adds its tokens once (countLateTokens), and a budget whoselimitsFromstarted at or after the stop takes them into its baseline, so it does not pay for them. Known secret values are masked at the three exits,updateRun,enqueueRecordandwriteEnvelope, each of which takes the secret set as a required argument. The set holds the value of each keyenv/secrets.yamldeclares, wherever this machine resolves it from, and each environment value whose name looks secret; masking follows the team's declarations, not what a run requires. A command resolves it once and passes it on:startRun,withRunand the run controls require it, so what the envelope masks and what the run file masks agree; the local driver also masks an attempt'sresult.jsonbefore it reports, as text when it is not JSON, and every attempt's result file when it stops driving the run, so an attempt it never reported keeps no secret either. -
A HITL request waits before any action or end.
settleScopechecks loop exhaustion first, renders a HITL request message, and moves an unanswered step towaiting. Waiting is neither stopped nor settled. An answer moves it to pending without a revision bump. Approve no skips, choose succeeds, approve yes continues. An end-only step with HITL reaches its end only after yes. The sharedtemplatedTextsmakes HITL reads participate in readiness. Onlydriver.can.hitldeclares HITL.parseNextPayloadreadsdriver.canintoNextOptions.can; storedDriverIdentityand leases contain only kind, machine and workspace. Busy polls never answer waiting HITL requests through the no-HITL rules. Only a driver declaring HITL receives a waiting request; a busy poll without HITL receives wait. An interactive step is a requirement, not a gate:negotiateholds it for a driver without HITL, on new leases and hand-backs alike. The process-only autoApprove option is never read by the JSON payload parser.respond --jsonuses the same identity schema as next, reports unread fields through ignored, and records a driver UI's declared person answer with channel driver and agent false. The dashboard answers through the samerespondToHitlwith channel dashboard and agent false, always sending the pass it showed (answerFromDashboardinsrc/dashboard/workflow-runs.ts). Answer driver identity stays local; records publish only choice, channel and agent. -
Retry validates every container before resetting any.
retryContainersinrun-controls.tsclimbs from the target through scopes and fan-out items until a running runner or the top. Each dependency cone includes needs, reads and loop waits, or item after dependencies. An independent standing end or break rejects the retry. The apply pass archives replaced passes and descendants, reopens settled runners withstartto keep inputs and round, then bumps revision and reconciles. Only the targeted loop owner's iteration resets; the top-level round does not. An answered refused approve or succeeded choose is retryable too, so a changed answer resets its dependent branches. A HITL request in the cone that is waiting, or answered and not yet run, starts a new pass too, so its answer is asked again in the new context and an answer to the old pass is stale. Unanswered skips in every affected container reset so skips caused by cancellation can run again. Retry's prelude reconciles without finishing a provisional outcome. Reopening clears the run's end, failure and endRecordQueued flag and removes its queued end file through records.ts. These three pieces stay consistent: run state, the pending end record, and published stats. The next end upserts the same record path; stats replace the origin end's outcome and duration contribution with the new end's, without adding another run. Replaying the same endedAt contributes nothing. -
The local driver keeps tools and questions interruptible. A single question joins command and prompt exits in the driver's race. An interactive tool owns the terminal alone: no question opens while it runs, and starting one aborts and closes an open question. A poll closes the question when its own step is leased or a different step or pass waits; an unrelated lease leaves it open. It polls next every second while asking, every two seconds while tools run, and aborts a replaced HITL request or cancelled prompt.
src/tool-launch/process-stop.tsshares process stopping between commands and adapters. Headless tools detach and stop with SIGTERM; interactive tools stay attached and stop with their captured descendant tree. Foreground interactive signals reuse env-exec's terminal detection and signal policy: when the terminal reaches the child, teamai ignores SIGINT and SIGQUIT, while SIGTERM and SIGHUP are forwarded and stop the driver. Interactive adapters inherit stdio and accept an optional result file. Repository edits are kept for interactive steps; only headless prompts run the read-only check. A nonzero interactive exit without a result reports its exit status.leaseNextrecords the identity of the latest driver that called next inRunState.driver, without capabilities. Resume uses this machine's open local lease workspace, then run.driver.workspace for a local driver on this machine, then cwd. Controls pass run.driver to finishRun so end records retain the driver kind. -
One local driver owns a run on this machine.
withDriverLockinlocal-driver.tstakesdriverLockPathonce withacquireLockand releases it in finally.runLocalDriverdrives inside it, andworkflow resumealso claims inside it, so a claim never lands under a driver already running the run. A live holder returnsdriver_running, including its pid, before anything is claimed or driven; the existing lock machinery reclaims dead owners. The driver lock spans tool execution and questions, whilewithRunholds a different run lock only during one engine operation. Neither lock's scope is extended by the other. Every HITL decision without a HITL driver logs once when the engine changes the step. HITL replies carry one literalrespondcommand template, which drivers display unchanged. -
Judge work never comes from
workflow next.scoring.tscomputes open judge work on everyteamai score --nextfrom facts already on disk: the run files, the scorersstartRunpinned inrun.scorers, theinstallIdthatreportAttemptstamps on each pass it settles, thewithinstamp on archived passes, and the labels, attempts and on-demand requests (teamai score --run) under<dataHome>/scores/. Nothing else is queued. The engine has no scoring code path, and scoring never writes a run file, so a run's counts, tokens, failure andendedAtcannot move and it settles without waiting. A judge lease settles only throughteamai score:--lease <ref> --submit, or--lease <ref>and--run, which run the local judge and settle through the same submit path.workflow reportanswersjudge_lease. A driver never lists a judge ref inworkflow next'srunning, which holds step attempts only: judge refs go inscore --next'srunning, which renews them.
Test parsing through parseWorkflow and syncWorkflowDefinitions. Test the engine through startRun, leaseNext, and reportAttempt. Every driver must pass workflowConformanceScenarios in src/workflow/conformance.ts, which runConformanceScenario in src/workflow/conformance-interpreter.ts runs, and a driver that takes workspace leases the git scenarios in conformance.ts too. That one list takes in the scenarios a concern keeps in its own file, such as limits-conformance.ts, so a runner cannot miss one. If a driver can see a new behavior, add a scenario to the file for its concern; a new file joins the list in conformance.ts.