A self-improving RLM agent for coding workflows and long-running autonomous tasks.
Rust
fix(coding-agent): single projection for RLM child snapshots (#1845)
Sebastian Müllerc0334a176fb8
diff --git a/packages/coding-agent/.changes/rlm-child-snapshot.md b/packages/coding-agent/.changes/rlm-child-snapshot.mdnew file mode 100644index 0000000000..ce9aa258aa--- /dev/null+++ b/packages/coding-agent/.changes/rlm-child-snapshot.md@@ -0,0 +1 @@+- Fixed reattached sessions omitting queued child agents or showing the wrong child activity.diff --git a/packages/coding-agent/src/core/agent-session.ts b/packages/coding-agent/src/core/agent-session.tsindex 1df004b2a4..d349643726 100644--- a/packages/coding-agent/src/core/agent-session.ts+++ b/packages/coding-agent/src/core/agent-session.ts@@ -885,6 +885,10 @@ interface RlmChildRun {sessionDir: string;model: Model<Api>;status: RlmChildAgentStatus;+ durationMs?: number;+ answerPreview?: string;+ toolUseCount: number;+ activity?: RlmChildAgentActivity;error?: string;abort: () => void;publication: AgentMessageDeferred;@@ -914,6 +918,11 @@ interface RlmChildRun {unsubscribe?: () => void;}+interface RetainedRlmChild {+ session: AgentSession;+ run?: RlmChildRun;+}+interface RlmSubagentModelSelection {model: Model<Api>;}@@ -1167,7 +1176,7 @@ export class AgentSession {private _pendingRlmSubagentSessionNames = new Set<string>();// Inline mode keeps finished child sessions so the inspector can still read them;// the daemon does the same by leaving the child session resident in its registry.- private _rlmChildSessions = new Map<string, AgentSession>();+ private _rlmChildSessions = new Map<string, RetainedRlmChild>();private _deletedRlmChildIds = new Set<string>();// Failed explicit deletes stay hidden from listings but retain their original// selector so a later delete can retry cleanup without orphaning the runtime.@@ -4043,7 +4052,7 @@ export class AgentSession {unsubscribe();}this._rlmChildUnsubscribes.clear();- for (const session of this._rlmChildSessions.values()) {+ for (const { session } of this._rlmChildSessions.values()) {await session.disposeAsync().catch(() => undefined);}this._rlmChildSessions.clear();@@ -4105,7 +4114,7 @@ export class AgentSession {unsubscribe();}this._rlmChildUnsubscribes.clear();- for (const session of this._rlmChildSessions.values()) {+ for (const { session } of this._rlmChildSessions.values()) {session.dispose();}this._rlmChildSessions.clear();@@ -9546,7 +9555,7 @@ export class AgentSession {});recorded.add(run.id);}- for (const [childId, childSession] of this._rlmChildSessions) {+ for (const [childId, { session: childSession }] of this._rlmChildSessions) {if (this._deletingRlmChildren.has(childId) ||recorded.has(childId) ||@@ -9634,7 +9643,7 @@ export class AgentSession {return result;}}- for (const retained of this._rlmChildSessions.values()) {+ for (const { session: retained } of this._rlmChildSessions.values()) {const result = await retained.deleteInactiveRlmSubagent(childId, isExternallyRunning);if (result !== "not_found") {return result;@@ -9911,7 +9920,7 @@ export class AgentSession {}this._emitRlmSubagentRemoval(subagent);- const retained = this._rlmChildSessions.get(childId);+ const retained = this._rlmChildSessions.get(childId)?.session;try {await this._deleteRlmSubagentSession(childId, retained);} catch (error) {@@ -9947,7 +9956,7 @@ export class AgentSession {void session.disposeAsync().catch(() => undefined);return false;}- this._rlmChildSessions.set(childId, session);+ this._rlmChildSessions.set(childId, { session, run: this._activeRlmChildRuns.get(childId) });if (unsubscribe) {this._rlmChildUnsubscribes.set(childId, unsubscribe);}@@ -9958,15 +9967,77 @@ export class AgentSession {const run = this._activeRlmChildRuns.get(childId);if (run?.session === session && run.status === "done") {const unsubscribe = run.unsubscribe ?? noopRlmChildEventUnsubscribe;- run.unsubscribe = undefined;- this._activeRlmChildRuns.delete(childId);- return unsubscribe;+ return () => {+ run.unsubscribe = undefined;+ this._activeRlmChildRuns.delete(childId);+ unsubscribe();+ };}- if (this._rlmChildSessions.get(childId) !== session) return false;+ if (this._rlmChildSessions.get(childId)?.session !== session) return false;const unsubscribe = this._rlmChildUnsubscribes.get(childId) ?? noopRlmChildEventUnsubscribe;- this._rlmChildUnsubscribes.delete(childId);- this._rlmChildSessions.delete(childId);- return unsubscribe;+ return () => {+ this._rlmChildUnsubscribes.delete(childId);+ this._rlmChildSessions.delete(childId);+ unsubscribe();+ };+ }++ private _rlmChildSnapshotForRun(+ run: RlmChildRun,+ child = run.session ?? this._rlmChildSessions.get(run.id)?.session,+ ): RlmChildAgentSnapshot {+ const model = child?.model ?? run.model;+ return {+ id: run.id,+ parentId: this._rlmParentNodeId,+ sessionName: child?.sessionName ?? run.sessionName,+ model: `${model.provider}/${model.id}`,+ label: rlmChildLabel(run.prompt),+ status: run.status,+ durationMs: run.durationMs,+ answerPreview: run.answerPreview,+ toolUseCount: run.toolUseCount > 0 ? run.toolUseCount : undefined,+ tokenCount: child?._contextTokensForCurrentMessages(),+ recap: child?.getCurrentRecap(),+ sessionDir: run.sessionDir,+ activity: run.activity,+ repliedSinceTask: child?._repliedToParentSinceTask,+ error: run.error,+ };+ }++ private _rlmChildSnapshotForSession(childId: string, child: AgentSession): RlmChildAgentSnapshot {+ let answerPreview: string | undefined;+ let toolUseCount = 0;+ const messages =+ child.state.streamingMessage?.role === "assistant"+ ? [...child.messages, child.state.streamingMessage]+ : child.messages;+ for (const message of messages) {+ if (message.role !== "assistant") continue;+ const text = compactRlmText(readAssistantText(message));+ if (text) answerPreview = text;+ toolUseCount += message.content.filter((block) => block.type === "toolCall").length;+ }+ return {+ id: childId,+ parentId: this._rlmParentNodeId,+ sessionName: child.sessionName,+ model: child.model ? `${child.model.provider}/${child.model.id}` : undefined,+ label: child.sessionName ?? "child agent",+ status: "done",+ answerPreview,+ toolUseCount: toolUseCount > 0 ? toolUseCount : undefined,+ tokenCount: child._contextTokensForCurrentMessages(),+ recap: child.getCurrentRecap(),+ sessionDir: child._rlmSessionDir ?? child.sessionManager.getSessionDir(),+ // No run exists (e.g. a child rehydrated after daemon recovery), so live+ // session state is the only source for in-flight follow-up work. Mirror+ // the run projection's convention: status stays "done" (the recorded task+ // finished) and current work surfaces through activity.+ activity: child.isSessionActive ? { kind: child.isStreaming ? "writing" : "waiting" } : undefined,+ repliedSinceTask: child._repliedToParentSinceTask,+ };}/** Live recursive child roster from lifecycle state, including nested work under retained parents. */@@ -9979,16 +10050,7 @@ export class AgentSession {run.detachedDeletion || this._deletingRlmChildren.has(run.id) || this._deletedRlmChildIds.has(run.id);const child = run.session;if (!hidden) {- const model = child?.model ?? run.model;- snapshots.push({- id: run.id,- parentId: this._rlmParentNodeId,- sessionName: child?.sessionName ?? run.sessionName,- model: `${model.provider}/${model.id}`,- label: rlmChildLabel(run.prompt),- status: run.status,- sessionDir: run.sessionDir,- });+ snapshots.push(this._rlmChildSnapshotForRun(run));recorded.add(run.id);}if (child) {@@ -9996,20 +10058,16 @@ export class AgentSession {snapshots.push(...child.getRlmChildSnapshots());}}- for (const [childId, child] of this._rlmChildSessions) {+ for (const [childId, { session: child, run }] of this._rlmChildSessions) {if (recorded.has(childId) || traversed.has(childId)) continue;const hidden = this._deletingRlmChildren.has(childId) || this._deletedRlmChildIds.has(childId);if (!hidden) {+ const snapshot = run+ ? this._rlmChildSnapshotForRun(run, child)+ : this._rlmChildSnapshotForSession(childId, child);snapshots.push({- id: childId,- parentId: this._rlmParentNodeId,- sessionName: child.sessionName,- model: child.model ? `${child.model.provider}/${child.model.id}` : undefined,- label: child.sessionName ?? "child agent",- // A failed delete retains the session solely for cleanup retry. Preserve- // its cancellation truth in snapshots rather than reviving it as done.- status: this._rlmChildCleanupFailures.has(childId) ? "cancelled" : "done",- sessionDir: child._rlmSessionDir ?? child.sessionManager.getSessionDir(),+ ...snapshot,+ status: this._rlmChildCleanupFailures.has(childId) ? "cancelled" : snapshot.status,});}snapshots.push(...child.getRlmChildSnapshots());@@ -10028,7 +10086,7 @@ export class AgentSession {}}// A finished direct child can still have a running nested subagent.- for (const session of this._rlmChildSessions.values()) {+ for (const { session } of this._rlmChildSessions.values()) {if (session.hasRunningRlmChildren()) {return true;}@@ -10038,7 +10096,7 @@ export class AgentSession {private _rlmChildSessionSnapshot(): AgentSession[] {const sessions = new Set<AgentSession>();- for (const [childId, session] of this._rlmChildSessions) {+ for (const [childId, { session }] of this._rlmChildSessions) {if (!this._abandonedRlmQuiescenceChildIds.has(childId)) sessions.add(session);}for (const run of this._activeRlmChildRuns.values()) {@@ -10109,7 +10167,7 @@ export class AgentSession {// Inline (non-daemon) mode only; daemon clients attach to the child session directly.getRlmChildSession(childId: string): AgentSession | undefined {- const direct = this._activeRlmChildRuns.get(childId)?.session ?? this._rlmChildSessions.get(childId);+ const direct = this._activeRlmChildRuns.get(childId)?.session ?? this._rlmChildSessions.get(childId)?.session;if (direct) {return direct;}@@ -10119,7 +10177,7 @@ export class AgentSession {return nested;}}- for (const retained of this._rlmChildSessions.values()) {+ for (const { session: retained } of this._rlmChildSessions.values()) {const nested = retained.getRlmChildSession(childId);if (nested) {return nested;@@ -10149,7 +10207,7 @@ export class AgentSession {return true;}}- for (const retained of this._rlmChildSessions.values()) {+ for (const { session: retained } of this._rlmChildSessions.values()) {if (retained.cancelRlmChildRun(childId, reason)) {return true;}@@ -10166,7 +10224,7 @@ export class AgentSession {[...this._activeRlmChildRuns.values()].some((run) => run.session?.sessionName === name || (!run.session && run.sessionName === name),) ||- [...this._rlmChildSessions.values()].some((session) => session.sessionName === name) ||+ [...this._rlmChildSessions.values()].some(({ session }) => session.sessionName === name) ||[...this._rlmChildCleanupFailures.values()].some((entry) => entry.session_name === name);if (localConflict) {throw new Error(formatAgentSessionNameUnavailable(name, depth));@@ -10286,12 +10344,7 @@ export class AgentSession {if (!requestedSessionName) await this._assertRlmSubagentSessionNameAvailable(sessionName);const startedAt = Date.now();const parentAssistantForUsage = this._findLastAssistantMessage();- const label = rlmChildLabel(prompt);- let answerPreview: string | undefined;- let durationMs: number | undefined;- let toolUseCount = 0;let runningToolCount = 0;- let activity: RlmChildAgentActivity | undefined;let childSession: AgentSession | undefined;const run: RlmChildRun = {id: childNodeId,@@ -10300,6 +10353,7 @@ export class AgentSession {sessionDir: childSessionDir,model: modelSelection.model,status: "queued",+ toolUseCount: 0,settled: false,abort: noopRlmChildAbort,publication: createAgentMessageDeferred(),@@ -10312,27 +10366,7 @@ export class AgentSession {this._activeRlmChildRuns.set(run.id, run);this._unsettledRlmChildRuns.add(run);const emitChildUpdate = () => {- const childModel = childSession?.model ?? modelSelection.model;- this._emit({- type: "rlm_child_update",- child: {- id: childNodeId,- parentId: this._rlmParentNodeId,- sessionName: childSession?.sessionName ?? sessionName,- model: `${childModel.provider}/${childModel.id}`,- label,- status: run.status,- durationMs,- answerPreview,- toolUseCount: toolUseCount > 0 ? toolUseCount : undefined,- tokenCount: childSession?._contextTokensForCurrentMessages(),- recap: childSession?.getCurrentRecap(),- sessionDir: childSessionDir,- activity,- repliedSinceTask: childSession?._repliedToParentSinceTask,- error: run.error,- },- });+ this._emit({ type: "rlm_child_update", child: this._rlmChildSnapshotForRun(run) });};run.emitUpdate = emitChildUpdate;emitChildUpdate();@@ -10415,10 +10449,10 @@ export class AgentSession {return;}if (event.type === "agent_start") {- activity = { kind: "waiting" };+ run.activity = { kind: "waiting" };emitChildUpdate();} else if (event.type === "agent_end") {- activity = undefined;+ run.activity = undefined;emitChildUpdate();} else if (event.type === "message_end" && event.message.role === "assistant") {const assistant = event.message as AssistantMessage;@@ -10449,24 +10483,24 @@ export class AgentSession {}}const text = compactRlmText(readAssistantText(assistant));- if (text) answerPreview = text;+ if (text) run.answerPreview = text;void flushAgentTraceUpload(child.sessionManager).catch(() => undefined);emitChildUpdate();} else if (event.type === "message_start" || event.type === "message_update") {if (event.message.role === "assistant") {const text = compactRlmText(readAssistantText(event.message as AssistantMessage));- if (text) answerPreview = text;- activity = { kind: "writing" };+ if (text) run.answerPreview = text;+ run.activity = { kind: "writing" };emitChildUpdate();}} else if (event.type === "tool_execution_start") {- toolUseCount += 1;+ run.toolUseCount += 1;runningToolCount += 1;- activity = { kind: "executing", toolName: event.toolName };+ run.activity = { kind: "executing", toolName: event.toolName };emitChildUpdate();} else if (event.type === "tool_execution_end") {runningToolCount = Math.max(0, runningToolCount - 1);- if (runningToolCount === 0) activity = { kind: "waiting" };+ if (runningToolCount === 0) run.activity = { kind: "waiting" };emitChildUpdate();} else if (event.type === "session_info_changed" || event.type === "recap_update") {emitChildUpdate();@@ -10501,8 +10535,8 @@ export class AgentSession {await child.waitForRlmQuiescence();if (run.error) throw new Error(run.error);run.status = "done";- durationMs = Date.now() - startedAt;- activity = undefined;+ run.durationMs = Date.now() - startedAt;+ run.activity = undefined;emitChildUpdate();if (!run.detachedDeletion &&@@ -10535,8 +10569,8 @@ export class AgentSession {run.status = "error";run.error = runError.message;}- durationMs = Date.now() - startedAt;- activity = undefined;+ run.durationMs = Date.now() - startedAt;+ run.activity = undefined;emitChildUpdate();if (!run.detachedDeletion && !run.suppressTerminalNotice) {if (run.status === "error") {diff --git a/packages/coding-agent/src/modes/daemon/daemon-mode.ts b/packages/coding-agent/src/modes/daemon/daemon-mode.tsindex df148b913e..66bfe736f1 100644--- a/packages/coding-agent/src/modes/daemon/daemon-mode.ts+++ b/packages/coding-agent/src/modes/daemon/daemon-mode.ts@@ -2677,12 +2677,9 @@ export class AgentDaemon {try {await this.closeSession(state, "shutdown", true, false);} catch (error) {- // A pre-removal close failure must not strand a resident child outside its- // parent's ownership map or disconnect its event forwarder.if (this.sessions.get(state.activeSessionId) === state &&- this.sessions.get(parentActiveSessionId) === parentState &&- parentState.runtime.session.registerRlmChildSession(childId, state.runtime.session, unsubscribeChild)+ this.sessions.get(parentActiveSessionId) === parentState) {throw error;}diff --git a/packages/coding-agent/src/modes/daemon/daemon-session-list.ts b/packages/coding-agent/src/modes/daemon/daemon-session-list.tsindex 49b5a16dc7..d41e83a67a 100644--- a/packages/coding-agent/src/modes/daemon/daemon-session-list.ts+++ b/packages/coding-agent/src/modes/daemon/daemon-session-list.ts@@ -2,8 +2,7 @@ import { statSync } from "node:fs";import { resolve } from "node:path";import type { AgentMessage, ThinkingLevel } from "@earendil-works/pi-agent-core";import type { Api, Model } from "@earendil-works/pi-ai";-import { compactRlmText, rlmChildLabel } from "../../core/agent-session.js";-import type { AgentSessionRuntimeMetadata } from "../../core/agent-session-runtime.js";+import { compactRlmText } from "../../core/agent-session.js";import type { AgentSessionRuntimeDiagnostic } from "../../core/agent-session-services.js";import { type AgentCronJob, isHeartbeatCronJob } from "../../core/cron-jobs.js";import type { SessionActionSnapshot } from "../../core/session-action-store.js";@@ -329,87 +328,23 @@ export function summaryForInactiveSession(};}-/**- * Build snapshots for all RLM child sessions hosted by the daemon under the- * given session, including grandchildren. Mirrors the shape of live- * rlm_child_update events so attach clients can seed their subagent state- * from daemon memory instead of replaying the event stream.- */+/** Build the root AgentSession projection with daemon-only active session ids. */export function buildRlmChildSnapshots(rootActiveSessionId: string,activeSessions: readonly ActiveSessionState[],): AgentConnectionRlmChildAgentSnapshot[] {- const childrenByParent = new Map<string, ActiveSessionState[]>();- for (const candidate of activeSessions) {- const metadata = candidate.runtime.metadata;- if (metadata.kind !== "subagent" || !metadata.parentActiveSessionId) {- continue;- }- const siblings = childrenByParent.get(metadata.parentActiveSessionId) ?? [];- siblings.push(candidate);- childrenByParent.set(metadata.parentActiveSessionId, siblings);- }-- const snapshots: AgentConnectionRlmChildAgentSnapshot[] = [];- const visit = (parent: ActiveSessionState | undefined, parentActiveSessionId: string): void => {- const parentNodeId = parent?.runtime.metadata.rlmChildId;- for (const child of childrenByParent.get(parentActiveSessionId) ?? []) {- snapshots.push(rlmChildSnapshotForActiveSession(child, child.runtime.metadata, parentNodeId, parent));- // A child passes its own node id to its children as their parent id.- visit(child, child.activeSessionId);- }- };const root = activeSessions.find((candidate) => candidate.activeSessionId === rootActiveSessionId);- visit(root, rootActiveSessionId);- return snapshots;-}--function rlmChildSnapshotForActiveSession(- activeSession: ActiveSessionState,- metadata: AgentSessionRuntimeMetadata,- parentNodeId: string | undefined,- parent: ActiveSessionState | undefined,-): AgentConnectionRlmChildAgentSnapshot {- const session = activeSession.runtime.session;- let answerPreview: string | undefined;- let toolUseCount = 0;- const messages =- session.state.streamingMessage?.role === "assistant"- ? [...session.messages, session.state.streamingMessage]- : session.messages;- for (const message of messages) {- if (message.role === "assistant") {- const text = compactRlmText(readMessageText(message.content));- if (text) {- answerPreview = text;- }- toolUseCount += message.content.filter((block) => block.type === "toolCall").length;- }- }- // The parent session's run tracker is the source of truth for child status;- // a daemon-hosted child whose agent is momentarily idle is still part of an- // active run. The streaming heuristic only covers parents the daemon does- // not host (e.g. children attributed to a session created by an older build).- const runStatus = metadata.rlmChildId- ? parent?.runtime.session.getRlmChildRunStatus(metadata.rlmChildId)- : undefined;- const status = runStatus ?? (session.isSessionActive ? "running" : "done");- const isActive = status === "running" || session.isSessionActive;- return {- id: metadata.rlmChildId ?? activeSession.activeSessionId,- parentId: parentNodeId,- activeSessionId: activeSession.activeSessionId,- sessionName: session.sessionName,- model: session.model ? `${session.model.provider}/${session.model.id}` : undefined,- label: rlmChildLabel(metadata.prompt ?? ""),- status,- answerPreview,- toolUseCount: toolUseCount > 0 ? toolUseCount : undefined,- tokenCount: session._contextTokensForCurrentMessages(),- recap: session.getCurrentRecap(),- sessionDir: metadata.sessionDir ?? session.sessionManager.getSessionDir(),- activity: isActive ? { kind: session.isStreaming ? "writing" : "waiting" } : undefined,- };+ if (!root) return [];+ const activeSessionIds = new Map(+ activeSessions.flatMap((candidate) => {+ const childId = candidate.runtime.metadata.rlmChildId;+ return childId ? [[childId, candidate.activeSessionId] as const] : [];+ }),+ );+ return root.runtime.session.getRlmChildSnapshots().map((snapshot) => ({+ ...snapshot,+ activeSessionId: activeSessionIds.get(snapshot.id),+ }));}function firstUserMessageText(session: ActiveSessionState["runtime"]["session"]): string | undefined {diff --git a/packages/coding-agent/test/agent-session-recursion.test.ts b/packages/coding-agent/test/agent-session-recursion.test.tsindex 793801106e..33979fbe14 100644--- a/packages/coding-agent/test/agent-session-recursion.test.ts+++ b/packages/coding-agent/test/agent-session-recursion.test.ts@@ -18,7 +18,7 @@ import {createAgentSessionMessage,isAgentSessionMessage,} from "../src/core/agent-messages.js";-import { AgentSession } from "../src/core/agent-session.js";+import { AgentSession, type RlmChildAgentSnapshot } from "../src/core/agent-session.js";import { AuthStorage } from "../src/core/auth-storage.js";import type { LoadExtensionsResult } from "../src/core/extensions/index.js";import { type HostRequestHandlers, ReplKernelManager } from "../src/core/kernel/index.js";@@ -120,7 +120,7 @@ interface InspectableRlmSession {}>;_rlmChildCleanupFailures: Map<string, Awaited<ReturnType<AgentSession["listRlmSubagents"]>>["subagents"][number]>;- _rlmChildSessions: Map<string, AgentSession>;+ _rlmChildSessions: Map<string, { session: AgentSession; run?: InspectableRlmRun }>;_rlmChildUnsubscribes: Map<string, () => void>;_deletedRlmChildIds: Set<string>;_rlmQuiescenceWaitAborts: Set<AbortController>;@@ -523,6 +523,10 @@ describe("AgentSession rlm recursion", () => {mkdirSync(childDir, { recursive: true });const child = createSession({ rlmSessionDir: childDir });child.setSessionName("restored-worker");+ const restoredAnswer = assistantMessage("restored answer", usage(7, 3));+ restoredAnswer.content.push({ type: "toolCall", id: "tool-1", name: "ipython", arguments: {} });+ child.agent.state.messages.push(restoredAnswer);+ child.setCurrentRecap("restored recap");const disposeChild = vi.spyOn(child, "disposeAsync");const root = createSession();const childStatuses: string[] = [];@@ -533,6 +537,15 @@ describe("AgentSession rlm recursion", () => {});expect(root.registerRlmChildSession(childId, child)).toBe(true);+ expect(root.getRlmChildSnapshots()).toEqual([+ expect.objectContaining({+ id: childId,+ answerPreview: "restored answer",+ toolUseCount: 1,+ tokenCount: 10,+ recap: "restored recap",+ }),+ ]);expect((await root.listRlmSubagents()).subagents).toEqual([expect.objectContaining({rlm_child_id: childId,@@ -549,6 +562,40 @@ describe("AgentSession rlm recursion", () => {expect(childStatuses).toEqual(["cancelled"]);});+ it("projects live follow-up activity for a restored session-only child", async () => {+ const childId = "restored-followup-child";+ const childDir = join(tempDir, childId);+ mkdirSync(childDir, { recursive: true });+ const followUpGate = deferred<void>();+ let followUpStarted = false;+ const child = createSession({+ rlmSessionDir: childDir,+ streamFn: () => {+ const stream = createAssistantMessageEventStream();+ followUpStarted = true;+ void followUpGate.promise.then(() => {+ stream.push({ type: "done", reason: "stop", message: assistantMessage("follow-up answer") });+ });+ return stream;+ },+ });+ const root = createSession();+ expect(root.registerRlmChildSession(childId, child)).toBe(true);++ const followUp = child.prompt("follow-up work");+ await waitFor(() => followUpStarted);+ const busy = root.getRlmChildSnapshots();+ expect(busy).toEqual([expect.objectContaining({ id: childId, status: "done" })]);+ expect(busy[0]?.activity).toBeDefined();++ followUpGate.resolve();+ await followUp;+ await child.waitForIdle();+ const idle = root.getRlmChildSnapshots();+ expect(idle).toEqual([expect.objectContaining({ id: childId, status: "done" })]);+ expect(idle[0]?.activity).toBeUndefined();+ });+it("retries and releases failed retained child cleanup on the next compaction", async () => {const childId = "retained-retry-child";const childDir = join(tempDir, childId);@@ -651,9 +698,9 @@ describe("AgentSession rlm recursion", () => {});// The same child can be visible in both lifecycle registries while// deletion settles; it must be traversed exactly once and remain hidden.- rootInternals._rlmChildSessions.set(id, parent);+ rootInternals._rlmChildSessions.set(id, { session: parent });} else {- rootInternals._rlmChildSessions.set(id, parent);+ rootInternals._rlmChildSessions.set(id, { session: parent });if (hiding === "deleted") {rootInternals._deletedRlmChildIds.add(id);} else {@@ -745,6 +792,14 @@ describe("AgentSession rlm recursion", () => {await waitFor(() => childUpdates.some((update) => update.status === "done"));const doneUpdate = [...childUpdates].reverse().find((update) => update.status === "done");expect(doneUpdate?.answerPreview).toBe("child answer: summarize shard 1");+ expect(root.getRlmChildSnapshots()).toEqual([+ expect.objectContaining({+ id: result.rlm_child_id,+ status: "done",+ answerPreview: doneUpdate?.answerPreview,+ durationMs: expect.any(Number),+ }),+ ]);const child = root.getRlmChildSession(result.rlm_child_id);expect(child?.messages[0]).toMatchObject({role: "custom",@@ -842,6 +897,9 @@ describe("AgentSession rlm recursion", () => {},});const spawned = await root.runRlmChild("pending task", { name: "pending-child" });+ expect(root.getRlmChildSnapshots()).toEqual([+ expect.objectContaining({ id: spawned.rlm_child_id, status: "queued" }),+ ]);const handlers = (root as unknown as InspectableRlmSession)._createKernelHostHandlers();const send = handlers["agent_message.send"];if (!send) throw new Error("Missing agent_message.send host handler");@@ -2196,14 +2254,33 @@ describe("AgentSession rlm recursion", () => {if (!child) {throw new Error("Missing retained child session");}+ const rootInternals = root as unknown as InspectableRlmSession;+ await waitFor(() => !rootInternals._activeRlmChildRuns.has(childId));+ const completeRelease = root.releaseRlmChildSession(childId, child);+ if (!completeRelease) throw new Error("Failed to release retained child");+ child.setCurrentRecap("retained recap");child.setSessionName("renamed-worker");const childUpdates = events.filter(- (event): event is { type: "rlm_child_update"; child: { sessionName?: string } } =>+ (event): event is { type: "rlm_child_update"; child: RlmChildAgentSnapshot } =>typeof event === "object" && event !== null && (event as { type?: string }).type === "rlm_child_update",);- expect(childUpdates.at(-1)?.child.sessionName).toBe("renamed-worker");+ expect(childUpdates.at(-1)?.child).toMatchObject({+ sessionName: "renamed-worker",+ durationMs: expect.any(Number),+ tokenCount: 10,+ recap: "retained recap",+ repliedSinceTask: false,+ });+ expect(root.getRlmChildSnapshots()).toEqual([+ expect.objectContaining({+ sessionName: "renamed-worker",+ durationMs: expect.any(Number),+ tokenCount: 10,+ recap: "retained recap",+ }),+ ]);});it("surfaces a child's recap on its snapshot once the summarizer sets it", async () => {diff --git a/packages/coding-agent/test/daemon-mode.test.ts b/packages/coding-agent/test/daemon-mode.test.tsindex 97c5f979d2..7e9373cb00 100644--- a/packages/coding-agent/test/daemon-mode.test.ts+++ b/packages/coding-agent/test/daemon-mode.test.ts@@ -5807,7 +5807,7 @@ describe("daemon mode helpers", () => {}});- it("re-adopts a resident child when its passivation close fails", async () => {+ it("keeps ownership of a resident child until passivation succeeds", async () => {const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-daemon-passivation-close-failure-"));let releaseAbort!: () => void;const abortGate = new Promise<void>((resolve) => {@@ -5831,7 +5831,6 @@ describe("daemon mode helpers", () => {const childState = await internals.createRuntime({ type: "create", sessionPath: fixture.childSessionFile });const parentSession = parentState.runtime.session as unknown as {releaseRlmChildSession: ReturnType<typeof vi.fn>;- registerRlmChildSession: ReturnType<typeof vi.fn>;};let parentOwnsChild = true;let forwarderActive = true;@@ -5844,16 +5843,11 @@ describe("daemon mode helpers", () => {});parentSession.releaseRlmChildSession = vi.fn(() => {if (!parentOwnsChild) return false;- parentOwnsChild = false;- return unsubscribeForwarder;- });- parentSession.registerRlmChildSession = vi.fn(- (_childId: string, _childSession: unknown, unsubscribe: () => void) => {- parentOwnsChild = true;- forwarderActive = unsubscribe === unsubscribeForwarder;- return true;- },- );+ return () => {+ parentOwnsChild = false;+ unsubscribeForwarder();+ };+ });childState.unsubscribe = vi.fn().mockImplementationOnce(() => {@@ -5879,11 +5873,6 @@ describe("daemon mode helpers", () => {await expect(delivery).resolves.toMatchObject({ deliveryStatus: "delivered" });expect(internals.sessions.get(childState.activeSessionId)).toBe(childState);expect(parentOwnsChild).toBe(true);- expect(parentSession.registerRlmChildSession).toHaveBeenCalledWith(- fixture.childId,- childState.runtime.session,- unsubscribeForwarder,- );expect(unsubscribeForwarder).not.toHaveBeenCalled();emitChildUpdate("recap after failed close");expect(parentUpdates).toEqual(["recap after failed close"]);@@ -8997,6 +8986,7 @@ function makeRuntimeSession(},setSubagentRuntimeHost: vi.fn(),getRlmChildRunStatus: vi.fn(() => "running"),+ getRlmChildSnapshots: vi.fn(() => []),registerRlmChildSession: vi.fn(() => true),releaseRlmChildSession: vi.fn(() => vi.fn()),subscribe: vi.fn(() => vi.fn()),diff --git a/packages/coding-agent/test/daemon-session-list.test.ts b/packages/coding-agent/test/daemon-session-list.test.tsindex a332372bfb..6cb772e27f 100644--- a/packages/coding-agent/test/daemon-session-list.test.ts+++ b/packages/coding-agent/test/daemon-session-list.test.ts@@ -1,6 +1,7 @@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 { AgentCronJob } from "../src/core/cron-jobs.js";import type { SessionInfo } from "../src/core/session-manager.js";import type { ActiveSessionState, DaemonSocketClient } from "../src/modes/daemon/active-session-state.js";@@ -496,150 +497,42 @@ describe("summaryForActiveSession recap currency", () => {});describe("buildRlmChildSnapshots", () => {- it("collects children and grandchildren with event-compatible parent ids", () => {- const parent = makeState({ activeSessionId: "parent", sessionFile: "/tmp/parent.jsonl" });- const child = makeState({- activeSessionId: "child",- model: { provider: "anthropic", id: "claude-opus-4-7" },- isStreaming: true,- metadata: {- kind: "subagent",- createdAt: 1,- parentActiveSessionId: "parent",- rlmChildId: "sub-aaa",- rlmParentNodeId: "sub-aaa",- prompt: "Summarize the repo\nlayout",- sessionDir: "/tmp/artifacts/sub-aaa",- },- messages: [- { role: "user", content: "Summarize the repo layout" },- {- role: "assistant",- content: [- { type: "text", text: "The repo is an npm workspace." },- { type: "toolCall", id: "tool-1", name: "ipython", arguments: {} },- ],- },- ] as AgentMessage[],- contextTokens: 41_000,- });- const grandchild = makeState({- activeSessionId: "grandchild",- metadata: {- kind: "subagent",- createdAt: 2,- parentActiveSessionId: "child",- rlmChildId: "sub-bbb",- rlmParentNodeId: "sub-bbb",- prompt: "Read the docs",- sessionDir: "/tmp/artifacts/sub-aaa/sub-bbb",- },- });- const unrelated = makeState({- activeSessionId: "unrelated-child",- metadata: {- kind: "subagent",- createdAt: 3,- parentActiveSessionId: "someone-else",- rlmChildId: "sub-ccc",- },- });-- const snapshots = buildRlmChildSnapshots("parent", [parent, child, grandchild, unrelated]);-- expect(snapshots.map((snapshot) => [snapshot.id, snapshot.parentId, snapshot.status])).toEqual([- ["sub-aaa", undefined, "running"],- ["sub-bbb", "sub-aaa", "done"],- ]);- expect(snapshots[0]).toMatchObject({- model: "anthropic/claude-opus-4-7",- label: "Summarize the repo layout",- answerPreview: "The repo is an npm workspace.",- toolUseCount: 1,- tokenCount: 41_000,- sessionDir: "/tmp/artifacts/sub-aaa",- activeSessionId: "child",- });- });-- it("prefers the parent's run status over the streaming heuristic", () => {- // An idle child session is still part of an active run; only the parent's- // run tracker knows that.- const parent = makeState({- activeSessionId: "parent",- sessionFile: "/tmp/parent.jsonl",- childRunStatuses: { "sub-aaa": "running" },- });- const idleChild = makeState({- activeSessionId: "child",- isStreaming: false,- metadata: {- kind: "subagent",- createdAt: 1,- parentActiveSessionId: "parent",- rlmChildId: "sub-aaa",- rlmParentNodeId: "sub-aaa",- prompt: "Slow task",- sessionDir: "/tmp/artifacts/sub-aaa",- },- });-- const snapshots = buildRlmChildSnapshots("parent", [parent, idleChild]);-- expect(snapshots.map((snapshot) => [snapshot.id, snapshot.status])).toEqual([["sub-aaa", "running"]]);- });-- it("keeps terminal run status while projecting a retained child's active follow-up", () => {+ it("uses the AgentSession projection and adds resident active session ids", () => {+ const queued = {+ id: "sub-queued",+ label: "Queued task",+ status: "queued" as const,+ sessionDir: "/tmp/artifacts/sub-queued",+ };+ const executing = {+ id: "sub-running",+ label: "Running task",+ status: "running" as const,+ sessionDir: "/tmp/artifacts/sub-running",+ activity: { kind: "executing" as const, toolName: "ipython" },+ };const parent = makeState({activeSessionId: "parent",- childRunStatuses: { "sub-aaa": "done" },+ childSnapshots: [queued, executing],});- const activeRetainedChild = makeState({- activeSessionId: "child",- isStreaming: true,+ const residentChild = makeState({+ activeSessionId: "running-child",metadata: {kind: "subagent",createdAt: 1,parentActiveSessionId: "parent",- rlmChildId: "sub-aaa",+ rlmChildId: "sub-running",},});- expect(buildRlmChildSnapshots("parent", [parent, activeRetainedChild])[0]).toMatchObject({- status: "done",- activity: { kind: "writing" },- });- });-- it("includes in-flight assistant output in child snapshots", () => {- const parent = makeState({ activeSessionId: "parent" });- const child = makeState({- activeSessionId: "child",- isStreaming: true,- metadata: {- kind: "subagent",- createdAt: 1,- parentActiveSessionId: "parent",- rlmChildId: "sub-aaa",- },- streamingMessage: {- role: "assistant",- content: [- { type: "text", text: "Still investigating" },- { type: "toolCall", id: "tool-1", name: "search", arguments: {} },- ],- } as AgentMessage,- });-- expect(buildRlmChildSnapshots("parent", [parent, child])[0]).toMatchObject({- answerPreview: "Still investigating",- toolUseCount: 1,- });+ expect(buildRlmChildSnapshots("parent", [parent, residentChild])).toEqual([+ { ...queued, activeSessionId: undefined },+ { ...executing, activeSessionId: "running-child" },+ ]);});- it("returns no snapshots for sessions without children", () => {- const solo = makeState({ activeSessionId: "solo" });- expect(buildRlmChildSnapshots("solo", [solo])).toEqual([]);+ it("returns no snapshots when the root is not resident", () => {+ expect(buildRlmChildSnapshots("missing", [])).toEqual([]);});});@@ -691,12 +584,12 @@ interface StateOptions {messages?: AgentMessage[];hasUserContent?: boolean;summaryState?: ActiveSessionState["summaryState"];- childRunStatuses?: Record<string, "queued" | "running" | "done" | "error" | "cancelled">;hasRunningRlmChildren?: boolean;hasAcceptedPromptInFlight?: boolean;unfinishedActionCount?: number;contextTokens?: number;streamingMessage?: AgentMessage;+ childSnapshots?: RlmChildAgentSnapshot[];rlmDepth?: number;metadata?: {kind: "top-level" | "subagent";@@ -741,7 +634,7 @@ function makeState(options: StateOptions): ActiveSessionState {hasUserContent: () => options.hasUserContent ?? false,},messages: options.messages ?? ([] as AgentMessage[]),- getRlmChildRunStatus: (childId: string) => options.childRunStatuses?.[childId],+ getRlmChildSnapshots: () => options.childSnapshots ?? [],hasRunningRlmChildren: () => options.hasRunningRlmChildren ?? false,hasAcceptedPromptInFlight: options.hasAcceptedPromptInFlight ?? false,unfinishedActionCount: options.unfinishedActionCount ?? (options.hasAcceptedPromptInFlight ? 1 : 0),