Skip to content

実装: local_asset_research route の live Serena MCP 応答待ちタイムアウトの信頼性を改善する #2015

Closed

Description

@squne121

Machine-Readable Contract

contract_schema_version: v1
issue_kind: implementation
parent_issue: "none"
goal_ref: "local_asset_research route (Claude Code / Codex CLI / Antigravity CLI native) の live Serena MCP 起動・応答待ちを、正しく特定された stage/tool 単位の failure classification と自己誘発 stall 排除のもとで安定させ、AGY-native MCP discovery と full route の genuine live PASS を固定 trial plan で証明する"
change_kind: code-and-test

Parent Issue

なし(単独改善)

Parent Goal Ref

該当なし(parent Issue を持たない単独改善)。起票元は #1886 の human-escalation resolution:「AC6 の未達は PR #2005 のコード欠陥ではなく acceptance を完了するための runtime prerequisite / reliability gap として分離する」。

Current Validated Scope

  • .claude/skills/gemini-cli-headless-delegation/scripts/run_gemini_headless.py の _collect_live_serena_read_only_evidence()(L2000-2141)および呼び出し元 except Exception as exc: ブロック(L5065-5111)に閉じる。
  • .claude/skills/gemini-cli-headless-delegation/tests/test_agy_provider.py は _collect_live_serena_read_only_evidence() を patch.object でモックしており(L502 付近)、transport-level failure(stderr backpressure・process cleanup・failure classification 分岐)を検証していない。本 Issue はこのファイルにも hermetic な transport-level test を追加する。
  • Serena package の pinning は既に references/serena-tool-manifest.json の pinned_ref(commit 3c241bab0d07d8adba8ef4f6c49676c954559dee)で実施済みであることを確認済み。本 Issue で新規にpinning機構を追加する必要はない(pinned_ref の更新是非は 調査: serena CLI コマンド形式の moving target リスクへの対策方針を決定する (PR #49 follow-up) #54 の関心事)。
  • 2026-08-09 OWNER directive による scope reframe: PR 実装: local_asset_research route の live Serena MCP 応答待ちタイムアウトの信頼性を改善する #2044 head 8a5b2f68 時点で AC8 full-route trial が 2/6 のみ genuine PASS(4件は run_agent_provider_route_smoke.py / run_worktree_agent_runtime_smoke.py(旧 Allowed Paths 外)の async child spawn/completion semantics の欠陥に起因)だったことを受け、OWNER が対話プロンプトで明示的に scope を拡張した。旧 Stop Condition「Serena MCP 以外の原因による AC8 failure は停止」を解除し、full-route harness・AGY-native MCP discovery・Serena install/cache 戦略・関連 CI/test contract を本 Issue・本 PR のスコープ内に統合する(別 Issue・別 PR への切り出しを禁止)。詳細は本文末尾の「OWNER Scope Reframe(2026-08-09)」節および PR 実装: local_asset_research route の live Serena MCP 応答待ちタイムアウトの信頼性を改善する #2044 のコメントを参照。

Remaining Parent Gaps

Background

Issue #1886 の impl-review-loop iteration 3 で、PR #2005 の AC6 のうち codex_cli / codebase-investigator / local_asset_research route を live 実行したところ live_serena_mcp_failed: timed out waiting for Serena MCP response id 4 で fail した。OWNER はこれを PR #2005 のコード欠陥ではなく runtime prerequisite / reliability gap と判定し、別 Issue として分離することを決定した。

本 Issue の contract は敵対的レビュー(OWNER, REQUEST_CHANGES)を複数回受けて改訂されてきた。P0-1〜P1-3(id マッピング・stderr pipe deadlock・CLI 引数・failure class 粒度・timeout 階層・process-tree cleanup)は control-plane が現行コードを直接読み事実確認済みで、iteration 1-2 で対応した。

PR #2044 は一度 bot pr-reviewer の APPROVE により draft_pr_ready に到達したが、OWNER が PR #2044 へ非常に詳細なコード行レベルの技術的 REQUEST_CHANGES(P1: AC8 full-route test が producer の exit code のみで PASS 判定・cleanup が process group の grandchild を回収しない・server_tool_timeout が実際には Serena 起動 command に渡っていない・retry が route-level deadline を破り初回証跡を破棄する)を投稿し、bot APPROVE を明示的に撤回した。iteration 3 でこのうち3件を修正・独立検証済みだが、AC8 full-route test の意味論的欠陥を修正した結果、genuine live 実行で collector-only は 12/12 PASS(Serena MCP 自体は安定)である一方、full-route は 2/6 のみ PASS(4件は本 Issue が変更していない run_agent_provider_route_smoke.py / run_worktree_agent_runtime_smoke.py の async child spawn/completion 欠陥起因)と判明し、旧 Stop Condition に基づき一度 human escalation した。

これを受けて OWNER は 2026-08-09、対話プロンプトで本 Issue のスコープを明示的に拡張した(詳細は「OWNER Scope Reframe(2026-08-09)」節)。

Outcome

run_gemini_headless.py の _collect_live_serena_read_only_evidence() とその呼び出し元、および local_asset_research route の full-route 実行経路(async child spawn/completion semantics を含む)が、Serena MCP の startup・protocol negotiation・tool execution・manifest validation・cleanup を段階別に観測し、stderr backpressure による自己誘発 stall を起こさず、monotonic な session deadline 内で終了する状態になる。

Antigravity CLI(AGY)自身が workspace の .agents/mcp_config.json から Serena MCP を native に discovery・接続・invoke できることが、モデルの自己申告ではなく MCP tool event / server log で証明される。

Serena は user-local に exact-pinned で persistent install され、cold/warm/offline のいずれでも安定して起動する。

固定済み trial plan に基づき、collector 単体(12/12)・AGY-native probe(3/3)・full route(Claude Code / Codex CLI、6/6 + no-change repeat 6/6)が genuine live PASS することが本 Issue の PR マージ前に確認され、証跡として記録される。

In Scope

  • _collect_live_serena_read_only_evidence() の各 JSON-RPC request を machine-readable な request ledger として記録する(local_asset_retrieval_metadata 配下)。
  • Serena subprocess の stderr を専用 thread で継続的に drain し、bounded ring buffer へ保存する。stdout と stderr を merge しない。
  • search_for_pattern の探索範囲を context file が属するディレクトリ等に限定し、repo-wide search を避ける。
  • stage 別 failure class を references/failure-class-taxonomy.md に追加し、retryable 判定を明記する。
  • transient failure class(timeout 系)に対してのみ、route 単位の単一 absolute monotonic deadline を共有する bounded single retry を実装する(初回証跡を破棄しない)。
  • cleanup を start_new_session=True による process group 単位の管理へ堅牢化し、grandchild process の残存を防ぐ(primary failure がない cleanup 失敗は fail-close、primary failure がある場合は cleanup_failure を secondary failure として記録)。
  • SERENA_SERVER_TOOL_TIMEOUT_SEC を実際に Serena 起動 command(--tool-timeout)へ配線する。
  • (2026-08-09 追加) full-route test(test_ac8_local_asset_research_full_route_fixed_live_trial_plan)を、producer exit code のみでなく canonical validator(scripts/agent-ops/validate_agent_provider_route_smoke.py)と route artifact の status/failure_class/retrieval_status/retrieval_mode/evidence_record_count/head_sha を直接 assert する実装に修正する。
  • (2026-08-09 追加) scripts/agent-ops/run_agent_provider_route_smoke.py および scripts/agent-ops/run_worktree_agent_runtime_smoke.py の async child spawn と completion の観測を分離し、child terminal event(SubagentStop 等)と artifact materialization を bounded polling で待つ実装へ修正する。producer の exit code 0 を route PASS として扱わない(--require-route-pass 相当の fail-on-route-failure flag を追加し AC で有効化する)。
  • (2026-08-09 追加) Antigravity CLI(AGY)自身が .agents/mcp_config.json から Serena MCP を native discovery・接続・invoke することを、MCP tool event / server log を必要条件として証明する専用 live probe を追加する(least-privilege な read-only Serena tool のみ allow)。
  • (2026-08-09 追加) Serena の resolver/launcher を scripts/agent-ops/resolve_serena_mcp.py に集約し、明示 override → PATH → user-local managed install → exact-pinned uvx fallback の優先順位で解決する。user-local へ latest compatible stable を persistent install する(machine-specific absolute path は repo に commit しない)。
  • (2026-08-09 追加) CI の test_ac13_minimal_agy_env_allowlist で検出された UV_CACHE_DIR env leak を修正する(_minimal_agy_env() と Serena 専用 env builder を分離する)。
  • (2026-08-09 追加) 上記の hermetic regression test 群(spawn/completion 分離・env leak・process group cleanup・cache cold/warm/offline 等)を追加する。
  • (2026-08-09 追加) root cause と再発防止策を PR 実装: local_asset_research route の live Serena MCP 応答待ちタイムアウトの信頼性を改善する #2044 のコメントまたは canonical artifact として machine-readable に報告する。

Out of Scope

Acceptance Criteria

  • AC1: _collect_live_serena_read_only_evidence() の各 request が、request_id・method・tool_name・arguments のハッシュ・elapsed time・response 受信有無を含む machine-readable な request ledger(local_asset_retrieval_metadata 配下)として記録されるテストが追加され PASS している。id=4 に対応する fixture は search_for_pattern を示す。
  • AC2: 大量の stderr を出力してから正常な JSON-RPC response を返す fake MCP server に対し、collector が timeout せず完了することを検証する hermetic test が追加され PASS している。
  • AC3: search_for_pattern の探索範囲がリポジトリ全体ではなく context file のディレクトリ等に限定されることを検証するテストが追加され PASS している。
  • AC4: stage 別 failure class が references/failure-class-taxonomy.md に記録され、retryable 判定が明記されている。manifest drift 以外のケースで manifest_drift_failed が true にならないことをテストで検証する。
  • AC5: retryable と判定された timeout class のみ、route 単位の単一 absolute deadline を共有する bounded single retry のテストが追加され PASS している。retry で first attempt の evidence(request ledger・stderr・cleanup)が失われないことを検証する。
  • AC6: recv() の deadline 計算が time.monotonic() ベースの absolute session deadline に変更され、server_tool_timeout < client_request_timeout < collector_session_deadline < route_harness_timeout - cleanup_grace の関係(retry を含めた worst case)がテストと本文の両方に記録されている。
  • AC7: 正常終了・SIGTERM 終了・SIGKILL fallback・grandchild process 存在(親が先に終了し grandchild が SIGTERM を無視するケースを含む)の各ケースで、process group 単位の残存確認により direct child と descendant process が回収されることを検証するテストが追加され PASS している。primary failure がない cleanup 失敗は fail-close される。
  • AC8: SERENA_SERVER_TOOL_TIMEOUT_SEC が実際に Serena 起動 command(--tool-timeout)へ配線され、preflight で検証されるテストが追加され PASS している。
  • AC9: .claude/skills/gemini-cli-headless-delegation/tests/ および scripts/agent-ops/tests/ 配下の全 pytest が引き続き PASS している。
  • AC10(旧AC8を改訂・2026-08-09): full-route test が canonical validator と route artifact の意味論フィールド(status/failure_class/retrieval_status/retrieval_mode/evidence_record_count/head_sha)を直接 assert し、producer exit code のみでは PASS できないことを検証するテストが追加され PASS している。
  • AC11(新設・2026-08-09): run_agent_provider_route_smoke.py / run_worktree_agent_runtime_smoke.py が child spawn 観測と completion 観測を分離し、child terminal event と artifact materialization を bounded polling で待つことを検証する hermetic regression test(fixture: async_launched child、spawn ありcompletion なし、agent_id 不一致等)が追加され PASS している。
  • AC12(新設・2026-08-09): Antigravity CLI 自身が workspace .agents/mcp_config.json から Serena MCP を native discovery・接続・invoke したことを、MCP tool event / server log を必要条件として証明する live probe が、3 回連続実行で 3/3 PASS している。
  • AC13(新設・2026-08-09): resolve_serena_mcp.py resolver が明示 override → PATH → user-local managed install → exact-pinned uvx fallback の優先順位で解決し、cold/warm/offline-warm の各 cache モードで正しく動作することを検証するテストが追加され PASS している。CI の test_ac13_minimal_agy_env_allowlist(UV_CACHE_DIR unexpected env key)が解消されている。
  • AC14(新設・2026-08-09): 固定 live trial plan(collector-only 12/12、AGY-native probe 3/3、full route Claude Code 3 + Codex CLI 3 の 6/6、さらにコード変更なしでの no-change repeat 6/6、計 full-route 12/12)が genuine live 実行で全て PASS し、PR 実装: local_asset_research route の live Serena MCP 応答待ちタイムアウトの信頼性を改善する #2044 に証跡として記録されている。環境 unavailable による skip は AC14 の達成に数えない。
  • AC15(新設・2026-08-09): root cause(元の Serena timeout の直接原因、2/6 failure の trial 別原因、AGY が実際に Serena MCP を使用できていたか、cache/download の実態、async completion 欠落の詳細、旧 AC8 が 18/18 false PASS を出した理由、CI の UV_CACHE_DIR regression を見逃した理由、再発防止策)が PR 実装: local_asset_research route の live Serena MCP 応答待ちタイムアウトの信頼性を改善する #2044 のコメントまたは canonical artifact に machine-readable に記録されている。

Verification Commands

# AC1
# preflight-scope: pr_review_only
$ rg -n "request_ledger" .claude/skills/gemini-cli-headless-delegation/scripts/run_gemini_headless.py
# AC2
# preflight-scope: pr_review_only
$ uv run --locked pytest .claude/skills/gemini-cli-headless-delegation/tests/test_agy_provider.py -k stderr_backpressure -q
# AC3
# preflight-scope: pr_review_only
$ uv run --locked pytest .claude/skills/gemini-cli-headless-delegation/tests/ -k search_for_pattern_scope -q
# AC4
# preflight-scope: pr_review_only
$ rg -n "startup_timeout" .claude/skills/gemini-cli-headless-delegation/references/failure-class-taxonomy.md
# AC5
# preflight-scope: pr_review_only
$ uv run --locked pytest .claude/skills/gemini-cli-headless-delegation/tests/test_run_gemini_headless.py -k serena_retry -q
# AC6
# preflight-scope: pr_review_only
$ rg -n "time.monotonic" .claude/skills/gemini-cli-headless-delegation/scripts/run_gemini_headless.py
# AC7
# preflight-scope: pr_review_only
$ uv run --locked pytest .claude/skills/gemini-cli-headless-delegation/tests/test_run_gemini_headless.py -k serena_cleanup -q
# AC8
# preflight-scope: pr_review_only
$ rg -n "tool-timeout" .claude/skills/gemini-cli-headless-delegation/scripts/run_gemini_headless.py
# AC9
# preflight-scope: pr_review_only
$ uv run --locked pytest .claude/skills/gemini-cli-headless-delegation/tests/ scripts/agent-ops/tests/ -q
# AC10
# preflight-scope: pr_review_only
$ uv run --locked pytest .claude/skills/gemini-cli-headless-delegation/tests/test_run_gemini_headless_live_trial.py -k full_route -q --collect-only
# AC11
# preflight-scope: pr_review_only
$ uv run --locked pytest scripts/agent-ops/tests/ -k spawn_completion -q
# AC12
# preflight-scope: runtime_only
$ uv run --locked pytest scripts/agent-ops/tests/ -k agy_native_serena_probe -q
# AC13
# preflight-scope: pr_review_only
$ rg -n "def resolve" scripts/agent-ops/resolve_serena_mcp.py
# AC14
# preflight-scope: runtime_only
$ uv run --locked pytest .claude/skills/gemini-cli-headless-delegation/tests/test_run_gemini_headless_live_trial.py -q
# AC15
# preflight-scope: pr_review_only
$ gh pr view 2044 --repo squne121/loop-protocol --json comments --jq '.comments[].body' --template '{{range .}}{{.}}{{"\n"}}{{end}}'

Allowed Paths

  • .claude/skills/gemini-cli-headless-delegation/scripts/run_gemini_headless.py
  • .claude/skills/gemini-cli-headless-delegation/references/failure-class-taxonomy.md
  • .claude/skills/gemini-cli-headless-delegation/tests/test_run_gemini_headless.py
  • .claude/skills/gemini-cli-headless-delegation/tests/test_agy_provider.py
  • .claude/skills/gemini-cli-headless-delegation/tests/test_run_gemini_headless_live_trial.py
  • .claude/skills/gemini-cli-headless-delegation/references/serena-tool-manifest.json
  • .claude/skills/gemini-cli-headless-delegation/references/
  • scripts/agent-ops/run_agent_provider_route_smoke.py
  • scripts/agent-ops/run_worktree_agent_runtime_smoke.py
  • scripts/agent-ops/validate_agent_provider_route_smoke.py
  • scripts/agent-ops/resolve_serena_mcp.py
  • scripts/agent-ops/tests/
  • .agents/mcp_config.json
  • .gemini/settings.json
  • .github/workflows/ci.yml
  • scripts/ci/

Stop Conditions

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

(2026-08-09 OWNER directive による本 Issue 限定の例外・優先ルール。上記6項目の一般原則は他 Issue への標準テンプレートとして維持するが、本 Issue #2015 の継続作業においては以下を優先し、単独では停止条件にしない):

  • 上記6項目のうち「Allowed Paths 外の変更が必要と判明した場合」は、本文「Allowed Paths」節に列挙された OWNER 承認済みの拡張パス(scripts/agent-ops/*、.agents/mcp_config.json、.gemini/settings.json、.github/workflows/ci.yml、scripts/ci/ 等)の範囲内である限り該当しない(それら以外の path が必要になった場合のみ該当)。
  • 「後続 Phase / 別スコープへの波及」「新規 Issue の起票が必要」は、full-route harness・async child completion・AGY MCP discovery・Serena install/cache・関連 CI/test contract に関する限り該当しない(OWNER directive によりこれらは本 Issue の明示スコープ内であり、別 Issue・別 PR へ切り出さない)。
  • 旧 Stop Condition「Serena MCP timeout の根本原因が本 Issue のコード変更では解決不能な外部 infra 問題と判明した場合」「AC8 の live 実行で Serena MCP 以外の原因(AGY provider・GH_TOKEN 等)による failure が判明した場合」は解除された。
  • 一時的なネットワーク障害、test failure、CI failure、runtime harness の不具合は、それ単体では停止条件にしない。原因を特定して修正を継続する。

本 Issue #2015 の継続作業における実効的な停止条件(human 承認不要で継続、以下のみ停止):

  • データ喪失を伴う破壊的操作が不可避と判明した場合。
  • secret の開示・生成・コミットが必要と判明した場合。
  • 明示されていない外部課金が必要と判明した場合。
  • GitHub または実行環境の権限が回復不能に不足し、push / comment / check 取得が実行不能になった場合。

Required Skills

  • Python
  • pytest
  • subprocess/process-group management
  • MCP (Model Context Protocol) client/server semantics

Required Design References

  • .claude/skills/gemini-cli-headless-delegation/references/failure-class-taxonomy.md
  • .claude/skills/gemini-cli-headless-delegation/references/serena-tool-manifest.json

Runtime Verification Applicability

本 Issue の変更対象はワークフロー文書・スクリプト・CI 設定のみです。ゲームの実行時動作には影響しません。

decision: not_applicable
reason: "Workflow documentation, script, and CI config changes only. No runtime game behavior changed."

Delivery Rule

1 Issue = 1 PR。既存 worktree・既存 branch・既存 PR #2044 を継続して使用する。新規 PR は作らない。

OWNER Scope Reframe(2026-08-09)

OWNER が PR #2044(issuecomment-5229836428)で対話プロンプトにより本 Issue のスコープを明示的に拡張した。

schema_version: ANCHOR_SCOPE_REFRAME_V1
target:
  repo: squne121/loop-protocol
  issue_number: 2015
decision: approve_scope_delta
allowed_path_deltas:
  - "scripts/agent-ops/run_agent_provider_route_smoke.py"
  - "scripts/agent-ops/run_worktree_agent_runtime_smoke.py"
  - "scripts/agent-ops/validate_agent_provider_route_smoke.py"
  - "scripts/agent-ops/resolve_serena_mcp.py"
  - "scripts/agent-ops/tests/"
  - ".agents/mcp_config.json"
  - ".gemini/settings.json"
  - ".claude/skills/gemini-cli-headless-delegation/references/serena-tool-manifest.json"
  - ".claude/skills/gemini-cli-headless-delegation/references/"
  - ".claude/skills/gemini-cli-headless-delegation/scripts/"
  - ".claude/skills/gemini-cli-headless-delegation/tests/"
  - ".github/workflows/ci.yml"
  - "scripts/ci/"
rationale: "OWNER directive: AC8 genuine full-route PASS is the outcome boundary. Runtime spawn/completion harness、AGY-native MCP discovery、Serena launch/cache strategy、関連CI/test contractを同一Issue #2015・PR #2044で修正する。least privilege、非破壊、secretなし、外部課金なし、無関係な権限拡張なし。"
required_rerun:
  - contract_review
  - refinement_preflight
  - allowed_paths_gate

停止条件は本文「Stop Conditions」節に置き換えられた(データ喪失不可避 / secret / 未承認課金 / 権限の回復不能な不足のみ)。旧 Stop Condition(AC8 の Serena 以外原因による failure、Allowed Paths 不足)は解除。

Notes for Reviewer

Activity

  1. squne121 commented on Aug 8, 2026

    @squne121
    OwnerAuthor

    [create-issue] post-create ready tuple validation FAILED: phase/implementation label missing. Manual fix required.

  2. squne121 commented on Aug 8, 2026

    @squne121
    OwnerAuthor

    [create-issue] post-create ready tuple validation now PASSES after adding label 'phase/implementation' via create_issue_txn.py reconcile. all_passed: true.

  3. squne121 commented on Aug 8, 2026

    @squne121
    OwnerAuthor

    Issue #2015 敵対的レビュー

    判定

    REQUEST_CHANGES — 現状の Issue 契約は implementation-ready ではありません。

    最も重大なのは、起票根拠となった timeout の発生箇所が誤認されていることです。その状態で timeout 延長や bounded retry を実装すると、実際には wrapper 自身が作っている stall を「transient infra」として隠蔽する可能性があります。

    現時点で #2015 に直接対応する実装 PR は確認できず、Issue コメントもラベル修復記録に留まっています。したがって、以下は現行 main の実装、起票元 PR #2005、関連調査 PR #2022、pin 済み Serena 実装を対象にした契約レビューです。Issue は _collect_live_serena_read_only_evidence()、timeout、failure taxonomy、retry、cleanup に範囲を限定しています。


    P0-1: timeout した request ID の対応付けが事実と異なる

    Issue 本文は、id=4 を3番目の tools/call、すなわち get_symbols_overview と説明しています。しかし現行コードの ID 発行順は次のとおりです。

    1. initialize: ID 1
    2. tools/list: ID 2
    3. find_file: ID 3
    4. search_for_pattern: ID 4
    5. get_symbols_overview: ID 5

    したがって観測された失敗は、少なくとも記録上は get_symbols_overview ではなく search_for_pattern の応答待ちです。

    しかも PR #2005 の route smoke は local_asset_research の context file に README.md を渡します。wrapper はその親ディレクトリ "." を search_for_pattern の探索範囲にし、固定パターン local_asset_research をリポジトリ全体から検索します。上流 Serena の実装も、このツールが指定範囲内のプロジェクトファイルを走査することを示しています。

    影響

    現在の Background、Outcome、AC1 は、誤った tool/stage を前提にしています。

    • symbolic/LSP 初期化遅延を疑うべき事象なのか
    • repo-wide regex search が高コストなのか
    • stdout/stderr transport が詰まったのか
    • MCP server が JSON-RPC error を返したのか

    が区別されていません。原因を特定しないまま timeout を増やすべきではありません。

    必須修正

    各 request について最低限、以下を機械可読で残す必要があります。

    request_id: 4
    phase: tool_call
    method: tools/call
    tool_name: search_for_pattern
    arguments_sha256: "..."
    started_monotonic_ms: 0
    elapsed_ms: 180001
    timeout_ms: 180000
    response_received: false
    process_exit_code: null

    Issue 本文の id=4 = get_symbols_overview は修正し、AC1 は単なる調査記録ではなく、この ledger から tool/stage を再計算できることを要求すべきです。


    P0-2: wrapper 自身が stderr pipe deadlock を発生させ得る

    現行 wrapper は Serena subprocess を次の構成で起動しています。

    stdout=subprocess.PIPE
    stderr=subprocess.PIPE

    しかし、待機ループが読むのは stdout だけで、stderr はプロセス終了時を含めて一度も drain されません。

    一方、pin 済み Serena は stdout を MCP 専用にし、起動ログ・tool call・tool result を stderr へ出します。さらに Tool.apply_ex() は tool result 全体を INFO ログへ書いた後に結果を返します。

    この組み合わせでは、search_for_pattern の大きな検索結果を stderr に記録して pipe が満杯になると、Serena は tool result を MCP stdout へ返す前に停止できます。親は stdout を待ち続け、180秒後に timeout します。

    これは当該実行で実際に pipe が満杯になったことの証明ではありません。しかし、現行コードに自己誘発 deadlock 経路が存在することはコード上成立しています。Python の公式ドキュメントも、PIPE を使用しながら適切に読み出さない場合の deadlock を明示的に警告しています。MCP stdio 仕様は stderr へのログ出力を許可し、stdout はプロトコルメッセージ専用としています。([Model Context Protocol]1)

    必須修正

    retry より先に、以下を実装してください。

    • stderr を専用 thread または selector で継続的に drain する
    • stdout と stderr は絶対に merge しない
    • stderr は bounded ring buffer または一時ファイルへ保存する
    • result JSON へは redaction 済み tail、byte count、SHA-256 のみを残す
    • fake MCP server が大量の stderr を書いた後に正常応答する hermetic test を追加する

    例えば次のケースが timeout せず成功しなければなりません。

    fake server:
      initialize response
      tools/list response
      find_file response
      stderrへ2 MiB以上出力
      search_for_pattern response
      get_symbols_overview response
    

    単に 180 → 300 秒へ変更するだけでは、この deadlock を300秒待つようになるだけです。


    P0-3: AC5 の Verification Command は実行不能

    Issue の AC5 は次の形です。

    run_gemini_headless.py \
      --tool-profile local_asset_research \
      --provider agy \
      --prompt "..."

    しかし現行 CLI にこれらの option は存在しません。通常実行では --request-file と --output-file が必須です。したがって、この Verification Command は argparse の usage error で終了します。

    さらに、仮に direct wrapper invocation を正しく直しても、それは Claude Code / Codex CLI の custom-agent spawn を検証しません。両 runtime の正規経路は既存の producer です。

    scripts/agent-ops/run_agent_provider_route_smoke.py \
      --runtime claude_code|codex_cli \
      --agent codebase-investigator \
      --profile local_asset_research

    修正版

    wrapper 単体の live probe は、まず request を正規 builder で生成します。

    TMP_DIR="$(mktemp -d)"
    
    uv run --locked python3 \
      .claude/skills/gemini-cli-headless-delegation/scripts/build_request.py \
      --provider agy \
      --profile local_asset_research \
      --objective "Issue #2015 live Serena verification" \
      --prompt "Return exactly OK." \
      --context-file README.md \
      --output "$TMP_DIR/request.json"
    
    uv run --locked python3 \
      .claude/skills/gemini-cli-headless-delegation/scripts/run_gemini_headless.py \
      --request-file "$TMP_DIR/request.json" \
      --output-file "$TMP_DIR/result.json"

    runtime integration は別に実行します。

    for runtime in claude_code codex_cli; do
      uv run --locked python3 \
        scripts/agent-ops/run_agent_provider_route_smoke.py \
        --runtime "$runtime" \
        --agent codebase-investigator \
        --profile local_asset_research \
        --timeout-seconds "$ROUTE_TIMEOUT_SECONDS" \
        --output-dir ".claude/artifacts/issue-2015/$runtime"
    done

    既存 aggregate validator の assertion flags は required six-route 全件を close gate にするため、#2015 の2 routeだけにそのまま適用すると必ず missing-route になります。2 route 専用の assertion を inline Python または新しい verifier で実施するか、既存 validator に subset mode を追加するなら Allowed Paths を明示的に拡張する必要があります。


    P0-4: failure class が粗すぎ、retry 判定に使用できない

    現在は live Serena 経路内のすべての例外を broad except Exception で捕捉し、同じ値へ丸めています。

    local_asset_research live_serena_mcp_failed
    

    さらに、例外の種類に関係なく manifest_drift_failed: true が設定されます。timeout、process exit、JSON parse error、JSON-RPC error、credential-like result 検出、tool manifest drift がすべて同じ状態です。

    この generic class を taxonomy に追加して retryable: true にすると、次まで再試行されます。

    • manifest drift
    • protocol version mismatch
    • required tool 欠落
    • malformed stdout
    • JSON-RPC tool error
    • credential-like material 検出
    • invalid MCP configuration

    これらは transient timeout ではありません。

    必要な分類

    少なくとも次へ分割すべきです。

    serena_mcp_startup_timeout
    serena_mcp_request_timeout
    serena_mcp_process_exited
    serena_mcp_protocol_error
    serena_mcp_jsonrpc_error
    serena_mcp_manifest_drift
    serena_mcp_tool_error
    serena_mcp_redaction_failed
    serena_mcp_cleanup_failed
    

    追加で次のフィールドが必要です。

    failure_origin: startup | transport | protocol | tool | policy | cleanup
    retryable: true | false
    retry_scope: fresh_process_once | none
    classification_confidence: exact | inferred

    manifest_drift_failed は実際に tools/list と manifest が不一致だった場合だけ true にし、それ以外は false または null にしてください。

    また failure class は既存 taxonomy と同様の snake_case token とし、空白を含む表示文を class に使用すべきではありません。現行 taxonomy は client_subprocess_timeout 等を retryable としていますが、Serena の startup・request・tool failure を区別していません。


    P0-5: timeout の階層が互いに矛盾している

    現在確認できる timeout は次の構造です。

    • wrapper の 各 request: 180秒
    • Serena 上流の default tool_timeout: 240秒
    • route smoke harness の default whole-route timeout: 180秒
    • wrapper 内の request 数: initialize、tools/list、tools/call × 3

    上流 Serena の tool は、設定された tool_timeout まで task result を待機します。デフォルト設定は240秒です。現在の client は180秒なので、server が正常に処理中でも60秒先に諦める可能性があります。

    一方、outer route の既定値も180秒です。wrapper の1 requestだけでouter budgetを使い切るため、inner timeout、agent startup、AGY 実行、artifact materialization を同じ budget に収められません。

    さらに現行 recv() は request ごとに新しい180秒 deadlineを作ります。すべての応答が期限直前まで掛かれば、1 attempt が最大約900秒、whole-collector retry で最大約1800秒になり得ます。

    必須設計

    次の不等式を明示的に満たす必要があります。

    server_tool_timeout
      < client_request_timeout
      < collector_session_deadline
      < route_harness_timeout - cleanup_grace
    

    実装は time.time() ではなく、時計補正の影響を受けない time.monotonic() による absolute session deadline を使うべきです。([Python documentation]2)

    推奨構造は次です。

    session_deadline = monotonic() + collector_budget
    
    remaining = session_deadline - monotonic()
    recv(
        expected_id,
        timeout=min(phase_timeout, remaining),
    )

    timeout 数値を先に決めるのではなく、実測した warm/cold distribution から決定してください。実際に Serenaへ渡された effective tool_timeout も evidence に記録する必要があります。


    P0-6: 「stable」の証明条件が存在しない

    AC5 は Claude Code / Codex CLI で各1回成功すれば満たせる構造ですが、1回の成功は安定性の証明ではありません。特に retry を追加すると、初回失敗を隠した「最終成功」だけを記録しやすくなります。

    関連する #2013 / PR #2022 では、再試行すると成功する非決定的事象を、事前固定した control 15 trial / production 15 trial で調査しました。その結果、transient infrastructure ではなくリポジトリ側の observability defect と判定され、retry は対象外のまま維持されています。#2015 も同じ因果判定水準を採用すべきです。

    必須の trial plan

    結果を見てから条件を変えない、次のような plan を Issue に固定してください。

    live_trial_plan:
      collector_only:
        warm_cache_trials: 10
        cold_cache_trials: 2
      full_route:
        claude_code_trials: 3
        codex_cli_trials: 3
      exclusions:
        allowed_after_execution: false
      report_separately:
        - first_attempt_pass_count
        - retry_recovered_count
        - final_pass_count
        - failure_class_distribution
        - phase_latency_distribution

    少なくとも以下を全 trial に記録します。

    • repository HEAD SHA
    • Serena pinned commit
    • uv version
    • runtime version
    • cache state
    • request ledger
    • first attempt result
    • retry result
    • cleanup result
    • stderr digest
    • result artifact digest

    commit pin は source identity を固定しますが、uvx の cold start、Git取得、環境構築、cache hit/miss の時間差までは消しません。uv は解決済み Git commit を cache key として利用するため、warm/cold lane を区別する必要があります。([Astral Docs]3)


    P1-1: cleanup は subprocess tree を回収していない

    現行 cleanup は次の処理です。

    1. process.terminate()
    2. wait(timeout=5)
    3. 失敗したら process.kill()

    ただし kill() 後に再度 wait() していません。また kill 対象は直接起動した uvx process だけで、Serena本体や language server などの descendant が残る可能性があります。

    MCP の lifecycle 仕様では、stdio server の終了は input close、graceful wait、SIGTERM、最後に SIGKILL という段階的処理が想定されています。request timeout 時には cancellation を送り、response 待機を停止することも定義されています。([Model Context Protocol]4)

    推奨処理

    POSIX を正式な対象にするなら、次の順序が妥当です。

    Popen(start_new_session=True)
    ↓
    timeout時に notifications/cancelled
    ↓
    stdin.close()
    ↓
    graceful wait
    ↓
    process groupへ SIGTERM
    ↓
    wait
    ↓
    process groupへ SIGKILL
    ↓
    必ず wait/reap
    

    テストは fake server が grandchild を起動し、SIGTERM を無視するケースまで含めるべきです。cleanup failure が発生しても、元の request timeout を上書きせず、primary failure と cleanup failure の両方を保持してください。


    P1-2: retry ledger の保存先が契約上未定義

    AC3 は initial_result を保持するよう要求していますが、#2015 は同時に固定キー集合・schema変更を Stop Condition とし、横断的な attempts / retryable / retry_scope は #277 の範囲外としています。

    現行 wrapper result には、#2015 用の initial_result の保存場所が定義されていません。一方、route smoke は独自に retry.initial_result 等を持っていますが、これは collector 内部 retry の証跡ではありません。

    #277 はまさに同じ run_gemini_headless.py、taxonomy、tests を対象に、failure_origin、retryable、retry_scope、attempts 等を追加する OPEN Issue です。

    必須決定

    次のいずれかを Issue 本文に明記してください。

    1. 実装: gemini-cli-headless-delegation failure_class taxonomy を result JSON に追加し retry policy を実装する #277 を先行依存にする
    2. 実装: local_asset_research route の live Serena MCP 応答待ちタイムアウトの信頼性を改善する #2015 は local_asset_retrieval_metadata.attempts という nested schema のみを所有し、実装: gemini-cli-headless-delegation failure_class taxonomy を result JSON に追加し retry policy を実装する #277 が後でtop-levelへ統合する
    3. 実装: local_asset_research route の live Serena MCP 応答待ちタイムアウトの信頼性を改善する #2015 から retry を除外し、分類・transport・cleanup の修復だけを行う

    現状の「schema変更禁止だが initial_result を保存する」は矛盾しています。


    P1-3: 根本原因が query shape でも修正できない Scope になっている

    誤った ID 対応を直すと、timeout 対象は repo-wide search_for_pattern です。しかし In Scope は timeout値、taxonomy、retry、cleanup に限定され、tool query の縮小は含まれていません。

    測定の結果、repo全体検索が原因だった場合に必要なのは、例えば次です。

    • relative_path を context file 自体へ限定
    • paths_include_glob で対象を限定
    • multiline=False
    • 固定文字列 local_asset_research ではなく、context file に確実に存在する bounded query を使用
    • max_answer_chars を明示
    • evidence purpose と query の対応を定義

    現状の Scope では、原因を発見しても timeout延長か別Issue化しかできません。query-shape reliability を In Scope に追加するか、Outcome を「原因調査・分類」へ縮小してください。


    推奨する修正版 Outcome

    以下の形へ置き換えるのが妥当です。

    _collect_live_serena_read_only_evidence() が、Serena MCP の startup、protocol negotiation、tool execution、manifest validation、cleanup を段階別に観測し、stderr backpressure による自己誘発 stall を起こさず、monotonic な session deadline 内で終了する状態にする。
    failure は machine-readable な stage-specific failure class と attempt ledger に保存し、retry は実証済みの timeout class に対してのみ fresh process で最大1回許可する。first attempt は破棄しない。
    固定済み trial plan に基づき、collector 単体および Claude Code / Codex CLI の local_asset_research route が genuine live evidence を生成することを確認する。


    推奨 Acceptance Criteria

    AC1: 正しい request attribution

    timeout/error artifact から request_id、method、tool name、arguments digest、elapsed time を再計算できる。ID 4 の fixture は search_for_pattern を示す。

    AC2: stderr backpressure 耐性

    大量の stderr を出力してから正常な JSON-RPC response を返す fake MCP server に対し、collector が timeoutせず完了する。stderr は bounded・redacted であり、stdout JSON-RPC は汚染されない。

    AC3: failure classification

    startup timeout、request timeout、process exit、protocol error、JSON-RPC error、manifest drift、redaction failure、cleanup failure が別 class になる。manifest drift 以外で manifest_drift_failed=true にならない。

    AC4: bounded retry

    retryable predicate を満たす timeout のみ fresh process で最大1回 retryする。初回 attempt、cleanup、retry attempt、final result がすべて保持される。manifest drift、protocol error、tool error、redaction failureは retry回数0。

    AC5: deadline hierarchy

    monotonic session deadline を使用し、server tool timeout、request timeout、collector timeout、route timeout の大小関係がテストと文書で固定される。

    AC6: process-tree cleanup

    正常終了、SIGTERM終了、SIGKILL fallback、grandchild存在の各ケースで direct child と descendant が回収される。kill後には必ず waitする。

    AC7: fixed live trials

    事前固定した collector-only trial と Claude/Codex integration trial を実行し、first-attempt pass と retry-recovered pass を別々に報告する。trial の事後除外は禁止。

    AC8: regression

    単一ファイルだけでなく、delegation skill の全 pytest が通る。

    uv run --locked pytest \
      .claude/skills/gemini-cli-headless-delegation/tests/ \
      -q

    Allowed Paths の修正

    最低でも次を追加すべきです。

    .claude/skills/gemini-cli-headless-delegation/tests/test_agy_provider.py
    

    現行の live Serena success tests は _collect_live_serena_read_only_evidence() を mock している test_agy_provider.py 側にあり、transport-level failure を直接検証していません。#2015 の対象を test_run_gemini_headless.py だけに限定すると、既存の AGY local-asset integration seam と分断されます。

    run_agent_provider_route_smoke.py や validator 自体を変更しないなら、scripts/agent-ops/ を Allowed Paths に加える必要はありません。既存 producer を verification-only で利用できます。


    最終結論

    #2015 の方向性自体は妥当です。ただし、現行契約は次の危険な順序になっています。

    timeoutをtransientと仮定
    → timeout値を変更
    → retryを追加
    → 1回成功
    → stableと判定
    

    採用すべき順序は逆です。

    正しいrequest IDを確定
    → stderr backpressureとrepo-wide searchを検証
    → stage別failure evidenceを実装
    → deadlineとcleanupを修復
    → 固定trialで原因分布を測定
    → transientと実証されたclassだけ最大1回retry
    → Claude/Codex双方で再検証
    

    現状のまま実装を開始すると、timeout の根本原因を隠す retry patch になる可能性が高いため、Issue 本文・AC・Verification Commands・Allowed Paths の再定義がマージ前提です。

  4. squne121 commented on Aug 8, 2026

    @squne121
    OwnerAuthor

    Issue Refinement Loop 終了報告(承認・approved)

    OWNER の anchor comment(issuecomment-5226174852、敵対的レビュー、REQUEST_CHANGES、P0-1〜P1-3)を反映し、2 iteration で本文を改訂しました。

    • iteration 1: control-plane が anchor comment の全技術的主張(P0-1 request id 対応付け、P0-2 stderr pipe deadlock、P0-3 CLI 引数、P0-4 failure class 粒度、P0-5 timeout 階層、P1-1 process cleanup)を現行コード(HEAD 1f15ef85)で直接検証し、すべて事実と確認。Outcome/In Scope/Out of Scope/AC1-AC9/Verification Commands/Allowed Paths を全面改訂。issue-reviewer → VERDICT: needs-fix(AC8 の VC が uv run python3 <script> 直接呼び出しで VC preflight allowlist 違反)。
    • iteration 2: AC8/AC9 の Verification Command を pytest wrapper 形式(新規 test_run_gemini_headless_live_trial.py)へ修正し、Allowed Paths に追加。issue-reviewer → VERDICT: approve(control-plane が check_issue_contract.py --issue 2015 を直接実行し独立に再確認、C1-C11 全 PASS、blockers 0)。

    Final Gate: not applicable at this stage(issue-contract-review skill の CONTRACT_REVIEW_RESULT_V1 snapshot は本 refinement loop の範囲外であり未実行。次段階として実装着手直前に別途実行が必要)。

    LOOP_HANDOFF_RESULT_V1:
      status: blocked
      routing_action: blocked
      contract_review:
        status: blocked
        gate_result: missing_go
        latest_comment_url: null
        generated_at: null
        body_sha256: null
      metadata:
        title_prefix_ready: true
        phase_label_ready: false
      auto_fixes:
        result: skipped
        required: []
        skipped: []
      blockers:
        - kind: contract_review_not_run
          description: "issue-contract-review skill (CONTRACT_REVIEW_RESULT_V1) has not been executed for this issue yet; issue-refinement-loop only certifies body quality (review-issue approve), not the pre-implementation readiness gate."
      permissions:
        unavailable: []
      generated_at: "2026-08-08T13:23:23Z"
      checked_body_sha256: "sha256:3ca1ffd59e2d0daf7bdab7e5b86fccd8a9e30fff3914c8a6f991dcf688a3806f"
      checker_exit_code: 0
      missing_sections: []
      missing_contract_keys: []

    Next Action: 実装着手前に issue-contract-review skill を実行して CONTRACT_REVIEW_RESULT_V1: status: go の fresh snapshot を得た上で impl-review-loop へ handoff してください。

  5. squne121 commented on Aug 8, 2026

    @squne121
    OwnerAuthor

    implement-issue: 実装完了 (2026-08-08T14:38:27Z)

    • PR: 実装: local_asset_research route の live Serena MCP 応答待ちタイムアウトの信頼性を改善する #2044
    • Worktree: .claude/worktrees/issue-2015-local-asset-research-route-live-serena-m
    • Branch: worktree-issue-2015-local-asset-research-route-live-serena-m
    • Verification: AC1-AC9 個別 VC 全て実行済み。skill 配下全テスト 1516 passed(本 PR と無関係な既存 flake 1件を除く)。AC8 は本開発環境に live agy CLI / Serena MCP が実際に利用可能だったため genuine live 実行し、collector-only 12/12・full route 6/6 の全18トライアル PASS(証跡は PR 本文の Live Trial Evidence 参照)。
    • 後続: PR レビュー(pr-review-judge)→ マージ → post-merge-cleanup
  6. squne121 commented on Aug 8, 2026

    @squne121
    OwnerAuthor

    impl-review-loop: 完了 (2026-08-08T16:00:00Z)

    IMPL_REVIEW_LOOP_RESULT_V1:
      schema_version: 1
      status: draft_pr_ready
      pr_url: "https://github.com/squne121/loop-protocol/pull/2044"
      head_sha: "7f51cd58f98867c43d2e3494c02679fffdeded6c"
      issue_number: 2015
      termination_reason: approved
      merge_ready: true
      iteration: 2
    
    FOLLOW_UP_MATERIALIZATION_RESULT_V1:
      schema_version: 1
      materialized_by: impl-review-loop
      follow_up_issues: []
      note_only_observations: []
  7. squne121 commented on Aug 9, 2026

    @squne121
    OwnerAuthor

    Issue #2015 scope reframe(OWNER directive materialization)

    OWNER が PR #2044 のコメント(issuecomment-5229836428)で本 impl-review-loop の対話セッションへ直接指示した内容を、Issue #2015 の canonical contract update として materialize する。

    エスカレーション時 head: 8a5b2f68ca9165b3ace8b3c4d6fe98b86f3da979

    対話プロンプトの要旨:

    • PR 実装: local_asset_research route の live Serena MCP 応答待ちタイムアウトの信頼性を改善する #2044 を同一 branch・同一 PR のまま継続し、Serena MCP collector 単体だけでなく Antigravity CLI native MCP discovery/tool invocation と Claude Code/Codex CLI の full local_asset_research route が安定して成功するまで完遂する。
    • 旧 Stop Condition「AC8 で Serena 以外の原因が判明した場合は停止」を本作業について解除する。
    • full-route harness、async child completion、AGY MCP discovery、Serena install/cache、関連 CI/test contract を本 Issue・PR の明示的なスコープ内とする。別 Issue・別 PR へ切り出さない。旧 Allowed Paths を理由に human escalation しない。
    • 人間承認は不要。停止条件はデータ喪失を伴う破壊的操作の不可避性・secret の開示/生成/コミット・明示されていない外部課金・GitHub または実行環境の権限が回復不能に不足する場合のみとする。
    schema_version: ANCHOR_SCOPE_REFRAME_V1
    target:
      repo: squne121/loop-protocol
      issue_number: 2015
    decision: approve_scope_delta
    allowed_path_deltas:
      - "scripts/agent-ops/run_agent_provider_route_smoke.py"
      - "scripts/agent-ops/run_worktree_agent_runtime_smoke.py"
      - "scripts/agent-ops/validate_agent_provider_route_smoke.py"
      - "scripts/agent-ops/resolve_serena_mcp.py"
      - "scripts/agent-ops/tests/"
      - ".agents/mcp_config.json"
      - ".gemini/settings.json"
      - ".claude/skills/gemini-cli-headless-delegation/references/serena-tool-manifest.json"
      - ".claude/skills/gemini-cli-headless-delegation/references/"
      - ".claude/skills/gemini-cli-headless-delegation/scripts/"
      - ".claude/skills/gemini-cli-headless-delegation/tests/"
      - ".github/workflows/ci.yml"
      - "scripts/ci/"
    rationale: "OWNER directive: AC8 genuine full-route PASS is the outcome boundary. Runtime spawn/completion harness、AGY-native MCP discovery、Serena launch/cache strategy、関連CI/test contractを同一Issue #2015・PR #2044で修正する。least privilege、非破壊、secretなし、外部課金なし、無関係な権限拡張なし。"
    required_rerun:
      - contract_review
      - refinement_preflight
      - allowed_paths_gate

    Issue 本文(In Scope / Allowed Paths / Acceptance Criteria / Verification Commands / Stop Conditions)を本 directive に合わせて同一 transaction で更新した。

  8. squne121 commented on Aug 10, 2026

    @squne121
    OwnerAuthor

    impl-review-loop: 完了 (2026-08-11T02:15:00Z)

    IMPL_REVIEW_LOOP_RESULT_V1:
      schema_version: 1
      status: draft_pr_ready
      pr_url: "https://github.com/squne121/loop-protocol/pull/2044"
      head_sha: "b2c67ab2d49f45d64157b7ab3f63a52a140f0462"
      issue_number: 2015
      termination_reason: approved
      merge_ready: true
      iteration: "OWNER scope reframe後の追加ラウンド多数(Phase 1-2、詳細は各PRコメント参照)"
    
    FOLLOW_UP_MATERIALIZATION_RESULT_V1:
      schema_version: 1
      materialized_by: impl-review-loop
      follow_up_issues: []
      note_only_observations:
        - dedupe_key: "codex-cli-spawn-agent-non-determinism"
          source_url: "https://github.com/squne121/loop-protocol/pull/2044"
          source_note_id: "root-cause-report-ac15"
          summary: "codex_cli 自身のモデルが spawn_agent tool を呼ばない選択をすることがある third-party non-determinism。retry/budget-splitで大幅緩和したが根絶不能。将来 codex CLI 側の改善余地あり(follow-up Issue 化は人間判断)。"
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

    phase/implementation

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions