Zero Labs
Industry News / AI

SoPhi Harness — A Black Box That Can’t Crash the Plane: Teaching an Agent to Learn Without Touching…

Source · Towards AI By Shukri Shukriev

From the publisher’s feed, collected in the ZeroLabs newsroom.

SoPhi Harness — A Black Box That Can’t Crash the Plane: Teaching an Agent to Learn Without Touching Its ControlsSeries: Building SoPhi — a Kotlin Agent Harness — Article 09Every airliner carries a box that the pilots never fly by. It sits in the tail, wired into the same data bus that feeds the cockpit instruments, and writes down everything: altitude, throttle, every switch thrown. It has three rules that matter more than anything it records. It never sends a signal back into the controls. It never asks the crew for anything. And if it breaks, the aircraft lands anyway. A recorder that could bring the plane down would be the most dangerous thing on board.SoPhi is an agent: it gets work done by calling tools, reading a file, running a command, fetching a page, and every one of those calls is a moment worth writing down. Its learning system started with a recorder, and the first surprise was that the wiring was already in the airframe. The plugin system had shipped with two hook points, one before each tool call and one after (HookPoint.BEFORE_TOOL and HookPoint.AFTER_TOOL in sophi-extensions), and nothing had ever fired them. Meanwhile, AgentLoop was already announcing every tool call it made, because the terminal needed to draw a spinner for each one. The bus was running. Nobody had plugged a recorder into it.ADR-008, dated 2026–07–09, made the bet for all four phases of the learning system: learning lives in its own sophi-learning module and observes the agent through the plugin system, never from inside the loop. ADR-009, the same day, settled the other half: what gets written down, and what the agent is allowed to read back. This article is about that first phase, which computes almost nothing clever. Its job was to get the recorder wired in without letting it touch the controls.A wire to a bus that was already runningAgentLoop emits TurnEvents through an onEvent callback: text deltas, tool call started, tool call finished. The CLI draws them. SophiRuntime used to throw them away. Activating the dead hook points needed no new event system, just an adapter from one stream to the other. Here is the whole of TurnEventBridge.kt:fun PluginRegistry.turnEventBridge(sessionId: String): suspend (TurnEvent) -> Unit = { event -> when (event) { is TurnEvent.ToolCallStarted -> dispatch( HookPoint.BEFORE_TOOL, HookContext(sessionId, toolName = event.name, argumentsJson = event.argsJson) ) is TurnEvent.ToolCallFinished -> dispatch( HookPoint.AFTER_TOOL, HookContext( sessionId, toolName = event.name, toolResult = event.result, success = !event.isError, durationMillis = event.durationMillis ) ) else -> Unit }}The return type is the point. A bridge is a suspend (TurnEvent) -> Unit, the same shape as the onEvent the loop already accepts, so a host composes it with its own handler and passes the result in. AgentLoop has no idea a plugin registry exists; sophi-core still doesn't depend on sophi-extensions. The only change the loop itself took was two fields on an event it already emitted with the data in hand:onEvent(TurnEvent.ToolCallStarted(call.name, call.argumentsJson))val start = System.currentTimeMillis()// ... execute, or record a denial ...// Tools signal a handled failure by returning an "Error: "-prefixed string// just as often as by throwing (every built-in tool's own validation follows// this convention) — count both the same way for loop-guard/reliability purposes.failed = failed || result.startsWith("Error: ")onEvent(TurnEvent.ToolCallFinished(call.name, result, failed, System.currentTimeMillis() - start))The obvious alternative was a LearningInterceptor inside the loop, a few lines in the dispatch code that call a learning store directly. It would have worked on day one. It would also have made every embedder of sophi-core carry learning whether they wanted it or not, and it would have put the recorder's wiring inside the controls, which is exactly the coupling the black-box rules exist to forbid. ADR-008 rejected it in its first reason: core stays minimal.That failed = failed || ... line is a later edit, and a useful one. In July, isError was true only when a tool threw or was denied. Most of Sophi's built-in tools never throw: they validate their input and return "Error: path is outside the workspace" as a string, which the model reads and recovers from. The recorder logged those calls as successes. Nobody noticed for almost three weeks, until someone chasing an unrelated race spotted it, and the comment left behind is the real lesson: a recorder is only as honest as the signal on the bus. The bridge was right; the bus was quietly wrong about which calls had failed.AgentLoop emits one stream of events. The host's own handler draws the terminal; the bridge turns the same events into BEFORE_TOOL/AFTER_TOOL dispatches that LearningPlugin records. Nothing flows back into the loop.Record everything, replay nothingThe recorder needed something the session file didn’t have. Before ADR-009, AgentLoop saved only what the user typed and what the assistant answered. The tool rounds in between (which tool, what arguments, what came back) lived in memory for the length of one turn and were gone. The session-end evaluator coming in phase 2 would need to judge how the agent worked, and the training export in phase 4 would need faithful tool_calls messages. Neither could be rebuilt after the fact.Saving them naively would have broken something else. PromptBuilder turns every session entry into a message for the next request, so persisted tool rounds would start riding along in every later prompt: more tokens on every turn, and a real chance of a malformed request, since providers require each tool call to be paired exactly with its result. The answer was a flag on the entry rather than a new file. AgentLoop appends tool rounds as real entries marked replay=false:pendingRounds.add(PendingEntry( EntryRole.ASSISTANT, "", mapOf( "replay" to "false", "toolCalls" to entryJson.encodeToString( toolCalls.map { ToolCallRecord(it.id, it.name, it.argumentsJson) }) )))and PromptBuilder drops them on the way out, one line before anything else happens:fun build(entries: List): List = entries .filter { it.metadata["replay"] != "false" } .map { entry ->That is the flight recorder’s first rule in code. The box sits on the bus, but the cockpit never reads from it. ADR-009 states the guarantee as a test: prompts built from a session are byte-identical before and after the change. Tool rounds are inert for prompting and live for everything else.The rule only holds if every reader of the session obeys it, and the first review found one that didn’t. When a conversation gets too long for the model’s context, it ContextCompactor squeezes its older part into a single summary. It walked session.branch() directly, so the summary prompt it sent to the model included raw tool output, and the summary then went back into the conversation. A session that was never supposed to see its tool results again would read a paraphrase of them on the next turn. The fix in 3d7f701 is a filter in the same spirit as PromptBuilder's, and it is still there today:// replay=false entries (e.g. persisted tool rounds) are inert for prompting; keep them in// the DAG but exclude them from the transcript and the keep/compact split so the summary// never leaks raw tool output and keepRecentCount counts real conversation entries.val replayable = entries.filter { it.metadata["replay"] != "false" }// The kept tail must open on a USER entry: the summary pair ends on ASSISTANT.val cut = cutIndex(replayable, keepRecentCount)if (cut The end of that comment is the less obvious bug. keepRecentCount = 4 meant "keep the last four messages of the conversation". With tool rounds counted, one busy turn could fill all four slots with tool calls and push the user's actual question into the summary.Three months later the compactor came back to the record, this time on purpose. A summary written from conversation alone keeps the gist of a long session and loses its specifics: which files Sophi had edited, which command had failed. In mid-October, a round of work on how Sophi manages its context gave the compactor a WorkingSet, built from the very replay=false entries it had been told to ignore:val transcript = toCompact.joinToString("\n") { entry -> "${entry.role.name}: ${entry.content}" }// The WorkingSet reads the persisted tool rounds too, so exact files/commands survive the cut.val fresh = WorkingSet.fromEntries(entries.takeWhile { it.id != firstKeptId })This doesn’t break the rule, it refines it. The transcript still holds conversation only. The WorkingSet takes facts out of the tool rounds, not text: which files were read or written, which commands ran and their exit codes, one short line per error. In flight-recorder terms, the crew still never hears the tape, but they now get a checklist that was filled in from it.The flag also carried a feature its authors didn’t plan for. In October, the new stop button needed to save a turn the user had interrupted halfway through a tool call. The provider rejects a tool call with no result, so saveStopped writes one, and marks it the same way:calls.forEach { c -> session.append(EntryRole.TOOL_RESULT, "Stopped by $by before this finished.", mapOf("replay" to "false", "toolCallId" to c.id, "toolName" to c.name))}The record stays complete for the evaluator and the export, and the prompt never learns that a synthetic result exists. Nobody had to design a new mechanism; the July rule already covered it. The $by arrived later that month with file checkpoints and/undo: a turn that dies on a network error after a tool round has already changed files, and /undo needs that round on disk, so the same function now saves it, "Stopped by an error", under the same flag.The session JSONL holds both conversation and tool rounds. PromptBuilder and the compactor's transcript skips every replay=false entry; the compactor's WorkingSet takes only facts from them (files, commands, exit codes); the evaluator and the export read all of them.Every tape needs a flight numberA recording you can’t attribute is just noise. Phase 4 would turn sessions into training examples, and a training example without the model that produced it and the system prompt it ran under is useless. Both were per-turn AgentConfig values, never saved. ADR-009 put them in the .meta.json sidecar that the previous article introduced for parentSessionId, never in the JSONL entry format:override fun saveConfigSnapshot(sessionId: String, model: String, systemPrompt: String?) { validateId(sessionId) writeSidecar(sessionId, readSidecar(sessionId).copy(model = model, systemPrompt = systemPrompt))}The sidecar is read with ignoreUnknownKeys, so every session saved before July still loads. SessionManager gives the method a no-op default, so an in-memory session manager simply doesn't record a snapshot, and the CLI, the web host, and SophiRuntime each call it once when a session starts. All three wrap the call in runCatching. That wrapping is the recorder's third rule, and it turned out to need its own section.A recorder that can’t crash the planeAn observer that can fail the system it observes is worse than no observer. ADR-008 states it as a constraint, and LearningPlugin enforces it in two places. Every hook body runs inside a wrapper that swallows its own exceptions:private fun hook(p: HookPoint, body: suspend (HookContext) -> Unit): AgentHook = object : AgentHook { override val point = p override suspend fun invoke(context: HookContext) { runCatching { body(context) } } }and every write to a store goes through one helper:private fun append(log: JsonlLog, line: String) { runCatching { log.append(line) } // learning must never break a turn}The stores themselves follow ADR-005, the same append-only design as sessions: one JSON object per line under ~/.sophi/learning/, every record tagged with a scope (the working directory) so lessons can be filtered per project and still be recalled across them. A crash mid-write leaves at most a torn last line, which readers skip.Intention wasn’t enough to make that discipline hold, and the review proved it. AgentLoop runs a round's tool calls concurrently withasync, so AFTER_TOOL hooks for one session fire from several coroutines at once. The first version counted tool calls and errors with a plainInt, which silently loses increments under that load: no exception, no crash, just a recorder that writes the wrong number. The fix made the counters atomic and the file append @Synchronized:private class Acc { // Mutated from concurrent async tool dispatches; atomics prevent lost updates. val turns = AtomicInteger(0) val toolCalls = AtomicInteger(0) val toolErrors = AtomicInteger(0) @Volatile var errored: Boolean = false val planningNotes = java.util.Collections.synchronizedList(mutableListOf())}The same review found the second-order cost of a recorder that never complains: when it isn’t wired in, nothing complains either. SophiRuntime.turn() dispatchedAFTER_TURN, but the CLI drove AgentLoop through its own TurnController and never did, so CLI sessions recorded tool events and no turn outcomes. The fix landed in the same review commit. A bigger version of the same gap lasted two months. The desktop companion, added in August, never called recordSessionEnd at all, so companion sessions were never evaluated. The fix, in early September, moved session-end wiring into one SophiRuntime.recordSessionEnd that both hosts call. A black box that has been unplugged looks exactly like one that recorded a quiet flight. The fail-silent rule is right, but it means every host's wiring has to be tested directly, because a missing recorder produces no errors to notice.recordSessionEnd itself shows how far the "cheap, mechanical, always" idea travelled. It returns the mechanical outcome before the optional LLM evaluation runs, so a caller that only needs a success signal doesn't have to wait for or depend on a model:val mechanical = SessionOutcome( ts = System.currentTimeMillis(), scope = config.scope, sessionId = sessionId, outcome = if (acc.errored) "error" else "completed", turns = acc.turns.get(), toolCalls = acc.toolCalls.get(), toolErrors = acc.toolErrors.get(), model = model, planningNote = acc.planningNotes.takeIf { it.isNotEmpty() }?.joinToString("\n"))runCatching { outcomes.append(json.encodeToString(SessionOutcome.serializer(), mechanical)) }That return value is what memory’s forgetting logic now reads to decide which recalled memories were worth recalling. The planningNote field arrived with /goal in August. Both are fields on a record that phase 1 defined, filled by systems phase 1 didn't know would exist.Reading the tapes, starting with countingWith the recorder wired in, phase 1 closed the smallest possible loop. ToolStatsStore folds the tool-event log into per-scope, per-tool numbers: attempts, failures, the current failure streak, the last few error snippets. It rebuilds from the file at most once a minute. There are no LLM calls involved, only counting.ToolReliabilitySection turns those numbers into a note in the system prompt, and only when it has to:val problems = stats.stats(scope).filterValues { s -> s.attempts >= config.reliabilityMinAttempts && (s.failures.toDouble() / s.attempts >= config.reliabilityFailureRate || s.streak >= 3)}if (problems.isEmpty()) return nullA warning that always fires is noise, so the gate has two parts. A tool needs at least five attempts before it is judged at all, and then needs either a 50% failure rate or three failures in a row. Most sessions inject nothing. When fetch_url has been timing out against a flaky intranet all morning, the model reads "fetch_url: failed 4 of last 6 calls. Last error: ..." before it tries again.It’s deliberately unambitious. Its job was to prove the pipeline end to end (event, bridge, hook, store, fold, prompt) before anything smarter was built on it, and it has since done more than that. When the self-improvement orchestrator arrived in August (ADR-027, ADR-029), the signal it used to decide where to propose changes was ToolStatsStore.stats(), the same fold, read by a new consumer.Instrument firstThe previous article gave every subagent run a paper trail in the sidecar, so a delegation could be traced back to the turn that spawned it. Phase 1 is the same instinct applied to the whole agent: write down what happened, in a place that can’t change what happens next. Nothing in it is clever. The bridge is twenty lines, the replay rule is one filter applied in two places, the reliability note is a threshold check. What made it work were the restrictions: the loop doesn’t know it is being observed, the prompt can’t see the record, and the recorder can’t break a turn. Every later phase relies on those three things being true.A flight recorder earns its keep after the flight, when an investigator sits down with the tape. Phase 1 built the box and left that seat empty on purpose. The next article fills it with the one LLM call this phase deliberately didn’t make: a debrief at the end of each session that reads the record and decides what was worth remembering.What’s next?The next article in this series covers what the learning system does with the record, or as the title refers to it: One LLM call at session end: lesson distillation without a vector storeIf you’re working on agent-based systems or have thoughts on the build-vs-buy divide in the JVM ecosystem, I’d love to hear your take in the comments below. If this deep dive helped clarify your own architectural choices, a few claps go a long way in helping other engineers find this series. Follow along to stay updated as we build in public.Find the full source on GitHub and connect with me on LinkedIn.SoPhi Harness — A Black Box That Can’t Crash the Plane: Teaching an Agent to Learn Without Touching… was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.