Skip to content
Merged
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
51 changes: 49 additions & 2 deletions .claude/agents/issue-author.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,15 @@ description: GitHub Issue を起票・修正する役割の SubAgent。新規起
tools:
- Bash
- Read
- Write
# Bash 制約: gh issue create / gh issue edit / gh issue comment および
# uv run python3 .claude/skills/create-issue/scripts/create_issue_txn.py * に限定。
# Write は /tmp/issue_*.md への body-file 一時書き出しのみ許可。
# repo file の作成・編集は禁止(Write/Edit/MultiEdit は disallowedTools)。
# /tmp/issue_*.md への body-file 書き出しは Bash の echo/cat リダイレクト経由のみ許可。
disallowedTools:
- Agent
- Edit
- MultiEdit
- Write
model: sonnet
permissionMode: acceptEdits
---
Expand All @@ -29,6 +30,52 @@ permissionMode: acceptEdits
| 起票 + 即時修正 | ユーザー要求 + 追記内容 | `create-issue` → `edit-issue` 連続 |
| child materialization | `task: materialize_children` + `CHILD_MATERIALIZATION_PLAN_V2` | `create-issue` + `edit-issue` (delivery-rollup-parent-update) |

## FAIL_CLOSED_REWRITE_CONSTRAINTS_V1 Rewrite Payload Contract

`issue-refinement-loop` が `fail_closed.required == true` の状態から rewrite を依頼する場合、以下のスキーマの入力を受け取る。

```yaml
FAIL_CLOSED_REWRITE_CONSTRAINTS_V1:
schema_version: "FAIL_CLOSED_REWRITE_CONSTRAINTS_V1"
required_sections: [] # 不足セクション名の一覧(必ず追加すること)
required_contract_keys: [] # 不足 contract キーの一覧(必ず追加すること)
rewrite_constraints:
must_add_sections: [] # required_sections と同一(フィールド重複は意図的)
must_add_contract_keys: [] # required_contract_keys と同一(フィールド重複は意図的)
freeform_rewrite_forbidden: true # 自由文形式の改変禁止
override_policy:
allowed_reason_codes: [] # override 可能な fail_closed reason codes
never_override_reason_codes: [] # override 不可な reason codes
overridable_in_current_result: []
non_overridable_in_current_result: []
max_rewrite_attempts: 2
no_progress_route: "human_judgment_required"
```

### Rewrite 実行ルール

1. `required_sections` の各セクションを Issue 本文に追加する(既存の内容を壊さない)
2. `required_contract_keys` の各キーを Machine-Readable Contract YAML ブロックに追加する
3. `rewrite_constraints.freeform_rewrite_forbidden == true` の場合、スコープ外の変更を行わない
4. `never_override_reason_codes` に該当する reason code が存在する場合は rewrite を実施せず `status: failed` を返す

### 受け入れない入力

- `FAIL_CLOSED_REWRITE_CONSTRAINTS_V1` スキーマを持たない freeform rewrite request(`rewrite_constraints.freeform_rewrite_forbidden == true` の場合)
- 呼び出し元が `FAIL_CLOSED_REWRITE_CONSTRAINTS_V1` を提供しない状態での fail_closed 修復要求

### ISSUE_AUTHOR_RESULT_V1 への追加フィールド

fail_closed rewrite 完了時は以下を追加で報告する:

```yaml
# ISSUE_AUTHOR_RESULT_V1 の追加フィールド(fail_closed rewrite 時のみ)
checked_body_sha256: <sha256> # pre-mutation dry-run checker に渡した本文の SHA256
checker_exit_code: <int> # post-mutation fresh checker の exit code
missing_sections: [] # rewrite 後も残っている不足セクション(空 = 解消済み)
missing_contract_keys: [] # rewrite 後も残っている不足 contract キー(空 = 解消済み)
```

## AC/VC Reflection & Rewrite Logic (SubAgent-owned)

本 SubAgent は、Issue 本文を更新(rewrite)する際、AC(Acceptance Criteria)および VC(Verification Commands)の妥当性を評価し、baseline 状態を適切に扱う責務を持つ。
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,31 @@ orchestrator はこれらの判定ロジックを再実装せず、SubAgent 側
- `reviewer_feedback_text` は opaque forwarding payload として扱う。
- anchor comment が絡む場合も、raw snapshot ではなく正規化済み `anchor_comment_feedback` だけを `issue-author` へ渡す。

## FAIL_CLOSED_REWRITE_CONSTRAINTS_V1 Forwarding

`fail_closed.required == true` の場合、orchestrator は `fail_closed.rewrite_constraints`(`FAIL_CLOSED_REWRITE_CONSTRAINTS_V1` スキーマ)を `issue-author` への rewrite 入力に含める必要がある。

- `issue-author` は `required_sections` / `required_contract_keys` / `rewrite_constraints` フィールドを受け取り、不足セクション・不足契約キーの補完を優先する
- `rewrite_constraints.freeform_rewrite_forbidden == true` の場合、`issue-author` は自由文形式の改変を拒否する
- `human_decision_reframe` による override が許可されていても、`FAIL_CLOSED_REWRITE_CONSTRAINTS_V1` を無視してよいわけではない

### Rewrite 後の自動再検証(2 段構成)

`issue-author` による rewrite 完了後に以下の検証を順に実施する:

1. **pre-mutation dry-run checker**: mutation 前に新本文の静的検証(`check_issue_contract.py` 相当)を dry-run で実施する
2. **post-mutation fresh checker**: `gh issue edit` 実行後に GitHub から本文を再取得し、静的検証を再実施する

`post-mutation fresh checker` が exit 0 以外の場合、Review に進まず Rewrite を継続する。

### max_rewrite_attempts / no-progress detection

- `FAIL_CLOSED_REWRITE_CONSTRAINTS_V1.max_rewrite_attempts: 2` — この回数を超えて同一 fail_closed を解消できない場合は `human_judgment_required` へ遷移する
- **no-progress detection**: 連続する 2 rewrite で `checked_body_sha256` が変化しない場合、前進がないと判定し `human_judgment_required` を返す

## Must not

- verification owner が異なる VC を refinement loop 側で再分類しない
- SubAgent 側の reflection 判定を orchestrator 側で再解釈しない
- `human_decision_reframe` を validation bypass として扱わない(`FAIL_CLOSED_REWRITE_CONSTRAINTS_V1` は必ず転送する)
- `never_override_reason_codes`(`unknown_issue_kind` / `issue_kind_policy_load_error` / `contract_schema_parse_error` / `template_resolution_error` / `checker_internal_error`)に対して override を許可しない
Original file line number Diff line number Diff line change
Expand Up @@ -148,12 +148,88 @@ When `fail_closed.required == true`:
2. Output is still valid JSON, but should not be used for decisions
3. Human escalation is required with `fail_closed.reason_codes` and `human_message`
4. The orchestrator should NOT attempt to infer missing policy
5. `fail_closed.rewrite_constraints` contains `FAIL_CLOSED_REWRITE_CONSTRAINTS_V1` — the orchestrator MUST forward this payload to `issue-author` when routing to Rewrite

**reason_codes**:
- `malformed_machine_readable_contract`: YAML block missing `contract_schema_version`
- `missing_required_section`: Outcome or other critical section missing
- `missing_required_contract_key`: Machine-Readable Contract missing required keys (`contract_schema_version`, `issue_kind`)
- `unknown_input_schema`: Input didn't match `REFINEMENT_LOOP_PLANNER_INPUT_V1`
- `planner_internal_error`: Unexpected exception during processing
- `unknown_issue_kind`: `issue_kind` field present but not in SSOT allowlist
- `issue_kind_policy_load_error`: ISSUE_KIND_POLICY_V1 SSOT could not be loaded
- `contract_schema_parse_error`: Machine-Readable Contract YAML could not be parsed
- `template_resolution_error`: Issue template file could not be resolved or loaded
- `checker_internal_error`: Internal error in the contract checker

## FAIL_CLOSED_REWRITE_CONSTRAINTS_V1

When `fail_closed.required == true`, the planner includes `fail_closed.rewrite_constraints` with the following schema:

```json
{
"schema_version": "FAIL_CLOSED_REWRITE_CONSTRAINTS_V1",
"required_sections": ["Outcome", "Acceptance Criteria"],
"required_contract_keys": ["contract_schema_version", "issue_kind"],
"rewrite_constraints": {
"must_add_sections": ["Outcome", "Acceptance Criteria"],
"must_add_contract_keys": ["contract_schema_version", "issue_kind"],
"freeform_rewrite_forbidden": true
},
"override_policy": {
"allowed_reason_codes": ["missing_required_section", "missing_required_contract_key"],
"never_override_reason_codes": [
"unknown_issue_kind",
"issue_kind_policy_load_error",
"contract_schema_parse_error",
"template_resolution_error",
"checker_internal_error"
],
"overridable_in_current_result": ["missing_required_section"],
"non_overridable_in_current_result": []
},
"max_rewrite_attempts": 2,
"no_progress_route": "human_judgment_required"
}
```

### Field Semantics

- `required_sections`: sections that must be added to the Issue body (missing from template check)
- `required_contract_keys`: keys that must be present in the Machine-Readable Contract block
- `rewrite_constraints.freeform_rewrite_forbidden`: `issue-author` MUST NOT accept freeform rewrite requests; only structured repair against `must_add_sections` / `must_add_contract_keys`
- `override_policy.allowed_reason_codes`: reason codes that `human_decision_reframe` can override
- `override_policy.never_override_reason_codes`: reason codes that are always blocked (no override)
- `max_rewrite_attempts`: loop router enforces this limit; after N attempts without progress, routes to `human_judgment_required`
- `no_progress_route`: destination when rewrite produces no forward progress

## human_decision_reframe Override Contract

`human_decision_reframe` is the mechanism by which a human anchor comment overrides a `fail_closed` verdict. This is NOT a validation bypass — it is a permission to continue rewriting under the constraint of `FAIL_CLOSED_REWRITE_CONSTRAINTS_V1`.

### Override is permitted when:
1. The `fail_closed.reason_codes` contain only codes in `override_policy.allowed_reason_codes`
2. The human anchor comment explicitly acknowledges the missing sections/keys
3. The rewrite is constrained to `FAIL_CLOSED_REWRITE_CONSTRAINTS_V1.rewrite_constraints`

### Override is NEVER permitted when:
- Any `fail_closed.reason_code` is in `override_policy.never_override_reason_codes`
- `unknown_issue_kind`, `issue_kind_policy_load_error`, `contract_schema_parse_error`, `template_resolution_error`, `checker_internal_error` always block, regardless of human instruction

### Post-override Rewrite Contract
After `human_decision_reframe` triggers Rewrite:
1. The orchestrator forwards `FAIL_CLOSED_REWRITE_CONSTRAINTS_V1` to `issue-author`
2. `issue-author` executes structured repair (adds missing sections/keys)
3. After `issue-author` completes, a contract checker re-runs automatically (pre-mutation dry-run + post-mutation fresh check)
4. If `post-mutation fresh checker` exits non-zero: Rewrite loop continues (up to `max_rewrite_attempts`)
5. If `max_rewrite_attempts` exceeded with no progress: route to `human_judgment_required`

### Terminal Result Fields (AC11)
The terminal/handoff result must include:
- `checked_body_sha256`: SHA256 of the Issue body that was checked
- `checker_exit_code`: exit code of the post-mutation checker
- `missing_sections`: list of sections still missing after rewrite (empty if all resolved)
- `missing_contract_keys`: list of contract keys still missing after rewrite (empty if all resolved)

## Idempotency Guarantee

Expand Down
128 changes: 128 additions & 0 deletions .claude/skills/issue-refinement-loop/scripts/plan_refinement_loop.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,43 @@
FAIL_CLOSED_REASON_INTERNAL_ERROR = "planner_internal_error"
FAIL_CLOSED_REASON_TEMPLATE_UNAVAILABLE = "template_required_sections_unavailable"
FAIL_CLOSED_REASON_UNKNOWN_ISSUE_KIND = "unknown_issue_kind"
FAIL_CLOSED_REASON_MISSING_CONTRACT_KEY = "missing_required_contract_key"
FAIL_CLOSED_REASON_CONTRACT_SCHEMA_PARSE_ERROR = "contract_schema_parse_error"
FAIL_CLOSED_REASON_ISSUE_KIND_POLICY_LOAD_ERROR = "issue_kind_policy_load_error"
FAIL_CLOSED_REASON_CHECKER_INTERNAL_ERROR = "checker_internal_error"
FAIL_CLOSED_REASON_TEMPLATE_RESOLUTION_ERROR = "template_resolution_error"

# Override policy: which fail_closed reason codes can be overridden by human_decision_reframe
# AC7: missing_required_section and missing_required_contract_key only
# unknown_issue_kind, issue_kind_policy_load_error, contract_schema_parse_error,
# template_resolution_error, checker_internal_error are never overridable.
OVERRIDE_POLICY = {
"allowed_reason_codes": [
FAIL_CLOSED_REASON_MISSING_SECTION,
FAIL_CLOSED_REASON_MISSING_CONTRACT_KEY,
],
"never_override_reason_codes": [
FAIL_CLOSED_REASON_UNKNOWN_ISSUE_KIND,
FAIL_CLOSED_REASON_ISSUE_KIND_POLICY_LOAD_ERROR,
FAIL_CLOSED_REASON_CONTRACT_SCHEMA_PARSE_ERROR,
FAIL_CLOSED_REASON_TEMPLATE_RESOLUTION_ERROR,
FAIL_CLOSED_REASON_CHECKER_INTERNAL_ERROR,
],
}

# Required machine-readable contract keys that must be present when a YAML contract exists
REQUIRED_CONTRACT_KEYS = [
"contract_schema_version",
"issue_kind",
]

# Standard required sections for implementation issues
STANDARD_REQUIRED_SECTIONS = [
"Outcome",
"Acceptance Criteria",
"Verification Commands",
"Allowed Paths",
]

# ---------------------------------------------------------------------------
# ISSUE_KIND_POLICY_V1 SSOT loader
Expand Down Expand Up @@ -937,6 +974,77 @@ def _stable_sort_dedupe(items: list[str]) -> list[str]:
return sorted(set(items))


def _extract_missing_contract_keys(issue_body: str) -> list[str]:
"""
Extract missing required contract keys from the Machine-Readable Contract.

Returns a list of required keys that are absent from the parsed contract dict.
Returns an empty list if no Machine-Readable Contract section or YAML block exists
(absence of contract is handled separately by section checks, not here).
Only returns missing keys when a contract block IS present but keys are absent.
"""
if not _YAML_AVAILABLE:
return []

sections = _extract_sections(issue_body)
# Only check for missing keys if a Machine-Readable Contract section exists
if "Machine-Readable Contract" not in sections:
return []

machine_contract = _extract_machine_contract(issue_body)
if machine_contract is None:
# Contract section exists but YAML couldn't be parsed — schema parse error
# Return all required keys as missing so the caller knows what to add
return list(REQUIRED_CONTRACT_KEYS)

missing = []
for key in REQUIRED_CONTRACT_KEYS:
if key not in machine_contract or machine_contract[key] is None:
missing.append(key)
return missing


def _build_fail_closed_rewrite_constraints(
fail_closed_reasons: list[str],
missing_sections: list[str],
missing_contract_keys: list[str],
) -> dict[str, Any]:
"""
Build FAIL_CLOSED_REWRITE_CONSTRAINTS_V1 payload.

AC1/AC2/AC8: Returned when fail_closed is triggered, to guide issue-author
rewrite toward deterministic repair instead of freeform editing.
"""
# Determine which reasons are overridable (AC7)
overridable_reasons = [
r for r in fail_closed_reasons
if r in OVERRIDE_POLICY["allowed_reason_codes"]
]
non_overridable_reasons = [
r for r in fail_closed_reasons
if r in OVERRIDE_POLICY["never_override_reason_codes"]
]

return {
"schema_version": "FAIL_CLOSED_REWRITE_CONSTRAINTS_V1",
"required_sections": missing_sections,
"required_contract_keys": missing_contract_keys,
"rewrite_constraints": {
"must_add_sections": missing_sections,
"must_add_contract_keys": missing_contract_keys,
"freeform_rewrite_forbidden": True,
},
"override_policy": {
"allowed_reason_codes": OVERRIDE_POLICY["allowed_reason_codes"],
"never_override_reason_codes": OVERRIDE_POLICY["never_override_reason_codes"],
"overridable_in_current_result": overridable_reasons,
"non_overridable_in_current_result": non_overridable_reasons,
},
"max_rewrite_attempts": 2,
"no_progress_route": "human_judgment_required",
}


def plan_refinement_loop(input_data: dict[str, Any]) -> tuple[dict[str, Any], int]:
"""
Main planner function.
Expand Down Expand Up @@ -1000,6 +1108,9 @@ def plan_refinement_loop(input_data: dict[str, Any]) -> tuple[dict[str, Any], in

# Check for malformations
fail_closed_reasons = []
# Track missing sections and contract keys for FAIL_CLOSED_REWRITE_CONSTRAINTS_V1
accumulated_missing_sections: list[str] = []
accumulated_missing_contract_keys: list[str] = []

if _check_malformed_contract(issue_body):
fail_closed_reasons.append(FAIL_CLOSED_REASON_MALFORMED_CONTRACT)
Expand All @@ -1009,6 +1120,12 @@ def plan_refinement_loop(input_data: dict[str, Any]) -> tuple[dict[str, Any], in
raw_issue_kind = machine_contract.get("issue_kind") if machine_contract else None
parent_mode = machine_contract.get("parent_mode") if machine_contract else None

# Check for missing required contract keys (AC2/AC11)
missing_contract_keys = _extract_missing_contract_keys(issue_body)
if missing_contract_keys:
accumulated_missing_contract_keys = missing_contract_keys
fail_closed_reasons.append(FAIL_CLOSED_REASON_MISSING_CONTRACT_KEY)

# Apply alias normalization (design→research, tracking→parent, etc.)
# _normalize_issue_kind returns None for unknown/unresolvable kinds.
issue_kind = _normalize_issue_kind(raw_issue_kind) if raw_issue_kind else None
Expand All @@ -1035,10 +1152,12 @@ def plan_refinement_loop(input_data: dict[str, Any]) -> tuple[dict[str, Any], in
else:
missing = _check_missing_sections_from_template(issue_body, load_result.required_labels)
if missing:
accumulated_missing_sections = missing
fail_closed_reasons.append(FAIL_CLOSED_REASON_MISSING_SECTION)
else:
# Template not found: fall back to Outcome check
if _check_missing_outcome(issue_body):
accumulated_missing_sections = ["Outcome"]
fail_closed_reasons.append(FAIL_CLOSED_REASON_MISSING_SECTION)
elif is_parent_delivery_rollup:
# AC1: parent delivery-rollup — check parent template sections (not Outcome)
Expand All @@ -1052,13 +1171,21 @@ def plan_refinement_loop(input_data: dict[str, Any]) -> tuple[dict[str, Any], in
else:
missing = _check_missing_sections_from_template(issue_body, load_result.required_labels)
if missing:
accumulated_missing_sections = missing
fail_closed_reasons.append(FAIL_CLOSED_REASON_MISSING_PARENT_SECTION)
else:
# No machine contract or unknown issue_kind: fall back to Outcome check
if _check_missing_outcome(issue_body):
accumulated_missing_sections = ["Outcome"]
fail_closed_reasons.append(FAIL_CLOSED_REASON_MISSING_SECTION)

if fail_closed_reasons:
# Build FAIL_CLOSED_REWRITE_CONSTRAINTS_V1 for AC1/AC2/AC8
rewrite_constraints = _build_fail_closed_rewrite_constraints(
fail_closed_reasons,
accumulated_missing_sections,
accumulated_missing_contract_keys,
)
# B3: Return schema-valid decisions with unknown confidence even in fail_closed
return (
{
Expand Down Expand Up @@ -1105,6 +1232,7 @@ def plan_refinement_loop(input_data: dict[str, Any]) -> tuple[dict[str, Any], in
"required": True,
"reason_codes": fail_closed_reasons,
"human_message": f"Issue contract malformation detected: {', '.join(fail_closed_reasons)}",
"rewrite_constraints": rewrite_constraints,
},
},
0,
Expand Down
Loading
Loading