Skip to content

feat(#1024): add build_loop_state.py — issue-refinement-loop の LOOP_STATE builder を追加し手書き JSON routing を禁止する - #1077

Merged
squne121 merged 4 commits into
mainfrom
worktree-issue-1024-loop-state-builder
Jun 21, 2026
Merged

squne121 merged 4 commits into
mainfrom
worktree-issue-1024-loop-state-builder

Conversation

@squne121

Copy link
Copy Markdown
Owner

概要

Issue #1024 の実装。build_loop_state.py を追加し、REFINEMENT_LOOP_PLAN_V1 と ISSUE_REVIEW_RESULT_COMPACT_V1 から LOOP_STATE_V1 を生成して routing に渡す builder-first フローを確立する。

変更内容

  • .claude/skills/issue-refinement-loop/scripts/build_loop_state.py — LOOP_STATE_V1 ビルダー(AC1-AC13)
  • .claude/skills/issue-refinement-loop/schemas/loop_state_build_result.schema.json — ビルド結果スキーマ(AC5)
  • .claude/skills/issue-refinement-loop/tests/test_loop_state_builder.py — 主要テスト(AC1,AC6,AC7,AC8,AC12)
  • .claude/skills/issue-refinement-loop/tests/test_loop_state_builder_negative.py — ネガティブフィクスチャ(AC9)
  • .claude/skills/issue-refinement-loop/tests/test_loop_state_decide_integration.py — 統合テスト(AC3,AC10)
  • .claude/skills/issue-refinement-loop/tests/fixtures/loop_state_builder/** — テストフィクスチャ 6 件
  • .claude/skills/issue-refinement-loop/SKILL.md — build_loop_state 参照追加(AC4,AC11)
  • .claude/skills/issue-refinement-loop/references/loop-state.md — builder-first flow セクション追加(AC11)

AC 達成状況

AC 結果 VC
AC1 pass pytest test_loop_state_builder.py -v — 17 passed
AC2 pass test -f build_loop_state.py — 存在確認 + スキーマ検証テスト
AC3 pass pytest test_loop_state_decide_integration.py -v — 7 passed
AC4 pass SKILL.md に build_loop_state 2 箇所
AC5 preflight-scope: pr_review_only CLI 実行は PR レビュー時
AC6 pass pytest -k provenance — 2 passed
AC7 pass pytest -k no_next_action — 1 passed
AC8 pass pytest -k no_raw_json — 1 passed; allow_abbrev=False 確認
AC9 pass pytest test_loop_state_builder_negative.py -v — 10 passed
AC10 pass pytest -k builder — 7 passed
AC11 pass references/loop-state.md に build_loop_state 2 箇所
AC12 pass pytest -k no_gh_mutation — 1 passed; ソースに gh コマンドなし
AC13 pass pnpm typecheck/lint/test/build — all pass; pytest 864 passed

テスト計画

  • uv run pytest .claude/skills/issue-refinement-loop/tests/test_loop_state_builder.py -v — 17 passed
  • uv run pytest .claude/skills/issue-refinement-loop/tests/test_loop_state_builder_negative.py -v — 10 passed
  • uv run pytest .claude/skills/issue-refinement-loop/tests/test_loop_state_decide_integration.py -v — 7 passed
  • uv run pytest .claude/skills/issue-refinement-loop/tests/ -q — 864 passed (既存テスト含む)
  • pnpm typecheck — pass
  • pnpm lint (playwright-report 除外) — pass
  • pnpm test — 922 passed
  • pnpm build — pass

Closes #1024

🤖 Generated with Claude Code

… validation

Adds scripts/build_loop_state.py that constructs LOOP_STATE_V1 from
REFINEMENT_LOOP_PLAN_V1 and ISSUE_REVIEW_RESULT_COMPACT_V1. Includes
schema validation, provenance tracking, and builder-first flow docs.

AC1: build_loop_state.py added with approve/needs-fix fixture tests
AC2: validates against loop_state.schema.json via iter_errors() (all errors)
AC3: decide_next_loop_action.py integration tested with builder output
AC4: SKILL.md updated to reference build_loop_state (builder-first flow)
AC5: LOOP_STATE_BUILD_RESULT_V1 with status/sha256/errors/warnings/provenance
AC6: provenance includes planner/review path/hash, issue_number, iteration, schema path/hash
AC7: builder does not produce next_action field
AC8: argparse allow_abbrev=False, file-path-only input
AC9: negative fixtures — required missing, mismatch, regression, unknown verdict, boundary
AC10: integration tests approve/needs-fix/scope_signal/max_iterations routing
AC11: references/loop-state.md updated with builder-first flow section
AC12: builder performs no gh mutations
AC13: pnpm typecheck/lint/test/build and pytest all pass

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
@github-actions

github-actions Bot commented Jun 21, 2026 •

Copy link
Copy Markdown
Contributor

Preview URL

Preview removed (PR #1077 closed).

@squne121

Copy link
Copy Markdown
Owner Author

PR Review: feat(#1024) -- build_loop_state.py

Allowed Paths Gate

AC Verification

AC1: PASS (control-plane: 17 passed)
AC2: PASS (control-plane: file exists + schema validation)
AC3: PASS (control-plane: 7 passed)
AC4: PASS (review-subagent: build_loop_state count=2 in SKILL.md confirmed from PR branch head)
AC5: PASS (review-subagent: CLI executed, status=ok, exit 0, all LOOP_STATE_BUILD_RESULT_V1 fields present)
AC6: PASS (review-subagent: _make_provenance has planner/review path+hash, issue_number, iteration, schema_path+hash)
AC7: PASS (review-subagent: no next_action computation in build_loop_state.py, only docstring mentions)
AC8: PASS (review-subagent: allow_abbrev=False in ArgumentParser, no raw JSON string args)
AC9: PASS (control-plane: 10 negative fixture tests passed)
AC10: PASS (control-plane: 7 integration tests passed)
AC11: PASS (review-subagent: build_loop_state count=2 in references/loop-state.md confirmed from PR branch head)
AC12: PASS (review-subagent: no subprocess import, no gh invocations in build_loop_state.py source)
AC13: PASS (control-plane: pnpm typecheck/lint/test/build all pass)

AC5 CLI Output (preflight-scope: pr_review_only)

Executed by review-subagent using fixtures extracted from PR branch head (57c5144):

Output (exit code 0, status=ok):

Verdict

LOOP_VERDICT_V2:
verdict: APPROVE
merge_ready: true
pr_number: 1077
reviewed_head_sha: 57c5144
iteration: 0
required_auto_actions: []
allowed_paths_gate:
status: ok
producer_role: review_subagent
worker_report_used_as_canonical: false
expected_contract_fingerprint: sha256:ac7d10e9a0c17453b563118d5bf066329405daf122318bfaa3ee433af07b1cb0
contract_source_kind: issue_comment
contract_source_id: "4760829507"
files_checked: 13
files_outside_allowed_paths: 0
blockers: []
summary: All 13 changed files within Allowed Paths. AC1-AC13 all pass including AC5 CLI (status=ok, exit 0) and AC12 gh-mutation absence confirmed by source inspection.

@squne121

Copy link
Copy Markdown
Owner Author

判定

REQUEST_CHANGES。
既存のPRコメントでは AC1-AC13 PASS / APPROVE / merge_ready: true とされていますが、実装差分を敵対的に見ると、#1024 の本質である 「手書き・欠落・不整合な LOOP_STATE routing を排除する」 目的をまだ閉じ切れていません。PRは #1024 のスコープ、Allowed Paths、happy path テストはおおむね満たしていますが、fail-closed 境界に穴があります。既存レビューコメントでは13ファイルすべてAllowed Paths内、AC1〜AC13 pass と報告されています。

#1024 は、REFINEMENT_LOOP_PLAN_V1 と ISSUE_REVIEW_RESULT_COMPACT_V1 から schema-valid な LOOP_STATE_V1 を生成し、それを decide_next_loop_action.py に渡すことをスコープにしています。特に AC2 は必須欠落・追加プロパティを fail-closed で検知すること、AC3 は builder 出力を router に渡して routing を確認することを求めています。

Blocking findings

1. --blockers-history-file が実質的に壊れており、履歴が黙って消える

これは最重要です。#1024 の mapping では blockers_history は previous state file または explicit input 由来とされています。
PR実装のCLIヘルプも --blockers-history-file を “previous blockers_history JSON array file” と説明しています。

しかし実装は load_json() を使って blockers history を読んでいます。この load_json() は JSON object、つまり Python の dict 以外を拒否します。 その一方で blockers history は JSON array のはずです。Python の JSON 仕様上、JSON object は dict、JSON array は list に変換されます。([Python documentation]1)

結果として、正しい JSON array ファイルを渡しても load_json() が拒否し、さらに呼び出し側はエラーを pass で握り潰します。
これは warnings[] すら出さずに履歴を空配列へ落とすため、loop の再試行履歴・blocker履歴が失われます。builder-first の信頼性を壊すため、マージブロッカーです。

修正方針:

- load_json_object(path) と load_json_array(path) を分離する
- --blockers-history-file は JSON array だけ許可する
- 読み込み失敗・非配列は status=invalid か少なくとも warnings[] に出す
- test_blockers_history_file_array_is_preserved
- test_blockers_history_file_object_is_invalid
- test_blockers_history_file_missing_is_invalid_or_warned

2. 入力 artifact の欠落を fail-closed できていない

builder は plan.get("decisions", {}) から各 field を .get(..., default) で読み、欠落していても false / null / [] に丸めます。
follow_up_materialization も同様に欠落時は candidates: [] に丸めます。

さらに loop_state.schema.json はトップレベル必須フィールドは持ちますが、web_research_policy、scope_signal_guard、delivery_rollup、follow_up_materialization の内部フィールドには required がありません。
つまり、壊れた REFINEMENT_LOOP_PLAN_V1 からでも、builder が“それっぽい” schema-valid な LOOP_STATE_V1 を作れてしまいます。

これは #1006 で問題化していた「手作業で LOOP_STATE JSON を組み立て、存在しないCLI引数やschema validation errorを踏んだ迷走」を再発させるタイプの穴です。#1006 はまさに manual LOOP_STATE / wrong CLI を排除する背景を持っています。

修正方針:

- REFINEMENT_LOOP_PLAN_V1 入力を schema または明示 validator で検証する
- ISSUE_REVIEW_RESULT_COMPACT_V1 入力も schema または明示 validator で検証する
- decisions.web_research_policy / scope_signal_guard / delivery_rollup / follow_up_materialization 欠落は invalid
- review VERDICT 欠落は invalid
- 追加プロパティの扱いも入力artifact側で検証する

追加テスト:

test_missing_planner_decisions_is_invalid
test_missing_planner_web_research_policy_is_invalid
test_missing_planner_scope_signal_guard_is_invalid
test_missing_review_verdict_is_invalid
test_planner_additional_property_is_invalid_if_contract_forbids_it

3. router統合テストが last_verdict の単一情報源性を証明していない

builder は review から VERDICT / verdict を取り、loop_state["last_verdict"] に入れます。
しかし decide_next_loop_action.py は routing を loop_state["last_verdict"] ではなく、別CLI引数 --review-result-verdict で受け取った値に基づいて行います。

そのため、integration test が builder 出力を router に渡していても、実際の verdict 経路は builder artifact ではなく外部引数で成立しています。これは AC3/AC10 の検証として弱いです。さらに last_verdict schema は null を許可しており、review 側で VERDICT が欠落しても builder は未知値でなければ止めません。

修正方針はどちらかです。

A. router が --review-result-verdict 省略時に loop_state.last_verdict を使う
B. builder integration test で loop_state.last_verdict と --review-result-verdict の一致を必須にする
C. 不一致時は inconsistent_state として exit 3 にする

追加テスト:

test_builder_router_uses_loop_state_last_verdict
test_review_verdict_missing_is_invalid
test_review_verdict_cli_mismatch_is_inconsistent_state

4. issue_number の型不正で traceback になる可能性がある

plan_issue / review_issue は int(...) で変換されていますが、ValueError / TypeError を捕捉していません。
"abc" や object が入ると LOOP_STATE_BUILD_RESULT_V1 の errors[] を返さず、Python traceback で落ちる可能性があります。これは “fail-closed with diagnostics” の契約違反です。

修正方針:

- issue_number coercion helper を作る
- int化不能なら status=invalid
- errors[] に path / message / schema_path を返す

追加テスト:

test_planner_issue_number_non_integer_returns_build_result_json
test_review_issue_number_non_integer_returns_build_result_json

Non-blocking but should fix

Draft7Validator 固定は将来の unevaluatedProperties 対応と矛盾する

現行 loop_state.schema.json は draft-07 なので、今すぐ壊れているわけではありません。
ただし #1024 の AC2 は、additionalProperties: false と allOf の衝突時に unevaluatedProperties: false を採用するとしています。JSON Schema では additionalProperties は同じ subschema 内の properties しか認識せず、allOf 拡張で問題になります。unevaluatedProperties は draft 2019-09 以降の解決策です。(JSON Schema)

実装は jsonschema.Draft7Validator を固定しており、コメントも “Draft7Validator to handle additionalProperties/unevaluatedProperties” としていますが、これは設計上危険です。

推奨:

validator_cls = jsonschema.validators.validator_for(schema)
validator_cls.check_schema(schema)
validator = validator_cls(schema)
errors = sorted(validator.iter_errors(state), key=...)

iter_errors() で複数エラーを集める実装自体は正しいです。jsonschema の公式ドキュメントでも iter_errors() は複数の validation error を列挙できます。(jsonschema)

allow_abbrev=False は良い実装

ここは肯定評価です。Python argparse は通常、long option の省略形を受け付けるため、agent ops 系CLIでは allow_abbrev=False が妥当です。([Python documentation]4)
PR実装でも ArgumentParser(..., allow_abbrev=False) が入っています。

Pages preview はこのPRの証拠にはならない

PRコメントには preview URL がありますが、asset-level live check は未検証と明記されています。
今回の変更は workflow script / fixture / docs 中心で、#1024 側も runtime gameplay verification は not applicable なので、これはマージブロッカーではありません。ただし “previewがあるから安全” という証拠には使えません。

推奨するPRコメント案

REQUEST_CHANGES

既存レビューでは AC1-AC13 PASS とされていますが、fail-closed 契約に未解消の穴があります。

Blocking:

1. `--blockers-history-file` が壊れています。
   CLI help は JSON array file と説明していますが、実装は dict 専用の `load_json()` で読み、JSON array を拒否します。そのエラーも `pass` で握り潰すため、blockers_history が黙って空配列になります。これは loop state の履歴喪失であり、builder-first contract の目的に反します。

2. 入力 artifact の欠落を fail-closed できていません。
   `decisions.web_research_policy` / `scope_signal_guard` / `delivery_rollup` / `follow_up_materialization` が欠落しても `.get(...,{})` と default 値で schema-valid な LOOP_STATE が生成されます。生成後 schema validation だけでは `REFINEMENT_LOOP_PLAN_V1` / `ISSUE_REVIEW_RESULT_COMPACT_V1` の破損を検知できません。

3. router integration が verdict の single source of truth を証明していません。
   builder は `last_verdict` を生成しますが、router は別途 `--review-result-verdict` によって routing します。`last_verdict` 欠落・不一致でもテストが通る可能性があります。

4. `issue_number` の型不正で `int(...)` が traceback になり得ます。
   `LOOP_STATE_BUILD_RESULT_V1.errors[]` で返すべきです。

Required fixes:
- `load_json_object()` / `load_json_array()` を分離し、blockers_history の array を保持する。
- blockers_history 読み込み失敗は invalid または warnings[] に出す。
- planner/review input artifact を schema または明示 validator で検証する。
- review VERDICT 欠落・planner decisions 欠落を invalid にする。
- router verdict と loop_state.last_verdict の不一致を検出する、または router が loop_state.last_verdict を単一情報源として使う。
- invalid issue_number 型でも build result JSON を返す。

この修正後なら merge 可に近いです。

最終結論

このPRは方向性は正しいです。allow_abbrev=False、iter_errors()、deterministic JSON write、no-gh mutation、docs更新は良いです。
ただし現状のままマージすると、「builderを追加したが、欠落入力・履歴喪失・verdict不整合をschema-valid風に通してしまう」 可能性が残ります。#1024 の事故再発防止としては不十分なので、上記4点を修正してから再レビューが妥当です。

- Blocker 1: split load_json into load_json_object/load_json_array so
  --blockers-history-file accepts only JSON arrays; non-array files are
  warned rather than silently swallowed
- Blocker 2: validate required planner decisions fields
  (web_research_policy, scope_signal_guard, delivery_rollup,
  follow_up_materialization) and review VERDICT; missing fields return
  status=invalid
- Blocker 3: decide_next_loop_action.py now uses loop_state.last_verdict
  as the single source of truth when --review-result-verdict is omitted
- Blocker 4: wrap int() conversion of issue_number fields in try/except;
  non-integer values return status=invalid with JSON output (no traceback)
- Non-blocking: use jsonschema.validators.validator_for() to auto-select
  validator based on $schema
- Add 12 new negative/integration tests covering all 4 blockers

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>

@squne121 squne121 left a comment

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

LOOP_VERDICT_V2 — PR #1077 iteration 1 review

レビュー結果: REQUEST_CHANGES

実装コード・テスト・スキーマは問題なし。PR 本文の日本語チェック CI(job: PR Body Japanese Check)が fail しているため REQUEST_CHANGES。


詳細は続く。

@squne121

Copy link
Copy Markdown
Owner Author

test comment from review subagent

@squne121

Copy link
Copy Markdown
Owner Author

削除テスト用コメント(直後に上書き予定)

@squne121

Copy link
Copy Markdown
Owner Author

LOOP_VERDICT_V2 PR 1077 iteration 1: verdict=REQUEST_CHANGES, blockers=[B0: PR Body Japanese Check CI fail]

@squne121

Copy link
Copy Markdown
Owner Author

LOOP_VERDICT_V2 PR1077 iter1: REQUEST_CHANGES. B0=PR Body Japanese Check CI fail. 4 blockers fixed ok. AC5 ok.

@squne121 squne121 left a comment

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

iteration 1 fix_delta review: APPROVE (self-authored, comment only).

All 4 prior REQUEST_CHANGES blockers confirmed fixed, verified behaviorally on PR head 1585485. Bot self-report not used.

Verification summary

  • Allowed Paths Gate: ok. All 14 changed files lie within the Issue 1024 contract Allowed Paths (review_subagent recomputed deterministically from changed-files set x contract snapshot).
  • AC5 CLI (preflight-scope pr_review_only): ran PR-head build_loop_state.py and got status ok with full LOOP_STATE_BUILD_RESULT_V1 fields (status, loop_state_path, loop_state_sha256, errors[], warnings[], provenance). provenance carries planner/review/schema path+hash, issue_number, iteration (AC5, AC6).
  • PR-head tests: builder, negative, decide-integration suites = 46 passed (consistent with control-plane 909 all-pass).

Blocker fixes (behavioral)

  • Blocker 1 (blockers-history JSON array): array preserved, object or missing routed to warnings list (fail-closed, no silent swallow). 3 negative tests.
  • Blocker 2 (missing input artifact fail-closed): planner decisions missing, the four decision sub-fields missing, and review VERDICT missing all yield status=invalid plus an errors list. Negative tests cover each.
  • Blocker 3 (router last_verdict): when the verdict flag is omitted, loop_state.last_verdict is used as the authoritative source (integration tests cover approve and needs-fix). The conflict guard is retained: both values present and differing yields inconsistent_state with exit code 3 (directly confirmed). No regression.
  • Blocker 4 (issue_number type safety): non-integer issue_number in planner or review is caught, no traceback, status=invalid plus an errors list. 2 negative tests.

LOOP_VERDICT_V2

LOOP_VERDICT_V2:
  pr_number: 1077
  reviewed_head_sha: "158548566470b920fb44ea945642b7553a81284c"
  verdict: APPROVE
  merge_ready: true
  required_auto_actions: []
  allowed_paths_gate:
    status: ok
    producer_role: review_subagent
    worker_report_used_as_canonical: false
    changed_files_count: 14
    out_of_path_files: []
  blockers: []
  summary: iteration 1 fix_delta resolves the four prior blockers and stays within scope

Self-authored PR: merge is left to human judgment.

@squne121
squne121 merged commit 9ad89b3 into main Jun 21, 2026
20 of 21 checks passed
@squne121
squne121 deleted the worktree-issue-1024-loop-state-builder branch June 21, 2026 07:23
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

実装: agent-ops: issue-refinement-loop の LOOP_STATE builder を追加し手書き JSON routing を禁止する

1 participant