Skip to content

build(lint): enforce small ruff rules the template already enables - #125

Merged
furedea merged 5 commits into
mainfrom
build/align-ruff-small-rules
Nov 10, 2026
Merged

furedea merged 5 commits into
mainfrom
build/align-ruff-small-rules

Conversation

@furedea-agent

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

Copy link
Copy Markdown
Contributor

概要

#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 の分割(refactor(hooks): split guard_command.py by responsibility #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

@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:50:45.187910Z
We couldn’t complete this review. Comment @codex review to try again.
465ae06 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.

Comment thread agents/hooks/lib/shell_paths.py Outdated
return walk.expand(os.path.expanduser(pattern), Path.home())
if os.path.isabs(pattern):
head, separator, tail = pattern.partition("/")
return walk.expand(f"{Path(head).expanduser()}{separator}{tail}", Path.home())

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1: the secret-path guard fails open on a ~user glob for an unknown user.

Path(head).expanduser() raises RuntimeError("Could not determine home directory.") when head names a user that doesn't exist (~nosuchuser) or contains a glob (~*). The old os.path.expanduser returned such a pattern unchanged. Nothing on the path catches RuntimeError: command_paths catches only UnsupportedSyntax, check_paths only UnexpandableGlob, and Adapter.main only (OSError, ValueError, TypeError, AttributeError). So the hook dies with a traceback and exits 1, and the PreToolUse hook treats that as a non-blocking error.

Example: cat ~/.ssh/id_rsa ~nosuchuser/*. command_paths raises before it returns, so the literal secret path is never checked, and the command runs. Before this PR, the same command was blocked.

Fix: catch RuntimeError here and re-raise it as UnexpandableGlob, which gets the hardened ask. Or keep os.path.expanduser(head). Please add a regression test with an unknown ~user glob next to a secret path.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 4932969. shell_paths now turns the RuntimeError into UnexpandableGlob, so the command is asked about instead of skipping the secret-path check. guard_file keeps an unknown ~user literal through home_expanded. Regression tests: tests/hooks/test_shell_paths.py and a ~user case in tests/hooks/test_guard_file.py.

@github-actions

Copy link
Copy Markdown

Review summary

1 blocking finding (P1)

  • P1 agents/hooks/lib/shell_paths.py:69: swapping os.path.expanduser for Path(head).expanduser() lets the secret-path guard fail open. For an unknown ~user (or ~*), pathlib raises RuntimeError, and none of the hook's handlers catch it. The hook exits 1, which is non-blocking, so a command like cat ~/.ssh/id_rsa ~nosuchuser/* skips the secret-path check. Convert the error to UnexpandableGlob and add a regression test.

Smaller note, not blocking: guard_file.protected_reason now raises the same RuntimeError for a ~nosuchuser/... file path. The result is still "allowed", the same as before, but the hook now crashes with a traceback instead of returning 0.

I found no other problems in the rest of the change: import sorting, line wrapping, the verify_page extend, the home_directory change, the statusline Path(cwd).name and the os.rename/os.replace → Path swaps.

🤖 Generated with Claude Code

@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 P0–P3 findings.

Most of this diff is mechanical: I001 import reordering, E501 line wrapping, F541, RUF005, and PERF401. I checked the edits that can change behavior:

  • shell_paths.expanded_paths: only the ~/~user head is expanded, and the glob tail is joined back unnormalized, so / and // keep their meaning. An unknown ~user now raises UnexpandableGlob and the command gets reviewed. Before, it was expanded as a literal. That is safer, and the new tests/hooks/test_shell_paths.py covers it.
  • guard_file.home_expanded: protected paths are now compared as Paths, which ignore trailing slashes and . segments. That can only add matches, so the boundary is stricter, never looser. An unknown ~user stays literal, and the new parametrized case covers it.
  • shell_words.home_directory: the old expanduser("~") == "~" check is now a caught RuntimeError from Path.home(). Both fail under the same conditions.
  • session_snapshot.link_signature: Path.readlink() normalizes link text slightly, for example ./x becomes x. Paths still resolve the same way. At most, a receipt saved before this change may be revalidated once.
  • verify_page / trusted_owners / session_store / os.getcwd → Path.cwd: the messages and semantics stay the same.

Not blocking.

🤖 Generated with Claude Code

@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 (read-only): no findings.

I checked the changes that do more than reorder imports or rewrap text:

  • shell_paths.expanded_paths: only the leading ~ segment is expanded now. An unknown ~user (and ~+, ~-, ~*) raises UnexpandableGlob, so the command is asked about. Before, it was silently walked relative to $HOME, so the new behaviour is stricter. When HOME=/ the pattern can come out as //tail, which is harmless because GlobWalk.expand drops empty segments.
  • shell_words.home_directory: Path.home() raising RuntimeError covers the same failure as the old expanduser("~") == "~" check.
  • guard_file.home_expanded: comparing Path objects normalizes // and trailing /, so protected-path matching can only get broader. An unknown ~user stays literal, and the new parametrized case tests this.
  • provider_adapter.main: catching RuntimeError (and its subclass RecursionError) now makes the hook block with exit 2 instead of crashing with exit 1. That is fail-closed, so it is safer.
  • verify_page: the error messages and their order are unchanged.
  • session_store rename/replace, the getcwd→Path.cwd swaps, the statusline basename change and the trusted_owners tuple unpacking all behave the same as before.
  • session_snapshot.link_signature: Path.readlink() normalizes the link text (./x becomes x, a//b becomes a/b), but the paths are equivalent, so I'm not raising this as a finding.

The new tests (test_shell_paths.py, test_shell_words.py, the CLI test for unknown-home globs, and the guard_file case) cover each behaviour change.

Blocking findings: 0.

furedea added a commit that referenced this pull request Nov 10, 2026
## 概要

`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](https://claude.com/claude-code)

Co-authored-by: furedea <[email protected]>
Co-authored-by: Claude Sonnet 5.5 <[email protected]>
@furedea-agent
furedea-agent Bot force-pushed the build/align-ruff-small-rules branch from 2493223 to ab7cbd0 Compare November 10, 2026 12:31
@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.

"""Record link text, and the target's signature only for a regular file inside the worktree."""
try:
text = os.readlink(path)
text = str(path.readlink())

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3: Path.readlink() is not the same as os.readlink(). It wraps the result in Path, which normalizes the raw link text: ./x becomes x, x/ becomes x, and a//b becomes a/b. When a link resolves to a directory or doesn't resolve at all, its signature is only link:{text}. So retargeting a link between x/ and x, or between ./x and x, no longer changes the snapshot. Also, every existing link whose text normalizes differently will get a new signature once after deploy.

That is a small behaviour change inside a lint-only refactor. To keep the exact link text, use os.fsdecode(os.readlink(path)). That is PTH115-clean only if it's allowed, so if the rule blocks it, accept the normalization knowingly.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Accepted knowingly and documented in the PR body. os.readlink is PTH115, and keeping the raw link text would need a suppression, which this PR does not add. The resolved target is the same; only the stored text of links spelled ./x, x/ or a//b changes, once.

@github-actions

Copy link
Copy Markdown

Review summary: no blocking findings (0 P0/P1).

The diff is mostly import sorting and docstring wrapping. I read every change that alters behaviour:

  • shell_paths.expanded_paths now expands only the leading segment, and an unknown ~user becomes UnexpandableGlob, so the command is asked about. That is stricter than before and has regression tests.
  • shell_words.home_directory now uses Path.home() and turns RuntimeError into UnsupportedSyntax. Same meaning as before; tested.
  • guard_file.home_expanded now compares Path objects instead of strings. Path normalization only adds matches (./x matches x), so it can't drop protection; the unknown-~user case is tested.
  • provider_adapter now catches RuntimeError and blocks (exit 2). This also catches RecursionError and NotImplementedError, which now block instead of crashing. That is fail-closed, so fine.
  • verify_page, trusted_owners (RUF005), session_store rename/replace, statusline basename, and the getcwd replacements keep the same behaviour.

One P3 posted inline: Path.readlink() normalizes symlink text in session_snapshot.link_signature, so some retargets (x/ to x, ./x to x) no longer change the snapshot.

🤖 Generated with Claude Code

furedea added a commit that referenced this pull request Nov 10, 2026
…124)

## 概要

ruff 設定を template-python に揃える第 1 段(Refs #74).

- 該当コードが 0 件の ignore を削除(B007, C401, DTZ005, FURB110, FURB122, FURB171,
UP015, UP017).
- `ARG001` の ignore を削除し,検出された 139 件(src 1,tests 138)を設計として修正.
- 残す project 固有の項目に理由コメントを付与(`E402`,`[tool.ty.environment]`).
- `PLR0917`: 使わない方針.`PLR0913`(max-args =
3)が引数の総数を抑えるので位置引数の数も抑えられ,PLR0917 は何も足さない.ruff 0.16 以降は preview
を卒業しており,ruff 0.17.0 では `PLR` prefix で有効(template の ruff 0.15.11
では無効).`tests/**` の per-file-ignore を削除し,全体の `ignore` に理由コメント付きで追加した.

## ARG001 の修正(非自明なもの)

| 箇所 | 修正 | 理由 |
| -------------------------------------------------------------------- |
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
| テスト約 120 件 | 副作用目的の fixture を `@pytest.mark.usefixtures(...)`
に移し,シグネチャから削除 | 値を使わない依存は pytest の宣言的な指定で表すのが意図に合う |
| `project` fixture(dsh, hermes, pi) | `isolated_project / "repo"`
から作る.`harness` への依存は外し,3 モジュールとも `pytestmark =
pytest.mark.usefixtures("harness")` で全テストに適用する(個別マーカーは削除) | 値を使うので
ARG001 の回避ではない.以前は `project` 経由で全テストが `harness` の分離済み
HOME・ポリシーを使っていた.一部にだけ宣言すると,ローカルでは通って CI
で落ちる(修正済み)/秘密マーカーに依存する否定テストが常に通る,という退行が起きるため,モジュール単位で宣言する(claude-review
P2/P3) |
| `project` fixture(devin) | `isolated_project` 依存を削除 | 他の fixture
と重複しており,外してもテストが通る |
| `verification_record`(conftest) | stub に `verification_calls`
のパスを直接埋め込み,環境変数 `VERIFICATION_TEST_CALLS` を廃止 | 環境変数経由の暗黙結合を,fixture
の値を使う明示的な結合に置換 |
| `recorded_primary` / `temporary` | `merged` は元どおり head を記録するだけの dict
に戻し,`workspace_listing` と `sandbox_tmp` を別々の fixture(各 1
つのパスの唯一の定義)にした.`recorded_primary` は前者,`temporary` は後者を直接要求し,`merged`
も両方に依存する.TMPDIR を `os.environ` から読み戻さず `sandbox_tmp` を使う | 無関係な 2 つのパスを
DTO にまとめない.`XDG_STATE_HOME` は autouse の `state_home` fixture
で設定し(`merged` からは削除),`recorded_primary` が実環境の state home
に書く余地をなくした.順序をテスト側で宣言する必要はなく,`getfixturevalue` の動的参照も使わない(claude-review
P3) |
| `test_trusted_owners_fallback` の `offline` | 空の autouse fixture を削除し
`pytestmark = pytest.mark.usefixtures("api")` に | 全テストに必要な副作用を module
レベルで宣言 |
| `hooks` fixture(skill commands) | `isolated_project` を使う test 側の
`usefixtures` に移動 | fixture 自体は値を使わない |
| `harness` fixture(devin, dsh, hermes, pi) | `isolated_project`
を引数に取り,その値から `home` と `root` を作る | `usefixtures("harness")` にすると
`isolated_project` より先に走り,`harness` が消したコマンドルール環境変数を `isolated_project`
が再設定する.依存を静的に戻して元の実行順を保つ(claude-review P3) |
| `test_an_invalid_program_path_is_rejected` | parametrize を `change`
のみにし,ラベルを `pytest.param(..., id=...)` に | ラベル引数を `usefixtures` で fixture
扱いしていたのは誤り(claude-review P3).全 `usefixtures` 名を走査し,該当はこの 1 件だけだった |
| 何も効かない `usefixtures("monkeypatch")` / `("tmp_path")`(7 箇所) | マーカーを削除 |
値も副作用もない要求なので,残す理由がない |
| `system_message`(provider_adapter) | `_event` | `Formatter`
の形に合わせるためだけの引数 |
| `check`(test_static_rules) | `_kind` に変更し,未使用の `readonly` は削除 |
唯一の呼び出し元(`lint_engine.diagnostics`)が `Callable[[str, Path], ...]` として 2
引数で呼ぶ.位置引数の形は固定なので `_kind` は残し,呼ばれない `readonly` は不要 |
| `observe_lock`(concurrency) | 置換対象と同じ `(path, *, timeout=None)`
を保ち,本体先頭で `del timeout # The fake always waits 5 seconds.` |
シグネチャを緩めず,意図的に無視する引数を明示 |

## 削除した ignore の元の理由(監査)

出典は dotfiles `8428059`(2026-05-09,`pyproject.toml` 新規作成).`59b76e7` がこの
repo にコメントなしでコピーした.対象のスクリプトは dotfiles `faa537f`(2026-05-20)で dotfiles
から出て,この repo では `309f46e`(2026-09-12,`skill-auditor` など retired skill
tooling の削除)で消えた.`8428059` 時点のツリーに削除対象 8 ルールをかけると 23 件あり,すべて
`agents/skills/skill-auditor/scripts/` 内だった.現在の tree には `skill-auditor`
も `run_audit` も無く,同ルールの検出は 0 件.

| ルール | 検査内容 | 元の理由(引用) | 今は当てはまらない理由 |
| ------- | ------------------------------------- |
--------------------------------------------------------------------------------
|
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
| B007 | ループ制御変数が本体で未使用 | "os.walk tuple names document positional
contents in existing code" | 該当は `collect_skills.py:235`(`dirs`
未使用).スクリプトは削除済み.現在の `os.walk` は `check_selection.py:238` と
`source_listing.py:29` の 2 箇所で,どちらも `directories[:] = …` で枝刈りに使い,3
名すべてを使う |
| C401 | `set(generator)` を set 内包表記へ | "Existing aggregation code
favors explicit generator layout" | 該当は `collect_skills.py:362`.削除済み |
| DTZ005 | tz なしの `datetime.now()` | "Timestamped local workspace names
intentionally use local time" | 該当は
`run_audit.py:73`.削除済み.`datetime.now()` は現在 `audit_log.py:324` の
`datetime.now(UTC)` のみ.ローカル時刻が要るなら `datetime.now().astimezone()` で tz
付きにできる |
| FURB110 | `x if x else y` を `x or y` へ | "Existing JSON output code
keeps explicit empty-list fallback branches" | 該当は
`collect_transcripts.py:580,664`.削除済み |
| FURB122 | ループの `f.write` を `writelines` へ | "Existing changelog writes
favor straightforward loops" | 該当は `apply_patches.py:231`.削除済み |
| FURB171 | 単一要素コンテナへの `in` | "Existing message-type checks use tuple
style consistently" | 該当は `collect_transcripts.py:284,773`.削除済み |
| UP015 | 不要な `open` の mode 引数 | "Explicit read/write modes are kept for
CLI-script clarity" | 該当は `skill-auditor` の 7 箇所.削除済み |
| UP017 | `timezone.utc` を `datetime.UTC` へ | "Existing code imports
timezone explicitly" | 該当は `skill-auditor` の 8 箇所.削除済み.現在は
`datetime.UTC` を使用 |
| ARG001 | 未使用の関数引数 | "Patch schema keeps current_description for
compatibility"(`apply_patches.py`) | 対象は削除済み.現在の検出は 139 件で,この PR
で設計として修正した |

「検出 0 件」だけを理由にはしていない.上の対応を `8428059` のツリーと現在の tree
の両方で確かめた.元の理由が今も成り立つ項目はなく,復元した entry は無い.

## 残した ignore の監査

この PR では変更しない.E501,I001,PTH,F541,FURB162,PERF401,PLW2901,RUF005 は別の open
PR(#125)が削除し,その理由の監査も #125 にある.INP001 と PLR2004 は template も ignore
しているので,このまま残す(template 側の根拠は別の議論).現在の検出数は `ruff --isolated` で数えた.

| ルール | 元の理由(dotfiles) | 現在の検出 | 判断 |
| ---------------- |
--------------------------------------------------------------------------
| ---------------------------------------------- |
-------------------------------------------------------------------------------------------------------------------------------------------------------------
|
| E402 | "run_audit adjusts sys.path before importing sibling scripts" |
48 | `run_audit` は削除済みだが,hooks と tests が `sys.path` を整えてから隣のモジュールを
import する構造が同じ理由で残る.コメントを現状の理由に書き換えて残した |
| E501 | "Embedded HTML/JS templates intentionally preserve long source
strings" | 27 | 埋め込みテンプレートは削除済み.現在は hooks
の正規表現とテストのコマンド文字列.元の理由は当てはまらない.別 PR で理由を決める(残置の根拠はまだ無い) |
| F541 | "Existing report/changelog writes include harmless f-string
literals" | 1(`test_pinned_program_project.py`) | 元の理由の対象は削除済み.同上 |
| FURB162 | "Existing timestamp parser normalizes trailing Z explicitly"
| 1(`test_audit_log.py`) | 元の対象は削除済み.同上 |
| I001 | "Keep script import blocks stable while sys.path bootstrapping
is present" | 147(135 ファイル) | うち 28 ファイルが `sys.path` を操作する.残りは当てはまらない.同上
|
| PERF401 | "Existing batching code favors stepwise mutation for
readability" | 3(`explain-visually/scripts/verify_page.py`) |
元の対象は削除済み.検出は別のスクリプト.同上 |
| PTH | "Legacy scripts use os.path; Path migration is a separate
refactor" | 13(`os.getcwd` など) | 元の「別 refactor」はまだ行われておらず,理由は成り立つ |
| PLW2901 | "Existing JSONL parser reuses line after stripping
whitespace" | 1(`test_skill_commands.py`) | 元の対象は削除済み.同上 |
| RUF005 | "Existing path reconstruction code is clearer with list
concatenation" | 3 | 元の対象は削除済み.同上 |
| INP001 / PLR2004 | 理由コメントなし(`87ba9da` で最初から存在) | 72 / 113 |
理由が無いため判断不能 |

## 検証

- `ruff format` / `ruff check`(`--no-cache`): 全件 pass
- `ty check`: pass
- `pytest`: 4521 passed, 1 skipped
- ARG001 は ignore なしで 0 件

## 計画からの変更

なし.

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

---------

Co-authored-by: furedea <[email protected]>
Co-authored-by: Claude Sonnet 5.5 <[email protected]>
furedea and others added 4 commits November 10, 2026 21:39
Drop the ignores for E501, I001, PTH, PERF401, RUF005, F541, FURB162 and
PLW2901 and fix what they report: sort imports, move os.path/os.getcwd
calls to pathlib, wrap long lines and docstrings, unpack instead of
concatenating, and extend lists from generators.

Refs #74

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Path.expanduser raises RuntimeError for a ~user whose home is unknown,
where os.path.expanduser left it unchanged. In shell_paths that crashed the
hook (a non-blocking exit), so a command naming a secret path next to
~nosuchuser/* skipped the check; it now raises UnexpandableGlob, which asks.
In guard_file the unknown ~user stays literal and matches no protected path.

Refs #74

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Add RuntimeError to the adapter's blocking exceptions, so a hook never exits
1 (non-blocking) on pathlib's unknown-home error. Cover an unknown-user glob
through the paths hook and home_directory with tests. Restore the original
wording of the pinned_program_objection and has_literal_words docstrings.

Refs #74

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
…e test

ARG001 is enforced on main now, so a fixture used only for its side effect
moves from the signature to usefixtures.

Refs #74

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
@furedea-agent
furedea-agent Bot force-pushed the build/align-ruff-small-rules branch from ab7cbd0 to 9d399b8 Compare November 10, 2026 12:41
@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.

try:
home_head = Path(head).expanduser()
except RuntimeError as error:
raise UnexpandableGlob(f"cannot expand {pattern}, whose home directory is unknown") from error

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3: This PR adds three new ways to handle an unknown home directory, and none of them has a test:

  • here, an unknown ~user raises UnexpandableGlob, so the command goes to ask
  • guard_file.home_expanded keeps an unknown ~user as literal text
  • provider_adapter.Adapter.main now catches RuntimeError and blocks with exit 2 instead of exiting 1 without blocking

Only shell_words.home_directory has a test. These paths decide whether a command is allowed, asked about or blocked. A small test for each would stop a later refactor from quietly undoing the safer behavior. For example: expanded_paths("~nosuchuser/x", ...) raises UnexpandableGlob, and an adapter whose dispatch raises RuntimeError returns 2.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Two of the three paths already had tests: shell_paths UnexpandableGlob in tests/hooks/test_shell_paths.py and the paths hook in tests/codex/test_hook_adapter_cli.py (test_a_glob_of_an_unknown_home_directory_needs_review), and guard_file.home_expanded in the ~no-such-user case of tests/hooks/test_guard_file.py. The adapter RuntimeError to exit 2 path had none; added in 465ae06 (tests/test_provider_adapters.py, every provider).

@github-actions

Copy link
Copy Markdown

Review summary

No blocking findings. One P3 comment is posted inline.

What I checked by reading the diff:

  • Import reordering: in every hook, the re-sorted imports still come after the sys.path setup.
  • os.path → pathlib: I checked each replacement for changes in behavior.
    • guard_file now compares Path objects. Every value that matched before still matches, and paths that differ only by a trailing / or a doubled // now match too, so it blocks slightly more.
    • shell_paths now sends an unknown ~user to ask instead of expanding it as literal text. That is more cautious than before.
    • shell_words.home_directory handles an unknown home directory the same way as before.
    • Catching RuntimeError in provider_adapter turns an unexpected crash into a block instead of letting the command through. This also covers RecursionError, which is a subclass.
  • session_snapshot: Path.readlink() cleans up the stored link text: ./x becomes x and x/ becomes x. Link signatures for these rare spellings will change once. That does not affect correctness.
  • verify_page: the merged extend produces the same messages, in the same order.

P3: of the four new unknown-home paths, only shell_words.home_directory has a test. The shell_paths UnexpandableGlob path, guard_file.home_expanded and the provider_adapter RuntimeError → exit 2 path have none.

I did not run the test suite.

Cover the provider_adapter path where RuntimeError ends in exit 2 for every
provider, so a later refactor cannot turn it back into a non-blocking exit 1.

Refs #74

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
@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 P0–P3 findings.

What I checked beyond the import reordering (I001) and line wrapping (E501):

  • Import order vs. sys.path setup (E402): reordered blocks such as tests/hooks/test_herdr_ownership_workspaces.py and cleanup_worktrees_runtime.py now import session_store / cleanup_worktrees earlier. That still works because tests/hooks/conftest.py adds agents/hooks and agents/hooks/lib to sys.path before any test module is collected. In hook sources, sorting stayed inside contiguous import blocks, so the trusted sys.path setup still runs first.

  • os.path.expanduser → Path.expanduser: Path.expanduser raises RuntimeError for an unknown ~user. Each caller handles this safely:

    • shell_paths.expanded_paths turns it into UnexpandableGlob, so the command goes to review. That is stricter than before: ~+/… and ~*/… used to be walked as literal names under $HOME, where they matched nothing.
    • guard_file.home_expanded keeps the value literal.
    • shell_words.home_directory raises UnsupportedSyntax.
    • Adapter.main now catches RuntimeError and blocks instead of exiting without a decision.

    Each of these paths has a new test. In guard_file, comparing Path objects instead of strings only widens matching (trailing slash, //), which is the safe direction for a protected-path check.

  • session_snapshot.link_signature: Path.readlink() normalizes the link text (./x → x, a//b → a/b, trailing /). Those forms point to the same target. The one case where they differ (file/ vs file) is still caught, because resolving file/ fails and the target part of the signature changes.

  • Path.cwd() / Path.rename / Path.replace / statusline basename: these behave the same as before. Dropping .replace("Z", ...) in test_audit_log is fine on 3.15, since fromisoformat accepts Z.

I did not run the tests: the project needs Python ≥ 3.15.2 and this runner has 3.12.

🤖 Generated with Claude Code

@furedea
furedea merged commit 9ab5315 into main Nov 10, 2026
22 of 24 checks passed
@furedea
furedea deleted the build/align-ruff-small-rules branch November 10, 2026 13:29
furedea added a commit that referenced this pull request Nov 10, 2026
…me (#129)

## 概要

`cat ~root/.aws/credentials` のように glob を含まない `~user` のパスが,展開されないまま
`~/.aws/**` などの規則と文字で照合され,通っていた抜けを塞ぐ.

## 設計

| 層 | 変更 | 理由 |
| ------------------------------ |
-------------------------------------------------------------------------------------------
|
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
| `secret_path_policy.normalize` | `~user/...` を `~/...` として照合する | 規則は
`.aws` や `.ssh`
など名前で秘密を指す.他人のホームでも同じ名前は同じ秘密なので,規則を複製せず自分のホーム基準のまま安全側に倒せる.展開後の絶対パスを照合する案は,ホームの場所(`/var/root`
など)ごとに規則を持つ必要があり採らない |
| `shell_paths.checked_home` | glob 以外の語でも先頭の `~user` を確認し,ホームが不明なら
`UnexpandableGlob`(確認に回す) | #125 の `known_home`(旧 glob 内の展開)を共有 |
| `shell_paths.expanded_paths` | `~user` の glob の一致結果を `~user/...`
の名前で返す | 上の `normalize` が同じ規則で扱えるようにする |

## guard_file の確認

Edit/Write の対象は `provider_adapter.check_paths` から同じ `blocked_rule`
を通るので,`normalize` の修正で `~root/.aws/credentials`
も止まる.`guard_file.protected_reason` は自分の harness
ファイルの一致を見るもので,`home_expanded` が既に `~user`
を展開し,不明なユーザーは文字のまま(どの保護パスにも一致しない).他人のホームの harness ファイルは境界の対象外なので変更しない.

## 検証

- `ruff check` / `ruff format --check` / `ty check` / `pytest`(4538
passed, 1 skipped)
- 追加したテスト:`~root/.aws/credentials` が止まる,`~no-such-user/...`
が確認に回る,`~root/notes.txt` は通る,`~root` の glob の一致が `~root/...` で返る

Closes #126

🤖 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.

1 participant