A self-improving RLM agent for coding workflows and long-running autonomous tasks.
Rust
fix(coding-agent): daemon protocol and quota-park follow-ups (#2502)
Sebastian Müller1b453dc5ab54
diff --git a/packages/coding-agent/.changes/crew-pins-daemon-followups.md b/packages/coding-agent/.changes/crew-pins-daemon-followups.mdnew file mode 100644index 0000000000..9e2d0a29d3--- /dev/null+++ b/packages/coding-agent/.changes/crew-pins-daemon-followups.md@@ -0,0 +1,3 @@+- Fixed quota parks restored after their wake time: a daemon wake or restart now keeps the park count so `retry.provider.waitForUsage.maxParks` still bounds re-parking, and the stale wake job is settled by the resumed session instead of lingering.+- Bumped the daemon schema revision for the structured update-restart error info, so mismatched daemon and CLI builds around that change are detected by the self-update checks.+- Fixed agents-view roster summaries going stale when a session's spawn code changed while every other summary field stayed the same.diff --git a/packages/coding-agent/src/core/agent-session.ts b/packages/coding-agent/src/core/agent-session.tsindex e8813da2cd..d0536e925c 100644--- a/packages/coding-agent/src/core/agent-session.ts+++ b/packages/coding-agent/src/core/agent-session.ts@@ -1542,7 +1542,7 @@ export class AgentSession {jobId?: string;/** Pending in-process wake timer for the current park. */timer?: ReturnType<typeof setTimeout>;- /** True from the wake until the park state clears (the resume probe is running). */+ /** True from the wake until the park state clears: the resume probe is running, or a wake already due is owned by the durable job. */waking?: boolean;/** Wake re-arms consumed without a resume; bounded by QUOTA_WAKE_MAX_RETRIES. */wakeRetries?: number;@@ -13621,8 +13621,9 @@ export class AgentSession {* Restore the park this branch ended on: a restart (daemon or worker) leaves* waitForUsage.maxParks unbounded otherwise, because the park count would* start over at 1 each time. Parks recorded before the branch's last resume- * entry are spent, and a park whose wake time has passed is left to the- * durable wake job — only one that is still ahead re-arms the timer.+ * entry are spent, and a park whose wake time has passed is restored without+ * a timer when its durable job still owns the wake; with no job the+ * in-process timer wakes it at once.*/private _restoreQuotaPark(): void {const branch = this.sessionManager.getBranch();@@ -13638,7 +13639,7 @@ export class AgentSession {continue;}const resumeAtMs = Date.parse(entry.data.resumeAt);- if (!Number.isFinite(resumeAtMs) || resumeAtMs <= Date.now()) {+ if (!Number.isFinite(resumeAtMs)) {return;}const jobId = this._restoreQuotaWakeJob(entry.data.jobId, resumeAtMs);@@ -13654,11 +13655,19 @@ export class AgentSession {jobId,});}+ // A wake already due belongs to its durable job (the daemon delivers it,+ // or the next turn settles it): keep the park so its count still bounds+ // the episode, and arm no timer that would race that delivery. With no+ // job left (a one-shot cannot be rebuilt in the past) the in-process+ // timer wakes the park at once.+ const pastDue = resumeAtMs <= Date.now();this._quotaPark = {parkCount: entry.data.parkCount,resumeAtMs,...(jobId !== undefined ? { jobId } : {}),- timer: this._scheduleQuotaResumeTimer(resumeAtMs),+ ...(pastDue && jobId !== undefined+ ? { waking: true }+ : { timer: this._scheduleQuotaResumeTimer(resumeAtMs) }),};return;}diff --git a/packages/coding-agent/src/modes/daemon/daemon-protocol.ts b/packages/coding-agent/src/modes/daemon/daemon-protocol.tsindex abc8613451..95cf3c2991 100644--- a/packages/coding-agent/src/modes/daemon/daemon-protocol.ts+++ b/packages/coding-agent/src/modes/daemon/daemon-protocol.ts@@ -75,8 +75,9 @@ export const DAEMON_COMMAND_ENVELOPE_MIN_PROTOCOL_VERSION = 7;// Revision 27 adds structured session_recovering failure info for known-but-unaddressable sessions.// Revision 28 publishes the last recorded model on saved-session rows.// Revision 29 adds the capability-gated abort_and_send_queued command.-export const DAEMON_SCHEMA_REVISION = 29;-export const DAEMON_SCHEMA_ID = "protocol-7-schema-29-a5c9d20f8b13";+// Revision 30 adds structured update_restarting failure info for opens fenced by an update restart.+export const DAEMON_SCHEMA_REVISION = 30;+export const DAEMON_SCHEMA_ID = "protocol-7-schema-30-f908f493c9e1";export type DaemonProtocolName = typeof DAEMON_PROTOCOL_NAME;export type DaemonProtocolVersion = number;diff --git a/packages/coding-agent/src/modes/daemon/daemon-session-list.ts b/packages/coding-agent/src/modes/daemon/daemon-session-list.tsindex 73a5c7c398..55f7bc791d 100644--- a/packages/coding-agent/src/modes/daemon/daemon-session-list.ts+++ b/packages/coding-agent/src/modes/daemon/daemon-session-list.ts@@ -274,6 +274,7 @@ interface SummaryComposeFingerprint {metadataParentSessionFile: string | undefined;metadataRlmChildId: string | undefined;metadataRlmParentNodeId: string | undefined;+ metadataSpawnCode: string | undefined;sessionName: string | undefined;sessionId: string;sessionFile: string | undefined;@@ -355,6 +356,7 @@ export function summaryForActiveSession(metadataParentSessionFile: metadata.parentSessionFile,metadataRlmChildId: metadata.rlmChildId,metadataRlmParentNodeId: metadata.rlmParentNodeId,+ metadataSpawnCode: metadata.spawnCode,sessionName: session.sessionName,sessionId: session.sessionId,sessionFile: session.sessionFile,@@ -425,7 +427,7 @@ export function summaryForActiveSession(...(isSummaryCurrent(activeSession) ? { taskState: activeSession.summaryState?.taskState } : {}),};summaryComposeMemos.set(activeSession, { fingerprint, summary });- return summary;+ return Object.freeze(summary);}function summaryComposeFingerprintsEqual(left: SummaryComposeFingerprint, right: SummaryComposeFingerprint): boolean {@@ -456,6 +458,7 @@ function summaryComposeFingerprintsEqual(left: SummaryComposeFingerprint, right:left.metadataParentSessionFile === right.metadataParentSessionFile &&left.metadataRlmChildId === right.metadataRlmChildId &&left.metadataRlmParentNodeId === right.metadataRlmParentNodeId &&+ left.metadataSpawnCode === right.metadataSpawnCode &&left.sessionName === right.sessionName &&left.sessionId === right.sessionId &&left.sessionFile === right.sessionFile &&diff --git a/packages/coding-agent/test/agent-connection-daemon.test.ts b/packages/coding-agent/test/agent-connection-daemon.test.tsindex 4bc3697e52..1b8bebf229 100644--- a/packages/coding-agent/test/agent-connection-daemon.test.ts+++ b/packages/coding-agent/test/agent-connection-daemon.test.ts@@ -1482,7 +1482,7 @@ describe("DaemonAgentConnection", () => {// read the relayed close as "killed"; a direct worker link closes as "shutdown".["announced daemon shutdown", (fakeClient: FakeDaemonClient) => announceClose("shutdown", fakeClient)],["announced supervisor shutdown", (fakeClient: FakeDaemonClient) => announceClose("killed", fakeClient)],- ])("recovers a %s by reconnecting to the restarted daemon", async (_closeKind, triggerClose) => {+ ])("recovers a %s by reconnecting, then a bare session stop is terminal", async (_closeKind, triggerClose) => {const fakeClient = new FakeDaemonClient();fakeClient.hello = { ...fakeClient.hello!, appVersion: "test-daemon-version" };// The restarted daemon lists the same session under a new active id.@@ -1502,6 +1502,9 @@ describe("DaemonAgentConnection", () => {await expect(connected).resolves.toMatchObject({ daemonVersion: "test-daemon-version" });expect(events.filter((event) => event.type === "closed")).toEqual([]);expect(events.filter((event) => event.type === "session_resynced").length).toBeGreaterThan(0);+ // The re-attach cleared the daemon_closing notice: a later bare stop of the recovered session is terminal again.+ fakeClient.emitMessage({ type: "session_closed", activeSessionId: "restored", reason: "killed" });+ expect(events.filter((event) => event.type === "closed")).toHaveLength(1);await connection.dispose();});diff --git a/packages/coding-agent/test/daemon-session-list.test.ts b/packages/coding-agent/test/daemon-session-list.test.tsindex 8e72f66b7a..19d8367ea0 100644--- a/packages/coding-agent/test/daemon-session-list.test.ts+++ b/packages/coding-agent/test/daemon-session-list.test.ts@@ -2,9 +2,10 @@ import { resolve } from "node:path";import type { AgentMessage } from "@earendil-works/pi-agent-core";import { describe, expect, it } from "vitest";import type { RlmChildAgentSnapshot } from "../src/core/agent-session.js";+import type { AgentSessionRuntimeDiagnostic } from "../src/core/agent-session-services.js";import type { AgentCronJob } from "../src/core/cron-jobs.js";import type { SessionActionSnapshot } from "../src/core/session-action-store.js";-import type { SessionInfo } from "../src/core/session-manager.js";+import type { AgentStatus, SessionInfo } from "../src/core/session-manager.js";import type { SessionUsageSummary } from "../src/core/usage.js";import type { ActiveSessionState, DaemonSocketClient } from "../src/modes/daemon/active-session-state.js";import { passivatedWorkerRosterEntry, workerRosterEntryFromSummary } from "../src/modes/daemon/agent-roster.js";@@ -518,6 +519,7 @@ describe("summary compose memoization", () => {// Roster flushes recompose every session each cycle; an unchanged session// must reuse the previous summary instead of recomposing it.expect(summaryForActiveSession(state)).toBe(first);+ expect(Object.isFrozen(first)).toBe(true);});it("recomposes when a message is appended and folds only the new tail", () => {@@ -535,50 +537,35 @@ describe("summary compose memoization", () => {expect(third.lastActivityAt).toBe("2026-05-02T00:00:00.000Z");});- it("recomposes when busy-state bits flip without an append", () => {- const state = makeState({ activeSessionId: "busy", messages: [messageAt("2026-05-01T00:00:00.000Z")] });- const first = summaryForActiveSession(state);- expect(first.isStreaming).toBe(false);- (state.runtime.session as unknown as { isStreaming: boolean }).isStreaming = true;- (state.runtime.session as unknown as { isSessionActive: boolean }).isSessionActive = true;- const second = summaryForActiveSession(state);- expect(second).not.toBe(first);- expect(second).toMatchObject({ isStreaming: true, activity: "working" });- });-- it("recomposes when the summarizer verdict is replaced", () => {- const state = makeState({- activeSessionId: "verdict",- messages: [messageAt("2026-05-01T00:00:00.000Z")],- });- const first = summaryForActiveSession(state);- expect(first.summary).toBeUndefined();- (state as unknown as { summaryState?: object }).summaryState = {- summary: "Editing the router",- taskState: "completed",- basedOnMessageCount: 1,- };- const second = summaryForActiveSession(state);- expect(second).not.toBe(first);- expect(second).toMatchObject({ summary: "Editing the router", taskState: "completed" });- });-- it("recomposes when the visible action snapshot changes", () => {- const state = makeState({ activeSessionId: "queued" });- const first = summaryForActiveSession(state);- expect(first.sessionActions).toMatchObject({ queuedCount: 0 });- (- state.runtime.session as unknown as {- getSessionActionSnapshot: () => SessionActionSnapshot;- }- ).getSessionActionSnapshot = () => ({- queuedCount: 1,- steering: ["revised plan"],- followUps: [],- });- const second = summaryForActiveSession(state);- expect(second).not.toBe(first);- expect(second.sessionActions).toMatchObject({ queuedCount: 1, steering: ["revised plan"] });+ it("recomposes when a compose input changes without an append", () => {+ const state = makeState({ activeSessionId: "inputs", messages: [messageAt("2026-05-01T00:00:00.000Z")] });+ const session = state.runtime.session as unknown as Record<string, unknown> & { state: Record<string, unknown> };+ const runtime = state.runtime as unknown as { diagnostics: unknown[]; metadata: Record<string, unknown> };+ const actions: SessionActionSnapshot = { queuedCount: 1, steering: ["revised plan"], followUps: [] };+ const usage: SessionUsageSummary = { inputTokens: 120, outputTokens: 40, cost: 0.03 };+ const model = { provider: "p", id: "m" } as SessionSummary["model"];+ const streaming = messageAt("2026-05-01T00:00:01.000Z");+ const diagnostic: AgentSessionRuntimeDiagnostic = { type: "warning", message: "rebuilt" };+ const verdict: AgentStatus = { summary: "Editing the router", taskState: "completed", basedOnMessageCount: 1 };+ const mutations: Array<[() => unknown, Partial<SessionSummary>]> = [+ [() => Object.assign(state, { summaryState: verdict }), { summary: "Editing the router" }],+ [() => Object.assign(session, { getSessionActionSnapshot: () => actions }), { sessionActions: actions }],+ [() => Object.assign(session, { getOwnUsageSummary: () => usage }), { usage }],+ [() => Object.assign(session, { model }), { model }],+ [() => Object.assign(session.state, { streamingMessage: streaming }), { streamingMessage: streaming }],+ [() => Object.assign(runtime, { diagnostics: [diagnostic] }), { diagnostics: [diagnostic] }],+ [() => Object.assign(runtime.metadata, { spawnCode: "rlm.spawn('x')" }), { spawnCode: "rlm.spawn('x')" }],+ [() => Object.assign(session, { isSessionActive: true }), { activity: "working" }],+ [() => Object.assign(session, { isStreaming: true }), { isStreaming: true }],+ ];+ let previous = summaryForActiveSession(state);+ for (const [mutate, expected] of mutations) {+ mutate();+ const next = summaryForActiveSession(state);+ expect(next).not.toBe(previous);+ expect(next).toMatchObject(expected);+ previous = next;+ }});it("recomposes when heartbeat registration flags differ per call site", () => {diff --git a/packages/coding-agent/test/suite/agent-session-retry-events.test.ts b/packages/coding-agent/test/suite/agent-session-retry-events.test.tsindex c4a29856ad..11c4f8d535 100644--- a/packages/coding-agent/test/suite/agent-session-retry-events.test.ts+++ b/packages/coding-agent/test/suite/agent-session-retry-events.test.ts@@ -1047,6 +1047,16 @@ describe("AgentSession retry and event characterization", () => {await promptParked(harness, "do the work");const sessionFile = harness.session.sessionFile!;+ // A restart past the wake time keeps the park count and leaves the wake to the durable job: no timer.+ vi.useFakeTimers({ toFake: ["Date"] });+ vi.setSystemTime(quotaPark(harness)!.resumeAtMs + 1);+ const late = await createHarness({ existingSessionFile: sessionFile, settings }).finally(() =>+ vi.useRealTimers(),+ );+ harnesses.push(late);+ expect(quotaPark(late)).toMatchObject({ parkCount: 1, jobId: quotaPark(harness)?.jobId, waking: true });+ expect(quotaPark(late)).not.toHaveProperty("timer");+// A restart rebuilds the park, and the wake still bounds the episode.const restarted = await createHarness({ existingSessionFile: sessionFile, settings });harnesses.push(restarted);@@ -1090,8 +1100,15 @@ describe("AgentSession retry and event characterization", () => {harnesses.push(restarted);expect(restarted.session.isQuotaParked).toBe(true);- await wakeQuotaProbe(harness)();- expect(harness.session.isQuotaParked).toBe(false);+ // Past the wake time the rebuild cannot schedule a one-shot job: the in-process timer wakes the park at once.+ const resumed = assistantTurns(harness);+ await harness.session.navigateTree(lastUserEntryId(harness));+ vi.useFakeTimers({ toFake: ["Date"] });+ vi.setSystemTime(quotaPark(restarted)!.resumeAtMs + 1);+ await harness.session.navigateTree(parkedLeaf);+ await resumed().finally(() => vi.useRealTimers());+ expect([harness.session.isQuotaParked, harness.faux.state.callCount]).toEqual([false, 2]);+ expect(quotaEntries(harness, "provider_quota_resume")[0]?.outcome).toBe("wake");});it("preserves an active goal across a quota park and resumes its continuation", async () => {