A self-improving RLM agent for coding workflows and long-running autonomous tasks.
Rust
[RSI, bug] Free child names at delete receipt and return cancelled collect envelopes (#2388)
Seth Karten1c1ad1e4855f
diff --git a/packages/coding-agent/.changes/free-deleted-name-collect-cancelled.md b/packages/coding-agent/.changes/free-deleted-name-collect-cancelled.mdnew file mode 100644index 0000000000..cbccafb19b--- /dev/null+++ b/packages/coding-agent/.changes/free-deleted-name-collect-cancelled.md@@ -0,0 +1,7 @@+- Fixed `rlm.delete_subagent` holding a deleted child's session name until its background unwind finished: the name now frees at the delete receipt, so a replacement child can be spawned immediately under the same name.+- Fixed `rlm.collect` throwing `No direct RLM child matches` when a requested target was deleted moments earlier: collect now returns a settled `cancelled` envelope for just-deleted targets immediately, without spending the timeout budget.+- Fixed a daemon-mode respawn under a just-deleted child's name failing the name check: the delete receipt now frees the child's session name in the daemon catalog too — and the daemon host's runtime-boundary re-assert honors the same freed ids the spawn admission forwarded, instead of only the parent session's local run map.+- Fixed `rlm.collect` resolving a reused child name to the previous generation's `cancelled` envelope while the new child's delete was still in preflight: the selector now reports no match until the delete settles.+- Fixed `rlm.collect` throwing `No direct RLM child matches` when a live child's background unwind had already finished before the parent collected it: the accepted delete now leaves a tombstone, so its settled `cancelled` envelope stays addressable by child id and session name until the parent session is disposed.+- Fixed `rlm.collect` for retained children deleted without an active run: a retained completed child or a daemon-hydrated child that never had a run now leaves the same delete tombstone as a live child, so collect answers with the settled `cancelled` envelope its delete receipt promised, and a still-pending run-less delete blocks a reused selector instead of resolving to the previous generation's envelope.+- Fixed `rlm.collect` resolving a reused child name to the previous generation's `cancelled` envelope while a live daemon-hydrated run-less replacement owns the name, including one whose delete failed and left it resident for a retry: the selector now reports no match until that replacement is deleted, matching the existing delete-preflight convention.diff --git a/packages/coding-agent/src/core/agent-messages.ts b/packages/coding-agent/src/core/agent-messages.tsindex 62bf08e600..0a91dcad12 100644--- a/packages/coding-agent/src/core/agent-messages.ts+++ b/packages/coding-agent/src/core/agent-messages.ts@@ -111,6 +111,13 @@ export interface AgentSessionNameScope {export interface AgentSessionNameAvailabilityInput extends AgentSessionNameScope {name: string;ignoreSessionId?: string;+ /**+ * Session ids of children whose delete receipt already returned. The daemon+ * catalog keeps listing such a child until its detached unwind removes the+ * runtime, so the caller passes every freed id it still holds and a same-name+ * respawn is admitted at the receipt instead of at the unwind.+ */+ ignoreSessionIds?: string[];}export interface AgentSessionMessagePayload {@@ -205,9 +212,11 @@ export function assertAgentSessionNameAvailable(catalog: readonly AgentFamilyCatalogEntry[],input: AgentSessionNameAvailabilityInput,): void {+ const freedSessionIds = input.ignoreSessionIds?.length ? new Set(input.ignoreSessionIds) : undefined;const conflict = catalog.some((entry) =>entry.id !== input.ignoreSessionId &&+ !freedSessionIds?.has(entry.id) &&entry.name === input.name &&entry.depth === input.depth &&sameAgentSessionNameParent(entry, input, catalog),diff --git a/packages/coding-agent/src/core/agent-session.ts b/packages/coding-agent/src/core/agent-session.tsindex 187bb087bc..46b38081ea 100644--- a/packages/coding-agent/src/core/agent-session.ts+++ b/packages/coding-agent/src/core/agent-session.ts@@ -1097,11 +1097,27 @@ interface RetainedRlmChild {run?: RlmChildRun;}+/**+ * A delete receipt frees the name once the child runtime is bound and only the+ * detached deletion unwind remains. A deleted startup without a bound session+ * still reserves its name until that startup settles, because the queued+ * runtime work can still surface under it.+ */+function freedRlmChildSessionId(run: RlmChildRun): string | undefined {+ return run.detachedDeletion !== undefined ? run.session?.sessionId : undefined;+}+interface RlmSubagentModelSelection {model: Model<Api>;}const KERNEL_STATE_LISTING_TIMEOUT_MS = 5000;++/**+ * No-model sentinel for a tombstoned run-less deletion: mirrors the agent core's+ * unknown/unknown placeholder. Only the snapshot's `provider/id` string reads it.+ */+const UNKNOWN_RLM_CHILD_MODEL = { provider: "unknown", id: "unknown" } as Model<Api>;const RLM_MAX_DEPTH_STATE_CUSTOM_TYPE = "rlm_max_depth_state";/** Minimum spacing between accepted progress notes from one child session. */const RLM_PROGRESS_NOTE_MIN_INTERVAL_MS = 10_000;@@ -1704,6 +1720,11 @@ export class AgentSession {// the daemon does the same by leaving the child session resident in its registry.private _rlmChildSessions = new Map<string, RetainedRlmChild>();private _deletedRlmChildIds = new Set<string>();+ // An accepted delete outlives the run it cancelled: once the run is removed+ // from both lookup maps, this tombstone keeps the child's identity so collect+ // can still answer with its settled cancelled envelope.+ // Entries live until the parent session is disposed, like _deletedRlmChildIds.+ private _deletedRlmChildRuns = new Map<string, RlmChildRun>();// Failed explicit deletes stay hidden from listings but retain their original// selector so a later delete can retry cleanup without orphaning the runtime.private _rlmChildCleanupFailures = new Map<string, RlmSubagentRegistryEntry>();@@ -5082,6 +5103,7 @@ export class AgentSession {this._rlmChildSessions.clear();this._rlmChildCleanupFailures.clear();this._deletedRlmChildIds.clear();+ this._deletedRlmChildRuns.clear();try {await this._ipythonKernelProvisioner?.dispose({ snapshot: kernelSnapshot });} catch {@@ -5151,6 +5173,7 @@ export class AgentSession {this._rlmChildSessions.clear();this._rlmChildCleanupFailures.clear();this._deletedRlmChildIds.clear();+ this._deletedRlmChildRuns.clear();this._pendingNextTurnMessages = [];const deliveryError = new Error("Session disposed before prompt delivery.");const completionError = new Error("Session disposed before prompt completion.");@@ -11210,6 +11233,7 @@ export class AgentSession {thinkingLevel?: ThinkingLevel;spawnedByRequestId?: string;}): CreateRlmSubagentRuntimeOptions {+ const freedSessionIds = this._freedRlmChildSessionIds();return {parentSession: this,id: options.id,@@ -11231,6 +11255,10 @@ export class AgentSession {rlmMaxDepth: this._rlmMaxDepth,rlmParentNodeId: options.id,spawnedByRequestId: options.spawnedByRequestId,+ // The daemon host re-asserts the name at the runtime boundary+ // against a catalog that still lists the unwinding child, so the+ // receipt's freed ids must survive that second check.+ ...(freedSessionIds.length > 0 ? { ignoreSessionIds: freedSessionIds } : {}),};}@@ -11518,7 +11546,9 @@ export class AgentSession {* never rejects on timeout — a timeout returns the current snapshots so* the caller can end its turn, poll, or retry. `targets` are child ids or* session names; an empty list means every direct child that is not being- * deleted.+ * deleted. A target whose delete receipt already returned resolves+ * immediately to a settled cancelled envelope instead of an+ * unknown-selector error.*/async collectRlmChildren(targets: string[], timeoutMs: number): Promise<RlmCollectResult> {const candidates = new Map<string, RlmChildRun>();@@ -11534,6 +11564,31 @@ export class AgentSession {}}const runs = new Map<string, RlmChildRun>();+ // Deleted targets resolve immediately to cancelled envelopes: their delete+ // receipt already accepted the cancellation, so waiting for the detached+ // unwind (or reporting an unsettled snapshot) would only mislead callers.+ // Only detachedDeletion marks an accepted delete. A run merely reserved in+ // _deletingRlmChildren is still inside delete preflight and can surface a+ // passive-selector conflict that fails the delete, so it stays hidden from+ // collect like every other selector view until the delete settles. That+ // preflight reservation also blocks the deleted fallback: a reused name+ // makes the previous generation's accepted delete match the same selector,+ // and answering with its cancelled envelope would report a run that is not+ // the target while the new delete can still fail and leave it live. The+ // selector throws no-match instead, exactly like a fresh-name collect+ // racing its own delete preflight. An accepted delete keeps its+ // _deletingRlmChildren reservation until the unwind settles, so only a+ // reservation without detachedDeletion blocks the fallback. Once the+ // unwind does settle, the run leaves both lookup maps and only its+ // _deletedRlmChildRuns tombstone still carries the receipt-bound identity,+ // so a later collect keeps answering with the same cancelled envelope. A+ // mid-preflight run blocks tombstone matches too: that delete can still+ // fail and leave a live replacement under the reused selector. The same+ // protection must not end at preflight: a run-less retained child is+ // invisible to candidates, yet while it is live it owns its reused name, so+ // the deleted generation of that name never answers for it. A live+ // replacement of a reused name always beats the deleted-generation fallback.+ const deletedRuns = new Map<string, RlmChildRun>();if (targets.length === 0) {for (const [childId, run] of candidates) {if (!run.detachedDeletion && !this._deletingRlmChildren.has(run.id)) {@@ -11549,7 +11604,64 @@ export class AgentSession {this._rlmChildRunMatchesTarget(run, target),);if (matches.length === 0) {- throw new Error(`No direct RLM child matches "${target}" in the current parent session`);+ // Mid-preflight runs stay hidden and must not fall through to the+ // deleted generation of the same selector. An accepted delete keeps+ // its reservation until the unwind settles, so only a reservation+ // without detachedDeletion is still inside preflight.+ const candidatePreflight = [...candidates.values()].some(+ (run) =>+ run.detachedDeletion === undefined &&+ this._deletingRlmChildren.has(run.id) &&+ this._rlmChildRunMatchesTarget(run, target),+ );+ // A run-less retained child is invisible to candidates, so its own+ // reservation is the only preflight signal. A reservation is kept past+ // the receipt only for an accepted delete with an active run, and the+ // accepted run-less delete is excluded by its tombstone, so a visible+ // run-less reservation is still inside preflight.+ const runlessPreflight = [...this._deletingRlmChildren].some(+ ([childId, reservation]) =>+ !candidates.has(childId) &&+ !this._deletedRlmChildRuns.has(childId) &&+ this._rlmSubagentMatchesTarget(reservation.subagent, target),+ );+ const preflight = candidatePreflight || runlessPreflight;+ // A live run-less retained child (a daemon-hydrated child, for example)+ // never enters candidates, so without this scan the deleted generation+ // of a reused name would answer for it. While the replacement stays+ // resident it owns the selector: a reservation or receipt may hide it+ // from listings, and a failed delete cleanup hides it from listings+ // only — it never returned a receipt, so both deleted-generation+ // fallbacks stay silent and the selector throws no-match, exactly+ // like the mid-preflight convention.+ const liveRunlessMatch = [...this._rlmChildSessions].some(+ ([childId, retained]) =>+ !retained.run &&+ !candidates.has(childId) &&+ !this._deletingRlmChildren.has(childId) &&+ !this._deletedRlmChildIds.has(childId) &&+ (childId === target ||+ retained.session.sessionId === target ||+ retained.session.sessionName === target),+ );+ // A run still mid-unwind stays in candidates; one whose unwind already+ // finished is reachable only through its tombstone.+ const unwoundMatches = [...candidates.values()].filter(+ (run) => run.detachedDeletion && this._rlmChildRunMatchesTarget(run, target),+ );+ const unwoundIds = new Set(unwoundMatches.map((run) => run.id));+ const tombstoneMatches = [...this._deletedRlmChildRuns.values()].filter(+ (run) => !unwoundIds.has(run.id) && this._rlmDeletedRunMatchesTarget(run, target),+ );+ const deletedMatches = preflight || liveRunlessMatch ? [] : [...unwoundMatches, ...tombstoneMatches];+ if (deletedMatches.length === 0) {+ throw new Error(`No direct RLM child matches "${target}" in the current parent session`);+ }+ if (deletedMatches.length > 1) {+ throw new Error(`RLM child selector "${target}" is ambiguous in the current parent session`);+ }+ deletedRuns.set(deletedMatches[0].id, deletedMatches[0]);+ continue;}if (matches.length > 1) {throw new Error(`RLM child selector "${target}" is ambiguous in the current parent session`);@@ -11582,7 +11694,12 @@ export class AgentSession {}),);}- return { results: [...runs.values()].map((run) => this._rlmCollectEntryForRun(run)) };+ return {+ results: [+ ...[...runs.values()].map((run) => this._rlmCollectEntryForRun(run)),+ ...[...deletedRuns.values()].map((run) => this._rlmDeletedCollectEntryForRun(run)),+ ],+ };}private _rlmChildRunMatchesTarget(run: RlmChildRun, target: string): boolean {@@ -11595,6 +11712,17 @@ export class AgentSession {);}+ /**+ * Tombstoned runs have no session object left, so registry identity stands in+ * for the session selectors a mid-unwind run still answered to.+ */+ private _rlmDeletedRunMatchesTarget(run: RlmChildRun, target: string): boolean {+ return (+ this._rlmChildRunMatchesTarget(run, target) ||+ (run.detachedDeletion !== undefined && this._rlmSubagentMatchesTarget(run.detachedDeletion, target))+ );+ }+private _rlmCollectEntryForRun(run: RlmChildRun): RlmCollectResultEntry {const snapshot = this._rlmChildSnapshotForRun(run);return {@@ -11611,6 +11739,22 @@ export class AgentSession {};}+ /**+ * Typed envelope for a target whose delete receipt already returned. The+ * detached unwind may still hold the run unsettled; the parent-facing+ * projection is terminal regardless, so the entry reports cancellation as a+ * settled answer instead of a snapshot that invites re-polling.+ */+ private _rlmDeletedCollectEntryForRun(run: RlmChildRun): RlmCollectResultEntry {+ const entry = this._rlmCollectEntryForRun(run);+ return {+ ...entry,+ status: "cancelled",+ settled: true,+ error: entry.error ?? "Deleted by parent orchestrator",+ };+ }+private _rlmSubagentMatchesTarget(entry: RlmSubagentRegistryEntry, target: string): boolean {return (entry.rlm_child_id === target ||@@ -11664,6 +11808,17 @@ export class AgentSession {}async deleteRlmSubagent(target: string): Promise<RlmDeleteSubagentResult> {+ // Freeing a name at the delete receipt reaches two transient selector+ // states, both inherent to that design and recoverable, so neither is+ // guarded away: (a) while an old generation with an accepted delete+ // still unwinds, its reservation matches the reused name and unions+ // with the live replacement below, so a name delete of the replacement+ // throws ambiguous until the unwind settles; the replacement stays+ // deletable by child id. (b) if that old generation's detached cleanup+ // fails after a replacement took the name, the cleanup-failure entry+ // keeps the name blocked for new spawns even after the replacement is+ // deleted, until the failed delete is retried by child id and the+ // cleanup succeeds.const inFlight = [...this._deletingRlmChildren.values()].filter(({ subagent }) =>this._rlmSubagentMatchesTarget(subagent, target),);@@ -11848,6 +12003,13 @@ export class AgentSession {}private _removeRlmSubagentTracking(childId: string, run?: RlmChildRun): void {+ // Every removal of an accepted-delete run funnels through here, so the+ // tombstone covers the settled unwind, an already-settled errored delete, and+ // the no-run retained delete. Other removals keep no tombstone: only a delete+ // receipt promises a collectable cancelled envelope.+ if (run?.detachedDeletion) {+ this._deletedRlmChildRuns.set(childId, run);+ }run?.unsubscribe?.();this._rlmChildUnsubscribes.get(childId)?.();this._rlmChildUnsubscribes.delete(childId);@@ -11861,6 +12023,14 @@ export class AgentSession {run.abort = noopRlmChildAbort;run.unsubscribe = undefined;run.session = undefined;+ if (run.detachedDeletion) {+ // Tombstones only need the label (derived from prompt) and the last+ // progress note to build the cancelled collect envelope. Strip the+ // full values so a long-lived parent with many deletions does not+ // accumulate unbounded memory.+ run.prompt = rlmChildLabel(run.prompt);+ run.progressNotes = run.progressNotes.slice(-1);+ }}}@@ -11880,6 +12050,43 @@ export class AgentSession {});}+ /**+ * Accepted-delete marker for a child removed without an active run: a retained+ * completed child, or a daemon-hydrated passive child that never had one. The+ * retained run is reused when the parent still holds it, because it is already+ * out of both lookup maps by removal time and the tombstone is its only+ * remaining reader; otherwise the tombstone carries the registry snapshot.+ */+ private _runForRetainedRlmChildDeletion(+ childId: string,+ subagent: RlmSubagentRegistryEntry,+ retained: RetainedRlmChild | undefined,+ ): RlmChildRun {+ if (retained?.run) {+ retained.run.detachedDeletion = subagent;+ return retained.run;+ }+ return {+ id: childId,+ prompt: subagent.label ?? "",+ sessionName: subagent.session_name,+ sessionDir: subagent.session_dir,+ model: retained?.session.model ?? this.model ?? UNKNOWN_RLM_CHILD_MODEL,+ status: "cancelled",+ durationMs: subagent.duration_ms,+ answerPreview: subagent.answer_preview,+ toolUseCount: subagent.tool_use_count ?? 0,+ progressNotes: subagent.progress_note ? [subagent.progress_note] : [],+ error: "Deleted by parent orchestrator",+ abort: noopRlmChildAbort,+ publication: createAgentMessageDeferred(),+ settlement: createAgentMessageDeferred(),+ settled: true,+ deletionReservation: createAgentMessageDeferred(),+ detachedDeletion: subagent,+ };+ }+private async _deleteResolvedRlmSubagent(subagent: RlmSubagentRegistryEntry): Promise<RlmDeleteSubagentResult> {const childId = subagent.rlm_child_id;const run = this._activeRlmChildRuns.get(childId);@@ -11922,20 +12129,22 @@ export class AgentSession {}this._emitRlmSubagentRemoval(subagent);- const retained = this._rlmChildSessions.get(childId)?.session;+ const retained = this._rlmChildSessions.get(childId);try {- await this._deleteRlmSubagentSession(childId, retained);+ await this._deleteRlmSubagentSession(childId, retained?.session);} catch (error) {if (this._disposed || this._disposing) {this._removeRlmSubagentTracking(childId);- void retained?.disposeAsync().catch(() => undefined);+ void retained?.session.disposeAsync().catch(() => undefined);} else {this._rlmChildCleanupFailures.set(childId, subagent);}throw error;}this._deletedRlmChildIds.add(childId);- this._removeRlmSubagentTracking(childId);+ // The receipt promises a collectable cancelled envelope, so a child deleted+ // without an active run still needs its accepted-delete tombstone.+ this._removeRlmSubagentTracking(childId, this._runForRetainedRlmChildDeletion(childId, subagent, retained));return { subagent };}@@ -12250,16 +12459,43 @@ export class AgentSession {return cancelled;}+ /**+ * Session ids of every child whose delete receipt already returned. Both the+ * name-availability check and the spawn options the daemon host re-asserts+ * with must ignore the same set, or a same-name respawn that admission+ * allowed fails later inside the detached child startup.+ */+ private _freedRlmChildSessionIds(): string[] {+ const freed = new Set<string>();+ for (const run of this._activeRlmChildRuns.values()) {+ const sessionId = freedRlmChildSessionId(run);+ if (sessionId) freed.add(sessionId);+ }+ for (const { session, run } of this._rlmChildSessions.values()) {+ if (run && freedRlmChildSessionId(run)) freed.add(session.sessionId);+ }+ return [...freed];+ }+private async _assertRlmSubagentSessionNameAvailable(name: string, ignorePendingReservation = false): Promise<void> {const depth = this._rlmDepth + 1;if (!ignorePendingReservation && this._pendingRlmSubagentSessionNames.has(name)) {throw new Error(formatAgentSessionNameUnavailable(name, depth));}+ // A daemon catalog still lists the closing child under its old name while+ // the detached unwind runs, which is after the delete receipt returned.+ // Forward every freed session id so both controller paths below admit the+ // immediate same-name respawn the receipt already promised.+ const ignoreSessionIds = new Set(this._freedRlmChildSessionIds());const localConflict =[...this._activeRlmChildRuns.values()].some(- (run) => run.session?.sessionName === name || (!run.session && run.sessionName === name),+ (run) =>+ freedRlmChildSessionId(run) === undefined &&+ (run.session?.sessionName === name || (!run.session && run.sessionName === name)),+ ) ||+ [...this._rlmChildSessions.values()].some(+ ({ session, run }) => !run?.detachedDeletion && session.sessionName === name,) ||- [...this._rlmChildSessions.values()].some(({ session }) => session.sessionName === name) ||[...this._rlmChildCleanupFailures.values()].some((entry) => entry.session_name === name);if (localConflict) {throw new Error(formatAgentSessionNameUnavailable(name, depth));@@ -12271,6 +12507,7 @@ export class AgentSession {depth,parentSessionId: this.sessionId,parentSessionPath: this.sessionFile,+ ...(ignoreSessionIds.size > 0 ? { ignoreSessionIds: [...ignoreSessionIds] } : {}),};if (controller.assertSessionNameAvailable) {await controller.assertSessionNameAvailable(input);diff --git a/packages/coding-agent/src/core/rlm-runtime.ts b/packages/coding-agent/src/core/rlm-runtime.tsindex 4455b00a5a..4a976f1c50 100644--- a/packages/coding-agent/src/core/rlm-runtime.ts+++ b/packages/coding-agent/src/core/rlm-runtime.ts@@ -474,6 +474,13 @@ export interface CreateRlmSubagentRuntimeOptions {spawnCode?: string;/** Publish the session to the parent before a host makes the runtime addressable. */onSessionPublished?: (session: AgentSession) => void;+ /**+ * Session ids of children whose delete receipt already returned. A host that+ * re-asserts the name against a catalog still listing the unwinding child+ * ignores these, so an admission the delete receipt freed holds at the host+ * boundary too.+ */+ ignoreSessionIds?: string[];}export interface CreateRlmRootSessionOptions {diff --git a/packages/coding-agent/src/modes/daemon/daemon-mode.ts b/packages/coding-agent/src/modes/daemon/daemon-mode.tsindex b00c6e2090..3be6137192 100644--- a/packages/coding-agent/src/modes/daemon/daemon-mode.ts+++ b/packages/coding-agent/src/modes/daemon/daemon-mode.ts@@ -36,6 +36,7 @@ import {AgentSessionMessageRateLimiter,type AgentSessionMessageReceipt,type AgentSessionMessageSender,+ type AgentSessionNameAvailabilityInput,agentFamilyRelationship,assertAgentFamilyReach,assertAgentSessionNameAvailable,@@ -2910,12 +2911,17 @@ export class AgentDaemon {// The sibling name is held under a daemon-wide reservation for the// whole admission and re-asserted at this boundary, so a same-name// sibling that lands mid-admission fails closed before the durable- // ledger edge is appended.+ // ledger edge is appended. A spawn admission may pass the parent's+ // name check on a delete receipt that freed the name while the old+ // child is still unwinding here: ignore the same freed ids, or the+ // admitted respawn errors "name unavailable" at startup instead of+ // failing synchronously where the caller could react.const nameReservation = {name: options.sessionName,depth: options.rlmDepth,parentSessionId: options.parentSession.sessionId,...(options.parentSession.sessionFile ? { parentSessionPath: options.parentSession.sessionFile } : {}),+ ...(options.ignoreSessionIds ? { ignoreSessionIds: options.ignoreSessionIds } : {}),};const reservationKey = sessionNameReservationKey(nameReservation);if (this.pendingSessionNames.has(reservationKey)) {@@ -6052,13 +6058,7 @@ export class AgentDaemon {}private async assertFamilySessionNameAvailable(- input: {- name: string;- depth: number;- parentSessionId?: string;- parentSessionPath?: string;- ignoreSessionId?: string;- },+ input: AgentSessionNameAvailabilityInput,currentState?: ActiveSessionState,ignorePendingReservation = false,): Promise<void> {diff --git a/packages/coding-agent/test/agent-session-recursion.test.ts b/packages/coding-agent/test/agent-session-recursion.test.tsindex f68d338884..257536c02e 100644--- a/packages/coding-agent/test/agent-session-recursion.test.ts+++ b/packages/coding-agent/test/agent-session-recursion.test.ts@@ -568,6 +568,27 @@ describe("AgentSession rlm recursion", () => {await expect(root.runRlmChild("respawn while retained", { name: "slow-worker" })).rejects.toThrow(unavailable);});+ it("admits a same-name respawn while the deleted child still unwinds", async () => {+ const unblockUnwind = deferred<void>();+ const root = createSession();+ const first = await root.runRlmChild("first shard", { name: "reused-worker" });+ const firstRun = (root as unknown as InspectableRlmSession)._activeRlmChildRuns.get(first.rlm_child_id)!;+ await firstRun.publication!.promise;+ const firstChild = firstRun.session!;+ // The blocked dispose holds the unwind open past the receipt.+ vi.spyOn(firstChild, "disposeAsync").mockImplementation(() => unblockUnwind.promise);+ await root.deleteRlmSubagent(first.rlm_child_id);+ const forwarded = (+ root as unknown as {+ _createRlmSubagentRuntimeOptions(options: Record<string, unknown>): { ignoreSessionIds?: string[] };+ }+ )._createRlmSubagentRuntimeOptions({ id: "probe", prompt: "p", sessionName: "reused-worker", model });+ // The freed id rides along for the daemon host's own name re-assert.+ expect(forwarded.ignoreSessionIds).toContain(firstChild.sessionId);+ await root.runRlmChild("second shard", { name: "reused-worker" });+ unblockUnwind.resolve();+ });+it("makes an externally restored retained child listable and deletable", async () => {const childId = "restored-child";const childDir = join(tempDir, childId);diff --git a/packages/coding-agent/test/daemon-mode.test.ts b/packages/coding-agent/test/daemon-mode.test.tsindex 9f3d6239bd..ac6922cdda 100644--- a/packages/coding-agent/test/daemon-mode.test.ts+++ b/packages/coding-agent/test/daemon-mode.test.ts@@ -120,7 +120,7 @@ describe("daemon mode helpers", () => {hasRunningRlmChildren: () => false,getSessionActionSnapshot: () => ({ queuedCount: 0, steering: [], followUps: [] }),});- const spawn = (id: string) =>+ const spawn = (id: string, ignoreSessionIds?: string[]) =>internals.createRlmSubagentRuntime(parentState, {parentSession: parentState.runtime.session,id,@@ -138,6 +138,7 @@ describe("daemon mode helpers", () => {rlmDepth: 1,rlmMaxDepth: 4,rlmParentNodeId: id,+ ...(ignoreSessionIds ? { ignoreSessionIds } : {}),});const admission = spawn("child-1");await expect(spawn("child-2")).rejects.toThrow('Agent name "real-worker" is unavailable');@@ -182,11 +183,14 @@ describe("daemon mode helpers", () => {prompt: "complete and persist",});await host.deleteRlmSubagentRuntime?.("child-1", childRuntime.session);- await spawn("child-3");+ const child3Runtime = await spawn("child-3");const edgesAfter = await internals.rlmSpawnLedger().liveEdges();const namedEdges = edgesAfter.filter((edge) => edge.name === "real-worker");expect(namedEdges).toHaveLength(1);expect(namedEdges[0]?.childId).toBe("child-3");+ // A respawn admitted past a freed name must hold at this re-asserting boundary.+ await expect(spawn("child-4")).rejects.toThrow('Agent name "real-worker" is unavailable');+ await expect(spawn("child-4", [child3Runtime.session.sessionId])).resolves.toBeTruthy();} finally {rmSync(tempDir, { recursive: true, force: true });}@@ -3358,6 +3362,7 @@ function makeRuntimeSession(},sessionFile: sessionManager.getSessionFile(),sessionId: sessionManager.getSessionId(),+ rlmDepth: sessionManager.getHeader()?.rlmDepth ?? 0,get sessionName() {return sessionManager.getSessionName();},diff --git a/packages/coding-agent/test/rlm-collect.test.ts b/packages/coding-agent/test/rlm-collect.test.tsindex ac77fbb946..1156c5f6a8 100644--- a/packages/coding-agent/test/rlm-collect.test.ts+++ b/packages/coding-agent/test/rlm-collect.test.ts@@ -14,7 +14,7 @@ import { AgentSession } from "../src/core/agent-session.js";import { AuthStorage } from "../src/core/auth-storage.js";import { convertToLlm } from "../src/core/messages.js";import { ModelRegistry } from "../src/core/model-registry.js";-import { createRlmCollectHostHandler } from "../src/core/rlm-runtime.js";+import { createRlmCollectHostHandler, 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 { getCodingAgentFixtureModel } from "./fixture-models.js";@@ -76,7 +76,9 @@ describe("rlm.collect typed fan-in", () => {rmSync(tempDir, { recursive: true, force: true });});- function makeSession(): AgentSession {+ function makeSession(+ options: { subagentRuntimeHost?: SubagentRuntimeHost; rlmSessionDir?: string } = {},+ ): AgentSession {const authStorage = AuthStorage.create(join(tempDir, "auth.json"));authStorage.setRuntimeApiKey("anthropic", "test-key");const agent = new Agent({@@ -92,9 +94,20 @@ describe("rlm.collect typed fan-in", () => {cwd: tempDir,modelRegistry: ModelRegistry.create(authStorage, join(tempDir, "models.json")),resourceLoader: createTestResourceLoader(),+ subagentRuntimeHost: options.subagentRuntimeHost,+ rlmSessionDir: options.rlmSessionDir,});}+ /** Register a daemon-hydrated run-less child under `name`, as the daemon does. */+ function registerRunlessChild(root: AgentSession, childId: string, name: string): AgentSession {+ const retainedChild = makeSession({ rlmSessionDir: join(tempDir, childId) });+ session = root;+ retainedChild.setSessionName(name);+ expect(root.registerRlmChildSession(childId, retainedChild)).toBe(true);+ return retainedChild;+ }+it("returns a typed envelope once the child settles", async () => {session = makeSession();const handle = await session.runRlmChild("compute the answer", { name: "worker-a" });@@ -110,15 +123,20 @@ describe("rlm.collect typed fan-in", () => {expect(entry.error).toBeUndefined();});- it("collects every direct child when no targets are given", async () => {+ it("collects every direct child when no targets are given and only the selected child when targeted", async () => {session = makeSession();const first = await session.runRlmChild("first task", { name: "worker-a" });const second = await session.runRlmChild("second task", { name: "worker-b" });- const results = await session.collectRlmChildren([], 10_000);- const ids = results.results.map((entry) => entry.rlm_child_id).sort();+ const all = await session.collectRlmChildren([], 10_000);+ const ids = all.results.map((entry) => entry.rlm_child_id).sort();expect(ids).toEqual([first.rlm_child_id, second.rlm_child_id].sort());- expect(results.results.every((entry) => entry.settled && entry.status === "done")).toBe(true);+ expect(all.results.every((entry) => entry.settled && entry.status === "done")).toBe(true);++ const targeted = await session.collectRlmChildren([first.rlm_child_id], 0);+ expect(targeted.results.map((entry) => entry.rlm_child_id)).toEqual([first.rlm_child_id]);+ const byName = await session.collectRlmChildren(["worker-b"], 0);+ expect(byName.results.map((entry) => entry.rlm_child_id)).toEqual([second.rlm_child_id]);});it("re-collects a settled child after terminal cleanup", async () => {@@ -143,18 +161,6 @@ describe("rlm.collect typed fan-in", () => {expect(all.results.map((entry) => entry.rlm_child_id)).toContain(handle.rlm_child_id);});- it("returns only the selected child from a targeted collect", async () => {- session = makeSession();- const first = await session.runRlmChild("first task", { name: "worker-a" });- const second = await session.runRlmChild("second task", { name: "worker-b" });- await session.collectRlmChildren([], 10_000);-- const targeted = await session.collectRlmChildren([first.rlm_child_id], 0);- expect(targeted.results.map((entry) => entry.rlm_child_id)).toEqual([first.rlm_child_id]);- const byName = await session.collectRlmChildren(["worker-b"], 0);- expect(byName.results.map((entry) => entry.rlm_child_id)).toEqual([second.rlm_child_id]);- });-it("returns current snapshots on timeout without rejecting", async () => {session = makeSession();const handle = await session.runRlmChild("slow task", { name: "worker-a" });@@ -187,4 +193,80 @@ describe("rlm.collect typed fan-in", () => {const defaults = await handler({});expect(defaults).toEqual({ results: [] });});++ it("keeps deleted children's cancelled envelopes after their delete receipts", async () => {+ session = makeSession();+ // A settled child takes the no-active-run delete path; a daemon-hydrated+ // run-less child exercises the registry-identity tombstone.+ const done = await session.runRlmChild("done shard", { name: "done-worker" });+ await session.collectRlmChildren([done.rlm_child_id], 10_000);+ registerRunlessChild(session, "runless-child", "runless-worker");+ await expect(session.deleteRlmSubagent(done.rlm_child_id)).resolves.toMatchObject({+ subagent: { rlm_child_id: done.rlm_child_id },+ });+ await expect(session.deleteRlmSubagent("runless-worker")).resolves.toMatchObject({+ subagent: { rlm_child_id: "runless-child" },+ });+ // The receipt promises a cancelled envelope even though both runs are gone.+ const byName = await session.collectRlmChildren(["done-worker"], 0);+ expect(byName.results[0]).toMatchObject({+ rlm_child_id: done.rlm_child_id,+ status: "cancelled",+ settled: true,+ error: "Deleted by parent orchestrator",+ });+ const byId = await session.collectRlmChildren(["runless-child"], 0);+ expect(byId.results[0]).toMatchObject({+ rlm_child_id: "runless-child",+ session_name: "runless-worker",+ status: "cancelled",+ settled: true,+ });+ });++ // The replacement's delete failed, so it never got a receipt and still owns the name.+ it("keeps a failed-cleanup run-less replacement off the deleted generation's cancelled envelope", async () => {+ const hostedChildren: AgentSession[] = [];+ const makeHostedChild = (): AgentSession => {+ const root = session;+ const child = makeSession();+ session = root;+ hostedChildren.push(child);+ return child;+ };+ const root = makeSession({+ subagentRuntimeHost: {+ // Only the run-less replacement's delete fails.+ createRlmSubagentRuntime: async () => ({ session: makeHostedChild() }),+ deleteRlmSubagentRuntime: async (childId: string) => {+ if (childId === "runless-failed") throw new Error("injected cleanup failure");+ },+ },+ });+ session = root;+ const first = await root.runRlmChild("first shard", { name: "reused-worker" });+ // Settle and delete the first generation: its tombstone is the stale envelope.+ await root.collectRlmChildren([first.rlm_child_id], 10_000);+ await root.deleteRlmSubagent(first.rlm_child_id);++ registerRunlessChild(root, "runless-failed", "reused-worker");+ await expect(root.deleteRlmSubagent("reused-worker")).rejects.toThrow("injected cleanup failure");++ // The replacement still owns the name: a same-name spawn stays blocked.+ await expect(root.runRlmChild("blocked shard", { name: "reused-worker" })).rejects.toThrow(+ 'Agent name "reused-worker" is unavailable',+ );+ // Resident and name-bound, it must keep the deleted generation's tombstone silent.+ await expect(root.collectRlmChildren(["reused-worker"], 0)).rejects.toThrow(+ 'No direct RLM child matches "reused-worker" in the current parent session',+ );+ const byOldId = await root.collectRlmChildren([first.rlm_child_id], 0);+ expect(byOldId.results).toHaveLength(1);+ expect(byOldId.results[0]).toMatchObject({+ rlm_child_id: first.rlm_child_id,+ status: "cancelled",+ settled: true,+ });+ for (const hosted of hostedChildren) hosted.dispose();+ });});