Runbook: gate decisions, gate timeouts, crash recovery and schedules for agents+gates runs (W2, core#4424)
Companion to agents-gates-claude-runtime.md (R1/R2). That runbook covers how a run parks at a gate. This one covers what happens next: who may decide the gate, how the decision reaches the run, what a timeout does, how a crashed run comes back, and how schedule triggers fire.
1. What arms, where
| Piece | Process | Armed when | Code |
|---|---|---|---|
| Decision authorizer (who may decide a gate) | agent-orchestrator (the approval service) | always. A gate row of source orchestrator-session is never decidable without it | internal/workflow/gatepolicy |
| DecisionPublisher arm (decision → resume) | agent-orchestrator | always registered; delivers only once the agents+gates mode is armed | internal/workflow/gatesweep (Publisher) |
| Gate and crash sweeper, every 15 s | agent-orchestrator | agents+gates mode armed (WORKFLOW_AGENTS_GATES_ENABLED + runtime deps) | gatesweep.Sweeper, cmd/agent-orchestrator/agentsgates_w2.go |
| Schedule runner, every 30 s | context-engine | WORKFLOW_AGENTS_GATES_ENABLED | internal/workflow/schedule |
Boot logs: agents+gates gate sweeper interval=15s; agents+gates schedule triggers armed tick=30s misfire_grace=1h0m0s timezone=UTC (or not armed, with the reason).
2. Who may decide a gate
The decision is checked in approval.Service.RecordDecision, before the first-write CAS. Every decision path goes through this check: the portal /approvals, the workflow AnswerRunPrompt RPC (what X1's answer_run_prompt and the portal prompt card call), Quad, and email. A refused decider gets PermissionDenied (approval: the decider may not decide this approval: <reason>). The row stays pending, and a workflow_gate_decision_refused audit row is written.
The rules come from the run's definition snapshot, never from the approval row:
- The decider must be an active human member of the run's org. Agent members and suspended or removed members never qualify.
GATE_ANSWERER_SCOPE_ANYONE: any such member.GATE_ANSWERER_SCOPE_REQUESTER: the run'srequester_member_id, resolved once at trigger. For a schedule or event run it resolves to the workflow's owner. If that owner is not an active human member, nobody qualifies and the gate cannot be decided. It then times out under itstimeout_policy. This is the resolve-or-refuse ruling, #4466 S4.GATE_ANSWERER_SCOPE_TEAM: a directorg_unit_membershipsrow inteam_id, for a unit that is not deleted. Membership is not inherited from parent or child units.- After the gate escalates, the audience is
timeout_policy.escalate_to. The original audience no longer qualifies. - Clearance: the decider must be at or above the gate's
required_clearanceand the row's floor. This holds for every gate kind, including input gates. - A governance-imposed gate (
governance:<policy>) may be decided by any active human member except the run's requester and its triggering actor, at or above the run's own clearance. This is architect ruling 7 on #4466. - The run must be parked on this gate. A decision on a gate of a cancelled, finished or moved-on run is refused.
3. From decision to resume
- When a decision is admitted, the CAS records it and
DecisionPublisherfires. - The
orchestrator-sessionarm builds the runReffrom the row (org, andmetadata.run_id). It callsResumer.ResumeDecidedon a bounded pool of 8, never on the RPC goroutine. The resume drives the run's next segment on this process. The session comes from the SessionStore, so any worker can serve it. ErrUndecidedandErrStaleApprovalare no-ops. They are counted, and the stale case is audited asworkflow_gate_decision_ignored.- If the pool is full, or the decision landed on a process where the mode is not armed, the sweeper delivers it on its next tick. A parked run whose row is decided is always swept.
4. Gate timeouts and escalation
- The sweeper owns the exact deadline. On its first sweep of a parked run, it stamps
metadata.gate_deadline = requested_at + timeout_minutesandexpires_at = gate_deadline + 5 min. The approvals scheduler's own expiry is only a backstop. - A governance-imposed gate has no timeout policy. It gets 24 h, and its expiry fails the run.
- At the deadline, the sweeper voids the row and delivers the
timeoutoutcome.FAIL(or unset): the run endsfailed(timeout).ESCALATE: the run re-parks on the same row. The sweeper re-opens that row toescalate_tofor another window, counted from the re-open, and recordsescalation_level + 1,metadata.gate_escalated_atand aworkflow_gate_escalatedaudit.- A second expiry fails the run.
- Rejections follow
on_reject.FAIL(or unset) ends the run.RETURN_TO_ORCHESTRATORresumes it with the rejection and reason. This is applied byrunstoreon R2'sResumeDecided. - A cancelled run's pending gate is voided by the sweeper (
workflow_gate_voided).
5. Crash recovery
- Orphaned runs. A run is orphaned when it is
running, its session is bound and its lease has lapsed. The usual causes are an orchestrator process that died or a segment that broke without an outcome.- The orchestrator's own claim loop picks these up every 2 s.
- The sweeper also calls
Recoverer.RecoverOrphans(1)for each orphan it finds, on the same bounded pool, every 15 s. - Every claim of a run with a bound session is a recovery, whichever path claimed it (claim loop or
RecoverOrphans). The claiming process logsrun.recovered(run_id,org_id,session_id,owner), countsworkflow_runs_recovered_total, and auditsworkflow_run_recoveredonce per run per 10 minutes per orchestrator process (the dedupe is in memory; core#4616: on dev the claim loop won every recovery, and only the sweeper audited). - Re-fired tool calls are idempotent on their hop key (
run:step@ordinal).
- Graceful stop (SIGTERM). agent-orchestrator stops agents+gates right after the health server (readiness drops first) and before the other servers and the pgx pool (
Orchestrator.Shutdown, at most 20 s of the 35 s budget). It stops claiming, and each in-flight segment ends without an outcome: a hook call in flight gets no reply, the worker stream is dropped, the segment's running time is recorded and the lease is released at once. The next claim, on this host after the restart or on another, resumes it in the same session. A store closed after a timed-out drain is only ever seen by a segment that is already being cut (core#4616). - The resume of a cut segment. With no gate answer and no deferred call to re-fire, the worker sends a recovery prompt that tells the model the platform interrupted the run, that a call denied by the stop did not run, and that a call already running when the run was interrupted may have completed (check before re-issuing a side-effecting call). Such a re-issue is a new hop key (
@2), so hop-key idempotency does not dedupe it: the at-least-once window ADR-0020 and ADR-0023 already state. A prompt-less resume of such a session waits for input forever (the pinned CLI, measured). A gate resume, or a session still parked on a deferred call, stays prompt-less so the call re-fires. - Wall time.
max_wall_minutesbounds the time the session spends running, across segments and processes (an interrupted segment's time is recorded on release). Time parked on a gate, or with no process holding the run, is not counted. A segment overruns its remaining wall by at most the worker's 15 s interrupt grace. - Task-less runs. A
runningrun with no task anchor that is older than 10 minutes is failed (workflow_run_abandoned). Claim never picks these runs up. - Completion is earned (core#4625). A session that stops
completedwithout a final output (an empty last turn, a sub-agent that returned nothing, an upstream failure the CLI reported as success) ends the runfailed(error)withstate_detailstartingno_output:, then the last upstream error the CLI reported (upstream API error 502 (server_error), retry 1 of 10) orthe model produced no final output. The orchestrator enforces it whatever the worker sends. An upstream 5xx that left nothing is retried once in the same segment by resuming the session. Cost: a persistent outage spends two rounds of the CLI's own retry backoff (about 3 minutes each) before the run fails, still insidemax_wall_minutes.
6. Schedule triggers
- A definition's
scheduletriggers become rows inworkflow_schedules. A trigger onworkflowsderives them whenever the definition, status or deletion changes. Only active, undeleted agents+gates workflows have rows. - Cron is five fields, in UTC. It accepts
*,?, lists, ranges, steps and the namesJAN-DECandSUN-SAT. When both day fields are restricted, a day matches either one. - A new schedule fires first at the next slot after it was armed. Nothing is back-filled.
- Exactly once per slot. Each run is started as the workflow's owner, through
TriggerWorkflow, with the idempotency keyschedule:<cron>@<slot RFC 3339>. Duplicate starts collapse on(workflow_id, idempotency_key), whether they come from retries or from two context-engine replicas. - Misfire. If context-engine was down past one or more slots, it fires the latest missed slot once, provided that slot is at most 1 h old. Older slots are skipped and audited (
workflow_schedule_skipped). - A transient start failure, including
FailedPrecondition, is retried on the next tick with the same key. It is retried until the misfire window passes. - A scheduled definition must not require inputs. A schedule supplies none, so
TriggerWorkflowrefuses the run (InvalidArgument) and the slot is skipped and audited. - No owner. A workflow whose
created_byis not an active member is skipped and audited (owner_unresolved).
7. Observing it
| Signal | Where |
|---|---|
| Audit actions | workflow_gate_decision_refused, …_decision_ignored, workflow_gate_timed_out, …_escalated, …_voided, workflow_run_recovered, workflow_run_abandoned, workflow_schedule_fired, …_skipped (migration 293) |
| INFO log events | run.parked, run.gate_delivered, run.gate_timed_out, run.gate_escalated, run.gate_voided, run.recovered, run.abandoned (structured run_id, session_id, approval_id; to move onto internal/obslog when #3477 lands) |
Metrics (agent-orchestrator/workflow-gates) | workflow_gate_deliveries_total{result,decision}, workflow_gate_sweeps_total{action}, workflow_runs_recovered_total, workflow_runs_abandoned_total, workflow_runs_orphaned (gauge) |
Find a parked run and its gate's state:
SELECT r.id, r.run_state, r.pending_gate_id, r.pending_gate_escalated, a.status, a.expires_at,
a.metadata->>'gate_deadline' AS deadline, a.metadata->>'answerable_by' AS audience
FROM workflow_runs r JOIN governance_approvals a ON a.id = r.pending_approval_id
WHERE r.org_id = :'org' AND r.run_state IN ('awaiting_approval', 'needs_input');
8. Acceptance on dev (coordinator + founder)
- Slice-2 demo. Trigger the SDLC workflow. It parks at
founder-signoff(before_agent:coder). Approve at/approvals/<pending_approval_id>as an L5 member. The run resumes into the coder and completes. Repeat the approval as an L2 member: it is refused and the row stays pending. - Governance gate. Give the run's team a policy that requires approval for the
coderdispatch, with no definition gate. Then:- the requester's approval is refused;
- another member's approval resumes the run.
- Timeout. Set
founder-signoff.timeout_policyto{timeout_minutes: 1, on_timeout: FAIL}. Within about 75 s the run isfailed(timeout). WithESCALATE, the row is pending again withescalation_level = 1, and onlyescalate_tocan decide it. - Crash. Kill agent-orchestrator mid-segment. Within one lease TTL plus 15 s,
run.recoveredis logged and the run continues in the same session. Adocker restart(SIGTERM) releases the lease at once, so the new process recovers it within one claim tick of starting; the dying process logsorchestrator: segment interrupted; releasing for recovery, neverclosed pool, and the session has no turn the model wrote after the cut. - Schedule. Add
{"schedule": {"cron": "*/5 * * * *"}}to an active definition with no required inputs. One run starts per 5-minute slot, withtrigger_key = schedule:*/5 * * * *. A context-engine restart within the slot starts no second run.
Local proof is go test -tags integration ./internal/workflow/ -run TestW2_, run against a scratch DB on both connection classes.