Skip to content

実装: agent-retrospective の structured output compatibility recovery が fence 前後の地の文で decode failure する missing_structured_output を解消する #2348

Closed

Description

@squne121

Machine-Readable Contract

contract_schema_version: v1
issue_kind: implementation
parent_issue: "none"
goal_ref: "agent-retrospective の production Agent invocation (`retrospective-runtime-observer`) が非空・実質的な分析タスク prompt に対して `reason_code=missing_structured_output` で不必要に fail-closed する根本原因(compatibility recovery の fence-anchor 正規表現不一致)を解消する"
change_kind: code

Parent Issue

なし(単独改善)

Parent Goal Ref

  • Goal: なし(単独 Issue)
  • Desired Destination: なし(単独 Issue)

Current Validated Scope

  • .claude/skills/agent-retrospective/scripts/run_retrospective.py の invoke_agent() / compatibility recovery(_structured_output_from_result_compat() 相当)の fence 抽出ロジック修正
  • 新規テストファイル .claude/skills/agent-retrospective/scripts/tests/test_run_retrospective_structured_output_prose_fence.py による regression test の追加

Remaining Parent Gaps

なし(単独改善 Issue のため)

Outcome

invoke_agent() の compatibility recovery(_structured_output_from_result_compat() 相当)が、fenced JSON block の前後に地の文(prose)を伴う --agent 呼び出しの実際の応答形状からも structured_output 相当の JSON を確実に抽出できるように run_retrospective.py を修正し、これを再現する regression test を新規テストファイルとして追加した上で、修正前は fail する新規テストが修正後に PASS し既存 hermetic suite(test_run_retrospective.py)が回帰なく PASS している状態を完了とする。schema validation は一切緩めない(malformed/partial output の fail-closed は維持する)。本 Issue の完了は本 Issue の failure shape(--agent 呼び出しの fence-anchor 不一致)の解消のみを意味し、agent-retrospective 全体や他 Issue(#2345/#2347、#2239、#2350 等)が扱う別種の failure の解消を含意しない。

Runtime Verification Applicability

decision: immediate
reason: 本 Issue は Issue #2341 と同種の claude_live 実 Claude Code CLI round-trip の挙動に関わる compatibility recovery ロジックを扱うため、docs/dev/runtime-verification-policy.md の適用判定スキーマ上 immediate に該当する。
applicable_acs: AC3
execution_environment: 現在インストール済みの claude CLI バイナリ(実装時点の最新 main HEAD、認証済みサブスクリプションログイン環境)による手動実行環境。デフォルト CI 実行環境(claude CLI 非搭載)とは区別する。
skip_conditions: claude binary が PATH に存在しない、または claude auth status が非ゼロ exit で終了する(認証未確立)場合は SKIP とし、実装完了報告に SKIP 種別を明記する。
fallback_policy: SKIP は PASS に昇格しない。SKIP が発生した場合は fail-closed のまま維持し、実装完了報告には「実行できなかった」ことと skip_condition の種別を明記する。
artifact_requirements: 実 CLI 経由で retrospective-runtime-observer を非空・実質的な分析 prompt で呼び出した際に、reason_code=missing_structured_output とならず structured_output が正しく抽出されることを示す sanitized bounded classification(reason_code, structured_output_present 等。raw stdout 全文・credential・絶対パスは含めない)を実装完了時に PR 本文または PR コメントへ証跡として残す。この artifact は compatibility recovery 関数が実際に経由したことの証明までは要求しない(その証明は AC1/AC2 の hermetic regression test が担う)。

Background

.claude/skills/agent-retrospective/scripts/run_retrospective.py(agent-retrospective の production entrypoint)を current main + Claude Code 2.1.245 で、retrospective-runtime-observer に対する非空・実質的な分析タスク prompt を用いて実行すると、reason_code=missing_structured_output(exit_code:0, wrapper is_error:false, structured_output フィールド欠落)で fail-closed する。

Issue #2341(CLOSED、PR #2342 merged)は同一症状を報告していたが、scope は「失敗を診断可能にすること」と「regression coverage gap の解消(allowlist 化)」のみであり、Stop Conditions で「upstream CLI 挙動の確定原因が調査しても特定できない場合、compatibility 対応は見送り follow-up として別途起票してよい」と根本原因修正を明示的に先送りしていた(実装完了報告でもこの対応は未実施)。

今回、独立 read-only SubAgent による調査で、より具体的な root cause が判明した。invoke_agent() の compatibility recovery 関数(_structured_output_from_result_compat() 相当、run_retrospective.py L710-943 付近)が使用する markdown fence 抽出用正規表現は、「result テキスト全体が単一の fenced JSON block のみで構成されている」ことを要求する厳格な anchor 正規表現である。しかし実際の --agent retrospective-runtime-observer --output-format json --json-schema <observer_result_v1.schema.json> --no-session-persistence 呼び出しの result テキストは、fenced JSON block の前後に説明的な地の文(prose)を伴う(sanitized 実測: fence_count=2、複雑 prompt 側は starts_with_fence=true / ends_with_fence=false、単純 echo prompt 側は starts_with_fence=false / ends_with_fence=false)ため、anchor 正規表現が非マッチとなり json.loads 段階で decode failure(Expecting value: line 1 column 1)となる。

この失敗は prompt の複雑さにも observer_result_v1.schema.json の findings フィールドの nesting 構造(Issue #2341 が仮説として挙げていたもの)にも依存せず、複雑 prompt・単純 echo prompt の両方で同一の fence-anchor 不一致により再現することを独立 SubAgent が確認した。_structured_output_from_result_compat のdocstring自体も「--agent <custom-subagent> 呼び出しは schema-less な -p --json-schema 呼び出しと異なり structured_output を省略する」ことを認めている。

この根本原因は Issue #2341 本文にも他の open Issue にも記載がなく、gh issue list --state all --search "missing_structured_output" 等の dedupe 検索でも既存 owner は見つからなかった。

参考: 同種の症状(subtype: success かつ result 内の markdown fence に有効な JSON があるにもかかわらず structured_output が欠落する)は upstream の公開 Issue(anthropics/claude-agent-sdk-typescript#277)でも報告されており、Agent SDK 公式ドキュメント(structured-outputs)自体も「subtype: success でも structured_output が存在しないケースがあり、失敗として扱うべき」と明記している。局所的な compatibility workaround を維持する実用上の根拠として記録する。

In Scope

  1. invoke_agent() の compatibility recovery(_structured_output_from_result_compat() 相当)の fence 抽出ロジックを次の方針で修正する: result 文字列全体に対する厳格な ^...$ anchor 一致を要求する現状の実装をやめ、result 内に現れる fenced code block(json ... / ...)を non-greedy に列挙し、各候補 body を json.loads した上で既存の jsonschema.validate(呼び出し時の json_schema_path に対する厳密検証。緩和しない)で検証し、schema-valid な候補が一意に定まる場合にのみそれを採用する。候補が0件、または schema-valid な候補が複数件(曖昧)の場合は、現状どおり None(missing_structured_output 扱い)を返す。
  2. 新規のリグレッションテストファイル .claude/skills/agent-retrospective/scripts/tests/test_run_retrospective_structured_output_prose_fence.py を追加する。既存 test_run_retrospective.py と同じ hermetic 実行契約(実 CLI 呼び出しなし、claude_live marker なし)に従い、少なくとも以下を検証する:
    • 本 Issue の Background に記載した実測 shape 1(starts_with_fence=true / ends_with_fence=false: fenced JSON block の直後に説明的な地の文が続く)を模した sanitized fixture で、修正前は decode failure し修正後は成功すること
    • 実測 shape 2(starts_with_fence=false / ends_with_fence=false: fenced JSON block の前後両方に地の文がある)を模した sanitized fixture で、同様に修正前は decode failure し修正後は成功すること
    • 地の文中に fenced block はあるが、その中身が対象 JSON Schema に適合しない場合、修正後も引き続き None(missing_structured_output 扱い)を返すこと(fail-closed が緩まないことを示すネガティブケース)

Out of Scope

Acceptance Criteria

  • AC1: invoke_agent() の compatibility recovery が、fenced JSON block の前後に地の文を伴う result テキストからも、In Scope 記載の non-greedy fence 列挙 + 一意 schema-valid candidate 判定方式で structured_output を抽出できるよう修正されている
  • AC2: fence 前後に地の文を含む2種類の sanitized fixture(実測 shape 1 / shape 2)と、schema 不適合な fenced block のみを含むネガティブケースを検証する regression test が新規テストファイル test_run_retrospective_structured_output_prose_fence.py として追加されている
  • AC3: 実 claude CLI 経由で retrospective-runtime-observer を非空・実質的な分析 prompt で呼び出した際に、reason_code=missing_structured_output とならず structured_output が抽出されることを既存の claude_live live wrapper 経由で確認する(Runtime Verification Applicability 参照。compatibility recovery 関数が実際に経由したことの証明までは要求しない)
  • AC4: 既存の hermetic suite test_run_retrospective.py が回帰なく PASS する

Verification Commands

# AC1
# AC2
# baseline-expect: fail
$ uv run --locked pytest .claude/skills/agent-retrospective/scripts/tests/test_run_retrospective_structured_output_prose_fence.py -q

# AC3
# baseline-expect: deferred
# preflight-scope: runtime_only
$ .claude/skills/agent-retrospective/scripts/tests/verify_run_retrospective_live_cli.sh --select test_real_claude_cli_analytical_prompt_structured_output_shape

# AC4
$ uv run --locked pytest .claude/skills/agent-retrospective/scripts/tests/test_run_retrospective.py

Allowed Paths

  • .claude/skills/agent-retrospective/scripts/run_retrospective.py
  • .claude/skills/agent-retrospective/scripts/tests/test_run_retrospective.py
  • .claude/skills/agent-retrospective/scripts/tests/test_run_retrospective_structured_output_prose_fence.py

Stop Conditions

  • Allowed Paths 外の変更が必要と判明した場合
  • In Scope の固定契約(キー集合・スキーマ・型定義)の変更が必要になった場合
  • 新規 Issue の起票が必要と判断した場合(スコープ分割が発生する場合)
  • 後続 Phase / 別スコープへの波及が判明した場合
  • nested SubAgent delegation が必要になった場合
  • 外部サービス利用・権限昇格・既存テスト大規模改変が必要になった場合
  • 修正により既存の test_real_claude_cli_production_policy_round_trip(test_run_retrospective_live_cli.py)が fail するようになった場合は停止
  • fence-anchor 緩和により schema validation が弱まる、または malformed output を誤って成功扱いする経路が生まれると判明した場合は停止
  • non-greedy fence 列挙の結果、複数の fence を跨いで JSON を誤結合する(greedy match 由来の新規 defect)実装になっていないと判明した場合は停止し、実装をやり直す

Required Skills

なし

Required Design References

  • .claude/skills/agent-retrospective/SKILL.md
  • docs/dev/runtime-verification-policy.md

Scope Delta(任意)

N/A

Activity

  1. squne121 commented on Aug 25, 2026

    @squne121
    OwnerAuthor

    結論

    判定: REQUEST_CHANGES です。

    ただし、Issue #2348 が狙っている修正方向そのものは正しいです。current main の _MARKDOWN_JSON_FENCE_RE は ^...$ で result 全体を単一 fenced block として要求しており、Issue が説明する「JSON fence の前後に prose があると decode できない」という根本原因と実装が一致しています。

    また、この compatibility recovery 自体を削除するべきではありません。Claude Code の公式仕様では --json-schema 時の正規出力は structured_output ですが、公式 Agent SDK docs 自体が subtype=success でも structured_output が存在しないケースを認めています。さらに Anthropic の公開 Issue #277 には、正しい JSON が result 内の Markdown fence に入っているのに structured_output が欠落する、#2348 と非常に近い実例があります。([Claude]1)

    問題は Issue 契約の VC が2か所壊れていることと、「非 anchored re.search にする」という修正案だけでは新しい曖昧性を作り得ることです。#2348 自体には現時点でコメントはありません。

    敵対的レビュー findings

    1. P0 — AC1 の Verification Command は現状ですでに PASS するので、baseline-expect: fail が虚偽です。
      AC1 は grep -n "def _structured_output_from_result_compat" ... ですが、その関数は current main に既に存在します。したがって未実装 baseline で exit 0 になります。しかもこの grep は「prose 前後の fence を回収できる」という AC1 の挙動を一切検証しません。Issue 本文の VC と production code が明確に食い違っています。
      これは実装前に直すべき blocker です。 AC1/AC2 は同じ behavioral regression test に束縛して構いません。

    2. P0 — AC3 は「runtime verification」と書いてあるのに、VC は shell file の executable bit しか確認していません。
      現在の VC は test -x .../verify_run_retrospective_live_cli.sh ですが、この wrapper は 検証・修正: agent-retrospective の production Agent invocation adapter を実 Claude CLI で確認する #2301 ですでに存在し、実際の Claude CLI を呼ぶ処理も既に持っています。test -x では Claude を一度も起動しないので、AC3 の「実 claude CLI 経由で抽出されること」を証明できません。
      ここは既存 wrapper をそのまま使えばよく、新しい harness は不要です。さらに live 挙動は baseline でも upstream 側の状態次第で PASS し得るため、repo が既に正式サポートしている baseline-expect: deferred が適切です。deferred は baseline 実行を延期する正式な VC grammar です。

    3. P1 — AC3 が「compatibility recovery が使われたこと」まで証明するよう読めるのは過剰です。
      既存 test_real_claude_cli_analytical_prompt_structured_output_shape は、実 CLI が最初から正常な structured_output を返した場合も PASS します。つまり live test の成功だけでは _structured_output_from_result_compat() が実際に走ったかは分かりません。
      ここを証明するために raw-wrapper instrumentation、receipt、別 harness を追加する価値はありません。hermetic test が recovery branch を直接証明し、live test は「実環境で missing_structured_output にならない」ことだけを証明する、という役割分担が最も軽量です。これは PR fix: agent-retrospective の observer wave 失敗を診断可能にし regression coverage gap を解消する #2342 の OWNER review で採った「Claude credential を CI に持ち込まず、手動 live smoke を信頼できるものにする」という方針とも整合します。

    4. P1 — 「anchor を外して re.search」だけだと、複数 fence に対する greedy match が新しい defect になります。
      現在の正規表現は (.*) + DOTALL です。単純に ^ / $ を取り除いて search() すると、複数 fence がある場合に「最初の opening fence から最後の closing fence」まで飲み込む可能性があります。
      また「最初の fence を採用」だけでも、モデルが説明用 JSON example → 最終 JSON の順で返した場合に誤った object を採用できます。高品質化するなら、fence を non-greedy に列挙し、各 candidate を既存 JSON Schema で検証し、schema-valid candidate が一意な場合だけ受理するのがよいです。これは数十行の Markdown parser を入れる話ではなく、小さな adapter fix で済みます。

    5. P1 — regression fixture は Issue 本文に書かれた「実測2形状」をそのまま固定すべきです。
      Issue 自身が starts_with_fence=true / ends_with_fence=false と starts_with_fence=false / ends_with_fence=false の2形状を観測したとしています。
      したがって少なくとも「fence + trailing prose」「leading prose + fence + trailing prose」の2ケースを parameterize するべきです。加えて「prose 内の fenced object が schema 不適合なら従来どおり missing_structured_output」を1件入れれば十分です。既存 suite はすでに non-success subtype、wrong-type structured_output、dict 優先、schema validation failure を網羅しているので、それらを再実装する必要はありません。

    6. P2 — 実装: agent-retrospective の structured output compatibility recovery が fence 前後の地の文で decode failure する missing_structured_output を解消する #2348 を直しても agent-retrospective 全体が安定した、とは扱わない方がよいです。
      実装: agent-retrospective canonical run が retrospective-runtime-observer の missing_structured_output で fail-closed する回帰を解消する #2341/fix: agent-retrospective の observer wave 失敗を診断可能にし regression coverage gap を解消する #2342 で診断可能性を上げた結果、空 prompt の別 defect が発見されました。 それは 実装: claude -p の空文字列 prompt 拒否 regression に対する agent-retrospective live smoke 検知経路の修正 #2345/fix: agent-retrospective live smoke の空 prompt 拒否 regression を解消 (#2345) #2347 の別 lane です。さらに現在は run_id を caller が prompt 作成前に知れない構造的 gap が 実装: agent-retrospective run_retrospective.py に run_id 事前指定機構を追加し非空 prompt での observer_run_id_mismatch 構造的発生を解消する #2350 として独立しており、実装: agent-retrospective run_retrospective.py に run_id 事前指定機構を追加し非空 prompt での observer_run_id_mismatch 構造的発生を解消する #2350 自身も 実装: agent-retrospective の structured output compatibility recovery が fence 前後の地の文で decode failure する missing_structured_output を解消する #2348 を明示的に別問題としています。
      optional plugin distribution の 実装: agent-retrospective を optional plugin distribution として配布可能にする #2240 も「project Skill の production invocation が安定してから」という前提です。 したがって 実装: agent-retrospective の structured output compatibility recovery が fence 前後の地の文で decode failure する missing_structured_output を解消する #2348 は重要な一段ですが、「plugin 化を unblock」「retrospective 完走を保証」といった広い completion claim は避けるべきです。

    推奨する実装形

    result 全体が raw JSON ならまず従来どおり直接 parse。その失敗時だけ fenced block を探します。正規表現は、全体 anchor ではなく各 fence の行境界だけを anchorし、body を non-greedy にします。

    _MARKDOWN_JSON_FENCE_RE = re.compile(
        r"^```(?:json)?[ \t]*\r?\n(?P<body>.*?)\r?\n```[ \t]*$",
        re.MULTILINE | re.DOTALL | re.IGNORECASE,
    )

    処理は概念的に、

    1. result.strip() を直接 JSON decode + schema validate
       -> valid dict なら即 return
    
    2. result 内の fenced block を finditer()
    
    3. 各 body を
       json.loads
       -> dict 判定
       -> 既存 jsonschema.validate
       の順で検証
    
    4. schema-valid candidate が exactly 1 件
       -> return candidate
    
    5. 0件または複数件
       -> None
       -> 既存 missing_structured_output
    

    で十分です。

    ここで重要なのは、JSON Schema validation を最後の authority として残すことです。公式 Agent SDK も structured output の利用側で runtime validation を行う例を示しています。([Claude Platform]2) 現在の subtype == success gate、structured_output が absent/None のときだけ compat recovery、present-but-wrong-type は拒否、という #2324 由来の境界も変更不要です。

    逆に json-repair、balanced-brace heuristic、任意 prose から {...} を探索する parser、Markdown AST、新しい safety harness は不要です。そこまでやると「互換回収」が model output repair subsystem に膨張します。

    Issue #2348 の VC はこう直すのが適切です

    # AC1, AC2
    # baseline-expect: fail
    $ uv run --locked pytest .claude/skills/agent-retrospective/scripts/tests/test_run_retrospective.py -q -k "prose_fence"
    
    # AC3
    # baseline-expect: deferred
    # preflight-scope: runtime_only
    $ .claude/skills/agent-retrospective/scripts/tests/verify_run_retrospective_live_cli.sh --select test_real_claude_cli_analytical_prompt_structured_output_shape
    
    # AC4
    $ uv run --locked pytest .claude/skills/agent-retrospective/scripts/tests/test_run_retrospective.py

    AC3 の文言も「compat recovery が使用されたこと」ではなく、**「実 CLI の substantive analytical prompt が status=ok かつ schema-valid structured output を返し、missing_structured_output で終了しない」**程度に縮めるのが適切です。

    最終評価

    Issue の問題設定・root cause・Allowed Paths・Out of Scope は概ね良いです。実装規模も適切です。 upstream でも success + structured_output absent + JSON in result/fence という同型事象が確認されているため、局所的な compatibility workaround には十分な実用上の根拠があります。([GitHub]3)

    一方、現在のまま実装へ渡すのは非推奨です。まず P0 の VC 2件を修正し、実装方針を「単純な nonanchored greedy search」から「非 greedy fence 列挙 + 一意な schema-valid candidate のみ受理」へ明確化してください。それ以外の harness・security machinery は増やさない方が、このリポジトリの個人開発用途には合っています。

  2. squne121 commented on Aug 25, 2026

    @squne121
    OwnerAuthor

    issue-refinement-loop: approved

    anchor comment(#issuecomment-5416395324、REQUEST_CHANGES)の指摘を反映して本文を全面改訂した。

    反映した主な指摘

    追加で、独立検証中に発見した以下の repo 固有の contract 不整合も合わせて修正した(reviewer コメント外の追加修正):

    • Runtime Verification Applicability セクションが箇条書き(- field: value)形式のため RVA001/EXTSURF001 チェッカーの正規表現(^\s*field\s*:、先頭 - 非対応)に非マッチで needs_fix になっていた → 箇条書きを外した field: value 形式に修正。
    • decision: immediate なのに AC に <!-- runtime-verification: true --> タグがなく C11_decision_tag_consistency が fail していた → AC3 にタグを付与。
    • VC の # AC1, AC2 グループ markers は vc_contract_syntax.py は許容するが create-issue/scripts/validate_issue_body.py の LP016 チェックはグループ形式非対応で fail していた → # AC1 / # AC2 の個別 bare marker 2行スタックに変更。

    検証結果(このループ内で独立に実行・確認)

    • codebase-investigator(read-only): _structured_output_from_result_compat の存在・行番号、_MARKDOWN_JSON_FENCE_RE の anchor 仕様、verify_run_retrospective_live_cli.sh の --select 実装、live test 名の存在、prose_fence テストが現状 0 件であることを独立確認。reviewer コメントの事実主張はすべて確認された。
    • web-researcher: Agent SDK 公式ドキュメントが subtype: success でも structured_output が absent なケースを認めていること(--agent 固有の言及は確認できず)、および upstream 公開 Issue outputFormat returns subtype 'success' when structured_output is absent — should return error_max_structured_output_retries anthropics/claude-agent-sdk-typescript#277 が同型症状を報告していることを確認。
    • contract_readiness_check.py --mode preflight-static: status: go
    • baseline_vc_preflight.py --strict: status: pass(AC1/AC2 束縛コマンド → expected_fail/go、AC3 → skipped/preflight-scope runtime_only、AC4 → expected_pass、135 tests green)
    • check_issue_contract.py(C1〜C13): verdict: approve、status: ok、blocking_issues なし
    • run_root_review_pipeline.py produce → classify-child-stdout: classification: ok、VERDICT: approve
    • run_contract_review_once.py --mode execute: CONTRACT_REVIEW_RESULT_V1.status: go(Final Gate 確認済み)

    Final Gate: passed(CONTRACT_REVIEW_RESULT_V1.status: go を実際に検証した通常経路)

    LOOP_HANDOFF_RESULT_V1:
      status: impl_ready
      routing_action: run_impl_review_loop
      contract_review:
        status: go
        gate_result: fresh_go
        latest_comment_url: null
        generated_at: "2026-08-25T20:53:06Z"
        body_sha256: "sha256:c83c3195f4eb9bba7f1ccde9de6115144684f6be129143b253da1717d9e88f0c"
      metadata:
        title_prefix_ready: true
      label_sync_observation:
        kind: presentation_sync
        result: noop
        detail: "no label mutation performed by this loop"
      auto_fixes:
        result: auto_fixed
        required:
          - kind: known_marker_fix
            executor: implementation-worker
            result: applied
            evidence:
              before: "Runtime Verification Applicability section used bulleted '- field: value' form; missing <!-- runtime-verification: true --> tag; VC used non-canonical grouped AC marker and existing-file new-node-id shape"
              after: "Unbulleted 'field: value' RVA form; runtime-verification tag added on AC3; VC rebound to a not-yet-created regression test file with stacked bare AC markers"
              comment_url: null
        skipped: []
      blockers: []
      permissions:
        unavailable: []
      generated_at: "2026-08-25T20:53:55Z"
      checked_body_sha256: "sha256:c83c3195f4eb9bba7f1ccde9de6115144684f6be129143b253da1717d9e88f0c"
      checker_exit_code: 0
      missing_sections: []
      missing_contract_keys: []
  3. squne121 commented on Aug 25, 2026

    @squne121
    OwnerAuthor

    root-owned entry router audit

    route: invoke_impl_review_loop
    reason: fresh_review_go_live_equality

  4. self-assigned this
    on Aug 25, 2026
  5. squne121 commented on Aug 25, 2026

    @squne121
    OwnerAuthor

    implement-issue: 実装完了 (2026-08-25T22:38:26Z)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions