Skip to main content

Runbook: the Claude runtime for agents+gates runs (R1 core#4421, R2 core#4422)

Audience: whoever arms agents+gates execution on a stack and whoever onboards an org onto it. The contract is internal/workflow/orchrt (README "Rules the worker end must keep"). The Go side is internal/workflow/orchsession and cmd/agent-orchestrator/agentsgates*.go. The worker side is services/agent-worker/src/agent_worker/orchestrator/.

1. What must be true before the mode arms​

agent-orchestrator logs one boot line, agents+gates orchestrator mode armed=<bool> reason=.... It arms only when every row in this table holds:

RequirementWhereIf missing
WORKFLOW_AGENTS_GATES_ENABLED=true on both context-engine (accepts runs) and agent-orchestrator (drives them)envreason=WORKFLOW_AGENTS_GATES_ENABLED is off
The worker pool / routeralways presentreason=no agent-worker pool/selector
A Model Gateway route minter: PLATFORM_SIGNING_KEY[_FILE] + _ID + PLATFORM_ISSUER, and MODEL_GATEWAY_BASE_URL. The mint audit sink is always wiredenvreason=no Model Gateway route minter .... Sessions never egress to a provider directly
agent-worker image built from a tree with claude-agent-sdk==0.2.180 (bundled Claude Code 2.1.321)imagethe worker refuses: no stream handler
SessionStore (R2): migration 292 applied; the orch_session_store role provisioned by dev/postgres/session-store-role.sql (compose db-roles runs it after migrate); the worker has WORKER_SESSION_STORE_DSN or WORKER_SESSION_STORE_DSN_FILE naming that rolemigration, role, worker envRuns still execute, but a parked run resumes only on the worker that parked it; any other worker answers the resume with session transcript is not on this worker and the run fails. A configured store that is unreachable refuses the segment (start refused: session store: ...): a session that cannot be stored must not run, because it could not park
The workflow's team has an APPROVED anthropic-dialect Model Gateway endpoint binding that admits the orchestrator's and every roster agent's model. The model is the definition override, or else the agent's agent_configurations.model_id. The Claude Code CLI speaks only the Anthropic Messages API, so openai_compatible endpoints are not reachable from this path, even with translationteam bindingsCreateWorkflow, UpdateWorkflowDefinition and TriggerWorkflow refuse with InvalidArgument … model "<m>" is not enabled for the team on any of its bound endpoints, naming the override or agent_ref <ref>, configured model. (A team with no bound endpoint is not restricted here; such a run then fails in the CLI. See the query below.) Admission does not check dialect; a model admitted only through an openai_compatible binding passes these checks and fails in the CLI — dialect-aware admission is #4576 ask 2

Every agent of a run needs a model. A definition's model (orchestrator or roster entry) overrides the agent's own; when it is empty, the orchestrator reads the agent's agent_configurations.model_id. An agent with neither fails the run (orchestrator: agent has no model), and the worker refuses an empty model, so a session never runs on the Claude Code CLI's own default model (which the Model Gateway refuses) (#4421). Every agent_ref must also resolve to an active agent of the org: an unknown, deleted, unmapped or paused agent fails the run permanently (orchestrator: agent is not an active agent of the org), because the credential locator would refuse to mint for it on every retry.

Orchestrator sessions are always Model-Gateway-routed. The route is minted for the orchestrator agent whatever its agent_configurations.gateway_routed column says: that column is the ExecuteStep path's direct-egress knob, and an orchestrator session has no direct-egress arm (principal-architect ruling on #4532, review 5920147128).

Diagnostic: the team's bindings, their dialect and the models each admits. Run it as the migrator role, with app.org_id set:

SELECT e.name, e.dialect, e.status, leu.approval_status, leu.binding_kind,
e.model_ids, leu.enabled_models
FROM llm_endpoint_units leu
JOIN llm_endpoints e ON e.id = leu.endpoint_id AND e.org_id = leu.org_id AND e.deleted_at IS NULL
WHERE leu.org_id = :'org' AND leu.unit_id = :'team' AND leu.deleted_at IS NULL
ORDER BY e.dialect, e.name;

At least one row must have dialect = 'anthropic', approval_status = 'approved' and endpoint status = 'approved', and it must admit every model the run uses. enabled_models NULL means the binding admits all of the endpoint's model_ids.

Optional, with the same meaning as for ExecuteStep turns:

  • MCP tokens. Set MCP_GATEWAY_ENABLED or MCP_GATEWAY_TENANTS, plus MCP_GATEWAY_PUBLIC_BASE_URL, on the orchestrator, and WORKER_MCP_TEAM_GATEWAY_URL on the worker. Without them, agents have no MCP tools. A roster entry with a non-empty tools_allowlist then refuses the start: an allowlist that matches nothing is a vocabulary error, not an empty agent (#4448 ruling).
  • Worker state. WORKER_ORCHESTRATOR_STATE_ROOT is local scratch: one CLAUDE_CONFIG_DIR per org (orgs/<org>/claude) and one working directory per run. With the SessionStore, a segment's local transcript is deleted when the segment ends, so nothing durable lives there. Without the store it is the only copy: it must survive worker restarts, and it is deleted when the run stops for good. A resume tries the worker the last segment used and, when that worker cannot open the segment, any other worker.

1.1 The SessionStore and its role (founder decision #4422 c6958175273)​

The Claude Agent SDK mirrors every transcript line of an orchestrator session to the store and, on a resume, materialises the session from it into a temporary CLAUDE_CONFIG_DIR before it spawns the CLI. That is what lets a run parked on one worker resume on another.

Table (migration 292)HoldsRole grant
orchestrator_sessionsone row per SDK session, bound to exactly one run of one org (composite FK to workflow_runs (id, org_id), ON DELETE CASCADE)SELECT, INSERT, UPDATE(updated_at)
orchestrator_session_entriesthe transcript lines (goal, inputs, tool I/O, personas: tenant data)SELECT, INSERT
orchestrator_session_hooksthe worker's ordinal book: the run:step@ordinal key each forwarded call was givenSELECT, INSERT
  • Role. orch_session_store: LOGIN, NOSUPERUSER, NOBYPASSRLS, NOINHERIT, no role membership, connection limit 32. It has no DELETE, no TRUNCATE, and nothing on any other table: no workflow_runs, no members, no business table. It can SELECT the global plan_catalog, which migration 073 grants to PUBLIC; that table has no org_id. The provisioning script ends with a self-check that walks every relation in public and every SECURITY DEFINER function, and it RAISEs if the role can reach anything else. Run the script again after any migration that grants to PUBLIC.
  • Isolation. All three tables FORCE ROW LEVEL SECURITY on app.org_id. Every worker statement runs in a transaction that sets app.org_id to the stream's x-tenant-id and carries the org explicitly. The store is built per segment, pinned to one org, one run and one session. A key that names another session is refused before any SQL runs. A session that is already bound to another run is refused.
  • Provisioning. On the dev stack, compose db-roles runs the script on every up. By hand, as the migrator role, after migrations: psql -v ON_ERROR_STOP=1 -v store_role=orch_session_store -v store_password="$PASSWORD" -f dev/postgres/session-store-role.sql. It must print verified orch_session_store holds only the session-store grants.
  • Credential. Dev compose builds WORKER_SESSION_STORE_DSN from ORCH_SESSION_STORE_DB_USER and ORCH_SESSION_STORE_DB_PASSWORD. The localhost-only dev default is allowed by ADR-0001 §7.1, the same rule as app_rw. A hosted deployment mounts the DSN from its secret store as a file and sets WORKER_SESSION_STORE_DSN_FILE. Never commit it to a repo .env. The worker connects directly to Postgres, not to pgbouncer, and never logs the DSN. To rotate the password: re-run the script with the new password, update the secret, then restart the worker.
  • Retention. A transcript is evidence. The audit chain and llm_usage_events are the records of truth. agent-orchestrator deletes a session's rows once its run has been terminal for WORKFLOW_SESSION_TRANSCRIPT_RETENTION_DAYS (default 30, at least 1, hourly), and rows also cascade with their run. A malformed value stops the mode from arming. The SDK's temporary resume directory is removed when each segment ends.
  • Provisioning is atomic. The script runs as one transaction. When the self-check fails, nothing is applied: no grant, and on a first run no role.
  • Residuals, accepted and recorded (backend-security L3/L4 on #4589):
    • The CLI leaves non-transcript files in the org's CLAUDE_CONFIG_DIR after cleanup: .claude.json, backups and the plugin cache. No tenant text was measured in them. Cleanup removes only the session's transcript and the run directory.
    • The worker's DSN reads every org's session rows. It is a cross-tenant read credential by design: one worker serves every org. Isolation rests on the worker process, which binds every statement to the stream's org, and on RLS. A compromised worker process can read every org's transcripts; it cannot read any business table.
  • Where the store's own tests run. services/agent-worker/tests/pg_session_store_integration.py exercises the adapter against Postgres on both connection classes. It needs ORCH_SESSION_STORE_TEST_ADMIN_DSN and ORCH_SESSION_STORE_TEST_DSN, and it runs locally and in the #4562 lane, not in the PR lanes: the agent-worker PR lane has no Postgres and forbids skips. The PR lanes run the in-memory double (test_orchestrator_cross_host.py).
  • Down. Migration 292's down drops the tables. A parked run then cannot resume on another worker. The role stays and loses its grants; re-run the script after re-applying 292.

2. Governance an org needs, and why (fail-closed families)​

tool_action and agent_action fail closed on no match (governance.FailsClosedOnNoMatch). The bridge governs:

  • every MCP call as tool_action / tool:<platform_tool>, where platform_tool is the gateway's {server}.{tool}, never the SDK name;
  • every dispatch as agent_action / <roster agent_ref>;
  • the gate tool as tool_action / tool:raise_gate.

With no allow row for these, every call is denied before any gate is consulted. That includes every on_request gate (architect F4 on #4532).

The gate tool is platform-owned: its control is the on_request gate itself, which always defers to a human. Seed it per org, together with the roster's dispatches and its tools. There is no migration, because policies are org-scoped rows (org_governance_policies, FORCE RLS) and a migration cannot seed orgs created later. Use the governance store's upsert (governance.Store.UpsertOrgPolicy). In SQL, as the migrator role:

BEGIN;
SELECT set_config('app.org_id', :'org', true);
INSERT INTO org_governance_policies (org_id, action_type, target, effect, min_clearance)
VALUES (:'org', 'tool_action', 'tool:raise_gate', 'allow', 0), -- on_request gates
(:'org', 'agent_action', 'product-manager', 'allow', 0), -- one row per roster agent_ref
(:'org', 'agent_action', 'architect', 'allow', 0),
(:'org', 'tool_action', 'tool:github.get_issue', 'allow', 0) -- one row per platform tool an agent may call
ON CONFLICT (org_id, action_type, target) DO UPDATE SET effect = EXCLUDED.effect, min_clearance = EXCLUDED.min_clearance;
COMMIT;

Do not seed tool_action with target *. A wildcard allow lifts the fail-closed mask, and any before_tool gate then becomes the only control on every tool (#4448 ruling §1).

3. Acceptance​

3.1 R2: a deferred gate parks, the worker restarts, the run resumes into the coder (core#4422)​

Local first, $0. Run this against a throwaway database. It uses the real bundled CLI, a scripted Messages API, the real Postgres store as orch_session_store, and two worker processes, with worker 1 stopped between the park and the approval:

# scratch DB migrated to head, app-role.sql and session-store-role.sql provisioned
DATABASE_URL=postgres://upsquad:...@127.0.0.1:<port>/<name>_test?sslmode=disable \
ORCH_SESSION_STORE_DSN=postgres://orch_session_store:...@127.0.0.1:<port>/<name>_test \
go test -tags integration,workerpy -run TestClaudeRuntime ./internal/workflow/ -count=1 -v

On dev, the coordinator runs this with the founder.

  1. Prerequisites. §1 and §1.1 must hold. docker logs upsquad-dev-db-roles must show the orch_session_store ... verified line, and the worker env must have WORKER_SESSION_STORE_DSN. Seed §2 for agent_action on all three roster refs, tool:raise_gate, and every tool the roster calls.
  2. Definition. Use a 3-agent roster (for example architect, coder, qa) with one gate {id: signoff, kind: APPROVAL, placement: {before_agent: "coder"}, answerable_by: ANYONE}. This gate is hook-enforced: the hook defers the orchestrator's Agent dispatch of coder, whatever the model decides (#4422 c6940228491). Trigger it.
  3. Park. The run must reach run_state = awaiting_approval with pending_gate_id = 'signoff', a pending_approval_id, and lease_owner NULL, meaning compute was released. Check that workflow_run_hops has <run>:coder@1 bound to that approval. The store must hold the session: SELECT (SELECT count(*) FROM orchestrator_session_entries e WHERE e.org_id = s.org_id AND e.session_id = s.session_id) FROM orchestrator_sessions s WHERE s.run_id = :'run' (with app.org_id set) must be greater than 0. find /mnt/data/upsquad-dev/agent-worker-orchestrator-state -name '*.jsonl' must print nothing.
  4. Zero tokens while parked. Record count(*) of llm_usage_events for the orchestrator agent, and the run's consumed_usage. Both must be unchanged when you approve.
  5. Different worker. Recreate the worker: docker compose -p upsquad-dev ... up -d --force-recreate --no-deps agent-worker. That is a new process, and its scratch directory holds no transcript. For a second host, start another worker container with its own empty state root and stop the first.
  6. Approve at /approvals/<pending_approval_id>. The resume needs W2's decision subscriber (#4424). That subscriber routes source = orchestrator-session decisions to orchestrator.Resumer.ResumeDecided, which this PR provides. ResumeDecided reads the outcome from the approval row, applies it to the run and drives the resume segment. Until W2 lands, no production component applies an approval decision to an agents+gates run, and the run stays parked.
  7. Resumed into the coder. The run must complete in the same orchestrator_session_id. workflow_actions must have a coder row with status completed, and <run>:coder@1 must be executed in workflow_run_hops. The worker log must show the segment on the recreated worker.
  8. raise_gate and its negative control (moved from R1). Run a second definition with an on_request gate whose goal tells the orchestrator to call raise_gate first. The run must park with needs_input or awaiting_approval. Then remove the tool:raise_gate seed (§2) and trigger again: the call must be denied with the governance reason, not parked. Restore the seed afterwards. on_request is model-initiated, so a model that never calls the tool proves nothing either way; re-run if needed.

3.2 R1: 2-agent run, live DAG, cost reconciliation​

On a stack where §1 holds and §2 is seeded for the org:

  1. Trigger. Trigger an agents+gates workflow with a 2-agent roster through X1: the platform MCP trigger_workflow tool with a seat token, or WorkflowService.TriggerWorkflow. Record run_id.
  2. Run. Watch the orchestrator log for agents+gates orchestrator mode armed=true, then the run's claim. Stream the live DAG with StreamRunStatus, or open the portal's run page. Both dispatch nodes must reach completed, and workflow_runs.run_state must reach completed.
  3. Projection. Run SELECT step_name, status, cost_usd FROM workflow_actions WHERE run_id = :'run': one row per dispatch, each with its cost bucket.
  4. Reconciliation. workflow_runs.cost_usd is the SDK's estimate, consumed + segment as the worker reports it. The record of truth is llm_usage_events, written by the Model Gateway for the orchestrator agent's token, because one CLI process makes all of the session's model calls. Compare sum(llm_usage_events.cost_usd) for that agent over the run window with workflow_runs.cost_usd. Sub-agent buckets (workflow_actions.cost_usd) are per-dispatch estimates from each sub-agent's transcript; their sum is at most the run total, and the remainder is the orchestrator's own turns.
  5. Gate. See §3.1 step 8.