A self-improving RLM agent for coding workflows and long-running autonomous tasks.
Rust
fix(coding-agent): persist kernel stderr to disk and bound the in-memory tail (#1947)
Sebastian Müller5c2750bdc3c9
diff --git a/packages/coding-agent/.changes/kernel-stderr-log.md b/packages/coding-agent/.changes/kernel-stderr-log.mdnew file mode 100644index 0000000000..9d844a4c5e--- /dev/null+++ b/packages/coding-agent/.changes/kernel-stderr-log.md@@ -0,0 +1 @@+- Kernel process stderr now lands in `kernel-stderr.log` in the session artifact directory (rotated at kernel start and capped by a 5 MiB per-spawn write budget), and the in-memory diagnostics tail is bounded instead of growing for the kernel's lifetime.diff --git a/packages/coding-agent/src/core/kernel/repl-manager.ts b/packages/coding-agent/src/core/kernel/repl-manager.tsindex a78ae3282a..8500c392af 100644--- a/packages/coding-agent/src/core/kernel/repl-manager.ts+++ b/packages/coding-agent/src/core/kernel/repl-manager.ts@@ -2,6 +2,8 @@// (`python -m rlm.repl`) — requests on stdin, events on stdout, stderr kept as// a diagnostics tail. The protocol is documented in prime-agent-runtime/src/rlm/repl.md.import { type ChildProcess, spawn } from "node:child_process";+import { closeSync, existsSync, mkdirSync, openSync, renameSync, rmSync, statSync, writeSync } from "node:fs";+import { dirname } from "node:path";import { StringDecoder } from "node:string_decoder";import { v4 as uuid } from "uuid";import { reapKernelOrphanProcesses, recordOrphanProcessState } from "../orphan-process-journal.js";@@ -56,6 +58,18 @@ const MAX_HANDLED_HOST_REQUEST_IDS = 1024;// Cap for unattributed background output buffered between and during cells.const MAX_BACKGROUND_OUTPUT_CHARS = 64 * 1024;+const MAX_KERNEL_STDERR_CHARS = 8 * 1024;+const MAX_KERNEL_STDERR_LOG_BYTES = 5 * 1024 * 1024;+const KERNEL_STDERR_LOG_BUDGET_MARKER = "[stderr log budget exhausted]\n";++/** fs.writeSync may write fewer bytes than asked (partial ENOSPC, signals); loop until done. */+function writeFullySync(fd: number, data: Buffer): void {+ let offset = 0;+ while (offset < data.length) {+ offset += writeSync(fd, data, offset);+ }+}+/** ExecuteResult plus the raw fields of the request's `done` event (state ops). */interface InternalExecuteResult extends ExecuteResult {doneFields?: Record<string, unknown>;@@ -136,7 +150,15 @@ function asReasonArray(value: unknown): { name: string; reason: string }[] {export class ReplKernelManager {private readonly options: Pick<KernelManagerOptions,- "python" | "cwd" | "env" | "sessionId" | "hostHandlers" | "pythonSkills" | "snapshot" | "bootstrapCode"+ | "python"+ | "cwd"+ | "env"+ | "sessionId"+ | "hostHandlers"+ | "pythonSkills"+ | "snapshot"+ | "bootstrapCode"+ | "stderrLogPath">;private readonly handledHostRequestIds = new Set<string>();private child?: ChildProcess;@@ -193,6 +215,7 @@ export class ReplKernelManager {pythonSkills: options.pythonSkills,snapshot: options.snapshot,bootstrapCode: options.bootstrapCode,+ stderrLogPath: options.stderrLogPath,};}@@ -201,7 +224,40 @@ export class ReplKernelManager {}private appendKernelDiagnostic(message: string): void {- this.kernelStderr += `[kernel] ${message.endsWith("\n") ? message : `${message}\n`}`;+ this.appendKernelStderrText(`[kernel] ${message.endsWith("\n") ? message : `${message}\n`}`);+ }++ private appendKernelStderrText(text: string): void {+ this.kernelStderr = (this.kernelStderr + text).slice(-MAX_KERNEL_STDERR_CHARS);+ }++ /**+ * The write budget is the file's remaining capacity, not a fresh allowance,+ * so current file and `.old` each stay near MAX_KERNEL_STDERR_LOG_BYTES and+ * per-session disk near 2x — even when rotation fails and the file is kept.+ */+ private openStderrLog(): { fd: number; budget: number } | undefined {+ const path = this.options.stderrLogPath;+ if (!path) return undefined;+ try {+ mkdirSync(dirname(path), { recursive: true });+ let size = existsSync(path) ? statSync(path).size : 0;+ if (size > MAX_KERNEL_STDERR_LOG_BYTES) {+ try {+ // Drop any prior .old first: rename fails on Windows if it exists.+ rmSync(`${path}.old`, { force: true });+ renameSync(path, `${path}.old`);+ size = 0;+ } catch (error) {+ // A failed rotation must not cost the log: keep appending instead.+ this.appendKernelDiagnostic(`cannot rotate kernel stderr log: ${errorMessage(error)}`);+ }+ }+ return { fd: openSync(path, "a"), budget: Math.max(0, MAX_KERNEL_STDERR_LOG_BYTES - size) };+ } catch (error) {+ this.appendKernelDiagnostic(`cannot open kernel stderr log: ${errorMessage(error)}`);+ return undefined;+ }}async start(options: KernelStartOptions = {}): Promise<void> {@@ -328,8 +384,51 @@ export class ReplKernelManager {}});+ // The runtime dup2's fd 2 into its protocol pump before ready (repl.py+ // _setup_fds), so this pipe only ever carries pre-ready bytes; the write+ // budget caps what lands on disk, and once it is spent the handler keeps+ // draining but discards (a blocked pipe would wedge a pre-ready kernel).+ const stderrLog = this.openStderrLog();+ const stderrDecoder = new StringDecoder("utf8");+ let stderrLogBudget = stderrLog?.budget ?? 0;+ let stderrLogWritable = stderrLog !== undefined;child.stderr?.on("data", (buf: Buffer) => {- this.kernelStderr += buf.toString();+ this.appendKernelStderrText(stderrDecoder.write(buf));+ if (!stderrLogWritable || stderrLog === undefined) return;+ try {+ if (buf.length <= stderrLogBudget) {+ writeFullySync(stderrLog.fd, buf);+ stderrLogBudget -= buf.length;+ } else {+ writeFullySync(stderrLog.fd, Buffer.from(KERNEL_STDERR_LOG_BUDGET_MARKER));+ stderrLogWritable = false;+ }+ } catch (error) {+ stderrLogWritable = false;+ this.appendKernelDiagnostic(`kernel stderr log write failed: ${errorMessage(error)}`);+ }+ });+ // A kernel that dies mid-character leaves bytes buffered in the decoder;+ // flush them so the tail keeps the truncated final character. Both events,+ // because each can be the only one to precede the tail build: 'end' beats+ // 'exit' on natural EOF (whose 'close' emission can land after it), while+ // a drain-destroyed stream skips 'end'. The second end() returns "".+ child.stderr?.once("end", () => this.appendKernelStderrText(stderrDecoder.end()));+ child.stderr?.once("close", () => {+ this.appendKernelStderrText(stderrDecoder.end());+ if (stderrLog === undefined) return;+ try {+ closeSync(stderrLog.fd);+ } catch (error) {+ this.appendKernelDiagnostic(`kernel stderr log close failed: ${errorMessage(error)}`);+ }+ });+ child.once("exit", () => {+ // One turn for the poll phase to deliver the bytes the kernel wrote+ // before dying (the pipe buffer bounds them), then destroy: EOF may+ // never come, and anything later is a surviving grandchild's+ // post-mortem noise, not the kernel's last words.+ globalThis.setImmediate(() => child.stderr?.destroy());});child.on("error", (err) => {@@ -588,8 +687,16 @@ export class ReplKernelManager {return await new Promise<number>((resolve, reject) => {ready.promise.then(resolve, reject);onExit = () => {- const tail = this.kernelStderr.slice(-1024);- reject(new Error(`Kernel exited before ready. stderr:\n${tail || "(empty)"}`));+ const finish = () => {+ const tail = this.kernelStderr.slice(-1024);+ reject(new Error(`Kernel exited before ready. stderr:\n${tail || "(empty)"}`));+ };+ // The final stderr chunks can still be in flight at 'exit'; wait for+ // the drained pipe so the tail includes the kernel's last words (the+ // ready timeout stays armed, bounding the wait).+ const stderr = child.stderr;+ if (!stderr || stderr.closed) finish();+ else stderr.once("close", finish);};if (child.exitCode !== null || child.signalCode !== null) {onExit();@@ -1157,7 +1264,13 @@ export class ReplKernelManager {if (child) {child.stdin?.destroy();child.stdout?.destroy();- child.stderr?.destroy();+ // An exited child keeps its stderr: the post-exit drain owns it, and+ // destroying here would drop its buffered last words. A still-alive+ // child may ignore the kill signal and never emit 'exit', so that+ // drain would never run — destroy now to bound the pipe's lifetime.+ if (child.exitCode === null && child.signalCode === null) {+ child.stderr?.destroy();+ }const pid = child.pid;let signaled = false;try {diff --git a/packages/coding-agent/src/core/kernel/shared.ts b/packages/coding-agent/src/core/kernel/shared.tsindex 25d43b9178..6f5e4c3225 100644--- a/packages/coding-agent/src/core/kernel/shared.ts+++ b/packages/coding-agent/src/core/kernel/shared.ts@@ -56,6 +56,8 @@ export interface KernelManagerOptions {snapshot?: KernelSnapshotConfig;/** Runtime bootstrap re-run on a protocol-repaired kernel so live handles (rlm, bash, skills) exist again. */bootstrapCode?: string;+ /** File receiving the kernel process's stderr, rotated once at each spawn. */+ stderrLogPath?: string;}export interface KernelStartOptions {diff --git a/packages/coding-agent/src/core/tools/ipython.ts b/packages/coding-agent/src/core/tools/ipython.tsindex 6c8501b928..5f1171024d 100644--- a/packages/coding-agent/src/core/tools/ipython.ts+++ b/packages/coding-agent/src/core/tools/ipython.ts@@ -1,4 +1,5 @@import { existsSync } from "node:fs";+import { join } from "node:path";import type { AgentTool } from "@earendil-works/pi-agent-core";import type { ImageContent, TextContent } from "@earendil-works/pi-ai";import { type Static, Type } from "typebox";@@ -474,6 +475,7 @@ export class IpythonKernelProvisioner {snapshot: snapshotDir? { path: snapshotPathIn(snapshotDir), manifestPath: manifestPathIn(snapshotDir) }: undefined,+ stderrLogPath: snapshotDir ? join(snapshotDir, "kernel-stderr.log") : undefined,bootstrapCode,});let pendingRestore: RestoreResult | undefined;diff --git a/packages/coding-agent/test/repl-kernel-shutdown.test.ts b/packages/coding-agent/test/repl-kernel-shutdown.test.tsindex f39bf469fe..081942902b 100644--- a/packages/coding-agent/test/repl-kernel-shutdown.test.ts+++ b/packages/coding-agent/test/repl-kernel-shutdown.test.ts@@ -19,7 +19,11 @@ type ShutdownInternals = {pid?: number;stdin: { destroyed: boolean; destroy: () => void };stdout?: { destroy: () => void; on: (event: string, listener: (...args: unknown[]) => void) => void };- stderr?: { destroy: () => void; on: (event: string, listener: (...args: unknown[]) => void) => void };+ stderr?: {+ destroy: () => void;+ on: (event: string, listener: (...args: unknown[]) => void) => void;+ once: (event: string, listener: (...args: unknown[]) => void) => void;+ };};};@@ -44,7 +48,7 @@ function configuredManager(pid: undefined,stdin: { destroyed: false, destroy: vi.fn() },stdout: { destroy: vi.fn(), on: vi.fn() },- stderr: { destroy: vi.fn(), on: vi.fn() },+ stderr: { destroy: vi.fn(), on: vi.fn(), once: vi.fn() },});Object.assign(internals, {state: "running",@@ -273,6 +277,23 @@ describe("ReplKernelManager graceful shutdown", () => {expect(start).not.toHaveBeenCalled();});+ it("kill() destroys stderr only while the child has not exited", async () => {+ // Alive child: it may ignore the signal and never emit 'exit', so the+ // post-exit drain would never bound the pipe — teardown must.+ const alive = configuredManager(() => {});+ const aliveChild = alive.internals.child;+ await alive.manager.kill();+ expect(aliveChild.stderr?.destroy).toHaveBeenCalledTimes(1);++ // Exited child: the post-exit drain owns the stream; destroying it in+ // teardown would drop the kernel's buffered last words.+ const exited = configuredManager(() => {});+ const exitedChild = exited.internals.child;+ exitedChild.exitCode = 42;+ await exited.manager.kill();+ expect(exitedChild.stderr?.destroy).not.toHaveBeenCalled();+ });+it("waits for the matching shutdown done and removes its waiter", async () => {const { manager, internals } = configuredManager(async (request, state) => {expect(request.type).toBe("shutdown");diff --git a/packages/coding-agent/test/repl-kernel-startup.test.ts b/packages/coding-agent/test/repl-kernel-startup.test.tsindex 219453f729..3c4707954c 100644--- a/packages/coding-agent/test/repl-kernel-startup.test.ts+++ b/packages/coding-agent/test/repl-kernel-startup.test.ts@@ -1,9 +1,43 @@-import { chmodSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { ReplKernelManager } from "../src/core/kernel/index.js";+// closeSync failures and short writes cannot be forced for real, so the mock+// arms faults against the stderr log fd, marked at open by its path;+// everything else passes through.+const closeFailure = vi.hoisted(() => ({ armed: false, fd: undefined as number | undefined }));+const shortWrites = vi.hoisted(() => ({ armed: false, fd: undefined as number | undefined }));+vi.mock("node:fs", async (importOriginal) => {+ const actual = await importOriginal<typeof import("node:fs")>();+ const openSync: typeof actual.openSync = (...args) => {+ const fd = actual.openSync(...args);+ if (String(args[0]).endsWith("kernel-stderr.log")) {+ if (closeFailure.armed) closeFailure.fd = fd;+ if (shortWrites.armed) shortWrites.fd = fd;+ }+ return fd;+ };+ const closeSync: typeof actual.closeSync = (fd) => {+ if (closeFailure.fd === fd) {+ closeFailure.fd = undefined;+ throw new Error("simulated stderr log close failure");+ }+ actual.closeSync(fd);+ };+ const writeSync = ((...args: [number, ...unknown[]]) => {+ const [fd, data, offset] = args as [number, NodeJS.ArrayBufferView | string, number?];+ if (shortWrites.fd === fd && typeof data !== "string") {+ const start = offset ?? 0;+ const remaining = data.byteLength - start;+ if (remaining > 1) return actual.writeSync(fd, data as Uint8Array, start, Math.ceil(remaining / 2));+ }+ return (actual.writeSync as (...forwarded: unknown[]) => number)(...args);+ }) as typeof actual.writeSync;+ return { ...actual, openSync, closeSync, writeSync };+});+let tempDir = "";function writeExecutable(filePath: string, content: string): void {@@ -39,6 +73,192 @@ describe("ReplKernelManager startup", () => {}});+ it("lands the exact kernel stderr bytes in the log file", async () => {+ const python = join(tempDir, "python");+ writeExecutable(+ python,+ [+ "#!/bin/sh",+ "printf 'progress 1\\rprogress 2\\rcaf\\303' >&2",+ "sleep 0.2",+ "printf '\\251\\n' >&2",+ // Trailing lone \303: the kernel dies mid-character.+ 'printf "final stderr line\\303" >&2',+ "exit 42",+ "",+ ].join("\n"),+ );+ const stderrLogPath = join(tempDir, "kernel-stderr.log");+ const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});+ const manager = new ReplKernelManager({ python, cwd: tempDir, stderrLogPath });+ // Byte fidelity must survive short writes: the mock halves every write to+ // the log fd, so only a write-all loop lands the exact bytes.+ shortWrites.armed = true;++ try {+ await expect(manager.execute("print(1)")).rejects.toThrow(+ // The \ufffd from the flushed decoder can land after the host's exit+ // diagnostic (exit/EOF order differs by platform).+ /Kernel exited before ready[\s\S]*caf\u00e9[\s\S]*final stderr line[\s\S]*\ufffd/,+ );+ await manager.shutdown({ snapshot: true, drainHostRequests: true });+ const expected = Buffer.concat([+ Buffer.from("progress 1\rprogress 2\rcaf\u00e9\nfinal stderr line", "utf8"),+ Buffer.from([0o303]),+ ]);+ expect(readFileSync(stderrLogPath).equals(expected)).toBe(true);+ } finally {+ shortWrites.armed = false;+ shortWrites.fd = undefined;+ errorSpy.mockRestore();+ }+ });++ it("completes teardown while an inherited grandchild keeps writing stderr", async () => {+ const python = join(tempDir, "python");+ writeExecutable(+ python,+ [+ "#!/bin/sh",+ // A busy writer inherits fd 2 and survives the kernel: its stream+ // never goes quiet and never EOFs.+ "sh -c 'while :; do echo post-mortem noise; done' >&2 &",+ "exit 42",+ "",+ ].join("\n"),+ );+ const stderrLogPath = join(tempDir, "kernel-stderr.log");+ const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});+ const manager = new ReplKernelManager({ python, cwd: tempDir, stderrLogPath });++ try {+ // Well under the 30s ready timeout: teardown must not wait for the+ // grandchild (destroying the pipe kills it with SIGPIPE).+ await expect(manager.execute("print(1)")).rejects.toThrow(/Kernel exited before ready/);+ } finally {+ errorSpy.mockRestore();+ await manager.shutdown({ snapshot: true, drainHostRequests: true });+ }+ }, 15000);++ it("caps the stderr log at the write budget while draining pre-ready spew", async () => {+ const python = join(tempDir, "python");+ writeExecutable(+ python,+ [+ "#!/bin/sh",+ // 6 MiB of spew: over the 5 MiB write budget, and far beyond the pipe+ // buffer, so the script only finishes if the host keeps draining.+ "head -c 6291456 /dev/zero | tr '\\0' x >&2",+ "printf 'SPEW TAIL' >&2",+ "exit 42",+ "",+ ].join("\n"),+ );+ const stderrLogPath = join(tempDir, "kernel-stderr.log");+ const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});+ const manager = new ReplKernelManager({ python, cwd: tempDir, stderrLogPath });++ try {+ // The in-memory tail still surfaces the kernel's last words even though+ // the on-disk log stopped at the budget.+ await expect(manager.execute("print(1)")).rejects.toThrow(/Kernel exited before ready[\s\S]*SPEW TAIL/);+ await manager.shutdown({ snapshot: true, drainHostRequests: true });+ const marker = "[stderr log budget exhausted]\n";+ const log = readFileSync(stderrLogPath, "utf8");+ expect(log.endsWith(marker)).toBe(true);+ expect(statSync(stderrLogPath).size).toBeLessThanOrEqual(5 * 1024 * 1024 + marker.length);+ } finally {+ errorSpy.mockRestore();+ }+ });++ it("survives a stderr log close failure with a diagnostic", async () => {+ const python = join(tempDir, "python");+ writeExecutable(python, ["#!/bin/sh", 'echo "goodbye" >&2', "exit 42", ""].join("\n"));+ const stderrLogPath = join(tempDir, "kernel-stderr.log");+ const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});+ const manager = new ReplKernelManager({ python, cwd: tempDir, stderrLogPath });+ closeFailure.armed = true;++ try {+ // The pin is host survival: an unguarded throw in the 'close' listener+ // is an unhandled error that fails this file. The close diagnostic+ // itself lands in the tail only after the 'close' emission, which can+ // trail this rejection, so it is not asserted here.+ await expect(manager.execute("print(1)")).rejects.toThrow(/Kernel exited before ready[\s\S]*goodbye/);+ } finally {+ closeFailure.armed = false;+ errorSpy.mockRestore();+ await manager.shutdown({ snapshot: true, drainHostRequests: true });+ }+ });++ it("stops writing at capacity when the oversized file cannot rotate", async () => {+ const python = join(tempDir, "python");+ writeExecutable(python, ["#!/bin/sh", 'echo "fresh incarnation" >&2', "exit 42", ""].join("\n"));+ const stderrLogPath = join(tempDir, "kernel-stderr.log");+ const previous = Buffer.alloc(5 * 1024 * 1024 + 1, "x");+ writeFileSync(stderrLogPath, previous);+ // A directory at the .old path makes the rotation's rm/rename throw.+ mkdirSync(`${stderrLogPath}.old`);+ const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});+ const manager = new ReplKernelManager({ python, cwd: tempDir, stderrLogPath });++ try {+ // The tail still carries the stderr; the file, already over capacity,+ // gains only the marker — not another per-spawn budget.+ await expect(manager.execute("print(1)")).rejects.toThrow(+ /cannot rotate kernel stderr log[\s\S]*fresh incarnation/,+ );+ await manager.shutdown({ snapshot: true, drainHostRequests: true });+ const marker = "[stderr log budget exhausted]\n";+ expect(statSync(stderrLogPath).size).toBe(previous.length + marker.length);+ expect(readFileSync(stderrLogPath, "utf8").endsWith(marker)).toBe(true);+ } finally {+ errorSpy.mockRestore();+ }+ });++ it("grants only the file's remaining capacity as the write budget", async () => {+ const python = join(tempDir, "python");+ writeExecutable(python, ["#!/bin/sh", 'echo "fresh incarnation" >&2', "exit 42", ""].join("\n"));+ const stderrLogPath = join(tempDir, "kernel-stderr.log");+ // Exactly at capacity: not oversized, so no rotation — and no room left.+ writeFileSync(stderrLogPath, Buffer.alloc(5 * 1024 * 1024, "x"));+ const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});+ const manager = new ReplKernelManager({ python, cwd: tempDir, stderrLogPath });++ try {+ await expect(manager.execute("print(1)")).rejects.toThrow(/Kernel exited before ready/);+ await manager.shutdown({ snapshot: true, drainHostRequests: true });+ const marker = "[stderr log budget exhausted]\n";+ expect(statSync(stderrLogPath).size).toBe(5 * 1024 * 1024 + marker.length);+ expect(readFileSync(stderrLogPath, "utf8").endsWith(marker)).toBe(true);+ } finally {+ errorSpy.mockRestore();+ }+ });++ it("rotates an oversized stderr log at spawn", async () => {+ const python = join(tempDir, "python");+ writeExecutable(python, ["#!/bin/sh", 'echo "fresh incarnation" >&2', "exit 42", ""].join("\n"));+ const stderrLogPath = join(tempDir, "kernel-stderr.log");+ const previous = Buffer.alloc(5 * 1024 * 1024 + 1, "x");+ writeFileSync(stderrLogPath, previous);+ const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});+ const manager = new ReplKernelManager({ python, cwd: tempDir, stderrLogPath });++ try {+ await expect(manager.execute("print(1)")).rejects.toThrow(/Kernel exited before ready/);+ await manager.shutdown({ snapshot: true, drainHostRequests: true });+ expect(statSync(`${stderrLogPath}.old`).size).toBe(previous.length);+ expect(readFileSync(stderrLogPath, "utf8")).toBe("fresh incarnation\n");+ } finally {+ errorSpy.mockRestore();+ }+ });+it("fails a runtime announcing an unexpected protocol version", async () => {const python = join(tempDir, "python");writeExecutable(