Specify a parent issue number, and launch a Workflow that automatically implements sub-issues under it (including all descendants below grandchildren) in parallel in worktrees while preserving dependency order, performs local diff review, push + PR creation, CI monitoring, and making them merge-ready. squash merge is performed on the client side only in opt-in runs with autoMerge: true + externalChecks explicit (including trusted check context declarations for all Apps) (see the "Client-side automatic merge design" section in references/automerge-design.md). By default (autoMerge unspecified / false), it stops without merging, and merging is done by a human on GitHub.
To conserve CI resources, a "pre-push review" design is adopted. In the Implement phase, commits are only accumulated on the local branch, and push/PR creation happens only after Review has fully passed. If Review fails to converge, neither push nor PR is created, so CI is not triggered at all. Immediately before push (at PR creation and re-push after a fix in the Merge loop), the base branch is always incorporated (establishing the starting point, fetch, merge, push, verifying the push took effect, and detecting and creating the PR are deterministically performed by scripts/pr-push.sh , and the agent is responsible only for resolving conflicts, deciding the subject to match commitlint, and the PR text. Issue #603, 4th installment). In a parallel run (parallel >= 2), if a sibling issue's PR has already been merged first, the base at the time of creation may already be old and in conflict, and if pushed in that state, GitHub cannot create a test merge commit and not a single CI check-run for the pull_request trigger is issued, so resolution is attempted at the pre-push gate before pushing (if it cannot be resolved, the push itself is stopped). Furthermore, immediately after push (at PR creation and at re-push for a fix), it checks whether checks have been issued for the pushed head (totalcheck-run の total_count + combined status の statuses count。gh pr checks / same aggregation definition as merge-exec. To avoid falsely determining 0 for CI that only issues commit status) and mergeable in a bounded manner (30-second intervals, maximum 5 minutes.scripts/observe-pr.sh --mode push waits for the pushed HEAD to become the PR's head before reading. Issue #603, 3rd installment), and returns it aschecksStarted / mergeableAfterPush (to catch the case where a sibling PR was merged and the base moved after passing the pre-push gate, before consuming a monitoring round). The host receivingmergeableAfterPush: CONFLICTING goes straight to base incorporation (bounded bybaseMergeCount ) without launching even one round of monitor. Both values are self-reported by the agent and are not used for merge determination (dedicated to branch hints and recording in the state file._/issue-trees/<n>.json の pushChecksStarted / pushMergeable)。
Terminal implementation issues are greedily placed into free slots using post-order DFS order as priority, up to a maximum of parallel(Up to 3 by default) are executed in parallel. Each implement / fix is run in isolation in a separate git worktree, so branches and working copies do not collide even in parallel. Functional dependencies (dependsOn) and parent-child relationships (the parent waits for all children to complete in verify-close) are the only waiting conditions.
Prerequisites
ghCLI is installed and authenticated (gh auth statusto check)jqCLI is installed (command -v jqto check).The monitor's observation scriptscripts/observe-pr.shuses an externaljqin all modes(assembling the envelope payload,gh api --paginateaggregating the per-page output ofjq -s〕、--arg/--argjson/@uri. jq 1.5 or higher is required, and actual execution has been confirmed on 1.6 (Ubuntu 22.04), 1.7 (Debian, macOS), and 1.8 (Alpine)). If it is not installed, the script exits with exit 3 without emitting an envelope, and monitoring treats it as a fetch failure. In addition, the human diagnostic-only command (B) in the section "When all checks appear to pass but the merge does not proceed (leftover checks of a canceled run)" pipes the raw JSON ofgh api --paginate --slurpto an externaljqto flatten and aggregate it, so it cannot be replaced bygh --jqalone. If it is not installed, do not run that command (and do not rerun either); treat it asblocked.ghThe feature's prerequisite (observe-pr.sh):gh pr view --json state,headRefOid,mergeable,headRefName,baseRefName,closingIssuesReferences,isCrossRepository・gh api --paginate・gh api graphql. Aggregating multiple pages is done bygh api --paginateoutput withjq -sand does not depend ongh api --slurp(a newer gh feature).The minimum required gh version is unconfirmed(actual execution has only been confirmed with the real API of gh 2.102.0; the version in which each field was introduced has not been checked in the official release notes). Because of the time limit, bash job control (set -m)とmktemp・date +%s・sleepis used (works with bash 3.2 on macOS and on Linux). For base incorporation,scripts/base-merge.shはgh pr view --json number,headRefName --jq …(gh's built-in jq; externaljqis not needed) andgit remote get-url --push --all(git 2.7 or higher) andgit merge --no-ff --no-edit -F(git 2.20 or higher. In actual measurement, it is present in 2.20.4 and absent in 2.18.4 and earlier; the 2.19 series is unconfirmed. With a git that lacks it, base incorporation becomescommitFailed〔failedend〕 and is not pushed. For details, see references/script-trust-model.md) andgit merge-base --is-ancestor・git ls-remoteare used.observe-pr.sh --mode pushreads the pushed HEAD withgit rev-parse HEAD, so run it in the working directory of the pr-create/fix agent (the pushed worktree).awkCLI is installed (command -v awkto check). The agent-executable command (A) in the same section is--jqcan only be applied per page, so when aggregating duplicates across pages it depends on the shell-sideawk. If it is not installed, do not run that command and treat it asUNDETERMINED(undeterminable).- The git working tree is clean (
git statusto check) - The measurement script (
scripts/measure-*.sh・scripts/run-verified.sh) usesbash・du・df・awkと、sha256sumorshasum(the macOS standard isshasum). Only writing styles that work on both macOS (BSD userland, bash 3.2) and Linux (GNU) are used. If any of them is missing, the measurement fails, and a run with a valid residual-byte axis blocks new starts (fail-closed) - The merge destination branch must be in a CI green state (
autoMergeIn operation, this is also checked after the run completes. This is because, under the strict = false assumption described later, it can be merged with the checks that succeeded against an old base still in place).This check depends on CI being triggered by a push to the merge destination branch. In repositories that have no push-triggered workflow, or thatpathsare not triggered for the relevant head by the filter, neither the precondition check nor the post-completion check can be verified, soautoMerge: trueis deprecated. For the procedure to confirm whether it holds (a probe that inspects the target (merge destination) branch.branchFalls back to the default branch only when unspecified) and how to handle the case where it does not hold, see the "Confirmation that the compensation measure holds (base CI probe)" section of references/automerge-design.md - (
autoMerge: truewhen used with) the base branch ruleset must have required status checks strict (requiring the base to be up to date before merging =strict_required_status_checks_policy)をfalseset to。truethen every time one is merged, the base of the other open PRs becomes stale, and parallel runs (parallel >= 2) do not converge. Since G0 does not require strict,falseauto-merge still holds (the "Reason why strict is not made a G0 requirement" section of references/automerge-design.md) - Have write permission to the target repository
- The parent issue and child issue must be linked via GitHub's sub-issues API (for linking, see
create-issue/create-issue-tree)
Usage
Using the Workflow tool, specify scriptPath and launch by specifying the scripts/implement-issue-tree.js in this skill directory. The path differs depending on the installation form, and if it is the same installation form as the merge-guard hook path described later,it is under the same root(the js and hook always reside together in the same skill directory). 3 layouts:
- upstream
skills/layout(source of this repositoryFandhe-AI/agent-cli-skills):skills/implement-issue-tree/scripts/implement-issue-tree.js .agents/skills/に vendored(npx skills add Fandhe-AI/agent-cli-skillsdownstream repository installed with):.agents/skills/implement-issue-tree/scripts/implement-issue-tree.js.claude/skills/via symlink(the layout this repository uses for internal references. The entity isskills/a symlink pointing to):.claude/skills/implement-issue-tree/scripts/implement-issue-tree.js
args.skillDir(after distribution, the caller must always pass it): scriptPath the same skill directory as (one of the three layouts above, implement-issue-tree/。scripts/ one level above) toabsolute pathで args.skillDir pass (e.g.: /Users/me/repo/.claude/skills/implement-issue-tree. If using a relative scriptPath , then $(pwd)/.claude/skills/implement-issue-tree make it absolute in the main working directory at launch time, as in). Since the Workflow script itself does not touch the filesystem, the part where the deterministic procedure was split out into a script bundled with the skill (Issue #603. Measurement scripts/measure-*.sh, PR observation and waiting scripts/observe-pr.sh・base ingestion scripts/base-merge.sh・PR creation and push of fixes scripts/pr-push.sh) decide the execution location from here.At run start (dryRun including.skillDir run), verify the hashes of all embedded scripts against the actual files once (one agent.run-verified.sh --verify-only), and if there is a version mismatch or missing file, stop without starting anything(pre-check. What can be detected is version mismatch and transcription errors, not fabrication by a malicious agent. Verification at each script startup works separately every time).named workflow({name: "implement-issue-tree"}), even when starting with args.skillDir is required(named workflow は .claude/workflows/implement-issue-tree.js only points to it, and the Workflow runtime does not tell where the scripts are located). Subagents must always be started with scripts/run-verified.sh を bash on this main working directory side (without depending on the executable bit), and must not use the copy in the worktree. Before startup, verify against the expected hash (embedded into the artifact by the builder), and on mismatch or missing, do not start and fail-closed. The trust model is references/script-trust-model.md. The format is validated with the same strictness as args.repo , and invalid values (relative paths,..・//, trailing /, disallowed characters, over 400 characters, non-string) are not silently reinterpreted but stop with a startup error.When unspecified: dryRun runs that are not (= runs that start actual agents. Because monitor uses observe-pr.sh every time, it is also required formaxResidualWorktreeBytes: 0 ) stop with a startup error before calling any agent even once. The only runs that can be omitted are dryRun: true runs.
{
"scriptPath": "<このスキルディレクトリ>/scripts/implement-issue-tree.js",
"args": {
"parent": "<親イシュー番号>",
"skillDir": "<このスキルディレクトリ(scripts/ の 1 つ上)の絶対パス。切り出したスクリプト(測定・PR の観測)の実行場所。dryRun: true のとき以外は必須。形式不正はエラーで停止。Issue #603>",
"branch": "<マージ先ブランチ(省略時 main)>",
"parallel": "<並列度 1〜8(省略時 3)>",
"phaseGate": "<boolean。true でルート直下の子(Phase 親 or leaf)を sub-issues リスト順(siblingIndex)に直列化し、前 Phase の全子孫が merged/closed になるまで次 Phase 配下のノードに着手しない(opt-in。Issue #494)。既定 false は現行動作(post-order 優先度のみ・追い越しあり)を完全に維持する。boolean 以外はエラーで停止>",
"dryRun": "<boolean。true で状態ファイル・worktree・PR・issue へ一切書かず、着手できる件数・blocked になる件数(ツリー外の前提待ち・phaseGate・下流の内訳)・ツリー外の open な前提 issue の一覧だけを返して終了する(事前見積り。Issue #585)。boolean 以外はエラーで停止>",
"externalChecks": "<外部チェック App と信頼済み required check context の組の配列(例: [{\"app\": \"cursor\", \"context\": \"Cursor Bugbot\"}]。使用しない場合は []。slug 文字列のみの旧形式も受理するが、context 未宣言のためクライアント側自動マージは fail-closed で停止する)>",
"optinTestCommands": "<人間がラン起動時に明示する、opt-in テストとして実行してよいコマンドの承認一覧(文字列配列・最大 20 件。省略時 []。イシュー本文の <!-- optin-tests: ... --> 宣言はこの一覧と正規化後の文字列完全一致でのみ採用される。1 件でも許可形式外なら起動時エラーで停止。PR #503 codex P0: 本文だけでは新しいコマンドを持ち込めない設計。次節「opt-in テストの宣言」参照)>",
"autoMerge": "<boolean。true + externalChecks 明示(確定。全 App の信頼済み context 宣言込み)でクライアント側 squash merge を実行する(opt-in。references/automerge-design.md の「クライアント側自動マージの設計」節参照)。既定 false / externalChecks 未確定時はマージ可能状態で停止し、マージは GitHub 上で人間が行うか、サーバー側 auto-merge workflow(upstream の docs/implement-issue-tree/auto-merge-sample.yml)+ branch protection に委ねる>",
"maxResidualWorktrees": "<残置 worktree 総数の上限(0 以上の整数。省略時 100、0 でこの軸のみ上限なし)>",
"maxResidualWorktreeBytes": "<残置 worktree ディスク使用量の上限(バイト。0 以上の整数。省略時 53687091200 = 50 GiB、0 でこの軸のみ上限なし。件数軸とは独立、Issue #348)>",
"maxBaseMerges": "<PR が base とコンフリクト(mergeable: CONFLICTING)した際の自動 base 取り込みの回数上限(0〜10 の整数。省略時 3、0 で自動 base 取り込みを無効化しコンフリクトを即 blocked にする)。fixCount とは独立の予算軸(Issue #441)>",
"agentCallLimit": "<新規着手・monitoring 再開を止める判断に使う、ランタイム上限の想定値(81〜1000 の整数。`securityReview` 有効時は 83〜1000。省略時 1000=ランタイムの上限。呼び出しそのものは止めない。範囲外・非整数はエラーで停止。Issue #592)>",
"repo": "<対象リポジトリの owner/repo(例: \"Fandhe-AI/agent-cli-skills\")。base 取り込み(maxBaseMerges > 0)の worktree routing ガードが期待する owner/repo として使うホスト側明示宣言。未指定時は base 取り込みの自動起動が無効化され、コンフリクトは blocked+quality で終端する(PR #443 codex P0: エージェント自己申告値は信頼境界に使わない)>",
"models": "<判断を伴う agent のモデルを段階ごとに上書きするオブジェクト(任意)。キーは plan / implement / review / securityReview / fix / prCreate / baseMerge、値は haiku / sonnet / opus / fable。未指定の段階は既定(plan はセッションのモデルを継ぐ・それ以外は sonnet)。オブジェクト以外・未知のキー・許可外の値はエラーで停止>",
"securityReview": "<true または {\"enabled\": true} で push 前 Review の各ラウンドにセキュリティ専用の Review エージェントを並列に足し、両方の結果を合わせて判定する(opt-in)。未指定・false は現行動作。それ以外の形はエラーで停止>"
}
}
Example: parent issue #42 under main to, with parallelism 3 and Cursor Bugbot already introduced (automatically proceeds to a mergeable state, and merging is done by a human on GitHub):
{
"scriptPath": ".claude/skills/implement-issue-tree/scripts/implement-issue-tree.js",
"args": { "parent": 42, "skillDir": "/Users/me/repo/.claude/skills/implement-issue-tree", "branch": "main", "parallel": 3, "externalChecks": [{"app": "cursor", "context": "Cursor Bugbot"}] }
}
Example: prioritizing quality, set planning to fable, implementation and fixes to opus , and add a security-only Review with opus (normal Review, PR creation, and mechanical agents remain at default):
{
"scriptPath": ".claude/skills/implement-issue-tree/scripts/implement-issue-tree.js",
"args": { "parent": 42, "skillDir": "/Users/me/repo/.claude/skills/implement-issue-tree", "externalChecks": [], "models": { "plan": "fable", "implement": "opus", "fix": "opus", "securityReview": "opus" }, "securityReview": true }
}
Argument
| Argument | Required | Default | Description |
|---|---|---|---|
parent |
Required | — | Parent (root) issue number.issue issue is also allowed |
skillDir |
Conditionally required | — | Absolute path of this skill directory (scripts/ one level above)(Issue #603). Scripts that extract deterministic procedures (currently byte measurement of leftover worktrees measure-residual-bytes.sh, actual disk free space measure-free-disk.sh, PR observation and bounded waiting observe-pr.sh, verification of automatic base ingestion and push base-merge.sh, pr-create and fix base ingestion, push, and PR creation pr-push.sh, state file writing state.sh, verification immediately before merge-exec's merge merge-gate.sh, worktree disposal and cleanup worktree-remove.sh) is where the subagent executes. At run start, the hashes of all scripts in this location are pre-checked once (on mismatch or missing, stop without starting anything).dryRun is omitted, it is not performed).scriptPath pass the same skill directory as.becomes required for dryRun runs that are not(monitor が observe-pr.sh because it uses,maxResidualWorktreeBytes: 0 is also required), and if unspecified, it stops with a startup error (the error message shows an example of the value to pass. The agent is not called even once).dryRun: true it can be omitted. The format is an absolute path (alphanumeric,.・_・-・/, half-width spaces, starting with / + alphanumeric or _) only; relative paths,..・//, trailing /, over 400 characters, or non-string causes a startup error. Existence and hash verification are performed by the script side (at runtime), and missing or mismatched files stop new work as a measurement failure (fail-closed). After distribution, the existing invocation procedure must be updated to pass this argument |
branch |
optional | main |
Merge destination branch. Error if it contains invalid characters |
parallel |
optional | 3 |
Number of parallel executions (1–8).1 specifying makes it effectively serial execution |
phaseGate |
optional | false |
true with root (args.parent) direct children (Phase parent or leaf) in sub-issues list order (siblingIndex. Title's feat(phase-N): etc. are untrusted data and are not parsed) opt-in gate that serializes. The unit of serialization is "the root's direct children and all their descendants (subtrees)", and the subtree of unit Uₖ (k≥1) does not start until all prerequisites of all preceding units U₀…U_{k-1} (for a Phase parent with children, all descendants excluding itself; for a leaf without children, itself) become merged/closed (the design does not include completion of the Phase parent's own verify-close as a prerequisite. To match the requirement "previous Phase parent'sall childrenare merged/closed"). No new scheduler state is created; synthetic edges are merely added to the existing dependency graph (depsMap), so the gate applies as-is to the dispatch loop, prerequisite probe (detection of manual merges during a run), andresumption of monitoring for the next Phase PR created in the previous run(even when re-executed with the same arguments, the next Phase's PR is not merged until the previous Phase completes). Gate edges are not removed by cycle elimination (the reverse-direction dependsOn originating from the body is ignored).autoMerge: false the previous Phase's PR remains mergeable and stops at blocked , so to proceed to the next Phase requires detection by the prerequisite probe after manual merge, or re-execution.parent If a Phase parent itself is passed, its direct children are serialized (it works per the spec, but specifying the root [tracking issue] is recommended). There is no need to separately launch runs for each Phase (verify-close propagates up to the root). Anything other than boolean stops with an error (typos are not silently reinterpreted) |
dryRun |
optional | false |
true performs only a preliminary estimate and exits without writing anything(Issue #585). Tree retrieval, dependency resolution, and state retrieval of prerequisite issues outside the tree are performed as usual, but state file creation/update (state:init-all included), worktree creation, launching implementation agents from Plan onward, and writing to PRs/issues are not performed at all. The return is dryRun: true・startable(expected number of startable items count, number of items that can be started immediately readyNow, first 5 items first. Expectation assuming all startable nodes succeed) ·blocked(count と、outOfTree[directly waiting on an open prerequisite outside the tree] / phaseGate[stopping at a composite edge due to an incomplete previous Phase] / downstream[other downstream/child holds] / optinTestsInvalid[implementation nodes that satisfy prerequisites but whose opt-in test declaration does not match the approval list and become blocked at the beginning of normal execution runImplement ] / savedBranchMismatch[likewise implementation nodes that become blocked because the state file's branch is not this issue's naming] each of their count and first 5 items first. Classification uses the first matching one in the above order; nodes that are not executed because a prerequisite has failed are classified into the dependent side without looking at their own conditions. Nodes that themselves become blocked are not included in the startable expectation and are propagated downstream) ·preBlocked(numbers that stop from the outset due to state file verification failure, etc.) ·outOfTreeDeps(open / unknown / closed / ancestors). halt, leftover worktree limits, and CI results are not included in the estimate because they are only known at execution time. If it turns out that "0 startable nodes and most are blocked," consider closing prerequisite issues outside the tree or reviewing phaseGate before a normal run. Anything other than boolean stops with an error |
externalChecks |
optional | unspecified | Array of external check declarations other than GitHub Actions (maximum 10 items). Elements are declared as {"app": "<slug>", "context": "<required check context>"} pairs (slug uses lowercase English letters, digits, and hyphens. For multiple contexts, contexts array. The old format with only a slug string is also accepted, but client-side automatic merging stops fail-closed as an undeclared context).unspecified and [] have different meanings |
optinTestCommands |
optional | [] |
Approval list of commands that may be executed as opt-in tests (string array, maximum 20 items.parseOptinTestCommands). The <!-- optin-tests: ... --> declaration in the issue body, after normalization (collapsing consecutive horizontal whitespace into one), matches values in this list byexact string matchOnly those that pass are handed to the implementation agent (see the next section, "Declaration of opt-in tests"). Elements must pass the permitted format (character set, path traversal,//, absolute paths, permitted runners, subcommand restrictions, mvn GAV, deno remote specifiers), otherwisestops with a startup error(same strictness asexternalChecks . Typos are not silently reinterpreted).If unspecified / [] , all entries are invalid even if declared in the body (fail-closed. Without an allowlist, commands cannot be brought in from the issue body alone) |
autoMerge |
optional | false |
true + externalChecks explicit (confirmed. Including trusted context declarations for all Apps) opt-in runs perform a client-side squash merge(see the "Client-side automatic merge design" section in references/automerge-design.md. The merge goes through merge-exec's self-fetch re-verification (HEAD sha, checks, threads, external checks) + G0 (measured server-side enforcement on the base branch = non-bypassability of required status checks (rulesets are bypass_actors empty. Repositories with only classic branch protection are unsupported — because verifying non-bypassability requires reading protection with admin privileges, which cannot be proven with a write token, so it is declined in classic-unsupported ) + strict application (base must be up to date before merge) + mandatory review thread resolution + making the check contexts subject to verdict in step 3 required (absence of client-only checks) + external check App declared contexts + App ID pairs (context + integration_id) bound as required + binding all required checks entries' origin to integration_id (blocking impersonation via same-named commit status. If it cannot be verified, issuer-unbound). If it cannot be confirmed, server-enforcement-missing で blocked terminal) + --match-head-commit + independent confirmation by merge-verify. Monitor output is not used as input to the merge path). Default false・externalChecks when unconfirmed or trusted context undeclared (old format with slug only), do not merge; the PR stops in a mergeable state at blocked (implementation, pre-push Review, PR creation, CI monitoring, and the fix loop proceed automatically regardless of the value). If opt-in is not used, auto-merge is delegated to the server-side workflow (upstream's docs/implement-issue-tree/auto-merge-sample.yml) + branch protection, or performed by a human merge on GitHub (setting branch protection on the target branch is recommended). Note: in repositories with the merge-guard hook, subagent gh pr merge is denied, so opt-in merge and the hook cannot be used together. Anything other than boolean stops with an error (typos are not silently reinterpreted) |
maxResidualWorktrees |
optional | 100 |
upper limit on the total number of leftover worktrees (the count axis of the DoS prevention gate. Used independently in combination with the byte axis maxResidualWorktreeBytes , and the decision is OR = if either one is exceeded, new starts are blocked). At run start, the worktrees observed by the cross-cutting scanphysical total count(Only the main worktree is excluded. Tracked in the state file = in-use worktrees are also counted. Whether in use or not does not change disk consumption) exceeds this valueexceed(>) if this happens, to prevent disk exhaustionstop starting new issues(fail-closed. Continuation of already-running issues and monitoring is not stopped). The dispatch loop re-evaluates "observation at start + this run's increments (ephemeralWorktrees.length. New-creation ledger for implement / review / pr-create / fix-routing-error)" every time immediately before starting a new one, and even at the point when this run's increments exceed the upper limit, it stops subsequent new starts (there is a similar mid-progress re-evaluation for the byte axis, but the calculation method differs, so it is described later). Furthermore, it accounts for tasks that have already been dispatched in parallel but have not yet reached the record, estimating a maximum per new start of EPHEMERAL_KIND_MAX table total (implement ×1 + review ×3 + pr-create ×1 + fix-routing-error ×1 = 6 items as the basic case.args.securityReview For runs with this enabled, security-review ×3, and base import adds maxBaseMerges items), and per monitoring resume a maximum of 1 item (for fix-routing-error) as reserved accounting, and stops submissions where "actual measured + reserved + start candidate portion" exceeds the upper limit.The monitoring resume itself is also subject to this reserved-inclusive judgment(however, only for resumes of item.kind === 'implement' . Resumes reached as a verify-close node do not enter the Merge loop and do not accumulate fix-routing-error, so the reservation is 0 and they are out of scope) runVerifyClose and before starting, the same projected judgment is applied, and if an exceedance is expected, that issue's resume is deferred only for this round (it is not permanently stopped. It is re-evaluated after the reservation is released in the next round / next execution. This is because if the start of the monitoring resume itself were allowed unconditionally, merely continuing to sequentially resume monitoring items would allow the number of leftovers to be increased without limit, ignoring the upper limit). Expected exceedance due to reservations is limited to deferring submission for the current round (defer), and it resumes once the reservation is released. Actual measured exceedance is permanently stopped (however, this permanent stop =newStartSuppressed maintains the design that the start of monitoring resume itself is not prevented, and is a gate independent of the above monitoring-resume-specific defer). If the cross-cutting scan itself at run start fails, even if either axis is enabled (`maxResidualWorktrees > 0 |
maxResidualWorktreeBytes |
optional | 53687091200(50 GiB) |
Upper limit of residual worktree disk usage (byte axis of the DoS prevention gate. In bytes. Can be verified and disabled independently of the count axis maxResidualWorktrees , and the judgment is OR).It is not an observation only at run start. At run start, in addition to the observation of executing du -sk on all entries in the residual path list and simply summing KiB, the working tree equivalent size of the main worktree excluding the shared .git object store (measureMainWorktreeContentBytes) is fixed as the safe-side reservation per new worktree perWorktreeByteReserve (plain du value includes the entire object store and would result in over-reservation, so it is excluded). In the same form as the count-axis "re-evaluation of this run's incremental additions" and "reservation accounting,"perWorktreeByteReserve × (台帳件数 − 直近基準確定時点の台帳件数) projection is re-evaluated every time immediately before both new starts during the run and resumption of monitoring, and if an excess is anticipated, new starts are halted (projectResidualBytes. Incremental additions up to the point the baseline is fixed are already included in the measured baseline value, so if that is not subtracted, it results in double counting).Furthermore perWorktreeByteReserve is the lower-bound floor value fixed at the start, and if a single worktree grows beyond the floor due to build artifacts etc., the projection alone may underestimate it, so every time the disposable worktree ledger is incremented by BYTE_REMEASURE_LEDGER_INTERVAL(3 entries), the sum of the residual path list + ledger paths is actually du re-measured (remeasureResidualBytesIfDue), and if the measured value exceeds the upper limit, new starts are halted independently.In addition, immediately before a new start (implement), re-measurement is always performed without going through the ledger-increment gate(remeasureResidualBytesNow. This is because even while the ledger does not increase by 3 entries, running worktrees may grow due to build artifacts etc., so if only ledger increments are used as the trigger, a fail-open remains in which starts after capacity exceedance cannot be halted. Measurement cost is bounded by throttling to "once per same dispatch round").This re-measurement updates the baseline for subsequent projections (residualBytesAtStartand ledger offset byteBaselineLedgerCount) with the same assignment(if the measurement result is used only for the immediate determination of upper-limit exceedance and then discarded, subsequent determinations remain on the old baseline and permit new starts that exceed capacity, resulting in fail-open). If the total (the most recent measured baseline, projection, or re-measurement) isoverthe upper limit, halts starts of new issues (fail-closed. Issues already running and continuation of monitoring are not halted. If already halted on the count axis, no additional suppression is applied and only observed values are logged). If unmeasurable (du fails even once, exits nonzero, or a path outside the permitted character set is mixed in) it is not padded with 0 but treated as an observation failure, and if this axis is enabled, new starts are halted (same fail-closed reason as the "unverifiable" accounting incountResidualWorktrees . Re-measurement failures also halt new starts without falling back to projection. Only non-existent paths [deleted by concurrent cleanup] are tolerated as 0, anddu only actual errors in itself are treated as measurement failures).If the agent's worktreePath is omitted or an empty string causes an unverified entry in the ledger, at this point fall back to the physical list of git worktree list --porcelain (all entries except main, with count cross-checking against the independent record count) and continue measurement, and only if the fallback also fails (list retrieval unsuccessful, count mismatch, path verification impossible) halt new starts in a fail-closed manner(buildPhysicalByteMeasureTargets。For review / pr-create / fix worktrees, since they are detached within an isolated worktree, attribution by branch matching cannot be done, and the fallback is measurement-only (not routed to the deletion path), replacing the physical list wholesale). If the observation at run start remains failed (residualBytesObserved === false), then the projected determination for resuming monitoring (the aforementioned item.kind === 'implement' -limited projection) itself is also deferred under the same fail-closed policy as the count axis, and the entire monitoring resumption for that run is kept waiting until observation recovers (because if a new fix-routing-error worktree were allowed to be created while observation is impossible, the capacity could be exceeded without being verifiable).0 is an explicit opt-out meaning "only this byte axis has no upper limit (check disabled)" (it does not affect the fail-closed behavior of the count axis. For the default-value fallback of the count axis, see the maxResidualWorktrees line).Negative values and non-integers stop with an error. The default of 50 GiB was chosen as a level that will not cause false stops even in repositories with large build artifacts, and as an absolute threshold independent of the file volume of the destination repository, it reinforces the validity of the count-axis default of 100.Independently of the total upper limit on leftover size, the actual free disk space itself is also re-verified every time immediately before starting new work or resuming monitoring(measureFreeDiskKib / remeasureFreeDiskNow. Even if the total leftover size is below the upper limit (default 50 GiB), the actual free disk space itself can be much smaller than that [example: at a destination with 8 GiB leftover and 4 GiB actually free, a gate that looks only at leftover size will not stop new work until it reaches 50 GiB], sodf -Pk measures the actual free space of the filesystem to which the main worktree belongs.A measurement taken only once at run start cannot reflect subsequent consumption, so the same design as the byte axis's remeasureResidualBytesNow is followed: "always re-measure immediately before starting new work or resuming monitoring (thinning is once per same dispatch cycle)". The required number of bytes used for the determination must not becompared only with the reservation for a single worktree(it would be an underestimate if the unconsumed reservations of running tasks and the reservation of the queued candidate itself are not summed in).projectFreeDiskReserveBytes is the sum of "the remaining reservation of running tasks (reservedUnits. The same calculation as the count axis and byte axis (b), "maximum increment − recorded count", is reused as is) + the maximum increment of the start candidate itself (extraReserveUnits)" multiplied by the raw capacity estimate per worktree (rawPerWorktreeByteReserve) to compute the required number of bytes, and if the measured free space falls below this, it is suppressed. The byte axis's perWorktreeByteReserve(clampPerWorktreeByteReserve (value clamped as the budget allocation against the capacity upper limit) is not used here — because the post-clamp value can be smaller than the actual single worktree size, using it for the physical disk exhaustion determination would miss the dangerous side. Same OR evaluation as the count axis and byte axis = if either one is on the dangerous side, suppress. When measurement is impossible, do not compensate with 0, and do not reuse old measured values as-is; treat it as an observation failure and stop new starts (fail-closed). In large-capacity environments or parallel environments, the sum of the already-submitted reservations of running tasks (reservedUnits) makes the required number of bytes large (e.g.: raw ~8 GiB × 9 total reservations = 72 GiB). A stop at run start (reservedUnits: 0) determines the required amount solely from the reservation of the start candidate itself, andargs.parallel lowering maxResidualWorktreeBytes or changingmaxResidualWorktreeBytes does not reduce this required amount (reservedUnits > 0is the upper limit of the total leftover size and is independent of this gate), so it can only be resolved by securing free space on the actual disk (including deleting gitignored build artifacts and dependencies in the main worktree). A stop during a run ( args.parallel loweringrawPerWorktreeByteReserve is also effective). Even if the update ofdu (recalculation of the reservation estimate derived from the actual measured du) fails due to either an unresolved implement path or an implement-only du failure, if the full measurement ( reserveStale: true kib) itself succeeds, only failed: true is returned and it is not made into(failed: true ), because making itwould cause omission of the cap latch that does not reach the all-kind latch which stops verify-close even when capacity excess has already been confirmed, the capacity-excess determination and the all-kind latch are confirmed upfront immediately after a successful full measurement).: reserveStale However, the defer determination for resuming monitoring is separate |
maxBaseMerges |
optional | 3 |
args.repo if unspecified, base import does not start regardless of the value(args.repo an invalid format stops with an error at startup and the run itself does not begin.repo line reference). When a PR conflicts with base (either themergeable: CONFLICTING。monitor の conflicting path or the merge-exec not-mergeable mapping), the upper limit (an integer from 0 to 10) of the number of times a base-import-dedicated agent that starts automatically without consuming the fix budget (fixCount) (baseMergePrompt. Verification of routing matching, fetch, merge, and push is performed by scripts/base-merge.sh , and the agent executes one command and transcribes the result).monitorsLeft It functions as an independent second termination guard. When the upper limit is reached, blocked / blockedReason: "quality" terminates with (halt is not counted. Unlike needs-fix when the fixCount limit is reached, even after the limit is reached, if a human directly pulls base into the PR branch and pushes, the conflict is resolved, and the next monitor does not return conflicting , and since this branch itself is not passed through again, unrecoverable is not used. Re-execution after the blocked termination resumes directly as monitoring — the Recover / PR Create phases are not passed through. Since baseMergeCount is carried over as the limit-reached value, resolution after reaching the limit requires a human to directly pull base into the PR branch and push).0 disables automatic base merging, and makes it immediately blocked upon conflict detection as an explicit opt-out (in this case too, blockedReason: "quality")。negative values, non-integers, and decimals stop with an error(same strictness as the merge gate input) |
repo |
optional (maxBaseMerges > 0 is effectively required if using base merging) |
unspecified ("") |
the target repository's owner/repo(e.g., "Fandhe-AI/agent-cli-skills")。scripts/base-merge.sh 's worktree routing guard (--repo。pr-create / fix の pr-push.sh(--mode prepare / push / pr 's 3 modes) and the observation script observe-pr.sh(making the gh call with -R attached) are also passed the same value. All lines of origin's fetch URL and push destination URL must have host github.com, owner/repo must exactly match this value case-insensitively, and gh pr view 's number and headRefName must match) as the expected owner/repo (expectedRepo), a host-side input explicitly specified by a human.Never use the agent's self-reported values (such as from an external check observation agent)(using self-reported values as a trust boundary cannot prevent pushes from a misplaced worktree to a different repository). If unspecified, expectedRepo is fixed as an empty string, base merging (baseMergePrompt startup) is not performed, and conflicting immediately terminates with blocked / blockedReason: "quality" (fail-closed. Implementation, pre-push Review, PR creation, and CI monitoring proceed automatically regardless of the value).invalid format (isValidRepoSlug values that do not pass the owner/repo format) stop with an error at startup(same strictness as the merge gate input. Because silently reinterpreting a typo as unspecified would quietly weaken the guard) |
agentCallLimit |
optional | 1000 |
the baseline value for the budget of the number of agent calls in 1 run (an integer from 81 to 1000.securityReview when enabled, the lower bound becomes 83. Issue #592).the assumed runtime limit used to decide to stop new starts and monitoring resumes, and the calls themselves are not stopped (startup processing, termination processing, and running issues continue even if the value is exceeded. This is because stopping in the middle of a running issue creates a half-finished state. The runtime holds the hard cap). The runtime cuts off at 1,000 agents per run, and the cutoff is completed is returned, so without a budget the run ends right after PR creation with no monitoring. Therefore, before starting new work (and resuming monitoring), verify that "remaining call count ≥ number of in-progress items × 30 + estimate for candidates (implementation 30, monitoring resume 12, verify-close 6) + reserve for termination processing (20 + rounding up of incomplete node count ÷ 100. For the 1 item first started in this run [when no items have been started yet and 0 are in progress], do not impose the rounding-up term, as a forward-progress guarantee)"; if this is not satisfied, do not start and prioritize completing in-progress issues (if in-progress decreases, start again). Nodes that were deferred are not-started(returned as note: budget insufficient) (the note reports the facts at the time it was deferred. See below). Only the first time the usage count exceeds the value, output a warning log, and the return value is agentBudget.reached が true becomes. The rationale and breakdown of the estimates are in references/agent-call-budget.md.lower bound [startup processing 30 + reserve for termination processing 20 + estimate for 1 issue 30 + 1 = 81.securityReview when enabled, the estimate for 1 issue increases by 2, to 83] less than the lower bound, values over 1,000, or non-integers stop with an error(values that are used up by startup processing alone are not accepted because they are contradictory). The 30 for startup processing is a fixed estimate, and in a large tree with many chunks of dependency declarations, actual usage will exceed it. When no items have been started in this run and there are nodes deferred solely because of budget, at the end of the runstagnation due to budget exhaustion(return value agentBudget.starved: true) is determined (whether work can start is only known during the loop, such as via the monitoring resume worktree gate or resolution of assumptions during the run, so do not make a definitive judgment at startup). The note on deferred nodes (including the blocked note saved in the state file) does not predict the behavior of the next run, and writes onlythe facts at the time it was deferred: "Deferred due to insufficient budget (usage u/L at deferral, required amount r. k items started in this run). At the time of deferral, args.agentCallLimit if is N or greater, the budget check passed (the required amount for the next run changes based on startup processing, nodes started first, and gate measurements)". N = usage at deferral + required amount at deferral (the threshold actually used by the gate. Do not add extra). When N exceeds 1,000, add only the fact "(exceeds the specifiable upper limit 1000)" and do not suggest splitting (deferral occurs only with used + required > limit , so with the default upper limit of 1000, N always exceeds 1,000). Return value agentBudget.stoppedDispatchAt(the usage count at the time of the first deferral) and held[].used(the usage count at the time that node was last determined to be deferred) are values at different times, and the latter can be larger. Return value agentBudget.held returns the observed values { issue, kind, resume, used, required, chunks, needed, budgetOnly } of all nodes deferred due to budget (including those coexisting with other stop reasons) in ascending issue number order (if read by a program, held, if read by a human, note).agentBudget.neededLimit は held of budgetOnly those that are needed minimum value (regardless of whether work has started; if none, null. It can exceed 1,000, and is not necessarily a value that can be passed as-is to agentCallLimit ),starved is when there are 0 started items and such a node exists. For notes on unstarted / monitoring resumption, list all applicable stop reasons in priority order (halt → suppression of new starts [remaining worktree limit, etc.] → prerequisites → resume gate → budget). For prerequisites, write separately those not yet settled ("waiting because prerequisite #A is incomplete") and those already recorded as failed/blocked ("prerequisite #B is not complete (recorded as failed/blocked)"). The budget fragment uses the same wording whether alone or alongside other reasons (nodes with other remaining reasons are not counted as targets of starved / neededLimit , and inheld Then budgetOnly: false. For details, see "Stop reasons in the note at termination" in references/agent-call-budget.md) |
models |
optional | unspecified ({}) |
override the model of judgment-involving agents per stage(parseAgentModels). Keys and target agents: plan(Plan. By default, do not pass a model and inherit the session model)・implement(Implement and recovery Implement)・review(pre-push Review)・securityReview(security-only Review.securityReview can be specified only when enabled; specifying it while disabled causes a startup error. The default is models.review, or if absent, sonnet)・fix(fix for the Review loop and Merge loop)・prCreate(push + PR creation)・baseMerge(base incorporation. From #603 round 3 onward, scripts/base-merge.sh is an agent that simply runs once and transcribes one resulting line, and routing verification, fetch, merge, and push validation are performed by scripts regardless of the model. Since it involves no judgment, it remains as an exception to the policy below that excludes mechanical agents. This is intended for use when specifying haiku to reduce cost).plan・securityReview defaults other than sonnet. The value is any of the aliases agent() の model passed to haiku / sonnet / opus / fable . Stages not specified remain at their defaults; if there are multiple agents in the same stage, the same value applies to all of them. The return value models includes the normalized value (in the order of the stages above; if unspecified, {}).Mechanical agents such as status files, worktree scanning, Tree, Recover safety checks, monitor, merge-exec, merge-verify, pr-bind, and close are excluded(Because there are many invocations and overwriting increases fixed costs, and to avoid creating a path where the caller can change the agent's model that is involved in the safe-side determination of merging). The Recover decision (continue / discard) inherits the session's model just like Plan. Anything other than an object, unknown keys (including mechanical agent stages), disallowed values, and case differences stop with a startup error (the agent is not invoked even once. Typos are not silently reinterpreted as defaults) |
securityReview |
optional | false |
true or {"enabled": true} and add a security-dedicated Review agent to each round of the pre-push Review(opt-in。parseSecurityReview). With the same worktree isolation as the normal Review (which looks at quality and security with one agent), the same comparison baseline and diff (git diff origin/<base>...HEAD) and the same return schema, launch in parallel agents whose perspective is narrowed to authentication, authorization, input validation and injection, exposure of secrets and personal information, privilege boundaries, and OWASP Top 10, and do not show each other's results. The determination combines both: if either is blocked then blocked, if either is needs-fix then that round does not pass and all findings from the side that has findings are passed to fix,highestSeverity is the higher of the two (invalid results,needs-fix yet severity none contradictory output is equivalent to medium). Existing determinations such as the rule to pass if only Low in the final round are applied to the combined result. The model default is the same as the normal Review (models.review, if not present sonnet)で、models.securityReview can be changed with. Return value securityReview({ enabled, model }) and log both results for each round. Cost: when enabled, each Review round adds 1 agent (up to 3) and 1 disposable worktree (up to 3). Therefore, the guideline for the number of invocations per issue (agentCallLimit determination) from 30 → 32,agentCallLimit lower bound from 81 → 83, and increase the reservation of disposable worktrees for 1 new start by 3. If unspecified,false・{"enabled": false} the agent invocation is the same as now. Any other form (string, number, array,enabled keys other than,enabled is not boolean) stops with a startup error. Do not add it to paths that do not go through Review before push (base incorporation at PR creation, base incorporation in the Merge loop) (see Step 5) |
externalChecks 4 states:
| Specified | Meaning | Merge behavior |
|---|---|---|
| Unspecified | External check configuration isundetermined | Stop automatic merge regardless of observation results and blocked terminate with (proceed through implementation, PR creation, and CI) |
[] |
"Do not use external checks" by a humanconfirmed | Skip waiting for external review and determine only by CI green and no unresolved threads |
[{"app": "cursor", "context": "Cursor Bugbot"}] etc. |
Specified App + trusted required check context are authoritative (overriding observed results) | specifiedall Apps verify the launch against HEAD sha. For cursor, the condition is "one or more reviews have arrived and CHANGES_REQUESTED is 0" (individual comments remain as review threads, so the "0 unresolved threads" gate blocks content-independently. The monitoring side's content evaluation is advisory for the fix loop and is not an input to mergeability); for other Apps, if there is 1 or more check-runs, all of them must have an allowable conclusion, and only when there are 0 check-runs is the fallback merge condition "1 or more APPROVED reviews and 0 negative reviews". In opt-in merge, G0 declares context is matched against the App ID pair for required status |
["cursor"] etc. (old format with slug only) |
the App is determined but the trusted context isnot declared | Monitoring and waiting for external reviews are the same as above. However, client-side auto-merge stops fail-closed (autoMerge: true does not merge even with blocked termination. This is because matching by App ID alone would pass G0 even when an unrelated context of the same App is made required) |
Observation-based detection only looks at the most recent 3 merged PRs, so it misses newly introduced Apps, conditionally triggered Apps, and Apps that were not run in the most recent 3. Of course, "no detection" is not proof of absence, and"detected" also does not guarantee completeness as a set(e.g., in observation, only sonarcloud are picked up, while actually required cursor are missed and it is treated as "confirmed", skipping revalidation of the cursor[bot] review). Therefore, observation results are not treated as confirmed information, but merely kept as reference values in logs, stop reasons, and return values.externalChecks is not an array, or the slug / context format is invalid (context must be 1 to 255 characters, and may not contain control characters (newlines, tabs, etc.) or only leading/trailing whitespace. GitHub's context has no character-type contract, so character types are not restricted; matrix-derived build [ubuntu] and contexts containing Japanese can be declared as-is — safety of embedding into shell / jq is guaranteed by single-quoted literals + jq --arg value passing) · if there are 11 or more, stop with an error instead of falling back to the default (parallel is a performance knob, so invalid values fall back to the default 3, butexternalChecks is an input to the merge gate, and silently reading a typo as "unspecified" or "confirmed none" would quietly weaken the gate).
opt-in test declaration (optional, disabled by default, Issue #495 / PR #503 codex P0)
#[ignore] tests with make e2e-* For issues whose acceptance criteria include tests that are not run by the default CI/tests, declaring this in the issue body as an HTML comment adds "the PR body contains a record of a passing run" to the pre-merge gate. For issues without such a declaration, this section's branching is not entered at all (the prompt, the judgment, and the PR body all remain identical to the current behavior. Disabled by default).
The only basis for commands permitted to run is args.optinTestCommands(the list of approvals explicitly given by a human at run launch time), and a declaration in the issue body alone cannot introduce a new command(make / npm run / yarn run / deno task etc. are dispatchers for arbitrary tasks, and validating only the permitted runner/subcommand form cannot close off arbitrary task launches such as make deploy・npm run release ). A declaration in the issue body is adopted only if, after normalization (removing leading and trailing whitespace, collapsing consecutive horizontal whitespace into a single half-width space), it args.optinTestCommands matches any element ofexact string match. Declarations that do not match, or declarations whereargs.optinTestCommands is unspecified / [] , are all treated as invalid and the implementation stops before launching at blocked (fail-closed).
Declaration format (one command per marker, maximum 10 items. The upper limit on the approval list side is args.optinTestCommands maximum 20 items):
<!-- optin-tests: make e2e-three-client -->
<!-- optin-tests: cargo test -- --ignored -->
For the above declaration to be adopted,args.optinTestCommands must contain an element that exactly matches the normalized value (e.g., ["make e2e-three-client", "cargo test -- --ignored"]).
args.optinTestCommands Each element of is validated for permitted form at launch time (validateOptinCommandForm. The first token must be one of the permitted test runners make / just / cargo / npm / pnpm / yarn / bun / go / pytest / deno / mvn / gradle / dotnet / swift / mix , and it must not contain shell metacharacters (; | & $ ), newlines,. not adjacent to ..(parent directory reference.go test ./... such as ... values containing are permitted),//, or absolute path arguments (a = at the start of a token or immediately after /. Example: cargo test --target-dir /tmp/x). If even one item is outside the permitted form, the implementation does not launch at all andstops with a launch-time error(externalChecks same strictness as . Misspellings are not silently reinterpreted).npm / pnpm / yarn / bun / cargo / go / dotnet / swift / mix / deno / mvn / gradle also restricts the second token (subcommand) to test etc.mvn additionally rejects GAV-format goal specifications (groupId:artifactId:goal etc., tokens containing two or more: ) as, anddeno additionally rejects remote specifiers (tokens beginning withnpm: / jsr: / http: / https: ) as, detour routes for arbitrary plugin execution and external code retrieval. This form validation applies only to the approval list side (because once a command is on the approval list, it is guaranteed to be in permitted form, the issue body declaration side only performs normalization + exact-match verification).
For issues whose declaration is adopted, the Implement / recovery Implement agent executes each command and reports the result (optinTestRuns). Execute as a required procedure. Reporting anything not executed as pass is prohibited, and if it cannot be executed due to environmental factors, return not-run and the reason. The PR body will be appended with a "## opt-in test execution record" section (a single heading line and, for each command, a human-readable line - opt-in テスト結果: <コマンド> => <result> + a machine-readable marker line). The record section consists only of fixed-format lines assembled solely from host-verified values (heading, 40-digit sha, result, commands matching the approval list), andnot-run reasons and other supplementary notes are not written in the PR body but are kept only in return values and logs. When updating in a reuse PR or post-push fix, all lines whose entire line matches the format of the record section's heading, human-readable lines, or marker lines are removed using a fixed pattern with start-of-line and end-of-line anchors (grep -vE), and then rewritten, so duplicate headings and old record lines do not remain, while lines that merely quote the heading or prefix within the body's explanatory text are preserved. The marker line uses a format bound with the HEAD sha at the beginning(<!-- optin-test-record: <40 桁 sha> <pass|fail|not-run> <コマンド> -->). Since sha and result use a fixed format (containing no spaces) and are placed before the command string (which may contain spaces),grep -cxF a parse becomes unique by exact match alone. This sha is the value of the HEAD that the agent writing the record itself obtained via git rev-parse HEAD and actually pushed (or is about to push).
Before merging (only for the new merge path.recoveryOnly does not apply), a read-only record verification agent confirms, counting only the number of items, that for each declared command there is at least one pass marker line and zero non-pass marker lines in the PR body (the body text itself is not placed in the context or return values. Same context separation contract as merge-exec).This count counts only "marker lines for the current PR headRefOid"(the verification agent obtains gh pr view --json body,headRefOid in a single call, and if headRefOid cannot be obtained as a 40-digit sha, all are treated as failing). Old records after HEAD has changed due to base incorporation (baseMergePrompt) or another push, or records before a fix, do not match the sha and thus do not hit grep at all, being treated as "nonexistent" and automatically failing (because without binding which HEAD a record is a result for, the gate could be passed merely by old pass markers remaining). If there is a deficiency, do not merge and stop with blocked(blockedReason: quality), and specify the deficient command in the termination reason.This PR body-based determination is ANDed with the actual measurements re-executed by the Merge loop's post-push fix (optinFixState. runs and the target HEAD's headSha are persisted to the state file and restored when monitoring resumes): If even one non-pass remains in the actual measurement of the fix, treat it as a failure even if the PR body remains pass (a multi-layered defense against fail-open due to failure or omission of PR body updates. The override works only when the fix's headSha matches the current headRefOid, and after HEAD advances further it defers without intervention to the sha-binding judgment on the PR body side — so that an old measurement does not permanently block the PR of a new HEAD).
This verified headRefOid, finalized immediately before the merge-exec call,is also passed to merge-exec as the expected HEAD sha(TOCTOU countermeasure). merge-exec additionally confirms that the headRefOid it self-acquires in step 2 matches this expected value, and if they do not match, it reason: head-moved declines. This expected value --match-head-commit does not become an input to--match-head-commit (only merge-exec's self-acquired value is used for
Persistence (optinFixState) writes, for each round that the post-push fix pushed (f.pushed === true), runs・headSha to the state file. The write confirms success or failure; on failure it retries once, and if it still fails it terminates fail-closed with blocked . The state file update on the termination path (failMergeTerminal) also includes optinFixState (otherwise, the actual measurement of a round terminated via another path after the fix ran would be lost). For the recovery procedure, see references/recovery.md .
Server-side delegation of auto-merge and the merge-guard hook (deny-only, best-effort)
Client-side auto-merge is executed only in opt-in runs where autoMerge: true + externalChecks is finalized (including trusted context declarations from all Apps)(see the next section, "Client-side auto-merge design". Under the opt-out default, no merge is performed. No auto-merge reservation (arm) is provided). The merge-guard hook is deny-only (not an approval boundary, but a bypassable best-effort reduction of attack surface).
Details: references/automerge-design.md
Client-side auto-merge design (important)
Client-side merge in opt-in runs addresses unapproved-merge inducement caused by false output from the monitor, which reads untrusted review bodies, with the following three layers: separation of monitor output from the merge path; merge-exec's self-acquired re-verification; and G0 server-side enforcement in actual measurement (in addition to the non-bypassability of required checks, it confirms the mandatory resolution of review threads, the required-ization of passing-judgment target check contexts (absence of client-only checks), the required-ization of external check Apps' declared context + App ID pair binding, and the integration_id binding of all required checks entries' issuers (blocking impersonation of same-named commit statuses — issuer-unbound declines), assuming a configuration in which the server rejects under the same conditions no matter which agent of the shared gh authentication attempts a direct merge): these three layers.
Details: references/automerge-design.md
branch protection (the core of merge determination; required for both human-merge and server-side auto-merge operations)
For the target base branch,we strongly recommend configuring server-side branch protection / ruleset(an operational recommendation, not a runtime gate). Even a compromised local agent cannot bypass server-side rules.
Details: references/automerge-design.md
Flow
Step 1: Fetch the tree and build an execution queue with a dependency graph (Tree)
Recursively fetch the entire tree under the parent issue down to the lowest layer using the sub-issues API of the gh CLI, and build an execution queue via post-order DFS. Fetching uses a queue approach, traversing the sub_issues of all nodes including closed nodes, without cutting off by depth. The only thing cut off is sub_issues_summary.total nodes with 0 (confirmed as leaves), and already-visited numbers are not traversed again. For each node, record subIssuesTotal(sub_issues_summary.total. total number of immediate children including closed) and have the host verify for all nodes that "the number of children among returned nodes == subIssuesTotal". If there is even one mismatch, stop the Workflow (fail-closed. Do not mistake a node that failed to be fetched for a leaf and silently leave its subtree unimplemented). For each open issue, read the body and extract functional dependencies (dependsOn).
From the body of each open issue, also mechanically extract the opt-in test declaration marker (<!-- optin-tests: ... -->) and re-validate on the host side whether it is in an allowed format (see the aforementioned "Opt-in Test Declaration" section. If there is no declaration, subsequent processing remains the same as the current behavior).
Following tree fetching, observe external check Apps other than GitHub Actions (e.g., Cursor Bugbot) from the check-runs of the last 3 merged PRs.Observation results are reference values, not definitive configuration information. Configuration is finalized by explicit input in args.externalChecks , and unless there is an explicit input, treat it as "cannot be determined" and stop auto-merge in the subsequent Merge step.
# 各ノードのサブイシューを取得(--paginate で 100 件超も全ページ自動取得。子ごとに繰り返す)
gh api --paginate "repos/{owner}/{repo}/issues/<parent>/sub_issues?per_page=100"
# 各 open イシューの本文を読み、機能的依存を抽出
gh issue view <N>
# 外部チェック観測(直前 3 件の merged PR の check-runs を確認。結果は参考値)
REPO=$(gh repo view --json owner,name --jq '"\(.owner.login)/\(.name)"')
# SHA は位置引数 $1、REPO は位置引数 $2、jq フィルタは位置引数 $3 で渡す
# (REPO を子シェル内で "${REPO}" と展開すると非 export の変数は sh -c に渡らず空になり、
# gh api が必ず失敗して常に apps: [] へフォールバックする)
gh pr list --state merged --limit 3 --json headRefOid --jq '.[].headRefOid' \
| xargs -I{} sh -c 'gh api "repos/$2/commits/$1/check-runs" --jq "$3" 2>/dev/null' \
_ {} "$REPO" '[.check_runs[] | select(.app.slug != "github-actions") | .app.slug] | .[]' \
| sort -u
Rules for building the execution queue and dependency graph:
- Order sub-issues within the same parent by the sub_issues API return order (
siblingIndex) - Process the parent issue only after all child issues are complete (parent nodes are verify-close)
- Automatically skip closed issues (treated as complete at run start). However, if there is an open descendant under a closed child, the parent's verify-close also waits for the completion of that open descendant (the first one appearing by penetrating through closed nodes). If it does not wait, the parent's verification runs while the subtree is incomplete, resulting in
failed(halt count) dependsOnInclude in only issue numbers for which "functional prior completion is mandatory" (limited to explicit dependency descriptions or prerequisite implementations in the body. Do not include mere relatedness or mere possibility of conflict)- In addition to the Tree agent's
dependsOnjudgment, mechanically extract dependency declarations from the body andtake the union(plan:declared-deps-*. Judgment-based extraction misses items in large trees, so it serves as a lower bound). Targets are dependency headings sections (## 依存/## 依存関係/## 前提/## Depends on/## Dependencies/## Blocked by. Heading levels 1-6, trailing colon allowed.## 依存クレートsuch other headings are excluded by an end-of-line anchor) placed at the beginning of a line (immediately after a bullet marker or checkbox) as#Nsequences and inline notationDepends on #N/Blocked by #N(including heading lines. Immediately after negations not / no longer / never / n't [words inserted without punctuation are within 1 word.not yet blocked byetc.] declarations are excluded, and unrelated negations do not drop dependencies on the same line).#Nsequences accept separators of whitespace, commas, Japanese commas, slashes, and "and" (#1, #2, and #3etc.). Even within a section, references other than at the beginning of a line (e.g., "No dependencies. Related issue #42") are not picked up, and line-initial items containing related / reference / negation terms (関連 / 参考 / 参照 / 任意 / なし / 不要 / related / see also / optional / none / no longer / not / never / unnecessary / n't) are excluded (line-level judgment applies only to line-initial items with one declaration per line, and not to inline notation). Inside code fences (preserving the opening symbol and length, and closing only on a closing line of the same type and equal or greater length), quote lines, and inline code (pairing backtick runs of the same length and removing them along with their contents; code spans spanning newlines are also removed on a paragraph basis and do not cross block boundaries) are excluded (to make dependency edges only for those where functional prior completion is required). Indented lines are extracted rather than treated as code blocks (list content indentation cannot be judged line by line, so bounded excessive waiting is chosen over missing items).gh api repos/{owner}/{repo}/issues/<N> --jq(REST core frame. Does not consume GraphQL frames) handles only output normalized into integer arrays, and body text is not placed into the agent's context. In chunks of 40 items, run at most 3 chunks concurrently (DECLARED_DEPS_CONCURRENCY) and verify the match between the full return of all numbers requested by the host and the check value computed by jq from issue numbers and depssigversus the value recomputed from the returned deps (since the host has no shell and cannot directly verify command output, transcription errors are detected by the check value. Missing items or contract violations [duplicate numbers, non-integers, deps not an array, over the limit, sig mismatch] are retried only once, and if still missing, stop before run start as fail-closed. This is to avoid starting with dependencies missed. Entries for numbers not requested are not adopted and are ignored while logged. This is because when user statements relayed by the Workflow harness contain multiple issue numbers, the extraction agent returns numbers from other runs too; since sig includes the number, it does not turn into a requested number, and missing requested numbers still cause a stop as before. Chunks confirmed as rate-limited (stderr messages containing rate limit / secondary rate limit /RATE_LIMITED, or HTTP 403/429 withgh api rate_limitの core のremainingseconds until the agent returns a recovery, the host waits that many seconds before retrying the unacquired portion (other 403s such as insufficient permissions or SSO are not treated as rate limiting, but are retried as ordinary failures, and if still not acquired, it stops. The secondary rate limit is unrelated to the core reset, soretry-afterseconds, or if absent, waits a fixed 60 seconds. Waiting does not consume retry attempts, up to 2 times per chunk. If the recovery exceeds 900 seconds, or if waiting is not possible, it does not wait, and stops indicating that it is transient and the resumable time. After the whole process has stopped due to a failure in another chunk, chunks whose wait has ended also do not call the agent). State acquisition under the out-of-tree assumption is the same [rate-limit recovery waiting is excluded]) - To an ancestor issue,
dependsOnis ignored (because the parent is the side that waits for the child's completion) - Wait for out-of-tree prerequisite issues (fail-closed, enabled by default):
dependsOn(the final value after the union of the Tree agent's extraction and the body declaration), numbers that are out-of-tree (args.parentnot under) have only their state mechanically acquired every run (plan:out-of-tree-deps-*。gh issue view <N> --json number,stateonly, without reading the body. Numbers that cannot be acquired as an issue aregh pr view <N> --json number,statereacquired with. Up to 200 per run, 40 per chunk, 1 retry). An issue with an open prerequisite is not started, and withblocked(not counted as halt) it records "not started because out-of-tree prerequisite issue #N is open (it will start when re-executed after close)", and successors that have it in the tree asdependsOnalso wait with "not started due to prerequisite issue failure/block". Numbers whose state could not be acquired (gh failure, nonexistent number, limit exceeded) are treated as open and waited on, with the reason left in the log. Prerequisites that are closed (or MERGED if the number is a PR) have no constraint as before. The root's ancestors (the parent chain of sub-issues.plan:root-ancestors-<round>が GraphQL のIssue.parentis traced 8 levels per round (ROOT_ANCESTOR_DEPTH) at a time, and if the true end is not reached, the starting point of the next round is appended to the deepest node of the previous round, up to a maximum of 5 rounds (ROOT_ANCESTOR_MAX_ROUNDS) = up to 40 levels,(number, parent)chain is confirmed) are not waited on because they are the side that waits for the child's completion. The host verifies that the chain starts from the root and that eachparentmatches the nextnumber, and if acquisition fails or there is an inconsistency, it falls to the waiting side without excluding ancestors, including the accumulated portion (fail-closed). If the end is still not reached even after reaching the safety limit of 5 rounds, ancestor confirmation beyond that is aborted and, as an out-of-tree prerequisite, the state is checked and waited on as usual. For numbers excluded as ancestors, only those that actually appeared in out-of-tree dependencies are output to the log. State transcription is the inspection value computed by jqsigThe host verifies this, and if there is a mismatch, it retries and then treats it as unobtainable (waiting). Since state is not saved to a state file, if the same args are rerun after closing the premise, it will be reevaluated and work will begin. The in-run premise completion probe (below) does not target numbers outside the tree (they are reflected on rerun). The operation assumes that human-assigned issues are managed in a separate tracking tree, and that their numbers are written in the dependency section of the implementation issue body - If there is a cycle in the dependency graph, detect it with DFS and remove the non-tree edges that form the cycle (
dependsOn) to prevent deadlock - Dependency blocks are re-evaluated on each cycle: even if downstream work cannot begin due to a failed or blocked prerequisite issue, do not finalize it immediately; keep it pending, andonly before halt occurs (stopping new work starts after 3 consecutive issues fail to complete. See Step 8), if a prerequisite is externally completed during the run (Issue CLOSED / PR MERGED), re-evaluate downstream work within the same run and begin it. After halt, only the probe and state recording (
prereqTransitionsand state persistence) continue, and new work is not resumed (halt is a safeguard that waits for user judgment and is not automatically lifted). External completions recorded after halt are reflected in downstream work when the next run is rerun - By default (
phaseGateunspecified /false),siblingIndexis merely a post-order priority. In parallel runs (parallel >= 2), leaves of a later Phase may be placed into free slots before the previous Phase completes (overtaking).create-issue-tree/update-issue-treeThe operational rule for the root body generated by "execution order is the order of the sub-issues list" isstrictlyIf you want to guarantee it, usephaseGate: true(phaseGateSee the explanation of the argument)
Step 2: Determine per-issue whether interrupted work can be recovered (Recover)
Before starting each leaf issue, check whether a leftover worktree / branch exists.If there is no existing work, skip Recover and proceed to Plan. If there is existing work, the Recover phase (an agent in the session inheritance model) determines whether "the in-progress work can be continued," and branches to one of the following depending on the result.
- continue: Check out the existing branch as is, pass the recovery brief (summary of done / remaining / broken) to Implement, and continue implementation from there. Plan is skipped. Recover never proceeds directly to Review; continued work always goes through Implement → Review → Merge. Deletion of the old worktree is only when completion of WIP evacuation can be verifiedperformed (the deletion gate described later). If it cannot be verified, do not delete the leftovers; preserve them with
failed(continuing while missing uncommitted changes that have not been evacuated would result in an incomplete implementation, so do not skip only the deletion and continue). In addition, cleaning up the old worktree andimplementing/reviewingIf the completion of the transition could not be confirmed via the return value of the state update, do not proceed either, andfailedpreserve it (if the old worktree still holds the branch, the new worktree cannot check out the same branch, andreviewingcontinuing without persisting leads to duplicate implementation. This pairs with the cleanup completion confirmation on the discard side). - discard: Delete the existing worktree and branch, then re-run with the normal Plan → Implement (new branch). Deletion is performed only when the completion of the WIP save has been verified(the deletion gate described below). If it cannot be verified, do not delete the remnants but preserve them with
failedand leave it to Recover on the next run. In addition, if the completion of the worktree / branch cleanup could not be confirmed via the return value of the state update, do not proceed to Plan either, and preserve it withfailed(because re-Planning while the branch remains causesgit checkout -Bto orphan the WIP commit).
The criteria for Recover are separate from those for Review. While Review judges "is the implementation correct / can it be merged," Recover judges "is it reasonable to continue from this in-progress work." Even if it does not work or is incomplete, if the direction is reasonable, continue (the rest is completed by Implement).
Uncommitted changes are saved to the branch as a WIP commit before deleting the worktree, so data is not lost on either the continue or discard path. In the case of discard, the branch is deleted with the WIP commit left in place.After deletion it does not remain in the reflog(it only remains as an unreachable object until gc), soworktree-remove.sh outputs the branch head sha from before deletion in the result, and the host records it in the log (git branch <名前> <sha> it can be restored until gc).
Deletion gate (common to continue / discard): The wipCommitted returned by the Recover agent is a self-reported value and can be tricked into true by misjudgment, abnormal responses, or prompt injection. In addition, Recover has a contract that "if saving failed due to a hook failure, etc., it returns wipCommitted: false and continues," socontinue can also be returned when saving fails. Therefore on either the continue / discard path the deletion of the worktree is executed only when both of the following 2 conditions arebothsatisfied.
- Declaration gate: The Recover agent returns
wipCommitted: true(true when it saved, and when there were no uncommitted changes that should be saved from the start. false when saving failed due to a hook failure, etc.) - Fact gate: The
scripts/worktree-remove.sh remove --mode discardrunning in the same process as the deletion confirms that the target worktree has no uncommitted changes (git -c core.excludesFile= status --porcelain=v2 -uall --ignore-submodules=noneoutput. In a form not affected by the user's status settings or global exclude files) and no initialized submodules, and--forceIt has been deleted without using. If a locked Claude Code session is still alive, it is retained without being deleted
If either condition is not satisfied (including cases where the script retained the worktree), or if the cleanup itself fails, the worktree / branch is not deleted and is failed preserved with (fail-safe). The preserved remnants are re-evaluated by Recover on the next run. Remnants consisting only of a branch with no worktree have neither a deletion target nor uncommitted changes, so they are excluded from this gate.
Step 3: Formulate an implementation plan for each issue (Plan)
Before implementing each leaf issue, formulate an implementation plan with a session-inheritance-model agent (no worktree, read-only). The plan is passed to the Implement agent as an argument (to avoid cross-worktree file references).
If a continue decision is made in the Recover phase, skip Planand the Implement agent that received the recovery brief continues implementation directly from the existing branch.
The plan includes the following:
- Background and purpose (the problem the issue solves)
- Target files and change locations (paths and overview of changes)
- Implementation steps (concrete procedures executable in order)
- Verification method (procedures for build, lint, test, and operation check)
- Security considerations from the OWASP Top 10 perspective
If the planning agent terminates abnormally or the plan body is empty, record the relevant issue as failed and proceed to the next.
Step 4: Implement leaf issues in parallel with worktree isolation (Implement)
Greedily assign leaf implementation issues to free slots with post-order DFS order as the priority, with a maximum of parallel(default 3) executed in parallel. Each implement / fix agent is executed in isolation in anindependent git worktree , so branches and working copies do not conflict even in parallel.
No push or PR creation is performed here. To save CI resources, the design is to push and create PRs all at once only once after Review passes.
Processing content for each issue (implement according to the plan formulated in Step 3):
0. worktree routing guard(executed first): git remote get-url origin check with the issue title matching whether the current worktree is placed in the correct repo and issue
0b. Check existing PRs and remote branches(prevention of interrupted resume and duplicate PRs):
- 0b-a (open PR search):
gh pr list --state opencheck whether an open PR corresponding to the issue number already exists. If found, do not create a new PR, fetch that branch, work from where it left off, and return that branch name (do not return the PR number. An open PR for the same branch is re-detected and reused by the subsequent PR Create phase).Skip branch creation in step 2(origin/<base>fromcheckout -Band redoing it will lose that PR's commits) - 0b-b (remote branch reuse): if no open PR is found,
git ls-remote --heads origincheck whether a remote branch containing the issue number (naming convention:<type>/<N>-<short-name>) remains. Detect branches left over from "push succeeded, PR creation failed",git fetch origin <branch> && git checkout -B <branch> origin/<branch>and fetch with , then continue implementing while preserving the pushed commits (origin/<base>do not recreate from scratch). Return as the branch name, with prNumber remaining 0 (the PR will be created by the subsequent PR Create phase) - 0b-c: only if neither an open PR nor a remote branch exists, create a new branch in steps 1 and 2
-
In the isolated worktree,
git statuscheck whether is clean, and if there are differences, return failure without doing any work -
(Skipped if the branch of an existing open PR was fetched in 0b-a, or if a remote branch was reused in 0b-b) Create a working branch from the specified branch (default:
main) (include the issue number in the branch name to prevent branch name collisions during parallelism) -
Implement according to the given plan(planning is already completed in the Plan phase). For implementation, if the target repository has delegation rules or specialized sub-agents, follow them and delegate by role
Comment policy (during implementation):
- For code comments, write "why it exists / the role of the target as seen from the package or service" rather than "what it does"
- Since subsequent readers (including Claude) can only judge from the information given, explicitly state the perspective from other files, other services, and callers/callees (where this symbol is called from and which boundary it is responsible for)
- If the target repository has
.claude/rules/code-comment-style.md(init-claude) deployed, follow those detailed rules. If not present, follow the key points above
-
Pass build, lint, and tests according to the target repository's CLAUDE.md, rules, and test execution conventions. If a test fails, investigate the root cause before fixing it (if the target repository has
.claude/rules/debugging.md, follow its four phases in order. If not present, follow the same policy [investigation → analysis → hypothesis → fix]. If the same location fails 3 times, judge it to be an architectural problem, record the relevant issue asblockedand report the situation to the user) 4b. Only when there is an opt-in test declaration: for each declared command, confirm before execution (whether it is a test entry point defined in the target repository) → execute as a single command (sh -c/evalprohibited) → report the result (pass/fail/not-run). Do not report something that was not executed aspass(see the aforementioned "Declaration of opt-in tests" section) -
After implementation, perform a security check from the OWASP Top 10 perspective (hardcoded API keys, injection, etc.). If any issues are found, fix them before proceeding to the next step.
-
Once implementation is complete,
create-commitfollow the skill and use Conventional Commits tocreate one implementation commit. Before committing, read the target repo's commitlint configuration (thecommitlint.config.*/.commitlintrc*/package.jsonのcommitlintfield)and checktype-enum/scope-enum, and use only allowed values. If there is no applicable scope, omit the scope entirely (in repos wherefeat: 実装内容)。do not put the issue number in scope (scope-enumis set, it will always fail, and will only be detected at push after consuming 3 rounds of Review). Link to the issue using the footer'sRefs #<N>and the PR body'sCloses #<N>. For the subject of the base-incorporation merge commit created by the pre-push base update gate (Step 5 / Merge loop fix), determine type / scope using the same procedure (it will be rejected by the commit-msg hook of repos with a fixedchore:はtype-enum/scope-enum. If rejected,git merge --abortand fail-closed without pushing) -
Do not push or create a PR here. Finish with the commits stacked on the local branch, and hand off to the subsequent Review phase
# 作業ブランチ作成例(並列時の衝突回避のためイシュー番号を含める)
git fetch origin && git checkout -B feat/<N>-<short-name> origin/<base-branch>
# 実装コミット(push しない)
# scope はイシュー番号ではなく変更対象のモジュール・ディレクトリ名。
# 対象リポの commitlint の scope-enum に該当する値が無ければ scope ごと省略する。
git commit -m "$(cat <<'EOF'
feat(<module>): 実装内容
Refs #<N>
EOF
)"
# → push・PR 作成は Review 全通過後に行う
Step 5: Independently review the local diff before push (Review)
After Implement completes and before push, launch an independent Review agent in worktree isolation to review the local diff.Do not push or create a PR, and review only the local commits. The Review agentdoes not make fixes, only judges.
Purpose of saving CI resources: If Review fails to converge, neither push nor PR creation is performed, so CI is not triggered at all. This reduces the cost of repeatedly pushing → running CI for each fix.
Review is performed in the following two stages.
①Spec compliance review(performed first):
- Check whether the issue's requirements and acceptance criteria are satisfied
- Check whether out-of-scope implementation has been mixed in
- Check whether implementation follows the Plan phase's plan
②Code quality review(performed after ① passes):
- Check readability, duplication, and design (architecture compliance, naming conventions)
- Check OWASP Top 10 security (hardcoded API keys, injection, authentication/authorization, etc.)
For details, refer to the implement-review skill.
③Security-specific Review(args.securityReview Only when enabled. Default is disabled): In each round, launch a separate agent from the above Review in parallel, and with the same worktree isolation, the same comparison baseline, and the same diff, examine only security (authentication, authorization, input validation and injection, exposure of secrets and personal information, privilege boundaries, OWASP Top 10). If the target repository's CLAUDE.md, rules, or specialized subagents contain security review procedures or perspectives, follow them. Do not show each other's results. The return uses the same schema as a normal Review, and the host combines both (if either is blocked then blocked, if either is needs-fix then it does not pass and all findings from the side that has findings are passed to fix,highestSeverity is the higher one). The following judgments (including the handling of Low in the final round) are applied to the combined result. Do not add this to conflict resolution performed at PR creation (Step 5.5) or when incorporating the base in the Merge loop: both do not go through a normal Review, and are existing designs verified after push by CI, external checks, and monitor; the diff being incorporated consists of already-reviewed commits on the base side and their resolution, and imposing a pre-push review for security only would cause the targets of the two Reviews to diverge. If one Review agent terminates with an exception, wait for both to settle, then record the disposable worktree in the ledger (the side that threw the exception is counted as one case with an unknown path), and report it via the same path as a normal exception in a standalone Review (end that issue with failed . Do not proceed to fix). A missing StructuredOutput (null) is treated as an invalid result with findings, as before.
Review conditions:
git checkout --detach <branch>to fetch the local branch as a detached HEAD (origin/<branch>does not exist because it is before push)- Immediately before review,
git fetch origin <base-branch>:refs/remotes/origin/<base-branch>を always run onceto bring the comparison baseline up to date (do not branch on whether the ref exists).Use a refspec with an explicit destination —git fetch origin <base-branch>a form that gives only the fetch source, such asFETCH_HEADonly updatesrefs/remotes/origin/<base-branch>and does not guarantee creation/update ofblocked, and after a successful fetch, resolution fails and a feasible review is dropped with git diff origin/<base-branch>...HEADto check the local diff (origin/<base-branch>(the remote-tracking ref re-fetched immediately before) is the comparison baseline. Because it is a three-dot range, the comparison point is fixed atmerge-base(origin/<base-branch>, HEAD)= the branch's merge base, and even if origin advances during the run afterward, the comparison point does not change. Even if an existing ref is present, if it is old, the merge-base falls before the actual branch point and unrelated commits on the base side are mixed into the diff, so do not use 'the ref exists' as grounds for freshness. If the fetch fails, or if it still cannot be resolved after fetching, do not perform the review and terminate fail-closed withstate: "blocked"/highestSeverity: "none".blockedis a dedicated state indicating that the review itself could not be performed due to environmental factors, and represents code findingsneeds-fixdiffers from the caller in handling and terminates immediately without launching a fix agent —needs-fix/criticalis not used. This is to avoid consuming the fix budget on attempts to fix unrelated code)- Even if there is at least one finding including Low (needs improvement),
needs-fix. If there are no findings,ok
ok in the case of, proceed to the Merge step via push + PR creation (Step 4.5).needs-fix in the case of, with the fix agentrecommit locallyand re-review (do not push).Review is performed at most 3 times, and in the final round (0 remaining), needs-fix cannot be re-reviewed, so no fix is performed and it is treated as convergence failure (to uphold the principle of always re-reviewing after a fix. In practice, fixes are at most 2 times). If it does not converge after 3 times,without pushing or creating a PR blocked record it as and proceed to the next issue. This blocked aggregates the remaining worktree, branch, and final findings into a report (see references/report-format.md), and on re-execution, restart from Recover (continue/discard) → the normal Implement path (pr: 0 because of this, it is not a monitoring restart. For details, see references/recovery.md).
Regarding re-evaluation of dependency blocks: even if a downstream issue is chain-blocked by a prerequisite issue's blocked(such as Review non-convergence in this section), the scheduler maintains the pending state on each cycle, andonly before halt occurs, if the prerequisite is externally completed during the run (manual merge/close), the downstream is re-evaluated within the same run. Detection of external completion after halt only probes and records state and is not reflected in new starts; it is reflected in the next run (for details, see Step 8).
Review / Merge の fix は fixCount(upper limit 6) is shared. Resolving conflicts with base (mergeable: CONFLICTING) does not consume fixCount and is managed by the independent budget baseMergeCount(upper limit maxBaseMerges. Default 3).
Step 5.5: After passing Review, push + create PR (PR Create)
Execute only after Review has fully passed (ok). This push triggers CI (push only once).
# Review 通過後にはじめて push する(CI がここで起動する)
git push origin <branch>
# PR 作成(Closes でイシューと紐付け)
gh pr create \
--base <branch> \
--title "feat: イシュータイトル" \
--body "$(cat <<'EOF'
## Summary
- 実装内容の要約
Closes #<N>
EOF
)"
If there is an opt-in test declaration, in the body, following the Closes line, also append a "## opt-in test execution record" section (including a machine-readable marker line for each command. The marker format binds the HEAD sha to be pushed. See the earlier "opt-in test declaration" section). Before this push, re-run the declared tests against the current HEAD after incorporating base (do not copy over results from the Implement time, as they may become stale after incorporating base). If there is no declaration, neither this section nor the re-execution procedure is output.
Reuse of an existing open PR: after successful push /gh pr create before, always check with gh pr list --state open --head <branch> --json number,baseRefName,headRefOid whether an open PR for this branch already exists. Interruption/resume (crash immediately after PR creation /pr saved failed When re-running from ), an open PR may still remain, and without checking, gh pr create this will always fail, leaving the live PR untracked.
There are two conditions for reuse, andonly when both are satisfiedthat number as prNumber and return it.
baseRefNamematches the specified base branch (reusing a PR opened from the same head to a different base (such as a release branch) willbase <branch>bypass the contract and be merged into an unintended branch)headRefOidmatches the tip sha of the pushed branch (do not merge a PR whose head moved due to a push by someone else or another run, along with unverified commits). The sha to compare must always be resolved from the branch ref (git rev-parse --verify "refs/heads/<branch>", or if it cannot be resolved,refs/remotes/origin/<branch>). The PR Create agent operates in an isolated worktree, and since there is no guarantee that the worktree has checked out the target branch,git rev-parse HEADmust not be used
When reusing a PR that satisfies the conditions, if the body does not contain Closes #<N>(and an "out-of-scope" section if there are out-of-scope items), append it. At this time,do not embed the existing body into a shell command string or HEREDOC(the body is untrusted data of external origin, and if a line consisting solely of the HEREDOC terminator string is planted, the HEREDOC will terminate early and subsequent lines will be executed as arbitrary commands).gh pr view <N> --json body --jq .body > "$f" directly to a file withgrep -qF after confirming existence with printf only append to the fixed template,gh pr edit <N> --body-file "$f" and update with . If only open PRs that do not satisfy the conditions exist, neither reuse nor new creation is performed; return prNumber: 0 and the reason and stop (branch is saved, so the next run recovers from impl step 0b).
If PR creation fails, record it as failed ,branch and save .branch The saved failed starts the Recover phase on the next re-run (impl step 0b is not reached). If continue, after recovery Implement step 2 has checked out the existing branch, git fetch origin <branch>:refs/remotes/origin/<branch> → git merge --ff-only refs/remotes/origin/<branch> makes the local follow the remote tip, recovering while retaining the pushed base-incorporation commit (the PR Create agent pushes the base-incorporation commit from detached HEAD and does not update the local refs/heads/<branch> , so without following, the next PR creation fails again with remote-ahead / diverged). A true diverged that cannot be fast-forwarded continues as is, and (iv) of the next PR creation stops it fail-closed.
Step 6: Monitor CI / external checks, confirm resolution of review comments, and squash merge (Merge)
scripts/observe-pr.sh --mode checks --until settled(gh pr checks --watch replacement. Issue #603 8th installment) wait for CI completion, and squash merge only when all of the following conditions are satisfied.
opt-in test record gate: If opt-in tests are declared in the issue, only for the new merge path (recoveryOnly not), immediately before the merge-exec call, start a read-only record verification agent, and check the number of PR body pass marker lines for each declared command only for those bound to the current headRefOid (the body is normalized to counts only via a temporary file, and like merge-exec, the body text is not put into the context of the executing entity). If there is a shortage, do not start merge-exec and stop with blocked(blockedReason: quality). Pass the verified headRefOid to merge-exec as the expected HEAD sha, and have it additionally confirm that it matches the value it obtained itself (TOCTOU countermeasure). However, if the PR has already been determined by independent confirmation to be MERGED , do not start this agent (Issue #509. Merge into the existing already-merged recovery path). For details, see the aforementioned "Declaration of opt-in tests" section andreferences/automerge-design.md .
Client-side auto-merge is executed only in opt-in runs (see the "Client-side auto-merge design" section in references/automerge-design.md): autoMerge: true + externalChecks In a run confirmed (including trusted context declarations for all Apps), after the monitor's ready determination, merge-exec via the verification script scripts/merge-gate.sh(run-verified.sh (#603, 6th batch) obtains and fixes the HEAD sha, then independently re-verifies all conditions (checks, number of unresolved threads, external check activation, G0 = actual measurement of server-side enforcement of the base branch: inability to bypass required checks (ruleset's bypass_actors empty. Repositories with only classic branch protection are declined as unsupported with classic-unsupported ), mandatory resolution of review threads, required-ization of passing-check target check contexts (absence of client-only checks), required-ization of the external check App's declared context + App ID pair binding, integration_id binding of the issuer of all required checks entries (blocking impersonation of same-name commit status — issuer-unbound declined with)), and executes a squash merge withgh pr merge --squash --delete-branch --match-head-commit <自己取得 sha> , and only if it passes merge-verify's independent confirmation (state=MERGED + exact match with the sha reported by merge-exec) does it terminate with merged . The monitor's output (ready / headSha) is not used as input to the merge path (ready is only the launch timing). In repositories where G0 cannot be confirmed, server-enforcement-missing(repositories with only classic branch protection terminate with classic-unsupported)で blocked (fail-closed. If ruleset-based branch protection is configured and it is rerun, it continues). In opt-out (default false)・externalChecks unconfirmed, trusted context undeclared (old format with slug only)) runs, do not execute a new merge, and terminate with the PR kept mergeable and blocked(blockedReason: quality)+ pr retained. At opt-out, even if monitor returns ready(including false), merge-exec gh pr merge is fixed to a recovery-only path that does not include (recoveryOnly mechanism. The opt-in determination is host deterministic code = args parsing only. It does not depend on model output or untrusted text). Close recovery for already-merged PRs (the already-merged path) passes in both modes. In addition to "PRs that were merged in a previous run but failed to be recorded in state", this path alsoserver-side auto-merge workflow (upstream's docs/implement-issue-tree/auto-merge-sample.yml) merges the PR while monitoringis covered in the same way, and both terminate as normal completion (merged).blocked + pr is subject to monitoring resumption in the next run, and merging is performed by a human on GitHubor delegated to the server-side auto-merge workflow + branch protection (see the "Server-side delegation of auto-merge and merge-guard hook" section in references/automerge-design.md).
Current contract of client-side auto-merge and approaches not adopted: In the allow path where the merge-guard hook performs an exact match on the grant issued by the host (the full canonical merge command = expectedCommand), an approval boundary cannot be created. While monitor reads untrusted review bodies, it shares the same Bash,gh authentication, and FS as merge-exec, andgh pr view it can obtain HEAD and forge a grant with an arbitrary nonce (grant forgery). There is no hook-only secret injection path, and since the hook cannot hold a key that it can verify and that subagents cannot read, signature / MAC also cannot be implemented, making it in principle impossible to implement unforgeable merge authorization in the hook. Client-side arm (agent precheck + hook carve-out) is also not adopted because the carve-out is not tied to authorization and opens arm to arbitrary subagents, the precheck can be fabricated by agent self-report, and--auto with immediate merge, the "reservation only" premise does not hold. The hook is deny-only (best-effort, not an approval boundary).Current contract (since the opt-in re-enablement on 2026-08-12): The default (autoMerge unspecified / false) does not perform a new merge and stops at the mergeable state blocked .autoMerge: true + externalChecks Only for opt-in runs with explicit (including trusted context declarations for all Apps), client-side squash merge is performed on the premise of separation from the monitor output merge path, self-acquisition re-verification by merge-exec, G0 (measurement of server-side enforcement. If it cannot be confirmed, server-enforcement-missing fail-closed decline with--match-head-commit, and independent verification by merge-verify (see the opt-in explanation at the beginning of this Step and the "Design of client-side auto-merge" section in references/automerge-design.md. Residual risks and their acceptance records are also in that section). grant / canary / branch-protection runtime gates, precheck / arm / hook carve-out are not provided.Outside the canonical path(monitor itself following the injection gh pr merge direct execution, REST / GraphQL merge, approve, alias / extension) is denied on a best-effort basis by the merge-guard hook, but this is merely one layer of bypassable defense in depth.What actually stops the merge is the opt-out default fail-closed behavior (the host does not open a new merge path without opt-in) and server-side branch protection(third party = non-author approval required, dismiss stale, normal/force push prohibited, required checks. See the "Server-side delegation of auto-merge and the merge-guard hook" section of references/automerge-design.md), and even in an opt-in run, it will not merge unless G0 empirically confirms server-side enforcement under the same conditions. Auto-merge that does not use opt-in delegates to the server-side workflow in the same section (upstream's docs/implement-issue-tree/auto-merge-sample.yml).
Separation of monitoring and merge execution, and independent verification of merged self-reports: This step is divided into three agents: monitoring, merge execution, and independent verification. Because the execution platform does not provide per-agent tool permission control, this is not a revocation of permissions but rathercontext separation(not letting untrusted text into the merge execution entity). For residual risks and the necessary platform support, see item 5, "Handling of untrusted data".
- Monitoring agent (monitor): checks CI, external checks, and review threads, and
state(ready/needs-fix/unresolved-comments/timeout/blocked)とheadShaperforms only advisory determination, returning (40 digits). Because it reads untrusted data in the form of PR review bodies, itgh pr merge/gh issue close/gh pr editdoes not have permission to execute the / resolve mutation.- Observation and waiting are done by a script (
scripts/observe-pr.sh, Issue #603, second batch): for the PR's state, mergeable, total check count, missing required contexts, arrival of external App reviews, and number of unresolved threads, monitor runsgh/jqwithout assemblingbash <skillDir>/scripts/run-verified.sh … observe-pr.sh --mode …and reads a one-line JSON envelope (payload of integers and fixed vocabulary). A single invocation of waiting (review arrival, required checks complete, zero total checks, waiting for CI completion--mode checks --until settled) must always return within 90 seconds of wall-clock time (OBSERVE_PR_WALL_SEC) plus a few seconds of cleanup, even when gh is slow or hangs (attach a 25-second time limit to each gh invocation and kill it group by group; if the remaining time is less than one observation's worth, do not start the next observation. This fits within the Bash tool's default timeout of 120 seconds).pendingeach time, increment--attemptby 1 and re-run the same command (maximum 7 times = approximately 10 minutes. Only for waiting for CI completion--until settledis it at 25-second intervals, 4 observations per invocation at approximately 83 seconds, maximum 30 times = approximately 40 minutes, the same as the longest for the oldgh pr checks --watch. The upper limit on the number of times is enforced by the script. This corrects the bug where the loop that the agent wrote itself each time ran all the way to the limit due topaste -sd+ | bc's BSD incompatibility). Acquisition failure returns aserr: 1, and does not fall back to 0 items / 0 missing. The only observation the host cross-checks and adopts from the envelope is the total check count (checksObservation. The basis for re-judging timeout and total count 0 as conflicting), and the other observations remain only as material for the monitor's advisory determination. Confirmation immediately after push (--mode push. The envelope for pr-create/fix agents to execute) is also neither verified nor adopted by the host (checksStarted/mergeableAfterPushremains dedicated to diagnosis and branching hints as before). The trust model is references/script-trust-model.md。
- Observation and waiting are done by a script (
- Merge execution agent (merge-exec): The host starts it when monitoring returns
ready. It does not read the review body, Issue body, orcheck namesat all,nor does it read files in the repository (CLAUDE.md,.claude/rulesetc. = untrusted text that can be modified on the PR side)(it does not insert COMMON, the shared instruction for implementation agents, and is configured with the same minimal instructions as merge-verify).The pre-merge verification (G0, checks, unresolved threads, mergeable, external checks) is performed byscripts/merge-gate.shfrom #603 round 6 onward(gh/jqprocedures are not in the prompt, and it returns the verdict termverdict(the same vocabulary as merge-exec's reason) in the envelope. merge-exec proceeds to the squash merge in step 3 only whenok, and the host verifies the envelope with the nonce, sha256, input, and HEAD sha before acceptingmerged: true / reason: merged. The merge execution itself is not included in the script; merge-exec performs it in the command form given in the prompt. For details, see the round 6 section of references/script-trust-model.md). The following refers to the contents of the verification (what the script reads). The PR'sstate/headRefOid/mergeable(enum, sha), the counts by checkstate(gh pr checks <N> --json state --jq '[.[].state] | group_by(.) | map({state: .[0], count: length})'. Rawgh pr checksや--json name / description / linkis not used), only thecount of unresolved review threads(removingcommentsfrom GraphQL and not fetching the body), and for the external check Apps determined byargs.externalChecks, only thecount and status enum for the HEAD sha(--jqnormalized by . Texts such as App names, check names, and bodies are not fetched) by re-fetching and verifying them itself, and furthermore the G0 gate (actual measurement of server-side enforcement on the base branch: non-bypassability of required checks (the ruleset'sbypass_actorsis empty. Repositories with only classic branch protection are unsupported because non-bypassability cannot be proven from a write token — declining withclassic-unsupported), mandatory resolution of review threads, and requirement of the passing-judgment target check contexts (verifying by the set difference in jq that there are 0 items among the check-runs / commit statuses on the HEAD sha that are not included in required, with thecount only. Context strings are not fetched) — requiring the binding of the external check App's declared context + App ID pair (context+integration_id) + the issuing originintegration_idbinding of all required checks entries (count verification that it matches the HEAD check-run's.app.id. Blocking spoofing by a commit status with the same name — declining withissuer-unboundif it cannot be verified). Verify with API output of only counts and booleans, and if it cannot be confirmed,server-enforcement-missingdeclines), only then execute squash merge and issue close. The HEAD sha is obtained and pinned from its owngh pr viewobservation (not received from the monitor), and the merge is executed withgh pr merge <N> --squash --delete-branch --match-head-commit <自己取得 sha>, so that a race (TOCTOU) where a push occurs between verification and merge is closed off by GitHub-side condition evaluation.- The reason check names are excluded is that names are externally derived text generated from the workflow / job / matrix definitions on the PR side, and thus become a route for bringing instruction statements into the context of the execution entity that holds merge permissions. For external checks, thecount(a non-negative integer) and the
.conclusion/.statusのstate enum are not media into which arbitrary text can be injected, so as outside the scope of this rationale, only--jqfetch with normalization is permitted. App filtering is performed by matching against the value verified to slug format (lowercase English letters, digits, hyphens, up to 39 characters) atargsinput, viaapp.slugmatch, and the App name, description, and output are not put into the context. - The reason external check re-verification is not placed solely on the monitoring agent side is that the monitoring judgment, which reads untrusted text, is merely a startup condition meaning "it is acceptable to attempt a merge," and cannot serve as evidence for the gate.
- The monitor's
headShais not used as input to the merge path (it is only a record for diagnostics; the HEAD sha for merge determination is obtained and pinned by merge-exec itself). In runs where opt-out / external check configuration is not yet determined (externalChecksunspecified) or where trusted context is not declared (old format with slug only), merge-exec starts in a recovery-only path (allowMerge=false), does not perform new merges, and is limited to "only confirming issue close if the PR is already MERGED" (maintaining fail-closed while preserving the recovery path for PRs that were merged in a previous run but failed to record state). This limitation is not left to prompt interpretation; the text of the merge execution procedure is also branched on the host side, and the recovery-only path prompt does not includegh pr merge/--match-head-commitat all and outputs only issue close confirmation. - If the issue close cannot be confirmed even when the merge succeeded (
issueClosed: false)はmergedwithout terminating, retry the close via re-monitoring, and if the monitoring count is exhausted, terminate withblockedas "PR is merged but close unconfirmed" (recovered when monitoring resumes on the next execution).
- The reason check names are excluded is that names are externally derived text generated from the workflow / job / matrix definitions on the PR side, and thus become a route for bringing instruction statements into the context of the execution entity that holds merge permissions. For external checks, thecount(a non-negative integer) and the
- Independent verification agent (merge-verify): merge-exec が
merged: trueeven if it returns, the host treats it as unverified model output and does not accept it unconditionally.merged: trueはreasonがmerged/already-mergedIt is treated as an acceptance candidate only when consistent with (inconsistency or out-of-enum is treated as systemic failure, withfailedtermination and subject to halt count), and furthermore, a read-only agent in a separate context from merge-exec returns only the values obtained forgh pr view <N> --json state,headRefOid,mergeCommit, and the host performs an exact match ofstate(MERGED) and match with the HEAD sha at monitoring time (sanitizeShapassing value. In the already-merged recovery path where a previous run merged but headSha was not recorded, there is no comparison target, so only state) is strictly re-verified. If it cannot be corroborated (state mismatch, HEAD mismatch, unobtainable, invalid response), fail-closed terminates atblocked(blockedReason: quality), and worktree deletion anddependsOnrelease of subsequent issues are not performed.blocked+pris subject to monitoring resumption on the next run, so if it is actually already merged it naturally recovers via the already-merged path. The return schema has no free-text fields, and the verification agent does not read the review body, Issue body, comments, or check names at all (only enum exact matches andsanitizeShaverification values that have passed are synthesized into the host log/note).- Decline reason (
reason) is, on the host side,head-moved/checks-not-green(including, in addition to the presence of out-of-allowance states, 0 total checks andgh pr checksnon-zero-exit fail-closed declines) /merge-failed→ re-monitor,unresolved-threads→ fix loop (however, if there is no structured list of thread contents at hand, do not launch fix and re-monitor instead, having the monitoring agent collect the contents),not-mergeable(conflicts, etc.) →conflicting(hand off to the base-incorporation-only agent.fixCountindependent budget that does not consumebaseMergeCount)、wrong-target(base mismatch, draft. Since fix does not resolve it, the fix budget is not consumed) → blocked,pr-closed→ blocked、external-review-missing→ blocked (since re-monitoring within the same run cannot guarantee arrival, do not fail-open but terminate, and continue on re-execution after check arrival by resuming monitoring. The termination reason includes the list of confirmed slugs and a note that "if it is not resolved, suspect a typo in the slug or that the App in question is not installed, and check the App's installation status or exclude the slug fromargs.externalChecks"). The presentation of pass conditions is differentiated by App type: for cursor, explicitly state "arrival of cursor[bot] review for the HEAD sha (1 or more) and 0 CHANGES_REQUESTED (do not wait for APPROVED because Bugbot does not return APPROVED)", and for slugs other than cursor, explicitly state "passing conclusion of the check-run, falling back to APPROVED review only when there are 0 check-runs"), out-of-enum → systemic failure.
- Decline reason (
Merge execution conditions:
- All CI green: all checks completed as success / neutral / skipped, with 0 failure / cancelled / timed_out and 0 pending / queued / in_progress. If pending remains, continue monitoring. And1 or more total checks exist. 0 checks is not considered green, and the monitoring side, after re-checking for up to 10 minutes, stops at
blocked(quality) (fail-closed so as not to auto-merge a PR for which CI has never started due to the workflow'son:condition, all jobs being skipped by a path filter, or a required workflow not being configured. The merge-exec side also treats 0 total checks and a non-zero exit ofgh pr checksaschecks-not-green(decline as).Exception: state がOPENandmergeable: CONFLICTING's PR, even if the total check count is 0,blockeddoes not proceed to , and directlyconflicting(forward to the base-merge-only agent.fixCountindependent budget that does not consumebaseMergeCount) — because for a conflicting PR no test merge commit is created, so thepull_requesttrigger's CI check-run is structurally never started, and waiting will not converge.mergeable: UNKNOWNis treated as pending calculation, andCONFLICTINGis not treated as such (to prevent wasting the base-merge budget on false detections).Waiting for required contexts to be satisfied (autoMerge run, Issue #577): monitor does not returnreadyuntil the ruleset's required contexts are all present on HEAD (as check-run names or commit status contexts), and if they are still missing after a bounded wait of up to 10 minutes, it setstimeout(re-monitor). This is an advisory determination to prevent prematurereadywhen only fast-finishing AI review checks have been satisfied first; the publisher binding is handled by merge-exec (G0 (v-b)). merge-exec returnschecks-not-green(re-monitor) if it is only the non-publication of bound check-runs (all integration_ids numeric), and returnsissuer-unbound(terminal) if an integration_id is non-numeric or unverifiable. Monitor-side zero-count detection: monitor はgh pr checks --watchBefore entering , obtain the head's total check count (sum of check-runs + commit statuses), and if the confirmed value is 0, immediately go to this zero-total determination (bounded wait +mergeablere-determination) (if either retrieval fails, do not treat it as 0, omitchecksTotaland proceed to--watch).--watchEven if the re-execution of (4 times) has been exhausted, do not returntimeoutand proceed to the total count confirmation.timeoutmay be returned only in the case where 'one or more checks exist and remain pending until the monitoring limit is reached'; the host does not acceptchecksTotal: 0のtimeoutand re-determines toconflicting(blocking the path that wastes the monitoring window of 7 rounds [each round up to about 40 minutes] with 0 checks and terminates atfailed). - No external check findings(or 'no external checks' is confirmed by
args.externalChecks: []):args.externalChecksBased on and the observation results of Step 1, perform the waiting procedure described below. If the configuration cannot be confirmed, or if for a confirmed external check App the basis for passing against the HEAD sha (a check-run with an allowable conclusion, or an APPROVED review) cannot be confirmed, do not merge (the condition is not 'the specified App's checks are green' but 'the specified App's checksexistand are green'). - No unresolved review comments: All threads must be resolved via the GraphQL API.Only the fix agent of the Merge loop (the version that pushes) may execute resolve: Assuming that one's own fixes have already been reflected in the remote head, (a) immediately after a successful push in the relevant round, target only the threads that one has fixed (limited to threadIds derived from the monitor's structured output and verified by the host; the fix is prohibited from re-fetching the thread list itself to broaden the target), and (b) in rounds without a push (fixes already made and pushed in past rounds), target only the allowlist deterministically computed by the host, via GraphQL
resolveReviewThreadmutation で resolve し、required_review_thread_resolutionresolve the gate without human intervention (resolve via any route other than fix is prohibited. Owner's decision).The allowlist in (b) is computed solely by deterministic matching on the host side: the monitor returns each roundcompareStatus(thegh api compareresults from the previously observed sha passed by the host to the current headSha) is observed by the pure functionapplyResolveProofObservation, andaheadand only when a push actually succeeded in the immediately preceding round,resolveProof.pushHeadis advanced andchangedFilesis accumulated (behind/diverged/ if it cannot be obtained, it is treated as a force-push etc., and everything is reset in a fail-closed manner). The allowlist is computed bycomputePermittedNoPushResolveIdsby narrowing down to only those threads whoseresolveProof.files(the set of files changed by the host-measured push) includespath(the path in GraphQL reviewThreads) (no use whatsoever is made of the fix's own declared sha or its own confirmation of reflection via git fetch / merge-base --is-ancestor. No alternative route via confirmation of reflection of file contents is provided either). resolveProof is confined to within the process and is not persisted to a state file, and immediately after resume it is always re-measured from empty (fail-closed).Current status (2026-08-21):compareStatus/changedFilesis merely the self-report of the monitor that reads untrusted review bodies, and since the host cannot executegh api compareitself to verify it,computePermittedNoPushResolveIdsregardless of the contents of proofStatealways returns an empty list(fail-closed). The (b) route will remainpermanently unestablisheduntil a dedicated proof agent that does not read untrusted text is created, and resolve is established only via (a). For detailed state transitions and residual risks, refer to "resolve 前提のホスト側決定的照合" in references/automerge-design.md. The fix in monitor / merge-exec / merge-verify / Review loop (before push) does not execute the resolve mutation. Failure of resolve is not fatal, and threads that remain unresolved are picked up as unresolved by the monitor in the next cycle. As a result of consideration by the fix agent, comments judged unfixable or out of scope for the current issue areは、not resolvedand not turned into an Issue on the spot either; instead, following the procedure in the "Handling of out-of-scope items" section of references/out-of-scope-support.md, the reason for not addressing them and a proposed approach are recorded in the "Out-of-scope" section of the PR body(The responsibility of the automatic flow to out-of-scope threads is limited to recording). Since recorded threads remain unresolved, unless a human resolves them, monitoring falls from unresolved-comments → blocked, and it is included in the decision on approving issue creation and manual resolution in the final report.For P0/P1-equivalent or security-related findings (vulnerabilities, authentication/authorization, exposure of secrets, destructive operations, etc.), it is prohibited to settle with only a record of "no action needed / out of scope"(Either fix it, or if it cannot be fixed, mark it as blocked and leave it to the user's judgment. If the judgment cannot be made, err on the safe side and treat it as P0/P1-equivalent).Do not finalize whether issue creation is necessary before user approval(The decision to execute issue creation follows procedures 3 and 4 in the same section, and is carried out upon user approval at the time of final report confirmation).
Waiting for completion has ended (met) alone does not count as passing. Confirm the conclusions of all checks by the envelope counts (passed / pending / failed / total). If pending remains and the wait limit (exhausted) is reached, then timeout。failed if there is any, pass it to the fixing agent (fix).
The 4 branches of external check waiting (args.externalChecks and based on the observation results of Step 1):
- Cannot be determined (
externalChecksunspecified): Since it cannot be determined whether external review may be omitted, stop atstate: blockedregardless of the CI result. The host side also has the same gate, and even if the monitoring agent returnsreadyeven if it returnsnew mergeis not performed and it terminates atblocked(dual verification by prompt + host). In the stop reason, the observation results (reference values) and an exampleargsfor re-execution are recorded, andblocked+prbecomes subject to monitoring resumption in the next run. However, if the PR is alreadyMERGED(a PR merged in a previous run whose state recording failed), recovery of closure/state recording can be terminated atgh pr mergevia recovery-only merge-exec (allowMerge=false. The prompt does not containstate=MERGED) + merge-verify'smergedindependent confirmation (the new merge path is not opened, and if the PR is not merged, it terminates withblockedas the undetermined reason). - Confirmed no external checks (
externalChecks: []): Skip waiting for external review. Judge only by all CI green and no unresolved threads. - cursor(Cursor Bugbot): Execute the review-waiting flow by cursor[bot].If there is no review for the HEAD sha,
@cursor reviewis urged only once(no reposting). Bugbotin automatic execution, when there are 0 findings, does not post a review and only marks the check-run as completedTherefore, the absence of a review must not be interpreted as "no findings" (in this case, if no nudge is sent, a PR with no findings remains permanently blocked). If explicitly requested, a "no new findings" review is posted even when there are 0 findings. The check-run is used only to determine when nudging is allowed (queued/in_progresswait if so) and to detect failures (if the conclusion is not allowed,needs-fix), and a passing conclusion is not used as grounds for "no findings" (even with findings,success/neutralboth are observed). Wait up to 10 minutes for a cursor[bot] review to arrive for the HEAD sha, and once it arrives, wait for findings to be resolved before merging.If it does not arrive, do not consider it "no review"; insteadstate: blockedstop with(fail-closed to prevent bypassing the review gate when the App fails, is delayed, or fails to start. If re-run after the review arrives, monitoring resumes and continues). - External checks other than cursor (e.g., sonarcloud): waiting for CI completion (
--until settled)は「existsonly guarantees whether the check turned green, and if the App never started in the first place, everything is judged all green without monitoring anything. Therefore, for each App, the very startup of a check-run for the HEAD shais verified (without this verification,externalChecksでsonarcloudeven if specified, it becomes fail-open and merging is possible while SonarCloud remains unstarted). If there are 0, wait up to 10 minutes and check again; if there are still 0,state: blockedstop with. For Apps that post only reviews without creating check-runs,<slug>[bot]also verify as a fallback that the review's HEAD sha matches (reviews verify up tostateverify up to. It can only be passed when "APPROVEDis 1 or more andCHANGES_REQUESTED/COMMENTED/PENDINGis 0"; if a negative review coexists withAPPROVED, it is also considered failed. Since merge-exec cannot read the review body or evaluate its content, anything that cannot be evaluated is failed as fail-closed.DISMISSEDhas been disabled on GitHub, so it is not included in the judgment).- In configurations that list cursor together with other Apps (e.g.,
[{"app": "cursor", "context": "Cursor Bugbot"}, {"app": "sonarcloud", "context": "SonarCloud Code Analysis"}]), in addition to confirming cursor's review arrival, also confirm the startup of the other Apps. blockedIf it is not resolved even by re-running, there may be a typo in the slug, or the App may not be operating on the target repository. Check the App's installation status, orargs.externalChecksexclude that slug and re-run.
- In configurations that list cursor together with other Apps (e.g.,
# HEAD sha を取得(push のたびに取り直す)
HEAD_SHA=$(gh pr view <pr-number> --json headRefOid -q .headRefOid)
# CI の完了待ち(monitor が run-verified.sh 経由で実行する。--attempt を 1 から最大 30 回まで増やして再実行 = およそ 40 分)
bash "<skillDir>/scripts/run-verified.sh" <sha256> observe-pr.sh --nonce <nonce> --mode checks --pr <pr-number> --until settled --wait --attempt 1
# 封筒の payload: passed / pending / failed / total。pending が 0 件で met。failed が 0 件、pending が 0 件であること
# Bugbot(cursor[bot])レビューが HEAD sha に対して到着しているか確認する(cursor 確定時のみ)
# commit_id が HEAD_SHA と一致するレビューを探す(30 件超のレビューを取りこぼさないよう --paginate 必須)
gh api --paginate "repos/{owner}/{repo}/pulls/<pr-number>/reviews" \
--jq "[.[] | select(.user.login == \"cursor[bot]\" and .commit_id == \"${HEAD_SHA}\")] | length"
# → 合計が 0 の場合は最大 10 分待つ(HEAD push から 1 分以上経過後に @cursor review を 1 回だけ催促可)
# → 待機上限を超えても到着しない場合は blocked で停止する(「レビューなし」として先へ進まない)
# cursor 以外の外部チェック App(例: sonarcloud)が HEAD sha に対して起動しているかを確認する
# commits/<sha>/check-runs は sha でスコープ済みのため jq 側で sha 比較は不要
gh api --paginate "repos/{owner}/{repo}/commits/${HEAD_SHA}/check-runs" \
--jq '[.check_runs[] | select(.app.slug == "sonarcloud") | (.conclusion // .status)] | group_by(.) | map({v: .[0], count: length})'
# → 出力は状態 enum ごとの件数のみ(チェック名・description は取得しない)
# → 全ページの count 合計が 0 なら未起動。最大 10 分待って再確認し、なお 0 なら blocked で停止する
# → 0 件のときは <slug>[bot] レビューをフォールバックとして確認する(state 別件数のみ取得する)
gh api --paginate "repos/{owner}/{repo}/pulls/<pr-number>/reviews" \
--jq "[.[] | select(.user.login == \"sonarcloud[bot]\" and .commit_id == \"${HEAD_SHA}\") | .state] | group_by(.) | map({v: .[0], count: length})"
# → 合格にできるのは APPROVED が 1 件以上かつ CHANGES_REQUESTED / COMMENTED / PENDING が
# 0 件の場合のみ。否定的レビューが APPROVED と併存する場合も不合格(fail-closed)
# マージ実行エージェント側の再検証も本文を読まず「件数・状態 enum」のみへ正規化して取得する
# (確定済み App ごとに実行する。合格の根拠が 1 件もなければ external-review-missing でマージしない)
gh api --paginate "repos/{owner}/{repo}/pulls/<pr-number>/reviews" \
--jq '[.[] | select(.user.login == "cursor[bot]" and .commit_id == "<検証した HEAD sha>")] | length'
gh api --paginate "repos/{owner}/{repo}/commits/<検証した HEAD sha>/check-runs" \
--jq '[.check_runs[] | select(.app.slug == "sonarcloud") | (.conclusion // .status)] | group_by(.) | map({v: .[0], count: length})'
# → --jq はページごとに適用されるため出力はページ数ぶんになる。全ページを合計して判定する
# レビュースレッドの解決確認(GraphQL)— 100 件超はページネーションで全件取得する
# after: $cursor を使い pageInfo.hasNextPage が false になるまでループする
gh api graphql -f query='
query($owner: String!, $name: String!, $number: Int!, $cursor: String) {
repository(owner: $owner, name: $name) {
pullRequest(number: $number) {
reviewThreads(first: 100, after: $cursor) {
nodes { isResolved comments(last: 1) { nodes { body author { login } } } }
pageInfo { hasNextPage endCursor }
}
}
}
}' -F owner="{owner}" -F name="{repo}" -F number=<pr-number> -F cursor=""
# CI 全 green・外部チェック指摘なし・未解決レビューコメントなしの場合のみ squash merge
# (実行するのは監視エージェントではなくマージ実行エージェント。上記条件を自ら再取得して検証したうえで実行する)
gh pr merge <pr-number> --squash --delete-branch --match-head-commit <検証した HEAD sha>
When all checks appear to pass but the merge does not proceed (leftover checks from a canceled run):
- Symptoms observable from the flow(Since automatic detection does not exist, do not describe behavior that is not implemented):
gh pr checksare all pass,mergeableはMERGEABLE. There are no conflicts and no unresolved threads, yet merge-exec does not proceed and re-monitoring repeats, with only the monitoring budget decreasing. In this state,mergeStateStatusがBLOCKEDremains stuck and does not move.mergeStateStatusis not currently acquired by any agent, so the operator checks withgh pr view <N> --json mergeStateStatus. - Cause: When multiple runs execute concurrently against the same head sha, a canceled run leaves behind a check run with a failure conclusion.
gh pr checksdisplays only the latest check with the same name, so it looks like all pass, but branch protection's required check determination picks up the residual check and becomes BLOCKED. In operations that simultaneously push the same change to many repositories (see later "Operational guard for simultaneous synchronization and mass PR submission"), the frequency of concurrency conflicts increases, making this state more likely to be encountered. - Detection commands (clearly separate those an agent may execute from those exclusively for human diagnosis):
# (A) エージェントが実行してよい形。取得成否を先に確定してから「件数」のみを返す。
# gh api は HTTP エラーの JSON 本文も stdout へ出す仕様のため、パイプ直結だと認証失敗・404・
# レート制限の出力が uniq -d にヒットせず「重複なし(0)」に化ける
# (対象リポジトリに .claude/rules/ruleset-policy.md があれば手順 B と同じ罠として記載されている)。
# そのため (1) 取得を独立させて終了コードを見る (2) 出力の空判定を行う (3) 集計は shell 側で
# 行う、の 3 段に分ける(--jq はページごとに適用されるため group_by をページ単位で行うと
# ページ跨ぎの重複を見逃す。名前+結論の一覧をシェル側 awk で全ページ分集約する)
if ! command -v awk >/dev/null; then
# awk 前提条件が未導入。集計不能なため判定不能として扱う(fetch 自体を実行しない。
# (B) の command -v jq ゲートと同じく前提確認を fetch より先に行う — レート制限下で
# 無駄な gh api 呼び出しを発生させないため)
echo "UNDETERMINED"
else
# `rows=$(gh api ...)` を独立した単純コマンドのまま実行すると、呼び出し元 shell で
# `set -e`(errexit)が有効な場合に gh api の非ゼロ終了(認証失敗・404・レート制限等)で
# shell がここで即終了し、次行の status=$? および UNDETERMINED 分岐へ到達できない
# (if/then/else の条件式に置かれたコマンドは errexit の対象外という shell の仕様を利用し、
# 代入自体を条件式へ移すことで errexit 下でも必ず失敗分岐を実行できる形にする)。
if rows=$(gh api --paginate "repos/{owner}/{repo}/commits/${HEAD_SHA}/check-runs?per_page=100" \
--jq '.check_runs[] | [.name, (.conclusion // "pending")] | @tsv' 2>/dev/null); then
status=0
else
status=$?
fi
if [ "${status}" -ne 0 ] || [ -z "${rows}" ]; then
# 取得失敗、または check-run が 1 件も返らない。この節は「全チェックが pass に見える」状態
# でのみ参照するため、0 件は前提と矛盾する = 取得できていない可能性が高く、判定不能として扱う
echo "UNDETERMINED"
else
printf '%s\n' "${rows}" | awk -F'\t' '
{ n[$1]++
if ($2 == "success" || $2 == "neutral" || $2 == "skipped") { }
else if ($2 == "pending") pend[$1] = 1
else bad[$1] = 1 }
END { d = 0; b = 0; p = 0
for (k in n) if (n[k] >= 2) { d++; if (k in bad) b++; if (k in pend) p++ }
printf "dup=%d bad=%d pend=%d\n", d, b, p }'
fi
fi
# → 出力は次の 2 形のみ(チェック名・エラー本文は出力に現れない):
# `UNDETERMINED` … 判定不能。「重複なし」ではない
# `dup=<D> bad=<B> pend=<P>` … 取得成功。D = 重複した check 名の数、
# B = そのうち結論が `success` / `neutral` / `skipped`
# (いずれも required status checks 上は合格・非ブロック扱い)
# でも `pending`(未完了)でもないものを含む数(cancelled /
# failure / timed_out / action_required / startup_failure /
# stale 等、`success`・`neutral`・`skipped` を正常扱いする
# 以外は全て bad へ倒す fail-closed 分類)、P = そのうち
# 結論が `pending`(未完了。実際の conclusion が null で
# in-progress/queued 中)を含む数
# → 読み方: **取得に成功したうえで** D が 0 なら重複なし。D >= 1 でも B = 0 かつ P = 0 の
# 場合のみ「重複はすべて正常な再実行(success/neutral/skipped 同士)」と読める。B・P は排他ではなく、
# 同じ重複名の中に bad な結論と pending な結論が両方含まれる場合は B・P 双方が 1 になる。
# 上記 2 形(正規表現 `^UNDETERMINED$` / `^dup=[0-9]+ bad=[0-9]+ pend=[0-9]+$`)以外の
# 出力も判定不能として扱う
# (B) 人間の診断専用。重複の内訳をチェック名つきで確認する
# チェック名は PR 側の workflow / job 定義から生成される未信頼テキストのため、
# monitor / merge-exec のコンテキストでは実行しない(権限境界の維持)
# 前提: 外部の `jq` CLI が必要(`gh --jq` はページ単位適用のためここでは使えない)。
# 事前に `command -v jq` で存在確認し、なければ実行せず `blocked` とする
command -v jq >/dev/null || { echo "jq が見つからないため診断を中断し blocked とする" >&2; exit 1; }
# `--paginate` の `--jq` は取得したページごとに個別適用されるため、group_by をそのまま
# 使うとページ単位の集計になり、同名 check-run が別ページに 1 件ずつ分かれて存在する場合に
# 検知できない(各ページ内では件数 1 の group にしかならず、実際は重複していても取りこぼす)。
# `--slurp` を付けると全ページを外側の配列として受け取れるが、gh api は `--slurp` と `--jq` の
# 併用を拒否する(`the --slurp option is not supported with --jq or --template`)ため、
# `--jq` は使わず `--slurp` の生 JSON 出力を外部の `jq` へパイプし、平坦化してから group_by する
# ことでページ跨ぎでも全件を一度に集約してから判定する。
# まず check 名だけで group_by し、件数 2 以上の group(=実際に重複している名前)に絞り込んでから、
# その中で conclusion 別の内訳を出す(name=conclusion のペアで group_by すると、同名 2 件が
# cancelled/success のように conclusion 違いで割れて各 group が件数 1 になり、重複そのものを
# 取りこぼすため、必ず name のみで group_by する)
gh api --paginate --slurp "repos/OWNER/REPO/commits/<sha>/check-runs?per_page=100" \
| jq -r '[.[] | .check_runs[] | {name, conclusion}]
| group_by(.name)
| map(select(length >= 2))
| map("\(.[0].name): " + ([.[] | .conclusion] | sort | group_by(.) | map("\(.[0]) x\(length)") | join(", ")))
| join("\n")'
- Remediation (measure the preconditions first, then execute the commands. The decision-making and execution authority isthe run operator / host side, not the monitor / merge-exec agent. (B) is exclusively for human diagnosis, so this entire flow cannot be completed by agent autonomy alone.):
- Precondition 0 (handling of undeterminable): If (A) returns
UNDETERMINED, or returns anything other than the above two forms, thenundeterminable. Without rerunning, pass it to the final report asblocked(quality). Do not read undeterminable as "no duplicates" and exclude the CI origin (typical causes are expired authentication, rate limiting, or wrong sha. When a human checks the cause, rerun the same gh api without discarding stderr). - Precondition 1 (measurement of duplicates and conclusions): (A) returns
dup=<D> bad=<B> pend=<P>, and D, B, and P are measured.- If D >= 1 and P >= 1 : among the duplicates, a
pending(incomplete) check-run remains. Since this pending itself can be the direct cause ofmergeStateStatus=BLOCKED, do not conclude that "all duplicates are normal reruns" and proceed with cause investigation in another direction. Without rerunning, wait for pending to complete and re-monitor (the decision-making and execution authority is the run operator / host side. Do not proceed to the rerun flow of Precondition 2 with the cause still unknown). - Only if D >= 1 and P = 0 and B >= 1 , proceed to Precondition 2 (uniqueness of rerun targets).
- If D >= 1 and B = 0 and P = 0 , all duplicates originate from normal reruns (
success/neutral/skippedto each other) and are not "residual checks of canceled runs". Without rerunning, check other causes of BLOCKED (required check context name mismatch, unresolved review threads, ruleset configuration, etc. For the target repository,.claude/rules/ruleset-policy.mdIf there is one, move the investigation to that 3-axis sweep (strict / bypass_actors / integration_id remaining).
- If D >= 1 and P >= 1 : among the duplicates, a
- Premise 2 (uniqueness of rerun target): Confirm the duplicated check name in (B), and identify the cancelled run that issued that name from the job list (command below).
- cancelled run がmultipleIf found but cannot be uniquely narrowed down: do not rerun and
blocked(quality) and send to the final report (rerunning the wrong run also reruns unrelated jobs and changes the state while the cause remains unknown). - cancelled run が 0 casesIn the case of: no rerun target exists. If B >= 1 remains, it does not originate from cancel but from non-cancel sources such as failure / timed_out / action_required / startup_failure / stale. Note that these remaining items are subject to the same masking as cancel remnants —
gh pr checksdisplays only the latest conclusion of a check with the same name (see the "Cause" section above), so older failure / timed_out etc. hidden behind a newer success / neutral / skipped do not appear in the output ofgh pr checksand cannot be detected as a normal visible CI failure. If left to the needs-fix path of the monitoring flow (gh pr checksbased CI failure detection), they will be overlooked, so do not rerun andblocked(quality) and send to the final report. If cause investigation is needed, based on the raw check-runs output of (A)/(B) (notgh pr checksbut), the run operator individually identifies and handles the run that issued the relevant check-run. Do not assume it is caused by cancel andgh run rerundo not.
- cancelled run がmultipleIf found but cannot be uniquely narrowed down: do not rerun and
- Do not rerun while the above is not satisfied (rerun restarts CI, which violates the design of "start CI only once after Review passes").
- Precondition 0 (handling of undeterminable): If (A) returns
# cancelled な run を head sha で列挙する(conclusion=cancelled のみに絞る)
gh api --paginate "repos/OWNER/REPO/actions/runs?head_sha=<sha>&per_page=100" \
--jq '.workflow_runs[] | select(.conclusion == "cancelled") | .id'
# 各 cancelled run が発行した job 名を確認し、(B) で特定した重複 check 名と突き合わせる
# (check-run の名前は `<job名>` または `<job名> / <ステップ>` 形式で job に対応するため、
# jobs API の name で同定できる。複数 run の job 名が同じ重複 check 名にヒットする場合は一意化不可)
gh api --paginate "repos/OWNER/REPO/actions/runs/<cancelled-run-id>/jobs?per_page=100" \
--jq '.jobs[].name'
# 一意に対応付けられた run に限り、全 job を回して残存 check を上書きする(--failed は付けない)
gh run rerun <run-id> -R OWNER/REPO
- Completion gate consistency: the fact that a rerun was performed is not itself evidence of green. After re-execution, enumerate the conclusions of all checks again and confirm that
failure/cancelled/timed_outis 0 cases andpending/queued/in_progressis 0 cases and the total number of checks is 1 or more before judging it as passing (in the target repository,.claude/rules/verification.mdif there is one, follow its 5-stage gate). If it is not resolved, do not proceed by guessing and send it asblockedto the final report.
If there is a CI failure, external check indication, or unresolved review thread, the fix agent (fix) acquires the target branch at detached HEAD, reflects the indication, and pushes again. fix always incorporates base before the fix work (commit) (git fetch → git merge), so even if base has moved, it does not affect the monitor in the next round. The fix agent also operates in worktree isolation, so it does not interfere with branches of other parallel issues.
Dedicated base incorporation loop: a PR that was in conflict with base from the time of creation (monitor is mergeable: CONFLICTING detected by. Exception to merge execution condition 1. above. merge-exec's not-mergeable mapping also follows the same path) is not sent to the fix loop, but to an independent dedicated base incorporation agent (baseMergePrompt) is started. Routing verification, fetch, checkout, merge, push, and their verification (matching the remote head before and after push) are scripts/base-merge.sh(lib/push-verify.sh. Issue #603, third installment) performs deterministically, and the agent executes the single command via run-verified.sh and merely transcribes the last line BASE_MERGE_RESULT {…} of standard output (no envelope is used: there is no newly adopted value on the host side, andpushed is used only for progress. The trust model is references/script-trust-model.md). When the script could not be executed (run-verified.sh exit 3 [hash mismatch] / 4 [missing] or the script's exit 2, etc., resulting in no result line), the agent returns with pushed: false・commitFailed: true , and the host terminates as conflict / hookRejected without the following commitFailed as failed (no re-ingestion). Since this is not a quality issue, it consumes no fixCount and is bounded by the independent budget baseMergeCount(upper limit args.maxBaseMerges. Default 3). The base-ingestion agent does not make any fixes for review comments, thread resolution, or PR body edits, and is responsible only for base ingestion, commit, and push. Conflicts are not resolved regardless of type (fail-closed). Content conflicts in regular files are not resolved because it has no authority to edit them (since validity cannot be confirmed via build/lint/test), and submodule (gitlink) pointer conflicts are also not resolved because both sides have changed the pointer and mechanically adopting the base side would silently discard the PR side's gitlink update. In either case, it does not attempt resolution and stops with commitFailed: true . When a content conflict is detected, it also returns conflict: true , and the host does not terminate as failed but in the same round delegates to the fix path (fixPrompt 's pre-push base update gate. It can legitimately run build/lint/test verification and fixCount[upper limit 6] is bounded) to have it perform conflict resolution, verification, and push (since no commit has been created, baseMergeCount is not consumed.conflict is the agent's self-report, but the worst case of misreporting is merely taking an extra trip to the bounded fix path with verification, which is on the safe side). The subject of the base-ingestion merge commit uses the embedding constant base-merge.sh of chore: base ブランチの変更を取り込む(fixed by hash. Not the host's literal), and the base-ingestion agent with push authority does not read any file in the repository, including commitlint configuration and commit history (the approach of separating subject computation into a read-only agent is not adopted because read-only is not enforced at runtime by prompt instructions alone, and untrusted reading itself is eliminated from the automatic base-ingestion path). If this fixed subject is rejected by a commit-msg hook (e.g., commitlint withtype-enum / scope-enum ) (branch (c)), it returns commitFailed: true in addition to hookRejected: true , and the host, similarly to conflict , failed Do not terminate; delegate to the fix path (the pre-push base update gate for fix, with permission to legitimately read the commitlint configuration, determines the subject, and creates, verifies, and pushes the merge commit).conflict / hookRejected without commitFailed(branch / base fetch failure, checkout failure, subject undetermined, etc.) is treated as an unrecoverable class and failed terminate. After push, mergeable and observation of check-run startup are not performed on this path (in the third round, the log-only mergeableAfter / checksStarted / headSha 's 3 items were abolished along with the return schema. The actual determination is made by the next round's monitor re-observing the actual server-side values).Classification when the base-incorporation upper limit is reached: baseMergeCount >= args.maxBaseMerges is reached, blocked / blockedReason: "quality" terminates it (halt not counted. This is because it may be resolved if a human directly incorporates base into the PR branch and pushes — unlike needs-fix when the fixCount upper limit is reached [the state changes only automatically even when fixCount is exhausted].unrecoverable〔status: "failed"〕 is not used; instead blocked is used, matching the public contract shared with args-example.json that "conflicts terminate as blocked"). On re-execution, by resuming monitoring (isActiveMonitoring。blocked + pr retained), the same PR is monitored directly again, and the Recover / Implement / PR Create phases are not passed through.baseMergeCount is carried over from the state file as the reached value (when monitoring resumes, the saved value is only clamped to maxBaseMerges , not reset), so even if this branch is re-entered, the base incorporation loop is not automatically re-executed. It can be resolved only when a human directly incorporates base into the PR branch and pushes; after that, the next monitor will no longer detect mergeable: CONFLICTING , and this branch itself will not be passed through. The fix agent, assuming that the fix has already been reflected in the remote head, resolves (a) immediately after a successful push, only the threads it addressed (limited to monitor-derived, host-verified threadIds), and (b) on rounds without a push, only the allowlist deterministically computed by the host, using the resolveReviewThread mutation, and reports the successfully resolved threadIds in resolvedThreadIds (resolution failure is not fatal; threads left unresolved are picked up as unresolved by the next round's monitor). Comments judged out of scope for fixing are not resolved, and are recorded in the PR body according to the procedure in the "Handling of out-of-scope items" section of references/out-of-scope-support.md (the responsibility of the automated flow for out-of-scope threads extends only to recording. Unless a human resolves them on GitHub, they remain unresolved, and blocked → the final report decides on issue-creation approval and manual resolution). Monitoring (monitor) is executed up to 7 times as the normal budget (it is extended once by the later "forced thread rescan rescue round," so the absolute upper limit for the entire execution is the initial budget + 1 = 8 times. See that section for details). CI startup confirmation immediately after push is mergeableAfterPush: CONFLICTING Rounds that reported do not launch the monitor agent, so they do not consume monitoring slots (the number of times this hint is set is bounded by 1 PR creation + number of fixes [upper limit 6], and the monitoring count does not extend indefinitely). Issues where 2 consecutive rounds have neither a push nor a new thread resolve are blocked (even without a push, a round that reports a resolve to a monitor-reported, not-yet-counted threadId is treated as having progress, resetting the consecutive count and continuing to re-monitoring. The effectiveness of the resolve is confirmed by the next round's monitor using the actual server value). When the monitor agent blocked returns, blockedReason(quality / unrecoverable) is mandatory, and the host side also double-validates the enum. Omission or out-of-enum is treated as unrecoverable (fail-safe).quality(which may be resolved by re-monitoring/re-execution) is terminated into the state file with blocked and becomes a target for monitoring resumption on the next run, whileunrecoverable(such as a PR closed without being merged) is terminated with failed and excluded from resumption targets. The fix upper limit is shared with Review (upper limit 6). See the Review step for details.
Classification when the fix upper limit (6 times) is reached: When the upper limit is reached and it falls to blocked , classify resumability based on the state observed at the time the upper limit was reached.unresolved-comments(unresolved threads actually exist) can be resolved by a human resolve, so quality(blocked termination/monitoring resumption target), andneeds-fix(such as CI failure) has exhausted the fix budget, so unrecoverable(failed termination/not a resumption target). If the latter is made resumable,fixCount runs restored with the upper limit unchanged would repeat "immediately blocked" every time, andblocked does not count toward the consecutive halt count, so the halt defense does not work either.The base incorporation upper limit (baseMergeCount >= args.maxBaseMerges) branches from this unrecoverable side's judgment: needs-fix is the exhaustion of the auto-fix budget, and outside automation the state does not change, but a base conflict can be resolved if a human directly incorporates the base into the PR branch and pushes. If resolved, the next monitor will no longer return conflicting and will not pass through the upper-limit determination branch itself, so the concern of "repeating immediately blocked every time" does not hold in the same form. Therefore, reaching the base incorporation upper limit is classified as quality(blocked termination/monitoring resumption target).
Fail-safe classification when StructuredOutput is not returned: Since the target issue's PR is always already created at the point of entering the Merge loop (impl.prNumber は runImplement calls the Merge loop only after PR creation succeeds), if any agent call among monitoring, merge execution, merge verification, base incorporation, and fixing ends without returning StructuredOutput (agent() exceptions and null returns are both merged into the same path), as a systemic failure failed(Recover → usually the Implement path. Including re-creating a PR) can create a duplicate PR for an existing PR. Therefore, distinguishing it from the existing out-of-enum response (inconsistency after the model returns something; maintaining strict failed maintaining) andblocked(monitoring resumes on the next run). The scope is limited to "within a Merge loop where a PR already exists," and it does not touch the failure classification of Plan / Implement / Review / Recover / PR Create (pr: 0) at all (halt defenses are not weakened. Only for monitor, when null or an exception occurs, an immediate retry is performed just once (the retry is performed with observation-only instructions that prohibit writes such as gh run rerun and @cursor review posting.) (fixes that involve writes may have already been pushed on the first attempt, and re-running them would result in a pushed:false no-op that loses track of the push, so no retry is performed); if it still fails, fall back to blocked . Otherwise, no automatic retry is performed within this run). The root node (verify-close) does not have the concept of pr / worktree , so for the same reason it is classified as blocked(not counted as halt), and verify-close is re-executed as-is on the next run. For details, see the "fail-safe when StructuredOutput is not returned" section in references/recovery.md.
Forced thread rescan rescue round: merge-exec が unresolved-threads(detects only the "count" of unresolved threads), and if a list of thread contents is not at hand, the host does not launch a fix, sets forceThreadRescan , and instructs the monitor in the next round to perform the forced rescan of step 5. At this time, if the monitoring budget has already been exhausted, the rescue round will not run even once, soextend the monitoring quota only once for the entire run(from the second time onward, it is not extended and terminates with the remaining budget. Even if merge-exec keeps returning an empty list, the number of monitoring iterations is bounded by the initial budget + 1).
The extended rescue round runs with zero remaining budget, so the result of that round becomes the final result as-is. The terminal classification of the rescue round is not determined immediately at the end of the round, butonly once at a single point after exiting the monitoring loopis evaluated (ready / needs-fix If a meaningful result such as is obtained, proceed to the normal branching process). The judgment branches on the timeout のsourceof : only the timeoutreturned when the monitoring agent itself failed to observe (= no transient reason mapping of merge-exec occurred in the same rescue round) is classified as **terminal status blocked(not counted as halt, subject to monitoring resumption on the next run)**. This is because the rescue is an "additional attempt to retrieve the contents of unresolved threads," and even if observation fails, the original quality-block fact that "unresolved threads remain" does not change.lastState は timeout is left as-is (the fact that it could not actually be observed is correct as a record of the terminal reason). On the other hand,derived from merge-exec in the same rescue round timeout mapping(head-moved / checks-not-green / merge-failed) is not classified as a quality block, and the default failed(subject to halt count). Since the rescan of the rescue round itself is established, it cannot be concluded that unresolved threads remain, and the substance is a failure of the merge operation itself. Regardless of origin, uniformly blocked If classified as, permanent merge failures (especially merge-failed) are never counted in the consecutive halt count, and the same rescue path is re-entered repeatedly, allowing the halt defense to be bypassed. For the detailed decision table and design rationale, see references/automerge-design.md the "End Classification of Rescue Rounds" section.
Number of omitted out-of-scope comments: outOfScopeLog is persisted as a maximum of 21 items: 20 items in the main body + 1 omission marker line ((他 N 件省略)). The marker uses only one line across the entire array, and N is cumulatively updated across subsequent fix rounds and interruption resumptions. In addition, the set of threadIds already declared as out-of-scope is saved to the state file as outOfScopeSeen and restored on resumption (because if the threadId whose body did not remain in outOfScopeLog due to omission is lost, the same thread being re-declared after resumption would be double-counted in the omission count).
Step 7: Verify and close the parent issue
A node with children (parent issue) is closed, once all descendants under it have completed, after confirming the following. Not only direct children, but alsosub_issues_summary.total > 0 recursively traverse the children and confirm that there is no open issue down to the lowest level of descendants.
# 1. 子孫の最下層まで open が無いか確認(--paginate で 100 件超も全ページ自動取得。
# total > 0 の子ごとに同じ呼び出しを繰り返す。全体を辿る場合は scripts/preview-tree.sh を使う)
gh api --paginate "repos/{owner}/{repo}/issues/<parent>/sub_issues?per_page=100" \
--jq '.[] | {number, state, total: .sub_issues_summary.total}'
# 2. 受入基準・チェックリストを読む
gh issue view <parent-number>
# 3. 受入基準を満たしていればクローズ
gh issue close <parent-number> --comment "配下のサブイシューがすべて実装・マージ完了。受入基準を確認してクローズ。"
If open sub-issues remain, or if acceptance criteria are not met, do not close and record as failed . The parent node is not submitted until all child issues (including open descendants under closed children) are complete, so it is verified after the parallel execution of children completes.
Step 8: Generate the final report
Output a report summarizing the processing results of all issues. Do not stop immediately on a single issue failure, but proceed to the next; however, **if 3 issues fail consecutively, stop starting new work (halt)** and wait for the user's judgment. Issues not started after the halt are recorded as not-started . Out-of-scope items are recorded in the "Out-of-scope" section of each PR body (including records derived from implementation and self-review,and records derived from unresolved review comments in the Merge phase), so when checking the report, refer to them and make the Issue creation decision (after approval, execute steps 3 and 4 of references/out-of-scope-support.md "Handling out-of-scope items"). In addition, blocked / fix out-of-scope unresolved comments (review threads that could not be resolved by oneself due to reaching the Merge loop's fixCount limit or blocked limit) are aggregated in the done of each entry's unresolvedComments(structured unresolved comment list) / outOfScope(log of comments judged out-of-scope by the fix agent) fields, so list them in this section when generating the report.
If a prerequisite issue is externally completed during the run (manual merge/close),Only before halt occursDownstream dependent block items are re-evaluated and started within the same run. Even after halt (stopping new starts when 3 issues fail to complete consecutively), probing and state recording (prereqTransitions recording and persistence to the state file) continue, but the new-start gate itself does not resume (halt is a user-judgment-waiting safeguard that stops new issue submission, and is not automatically lifted due to external completion detection). External completions detected/recorded after halt are reflected in downstream starts on the next run's re-execution. This re-evaluation count is recorded in the report's return value prereqTransitions . The precondition PR MERGED determination requires not only a PR number match but also the same PR-issue linking verification as merge-verify (headRefName, base, same repository, closingIssues) (see references/recovery.md for details).
See below for the report output template (processing result summary, completed issues, failed/not-started issues, out-of-scope/unresolved comments sections) and the description of return value fields.
Return value mainWorktreeUntracked contains the untracked file inspection result for the main worktree (repository root). Files newly appearing during this run are detected from the observed diff at run start and end, andno deletion, warning onlyis performed (attribution is estimated since concurrent runs and human work may also be picked up).observed: false indicates that the inspection itself failed, in which case git status manually verify with. If 1 or more are detected, also note it in the report and prompt the user to manually verify/delete.
Return value mainWorktreeHead contains the main worktree's HEAD inspection result (observed / changed / shaChanged / baselineRef / endRef).changed: true indicates that the branch was switched during the run (or that it moved while remaining detached HEAD).Do not revert automaticallyso,git status verify with and manually return to the original branch.observed: false the inspection failed, so manually verify.
Details: references/report-format.md
Verification
Each implementation agent must newly run the test command, check the full output and exit code before declaring completion (if .claude/rules/verification.md exists in the target repository, follow that 5-stage gate). Declaring completion with speculative words such as "should be" or "probably passes" is prohibited. Declare completion only after citing the test output and exit code as evidence.
Confirm that all target issues are listed in the "completed issues" of the final report and that "stopped issues" is empty.scripts/implement-issue-tree.js See below for the application confirmation procedure (grep command and expected results) for the untrusted data boundary, leftover worktree limit gate, merge-guard hook, and prevention of temporary file leftovers in the main worktree when
Edit scripts against development files: scripts/implement-issue-tree.js is the executable file (artifact) passed to the Workflow, and must not be edited directly. Edit scripts/implement-issue-tree.src.js(the development file with comments), andnode skills/implement-issue-tree/scripts/build-workflow.mjs regenerates the executable file with comments, leading indentation, and unnecessary half-width spaces between tokens removed (line numbers match between the two, column numbers do not). The builder reads the generated file and the development file with acorn's parser (acorn.parse の onToken. whether block or object, condition parentheses,for await etc. with context) and compares the token sequences (including the contents of strings and templates). The readings are module and the form the Workflow runtime actually evaluates (the body with the leading export const meta の export removed, evaluated as a function body = script.<!-- and the line-start --> becomes a line-end comment), and both must match. If they do not match, if either cannot be parsed, if the comparison cannot be executed, or if the comparison result is not in the expected form, abort without writing the generated file. There is no CLI argument to replace the comparison.How to write a development file that causes an abort(measured): } a regular expression placed immediately after contains // /* (an ordinary /re/.test(s) passes),for ( inside the parentheses of , using the variable of in a division line (i < of / 2) and on the same line a // block comment containing (also when there is a template containing / on the same line and then a multi-line template etc. after it),class A extends /[//]/… like , extends immediately after // /* place a regular expression containing (it passes if wrapped in parentheses),o?.in / 2 like , ?. immediately after the keyword-name property immediately after place / (the bundled acorn misreads it and cannot parse.(o?.in) / 2 avoid with ),with statement,<!-- is used as a line-end comment and /* is placed after it. There are also forms that do not cause an abort but do not shrink the generated output (the meaning is the same. Development comments remain in the distributed artifact): } immediately after /`/ or a regular expression containing an unpaired quote (/a b['"]x/.test(s))、of division line (line-end // comment remains. If there is a template containing / on the same line, the subsequent comments and indentation also remain), the method name is for inside the parentheses of the definition, using of in division.The exact conditions for these are build-workflow.mjs の stripComments shall be governed by the doc comment ("remaining constraints")(only representative forms are listed here). Sync omissions and direct edits are detected by CI's tests/build-workflow.test.mjs(freshness gate).
Details: references/verification.md
How to run the tests (whole, per file, Node 24 and 22 in parallel) and how to use the executor tests/tools/mutate.mjs to verify with mutations that the checks have not weakened: references/testing.md
Common failures
| Problem | Workaround |
|---|---|
| Repeatedly making speculative fixes without investigating the cause of the test failure | If the target repository has .claude/rules/debugging.md then follow its 4 phases; if not, follow the same approach (investigation → analysis → hypothesis → fix). If it fails 3 times, blocked and report to the user |
| Judging CI as passed just because the completion wait has ended (met) | Confirm the conclusion of all checks using the envelope counts (passed / pending / failed / total). Do not consider total 0 as green |
| Moving on to code quality review without confirming spec compliance | The Step 5 review is performed in the order ① spec compliance → ② code quality |
| Pushing / creating a PR before Review | Push / PR creation are performed in Step 5.5 after all Reviews pass. This design prevents CI from being triggered when Review fails |
| Pushing during Review fix | Fixes in the Review loop are local commits only. Push is performed only in Step 5.5 |
| Re-running with a corrupted state file and creating duplicate PRs | On a parse error, stop immediately.cat _/issue-trees/<N>.json Confirm with before re-running |
| Manually deleting the worktree after an interruption, then re-running | Manual deletion is unnecessary because the Recover phase handles it automatically on re-run. If you delete manually, Recover determines there are no remnants and starts a new run from Plan without carrying over the work from before the interruption |
| An agent other than fix resolving review threads / fix resolving threads even outside its scope | Only the fix in the Merge loop (the version that pushes) may execute the resolve mutation, and only for fixes already reflected in the remote head ((a) immediately after a successful push, threads it handled itself; (b) in rounds with no push, only the allowlist deterministically computed by the host. fix's own reported sha or its own reflection check are not used. (b) is currently permanently an empty list = not applicable). monitor / merge-exec / merge-verify / the fix in the Review loop do not execute it. Out-of-scope threads are not resolved; stop at recording them, and unless a human resolves them, blocked → final report |
Put the issue number in the scope of the implementation commit (e.g. feat の scope に 42 include it) |
scope-enum In repositories with , commitlint will always fail. It is first detected on push after consuming 3 Review rounds, and--no-verify is prohibited, so it cannot be avoided either. Make the scope a module or directory name, or omit it, and link the issue with Refs #<N> / Closes #<N> performed with |
| Treating P0/P1-equivalent or security findings as out of scope | The fix agent must not unilaterally decide something is out of scope and merely record it. Until it is fixed or approval is obtained from the user or the reporter, treat it as blocked (safety-side guard) |
| Since all checks appear to pass, exclude CI-related causes and continue investigating while suspecting the PR diff | Measure the actual number of duplicates for check-runs with the same name (the relevant branch in Step 6). Remaining checks from cancelled runs can cause BLOCKED |
Without verifying the output of (A), 0 read as "no duplicates" |
Acquisition failure, empty output, or format mismatch is UNDETERMINED. Without excluding CI-related causes, blockedlean toward (quality) |
due to insufficient opt-in test records, blocked repeatedly rerun while remaining in the state of |
optinFixState Non-pass and unbound-derived failures (latch) are by design intentional fail-closed (the host cannot directly observe the self-reported test execution of the fix, so it does not automatically clear them), and are not automatically cleared. To resolve, either (a) push a new commit in which the declared tests actually pass (existing path; it is automatically replaced by the pass record of the new HEAD), or (b) a human confirms the content and manually merges on GitHub. For (b), if you rerun with the same args after the manual merge, the independent confirmation on the next run automatically completes up to issue close confirmation without going through the opt-in gate (Issue #509). The state file's optinFixState No procedure is provided to bypass by deleting or altering. If the cause is only the PR body (ordinary missing records, not a latch), follow the procedure for references/recovery.md (run locally against the current HEAD → update the relevant marker line in the PR body with the current HEAD sha and pass → rerun with the same args) |
| Limit duplicate bads to cancelled / failure / timed_out only, and include pending, action_required, startup_failure, and stale in "normal duplicates" | success・neutral・skippedOther than (treated as passing and non-blocking under required status checks), do not treat as normal. pending (incomplete) is detected by the separate pend and can itself cause BLOCKED, so wait without proceeding to search for rerun targets |
neutral・skipped as bad (ordinary CI failure) and proceed to search for rerun targets |
neutral・skipped is a conclusion that is treated as passing in GitHub's required status checks determination and is not subject to fail-closed.success・neutral・skipped Treat duplicates of as normal reruns, and suspect another cause of BLOCKED |
| Without confirming that a test failure is unrelated to the diff, assume it is flaky and rerun | After actually verifying the two points—the same job is green on main and the diff scope—then rerun (see "Operational guard during simultaneous sync / mass PR submission" below) |
Operational guard during simultaneous sync / mass PR submission
In operations that submit the same change simultaneously to many repositories (such as skill sync), CI-derived failures unrelated to the diff content occur. Below are three types that are easy to misdiagnose and the steps to isolate them.
| Event | Symptom | Action |
|---|---|---|
| OOM due to parallel load | During linking ld terminated with signal 9 [Killed] |
This is caused by runner memory pressure, so rerunning while congested yields the same result. Wait until the queue is empty |
| Missing label for repos newly introducing CI | In repos newly introducing CI, dependencies / automated there is no label and gh pr create --label exits 1, so the PR is not even created |
Create the label before submitting |
| Misjudgment of flaky | Tests unrelated to the diff fail | Check the following 2 points before rerunning: "the same job is green on main" and "the diff cannot affect that test (the changed paths were actually measured)". For the former, gh run list --branch main should not be used alone (successes from another workflow or skipped jobs can get mixed in, and the crucial failing job may actually be failing or unexecuted on main yet be misidentified as green). After identifying the workflow file name and job name on the failed PR,gh run list --branch main --workflow <workflow-file> --json databaseId,conclusion --limit 1 --jq '.[0].databaseId' get the ID of the most recent run with, and `gh api repos/OWNER/REPO/actions/runs//jobs --jq '.jobs[] |
Recommended submission unit: split into 5 or fewer repositories per batch, and submit the next batch after all runs of the previous batch have completed (gh run list で in_progress / queued is 0) (the number of batches is derived with ceil(対象リポジトリ数 / 5) ). This corresponds to the cross-repository version of the parallel parallelism guideline in "Notes" (the higher the parallelism, the more the CI queue is strained).
If BLOCKED appears during simultaneous submission, refer to the branch for "When all checks appear to pass but the merge does not proceed" in Step 6.
Model / effort assignment
| Agent | model | effort | Rationale |
|---|---|---|---|
plan:issue-tree(Tree retrieval / dependency extraction) |
sonnet | medium | Body reading comprehension / dependency judgment |
plan:declared-deps-*(Mechanical extraction of dependency declarations in the body) |
haiku | low | Transcription of routine command output (no judgment) |
plan:out-of-tree-deps-* / plan:root-ancestors-<round>(Mechanical retrieval of state premised on being outside the tree and the root's ancestor chain) |
haiku | low | Transcription of routine command output (no judgment). Launched only when there is a premise outside the tree. The ancestor chain changes its label each round (plan:root-ancestors-1 etc., up to 5 rounds) |
detect:external-checks(External check determination) |
haiku | low | Routine command aggregation |
state:load / state:load-verify / state:load-fill / state:update / state:update-batch:<n> / state:cleanup / state:init-all / state:high-water |
haiku (falls back once to sonnet if not returned) | low | Mechanical processing by jq. Only when StructuredOutput is not returned (exception, null, schema nonconformance) continues, fall back once to sonnet with the same prompt.state:load-verify is an independent agent that verifies the read results by sha256 per item.state:load-fill re-fetches keys that were not returned, 5 at a time, using host-assembled jq (for details, see references/recovery.md)。state:update-batch:<n> writes the blocked records for nodes that cannot be started, 100 at a time in one go (do not launch in proportion to the count. See below) |
nonce:seed(seed generation for boundary tokens) |
haiku | low | /dev/urandom Read-only (because the driver has no random number source. See "Handling of untrusted data" 2 below) |
recover:#N(Judgment of whether interrupted work can be resumed) |
(Unspecified = inherit session) | medium | Equivalent to plan judgment (judged on the same axis as Plan) |
plan:#N(Per-issue planning) |
(Unspecified = inherit session) | high | Most complex planning |
impl:#N(Implementation) |
sonnet | medium | Implementation according to the plan (cost optimization) |
review:#N(Independent Review) |
sonnet | medium | Quality and security assessment |
fix:#N(Fix) |
sonnet | medium | Implementation-related, cost optimization |
pr-bind:#N(PR verification before resuming monitoring and before entering a newly created PR into the Merge loop) |
sonnet | low | gh pr view Only transcription of the value obtained for . (Verification of existence, headRefName, and closingIssuesReferences is done on the host side) |
merge:#N(CI/review monitoring and merge) |
sonnet | medium | CI/review assessment and mergeability gate |
close:#N(Acceptance criteria verification and close) |
sonnet | medium | Acceptance criteria verification and close |
Resume from interruption or failure
The running state is _/issue-trees/<親イシュー番号>.json It is automatically saved to . Even if the session is interrupted or forcibly terminated,the same args you can resume just by re-running with. For the state file's status transition table, automatic deletion of the worktree, and the procedure for the implementation agent to reuse existing PRs/remote branches, see below.
Details: references/recovery.md
Handling of out-of-scope items
If, during the implementation and self-review of each sub-issue (process step 7: implement-review), items arise that should be addressed but are judged to be outside the current scope (unaddressed improvements, separate features, technical debt, follow-up work), do not leave them unattended and be sure to track them.Among the unresolved review comments considered by the fix agent in the Merge phase (Step 6), those judged unfixable or outside the scope of the current issueare also treated as detection sources in the same way. For the procedure and handling of untrusted data (prompt injection mitigation), see below.
Details: references/out-of-scope-support.md
Notes
- Automatically execute up to PR creation without user approvalTherefore, carefully check the parent issue number, branch, and parallelism in advance.Client-side automatic merging is
autoMerge: true+externalChecksexecuted only in opt-in runs where is confirmed (including trusted context declarations for all Apps)(See the "Client-side automatic merge design" section in references/automerge-design.md. Opting in proceeds all the way to squash merge without per-instance user approval, so opt-in must be specified with an understanding of the residual risks described in that section — in particular, that under a branch protection configuration that does not require non-author approval, the merge can be completed without additional human approval.) With opt-out (the default), a PR that satisfies the merge conditions stops in a mergeable stateblockedand the merge is performed by a human on GitHubか、via the server-side auto-merge workflow (upstream'sdocs/implement-issue-tree/auto-merge-sample.yml)+ branch protection .The merge-guard hook and autoMerge opt-in (client-side merge) cannot be used together(because in a repo with the hook installed, the subagent'sgh pr mergeis denied. See the "Server-side delegation of automatic merge and the merge-guard hook" section in references/automerge-design.md). Choose one of the following for operation: (a)autoMerge: truewhen using the opt-in run of , do not install the merge-guard hook and enforce only via server-side branch protection (third party = non-author approval required, dismiss stale, normal/force push prohibited, required checks), or (b) when installing the merge-guard hook, do not perform automatic merge (defaultautoMerge: false) and delegate the merge to a human or the server-side auto-merge workflow, using the hook and branch protection together (see Step 6, "Server-side delegation of automatic merge and the merge-guard hook", and "Handling untrusted data" item 5) parallelOnly integers from 1 to 8 are valid. Non-integers and out-of-range values fall back to the default of 3. The higher the parallelism, the more attention is needed regarding API rate limits and CI queue congestion- Only the fix agent of the Merge loop performs the resolve (marking as resolved) of review threads: assuming the fix has already been reflected in the remote head, (a) immediately after a successful push, it resolves the threads it handled itself (derived from the monitor's structured output, host-verified threadId), and (b) in rounds without a push, only the allowlist deterministically computed by the host is resolved via the
resolveReviewThreadmutation (resolve via any path other than fix is prohibited. For details of the deterministic matching in (b), see references/automerge-design.md. However, (b) is currently permanently an empty list = does not hold, so in practice only (a) holds). The monitor / merge-exec / merge-verify / Review loop fix do not execute it. Threads judged out-of-scope are not resolved and stop at being recorded in the PR body, so they remain unresolved and become blocked → at the final report, decide whether to approve creating an issue and resolve manually. Re-execution after a human resolve (or a resolve during continued monitoring) re-evaluates the merge conditions - Each implement / fix runs isolated in an independent worktree, but does not change global state such as the main working copy's branch or shared settings
- All agents do not change the ruleset, branch protection, or repository settings(
gh apiviarulesets/branches/<branch>/protectionPATCH, PUT, POST, DELETE to , or the repository itselfrepos/<owner>/<repo>の PATCH・DELETE、gh repo edit, GraphQL mutations of the same kind, etc. As common instructions,REPO_SETTINGS_POLICY(implemented into all prompts such as implementation, fix, monitoring, merging, base incorporation, etc.). Even if a review requests a configuration change (e.g., registering a new check as required), do not perform it; report it in summary / outOfScope as an action item. Do not describe the presence or absence of approval as anything more than fact (do not write approvals in commit/PR bodies that were not actually obtained). Changes to the ruleset are made by humans together with the 3-axis validation of.claude/rules/ruleset-policy.md(if present in the target repository). What the merge-guard hook (optional to introduce) mechanically denies is writes to the ruleset, branch protection, and the repository itself (repos/<owner>/<repo>), GraphQL mutations of the same kind, andgh repo edit/rename/archive/unarchive/delete, limited to these. Other configuration changes such as variables / secrets / actions permissions / collaborators / hooks / environments are prohibited only in the prompt (best-effort). - The tree is fetched only once at the start of the run. Sub-issues added during the run are not subject to implementation in that run, and are detected as open descendants during parent close validation, so the parent is not closed. After additions, re-run.
- For large trees (hundreds of items), execute in multiple batches per sub-parent (the agent limit for one workflow is 1,000. As the limit approaches, stop starting new work and let in-progress issues complete. Issue #592, references/agent-call-budget.md). Before starting,
dryRun: trueyou can check how many items can be started and how many will become blocked. - Write the blocked records for nodes that cannot be started all together(Issue #585). For blocked nodes confirmed by a chain of dependency failures and nodes left unstarted due to a halt etc., do not launch
state:update:#None by one; at the end of the run, write them to the state file in chunks of 100 with one agent (state:update-batch:<n>) (chunks are serial; even 1,101 items take 12 times). If the saved state is alreadyblockedでnoteもprand the items are the same, do not write them (do not pay again for nodes that are unchanged when re-running with the same arguments. Do not omit items whose state file could not be read; write them). For nodes that have a PR, do not overwrite the resume information as before.noteIf the issue number listing has 6 or more items, shorten it to "N items (first 5: #a, #b, …)". Even if an intermediate chunk fails, continue, and in the return value'sblockedStateWrite(requestednumber of items attempted to record /unchangednumber of items omitted /attemptednumber of items attempted to write /writtennumber successfully written /unwrittennumber that could not be written /unwrittenIssuesfirst 20 items /chunks/failedChunks) and the log (⚠️ blocked の状態ファイル記録: N 件を書けなかった), the discrepancy between the return value (done) and the number of items in the state file can be seen. The discrepant portion is rewritten when re-run with the same arguments. --no-verifyis never used (bypassing pre-commit hooks is prohibited. If the target repository has.claude/rules/conventional-commits.md, follow its conventions).- Shell command variables must always be
"${var}"quote with (countermeasure against command injection). Strings retrieved from the GitHub API are sanitized before prompt embedding - 1 issue failure does not stop and proceeds to the next, but 3 consecutive issue failures halt new work starts
- Before merging, CI must complete with all checks in success/neutral/skipped (0 pending/failure)explicitly confirm (do not pass just because waiting for CI completion has ended; confirm the conclusion of all checks by the count in the envelope)
- Before merging, there must be at least 1 checkconfirm. Total check count 0 and
gh pr checks's non-zero exit (including check absence errors and retrieval failure) is not considered green; the monitoring side stops withblocked(quality), and the merge-exec side declines withchecks-not-green(fail-closed: do not automatically merge a PR whose CI has not started) - The configuration of external checks (Cursor Bugbot, etc.) is specified with
args.externalChecks(declared as the pair of{"app": "<slug>", "context": "<required check context>"}. The old format with slug only allows monitoring/waiting to work, but client-side automatic merge stops with fail-closed). Step 1 (Tree phase) observation (analysis of the most recent 3 merged PRs) is only a reference value, and unless explicitly stated,new mergesare stopped (only closing and state record recovery when the PR is alreadyMERGEDcan terminate withmergedvia the recovery-only merge-exec + merge-verify). Skipping Bugbot waiting and@cursor reviewreminders is possible only whenexternalChecks: []has confirmed "no external checks" args.externalChecksExternal check Apps explicitly specified with confirmation of startup for the HEAD shais a mandatory condition for merging regardless of slug (verify not only cursor but also sonarcloud, etc.). For cursor, at least 1 review must have arrived and CHANGES_REQUESTED must be 0 (since Bugbot does not issue APPROVED, APPROVED is not required. Individual comments are posted as inline review threads, so the "0 unresolved threads" gate works as content-independent mechanical enforcement. The monitoring side's needs-fix determination is advisory for the fix loop and is not an input to mergeability). For non-cursor, if there is at least 1 check-run, all of them must have an allowable conclusion (if there is failure or incompleteness, it fails even if an APPROVED review exists); only when there are 0 check-runs is the condition "at least 1 APPROVED review and 0 CHANGES_REQUESTED / COMMENTED / PENDING". If startup cannot be confirmed within the waiting limit (maximum 10 minutes), do not consider it "no checks" and stop withblocked(fail-closed: do not bypass the gate on App failure, delay, or startup failure). The merge execution agent side also independently verifies by re-fetching only the count and state enum for each App- Before merging, all review comments must be resolvedcheck (do not merge if there are unresolved comments)
- merged terminal only if it has passed independent verificationconfirm. merge-exec's
merged: trueはreason(merged/already-merged) and require consistency with it (inconsistency as systemic failurefailedterminal), and furthermore, with a read-only merge-verify agent,state=MERGEDtreat as merged only if the match with the monitoring-time HEAD sha can be independently verified. If verification is impossible or there is a mismatch,blocked(quality) fail-closed, and if it was actually already merged, recover on the next run by resuming monitoring (already-merged path) - Commits and PR creation follow Conventional Commits (if the target repository has
.claude/rules/conventional-commits.md, follow that). If a security issue is detected, fix it before proceeding (if the target repository has.claude/rules/security.md, follow its OWASP Top 10 perspective. If not, check from the perspectives of hardcoded secrets, injection, and excessive privileges) - If CI appears all green but the merge does not proceed, suspect remaining checks from cancelled runs and triage according to the Step 6 branch "when all checks appear to pass but the merge does not proceed" (
mergeStateStatusis not obtained in the automated flow) - After an interruption or failure, there is no need to manually delete the worktree or answer a deletion confirmation. On re-execution, the Recover phase decides per-issue whether to continue, and sorts worktrees with work into continue (continue with Implement) or discard (delete → start fresh from Plan). Deletion of either continue / discard worktrees is executed only if the completion of WIP saving can be verified, and if it cannot be verified, the remnants are preserved and
failed(fail-safe choosing stagnation over data loss). Note that disposable worktrees for review / pr-create are not automatically deleted by policy, so look at the log list at the end of the run and clean them up manually as needed - Each agent must not create files in the main worktree (repository root) or the current directory (exceptions are the host-specified state file and its
mktemptemporary file only). Temporary files are placed at the absolute path ofmktemp, or in a dedicated directory created withmktemp -dinside the scratchpad, and deletion is limited to only what was created by oneself. At run start and end, untracked files in the main worktree are inspected, and if any file newly appeared during this run, warn in the final reportmainWorktreeUntrackedand in the log (not automatically deleted. Attribution is inferred because concurrent runs or human work may also be picked up) - Agents during a run share the scratchpad with the main session. Files used between runs (work contracts, gate scripts, wait scripts, etc.) are not placed in the scratchpad, but
~/.cache/<名前>/Place it outside the scratchpad and pass that path to the agent (the agent is subject to a rule not to delete or overwrite anything other than its own creations, but do not rely on the rule; leave no room for it to be affected) - Agents that do not have an isolated worktree (planning, monitoring, merging, state writing, etc.) run in the main worktree, so
git checkout/switch/reset/merge/rebase/stash/pull/commit/cleando not change the main worktree's HEAD, index, or working tree with etc. (origin/<base>the contents ofgit show/git diff/git ls-tree/git logare read with). Observe the main worktree's HEAD (branch name and sha) at run start and end, and if the branch has changed (or if it was detached at start and the sha has moved), warn in the final reportmainWorktreeHeadand the log (do not automatically restore)
Execution in a sandbox environment
This skill requires GitHub operations over the network (git fetch / git push / PR creation and merging). The relevant commands are executed with the sandbox disabled on a per-command basis. It cannot be executed in an environment where network blocking cannot be lifted.