Skip to content

fix: fence 前後の地の文でも structured_output を抽出できるようにする - #2353

Merged
squne121 merged 3 commits into
mainfrom
worktree-issue-2348-fence-prose-decode
Aug 26, 2026
Merged

squne121 merged 3 commits into
mainfrom
worktree-issue-2348-fence-prose-decode

Conversation

@squne121

Copy link
Copy Markdown
Owner

Summary

  • _structured_output_from_result_compat()(run_retrospective.py)の fence 抽出が result テキスト全体への厳格な ^...$ anchor 一致を要求していたため、fenced JSON block の前後に地の文を伴う実際の --agent 応答で decode failure し reason_code=missing_structured_output に不必要に fail-closed していた問題を解消する(Issue 実装: agent-retrospective の structured output compatibility recovery が fence 前後の地の文で decode failure する missing_structured_output を解消する #2348)。
  • result 内の fenced code block を non-greedy に列挙し、各候補を独立に json.loads + 対象 JSON Schema で厳密検証し、schema-valid な候補が一意に定まる場合にのみ採用する方式に変更した。schema validation は一切緩めていない(malformed / partial output は引き続き fail-closed)。
  • 新規リグレッションテストファイル test_run_retrospective_structured_output_prose_fence.py を追加し、実測 shape 1/2(fence 直後に地の文 / fence 前後に地の文)の recovery、schema 不適合 fence のネガティブケース、複数 schema-valid 候補の曖昧性拒否(fail-closed)を検証する。

Checks

Schema Change Applicability

  • decision: not_schema_change
  • reason: observer_result_v1.schema.json を含む producer-consumer 境界の machine-readable contract 自体は変更していない。変更対象は run_retrospective.py 内部の result テキストから既存スキーマへ照合する compat recovery の抽出ロジックのみで、schema の形状・フィールド・型定義は不変。

Schema Consumer Inventory

N/A(not_schema_change のため)。

Compatibility Decision(互換性判定)

  • change_type: N/A
  • compatibility: N/A
  • migration_required: N/A
  • migration_or_followup: N/A
  • reason: schema 自体の変更なし。

Safety Claim Matrix

Issue #2348 の AC3 は docs/dev/runtime-verification-policy.md の decision: immediate に該当し、実 claude CLI 経由の runtime verification を伴うため本セクションを記載する。

Claim Implemented? Not controlled Evidence Follow-up
fence-anchor 緩和後も schema validation の fail-closed は維持され、malformed / partial output を成功として扱わない yes test_prose_fence_schema_invalid_fence_stays_missing_structured_output PASS(uv run --locked pytest .claude/skills/agent-retrospective/scripts/tests/test_run_retrospective_structured_output_prose_fence.py -q 4 passed) N/A
non-greedy fence 列挙により複数候補が曖昧な場合は fail-closed(推測で片方を採用しない) yes test_prose_fence_multiple_schema_valid_candidates_ambiguous_rejected PASS(同上ファイル) N/A
実 claude CLI 経由で retrospective-runtime-observer を非空・実質的な分析 prompt で呼び出した際に reason_code=missing_structured_output とならず structured_output が抽出される(AC3) yes verify_run_retrospective_live_cli.sh --select test_real_claude_cli_analytical_prompt_structured_output_shape → 1 passed。sanitized bounded classification: adapter_status=ok adapter_reason_code=None child_exit_code=0 N/A
既存 hermetic suite(test_run_retrospective.py)に回帰なし(AC4) yes uv run --locked pytest .claude/skills/agent-retrospective/scripts/tests/test_run_retrospective.py → 135 passed N/A

Visual Impact Declaration(視覚影響申告)

N/A(UI / DOM / CSS 変更なし)。

検証コマンド結果

  • AC1/AC2: uv run --locked pytest .claude/skills/agent-retrospective/scripts/tests/test_run_retrospective_structured_output_prose_fence.py -q → 修正前(fix を git stash で一時退避し baseline 検証): 2 failed, 2 passed(shape1/shape2 が期待どおり fail)。修正適用後: 4 passed。
  • AC3: .claude/skills/agent-retrospective/scripts/tests/verify_run_retrospective_live_cli.sh --select test_real_claude_cli_analytical_prompt_structured_output_shape → PASS: live CLI verification succeeded(claude CLI 2.1.245、claude auth status ログイン済み環境)。sanitized bounded classification: adapter_status=ok adapter_reason_code=None child_exit_code=0(missing_structured_output は発生せず)。
  • AC4: uv run --locked pytest .claude/skills/agent-retrospective/scripts/tests/test_run_retrospective.py → 135 passed(既存 hermetic suite に無回帰)。
  • 追加: uv run pytest .claude/skills/gemini-cli-headless-delegation/tests/test_model_routing.py → 24 passed(project constitution の標準チェック)。

Notes

`_structured_output_from_result_compat()` の fence 抽出が `result` テキスト
全体に対する厳格な `^...$` anchor 一致を要求していたため、実際の `--agent`
呼び出し応答(fenced JSON block の前後に地の文を伴う shape)で decode
failure し `missing_structured_output` に fail-closed していた。

`result` 内の fenced code block を non-greedy に列挙し、各候補を
`json.loads` した上で対象 JSON Schema に対して独立に厳密検証し、
schema-valid な候補が一意に定まる場合にのみ採用するよう修正した。候補が
0件、または schema-valid な候補が複数(曖昧)の場合は従来どおり `None`
(missing_structured_output 扱い)を返す。fence が全く無い `result`
テキストは従来どおり全体を単一候補として扱う(後方互換)。

新規リグレッションテスト
`test_run_retrospective_structured_output_prose_fence.py` を追加し、
実測 shape 1/2(fence+trailing prose / leading+trailing prose)の
recovery、schema 不適合 fence のネガティブケース、複数 schema-valid
候補の曖昧性拒否を検証する。既存 hermetic suite
(test_run_retrospective.py, 135 tests)は無回帰で PASS。

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

github-actions Bot commented Aug 25, 2026 •

Copy link
Copy Markdown
Contributor

Preview URL

Preview removed (PR #2353 closed).

@squne121

Copy link
Copy Markdown
Owner Author

PR Review Verdict (impl-review-loop, iteration 1)

確認内容(独立再検証、live head a5431e2c280bc42c6bc621200e6743d86f9d8526)

  • Linked Issue 実装: agent-retrospective の structured output compatibility recovery が fence 前後の地の文で decode failure する missing_structured_output を解消する #2348 の Machine-Readable Contract / AC / Allowed Paths / Verification Commands を live 本文から取得し照合。
  • Diff は run_retrospective.py と新規 test_run_retrospective_structured_output_prose_fence.py の2件のみ(Allowed Paths gate: status: ok, violations なし)。
  • AC1/AC2: test_run_retrospective_structured_output_prose_fence.py -q → 4 passed。base(origin/main 時点コード)に一時差し替えて再実行し 2 failed, 2 passed を確認(regression test が実際に fix に依存する load-bearing なものであることを確認)。
  • AC3(runtime-verification: immediate): 実 claude CLI(2.1.246、認証確認済み)で verify_run_retrospective_live_cli.sh --select test_real_claude_cli_analytical_prompt_structured_output_shape を独立実行 → PASS。
  • AC4: test_run_retrospective.py → 135 passed、無回帰。
  • CI 必須チェック: typecheck/lint/test/build/validate-generated-artifact/python-test 全 SUCCESS(wait_ci_checks.py --required で確認)。
  • Schema Change Applicability: not_schema_change(スキーマファイル変更なし、抽出ロジックのみ)。
  • Safety Claim Matrix: fail-closed 維持・ambiguous 拒否・live CLI 経由の抽出確認の3claimがevidence付きで記載。
  • Stop Conditions: non-greedy fence 抽出、schema validation 緩和なし、複数候補時 fail-closed を確認。

Non-blocking warning

  • PR本文に procedure が言及する見出し「## 受け入れ条件の達成状況」は無いが、検証コマンド結果 + Safety Claim Matrix で全AC(AC1-AC4)が証跡付きでカバーされている(直近merge済みPR5件も同見出し不使用の precedent と整合、blocker としない)。
verdict: APPROVE
reviewed_head_sha: "a5431e2c280bc42c6bc621200e6743d86f9d8526"
blockers: []
warnings:
  - "PR本文に「## 受け入れ条件の達成状況」見出しは無いが、検証コマンド結果 + Safety Claim Matrixで全AC(AC1-AC4)が証跡付きでカバーされている(直近merge済みPR5件も同見出し不使用のprecedentと整合、blockerとしない)"

@squne121

Copy link
Copy Markdown
Owner Author

結論

判定: REQUEST_CHANGES です。

修正方向は正しく、compatibility recovery を残す判断にも実用上の根拠があります。Claude Code の現行ドキュメントは --output-format json --json-schema の結果を structured_output に返す契約を示していますが、Anthropic 側の公開 Issue #277 では、subtype: "success" なのに structured_output が欠落し、正しい JSON が result 内の Markdown fence に残る事象が現在も open です。([Claude]1)

PR #2353 はその実害を局所的に救う小さな adapter fix であり、CI も全緑、既存 impl-review-loop も APPROVE しています。 ただし、新しい fence 列挙正規表現に実運用で起こり得る false negative が残っています。 マージ前にここだけ直す価値があります。

Findings

  1. P1 / Blocker — JSON fence より前に別言語の fenced block があると、closing fence を opener と誤認し、本命 JSON を見失います。

    現在の実装は次です。

    _FENCED_JSON_BLOCK_RE = re.compile(
        r"```(?:json)?\s*\n(.*?)\n```",
        re.DOTALL,
    )

    つまり認識する opener は ```json または bare ``` だけです。一方、 ```text や ```python の block 自体は opener として消費しません。

    そのため、例えばモデルがこう返した場合、

    Analysis:
    ```text
    foo
    

    Final:

    {"a":"x"}
    
    regex は ` ```text` を無視したあと、その **closing ` ``` ` を新しい bare opener と解釈**します。そして次の ` ```json` を closing fence として消費し、candidate は `"Final:"` になります。本命 `{"a":"x"}` は `finditer()` の候補に一度も現れません。
    
    同様に、
    
    ```text
    ```python
    print("x")
    
    {"a":"x"}
    
    でも本命 JSON が standalone candidate にならず `json.loads()` が失敗します。
    
    これは Markdown の細かい規格適合性の話ではありません。**「分析の途中でコード例を出し、最後に JSON を出す」という LLM の自然な応答が再び `missing_structured_output` になる production defect** です。今回追加された4テストは「prose + JSON fence」しか扱わず、「foreign-language fence + JSON fence」を検証していないため全緑でも捕捉できません。PR の現在のテスト戦略自体は Issue #2348 の AC を満たしていますが、この穴は AC より実利用を優先すると塞ぐべきです。
    
    最小修正は、Markdown parser ライブラリを追加することではありません。**全 backtick fenced block を opener の info string を問わず順番に消費し、その後 `info == ""` または `json` の block だけ JSON candidate にする**程度の小さな scanner で十分です。GFM でも fence には任意の info string が存在するのが正規仕様です。:contentReference[oaicite:5]{index=5}
    
    
  2. P2 — 現 regex は小さな表記揺れにも弱く、互換回収としてはもう一段だけ緩くしてよいです。

    ```JSON は認識されず、closing fence の手前に1〜3スペースの indent がある fenced blockも認識されません。GFM では opening/closing fence は最大3スペースまで indent 可能で、info string も一般的な構造です。([GitHub Pages]2)

    ただし、ここで「完全な GFM parser にしろ」とは勧めません。Anthropic の公開 実装: gemini-cli-headless-delegation failure_class taxonomy を result JSON に追加し retry policy を実装する #277 の実例自体が Here is the JSON: ```json ... のような、厳密な block Markdown から外れ得る出力形を報告しています。

    したがって個人開発用途なら、IGNORECASE と軽い indent 対応を加えつつ、実測 Claude 出力を拾う compatibility adapter と割り切るのが適切です。

  3. P2 / workflow-oriented — 同一の schema-valid JSON が2回出ただけでも fail-closed するのは、少し厳しすぎます。

    現実装は candidate の出現数が1であることを要求しています。したがってモデルが最終 JSON を説明中に一度示し、最後にまったく同じ JSON をもう一度出すと len(schema_valid_candidates) == 2 になって拒否します。

    Issue 実装: agent-retrospective の structured output compatibility recovery が fence 前後の地の文で decode failure する missing_structured_output を解消する #2348 の契約上は「複数 schema-valid candidate は ambiguous として拒否」なので、これは PR の契約違反ではありません。

    ただ、今回の「ワークフローを妨げない」優先順位なら、candidate occurrence が1件ではなく、distinct schema-valid value が1種類なら採用の方が使いやすいです。異なる2 object なら従来どおり拒否、完全一致なら成功でよいでしょう。追加ハーネスは不要です。

良い点

subtype != "success" を先に拒否し、compat recovery は structured_output が absent / None の場合だけ行い、present-but-wrong-type を救済しないという #2324 の境界を #2353 は維持しています。これは適切です。

また、回収した candidate を元の JSON Schema に再度通す設計も正しいです。Claude の構造化出力は本来スキーマ準拠 JSON を得るための機能なので、抽出だけ緩め、意味上の acceptance criterion は schema validation に残すのが妥当です。([Claude Platform]3)

CI は required な typecheck / lint / test / build / python-test / validate-generated-artifact を含め成功しており、現在の main も PR の base SHA c8a68a... のままなので、レビュー中の base drift もありません。

マージ前に求める変更

私は P1 の1件だけを必須にします。foreign-language fenced block → final JSON fence を再現する regression test を1件追加し、fence extractor が「対象外 block の closing fence」を opener として再利用しないよう直すべきです。

uppercase JSON、indent、同一 candidate の dedupe はその修正時に低コストなら一緒に入れる程度でよく、別の security framework、Markdown AST dependency、json-repair、Claude credential を使う追加 CI、巨大な live harness は不要です。前回 Issue レビューで採った軽量方針とも整合します。

なお、#2353 が直っても agent-retrospective 全体の完走保証にはなりません。run_id を caller が prompt 作成前に確定できない observer_run_id_mismatch は #2350 としてまだ独立して open です。

最終判定は REQUEST_CHANGES (1 blocker)。 Blocker 修正後は、現在のスコープのまま APPROVE でよいと見ます。

…2348)

OWNER P1 REQUEST_CHANGES fix_delta on PR #2353
(#2353 (comment)).

`_FENCED_JSON_BLOCK_RE` matched only ```json / bare ``` *opener* fences.
A foreign-language fenced block (e.g. ```text) appearing before the real
```json block had its own *closing* fence misread by `finditer()` as a new
bare *opening* fence, corrupting subsequent pairing so the real JSON
block's closing fence -- and thus the real JSON candidate itself -- never
appeared in the results. This reproduced `missing_structured_output` for
the common "prose with a text/code example, then the final JSON answer"
LLM response shape.

Replace the opener-only regex with a delimiter-line scanner
(`_FENCE_DELIMITER_RE`) that finds ALL fence delimiter lines in encounter
order and pairs them sequentially (opener, closer), filtering to pairs
whose opener info string is "" or "json" (case-insensitive). Non-JSON
fences are still correctly paired and skipped, not misread as new fence
boundaries.

Add regression test
test_prose_fence_foreign_language_fence_before_json_fence_recovered,
confirmed to FAIL against the pre-fix code (malformed_output /
missing_structured_output) and PASS after the fix.

Incidentally satisfies two optional review suggestions for free:
case-insensitive JSON info string, and closing-fence indent tolerance
(up to 3 spaces, GFM-compliant). Distinct-value dedup for duplicate
schema-valid candidates was explicitly NOT implemented, per review
guidance to keep this fix_delta minimal.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
@squne121

Copy link
Copy Markdown
Owner Author

fix_delta: OWNER P1 fence-pairing blocker resolved

Fix_delta for the P1 REQUEST_CHANGES blocker raised in
#2353 (comment).

変更内容 (what changed)

.claude/skills/agent-retrospective/scripts/run_retrospective.py:
_FENCED_JSON_BLOCK_RE(opener限定の正規表現)を _FENCE_DELIMITER_RE を
用いたdelimiter-lineスキャナに置き換えた。全てのbacktick fence delimiter
行を出現順に検出し、順次 (opener, closer) としてペアリング、opener の
info stringが "" または大文字小文字を無視した "json" の場合のみ
JSON候補として扱う。

根本原因 (root cause)

旧実装は ```json / bare ``` の opener のみを直接1つの正規表現で
マッチしていたため、```text のような別言語のfenceブロックが実際の
```json ブロックより前にあると、その別言語ブロックの closing fence
が finditer() によって新しい bare opening fence と誤認識され、ペアリング
が崩壊。結果として実際のJSONブロックのclosing fence(ひいてはJSON候補自体)
が結果集合から消え、missing_structured_output fail-closedを引き起こして
いた(「テキスト/コード例付きの説明文の後に最終JSON回答」という一般的な
LLM応答形状で発生)。

テスト結果 (test results)

新規回帰テスト test_prose_fence_foreign_language_fence_before_json_fence_recovered
を .claude/skills/agent-retrospective/scripts/tests/test_run_retrospective_structured_output_prose_fence.py
に追加。

  • 修正前 (unfixed code): FAILED — AssertionError: assert 'malformed_output' == 'ok'(バグを正しく再現)
  • 修正後 (fixed code): PASSED

フルテストファイル(既存4件+新規1件): 5 passed
広範な hermetic suite test_run_retrospective.py: 135 passed

追加検証 (project-wide required verification)

  • pnpm typecheck: PASS
  • pnpm lint: PASS
  • pnpm test: PASS(112 test files / 1876 tests)
  • pnpm build: PASS
  • uv run pytest .claude/skills/gemini-cli-headless-delegation/tests/test_model_routing.py: PASS(24 tests)

スコープメモ (scope notes)

レビューコメントのOPTIONAL項目のうち以下2件は今回の修正で副次的に満たした:

  • JSON info stringの大文字小文字非依存(```JSON も受理、.lower() 比較)
  • closing fenceの最大3スペースインデント許容(GFM準拠、opener/closerで同一正規表現使用)

以下のOPTIONAL項目は意図的に未実装:

  • schema-validな重複候補のdistinct-value dedup(現状の occurrence-count dedup を維持)
    — レビュー指示に従いスコープを最小限に保つため。_structured_output_from_result_compat
    の len(schema_valid_candidates) != 1 => reject ロジックは変更なし。

Markdown ASTライブラリ・json-repair・新規CIハーネスの追加は行っていない(scope外)。

コミット / push

  • commit: a45b2c196c593a342b0d5d234b29b2e9e25c1b16
  • branch: worktree-issue-2348-fence-prose-decode(force-pushなし、fast-forward)
  • PR head: 更新済み、mergeable: MERGEABLE

@squne121

Copy link
Copy Markdown
Owner Author

LOOP_VERDICT (impl-review-loop, iteration 2)

verdict: APPROVE
reviewed_head_sha: "a45b2c196c593a342b0d5d234b29b2e9e25c1b16"
blockers: []
warnings:
  - "PR本文(Safety Claim Matrix/検証コマンド結果)がfix_delta前の状態のまま(AC1/AC2を「4 passed」と記載、実際は5 passed)。AC3のPR本文evidenceもiteration-1 head時点のもの。ただしiteration-1→fix_delta間の差分はフェンス抽出アルゴリズムのみに限定されており、単一fenceケースの挙動は変更前後で同一であることをdiffトレースで確認済みのためblockerとしない。"

確認内容(独立再検証、live head a45b2c19)

  • Allowed Paths gate: status: ok, violations なし(変更2ファイルとも Issue 実装: agent-retrospective の structured output compatibility recovery が fence 前後の地の文で decode failure する missing_structured_output を解消する #2348 の Allowed Paths 内)
  • OWNER 指摘の P1 blocker(foreign-language fence → JSON fence 誤認識)を修正: フェンス列挙アルゴリズムを opener-only regex から「全 fence delimiter を出現順にペアリングし、info string が ""/"json" の pair のみ JSON 候補として採用」する方式に変更。OWNER 指摘の2具体例(text fence 直後に json fence/python fence 直後に json fence)を手トレースで検証
  • 新規 regression test test_prose_fence_foreign_language_fence_before_json_fence_recovered を独立実行し PASS。fix 前コードに一時差し替えて同テストが FAIL することも確認(load-bearing であることを実測確認)
  • AC1/AC2: 5 passed(既存4件+新規1件)。AC4: 既存135件、無回帰
  • CI 必須チェック全 SUCCESS(head一致確認済み)

mergeStateStatus: CLEAN / mergeable: MERGEABLE — impl-review-loop 終了条件を満たすため、本ループはここで完了とします(draft_pr_ready)。人間のマージ判断をお願いします。

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

Labels

None yet

Projects

None yet

1 participant