Repository navigation
fix: controlled_skill_mutation_exec の postcondition を metadata-snapshot 方式に置き換える (#2163) - #2178
Conversation
…ot 方式に置き換える (#2163) `_check_no_tracked_changes` を、mutation 前後の `git status` 行の単純な集合差分 ではなく、mutation 前に `_capture_pre_mutation_snapshot` で取得した filesystem metadata(kind, mtime_ns, size)と mutation 後の状態を比較する方式へ置き換えた (`skill_runtime_exec.py` の `_snapshot_repo_paths` に準ずる設計、ただし対象は `git status` 候補パスに限定し全 repo walk は行わない)。既存の 9 呼び出し箇所すべてを pre/post snapshot 比較に統一し、`issue_body.update` / `issue_comment.publish` の postcondition failure には `mutation_outcome: applied` を extra に追加した (`issue_content.update` の既存パターンに合わせる)。 `.claude/.investigation-context.md` は repo 内に producer/consumer の記述がなく (起票前調査でゼロ件確認)、Claude Code ツール本体由来と推定される外部 untracked artifact のため、`skill_runtime_exec.py` の race-tolerant peer root 除外に準ずる 明示的 exemption として候補パス集合から除外し、`.gitignore` と `docs/dev/agent-skill-boundaries.md` に判断根拠を記録した。 Co-Authored-By: Claude Sonnet 5 <[email protected]>
Preview URLPreview removed (PR #2178 closed). |
CI の PR Body Japanese Check が変更 Markdown ファイル本体も per-block 検査する 仕様であることを踏まえ、日本語比率が閾値未満だった新規見出しに日本語表記を 併記した(意味は変更しない)。
判定REQUEST_CHANGES — 現状のままマージ不可です。 確認した最新 HEAD は 方向性として、全9箇所へ pre-snapshot を配線したこと、 再現結果現行関数と同じ pathname 抽出・snapshot・比較式を使い、最小 Git repository で確認しました。 操作 | post 側 git status | checker の結果 -- | -- | -- space name.txt を新規作成 | ?? "space name.txt" | [] clean な tracked README を削除 | D README | [] 既存 untracked を git add | ?? → A | [] 許可 root 内から外へ git mv | R artifacts/2163/inside.txt -> src/outside.txt | [] 同サイズで内容を書換え、mtime を復元 | ?? same.txt | [] 既存 untracked を chmod +x | ?? chmod.txt | []つまり、新規作成・削除・rename・staging・内容改変・mode 改変のいずれにも検知漏れがあります。 P0-1 — non- |
| 操作 | post 側 git status |
checker の結果 |
|---|---|---|
space name.txt を新規作成 |
?? "space name.txt" |
[] |
clean な tracked README を削除 |
D README |
[] |
既存 untracked を git add |
?? → A |
[] |
許可 root 内から外へ git mv |
R artifacts/2163/inside.txt -> src/outside.txt |
[] |
| 同サイズで内容を書換え、mtime を復元 | ?? same.txt |
[] |
既存 untracked を chmod +x |
?? chmod.txt |
[] |
つまり、新規作成・削除・rename・staging・内容改変・mode 改変のいずれにも検知漏れがあります。
P0-1 — non--z porcelain の pathname 解釈が fail-open
実装は git status --porcelain=v1 を text=True で取得し、splitlines() と line[3:] で pathname を取り出しています。その文字列へ直接 lstat() し、allowed_prefix も文字列 prefix で判定しています。
Git の仕様上、通常の porcelain v1 では空白・タブ・改行・引用符・バックスラッシュ等を含む pathname は C-style quoting されます。rename は <orig-path> -> <path> という二 pathname の複合表現です。機械処理には -z が推奨され、rename の二 pathname を個別に処理する必要があります。(Git)
これにより二種類の bypass が発生します。
?? "space name.txt"に対して、コードは引用符込みの"space name.txt"をlstat()する。実ファイルと一致しないためNoneとなり、後述するNone == Noneで許可される。R artifacts/2163/allowed -> src/forbidden.pyは行全体が許可 prefix から始まるため、移動先が許可範囲外でも丸ごと除外される。
必須修正: git status --porcelain=v2 -z --untracked-files=all --renames を bytes で取得し、NUL レコードを構造的に解析してください。rename/copy は source・destination の双方を個別に認可し、少なくとも destination が許可 root 外なら拒否する必要があります。
P0-2 — 「snapshot にキーがない」と「ファイルが存在しない」が同じ None
比較は次の構造です。
if before_snapshot.get(path) != after_snapshot.get(path):
violation_snapshot_status_path_metadata() も、path が存在しない場合や lstat() に失敗した場合に None を格納します。したがって、before にキーが存在しない新規候補と、after で削除済みの候補を区別できません。
clean な tracked file を executor window 中に削除すると、
before_snapshot: path のキーなし
after status: D path
after_snapshot: path -> None
before.get(path): None
となり、違反なしで通過します。
さらに、pre-existing untracked file を削除すると post 側 git status から pathname 自体が消えます。実装は post 候補だけを反復し、候補が空なら即座に [] を返すため、この削除も検出不能です。
必須修正:
UNOBSERVEDとABSENTを別 sentinel にする。before_paths ∪ after_pathsの和集合を比較する。- before-only、after-only、両方存在の三遷移を明示的に分類する。
- docstring にある「removed を検知する」という主張を、実際の negative test で証明する。
P0-3 — Git index の状態遷移を snapshot していない
post 側では XY を取得していますが、before snapshot に保存されるのは filesystem の (kind, mtime_ns, size) だけです。比較時にも XY は violation の表示に使うだけで、before/post の index state を比較していません。
そのため、次はすべて通過します。
?? file -> A file # git add
M file -> M file # staging
index OID/mode のみ変更 # worktree bytes 不変
関数自身は「staged・unstaged・untracked を拒否する」と宣言していますが、現状は filesystem metadata が同一なら staged transition を許可します。
必須修正: snapshot state に少なくとも次を含めてください。
- porcelain の
XY - HEAD/index/worktree mode
- HEAD/index object ID
- rename/copy の orig path
- unmerged/submodule state
Porcelain v2 は mode と object ID を構造化して返すため、この用途には v1 より適しています。Git 公式仕様でも v2 はより詳細な tracked-entry 情報を提供します。(Git)
P1-1 — (dir|file, mtime_ns, size) は内容同一性でも node 同一性でもない
新実装は全非 directory node を "file" に畳み込み、mtime と size だけを比較します。また、すべての OSError を None として処理します。
このモデルでは以下を識別できません。
- 同サイズの内容書換え後に mtime を復元
chmod等の mode-only change- regular file、symlink、FIFO、socket、device の置換
- atomic replace による inode 変更
- hardlink 数や device の変更
EACCES、EIO、ENOTDIRと、本当に存在しない状態の違い
Python の stat API は file type、mode、inode、device、link count、ctime 等を取得でき、regular file の内容確認には hashlib.file_digest(..., "sha256") が利用できます。([Python documentation]2)
さらに、このPRが参照実装として挙げている skill_runtime_exec.py は、symlink・regular・FIFO・socket・device を区別し、FileNotFoundError 以外の OSError を「absent」へ折り畳まない設計です。PR側はその重要な fail-closed 性質を落としており、「準ずる実装」という説明は不正確です。
必須修正:
FileNotFoundErrorだけをABSENTとする。- その他の
OSErrorは baseline capture failure / postcondition indeterminate として拒否する。 - regular file は SHA-256 を取る。
- symlink は
os.readlink()の target を取る。 st_mode,st_dev,st_ino,st_nlink,st_ctime_nsを保持する。_capture_pre_mutation_snapshot()の例外時{}fallback を廃止し、remote mutation 前に停止する。
P1-2 — .claude/.investigation-context.md の根本原因調査をせず、永久 blind spot にしている
OWNER は、ファイルの用途・生成元・必要性・並列安全性・配置と、ワークフローそのものの見直しを要求しています。
PR が提示している根拠は「tracked repository 内に producer/consumer が見つからない」だけです。それにもかかわらず、
- 「最も可能性が高い生成元は Claude Code」
- 「repo-uncontrollable」
.gitignore追加- checker から完全除外
まで進めています。これは証明ではなく、producer を特定できなかったことからの推測です。
Claude Code の公式 directory 仕様には、project .claude の標準要素として CLAUDE.md、settings、hooks、skills、commands、subagents、rules 等が記載されています。auto memory は ~/.claude/projects/<project>/memory/ 側です。少なくとも公式資料は .claude/.investigation-context.md を Claude Code 標準 singleton とする根拠を与えていません。(Claude)
.gitignore に追加した時点で、git status ベースの checker は当該ファイルの作成・変更・削除を一切観測できなくなります。コード内の exact exemption よりさらに強い恒久 blind spotです。
また、リポジトリには #2136/PR #2143 で、Issue artifact root に confinement された --investigation-evidence-transport-path と real-subprocess E2E が既に存在します。新しい singleton を無視するより、既存 transport へ統合する方が repository architecture と整合します。
必須修正:
-
.gitignoreと_INVESTIGATION_CONTEXT_EXEMPT_RELを撤回する。 -
runtime trace、hook log、process open/write trace 等で実 producer を特定する。
-
必要なファイルなら次のいずれかへ移す。
.claude/artifacts/issue-refinement-loop/<issue>/<run-id>/tmp/issue-refinement-loop/<issue>/<run-id>/- 既存
--investigation-evidence-transport-path
-
不要なら producer を停止する。
-
Issue 番号だけでなく run-id/content digest を含め、同一 Issue の並列実行にも耐えるようにする。
Claude Code の公式並列実行モデルも、セッション間のファイル衝突を避けるため worktree isolation を推奨しています。共有 checkout 直下の無所有 singleton はその設計と逆方向です。(Claude)
P1-3 — mutation_outcome: applied は分類であって recovery ではない
issue_body.update では、remote body が既に new_body_sha256 に一致する場合の already_applied 成功が、local marker が存在する分岐内に残っています。marker がない状態では previous_body_sha256 の stale precondition に進みます。
したがって、
remote PATCH 成功
→ local postcondition failure
→ marker 未作成
→ retry
→ remote は新 body、marker なし
→ stale_precondition failure
という状態は解消していません。今回の mutation_outcome: applied 追加は caller に状況を知らせる点では有用ですが、同一 transaction の回復可能性は改善していません。
必須修正:
-
marker の有無にかかわらず remote readback を最初に行う。
-
remote が desired state と一致するなら marker を repair して
already_appliedとする。 -
postcondition failure では remote receipt を返す。
- issue/comment URL
- ID
- body/content SHA-256
- observed
updatedAt - retry policy
-
applied_but_local_postcondition_failed相当を通常の mutation failure と区別する。
テスト不足
追加テストは、単純な filename、明確に異なる長さへの上書き、新規 untracked file という成功しやすいケースに限定されています。
最低限、次の回帰テストが必要です。
test_rejects_new_untracked_path_with_space
test_rejects_path_with_tab_newline_quote_and_backslash
test_rejects_rename_from_allowed_root_to_forbidden_root
test_rejects_rename_from_forbidden_root_to_allowed_root
test_rejects_newly_deleted_tracked_file
test_rejects_deleted_preexisting_untracked_file
test_rejects_untracked_to_staged_transition
test_rejects_unstaged_to_staged_transition
test_rejects_same_size_content_change_with_restored_mtime
test_rejects_chmod_only_change
test_rejects_regular_to_symlink_fifo_or_socket_transition
test_fails_closed_on_lstat_eacces_eio_enotdir
test_fails_before_remote_mutation_when_pre_snapshot_fails
test_issue_body_retry_repairs_marker_after_remote_applied
mock だけでなく、実 Git repository を作り、実 git status --porcelain=v2 -z を通す subprocess test が必要です。
推奨する実装構造
現在の _check_no_tracked_changes() に「現在状態の clean gate」と「transaction の before/after 比較」を兼務させるのは避けるべきです。
collect_repo_state()
├─ structured Git status/index state
└─ exact filesystem node/content state
check_clean_precondition()
└─ remote mutation 前の current-state gate
compare_repo_transition(before, after)
└─ before_paths ∪ after_paths の transition 判定
remote-only mutation command では、可能なら mutation 前に許可 root 外の dirty state を拒否する方が単純で安全です。並行 writer を許容する必要がある path は、skill_runtime_exec.py と同様に producer が確認された exact path と、許可される transition type を個別定義してください。生成元不明ファイルの blanket exemption は不可です。
関連スコープ
OPEN Issue #1916 も同じ controlled_skill_mutation_exec.py を変更対象にしており、pagination/totalCount の別関心ではあるものの merge-order conflict は現実的です。どちらかが先に入った場合、最新 main への rebase と targeted suite の再実行が必要です。
結論: metadata snapshot 化そのものは妥当な方向ですが、現在の pathname parser・state model・error semantics では旧実装より検知範囲が広がった一方、新しい明確な bypass も導入しています。Issue #2163 をこのPRで closeせず、ACを porcelain -z、index state、union transition、digest、fail-closed error、producer特定、markerless recoveryまで再度強化してから実装を更新すべきです。
… + union-transition 比較へ再設計する (#2163) PR #2178 への OWNER REQUEST_CHANGES を反映する fix_delta。 - porcelain=v1 テキストパースを porcelain=v2 -z の構造化 NUL レコードパースへ 置き換え、C-style quoting されたパス名・rename の2パス表現を正しく扱う (P0-1)。rename/copy は destination/source を個別に allowed_prefix 判定する。 - snapshot にキーがない(UNOBSERVED)場合とファイル不在を確認済み(ABSENT)の 場合を別 sentinel に分離し、before/after candidate_paths の和集合で transition を比較する (P0-2)。 - git index の XY / mode(head/index/worktree) / object id(head/index) / orig_path を snapshot に含め、staged/unstaged 遷移を検知する (P0-3)。 - filesystem node identity を強化: regular file は SHA-256 content digest、 symlink は readlink target、st_mode/st_dev/st_ino/st_nlink/st_ctime_ns を 保持。FileNotFoundError のみ ABSENT とし、その他の OSError は baseline capture failure として fail-closed にする (P1-1)。 `_capture_pre_mutation_snapshot` の except-Exception-return-{} フォール バックを廃止し、capture 失敗時はリモート mutation 前に停止する。 - `.claude/.investigation-context.md` の blanket exemption と `.gitignore` 登録を撤回し、再調査結果(producer 未特定・限界を明記)を doc に記録する (P1-2)。 - `issue_body.update` の markerless remote recovery を実装: marker の有無に 関わらず remote readback を先に desired state と比較し、一致していれば marker を repair して already_applied として返す。postcondition failure は `applied_but_local_postcondition_failed` として区別し、remote receipt と retry policy を返す (P1-3)。 `_collect_repo_state()` / `_check_clean_precondition()` / `_compare_repo_transition()` へ責務を分離した(reviewer 推奨構造)。実 Git repository を使った OWNER 指定の回帰テストを追加。 Co-Authored-By: Claude Sonnet 5 <[email protected]>
Fix delta: OWNER REQUEST_CHANGES 対応(reviewed_head_sha
|
概要
scripts/agent-guards/controlled_skill_mutation_exec.pyの postcondition checker(
_check_no_tracked_changes)を、mutation 前後のgit status行の単純な集合差分方式から、
git status --porcelain=v2 -zの構造化 bytes パース+filesystem node identity(content digest / symlink target / mode / device / inode 等)による pre/post 比較方式へ
置き換えた。
Closes #2163(本 Issue をクローズする)
経緯(OWNER レビューによる大規模 fix_delta を含む)
初回実装は mtime/size のみを比較する metadata-snapshot 方式だったが、OWNER のレビュー
(comment)で
以下 7 件の再現可能な fail-open が指摘され、REQUEST_CHANGES となった。本 PR の現行 head は
その全件に対応した fix_delta 後の実装である。
non_z_porcelain_path_parser_fail_open: porcelain v1 のテキスト行を素朴にsplitlines()/line[3:]していたため、空白を含むパス(quoting)や rename の2パス表現を誤って通過させていた。
deletion_absence_sentinel_collision: 「snapshot にキーがない」と「削除済み」が同じ
Noneになり、削除が検知不能だった。git_index_transition_not_snapshotted: staged/unstaged への遷移が index state を比較していなかったため検知漏れだった。
metadata_identity_insufficient/ambiguous_oserror_treated_as_absent:mtime/size のみの比較では同サイズ内容書換え+mtime復元・chmod 変更を検知できず、
FileNotFoundError以外のOSErrorも一律 absent 扱いにしていた。unowned_global_singleton_blind_spot:.claude/.investigation-context.mdをproducer 未特定のまま
.gitignore+ code exemption で恒久的に checker の死角にしていた。markerless_remote_recovery_missing:issue_body.updateの postcondition failure後、marker 未作成のまま retry すると stale precondition failure に陥る回復不能状態が残っていた。
変更内容(現行 head 時点)
_run_git_status_v2_z():git status --porcelain=v2 -z --untracked-files=all --renamesをbytes で取得し NUL 区切りレコードを構造的にパース。rename/copy は source・destination を
個別に
allowed_prefix判定し、destination が許可 root 外なら拒否する(P0-1 解消)。_ABSENT/_UNOBSERVEDの sentinel を分離し、_compare_repo_transition()がbefore.candidate_paths | after.candidate_pathsの和集合で before-only / after-only /両方存在の3遷移を明示的に分類する(P0-2 解消)。
_PorcelainEntry/_PathObservationが porcelain のXY、HEAD/index/worktree mode、HEAD/index object id、rename の orig path を保持し、before/after 比較に含める
(P0-3 解消)。
_stat_fs_node():FileNotFoundErrorのみ_ABSENTとし、他のOSError(
EACCES/EIO/ENOTDIR等)は_RepoStateCaptureErrorを送出して remote mutation 前にfail-closed で停止する。regular file は SHA-256 content digest、symlink は
readlink()target、st_mode/st_dev/st_ino/st_nlink/st_ctime_nsを保持する(P1-1 解消)。
_capture_pre_mutation_snapshot()のexcept Exception: return {}フォールバックを削除し、pre-snapshot 取得失敗時は全 8 呼び出し箇所で remote mutation 実行前に
明示的に停止するようにした。
.claude/.investigation-context.mdの.gitignoreエントリと_INVESTIGATION_CONTEXT_EXEMPT_RELによるコード除外を撤回。producer 再調査の結果(repo 内にproducer/consumer の参照が一切なく、runtime trace の取得までは行っていないという限界を含む)を
docs/dev/agent-skill-boundaries.mdに記録し、blanket exemption ではなく通常の候補パスとしてfail-closed 判定の対象に戻した(P1-2 解消)。
issue_body.updateの remote readback を marker の有無に関わらず先頭で実行し、remote がdesired state と一致する場合は marker を repair して
already_applied_marker_repairedを返すようにした。
issue_body.update/issue_comment.publishの postcondition failure ではapplied_but_local_postcondition_failedステータス+remote_receipt+retry_policyを返す(P1-3 解消)。
_collect_repo_state()(構造化 git status + filesystem node identity 取得)/_check_clean_precondition()(mutation 前 current-state gate)/_compare_repo_transition()(before/after の transition 判定)に分割。Allowed Paths 遵守
scripts/agent-guards/controlled_skill_mutation_exec.pyscripts/agent-guards/tests/test_controlled_skill_mutation_exec.pydocs/dev/agent-skill-boundaries.md(
.gitignoreは今回の diff に変更なし。P1-2 対応で追加していたエントリを撤回したため。)検証コマンド結果(現行 head)
rg -n "_check_no_tracked_changes" scripts/agent-guards/controlled_skill_mutation_exec.py→ PASSrg -n "test_postcondition_ignores_preexisting_untracked_file_no_content_change" ...→ PASSrg -n "test_postcondition_detects_content_change_to_preexisting_file" ...→ PASSrg -n "test_postcondition_detects_new_untracked_or_tracked_change" ...→ PASSrg -n "test_issue_body_update_postcondition_failure_reports_mutation_outcome" .../test_issue_comment_publish_postcondition_failure_reports_mutation_outcome→ PASSrg -n "investigation-context" scripts/agent-guards/controlled_skill_mutation_exec.py docs/dev/agent-skill-boundaries.md→ PASS(再調査結果として記録、code側は除外せず候補パスとして扱う)uv run --locked pytest scripts/agent-guards/tests/test_controlled_skill_mutation_exec.py -v→ 85 passed(既存 66 + fix_delta 追加 19、OWNER 指定14回帰ケースを含む)TestPostconditionRealGitRegressions)で、空白パス・タブ/改行/引用符/バックスラッシュ・rename 越境・削除・staged 遷移・同サイズ内容書換え・chmod・OSError fail-closed 等を検証ruff check→ All checks passedRuntime Verification Applicability
decision: not_applicable(Issue 本文どおり)。pytest ユニットテストと rg 静的検査のみで完結。レビュアー向け補足(Notes for Reviewer)
.claude/.investigation-context.mdの producer は、repo 内の静的調査(コード・skills・settings 全文検索)では特定できず、runtime trace / hook log 等による動的特定までは実施していない。今後別途調査が必要な場合は follow-up として扱う。