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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions cli/src/test/kotlin/loop/cli/AtomicFiles.kt
Original file line number Diff line number Diff line change
@@ -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)
}
}
35 changes: 27 additions & 8 deletions cli/src/test/kotlin/loop/cli/ClaudeCodeTrackerToolsTest.kt
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -68,17 +69,17 @@ 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 =
fixture
.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.
Expand Down Expand Up @@ -124,17 +125,18 @@ 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
.issueFile("l-1")
.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.
Expand All @@ -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")
Expand All @@ -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 =
Expand Down
8 changes: 5 additions & 3 deletions cli/src/test/kotlin/loop/cli/LoopFixture.kt
Original file line number Diff line number Diff line change
Expand Up @@ -78,14 +78,16 @@ 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<String> = listOf("todo"),
extra: String = "",
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" +
Expand All @@ -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. */
Expand Down
18 changes: 2 additions & 16 deletions cli/src/test/kotlin/loop/cli/TranscriptReplay.kt
Original file line number Diff line number Diff line change
Expand Up @@ -40,15 +40,15 @@ fun main(args: Array<String>) {
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()
.firstOrNull { it.first == "--mcp-config" }
?.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()
Expand Down Expand Up @@ -81,20 +81,6 @@ fun main(args: Array<String>) {
}

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,
Expand Down
10 changes: 8 additions & 2 deletions cli/src/test/kotlin/loop/cli/WorkflowReloadCommandTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,12 @@ class WorkflowReloadCommandTest {
private fun events(kind: String): List<Map<String, String>> =
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<String, String> {
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()
Expand All @@ -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())
Expand Down Expand Up @@ -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"])
Expand Down