Skip to content

実装: Codex linked issue worktree 内の rtk git mutation path と hook/rules split-brain を解消する #1241

Closed

Description

@squne121

Machine-Readable Contract

contract_schema_version: v1
issue_kind: implementation
parent_issue: none
goal_ref: "Codex linked issue worktree 内で policy bypass なしに rtk git add/commit/push を実行できる正規経路を復旧し、hook block 後の安全な修正コマンド提示も可能にし、root checkout branch drift 防止を維持する"
change_kind: workflow

Parent Issue

なし(単独改善。Codex hook / rules の運用バグ修正)

Parent Goal Ref

  • Goal: Codex rules と local_main_branch_guard / worktree_scope_guard の split-brain を解消し、linked issue worktree 内の正規 rtk git mutation path と hook repair hint path を deterministic に提供する
  • Desired Destination: .codex/ と guard scripts / validator / SSOT docs の範囲で、Codex 実装系 worker が issue-bound worktree branch を更新でき、hook block 後も安全な次コマンドを判断できる状態

Current Validated Scope

  • .codex/rules/default.rules の rtk git mutation policy を、linked issue worktree publish path 専用の exact / bounded command class と整合する形へ更新する
  • .codex/hooks.json の Codex PreToolUse / PermissionRequest hook chain で使う guard の責務分担を明文化し、rtk git mutation path と hook repair hint path の両方が fail-closed で到達可能な構成へ修正する
  • scripts/agent-guards/local_main_branch_guard.py に、rtk git add/commit/push の exact / bounded classify と HOOK_COMMAND_REPAIR_HINT_V1 出力を扱う共有 policy / formatter を追加する
  • .claude/hooks/worktree_scope_guard.py と shared policy の整合を取り、active worktree / branch / cwd / target branch の一致時のみ mutation を許可し、block 時は bounded repair hint を返す
  • scripts/check-codex-agents.mjs に Codex hook / rules / agent surface / repair hint contract の整合チェックを追加する
  • docs/dev/hook-boundaries.md と docs/dev/agent-skill-boundaries.md を current runtime contract に同期する
  • PR feat(#1233): Allowed Paths matcher を mid-path ** 対応 v2 grammar に拡張する #1240 / Issue 実装: allowed_paths_review_gate.py の Allowed Paths matcher を mid-path ** 対応 v2 grammar に拡張する #1233 で再現した blocker と、hook block 後の command repair hint を fixture / self-test / validator で再現・固定する

Remaining Parent Gaps

なし(ただし Codex runtime 自体の repo 外仕様で制御不能と判明した場合は別 research issue に分離)

Outcome

linked issue worktree 内で、active worktree branch と一致する対象に限り rtk git add / rtk git commit / rtk git push が policy bypass なしで許可され、hook が block した場合も Claude Code / Codex CLI が次に打つ安全コマンドを HOOK_COMMAND_REPAIR_HINT_V1 で判断でき、primary root checkout の branch drift 防止と destructive git deny は維持されたまま historical regression(PR #1240 系 blocker)を再現・防止できる状態。

In Scope

  • rtk git add/commit/push の exact / bounded allow policy 追加
  • git push origin HEAD:refs/heads/<active_branch> 相当だけを許可し、--force / --tags / --all / --mirror / --delete / unrelated remote or refspec を deny する command class 設計
  • rtk git commit -m の staged diff subset 検証と、git add literal pathspec + Allowed Paths matcher 適用の明文化
  • root checkout と linked issue worktree の裁定責務の再設計
  • local_main_branch_guard と worktree_scope_guard の shared classifier / shared mutation policy / shared repair hint formatter への寄せ
  • HOOK_COMMAND_REPAIR_HINT_V1 を用いた Claude Code / Codex CLI 向け block reason / repair hint 契約追加
  • Codex rules / hooks / validator / docs の同時更新
  • PR feat(#1233): Allowed Paths matcher を mid-path ** 対応 v2 grammar に拡張する #1240 / Issue 実装: allowed_paths_review_gate.py の Allowed Paths matcher を mid-path ** 対応 v2 grammar に拡張する #1233 の historical regression と repair hint 出力を用いた deterministic test / self-test 追加

Out of Scope

  • root checkout 上での direct git add/commit/push の許可
  • rtk git mutation 全体の blanket allow
  • git reset, git clean, git checkout --, force push, unrelated branch mutation の許可
  • Claude Code 側 workflow 全般の redesign
  • GitHub merge / undraft / PR review policy 自体の変更
  • updatedInput による hook 自動コマンド書き換え
  • partial-shell workaround や policy bypass を前提にした運用回避

Additional Requirement: Hook Repair Hint Contract

hook が block する場合、Claude Code / Codex CLI が次に実行すべき安全な修正方針を判断できるよう、bounded stderr に HOOK_COMMAND_REPAIR_HINT_V1 を出す。

Output Contract

  • Claude Code 互換のため、exit 2 block 時は stderr に出す
  • Codex CLI 互換のため、同じ内容を reason / permissionDecisionReason / additionalContext に再利用できる pure formatter にする
  • raw secret / raw body / raw full command / raw branch name は出さない
  • 出力は最大 10 行、各行 240 文字以下を目安にする
  • 代替コマンド候補は allowlist 済みの exact / bounded command のみを出す
  • reset, clean, checkout, switch, force push, rtk proxy, shell chain, bypass env は候補に出さない
  • updatedInput による自動書き換えは行わず、block + hint のみを提供する

Required Fields

HOOK_COMMAND_REPAIR_HINT_V1:
  blocked_command_class: "<class>"
  reason_code: "<reason>"
  safe_action: "<one sentence>"
  suggested_command: "<single safe command or omitted>"
  forbidden_alternatives:
    - "<blocked pattern>"
  verification_command: "<optional safe read-only check>"
  stop_condition: "<when human must intervene>"

Acceptance Criteria

  • AC1: linked issue worktree 内で rtk git add <allowed-path-file> が local_main_branch_guard と worktree_scope_guard の両方を通過し、root checkout では従来どおり block される
  • AC2: linked issue worktree 内で rtk git commit -m "<msg>" が active worktree branch / cwd / issue context 一致時のみ許可され、実行前に staged diff が Allowed Paths subset であることを検証する
  • AC3: linked issue worktree 内で rtk git push origin HEAD:refs/heads/<active_branch> 相当のみが許可され、root checkout・unrelated branch・unrelated remote/refspec・--force / --tags / --all / --mirror / --delete は block される
  • AC4: direct git add, git commit, git push は引き続き Codex rules / hooks で許可されない
  • AC5: rtk git reset, rtk git clean, rtk git checkout, force push 相当、unrelated branch mutation は引き続き block または prompt のままである
  • AC6: shared classifier または明示的な shared mutation policy により .codex/rules/default.rules と local_main_branch_guard.py / worktree_scope_guard.py の allow/deny が split-brain にならない
  • AC7: local_main_branch_guard.py が direct_bypass_requires_rtk, rtk_unknown_inner, local_root_branch_drift, gh_mutation_denied, unparseable_branch_mutation などの block 時に HOOK_COMMAND_REPAIR_HINT_V1 を stderr で返せる
  • AC8: worktree_scope_guard.py が git_add_requires_explicit_pathspec, target_dir_outside_worktree, no_matching_worktree, ambiguous_worktree, push_refspec_requires_active_branch などの block 時に HOOK_COMMAND_REPAIR_HINT_V1 を返し、危険な代替案を提示しない
  • AC9: HOOK_COMMAND_REPAIR_HINT_V1 は blocked_command_class, reason_code, safe_action, suggested_command, forbidden_alternatives, verification_command, stop_condition を持ち、raw branch name / raw secret-like value / raw full command / body text を漏らさず、最大 10 行制約を守る
  • AC10: scripts/check-codex-agents.mjs または同等 validator が、この policy / repair hint contract の drift を fail-closed で検出できる
  • AC11: docs/dev/hook-boundaries.md と docs/dev/agent-skill-boundaries.md が新しい rtk git mutation contract と repair hint contract を反映し、repair hint は agent steering 用で authorization ではないと明記している
  • AC12: PR feat(#1233): Allowed Paths matcher を mid-path ** 対応 v2 grammar に拡張する #1240 / Issue 実装: allowed_paths_review_gate.py の Allowed Paths matcher を mid-path ** 対応 v2 grammar に拡張する #1233 で観測された historical regression(worktree cwd、branch worktree-issue-1233-allowed-paths-matcher-v2、rtk git add が rtk_unknown_inner で止まるケース)と repair hint 出力が regression test / self-test で再現され、修正後に pass する

Verification Commands

# AC1
# preflight-scope: pr_review_only
$ uv run pytest scripts/agent-guards/tests/test_local_main_branch_guard.py -q

# AC2
# preflight-scope: pr_review_only
$ uv run pytest .claude/hooks/tests/test_worktree_scope_guard.py -q

# AC3
# preflight-scope: pr_review_only
$ rg -n --fixed-strings "HEAD:refs/heads/" .codex/rules/default.rules

# AC4
# preflight-scope: pr_review_only
$ rg -n --fixed-strings "direct_bypass_requires_rtk" scripts/agent-guards/local_main_branch_guard.py

# AC5
# preflight-scope: pr_review_only
$ rg -n --fixed-strings "rtk git reset" .codex/rules/default.rules

# AC6
# baseline-expect: fail
$ test -f scripts/agent-guards/git_mutation_command_policy.py

# AC7
# preflight-scope: pr_review_only
$ rg -n --fixed-strings "HOOK_COMMAND_REPAIR_HINT_V1" scripts/agent-guards/local_main_branch_guard.py

# AC8
# preflight-scope: pr_review_only
$ rg -n --fixed-strings "HOOK_COMMAND_REPAIR_HINT_V1" .claude/hooks/worktree_scope_guard.py

# AC9
# preflight-scope: pr_review_only
$ rg -n --fixed-strings "blocked_command_class" docs/dev/hook-boundaries.md

# AC10
# preflight-scope: pr_review_only
$ node scripts/check-codex-agents.mjs --self-test

# AC11
# preflight-scope: pr_review_only
$ rg -n --fixed-strings "agent steering" docs/dev/agent-skill-boundaries.md

# AC12
# baseline-expect: fail
$ test -f .claude/hooks/tests/test_issue1241_hook_repair_hint.py

Allowed Paths

  • .codex/rules/default.rules
  • .codex/hooks.json
  • .codex/hooks/local_main_branch_guard.sh
  • scripts/agent-guards/local_main_branch_guard.py
  • scripts/agent-guards/hook_repair_hints.py
  • scripts/agent-guards/git_mutation_command_policy.py
  • .claude/hooks/worktree_scope_guard.py
  • scripts/check-codex-agents.mjs
  • docs/dev/hook-boundaries.md
  • docs/dev/agent-skill-boundaries.md
  • scripts/agent-guards/tests/
  • .claude/hooks/tests/

Stop Conditions

  • Allowed Paths 外の変更が必要と判明した場合
  • In Scope の固定契約(キー集合・スキーマ・型定義)の変更が必要になった場合
  • 新規 Issue の起票が必要と判断した場合(スコープ分割が発生する場合)
  • 後続 Phase / 別スコープへの波及が判明した場合
  • nested SubAgent delegation が必要になった場合
  • 外部サービス利用・権限昇格・既存テスト大規模改変が必要になった場合
  • root checkout への mutating git を許可しないと解けないと判明した場合
  • git reset, git clean, force push, destructive checkout などの破壊的操作を新たに許可しないと解けない場合
  • Codex runtime 側の固定仕様により repo 側から制御不能で、local policy 修正だけでは到達不能と判明した場合
  • secret / token / 外部課金 / 権限昇格が必要な検証しか残らない場合
  • linked issue worktree と unrelated branch mutation を deterministic に区別できる根拠が得られない場合
  • repair hint が安全な bounded command を提示できず、危険操作しか候補にできない場合
  • Claude Code / Codex CLI のどちらかで hook block 後の repair hint 契約を安全に満たせないと判明した場合

Required Skills

  • Python
  • Node.js
  • Git hook / command classification
  • Codex execpolicy / hook integration test

Scope Delta(任意)

N/A

Root Cause

現在の Codex policy は 2 層で矛盾している。

  1. .codex/rules/default.rules と AGENTS.md は direct mutating git を禁止し、正規経路を rtk git mutation に寄せている。
  2. しかし scripts/agent-guards/local_main_branch_guard.py は rtk git add のような mutation subcommand を exact / bounded に classify せず、Codex hook からは rtk_wrapper -> unknown inner として fail-closed block する。
  3. さらに worktree_scope_guard.py は worktree containment を担うが、rtk git mutation を「active issue worktree 内の正規 publish path」として受理する shared classifier と hook repair hint formatter が不足している。
  4. その結果、linked issue worktree 内で direct git は direct_bypass_requires_rtk、rtk git は rtk_unknown_inner となり、正規の stage/commit/push 経路が消失し、block 後に安全な代替コマンドも提示できない。

これは branch drift 防止そのものではなく、rules 側の「rtk を使え」と guard 側の「rtk git mutation を解釈できない」が食い違っている split-brain である。

Existing Harm / Historical Regression Context

PR #1240 は 2026-06-29 時点で MERGED だが、Issue #1233 系で観測された historical regression は本件の再現条件としてなお有効である。参照時点での PR metadata は以下。

当時の linked issue worktree 文脈では、以下がすでに完了していた。

  • cwd: /home/squne/projects/LOOP_PROTOCOL/.claude/worktrees/issue-1233-allowed-paths-matcher-v2
  • branch: worktree-issue-1233-allowed-paths-matcher-v2
  • historical head SHA sample: 98a0f0e7117333774c2333584b7218ec2c7db911
  • 未コミット差分:
    • .claude/skills/pr-review-judge/references/allowed-paths-gate.md
    • .claude/skills/pr-review-judge/tests/test_allowed_paths_matcher_v2.py
  • 検証結果:
    • uv run --locked pytest ... -q → 48 passed
    • uv run ruff check --select E,F --ignore E402 ... → All checks passed!

にもかかわらず publish 段階で:

  • direct git add → direct_bypass_requires_rtk
  • rtk git add → local_main_branch_guard の rtk_unknown_inner
  • rtk git --help も同系統 block

となり、Codex 実装 worker は policy bypass せずに差分を PR branch へ反映できない。これは implementation loop の Step 1 完了後に publish 不能で停止する実害であり、P1/P2 品質改善を適用済みでも PR を前進できない。加えて、block 後に安全な修正コマンドを hook 出力から判断できないため、Claude Code / Codex CLI の自己修復性も不足している。

Implementation Approach

  1. rtk git mutation を blanket allow せず、linked issue worktree publish path 専用の shared classifier を導入する。
  2. .codex/rules/default.rules 側は rtk git mutation の bounded subset、exact command class、deny matrix を明示する。
  3. local_main_branch_guard.py は unknown inner へ落とす前に shared policy を照会し、block 時は HOOK_COMMAND_REPAIR_HINT_V1 を emit する。
  4. worktree_scope_guard.py は stale directory prefix ではなく active worktree catalog / branch / cwd 一致を allow 根拠にし、block 時は bounded repair hint を返す。
  5. scripts/check-codex-agents.mjs に rules / hooks / docs / repair hint contract の drift 検出を追加する。
  6. docs/dev/hook-boundaries.md と docs/dev/agent-skill-boundaries.md を同 PR で同期する。

Runtime Verification Applicability

  • decision: not_applicable
  • reason: 本 Issue は local hook / rules / validator / docs の静的・テスト駆動改善で完結し、外部 UI / deploy / runtime artifact 採取を要求しない

Related

Delivery Rule

  • 1 Issue = 1 PR
  • 専用 worktree で実装する
  • Draft PR で開始する
  • Draft 解除 / merge は人間判断に残す

Activity

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

    @squne121
    OwnerAuthor

    you asked

    message time: 2026-06-29 22:04:32

    #1241
    内容について関連Issue、PR、リポジトリ資産、コメントを参照した上で敵対的レビューして。
    取り扱う技術や配布物の実装をWEB検索し高品質化してほしい。


    chatgpt response

    対象 Issue #1241 を中心に、GitHub 側の本文・コメント・関連 PR/Issue・リポジトリ内の運用資産を確認します。並行して、該当技術の現在仕様を Web で検証し、最後に敵対的レビューと次アクション用プロンプトまでまとめます。

    Issue 本文上は、正規経路が direct git 禁止・rtk git 推奨なのに、guard が rtk git add を rtk_unknown_inner として落とす、という二層ポリシー不整合が主因です。ここから関連 Issue/PR と実ファイルの実装状態を照合します。

    ここまでで、#1241 自体にコメントはなく、実害は #1233/#1240 の publish 停止に集約されることを確認しました。次に、リポジトリ内の rules/hooks/guard/docs の実装面を見て、契約の抜けを具体化します。

    結論

    #1241 の問題設定は妥当です。実害も明確です。#1233/#1240 では内容上の実装・CI・allowed paths gate は概ね通っている一方、publish 段階で direct git add は direct_bypass_requires_rtk、rtk git add は rtk_unknown_inner で止まり、正規の stage/commit/push 経路が消失しています。#1241 自体にコメントはまだありません。

    ただし、今の #1241 契約は 「rtk git add/commit/push を linked issue worktree 内で許可する」粒度が粗すぎます。このまま実装すると、rtk git push の blanket allow、staged index 経由の allowed paths 回避、Codex rules と hook の最終 decision 不一致が残る可能性があります。

    P0 blocker 相当

    1. rtk git push の許可条件が危険に曖昧

    worktree_scope_guard.py は、active issue worktree 内で cwd が expected worktree 配下なら mutating command を最終的に allow します。これは containment guard としては妥当ですが、git push の remote/refspec/force/tag/all/mirror/delete を検証していません。つまり「cwd が正しい」だけでは「active branch だけを publish する」証明になりません。

    修正条件は、rtk git push origin HEAD:refs/heads/<active_branch> のような 明示 refspec の exact command class に寄せるべきです。少なくとも --force, --force-with-lease, --tags, --all, --mirror, --delete, :<branch>, unrelated remote, unrelated branch refspec は fail-closed fixture に入れる必要があります。RTK 自体は rtk git push や rtk proxy <command> の command surface を提供しますが、それ自体を policy boundary と見なすべきではありません。(GitHub)

    2. rtk git commit -m は staged index の汚染を検出しないと危険

    commit の安全性は cwd ではなく index の内容 で決まります。既に out-of-scope file が stage 済みなら、rtk git commit -m "..." を許可した瞬間に allowed paths を迂回できます。#1241 は add <allowed-path-file> を AC1 に置いていますが、AC2 の commit に git diff --cached --name-status -z の subset 検証を要求していません。

    commit allow の前提として、staged file set が issue contract の Allowed Paths と protected paths policy に一致すること、rename/copy/delete の扱い、secret-like path、assets/, LICENSES/, .env*, .git/** を検査する postcondition が必要です。AGENTS.md も assets/ と LICENSES/ を明示保護しています。

    3. rtk git add は pathspec 制限だけでは不足

    既存 worktree_scope_guard.py は git add -A, --all, -u, --pathspec-from-file, ., .., wildcard、directory pathspec を reject するロジックを持っています。これは良い基盤です。

    ただし #1241 の目的は「worktree containment」ではなく「Issue 契約内の publish path 復旧」です。したがって git add <literal-file> が expected worktree 内であるだけでなく、#1233/#1240 の Allowed Paths matcher と同じ repo-relative POSIX path 判定で許可される必要があります。#1240 側は Allowed Paths matcher v2 の仕様・テストが概ね整っており、review_subagent 再計算でも allowed_paths_gate: ok と記録されています。

    4. shared classifier が「方針」止まりで、API が未定義

    #1241 は shared classifier / shared mutation policy を要求していますが、モジュール名・入力・出力 schema・reason_code・rule_id が未定義です。ここを曖昧にすると、local_main_branch_guard.py, worktree_scope_guard.py, .codex/rules/default.rules, check-codex-agents.mjs が再び split-brain になります。

    既存 repo には良い前例があります。local_main_branch_guard.py は controlled skill mutation policy と worktree bootstrap policy を sibling module として import し、利用不能時は fail-closed にしています。 worktree_scope_guard.py も shared cleanup/catalog と controlled skill mutation policy を import して同じ判断根拠に寄せています。

    #1241 も scripts/agent-guards/git_mutation_command_policy.py のような単一 SSOT を作り、両 guard と validator が同じ関数を呼ぶ形にするべきです。

    5. Codex rules の最終 decision 検証が必須

    .codex/rules/default.rules では現在、rtk git read-only は allow、rtk git add/commit/push など mutation は prompt です。 一方、direct git add/commit/push は forbidden です。

    Codex rules は複数 rule が match した場合、最も restrictive な decision が勝ちます。つまり allow rule を足しただけでは、既存 prompt/forbidden rule に負ける可能性があります。codex execpolicy check で positive/negative の最終 decision を固定しない PR は信用できません。(OpenAI 開発者)

    6. hook は canonical gate ではない、という既存前提をテストで守る必要がある

    AGENTS.md は「hook は diagnostic/prevention layer、post-run verifier が canonical gate」と明記しています。 Codex 公式 docs も、PreToolUse hook は guardrail であり、すべての shell call を intercept する完全な enforcement boundary ではないと説明しています。(OpenAI 開発者)

    したがって #1241 は hook allow だけでなく、publish 後に「push された head が active issue branch である」「commit diff が allowed paths subset である」「root checkout は default branch のまま」を post-run verifier で確認する契約を追加すべきです。

    契約に追加すべき具体条件

    AC を次のように強化するのが安全です。

    • rtk git add: linked issue worktree 内、expected worktree catalog 1 件一致、branch worktree-issue-<N>-<slug> 一致、literal file pathspec のみ、directory/wildcard/magic/broad option 禁止、Allowed Paths matcher で許可された repo-relative file のみ allow。
    • rtk git commit: -m <msg> のみ。-a, --all, --amend, --no-verify, --allow-empty, --reuse-message, --file, pathspec付き commit は deny。実行前に staged set を Allowed Paths subset として検証。
    • rtk git push: explicit remote/refspec のみ。推奨は rtk git push origin HEAD:refs/heads/<active_branch>。force/tag/all/mirror/delete/unrelated remote/unrelated refspec は deny。
    • direct git add/commit/push: 引き続き forbidden。
    • rtk proxy, bash -lc, env ... rtk git ..., shell chain, newline, semicolon, pipe, redirection, command substitution は deny。
    • PermissionRequest と PreToolUse の差分を明記する。現 hooks.json では Bash の PreToolUse に worktree_scope_guard.py が入っていますが、PermissionRequest には入っていません。

    実装者に渡す推奨プロンプト

    Issue #1241 を実装してください。目的は、Codex linked issue worktree 内で direct git bypass なしに rtk git add/commit/push の publish path を復旧することです。ただし blanket allowは禁止です。
    
    必須方針:
    1. `scripts/agent-guards/git_mutation_command_policy.py` などの shared policy module を作り、local_main_branch_guard.py / worktree_scope_guard.py / scripts/check-codex-agents.mjs の検証が同じ command class を参照できるようにする。
    2. allow するのは linked issue worktree publish path 専用の exact/bounded subset のみ。
       - add: literal file pathspec only。-A/--all/-u/./../wildcard/directory/pathspec-from-file/magic pathspec 禁止。
       - commit: `commit -m <msg>` のみ。実行前 staged set が Allowed Paths subset であることを検証。
       - push: `push origin HEAD:refs/heads/<active_branch>` 相当のみ。force/tags/all/mirror/delete/unrelated remote/refspec 禁止。
    3. root checkout での mutating git は direct/rtk とも許可しない。
    4. direct git add/commit/push は引き続き Codex rules で forbidden。
    5. `rtk proxy`, shell wrapper, inline env, chain, redirection, command substitution は deny。
    6. #1233/#1240 の再現条件を synthetic fixture 化し、live PR 依存にしない。
    7. `codex execpolicy check` で最終 decision を検証する。allow rule 追加だけで済ませない。
    8. docs/dev/hook-boundaries.md, docs/dev/agent-skill-boundaries.md, AGENTS.md の rtk trust boundary と post-run verifier canonical gate を同期する。
    
    検証:
    - uv run pytest scripts/agent-guards/tests/ -q
    - uv run pytest .claude/hooks/tests/ -q
    - node scripts/check-codex-agents.mjs --self-test
    - codex execpolicy check --rules .codex/rules/default.rules -- rtk git add <allowed-file>
    - codex execpolicy check --rules .codex/rules/default.rules -- rtk git push origin HEAD:refs/heads/worktree-issue-1233-allowed-paths-matcher-v2
    - codex execpolicy check --rules .codex/rules/default.rules -- git add foo.txt
    - codex execpolicy check --rules .codex/rules/default.rules -- rtk git reset --hard
    - rg -n "rtk git|linked issue worktree|canonical gate|post-run verifier" docs/dev/hook-boundaries.md docs/dev/agent-skill-boundaries.md AGENTS.md
    
    停止条件:
    破壊的操作、秘密情報、外部課金、権限不足、root checkout mutating git の許可、force push/reset/clean/checkout/switch の許可が必要になった場合は停止。
    

    この Issue は実装価値があります。ただし、最優先で潰すべきリスクは push と commit の証明不足 です。rtk git を通せるようにするだけなら簡単ですが、それでは policy bypass の別名になります。


    you asked

    message time: 2026-06-29 22:16:09

    ClaudecodeやCodexCliのためにhookの出力でコマンドをどのように修正すればいいか分かるようにして。


    chatgpt response

    方針としては、hook の stderr/stdout を単なる block 理由ではなく、機械可読な「代替コマンド候補」まで含む診断契約にします。現行 hook の block 出力を確認し、Claude Code / Codex CLI の hook 挙動に合わせた最小変更案に落とします。

    はい。#1241 に 「hook が block したとき、Claude Code / Codex CLI が次に打つべき修正コマンドを読める形式で出す」 という要件を追加するべきです。

    現状の local_main_branch_guard.py は stderr に reason_code, rule_id, argv_redacted, recovery を最大 10 行で出していますが、recovery は「simple command を使え」程度で、実際にどう書き換えるかが不足しています。 worktree_scope_guard.py の cleanup block も reason だけで、代替コマンド候補はありません。

    Claude Code では exit 2 の stderr が Claude にエラーとして返り、PreToolUse は tool call を block します。JSON stdout は exit 0 のときだけ処理され、exit 2 では無視されます。(Claude Platform Docs) そのため Claude Code 向けには exit 2 stderr に短い YAML/JSONL 風の修正ヒントを書くのが安全です。Codex CLI は PreToolUse で decision: block / reason、または exit code 2 + stderr の blocking reason を使え、さらに additionalContext や updatedInput もサポートします。(OpenAI 開発者)

    追加すべき仕様

    #1241 に以下を追加してください。

    ## Additional Requirement: Hook Repair Hint Contract
    
    hook が block する場合、Claude Code / Codex CLI が次に実行すべき安全な修正方針を判断できるよう、bounded stderr に `HOOK_COMMAND_REPAIR_HINT_V1` を出す。
    
    ### Output contract
    
    - Claude Code 互換のため、exit 2 block 時は stderr に出す。
    - Codex CLI 互換のため、同じ内容を `reason` / `permissionDecisionReason` / `additionalContext` に再利用できる pure formatter として実装する。
    - raw secret / raw body / raw full command / raw branch name は出さない。
    - 出力は最大 10 行、各行 240 文字以下を目安にする。
    - 代替コマンド候補は allowlist 済みの exact/bounded command のみを出す。
    - 危険操作を suggestion しない。`reset`, `clean`, `checkout`, `switch`, force push, `rtk proxy`, shell chain, bypass env は候補に出さない。
    
    ### Required fields
    
    ```yaml
    HOOK_COMMAND_REPAIR_HINT_V1:
      blocked_command_class: "<class>"
      reason_code: "<reason>"
      safe_action: "<one sentence>"
      suggested_command: "<single safe command or omitted>"
      forbidden_alternatives:
        - "<blocked pattern>"
      verification_command: "<optional safe read-only check>"
      stop_condition: "<when human must intervene>"

    Example: direct git add blocked

    [local_main_branch_guard] blocked: direct mutating git is not allowed
    HOOK_COMMAND_REPAIR_HINT_V1:
      blocked_command_class: direct_git_add
      reason_code: direct_bypass_requires_rtk
      safe_action: run the issue-worktree bounded rtk git add path instead
      suggested_command: rtk git add -- <repo-relative-allowed-file>
      forbidden_alternatives: ["git add", "git add .", "git add -A", "rtk git add ."]
      verification_command: rtk git status --short
      stop_condition: if the file is outside issue Allowed Paths, stop and update the Issue contract
    

    Example: rtk git add broad path blocked

    [worktree_scope_guard] blocked: git add pathspec is too broad
    HOOK_COMMAND_REPAIR_HINT_V1:
      blocked_command_class: rtk_git_add
      reason_code: git_add_requires_explicit_pathspec
      safe_action: add only explicit files that are inside the active issue worktree and Allowed Paths
      suggested_command: rtk git add -- <repo-relative-allowed-file>
      forbidden_alternatives: ["rtk git add .", "rtk git add -A", "rtk git add <directory>", "rtk git add '*.py'"]
      verification_command: rtk git diff --cached --name-status
      stop_condition: if staged files include out-of-scope paths, unstage manually only with human approval
    

    Example: rtk git push blocked

    [worktree_scope_guard] blocked: push target is not proven to be active issue branch
    HOOK_COMMAND_REPAIR_HINT_V1:
      blocked_command_class: rtk_git_push
      reason_code: push_refspec_requires_active_branch
      safe_action: publish only HEAD to the active issue branch
      suggested_command: rtk git push origin HEAD:refs/heads/<active-worktree-branch>
      forbidden_alternatives: ["rtk git push --force", "rtk git push --tags", "rtk git push --all", "rtk git push origin :branch"]
      verification_command: rtk git branch --show-current
      stop_condition: if active branch cannot be resolved from worktree catalog, stop
    
    
    ## 実装プロンプト
    
    Claude Code / Codex CLI に渡すなら、このまま使えます。
    
    **Standard Title: **
    
    Issue #1241 に hook repair hint contract を追加して実装してください。
    
    目的:
    Claude Code / Codex CLI が hook block 後に「どのコマンドへ修正すればよいか」を判断できるよう、local_main_branch_guard.py / worktree_scope_guard.py の block 出力に `HOOK_COMMAND_REPAIR_HINT_V1` を追加する。
    
    実装要件:
    1. `scripts/agent-guards/hook_repair_hints.py` を追加する。
       - reason_code / command_class から bounded な repair hint を生成する pure formatter にする。
       - raw command, raw branch name, raw secret-like value, raw body は出さない。
       - suggested_command は allowlist 済み exact/bounded command のみ。
       - 危険操作、bypass env、rtk proxy、shell chain は suggestion しない。
    
    2. `local_main_branch_guard.py` の `_emit_block_stderr()` に repair hint を追加する。
       - Claude Code 互換のため exit 2 stderr に出す。
       - 現在の最大 10 行制限を維持するか、既存行を圧縮して 10 行以内に収める。
       - `direct_bypass_requires_rtk`, `rtk_unknown_inner`, `local_root_branch_drift`, `gh_mutation_denied`, `unparseable_branch_mutation` に最低限対応する。
    
    3. `worktree_scope_guard.py` の block 出力にも同じ formatter を使う。
       - `git_add_requires_explicit_pathspec`
       - `target_dir_outside_worktree`
       - `no_matching_worktree`
       - `ambiguous_worktree`
       - `push_refspec_requires_active_branch`
       - cleanup 系 reason
       に対応する。
    
    4. Codex 用には同じ repair hint 本文を `decision: block` の reason / `permissionDecisionReason` / `additionalContext` に流用できる関数にする。
       - Codex PreToolUse は JSON stdout で `permissionDecision: "deny"` と reason を返せるが、既存 hook が exit 2 stderr 方式なら互換性を壊さず stderr 方式を維持してよい。
       - JSON stdout と exit 2 stderr を同一 hook で混在させない。
    
    5. tests を追加する。
       - hook stderr に `HOOK_COMMAND_REPAIR_HINT_V1` が出る。
       - `suggested_command` が dangerous command を含まない。
       - `git add .`, `git add -A`, force push, reset, clean, checkout, switch, rtk proxy は suggestion に出ない。
       - direct `git add foo` block 時は `rtk git add -- <repo-relative-allowed-file>` 型の hint が出る。
       - `rtk git push` block 時は active branch refspec 型の hint が出る。
       - raw branch name / absolute secret-like path / body text が stderr に漏れない。
    
    6. docs を更新する。
       - docs/dev/hook-boundaries.md に `HOOK_COMMAND_REPAIR_HINT_V1` を追記。
       - docs/dev/agent-skill-boundaries.md に、hook は diagnostic/prevention layer、post-run verifier が canonical gate であることを維持したまま、repair hint は agent steering 用であり authorization ではないと明記。
    
    検証:
    - uv run pytest scripts/agent-guards/tests/ -q
    - uv run pytest .claude/hooks/tests/ -q
    - node scripts/check-codex-agents.mjs --self-test
    - rg -n "HOOK_COMMAND_REPAIR_HINT_V1|suggested_command|forbidden_alternatives" scripts/agent-guards .claude/hooks docs/dev
    
    停止条件:
    破壊的操作、秘密情報、外部課金、権限不足、root checkout mutating git の許可、force push/reset/clean/checkout/switch の許可が必要になった場合は停止。
    
    ## 重要な注意
    
    `updatedInput` で hook が自動的に command を書き換える案は、今回の用途では避けた方がよいです。Codex は PreToolUse で `updatedInput` をサポートしていますが、これは allow と同時に tool input を差し替える機能です。([OpenAI 開発者](https://developers.openai.com/codex/hooks)) 今回は stage/commit/push という git mutation なので、hook が勝手に修正実行へ進めるより、**block して次に打つ安全コマンドを提示する**方が事故が少ないです。
    
  3. squne121 commented on Jun 29, 2026

    @squne121
    OwnerAuthor

    Contract Review Result

    CONTRACT_REVIEW_RESULT_V1:
      status: go
      generated_at: "2026-06-29T13:30:41Z"
      generated_by: issue-contract-review
      issue_url: https://github.com/squne121/loop-protocol/issues/1241
      body_sha256: "sha256:3ff79b58e75ed34dd127f535eca630bb4b00bc7510c0c531ed9b93ad67ff12cf"
      checks:
        readiness: go
        blockers: pass
        product_spec: pass
        vc_preflight: pass
      source: ensure_contract_snapshot_auto
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