Skip to content

feat(drivers): claude-cloud AgentDriver — run a phase as a claude.ai cloud session instead of a nested local CLI #1137

Open

Description

@admarble

Context

sequant run executes every phase through an AgentDriver (src/lib/workflow/drivers/agent-driver.ts: executePhase(prompt, config), isAvailable(), canResume(), resolvesSkills, usesSdkMcp) with four adapters: claude-code, codex, opencode, aider. All four spawn a local subprocess.

The 2026-09-24 matcha-maps credit plan needed to spend claude.ai cloud credits on a 16-issue backlog and found that the orchestrator cannot run there: a cloud session receives API credentials through a proxy, not as shell env, so a nested claude CLI has no auth. The plan therefore hand-rolled the driver: a local coordinator fires one one-shot cloud session per issue-phase (routine API via RemoteTrigger, or claude --cloud "<prompt>" on CLI 2.1.281), polls list_runs / get_run_log, reads the PR and the verdict comment, and continues locally. That loop is an AgentDriver in everything but name, and rebuilding it per project by hand loses the ledger, the tiering policy, the timeout, the token metrics (#986/#944) and the conformance guarantees (#1096).

Observed in the #1079 cloud run (sequant, 2026-09-17, Sonnet 5, 67 turns, 536 s): project-scope skills, hooks and CLAUDE.md load; npm ci, lint, build, suite and a mutation check ran; git commit passed the hook; the push failed only on GitHub App permissions.

Fix shape

src/lib/workflow/drivers/claude-cloud.ts:

Launch mechanism (decided in the /spec comment, 2026-09-24): use the routines/sessions API (POST /v1/code/triggers one-shot + run, then poll GET /v1/code/sessions/{id}/events). claude --cloud "<prompt>" cannot create a session without a TTY on CLI 2.1.282: it errors with --cloud requires an interactive terminal and, with -p, --cloud cannot be combined with --print. claude -p "<msg>" --cloud <cse_id> is used only to steer an existing session.

Gate (owner decision, 2026-09-24; tracked as #1151): no exec until the Phase-0 probes are posted here:

  • P-1: a Node process can authenticate to /v1/code/triggers with the token from claude setup-token.
  • P-2: the trigger accepts a model.
  • P-3: the raw events carry usage/modelUsage.
  • P-4: the call that stops a live session.

If P-1 fails, #1137 is parked. No LLM-mediated launcher shim.

Environment variables (owner decision, 2026-09-24): static values go in a dedicated cloud environment for the driver, which sets SEQUANT_CHECKOUT=in-place and SEQUANT_ORCHESTRATOR=sequant-run. Per-run SEQUANT_ISSUE/SEQUANT_PHASE go in the prompt preamble. The existing "Sequant in-place" environment stays unchanged: with SEQUANT_ORCHESTRATOR set, /exec skips its progress comment and defers the GitHub update to an orchestrator, and human-run sessions on that environment have none.

Conformance (#1096) mapping: item 1 commit inside the cloud sandbox (observed in #1079); item 2 gh api rate_limit from the session; item 3 typed errors need the routines API's real failure text (capture it during a Phase-0 probe, not synthesized, per #1115's rule); item 4 env injection via the session environment; item 5 tokensUsed > 0 from the run's usage; item 6 project-scope /exec load (observed).

Acceptance criteria

  • AC-1: the driver is registered and the conformance suite enumerates it; every contract item passes or names a tracking issue in its skip reason — Evidence: npx vitest run src/lib/workflow/drivers/__tests__/driver-conformance.test.ts -t "claude-cloud" green
  • AC-2: isAvailable() returns false with a named reason when no environment id or cloud auth is configured — Evidence: unit test in src/lib/workflow/drivers/claude-cloud.test.ts
  • AC-3: with run.agent: "claude-code" and run.phases.exec.agent: "claude-cloud" (the feat(run): per-phase agent selection — run.phases.<phase>.agent #1150 key), exec dispatches to the cloud driver and qa to the local claude-code driver — Evidence: src/lib/workflow/phase-executor.test.ts case asserting the driver chosen per phase, using feat(run): per-phase agent selection — run.phases.<phase>.agent #1150's resolvePhaseAgent
  • AC-4: a run exceeding run.timeout is stopped by the driver and reported as the existing timeout outcome, not as success or an unknown failure — Evidence: unit test with a fake poller
  • AC-5: after a cloud exec completes, sequant worktree resolve <N> in the local repo returns a worktree on the pushed branch — Evidence: integration test against a fake remote
  • AC-6: when the session events carry usage (probe P-3), AgentPhaseResult.modelUsage has non-zero input and output tokens; when they do not, tokens are reported unmeasured (never 0) and turns plus duration are recorded — Evidence: unit test on the run-log mapper against both a captured with-usage fixture and a captured without-usage fixture
  • AC-7: docs page for the driver covers the dedicated environment and its two static variables, the no-secrets rule, dependency install from the preamble, the absent gh, permissions.ask stalls, per-phase driver and model selection, the timeout behaviour and the daily fire cap — Evidence: grep -l "claude-cloud" docs/reference/*.md non-empty
  • AC-8: npm run build && npm test green — Evidence: CI test job
  • AC-9: the session's tool policy excludes mcp__Claude_Code_Remote__* and PushNotification — Evidence: unit test in src/lib/workflow/drivers/claude-cloud.test.ts asserting the trigger request body
  • AC-10: the prompt preamble never carries SEQUANT_WORKTREE or any secret value — Evidence: unit test on the preamble builder in src/lib/workflow/drivers/claude-cloud.test.ts
  • AC-11: the driver refuses to fire, with a named reason, when tracked .claude/settings.json or .claude/settings.local.json has a non-empty permissions.ask — Evidence: unit test in src/lib/workflow/drivers/claude-cloud.test.ts over a temp project
  • AC-12: the run-log mapper takes the first result: after the phase prompt, not the last, and reads duration from duration=, not timestamps — Evidence: unit test on a captured fixture with four result: lines
  • AC-13: the one-shot trigger is deleted or disabled after its run, on success, failure and timeout alike — Evidence: unit test with a fake transport asserting the cleanup call on each path
  • AC-14: <branch>--session-<id> checkpoint branches never resolve as the issue's worktree branch — Evidence: unit test on sequant worktree resolve with a checkpoint branch present
  • AC-15: phase cost is reported as unmeasured, never $0, until the run's usage is observed — Evidence: unit test on the result mapping in src/lib/workflow/drivers/claude-cloud.test.ts

Non-Goals

  • MCP servers inside cloud sessions
  • Running qa in the cloud by default
  • Working around the routines daily fire cap (document it; there is no claude --cloud fallback, since it cannot create a session headlessly)
  • An LLM-mediated launcher if P-1 fails (park instead)

Graph metadata

Related

#1096 (conformance) · #1115 (usage and typed errors for the other drivers) · #497 / #862 (the last two driver additions) · #1049 (no-progress wall) · #944 (cost baseline — cloud runs report real per-phase tokens) · #1079 (the proving run)

Activity

  1. added
    enhancement
    multi-agent
    on Sep 24, 2026
  2. admarble commented on Sep 24, 2026

    @admarble
    ContributorAuthor

    Phase 0 field facts from the matcha-maps credit run (2026-09-24) — two one-shot routines on an Anthropic-hosted environment (env_011CUvi781XSsaoVy7qTLDfS), Sonnet 5, each running one issue to a PR: admarble/matcha-maps#1046 (59 turns, 476 s) and admarble/matcha-maps#1047 (102 turns, 1094 s). Full notes: docs/internal/graph-2026-09-credits/HANDOFF.md in that repo.

    (a) SEQUANT_* in the session environment or in the prompt preamble? Neither the trigger nor the session can carry per-run env vars: RemoteTrigger create with session_request.environment_variables is refused (see b). The environment's own variable store does reach the shell — the worker's probe (node -e "console.log(JSON.stringify(Object.keys(process.env).filter(k => /^(SEQUANT|NEXT_PUBLIC|CLAUDE)/.test(k)).sort()))") printed the four NEXT_PUBLIC_* keys set in the environment UI plus ~50 CLAUDE_* keys and no SEQUANT_*. So: a static SEQUANT_* set can live in the environment store (one value per environment, not per run); anything per-run (SEQUANT_ISSUE, SEQUANT_PHASE) has to ride in the prompt preamble. Note env/printenv are permission-denied in the sandbox (Permission to use Bash with command env has been denied) and the repo's vendored hook blocks unanchored env greps — probe with node -e and print key names only. Relevant CLAUDE_* keys seen: CLAUDE_CODE_REMOTE, CLAUDE_CODE_REMOTE_SESSION_ID, CLAUDE_CODE_REMOTE_HERMETIC_MODE, CLAUDE_CODE_SESSION_ATTENDED, CLAUDE_CODE_HOLD_UNANSWERED_PARKED_PERMISSION, CLAUDE_CODE_CONTAINER_ID, CLAUDE_CODE_ENVIRONMENT_RUNNER_VERSION.

    (b) Verbatim routines-API failure text (HTTP 400 both; no quota/auth/cap failure was hit in two runs):

    {"error":{"message":"session_request.environment_variables is not supported on triggers — trigger configs are persisted and replayed on every fire","reason":"unsupported field","type":"invalid_request_error"},"request_id":"req_011CfMp4xgPGew7jpQFbRocr","type":"error"}
    {"error":{"message":"run_once_at must be in the future","reason":"run_once_at in past","type":"invalid_request_error"},"request_id":"req_011CfMqqc1o3bUqsobyDaBDM","type":"error"}
    

    (c) Complete get_run_log fixture: docs/internal/graph-2026-09-credits/fixtures/get_run_log-P0-1.txt in admarble/matcha-maps (newest page of session cse_01R9TaSCgCDzyiJ97rt3wL3B, verbatim as the RemoteTrigger tool returns it). The shape the mapper needs: result: success is_error=false turns=59 duration=476s permission_denials=5 — <final assistant text>; a run can carry several result: lines because the session is re-woken by PR events (this one had four). Older pages are reached with cursor (here 252 → 52 → first event). Non-transcript event kinds are summarised in a header line (system/hook_response ×63, …), not listed.

    (d) Does a run stopped mid-way leave a readable partial log? Not exercised: neither probe overran. What was exercised: the worker of #1046, after "STOP", called mcp__Claude_Code_Remote__send_later and created its own follow-up routine (persist_session: true, "keep re-arming until the PR is merged"); RemoteTrigger update <id> {"enabled": false} cancelled it (HTTP 200, enabled:false read back, no run row created). Stopping a live session through the API is still untested. Two related facts the driver must plan for: (1) a permission prompt event on npm ci blocked run #2 for ~4 hours and resolved within a minute of the owner's local Claude Code session waking from laptop sleep — the same prompt auto-resolved in <1 s in run #1 while that session was awake — so run.timeout enforcement by polling is necessary but the driver also needs the permission mode / auto_mode_* config sorted out or runs will stall unattended; (2) gh is not installed in the environment (which gh → none); workers used the GitHub MCP connector (mcp__github__create_pull_request, issue_read, add_issue_comment) and plain git push (write access via the Claude GitHub App).

    Other observed: project-scope skills load only when the prompt names the Skill tool (skill "spec", args "979") — told merely to "invoke /exec", run #1's worker never called it and followed the prompt's inline discipline; the vendored hooks (pre-tool.sh conventional-commit and env-dump guards) and a user-level stop hook run in the sandbox; npm ci 37 s, jest suite 2 min 17 s, npm run build ~65 s on the sandbox.

  3. admarble commented on Sep 24, 2026

    @admarble
    ContributorAuthor

    Design implications from the Phase 0 facts above (coordinator-side reading, 2026-09-24). Each one changes an AC or the fix shape; fold into /spec when this unblocks.

    1. Containment: exclude the Remote MCP tools. The docs(graph): wave-2 execution record — D18–D20 and the post-wave ledger #1046 worker, after "STOP", called mcp__Claude_Code_Remote__subscribe_pr_activity and mcp__Claude_Code_Remote__send_later, creating its own follow-up routine with fix-and-push authority. The driver's allowed_tools (or the prompt's session rules) must exclude mcp__Claude_Code_Remote__* and PushNotification. Same class as fix(containment): a phase agent killed its own orchestrator — no Bash signal guard, no process-group isolation, machine re-prompts read as human consent #934, one layer up.
    2. Env injection (conformance item 4): static SEQUANT_* in the environment's variable store, per-run SEQUANT_ISSUE / SEQUANT_PHASE in the prompt preamble. The conformance probe must be node -e over process.env — env and printenv are permission-denied in the sandbox and the vendored hook blocks unanchored env | grep.
    3. permissions.ask in the repo's tracked settings reaches the cloud session. admarble/matcha-maps tracks .claude/settings.local.json with "ask": ["Bash(npm ci)", …]; both runs logged a permission prompt event on npm ci. Run 1 resolved in <1 s while the owner's local Claude Code client was connected; run 2 blocked ~4 h while the laptop slept and resolved within a minute of it waking. The routines docs say routines "never stop for approval"; the log says otherwise. Driver preflight: scan .claude/settings.json + settings.local.json for permissions.ask and refuse (or warn loudly) before firing — a blocked run burns wall-clock and, per the 2× stop rule, would be killed as an overrun.
    4. gh is absent in cloud environments. The spec skill's preflight printed GITHUB_AVAILABLE=false; workers used the GitHub MCP connector. The driver docs must say: install gh via the environment's setup script, or accept MCP-only and make the platform preflight non-fatal.
    5. Run-log mapper (AC-6): a session carries several result: lines (PR-event re-wakes of 2–7 turns each); the phase outcome is the first result: after the prompt, not the last. Event timestamps are unreliable after a sandbox re-provision (~4 h skew observed); read duration= from the result: line. The condensed log's result: line carries turns, duration, permission_denials and no token counts — AC-6 (modelUsage non-zero) needs a usage field from the sessions API that Phase 0 did not see. Verify it exists before keeping AC-6 as written.
    6. Stop (AC-4): RemoteTrigger update {enabled:false} cancels a scheduled routine; stopping a live session is untested. AC-4 needs the actual session-stop call identified first.
    7. Cost sensor: the usage page showed $250.00 of $250 after ~26 min of Sonnet across both runs. Until the page or the API exposes spend, the driver reports turns and duration and marks cost as unmeasured rather than $0.

    Fixture for item 5: docs/internal/graph-2026-09-credits/fixtures/get_run_log-P0-1.txt in admarble/matcha-maps.

  4. admarble commented on Sep 24, 2026

    @admarble
    ContributorAuthor

    Phase-0 evidence from the #1136 dogfood (sequant, 2026-09-24)

    Not the matcha-maps credit run, but it answers the same four questions. Sessions: cse_01NXWtKRSMZZPhMXuBkTtjbx (died at setup) and cse_01W6MSXo6CpVP1WmyNMwxWVz (opened PR #1142). Environment env_01QXpqvWm6CyRyTgxsA4C62d ("Sequant in-place").

    1. SEQUANT_* in the session env: only what the environment config sets. printenv | grep '^SEQUANT_' inside the session printed exactly SEQUANT_CHECKOUT. Nothing from the orchestrator leaks in.
    2. Real failure text: a setup script of npm ci fails because it does not run in the repo checkout: npm error code EUSAGE … can only install with an existing package-lock.json. The runner logs env[error]: Setup script failed and the session ends result: error_during_execution is_error=true turns=0 duration=0s errors=["Setup script failed with exit code 1."]. Put dependency install in the prompt instead.
    3. Run-log shape: GET /v1/code/sessions/{id}/events works for ad-hoc web sessions, not only routine runs. It returns runner lines (env[info]: Allocating sandbox, Cloning repository, Using existing repository clones on resume), init: model=… cwd=…, tool calls with truncated results, and a terminal result: line with turns and duration. Pages of 200 events, newest first, next_cursor for older.
    4. A stopped run leaves a readable log: yes, including the zero-turn one.

    Also relevant to the driver: no gh in the sandbox (exit 127), so skill bash that shells out to gh fails; the clone is shallow (51 commits), which false-fails evals-fixture-commit.test.ts (#1140); a skill-created feature/N-slug branch pushes despite the session's claude/… outcome branch; claude -p '<msg>' --cloud <cse_id> delivers a mid-turn follow-up within seconds; the repo's Stop hook errors in the cloud.

  5. admarble commented on Sep 24, 2026

    @admarble
    ContributorAuthor

    Addendum to item 1 (containment): cancelling one self-scheduled routine does not stop the chain.

    The matcha coordinator disabled the worker's first send_later routine (trig_01Lnfk8WPJjcoDKdmYqUye5m) at 07:07Z and recorded the chain as stopped. The routines API shows it was not: the worker's earlier PR-event wake had already armed trig_016sycASWYkdQtJSZuwhHxrv (07:07Z), and each subsequent fire armed the next — trig_014iU1WQGhvdGxRs2s93UeEc (08:09Z), trig_01KvkCQFHjQ46g3cdkgvBpzF (09:11Z), trig_01J2X4J4jpCGSDwWfGmTVKwj (10:13Z). Every fire re-provisioned a sandbox and ran ~6 turns in the original session cse_01R9TaSCgCDzyiJ97rt3wL3B (persist_session: true), so list_runs on the new routines shows no rows; the evidence is only in the session's own log. The chain ended at 11:12Z because the PR merged, not because anything stopped it. Against a PR that never merges, the prompt's own rule ("keep re-arming until merged or closed") runs until the credits are gone.

    Driver consequences: (1) exclusion of mcp__Claude_Code_Remote__* from allowed_tools is the only reliable guard — a stop-rule that disables routines by id chases a moving target; (2) the driver's stop path must act on the session (or kill its subscription), and Phase 0 still has not identified that call (item 6); (3) the run-log mapper must treat every result: line after the first as a wake, and the driver should sum them into the phase's cost rather than report only the first run's turns=.

  6. admarble commented on Sep 24, 2026

    @admarble
    ContributorAuthor

    Complexity: Complex (8 ACs + 7 derived, 4 directories)

    Decision: routines API to launch; claude --cloud only to steer

    Recommendation: launch each phase through the routines/sessions API (POST /v1/code/triggers one-shot + run, get_run_log / GET /v1/code/sessions/{id}/events). Use claude -p "<msg>" --cloud <cse_id> only for mid-run steering. claude --cloud "<prompt>" cannot start a session from a driver. Observed today on CLI 2.1.282; both commands failed during argument parsing, before any session was created:

    $ claude --cloud "Reply with the single word OK and stop." </dev/null   # stdout piped
    Error: --cloud requires an interactive terminal.
    Non-interactive invocations (piped stdout, --init-only, --sdk-url) run locally and would silently ignore --cloud. Drop --cloud, or run from a TTY.
    
    $ claude -p --cloud "Reply with the single word OK and stop."
    Error: --cloud cannot be combined with --print.
    Starting a new cloud session with --cloud is interactive only: drop --print, or drop --cloud to run locally. To message an existing cloud session instead, pass its ID: `claude -p "message" --cloud <session-id>` (find IDs at claude.ai/code).
    

    A driver spawns a subprocess with piped stdio, so creating a session with --cloud is ruled out. The alternative, faking a TTY, is the pattern that SIGKILLs at ~106 s (#856). Two more facts count against it even where it works:

    • --environment accepts only self-hosted ccpool_… pools. An env_… id can only be chosen through the remote.defaultEnvironmentId setting.
    • There is no branch flag and no env-var flag.

    claude -p "<msg>" --cloud <cse_id> does work headless, and delivered a mid-turn follow-up within seconds on 2026-09-24. Keep it for steering.

    Routines/sessions API claude --cloud
    Headless create ✅ (matcha P0 ×2, #1079) ❌ TTY-only (above)
    Pick environment env_… ✅ on the trigger settings-only (remote.defaultEnvironmentId)
    Model per phase trigger session model field ⚠️ P-2 --model
    Per-run env vars ❌ refused (HTTP 400, verbatim on this issue) ❌ none
    Run log / result get_run_log + events API ✅ same API, by cse id
    Stop a live run ⚠️ unknown (P-4) ⚠️ same
    Auth from a Node process ⚠️ unknown (P-1): blocks the driver CLI handles it
    Costs daily fire cap; triggers persist and replay (delete after fire) none extra

    The blocker: auth from Node. Every routine so far was fired by a Claude Code session calling the RemoteTrigger tool, which has the CLI's claude.ai OAuth. The SDK's session helpers (createCodeSession(baseUrl, accessToken, …) in @anthropic-ai/claude-agent-sdk/bridge) are documented as "thin HTTP wrappers … callers supply their own OAuth token". Reading the CLI's keychain token from sequant is not an option we should ship. Before any code, probe P-1:

    • P-1 (auth): does POST /v1/code/triggers accept the long-lived token from claude setup-token as a bearer? Yes → plain HTTP client in the driver. No → the fallback is a launcher shim: claude -p --model haiku --allowedTools RemoteTrigger --output-format json with a fixed JSON contract (create, run, poll, fetch log). That's the proven matcha coordinator shape, but LLM-mediated: roughly 1¢ per call, and not deterministic. If neither works, park feat(drivers): claude-cloud AgentDriver — run a phase as a claude.ai cloud session instead of a nested local CLI #1137.
    • P-2 (model): does the trigger's session_request accept a model field? Needed for per-phase tiering.
    • P-3 (usage): does the raw GET /v1/code/sessions/{id}/events (not the condensed get_run_log text) carry the SDK result message with usage/modelUsage? The condensed result: line has turns, duration and permission_denials, and no tokens. The SDK's browser query() streams typed SDKMessages from …/events/stream, which suggests the raw events do.
    • P-4 (stop): which call stops a live session? The CLI bundle references /v1/sessions/{id}/archive and an interrupt control request. Identify and exercise one.

    Cost: ≤ $1 (two trivial sessions). Capture every response verbatim as a fixture, with identifiers scrubbed (this repo is public).


    AC Quality Check

    lintAcceptanceCriteria flags AC-2/4/5/6 as incomplete: the error scenarios aren't enumerated. The derived ACs below enumerate them.

    • AC-3 names the wrong keys. Sequant has no run.driver: the setting is run.agent. run.phases.<phase> (PhasePolicy) holds only model/effort, and it's documented as claude-code-only. See OQ-2.
    • AC-6 may be unmeasurable as written until P-3 answers. See OQ-3.

    Scope Assessment

    Non-Goals: the "Not in scope" section: MCP servers inside cloud sessions, qa in the cloud by default, and the routines daily fire cap (documented, not worked around; the --cloud fallback it names is not available, see above). performScopeAssessment didn't see this section because of its heading.

    Metric Value Status
    Feature count 4 (driver, per-phase selection, worktree sync, docs) ❌
    AC items 8 (+7 derived) ⚠️
    Directory spread 4 (drivers/, workflow/, settings, docs/reference) ⚠️

    Verdict: ❌ SCOPE_SPLIT_RECOMMENDED. Carve AC-3 (per-phase driver selection) into its own issue. It is generic and local, has no cloud dependency, and touches every config.agent read (phase-executor.ts:1324, :1369, :1598, :2050, skills-preflight.ts:151/167). #1137 then depends on it. The rest stays together, gated on P-1.


    Acceptance Criteria

    AC-1: registered; conformance enumerates it; each item passes or names a tracking issue

    Verification: Unit Test (driver-conformance.test.ts -t "claude-cloud")
    Scenario: Given DRIVERS["claude-cloud"] → the registry test demands an adapter → items map as follows:

    1. commit: unavailable: (needs a live session; observed in bug(codex): workspace-write disables network, so every phase runs offline — no gh, no comments, no push #1079/fix(#1123): --yes init no longer replaces an unparseable .mcp.json #1142).
    2. gh api rate_limit: structural: (the sandbox has no gh, exit 127; GitHub goes through MCP).
    3. errors: cases built from the captured failure text (setup-script error_during_execution, HTTP 400 invalid_request_error). No synthesized strings (bug(drivers): opencode and aider report no token usage and no typed errors, so conformance items 3 and 5 cannot pass #1115).
    4. env: asserts the preamble carries SEQUANT_PHASE/SEQUANT_ISSUE and the environment carries the static set (OQ-4).
    5. outcome: gated on P-3.
    6. skill load: asserts the preamble invokes the Skill tool by name. matcha P0 found skills load only when the prompt names the tool.

    AC-2: isAvailable() false, with a named reason, when no environment id or auth is configured

    Verification: Unit Test (claude-cloud.test.ts)
    Scenario: Given settings without run.claudeCloud.environmentId → isAvailable() is false and the reason names the key. Same for missing auth (the P-1 outcome decides which credential).
    Assumptions: the interface returns boolean. A reason needs a side channel such as lastUnavailableReason, or a widened return type. Check how codex/opencode surface theirs before adding a third pattern.

    AC-3: exec to cloud, qa to local → proposed for split (OQ-1)

    Verification: Unit Test (phase-executor: driver chosen per phase)

    AC-4: exceeding run.timeout stops the run and maps to the existing timeout outcome

    Verification: Unit Test (fake poller + fake clock)
    Assumptions: P-4 finds the stop call. The timeout must not read as "Out of credits" (the known 1800 s-timeout mislabel).

    AC-5: after a cloud exec, sequant worktree resolve <N> returns a worktree on the pushed branch

    Verification: Integration Test (bare-repo fake remote)
    Scenario: The orchestrator creates the local worktree feature/N-slug at origin/main before exec. The cloud pushes the same name, because the preamble passes the exact branch and the in-place block keeps a non-base branch. Afterwards the driver runs fetch origin <branch> + merge --ff-only in the worktree. A non-fast-forward result is a named failure, never a reset.

    AC-6: modelUsage has non-zero input/output tokens from a completed run

    Verification: Unit Test (mapper on a captured events fixture)
    Assumptions: P-3. If usage is absent, reword to "tokens reported unmeasured (never 0), turns + duration recorded" (OQ-3).

    AC-7: docs/reference/claude-cloud-driver.md

    Verification: Manual Test (grep -l claude-cloud docs/reference/*.md)
    Covers: environment setup and the static env set, the no-secrets rule, install deps from the preamble (setup script runs outside the repo), gh absence, permissions.ask stalls, model and driver selection, timeout, cost ceiling, daily fire cap.

    AC-8: npm run build && npm test green

    Verification: CI


    Implementation Plan

    Phase 0: probes (gate, ≤ $1). P-1…P-4 above. Script: scripts/probes/claude-cloud-probe.ts. Scrubbed fixtures go to src/lib/workflow/drivers/__fixtures__/claude-cloud/. Post results here, then stop for the go/no-go on P-1.

    Phase 1: pure core (no network).

    1. drivers/claude-cloud/preamble.ts: builds the prompt. Deps install (npm ci), exact branch checkout, Skill tool invocation, per-run SEQUANT_ISSUE/SEQUANT_PHASE, and the tool exclusions. It never includes SEQUANT_WORKTREE (in-place + worktree → HALT) and never includes secrets.
    2. drivers/claude-cloud/run-log.ts: maps events to AgentPhaseResult. It uses the first result: after the prompt: PR-event re-wakes add later ones (4 in matcha P0-1). Duration comes from duration=, never timestamps (~4 h skew observed). is_error + errors[] map to typed errors.
    3. drivers/claude-cloud/preflight.ts: refuses to fire when tracked .claude/settings*.json has permissions.ask (matcha: 4 h stall).

    Phase 2: driver.
    4. claude-cloud.ts: executePhase = create trigger (environment_id, model, run_once_at) → run → poll with backoff → delete trigger → map. It enforces phaseTimeout itself (no 30-min wall in the cloud), then stops the run. resolvesSkills: true, usesSdkMcp: false, canResume false in v1.
    5. Register it in drivers/index.ts and add the settings run.claudeCloud { environmentId, model? } (zod + known keys; #1107's networkAccess miss is the precedent).

    Phase 3: local handoff.
    6. Post-exec, sync the worktree (AC-5). Ignore <branch>--session-* checkpoint branches: the resolver's feature/(\d+)- key matches them. Local batch-executor does the GitHub side (PR/comment) with local gh.
    7. Add the conformance adapter and docs.

    Design Review

    1. Where it belongs: src/lib/workflow/drivers/, the same layer as codex/opencode. The executor stays driver-agnostic apart from the AC-3 resolver.
    2. Simplest correct approach: a thin HTTP client plus pure mappers, with every network call behind an injectable transport so AC-4/AC-6 test against fixtures. Rejected: claude --cloud (TTY-only), and a PTY wrapper (Nested phase claude that hangs after its turn is killed at ~106s, taking down the parent sequant run #856).
    3. Existing pattern: codex's typed failure mapping from captured text (bug(codex): usage-limit turn failures classified 'unknown' — quality loop re-runs into the same quota, --auto-wait can't engage #1087/bug(drivers): opencode and aider report no token usage and no typed errors, so conformance items 3 and 5 cannot pass #1115), and conformance adapters (test(drivers): conformance suite every agent driver must pass — commit in sandbox, network, typed error mapping, env injection, structured outcome #1096).
    4. What a reviewer will challenge: "Why not let the cloud open the PR?" Because the sandbox has no gh (22 lines of exec/SKILL.md reference gh). The MCP route works but its failures are silent. Keep PR and comments local, where gh exists.

    Feature Quality Planning

    Standard checks pass except the gaps above. Derived ACs:

    Source Derived AC Priority
    Containment (comment 2, item 1) AC-9: the session's tool policy excludes mcp__Claude_Code_Remote__* and PushNotification. Asserted on the trigger request body High
    Env (in-place contract) AC-10: the preamble never carries SEQUANT_WORKTREE or secrets; unit test on the builder High
    Stall (item 3) AC-11: preflight refuses to fire on permissions.ask in tracked settings, with a named reason High
    Mapper (item 5) AC-12: first result: after the prompt wins; a fixture with 4 result: lines maps to the first High
    Hygiene AC-13: the one-shot trigger is deleted/disabled after its fire, including on failure and timeout High
    Branches AC-14: --session-* checkpoint branches never resolve as the issue's worktree branch Medium
    Cost AC-15: cost reads unmeasured until usage is observed; turns + duration always recorded Medium

    Open Questions

    1. Split AC-3 out? Recommendation: yes, as its own issue blocking feat(drivers): claude-cloud AgentDriver — run a phase as a claude.ai cloud session instead of a nested local CLI #1137. Impact if not: a 5-site executor change lands inside an unprobed driver PR.
    2. Key names: recommendation: run.phases.<phase>.agent, matching run.agent, rather than .driver. That also widens PhasePolicy beyond claude-code, so the doc comment changes. Impact: rename churn later.
    3. AC-6 if P-3 finds no usage: recommendation: reword as AC-15 does. Impact: a tautological AC, or a fabricated zero.
    4. Static env set: recommendation: set SEQUANT_ORCHESTRATOR=sequant-run + SEQUANT_CHECKOUT=in-place in the environment store (so skills take the orchestrated paths), with per-run values in the preamble. Impact: without it the cloud exec runs standalone and posts its own comments.
    5. Auth fallback (P-1 = no): ship the LLM launcher shim, or park? Recommendation: park, and file upstream for a documented token path. Impact: a nondeterministic driver.

    Recommended Workflow

    Phases: spec → testgen → exec → qa. Exec starts only after the P-1 go/no-go.
    Quality Loop: enabled
    Reasoning: 9 unit/integration ACs with pure mappers, which suits testgen. Complex scope and an external API contract, which suits the loop. qa stays local (the cost finding).

    Label Review

    Current: enhancement, multi-agent · Recommended: + planned, + complex · Reason: 15 ACs, an external contract, and a gate before exec.

  7. added
    planned
    on Sep 24, 2026
  8. admarble commented on Sep 24, 2026

    @admarble
    ContributorAuthor

    Owner decisions on the /spec open questions (2026-09-24)

    1. Split AC-3: yes. Per-phase driver selection is now feat(run): per-phase agent selection — run.phases.<phase>.agent #1150 and blocks this issue. AC-3 keeps its ID and is rewritten to the feat(run): per-phase agent selection — run.phases.<phase>.agent #1150 key.
    2. Key name: run.phases.<phase>.agent, matching run.agent.
    3. AC-6: conditional. Non-zero modelUsage if the events carry usage (P-3); otherwise unmeasured (never 0), with turns and duration recorded. Both branches are verified against captured fixtures.
    4. Static env: a dedicated cloud environment for the driver with SEQUANT_CHECKOUT=in-place + SEQUANT_ORCHESTRATOR=sequant-run. "Sequant in-place" stays unchanged, because orchestrated /exec drops its progress comment and human-run sessions have no orchestrator to post it. Create it only after P-1 passes.
    5. P-1 fails → park. No LLM-mediated launcher.

    The issue body now carries all of this: the ACs, a Gate paragraph, Non-Goals and Blocked by: #1136, #1150. Derived AC-9 to AC-15 from the spec are now body ACs. After these edits the scope heuristic still reads SPLIT_RECOMMENDED (15 ACs, 5 dirs); flagged, not acted on.

  9. admarble commented on Sep 24, 2026

    @admarble
    ContributorAuthor

    Driver environment created 2026-09-24: "Sequant Driver" (claude.ai cloud). It has SEQUANT_CHECKOUT=in-place and SEQUANT_ORCHESTRATOR=sequant-run, no setup script, and network set to Trusted. Its env_… id is not recorded yet: the Phase-0 probe (P-1) captures it and posts it here. "Sequant in-place" (env_01QXpqvWm6CyRyTgxsA4C62d) is unchanged.

  10. admarble commented on Sep 24, 2026

    @admarble
    ContributorAuthor

    The "Sequant Driver" environment id is env_01GHgDSBdiWR6evstrUbX2xh (kind: anthropic_cloud, state: active).

    Found through GET /v1/environment_providers with the claude.ai browser session and an x-organization-uuid header. /v1/environments rejects the ccr-byoc beta header, and /v1/code/environments returns 404. This is useful for the driver's isAvailable() check (AC-2): the list endpoint exists, and the Node-side auth question is still P-1.

  11. admarble commented on Sep 25, 2026

    @admarble
    ContributorAuthor

    P-1 (#1151 AC-1): fail, so #1137 is parked

    The token came from claude setup-token (CLI 2.1.282) and was sent as a bearer from a plain Node process. The headers match what the CLI sends to these endpoints: anthropic-version: 2023-06-01, anthropic-beta: ccr-byoc-2025-07-29 and x-organization-uuid. Output of npx tsx scripts/probes/claude-cloud-probe.ts auth, redacted:

    {
      "probe": "P-1",
      "verdict": "fail",
      "results": [
        {
          "endpoint": "GET /v1/environment_providers",
          "status": 403,
          "body": {
            "type": "error",
            "error": {
              "type": "permission_error",
              "message": "OAuth token does not meet scope requirement any_of(org:sessions:claude_code, user:developer, user:sessions:claude_code, workspace:developer)"
            },
            "request_id": "req_011CfPTDrf3doUQoE6m2f7Ma"
          }
        },
        {
          "endpoint": "GET /v1/code/triggers",
          "status": 401,
          "body": {
            "error": {
              "message": "OAuth token lacks a scope this endpoint accepts",
              "reason": "oauth_scope_insufficient",
              "type": "authentication_error"
            },
            "request_id": "req_011CfPTDs763raLHwrbMeXVV",
            "type": "error"
          }
        }
      ]
    }

    Why: setup-token issues an inference-scoped token and takes no scope options (claude setup-token --help lists only -h). The session and trigger endpoints require user:sessions:claude_code (or org:sessions:claude_code, user:developer, workspace:developer). Only the interactive claude auth login token carries that scope, and reading it out of the keychain is a Non-Goal of #1151.

    Decision (owner, 2026-09-24, item 5 of the /spec questions): P-1 fails → park #1137. No LLM-mediated launcher. P-2 to P-4 (#1151 AC-3 to AC-5) are not run, since they are conditional on P-1.

    What would unpark it: a documented way to mint a long-lived token with a sessions:claude_code scope (for example, a scope option on setup-token), or a headless session-create path in the CLI (claude --cloud is TTY-only today). Either one is an upstream change.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementmulti-agentplanned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions