From 793091b8b59ea8dfc54585dfbf79b646ede0b8c8 Mon Sep 17 00:00:00 2001 From: Jason Monk Date: Tue, 14 Apr 2026 19:55:24 -0400 Subject: [PATCH] Fix #146: Replace message-prefix log routing with typed LogLevel lambda AppModule was routing `Log.e` vs `Log.w` vs `Log.i` by string-matching message prefixes ("Audit:", "TunnelClient: disconnected:"). Severity is known at the call site, not at wiring. Renaming a log string silently downgraded severity, and "frame arrived after disconnect" landed as WARN despite the spec calling for DEBUG. Introduce `LogLevel { DEBUG, INFO, WARN, ERROR }` in both `:core:mcp` and `:core:tunnel` (duplicated to avoid a cross-module dependency on a four-value enum). Change `log: (String) -> Unit` to `log: (LogLevel, String) -> Unit` on `ConnectionStateMachine`, `TunnelClientImpl`, `MuxDemux`, `configureMcpRouting`, `McpSession`, and the audit-emission helpers. Each call site declares its own severity. AppModule's lambda becomes a simple `when (level)` switch onto `android.util.Log`. The emitted log tags and severities are unchanged for existing events; "frame arrived after disconnect" now correctly lands at DEBUG. Tests capture `Pair` and assert the expected level. Co-Authored-By: Claude Opus 4.6 (1M context) --- .../java/com/rousecontext/app/di/AppModule.kt | 40 +++++++++++++------ .../com/rousecontext/mcp/core/LogLevel.kt | 12 ++++++ .../com/rousecontext/mcp/core/McpRouting.kt | 16 ++++---- .../com/rousecontext/mcp/core/McpSession.kt | 2 +- .../rousecontext/mcp/core/HttpRoutingTest.kt | 9 +++-- .../tunnel/ConnectionStateMachine.kt | 7 +++- .../com/rousecontext/tunnel/LogLevel.kt | 12 ++++++ .../com/rousecontext/tunnel/MuxDemux.kt | 3 +- .../rousecontext/tunnel/TunnelClientImpl.kt | 14 ++++--- .../com/rousecontext/tunnel/MuxDemuxTest.kt | 7 ++-- .../tunnel/ConnectionStateMachineTest.kt | 11 ++--- .../tunnel/TunnelClientImplTest.kt | 11 +++-- 12 files changed, 101 insertions(+), 43 deletions(-) create mode 100644 core/mcp/src/commonMain/kotlin/com/rousecontext/mcp/core/LogLevel.kt create mode 100644 core/tunnel/src/commonMain/kotlin/com/rousecontext/tunnel/LogLevel.kt diff --git a/app/src/main/java/com/rousecontext/app/di/AppModule.kt b/app/src/main/java/com/rousecontext/app/di/AppModule.kt index 00b30ecc..a3b7942c 100644 --- a/app/src/main/java/com/rousecontext/app/di/AppModule.kt +++ b/app/src/main/java/com/rousecontext/app/di/AppModule.kt @@ -347,11 +347,12 @@ val appModule = module { ) ?: "" self == "alert" || ct == "alert" }, - log = { msg -> - if (msg.startsWith("Audit:")) { - Log.e("McpRouting", msg) - } else { - Log.w("McpRouting", msg) + log = { level, msg -> + when (level) { + com.rousecontext.mcp.core.LogLevel.DEBUG -> Log.d("McpRouting", msg) + com.rousecontext.mcp.core.LogLevel.INFO -> Log.i("McpRouting", msg) + com.rousecontext.mcp.core.LogLevel.WARN -> Log.w("McpRouting", msg) + com.rousecontext.mcp.core.LogLevel.ERROR -> Log.e("McpRouting", msg) } } ).also { session -> @@ -384,15 +385,30 @@ val appModule = module { TunnelClientImpl( scope = get(named("appScope")), webSocketFactory = get(), - log = { msg -> - if (msg.startsWith("TunnelClient: disconnected:")) { - Log.i("TunnelClient", msg) - } else { - Log.w("TunnelClient", msg) + log = { level, msg -> + when (level) { + com.rousecontext.tunnel.LogLevel.DEBUG -> Log.d("TunnelClient", msg) + com.rousecontext.tunnel.LogLevel.INFO -> Log.i("TunnelClient", msg) + com.rousecontext.tunnel.LogLevel.WARN -> Log.w("TunnelClient", msg) + com.rousecontext.tunnel.LogLevel.ERROR -> Log.e("TunnelClient", msg) } }, - stateMachineLog = { msg -> Log.w("ConnectionStateMachine", msg) }, - muxDemuxLog = { msg -> Log.w("MuxDemux", msg) } + stateMachineLog = { level, msg -> + when (level) { + com.rousecontext.tunnel.LogLevel.DEBUG -> Log.d("ConnectionStateMachine", msg) + com.rousecontext.tunnel.LogLevel.INFO -> Log.i("ConnectionStateMachine", msg) + com.rousecontext.tunnel.LogLevel.WARN -> Log.w("ConnectionStateMachine", msg) + com.rousecontext.tunnel.LogLevel.ERROR -> Log.e("ConnectionStateMachine", msg) + } + }, + muxDemuxLog = { level, msg -> + when (level) { + com.rousecontext.tunnel.LogLevel.DEBUG -> Log.d("MuxDemux", msg) + com.rousecontext.tunnel.LogLevel.INFO -> Log.i("MuxDemux", msg) + com.rousecontext.tunnel.LogLevel.WARN -> Log.w("MuxDemux", msg) + com.rousecontext.tunnel.LogLevel.ERROR -> Log.e("MuxDemux", msg) + } + } ) } diff --git a/core/mcp/src/commonMain/kotlin/com/rousecontext/mcp/core/LogLevel.kt b/core/mcp/src/commonMain/kotlin/com/rousecontext/mcp/core/LogLevel.kt new file mode 100644 index 00000000..cb5ef7bf --- /dev/null +++ b/core/mcp/src/commonMain/kotlin/com/rousecontext/mcp/core/LogLevel.kt @@ -0,0 +1,12 @@ +package com.rousecontext.mcp.core + +/** + * Severity level for diagnostic log messages emitted by `:core:mcp` classes. + * + * The call site knows the intended severity; the wiring layer decides how to + * map each level onto a concrete logging backend (e.g. `android.util.Log`). + * + * A separate enum is duplicated in `:core:tunnel` to keep the two modules free + * of cross-dependencies. + */ +enum class LogLevel { DEBUG, INFO, WARN, ERROR } diff --git a/core/mcp/src/commonMain/kotlin/com/rousecontext/mcp/core/McpRouting.kt b/core/mcp/src/commonMain/kotlin/com/rousecontext/mcp/core/McpRouting.kt index 95dfd49c..995bc352 100644 --- a/core/mcp/src/commonMain/kotlin/com/rousecontext/mcp/core/McpRouting.kt +++ b/core/mcp/src/commonMain/kotlin/com/rousecontext/mcp/core/McpRouting.kt @@ -77,7 +77,7 @@ fun Application.configureMcpRouting( securityAlertCheck: (() -> Boolean)? = null, serverName: String = "rouse-context", serverVersion: String = "0.1.0", - log: (String) -> Unit = {} + log: (LogLevel, String) -> Unit = { _, _ -> } ) { install(ContentNegotiation) { json(mcpJson) @@ -140,7 +140,7 @@ internal class McpRoutes( private val securityAlertCheck: (() -> Boolean)?, private val serverName: String, private val serverVersion: String, - private val log: (String) -> Unit + private val log: (LogLevel, String) -> Unit ) { // Per-integration MCP servers, created lazily and cached private val integrationServers = mutableMapOf() @@ -231,6 +231,7 @@ internal class McpRoutes( mcpJson.parseToJsonElement(text).jsonObject } catch (e: Exception) { log( + LogLevel.WARN, "McpRouting: /register body read failed: " + "${e::class.simpleName}: ${e.message}" ) @@ -570,6 +571,7 @@ internal class McpRoutes( } } catch (e: Exception) { log( + LogLevel.WARN, "McpRouting: /mcp body read failed: " + "${e::class.simpleName}: ${e.message}" ) @@ -876,7 +878,7 @@ private fun emitAuditEvent( integration: String, startMs: Long, clock: Clock, - log: (String) -> Unit + log: (LogLevel, String) -> Unit ) { val method = try { request["method"]?.jsonPrimitive?.content @@ -919,7 +921,7 @@ private fun emitRequestEvent( method: String, startMs: Long, durationMs: Long, - log: (String) -> Unit + log: (LogLevel, String) -> Unit ) { try { val params = request["params"] @@ -936,7 +938,7 @@ private fun emitRequestEvent( ) ) } catch (e: Exception) { - log("Audit: failed to emit onRequest event: ${e.message}") + log(LogLevel.ERROR, "Audit: failed to emit onRequest event: ${e.message}") } } @@ -948,7 +950,7 @@ private fun emitToolCallEvent( integration: String, startMs: Long, durationMs: Long, - log: (String) -> Unit + log: (LogLevel, String) -> Unit ) { try { val params = request["params"]?.jsonObject ?: return @@ -972,7 +974,7 @@ private fun emitToolCallEvent( ) } catch (e: Exception) { // Audit is best-effort; never fail the request due to audit errors - log("Audit: failed to emit tool-call event: ${e.message}") + log(LogLevel.ERROR, "Audit: failed to emit tool-call event: ${e.message}") } } diff --git a/core/mcp/src/commonMain/kotlin/com/rousecontext/mcp/core/McpSession.kt b/core/mcp/src/commonMain/kotlin/com/rousecontext/mcp/core/McpSession.kt index 02717d30..ca2829f4 100644 --- a/core/mcp/src/commonMain/kotlin/com/rousecontext/mcp/core/McpSession.kt +++ b/core/mcp/src/commonMain/kotlin/com/rousecontext/mcp/core/McpSession.kt @@ -43,7 +43,7 @@ class McpSession( private val securityAlertCheck: (() -> Boolean)? = null, private val serverName: String = "rouse-context", private val serverVersion: String = "0.1.0", - private val log: (String) -> Unit = {} + private val log: (LogLevel, String) -> Unit = { _, _ -> } ) { private val done = CompletableDeferred() diff --git a/core/mcp/src/jvmTest/kotlin/com/rousecontext/mcp/core/HttpRoutingTest.kt b/core/mcp/src/jvmTest/kotlin/com/rousecontext/mcp/core/HttpRoutingTest.kt index 3f85dd85..569663ab 100644 --- a/core/mcp/src/jvmTest/kotlin/com/rousecontext/mcp/core/HttpRoutingTest.kt +++ b/core/mcp/src/jvmTest/kotlin/com/rousecontext/mcp/core/HttpRoutingTest.kt @@ -243,7 +243,7 @@ class HttpRoutingTest { val registry = testRegistry("health" to stubProvider("health", "Health Connect")) val tokenStore = InMemoryTokenStore() val deviceCodeManager = DeviceCodeManager(tokenStore = tokenStore) - val captured = mutableListOf() + val captured = mutableListOf>() application { configureMcpRouting( @@ -252,7 +252,7 @@ class HttpRoutingTest { deviceCodeManager = deviceCodeManager, hostname = "brave-falcon.rousecontext.com", integration = "health", - log = { captured.add(it) } + log = { level, msg -> captured.add(level to msg) } ) } @@ -263,7 +263,10 @@ class HttpRoutingTest { assertEquals(HttpStatusCode.BadRequest, response.status) assertTrue( "Expected /register body read failure log, got $captured", - captured.any { it.startsWith("McpRouting: /register body read failed:") } + captured.any { + it.first == LogLevel.WARN && + it.second.startsWith("McpRouting: /register body read failed:") + } ) } } diff --git a/core/tunnel/src/commonMain/kotlin/com/rousecontext/tunnel/ConnectionStateMachine.kt b/core/tunnel/src/commonMain/kotlin/com/rousecontext/tunnel/ConnectionStateMachine.kt index ee8ceeca..fac22f17 100644 --- a/core/tunnel/src/commonMain/kotlin/com/rousecontext/tunnel/ConnectionStateMachine.kt +++ b/core/tunnel/src/commonMain/kotlin/com/rousecontext/tunnel/ConnectionStateMachine.kt @@ -17,7 +17,7 @@ import kotlinx.coroutines.flow.asStateFlow * - ACTIVE -> CONNECTED (last stream closed) * - DISCONNECTING -> DISCONNECTED */ -class ConnectionStateMachine(private val log: (String) -> Unit = {}) { +class ConnectionStateMachine(private val log: (LogLevel, String) -> Unit = { _, _ -> }) { private val _state = MutableStateFlow(TunnelState.DISCONNECTED) @@ -35,7 +35,10 @@ class ConnectionStateMachine(private val log: (String) -> Unit = {}) { fun transition(to: TunnelState): Boolean { val from = _state.value if (!isValidTransition(from, to)) { - log("ConnectionStateMachine: ignoring invalid transition from $from to $to") + log( + LogLevel.WARN, + "ConnectionStateMachine: ignoring invalid transition from $from to $to" + ) return false } _state.value = to diff --git a/core/tunnel/src/commonMain/kotlin/com/rousecontext/tunnel/LogLevel.kt b/core/tunnel/src/commonMain/kotlin/com/rousecontext/tunnel/LogLevel.kt new file mode 100644 index 00000000..b5909e80 --- /dev/null +++ b/core/tunnel/src/commonMain/kotlin/com/rousecontext/tunnel/LogLevel.kt @@ -0,0 +1,12 @@ +package com.rousecontext.tunnel + +/** + * Severity level for diagnostic log messages emitted by `:core:tunnel` classes. + * + * The call site knows the intended severity; the wiring layer decides how to + * map each level onto a concrete logging backend (e.g. `android.util.Log`). + * + * A separate enum is duplicated in `:core:mcp` to keep the two modules free of + * cross-dependencies. + */ +enum class LogLevel { DEBUG, INFO, WARN, ERROR } diff --git a/core/tunnel/src/commonMain/kotlin/com/rousecontext/tunnel/MuxDemux.kt b/core/tunnel/src/commonMain/kotlin/com/rousecontext/tunnel/MuxDemux.kt index 50b6c483..e8ed49f2 100644 --- a/core/tunnel/src/commonMain/kotlin/com/rousecontext/tunnel/MuxDemux.kt +++ b/core/tunnel/src/commonMain/kotlin/com/rousecontext/tunnel/MuxDemux.kt @@ -14,7 +14,7 @@ import kotlinx.coroutines.sync.withLock * * Thread-safe: all access to the stream map is synchronized via a [Mutex]. */ -class MuxDemux(private val log: (String) -> Unit = {}) { +class MuxDemux(private val log: (LogLevel, String) -> Unit = { _, _ -> }) { private val streams = mutableMapOf() private val streamsMutex = Mutex() @@ -62,6 +62,7 @@ class MuxDemux(private val log: (String) -> Unit = {}) { incomingChannel.send(stream) } else { log( + LogLevel.WARN, "MuxDemux: rejecting stream ${frame.streamId}, " + "limit $maxStreams reached" ) diff --git a/core/tunnel/src/commonMain/kotlin/com/rousecontext/tunnel/TunnelClientImpl.kt b/core/tunnel/src/commonMain/kotlin/com/rousecontext/tunnel/TunnelClientImpl.kt index dbc7d274..d1b52e11 100644 --- a/core/tunnel/src/commonMain/kotlin/com/rousecontext/tunnel/TunnelClientImpl.kt +++ b/core/tunnel/src/commonMain/kotlin/com/rousecontext/tunnel/TunnelClientImpl.kt @@ -19,9 +19,9 @@ import kotlinx.coroutines.launch class TunnelClientImpl( private val scope: CoroutineScope, private val webSocketFactory: WebSocketFactory, - private val log: (String) -> Unit = {}, - private val stateMachineLog: (String) -> Unit = {}, - private val muxDemuxLog: (String) -> Unit = {} + private val log: (LogLevel, String) -> Unit = { _, _ -> }, + private val stateMachineLog: (LogLevel, String) -> Unit = { _, _ -> }, + private val muxDemuxLog: (LogLevel, String) -> Unit = { _, _ -> } ) : TunnelClient { private val stateMachine = ConnectionStateMachine(log = stateMachineLog) private var muxDemux: MuxDemux? = null @@ -41,6 +41,7 @@ class TunnelClientImpl( override suspend fun connect(url: String) { if (!stateMachine.transition(TunnelState.CONNECTING)) { log( + LogLevel.WARN, "TunnelClient: connect() ignored, current state is ${stateMachine.state.value}" ) return @@ -62,7 +63,10 @@ class TunnelClientImpl( try { demux.handleFrame(muxFrame) } catch (_: kotlinx.coroutines.channels.ClosedSendChannelException) { - log("TunnelClient: frame arrived after disconnect, ignoring") + log( + LogLevel.DEBUG, + "TunnelClient: frame arrived after disconnect, ignoring" + ) } } } @@ -153,7 +157,7 @@ class TunnelClientImpl( } private suspend fun handleDisconnect(error: TunnelError) { - log("TunnelClient: disconnected: ${error.message}") + log(LogLevel.INFO, "TunnelClient: disconnected: ${error.message}") _errors.emit(error) // Use quiet cleanup -- transport is already broken, don't try to send CLOSE frames muxDemux?.closeAllQuietly() diff --git a/core/tunnel/src/commonTest/kotlin/com/rousecontext/tunnel/MuxDemuxTest.kt b/core/tunnel/src/commonTest/kotlin/com/rousecontext/tunnel/MuxDemuxTest.kt index dc794374..1df97082 100644 --- a/core/tunnel/src/commonTest/kotlin/com/rousecontext/tunnel/MuxDemuxTest.kt +++ b/core/tunnel/src/commonTest/kotlin/com/rousecontext/tunnel/MuxDemuxTest.kt @@ -183,8 +183,8 @@ class MuxDemuxTest { @Test fun rejectedOpenInvokesLogLambda() = runBlocking { - val captured = mutableListOf() - val demux = MuxDemux(log = { captured.add(it) }) + val captured = mutableListOf>() + val demux = MuxDemux(log = { level, msg -> captured.add(level to msg) }) demux.maxStreams = 1 demux.onOutgoingFrame = { /* swallow ERROR frame */ } @@ -199,7 +199,8 @@ class MuxDemuxTest { demux.handleFrame(MuxFrame.Open(streamId = 2u)) assertEquals(1, captured.size) - assertTrue(captured[0].contains("rejecting stream 2")) + assertEquals(LogLevel.WARN, captured[0].first) + assertTrue(captured[0].second.contains("rejecting stream 2")) coroutineContext.cancelChildren() } diff --git a/core/tunnel/src/jvmTest/kotlin/com/rousecontext/tunnel/ConnectionStateMachineTest.kt b/core/tunnel/src/jvmTest/kotlin/com/rousecontext/tunnel/ConnectionStateMachineTest.kt index 06305f36..751c2d51 100644 --- a/core/tunnel/src/jvmTest/kotlin/com/rousecontext/tunnel/ConnectionStateMachineTest.kt +++ b/core/tunnel/src/jvmTest/kotlin/com/rousecontext/tunnel/ConnectionStateMachineTest.kt @@ -158,12 +158,13 @@ class ConnectionStateMachineTest { @Test fun invalidTransitionInvokesLogLambda() { - val captured = mutableListOf() - val sm = ConnectionStateMachine(log = { captured.add(it) }) + val captured = mutableListOf>() + val sm = ConnectionStateMachine(log = { level, msg -> captured.add(level to msg) }) sm.transition(TunnelState.CONNECTED) assertEquals(1, captured.size) - assertTrue(captured[0].contains("invalid transition")) - assertTrue(captured[0].contains("DISCONNECTED")) - assertTrue(captured[0].contains("CONNECTED")) + assertEquals(LogLevel.WARN, captured[0].first) + assertTrue(captured[0].second.contains("invalid transition")) + assertTrue(captured[0].second.contains("DISCONNECTED")) + assertTrue(captured[0].second.contains("CONNECTED")) } } diff --git a/core/tunnel/src/jvmTest/kotlin/com/rousecontext/tunnel/TunnelClientImplTest.kt b/core/tunnel/src/jvmTest/kotlin/com/rousecontext/tunnel/TunnelClientImplTest.kt index dd525d6c..484963e7 100644 --- a/core/tunnel/src/jvmTest/kotlin/com/rousecontext/tunnel/TunnelClientImplTest.kt +++ b/core/tunnel/src/jvmTest/kotlin/com/rousecontext/tunnel/TunnelClientImplTest.kt @@ -405,11 +405,11 @@ class TunnelClientImplTest { @Test fun `connection failure invokes log lambda`() = runBlocking { - val captured = mutableListOf() + val captured = mutableListOf>() val client = TunnelClientImpl( this, KtorWebSocketFactory(), - log = { captured.add(it) } + log = { level, msg -> captured.add(level to msg) } ) // Connect to a port that nothing is listening on -- triggers handleDisconnect @@ -420,8 +420,11 @@ class TunnelClientImplTest { delay(200) assertTrue( - captured.any { it.startsWith("TunnelClient: disconnected:") }, - "Expected log message starting with 'TunnelClient: disconnected:', got $captured" + captured.any { + it.first == LogLevel.INFO && + it.second.startsWith("TunnelClient: disconnected:") + }, + "Expected INFO log starting with 'TunnelClient: disconnected:', got $captured" ) coroutineContext.cancelChildren()