Skip to content

test(rules): list overlaps between allow prefixes and forbidden regexes with Z3 - #102

Closed
furedea-agent[bot] wants to merge 7 commits into
test/73-guard-transformationsfrom
test/73-forbidden-overlap
Closed

furedea-agent[bot] wants to merge 7 commits into
test/73-guard-transformationsfrom
test/73-forbidden-overlap

Conversation

@furedea-agent

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

Copy link
Copy Markdown
Contributor

概要

#73 の P2(allow prefix と禁止正規表現の重なりの列挙)を Z3 で追加する.Refs #73.#100(P4)に積んだ PR で,base は test/73-guard-transformations(#100 のマージ後に main へ付け替える).マージ順は #100 → #102 → #104.

  • tests/ere_to_z3.py: POSIX ERE から Z3 正規表現への変換器.規則が使う文法(^ $ . [] [:class:] () | * + ? {m,n} とエスケープ)だけを扱い,後方参照・先読み・\w などは UnsupportedPattern で拒否する.
  • tests/rule_overlap.py: allow prefix の語列(と,その後ろに空白と任意の文字列が続く形)と,禁止規則(例外を除く)の共通部分を Z3 で解き,witness を 1 行返す.
  • tests/test_forbidden_overlap.py: 現行規則の 20 件を「確認済み」として固定する.増えた重なりも,規則の削除で消えた重なりも赤になる.
変換器の検査 内容
文法ごとの例 受理 / 拒否する文字列 26 組
grep との差分 全 forbidden パターン × 大小文字の区別あり / なし で,ランダム文字列と,Z3 の witness を少し編集した文字列を grep -E と比較
範囲外の文法 後方参照,\w,括弧の不整合などを拒否
witness Z3 の witness を grep が受理する.充足不能な a^b などは witness なし

判断

  • 未アンカーのパターン((^|[[:space:]])git add)は,どの prefix の後ろの自由な tail にも現れるため,全 278 prefix と重なり 1405 件のノイズになった.マッチが prefix の語の範囲内から始まるものだけを数える定義に絞り,20 件になった.
  • agent-browser の file: など,引数に現れる禁止形は tail から始まるため P2 の対象外.これらは P4 の変形検査と既存テストで見る.
  • 20 件はいずれも「provider は prefix を許可し,hook が狭い形を deny する」意図どおりの構成で,修正は不要と判断した(git add と git add .,uv run ... mutmut apply など).自動修正はしない.
  • .hypothesis/ を ls-lint の ignore に追加した(ローカルで Hypothesis を動かすと pre-commit の ls-lint が落ちるため.P4 のコミット時点では未生成で気づかなかった).

検証

  • 壊したルールの検査:allow prefix を広げる(git を追加),deny 規則を消すと,確認済みリストと一致せず赤になる 2 件

  • pytest 224 件 pass(関連テスト選択),ruff check / format,ty

  • 実行時間:20 件の列挙に約 5 秒

  • flake.nix:Linux の devShell で libstdc++ が見つからず libz3.so を読めなかったため,LD_LIBRARY_PATH を追加した(CI の test が落ちた原因).

  • 変換器は C ロケールの grep を模す.ロケール依存の構文(文字クラス,等価クラス,非 ASCII の大小畳み込みなど)は拒否する.[[:space:]] だけは ASCII の空白として扱う限界を docstring に記載した.

計画:#73 (comment)
未対応のレビュー指摘(xargs など wrapper の内側コマンドの重なり):#107

🤖 Generated with Claude Code

@furedea

furedea commented Nov 9, 2026

Copy link
Copy Markdown
Owner

@codex review

@chatgpt-codex-connector

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

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-09T08:49:24.530064Z e0b52cb 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.

@github-actions

github-actions Bot commented Nov 9, 2026

Copy link
Copy Markdown

Review summary

No P0–P3 findings.

What I checked:

  • tests/ere_to_z3.py: parser precedence, anchors via sentinels, bracket handling (leading ], trailing -, negation with case folding, POSIX classes), interval forms, and refusal of unsupported syntax. The grep differential tests (random text and edits near the Z3 witness, run case-sensitive and case-insensitive) cover the real rule set well.
  • tests/rule_overlap.py: I compared it with command_policy. Scoped rules (programs) are case-insensitive for both patterns and exceptions, matching argument_reason. Unscoped rules are case-sensitive, matching rule_applies. The 'begins within the prefix span' window counts the START sentinel correctly, so a match can begin anywhere inside the prefix words.
  • tests/test_forbidden_overlap.py: the reviewed set is checked in both directions. The two mutation tests (wider prefix, deleted rule) show the check fails when the rules change.
  • related_test_extensions.json and .ls-lint.yml: the mapped sources and targets exist, and z3-solver and hypothesis are already in pyproject.toml.

Note (not blocking): \\<, \\> and [[.x.]] / [[=x=]] are read as literals, not refused. No current rule uses them, and the grep differential test should flag a new rule that does.

I could not run the test suite here because the command needed approval, so this review is from reading the code only.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: a3b3d2da34

ℹ️ 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".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

def overlap_keys(prefixes: list[tuple[str, ...]], rules: list[dict]) -> set[tuple[str, str]]:
return {(" ".join(item.prefix), item.pattern[:KEY_LENGTH]) for item in find_overlaps(prefixes, rules)}


Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Keep the full pattern in overlap keys

When a new forbidden regex shares its first 40 characters with an already reviewed regex for the same allow prefix, this set comprehension collapses both overlaps into the same key, so the audit remains green without reviewing the new rule. Long policy regexes commonly share prefixes, and edits after character 40 are likewise invisible; use the complete pattern or another collision-free identifier so every distinct overlap is represented.

Useful? React with 👍 / 👎.

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.

修正しました(20350df).確認済みリストのキーを「prefix の語列 + 禁止パターン全体」にしました.先頭 40 文字が同じ 2 パターンが別の重なりとして扱われることをテストで固定しています.

@furedea

furedea commented Nov 9, 2026

Copy link
Copy Markdown
Owner

@codex review

Comment thread tests/test_forbidden_overlap.py Outdated
POLICY = json.loads((REPO_ROOT / "agents/command_permissions.json").read_text())["rules"]
FORBIDDEN = json.loads((REPO_ROOT / "agents/hooks/rules/forbidden_commands.json").read_text())["rules"]
ALLOW = [tuple(rule["prefix"]) for rule in POLICY if rule["decision"] == "allow"]
KEY_LENGTH = 40

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: Keying overlaps by pattern[:40] can hide a new overlap. Several reviewed patterns start with long shared text such as (^|[[:space:]])git[[:space:]]+add([[:spa. Suppose someone adds a second forbidden pattern that begins with the same 40 characters and overlaps the same prefix. Both patterns collapse to one key, so found == REVIEWED still holds and the test passes. The docstring promises that a newly overlapping form fails here, and that would not happen. No two current patterns share their first 40 characters (I checked with jq … | cut -c1-40 | uniq -d), so this does not break anything today. Keying on the full pattern, or on (rule index, pattern index), would close the gap.

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.

修正しました(20350df).指摘どおり,キーを禁止パターン全体にしました.先頭 40 文字が共通する 2 パターンが別々の重なりになるテストも追加しています.

@github-actions

github-actions Bot commented Nov 9, 2026

Copy link
Copy Markdown

Review summary

No blocking findings (P0: 0, P1: 0).

I reviewed the ERE→Z3 converter, the overlap search and the tests:

  • Anchors as sentinel characters: the sentinel encoding is sound.
  • Brackets and POSIX classes: bracket and POSIX-class handling, including a leading ], a trailing - and negation under -i, agrees with grep -E. The differential tests check this for every real forbidden pattern.
  • "Begins within the prefix" window: Loop(any, 0, span) over START + line limits a match to starting inside the prefix words (including at the leading ^). This matches what the PR description says.
  • Scoped rules: they are case-insensitive and filtered by programs, which matches command_policy.argument_reason.

One P3 is posted inline: keying the reviewed list on pattern[:40] can hide a new overlap when a new pattern begins with the same 40 characters as one already reviewed. No current patterns collide, so this does not break anything today.

🤖 Generated with Claude Code

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 05526790c6

ℹ️ 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".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread tests/ere_to_z3.py
Comment on lines +238 to +243
if self.peek() == "-" and self.peek(1) not in {"]", None}:
self.position += 1
high = self.take()
if ord(high) < ord(mark):
raise UnsupportedPattern(f"reversed range in {self.pattern!r}")
return ((ord(mark), ord(high)),)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Treat a leading hyphen as a bracket literal

When a forbidden pattern uses a valid bracket expression with - first, such as ^tool [-A]$, this condition interprets it as the range - through A instead of the two literals - and A. Checked with GNU grep 3.11 under LC_ALL=C, where ^[-A]$ matches only - and A, while this converter also admits characters such as /; the overlap audit can therefore report nonexistent overlaps or produce a witness that grep rejects. Handle - as a literal in the first bracket position, as is already done for a trailing hyphen.

Useful? React with 👍 / 👎.

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.

再現しませんでした.この変換器では ^[-A]$ は - と A だけを受理し,/ は受理しません(先頭の - は範囲の始点ではなく文字として扱います).tests/test_ere_to_z3.py に ^[-A]$ が -・A を受理し /・B・. を拒否するケースを追加して固定しました(20350df).bracket_item は先頭要素の直後が - のときだけ範囲として読みます.

Comment thread tests/rule_overlap.py
Comment on lines +94 to +95
rest = z3.Concat(z3.Re(" "), z3.Star(characters(TEXT_CHARACTERS)))
return z3.Concat(z3.Re(" ".join(prefix)), z3.Option(rest))

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Preserve argument boundaries when modeling prefixes

When a valid allow-prefix element contains whitespace, for example ['tool', 'sub command'], joining the tuple models it as the separate arguments tool sub command. The policy validator permits any nonempty string as an element, while prefix_rule compares argument tuples and therefore distinguishes these forms; moreover, the guard replaces a whitespace-containing argument with _ before unscoped regex matching. Consequently, an overlap such as one with ^tool _$ is missed and overlaps belonging to the separate-argument command may be reported instead. Either reject whitespace in prefix elements at the policy boundary or model the guard's argument representation without flattening token boundaries.

Useful? React with 👍 / 👎.

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.

修正しました(20350df).空の語や空白を含む語を持つ prefix は ValueError で拒否します(語を空白で連結すると,provider が分けて扱う引数が混ざるため).現行ポリシーにそのような prefix はありません.

@furedea

furedea commented Nov 9, 2026

Copy link
Copy Markdown
Owner

@codex review

@github-actions

github-actions Bot commented Nov 9, 2026

Copy link
Copy Markdown

レビュー結果(read-only)

ブロッキングな指摘はなし(P0: 0,P1: 0,P2: 0,P3: 0).

確認した点:

  • rule_overlap.py のモデルがガードの判定と一致すること:unscoped 規則は大小文字を区別して語のテキストに,scoped 規則は -i で decode 済みの引数に適用され,例外は行全体に効く(command_policy.rule_matches / argument_reason と同じ).governs が prefix[0] を見るのも,canonical が uv run などのラッパーを剥がさないため妥当.
  • denied_from_within のオフセット:START 番兵が 1 文字分を占めるため,Loop(any, 0, span) はマッチ開始を prefix の語の範囲(行の index 0..span-1)に限る.prefix 直後の空白から始まるマッチは除外され,PR 本文の定義どおり.
  • ere_to_z3.py:否定ブラケットの case folding([^a] を -i で使うと A を除外),ブラケット内のバックスラッシュをリテラルとして扱う点(POSIX どおり),区間の不正形の拒否,decode の \\u{5c} の扱い.
  • REVIEWED のキーは 40 文字に切り詰められるが,現行の forbidden パターンで先頭 40 文字が重複するものはなく,キーの衝突で重なりを見落とすことはない.

既知の限界(意図どおりで,指摘はしない):fold_case は ASCII だけを畳み込むので,grep -i の Unicode の大小文字同一視(例:K と KELVIN SIGN)は扱わない.現行の scoped 規則は ASCII だけなので影響はない.

🤖 Generated with Claude Code

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: e8e1629b1d

ℹ️ 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".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread tests/ere_to_z3.py Outdated
END = "\x03"
MAX_CODE_POINT = 0x2FFFF
# Line breaks are folded to spaces before grep runs, and the sentinels never occur in a command.
TEXT_CHARACTERS = ((4, 9), (11, 12), (14, MAX_CODE_POINT))

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Include SOH in the modeled command alphabet

When a forbidden pattern contains U+0001, such as ^echo \x01$, this alphabet excludes the character even though policy validation accepts it and a shell argument can contain it. The real guard retains U+0001 in command_arguments_text, so grep can deny echo $'\x01', but find_line() constrains every witness to TEXT_CHARACTERS and reports no overlap for an allowed echo prefix. Include U+0001 in the text alphabet, reserving only the actual sentinel values.

Useful? React with 👍 / 👎.

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.

修正しました(20350df).行の区切りを Unicode の最上位 2 コードポイント(U+2FFFE・U+2FFFF)に移し,U+0001 と U+0002 を通常の文字として扱います.echo の prefix と ^echo \x01$ が重なり,witness が echo \x01 になるテストを追加しました.

Comment thread tests/ere_to_z3.py
if ord(high) < ord(mark):
raise UnsupportedPattern(f"reversed range in {self.pattern!r}")
return ((ord(mark), ord(high)),)
return ((ord(mark), ord(mark)),)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Reject or translate escapes inside bracket expressions

When a future valid system-grep pattern contains a bracket escape, bracket_item() treats the backslash and following character as separate members rather than either modeling or rejecting the construct. I checked the guard's extended-regexp mode against GNU grep 3.11: ^[\.]$ matches . but not \, while this fallback admits both, so an allow prefix ending in a literal backslash can acquire a nonexistent overlap and Z3 can produce a witness grep rejects. Handle the system grep's bracket-escape semantics or raise UnsupportedPattern instead of silently widening the set.

Useful? React with 👍 / 👎.

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.

修正しました(20350df).括弧式の中のバックスラッシュは UnsupportedPattern で拒否します(grep の方言で意味が違うため,広げて読むことはしません).[\.] と [a\]] が拒否されるテストを追加しました.

@furedea

furedea commented Nov 9, 2026

Copy link
Copy Markdown
Owner

@codex review

Comment thread tests/ere_to_z3.py Outdated

def escaped(self) -> z3.ReRef:
mark = self.take()
if mark.isalnum():

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 escaped() only refuses alphanumeric escapes, so \<, \>, \` and \' get read as the literal characters <, >, `, '. GNU grep, and BSD grep for \</\>, treats them as word or buffer anchors. The module docstring says a new construct "fails loudly instead of being read wrongly", but a future forbidden rule that uses \<git would be converted silently and wrongly. The overlap list would then be wrong, and no test would fail, because no current pattern uses these escapes and the grep-differential tests only exercise existing patterns. Consider refusing these four escapes as well, and adding them to test_syntax_outside_the_rule_dialect_is_refused.

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.

修正しました(2d92152).\< \> \` \' は UnsupportedPattern で拒否します.拒否のテストにも追加しました.

@github-actions

github-actions Bot commented Nov 9, 2026

Copy link
Copy Markdown

Review summary

No blocking findings (P0/P1: 0).

  • P3 tests/ere_to_z3.py escaped(): the GNU anchor escapes \<, \>, \`` and '` are read as literal characters instead of being refused. No current rule uses them, so this only matters for future rules. Details are in the inline comment.

What I checked:

  • ERE → Z3 converter: the sentinel encoding for ^/$, the bracket parsing (leading ], literal -, negated sets combined with case folding), interval bounds, and the \u{..} decoding of witnesses, including literal backslashes.
  • denied_from_within: the 0..span loop over START+line lets a match begin only inside the prefix words, as the PR description says. Exceptions are applied by intersecting with their complements.
  • Scoped and unscoped rules: case-insensitivity is modelled the same way as command_policy.argument_reason. Tab stripping and option-value masking are not modelled, so some overlaps may be over- or under-reported. That is acceptable for a reviewed list, but worth keeping in mind.
  • flake.nix: the env = {...} // optionalAttrs ... merge is valid Nix. z3-solver and hypothesis are already in pyproject.toml/uv.lock on the base branch.

