Skip to content

docs: hook の strict guard と best-effort telemetry の責務境界を監査・文書化する #923

Closed

Description

@squne121

Machine-Readable Contract

contract_schema_version: v1
issue_kind: implementation
parent_issue: "none"
goal_ref: "hook ごとに blocker / warning / telemetry を明文化し、AI agent が hook failure を作業停止条件として誤判断しないようにする"
change_kind: mixed

Parent Issue

none

Parent Goal Ref

  • Goal: hook ごとに blocker / warning / telemetry を明文化し、AI agent が hook failure を作業停止条件として誤判断しないようにする
  • Desired Destination: 単独改善。.claude/settings.json の runtime hook topology と docs/dev/hook-boundaries.md 内 manifest を厳密照合する「境界契約のロックファイル」を確立する

Current Validated Scope

  • docs/dev/hook-boundaries.md を新規追加し、hook_boundaries_manifest_v1 を正本として hook 分類・fail policy・exit code / stdout / stderr contract・agent routing を記述する
  • scripts/check_hook_boundaries.py を新規追加し、.claude/settings.json と manifest を構造照合する
  • tests/test_hook_boundaries_doc.py を新規追加し、checker の回帰(特に PostToolUse の node + args identity)を固定する

Remaining Parent Gaps

なし(単独 Issue。parent gap なし)

Background

.claude/settings.json には secret boundary guard / Japanese prose guard / rtk boundary shadow guard / session manifest coordinator / precompact loop state save など複数 hook が設定されている。

strict guard と best-effort telemetry が混在する現状では、AI agent がどの hook failure を作業停止条件として扱うべきか迷いやすい。これにより、telemetry hook の失敗で不必要な停止や、secret boundary hook の失敗でも継続するような誤挙動が生じうる。

本 Issue は過去の hook 境界実装(#412/#495 secret guard、#651/#694 session manifest coordinator、#657/#702 Japanese prose guard、#823/#875 rtk shadow guard、#797/#852 PreCompact / stdout policy)の棚卸しでもある。敵対的レビュー(#923 コメント)で指摘された通り、prose 表に分類を閉じ込め .claude/settings.json との一致確認を「hook 名の grep」程度で済ませる実装は受け入れない。docs は機械可読 manifest を正本とし、checker は .claude/settings.json から抽出した hook topology と manifest を構造照合する。

外部仕様上の重要な前提:

  • Claude Code では PreToolUse の exit 2 は tool call を block、Stop は Claude 停止を防ぎ、SubagentStop は subagent 停止を防ぎ、PreCompact は compaction を block する。PostToolUse は tool 実行後のため block できず stderr を見せるのみ(Claude Code hooks reference)。
  • したがって telemetry / fail-open hook が「常に exit 0」とする contract には外部仕様上の理由がある。docs はこの理由を明記する。
  • Codex CLI は Claude Code と hook semantics の output-field parity を持たない(openai/codex#19385)。判断表は Claude Code と Codex を分離し、Codex の parity を過剰主張しない。

Outcome

docs/dev/hook-boundaries.md が存在し、hook_boundaries_manifest_v1 YAML block を正本として各 hook の分類(blocker / warning / mode_dependent / telemetry)・fail policy(fail_closed / fail_open)・exit code contract・stdout / stderr contract・agent routing を機械可読に記述している。scripts/check_hook_boundaries.py が .claude/settings.json から抽出した hook topology と docs 内 manifest を構造照合し、drift を検出して fail する。両者が一致するとき checker が exit 0 で通る状態。

In Scope

  • docs/dev/hook-boundaries.md を追加する
    • hook_boundaries_manifest_v1 YAML block を正本として記述する(prose 表は manifest からの補助表として併記)
    • 各 hook の分類: blocker / warning / mode_dependent / telemetry
    • fail policy: fail_closed / fail_open
    • exit code contract(script の exit code と Claude event 側の exit 2 semantics の両方)
    • stdout / stderr contract(raw command / raw path / secret-like value / manifest body を出さない契約を含む)
    • agent routing(作業停止すべきか継続すべきか)
    • session_manifest_coordinator.sh の best-effort(fail-open)性と、diagnostic artifact 欠落時は follow-up が必要になりうる旨を明記する
    • secret_boundary_guard.sh の fail-closed 性を明記する
    • guard-japanese-prose.sh を mode_dependent(default shadow / GUARD_JAPANESE_PROSE_MODE=enforce 時のみ exit 2 block)として記述する
    • save_loop_state_before_compaction.sh の exit_always: 0 / blocks_agent: false を明記する
    • Claude Code 用と Codex CLI 用の判断表を別表として追加し、Codex は Claude Code parity を過剰主張しない
  • scripts/check_hook_boundaries.py を追加する(checker 正本)
    • .claude/settings.json と docs/dev/hook-boundaries.md の hook 一覧・identity が一致することを検証する
    • handler identity を command と args の両方から解決する(PostToolUse の command: "node" + args 内 hook script を取り逃がさない)
    • event / matcher / handler_id / timeout / classification / agent_action を比較する
  • tests/test_hook_boundaries_doc.py を追加する(checker の回帰固定)
    • command == "node" かつ args に hook script が入る PostToolUse を fixture に含める

Out of Scope

  • hook の実装変更(分類・文書化のみ)
  • .claude/settings.json の hook 追加・削除・matcher / timeout 変更
  • hook の自動テスト実行や runtime 発火証跡の取得(docs と静的照合に限定)
  • secret-policy / session-recording-policy 等、別 docs の責務への越境編集

Acceptance Criteria

  • AC1: hook failure 時に agent が停止すべきか継続すべきか判断できる一覧が存在する
  • AC2: best-effort telemetry hook(session_manifest_coordinator.sh / generate_session_manifest_from_hook.mjs / save_loop_state_before_compaction.sh / rtk_boundary_shadow_guard.sh)は作業 blocker にしないことが明記される
  • AC3: secret / credential boundary hook(secret_boundary_guard.sh)は fail-closed のまま維持されることが明記される
  • AC4: .claude/settings.json と docs の hook 一覧・identity が一致することを検証するテストまたは checker が通る
  • AC5: docs は prose table だけでなく hook_boundaries_manifest_v1 YAML block を含み、checker はこの manifest を入力正本にする
  • AC6: checker は hook identity を command と args の両方から解決する(PostToolUse の node ラッパーを取り逃がさない)
  • AC7: checker は event / matcher / handler_id / timeout / classification / agent_action を比較し、いずれかの drift で fail する
  • AC8: guard-japanese-prose.sh は mode_dependent として記述され、default shadow(exit 0)と GUARD_JAPANESE_PROSE_MODE=enforce(exit 2 block)が分離される
  • AC9: Claude Code と Codex CLI の判断表は別表にし、Codex は Claude Code parity を過剰主張しない
  • AC10: telemetry hook failure は task blocker ではないが、diagnostic artifact 欠落として記録・報告される旨が明記される

Verification Commands

# AC1
# baseline-expect: fail
$ rg -n "blocker|telemetry" docs/dev/hook-boundaries.md

# AC2
# baseline-expect: fail
$ rg -n "fail.open|best.effort" docs/dev/hook-boundaries.md

# AC3
# baseline-expect: fail
$ rg -n "secret_boundary|fail.closed" docs/dev/hook-boundaries.md

# AC4
# baseline-expect: fail
$ uv run pytest tests/test_hook_boundaries_doc.py -v

# AC5
# baseline-expect: fail
$ rg -n "hook_boundaries_manifest_v1" docs/dev/hook-boundaries.md

# AC6
# baseline-expect: fail
$ rg -n "args" scripts/check_hook_boundaries.py

# AC7
# baseline-expect: fail
$ rg -n "classification|agent_action|handler_id|timeout" docs/dev/hook-boundaries.md

# AC8
# baseline-expect: fail
$ rg -n "mode_dependent" docs/dev/hook-boundaries.md

# AC9
# baseline-expect: fail
$ rg -n "Codex" docs/dev/hook-boundaries.md

# AC10
# baseline-expect: fail
$ rg -n "diagnostic|follow.up" docs/dev/hook-boundaries.md

Runtime Verification Applicability

decision: not_applicable
reason: "docs 追加・静的 checker・pytest であり、interactive game runtime の発火証跡を成功条件に含まない。hook の runtime 発火検証は本 Issue の Out of Scope。"

Allowed Paths

  • docs/dev/hook-boundaries.md
  • scripts/check_hook_boundaries.py
  • tests/test_hook_boundaries_doc.py

Stop Conditions

  • Allowed Paths 外の変更が必要と判明した場合
  • In Scope の固定契約(キー集合・スキーマ・型定義)の変更が必要になった場合
  • 新規 Issue の起票が必要と判断した場合(スコープ分割が発生する場合)
  • 後続 Phase / 別スコープへの波及が判明した場合
  • nested SubAgent delegation が必要になった場合
  • 外部サービス利用・権限昇格・既存テスト大規模改変が必要になった場合
  • checker が .claude/settings.json の hook 実装変更を要求し始めた場合(本 Issue は文書化のみで実装変更は Out of Scope)

Required Skills

  • POSIX shell / hook script の exit code semantics
  • Claude Code hook 仕様(PreToolUse / PostToolUse / Stop / SubagentStop / PreCompact の exit 2 semantics)
  • Python(.claude/settings.json parse・構造照合・pytest)
  • YAML(manifest block の設計)

Scope Delta(任意)

N/A

Activity

  1. added
    documentation
    on Jun 14, 2026
  2. squne121 commented on Jun 17, 2026

    @squne121
    OwnerAuthor

    敵対的レビュー結論

    #923 の方向性は妥当です。ただし、現状の Issue 文面のまま実装すると 「それっぽい運用ドキュメント」はできるが、agent が実際に誤停止・誤継続しないことは保証できません。特に危険なのは、hook の分類を prose 表に閉じ込め、.claude/settings.json との一致確認を「hook名の grep」程度で済ませる実装です。

    #923 は docs/dev/hook-boundaries.md を追加し、各 hook の分類、exit code、stdout/stderr、agent routing を一覧化し、.claude/settings.json と docs の hook 一覧一致をテストまたは checker で固定する Issue です。Allowed Paths は docs と checker/test に限定されています。 #923 自体にはコメントがありません。

    関連Issue / PR / コメントから見た前提

    #923 は単独の docs Issue ですが、実質的には過去の hook 境界実装の棚卸しです。関連する主要PRは次の通りです。

    PR #495 は #412 の secret boundary guard 実装で、secret_boundary_guard.sh を PreToolUse に配線し、printenv、env、gh secret、.env 読み取り、credential file access を exit code 2 でブロックし、stderr は構造的メッセージに限定する設計です。 現行実装でも exit code は 0 = allow、2 = block と明示され、jq 不在や malformed stdin は fail-closed で exit 2 です。

    PR #694 は #651 の session manifest coordinator 実装で、Stop/SubagentStop の entry point を session_manifest_coordinator.sh に集約し、guard → producer を直列実行しつつ、どの経路でも exit 0 で agent 作業をブロックしない方針です。 PR #694 のレビューコメントでは、直接 script に JSON を pipe した smoke test は「実 Claude Code Stop/SubagentStop 発火の証跡ではない」として REQUEST_CHANGES が出ています。これは #923 にも効く重要な先例で、docs に「Claude/Codex 判断表」を書くだけでは runtime hook 発火証跡の代替になりません。

    PR #702 は #657 の Japanese prose guard shadow/enforce mode 実装です。GUARD_JAPANESE_PROSE_MODE 未設定または shadow では block せず exit 0、enforce では exit 2、不正値は shadow として扱う設計です。 現行 hook も同じ分岐を持ち、Issue #923 の分類表では単純な blocker ではなく mode-dependent guard として扱う必要があります。

    PR #875 は #823 の rtk boundary shadow guard 実装で、mutating git/gh/dependency mutation を JSONL に記録するが常に exit 0 で通過する shadow hook です。 現行実装も「block は一切行わない」「常に exit 0」「fail-open」と明記しています。

    PR #852 は #797 の hook stdout policy / PreCompact / payload digest throttle 実装です。PreCompact hook は fail-open、stdout empty、compaction を block しない設計です。 ただし PR #852 のレビューコメントでは Allowed Paths 違反で REQUEST_CHANGES が出ています。#923 でも checker/test の配置が Allowed Paths 外に漏れると同じ失敗を再発します。

    外部仕様との照合で見える重大リスク

    Claude Code の公式 hook 仕様では、command hook は stdin で JSON context を受け取り、exit code によって block / non-blocking error / JSON decision が分かれます。exit 0 の stdout JSON は処理されますが、exit 2 は blocking error で、exit 1 は多くの event で non-blocking errorです。(Claude Code) (Claude Code) したがって、#923 の docs は「script の exit code」だけでなく Claude event 側の exit 2 semantics を併記しないと不正確です。

    特に Claude Code では PreToolUse の exit 2 は tool call を block し、Stop は Claude の停止を防ぎ、SubagentStop は subagent の停止を防ぎ、PreCompact は compaction を block します。一方、PostToolUse は tool が既に実行済みなので block できず、stderr を Claude に見せるだけです。(Claude Code) これは #923 の中核です。session_manifest_coordinator.sh と save_loop_state_before_compaction.sh が「常に exit 0」としている理由は、外部仕様上それぞれ Stop/SubagentStop/PreCompact を block できてしまうからです。

    Claude Code の security considerations では command hooks がユーザー権限で実行されるため、入力検証、shell variable quoting、path traversal blocking、absolute path、sensitive file skip が推奨されています。(Claude Code) そのため #923 のドキュメントは「agent routing」だけでなく、stderr に raw command/path/secret を出さない contract も blocker/warning/telemetry ごとに固定すべきです。

    Codex 側は Claude Code と同一視できません。OpenAI は Codex 運用について、bounded environment、sandboxing、approval policy、network policy、agent-native telemetry を安全制御の柱として説明しています。(OpenAI) また openai/codex #19385 では、Codex は Claude-style hook discovery/config shape を持つが、全 hook event で Claude Code と同等の output-field parity はなく、PreToolUse は context injection ではなく guardrail/blocking hook として扱うべきだと指摘されています。(GitHub) docs/dev/session-recording-policy.md も、Codex の hook structural validation は runtime active hook state や trust state の証跡ではなく、PreToolUse/PermissionRequest は予防層であって security boundary ではない、と既に明記しています。

    Blockers

    B1: checker が command だけを見る実装だと PostToolUse hook を取り逃がす

    .claude/settings.json の PostToolUse は command: "node" で、実際の hook script は args に ${CLAUDE_PROJECT_DIR}/.claude/hooks/generate_session_manifest_from_hook.mjs として入っています。 したがって、checker が hook["command"] の文字列だけを docs と照合すると、重要な telemetry producer を node としか認識できず、hook identity が崩れます。

    要求すべき正規化は event + matcher + handler index + type + command + args + timeout です。さらに handler identity は、command に hook path がある場合と、args に hook path がある場合の両方を解決する必要があります。

    B2: guard-japanese-prose.sh を blocker と断定すると誤分類になる

    この hook はデフォルト shadow です。未設定または shadow では exit 0 で通過し、would-block 判定を JSONL に記録します。enforce のときだけ exit 2 で block します。 テストも default shadow、shadow no-block、enforce block を固定しています。

    #923 の分類欄は warning または mode-dependent を許可すべきです。単純な enum blocker|warning|telemetry だけでは不十分です。最低限、classification: warning_by_default、blocking_condition: GUARD_JAPANESE_PROSE_MODE=enforce、agent_action_shadow: continue、agent_action_enforce_failure: stop_and_repair_payload のように分けるべきです。

    B3: session_manifest_coordinator.sh は telemetry だが「無視してよい失敗」ではない

    coordinator は Stop/SubagentStop で guard → producer を直列実行し、guard 失敗時は producer を抑止して exit 0、producer 失敗時も exit 0 です。 ただし内部には scope rollup capture の処理があり、PyYAML 不在時に hook_unavailable record を書き、capture required 時の fail-closed preparation を示す stderr を出します。

    したがって routing は continue work でよいが、docs には telemetry failure is not a task blocker と同時に、diagnostic artifact absence may require human follow-up を書くべきです。best-effort を「観測しなくてよい」に読み替えると、#651/#694 の runtime verification 指摘を再発します。

    B4: PreCompact は外部仕様上 block 可能なので、fail-open contract を強く固定する必要がある

    Claude Code では PreCompact の exit 2 は compaction を block します。(Claude Code) 現行 save_loop_state_before_compaction.sh は stdout empty、stderr diagnostic、exit always 0、compaction must not be blocked と明記しています。 mkdir / python / payload build / rename failure も exit 0 で fail-open します。

    #923 の docs がここを弱く書くと、将来の修正で set -euo pipefail による accidental exit 1/2 が compaction 体験を破壊します。checker は少なくとも docs 側で exit_always: 0 と blocks_agent: false を固定すべきです。

    B5: docs と .claude/settings.json の一致確認は「一覧が同じ」だけでは足りない

    .claude/settings.json には PreToolUse が3本、Stop/SubagentStop が coordinator、PostToolUse が node wrapper、PreCompact が loop-state saver として登録されています。 これを docs で一覧化するだけでは、matcher drift、timeout drift、args drift、duplicate handler、event 移動を検出できません。

    checker の fail 条件は次まで必要です。

    fail_conditions:
      - settings hook exists but docs entry missing
      - docs entry exists but settings hook missing
      - same event/matcher/handler appears twice in docs
      - command+args normalized identity mismatch
      - timeout mismatch
      - classification missing or outside allowed vocabulary
      - blocker hook lacks exit_code 2 contract
      - telemetry hook lacks fail-open / non-blocking routing
      - stdout/stderr contract missing
      - agent_action missing
    

    推奨される hook 分類

    Event | Matcher | Handler | 分類 | agent routing -- | -- | -- | -- | -- PreToolUse | `Bash | Read | Write | Edit PreToolUse | `Bash | Write | Edit | MultiEdit` PreToolUse | Bash | rtk_boundary_shadow_guard.sh | telemetry / warning | 常に継続。JSONL を誤検知・違反傾向の監査に使う。 Stop | n/a | session_manifest_coordinator.sh | telemetry / fail-open | 継続。producer/guard 失敗は作業 blocker にしない。 SubagentStop | n/a | session_manifest_coordinator.sh | telemetry / fail-open | 継続。subagent 終了を妨げない。 PostToolUse | `Bash | Edit | Write` | node ... generate_session_manifest_from_hook.mjs PreCompact | n/a | save_loop_state_before_compaction.sh | telemetry / snapshot / fail-open | compaction を止めない。artifact 欠落は follow-up diagnostic。

    この分類は現行実装と一致します。secret guard は blocked pattern と sensitive path を exit 2 にしています。 rtk guard は raw command を保存せず redacted preview と hash を JSONL に書き、最後は常に exit 0 です。 generate_session_manifest_from_hook.mjs は stdout silent、stderr diagnostic、exit 0 always、producer failure non-blocking と明記しています。

    docs/dev/hook-boundaries.md の推奨構造

    prose 表だけではなく、機械可読 block を正本にしてください。例:

    hook_boundaries_manifest_v1:
      source_settings: ".claude/settings.json"
      entries:
        - event: PreToolUse
          matcher: "Bash|Read|Write|Edit|Grep|Glob"
          handler_id: ".claude/hooks/secret_boundary_guard.sh"
          command: "${CLAUDE_PROJECT_DIR}/.claude/hooks/secret_boundary_guard.sh"
          args: []
          timeout: 10
          classification: blocker
          fail_policy: fail_closed
          exit_code_contract:
            "0": allow
            "2": block
          stdout_contract: empty
          stderr_contract: generic_structural_message_no_raw_command_no_raw_path_no_secret
          agent_action_on_failure: stop_current_tool_call_and_remove_secret_boundary_violation
    
    - event: PreToolUse
      matcher: "Bash|Write|Edit|MultiEdit"
      handler_id: ".claude/hooks/guard-japanese-prose.sh"
      command: "${CLAUDE_PROJECT_DIR}/.claude/hooks/guard-japanese-prose.sh"
      args: []
      timeout: 15
      classification: mode_dependent
      default_mode: shadow
      blocking_condition: "GUARD_JAPANESE_PROSE_MODE=enforce"
      exit_code_contract:
        "0": allow_or_shadow_record
        "2": block_only_in_enforce
      stdout_contract: empty
      stderr_contract: diagnostic_no_secret_material
      agent_action_on_shadow: continue
      agent_action_on_enforce_failure: stop_and_repair_japanese_prose
    
    - event: PostToolUse
      matcher: "Bash|Edit|Write"
      handler_id: ".claude/hooks/generate_session_manifest_from_hook.mjs"
      command: "node"
      args:
        - "${CLAUDE_PROJECT_DIR}/.claude/hooks/generate_session_manifest_from_hook.mjs"
      timeout: 60
      classification: telemetry
      fail_policy: fail_open
      exit_code_contract:
        "0": always
      stdout_contract: empty
      stderr_contract: diagnostic_no_manifest_body_no_absolute_paths
      agent_action_on_failure: continue_and_note_manifest_generation_failure
    

    この block を checker の入力正本にし、Markdown 表はこの YAML から人間が読む補助表として扱うのが安全です。

    checker / test の実装方針

    scripts/check_hook_boundaries.py を推奨します。理由は docs と .claude/settings.json の構造照合に Python が向いており、Issue の Verification Command でも uv run python3 scripts/check_hook_boundaries.py が許可されているためです。

    実装の要点:

    def normalize_handler(event: str, matcher: str | None, hook: dict) -> dict:
    command = hook.get("command", "")
    args = hook.get("args") or []
    timeout = hook.get("timeout")

    handler_id = command
    for token in [command, *map(str, args)]:
        marker = ".claude/hooks/"
        if marker in token:
            handler_id = token[token.index(marker):]
            break
    
    return {
        "event": event,
        "matcher": matcher or "",
        "type": hook.get("type"),
        "handler_id": handler_id,
        "command": command,
        "args": args,
        "timeout": timeout,
    }
    

    必ず command == "node" かつ args に hook script が入る PostToolUse をテスト fixture に含めてください。ここを落とす checker は #923 の AC4 を満たしているように見えて、実際には最重要 telemetry hook を未検証にします。

    受け入れ条件の強化案

    現行ACは方向性としては足りますが、敵対的には曖昧です。次の文言を Issue または実装PR説明に入れるべきです。

    additional_acceptance_criteria:

    • AC5: docs は prose table だけでなく hook_boundaries_manifest_v1 YAML block を含む
    • AC6: checker は command と args の両方から hook identity を解決する
    • AC7: checker は event/matcher/handler_id/timeout/classification/agent_action を比較する
    • AC8: guard-japanese-prose は mode_dependent として記述され、default shadow と enforce blocking が分離される
    • AC9: Claude Code と Codex CLI の判断表は別表にし、Codex は Claude Code parity を過剰主張しない
    • AC10: telemetry hook failure は task blocker ではないが、diagnostic artifact 欠落として記録・報告される

    最終判定

    #923 は実装すべきです。ただし、PR レビューでは次を merge blocker として扱うべきです。

    1. docs/dev/hook-boundaries.md が prose 表のみで、機械可読 manifest を持たない。

    2. checker が command だけを比較し、args 内 hook script を見ない。

    3. guard-japanese-prose.sh を無条件 blocker または無条件 telemetry として分類している。

    4. Claude Code と Codex の hook semantics を同一表で混在させている。

    5. Stop / SubagentStop / PreCompact が外部仕様上 block 可能である事実を明記せず、現行実装の exit 0 always contract を弱く扱っている。

    6. stderr contract に「raw command / raw path / secret-like value / manifest body を出さない」が入っていない。

    7. PR feat: Claude/Codex hook stdout policy、PreCompact state 保存、payload digest throttle を fixture 検証付きで整備する #852 のような Allowed Paths 違反を防ぐための file placement 確認がない。

    この Issue の高品質な完了形は、「AI agent 向けの読み物」ではなく、.claude/settings.json から抽出した runtime hook topology と docs 内 manifest を厳密照合する 境界契約のロックファイル です。

    ## 敵対的レビュー結論

    #923 の方向性は妥当です。ただし、現状の Issue 文面のまま実装すると 「それっぽい運用ドキュメント」はできるが、agent が実際に誤停止・誤継続しないことは保証できません。特に危険なのは、hook の分類を prose 表に閉じ込め、.claude/settings.json との一致確認を「hook名の grep」程度で済ませる実装です。

    #923 は docs/dev/hook-boundaries.md を追加し、各 hook の分類、exit code、stdout/stderr、agent routing を一覧化し、.claude/settings.json と docs の hook 一覧一致をテストまたは checker で固定する Issue です。Allowed Paths は docs と checker/test に限定されています。 #923 自体にはコメントがありません。

    関連Issue / PR / コメントから見た前提

    #923 は単独の docs Issue ですが、実質的には過去の hook 境界実装の棚卸しです。関連する主要PRは次の通りです。

    PR #495 は #412 の secret boundary guard 実装で、secret_boundary_guard.sh を PreToolUse に配線し、printenv、env、gh secret、.env 読み取り、credential file access を exit code 2 でブロックし、stderr は構造的メッセージに限定する設計です。 現行実装でも exit code は 0 = allow、2 = block と明示され、jq 不在や malformed stdin は fail-closed で exit 2 です。

    PR #694 は #651 の session manifest coordinator 実装で、Stop/SubagentStop の entry point を session_manifest_coordinator.sh に集約し、guard → producer を直列実行しつつ、どの経路でも exit 0 で agent 作業をブロックしない方針です。 PR #694 のレビューコメントでは、直接 script に JSON を pipe した smoke test は「実 Claude Code Stop/SubagentStop 発火の証跡ではない」として REQUEST_CHANGES が出ています。これは #923 にも効く重要な先例で、docs に「Claude/Codex 判断表」を書くだけでは runtime hook 発火証跡の代替になりません。

    PR #702 は #657 の Japanese prose guard shadow/enforce mode 実装です。GUARD_JAPANESE_PROSE_MODE 未設定または shadow では block せず exit 0、enforce では exit 2、不正値は shadow として扱う設計です。 現行 hook も同じ分岐を持ち、Issue #923 の分類表では単純な blocker ではなく mode-dependent guard として扱う必要があります。

    PR #875 は #823 の rtk boundary shadow guard 実装で、mutating git/gh/dependency mutation を JSONL に記録するが常に exit 0 で通過する shadow hook です。 現行実装も「block は一切行わない」「常に exit 0」「fail-open」と明記しています。

    PR #852 は #797 の hook stdout policy / PreCompact / payload digest throttle 実装です。PreCompact hook は fail-open、stdout empty、compaction を block しない設計です。 ただし PR #852 のレビューコメントでは Allowed Paths 違反で REQUEST_CHANGES が出ています。#923 でも checker/test の配置が Allowed Paths 外に漏れると同じ失敗を再発します。

    外部仕様との照合で見える重大リスク

    Claude Code の公式 hook 仕様では、command hook は stdin で JSON context を受け取り、exit code によって block / non-blocking error / JSON decision が分かれます。exit 0 の stdout JSON は処理されますが、exit 2 は blocking error で、exit 1 は多くの event で non-blocking errorです。([Claude Code]1) ([Claude Code]1) したがって、#923 の docs は「script の exit code」だけでなく Claude event 側の exit 2 semantics を併記しないと不正確です。

    特に Claude Code では PreToolUse の exit 2 は tool call を block し、Stop は Claude の停止を防ぎ、SubagentStop は subagent の停止を防ぎ、PreCompact は compaction を block します。一方、PostToolUse は tool が既に実行済みなので block できず、stderr を Claude に見せるだけです。([Claude Code]1) これは #923 の中核です。session_manifest_coordinator.sh と save_loop_state_before_compaction.sh が「常に exit 0」としている理由は、外部仕様上それぞれ Stop/SubagentStop/PreCompact を block できてしまうからです。

    Claude Code の security considerations では command hooks がユーザー権限で実行されるため、入力検証、shell variable quoting、path traversal blocking、absolute path、sensitive file skip が推奨されています。([Claude Code]1) そのため #923 のドキュメントは「agent routing」だけでなく、stderr に raw command/path/secret を出さない contract も blocker/warning/telemetry ごとに固定すべきです。

    Codex 側は Claude Code と同一視できません。OpenAI は Codex 運用について、bounded environment、sandboxing、approval policy、network policy、agent-native telemetry を安全制御の柱として説明しています。([OpenAI]2) また openai/codex #19385 では、Codex は Claude-style hook discovery/config shape を持つが、全 hook event で Claude Code と同等の output-field parity はなく、PreToolUse は context injection ではなく guardrail/blocking hook として扱うべきだと指摘されています。([GitHub]3) docs/dev/session-recording-policy.md も、Codex の hook structural validation は runtime active hook state や trust state の証跡ではなく、PreToolUse/PermissionRequest は予防層であって security boundary ではない、と既に明記しています。

    Blockers

    B1: checker が command だけを見る実装だと PostToolUse hook を取り逃がす

    .claude/settings.json の PostToolUse は command: "node" で、実際の hook script は args に ${CLAUDE_PROJECT_DIR}/.claude/hooks/generate_session_manifest_from_hook.mjs として入っています。 したがって、checker が hook["command"] の文字列だけを docs と照合すると、重要な telemetry producer を node としか認識できず、hook identity が崩れます。

    要求すべき正規化は event + matcher + handler index + type + command + args + timeout です。さらに handler identity は、command に hook path がある場合と、args に hook path がある場合の両方を解決する必要があります。

    B2: guard-japanese-prose.sh を blocker と断定すると誤分類になる

    この hook はデフォルト shadow です。未設定または shadow では exit 0 で通過し、would-block 判定を JSONL に記録します。enforce のときだけ exit 2 で block します。 テストも default shadow、shadow no-block、enforce block を固定しています。

    #923 の分類欄は warning または mode-dependent を許可すべきです。単純な enum blocker|warning|telemetry だけでは不十分です。最低限、classification: warning_by_default、blocking_condition: GUARD_JAPANESE_PROSE_MODE=enforce、agent_action_shadow: continue、agent_action_enforce_failure: stop_and_repair_payload のように分けるべきです。

    B3: session_manifest_coordinator.sh は telemetry だが「無視してよい失敗」ではない

    coordinator は Stop/SubagentStop で guard → producer を直列実行し、guard 失敗時は producer を抑止して exit 0、producer 失敗時も exit 0 です。 ただし内部には scope rollup capture の処理があり、PyYAML 不在時に hook_unavailable record を書き、capture required 時の fail-closed preparation を示す stderr を出します。

    したがって routing は continue work でよいが、docs には telemetry failure is not a task blocker と同時に、diagnostic artifact absence may require human follow-up を書くべきです。best-effort を「観測しなくてよい」に読み替えると、#651/#694 の runtime verification 指摘を再発します。

    B4: PreCompact は外部仕様上 block 可能なので、fail-open contract を強く固定する必要がある

    Claude Code では PreCompact の exit 2 は compaction を block します。(Claude Code) 現行 save_loop_state_before_compaction.sh は stdout empty、stderr diagnostic、exit always 0、compaction must not be blocked と明記しています。 mkdir / python / payload build / rename failure も exit 0 で fail-open します。

    #923 の docs がここを弱く書くと、将来の修正で set -euo pipefail による accidental exit 1/2 が compaction 体験を破壊します。checker は少なくとも docs 側で exit_always: 0 と blocks_agent: false を固定すべきです。

    B5: docs と .claude/settings.json の一致確認は「一覧が同じ」だけでは足りない

    .claude/settings.json には PreToolUse が3本、Stop/SubagentStop が coordinator、PostToolUse が node wrapper、PreCompact が loop-state saver として登録されています。 これを docs で一覧化するだけでは、matcher drift、timeout drift、args drift、duplicate handler、event 移動を検出できません。

    checker の fail 条件は次まで必要です。

    fail_conditions:
      - settings hook exists but docs entry missing
      - docs entry exists but settings hook missing
      - same event/matcher/handler appears twice in docs
      - command+args normalized identity mismatch
      - timeout mismatch
      - classification missing or outside allowed vocabulary
      - blocker hook lacks exit_code 2 contract
      - telemetry hook lacks fail-open / non-blocking routing
      - stdout/stderr contract missing
      - agent_action missing

    推奨される hook 分類

    Event Matcher Handler 分類 agent routing
    PreToolUse `Bash Read Write Edit Grep Glob` secret_boundary_guard.sh blocker / fail-closed exit 2 は停止。secret/path/credential 操作を修正してから再試行。
    PreToolUse `Bash Write Edit MultiEdit` guard-japanese-prose.sh warning_by_default / blocker_when_enforce shadow は継続、enforce exit 2 は本文修復。
    PreToolUse Bash rtk_boundary_shadow_guard.sh telemetry / warning 常に継続。JSONL を誤検知・違反傾向の監査に使う。
    Stop n/a session_manifest_coordinator.sh telemetry / fail-open 継続。producer/guard 失敗は作業 blocker にしない。
    SubagentStop n/a session_manifest_coordinator.sh telemetry / fail-open 継続。subagent 終了を妨げない。
    PostToolUse `Bash Edit Write` node ... generate_session_manifest_from_hook.mjs telemetry / fail-open tool は既に実行済み。failure は diagnostic として扱う。
    PreCompact n/a save_loop_state_before_compaction.sh telemetry / snapshot / fail-open compaction を止めない。artifact 欠落は follow-up diagnostic。

    この分類は現行実装と一致します。secret guard は blocked pattern と sensitive path を exit 2 にしています。 rtk guard は raw command を保存せず redacted preview と hash を JSONL に書き、最後は常に exit 0 です。 generate_session_manifest_from_hook.mjs は stdout silent、stderr diagnostic、exit 0 always、producer failure non-blocking と明記しています。

    docs/dev/hook-boundaries.md の推奨構造

    prose 表だけではなく、機械可読 block を正本にしてください。例:

    hook_boundaries_manifest_v1:
      source_settings: ".claude/settings.json"
      entries:
        - event: PreToolUse
          matcher: "Bash|Read|Write|Edit|Grep|Glob"
          handler_id: ".claude/hooks/secret_boundary_guard.sh"
          command: "${CLAUDE_PROJECT_DIR}/.claude/hooks/secret_boundary_guard.sh"
          args: []
          timeout: 10
          classification: blocker
          fail_policy: fail_closed
          exit_code_contract:
            "0": allow
            "2": block
          stdout_contract: empty
          stderr_contract: generic_structural_message_no_raw_command_no_raw_path_no_secret
          agent_action_on_failure: stop_current_tool_call_and_remove_secret_boundary_violation
    
        - event: PreToolUse
          matcher: "Bash|Write|Edit|MultiEdit"
          handler_id: ".claude/hooks/guard-japanese-prose.sh"
          command: "${CLAUDE_PROJECT_DIR}/.claude/hooks/guard-japanese-prose.sh"
          args: []
          timeout: 15
          classification: mode_dependent
          default_mode: shadow
          blocking_condition: "GUARD_JAPANESE_PROSE_MODE=enforce"
          exit_code_contract:
            "0": allow_or_shadow_record
            "2": block_only_in_enforce
          stdout_contract: empty
          stderr_contract: diagnostic_no_secret_material
          agent_action_on_shadow: continue
          agent_action_on_enforce_failure: stop_and_repair_japanese_prose
    
        - event: PostToolUse
          matcher: "Bash|Edit|Write"
          handler_id: ".claude/hooks/generate_session_manifest_from_hook.mjs"
          command: "node"
          args:
            - "${CLAUDE_PROJECT_DIR}/.claude/hooks/generate_session_manifest_from_hook.mjs"
          timeout: 60
          classification: telemetry
          fail_policy: fail_open
          exit_code_contract:
            "0": always
          stdout_contract: empty
          stderr_contract: diagnostic_no_manifest_body_no_absolute_paths
          agent_action_on_failure: continue_and_note_manifest_generation_failure

    この block を checker の入力正本にし、Markdown 表はこの YAML から人間が読む補助表として扱うのが安全です。

    checker / test の実装方針

    scripts/check_hook_boundaries.py を推奨します。理由は docs と .claude/settings.json の構造照合に Python が向いており、Issue の Verification Command でも uv run python3 scripts/check_hook_boundaries.py が許可されているためです。

    実装の要点:

    def normalize_handler(event: str, matcher: str | None, hook: dict) -> dict:
        command = hook.get("command", "")
        args = hook.get("args") or []
        timeout = hook.get("timeout")
    
        handler_id = command
        for token in [command, *map(str, args)]:
            marker = ".claude/hooks/"
            if marker in token:
                handler_id = token[token.index(marker):]
                break
    
        return {
            "event": event,
            "matcher": matcher or "",
            "type": hook.get("type"),
            "handler_id": handler_id,
            "command": command,
            "args": args,
            "timeout": timeout,
        }

    必ず command == "node" かつ args に hook script が入る PostToolUse をテスト fixture に含めてください。ここを落とす checker は #923 の AC4 を満たしているように見えて、実際には最重要 telemetry hook を未検証にします。

    受け入れ条件の強化案

    現行ACは方向性としては足りますが、敵対的には曖昧です。次の文言を Issue または実装PR説明に入れるべきです。

    additional_acceptance_criteria:
      - AC5: docs は prose table だけでなく hook_boundaries_manifest_v1 YAML block を含む
      - AC6: checker は command と args の両方から hook identity を解決する
      - AC7: checker は event/matcher/handler_id/timeout/classification/agent_action を比較する
      - AC8: guard-japanese-prose は mode_dependent として記述され、default shadow と enforce blocking が分離される
      - AC9: Claude Code と Codex CLI の判断表は別表にし、Codex は Claude Code parity を過剰主張しない
      - AC10: telemetry hook failure は task blocker ではないが、diagnostic artifact 欠落として記録・報告される

    最終判定

    #923 は実装すべきです。ただし、PR レビューでは次を merge blocker として扱うべきです。

    1. docs/dev/hook-boundaries.md が prose 表のみで、機械可読 manifest を持たない。
    2. checker が command だけを比較し、args 内 hook script を見ない。
    3. guard-japanese-prose.sh を無条件 blocker または無条件 telemetry として分類している。
    4. Claude Code と Codex の hook semantics を同一表で混在させている。
    5. Stop / SubagentStop / PreCompact が外部仕様上 block 可能である事実を明記せず、現行実装の exit 0 always contract を弱く扱っている。
    6. stderr contract に「raw command / raw path / secret-like value / manifest body を出さない」が入っていない。
    7. PR feat: Claude/Codex hook stdout policy、PreCompact state 保存、payload digest throttle を fixture 検証付きで整備する #852 のような Allowed Paths 違反を防ぐための file placement 確認がない。

    この Issue の高品質な完了形は、「AI agent 向けの読み物」ではなく、.claude/settings.json から抽出した runtime hook topology と docs 内 manifest を厳密照合する 境界契約のロックファイル です。

  3. squne121 commented on Jun 17, 2026

    @squne121
    OwnerAuthor

    Refinement Loop: Approved

    The issue has been approved and is ready for implementation.

  4. squne121 commented on Jun 17, 2026

    @squne121
    OwnerAuthor

    CONTRACT_REVIEW_RESULT_V1

    CONTRACT_REVIEW_RESULT_V1:
      status: go
      generated_by: issue-contract-review
      generated_at: "2026-06-17T21:10:21Z"
      issue_url: "https://github.com/squne121/loop-protocol/issues/923"
      issue: 923
      repo: squne121/loop-protocol
      body_sha256: "sha256:37f39f452491cc05478417f19d88a3d5724d1cd751034c7ef906ca6a88bf1478"
      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
        blocked_reasons: []
        next_action: handoff_to_implement_issue
      worktree: .claude/worktrees/issue-923-hook-boundaries-doc
      branch: worktree-issue-923-hook-boundaries-doc
      allowed_paths:
        - docs/dev/hook-boundaries.md
        - scripts/check_hook_boundaries.py
        - tests/test_hook_boundaries_doc.py
      vc_preflight:
        summary:
          vc_expected_pass: 0
          vc_failed_as_expected: 10
          vc_human_judgment: 0
          vc_passed_unexpectedly: 0
          vc_unrunnable: 0
        classifications:
          - ac: AC1..AC3, AC5..AC10
            scope_class: baseline_fail_expected
            decision: go
            note: >
              docs-creation issue の既知偽陽性パターン。
              rg は対象ファイル未作成のため exit_code 2(file not found)。
              全 VC に # baseline-expect: fail アノテーション付き。
              feedback_docs_creation_contract_review: ignore-pattern / go 判断。
          - ac: AC4
            scope_class: baseline_fail_expected
            decision: go
            note: "tests/test_hook_boundaries_doc.py が未作成のため pytest exit 4 = expected baseline fail"
  5. squne121 commented on Jun 17, 2026

    @squne121
    OwnerAuthor

    IMPLEMENT_RESULT_V1

    IMPLEMENT_RESULT_V1:
      status: ok
      issue: 923
      pr_url: "https://github.com/squne121/loop-protocol/pull/976"
      pr_number: 976
      branch: worktree-issue-923-hook-boundaries-doc
      worktree: .claude/worktrees/issue-923-hook-boundaries-doc
      commit_sha: 1a8ed51d
      allowed_paths_compliance: true
      files_changed:
        - docs/dev/hook-boundaries.md
        - scripts/check_hook_boundaries.py
        - tests/test_hook_boundaries_doc.py
      vc_results:
        - ac: AC1
          command: "rg -n 'blocker|telemetry' docs/dev/hook-boundaries.md"
          result: pass
        - ac: AC2
          command: "rg -n 'fail.open|best.effort' docs/dev/hook-boundaries.md"
          result: pass
        - ac: AC3
          command: "rg -n 'secret_boundary|fail.closed' docs/dev/hook-boundaries.md"
          result: pass
        - ac: AC4
          command: "uv run pytest tests/test_hook_boundaries_doc.py -v"
          result: pass
          detail: "17 passed"
        - ac: AC5
          command: "rg -n 'hook_boundaries_manifest_v1' docs/dev/hook-boundaries.md"
          result: pass
        - ac: AC6
          command: "rg -n 'args' scripts/check_hook_boundaries.py"
          result: pass
        - ac: AC7
          command: "rg -n 'classification|agent_action|handler_id|timeout' docs/dev/hook-boundaries.md"
          result: pass
        - ac: AC8
          command: "rg -n 'mode_dependent' docs/dev/hook-boundaries.md"
          result: pass
        - ac: AC9
          command: "rg -n 'Codex' docs/dev/hook-boundaries.md"
          result: pass
        - ac: AC10
          command: "rg -n 'diagnostic|follow.up' docs/dev/hook-boundaries.md"
          result: pass
      implementation_notes: |
        settings.json の実際の hook topology を git history から確認した。
        worktree_scope_guard.sh が最新 commit(#971)で追加されており manifest に含めた。
        guard-japanese-prose.sh はハイフン含みファイル名のため handler_id を
        guard-japanese-prose(ハイフン)で統一した。
        session_manifest_coordinator は Stop / SubagentStop の 2 event に配置されるため
        照合キーを (handler_id, event) 複合キーとして設計した。
  6. squne121 commented on Jun 17, 2026

    @squne121
    OwnerAuthor

    IMPL_REVIEW_LOOP_RESULT_V1

    IMPL_REVIEW_LOOP_RESULT_V1:
      status: draft_pr_ready
      merge_ready: true
      issue_number: 923
      pr_url: "https://github.com/squne121/loop-protocol/pull/976"
      pr_number: 976
      branch: worktree-issue-923-hook-boundaries-doc
      iterations_completed: 1
      loop_verdict: APPROVE
      contract_snapshot_url: "https://github.com/squne121/loop-protocol/issues/923#issuecomment-4735562712"
    
      files_changed:
        - docs/dev/hook-boundaries.md
        - scripts/check_hook_boundaries.py
        - tests/test_hook_boundaries_doc.py
    
      ac_summary: all 10 AC pass
    
      ci_summary:
        pr_body_japanese_check: pass
        build: pass
        lint: pass
        typecheck: pass
        test: pass
        python_test: pass (17 passed)
        e2e: pass
        actionlint: pass
    
      allowed_paths_gate: pass
      merge_state: CLEAN
    
      termination_reason: approved
      next_action: human_merge_decision

    PR はマージ準備完了です。マージは人間が判断してください。

  7. added a commit that references this issue on Jun 17, 2026
  8. squne121 commented on Jun 17, 2026

    @squne121
    OwnerAuthor

    fix_delta 完了(B1〜B6 対応)

    PR #976 ブランチ worktree-issue-923-hook-boundaries-doc に B1〜B6 の修正を commit/push 済み。

    コミット: d03282a

    対応内容

    # ブロッカー 対応
    B1 checker が duplicate topology を黙殺する detect_duplicates_in_manifest / detect_duplicates_in_settings を追加。dict 化前に (handler_id, event) 重複を fail-closed で検出
    B2 classification / agent_action 比較が存在確認のみ validate_manifest_schema を追加。classification 語彙チェック・blocker/telemetry/mode_dependent 必須フィールド検証
    B3 exit contract が script contract と Claude event semantics を混同 manifest に script_exit_contract / claude_event_semantics の 2 層構造を追加
    B4 Codex CLI 表が断定的すぎる Codex CLI セクションを「この manifest は Claude Code を対象とする」に改訂
    B5 Claude event ごとの exit 2 効果が manifest にない 全 manifest entry に claude_event_semantics.exit_2_effect を追加し checker で validate
    B6 security/output contract の検証が浅い 全 manifest entry に redaction_contract を追加し stdout/stderr/redaction_contract を必須化

    検証結果

    • uv run pytest tests/test_hook_boundaries_doc.py -v — 33 passed(追加 14 + 既存 19)
    • uv run python3 scripts/check_hook_boundaries.py — exit 0(drift なし)
    • pnpm typecheck / pnpm lint / pnpm test (702 passed) / pnpm build — 全 PASS

    PR body 更新の注意

    PR #976 の本文更新は update_pr.py wrapper が LP052(英語必須セクション: Summary, Checks 等)と日本語比率チェック(英語見出し行が ratio=0.000)の矛盾で block されています。PR body の更新には prose_boundary_policy.py の HEADING_POLICY への追加または validate_pr_body.py の bilingual 形式対応が必要です(Allowed Paths 外)。人間による PR body 更新または Allowed Paths 外修正の許可をお願いします。

  9. squne121 commented on Jun 17, 2026

    @squne121
    OwnerAuthor

    IMPL_REVIEW_LOOP_RESULT_V1

    IMPL_REVIEW_LOOP_RESULT_V1:
      status: draft_pr_ready
      merge_ready: true
      issue_number: 923
      pr_url: "https://github.com/squne121/loop-protocol/pull/976"
      pr_number: 976
      branch: worktree-issue-923-hook-boundaries-doc
      iterations_completed: 2
      loop_verdict: APPROVE
    
      iteration_history:
        - iteration: 0
          verdict: APPROVE (bot)
          human_review: REQUEST_CHANGES (B1〜B6)
          action: fix_delta 委譲
        - iteration: 1
          verdict: APPROVE (bot)
          b1_resolved: duplicate detection 追加
          b2_resolved: manifest schema validation 追加
          b3_resolved: script_exit_contract / claude_event_semantics 2層化
          b4_resolved: Codex CLI parity 非主張に修正
          b5_resolved: 全 entry に claude_event_semantics.exit_2_effect 追加
          b6_resolved: stdout/stderr/redaction_contract 必須化
          tests: 33 passed (19 + 14 追加)
    
      files_changed:
        - docs/dev/hook-boundaries.md
        - scripts/check_hook_boundaries.py
        - tests/test_hook_boundaries_doc.py
    
      allowed_paths_gate: pass
      merge_state: CLEAN
      termination_reason: approved
      next_action: human_merge_decision

    PR はマージ準備完了です。マージは人間が判断してください。

  10. added a commit that references this issue on Jun 17, 2026
  11. squne121 commented on Jun 17, 2026

    @squne121
    OwnerAuthor

    post-merge-cleanup: 完了 (2026-06-18T00:28:00Z)

    • status: ok
    • 次アクション: なし(parent issue なし、follow-up なし)
    FOLLOW_UP_MATERIALIZATION_RESULT_V1:
      schema_version: 1
      materialized_by: post-merge-cleanup
      follow_up_issues: []
      note_only_observations: []

    実施内容

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

    documentation

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions