A self-improving RLM agent for coding workflows and long-running autonomous tasks.
Rust
feat(coding-agent): lazy child session hydration (#583)
Sebastian Müller5d457cbe93f0
diff --git a/packages/coding-agent/src/core/agent-messages.ts b/packages/coding-agent/src/core/agent-messages.tsindex 10de6d8846..57ab32edc1 100644--- a/packages/coding-agent/src/core/agent-messages.ts+++ b/packages/coding-agent/src/core/agent-messages.ts@@ -34,6 +34,7 @@ export interface AgentSessionMessageAgentSummary extends AgentSessionMessageEndpunfinishedActionCount: number;parentActiveSessionId?: string;rlmChildId?: string;+ sessionDir?: string;}export interface AgentSessionMessageListResult {@@ -85,7 +86,7 @@ export interface AgentSessionMessageSendInput {}export interface AgentSessionMessageController {- listAgents(): AgentSessionMessageListResult;+ listAgents(): AgentSessionMessageListResult | Promise<AgentSessionMessageListResult>;sendAgentMessage(input: AgentSessionMessageSendInput): Promise<AgentSessionMessageReceipt>;}@@ -305,7 +306,7 @@ export function createAgentMessageHostHandlers(controller: AgentSessionMessageController,): Record<string, HostRequestHandler> {return {- "agent_message.list": async () => controller.listAgents() as unknown as Record<string, unknown>,+ "agent_message.list": async () => (await controller.listAgents()) as unknown as Record<string, unknown>,"agent_message.send": async (payload) => {if (typeof payload.target !== "string") {throw new Error("agent_message.send target must be a string");diff --git a/packages/coding-agent/src/core/agent-observe.ts b/packages/coding-agent/src/core/agent-observe.tsindex a53f2c9b8b..e68a08b45a 100644--- a/packages/coding-agent/src/core/agent-observe.ts+++ b/packages/coding-agent/src/core/agent-observe.ts@@ -61,8 +61,10 @@ export interface AgentObserveMessagePreview {export interface AgentObserveController {listAgents(): AgentObserveListResult;- getAgent(target: string): AgentObserveAgentSnapshot;- recentMessages(input: AgentObserveRecentMessagesInput): AgentObserveRecentMessagesResult;+ getAgent(target: string): AgentObserveAgentSnapshot | Promise<AgentObserveAgentSnapshot>;+ recentMessages(+ input: AgentObserveRecentMessagesInput,+ ): AgentObserveRecentMessagesResult | Promise<AgentObserveRecentMessagesResult>;}export function createAgentObserveHostHandlers(controller: AgentObserveController) {@@ -72,17 +74,17 @@ export function createAgentObserveHostHandlers(controller: AgentObserveControlleif (typeof payload.target !== "string") {throw new Error("agent_observe.get target must be a string");}- return controller.getAgent(payload.target) as unknown as Record<string, unknown>;+ return (await controller.getAgent(payload.target)) as unknown as Record<string, unknown>;},"agent_observe.recent": async (payload: Record<string, unknown> = {}) => {if (typeof payload.target !== "string") {throw new Error("agent_observe.recent target must be a string");}- return controller.recentMessages({+ return (await controller.recentMessages({target: payload.target,limit: normalizeOptionalInteger(payload.limit, "agent_observe.recent limit"),maxChars: normalizeOptionalInteger(payload.max_chars ?? payload.maxChars, "agent_observe.recent max_chars"),- }) as unknown as Record<string, unknown>;+ })) as unknown as Record<string, unknown>;},};}diff --git a/packages/coding-agent/src/core/agent-session.ts b/packages/coding-agent/src/core/agent-session.tsindex 1ad1d3c4fd..8f2e8530ab 100644--- a/packages/coding-agent/src/core/agent-session.ts+++ b/packages/coding-agent/src/core/agent-session.ts@@ -2893,7 +2893,7 @@ export class AgentSession {handleAgentMessageHostRequest(type: string,payload: Record<string, unknown> = {},- ): AgentSessionMessageListResult | Promise<AgentSessionMessageReceipt> {+ ): Promise<AgentSessionMessageListResult | AgentSessionMessageReceipt> | AgentSessionMessageListResult {if (!this._agentMessageController) {throw new Error("agent messaging is not available in this session");}@@ -2922,7 +2922,11 @@ export class AgentSession {handleAgentObserveHostRequest(type: string,payload: Record<string, unknown> = {},- ): AgentObserveListResult | AgentObserveAgentSnapshot | AgentObserveRecentMessagesResult {+ ):+ | AgentObserveListResult+ | AgentObserveAgentSnapshot+ | AgentObserveRecentMessagesResult+ | Promise<AgentObserveAgentSnapshot | AgentObserveRecentMessagesResult> {const controller = this._agentObserveController;if (!controller) {throw new Error("agent observation is not available in this session");@@ -8348,8 +8352,8 @@ export class AgentSession {Object.assign(handlers,createAgentMessageHostHandlers({- listAgents: () =>- this.handleAgentMessageHostRequest("agent_message.list") as AgentSessionMessageListResult,+ listAgents: async () =>+ (await this.handleAgentMessageHostRequest("agent_message.list")) as AgentSessionMessageListResult,sendAgentMessage: async (input) =>(await this.handleAgentMessageHostRequest("agent_message.send", {target: input.target,@@ -8709,9 +8713,12 @@ export class AgentSession {}/** Current direct-child registry for the model-facing rlm.list_subagents API. */- listRlmSubagents(): RlmListSubagentsResult {+ async listRlmSubagents(): Promise<RlmListSubagentsResult> {+ return this._buildRlmSubagentList(await this._agentMessageController?.listAgents());+ }++ private _buildRlmSubagentList(listedAgents?: AgentSessionMessageListResult): RlmListSubagentsResult {const daemonChildren = new Map<string, AgentSessionMessageAgentSummary>();- const listedAgents = this._agentMessageController?.listAgents();const parentActiveSessionId = listedAgents?.current?.activeSessionId;if (parentActiveSessionId) {for (const agent of listedAgents.agents) {@@ -8764,6 +8771,26 @@ export class AgentSession {session_dir: sessionDir,status: "completed",});+ recorded.add(childId);+ }+ for (const [childId, daemonChild] of daemonChildren) {+ if (+ recorded.has(childId) ||+ this._deletingRlmChildren.has(childId) ||+ this._deletedRlmChildIds.has(childId) ||+ this._retryableRlmSubagentDeletions.has(childId) ||+ !daemonChild.sessionDir+ ) {+ continue;+ }+ subagents.push({+ rlm_child_id: childId,+ active_session_id: null,+ session_id: daemonChild.sessionId,+ session_name: daemonChild.sessionName ?? createDefaultRlmSubagentSessionName("", childId),+ session_dir: daemonChild.sessionDir,+ status: "completed",+ });}return { subagents };}@@ -8777,8 +8804,11 @@ export class AgentSession {);}- private _resolveDirectRlmSubagent(target: string): RlmSubagentRegistryEntry {- const candidates = [...this.listRlmSubagents().subagents, ...this._retryableRlmSubagentDeletions.values()];+ private async _resolveDirectRlmSubagent(target: string): Promise<RlmSubagentRegistryEntry> {+ const candidates = [+ ...(await this.listRlmSubagents()).subagents,+ ...this._retryableRlmSubagentDeletions.values(),+ ];const matches = candidates.filter((entry) => this._rlmSubagentMatchesTarget(entry, target));if (matches.length === 0) {throw new Error(`No direct RLM subagent matches "${target}" in the current parent session`);@@ -8789,28 +8819,77 @@ export class AgentSession {return matches[0]!;}- /** Delete a running or retained direct child selected from this parent session's registry. */+ /** Delete a running, retained, or passive direct child selected from this parent session's registry. */async deleteRlmSubagent(target: string): Promise<RlmDeleteSubagentResult> {const inFlight = [...this._deletingRlmChildren.values()].filter(({ subagent }) =>this._rlmSubagentMatchesTarget(subagent, target),);- const directMatches = [- ...this.listRlmSubagents().subagents,+ if (inFlight.length > 1) {+ throw new Error(`RLM subagent selector "${target}" is ambiguous in the current parent session`);+ }++ // Running and retained children can be reserved synchronously. This keeps+ // them hidden immediately while the async daemon listing checks for a+ // conflicting passive selector.+ const localMatches = [+ ...this._buildRlmSubagentList().subagents,...this._retryableRlmSubagentDeletions.values(),].filter((entry) => this._rlmSubagentMatchesTarget(entry, target));const matchingChildIds = new Set([...inFlight.map(({ subagent }) => subagent.rlm_child_id),- ...directMatches.map((subagent) => subagent.rlm_child_id),+ ...localMatches.map((subagent) => subagent.rlm_child_id),]);- if (matchingChildIds.size > 1) {+ if (matchingChildIds.size > 1 || localMatches.length > 1) {throw new Error(`RLM subagent selector "${target}" is ambiguous in the current parent session`);}if (inFlight[0]) {return inFlight[0].promise;}+ if (localMatches[0]) {+ const subagent = localMatches[0];+ const deletion = (async () => {+ const listedAgents = await this._agentMessageController?.listAgents();+ const listedSubagents = this._buildRlmSubagentList(listedAgents).subagents;+ const passiveMatches = listedSubagents.filter(+ (entry) => entry.rlm_child_id !== subagent.rlm_child_id && this._rlmSubagentMatchesTarget(entry, target),+ );+ if (passiveMatches.length > 0) {+ throw new Error(`RLM subagent selector "${target}" is ambiguous in the current parent session`);+ }+ const parentActiveSessionId = listedAgents?.current?.activeSessionId;+ const daemonChild = listedAgents?.agents.find(+ (agent) =>+ agent.rlmChildId === subagent.rlm_child_id && agent.parentActiveSessionId === parentActiveSessionId,+ );+ const resolvedSubagent = daemonChild+ ? {+ ...subagent,+ active_session_id: daemonChild.activeSessionId,+ session_id: daemonChild.sessionId,+ session_name: daemonChild.sessionName ?? subagent.session_name,+ }+ : subagent;+ return this._deleteResolvedRlmSubagent(resolvedSubagent);+ })();+ return this._trackRlmSubagentDeletion(subagent, deletion);+ }++ const directMatches = [+ ...(await this.listRlmSubagents()).subagents,+ ...this._retryableRlmSubagentDeletions.values(),+ ].filter((entry) => this._rlmSubagentMatchesTarget(entry, target));+ const directChildIds = new Set(directMatches.map((subagent) => subagent.rlm_child_id));+ if (directChildIds.size > 1) {+ throw new Error(`RLM subagent selector "${target}" is ambiguous in the current parent session`);+ }+ const subagent = directMatches[0] ?? (await this._resolveDirectRlmSubagent(target));+ return this._trackRlmSubagentDeletion(subagent, this._deleteResolvedRlmSubagent(subagent));+ }- const subagent = directMatches[0] ?? this._resolveDirectRlmSubagent(target);- const deletion = this._deleteResolvedRlmSubagent(subagent);+ private async _trackRlmSubagentDeletion(+ subagent: RlmSubagentRegistryEntry,+ deletion: Promise<RlmDeleteSubagentResult>,+ ): Promise<RlmDeleteSubagentResult> {this._deletingRlmChildren.set(subagent.rlm_child_id, { subagent, promise: deletion });try {return await deletion;@@ -8821,11 +8900,11 @@ export class AgentSession {}}- private _deleteRlmSubagentSession(childId: string, session: AgentSession): Promise<void> {+ private _deleteRlmSubagentSession(childId: string, session?: AgentSession): Promise<void> {if (this._subagentRuntimeHost) {return this._subagentRuntimeHost.deleteRlmSubagentRuntime(childId, session);}- return session.disposeAsync();+ return session?.disposeAsync() ?? Promise.resolve();}private _removeRlmSubagentTracking(childId: string, run?: RlmChildRun): void {@@ -8918,20 +8997,18 @@ export class AgentSession {this._emitRlmSubagentRemoval(subagent);const retained = this._retainedRlmChildSessions.get(childId);- if (retained) {- try {- await this._deleteRlmSubagentSession(childId, retained);- } catch (error) {- if (this._disposed || this._disposing) {- this._removeRlmSubagentTracking(childId);- void retained.disposeAsync().catch(() => undefined);- } else {- // Hide failed cleanup from the public registry while preserving the- // original selector and session for an explicit retry.- this._retryableRlmSubagentDeletions.set(childId, subagent);- }- throw error;+ try {+ await this._deleteRlmSubagentSession(childId, retained);+ } catch (error) {+ if (this._disposed || this._disposing) {+ this._removeRlmSubagentTracking(childId);+ void retained?.disposeAsync().catch(() => undefined);+ } else {+ // Hide failed cleanup from the public registry while preserving the+ // original selector and any retained session for an explicit retry.+ this._retryableRlmSubagentDeletions.set(childId, subagent);}+ throw error;}this._deletedRlmChildIds.add(childId);this._removeRlmSubagentTracking(childId);@@ -9023,8 +9100,8 @@ export class AgentSession {return false;}- private _assertRlmSubagentSessionNameAvailable(name: string): void {- if (this._pendingRlmSubagentSessionNames.has(name)) {+ private async _assertRlmSubagentSessionNameAvailable(name: string, ignorePendingReservation = false): Promise<void> {+ if (!ignorePendingReservation && this._pendingRlmSubagentSessionNames.has(name)) {throw new Error(`RLM subagent session name "${name}" is already in use`);}const conflictsWithSelector = (endpoint: {@@ -9057,7 +9134,7 @@ export class AgentSession {throw new Error(`RLM subagent session name "${name}" is already in use`);}}- const listedAgents = this._agentMessageController?.listAgents();+ const listedAgents = await this._agentMessageController?.listAgents();if (listedAgents &&((listedAgents.current ? conflictsWithSelector(listedAgents.current) : false) ||@@ -9134,11 +9211,16 @@ export class AgentSession {);}if (requestedSessionName) {- this._assertRlmSubagentSessionNameAvailable(requestedSessionName);+ if (this._pendingRlmSubagentSessionNames.has(requestedSessionName)) {+ throw new Error(`RLM subagent session name "${requestedSessionName}" is already in use`);+ }this._pendingRlmSubagentSessionNames.add(requestedSessionName);}let modelSelection: RlmSubagentModelSelection;try {+ if (requestedSessionName) {+ await this._assertRlmSubagentSessionNameAvailable(requestedSessionName, true);+ }modelSelection = await this._resolveRlmSubagentModel(requestedModel);} finally {if (requestedSessionName) {@@ -9153,7 +9235,7 @@ export class AgentSession {const childNodeId = basename(childSessionDir);const sessionName = requestedSessionName ?? createDefaultRlmSubagentSessionName(prompt, childNodeId);if (!requestedSessionName) {- this._assertRlmSubagentSessionNameAvailable(sessionName);+ await this._assertRlmSubagentSessionNameAvailable(sessionName);}const startedAt = Date.now();const parentAssistantForUsage = this._findLastAssistantMessage();diff --git a/packages/coding-agent/src/core/rlm-runtime.ts b/packages/coding-agent/src/core/rlm-runtime.tsindex eb273950ce..08f39aed0d 100644--- a/packages/coding-agent/src/core/rlm-runtime.ts+++ b/packages/coding-agent/src/core/rlm-runtime.ts@@ -60,7 +60,7 @@ export interface RlmFindModelsResult {}export type RlmRunHandler = (request: RlmRunRequest) => Promise<RlmRunResult>;-export type RlmListSubagentsHandler = () => RlmListSubagentsResult;+export type RlmListSubagentsHandler = () => RlmListSubagentsResult | Promise<RlmListSubagentsResult>;export type RlmDeleteSubagentHandler = (target: string) => Promise<RlmDeleteSubagentResult>;export type RlmFindModelsHandler = (query: string, limit: number) => RlmFindModelsResult | Promise<RlmFindModelsResult>;@@ -188,7 +188,7 @@ export function createRlmFindModelsHostHandler(handler: RlmFindModelsHandler): H/** Expose the current parent session's RLM child registry to its kernel. */export function createRlmListSubagentsHostHandler(handler: RlmListSubagentsHandler): HostRequestHandler {return async () => {- const { subagents } = handler();+ const { subagents } = await handler();return { subagents };};}@@ -237,8 +237,8 @@ export type RlmSubagentReleaseStatus = "done" | "error" | "cancelled";export interface SubagentRuntimeHost {createRlmSubagentRuntime(options: CreateRlmSubagentRuntimeOptions): Promise<RlmSubagentRuntime>;- /** Close the host-owned child identified by childId; session may predate an in-child session replacement. */- deleteRlmSubagentRuntime(childId: string, session: AgentSession): Promise<void>;+ /** Close or remove the host-owned child; session is absent when a persisted child is still passive. */+ deleteRlmSubagentRuntime(childId: string, session?: AgentSession): Promise<void>;releaseRlmSubagentRuntime?(runtime: RlmSubagentRuntime,options: CreateRlmSubagentRuntimeOptions,diff --git a/packages/coding-agent/src/modes/daemon/daemon-mode.ts b/packages/coding-agent/src/modes/daemon/daemon-mode.tsindex e09563fe57..8b646923ce 100644--- a/packages/coding-agent/src/modes/daemon/daemon-mode.ts+++ b/packages/coding-agent/src/modes/daemon/daemon-mode.ts@@ -20,6 +20,7 @@ import {writeFileSync,writeSync,} from "node:fs";+import { readFile } from "node:fs/promises";import { createConnection, createServer, type Server, type Socket } from "node:net";import { dirname, join, resolve } from "node:path";import { type Api, getLogger, type Model } from "@earendil-works/pi-ai";@@ -157,7 +158,9 @@ import { getDaemonRuntimeIdentity } from "./daemon-runtime-identity.js";import {buildRlmChildSnapshots,buildSessionList,+ inactiveLifecycleForSession,isActiveSessionBusy,+ type SessionSummary,summaryForActiveSession,} from "./daemon-session-list.js";import { DaemonSessionSummarizer } from "./daemon-session-summarizer.js";@@ -361,6 +364,16 @@ interface PersistedRlmSubagentRegistryEntry {updatedAt: string;}+type PassiveRlmRoot =+ | { rootParentState: ActiveSessionState; rootInfo?: never }+ | { rootParentState?: never; rootInfo: SessionInfo };++type PassiveRlmSubagent = PassiveRlmRoot & {+ entry: PersistedRlmSubagentRegistryEntry;+ info: SessionInfo;+ chain: PersistedRlmSubagentRegistryEntry[];+};+class RuntimeOpenCancelledError extends Error {}class BoundSessionUnavailableError extends Error {}@@ -396,10 +409,7 @@ export class AgentDaemon {private readonly openingSessions = new Map<string, Promise<ActiveSessionState>>();/** Covers path resolution through publication in openingSessions, before the runtime promise exists. */private readonly reservingSessionOpens = new Map<string, Promise<void>>();- private readonly rlmRehydrationClaims = new Map<- string,- { parentState: ActiveSessionState; entry: PersistedRlmSubagentRegistryEntry }- >();+ private readonly bindingCompletions = new Map<string, Promise<void>>();private readonly closingSessions = new Map<string, Promise<void>>();private readonly sideQuestionRuns = new Map<string,@@ -881,8 +891,10 @@ export class AgentDaemon {});}- private recordRlmSubagentDeletion(parentState: ActiveSessionState, childId: string): void {- const latest = this.readLatestRlmSubagentRegistry(parentState, true).find((entry) => entry.childId === childId);+ private async recordRlmSubagentDeletion(parentState: ActiveSessionState, childId: string): Promise<void> {+ const latest = (await this.readLatestRlmSubagentRegistry(parentState, true)).find(+ (entry) => entry.childId === childId,+ );if (!latest || latest.status === "deleted") {return;}@@ -900,16 +912,28 @@ export class AgentDaemon {private readLatestRlmSubagentRegistry(parentState: ActiveSessionState,throwOnReadError = false,- ): PersistedRlmSubagentRegistryEntry[] {- const path = this.rlmSubagentRegistryPath(parentState.runtime.session);- if (!path || !existsSync(path)) {+ ): Promise<PersistedRlmSubagentRegistryEntry[]> {+ return this.readLatestRlmSubagentRegistryPath(+ this.rlmSubagentRegistryPath(parentState.runtime.session),+ throwOnReadError,+ );+ }++ private async readLatestRlmSubagentRegistryPath(+ path: string | undefined,+ throwOnReadError = false,+ ): Promise<PersistedRlmSubagentRegistryEntry[]> {+ if (!path) {return [];}const latest = new Map<string, PersistedRlmSubagentRegistryEntry>();let lines: string[];try {- lines = readFileSync(path, "utf8").split(/\r?\n/);+ lines = (await readFile(path, "utf8")).split(/\r?\n/);} catch (error) {+ if ((error as NodeJS.ErrnoException).code === "ENOENT") {+ return [];+ }this.log(`failed to read RLM subagent registry: ${error instanceof Error ? error.message : String(error)}`);if (throwOnReadError) {throw error;@@ -945,6 +969,132 @@ export class AgentDaemon {return [...latest.values()];}+ private rlmSubagentRegistryPathForEntry(entry: PersistedRlmSubagentRegistryEntry, info: SessionInfo): string {+ return join(dirname(entry.sessionDir), "session-artifacts", info.id, RLM_SUBAGENT_REGISTRY_FILE);+ }++ private rlmSubagentRegistryPathForInfo(info: SessionInfo): string {+ return join(dirname(dirname(info.path)), "session-artifacts", info.id, RLM_SUBAGENT_REGISTRY_FILE);+ }++ /** Walk each supplied parent's persisted child tree once, without creating runtimes. */+ private async listPassiveRlmSubagents(+ savedRoots: SessionInfo[] = [],+ includeResident = false,+ ): Promise<PassiveRlmSubagent[]> {+ const passive: PassiveRlmSubagent[] = [];+ const visit = async (+ root: PassiveRlmRoot,+ entries: PersistedRlmSubagentRegistryEntry[],+ parentChain: PersistedRlmSubagentRegistryEntry[],+ visited: Set<string>,+ ): Promise<void> => {+ for (const entry of entries) {+ const sessionKey = resolve(entry.sessionFile);+ if (entry.status !== "completed" || visited.has(sessionKey)) continue;+ visited.add(sessionKey);+ const info = await readSessionInfo(entry.sessionFile);+ if (!info) continue;+ // A resident child walks its own registry as an outer root below. Avoid+ // both duplicate rows and attributing its descendants to an ancestor.+ if (!includeResident && this.findSessionBySessionFile(entry.sessionFile)) continue;+ const chain = [...parentChain, entry];+ passive.push({ ...root, entry, info, chain });+ await visit(+ root,+ await this.readLatestRlmSubagentRegistryPath(this.rlmSubagentRegistryPathForEntry(entry, info)),+ chain,+ visited,+ );+ }+ };+ const residentRootPaths = new Set<string>();+ for (const parentState of this.sessions.values()) {+ const parentFile = parentState.runtime.session.sessionFile;+ // An in-memory session cannot own a persisted registry.+ if (!parentFile) continue;+ const parentPath = resolve(parentFile);+ residentRootPaths.add(parentPath);+ await visit(+ { rootParentState: parentState },+ await this.readLatestRlmSubagentRegistry(parentState),+ [],+ new Set([parentPath]),+ );+ }+ for (const rootInfo of savedRoots) {+ const rootPath = resolve(rootInfo.path);+ if (inactiveLifecycleForSession(rootInfo) !== "live" || residentRootPaths.has(rootPath)) continue;+ const registryPath = this.rlmSubagentRegistryPathForInfo(rootInfo);+ if (!existsSync(registryPath)) continue;+ await visit({ rootInfo }, await this.readLatestRlmSubagentRegistryPath(registryPath), [], new Set([rootPath]));+ }+ return passive;+ }++ private async passiveRlmSubagentsByPath(+ savedRoots: SessionInfo[] = [],+ includeResident = false,+ ): Promise<Map<string, PassiveRlmSubagent>> {+ return new Map(+ (await this.listPassiveRlmSubagents(savedRoots, includeResident)).map((passive) => [+ resolve(passive.entry.sessionFile),+ passive,+ ]),+ );+ }++ private async buildSessionListWithPassiveRlmSubagents(+ activeSessions: ActiveSessionState[],+ savedSessions: SessionInfo[],+ scheduledJobs: AgentCronJob[],+ ): Promise<SessionSummary[]> {+ const passiveByPath = await this.passiveRlmSubagentsByPath(savedSessions);+ const savedByPath = new Map(savedSessions.map((session) => [resolve(session.path), session]));+ for (const [path, passive] of passiveByPath) {+ savedByPath.set(path, passive.info);+ }+ return buildSessionList(activeSessions, [...savedByPath.values()], scheduledJobs).map((summary) => {+ const passive = summary.sessionFile ? passiveByPath.get(resolve(summary.sessionFile)) : undefined;+ if (!passive || summary.activeSessionId) return summary;+ const parentEntry = passive.chain.at(-2);+ return {+ ...summary,+ runtimeKind: "subagent",+ ...(passive.chain.length === 1 && passive.rootParentState+ ? { parentActiveSessionId: passive.rootParentState.activeSessionId }+ : {}),+ parentSessionId: passive.entry.parentSessionId,+ parentSessionPath:+ passive.entry.parentSessionFile ??+ parentEntry?.sessionFile ??+ passive.rootParentState?.runtime.session.sessionFile ??+ passive.rootInfo?.path,+ rlmChildId: passive.entry.childId,+ rlmParentNodeId: passive.entry.rlmParentNodeId ?? passive.entry.childId,+ ...(!passive.rootParentState ? { rlmDepth: passive.entry.rlmDepth } : {}),+ spawnCode: passive.entry.spawnCode,+ };+ });+ }++ private async findPassiveRlmSubagent(+ target: string,+ includeResident = false,+ ): Promise<PassiveRlmSubagent | undefined> {+ const matches = [...(await this.passiveRlmSubagentsByPath([], includeResident)).values()].filter(+ ({ entry, info }) =>+ entry.childId === target ||+ resolve(entry.sessionFile) === resolve(target) ||+ info.id === target ||+ (info.name ?? entry.sessionName) === target,+ );+ if (matches.length > 1) {+ throw new Error(`Session selector "${target}" is ambiguous`);+ }+ return matches[0];+ }+private async addRuntime(runtime: AgentSessionRuntime,name?: string,@@ -952,15 +1102,17 @@ export class AgentDaemon {onStateCreated?: (state: ActiveSessionState) => void,runtimeOpenGuard?: RuntimeOpenGuard,onStateBound?: (state: ActiveSessionState) => void,+ restoreActiveSessionId?: string,): Promise<ActiveSessionState> {- const restoredActiveSessionId = runtime.metadata.kind === "top-level" ? this.restoreActiveSessionId : undefined;- if (restoredActiveSessionId) {+ const desiredActiveSessionId =+ runtime.metadata.kind === "top-level" ? this.restoreActiveSessionId : restoreActiveSessionId;+ if (runtime.metadata.kind === "top-level" && desiredActiveSessionId) {this.restoreActiveSessionId = undefined;}const state: ActiveSessionState = {activeSessionId:- restoredActiveSessionId && !this.sessions.has(restoredActiveSessionId)- ? restoredActiveSessionId+ desiredActiveSessionId && !this.sessions.has(desiredActiveSessionId)+ ? desiredActiveSessionId: createActiveSessionId(this.sessions),runtime,clients: new Set(),@@ -974,6 +1126,11 @@ export class AgentDaemon {}this.sessions.set(state.activeSessionId, state);this.bindingSessions.add(state.activeSessionId);+ let completeBinding!: () => void;+ const bindingCompletion = new Promise<void>((resolveBinding) => {+ completeBinding = resolveBinding;+ });+ this.bindingCompletions.set(state.activeSessionId, bindingCompletion);onStateCreated?.(state);try {await bindActiveSessionState(state, {@@ -999,6 +1156,8 @@ export class AgentDaemon {throw error;} finally {this.bindingSessions.delete(state.activeSessionId);+ this.bindingCompletions.delete(state.activeSessionId);+ completeBinding();}this.registerCronStoreForState(state);this.rebindCronJobsToState(state);@@ -1096,6 +1255,20 @@ export class AgentDaemon {return state;}+ const passiveSubagent = sessionPath ? await this.findPassiveRlmSubagent(sessionPath) : undefined;+ if (passiveSubagent) {+ if (runtimeOpenGuard && !(await runtimeOpenGuard())) {+ throw new RuntimeOpenCancelledError();+ }+ return this.hydratePassiveRlmSubagent(passiveSubagent);+ }++ // Hydration may have started while the async registry walk above was in+ // progress. Re-enter so the explicit opener joins its published promise.+ if (sessionKey && this.openingSessions.has(sessionKey)) {+ return this.createRuntime(command, runtimeOpenGuard);+ }+let releaseOpenReservation = () => {};if (sessionKey) {const reservation = this.reservingSessionOpens.get(sessionKey);@@ -1122,6 +1295,7 @@ export class AgentDaemon {const existing = sessionPath ? this.findSessionBySessionFile(sessionPath) : undefined;if (existing) {releaseOpenReservation();+ await this.waitForBoundSession(existing);if (runtimeOpenGuard && !(await runtimeOpenGuard())) {throw new RuntimeOpenCancelledError();}@@ -1157,6 +1331,7 @@ export class AgentDaemon {const existing = this.findSessionBySessionFile(sessionManager.getSessionFile());if (existing) {sessionLease?.release();+ await this.waitForBoundSession(existing);// A live runtime already owns this session file; reuse it instead of// starting a second runtime that would interleave writes to one file.// clientEnv adopts the first offered identity (e.g. a pane opening a@@ -1227,19 +1402,6 @@ export class AgentDaemon {},runtimeOpenGuard,);- const openedSessionFile = state.runtime.session.sessionFile;- const rehydrationKey = openedSessionFile ? resolve(openedSessionFile) : undefined;- const rehydrationClaim = rehydrationKey ? this.rlmRehydrationClaims.get(rehydrationKey) : undefined;- if (rehydrationKey && rehydrationClaim) {- if (this.rlmRehydrationClaims.get(rehydrationKey) === rehydrationClaim) {- this.rlmRehydrationClaims.delete(rehydrationKey);- }- await this.closeSession(state, "replaced");- return this.rehydrateCompletedRlmSubagent(rehydrationClaim.parentState, rehydrationClaim.entry);- }- if (state.runtime.metadata.kind === "top-level") {- await this.rehydrateCompletedRlmSubagents(state);- }return state;};@@ -1696,9 +1858,13 @@ export class AgentDaemon {(!requirePersistedJob || activeIdMatch?.runtime.session.sessionId === dueJob.sessionId? activeIdMatch: undefined);+ const requiresRlmSubagentRestore =+ dueJob.source === "rlm_heartbeat" &&+ dueJob.runtimeKind === "subagent" &&+ current?.runtime.metadata.kind !== "subagent";// A half-bound match falls through to createRuntime, which awaits the// pending create for the same session file instead of prompting mid-bind.- if (current && !this.bindingSessions.has(current.activeSessionId)) {+ if (current && !this.bindingSessions.has(current.activeSessionId) && !requiresRlmSubagentRestore) {this.rebindCronJobsToState(current);const reboundJob = requirePersistedJob ? this.getRunnableCronJob(job.id) : dueJob;return reboundJob && this.isCronJobRunnableForState(reboundJob, current, requirePersistedJob)@@ -1745,12 +1911,16 @@ export class AgentDaemon {}try {- const parentState = await this.createRuntime(+ const residentChild = this.findSessionBySessionFile(job.sessionFile);+ await this.createRuntime({ type: "create", sessionPath: parentSessionPath },() => this.getRunnableCronJob(job.id) !== undefined,);- await this.rehydrateCompletedRlmSubagents(parentState);- const childState = this.findSessionBySessionFile(job.sessionFile);+ const passiveSubagent = await this.findPassiveRlmSubagent(+ job.sessionFile,+ residentChild !== undefined && residentChild.runtime.metadata.kind !== "subagent",+ );+ const childState = passiveSubagent ? await this.hydratePassiveRlmSubagent(passiveSubagent) : residentChild;if (!childState || childState.runtime.metadata.kind !== "subagent") {this.cancelRlmHeartbeat(job.id);return undefined;@@ -1849,6 +2019,29 @@ export class AgentDaemon {return state;}+ private async getOrHydrateBoundSessionState(id: string): Promise<ActiveSessionState> {+ let lookupError: unknown;+ try {+ return this.getBoundSessionState(id);+ } catch (error) {+ if (error instanceof BoundSessionUnavailableError) {+ return this.waitForBoundSession(this.getSessionState(id));+ }+ lookupError = error;+ }+ const passiveSubagent = await this.findPassiveRlmSubagent(id);+ if (passiveSubagent) {+ return this.hydratePassiveRlmSubagent(passiveSubagent);+ }+ const hydratingChild = [...this.sessions.values()].find(+ (state) => state.runtime.metadata.kind === "subagent" && state.runtime.metadata.rlmChildId === id,+ );+ if (hydratingChild) {+ return this.waitForBoundSession(hydratingChild);+ }+ throw lookupError;+ }+private findRuntimeState(runtime: RlmSubagentRuntime): ActiveSessionState | undefined {if (!(runtime instanceof AgentSessionRuntime)) {return undefined;@@ -1871,21 +2064,24 @@ export class AgentDaemon {candidate.runtime.metadata.parentActiveSessionId === parentState.activeSessionId &&candidate.runtime.metadata.rlmChildId === childId,);- // Persist the deletion boundary before tearing down the runtime. If the write- // fails, the live child remains available for the parent to retry instead of- // becoming a disposed session that can still rehydrate after a crash.- this.recordRlmSubagentDeletion(parentState, childId);- if (!state) {- await session.disposeAsync();- return;- }- const shouldDisposeStaleSession = state.runtime.session !== session;+ const persisted = (await this.readLatestRlmSubagentRegistry(parentState, true)).find(+ (entry) => entry.childId === childId,+ );+ // Persist the deletion boundary before tearing down the runtime. As with a+ // resident child, deletion keeps its transcript and artifact tree on disk.+ await this.recordRlmSubagentDeletion(parentState, childId);+ const staleSession = state && session && state.runtime.session !== session ? session : undefined;try {- await this.closeSession(state, "killed", false);- } finally {- if (shouldDisposeStaleSession) {- await session.disposeAsync();+ if (state) {+ await this.closeSession(state, "killed", false);+ } else {+ await session?.disposeAsync();}+ } finally {+ await staleSession?.disposeAsync();+ }+ if (persisted && !state) {+ this.cancelScheduledJobsForSessionFile(persisted.sessionFile);}},disposeRlmSubagentRuntimes: async () => {@@ -2052,43 +2248,79 @@ export class AgentDaemon {return runtime;}- private isRlmAncestorState(state: ActiveSessionState, candidate: ActiveSessionState): boolean {- const visited = new Set<string>();- let current: ActiveSessionState | undefined = state;- while (current && !visited.has(current.activeSessionId)) {- if (current.activeSessionId === candidate.activeSessionId) {- return true;- }- visited.add(current.activeSessionId);- const parentId: string | undefined = current.runtime.metadata.parentActiveSessionId;- current = parentId ? this.sessions.get(parentId) : undefined;+ private async hydratePassiveRlmSubagent(passive: PassiveRlmSubagent): Promise<ActiveSessionState> {+ let parentState = passive.rootParentState;+ if (!parentState) {+ throw new Error(`Cannot hydrate RLM subagent ${passive.entry.childId} without a resident root parent`);}- return false;+ for (const entry of passive.chain) {+ const activeSessionId = entry === passive.entry ? passive.info.id : undefined;+ parentState = await this.rehydrateCompletedRlmSubagent(parentState, entry, activeSessionId);+ }+ return parentState;}- private hasRlmSubagentState(parentState: ActiveSessionState, childId: string, sessionFile?: string): boolean {- const targetSessionFile = sessionFile ? resolve(sessionFile) : undefined;- return [...this.sessions.values()].some((state) => {- const existingFile = state.runtime.session.sessionFile;- if (targetSessionFile && existingFile && resolve(existingFile) === targetSessionFile) {- return true;+ private async rehydrateCompletedRlmSubagent(+ parentState: ActiveSessionState,+ entry: PersistedRlmSubagentRegistryEntry,+ restoreActiveSessionId?: string,+ ): Promise<ActiveSessionState> {+ const sessionKey = resolve(entry.sessionFile);+ const reservation = this.reservingSessionOpens.get(sessionKey);+ if (reservation) {+ await reservation;+ return this.rehydrateCompletedRlmSubagent(parentState, entry, restoreActiveSessionId);+ }+ const pending = this.openingSessions.get(sessionKey);+ if (pending) {+ return pending;+ }+ const existing = this.findSessionBySessionFile(entry.sessionFile);+ if (existing?.runtime.metadata.kind === "subagent") {+ return this.waitForBoundSession(existing);+ }+ const hydration = (async () => {+ if (existing) {+ await this.closeSession(existing, "replaced");}- const metadata = state.runtime.metadata;- return (- metadata.kind === "subagent" &&- metadata.parentActiveSessionId === parentState.activeSessionId &&- metadata.rlmChildId === childId- );- });+ return this.rehydrateCompletedRlmSubagentOnce(parentState, entry, restoreActiveSessionId);+ })();+ // Explicit opens and all lazy triggers share this path-keyed publication,+ // so no caller can acquire a second lease/runtime while hydration binds.+ this.openingSessions.set(sessionKey, hydration);+ try {+ return await hydration;+ } finally {+ if (this.openingSessions.get(sessionKey) === hydration) {+ this.openingSessions.delete(sessionKey);+ }+ }}- private async rehydrateCompletedRlmSubagent(+ private async waitForBoundSession(state: ActiveSessionState): Promise<ActiveSessionState> {+ const completion = this.bindingCompletions.get(state.activeSessionId);+ if (completion) {+ await completion;+ }+ if (this.sessions.get(state.activeSessionId) !== state || this.bindingSessions.has(state.activeSessionId)) {+ throw new BoundSessionUnavailableError(`Active session ${state.activeSessionId} did not finish initializing`);+ }+ if (this.closingSessions.has(state.activeSessionId)) {+ throw new BoundSessionUnavailableError(`Active session ${state.activeSessionId} is closing`);+ }+ return state;+ }++ private async rehydrateCompletedRlmSubagentOnce(parentState: ActiveSessionState,entry: PersistedRlmSubagentRegistryEntry,+ restoreActiveSessionId?: string,): Promise<ActiveSessionState> {let stateRef: ActiveSessionState | undefined;let runtime: AgentSessionRuntime | undefined;+ let sessionLease: SessionLease | undefined;try {+ sessionLease = acquireSessionLease(entry.sessionFile, parentState.runtime.services.agentDir);const sessionManager = await SessionManager.openAsync(entry.sessionFile, entry.sessionDir);const modelRegistry = parentState.runtime.services.modelRegistry;let rehydratedModel: Model<Api> | undefined;@@ -2105,6 +2337,7 @@ export class AgentDaemon {sessionManager,sessionStartEvent: { type: "session_start", reason: "startup" },sessionConfig: parentState.runtime.runtimeConfig,+ sessionLease,sessionOptions: {...(rehydratedModel ? { model: rehydratedModel } : {}),agentMessageController: this.createAgentMessageController(() => stateRef),@@ -2156,16 +2389,23 @@ export class AgentDaemon {},}),);- const state = await this.addRuntime(runtime, undefined, parentState.clientEnv, (createdState) => {- stateRef = createdState;- });+ const state = await this.addRuntime(+ runtime,+ undefined,+ parentState.clientEnv,+ (createdState) => {+ stateRef = createdState;+ },+ undefined,+ undefined,+ restoreActiveSessionId,+ );// The session transcript is authoritative for mutable metadata such as a// later user-assigned name; the registry value is only the spawn snapshot.if (!parentState.runtime.session.retainFinishedRlmChildSession(entry.childId, runtime.session)) {await this.closeSession(state, "replaced");throw new RuntimeOpenCancelledError();}- await this.rehydrateCompletedRlmSubagents(state);return state;} catch (error) {if (stateRef && this.sessions.get(stateRef.activeSessionId) === stateRef) {@@ -2173,87 +2413,11 @@ export class AgentDaemon {} else {await runtime?.dispose().catch(() => undefined);}+ sessionLease?.release();throw error;}}- private async rehydrateCompletedRlmSubagents(parentState: ActiveSessionState): Promise<void> {- for (const entry of this.readLatestRlmSubagentRegistry(parentState)) {- if (entry.status !== "completed" || !existsSync(entry.sessionFile)) {- continue;- }- const sessionKey = resolve(entry.sessionFile);- const existing = this.findSessionBySessionFile(entry.sessionFile);- if (existing && this.isRlmAncestorState(parentState, existing)) {- continue;- }- if (existing && !this.bindingSessions.has(existing.activeSessionId)) {- if (existing.runtime.metadata.kind !== "top-level") {- continue;- }- // A stable explicit open has already returned a valid active ID. Notify- // its clients before replacing it with the correctly configured child.- await this.closeSession(existing, "replaced").catch((error) => {- this.log(- `failed to replace top-level RLM subagent ${entry.sessionName}: ${- error instanceof Error ? error.message : String(error)- }`,- );- });- }- const pending = this.openingSessions.get(sessionKey);- if (pending) {- const claim = { parentState, entry };- const installedClaim = !this.rlmRehydrationClaims.has(sessionKey);- if (installedClaim) {- // createRuntime consumes this after binding but before top-level recursive- // recovery or promise resolution, so callers receive the child state.- this.rlmRehydrationClaims.set(sessionKey, claim);- }- try {- await pending;- continue;- } catch (error) {- this.log(- `failed to await completed RLM subagent ${entry.sessionName}: ${- error instanceof Error ? error.message : String(error)- }`,- );- // The failed owner completed all runtime cleanup before rejecting. Clear- // only that stale claim, then let rehydration retry the persisted child.- if (this.openingSessions.get(sessionKey) === pending) {- this.openingSessions.delete(sessionKey);- }- if (this.hasRlmSubagentState(parentState, entry.childId, entry.sessionFile)) {- continue;- }- } finally {- if (installedClaim && this.rlmRehydrationClaims.get(sessionKey) === claim) {- this.rlmRehydrationClaims.delete(sessionKey);- }- }- }- if (this.hasRlmSubagentState(parentState, entry.childId, entry.sessionFile)) {- continue;- }- const opening = this.rehydrateCompletedRlmSubagent(parentState, entry);- this.openingSessions.set(sessionKey, opening);- try {- await opening;- } catch (error) {- this.log(- `failed to rehydrate completed RLM subagent ${entry.sessionName}: ${- error instanceof Error ? error.message : String(error)- }`,- );- } finally {- if (this.openingSessions.get(sessionKey) === opening) {- this.openingSessions.delete(sessionKey);- }- }- }- }-private createAgentMessageController(getCurrentState: () => ActiveSessionState | undefined,): AgentSessionMessageController {@@ -2301,20 +2465,20 @@ export class AgentDaemon {};}- private createAgentObserveAgentSnapshot(+ private async createAgentObserveAgentSnapshot(currentState: ActiveSessionState,target: string,- ): AgentObserveAgentSnapshot {+ ): Promise<AgentObserveAgentSnapshot> {return {- agent: this.createAgentObserveSummary(this.getBoundSessionState(target), currentState),+ agent: this.createAgentObserveSummary(await this.getOrHydrateBoundSessionState(target), currentState),};}- private createAgentObserveRecentMessages(+ private async createAgentObserveRecentMessages(currentState: ActiveSessionState,input: AgentObserveRecentMessagesInput,- ): AgentObserveRecentMessagesResult {- const targetState = this.getBoundSessionState(input.target);+ ): Promise<AgentObserveRecentMessagesResult> {+ const targetState = await this.getOrHydrateBoundSessionState(input.target);const limit = normalizeObserveLimit(input.limit);const maxChars = normalizeObserveMaxChars(input.maxChars);const messages = targetState.runtime.session.messages;@@ -2842,7 +3006,7 @@ export class AgentDaemon {const scheduledJobs = this.cronStore.list();if (!command.all) {return success(command.id, "list", {- sessions: buildSessionList(activeSessions, [], scheduledJobs),+ sessions: await this.buildSessionListWithPassiveRlmSubagents(activeSessions, [], scheduledJobs),});}const defaultConfig = this.options.defaultSessionConfig;@@ -2850,7 +3014,11 @@ export class AgentDaemon {if (command.cwd) {const savedSessions = await SessionManager.list(resolve(command.cwd), listSessionDir);return success(command.id, "list", {- sessions: buildSessionList(activeSessions, savedSessions, scheduledJobs),+ sessions: await this.buildSessionListWithPassiveRlmSubagents(+ activeSessions,+ savedSessions,+ scheduledJobs,+ ),});}const savedSessions =@@ -2858,7 +3026,11 @@ export class AgentDaemon {? await SessionManager.listAll(undefined, listSessionDir): await SessionManager.listAll();return success(command.id, "list", {- sessions: buildSessionList(activeSessions, savedSessions, scheduledJobs),+ sessions: await this.buildSessionListWithPassiveRlmSubagents(+ activeSessions,+ savedSessions,+ scheduledJobs,+ ),});}@@ -2913,7 +3085,7 @@ export class AgentDaemon {}case "attach": {- const state = this.getBoundSessionState(command.activeSessionId);+ const state = await this.getOrHydrateBoundSessionState(command.activeSessionId);if (command.clientId) {client.id = command.clientId;}@@ -4157,13 +4329,32 @@ export class AgentDaemon {unfinishedActionCount: state.runtime.session.unfinishedActionCount,...(metadata.parentActiveSessionId ? { parentActiveSessionId: metadata.parentActiveSessionId } : {}),...(metadata.rlmChildId ? { rlmChildId: metadata.rlmChildId } : {}),+ ...(metadata.sessionDir ? { sessionDir: metadata.sessionDir } : {}),};}- private createAgentMessageListResult(current: ActiveSessionState): AgentSessionMessageListResult {+ private async createAgentMessageListResult(current: ActiveSessionState): Promise<AgentSessionMessageListResult> {const localAgents = this.listTargetableSessionStates(current).map((state) =>this.createAgentMessageAgentSummary(state),);+ for (const passive of await this.listPassiveRlmSubagents()) {+ const { entry, info } = passive;+ localAgents.push({+ // Before hydration the persisted session id is its supervisor-routable id.+ activeSessionId: info.id,+ sessionId: info.id,+ sessionName: info.name ?? entry.sessionName,+ runtimeKind: "subagent",+ cwd: info.cwd,+ isStreaming: false,+ unfinishedActionCount: 0,+ ...(passive.chain.length === 1 && passive.rootParentState+ ? { parentActiveSessionId: passive.rootParentState.activeSessionId }+ : {}),+ rlmChildId: entry.childId,+ sessionDir: entry.sessionDir,+ });+ }const localIds = new Set(localAgents.map((agent) => agent.activeSessionId));return {current: this.createAgentSessionMessageEndpoint(current),@@ -4282,17 +4473,30 @@ export class AgentDaemon {targetState = this.getBoundSessionState(targetSelector);} catch (error) {if (error instanceof BoundSessionUnavailableError) {- throw error;- }- if (this.options.worker && options.fromState && this.findRemoteAgentPeer(targetSelector)) {- return this.sendRemoteAgentSessionMessage(- options.fromState,- targetSelector,- options.message,- options.deliveryMode,- );+ targetState = await this.waitForBoundSession(this.getSessionState(targetSelector));+ } else {+ const passiveSubagent = await this.findPassiveRlmSubagent(targetSelector);+ if (passiveSubagent) {+ targetState = await this.hydratePassiveRlmSubagent(passiveSubagent);+ } else {+ const hydratingChild = [...this.sessions.values()].find(+ (state) =>+ state.runtime.metadata.kind === "subagent" && state.runtime.metadata.rlmChildId === targetSelector,+ );+ if (hydratingChild) {+ targetState = await this.waitForBoundSession(hydratingChild);+ } else if (this.options.worker && options.fromState && this.findRemoteAgentPeer(targetSelector)) {+ return this.sendRemoteAgentSessionMessage(+ options.fromState,+ targetSelector,+ options.message,+ options.deliveryMode,+ );+ } else {+ throw error;+ }+ }}- throw error;}if (options.fromState?.activeSessionId === targetState.activeSessionId) {throw new Error("Agent messaging cannot target the sending session");diff --git a/packages/coding-agent/src/modes/daemon/daemon-protocol.ts b/packages/coding-agent/src/modes/daemon/daemon-protocol.tsindex bd13063d09..37d1643d5a 100644--- a/packages/coding-agent/src/modes/daemon/daemon-protocol.ts+++ b/packages/coding-agent/src/modes/daemon/daemon-protocol.ts@@ -51,9 +51,9 @@ import type { SessionSummary } from "./daemon-session-list.js";export const DAEMON_PROTOCOL_NAME = "prime-agent.daemon";export const DAEMON_PROTOCOL_VERSION = 7;export const DAEMON_COMMAND_ENVELOPE_MIN_PROTOCOL_VERSION = 7;-// Revision 8 publishes literal session-action queues and activity separately.-export const DAEMON_SCHEMA_REVISION = 8;-export const DAEMON_SCHEMA_ID = "protocol-7-schema-8-b56e29842cfa";+// Revision 9 publishes persisted RLM spawn depth on passive session rows.+export const DAEMON_SCHEMA_REVISION = 9;+export const DAEMON_SCHEMA_ID = "protocol-7-schema-9-b56e29842cfa";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 7e6a5397ac..7a2d2d37ed 100644--- a/packages/coding-agent/src/modes/daemon/daemon-session-list.ts+++ b/packages/coding-agent/src/modes/daemon/daemon-session-list.ts@@ -32,6 +32,8 @@ export interface SessionSummary {isSessionActive: boolean;hasActiveHeartbeat?: boolean;runtimeKind?: "top-level" | "subagent";+ /** RLM spawn depth for persisted passive subagent rows. */+ rlmDepth?: number;activeSessionId?: string;sessionId: string;sessionFile?: string;diff --git a/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts b/packages/coding-agent/src/modes/daemon/daemon-supervisor.tsindex ffce3270d5..43be339a1d 100644--- a/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts+++ b/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts@@ -1247,6 +1247,22 @@ export class DaemonSupervisor {return this.handleSavedSessionList(client, command);case "create": {const worker = await this.createOrReuseWorker(this.protocolClientId(client), command);+ const requestedSummary = command.sessionPath+ ? this.findSummaryInWorker(worker, command.sessionPath)+ : undefined;+ if (+ requestedSummary &&+ (requestedSummary.activeSessionId ?? requestedSummary.id) !== worker.descriptor.rootActiveSessionId+ ) {+ // A create forwarded to a recovering worker still surfaces an opaque lifecycle error.+ const response = await this.forwardToWorker(worker, withoutSupervisorCreateFields(command));+ if (response.success && isSessionSummary(response.data)) {+ await this.refreshWorkerSummaries(worker);+ await this.syncAgentPeers().catch(() => undefined);+ return { ...response, id: command.id, data: this.publicSummary(worker, response.data) };+ }+ return responseWithId(response, command.id);+ }const summary = worker.summaries.get(worker.descriptor.rootActiveSessionId);if (!summary) {throw new Error("Session worker started without a root session");@@ -1748,6 +1764,8 @@ export class DaemonSupervisor {if (existing) {return this.reuseWorkerForCreate(existing.worker, ownerClientId, sessionPath);}+ // A passive child from a stopped worker reopens as top-level here (pre-existing behavior);+ // the recursive-harness residency/eviction PR will revisit it.}const key = createCommand.sessionPath? canonicalSessionPath(createCommand.sessionPath)@@ -2773,6 +2791,21 @@ export class DaemonSupervisor {return exact.length > 0 ? exact : suffix;}+ private findSummaryInWorker(worker: ResidentWorker, selector: string): SessionSummary | undefined {+ const pathSelector = looksLikeSessionPath(selector) ? canonicalSessionPath(selector) : undefined;+ return [...worker.summaries.values()].find((summary) => {+ const activeSessionId = summary.activeSessionId ?? summary.id;+ return (+ activeSessionId === selector ||+ summary.sessionId === selector ||+ summary.sessionName === selector ||+ (pathSelector !== undefined &&+ summary.sessionFile !== undefined &&+ canonicalSessionPath(summary.sessionFile) === pathSelector)+ );+ });+ }+private findWorkerBySessionFile(sessionFile: string): WorkerMatch | undefined {const target = canonicalSessionPath(sessionFile);for (const worker of this.workers.values()) {diff --git a/packages/coding-agent/test/agent-session-recursion.test.ts b/packages/coding-agent/test/agent-session-recursion.test.tsindex d6c70d0465..714ab0dad9 100644--- a/packages/coding-agent/test/agent-session-recursion.test.ts+++ b/packages/coding-agent/test/agent-session-recursion.test.ts@@ -108,9 +108,15 @@ interface InspectableRlmSession {_activeRlmChildRuns: Map<string, InspectableRlmRun>;_deletingRlmChildren: Map<string,- { subagent: ReturnType<AgentSession["listRlmSubagents"]>["subagents"][number]; promise: Promise<unknown> }+ {+ subagent: Awaited<ReturnType<AgentSession["listRlmSubagents"]>>["subagents"][number];+ promise: Promise<unknown>;+ }+ >;+ _retryableRlmSubagentDeletions: Map<+ string,+ Awaited<ReturnType<AgentSession["listRlmSubagents"]>>["subagents"][number]>;- _retryableRlmSubagentDeletions: Map<string, ReturnType<AgentSession["listRlmSubagents"]>["subagents"][number]>;_retainedRlmChildSessions: Map<string, AgentSession>;_retainedRlmChildUnsubscribes: Map<string, () => void>;_createKernelHostHandlers(): HostRequestHandlers;@@ -285,7 +291,7 @@ describe("AgentSession rlm recursion", () => {throw new Error("Missing retained child session");}expect(childSession.sessionName).toBe("api-reviewer");- expect(root.listRlmSubagents().subagents[0]?.session_name).toBe("api-reviewer");+ expect((await root.listRlmSubagents()).subagents[0]?.session_name).toBe("api-reviewer");await expect(root.runRlmChild("collide with child id", { name: childId })).rejects.toThrow(`RLM subagent session name "${childId}" is already in use`,@@ -324,7 +330,7 @@ describe("AgentSession rlm recursion", () => {});const runPromise = root.runRlmChild("rename while running", { name: "spawn-worker" });await waitFor(() => childStarted);- const running = root.listRlmSubagents().subagents[0];+ const running = (await root.listRlmSubagents()).subagents[0];if (!running) {throw new Error("Missing running child");}@@ -332,7 +338,7 @@ describe("AgentSession rlm recursion", () => {throw new Error("Missing running child session ID");}root.getRlmChildSession(running.rlm_child_id)?.setSessionName("renamed-running-worker");- expect(root.listRlmSubagents().subagents[0]?.session_name).toBe("renamed-running-worker");+ expect((await root.listRlmSubagents()).subagents[0]?.session_name).toBe("renamed-running-worker");await expect(root.runRlmChild("reuse renamed selector", { name: "renamed-running-worker" })).rejects.toThrow('RLM subagent session name "renamed-running-worker" is already in use',@@ -360,7 +366,7 @@ describe("AgentSession rlm recursion", () => {});expect(root.retainFinishedRlmChildSession(childId, child)).toBe(true);- expect(root.listRlmSubagents().subagents).toEqual([+ expect((await root.listRlmSubagents()).subagents).toEqual([expect.objectContaining({rlm_child_id: childId,session_name: "restored-worker",@@ -372,7 +378,7 @@ describe("AgentSession rlm recursion", () => {subagent: { rlm_child_id: childId, session_name: "restored-worker" },});expect(disposeChild).toHaveBeenCalledOnce();- expect(root.listRlmSubagents()).toEqual({ subagents: [] });+ expect(await root.listRlmSubagents()).toEqual({ subagents: [] });expect(childStatuses).toEqual(["cancelled"]);});@@ -397,13 +403,13 @@ describe("AgentSession rlm recursion", () => {},});expect(root.retainFinishedRlmChildSession(childId, child)).toBe(true);- const retainedSnapshot = root.listRlmSubagents().subagents[0];+ const retainedSnapshot = (await root.listRlmSubagents()).subagents[0];if (!retainedSnapshot?.session_id) {throw new Error("Missing retained child session ID");}await expect(root.deleteRlmSubagent("retained-retry-worker")).rejects.toThrow("retained close failed");- expect(root.listRlmSubagents()).toEqual({ subagents: [] });+ expect(await root.listRlmSubagents()).toEqual({ subagents: [] });expect((root as unknown as InspectableRlmSession)._retryableRlmSubagentDeletions.size).toBe(1);child.setSessionName("renamed-retry-worker");await expect(root.runRlmChild("reuse retry selector", { name: "retained-retry-worker" })).rejects.toThrow(@@ -525,7 +531,7 @@ describe("AgentSession rlm recursion", () => {},],};- expect(root.listRlmSubagents()).toEqual(expectedRegistry);+ expect(await root.listRlmSubagents()).toEqual(expectedRegistry);const inspectable = root as unknown as InspectableRlmSession;const conflictingDeletion = {...expectedRegistry.subagents[0],@@ -551,12 +557,59 @@ describe("AgentSession rlm recursion", () => {subagent: expectedRegistry.subagents[0],});expect(root.getRlmChildSession(daemonChildId)).toBeUndefined();- expect(root.listRlmSubagents()).toEqual({ subagents: [] });+ expect(await root.listRlmSubagents()).toEqual({ subagents: [] });await expect(deleteHandler({ target: expectedSessionName })).rejects.toThrow("No direct RLM subagent matches");root.dispose();- expect(root.listRlmSubagents()).toEqual({ subagents: [] });+ expect(await root.listRlmSubagents()).toEqual({ subagents: [] });+ });++ it("lists and deletes a passive daemon child without a retained runtime", async () => {+ const deleteRlmSubagentRuntime = vi.fn(async () => {});+ const root = createSession({+ agentMessageController: {+ listAgents: () => ({+ current: { activeSessionId: "parent-active", sessionId: "parent-session" },+ agents: [+ {+ activeSessionId: "passive-session",+ sessionId: "passive-session",+ sessionName: "passive-worker",+ runtimeKind: "subagent",+ cwd: tempDir,+ isStreaming: false,+ unfinishedActionCount: 0,+ parentActiveSessionId: "parent-active",+ rlmChildId: "passive-child",+ sessionDir: join(tempDir, "passive-child"),+ },+ ],+ }),+ sendAgentMessage: async () => {+ throw new Error("unexpected send");+ },+ },+ subagentRuntimeHost: {+ createRlmSubagentRuntime: async () => {+ throw new Error("unexpected hydration");+ },+ deleteRlmSubagentRuntime,+ },+ });+ const expected = {+ rlm_child_id: "passive-child",+ active_session_id: null,+ session_id: "passive-session",+ session_name: "passive-worker",+ session_dir: join(tempDir, "passive-child"),+ status: "completed" as const,+ };++ expect(await root.listRlmSubagents()).toEqual({ subagents: [expected] });+ await expect(root.deleteRlmSubagent("passive-worker")).resolves.toEqual({ subagent: expected });+ expect(deleteRlmSubagentRuntime).toHaveBeenCalledWith("passive-child", undefined);+ expect(await root.listRlmSubagents()).toEqual({ subagents: [] });});it("disposes an inline child when setting its session name fails", async () => {@@ -631,7 +684,7 @@ describe("AgentSession rlm recursion", () => {if (!rootRun?.session) {throw new Error("Missing child session on root run");}- expect(root.listRlmSubagents()).toEqual({+ expect(await root.listRlmSubagents()).toEqual({subagents: [{rlm_child_id: rootRun.id,@@ -886,7 +939,7 @@ describe("AgentSession rlm recursion", () => {releaseChild();await expect(runPromise).rejects.toThrow("Cancelled by user");expect(childStatuses[childStatuses.length - 1]).toBe("cancelled");- expect(root.listRlmSubagents()).toEqual({ subagents: [] });+ expect(await root.listRlmSubagents()).toEqual({ subagents: [] });// The run has finished; a second cancel finds nothing to stop.expect(root.cancelRlmChildRun(childId)).toBe(false);@@ -903,6 +956,7 @@ describe("AgentSession rlm recursion", () => {subagentRuntimeHost: {createRlmSubagentRuntime: async () => ({ session: hostedChild }),deleteRlmSubagentRuntime: async (_childId, child) => {+ if (!child) throw new Error("missing live child");await child.disposeAsync();},releaseRlmSubagentRuntime: async (runtime, options, status) => {@@ -922,18 +976,18 @@ describe("AgentSession rlm recursion", () => {const runPromise = root.runRlmChild("fast child", { name: "fast-worker" });const runFailure = expect(runPromise).rejects.toThrow("Deleted by parent orchestrator");await waitFor(() => releaseStarted);- const completed = root.listRlmSubagents().subagents[0];+ const completed = (await root.listRlmSubagents()).subagents[0];if (!completed) {throw new Error("Missing completed child during release");}const deletion = root.deleteRlmSubagent("fast-worker");- expect(root.listRlmSubagents()).toEqual({ subagents: [] });+ expect(await root.listRlmSubagents()).toEqual({ subagents: [] });await expect(deletion).resolves.toEqual({ subagent: completed });await runFailure;releaseRetention();await Promise.resolve();- expect(root.listRlmSubagents()).toEqual({ subagents: [] });+ expect(await root.listRlmSubagents()).toEqual({ subagents: [] });});it("keeps failed closure retryable without hanging or late resurrection", async () => {@@ -977,21 +1031,21 @@ describe("AgentSession rlm recursion", () => {await waitFor(() => childStarted);const runFailure = expect(runPromise).rejects.toThrow("Deleted by parent orchestrator");const deletion = root.deleteRlmSubagent("release-worker");- expect(root.listRlmSubagents()).toEqual({ subagents: [] });+ expect(await root.listRlmSubagents()).toEqual({ subagents: [] });await expect(deletion).rejects.toThrow("close failed");await runFailure;expect((root as unknown as InspectableRlmSession)._activeRlmChildRuns.size).toBe(0);- expect(root.listRlmSubagents()).toEqual({ subagents: [] });+ expect(await root.listRlmSubagents()).toEqual({ subagents: [] });// The failed close remains directly retryable by the original selector even// though the cancelled child is hidden from the public registry.await expect(root.deleteRlmSubagent("release-worker")).resolves.toMatchObject({subagent: { session_name: "release-worker" },});- expect(root.listRlmSubagents()).toEqual({ subagents: [] });+ expect(await root.listRlmSubagents()).toEqual({ subagents: [] });releaseChild();await Promise.resolve();- expect(root.listRlmSubagents()).toEqual({ subagents: [] });+ expect(await root.listRlmSubagents()).toEqual({ subagents: [] });});it("does not restore failed delete retry state after parent teardown", async () => {@@ -1076,7 +1130,7 @@ describe("AgentSession rlm recursion", () => {releaseChild();await waitFor(() => releaseRuntime.mock.calls.length === 1);await waitFor(() => internals._retryableRlmSubagentDeletions.size === 0);- expect(root.listRlmSubagents()).toEqual({ subagents: [] });+ expect(await root.listRlmSubagents()).toEqual({ subagents: [] });await expect(root.deleteRlmSubagent("eventual-release-worker")).rejects.toThrow("No direct RLM subagent matches");});@@ -1109,14 +1163,14 @@ describe("AgentSession rlm recursion", () => {const runPromise = root.runRlmChild("cancel before failed release", { name: "cancelled-worker" });await waitFor(() => childStarted);- const childId = root.listRlmSubagents().subagents[0]?.rlm_child_id;+ const childId = (await root.listRlmSubagents()).subagents[0]?.rlm_child_id;expect(childId).toBeTruthy();expect(root.cancelRlmChildRun(childId as string)).toBe(true);releaseChild();await expect(runPromise).rejects.toThrow();expect(disposeHostedChild).toHaveBeenCalledOnce();- expect(root.listRlmSubagents()).toEqual({ subagents: [] });+ expect(await root.listRlmSubagents()).toEqual({ subagents: [] });});it("deletes a queued child without waiting for blocked startup", async () => {@@ -1143,19 +1197,19 @@ describe("AgentSession rlm recursion", () => {const runPromise = root.runRlmChild("blocked before runtime creation", { name: "queued-worker" });const runFailure = expect(runPromise).rejects.toThrow("Deleted by parent orchestrator");await waitFor(() => runtimeCreationStarted);- const queued = root.listRlmSubagents().subagents[0];+ const queued = (await root.listRlmSubagents()).subagents[0];expect(queued).toBeDefined();await expect(root.deleteRlmSubagent("queued-worker")).resolves.toEqual({ subagent: queued });await runFailure;expect((root as unknown as InspectableRlmSession)._activeRlmChildRuns.size).toBe(1);- expect(root.listRlmSubagents()).toEqual({ subagents: [] });+ expect(await root.listRlmSubagents()).toEqual({ subagents: [] });await expect(root.runRlmChild("replacement", { name: "queued-worker" })).rejects.toThrow("already in use");releaseRuntimeCreation();await waitFor(() => releaseRuntime.mock.calls.length === 1);await waitFor(() => (root as unknown as InspectableRlmSession)._activeRlmChildRuns.size === 0);- expect(root.listRlmSubagents()).toEqual({ subagents: [] });+ expect(await root.listRlmSubagents()).toEqual({ subagents: [] });});it("keeps late startup cleanup retryable when release and fallback delete fail", async () => {@@ -1192,7 +1246,7 @@ describe("AgentSession rlm recursion", () => {const runPromise = root.runRlmChild("delete during runtime creation", { name: "starting-worker" });const runFailure = expect(runPromise).rejects.toThrow("Deleted by parent orchestrator");await waitFor(() => runtimeCreationStarted);- const starting = root.listRlmSubagents().subagents[0];+ const starting = (await root.listRlmSubagents()).subagents[0];expect(starting).toBeDefined();await expect(root.deleteRlmSubagent("starting-worker")).resolves.toEqual({ subagent: starting });@@ -1203,7 +1257,7 @@ describe("AgentSession rlm recursion", () => {const internals = root as unknown as InspectableRlmSession;await waitFor(() => releaseRuntime.mock.calls.length === 1);await waitFor(() => internals._retryableRlmSubagentDeletions.size === 1);- expect(root.listRlmSubagents()).toEqual({ subagents: [] });+ expect(await root.listRlmSubagents()).toEqual({ subagents: [] });expect(deleteRuntime).toHaveBeenCalledTimes(1);expect(disposeHostedChild).not.toHaveBeenCalled();@@ -1233,19 +1287,19 @@ describe("AgentSession rlm recursion", () => {const runPromise = root.runRlmChild("slow named shard", { name: "slow-worker" });await waitFor(() => childStarted);- const running = root.listRlmSubagents().subagents[0];+ const running = (await root.listRlmSubagents()).subagents[0];if (!running) {throw new Error("Missing running child registry entry");}const runFailure = expect(runPromise).rejects.toThrow("Deleted by parent orchestrator");const deletion = root.deleteRlmSubagent("slow-worker");const duplicateDeletion = root.deleteRlmSubagent(running.rlm_child_id);- expect(root.listRlmSubagents()).toEqual({ subagents: [] });+ expect(await root.listRlmSubagents()).toEqual({ subagents: [] });await expect(deletion).resolves.toEqual({ subagent: running });await expect(duplicateDeletion).resolves.toEqual({ subagent: running });await runFailure;releaseChild();- expect(root.listRlmSubagents()).toEqual({ subagents: [] });+ expect(await root.listRlmSubagents()).toEqual({ subagents: [] });});it("cancels nested rlm child runs through the root session", async () => {diff --git a/packages/coding-agent/test/daemon-mode.test.ts b/packages/coding-agent/test/daemon-mode.test.tsindex 7c15f5b55a..90a685efdb 100644--- a/packages/coding-agent/test/daemon-mode.test.ts+++ b/packages/coding-agent/test/daemon-mode.test.ts@@ -1,11 +1,12 @@import { EventEmitter } from "node:events";-import { appendFileSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";import type { Socket } from "node:net";import { tmpdir } from "node:os";import { join, resolve } from "node:path";import type { Api, Model } from "@earendil-works/pi-ai";import { describe, expect, it, vi } from "vitest";import type { AgentSessionMessageController } from "../src/core/agent-messages.js";+import type { AgentObserveController } from "../src/core/agent-observe.js";import type { CreateAgentSessionRuntimeFactory } from "../src/core/agent-session-runtime.js";import { installAgentTraceUpload } from "../src/core/agent-traces.js";import { AuthStorage } from "../src/core/auth-storage.js";@@ -15,7 +16,7 @@ import {createDefaultRlmSubagentSessionName,type SubagentRuntimeHost,} from "../src/core/rlm-runtime.js";-import { SessionManager } from "../src/core/session-manager.js";+import { readSessionInfo, type SessionInfo, SessionManager } from "../src/core/session-manager.js";import { SettingsManager } from "../src/core/settings-manager.js";import type { ActiveSessionState, DaemonSocketClient } from "../src/modes/daemon/active-session-state.js";import {@@ -33,6 +34,7 @@ import {type DaemonAttachResult,type DaemonCommand,} from "../src/modes/daemon/daemon-protocol.js";+import type { SessionSummary } from "../src/modes/daemon/daemon-session-list.js";describe("daemon mode helpers", () => {it("preserves envelope client identity while registering prompt admission", () => {@@ -239,9 +241,9 @@ describe("daemon mode helpers", () => {internals.sessions.set(subagentState.activeSessionId, subagentState);const controller = internals.createAgentMessageController(() => parentState);- const subagentSummary = controller- .listAgents()- .agents.find((agent) => agent.activeSessionId === subagentState.activeSessionId);+ const subagentSummary = (await controller.listAgents()).agents.find(+ (agent) => agent.activeSessionId === subagentState.activeSessionId,+ );expect(subagentSummary).toMatchObject({sessionName: defaultSubagentName,runtimeKind: "subagent",@@ -768,7 +770,7 @@ describe("daemon mode helpers", () => {internals.closingSessions.set(childState.activeSessionId, Promise.resolve());const controller = internals.createAgentMessageController(() => parentState);- const listed = controller.listAgents();+ const listed = await controller.listAgents();expect(listed.agents).not.toContainEqual(expect.objectContaining({ activeSessionId: childState.activeSessionId }),);@@ -880,7 +882,9 @@ describe("daemon mode helpers", () => {const internals = daemon as unknown as {sessions: Map<string, ActiveSessionState>;remoteAgentPeers: Map<string, Record<string, unknown>>;- createAgentMessageListResult(current: ActiveSessionState): { agents: Array<{ activeSessionId: string }> };+ createAgentMessageListResult(+ current: ActiveSessionState,+ ): Promise<{ agents: Array<{ activeSessionId: string }> }>;sendRemoteAgentSessionMessage: typeof sendRemoteAgentSessionMessage;sendAgentSessionMessage(options: {targetSelector: string;@@ -901,7 +905,7 @@ describe("daemon mode helpers", () => {});internals.sendRemoteAgentSessionMessage = sendRemoteAgentSessionMessage;- expect(internals.createAgentMessageListResult(source).agents).toContainEqual(+ expect((await internals.createAgentMessageListResult(source)).agents).toContainEqual(expect.objectContaining({ activeSessionId: remoteSelector }),);await expect(@@ -1633,7 +1637,7 @@ describe("daemon mode helpers", () => {expect(acceptAgentMessagePrompt).not.toHaveBeenCalled();});- it("reports accepted in-flight agent messages in agent-message lists", () => {+ it("reports accepted in-flight agent messages in agent-message lists", async () => {const daemon = new AgentDaemon("/tmp/prime-agent-test.sock", {defaultSessionConfig: { agentDir: "/tmp/prime-agent-test-agent", cwd: "/tmp" },createRuntime: async () => {@@ -1654,13 +1658,13 @@ describe("daemon mode helpers", () => {} as never;const internals = daemon as unknown as {sessions: Map<string, ActiveSessionState>;- createAgentMessageListResult(current: ActiveSessionState): {+ createAgentMessageListResult(current: ActiveSessionState): Promise<{agents: Array<{ unfinishedActionCount: number }>;- };+ }>;};internals.sessions.set(targetState.activeSessionId, targetState);- expect(internals.createAgentMessageListResult(targetState).agents[0]?.unfinishedActionCount).toBe(3);+ expect((await internals.createAgentMessageListResult(targetState)).agents[0]?.unfinishedActionCount).toBe(3);});it("reports non-streaming busy sessions as active in agent-observe summaries", () => {@@ -3300,7 +3304,7 @@ describe("daemon mode helpers", () => {const createRuntime = vi.fn(async (options: Parameters<CreateAgentSessionRuntimeFactory>[0]) => {const session = makeRuntimeSession(options.sessionManager);session.bindExtensions = vi.fn(async () => {- const result = options.sessionOptions?.agentMessageController?.listAgents();+ const result = await options.sessionOptions?.agentMessageController?.listAgents();expect(result?.current?.activeSessionId).toBeTruthy();listedAgentsDuringBind++;});@@ -3420,43 +3424,102 @@ describe("daemon mode helpers", () => {}});- it("cancels a detached subagent heartbeat when its parent is archived", async () => {- const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-daemon-archived-subagent-heartbeat-"));+ it("replaces a resident top-level RLM child when restoring its heartbeat", async () => {+ const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-daemon-replace-child-heartbeat-"));+ try {+ const fixture = makePersistedRlmDaemonFixture(tempDir);+ const parentManager = SessionManager.open(fixture.parentSessionFile);+ parentManager.appendSessionState({ status: "active" });+ const internals = fixture.daemon as unknown as {+ cronStore: AgentCronJobStore;+ createRuntime(command: Extract<DaemonCommand, { type: "create" }>): Promise<ActiveSessionState>;+ getOrCreateCronJobSession(+ job: AgentCronJob,+ requirePersistedJob: boolean,+ ): Promise<ActiveSessionState | undefined>;+ };+ const topLevelState = await internals.createRuntime({+ type: "create",+ sessionPath: fixture.childSessionFile,+ });+ expect(topLevelState.runtime.metadata.kind).toBe("top-level");+ const topLevelAbort = topLevelState.runtime.session.abort as ReturnType<typeof vi.fn>;+ const heartbeat = internals.cronStore.createRlmHeartbeat({+ activeSessionId: "stale-child-active-id",+ sessionId: topLevelState.runtime.session.sessionId,+ sessionFile: fixture.childSessionFile,+ cwd: tempDir,+ runtimeKind: "subagent",+ scheduleText: "every 30s",+ prompt: "report exactly: hi",+ now: new Date("2026-01-01T00:00:00.000Z"),+ });++ const childState = await internals.getOrCreateCronJobSession(heartbeat, true);++ expect(childState).toBeDefined();+ expect(childState).not.toBe(topLevelState);+ expect(childState?.runtime.metadata).toMatchObject({+ kind: "subagent",+ rlmChildId: fixture.childId,+ });+ expect(topLevelAbort).toHaveBeenCalledOnce();+ expect(internals.cronStore.list().find((job) => job.id === heartbeat.id)).toMatchObject({+ status: "active",+ activeSessionId: childState?.activeSessionId,+ });+ } finally {+ rmSync(tempDir, { recursive: true, force: true });+ }+ });++ it("cancels an RLM heartbeat for a resident top-level session that is not a registered child", async () => {+ const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-daemon-nonchild-heartbeat-"));try {const sessionDir = join(tempDir, "sessions");const parentManager = SessionManager.create(tempDir, sessionDir);parentManager.newSession();- parentManager.appendSessionState({ status: "archived" });+ parentManager.appendSessionState({ status: "active" });const parentSessionFile = parentManager.getSessionFile();const parentArtifactDir = parentManager.getSessionArtifactDir();if (!parentSessionFile || !parentArtifactDir) {throw new Error("Missing parent session paths");}- const childManager = SessionManager.create(tempDir, join(parentArtifactDir, "child-1"));- childManager.newSession({ parentSession: parentSessionFile });- const childSessionFile = childManager.getSessionFile();- if (!childSessionFile) {- throw new Error("Missing child session file");+ const sessionManager = SessionManager.create(tempDir, join(parentArtifactDir, "unregistered-child"));+ sessionManager.newSession({ parentSession: parentSessionFile });+ sessionManager.appendSessionState({ status: "active" });+ const sessionFile = sessionManager.getSessionFile();+ if (!sessionFile) {+ throw new Error("Missing session file");}-- const createRuntime = vi.fn(async () => {- throw new Error("archived parent must not be restored");- });+ const createRuntime = vi.fn(async (options: Parameters<CreateAgentSessionRuntimeFactory>[0]) => ({+ session: makeRuntimeSession(options.sessionManager),+ extensionsResult: { extensions: [], errors: [], runtime: {} } as unknown as Awaited<+ ReturnType<CreateAgentSessionRuntimeFactory>+ >["extensionsResult"],+ services: { cwd: options.cwd, agentDir: options.agentDir } as Awaited<+ ReturnType<CreateAgentSessionRuntimeFactory>+ >["services"],+ diagnostics: [],+ }));const daemon = new AgentDaemon(join(tempDir, "daemon.sock"), {defaultSessionConfig: { agentDir: tempDir, cwd: tempDir, sessionDir },createRuntime,});const internals = daemon as unknown as {cronStore: AgentCronJobStore;+ createRuntime(command: Extract<DaemonCommand, { type: "create" }>): Promise<ActiveSessionState>;getOrCreateCronJobSession(job: AgentCronJob,requirePersistedJob: boolean,): Promise<ActiveSessionState | undefined>;};+ const topLevelState = await internals.createRuntime({ type: "create", sessionPath: sessionFile });+ const abort = topLevelState.runtime.session.abort as ReturnType<typeof vi.fn>;const heartbeat = internals.cronStore.createRlmHeartbeat({- activeSessionId: "stale-child-active-id",- sessionId: childManager.getSessionId(),- sessionFile: childSessionFile,+ activeSessionId: topLevelState.activeSessionId,+ sessionId: sessionManager.getSessionId(),+ sessionFile,cwd: tempDir,runtimeKind: "subagent",scheduleText: "every 30s",@@ -3465,473 +3528,586 @@ describe("daemon mode helpers", () => {});await expect(internals.getOrCreateCronJobSession(heartbeat, true)).resolves.toBeUndefined();- expect(createRuntime).not.toHaveBeenCalled();+ expect(abort).not.toHaveBeenCalled();expect(internals.cronStore.list().find((job) => job.id === heartbeat.id)).toMatchObject({status: "cancelled",});+ expect(createRuntime).toHaveBeenCalledTimes(2);+ expect(createRuntime.mock.calls[1]?.[0].sessionManager.getSessionFile()).toBe(parentSessionFile);} finally {rmSync(tempDir, { recursive: true, force: true });}});- it("rehydrates completed RLM subagents into the parent registry and durably deletes them", async () => {- const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-daemon-rlm-rehydrate-"));+ it("cancels a detached subagent heartbeat when its parent is archived", async () => {+ const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-daemon-archived-subagent-heartbeat-"));try {const sessionDir = join(tempDir, "sessions");const parentManager = SessionManager.create(tempDir, sessionDir);parentManager.newSession();- parentManager.appendSessionInfo("Parent");+ parentManager.appendSessionState({ status: "archived" });const parentSessionFile = parentManager.getSessionFile();const parentArtifactDir = parentManager.getSessionArtifactDir();if (!parentSessionFile || !parentArtifactDir) {throw new Error("Missing parent session paths");}-- const childId = "child-1";- const childSessionDir = join(parentArtifactDir, childId);- const childManager = SessionManager.create(tempDir, childSessionDir);+ const childManager = SessionManager.create(tempDir, join(parentArtifactDir, "child-1"));childManager.newSession({ parentSession: parentSessionFile });- childManager.appendSessionInfo("spawn-worker");- childManager.appendSessionInfo("renamed-worker");const childSessionFile = childManager.getSessionFile();- const childArtifactDir = childManager.getSessionArtifactDir();- if (!childSessionFile || !childArtifactDir) {- throw new Error("Missing child session paths");- }- const grandchildId = "grandchild-1";- const grandchildSessionDir = join(childArtifactDir, grandchildId);- const grandchildManager = SessionManager.create(tempDir, grandchildSessionDir);- grandchildManager.newSession({ parentSession: childSessionFile });- grandchildManager.appendSessionInfo("nested-worker");- const grandchildSessionFile = grandchildManager.getSessionFile();- if (!grandchildSessionFile) {- throw new Error("Missing grandchild session file");+ if (!childSessionFile) {+ throw new Error("Missing child session file");}- writeFileSync(- join(childArtifactDir, "rlm-subagents.jsonl"),- `${JSON.stringify({- type: "rlm_subagent",- childId: grandchildId,- sessionName: "nested-worker",- sessionDir: grandchildSessionDir,- sessionFile: grandchildSessionFile,- parentSessionId: childManager.getSessionId(),- parentSessionFile: childSessionFile,- rlmDepth: 2,- rlmMaxDepth: 4,- rlmParentNodeId: grandchildId,- status: "completed",- createdAt: 2,- updatedAt: "2026-01-01T00:00:00.000Z",- })}\n${JSON.stringify({- type: "rlm_subagent",- childId: "cycle-to-root",- sessionName: "cycle-to-root",- sessionDir: parentArtifactDir,- sessionFile: parentSessionFile,- parentSessionId: childManager.getSessionId(),- parentSessionFile: childSessionFile,- rlmDepth: 2,- rlmMaxDepth: 4,- rlmParentNodeId: "cycle-to-root",- status: "completed",- createdAt: 3,- updatedAt: "2026-01-01T00:00:00.000Z",- })}\n`,- );- writeFileSync(- join(parentArtifactDir, "rlm-subagents.jsonl"),- `${JSON.stringify({- type: "rlm_subagent",- childId,- sessionName: "spawn-worker",- sessionDir: childSessionDir,- sessionFile: childSessionFile,- parentSessionId: parentManager.getSessionId(),- parentSessionFile,- rlmDepth: 1,- rlmMaxDepth: 4,- rlmParentNodeId: childId,- status: "completed",- createdAt: 1,- updatedAt: "2026-01-01T00:00:00.000Z",- })}\n`,- );- const createRuntime = vi.fn(async (options: Parameters<CreateAgentSessionRuntimeFactory>[0]) => {- return {- session: makeRuntimeSession(options.sessionManager),- extensionsResult: { extensions: [], errors: [], runtime: {} } as unknown as Awaited<- ReturnType<CreateAgentSessionRuntimeFactory>- >["extensionsResult"],- services: { cwd: options.cwd, agentDir: options.agentDir } as Awaited<- ReturnType<CreateAgentSessionRuntimeFactory>- >["services"],- diagnostics: [],- };+ const createRuntime = vi.fn(async () => {+ throw new Error("archived parent must not be restored");});const daemon = new AgentDaemon(join(tempDir, "daemon.sock"), {defaultSessionConfig: { agentDir: tempDir, cwd: tempDir, sessionDir },createRuntime,});const internals = daemon as unknown as {+ cronStore: AgentCronJobStore;+ getOrCreateCronJobSession(+ job: AgentCronJob,+ requirePersistedJob: boolean,+ ): Promise<ActiveSessionState | undefined>;+ };+ const heartbeat = internals.cronStore.createRlmHeartbeat({+ activeSessionId: "stale-child-active-id",+ sessionId: childManager.getSessionId(),+ sessionFile: childSessionFile,+ cwd: tempDir,+ runtimeKind: "subagent",+ scheduleText: "every 30s",+ prompt: "report exactly: hi",+ now: new Date("2026-01-01T00:00:00.000Z"),+ });++ await expect(internals.getOrCreateCronJobSession(heartbeat, true)).resolves.toBeUndefined();+ expect(createRuntime).not.toHaveBeenCalled();+ expect(internals.cronStore.list().find((job) => job.id === heartbeat.id)).toMatchObject({+ status: "cancelled",+ });+ } finally {+ rmSync(tempDir, { recursive: true, force: true });+ }+ });++ it("reopens a parent with completed children without creating child runtimes and lists them as passive", async () => {+ const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-daemon-lazy-rlm-list-"));+ try {+ const fixture = makePersistedRlmDaemonFixture(tempDir);+ const internals = fixture.daemon as unknown as {sessions: Map<string, ActiveSessionState>;createRuntime(command: Extract<DaemonCommand, { type: "create" }>): Promise<ActiveSessionState>;- createSubagentRuntimeHost(parent: ActiveSessionState): {- deleteRlmSubagentRuntime(- childId: string,- session: ActiveSessionState["runtime"]["session"],- ): Promise<void>;- };- rehydrateCompletedRlmSubagents(parent: ActiveSessionState): Promise<void>;- closeSession(state: ActiveSessionState, reason: "killed", waitForAbort?: boolean): Promise<void>;+ createAgentMessageController(+ getCurrentState: () => ActiveSessionState | undefined,+ ): AgentSessionMessageController;+ handleCommand(client: DaemonSocketClient, command: DaemonCommand): Promise<unknown>;};- const parentState = await internals.createRuntime({ type: "create", sessionPath: parentSessionFile });- const childState = [...internals.sessions.values()].find(- (state) => state.runtime.metadata.rlmChildId === childId,+ const parentState = await internals.createRuntime({+ type: "create",+ sessionPath: fixture.parentSessionFile,+ });++ expect(fixture.createRuntime).toHaveBeenCalledOnce();+ expect([...internals.sessions.values()]).toEqual([parentState]);+ expect((await internals.createAgentMessageController(() => parentState).listAgents()).agents).toContainEqual(+ expect.objectContaining({+ activeSessionId: expect.any(String),+ sessionId: expect.any(String),+ sessionName: "renamed-worker",+ runtimeKind: "subagent",+ parentActiveSessionId: parentState.activeSessionId,+ rlmChildId: fixture.childId,+ }),);- const grandchildState = [...internals.sessions.values()].find(- (state) => state.runtime.metadata.rlmChildId === grandchildId,+ expect((await internals.createAgentMessageController(() => parentState).listAgents()).agents).toContainEqual(+ expect.objectContaining({+ activeSessionId: expect.any(String),+ sessionName: "nested-worker",+ rlmChildId: fixture.grandchildId,+ }),);-- expect(createRuntime).toHaveBeenCalledTimes(3);- expect(createRuntime.mock.calls[1]?.[0].sessionOptions).toMatchObject({- rlmDepth: 1,- rlmMaxDepth: 4,- });- expect(createRuntime.mock.calls[2]?.[0].sessionOptions).toMatchObject({- rlmDepth: 2,- rlmMaxDepth: 4,- });- expect(childState?.runtime.session.sessionName).toBe("renamed-worker");- expect(childState?.runtime.metadata).toMatchObject({- kind: "subagent",+ const listResponse = (await internals.handleCommand(makeClient("client-1", parentState.activeSessionId), {+ type: "list",+ all: true,+ })) as { data: { sessions: Array<Record<string, unknown>> } };+ const passiveRow = listResponse.data.sessions.find(+ (session) => session.sessionFile === fixture.childSessionFile,+ );+ expect(passiveRow).toMatchObject({+ lifecycle: "live",+ sessionName: "renamed-worker",+ runtimeKind: "subagent",parentActiveSessionId: parentState.activeSessionId,- parentSessionId: parentState.runtime.session.sessionId,- rlmChildId: childId,- rlmParentNodeId: childId,- sessionDir: childSessionDir,+ rlmChildId: fixture.childId,+ parentSessionPath: fixture.parentSessionFile,});- expect(parentState.runtime.session.retainFinishedRlmChildSession).toHaveBeenCalledWith(- childId,- childState?.runtime.session,+ expect(passiveRow?.activeSessionId).toBeUndefined();+ const nestedRow = listResponse.data.sessions.find(+ (session) => session.sessionFile === fixture.grandchildSessionFile,);- expect(grandchildState?.runtime.metadata).toMatchObject({- kind: "subagent",- parentActiveSessionId: childState?.activeSessionId,- parentSessionId: childState?.runtime.session.sessionId,- rlmChildId: grandchildId,+ expect(nestedRow).toMatchObject({+ sessionName: "nested-worker",+ runtimeKind: "subagent",+ rlmChildId: fixture.grandchildId,+ parentSessionPath: fixture.childSessionFile,});- expect(childState?.runtime.session.retainFinishedRlmChildSession).toHaveBeenCalledWith(- grandchildId,- grandchildState?.runtime.session,++ const activeOnlyResponse = (await internals.handleCommand(+ makeClient("client-2", parentState.activeSessionId),+ { type: "list" },+ )) as { data: { sessions: Array<Record<string, unknown>> } };+ expect(activeOnlyResponse.data.sessions).toEqual(+ expect.arrayContaining([+ expect.objectContaining({ sessionFile: fixture.childSessionFile, rlmChildId: fixture.childId }),+ expect.objectContaining({+ sessionFile: fixture.grandchildSessionFile,+ rlmChildId: fixture.grandchildId,+ parentSessionPath: fixture.childSessionFile,+ }),+ ]),);- expect(- [...internals.sessions.values()].some((state) => state.runtime.metadata.rlmChildId === "cycle-to-root"),- ).toBe(false);+ } finally {+ rmSync(tempDir, { recursive: true, force: true });+ }+ });- if (!childState) {- throw new Error("Missing rehydrated child state");- }- appendFileSync(join(parentArtifactDir, "rlm-subagents.jsonl"), "{unterminated malformed registry line");- internals.closeSession = vi.fn(async (state: ActiveSessionState) => {- internals.sessions.delete(state.activeSessionId);+ it("lists passive descendants under a nonresident saved root", async () => {+ const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-daemon-lazy-rlm-nonresident-root-"));+ try {+ const fixture = makePersistedRlmDaemonFixture(tempDir);+ const parentManager = SessionManager.open(fixture.parentSessionFile);+ parentManager.appendMessage({ role: "user", content: "parent task", timestamp: 0 });+ parentManager.flushNow();+ const parentInfo = await readSessionInfo(fixture.parentSessionFile);+ if (!parentInfo) throw new Error("Missing parent session info");+ const internals = fixture.daemon as unknown as {+ sessions: Map<string, ActiveSessionState>;+ buildSessionListWithPassiveRlmSubagents(+ activeSessions: ActiveSessionState[],+ savedSessions: SessionInfo[],+ scheduledJobs: AgentCronJob[],+ ): Promise<SessionSummary[]>;+ };++ expect(internals.sessions.size).toBe(0);+ const sessions = await internals.buildSessionListWithPassiveRlmSubagents([], [parentInfo], []);+ const child = sessions.find((session) => session.sessionFile === fixture.childSessionFile);+ expect(child).toMatchObject({+ runtimeKind: "subagent",+ parentSessionId: fixture.parentSessionId,+ parentSessionPath: fixture.parentSessionFile,+ rlmChildId: fixture.childId,+ rlmDepth: 1,});- await internals- .createSubagentRuntimeHost(parentState)- .deleteRlmSubagentRuntime(childId, childState.runtime.session);- expect(internals.sessions.has(childState.activeSessionId)).toBe(false);- const persistedLines = readFileSync(join(parentArtifactDir, "rlm-subagents.jsonl"), "utf8")- .trim()- .split(/\r?\n/);- const persistedDeletion = JSON.parse(persistedLines.at(-1) ?? "") as { childId: string; status: string };- expect(persistedDeletion).toMatchObject({ childId, status: "deleted" });-- await internals.rehydrateCompletedRlmSubagents(parentState);- expect(createRuntime).toHaveBeenCalledTimes(3);- expect([...internals.sessions.values()].some((state) => state.runtime.metadata.rlmChildId === childId)).toBe(- false,- );+ expect(child?.parentActiveSessionId).toBeUndefined();++ const grandchild = sessions.find((session) => session.sessionFile === fixture.grandchildSessionFile);+ expect(grandchild).toMatchObject({+ runtimeKind: "subagent",+ parentSessionPath: fixture.childSessionFile,+ rlmChildId: fixture.grandchildId,+ rlmDepth: 2,+ });+ expect(grandchild?.parentActiveSessionId).toBeUndefined();+ expect(fixture.createRuntime).not.toHaveBeenCalled();} finally {rmSync(tempDir, { recursive: true, force: true });}});- it("coalesces retained rehydration with successful and failed explicit session opens", async () => {- const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-daemon-rehydrate-open-race-"));+ it("ignores a crashed registry tail and protects a nested cycle back to the root", async () => {+ const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-daemon-lazy-rlm-corrupt-registry-"));try {- const sessionDir = join(tempDir, "sessions");- const parentManager = SessionManager.create(tempDir, sessionDir);- parentManager.newSession();- const parentArtifactDir = parentManager.getSessionArtifactDir();- const parentSessionFile = parentManager.getSessionFile();- if (!parentArtifactDir || !parentSessionFile) {- throw new Error("Missing parent session paths");- }- const childId = "racing-child";- const childSessionDir = join(parentArtifactDir, childId);- const childManager = SessionManager.create(tempDir, childSessionDir);- childManager.newSession({ parentSession: parentSessionFile });- childManager.appendSessionInfo("racing-worker");- const childSessionFile = childManager.getSessionFile();- if (!childSessionFile) {- throw new Error("Missing child session file");- }- mkdirSync(parentArtifactDir, { recursive: true });+ const fixture = makePersistedRlmDaemonFixture(tempDir);+ const parentRegistry = join(fixture.parentArtifactDir, "rlm-subagents.jsonl");+ writeFileSync(parentRegistry, `${readFileSync(parentRegistry, "utf8")}{"type":"rlm_subagent","childId":`);++ const childInfo = await readSessionInfo(fixture.childSessionFile);+ if (!childInfo) throw new Error("Missing child session info");+ const childRegistry = join(+ fixture.parentArtifactDir,+ "session-artifacts",+ childInfo.id,+ "rlm-subagents.jsonl",+ );writeFileSync(- join(parentArtifactDir, "rlm-subagents.jsonl"),- `${JSON.stringify({+ childRegistry,+ `${readFileSync(childRegistry, "utf8")}${JSON.stringify({type: "rlm_subagent",- childId,- sessionName: "racing-worker",- sessionDir: childSessionDir,- sessionFile: childSessionFile,- parentSessionId: parentManager.getSessionId(),- parentSessionFile,- rlmDepth: 1,- rlmMaxDepth: 4,- rlmParentNodeId: childId,+ childId: "cycle-to-root",+ sessionName: "cycle-to-root",+ sessionDir: join(tempDir, "sessions"),+ sessionFile: fixture.parentSessionFile,+ parentSessionId: childInfo.id,+ parentSessionFile: fixture.childSessionFile,status: "completed",- createdAt: 1,- updatedAt: "2026-01-01T00:00:00.000Z",- })}\n`,+ createdAt: 3,+ updatedAt: "2026-01-01T00:00:02.000Z",+ })}+`,);- let bindStarted = false;- let releaseBind: () => void = () => {};- const bindGate = new Promise<void>((resolve) => {- releaseBind = resolve;- });- let successfulBindStarted = false;- let releaseSuccessfulBind: () => void = () => {};- const successfulBindGate = new Promise<void>((resolve) => {- releaseSuccessfulBind = resolve;- });- const createRuntime = vi.fn(async (options: Parameters<CreateAgentSessionRuntimeFactory>[0]) => {- const session = makeRuntimeSession(options.sessionManager);- const runtimeNumber = createRuntime.mock.calls.length;- session.bindExtensions = vi.fn(async () => {- if (runtimeNumber === 1) {- bindStarted = true;- await bindGate;- throw new Error("explicit bind failed");- }- if (runtimeNumber === 3) {- successfulBindStarted = true;- await successfulBindGate;- }- });- return {- session,- extensionsResult: { extensions: [], errors: [], runtime: {} } as unknown as Awaited<- ReturnType<CreateAgentSessionRuntimeFactory>- >["extensionsResult"],- services: { cwd: options.cwd, agentDir: options.agentDir } as Awaited<- ReturnType<CreateAgentSessionRuntimeFactory>- >["services"],- diagnostics: [],- };- });- const daemon = new AgentDaemon(join(tempDir, "daemon.sock"), {- defaultSessionConfig: { agentDir: tempDir, cwd: tempDir, sessionDir },- createRuntime,- });- const internals = daemon as unknown as {- sessions: Map<string, ActiveSessionState>;+ const internals = fixture.daemon as unknown as {createRuntime(command: Extract<DaemonCommand, { type: "create" }>): Promise<ActiveSessionState>;- rehydrateCompletedRlmSubagents(parent: ActiveSessionState): Promise<void>;+ handleCommand(client: DaemonSocketClient, command: DaemonCommand): Promise<unknown>;};- const parentState = makeState("parent");- parentState.runtime = {- ...parentState.runtime,- metadata: { kind: "top-level", createdAt: 1 },- runtimeConfig: {},- services: { cwd: tempDir, agentDir: tempDir },- session: makeRuntimeSession(parentManager),- } as unknown as ActiveSessionState["runtime"];- internals.sessions.set(parentState.activeSessionId, parentState);+ const parentState = await internals.createRuntime({ type: "create", sessionPath: fixture.parentSessionFile });+ const response = (await internals.handleCommand(makeClient("client-1", parentState.activeSessionId), {+ type: "list",+ })) as { data: { sessions: Array<{ rlmChildId?: string }> } };++ expect(response.data.sessions.map((session) => session.rlmChildId).filter(Boolean)).toEqual([+ fixture.childId,+ fixture.grandchildId,+ ]);+ expect(fixture.createRuntime).toHaveBeenCalledOnce();+ } finally {+ rmSync(tempDir, { recursive: true, force: true });+ }+ });- const explicitOpen = internals.createRuntime({ type: "create", sessionPath: childSessionFile });- const explicitFailure = explicitOpen.catch((error: unknown) => error);- for (let attempt = 0; attempt < 50 && !bindStarted; attempt++) {- await new Promise((resolve) => setTimeout(resolve, 1));- }- expect(bindStarted).toBe(true);- const rehydrate = internals.rehydrateCompletedRlmSubagents(parentState);- releaseBind();- const [explicitError] = await Promise.all([explicitFailure, rehydrate]);+ it("hydrates a passive child on agent message and delivers to it", async () => {+ const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-daemon-lazy-rlm-message-"));+ try {+ const fixture = makePersistedRlmDaemonFixture(tempDir);+ const internals = fixture.daemon as unknown as {+ sessions: Map<string, ActiveSessionState>;+ createRuntime(command: Extract<DaemonCommand, { type: "create" }>): Promise<ActiveSessionState>;+ createAgentMessageController(+ getCurrentState: () => ActiveSessionState | undefined,+ ): AgentSessionMessageController;+ };+ const parentState = await internals.createRuntime({+ type: "create",+ sessionPath: fixture.parentSessionFile,+ });- expect(explicitError).toEqual(expect.objectContaining({ message: "explicit bind failed" }));- expect(createRuntime).toHaveBeenCalledTimes(2);+ await expect(+ internals+ .createAgentMessageController(() => parentState)+ .sendAgentMessage({+ target: "renamed-worker",+ message: "report progress",+ }),+ ).resolves.toMatchObject({+ deliveryStatus: "delivered",+ target: { runtimeKind: "subagent", sessionName: "renamed-worker" },+ });+ expect(fixture.createRuntime).toHaveBeenCalledTimes(2);+ expect(fixture.acceptAgentMessagePrompt).toHaveBeenCalledOnce();expect(- [...internals.sessions.values()].filter(- (state) =>- state.runtime.session.sessionFile &&- resolve(state.runtime.session.sessionFile) === resolve(childSessionFile),- ),+ [...internals.sessions.values()].filter((state) => state.runtime.metadata.kind === "subagent"),).toHaveLength(1);- const rehydrated = [...internals.sessions.values()].find(- (state) => state.runtime.metadata.rlmChildId === childId,- );- expect(rehydrated).toBeDefined();- expect(parentState.runtime.session.retainFinishedRlmChildSession).toHaveBeenCalledWith(- childId,- rehydrated?.runtime.session,- );+ } finally {+ rmSync(tempDir, { recursive: true, force: true });+ }+ });- const siblingId = "successful-racing-child";- const siblingSessionDir = join(parentArtifactDir, siblingId);+ it("does not match a renamed passive child by its stale registry name", async () => {+ const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-daemon-lazy-rlm-renamed-"));+ try {+ const fixture = makePersistedRlmDaemonFixture(tempDir);+ const siblingId = "child-2";+ const siblingSessionDir = join(fixture.parentArtifactDir, siblingId);const siblingManager = SessionManager.create(tempDir, siblingSessionDir);- siblingManager.newSession({ parentSession: parentSessionFile });- siblingManager.appendSessionInfo("successful-racing-worker");+ siblingManager.newSession({ parentSession: fixture.parentSessionFile });+ siblingManager.appendSessionInfo("spawn-worker");+ siblingManager.flushNow();const siblingSessionFile = siblingManager.getSessionFile();- if (!siblingSessionFile) {- throw new Error("Missing sibling session file");- }- const siblingArtifactDir = siblingManager.getSessionArtifactDir();- if (!siblingArtifactDir) {- throw new Error("Missing sibling artifact directory");- }- mkdirSync(siblingArtifactDir, { recursive: true });+ if (!siblingSessionFile) throw new Error("Missing sibling session file");+ const parentRegistry = join(fixture.parentArtifactDir, "rlm-subagents.jsonl");writeFileSync(- join(siblingArtifactDir, "rlm-subagents.jsonl"),- `${JSON.stringify({- type: "rlm_subagent",- childId: "cycle-to-root",- sessionName: "cycle-to-root",- sessionDir,- sessionFile: parentSessionFile,- parentSessionId: siblingManager.getSessionId(),- parentSessionFile: siblingSessionFile,- rlmDepth: 0,- rlmMaxDepth: 4,- rlmParentNodeId: "cycle-to-root",- status: "completed",- createdAt: 2,- updatedAt: "2026-01-01T00:00:01.000Z",- })}\n`,- );- appendFileSync(- join(parentArtifactDir, "rlm-subagents.jsonl"),- `${JSON.stringify({+ parentRegistry,+ `${readFileSync(parentRegistry, "utf8")}${JSON.stringify({type: "rlm_subagent",childId: siblingId,- sessionName: "successful-racing-worker",+ sessionName: "spawn-worker",sessionDir: siblingSessionDir,sessionFile: siblingSessionFile,- parentSessionId: parentManager.getSessionId(),- parentSessionFile,- rlmDepth: 1,- rlmMaxDepth: 4,- rlmParentNodeId: siblingId,+ parentSessionId: fixture.parentSessionId,+ parentSessionFile: fixture.parentSessionFile,status: "completed",createdAt: 2,updatedAt: "2026-01-01T00:00:01.000Z",})}\n`,);- const successfulExplicitOpen = internals.createRuntime({+ const internals = fixture.daemon as unknown as {+ createRuntime(command: Extract<DaemonCommand, { type: "create" }>): Promise<ActiveSessionState>;+ createAgentMessageController(+ getCurrentState: () => ActiveSessionState | undefined,+ ): AgentSessionMessageController;+ };+ const parentState = await internals.createRuntime({type: "create",- sessionPath: siblingSessionFile,+ sessionPath: fixture.parentSessionFile,});- for (let attempt = 0; attempt < 50 && !successfulBindStarted; attempt++) {- await new Promise((resolve) => setTimeout(resolve, 1));- }- expect(successfulBindStarted).toBe(true);- const successfulRehydrate = internals.rehydrateCompletedRlmSubagents(parentState);- releaseSuccessfulBind();- const [successfulState] = await Promise.all([successfulExplicitOpen, successfulRehydrate]);- expect(createRuntime).toHaveBeenCalledTimes(4);- expect(createRuntime.mock.calls[3]?.[0].sessionOptions).toEqual(- expect.objectContaining({- rlmSessionDir: siblingSessionDir,- rlmDepth: 1,- rlmMaxDepth: 4,- rlmParentNodeId: siblingId,- }),- );- expect(successfulState.runtime.metadata).toEqual(- expect.objectContaining({- kind: "subagent",- parentActiveSessionId: parentState.activeSessionId,- rlmChildId: siblingId,- }),- );- expect(internals.sessions.has(successfulState.activeSessionId)).toBe(true);- expect(parentState.runtime.session.retainFinishedRlmChildSession).toHaveBeenCalledWith(- siblingId,- successfulState.runtime.session,- );- expect(successfulState.runtime.session.retainFinishedRlmChildSession).not.toHaveBeenCalledWith(- "cycle-to-root",- expect.anything(),+ await expect(+ internals+ .createAgentMessageController(() => parentState)+ .sendAgentMessage({ target: "spawn-worker", message: "report progress" }),+ ).resolves.toMatchObject({+ deliveryStatus: "delivered",+ target: { runtimeKind: "subagent", sessionName: "spawn-worker" },+ });+ expect(fixture.createRuntime).toHaveBeenCalledTimes(2);+ expect(fixture.createRuntime.mock.calls[1]?.[0].sessionManager.getSessionFile()).toBe(siblingSessionFile);+ } finally {+ rmSync(tempDir, { recursive: true, force: true });+ }+ });++ it("hydrates only the ancestor chain when a nested passive child is messaged", async () => {+ const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-daemon-lazy-nested-message-"));+ try {+ const fixture = makePersistedRlmDaemonFixture(tempDir);+ const internals = fixture.daemon as unknown as {+ sessions: Map<string, ActiveSessionState>;+ createRuntime(command: Extract<DaemonCommand, { type: "create" }>): Promise<ActiveSessionState>;+ createAgentMessageController(+ getCurrentState: () => ActiveSessionState | undefined,+ ): AgentSessionMessageController;+ };+ const parentState = await internals.createRuntime({+ type: "create",+ sessionPath: fixture.parentSessionFile,+ });++ await internals+ .createAgentMessageController(() => parentState)+ .sendAgentMessage({+ target: "nested-worker",+ message: "report nested progress",+ });++ expect(fixture.createRuntime).toHaveBeenCalledTimes(3);+ expect([...internals.sessions.values()].map((state) => state.runtime.metadata.rlmChildId)).toEqual(+ expect.arrayContaining([fixture.childId, fixture.grandchildId]),);- expect(internals.sessions.get(parentState.activeSessionId)).toBe(parentState);+ } finally {+ rmSync(tempDir, { recursive: true, force: true });+ }+ });++ it("hydrates a passive child when agent_observe reads it", async () => {+ const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-daemon-lazy-rlm-observe-"));+ try {+ const fixture = makePersistedRlmDaemonFixture(tempDir);+ const internals = fixture.daemon as unknown as {+ createRuntime(command: Extract<DaemonCommand, { type: "create" }>): Promise<ActiveSessionState>;+ createAgentObserveController(getCurrentState: () => ActiveSessionState | undefined): AgentObserveController;+ };+ const parentState = await internals.createRuntime({+ type: "create",+ sessionPath: fixture.parentSessionFile,+ });+ const controller = internals.createAgentObserveController(() => parentState);++ await expect(controller.getAgent("renamed-worker")).resolves.toMatchObject({+ agent: { runtimeKind: "subagent", sessionName: "renamed-worker" },+ });+ await expect(controller.recentMessages({ target: "renamed-worker" })).resolves.toMatchObject({+ agent: { runtimeKind: "subagent" },+ messages: [],+ });+ expect(fixture.createRuntime).toHaveBeenCalledTimes(2);+ } finally {+ rmSync(tempDir, { recursive: true, force: true });+ }+ });++ it("waits for an explicit open reservation before hydrating a passive child", async () => {+ const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-daemon-lazy-rlm-reservation-race-"));+ let releaseOpen!: () => void;+ const openGate = new Promise<void>((resolveGate) => {+ releaseOpen = resolveGate;+ });+ let markOpenStarted!: () => void;+ const openStarted = new Promise<void>((resolveStarted) => {+ markOpenStarted = resolveStarted;+ });+ const originalOpenAsync = SessionManager.openAsync;+ let openAsyncSpy: ReturnType<typeof vi.spyOn> | undefined;+ try {+ const fixture = makePersistedRlmDaemonFixture(tempDir);+ const internals = fixture.daemon as unknown as {+ reservingSessionOpens: Map<string, Promise<void>>;+ createRuntime(command: Extract<DaemonCommand, { type: "create" }>): Promise<ActiveSessionState>;+ findPassiveRlmSubagent(target: string): Promise<unknown>;+ hydratePassiveRlmSubagent(passive: unknown): Promise<ActiveSessionState>;+ };+ await internals.createRuntime({+ type: "create",+ sessionPath: fixture.parentSessionFile,+ });+ const findPassiveRlmSubagent = internals.findPassiveRlmSubagent.bind(fixture.daemon);+ const passive = await findPassiveRlmSubagent(fixture.childId);+ if (!passive) throw new Error("Missing passive child");+ internals.findPassiveRlmSubagent = vi.fn(async (target: string) => {+ if (resolve(target) === resolve(fixture.childSessionFile)) {+ return undefined;+ }+ return findPassiveRlmSubagent(target);+ });+ openAsyncSpy = vi+ .spyOn(SessionManager, "openAsync")+ .mockImplementation(async (path, sessionDir, cwdOverride) => {+ if (resolve(path) === resolve(fixture.childSessionFile)) {+ markOpenStarted();+ await openGate;+ }+ return originalOpenAsync(path, sessionDir, cwdOverride);+ });++ const explicitOpen = internals.createRuntime({ type: "create", sessionPath: fixture.childSessionFile });+ await openStarted;+ expect(internals.reservingSessionOpens.has(resolve(fixture.childSessionFile))).toBe(true);++ const hydration = internals.hydratePassiveRlmSubagent(passive);+ const joined = Promise.all([explicitOpen, hydration]);+ releaseOpen();++ const [openedState, hydratedState] = await joined;+ expect(hydratedState).toBe(openedState);+ expect(openedState.runtime.session.sessionFile).toBe(fixture.childSessionFile);+ expect(fixture.createRuntime).toHaveBeenCalledTimes(2);+ } finally {+ releaseOpen();+ openAsyncSpy?.mockRestore();+ rmSync(tempDir, { recursive: true, force: true });+ }+ });++ it("coalesces a gated hydration with concurrent messaging and an explicit open", async () => {+ const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-daemon-lazy-rlm-race-"));+ let releaseHydration!: () => void;+ const hydrationGate = new Promise<void>((resolveGate) => {+ releaseHydration = resolveGate;+ });+ let markHydrationStarted!: () => void;+ const hydrationStarted = new Promise<void>((resolveStarted) => {+ markHydrationStarted = resolveStarted;+ });+ try {+ const fixture = makePersistedRlmDaemonFixture(tempDir, {+ childRuntimeStarted: markHydrationStarted,+ childRuntimeGate: hydrationGate,+ });+ const internals = fixture.daemon as unknown as {+ sessions: Map<string, ActiveSessionState>;+ createRuntime(command: Extract<DaemonCommand, { type: "create" }>): Promise<ActiveSessionState>;+ createAgentMessageController(+ getCurrentState: () => ActiveSessionState | undefined,+ ): AgentSessionMessageController;+ };+ const parentState = await internals.createRuntime({+ type: "create",+ sessionPath: fixture.parentSessionFile,+ });+ const controller = internals.createAgentMessageController(() => parentState);++ const firstMessage = controller.sendAgentMessage({ target: fixture.childId, message: "first" });+ await hydrationStarted;+ const explicitOpen = internals.createRuntime({ type: "create", sessionPath: fixture.childSessionFile });+ const secondMessage = controller.sendAgentMessage({ target: fixture.childId, message: "second" });+ expect(fixture.createRuntime).toHaveBeenCalledTimes(2);++ releaseHydration();+ const [, openedState] = await Promise.all([firstMessage, explicitOpen, secondMessage]);++ expect(openedState.runtime.metadata).toMatchObject({ kind: "subagent", rlmChildId: fixture.childId });+ expect(fixture.createRuntime).toHaveBeenCalledTimes(2);expect(- [...internals.sessions.values()].filter(- (state) =>- state.runtime.session.sessionFile &&- resolve(state.runtime.session.sessionFile) === resolve(siblingSessionFile),- ),+ [...internals.sessions.values()].filter((state) => state.runtime.metadata.kind === "subagent"),).toHaveLength(1);+ expect(fixture.acceptAgentMessagePrompt).toHaveBeenCalledTimes(2);+ } finally {+ releaseHydration();+ rmSync(tempDir, { recursive: true, force: true });+ }+ });- const stableId = "stable-explicit-child";- const stableSessionDir = join(parentArtifactDir, stableId);- const stableManager = SessionManager.create(tempDir, stableSessionDir);- stableManager.newSession({ parentSession: parentSessionFile });- stableManager.appendSessionInfo("stable-explicit-worker");- const stableSessionFile = stableManager.getSessionFile();- if (!stableSessionFile) {- throw new Error("Missing stable explicit session file");- }- appendFileSync(- join(parentArtifactDir, "rlm-subagents.jsonl"),- `${JSON.stringify({- type: "rlm_subagent",- childId: stableId,- sessionName: "stable-explicit-worker",- sessionDir: stableSessionDir,- sessionFile: stableSessionFile,- parentSessionId: parentManager.getSessionId(),- parentSessionFile,- rlmDepth: 2,- rlmMaxDepth: 5,- rlmParentNodeId: stableId,- status: "completed",- createdAt: 3,- updatedAt: "2026-01-01T00:00:02.000Z",- })}\n`,- );- const stableState = await internals.createRuntime({ type: "create", sessionPath: stableSessionFile });- expect(stableState.runtime.metadata.kind).toBe("top-level");- await internals.rehydrateCompletedRlmSubagents(parentState);+ it("hydrates a passive child when it is opened from its saved-session row", async () => {+ const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-daemon-lazy-rlm-open-"));+ try {+ const fixture = makePersistedRlmDaemonFixture(tempDir);+ const internals = fixture.daemon as unknown as {+ createRuntime(command: Extract<DaemonCommand, { type: "create" }>): Promise<ActiveSessionState>;+ };+ await internals.createRuntime({ type: "create", sessionPath: fixture.parentSessionFile });- expect(createRuntime).toHaveBeenCalledTimes(6);- expect(createRuntime.mock.calls[5]?.[0].sessionOptions).toEqual(- expect.objectContaining({- rlmSessionDir: stableSessionDir,- rlmDepth: 2,- rlmMaxDepth: 5,- rlmParentNodeId: stableId,- }),- );- expect(stableState.runtime.metadata.kind).toBe("top-level");- expect(internals.sessions.has(stableState.activeSessionId)).toBe(false);- const restoredStableState = [...internals.sessions.values()].find(- (state) => state.runtime.metadata.rlmChildId === stableId,- );- expect(restoredStableState?.runtime.metadata).toEqual(- expect.objectContaining({- kind: "subagent",- parentActiveSessionId: parentState.activeSessionId,- rlmChildId: stableId,- }),- );- expect(parentState.runtime.session.retainFinishedRlmChildSession).toHaveBeenCalledWith(- stableId,- restoredStableState?.runtime.session,+ const childState = await internals.createRuntime({ type: "create", sessionPath: fixture.childSessionFile });++ expect(childState.runtime.metadata).toMatchObject({ kind: "subagent", rlmChildId: fixture.childId });+ expect(fixture.createRuntime).toHaveBeenCalledTimes(2);+ } finally {+ rmSync(tempDir, { recursive: true, force: true });+ }+ });++ it("keeps a passive child row id when attach hydrates it", async () => {+ const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-daemon-lazy-rlm-attach-"));+ try {+ const fixture = makePersistedRlmDaemonFixture(tempDir);+ const internals = fixture.daemon as unknown as {+ sessions: Map<string, ActiveSessionState>;+ createRuntime(command: Extract<DaemonCommand, { type: "create" }>): Promise<ActiveSessionState>;+ handleCommand(client: DaemonSocketClient, command: DaemonCommand): Promise<unknown>;+ };+ const parentState = await internals.createRuntime({+ type: "create",+ sessionPath: fixture.parentSessionFile,+ });+ const client = makeClient("client-1", parentState.activeSessionId);+ client.socket.write = vi.fn(() => true);+ const listResponse = (await internals.handleCommand(client, { type: "list" })) as {+ data: { sessions: SessionSummary[] };+ };+ const passiveRow = listResponse.data.sessions.find(+ (session) => session.sessionFile === fixture.childSessionFile,);+ if (!passiveRow) throw new Error("Missing passive child row");+ expect(passiveRow.activeSessionId).toBeUndefined();++ const attachResponse = (await internals.handleCommand(client, {+ type: "attach",+ activeSessionId: passiveRow.id,+ })) as { data: DaemonAttachResult };++ expect(attachResponse.data.activeSessionId).toBe(passiveRow.id);+ expect(internals.sessions.get(passiveRow.id)?.activeSessionId).toBe(passiveRow.id);+ expect(client.attachedActiveSessionIds).toContain(passiveRow.id);+ } finally {+ rmSync(tempDir, { recursive: true, force: true });+ }+ });++ it("deletes a passive child without hydrating it", async () => {+ const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-daemon-lazy-rlm-delete-"));+ try {+ const fixture = makePersistedRlmDaemonFixture(tempDir);+ const internals = fixture.daemon as unknown as {+ createRuntime(command: Extract<DaemonCommand, { type: "create" }>): Promise<ActiveSessionState>;+ createSubagentRuntimeHost(parent: ActiveSessionState): SubagentRuntimeHost;+ };+ const parentState = await internals.createRuntime({+ type: "create",+ sessionPath: fixture.parentSessionFile,+ });++ await internals.createSubagentRuntimeHost(parentState).deleteRlmSubagentRuntime(fixture.childId);++ expect(fixture.createRuntime).toHaveBeenCalledOnce();+ expect(existsSync(fixture.childSessionFile)).toBe(true);+ const persisted = readFileSync(join(fixture.parentArtifactDir, "rlm-subagents.jsonl"), "utf8")+ .trim()+ .split(/\r?\n/)+ .map((line) => JSON.parse(line) as { childId: string; status: string });+ expect(persisted.at(-1)).toMatchObject({ childId: fixture.childId, status: "deleted" });} finally {rmSync(tempDir, { recursive: true, force: true });}@@ -4006,7 +4182,7 @@ describe("daemon mode helpers", () => {const childOptions = createRuntime.mock.calls[1]?.[0];const childController = childOptions?.sessionOptions?.agentMessageController;expect(childController).toBeDefined();- const currentChild = childController?.listAgents().current;+ const currentChild = (await childController?.listAgents())?.current;const childActiveSessionId = currentChild?.activeSessionId;expect(childActiveSessionId).toBeTruthy();expect(currentChild?.sessionName).toBe(childSessionName);@@ -4025,7 +4201,7 @@ describe("daemon mode helpers", () => {},} as never;internals.sessions.set(grandchildState.activeSessionId, grandchildState);- expect(childController?.listAgents().agents).toContainEqual(+ expect((await childController?.listAgents())?.agents).toContainEqual(expect.objectContaining({activeSessionId: grandchildState.activeSessionId,parentActiveSessionId: childActiveSessionId,@@ -4130,7 +4306,7 @@ describe("daemon mode helpers", () => {}});- it("excludes half-bound sessions from targeting until extension binding completes", async () => {+ it("waits for extension binding before targeting half-bound sessions", async () => {const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-daemon-binding-gate-"));try {let releaseBind: () => void = () => {};@@ -4139,6 +4315,7 @@ describe("daemon mode helpers", () => {});const createRuntime = vi.fn(async (options: Parameters<CreateAgentSessionRuntimeFactory>[0]) => {const session = makeRuntimeSession(options.sessionManager);+ session.prompt = vi.fn(async () => {});session.bindExtensions = vi.fn(async () => {await bindBarrier;});@@ -4161,9 +4338,9 @@ describe("daemon mode helpers", () => {sessions: Map<string, ActiveSessionState>;createRuntime(command: Extract<DaemonCommand, { type: "create" }>): Promise<ActiveSessionState>;handleCommand(client: DaemonSocketClient, command: DaemonCommand): Promise<unknown> | undefined;- createAgentMessageListResult(current: ActiveSessionState): {+ createAgentMessageListResult(current: ActiveSessionState): Promise<{agents: Array<{ activeSessionId: string }>;- };+ }>;sendAgentSessionMessage(options: {targetSelector: string;message: string;@@ -4191,33 +4368,52 @@ describe("daemon mode helpers", () => {const bindingId = [...internals.sessions.keys()].find((id) => id !== fromState.activeSessionId);expect(bindingId).toBeTruthy();- await expect(- internals.sendAgentSessionMessage({- targetSelector: bindingId as string,- message: "too early",- fromState,- origin: "agent",+ const message = internals.sendAgentSessionMessage({+ targetSelector: bindingId as string,+ message: "wait for binding",+ fromState,+ origin: "agent",+ });+ const attach = Promise.resolve(+ internals.handleCommand(makeClient("client-1", bindingId as string), {+ id: "command-1",+ type: "attach",+ activeSessionId: bindingId as string,}),- ).rejects.toThrow("still initializing");- await expect(- Promise.resolve(- internals.handleCommand(makeClient("client-1", bindingId as string), {- id: "command-1",- type: "attach",- activeSessionId: bindingId as string,- }),- ),- ).rejects.toThrow("still initializing");- expect(internals.createAgentMessageListResult(fromState).agents.map((agent) => agent.activeSessionId)).toEqual(- [fromState.activeSessionId],);+ let messageSettled = false;+ let attachSettled = false;+ void message.then(+ () => {+ messageSettled = true;+ },+ () => {+ messageSettled = true;+ },+ );+ void attach.then(+ () => {+ attachSettled = true;+ },+ () => {+ attachSettled = true;+ },+ );+ await Promise.resolve();+ expect(messageSettled).toBe(false);+ expect(attachSettled).toBe(false);+ expect(+ (await internals.createAgentMessageListResult(fromState)).agents.map((agent) => agent.activeSessionId),+ ).toEqual([fromState.activeSessionId]);releaseBind();await created;+ await expect(message).resolves.toBeDefined();+ await attach.catch(() => undefined);- expect(internals.createAgentMessageListResult(fromState).agents.map((agent) => agent.activeSessionId)).toEqual(- expect.arrayContaining([fromState.activeSessionId, bindingId]),- );+ expect(+ (await internals.createAgentMessageListResult(fromState)).agents.map((agent) => agent.activeSessionId),+ ).toEqual(expect.arrayContaining([fromState.activeSessionId, bindingId]));} finally {rmSync(tempDir, { recursive: true, force: true });}@@ -5897,6 +6093,134 @@ function makeCronJob(input: {};}+function makePersistedRlmDaemonFixture(+ tempDir: string,+ options: { childRuntimeStarted?: () => void; childRuntimeGate?: Promise<void> } = {},+) {+ const sessionDir = join(tempDir, "sessions");+ const parentManager = SessionManager.create(tempDir, sessionDir);+ parentManager.newSession();+ parentManager.appendSessionInfo("Parent");+ const parentSessionFile = parentManager.getSessionFile();+ const parentArtifactDir = parentManager.getSessionArtifactDir();+ if (!parentSessionFile || !parentArtifactDir) {+ throw new Error("Missing parent session paths");+ }++ const childId = "child-1";+ const childSessionDir = join(parentArtifactDir, childId);+ const childManager = SessionManager.create(tempDir, childSessionDir);+ childManager.newSession({ parentSession: parentSessionFile });+ childManager.appendSessionInfo("spawn-worker");+ childManager.appendSessionInfo("renamed-worker");+ childManager.appendMessage({ role: "user", content: "complete this task", timestamp: 1 });+ childManager.flushNow();+ const childSessionFile = childManager.getSessionFile();+ const childArtifactDir = childManager.getSessionArtifactDir();+ if (!childSessionFile || !childArtifactDir) {+ throw new Error("Missing child session paths");+ }+ const grandchildId = "grandchild-1";+ const grandchildSessionDir = join(childArtifactDir, grandchildId);+ const grandchildManager = SessionManager.create(tempDir, grandchildSessionDir);+ grandchildManager.newSession({ parentSession: childSessionFile });+ grandchildManager.appendSessionInfo("nested-worker");+ grandchildManager.appendMessage({ role: "user", content: "complete the nested task", timestamp: 2 });+ grandchildManager.flushNow();+ const grandchildSessionFile = grandchildManager.getSessionFile();+ if (!grandchildSessionFile) throw new Error("Missing grandchild session file");+ writeFileSync(+ join(childArtifactDir, "rlm-subagents.jsonl"),+ `${JSON.stringify({+ type: "rlm_subagent",+ childId: grandchildId,+ sessionName: "nested-worker",+ sessionDir: grandchildSessionDir,+ sessionFile: grandchildSessionFile,+ parentSessionId: childManager.getSessionId(),+ parentSessionFile: childSessionFile,+ rlmDepth: 2,+ rlmMaxDepth: 4,+ rlmParentNodeId: grandchildId,+ status: "completed",+ createdAt: 2,+ updatedAt: "2026-01-01T00:00:01.000Z",+ })}+`,+ );+ writeFileSync(+ join(parentArtifactDir, "rlm-subagents.jsonl"),+ `${JSON.stringify({+ type: "rlm_subagent",+ childId,+ sessionName: "spawn-worker",+ sessionDir: childSessionDir,+ sessionFile: childSessionFile,+ parentSessionId: parentManager.getSessionId(),+ parentSessionFile,+ rlmDepth: 1,+ rlmMaxDepth: 4,+ rlmParentNodeId: childId,+ status: "completed",+ createdAt: 1,+ updatedAt: "2026-01-01T00:00:00.000Z",+ })}+`,+ );++ const acceptAgentMessagePrompt = vi.fn(+ (_message: string, options?: { preflightResult?: (didSucceed: boolean) => void }) => {+ options?.preflightResult?.(true);+ return Promise.resolve();+ },+ );+ const createRuntime = vi.fn(async (runtimeOptions: Parameters<CreateAgentSessionRuntimeFactory>[0]) => {+ if (runtimeOptions.sessionManager.getSessionFile() === childSessionFile && options.childRuntimeGate) {+ options.childRuntimeStarted?.();+ await options.childRuntimeGate;+ }+ const runtimeSession = makeRuntimeSession(runtimeOptions.sessionManager);+ Object.assign(runtimeSession, {+ isStreaming: false,+ isCompacting: false,+ isSessionActive: false,+ unfinishedActionCount: 0,+ state: { pendingToolCalls: new Set() },+ hasRunningRlmChildren: () => false,+ getSessionActionSnapshot: () => ({ queuedCount: 0, steering: [], followUps: [] }),+ sessionActions: { queuedCount: 0, steering: [], followUps: [] },+ acceptAgentMessagePrompt,+ });+ return {+ session: runtimeSession,+ extensionsResult: { extensions: [], errors: [], runtime: {} } as unknown as Awaited<+ ReturnType<CreateAgentSessionRuntimeFactory>+ >["extensionsResult"],+ services: { cwd: runtimeOptions.cwd, agentDir: runtimeOptions.agentDir } as Awaited<+ ReturnType<CreateAgentSessionRuntimeFactory>+ >["services"],+ diagnostics: [],+ };+ });+ const daemon = new AgentDaemon(join(tempDir, "daemon.sock"), {+ defaultSessionConfig: { agentDir: tempDir, cwd: tempDir, sessionDir },+ createRuntime,+ });+ return {+ daemon,+ createRuntime,+ acceptAgentMessagePrompt,+ parentSessionFile,+ parentArtifactDir,+ parentSessionId: parentManager.getSessionId(),+ childId,+ childSessionFile,+ childSessionDir,+ grandchildId,+ grandchildSessionFile,+ };+}+function makeRuntimeSession(sessionManager: Parameters<CreateAgentSessionRuntimeFactory>[0]["sessionManager"],): Awaited<ReturnType<CreateAgentSessionRuntimeFactory>>["session"] {@@ -5918,6 +6242,10 @@ function makeRuntimeSession(subscribe: vi.fn(() => vi.fn()),bindExtensions: vi.fn(async () => {}),setExecEnvProvider: vi.fn(),+ getAvailableThinkingLevels: vi.fn(() => []),+ scopedModels: [],+ getActiveToolNames: vi.fn(() => []),+ getContextUsage: vi.fn(() => undefined),setSessionName: vi.fn((name: string) => sessionManager.appendSessionInfo(name)),dispose: vi.fn(),disposeAsync: vi.fn(async () => {}),diff --git a/packages/coding-agent/test/daemon-supervisor-lazy-subagents.test.ts b/packages/coding-agent/test/daemon-supervisor-lazy-subagents.test.tsnew file mode 100644index 0000000000..c329408b68--- /dev/null+++ b/packages/coding-agent/test/daemon-supervisor-lazy-subagents.test.ts@@ -0,0 +1,119 @@+import { mkdtempSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, describe, expect, it, vi } from "vitest";+import type { AgentSessionMessageAgentSummary } from "../src/core/agent-messages.js";+import { success } from "../src/modes/daemon/daemon-protocol.js";+import type { SessionSummary } from "../src/modes/daemon/daemon-session-list.js";+import { DaemonSupervisor } from "../src/modes/daemon/daemon-supervisor.js";++interface SupervisorInternals {+ workers: Map<string, WorkerFixture>;+ refreshWorkerSummaries(worker: WorkerFixture): Promise<void>;+ syncAgentPeers(): Promise<void>;+}++interface WorkerFixture {+ descriptor: {+ workerId: string;+ lifecycle: "ready";+ rootActiveSessionId: string;+ rootSessionId: string;+ pid: number;+ };+ client: {+ request: ReturnType<typeof vi.fn>;+ requestWorker: ReturnType<typeof vi.fn>;+ };+ summaries: Map<string, SessionSummary>;+}++const tempDirs: string[] = [];++afterEach(() => {+ for (const directory of tempDirs.splice(0)) rmSync(directory, { recursive: true, force: true });+});++function summary(overrides: Partial<SessionSummary> & Pick<SessionSummary, "id" | "sessionId">): SessionSummary {+ return {+ lifecycle: "live",+ activity: "idle",+ isSessionActive: false,+ cwd: "/tmp/project",+ isStreaming: false,+ isCompacting: false,+ attachedClients: 0,+ messageCount: 1,+ sessionActions: { queuedCount: 0, steering: [], followUps: [] },+ ...overrides,+ };+}++function worker(workerId: string, summaries: SessionSummary[] = []): WorkerFixture {+ return {+ descriptor: {+ workerId,+ lifecycle: "ready",+ rootActiveSessionId: `${workerId}-root-active`,+ rootSessionId: `${workerId}-root-session`,+ pid: 1,+ },+ client: {+ request: vi.fn(),+ requestWorker: vi.fn(async () => ({ type: "response", command: "worker_sync_agent_peers", success: true })),+ },+ summaries: new Map(summaries.map((entry) => [entry.activeSessionId ?? entry.id, entry])),+ };+}++describe("daemon supervisor passive subagent topology", () => {+ it("retains passive worker summaries and sends them to cross-worker agent peer maps", async () => {+ const directory = mkdtempSync(join(tmpdir(), "prime-supervisor-passive-peers-"));+ tempDirs.push(directory);+ const supervisor = new DaemonSupervisor(join(directory, "daemon.sock"), {+ defaultSessionConfig: { agentDir: directory, cwd: directory },+ descriptorDir: join(directory, "workers"),+ }) as unknown as SupervisorInternals;++ const passive = summary({+ id: "passive-session",+ sessionId: "passive-session",+ sessionFile: join(directory, "passive.jsonl"),+ sessionName: "passive-worker",+ runtimeKind: "subagent",+ rlmChildId: "passive-child",+ });+ const first = worker("first");+ first.client.request.mockResolvedValue(success(undefined, "list", { sessions: [passive] }));+ const secondRoot = summary({+ id: "second-root-active",+ activeSessionId: "second-root-active",+ sessionId: "second-root-session",+ });+ const second = worker("second", [secondRoot]);+ supervisor.workers.set("first", first);+ supervisor.workers.set("second", second);++ await supervisor.refreshWorkerSummaries(first);+ expect(first.client.request).toHaveBeenCalledWith({ type: "list" }, 5000);+ expect(first.summaries.get("passive-session")).toMatchObject({+ sessionFile: passive.sessionFile,+ runtimeKind: "subagent",+ rlmChildId: "passive-child",+ });++ await supervisor.syncAgentPeers();+ const secondPeerCommand = second.client.requestWorker.mock.calls[0]?.[0] as+ | { peers: AgentSessionMessageAgentSummary[] }+ | undefined;+ expect(secondPeerCommand?.peers).toContainEqual(+ expect.objectContaining({+ activeSessionId: "passive-session",+ sessionId: "passive-session",+ sessionName: "passive-worker",+ runtimeKind: "subagent",+ rlmChildId: "passive-child",+ }),+ );+ });+});diff --git a/packages/coding-agent/test/daemon-supervisor-process.test.ts b/packages/coding-agent/test/daemon-supervisor-process.test.tsindex c10ec52e19..70e8c1a0e5 100644--- a/packages/coding-agent/test/daemon-supervisor-process.test.ts+++ b/packages/coding-agent/test/daemon-supervisor-process.test.ts@@ -1,6 +1,6 @@import { type ChildProcess, spawn } from "node:child_process";import { randomUUID } from "node:crypto";-import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync } from "node:fs";+import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { dirname, join, resolve } from "node:path";import { afterEach, describe, expect, it } from "vitest";@@ -286,6 +286,119 @@ async function startBlockingBash(client: DaemonClient, activeSessionId: string,}describe("daemon supervisor resident workers", () => {+ it("lists, creates, and attaches passive children through their owning worker", async () => {+ const root = tempDir();+ const agentDir = join(root, "agent");+ const projectDir = join(root, "project");+ const sessionDir = join(agentDir, "sessions");+ const socketPath = join(tmpdir(), `prime-supervisor-passive-${process.pid}-${randomUUID().slice(0, 8)}.sock`);+ mkdirSync(projectDir, { recursive: true });++ const parentManager = SessionManager.create(projectDir, sessionDir);+ parentManager.appendMessage({ role: "user", content: "parent fixture", timestamp: 1 });+ parentManager.flushNow();+ const parentSessionFile = parentManager.getSessionFile();+ const parentArtifactDir = parentManager.getSessionArtifactDir();+ if (!parentSessionFile || !parentArtifactDir) throw new Error("Missing parent fixture paths");++ const makeChild = (childId: string, sessionName: string, timestamp: number) => {+ const childSessionDir = join(parentArtifactDir, childId);+ const manager = SessionManager.create(projectDir, childSessionDir);+ manager.newSession({ parentSession: parentSessionFile });+ manager.appendSessionInfo(sessionName);+ manager.appendMessage({ role: "user", content: `completed ${childId} fixture`, timestamp });+ manager.flushNow();+ const sessionFile = manager.getSessionFile();+ if (!sessionFile) throw new Error("Missing child fixture path");+ return { childId, sessionName, childSessionDir, manager, sessionFile };+ };+ const child = makeChild("passive-child", "passive-child-worker", 2);+ const createChild = makeChild("passive-create-child", "passive-create-worker", 3);+ writeFileSync(+ join(parentArtifactDir, "rlm-subagents.jsonl"),+ `${[child, createChild]+ .map((fixture) =>+ JSON.stringify({+ type: "rlm_subagent",+ childId: fixture.childId,+ sessionName: fixture.sessionName,+ sessionDir: fixture.childSessionDir,+ sessionFile: fixture.sessionFile,+ parentSessionId: parentManager.getSessionId(),+ parentSessionFile,+ rlmDepth: 1,+ rlmMaxDepth: 4,+ rlmParentNodeId: fixture.childId,+ status: "completed",+ createdAt: 1,+ updatedAt: "2026-01-01T00:00:00.000Z",+ }),+ )+ .join("\n")}+`,+ );++ const supervisor = spawnSupervisor(agentDir, socketPath, projectDir);+ const client = await connectEventually(socketPath, supervisor);+ const created = await client.request({+ type: "create",+ sessionPath: parentSessionFile,+ config: { cwd: projectDir, agentDir, sessionDir, noTools: true, noExtensions: true },+ });+ expect(created.success).toBe(true);+ const parentSummary = requireSummary(created.success ? created.data : undefined);+ if (!parentSummary.workerPid) throw new Error("Parent worker did not expose its pid");+ workerPids.add(parentSummary.workerPid);++ const beforeAttach = await client.request({ type: "list" });+ expect(beforeAttach.success).toBe(true);+ const passiveSummary = requireSessionList(beforeAttach.success ? beforeAttach.data : undefined).find(+ (summary) => summary.sessionFile === child.sessionFile,+ );+ expect(passiveSummary).toMatchObject({+ sessionId: child.manager.getSessionId(),+ sessionName: "passive-child-worker",+ runtimeKind: "subagent",+ rlmChildId: child.childId,+ workerPid: parentSummary.workerPid,+ });+ expect(passiveSummary?.activeSessionId).toBeUndefined();++ const createdChild = await client.request({+ type: "create",+ sessionPath: createChild.sessionFile,+ config: { cwd: projectDir, agentDir, sessionDir, noTools: true, noExtensions: true },+ });+ if (!createdChild.success) throw new Error(createdChild.error);+ expect(requireSummary(createdChild.data)).toMatchObject({+ workerPid: parentSummary.workerPid,+ rlmChildId: createChild.childId,+ });+ expect(countWorkerDescriptors(agentDir)).toBe(1);++ const attached = await client.request({+ type: "attach",+ activeSessionId: child.manager.getSessionId(),+ capabilities: ["attach_snapshot", "event_sequence", "slim_attach"],+ });+ if (!attached.success) throw new Error(attached.error);++ const afterAttach = await client.request({ type: "list" });+ const hydratedSummary = requireSessionList(afterAttach.success ? afterAttach.data : undefined).find(+ (summary) => summary.sessionFile === child.sessionFile,+ );+ expect(hydratedSummary).toMatchObject({+ activeSessionId: expect.any(String),+ workerPid: parentSummary.workerPid,+ rlmChildId: child.childId,+ });+ expect(countWorkerDescriptors(agentDir)).toBe(1);++ await client.request({ type: "shutdown" });+ client.close();+ await waitForSocketGone(socketPath);+ }, 60_000);+it("keeps client-owned workers hidden and removes them without archiving", async () => {const root = tempDir();const agentDir = join(root, "agent");diff --git a/packages/coding-agent/test/suite/regressions/4649-subagent-model-selection.test.ts b/packages/coding-agent/test/suite/regressions/4649-subagent-model-selection.test.tsindex af0baf1dd7..64fc4d7937 100644--- a/packages/coding-agent/test/suite/regressions/4649-subagent-model-selection.test.ts+++ b/packages/coding-agent/test/suite/regressions/4649-subagent-model-selection.test.ts@@ -44,7 +44,7 @@ describe("ENG-4649 subagent model selection", () => {model: `${provider}/model-319`,});- const childEntry = harness.session.listRlmSubagents().subagents[0];+ const childEntry = (await harness.session.listRlmSubagents()).subagents[0];const child = harness.session.getRlmChildSession(childEntry!.rlm_child_id);expect(child?.model?.id).toBe("model-319");expect(result.model).toBe(`${provider}/model-319`);@@ -220,7 +220,7 @@ describe("ENG-4649 subagent model selection", () => {await expect(run).rejects.toThrow("parent session has been disposed");expect(providerCalls).toBe(0);- expect(harness.session.listRlmSubagents().subagents).toEqual([]);+ expect((await harness.session.listRlmSubagents()).subagents).toEqual([]);} finally {releasePreflight();harness.cleanup();@@ -273,7 +273,7 @@ describe("ENG-4649 subagent model selection", () => {name: "api-reviewer",model: `${provider}/child-model`,});- const childEntry = harness.session.listRlmSubagents().subagents[0];+ const childEntry = (await harness.session.listRlmSubagents()).subagents[0];expect(childEntry?.status).toBe("completed");const child = harness.session.getRlmChildSession(childEntry!.rlm_child_id);expect(child?.model?.id).toBe("child-model");@@ -392,8 +392,8 @@ describe("ENG-4649 subagent model selection", () => {expect(failedPreflight.model).toBe(`${provider}/parent-model`);expect(failedPreflight.warning).toContain("failed authentication preflight");- expect(harness.session.listRlmSubagents().subagents).toHaveLength(4);- for (const child of harness.session.listRlmSubagents().subagents) {+ expect((await harness.session.listRlmSubagents()).subagents).toHaveLength(4);+ for (const child of (await harness.session.listRlmSubagents()).subagents) {expect(harness.session.getRlmChildSession(child.rlm_child_id)?.model?.id).toBe("parent-model");}} finally {