diff --git a/cli/src/test/kotlin/loop/cli/AtomicFiles.kt b/cli/src/test/kotlin/loop/cli/AtomicFiles.kt new file mode 100644 index 0000000..b074bb6 --- /dev/null +++ b/cli/src/test/kotlin/loop/cli/AtomicFiles.kt @@ -0,0 +1,22 @@ +package loop.cli + +import java.nio.file.Files +import java.nio.file.Path +import java.nio.file.StandardCopyOption + +/** + * Writes [target] through [write] into a temporary file of its own folder, then moves it over [target] atomically, + * so a concurrent reader sees the old text or the new one, never a truncated or partial file. + */ +fun replaceAtomically( + target: Path, + write: (Path) -> Unit, +) { + val temp = Files.createTempFile(target.parent, ".${target.fileName}", ".tmp") + try { + write(temp) + Files.move(temp, target, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING) + } finally { + Files.deleteIfExists(temp) + } +} diff --git a/cli/src/test/kotlin/loop/cli/ClaudeCodeTrackerToolsTest.kt b/cli/src/test/kotlin/loop/cli/ClaudeCodeTrackerToolsTest.kt index 9128c6e..f1c9c0d 100644 --- a/cli/src/test/kotlin/loop/cli/ClaudeCodeTrackerToolsTest.kt +++ b/cli/src/test/kotlin/loop/cli/ClaudeCodeTrackerToolsTest.kt @@ -1,5 +1,6 @@ package loop.cli +import com.github.ajalt.clikt.testing.CliktCommandTestResult import com.github.ajalt.clikt.testing.test import loop.runner.claudecode.PreflightResult import org.junit.jupiter.api.io.TempDir @@ -68,9 +69,9 @@ class ClaudeCodeTrackerToolsTest { val result = LoopCommand(host()).test(listOf("run", fixture.workflow.toString(), "--once")) - assertEquals(0, result.statusCode, result.output + result.stderr) + assertEquals(0, result.statusCode, diagnostics(result, "default:t-1")) // In Loop mode a move to needs_info is not a submitted result: it applies as asked, with no verification. - assertEquals("needs_info", fixture.stateOf("t-1"), result.output + result.stderr) + assertEquals("needs_info", fixture.stateOf("t-1"), diagnostics(result, "default:t-1")) assertContains(fixture.issueFile("t-1").readText(), question) val applied = listOf("issue_comment_requested", "issue_move_requested", "issue_commented", "issue_moved") val kinds = @@ -78,7 +79,7 @@ class ClaudeCodeTrackerToolsTest { .query("SELECT kind FROM events WHERE issue_id = 'default:t-1' ORDER BY seq") .mapNotNull { it["kind"] } .filter { it in applied + "result_submitted" } - assertEquals(applied, kinds) + assertEquals(applied, kinds, diagnostics(result, "default:t-1")) fun dataOf(kind: String) = fixture.query("SELECT data FROM events WHERE kind = '$kind'").single()["data"].orEmpty() // The requests of loop tool comment and loop tool move, with no source. @@ -124,9 +125,10 @@ class ClaudeCodeTrackerToolsTest { val result = LoopCommand(host(GITHUB_TOKEN)).test(listOf("run", fixture.workflow.toString(), "--once")) - assertEquals(0, result.statusCode, result.output + result.stderr) + val both = { diagnostics(result, "local:l-1", "gh:26") } + assertEquals(0, result.statusCode, both()) // The files issue got its own comment and move, once each, and nothing of the GitHub issue's. - assertEquals("needs_info", fixture.stateOf("l-1"), result.output + result.stderr) + assertEquals("needs_info", fixture.stateOf("l-1"), both()) assertEquals( 1, fixture @@ -134,7 +136,7 @@ class ClaudeCodeTrackerToolsTest { .readText() .split(question) .size - 1, - fixture.issueFile("l-1").readText(), + fixture.issueFile("l-1").readText() + both(), ) // GitHub got the comment and the needs_info move of issue 26 only: one comment, the handoff label added, // the required label removed, and no write for the files issue. @@ -145,7 +147,7 @@ class ClaudeCodeTrackerToolsTest { "DELETE /api/repos/octocat/Hello-World/issues/26/labels/gh-ready", ), github.writePaths, - result.output + result.stderr, + both(), ) assertContains(github.writes.first().body, "archived items") val applied = listOf("issue_comment_requested", "issue_move_requested", "issue_commented", "issue_moved") @@ -155,12 +157,29 @@ class ClaudeCodeTrackerToolsTest { .query("SELECT kind FROM events WHERE issue_id = '$issue' ORDER BY seq") .mapNotNull { it["kind"] } .filter { it in applied + "tool_request_failed" } - assertEquals(applied, kinds, issue) + assertEquals(applied, kinds, "$issue\n" + both()) } assertTrue(result.stderr.lines().none { "No tracker" in it }, result.stderr) } } + /** + * What `run --once` printed, then the `runner_output` events of each of [issues], stderr included, so a fake + * `claude` that exits before its transcript shows why in the failure message. + */ + private fun diagnostics( + result: CliktCommandTestResult, + vararg issues: String, + ): String = + result.output + result.stderr + + issues.joinToString("") { issue -> + val lines = + fixture + .query("SELECT data FROM events WHERE kind = 'runner_output' AND issue_id = '$issue' ORDER BY seq") + .map { it["data"].orEmpty() } + "\n--- runner_output of $issue (${lines.size})\n" + lines.joinToString("\n") + } + private fun host(githubToken: String? = null): Host = Host( env = diff --git a/cli/src/test/kotlin/loop/cli/LoopFixture.kt b/cli/src/test/kotlin/loop/cli/LoopFixture.kt index 538eb80..e41cb84 100644 --- a/cli/src/test/kotlin/loop/cli/LoopFixture.kt +++ b/cli/src/test/kotlin/loop/cli/LoopFixture.kt @@ -78,6 +78,8 @@ class LoopFixture( /** * Writes `WORKFLOW.md` with [activeStates], plus [extra] front matter lines * (for example `retries:` with ` max_attempts: 1`), and [prompt] as its template. + * The file is replaced atomically (bl-186): a running `loop run` polls it, and a plain write truncates it + * first, so a poll in between would read a torn text and record it as an edit of its own. */ fun writeWorkflow( activeStates: List = listOf("todo"), @@ -85,7 +87,7 @@ class LoopFixture( prompt: String = "Work on {{ issue.identifier }}: {{ issue.title }}\n", ) { val extraLines = if (extra.isEmpty()) "" else extra.trimEnd() + "\n" - workflow.writeText( + val text = "---\n" + "tracker:\n" + " kind: files\n" + @@ -102,8 +104,8 @@ class LoopFixture( " interval_ms: 1000\n" + extraLines + "---\n" + - prompt, - ) + prompt + replaceAtomically(workflow) { it.writeText(text) } } /** One line per agent call, the attempt id, written outside the project by an agent that logs its calls. */ diff --git a/cli/src/test/kotlin/loop/cli/TranscriptReplay.kt b/cli/src/test/kotlin/loop/cli/TranscriptReplay.kt index 670bf3c..ab7c359 100644 --- a/cli/src/test/kotlin/loop/cli/TranscriptReplay.kt +++ b/cli/src/test/kotlin/loop/cli/TranscriptReplay.kt @@ -40,7 +40,7 @@ fun main(args: Array) { val argv = args.drop(2) // Two attempts of one run may replay at once into the same record folder: each file is replaced atomically, since // concurrent `Files.copy` with REPLACE_EXISTING deletes then creates the target and one of them can fail. - TranscriptReplay.replaceAtomically(record.resolve("argv")) { it.writeText(argv.joinToString("\n")) } + replaceAtomically(record.resolve("argv")) { it.writeText(argv.joinToString("\n")) } val mcpConfig = argv .zipWithNext() @@ -48,7 +48,7 @@ fun main(args: Array) { ?.second ?.let { Path.of(it) } mcpConfig?.let { config -> - TranscriptReplay.replaceAtomically(record.resolve("mcp.json")) { Files.copy(config, it, StandardCopyOption.REPLACE_EXISTING) } + replaceAtomically(record.resolve("mcp.json")) { Files.copy(config, it, StandardCopyOption.REPLACE_EXISTING) } } // The first user message line; Claude Code with `--input-format stream-json` keeps stdin open (m3-07). readlnOrNull() @@ -81,20 +81,6 @@ fun main(args: Array) { } object TranscriptReplay { - /** Writes [target] through [write] into a temporary file of its own folder, then moves it over [target] atomically. */ - fun replaceAtomically( - target: Path, - write: (Path) -> Unit, - ) { - val temp = Files.createTempFile(target.parent, ".${target.fileName}", ".tmp") - try { - write(temp) - Files.move(temp, target, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING) - } finally { - Files.deleteIfExists(temp) - } - } - data class ToolUse( val id: String, val name: String, diff --git a/cli/src/test/kotlin/loop/cli/WorkflowReloadCommandTest.kt b/cli/src/test/kotlin/loop/cli/WorkflowReloadCommandTest.kt index 1fba111..bc81663 100644 --- a/cli/src/test/kotlin/loop/cli/WorkflowReloadCommandTest.kt +++ b/cli/src/test/kotlin/loop/cli/WorkflowReloadCommandTest.kt @@ -81,6 +81,12 @@ class WorkflowReloadCommandTest { private fun events(kind: String): List> = fixture.query("SELECT data FROM events WHERE kind = '$kind' ORDER BY seq").map(::data) + /** The one event of [kind]; when there is not exactly one, the failure lists every event of that kind. */ + private fun single(kind: String): Map { + val all = events(kind) + return all.singleOrNull() ?: fail("expected one $kind event, got ${all.size}:\n${all.joinToString("\n")}") + } + @Test fun `an edit of max_turns while loop run runs reaches the next attempt and loop trace shows each config version`() { useTwoCallAgent() @@ -99,7 +105,7 @@ class WorkflowReloadCommandTest { val turns = events("turn_completed").map { it["max_turns"] } assertEquals(listOf("1", "2"), turns, run.toString()) assertEquals(listOf(first, second), events("attempt_started").map { it["config_version"] }, run.toString()) - val reloaded = events("config_reloaded").single() + val reloaded = single("config_reloaded") assertEquals(second, reloaded["config_version"]) assertEquals(first, reloaded["previous_version"]) assertTrue("- max_turns: 1\n+ max_turns: 2\n" in reloaded.getValue("diff"), reloaded.toString()) @@ -149,7 +155,7 @@ class WorkflowReloadCommandTest { await("the move to review", running) { fixture.stateOf("t-1") == "review" } val run = stop(running) - val rejected = events("config_reload_failed").single() + val rejected = single("config_reload_failed") assertEquals(bad, rejected["config_version"]) assertEquals(good, rejected["active_version"]) assertEquals("invalid_config", rejected["error"])