Skip to content

実装: Claude Code / Codex CLI で local root checkout のブランチ変更をブロックする #1014

Closed

Description

@squne121

Machine-Readable Contract

contract_schema_version: v1
issue_kind: implementation
goal_ref: "ローカルリポジトリ root checkout は default branch に固定し、issue 作業は linked issue worktree のみで行う"
change_kind: mixed
risk_class: agent_ops_guard
affected_runtimes:
  - claude_code
  - codex_cli
primary_failure_mode:
  - local_root_branch_drift
  - no_matching_worktree_block_churn
  - agent_context_pollution
  - repeated_permission_failure
non_goals:
  - remote branch protection の変更
  - worktree_scope_guard の置換
  - local root での通常実装作業許可
  - hooks を唯一の security boundary とみなすこと
  - Codex PreToolUse / PermissionRequest hook を完全な enforcement boundary とみなすこと
  - Codex hook の実行順序に依存すること
  - branch drift guard を general mutation guard に拡張すること

Parent Issue

なし(standalone 実装 Issue)

Parent Goal Ref

ローカルリポジトリ root checkout は default branch に固定し、issue 作業は linked issue worktree のみで行う

Current Validated Scope

  • scripts/agent-guards/local_main_branch_guard.py
  • .claude/hooks/local_main_branch_guard.sh
  • .claude/hooks/tests/test_local_main_branch_guard.py
  • .claude/settings.json
  • docs/dev/hook-boundaries.md
  • scripts/check_hook_boundaries.py
  • scripts/check_local_main_branch_state.py
  • scripts/check_codex_agent_config.py
  • .codex/hooks/local_main_branch_guard.sh
  • .codex/hooks.json
  • tests/codex/test_local_main_branch_guard.py
  • .codex/rules/default.rules

Remaining Parent Gaps

なし(standalone 実装 Issue)

Outcome

ローカルリポジトリ root checkout が常に main / default branch に固定される。Claude Code・Codex CLI の双方で local_main_branch_guard が機能し、worktree_scope_guard より前段で root checkout の branch drift を即時ブロックする。drift 後に繰り返されていた無駄な token 消費・原因誤認・人間手戻りが防止される。

In Scope

  • scripts/agent-guards/local_main_branch_guard.py の新規実装(共有ロジック)
  • .claude/hooks/local_main_branch_guard.sh の新規実装(Claude Code wrapper)
  • .codex/hooks/local_main_branch_guard.sh の新規実装(Codex CLI wrapper)
  • .claude/settings.json の PreToolUse hook 順序更新(secret → local_main → worktree)
  • .codex/hooks.json への hook entry 追加(event → matcher → hooks array 形式)
  • scripts/check_hook_boundaries.py による hook 順序・manifest drift 検証
  • scripts/check_codex_agent_config.py による Codex config 整合性検証
  • scripts/check_local_main_branch_state.py による startup preflight の新規実装
  • .claude/hooks/tests/test_local_main_branch_guard.py の新規テスト
  • tests/codex/test_local_main_branch_guard.py
  • .codex/rules/default.rules の新規テスト
  • docs/dev/hook-boundaries.md への local_main_branch_guard 追記

Out of Scope

  • remote branch protection の変更
  • worktree_scope_guard の既存ロジック変更
  • local root での通常実装作業の許可
  • Codex PreToolUse / PermissionRequest hook を完全な enforcement boundary とみなす設計
  • Codex hook の実行順序への依存
  • branch drift guard の general mutation guard への拡張

背景

AI エージェント作業中に、ローカルリポジトリ root checkout が main / default branch から issue-* ブランチへ変わった状態で作業が継続された。

その結果、既存の worktree_scope_guard が current branch から active issue を推定し、対応する .claude/worktrees/issue-<N>-* が存在しないため expected_worktree: <no-matching-worktree> として fail-closed した。
このブロック自体は worktree guard の責務として妥当だが、発火タイミングが遅いため、エージェントはその後も gh issue view / uv run / gh issue edit 等を試し、無駄な token 消費・SubAgent 起動・原因誤認・人間への手戻りを発生させた。

問題

現在の guard 層は「active issue worktree 外で mutation しようとした瞬間」は止めるが、次を事前に防げない。

  • local root checkout が main / default branch から issue-* / worktree-issue-* / PR checkout branch へ drift する
  • drift 後に worktree_scope_guard が <no-matching-worktree> で広範囲に block する
  • agent が block 原因を workflow 誤りではなく hook 設計不良・scope_signal_guard 問題として誤読する
  • Claude Code と Codex CLI の hook / config 境界が非対称になる

方針

worktree_scope_guard の前段に、local root checkout の branch drift を検出・ブロックする guard を追加する。

追加する guard

  • 共有本体: scripts/agent-guards/local_main_branch_guard.py
  • Claude Code wrapper: .claude/hooks/local_main_branch_guard.sh
  • Codex CLI wrapper: .codex/hooks/local_main_branch_guard.sh
  • テスト: .claude/hooks/tests/test_local_main_branch_guard.py / tests/codex/test_local_main_branch_guard.py
  • config / docs: .claude/settings.json / .codex/config.toml / docs/dev/hook-boundaries.md / scripts/check_hook_boundaries.py / scripts/check_codex_agent_config.py

Guard 判定仕様

Local root context

以下をすべて満たす場合だけ、この guard の enforcement 対象とする。

local_root_context:
  cwd_realpath_equals_project_root: true
  current_worktree_is_primary_repo_root: true
  cwd_not_under_dot_claude_worktrees: true

project_root 解決は git worktree list --porcelain -z で primary worktree を catalog から特定する。git rev-parse --show-toplevel 単体は linked worktree 内で main root を返すため使用しない。linked worktree 内では本 guard は allow し、既存の worktree_scope_guard に任せる。解決優先順位:

  1. CLAUDE_PROJECT_DIR
  2. Codex hook input の cwd から上位探索
  3. git worktree list --porcelain -z の primary worktree path
  4. script path anchor

Default branch 解決

default branch は以下の順で解決する。

  1. LOOP_DEFAULT_BRANCH
  2. git symbolic-ref --short refs/remotes/origin/HEAD
  3. main
  4. master
  5. trunk

Block 対象コマンド

local root context で、以下のように root checkout の branch を default branch 以外へ変更しうる Bash を block する。

blocked_patterns:
  - git switch <non_default_branch>
  - git switch -c <branch>
  - git switch -C <branch>
  - git switch --detach [<start-point>]
  - git switch --orphan <branch>
  - git switch --guess <remote-branch-like>
  - git checkout <non_default_branch>
  - git checkout -b <branch>
  - git checkout -B <branch>
  - git checkout --orphan <branch>
  - git checkout --detach <commit-or-branch>
  - git checkout --ignore-other-worktrees <branch>
  - git branch -m <branch>
  - git branch -M <branch>
  - gh pr checkout <number_or_branch>
  - hub pr checkout <number_or_branch>
  - bash -lc "git switch ..."
  - sh -c "git checkout ..."

local root context で branch mutation grammar を完全に証明できない compound command は fail-closed にする(unparseable_branch_mutation)。

以下は allow する。

allowed_patterns:
  - git status
  - git branch --show-current
  - git rev-parse --abbrev-ref HEAD
  - git worktree list
  - git fetch
  - git switch <default_branch>
  - git checkout <default_branch>
  - git checkout -- <path>
  - git checkout HEAD -- <path>
  - git checkout --pathspec-from-file=<file>
  - git checkout -p -- <path>
  - git restore <path>

注意: git checkout -- <path> / git checkout HEAD -- <path> / git checkout --pathspec-from-file / git checkout -p は branch switch ではないため、この guard では block しない。ファイル mutation の可否は既存の worktree_scope_guard に任せる。

既に drift 済みの場合

local root checkout がすでに default branch 以外の場合は、以下の allowlist のみ許可する。

allowed_when_already_drifted:
  git:
    - git status
    - git branch --show-current
    - git rev-parse --abbrev-ref HEAD
    - git worktree list
    - git switch <default_branch>
    - git checkout <default_branch>
  gh:
    - gh issue view <number>
    - gh issue list
    - gh pr view <number>
    - gh pr list
    - gh pr status
blocked_when_already_drifted:
  - gh issue edit|comment|close|reopen|delete|lock|unlock
  - gh pr checkout|edit|comment|merge|close|reopen|ready|review|update-branch
  - hub pr checkout
  - uv run / pnpm / npm / test / build commands from drifted root

それ以外の branch mutation は block する。

Manual override

緊急時のみ、CLI 起動前に人間が明示した環境変数で override できる。

LOOP_ALLOW_LOCAL_ROOT_BRANCH_CHANGE=1
LOOP_LOCAL_ROOT_BRANCH_CHANGE_REASON="manual recovery: ..."

hook 対象 Bash コマンド内の inline env 指定は override として扱わない。
例: LOOP_ALLOW_LOCAL_ROOT_BRANCH_CHANGE=1 git switch issue-123-x は block する(hook process env のみ有効)。

block stderr には override reason の全文を出さず、manual_override: accepted か manual_override: missing_reason 程度にとどめる。branch 名は raw 出力せず target_branch_kind に寄せる。

Claude Code integration

.claude/settings.json の PreToolUse に local_main_branch_guard.sh を追加する。

順序は以下とする。

  1. secret_boundary_guard
  2. local_main_branch_guard
  3. worktree_scope_guard
  4. その他 guard

理由: branch drift は worktree scope violation より前に、より明確な reason で止めるべきである。

block 時は exit 2。stderr は最大 10 行、raw command / raw env / secret-like value を出さない。

例:

[local_main_branch_guard] blocked: local root checkout must stay on default branch
reason_code: local_root_branch_drift
current_branch: main
target_branch_kind: issue_branch
recovery: create/enter linked issue worktree, or switch only to default branch

Codex CLI integration

Codex 側にも同一判定を入れる。このリポジトリの Codex hooks は .codex/hooks.json(JSON)に定義する。.codex/config.toml には hooks を含めない。.codex/hooks.json に以下を追加する。

{
  "PreToolUse": [
    {
      "matcher": "Bash",
      "hooks": [
        {
          "type": "command",
          "command": "bash \"$(git rev-parse --show-toplevel)/.codex/hooks/local_main_branch_guard.sh\"",
          "timeout": 10,
          "statusMessage": "Checking local root branch policy"
        }
      ]
    }
  ],
  "PermissionRequest": [
    {
      "matcher": "Bash",
      "hooks": [
        {
          "type": "command",
          "command": "bash \"$(git rev-parse --show-toplevel)/.codex/hooks/local_main_branch_guard.sh\"",
          "timeout": 10,
          "statusMessage": "Checking local root branch policy"
        }
      ]
    }
  ]
}

Codex の PreToolUse は全 shell 経路を完全捕捉する security boundary ではないため、追加で起動前 preflight を用意する。

  • scripts/check_local_main_branch_state.py
  • scripts/check_codex_agent_config.py に hook 有効化確認を追加
  • Codex セッション開始プロンプト / rules に「preflight 失敗時は実装作業を開始しない」を明記

check_codex_agent_config.py は以下の条件で fail する。

  • command handler が .codex/hooks.json の hooks.<Event>[] → hooks[] ネストの外側に定義されている
  • .codex/hooks.json に startup preflight が記載されていない
  • startup preflight が Codex rules / session prompt に記載されていない

共有スクリプトの出力仕様

hook 実行時:

allow:
  exit_code: 0
  stdout: ""
  stderr: ""

block:
  exit_code: 2
  stdout: ""
  stderr: bounded_structural_message

self-test / CLI 実行時:

LOCAL_MAIN_BRANCH_GUARD_RESULT_V1:
  status: allow | block
  reason_code:
    - not_local_root_context
    - readonly_command
    - recovery_to_default_branch
    - local_root_branch_drift
    - already_drifted_root
    - unparseable_branch_mutation
    - inline_env_override_not_allowed
  current_branch: string | null
  target_branch: string | null
  target_branch_kind: default | issue | worktree_issue | pr | unknown | null
  hook_flavor: claude | codex | cli

Acceptance Criteria

  • AC1: Claude Code blocks root branch drift。一時 repo で cwd=repo root、current branch=main の状態で git switch issue-981-* / git checkout issue-981-* / git checkout -b issue-981-* / gh pr checkout 988 / bash -lc 'git switch issue-981-*' を block する。
  • AC2: Claude Code allows recovery to default branch。local root が issue-981-* になっていても git switch main / git checkout main / git status / git branch --show-current は allow する。
  • AC3: issue worktree 内ではこの guard は block しない。cwd が .claude/worktrees/issue-981-* の場合、branch command を原則 allow し既存の worktree_scope_guard に委譲する。
  • AC4: git checkout -- <path> を branch switch と誤判定しない。git checkout -- README.md / git checkout HEAD -- README.md / git restore README.md は local branch drift としては block しない。
  • AC5: bounded stderr / no leak。block stderr は最大 10 行。raw command 全文 / raw tool input JSON / env dump / token-secret / worktree catalog 全体を含めない。
  • AC6: hook order is enforced。secret_boundary_guard が local_main_branch_guard より前、local_main_branch_guard が worktree_scope_guard より前であることを test で検証する。
  • AC7: hook-boundaries manifest drift check。docs/dev/hook-boundaries.md に local_main_branch_guard を追加し、scripts/check_hook_boundaries.py が drift なしで pass する。
  • AC8: Codex parity。Codex hook input fixture で git switch issue-* が deny、git switch main が allow、PermissionRequest 経由でも同判定になる。
  • AC9: startup preflight。uv run python3 scripts/check_local_main_branch_state.py --json が local root が default branch 以外の場合 non-zero で終了する。
  • AC10: branch mutation grammar is complete。Block: git switch -C <branch> / git switch --detach / git switch --orphan <branch> / git switch --guess <remote> / git checkout -B <branch> / git checkout --detach / git checkout --orphan <branch> / git checkout --ignore-other-worktrees <branch> / git branch -m <branch> / git branch -M <branch>。
  • AC11: git checkout path restore forms are not overblocked。git checkout HEAD -- README.md / git checkout --pathspec-from-file=<file> / git checkout -p -- README.md は local branch drift として block しない。
  • AC12: already-drifted state uses explicit allowlist。mutating gh issue edit/comment/close および gh pr checkout/edit/comment/merge/update-branch は already-drifted root から block される。allowlist 外の gh コマンドもデフォルト block。
  • AC13: project root / primary worktree detection uses git worktree list --porcelain -z catalog。git rev-parse --show-toplevel 単体に依存せず、linked worktree 内で primary root を誤判定しない。
  • AC14: default branch resolution is tested against shared fixtures。LOOP_DEFAULT_BRANCH 優先 / origin/HEAD fallback / main fallback の順序が既存 local main scratch guard と同一 fixtures で検証される。
  • AC15: inline env override in Bash command is blocked。LOOP_ALLOW_LOCAL_ROOT_BRANCH_CHANGE=1 git switch issue-* は block。hook process env に両変数が設定されている場合のみ allow。
  • AC16: unparseable compound shell commands are fail-closed。cd repo && git checkout issue-* / command git switch issue-* / env FOO=bar git switch issue-* 等、branch mutation が証明できない compound command は unparseable_branch_mutation で block する。
  • AC17: Codex startup preflight is mandatory。scripts/check_codex_agent_config.py が startup preflight 未記載・handler 形式不正・hooks.json 二重定義のいずれかで fail する。

Verification Commands

# AC1
uv run pytest .claude/hooks/tests/test_local_main_branch_guard.py -q
# AC2
uv run pytest .claude/hooks/tests/test_local_main_branch_guard.py -q
# AC3
uv run pytest .claude/hooks/tests/test_local_main_branch_guard.py -q
# AC4
uv run pytest .claude/hooks/tests/test_local_main_branch_guard.py -q
# AC5
uv run pytest .claude/hooks/tests/test_local_main_branch_guard.py -q
# AC6
uv run pytest .claude/hooks/tests/test_local_main_branch_guard.py -q
# AC7
uv run pytest .claude/hooks/tests/test_local_main_branch_guard.py -q
# AC8
uv run pytest tests/codex/test_local_main_branch_guard.py -q
# AC9
uv run pytest .claude/hooks/tests/test_local_main_branch_guard.py -q
# AC10
uv run pytest .claude/hooks/tests/test_local_main_branch_guard.py -q
# AC11
uv run pytest .claude/hooks/tests/test_local_main_branch_guard.py -q
# AC12
uv run pytest .claude/hooks/tests/test_local_main_branch_guard.py -q
# AC13
uv run pytest .claude/hooks/tests/test_local_main_branch_guard.py -q
# AC14
uv run pytest .claude/hooks/tests/test_local_main_branch_guard.py -q
# AC15
uv run pytest .claude/hooks/tests/test_local_main_branch_guard.py -q
# AC16
uv run pytest .claude/hooks/tests/test_local_main_branch_guard.py -q
# AC17
uv run pytest tests/codex/test_local_main_branch_guard.py -q

Allowed Paths

  • scripts/agent-guards/local_main_branch_guard.py
  • .claude/hooks/local_main_branch_guard.sh
  • .claude/hooks/tests/test_local_main_branch_guard.py
  • .claude/settings.json
  • docs/dev/hook-boundaries.md
  • scripts/check_hook_boundaries.py
  • scripts/check_local_main_branch_state.py
  • scripts/check_codex_agent_config.py
  • .codex/hooks/local_main_branch_guard.sh
  • .codex/hooks.json
  • tests/codex/test_local_main_branch_guard.py
  • .codex/rules/default.rules

Runtime Verification Applicability

decision: not_applicable
reason: "hook / script 追加の範囲で完結し、interactive runtime 証跡を成功条件に含まない。ただし temp repo を使った integration fixture(一時 git repo 作成・root に main ブランチ設定・guard 実行・block/allow 判定)は AC1–AC16 テストの一部として実装する"

Stop Conditions

  • Allowed Paths 外の変更が必要と判明した場合
  • worktree_scope_guard の既存ロジック変更が必要になった場合
  • Codex CLI の hook 仕様(.codex/hooks.json 形式)が公式ドキュメントと異なることが判明した場合
  • git worktree list --porcelain -z が primary worktree を期待形式で返さない環境が判明した場合
  • Claude Code の hook 実行順序が .claude/settings.json と docs/dev/hook-boundaries.md で整合不可能な場合
  • check_hook_boundaries.py または check_codex_agent_config.py の既存テスト前提を破壊する変更が必要になった場合

Required Skills

  • Python / shell scripting
  • Claude Code hooks / PreToolUse
  • git worktree

Delivery Rule

  • 1 Issue = 1 PR で完了する。
  • Draft PR を既定とする。

Activity

  1. added
    enhancement
    workflow
    area/ai-ops
    on Jun 19, 2026
  2. squne121 commented on Jun 19, 2026

    @squne121
    OwnerAuthor

    判定

    #1014 の問題設定は妥当です。local root checkout が main から issue-* 系へ drift した結果、既存 worktree_scope_guard が <no-matching-worktree> で fail-closed し、エージェントが原因を誤読して無駄な gh issue view / uv run / gh issue edit を繰り返した、という failure mode は Issue 本文と整合しています。#1014 自体にはコメントはありません。

    ただし、現状の #1014 は実装着手前に修正すべき blocker があります。特に Codex hook 設定例が公式仕様とずれており、このまま実装すると「Claude 側は効くが Codex 側は効かない/信頼されず実行されない/順序を誤認する」危険があります。

    関連Issue / PRから見た位置づけ

    #1014 は #960 / PR #971 の worktree_scope_guard を置換するものではなく、前段で root branch drift を早期に止める追加 guard です。PR #971 は active issue worktree 外の Write/Edit/MultiEdit と mutating Bash を fail-closed する hook で、project root 解決に git rev-parse --show-toplevel を使わず CLAUDE_PROJECT_DIR と script anchor を使う設計でした。ここは #1014 の root 解決仕様と衝突し得ます。

    #974 / PR #979 は local main checkout 上の .gitignore 対象 scratch 出力だけを限定許可する例外です。#1014 はこの例外と競合しない必要があります。特に「local root が default branch であること」は #979 の local main context 判定と同じ中核条件なので、default branch resolver を二重実装せず共通化すべきです。

    #970 / PR #989 は hook 順序と hook-boundaries.md の manifest drift 検出に関係します。PR #989 では secret_boundary_guard が worktree_scope_guard より前であること、manifest と settings の matcher が一致することを検証対象にしています。#1014 の「secret → local_main → worktree」の順序も、同じ manifest 検査に載せるべきです。

    gh pr checkout 988 が AC1 に入っている点も妥当です。PR #988 は head branch が issue-981-unit-taxonomy-types で、まさに local root が issue branch へ drift し得る形です。GitHub CLI 公式 manual でも gh pr checkout は PR を git checkout し、既定では head branch 名の local branch を使い、--detach や --force も持ちます。 ([GitHub CLI]1)

    Blocker

    B1. Codex hook 設定例が公式仕様と一致していない

    #1014 の Codex 例は次の形です。

    [[hooks.PreToolUse]]
    matcher = "Bash"
    command = ".codex/hooks/local_main_branch_guard.sh"

    これは Codex hooks の三層構造に合っていません。公式 docs では event → matcher group → hooks handler array の構造で、command は matcher group 直下ではなく handler 直下に置きます。また、複数 hook は同時起動されるため、Claude のような逐次順序を Codex 側に期待できません。project-local hooks は .codex/ layer が trust 済みでないと実行されず、同一 layer に hooks.json と config.toml の両方があると merge + warning になります。([OpenAI Developers]2)

    修正案はこうです。

    [features]
    hooks = true
    
    [[hooks.PreToolUse]]
    matcher = "Bash"
    
    [[hooks.PreToolUse.hooks]]
    type = "command"
    command = 'bash "$(git rev-parse --show-toplevel)/.codex/hooks/local_main_branch_guard.sh"'
    timeout = 10
    statusMessage = "Checking local root branch policy"
    
    [[hooks.PermissionRequest]]
    matcher = "Bash"
    
    [[hooks.PermissionRequest.hooks]]
    type = "command"
    command = 'bash "$(git rev-parse --show-toplevel)/.codex/hooks/local_main_branch_guard.sh"'
    timeout = 10
    statusMessage = "Checking local root branch policy"

    さらに AC8 は「Codex parity」だけでは弱いです。scripts/check_codex_agent_config.py で、config.toml の nested handler 形式、features.hooks != false、hooks.json との二重定義なし、project-local hook trust 前提の明記、command path が git root 基準であることまで検査対象にしてください。

    B2. Codex PreToolUse を enforcement boundary と誤認しない条件が弱い

    #1014 は「hooks を唯一の security boundary とみなさない」と書いていますが、AC 側ではまだ弱いです。Codex 公式 docs は、PreToolUse は Bash / apply_patch / MCP などを intercept できるが、完全な enforcement boundary ではなく、すべての shell call を捕捉するわけではない、と明記しています。PermissionRequest も「承認が必要なコマンド」の前にだけ走ります。([OpenAI Developers]2) ([OpenAI Developers]2)

    したがって、Codex 側は hook だけでなく scripts/check_local_main_branch_state.py --json を session startup preflight の必須 gate に格上げしてください。AC9 は「non-zero で終了する」だけでなく、「Codex セッション開始プロンプト / rules / check_codex_agent_config が preflight 実行を要求し、失敗時は実装作業を開始しない」まで含めるべきです。

    B3. git switch / git checkout の command grammar が不足している

    git switch は単なる branch switch だけではありません。-c / -C で作成して switch、--orphan で unborn branch、--detach で detached HEAD、--guess で remote branch から暗黙作成できます。#1014 の blocked patterns は git switch -c と --orphan までは入っていますが、-C、--detach、--guess、--discard-changes、--merge、--force-create 相当の扱いが曖昧です。([Git]3)

    git checkout はさらに危険です。公式 docs 上、branch switch と file restore の二つの mode があり、git checkout <tree-ish> -- <pathspec> や --pathspec-from-file は path restore、git checkout -b/-B/--orphan は branch 作成、--detach は detached HEAD です。#1014 は git checkout -- <path> を許可に入れていますが、git checkout HEAD -- README.md 以外に --pathspec-from-file、-p/--patch、-B、--detach、--ignore-other-worktrees の扱いをテスト化する必要があります。([Git]4) ([Git]4)

    追加すべき AC:

    - [ ] AC10: branch mutation grammar is complete.
      Block:
      - git switch -C <branch>
      - git switch --detach [<start-point>]
      - git switch --orphan <branch>
      - git switch --guess <remote-branch-like>
      - git checkout -B <branch>
      - git checkout --detach <commit-or-branch>
      - git checkout --orphan <branch>
      - git checkout --ignore-other-worktrees <branch>
      - git branch -m <branch>
      - git branch -M <branch>
      Allow as non-branch drift:
      - git checkout HEAD -- README.md
      - git checkout --pathspec-from-file=<file>
      - git checkout -p -- README.md

    B4. root 解決仕様が既存 guard と衝突し得る

    #1014 は project root 解決の優先順位に git rev-parse --show-toplevel を入れています。一方、PR #971 の worktree_scope_guard は、worktree isolation では git rev-parse --show-toplevel が main root を返すため使わない、という設計でした。ここを雑に実装すると、issue worktree 内なのに local root context と誤判定するか、逆に primary root を見逃す可能性があります。

    修正方針は、git rev-parse 単体ではなく git worktree list --porcelain -z を使って「primary worktree path」と「linked issue worktree path」を catalog から決めることです。Git の porcelain -z は machine parsing 用に NUL terminated 形式を提供しているため、既存 worktree_scope_guard と同じ catalog parser を共有するのが安全です。([Git]4)

    B5. 「既に drift 済みの場合の read-only Git / gh allow」が広すぎる

    #1014 の背景では、drift 後に gh issue view / uv run / gh issue edit 等を試して churn したことが問題です。ところが仕様では「read-only Git / gh command」を許可するとしか書いていません。gh issue edit は明らかに read-only ではありません。ここは allowlist にしてください。

    推奨:

    allowed_when_already_drifted:
      git:
        - git status
        - git branch --show-current
        - git rev-parse --abbrev-ref HEAD
        - git worktree list
        - git switch <default_branch>
        - git checkout <default_branch>
      gh:
        - gh issue view <number>
        - gh issue list ...
        - gh pr view <number>
        - gh pr list ...
        - gh pr status
    blocked_when_already_drifted:
      - gh issue edit|comment|close|reopen|delete|lock|unlock
      - gh pr checkout|edit|comment|merge|close|reopen|ready|review|update-branch
      - hub pr checkout
      - uv run / pnpm / npm / test/build commands from drifted root

    B6. manual override の検証条件が不足している

    「CLI 起動前に人間が明示した env だけ許可、inline env は不許可」という方針は正しいです。ただし実装上は、hook process の環境にある env と Bash command 文字列中の inline env を分けて扱う必要があります。Claude hook は stdin の tool_input.command と process env を両方見られます。exit 2 は PreToolUse / PermissionRequest を block できますが、exit 2 の場合 stdout JSON は無視されるため、構造化出力と stderr 方式を混ぜない方がよいです。([Claude API Docs]5)

    追加テスト:

    LOOP_ALLOW_LOCAL_ROOT_BRANCH_CHANGE=1 git switch issue-123-x
    # => block: inline_env_override_not_allowed
    
    env LOOP_ALLOW_LOCAL_ROOT_BRANCH_CHANGE=1 \
        LOOP_LOCAL_ROOT_BRANCH_CHANGE_REASON="manual recovery: ..." \
        claude-or-codex-session ...
    # => allow only if hook process env contains both values

    stderr には override reason の全文を出さず、manual_override: accepted か manual_override: missing_reason 程度にしてください。branch 名も raw 出力せず、target_branch_kind: issue | worktree_issue | pr | unknown に寄せる方が安全です。

    B7. Runtime Verification Applicability が弱い

    #1014 は runtime verification: not_applicable としていますが、これはアプリ runtime には正しい一方、hook 自体は operational runtime です。hook / script 追加は「実行時挙動が本体」なので、temp repo integration test と self-test は必須です。Issue 本文の verification commands は unit test 寄りなので、次を足してください。

    uv run python scripts/check_local_main_branch_state.py --self-test
    
    tmpdir="$(mktemp -d)"
    # create repo, origin/HEAD, main, issue branch, linked worktree
    # run guard fixture against:
    # - root on main + git switch issue-* => block
    # - root already issue-* + git switch main => allow
    # - .claude/worktrees/issue-* cwd + git switch ... => allow/defer
    # - root on main + git checkout HEAD -- README.md => allow

    B8. bash -lc / compound command の fail-closed 方針が必要

    #1014 は bash -lc "git switch ..." と sh -c "git checkout ..." を block 対象にしていますが、現実には次のような形も出ます。

    cd src && git switch issue-123-x
    command git switch issue-123-x
    env FOO=bar git switch issue-123-x
    bash -lc 'cd /repo && git checkout issue-123-x'

    local root context で branch mutation grammar を完全に証明できない compound command は、branch guard では fail-closed にしてください。これは worktree_scope_guard の「unparseable Bash that may mutate is blocked」という既存思想とも整合します。PR #971 の設計は shell wrapper の再帰 unwrap と unparseable mutating Bash の fail-closed を採っています。

    Issue本文に入れるべき修正差分

    最小修正は以下です。

    ## Additional Non-Goals
    
    - Codex PreToolUse / PermissionRequest hook を完全な enforcement boundary とみなすこと
    - Codex hook の実行順序に依存すること
    - branch drift guard を general mutation guard に拡張すること
    
    ## Codex config requirement
    
    Use exactly one project-local representation:
    - `.codex/config.toml`
    
    Do not add `.codex/hooks.json` in the same layer.
    
    The TOML shape must be event -> matcher group -> handler array:
    
    ```toml
    [features]
    hooks = true
    
    [[hooks.PreToolUse]]
    matcher = "Bash"
    
    [[hooks.PreToolUse.hooks]]
    type = "command"
    command = 'bash "$(git rev-parse --show-toplevel)/.codex/hooks/local_main_branch_guard.sh"'
    timeout = 10
    statusMessage = "Checking local root branch policy"
    
    [[hooks.PermissionRequest]]
    matcher = "Bash"
    
    [[hooks.PermissionRequest.hooks]]
    type = "command"
    command = 'bash "$(git rev-parse --show-toplevel)/.codex/hooks/local_main_branch_guard.sh"'
    timeout = 10
    statusMessage = "Checking local root branch policy"

    check_codex_agent_config.py must fail if:

    • [features].hooks = false
    • command handler is not nested under [[hooks.<Event>.hooks]]
    • both .codex/config.toml and .codex/hooks.json define hooks in the same layer
    • startup preflight is not documented in Codex rules/session prompt
    
    ```markdown
    ## Additional Acceptance Criteria
    
    - [ ] AC10: Git branch mutation grammar covers `switch -C`, `switch --detach`, `switch --guess`, `checkout -B`, `checkout --detach`, `checkout --orphan`, `checkout --ignore-other-worktrees`, `branch -m`, `branch -M`.
    - [ ] AC11: `git checkout` path restore forms are not overblocked: `HEAD -- path`, `--pathspec-from-file`, `-p/--patch`.
    - [ ] AC12: `gh` / `hub` handling uses allowlist in already-drifted state; mutating `gh issue edit/comment` and `gh pr checkout/edit/comment/merge/update-branch` are blocked.
    - [ ] AC13: project root / primary worktree detection uses `git worktree list --porcelain -z` catalog and does not rely on `git rev-parse --show-toplevel` alone.
    - [ ] AC14: default branch resolution is shared with existing local main scratch logic or tested against the same fixtures.
    - [ ] AC15: inline env override in Bash command is blocked; only hook process env override with non-empty reason is accepted.
    - [ ] AC16: compound shell commands that may branch-mutate local root are fail-closed unless parsed and proven safe.
    - [ ] AC17: Codex startup preflight is mandatory because Codex PreToolUse is not a complete shell interception boundary.
    

    最終結論

    #1014 は必要です。特に #960/PR #971 の worktree_scope_guard は「mutation outside active issue worktree」を止める層であり、local root が issue branch に drift する前段事故を説明する UI / reason code ではありません。#1014 の local_main_branch_guard は追加する価値があります。

    ただし、このまま実装に投げると Codex 側の hook 設定・信頼・不完全 interception・command grammar の穴で fail-open します。先に #1014 本文を上記 blocker で補強し、Codex config shape、startup preflight、git checkout/switch grammar、gh allowlist、root/worktree catalog resolver を AC に昇格してください。

  3. squne121 commented on Jun 20, 2026

    @squne121
    OwnerAuthor

    Refinement Loop: Human Escalation Required

    The loop has terminated and requires human review. Cause: human judgment required

    Blockers

    "C4: issue-reviewer が VC コマンドに $ prefix / backtick が必要と主張(3 iteration 連続)"
    
    "しかし contract_readiness_check(LP010)と baseline_vc_preflight(status:pass, expected_fail:17, blocked:0)は 3 回とも PASS"
    
    "reviewer の C4 は false positive の疑いが強い。deterministic tools と reviewer 判定の矛盾を人間が確認してください"
    
    "Issue 本文は anchor comment(B1-B8, AC10-AC17)の要求事項をすべて反映済み"
    
    "Allowed Paths / Codex integration / Stop Conditions / In Scope / CVS をすべて修正・整合済み"
    
  4. squne121 commented on Jun 20, 2026

    @squne121
    OwnerAuthor

    CONTRACT_REVIEW_RESULT_V1

    schema: CONTRACT_REVIEW_RESULT_V1
    issue_number: 1014
    repo: squne121/loop-protocol
    status: go
    generated_at: "2026-06-20T02:36:00Z"
    body_sha256: "sha256:a4f88b57d9b3487d15ab526b96b33df9db923644cb4acca39c65878d3a9f01e0"
    
    checks:
      template_compliance: pass
      state_label: pass          # state/needs-human ラベルなし
      allowed_paths_present: pass
      vc_present: pass
      stop_conditions_complete: pass
      ac_verifiability: pass     # 全 AC チェックボックス形式・AC1–AC17 対応 VC あり
      product_spec_check:
        applicability: not_applicable
        decision: pass
      worktree_branch_collision: pass   # issue-1014 worktree 未作成
      vc_preflight:
        status: pass
        summary:
          expected_fail: 17
          unexpected_pass: 0
          blocked: 0
          human_judgment: 0
        note: "全 AC1–AC17 が exit4(テストファイル未作成)→ expected_baseline_fail / go"
      next_action: implement-issue
      blocked_reasons: []

    VC Preflight 詳細

    AC command exit decision scope_class
    AC1–AC7, AC9–AC16 uv run pytest .claude/hooks/tests/test_local_main_branch_guard.py -q 4 go baseline_fail_expected
    AC8, AC17 uv run pytest tests/codex/test_local_main_branch_guard.py -q 4 go baseline_fail_expected

    C4 false positive 確認: 直前 refinement loop で issue-reviewer が「VC に $ prefix / backtick が必要」と主張したが、baseline_vc_preflight(LP010 / contract_readiness_check)は 3 回ともPASS。run_contract_review_once.py も status: go / source: all_checks_pass を返す。C4 は false positive と判定。

    Contract Snapshot

    Outcome: ローカルリポジトリ root checkout が常に main / default branch に固定される。Claude Code・Codex CLI の双方で local_main_branch_guard が機能し、worktree_scope_guard より前段で root checkout の branch drift を即時ブロックする。

    Worktree / Branch:

    • worktree: .claude/worktrees/issue-1014-local-main-branch-guard
    • branch: worktree-issue-1014-local-main-branch-guard

    Allowed Paths:

    • scripts/agent-guards/local_main_branch_guard.py
    • .claude/hooks/local_main_branch_guard.sh
    • .claude/hooks/tests/test_local_main_branch_guard.py
    • .claude/settings.json
    • docs/dev/hook-boundaries.md
    • scripts/check_hook_boundaries.py
    • scripts/check_local_main_branch_state.py
    • scripts/check_codex_agent_config.py
    • .codex/hooks/local_main_branch_guard.sh
    • .codex/hooks.json
    • tests/codex/test_local_main_branch_guard.py

    Runtime Verification Applicability: not_applicable

    Required Skills: Python / shell scripting, Claude Code hooks / PreToolUse, git worktree

  5. squne121 commented on Jun 20, 2026

    @squne121
    OwnerAuthor

    実装完了 — Draft PR #1041

    PR

    #1041

    検証結果

    # AC1–AC7, AC9–AC16
    uv run pytest .claude/hooks/tests/test_local_main_branch_guard.py -q
    # 77 passed
    
    # AC8, AC17
    uv run pytest tests/codex/test_local_main_branch_guard.py -q
    # 13 passed
    
    # AC7: manifest drift check
    uv run python3 scripts/check_hook_boundaries.py
    # [check_hook_boundaries] OK: manifest=9 entries, settings=9 entries — drift なし
    
    # AC17: Codex startup preflight validation
    uv run python3 scripts/check_codex_agent_config.py --assert-local-main-branch-guard
    # OK: Codex agent contract validation passed
    

    Allowed Paths 準拠

    全変更ファイルが contract Allowed Paths 内に収まっている(self-report: true)。

  6. added a commit that references this issue on Jun 20, 2026
  7. squne121 commented on Jun 20, 2026

    @squne121
    OwnerAuthor

    CONTRACT_REVIEW_RESULT_V1

    schema: CONTRACT_REVIEW_RESULT_V1
    issue_number: 1014
    repo: squne121/loop-protocol
    status: go
    generated_at: "2026-06-20T03:45:00Z"
    body_sha256: "sha256:2475d85b3632e3bb9e6b79e70a795b167de1e76b6013614dfd5bf8a6c2a1d0bf"
    
    scope_delta:
      reason: "Scope Delta: .codex/rules/default.rules を Allowed Paths に追加(B5 fix により B5 の preflight 記述先として必要)"
      supersedes: "https://github.com/squne121/loop-protocol/issues/1014#issuecomment-4756083657"
    
    checks:
      template_compliance: pass
      state_label: pass
      allowed_paths_present: pass
      vc_present: pass
      stop_conditions_complete: pass
      ac_verifiability: pass
      product_spec_check:
        applicability: not_applicable
        decision: pass
      worktree_branch_collision: pass
      vc_preflight:
        status: pass
        summary:
          expected_fail: 17
          unexpected_pass: 0
          blocked: 0
          human_judgment: 0
      next_action: implement-issue
      blocked_reasons: []

    Scope Delta 詳細

    前回 go コメント(#issuecomment-4756083657)から以下を変更:

    変更 内容
    Allowed Paths 追加 .codex/rules/default.rules
    理由 B5 fix: Codex startup preflight の mandatory gate を .codex/rules/default.rules に記述し check_codex_agent_config.py が実検証するため

    Contract Snapshot

    Worktree / Branch:

    • worktree: .claude/worktrees/issue-1014-local-main-branch-guard
    • branch: worktree-issue-1014-local-main-branch-guard

    Allowed Paths(更新後):

    • scripts/agent-guards/local_main_branch_guard.py
    • .claude/hooks/local_main_branch_guard.sh
    • .claude/hooks/tests/test_local_main_branch_guard.py
    • .claude/settings.json
    • docs/dev/hook-boundaries.md
    • scripts/check_hook_boundaries.py
    • scripts/check_local_main_branch_state.py
    • scripts/check_codex_agent_config.py
    • .codex/hooks/local_main_branch_guard.sh
    • .codex/hooks.json
    • tests/codex/test_local_main_branch_guard.py
    • .codex/rules/default.rules ← Scope Delta 追加

    VC preflight: 全 AC1–AC17 が expected_baseline_fail / go(exit4)

  8. added 2 commits that reference this issue on Jun 20, 2026
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

    area/ai-opsenhancementworkflow

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions