Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -435,10 +435,15 @@ async def _run_acp_session(
session_cwd = cwd_override if cwd_override is not None else os.getcwd()

# Launch gemini --acp — honour GEMINI_BIN so callers can inject a custom binary
# GEMINI_ACP_DEBUG=1 appends --debug to enable verbose ACP protocol logging.
# This is used by verify_acp_roundtrip.sh to capture ACP JSON-RPC messages
# in stderr for runtime verification evidence (AC1 of Issue #113).
acp_args: list[str] = [gemini_bin, "--acp"]
if os.environ.get("GEMINI_ACP_DEBUG") == "1":
acp_args.append("--debug")
try:
proc = await asyncio.create_subprocess_exec(
gemini_bin,
"--acp",
*acp_args,
stdin=asyncio.subprocess.PIPE,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@
# - scenario 2 (controlled experiment): permission outcome controls a side
# effect — 2a deny → no file, 2b approve → file created
# - Artifact output to artifacts/runtime-verification-AC7-<ISO8601>.log
# - Telemetry artifact to artifacts/runtime-verification-AC7-<ISO8601>.telemetry.json
# when real Gemini CLI is available and pre-authenticated
#
# Result schema note: run_delegation() normalizes ACP results to
# delegation_result/v1. ACP-specific fields (structured_events, failure_class)
Expand All @@ -22,7 +24,11 @@
# 77 Execution environment unavailable (gemini, jq, or uv not found)
#
# Environment:
# GEMINI_BIN Override the gemini CLI binary path (default: gemini)
# GEMINI_BIN Override the gemini CLI binary path (default: gemini)
# GEMINI_ACP_DEBUG Set to "1" to pass --debug to gemini --acp (real CLI only)
# GEMINI_TELEMETRY_ENABLED Set to "true" to enable telemetry output (real CLI only)
# GEMINI_TELEMETRY_TARGET Set to "local" for local telemetry file output
# GEMINI_TELEMETRY_OUTFILE Path for telemetry JSON output file

set -euo pipefail

Expand Down Expand Up @@ -63,8 +69,27 @@ ARTIFACTS_DIR="$REPO_DIR/artifacts"
mkdir -p "$ARTIFACTS_DIR"
LOG_FILE="$ARTIFACTS_DIR/runtime-verification-AC7-${TIMESTAMP}.log"

# --- Telemetry artifact path (real Gemini CLI + pre-authenticated env only) ---
# GEMINI_TELEMETRY_OUTFILE defaults to artifacts/runtime-verification-AC7-<TIMESTAMP>.telemetry.json
# This file is created by gemini CLI when GEMINI_TELEMETRY_ENABLED=true and
# GEMINI_TELEMETRY_TARGET=local. Fake-ACP-agent scenarios (scenario 2) do NOT
# produce telemetry artifacts.
TELEMETRY_FILE="${GEMINI_TELEMETRY_OUTFILE:-$ARTIFACTS_DIR/runtime-verification-AC7-${TIMESTAMP}.telemetry.json}"
# Export telemetry env vars so run_gemini_acp.py subprocess inherits them for
# real Gemini CLI scenario 1. Values are only set when not already exported by
# the caller; set defaults here so callers that want to disable telemetry can
# unset GEMINI_TELEMETRY_ENABLED before running this script.
export GEMINI_TELEMETRY_OUTFILE="$TELEMETRY_FILE"
export GEMINI_TELEMETRY_ENABLED=true
export GEMINI_TELEMETRY_TARGET=local
export GEMINI_TELEMETRY_LOG_PROMPTS=false
# GEMINI_ACP_DEBUG=1 causes run_gemini_acp.py to append --debug to the gemini
# --acp subprocess args, which enables verbose ACP protocol logging to stderr.
export GEMINI_ACP_DEBUG="${GEMINI_ACP_DEBUG:-1}"

# Collect environment info once
ENV_INFO="OS=$(uname -sr), gemini=$(command -v "$GEMINI_BIN"), jq=$(command -v jq), uv=$(command -v uv 2>/dev/null || echo 'not found')"
GEMINI_VERSION="$("$GEMINI_BIN" --version 2>/dev/null || echo 'unknown')"
ENV_INFO="OS=$(uname -sr), gemini=$GEMINI_VERSION ($(command -v "$GEMINI_BIN")), jq=$(command -v jq), uv=$(command -v uv 2>/dev/null || echo 'not found')"

# Track overall pass/fail
OVERALL_RESULT=0
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1837,3 +1837,73 @@ def _fake_run_acp(request: dict[str, Any], **kwargs: Any) -> dict[str, Any]:
"failure_class"
)
assert fclass == "auth_required"


# ---------------------------------------------------------------------------
# GEMINI_ACP_DEBUG argv shape tests (Issue #113 Major fix)
# ---------------------------------------------------------------------------


class TestGeminiAcpDebugArgvShape:
"""GIVEN GEMINI_ACP_DEBUG env var, WHEN run_acp is called, THEN argv shape is correct.

Verifies that:
- unset → gemini --acp (no --debug)
- value=0 → gemini --acp (no --debug)
- value=1 → gemini --acp --debug
"""

@pytest.mark.parametrize(
"env_value, expected_has_debug",
[
(None, False), # unset
("0", False), # explicitly disabled
("1", True), # explicitly enabled
],
)
def test_argv_shape(
self, env_value: str | None, expected_has_debug: bool, monkeypatch: pytest.MonkeyPatch
) -> None:
"""Verify --debug is appended iff GEMINI_ACP_DEBUG=1."""
captured_args: list[str] = []

async def fake_subprocess(*args: str, **kwargs: object) -> None: # type: ignore[return]
captured_args.extend(args)
raise FileNotFoundError("fake gemini not found")

if env_value is None:
monkeypatch.delenv("GEMINI_ACP_DEBUG", raising=False)
else:
monkeypatch.setenv("GEMINI_ACP_DEBUG", env_value)

fake_request = {
"schema": "delegation_request_v1",
"transport": "acp",
"objective": "test",
"instructions": [],
"tool_profile": "no_tools",
"output_sections": ["Response"],
"model": "gemini-2.5-flash",
"timeout_sec": 10,
}

with patch("asyncio.create_subprocess_exec", side_effect=fake_subprocess):
result = asyncio.run(
acp._run_acp_session(
prompt="test",
model="gemini-2.5-flash",
approve_edits=False,
timeout_sec=10,
gemini_bin="gemini",
cwd_override=None,
)
)

assert result.get("failure_class") == "gemini_not_found"

has_debug = "--debug" in captured_args
assert has_debug == expected_has_debug, (
f"GEMINI_ACP_DEBUG={env_value!r}: "
f"expected --debug={'present' if expected_has_debug else 'absent'}, "
f"got args={captured_args!r}"
)
36 changes: 36 additions & 0 deletions docs/dev/runtime-verification-policy.md
Original file line number Diff line number Diff line change
Expand Up @@ -252,6 +252,42 @@ fi
| timeout(サーバー無応答)| 異常系 | timeout エラーが返り fallback が発火しない |
| fallback 発火 | 異常系 | `_*_fallback: true` → FAIL 判定 |

### ACP transport 動作検証スクリプト (`verify_acp_roundtrip.sh`)

ACP transport の end-to-end 動作検証は `.claude/skills/gemini-cli-headless-delegation/scripts/verify_acp_roundtrip.sh` で実施する。

このスクリプトは以下の 2 種類のシナリオを含む:

1. **scenario 1(実 Gemini CLI 向け正常系)**: PONG roundtrip — 実 Gemini CLI が pre-authenticated の場合のみ実行。`GEMINI_TELEMETRY_OUTFILE` に telemetry.json を出力し、`--debug` flag(`GEMINI_ACP_DEBUG=1`)で ACP JSON-RPC protocol ログを stderr に記録する。実 CLI 不在または auth 失敗の場合は SKIP exit 77 を返す。
2. **scenario 2(deterministic fake-agent 向け controlled experiment)**: permission proxy の branch が side effect を制御することを検証する決定論的テスト。実 Gemini CLI を使わないため常に実行される。

#### 実 Gemini CLI 向けの証跡取得フロー(AC1: Issue #113)

実 Gemini CLI が存在し pre-authenticated の場合、以下の環境変数が自動設定される:

| 環境変数 | 既定値 | 用途 |
|---|---|---|
| `GEMINI_ACP_DEBUG` | `1` | `gemini --acp --debug` を有効化し ACP JSON-RPC ログを stderr に記録 |
| `GEMINI_TELEMETRY_ENABLED` | `true` | gemini CLI の telemetry 出力を有効化 |
| `GEMINI_TELEMETRY_TARGET` | `local` | ローカルファイルへの telemetry 書き出し |
| `GEMINI_TELEMETRY_OUTFILE` | `artifacts/runtime-verification-AC7-<TIMESTAMP>.telemetry.json` | telemetry 出力先 |

呼び出し元が `GEMINI_TELEMETRY_ENABLED=false` をエクスポートすることで telemetry を無効化できる(CI 環境等)。

#### telemetry.json 証跡の PR 引用規約(AC4: Issue #113)

`artifacts/runtime-verification-AC7-<TIMESTAMP>.telemetry.json` を PR 本文 `## Runtime Verification Evidence` セクションに引用する際は、以下の **redact ルール** を適用する:

| 引用すべき内容 | 引用禁止(redact)する内容 |
|---|---|
| `gemini --version` / OS 情報 | HOME / token / OAuth identifier |
| コマンド形状: `gemini --acp --debug` | absolute local path(フルパス) |
| initialize / session/new / session/prompt が観測された事実 | prompt 全文 |
| scenario verdict(PASS / FAIL / SKIP) | telemetry.json 全文の貼り付け |

**禁止**: `telemetry.json` の full content を PR 本文に貼り付けること(token / OAuth 情報漏洩リスク)。
**必須**: 観測した ACP イベント種別の列挙(`initialize`, `session/new`, `session/prompt` 等)と verdict のみを引用する。

---

## 6. Stop Condition 連動
Expand Down
Loading