A self-improving RLM agent for coding workflows and long-running autonomous tasks.
Rust
feat(coding-agent): intra-tree child session passivation (#589)
Sebastian Müllerb030f3938463
diff --git a/packages/coding-agent/src/core/agent-session-runtime.ts b/packages/coding-agent/src/core/agent-session-runtime.tsindex c862753a54..ce0498d2b7 100644--- a/packages/coding-agent/src/core/agent-session-runtime.ts+++ b/packages/coding-agent/src/core/agent-session-runtime.ts@@ -512,7 +512,10 @@ export class AgentSessionRuntime implements SubagentRuntimeHost {const sessionDir = this.session.sessionManager.getSessionDir();const sessionManager = SessionManager.create(this.cwd, sessionDir);if (options?.parentSession) {- sessionManager.newSession({ parentSession: options.parentSession });+ sessionManager.newSession({+ parentSession: options.parentSession,+ rlmDepth: this.session.sessionManager.getHeader()?.rlmDepth ?? this.session.rlmDepth,+ });}const lease = this.acquireReplacementLease(sessionManager.getSessionFile());@@ -577,7 +580,7 @@ export class AgentSessionRuntime implements SubagentRuntimeHost {const sessionManager = SessionManager.create(this.cwd, sessionDir);sessionManager.newSession({parentSession: currentSessionFile,- rlmDepth: sourceHeader?.rlmDepth,+ rlmDepth: sourceHeader?.rlmDepth ?? this.session.rlmDepth,});const lease = this.acquireReplacementLease(sessionManager.getSessionFile());await this.teardownForReplacement("fork", sessionManager.getSessionFile(), lease);@@ -628,7 +631,7 @@ export class AgentSessionRuntime implements SubagentRuntimeHost {const sourceHeader = sessionManager.getHeader();sessionManager.newSession({parentSession: this.session.sessionFile,- rlmDepth: sourceHeader?.rlmDepth,+ rlmDepth: sourceHeader?.rlmDepth ?? this.session.rlmDepth,});} else {sessionManager.createBranchedSession(targetLeafId);diff --git a/packages/coding-agent/src/core/agent-session.ts b/packages/coding-agent/src/core/agent-session.tsindex 71cd9e600a..3be6f0e67c 100644--- a/packages/coding-agent/src/core/agent-session.ts+++ b/packages/coding-agent/src/core/agent-session.ts@@ -925,6 +925,7 @@ const KERNEL_STATE_LISTING_TIMEOUT_MS = 5000;const RLM_MAX_DEPTH_STATE_CUSTOM_TYPE = "rlm_max_depth_state";function noopRlmChildAbort(): void {}+function noopRlmChildEventUnsubscribe(): void {}function isRlmChildRunCancelled(run: RlmChildRun): boolean {return run.status === "cancelled";@@ -1076,6 +1077,7 @@ export class AgentSession {private readonly _queuedWorkPauses = new Set<symbol>();private _sessionActionCommitTail: Promise<void> = Promise.resolve();private _sessionActionCommitOwner: symbol | undefined;+ private _pendingSessionActionFenceWaiters = 0;private readonly _sessionActionCommitContext = new AsyncLocalStorage<symbol>();private readonly _sessionActionCommitDisposeAbortController = new AbortController();// Checkpoint and handoff waiters share lifecycle-edge notifications to avoid polling.@@ -1255,10 +1257,10 @@ export class AgentSession {this._mcpManager = config.mcpManager;this._baseToolsOverride = config.baseToolsOverride;this._sessionStartEvent = config.sessionStartEvent ?? { type: "session_start", reason: "startup" };+ const headerRlmDepth = this.sessionManager.getHeader()?.rlmDepth;this._rlmDepth =config.rlmDepth ??- this.sessionManager.getHeader()?.rlmDepth ??- parseDepth(process.env.RLM_DEPTH, 0, "RLM_DEPTH");+ (isNonNegativeInteger(headerRlmDepth) ? headerRlmDepth : parseDepth(process.env.RLM_DEPTH, 0, "RLM_DEPTH"));this._configuredRlmMaxDepth = config.rlmMaxDepth;if (this._configuredRlmMaxDepth !== undefined && !isNonNegativeInteger(this._configuredRlmMaxDepth)) {throw new Error("rlmMaxDepth must be a non-negative integer");@@ -1521,10 +1523,7 @@ export class AgentSession {return { maxDepth: this._configuredRlmMaxDepth, source: "inherited" };}const global = this.settingsManager.getRlmMaxDepth();- if (global !== undefined) {- if (!isNonNegativeInteger(global)) {- throw new Error("The rlmMaxDepth setting must be a non-negative integer");- }+ if (global !== undefined && isNonNegativeInteger(global)) {return { maxDepth: global, source: "global" };}const env = process.env.RLM_MAX_DEPTH;@@ -5224,6 +5223,14 @@ export class AgentSession {});}+ get hasPendingAdmissionWaiters(): boolean {+ return (+ this._sessionActionCommitOwner !== undefined ||+ this._pendingSessionActionFenceWaiters > 0 ||+ this._sessionInputCheckpointWaiters.size > 0+ );+ }+private _scheduleSessionInputPump(): void {if (this._sessionInputPumpSuspended || this._queuedWorkPauses.size > 0) return;if (this._disposed || this._disposing || this._sessionInputPumpRequested || !this._hasSelectableSessionInput()) {@@ -6164,9 +6171,11 @@ export class AgentSession {});const disposeSignal = this._sessionActionCommitDisposeAbortController.signal;const waitSignal = signal ? AbortSignal.any([signal, disposeSignal]) : disposeSignal;+ this._pendingSessionActionFenceWaiters++;try {await waitForPromiseOrAbort(previous, waitSignal, "Update restart preparation cancelled");} catch (error) {+ this._pendingSessionActionFenceWaiters--;// A cancelled waiter remains in the FIFO chain until its predecessor releases.void previous.then(resolve, resolve);if (disposeSignal.aborted) {@@ -6176,6 +6185,7 @@ export class AgentSession {}const owner = Symbol("session-action-commit");this._sessionActionCommitOwner = owner;+ this._pendingSessionActionFenceWaiters--;let released = false;return {owner,@@ -8881,7 +8891,7 @@ export class AgentSession {}subagents.push({rlm_child_id: childId,- active_session_id: null,+ active_session_id: daemonChild.activeSessionId,session_id: daemonChild.sessionId,session_name: daemonChild.sessionName ?? createDefaultRlmSubagentSessionName("", childId),session_dir: daemonChild.sessionDir,@@ -8943,7 +8953,7 @@ export class AgentSession {}if (localMatches[0]) {const subagent = localMatches[0];- const deletion = (async () => {+ return this._trackRlmSubagentDeletion(subagent, async () => {const listedAgents = await this._agentMessageController?.listAgents();const listedSubagents = this._buildRlmSubagentList(listedAgents).subagents;const passiveMatches = listedSubagents.filter(@@ -8966,8 +8976,7 @@ export class AgentSession {}: subagent;return this._deleteResolvedRlmSubagent(resolvedSubagent);- })();- return this._trackRlmSubagentDeletion(subagent, deletion);+ });}const directMatches = [@@ -8979,13 +8988,16 @@ export class AgentSession {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));+ return this._trackRlmSubagentDeletion(subagent, () => this._deleteResolvedRlmSubagent(subagent));}private async _trackRlmSubagentDeletion(subagent: RlmSubagentRegistryEntry,- deletion: Promise<RlmDeleteSubagentResult>,+ startDeletion: () => Promise<RlmDeleteSubagentResult>,): Promise<RlmDeleteSubagentResult> {+ const existing = this._deletingRlmChildren.get(subagent.rlm_child_id);+ if (existing) return existing.promise;+ const deletion = Promise.resolve().then(startDeletion);this._deletingRlmChildren.set(subagent.rlm_child_id, { subagent, promise: deletion });try {return await deletion;@@ -9117,7 +9129,7 @@ export class AgentSession {* the child) when the parent is already tearing down, so the caller can drop the* matching event forwarder too.*/- retainFinishedRlmChildSession(childId: string, session: AgentSession): boolean {+ retainFinishedRlmChildSession(childId: string, session: AgentSession, unsubscribe?: () => void): boolean {// A child can finish concurrently while the parent is (or has) torn down; don't// resurrect the map (it would never be disposed), just drop the child now.if (this._disposed || this._disposing) {@@ -9128,9 +9140,21 @@ export class AgentSession {return false;}this._retainedRlmChildSessions.set(childId, session);+ if (unsubscribe) {+ this._retainedRlmChildUnsubscribes.set(childId, unsubscribe);+ }return true;}+ /** Stop retaining an idle daemon child without deleting its durable registry row. */+ releaseFinishedRlmChildSession(childId: string, session: AgentSession): (() => void) | false {+ if (this._retainedRlmChildSessions.get(childId) !== session) return false;+ const unsubscribe = this._retainedRlmChildUnsubscribes.get(childId) ?? noopRlmChildEventUnsubscribe;+ this._retainedRlmChildUnsubscribes.delete(childId);+ this._retainedRlmChildSessions.delete(childId);+ return unsubscribe;+ }+/** True when any direct or nested subagent is still running or queued. */hasRunningRlmChildren(): boolean {for (const run of this._activeRlmChildRuns.values()) {@@ -10177,9 +10201,14 @@ export class AgentSession {let globalError: string | undefined;if (options.global) {+ await this.settingsManager.flush();+ const staleErrors = this.settingsManager.drainErrors("global");+ for (const { error } of staleErrors) {+ console.warn(`Warning: Earlier global settings write failed: ${error.message}`);+ }this.settingsManager.setRlmMaxDepth(maxDepth);await this.settingsManager.flush();- const errors = this.settingsManager.drainErrors().filter(({ scope }) => scope === "global");+ const errors = this.settingsManager.drainErrors("global");globalError = errors.map(({ error }) => error.message).join("; ") || undefined;}diff --git a/packages/coding-agent/src/core/session-action-store.ts b/packages/coding-agent/src/core/session-action-store.tsindex 91ea4816b1..fc7a815dcd 100644--- a/packages/coding-agent/src/core/session-action-store.ts+++ b/packages/coding-agent/src/core/session-action-store.ts@@ -319,6 +319,12 @@ export interface SessionEvictionSnapshot {lastActivityAt: number;}+export interface SessionPassivationSnapshot extends SessionEvictionSnapshot {+ hasParent: boolean;+ hasNonPassiveDescendants: boolean;+ isHydrating: boolean;+}+export interface WorkerEvictionSnapshot {lifecycle: "starting" | "ready" | "recovering" | "failed";isConnected: boolean;@@ -328,6 +334,38 @@ export interface WorkerEvictionSnapshot {sessions: readonly SessionEvictionSnapshot[];}+function isIdleEvictionThresholdMet(+ session: SessionEvictionSnapshot,+ idleEvictionMinutes: IdleEvictionMinutes,+ now: number,+): boolean {+ if (idleEvictionMinutes === "off" || !Number.isFinite(idleEvictionMinutes) || idleEvictionMinutes <= 0) {+ return false;+ }+ return (+ !session.isSessionActive &&+ session.attachedClients === 0 &&+ !session.hasRegisteredHeartbeat &&+ !session.hasRegisteredCronJob &&+ Number.isFinite(session.lastActivityAt) &&+ now - session.lastActivityAt >= idleEvictionMinutes * 60_000+ );+}++/** Pure per-node residency policy. Roots remain owned by whole-worker eviction. */+export function canPassivateSession(+ session: SessionPassivationSnapshot,+ idleEvictionMinutes: IdleEvictionMinutes,+ now = Date.now(),+): boolean {+ return (+ session.hasParent &&+ !session.hasNonPassiveDescendants &&+ !session.isHydrating &&+ isIdleEvictionThresholdMet(session, idleEvictionMinutes, now)+ );+}+/** Pure whole-tree residency policy. Callers must supply supervisor-owned attachment state. */export function canEvictWorker(worker: WorkerEvictionSnapshot,@@ -335,9 +373,6 @@ export function canEvictWorker(now = Date.now(),): boolean {if (- idleEvictionMinutes === "off" ||- !Number.isFinite(idleEvictionMinutes) ||- idleEvictionMinutes <= 0 ||worker.lifecycle !== "ready" ||!worker.isConnected ||worker.isStopping ||@@ -347,16 +382,7 @@ export function canEvictWorker() {return false;}- const idleThresholdMs = idleEvictionMinutes * 60_000;- return worker.sessions.every(- (session) =>- !session.isSessionActive &&- session.attachedClients === 0 &&- !session.hasRegisteredHeartbeat &&- !session.hasRegisteredCronJob &&- Number.isFinite(session.lastActivityAt) &&- now - session.lastActivityAt >= idleThresholdMs,- );+ return worker.sessions.every((session) => isIdleEvictionThresholdMet(session, idleEvictionMinutes, now));}export function canSelectSessionAction(activity: RuntimeActivity): boolean {diff --git a/packages/coding-agent/src/core/session-manager.ts b/packages/coding-agent/src/core/session-manager.tsindex cfbfaa1660..2c1bcc4480 100644--- a/packages/coding-agent/src/core/session-manager.ts+++ b/packages/coding-agent/src/core/session-manager.ts@@ -759,7 +759,8 @@ function legacyChildDepthFromPath(sessionPath: string): number {}function deriveChildRlmDepth(parentHeader: Partial<SessionHeader> | undefined): number | undefined {- return isValidRlmDepth(parentHeader?.rlmDepth) ? parentHeader.rlmDepth + 1 : undefined;+ const depth = parentHeader?.rlmDepth;+ return isValidRlmDepth(depth) && depth < Number.MAX_SAFE_INTEGER ? depth + 1 : undefined;}function rootRlmDepthFromEnv(): number {@@ -767,8 +768,8 @@ function rootRlmDepthFromEnv(): number {if (value === undefined || value === "") {return 0;}- const parsed = Number.parseInt(value, 10);- if (!Number.isFinite(parsed) || parsed < 0) {+ const parsed = Number(value);+ if (!/^\d+$/.test(value) || !isValidRlmDepth(parsed)) {throw new Error("RLM_DEPTH must be a non-negative integer");}return parsed;diff --git a/packages/coding-agent/src/core/settings-manager.ts b/packages/coding-agent/src/core/settings-manager.tsindex da98aed7b0..0647fc3b63 100644--- a/packages/coding-agent/src/core/settings-manager.ts+++ b/packages/coding-agent/src/core/settings-manager.ts@@ -626,9 +626,14 @@ export class SettingsManager {await this.writeQueue;}- drainErrors(): SettingsError[] {- const drained = [...this.errors];- this.errors = [];+ drainErrors(scope?: SettingsScope): SettingsError[] {+ if (!scope) {+ const drained = [...this.errors];+ this.errors = [];+ return drained;+ }+ const drained = this.errors.filter((entry) => entry.scope === scope);+ this.errors = this.errors.filter((entry) => entry.scope !== scope);return drained;}diff --git a/packages/coding-agent/src/modes/agents-view/agents-view-mode.ts b/packages/coding-agent/src/modes/agents-view/agents-view-mode.tsindex 9f4610d3f9..a15c30bd39 100644--- a/packages/coding-agent/src/modes/agents-view/agents-view-mode.ts+++ b/packages/coding-agent/src/modes/agents-view/agents-view-mode.ts@@ -152,6 +152,7 @@ export type AgentsViewPersistentState = {selectedRowIdentity?: string;backSession?: SessionSummary;scopeFrames?: AgentsViewScopeFrame[];+ scopeRootSummary?: SessionSummary;selectedSessionKey?: AgentsViewSelectionKey;// Ancestor chain to re-expand on return to a nested agent. Kept by sessionId,// not row identity, so it survives an active→persisted identity flip.@@ -421,6 +422,7 @@ export async function runAgentsViewMode(options: AgentsViewModeOptions): Promiselet result: Extract<AgentsViewRunResult, { type: "open" }>;if (viewResult.type === "scope_back") {persistentState.scopeFrames = transitionAgentsViewScope(persistentState.scopeFrames ?? [], { type: "back" });+ persistentState.scopeRootSummary = undefined;persistentState.selectedRowIdentity = getSummaryIdentity(viewResult.selection);persistentState.selectedSessionKey = getAgentsViewSelectionKey(viewResult.selection);persistentState.pendingExpandedAncestorSessionIds = viewResult.expandedAncestorSessionIds;@@ -441,6 +443,7 @@ export async function runAgentsViewMode(options: AgentsViewModeOptions): Promiselet opened: OpenedAgentsViewSession | undefined;try {opened = await openAgentsViewSession(options, result.summary);+ persistentState.backSession = opened.summary;if (opened.cwdFallbackNotice) {persistentState.statusMessage = combineAgentsViewStartupNotices(result.statusMessage,@@ -494,6 +497,7 @@ export async function runAgentsViewMode(options: AgentsViewModeOptions): PromisecachedIndex === -1? [...cachedLiveSummaries, returnedSession]: cachedLiveSummaries.map((summary, index) => (index === cachedIndex ? returnedSession : summary));+ persistentState.scopeRootSummary = undefined;persistentState.query = "";}persistentState.backSession = returnedSession;@@ -689,6 +693,7 @@ export class AgentsViewMode implements Component, Focusable {);persistentState.scopeFrames = initialFrames;this.scopeKey = initialFrames.at(-1)?.scope;+ this.scopeRootSummary = persistentState.scopeRootSummary;this.selectedRowIdentity = persistentState.selectedRowIdentity;this.selectedSessionKey = persistentState.selectedSessionKey;this.selectedActiveSessionId = persistentState.selectedSessionKey?.activeSessionId;@@ -2136,6 +2141,7 @@ export class AgentsViewMode implements Component, Focusable {this.persistentState.scopeFrames = resolution.frames;this.scopeKey = resolution.frames.at(-1)?.scope;this.scopeRootSummary = resolution.root ? summaryForUnifiedRecord(resolution.root) : undefined;+ this.persistentState.scopeRootSummary = this.scopeRootSummary;if (resolution.droppedFrames > 0) {const destination = resolution.root ? "the nearest available parent" : "the global view";this.setStatusMessage(`Scope is no longer available; returned to ${destination}`, { render: false });@@ -2169,6 +2175,7 @@ export class AgentsViewMode implements Component, Focusable {const generation = ++this.savedCatalogGeneration;this.persistentState.savedCatalogGeneration = generation;this.savedCatalogRefreshPending = true;+ this.savedCatalogReady = false;const successfulSessions = this.lastSuccessfulSavedSessions;const progressiveSessions = new Map(successfulSessions.map((session) => [resolvePath(canonicalizePath(session.path)), session]),diff --git a/packages/coding-agent/src/modes/daemon/active-session-state.ts b/packages/coding-agent/src/modes/daemon/active-session-state.tsindex d28c37976b..fe062253ce 100644--- a/packages/coding-agent/src/modes/daemon/active-session-state.ts+++ b/packages/coding-agent/src/modes/daemon/active-session-state.ts@@ -35,6 +35,8 @@ export interface ActiveSessionState {activeSessionId: string;runtime: AgentSessionRuntime;clients: Set<DaemonSocketClient>;+ /** Attach snapshots in flight: reserved for passivation busyness, but not yet event recipients. */+ pendingAttaches: number;extensionUiRequests: Map<string, ActiveSessionExtensionUiRequest>;eventGeneration: string;lastEventSequence: DaemonEventSequence;@@ -68,6 +70,13 @@ export function createActiveSessionId(existingIds?: ActiveSessionIdIndex): strin}}+export class AmbiguousActiveSessionError extends Error {+ constructor(message: string) {+ super(message);+ this.name = "AmbiguousActiveSessionError";+ }+}+export function resolveActiveSessionState(sessions: ReadonlyMap<string, ActiveSessionState>,selector: string,@@ -87,7 +96,7 @@ export function resolveActiveSessionState(return exactMatches[0]!;}if (exactMatches.length > 1) {- throw new Error(formatAmbiguousSessionError(selector, exactMatches));+ throw new AmbiguousActiveSessionError(formatAmbiguousSessionError(selector, exactMatches));}const suffixMatches = uniqueStates(@@ -103,7 +112,7 @@ export function resolveActiveSessionState(return suffixMatches[0]!;}if (suffixMatches.length > 1) {- throw new Error(formatAmbiguousSessionError(selector, suffixMatches));+ throw new AmbiguousActiveSessionError(formatAmbiguousSessionError(selector, suffixMatches));}throw new Error(`Unknown active session: ${selector}`);diff --git a/packages/coding-agent/src/modes/daemon/daemon-mode.ts b/packages/coding-agent/src/modes/daemon/daemon-mode.tsindex cf181df280..f3c1c8187b 100644--- a/packages/coding-agent/src/modes/daemon/daemon-mode.ts+++ b/packages/coding-agent/src/modes/daemon/daemon-mode.ts@@ -97,6 +97,11 @@ import type {RlmSubagentRuntime,SubagentRuntimeHost,} from "../../core/rlm-runtime.js";+import {+ canPassivateSession,+ type IdleEvictionMinutes,+ type SessionPassivationSnapshot,+} from "../../core/session-action-store.js";import { deleteSessionFile } from "../../core/session-file-actions.js";import { acquireSessionLease, type SessionLease } from "../../core/session-lease.js";import {@@ -121,6 +126,7 @@ import { attachJsonlLineReader, serializeJsonLine } from "../rpc/jsonl.js";import { encodePrivateFrame, PrivateFrameDecoder } from "../session-worker/private-framing.js";import {type ActiveSessionState,+ AmbiguousActiveSessionError,createActiveSessionId,type DaemonSocketClient,resolveActiveSessionState,@@ -215,6 +221,7 @@ export { defaultDaemonSocketPath } from "./daemon-socket.js";const structuredLog = getLogger("coding-agent.daemon");const WORKER_SNAPSHOT_TERMINAL_DRAIN_TIMEOUT_MS = 1_000;const UPDATE_RESTART_PREPARE_TIMEOUT_MS = 90_000;+const MAX_SESSION_SNAPSHOT_STABILIZATION_RETRIES = 3;const DAEMON_COMMAND_TYPES: ReadonlySet<string> = new Set(["ack_result",@@ -418,7 +425,22 @@ export class AgentDaemon {/** Covers path resolution through publication in openingSessions, before the runtime promise exists. */private readonly reservingSessionOpens = new Map<string, Promise<void>>();private readonly bindingCompletions = new Map<string, Promise<void>>();- private readonly closingSessions = new Map<string, Promise<void>>();+ /**+ * Resolved-session-file keyed passivations let wake paths join after closeSessionOnce+ * removes the live session. This intentionally complements closingSessions: that map+ * coalesces every close by transient activeSessionId, while this one identifies the+ * passivation-only close reason by the durable identity needed by hydration/opening.+ */+ private readonly passivatingSessions = new Map<string, Promise<void>>();+ private readonly closingSessions = new Map<+ string,+ {+ promise: Promise<void>;+ reason: DaemonSessionClosedReason;+ descendants: Set<ActiveSessionState>;+ reasonUpgrade?: Promise<void>;+ }+ >();private readonly sideQuestionRuns = new Map<string,{ run: SideQuestionRun; client: DaemonSocketClient; activeSessionId: string }@@ -1158,6 +1180,7 @@ export class AgentDaemon {: createActiveSessionId(this.sessions),runtime,clients: new Set(),+ pendingAttaches: 0,extensionUiRequests: new Map(),eventGeneration: createActiveSessionId(),lastEventSequence: 0,@@ -1270,6 +1293,10 @@ export class AgentDaemon {? await resolveDaemonSessionPath(command.sessionPath, cwd, config.sessionDir): undefined;const sessionKey = sessionPath ? resolve(sessionPath) : undefined;+ if (sessionKey && this.findPassivationBySessionFile(sessionKey)) {+ await this.waitForPassivation(sessionKey);+ return this.createRuntime(command, runtimeOpenGuard);+ }const pending = sessionKey ? this.openingSessions.get(sessionKey) : undefined;if (pending && sessionKey) {// Join the in-process open before attempting the filesystem lease. The@@ -1302,7 +1329,16 @@ export class AgentDaemon {if (runtimeOpenGuard && !(await runtimeOpenGuard())) {throw new RuntimeOpenCancelledError();}- return this.hydratePassiveRlmSubagent(passiveSubagent);+ const state = await this.hydratePassiveRlmSubagent(passiveSubagent, clientEnv);+ if (runtimeOpenGuard && !(await runtimeOpenGuard())) {+ throw new RuntimeOpenCancelledError();+ }+ if (command.name) {+ state.runtime.session.setSessionName(command.name);+ }+ if (passiveSubagent.rootParentState) this.adoptClientEnv(passiveSubagent.rootParentState, clientEnv);+ this.adoptClientEnv(state, clientEnv);+ return state;}// Hydration may have started while the async registry walk above was in@@ -1962,7 +1998,15 @@ export class AgentDaemon {job.sessionFile,residentChild !== undefined && residentChild.runtime.metadata.kind !== "subagent",);- const childState = passiveSubagent ? await this.hydratePassiveRlmSubagent(passiveSubagent) : residentChild;+ const resident = this.findSessionBySessionFile(job.sessionFile);+ const childState = passiveSubagent+ ? await this.hydratePassiveRlmSubagent(passiveSubagent)+ : resident+ ? await this.waitForBoundSession(resident)+ : undefined;+ if (passiveSubagent && childState && this.getRunnableCronJob(job.id) === undefined) {+ throw new RuntimeOpenCancelledError();+ }if (!childState || childState.runtime.metadata.kind !== "subagent") {this.cancelRlmHeartbeat(job.id);return undefined;@@ -1971,7 +2015,7 @@ export class AgentDaemon {const reboundJob = this.getRunnableCronJob(job.id);return reboundJob && this.isCronJobRunnableForState(reboundJob, childState, true) ? childState : undefined;} catch (error) {- if (error instanceof RuntimeOpenCancelledError) {+ if (error instanceof RuntimeOpenCancelledError || error instanceof BoundSessionUnavailableError) {return undefined;}throw error;@@ -2067,7 +2111,10 @@ export class AgentDaemon {return this.getBoundSessionState(id);} catch (error) {if (error instanceof BoundSessionUnavailableError) {- return this.waitForBoundSession(this.getSessionState(id));+ return this.waitForHydratingChild(this.getSessionState(id), id);+ }+ if (error instanceof AmbiguousActiveSessionError) {+ throw error;}lookupError = error;}@@ -2079,9 +2126,27 @@ export class AgentDaemon {(state) => state.runtime.metadata.kind === "subagent" && state.runtime.metadata.rlmChildId === id,);if (hydratingChild) {- return this.waitForBoundSession(hydratingChild);+ return this.waitForHydratingChild(hydratingChild, id);+ }+ try {+ return this.getBoundSessionState(id);+ } catch (error) {+ if (error instanceof BoundSessionUnavailableError) {+ return this.waitForHydratingChild(this.getSessionState(id), id);+ }+ if (error instanceof AmbiguousActiveSessionError) throw error;+ throw lookupError;}- throw lookupError;+ }++ private async waitForHydratingChild(state: ActiveSessionState, selector: string): Promise<ActiveSessionState> {+ const sessionFile = state.runtime.session.sessionFile;+ if (!sessionFile || !this.findPassivationBySessionFile(sessionFile)) {+ return this.waitForBoundSession(state);+ }+ await this.waitForPassivation(sessionFile);+ const passive = await this.findPassiveRlmSubagent(sessionFile);+ return passive ? this.hydratePassiveRlmSubagent(passive) : this.getOrHydrateBoundSessionState(selector);}private findRuntimeState(runtime: RlmSubagentRuntime): ActiveSessionState | undefined {@@ -2109,6 +2174,7 @@ export class AgentDaemon {const persisted = (await this.readLatestRlmSubagentRegistry(parentState, true)).find((entry) => entry.childId === childId,);+ const childSessionFile = persisted?.sessionFile ?? state?.runtime.session.sessionFile;// 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);@@ -2122,8 +2188,9 @@ export class AgentDaemon {} finally {await staleSession?.disposeAsync();}- if (persisted && !state) {- this.cancelScheduledJobsForSessionFile(persisted.sessionFile);+ // A killed close can join a passivation close that already skipped killed cleanup.+ if (childSessionFile) {+ this.cancelScheduledJobsForSessionFile(childSessionFile);}},disposeRlmSubagentRuntimes: async () => {@@ -2187,12 +2254,10 @@ export class AgentDaemon {options: CreateRlmSubagentRuntimeOptions,): Promise<AgentSessionRuntime> {const sessionManager = SessionManager.create(options.parentSession.sessionManager.getCwd(), options.sessionDir);- if (options.parentSession.sessionFile) {- sessionManager.newSession({- parentSession: options.parentSession.sessionFile,- rlmDepth: options.rlmDepth,- });- }+ sessionManager.newSession({+ parentSession: options.parentSession.sessionFile,+ rlmDepth: options.rlmDepth,+ });let stateRef: ActiveSessionState | undefined;// Subagents inherit the parent's client env (e.g. herdr pane identity).const runtime = await withClientEnv(parentState.clientEnv, () =>@@ -2293,14 +2358,223 @@ export class AgentDaemon {return runtime;}- private async hydratePassiveRlmSubagent(passive: PassiveRlmSubagent): Promise<ActiveSessionState> {- let parentState = passive.rootParentState;- if (!parentState) {+ private async sessionPassivationSnapshot(+ state: ActiveSessionState,+ passiveRlmSubagents?: readonly PassiveRlmSubagent[],+ ): Promise<SessionPassivationSnapshot> {+ const passiveDescendants = passiveRlmSubagents ?? (await this.listPassiveRlmSubagents());+ const summary = summaryForActiveSession(state);+ const sessionFile = state.runtime.session.sessionFile;+ const jobs = this.cronStore+ .list()+ .filter(+ (job) =>+ job.activeSessionId === state.activeSessionId &&+ job.status !== "cancelled" &&+ job.status !== "completed",+ );+ const hasPendingAdmission =+ this.agentMessageAcceptingTargets.has(state.activeSessionId) ||+ this.agentMessagePreparingTargets.has(state.activeSessionId) ||+ this.agentMessageTargetLocks.has(state.activeSessionId) ||+ [...this.promptAdmissions.values()].some(+ (admission) => admission.activeSessionId === state.activeSessionId && admission.status !== "cancelled",+ ) ||+ state.runtime.session.hasPendingAdmissionWaiters;+ return {+ isSessionActive: summary.isSessionActive || summary.hasRunningRlmChildren === true || hasPendingAdmission,+ attachedClients: state.clients.size + state.pendingAttaches,+ hasRegisteredHeartbeat: jobs.some((job) => isHeartbeatCronJob(job) && job.status === "active"),+ hasRegisteredCronJob: jobs.some((job) => !isHeartbeatCronJob(job)),+ lastActivityAt: Date.parse(summary.lastActivityAt ?? ""),+ hasParent: state.runtime.metadata.kind === "subagent" && !!state.runtime.metadata.parentActiveSessionId,+ hasNonPassiveDescendants: getChildActiveSessionStates(this.sessions, state).length > 0,+ isHydrating:+ this.bindingSessions.has(state.activeSessionId) ||+ (sessionFile ? this.openingSessions.has(resolve(sessionFile)) : false) ||+ passiveDescendants.some(+ (passive) =>+ passive.rootParentState === state &&+ passive.chain.some((entry) => this.openingSessions.has(resolve(entry.sessionFile))),+ ),+ };+ }++ private async passivateSession(+ state: ActiveSessionState,+ idleEvictionMinutes: IdleEvictionMinutes,+ now: number,+ selectedSnapshot?: SessionPassivationSnapshot,+ ): Promise<boolean> {+ const sessionFile = state.runtime.session.sessionFile;+ const metadata = state.runtime.metadata;+ if (!sessionFile || metadata.kind !== "subagent" || !metadata.rlmChildId || !metadata.parentActiveSessionId) {+ return false;+ }+ const sessionKey = resolve(sessionFile);+ const parentActiveSessionId = metadata.parentActiveSessionId;+ const childId = metadata.rlmChildId;+ const existing = this.passivatingSessions.get(sessionKey);+ if (existing) {+ await existing;+ return false;+ }+ const snapshot = selectedSnapshot ?? (await this.sessionPassivationSnapshot(state));+ if (!canPassivateSession(snapshot, idleEvictionMinutes, now)) return false;++ // Publish the durable identity before running the close so opens and lazy+ // hydration can join throughout closeSessionOnce, including after sessions.delete.+ const passivation = Promise.resolve().then(async () => {+ // Fence against touches and state changes after candidate selection. This+ // snapshot is intentionally fresh rather than reusing the sweep snapshot.+ if (+ this.shuttingDown ||+ this.updateRestart !== undefined ||+ this.sessions.get(state.activeSessionId) !== state ||+ !canPassivateSession(await this.sessionPassivationSnapshot(state), idleEvictionMinutes, now)+ ) {+ return;+ }+ const parentState = this.sessions.get(parentActiveSessionId);+ if (!parentState) return;+ const idleMinutes = Math.floor((now - snapshot.lastActivityAt) / 60_000);+ // Detach parent tracking before the standard graceful runtime disposal. The+ // registry/catalog rows remain the sole passive representation after close.+ const unsubscribeChild = parentState.runtime.session.releaseFinishedRlmChildSession(+ childId,+ state.runtime.session,+ );+ if (!unsubscribeChild) {+ return;+ }+ try {+ await this.closeSession(state, "shutdown", true, false);+ } catch (error) {+ // A pre-removal close failure must not strand a resident child outside its+ // parent's ownership map or disconnect its event forwarder.+ if (+ this.sessions.get(state.activeSessionId) === state &&+ this.sessions.get(parentActiveSessionId) === parentState &&+ parentState.runtime.session.retainFinishedRlmChildSession(+ childId,+ state.runtime.session,+ unsubscribeChild,+ )+ ) {+ throw error;+ }+ unsubscribeChild();+ throw error;+ }+ unsubscribeChild();+ this.log(+ `Passivated idle child sessionId=${state.runtime.session.sessionId} name=${JSON.stringify(state.runtime.session.sessionName ?? "")} idleMinutes=${idleMinutes}`,+ );+ });+ this.passivatingSessions.set(sessionKey, passivation);+ try {+ await passivation;+ return this.sessions.get(state.activeSessionId) !== state;+ } finally {+ if (this.passivatingSessions.get(sessionKey) === passivation) {+ this.passivatingSessions.delete(sessionKey);+ }+ }+ }++ private async passivateIdleChildren(+ idleEvictionMinutes: IdleEvictionMinutes,+ now: number,+ limit: number,+ ): Promise<number> {+ if (this.shuttingDown || this.updateRestart !== undefined || limit <= 0) return 0;+ const states = [...this.sessions.values()];+ const passiveRlmSubagents = await this.listPassiveRlmSubagents();+ const snapshots = await Promise.all(+ states.map(async (state) => ({+ state,+ snapshot: await this.sessionPassivationSnapshot(state, passiveRlmSubagents),+ })),+ );+ const candidates = snapshots+ .filter(({ snapshot }) => canPassivateSession(snapshot, idleEvictionMinutes, now))+ .sort((left, right) => left.snapshot.lastActivityAt - right.snapshot.lastActivityAt)+ .slice(0, limit);+ const results = await Promise.all(+ candidates.map(({ state, snapshot }) => this.passivateSession(state, idleEvictionMinutes, now, snapshot)),+ );+ return results.filter(Boolean).length;+ }++ private findPassivationBySessionFile(sessionFile: string): Promise<void> | undefined {+ return this.passivatingSessions.get(resolve(sessionFile));+ }++ private async waitForPassivation(sessionFile: string): Promise<void> {+ const passivation = this.findPassivationBySessionFile(sessionFile);+ if (passivation) await passivation.catch(() => {});+ }++ private async hydratePassiveRlmSubagent(+ passive: PassiveRlmSubagent,+ clientEnv?: Record<string, string>,+ ): Promise<ActiveSessionState> {+ if (this.updateRestart !== undefined) {+ throw new BoundSessionUnavailableError("Daemon is preparing an update restart");+ }+ const isResident = (state: ActiveSessionState): boolean =>+ this.sessions.get(state.activeSessionId) === state && !this.closingSessions.has(state.activeSessionId);+ const restartAfterParentChange = async (staleParent: ActiveSessionState): Promise<ActiveSessionState> => {+ const staleParentFile = staleParent.runtime.session.sessionFile;+ if (staleParentFile) await this.waitForPassivation(staleParentFile);+ const refreshed = await this.findPassiveRlmSubagent(passive.entry.sessionFile, true);+ if (!refreshed) throw new RuntimeOpenCancelledError();+ const resident = this.findSessionBySessionFile(passive.entry.sessionFile);+ if (+ resident &&+ resident.runtime.metadata.kind === "subagent" &&+ resident.runtime.metadata.rlmChildId === passive.entry.childId+ ) {+ return this.waitForBoundSession(resident);+ }+ return this.hydratePassiveRlmSubagent(refreshed, clientEnv);+ };+ const rootParent = passive.rootParentState;+ if (!rootParent) {throw new Error(`Cannot hydrate RLM subagent ${passive.entry.childId} without a resident root parent`);}+ const rootParentFile = rootParent.runtime.session.sessionFile;+ if (rootParentFile) await this.waitForPassivation(rootParentFile);+ if (!isResident(rootParent)) {+ return restartAfterParentChange(rootParent);+ }+ let parentState = rootParent;for (const entry of passive.chain) {+ await this.waitForPassivation(entry.sessionFile);+ if (!isResident(parentState)) {+ return restartAfterParentChange(parentState);+ }+ const hydratingParent = parentState;const activeSessionId = entry === passive.entry ? passive.info.id : undefined;- parentState = await this.rehydrateCompletedRlmSubagent(parentState, entry, activeSessionId);+ let hydrated: ActiveSessionState;+ try {+ hydrated = await this.rehydrateCompletedRlmSubagent(hydratingParent, entry, activeSessionId, clientEnv);+ } catch (error) {+ const passivation = this.findPassivationBySessionFile(entry.sessionFile);+ if (error instanceof BoundSessionUnavailableError && passivation) {+ await passivation.catch(() => {});+ return restartAfterParentChange(hydratingParent);+ }+ if (isResident(hydratingParent)) throw error;+ return restartAfterParentChange(hydratingParent);+ }+ if (!isResident(hydratingParent)) {+ return restartAfterParentChange(hydratingParent);+ }+ if (!isResident(hydrated)) {+ return restartAfterParentChange(hydrated);+ }+ parentState = hydrated;}return parentState;}@@ -2309,26 +2583,35 @@ export class AgentDaemon {parentState: ActiveSessionState,entry: PersistedRlmSubagentRegistryEntry,restoreActiveSessionId?: string,+ clientEnv?: Record<string, string>,): Promise<ActiveSessionState> {+ if (this.updateRestart !== undefined) {+ throw new BoundSessionUnavailableError("Daemon is preparing an update restart");+ }const sessionKey = resolve(entry.sessionFile);const reservation = this.reservingSessionOpens.get(sessionKey);if (reservation) {await reservation;- return this.rehydrateCompletedRlmSubagent(parentState, entry, restoreActiveSessionId);+ return this.rehydrateCompletedRlmSubagent(parentState, entry, restoreActiveSessionId, clientEnv);}const pending = this.openingSessions.get(sessionKey);if (pending) {- return pending;+ const state = await pending;+ if (state.runtime.metadata.kind !== "subagent" || state.runtime.metadata.rlmChildId !== entry.childId) {+ if (this.openingSessions.get(sessionKey) === pending) this.openingSessions.delete(sessionKey);+ return this.rehydrateCompletedRlmSubagent(parentState, entry, restoreActiveSessionId, clientEnv);+ }+ return this.waitForBoundSession(state);}const existing = this.findSessionBySessionFile(entry.sessionFile);- if (existing?.runtime.metadata.kind === "subagent") {+ if (existing?.runtime.metadata.kind === "subagent" && existing.runtime.metadata.rlmChildId === entry.childId) {return this.waitForBoundSession(existing);}const hydration = (async () => {if (existing) {await this.closeSession(existing, "replaced");}- return this.rehydrateCompletedRlmSubagentOnce(parentState, entry, restoreActiveSessionId);+ return this.rehydrateCompletedRlmSubagentOnce(parentState, entry, restoreActiveSessionId, clientEnv);})();// Explicit opens and all lazy triggers share this path-keyed publication,// so no caller can acquire a second lease/runtime while hydration binds.@@ -2360,7 +2643,9 @@ export class AgentDaemon {parentState: ActiveSessionState,entry: PersistedRlmSubagentRegistryEntry,restoreActiveSessionId?: string,+ clientEnv?: Record<string, string>,): Promise<ActiveSessionState> {+ const hydrationEnv = parentState.clientEnv ?? clientEnv;let stateRef: ActiveSessionState | undefined;let runtime: AgentSessionRuntime | undefined;let sessionLease: SessionLease | undefined;@@ -2375,7 +2660,7 @@ export class AgentDaemon {rehydratedModel = resolved;}}- runtime = await withClientEnv(parentState.clientEnv, () =>+ runtime = await withClientEnv(hydrationEnv, () =>createAgentSessionRuntime(this.options.createRuntime, {cwd: sessionManager.getCwd(),agentDir: parentState.runtime.services.agentDir,@@ -2414,9 +2699,14 @@ export class AgentDaemon {},},rlmSessionDir: entry.sessionDir,- rlmDepth: existsSync(entry.sessionFile)- ? resolveSessionRlmDepth(sessionManager.getHeader() ?? {}, entry.sessionFile)- : undefined,+ // Registry depth is authoritative (written at spawn); for legacy entries+ // without it, the shared accessor resolves persisted header depth or the+ // session file's sub- path before the depth-1 default.+ rlmDepth:+ entry.rlmDepth ??+ (existsSync(entry.sessionFile)+ ? resolveSessionRlmDepth(sessionManager.getHeader() ?? {}, entry.sessionFile)+ : 1),rlmMaxDepth: entry.rlmMaxDepth,rlmParentNodeId: entry.rlmParentNodeId ?? entry.childId,},@@ -2439,7 +2729,7 @@ export class AgentDaemon {const state = await this.addRuntime(runtime,undefined,- parentState.clientEnv,+ hydrationEnv,(createdState) => {stateRef = createdState;},@@ -2453,6 +2743,23 @@ export class AgentDaemon {await this.closeSession(state, "replaced");throw new RuntimeOpenCancelledError();}+ if (+ this.sessions.get(parentState.activeSessionId) !== parentState ||+ this.closingSessions.has(parentState.activeSessionId)+ ) {+ const unsubscribeChild = parentState.runtime.session.releaseFinishedRlmChildSession(+ entry.childId,+ runtime.session,+ );+ try {+ await this.closeSession(state, "replaced");+ } finally {+ if (unsubscribeChild) {+ unsubscribeChild();+ }+ }+ throw new RuntimeOpenCancelledError();+ }return state;} catch (error) {if (stateRef && this.sessions.get(stateRef.activeSessionId) === stateRef) {@@ -2962,6 +3269,11 @@ export class AgentDaemon {setImmediate(() => void this.shutdown(0));return;}+ case "worker_passivate_idle_children": {+ const count = await this.passivateIdleChildren(command.idleEvictionMinutes, command.now, command.limit);+ this.writeWorkerSuccess(client, command, { count });+ return;+ }case "worker_deliver_message": {const receipt = await this.sendAgentSessionMessage({targetSelector: command.targetActiveSessionId,@@ -3154,20 +3466,29 @@ export class AgentDaemon {const snapshotSignal = streamsSnapshot? markClientSnapshotStreaming(client, state.activeSessionId): undefined;- state.clients.add(client);- client.attachedActiveSessionIds.add(state.activeSessionId);let result: DaemonAttachResult;+ state.pendingAttaches++;try {result = await this.createAttachResult(client, state, command);+ if (+ this.sessions.get(state.activeSessionId) !== state ||+ this.closingSessions.has(state.activeSessionId)+ ) {+ throw new BoundSessionUnavailableError(+ `Active session ${state.activeSessionId} closed during attach`,+ );+ }} catch (error) {- state.clients.delete(client);- client.attachedActiveSessionIds.delete(state.activeSessionId);removeDaemonClientSessionCapabilities(client, state.activeSessionId);if (streamsSnapshot) {finishClientSnapshotStreaming(client, state.activeSessionId);}throw error;+ } finally {+ state.pendingAttaches--;}+ state.clients.add(client);+ client.attachedActiveSessionIds.add(state.activeSessionId);if (deferClientEnv && clientEnv) {this.updateRestart?.deferredClientEnv.push({ client, state, env: clientEnv });}@@ -4108,13 +4429,23 @@ export class AgentDaemon {...(metadata.rlmChildId ? { childId: metadata.rlmChildId } : {}),}: undefined;- const children = await this.buildRlmChildSnapshotsWithPassiveRlmSubagents(state);+ let session = state.runtime.session;+ let children = await this.buildRlmChildSnapshotsWithPassiveRlmSubagents(state);+ for (+ let retries = 0;+ retries < MAX_SESSION_SNAPSHOT_STABILIZATION_RETRIES && state.runtime.session !== session;+ retries+++ ) {+ session = state.runtime.session;+ children = await this.buildRlmChildSnapshotsWithPassiveRlmSubagents(state);+ }+ session = state.runtime.session;const connectionState = this.createConnectionState(state);return {activeSessionId: state.activeSessionId,summary: summaryForActiveSession(state),state: connectionState,- messages: state.runtime.session.messages,+ messages: session.messages,// Omit duplicate heavy payloads from attach. The client can derive render// context from messages + state, and fetch the full session tree lazily// when the tree/branch selector opens.@@ -4524,8 +4855,9 @@ export class AgentDaemon {targetState = this.getBoundSessionState(targetSelector);} catch (error) {if (error instanceof BoundSessionUnavailableError) {- targetState = await this.waitForBoundSession(this.getSessionState(targetSelector));+ targetState = await this.getOrHydrateBoundSessionState(targetSelector);} else {+ if (error instanceof AmbiguousActiveSessionError) throw error;const passiveSubagent = await this.findPassiveRlmSubagent(targetSelector);if (passiveSubagent) {targetState = await this.hydratePassiveRlmSubagent(passiveSubagent);@@ -4535,7 +4867,7 @@ export class AgentDaemon {state.runtime.metadata.kind === "subagent" && state.runtime.metadata.rlmChildId === targetSelector,);if (hydratingChild) {- targetState = await this.waitForBoundSession(hydratingChild);+ targetState = await this.waitForHydratingChild(hydratingChild, targetSelector);} else if (this.options.worker && options.fromState) {// The supervisor can resolve and wake a saved worker even when it is no longer// present in this worker's resident peer snapshot.@@ -4636,10 +4968,10 @@ export class AgentDaemon {}return response.data as AgentSessionMessageReceipt;} catch (error) {+ lastError = error;if (receivedResponse) {throw error;}- lastError = error;} finally {client.close();}@@ -5060,6 +5392,8 @@ export class AgentDaemon {state: ActiveSessionState,reason: DaemonSessionClosedReason,waitForAbort = true,+ cascadeChildren = true,+ descendantCollector?: Set<ActiveSessionState>,): Promise<void> {this.abortWaitingPromptAdmissionsForSession(state.activeSessionId);for (const client of state.clients) {@@ -5067,16 +5401,93 @@ export class AgentDaemon {}const existingClose = this.closingSessions.get(state.activeSessionId);if (existingClose) {- await existingClose;+ const requestedReason = this.isStrongerCloseReason(reason, existingClose.reason)+ ? reason+ : existingClose.reason;+ let closeError: unknown;+ let closeFailed = false;+ try {+ await existingClose.promise;+ } catch (error) {+ closeError = error;+ closeFailed = true;+ }+ const reasonUpgrade = (existingClose.reasonUpgrade ?? Promise.resolve()).then(() => {+ if (!this.isStrongerCloseReason(requestedReason, existingClose.reason)) return;+ try {+ this.applyReasonUpgrade(state, existingClose.descendants, existingClose.reason, requestedReason);+ } finally {+ existingClose.reason = requestedReason;+ }+ });+ existingClose.reasonUpgrade = reasonUpgrade.catch(() => undefined);+ try {+ await reasonUpgrade;+ } finally {+ descendantCollector?.add(state);+ for (const descendant of existingClose.descendants) descendantCollector?.add(descendant);+ }+ if (closeFailed) throw closeError;return;}- const closePromise = Promise.resolve().then(() => this.closeSessionOnce(state, reason, waitForAbort));- this.closingSessions.set(state.activeSessionId, closePromise);+ const descendants = new Set<ActiveSessionState>();+ const closePromise = Promise.resolve().then(() =>+ this.closeSessionOnce(state, reason, waitForAbort, cascadeChildren, descendants),+ );+ const close = { promise: closePromise, reason, descendants };+ this.closingSessions.set(state.activeSessionId, close);try {await closePromise;} finally {- this.closingSessions.delete(state.activeSessionId);+ descendantCollector?.add(state);+ for (const descendant of descendants) descendantCollector?.add(descendant);+ if (this.closingSessions.get(state.activeSessionId) === close) {+ this.closingSessions.delete(state.activeSessionId);+ }+ }+ }++ private closeReasonStrength(reason: DaemonSessionClosedReason): number {+ if (reason === "killed") return 2;+ if (reason === "completed" || reason === "replaced") return 1;+ return 0;+ }++ private isStrongerCloseReason(candidate: DaemonSessionClosedReason, current: DaemonSessionClosedReason): boolean {+ return this.closeReasonStrength(candidate) > this.closeReasonStrength(current);+ }++ private applyReasonUpgrade(+ state: ActiveSessionState,+ descendants: ReadonlySet<ActiveSessionState>,+ from: DaemonSessionClosedReason,+ to: DaemonSessionClosedReason,+ ): void {+ let persistError: unknown;+ let persistenceFailed = false;+ for (const target of [state, ...descendants]) {+ try {+ if (to === "killed") this.cancelScheduledJobsForSession(target);+ } catch (error) {+ if (!persistenceFailed) persistError = error;+ persistenceFailed = true;+ }+ try {+ if (this.closeKeepsResumeEntry(from)) this.archiveSession(target);+ } catch (error) {+ if (!persistenceFailed) persistError = error;+ persistenceFailed = true;+ }}+ if (persistenceFailed) throw persistError;+ }++ private closeKeepsResumeEntry(reason: DaemonSessionClosedReason): boolean {+ return reason === "shutdown" || reason === "update";+ }++ private archiveSession(state: ActiveSessionState): void {+ state.runtime.session.sessionManager.appendSessionState({ status: "archived" });}private async abortBashForClose(state: ActiveSessionState): Promise<void> {@@ -5094,6 +5505,8 @@ export class AgentDaemon {state: ActiveSessionState,reason: DaemonSessionClosedReason,waitForAbort: boolean,+ cascadeChildren: boolean,+ descendants: Set<ActiveSessionState>,): Promise<void> {if (!this.sessions.has(state.activeSessionId)) {return;@@ -5106,17 +5519,19 @@ export class AgentDaemon {// Abort in-flight status work before any await/dispose so it can't write// agent_status to a session being torn down.this.summarizer.forget(state.activeSessionId);- const cascadeError = await this.closeChildSessions(state, reason, waitForAbort);+ const cascadeError = cascadeChildren+ ? await this.closeChildSessions(state, reason, waitForAbort, descendants)+ : undefined;// Empty draft (no messages, config, or jobs): discard rather than persist an// empty session file. Mirrors the detach-time discard so a config-bearing// draft closed via kill/completed is never wiped.- const keepsResumeEntry = reason === "shutdown" || reason === "update";+ const keepsResumeEntry = this.closeKeepsResumeEntry(reason);const isEmptyDraftSession = !keepsResumeEntry && this.isEmptyDraftContent(state);let persistError: unknown;// Clean shutdown leaves the session un-archived so it stays in the resume list.if (!keepsResumeEntry && !isEmptyDraftSession) {try {- state.runtime.session.sessionManager.appendSessionState({ status: "archived" });+ this.archiveSession(state);} catch (error) {persistError = error;}@@ -5175,11 +5590,13 @@ export class AgentDaemon {parentState: ActiveSessionState,reason: DaemonSessionClosedReason,waitForAbort = true,+ descendants = new Set<ActiveSessionState>(),): Promise<unknown> {let cascadeError: unknown;for (const childState of getChildActiveSessionStates(this.sessions, parentState)) {+ descendants.add(childState);try {- await this.closeSession(childState, reason, waitForAbort);+ await this.closeSession(childState, reason, waitForAbort, true, descendants);} catch (error) {cascadeError ??= error;}@@ -5434,6 +5851,9 @@ export class AgentDaemon {type: "attach",activeSessionId,});+ if (this.sessions.get(activeSessionId) !== state || !state.clients.has(client)) {+ continue;+ }if (client.transport === "private-framed" &&daemonClientCapabilitiesForSession(client, activeSessionId).has("chunked_snapshot")diff --git a/packages/coding-agent/src/modes/daemon/daemon-session-list.ts b/packages/coding-agent/src/modes/daemon/daemon-session-list.tsindex 5ba0a8e93e..533684db30 100644--- a/packages/coding-agent/src/modes/daemon/daemon-session-list.ts+++ b/packages/coding-agent/src/modes/daemon/daemon-session-list.ts@@ -145,8 +145,10 @@ export function buildSessionList(activeSession,savedSession,heartbeatSessionIds.has(activeSession.activeSessionId),- registeredHeartbeatSessionIds.has(activeSession.activeSessionId),- registeredCronSessionIds.has(activeSession.activeSessionId),+ registeredHeartbeatSessionIds.has(activeSession.activeSessionId) ||+ registeredHeartbeatSessionFiles.has(sessionFile),+ registeredCronSessionIds.has(activeSession.activeSessionId) ||+ registeredCronSessionFiles.has(sessionFile),),);seenActiveSessionIds.add(activeSession.activeSessionId);@@ -163,13 +165,17 @@ export function buildSessionList(for (const activeSession of activeSessions) {if (!seenActiveSessionIds.has(activeSession.activeSessionId)) {+ const sessionFile = activeSession.runtime.session.sessionFile;+ const resolvedSessionFile = sessionFile ? resolve(sessionFile) : undefined;entries.push(summaryForActiveSession(activeSession,undefined,heartbeatSessionIds.has(activeSession.activeSessionId),- registeredHeartbeatSessionIds.has(activeSession.activeSessionId),- registeredCronSessionIds.has(activeSession.activeSessionId),+ registeredHeartbeatSessionIds.has(activeSession.activeSessionId) ||+ (resolvedSessionFile !== undefined && registeredHeartbeatSessionFiles.has(resolvedSessionFile)),+ registeredCronSessionIds.has(activeSession.activeSessionId) ||+ (resolvedSessionFile !== undefined && registeredCronSessionFiles.has(resolvedSessionFile)),),);}diff --git a/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts b/packages/coding-agent/src/modes/daemon/daemon-supervisor.tsindex d8546cd5f7..6f284f5158 100644--- a/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts+++ b/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts@@ -127,6 +127,7 @@ const OWNED_WORKER_DISCONNECT_GRACE_MS = 30_000;const IDLE_EVICTION_MAX_SWEEP_INTERVAL_MS = 5 * 60_000;const IDLE_EVICTION_MIN_SWEEP_INTERVAL_MS = 60_000;const IDLE_EVICTION_DRAIN_TIMEOUT_MS = 5_000;+const CHILD_PASSIVATION_PER_WORKER_CAP = 2;const SUPERVISOR_CONFIG_FILE_NAME = "supervisor-config";const WORKER_STARTUP_GATE_FD = 3;@@ -790,7 +791,31 @@ export class DaemonSupervisor {const candidates = [...refreshed].filter((worker) =>canEvictWorker(this.workerEvictionSnapshot(worker), idleEvictionMinutes, now),);- if (candidates.length === 0 || this.shuttingDown || this.updateRestartPhase !== undefined) return;+ if (this.shuttingDown || this.updateRestartPhase !== undefined) return;+ // Whole-tree candidates skip child work because stopWorker releases everything.+ await Promise.all(+ [...refreshed]+ .filter((worker) => !candidates.includes(worker))+ .map(async (worker) => {+ try {+ const response = await worker.client?.requestWorker(+ {+ type: "worker_passivate_idle_children",+ idleEvictionMinutes,+ now,+ limit: CHILD_PASSIVATION_PER_WORKER_CAP,+ },+ 30_000,+ );+ if (response && !response.success) throw new Error(response.error);+ await this.refreshWorkerSummaries(worker);+ } catch (error) {+ refreshed.delete(worker);+ this.log(`Child passivation sweep failed for worker ${worker.descriptor.workerId}: ${String(error)}`);+ }+ }),+ );+ if (this.shuttingDown || this.updateRestartPhase !== undefined) return;let releaseFence: () => void = () => {};const fence = new Promise<void>((resolveFence) => {@@ -2958,7 +2983,8 @@ export class DaemonSupervisor {private findSummaryInWorker(worker: ResidentWorker, selector: string): SessionSummary | undefined {const pathSelector = looksLikeSessionPath(selector) ? canonicalSessionPath(selector) : undefined;- return [...worker.summaries.values()].find((summary) => {+ const summaries = [...worker.summaries.values()];+ const exact = summaries.find((summary) => {const activeSessionId = summary.activeSessionId ?? summary.id;return (activeSessionId === selector ||@@ -2969,6 +2995,13 @@ export class DaemonSupervisor {canonicalSessionPath(summary.sessionFile) === pathSelector));});+ if (exact) return exact;+ return summaries.find((summary) => {+ const activeSessionId = summary.activeSessionId ?? summary.id;+ return (+ matchesSessionIdSuffix(activeSessionId, selector) || matchesSessionIdSuffix(summary.sessionId, selector)+ );+ });}private findWorkerBySessionFile(sessionFile: string): WorkerMatch | undefined {diff --git a/packages/coding-agent/src/modes/daemon/daemon-worker-protocol.ts b/packages/coding-agent/src/modes/daemon/daemon-worker-protocol.tsindex f24e3efec6..c7f1495427 100644--- a/packages/coding-agent/src/modes/daemon/daemon-worker-protocol.ts+++ b/packages/coding-agent/src/modes/daemon/daemon-worker-protocol.ts@@ -4,6 +4,7 @@ import type {AgentSessionMessageDeliveryMode,AgentSessionMessageSender,} from "../../core/agent-messages.js";+import type { IdleEvictionMinutes } from "../../core/session-action-store.js";export { SESSION_LEASE_OWNER_ID_ENV, SESSION_LEASES_ENABLED_ENV } from "../../core/session-lease.js";@@ -57,6 +58,13 @@ export type DaemonWorkerCommand =| { id?: string; type: "worker_unsubscribe"; activeSessionId: string }| { id?: string; type: "worker_sync_agent_peers"; peers: AgentSessionMessageAgentSummary[] }| { id?: string; type: "worker_archive_and_shutdown" }+ | {+ id?: string;+ type: "worker_passivate_idle_children";+ idleEvictionMinutes: IdleEvictionMinutes;+ now: number;+ limit: number;+ }| {id?: string;type: "worker_deliver_message";diff --git a/packages/coding-agent/src/modes/interactive/components/settings-selector.ts b/packages/coding-agent/src/modes/interactive/components/settings-selector.tsindex 3f8c757658..3805cc4228 100644--- a/packages/coding-agent/src/modes/interactive/components/settings-selector.ts+++ b/packages/coding-agent/src/modes/interactive/components/settings-selector.ts@@ -203,6 +203,11 @@ export class SettingsSelectorComponent extends Container {super();let currentWarnings = { ...config.warnings };+ const idleEvictionValues = [30, 60, 90, 180, 360];+ if (typeof config.idleEvictionMinutes === "number" && !idleEvictionValues.includes(config.idleEvictionMinutes)) {+ idleEvictionValues.push(config.idleEvictionMinutes);+ idleEvictionValues.sort((a, b) => a - b);+ }const items: SettingItem[] = [{@@ -217,7 +222,7 @@ export class SettingsSelectorComponent extends Container {label: "Idle worker eviction",description: "Stop fully idle agent trees after this many minutes (global daemon policy)",currentValue: String(config.idleEvictionMinutes),- values: ["off", "30", "60", "90", "180", "360"],+ values: ["off", ...idleEvictionValues.map(String)],},{id: "steering-mode",@@ -451,7 +456,7 @@ export class SettingsSelectorComponent extends Container {callbacks.onAutoCompactChange(newValue === "true");break;case "idle-eviction-minutes":- callbacks.onIdleEvictionMinutesChange(newValue === "off" ? "off" : parseInt(newValue, 10));+ callbacks.onIdleEvictionMinutesChange(newValue === "off" ? "off" : Number(newValue));break;case "show-images":callbacks.onShowImagesChange(newValue === "true");diff --git a/packages/coding-agent/src/modes/interactive/interactive-mode.ts b/packages/coding-agent/src/modes/interactive/interactive-mode.tsindex 5b3ff9f1ee..823ded1f46 100644--- a/packages/coding-agent/src/modes/interactive/interactive-mode.ts+++ b/packages/coding-agent/src/modes/interactive/interactive-mode.ts@@ -3280,7 +3280,7 @@ export class InteractiveMode {}private updateWorkingPulse(): void {- const active = this.isAgentStreaming() || this.countRunningSubagents() > 0;+ const active = this.isAgentStreaming();if (!active) {this.stopWorkingPulse();return;@@ -3304,16 +3304,6 @@ export class InteractiveMode {}}- private countRunningSubagents(): number {- let count = 0;- for (const child of this.subagentSnapshots.values()) {- if (child.status === "running") {- count += 1;- }- }- return count;- }-private shouldShowWorkingLoader(): boolean {// Background subagents (agent turn done, asyncio tasks still running) would// otherwise show a textless spinner; the subagent tree above the loader carries@@ -5804,16 +5794,14 @@ export class InteractiveMode {}private seedSubagentSummary(children: readonly AgentConnectionRlmChildAgentSnapshot[] | undefined): void {- let changed = false;for (const child of children ?? []) {// Live updates can arrive before the initial snapshot; do not replace them// with the snapshot's older state.if (!this.subagentSnapshots.has(child.id) && child.status !== "cancelled") {this.subagentSnapshots.set(child.id, child);- changed = true;}}- if (changed) this.refreshSubagentSummary();+ this.refreshSubagentSummary();}private replaceSubagentSummary(children: readonly AgentConnectionRlmChildAgentSnapshot[] | undefined): void {diff --git a/packages/coding-agent/test/agent-session-recursion.test.ts b/packages/coding-agent/test/agent-session-recursion.test.tsindex c89673ea29..53bfa57e29 100644--- a/packages/coding-agent/test/agent-session-recursion.test.ts+++ b/packages/coding-agent/test/agent-session-recursion.test.ts@@ -1,5 +1,6 @@+import { spawnSync } from "node:child_process";import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";-import { tmpdir } from "node:os";+import { homedir, tmpdir } from "node:os";import { basename, dirname, join } from "node:path";import { setTimeout as sleep } from "node:timers/promises";import { Agent, type StreamFn } from "@earendil-works/pi-agent-core";@@ -24,7 +25,7 @@ import {type SubagentRuntimeHost,} from "../src/core/rlm-runtime.js";import { SessionManager } from "../src/core/session-manager.js";-import { SettingsManager } from "../src/core/settings-manager.js";+import { SettingsManager, type SettingsStorage } from "../src/core/settings-manager.js";import type { Skill } from "../src/core/skills.js";import { createSyntheticSourceInfo } from "../src/core/source-info.js";import { createTestResourceLoader } from "./utilities.js";@@ -296,6 +297,24 @@ describe("AgentSession rlm recursion", () => {}});+ it.each([-1, "0"])("ignores invalid persisted RLM depth %j", (invalidDepth) => {+ const persistedManager = SessionManager.create(tempDir, join(tempDir, "invalid-depth-sessions"));+ persistedManager.newSession({ rlmDepth: 2 });+ persistedManager.flushNow();+ const sessionFile = persistedManager.getSessionFile();+ if (!sessionFile) throw new Error("Missing persisted session file");+ const lines = readFileSync(sessionFile, "utf8").split("\n");+ lines[0] = JSON.stringify({ ...JSON.parse(lines[0] ?? "{}"), rlmDepth: invalidDepth });+ writeFileSync(sessionFile, lines.join("\n"));+ const reopened = SessionManager.open(sessionFile, join(tempDir, "invalid-depth-sessions"));+ vi.stubEnv("RLM_DEPTH", "1");+ try {+ expect(createSession({ maxDepth: 2, sessionManager: reopened }).rlmDepth).toBe(1);+ } finally {+ vi.unstubAllEnvs();+ }+ });+it("keeps a forked root at depth zero so recursion remains allowed", async () => {const source = SessionManager.create(tempDir, join(tempDir, "source-sessions"));source.newSession({ rlmDepth: 0 });@@ -657,7 +676,7 @@ describe("AgentSession rlm recursion", () => {});const expected = {rlm_child_id: "passive-child",- active_session_id: null,+ active_session_id: "passive-session",session_id: "passive-session",session_name: "passive-worker",session_dir: join(tempDir, "passive-child"),@@ -670,6 +689,53 @@ describe("AgentSession rlm recursion", () => {expect(await root.listRlmSubagents()).toEqual({ subagents: [] });});+ it("coalesces concurrent deletion of the same passive daemon child", async () => {+ let releaseListing!: () => void;+ const listingGate = new Promise<void>((resolve) => {+ releaseListing = resolve;+ });+ const deleteRlmSubagentRuntime = vi.fn(async () => {});+ const root = createSession({+ agentMessageController: {+ listAgents: async () => {+ await listingGate;+ return {+ current: { activeSessionId: "parent-active", sessionId: "parent-session" },+ agents: [+ {+ activeSessionId: "passive-session",+ sessionId: "passive-session",+ sessionName: "passive-worker",+ runtimeKind: "subagent" as const,+ 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 first = root.deleteRlmSubagent("passive-worker");+ const second = root.deleteRlmSubagent("passive-worker");+ releaseListing();+ await expect(Promise.all([first, second])).resolves.toHaveLength(2);+ expect(deleteRlmSubagentRuntime).toHaveBeenCalledOnce();+ });+it("disposes an inline child when setting its session name fails", async () => {const root = createSession();const appendSessionInfo = vi.spyOn(SessionManager.prototype, "appendSessionInfo").mockImplementation(() => {@@ -717,7 +783,8 @@ describe("AgentSession rlm recursion", () => {releaseChild = resolve;});let childStarted = false;- const root = createSession({+ let root: AgentSession;+ root = createSession({streamFn: (_model, context) => {const text = userText(context);const stream = createAssistantMessageEventStream();@@ -727,6 +794,32 @@ describe("AgentSession rlm recursion", () => {});return stream;},+ agentMessageController: {+ listAgents: () => {+ const run = [...(root as unknown as InspectableRlmSession)._activeRlmChildRuns.values()][0];+ return {+ current: { activeSessionId: "parent-active", sessionId: root.sessionId },+ agents: run?.session+ ? [+ {+ activeSessionId: "running-active",+ sessionId: run.session.sessionId,+ runtimeKind: "subagent" as const,+ cwd: tempDir,+ isStreaming: true,+ unfinishedActionCount: 0,+ parentActiveSessionId: "parent-active",+ rlmChildId: run.id,+ sessionDir: run.sessionDir,+ },+ ]+ : [],+ };+ },+ sendAgentMessage: async () => {+ throw new Error("unexpected send");+ },+ },});const recaps: Array<string | undefined> = [];@@ -746,7 +839,7 @@ describe("AgentSession rlm recursion", () => {subagents: [{rlm_child_id: rootRun.id,- active_session_id: null,+ active_session_id: "running-active",session_id: rootRun.session.sessionId,session_name: createDefaultRlmSubagentSessionName("slow shard", rootRun.id),session_dir: rootRun.sessionDir,@@ -962,6 +1055,118 @@ describe("AgentSession rlm recursion", () => {existing.dispose();});+ it("does not claim a failed global max-depth write was saved", async () => {+ const globalSettings = JSON.stringify({ rlmMaxDepth: 1 });+ const storage: SettingsStorage = {+ withLock(scope, update) {+ const current = scope === "global" ? globalSettings : undefined;+ const next = update(current);+ if (scope === "global" && next !== undefined) {+ throw new Error("EROFS: read-only file system");+ }+ },+ };+ const current = createSession({ settingsManager: SettingsManager.fromStorage(storage) });++ const result = await current.setRlmMaxDepth(5, { global: true });++ expect(result).toMatchObject({ maxDepth: 5, source: "chat", globalSaved: false });+ expect(result.globalError).toContain("EROFS: read-only file system");+ expect(SettingsManager.fromStorage(storage).getRlmMaxDepth()).toBe(1);+ expect(globalSettings).toBe(JSON.stringify({ rlmMaxDepth: 1 }));+ });++ it("does not attribute stale errors to a successful global max-depth write", async () => {+ const writes: Record<"global" | "project", string | undefined> = {+ global: JSON.stringify({ rlmMaxDepth: 1 }),+ project: undefined,+ };+ let failGlobal = true;+ let failProject = true;+ const storage: SettingsStorage = {+ withLock(scope, update) {+ const next = update(writes[scope]);+ if (scope === "global" && failGlobal && next !== undefined) {+ throw new Error("stale global failure");+ }+ if (scope === "project" && failProject && next !== undefined) {+ throw new Error("project warning");+ }+ writes[scope] = next;+ },+ };+ const settingsManager = SettingsManager.fromStorage(storage);+ settingsManager.setDefaultModelAndProvider("provider", "model");+ await settingsManager.flush();+ settingsManager.setProjectExtensionPaths(["broken-project-extension"]);+ await settingsManager.flush();+ // Preserve the queued project diagnostic while recovering the global store.+ failGlobal = false;+ failProject = false;+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});+ const current = createSession({ settingsManager });++ const result = await current.setRlmMaxDepth(5, { global: true });++ expect(result).toMatchObject({ maxDepth: 5, source: "chat", globalSaved: true });+ expect(warn).toHaveBeenCalledWith("Warning: Earlier global settings write failed: stale global failure");+ expect(settingsManager.drainErrors()).toMatchObject([+ { scope: "project", error: { message: "project warning" } },+ ]);+ expect(JSON.parse(writes.global ?? "{}")).toMatchObject({ rlmMaxDepth: 5 });+ warn.mockRestore();+ });++ it("rolls back max-depth state when chat persistence fails", async () => {+ const root = createSession();+ const originalPrompt = root.systemPrompt;+ const flush = vi.spyOn(root.sessionManager, "flushNow").mockImplementation(() => {+ throw new Error("disk full");+ });++ await expect(root.setRlmMaxDepth(0)).rejects.toThrow("disk full");+ expect(root.rlmMaxDepth).toBe(1);+ expect(root.systemPrompt).toBe(originalPrompt);+ expect(+ root.sessionManager+ .getBranch()+ .some((entry) => entry.type === "custom" && entry.customType === "rlm_max_depth_state"),+ ).toBe(false);++ flush.mockRestore();+ root.sessionManager.flushNow();+ expect(readFileSync(root.sessionFile!, "utf8")).not.toContain('"customType":"rlm_max_depth_state"');+ });+ it("falls through an invalid global max depth while navigating off a chat override", async () => {+ const original = createSession();+ await original.prompt("baseline branch");+ await original.agent.waitForIdle();+ const baselineLeafId = original.sessionManager.getLeafId();+ if (!baselineLeafId) throw new Error("Missing baseline branch leaf");+ await original.setRlmMaxDepth(2);+ const sessionFile = original.sessionFile;+ if (!sessionFile) throw new Error("Missing persisted session file");+ original.dispose();++ vi.stubEnv("RLM_MAX_DEPTH", "0");+ try {+ const resumed = createSession({+ sessionManager: SessionManager.open(sessionFile, join(tempDir, "sessions")),+ settingsManager: SettingsManager.inMemory({ rlmMaxDepth: -1 }),+ });+ expect(resumed.rlmMaxDepth).toBe(2);++ await expect(resumed.navigateTree(baselineLeafId, { summarize: false })).resolves.toMatchObject({+ cancelled: false,+ });+ expect(resumed.sessionManager.getLeafId()).toBe(baselineLeafId);+ expect(resumed.rlmMaxDepth).toBe(0);+ expect(resumed.systemPrompt).not.toContain("A callable `rlm`");+ } finally {+ vi.unstubAllEnvs();+ }+ });+it("keeps a spawned child's chat override when reconstructed with its inherited config", async () => {const root = createSession({ maxDepth: 2 });const childResult = await root.runRlmChild("child with a durable override");@@ -1004,6 +1209,24 @@ describe("AgentSession rlm recursion", () => {expect(child.rlmMaxDepth).toBe(3);});+ it("lets a stale kernel depth cap defer to the live host gate", () => {+ const python =+ process.env.PRIME_AGENT_KERNEL_PYTHON ?? join(homedir(), ".prime", "agent", "kernel-venv", "bin", "python");+ const runtime = join(process.cwd(), "..", "..", "prime-agent-runtime", "src");+ const probe = spawnSync(+ python,+ ["-c", "import asyncio, rlm; rlm.Comm = None; asyncio.run(rlm.run('raised live cap'))"],+ {+ env: { ...process.env, PYTHONPATH: runtime, RLM_DEPTH: "1", RLM_MAX_DEPTH: "1" },+ encoding: "utf8",+ },+ );++ expect(probe.status).not.toBe(0);+ expect(probe.stderr).toContain("Jupyter comm support is unavailable in this kernel");+ expect(probe.stderr).not.toContain("RLM recursion depth limit reached");+ });+it("rejects child creation at the configured recursion depth cap", async () => {const root = createSession({ depth: 1, maxDepth: 1 });diff --git a/packages/coding-agent/test/agents-view-mode.test.ts b/packages/coding-agent/test/agents-view-mode.test.tsindex 617a1b1c14..aa2c65a7b9 100644--- a/packages/coding-agent/test/agents-view-mode.test.ts+++ b/packages/coding-agent/test/agents-view-mode.test.ts@@ -1,7 +1,9 @@-import { afterEach, describe, expect, it, vi } from "vitest";+import { setKeybindings } from "@earendil-works/pi-tui";+import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";+import { KeybindingsManager } from "../src/core/keybindings.js";import type { ModelRegistry } from "../src/core/model-registry.js";import { SettingsManager } from "../src/core/settings-manager.js";-import { DaemonAgentConnection } from "../src/modes/agent-connection/daemon-agent-connection.js";+import type { AgentConnectionSavedSessionInfo } from "../src/modes/agent-connection/types.js";import {AgentsViewMode,type AgentsViewPersistentState,@@ -9,22 +11,59 @@ import {createInitialAgentsViewPersistentState,runAgentsViewMode,} from "../src/modes/agents-view/agents-view-mode.js";-import { DaemonClient } from "../src/modes/daemon/daemon-client.js";+import { resolveAgentsViewLeftResult } from "../src/modes/agents-view/agents-view-state.js";import type { SessionSummary } from "../src/modes/daemon/daemon-session-list.js";-import { InteractiveMode } from "../src/modes/interactive/interactive-mode.js";import type { InteractiveModeUiServices } from "../src/modes/interactive/interactive-mode-services.js";import { stopThemeWatcher } from "../src/modes/interactive/theme/theme.js";+const modeMocks = vi.hoisted(() => ({+ interactiveRun: vi.fn<() => Promise<never>>(),+ teardownSessionUi: vi.fn(async () => undefined),+ dispose: vi.fn(async () => undefined),+ clientRequest: vi.fn<() => Promise<unknown>>(),+}));++vi.mock("../src/config.js", async (importOriginal) => {+ const actual = await importOriginal<typeof import("../src/config.js")>();+ return { ...actual, appendRotatingLog: vi.fn() };+});++vi.mock("../src/modes/daemon/daemon-client.js", () => ({+ DaemonClient: class {+ connect = vi.fn(async () => undefined);+ close = vi.fn();+ request = modeMocks.clientRequest;+ },+ getDaemonSocketCloseReason: vi.fn(),+}));++vi.mock("../src/modes/agent-connection/daemon-agent-connection.js", () => ({+ DaemonAgentConnection: Object.assign(function DaemonAgentConnection() {}, {+ attach: vi.fn(async () => ({ dispose: modeMocks.dispose })),+ }),+}));++vi.mock("../src/modes/interactive/interactive-mode.js", async (importOriginal) => {+ const actual = await importOriginal<typeof import("../src/modes/interactive/interactive-mode.js")>();+ return {+ ...actual,+ InteractiveMode: class {+ run = modeMocks.interactiveRun;+ teardownSessionUi = modeMocks.teardownSessionUi;+ },+ };+});+function summary(overrides: Partial<SessionSummary> = {}): SessionSummary {return {- id: "root-active",- activeSessionId: "root-active",+ id: "scope-active",+ activeSessionId: "scope-active",lifecycle: "live",activity: "idle",- isSessionActive: true,- runtimeKind: "top-level",- sessionId: "root-session",- cwd: process.cwd(),+ isSessionActive: false,+ sessionId: "scope-session",+ sessionFile: "/tmp/scope.jsonl",+ cwd: "/tmp",isStreaming: false,isCompacting: false,attachedClients: 0,@@ -34,28 +73,24 @@ function summary(overrides: Partial<SessionSummary> = {}): SessionSummary {};}-function createUiServices(): InteractiveModeUiServices {- return {- settingsManager: SettingsManager.inMemory({ theme: "dark" }),- modelRegistry: {} as ModelRegistry,- getInitialCwd: () => process.cwd(),- getInitialSessionName: () => undefined,- getThemes: () => [],- };-}-function invoke(method: string, self: object, ...args: unknown[]): unknown {- const member = Reflect.get(AgentsViewMode.prototype, method) as ((...args: unknown[]) => unknown) | undefined;+ const member = Reflect.get(AgentsViewMode.prototype, method) as ((...a: unknown[]) => unknown) | undefined;if (typeof member !== "function") throw new Error(`AgentsViewMode.${method} no longer exists`);return member.call(self, ...args);}-afterEach(() => {- vi.restoreAllMocks();- stopThemeWatcher();-});+const settingsManager = {+ getTheme: () => "dark",+ getShowHardwareCursor: () => false,+ getClearOnShrink: () => false,+ getEditorPaddingX: () => 0,+ getAutocompleteMaxVisible: () => 5,+};++describe("AgentsViewMode", () => {+ beforeAll(() => setKeybindings(new KeybindingsManager()));+ beforeEach(() => vi.clearAllMocks());-describe("AgentsViewMode search selection", () => {it("keeps the selection chosen by row rebuilding when the query changes", () => {const self = {editor: { getText: () => "matching query" },@@ -66,12 +101,267 @@ describe("AgentsViewMode search selection", () => {ui: { requestRender: vi.fn() },};- (AgentsViewMode.prototype as unknown as { queryChanged(this: typeof self): void }).queryChanged.call(self);+ invoke("queryChanged", self);expect(self.persistentState.query).toBe("matching query");expect(self.rebuildRows).toHaveBeenCalledOnce();expect(self.selectedIndex).toBe(4);});++ it("uses the opened session as the crash-path back target", async () => {+ const opened = summary({ sessionName: "opened" });+ const previous = summary({ id: "previous", activeSessionId: "previous", sessionId: "previous" });+ const runView = vi+ .spyOn(AgentsViewMode.prototype, "run")+ .mockResolvedValueOnce({ type: "open", summary: opened })+ .mockImplementationOnce(function (this: AgentsViewMode) {+ const state = (this as unknown as { persistentState: AgentsViewPersistentState }).persistentState;+ expect(state.backSession).toMatchObject({ sessionId: opened.sessionId });+ return Promise.resolve({ type: "exit" });+ });+ modeMocks.interactiveRun.mockRejectedValueOnce(new Error("post-attach crash"));++ await runAgentsViewMode({+ socketPath: "/tmp/fake-daemon.sock",+ config: { cwd: "/tmp" } as never,+ initialSession: previous,+ uiServices: {+ settingsManager: settingsManager as never,+ modelRegistry: {} as never,+ getInitialCwd: () => "/tmp",+ getInitialSessionName: () => undefined,+ getThemes: () => [],+ },+ });++ expect(modeMocks.teardownSessionUi).toHaveBeenCalledWith({ preserveAltScreen: true });+ expect(modeMocks.dispose).toHaveBeenCalledOnce();+ runView.mockRestore();+ });++ it("invalidates the persisted scope root after popping a scope frame", async () => {+ const parent = summary({ id: "parent", activeSessionId: "parent", sessionId: "parent" });+ const child = summary({ id: "child", activeSessionId: "child", sessionId: "child" });+ const runView = vi+ .spyOn(AgentsViewMode.prototype, "run")+ .mockImplementationOnce(function (this: AgentsViewMode) {+ const state = (this as unknown as { persistentState: AgentsViewPersistentState }).persistentState;+ state.scopeFrames = [+ { scope: { sessionId: parent.sessionId, activeSessionId: parent.activeSessionId } },+ { scope: { sessionId: child.sessionId, activeSessionId: child.activeSessionId } },+ ];+ state.scopeRootSummary = child;+ return Promise.resolve({+ type: "scope_back",+ selection: child,+ expandedAncestorSessionIds: [],+ hasChildren: false,+ });+ })+ .mockImplementationOnce(function (this: AgentsViewMode) {+ const state = (this as unknown as { persistentState: AgentsViewPersistentState }).persistentState;+ expect(state.scopeFrames).toHaveLength(1);+ expect(state.scopeRootSummary).toBeUndefined();+ return Promise.resolve({ type: "exit" });+ });++ await runAgentsViewMode({+ config: { cwd: "/tmp" } as never,+ uiServices: {+ settingsManager: settingsManager as never,+ modelRegistry: {} as never,+ getInitialCwd: () => "/tmp",+ getInitialSessionName: () => undefined,+ getThemes: () => [],+ },+ });++ runView.mockRestore();+ });++ it("invalidates the persisted scope root after pushing a scope frame", async () => {+ const parent = summary({ id: "parent", activeSessionId: "parent", sessionId: "parent" });+ const child = summary({ id: "child", activeSessionId: "child", sessionId: "child" });+ const runView = vi+ .spyOn(AgentsViewMode.prototype, "run")+ .mockImplementationOnce(function (this: AgentsViewMode) {+ const state = (this as unknown as { persistentState: AgentsViewPersistentState }).persistentState;+ state.scopeFrames = [{ scope: { sessionId: parent.sessionId, activeSessionId: parent.activeSessionId } }];+ state.scopeRootSummary = parent;+ return Promise.resolve({ type: "open", summary: child });+ })+ .mockImplementationOnce(function (this: AgentsViewMode) {+ const state = (this as unknown as { persistentState: AgentsViewPersistentState }).persistentState;+ expect(state.scopeFrames).toHaveLength(2);+ expect(state.scopeRootSummary).toBeUndefined();+ return Promise.resolve({ type: "exit" });+ });+ modeMocks.interactiveRun.mockResolvedValueOnce({+ type: "scoped_agents_view",+ source: {+ activeSessionId: child.activeSessionId,+ sessionFile: child.sessionFile,+ sessionId: child.sessionId,+ sessionName: child.sessionName,+ cwd: child.cwd,+ },+ } as never);++ await runAgentsViewMode({+ socketPath: "/tmp/fake-daemon.sock",+ config: { cwd: "/tmp" } as never,+ uiServices: {+ settingsManager: settingsManager as never,+ modelRegistry: {} as never,+ getInitialCwd: () => "/tmp",+ getInitialSessionName: () => undefined,+ getThemes: () => [],+ },+ });++ runView.mockRestore();+ });++ it("does not discard scope while the saved-session refresh is in flight", async () => {+ let finishRefresh: ((value: { success: true; data: { sessions: unknown[] } }) => void) | undefined;+ const request = vi.fn(+ () =>+ new Promise<{ success: true; data: { sessions: unknown[] } }>((resolve) => {+ finishRefresh = resolve;+ }),+ );+ const scopeSummary = summary();+ const persistentState: AgentsViewPersistentState = {+ scopeFrames: [{ scope: { sessionId: scopeSummary.sessionId, activeSessionId: scopeSummary.activeSessionId } }],+ };+ const self: Record<string, unknown> = {+ options: { config: { cwd: "/tmp" } },+ persistentState,+ savedCatalogGeneration: 0,+ savedCatalogReady: true,+ savedCatalogRefreshPending: false,+ lastSuccessfulSavedSessions: [],+ savedSessions: [],+ requireClient: () => ({ request }),+ getSavedSessionCatalogContext: () => ({ cwd: "/tmp" }),+ reconcileCatalogs: vi.fn(),+ resolveMissingSelectionAnchor: vi.fn(),+ };++ const refresh = invoke("refreshSavedSessions", self) as Promise<boolean>;+ await vi.waitFor(() => expect(request).toHaveBeenCalledOnce());+ expect(self.savedCatalogReady).toBe(false);++ Object.assign(self, {+ lastListedSummaries: [],+ heartbeats: [],+ inactiveAgentIdentities: new Set(),+ pendingDeleteAgent: undefined,+ liveCatalogReady: true,+ liveCatalogRefreshPending: false,+ scopeKey: persistentState.scopeFrames?.[0]?.scope,+ expandedSubagentParents: new Set(),+ programShownParents: new Set(),+ editor: { getText: () => "" },+ getFilteredRecords: () => Reflect.get(self, "scopedRecords"),+ applyPendingAncestorExpansion: vi.fn(),+ restoreSelection: vi.fn(),+ ui: { requestRender: vi.fn() },+ setStatusMessage: vi.fn(),+ withPendingDeleteSession: (sessions: SessionSummary[]) => sessions,+ });+ self.reconcileCatalogs = () => invoke("reconcileCatalogs", self);+ invoke("reconcileCatalogs", self);+ expect(persistentState.scopeFrames).toHaveLength(1);++ const saved: AgentConnectionSavedSessionInfo = {+ path: "/tmp/scope.jsonl",+ id: "scope-session",+ cwd: "/tmp",+ created: new Date("2026-01-01T00:00:00Z"),+ modified: new Date("2026-01-01T00:00:00Z"),+ messageCount: 1,+ firstMessage: "scope",+ allMessagesText: "scope",+ };+ finishRefresh?.({+ success: true,+ data: {+ sessions: [+ {+ ...saved,+ created: saved.created.toISOString(),+ modified: saved.modified.toISOString(),+ },+ ],+ },+ });+ await expect(refresh).resolves.toBe(true);+ expect(persistentState.scopeFrames).toHaveLength(1);+ });++ it("carries the resolved scope root across view remounts", () => {+ const root = summary({ sessionName: "Scoped root" });+ const persistentState: AgentsViewPersistentState = {+ scopeFrames: [{ scope: { sessionId: root.sessionId, activeSessionId: root.activeSessionId } }],+ };+ const self: Record<string, unknown> = {+ persistentState,+ lastListedSummaries: [root],+ savedSessions: [],+ heartbeats: [],+ inactiveAgentIdentities: new Set(),+ pendingDeleteAgent: undefined,+ liveCatalogReady: true,+ savedCatalogReady: true,+ scopeKey: persistentState.scopeFrames?.[0]?.scope,+ expandedSubagentParents: new Set(),+ programShownParents: new Set(),+ editor: { getText: () => "" },+ getFilteredRecords: () => Reflect.get(self, "scopedRecords"),+ applyPendingAncestorExpansion: vi.fn(),+ restoreSelection: vi.fn(),+ ui: { requestRender: vi.fn() },+ setStatusMessage: vi.fn(),+ withPendingDeleteSession: (sessions: SessionSummary[]) => sessions,+ };+ invoke("reconcileCatalogs", self);+ expect(persistentState.scopeRootSummary).toMatchObject({ sessionId: root.sessionId });++ const remount = new AgentsViewMode(+ {+ config: { cwd: "/tmp" } as never,+ uiServices: {+ settingsManager: settingsManager as never,+ modelRegistry: {} as never,+ getInitialCwd: () => "/tmp",+ getInitialSessionName: () => undefined,+ getThemes: () => [],+ },+ },+ persistentState,+ ) as AgentsViewMode & Record<string, unknown>;+ const remountedRoot = Reflect.get(remount, "scopeRootSummary") as SessionSummary;+ expect(remountedRoot).toMatchObject({ sessionName: "Scoped root" });+ expect(resolveAgentsViewLeftResult(remountedRoot)).toMatchObject({+ type: "scope_back",+ selection: { sessionId: root.sessionId },+ });+ });+});++function createUiServices(): InteractiveModeUiServices {+ return {+ settingsManager: SettingsManager.inMemory({ theme: "dark" }),+ modelRegistry: {} as ModelRegistry,+ getInitialCwd: () => process.cwd(),+ getInitialSessionName: () => undefined,+ getThemes: () => [],+ };+}++afterEach(() => {+ vi.restoreAllMocks();});describe("AgentsViewMode persistent catalog state", () => {@@ -103,7 +393,14 @@ describe("AgentsViewMode persistent catalog state", () => {});it("keeps a live-only scope after a fresh instance's first live poll fails", async () => {- const root = summary();+ const root = summary({+ id: "root-active",+ activeSessionId: "root-active",+ isSessionActive: true,+ runtimeKind: "top-level",+ sessionId: "root-session",+ cwd: process.cwd(),+ });const persistentState: AgentsViewPersistentState = {scopeFrames: [{ scope: { sessionId: root.sessionId, activeSessionId: root.activeSessionId } }],lastSuccessfulLiveSummaries: [root],@@ -187,12 +484,7 @@ describe("AgentsViewMode persistent catalog state", () => {expect(persistentState.scopeFrames).toEqual([{ scope, returnChat: returnedRoot }]);return { type: "exit" };});- vi.spyOn(DaemonClient.prototype, "connect").mockResolvedValue();- vi.spyOn(DaemonAgentConnection, "attach").mockResolvedValue({- dispose: vi.fn(async () => {}),- onBeforeSessionInvalidate: vi.fn(),- } as unknown as DaemonAgentConnection);- vi.spyOn(InteractiveMode.prototype, "run").mockResolvedValue({+ modeMocks.interactiveRun.mockResolvedValue({type: "scoped_agents_view",source: {activeSessionId: root.activeSessionId!,@@ -200,7 +492,7 @@ describe("AgentsViewMode persistent catalog state", () => {sessionName: returnedRoot.sessionName,cwd: root.cwd,},- });+ } as never);await runAgentsViewMode({config: { cwd: process.cwd() },@@ -246,25 +538,20 @@ describe("agents view startup notices", () => {});return { type: "exit" };});- vi.spyOn(DaemonClient.prototype, "connect").mockResolvedValue();- vi.spyOn(DaemonClient.prototype, "request").mockResolvedValue({+ modeMocks.clientRequest.mockResolvedValue({type: "response",command: "create",success: true,data: { ...root, cwd: process.cwd(), activeSessionId: "resumed-active", lifecycle: "live" },});- vi.spyOn(DaemonAgentConnection, "attach").mockResolvedValue({- dispose: vi.fn(async () => {}),- onBeforeSessionInvalidate: vi.fn(),- } as unknown as DaemonAgentConnection);- vi.spyOn(InteractiveMode.prototype, "run").mockResolvedValue({+ modeMocks.interactiveRun.mockResolvedValue({type: "agents_view",source: {activeSessionId: "resumed-active",sessionId: root.sessionId,cwd: process.cwd(),},- });+ } as never);await runAgentsViewMode({config: { cwd: process.cwd() },diff --git a/packages/coding-agent/test/daemon-extension-binding.test.ts b/packages/coding-agent/test/daemon-extension-binding.test.tsindex 182ff24116..c71f4ba565 100644--- a/packages/coding-agent/test/daemon-extension-binding.test.ts+++ b/packages/coding-agent/test/daemon-extension-binding.test.ts@@ -120,6 +120,7 @@ describe("daemon extension binding", () => {activeSessionId: "active-slim",runtime,clients: new Set(),+ pendingAttaches: 0,extensionUiRequests: new Map(),eventGeneration: "generation-slim",lastEventSequence: 0,@@ -193,6 +194,7 @@ describe("daemon extension binding", () => {activeSessionId: "active-test",runtime,clients: new Set(),+ pendingAttaches: 0,extensionUiRequests: new Map(),eventGeneration: "generation-test",lastEventSequence: 0,diff --git a/packages/coding-agent/test/daemon-mode.test.ts b/packages/coding-agent/test/daemon-mode.test.tsindex 91a5afd71c..179a5fb282 100644--- a/packages/coding-agent/test/daemon-mode.test.ts+++ b/packages/coding-agent/test/daemon-mode.test.ts@@ -33,9 +33,11 @@ import {createDaemonCommandEnvelope,DAEMON_PROTOCOL_INFO,DAEMON_SCHEMA_ID,+ DAEMON_SCHEMA_REVISION,type DaemonAttachResult,type DaemonCommand,type DaemonOutbound,+ failure,} from "../src/modes/daemon/daemon-protocol.js";import type { SessionSummary } from "../src/modes/daemon/daemon-session-list.js";import { DAEMON_WORKER_SUPERVISOR_SOCKET_ENV } from "../src/modes/daemon/daemon-worker-protocol.js";@@ -484,6 +486,58 @@ describe("daemon mode helpers", () => {}});+ it("persists explicit child depth for an in-memory daemon parent", async () => {+ const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-daemon-in-memory-parent-depth-"));+ try {+ 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: join(tempDir, "sessions") },+ createRuntime,+ });+ const internals = daemon as unknown as {+ createRuntime(command: Extract<DaemonCommand, { type: "create" }>): Promise<ActiveSessionState>;+ createRlmSubagentRuntime(+ parentState: ActiveSessionState,+ options: CreateRlmSubagentRuntimeOptions,+ ): Promise<ActiveSessionState["runtime"]>;+ };+ const parentState = await internals.createRuntime({ type: "create", noSession: true });+ const child = await internals.createRlmSubagentRuntime(parentState, {+ parentSession: parentState.runtime.session,+ id: "child-1",+ prompt: "persist depth",+ sessionName: "depth-child",+ sessionDir: join(tempDir, "child"),+ model: {} as Model<Api>,+ thinkingLevel: "off",+ serviceTier: null,+ scopedModels: [],+ activeToolNames: [],+ customTools: [],+ includeGoals: false,+ includeCompactSkill: false,+ rlmDepth: 1,+ rlmMaxDepth: 2,+ rlmParentNodeId: "child-1",+ });++ expect(parentState.runtime.session.sessionFile).toBeUndefined();+ expect(child.session.sessionManager.getHeader()).toMatchObject({ rlmDepth: 1 });+ expect(child.session.sessionManager.getHeader()?.parentSession).toBeUndefined();+ } finally {+ rmSync(tempDir, { recursive: true, force: true });+ }+ });+it("defers RLM heartbeats while a subagent is binding", async () => {const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-daemon-binding-heartbeat-"));let releaseChildBinding: (() => void) | undefined;@@ -676,6 +730,55 @@ describe("daemon mode helpers", () => {expect(missingSession.disposeAsync).toHaveBeenCalledOnce();});+ it("cancels child jobs when deletion joins an in-flight passivation close", async () => {+ const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-daemon-delete-passivation-race-"));+ let releaseDispose!: () => void;+ const disposeGate = new Promise<void>((resolve) => {+ releaseDispose = resolve;+ });+ let markDisposeStarted!: () => void;+ const disposeStarted = new Promise<void>((resolve) => {+ markDisposeStarted = resolve;+ });+ try {+ const fixture = makePersistedRlmDaemonFixture(tempDir, {+ childDisposeStarted: markDisposeStarted,+ childDisposeGate: disposeGate,+ });+ const internals = fixture.daemon as unknown as {+ cronStore: AgentCronJobStore;+ createRuntime(command: Extract<DaemonCommand, { type: "create" }>): Promise<ActiveSessionState>;+ createSubagentRuntimeHost(parent: ActiveSessionState): SubagentRuntimeHost;+ passivateIdleChildren(threshold: number, now: number, limit: number): Promise<number>;+ };+ const parentState = await internals.createRuntime({ type: "create", sessionPath: fixture.parentSessionFile });+ const childState = await internals.createRuntime({ type: "create", sessionPath: fixture.childSessionFile });+ (+ parentState.runtime.session as unknown as { releaseFinishedRlmChildSession: ReturnType<typeof vi.fn> }+ ).releaseFinishedRlmChildSession = vi.fn(() => vi.fn());+ const passivation = internals.passivateIdleChildren(90, Date.parse("2036-08-01T12:00:00Z"), 1);+ await disposeStarted;+ const job = internals.cronStore.create({+ activeSessionId: childState.activeSessionId,+ sessionId: childState.runtime.session.sessionId,+ sessionFile: fixture.childSessionFile,+ cwd: tempDir,+ scheduleText: "every 5m",+ prompt: "scheduled child work",+ });+ const deletion = internals+ .createSubagentRuntimeHost(parentState)+ .deleteRlmSubagentRuntime(fixture.childId, childState.runtime.session);+ releaseDispose();++ await Promise.all([passivation, deletion]);+ expect(internals.cronStore.list().find((candidate) => candidate.id === job.id)?.status).toBe("cancelled");+ } finally {+ releaseDispose();+ rmSync(tempDir, { recursive: true, force: true });+ }+ });+it("keeps a child live when its durable deletion boundary cannot be read", async () => {const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-daemon-delete-registry-failure-"));try {@@ -760,7 +863,7 @@ describe("daemon mode helpers", () => {}const internals = daemon as unknown as {sessions: Map<string, ActiveSessionState>;- closingSessions: Map<string, Promise<void>>;+ closingSessions: Map<string, { promise: Promise<void>; reason: "shutdown" }>;createAgentMessageController(getCurrentState: () => ActiveSessionState | undefined,): AgentSessionMessageController;@@ -771,7 +874,7 @@ describe("daemon mode helpers", () => {};internals.sessions.set(parentState.activeSessionId, parentState);internals.sessions.set(childState.activeSessionId, childState);- internals.closingSessions.set(childState.activeSessionId, Promise.resolve());+ internals.closingSessions.set(childState.activeSessionId, { promise: Promise.resolve(), reason: "shutdown" });const controller = internals.createAgentMessageController(() => parentState);const listed = await controller.listAgents();@@ -799,7 +902,7 @@ describe("daemon mode helpers", () => {internals.agentMessageTargetLocks.set(childState.activeSessionId, targetLock);const guardedPrompt = internals.promptWithAgentMessagePreparingGuard(childState, "continue");await Promise.resolve();- internals.closingSessions.set(childState.activeSessionId, Promise.resolve());+ internals.closingSessions.set(childState.activeSessionId, { promise: Promise.resolve(), reason: "shutdown" });releaseTargetLock();await expect(guardedPrompt).rejects.toThrow("closing before prompt delivery");expect(sessionPrompt).not.toHaveBeenCalled();@@ -829,7 +932,7 @@ describe("daemon mode helpers", () => {state.unsubscribe = vi.fn();const internals = daemon as unknown as {sessions: Map<string, ActiveSessionState>;- closingSessions: Map<string, Promise<void>>;+ closingSessions: Map<string, { promise: Promise<void>; reason: "shutdown" }>;closeSession(state: ActiveSessionState, reason: "killed", waitForAbort?: boolean): Promise<void>;closeChildSessions: ReturnType<typeof vi.fn>;isEmptyDraftContent: ReturnType<typeof vi.fn>;@@ -1091,6 +1194,64 @@ describe("daemon mode helpers", () => {}});+ it("does not retry permanent ambiguity errors from the supervisor", async () => {+ const tempDir = mkdtempSync(join(tmpdir(), "pa-ambiguous-"));+ const socketPath = join(tempDir, "s");+ let requestCount = 0;+ const server = createServer((socket) => {+ socket.write(+ `${JSON.stringify({+ type: "daemon_hello",+ socketPath,+ protocol: DAEMON_PROTOCOL_INFO,+ schemaRevision: DAEMON_SCHEMA_REVISION,+ serverCapabilities: [],+ })}\n`,+ );+ let buffered = "";+ socket.on("data", (chunk: Buffer) => {+ buffered += chunk.toString("utf8");+ const newline = buffered.indexOf("\n");+ if (newline < 0 || requestCount > 0) return;+ const command = JSON.parse(buffered.slice(0, newline)) as { id?: string };+ requestCount++;+ socket.write(+ `${JSON.stringify(failure(command.id, "send_message", new Error('Ambiguous session selector "duplicate"')))}\n`,+ );+ });+ });+ const previousSocketPath = process.env[DAEMON_WORKER_SUPERVISOR_SOCKET_ENV];+ try {+ await new Promise<void>((resolve, reject) => {+ server.once("error", reject);+ server.listen(socketPath, resolve);+ });+ process.env[DAEMON_WORKER_SUPERVISOR_SOCKET_ENV] = socketPath;+ const daemon = new AgentDaemon(join(tempDir, "worker.sock"), {+ defaultSessionConfig: { agentDir: tempDir, cwd: tempDir },+ createRuntime: vi.fn(),+ });+ const source = makeState("source");+ const internals = daemon as unknown as {+ sendRemoteAgentSessionMessage(+ fromState: ActiveSessionState,+ targetSelector: string,+ message: string,+ ): Promise<unknown>;+ };++ await expect(internals.sendRemoteAgentSessionMessage(source, "duplicate", "hello")).rejects.toThrow(+ 'Ambiguous session selector "duplicate"',+ );+ expect(requestCount).toBe(1);+ } finally {+ if (previousSocketPath === undefined) delete process.env[DAEMON_WORKER_SUPERVISOR_SOCKET_ENV];+ else process.env[DAEMON_WORKER_SUPERVISOR_SOCKET_ENV] = previousSocketPath;+ await new Promise<void>((resolve) => server.close(() => resolve()));+ rmSync(tempDir, { recursive: true, force: true });+ }+ });+it("reports queued status when a direct accept races into the queue", async () => {const daemon = new AgentDaemon("/tmp/prime-agent-test.sock", {defaultSessionConfig: { agentDir: "/tmp/prime-agent-test-agent", cwd: "/tmp" },@@ -3322,6 +3483,118 @@ describe("daemon mode helpers", () => {expect(createAttachResult).toHaveBeenCalledOnce();});+ it("does not attach a non-chunked client until its snapshot is ready", async () => {+ const daemon = new AgentDaemon("/tmp/prime-agent-test.sock", {+ defaultSessionConfig: { agentDir: "/tmp/prime-agent-test-agent", cwd: "/tmp" },+ createRuntime: vi.fn(),+ });+ const state = makeState("active");+ const client = makeClient("client-1", state.activeSessionId);+ client.attachedActiveSessionIds.clear();+ let releaseSnapshot!: () => void;+ const snapshotGate = new Promise<void>((resolve) => {+ releaseSnapshot = resolve;+ });+ const result = {+ activeSessionId: state.activeSessionId,+ snapshot: { summary: {}, state: {}, messages: [] },+ lastEventSequence: 0,+ } as unknown as DaemonAttachResult;+ const internals = daemon as unknown as {+ sessions: Map<string, ActiveSessionState>;+ createAttachResult: ReturnType<typeof vi.fn>;+ handleCommand(client: DaemonSocketClient, command: DaemonCommand): Promise<unknown>;+ };+ internals.sessions.set(state.activeSessionId, state);+ internals.createAttachResult = vi.fn(async () => {+ await snapshotGate;+ return result;+ });++ const attach = internals.handleCommand(client, { type: "attach", activeSessionId: state.activeSessionId });+ await vi.waitFor(() => expect(internals.createAttachResult).toHaveBeenCalledOnce());+ expect(state.clients).not.toContain(client);+ expect(client.attachedActiveSessionIds).not.toContain(state.activeSessionId);+ releaseSnapshot();+ await attach;+ expect(state.clients).toContain(client);+ expect(client.attachedActiveSessionIds).toContain(state.activeSessionId);+ });++ it("rejects an attach when its session closes during snapshot creation", async () => {+ const daemon = new AgentDaemon("/tmp/prime-agent-test.sock", {+ defaultSessionConfig: { agentDir: "/tmp/prime-agent-test-agent", cwd: "/tmp" },+ createRuntime: vi.fn(),+ });+ const state = makeState("active");+ const client = makeClient("client-1", state.activeSessionId);+ client.attachedActiveSessionIds.clear();+ let releaseSnapshot!: () => void;+ const snapshotGate = new Promise<void>((resolve) => {+ releaseSnapshot = resolve;+ });+ const internals = daemon as unknown as {+ sessions: Map<string, ActiveSessionState>;+ createAttachResult: ReturnType<typeof vi.fn>;+ handleCommand(client: DaemonSocketClient, command: DaemonCommand): Promise<unknown>;+ };+ internals.sessions.set(state.activeSessionId, state);+ internals.createAttachResult = vi.fn(async () => {+ await snapshotGate;+ return { activeSessionId: state.activeSessionId, snapshot: {}, lastEventSequence: 0 };+ });++ const attach = internals.handleCommand(client, { type: "attach", activeSessionId: state.activeSessionId });+ await vi.waitFor(() => expect(state.pendingAttaches).toBe(1));+ internals.sessions.delete(state.activeSessionId);+ releaseSnapshot();++ await expect(attach).rejects.toThrow(`Active session ${state.activeSessionId} closed during attach`);+ expect(state.pendingAttaches).toBe(0);+ expect(state.clients).not.toContain(client);+ expect(client.attachedActiveSessionIds).not.toContain(state.activeSessionId);+ });++ it("drops a backpressure catch-up when the client detaches during snapshot creation", async () => {+ const daemon = new AgentDaemon("/tmp/prime-agent-test.sock", {+ defaultSessionConfig: { agentDir: "/tmp/prime-agent-test-agent", cwd: "/tmp" },+ createRuntime: vi.fn(),+ });+ const state = makeState("active");+ const write = vi.fn(() => true);+ const client = makeClient("client-1", state.activeSessionId);+ client.socket = { destroyed: false, write } as unknown as Socket;+ client.catchupActiveSessionIds = new Set([state.activeSessionId]);+ state.clients.add(client);+ let releaseSnapshot!: () => void;+ const snapshotGate = new Promise<void>((resolve) => {+ releaseSnapshot = resolve;+ });+ const result = {+ activeSessionId: state.activeSessionId,+ snapshot: { summary: {}, state: {}, messages: [], lastEventSequence: 0 },+ lastEventSequence: 0,+ } as unknown as DaemonAttachResult;+ const internals = daemon as unknown as {+ sessions: Map<string, ActiveSessionState>;+ createAttachResult: ReturnType<typeof vi.fn>;+ drainBackpressuredClientCatchups(client: DaemonSocketClient): Promise<void>;+ };+ internals.sessions.set(state.activeSessionId, state);+ internals.createAttachResult = vi.fn(async () => {+ await snapshotGate;+ return result;+ });++ const catchup = internals.drainBackpressuredClientCatchups(client);+ await vi.waitFor(() => expect(internals.createAttachResult).toHaveBeenCalledOnce());+ state.clients.delete(client);+ client.attachedActiveSessionIds.delete(state.activeSessionId);+ releaseSnapshot();+ await catchup;+ expect(write).not.toHaveBeenCalled();+ });+it("marks a chunked attach as snapshotting before deferred streaming", async () => {const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-daemon-snapshot-order-"));try {@@ -3917,6 +4190,82 @@ describe("daemon mode helpers", () => {}});+ it("waits for a concurrently hydrating heartbeat child to finish binding", async () => {+ const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-daemon-heartbeat-hydration-race-"));+ let releasePassiveList!: () => void;+ const passiveListGate = new Promise<void>((resolve) => {+ releasePassiveList = resolve;+ });+ let markPassiveListStarted!: () => void;+ const passiveListStarted = new Promise<void>((resolve) => {+ markPassiveListStarted = resolve;+ });+ let releaseBinding!: () => void;+ const bindingGate = new Promise<void>((resolve) => {+ releaseBinding = resolve;+ });+ let markBindingStarted!: () => void;+ const bindingStarted = new Promise<void>((resolve) => {+ markBindingStarted = resolve;+ });+ try {+ const fixture = makePersistedRlmDaemonFixture(tempDir, {+ childBindingStarted: markBindingStarted,+ childBindingGate: bindingGate,+ });+ const internals = fixture.daemon as unknown as {+ cronStore: AgentCronJobStore;+ createRuntime(command: Extract<DaemonCommand, { type: "create" }>): Promise<ActiveSessionState>;+ getOrHydrateBoundSessionState(id: string): Promise<ActiveSessionState>;+ listPassiveRlmSubagents(): Promise<unknown[]>;+ restoreRlmHeartbeatSession(job: AgentCronJob): Promise<ActiveSessionState | undefined>;+ };+ await internals.createRuntime({ type: "create", sessionPath: fixture.parentSessionFile });+ const childInfo = await readSessionInfo(fixture.childSessionFile);+ if (!childInfo) throw new Error("Missing child session info");+ const heartbeat = internals.cronStore.createRlmHeartbeat({+ activeSessionId: "stale-child-active-id",+ sessionId: childInfo.id,+ sessionFile: fixture.childSessionFile,+ cwd: tempDir,+ runtimeKind: "subagent",+ scheduleText: "every 30s",+ prompt: "report exactly: hi",+ now: new Date("2026-01-01T00:00:00.000Z"),+ });+ const listPassive = internals.listPassiveRlmSubagents.bind(fixture.daemon);+ let blockNextList = true;+ internals.listPassiveRlmSubagents = vi.fn(async () => {+ if (blockNextList) {+ blockNextList = false;+ markPassiveListStarted();+ await passiveListGate;+ }+ return listPassive();+ });++ let restored = false;+ const restoration = internals.restoreRlmHeartbeatSession(heartbeat).then((state) => {+ restored = true;+ return state;+ });+ await passiveListStarted;+ const hydration = internals.getOrHydrateBoundSessionState(fixture.childId);+ await bindingStarted;+ releasePassiveList();+ await Promise.resolve();+ expect(restored).toBe(false);+ releaseBinding();++ const [restoredState, hydratedState] = await Promise.all([restoration, hydration]);+ expect(restoredState).toBe(hydratedState);+ } finally {+ releasePassiveList();+ releaseBinding();+ rmSync(tempDir, { recursive: true, force: true });+ }+ });+it("cancels a detached subagent heartbeat when its parent is archived", async () => {const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-daemon-archived-subagent-heartbeat-"));try {@@ -4211,6 +4560,79 @@ describe("daemon mode helpers", () => {}});+ it("recomputes snapshot children when the runtime session changes during the passive walk", async () => {+ const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-daemon-snapshot-replacement-"));+ try {+ const fixture = makePersistedRlmDaemonFixture(tempDir);+ const internals = fixture.daemon as unknown as {+ createRuntime(command: Extract<DaemonCommand, { type: "create" }>): Promise<ActiveSessionState>;+ createSessionSnapshot(state: ActiveSessionState): Promise<DaemonAttachResult["snapshot"]>;+ createConnectionState: ReturnType<typeof vi.fn>;+ buildRlmChildSnapshotsWithPassiveRlmSubagents: ReturnType<typeof vi.fn>;+ };+ const state = await internals.createRuntime({ type: "create", sessionPath: fixture.parentSessionFile });+ const originalSession = state.runtime.session;+ const replacementSession = Object.create(originalSession) as typeof originalSession;+ Object.defineProperty(replacementSession, "messages", {+ value: [{ role: "user", content: "new transcript", timestamp: 1 }],+ });+ internals.createConnectionState = vi.fn(() => ({}));+ let calls = 0;+ internals.buildRlmChildSnapshotsWithPassiveRlmSubagents = vi.fn(async () => {+ calls++;+ if (calls === 1)+ (state.runtime as unknown as { _session: typeof originalSession })._session =+ replacementSession as typeof originalSession;+ return [{ id: calls === 1 ? "old-child" : "new-child", status: "done", sessionDir: tempDir }];+ });++ const snapshot = await internals.createSessionSnapshot(state);++ expect(internals.buildRlmChildSnapshotsWithPassiveRlmSubagents).toHaveBeenCalledTimes(2);+ expect(snapshot.children).toEqual([expect.objectContaining({ id: "new-child" })]);+ expect(snapshot.messages).toBe(replacementSession.messages);+ } finally {+ rmSync(tempDir, { recursive: true, force: true });+ }+ });++ it("bounds snapshot stabilization when every child build replaces the runtime session", async () => {+ const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-daemon-snapshot-stabilization-bound-"));+ try {+ const fixture = makePersistedRlmDaemonFixture(tempDir);+ const internals = fixture.daemon as unknown as {+ createRuntime(command: Extract<DaemonCommand, { type: "create" }>): Promise<ActiveSessionState>;+ createSessionSnapshot(state: ActiveSessionState): Promise<DaemonAttachResult["snapshot"]>;+ createConnectionState: ReturnType<typeof vi.fn>;+ buildRlmChildSnapshotsWithPassiveRlmSubagents: ReturnType<typeof vi.fn>;+ };+ const state = await internals.createRuntime({ type: "create", sessionPath: fixture.parentSessionFile });+ internals.createConnectionState = vi.fn(() => ({}));+ let calls = 0;+ internals.buildRlmChildSnapshotsWithPassiveRlmSubagents = vi.fn(async () => {+ calls++;+ const replacementSession = Object.create(state.runtime.session) as typeof state.runtime.session;+ Object.defineProperties(replacementSession, {+ messages: {+ value: [{ role: "user", content: `transcript ${calls}`, timestamp: calls }],+ },+ sessionId: { value: `session-${calls}` },+ });+ (state.runtime as unknown as { _session: typeof replacementSession })._session = replacementSession;+ return [{ id: `child-${calls}`, status: "done", sessionDir: tempDir }];+ });++ await expect(internals.createSessionSnapshot(state)).resolves.toMatchObject({+ children: [expect.objectContaining({ id: "child-4" })],+ messages: [{ content: "transcript 4" }],+ summary: { sessionId: "session-4" },+ });+ expect(internals.buildRlmChildSnapshotsWithPassiveRlmSubagents).toHaveBeenCalledTimes(4);+ } finally {+ rmSync(tempDir, { recursive: true, force: true });+ }+ });+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 {@@ -4329,12 +4751,22 @@ describe("daemon mode helpers", () => {}});- 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-"));+ it("rehydrates a legacy passive subagent at depth one", async () => {+ const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-daemon-legacy-rlm-depth-"));try {const fixture = makePersistedRlmDaemonFixture(tempDir);+ const childLines = readFileSync(fixture.childSessionFile, "utf8").split("\n");+ const childHeader = JSON.parse(childLines[0] ?? "{}") as Record<string, unknown>;+ delete childHeader.rlmDepth;+ childLines[0] = JSON.stringify(childHeader);+ writeFileSync(fixture.childSessionFile, childLines.join("\n"));++ const registryPath = join(fixture.parentArtifactDir, "rlm-subagents.jsonl");+ const registryEntry = JSON.parse(readFileSync(registryPath, "utf8").trim()) as Record<string, unknown>;+ delete registryEntry.rlmDepth;+ writeFileSync(registryPath, `${JSON.stringify(registryEntry)}\n`);+const internals = fixture.daemon as unknown as {- sessions: Map<string, ActiveSessionState>;createRuntime(command: Extract<DaemonCommand, { type: "create" }>): Promise<ActiveSessionState>;createAgentMessageController(getCurrentState: () => ActiveSessionState | undefined,@@ -4347,56 +4779,120 @@ describe("daemon mode helpers", () => {await internals.createAgentMessageController(() => parentState)- .sendAgentMessage({- target: "nested-worker",- message: "report nested progress",- });+ .sendAgentMessage({ target: "renamed-worker", message: "report progress" });- expect(fixture.createRuntime).toHaveBeenCalledTimes(3);- expect([...internals.sessions.values()].map((state) => state.runtime.metadata.rlmChildId)).toEqual(- expect.arrayContaining([fixture.childId, fixture.grandchildId]),- );+ expect(fixture.createRuntime.mock.calls[1]?.[0].sessionOptions?.rlmDepth).toBe(1);} 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-"));+ it("prefers the persisted header depth when a legacy registry entry lacks one", async () => {+ const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-daemon-legacy-header-depth-"));try {const fixture = makePersistedRlmDaemonFixture(tempDir);+ const childLines = readFileSync(fixture.childSessionFile, "utf8").split("\n");+ const childHeader = JSON.parse(childLines[0] ?? "{}") as Record<string, unknown>;+ childHeader.rlmDepth = 2;+ childLines[0] = JSON.stringify(childHeader);+ writeFileSync(fixture.childSessionFile, childLines.join("\n"));++ const registryPath = join(fixture.parentArtifactDir, "rlm-subagents.jsonl");+ const registryEntry = JSON.parse(readFileSync(registryPath, "utf8").trim()) as Record<string, unknown>;+ delete registryEntry.rlmDepth;+ writeFileSync(registryPath, `${JSON.stringify(registryEntry)}\n`);+const internals = fixture.daemon as unknown as {createRuntime(command: Extract<DaemonCommand, { type: "create" }>): Promise<ActiveSessionState>;- createAgentObserveController(getCurrentState: () => ActiveSessionState | undefined): AgentObserveController;+ createAgentMessageController(+ getCurrentState: () => ActiveSessionState | undefined,+ ): AgentSessionMessageController;};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);+ await internals+ .createAgentMessageController(() => parentState)+ .sendAgentMessage({ target: "renamed-worker", message: "report progress" });++ // The nested header depth must win over the legacy depth-1 default so the+ // woken child does not come up shallower than persisted.+ expect(fixture.createRuntime.mock.calls[1]?.[0].sessionOptions?.rlmDepth).toBe(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;+ 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]),+ );+ } 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;@@ -4435,35 +4931,1115 @@ describe("daemon mode helpers", () => {await openStarted;expect(internals.reservingSessionOpens.has(resolve(fixture.childSessionFile))).toBe(true);- const hydration = internals.hydratePassiveRlmSubagent(passive);- const joined = Promise.all([explicitOpen, hydration]);- releaseOpen();+ const hydration = internals.hydratePassiveRlmSubagent(passive);+ const joined = Promise.all([explicitOpen, hydration]);+ releaseOpen();++ const [openedState, hydratedState] = await joined;+ expect(openedState.runtime.session.sessionFile).toBe(fixture.childSessionFile);+ expect(hydratedState.runtime.session.sessionFile).toBe(fixture.childSessionFile);+ // Kind fidelity may replace a non-subagent explicit open with a proper+ // subagent rehydration; either way the lazy path must join the explicit+ // open's lease instead of failing with a lease conflict, and exactly one+ // resident state may own the session file afterwards.+ const internalsAfter = fixture.daemon as unknown as { sessions: Map<string, ActiveSessionState> };+ const owners = [...internalsAfter.sessions.values()].filter(+ (state) => state.runtime.session.sessionFile === fixture.childSessionFile,+ );+ expect(owners).toHaveLength(1);+ expect(owners[0]).toBe(hydratedState);+ } finally {+ releaseOpen();+ openAsyncSpy?.mockRestore();+ rmSync(tempDir, { recursive: true, force: true });+ }+ });++ it("loads a passive child under the create command client env", async () => {+ const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-daemon-passive-create-env-"));+ const inheritedPaneId = process.env.HERDR_PANE_ID;+ delete process.env.HERDR_PANE_ID;+ try {+ const fixture = makePersistedRlmDaemonFixture(tempDir);+ const envAtRuntimeCreation: Array<string | undefined> = [];+ const createRuntime = fixture.createRuntime.getMockImplementation();+ if (!createRuntime) throw new Error("Missing fixture runtime factory");+ fixture.createRuntime.mockImplementation(async (runtimeOptions) => {+ envAtRuntimeCreation.push(process.env.HERDR_PANE_ID);+ return createRuntime(runtimeOptions);+ });+ const internals = fixture.daemon as unknown as {+ createRuntime(command: Extract<DaemonCommand, { type: "create" }>): Promise<ActiveSessionState>;+ };+ const parentState = await internals.createRuntime({ type: "create", sessionPath: fixture.parentSessionFile });+ expect(parentState.clientEnv).toBeUndefined();++ const childState = await internals.createRuntime({+ type: "create",+ sessionPath: fixture.childSessionFile,+ env: { HERDR_PANE_ID: "pane-42" },+ });++ expect(envAtRuntimeCreation).toEqual([undefined, "pane-42"]);+ expect(parentState.clientEnv).toEqual({ HERDR_PANE_ID: "pane-42" });+ expect(childState.clientEnv).toEqual({ HERDR_PANE_ID: "pane-42" });+ } finally {+ if (inheritedPaneId === undefined) delete process.env.HERDR_PANE_ID;+ else process.env.HERDR_PANE_ID = inheritedPaneId;+ rmSync(tempDir, { recursive: true, force: true });+ }+ });++ it("does not adopt a failed passive opener env on the root parent", async () => {+ const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-daemon-failed-passive-env-"));+ try {+ const fixture = makePersistedRlmDaemonFixture(tempDir);+ const internals = fixture.daemon as unknown as {+ createRuntime(command: Extract<DaemonCommand, { type: "create" }>): Promise<ActiveSessionState>;+ };+ const parentState = await internals.createRuntime({ type: "create", sessionPath: fixture.parentSessionFile });+ const createRuntime = fixture.createRuntime.getMockImplementation();+ if (!createRuntime) throw new Error("Missing fixture runtime factory");+ let failHydration = true;+ const childEnvAtRuntimeCreation: Array<string | undefined> = [];+ fixture.createRuntime.mockImplementation(async (runtimeOptions) => {+ if (runtimeOptions.sessionManager.getSessionFile() === fixture.childSessionFile) {+ childEnvAtRuntimeCreation.push(process.env.HERDR_PANE_ID);+ if (failHydration) {+ failHydration = false;+ throw new Error("hydration failed");+ }+ }+ return createRuntime(runtimeOptions);+ });++ await expect(+ internals.createRuntime({+ type: "create",+ sessionPath: fixture.childSessionFile,+ env: { HERDR_PANE_ID: "failed-pane" },+ }),+ ).rejects.toThrow("hydration failed");+ expect(parentState.clientEnv).toBeUndefined();++ const childState = await internals.createRuntime({+ type: "create",+ sessionPath: fixture.childSessionFile,+ env: { HERDR_PANE_ID: "successful-pane" },+ });+ expect(childEnvAtRuntimeCreation).toEqual(["failed-pane", "successful-pane"]);+ expect(parentState.clientEnv).toEqual({ HERDR_PANE_ID: "successful-pane" });+ expect(childState.clientEnv).toEqual({ HERDR_PANE_ID: "successful-pane" });+ } finally {+ rmSync(tempDir, { recursive: true, force: true });+ }+ });++ it("joins binding when advertised session ID resolution races passive hydration", async () => {+ const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-daemon-lazy-rlm-resolve-race-"));+ let releasePassiveList!: () => void;+ const passiveListGate = new Promise<void>((resolve) => {+ releasePassiveList = resolve;+ });+ let releaseBinding!: () => void;+ const bindingGate = new Promise<void>((resolve) => {+ releaseBinding = resolve;+ });+ let markBindingStarted!: () => void;+ const bindingStarted = new Promise<void>((resolve) => {+ markBindingStarted = resolve;+ });+ try {+ const fixture = makePersistedRlmDaemonFixture(tempDir, {+ childBindingStarted: markBindingStarted,+ childBindingGate: bindingGate,+ });+ const internals = fixture.daemon as unknown as {+ createRuntime(command: Extract<DaemonCommand, { type: "create" }>): Promise<ActiveSessionState>;+ getOrHydrateBoundSessionState(id: string): Promise<ActiveSessionState>;+ listPassiveRlmSubagents(): Promise<unknown[]>;+ };+ await internals.createRuntime({ type: "create", sessionPath: fixture.parentSessionFile });+ const childInfo = await readSessionInfo(fixture.childSessionFile);+ if (!childInfo) throw new Error("Missing child session info");+ const listPassive = internals.listPassiveRlmSubagents.bind(fixture.daemon);+ let blockNextList = true;+ internals.listPassiveRlmSubagents = vi.fn(async () => {+ if (blockNextList) {+ blockNextList = false;+ await passiveListGate;+ }+ return listPassive();+ });++ let advertisedResolved = false;+ const advertisedLookup = internals.getOrHydrateBoundSessionState(childInfo.id).then((state) => {+ advertisedResolved = true;+ return state;+ });+ await Promise.resolve();+ const hydration = internals.getOrHydrateBoundSessionState(fixture.childId);+ await bindingStarted;+ releasePassiveList();+ await Promise.resolve();+ expect(advertisedResolved).toBe(false);+ releaseBinding();++ const hydrated = await hydration;+ await expect(advertisedLookup).resolves.toBe(hydrated);+ } finally {+ releasePassiveList();+ releaseBinding();+ rmSync(tempDir, { recursive: true, force: true });+ }+ });++ it("rejects an ambiguous live selector before consulting passive children", async () => {+ const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-daemon-ambiguous-passive-selector-"));+ try {+ const fixture = makePersistedRlmDaemonFixture(tempDir);+ const internals = fixture.daemon as unknown as {+ sessions: Map<string, ActiveSessionState>;+ createRuntime(command: Extract<DaemonCommand, { type: "create" }>): Promise<ActiveSessionState>;+ getOrHydrateBoundSessionState(id: string): Promise<ActiveSessionState>;+ };+ await internals.createRuntime({ type: "create", sessionPath: fixture.parentSessionFile });+ for (const id of ["live-one", "live-two"]) {+ const state = makeState(id);+ Object.assign(state.runtime, {+ session: { sessionId: `${id}-session`, sessionName: "renamed-worker" },+ metadata: { kind: "root", createdAt: 1 },+ });+ internals.sessions.set(id, state);+ }++ await expect(internals.getOrHydrateBoundSessionState("renamed-worker")).rejects.toThrow(+ 'Ambiguous active session "renamed-worker"',+ );+ expect(fixture.createRuntime).toHaveBeenCalledOnce();+ } finally {+ rmSync(tempDir, { recursive: true, force: true });+ }+ });++ it("leaves passive hydration resident when its runtime-open guard is cancelled", async () => {+ const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-daemon-guarded-hydration-"));+ let releaseHydration!: () => void;+ const hydrationGate = new Promise<void>((resolve) => {+ releaseHydration = resolve;+ });+ let markHydrationStarted!: () => void;+ const hydrationStarted = new Promise<void>((resolve) => {+ markHydrationStarted = resolve;+ });+ try {+ const fixture = makePersistedRlmDaemonFixture(tempDir, {+ childRuntimeStarted: markHydrationStarted,+ childRuntimeGate: hydrationGate,+ });+ const internals = fixture.daemon as unknown as {+ cronStore: AgentCronJobStore;+ sessions: Map<string, ActiveSessionState>;+ createRuntime(command: Extract<DaemonCommand, { type: "create" }>): Promise<ActiveSessionState>;+ getRunnableCronJob(id: string): AgentCronJob | undefined;+ runCronJob(job: AgentCronJob): Promise<"skipped" | undefined>;+ passivateIdleChildren(threshold: number, now: number, limit: number): Promise<number>;+ };+ const parentState = await internals.createRuntime({+ type: "create",+ sessionPath: fixture.parentSessionFile,+ });+ const parentSession = parentState.runtime.session as unknown as {+ releaseFinishedRlmChildSession: ReturnType<typeof vi.fn>;+ };+ parentSession.releaseFinishedRlmChildSession = vi.fn(() => vi.fn());+ const childInfo = await readSessionInfo(fixture.childSessionFile);+ if (!childInfo) throw new Error("Missing child session info");+ const heartbeat = internals.cronStore.createRlmHeartbeat({+ activeSessionId: "stale-child-active-id",+ sessionId: childInfo.id,+ sessionFile: fixture.childSessionFile,+ cwd: tempDir,+ runtimeKind: "subagent",+ scheduleText: "every 30s",+ prompt: "must not run",+ now: new Date("2026-01-01T00:00:00.000Z"),+ });+ let runnable = true;+ internals.getRunnableCronJob = vi.fn(() => (runnable ? heartbeat : undefined));++ const run = internals.runCronJob(heartbeat);+ await hydrationStarted;+ runnable = false;+ releaseHydration();++ await expect(run).resolves.toBe("skipped");+ internals.cronStore.cancel(heartbeat.id);+ const childState = [...internals.sessions.values()].find(+ (state) => state.runtime.metadata.rlmChildId === fixture.childId,+ );+ expect(childState).toBeDefined();+ expect(fixture.runtimeSessions[1]?.disposeAsync).not.toHaveBeenCalled();+ expect(parentSession.releaseFinishedRlmChildSession).not.toHaveBeenCalled();++ await expect(internals.passivateIdleChildren(90, Date.parse("2036-08-01T12:00:00Z"), 1)).resolves.toBe(1);+ expect(internals.sessions.has(childState!.activeSessionId)).toBe(false);+ expect(fixture.runtimeSessions[1]?.disposeAsync).toHaveBeenCalledOnce();+ expect(parentSession.releaseFinishedRlmChildSession).toHaveBeenCalledWith(+ fixture.childId,+ childState!.runtime.session,+ );+ } finally {+ releaseHydration();+ rmSync(tempDir, { recursive: true, force: true });+ }+ });++ it("keeps an attach-owned passive hydration usable when a joining heartbeat is cancelled", async () => {+ const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-daemon-shared-guarded-hydration-"));+ let releaseHydration!: () => void;+ const hydrationGate = new Promise<void>((resolve) => {+ releaseHydration = resolve;+ });+ let markHydrationStarted!: () => void;+ const hydrationStarted = new Promise<void>((resolve) => {+ markHydrationStarted = resolve;+ });+ let markHeartbeatJoinStarted!: () => void;+ const heartbeatJoinStarted = new Promise<void>((resolve) => {+ markHeartbeatJoinStarted = resolve;+ });+ try {+ const fixture = makePersistedRlmDaemonFixture(tempDir, {+ childRuntimeStarted: markHydrationStarted,+ childRuntimeGate: hydrationGate,+ });+ const internals = fixture.daemon as unknown as {+ cronStore: AgentCronJobStore;+ sessions: Map<string, ActiveSessionState>;+ createRuntime(command: Extract<DaemonCommand, { type: "create" }>): Promise<ActiveSessionState>;+ createAgentMessageController(+ getCurrentState: () => ActiveSessionState | undefined,+ ): AgentSessionMessageController;+ getRunnableCronJob(id: string): AgentCronJob | undefined;+ runCronJob(job: AgentCronJob): Promise<"skipped" | undefined>;+ hydratePassiveRlmSubagent(passive: unknown): Promise<ActiveSessionState>;+ };+ const parentState = await internals.createRuntime({+ type: "create",+ sessionPath: fixture.parentSessionFile,+ });+ const parentSession = parentState.runtime.session as unknown as {+ releaseFinishedRlmChildSession: ReturnType<typeof vi.fn>;+ retainFinishedRlmChildSession: ReturnType<typeof vi.fn>;+ };+ parentSession.releaseFinishedRlmChildSession = vi.fn(() => vi.fn());+ const childInfo = await readSessionInfo(fixture.childSessionFile);+ if (!childInfo) throw new Error("Missing child session info");+ const heartbeat = internals.cronStore.createRlmHeartbeat({+ activeSessionId: "stale-child-active-id",+ sessionId: childInfo.id,+ sessionFile: fixture.childSessionFile,+ cwd: tempDir,+ runtimeKind: "subagent",+ scheduleText: "every 30s",+ prompt: "must not run",+ now: new Date("2026-01-01T00:00:00.000Z"),+ });+ let runnable = true;+ internals.getRunnableCronJob = vi.fn(() => (runnable ? heartbeat : undefined));++ const attach = internals.createRuntime({ type: "create", sessionPath: fixture.childSessionFile });+ await hydrationStarted;+ const hydratePassive = internals.hydratePassiveRlmSubagent.bind(fixture.daemon);+ internals.hydratePassiveRlmSubagent = vi.fn(async (passive) => {+ markHeartbeatJoinStarted();+ return hydratePassive(passive);+ });+ const run = internals.runCronJob(heartbeat);+ await heartbeatJoinStarted;+ runnable = false;+ releaseHydration();++ const attachedState = await attach;+ await expect(run).resolves.toBe("skipped");+ expect(internals.sessions.get(attachedState.activeSessionId)).toBe(attachedState);+ expect(fixture.runtimeSessions[1]?.disposeAsync).not.toHaveBeenCalled();+ expect(parentSession.releaseFinishedRlmChildSession).not.toHaveBeenCalled();+ expect(parentSession.retainFinishedRlmChildSession).toHaveBeenCalledWith(+ fixture.childId,+ attachedState.runtime.session,+ );++ await expect(+ internals+ .createAgentMessageController(() => parentState)+ .sendAgentMessage({ target: fixture.childId, message: "still usable" }),+ ).resolves.toMatchObject({ deliveryStatus: "delivered", target: { runtimeKind: "subagent" } });+ expect(fixture.acceptAgentMessagePrompt).toHaveBeenCalledWith(+ expect.stringContaining("still usable"),+ expect.any(Object),+ );+ } finally {+ releaseHydration();+ rmSync(tempDir, { recursive: true, force: true });+ }+ });++ it("repairs a wrong-kind pending open while preserving the passive row id", async () => {+ const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-daemon-wrong-kind-open-"));+ try {+ const fixture = makePersistedRlmDaemonFixture(tempDir);+ const internals = fixture.daemon as unknown as {+ sessions: Map<string, ActiveSessionState>;+ openingSessions: Map<string, Promise<ActiveSessionState>>;+ createRuntime(command: Extract<DaemonCommand, { type: "create" }>): Promise<ActiveSessionState>;+ findPassiveRlmSubagent(id: string): Promise<unknown>;+ hydratePassiveRlmSubagent(passive: unknown): Promise<ActiveSessionState>;+ };+ await internals.createRuntime({ type: "create", sessionPath: fixture.parentSessionFile });+ const passive = (await internals.findPassiveRlmSubagent(fixture.childId)) as { info: { id: string } };+ const wrongState = makeState("wrong-kind");+ Object.assign(wrongState, { extensionUiRequests: new Map(), eventGeneration: "wrong", lastEventSequence: 0 });+ Object.assign(wrongState.runtime, {+ dispose: vi.fn(async () => {}),+ metadata: { kind: "root", createdAt: 1 },+ session: makeRuntimeSession(SessionManager.open(fixture.childSessionFile, fixture.childSessionDir)),+ });+ internals.sessions.set(wrongState.activeSessionId, wrongState);+ internals.openingSessions.set(resolve(fixture.childSessionFile), Promise.resolve(wrongState));++ const childState = await internals.hydratePassiveRlmSubagent(passive);++ expect(childState.activeSessionId).toBe(passive.info.id);+ expect(childState.runtime.metadata).toMatchObject({ kind: "subagent", rlmChildId: fixture.childId });+ expect(internals.sessions.has(wrongState.activeSessionId)).toBe(false);+ } finally {+ rmSync(tempDir, { recursive: true, force: true });+ }+ });++ it("rejects passive hydration while an update restart is fenced", async () => {+ const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-daemon-update-hydration-"));+ try {+ const fixture = makePersistedRlmDaemonFixture(tempDir);+ const internals = fixture.daemon as unknown as {+ updateRestart: unknown;+ createRuntime(command: Extract<DaemonCommand, { type: "create" }>): Promise<ActiveSessionState>;+ getOrHydrateBoundSessionState(id: string): Promise<ActiveSessionState>;+ };+ await internals.createRuntime({ type: "create", sessionPath: fixture.parentSessionFile });+ internals.updateRestart = { phase: "prepared" };++ await expect(internals.getOrHydrateBoundSessionState(fixture.childId)).rejects.toThrow(+ "Daemon is preparing an update restart",+ );+ expect(fixture.createRuntime).toHaveBeenCalledOnce();+ } finally {+ 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.metadata.kind === "subagent"),+ ).toHaveLength(1);+ expect(fixture.acceptAgentMessagePrompt).toHaveBeenCalledTimes(2);+ } finally {+ releaseHydration();+ rmSync(tempDir, { recursive: true, force: true });+ }+ });++ it("keeps a parent resident while one of its passive descendants is hydrating", async () => {+ const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-daemon-hydration-passivation-race-"));+ let releaseHydration!: () => void;+ const hydrationGate = new Promise<void>((resolve) => {+ releaseHydration = resolve;+ });+ let markHydrationStarted!: () => void;+ const hydrationStarted = new Promise<void>((resolve) => {+ markHydrationStarted = resolve;+ });+ try {+ const fixture = makePersistedRlmDaemonFixture(tempDir, {+ grandchildRuntimeStarted: markHydrationStarted,+ grandchildRuntimeGate: hydrationGate,+ });+ const internals = fixture.daemon as unknown as {+ sessions: Map<string, ActiveSessionState>;+ createRuntime(command: Extract<DaemonCommand, { type: "create" }>): Promise<ActiveSessionState>;+ getOrHydrateBoundSessionState(id: string): Promise<ActiveSessionState>;+ passivateIdleChildren(threshold: number, now: number, limit: number): Promise<number>;+ };+ const rootState = await internals.createRuntime({+ type: "create",+ sessionPath: fixture.parentSessionFile,+ });+ const parentState = await internals.createRuntime({+ type: "create",+ sessionPath: fixture.childSessionFile,+ });+ const rootSession = rootState.runtime.session as unknown as {+ releaseFinishedRlmChildSession: ReturnType<typeof vi.fn>;+ };+ rootSession.releaseFinishedRlmChildSession = vi.fn(() => vi.fn());++ const hydration = internals.getOrHydrateBoundSessionState(fixture.grandchildId);+ await hydrationStarted;+ await expect(internals.passivateIdleChildren(90, Date.parse("2036-08-01T12:00:00Z"), 1)).resolves.toBe(0);+ expect(internals.sessions.get(parentState.activeSessionId)).toBe(parentState);+ expect(rootSession.releaseFinishedRlmChildSession).not.toHaveBeenCalled();++ releaseHydration();+ const grandchildState = await hydration;+ expect(internals.sessions.get(parentState.activeSessionId)).toBe(parentState);+ expect(grandchildState.runtime.metadata).toMatchObject({+ parentActiveSessionId: parentState.activeSessionId,+ rlmChildId: fixture.grandchildId,+ });+ expect(+ (parentState.runtime.session as unknown as { retainFinishedRlmChildSession: ReturnType<typeof vi.fn> })+ .retainFinishedRlmChildSession,+ ).toHaveBeenCalledWith(fixture.grandchildId, grandchildState.runtime.session);+ } finally {+ releaseHydration();+ rmSync(tempDir, { recursive: true, force: true });+ }+ });++ it("returns a resident target when a concurrent opener wins a parent-change restart", async () => {+ const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-daemon-parent-change-open-race-"));+ try {+ const fixture = makePersistedRlmDaemonFixture(tempDir);+ const internals = fixture.daemon as unknown as {+ sessions: Map<string, ActiveSessionState>;+ openingSessions: Map<string, Promise<ActiveSessionState>>;+ createRuntime(command: Extract<DaemonCommand, { type: "create" }>): Promise<ActiveSessionState>;+ findPassiveRlmSubagent(id: string): Promise<unknown>;+ hydratePassiveRlmSubagent(passive: unknown): Promise<ActiveSessionState>;+ rehydrateCompletedRlmSubagent(+ parent: ActiveSessionState,+ entry: { childId: string; sessionFile: string },+ ): Promise<ActiveSessionState>;+ waitForPassivation(sessionFile: string): Promise<void>;+ };+ const rootState = await internals.createRuntime({ type: "create", sessionPath: fixture.parentSessionFile });+ const passive = await internals.findPassiveRlmSubagent(fixture.grandchildId);+ if (!passive) throw new Error("Missing passive grandchild");+ const staleParent = makeState("stale-parent", rootState.activeSessionId);+ Object.assign(staleParent.runtime, { session: { sessionFile: fixture.childSessionFile } });+ const residentGrandchild = makeState("resident-grandchild", staleParent.activeSessionId);+ Object.assign(residentGrandchild.runtime, {+ metadata: {+ kind: "subagent",+ createdAt: 1,+ parentActiveSessionId: staleParent.activeSessionId,+ rlmChildId: fixture.grandchildId,+ },+ session: { sessionFile: fixture.grandchildSessionFile },+ });+ let hydrationAttempts = 0;+ internals.rehydrateCompletedRlmSubagent = vi.fn(async () => {+ if (++hydrationAttempts === 1) {+ internals.sessions.set(staleParent.activeSessionId, staleParent);+ return staleParent;+ }+ return residentGrandchild;+ });+ const findPassiveRlmSubagent = internals.findPassiveRlmSubagent.bind(fixture.daemon);+ internals.findPassiveRlmSubagent = vi.fn(async (id: string) => {+ if (id === fixture.grandchildSessionFile) return passive;+ return findPassiveRlmSubagent(id);+ });+ internals.waitForPassivation = vi.fn(async (sessionFile) => {+ if (sessionFile !== fixture.grandchildSessionFile) return;+ internals.sessions.delete(staleParent.activeSessionId);+ internals.sessions.set(residentGrandchild.activeSessionId, residentGrandchild);+ internals.openingSessions.set(resolve(fixture.grandchildSessionFile), Promise.resolve(residentGrandchild));+ });++ await expect(internals.hydratePassiveRlmSubagent(passive)).resolves.toBe(residentGrandchild);+ } finally {+ rmSync(tempDir, { recursive: true, force: true });+ }+ });++ it("re-walks the passive chain when an intermediate parent passivates between entries", async () => {+ const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-daemon-chain-parent-passivation-race-"));+ try {+ const fixture = makePersistedRlmDaemonFixture(tempDir);+ const internals = fixture.daemon as unknown as {+ sessions: Map<string, ActiveSessionState>;+ createRuntime(command: Extract<DaemonCommand, { type: "create" }>): Promise<ActiveSessionState>;+ findPassiveRlmSubagent(id: string): Promise<+ | {+ rootParentState: ActiveSessionState;+ entry: { childId: string; sessionFile: string };+ chain: Array<{ childId: string; sessionFile: string }>;+ }+ | undefined+ >;+ hydratePassiveRlmSubagent(passive: unknown): Promise<ActiveSessionState>;+ waitForPassivation(sessionFile: string): Promise<void>;+ rehydrateCompletedRlmSubagent(+ parent: ActiveSessionState,+ entry: { childId: string; sessionFile: string },+ ): Promise<ActiveSessionState>;+ };+ const rootState = await internals.createRuntime({ type: "create", sessionPath: fixture.parentSessionFile });+ const passive = await internals.findPassiveRlmSubagent(fixture.grandchildId);+ if (!passive) throw new Error("Missing passive grandchild");++ const staleParent = makeState("stale-parent", rootState.activeSessionId);+ const refreshedParent = makeState("refreshed-parent", rootState.activeSessionId);+ const grandchild = makeState("rehydrated-grandchild", refreshedParent.activeSessionId);+ for (const [state, sessionFile] of [+ [staleParent, fixture.childSessionFile],+ [refreshedParent, fixture.childSessionFile],+ [grandchild, fixture.grandchildSessionFile],+ ] as const) {+ Object.assign(state.runtime, { session: { sessionFile } });+ }++ let childHydrations = 0;+ internals.rehydrateCompletedRlmSubagent = vi.fn(async (_parent, entry) => {+ const hydrated =+ entry.childId === fixture.childId+ ? ++childHydrations === 1+ ? staleParent+ : refreshedParent+ : grandchild;+ internals.sessions.set(hydrated.activeSessionId, hydrated);+ return hydrated;+ });+ let grandchildWaits = 0;+ internals.waitForPassivation = vi.fn(async (sessionFile) => {+ if (sessionFile === fixture.grandchildSessionFile && ++grandchildWaits === 1) {+ internals.sessions.delete(staleParent.activeSessionId);+ }+ });+ internals.findPassiveRlmSubagent = vi.fn(async () => passive);++ await expect(internals.hydratePassiveRlmSubagent(passive)).resolves.toBe(grandchild);+ expect(childHydrations).toBe(2);+ expect(internals.rehydrateCompletedRlmSubagent).toHaveBeenCalledWith(+ refreshedParent,+ passive.entry,+ expect.anything(),+ undefined,+ );+ expect(internals.rehydrateCompletedRlmSubagent).not.toHaveBeenCalledWith(+ staleParent,+ passive.entry,+ expect.anything(),+ undefined,+ );+ } finally {+ rmSync(tempDir, { recursive: true, force: true });+ }+ });++ it("retries hydration when the target child starts passivating after the initial wait", async () => {+ const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-daemon-child-hydration-passivation-race-"));+ let releasePassivation!: () => void;+ const passivationGate = new Promise<void>((resolve) => {+ releasePassivation = resolve;+ });+ let markRaceStarted!: () => void;+ const raceStarted = new Promise<void>((resolve) => {+ markRaceStarted = resolve;+ });+ try {+ const fixture = makePersistedRlmDaemonFixture(tempDir);+ const internals = fixture.daemon as unknown as {+ sessions: Map<string, ActiveSessionState>;+ closingSessions: Map<string, { promise: Promise<void>; reason: "shutdown"; killedEffects?: Promise<void> }>;+ passivatingSessions: Map<string, Promise<void>>;+ createRuntime(command: Extract<DaemonCommand, { type: "create" }>): Promise<ActiveSessionState>;+ findPassiveRlmSubagent(id: string): Promise<unknown>;+ hydratePassiveRlmSubagent(passive: unknown): Promise<ActiveSessionState>;+ rehydrateCompletedRlmSubagent(+ parent: ActiveSessionState,+ entry: { childId: string; sessionFile: string },+ ): Promise<ActiveSessionState>;+ waitForBoundSession(state: ActiveSessionState): Promise<ActiveSessionState>;+ };+ const rootState = await internals.createRuntime({ type: "create", sessionPath: fixture.parentSessionFile });+ const passive = await internals.findPassiveRlmSubagent(fixture.childId);+ if (!passive) throw new Error("Missing passive child");+ const closingChild = makeState("closing-child", rootState.activeSessionId);+ const refreshedChild = makeState("refreshed-child", rootState.activeSessionId);+ Object.assign(closingChild.runtime, { session: { sessionFile: fixture.childSessionFile } });+ Object.assign(refreshedChild.runtime, { session: { sessionFile: fixture.childSessionFile } });+ const passivation = passivationGate.then(() => {+ internals.sessions.delete(closingChild.activeSessionId);+ internals.closingSessions.delete(closingChild.activeSessionId);+ throw new Error("passivation failed");+ });+ let hydrationAttempts = 0;+ internals.rehydrateCompletedRlmSubagent = vi.fn(async () => {+ if (++hydrationAttempts === 1) {+ internals.sessions.set(closingChild.activeSessionId, closingChild);+ internals.closingSessions.set(closingChild.activeSessionId, {+ promise: passivation,+ reason: "shutdown",+ });+ internals.passivatingSessions.set(resolve(fixture.childSessionFile), passivation);+ markRaceStarted();+ return internals.waitForBoundSession(closingChild);+ }+ internals.sessions.set(refreshedChild.activeSessionId, refreshedChild);+ return refreshedChild;+ });+ internals.findPassiveRlmSubagent = vi.fn(async () => passive);++ const hydration = internals.hydratePassiveRlmSubagent(passive);+ await raceStarted;+ releasePassivation();++ await expect(hydration).resolves.toBe(refreshedChild);+ expect(hydrationAttempts).toBe(2);+ } finally {+ releasePassivation();+ rmSync(tempDir, { recursive: true, force: true });+ }+ });++ it("rehydrates a passivated parent before publishing its racing child", async () => {+ const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-daemon-parent-passivation-race-"));+ let releaseParentDispose!: () => void;+ const parentDisposeGate = new Promise<void>((resolve) => {+ releaseParentDispose = resolve;+ });+ let markParentDisposeStarted!: () => void;+ const parentDisposeStarted = new Promise<void>((resolve) => {+ markParentDisposeStarted = resolve;+ });+ try {+ const fixture = makePersistedRlmDaemonFixture(tempDir, {+ childDisposeStarted: markParentDisposeStarted,+ childDisposeGate: parentDisposeGate,+ });+ const internals = fixture.daemon as unknown as {+ sessions: Map<string, ActiveSessionState>;+ createRuntime(command: Extract<DaemonCommand, { type: "create" }>): Promise<ActiveSessionState>;+ getOrHydrateBoundSessionState(id: string): Promise<ActiveSessionState>;+ passivateIdleChildren(threshold: number, now: number, limit: number): Promise<number>;+ };+ const rootState = await internals.createRuntime({ type: "create", sessionPath: fixture.parentSessionFile });+ const parentState = await internals.createRuntime({ type: "create", sessionPath: fixture.childSessionFile });+ (+ rootState.runtime.session as unknown as { releaseFinishedRlmChildSession: ReturnType<typeof vi.fn> }+ ).releaseFinishedRlmChildSession = vi.fn(() => vi.fn());++ const passivation = internals.passivateIdleChildren(90, Date.parse("2036-08-01T12:00:00Z"), 1);+ await parentDisposeStarted;+ const hydration = internals.getOrHydrateBoundSessionState(fixture.grandchildId);+ let hydrationSettled = false;+ void hydration.finally(() => {+ hydrationSettled = true;+ });+ await Promise.resolve();+ expect(hydrationSettled).toBe(false);+ releaseParentDispose();++ await expect(passivation).resolves.toBe(1);+ const grandchildState = await hydration;+ const reboundParentId = grandchildState.runtime.metadata.parentActiveSessionId;+ expect(internals.sessions.has(parentState.activeSessionId)).toBe(false);+ expect(reboundParentId).toBeDefined();+ expect(internals.sessions.has(reboundParentId!)).toBe(true);+ expect(grandchildState.runtime.metadata.rlmChildId).toBe(fixture.grandchildId);+ } finally {+ releaseParentDispose();+ rmSync(tempDir, { recursive: true, force: true });+ }+ });++ it("keeps a child resident while an attach snapshot is in flight", async () => {+ const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-daemon-attach-passivation-race-"));+ let releaseSnapshot!: () => void;+ const snapshotGate = new Promise<void>((resolve) => {+ releaseSnapshot = resolve;+ });+ try {+ const fixture = makePersistedRlmDaemonFixture(tempDir);+ const internals = fixture.daemon as unknown as {+ sessions: Map<string, ActiveSessionState>;+ createRuntime(command: Extract<DaemonCommand, { type: "create" }>): Promise<ActiveSessionState>;+ createAttachResult: ReturnType<typeof vi.fn>;+ handleCommand(client: DaemonSocketClient, command: DaemonCommand): Promise<unknown>;+ passivateIdleChildren(threshold: number, now: number, limit: number): Promise<number>;+ };+ const parentState = await internals.createRuntime({ type: "create", sessionPath: fixture.parentSessionFile });+ const childState = await internals.createRuntime({ type: "create", sessionPath: fixture.childSessionFile });+ const client = makeClient("attach-client", childState.activeSessionId);+ client.attachedActiveSessionIds.clear();+ internals.createAttachResult = vi.fn(async () => {+ await snapshotGate;+ return { activeSessionId: childState.activeSessionId, snapshot: {}, lastEventSequence: 0 };+ });++ const attach = internals.handleCommand(client, {+ type: "attach",+ activeSessionId: childState.activeSessionId,+ });+ await vi.waitFor(() => expect(childState.pendingAttaches).toBe(1));+ await expect(internals.passivateIdleChildren(90, Date.parse("2036-08-01T12:00:00Z"), 1)).resolves.toBe(0);+ expect(internals.sessions.get(childState.activeSessionId)).toBe(childState);+ expect(parentState.runtime.session.releaseFinishedRlmChildSession).not.toHaveBeenCalled();++ releaseSnapshot();+ await attach;+ expect(childState.pendingAttaches).toBe(0);+ expect(childState.clients).toContain(client);+ expect(client.attachedActiveSessionIds).toContain(childState.activeSessionId);+ } finally {+ releaseSnapshot();+ rmSync(tempDir, { recursive: true, force: true });+ }+ });++ it("does not passivate a child that starts streaming during the fence snapshot", async () => {+ const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-daemon-passivation-stream-race-"));+ try {+ const fixture = makePersistedRlmDaemonFixture(tempDir);+ const internals = fixture.daemon as unknown as {+ createRuntime(command: Extract<DaemonCommand, { type: "create" }>): Promise<ActiveSessionState>;+ listPassiveRlmSubagents: ReturnType<typeof vi.fn>;+ passivateIdleChildren(threshold: number, now: number, limit: number): Promise<number>;+ };+ const parentState = await internals.createRuntime({ type: "create", sessionPath: fixture.parentSessionFile });+ const childState = await internals.createRuntime({ type: "create", sessionPath: fixture.childSessionFile });+ const childSession = childState.runtime.session as unknown as {+ isStreaming: boolean;+ isSessionActive: boolean;+ abort: ReturnType<typeof vi.fn>;+ };+ let passiveListCalls = 0;+ internals.listPassiveRlmSubagents = vi.fn(async () => {+ passiveListCalls++;+ if (passiveListCalls === 2) {+ childSession.isStreaming = true;+ childSession.isSessionActive = true;+ }+ return [];+ });++ await expect(internals.passivateIdleChildren(90, Date.parse("2036-08-01T12:00:00Z"), 1)).resolves.toBe(0);+ expect(passiveListCalls).toBe(2);+ expect(childSession.abort).not.toHaveBeenCalled();+ expect(parentState.runtime.session.releaseFinishedRlmChildSession).not.toHaveBeenCalled();+ } finally {+ rmSync(tempDir, { recursive: true, force: true });+ }+ });++ it("re-adopts a resident child when its passivation close fails", async () => {+ const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-daemon-passivation-close-failure-"));+ let releaseAbort!: () => void;+ const abortGate = new Promise<void>((resolve) => {+ releaseAbort = resolve;+ });+ let markAbortStarted!: () => void;+ const abortStarted = new Promise<void>((resolve) => {+ markAbortStarted = resolve;+ });+ try {+ const fixture = makePersistedRlmDaemonFixture(tempDir);+ const internals = fixture.daemon as unknown as {+ sessions: Map<string, ActiveSessionState>;+ createAgentMessageController(+ getCurrentState: () => ActiveSessionState | undefined,+ ): AgentSessionMessageController;+ createRuntime(command: Extract<DaemonCommand, { type: "create" }>): Promise<ActiveSessionState>;+ passivateIdleChildren(threshold: number, now: number, limit: number): Promise<number>;+ };+ const parentState = await internals.createRuntime({ type: "create", sessionPath: fixture.parentSessionFile });+ const childState = await internals.createRuntime({ type: "create", sessionPath: fixture.childSessionFile });+ const parentSession = parentState.runtime.session as unknown as {+ releaseFinishedRlmChildSession: ReturnType<typeof vi.fn>;+ retainFinishedRlmChildSession: ReturnType<typeof vi.fn>;+ };+ let parentOwnsChild = true;+ let forwarderActive = true;+ const parentUpdates: string[] = [];+ const emitChildUpdate = (recap: string) => {+ if (forwarderActive) parentUpdates.push(recap);+ };+ const unsubscribeForwarder = vi.fn(() => {+ forwarderActive = false;+ });+ parentSession.releaseFinishedRlmChildSession = vi.fn(() => {+ if (!parentOwnsChild) return false;+ parentOwnsChild = false;+ return unsubscribeForwarder;+ });+ parentSession.retainFinishedRlmChildSession = vi.fn(+ (_childId: string, _childSession: unknown, unsubscribe: () => void) => {+ parentOwnsChild = true;+ forwarderActive = unsubscribe === unsubscribeForwarder;+ return true;+ },+ );+ childState.unsubscribe = vi+ .fn()+ .mockImplementationOnce(() => {+ throw new Error("unsubscribe failed");+ })+ .mockImplementation(() => undefined);+ const childSession = childState.runtime.session as unknown as { abort: ReturnType<typeof vi.fn> };+ childSession.abort = vi.fn(async () => {+ markAbortStarted();+ await abortGate;+ });++ const passivation = internals.passivateIdleChildren(90, Date.parse("2036-08-01T12:00:00Z"), 1);+ await abortStarted;+ const explicitOpen = internals.createRuntime({ type: "create", sessionPath: fixture.childSessionFile });+ const delivery = internals+ .createAgentMessageController(() => parentState)+ .sendAgentMessage({ target: fixture.childId, message: "continue after failed passivation" });+ releaseAbort();++ await expect(passivation).rejects.toThrow("unsubscribe failed");+ await expect(explicitOpen).resolves.toBe(childState);+ await expect(delivery).resolves.toMatchObject({ deliveryStatus: "delivered" });+ expect(internals.sessions.get(childState.activeSessionId)).toBe(childState);+ expect(parentOwnsChild).toBe(true);+ expect(parentSession.retainFinishedRlmChildSession).toHaveBeenCalledWith(+ fixture.childId,+ childState.runtime.session,+ unsubscribeForwarder,+ );+ expect(unsubscribeForwarder).not.toHaveBeenCalled();+ emitChildUpdate("recap after failed close");+ expect(parentUpdates).toEqual(["recap after failed close"]);++ await expect(internals.passivateIdleChildren(90, Date.parse("2036-08-01T12:00:00Z"), 1)).resolves.toBe(1);+ expect(parentSession.releaseFinishedRlmChildSession).toHaveBeenCalledTimes(2);+ expect(unsubscribeForwarder).toHaveBeenCalledOnce();+ emitChildUpdate("recap after successful close");+ expect(parentUpdates).toEqual(["recap after failed close"]);+ expect(internals.sessions.has(childState.activeSessionId)).toBe(false);+ } finally {+ releaseAbort();+ rmSync(tempDir, { recursive: true, force: true });+ }+ });++ it("limits each worker sweep and leaves non-leaf children resident", async () => {+ const daemon = new AgentDaemon("/tmp/prime-agent-passivation-cap.sock", {+ defaultSessionConfig: { agentDir: "/tmp", cwd: "/tmp" },+ createRuntime: vi.fn(),+ });+ const root = makeState("root");+ const oldestLeaf = makeState("oldest-leaf", "root");+ const nextLeaf = makeState("next-leaf", "root");+ const queuedLeaf = makeState("queued-leaf", "root");+ const nonLeaf = makeState("non-leaf", "root");+ const nested = makeState("nested", "non-leaf");+ const states = [root, oldestLeaf, nextLeaf, queuedLeaf, nonLeaf, nested];+ const internals = daemon as unknown as {+ sessions: Map<string, ActiveSessionState>;+ listPassiveRlmSubagents: ReturnType<typeof vi.fn>;+ sessionPassivationSnapshot: ReturnType<typeof vi.fn>;+ passivateSession: ReturnType<typeof vi.fn>;+ passivateIdleChildren(threshold: number, now: number, limit: number): Promise<number>;+ };+ for (const state of states) internals.sessions.set(state.activeSessionId, state);+ const order = new Map([+ [oldestLeaf, 1],+ [nextLeaf, 2],+ [queuedLeaf, 3],+ [nested, 4],+ [nonLeaf, 5],+ [root, 6],+ ]);+ internals.listPassiveRlmSubagents = vi.fn(async () => []);+ internals.sessionPassivationSnapshot = vi.fn(async (state: ActiveSessionState) => ({+ isSessionActive: false,+ attachedClients: 0,+ hasRegisteredHeartbeat: false,+ hasRegisteredCronJob: false,+ lastActivityAt: order.get(state) ?? 99,+ hasParent: state !== root,+ hasNonPassiveDescendants: state === nonLeaf,+ isHydrating: false,+ }));+ internals.passivateSession = vi.fn(async () => true);++ await expect(internals.passivateIdleChildren(90, 200 * 60_000, 2)).resolves.toBe(2);+ expect(internals.sessionPassivationSnapshot).toHaveBeenCalledTimes(states.length);+ expect(internals.passivateSession).toHaveBeenCalledTimes(2);+ expect(internals.passivateSession.mock.calls.map((call) => call[0])).toEqual([oldestLeaf, nextLeaf]);+ expect(internals.passivateSession).not.toHaveBeenCalledWith(nonLeaf, expect.anything(), expect.anything());+ expect(internals.passivateSession).not.toHaveBeenCalledWith(queuedLeaf, expect.anything(), expect.anything());+ });++ it("passivates an idle leaf and makes list, attach, and message use the normal passive wake path", async () => {+ const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-daemon-passivate-child-"));+ 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;+ passivateIdleChildren(threshold: number | "off", now: number, limit: number): Promise<number>;+ handleCommand(client: DaemonSocketClient, command: DaemonCommand): Promise<unknown>;+ };+ const parentState = await internals.createRuntime({ type: "create", sessionPath: fixture.parentSessionFile });+ const firstChild = await internals.createRuntime({ type: "create", sessionPath: fixture.childSessionFile });+ const parentSession = parentState.runtime.session as unknown as {+ releaseFinishedRlmChildSession: ReturnType<typeof vi.fn>;+ };+ parentSession.releaseFinishedRlmChildSession = vi.fn(() => vi.fn());++ expect(await internals.passivateIdleChildren(90, Date.parse("2036-08-01T12:00:00Z"), 2)).toBe(1);+ expect(internals.sessions.has(firstChild.activeSessionId)).toBe(false);+ expect(parentSession.releaseFinishedRlmChildSession).toHaveBeenCalledWith(+ fixture.childId,+ firstChild.runtime.session,+ );+ expect(fixture.runtimeSessions[1]?.disposeAsync).toHaveBeenCalledOnce();++ const listed = (await internals.handleCommand(makeClient("list-client", parentState.activeSessionId), {+ type: "list",+ })) as { data: { sessions: Array<Record<string, unknown>> } };+ const passiveRow = listed.data.sessions.find((row) => row.sessionFile === fixture.childSessionFile);+ expect(passiveRow).toMatchObject({ rlmChildId: fixture.childId, sessionName: "renamed-worker" });+ expect(passiveRow?.activeSessionId).toBeUndefined();++ const attachedState = await (+ fixture.daemon as unknown as {+ getOrHydrateBoundSessionState(id: string): Promise<ActiveSessionState>;+ }+ ).getOrHydrateBoundSessionState(String(passiveRow?.sessionId));+ expect(attachedState.runtime.metadata).toMatchObject({ rlmChildId: fixture.childId });++ // Detach so the same runtime can passivate again and prove a2a wake/delivery.+ attachedState?.clients.clear();+ const parentSessionAgain = parentState.runtime.session as unknown as {+ releaseFinishedRlmChildSession: ReturnType<typeof vi.fn>;+ };+ parentSessionAgain.releaseFinishedRlmChildSession = vi.fn(() => vi.fn());+ expect(await internals.passivateIdleChildren(90, Date.parse("2036-08-01T12:00:00Z"), 2)).toBe(1);+ await expect(+ internals+ .createAgentMessageController(() => parentState)+ .sendAgentMessage({+ target: fixture.childId,+ message: "wake after passivation",+ }),+ ).resolves.toMatchObject({ deliveryStatus: "delivered", target: { runtimeKind: "subagent" } });+ expect(fixture.acceptAgentMessagePrompt).toHaveBeenCalledWith(+ expect.stringContaining("wake after passivation"),+ expect.any(Object),+ );+ } finally {+ rmSync(tempDir, { recursive: true, force: true });+ }+ });++ it("keeps an idle child resident while an agent message waits for admission", async () => {+ const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-daemon-admission-passivation-race-"));+ let releaseAdmission!: () => void;+ const admissionGate = new Promise<void>((resolve) => {+ releaseAdmission = resolve;+ });+ let markAdmissionStarted!: () => void;+ const admissionStarted = new Promise<void>((resolve) => {+ markAdmissionStarted = resolve;+ });+ try {+ const fixture = makePersistedRlmDaemonFixture(tempDir, {+ childAdmissionStarted: markAdmissionStarted,+ childAdmissionGate: admissionGate,+ });+ const internals = fixture.daemon as unknown as {+ sessions: Map<string, ActiveSessionState>;+ createRuntime(command: Extract<DaemonCommand, { type: "create" }>): Promise<ActiveSessionState>;+ createAgentMessageController(+ getCurrentState: () => ActiveSessionState | undefined,+ ): AgentSessionMessageController;+ passivateIdleChildren(threshold: number, now: number, limit: number): Promise<number>;+ };+ const parentState = await internals.createRuntime({ type: "create", sessionPath: fixture.parentSessionFile });+ const childState = await internals.createRuntime({ type: "create", sessionPath: fixture.childSessionFile });+ (+ parentState.runtime.session as unknown as { releaseFinishedRlmChildSession: ReturnType<typeof vi.fn> }+ ).releaseFinishedRlmChildSession = vi.fn(() => vi.fn());++ const delivery = internals+ .createAgentMessageController(() => parentState)+ .sendAgentMessage({ target: fixture.childId, message: "admit after gate" });+ await admissionStarted;- const [openedState, hydratedState] = await joined;- expect(hydratedState).toBe(openedState);- expect(openedState.runtime.session.sessionFile).toBe(fixture.childSessionFile);- expect(fixture.createRuntime).toHaveBeenCalledTimes(2);+ await expect(internals.passivateIdleChildren(90, Date.parse("2036-08-01T12:00:00Z"), 1)).resolves.toBe(0);+ expect(internals.sessions.get(childState.activeSessionId)).toBe(childState);+ releaseAdmission();+ await expect(delivery).resolves.toMatchObject({ deliveryStatus: "delivered" });} finally {- releaseOpen();- openAsyncSpy?.mockRestore();+ releaseAdmission();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;+ it("waits for passivation before rehydrating and delivering a racing a2a message", async () => {+ const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-daemon-passivation-race-"));+ let releaseDispose!: () => void;+ const disposeGate = new Promise<void>((resolve) => {+ releaseDispose = resolve;});- let markHydrationStarted!: () => void;- const hydrationStarted = new Promise<void>((resolveStarted) => {- markHydrationStarted = resolveStarted;+ let markDisposeStarted!: () => void;+ const disposeStarted = new Promise<void>((resolve) => {+ markDisposeStarted = resolve;});try {const fixture = makePersistedRlmDaemonFixture(tempDir, {- childRuntimeStarted: markHydrationStarted,- childRuntimeGate: hydrationGate,+ childDisposeStarted: markDisposeStarted,+ childDisposeGate: disposeGate,});const internals = fixture.daemon as unknown as {sessions: Map<string, ActiveSessionState>;@@ -4471,30 +6047,42 @@ describe("daemon mode helpers", () => {createAgentMessageController(getCurrentState: () => ActiveSessionState | undefined,): AgentSessionMessageController;+ passivateIdleChildren(threshold: number, now: number, limit: number): Promise<number>;};- 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 parentState = await internals.createRuntime({ type: "create", sessionPath: fixture.parentSessionFile });+ const childState = await internals.createRuntime({ type: "create", sessionPath: fixture.childSessionFile });+ (+ parentState.runtime.session as unknown as { releaseFinishedRlmChildSession: ReturnType<typeof vi.fn> }+ ).releaseFinishedRlmChildSession = vi.fn(() => vi.fn());++ const passivation = internals.passivateIdleChildren(90, Date.parse("2036-08-01T12:00:00Z"), 1);+ await disposeStarted;+ // The child is still resident and closing while dispose is blocked. A child-ID+ // selector must join passivation instead of treating that resident state as targetable.+ expect(internals.sessions.get(childState.activeSessionId)).toBe(childState);+ const delivery = internals+ .createAgentMessageController(() => parentState)+ .sendAgentMessage({+ target: fixture.childId,+ message: "arrived while passivating",+ });const explicitOpen = internals.createRuntime({ type: "create", sessionPath: fixture.childSessionFile });- const secondMessage = controller.sendAgentMessage({ target: fixture.childId, message: "second" });+ await Promise.resolve();expect(fixture.createRuntime).toHaveBeenCalledTimes(2);+ releaseDispose();- 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.metadata.kind === "subagent"),- ).toHaveLength(1);- expect(fixture.acceptAgentMessagePrompt).toHaveBeenCalledTimes(2);+ await expect(passivation).resolves.toBe(1);+ await expect(delivery).resolves.toMatchObject({ deliveryStatus: "delivered" });+ await expect(explicitOpen).resolves.toMatchObject({+ runtime: { metadata: { rlmChildId: fixture.childId } },+ });+ expect(fixture.createRuntime).toHaveBeenCalledTimes(3);+ expect(fixture.acceptAgentMessagePrompt).toHaveBeenCalledWith(+ expect.stringContaining("arrived while passivating"),+ expect.any(Object),+ );} finally {- releaseHydration();+ releaseDispose();rmSync(tempDir, { recursive: true, force: true });}});@@ -4508,9 +6096,16 @@ describe("daemon mode helpers", () => {};await internals.createRuntime({ type: "create", sessionPath: fixture.parentSessionFile });- const childState = await internals.createRuntime({ type: "create", sessionPath: fixture.childSessionFile });+ const childState = await internals.createRuntime({+ type: "create",+ sessionPath: fixture.childSessionFile,+ name: "explicit-new-name",+ env: { HERDR_PANE_ID: "pane-42" },+ });expect(childState.runtime.metadata).toMatchObject({ kind: "subagent", rlmChildId: fixture.childId });+ expect(childState.runtime.session.sessionName).toBe("explicit-new-name");+ expect(childState.clientEnv).toEqual({ HERDR_PANE_ID: "pane-42" });expect(fixture.createRuntime).toHaveBeenCalledTimes(2);} finally {rmSync(tempDir, { recursive: true, force: true });@@ -5016,6 +6611,332 @@ describe("daemon mode helpers", () => {}});+ it("applies killed effects when kill joins a passivation close", async () => {+ const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-daemon-kill-passivation-race-"));+ let releaseDispose!: () => void;+ const disposeGate = new Promise<void>((resolve) => {+ releaseDispose = resolve;+ });+ let markDisposeStarted!: () => void;+ const disposeStarted = new Promise<void>((resolve) => {+ markDisposeStarted = resolve;+ });+ try {+ const daemon = new AgentDaemon(join(tempDir, "daemon.sock"), {+ defaultSessionConfig: { agentDir: tempDir, cwd: tempDir },+ createRuntime: async () => {+ throw new Error("unexpected runtime creation");+ },+ });+ const sessionFile = join(tempDir, "session.jsonl");+ const appendSessionState = vi.fn();+ const state = makeState("active-1");+ state.extensionUiRequests = new Map();+ state.runtime = {+ metadata: { kind: "subagent", createdAt: 1 },+ cwd: tempDir,+ dispose: vi.fn(async () => {+ markDisposeStarted();+ await disposeGate;+ }),+ session: {+ sessionId: "session-1",+ sessionFile,+ messages: ["user message"],+ isBashRunning: false,+ sessionManager: { appendSessionState, hasUserContent: () => true },+ abort: vi.fn(async () => {}),+ },+ } as never;+ const internals = daemon as unknown as {+ cronStore: AgentCronJobStore;+ sessions: Map<string, ActiveSessionState>;+ closeSession(+ state: ActiveSessionState,+ reason: "shutdown",+ waitForAbort: boolean,+ cascadeChildren: boolean,+ ): Promise<void>;+ handleCommand(client: DaemonSocketClient, command: DaemonCommand): Promise<unknown>;+ };+ internals.sessions.set(state.activeSessionId, state);+ const cron = internals.cronStore.create({+ activeSessionId: state.activeSessionId,+ sessionId: "session-1",+ sessionFile,+ cwd: tempDir,+ scheduleText: "in 1h",+ prompt: "check long run",+ now: new Date("2026-01-01T12:00:00.000Z"),+ });++ const passivationClose = internals.closeSession(state, "shutdown", true, false);+ await disposeStarted;+ const kill = internals.handleCommand(makeClient("client-1", state.activeSessionId), {+ id: "command-1",+ type: "kill",+ activeSessionId: state.activeSessionId,+ });+ releaseDispose();++ await expect(Promise.all([passivationClose, kill])).resolves.toBeDefined();+ expect(internals.cronStore.list().find((job) => job.id === cron.id)).toMatchObject({ status: "cancelled" });+ expect(appendSessionState).toHaveBeenCalledOnce();+ expect(appendSessionState).toHaveBeenCalledWith({ status: "archived" });+ } finally {+ releaseDispose();+ rmSync(tempDir, { recursive: true, force: true });+ }+ });++ it("applies a stronger reason after the joined close rejects", async () => {+ const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-daemon-kill-failed-close-race-"));+ let rejectClose!: (error: Error) => void;+ const failedClose = new Promise<void>((_resolve, reject) => {+ rejectClose = reject;+ });+ try {+ const daemon = new AgentDaemon(join(tempDir, "daemon.sock"), {+ defaultSessionConfig: { agentDir: tempDir, cwd: tempDir },+ createRuntime: async () => {+ throw new Error("unexpected runtime creation");+ },+ });+ const appendSessionState = vi.fn();+ const state = makeState("active-1");+ state.runtime = {+ ...state.runtime,+ cwd: tempDir,+ session: {+ sessionId: "session-1",+ sessionFile: join(tempDir, "session.jsonl"),+ sessionManager: { appendSessionState },+ },+ } as never;+ const existingClose = {+ promise: failedClose,+ reason: "shutdown" as const,+ descendants: new Set<ActiveSessionState>(),+ };+ const internals = daemon as unknown as {+ cronStore: AgentCronJobStore;+ closingSessions: Map<string, typeof existingClose>;+ closeSession(state: ActiveSessionState, reason: "killed"): Promise<void>;+ };+ internals.closingSessions.set(state.activeSessionId, existingClose);+ const cron = internals.cronStore.create({+ activeSessionId: state.activeSessionId,+ sessionId: "session-1",+ sessionFile: join(tempDir, "session.jsonl"),+ cwd: tempDir,+ scheduleText: "in 1h",+ prompt: "scheduled work",+ });++ const kill = internals.closeSession(state, "killed");+ rejectClose(new Error("dispose failed"));++ await expect(kill).rejects.toThrow("dispose failed");+ expect(internals.cronStore.list().find((job) => job.id === cron.id)).toMatchObject({ status: "cancelled" });+ expect(appendSessionState).toHaveBeenCalledWith({ status: "archived" });+ expect(existingClose.reason).toBe("killed");+ } finally {+ rmSync(tempDir, { recursive: true, force: true });+ }+ });++ it("finishes a reason upgrade after one target fails to archive", async () => {+ const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-daemon-kill-archive-failure-"));+ try {+ const daemon = new AgentDaemon(join(tempDir, "daemon.sock"), {+ defaultSessionConfig: { agentDir: tempDir, cwd: tempDir },+ createRuntime: async () => {+ throw new Error("unexpected runtime creation");+ },+ });+ const parent = makeState("parent");+ const child = makeState("child", parent.activeSessionId);+ const parentArchive = vi.fn(() => {+ throw new Error("archive failed");+ });+ const childArchive = vi.fn();+ for (const [state, sessionId, appendSessionState] of [+ [parent, "session-parent", parentArchive],+ [child, "session-child", childArchive],+ ] as const) {+ state.runtime = {+ ...state.runtime,+ cwd: tempDir,+ session: {+ sessionId,+ sessionFile: join(tempDir, `${sessionId}.jsonl`),+ sessionManager: { appendSessionState },+ },+ } as never;+ }+ const existingClose = {+ promise: Promise.resolve(),+ reason: "shutdown" as "shutdown" | "killed",+ descendants: new Set([child]),+ };+ const internals = daemon as unknown as {+ cronStore: AgentCronJobStore;+ closingSessions: Map<string, typeof existingClose>;+ closeSession(state: ActiveSessionState, reason: "killed"): Promise<void>;+ };+ internals.closingSessions.set(parent.activeSessionId, existingClose);+ const jobs = [parent, child].map((state) =>+ internals.cronStore.create({+ activeSessionId: state.activeSessionId,+ sessionId: state.runtime.session.sessionId,+ sessionFile: state.runtime.session.sessionFile!,+ cwd: tempDir,+ scheduleText: "in 1h",+ prompt: "scheduled work",+ }),+ );++ await expect(internals.closeSession(parent, "killed")).rejects.toThrow("archive failed");++ for (const job of jobs) {+ expect(internals.cronStore.list().find((candidate) => candidate.id === job.id)).toMatchObject({+ status: "cancelled",+ });+ }+ expect(parentArchive).toHaveBeenCalledOnce();+ expect(childArchive).toHaveBeenCalledWith({ status: "archived" });+ expect(existingClose.reason).toBe("killed");+ await expect(internals.closeSession(parent, "killed")).resolves.toBeUndefined();+ expect(parentArchive).toHaveBeenCalledOnce();+ expect(childArchive).toHaveBeenCalledOnce();+ } finally {+ rmSync(tempDir, { recursive: true, force: true });+ }+ });++ it("upgrades resident descendants when kill joins a parent shutdown close", async () => {+ const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-daemon-kill-parent-shutdown-race-"));+ let releaseParentDispose!: () => void;+ const parentDisposeGate = new Promise<void>((resolve) => {+ releaseParentDispose = resolve;+ });+ let markParentDisposeStarted!: () => void;+ const parentDisposeStarted = new Promise<void>((resolve) => {+ markParentDisposeStarted = resolve;+ });+ try {+ const fixture = makePersistedRlmDaemonFixture(tempDir);+ const internals = fixture.daemon as unknown as {+ cronStore: AgentCronJobStore;+ createRuntime(command: Extract<DaemonCommand, { type: "create" }>): Promise<ActiveSessionState>;+ closeSession(state: ActiveSessionState, reason: "shutdown"): Promise<void>;+ handleCommand(client: DaemonSocketClient, command: DaemonCommand): Promise<unknown>;+ };+ const parentState = await internals.createRuntime({ type: "create", sessionPath: fixture.parentSessionFile });+ const childState = await internals.createRuntime({ type: "create", sessionPath: fixture.childSessionFile });+ parentState.runtime.dispose = vi.fn(async () => {+ markParentDisposeStarted();+ await parentDisposeGate;+ });+ const childJob = internals.cronStore.create({+ activeSessionId: childState.activeSessionId,+ sessionId: childState.runtime.session.sessionId,+ sessionFile: fixture.childSessionFile,+ cwd: tempDir,+ scheduleText: "every 5m",+ prompt: "scheduled child work",+ });++ const shutdownClose = internals.closeSession(parentState, "shutdown");+ await parentDisposeStarted;+ const kill = internals.handleCommand(makeClient("client-1", parentState.activeSessionId), {+ id: "command-1",+ type: "kill",+ activeSessionId: parentState.activeSessionId,+ });+ releaseParentDispose();++ await expect(Promise.all([shutdownClose, kill])).resolves.toBeDefined();+ expect(internals.cronStore.list().find((job) => job.id === childJob.id)).toMatchObject({+ status: "cancelled",+ });+ expect(SessionManager.open(fixture.childSessionFile).getSessionState()).toEqual({ status: "archived" });+ } finally {+ releaseParentDispose();+ rmSync(tempDir, { recursive: true, force: true });+ }+ });++ it("does not duplicate effects when kill joins a completed close", async () => {+ const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-daemon-kill-completed-race-"));+ let releaseDispose!: () => void;+ const disposeGate = new Promise<void>((resolve) => {+ releaseDispose = resolve;+ });+ let markDisposeStarted!: () => void;+ const disposeStarted = new Promise<void>((resolve) => {+ markDisposeStarted = resolve;+ });+ try {+ const daemon = new AgentDaemon(join(tempDir, "daemon.sock"), {+ defaultSessionConfig: { agentDir: tempDir, cwd: tempDir },+ createRuntime: async () => {+ throw new Error("unexpected runtime creation");+ },+ });+ const appendSessionState = vi.fn();+ const state = makeState("active-1");+ state.extensionUiRequests = new Map();+ state.runtime = {+ metadata: { kind: "subagent", createdAt: 1 },+ cwd: tempDir,+ dispose: vi.fn(async () => {+ markDisposeStarted();+ await disposeGate;+ }),+ session: {+ sessionId: "session-1",+ sessionFile: join(tempDir, "session.jsonl"),+ messages: ["user message"],+ isBashRunning: false,+ sessionManager: { appendSessionState, hasUserContent: () => true },+ },+ } as never;+ const internals = daemon as unknown as {+ cronStore: AgentCronJobStore;+ sessions: Map<string, ActiveSessionState>;+ closeSession(state: ActiveSessionState, reason: "completed"): Promise<void>;+ handleCommand(client: DaemonSocketClient, command: DaemonCommand): Promise<unknown>;+ };+ internals.sessions.set(state.activeSessionId, state);+ const cron = internals.cronStore.create({+ activeSessionId: state.activeSessionId,+ sessionId: "session-1",+ sessionFile: join(tempDir, "session.jsonl"),+ cwd: tempDir,+ scheduleText: "in 1h",+ prompt: "check completed run",+ });++ const completedClose = internals.closeSession(state, "completed");+ await disposeStarted;+ const kill = internals.handleCommand(makeClient("client-1", state.activeSessionId), {+ id: "command-1",+ type: "kill",+ activeSessionId: state.activeSessionId,+ });+ releaseDispose();++ await expect(Promise.all([completedClose, kill])).resolves.toBeDefined();+ expect(internals.cronStore.list().find((job) => job.id === cron.id)).toMatchObject({ status: "cancelled" });+ expect(appendSessionState).toHaveBeenCalledOnce();+ expect(appendSessionState).toHaveBeenCalledWith({ status: "archived" });+ } finally {+ releaseDispose();+ rmSync(tempDir, { recursive: true, force: true });+ }+ });+it("cancels scheduled jobs when a saved session is deleted", async () => {const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-daemon-delete-cron-"));try {@@ -6602,12 +8523,24 @@ function makeCronJob(input: {function makePersistedRlmDaemonFixture(tempDir: string,- options: { childRuntimeStarted?: () => void; childRuntimeGate?: Promise<void> } = {},+ options: {+ childRuntimeStarted?: () => void;+ childRuntimeGate?: Promise<void>;+ childBindingStarted?: () => void;+ childBindingGate?: Promise<void>;+ grandchildRuntimeStarted?: () => void;+ grandchildRuntimeGate?: Promise<void>;+ childDisposeStarted?: () => void;+ childDisposeGate?: Promise<void>;+ childAdmissionStarted?: () => void;+ childAdmissionGate?: Promise<void>;+ } = {},) {const sessionDir = join(tempDir, "sessions");const parentManager = SessionManager.create(tempDir, sessionDir);parentManager.newSession();parentManager.appendSessionInfo("Parent");+ parentManager.appendSessionState({ status: "active" });const parentSessionFile = parentManager.getSessionFile();const parentArtifactDir = parentManager.getSessionArtifactDir();if (!parentSessionFile || !parentArtifactDir) {@@ -6677,17 +8610,41 @@ function makePersistedRlmDaemonFixture();const acceptAgentMessagePrompt = vi.fn(- (_message: string, options?: { preflightResult?: (didSucceed: boolean) => void }) => {- options?.preflightResult?.(true);- return Promise.resolve();+ async (_message: string, promptOptions?: { preflightResult?: (didSucceed: boolean) => void }) => {+ if (options.childAdmissionGate) {+ options.childAdmissionStarted?.();+ await options.childAdmissionGate;+ }+ promptOptions?.preflightResult?.(true);},);+ const runtimeSessions: Array<ReturnType<typeof makeRuntimeSession>> = [];const createRuntime = vi.fn(async (runtimeOptions: Parameters<CreateAgentSessionRuntimeFactory>[0]) => {- if (runtimeOptions.sessionManager.getSessionFile() === childSessionFile && options.childRuntimeGate) {+ const sessionFile = runtimeOptions.sessionManager.getSessionFile();+ const isChild = sessionFile === childSessionFile;+ const isGrandchild = sessionFile === grandchildSessionFile;+ if (isChild && options.childRuntimeGate) {options.childRuntimeStarted?.();await options.childRuntimeGate;}+ if (isGrandchild && options.grandchildRuntimeGate) {+ options.grandchildRuntimeStarted?.();+ await options.grandchildRuntimeGate;+ }const runtimeSession = makeRuntimeSession(runtimeOptions.sessionManager);+ runtimeSessions.push(runtimeSession);+ if (isChild && options.childBindingGate) {+ runtimeSession.bindExtensions = vi.fn(async () => {+ options.childBindingStarted?.();+ await options.childBindingGate;+ });+ }+ if (isChild && options.childDisposeGate) {+ runtimeSession.disposeAsync = vi.fn(async () => {+ options.childDisposeStarted?.();+ await options.childDisposeGate;+ });+ }Object.assign(runtimeSession, {isStreaming: false,isCompacting: false,@@ -6717,6 +8674,7 @@ function makePersistedRlmDaemonFixture(return {daemon,createRuntime,+ runtimeSessions,acceptAgentMessagePrompt,parentSessionFile,parentArtifactDir,@@ -6747,6 +8705,7 @@ function makeRuntimeSession(setSubagentRuntimeHost: vi.fn(),getRlmChildRunStatus: vi.fn(() => "running"),retainFinishedRlmChildSession: vi.fn(() => true),+ releaseFinishedRlmChildSession: vi.fn(() => vi.fn()),subscribe: vi.fn(() => vi.fn()),bindExtensions: vi.fn(async () => {}),setExecEnvProvider: vi.fn(),@@ -6765,6 +8724,7 @@ function makeState(activeSessionId: string, parentActiveSessionId?: string): Actreturn {activeSessionId,clients: new Set(),+ pendingAttaches: 0,lastEventSequence: 0,runtime: {metadata: {diff --git a/packages/coding-agent/test/daemon-session-list.test.ts b/packages/coding-agent/test/daemon-session-list.test.tsindex 5f53903ae1..f07004737a 100644--- a/packages/coding-agent/test/daemon-session-list.test.ts+++ b/packages/coding-agent/test/daemon-session-list.test.ts@@ -179,6 +179,30 @@ describe("buildSessionList", () => {});});+ it("keeps file-keyed schedule pins on active rows while active ids are being rebound", () => {+ const sessionFile = "/tmp/child.jsonl";+ const [entry] = buildSessionList(+ [makeState({ activeSessionId: "new-active-id", sessionFile })],+ [makeSessionInfo({ id: "child-session", path: sessionFile })],+ [+ makeCronJob({+ id: "stale-heartbeat",+ activeSessionId: "old-active-id",+ sessionFile,+ source: "heartbeat",+ }),+ makeCronJob({+ id: "stale-cron",+ activeSessionId: "old-active-id",+ sessionFile,+ source: "cron",+ }),+ ],+ );++ expect(entry).toMatchObject({ hasRegisteredHeartbeat: true, hasRegisteredCronJob: true });+ });+it("reports accepted in-flight prompts as active with no queued work", () => {const oneMessage = [{ role: "user", content: "hi" }] as unknown as AgentMessage[];const summary = summaryForActiveSession(diff --git a/packages/coding-agent/test/daemon-supervisor-eviction.test.ts b/packages/coding-agent/test/daemon-supervisor-eviction.test.tsindex 990e16e248..6b2542444f 100644--- a/packages/coding-agent/test/daemon-supervisor-eviction.test.ts+++ b/packages/coding-agent/test/daemon-supervisor-eviction.test.ts@@ -30,6 +30,7 @@ interface WorkerFixture {interface SupervisorInternals {workers: Map<string, WorkerFixture>;clients: Set<{ id: string; attachedActiveSessionIds: Set<string> }>;+ idleEvictionFence?: Promise<void>;catalog: { resolve: ReturnType<typeof vi.fn>; stop: ReturnType<typeof vi.fn> };createOrReuseWorker: ReturnType<typeof vi.fn>;stopWorker: ReturnType<typeof vi.fn>;@@ -133,6 +134,65 @@ describe("daemon supervisor whole-tree eviction", () => {expect([...supervisor.workers.keys()].sort()).toEqual(["active", "attached", "cron", "heartbeat"]);});+ it("delegates capped child passivation only to live non-evictable workers", async () => {+ const now = Date.parse("2026-08-01T12:00:00.000Z");+ const supervisor = makeSupervisor();+ const active = makeWorker("active", [+ makeSummary("active-root", now, { isSessionActive: true }),+ makeSummary("idle-child", now, { runtimeKind: "subagent", parentActiveSessionId: "active-root" }),+ ]);+ const whollyIdle = makeWorker("wholly-idle", [makeSummary("idle-root", now)]);+ active.client!.requestWorker.mockResolvedValue({+ type: "response",+ command: "worker_passivate_idle_children",+ success: true,+ data: { count: 1 },+ });+ supervisor.workers.set("active", active);+ supervisor.workers.set("wholly-idle", whollyIdle);++ await supervisor.runIdleEvictionSweep(now);++ expect(active.client?.requestWorker).toHaveBeenCalledWith(+ {+ type: "worker_passivate_idle_children",+ idleEvictionMinutes: 90,+ now,+ limit: 2,+ },+ 30_000,+ );+ expect(whollyIdle.client?.requestWorker).not.toHaveBeenCalled();+ expect(supervisor.stopWorker).toHaveBeenCalledWith(whollyIdle, true);+ });++ it("does not fence unrelated mutations while child passivation is in flight", async () => {+ const now = Date.parse("2026-08-01T12:00:00.000Z");+ const supervisor = makeSupervisor();+ const active = makeWorker("active", [makeSummary("active-root", now, { isSessionActive: true })]);+ let releasePassivation!: () => void;+ active.client!.requestWorker.mockImplementation(+ () =>+ new Promise((resolve) => {+ releasePassivation = () =>+ resolve({+ type: "response",+ command: "worker_passivate_idle_children",+ success: true,+ data: { count: 0 },+ });+ }),+ );+ supervisor.workers.set("active", active);++ const sweep = supervisor.runIdleEvictionSweep(now);+ await vi.waitFor(() => expect(active.client?.requestWorker).toHaveBeenCalledOnce());++ expect(supervisor.idleEvictionFence).toBeUndefined();+ releasePassivation();+ await sweep;+ });+it("uses canonical busy state so a stale parent with a running child is not evicted", async () => {const now = Date.parse("2026-08-01T12:00:00.000Z");const supervisor = makeSupervisor();diff --git a/packages/coding-agent/test/daemon-supervisor-lazy-subagents.test.ts b/packages/coding-agent/test/daemon-supervisor-lazy-subagents.test.tsindex c329408b68..2837da19a0 100644--- a/packages/coding-agent/test/daemon-supervisor-lazy-subagents.test.ts+++ b/packages/coding-agent/test/daemon-supervisor-lazy-subagents.test.ts@@ -11,6 +11,7 @@ interface SupervisorInternals {workers: Map<string, WorkerFixture>;refreshWorkerSummaries(worker: WorkerFixture): Promise<void>;syncAgentPeers(): Promise<void>;+ findSummaryInWorker(worker: WorkerFixture, selector: string): SessionSummary | undefined;}interface WorkerFixture {@@ -67,6 +68,23 @@ function worker(workerId: string, summaries: SessionSummary[] = []): WorkerFixtu}describe("daemon supervisor passive subagent topology", () => {+ it("finds a child summary by its displayed session ID suffix", () => {+ const directory = mkdtempSync(join(tmpdir(), "prime-supervisor-child-suffix-"));+ 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 child = summary({+ id: "bbbb6666777788889999cccc",+ activeSessionId: "bbbb6666777788889999cccc",+ sessionId: "aaaa6666777788889999dddd",+ });+ const resident = worker("first", [child]);++ expect(supervisor.findSummaryInWorker(resident, "88889999cccc")).toBe(child);+ });+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);diff --git a/packages/coding-agent/test/interactive-mode-streaming.test.ts b/packages/coding-agent/test/interactive-mode-streaming.test.tsindex 1419aef040..6b628a4946 100644--- a/packages/coding-agent/test/interactive-mode-streaming.test.ts+++ b/packages/coding-agent/test/interactive-mode-streaming.test.ts@@ -325,4 +325,29 @@ describe("InteractiveMode streaming events", () => {expect(fakeThis.focusEditor).not.toHaveBeenCalled();expect(fakeThis.editor.handleInput).not.toHaveBeenCalled();});++ test("does not pulse renders for background-only subagent work", () => {+ vi.useFakeTimers();+ try {+ const requestRender = vi.fn();+ const mode = Object.create(InteractiveMode.prototype) as InteractiveMode & Record<string, unknown>;+ Object.assign(mode, {+ connectionState: { isStreaming: false },+ subagentSnapshots: new Map([["worker", { id: "worker", status: "running" }]]),+ pulseTimer: undefined,+ ui: { requestRender },+ });+ const updatePulse = Reflect.get(InteractiveMode.prototype, "updateWorkingPulse") as (+ this: typeof mode,+ ) => void;++ updatePulse.call(mode);+ vi.advanceTimersByTime(1000);++ expect(requestRender).not.toHaveBeenCalled();+ expect(Reflect.get(mode, "pulseTimer")).toBeUndefined();+ } finally {+ vi.useRealTimers();+ }+ });});diff --git a/packages/coding-agent/test/session-action-store.test.ts b/packages/coding-agent/test/session-action-store.test.tsindex 1c204704c6..e6a9ee752c 100644--- a/packages/coding-agent/test/session-action-store.test.ts+++ b/packages/coding-agent/test/session-action-store.test.ts@@ -4,6 +4,7 @@ import {type ActionLifecycle,ActionStore,canEvictWorker,+ canPassivateSession,canSelectSessionAction,type DeliveryPolicy,type RuntimeActivity,@@ -289,3 +290,41 @@ describe("whole-tree eviction capability", () => {expect(canEvictWorker(idleWorker, Number.NaN, now)).toBe(false);});});++describe("child passivation capability", () => {+ const now = Date.parse("2026-08-01T12:00:00.000Z");+ const idleChild = {+ isSessionActive: false,+ attachedClients: 0,+ hasRegisteredHeartbeat: false,+ hasRegisteredCronJob: false,+ lastActivityAt: now - 90 * 60_000,+ hasParent: true,+ hasNonPassiveDescendants: false,+ isHydrating: false,+ };++ it("accepts an idle leaf child at the shared inclusive threshold", () => {+ expect(canPassivateSession(idleChild, 90, now)).toBe(true);+ });++ it.each([+ ["root", { hasParent: false }],+ ["child with a resident descendant", { hasNonPassiveDescendants: true }],+ ["hydrating child", { isHydrating: true }],+ ["busy child", { isSessionActive: true }],+ ["attached child", { attachedClients: 1 }],+ ["heartbeat child", { hasRegisteredHeartbeat: true }],+ ["cron child", { hasRegisteredCronJob: true }],+ ["recent child", { lastActivityAt: now - 89 * 60_000 }],+ ["child without activity time", { lastActivityAt: Number.NaN }],+ ])("rejects a %s", (_name, override) => {+ expect(canPassivateSession({ ...idleChild, ...override }, 90, now)).toBe(false);+ });++ it("shares the whole-tree off and invalid threshold behavior", () => {+ expect(canPassivateSession(idleChild, "off", now)).toBe(false);+ expect(canPassivateSession(idleChild, 0, now)).toBe(false);+ expect(canPassivateSession(idleChild, Number.NaN, now)).toBe(false);+ });+});diff --git a/packages/coding-agent/test/session-manager/file-operations.test.ts b/packages/coding-agent/test/session-manager/file-operations.test.tsindex 20fcac326d..6125b4c3b9 100644--- a/packages/coding-agent/test/session-manager/file-operations.test.ts+++ b/packages/coding-agent/test/session-manager/file-operations.test.ts@@ -158,6 +158,37 @@ describe("loadEntriesFromFile", () => {});describe("session tree metadata", () => {+ it.each(["2.5", "2oops", "9007199254740993"])("rejects invalid RLM_DEPTH value %s", (value) => {+ const tempDir = join(tmpdir(), `invalid-root-depth-test-${Date.now()}-${Math.random()}`);+ mkdirSync(tempDir, { recursive: true });+ vi.stubEnv("RLM_DEPTH", value);+ try {+ expect(() => SessionManager.create(tempDir, tempDir)).toThrow("RLM_DEPTH must be a non-negative integer");+ } finally {+ vi.unstubAllEnvs();+ rmSync(tempDir, { recursive: true, force: true });+ }+ });++ it("does not persist an unsafe derived depth", () => {+ const tempDir = join(tmpdir(), `max-parent-depth-test-${Date.now()}-${Math.random()}`);+ mkdirSync(tempDir, { recursive: true });+ try {+ const parent = SessionManager.create(tempDir, tempDir);+ parent.newSession({ rlmDepth: Number.MAX_SAFE_INTEGER });+ parent.flushNow();+ const parentFile = parent.getSessionFile();+ if (!parentFile) throw new Error("Missing parent session file");++ const child = SessionManager.create(tempDir, tempDir);+ child.newSession({ parentSession: parentFile });++ expect(child.getHeader()?.rlmDepth).toBeUndefined();+ } finally {+ rmSync(tempDir, { recursive: true, force: true });+ }+ });+it("persists a derived depth and exposes parent linkage from the header", async () => {const tempDir = join(tmpdir(), `session-tree-test-${Date.now()}-${Math.random()}`);mkdirSync(tempDir, { recursive: true });diff --git a/packages/coding-agent/test/settings-manager.test.ts b/packages/coding-agent/test/settings-manager.test.tsindex 24c051fc3f..bb07a2650a 100644--- a/packages/coding-agent/test/settings-manager.test.ts+++ b/packages/coding-agent/test/settings-manager.test.ts@@ -352,6 +352,15 @@ describe("SettingsManager", () => {expect(errors[0]?.error.message).toContain("Project settings not saved: settings file failed to parse:");expect(readFileSync(settingsPath, "utf-8")).toBe(invalidSettings);});++ it("drains only the requested scope", () => {+ writeFileSync(join(agentDir, "settings.json"), "{ invalid global json");+ writeFileSync(join(projectDir, ".prime", "agent", "settings.json"), "{ invalid project json");+ const manager = SettingsManager.create(projectDir, agentDir);++ expect(manager.drainErrors("global").map((entry) => entry.scope)).toEqual(["global"]);+ expect(manager.drainErrors().map((entry) => entry.scope)).toEqual(["project"]);+ });});describe("project settings directory creation", () => {diff --git a/packages/coding-agent/test/settings-selector.test.ts b/packages/coding-agent/test/settings-selector.test.tsindex 28492b8f5f..81b19973cd 100644--- a/packages/coding-agent/test/settings-selector.test.ts+++ b/packages/coding-agent/test/settings-selector.test.ts@@ -1,6 +1,6 @@import { resetCapabilitiesCache, setCapabilities } from "@earendil-works/pi-tui";import stripAnsi from "strip-ansi";-import { beforeAll, describe, expect, test } from "vitest";+import { beforeAll, describe, expect, test, vi } from "vitest";import {type SettingsCallbacks,type SettingsConfig,@@ -80,4 +80,34 @@ describe("SettingsSelectorComponent", () => {resetCapabilitiesCache();}});++ test("cycles a custom idle eviction value to the next numeric option", () => {+ const onIdleEvictionMinutesChange = vi.fn();+ const component = new SettingsSelectorComponent(+ { ...config, idleEvictionMinutes: 120 },+ { ...callbacks, onIdleEvictionMinutesChange },+ );+ const list = component.getSettingsList();+ for (const character of "idle") list.handleInput(character);++ list.handleInput("\r");++ expect(onIdleEvictionMinutesChange).toHaveBeenCalledWith(180);+ });++ test.each([0.5, 1.5])("round-trips a fractional idle eviction value of %s", (value) => {+ const onIdleEvictionMinutesChange = vi.fn();+ const component = new SettingsSelectorComponent(+ { ...config, idleEvictionMinutes: value },+ { ...callbacks, onIdleEvictionMinutesChange },+ );+ const list = component.getSettingsList();+ for (const character of "idle") list.handleInput(character);++ // Cycle through every option and back onto the custom fractional value.+ for (let index = 0; index < 7; index++) list.handleInput("\r");++ expect(onIdleEvictionMinutesChange).toHaveBeenLastCalledWith(value);+ expect(stripAnsi(component.render(120).join("\n"))).toContain(String(value));+ });});diff --git a/packages/coding-agent/test/subagent-summary-line.test.ts b/packages/coding-agent/test/subagent-summary-line.test.tsindex 504879a3f4..19964c7ca3 100644--- a/packages/coding-agent/test/subagent-summary-line.test.ts+++ b/packages/coding-agent/test/subagent-summary-line.test.ts@@ -113,6 +113,38 @@ describe("SubagentSummaryLine", () => {expect(stripAnsi(line.render(100).join("\n"))).toContain("0 running · 1 idle · 0 inactive");});+ it("refreshes counts when startup seeding follows an early live child update", () => {+ const line = new SubagentSummaryLine();+ const mode = Object.create(InteractiveMode.prototype) as InteractiveMode & Record<string, unknown>;+ Object.assign(mode, {+ subagentSnapshots: new Map<string, AgentConnectionRlmChildAgentSnapshot>(),+ rlmNodeId: undefined,+ heartbeatCatalog: [],+ subagentSummaryLine: line,+ updateScopedHeartbeats: vi.fn(),+ updateWorkingPulse: vi.fn(),+ syncWorkingLoader: vi.fn(),+ updateWorkingLoaderMessage: vi.fn(),+ ui: { requestRender: vi.fn() },+ });+ const worker = child("worker", "done", { parentId: "me" });+ const update = Reflect.get(InteractiveMode.prototype, "updateSubagentSummary") as (+ this: typeof mode,+ value: AgentConnectionRlmChildAgentSnapshot,+ ) => void;+ const seed = Reflect.get(InteractiveMode.prototype, "seedSubagentSummary") as (+ this: typeof mode,+ children: readonly AgentConnectionRlmChildAgentSnapshot[],+ ) => void;++ update.call(mode, worker);+ expect(line.render(100)).toEqual([]);+ Reflect.set(mode, "rlmNodeId", "me");+ seed.call(mode, [worker]);++ expect(stripAnsi(line.render(100).join("\n"))).toContain("1 subagent:");+ });+it("clears a resident session id when a terminal update reports an evicted child", () => {const line = new SubagentSummaryLine();const mode = Object.create(InteractiveMode.prototype) as InteractiveMode & Record<string, unknown>;diff --git a/packages/coding-agent/test/suite/agent-session-action-races.test.ts b/packages/coding-agent/test/suite/agent-session-action-races.test.tsindex 86c7558709..8239c1f2f2 100644--- a/packages/coding-agent/test/suite/agent-session-action-races.test.ts+++ b/packages/coding-agent/test/suite/agent-session-action-races.test.ts@@ -9,6 +9,7 @@ type ActionKind = "turn" | "command";interface CommitFenceInternals {_actionStore: ActionStore<SessionAction>;+ _pendingSessionActionFenceWaiters: number;_refineInFlight?: Promise<void>;_scheduleSessionInputPump(): void;_acquireDirectTurnAdmissionFence(signal?: AbortSignal): Promise<{ release(): void }>;@@ -125,6 +126,23 @@ describe("AgentSession action commit-fence races", () => {expect(settlementCount).toBe(1);});+ it("reports a queued commit-fence waiter while its predecessor releases", async () => {+ const harness = await createHarness();+ harnesses.push(harness);+ const internals = harness.session as unknown as CommitFenceInternals;+ const heldFence = await internals._acquireSessionActionCommitFence();+ const nextFencePromise = internals._acquireSessionActionCommitFence();+ await vi.waitFor(() => expect(internals._pendingSessionActionFenceWaiters).toBe(1));++ heldFence.release();+ expect(harness.session.hasPendingAdmissionWaiters).toBe(true);++ const nextFence = await nextFencePromise;+ expect(harness.session.hasPendingAdmissionWaiters).toBe(true);+ nextFence.release();+ expect(harness.session.hasPendingAdmissionWaiters).toBe(false);+ });+it("aborts a prompt waiting for the commit fence without leaking the fence", async () => {const harness = await createHarness();harnesses.push(harness);diff --git a/packages/coding-agent/test/suite/agent-session-runtime.test.ts b/packages/coding-agent/test/suite/agent-session-runtime.test.tsindex f96b2d78d9..a829174478 100644--- a/packages/coding-agent/test/suite/agent-session-runtime.test.ts+++ b/packages/coding-agent/test/suite/agent-session-runtime.test.ts@@ -52,6 +52,8 @@ describe("AgentSessionRuntime characterization", () => {bootstrapThinkingLevel?: boolean;inMemory?: boolean;sessionConfig?: AgentSessionRuntimeConfig;+ sessionManager?: SessionManager;+ sessionOptions?: Parameters<CreateAgentSessionRuntimeFactory>[0]["sessionOptions"];onCreateRuntime?: (options: Parameters<CreateAgentSessionRuntimeFactory>[0]) => void;},) {@@ -115,6 +117,7 @@ describe("AgentSessionRuntime characterization", () => {sessionStartEvent,model: serviceOptions.model,thinkingLevel: serviceOptions.thinkingLevel,+ ...runtimeOptions.sessionOptions,})),services,diagnostics: services.diagnostics,@@ -123,10 +126,13 @@ describe("AgentSessionRuntime characterization", () => {const runtime = await createAgentSessionRuntime(createRuntime, {cwd: tempDir,agentDir: tempDir,- sessionManager: options?.inMemory- ? SessionManager.inMemory(tempDir)- : SessionManager.create(tempDir, join(tempDir, "sessions")),+ sessionManager:+ options?.sessionManager ??+ (options?.inMemory+ ? SessionManager.inMemory(tempDir)+ : SessionManager.create(tempDir, join(tempDir, "sessions"))),sessionConfig: options?.sessionConfig,+ sessionOptions: options?.sessionOptions,});await runtime.session.bindExtensions({});@@ -183,6 +189,55 @@ describe("AgentSessionRuntime characterization", () => {expect(calls[1]?.sessionConfig).toBe(sessionConfig);});+ it("copies depth across new-session parent reference edges", async () => {+ const { runtime } = await createRuntimeForTest(() => {});+ const parentSession = runtime.session.sessionFile;+ if (!parentSession) throw new Error("Missing parent session file");++ await runtime.newSession({ parentSession });++ expect(runtime.session.sessionManager.getHeader()).toMatchObject({ parentSession, rlmDepth: 0 });+ });++ it("uses effective runtime depth for a parented new session from a legacy header", async () => {+ const tempDir = join(tmpdir(), `pi-runtime-legacy-new-${Date.now()}-${Math.random().toString(36).slice(2)}`);+ const sessionManager = SessionManager.create(tempDir, join(tempDir, "sessions"));+ sessionManager.newSession({ rlmDepth: undefined });+ const parentSession = sessionManager.getSessionFile();+ if (!parentSession) throw new Error("Missing parent session file");+ const { runtime } = await createRuntimeForTest(() => {}, {+ cwd: tempDir,+ sessionManager,+ sessionOptions: { rlmDepth: 2 },+ });++ await runtime.newSession({ parentSession });++ expect(runtime.session.sessionManager.getHeader()).toMatchObject({ parentSession, rlmDepth: 2 });+ });++ it.each([false, true])(+ "uses the effective runtime depth when forking a legacy session before its first entry (inMemory=%s)",+ async (inMemory) => {+ const tempDir = join(tmpdir(), `pi-runtime-legacy-fork-${Date.now()}-${Math.random().toString(36).slice(2)}`);+ const sessionManager = inMemory+ ? SessionManager.inMemory(tempDir)+ : SessionManager.create(tempDir, join(tempDir, "sessions"));+ sessionManager.newSession({ rlmDepth: undefined });+ const firstEntry = sessionManager.appendMessage({ role: "user", content: "fork here", timestamp: 1 });+ const { runtime } = await createRuntimeForTest(() => {}, {+ cwd: tempDir,+ sessionManager,+ sessionOptions: { rlmDepth: 2 },+ });++ await runtime.fork(firstEntry);++ expect(runtime.session.sessionManager.getHeader()?.rlmDepth).toBe(2);+ expect(runtime.session.rlmDepth).toBe(2);+ },+ );+it("disposes a runtime only once across repeated teardown calls", async () => {const shutdownEvents: SessionShutdownEvent[] = [];const beforeInvalidate = vi.fn();@@ -694,6 +749,7 @@ describe("AgentSessionRuntime characterization", () => {});await otherRuntime.session.prompt("other");const otherSessionFile = otherRuntime.session.sessionFile!;+ await otherRuntime.dispose();await runtime.switchSession(otherSessionFile);@@ -769,6 +825,7 @@ describe("AgentSessionRuntime characterization", () => {otherRuntime.session.setThinkingLevel("off");await otherRuntime.session.prompt("hello");const targetSessionFile = otherRuntime.session.sessionFile!;+ await otherRuntime.dispose();await runtime.switchSession(targetSessionFile);diff --git a/packages/coding-agent/test/suite/regressions/4257-update-restart-resume.test.ts b/packages/coding-agent/test/suite/regressions/4257-update-restart-resume.test.tsindex 436bcece7e..ddfd58b603 100644--- a/packages/coding-agent/test/suite/regressions/4257-update-restart-resume.test.ts+++ b/packages/coding-agent/test/suite/regressions/4257-update-restart-resume.test.ts@@ -73,6 +73,7 @@ function createState(activeSessionId,runtime,clients: new Set(),+ pendingAttaches: 0,extensionUiRequests: new Map(),eventGeneration: `generation-${activeSessionId}`,lastEventSequence: 0,diff --git a/packages/coding-agent/test/suite/regressions/4657-update-heartbeat-recovery.test.ts b/packages/coding-agent/test/suite/regressions/4657-update-heartbeat-recovery.test.tsindex e2885c56ab..ad019be2ca 100644--- a/packages/coding-agent/test/suite/regressions/4657-update-heartbeat-recovery.test.ts+++ b/packages/coding-agent/test/suite/regressions/4657-update-heartbeat-recovery.test.ts@@ -65,6 +65,7 @@ describe("ENG-4657 update heartbeat recovery", () => {dispose: async () => {},} as unknown as AgentSessionRuntime,clients: new Set(),+ pendingAttaches: 0,extensionUiRequests: new Map(),eventGeneration: "restored-generation",lastEventSequence: 0,diff --git a/prime-agent-runtime/src/rlm/__init__.py b/prime-agent-runtime/src/rlm/__init__.pyindex 937ca6a185..8a39df68ac 100644--- a/prime-agent-runtime/src/rlm/__init__.py+++ b/prime-agent-runtime/src/rlm/__init__.py@@ -3,7 +3,6 @@from __future__ import annotationsimport asyncio-import osimport sysimport typesfrom dataclasses import dataclass, field@@ -63,26 +62,6 @@ class RLMSubagent:status: str-def _env_int(name: str, default: int) -> int:- raw = os.environ.get(name)- if raw is None or raw == "":- return default- try:- return int(raw)- except ValueError as exc:- raise RuntimeError(f"{name} must be an integer, got {raw!r}") from exc---def _ensure_recursion_allowed() -> None:- depth = _env_int("RLM_DEPTH", 0)- max_depth = _env_int("RLM_MAX_DEPTH", 1)- if depth >= max_depth:- raise RuntimeError(- f"RLM recursion depth limit reached "- f"(RLM_DEPTH={depth}, RLM_MAX_DEPTH={max_depth})"- )--def _install_control_comm_handlers() -> None:"""Let comm replies arrive on the control channel during an execute_request."""if get_ipython is None:@@ -184,7 +163,6 @@ async def run(prompt: str, **kwargs: Any) -> RLMResult:"""if not isinstance(prompt, str):raise TypeError(f"prompt must be str, got {type(prompt).__name__}")- _ensure_recursion_allowed()payload = await host_request("rlm.run", {"prompt": prompt, "kwargs": kwargs})return _result_from_payload(payload)