Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 44 additions & 0 deletions .claude/agents/implementation-worker.md
Original file line number Diff line number Diff line change
Expand Up @@ -242,6 +242,50 @@ preflight が pass した場合のみ実装フローを継続する。

これらは「動作検証が形骸化する構造的欠陥」であり、別 Issue でのスコープ分割または contract の再確認が必要。

## Allowed Paths Gate(AC1, AC2, AC3)

### ALLOWED_PATHS_GATE_RESULT_V1(AC1)

worker が実装前に contract snapshot から Allowed Paths を固定し、実装終了時に final diff audit を行って stale snapshot を fail-closed に検知する。以下の構造で gate 結果を生成する:

```yaml
ALLOWED_PATHS_GATE_RESULT_V1:
status: ok | fail_closed | stale_snapshot | indeterminate
# status 説明:
# ok: 実装中の全変更が contract の Allowed Paths 内に収まる(pass)
# fail_closed: 変更が Allowed Paths 外に検出(差し戻し)
# stale_snapshot: contract snapshot が古い、または判定根拠が不一致(final audit 時)
# indeterminate: 判定が確定できない、機械可読 contract 欠落(人間判断へ escalate)
allowed_paths: [<list of globs from contract>] # contract から固定(worktree 着手前に snapshot)
manifest_snapshot_sha256: "<合計ハッシュ>" # 実装前に生成したファイルマニフェスト
final_diff_paths: [<list of files changed by git diff>] # PR boundary audit 時に抽出
compliance_detail: "<optional explanation>"
reason: null | <machine-readable reason>
```

### advisory としての allowed_paths_compliance(AC2)

`IMPLEMENT_RESULT_V1.allowed_paths_compliance: true | false` は worker の self-report であり、**canonical 判定根拠ではない**。canonical 判定は `ALLOWED_PATHS_GATE_RESULT_V1.status` の値のみを参照する。

- `allowed_paths_compliance` は参考情報(advisory)に留める
- `ALLOWED_PATHS_GATE_RESULT_V1.status: ok` に対して `allowed_paths_compliance: false` であっても、status が canonical に route される
- `impl-review-loop` / control-plane は raw diff を canonical 判定根拠にしない(機械可読 gate result だけを参照)

### PreToolUse ベースの worker-side path guard(AC3)

implementation-worker は Edit / Write / MultiEdit ツール呼び出し前に、Allowed Paths に対する PreToolUse 検査を実施する:

```
PreToolUse hook: tool in (Edit, Write, MultiEdit)
→ check target path against Allowed Paths manifest
→ path matches manifest glob → allow
→ path NOT in manifest → DENY(exit nonzero, emit human escalation)
```

- Bash 経由の `git add / git rm / cp / mv / rm` コマンドは allowlist(`.claude/skills/implement-issue/**` に許可リスト記載)またはプロセス境界で fail-closed にする
- Bash 直接実行による `/tmp`、`/home/` 等への無制約書き込みはプロセス境界で検知できないため、contract 着手前に `LD_PRELOAD` / `ptrace` 等の infrastructure 対応を検討する場合は follow-up Issue へ分割する(本 Issue 範囲外)
- 本 Issue では Edit / Write / MultiEdit PreToolUse path guard を worker-side に実装し、Bash allowlist / fail-closed は `.claude/skills/implement-issue/SKILL.md` で明記する

## 出力制約 (OUTPUT_BUDGET_V1)

`docs/dev/agent-skill-boundaries.md#OUTPUT_BUDGET_V1` の制約に従う。routing-critical な機械可読フィールドは削らず、人間向け説明・証跡・diff 再掲のみを削減する。
Expand Down
62 changes: 62 additions & 0 deletions .claude/skills/impl-review-loop/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,68 @@ preparation step で取得した contract snapshot 内の以下の情報を Step
- 全 SubAgent 出力は構造化フォーマット(YAML / KEY=VALUE)で受け取り、散文サマリで上書きしない
- **issue-contract-review 自動実行しない(fail-only gate)**: `status: go` が存在しない場合に `issue-contract-review` を自動実行する旧設計(auto run deprecated)は #564 以降廃止。`missing_contract_go` 判定時は人間に `issue-contract-review` 実行を依頼して停止する(#564 整合)。