I reviewed the code without running the tests.

🤖 Generated with Claude Code

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 20350df939

ℹ️ 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".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread tests/ere_to_z3.py Outdated
TEXT_CHARACTERS = ((1, 9), (11, 12), (14, MAX_CODE_POINT - 2))
POSIX_CLASSES = {
"space": ((9, 13), (32, 32)),
"alpha": ((65, 90), (97, 122)),

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Honor the active locale in POSIX character classes

When the guard runs under a UTF-8 locale, GNU grep 3.11 treats non-ASCII letters such as é as members of [[:alpha:]], but this hardcoded interval admits only ASCII. For example, a valid allow prefix ("é",) and forbidden pattern ^[[:alpha:]]$ overlap in the real guard, while find_overlaps() reports none, allowing a newly introduced conflict to pass the audit. Either model the locale used by grep or force both grep and the converter to a locale with these ASCII-only semantics.

Useful? React with 👍 / 👎.

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.

修正しました(2d92152).ロケールで中身が変わる alpha・alnum・upper・lower は UnsupportedPattern で拒否します(ASCII だけとして扱うと,UTF-8 の grep との差が黙って残るため).残した digit は ASCII 固定です.space は ASCII の空白として扱います.現行規則が使う文字クラスは space だけで,この仮定は変換器の docstring に書きました.

@furedea

furedea commented Nov 9, 2026

Copy link
Copy Markdown
Owner

@codex review

@github-actions

github-actions Bot commented Nov 9, 2026

Copy link
Copy Markdown

Review summary

No P0–P3 findings.

What I checked:

  • ERE to Z3 converter (tests/ere_to_z3.py): anchors become sentinels, . and negated brackets stay inside TEXT_CHARACTERS, ASCII case folding runs before negated brackets are complemented, and interval, escape and bracket edge cases are refused instead of read wrongly. Each real forbidden pattern is also compared with grep -E, with and without -i.
  • Overlap model (tests/rule_overlap.py): this matches the guard. Scoped rules ignore case and are filtered by programs, as in argument_reason. Unscoped rules keep case, as in rule_matches. Exceptions are subtracted over the whole line. The span bound (with START taking one position) limits matches to ones that start inside the prefix words, which is what the PR says.
  • Dependencies and config: z3-solver and hypothesis are already in pyproject.toml, and .hypothesis is already ignored in .ls-lint.yml. The flake.nix // merge is valid Nix.

Known approximations, which the PR already scopes out: case folding is ASCII-only, the model does not drop tabs as the scoped-rule path does, and only space-joined prefix forms are modeled.

🤖 Generated with Claude Code

@furedea-agent
furedea-agent Bot force-pushed the test/73-guard-transformations branch from 6bc2aa0 to a460a23 Compare November 9, 2026 08:19
furedea and others added 4 commits November 9, 2026 17:19
…es with Z3

Add the P2 check of #73. A POSIX ERE to Z3 converter covers the dialect the
forbidden rules use and refuses anything else; it is compared with the system
grep on every forbidden pattern, with and without case folding, on random text
and on edited Z3 witnesses. The overlap finder names one line that an allow
prefix lets through and a forbidden rule would deny, skipping matches that
begin only in the free tail after the prefix words. The 20 overlaps found are
listed as reviewed; a new or vanished one fails the test.

Refs #73

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
The z3-solver wheel links libstdc++, which a Nix Python on Linux does not find by
itself, so every test that imports z3 failed to load libz3 in CI. Point
LD_LIBRARY_PATH at the compiler runtime library in the dev shell on Linux only.

Refs #73

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Address review of the P2 check.

- Key each reviewed overlap by the complete forbidden pattern, so a new pattern
  that shares its first characters with a reviewed one no longer collapses into
  it.
- Move the line sentinels to the two highest code points so U+0001 and U+0002
  are ordinary text characters, as in a shell argument.
- Refuse a backslash inside a bracket expression, where the grep dialects
  differ, instead of widening the set.
- Refuse a prefix word that is empty or holds whitespace, which joining with
  spaces would merge into several arguments.
- Pin that a leading hyphen in a bracket expression is a literal.

Refs #73

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

Refuse the grep anchor escapes \< \> \` and \' instead of reading them as plain
characters, and refuse the alpha, alnum, upper, and lower classes, whose members
grow with a UTF-8 locale. The space and digit classes stay, read as ASCII.

Refs #73

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
@furedea-agent
furedea-agent Bot force-pushed the test/73-forbidden-overlap branch from 2d92152 to a3e58bd Compare November 9, 2026 08:19
@furedea

furedea commented Nov 9, 2026

Copy link
Copy Markdown
Owner

@codex review

@github-actions

github-actions Bot commented Nov 9, 2026

Copy link
Copy Markdown

Automated review (read-only): no findings at P0–P3.

What I checked:

  • tests/ere_to_z3.py: parsing of anchors, sentinels, intervals, bracket expressions (a leading ], a negated ], dashes at either end, POSIX classes), case folding on negated sets, and that unsupported syntax is refused. Compared it with how command_policy.any_regex_matches calls grep (-qE / -qiE, line breaks turned into spaces).
  • tests/rule_overlap.py: rules scoped to a program ignore case and unscoped rules don't, matching argument_reason and regex_reason. Exceptions are subtracted as a search language. The Loop(any, 0, span) start window counts the START sentinel correctly, so a pattern can begin anywhere up to the last character of the prefix words.
  • tests/test_forbidden_overlap.py: FORBIDDEN[1:] drops the first rule, which holds the git add, git commit and pip patterns on the reviewed list, so the mutation test really detects a deleted rule.

Known limits, not blocking: the model checks only the prefix line itself, not the unwrapped candidate or the option-value-stripped text the guard also checks. Case folding is ASCII-only, while grep -i in a UTF-8 locale also folds some non-ASCII characters. Both can only make P2 report fewer overlaps, and the PR description already says the definition is narrowed.

I could not run the tests in this sandbox.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: a3e58bd8e0

ℹ️ 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".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread tests/ere_to_z3.py
Comment on lines +130 to +131
shifted = [(low + CASE_OFFSET, high + CASE_OFFSET) for low, high in intersect(intervals, (UPPERCASE,))]
shifted += [(low - CASE_OFFSET, high - CASE_OFFSET) for low, high in intersect(intervals, (LOWERCASE,))]

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Handle non-ASCII case folding in scoped rules

When a scoped rule contains a cased non-ASCII literal, this folds only ASCII even though compile_rule() enables case-insensitive matching to mirror the guard. Checked with GNU grep 3.11 under C.UTF-8: ^tool Ä$ matches tool ä with -i, while the converted language does not, so an allow prefix such as ("tool", "ä") can acquire a real forbidden overlap without changing this audit. GNU documents that -i makes characters differing only in case match; either model the active locale's folding or reject cased non-ASCII literals in scoped patterns. GNU grep matching control

Useful? React with 👍 / 👎.

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.

修正しました(3e15f19).大文字小文字を無視する規則(scoped rule)に,大小の別がある非 ASCII 文字(Ä é ß など)が入る場合は,ASCII だけを畳み込む代わりに UnsupportedPattern で拒否します.大小のない文字(日本語など)はそのまま扱います.両方のテストを追加しました.

Comment thread tests/ere_to_z3.py
# white space, which is what the guard's text holds; the letter classes grow with a UTF-8 locale, so they
# are refused rather than modeled as ASCII-only.
POSIX_CLASSES = {
"space": ((9, 13), (32, 32)),

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Honor the locale for the space character class

When grep runs in a UTF-8 locale, this ASCII-only class disagrees with the guard: GNU grep 3.11 under the inspected C.UTF-8 environment accepts U+2003 for [[:space:]]. For example, with prefix ("tool",), pattern ^tool( [[:space:]])x$, and exception ^tool x$, the real guard denies an argument \u2003x, but the converter sees only the ASCII witness removed by the exception and reports no overlap. GNU documents that named character classes depend on LC_CTYPE; force both paths to the C locale, model the active class, or refuse space rather than silently narrowing it. GNU grep character classes

Useful? React with 👍 / 👎.

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.

修正はせず,限界として明記しました(3e15f19).この変換器は C ロケールの grep を模します.ロケールで中身が変わる文字クラス(alpha など)と非 ASCII の大小畳み込みは拒否しますが,[[:space:]] は現行規則の大半が使うため拒否できず,ASCII の空白として扱います.UTF-8 ロケールで U+2003 などが加わる差は,モジュールの docstring に書きました.guard が grep のロケールを固定しない点は guard 側の挙動で,この PR の範囲外です(#87 の担当領域でもあります).

… converter

A cased non-ASCII letter folds by locale in grep, so a scoped rule with one is
refused instead of folded as ASCII only. State in the module docstring that the
converter models the C locale and where [[:space:]] differs under UTF-8.

Refs #73

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
@furedea

furedea commented Nov 9, 2026

Copy link
Copy Markdown
Owner

@codex review

@github-actions

github-actions Bot commented Nov 9, 2026

Copy link
Copy Markdown

Review summary (read-only)

No findings: I found no P0–P3 issues.

What I checked:

  • tests/ere_to_z3.py
    • Sentinel encoding: ^/$ are mapped to sentinel characters, and . and negated brackets are limited to the text characters.
    • Case folding: -i folding is applied before a bracket is negated, which matches grep.
    • Brackets: a leading ] and a trailing - are read as literals.
    • Refusals: intervals, unsupported escapes and unbalanced groups are rejected.
  • tests/rule_overlap.py
    • The denied_from_within(span) window lets a pattern start at START or inside the joined prefix words, but not in the free tail. This matches the narrowed definition in the PR body.
    • Exceptions are applied as complements over the same wrapped line.
    • Scoped rules are limited to prefix[0] and are case-insensitive, which matches command_policy.argument_reason. Unscoped rules are case-sensitive, which matches rule_matches.
  • Dependencies and wiring: z3-solver and hypothesis are already in pyproject.toml and uv.lock. The related-test extension entries and test_related_test_extensions.py are updated to match.

Known limits, not defects, since this is a report-only audit:

  • The model does not reproduce the guard's without_option_values and trailing-redirect stripping.
  • It does not drop tabs and newlines the way scoped rules do.
  • POSIX equivalence and collating classes ([[=a=]], [[.x.]]) are read as literal characters rather than refused. The current rules don't use them.

I could not run the test suite in this environment because the command needed approval, so this review is from reading the code only.

🤖 Generated with Claude Code

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 3e15f19576

ℹ️ 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".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread tests/ere_to_z3.py
Comment on lines +258 to +259
if mark == "[" and self.peek() == ":":
return self.posix_class()

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Reject unsupported equivalence classes

When a valid rule uses a POSIX equivalence class such as ^[[=a=]]$, GNU grep 3.11 under LC_ALL=C matches a, but this branch recognizes only [:class:]: the parser consumes the inner ] as the end of the outer bracket and treats the final ] as a literal. Consequently, find_overlaps([("a",)], ...) reports no overlap even though the guard denies a, allowing the conflict to pass the audit. Support [=...=]/[....] bracket constructs or raise UnsupportedPattern for them; these constructs are defined in the GNU grep bracket-expression documentation.

Useful? React with 👍 / 👎.

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.

修正しました(c03e8a7).括弧式の中の [=…=](等価クラス)と [.…​.](照合要素)は,ロケール依存のため UnsupportedPattern で拒否します.^[[=a=]]$ ^[[.a.]]$ ^[[.hyphen.]]$ が拒否されるテストを追加しました.

[=a=] and [.a.] depend on the locale and were read as ordinary bracket members,
which silently widened or shifted the set. Refuse them.

Refs #73

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
@furedea

furedea commented Nov 9, 2026

Copy link
Copy Markdown
Owner

@codex review

@github-actions

github-actions Bot commented Nov 9, 2026

Copy link
Copy Markdown

レビュー結果(read-only)

指摘なし(P0/P1/P2/P3 いずれも 0 件).

確認した点:

  • tests/ere_to_z3.py:アンカーを番兵文字にする扱い(a^b が充足不能になる),[]a] や [a-] の先頭・末尾の扱い,否定ブラケットで大小文字を畳んでから補集合を取る順序,TEXT_CHARACTERS から改行と NUL を外していることが,command_policy.any_regex_matches(grep -qE / -qiE,改行は空白に置換)の動作と一致している.範囲外の文法は黙って読み違えずに UnsupportedPattern で落ちる.
  • tests/rule_overlap.py:programs のある規則だけを大小文字無視で扱う点,例外を同じ行全体への検索として補集合にする点が,argument_reason / rule_matches と一致している.Loop(any, 0, span) は番兵の位置 0 から prefix の最後の文字までを開始位置として許しており,「prefix の語の範囲内から始まるマッチ」という定義どおり.
  • tests/test_forbidden_overlap.py:確認済み集合との双方向差分と,prefix を広げる・規則を消す 2 つの変異の検査で,増えた場合も減った場合も赤になる.

既知の範囲の制約(PR 本文で説明済みのため指摘にはしない):ガードが照合前に行う変換(without_option_values,scoped 規則での tab 除去,UTF-8 ロケールでの [[:space:]] の拡張)はモデル化していないので,列挙は下側の近似になる.

なお,この環境では pytest の実行が承認されなかったため,テストは実行しておらず静的に確認した.

🤖 Generated with Claude Code

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: c03e8a7a17

ℹ️ 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".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread tests/ere_to_z3.py
return self.escaped()
if mark in {"*", "+", "?", "{", ")"}:
raise UnsupportedPattern(f"nothing to repeat or unbalanced {mark!r} in {self.pattern!r}")
return self.literal(ord(mark))

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Reject newline-separated grep patterns

When a valid rule contains a newline, such as ^foo$\n^bar$, this fallback parses the newline as a literal character; because modeled command lines exclude line breaks, the resulting language is unsatisfiable and an allowed foo prefix appears not to overlap. GNU grep 3.11's --help explicitly says, “PATTERNS can contain multiple patterns separated by newlines,” so the real guard treats this as two alternatives and denies foo. Split newline-separated patterns as grep does, or raise UnsupportedPattern instead of silently missing the overlap.

Useful? React with 👍 / 👎.

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.

修正しました(e0b52cb).パターンに改行があれば UnsupportedPattern で拒否します(grep は改行ごとに別のパターンとして読むため).a\nb と ^a$\n^b$ が拒否されるテストを追加しました.

grep reads each line of a pattern as a separate pattern, which the converter
would otherwise treat as one literal newline. Refuse it.

Refs #73

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
@furedea

furedea commented Nov 9, 2026

Copy link
Copy Markdown
Owner

@codex review

@github-actions

github-actions Bot commented Nov 9, 2026

Copy link
Copy Markdown

Review summary

No P0–P3 findings.

What I checked:

  • tests/ere_to_z3.py: the parser's handling of anchors (as start/end markers), bracket expressions (] first, - at the edges, negation limited to text characters), case folding (ASCII only, cased non-ASCII refused), intervals, and escapes. The text alphabet leaves out NUL, LF and CR. That matches any_regex_matches, which turns \\r\\n into spaces before calling grep.
  • tests/rule_overlap.py: matches how the guard applies rules. Scoped rules (programs) are case-insensitive, take their exceptions from the same rule, and apply only when prefix[0] is one of the listed programs. Unscoped rules are case-sensitive. The Loop(any, 0, span) start window covers the opening marker plus the prefix words, but not the space before the free tail. This fits the documented definition of an overlap.
  • Tests: the fixed list of reviewed overlaps fails in both directions. The tests for a deleted rule (FORBIDDEN[1:]) and a widened prefix (git) are real checks, because rule 0 produces reviewed overlaps. The related-test mapping and the LD_LIBRARY_PATH setting for the z3 wheel (Linux only) look correct.

Known limit, already stated in the PR: a forbidden form that can only start in the free tail is not checked here. without_option_values can also change the text the guard sees for prefixes that take option values (e.g. --group audit), so this audit may under-report for those prefixes. It is an audit gap, not a defect.

Note: I couldn't run the tests in this environment because command approval was required. This review is from reading the code.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: e0b52cbfbd

ℹ️ 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".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread tests/rule_overlap.py
Comment on lines +45 to +46
def governs(self, prefix: Prefix) -> bool:
return not self.programs or prefix[0] in self.programs

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Audit scoped rules through allowed wrappers

When an allowed prefix is a process wrapper, this comparison drops every scoped rule because it checks the wrapper name rather than the unwrapped program. In the current configuration, xargs is allowed specifically because the hook inspects its wrapped command (agents/command_permissions.json:1663-1668), and shell_syntax.parse() exposes that inner command, so xargs uv run mutmut apply is denied by the scoped uv rule at agents/hooks/rules/forbidden_commands.json:30-41; nevertheless, this audit reports no xargs overlap. Model the wrapper transformation, or explicitly include these wrapper-derived overlaps, so the reviewed set covers commands the provider allows and the hook denies.

Useful? React with 👍 / 👎.

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.

指摘は妥当で,xargs は wrapper のため,現行の確認済みリストはその内側コマンドの重なりを含みません.未対応です.wrapper の内側コマンドを規則の対象として扱う設計(wrapper の prefix では「語の範囲内から始まる」制約を外し,内側コマンドの規則言語との共通部分を取る)が必要で,再レビューのたびに新規の指摘が続いているため,ここで止めてユーザー判断に回します.

furedea added a commit that referenced this pull request Nov 9, 2026
…ns (#100)

## 概要

#73 の P4(guard が対応を謳う変形で禁止が効くこと)を Hypothesis で追加する.`Refs
#73`.#98(P1)のマージ後に main へ付け替えた.#102・#104 がこの PR の上に積まれている(マージ順は #100 →
#102 → #104).

- 実ポリシーの deny prefix 130 件が,変形後も `forbidden` で deny になることを検査する(shell 系 5
件は `bash -c true` のように script を付けた代表形).
- ask prefix は wrapper や script の内側で `allowed` が ask になり,直接なら
allow(provider の判定)のままであることを検査する.
- 変形は,クォート(単・二重・なし),`/usr/bin/` 付きパス,wrapper 10 種,`bash`・`sh`・`zsh` の
`-c`,シェル組み込みの実行,先頭の `!` を最大 3 層まで組み合わせる.
- `hypothesis` と `z3-solver` を test グループに追加した(`z3-solver` は P2・P3 用).

| 検査 | 内容 |
| ------------ |
---------------------------------------------------------------------------
|
| deny 性質 | 全変形で deny |
| ask 性質 | 層があれば ask,なければ allow |
| 壊したルール | deny / ask prefix を全部消したポリシーで各性質が赤になることを確認する 2 件 |

## 検証

- [x] `tests/hooks/test_guard_transformations.py` 183 件 pass(deny 125
件・ask 48 件を個別に,1 prefix あたり 12 例,`derandomize=True` で再現可能.prefix を 1
件だけ消したポリシーで赤になるテスト 10 件を含む)
- [x] 関連テスト選択への登録と期待値の更新
- [x] ruff check / format,ty

## 発見と判断

- `bash -c`,`bash -lc`,`sh -c`,`zsh -c`,`zsh -lc` は deny prefix
だが,script がない素の形では guard が先に ask を返す.deny にはならないが,安全側で止まる.script
を付けた代表形で検査している.
- 5 件以外に,素の形・変形のどちらでも #87 の抜け道によって落ちるものは見つからなかったため,`xfail` は使っていない.guard
本体は変更していない.
- 依存は `uv add` が `>=` で入れた.repo の他の test 依存は `==` 固定のため,`==` に揃えるなら `uv
lock` の再実行が必要(ユーザー作業).


計画:#73 (comment)
未対応のレビュー指摘(`sudo` と shell 層で deny 性質が自明に通る件):#107

🤖 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
furedea deleted the branch test/73-guard-transformations November 9, 2026 09:44
@furedea furedea closed this Nov 9, 2026
@furedea-agent

furedea-agent Bot commented Nov 9, 2026

Copy link
Copy Markdown
Contributor Author

base ブランチの削除で自動的に close されました.force push 済みのため reopen できず,#108 に引き継ぎました.未対応の指摘は #107 にあります.

furedea added a commit that referenced this pull request Nov 9, 2026
…es with Z3 (#108)

## 概要

#73 の P2(allow prefix と禁止正規表現の重なりの列挙)を Z3 で追加する.`Refs #73`.#102
の引き継ぎ.#100 のマージで base ブランチが削除され,#102 が自動で close されたあと,force push 済みのため
reopen できなかった.レビューの経緯(スレッドと返信)は #102 に残っている.#100 は main にマージ済みで,この PR の
base は main.#104 がこの PR の上に積まれている.

- `tests/ere_to_z3.py`: POSIX ERE から Z3 正規表現への変換器.規則が使う文法(`^ $ . []
[:class:] () | * + ? {m,n}` とエスケープ)だけを扱い,後方参照・先読み・`\w` などは
`UnsupportedPattern` で拒否する.
- `tests/rule_overlap.py`: allow prefix
の語列(と,その後ろに空白と任意の文字列が続く形)と,禁止規則(例外を除く)の共通部分を Z3 で解き,witness を 1 行返す.
- `tests/test_forbidden_overlap.py`: 現行規則の 20
件を「確認済み」として固定する.増えた重なりも,規則の削除で消えた重なりも赤になる.

| 変換器の検査 | 内容 |
| ------------- |
-----------------------------------------------------------------------------------------------------------------------------
|
| 文法ごとの例 | 受理 / 拒否する文字列 26 組 |
| grep との差分 | 全 forbidden パターン × 大小文字の区別あり / なし で,ランダム文字列と,Z3 の witness
を少し編集した文字列を `grep -E` と比較 |
| 範囲外の文法 | 後方参照,`\w`,括弧の不整合などを拒否 |
| witness | Z3 の witness を grep が受理する.充足不能な `a^b` などは witness なし |

## 判断

- 未アンカーのパターン(`(^|[[:space:]])git add`)は,どの prefix の後ろの自由な tail にも現れるため,全
278 prefix と重なり 1405 件のノイズになった.マッチが prefix の語の範囲内から始まるものだけを数える定義に絞り,20
件になった.
- `agent-browser` の `file:` など,引数に現れる禁止形は tail から始まるため P2 の対象外.これらは P4
の変形検査と既存テストで見る.
- 20 件はいずれも「provider は prefix を許可し,hook が狭い形を deny
する」意図どおりの構成で,修正は不要と判断した(`git add` と `git add .`,`uv run ... mutmut
apply` など).自動修正はしない.
- `REVIEWED` リスト(禁止形 7 種と,それに重なる allow prefix)は,2026-11-09
にユーザーが確認し,すべて意図どおりであることを確認済み.
- `.hypothesis/` を ls-lint の ignore に追加した(ローカルで Hypothesis を動かすと
pre-commit の ls-lint が落ちるため.P4 のコミット時点では未生成で気づかなかった).

## 検証

- [x] 壊したルールの検査:allow prefix を広げる(`git` を追加),deny
規則を消すと,確認済みリストと一致せず赤になる 2 件
- [x] pytest 224 件 pass(関連テスト選択),ruff check / format,ty
- 実行時間:20 件の列挙に約 5 秒

- `flake.nix`:Linux の devShell で `libstdc++` が見つからず `libz3.so`
を読めなかったため,`LD_LIBRARY_PATH` を追加した(CI の `test` が落ちた原因).
- 変換器は C ロケールの grep を模す.ロケール依存の構文(文字クラス,等価クラス,非 ASCII
の大小畳み込みなど)は拒否する.`[[:space:]]` だけは ASCII の空白として扱う限界を docstring に記載した.


計画:#73 (comment)
未対応のレビュー指摘(`xargs` など wrapper の内側コマンドの重なり):#107

🤖 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 added a commit that referenced this pull request Nov 9, 2026
…104)

## 概要

#73 の P3(生成された Claude / Codex / Devin のルールが元と同じ判定をすること)を追加する.`Refs
#73`.#102(P2)に積んだ PR で,base は `test/73-forbidden-overlap`(#102 のマージ後に
main へ付け替える).マージ順は #100 → #102 → #104.

| 対象 | 手段 | 結果 |
| ------------------------------------------------------------------ |
---------------------------------------------------------------------------------------
| ------------------------------- |
| Claude `Bash(prefix:*)`,Codex `prefix_rule`,Devin `Exec(prefix)` | 全
prefix・短い形・長い形・未登録コマンドを列挙し,最も厳しい判定が勝つモデルで元と比較 | 3 つとも差なし |
| `generate-forbidden-commands` の正規表現規則 | 規則を位置で対にして,Z3 で「片方だけが deny
する行」を探す | 6 規則中 4 規則で差あり(下記) |

## 発見:`generate-forbidden-commands` が `exceptions` と `programs` を落とす

固定している agent-harness 0.9.9 の出力では,次の差が出る.guard は両フィールドを読むため,この出力を
`~/.claude/hooks/rules/forbidden_commands.json` に置くと判定が変わる(agent-harness
の README にその置き場所の記載がある).

| 規則 | Z3 の witness | 差 |
| ---------------------------------- |
------------------------------------------------------------------- |
----------------------------------------------------------- |
| 2(`herdr agent start ... --`) | `herdr agent start a --timeout 0 --
--model sonnet --effort medium` | 例外で許可される形まで deny する |
| 3(cargo / pnpm / uv の in-place) | `uv ruN MUTMUT APPLY` | scope
と大小文字の無視が消え,元が deny する行を allow する |
| 4(agent-browser の `file:`) | `agent-browser filE:` | 同上 |
| 5(agent-desktop のアプリ名) | `agent-desktop warP` | 同上 |

- この 4 件は `xfail(strict=True)` にして,agent-harness
が両フィールドを保持するようになったらマーカーを外す.
- 追跡:furedea/agent-harness#203.xfail のマーカーとコメントから参照している.本 PR では guard や
harness を変更していない.
- #87 の抜け道が原因で落ちる性質は P3 にはなかった.

## 判断

- Devin の判定意味は未確認のため,最も厳しい判定が勝つと仮定して比較している.仮定はテストの docstring に書いた.
- 規則全体の補集合を使う Z3 の問いは 13 パターンでは 30 秒で解けなかったため,生成規則と元規則を位置で対にした.generator
は順序を保つ.規則の数が同じであることも検査する.
- Claude の `Bash(dangerouslyDisableSandbox:true)` は prefix
ではないため比較から外した.

## 検証

- [x] 壊した生成規則(allow の追加,deny の欠落,判定の書き換え,長い形だけの欠落)で gap が出る単体テスト
- [x] 未知の形の項目は読み飛ばさず `ValueError`
- [x] pytest 37 件(33 pass,4 xfail),ruff check / format,ty
- 実行時間:Z3 の比較で約 20 秒(規則 5 の大文字小文字を無視する比較が支配的)


計画:#73 (comment)
未対応のレビュー指摘(xfail の `raises=`,裸の `Bash` エントリの拒否):#107

🤖 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 added a commit that referenced this pull request Nov 9, 2026
…ings (#107) (#114)

## 概要

#107 のうち 1・4・5・6 番目の項目を,項目ごとのコミットで対応する.2・3 番目(UTF-8 の大小文字,deny 性質)は範囲外.

Refs #107


計画:#107 (comment)

## 変更

| 項目 | 変更 |
| --------------------------------- |
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
|
| 1. wrapper の内側コマンドの重なり | `find_overlaps(prefixes, rules,
wrappers)`.wrapper の prefix
は「語の範囲内から始まる」制約を外し,内側コマンドの規則言語(`programs`・`exceptions`
を含む)との共通部分を取る.`command -v`/`-V` は除外.wrapper 名はガードの `WRAPPERS` を使う |
| 4. xfail | `raises=AssertionError` を追加し,テストで固定 |
| 5. 関連テスト | `.agents/hooks/rules/related_test_extensions.json` の
`agents/claude/settings.json` に `tests/test_generated_rules.py`
を追加し,選択テストを追加 |
| 6. 裸の `Bash` | `claude_rules` が `ValueError` で拒否し,未知の形のテストに追加 |

## 新規の重なり(ユーザーが 2026-11-10 に確認済み)

新しいチェックが報告した `xargs` の重なり 13 件は,ユーザーが 2026-11-10 に安全と確認した(hook が `xargs`
を外して内側のコマンドを拒否する.`git add` と `git add .` と同じ構造).`REVIEWED` に入れてある.allow
prefix のうち wrapper で新たに重なるのは `xargs` だけだった.

| 規則(パターンの要点) | 例(Z3 の witness を要約) |
| ---------------------------------------------------- |
------------------------------------------ |
| `.venv/bin/python` | `xargs .venv/bin/python` |
| `git add` の広い形(`^` あり・なし) | `xargs git add .` |
| `git commit` の `--no-verify`/`-n`(`^` あり・なし) | `xargs git commit -n` |
| `python -m pip/ensurepip` | `xargs python -mpip` |
| `find -delete/-exec/-fprintf` など | `xargs find -fprintf` |
| `herdr agent start ... --` | `xargs herdr agent start --` |
| `cargo mutants --in-place` | `xargs cargo mutants --in-place` |
| `pnpm exec stryker --inPlace` | `xargs pnpm exec stryker --inPlace` |
| `uv run ... mutmut apply` | `xargs uv run mutmut apply`(#102 の指摘) |
| `(file\|chrome):` | `xargs agent-browser file:` |
| デスクトップアプリ名 | `xargs agent-desktop パスワード` |

いずれも「provider は `xargs` を許可し,hook が内側のコマンドを拒否する」形で,`git add` と `git add
.` と同じ構造.

## 検証

- flake の dev shell で
`tests/test_forbidden_overlap.py`・`tests/test_denial_difference.py`・`tests/test_generated_rules.py`・`tests/test_related_test_extensions.py`:成功(xfail
4 件は想定どおり)
- 先に失敗するテストを書いた項目:1(wrapper の witness)・5(選択テスト)・6(`Bash`).4 は `raises`
を付けた後にマーカーを固定するテストを足した
- `verification_session.py verify` はローカルで pytest が 8 件失敗した.原因は PATH 上の
`agent-harness` が lock の 0.9.9 より新しく,xfail が XPASS(strict) になるため.flake の
dev shell では成功し,本変更とは無関係

## 計画からの変更

なし.

🤖 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