Skip to content

実装: PreToolUse の git push 判定を実行コマンド構造ベースに修正する #1428

Closed

Description

@squne121

Machine-Readable Contract

contract_schema_version: v1
issue_kind: implementation
parent_issue: "none"
blocked_by: "#1420, #1421"
goal_ref: "PreToolUse remote write classifier が、quoted argument・option value・検索キーワード内の `git push` を実行命令と誤認せず、実際に実行される `git push` と nested shell execution は引き続き deny する"
change_kind: code

Parent Issue

なし

Related Issues

Parent Goal Ref

なし。

本 Issue の目的は、remote write の認可条件を変更することではなく、その前段にある remote write の検出精度を改善することである。

Current Validated Scope

  • scripts/session-recording/codex-hook-adapter.mjs の classifyRemoteWrite(command) は、現在、command 文字列全体に次の正規表現を適用している。
/\bgit(?:\s+-C\s+\S+)?\s+push\b/
  • 上記判定は、シェル上で実行される executable / subcommand の位置を解析していない。
  • このため、次のように git push が検索キーワードの値として渡されただけの read-only command も remote_write_requires_approval として block される。
.claude/skills/ssot-discovery/scripts/match-ssot.sh \
  --keywords "issue-refinement ... git push ..."
  • 実際に観測された deny は次のとおり。
PreToolUse: remote_write_requires_approval
[command_kind=git_push]
blocked_command_preview=".claude/skills/ssot-discovery/scripts/match-ssot.sh --keywords ..."
  • 人間または agent は、回避策として git push という mutation-like keyword を検索条件から除外して再実行する必要があった。
  • この回避は command の安全性を高めるものではなく、SSOT discovery の検索条件を欠落させ、関連 Issue・PR・設計資産の recall を低下させる。
  • 既存の tests/session_recording/codex/test_hook_adapter.py には実際の git push と git -C ... push を block するテストが存在するが、quoted argument、option value、検索 pattern、heredoc body などの非実行データを扱う negative regression が存在しない。
  • 実装: PreToolUse guard の誤検知緩和と理由分類・診断検証を追加する #783 では remote write と secret boundary の reason 分離、env VAR=value wrapper、mixed-command priority などを改善したが、command word と argument data の区別は固定されていない。
  • 実装: PreToolUse remote_write_requires_approval を publish lane 証跡で通過可能にする #1408 は実行対象と判定された rtk git push の認可を扱う。今回の Issue では 実装: PreToolUse remote_write_requires_approval を publish lane 証跡で通過可能にする #1408 の publish evidence 条件や allow / deny 判断を変更しない。
  • scripts/agent-guards/git_mutation_command_policy.py の classify_rtk_git_mutation(command, *, cwd, require_active_branch_push) は、内部で _tokenize(command)(実体は shlex.split(command, comments=False, posix=True))を使って raw command string を再 tokenize している。本 Issue の analyzer は、この既存 policy と二重 parser(split-brain)にならないよう、既存 policy が解析済み構造化結果を受け取れるようにする(詳細は Allowed Paths / In Scope 4 参照)。
  • .claude/skills/issue-refinement-loop/scripts/command_registry.py には shlex と shell operator の解析例が存在するが、issue-refinement-loop 専用 validator であり、現在の session-recording classifier からは再利用されていない。

Remaining Parent Gaps

なし。

scripts/session-recording/codex-hook-adapter.mjs および関連テストは Issue #1420 / Draft PR #1421 と競合するため、blocked_by により実装順序を固定した(上記 Machine-Readable Contract / Related Issues 参照)。

Outcome

PreToolUse の remote write classifier が raw command 全体の substring / regex match ではなく、シェル上で実際に実行される simple command の、静的に決定可能な command facts(literal な command word・subcommand・関連 flag の分類)を基準に git push を判定する状態にする。実行時にしか決まらない dynamic な command word / subcommand は indeterminate として fail-closed に扱う。

次を同時に満たすこと。

  1. 検索語、説明文、option value、quoted argument、heredoc bodyなどに含まれる文字列 git push は block しない。
  2. top-level command、pipeline、command list、command substitution、既知の execution-carrier(bash -c / sh -c 等、In Scope 1 参照)内などで実際に実行される git push は引き続き block する。
  3. shell syntax を安全に判定できない場合、または command word / subcommand が静的に literal と確定できない場合は fail-open せず、機械可読な parse-indeterminate / dynamic-command reason で fail-closed にする。
  4. 実装: PreToolUse remote_write_requires_approval を publish lane 証跡で通過可能にする #1408 が扱う publish lane authorization と、本 Issue が扱う command structure classification を分離する。
  5. secret boundary、forbidden path、output shape、redacted preview の既存契約を壊さない。analyzer の構造化出力には任意の argument 文字列(raw argv)を含めない。

In Scope

1. Command structure analyzer の追加

scripts/agent-guards/ 配下に、shell command string から実行対象の simple commands を抽出する共通 analyzer を追加する。

想定する責務は次のとおり。

  • shell quoting を考慮して token を分離する
  • command word と argument data を区別する
  • command word / subcommand が完全な literal か、展開(parameter expansion、command substitution、arithmetic expansion 等)を含む dynamic な word かを区別する(literal | dynamic)
  • control operator ごとの simple command を抽出する
  • pipeline 内の各 command を抽出する
  • command substitution / process substitution / backtick 内の実行 command を識別する
  • 以下の既知 execution-carrier を再帰的に解析する: bash -c / sh -c / bash -s / sh -s、eval、exec、source / .、env FOO=bar ...(先頭環境変数代入)、command ...。上記に含まれない未知の execution-carrier(例: find -exec、xargs、sudo、timeout、nice、nohup 等)は再帰解析せず indeterminate とする(Design Constraints 参照)。
  • quoted string、通常の option value、search pattern、comment を executable と誤認しない
  • heredoc / here-string は、delimiter が quoted の場合のみ data-only として扱う。delimiter が unquoted の heredoc、および here-string の word は、command substitution 等の展開対象になり得るため analyzer の解析対象に含める(unquoted heredoc body 内の展開・here-string 内の command substitution を見逃さない)。
  • parse error、未対応の動的 shell construct、解析 timeout は indeterminate とする
  • analyzer 自身は command を実行しない
  • raw command や secret-like argument(credential を含みうる任意の argument 値、git -c <name>=<value> 等の任意設定値を含む)を structured output に複製しない

2. Structured analysis result の固定

analyzer は少なくとも次と同等の構造化結果を返す。raw argv 全体を出力せず、許可された enum と分類結果のみを返す(secret boundary との両立のため)。

SHELL_COMMAND_ANALYSIS_V1:
  schema: SHELL_COMMAND_ANALYSIS_V1
  status: ok | indeterminate
  commands:
    - command_kind: git_push | rtk_git_push
      executable_literalness: literal | dynamic
      subcommand_literalness: literal | dynamic
      remote_class: origin | other_literal | dynamic | absent
      refspec_class: head_to_literal_branch | other_literal | dynamic | absent
      dangerous_flags:
        - force
        - tags
        - all
        - mirror
        - delete
      execution_context: top_level | list | pipeline | command_substitution | process_substitution | execution_carrier
      source_span:
        start: 0
        end: 20
  reason_code: parsed | malformed_shell | unsupported_construct | dynamic_command_word | analysis_timeout

要件:

  • commands[*] は任意の argument 文字列(argv 全体)を含まない。含めてよいのは上記の許可された enum / boolean / span(数値位置)のみ。
  • executable_literalness または subcommand_literalness が dynamic で、remote-write の有無に影響し得る場合は reason_code: dynamic_command_word とし、status: indeterminate に倒す。
  • source span は文字列位置のみとし、raw command text は含めない
  • status: indeterminate のとき、remote write classifier は allow に倒さない
  • schema validation failure や analyzer process failure も indeterminate と同等に扱う

正確な field 名を変更する場合は、tests と docs に同一契約を固定する(本 schema 名は SHELL_COMMAND_ANALYSIS_V1 に固定し、V2 等への rename は本 Issue のスコープ外とする)。

3. Remote write classifier の置き換え

codex-hook-adapter.mjs の remote write 判定を、raw command に対する次のような正規表現検索から切り離す。

/\bgit(?:\s+-C\s+\S+)?\s+push\b/

新しい判定では、analyzer が抽出した各 command に対してのみ、次を remote write candidate として識別する。

git push ...
git -C <path> push ...
rtk git push ...

rtk git push の最終的な allow / deny は #1408 の bounded publish policy に委譲する。本 Issue 単独では、新しい publish allow 条件を追加しない。

4. Analyzer 呼び出し境界の安全化

Node.js adapter から外部 analyzer を呼ぶ場合は、次を満たす。

  • execFile / execFileSync 相当の argv 呼び出しを使用する
  • shell: true や shell string interpolation を使用しない
  • command は JSON stdin などの data channel から渡す
  • timeout を設定する
  • non-zero exit、timeout、malformed JSON、schema mismatch は fail-closed にする
  • stderr の内容をそのまま hook response に転記しない
  • deny response には既存の redacted preview のみを使用する

5. git_mutation_command_policy.py との連携境界

scripts/agent-guards/git_mutation_command_policy.py(classify_rtk_git_mutation)は、既存どおり #1408 の publish authorization に用いる。本 Issue で追加する analyzer は、この既存 policy の raw command 再 tokenize を置き換えるものではない。本 Issue のスコープでは、analyzer の構造化結果と既存 policy の呼び出しを同一 trust boundary 内に置きつつ、両者が互いに独立した raw command 文字列を個別に再 parse し続けても split-brain にならないことをテストで固定する(既存 policy の外部 API 変更は行わない)。

6. 呼び出しイベント境界の固定

analyzer は次の条件を満たす場合にのみ起動する。

event ∈ {PreToolUse, PermissionRequest}
AND tool_name == "Bash"
AND typeof tool_input.command == "string"

Bash tool 呼び出しであるにもかかわらず tool_input.command が存在しない、または型が異なる場合は malformed_payload として fail-closed にする。tool_input.description を command の代替として remote-write analyzer に渡さない(既存の description fallback 経路を remote-write 判定から除外する)。Stop / SubagentStop、および非 Bash tool の PreToolUse では analyzer を起動しない。

7. Adversarial regression matrix の追加

最低限、以下の分類を実 hook entrypoint を通して固定する。

Allow: git push が非実行データであるケース

.claude/skills/ssot-discovery/scripts/match-ssot.sh \
  --keywords "issue-refinement remote_write git push"
rg -n "git push" docs/ .claude/
grep -R 'git push origin main' docs/
printf '%s\n' 'git push origin main'
python3 tool.py --message "git push origin main"
git log --grep="git push"
some-command --keyword='git push' --description="do not execute git push"
cat <<'EOF'
git push origin main
EOF

これらは、少なくとも remote_write_requires_approval / command_kind=git_push を返してはならない。

Deny: git push が実行されるケース

git push origin main
git -C . push origin main
env FOO=bar git push origin main
command git push origin main
echo ok && git push origin main
git status | git push origin main
echo "$(git push origin main)"
echo `git push origin main`
bash -c 'git push origin main'
sh -c "git push origin main"
cat <<EOF
$(git push origin main)
EOF
cat <<< "$(git push origin main)"

これらは引き続き remote write と判定し、認可済み publish lane でない限り deny する。

Dynamic command word: 静的に literal と確定できないケース(indeterminate)

cmd=git
"$cmd" push origin main
git p$(printf ush) origin main
"$command" push origin main

これらは executable / subcommand が dynamic であり remote-write の有無に影響し得るため、allow にはせず indeterminate として fail-closed にする。

8. Parse-indeterminate / execution-carrier-unsupported regression の追加

以下のケースを固定する。

  • unclosed quote
  • malformed command substitution
  • analyzer timeout
  • analyzer process non-zero exit
  • malformed analyzer JSON
  • unknown schema version
  • executable command の位置を確定できない未対応 shell construct
  • In Scope 1 に列挙した既知 execution-carrier 以外(例: find -exec、xargs、sudo、timeout、nice、nohup 経由の command)

これらを無条件 allow にしてはならない。

reason は、次と同等の機械可読分類を含める。

shell_command_parse_indeterminate
shell_command_analysis_failed
shell_command_analysis_timeout
dynamic_command_word
unsupported_execution_carrier

既存 consumer が新 reason を処理できない場合は、外部 reason を generic remote_write_requires_approval に保ちつつ、内部 diagnostic field または sanitized stderr に parse failure reason を残す。

9. 既存 boundary の維持

次を回帰テストする。

  • forbidden path 判定は remote write より優先される
  • secret boundary 判定は remote write より優先される
  • PreToolUse の output shape は既存の supported fields のみ
  • PermissionRequest の event-specific output shape を壊さない
  • blocked_command_preview の redaction と truncation を維持する
  • read-only command は manifest を生成せず stdout を空のまま通過できる
  • .codex/hooks.json の active handler wiring を変更しない
  • data-only な文字列(例: printf '%s\n' 'gh secret list' && git push origin main の gh secret list 部分)が secret reason を優先させて remote-write 判定を欠落させないことを確認する(既知の priority 非対称性の regression)

Design Constraints

Raw substring exclusionで修正しない

次のような局所的例外は禁止する。

  • match-ssot.sh の場合だけ allow
  • --keywords の後ろを一律無視
  • quote 内の文字列をすべて削除してから regex 判定
  • git push の前に特定 script path があれば allow
  • blocked keyword を検索語から取り除くよう agent に案内するだけ

特に quote 内を一律無視すると、次の実行を見逃す。

echo "$(git push origin main)"

したがって、quoted data と quoted command substitution を区別する必要がある。

shlex 単体を full shell parser とみなさない

既存の command_registry.py にある shlex 利用は参考にできるが、tokenize 成功だけで shell execution semantics を完全に表現できるとはみなさない。

shlex を採用する場合は、対応する bounded grammar を明示し、未対応構文を fail-closed にする。本 Issue のデフォルト方針は、third-party parser dependency を追加せず、上記 bounded grammar(In Scope 1 に列挙した構文範囲に限定した hand-written analyzer)で実装することとする。

新規 parser dependency の条件

third-party parser を導入する場合(bounded grammar での実装が構文カバレッジ上どうしても不可能と判明した場合のみ)は、実装前に以下を確認する。

  • repository の配布ライセンスとの互換性(LICENSES/README.md は現時点で placeholder であり、各アセットのライセンス確認は未完了。third-party parser dependency を追加する場合、本 Issue の PR で個別に確認結果を記録する)
  • pure Python / pure JavaScript か、native build が必要か
  • Node 24 / Python 3.12 / WSL2 / CI での再現性
  • lockfile による version 固定
  • maintenance status
  • command を実行せず parse のみを行うこと
  • command substitution、pipeline、execution-carrier、shell -c の必要範囲を解析できること

ライセンスまたは supply-chain review を完了できない dependency が必要になった場合は、実装を継続せず Stop Condition とする。third-party parser を追加しない場合、AC11・Allowed Paths の pyproject.toml / uv.lock / package.json / pnpm-lock.yaml は変更不要(該当なし)とする。

Out of Scope

  • 実際の rtk git push を自動許可する条件の追加
  • 実装: PreToolUse remote_write_requires_approval を publish lane 証跡で通過可能にする #1408 の publish evidence、remote head、verified head、Allowed Paths gate の変更
  • force push、tag push、mirror push、delete push の許可
  • GitHub credential、OAuth、token scope の変更
  • Codex / Claude runtime 本体の permission model の変更
  • SSOT discovery の検索語や検索アルゴリズムの変更
  • match-ssot.sh 固有の allowlist 追加
  • remote write 以外の全 command policy の全面的な AST 化
  • shell alias、user-defined function、runtime eval の内容そのものの完全な静的解決(eval 自体は execution-carrier として認識し indeterminate に倒すが、eval に渡される動的文字列の中身までは解決しない)
  • hook を OS sandbox または完全な security boundary とみなす設計変更
  • Codex CLI / Claude Code の非対話モードを用いた実 GitHub remote への git push product smoke test の追加(本 Issue のスコープ外。必要であれば別 Issue として起票する)
  • git_mutation_command_policy.py の外部 API(classify_rtk_git_mutation のシグネチャ)の変更

Runtime Verification Applicability

decision: not_applicable
runtime_verification_applicability: not_applicable
reason: "本 Issue は shell command fixture を入力とする deterministic parser / hook adapter regression で検証でき、実 Git remote への push、credential 使用、外部サービス mutation を必要としないため"

実際の remote branch に対する git push は verification として実行しない。Codex CLI / Claude Code の非対話モードを用いた実 GitHub remote への product smoke test は、本 Issue の Out of Scope(上記)に基づき対象外とする。

Acceptance Criteria

  • AC1: 実際に観測された match-ssot.sh --keywords "... git push ..." command を PreToolUse payload として入力したとき、remote_write_requires_approval / command_kind=git_push deny が返らない
  • AC2: rg、grep、printf、Python option value、git log --grep、通常の quoted argument、quoted-delimiter heredoc body に含まれる git push が remote write と分類されない
  • AC3: top-level の git push および git -C <path> push は既存どおり remote_write_requires_approval / command_kind=git_push として deny される
  • AC4: && / || / ; / pipeline 内で実行される git push が検出され、deny される
  • AC5: $() / backtick / process substitution / bash -c / sh -c / unquoted heredoc / here-string 内で実行される git push が検出され、deny される
  • AC6: env VAR=value、先頭環境変数代入、command wrapper を用いても実 git push 判定を bypass できない
  • AC7: remote write 判定は raw command 全体への substring / regex match ではなく、構造解析結果の command 分類(command_kind / literalness / execution_context 等の enum)のみに適用される
  • AC8: parse error、timeout、analyzer failure、schema mismatch、未対応 dynamic syntax、未対応 execution-carrier、dynamic command word は fail-open せず、機械可読な indeterminate 系 reason(shell_command_parse_indeterminate / dynamic_command_word / unsupported_execution_carrier 等)を伴って fail-closed になる
  • AC9: secret boundary、forbidden path、mixed-command priority(data-only secret-like文字列によるremote-write見落としを含む)、redacted preview、PreToolUse / PermissionRequest output shape の既存テストが全件 PASS する
  • AC10: 実装: PreToolUse remote_write_requires_approval を publish lane 証跡で通過可能にする #1408 の publish lane authorization と本 Issue の syntax classification の責務差分が docs に明記される
  • AC11: third-party parser dependency を新規導入した場合に限り、license compatibility、lockfile、CI reproducibility の確認結果が PR body に記録される(導入しない場合は本 AC は N/A とし、PR body にその旨を明記する)
  • AC12: 対象 tests の fixture 名または parameter ID から、data_only / executed / indeterminate の期待分類を判別できる

Verification Commands

# AC1
# preflight-scope: runtime_only
$ uv run --locked pytest tests/session_recording/codex/test_hook_adapter.py -v -k "keyword_false_positive_match_ssot"
# AC2
# preflight-scope: runtime_only
$ uv run --locked pytest tests/session_recording/codex/test_hook_adapter.py -v -k "data_only"
# AC3
# preflight-scope: runtime_only
$ uv run --locked pytest tests/session_recording/codex/test_hook_adapter.py -v -k "remote_write_top_level"
# AC4
# preflight-scope: runtime_only
$ uv run --locked pytest tests/session_recording/codex/test_hook_adapter.py -v -k "remote_write_compound"
# AC5
# preflight-scope: runtime_only
$ uv run --locked pytest tests/session_recording/codex/test_hook_adapter.py -v -k "remote_write_substitution"
# AC6
# preflight-scope: runtime_only
$ uv run --locked pytest tests/session_recording/codex/test_hook_adapter.py -v -k "remote_write_wrapper"
# AC7
$ uv run --locked pytest scripts/agent-guards/tests/test_shell_command_analysis.py -v
# AC8
$ uv run --locked pytest scripts/agent-guards/tests/test_shell_command_analysis.py -v -k "indeterminate"
# AC9
$ uv run --locked pytest tests/session_recording/codex/test_hook_adapter.py -v
# AC10
$ rg -n "command structure classification" docs/dev/session-recording-policy.md docs/dev/hook-boundaries.md
# AC11
# 該当する場合のみ実行。third-party parser dependency を追加しない場合はこの AC を N/A として PR body に明記する。
# baseline-expect: pass
$ test -f pyproject.toml
# AC12
$ rg -n "_indeterminate" tests/session_recording/codex/test_hook_adapter.py

補助検証(AC 番号非対応。既存契約の非回帰確認。PR 作成時にレビュアーが確認する):

$ uv run --locked pytest scripts/agent-guards/tests/test_git_mutation_command_policy.py -v

以下の2件は VC preflight の対象としないが、PR body の Delivery Rule に記載のとおり PR 作成前にローカルで実行し、結果を PR body に記録する。

  • uv run --locked ruff check scripts/agent-guards/shell_command_analysis.py scripts/agent-guards/tests/test_shell_command_analysis.py
  • node --check scripts/session-recording/codex-hook-adapter.mjs

新規テストファイル名や module 名を変更した場合は、同等の対象を verification command に反映する。

Allowed Paths

  • scripts/session-recording/codex-hook-adapter.mjs
  • tests/session_recording/codex/test_hook_adapter.py
  • scripts/agent-guards/shell_command_analysis.py(新規。名称変更可)
  • scripts/agent-guards/tests/test_shell_command_analysis.py(新規。名称変更可)
  • docs/dev/session-recording-policy.md
  • docs/dev/hook-boundaries.md
  • pyproject.toml(third-party parser dependency を追加する場合のみ)
  • uv.lock(third-party parser dependency を追加する場合のみ)
  • package.json(Node parser dependency を採用する場合のみ)
  • pnpm-lock.yaml(Node parser dependency を採用する場合のみ)

Stop Conditions

  • Allowed Paths 外の変更が必要と判明した場合
  • In Scope の固定契約(キー集合・スキーマ・型定義)の変更が必要になった場合
  • 新規 Issue の起票が必要と判断した場合(スコープ分割が発生する場合)
  • 後続 Phase / 別スコープへの波及が判明した場合
  • nested SubAgent delegation が必要になった場合
  • 外部サービス利用・権限昇格・既存テスト大規模改変が必要になった場合
  • 実装: PreToolUse remote_write_requires_approval を publish lane 証跡で通過可能にする #1408 の publish authorization 条件そのものを変更しなければ目的を達成できない場合
  • Codex / Claude runtime 本体の hook schema または permission model の変更が必要になった場合
  • command structure analyzer が既知 execution-carrier 以外の構文(find -exec / xargs 等)を fail-open にしなければ実装できない場合
  • 新規 dependency の license compatibility を確認できない場合
  • native parser dependency により、サポート対象環境または CI で deterministic installation を保証できない場合
  • analyzer の出力に raw command、secret-like value、credential path を含める必要が生じた場合
  • 既存の PreToolUse output schema に破壊的変更が必要になった場合
  • match-ssot.sh 固有の hard-coded exception 以外に実装案を構成できない場合
  • fix: MANIFEST_ROOT を xdist 並列実行から分離する #1421 が本 Issue 着手前にまだ main へ merge されておらず、かつ fix: MANIFEST_ROOT を xdist 並列実行から分離する #1421 側の変更内容と本 Issue の変更内容が rebase で解決できない競合を起こす場合

Required Skills

  • JavaScript / Node.js ESM
  • Python 3.12
  • shell lexical analysis / command parsing
  • pytest parameterized regression tests
  • PreToolUse hook output contract
  • secure process invocation
  • dependency / license review

Required Design References

Delivery Rule

Scope Delta

#783 で導入された reason taxonomy と env-wrapper 対応を維持しつつ、分類単位を raw command string から静的に決定可能な command facts(literal/dynamic 区別、execution context、既知 execution-carrier)へ変更する。

full argv の out-of-the-box な出力は行わない。任意 argument 文字列を含む structured output は secret boundary と両立しないため、許可された enum のみを返す(In Scope 2 参照)。

#1408 が扱う「検出後の remote write authorization」は変更しない。git_mutation_command_policy.py の外部 API も変更しない。

Background

Issue #1413 の refinement 実行中、SSOT discovery のため次の read-only command が実行された。

.claude/skills/ssot-discovery/scripts/match-ssot.sh \
  --keywords "issue-refinement ... git push ..."

この command の executable は match-ssot.sh であり、git push は --keywords の argument data にすぎない。

しかし、session-recording PreToolUse classifier は command string 全体から git push という連続文字列を検出し、次の deny を返した。

remote_write_requires_approval [command_kind=git_push]

その結果、agent は mutation-like keyword を検索条件から除去して再実行した。

この運用では、guard の誤検知を避けるために調査語を弱めることになり、SSOT discovery、関連 Issue / PR 検索、過去障害検索の精度を低下させる。また、同種の誤検知は rg "git push"、git log --grep="git push"、安全性ドキュメントの検査などでも発生し得る。

一方、単純に quoted text を削除してから検査すると、次のような command substitution を見逃す。

echo "$(git push origin main)"

したがって必要なのは keyword allowlist や quote stripping ではなく、シェル上で実行される command node と、その command に渡される data argument の構造的な分離である。

敵対的レビューを反映した改訂について

本 Issue は、issuecomment-4939001380 の OWNER による敵対的レビューを受けて改訂された。同レビューは、issue-refinement-loop(investigation + web research)による独立検証で技術的に妥当と確認された(Issue #1420/PR #1421 との重複、git_mutation_command_policy.py の shlex 実装、Bash heredoc/here-string 展開セマンティクス、Git global option の credential 機密性、Codex CLI / Claude Code CLI の該当フラグ、主要 parser ライブラリのライセンス等)。

ただし、同レビューが提案した「Codex CLI / Claude Code の非対話モードによる実 GitHub remote への git push product smoke test を merge gate として必須化する」という提案(AC13〜19 相当)は、本 Issue 自身の Out of Scope(GitHub credential/OAuth/token scope の変更)および Stop Conditions(Codex / Claude runtime 本体の permission model 変更が必要になった場合)と緊張関係にあり、かつ本 Issue の目的(検出精度の改善)を超えるスコープであるため、本 Issue には反映せず Out of Scope に明記した。必要であれば別 Issue として起票する。

Activity

  1. added
    enhancement
    phase/implementation
    triage-required
    agent/implementer
    on Jul 10, 2026
  2. squne121 commented on Jul 10, 2026

    @squne121
    OwnerAuthor

    [create-issue] post-create ready tuple validation: label reconcile 完了。enhancement / phase/implementation / triage-required / agent/implementer の4ラベルを付与しました。 [ISSUE_COMMENT_1428_LABEL_RECONCILE_V1]

  3. squne121 commented on Jul 10, 2026

    @squne121
    OwnerAuthor

    you asked

    message time: 2026-07-11 04:26:21

    #1428
    内容について関連Issue、PR、リポジトリ資産、コメントを参照した上で敵対的レビューして。
    取り扱う技術や配布物の実装をWEB検索し高品質化してほしい。


    chatgpt response

    Issue #1428の主張と履歴、関連Issue/PR、コード・設定・配布資産を横断し、外部仕様・実装例と照合します。破綻条件、不足証拠、再現条件、修正要求を重大度順に整理します。


    chatgpt response

    現案は実質的に限定シェル解析器の導入で、#784の未検証ギャップを埋める一方、既存分類器との責務重複やfail-closed時の不整合が焦点です。


    chatgpt response

    外部仕様照合では、非引用heredocとhere-stringのcommand substitutionを「常にデータ」と扱う要件がbypassを生みます。さらに#1420/PR #1421も同一adapter・testを変更中で、競合条件の追加が必要です。


    chatgpt response

    敵対的レビュー結果

    判定

    REQUEST_CHANGES — 現状は implementation-ready: false です。

    観測された誤検知と、raw command 全体への正規表現判定を廃止する方向自体は妥当です。現行実装は実際に /\bgit(?:\s+-C\s+\S+)?\s+push\b/ を command 全体へ適用しており、検索語・説明文・quoted argument と executable position を区別していません。#783/#784 で reason taxonomy、env wrapper、mixed-command priority は改善されましたが、構文上の command/data 分離は残っています。 (GitHub)

    ただし #1428 は、単なる誤検知修正ではなく、Bash の静的フロントエンド、動的評価の不確実性モデル、別プロセス境界、配布依存関係、#1408 の認可ポリシー接続を同時に導入する契約です。その割に以下の設計が未確定または内部矛盾しています。Issueの唯一のコメントもラベル調整で、技術的な反証・合意はまだありません。


    Blocker 1 — #1420 / Draft PR #1421 が依存関係から欠落している

    2026年7月10日時点で、同じ scripts/session-recording/codex-hook-adapter.mjs と tests/session_recording/codex/test_hook_adapter.py を変更する Draft PR #1421 が存在します。これはテスト間で共有していた MANIFEST_ROOT による pytest-xdist フレークを直し、さらに当該テストを実際に実行するため .github/workflows/ci.yml と .github/ci/python-test-plan.json まで変更しています。

    PR #1421 の履歴では、当初の3ファイルだけの変更が uncovered-test fail-closed gate により python-test と node-backed-hook-tests を失敗させました。そのため CI workflow と test plan の追加変更が必要になっています。#1428 の Allowed Paths にはこの2ファイルがありません。

    したがって #1428 は次のどちらかを契約に追加する必要があります。

    1. blocked_by: #1420 / #1421 とし、fix: MANIFEST_ROOT を xdist 並列実行から分離する #1421 merge後の main へ必ず rebaseする。
    2. .github/workflows/ci.yml と .github/ci/python-test-plan.json を Allowed Paths に追加する。

    現状のまま #1421 より先に実装すると、既知のCIゲート問題を再発させる可能性が高く、Issue自身の「Allowed Paths外の変更が必要ならStop Condition」に抵触します。


    Blocker 2 — 「実際に実行される argv」を静的解析で確定する契約は成立しない

    Issueの commands[*].argv は、字句上の word と実行時 argv を区別していません。

    Bashでは構文解析後に、parameter expansion、command substitution、arithmetic expansion、word splitting、pathname expansion、quote removalなどが行われます。さらに、展開後の最初のwordが command name、残りがargumentsになります。つまり AST の Word を並べても実行時 argv にはなりません。(GNU)

    例えば次は構文木だけでは git push と確定できません。

    cmd=git
    "$cmd" push origin main
    git p$(printf ush) origin main
    bash -c 'exec "$0" "$@"' git push origin main

    commandを実行しないという要件を維持するなら、返せるのは「実際の argv」ではなく、静的 command template と literalnessです。

    必要な契約変更は次です。

    • command word が完全なliteralか、展開を含むdynamic wordかを区別する。
    • Git subcommandも literal | dynamic にする。
    • executableまたはsubcommandがdynamicで、remote-writeの有無に影響し得る場合は indeterminate にする。
    • commands[*].argv という名称を廃止する。少なくとも lexical_words または static_command_facts に変更する。

    これはフィールド名の微修正ではなく意味論の修正です。Issue内には「正確なfield名は変更可能」と「固定契約の変更が必要ならStop Condition」が併存しており、契約のnormative/illustrative区分も矛盾しています。


    Blocker 3 — 全argv出力と「raw/secret-like argumentを出力しない」が両立しない

    Issueは analyzer output に以下を要求しています。

    commands:
      - argv:
          - git
          - push
          - origin
          - main

    一方で「raw commandやsecret-like argumentをstructured outputに複製しない」とも要求しています。これは両立しません。argvには任意のtoken、header、credential、path、messageが含まれ得ます。

    Git自身も -c <name>=<value> や --config-env など、subcommand前に任意の設定値を受け取ります。Gitの公式文書も、一部の設定値には機密情報が含まれ得ることを明記しています。(Git)

    git -c http.extraHeader='Authorization: Bearer <token>' push origin main

    現行の blocked_command_preview はresponse生成時に限定的なregex redactionを行っていますが、analyzerが先にfull argvをJSON化すれば、その境界の外側で漏えいします。

    analyzer outputは次のような許可されたenumと分類結果だけに制限すべきです。

    • command_kind: git_push | rtk_git_push
    • wrapper: direct | rtk
    • remote_class: origin | other_literal | dynamic | absent
    • refspec_class: head_to_literal_branch | other_literal | dynamic | absent
    • dangerous_flags: [force, tags, all, mirror, delete]
    • execution_context
    • spanと不確実性reason

    任意argumentの文字列値は返してはいけません。#1408 が正確なrefspec値を必要とする場合も、同一trust boundary内で比較し、hook response・ログ・汎用analysis JSONには載せない設計が必要です。


    Blocker 4 — Bash commandの入力元とevent/tool境界が未定義

    現行の getCommand() は tool_input.command がなければ tool_input.description をcommandとして扱います。

    しかし session-recording adapter は Bash だけでなく、apply_patch | Edit | Write のPreToolUseおよびPermissionRequestからも呼ばれます。

    このまま analyzerを接続すると、以下をBash sourceとして解析する可能性があります。

    • patchやwrite操作のdescription
    • 文書中のshell example
    • edit内容に含まれる git push
    • Stop/SubagentStop payload中の説明データ

    呼び出し条件を明示的に固定すべきです。

    event ∈ {PreToolUse, PermissionRequest}
    AND tool_name == "Bash"
    AND typeof tool_input.command == "string"
    

    Bash toolなのにcommandがない、または型が異なる場合だけ malformed_payload としてfail-closedにします。description fallbackはremote-write analyzerから除外すべきです。Stop/SubagentStopおよび非Bash toolでは analyzerを起動してはいけません。


    Blocker 5 — heredocの契約が過度に一般化されている

    Issueのfixture例にあるquoted delimiterはdata-onlyです。

    cat <<'EOF'
    git push origin main
    EOF

    しかしAC2やOutcomeにある「heredoc bodyはremote writeと分類しない」という一般化は誤りです。delimiterがunquotedなら、heredoc bodyではcommand substitution、parameter expansion、arithmetic expansionが実行されます。here-stringのwordにもcommand substitutionが適用されます。(GNU)

    以下はdeny対象です。

    cat <<EOF
    $(git push origin main)
    EOF
    cat <<< "$(git push origin main)"

    AC2は次のように修正する必要があります。

    quoted heredoc delimiter により expansion が無効化されたbody内の git push はdata-only。unquoted heredoc、here-string、redirection operandに含まれるcommand/process substitutionは解析対象。

    assignment RHSやparameter expansion operandもcommand substitutionを含み得るため、単純なargument walkerでは不十分です。Bashはassignmentの = 右辺にもcommand substitutionを適用します。(GNU)


    Blocker 6 — shell ASTだけでは「実際に起動されるcommand」を網羅できない

    Issueは bash -c、sh -c、env、command を挙げていますが、実行対象をargumentとして受け取る構造はそれだけではありません。

    find . -maxdepth 0 -exec git push origin main \;
    xargs git push < push-args.txt
    printf 'git push origin main\n' | bash
    eval 'git push origin main'
    source generated-script.sh

    Bashの eval はargumentを新たなcommandとして読み直して実行し、. / source は指定ファイルを現在のshell contextで実行します。exec も後続argumentをcommandとして扱います。また bash -s はstdinからcommandを読みます。(GNU)

    特に find -exec git push ... は現行raw regexならdenyされますが、単純なAST walkerでは executableを find とだけ見てallowする可能性があります。これは誤検知修正ではなく、既存検出のfalse negative化です。

    必要なのは次のいずれかです。

    • eval、exec、source、bash|sh -c/-s、find -exec、xargs、sudo、timeout、nice、nohup、rtk等を対象とするbounded execution-carrier registryを定義する。
    • 未対応carrierについては indeterminate とする。
    • あるいはGoalを「すべての実行command」から「direct shell simple commandと明示されたwrapper registry」に狭める。

    未知の外部commandがargumentsをどう解釈するかを全て静的解決することはできないため、脅威モデルの境界を契約に書く必要があります。


    Blocker 7 — #1408 とのAPI接続が現在のAllowed Pathsでは実装不能

    #1408はpublish authorizationを scripts/agent-guards/git_mutation_command_policy.py に集約し、adapter側に別の安全判定を増やさないことを要求しています。(GitHub)

    しかし現在の共有policyは次の形です。

    def classify_rtk_git_mutation(
        command: str,
        *,
        cwd: str,
        require_active_branch_push: bool,
    )

    内部では shlex.split(command) によりraw command stringを再tokenizeしています。

    一方、#1428のDelivery Ruleは「#1428が先なら、#1408はstructured executable argvを入力にする」としていますが、#1428のAllowed Pathsにはpolicy本体とpolicy testがありません。

    解決方法は二つです。

    1. #1408を先に実装し、policyにargv/facts-native APIを追加してから #1428をrebaseする。
    2. #1428のAllowed Pathsに以下を追加し、raw-string APIを廃止またはadapter化する。
    scripts/agent-guards/git_mutation_command_policy.py
    scripts/agent-guards/tests/test_git_mutation_command_policy.py
    

    adapterで解析済みargvをshell文字列へ戻し、policyで再度shlex.splitする案は不可です。quote、expansion、provenanceを失い、二重parserによるsplit-brain policyになります。


    Blocker 8 — parser依存関係と配布ライセンスのStop Conditionが既に発火している

    確認できたrepository-wide license資産は LICENSES/README.md のplaceholderで、code/assetsごとにlicenseが異なり得るため公開前に確認する、という段階です。したがって「repositoryの配布licenseとの互換性」を現時点で確定できません。

    IssueのAC11検証コマンドは単なる次の確認です。

    test -f pyproject.toml

    Issue本文自身も、これは常時PASSするrepository不変条件であり、license/lockfile要件を検証しないと認めています。これはACではなくfalse-greenです。

    候補実装の評価は次のとおりです。

    bashlex — 採用不可

    pure Pythonで、command/process substitutionを含むASTを生成します。一方、arithmetic expressionを未サポートとし、複雑なparameter expansionはchild nodeを生成せずliteralとして扱います。ライセンスはGPLv3+です。必要な構文カバレッジと現在未確定のrepository licenseの両面で、#1428のStop Conditionsを通過できません。(GitHub)

    tree-sitter-bash — 条件付き候補

    MITで保守されており、最新releaseはv0.25.1です。ただしNode packageのdefault entrypointはnative bindingで、node-gyp-build install scriptを持ちます。Python側もC extensionです。packageにはprebuildやWASMも含まれますが、Node 24、Python 3.12、Linux/WSL2、CI対象architectureの全組み合わせでsource buildへfallbackしないことを検証する必要があります。(GitHub)

    採用するならnative bindingではなく、pinned WASM runtimeを明示的に選ぶ方が配布再現性は高くなります。ただしTree-sitterはerror recoveryを行うため、ERROR nodeやmissing nodeを明示的に indeterminate にしなければなりません。

    vorpaljs/bash-parser — 採用不可

    MITですがlatest releaseは2017年6月のv0.5.0です。security-sensitiveなshell parserの新規導入候補としては保守状況が不十分です。(GitHub)

    stock sh-syntax — そのままでは採用不可

    mvdan/shベースのWASM packageで、MIT、2026年7月8日にv0.6.0がreleaseされており、見た目上は適合します。(GitHub)

    しかし現行bridgeのresultにはfull inputの Text が含まれ、mapped command nodeは主に位置情報だけで、#1428が必要とするcommand node typeやnested execution semanticsを保持していません。raw commandを返さない要件にも抵触します。

    custom mvdan/sh bridge — 技術的には第一候補、現スコープでは不可

    mvdan/sh はPOSIX Shell、Bash、Zsh、mkshを扱い、BSD-3-Clause、継続的なreleaseとnative fuzzingがあります。文法品質では最有力です。(GitHub)

    ただし現在はGo 1.25以上を要求します。最小限のGo/WASM bridgeを独自に作る場合、Go/TinyGo toolchain、source、generated WASM、build script、license notice、checksum、reproducibility testの追加が必要です。これらは現Allowed Pathsにありません。

    結論: 技術的にはcustom mvdan/sh bridge、次点でtree-sitter-bashのpinned WASMですが、いずれもIssueを先にscope amendmentしなければ実装開始できません。


    その他の必須修正

    Git global optionのnormalizationが不足している

    Gitは -C だけでなく、-c、--git-dir、--work-tree、--namespace、--config-envなどをsubcommand前に受け取ります。(Git)

    以下もremote-write candidateです。

    git -c color.ui=false push origin main
    git --git-dir=.git push origin main
    git --work-tree=. push origin main

    global option parserはoptionごとのarity、--opt=value と --opt value、複数の -C を処理する必要があります。未対応optionはallowではなく indeterminate にすべきです。

    Git aliasとcustom git-* subcommandも公式にサポートされています。alias解決をOut of Scopeにする場合、少なくとも git -c alias.*=... を含むcommandを無条件allowしてはいけません。(Git)

    source spanの単位とnested source provenanceが未定義

    Tree-sitterはsource positionをraw byte単位で保持し、columnもbyte数です。JavaScript string indexやPython string indexとは単位が一致しません。(Tree-sitter)

    次を固定すべきです。

    • half-open interval [start, end)
    • UTF-8 byte offset
    • source_id
    • root sourceと bash -c 内部sourceの親子関係
    • inner decoded stringのspanとroot quoted argument spanの両方

    Unicode、CRLF、escaped newline、nested bash -c のテストが必要です。

    timeoutだけではresource boundaryにならない

    Node 24のexecFile()はdefaultでshellを使わず、timeout、maxBuffer、AbortSignalを持つため、外部analyzer呼び出しには適しています。(Node.js)

    一方、execFileSync()はtimeout後にSIGTERMを送っても、childがSIGTERMを処理して終了しなければ待ち続けます。(Node.js)

    最低限、以下を契約化すべきです。

    • maximum input bytes
    • maximum nesting depth
    • maximum AST node count
    • maximum candidate count
    • stdout/stderr byte cap
    • parser wall-clock timeout
    • unknown/oversized outputのfail-closed
    • child environmentのallowlist
    • shell: false
    • analyzerがchild/grandchild processを生成しないこと

    maxBuffer は文字数ではなくbyte数で、UTF-8 multibyte input/outputも考慮が必要です。(Node.js)

    classifier間の意味論が非対称になる

    remote-writeだけをAST化しても、forbidden pathとsecret boundaryはraw command regexのままです。現行priorityは forbidden path → secret boundary → remote writeです。

    例えば次は、実際にはremote-writeですがquoted data中の gh secret によりsecret reasonが先に返る可能性があります。

    printf '%s\n' 'gh secret list' && git push origin main

    全面AST化をOut of Scopeにすること自体は可能ですが、少なくともこの非対称性をKnown Limitationとしてdocsへ記載し、priority testを「既存reasonを維持」だけでなく「data-only文字列によるpriority乗っ取り」として追加すべきです。


    推奨する解析契約

    full argvを返す SHELL_COMMAND_ANALYSIS_V1 は破棄し、次のような最小情報契約に変更するのが妥当です。

    SHELL_COMMAND_ANALYSIS_V2:
      schema: SHELL_COMMAND_ANALYSIS_V2
      status: ok | indeterminate
    
      completeness:
        remote_write: complete | indeterminate
    
      candidates:
        - command_kind: git_push | rtk_git_push
    
          literalness:
            executable: literal
            git_subcommand: literal
    
          execution_context:
            kind: top_level
              | list
              | pipeline
              | command_substitution
              | process_substitution
              | heredoc_expansion
              | shell_c
              | execution_wrapper
    
          policy_facts:
            remote_class: origin | other_literal | dynamic | absent
            refspec_class:
              head_to_literal_branch
              | other_literal
              | dynamic
              | absent
            dangerous_flags:
              - force
              - tags
              - all
              - mirror
              - delete
    
          source:
            source_id: root
            start_utf8_byte: 0
            end_utf8_byte: 8
            parent_source_id: null
            parent_start_utf8_byte: null
            parent_end_utf8_byte: null
    
      uncertainty:
        reason_codes:
          - dynamic_command_word
          - dynamic_git_subcommand
          - unsupported_execution_carrier
          - malformed_shell
          - parse_error_node
          - analysis_timeout
          - resource_limit_exceeded

    要点は以下です。

    • arbitrary argvを出力しない。
    • dynamic command wordをliteral扱いしない。
    • parser全体の成否と、remote-write classificationの完全性を分離する。
    • unsupported constructが存在するだけで全commandをdenyするのではなく、remote-writeに影響し得るかを判定する。
    • schemaは実ファイルまたはstrict validatorとして固定し、unknown key、過大配列、範囲外spanをrejectする。
    • schema version、exact key set、maximum lengthsをtestsで固定する。

    event decision matrixも明文化すべき

    現行ではPreToolUseのremote writeはdeny、PermissionRequestではremote-write reasonだけstdoutなしのno_decisionです。

    Event / Tool complete・candidateなし remote-write candidate indeterminate
    PreToolUse / Bash pass #1408 policyへ委譲。未認可ならdeny deny
    PermissionRequest / Bash pass 現行どおりno_decision、または#1408の明示decision 明示deny
    PreToolUse / 非Bash analyzer非実行 analyzer非実行 analyzer非実行
    Stop / SubagentStop analyzer非実行 analyzer非実行 analyzer非実行

    parse failureをgeneric remote_write_requires_approval に変換すると、PermissionRequest側で no_decision に落ちる可能性があります。これはfail-closedではありません。parse failure reasonとclassified remote-write reasonを混同してはいけません。


    追加すべき敵対的fixture

    現行matrixに加えて、少なくとも次を固定すべきです。

    実行としてdeny

    git -c color.ui=false push origin main
    git --git-dir=.git push origin main
    cat <<EOF
    $(git push origin main)
    EOF
    cat <<< "$(git push origin main)"
    x="$(git push origin main)"
    echo "${x:-$(git push origin main)}"

    wrapper registryでdeny、未対応ならindeterminate

    find . -maxdepth 0 -exec git push origin main \;
    xargs git push < push-args.txt
    printf 'git push origin main\n' | bash
    eval 'git push origin main'
    source generated-script.sh

    必ずindeterminate

    "$command" push origin main
    git "$subcommand" origin main
    git p$(unknown-command)
    bash -c "$script"

    protocol/resource

    Unicodeを含むsource span
    CRLF
    escaped newline
    深いnested command substitution
    oversized input
    oversized stdout/stderr
    unknown schema
    extra properties
    negative / out-of-range spans
    duplicate candidate spans
    timeout
    child non-zero
    

    execution carrierに対応しない場合でも、少なくとも上記をsilent allowにしてはいけません。


    Issue本文へ反映すべき最小修正

    1. blocked_by: #1420 / #1421 を追加し、fix: MANIFEST_ROOT を xdist 並列実行から分離する #1421 merge後のrebase順序を明記する。
    2. #1408先行またはpolicyファイルのAllowed Paths追加を決める。
    3. 「実際のargv」を「static command facts + literalness」に変更する。
    4. full argv をschemaから削除する。
    5. direct simple commandとexecution-carrier registryの境界を明記する。
    6. quoted/unquoted heredocとhere-stringを分離する。
    7. Bash tool/event gateを固定し、description fallbackを禁止する。
    8. Git global option normalizerを追加する。
    9. spanをUTF-8 byteのhalf-open intervalとして固定し、nested source provenanceを追加する。
    10. parser input、AST、output、timeoutのresource limitsを定義する。
    11. PermissionRequestを含むevent decision matrixを固定する。
    12. AC11の test -f pyproject.toml を削除し、実際のdependency import、locked install、platform matrix、license/provenanceを検証する。
    13. parser/WASM/native assetを導入する場合のsource、build recipe、toolchain version、SHA-256、license notice、reproducibility test用パスをAllowed Pathsへ追加する。
    14. SHELL_COMMAND_ANALYSIS_V2 のstrict schemaまたはvalidatorを正本として追加する。

    最終判定

    LOOP_ADVERSARIAL_REVIEW_V1:
      verdict: REQUEST_CHANGES
      implementation_ready: false
    
      blockers:
        - missing_dependency_on_1420_1421
        - runtime_argv_not_statically_determinable
        - full_argv_conflicts_with_secret_boundary
        - bash_tool_and_event_provenance_undefined
        - heredoc_semantics_incorrectly_generalized
        - indirect_execution_carriers_unmodeled
        - policy_api_conflicts_with_1408_and_allowed_paths
        - parser_license_and_distribution_review_incomplete
    
      required_before_implementation:
        - dependency_and_rebase_order_fixed
        - analysis_schema_rewritten
        - threat_model_bounded
        - parser_and_distribution_strategy_approved
        - event_and_resource_contract_fixed

    現状の phase/implementation は早く、設計契約を修正してから実装へ戻すべきIssueです。


    you asked

    message time: 2026-07-11 05:04:11

    「実際の remote branch に対する git push は verification として実行しない。」
    ClaudeCode,CodexCLI 影響する製品の動作検証は行ってほしい。
    実装PRへgit pushを試して動作検証できないか?非対話でClaudeCode,CodexCLIなどの動作検証する、などhookの動作検証方法を検索して。


    chatgpt response

    検証を「実remote mutation禁止」で切るのは弱すぎます。公式CLIの非対話モード、hook dispatch、権限・trust設定、実pushを安全に限定する方法を確認し、#1428へ追加すべき実動作ACを整理します。

    Codex側は状況が変わっています。codex exec のhook trust引き継ぎ不具合は2026年6月16日に修正がmergeされ、0.141.0以降へ入っているため、旧来の「diagnostic-only」扱いは更新対象です。

    結論

    実装PRのhead branchに対する実際の git push を、動作検証として実行できます。むしろ #1428 は、CLI本体を通した実動作検証を必須にすべきです。

    ただし、危険なpush形状まで実GitHub repositoryで試してはいけません。

    • main / master
    • force / force-with-lease
    • tag / all / mirror
    • delete
    • 複数refspec
    • 認可証跡なしのbranch

    これらのdeny検証は、認証情報を持たない環境または一時bare repositoryで行います。GitHubに対して実行するのは、実装PRのhead branchへの単一refspec・fast-forward pushだけです。

    #1428の次の記述は変更すべきです。

    実際の remote branch に対する git push は verification として実行しない。

    変更後の方針は次が適切です。

    危険なpush形状を実remoteへ送信する検証は行わない。
    実装PRのhead branchに対する、単一refspecかつfast-forwardの実publish commandは、precondition・publish evidence・post-push readbackを満たす場合に限り、必須の製品runtime verificationとして1回実行する。


    Codex CLIは非対話検証できる

    OpenAI公式では、codex exec がスクリプトやCI向けの非対話実行インターフェースです。sandboxとapprovalを事前設定でき、--json でJSONLイベントを取得できます。(ChatGPT学習)

    以前問題だった「codex exec ではhookがdispatchされない」という不具合は状況が変わっています。

    • Codex CLI 0.139.0では、--dangerously-bypass-hook-trust を指定してもhookが実行されない再現報告がありました。
    • 修正PRでは、codex exec のthread start/resumeにhook trust bypassを引き継ぎ、実際にmarker fileを生成するE2E testが追加されました。
    • その修正は2026年6月18日リリースの0.141.0に含まれています。(GitHub)
    • 2026年7月11日時点の最新stableは0.144.1です。(GitHub)

    したがって、以前共有された Codex CLI 0.139.0のままなら検証前に0.141.0以上へ更新が必要です。#783のdocsに残っている「upstream issueがopenなのでdiagnostic-only」という説明も、Issueがopenのままであっても修正・release済みという現在の実態に更新すべきです。

    Codexのproject hookは、one-off automationでは --dangerously-bypass-hook-trust により永続trustなしで実行できます。このflagはhook trustだけを対象とします。--dangerously-bypass-approvals-and-sandbox はapprovalとsandboxを無効化するため、今回の検証では使用しません。(OpenAI Developers)


    Claude Codeも非対話検証できる

    Claude Codeは claude -p が非対話実行モードです。--allowedTools、--output-format、permission modeなどを使用できます。(Claude)

    今回のような検証では、次の組み合わせが使えます。

    • --tools Bash:モデルへ公開するbuilt-in toolをBashだけに限定
    • --allowedTools "Bash(<exact command>)":対象commandだけを許可
    • --permission-mode dontAsk:allow rule外の操作を非対話で拒否
    • --setting-sources project:project settingsに限定
    • --settings <test-settings.json>:検証専用設定の追加
    • --output-format stream-json --verbose:実行イベント取得
    • --debug-file <path>:hook match、exit code、stdout/stderrを確認

    これらは公式CLIで提供されています。(Claude)

    Claude Codeのdebug logにはhookのmatch結果、exit code、完全なstdout/stderrが記録されます。検証には有効ですが、raw commandやsecretを含む可能性があるため、PRにはそのまま掲載せず、private artifactとして保存してredacted summaryだけを公開します。(Claude)

    なお、--bare と --safe-mode はhookをロードしないため、今回の検証では使用不可です。(Claude)


    推奨する4段階の検証

    1. Parser / hook entrypointの決定論的テスト

    現在のpytest方式です。

    printf '%s' "$PRETOOL_PAYLOAD" \
      | node .codex/hooks/session-recording-composite.mjs --event PreToolUse

    ここでは以下を検証します。

    • data-onlyの git push はstdoutなし
    • 実行される git push はdeny
    • parse-indeterminateはdeny
    • output shape
    • redaction
    • timeout / malformed JSON

    ただし、これはadapterを直接起動しているだけで、Codex CLIがhookを発火させた証明にはなりません。


    2. CLI本体+一時bare remoteによる実push

    GitHub credentialを使わず、実際のGit subprocessとremote ref updateを確認します。

    概念的には以下です。

    temporary bare repository
            ↑ origin
    temporary clone containing PR implementation
            ↑
    Codex CLI / Claude Code
            ↑
    PreToolUse hook
    

    この環境で以下を行います。

    • data-only commandが通過する
    • direct pushがdenyされる
    • nested pushがdenyされる
    • 検証済みbranch pushだけallowされる
    • remote branchが実際にlocal HEADへ更新される
    • post-push git ls-remote が一致する

    denyが壊れていてもGitHubへ影響しないため、adversarial fixtureはこのレーンで実行します。


    3. Codex / Claudeの非対話product smoke

    Codex CLI

    概念例です。

    branch="$(git branch --show-current)"
    artifact_dir="tmp/runtime-proof/codex"
    mkdir -p "$artifact_dir"
    
    codex exec \
      -C "$PWD" \
      --ephemeral \
      --json \
      --dangerously-bypass-hook-trust \
      --sandbox danger-full-access \
      "Use the Bash tool exactly once. Run exactly:
    rtk git push origin HEAD:refs/heads/${branch}
    Do not run another command." \
      >"$artifact_dir/events.jsonl"

    danger-full-access はGit network accessが必要な場合に限り、隔離されたworktree・container・runnerで使用します。通常のローカル自動処理には workspace-write が推奨され、approval/sandbox bypassは専用sandbox VM以外では避けるよう公式にも案内されています。(ChatGPT学習)

    有効な検証結果とする条件は次です。

    codex_product_smoke:
      version: ">= 0.141.0"
      pretool_hook_marker_count: 1
      observed_tool_name: Bash
      exact_command_hash_match: true
      permission_request_result: allow | not_required
      bash_exit_code: 0
      model_alternative_command_count: 0

    CodexのPreToolUseは、現時点でもすべてのshell execution pathを捕捉する完全なsecurity boundaryではなく、unified_exec等のinterceptionには未完成部分があります。そのため、「hook markerが実際に1件発生したこと」を必須assertionにします。markerがなければ、pushが成功していてもproduct smokeは失敗です。(OpenAI Developers)

    Claude Code

    branch="$(git branch --show-current)"
    artifact_dir="tmp/runtime-proof/claude"
    mkdir -p "$artifact_dir"
    
    claude -p \
      --tools "Bash" \
      --allowedTools "Bash(rtk git push origin HEAD:refs/heads/${branch})" \
      --disallowedTools "mcp__*" \
      --permission-mode dontAsk \
      --setting-sources project \
      --no-session-persistence \
      --output-format stream-json \
      --verbose \
      --debug-file "$artifact_dir/debug.log" \
      "Use Bash exactly once. Run exactly:
    rtk git push origin HEAD:refs/heads/${branch}
    Do not run another command." \
      >"$artifact_dir/events.jsonl"

    Claude CodeのPreToolUseはtool実行前に発火し、denyまたはexit code 2ならtool callを停止します。PermissionRequestは実際にpermission dialogが必要になる操作だけで発火します。(Claude)

    したがって、PreToolUseとPermissionRequestは別々に評価します。

    claude_product_smoke:
      pretooluse:
        required: true
        observed: true
      permission_request:
        required_only_when_permission_would_be_requested: true
      exact_command_hash_match: true
      alternative_command_count: 0
      bash_exit_code: 0

    4. 実装PR branchへの実GitHub push

    これを最終runtime gateにします。

    Precondition

    branch="$(git branch --show-current)"
    local_head="$(git rev-parse HEAD)"
    remote_before="$(
      git ls-remote --exit-code origin "refs/heads/$branch" |
      awk '{print $1}'
    )"

    必須条件:

    live_push_precondition:
      branch_is_pr_head: true
      branch_not_main_or_master: true
      remote: origin
      refspec: HEAD:refs/heads/<exact-active-branch>
      single_refspec: true
      expected_remote_head_equals_fresh_remote_head: true
      remote_before_is_ancestor_of_local_head: true
      local_head_equals_declared_publish_head: true
      local_head_equals_verified_head: true
      allowed_paths_gate_status: ok
      force_flags_absent: true
      tag_delete_mirror_all_absent: true

    そのうえで、Codex CLIまたはClaude Code自身に次の一命令だけを実行させます。

    rtk git push origin "HEAD:refs/heads/$branch"

    Postcondition

    remote_after="$(
      git ls-remote --exit-code origin "refs/heads/$branch" |
      awk '{print $1}'
    )"
    
    test "$remote_after" = "$local_head"

    さらにPRのhead SHAも照合します。

    gh pr view "$pr_number" \
      --json headRefName,headRefOid

    最終証跡は次で十分です。

    LIVE_PR_PUSH_VERIFICATION_V1:
      product: codex_cli | claude_code
      product_version: "<version>"
      pr_number: <number>
      branch: "<implementation-branch>"
      command_shape: "rtk git push origin HEAD:refs/heads/<branch>"
      command_sha256: "<digest>"
      remote_head_before: "<sha>"
      local_head: "<sha>"
      remote_head_after: "<sha>"
      pr_head_after: "<sha>"
      pretooluse_observed: true
      pretooluse_decision: allow
      permission_request_observed: true | false
      permission_request_decision: allow | not_required
      push_exit_code: 0
      remote_head_after_equals_local_head: true

    raw command全文、environment、credential、debug log本文は公開証跡へ載せません。


    no-op pushと実更新pushの違い

    branchが既に同期済みの場合、

    Everything up-to-date
    

    となるno-op pushでも、以下は検証できます。

    • CLIからBash toolが呼ばれた
    • PreToolUseが発火した
    • hookがallowした
    • sandbox / permissionを通過した
    • GitHub authenticationとremote接続が成功した

    ただし、remote refの状態遷移は検証できません。

    したがって最良なのは、実装commitをremoteへ初めてpublishする通常のpushそのものをruntime verificationにすることです。検証専用の無意味なcommitは作成しません。既に同期済みならno-op結果を部分的な証跡として扱い、次の実装commit publish時に状態遷移の証跡を取得します。


    #1428へ追加すべきAC

    AC13:
      Codex CLI 0.141.0以上のcodex execを使用し、
      project PreToolUse hookが実際にdispatchされたことをmarkerとJSONLで確認する。
    
    AC14:
      Claude Codeのclaude -pを使用し、
      PreToolUse hookのallow / deny / indeterminateを非対話で確認する。
    
    AC15:
      一時bare originに対し、両CLIから実git pushを実行し、
      adversarial denyとbounded allowを検証する。
    
    AC16:
      実装PRのhead branchに対して、
      実装commitの単一refspec fast-forward pushを1回実行する。
    
    AC17:
      push前後にgit ls-remoteを実行し、
      remote_before == expected_remote_head、
      remote_after == local_head、
      PR head == local_headを確認する。
    
    AC18:
      PreToolUse markerが観測できなかった場合、
      push自体が成功してもruntime verificationをFAILとする。
    
    AC19:
      main/master、force、tag、mirror、delete等のdeny検証は
      実GitHub remoteではなく一時bare remoteでのみ実行する。

    Runtime Verification Applicabilityの修正案

    decision: required
    runtime_verification_applicability: required
    reason: >
      本IssueはCodex CLI / Claude Codeの実hook dispatch、
      PreToolUse / PermissionRequest decision処理、
      sandbox・trust・非対話実行、およびgit remote updateを変更対象とする。
      adapter単体fixtureでは製品runtimeがhookをdispatchすること、
      denyがtool execution前に適用されること、
      bounded publish laneが実remote updateを完了できることを証明できない。
      そのため、local bare remoteを用いた製品E2Eと、
      実装PR head branchへの単一refspec fast-forward pushを必須とする。

    判断としては、現在の not_applicable は不適切です。
    #1428はCodex CLIの実製品smokeをmerge gateにし、Claude Codeについても同一analyzerをhookから呼び出す構成なら必須、少なくとも互換product smokeとして実施するのが妥当です。

  4. squne121 commented on Jul 10, 2026

    @squne121
    OwnerAuthor

    Refinement Loop: Human Escalation Required

    The loop has terminated and requires human review. Cause: human judgment required

    Blockers

    "reviewer_claim_replay: producer_body_sha256とlive body shaの不一致によりinput_or_runtime_error(body_sha_mismatch)。正式な自動裁定不可"
    
    "review-issue skill自体のchecker実装バグを検出: check_issue_contract.py の check_c2_stop_conditions() (line 857) が '^- ' のみ認識し '*' bulletを見落とす。共有BULLET_RE([-*+])との不整合。Issue #1428のStop Conditionsは*bulletで14項目正しく存在するがC2は0件と誤判定"
    
    "残る3 blocker(VC preflight command_not_allowed AC1-AC9、AC11 unexpected pass未annotation、VC_UNKNOWN unsafe commands)はIssue本文側の実質的な修正が必要"
    
    "anchor commentのAC13-19提案(実GitHub remoteへのgit push runtime verification必須化)はIssue本文のOut of Scope/Stop Conditionsと緊張関係にあり、scope_delta_decisionはfail_closed(no_anchor_scope_reframe_v1_payload)。OWNER判断が必要"
    
    "anchor comment Blocker1(#1420/PR#1421との重複)・Blocker7(shlex実装)は独立調査で技術的に正確と確認済み。web researchでも大半のcritical外部仕様claimが検証済み"
    
  5. squne121 commented on Jul 11, 2026

    @squne121
    OwnerAuthor

    Contract Review Result

    CONTRACT_REVIEW_RESULT_V1:
      status: go
      generated_at: "2026-07-11T01:02:28Z"
      generated_by: issue-contract-review
      issue_url: https://github.com/squne121/loop-protocol/issues/1428
      body_sha256: "sha256:af2fdee5892bcdcc90937b7cf2b46bb0fa9751651f73804eeb48dd619dbe0ef2"
      checks:
        readiness: go
        blockers: pass
        product_spec: pass
        vc_preflight: pass
      source: ensure_contract_snapshot_auto
  6. squne121 commented on Jul 11, 2026

    @squne121
    OwnerAuthor

    implement-issue: 実装完了

    • PR: fix: PreToolUse remote write classifier を command structure 解析ベースに置き換える #1441 (Draft, head fc4f9b0)
    • Worktree: .claude/worktrees/issue-1428-pretooluse-git-push
    • Branch: worktree-issue-1428-pretooluse-git-push
    • Verification: 主要 VC 全 PASS(tests/session_recording/codex/test_hook_adapter.py 65 passed、scripts/agent-guards/tests/test_shell_command_analysis.py 46 passed、test_git_mutation_command_policy.py 19 passed、ruff/node --check green)
    • third-party parser dependency: 未導入(AC11 は N/A、bounded grammar hand-written analyzer で実装)
    • 後続: PR レビュー(pr-review-judge)→ マージ → post-merge-cleanup
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    agent/implementerenhancementphase/implementationtriage-required

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions