From 11698dfa72403c966f2148633e5ac52afc413429 Mon Sep 17 00:00:00 2001 From: Souleymane Sidibe <936370+soulesidibe@users.noreply.github.com> Date: Thu, 26 Nov 2026 09:47:55 +0000 Subject: [PATCH 1/4] bl-205: Gemini merge risk reviewer in runner-acp, a read only mode of the ACP runner --- .../loop/runner/acp/AcpPermissionPolicy.kt | 12 +- .../main/kotlin/loop/runner/acp/AcpRunner.kt | 11 +- .../kotlin/loop/runner/acp/AcpSettings.kt | 21 + .../loop/runner/acp/GeminiRiskReviewer.kt | 133 ++++++ .../loop/runner/acp/GeminiRiskReviewerTest.kt | 442 ++++++++++++++++++ 5 files changed, 613 insertions(+), 6 deletions(-) create mode 100644 plugins/runner-acp/src/main/kotlin/loop/runner/acp/GeminiRiskReviewer.kt create mode 100644 plugins/runner-acp/src/test/kotlin/loop/runner/acp/GeminiRiskReviewerTest.kt diff --git a/plugins/runner-acp/src/main/kotlin/loop/runner/acp/AcpPermissionPolicy.kt b/plugins/runner-acp/src/main/kotlin/loop/runner/acp/AcpPermissionPolicy.kt index 8acda3ee..c385f177 100644 --- a/plugins/runner-acp/src/main/kotlin/loop/runner/acp/AcpPermissionPolicy.kt +++ b/plugins/runner-acp/src/main/kotlin/loop/runner/acp/AcpPermissionPolicy.kt @@ -21,6 +21,10 @@ import java.util.Locale * * Uses the shared matchers from `plugins/runner-process` ([DeniedCommands], [HoldoutFolder], and * [ProtectedWorkspaceRoots]). This is a guardrail, not an OS sandbox. + * + * With [readOnly], the mode of the Gemini merge risk reviewer (bl-205), every command, write, edit, delete, move and MCP + * tool is declined, with [READ_ONLY] when no other rule refuses it first; reads and searches keep their rules, so only + * the holdout folder is refused to them. */ internal class AcpPermissionPolicy( private val workspace: Path, @@ -30,6 +34,7 @@ internal class AcpPermissionPolicy( private val launcher: String? = null, /** Internal Loop directories (isolated `--gemini-dir`, attempt folder) that the agent must never modify. */ private val protectedWriteDirs: () -> List = { emptyList() }, + private val readOnly: Boolean = false, ) { sealed interface Answer { /** Send [line] to the agent stdin and log [note] as a `loop:` stderr line (never quoting request data). */ @@ -79,9 +84,9 @@ internal class AcpPermissionPolicy( val refusal = when { - isMcpTool(name) -> evaluateMcp(name!!) - isCommandTool(name, kind) -> evaluateCommand(rawInput, args, locations, cwd) - isWriteTool(name, kind) -> evaluateFileWrite(rawInput, args, locations, cwd) + isMcpTool(name) -> if (readOnly) READ_ONLY else evaluateMcp(name!!) + isCommandTool(name, kind) -> evaluateCommand(rawInput, args, locations, cwd) ?: READ_ONLY.takeIf { readOnly } + isWriteTool(name, kind) -> evaluateFileWrite(rawInput, args, locations, cwd) ?: READ_ONLY.takeIf { readOnly } isReadTool(name, kind) -> evaluateFileRead(rawInput, args, locations, cwd) kind == "think" -> null else -> UNSUPPORTED_TOOL @@ -412,5 +417,6 @@ internal class AcpPermissionPolicy( const val NON_LOOP_MCP: String = "strict_mcp declines non-Loop MCP tools" const val UNSUPPORTED_TOOL: String = "the tool is not allowed by Loop's fail-closed permission policy" const val NO_ALLOW_OPTION: String = "no allow option was offered" + const val READ_ONLY: String = "the merge risk reviewer runs read only" } } diff --git a/plugins/runner-acp/src/main/kotlin/loop/runner/acp/AcpRunner.kt b/plugins/runner-acp/src/main/kotlin/loop/runner/acp/AcpRunner.kt index 86d5d436..00e310b3 100644 --- a/plugins/runner-acp/src/main/kotlin/loop/runner/acp/AcpRunner.kt +++ b/plugins/runner-acp/src/main/kotlin/loop/runner/acp/AcpRunner.kt @@ -52,6 +52,9 @@ import kotlin.time.TimeSource * Under `preset: agy`, strips Google API keys from the inherited host environment by default (an * operator can still opt in through `agent.env`), enforces the pinned `agy` major version `1` on * `initialize`, pins `runners.acp.model` with `session/set_model`, and escapes leading `/` prompts. + * + * With [AcpSettings.readOnly] (bl-205, the Gemini merge risk reviewer), the permission policy is read only, no + * `mcpServers` are passed, a session never resumes and its isolated folder is removed when it stops, never kept. */ class AcpRunner internal constructor( internal val settings: AcpSettings, @@ -112,6 +115,7 @@ class AcpRunner internal constructor( ctx: AttemptContext, runtimeSessionId: String, ): AgentSession? { + if (settings.readOnly) return null if (!settings.isAgyPreset) return AcpSession(ctx, resumeFrom = runtimeSessionId) val roots = isolationRoots(agentEnv(ctx)) AgyIsolationDir.sweepStale(roots.home, roots.loopHome).forEach { warn(ctx, it) } @@ -198,6 +202,7 @@ class AcpRunner internal constructor( strictMcp = settings.strictMcp, launcher = ctx.env["LOOP_LAUNCHER"], protectedWriteDirs = ::internalProtectedDirs, + readOnly = settings.readOnly, ) private val telemetry = AcpTelemetry(isAgyPreset = settings.isAgyPreset) @@ -352,11 +357,11 @@ class AcpRunner internal constructor( /** * At the stop, keeps the folder of a session that reported its runtime session id, so a respawn or a later - * attempt can load it (bl-213), and deletes any other. + * attempt can load it (bl-213), and deletes any other, and every folder of a read only session. */ private fun releaseIsolationDir() { val dir = isolationDir ?: return - if (dir.keep()) { + if (!settings.readOnly && dir.keep()) { isolationDir = null } else { deleteIsolationDir() @@ -431,7 +436,7 @@ class AcpRunner internal constructor( ProtectedRootsCheck.refusal(ctx.workspace, ctx.baseRef)?.let { return fail(null, it) } } val mcpEnv = ctx.env + mapOf(ENV_SESSION_ID to sessionId.value, ENV_TURN_ID to turnId.value) - val mcpServers = AcpMcpConfig.mcpServers(mcpEnv) + val mcpServers = if (settings.readOnly) JsonArray(emptyList()) else AcpMcpConfig.mcpServers(mcpEnv) sessionMcpServers = mcpServers pendingResume?.let { resumed -> val refusal = isolationDir?.checkBeforeLoad() diff --git a/plugins/runner-acp/src/main/kotlin/loop/runner/acp/AcpSettings.kt b/plugins/runner-acp/src/main/kotlin/loop/runner/acp/AcpSettings.kt index 685cae8f..e0751fde 100644 --- a/plugins/runner-acp/src/main/kotlin/loop/runner/acp/AcpSettings.kt +++ b/plugins/runner-acp/src/main/kotlin/loop/runner/acp/AcpSettings.kt @@ -16,6 +16,10 @@ import kotlin.time.Duration.Companion.milliseconds * (bare or by path, with no extra flags) and [model] is required and must start with `gemini-`. * Without a preset, [model] is forbidden and [strictMcp] must be false because Loop cannot isolate an * unknown ACP agent's MCP configuration. + * + * [readOnly], which is not a profile key, is the mode of the Gemini merge risk reviewer (bl-205): the permission policy + * declines every command, write, edit, delete, move and MCP tool, no Loop tool is passed and the isolated folder is + * never kept. */ data class AcpSettings( val command: String, @@ -25,6 +29,7 @@ data class AcpSettings( val readTimeout: Duration = DEFAULT_READ_TIMEOUT_MS.milliseconds, val strictMcp: Boolean = true, val holdoutDir: Path? = null, + val readOnly: Boolean = false, ) { /** [command] split into the words the runner launches; throws [RunnerConfigException]. */ val argv: List get() = CommandWords.of(command, "runners.$SECTION.command") @@ -68,6 +73,22 @@ data class AcpSettings( private const val AGY_SUBCOMMAND: String = "acp" private const val GEMINI_MODEL_PREFIX: String = "gemini-" + /** The command of a Gemini merge risk reviewer whose workflow sets none (bl-205). */ + const val DEFAULT_AGY_COMMAND: String = "$AGY_PROGRAM $AGY_SUBCOMMAND" + + /** + * [words] joined into a command that [CommandWords] splits back into them: a word of letters, digits, `-` and `_` + * stays bare, any other is put in single quotes. + */ + fun commandOf(words: List): String = + words.joinToString(" ") { word -> + if (word.isNotEmpty() && word.all { it.isLetterOrDigit() || it in "-_" }) { + word + } else { + "'" + word.replace("'", "'\\''") + "'" + } + } + /** The plugin profile of `runners.acp`. */ val PROFILE: PluginProfile = PluginProfile( diff --git a/plugins/runner-acp/src/main/kotlin/loop/runner/acp/GeminiRiskReviewer.kt b/plugins/runner-acp/src/main/kotlin/loop/runner/acp/GeminiRiskReviewer.kt new file mode 100644 index 00000000..637b4dc9 --- /dev/null +++ b/plugins/runner-acp/src/main/kotlin/loop/runner/acp/GeminiRiskReviewer.kt @@ -0,0 +1,133 @@ +package loop.runner.acp + +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.withTimeoutOrNull +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive +import loop.api.AttemptContext +import loop.api.AttemptId +import loop.api.Issue +import loop.api.LedgerTokens +import loop.api.ProjectId +import loop.api.RiskReview +import loop.api.RiskReviewError +import loop.api.RiskReviewRequest +import loop.api.RiskReviewer +import loop.api.RunId +import loop.api.RunnerEvent +import loop.api.RunnerEvent.Output.Stream +import kotlin.time.Duration.Companion.milliseconds + +/** + * The merge risk reviewer of Gemini (bl-205), the `agy` twin of the Codex one: one `agy acp` turn under `preset: agy` in + * the issue workspace, run by [AcpRunner] with [settings], so the version pin, the isolated `--gemini-dir`, `--sandbox`, + * strict MCP, the protected roots check and the env policy ([hostEnv] minus [removedEnvNames]) are the runner's. Each + * review sets the model of the request with `session/set_model` and runs [AcpSettings.readOnly]: every command and every + * write, edit, delete or move is declined, reads and searches are allowed except under the holdout folder of [settings], + * and no Loop tool is passed. A review never resumes, and its isolated folder is removed when it ends. + * + * The answer is the text of the turn's final agent message, its `agent_message_chunk` texts after the last tool call, + * with the session's tokens and no cost, which ACP does not report. A turn past [RiskReviewRequest.timeoutMs] is stopped, + * with its `agy`, and is a [RiskReviewError.Timeout]; a turn that fails, asks for input, cannot start or ends with no + * agent message is a [RiskReviewError.Crashed]. + */ +class GeminiRiskReviewer( + private val settings: AcpSettings, + private val hostEnv: Map = System.getenv(), + private val removedEnvNames: Set = emptySet(), +) : RiskReviewer { + override suspend fun review(request: RiskReviewRequest): Result { + val reviewSettings = + settings.copy( + preset = AcpSettings.PRESET_AGY, + model = request.model, + strictMcp = true, + readOnly = true, + turnTimeout = request.timeoutMs.coerceIn(1, AcpSettings.MAX_TIMEOUT_MS).milliseconds, + ) + val runner = AcpRunner(reviewSettings, hostEnv, removedEnvNames) + val answer = Answer() + val end = + try { + withTimeoutOrNull(request.timeoutMs) { + var terminal: RunnerEvent? = null + runner.run(context(request), request.prompt).collect { event -> + answer.read(event) + if (event.isTerminal()) terminal = event + } + terminal + } ?: return Result.failure(RiskReviewError.Timeout("no answer within ${request.timeoutMs} ms")) + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + return Result.failure(RiskReviewError.Crashed("agy cannot run the review: ${e.message}", e)) + } + return when (end) { + is RunnerEvent.TurnCompleted -> + answer.text?.let { Result.success(RiskReview(it, answer.tokens, null)) } + ?: Result.failure(RiskReviewError.Crashed("agy ended the turn with no answer")) + is RunnerEvent.TurnFailed -> Result.failure(RiskReviewError.Crashed("agy ended in error: ${end.reason.take(DETAIL_MAX)}")) + is RunnerEvent.TurnInputRequired -> + Result.failure(RiskReviewError.Crashed("agy asked for input, which a review cannot give: ${end.reason}")) + else -> Result.failure(RiskReviewError.Crashed("agy ended the turn with no terminal event")) + } + } + + /** What the review collected from the runner's events: the agent's final message and the session's tokens. */ + private class Answer { + private val message = StringBuilder() + var tokens: LedgerTokens? = null + private set + + /** The text of the agent message after the last tool call; null when the agent wrote none. */ + val text: String? get() = message.toString().takeIf { it.isNotBlank() } + + fun read(event: RunnerEvent) { + when (event) { + is RunnerEvent.Usage -> + tokens = LedgerTokens(event.inputTokens, event.outputTokens, event.cacheReadInputTokens, event.cacheCreationInputTokens) + is RunnerEvent.Output -> if (event.stream == Stream.Stdout) update(event.line) + else -> Unit + } + } + + /** Reads a `session/update` on [line], a protocol line of `agy`: a message chunk adds to it, a tool call ends it. */ + private fun update(line: String) { + if (SESSION_UPDATE !in line) return + val frame = AcpFraming.decode(line) as? AcpFrame.Notification ?: return + if (frame.method != AcpHandshake.METHOD_SESSION_UPDATE) return + val update = (frame.params as? JsonObject)?.get("update") as? JsonObject ?: return + when (update.string("sessionUpdate")) { + AGENT_MESSAGE_CHUNK -> (update["content"] as? JsonObject)?.string("text")?.let { message.append(it) } + TOOL_CALL, TOOL_CALL_UPDATE -> message.clear() + } + } + + private fun JsonObject.string(key: String): String? = (get(key) as? JsonPrimitive)?.takeIf { it.isString }?.content + } + + private fun RunnerEvent.isTerminal(): Boolean = + this is RunnerEvent.TurnCompleted || this is RunnerEvent.TurnFailed || this is RunnerEvent.TurnInputRequired + + /** The attempt the runner needs: the review's workspace, ids of its own and an empty env, so no Loop tool is passed. */ + private fun context(request: RiskReviewRequest): AttemptContext = + AttemptContext( + runId = RunId(REVIEW_ID), + projectId = ProjectId(REVIEW_ID), + issue = Issue(REVIEW_ID, REVIEW_ID, "merge risk review", "review", null, emptyList(), emptyList(), null, null), + attemptId = AttemptId(REVIEW_ID), + workspace = request.workspace, + env = emptyMap(), + ) + + override fun toString(): String = "GeminiRiskReviewer(command=${settings.command})" + + private companion object { + const val REVIEW_ID = "merge-risk-review" + const val SESSION_UPDATE = "session/update" + const val AGENT_MESSAGE_CHUNK = "agent_message_chunk" + const val TOOL_CALL = "tool_call" + const val TOOL_CALL_UPDATE = "tool_call_update" + const val DETAIL_MAX = 300 + } +} diff --git a/plugins/runner-acp/src/test/kotlin/loop/runner/acp/GeminiRiskReviewerTest.kt b/plugins/runner-acp/src/test/kotlin/loop/runner/acp/GeminiRiskReviewerTest.kt new file mode 100644 index 00000000..dca754b3 --- /dev/null +++ b/plugins/runner-acp/src/test/kotlin/loop/runner/acp/GeminiRiskReviewerTest.kt @@ -0,0 +1,442 @@ +package loop.runner.acp + +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.withTimeout +import kotlinx.serialization.json.JsonArray +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.buildJsonArray +import kotlinx.serialization.json.buildJsonObject +import kotlinx.serialization.json.jsonArray +import kotlinx.serialization.json.jsonObject +import kotlinx.serialization.json.jsonPrimitive +import kotlinx.serialization.json.put +import loop.api.LedgerTokens +import loop.api.RiskReview +import loop.api.RiskReviewError +import loop.api.RiskReviewRequest +import org.junit.jupiter.api.io.TempDir +import java.nio.file.Files +import java.nio.file.Path +import kotlin.io.path.createDirectories +import kotlin.io.path.exists +import kotlin.io.path.readLines +import kotlin.io.path.writeText +import kotlin.test.Test +import kotlin.test.assertContains +import kotlin.test.assertEquals +import kotlin.test.assertIs +import kotlin.test.assertTrue +import kotlin.time.Duration.Companion.seconds + +/** + * bl-205: the merge risk reviewer of Gemini, the `agy` twin of the Codex reviewer. It runs one `agy acp` turn under + * `preset: agy` in the issue workspace with the model of `risk.reviewer`, declines every command and every edit, allows + * reads except under the holdout folder, passes no Loop tool, and answers with the text of the turn's final agent + * message and the session's tokens. Each server is a [FakeAcpServer]. + */ +class GeminiRiskReviewerTest { + @TempDir + lateinit var workspace: Path + + @TempDir + lateinit var dir: Path + + @TempDir + lateinit var home: Path + + private val holdout: Path by lazy { + dir.resolve("loop-home/holdout").createDirectories().also { it.resolve("check.sh").writeText("exit 0\n") } + } + + private val verdict = """{"dimensions":{"impact":{"verdict":"low"}}}""" + + @Test + fun `bl-205 the answer is the text of the final agent message, with the session tokens and no cost`() { + val server = + FakeAcpServer.write(dir) { + handshake() + awaitClient() + agentChunk("Reading the diff first.") + toolCall("read_file") + agentChunk(verdict.substring(0, 10)) + agentChunk(verdict.substring(10)) + response(4, promptResult(inputTokens = 3_119, outputTokens = 5, cachedRead = 12_288)) + } + + val review = review(server).getOrThrow() + + assertEquals(RiskReview(verdict, LedgerTokens(3_119, 5, 12_288, 0), null), review) + } + + @Test + fun `bl-205 the session runs the reviewer model in the workspace with no Loop tool, the prompt as its input`() { + val server = + FakeAcpServer.write(dir) { + handshake(model = "gemini-4-neon-xhigh") + awaitClient() + agentChunk(verdict) + response(4, promptResult()) + } + + review(server, model = "gemini-4-neon-xhigh").getOrThrow() + + val sent = received(server) + val new = sent.single { it.method == "session/new" }.getValue("params").jsonObject + assertEquals(workspace.toAbsolutePath().toString(), new.getValue("cwd").jsonPrimitive.content) + assertEquals(JsonArray(emptyList()), new.getValue("mcpServers").jsonArray, "a reviewer passes no Loop tool") + val setModel = sent.single { it.method == "session/set_model" }.getValue("params").jsonObject + assertEquals("gemini-4-neon-xhigh", setModel.getValue("modelId").jsonPrimitive.content) + val prompt = sent.single { it.method == "session/prompt" }.getValue("params").jsonObject + assertContains(prompt.getValue("prompt").toString(), "Review this pull request.") + } + + @Test + fun `bl-205 a command is declined, even a plain read, since the reviewer runs read only`() { + val server = + FakeAcpServer.write(dir) { + handshake() + awaitClient() + permission(101, "run_command", "execute", "rawInput" to buildJsonObject { put("CommandLine", "cat README.md") }) + awaitClient() + permission(102, "run_command", "execute", "rawInput" to buildJsonObject { put("CommandLine", "./gradlew test") }) + awaitClient() + agentChunk(verdict) + response(4, promptResult()) + } + + assertEquals(verdict, review(server).getOrThrow().text) + + assertEquals(mapOf("101" to "reject_once", "102" to "reject_once"), answers(server)) + } + + @Test + fun `bl-205 an edit, a write, a delete and a move are declined`() { + val file = workspace.resolve("src/Main.kt").toString() + val server = + FakeAcpServer.write(dir) { + handshake() + awaitClient() + permission(101, "replace_file_content", "edit", "rawInput" to buildJsonObject { put("TargetFile", file) }) + awaitClient() + permission(102, "write_to_file", "edit", "rawInput" to buildJsonObject { put("TargetFile", file) }) + awaitClient() + permission(103, null, "delete", "locations" to locations(file)) + awaitClient() + permission(104, null, "move", "locations" to locations(file)) + awaitClient() + agentChunk(verdict) + response(4, promptResult()) + } + + assertEquals(verdict, review(server).getOrThrow().text) + + assertEquals( + mapOf("101" to "reject_once", "102" to "reject_once", "103" to "reject_once", "104" to "reject_once"), + answers(server), + ) + } + + @Test + fun `bl-205 a read and a search in the workspace are allowed, a read of the holdout folder is refused`() { + val server = + FakeAcpServer.write(dir) { + handshake() + awaitClient() + permission(101, "view_file", "read", "rawInput" to buildJsonObject { put("Path", workspace.resolve("a.kt").toString()) }) + awaitClient() + permission( + 102, + "grep_search", + "search", + "rawInput" to buildJsonObject { put("SearchPath", workspace.toAbsolutePath().toString()) }, + ) + awaitClient() + permission(103, "view_file", "read", "rawInput" to buildJsonObject { put("Path", holdout.resolve("check.sh").toString()) }) + awaitClient() + agentChunk(verdict) + response(4, promptResult()) + } + + assertEquals(verdict, review(server).getOrThrow().text) + + assertEquals(mapOf("101" to "allow_once", "102" to "allow_once", "103" to "reject_once"), answers(server)) + } + + @Test + fun `bl-205 a Loop MCP tool is declined, since a review passes none`() { + val server = + FakeAcpServer.write(dir) { + handshake() + awaitClient() + permission(101, "mcp_loop_move", null) + awaitClient() + agentChunk(verdict) + response(4, promptResult()) + } + + review(server).getOrThrow() + + assertEquals(mapOf("101" to "reject_once"), answers(server)) + } + + @Test + fun `bl-205 a failed turn is a crash naming the reason`() { + val server = + FakeAcpServer.write(dir) { + handshake() + awaitClient() + agentChunk("Half an answer") + error(4, -32603, "internal error") + } + + val error = assertIs(review(server).exceptionOrNull()) + + assertContains(error.message.orEmpty(), "agy ended in error: turn_failed: internal error") + } + + @Test + fun `bl-205 a turn with no agent message is a crash`() { + val server = + FakeAcpServer.write(dir) { + handshake() + awaitClient() + toolCall("read_file") + response(4, promptResult()) + } + + val error = assertIs(review(server).exceptionOrNull()) + + assertEquals("agy ended the turn with no answer", error.message) + } + + @Test + fun `bl-205 a request for input is a crash`() { + val server = + FakeAcpServer.write(dir) { + handshake() + awaitClient() + request(201, "session/request_user_input", buildJsonObject { put("prompt", "Which one?") }) + shell("sleep 30") + } + + val error = assertIs(review(server).exceptionOrNull()) + + assertContains(error.message.orEmpty(), "agy asked for input, which a review cannot give") + } + + @Test + fun `bl-205 a turn past the time limit is a timeout, its agy stopped`() { + val pidFile = dir.resolve("agy.pid") + val server = + FakeAcpServer.write(dir) { + shell("echo $$ > '$pidFile'") + handshake() + awaitClient() + shell("sleep 30") + } + + val started = System.nanoTime() + val error = assertIs(review(server, timeoutMs = 2_000).exceptionOrNull()) + val elapsed = (System.nanoTime() - started) / 1_000_000 + + assertEquals("no answer within 2000 ms", error.message) + assertTrue(elapsed < 15_000, "the review stops at its limit, not when agy would end: $elapsed ms") + val pid = Files.readString(pidFile).trim().toLong() + assertTrue( + ProcessHandle.of(pid).map { !it.isAlive }.orElse(true), + "the agy process of a timed out review is stopped", + ) + } + + @Test + fun `bl-205 a command that cannot start is a crash`() { + val reviewer = + GeminiRiskReviewer( + settings(command = "'${dir.resolve("missing/agy")}' acp"), + hostEnv = hostEnv(), + ) + + val result = runBlocking { reviewer.review(RiskReviewRequest(workspace, MODEL, "Review this pull request.", 10_000)) } + + assertIs(result.exceptionOrNull()) + } + + @Test + fun `bl-205 a review never keeps its isolated folder, even after the session reported its id`() { + val server = + FakeAcpServer.write(dir) { + handshake() + awaitClient() + agentChunk(verdict) + response(4, promptResult()) + } + + review(server).getOrThrow() + + val root = home.resolve(AgyIsolationDir.FALLBACK_ROOT_NAME) + val left = if (root.exists()) Files.list(root).use { it.toList() } else emptyList() + assertEquals(emptyList(), left, "the isolated folder is removed when the review ends") + } + + @Test + fun `bl-205 toString names the command`() { + assertEquals("GeminiRiskReviewer(command='/opt/agy' acp)", GeminiRiskReviewer(settings(command = "'/opt/agy' acp")).toString()) + } + + @Test + fun `bl-205 commandOf quotes a word only when it needs it, and the runner splits it back`() { + val words = listOf("/Applications/My Tools/it's/agy", "acp") + + val command = AcpSettings.commandOf(words) + + assertEquals("'/Applications/My Tools/it'\\''s/agy' acp", command) + assertEquals(words, CommandWords.of(command, "runners.acp.command")) + } + + private fun review( + server: FakeAcpServer, + model: String = MODEL, + timeoutMs: Long = 15_000, + ): Result = + runBlocking { + withTimeout(30.seconds) { + GeminiRiskReviewer(settings(server.agyCommand), hostEnv()) + .review(RiskReviewRequest(workspace, model, "Review this pull request.", timeoutMs)) + } + } + + private fun settings(command: String): AcpSettings = + AcpSettings( + command = command, + preset = AcpSettings.PRESET_AGY, + model = "gemini-4-neon-low", + readTimeout = FakeAcpServer.READ_TIMEOUT, + holdoutDir = holdout, + ) + + private fun hostEnv(): Map = mapOf("PATH" to System.getenv("PATH"), "HOME" to home.toString()) + + private fun FakeAcpServer.Script.handshake(model: String = MODEL) { + initialize(id = 1) + sessionNew(id = 2, sessionId = SESSION) + sessionSetModel(id = 3, configUpdateModelId = model, sessionId = SESSION) + } + + private fun FakeAcpServer.Script.agentChunk(text: String) = + update( + buildJsonObject { + put("sessionUpdate", "agent_message_chunk") + put( + "content", + buildJsonObject { + put("type", "text") + put("text", text) + }, + ) + }, + ) + + private fun FakeAcpServer.Script.toolCall(name: String) = + update( + buildJsonObject { + put("sessionUpdate", "tool_call") + put("toolCallId", "call-1") + put("name", name) + }, + ) + + private fun FakeAcpServer.Script.update(update: JsonObject) = + notification( + AcpHandshake.METHOD_SESSION_UPDATE, + buildJsonObject { + put("sessionId", SESSION) + put("update", update) + }, + ) + + private fun FakeAcpServer.Script.permission( + id: Long, + name: String?, + kind: String?, + vararg fields: Pair, + ) = request( + id, + AcpHandshake.METHOD_REQUEST_PERMISSION, + buildJsonObject { + put("sessionId", SESSION) + put( + "toolCall", + buildJsonObject { + if (name != null) put("name", name) + if (kind != null) put("kind", kind) + fields.forEach { (key, value) -> put(key, value) } + }, + ) + put("options", OPTIONS) + }, + ) + + private fun locations(path: String): JsonArray = buildJsonArray { add(buildJsonObject { put("path", path) }) } + + private fun promptResult( + inputTokens: Long = 10, + outputTokens: Long = 1, + cachedRead: Long = 0, + ): JsonObject = + buildJsonObject { + put("stopReason", "end_turn") + put( + "usage", + buildJsonObject { + put("inputTokens", inputTokens) + put("outputTokens", outputTokens) + put("cachedReadTokens", cachedRead) + put("cachedWriteTokens", 0) + }, + ) + } + + private fun received(server: FakeAcpServer): List = + server.received + .readLines() + .filter { it.isNotBlank() } + .map { AcpFraming.json.parseToJsonElement(it).jsonObject } + + /** The option Loop selected for each permission request, by request id. */ + private fun answers(server: FakeAcpServer): Map = + received(server) + .filter { "result" in it } + .associate { + it.getValue("id").jsonPrimitive.content to + it + .getValue("result") + .jsonObject + .getValue("outcome") + .jsonObject + .getValue("optionId") + .jsonPrimitive.content + } + + private val JsonObject.method: String? get() = get("method")?.jsonPrimitive?.content + + private companion object { + const val SESSION = "review-session-1" + const val MODEL = "gemini-4-neon-high" + + val OPTIONS = + buildJsonArray { + add( + buildJsonObject { + put("optionId", "allow_once") + put("kind", "allow_once") + }, + ) + add( + buildJsonObject { + put("optionId", "reject_once") + put("kind", "reject_once") + }, + ) + } + } +} From 365d60f45edd6c872b26260dc58819e2924d0b83 Mon Sep 17 00:00:00 2001 From: Souleymane Sidibe <936370+soulesidibe@users.noreply.github.com> Date: Thu, 26 Nov 2026 09:51:01 +0000 Subject: [PATCH 2/4] bl-205: a gemini- reviewer model picks the Gemini merge risk reviewer, with the agy startup warning --- cli/src/main/kotlin/loop/cli/Host.kt | 56 ++++++++++-- .../kotlin/loop/cli/RiskReviewerRuntime.kt | 12 ++- .../kotlin/loop/cli/DeliveryExecutorsTest.kt | 85 +++++++++++++++++++ .../loop/cli/RiskReviewerRuntimeTest.kt | 21 ++++- .../loop/cli/RiskReviewerWarningTest.kt | 21 +++++ 5 files changed, 186 insertions(+), 9 deletions(-) diff --git a/cli/src/main/kotlin/loop/cli/Host.kt b/cli/src/main/kotlin/loop/cli/Host.kt index dd0eb245..9c31506d 100644 --- a/cli/src/main/kotlin/loop/cli/Host.kt +++ b/cli/src/main/kotlin/loop/cli/Host.kt @@ -22,6 +22,7 @@ import loop.core.workflow.WorkflowFile import loop.core.workflow.WorkflowLoader import loop.runner.acp.AcpSettings import loop.runner.acp.AgyPreflight +import loop.runner.acp.GeminiRiskReviewer import loop.runner.claudecode.ClaudeCodePreflight import loop.runner.claudecode.ClaudeCodeRiskReviewer import loop.runner.claudecode.ClaudeCodeSettings @@ -445,9 +446,10 @@ fun runnerFor( * The read only reviewer of the merge risk assessment (m2-28), whatever `runner.kind` is (m4-06, bl-145), since the * reviewer is a concern apart from the runner that did the work: the model the workflow names in `risk.reviewer` picks * its runtime ([RiskReviewerRuntime], bl-214). A Codex model gets Codex's reviewer, with the settings of `runners.codex` - * ([codexReviewerSettings]); any other model Claude Code's, with the [riskReviewerCommand]. The program is resolved as - * [resolveCommand] does, so the reviewer starts exactly the file the startup check found; null when it cannot be found, - * or `runners.codex` cannot be read, so the auto merge gate falls back naming the reviewer setup, and the startup warns + * ([codexReviewerSettings]); a Gemini model Gemini's (bl-205), with [geminiReviewerSettings]; any other model Claude + * Code's, with the [riskReviewerCommand]. The program is resolved as [resolveCommand] does, so the reviewer starts exactly + * the file the startup check found; null when it cannot be found, or the runner section cannot be read, so the auto + * merge gate falls back naming the reviewer setup, and the startup warns * ([riskReviewerWarning]). Its env is the agent env policy and it refuses reads under [holdoutDir], like an agent. */ fun riskReviewerFor( @@ -469,6 +471,14 @@ fun riskReviewerFor( CodexRiskReviewer(settings.copy(command = command), hostEnv, removedEnvNames) } } + RiskReviewerRuntime.Gemini -> { + val settings = geminiReviewerSettings(workflow, holdoutDir).getOrNull() + val argv = settings?.argv + argv?.let { resolveCommand(it.first(), hostEnv) }?.let { program -> + val command = AcpSettings.commandOf(listOf(program) + argv.drop(1)) + GeminiRiskReviewer(settings.copy(command = command), hostEnv, removedEnvNames) + } + } } /** bl-214: the runtime of the merge risk reviewer of [workflow], from the model of `risk.reviewer`. */ @@ -498,16 +508,46 @@ fun codexReviewerSettings( } /** - * The program the merge risk reviewer runs (m4-06, bl-214). For a Claude Code reviewer: under `runner.kind: + * bl-205: the settings of the Gemini merge risk reviewer, with [holdoutDir]. Under `runner.kind: acp` with `preset: agy` + * they are `runners.acp` read as the ACP runner reads it, which the loader already checked: its `command`, + * `read_timeout_ms` and `strict_mcp` apply. Under any other runner they are the defaults with `agy acp`. The model and + * the time limit are always the review's. + */ +fun geminiReviewerSettings( + workflow: WorkflowFile, + holdoutDir: Path? = null, +): Result = + runCatching { + val settings = + if (geminiReviewerOwnsCommand(workflow)) { + AcpSettings.of(workflow.runner.section(AcpSettings.SECTION), holdoutDir) + } else { + AcpSettings(command = AcpSettings.DEFAULT_AGY_COMMAND, preset = AcpSettings.PRESET_AGY, holdoutDir = holdoutDir) + } + settings.also { it.argv } + } + +/** bl-205: true when the Gemini reviewer's command is `runners.acp.command`, the runner being `acp` with `preset: agy`. */ +private fun geminiReviewerOwnsCommand(workflow: WorkflowFile): Boolean = + workflow.runner.kind == AcpSettings.KIND && + (workflow.runner.sections[AcpSettings.SECTION] as? Map<*, *>)?.get("preset")?.let { it as? String }?.trim() == + AcpSettings.PRESET_AGY + +/** + * The program the merge risk reviewer runs (m4-06, bl-214, bl-205). For a Claude Code reviewer: under `runner.kind: * claude-code` the command of its section, which the loader checked; under any other runner `runners.claude-code.command` * when it is set and not blank, else [DEFAULT_REVIEWER_COMMAND]. For a Codex reviewer: the first word of the command of - * [codexReviewerSettings], or [CodexAppServerSettings.DEFAULT_COMMAND]'s when the section cannot be read. + * [codexReviewerSettings], or [CodexAppServerSettings.DEFAULT_COMMAND]'s when the section cannot be read. For a Gemini + * reviewer: the first word of the command of [geminiReviewerSettings], or `agy` when it cannot be read. */ fun riskReviewerCommand(workflow: WorkflowFile): String = when (riskReviewerRuntime(workflow)) { RiskReviewerRuntime.Codex -> codexReviewerSettings(workflow).getOrNull()?.argv?.first() ?: CodexAppServerSettings.DEFAULT_COMMAND.substringBefore(' ') + RiskReviewerRuntime.Gemini -> + geminiReviewerSettings(workflow).getOrNull()?.argv?.first() + ?: AcpSettings.DEFAULT_AGY_COMMAND.substringBefore(' ') RiskReviewerRuntime.ClaudeCode -> if (workflow.runner.kind == ClaudeCodeSettings.KIND) { ClaudeCodeSettings.of(workflow.runner.section(ClaudeCodeSettings.KIND)).command @@ -549,6 +589,12 @@ fun riskReviewerWarning( when (runtime) { RiskReviewerRuntime.ClaudeCode -> "Install Claude Code or set runners.claude-code.command" RiskReviewerRuntime.Codex -> "Install Codex or set runners.codex.command" + RiskReviewerRuntime.Gemini -> + if (geminiReviewerOwnsCommand(workflow)) { + "Install the Antigravity CLI or set runners.acp.command" + } else { + "Install the Antigravity CLI so agy is on PATH" + } } return "kinds.code.delivery.risk.reviewer is $model, but its command $command cannot be found, so no merge risk " + "reviewer can run and every result waits for loop approve. $fix" diff --git a/cli/src/main/kotlin/loop/cli/RiskReviewerRuntime.kt b/cli/src/main/kotlin/loop/cli/RiskReviewerRuntime.kt index 1fc6671b..fb69548f 100644 --- a/cli/src/main/kotlin/loop/cli/RiskReviewerRuntime.kt +++ b/cli/src/main/kotlin/loop/cli/RiskReviewerRuntime.kt @@ -3,7 +3,7 @@ package loop.cli /** * The runtime that runs the merge risk reviewer (bl-214), chosen by the model `kinds.code.delivery.risk.reviewer` names, * not by `runner.kind`: the reviewer is a concern apart from the runner that did the work (m4-06). [of] is the one place - * the choice is made, so a reviewer of another runtime (bl-205, Gemini) adds its value and its model names here. + * the choice is made, so a reviewer of another runtime adds its value and its model names here, as Gemini did (bl-205). */ enum class RiskReviewerRuntime { /** Claude Code, the reviewer of m2-28: every model no other runtime claims, aliases such as `sonnet` included. */ @@ -11,15 +11,23 @@ enum class RiskReviewerRuntime { /** Codex (bl-214): a model of the `gpt-` or `codex-` families, or of the `o` series such as `o3` and `o4-mini`. */ Codex, + + /** Gemini (bl-205), through `agy acp`: a model whose name starts with `gemini-`. */ + Gemini, ; companion object { private val CODEX_MODEL = Regex("""^(gpt-|codex-|o\d).*""") + private const val GEMINI_PREFIX = "gemini-" /** The runtime of [model], trimmed and in any case; [ClaudeCode] for a model no other runtime claims, or none. */ fun of(model: String?): RiskReviewerRuntime { val name = model?.trim()?.lowercase() ?: return ClaudeCode - return if (CODEX_MODEL.matches(name)) Codex else ClaudeCode + return when { + CODEX_MODEL.matches(name) -> Codex + name.startsWith(GEMINI_PREFIX) -> Gemini + else -> ClaudeCode + } } } } diff --git a/cli/src/test/kotlin/loop/cli/DeliveryExecutorsTest.kt b/cli/src/test/kotlin/loop/cli/DeliveryExecutorsTest.kt index 1711e129..cb86444f 100644 --- a/cli/src/test/kotlin/loop/cli/DeliveryExecutorsTest.kt +++ b/cli/src/test/kotlin/loop/cli/DeliveryExecutorsTest.kt @@ -6,6 +6,7 @@ import loop.api.RiskReviewError import loop.api.RiskReviewRequest import loop.core.workflow.WorkflowFile import loop.core.workflow.WorkflowLoader +import loop.runner.acp.GeminiRiskReviewer import loop.runner.claudecode.ClaudeCodeRiskReviewer import loop.runner.codex.CodexRiskReviewer import loop.tracker.github.GitHubResponse @@ -351,4 +352,88 @@ class DeliveryExecutorsTest { "codex is not on PATH, and claude does not stand in for it", ) } + + /** bl-205: a fake `agy` in [dir] that logs its arguments and directory to `agy.log`, then exits 1. */ + private fun fakeAgy(dir: Path): Path { + Files.createDirectories(dir) + val log = dir.resolve("agy.log") + return dir.resolve("agy").also { + it.writeText("#!/bin/sh\n{ echo \"ARGS \$*\"; echo \"PWD \$(pwd)\"; } >> '$log'\nexit 1\n") + Files.setPosixFilePermissions(it, PosixFilePermissions.fromString("rwxr-xr-x")) + } + } + + @Test + fun `bl-205 gemini-4-neon-high picks the Gemini reviewer, sonnet keeps Claude Code and gpt-6_1-sol keeps Codex`() { + val bin = root.resolve("bin-all") + val claude = fakeClaude(bin) + val codex = fakeCodex(bin) + val agy = fakeAgy(bin) + val host = mapOf("PATH" to "$bin:/usr/bin:/bin", "HOME" to root.toString()) + val runners = " claude-code:\n command: claude" + + assertEquals( + "GeminiRiskReviewer(command='$agy' acp)", + riskReviewerFor(autoMergeWorkflow("claude-code", runners, "gemini", "gemini-4-neon-high"), host, emptySet()).toString(), + ) + assertEquals( + "ClaudeCodeRiskReviewer(command=$claude)", + riskReviewerFor(autoMergeWorkflow("claude-code", runners, "sonnet", "sonnet"), host, emptySet()).toString(), + ) + assertEquals( + "CodexRiskReviewer(command='$codex' 'app-server')", + riskReviewerFor(autoMergeWorkflow("claude-code", runners, "gpt", "gpt-6.1-sol"), host, emptySet()).toString(), + ) + } + + @Test + fun `bl-205 a Gemini reviewer runs agy acp under preset agy, found on the host PATH, in the workspace`() = + runBlocking { + val bin = root.resolve("bin-agy") + fakeAgy(bin) + val workflow = + autoMergeWorkflow("codex-app-server", " codex:\n command: codex app-server", reviewer = "gemini-4-neon-high") + val host = mapOf("PATH" to "$bin:/usr/bin:/bin", "HOME" to root.toString()) + + val reviewer = assertIs(riskReviewerFor(workflow, host, emptySet())) + assertEquals( + "GeminiRiskReviewer(command='${bin.resolve("agy")}' acp)", + reviewer.toString(), + "the default command agy acp, its program found on the host PATH", + ) + + val workspace = Files.createDirectories(root.resolve("workspaces/t-3")).toRealPath() + val result = reviewer.review(RiskReviewRequest(workspace, "gemini-4-neon-high", "Review this.", 10_000)) + + assertIs(result.exceptionOrNull(), "the fake exits before any answer") + val logged = bin.resolve("agy.log").readText() + assertContains(logged, "ARGS acp --disable-telemetry --sandbox --gemini-dir ") + assertContains(logged, "PWD $workspace") + } + + @Test + fun `bl-205 under runner acp with preset agy the Gemini reviewer takes runners acp command`() { + val agy = fakeAgy(root.resolve("pinned agy")) + val workflow = + autoMergeWorkflow( + "acp", + " acp:\n command: \"'$agy' acp\"\n preset: agy\n model: gemini-4-neon-medium", + reviewer = "gemini-4-neon-high", + ) + + val reviewer = riskReviewerFor(workflow, mapOf("PATH" to "/usr/bin:/bin"), emptySet()) + + assertEquals("GeminiRiskReviewer(command='$agy' acp)", reviewer.toString()) + } + + @Test + fun `bl-205 a Gemini reviewer whose agy cannot be found gives no reviewer, so the gate falls back`() { + fakeClaude(root.resolve("only-claude-2")) + val workflow = autoMergeWorkflow("claude-code", " claude-code:\n command: claude", reviewer = "gemini-4-neon-high") + + assertNull( + riskReviewerFor(workflow, mapOf("PATH" to root.resolve("only-claude-2").toString()), emptySet()), + "agy is not on PATH, and claude does not stand in for it", + ) + } } diff --git a/cli/src/test/kotlin/loop/cli/RiskReviewerRuntimeTest.kt b/cli/src/test/kotlin/loop/cli/RiskReviewerRuntimeTest.kt index b280d2db..d778557b 100644 --- a/cli/src/test/kotlin/loop/cli/RiskReviewerRuntimeTest.kt +++ b/cli/src/test/kotlin/loop/cli/RiskReviewerRuntimeTest.kt @@ -3,7 +3,10 @@ package loop.cli import kotlin.test.Test import kotlin.test.assertEquals -/** bl-214: the model of `risk.reviewer` picks the runtime that runs the merge risk reviewer, Codex for a Codex model. */ +/** + * bl-214 and bl-205: the model of `risk.reviewer` picks the runtime that runs the merge risk reviewer, Codex for a Codex + * model and Gemini for a Gemini model. + */ class RiskReviewerRuntimeTest { @Test fun `bl-214 a gpt, codex or o series model runs on Codex, whatever its case`() { @@ -12,9 +15,23 @@ class RiskReviewerRuntimeTest { } } + @Test + fun `bl-205 a gemini model runs on Gemini, whatever its case`() { + listOf("gemini-4-neon-high", "Gemini-3.8-flash-low", " gemini-4-carbon-medium ").forEach { + assertEquals(RiskReviewerRuntime.Gemini, RiskReviewerRuntime.of(it), it) + } + } + + @Test + fun `bl-205 gemini-4-neon-high picks Gemini, sonnet keeps Claude Code and gpt-6_1-sol keeps Codex`() { + assertEquals(RiskReviewerRuntime.Gemini, RiskReviewerRuntime.of("gemini-4-neon-high")) + assertEquals(RiskReviewerRuntime.ClaudeCode, RiskReviewerRuntime.of("sonnet")) + assertEquals(RiskReviewerRuntime.Codex, RiskReviewerRuntime.of("gpt-6.1-sol")) + } + @Test fun `bl-214 a Claude model, an alias, another name or no model stays on Claude Code`() { - listOf("claude-sonnet-5-5", "sonnet", "opus", "fable", "ollama-llama", "openai", "gpt", null).forEach { + listOf("claude-sonnet-5-5", "sonnet", "opus", "fable", "ollama-llama", "openai", "gpt", "gemini", null).forEach { assertEquals(RiskReviewerRuntime.ClaudeCode, RiskReviewerRuntime.of(it), "$it") } } diff --git a/cli/src/test/kotlin/loop/cli/RiskReviewerWarningTest.kt b/cli/src/test/kotlin/loop/cli/RiskReviewerWarningTest.kt index ecad4e14..cecff4be 100644 --- a/cli/src/test/kotlin/loop/cli/RiskReviewerWarningTest.kt +++ b/cli/src/test/kotlin/loop/cli/RiskReviewerWarningTest.kt @@ -179,6 +179,27 @@ class RiskReviewerWarningTest { ) } + @Test + fun `bl-205 a Gemini reviewer model whose agy cannot be found warns, naming agy and its fix`() { + useCodex(delivery = AUTO_MERGE.replace("claude-sonnet-5-5", "gemini-4-neon-high")) + + assertEquals( + "kinds.code.delivery.risk.reviewer is gemini-4-neon-high, but its command agy cannot be found, so no " + + "merge risk reviewer can run and every result waits for loop approve. Install the Antigravity CLI so " + + "agy is on PATH", + riskReviewerWarning(workflow(), mapOf("PATH" to root.resolve("empty").toString())), + ) + } + + @Test + fun `bl-205 a Gemini reviewer model whose agy is on PATH gives no warning, even without claude`() { + val bin = root.resolve("bin-agy") + executable(bin.resolve("agy")) + useCodex(delivery = AUTO_MERGE.replace("claude-sonnet-5-5", "gemini-4-neon-high")) + + assertNull(riskReviewerWarning(workflow(), mapOf("PATH" to "$bin"))) + } + private companion object { const val PULL_REQUEST = " policy: POLICY\n" + From 1de938927f928a45e9bd6e9d74b77178673b138f Mon Sep 17 00:00:00 2001 From: Souleymane Sidibe <936370+soulesidibe@users.noreply.github.com> Date: Thu, 26 Nov 2026 09:52:13 +0000 Subject: [PATCH 3/4] bl-205: docs for the Gemini merge risk reviewer in runner-acp.md and spec-decisions.md --- docs/plugins/runner-acp.md | 18 ++++++++++++++++-- docs/spec-decisions.md | 19 +++++++++++++++++-- 2 files changed, 33 insertions(+), 4 deletions(-) diff --git a/docs/plugins/runner-acp.md b/docs/plugins/runner-acp.md index 2eee7959..91f7d978 100644 --- a/docs/plugins/runner-acp.md +++ b/docs/plugins/runner-acp.md @@ -10,8 +10,10 @@ The `acp` runner drives an Agent Client Protocol (ACP) agent over JSON-RPC 2.0 o 4. [Launch and streams](#launch-and-streams) 5. [Session startup and turns](#session-startup-and-turns) 6. [Isolated folder lifetime](#isolated-folder-lifetime) -7. [Context limits and rotation](#context-limits-and-rotation) -8. [Capabilities](#capabilities) +7. [Guards and holdout protection](#guards-and-holdout-protection) +8. [Merge risk reviewer](#merge-risk-reviewer) +9. [Context limits and rotation](#context-limits-and-rotation) +10. [Capabilities](#capabilities) ## Configuration @@ -104,6 +106,18 @@ Every `session/request_permission` request is evaluated fail-closed in Kotlin us - **Human-input prompts:** unsupported human-input requests end the turn immediately with `turn_input_required` and stop the session. - **Protected workspace roots check (`preset: agy`):** before every session and before every `session/prompt`, inspects `.agents/`, `.agent/`, `_agents/`, and `_agent/` directly in directories between the workspace and the repository root (ignoring nested paths `agy` never loads). Any protected root that is a symbolic link (even if tracked) is refused on every turn. Every on-disk customization file (`hooks.json`, `mcp_config.json`, `skills.json`, `rules.json`, `plugins.json`, or any file under `plugins/`, `rules/`, or `hooks/`) is compared against the host-resolved base commit SHA (`git ls-tree` mode and `git hash-object` blob SHA, independent of the git index). When no base commit can be resolved from `AttemptContext.baseRef`, `main`, `master`, or `origin/HEAD`, the check fails closed naming `kinds.code.guards.base` and `kinds.code.delivery.pull_request.base`. Any mismatch fails the turn naming the path and stops the session. +## Merge risk reviewer + +The merge risk reviewer follows the model of `kinds.code.delivery.risk.reviewer`, not `runner.kind`. Since bl-205 a model whose name starts with `gemini-`, such as `gemini-4-neon-high`, runs on Gemini through this runner, so a workflow on Claude Code or Codex can use a Gemini model as its independent reviewer, and a machine without Claude Code can run `policy: auto` with merge. `GeminiRiskReviewer` runs one `agy acp` turn of `AcpRunner` under `preset: agy` in the issue workspace: + +- **Command:** `runners.acp.command` under `runner.kind: acp` with `preset: agy`, with its `read_timeout_ms`; under any other runner `agy acp`. The program is looked up on the host `PATH`, and under `policy: auto` with merge `loop run` warns at startup when it cannot be found. +- **Model and time:** the reviewer's model is set with `session/set_model`, and the turn ends at `kinds.code.delivery.risk.timeout_ms`, which stops `agy`. +- **Read only:** `AcpSettings.readOnly`, which is not a profile key. Every command, write, edit, delete, move and MCP tool permission request is declined (`the merge risk reviewer runs read only`); reads and searches are allowed except under the holdout folder. No `mcpServers` are passed. Everything else of `preset: agy` holds: the version pin, the isolated `--gemini-dir`, `--sandbox`, the protected roots check and the env policy. +- **No kept folder:** a review never resumes, and its isolated folder is removed when it ends. +- **Answer:** the text of the final agent message (the `agent_message_chunk` texts after the last tool call), with the session's tokens and no cost. A failed turn, an input request, a launch failure or no agent message is a crash, and the gate falls back to `loop approve`. + +Any other model keeps its reviewer: a Codex model (`gpt-6.1-sol`) runs on Codex (bl-214) and any other, such as `sonnet`, on Claude Code (m4-06). See [Gemini merge risk reviewer](../spec-decisions.md#gemini-merge-risk-reviewer-extension-bl-205). + ## Context limits and rotation Loop ships default context windows of `1048576` tokens in `ContextConfig.DEFAULT_WINDOWS` for `google/gemini-4-neon-high`, `google/gemini-4-neon-medium`, `google/gemini-4-neon-low`, `google/gemini-4-neon-xhigh`, `google/gemini-3.8-flash-high`, `google/gemini-3.8-flash-medium`, and `google/gemini-3.8-flash-low`. diff --git a/docs/spec-decisions.md b/docs/spec-decisions.md index ad33e1ce..3d2e63cd 100644 --- a/docs/spec-decisions.md +++ b/docs/spec-decisions.md @@ -2566,7 +2566,7 @@ Story 106, carrying bl-145 and bl-100. Until m4-06 `riskReviewerFor` built a rev - **Where the command is looked up.** A bare name is looked up in the folders of the host `PATH` and the reviewer starts the absolute path found, so the check and the run agree; an absolute path must be an executable file; a relative path with a slash resolves against the issue workspace, which does not exist at startup, so it is kept as written. - **No reviewer can run.** When the command cannot be found, `riskReviewerFor` gives no reviewer and the gate falls back as before, the comment reading `Merge risk: not assessed, this Loop cannot run its merge risk reviewer, so the reviewer setup, not the result, is why the merge waits`. Under `policy: auto` with `pull_request.merge` and `risk.reviewer`, `loop run` warns once at startup: `loop run: warning: kinds.code.delivery.risk.reviewer is claude-sonnet-5-5, but its command claude cannot be found, so no merge risk reviewer can run and every result waits for loop approve. Install Claude Code or set runners.claude-code.command.` A command that is found but fails to start or crashes falls back as any reviewer crash. - **Never in the operator's checkout (bl-100).** During the run of 2026-11-16 a merge risk reviewer started by hand ran `git checkout` in the operator's main checkout, which holds the live `WORKFLOW.md`. Loop's own reviewer runs with the issue workspace as its directory and without Bash; tests now pin both, so a change that moves it to the project root or gives it Bash fails. The `merge-risk` skill states the same rule for a reviewer started by hand: read only, never `git checkout`, `git switch`, `git reset` or `git stash` in the operator's checkout; read with `git diff` and `git show :`, or in a separate `git worktree` of the pull request head. -- **Out of scope.** A Codex native reviewer, a reviewer section in the workflow and the merge risk scoring itself. Since bl-214 a Codex model in `risk.reviewer` gets a Codex reviewer, see [Codex merge risk reviewer](#codex-merge-risk-reviewer-extension-bl-214). +- **Out of scope.** A Codex native reviewer, a reviewer section in the workflow and the merge risk scoring itself. Since bl-214 a Codex model in `risk.reviewer` gets a Codex reviewer, see [Codex merge risk reviewer](#codex-merge-risk-reviewer-extension-bl-214), and since bl-205 a Gemini model a Gemini reviewer, see [Gemini merge risk reviewer](#gemini-merge-risk-reviewer-extension-bl-205). Tests: `cli/src/test/kotlin/loop/cli/DeliveryExecutorsTest.kt` (the `m4-06` tests: under `codex-app-server` the reviewer is Claude Code's, found on the host `PATH` and run with the model of `risk.reviewer` in the workspace; `runners.claude-code.command` when set; the `command` and `claude-code` runners; no reviewer when the command cannot be found), `cli/src/test/kotlin/loop/cli/RiskReviewerWarningTest.kt` (the startup warning, its conditions and `loop run` printing it), `spec-core/src/test/kotlin/loop/core/orchestrator/AutoMergeOrchestratorTest.kt` (a Codex result with every condition held and a low band from a fake reviewer auto merges; and `a host with no reviewer falls back`, now naming the reviewer setup), `spec-core/src/test/kotlin/loop/core/merge/MergesTest.kt` (the fallback reason) and `plugins/runner-claude-code/src/test/kotlin/loop/runner/claudecode/ClaudeCodeRiskReviewerTest.kt` (the `bl-100` tests: the directory is the issue workspace, never the project root or Loop's own directory, and Bash stays among the disallowed tools). @@ -2581,10 +2581,25 @@ The Codex twin of bl-205. Since m4-06 every merge risk review ran through Claude - **Holdout.** The runner's holdout rules stay on, so a request that names the holdout folder is declined as touching it, and every other request is declined anyway. Not covered, the gap of m3-20: a known safe command that reads the holdout folder runs without a request. - **The answer.** The text of the turn's last completed `agentMessage` item, the one of phase `final_answer` when there is one, with the session's tokens from `thread/tokenUsage/updated` and no cost, which Codex does not report. A failed turn, a user input request, a launch failure or a turn with no agent message is a crash; a turn past `risk.timeout_ms` is a timeout and its app server is stopped. The orchestrator parses the answer as any reviewer's. - **The warning.** Under `policy: auto` with merge, a Codex reviewer whose program cannot be found warns at startup with `... but its command codex cannot be found, so no merge risk reviewer can run and every result waits for loop approve. Install Codex or set runners.codex.command`; one whose `runners.codex` cannot be read warns with the reason. -- **Out of scope.** The Gemini reviewer (bl-205), a model list from the runtimes, and a read deny that holds without an approval request. +- **Out of scope.** The Gemini reviewer, built by bl-205 (see [Gemini merge risk reviewer](#gemini-merge-risk-reviewer-extension-bl-205)), a model list from the runtimes, and a read deny that holds without an approval request. Tests: `plugins/runner-codex-app-server/src/test/kotlin/loop/runner/codex/CodexRiskReviewerTest.kt` (the answer and tokens, the read-only sandbox, model, prompt and workspace of the thread, every command, file change and older approval declined, a holdout read declined, a failed turn, no answer, the timeout, a command that cannot start, `commandOf`), `cli/src/test/kotlin/loop/cli/RiskReviewerRuntimeTest.kt` (the model names), `cli/src/test/kotlin/loop/cli/DeliveryExecutorsTest.kt` (the `bl-214` tests: a Codex model gets the Codex reviewer found on the host `PATH` and run in the workspace, `runners.codex.command` with its other words, a Claude model keeps Claude Code under `codex-app-server`, no reviewer when codex cannot be found) and `cli/src/test/kotlin/loop/cli/RiskReviewerWarningTest.kt` (the Codex warning, none when codex is found, and `loop run` printing it). +### Gemini merge risk reviewer (extension, bl-205) + +The `agy` twin of bl-214, filed from `.loop/specs/gemini-support.md` item 8. Until bl-205 a `gemini-` model in `risk.reviewer` went to Claude Code, which refuses it, so a machine with only `agy` could not use `policy: auto` with merge. The decisions: + +- **The model picks the runtime.** `RiskReviewerRuntime.of` gains `Gemini`: a model whose name, trimmed and in any case, starts with `gemini-` runs on Gemini, and `riskReviewerFor` builds `GeminiRiskReviewer`. `gpt-6.1-sol` still runs on Codex and `sonnet` on Claude Code, whatever `runner.kind` is. A model `agy` serves that does not start with `gemini-` is not routed to it. +- **Its settings.** Under `runner.kind: acp` with `preset: agy` they are `runners.acp`, read as the ACP runner reads it with the holdout folder, which the loader already checked: `command`, `read_timeout_ms` and `strict_mcp` apply. Under any other runner they are the defaults with the command `agy acp`. The model is always the reviewer's, set with `session/set_model`, and the turn timeout is `risk.timeout_ms`. The first word of the command is looked up on the host `PATH` as m4-06 looks up `claude`, and the reviewer starts the absolute path found, so the check and the run agree. +- **One turn of the runner.** `GeminiRiskReviewer` in `plugins/runner-acp` runs one `agy acp` turn of `AcpRunner` under `preset: agy` in the issue workspace, so the version pin at `initialize`, the isolated `--gemini-dir`, `--sandbox`, `--disable-telemetry`, strict MCP, the protected roots check and the agent env policy, Google API keys removed, are the runner's. The `agy models` preflight of `runner.kind: acp` is not run for a reviewer: the startup warning below names a missing `agy`, and an `agy` that is too old fails the review at `initialize`, a crash that falls back. +- **Read only.** `AcpSettings.readOnly`, which is not a profile key, makes the permission policy read only: every command (`run_command`, `kind: execute`), every write, edit, delete or move, and every MCP tool is declined, with the reason `the merge risk reviewer runs read only` when no other rule refuses it first. Reads and searches keep their rule, so they are allowed except under the holdout folder, which is refused. No `mcpServers` are passed, so no Loop tool exists in the session, and its attempt env is empty. +- **No kept folder.** A read only session never resumes, and its isolated folder is removed when the review ends, even after `agy` reported its runtime session id, so a review never leaves a folder for the bl-213 resume to find. +- **The answer.** The text of the turn's final agent message: the `agent_message_chunk` texts after the last `tool_call` or `tool_call_update`, with the session's tokens from the `session/prompt` usage and no cost, which ACP does not report. A failed turn, a user input request, a launch failure or a turn with no agent message is a crash; a turn past `risk.timeout_ms` is a timeout, and its `agy` is stopped. The orchestrator parses the answer as any reviewer's. +- **The warning.** Under `policy: auto` with merge, a Gemini reviewer whose program cannot be found warns at startup with `... but its command agy cannot be found, so no merge risk reviewer can run and every result waits for loop approve. Install the Antigravity CLI so agy is on PATH`, or `Install the Antigravity CLI or set runners.acp.command` under `runner.kind: acp` with `preset: agy`. +- **Out of scope.** The Claude Code and Codex reviewers are unchanged, no warning names a reviewer on the same runtime as the worker, and non `gemini-` models that `agy` also serves stay on Claude Code. + +Tests: `plugins/runner-acp/src/test/kotlin/loop/runner/acp/GeminiRiskReviewerTest.kt` (with a fake ACP server: the answer and tokens, the model, workspace and empty `mcpServers` of the session, a declined command, a declined edit, write, delete and move, an allowed read and search with a refused holdout read, a declined Loop MCP tool, a failed turn, no answer, an input request, the timeout with its `agy` stopped, a command that cannot start, no kept folder, `commandOf`), `cli/src/test/kotlin/loop/cli/RiskReviewerRuntimeTest.kt` (the `bl-205` tests: `gemini-` models, and `gemini-4-neon-high`, `sonnet` and `gpt-6.1-sol` each on its runtime), `cli/src/test/kotlin/loop/cli/DeliveryExecutorsTest.kt` (the `bl-205` tests: the three models pick their three reviewers, a Gemini reviewer runs `agy acp` under `preset: agy` found on the host `PATH` in the workspace, `runners.acp.command` under `runner.kind: acp`, no reviewer when `agy` cannot be found) and `cli/src/test/kotlin/loop/cli/RiskReviewerWarningTest.kt` (the Gemini warning, none when `agy` is found). + ### Network loss (extension, m4-08) Story 108, first half, carrying bl-123 and the sleep decision of bl-156. On 2026-11-16 between 12:32 and 12:48 UTC the machine lost its connection, and Claude Code ended the turn with `API Error: Can't reach the API server (...) check your internet or DNS (ENOTFOUND)`. Loop recorded an ordinary `turn_failed` and failed the attempt of both running issues, bl-117 after 7.3M tokens and 3.78 US dollars of work, m3-07 after 0.41 US dollars. A lost network says nothing about the issue, the same as an authentication failure, so it now goes through the [runner unavailable hold](#runner-unavailable-hold-extension-bl-39). The decisions: From e5f2de8f93e6436f8e7af7c53fe4d4eccf70fe0b Mon Sep 17 00:00:00 2001 From: Souleymane Sidibe <936370+soulesidibe@users.noreply.github.com> Date: Thu, 26 Nov 2026 14:24:35 +0000 Subject: [PATCH 4/4] bl-205: reviewer takes the last agent message, sets the trimmed model, reports a missing terminal event, read only policy tests and docs --- docs/plugins/runner-acp.md | 8 +- docs/spec-decisions.md | 11 +-- .../loop/runner/acp/GeminiRiskReviewer.kt | 50 ++++++++--- .../runner/acp/AcpPermissionPolicyTest.kt | 54 ++++++++++++ .../loop/runner/acp/GeminiRiskReviewerTest.kt | 86 ++++++++++++++++--- 5 files changed, 175 insertions(+), 34 deletions(-) diff --git a/docs/plugins/runner-acp.md b/docs/plugins/runner-acp.md index dc92addf..a9b1613c 100644 --- a/docs/plugins/runner-acp.md +++ b/docs/plugins/runner-acp.md @@ -123,10 +123,12 @@ Every `session/request_permission` request is evaluated fail-closed in Kotlin us The merge risk reviewer follows the model of `kinds.code.delivery.risk.reviewer`, not `runner.kind`. Since bl-205 a model whose name starts with `gemini-`, such as `gemini-4-neon-high`, runs on Gemini through this runner, so a workflow on Claude Code or Codex can use a Gemini model as its independent reviewer, and a machine without Claude Code can run `policy: auto` with merge. `GeminiRiskReviewer` runs one `agy acp` turn of `AcpRunner` under `preset: agy` in the issue workspace: - **Command:** `runners.acp.command` under `runner.kind: acp` with `preset: agy`, with its `read_timeout_ms`; under any other runner `agy acp`. The program is looked up on the host `PATH`, and under `policy: auto` with merge `loop run` warns at startup when it cannot be found. -- **Model and time:** the reviewer's model is set with `session/set_model`, and the turn ends at `kinds.code.delivery.risk.timeout_ms`, which stops `agy`. -- **Read only:** `AcpSettings.readOnly`, which is not a profile key. Every command, write, edit, delete, move and MCP tool permission request is declined (`the merge risk reviewer runs read only`); reads and searches are allowed except under the holdout folder. No `mcpServers` are passed. Everything else of `preset: agy` holds: the version pin, the isolated `--gemini-dir`, `--sandbox`, the protected roots check and the env policy. +- **Model and time:** the reviewer's model, trimmed and in lower case as the routing reads it, is set with `session/set_model`, and the turn ends at `kinds.code.delivery.risk.timeout_ms`, which stops `agy`. +- **Read only:** `AcpSettings.readOnly`, which is not a profile key. Every command, write, edit, delete, move and MCP tool permission request is declined (`the merge risk reviewer runs read only`); reads and searches are allowed except under the holdout folder, and, as for a worker, reads outside the workspace are allowed. No `mcpServers` are passed. Everything else of `preset: agy` holds: the version pin, the isolated `--gemini-dir`, `--sandbox`, the protected roots check and the env policy. - **No kept folder:** a review never resumes, and its isolated folder is removed when it ends. -- **Answer:** the text of the final agent message (the `agent_message_chunk` texts after the last tool call), with the session's tokens and no cost. A failed turn, an input request, a launch failure or no agent message is a crash, and the gate falls back to `loop approve`. +- **Protected roots:** the review keeps the protected workspace roots check, so it fails closed with `protected_workspace_root` when the pull request touches an agent customization root (`.agents`, `.agent`, `_agents`, `_agent`), or when no base commit can be resolved from `main`, `master` or `origin/HEAD`, and the gate falls back to `loop approve`. +- **Context files:** unlike the Claude Code reviewer, the review turns off no workspace context file (`AGENTS.md`, `GEMINI.md`): `agy` loads them, and the gate's `protected_paths` condition is what keeps a pull request that edits them from merging on its own. +- **Answer:** the text of the last agent message, as for the Codex reviewer, with the session's tokens and no cost. A message is a run of `agent_message_chunk` texts that a tool call, an update of one or a chunk with another `messageId` ends, and a message with no text is skipped, so a tool call update after the final message keeps it. A failed turn, an input request, a launch failure, no agent message or no terminal event is a crash, and the gate falls back to `loop approve`. Any other model keeps its reviewer: a Codex model (`gpt-6.1-sol`) runs on Codex (bl-214) and any other, such as `sonnet`, on Claude Code (m4-06). See [Gemini merge risk reviewer](../spec-decisions.md#gemini-merge-risk-reviewer-extension-bl-205). diff --git a/docs/spec-decisions.md b/docs/spec-decisions.md index b19500f3..0d5b6b1b 100644 --- a/docs/spec-decisions.md +++ b/docs/spec-decisions.md @@ -2590,15 +2590,16 @@ Tests: `plugins/runner-codex-app-server/src/test/kotlin/loop/runner/codex/CodexR The `agy` twin of bl-214, filed from `.loop/specs/gemini-support.md` item 8. Until bl-205 a `gemini-` model in `risk.reviewer` went to Claude Code, which refuses it, so a machine with only `agy` could not use `policy: auto` with merge. The decisions: - **The model picks the runtime.** `RiskReviewerRuntime.of` gains `Gemini`: a model whose name, trimmed and in any case, starts with `gemini-` runs on Gemini, and `riskReviewerFor` builds `GeminiRiskReviewer`. `gpt-6.1-sol` still runs on Codex and `sonnet` on Claude Code, whatever `runner.kind` is. A model `agy` serves that does not start with `gemini-` is not routed to it. -- **Its settings.** Under `runner.kind: acp` with `preset: agy` they are `runners.acp`, read as the ACP runner reads it with the holdout folder, which the loader already checked: `command`, `read_timeout_ms` and `strict_mcp` apply. Under any other runner they are the defaults with the command `agy acp`. The model is always the reviewer's, set with `session/set_model`, and the turn timeout is `risk.timeout_ms`. The first word of the command is looked up on the host `PATH` as m4-06 looks up `claude`, and the reviewer starts the absolute path found, so the check and the run agree. +- **Its settings.** Under `runner.kind: acp` with `preset: agy` they are `runners.acp`, read as the ACP runner reads it with the holdout folder, which the loader already checked: `command`, `read_timeout_ms` and `strict_mcp` apply. Under any other runner they are the defaults with the command `agy acp`. The model is always the reviewer's, trimmed and in lower case as the routing reads it, set with `session/set_model`, and the turn timeout is `risk.timeout_ms`. The first word of the command is looked up on the host `PATH` as m4-06 looks up `claude`, and the reviewer starts the absolute path found, so the check and the run agree. - **One turn of the runner.** `GeminiRiskReviewer` in `plugins/runner-acp` runs one `agy acp` turn of `AcpRunner` under `preset: agy` in the issue workspace, so the version pin at `initialize`, the isolated `--gemini-dir`, `--sandbox`, `--disable-telemetry`, strict MCP, the protected roots check and the agent env policy, Google API keys removed, are the runner's. The `agy models` preflight of `runner.kind: acp` is not run for a reviewer: the startup warning below names a missing `agy`, and an `agy` that is too old fails the review at `initialize`, a crash that falls back. -- **Read only.** `AcpSettings.readOnly`, which is not a profile key, makes the permission policy read only: every command (`run_command`, `kind: execute`), every write, edit, delete or move, and every MCP tool is declined, with the reason `the merge risk reviewer runs read only` when no other rule refuses it first. Reads and searches keep their rule, so they are allowed except under the holdout folder, which is refused. No `mcpServers` are passed, so no Loop tool exists in the session, and its attempt env is empty. -- **No kept folder.** A read only session never resumes, and its isolated folder is removed when the review ends, even after `agy` reported its runtime session id, so a review never leaves a folder for the bl-213 resume to find. -- **The answer.** The text of the turn's final agent message: the `agent_message_chunk` texts after the last `tool_call` or `tool_call_update`, with the session's tokens from the `session/prompt` usage and no cost, which ACP does not report. A failed turn, a user input request, a launch failure or a turn with no agent message is a crash; a turn past `risk.timeout_ms` is a timeout, and its `agy` is stopped. The orchestrator parses the answer as any reviewer's. +- **Read only.** `AcpSettings.readOnly`, which is not a profile key, makes the permission policy read only: every command (`run_command`, `kind: execute`), every write, edit, delete or move, and every MCP tool is declined, with the reason `the merge risk reviewer runs read only` when no other rule refuses it first. Reads and searches keep their rule, so they are allowed except under the holdout folder, which is refused, and reads outside the workspace are allowed as for a worker. No `mcpServers` are passed, so no Loop tool exists in the session, and its attempt env is empty. +- **No kept folder.** A read only session never resumes, and its isolated folder is removed when the review ends, even after `agy` reported its runtime session id, so a review never leaves a folder for the bl-213 resume to find. The bl-230 rule that a guard ended session keeps no folder holds beside it. +- **Protected roots and context files.** The protected roots check stays on, so a review fails closed with `protected_workspace_root` when the pull request touches `.agents`, `.agent`, `_agents` or `_agent`, or when no base commit can be resolved from `main`, `master` or `origin/HEAD`, and the gate falls back to `loop approve`. Unlike the Claude Code reviewer, no workspace context file (`AGENTS.md`, `GEMINI.md`) is turned off; the gate's `protected_paths` condition keeps a pull request that edits them from merging on its own. +- **The answer.** The text of the turn's last agent message, as the Codex reviewer takes the last completed one: a run of `agent_message_chunk` texts that a `tool_call`, a `tool_call_update` or a chunk with another `messageId` ends, a message with no text skipped, so a tool call update after the final message keeps it. The session's tokens come from the `session/prompt` usage, with no cost, which ACP does not report. A failed turn, a user input request, a launch failure, a turn with no agent message or a run of events with no terminal event is a crash; a turn past `risk.timeout_ms` is a timeout, and its `agy` is stopped. The orchestrator parses the answer as any reviewer's. - **The warning.** Under `policy: auto` with merge, a Gemini reviewer whose program cannot be found warns at startup with `... but its command agy cannot be found, so no merge risk reviewer can run and every result waits for loop approve. Install the Antigravity CLI so agy is on PATH`, or `Install the Antigravity CLI or set runners.acp.command` under `runner.kind: acp` with `preset: agy`. - **Out of scope.** The Claude Code and Codex reviewers are unchanged, no warning names a reviewer on the same runtime as the worker, and non `gemini-` models that `agy` also serves stay on Claude Code. -Tests: `plugins/runner-acp/src/test/kotlin/loop/runner/acp/GeminiRiskReviewerTest.kt` (with a fake ACP server: the answer and tokens, the model, workspace and empty `mcpServers` of the session, a declined command, a declined edit, write, delete and move, an allowed read and search with a refused holdout read, a declined Loop MCP tool, a failed turn, no answer, an input request, the timeout with its `agy` stopped, a command that cannot start, no kept folder, `commandOf`), `cli/src/test/kotlin/loop/cli/RiskReviewerRuntimeTest.kt` (the `bl-205` tests: `gemini-` models, and `gemini-4-neon-high`, `sonnet` and `gpt-6.1-sol` each on its runtime), `cli/src/test/kotlin/loop/cli/DeliveryExecutorsTest.kt` (the `bl-205` tests: the three models pick their three reviewers, a Gemini reviewer runs `agy acp` under `preset: agy` found on the host `PATH` in the workspace, `runners.acp.command` under `runner.kind: acp`, no reviewer when `agy` cannot be found) and `cli/src/test/kotlin/loop/cli/RiskReviewerWarningTest.kt` (the Gemini warning, none when `agy` is found). +Tests: `plugins/runner-acp/src/test/kotlin/loop/runner/acp/GeminiRiskReviewerTest.kt` (with a fake ACP server: the answer and tokens, the model, workspace and empty `mcpServers` of the session, a declined command, a declined edit, write, delete and move, an allowed read and search with a refused holdout read, a declined Loop MCP tool, the model trimmed and in lower case, a tool call update after the final message, the last of two messages with their own ids, a failed turn, no answer, an input request, the timeout with its `agy` stopped, a command that cannot start, no kept folder, `commandOf`), `plugins/runner-acp/src/test/kotlin/loop/runner/acp/AcpPermissionPolicyTest.kt` (the `bl-205` test: in read only mode a non Loop and a Loop MCP tool, a write under an internal Loop directory, `kind: fetch` and a `write_file` of `kind: think` are declined, a plain `think` is allowed), `cli/src/test/kotlin/loop/cli/RiskReviewerRuntimeTest.kt` (the `bl-205` tests: `gemini-` models, and `gemini-4-neon-high`, `sonnet` and `gpt-6.1-sol` each on its runtime), `cli/src/test/kotlin/loop/cli/DeliveryExecutorsTest.kt` (the `bl-205` tests: the three models pick their three reviewers, a Gemini reviewer runs `agy acp` under `preset: agy` found on the host `PATH` in the workspace, `runners.acp.command` under `runner.kind: acp`, no reviewer when `agy` cannot be found) and `cli/src/test/kotlin/loop/cli/RiskReviewerWarningTest.kt` (the Gemini warning, none when `agy` is found). ### Network loss (extension, m4-08) diff --git a/plugins/runner-acp/src/main/kotlin/loop/runner/acp/GeminiRiskReviewer.kt b/plugins/runner-acp/src/main/kotlin/loop/runner/acp/GeminiRiskReviewer.kt index 637b4dc9..260ff467 100644 --- a/plugins/runner-acp/src/main/kotlin/loop/runner/acp/GeminiRiskReviewer.kt +++ b/plugins/runner-acp/src/main/kotlin/loop/runner/acp/GeminiRiskReviewer.kt @@ -16,6 +16,7 @@ import loop.api.RiskReviewer import loop.api.RunId import loop.api.RunnerEvent import loop.api.RunnerEvent.Output.Stream +import java.util.Locale import kotlin.time.Duration.Companion.milliseconds /** @@ -26,10 +27,11 @@ import kotlin.time.Duration.Companion.milliseconds * write, edit, delete or move is declined, reads and searches are allowed except under the holdout folder of [settings], * and no Loop tool is passed. A review never resumes, and its isolated folder is removed when it ends. * - * The answer is the text of the turn's final agent message, its `agent_message_chunk` texts after the last tool call, - * with the session's tokens and no cost, which ACP does not report. A turn past [RiskReviewRequest.timeoutMs] is stopped, + * The answer is the text of the turn's last agent message, as for the Codex reviewer, with the session's tokens and no + * cost, which ACP does not report. A message is a run of `agent_message_chunk` texts; a tool call, an update of one or a + * chunk with another `messageId` ends it, and a message with no text is skipped. A turn past [RiskReviewRequest.timeoutMs] is stopped, * with its `agy`, and is a [RiskReviewError.Timeout]; a turn that fails, asks for input, cannot start or ends with no - * agent message is a [RiskReviewError.Crashed]. + * agent message, or with no terminal event, is a [RiskReviewError.Crashed]. */ class GeminiRiskReviewer( private val settings: AcpSettings, @@ -40,14 +42,14 @@ class GeminiRiskReviewer( val reviewSettings = settings.copy( preset = AcpSettings.PRESET_AGY, - model = request.model, + model = request.model.trim().lowercase(Locale.ROOT), strictMcp = true, readOnly = true, turnTimeout = request.timeoutMs.coerceIn(1, AcpSettings.MAX_TIMEOUT_MS).milliseconds, ) val runner = AcpRunner(reviewSettings, hostEnv, removedEnvNames) val answer = Answer() - val end = + val ended = try { withTimeoutOrNull(request.timeoutMs) { var terminal: RunnerEvent? = null @@ -55,14 +57,14 @@ class GeminiRiskReviewer( answer.read(event) if (event.isTerminal()) terminal = event } - terminal + Ended(terminal) } ?: return Result.failure(RiskReviewError.Timeout("no answer within ${request.timeoutMs} ms")) } catch (e: CancellationException) { throw e } catch (e: Exception) { return Result.failure(RiskReviewError.Crashed("agy cannot run the review: ${e.message}", e)) } - return when (end) { + return when (val end = ended.terminal) { is RunnerEvent.TurnCompleted -> answer.text?.let { Result.success(RiskReview(it, answer.tokens, null)) } ?: Result.failure(RiskReviewError.Crashed("agy ended the turn with no answer")) @@ -73,14 +75,21 @@ class GeminiRiskReviewer( } } - /** What the review collected from the runner's events: the agent's final message and the session's tokens. */ + /** How the turn's events ended: with the [terminal] event, or null when the runner sent none. */ + private class Ended( + val terminal: RunnerEvent?, + ) + + /** What the review collected from the runner's events: the agent's last message and the session's tokens. */ private class Answer { private val message = StringBuilder() + private var messageId: String? = null + private var last: String? = null var tokens: LedgerTokens? = null private set - /** The text of the agent message after the last tool call; null when the agent wrote none. */ - val text: String? get() = message.toString().takeIf { it.isNotBlank() } + /** The text of the last agent message that has any; null when the agent wrote none. */ + val text: String? get() = message.toString().takeIf { it.isNotBlank() } ?: last fun read(event: RunnerEvent) { when (event) { @@ -91,18 +100,33 @@ class GeminiRiskReviewer( } } - /** Reads a `session/update` on [line], a protocol line of `agy`: a message chunk adds to it, a tool call ends it. */ + /** + * Reads a `session/update` on [line], a protocol line of `agy`: a message chunk adds to the current message, a + * tool call, an update of one or a chunk of another message ends it. + */ private fun update(line: String) { if (SESSION_UPDATE !in line) return val frame = AcpFraming.decode(line) as? AcpFrame.Notification ?: return if (frame.method != AcpHandshake.METHOD_SESSION_UPDATE) return val update = (frame.params as? JsonObject)?.get("update") as? JsonObject ?: return when (update.string("sessionUpdate")) { - AGENT_MESSAGE_CHUNK -> (update["content"] as? JsonObject)?.string("text")?.let { message.append(it) } - TOOL_CALL, TOOL_CALL_UPDATE -> message.clear() + AGENT_MESSAGE_CHUNK -> { + val id = update.string("messageId") + if (id != null && id != messageId) endMessage() + messageId = id + (update["content"] as? JsonObject)?.string("text")?.let { message.append(it) } + } + TOOL_CALL, TOOL_CALL_UPDATE -> endMessage() } } + /** Ends the current message, kept as the last one when it has any text. */ + private fun endMessage() { + message.toString().takeIf { it.isNotBlank() }?.let { last = it } + message.clear() + messageId = null + } + private fun JsonObject.string(key: String): String? = (get(key) as? JsonPrimitive)?.takeIf { it.isString }?.content } diff --git a/plugins/runner-acp/src/test/kotlin/loop/runner/acp/AcpPermissionPolicyTest.kt b/plugins/runner-acp/src/test/kotlin/loop/runner/acp/AcpPermissionPolicyTest.kt index 7116539a..d8042188 100644 --- a/plugins/runner-acp/src/test/kotlin/loop/runner/acp/AcpPermissionPolicyTest.kt +++ b/plugins/runner-acp/src/test/kotlin/loop/runner/acp/AcpPermissionPolicyTest.kt @@ -401,6 +401,60 @@ class AcpPermissionPolicyTest { assertTrue(AcpPermissionPolicy.INTERNAL_LOOP_DIR in cmdDeny.note, cmdDeny.note) } + @Test + fun `bl-205 read only declines every MCP tool, writes under internal Loop directories, fetch and a mutating tool of kind think`() { + val internalDir = home.resolve(".loop/attempts/proj-1/att-1").createDirectories() + val readOnly = + AcpPermissionPolicy( + workspace = workspace, + holdout = HoldoutFolder(holdoutDir, home), + protectedRoots = ProtectedWorkspaceRoots(workspace, home), + strictMcp = false, + launcher = customLauncher, + protectedWriteDirs = { listOf(HoldoutFolder(internalDir, home)) }, + readOnly = true, + ) + + fun declined( + toolCall: JsonObject, + reason: String, + ) { + val answer = assertIs(readOnly.answer(permissionRequest(toolCall = toolCall))) + assertEquals("opt-reject-once", outcomeOf(answer)["optionId"]!!.jsonPrimitive.content, answer.note) + assertTrue(reason in answer.note, answer.note) + } + + declined(buildJsonObject { put("name", "mcp_github_push") }, AcpPermissionPolicy.READ_ONLY) + declined(buildJsonObject { put("name", "mcp__loop__move") }, AcpPermissionPolicy.READ_ONLY) + declined( + buildJsonObject { + put("name", "write_file") + put("kind", "edit") + put("rawInput", buildJsonObject { put("Path", internalDir.resolve("settings.json").toString()) }) + }, + AcpPermissionPolicy.INTERNAL_LOOP_DIR, + ) + declined( + buildJsonObject { + put("name", "web_fetch") + put("kind", "fetch") + put("rawInput", buildJsonObject { put("url", "https://example.com") }) + }, + AcpPermissionPolicy.UNSUPPORTED_TOOL, + ) + declined( + buildJsonObject { + put("name", "write_file") + put("kind", "think") + put("rawInput", buildJsonObject { put("Path", workspace.resolve("notes.md").toString()) }) + }, + AcpPermissionPolicy.READ_ONLY, + ) + + val think = readOnly.answer(permissionRequest(toolCall = buildJsonObject { put("kind", "think") })) + assertEquals("opt-allow-once", outcomeOf(assertIs(think))["optionId"]!!.jsonPrimitive.content) + } + /** * A `session/request_permission` frame of the shape agy 1.5.18 sends for a file tool called by URI: the recorded * frame envelope, `args` and `rawInput` carrying the `Path` as given, and `locations[].path`. Each path is optional diff --git a/plugins/runner-acp/src/test/kotlin/loop/runner/acp/GeminiRiskReviewerTest.kt b/plugins/runner-acp/src/test/kotlin/loop/runner/acp/GeminiRiskReviewerTest.kt index dca754b3..4b034b2a 100644 --- a/plugins/runner-acp/src/test/kotlin/loop/runner/acp/GeminiRiskReviewerTest.kt +++ b/plugins/runner-acp/src/test/kotlin/loop/runner/acp/GeminiRiskReviewerTest.kt @@ -90,6 +90,52 @@ class GeminiRiskReviewerTest { assertContains(prompt.getValue("prompt").toString(), "Review this pull request.") } + @Test + fun `bl-205 the model is set trimmed and in lower case, as the routing reads it`() { + val server = + FakeAcpServer.write(dir) { + handshake(model = MODEL) + awaitClient() + agentChunk(verdict) + response(4, promptResult()) + } + + assertEquals(verdict, review(server, model = " Gemini-4-Neon-High ").getOrThrow().text) + + val setModel = received(server).single { it.method == "session/set_model" }.getValue("params").jsonObject + assertEquals(MODEL, setModel.getValue("modelId").jsonPrimitive.content) + } + + @Test + fun `bl-205 a tool call update after the final message keeps the answer`() { + val server = + FakeAcpServer.write(dir) { + handshake() + awaitClient() + toolCall("read_file") + agentChunk(verdict) + toolCallUpdate("call-1", "completed") + response(4, promptResult()) + } + + assertEquals(verdict, review(server).getOrThrow().text) + } + + @Test + fun `bl-205 of two agent messages with their own ids, the answer is the last one`() { + val server = + FakeAcpServer.write(dir) { + handshake() + awaitClient() + agentChunk("Here is my assessment.", messageId = "m-1") + agentChunk(verdict.substring(0, 10), messageId = "m-2") + agentChunk(verdict.substring(10), messageId = "m-2") + response(4, promptResult()) + } + + assertEquals(verdict, review(server).getOrThrow().text) + } + @Test fun `bl-205 a command is declined, even a plain read, since the reviewer runs read only`() { val server = @@ -322,19 +368,33 @@ class GeminiRiskReviewerTest { sessionSetModel(id = 3, configUpdateModelId = model, sessionId = SESSION) } - private fun FakeAcpServer.Script.agentChunk(text: String) = - update( - buildJsonObject { - put("sessionUpdate", "agent_message_chunk") - put( - "content", - buildJsonObject { - put("type", "text") - put("text", text) - }, - ) - }, - ) + private fun FakeAcpServer.Script.agentChunk( + text: String, + messageId: String? = null, + ) = update( + buildJsonObject { + put("sessionUpdate", "agent_message_chunk") + if (messageId != null) put("messageId", messageId) + put( + "content", + buildJsonObject { + put("type", "text") + put("text", text) + }, + ) + }, + ) + + private fun FakeAcpServer.Script.toolCallUpdate( + id: String, + status: String, + ) = update( + buildJsonObject { + put("sessionUpdate", "tool_call_update") + put("toolCallId", id) + put("status", status) + }, + ) private fun FakeAcpServer.Script.toolCall(name: String) = update(