A self-improving RLM agent for coding workflows and long-running autonomous tasks.
Rust
refactor(daemon): consolidate rlm subagent metadata onto the spawn ledger (#1390)
Sebastian Müller06e4a19dc902
diff --git a/packages/coding-agent/src/modes/daemon/daemon-catalog-process.ts b/packages/coding-agent/src/modes/daemon/daemon-catalog-process.tsindex c841b5b79c..aabe580008 100644--- a/packages/coding-agent/src/modes/daemon/daemon-catalog-process.ts+++ b/packages/coding-agent/src/modes/daemon/daemon-catalog-process.ts@@ -1,7 +1,5 @@import { type ChildProcess, spawn } from "node:child_process";import { randomUUID } from "node:crypto";-import { readFile } from "node:fs/promises";-import { dirname, join, resolve } from "node:path";import { createCliSubprocessEnv, createCliSubprocessLaunchSpec } from "../../cli/subprocess-launch.js";import type { DeleteSessionFileResult } from "../../core/session-file-actions.js";import { deleteSessionFile } from "../../core/session-file-actions.js";@@ -17,7 +15,6 @@ interface SessionInfoWire extends Omit<SessionInfo, "created" | "modified"> {type CatalogRequest =| { type: "request"; id: string; command: "list"; cwd?: string; sessionDir?: string }| { type: "request"; id: string; command: "resolve"; selector: string; cwd: string; sessionDir?: string }- | { type: "request"; id: string; command: "siblings"; sessionPath: string }| { type: "request"; id: string; command: "rename"; sessionPath: string; name: string }| { type: "request"; id: string; command: "delete"; sessionPath: string }| { type: "request"; id: string; command: "archive"; sessionPath: string; sessionId: string }@@ -59,52 +56,6 @@ function deserializeSessionInfo(session: SessionInfoWire): SessionInfo {};}-interface SavedRlmSubagentRegistryEntry {- type?: unknown;- childId?: unknown;- sessionFile?: unknown;- status?: unknown;-}--export async function listSavedSessionSiblings(sessionPath: string): Promise<SessionInfo[]> {- const target = await readSessionInfo(sessionPath);- if (!target) throw new Error(`Session not found: ${sessionPath}`);- if (!target.parentSessionPath) return [target];- const parentPath = resolve(dirname(target.path), target.parentSessionPath);- const parent = await readSessionInfo(parentPath);- if (!parent) return [target];- const registryPath = join(dirname(dirname(parent.path)), "session-artifacts", parent.id, "rlm-subagents.jsonl");- let contents: string;- try {- contents = await readFile(registryPath, "utf8");- } catch (error) {- if ((error as NodeJS.ErrnoException).code === "ENOENT") return [target];- throw error;- }- const latest = new Map<string, SavedRlmSubagentRegistryEntry>();- for (const line of contents.split(/\r?\n/)) {- if (!line.trim()) continue;- try {- const entry = JSON.parse(line) as SavedRlmSubagentRegistryEntry;- if (entry.type === "rlm_subagent" && typeof entry.childId === "string") latest.set(entry.childId, entry);- } catch {- // Ignore malformed registry history just like the owning worker does.- }- }- const siblingPaths = new Set<string>([resolve(target.path)]);- for (const entry of latest.values()) {- if (entry.status !== "deleted" && typeof entry.sessionFile === "string")- siblingPaths.add(resolve(entry.sessionFile));- }- const siblings = await Promise.all([...siblingPaths].map((path) => readSessionInfo(path)));- return siblings.filter(- (info): info is SessionInfo =>- info !== null &&- info.parentSessionPath !== undefined &&- resolve(dirname(info.path), info.parentSessionPath) === parentPath,- );-}-/** @internal Exported to pin catalog selector semantics without spawning a catalog process. */export function resolveCatalogSessionMatch(sessions: readonly SessionInfo[],@@ -142,7 +93,6 @@ function isCatalogRequest(value: unknown): value is CatalogRequest {typeof candidate.id === "string" &&(candidate.command === "list" ||candidate.command === "resolve" ||- candidate.command === "siblings" ||candidate.command === "rename" ||candidate.command === "delete" ||candidate.command === "archive" ||@@ -223,14 +173,6 @@ async function handleCatalogRequest(request: CatalogRequest): Promise<void> {}throw new Error(`No session found matching '${request.selector}'`);}- case "siblings":- sendCatalogMessage({- type: "response",- id: request.id,- success: true,- data: { sessions: (await listSavedSessionSiblings(request.sessionPath)).map(serializeSessionInfo) },- });- return;case "rename":SessionManager.open(request.sessionPath).appendSessionInfo(request.name.trim());sendCatalogMessage({ type: "response", id: request.id, success: true });@@ -328,16 +270,6 @@ export class DaemonCatalogClient {return data.sessions.map(deserializeSessionInfo);}- async siblings(sessionPath: string): Promise<SessionInfo[]> {- const data = await this.request<{ sessions: SessionInfoWire[] }>({- type: "request",- id: randomUUID(),- command: "siblings",- sessionPath,- });- return data.sessions.map(deserializeSessionInfo);- }-async rename(sessionPath: string, name: string): Promise<void> {await this.request({ type: "request", id: randomUUID(), command: "rename", sessionPath, name });}diff --git a/packages/coding-agent/src/modes/daemon/daemon-mode.ts b/packages/coding-agent/src/modes/daemon/daemon-mode.tsindex 68667dce9d..841160ecb0 100644--- a/packages/coding-agent/src/modes/daemon/daemon-mode.ts+++ b/packages/coding-agent/src/modes/daemon/daemon-mode.ts@@ -8,19 +8,8 @@import { spawn } from "node:child_process";import { createHash, randomUUID } from "node:crypto";-import {- closeSync,- existsSync,- fsyncSync,- mkdirSync,- openSync,- readFileSync,- renameSync,- rmSync,- writeFileSync,- writeSync,-} from "node:fs";-import { readFile } from "node:fs/promises";+import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";+import { readFile, stat } from "node:fs/promises";import { createConnection, createServer, type Server, type Socket } from "node:net";import { dirname, isAbsolute, join, resolve } from "node:path";import { type Api, getLogger, type Model } from "@earendil-works/pi-ai";@@ -202,7 +191,17 @@ import {SESSION_LEASES_ENABLED_ENV,} from "./daemon-worker-protocol.js";import { MutationDrainLatch } from "./mutation-drain-latch.js";-import { createRlmLedgerRegistrySeedSource, type RlmLedgerDeleteReason, RlmSpawnLedger } from "./rlm-ledger.js";+import {+ createRlmLedgerRegistrySeedSource,+ type RlmLedgerDeleteReason,+ type RlmLedgerEdge,+ RlmSpawnLedger,+} from "./rlm-ledger.js";+import {+ readRlmSubagentDisplayEntry,+ rlmSubagentDisplayPath,+ writeRlmSubagentDisplayEntry,+} from "./rlm-subagent-display.js";import { serializeSavedSessionInfo } from "./saved-session-info.js";import {createSnapshotTranscriptChunks,@@ -377,8 +376,13 @@ interface BoundSupervisorGenerationClaim {const RLM_SUBAGENT_REGISTRY_FILE = "rlm-subagents.jsonl";-interface PersistedRlmSubagentRegistryEntry {- type: "rlm_subagent";+/**+ * One passive child as the daemon presents it: topology (sessionFile, parent,+ * depth, name) from the spawn ledger; hydration metadata (prompt, spawnCode,+ * model, rlmMaxDepth, status, createdAt) from the per-child display file, or+ * the legacy registry for pre-ledger children without one.+ */+interface PassiveRlmSubagentEntry {childId: string;sessionName: string;sessionDir: string;@@ -393,17 +397,44 @@ interface PersistedRlmSubagentRegistryEntry {model?: { provider: string; modelId: string };status: "running" | "completed" | "deleted";createdAt: number;+}++/**+ * Legacy per-parent `rlm-subagents.jsonl` entry shape, exactly as the daemon+ * wrote it before the spawn ledger became topology authority. Read-only:+ * registries are consumed only as the ledger seed source and as fallback+ * hydration metadata for pre-ledger children without a display file.+ */+interface LegacyRlmSubagentRegistryEntry extends PassiveRlmSubagentEntry {+ type: "rlm_subagent";updatedAt: string;}+/** Spread-ready optional metadata fields shared by display files and legacy registry entries. */+function rlmSubagentMetadataFields(source: {+ rlmMaxDepth?: number;+ rlmParentNodeId?: string;+ prompt?: string;+ spawnCode?: string;+ model?: { provider: string; modelId: string };+}): Pick<PassiveRlmSubagentEntry, "rlmMaxDepth" | "rlmParentNodeId" | "prompt" | "spawnCode" | "model"> {+ return {+ ...(source.rlmMaxDepth !== undefined ? { rlmMaxDepth: source.rlmMaxDepth } : {}),+ ...(source.rlmParentNodeId ? { rlmParentNodeId: source.rlmParentNodeId } : {}),+ ...(source.prompt ? { prompt: source.prompt } : {}),+ ...(source.spawnCode ? { spawnCode: source.spawnCode } : {}),+ ...(source.model ? { model: source.model } : {}),+ };+}+type PassiveRlmRoot =| { rootParentState: ActiveSessionState; rootInfo?: never }| { rootParentState?: never; rootInfo: SessionInfo };type PassiveRlmSubagent = PassiveRlmRoot & {- entry: PersistedRlmSubagentRegistryEntry;+ entry: PassiveRlmSubagentEntry;info: SessionInfo;- chain: PersistedRlmSubagentRegistryEntry[];+ chain: PassiveRlmSubagentEntry[];};class RuntimeOpenCancelledError extends Error {}@@ -524,6 +555,8 @@ export class AgentDaemon {);private readonly recoveryJournal?: WorkerRecoveryJournal;private rlmSpawnLedgerInstance?: RlmSpawnLedger;+ /** In-flight admission spawn appends, awaited (and consumed) by createRlmSubagentRuntime. */+ private readonly pendingRlmSpawnAppends = new Map<string, Promise<void>>();constructor(private readonly socketPath: string,@@ -901,23 +934,6 @@ export class AgentDaemon {return this.rlmSpawnLedgerInstance;}- private appendRlmLedgerSpawn(input: {- childId: string;- parent: string;- child: string;- depth: number;- name: string;- }): void {- this.rlmSpawnLedger()- .appendSpawn(input)- .catch((error) => {- // TODO: once the ledger is the messaging authority (post-stack- // rebase), a swallowed spawn-append failure means an invisible- // child — revisit failing admission here instead of logging.- this.log(`failed to append RLM ledger spawn: ${error instanceof Error ? error.message : String(error)}`);- });- }-private async appendRlmLedgerRenameForState(state: ActiveSessionState, name: string): Promise<void> {const childId = state.runtime.metadata.rlmChildId;const child = state.runtime.session.sessionFile;@@ -931,43 +947,72 @@ export class AgentDaemon {});}- private rlmSubagentRegistryPath(parentSession: AgentSession): string | undefined {- const artifactDir = parentSession.sessionManager.getSessionArtifactDir();- if (!artifactDir) {- return undefined;- }- return join(artifactDir, RLM_SUBAGENT_REGISTRY_FILE);+ /**+ * Legacy per-parent registry path. Read-only: consumed solely as fallback+ * hydration metadata for pre-ledger children without a display file (the+ * ledger seed source has its own equivalent reader).+ */+ private legacyRlmSubagentRegistryPath(parentSessionFile: string, parentSessionId: string): string {+ return join(+ dirname(dirname(parentSessionFile)),+ "session-artifacts",+ parentSessionId,+ RLM_SUBAGENT_REGISTRY_FILE,+ );}- private appendRlmSubagentRegistryEntry(- parentState: ActiveSessionState,- entry: PersistedRlmSubagentRegistryEntry,- ): boolean {- const path = this.rlmSubagentRegistryPath(parentState.runtime.session);- if (!path) {- return true;- }+ private async readLegacyRlmSubagentRegistry(+ path: string,+ throwOnReadError = false,+ ): Promise<LegacyRlmSubagentRegistryEntry[]> {+ let lines: string[];try {- mkdirSync(dirname(path), { recursive: true });- const existing = existsSync(path) ? readFileSync(path, "utf8") : "";- const separator = existing.length > 0 && !existing.endsWith("\n") ? "\n" : "";- const handle = openSync(path, "a");+ lines = (await readFile(path, "utf8")).split(/\r?\n/);+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") {+ this.log(`failed to read RLM subagent registry: ${error instanceof Error ? error.message : String(error)}`);+ if (throwOnReadError) {+ throw error;+ }+ }+ return [];+ }+ const latest = new Map<string, LegacyRlmSubagentRegistryEntry>();+ for (const line of lines) {+ const trimmed = line.trim();+ if (!trimmed) {+ continue;+ }try {- writeSync(handle, `${separator}${JSON.stringify(entry)}\n`);- fsyncSync(handle);- } finally {- closeSync(handle);+ const entry = JSON.parse(trimmed) as Partial<LegacyRlmSubagentRegistryEntry>;+ if (+ entry.type !== "rlm_subagent" ||+ typeof entry.childId !== "string" ||+ typeof entry.sessionName !== "string" ||+ typeof entry.sessionDir !== "string" ||+ typeof entry.sessionFile !== "string" ||+ (entry.status !== "running" && entry.status !== "completed" && entry.status !== "deleted") ||+ (entry.rlmDepth !== undefined && (!Number.isSafeInteger(entry.rlmDepth) || entry.rlmDepth < 0)) ||+ (entry.rlmMaxDepth !== undefined && (!Number.isSafeInteger(entry.rlmMaxDepth) || entry.rlmMaxDepth < 0))+ ) {+ continue;+ }+ latest.set(entry.childId, entry as LegacyRlmSubagentRegistryEntry);+ } catch (error) {+ this.log(+ `ignored malformed RLM subagent registry entry: ${error instanceof Error ? error.message : String(error)}`,+ );}- return true;- } catch (error) {- this.log(- `failed to persist RLM subagent registry entry: ${error instanceof Error ? error.message : String(error)}`,- );- return false;}+ return [...latest.values()];}- private recordRlmSubagentRegistryEntry(+ /**+ * Record a spawned or completed child: topology (the spawn edge) goes to+ * the daemon-owned ledger at admission; hydration/display metadata goes to+ * the child's per-child display file at both moments.+ */+ private recordRlmSubagentState(parentState: ActiveSessionState,input: {childId: string;@@ -980,41 +1025,49 @@ export class AgentDaemon {prompt?: string;spawnCode?: string;model?: { provider: string; modelId: string };- status: PersistedRlmSubagentRegistryEntry["status"];+ status: "running" | "completed";createdAt?: number;},): boolean {const parentSession = parentState.runtime.session;- // Spawn admission is the moment the daemon knows the edge firsthand;- // record it in the supervisor-owned ledger (registries keep being- // written unchanged for their non-topology consumers).+ // Spawn admission is the moment the daemon knows the edge firsthand.+ // The ledger is the only topology store, so the append's outcome is+ // load-bearing: the promise is stashed per childId for the admission+ // path to await — admission fails if the spawn record cannot be made+ // durable (a swallowed failure would admit a child that listing,+ // hydration, and a2a wake can never find after passivation).if (input.status === "running" && parentSession.sessionFile) {- this.appendRlmLedgerSpawn({+ const spawnAppend = this.rlmSpawnLedger().appendSpawn({childId: input.childId,parent: parentSession.sessionFile,child: input.sessionFile,depth: input.rlmDepth,name: input.sessionName,});+ // Mark handled so an early rejection cannot surface as an+ // unhandled-rejection crash before the admission path awaits it.+ spawnAppend.catch(() => undefined);+ this.pendingRlmSpawnAppends.set(input.childId, spawnAppend);+ }+ try {+ writeRlmSubagentDisplayEntry({+ type: "rlm_subagent",+ childId: input.childId,+ sessionName: input.sessionName,+ sessionDir: input.sessionDir,+ sessionFile: input.sessionFile,+ ...rlmSubagentMetadataFields(input),+ status: input.status,+ createdAt: input.createdAt ?? Date.now(),+ updatedAt: new Date().toISOString(),+ });+ return true;+ } catch (error) {+ this.log(+ `failed to persist RLM subagent display entry: ${error instanceof Error ? error.message : String(error)}`,+ );+ return false;}- return this.appendRlmSubagentRegistryEntry(parentState, {- type: "rlm_subagent",- childId: input.childId,- sessionName: input.sessionName,- sessionDir: input.sessionDir,- sessionFile: input.sessionFile,- parentSessionId: parentSession.sessionId,- ...(parentSession.sessionFile ? { parentSessionFile: parentSession.sessionFile } : {}),- rlmDepth: input.rlmDepth,- rlmMaxDepth: input.rlmMaxDepth,- ...(input.rlmParentNodeId ? { rlmParentNodeId: input.rlmParentNodeId } : {}),- ...(input.prompt ? { prompt: input.prompt } : {}),- ...(input.spawnCode ? { spawnCode: input.spawnCode } : {}),- ...(input.model ? { model: input.model } : {}),- status: input.status,- createdAt: input.createdAt ?? Date.now(),- updatedAt: new Date().toISOString(),- });}private async recordRlmSubagentDeletion(@@ -1022,173 +1075,215 @@ export class AgentDaemon {childId: string,reason: RlmLedgerDeleteReason = "user",): Promise<void> {- const latest = (await this.readLatestRlmSubagentRegistry(parentState, true)).find(- (entry) => entry.childId === childId,- );- if (!latest) {+ const parentFile = parentState.runtime.session.sessionFile;+ if (!parentFile) {return;}- if (latest.status === "deleted") {- // Self-heal: a crash between the registry tombstone and the ledger- // delete leaves a permanent ghost live edge; retrying the deletion- // finishes the ledger side.- await this.appendRlmLedgerDeleteIfLive(childId, latest.sessionFile, reason);+ const parentPath = canonicalSessionPath(parentFile);+ const edges = (await this.rlmSpawnLedger().edges(true)).filter(+ (candidate) => candidate.childId === childId && canonicalSessionPath(candidate.parent) === parentPath,+ );+ const edge = edges.find((candidate) => !candidate.deleted);+ let entry: PassiveRlmSubagentEntry | undefined;+ if (edge) {+ entry = await this.passiveRlmSubagentEntryForEdge(edge, {+ sessionId: parentState.runtime.session.sessionId,+ sessionFile: parentFile,+ });+ } else if (edges.length > 0) {+ // Only a tombstoned edge: the topology tombstone is already durable+ // (the display tombstone was written before it), nothing to re-append.return;+ } else {+ // No edge at all. A pre-ledger child the seed missed may still exist+ // in the legacy registry; an unreadable registry means the durable+ // deletion boundary cannot be established, so the deletion fails.+ const legacy = (+ await this.readLegacyRlmSubagentRegistry(+ this.legacyRlmSubagentRegistryPath(parentFile, parentState.runtime.session.sessionId),+ true,+ )+ ).find((candidate) => candidate.childId === childId);+ if (!legacy || legacy.status === "deleted") {+ // The child never existed under this parent, or its tombstone is+ // already durable.+ return;+ }+ entry = {+ childId: legacy.childId,+ sessionName: legacy.sessionName,+ sessionDir: legacy.sessionDir,+ sessionFile: legacy.sessionFile,+ parentSessionId: parentState.runtime.session.sessionId,+ parentSessionFile: parentFile,+ ...(legacy.rlmDepth !== undefined ? { rlmDepth: legacy.rlmDepth } : {}),+ ...rlmSubagentMetadataFields(legacy),+ status: legacy.status,+ createdAt: legacy.createdAt,+ };}- if (- !this.appendRlmSubagentRegistryEntry(parentState, {- ...latest,+ // Display tombstone first ("deleted deliberately, transcript retained"):+ // a crash in between leaves a live ledger edge over a deleted display+ // entry, healed by retrying the deletion; the reverse order could+ // tombstone the ledger while the display file still claims the child+ // exists.+ try {+ writeRlmSubagentDisplayEntry({+ type: "rlm_subagent",+ childId: entry.childId,+ sessionName: entry.sessionName,+ sessionDir: entry.sessionDir,+ sessionFile: entry.sessionFile,+ ...rlmSubagentMetadataFields(entry),status: "deleted",+ createdAt: entry.createdAt,updatedAt: new Date().toISOString(),- })- ) {- throw new Error(`Failed to persist deletion for RLM subagent ${childId}`);- }- // After the registry tombstone: a crash in between leaves a live ledger- // edge over a tombstoned registry entry (healed on a retried delete);- // the reverse order could tombstone the ledger while the registry still- // claims the child exists.- await this.rlmSpawnLedger()- .appendDelete({ childId, child: latest.sessionFile, reason })- .catch((error) => {- this.log(`failed to append RLM ledger delete: ${error instanceof Error ? error.message : String(error)}`);});- }-- private async appendRlmLedgerDeleteIfLive(childId: string, child: string, reason: RlmLedgerDeleteReason) {- try {- const ledger = this.rlmSpawnLedger();- const target = canonicalSessionPath(child);- const live = (await ledger.edges()).some(- (edge) => edge.childId === childId && canonicalSessionPath(edge.child) === target,- );- if (live) {- await ledger.appendDelete({ childId, child, reason });- }} catch (error) {- this.log(`failed to heal RLM ledger delete: ${error instanceof Error ? error.message : String(error)}`);+ throw new Error(+ `Failed to persist deletion for RLM subagent ${childId}: ${error instanceof Error ? error.message : String(error)}`,+ );}+ // The ledger delete record is the topology tombstone; unlike the+ // dual-write era it has no other writer to fall back on, so a failed+ // append is a failed deletion.+ await this.rlmSpawnLedger().appendDelete({ childId, child: entry.sessionFile, reason });}- private readLatestRlmSubagentRegistry(- parentState: ActiveSessionState,- throwOnReadError = false,- ): Promise<PersistedRlmSubagentRegistryEntry[]> {- return this.readLatestRlmSubagentRegistryPath(- this.rlmSubagentRegistryPath(parentState.runtime.session),- throwOnReadError,- );- }-- private async readLatestRlmSubagentRegistryPath(- path: string | undefined,- throwOnReadError = false,- ): Promise<PersistedRlmSubagentRegistryEntry[]> {- if (!path) {- return [];- }- const latest = new Map<string, PersistedRlmSubagentRegistryEntry>();- let lines: string[];+ /**+ * Hydration/display metadata for one live ledger edge: per-child display+ * file first, then the legacy registry for pre-ledger children, then+ * edge-only defaults. Topology (childId, paths, depth, name) always comes+ * from the ledger edge.+ */+ private async passiveRlmSubagentEntryForEdge(+ edge: RlmLedgerEdge,+ parent: { sessionId: string; sessionFile: string },+ legacyRegistryCache?: Map<string, Promise<LegacyRlmSubagentRegistryEntry[]>>,+ ): Promise<PassiveRlmSubagentEntry> {+ const edgeChild = canonicalSessionPath(edge.child);+ const base = {+ childId: edge.childId,+ sessionName: edge.name,+ sessionDir: dirname(edge.child),+ sessionFile: edge.child,+ parentSessionId: parent.sessionId,+ parentSessionFile: parent.sessionFile,+ };+ // The ledger stores realpath-canonical paths, the rest of the daemon+ // keys maps by resolve(): present the paths the writer recorded (the+ // metadata file is validated to describe this same child) so passive+ // rows keep matching residency, opens, and passivation bookkeeping.+ const metadataFields = (source: {+ sessionDir: string;+ sessionFile: string;+ rlmMaxDepth?: number;+ rlmParentNodeId?: string;+ prompt?: string;+ spawnCode?: string;+ model?: { provider: string; modelId: string };+ status: "running" | "completed" | "deleted";+ createdAt: number;+ }) => ({+ ...base,+ ...(canonicalSessionPath(source.sessionFile) === edgeChild+ ? { sessionDir: source.sessionDir, sessionFile: source.sessionFile }+ : {}),+ ...rlmSubagentMetadataFields(source),+ status: source.status,+ createdAt: source.createdAt,+ });+ const display = await readRlmSubagentDisplayEntry(dirname(edge.child));+ if (display && display.childId === edge.childId) {+ // A display-file child was ledger-spawned: the edge depth is real.+ return { ...metadataFields(display), rlmDepth: edge.depth };+ }+ const registryPath = this.legacyRlmSubagentRegistryPath(parent.sessionFile, parent.sessionId);+ let registryRead = legacyRegistryCache?.get(registryPath);+ if (!registryRead) {+ registryRead = this.readLegacyRlmSubagentRegistry(registryPath);+ legacyRegistryCache?.set(registryPath, registryRead);+ }+ const legacy = (await registryRead).find((entry) => entry.childId === edge.childId);+ if (legacy) {+ // A seeded edge's depth may be a parent+1 guess for legacy entries+ // without one: leave it absent so hydration falls back to the+ // persisted header depth, exactly as the registry reader did.+ return { ...metadataFields(legacy), ...(legacy.rlmDepth !== undefined ? { rlmDepth: legacy.rlmDepth } : {}) };+ }+ // Ledger-only child (metadata lost): hydratable with defaults.+ let createdAt = 0;try {- lines = (await readFile(path, "utf8")).split(/\r?\n/);- } catch (error) {- if ((error as NodeJS.ErrnoException).code === "ENOENT") {- return [];- }- this.log(`failed to read RLM subagent registry: ${error instanceof Error ? error.message : String(error)}`);- if (throwOnReadError) {- throw error;- }- return [];- }- for (const line of lines) {- const trimmed = line.trim();- if (!trimmed) {- continue;- }- try {- const entry = JSON.parse(trimmed) as Partial<PersistedRlmSubagentRegistryEntry>;- if (- entry.type !== "rlm_subagent" ||- typeof entry.childId !== "string" ||- typeof entry.sessionName !== "string" ||- typeof entry.sessionDir !== "string" ||- typeof entry.sessionFile !== "string" ||- (entry.status !== "running" && entry.status !== "completed" && entry.status !== "deleted") ||- (entry.rlmDepth !== undefined && (!Number.isSafeInteger(entry.rlmDepth) || entry.rlmDepth < 0)) ||- (entry.rlmMaxDepth !== undefined && (!Number.isSafeInteger(entry.rlmMaxDepth) || entry.rlmMaxDepth < 0))- ) {- continue;- }- latest.set(entry.childId, entry as PersistedRlmSubagentRegistryEntry);- } catch (error) {- this.log(- `ignored malformed RLM subagent registry entry: ${error instanceof Error ? error.message : String(error)}`,- );- }+ createdAt = (await stat(edge.child)).birthtimeMs || 0;+ } catch {+ // The stat is display-grade; a failed read keeps the epoch default.}- return [...latest.values()];+ return { ...base, rlmDepth: edge.depth, status: "completed", createdAt };}- private rlmSubagentRegistryPathForEntry(entry: PersistedRlmSubagentRegistryEntry, info: SessionInfo): string {- return join(dirname(entry.sessionDir), "session-artifacts", info.id, RLM_SUBAGENT_REGISTRY_FILE);- }-- private rlmSubagentRegistryPathForInfo(info: SessionInfo): string {- return join(dirname(dirname(info.path)), "session-artifacts", info.id, RLM_SUBAGENT_REGISTRY_FILE);- }-- /** Walk each supplied parent's persisted child tree once, without creating runtimes. */+ /** List each root's passive (non-resident) descendants from the ledger, without creating runtimes. */private async listPassiveRlmSubagents(savedRoots: SessionInfo[] = [],includeResident = false,): Promise<PassiveRlmSubagent[]> {+ const residentRoots: Array<{ parentState: ActiveSessionState; sessionFile: string }> = [];+ for (const parentState of this.sessions.values()) {+ const parentFile = parentState.runtime.session.sessionFile;+ // An in-memory session cannot own persisted children.+ if (parentFile) residentRoots.push({ parentState, sessionFile: parentFile });+ }+ const savedRootInfos = savedRoots.filter((rootInfo) => inactiveLifecycleForSession(rootInfo) === "live");+ if (residentRoots.length === 0 && savedRootInfos.length === 0) return [];+ const edges = await this.rlmSpawnLedger().edges();+ const childrenByParent = new Map<string, RlmLedgerEdge[]>();+ for (const edge of edges) {+ const parentPath = canonicalSessionPath(edge.parent);+ const siblings = childrenByParent.get(parentPath) ?? [];+ siblings.push(edge);+ childrenByParent.set(parentPath, siblings);+ }+ const legacyRegistryCache = new Map<string, Promise<LegacyRlmSubagentRegistryEntry[]>>();const passive: PassiveRlmSubagent[] = [];const visit = async (root: PassiveRlmRoot,- entries: PersistedRlmSubagentRegistryEntry[],- parentChain: PersistedRlmSubagentRegistryEntry[],+ parent: { sessionId: string; sessionFile: string },+ parentChain: PassiveRlmSubagentEntry[],visited: Set<string>,): Promise<void> => {- for (const entry of entries) {+ for (const edge of childrenByParent.get(canonicalSessionPath(parent.sessionFile)) ?? []) {+ // The ledger stores realpath-canonical paths while the rest of the+ // daemon keys by resolve(): work with the writer-recorded path from+ // the metadata entry so passive rows keep matching residency,+ // opens, and passivation bookkeeping.+ const entry = await this.passiveRlmSubagentEntryForEdge(edge, parent, legacyRegistryCache);const sessionKey = resolve(entry.sessionFile);if (entry.status === "deleted" || visited.has(sessionKey)) continue;visited.add(sessionKey);const info = await readSessionInfo(entry.sessionFile);if (!info) continue;- // A resident child walks its own registry as an outer root below. Avoid+ // A resident child walks its own subtree as an outer root below. Avoid// both duplicate rows and attributing its descendants to an ancestor.if (!includeResident && this.findSessionBySessionFile(entry.sessionFile)) continue;const chain = [...parentChain, entry];passive.push({ ...root, entry, info, chain });- await visit(- root,- await this.readLatestRlmSubagentRegistryPath(this.rlmSubagentRegistryPathForEntry(entry, info)),- chain,- visited,- );+ await visit(root, { sessionId: info.id, sessionFile: entry.sessionFile }, chain, visited);}};const residentRootPaths = new Set<string>();- for (const parentState of this.sessions.values()) {- const parentFile = parentState.runtime.session.sessionFile;- // An in-memory session cannot own a persisted registry.- if (!parentFile) continue;- const parentPath = resolve(parentFile);+ for (const { parentState, sessionFile } of residentRoots) {+ const parentPath = resolve(sessionFile);residentRootPaths.add(parentPath);await visit({ rootParentState: parentState },- await this.readLatestRlmSubagentRegistry(parentState),+ { sessionId: parentState.runtime.session.sessionId, sessionFile },[],new Set([parentPath]),);}- for (const rootInfo of savedRoots) {+ for (const rootInfo of savedRootInfos) {const rootPath = resolve(rootInfo.path);- if (inactiveLifecycleForSession(rootInfo) !== "live" || residentRootPaths.has(rootPath)) continue;- const registryPath = this.rlmSubagentRegistryPathForInfo(rootInfo);- if (!existsSync(registryPath)) continue;- await visit({ rootInfo }, await this.readLatestRlmSubagentRegistryPath(registryPath), [], new Set([rootPath]));+ if (residentRootPaths.has(rootPath)) continue;+ await visit({ rootInfo }, { sessionId: rootInfo.id, sessionFile: rootInfo.path }, [], new Set([rootPath]));}return passive;}@@ -2323,7 +2418,7 @@ export class AgentDaemon {if (state.runtime.metadata.rehydratedCompleted) return true;const metadata = state.runtime.metadata;const model = session.model;- return this.recordRlmSubagentRegistryEntry(parentState, {+ return this.recordRlmSubagentState(parentState, {childId,sessionName: session.sessionName ?? childId,sessionDir: metadata.sessionDir ?? dirname(state.runtime.session.sessionFile),@@ -2370,10 +2465,36 @@ export class AgentDaemon {candidate.runtime.metadata.parentActiveSessionId === parentState.activeSessionId &&candidate.runtime.metadata.rlmChildId === childId,);- const persisted = (await this.readLatestRlmSubagentRegistry(parentState, true)).find(- (entry) => entry.childId === childId,- );- const childSessionFile = persisted?.sessionFile ?? state?.runtime.session.sessionFile;+ const parentFile = parentState.runtime.session.sessionFile;+ const parentPath = parentFile ? canonicalSessionPath(parentFile) : undefined;+ // Tombstoned edges included: a retried delete must still resolve the+ // child's path so its scheduled jobs get cancelled.+ const persistedEdge = parentPath+ ? (await this.rlmSpawnLedger().edges(true)).find(+ (edge) => edge.childId === childId && canonicalSessionPath(edge.parent) === parentPath,+ )+ : undefined;+ // The writer-recorded path (not the ledger's realpath-canonical one)+ // keys the cron store and residency maps.+ const persisted =+ persistedEdge && parentFile+ ? await this.passiveRlmSubagentEntryForEdge(persistedEdge, {+ sessionId: parentState.runtime.session.sessionId,+ sessionFile: parentFile,+ })+ : undefined;+ // Pre-ledger children have no edge at all (tombstoned or live): the+ // legacy registry (including its tombstones) is the last path source.+ const legacyFallback =+ !persisted && !state && parentFile+ ? (+ await this.readLegacyRlmSubagentRegistry(+ this.legacyRlmSubagentRegistryPath(parentFile, parentState.runtime.session.sessionId),+ )+ ).find((entry) => entry.childId === childId)+ : undefined;+ const childSessionFile =+ persisted?.sessionFile ?? state?.runtime.session.sessionFile ?? legacyFallback?.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);@@ -2477,44 +2598,70 @@ export class AgentDaemon {},}),);- await this.addRuntime(- runtime,- undefined,- parentState.clientEnv,- (state) => {- stateRef = state;- },- () => options.parentSession.getRlmChildRunStatus(options.id) !== "cancelled",- () => {- if (runtime.session.sessionName !== options.sessionName) {- runtime.session.setSessionName(options.sessionName);- }- if (runtime.session.sessionFile) {- this.recordRlmSubagentRegistryEntry(parentState, {- childId: options.id,- sessionName: options.sessionName,- sessionDir: options.sessionDir,- sessionFile: runtime.session.sessionFile,- rlmDepth: options.rlmDepth,- rlmMaxDepth: options.rlmMaxDepth,- rlmParentNodeId: options.rlmParentNodeId,- prompt: options.prompt.length <= 4096 ? options.prompt : undefined,- spawnCode: options.spawnCode,- model: {- provider: options.model.provider,- modelId: options.model.id,- },- status: "running",- createdAt: runtime.metadata.createdAt,- });- }- options.onSessionPublished?.(runtime.session);- },- );+ let state: ActiveSessionState;+ try {+ state = await this.addRuntime(+ runtime,+ undefined,+ parentState.clientEnv,+ (createdState) => {+ stateRef = createdState;+ },+ () => options.parentSession.getRlmChildRunStatus(options.id) !== "cancelled",+ () => {+ if (runtime.session.sessionName !== options.sessionName) {+ runtime.session.setSessionName(options.sessionName);+ }+ if (runtime.session.sessionFile) {+ this.recordRlmSubagentState(parentState, {+ childId: options.id,+ sessionName: options.sessionName,+ sessionDir: options.sessionDir,+ sessionFile: runtime.session.sessionFile,+ rlmDepth: options.rlmDepth,+ rlmMaxDepth: options.rlmMaxDepth,+ rlmParentNodeId: options.rlmParentNodeId,+ prompt: options.prompt.length <= 4096 ? options.prompt : undefined,+ spawnCode: options.spawnCode,+ model: {+ provider: options.model.provider,+ modelId: options.model.id,+ },+ status: "running",+ createdAt: runtime.metadata.createdAt,+ });+ }+ options.onSessionPublished?.(runtime.session);+ },+ );+ } catch (error) {+ this.pendingRlmSpawnAppends.delete(options.id);+ throw error;+ }// Admission is complete only once the spawn record is durably in the// ledger: no self-heal exists for a lost spawn record (seeding only runs- // when the ledger file is absent; reconciliation only drops edges).- await this.rlmSpawnLedger().flush();+ // when the ledger file is absent; reconciliation only drops edges). A+ // failed append therefore FAILS admission — the just-added child is+ // closed like any other admission failure rather than admitted as a+ // ghost the ledger-driven listing and hydration could never find.+ const spawnAppend = this.pendingRlmSpawnAppends.get(options.id);+ this.pendingRlmSpawnAppends.delete(options.id);+ try {+ await spawnAppend;+ } catch (error) {+ await this.closeSession(state, "killed", false).catch(() => undefined);+ // The child was never admitted: no ledger edge exists, so the+ // display file written at the spawn write point must not remain+ // claiming a running child.+ try {+ rmSync(rlmSubagentDisplayPath(options.sessionDir), { force: true });+ } catch {+ // Best-effort: a stale display file without an edge is inert.+ }+ throw new Error(+ `Failed to record RLM subagent spawn for ${options.id}: ${error instanceof Error ? error.message : String(error)}`,+ );+ }return runtime;}@@ -2734,7 +2881,7 @@ export class AgentDaemon {private async rehydrateCompletedRlmSubagent(parentState: ActiveSessionState,- entry: PersistedRlmSubagentRegistryEntry,+ entry: PassiveRlmSubagentEntry,restoreActiveSessionId?: string,clientEnv?: Record<string, string>,): Promise<ActiveSessionState> {@@ -2794,7 +2941,7 @@ export class AgentDaemon {private async rehydrateCompletedRlmSubagentOnce(parentState: ActiveSessionState,- entry: PersistedRlmSubagentRegistryEntry,+ entry: PassiveRlmSubagentEntry,restoreActiveSessionId?: string,clientEnv?: Record<string, string>,): Promise<ActiveSessionState> {diff --git a/packages/coding-agent/src/modes/daemon/rlm-ledger.ts b/packages/coding-agent/src/modes/daemon/rlm-ledger.tsindex 4c52dd7c66..0f8e6a4d1b 100644--- a/packages/coding-agent/src/modes/daemon/rlm-ledger.ts+++ b/packages/coding-agent/src/modes/daemon/rlm-ledger.ts@@ -11,7 +11,6 @@ import {readFileSync,readSync,realpathSync,- renameSync,rmSync,statSync,writeSync,@@ -369,9 +368,14 @@ export class RlmSpawnLedger {return this.queue.then(() => undefined);}- /** Replay live (non-deleted) edges, without liveness reconciliation. */- edges(): Promise<RlmLedgerEdge[]> {- return this.enqueue(() => [...this.replaySync().values()].filter((edge) => !edge.deleted));+ /**+ * Replay edges without liveness reconciliation. Deleted edges are filtered+ * by default; `includeDeleted` keeps the tombstones (marked with their+ * delete reason) for consumers that need a deleted child's identity, such+ * as cleanup retries.+ */+ edges(includeDeleted = false): Promise<RlmLedgerEdge[]> {+ return this.enqueue(() => [...this.replaySync().values()].filter((edge) => includeDeleted || !edge.deleted));}/**@@ -675,25 +679,20 @@ export class RlmSpawnLedger {private publishSeedFile(tempPath: string): void {// Atomic no-clobber publish: link() fails with EEXIST if a live append// created the real file meanwhile — that append wins (its data is- // fresher than the registries) and the seed is discarded. A clobbering- // rename() here would overwrite and lose that append.+ // fresher than the registries) and the seed is discarded. No-clobber+ // publication is a hard requirement for seeding: post-consolidation,+ // deletes live only in the ledger, so any clobber window can lose live+ // appends and resurrect deleted edges. Filesystems that cannot provide+ // link() therefore get flat pre-ledger history (the documented+ // degradation mode) rather than a check-then-rename race.try {linkSync(tempPath, this.path);- return;} catch (error) {const code = (error as NodeJS.ErrnoException).code;if (code === "EEXIST") {return;}- // Filesystems without hard links (network/synced homes, non-NTFS- // Windows volumes): fall back to check-then-rename. Non-atomic, but- // strictly better than never seeding; the residual window is the- // documented O_APPEND trust bucket.- this.log(`RLM ledger: link publish failed (${code ?? "unknown"}), falling back to rename`);- if (existsSync(this.path)) {- return;- }- renameSync(tempPath, this.path);+ this.log(`RLM ledger: link publish unavailable (${code ?? "unknown"}); skipping seeding`);}}diff --git a/packages/coding-agent/src/modes/daemon/rlm-subagent-display.ts b/packages/coding-agent/src/modes/daemon/rlm-subagent-display.tsnew file mode 100644index 0000000000..f3a0a8cd9c--- /dev/null+++ b/packages/coding-agent/src/modes/daemon/rlm-subagent-display.ts@@ -0,0 +1,89 @@+import { closeSync, fsyncSync, mkdirSync, openSync, renameSync, rmSync, writeSync } from "node:fs";+import { readFile } from "node:fs/promises";+import { join } from "node:path";++/**+ * Per-child RLM subagent hydration/display metadata.+ *+ * One JSON file per child in the child's own session dir+ * (`session-artifacts/<parentId>/<childId>/rlm-subagent.json`). Topology+ * (parent/child edges, depths, names) lives exclusively in the daemon-owned+ * spawn ledger and is never read from this file; it carries only what+ * hydration and display need. It is written at the same moments the legacy+ * per-parent `rlm-subagents.jsonl` registry used to be written: spawn+ * admission, completion, and deletion. Writes are atomic (temp file ++ * rename); reads are tolerant.+ */+const RLM_SUBAGENT_DISPLAY_FILE = "rlm-subagent.json";++export interface RlmSubagentDisplayEntry {+ type: "rlm_subagent";+ childId: string;+ sessionName: string;+ sessionDir: string;+ sessionFile: string;+ rlmMaxDepth?: number;+ rlmParentNodeId?: string;+ prompt?: string;+ spawnCode?: string;+ model?: { provider: string; modelId: string };+ status: "running" | "completed" | "deleted";+ createdAt: number;+ updatedAt: string;+}++export function rlmSubagentDisplayPath(sessionDir: string): string {+ return join(sessionDir, RLM_SUBAGENT_DISPLAY_FILE);+}++function isRlmSubagentDisplayEntry(value: unknown): value is RlmSubagentDisplayEntry {+ if (!value || typeof value !== "object") return false;+ const entry = value as Partial<RlmSubagentDisplayEntry>;+ return (+ entry.type === "rlm_subagent" &&+ typeof entry.childId === "string" &&+ typeof entry.sessionName === "string" &&+ typeof entry.sessionDir === "string" &&+ typeof entry.sessionFile === "string" &&+ (entry.status === "running" || entry.status === "completed" || entry.status === "deleted") &&+ (entry.rlmMaxDepth === undefined || (Number.isSafeInteger(entry.rlmMaxDepth) && entry.rlmMaxDepth >= 0)) &&+ typeof entry.createdAt === "number"+ );+}++/** Atomic write (temp + rename). Throws on failure; callers decide severity. */+export function writeRlmSubagentDisplayEntry(entry: RlmSubagentDisplayEntry): void {+ const path = rlmSubagentDisplayPath(entry.sessionDir);+ mkdirSync(entry.sessionDir, { recursive: true });+ const tempPath = `${path}.tmp-${process.pid}-${Date.now()}`;+ const handle = openSync(tempPath, "wx", 0o600);+ try {+ try {+ writeSync(handle, `${JSON.stringify(entry)}\n`);+ fsyncSync(handle);+ } finally {+ closeSync(handle);+ }+ renameSync(tempPath, path);+ } catch (error) {+ // A failed write, fsync, or rename must not leak the temp file.+ rmSync(tempPath, { force: true });+ throw error;+ }+}++/** Tolerant read: undefined for a missing, malformed, or invalid file. */+export async function readRlmSubagentDisplayEntry(sessionDir: string): Promise<RlmSubagentDisplayEntry | undefined> {+ let contents: string;+ try {+ contents = await readFile(rlmSubagentDisplayPath(sessionDir), "utf8");+ } catch {+ return undefined;+ }+ try {+ const parsed = JSON.parse(contents) as unknown;+ return isRlmSubagentDisplayEntry(parsed) ? parsed : undefined;+ } catch {+ return undefined;+ }+}diff --git a/packages/coding-agent/test/daemon-catalog-process.test.ts b/packages/coding-agent/test/daemon-catalog-process.test.tsindex 53bc162f1d..98282f4e43 100644--- a/packages/coding-agent/test/daemon-catalog-process.test.ts+++ b/packages/coding-agent/test/daemon-catalog-process.test.ts@@ -1,9 +1,6 @@-import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs";-import { tmpdir } from "node:os";-import { dirname, join, relative } from "node:path";import { describe, expect, it } from "vitest";-import { type SessionInfo, SessionManager } from "../src/core/session-manager.js";-import { listSavedSessionSiblings, resolveCatalogSessionMatch } from "../src/modes/daemon/daemon-catalog-process.js";+import type { SessionInfo } from "../src/core/session-manager.js";+import { resolveCatalogSessionMatch } from "../src/modes/daemon/daemon-catalog-process.js";function session(id: string, name: string | undefined, path: string): SessionInfo {return {@@ -21,69 +18,6 @@ function session(id: string, name: string | undefined, path: string): SessionInf}describe("daemon catalog selector resolution", () => {- it("reads only a saved child's persisted sibling set", async () => {- const root = mkdtempSync(join(tmpdir(), "prime-catalog-siblings-"));- const sessionDir = join(root, "sessions");- const parent = SessionManager.create(root, sessionDir);- parent.newSession();- parent.appendSessionInfo("parent");- const first = SessionManager.create(root, join(root, "first"));- first.newSession({ parentSession: parent.getSessionFile(), rlmDepth: 1 });- first.appendSessionInfo("first");- const second = SessionManager.create(root, join(root, "second"));- second.newSession({ parentSession: parent.getSessionFile(), rlmDepth: 1 });- second.appendSessionInfo("second");- const registry = join(dirname(sessionDir), "session-artifacts", parent.getSessionId(), "rlm-subagents.jsonl");- mkdirSync(dirname(registry), { recursive: true });- writeFileSync(- registry,- [- { type: "rlm_subagent", childId: "first", sessionFile: first.getSessionFile(), status: "completed" },- { type: "rlm_subagent", childId: "second", sessionFile: second.getSessionFile(), status: "completed" },- ]- .map((entry) => JSON.stringify(entry))- .join("\n"),- );-- await expect(listSavedSessionSiblings(first.getSessionFile()!)).resolves.toEqual([- expect.objectContaining({ id: first.getSessionId(), name: "first" }),- expect.objectContaining({ id: second.getSessionId(), name: "second" }),- ]);- });-- it("resolves relative parent headers from each child session directory", async () => {- const root = mkdtempSync(join(tmpdir(), "prime-catalog-relative-siblings-"));- const sessionDir = join(root, "sessions");- const parent = SessionManager.create(root, sessionDir);- parent.newSession();- parent.appendSessionInfo("parent");- const parentFile = parent.getSessionFile()!;- const firstDir = join(root, "first");- const first = SessionManager.create(root, firstDir);- first.newSession({ parentSession: relative(firstDir, parentFile), rlmDepth: 1 });- first.appendSessionInfo("first");- const secondDir = join(root, "second");- const second = SessionManager.create(root, secondDir);- second.newSession({ parentSession: relative(secondDir, parentFile), rlmDepth: 1 });- second.appendSessionInfo("second");- const registry = join(dirname(sessionDir), "session-artifacts", parent.getSessionId(), "rlm-subagents.jsonl");- mkdirSync(dirname(registry), { recursive: true });- writeFileSync(- registry,- [- { type: "rlm_subagent", childId: "first", sessionFile: first.getSessionFile(), status: "completed" },- { type: "rlm_subagent", childId: "second", sessionFile: second.getSessionFile(), status: "completed" },- ]- .map((entry) => JSON.stringify(entry))- .join("\n"),- );-- await expect(listSavedSessionSiblings(first.getSessionFile()!)).resolves.toEqual([- expect.objectContaining({ id: first.getSessionId(), name: "first" }),- expect.objectContaining({ id: second.getSessionId(), name: "second" }),- ]);- });-it("treats an exact name colliding with another session id prefix as ambiguous", () => {const sessions = [session("named-session-id", "target", "/tmp/by-name.jsonl"),diff --git a/packages/coding-agent/test/daemon-mode.test.ts b/packages/coding-agent/test/daemon-mode.test.tsindex cb4b03a5c5..c921a24786 100644--- a/packages/coding-agent/test/daemon-mode.test.ts+++ b/packages/coding-agent/test/daemon-mode.test.ts@@ -1,5 +1,14 @@import { EventEmitter } from "node:events";-import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "node:fs";+import {+ existsSync,+ mkdirSync,+ mkdtempSync,+ readdirSync,+ readFileSync,+ rmSync,+ symlinkSync,+ writeFileSync,+} from "node:fs";import { createServer, type Server, type Socket } from "node:net";import { tmpdir } from "node:os";import { join, resolve } from "node:path";@@ -44,6 +53,7 @@ import {} 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";+import { RlmSpawnLedger } from "../src/modes/daemon/rlm-ledger.js";describe("daemon mode helpers", () => {it("preserves envelope client identity while registering prompt admission", () => {@@ -815,6 +825,19 @@ describe("daemon mode helpers", () => {expect(listed).toContainEqual(expect.objectContaining({ sessionFile: childState.runtime.session.sessionFile, rlmChildId: "child-1" }),);+ // The registry is legacy read-only now: spawn and completion must land+ // in the per-child display file, never in rlm-subagents.jsonl.+ expect(existsSync(join(parentManager.getSessionArtifactDir()!, "rlm-subagents.jsonl"))).toBe(false);+ const display = JSON.parse(readFileSync(join(childSessionDir, "rlm-subagent.json"), "utf8")) as Record<+ string,+ unknown+ >;+ expect(display).toMatchObject({+ childId: "child-1",+ sessionName: "real-worker",+ status: "completed",+ prompt: "complete and persist",+ });} finally {rmSync(tempDir, { recursive: true, force: true });}@@ -5370,6 +5393,89 @@ describe("daemon mode helpers", () => {}});+ it("prefers the per-child display file over the legacy registry for passive metadata", async () => {+ const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-daemon-display-over-registry-"));+ try {+ const fixture = makePersistedRlmDaemonFixture(tempDir);+ // A post-consolidation write: the display file is fresher than the+ // stale pre-ledger registry entry left behind by an old daemon.+ writeFileSync(+ join(fixture.childSessionDir, "rlm-subagent.json"),+ `${JSON.stringify({+ type: "rlm_subagent",+ childId: fixture.childId,+ sessionName: "renamed-worker",+ sessionDir: fixture.childSessionDir,+ sessionFile: fixture.childSessionFile,+ rlmMaxDepth: 6,+ rlmParentNodeId: fixture.childId,+ prompt: "fresher prompt",+ status: "completed",+ createdAt: 3,+ updatedAt: "2026-01-02T00:00:00.000Z",+ })}\n`,+ );+ const internals = fixture.daemon as unknown as {+ createRuntime(command: Extract<DaemonCommand, { type: "create" }>): Promise<ActiveSessionState>;+ listPassiveRlmSubagents(): Promise<+ Array<{ entry: { childId: string; prompt?: string; rlmMaxDepth?: number } }>+ >;+ };+ await internals.createRuntime({ type: "create", sessionPath: fixture.parentSessionFile });++ const passive = (await internals.listPassiveRlmSubagents()).find(+ ({ entry }) => entry.childId === fixture.childId,+ );+ expect(passive?.entry).toMatchObject({ prompt: "fresher prompt", rlmMaxDepth: 6 });+ } finally {+ rmSync(tempDir, { recursive: true, force: true });+ }+ });++ it("falls back to the legacy registry for a pre-ledger child without a display file", async () => {+ const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-daemon-legacy-metadata-fallback-"));+ try {+ // The fixture writes registries exactly as the pre-consolidation daemon+ // did and no display files: the pure migration state.+ const fixture = makePersistedRlmDaemonFixture(tempDir);+ const registryPath = join(fixture.parentArtifactDir, "rlm-subagents.jsonl");+ const registryEntry = JSON.parse(readFileSync(registryPath, "utf8").trim()) as Record<string, unknown>;+ registryEntry.prompt = "legacy prompt";+ registryEntry.spawnCode = "await rlm('legacy prompt')";+ registryEntry.model = { provider: "test", modelId: "legacy-model" };+ writeFileSync(registryPath, `${JSON.stringify(registryEntry)}\n`);+ const internals = fixture.daemon as unknown as {+ createRuntime(command: Extract<DaemonCommand, { type: "create" }>): Promise<ActiveSessionState>;+ listPassiveRlmSubagents(): Promise<+ Array<{+ entry: {+ childId: string;+ prompt?: string;+ spawnCode?: string;+ model?: { provider: string; modelId: string };+ rlmMaxDepth?: number;+ status: string;+ };+ }>+ >;+ };+ await internals.createRuntime({ type: "create", sessionPath: fixture.parentSessionFile });++ const passive = (await internals.listPassiveRlmSubagents()).find(+ ({ entry }) => entry.childId === fixture.childId,+ );+ expect(passive?.entry).toMatchObject({+ prompt: "legacy prompt",+ spawnCode: "await rlm('legacy prompt')",+ model: { provider: "test", modelId: "legacy-model" },+ rlmMaxDepth: 4,+ status: "completed",+ });+ } finally {+ rmSync(tempDir, { recursive: true, force: true });+ }+ });+it("ignores a crashed registry tail and protects a nested cycle back to the root", async () => {const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-daemon-lazy-rlm-corrupt-registry-"));try {@@ -5654,7 +5760,7 @@ describe("daemon mode helpers", () => {}});- it("rehydrates completed children without rewriting their completed registry entry", async () => {+ it("rehydrates completed children without rewriting their persisted completion", async () => {const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-daemon-idempotent-rlm-hydration-"));try {const fixture = makePersistedRlmDaemonFixture(tempDir);@@ -5663,12 +5769,12 @@ describe("daemon mode helpers", () => {createAgentMessageController(getCurrentState: () => ActiveSessionState | undefined,): AgentSessionMessageController;- recordRlmSubagentRegistryEntry: ReturnType<typeof vi.fn>;+ recordRlmSubagentState: ReturnType<typeof vi.fn>;};const parentState = await internals.createRuntime({ type: "create", sessionPath: fixture.parentSessionFile });const registryPath = join(fixture.parentArtifactDir, "rlm-subagents.jsonl");const before = readFileSync(registryPath, "utf8");- internals.recordRlmSubagentRegistryEntry = vi.fn(() => false);+ internals.recordRlmSubagentState = vi.fn(() => false);await expect(internals@@ -5676,8 +5782,9 @@ describe("daemon mode helpers", () => {.sendAgentMessage({ target: "renamed-worker", message: "report progress" }),).resolves.toMatchObject({ deliveryStatus: "delivered" });- expect(internals.recordRlmSubagentRegistryEntry).not.toHaveBeenCalled();+ expect(internals.recordRlmSubagentState).not.toHaveBeenCalled();expect(readFileSync(registryPath, "utf8")).toBe(before);+ expect(existsSync(join(fixture.childSessionDir, "rlm-subagent.json"))).toBe(false);} finally {rmSync(tempDir, { recursive: true, force: true });}@@ -7251,15 +7358,83 @@ describe("daemon mode helpers", () => {expect(result.data).toEqual({ deleted: true });expect(fixture.createRuntime).toHaveBeenCalledOnce();expect(existsSync(fixture.childSessionFile)).toBe(true);- const persisted = readFileSync(join(fixture.parentArtifactDir, "rlm-subagents.jsonl"), "utf8")+ // The tombstone is durable in the child's display file ("deleted+ // deliberately, transcript retained") and in the ledger.+ const display = JSON.parse(readFileSync(join(fixture.childSessionDir, "rlm-subagent.json"), "utf8")) as {+ childId: string;+ status: string;+ };+ expect(display).toMatchObject({ childId: fixture.childId, status: "deleted" });+ const ledgerDir = join(tempDir, "rlm-ledger");+ const ledgerFile = readdirSync(ledgerDir).find((name) => name.endsWith(".jsonl"));+ if (!ledgerFile) throw new Error("Missing RLM ledger file");+ const ledgerOps = readFileSync(join(ledgerDir, ledgerFile), "utf8").trim().split(/\r?\n/)- .map((line) => JSON.parse(line) as { childId: string; status: string });- expect(persisted.at(-1)).toMatchObject({ childId: fixture.childId, status: "deleted" });+ .map((line) => JSON.parse(line) as { op: string; childId?: string });+ expect(ledgerOps.at(-1)).toMatchObject({ op: "delete", childId: fixture.childId });++ // A retried delete of the now-tombstoned child still resolves the+ // session path and cancels its scheduled jobs.+ const cronStore = (fixture.daemon as unknown as { cronStore: AgentCronJobStore }).cronStore;+ const retryJob = cronStore.create({+ activeSessionId: "gone",+ sessionId: "gone",+ sessionFile: fixture.childSessionFile,+ cwd: tempDir,+ scheduleText: "every 5m",+ prompt: "left-behind heartbeat",+ });+ await (+ fixture.daemon as unknown as { createSubagentRuntimeHost(parent: ActiveSessionState): SubagentRuntimeHost }+ )+ .createSubagentRuntimeHost(parentState)+ .deleteRlmSubagentRuntime(fixture.childId);+ expect(cronStore.list().find((candidate) => candidate.id === retryJob.id)?.status).toBe("cancelled");+ } finally {+ rmSync(tempDir, { recursive: true, force: true });+ }+ });++ it("cancels scheduled jobs when deleting a pre-ledger legacy child without hydrating it", async () => {+ const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-daemon-legacy-delete-jobs-"));+ try {+ const fixture = makePersistedRlmDaemonFixture(tempDir);+ const internals = fixture.daemon as unknown as {+ createRuntime(command: Extract<DaemonCommand, { type: "create" }>): Promise<ActiveSessionState>;+ createSubagentRuntimeHost(parent: ActiveSessionState): SubagentRuntimeHost;+ rlmSpawnLedger(): { appendDelete(input: unknown): Promise<void>; edges(all?: boolean): Promise<unknown[]> };+ cronStore: AgentCronJobStore;+ };+ const parentState = await internals.createRuntime({ type: "create", sessionPath: fixture.parentSessionFile });+ // Simulate a pre-ledger child the seed missed: only the legacy+ // registry knows it. Remove its seeded edge by deleting the ledger+ // files entirely and pointing the daemon at a fresh (empty) ledger.+ rmSync(join(tempDir, "rlm-ledger"), { recursive: true, force: true });+ (fixture.daemon as unknown as { rlmSpawnLedgerInstance?: unknown }).rlmSpawnLedgerInstance =+ new RlmSpawnLedger(tempDir, join(tempDir, "sessions"));+ const job = internals.cronStore.create({+ activeSessionId: "gone",+ sessionId: "gone",+ sessionFile: fixture.childSessionFile,+ cwd: tempDir,+ scheduleText: "every 5m",+ prompt: "legacy heartbeat",+ });++ await internals.createSubagentRuntimeHost(parentState).deleteRlmSubagentRuntime(fixture.childId);++ expect(internals.cronStore.list().find((candidate) => candidate.id === job.id)?.status).toBe("cancelled");+ // The durable tombstone lands in the child's display file.+ const display = JSON.parse(readFileSync(join(fixture.childSessionDir, "rlm-subagent.json"), "utf8")) as {+ status: string;+ };+ expect(display).toMatchObject({ status: "deleted" });} finally {rmSync(tempDir, { recursive: true, force: true });}});+it("gives RLM subagents messaging controllers for their own nested children", async () => {const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-daemon-nested-controller-"));try {diff --git a/packages/coding-agent/test/rlm-ledger.test.ts b/packages/coding-agent/test/rlm-ledger.test.tsindex bf3fc38000..18af973e15 100644--- a/packages/coding-agent/test/rlm-ledger.test.ts+++ b/packages/coding-agent/test/rlm-ledger.test.ts@@ -597,6 +597,46 @@ describe("rlm spawn ledger daemon wiring", () => {}});+ it("fails admission when the spawn record cannot be made durable", async () => {+ const tempDir = mkdtempSync(join(tmpdir(), "prime-rlm-ledger-spawn-fail-"));+ try {+ const { internals, sessionsDir } = makeDaemonFixture(tempDir);+ const parentManager = SessionManager.create(tempDir, sessionsDir);+ parentManager.newSession();+ parentManager.appendSessionInfo("parent");+ const parentFile = parentManager.getSessionFile();+ if (!parentFile) throw new Error("Missing parent session file");+ const parentState = await internals.createRuntime({ type: "create", sessionPath: parentFile });+ const ledger = internals.rlmSpawnLedger();+ const failingAppend = vi.spyOn(ledger, "appendSpawn").mockRejectedValue(new Error("ledger disk exploded"));+ const childDir = join(parentManager.getSessionArtifactDir()!, "sub-badbadba");++ await expect(+ internals.createRlmSubagentRuntime(+ parentState,+ subagentRuntimeOptions(parentState, { id: "sub-badbadba", sessionDir: childDir }),+ ),+ ).rejects.toThrow("Failed to record RLM subagent spawn for sub-badbadba");+ // No ghost resident session and no display file claiming a running+ // child the ledger cannot see.+ expect(+ [...internals.sessions.values()].some((state) => state.runtime.metadata.rlmChildId === "sub-badbadba"),+ ).toBe(false);+ expect(existsSync(join(childDir, "rlm-subagent.json"))).toBe(false);++ // The same spawn succeeds once the append works again.+ failingAppend.mockRestore();+ const retryDir = join(parentManager.getSessionArtifactDir()!, "sub-a11a11a1");+ await internals.createRlmSubagentRuntime(+ parentState,+ subagentRuntimeOptions(parentState, { id: "sub-a11a11a1", sessionDir: retryDir }),+ );+ await expect(ledger.edges()).resolves.toEqual([expect.objectContaining({ childId: "sub-a11a11a1" })]);+ } finally {+ rmSync(tempDir, { recursive: true, force: true });+ }+ });+it("records an offline saved-session rename by child path", async () => {const tempDir = mkdtempSync(join(tmpdir(), "prime-rlm-ledger-offline-rename-"));try {@@ -875,7 +915,7 @@ describe("rlm spawn ledger daemon wiring", () => {}});- it("publishes the seed via rename fallback on filesystems without hard links", async () => {+ it("skips seeding on filesystems without hard links instead of racing a clobber", async () => {const tempDir = mkdtempSync(join(tmpdir(), "prime-rlm-ledger-seed-nolink-"));try {const sessionsDir = join(tempDir, "sessions");@@ -909,15 +949,17 @@ describe("rlm spawn ledger daemon wiring", () => {);linkFailure.code = "ENOTSUP";try {- await expect(ledger.family()).resolves.toEqual([- expect.objectContaining({ name: "parent", rlmDepth: 0 }),- expect.objectContaining({ name: "worker", rlmDepth: 1 }),- ]);+ // No-clobber publication is unavailable: the seed is discarded and+ // pre-ledger history stays flat rather than risking a clobbered+ // live append.+ await expect(ledger.family()).resolves.toEqual([expect.objectContaining({ name: "parent", rlmDepth: 0 })]);} finally {linkFailure.code = undefined;}- expect(existsSync(rlmLedgerPath(tempDir, sessionsDir))).toBe(true);- expect(logged.some((message) => message.includes("falling back to rename"))).toBe(true);+ expect(existsSync(rlmLedgerPath(tempDir, sessionsDir))).toBe(false);+ expect(+ logged.some((message) => message.includes("link publish unavailable (ENOTSUP); skipping seeding")),+ ).toBe(true);} finally {rmSync(tempDir, { recursive: true, force: true });}diff --git a/packages/coding-agent/test/rlm-subagent-display.test.ts b/packages/coding-agent/test/rlm-subagent-display.test.tsnew file mode 100644index 0000000000..6dbccac065--- /dev/null+++ b/packages/coding-agent/test/rlm-subagent-display.test.ts@@ -0,0 +1,87 @@+import { mkdirSync, mkdtempSync, readdirSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { describe, expect, it } from "vitest";+import {+ type RlmSubagentDisplayEntry,+ readRlmSubagentDisplayEntry,+ rlmSubagentDisplayPath,+ writeRlmSubagentDisplayEntry,+} from "../src/modes/daemon/rlm-subagent-display.js";++function makeEntry(sessionDir: string, overrides: Partial<RlmSubagentDisplayEntry> = {}): RlmSubagentDisplayEntry {+ return {+ type: "rlm_subagent",+ childId: "sub-1234abcd",+ sessionName: "worker",+ sessionDir,+ sessionFile: join(sessionDir, "01a0-child.jsonl"),+ rlmMaxDepth: 4,+ rlmParentNodeId: "sub-1234abcd",+ prompt: "do the work",+ spawnCode: "await rlm('do the work')",+ model: { provider: "test", modelId: "model" },+ status: "running",+ createdAt: 1,+ updatedAt: "2026-01-01T00:00:00.000Z",+ ...overrides,+ };+}++describe("rlm subagent display files", () => {+ it("round-trips an entry and replaces it atomically without temp-file residue", async () => {+ const tempDir = mkdtempSync(join(tmpdir(), "prime-rlm-display-"));+ try {+ const sessionDir = join(tempDir, "sub-1234abcd");+ const entry = makeEntry(sessionDir);+ writeRlmSubagentDisplayEntry(entry);+ await expect(readRlmSubagentDisplayEntry(sessionDir)).resolves.toEqual(entry);++ const updated = makeEntry(sessionDir, { status: "deleted", updatedAt: "2026-01-01T00:00:01.000Z" });+ writeRlmSubagentDisplayEntry(updated);+ await expect(readRlmSubagentDisplayEntry(sessionDir)).resolves.toEqual(updated);+ expect(readdirSync(sessionDir)).toEqual(["rlm-subagent.json"]);+ } finally {+ rmSync(tempDir, { recursive: true, force: true });+ }+ });++ it("reads tolerantly: missing, malformed, and invalid files are undefined", async () => {+ const tempDir = mkdtempSync(join(tmpdir(), "prime-rlm-display-tolerant-"));+ try {+ const sessionDir = join(tempDir, "sub-1234abcd");+ await expect(readRlmSubagentDisplayEntry(sessionDir)).resolves.toBeUndefined();++ mkdirSync(sessionDir, { recursive: true });+ writeFileSync(rlmSubagentDisplayPath(sessionDir), "{not json");+ await expect(readRlmSubagentDisplayEntry(sessionDir)).resolves.toBeUndefined();++ writeFileSync(rlmSubagentDisplayPath(sessionDir), JSON.stringify({ type: "rlm_subagent", childId: 42 }));+ await expect(readRlmSubagentDisplayEntry(sessionDir)).resolves.toBeUndefined();++ writeFileSync(+ rlmSubagentDisplayPath(sessionDir),+ JSON.stringify(makeEntry(sessionDir, { status: "exploded" as RlmSubagentDisplayEntry["status"] })),+ );+ await expect(readRlmSubagentDisplayEntry(sessionDir)).resolves.toBeUndefined();+ } finally {+ rmSync(tempDir, { recursive: true, force: true });+ }+ });++ it("accepts unknown extra fields from newer writers", async () => {+ const tempDir = mkdtempSync(join(tmpdir(), "prime-rlm-display-forward-"));+ try {+ const sessionDir = join(tempDir, "sub-1234abcd");+ const entry = makeEntry(sessionDir);+ mkdirSync(sessionDir, { recursive: true });+ writeFileSync(rlmSubagentDisplayPath(sessionDir), JSON.stringify({ ...entry, futureField: true }));+ await expect(readRlmSubagentDisplayEntry(sessionDir)).resolves.toMatchObject({+ childId: entry.childId,+ status: "running",+ });+ } finally {+ rmSync(tempDir, { recursive: true, force: true });+ }+ });+});