## ALLOWED_PATHS_GATE_RESULT_V1 routing(AC5)

Step 1 (Implementation) で worker が emit する `ALLOWED_PATHS_GATE_RESULT_V1` の status field を canonical に route し、raw diff comparison を blocking 判定根拠にしない:

- `ALLOWED_PATHS_GATE_RESULT_V1.status: ok` → 続行(Allowed Paths 内確認)
- `ALLOWED_PATHS_GATE_RESULT_V1.status: fail_closed` → Step 1 再実行(worker 側で逸脱を修正)
- `ALLOWED_PATHS_GATE_RESULT_V1.status: stale_snapshot` → human_escalation(contract snapshot 再確認が必要)
- `ALLOWED_PATHS_GATE_RESULT_V1.status: indeterminate` → human_escalation(機械可読 decision 確定不能)

**重要**: control-plane は raw git diff を参照して「このファイルは Allowed Paths 外では?」などの人間判断を入れない。judgment 根拠は exclusively `ALLOWED_PATHS_GATE_RESULT_V1.status` に限定する。worker の `IMPLEMENT_RESULT_V1.allowed_paths_compliance` は参考情報(advisory)であり、route 判定に使用しない。

## Overblocking risk review(AC7)

hook handler / gate evaluator が blocking decision を出すべき対象と advisory に留めるべき対象を区分する。**正当な AI 作業を過剰に阻止する overblocking は、fail-closed 強化と同じくらい危険である**:

### Hard Invariant — blocking decision を返してよい条件

以下の hard invariant に該当する場合のみ blocking(Stop / SubagentStop / error exit)を返す:

1. **Allowed Paths 逸脱**: Edit / Write / MultiEdit で Allowed Paths 外への変更を検出 → `ALLOWED_PATHS_GATE_RESULT_V1.status: fail_closed` で step を block
2. **Secret / sensitive file**: `.env`、`.git`、credential、private key、API key containing の変更を検出 → `status: blocked` + human_escalation
3. **Destructive command**: `git reset --hard`, `git push --force`, `rm -rf /`, `dd if=/dev/zero` 等の危険操作を検出 → exit nonzero + detailed reason
4. **Routing-critical machine-readable contract 欠落**: `ALLOWED_PATHS_GATE_RESULT_V1.status` が indeterminate で、判定が確定できない → human_escalation

### Advisory に留めるべき条件(blocking してはいけない)

以下の条件では block ではなく advisory / review finding / comment に留める。**正当な AI 作業として認可する**:

- 文体・言語・表現が日本語ルール(`.claude/rules/project-constitution.md`)に不一致
- PR body の format が慣例と異なる(構成、見出し順序、行折り返し、空行)
- コミットメッセージが Conventional Commits でない、またはスコープ・型が慣例と異なる
- レビューコメント / docstring / log メッセージの説明品質が低い
- テスト名が GIVEN/WHEN/THEN 形式でない
- 報告フォーマット(YAML / JSON の キー順序)が異なる
- 参考 URL の引用形式、リスト記号の統一性
- 以上の「スタイル / 報告形式」を理由に実装を止めてはならない(レビュー後に author が修正判断をする権利がある)

### 区分不可能な case 対応

blocking と advisory の境界が曖昧な case が判明した場合:
- 即座に決定を下さず人間に escalate(human_judgment_required)
- 判定基準を `.claude/rules/project-constitution.md` または `.claude/skills/impl-review-loop/references/overblocking-risk-matrix.md` へ追加して deterministic に固定

## Loop-prevention invariant(AC9)

この loop-prevention 規則は、Stop / SubagentStop / TeammateIdle hook が表現・言語・報告品質の不足を理由に継続実行を強制しないことを要求する重要な不変条件である。同時に、block する場合は理由が machine-readable で、次 action が有限・一意かつ human_escalation path を持つ:

Stop / SubagentStop / TeammateIdle hook は表現・言語・報告品質の不足を理由に継続実行を強制しない。同時に、block する場合は理由が machine-readable で、次 action が有限・一意かつ human_escalation path を持つ:

- Stop / SubagentStop:自動 block による無限停止を防ぐ
- 文体 / 言語エラーを理由に Stop してはいけない(代わり review finding に留める)
- block する場合:`reason` field は machine-readable enum(例: `Allowed_Paths_violation`)+ human-readable explanation
- 次 action:明確(例: "worker rerun + edit path.txt")、有限("再試行の上限回数")、escalation path あり("3 回目失敗時 human_judgment へ")

- SubagentStop:worker から control-plane への transition
- advisory feedback(文体指摘等)を理由に SubagentStop してはいけない
- fail-closed decision は structured RESULT スキーマ(`IMPLEMENT_RESULT_V1`, `ALLOWED_PATHS_GATE_RESULT_V1` 等)で emit

- TeammateIdle:agent team 文脈での teammate idling 決定
- 表現品質不足を理由に teammate を idle 化し協力を打ち切ってはいけない
- block 判定は hard invariant に限定し、fallback skill / escalation path を含める

## Related

- `.claude/skills/implement-issue/SKILL.md` — Step 1 で使う実装手順
Expand Down
227 changes: 227 additions & 0 deletions .claude/skills/impl-review-loop/scripts/allowed_paths_gate.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,227 @@
#!/usr/bin/env python3
"""Deterministic evaluation module for ALLOWED_PATHS_GATE_RESULT_V1.

This module is the canonical source for evaluating whether:
1. Changed files fall within Allowed Paths (allow / fail_closed)
2. Commands are safe to execute (hard_invariant_block / allow)
3. File paths contain sensitive data (hard_invariant_block / normal)
4. Quality issues should block execution (advisory / hard_invariant_block)

Used by impl-review-loop Step 1 worker and test fixtures for regression testing.

AC8 note: This is the ONLY source for gate evaluation logic. Tests import these
functions directly; they do not redefine evaluators inline (preventing tautology).
"""

from __future__ import annotations

import fnmatch
import hashlib
from typing import Any


def evaluate_allowed_paths_gate(
allowed_paths: list[str],
changed_files: list[str],
manifest_sha256: str | None = None,
) -> dict[str, Any]:
"""Evaluate ALLOWED_PATHS_GATE_RESULT_V1.

Args:
allowed_paths: List of glob patterns (e.g., [".claude/agents/**", "tests/**"])
changed_files: List of files changed by worker (e.g., [".claude/agents/worker.md"])
manifest_sha256: Expected manifest hash (for race guard). If provided and
does not match, returns status="stale_snapshot".

Returns:
dict with status: "ok" | "fail_closed" | "stale_snapshot" | "indeterminate"
- "ok": all changed_files match allowed_paths patterns
- "fail_closed": one or more changed_files violate allowed_paths
- "stale_snapshot": manifest_sha256 mismatch (contract stale)
- "indeterminate": input validation error (None allowed_paths, etc)
"""
# Validate inputs
if not allowed_paths or None in allowed_paths:
return {
"status": "indeterminate",
"manifest_snapshot_sha256": None,
"violations": [],
"final_diff_paths": changed_files,
"reason": "allowed_paths is None or empty",
}

if not isinstance(changed_files, list):
return {
"status": "indeterminate",
"manifest_snapshot_sha256": None,
"violations": [],
"final_diff_paths": [],
"reason": "changed_files must be a list",
}

# Compute actual manifest hash
manifest_str = "|".join(sorted(allowed_paths))
actual_manifest_hash = hashlib.sha256(manifest_str.encode()).hexdigest()

# Check for stale snapshot
if manifest_sha256 is not None and manifest_sha256 != actual_manifest_hash:
return {
"status": "stale_snapshot",
"manifest_snapshot_sha256": actual_manifest_hash,
"violations": [],
"final_diff_paths": changed_files,
"reason": f"manifest mismatch: expected {manifest_sha256}, got {actual_manifest_hash}",
}

# Check each file against patterns
violations = []
for file_path in changed_files:
matched = False
for pattern in allowed_paths:
if fnmatch.fnmatch(file_path, pattern):
matched = True
break
if not matched:
violations.append(file_path)

# Determine final status
status = "fail_closed" if violations else "ok"

return {
"status": status,
"manifest_snapshot_sha256": actual_manifest_hash,
"violations": violations,
"final_diff_paths": changed_files,
}


def classify_command(cmd: str) -> str:
"""Classify command as hard_invariant_block or allow.

Hard invariant block cases:
- git reset --hard, --force-with-lease, etc (destructive git)
- git push --force, -f (force push)
- rm -rf, dd if=/dev/zero, etc (destructive file ops)
- chmod 000 (permission death)

Allow cases:
- pnpm typecheck, lint, test, build (standard verification)
- git diff, status, log, show, rev-parse (read-only inspection)
- gh pr view, list, issue view, list (read-only GitHub inspection)
- grep, rg, find, etc (read-only text search)

Args:
cmd: Shell command string

Returns:
"hard_invariant_block" | "allow"
"""
# Hard invariant: destructive git commands
if "git reset" in cmd and "--hard" in cmd:
return "hard_invariant_block"
if "git push" in cmd and "--force" in cmd:
return "hard_invariant_block"
if "git push" in cmd and " -f" in cmd:
return "hard_invariant_block"

# Hard invariant: destructive file operations
if "rm -rf" in cmd or "rm -rf /" in cmd:
return "hard_invariant_block"
if "dd if=/dev/zero" in cmd:
return "hard_invariant_block"
if "chmod 000" in cmd:
return "hard_invariant_block"

# Allow: standard verification
standard_verification = [
"pnpm typecheck",
"pnpm lint",
"pnpm test",
"pnpm build",
]
if any(cmd.startswith(pattern) for pattern in standard_verification):
return "allow"

# Allow: read-only git inspection
read_only_git = ["diff", "status", "log", "show", "rev-parse"]
if cmd.startswith("git ") and any(ro in cmd for ro in read_only_git):
return "allow"

# Allow: read-only GitHub inspection
if ("gh pr view" in cmd or "gh issue view" in cmd or
"gh pr list" in cmd or "gh issue list" in cmd):
return "allow"

# Allow: read-only text search
if cmd.startswith("grep ") or cmd.startswith("rg "):
return "allow"

# Default: unknown command => must be evaluated elsewhere
return "allow" # permissive default for unknown commands


def classify_path(path: str) -> str:
"""Classify file path as hard_invariant_block or normal.

Hard invariant block cases:
- .env, .env.*, .env.local, .env.prod
- .git/config, .git/credentials
- credentials.json, secret*.key, private*.pem
- api_key.txt, token.*.txt, password.txt

Args:
path: File path string (e.g., ".env", "src/credentials.json")

Returns:
"hard_invariant_block" | "normal"
"""
path_lower = path.lower()

# Sensitive patterns
sensitive_patterns = [
".env",
"credentials",
"secret",
"private",
"api_key",
"token",
"password",
".git",
]

for pattern in sensitive_patterns:
if pattern in path_lower:
return "hard_invariant_block"

return "normal"


def classify_quality_issue(kind: str) -> dict[str, bool]:
"""Classify quality issue as advisory or blocking.

Policy: **Quality issues (style, language, format, naming) are ALWAYS advisory.**
They must never block execution. This is a documented policy, not a bug.

Acceptable kinds:
- "language": Japanese/English consistency
- "commit_format": Conventional Commits style
- "pr_body_format": PR body structure / section order
- "test_naming": GIVEN/WHEN/THEN convention
- "yaml_key_order": YAML/JSON key ordering
- "docstring_quality": Comment / docstring clarity
- any other style/format/language issue

Args:
kind: Issue category (language | commit_format | test_naming | etc)

Returns:
dict with keys:
- "category": "advisory" (always, by policy)
- "should_block": False (always, by policy)
"""
# All quality issues are advisory by design
# This is NOT a bug; it is the documented loop-prevention policy
return {
"category": "advisory",
"should_block": False,
}
Loading