Repository navigation
Description
Machine-Readable Contract
contract_schema_version: v1
issue_kind: implementation
goal_ref: "agent-ops:guard-arbitration-cleanup-contract-delivery"
risk_class: agent_ops_guard
change_kind: workflow
dedupe_key: "agent-ops:guard-arbitration-cleanup-contract-delivery:pr1130-retro"
affected_runtimes:
- claude_code
- codex_cli
parent_issue: "none"Parent Issue
none
Parent Goal Ref
なし(単独改善のため parent goal 参照なし)。本 Issue 自身の ## Outcome を goal の正本とする。
Current Validated Scope
## Allowed Paths に列挙したファイル群のみを write-capable な作業範囲とする。cleanup contract の配送スキーマ「自体」(POST_MERGE_CLEANUP_REQUEST_V2 のキー集合・基本配送経路)は #1050(CLOSED/COMPLETED)で実装済のため再実装しない。
本 Issue は 2026-06-23 の OWNER レビュー(PR #1139 comment #4774308040)で REQUEST_CHANGES を受け、認可境界・実 hook 経路検証・schema 不足が判明したため contract を改訂した。改訂後のスコープは次の 6 点である。(1) cleanup の認可境界を単一 cleanup_exec executor に集約(agent は bare git cleanup を直接実行せず executor 経由のみ)、(2) guard が cleanup_exec / guard_preflight / materialize を 実 PreToolUse hook 経路 で allow すること(active issue worktree + cwd=local main root + branch=default の実状態で)、(3) POST_MERGE_CLEANUP_REQUEST_V3 の one-shot 化(nonce / issued_at / operation / per-operation argv hash・consume)、(4) V3 invalid 時の V2 downgrade 禁止(3 値ローダ)、(5) preflight が実 worktree catalog を使用、(6) Codex guarded route の成立(broad rule 分割 + codex execpolicy CI)。
Remaining Parent Gaps
- 本 Issue 完了後も残る gap として、overlap preflight の hard-gate 化(cleanup contract の自動 expiry GC)は別 follow-up で扱う。
- guard arbitration の matrix を他 cleanup skill(pr-review 系)へ横展開する作業は本 Issue の範囲外で、必要時に follow-up Issue を切る。
- V2 contract 経路の完全削除(移行期間終了後)は follow-up とする。本 Issue では V3 invalid 時の V2 downgrade を塞ぐところまでを扱う。
Source
- origin: agent-ops-review retro of PR feat: record assist_player playtest evidence #1130 / Issue 実装: assist_player playtest self-explanation test と evidence policy を整備する #987(merged, completed)+ PR feat(#1137): guard arbitration preflight と cleanup contract V3 delivery を機械化 #1139 OWNER review(REQUEST_CHANGES, 2026-06-23)
- dedupe_key:
agent-ops:guard-arbitration-cleanup-contract-delivery:pr1130-retro - related (re-use, do not re-implement): 実装: worktree_scope_guard に read-only / mutation / cleanup 分類を導入し post-merge-cleanup を詰まらせない #1050(cleanup-contract delivery schema + exact-argv allow、CLOSED/COMPLETED)
- related (prior guard work): fix(guard): gh issue/pr GitHub ops を allowlist-closed から除外し post-merge-cleanup 操作を復元する #1108 / 実装: Claude Code / Codex CLI で local root checkout のブランチ変更をブロックする #1014 / 実装: local_main_branch_guard の Claude/Codex read-only parity と script allowlist を整備する #1089 / 実装: CodexCLI read-only Bash hook noise guard を追加する #1069
- superseded attempt: PR feat(#1137): guard arbitration preflight と cleanup contract V3 delivery を機械化 #1139(contract-based 設計、OWNER REQUEST_CHANGES。本改訂で認可境界を executor へ pivot)
- anchor decision: PR feat(#1137): guard arbitration preflight と cleanup contract V3 delivery を機械化 #1139 OWNER レビューコメント #4774308040 の 5 Blocker / High / Medium / 12 必須マージゲートを本文へ反映済み。
Repo Ground Truth(着手前提)
実装着手者は以下の現状を前提にする(2026-06-23 時点で検証済み。baseline は origin/main)。
scripts/agent-ops/ディレクトリは origin/main 上では未作成。guard_preflight.py/materialize_cleanup_contract.py/cleanup_contract_v3.py/cleanup_exec.py/worktree_catalog.pyはいずれも未実装。- 実機再現済みの中核バグ: active
LOOP_ISSUE_NUMBER+ matching worktree がある状態で local main root からuv run python3 scripts/agent-ops/<tool>.py ...を実行すると、worktree_scope_guard.build_decisionはuv ...をunknown分類しcwd_outside_worktreeで deny する。よって新ツールは worktree_scope_guard 側に exact 専用 command class allow を追加しない限り実行不能。permission allowlist では同一 Bash tool に登録された hook を回避できない。 .claude/hooks/worktree_scope_guard.pyの cleanup decision は先頭 program がgitの場合のみ cleanup class に入る(rtk git ...はunknown)。clean 判定 subprocess の hook timeout は Codex 側 10 秒。.codex/rules/default.rulesでは broad rule によりgit worktree ...は forbidden、git branchは read-only allow に含まれgit branch -d/-Dも allow 側に倒れる。最も厳しい decision が勝つため exact prompt rule を足すだけでは guarded route は成立しない。.github/workflows/にcodex execpolicy checkを回す job は存在しない。tests/codex/test_local_main_branch_guard.pyと.claude/hooks/tests/test_worktree_scope_guard.pyは既存。実 hook 経路(.shラッパに stdin JSON を渡す process 統合)テストの cleanup 版・Codex hook chain 起動テストは未整備。
Runtime Verification Applicability
- decision: not_applicable
- reason: 変更対象は guard / hook の判定ロジック・cleanup executor・cleanup contract validator・CI 設定であり、検証は静的検証(rg / test -f)と pytest(実 hook 経路 process 統合・fault injection 含む)、および
codex execpolicy checkで完結する。ゲームプロセスの起動・通信・I/O を要する動作検証は不要。 - if immediate: N/A
- if deferred: N/A
Outcome
post-merge-cleanup の worktree / branch 削除が、単一の狭い認可境界 scripts/agent-ops/cleanup_exec.py を通して安全に実行できる。cleanup_exec は実行のたびに「PR が merged」「PR head branch が一致」「linked issue が一致」「worktree が実 catalog に存在」「worktree branch が一致」「root が default branch」「対象 worktree が clean」を検証してから exact git worktree remove + git branch -d を内部 subprocess 配列で実行する。agent は bare git cleanup を直接実行しない。
worktree_scope_guard.py(Claude)と .codex/hooks.json(Codex)は cleanup_exec / guard_preflight / materialize_cleanup_contract を 完全一致の専用 command class として allow し、active issue worktree + cwd=local main root + branch=default の実状態で 実 PreToolUse hook 経路 を通ることが process 統合テストで実証される。POST_MERGE_CLEANUP_REQUEST_V3 を defense-in-depth で残す場合は one-shot(nonce / issued_at / operation / per-operation argv hash・使用後 consume)とし、V3 invalid 時に古い V2 へ downgrade しない。guard_preflight は実 git worktree list --porcelain -z catalog を使って判定する。Codex 側は broad rule を分割し codex execpolicy check を CI で検証する。
Problem
PR #1139(contract-based 設計)に対する OWNER レビューで以下が判明した(comment #4774308040)。
- Blocker 1: active issue worktree + cwd=local main root の状態では、SKILL 記載の
guard_preflight/materialize実行コマンドが worktree_scope_guard にcwd_outside_worktreeで deny される。追加テストが関数直接呼び出しで実 hook 経路を回避し、この事実を隠蔽していた(実機再現済み)。 - Blocker 2: V3 が JSON 破損 / schema 不正 / 読み取りエラー / module import 失敗のとき V2 env /
.claude/artifactscontract へ downgrade する。古い無期限 V2 が残れば V3 を壊すことで降格できる。 - Blocker 3:
guard_preflightがcwdを使わず、active_worktree_stateを実 worktree catalog でなく環境変数と root branch 名だけで決めるため誤判定する。cleanup_contract_state: validも schema/expiry しか見ず runtime guard が拒否する contract をrun_gated_cleanupと案内し得る。 - Blocker 4: Codex rules で
git worktree removeは broad forbidden、git branch -d/-Dは broad allow に倒れ、追加した prompt rule は到達不能。guarded route が成立していない。rtk git ...は cleanup class に入らない。codex execpolicy checkも CI 未配線。 - Blocker 5 / High(replay / one-shot / per-op hash): contract が CLI 入力をそのまま信頼し PR merged 等を検証しない自己発行可能な checksum で、authorization boundary になっていない。1 時間 TTL で consume されず replay 可能。
git branch -dに hash gate がなく、worktree remove の hash も contract の lexical path から再計算するため symlink alias で実 argv と乖離し得る。 - High(durability / symlink): materialize は file/dir fsync がなく durable でない。islink 事前検査と makedirs/mkstemp 間に TOCTOU。reader が O_NOFOLLOW / fstat 検査をしない。
- High(timeout): 内部 subprocess timeout 合計が外側 hook timeout(10s) を超え得る。
- Medium: worktree 確認が
--porcelain(非 -z)/ branch validator がgit check-ref-format非準拠 / expiry 無上限・naive timestamp / 単一 global contract path の concurrent 競合。
加えて従来からの deadlock(git -C <worktree> の unparseable_branch_mutation、root drift + active worktree での復旧不能)も解消対象とする。
Design Decisions(OWNER レビュー反映・確定方針)
実装着手者は以下を満たすこと。満たさない PR は block 対象。
- 認可境界 = 単一 executor: cleanup の正本経路を
scripts/agent-ops/cleanup_exec.pyに集約する。cleanup_execは実行時に PR merged / head branch / linked issue / worktree catalog / branch / root=default / clean state を検証してから exact worktree remove + branch -d を内部 subprocess 配列で行う。agent は baregit worktree remove/git branch -dを直接実行しない(guard が deny)。materializeで発行する V3 contract は defense-in-depth であり single source of authorization ではない。 - 実 hook 経路での allow(exact command class):
worktree_scope_guardはcleanup_exec/guard_preflight/materialize_cleanup_contractを完全一致の専用 command class として allow する。条件: shell chain / inline env /python -c/ 任意スクリプト置換を拒否、script の realpath が repo 内所定ファイルと一致、cwd=canonical main worktree root、root branch=default、引数の余剰・重複を拒否。検証は 実 hook stdin JSON を与える process 統合テスト(関数直接呼び出し禁止、env だけの状態擬装禁止、実 git worktree を構築)で行う。 - V3 三値ローダ: loader を
ABSENT/VALID_V3/PRESENT_BUT_INVALIDに分ける。V3 path がlexists()する場合、parse / schema / permission / I/O の全エラーを deny に倒す。V2 fallback は V3 path が本当に存在しない場合のみ。V3 module の import 失敗は cleanup deny。invalid V3 + valid V2 env/file => denyを必須テスト化。 - operation 別 one-shot contract: V3 に
operation(worktree_remove|branch_delete)・nonce(cryptographically random)・issued_atを追加し、command_hash は operation ごとに分け、runtime ではshlex.split()した 実 argv から再計算する(contract 値から期待 argv を再構築して hash しない)。extra argv / relative path / 別 lexical form を拒否。使用前に contract を atomic rename で consume し、成功・失敗後とも元 contract を残さない(replay / 同名 branch 再作成後の再利用を deny)。 - preflight は実 catalog 使用:
git worktree list --porcelain -zの catalog 処理を共有モジュールscripts/agent-ops/worktree_catalog.pyに出し、worktree_scope_guardとguard_preflightが同一解決を使う。matchesは issue number / worktree realpath / branch ref / cwd classification / git common-dir / contract target / command hash がすべて一致する場合に限る。cwd引数を実際に使用する。 - Codex guarded route の成立:
.codex/rules/default.rulesの broadgit worktree/git branchrule を分割する。exactgit worktree remove <one-path>= prompt、add/move/lock/unlock/prune/repair/--force= forbidden。git branchの broad allow を廃し read-only は--show-current/--listを個別 allow、exactgit branch -d <one-branch>= prompt、-D/-f/--force/multi-target = forbidden。bare route に統一(rtk git ...は cleanup として認識しない)。codex execpolicy checkを CI に追加し bare/rtk/force/multi の全マトリクスを検証。実.codex/hooks.jsonを起動する統合テストを追加。複数 hook は順次委譲でなく並行実行であり「全 guard の論理積で allow」と定義する。 - durable / symlink-safe 書き込み: materialize は temp を
fchmod(0600)→ write → flush →fsync(temp_fd)→os.replace/renameat→fsync(parent_dir_fd)。symlink 対策は directory fd 基準の descriptor-relative traversal(各 component にO_DIRECTORY|O_NOFOLLOW、Linux ではopenat2(RESOLVE_BENEATH|RESOLVE_NO_SYMLINKS))。reader もO_NOFOLLOW+fstatで regular file / owner / mode / 上限 size を検査。 - 共有 monotonic deadline: 全 guard 判定で共有する monotonic deadline を導入し、個別 subprocess timeout を残時間以下に、外側 hook timeout を worst-case 合計より大きくする。timeout は共通 reason code に正規化。slow git / locked index の fault-injection test を追加。
- Medium 群: worktree parser を全箇所
--porcelain -zに統一。branch validator はgit check-ref-format --branchを正本にする。expires_atは timezone 必須、issued_at追加、最大 TTL を数分に制限、clock skew 上限を定義。単一 global contract path の concurrent 競合を lock または target-scoped nonce file で直列化する。 - stale 手順の集約:
post-merge-cleanupSKILL から agent 直接のgit -C <worktree>clean 判定を削除し、clean 判定をcleanup_exec/ guard 内部 subprocess へ集約。SKILL は bare cleanup でなくcleanup_exec経由を案内する。
Required Schemas
CLEANUP_EXEC_REQUEST_V1: # cleanup_exec の CLI 入力
pr_number: int
linked_issue_number: int | null
worktree_path: string
branch_name: string
CLEANUP_EXEC_RESULT_V1:
status: ok | refused | error
reason_code: string # SHARED_CLEANUP_REASON_CODES から取る
verified:
pr_merged: bool
head_branch_match: bool
linked_issue_match: bool
worktree_in_catalog: bool
branch_match: bool
root_default: bool
worktree_clean: bool
actions_taken: [] # worktree_remove | branch_delete
stderr_line_count: int # <= 10
AGENT_GUARD_PREFLIGHT_V1:
status: ok | blocked | human_required
root_branch_state: default | drifted | detached_or_unknown
active_worktree_state: none | matches | mismatch # 実 catalog 由来
cleanup_contract_state: absent | valid_v3 | present_but_invalid | expired
resolved_worktree: # 実 catalog の解決結果(誤判定防止)
issue_number: int | null
worktree_realpath: string | null
branch_ref: string | null
cwd_classification: inside_worktree | outside_worktree | unknown
git_common_dir: string | null
safe_scratch_contract_path: artifacts/agent-ops/cleanup_contract.json
allowed_next_commands: []
blocked_reason_codes: []
POST_MERGE_CLEANUP_REQUEST_V3: # defense-in-depth, one-shot
schema: POST_MERGE_CLEANUP_REQUEST_V3
pr_number: int
linked_issue_number: int | null
worktree_path: string # materialize 時点で realpath 固定
branch_name: string # git check-ref-format --branch 準拠
require_clean: true
operation: worktree_remove | branch_delete
command_hash: string # 実 argv の SHA-256(operation 別)
nonce: string # cryptographically random
issued_at: iso8601 # timezone 必須
expires_at: iso8601 # timezone 必須・最大 TTL 数分
WORKTREE_CATALOG_ENTRY_V1: # 共有 worktree_catalog.py の出力
worktree_realpath: string
branch_ref: string | null
git_common_dir: string | null
detached: bool
# 共有 reason_code 列挙(Claude / Codex parity の対象)
SHARED_CLEANUP_REASON_CODES:
- no_cleanup_contract
- cleanup_contract_present_but_invalid
- cleanup_contract_expired
- cleanup_contract_consumed
- cleanup_command_hash_mismatch
- cleanup_operation_mismatch
- worktree_path_mismatch
- worktree_not_in_catalog
- worktree_dirty
- branch_force_delete_denied
- root_drift_active_worktree_mismatch
- pr_not_merged
- guard_deadline_exceededIn Scope
scripts/agent-ops/cleanup_exec.py新規(認可境界・単一 executor)scripts/agent-ops/worktree_catalog.py新規(--porcelain -zcatalog 共有モジュール)scripts/agent-ops/cleanup_contract_v3.py新規(V3 one-shot validation + operation 別 argv hash + 三値ローダ + check-ref-format)scripts/agent-ops/guard_preflight.py新規(実 catalog 使用・cwd使用・recovery hint)scripts/agent-ops/materialize_cleanup_contract.py新規(durable/symlink-safe 書き込み・nonce/operation/one-shot 発行).claude/hooks/worktree_scope_guard.pyの exact command class allow / V3 三値ローダ / operation 別 hash / 共有 deadline / catalog 共有scripts/agent-guards/local_main_branch_guard.pyの arbitration 整合- 実 hook 経路 process 統合テスト(Claude
.sh+ Codex.codex/hooks.json起動)・fault injection(slow git / symlink swap / crash durability / deadline)を含む pytest .claude/skills/post-merge-cleanup/SKILL.mdの手順更新(cleanup_exec経由・stalegit -C削除).codex/hooks.json/.codex/rules/default.rulesの Codex 側配線(broad rule 分割・同一判定コア).github/workflows/にcodex execpolicy checkjob 追加
Out of Scope
- cleanup contract V2 配送スキーマ「自体」の再実装 — 実装: worktree_scope_guard に read-only / mutation / cleanup 分類を導入し post-merge-cleanup を詰まらせない #1050(CLOSED)で実装済。
- V2 経路の完全削除(移行期間後の follow-up)。本 Issue は V3 invalid 時の V2 downgrade を塞ぐまで。
- permission skip / hook bypass /
--dangerously-skip-permissions - clean-state 証明なしの破壊的 cleanup
- cleanup contract の CI artifact 公開配布(
actions/upload-artifact) - overlap preflight の hard-gate 化 / 自動 expiry GC(follow-up)
- guard arbitration matrix の他 cleanup skill 横展開(follow-up)
assets//LICENSES// secrets / agent ops と無関係な feature 実装
Acceptance Criteria
各 AC の最終挙動は ## Design Decisions の確定方針を満たすことを必須とする。VC は baseline(origin/main)で決定論的に fail することを確認するためのもの(新規ファイルは test -f、既存ファイルへの新規 token は rg -n)。最終受け入れは Design Decisions + AC 本文 + PR レビュー時の pnpm test / uv run pytest / codex execpolicy check 回帰ゲートで判定する。
- AC1:
scripts/agent-ops/cleanup_exec.pyを新規作成し、CLEANUP_EXEC_REQUEST_V1を受けて PR merged / head branch / linked issue / worktree catalog / branch / root=default / clean を検証してから exact worktree remove + branch -d を内部 subprocess 配列で実行しCLEANUP_EXEC_RESULT_V1を返す(Design Decisions 1)。検証失敗時はstatus: refused+ 該当 reason_code。 - AC2:
scripts/agent-ops/worktree_catalog.pyを新規作成し、git worktree list --porcelain -zをWORKTREE_CATALOG_ENTRY_V1列へ parse する共有モジュールを提供する。worktree_scope_guardとguard_preflightがこれを使用する(Design Decisions 5, 9)。 - AC3:
worktree_scope_guardがcleanup_exec/guard_preflight/materialize_cleanup_contractを exact 専用 command class として allow する(shell chain / inline env /python -c/ 任意スクリプト置換 / 引数余剰を拒否、script realpath 一致、cwd=main root、root=default)。実 hook stdin JSON を与える process 統合テストで、activeLOOP_ISSUE_NUMBER+ 実 matching worktree + cwd=main root の状態で allow されることを実証する(Design Decisions 2, Blocker 1)。 - AC4:
scripts/agent-ops/cleanup_contract_v3.pyを新規作成し、V3 を三値(ABSENT/VALID_V3/PRESENT_BUT_INVALID)で分類する。V3 path がlexists()する場合の parse/schema/permission/I/O エラーと module import 失敗を deny に倒す。invalid V3 + valid V2 env/file => denyを pytest 化(Design Decisions 3, Blocker 2)。 - AC5:
command_hashを operation 別とし、runtime ではshlex.split()した実 argv から再計算する(contract 値からの再構築をしない)。operation不一致はcleanup_operation_mismatch、hash 不一致はcleanup_command_hash_mismatch、extra argv / relative / 別 lexical form / symlink alias mismatch を deny。git worktree remove・git branch -d双方に hash gate を持たせる(Design Decisions 4, High)。 - AC6: V3 contract を one-shot 化する。
nonce/issued_at/ timezone 付きexpires_at(最大 TTL 数分)を持ち、使用前に atomic rename で consume し成功・失敗後とも元 contract を残さない。replay(同 contract 再利用)・同名 branch 再作成後の再利用を deny する pytest を追加(Design Decisions 4, 9, High replay)。 - AC7:
guard_preflight.pyが実worktree_catalogを使用しcwdを実際に使う。active_worktree_state: matchesは issue number / worktree realpath / branch ref / cwd classification / git common-dir / contract target / command hash 全一致時のみ。worktree 不在 / 複数一致 / branch mismatch / cwd mismatch の matrix を pytest 化(Design Decisions 5, Blocker 3)。 - AC8:
.codex/rules/default.rulesの broadgit worktree/git branchrule を分割し、exactgit worktree remove <one-path>とgit branch -d <one-branch>を prompt、force/add/move/lock/unlock/prune/repair/-D/-f/--force/multi-target を forbidden、read-only branch を個別 allow にする。codex execpolicy checkの bare/rtk/force/multi 全マトリクスが期待 decision を返す(Design Decisions 6, Blocker 4)。 - AC9:
.github/workflows/にcodex execpolicy checkを回す job を追加し、実.codex/hooks.jsonを起動する process 統合テスト(main root と linked-worktree cwd の双方)を追加する(Design Decisions 6, Blocker 4)。 - AC10:
materialize_cleanup_contract.pyを durable/symlink-safe にする(fchmod(0600)→ fsync(file) → replace → fsync(parent dir)、directory fd /O_NOFOLLOW/ 可能ならopenat2(RESOLVE_NO_SYMLINKS|RESOLVE_BENEATH)、reader もO_NOFOLLOW+fstat)。symlink swap / crash durability の fault-injection test を追加(Design Decisions 7, High)。 - AC11: 全 guard 判定で共有する monotonic deadline を導入し、個別 subprocess timeout を残時間以下に、timeout を
guard_deadline_exceededに正規化する。外側 hook timeout は worst-case より大きく設定。slow git / locked index の fault-injection test を追加(Design Decisions 8, High)。 - AC12: branch validator を
git check-ref-format --branch準拠にし、worktree parser を全箇所--porcelain -zに統一し、expires_at/issued_atを timezone 必須・最大 TTL 数分・clock skew 上限とし、単一 global contract path の concurrent 競合を lock / target-scoped nonce で直列化する(Design Decisions 9, Medium)。 - AC13:
root_drift_active_worktree_mismatchを共有 reason_code として guard / preflight が返す。arbitration / cleanup block の stderr は 10 行以内で raw command / raw env / secret-like path を出さない。 - AC14:
.claude/skills/post-merge-cleanup/SKILL.mdをcleanup_exec経由の手順へ更新し、agent 直接のgit -C <worktree>clean 判定を削除する。 - AC15: 既存
tests/codex/test_local_main_branch_guard.py/.claude/hooks/tests/test_worktree_scope_guard.pyを拡張し、Claude / Codex のSHARED_CLEANUP_REASON_CODESparity を 実 hook 経路 で検証する pytest を追加して PASS する。
Verification Commands
baseline(origin/main)で決定論的に fail する。新規ファイルは test -f(exit 1 = absent)、既存ファイルへの新規 token は rg -n(exit 1 = no-match)。contract review の VC preflight allowlist 内コマンドのみ使用(uv run python3 <script> 直叩き・未作成ファイルへの rg は使用しない)。
# AC1
# baseline-expect: fail
$ test -f scripts/agent-ops/cleanup_exec.py# AC2
# baseline-expect: fail
$ test -f scripts/agent-ops/worktree_catalog.py# AC3
# baseline-expect: fail
$ rg -n "cleanup_exec" .claude/hooks/worktree_scope_guard.py# AC4
# baseline-expect: fail
$ test -f scripts/agent-ops/cleanup_contract_v3.py# AC5
# baseline-expect: fail
$ rg -n "cleanup_operation_mismatch" .claude/hooks/worktree_scope_guard.py# AC6
# baseline-expect: fail
$ rg -n "cleanup_contract_consumed" .claude/hooks/worktree_scope_guard.py# AC7
# baseline-expect: fail
$ test -f scripts/agent-ops/guard_preflight.py# AC8
# baseline-expect: fail
$ rg -n "guarded cleanup route" .codex/rules/default.rules# AC9
# baseline-expect: fail
$ rg -n "execpolicy" .github/workflows/ci.yml# AC10
# baseline-expect: fail
$ test -f scripts/agent-ops/materialize_cleanup_contract.py# AC11
# baseline-expect: fail
$ rg -n "guard_deadline_exceeded" .claude/hooks/worktree_scope_guard.py# AC12
# baseline-expect: fail
$ rg -n "check-ref-format" .claude/hooks/worktree_scope_guard.py# AC13
# baseline-expect: fail
$ rg -n "root_drift_active_worktree_mismatch" .claude/hooks/worktree_scope_guard.py# AC14
# baseline-expect: fail
$ rg -n "cleanup_exec" .claude/skills/post-merge-cleanup/SKILL.md# AC15
# baseline-expect: fail
$ rg -n "cleanup_command_hash_mismatch" tests/codex/test_local_main_branch_guard.pyAllowed Paths
scripts/agent-ops/cleanup_exec.pyscripts/agent-ops/worktree_catalog.pyscripts/agent-ops/cleanup_contract_v3.pyscripts/agent-ops/guard_preflight.pyscripts/agent-ops/materialize_cleanup_contract.pyscripts/agent-guards/local_main_branch_guard.py.claude/hooks/worktree_scope_guard.py.claude/hooks/tests/test_worktree_scope_guard.pytests/codex/test_local_main_branch_guard.py.claude/skills/post-merge-cleanup/SKILL.md.codex/hooks.json.codex/rules/default.rules.github/workflows/ci.ymlartifacts/agent-ops/(生成物、gitignored)
Stop Conditions
- Allowed Paths 外の変更が必要と判明した場合
- 本 Issue の Required Schemas(キー集合・スキーマ・型定義)の更なる変更が必要になった場合
- 新規 Issue の起票が必要と判断した場合(スコープ分割が発生する場合)
- 後続 Phase / 別スコープへの波及が判明した場合
- nested SubAgent delegation が必要になった場合
- 権限昇格・既存テストの破壊的削除が必要になった場合
- guard の bypass / hook skip / secret・env 読み取りが必要になった場合
- cleanup 対象 worktree に staged / unstaged / untracked があり安全判定不能な場合
openat2等が CI ランナーで利用不可で、symlink-safe 要件を満たす代替が Allowed Paths 内で実現困難な場合
Required Skills
なし(ドメイン runtime dependency なし。Python・git CLI・GitHub Actions・codex execpolicy の標準知識で着手可能)。
Delivery Rule
1 Issue = 1 PR。隔離 worktree で実装し Draft PR を既定とする。root ブランチへ直接 commit しない。
Activity
squne121 commentedon Jun 22, 2026
結論
#1137 は方向性として必要です。PR #1130 の post-merge cleanup で露呈した「local main branch guard と worktree scope guard の相互ブロック」を、個別例外でなく 契約ファイル + preflight + reason_code parity に落とす設計は妥当です。ただし、現 Issue のまま実装すると 高確率で deadlock は残るか、逆に guard を弱めすぎます。
#1137 本体は open で、コメントは 0 件でした。本文上は #1050 の既存 cleanup contract を再利用しつつ、
guard_preflight.pyとmaterialize_cleanup_contract.pyを追加するスコープです。最重要ブロッカー
1.
POST_MERGE_CLEANUP_REQUEST_V3と既存 V2 実装が非互換#1137 は V3 schema に
command_hashとexpires_atを追加する想定ですが、現行worktree_scope_guard.pyはPOST_MERGE_CLEANUP_REQUEST_V2だけを読みます。しかも供給元は env var または.claude/artifacts/cleanup_contract.jsonです。このまま
materialize_cleanup_contract.pyが V3 をartifacts/agent-ops/cleanup_contract.jsonに出しても、guard 側が読まなければ AC5 は成立しません。Issue に以下を明記すべきです。2. safe scratch への契約ファイル materialize が Bash では通らない可能性がある
現行
LOCAL_MAIN_SCRATCH_ALLOW_V1は、local main checkout からartifacts/,playwright-report/,test-results/,coverage/,.cache/への Write/Edit/MultiEdit のみを例外許可しています。Bash write は明示的に Phase 2 扱いで、現時点では対象外です。さらに、例外条件は「repo-local
.gitignoreによって ignore されている」「未追跡」「安全 prefix」「secret-like path でない」「symlink component なし」などが必要です。.gitignore側ではartifacts/は safe scratch prefix として ignore 済みなので、パス選定自体は正しいです。問題は、#1137 が
scripts/agent-ops/materialize_cleanup_contract.pyを追加すると書いている点です。これを Bash で実行してファイルを書かせるなら、現在の safe scratch 例外の対象外です。Issue に次を追加すべきです。3. Codex parity は現状の配線では成立しない
Claude 側は
.claude/settings.jsonでlocal_main_branch_guardの後にworktree_scope_guardが走ります。 一方、Codex 側.codex/hooks.jsonは Bash にlocal_main_branch_guardを配線していますが、worktree_scope_guardは配線されていません。加えて
.codex/rules/default.rulesは directgit worktree,git branch,git checkout,git switch等を forbidden にしています。 つまり #1137 の「Claude/Codex reason_code parity」は、Codex に worktree cleanup 判定器を入れない限り実体を持ちません。最低限、Issue に以下を追加してください。
4.
git -C <worktree>をどう扱うかが曖昧PR #1130 cleanup の blocker に
git -C <worktree>がlocal_main_branch_guardでunparseable_branch_mutation扱いされたことが挙がっています。これは現行実装上、意図された挙動です。local_main_branch_guard.pyはgit -C,-c,--git-dir,--work-tree,--config-envを fail-closed global option にしています。一方、現行
post-merge-cleanupskill は worktree 削除前の確認にgit -C "<worktree_path>" ...を使う手順をまだ持っています。 #1137 ではこれを許可するのではなく、guard_preflight.py側が subprocess 配列で clean 判定し、agent にgit -Cを打たせない方針に寄せるべきです。Git 公式仕様上、
git worktree removeは clean worktree だけを削除でき、dirty/submodule 付き worktree は--forceが必要です。したがって、guard がgit status --porcelain=v1 -zで clean を検証してから exactgit worktree remove <path>のみ許可する設計は正しいです。([Git]1) (Git)5. recovery deadlock の解き方が未定義
local_main_branch_guardは default branch への recovery、つまりgit switch main相当を allow します。 しかしworktree_scope_guardは active issue worktree がある状態で cwd が expected worktree 外だと mutation を block します。 これが #1137 の deadlock 本体です。AC7 は「root drift + active worktree mismatch の場合、recovery command を提示するだけで mutation しない」としていますが、これは hook の allow/block 仕様としては不十分です。次を決める必要があります。
推奨は B です。自動 recovery mutation はしない。ただし stderr に raw command を出さず、
AGENT_GUARD_PREFLIGHT_V1.allowed_next_commandsへ構造化された recovery hint を返す。人間が明示承認した場合だけ既存 override 経路で復旧する。High severity
command_hashの canonicalization が未定義V3 schema に
command_hashを入れるのはよいですが、何を hash するか未定義です。raw shell string を hash すると、quote 差分、相対パス、symlink、末尾 space で不安定になります。推奨仕様:
{ "argv": ["git", "worktree", "remove", "<realpath>"], "project_root": "<realpath>", "worktree_path": "<realpath>", "branch_name": "issue-123-slug", "require_clean": true }これを
json.dumps(..., sort_keys=True, separators=(",", ":"))した UTF-8 bytes の SHA-256 にする。git branch -d <branch>も同じ形式で別 hash を持たせる。exact argv の判定はshlex.split()後の argv に対して行う。cleanup stderr だけでなく arbitration stderr も 10 行以内に統一すべき
現行 cleanup block は 10 行以内・raw path/command を出さない設計です。 ただし通常の worktree block は expected worktree と actual cwd を stderr に出します。 #1137 の AC9 は「raw command / raw env / secret-like path を出さない」としているため、
GUARD_ARBITRATION_DECISION_V1用の出力は cleanup block と同水準に寄せるべきです。既存の
is_gh_mutation_command()は docstring と実装がズレている現行
evaluate()はis_github_issue_mutation_command()とis_github_remote_ops_command()を先に allow してからis_gh_mutation_command()に落とすので、実行経路としては概ね成立しています。 ただしis_gh_mutation_command()自体の docstring は remote ops / issue mutation を除外すると書きつつ、実装は readonly 以外を mutation 扱いにしています。 #1137 で reason_code parity を追加するなら、この種の「単体関数 contract と evaluate ordering のズレ」はテスト対象に入れるべきです。配布物・artifact 実装面の確認
PR #1130 は cleanup guard の PR ではなく、assist_player playtest evidence の PR です。差分では GitHub Actions の
actions/upload-artifact@v7を使ってplaytest-evidence-provenance.jsonを artifact として出し、bundle build 後にしか分からないartifact-url/artifact-digestを bundle 外へ分離する構成になっています。この方向は GitHub Actions の現行
upload-artifactREADME と整合します。公式 README はartifact-urlとartifact-digestを outputs として説明しており、artifact URL は artifact/run/repository が消えるか期限切れになるまで有効とされています。([GitHub]3) また retention-days は 1〜90 の範囲で指定可能です。(GitHub)ただし、#1137 の cleanup contract は 配布 artifact ではなく local scratch contract です。PR #1130 の「bundle に後段 provenance を混ぜない」設計は参考にできますが、
artifacts/agent-ops/cleanup_contract.jsonは upload-artifact 対象にしてはいけません。gitignored local-only、期限付き、raw path/secret-like path 非表示、実行後削除または invalidation が正しい扱いです。Issue #1137 に追記すべき具体 AC
このまま実装へ進めるより、Issue 本文に以下を追加してから着手するのが安全です。
実装方針
推奨は、
guard_preflight.pyを単なる CLI にせず、両 guard から import できる判定コアにすることです。ただし現 Issue の Allowed Paths には shared library 用ファイルがありません。scripts/agent-ops/guard_preflight.pyとmaterialize_cleanup_contract.pyだけに閉じるとロジック重複が起きます。Allowed Paths に以下を足すか、既存 guard 内に最小 validator を置く判断が必要です。これを追加しないなら、V3 schema validation と command_hash canonicalization が
materialize_cleanup_contract.pyとworktree_scope_guard.pyに二重実装されます。guard 系で二重実装は、今回のような deadlock 再発の温床です。最終判定
Issue #1137 は実装してよいが、現状の Acceptance Criteria では不十分です。 特に V3 contract の読み込み優先順位、materialize 実行経路、Codex 配線、recovery deadlock の allow/block 方針を明文化しないまま PR 化すると、レビューでは block すべきです。
squne121 commentedon Jun 22, 2026
Refinement Loop: Approved
issue-refinement-loopを完了し、Issue #1137 は実装着手可能(impl_ready)と判定した。anchor comment(OWNER レビュー)の指摘を本文へ反映し、決定論的レビューと contract review preflight の双方を通過した。反映した OWNER feedback(anchor: #issuecomment-4767859636)
着手前に repo の ground truth を実コマンドで検証した結果、anchor の主要主張はいずれも現状コードと一致していた(stale ではない)。これを踏まえて本文を次のとおり強化した。
worktree_scope_guard.pyは現状POST_MERGE_CLEANUP_REQUEST_V2のみ検証(L1500–1539、expires_at/command_hashなし)。V3 primary 検証・期限切れ block・hash 不一致 block を AC4/AC5 として明文化。chmod 0600を満たすことを AC2 + Design Decisions に明記。sort_keys)の SHA-256 とし、共有 validatorscripts/agent-ops/cleanup_contract_v3.pyに集約(二重実装回避)。AC3。root_drift_active_worktree_mismatch+ 構造化 recovery hint を返す。AC6。.codex/hooks.jsonは現状worktree_scope_guard未配線。同一判定コア配線・default.rulesの guarded route 化・SHARED_CLEANUP_REASON_CODESparity を AC7/AC9 に追加。post-merge-cleanupskill の agent 直接git -Cclean 判定を削除しguard_preflight.pyへ集約。AC8。ground truth 補正(誤前提の除去)
guard_preflight.py/materialize_cleanup_contract.py/cleanup_contract_v3.pyは未実装(scripts/agent-ops/ディレクトリ自体が不在)。新規作成として AC 化。worktree_scope_guard.py(branch_force_delete_denied, L1381/L1799)に既存。旧 AC が参照していたlocal_main_branch_guard.py側のbranch_delete_force_deniedは存在しないため、VC ターゲットを実在箇所に補正。tests/codex/test_local_main_branch_guard.py/.claude/hooks/tests/test_worktree_scope_guard.pyは既存(新規作成ではなく拡張)。検証結果(決定論的)
review-issue(check_issue_contract.py): approve — C1–C11 全 pass。issue-contract-review(run_contract_review_once.py --mode execute): go — readiness / blockers / product_spec / vc_preflight 全 pass。expected_fail(baseline-fail)/decision: go、human_judgment/unexpected_passゼロ。新規ファイルはtest -f、既存ファイルはrg <token>(exit 1)で gate allowlist 互換に統一。repair_issue_contract.py(dry-run):changed: false(追加修復なし)。Contract Snapshot
次アクション
impl-review-loopで実装に進める(contract review go・baseline VC fail を確認済み)。実装は隔離 worktree / Draft PR 既定、Allowed Paths 内に限定する。fix(#1137): runtime _decide_bash の cleanup 分岐にも root_drift gate を適用
fix(#1137): OWNER review #4778110602 の 10 Blocker を反映
fix(#1137): codex execpolicy matrix の invocation を公式仕様に修正
fix(#1137): codex execpolicy 非対応 CLI を loud-skip で graceful 処理
squne121 commentedon Aug 12, 2026
disposition 確認: KEEP(既に completed close 済み・executor-only reframe 済み)
#1782 の OWNER 敵対的レビュー(https://github.com/squne121/loop-protocol/issues/1782#issuecomment-5266277591)で、本 Issue は「KEEP して executor-only に reframe(cleanup_exec 自身の PR merged/head/issue/worktree/clean-state validation は有用だが Hook allowlist・nonce/TTL/hash contract 等は撤去候補)」と評価された。
本 Issue は既に CLOSED / COMPLETED(PR マージ済み)であり、実装済みスコープは単一
cleanup_execexecutor への認可境界集約・POST_MERGE_CLEANUP_REQUEST_V3の one-shot 化・実 PreToolUse hook 経路での allow 検証であった。これはレビューが求める executor-only reframe と整合しているため、追加の本文変更・再オープンは行わない。