Skip to content

実装: check_issue_contract.py --json consumer の stdout/stderr 契約を regression test で固定する #598

Closed

Description

@squne121

Machine-Readable Contract

contract_schema_version: v1
issue_kind: implementation
parent_issue: none
goal_ref: "check_issue_contract.py --json の caller が stdout のみを JSON parse し stderr は diagnostics として扱う契約を regression test で固定し、stdout が JSON parse 不能なときは fail-open ではなく fail-closed にする"
change_kind: code

Parent Issue

none(PR #596 の follow-up 単独バグ修正)

Parent Goal Ref

  • Goal: なし(単独 follow-up)
  • Desired Destination: なし

Current Validated Scope

  • issue_contract_hygiene_autofix.py の check_non_c4_c9_blockers で、json.loads(proc.stdout) が JSONDecodeError を出した場合の挙動を、現状の fail-open(return False, [])から fail-closed(return True, ["check_error"])へ変更する
  • 同関数に caller contract コメント(stdout = JSON only、stderr = diagnostics、stderr を stdout に merge しない)を追加する
  • test_issue_contract_hygiene_autofix.py に subprocess.run を monkeypatch する regression test 群(stream 分離 kwargs 検査・stderr 診断混入の正例・stdout 結合の fail-closed 負例)を追加する
  • check_issue_contract.py の --json モード docstring または argparse --json help に caller contract を明記する

Remaining Parent Gaps

なし

Outcome

check_issue_contract.py --json の主要 consumer(issue_contract_hygiene_autofix.py の check_non_c4_c9_blockers)が、

  1. subprocess.run(..., capture_output=True, text=True) で stdout/stderr を分離してキャプチャし(stderr=subprocess.STDOUT を使わない)、
  2. JSON parse 対象を stdout のみに限定し、stderr に診断出力が流れても parse が成功し、
  3. stdout が valid JSON として parse できない場合は fail-open(return False, [])せず fail-closed(return True, ["check_error"])で non-C4/C9 blocker check を有効化したまま安全側へ倒す、

ことを monkeypatch ベースの regression test が保証している状態。

Background

PR #596(Issue #574)で check_issue_contract.py --json 単体の stdout purity を修正した。script 側は contextlib.redirect_stdout(sys.stderr) で最終 JSON 以外の標準出力を封じ、datetime.utcnow() の DeprecationWarning も除去した。

しかし、caller 側の契約(stdout のみを JSON parse し、stderr は diagnostics として扱う)は regression test で固定されていない。将来 consumer が stderr=subprocess.STDOUT 相当でストリームを結合した場合、将来追加された warning や diagnostics によって JSON parse error が再発する可能性がある。

さらに、現行 check_non_c4_c9_blockers は json.loads(proc.stdout) が JSONDecodeError を出した場合に return False, [](fail-open)しており、これは「契約違反を検出したら non-C4/C9 blocker の検出をスキップして autofix を続行しうる」挙動である。本 Issue では caller 契約の固定に合わせて、この parse 失敗を fail-closed(check_error)へ変更し、退行を regression test で固定する。

現在の check_non_c4_c9_blockers は capture_output=True(stdout/stderr 分離)を使っているが、この分離を保証する regression test がなく、将来 stderr=subprocess.STDOUT が追加されても検出できない。

In Scope

  • check_non_c4_c9_blockers の JSONDecodeError 分岐を fail-open(return False, [])から fail-closed(return True, ["check_error"])へ変更する
  • 同関数に caller contract コメント(stdout のみを JSON parse、stderr は diagnostics、stderr を stdout に merge しない)を追加する
  • test_issue_contract_hygiene_autofix.py に subprocess.run を monkeypatch して以下を固定する regression test を追加する:
    • 関数名に stream_separation を含むテスト: check_non_c4_c9_blockers が capture_output=True, text=True を使い stderr=subprocess.STDOUT を使わないことを kwargs 検査で固定する
    • 関数名に stderr_diagnostic_ignored を含むテスト: stdout が valid JSON・stderr に診断 warning がある場合に stdout のみ parse して成功する(正例)
    • 関数名に fail_closed_on_non_json を含むテスト: stdout が「診断テキスト + JSON」結合の場合に fail-open せず return True, ["check_error"] で fail-closed する(負例)
  • check_issue_contract.py の --json モード docstring または argparse --json help に caller contract を明記する("diagnostics" を含む文言で stdout=JSON only / stderr=diagnostics / stderr を stdout に merge しない、を記述)

Out of Scope

Acceptance Criteria

  • AC1: test_issue_contract_hygiene_autofix.py に、check_non_c4_c9_blockers が subprocess.run(..., capture_output=True, text=True) を使い stderr=subprocess.STDOUT を使わないことを monkeypatch で kwargs 検査する regression test(関数名に stream_separation を含む)が追加され、PASS する
  • AC2: subprocess.run の戻り値が stdout=<valid JSON>, stderr=<診断 warning> の場合に check_non_c4_c9_blockers が stdout のみを JSON parse し stderr に影響されず成功する regression test(関数名に stderr_diagnostic_ignored を含む)が追加され、PASS する
  • AC3: subprocess.run の戻り値が stdout=<診断テキスト + JSON> の場合に check_non_c4_c9_blockers が fail-open せず return True, ["check_error"] で fail-closed する regression test(関数名に fail_closed_on_non_json を含む)が追加され、PASS する
  • AC4: check_issue_contract.py に caller contract(stdout = JSON only、stderr = diagnostics、caller は stderr を stdout に merge しない)が module docstring または --json argparse help に "diagnostics" を含む文言で明記されている
  • AC5: pnpm typecheck が PASS する
  • AC6: pnpm lint が PASS する
  • AC7: pnpm test が PASS する
  • AC8: pnpm build が PASS する

Verification Commands

# AC1
$ rg -n "stream_separation" .claude/skills/edit-issue/tests/test_issue_contract_hygiene_autofix.py

# AC2
$ rg -n "stderr_diagnostic_ignored" .claude/skills/edit-issue/tests/test_issue_contract_hygiene_autofix.py

# AC3
$ rg -n "fail_closed_on_non_json" .claude/skills/edit-issue/tests/test_issue_contract_hygiene_autofix.py

# AC4
$ rg -n "diagnostics" .claude/skills/review-issue/scripts/check_issue_contract.py

# AC5
# preflight-scope: runtime_only
$ pnpm typecheck

# AC6
# preflight-scope: runtime_only
$ pnpm lint

# AC7
# preflight-scope: runtime_only
$ pnpm test

# AC8
# preflight-scope: runtime_only
$ pnpm build

Allowed Paths

  • .claude/skills/edit-issue/tests/test_issue_contract_hygiene_autofix.py
  • .claude/skills/edit-issue/scripts/issue_contract_hygiene_autofix.py
  • .claude/skills/review-issue/scripts/check_issue_contract.py

Stop Conditions

  • Allowed Paths 外の変更が必要と判明した場合
  • In Scope の固定契約(キー集合・スキーマ・型定義)の変更が必要になった場合
  • 新規 Issue の起票が必要と判断した場合(スコープ分割が発生する場合)
  • 後続 Phase / 別スコープへの波及が判明した場合
  • nested SubAgent delegation が必要になった場合
  • 外部サービス利用・権限昇格・既存テスト大規模改変が必要になった場合

Required Skills

なし

Scope Delta(任意)

PR #596 の follow-up として起票後、anchor comment(#598 の human review, 2026-06-06)の NEEDS FIX 判定を反映して In Scope / Outcome / AC を更新した。主な変更は (1) JSONDecodeError 分岐の fail-open → fail-closed 化を In Scope に追加、(2) 弱い grep AC を subprocess.run monkeypatch ベースの kwargs 検査 + 正例/負例 regression test に差し替え、(3) caller contract の明記要件を docstring または argparse help に拡張、の 3 点。Allowed Paths は変更なし。

Runtime Verification Applicability

本 Issue は Python スクリプトの挙動変更(fail-closed 化)とテスト追加・docstring 追加のみです。ゲームの実行時動作には影響しません。

decision: not_applicable
reason: "Python script consumer behavior change (fail-open to fail-closed) plus regression test and docstring addition only. No runtime game behavior changed."

Delivery Rule

1 Issue = 1 PR、worktree 作業、Draft PR 既定。

Activity

  1. added
    bug
    phase/implementation
    agent/implementer
    on Jun 2, 2026
  2. squne121 commented on Jun 6, 2026

    @squne121
    OwnerAuthor

    判定: NEEDS FIX

    #598 の方向性は妥当です。ただし、このまま実装すると「stdout/stderr 分離契約を固定したつもり」になり、肝心の退行条件を殺しきれません。特に、現在の consumer 側は json.loads(proc.stdout) に失敗した場合に fail-open で return False, [] しており、これは「非 C4/C9 blocker の検出をスキップして autofix を続行しうる」挙動です。ここはブロッカーです。([GitHub]1)

    確認した関連関係

    #598 は #596 の follow-up 単独バグ修正として作られており、目的は check_issue_contract.py --json の caller が stdout のみを JSON parse し、stderr を diagnostics として扱う契約を regression test で固定することです。Scope には issue_contract_hygiene_autofix.py の caller contract コメント追加、test_issue_contract_hygiene_autofix.py への stderr 混入 regression test 追加、check_issue_contract.py の --json docstring 明記が入っています。([GitHub]2)

    #574 は前段の問題で、check_issue_contract.py --json 実行時に datetime.utcnow() の DeprecationWarning や diagnostics が stdout/JSON parse を壊す可能性を扱っていました。#574 自体も「Python warnings は通常 stderr」「caller が stdout/stderr を結合している可能性」を明示しています。([GitHub]3)

    #596 は #574 対応 PR で、datetime.datetime.utcnow() を datetime.datetime.now(datetime.timezone.utc) に置換し、--json 処理中の incidental stdout を contextlib.redirect_stdout(sys.stderr) で stderr に逃がし、stdout に最終 JSON だけを出す変更を入れています。([GitHub]4)

    #598 自体は Open で、GitHub 上の Development 欄には現時点で branch / PR は紐づいていません。([GitHub]2)

    技術調査からの前提

    Python の subprocess.run(capture_output=True) は内部的に stdout/stderr をそれぞれ PIPE にし、分離して捕捉します。逆に stdout/stderr を結合したい場合は stdout=PIPE, stderr=STDOUT を使う、というのが公式仕様です。したがって、この Issue で固定すべき契約は「capture_output=True または stdout=PIPE, stderr=PIPE で分離し、JSON parse 対象は stdout のみ」です。([Python documentation]5)

    Python warnings は通常 sys.stderr に書かれます。つまり stderr に warning が出ること自体は正常であり、consumer が stderr を stdout に混ぜて JSON parse するのが壊れ方の本質です。([Python documentation]6)

    contextlib.redirect_stdout は utility script では有用ですが、sys.stdout への global side effect があるため library code や threaded application には不向きで、subprocess の出力には効きません。#596 の script-local 対応は utility script としては許容できますが、caller 側では subprocess の stream 分離を別途固定する必要があります。([Python documentation]7)

    ブロッカー

    B1. JSON parse failure が fail-open のまま残っている

    現行 issue_contract_hygiene_autofix.py は proc.stdout を json.loads し、JSONDecodeError なら「non-JSON output; cannot parse — skip guard」として return False, [] します。これは「契約違反を検出したら安全側に倒す」ではなく、「契約違反時に blocker check を無効化する」です。([GitHub]1)

    #598 の主題は「caller 契約の固定」です。ならば、stdout が JSON として parse できない場合は return True, ["check_error"] 相当で fail-closed にすべきです。最低でも regression test で以下を固定してください。

    def test_check_non_c4_c9_blockers_fails_closed_when_stdout_is_not_json(monkeypatch, tmp_path):
        import subprocess
        import issue_contract_hygiene_autofix as mod
    
        def fake_run(*args, **kwargs):
            return subprocess.CompletedProcess(
                args=args[0],
                returncode=1,
                stdout="DeprecationWarning: noisy diagnostic\n{\"blocking_issues\": []}",
                stderr="",
            )
    
        monkeypatch.setattr(mod.subprocess, "run", fake_run)
        monkeypatch.setattr(mod.os.path, "isfile", lambda _: True)
    
        has_other, codes = mod.check_non_c4_c9_blockers("body")
        assert has_other is True
        assert codes == ["check_error"]

    B2. AC2 が rg "capture_output" だけなのは弱い

    #598 の AC2 は capture_output=True の grep 一致です。これはコメントや無関係箇所でも通りますし、将来 stderr=subprocess.STDOUT が追加されても検出できません。現行実装は capture_output=True で subprocess を呼び、stdout のみを parse していますが、これを grep ではなくテストで固定すべきです。([GitHub]1)

    推奨テストは、subprocess.run を monkeypatch して kwargs を検査する形です。pytest の monkeypatch.setattr はテスト中だけ関数・属性を差し替え、テスト終了後に戻す用途として公式に想定されています。([pytest]8)

    def test_check_non_c4_c9_blockers_uses_separated_stdout_stderr(monkeypatch):
        import subprocess
        import issue_contract_hygiene_autofix as mod
    
        seen = {}
    
        def fake_run(*args, **kwargs):
            seen["kwargs"] = kwargs
            return subprocess.CompletedProcess(
                args=args[0],
                returncode=1,
                stdout='{"blocking_issues": []}',
                stderr="DeprecationWarning: diagnostic on stderr",
            )
    
        monkeypatch.setattr(mod.subprocess, "run", fake_run)
        monkeypatch.setattr(mod.os.path, "isfile", lambda _: True)
    
        has_other, codes = mod.check_non_c4_c9_blockers("body")
    
        assert has_other is False
        assert codes == []
        assert seen["kwargs"]["capture_output"] is True
        assert "stderr" not in seen["kwargs"]  # stderr=STDOUT 退行を禁止
        assert seen["kwargs"]["text"] is True

    B3. 「stderr に疑似 warning が流れても stdout parse 成功」だけでは、本件の退行を十分に再現していない

    stderr が別 stream にある限り、stdout JSON parse が成功するのは当然です。Python 公式でも capture_output=True は stdout/stderr を別々に捕捉します。([Python documentation]5)

    本当に殺すべき退行は、将来誰かが stderr=subprocess.STDOUT 相当で結合した場合です。したがって、テストは少なくとも次の 2 本が必要です。

    1. 正のケース: stdout='{"blocking_issues":[]}', stderr='DeprecationWarning...' なら parse 成功。
    2. 負のケース: stdout='DeprecationWarning...\n{"blocking_issues":[]}', stderr=None なら fail-closed。

    これを入れないと、#574 で特定した壊れ方を #598 が固定できません。

    ノンブロッカー

    N1. check_issue_contract.py の docstring だけでなく CLI help にも契約を出した方がよい

    #598 は --json モード docstring に caller contract を明記するとしています。これは最低限として妥当ですが、caller 実装者が見るのは module docstring より --help や周辺コメントの可能性が高いです。argparse の --json help にも次の趣旨を入れるとよいです。

    --json: emit exactly one JSON object to stdout; diagnostics may be emitted to stderr. Callers MUST parse stdout only and MUST NOT merge stderr into stdout before JSON parsing.
    

    N2. contextlib.redirect_stdout への過信は避ける

    #596 の redirect_stdout(sys.stderr) は utility script では許容できますが、公式 docs の通り global stdout を差し替えるため library / threaded 用途には不向きです。([Python documentation]7)
    #598 側の説明では「script 側で stdout purity を頑張る」ではなく、「caller は stream contract を守る」と明確に分離してください。

    N3. AC4〜AC7 は過剰気味

    #598 の変更対象は .claude/skills/** の Python script / test / docstring であり、ゲーム runtime には影響しません。Issue 本文も runtime verification は not_applicable としています。([GitHub]2)
    pnpm typecheck/lint/test/build を残すのはプロジェクト運用上はよいですが、実質的な品質ゲートは uv run pytest .claude/skills/edit-issue/tests/test_issue_contract_hygiene_autofix.py -v と、必要なら review-issue 側の pytest です。

    起票文への修正提案

    #598 はこのまま実装に回すより、AC を次のように差し替えるのが安全です。

    ## Acceptance Criteria
    
    - AC1: `test_issue_contract_hygiene_autofix.py` に、`check_non_c4_c9_blockers` が `subprocess.run(..., capture_output=True, text=True)` を使い、`stderr=subprocess.STDOUT` を使わないことを monkeypatch で検証する regression test がある。
    - AC2: `subprocess.run` の戻り値が `stdout=<valid JSON>`, `stderr=<diagnostic warning text>` の場合、`check_non_c4_c9_blockers` が stdout のみを JSON parse し、stderr に影響されず成功する regression test がある。
    - AC3: `subprocess.run` の戻り値が `stdout=<diagnostic text + JSON>` の場合、`check_non_c4_c9_blockers` が fail-open せず `check_error` として fail-closed する regression test がある。
    - AC4: `check_issue_contract.py --json` の caller contract が module docstring または `--json` help に明記されている: stdout は JSON only、stderr は diagnostics、caller は stderr を stdout に merge して JSON parse してはならない。
    - AC5: `uv run pytest .claude/skills/edit-issue/tests/test_issue_contract_hygiene_autofix.py -v` が PASS する。

    結論

    #598 は必要です。ただし、現状の AC だと「現在たまたま分離している」ことを弱く確認するだけで、実際の退行条件である stderr=STDOUT / JSONDecodeError / fail-open を固定できません。

    実装に回す前に、JSONDecodeError を fail-closed に変更すること、grep ではなく monkeypatch による kwargs 検査を入れること、stderr 分離の正例と stderr 結合の負例を両方 regression test 化することをブロッカーとして要求するのが妥当です。

  3. squne121 commented on Jun 6, 2026

    @squne121
    OwnerAuthor

    Refinement Loop: Approved

    The issue has been approved and is ready for implementation.

  4. squne121 commented on Jun 6, 2026

    @squne121
    OwnerAuthor
    LOOP_HANDOFF_RESULT_V1:
      status: impl_ready
      routing_action: run_impl_review_loop
      contract_review:
        status: go
        gate_result: fresh_go
        latest_comment_url: https://github.com/squne121/loop-protocol/issues/598
        generated_at: "2026-06-06T23:42:49Z"
        body_sha256: sha256:06a16248cb2dea62c0680b73f4313e6c38ff7344742962252af1ce0d2845faec
      metadata:
        title_prefix_ready: true
        phase_label_ready: true
      auto_fixes:
        result: auto_fixed
        required: []
        skipped: []
      blockers: []
      permissions:
        unavailable: []
      generated_at: "2026-06-06T23:42:49Z"
      checked_body_sha256: sha256:06a16248cb2dea62c0680b73f4313e6c38ff7344742962252af1ce0d2845faec
      checker_exit_code: 0
      missing_sections: []
      missing_contract_keys: []
    FOLLOW_UP_MATERIALIZATION_RESULT_V1:
      schema_version: 1
      materialized_by: issue-refinement-loop
      follow_up_issues: []
      note_only_observations: []
  5. squne121 commented on Jun 6, 2026

    @squne121
    OwnerAuthor

    Contract Snapshot (2026-06-06T23:48:05Z)

    • Outcome: check_issue_contract.py --json の consumer (check_non_c4_c9_blockers) が stdout/stderr を分離キャプチャし、stdout のみ JSON parse、parse 不能時は fail-closed (return True, ["check_error"]) になることを regression test で固定した状態。
    • Acceptance Criteria: AC1 stream_separation test / AC2 stderr_diagnostic_ignored test / AC3 fail_closed_on_non_json test / AC4 caller contract docstring or --json help に "diagnostics" 明記 / AC5-8 pnpm typecheck/lint/test/build
    • Verification Commands: rg(AC1-3 test 関数名) / rg "diagnostics"(AC4) / pnpm typecheck,lint,test,build(AC5-8, runtime_only)
    • Allowed Paths: .claude/skills/edit-issue/tests/test_issue_contract_hygiene_autofix.py, .claude/skills/edit-issue/scripts/issue_contract_hygiene_autofix.py, .claude/skills/review-issue/scripts/check_issue_contract.py
    • Worktree: .claude/worktrees/issue-598-check-issue-contract-py-json-consumer-st
    • Branch: worktree-issue-598-check-issue-contract-py-json-consumer-st
    • VC preflight: baseline fail = 4 (AC1-4), 想定外 pass = 0, 実行不可 = 0, skipped(runtime_only) = 4 (AC5-8)
    CONTRACT_REVIEW_RESULT_V1:
      status: go
      generated_at: 2026-06-06T23:48:05Z
      generated_by: issue-contract-review
      issue_url: https://github.com/squne121/loop-protocol/issues/598
      body_sha256: 33c884d6847ed441d21512cb44187f70eb9524b2062d7c73c19b70cb129de6e4
      checks:
        template_compliance: pass
        state_label: ok
        allowed_paths_present: pass
        vc_present: pass
        stop_conditions_complete: pass
        vc_preflight:
          passed: true
          vc_failed_as_expected: 4
          vc_passed_unexpectedly: 0
          vc_unrunnable: 0
          vc_expected_pass: 0
          vc_skipped: 4
          status: pass
          classifications:
            - ac: AC1
              classification: expected_fail
              category: expected_baseline_fail
              scope_class: baseline_fail_expected
              decision: go
            - ac: AC2
              classification: expected_fail
              category: expected_baseline_fail
              scope_class: baseline_fail_expected
              decision: go
            - ac: AC3
              classification: expected_fail
              category: expected_baseline_fail
              scope_class: baseline_fail_expected
              decision: go
            - ac: AC4
              classification: expected_fail
              category: expected_baseline_fail
              scope_class: baseline_fail_expected
              decision: go
            - ac: AC5
              classification: skipped
              category: preflight_scope_runtime_only
              scope_class: runtime_only
              decision: go
            - ac: AC6
              classification: skipped
              category: preflight_scope_runtime_only
              scope_class: runtime_only
              decision: go
            - ac: AC7
              classification: skipped
              category: preflight_scope_runtime_only
              scope_class: runtime_only
              decision: go
            - ac: AC8
              classification: skipped
              category: preflight_scope_runtime_only
              scope_class: runtime_only
              decision: go
        ac_verifiability: pass
        product_spec_check:
          applicability: not_applicable
          decision: pass
        worktree_branch_collision: clear
      next_action: implement_issue
      blocked_reasons: []
      warnings: []
  6. squne121 commented on Jun 6, 2026

    @squne121
    OwnerAuthor

    implement-issue: 実装完了 (2026-06-06T23:54:42Z)

  7. added 2 commits that reference this issue on Jun 7, 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/implementerbugphase/implementation

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions