Skip to content

refactor(hooks): split guard_command.py by responsibility - #128

Merged
furedea merged 1 commit into
mainfrom
refactor/127-split-guard-command
Nov 10, 2026
Merged

furedea merged 1 commit into
mainfrom
refactor/127-split-guard-command

Conversation

@furedea-agent

@furedea-agent furedea-agent Bot commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

概要

agents/hooks/guard_command.py(499 行,上限 500 行)を責務ごとに 3 つに分けた.動きは変えず,関数・docstring・コメントはそのまま移した(削っていない).

ファイル 責務 行数
guard_command.py 入口(main/check/decide),組み立て,監査記録,このフックの設定(Policy,policies(),ignored_project_rules()) 189(元 499)
lib/command_objections.py すべての指摘:セグメント,curl/wget の設定,pin されたプログラム,cleanup/companion の単一呼び出し形式(定数を含む) 280
lib/literal_words.py シェル文字列を解析する述語(allows_literal_rules,has_literal_words,is_read_only_filter と正規表現) 73

各ファイルは 500 行の上限に十分な余裕がある.

境界と循環の避け方

  • 依存は一方向:guard_command → command_objections → literal_words.
  • command_objections が読む Policy は prefixes,rules,listing_rules の 3 属性だけなので,command_objections 側にその 3 属性の Protocol(Policy)を宣言した.具体型 guard_command.Policy はそれを構造的に満たす.こうすれば command_objections は guard_command を import せず(guard_command はスクリプトとして実行されるため,逆向きの import は循環になる),関数のシグネチャも変わらない.Policy を別モジュールに出す案は,既存の lib/command_policy と紛らわしくなるので採らなかった.
  • 新モジュールは agents/hooks/lib/ に置いた.hooks はディレクトリごと配布され,guard_command.py が lib を sys.path に入れ,各 provider アダプタも lib から import するため,既存の lib モジュールと同じ経路で全アダプタから読める.tests/test_python_runtime.py の rendered 検証も通る.
  • pyproject.toml の deptry known_first_party に command_objections と literal_words を追加した.

テストの変更(import 経路のみ)

  • guard.allows_literal_rules と guard.command_policy は,guard_command の属性として使えなくなった(または使うべきでなくなった)ので,lib のモジュールを直接読み込むようにした(test_allowed_command,test_command_policy,test_rule_overlap,test_ere_to_z3).
  • アサーションと期待値は変えていない.

補足

LITERAL_PROGRAMS の直前のコメントの 1 文目("Settings that can send a request ...")は,元から REQUEST_SETTINGS の説明のように読める位置にあった.純粋な移動にするため,そのまま LITERAL_PROGRAMS の上に移した.直すなら別 PR で扱う.

検証

  • ruff check / ruff format --check / ty check:通過
  • lefthook pre-commit(file-length を含む):通過
  • pytest 全件(integration を含む):4521 passed, 1 skipped

#125 は同じファイルを触るため,この PR の後に rebase される想定.差分は移動のみ.

Closes #127

🤖 Generated with Claude Code

@furedea

furedea commented Nov 10, 2026

Copy link
Copy Markdown
Owner

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 10, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ❌ Failed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ❌ Failed 2026-11-10T12:15:34.447194Z
We couldn’t complete this review. Comment @codex review to try again.
f7d07ba Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

@github-actions

Copy link
Copy Markdown

レビュー結果

指摘なし(P0/P1: 0 件).

  • guard_command.py から 5 つの lib モジュールへの移動を確認した.関数本体・定数・docstring はそのまま移されており,判定ロジックの変化は見当たらない.
  • import の依存は一方向(guard_policy ← segment_policy ← pinned_program_policy,literal_words_policy は独立)で循環はない.lib 内に同名モジュールの衝突もない.
  • 消えた名前(allows_literal_rules,is_listed,policies など)を guard_command 経由で参照している箇所は,テスト以外に残っていない.テスト側の import 修正と guard_policy の再ロード追加も妥当.
  • 挙動を変えない移動のため,既存テストで足りており,テストの追加は不要と判断した.

🤖 Generated with Claude Code

guard_command.py reached 499 of the 500-line file limit. Split it along
its real responsibilities instead of trimming comments; every function,
docstring, and comment moves verbatim and behavior is unchanged.

- guard_command.py: entry point, composition, audit record, and the
  hook's own configuration (Policy, policies, ignored_project_rules)
- lib/command_objections.py: every objection the guard can raise
- lib/literal_words.py: predicates over shell text for literal_words

command_objections declares the three Policy attributes it reads as a
Protocol, so it never imports guard_command. Tests only change import
paths.

Refs #127

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
@furedea-agent
furedea-agent Bot force-pushed the refactor/127-split-guard-command branch from 3481f74 to f7d07ba Compare November 10, 2026 12:15
@furedea

furedea commented Nov 10, 2026

Copy link
Copy Markdown
Owner

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

@github-actions

Copy link
Copy Markdown

Review summary: no findings (0 blocking)

I compared the moved code line by line. Every function, constant, regex and docstring removed from guard_command.py shows up unchanged in lib/command_objections.py or lib/literal_words.py. The only edits are the new module prefixes at the call sites and literal_words.has_literal_words inside pinned_program_objection.

  • Order of checks: command_verdict still runs companion → cleanup → pinned → literal_words → per-segment → foreign shell → automation → settings, as before.
  • Imports: guard_command still uses os, re and Path. The imports that are no longer needed (herdr_grammar, shell_inspection) were dropped.
  • Policy type: the Policy Protocol matches the concrete frozen dataclass, and replace(policy, literal_words=False) still acts on the concrete type.
  • No circular import: the new lib modules don't import guard_command.
  • Tests: none of them monkeypatch or reach into the moved names through guard_command.
  • Test selection: neither new module has an entry in related_test_extensions.json. By design (test_an_unmapped_hook_module_keeps_its_full_suite_fallback), that makes a change to either one run the full suite, so coverage doesn't shrink.

🤖 Generated with Claude Code

@furedea
furedea merged commit a31fb4b into main Nov 10, 2026
22 of 24 checks passed
@furedea
furedea deleted the refactor/127-split-guard-command branch November 10, 2026 12:28
furedea added a commit that referenced this pull request Nov 10, 2026
)

## 概要

#74 段階 1B の PR 2.template-python が有効にしている小規模な ruff
規則を,agent-config でも有効にした(ignore から削除).

| 削除した ignore | 違反数 | 対応 |
| ---------------------------------------- | ------ |
------------------------------------------------- |
| I001 | 152 | 自動修正(import の並び替え) |
| E501 | 27 | docstring・コメント・文字列を折り返し,または短縮 |
| PTH(104, 105, 109, 111, 115, 117, 119) | 12 | pathlib へ置換 |
| PERF401 | 3 | `extend` とジェネレータ |
| RUF005 | 3 | アンパック |
| F541 | 1 | 自動修正 |
| FURB162 | 1 | 不要な `replace("Z", ...)` を削除 |
| PLW2901 | 1 | ループ変数の名前を分離 |

残した ignore(`E402`,`INP001`,`PLR2004`,`PLR0917`)のうち,理由を持つ `E402` と
`PLR0917` は,テンプレートと dotfiles と同じく理由を 1 行上の `# CODE: reason`
に書く形にそろえた(#124 の行末コメントから変更,末尾のピリオドなし).

`noqa` と per-file-ignores は追加していない.D/N(PR 3),ARG001 と tests の
PLR0917(c-ac1)はこの PR の範囲外.

## 削除した ignore の元の理由

dotfiles 8428059 で付いたコメントを,agent-config 59b76e7
がそのまま取り込んでいた.各理由が今も成り立つかを確認した.成り立つものはなく,ignore を戻す必要はない.

| ignore | 元の理由(dotfiles 8428059) | 今は成り立たない理由 |
| ------- |
--------------------------------------------------------------- |
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
| E501 | 埋め込み HTML/JS テンプレートの長い文字列を保つ | agent-config に埋め込みテンプレートはない.違反
27 件は docstring・コメント・テストの文字列で,意味を変えずに折り返せた |
| I001 | `sys.path` を整える間,スクリプトの import ブロックを安定させる | ruff は `sys.path`
の操作などのコードで import ブロックを分けて整列するので,path 設定の前後の順序は変わらない.hook の import は
path 設定の後でのみ並び替わり,`ty` と全テストが通る |
| PTH | 古いスクリプトが `os.path` を使う.`Path` への移行は別の作業 | その移行がこの PR.12
か所を置換し,未知の `~user` の挙動差は上の変換で扱った |
| PERF401 | バッチ処理のコードは段階的な変更のほうが読みやすい | 違反 3 件は `verify_page` の同形のループで,1
つの `extend` にまとめたほうが読みやすい(バッチ処理のコードではない) |
| RUF005 | パス再構築のコードはリスト連結のほうが明快 | 違反 3
件はタプルの連結とテストのパラメータで,パス再構築ではない.アンパックで同じ読みやすさ |
| F541 | レポートや changelog の書き込みに無害な f 文字列がある | 該当は 1 件で,不要な `f` を外した |
| FURB162 | タイムスタンプのパーサーが末尾の `Z` を明示的に正規化する | 該当はテストの `replace("Z",
"+00:00")` のみ.対象は Python 3.15 で,`fromisoformat` が `Z` を直接読む(テストが通る) |
| PLW2901 | JSONL パーサーが空白除去後に `line` を再利用する | 該当は 1 件で,JSONL
パーサーではなくテストのループ変数 `block`.別名にして解消した |

## 設計上の判断(自明でない修正)

- `os.path.expanduser(pattern)`(shell_paths): `Path` は末尾の `/` や `//`
を正規化し,glob の意味が変わる.先頭セグメントだけ `Path(head).expanduser()` で展開し,残りはそのまま繋ぐ.
- `home_directory`(shell_words): `expanduser("~")` が `"~"`
を返す失敗判定をやめ,`Path.home()` の `RuntimeError` を `UnsupportedSyntax`
に変換する.失敗を値の比較ではなく例外で表す.
- `session_snapshot.link_signature`: `os.readlink` を `Path.readlink`
にしたため,リンク文字列が正規化される(`./x` は `x`,`x/` は `x`,`a//b` は
`a/b`).解決先は同じで,該当する綴りのリンクの署名が 1 度だけ変わる.`os.readlink` は PTH115
に該当し,生の文字列を保つには抑制が要るため,この正規化を承知のうえで受け入れた.
- `verify_page`: 3 つの同形のループを,(出所の表示,リソース列)の対応に対する 1 つの `extend`
にまとめた.メッセージは変わらない.
- `test_skill_commands`: ループ変数を `fenced_block` とし,dedent 後を `block`
とした(PLW2901).
- `test_forbidden_command`: 長い文字列リテラルの重複を `COMPANION` / `HOME_COMPANION`
定数にまとめた.
- 長い docstring は,元の文言を保ったまま,要約と補足に折り返した(`noqa` は使わない).`guard_command.py`
の分割(#128)のあとに rebase
し,`pinned_program_objection`(`command_objections.py`)と
`has_literal_words`(`literal_words.py`)の元の文言を復元した.サイズ上限に合わせた短縮はしていない.
- `Path.expanduser` / `Path.home` は,未知の `~user` で `RuntimeError`
を出す(`os.path.expanduser` は文字のまま返す).この PR が新たに導入した箇所を次のように扱う.
    - `shell_paths.expanded_paths`: `UnexpandableGlob` に変換し,確認(ask)に回す.
    - `shell_words.home_directory`: `UnsupportedSyntax` に変換する.
    - `guard_file.home_expanded`: 未知の `~user` は文字のまま扱い,保護パスに一致させない.
- `provider_adapter.Adapter.main`: 例外の一覧に `RuntimeError` を加え,hook が exit
1(非ブロック)で終わらず,ブロック(exit 2)になるようにした.
- `hook_input.py`,`audit_log.py`,`session_store.py`,`trusted_owners.py`
の `expanduser` は,この PR より前からある呼び出しで,今回の差分では変えていない.

## 確認

- `uv run ruff check` / `ruff format --check`: 通過
- `uv run ty check`: 通過
- `uv run pytest`: 4526 passed, 1 skipped(未知の `~user` の glob を paths
hook に通す回帰テスト,`home_directory` と `shell_paths` の単体テストを含む)
- lefthook の pre-commit(ruff, ty, file-length ほか): 通過

Refs #74

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: furedea <[email protected]>
Co-authored-by: Claude Sonnet 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

refactor(hooks): split guard_command.py by responsibility before it reaches 500 lines

1 participant