Skip to content

実装: guard arbitration preflight と cleanup contract delivery を機械化する (agent-ops) #1137

Closed

Description

@squne121

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

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/artifacts contract へ 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 対象。

  1. 認可境界 = 単一 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 は bare git worktree remove / git branch -d を直接実行しない(guard が deny)。materialize で発行する V3 contract は defense-in-depth であり single source of authorization ではない。
  2. 実 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 を構築)で行う。
  3. 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 を必須テスト化。
  4. 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)。
  5. 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 引数を実際に使用する。
  6. Codex guarded route の成立: .codex/rules/default.rules の broad git worktree / git branch rule を分割する。exact git worktree remove <one-path> = prompt、add/move/lock/unlock/prune/repair/--force = forbidden。git branch の broad allow を廃し read-only は --show-current / --list を個別 allow、exact git 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」と定義する。
  7. 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 を検査。
  8. 共有 monotonic deadline: 全 guard 判定で共有する monotonic deadline を導入し、個別 subprocess timeout を残時間以下に、外側 hook timeout を worst-case 合計より大きくする。timeout は共通 reason code に正規化。slow git / locked index の fault-injection test を追加。
  9. 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 で直列化する。
  10. stale 手順の集約: post-merge-cleanup SKILL から 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_exceeded

In Scope

  • scripts/agent-ops/cleanup_exec.py 新規(認可境界・単一 executor)
  • scripts/agent-ops/worktree_catalog.py 新規(--porcelain -z catalog 共有モジュール)
  • 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 経由・stale git -C 削除)
  • .codex/hooks.json / .codex/rules/default.rules の Codex 側配線(broad rule 分割・同一判定コア)
  • .github/workflows/ に codex execpolicy check job 追加

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 統合テストで、active LOOP_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 の broad git worktree / git branch rule を分割し、exact git 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_CODES parity を 実 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.py

Allowed Paths

  • scripts/agent-ops/cleanup_exec.py
  • scripts/agent-ops/worktree_catalog.py
  • scripts/agent-ops/cleanup_contract_v3.py
  • scripts/agent-ops/guard_preflight.py
  • scripts/agent-ops/materialize_cleanup_contract.py
  • scripts/agent-guards/local_main_branch_guard.py
  • .claude/hooks/worktree_scope_guard.py
  • .claude/hooks/tests/test_worktree_scope_guard.py
  • tests/codex/test_local_main_branch_guard.py
  • .claude/skills/post-merge-cleanup/SKILL.md
  • .codex/hooks.json
  • .codex/rules/default.rules
  • .github/workflows/ci.yml
  • artifacts/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

  1. added
    phase/implementation
    agent/implementer
    enhancement
    on Jun 22, 2026
  2. squne121 commented on Jun 22, 2026

    @squne121
    OwnerAuthor

    結論

    #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 に以下を明記すべきです。

    worktree_scope_guard.py は POST_MERGE_CLEANUP_REQUEST_V3 を primary として検証する。
    legacy V2 は移行互換として残す場合でも、V3 path が存在する場合は V3 を優先する。
    V3 は expires_at 未設定・期限切れ・command_hash 不一致・schema 不一致を block する。
    

    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 に次を追加すべきです。

    materialize_cleanup_contract.py は hook 配下で実行可能であることをテストする。
    - active issue worktree が存在する
    - cwd は local main root
    - branch は default
    - 出力先は artifacts/agent-ops/cleanup_contract.json
    この条件で PreToolUse guard が block しないこと。
    

    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 は direct git worktree, git branch, git checkout, git switch 等を forbidden にしています。 つまり #1137 の「Claude/Codex reason_code parity」は、Codex に worktree cleanup 判定器を入れない限り実体を持ちません。

    最低限、Issue に以下を追加してください。

    Codex 側にも worktree_scope_guard 相当の判定を通す。
    .codex/hooks.json に Bash cleanup 判定を追加するか、Codex 専用 wrapper から同一 Python 判定関数を呼ぶ。
    .codex/rules/default.rules は static allow ではなく、exact cleanup command を prompt/guarded route に通す。
    

    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-cleanup skill は 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 を検証してから exact git 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 仕様としては不十分です。次を決める必要があります。

    root drift + active worktree mismatch のとき:
    A. hook は git switch main を allow するのか
    B. hook は block し、人間に hook override 手順を提示するのか
    C. guard_preflight.py は advisory だけでなく、後続 guard に short-circuit signal を渡すのか
    

    推奨は 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-artifact README と整合します。公式 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 本文に以下を追加してから着手するのが安全です。

    ### AC追加: V3 contract validation
    
    - `POST_MERGE_CLEANUP_REQUEST_V3` を primary schema とする。
    - `schema != POST_MERGE_CLEANUP_REQUEST_V3` は block。ただし legacy V2 互換を残す場合は明示テストを追加する。
    - `expires_at <= now` は `cleanup_contract_expired` で block。
    - `command_hash` は canonical argv JSON の SHA-256 とし、raw shell string hash は使わない。
    - hash mismatch は `cleanup_command_hash_mismatch` で block。
    
    ### AC追加: materialize route
    
    - `scripts/agent-ops/materialize_cleanup_contract.py` は active issue worktree が存在する local main root から実行しても block されない。
    - 書き込み先は `artifacts/agent-ops/cleanup_contract.json` のみ。
    - parent directory に symlink component がある場合は fail-closed。
    - atomic write: temp file + fsync + os.replace。
    - chmod 0600 best-effort。ただし Windows/WSL 差分は警告に留める。
    
    ### AC追加: Codex parity
    
    - `.codex/hooks.json` から同一 Python 判定関数を呼ぶ。
    - `.codex/rules/default.rules` は cleanup exact command を static allow しない。guarded/prompt route に限定する。
    - Claude/Codex の fixture table は同じ reason_code を返す:
      - no_cleanup_contract
      - cleanup_contract_expired
      - cleanup_command_hash_mismatch
      - worktree_path_mismatch
      - worktree_dirty
      - branch_force_delete_denied
      - root_drift_active_worktree_mismatch
    
    ### AC追加: stale cleanup procedure removal
    
    - `.claude/skills/post-merge-cleanup/SKILL.md` から agent が直接 `git -C <worktree>` で clean 判定する手順を削除する。
    - clean 判定は `guard_preflight.py` または guard 内部 subprocess 配列実行に集約する。

    実装方針

    推奨は、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 を置く判断が必要です。

    scripts/agent-ops/cleanup_contract_v3.py
    

    これを追加しないなら、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 すべきです。

  3. squne121 commented on Jun 22, 2026

    @squne121
    OwnerAuthor

    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 ではない)。これを踏まえて本文を次のとおり強化した。

    • V3 読込優先順位: worktree_scope_guard.py は現状 POST_MERGE_CLEANUP_REQUEST_V2 のみ検証(L1500–1539、expires_at / command_hash なし)。V3 primary 検証・期限切れ block・hash 不一致 block を AC4/AC5 として明文化。
    • materialize 実行経路: active issue worktree あり・local main root・branch=default から hook に block されず実行でき、atomic write / symlink fail-closed / chmod 0600 を満たすことを AC2 + Design Decisions に明記。
    • command_hash canonicalization: raw shell string ではなく canonical argv JSON(sort_keys)の SHA-256 とし、共有 validator scripts/agent-ops/cleanup_contract_v3.py に集約(二重実装回避)。AC3。
    • recovery deadlock 方針 B: 自動 mutation せず root_drift_active_worktree_mismatch + 構造化 recovery hint を返す。AC6。
    • Codex parity: .codex/hooks.json は現状 worktree_scope_guard 未配線。同一判定コア配線・default.rules の guarded route 化・SHARED_CLEANUP_REASON_CODES parity を AC7/AC9 に追加。
    • stale 手順集約: post-merge-cleanup skill の agent 直接 git -C clean 判定を削除し guard_preflight.py へ集約。AC8。

    ground truth 補正(誤前提の除去)

    • guard_preflight.py / materialize_cleanup_contract.py / cleanup_contract_v3.py は未実装(scripts/agent-ops/ ディレクトリ自体が不在)。新規作成として AC 化。
    • force branch delete deny は 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。
    • VC preflight: AC1–AC9 の 9 件すべて 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

    CONTRACT_REVIEW_RESULT_V1:
      status: go
      generated_by: issue-contract-review
      generated_at: "2026-06-22T22:27:52Z"
      issue_url: "https://github.com/squne121/loop-protocol/issues/1137"
      body_sha256: "sha256:3775017f28d56f15b4effd34a57e30383a56fa1c806bc6ac05cc64942dd461f3"
      source: all_checks_pass
      checks:
        readiness: go
        blockers: pass
        product_spec: pass
        vc_preflight: pass
      vc_preflight:
        total: 9
        failed_as_expected: 9
        human_judgment: 0
        passed_unexpectedly: 0
    LOOP_HANDOFF_RESULT_V1:
      status: impl_ready
      routing_action: run_impl_review_loop
      contract_review:
        status: go
        gate_result: fresh_go
        latest_comment_url: "https://github.com/squne121/loop-protocol/issues/1137"
        generated_at: "2026-06-22T22:27:52Z"
        body_sha256: "sha256:3775017f28d56f15b4effd34a57e30383a56fa1c806bc6ac05cc64942dd461f3"
      metadata:
        title_prefix_ready: true
        phase_label_ready: true
      auto_fixes:
        result: auto_fixed
        required: []
        skipped: []
      blockers: []
      permissions:
        unavailable: []
      generated_at: "2026-06-22T22:27:52Z"

    次アクション

    impl-review-loop で実装に進める(contract review go・baseline VC fail を確認済み)。実装は隔離 worktree / Draft PR 既定、Allowed Paths 内に限定する。

  4. added 4 commits that reference this issue on Jun 22, 2026
  5. squne121 commented on Aug 12, 2026

    @squne121
    OwnerAuthor

    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_exec executor への認可境界集約・POST_MERGE_CLEANUP_REQUEST_V3 の one-shot 化・実 PreToolUse hook 経路での allow 検証であった。これはレビューが求める executor-only reframe と整合しているため、追加の本文変更・再オープンは行わない。

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    agent/implementerenhancementphase/implementation

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions