Skip to content

実装: E501 migration guard tooling — verify-diff 一体検証(#1138 Child 1) - #1148

Merged
squne121 merged 2 commits into
mainfrom
worktree-issue-1144-e501-migration-guard-tooling-baseline-ch
Jun 23, 2026
Merged

squne121 merged 2 commits into
mainfrom
worktree-issue-1144-e501-migration-guard-tooling-baseline-ch

Conversation

@squne121

Copy link
Copy Markdown
Owner

概要

#1144(#1138 Child 1)の実装です。legacy E501 を base/head の SHA 固定・merge-base 差分・AST 同値性・suppression 禁止・テスト保全を一体で強制する単一 verify-diff エントリポイントとして提供し、後続の領域別 cleanup child(#1138 Child 2〜4)と final gate child(Child 5)が安全に E501 を ratchet 解消できる検証 tooling を導入します。

変更内容

  • scripts/e501_migration_guard.py(新規): 唯一の合否判定エントリポイント verify-diff を実装。ref→不変 SHA 固定 → merge-base 解決(HEAD^ fallback なし)→ git diff --name-status -z による NUL 区切り manifest(splitlines() 不使用)→ status/scope 検査(対象 Python は M のみ許可、A/D/R/C/T/U・scope 外・guard 自身の変更を拒否)→ type_comments=True + compile(dont_inherit=True) ベースの AST 同値性 → suppression / config 検査 → --isolated 固定設定での Ruff 実行(exit 0/1/2 区別、exit2/timeout/JSON decode 失敗を「0 件」扱いしない)→ per-file / scope 合計 ratchet → 版付き report e501-migration-guard/v1 を stdout に JSON のみで出力(人間向けログは stderr)。すべて fail-closed で一体実行します。
  • scripts/tests/test_e501_migration_guard.py(新規): 各ステップの正常系・異常系に加え、一時 Git リポジトリを用いた subprocess 駆動の E2E mutation suite を実装。PR 実装(#1133): staged Ruff E/F gate を green 化 (E501/E402 除外) #1136 型のテスト破壊(assertion/test body 削除)について、通常 pytest が green でも verify-diff が AST 同値性違反として検出することを検証します。

設計上のポイント

  • Ruff は uv run --locked で起動し、内側は ruff check --isolated --select E501 --line-length 120 --target-version py312 --no-preview --ignore-noqa --no-respect-gitignore --no-cache --output-format json に固定。対象 blob は絶対パスで渡すため Ruff の作業ディレクトリは guard 自身の project root(uv.lock のある場所)に固定し、toolchain の再現性を担保します。
  • guard 自己改変防止として、verify-diff は scripts/e501_migration_guard.py とその test が merge-base から変更されている場合を guard_self_change として拒否します。
  • shell=True 禁止・全 subprocess に timeout・stderr サイズ上限・path containment 検証・一時ディレクトリ確実 cleanup・解析不能時 fail-closed の実装規約を満たします。

検証

  • AC1〜AC11: uv run --locked pytest scripts/tests/test_e501_migration_guard.py(各 AC の named test を含む全件 pass)。
  • AC11: scripts/e501_migration_guard.py / scripts/tests/test_e501_migration_guard.py が ruff check --select E,F --ignore E402 で診断 0 件であることを、実 ruff を subprocess 起動する pytest テストで検証。
  • AC12〜AC15: pnpm typecheck / pnpm lint / pnpm test / pnpm build(いずれも Python 追加のみのため regression-safe)。

スコープ境界

Closes #1144

…hild 1)

legacy E501 を SHA 固定・merge-base 差分・AST 同値性・suppression 禁止・テスト保全を一体で fail-closed 検証する単一 verify-diff を追加。

Closes #1144

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@github-actions

github-actions Bot commented Jun 23, 2026 •

Copy link
Copy Markdown
Contributor

Preview URL

✅ verified live assets: https://squne121.github.io/loop-protocol/pr-1148/

The preview will be removed when this PR is closed.

@squne121

Copy link
Copy Markdown
Owner Author

LOOP_VERDICT: APPROVE(impl-review-loop / control-plane 最終判断)

#1144 の contract に対し、PR diff・証跡を独立照合した結果 APPROVE と判定します。PR は人間のマージ判断待ち(Draft, MERGEABLE)。

AC coverage(決定論的に検証)

  • AC1 一体 fail-closed orchestration: test_verify_diff_runs_all_checks_fail_closed(全 check section 存在 + 単一失敗で全体 fail + unrelated-history で tool error)
  • AC2 SHA 固定 + NUL manifest(HEAD^ fallback なし): test_verify_diff_pins_sha_and_builds_nul_manifest(symbolic ref→40-hex 固定 / 空白入りパスの NUL 解析 / merge-base 不在で fail-closed)
  • AC3 M 限定・guard 自己改変拒否: test_verify_diff_rejects_non_modified_and_guard_self_change(A / rename / out-of-scope / guard-self を各々拒否)
  • AC4 AST 同値性(type_comments=True + compile): test_ast_equiv_type_comments_and_compile(空白等価 / 文字列差 not-equal / type comment 差 not-equal / SyntaxError は tool error)
  • AC5 全 suppression 形式 + config: test_suppression_scan_detects_all_forms(コメント 8 形式 parametrized)+ test_suppression_scan_detects_config_widening(line-length 増・per-file-ignores 追加)
  • AC6 Ruff --isolated + exit2 区別: test_ruff_exec_isolated_distinguishes_exit2(exit2 / malformed JSON を「0 件」扱いせず tool error、isolated argv・suppression flag 不在を assert)
  • AC7 ratchet per-file + scope 合計: test_ratchet_per_file_and_scope_total(flat total でも per-file regression を検出 / cleanup・completion mode)
  • AC8 report e501-migration-guard/v1: test_report_v1_schema_complete(全キー・40-hex SHA・uv_lock_sha256・sorted path・stdout JSON-only)
  • AC9 PR 実装(#1133): staged Ruff E/F gate を green 化 (E501/E402 除外) #1136 型 mutation: test_e2e_mutation_pr1136_test_destruction(通常 pytest は green でも verify-diff は AST 破壊を fail 検出 = ungameable)
  • AC10 全 pytest: uv run --locked pytest scripts/tests/test_e501_migration_guard.py → 21 passed
  • AC11 guard 自身 E,F clean: test_guard_files_clean_under_ruff_ef(実 uv run --locked ruff check --select E,F --ignore E402 を subprocess 起動、exit 0)
  • AC12–AC15 pnpm typecheck/lint/test/build: いずれも exit 0(CI=true, worktree 環境)

gate

  • Allowed Paths 厳守(scripts/e501_migration_guard.py / scripts/tests/test_e501_migration_guard.py の 2 ファイルのみ、out-of-scope 変更なし)
  • 実装は subprocess + 一時 Git リポジトリ駆動の behavioral test であり、空 collect の vacuous 緑ではない
  • push 済み blob は検証済みファイルとバイト同一(control-plane が hash-object で照合)

merge_ready: true / required_auto_actions: なし。マージは人間が実施してください。

@squne121

Copy link
Copy Markdown
Owner Author

以下、PR #1148 の敵対的レビューです。

取得できた関連情報は、PR本文・差分・変更ファイル本文・PR本文内の参照(#1144 / #1138 Child 1 / PR #1136 型のテスト破壊)です。関連Issue本文・コメント本文そのものは、この実行では取得できませんでした。そのため、Issue/コメント照合はPR本文上の参照範囲に限定しています。

判定

REQUEST_CHANGES 相当。Draftのまま維持。

方向性は良いです。特に「E501 cleanup PR がテストや意味論を壊さず、単一 verify-diff で fail-closed に検査される」という狙いは妥当です。PRは #1144 / #1138 Child 1 の実装として、guard本体とテストの2ファイルだけを追加し、1456行追加・削除なしのDraft PRです。

ただし、現状のまま「信頼境界」「gate tooling」として扱うには、少なくとも1件の致命的な穴があります。


Blocking findings

1. --ruff-cmd override により gate が偽造可能

PR本文は uv run --locked ruff による固定toolchainを設計上の要点にしています。 実装でもデフォルトは ("uv", "run", "--locked", "ruff") で、Ruff引数は --isolated --select E501 --line-length 120 ... --output-format json に固定されています。

しかしCLIには --ruff-cmd が公開され、shlex.split() した任意コマンドをRuffとして実行できます。禁止チェックは ruff_cmd の各トークンが --ignore 等と完全一致するかだけで、任意のラッパーや偽Ruffを防げません。 実際、テストは fake Ruff をこの経路で差し込んでいます。

これはE501 gateとしては致命的です。CIや後続PRが --ruff-cmd 'python fake.py' を渡せば、ruff --version とJSONを偽装して pass を作れます。

修正案:

  • production CLI から --ruff-cmd を削除する。
  • テスト用の差し替えは関数注入・monkeypatch・専用fixtureに閉じる。
  • どうしてもCLIに残すなら、E501_GUARD_ALLOW_TEST_RUFF=1 かつ PYTEST_CURRENT_TEST などの明示条件下でのみ許可し、CI本番では ruff_cmd != DEFAULT_RUFF_CMD を即failにする。
  • レポートにも non_default_ruff_cmd: true を出し、非デフォルトなら pass 不可にする。

2. Ruff config suppression scan が「実効設定」の検査になっていない

Ruffは pyproject.toml / ruff.toml / .ruff.toml を読み、ignore = ["E501"] や per-file-ignores でE501を抑制できます。また、Ruffは階層設定を暗黙マージせず、extend により別設定を継承できます。([Astral Docs]1)

実装の _extract_config_signals() は ignore / extend-ignore / per-file-ignores / exclude / line-length など一部だけを抽出しますが、extend による継承、include / extend-include / force-exclude などの実効設定変更は対象外です。 さらに scan_config_suppression() は「変更された config basename」だけを拾う構造です。

測定自体は --isolated と直渡しファイルによりかなり守られています。Ruff docsでも、CLIで直接渡したファイルは通常excludeに関係なく解析されます。([Astral Docs]1) ただし、PRが主張する「suppression / config 検査」としては不完全です。実効Ruff設定の禁止ではなく、「一部の既知キーの差分検査」に留まります。

修正案:

  • 後続cleanup PRでは configファイル変更を全面禁止する、という方針に寄せる。
  • あるいは extend graph を解決し、base/headの実効設定を正規化比較する。
  • 中途半端な config widening scan を残すなら、レポート上で config_scan_mode: partial_static_scan のように明示し、過信を避ける。

3. --scope と path の正規化・containment が不足

check_status_scope() は、Git差分の path をそのまま _is_guard_self() と _in_scope() に渡しています。guard自己変更は完全一致、scope判定は path == norm or path.startswith(norm + "/") です。

一方、path containment は blob materialization 時にだけ入っています。 つまり、policy判定の入口で scope と path の正規化がされていません。--scope .、空に近いscope、pkg/../scripts、重複スラッシュ、Windows由来の \ を含む入力などを明示拒否していないため、後続CIで「意図したscopeだけ」を保証するには弱いです。

修正案:

  • --scope は PurePosixPath ベースで正規化し、絶対パス、.、..、空、バックスラッシュ、NUL相当、重複区切りを拒否する。
  • Git pathも同様にcanonical formへ変換し、canonical同士で比較する。
  • GUARD_SELF_PATHS もcanonical化して比較する。
  • 複数scope指定時の重複・親子包含もレポートに出す。

High-value hardening

4. suppression comment の比較が構文差分で、意味差分ではない

# noqa: E501 と blanket # noqa を区別している点は良いです。 ただし、現在はコメント残部をほぼ文字列としてkey化しているため、コード順序・空白・大文字小文字・理由コメントの違いに過敏です。

例:

# noqa: E501, F401
# noqa: F401, E501

これは意味的には同じでも、現在の実装では「追加」と見なされる可能性があります。逆に、semantic widening / narrowing の分類も曖昧です。テストも suppression 追加フォームの検出が中心で、順序変更・削除・縮小・正規化変更は薄いです。

修正案:

  • suppression selectorをsetとしてparseする。
  • blanket * とコード指定を分ける。
  • head_codes - base_codes で意味的なwideningだけをfailにする。
  • reordering / whitespace-only / narrowing はpassまたは別分類にする。

5. merge-base baseline と base_ref SHA の意味が曖昧

verify_diff() は base_ref と head_ref をSHAに固定してレポートしますが、実際の差分・base側Ruff測定は merge_base 対 head_sha です。 これはPR差分としては自然ですが、base_sha が常に検査baselineだと誤読されます。

修正案:

  • baseline_sha を明示し、実際に使ったSHAを merge_base_sha ではなく baseline_sha として扱う。
  • base_sha != merge_base_sha の場合は base_ref_is_not_baseline: true を出す。
  • gate仕様上「merge-baseをbaselineにする」のか「PR作成時base SHAをbaselineにする」のかをREADME/Issue ACに固定する。

6. report が監査用として薄い

現在のreportは per-file count と合否には十分ですが、後からレビューするには不足します。Ruffの診断は per_file countに集約され、行・列・message・該当ファイルblob hashは残りません。

修正案:

  • base/headそれぞれの診断配列を出す。

    • path
    • code
    • row
    • column
    • message
    • physical_line_length 可能なら
  • materialized blobのsha256またはGit blob idを出す。

  • ruff_argv は絶対パスを含むため、CI logで長くなる。必要なら argv_redacted と argv_full を分ける。


良い点

  • verify-diff を単一の入口にして、Git ref解決、merge-base、diff manifest、AST同値性、suppression、Ruff、ratchetを一体化している設計は妥当です。
  • AST同値性で type_comments=True を使い、さらに compile(..., dont_inherit=True) しているのは堅いです。Python標準の ast はPython構文木を生成・compile可能な形で扱うため、この用途に合っています。 ([Python documentation]2)
  • Ruff exit 2 やJSON decode失敗を「0件」と扱わず tool error にしているのは正しいです。
  • PR 実装(#1133): staged Ruff E/F gate を green 化 (E501/E402 除外) #1136 型の「pytestはgreenだがassertionを破壊する」ケースをE2Eで検出している点は、今回のguardの目的に合っています。

推奨結論

このPRは tooling prototypeとしては前進 ですが、E501 cleanup gateの信頼境界としては未完成 です。

最低限、以下を直すまでmergeしない方がよいです。

  1. --ruff-cmd をproductionで無効化する。
  2. --scope / path のcanonical validationを追加する。
  3. config suppression scan の範囲を「全面禁止」または「実効設定比較」に寄せる。
  4. suppression comment比較をsemantic set比較にする。
  5. reportに実baseline SHAと診断詳細を追加する。

この5点を入れれば、#1138 Child 2〜4 のcleanup PRで「意味変更なし・E501だけ減る」をかなり信頼できる形で強制できます。

… scope canonical / semantic suppression / baseline 明示 / audit report

PR #1148 レビュー (issuecomment-4778325233) の Blocking 5点 + hardening を反映。

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@squne121

Copy link
Copy Markdown
Owner Author

敵対的レビュー(#issuecomment-4778325233)対応

REQUEST_CHANGES の指摘 5 点 + hardening を反映しました。

1. --ruff-cmd による gate 偽造(致命的)→ production CLI から完全排除

  • verify-diff の CLI から --ruff-cmd フラグを削除しました(production に override 面を残さない)。verify-diff --help に --ruff-cmd が存在しないことをテストで検証(test_verify_diff_has_no_ruff_cmd_flag)。
  • テスト用の差し替えは 2 つの環境変数同時設定(E501_GUARD_ALLOW_TEST_RUFF=1 かつ E501_GUARD_RUFF_CMD=...)でのみ有効。allow フラグ無しの override env は無視(test_resolve_ruff_cmd_is_production_locked)。CI / 後続 PR はこの env を設定しないため偽造不能。
  • report に ruff.cmd_source(default | env_test_override)/ ruff.non_default_ruff_cmd / ruff.trusted を出力。非信頼 cmd は untrusted_ruff_cmd failure で pass 不可。

2. config suppression scan が実効設定検査でない → 全面禁止スタンス + 範囲明示

  • ratchet cleanup PR では Ruff config ファイル変更自体を拒否(config_files_changed を fail に直結、status_scope の out-of-scope 判定と二重防御)。
  • extend / include / extend-include / force-exclude を signal に追加。
  • 過信回避のため report に config_scan_mode: partial_static_scan を明示。

3. --scope / path の正規化・containment 不足 → canonical 化

  • --scope を PurePosixPath で正規化し、絶対パス・.・..・空・バックスラッシュ・NUL を fail-closed で拒否(test_scope_validation_rejects_unsafe_inputs)。
  • Git path と GUARD_SELF_PATHS を canonical 化して比較。複数 scope の重複・親子包含を scope_overlaps で report に出力。

4. suppression comment 比較が構文差分 → semantic set 比較

  • selector を set として parse、blanket(*)とコード指定を分離。head_codes - base_codes の意味的 widening のみ fail。reordering / whitespace / narrowing は非検出(test_suppression_widening_is_semantic_set_compare)。report に comment_scan_mode: semantic_set_compare。

5. baseline SHA の曖昧さ → 明示

  • report.refs に baseline_sha(= merge_base_sha、実検査 baseline)と base_ref_is_not_baseline を追加(test_baseline_sha_is_merge_base_not_base_ref)。baseline は merge-base である旨を docstring に固定。

6.(hardening)監査用 report 強化

  • base/head それぞれの Ruff 診断を diagnostics.{base,head}.items[](path / code / row / column / message)として出力。
  • materialized 対象の Git blob id を blobs[](base_blob / head_blob)に出力。

検証

uv run --locked pytest scripts/tests/test_e501_migration_guard.py → 32 passed(AC1–AC11 + 上記 hardening test)。guard 2 ファイルは実 ruff check --select E,F --ignore E402 で診断 0 件。Allowed Paths(2 ファイル)不変。

@squne121

Copy link
Copy Markdown
Owner Author

LOOP_VERDICT (iteration 1): APPROVE

OWNER 敵対的レビュー(#issuecomment-4778325233, REQUEST_CHANGES)の Blocking 5 点 + hardening を head 3384b55c で解消し、再判定の結果 APPROVE とします。PR は人間のマージ判断待ち(Draft, MERGEABLE)。

Blocker 解消の検証対応

# 指摘 解消 検証 test
1 --ruff-cmd で gate 偽造 CLI から削除、2-env gate のみ、untrusted_ruff_cmd で pass 不可 test_verify_diff_has_no_ruff_cmd_flag / test_resolve_ruff_cmd_is_production_locked
2 config scan が実効設定検査でない config 変更を全面 fail (config_files_changed) + config_scan_mode: partial_static_scan + extend/include/force-exclude test_suppression_scan_detects_config_widening
3 scope/path 正規化不足 PurePosixPath 正規化 + 絶対/./../backslash/NUL 拒否 + canonical 比較 test_scope_validation_rejects_unsafe_inputs
4 suppression 比較が構文差分 selector set 化、semantic widening のみ fail(reorder/narrowing 非検出) test_suppression_widening_is_semantic_set_compare
5 baseline SHA の曖昧さ baseline_sha(=merge_base) + base_ref_is_not_baseline 明示 test_baseline_sha_is_merge_base_not_base_ref
6 report が監査用に薄い diagnostics.items[](code/row/column/message) + blobs[](base/head blob id) test_report_includes_ruff_diagnostic_detail

gate

  • uv run --locked pytest scripts/tests/test_e501_migration_guard.py → 32 passed
  • guard 2 ファイルは実 ruff check --select E,F --ignore E402 で診断 0 件(test_guard_files_clean_under_ruff_ef)
  • Allowed Paths(2 ファイル)不変、out-of-scope 変更なし
  • push 済み blob は control-plane が hash-object で検証済みファイルとバイト同一を照合

merge_ready: true / required_auto_actions: なし。マージは人間が実施してください。

@squne121
squne121 marked this pull request as ready for review June 23, 2026 11:03
@squne121
squne121 merged commit dee8956 into main Jun 23, 2026
17 of 18 checks passed
@squne121
squne121 deleted the worktree-issue-1144-e501-migration-guard-tooling-baseline-ch branch June 23, 2026 11:03
squne121 added a commit that referenced this pull request Jun 25, 2026
…I 対象に追加(#1163 Scope Delta)

PR #1148 マージ時に python-test-plan.json への登録が漏れていた。
本 PR でテストを追加するため Scope Delta として登録する。
squne121 added a commit that referenced this pull request Jun 26, 2026
…I 対象に追加(#1163 Scope Delta)

PR #1148 マージ時に python-test-plan.json への登録が漏れていた。
本 PR でテストを追加するため Scope Delta として登録する。
squne121 added a commit that referenced this pull request Jun 26, 2026
…1163) (#1179)

* fix(e501_migration_guard): TypeIgnore 意味論的正規化と --coverage scope モード追加(#1163)

- TypeIgnoreSignature(frozen, order=True) dataclassによる構造的アンカー比較
  - `owner_ast_path`(最小 stmt への構造パス)で lineno シフトを無視した比較
  - `checks.type_ignore_equiv` を report に追加(ok / base_count / head_count / mismatches / ambiguous_anchor)
  - ast_fingerprint() を 3-tuple 返却(dump, sigs, ambiguous)に更新
- `--coverage scope` オプション追加(デフォルト: changed で後方互換)
  - `git ls-tree -r -z --full-tree` + `:(literal)<scope>` で NUL-safe に *.py を列挙
  - 空 inventory は fail-closed(vacuous pass 防止)
  - `checks.full_scope_e501` チェックと `e501-migration-guard/v2` schema を追加
  - changed_targets と head_scope_targets を分離(二重計数禁止)
- 新規テスト 12 本追加(既存 32 テストは無変更):
  TypeIgnore 系 5 本 + full_scope 系 7 本(実 ruff 含む)

Closes #1163

* fix(python-test-plan): scripts/tests/test_e501_migration_guard.py を CI 対象に追加(#1163 Scope Delta)

PR #1148 マージ時に python-test-plan.json への登録が漏れていた。
本 PR でテストを追加するため Scope Delta として登録する。

* fix(#1163): TypeIgnoreSignature per-file path + token anchor + file_wide B3 + v2 schema B4 + H1-H3

B1: Add path field to TypeIgnoreSignature; move between files now detected.
B2: Add preceding_token_fingerprint via tokenize module for sub-expr detection.
B3: _get_stmt_at_line returning None -> file_wide (not ambiguous); test fixed.
B4: GuardError in main() uses REPORT_SCHEMA_V2 when --coverage scope.
H1: empty changed_targets + cleanup/completion -> policy fail in check_ratchet.
H2: enumerate_scope_py_files returns (paths, entries); _inventory_sha256_from_entries
    includes git blob SHA so inventory digest changes when blob changes.
H3: full_scope_e501.diagnostics capped at 100 entries.

New tests: test_type_ignore_move_between_files_fails,
test_type_ignore_move_within_multiline_statement_fails,
test_file_wide_type_ignore_same_top_position_passes,
test_line_bound_to_file_wide_fails,
test_coverage_scope_tool_error_uses_v2_schema,
test_empty_changed_targets_cleanup_fails,
test_empty_changed_targets_completion_fails,
test_empty_changed_targets_ratchet_passes,
test_scope_inventory_digest_changes_when_blob_changes,
test_full_scope_failure_reports_diagnostics
54 tests pass (was 44).
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.

実装: E501 migration guard tooling — baseline 再生成 + changed-file ratchet + AST 同値性 + suppression 検出(#1138 Child 1)

1 participant