A self-improving RLM agent for coding workflows and long-running autonomous tasks.
Rust
[RSI] Typed fan-in for subagent results (rlm.collect) (#2223)
Seth Karten9150cc28a3e1
diff --git a/packages/coding-agent/.changes/eng-6088-rlm-collect-typed-fanin.md b/packages/coding-agent/.changes/eng-6088-rlm-collect-typed-fanin.mdnew file mode 100644index 0000000000..d7922fd736--- /dev/null+++ b/packages/coding-agent/.changes/eng-6088-rlm-collect-typed-fanin.md@@ -0,0 +1 @@+- Added `rlm.collect`, a typed non-steering fan-in for subagent results: it awaits direct children's runs with a bounded timeout and returns per-child result envelopes (status, settled, answer preview, error, duration, tool count) without growing the parent's message queue.diff --git a/packages/coding-agent/src/core/agent-session.ts b/packages/coding-agent/src/core/agent-session.tsindex f66e86db7a..cc7a7ea3f8 100644--- a/packages/coding-agent/src/core/agent-session.ts+++ b/packages/coding-agent/src/core/agent-session.ts@@ -239,6 +239,7 @@ import {createAsyncBashCompletionHostHandler,createAsyncBashConsumedHostHandler,createDefaultRlmSubagentSessionName,+ createRlmCollectHostHandler,createRlmCreateSessionHostHandler,createRlmDeleteSubagentHostHandler,createRlmFindModelsHostHandler,@@ -248,6 +249,8 @@ import {normalizeRequestedRlmSubagentModel,normalizeRequestedRlmSubagentSessionName,normalizeRequestedRlmSubagentThinkingLevel,+ type RlmCollectResult,+ type RlmCollectResultEntry,type RlmCreateSessionResult,type RlmDeleteSubagentResult,type RlmFindModelsResult,@@ -9762,6 +9765,9 @@ export class AgentSession {}),"rlm.find_models": createRlmFindModelsHostHandler((query, limit) => this.findRlmModels(query, limit)),"rlm.list_subagents": createRlmListSubagentsHostHandler(() => this.listRlmSubagents()),+ "rlm.collect": createRlmCollectHostHandler((targets, timeoutMs) =>+ this.collectRlmChildren(targets, timeoutMs),+ ),"rlm.delete_subagent": createRlmDeleteSubagentHostHandler((target) => this.deleteRlmSubagent(target)),"model.info": async () => ({id: this.model?.id ?? null,@@ -10255,6 +10261,105 @@ export class AgentSession {return { subagents };}+ /**+ * Typed fan-in for direct RLM children: wait (bounded) for the selected+ * runs to settle and return result envelopes. Never steers the parent and+ * 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.+ */+ async collectRlmChildren(targets: string[], timeoutMs: number): Promise<RlmCollectResult> {+ const candidates = new Map<string, RlmChildRun>();+ for (const run of this._activeRlmChildRuns.values()) {+ candidates.set(run.id, run);+ }+ // Terminal cleanup moves settled runs out of _activeRlmChildRuns while their+ // envelope stays retained in _rlmChildSessions until deleted; collect must see+ // both or a completed child can no longer be re-collected.+ for (const [childId, retained] of this._rlmChildSessions) {+ if (retained.run && !candidates.has(childId)) {+ candidates.set(childId, retained.run);+ }+ }+ const runs = new Map<string, RlmChildRun>();+ if (targets.length === 0) {+ for (const [childId, run] of candidates) {+ if (!run.detachedDeletion && !this._deletingRlmChildren.has(run.id)) {+ runs.set(childId, run);+ }+ }+ } else {+ for (const target of targets) {+ const matches = [...candidates.values()].filter(+ (run) =>+ !run.detachedDeletion &&+ !this._deletingRlmChildren.has(run.id) &&+ this._rlmChildRunMatchesTarget(run, target),+ );+ if (matches.length === 0) {+ throw new Error(`No direct RLM child matches "${target}" in the current parent session`);+ }+ if (matches.length > 1) {+ throw new Error(`RLM child selector "${target}" is ambiguous in the current parent session`);+ }+ runs.set(matches[0].id, matches[0]);+ }+ }+ if (timeoutMs > 0) {+ const deadline = Date.now() + timeoutMs;+ await Promise.all(+ [...runs.values()].map((run) => {+ if (run.settled) return undefined;+ const remainingMs = deadline - Date.now();+ if (remainingMs <= 0) return undefined;+ let timer: NodeJS.Timeout | undefined;+ const timeout = new Promise<void>((resolve) => {+ timer = setTimeout(resolve, remainingMs);+ timer.unref?.();+ });+ return Promise.race([+ // A settled failure is terminal state, not a collect error.+ run.settlement.promise.then(+ () => undefined,+ () => undefined,+ ),+ timeout,+ ]).finally(() => {+ clearTimeout(timer);+ });+ }),+ );+ }+ return { results: [...runs.values()].map((run) => this._rlmCollectEntryForRun(run)) };+ }++ private _rlmChildRunMatchesTarget(run: RlmChildRun, target: string): boolean {+ const session = run.session ?? this._rlmChildSessions.get(run.id)?.session;+ return (+ run.id === target ||+ run.sessionName === target ||+ session?.sessionId === target ||+ session?.sessionName === target+ );+ }++ private _rlmCollectEntryForRun(run: RlmChildRun): RlmCollectResultEntry {+ const snapshot = this._rlmChildSnapshotForRun(run);+ return {+ rlm_child_id: snapshot.id,+ session_name: snapshot.sessionName,+ session_dir: snapshot.sessionDir,+ status: snapshot.status,+ settled: run.settled,+ answer_preview: snapshot.answerPreview,+ error: snapshot.error,+ duration_ms: snapshot.durationMs,+ tool_use_count: snapshot.toolUseCount,+ replied_since_task: snapshot.repliedSinceTask,+ };+ }+private _rlmSubagentMatchesTarget(entry: RlmSubagentRegistryEntry, target: string): boolean {return (entry.rlm_child_id === target ||diff --git a/packages/coding-agent/src/core/prompts/rlm.ts b/packages/coding-agent/src/core/prompts/rlm.tsindex c8b932cc8b..d9bae2d69e 100644--- a/packages/coding-agent/src/core/prompts/rlm.ts+++ b/packages/coding-agent/src/core/prompts/rlm.ts@@ -222,7 +222,8 @@ export function buildSubagentGuidance(lines.push("Use `agent_observe` for bounded transcript inspection.");}lines.push(- "Have children write files and read those files for fan-in.",+ "Fan-in results with `await rlm.collect(targets, timeout_ms=0)`: it returns typed snapshots of direct children (status, answer preview, error) without steering anyone; an explicit timeout blocks only that call until the children settle or the deadline passes.",+ "Large child outputs belong in files that you read selectively; `collect` snapshots are previews, not full results.","Delegate parallel context-heavy research or independent implementation; do a single known lookup, edit, or command inline.",);if (options.includeRefineExamples ?? true) {diff --git a/packages/coding-agent/src/core/rlm-runtime.ts b/packages/coding-agent/src/core/rlm-runtime.tsindex fdef11f9c2..ea8bdf5946 100644--- a/packages/coding-agent/src/core/rlm-runtime.ts+++ b/packages/coding-agent/src/core/rlm-runtime.ts@@ -1,6 +1,6 @@import type { ThinkingLevel } from "@earendil-works/pi-agent-core";import type { Api, Model, ServiceTier } from "@earendil-works/pi-ai";-import type { AgentSession } from "./agent-session.js";+import type { AgentSession, RlmChildAgentStatus } from "./agent-session.js";import type { ToolDefinition } from "./extensions/index.js";import type { HostRequestHandler } from "./kernel/index.js";import { THINKING_LEVELS } from "./thinking-levels.js";@@ -63,6 +63,27 @@ export interface RlmFindModelsResult {models: RlmModelMatch[];}+export interface RlmCollectResultEntry {+ rlm_child_id: string;+ session_name: string | undefined;+ session_dir: string;+ /** Raw run status: queued | running | done | error | cancelled. */+ status: RlmChildAgentStatus;+ /** True once the run reached a terminal state (settlement resolved or rejected). */+ settled: boolean;+ answer_preview: string | undefined;+ error: string | undefined;+ duration_ms: number | undefined;+ tool_use_count: number | undefined;+ replied_since_task: boolean | undefined;+}++export interface RlmCollectResult {+ results: RlmCollectResultEntry[];+}++export type RlmCollectHandler = (targets: string[], timeoutMs: number) => Promise<RlmCollectResult>;+export type RlmRunHandler = (request: RlmRunRequest) => Promise<Record<string, unknown>>;type RlmCreateSessionHandler = (request: RlmCreateSessionRequest) => Promise<RlmCreateSessionResult>;@@ -287,6 +308,42 @@ export function createRlmDeleteSubagentHostHandler(handler: RlmDeleteSubagentHan};}+/**+ * Typed fan-in for subagent results: `rlm.collect` waits (bounded) for the+ * selected direct children's runs to settle and returns result envelopes.+ * Never steers the parent: a timeout returns the current snapshots instead of+ * rejecting, so the caller can poll, end the turn, or retry.+ */+export function createRlmCollectHostHandler(handler: RlmCollectHandler): HostRequestHandler {+ return async (payload) => {+ const rawTargets = payload.targets;+ if (rawTargets !== undefined && rawTargets !== null && !Array.isArray(rawTargets)) {+ throw new Error("rlm.collect targets must be an array of child ids or names");+ }+ const targets = (rawTargets ?? []).map((target) => {+ if (typeof target !== "string" || !target.trim()) {+ throw new Error("rlm.collect targets must be non-empty strings");+ }+ return target.trim();+ });+ const rawTimeout = payload.timeout_ms;+ if (rawTimeout === undefined || rawTimeout === null) {+ const { results } = await handler(targets, 0);+ return { results };+ }+ if (+ typeof rawTimeout !== "number" ||+ !Number.isSafeInteger(rawTimeout) ||+ rawTimeout < 0 ||+ rawTimeout > 2_147_483_647+ ) {+ throw new Error("rlm.collect timeout_ms must be a non-negative integer up to 2147483647");+ }+ const { results } = await handler(targets, rawTimeout);+ return { results };+ };+}+export interface RlmSubagentRuntime {session: AgentSession;}diff --git a/packages/coding-agent/test/rlm-collect.test.ts b/packages/coding-agent/test/rlm-collect.test.tsnew file mode 100644index 0000000000..1564e56bb9--- /dev/null+++ b/packages/coding-agent/test/rlm-collect.test.ts@@ -0,0 +1,190 @@+import { mkdirSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { Agent } from "@earendil-works/pi-agent-core";+import {+ type AssistantMessage,+ type Context,+ createAssistantMessageEventStream,+ getModel,+ type TextContent,+ type Usage,+} from "@earendil-works/pi-ai";+import { afterEach, beforeEach, describe, expect, it } from "vitest";+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 { SessionManager } from "../src/core/session-manager.js";+import { SettingsManager } from "../src/core/settings-manager.js";+import { createTestResourceLoader } from "./utilities.js";++const model = getModel("anthropic", "claude-sonnet-4-5")!;++function userText(context: Context): string {+ const last = context.messages.at(-1);+ if (!last || last.role !== "user") return "";+ if (typeof last.content === "string") return last.content;+ return last.content+ .filter((block): block is TextContent => block.type === "text")+ .map((block) => block.text)+ .join(" ");+}++function usage(input = 7, output = 3): Usage {+ return {+ input,+ output,+ cacheRead: 0,+ cacheWrite: 0,+ totalTokens: input + output,+ cost: { input, output, cacheRead: 0, cacheWrite: 0, total: input + output },+ };+}++function streamAnswer(text: string): ReturnType<typeof createAssistantMessageEventStream> {+ const stream = createAssistantMessageEventStream();+ queueMicrotask(() => {+ const message: AssistantMessage = {+ role: "assistant",+ content: [{ type: "text", text }],+ api: model.api,+ provider: model.provider,+ model: model.id,+ usage: usage(),+ stopReason: "stop",+ timestamp: Date.now(),+ };+ stream.push({ type: "done", reason: "stop", message });+ });+ return stream;+}++describe("rlm.collect typed fan-in", () => {+ let tempDir: string;+ let session: AgentSession | undefined;++ beforeEach(() => {+ tempDir = join(tmpdir(), `pi-rlm-collect-${Date.now()}-${Math.random().toString(36).slice(2)}`);+ mkdirSync(tempDir, { recursive: true });+ });++ afterEach(() => {+ session?.dispose();+ session = undefined;+ rmSync(tempDir, { recursive: true, force: true });+ });++ function makeSession(): AgentSession {+ const authStorage = AuthStorage.create(join(tempDir, "auth.json"));+ authStorage.setRuntimeApiKey("anthropic", "test-key");+ const agent = new Agent({+ convertToLlm,+ getApiKey: () => "test-key",+ initialState: { model, systemPrompt: "", tools: [], thinkingLevel: "off" },+ streamFn: (_model, context) => streamAnswer(`child answer: ${userText(context)}`),+ });+ return new AgentSession({+ agent,+ sessionManager: SessionManager.create(tempDir, join(tempDir, "sessions")),+ settingsManager: SettingsManager.create(tempDir, tempDir),+ cwd: tempDir,+ modelRegistry: ModelRegistry.create(authStorage, join(tempDir, "models.json")),+ resourceLoader: createTestResourceLoader(),+ });+ }++ it("returns a typed envelope once the child settles", async () => {+ session = makeSession();+ const handle = await session.runRlmChild("compute the answer", { name: "worker-a" });++ const results = await session.collectRlmChildren([handle.rlm_child_id], 10_000);+ expect(results.results).toHaveLength(1);+ const entry = results.results[0];+ expect(entry.rlm_child_id).toBe(handle.rlm_child_id);+ expect(entry.session_name).toBe("worker-a");+ expect(entry.status).toBe("done");+ expect(entry.settled).toBe(true);+ expect(entry.answer_preview).toContain("child answer");+ expect(entry.error).toBeUndefined();+ });++ it("collects every direct child when no targets are given", 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();+ expect(ids).toEqual([first.rlm_child_id, second.rlm_child_id].sort());+ expect(results.results.every((entry) => entry.settled && entry.status === "done")).toBe(true);+ });++ it("re-collects a settled child after terminal cleanup", async () => {+ session = makeSession();+ const handle = await session.runRlmChild("compute the answer", { name: "worker-a" });+ // Wait for settlement: the terminal path removes the settled run from+ // _activeRlmChildRuns while its envelope stays retained until deleted.+ const settled = await session.collectRlmChildren([handle.rlm_child_id], 10_000);+ expect(settled.results[0]?.settled).toBe(true);++ const byId = await session.collectRlmChildren([handle.rlm_child_id], 0);+ expect(byId.results).toHaveLength(1);+ expect(byId.results[0]?.rlm_child_id).toBe(handle.rlm_child_id);+ expect(byId.results[0]?.status).toBe("done");+ expect(byId.results[0]?.settled).toBe(true);+ expect(byId.results[0]?.answer_preview).toContain("child answer");++ const byName = await session.collectRlmChildren(["worker-a"], 0);+ expect(byName.results[0]?.rlm_child_id).toBe(handle.rlm_child_id);++ const all = await session.collectRlmChildren([], 0);+ 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" });+ // The child runs to completion quickly in this stub; a zero timeout is+ // the guaranteed non-blocking read used for polling.+ const snapshot = await session.collectRlmChildren([handle.rlm_child_id], 0);+ expect(snapshot.results).toHaveLength(1);+ expect(snapshot.results[0].rlm_child_id).toBe(handle.rlm_child_id);+ expect(["queued", "running", "done"]).toContain(snapshot.results[0].status);+ });++ it("throws for unknown selectors and keeps ambiguity detection", async () => {+ session = makeSession();+ await expect(session.collectRlmChildren(["no-such-child"], 0)).rejects.toThrow(+ 'No direct RLM child matches "no-such-child"',+ );+ });++ it("validates host payload shape", async () => {+ const handler = createRlmCollectHostHandler(async () => ({ results: [] }));+ await expect(handler({ targets: "worker-a" })).rejects.toThrow("targets must be an array");+ await expect(handler({ targets: [""] })).rejects.toThrow("non-empty strings");+ await expect(handler({ timeout_ms: -1 })).rejects.toThrow("non-negative integer");+ await expect(handler({ timeout_ms: "soon" })).rejects.toThrow("non-negative integer");+ // Node clamps setTimeout delays above 2^31-1 to 1ms, so an oversized+ // timeout must be rejected instead of returning an immediate snapshot.+ await expect(handler({ timeout_ms: 2_147_483_648 })).rejects.toThrow("2147483647");+ const ok = await handler({ targets: ["worker-a"], timeout_ms: 5 });+ expect(ok).toEqual({ results: [] });+ const defaults = await handler({});+ expect(defaults).toEqual({ results: [] });+ });+});diff --git a/prime-agent-runtime/src/rlm/__init__.py b/prime-agent-runtime/src/rlm/__init__.pyindex 8d416e0c14..3fde0442a2 100644--- a/prime-agent-runtime/src/rlm/__init__.py+++ b/prime-agent-runtime/src/rlm/__init__.py@@ -50,6 +50,22 @@ class RLMSubagent:status: str+@dataclass(frozen=True)+class RLMChildResult:+ """Terminal or in-progress state of one direct child, from `collect()`."""++ rlm_child_id: str+ session_name: str | None+ session_dir: Path | None+ status: str+ settled: bool+ answer_preview: str | None+ error: str | None+ duration_ms: int | None+ tool_use_count: int | None+ replied_since_task: bool | None++def _spawn_handle_from_payload(payload: Any) -> RLMSpawnHandle:if not isinstance(payload, dict):raise RuntimeError("rlm.spawn returned an invalid spawn handle")@@ -239,6 +255,103 @@ async def list_subagents() -> list[RLMSubagent]:return [_subagent_from_payload(entry) for entry in entries]+def _collect_target_selector(target: Any) -> str:+ """Normalize a collect target: spawn handle, subagent row, or a name/id string."""+ if isinstance(target, RLMSpawnHandle):+ return target.rlm_child_id+ if isinstance(target, RLMSubagent):+ return target.rlm_child_id+ if isinstance(target, str) and target.strip():+ return target.strip()+ raise TypeError(+ f"collect target must be RLMSpawnHandle, RLMSubagent, or non-empty str, got {type(target).__name__}"+ )+++def _child_result_from_payload(payload: Any) -> RLMChildResult:+ if not isinstance(payload, dict):+ raise RuntimeError("rlm.collect returned an invalid result entry")+ child_id = payload.get("rlm_child_id")+ if not isinstance(child_id, str) or not child_id:+ raise RuntimeError("rlm.collect entry is missing rlm_child_id")+ status = payload.get("status")+ if status not in {"queued", "running", "done", "error", "cancelled"}:+ raise RuntimeError("rlm.collect entry has invalid status")+ settled = payload.get("settled")+ if not isinstance(settled, bool):+ raise RuntimeError("rlm.collect entry has invalid settled flag")++ def _optional_str(field: str) -> str | None:+ value = payload.get(field)+ if value is None:+ return None+ if not isinstance(value, str):+ raise RuntimeError(f"rlm.collect entry has invalid {field}")+ return value++ def _optional_int(field: str) -> int | None:+ value = payload.get(field)+ if value is None:+ return None+ if not isinstance(value, int) or isinstance(value, bool):+ raise RuntimeError(f"rlm.collect entry has invalid {field}")+ return value++ session_dir = _optional_str("session_dir")+ replied = payload.get("replied_since_task")+ if replied is not None and not isinstance(replied, bool):+ raise RuntimeError("rlm.collect entry has invalid replied_since_task")+ return RLMChildResult(+ rlm_child_id=child_id,+ session_name=_optional_str("session_name"),+ session_dir=Path(session_dir) if session_dir else None,+ status=status,+ settled=settled,+ answer_preview=_optional_str("answer_preview"),+ error=_optional_str("error"),+ duration_ms=_optional_int("duration_ms"),+ tool_use_count=_optional_int("tool_use_count"),+ replied_since_task=replied,+ )+++async def collect(+ targets: Any = None,+ *,+ timeout_ms: int = 0,+) -> list[RLMChildResult]:+ """Collect typed results from direct RLM children.++ ``targets`` selects children: spawn handles, subagent rows, name strings,+ or a list mixing all three. ``None`` (or an empty list) selects every+ direct child that is not being deleted.++ ``timeout_ms`` bounds the wait for the selected children to settle:+ 0 returns a non-blocking snapshot immediately; a positive value blocks+ only this kernel call until the runs settle or the timeout elapses —+ a timeout returns current snapshots, never an error, and the parent+ session is never steered. Completed children keep their result until+ deleted, so a later ``collect`` re-reads them without waiting.+ """+ if not isinstance(timeout_ms, int) or isinstance(timeout_ms, bool) or timeout_ms < 0:+ raise TypeError("timeout_ms must be a non-negative int")+ if targets is None:+ selectors: list[str] = []+ elif isinstance(targets, (RLMSpawnHandle, RLMSubagent, str)):+ selectors = [_collect_target_selector(targets)]+ elif isinstance(targets, (list, tuple)):+ selectors = [_collect_target_selector(target) for target in targets]+ else:+ raise TypeError(+ f"targets must be None, a target, or a list of targets, got {type(targets).__name__}"+ )+ payload = await host_request("rlm.collect", {"targets": selectors, "timeout_ms": timeout_ms})+ results = payload.get("results")+ if not isinstance(results, list):+ raise RuntimeError("rlm.collect returned an invalid results list")+ return [_child_result_from_payload(entry) for entry in results]++async def delete_subagent(target: str | RLMSubagent) -> RLMSubagent:"""Delete one running or retained direct child from the current parent session."""if isinstance(target, RLMSubagent):@@ -335,6 +448,9 @@ class _RLMNamespace:async def delete_subagent(self, target: str | RLMSubagent) -> RLMSubagent:return await delete_subagent(target)+ async def collect(self, targets: Any = None, *, timeout_ms: int = 0) -> list[RLMChildResult]:+ return await collect(targets, timeout_ms=timeout_ms)+def __call__(self, *args: Any, **kwargs: Any) -> Any:raise TypeError(_NOT_CALLABLE_MESSAGE)diff --git a/prime-agent-runtime/test/test_subagent_registry.py b/prime-agent-runtime/test/test_subagent_registry.pyindex ad38ca77b4..b3acddaaf8 100644--- a/prime-agent-runtime/test/test_subagent_registry.py+++ b/prime-agent-runtime/test/test_subagent_registry.py@@ -239,3 +239,91 @@ class RlmSubagentRegistryTest(unittest.TestCase):if __name__ == "__main__":unittest.main()++class RlmCollectTest(unittest.TestCase):+ def test_collect_all_children_returns_typed_results(self) -> None:+ host_request = AsyncMock(+ return_value={+ "results": [+ {+ "rlm_child_id": "sub-a1b2c3d4",+ "session_name": "worker-a",+ "session_dir": "/tmp/parent/sub-a1b2c3d4",+ "status": "done",+ "settled": True,+ "answer_preview": "task finished cleanly",+ "error": None,+ "duration_ms": 4321,+ "tool_use_count": 3,+ "replied_since_task": False,+ },+ {+ "rlm_child_id": "sub-b2c3d4e5",+ "session_name": "worker-b",+ "session_dir": "/tmp/parent/sub-b2c3d4e5",+ "status": "running",+ "settled": False,+ "answer_preview": None,+ "error": None,+ "duration_ms": None,+ "tool_use_count": None,+ "replied_since_task": None,+ },+ ]+ }+ )++ with patch.object(rlm_module, "host_request", host_request):+ results = asyncio.run(rlm_module.rlm.collect())++ self.assertEqual(len(results), 2)+ done = results[0]+ self.assertEqual(done.rlm_child_id, "sub-a1b2c3d4")+ self.assertEqual(done.session_name, "worker-a")+ self.assertEqual(done.session_dir, Path("/tmp/parent/sub-a1b2c3d4"))+ self.assertEqual(done.status, "done")+ self.assertTrue(done.settled)+ self.assertEqual(done.answer_preview, "task finished cleanly")+ self.assertIsNone(done.error)+ self.assertEqual(done.duration_ms, 4321)+ self.assertEqual(done.tool_use_count, 3)+ self.assertFalse(done.replied_since_task)+ running = results[1]+ self.assertEqual(running.status, "running")+ self.assertFalse(running.settled)+ self.assertIsNone(running.answer_preview)+ host_request.assert_awaited_once_with("rlm.collect", {"targets": [], "timeout_ms": 0})++ def test_collect_normalizes_spawn_handles_and_names(self) -> None:+ host_request = AsyncMock(return_value={"results": []})+ handle = rlm_module.RLMSpawnHandle(+ rlm_child_id="sub-h1",+ name="worker-h",+ session_dir=Path("/tmp/parent/sub-h1"),+ model="anthropic/claude-sonnet-4-5",+ )++ with patch.object(rlm_module, "host_request", host_request):+ results = asyncio.run(rlm_module.rlm.collect([handle, "worker-b"], timeout_ms=250))++ self.assertEqual(results, [])+ host_request.assert_awaited_once_with(+ "rlm.collect", {"targets": ["sub-h1", "worker-b"], "timeout_ms": 250}+ )++ def test_collect_validates_arguments(self) -> None:+ with self.assertRaisesRegex(TypeError, "timeout_ms"):+ asyncio.run(rlm_module.rlm.collect(timeout_ms=-1))+ with self.assertRaisesRegex(TypeError, "timeout_ms"):+ asyncio.run(rlm_module.rlm.collect(timeout_ms="soon"))+ with self.assertRaisesRegex(TypeError, "targets must be"):+ asyncio.run(rlm_module.rlm.collect(42))+ with self.assertRaisesRegex(TypeError, "collect target"):+ asyncio.run(rlm_module.rlm.collect(["ok", ""]))++ def test_collect_rejects_invalid_payloads(self) -> None:+ host_request = AsyncMock(return_value={"results": [{"rlm_child_id": "sub-x", "status": "nonsense"}]})++ with patch.object(rlm_module, "host_request", host_request):+ with self.assertRaisesRegex(RuntimeError, "invalid status"):+ asyncio.run(rlm_module.rlm.collect())