Skip to content

実装: active issue worktree 外への Write/Edit/Bash mutation を hook で遮断する #960

Closed

Description

@squne121

Machine-Readable Contract

contract_schema_version: v1
issue_kind: implementation
parent_issue: "none"
goal_ref: "subagent の Read/Edit/Bash mutation が intended worktree ではなく main checkout に解決されて main を汚染する事故を、説明規則だけでなく PreToolUse hook で fail-closed に遮断する"
change_kind: workflow

Parent Issue

none(単独改善 / mutation safety hardening の一部)

Parent Goal Ref

  • Goal: active issue worktree が存在するとき、その worktree 外への Write/Edit/mutating Bash を hook で block し、main checkout 汚染と別 Issue 作業との混線を構造的に防ぐ
  • Desired Destination: worktree_scope_guard が PreToolUse で動作し、worktree 外 mutation を block、read-only は allow、secret boundary guard との順序が固定される

Current Validated Scope

  • .claude/hooks/worktree_scope_guard.sh(薄い wrapper)と .claude/hooks/worktree_scope_guard.py(判定本体)を新規追加する
  • .claude/settings.json の PreToolUse に Bash|Write|Edit|MultiEdit matcher で guard を追加する(secret boundary guard より後段)
  • .claude/hooks/tests/test_worktree_scope_guard.py を新規追加する
  • expected worktree 解決規約(WORKTREE_SCOPE_RESOLUTION_V1)と mutating Bash classifier の最小集合を本 Issue で固定する
  • path containment を realpath / commonpath で判定し、symlink / .. traversal / absolute outside を遮断する
  • malformed payload / git binary 不在 / worktree 0 件・複数件の fail-closed 挙動を固定する

Remaining Parent Gaps

  • git add -A 混入や Allowed Paths 外 staged diff の遮断は別 Issue(staging guard)で扱う
  • subagent 成功報告の証跡 gate は別 Issue(evidence gate)で扱う
  • 既存 secret_boundary_guard の MultiEdit 対応拡張は既存 hook 挙動変更にあたるため別 Issue(follow-up)で扱う(本 Issue では既存 secret guard を変更しない)

Outcome

active issue worktree が存在するとき、worktree 外への Write/Edit/MultiEdit と mutating Bash(git add/commit/checkout/push, gh pr/issue mutation, gh api の書き込みメソッド, package manager mutation, shell file-write 等)が hook で fail-closed に block され、read-only Bash と worktree 内 mutation は allow される状態。path 判定は realpath / commonpath で行い symlink / .. traversal を防ぐ。expected worktree 解決は WORKTREE_SCOPE_RESOLUTION_V1 の precedence で決定論的に行い、worktree 0 件・複数件・malformed payload・git binary 不在は mutation に対して block(fail-closed)する。block message は bounded(expected worktree と actual cwd のみ)で secret path / command / env を漏らさない。secret boundary guard が共有 tool で先行する順序がテストで固定され、新規 pytest と pnpm typecheck/lint/test/build・既存 settings 検証が PASS する。

In Scope

  • Hook stdin(cwd / tool name / tool input)と環境変数からの active issue / expected worktree 解決(WORKTREE_SCOPE_RESOLUTION_V1)
  • Edit/Write/MultiEdit 対象 path を realpath / commonpath で正規化し、expected worktree 外なら block
  • mutating Bash(git / gh / package manager / shell file-write)の最小 classifier(MUTATING_BASH_CLASSIFIER_V1)を実装し、worktree 外なら block
  • git -C <path> / 先頭 cd <path> && / bash -c|-lc / sh -c / command git / env VAR=... git 等の wrapper を検出し effective target を判定
  • Read/Grep/Glob と read-only Bash(git status/diff/log, gh pr/issue view 等)は原則 allow(secret boundary guard は現行どおり先行)
  • settings.json への PreToolUse 追加(secret boundary guard の後段)
  • guard failure message の上限(20 行以内、expected worktree と actual cwd のみ、command / path / worktree list / env を出さない)
  • malformed payload / git binary 不在 / worktree 0 件・複数件・branch-path mismatch の fail-closed 挙動固定
  • 対応するテスト追加と secret guard との順序固定

Out of Scope

  • git add -A / Allowed Paths 外 staged diff の判定(別 Issue)
  • subagent 成功報告の証跡判定(別 Issue)
  • 既存 secret_boundary_guard の matcher / SENSITIVE_TOOLS への MultiEdit 追加(既存 hook 挙動変更のため別 Issue follow-up)
  • worktree 自体の作成 / 削除ロジック変更
  • Allowed Paths を .claude/hooks/** + settings + tests 以外へ拡張すること
  • 完全な shell interpreter の実装(classifier は最小集合 + 解析不能時 fail-closed で代替する)

Resolver Contract(WORKTREE_SCOPE_RESOLUTION_V1)

expected worktree の解決は以下の precedence で決定論的に行う。実装者ごとに resolver が揺れないよう本 Issue で固定する。

WORKTREE_SCOPE_RESOLUTION_V1:
  project_root_source_precedence:
    - CLAUDE_PROJECT_DIR
    - settings_json_parent_resolution   # .claude/settings.json の親を辿る。git rev-parse --show-toplevel は worktree isolation で main root を返すため使わない
  current_issue_source_precedence:
    - env LOOP_ISSUE_NUMBER
    - cwd basename /^issue-(\d+)-/
    - current_branch /^issue-(\d+)-/
  worktree_catalog:
    command: git -C <project_root> worktree list --porcelain -z
    parser: nul_record_parser   # worktree 行始まりの NUL 区切り record を解析する
  expected_worktree_selection:
    match:
      - branch == refs/heads/issue-<issue>-*
      - path basename == issue-<issue>-*
    zero_matches_for_mutation: block      # fail-closed
    multiple_matches_for_mutation: block  # fail-closed
    zero_matches_for_read_only: allow
  fail_closed:
    malformed_stdin_for_matched_mutation_tool: block
    git_binary_unavailable_for_mutation: block
    unparseable_bash_with_possible_mutation: block

Mutating Bash Classifier(MUTATING_BASH_CLASSIFIER_V1)

worktree 外で block すべき mutating Bash の最小集合を固定する。完全な shell 解釈は行わず、解析不能で mutation 可能性が残る場合は worktree 外では block(fail-closed)する。

MUTATING_BASH_CLASSIFIER_V1:
  git:
    - add, commit, push, checkout, switch, restore, reset, rebase, merge,
      cherry-pick, revert, am, apply, rm, mv, tag, stash (list/show 以外),
      worktree (list 以外)
  gh:
    - pr create/edit/merge/review/comment/close/reopen/ready/draft/lock/unlock
    - issue create/edit/comment/close/reopen/delete/lock/unlock
    - api with -X/--method PATCH|POST|PUT|DELETE
    - api with -f/-F/--field/--raw-field/--input(明示 GET を除く)
  package_managers:
    - npm/pnpm/yarn/bun add/install/remove/update/publish/version/link/unlink
  filesystem_write_patterns:
    - shell redirection >, >>, tee, sed -i, perl -i
    - python/node/ruby のファイル書き込み one-liner
  read_only_allow (worktree 解決不能でも allow):
    - git status/diff/log/show/rev-parse/worktree list
    - gh pr view, gh issue view, gh api(明示 GET)

Acceptance Criteria

  • AC1: cwd=/repo で .claude/skills/** への Write/Edit を試みた場合、active issue worktree が存在するなら block する。
  • AC2: cwd=/repo/.claude/worktrees/issue-942-x で同 worktree 内 path への Write/Edit は allow する。
  • AC3: git commit / git add / git push / gh pr create / gh pr edit は expected worktree 外では block する。
  • AC4: git status / git diff / gh pr view / gh issue view など read-only Bash は allow する。
  • AC5: guard failure message は 20 行以内で、expected worktree と actual cwd のみを示し、full path dump をしない。
  • AC6: secret boundary guard と worktree scope guard が共に matcher に含む tool(Bash/Write/Edit)について、secret guard が先行する実行順序をテストで固定する。MultiEdit は現行 secret guard の matcher 外のため、worktree guard の block message が bounded(AC13)であることで secret path 漏洩を防ぐ。secret guard の MultiEdit 拡張は別 Issue(follow-up)で扱う。
  • AC7: uv run pytest .claude/hooks/tests/test_worktree_scope_guard.py, pnpm test -- tests/agent-session-manifest.test.ts, pnpm typecheck, pnpm lint, pnpm build が PASS する。
  • AC8: mutating Bash classifier は MUTATING_BASH_CLASSIFIER_V1 の git / gh / package manager / shell file-write 集合を expected worktree 外で block する。
  • AC9: cwd が expected worktree 内でも、git -C /repo commit / cd /repo && git add のように explicit target が外を指す場合は block する。
  • AC10: gh api -X PATCH / gh api -f ... / gh issue comment / gh pr merge / gh pr review / gh pr comment は expected worktree 外で block する。
  • AC11: Write/Edit/MultiEdit の target path は realpath / commonpath で判定し、symlink outside / .. traversal / absolute outside を block する(startswith 不可)。
  • AC12: active issue worktree が 0 件 / 複数件 / branch-path mismatch のときの decision を固定する(mutation は block、read-only は allow)。
  • AC13: block stderr は 20 行以内で、tool command・tool input path・worktree list・env を含まない。
  • AC14: git worktree list --porcelain -z の NUL 区切り fixture を parser が正しく処理する。
  • AC15: malformed stdin payload(matched mutation tool)/ git binary 不在 / 解析不能な mutation 候補 Bash は fail-closed で block する。

Runtime Verification Applicability

decision: not_applicable
reason: "PreToolUse hook の判定ロジックは pytest で stdin/stdout 契約として検証でき、外部 service 実行を成功条件に含まない。settings 配線は既存 manifest テストで確認する"

Verification Commands

baseline では新規 hook / test が未作成のため、AC1〜AC6 および AC8〜AC15 の pytest は file not found(pytest exit 4)で baseline-fail する(baseline-expect: fail)。実装後に PASS する。AC7 の pnpm 群は regression gate。

# AC1
# baseline-expect: fail
$ uv run pytest .claude/hooks/tests/test_worktree_scope_guard.py -k "block_outside_worktree" -v
# AC2
# baseline-expect: fail
$ uv run pytest .claude/hooks/tests/test_worktree_scope_guard.py -k "allow_inside_worktree" -v
# AC3
# baseline-expect: fail
$ uv run pytest .claude/hooks/tests/test_worktree_scope_guard.py -k "block_mutating_bash" -v
# AC4
# baseline-expect: fail
$ uv run pytest .claude/hooks/tests/test_worktree_scope_guard.py -k "allow_read_only_bash" -v
# AC5
# baseline-expect: fail
$ uv run pytest .claude/hooks/tests/test_worktree_scope_guard.py -k "message_bounded" -v
# AC6
# baseline-expect: fail
$ uv run pytest .claude/hooks/tests/test_worktree_scope_guard.py -k "guard_ordering" -v
# AC8
# baseline-expect: fail
$ uv run pytest .claude/hooks/tests/test_worktree_scope_guard.py -k "classifier_minimal_set" -v
# AC9
# baseline-expect: fail
$ uv run pytest .claude/hooks/tests/test_worktree_scope_guard.py -k "block_wrapper_explicit_target" -v
# AC10
# baseline-expect: fail
$ uv run pytest .claude/hooks/tests/test_worktree_scope_guard.py -k "block_gh_api_and_mutations" -v
# AC11
# baseline-expect: fail
$ uv run pytest .claude/hooks/tests/test_worktree_scope_guard.py -k "path_containment_realpath" -v
# AC12
# baseline-expect: fail
$ uv run pytest .claude/hooks/tests/test_worktree_scope_guard.py -k "worktree_ambiguity_decision" -v
# AC13
# baseline-expect: fail
$ uv run pytest .claude/hooks/tests/test_worktree_scope_guard.py -k "stderr_bounded_no_leak" -v
# AC14
# baseline-expect: fail
$ uv run pytest .claude/hooks/tests/test_worktree_scope_guard.py -k "porcelain_z_parser" -v
# AC15
# baseline-expect: fail
$ uv run pytest .claude/hooks/tests/test_worktree_scope_guard.py -k "fail_closed_malformed_or_missing" -v
# AC7
$ uv run pytest .claude/hooks/tests/test_worktree_scope_guard.py
$ pnpm test -- tests/agent-session-manifest.test.ts
$ pnpm typecheck
$ pnpm lint
$ pnpm build

Allowed Paths

  • .claude/hooks/worktree_scope_guard.sh
  • .claude/hooks/worktree_scope_guard.py
  • .claude/hooks/tests/test_worktree_scope_guard.py
  • .claude/settings.json

Stop Conditions

  • Allowed Paths 外の変更が必要と判明した場合
  • 既存 PreToolUse hook(secret guard 等)の挙動を変更する必要が出た場合
  • expected worktree 解決方式が WORKTREE_SCOPE_RESOLUTION_V1 の precedence で決定できないと判明した場合
  • 新規 Issue の起票が必要と判断した場合(スコープ分割)
  • 外部サービス利用・権限昇格・既存テスト大規模改変が必要になった場合
  • AC8〜AC15 で要求する classifier / path containment / fail-closed 範囲が Allowed Paths 内で完結できないと判明した場合

Required Skills

  • Bash / Python 3(PreToolUse hook の stdin/stdout 契約、realpath / commonpath による path containment)
  • Claude Code settings.json hook 配線
  • git worktree のパス解決(git worktree list --porcelain -z の NUL record parser)

Scope Delta(任意)

anchor comment(#960 への request_changes レビュー)の指摘を反映し、契約を強化した:

  • WORKTREE_SCOPE_RESOLUTION_V1(resolver precedence / 0 件・複数件 fail-closed)を追加
  • MUTATING_BASH_CLASSIFIER_V1(gh api / gh issue/pr mutation / git -C/cd wrapper / package manager / shell file-write)を追加
  • path containment を realpath / commonpath 必須に明記(symlink / .. traversal 遮断)
  • malformed payload / git binary 不在の fail-closed を明記
  • MultiEdit と secret guard の順序判断を確定(既存 secret guard は変更せず、bounded message で secret 漏洩を防止、MultiEdit secret 拡張は follow-up)
  • AC8〜AC15 を追加し、Stop Conditions を 6 項目に拡張

Activity

  1. added
    phase/implementation
    agent/implementer
    enhancement
    on Jun 17, 2026
  2. squne121 commented on Jun 17, 2026

    @squne121
    OwnerAuthor

    CONTRACT_REVIEW_RESULT_V1

    status: go
    issue: 960
    repo: squne121/loop-protocol
    checks:
      template_compliance: pass
      state_label: pass        # state/needs-human なし
      allowed_paths_present: pass
      vc_present: pass
      stop_conditions_complete: pass
      ac_verifiability: pass    # AC1..AC7 が VC # AC1..# AC7 と一致、決定論的(exit code)
      product_spec_check: not_applicable
      worktree_branch_collision: pass   # issue-960 用 worktree / branch は未作成
      blocked_reasons: []
      next_action: handoff_to_implement_issue
    vc_preflight:
      summary:
        vc_expected_pass: 2
        vc_failed_as_expected: 6
        vc_human_judgment: 0
        vc_passed_unexpectedly: 0
        vc_unrunnable: 0
      classifications:
        - ac: AC1..AC6
          scope_class: baseline_fail_expected
          decision: go
          note: "新規 .claude/hooks/tests/test_worktree_scope_guard.py が未作成のため pytest exit 4 (file not found) = expected baseline fail"
        - ac: AC7 (pnpm test / typecheck)
          scope_class: regression_gate
          decision: go
          note: "CI=true で expected_pass"
        - ac: AC7 (pnpm lint / build)
          scope_class: regression_gate
          decision: go
          note: |
            main working tree では untracked artifact (playwright-report/, artifacts/) を
            eslint が拾い ERR で blocked になるが、これは #960 の contract 欠陥ではなく
            環境汚染。origin/main の clean worktree + CI=true で lint exit 0 / build exit 0 を確認済み。
      environment_notes:
        - "pnpm 系 VC は NO_TTY 回避のため CI=true で実行(ERR_PNPM_ABORTED_REMOVE_MODULES_DIR_NO_TTY)"
        - "lint/build の baseline 検証は clean worktree (origin/main detached) で実施し untracked artifact 汚染を排除"
    contract_snapshot:
      outcome: "active issue worktree 存在時、worktree 外への Write/Edit/MultiEdit と mutating Bash が PreToolUse hook で block され、read-only と worktree 内 mutation は allow、secret guard 先行順序がテストで固定される"
      acceptance_criteria: "AC1..AC7(本文参照)"
      verification_commands: "AC1..AC6 = pytest .claude/hooks/tests/test_worktree_scope_guard.py(baseline fail expected), AC7 = pnpm test/typecheck/lint/build(regression gate, CI=true)"
      allowed_paths:
        - .claude/hooks/worktree_scope_guard.sh
        - .claude/hooks/worktree_scope_guard.py
        - .claude/hooks/tests/test_worktree_scope_guard.py
        - .claude/settings.json
      required_skills:
        - "Bash / Python 3(PreToolUse hook の stdin/stdout 契約)"
        - "Claude Code settings.json hook 配線 / git worktree path 解決"
      worktree_branch: "worktree: .claude/worktrees/issue-960-worktree-scope-guard / branch: issue-960-worktree-scope-guard(preflight 時点で未作成・collision なし)"
    guardrails_note: ".claude/hooks/** + .claude/settings.json を触るため、implement-issue 着手時に Stop 条件で一度停止し review_subagent gate を要求する"

    判定: go — implement-issue / impl-review-loop へ handoff 可能。

  3. squne121 commented on Jun 17, 2026

    @squne121
    OwnerAuthor

    判定

    request_changes。 #960 の問題設定は妥当です。現状の .claude/settings.json では git push / git commit / git checkout / gh pr create / gh pr merge / gh api などが広く許可されており、説明規則だけでは main checkout 汚染を止められません。PreToolUse で fail-closed にする方向は正しいです。

    ただし、現契約のまま実装すると、MultiEdit の secret guard 順序、expected worktree 解決、Bash mutation 分類、symlink/path containment の4点で false green になります。実装前に Issue 本文を補強するべきです。


    参照した関連情報

    #960 は、active issue worktree が存在する場合に、worktree 外の Write/Edit/MultiEdit と mutating Bash を block し、read-only Bash と worktree 内 mutation を allow する hook を追加する契約です。対象配布物は .claude/hooks/worktree_scope_guard.sh、.claude/hooks/worktree_scope_guard.py、.claude/hooks/tests/test_worktree_scope_guard.py、.claude/settings.json に限定されています。

    関連 Issue と責務分界は次の通りです。#963 は git add -A / staged diff の Allowed Paths 混入を扱い、#960 の worktree 外 mutation 遮断とは明示的に分離されています。 #961 は subagent の証跡なし成功報告を evidence gate で fail-closed にする別レイヤーです。 #966 は loop 前に active worktree / dirty main / overlapping paths を ledger 化する preflight 層で、#960 の runtime hook と補完関係にあります。 #958 は contract snapshot / VC preflight / worktree / PR / checkout 汚染を intake capsule に集約する設計です。

    Issue コメントでは CONTRACT_REVIEW_RESULT_V1 status: go が出ており、AC1〜AC6 は新規 test file 未作成による baseline fail expected、AC7 は regression gate として扱われています。 ただし、私が確認できた範囲では #960 対応 PR は検索結果に出ておらず、レビュー対象は Issue 契約・既存 hook・settings・関連 Issue が中心です。


    外部仕様から見た必須前提

    Claude Code の hook は tool call 前に PreToolUse を実行でき、hook command は stdin で JSON を受け取ります。PreToolUse では exit code 2 が blocking error で、stderr が Claude に返されます。exit code 1 は通常 non-blocking なので、#960 の enforcement は必ず exit 2 で行う必要があります。([Claude Code]1)

    Claude Code の matcher は Edit|Write のような tool 名マッチをサポートしますが、公式 docs の if filter は command を parse できない場合に fail-open になるため、#960 のような hard guard の主 enforcement に使うべきではありません。分類は hook script 側で fail-closed に寄せるべきです。([Claude Code]1)

    Git worktree の列挙は git worktree list --porcelain が安定した形式として用意されており、-z を付けると path に改行等が含まれる場合も扱えます。worktree 行から始まる record を parser で処理し、branch/path から expected worktree を解決する設計が堅いです。([Git]2)

    GitHub CLI 側では、gh api は通常 GET ですが field flags を付けると POST になり、--input も request body を送ります。したがって gh api -f ... や gh api -X PATCH は #960 の mutating Bash 分類に含めるべきです。([GitHub CLI]3) また gh pr create は PR を作成するだけでなく、branch が未 push の場合に push/fork を促す挙動もあるため、wrong checkout での実行は明確に危険です。([GitHub CLI]4)


    致命的指摘 1: MultiEdit と secret boundary guard の順序要件が満たせない

    #960 は .claude/settings.json の PreToolUse に Bash|Write|Edit|MultiEdit matcher で worktree guard を追加する契約です。 一方、現行 settings の secret boundary guard は Bash|Read|Write|Edit|Grep|Glob にだけ掛かっており、MultiEdit が含まれていません。 さらに script 内の sensitive tool list も Read Write Edit Grep Glob で、ここにも MultiEdit がありません。

    これは #960 AC6 の「secret boundary guard が先行」を満たす上で穴です。MultiEdit に対して worktree guard が走るが secret guard は走らない、という状態になります。worktree guard が path を含む block message を誤って出すと、secret path の存在や構造を漏らす余地もあります。

    修正案: Issue 本文に次のいずれかを明記してください。

    1. 実装: active issue worktree 外への Write/Edit/Bash mutation を hook で遮断する #960 の範囲で secret boundary guard matcher と test を MultiEdit 対応に拡張する。ただしこれは「既存 PreToolUse hook の挙動変更」に該当し得るため、Stop Conditions に従って review_subagent / human gate を明示する。
    2. 実装: active issue worktree 外への Write/Edit/Bash mutation を hook で遮断する #960 の worktree guard matcher から MultiEdit を外し、MultiEdit secret coverage は別 Issue に分離する。これは現 AC とは矛盾するので、AC1/AC2/AC6 の書き換えが必要です。

    この点を未解決のまま実装すると、AC6 はテスト上だけ pass しても仕様上は false green です。


    致命的指摘 2: expected worktree 解決方式が未定義すぎる

    #960 は「Hook stdin の cwd / tool name / tool input から active issue / expected worktree 解決」と書いていますが、実際の解決優先順位が未定義です。どの値を canonical とするのか、LOOP_STATE がどこから得られるのか、branch 名と path 名が衝突した場合どうするのか、active worktree が複数ある場合どうするのかが書かれていません。

    既存 test には重要な注意があります。git rev-parse --show-toplevel はこの repo の worktree isolation では main repo root を返すため、test は __file__ を anchor にしています。 #960 の guard / test が安易に git rev-parse --show-toplevel に依存すると、まさに防ぎたい main checkout 汚染を見逃す可能性があります。

    修正案: Issue に resolver contract を追加してください。

    WORKTREE_SCOPE_RESOLUTION_V1:
      project_root_source_precedence:
        - CLAUDE_PROJECT_DIR
        - settings_json_parent_resolution
      current_issue_source_precedence:
        - LOOP_STATE.issue_number
        - env LOOP_ISSUE_NUMBER
        - cwd basename /^issue-(\d+)-/
        - current_branch /^issue-(\d+)-/
      worktree_catalog:
        command: git -C <project_root> worktree list --porcelain -z
        parser: nul_record_parser
      expected_worktree_selection:
        match:
          - branch == refs/heads/issue-<issue>-*
          - path basename == issue-<issue>-*
        zero_matches_for_mutation: block
        multiple_matches_for_mutation: block
        zero_matches_for_read_only: allow

    これを入れないと、実装者ごとに resolver が揺れ、AC1/AC2 の意味が不安定になります。


    高リスク指摘 3: Bash mutation classifier が狭いと簡単に抜ける

    現行の rtk shadow guard には既に mutating git / gh / package manager の分類ロジックがあります。git commit/push/add/checkout/stash/worktree、gh api の mutating method / field flags、gh issue edit/comment/close、gh pr create/merge/review/comment/edit などを分類しています。

    #960 の AC3 は git commit / git add / git push / gh pr create / gh pr edit だけを例示しています。しかし settings は gh api、gh issue edit/create/close/comment、gh pr merge/review/comment も許可しています。 ここを分類しないと、例えば main checkout から gh api -X PATCH ...、gh issue comment ...、gh pr merge ... が通ります。

    修正案: classifier の AC を追加してください。

    AC8: mutating Bash classifier は最低限、以下を outside expected worktree で block する:
      git:
        - add, commit, push, checkout, switch, restore, reset, rebase, merge,
          cherry-pick, revert, am, apply, rm, mv, tag, stash except list/show,
          worktree except list
      gh:
        - pr create/edit/merge/review/comment/close/reopen/ready/draft/lock/unlock
        - issue create/edit/comment/close/reopen/delete/lock/unlock
        - api with -X/--method PATCH|POST|PUT|DELETE
        - api with -f/-F/--field/--raw-field/--input unless explicit GET
      package_managers:
        - npm/pnpm/yarn/bun add/install/remove/update/publish/version/link/unlink
      filesystem_write_patterns:
        - shell redirection >, >>, 2>, tee, sed -i, perl -i
        - python/node/ruby one-liners that open/write files

    完全な shell interpreter を作る必要はありません。ただし hard guard としては、outside expected worktree では known read-only allowlist 以外を block する方が設計に合います。Claude Code の if filter は parse 失敗時 fail-open なので、ここを外部 matcher に委ねるべきではありません。(Claude Code)


    高リスク指摘 4: cwd だけを見ると git -C / cd / wrapper で抜ける

    cwd=/repo/.claude/worktrees/issue-960-x なら allow、という単純判定は不十分です。

    抜け道は次の通りです。

    git -C /repo commit -m "oops"
    cd /repo && git add . && git commit -m "oops"
    bash -lc 'cd /repo && gh pr create --fill'
    command git -C /repo push

    rtk shadow guard も wrapper 検出はありますが、bash -lc 内部の一般 shell 構文を完全には解釈していません。 #960 は blocking guard なので、rtk の shadow classifier より保守的にする必要があります。

    修正案: Bash 判定を次の2段にしてください。

    1. tool_input.command から git -C <path>、先頭 cd <path> &&、bash -c/-lc、sh -c、command git、env VAR=... git を検出する。
    2. mutating command で、effective cwd / explicit target dir が expected worktree 外なら block。解析不能で mutation 可能性がある場合も outside expected worktree では block。

    高リスク指摘 5: path containment は realpath/commonpath でないと symlink で抜ける

    Write / Edit / MultiEdit の path 判定を string prefix で行うと危険です。

    攻撃例:

    expected: /repo/.claude/worktrees/issue-960
    input:    /repo/.claude/worktrees/issue-960-link/../main-file
    symlink:  /repo/.claude/worktrees/issue-960/out -> /repo/.claude/skills
    target:   /repo/.claude/worktrees/issue-960/out/SKILL.md
    

    修正案: Python 側では、path を cwd 基準で絶対化し、Path.resolve(strict=False) または os.path.realpath を通した上で os.path.commonpath([expected, actual]) == expected を使ってください。startswith() は不可です。テストには ..、relative path、absolute path、symlink outside、case-insensitive filesystem 想定を入れるべきです。


    中リスク指摘 6: failure message の AC が曖昧

    #960 は「failure message は20行以内、expected worktree と actual cwd のみ、full path dump なし」としています。これは良い制約ですが、「expected worktree と actual cwd を full path で出すのか、project-relative で出すのか」が曖昧です。

    推奨: stderr は固定3〜4行にしてください。

    [worktree_scope_guard] blocked: mutation outside active issue worktree
    expected_worktree: .claude/worktrees/issue-960-worktree-scope-guard
    actual_cwd: .
    

    tool input path、command、branch list、worktree list、env、full command preview は出さない。既存 secret boundary guard も block 時に command/path を echo しない方針を取っています。


    実装設計の推奨形

    worktree_scope_guard.sh は薄い wrapper にし、判定は Python に寄せるのがよいです。既存 secret guard は Bash + jq ですが、新規 guard は path normalization と porcelain parser が必要なので Python の方が安全です。

    #!/usr/bin/env bash
    set -euo pipefail
    SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
    exec python3 "${SCRIPT_DIR}/worktree_scope_guard.py"

    worktree_scope_guard.py の責務は次に限定します。

    inputs:
      stdin_json:
        - tool_name
        - tool_input
        - cwd
      env:
        - CLAUDE_PROJECT_DIR
        - LOOP_ISSUE_NUMBER optional
        - LOOP_STATE optional
    
    decision:
      no_active_issue_worktree:
        read_only: allow
        mutation: allow_or_warn # Issueで明示する
      active_issue_worktree_exists:
        read_only_bash: allow
        write_edit_multiedit_inside_expected: allow
        write_edit_multiedit_outside_expected: block_exit_2
        mutating_bash_from_outside_expected: block_exit_2
        mutating_bash_with_explicit_outside_target: block_exit_2
        malformed_payload_for_matched_tool: block_exit_2
    
    output:
      allow: exit 0, no stdout/stderr
      block: exit 2, bounded stderr only

    settings の hook order は、少なくとも次にしてください。

    "PreToolUse": [
      {
        "matcher": "Bash|Read|Write|Edit|Grep|Glob|MultiEdit",
        "hooks": ["secret_boundary_guard"]
      },
      {
        "matcher": "Bash|Write|Edit|MultiEdit",
        "hooks": ["worktree_scope_guard"]
      },
      {
        "matcher": "Bash|Write|Edit|MultiEdit",
        "hooks": ["guard-japanese-prose"]
      },
      {
        "matcher": "Bash",
        "hooks": ["rtk_boundary_shadow_guard"]
      }
    ]

    ただし、先述の通り MultiEdit を secret boundary guard に足すのは既存 hook 挙動変更です。#960 の Stop Conditions に抵触し得るため、Issue 本文に明示的な許可または別 Issue 分割が必要です。


    追加すべきテスト

    現 AC1〜AC6 だけでは抜け道を潰せません。最低限、次を追加してください。

    AC8: MultiEdit が secret boundary guard より後に worktree guard へ到達しないこと、
         または secret boundary guard matcher が MultiEdit を含むことを settings test で固定する。
    
    AC9: cwd が expected worktree 内でも、git -C /repo commit / cd /repo && git add は block する。
    
    AC10: gh api -X PATCH、gh api -f、gh issue comment、gh pr merge/review/comment は
          outside expected worktree で block する。
    
    AC11: Write/Edit/MultiEdit の target path は realpath/commonpath で判定し、
          symlink outside / ../ traversal / absolute outside を block する。
    
    AC12: active issue worktree が 0 件 / 複数件 / branch-path mismatch のときの decision を固定する。
    
    AC13: block stderr は 20 行以内で、tool command・tool input path・worktree list・env を含まない。
    
    AC14: git worktree list parser は --porcelain -z fixture を処理する。

    既存 secret boundary test は repo root を __file__ から解決しており、worktree isolation の前提に合っています。#960 の test もこの方式を踏襲するべきです。


    最終レビューコメント案

    このまま実装に入るより、#960 に以下の差分を入れてから着手するのが妥当です。

    REVIEW_RESULT_V1:
      status: request_changes
      target_issue: 960
      blockers:
        - id: multi_edit_secret_order_gap
          severity: critical
          summary: >
            worktree guard matcher includes MultiEdit, but current secret_boundary_guard
            matcher and script do not cover MultiEdit. AC6 cannot be satisfied literally.
        - id: expected_worktree_resolution_underspecified
          severity: critical
          summary: >
            LOOP_STATE/branch/cwd/worktree-list precedence is undefined; ambiguous or multiple
            active worktrees are not specified.
        - id: bash_mutation_classifier_too_narrow
          severity: high
          summary: >
            AC3 examples omit gh api, gh issue/pr mutations, git -C/cd wrappers,
            package manager mutations, and shell file-write patterns.
        - id: path_containment_bypass
          severity: high
          summary: >
            Tests must require realpath/commonpath containment and cover symlink/../ outside targets.
      required_issue_updates:
        - Add WORKTREE_SCOPE_RESOLUTION_V1.
        - Decide whether #960 may modify secret_boundary_guard MultiEdit coverage.
        - Add AC8-AC14 for classifier, symlink, parser, ambiguity, and stderr bounds.
        - Specify fail-closed behavior for malformed payload, missing Python, missing git, zero/multiple worktree matches.

    結論: #960 は方向性としては必要ですが、現契約は「main checkout 事故」を止めるにはまだ甘いです。特に MultiEdit と git -C / gh api / symlink outside は、敵対的には最初に突くべき穴です。実装前に contract を上記の粒度まで引き上げるべきです。

  4. squne121 commented on Jun 17, 2026

    @squne121
    OwnerAuthor

    issue-refinement-loop 完了(approved / 人間承認不要モード)

    anchor comment(request_changes review)の指摘を fact-check の上で全反映し、本文を更新しました。

    Fact-check 結果

    • repo 事実主張 7 件: すべて supported(secret_boundary_guard matcher が MultiEdit 非対応、rtk_boundary_shadow_guard の mutating 分類、__file__ anchor test、PreToolUse 配線、worktree_scope_guard 未作成)
    • 外部仕様 5 件: 4 件 supported(PreToolUse exit 2 blocking、git worktree --porcelain -z、gh api の POST 化、gh pr create の push/fork prompt)、1 件 partial(matcher の if filter fail-open は公式 docs に明記なし → 本文では if filter に hard enforcement を委ねず hook script 側で fail-closed に寄せる方針で吸収)

    反映した契約強化

    指摘 対応
    MultiEdit と secret guard の順序(critical) 既存 secret guard は変更せず、AC6 を共有 tool(Bash/Write/Edit)の先行順序に限定。MultiEdit は bounded message(AC13)で secret 漏洩を防止。secret guard の MultiEdit 拡張は follow-up Issue へ分離
    expected worktree 解決未定義(critical) WORKTREE_SCOPE_RESOLUTION_V1(root/issue precedence・--porcelain -z parser・0件/複数件 fail-closed)を追加
    Bash classifier が狭い(high) MUTATING_BASH_CLASSIFIER_V1(git/gh api/gh issue・pr/package manager/shell file-write + read-only allowlist)を追加、AC8/AC10
    cwd だけだと wrapper で抜ける(high) git -C / cd && / bash -lc / command git 等の effective target 判定、AC9
    path containment(high) realpath/commonpath 必須・startswith 不可を明記、symlink/../absolute outside を block、AC11
    failure message 曖昧(medium) 20 行以内・expected worktree と actual cwd のみ・command/path/worktree list/env を出さない、AC5/AC13
    fail-closed 未定義 malformed payload / git binary 不在 / 解析不能 mutation を block、AC15
    C2: Stop Conditions 5 件 6 件へ拡張

    AC を AC1–AC7 から AC1–AC15 へ拡張し、各 AC に対応する baseline-expect: fail の VC を追加しました。

    Review 結果(iteration 2)

    check_issue_contract.py の決定論的チェック C1–C11 すべて pass(C12/C13 は implementation issue のため n/a)。前回 fail だった C2_stop_conditions_6 も pass。

    regression gate(pnpm lint/test/build)は 環境 false-blocker と確定(本文欠陥ではない):

    • pnpm lint の 3980 errors は全件 untracked な playwright-report/trace/assets/*.js(ブラウザバンドル)由来。repo ソース・本 Issue とは無関係
    • CI=true pnpm typecheck = EXIT 0、CI=true pnpm test -- tests/agent-session-manifest.test.ts = 696 passed / EXIT 0(AC7 核心 VC の健全性を実証)
    • TTY 不在による ERR_PNPM_ABORTED_REMOVE_MODULES_DIR_NO_TTY は CI=true で解消

    Handoff

    loop_handoff_result_v1:
      issue: 960
      termination_reason: approved
      deterministic_contract_review: pass            # C1-C11 pass, C12/C13 n/a
      anchor_feedback_incorporated: true
      residual_blockers_class: environment_only       # regression gate pollution (playwright-report/*)
      body_vc_soundness: verified                      # typecheck EXIT0 / manifest 696 passed
      next_step: issue-contract-review -> impl-review-loop
      follow_up_required:
        - secret_boundary_guard を MultiEdit 対応に拡張する別 Issue(既存 hook 挙動変更のため #960 から分離)

    次工程は issue-contract-review(go 確認)→ impl-review-loop での実装です。

  5. squne121 commented on Jun 17, 2026

    @squne121
    OwnerAuthor

    CONTRACT_REVIEW_RESULT_V1

    status: go
    generated_by: issue-contract-review
    issue: 960
    issue_url: https://github.com/squne121/loop-protocol/issues/960
    repo: squne121/loop-protocol
    generated_at: "2026-06-17T12:06:40Z"
    body_sha256: "6480abe622dc4c2159e1881e8e360f945e9cb2ca09e32c9d2361d4ab028094d2"
    supersedes: issue-comment 4729360568   # 旧 go は AC1..AC7 のみ検証。本文が Scope Delta で AC1..AC15 に拡張されたため再検証
    checks:
      template_compliance: pass
      state_label: pass
      allowed_paths_present: pass
      vc_present: pass
      stop_conditions_complete: pass
      ac_verifiability: pass        # AC1..AC15 が VC # AC1..# AC15 と一致、決定論的(exit code)
      product_spec_check: pass      # not_applicable(hook/workflow 変更、docs/product 非対象)
      worktree_branch_collision: pass
      blocked_reasons: []
      next_action: handoff_to_implement_issue
    vc_preflight:
      status: pass
      summary:
        vc_expected_pass: 4         # AC7 pnpm test/typecheck/lint/build
        vc_failed_as_expected: 16   # AC1..AC15 pytest (file not found exit 4) + AC7 pytest
        vc_human_judgment: 0
        vc_passed_unexpectedly: 0
        vc_unrunnable: 0
      classifications:
        - ac: AC1..AC15 (pytest)
          scope_class: baseline_fail_expected
          decision: go
          note: "新規 .claude/hooks/tests/test_worktree_scope_guard.py 未作成のため pytest exit 4 (file not found) = expected baseline fail"
        - ac: AC7 (pnpm test/typecheck/lint/build)
          scope_class: regression_gate
          decision: go
          note: "clean worktree (origin/main detached, CI=true) で再実行: test 687 passed / typecheck 0 / lint 0 / build 0"
      environment_notes:
        - "main working tree は root 所有 dist/assets により vite prepareOutDir が EACCES で build fail する偽 human_judgment が発生。これは #960 contract 欠陥ではなく環境汚染。clean worktree で lint/build exit 0 を確認済み"
        - "pnpm 系 VC は NO_TTY 回避のため CI=true で実行"
    contract_snapshot:
      outcome: "active issue worktree 存在時、worktree 外への Write/Edit/MultiEdit と mutating Bash が PreToolUse hook で fail-closed に block され、read-only と worktree 内 mutation は allow、secret guard 先行順序がテストで固定される"
      acceptance_criteria: "AC1..AC15(本文参照)"
      verification_commands: "AC1..AC6 / AC8..AC15 = pytest .claude/hooks/tests/test_worktree_scope_guard.py -k <name>(baseline fail expected), AC7 = pytest 全体 + pnpm test/typecheck/lint/build(regression gate, CI=true)"
      allowed_paths:
        - .claude/hooks/worktree_scope_guard.sh
        - .claude/hooks/worktree_scope_guard.py
        - .claude/hooks/tests/test_worktree_scope_guard.py
        - .claude/settings.json
      required_skills:
        - "Bash / Python 3(PreToolUse hook の stdin/stdout 契約、realpath/commonpath による path containment)"
        - "Claude Code settings.json hook 配線 / git worktree path 解決(--porcelain -z NUL parser)"
      worktree_branch: "worktree: .claude/worktrees/issue-960-<slug> / branch: worktree-issue-960-<slug>(preflight 時点で未作成・collision なし)"
    guardrails_note: ".claude/hooks/** + .claude/settings.json を触るため、implement-issue 着手時に Stop 条件で一度停止し review_subagent gate を要求する"

    判定: go — 旧 go コメント(#issuecomment-4729360568)は AC1..AC7 のみを検証していたが、その後 anchor request_changes レビューを反映して本文が AC1..AC15(WORKTREE_SCOPE_RESOLUTION_V1 / MUTATING_BASH_CLASSIFIER_V1 / realpath-containment / fail-closed 群)へ拡張された。現在の本文(body_sha256 上記)に対して全 deterministic check を再実行し go を確認したため、本コメントが正本。implement-issue / impl-review-loop へ handoff 可能。

  6. squne121 commented on Jun 17, 2026

    @squne121
    OwnerAuthor

    implement-issue 完了(Draft PR 起票)

    worktree 外 mutation を遮断する worktree_scope_guard を実装し、Draft PR を起票しました。

    検証(worktree 内, CI=true)

    • uv run pytest .claude/hooks/tests/test_worktree_scope_guard.py → 75 passed(AC1..AC15 網羅)
    • pnpm test -- tests/agent-session-manifest.test.ts → 687 passed / EXIT 0
    • pnpm typecheck / pnpm lint / pnpm build → すべて EXIT 0

    次工程は impl-review-loop の review gate(review_subagent が git diff から Allowed Paths を独立再計算)です。

  7. added 3 commits that reference this issue on Jun 17, 2026
  8. added 2 commits that reference this issue on Jun 18, 2026
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/implementation

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions