chore(clean up): remove unused imports, unnecessary object impls, concurrency/coroutine issues, trailing commas, etc.

This commit is contained in:
2026-05-24 22:56:19 +04:00
parent 71aac8afc9
commit ac05ad8733
16 changed files with 85 additions and 83 deletions
@@ -132,20 +132,24 @@ class RunCommand : CliktCommand(name = "run") {
setExitCode(0)
false
}
"SessionFailed" -> {
val reason = field("reason") ?: "unknown"
printLine("session_failed", mapOf("sessionId" to ctx.sid, "reason" to reason), ctx.outputJson)
setExitCode(1)
false
}
"StageStarted" -> {
printLine("stage_started", mapOf("stageId" to (field("stageId") ?: "")), ctx.outputJson)
true
}
"StageCompleted" -> {
printLine("stage_completed", mapOf("stageId" to (field("stageId") ?: "")), ctx.outputJson)
true
}
"StageFailed" -> {
printLine(
"stage_failed",
@@ -154,14 +158,17 @@ class RunCommand : CliktCommand(name = "run") {
)
true
}
"ToolStarted" -> {
printLine("tool_started", mapOf("tool" to (field("toolName") ?: "")), ctx.outputJson)
true
}
"ToolCompleted" -> {
printLine("tool_completed", mapOf("tool" to (field("toolName") ?: "")), ctx.outputJson)
true
}
"ToolFailed" -> {
printLine(
"tool_failed",
@@ -170,6 +177,7 @@ class RunCommand : CliktCommand(name = "run") {
)
true
}
"ToolRejected" -> {
printLine(
"tool_rejected",
@@ -178,6 +186,7 @@ class RunCommand : CliktCommand(name = "run") {
)
true
}
"ApprovalRequired" -> {
val approvalCtx = ApprovalContext(
session = session,
@@ -187,6 +196,7 @@ class RunCommand : CliktCommand(name = "run") {
)
handleApproval(approvalCtx, ctx, setExitCode)
}
else -> true
}
}
@@ -200,7 +210,7 @@ class RunCommand : CliktCommand(name = "run") {
val steeringNote = if (decision == "STEER" && ctx.isTty) {
print("Steering note: ")
readLine()
readlnOrNull()
} else {
null
}
@@ -225,10 +235,11 @@ class RunCommand : CliktCommand(name = "run") {
ctx.autoApprove -> "APPROVE"
!ctx.isTty -> {
System.err.println(
"WARNING: approval required but no TTY and --auto-approve not set — denying"
"WARNING: approval required but no TTY and --auto-approve not set — denying",
)
"REJECT"
}
else -> promptApproval(toolName, preview)
}
@@ -236,7 +247,7 @@ class RunCommand : CliktCommand(name = "run") {
println("\nApproval required for tool: $toolName")
preview?.let { println("Preview: $it") }
print("[a]pprove / [r]eject / [s]teer: ")
return when (readLine()?.trim()?.lowercase()) {
return when (readlnOrNull()?.trim()?.lowercase()) {
"a", "approve" -> "APPROVE"
"s", "steer" -> "STEER"
else -> "REJECT"
@@ -256,4 +267,4 @@ class RunCommand : CliktCommand(name = "run") {
}
}
class SystemExitException(val code: Int) : Exception("exit $code")
class SystemExitException(code: Int) : Exception("exit $code")
@@ -67,8 +67,9 @@ class SessionEventBridgeTest {
override suspend fun appendAll(events: List<NewEvent>): List<StoredEvent> = error("unused")
override fun read(sessionId: SessionId): List<StoredEvent> = allEventsList
override fun readFrom(sessionId: SessionId, fromSequence: Long): List<StoredEvent> = allEventsList
override fun lastSequence(sessionId: SessionId): Long? =
override fun lastSequence(sessionId: SessionId): Long =
allEventsList.maxOfOrNull { it.sequence } ?: 0L
override fun subscribe(sessionId: SessionId): Flow<StoredEvent> = liveFlow
override fun allEvents(): Sequence<StoredEvent> = allEventsList.asSequence()
override fun allSessionIds(): Set<SessionId> = allEventsList.map { it.metadata.sessionId }.toSet()
@@ -51,7 +51,7 @@ fun main(args: Array<String>) {
log.debug("got input state after reducers: {}", next.input)
log.debug(
"got session state after reducers: {}",
next.sessions.sessions.firstOrNull() { it.status != "COMPLETED" },
next.sessions.sessions.firstOrNull { it.status != "COMPLETED" },
)
state = next
effects.forEach { effect ->
@@ -71,7 +71,7 @@ private fun createRowsForNavigate(
hasSession: Boolean,
): Pair<Line?, Line?> {
val row1Line = Line.from(Span.styled(" ↑↓ sessions enter select", dimStyle))
val hints = buildList<String> {
val hints = buildList {
add("$sessionName · navigate")
add("tab router")
if (hasApproval) {
@@ -96,7 +96,7 @@ private fun createRowsForRouter(
} else {
Line.from(Span.raw(""), Span.styled("Ask anything…", dimStyle))
}
val hints = buildList<String> {
val hints = buildList {
add("$sessionName · router")
add("tab navigate")
if (hasApproval) {
@@ -142,10 +142,7 @@ abstract class SessionOrchestrator(
?.let { path ->
runCatching { promptResolver.resolve(path) }
.onFailure {
log.error(
"[SessionOrchestrator] stage=${stageId.value}: " +
"failed to load prompt '$path': ${it.message}",
)
log.error(error(stageId, path, it))
}
.getOrNull()
}
@@ -165,10 +162,7 @@ abstract class SessionOrchestrator(
?.let { path ->
runCatching { promptResolver.resolve(path) }
.onFailure {
log.error(
"[SessionOrchestrator] stage=${stageId.value}: " +
"failed to load default system prompt '$path': ${it.message}",
)
log.error(error(stageId, path, it))
}
.getOrNull()
}
@@ -275,6 +269,13 @@ abstract class SessionOrchestrator(
}
}
private fun error(
stageId: StageId,
path: String,
throwable: Throwable,
): String = "[SessionOrchestrator] stage=${stageId.value}: " +
"failed to load prompt '$path': ${throwable.message}"
private suspend fun dispatchToolCalls(
sessionId: SessionId,
stageId: StageId,
@@ -7,6 +7,7 @@ import com.correx.core.artifacts.kind.FileWrittenPayload
import com.correx.infrastructure.artifactscas.segment.SegmentLayout
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import java.nio.file.Files
import java.nio.file.Path
@@ -15,7 +16,7 @@ import java.nio.file.attribute.PosixFilePermissions
class DefaultMaterializingArtifactWriter : MaterializingArtifactWriter {
private companion object {
val log = LoggerFactory.getLogger(DefaultMaterializingArtifactWriter::class.java)
val log: Logger = LoggerFactory.getLogger(DefaultMaterializingArtifactWriter::class.java)
const val DEFAULT_MODE = "644"
const val OCTAL_RADIX = 8
const val POSIX_PERMISSION_BITS = 9
@@ -37,6 +37,7 @@ class TailScanner(
private suspend fun scanAndRecover(activeId: Long, path: Path, startOffset: Long): TailScanReport {
var recovered = 0
var truncatedAt: Long? = null
withContext(Dispatchers.IO) {
RandomAccessFile(path.toFile(), "rw").use { raf ->
val fileLen = raf.length()
var pos = startOffset
@@ -53,6 +54,7 @@ class TailScanner(
// Truncate at first bad/partial record so writer resumes at a clean boundary.
truncatedAt?.let { raf.setLength(it) }
}
}
return TailScanReport(activeId, startOffset, recovered, truncatedAt)
}
@@ -25,7 +25,7 @@ import java.util.concurrent.*
class LiveArtifactRepository(
private val eventStore: EventStore,
private val reducer: ArtifactReducer,
reducer: ArtifactReducer,
private val scope: CoroutineScope = CoroutineScope(Dispatchers.IO + SupervisorJob()),
) : ArtifactRepository {
@@ -41,8 +41,8 @@ class LiveArtifactRepository(
override fun getByStage(sessionId: SessionId, stageId: StageId): Map<ArtifactId, ArtifactState> {
ensureSubscribed(sessionId)
val cache = artifactCache[sessionId] ?: emptyMap<ArtifactId, ArtifactState>()
val index = stageIndex[sessionId] ?: emptyMap<ArtifactId, StageId>()
val cache = artifactCache[sessionId] ?: emptyMap()
val index = stageIndex[sessionId] ?: emptyMap()
return cache.filter { (artifactId, _) -> index[artifactId] == stageId }
}
@@ -24,6 +24,7 @@ import kotlinx.serialization.json.buildJsonArray
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.put
import kotlinx.serialization.json.putJsonObject
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import java.io.IOException
import java.nio.file.Files
@@ -40,7 +41,7 @@ class FileWriteTool(
) : Tool, FileAffectingTool, ToolExecutor {
private companion object {
val log = LoggerFactory.getLogger(FileWriteTool::class.java)
val log: Logger = LoggerFactory.getLogger(FileWriteTool::class.java)
}
private val normalizedAllowedPaths: Set<Path> = allowedPaths.map { it.normalize().toAbsolutePath() }.toSet()
@@ -172,7 +173,9 @@ class FileWriteTool(
): ToolResult = when (operation) {
"write" -> {
val content = request.parameters["content"] as String
withContext(Dispatchers.IO) {
Files.writeString(path, content)
}
storeArtifact(pathString, content, request.parameters["mode"] as? String ?: "0644")
ToolResult.Success(
invocationId = request.invocationId,
@@ -182,7 +185,9 @@ class FileWriteTool(
"delete" -> {
if (Files.exists(path)) {
withContext(Dispatchers.IO) {
Files.deleteIfExists(path)
}
ToolResult.Success(
invocationId = request.invocationId,
output = "File deleted successfully: $pathString",
@@ -145,7 +145,7 @@ class FileWriteToolTest {
assertTrue(result is ToolResult.Success)
val success = result as ToolResult.Success
assertEquals("File written successfully to ${filePath}", success.output)
assertEquals("File written successfully to $filePath", success.output)
assertEquals(invocationId, success.invocationId)
assertEquals(content, Files.readString(filePath))
}
@@ -31,20 +31,22 @@ class DefaultInferenceRouterTest {
override fun register(provider: InferenceProvider) = Unit
override fun resolve(capability: ModelCapability) =
providers.filter { p -> p.capabilities().any { it.capability == capability } }
override fun listAll() = providers.toList()
override suspend fun healthCheckAll() = providers.associate { it.id to ProviderHealth.Healthy }
}
private fun firstStrategy(): RoutingStrategy =
object : RoutingStrategy {
override fun select(candidates: List<InferenceProvider>, requiredCapabilities: Set<ModelCapability>) =
RoutingStrategy { candidates, _ ->
candidates.firstOrNull() ?: throw NoEligibleProviderException(StageId("?"), emptySet())
}
private fun throwingStrategy(): RoutingStrategy =
object : RoutingStrategy {
override fun select(candidates: List<InferenceProvider>, requiredCapabilities: Set<ModelCapability>) =
throw NoEligibleProviderException(StageId("?"), requiredCapabilities)
RoutingStrategy { _, requiredCapabilities ->
throw NoEligibleProviderException(
StageId("?"),
requiredCapabilities,
)
}
// ── capability matching ───────────────────────────────────────────────────
@@ -60,14 +62,9 @@ class DefaultInferenceRouterTest {
fun `deduplicates providers that satisfy multiple required capabilities`(): Unit = runBlocking {
val p = provider("a", ModelCapability.General, ModelCapability.Coding)
val selected = mutableListOf<InferenceProvider>()
val captureStrategy = object : RoutingStrategy {
override fun select(
candidates: List<InferenceProvider>,
requiredCapabilities: Set<ModelCapability>,
): InferenceProvider {
val captureStrategy = RoutingStrategy { candidates, _ ->
selected.addAll(candidates)
return candidates.first()
}
candidates.first()
}
val router = DefaultInferenceRouter(
registryOf(p),
@@ -7,7 +7,6 @@ import com.correx.core.events.types.SessionId
import com.correx.testing.contracts.utils.ConcurrencyRunner
import com.correx.testing.fixtures.EventFixtures
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.yield
@@ -39,7 +38,7 @@ abstract class EventStoreContractTest {
store.append(e)
assertThrows<Exception> {
runBlocking { store.append(e) }
store.append(e)
}
Assertions.assertEquals(1, store.read(SessionId("s1")).size)
}
@@ -75,7 +74,7 @@ abstract class EventStoreContractTest {
ConcurrencyRunner.run(20, 100) { t, i ->
runBlocking {
store.append(
EventFixtures.newEvent(EventId("e-$i-$t"), SessionId("s1"))
EventFixtures.newEvent(EventId("e-$i-$t"), SessionId("s1")),
)
}
}
@@ -152,7 +151,7 @@ abstract class EventStoreContractTest {
store.append(EventFixtures.newEvent(EventId("a-$t-$i"), SessionId("s1")))
} else {
store.appendAll(
listOf(EventFixtures.newEvent(EventId("b-$t-$i"), SessionId("s1")))
listOf(EventFixtures.newEvent(EventId("b-$t-$i"), SessionId("s1"))),
)
}
}
@@ -1,5 +1,4 @@
import com.correx.core.events.events.EventMetadata
import com.correx.core.events.events.EventPayload
import com.correx.core.events.events.NewEvent
import com.correx.core.events.events.SessionPausedEvent
import com.correx.core.events.events.SessionResumedEvent
@@ -20,7 +19,7 @@ class SessionReplayDeterminismTest {
private fun build(store: EventStore) = DefaultEventReplayer(
store,
SessionProjector(DefaultSessionReducer())
SessionProjector(DefaultSessionReducer()),
)
@Test
@@ -30,16 +29,16 @@ class SessionReplayDeterminismTest {
val store1 = InMemoryEventStore()
val store2 = InMemoryEventStore()
val events = mapOf<EventMetadata, EventPayload>(
val events = mapOf(
EventMetadata(EventId("start"), sessionId, Clock.System.now(), 1, null, null) to SessionStartedEvent(
sessionId
sessionId,
),
EventMetadata(EventId("paused"), sessionId, Clock.System.now(), 1, null, null) to SessionPausedEvent(
sessionId
sessionId,
),
EventMetadata(EventId("resumed"), sessionId, Clock.System.now(), 1, null, null) to SessionResumedEvent(
sessionId
)
sessionId,
),
)
events.forEach { (meta, payload) ->
@@ -2,10 +2,8 @@ package com.correx.testing.fixtures.transitions
import com.correx.core.events.types.StageId
import com.correx.core.events.types.TransitionId
import com.correx.core.transitions.evaluation.EvaluationContext
import com.correx.core.transitions.evaluation.TransitionConditionEvaluator
import com.correx.core.transitions.graph.StageConfig
import com.correx.core.transitions.graph.TransitionCondition
import com.correx.core.transitions.graph.TransitionEdge
import com.correx.core.transitions.graph.WorkflowGraph
import com.correx.core.transitions.resolution.DefaultTransitionResolver
@@ -15,11 +13,7 @@ import com.correx.testing.fixtures.WorkflowFixtures
object TransitionFixtures {
fun alwaysTrueEvaluator(): TransitionConditionEvaluator {
return object : TransitionConditionEvaluator {
override fun evaluate(condition: TransitionCondition, context: EvaluationContext): Boolean {
return true
}
}
return TransitionConditionEvaluator { _, _ -> true }
}
fun simpleResolver(): TransitionResolver {
@@ -1,5 +1,4 @@
import com.correx.core.events.events.EventMetadata
import com.correx.core.events.events.EventPayload
import com.correx.core.events.events.NewEvent
import com.correx.core.events.events.SessionCompletedEvent
import com.correx.core.events.events.SessionPausedEvent
@@ -26,15 +25,15 @@ class SessionReplayTest {
fun `rebuild session from event stream`(): Unit = kotlinx.coroutines.runBlocking {
val sessionId = SessionId("s1")
val metadataToPayload = mapOf<EventMetadata, EventPayload>(
val metadataToPayload = mapOf(
EventMetadata(EventId("start"), sessionId, Clock.System.now(), 1, null, null) to SessionStartedEvent(
sessionId
sessionId,
),
EventMetadata(EventId("paused"), sessionId, Clock.System.now(), 1, null, null) to SessionPausedEvent(
sessionId
sessionId,
),
EventMetadata(EventId("resumed"), sessionId, Clock.System.now(), 1, null, null) to SessionResumedEvent(
sessionId
sessionId,
),
EventMetadata(
EventId("completed"),
@@ -42,7 +41,7 @@ class SessionReplayTest {
Clock.System.now(),
1,
null,
null
null,
) to SessionCompletedEvent(sessionId),
)
@@ -16,14 +16,7 @@ import org.junit.jupiter.api.assertInstanceOf
class DefaultTransitionResolverTest {
private val evaluator = object : TransitionConditionEvaluator {
override fun evaluate(
condition: TransitionCondition,
context: EvaluationContext,
): Boolean {
return condition.evaluate(context)
}
}
private val evaluator = TransitionConditionEvaluator { condition, context -> condition.evaluate(context) }
private val resolver: TransitionResolver = DefaultTransitionResolver(evaluator)