drain
Unattended queue-draining loop — fresh-context one-shot spawning and stop conditions for src/worktrail/drain
- License 许可
- MIT
- 最近更新
- 2026-11-14
- Stars
- ★ 0
- Forks
- 0
01 前言 Front Matter
- name
- drain
- triggers
- { "files": [ "src/worktrail/drain/**" ], "keywords": [ "drain", "queue_empty", "circuit_breaker", "capacity_gated", "no_pick", "fallback-agent", "_land_remediation_pr" ] }
- description
- Unattended queue-draining loop — fresh-context one-shot spawning and stop conditions for src/worktrail/drain
03 SKILL.md 正文
You are working on worktrail's queue-drain driver: repeatedly spawning fresh-context headless one-shots against the router until the work queue empties or a stop condition fires.
Domain purpose
Each iteration spawns exactly ONE headless agent CLI process (default claude -p "worktrail-go auto"), waits for it to exit, classifies the outcome from the newest run record under the runs
dir, then re-checks the queue. A fresh process per iteration means fresh context by
construction — nothing accumulates across iterations.
Business rules / invariants
- The prompt is
"worktrail-go auto", never"/go auto".worktrail-gohas never been a registered slash command — only a skill. Claude Code's CLI fails immediately on an unrecognized/go("Unknown command... Did you mean /goal?") but exits 0, which this module's ownno_pickclassification then reads as "nothing was eligible to claim" rather than "the one-shot never even started." Using the wrong prompt form silently no-ops every drain iteration that usesagent=claude. build_commandalways adds--skip-git-repo-checkto every codex spawn. The cwd for a codex one-shot is alwaysworker_scratch_dir(), never a git checkout, socodex execotherwise refuses outright with "Not inside a trusted directory" before emitting any classifiable output — confirmed live from~/.worktrail/drain-logs/transcripts/*-codex.logon every codex iteration back to 2026-09-08. The flag is spliced in right aftersandbox_argsand beforepermission_args, for everybuild_command("codex", ...)call regardless of template/model/effort.- Seven distinct stop conditions, each printed, never silent:
queue_empty,no_pick,capacity_gated(every configured agent — primary +--fallback-agentchain — is gated),circuit_breaker(N consecutive failed iterations, default 2),max_items,budget_exhausted,lock_held(another drain already owns this queue). completed_awaiting_human_approvalis a gate working, not a stall — the driver notes the pending PR and continues to the next iteration rather than treating it as failure.- A timeout (exit 124) with a PR already recorded classifies as
timeout_after_pr, notfailed. The substantive work succeeded and only post-PR wrap-up was still running when the timeout fired, so it does not count towardcircuit_breaker. A timeout with no PR remains a plainfailediteration. - A record-less iteration that classifies as an account-level failure
(
agent_capacity.classify_failure: auth/billing, the latter also covering "usage limit"/ "session limit"/"weekly limit"/"fable limit" wording — the last confirmed live 2026-09-07 against Claude Fable's "You've reached your Fable limit..." refusal, which previously fell through to "transport" and tripped the circuit breaker after only two hits — plus "insufficient balance", the DeepSeek-compatible cell's 402 account-exhaustion wording, confirmed live 2026-10-03 after an unrelated stderr line landed it in "startup" and two 16s fast-fail iterations tripped the circuit breaker) isblocked, notfailed— it does not count towardcircuit_breaker, and persists a capacity gate (keyed as described below) with aretry_afterparsed from the notice when present, else the class's generic cooldown (the Fable notice carries no reset timestamp, so it always falls back to the generic billing cooldown). - Agent selection re-runs every iteration in fixed priority order (
[--agent] + --fallback-agent...,select_available_agent, which returns the chosen cell's harness, model, effort, and the routing target it came from) — a gated primary is skipped in favor of a fallback automatically and picked back up automatically once its gate expires. Onlycapacity_gated(every configured agent gated at once) actually stops the drain. - A blocked iteration's capacity gate is keyed by its routing target, not the harness name
(
record_capacity_gate'sgate_key, passed asactive_target or active_agent): under routing,select_available_agent's per-cell capacity check queriesprovider_key(target, model), andcapacity_gated()honors a bare target entry for every model of that target — so a harness-keyed gate ("claude") is invisible to a target-keyed query ("claude-deepseek:deepseek-flash[1m]") and the same exhausted cell gets re-selected. Confirmed live 2026-10-03 (drain-logs/2026-10-03T09-17-01Z.json): two blocked iterations advanced to the circuit breaker instead of failing over to the next target. Without routing the selection unit is the bare harness name, so the harness name is the key then. - Applies the same
go:risk-*PR label correction as the interactive path (pr_labels.ensure_pr_risk_label) after a spawned one-shot's owngh pr create, since neither Codex/OpenCode nor a headlessclaude -psession reliably runs the interactive PreToutUse label-enforcement hook. - Drain's three remediation sweeps (sync-pending, stale-bookkeeping, OpenSpec archive) open
their PR through one helper,
_land_remediation_pr, which composes with the sharedrouter/land_pr.pypipeline (land_pr(LandRequest(route="E", risk="low", run=None, watch_timeout_s=timeout, ...))) — never a hand-rolledgh pr create. The former per-sweep_open_sync_pending_pr/_open_stale_bookkeeping_pr/_open_openspec_archive_prfunctions and their_refresh_pr_labelsimport are gone. The helper returns the PR URL only on alandedoutcome and raisesRuntimeError(land_pr for <repo> <spec> failed: <outcome> (<detail|refused_step>)) on any other outcome, whichsweep_remediationslogs as an<action> error:line and skips rather than aborting the sweep. Each sweep still does its owngit push --force -u origin <branch>before calling the helper. Tests mockdrain.land_prdirectly (nogh pr createsubprocess fake remains for these paths). The OpenSpec archive sweep additionally runsclose_stale_openspec._delta_precheck(openspec validate --strictplus the delta-vs-canonical and archived-sibling drift checks) after the unchecked-task refusal and beforeopenspec archive -y. Any pre-check refusal raisesRuntimeErrorand is logged as anarchive-openspec-change error:line with no archive, commit, push, or PR. Drain deliberately has no--allow-delta-driftequivalent: an unattended sweep never overrides drift, the interactive close-stale path is the only place that flag exists.
Critical files
drain/drain.py— the whole driver: iteration loop, stop-condition classification, agent fallback selection, and_land_remediation_pr(the singleland_prseam for remediation PRs)
Last Updated: 2026-10-04
04 同仓库更多 Skills
worktrail-sdd-workflow
Internal SDD workflow executor invoked by /go only. Do not call directly. Executes classified routes A–J: feature planning, implementation (parallel orchestration, PR generation), defect repair, refactoring, spec changes, investigation, and workflow evolution.
worktrail-routing-config
Configure Worktrail's agent routing table (`~/.worktrail/routing.yaml`, or a repo-local `routing:` policy block) — which harness/model executes each role and tier, and how fallback between them works. Use when the operator wants to add or remove a harness/adapter (claude/codex/opencode), add a model to an existing harness (e.g. adding a DeepSeek model to opencode), pin or change who does code review, add a new tier or purpose mapping, change the default tier, or is confused about which harness actually served a spawn (e.g. "why did this use Codex when I only configured Claude"). Trigger phrases: "routing.yaml", "add a harness", "disable a harness", "add an adapter", "remove an adapter", "add a model", "add deepseek to opencode", "change the reviewer", "pin the reviewer", "routing tiers", "routing targets", "default_tier", "independent reviewer", "why did codex get called". This skill is about *editing the config file*; it does not cover `/go`'s own dispatch mechanics (see `worktrail-go`'s SKILL.md Phase 7 for how `tier_for()`/`select_cell()` resolve it at runtime).
worktrail-repo-init
Bootstrap a new repo, or migrate an existing single-branch repo, onto the workspace's repo-standards doctrine (~/rules/CLAUDE.repo.md): the AGENTS.md-is-truth/CLAUDE.md-imports-it split, a dev/prd, dev/stg/prd, or main-only (trunk) branch model with matching GitHub rulesets, an OpenSpec scaffold, an auto-merge workflow, and a seeded .worktrail/policy.yaml. Trigger phrases: "onboard this repo", "apply repo standards", "initialize repo standards", "set up this repo like the rest of the fleet", "bring this repo into line with the repo standards doctrine".
worktrail-help
Show the Worktrail front-door commands and accepted positional arguments. Use when the user asks how to invoke worktrail-go, wants the available handoff, spec, pr, repo, or route forms, invokes worktrail-go with help or with a bare noun, or asks how to answer a filed product decision (worktrail-decision).
worktrail-handoff
Capture a discovered problem, gap, tech debt, or deferred work into a local work queue so a future agent session can pick it up cold. Use mid-session whenever you set work aside instead of doing it now — a fix you judge out of scope for this PR, work that belongs in a follow-up or a separate/later PR, an item you're deferring, or something worth fixing you won't tackle now — so the outstanding item isn't lost without derailing current work; can be called multiple times per session. Trigger phrases: "defer this", "item deferred", "out of scope for this PR", "follow-up work", "leave for another PR", "capture for later", "outstanding item". This skill captures only. Picking a brief back up is the front door's job: worktrail-go <brief-id>.
worktrail-go
Use when the user invokes worktrail-go, asks to pick up queued work, resume active specs, implement or fix a spec, route engineering work, or orient across repositories. Renders the orientation dashboard, classifies free-text requests, claims/resumes handoff briefs, and dispatches SDD work without requiring the user to know sdd-workflow. Grammar: worktrail-go [REPO] <noun> <verb>, nouns handoff / spec / pr / decision. Triggers: worktrail-go, worktrail-go help, worktrail-go spec fix, worktrail-go spec implement, worktrail-go spec route F, worktrail-go handoff new, worktrail-go handoff auto, worktrail-go decision answer, worktrail-go BRIEF-ID, bare worktrail-go, multi-repo orientation.