A self-improving RLM agent for coding workflows and long-running autonomous tasks.
Rust
feat(daemon): supervisor-owned rlm spawn ledger as family authority (#1387)
Sebastian Müller97b994c3d7c4
diff --git a/packages/coding-agent/src/modes/daemon/daemon-mode.ts b/packages/coding-agent/src/modes/daemon/daemon-mode.tsindex 3443cd3f8c..68667dce9d 100644--- a/packages/coding-agent/src/modes/daemon/daemon-mode.ts+++ b/packages/coding-agent/src/modes/daemon/daemon-mode.ts@@ -30,6 +30,7 @@ import {getCronJobsPath,getDaemonLogPath,getDaemonUpdateRestartManifestPath,+ getSessionsDir,VERSION,} from "../../config.js";import {@@ -201,6 +202,7 @@ 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 { serializeSavedSessionInfo } from "./saved-session-info.js";import {createSnapshotTranscriptChunks,@@ -521,6 +523,7 @@ export class AgentDaemon {},);private readonly recoveryJournal?: WorkerRecoveryJournal;+ private rlmSpawnLedgerInstance?: RlmSpawnLedger;constructor(private readonly socketPath: string,@@ -878,6 +881,56 @@ export class AgentDaemon {}}+ /** Root sessions dir that keys this daemon's spawn ledger. */+ private rlmLedgerSessionsDir(): string {+ return this.options.defaultSessionConfig.sessionDir ?? getSessionsDir(this.agentDir);+ }++ /**+ * Supervisor-owned spawn ledger for this daemon's sessions dir. Seeded+ * lazily from the existing per-parent registries via the same tolerant+ * reader the daemon already uses for passive hydration.+ */+ private rlmSpawnLedger(): RlmSpawnLedger {+ this.rlmSpawnLedgerInstance ??= new RlmSpawnLedger(+ this.agentDir,+ this.rlmLedgerSessionsDir(),+ createRlmLedgerRegistrySeedSource(),+ (message) => this.log(message),+ );+ 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;+ if (!childId || !child) return;+ // Awaited: the supervisor answers sibling-name checks from the ledger,+ // so the rename must be durable before the reservation is released.+ await this.rlmSpawnLedger()+ .appendRename({ childId, child, name })+ .catch((error) => {+ this.log(`failed to append RLM ledger rename: ${error instanceof Error ? error.message : String(error)}`);+ });+ }+private rlmSubagentRegistryPath(parentSession: AgentSession): string | undefined {const artifactDir = parentSession.sessionManager.getSessionArtifactDir();if (!artifactDir) {@@ -932,6 +985,18 @@ export class AgentDaemon {},): 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).+ if (input.status === "running" && parentSession.sessionFile) {+ this.appendRlmLedgerSpawn({+ childId: input.childId,+ parent: parentSession.sessionFile,+ child: input.sessionFile,+ depth: input.rlmDepth,+ name: input.sessionName,+ });+ }return this.appendRlmSubagentRegistryEntry(parentState, {type: "rlm_subagent",childId: input.childId,@@ -952,11 +1017,22 @@ export class AgentDaemon {});}- private async recordRlmSubagentDeletion(parentState: ActiveSessionState, childId: string): Promise<void> {+ private async recordRlmSubagentDeletion(+ parentState: ActiveSessionState,+ childId: string,+ reason: RlmLedgerDeleteReason = "user",+ ): Promise<void> {const latest = (await this.readLatestRlmSubagentRegistry(parentState, true)).find((entry) => entry.childId === childId,);- if (!latest || latest.status === "deleted") {+ if (!latest) {+ 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);return;}if (@@ -968,6 +1044,30 @@ export class AgentDaemon {) {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)}`);+ }}private readLatestRlmSubagentRegistry(@@ -2244,7 +2344,7 @@ export class AgentDaemon {let deletionError: unknown;if (status === "cancelled") {try {- await this.recordRlmSubagentDeletion(parentState, options.id);+ await this.recordRlmSubagentDeletion(parentState, options.id, "revoked");} catch (error) {deletionError = error;}@@ -2411,6 +2511,10 @@ export class AgentDaemon {options.onSessionPublished?.(runtime.session);},);+ // 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();return runtime;}@@ -3712,6 +3816,13 @@ export class AgentDaemon {true,);SessionManager.open(command.sessionPath).appendSessionInfo(name);+ await this.rlmSpawnLedger()+ .appendRenameByChildPath(command.sessionPath, name)+ .catch((error) => {+ this.log(+ `failed to append RLM ledger rename: ${error instanceof Error ? error.message : String(error)}`,+ );+ });},);}@@ -5153,6 +5264,7 @@ export class AgentDaemon {async () => {await this.assertStateSessionNameAvailable(state, normalizedName);state.runtime.session.setSessionName(normalizedName);+ await this.appendRlmLedgerRenameForState(state, normalizedName);},);}diff --git a/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts b/packages/coding-agent/src/modes/daemon/daemon-supervisor.tsindex 3069dd4af4..43d550fe98 100644--- a/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts+++ b/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts@@ -11,6 +11,7 @@ import {getCronJobsPath,getDaemonLogPath,getDaemonUpdateRestartManifestPath,+ getSessionsDir,VERSION,} from "../../config.js";import {@@ -118,6 +119,7 @@ import {SESSION_LEASES_ENABLED_ENV,} from "./daemon-worker-protocol.js";import { MutationDrainLatch } from "./mutation-drain-latch.js";+import { createRlmLedgerRegistrySeedSource, RlmSpawnLedger } from "./rlm-ledger.js";import { serializeSavedSessionInfo } from "./saved-session-info.js";import { SNAPSHOT_TARGET_CHUNK_BYTES, SnapshotTranscriptCache } from "./snapshot-transcript-cache.js";import { WorkerRecoveryJournal } from "./worker-recovery-journal.js";@@ -613,6 +615,7 @@ export class DaemonSupervisor {private readonly pendingSessionNames = new Set<string>();private readonly catalog: DaemonCatalogClient;private readonly settingsManager: SettingsManager;+ private rlmSpawnLedgerInstance?: RlmSpawnLedger;private idleEvictionTimer?: ReturnType<typeof setTimeout>;private idleEvictionSweep?: Promise<void>;private idleEvictionFence?: Promise<void>;@@ -1764,6 +1767,15 @@ export class DaemonSupervisor {await this.assertSupervisorSavedSessionNameAvailable(command.sessionPath, target.name);if (!command.activeSessionId) {await this.catalog.rename(command.sessionPath, command.name);+ // Third rename write point: an offline saved-session rename+ // changes the name the ledger carries for that child.+ await this.rlmSpawnLedger()+ .appendRenameByChildPath(command.sessionPath, target.name)+ .catch((error) => {+ this.log(+ `failed to append RLM ledger rename: ${error instanceof Error ? error.message : String(error)}`,+ );+ });return success(command.id, command.type);}const match = await this.findWorkerForClient(client, command.activeSessionId);@@ -2038,7 +2050,7 @@ export class DaemonSupervisor {}const opening = (async () => {if (!createCommand.name) return this.launchWorker(createCommand, undefined, ownerClientId);- const savedSiblings = createCommand.sessionPath ? await this.catalog.siblings(createCommand.sessionPath) : [];+ const savedSiblings = createCommand.sessionPath ? await this.rlmLedgerSiblings(createCommand.sessionPath) : [];const target = savedSiblings.find((session) => canonicalSessionPath(session.path) === canonicalSessionPath(createCommand.sessionPath!),);@@ -3052,6 +3064,34 @@ export class DaemonSupervisor {});}+ /**+ * Supervisor-side view of the spawn ledger for this supervisor's sessions+ * dir. Workers hold their own instances over the same file; every read+ * re-reads the file, so cross-process freshness is per-operation.+ */+ private rlmSpawnLedger(): RlmSpawnLedger {+ const agentDir = this.defaultSessionConfig.agentDir;+ if (!agentDir) {+ throw new Error("Daemon supervisor config is missing agentDir");+ }+ this.rlmSpawnLedgerInstance ??= new RlmSpawnLedger(+ agentDir,+ this.defaultSessionConfig.sessionDir ?? getSessionsDir(agentDir),+ createRlmLedgerRegistrySeedSource(),+ (message) => this.log(message),+ );+ return this.rlmSpawnLedgerInstance;+ }++ /**+ * Ledger-backed same-parent rows for name reservation and admission. Rows+ * carry ledger topology plus best-effort display fields; consumers here+ * only need id/path/name/depth/parent.+ */+ private rlmLedgerSiblings(sessionPath: string): Promise<SessionInfo[]> {+ return this.rlmSpawnLedger().siblings(sessionPath);+ }+private async savedSessionNameReservationInput(sessionPath: string,name: string,@@ -3061,7 +3101,7 @@ export class DaemonSupervisor {.flatMap((worker) => [...worker.summaries.values()]).find((summary) => summary.sessionFile && canonicalSessionPath(summary.sessionFile) === targetPath);if (active) return this.summaryNameReservationInput(active, name);- const siblings = await this.catalog.siblings(sessionPath);+ const siblings = await this.rlmLedgerSiblings(sessionPath);const saved = siblings.find((info) => canonicalSessionPath(info.path) === targetPath);if (!saved) throw new Error(`Session not found: ${sessionPath}`);return {@@ -3090,7 +3130,7 @@ export class DaemonSupervisor {.flatMap((worker) => [...worker.summaries.values()]).find((summary) => summary.sessionFile && canonicalSessionPath(summary.sessionFile) === targetPath);if (active) return this.assertSupervisorSessionNameAvailable(active, name);- const siblings = await this.catalog.siblings(sessionPath);+ const siblings = await this.rlmLedgerSiblings(sessionPath);const saved = siblings.find((info) => canonicalSessionPath(info.path) === targetPath);if (!saved) throw new Error(`Session not found: ${sessionPath}`);if (saved.parentSessionPath && (saved.rlmDepth ?? 0) > 0) {diff --git a/packages/coding-agent/src/modes/daemon/rlm-ledger.ts b/packages/coding-agent/src/modes/daemon/rlm-ledger.tsnew file mode 100644index 0000000000..4c52dd7c66--- /dev/null+++ b/packages/coding-agent/src/modes/daemon/rlm-ledger.ts@@ -0,0 +1,830 @@+import { createHash } from "node:crypto";+import {+ closeSync,+ existsSync,+ fstatSync,+ fsyncSync,+ ftruncateSync,+ linkSync,+ mkdirSync,+ openSync,+ readFileSync,+ readSync,+ realpathSync,+ renameSync,+ rmSync,+ statSync,+ writeSync,+} from "node:fs";+import { readdir, readFile, stat } from "node:fs/promises";+import { basename, dirname, join, resolve } from "node:path";+import { canonicalSessionPath } from "../../core/session-lease.js";+import { readSessionInfo, type SessionInfo } from "../../core/session-manager.js";+import { readFirstLineSync } from "../../utils/file-lines.js";++/**+ * Daemon-owned RLM spawn ledger.+ *+ * One append-only JSONL file per sessions dir, written by daemon processes at+ * the moments they admit a spawn, perform a rename, or record a deletion.+ * Family topology (parent/child edges, depths, names) is read back from this+ * file instead of being re-derived from writer-owned session headers,+ * registries, and bodies at read time.+ *+ * Multi-writer reality: the supervisor and each session worker hold their own+ * instance over the same file. Appends are single small O_APPEND writes (well+ * under PIPE_BUF-scale sizes), whose atomicity we rely on for interleaving;+ * reads re-read the whole file per operation, so cross-process staleness is+ * bounded to in-flight appends. In-process appends are serialized on an+ * internal queue.+ */++export const RLM_LEDGER_DIR = "rlm-ledger";++/** Bounded read: a ledger beyond these limits fails closed loudly. */+export const RLM_LEDGER_MAX_BYTES = 32 * 1024 * 1024;+export const RLM_LEDGER_MAX_RECORDS = 100_000;++export type RlmLedgerDeleteReason = "user" | "parent-teardown" | "revoked" | "gc";++interface RlmLedgerMetaRecord {+ v: 1;+ op: "meta";+ at: string;+ sessionsDir: string;+}++export interface RlmLedgerSpawnRecord {+ v: 1;+ op: "spawn";+ at: string;+ childId: string;+ parent: string;+ child: string;+ depth: number;+ name: string;+}++export interface RlmLedgerRenameRecord {+ v: 1;+ op: "rename";+ at: string;+ childId: string;+ child: string;+ name: string;+}++export interface RlmLedgerDeleteRecord {+ v: 1;+ op: "delete";+ at: string;+ childId: string;+ child: string;+ reason: RlmLedgerDeleteReason;+}++export type RlmLedgerRecord = RlmLedgerSpawnRecord | RlmLedgerRenameRecord | RlmLedgerDeleteRecord;++/** A live edge after replaying the ledger (last-writer-wins per childId+child). */+export interface RlmLedgerEdge {+ childId: string;+ parent: string;+ child: string;+ depth: number;+ name: string;+ deleted?: RlmLedgerDeleteReason;+}++/** Minimal registry-entry shape the seeder consumes (matches the daemon writer). */+export interface RlmLedgerSeedRegistryEntry {+ childId: string;+ sessionName: string;+ sessionFile: string;+ rlmDepth?: number;+ status: "running" | "completed" | "deleted";+}++export interface RlmLedgerSeedSource {+ /**+ * Tolerant last-writer-wins registry read for a parent session file, using+ * the daemon's existing registry conventions. Must never throw for a+ * missing registry; other failures may throw (seeding degrades to empty).+ */+ readRegistryForSessionFile(sessionFile: string): Promise<RlmLedgerSeedRegistryEntry[]>;+}++/**+ * Default seed source: derive the per-parent registry path from the session+ * file's header id (a bounded first-line read, no full transcript parse) and+ * read it with the same tolerant last-writer-wins semantics the daemon's+ * passive-hydration reader uses (malformed lines ignored, unknown fields+ * accepted, absent depths allowed).+ */+export function createRlmLedgerRegistrySeedSource(): RlmLedgerSeedSource {+ return {+ readRegistryForSessionFile: async (sessionFile) => {+ let headerId: string | undefined;+ try {+ const firstLine = readFirstLineSync(sessionFile);+ if (firstLine) {+ const header = JSON.parse(firstLine) as { id?: unknown };+ if (typeof header.id === "string") headerId = header.id;+ }+ } catch {+ return [];+ }+ if (!headerId) return [];+ const registryPath = join(dirname(dirname(sessionFile)), "session-artifacts", headerId, "rlm-subagents.jsonl");+ let contents: string;+ try {+ contents = await readFile(registryPath, "utf8");+ } catch {+ return [];+ }+ const latest = new Map<string, RlmLedgerSeedRegistryEntry>();+ for (const line of contents.split(/\r?\n/)) {+ const trimmed = line.trim();+ if (!trimmed) continue;+ try {+ const entry = JSON.parse(trimmed) as {+ type?: unknown;+ childId?: unknown;+ sessionName?: unknown;+ sessionFile?: unknown;+ rlmDepth?: unknown;+ status?: unknown;+ };+ if (+ entry.type !== "rlm_subagent" ||+ typeof entry.childId !== "string" ||+ typeof entry.sessionName !== "string" ||+ typeof entry.sessionFile !== "string" ||+ (entry.status !== "running" && entry.status !== "completed" && entry.status !== "deleted") ||+ (entry.rlmDepth !== undefined &&+ (!Number.isSafeInteger(entry.rlmDepth) || (entry.rlmDepth as number) < 0))+ ) {+ continue;+ }+ latest.set(entry.childId, {+ childId: entry.childId,+ sessionName: entry.sessionName,+ sessionFile: entry.sessionFile,+ ...(typeof entry.rlmDepth === "number" ? { rlmDepth: entry.rlmDepth } : {}),+ status: entry.status,+ });+ } catch {+ // Malformed registry history is ignored, matching the daemon reader.+ }+ }+ return [...latest.values()];+ },+ };+}++/** Canonicalize a directory: realpath when it exists, plain resolve otherwise. */+function canonicalizeDirPath(dir: string): string {+ const resolved = resolve(dir);+ try {+ return realpathSync(resolved);+ } catch {+ return resolved;+ }+}++export function rlmLedgerPath(agentDir: string, sessionsDir: string): string {+ const canonical = canonicalizeDirPath(sessionsDir);+ const hash = createHash("sha256").update(canonical).digest("hex").slice(0, 16);+ return join(agentDir, RLM_LEDGER_DIR, `${hash}.jsonl`);+}++function nowIso(): string {+ return new Date().toISOString();+}++function isDeleteReason(value: unknown): value is RlmLedgerDeleteReason {+ return value === "user" || value === "parent-teardown" || value === "revoked" || value === "gc";+}++/**+ * Parse one ledger line. Returns undefined for a well-formed v:1 record with+ * an unknown op (forward-compat: newer writers may add ops; readers skip+ * them). Any other violation throws. Version policy: v !== 1 fails loudly —+ * a future v2 must move to a new file/hash (or accept breaking old readers),+ * because silently skipping records a reader cannot understand would corrupt+ * topology.+ */+function parseLedgerLine(line: string, index: number): RlmLedgerRecord | RlmLedgerMetaRecord | undefined {+ let parsed: unknown;+ try {+ parsed = JSON.parse(line);+ } catch (error) {+ throw new Error(+ `Malformed RLM ledger line ${index + 1}: ${error instanceof Error ? error.message : String(error)}`,+ );+ }+ const record = parsed as {+ v?: unknown;+ op?: unknown;+ at?: unknown;+ sessionsDir?: unknown;+ childId?: unknown;+ parent?: unknown;+ child?: unknown;+ depth?: unknown;+ name?: unknown;+ reason?: unknown;+ };+ if (record.v !== 1 || typeof record.at !== "string") {+ throw new Error(`Malformed RLM ledger line ${index + 1}: missing v/at`);+ }+ switch (record.op) {+ case "meta":+ if (typeof record.sessionsDir !== "string") {+ throw new Error(`Malformed RLM ledger line ${index + 1}: meta without sessionsDir`);+ }+ return record as unknown as RlmLedgerMetaRecord;+ case "spawn":+ if (+ typeof record.childId !== "string" ||+ typeof record.parent !== "string" ||+ typeof record.child !== "string" ||+ typeof record.name !== "string" ||+ typeof record.depth !== "number" ||+ !Number.isSafeInteger(record.depth) ||+ record.depth < 1+ ) {+ throw new Error(`Malformed RLM ledger line ${index + 1}: invalid spawn record`);+ }+ return record as unknown as RlmLedgerSpawnRecord;+ case "rename":+ if (+ typeof record.childId !== "string" ||+ typeof record.child !== "string" ||+ typeof record.name !== "string"+ ) {+ throw new Error(`Malformed RLM ledger line ${index + 1}: invalid rename record`);+ }+ return record as unknown as RlmLedgerRenameRecord;+ case "delete":+ if (typeof record.childId !== "string" || typeof record.child !== "string" || !isDeleteReason(record.reason)) {+ throw new Error(`Malformed RLM ledger line ${index + 1}: invalid delete record`);+ }+ return record as unknown as RlmLedgerDeleteRecord;+ default:+ return undefined;+ }+}++function readAllSync(fd: number): Buffer {+ const size = fstatSync(fd).size;+ // Never allocate beyond the read bound: every full read of the ledger,+ // including the repair path, is bounded the same way replaySync is.+ if (size > RLM_LEDGER_MAX_BYTES) {+ throw new Error(`RLM ledger exceeds ${RLM_LEDGER_MAX_BYTES} bytes (${size}); refusing to read`);+ }+ const buffer = Buffer.alloc(size);+ let offset = 0;+ while (offset < size) {+ const bytesRead = readSync(fd, buffer, offset, size - offset, offset);+ if (bytesRead === 0) break;+ offset += bytesRead;+ }+ return buffer.subarray(0, offset);+}++function edgeKey(childId: string, child: string): string {+ return `${childId}\u0000${canonicalSessionPath(child)}`;+}++/**+ * Per-sessions-dir spawn ledger. All operations are serialized on an internal+ * queue; the first operation lazily seeds a missing ledger from the existing+ * per-parent registries (memoized; a seeding failure degrades to an empty+ * ledger and is never fail-closed).+ */+export class RlmSpawnLedger {+ private readonly path: string;+ private readonly canonicalSessionsDir: string;+ private queue: Promise<unknown> = Promise.resolve();+ private seedAttempted = false;++ constructor(+ agentDir: string,+ sessionsDir: string,+ private readonly seedSource?: RlmLedgerSeedSource,+ private readonly log: (message: string) => void = () => {},+ ) {+ this.canonicalSessionsDir = canonicalizeDirPath(sessionsDir);+ this.path = rlmLedgerPath(agentDir, sessionsDir);+ }++ get ledgerPath(): string {+ return this.path;+ }++ appendSpawn(input: { childId: string; parent: string; child: string; depth: number; name: string }): Promise<void> {+ return this.enqueue(() => this.appendSpawnUnlocked(input));+ }++ appendRename(input: { childId: string; child: string; name: string }): Promise<void> {+ return this.enqueue(() => {+ this.appendRecord({+ v: 1,+ op: "rename",+ at: nowIso(),+ childId: input.childId,+ child: canonicalSessionPath(input.child),+ name: input.name,+ });+ });+ }++ /** Rename by child session path alone (offline saved-session rename knows no childId). */+ appendRenameByChildPath(child: string, name: string): Promise<void> {+ return this.enqueue(() => {+ const target = canonicalSessionPath(child);+ for (const edge of this.replaySync().values()) {+ if (!edge.deleted && canonicalSessionPath(edge.child) === target) {+ this.appendRecord({ v: 1, op: "rename", at: nowIso(), childId: edge.childId, child: target, name });+ }+ }+ });+ }++ appendDelete(input: { childId: string; child: string; reason: RlmLedgerDeleteReason }): Promise<void> {+ return this.enqueue(() => {+ this.appendRecord({+ v: 1,+ op: "delete",+ at: nowIso(),+ childId: input.childId,+ child: canonicalSessionPath(input.child),+ reason: input.reason,+ });+ });+ }++ /** Resolves once every operation enqueued so far has completed (durably, for appends). */+ flush(): Promise<void> {+ 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));+ }++ /**+ * Family of every session rooted in this ledger's sessions dir: bounded+ * readdir of *.jsonl roots as depth-0 rows plus live ledger edges, both+ * reconciled by stat (a dead parent or child drops the edge). Depths are+ * verified parent+1 between ledger-known depths; a contradictory edge is+ * dropped and logged, never fails the whole family.+ */+ family(): Promise<SessionInfo[]> {+ return this.enqueue(() => this.familyUnlocked());+ }++ /** Same-parent rows for a child session path, including the child itself. */+ siblings(sessionPath: string): Promise<SessionInfo[]> {+ return this.enqueue(async () => {+ const target = canonicalSessionPath(sessionPath);+ const family = await this.familyUnlocked();+ const edges = [...this.replaySync().values()].filter((edge) => !edge.deleted);+ const parentByChild = new Map(+ edges.map((edge) => [canonicalSessionPath(edge.child), canonicalSessionPath(edge.parent)]),+ );+ const parent = parentByChild.get(target);+ if (parent !== undefined) {+ const rows = family.filter((row) => parentByChild.get(canonicalSessionPath(row.path)) === parent);+ // The target's edge can be reconciliation-dropped (parent file+ // gone) while its own file still exists: fall back to presenting+ // the survivor alone rather than an empty set the callers would+ // read as "session not found".+ if (!rows.some((row) => canonicalSessionPath(row.path) === target)) {+ try {+ if ((await stat(target)).isFile()) {+ return [await this.sessionRow(target, 0, undefined, undefined)];+ }+ } catch {+ // fall through to the (possibly empty) sibling rows+ }+ }+ return rows;+ }+ // Roots are siblings of the other roots. A session outside both the+ // ledger and the sessions dir is presented alone (matching the+ // registry-walking reader's behavior for parentless sessions).+ const roots = family.filter((row) => row.rlmDepth === 0);+ if (roots.some((row) => canonicalSessionPath(row.path) === target)) {+ return roots;+ }+ try {+ if (!(await stat(target)).isFile()) return [];+ } catch {+ return [];+ }+ return [await this.sessionRow(target, 0, undefined, undefined)];+ });+ }++ private enqueue<T>(fn: () => Promise<T> | T): Promise<T> {+ const next = this.queue.then(async () => {+ if (!this.seedAttempted) {+ this.seedAttempted = true;+ try {+ await this.seed();+ } catch (error) {+ this.log(`RLM ledger seeding failed: ${error instanceof Error ? error.message : String(error)}`);+ }+ }+ return fn();+ });+ this.queue = next.catch(() => undefined);+ return next;+ }++ private appendSpawnUnlocked(input: {+ childId: string;+ parent: string;+ child: string;+ depth: number;+ name: string;+ }): void {+ // Enforce the same invariants parseLedgerLine checks: never write a+ // record this reader would refuse to read back.+ if (!input.childId || !input.parent || !input.child || !Number.isSafeInteger(input.depth) || input.depth < 1) {+ throw new Error(+ `RLM ledger: invalid spawn for ${input.childId || "<missing childId>"} (depth ${input.depth})`,+ );+ }+ const childPath = canonicalSessionPath(input.child);+ // Advisory, per-process: catches double-admission mistakes inside this+ // daemon. It is NOT a global uniqueness guarantee — other processes+ // append to the same file between our read and write.+ for (const edge of this.replaySync().values()) {+ if (!edge.deleted && canonicalSessionPath(edge.child) === childPath && edge.childId !== input.childId) {+ throw new Error(`RLM ledger: duplicate child session path ${childPath} (already ${edge.childId})`);+ }+ }+ this.appendRecord({+ v: 1,+ op: "spawn",+ at: nowIso(),+ childId: input.childId,+ parent: canonicalSessionPath(input.parent),+ child: childPath,+ depth: input.depth,+ name: input.name,+ });+ }++ private async familyUnlocked(): Promise<SessionInfo[]> {+ const edges = [...this.replaySync().values()].filter((edge) => !edge.deleted);+ const byChild = new Map<string, RlmLedgerEdge>();+ for (const edge of edges) {+ byChild.set(canonicalSessionPath(edge.child), edge);+ }+ const statCache = new Map<string, boolean>();+ const exists = async (path: string): Promise<boolean> => {+ const cached = statCache.get(path);+ if (cached !== undefined) return cached;+ let ok = false;+ try {+ ok = (await stat(path)).isFile();+ } catch {+ ok = false;+ }+ statCache.set(path, ok);+ return ok;+ };+ let alive: RlmLedgerEdge[] = [];+ for (const edge of edges) {+ if ((await exists(canonicalSessionPath(edge.child))) && (await exists(canonicalSessionPath(edge.parent)))) {+ alive.push(edge);+ }+ }+ const rootPaths: string[] = [];+ let rootEntries: string[] = [];+ try {+ rootEntries = await readdir(this.canonicalSessionsDir);+ } catch {+ rootEntries = [];+ }+ for (const entry of rootEntries.filter((name) => name.endsWith(".jsonl")).sort()) {+ const path = canonicalSessionPath(join(this.canonicalSessionsDir, entry));+ // Ledger children that live directly in the sessions dir are not roots.+ if (byChild.has(path)) continue;+ rootPaths.push(path);+ }+ // Verify depth monotonicity between ledger-known depths only: a root's+ // presented depth of 0 is a display convention, not an assertion (a+ // nested daemon's roots legitimately carry env-derived depths > 0). A+ // contradictory edge is dropped and logged; one bad edge must not fail+ // the whole family.+ const depthByPath = new Map<string, number>();+ for (const edge of alive) {+ depthByPath.set(canonicalSessionPath(edge.child), edge.depth);+ }+ alive = alive.filter((edge) => {+ const parentDepth = depthByPath.get(canonicalSessionPath(edge.parent));+ if (parentDepth !== undefined && edge.depth !== parentDepth + 1) {+ this.log(+ `RLM ledger: dropped edge ${edge.childId} with contradictory depth (parent ${parentDepth}, child ${edge.depth})`,+ );+ return false;+ }+ return true;+ });+ const rows: SessionInfo[] = [];+ for (const rootPath of rootPaths) {+ rows.push(await this.sessionRow(rootPath, 0, undefined, undefined));+ }+ for (const edge of alive) {+ rows.push(+ await this.sessionRow(+ canonicalSessionPath(edge.child),+ edge.depth,+ canonicalSessionPath(edge.parent),+ edge.name,+ ),+ );+ }+ return rows;+ }++ private async sessionRow(+ path: string,+ depth: number,+ parentPath: string | undefined,+ name: string | undefined,+ ): Promise<SessionInfo> {+ // Display-grade fields are best-effort from the ordinary session-info+ // read; topology (path, depth, parent) comes EXCLUSIVELY from the+ // ledger: header-claimed parentSessionPath/rlmDepth (e.g. fork headers)+ // are stripped, never passed through. For roots the ledger carries no+ // name, so the name comes from this read — writer-owned display data,+ // not authority.+ const info = await readSessionInfo(path).catch(() => null);+ if (info) {+ const { parentSessionPath: _headerParent, rlmDepth: _headerDepth, ...display } = info;+ return {+ ...display,+ rlmDepth: depth,+ ...(parentPath ? { parentSessionPath: parentPath } : {}),+ ...(name ? { name } : {}),+ };+ }+ return {+ path,+ id: basename(path, ".jsonl"),+ cwd: "",+ ...(name ? { name } : {}),+ ...(parentPath ? { parentSessionPath: parentPath } : {}),+ rlmDepth: depth,+ created: new Date(0),+ modified: new Date(0),+ messageCount: 0,+ firstMessage: "",+ allMessagesText: "",+ };+ }++ private async seed(): Promise<void> {+ if (!this.seedSource || existsSync(this.path)) return;+ let rootEntries: string[] = [];+ try {+ rootEntries = await readdir(this.canonicalSessionsDir);+ } catch {+ return;+ }+ // Collect the complete seed first, then publish it atomically via a+ // temp file + rename: the ledger file only exists once seeding is+ // complete, so an interrupted seed leaves nothing and the next+ // construction re-seeds from scratch. A concurrent process appending+ // before the rename creates the real file on demand and thereby+ // suppresses this seed — the same behavior as any pre-existing ledger.+ const records: RlmLedgerSpawnRecord[] = [];+ const queue: Array<{ sessionFile: string; depth: number }> = rootEntries+ .filter((name) => name.endsWith(".jsonl"))+ .sort()+ .map((name) => ({ sessionFile: join(this.canonicalSessionsDir, name), depth: 0 }));+ const visited = new Set<string>(queue.map((item) => canonicalSessionPath(item.sessionFile)));+ while (queue.length > 0) {+ const { sessionFile, depth } = queue.shift()!;+ for (const entry of await this.seedSource.readRegistryForSessionFile(sessionFile)) {+ if (entry.status === "deleted") continue;+ const childPath = canonicalSessionPath(entry.sessionFile);+ if (visited.has(childPath)) continue;+ visited.add(childPath);+ // A registry depth < 1 (legacy 0-depth entries exist in real data)+ // would be unwritable under the spawn invariants; treat it as+ // absent and derive parent depth + 1 instead of skipping the edge.+ const registryDepth = entry.rlmDepth !== undefined && entry.rlmDepth >= 1 ? entry.rlmDepth : undefined;+ const childDepth = registryDepth ?? depth + 1;+ if (!entry.childId) {+ this.log("RLM ledger: skipped seeding a registry entry without a childId");+ continue;+ }+ records.push({+ v: 1,+ op: "spawn",+ at: nowIso(),+ childId: entry.childId,+ parent: canonicalSessionPath(sessionFile),+ child: childPath,+ depth: childDepth,+ name: entry.sessionName,+ });+ queue.push({ sessionFile: entry.sessionFile, depth: childDepth });+ }+ }+ if (records.length === 0) return;+ const meta: RlmLedgerMetaRecord = { v: 1, op: "meta", at: nowIso(), sessionsDir: this.canonicalSessionsDir };+ const payload = [meta, ...records].map((record) => `${JSON.stringify(record)}\n`).join("");+ // A seed beyond the read bounds would publish a ledger every replaySync+ // refuses to read — manufacturing the exact poisoned state the bounds+ // exist to prevent. Skip seeding entirely (flat families, the documented+ // degradation mode) rather than publishing partial topology: profiles+ // this large are pathological, and a truncated tree would be more+ // confusing than a flat one. Not thrown: a hard error here would stick+ // via seedAttempted and the next append would create an empty ledger.+ if (records.length + 1 > RLM_LEDGER_MAX_RECORDS || Buffer.byteLength(payload) > RLM_LEDGER_MAX_BYTES) {+ this.log(+ `RLM ledger: seed exceeds read bounds (${records.length} records, ${Buffer.byteLength(payload)} bytes); skipping seeding`,+ );+ return;+ }+ const dir = dirname(this.path);+ mkdirSync(dir, { recursive: true, mode: 0o700 });+ const tempPath = `${this.path}.seed-${process.pid}-${Date.now()}`;+ const handle = openSync(tempPath, "wx", 0o600);+ try {+ writeSync(handle, payload);+ fsyncSync(handle);+ } finally {+ closeSync(handle);+ }+ try {+ this.publishSeedFile(tempPath);+ } finally {+ rmSync(tempPath, { force: true });+ }+ }++ 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.+ 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);+ }+ }++ private appendRecord(record: RlmLedgerRecord): void {+ const dir = dirname(this.path);+ mkdirSync(dir, { recursive: true, mode: 0o700 });+ const isNew = !existsSync(this.path);+ if (!isNew) {+ // Repair a torn final line from a crashed writer before appending:+ // otherwise the next append would turn a tolerable torn tail into a+ // fail-closed interior line. The torn bytes were never readable data.+ this.truncateTornTailSync();+ }+ const handle = openSync(this.path, "a", 0o600);+ try {+ if (isNew) {+ const meta: RlmLedgerMetaRecord = {+ v: 1,+ op: "meta",+ at: nowIso(),+ sessionsDir: this.canonicalSessionsDir,+ };+ writeSync(handle, `${JSON.stringify(meta)}\n`);+ }+ writeSync(handle, `${JSON.stringify(record)}\n`);+ fsyncSync(handle);+ } finally {+ closeSync(handle);+ }+ }++ private truncateTornTailSync(): void {+ // Fail closed loudly at the read bound BEFORE the swallowing repair+ // try-block: an oversized ledger must never trigger a file-sized+ // allocation, and the error must not be silenced as a repair failure.+ let size: number;+ try {+ size = statSync(this.path).size;+ } catch {+ return;+ }+ if (size > RLM_LEDGER_MAX_BYTES) {+ throw new Error(`RLM ledger ${this.path} exceeds ${RLM_LEDGER_MAX_BYTES} bytes (${size}); refusing to read`);+ }+ // All offsets are BYTE offsets on raw buffers: string indices diverge+ // from byte offsets as soon as any record carries multi-byte UTF-8+ // (session names do, in real data), and ftruncate takes bytes.+ try {+ const fd = openSync(this.path, "r+");+ try {+ const first = readAllSync(fd);+ if (first.length === 0 || first[first.length - 1] === 0x0a) return;+ const lastNewline = first.lastIndexOf(0x0a);+ // Cheap cross-process hardening: only truncate when the bytes are+ // stable across two reads and the size has not moved under us+ // (same fd for stat and truncate). A racing append between this+ // check and the ftruncate remains possible — same trust bucket as+ // the documented O_APPEND small-write atomicity assumption.+ const second = readAllSync(fd);+ if (second.length !== first.length || !second.equals(first)) return;+ if (fstatSync(fd).size !== first.length) return;+ ftruncateSync(fd, lastNewline + 1);+ this.log(`RLM ledger: truncated torn final line (${first.length - lastNewline - 1} bytes)`);+ } finally {+ closeSync(fd);+ }+ } catch {+ // Leave the tail for the reader's torn-line tolerance.+ }+ }++ private replaySync(): Map<string, RlmLedgerEdge> {+ const edges = new Map<string, RlmLedgerEdge>();+ if (!existsSync(this.path)) return edges;+ const size = statSync(this.path).size;+ if (size > RLM_LEDGER_MAX_BYTES) {+ throw new Error(`RLM ledger ${this.path} exceeds ${RLM_LEDGER_MAX_BYTES} bytes (${size}); refusing to read`);+ }+ const contents = readFileSync(this.path, "utf8");+ const endsWithNewline = contents.endsWith("\n");+ const rawLines = contents.split("\n");+ let recordCount = 0;+ for (let index = 0; index < rawLines.length; index++) {+ const line = rawLines[index].trim();+ if (!line) continue;+ if (++recordCount > RLM_LEDGER_MAX_RECORDS) {+ throw new Error(`RLM ledger ${this.path} exceeds ${RLM_LEDGER_MAX_RECORDS} records; refusing to read`);+ }+ let record: RlmLedgerRecord | RlmLedgerMetaRecord | undefined;+ try {+ record = parseLedgerLine(line, index);+ } catch (error) {+ // Exactly one unparseable FINAL line without a trailing newline is+ // an in-progress or crashed append: log and ignore it. Interior+ // malformed lines stay fail-closed.+ if (index === rawLines.length - 1 && !endsWithNewline) {+ this.log(+ `RLM ledger: ignored torn final line: ${error instanceof Error ? error.message : String(error)}`,+ );+ continue;+ }+ throw error;+ }+ if (record === undefined) {+ this.log(`RLM ledger: skipped record with unknown op on line ${index + 1}`);+ continue;+ }+ if (record.op === "meta") continue;+ const key = edgeKey(record.childId, record.child);+ switch (record.op) {+ case "spawn":+ edges.set(key, {+ childId: record.childId,+ parent: record.parent,+ child: record.child,+ depth: record.depth,+ name: record.name,+ });+ break;+ case "rename": {+ const existing = edges.get(key);+ if (existing) existing.name = record.name;+ break;+ }+ case "delete": {+ const existing = edges.get(key);+ if (existing) existing.deleted = record.reason;+ break;+ }+ }+ }+ return edges;+ }+}diff --git a/packages/coding-agent/test/daemon-mode.test.ts b/packages/coding-agent/test/daemon-mode.test.tsindex fe278efdbd..cb4b03a5c5 100644--- a/packages/coding-agent/test/daemon-mode.test.ts+++ b/packages/coding-agent/test/daemon-mode.test.ts@@ -696,7 +696,7 @@ describe("daemon mode helpers", () => {{ id: "child-1" } as CreateRlmSubagentRuntimeOptions,"cancelled",);- expect(recordDeletion).toHaveBeenCalledWith(parentState, "child-1");+ expect(recordDeletion).toHaveBeenCalledWith(parentState, "child-1", "revoked");expect(recordDeletion.mock.invocationCallOrder[0]).toBeLessThan(closeSession.mock.invocationCallOrder[1]!);expect(closeSession).toHaveBeenLastCalledWith(childState, "killed");expect(internals.sessions.has(childState.activeSessionId)).toBe(false);diff --git a/packages/coding-agent/test/daemon-supervisor-lazy-subagents.test.ts b/packages/coding-agent/test/daemon-supervisor-lazy-subagents.test.tsindex 497c7e0170..7ca17f5c4d 100644--- a/packages/coding-agent/test/daemon-supervisor-lazy-subagents.test.ts+++ b/packages/coding-agent/test/daemon-supervisor-lazy-subagents.test.ts@@ -240,8 +240,8 @@ describe("daemon supervisor passive subagent topology", () => {descriptorDir: join(directory, "workers"),}) as unknown as SupervisorInternals;Object.assign(supervisor, {+ rlmLedgerSiblings: vi.fn(async () => [target]),catalog: {- siblings: vi.fn(async () => [target]),list: vi.fn(async () => [target, duplicate]),},});@@ -564,8 +564,9 @@ describe("daemon supervisor passive subagent topology", () => {descriptorDir: join(directory, "workers"),}) as unknown as SupervisorInternals;Object.assign(supervisor, {+ rlmLedgerSiblings: vi.fn(async () => saved),+ rlmSpawnLedger: vi.fn(() => ({ appendRenameByChildPath: vi.fn(async () => {}) })),catalog: {- siblings: vi.fn(async () => saved),rename,},});@@ -620,9 +621,9 @@ describe("daemon supervisor passive subagent topology", () => {descriptorDir: join(directory, "workers"),}) as unknown as SupervisorInternals;Object.assign(supervisor, {+ rlmLedgerSiblings: vi.fn(async (path: string) => [path === firstChild.path ? firstChild : secondChild]),catalog: {resolve: vi.fn(async (path: string) => path),- siblings: vi.fn(async (path: string) => [path === firstChild.path ? firstChild : secondChild]),},launchWorker,});diff --git a/packages/coding-agent/test/rlm-ledger.test.ts b/packages/coding-agent/test/rlm-ledger.test.tsnew file mode 100644index 0000000000..bf3fc38000--- /dev/null+++ b/packages/coding-agent/test/rlm-ledger.test.ts@@ -0,0 +1,1050 @@+import {+ existsSync,+ mkdirSync,+ mkdtempSync,+ readFileSync,+ realpathSync,+ rmSync,+ statSync,+ writeFileSync,+} from "node:fs";+import { tmpdir } from "node:os";++const linkFailure = vi.hoisted(() => ({ code: undefined as string | undefined }));+vi.mock("node:fs", async (importOriginal) => {+ const actual = await importOriginal<typeof import("node:fs")>();+ return {+ ...actual,+ linkSync: (+ existingPath: Parameters<typeof actual.linkSync>[0],+ newPath: Parameters<typeof actual.linkSync>[1],+ ) => {+ if (linkFailure.code) {+ const error = new Error(`simulated link failure ${linkFailure.code}`) as NodeJS.ErrnoException;+ error.code = linkFailure.code;+ throw error;+ }+ return actual.linkSync(existingPath, newPath);+ },+ };+});++import { dirname, join } from "node:path";+import type { Api, Model } from "@earendil-works/pi-ai";+import { describe, expect, it, vi } from "vitest";+import type { CreateAgentSessionRuntimeFactory } from "../src/core/agent-session-runtime.js";+import type { CreateRlmSubagentRuntimeOptions, SubagentRuntimeHost } from "../src/core/rlm-runtime.js";+import { canonicalSessionPath } from "../src/core/session-lease.js";+import { SessionManager } from "../src/core/session-manager.js";+import type { ActiveSessionState } from "../src/modes/daemon/active-session-state.js";+import { AgentDaemon } from "../src/modes/daemon/daemon-mode.js";+import type { DaemonCommand } from "../src/modes/daemon/daemon-protocol.js";+import { DaemonSupervisor } from "../src/modes/daemon/daemon-supervisor.js";+import {+ RLM_LEDGER_MAX_BYTES,+ RLM_LEDGER_MAX_RECORDS,+ type RlmLedgerDeleteReason,+ RlmSpawnLedger,+ rlmLedgerPath,+} from "../src/modes/daemon/rlm-ledger.js";++function makeRoots(root: string) {+ const sessionsDir = join(root, "sessions");+ const parent = SessionManager.create(root, sessionsDir);+ parent.newSession();+ parent.appendSessionInfo("parent");+ parent.flushNow();+ const parentFile = parent.getSessionFile();+ if (!parentFile) throw new Error("Missing parent session file");+ return { sessionsDir, parent, parentFile };+}++function makeChildSession(root: string, dir: string, parentFile: string, depth: number, name: string) {+ const manager = SessionManager.create(root, dir);+ manager.newSession({ parentSession: parentFile, rlmDepth: depth });+ manager.appendSessionInfo(name);+ manager.flushNow();+ const file = manager.getSessionFile();+ if (!file) throw new Error("Missing child session file");+ return { manager, file };+}++describe("rlm spawn ledger", () => {+ it("replays spawn, rename, and delete records last-writer-wins", async () => {+ const root = mkdtempSync(join(tmpdir(), "prime-rlm-ledger-"));+ try {+ const { sessionsDir, parentFile } = makeRoots(root);+ const ledger = new RlmSpawnLedger(root, sessionsDir);+ await ledger.appendSpawn({+ childId: "sub-11111111",+ parent: parentFile,+ child: join(root, "a.jsonl"),+ depth: 1,+ name: "worker-a",+ });+ await ledger.appendSpawn({+ childId: "sub-22222222",+ parent: parentFile,+ child: join(root, "b.jsonl"),+ depth: 1,+ name: "worker-b",+ });+ await ledger.appendRename({ childId: "sub-22222222", child: join(root, "b.jsonl"), name: "renamed-b" });+ await ledger.appendDelete({ childId: "sub-11111111", child: join(root, "a.jsonl"), reason: "revoked" });++ const edges = await ledger.edges();+ expect(edges).toEqual([expect.objectContaining({ childId: "sub-22222222", name: "renamed-b", depth: 1 })]);+ const lines = readFileSync(ledger.ledgerPath, "utf8").trim().split("\n");+ expect(JSON.parse(lines[0])).toMatchObject({ v: 1, op: "meta", sessionsDir: realpathSync(sessionsDir) });+ expect(JSON.parse(lines[4])).toMatchObject({ v: 1, op: "delete", reason: "revoked" });+ expect(statSync(ledger.ledgerPath).mode & 0o777).toBe(0o600);+ expect(statSync(dirname(ledger.ledgerPath)).mode & 0o777).toBe(0o700);+ } finally {+ rmSync(root, { recursive: true, force: true });+ }+ });++ it("rejects a duplicate canonical child path at append", async () => {+ const root = mkdtempSync(join(tmpdir(), "prime-rlm-ledger-dup-"));+ try {+ const { sessionsDir, parentFile } = makeRoots(root);+ const ledger = new RlmSpawnLedger(root, sessionsDir);+ const child = join(root, "child.jsonl");+ await ledger.appendSpawn({ childId: "sub-11111111", parent: parentFile, child, depth: 1, name: "a" });+ await expect(+ ledger.appendSpawn({ childId: "sub-22222222", parent: parentFile, child, depth: 1, name: "b" }),+ ).rejects.toThrow("duplicate child session path");+ // Same childId re-recording the same path is an update, not a duplicate.+ await ledger.appendSpawn({ childId: "sub-11111111", parent: parentFile, child, depth: 1, name: "a2" });+ // A deleted edge releases its path.+ await ledger.appendDelete({ childId: "sub-11111111", child, reason: "user" });+ await ledger.appendSpawn({ childId: "sub-33333333", parent: parentFile, child, depth: 1, name: "c" });+ expect(await ledger.edges()).toEqual([expect.objectContaining({ childId: "sub-33333333", name: "c" })]);+ } finally {+ rmSync(root, { recursive: true, force: true });+ }+ });++ it("fails closed on a malformed ledger line", async () => {+ const root = mkdtempSync(join(tmpdir(), "prime-rlm-ledger-malformed-"));+ try {+ const { sessionsDir, parentFile } = makeRoots(root);+ const ledger = new RlmSpawnLedger(root, sessionsDir);+ await ledger.appendSpawn({+ childId: "sub-11111111",+ parent: parentFile,+ child: join(root, "a.jsonl"),+ depth: 1,+ name: "a",+ });+ writeFileSync(ledger.ledgerPath, `${readFileSync(ledger.ledgerPath, "utf8")}not json\n`);+ await expect(ledger.edges()).rejects.toThrow("Malformed RLM ledger line");+ const fresh = new RlmSpawnLedger(root, sessionsDir);+ writeFileSync(+ fresh.ledgerPath,+ `${JSON.stringify({ v: 1, op: "spawn", at: "x", childId: "sub-1", child: "/c", depth: 0, name: "n", parent: "/p" })}\n`,+ );+ await expect(fresh.edges()).rejects.toThrow("invalid spawn record");+ } finally {+ rmSync(root, { recursive: true, force: true });+ }+ });++ it("tolerates one torn final line without a trailing newline, but not mid-file", async () => {+ const root = mkdtempSync(join(tmpdir(), "prime-rlm-ledger-torn-"));+ try {+ const { sessionsDir, parentFile } = makeRoots(root);+ const ledger = new RlmSpawnLedger(root, sessionsDir);+ await ledger.appendSpawn({+ childId: "sub-11111111",+ parent: parentFile,+ child: join(root, "a.jsonl"),+ depth: 1,+ name: "a",+ });+ const intact = readFileSync(ledger.ledgerPath, "utf8");+ // A crashed writer's torn final append (no trailing newline) is+ // in-progress data: ignored with a log, not fail-closed.+ writeFileSync(ledger.ledgerPath, `${intact}{"v":1,"op":"spawn","at":"2026-`);+ const logged: string[] = [];+ const torn = new RlmSpawnLedger(root, sessionsDir, undefined, (message) => logged.push(message));+ await expect(torn.edges()).resolves.toEqual([expect.objectContaining({ childId: "sub-11111111" })]);+ expect(logged.some((message) => message.includes("torn final line"))).toBe(true);+ // The next append repairs the torn tail with a newline first.+ await torn.appendSpawn({+ childId: "sub-22222222",+ parent: parentFile,+ child: join(root, "b.jsonl"),+ depth: 1,+ name: "b",+ });+ await expect(new RlmSpawnLedger(root, sessionsDir).edges()).resolves.toHaveLength(2);+ // The same content mid-file (trailing newline present) stays fail-closed.+ writeFileSync(ledger.ledgerPath, `${intact}{"v":1,"op":"spawn","at":"2026-\n`);+ await expect(new RlmSpawnLedger(root, sessionsDir).edges()).rejects.toThrow("Malformed RLM ledger line");+ } finally {+ rmSync(root, { recursive: true, force: true });+ }+ });++ it("repairs a torn tail by byte offset, preserving preceding multi-byte UTF-8 records", async () => {+ const root = mkdtempSync(join(tmpdir(), "prime-rlm-ledger-utf8-torn-"));+ try {+ const { sessionsDir, parentFile } = makeRoots(root);+ const ledger = new RlmSpawnLedger(root, sessionsDir);+ // Multi-byte UTF-8 in the name makes string indices diverge from+ // byte offsets; the truncate must not cut into this record.+ await ledger.appendSpawn({+ childId: "sub-11111111",+ parent: parentFile,+ child: join(root, "a.jsonl"),+ depth: 1,+ name: "wörker-💥-ümlaut",+ });+ writeFileSync(ledger.ledgerPath, `${readFileSync(ledger.ledgerPath, "utf8")}{"v":1,"op":"spawn","torn`);+ const repairing = new RlmSpawnLedger(root, sessionsDir);+ await repairing.appendSpawn({+ childId: "sub-22222222",+ parent: parentFile,+ child: join(root, "b.jsonl"),+ depth: 1,+ name: "second",+ });+ await expect(new RlmSpawnLedger(root, sessionsDir).edges()).resolves.toEqual([+ expect.objectContaining({ childId: "sub-11111111", name: "wörker-💥-ümlaut" }),+ expect.objectContaining({ childId: "sub-22222222", name: "second" }),+ ]);+ } finally {+ rmSync(root, { recursive: true, force: true });+ }+ });++ it("skips v1 records with unknown ops instead of failing the whole ledger", async () => {+ const root = mkdtempSync(join(tmpdir(), "prime-rlm-ledger-forward-"));+ try {+ const { sessionsDir, parentFile } = makeRoots(root);+ const ledger = new RlmSpawnLedger(root, sessionsDir);+ await ledger.appendSpawn({+ childId: "sub-11111111",+ parent: parentFile,+ child: join(root, "a.jsonl"),+ depth: 1,+ name: "a",+ });+ writeFileSync(+ ledger.ledgerPath,+ `${readFileSync(ledger.ledgerPath, "utf8")}${JSON.stringify({ v: 1, op: "future-op", at: "2026-01-01T00:00:00.000Z" })}\n`,+ );+ const logged: string[] = [];+ const reader = new RlmSpawnLedger(root, sessionsDir, undefined, (message) => logged.push(message));+ await expect(reader.edges()).resolves.toEqual([expect.objectContaining({ childId: "sub-11111111" })]);+ expect(logged.some((message) => message.includes("unknown op"))).toBe(true);+ // A future major version still fails loudly.+ writeFileSync(+ ledger.ledgerPath,+ `${readFileSync(ledger.ledgerPath, "utf8")}${JSON.stringify({ v: 2, op: "spawn", at: "2026-01-01T00:00:00.000Z" })}\n`,+ );+ await expect(new RlmSpawnLedger(root, sessionsDir).edges()).rejects.toThrow("missing v/at");+ } finally {+ rmSync(root, { recursive: true, force: true });+ }+ });++ it("fails closed on byte and record bounds", async () => {+ const root = mkdtempSync(join(tmpdir(), "prime-rlm-ledger-bounds-"));+ try {+ const { sessionsDir } = makeRoots(root);+ const oversized = new RlmSpawnLedger(root, sessionsDir);+ mkdirSync(dirname(oversized.ledgerPath), { recursive: true });+ writeFileSync(oversized.ledgerPath, Buffer.alloc(RLM_LEDGER_MAX_BYTES + 1, "\n"));+ await expect(oversized.edges()).rejects.toThrow("bytes");++ // The torn-tail repair path must hit the same bound before any+ // file-sized allocation, not just replaySync.+ await expect(+ new RlmSpawnLedger(root, sessionsDir).appendRename({ childId: "sub-1", child: "/c", name: "n" }),+ ).rejects.toThrow("bytes");++ const record = `${JSON.stringify({ v: 1, op: "rename", at: "x", childId: "sub-1", child: "/c", name: "n" })}\n`;+ writeFileSync(oversized.ledgerPath, record.repeat(RLM_LEDGER_MAX_RECORDS + 1));+ await expect(new RlmSpawnLedger(root, sessionsDir).edges()).rejects.toThrow("records");+ } finally {+ rmSync(root, { recursive: true, force: true });+ }+ });++ it("builds families from roots plus live edges and drops dead entries", async () => {+ const root = mkdtempSync(join(tmpdir(), "prime-rlm-ledger-family-"));+ try {+ const { sessionsDir, parent, parentFile } = makeRoots(root);+ const other = SessionManager.create(root, sessionsDir);+ other.newSession();+ other.appendSessionInfo("other-root");+ other.flushNow();+ const artifactDir = parent.getSessionArtifactDir();+ if (!artifactDir) throw new Error("Missing artifact dir");+ const child = makeChildSession(root, join(artifactDir, "sub-11111111"), parentFile, 1, "worker");+ const grandchild = makeChildSession(root, join(artifactDir, "sub-22222222"), child.file, 2, "nested");++ const ledger = new RlmSpawnLedger(root, sessionsDir);+ await ledger.appendSpawn({+ childId: "sub-11111111",+ parent: parentFile,+ child: child.file,+ depth: 1,+ name: "worker",+ });+ await ledger.appendSpawn({+ childId: "sub-22222222",+ parent: child.file,+ child: grandchild.file,+ depth: 2,+ name: "nested",+ });+ await ledger.appendSpawn({+ childId: "sub-33333333",+ parent: parentFile,+ child: join(artifactDir, "sub-33333333", "gone.jsonl"),+ depth: 1,+ name: "vanished",+ });+ await ledger.appendRename({ childId: "sub-11111111", child: child.file, name: "renamed-worker" });++ const family = await ledger.family();+ expect(family.map((row) => [row.name, row.rlmDepth])).toEqual([+ ["parent", 0],+ ["other-root", 0],+ ["renamed-worker", 1],+ ["nested", 2],+ ]);+ const childRow = family.find((row) => row.name === "renamed-worker");+ expect(childRow?.parentSessionPath).toBe(canonicalSessionPath(parentFile));+ expect(family.some((row) => row.name === "vanished")).toBe(false);++ const siblings = await ledger.siblings(child.file);+ expect(siblings.map((row) => row.name)).toEqual(["renamed-worker"]);+ const rootSiblings = await ledger.siblings(parentFile);+ expect(rootSiblings.map((row) => row.name)).toEqual(["parent", "other-root"]);+ } finally {+ rmSync(root, { recursive: true, force: true });+ }+ });++ it("drops a depth-contradictory edge without failing the rest of the family", async () => {+ const root = mkdtempSync(join(tmpdir(), "prime-rlm-ledger-depth-"));+ try {+ const { sessionsDir, parent, parentFile } = makeRoots(root);+ const artifactDir = parent.getSessionArtifactDir();+ if (!artifactDir) throw new Error("Missing artifact dir");+ const child = makeChildSession(root, join(artifactDir, "sub-11111111"), parentFile, 1, "worker");+ const grandchild = makeChildSession(root, join(artifactDir, "sub-22222222"), child.file, 2, "nested");+ const logged: string[] = [];+ const ledger = new RlmSpawnLedger(root, sessionsDir, undefined, (message) => logged.push(message));+ await ledger.appendSpawn({+ childId: "sub-11111111",+ parent: parentFile,+ child: child.file,+ depth: 1,+ name: "worker",+ });+ await ledger.appendSpawn({+ childId: "sub-22222222",+ parent: child.file,+ child: grandchild.file,+ depth: 3,+ name: "nested",+ });+ const family = await ledger.family();+ expect(family.map((row) => row.name)).toEqual(["parent", "worker"]);+ expect(logged.some((message) => message.includes("contradictory depth"))).toBe(true);+ } finally {+ rmSync(root, { recursive: true, force: true });+ }+ });++ it("never passes header-claimed topology through for roots (fork headers)", async () => {+ const root = mkdtempSync(join(tmpdir(), "prime-rlm-ledger-fork-root-"));+ try {+ const { sessionsDir, parentFile } = makeRoots(root);+ // A fork: header carries parentSession, so readSessionInfo reports a+ // parentSessionPath — writer-owned topology the ledger must strip.+ const fork = SessionManager.forkFrom(parentFile, root, sessionsDir);+ fork.appendSessionInfo("forked-root");+ fork.flushNow();+ const forkFile = fork.getSessionFile();+ if (!forkFile) throw new Error("Missing fork session file");+ const ledger = new RlmSpawnLedger(root, sessionsDir);+ const family = await ledger.family();+ const forkRow = family.find((row) => row.name === "forked-root");+ expect(forkRow).toBeDefined();+ expect(forkRow?.rlmDepth).toBe(0);+ expect(forkRow?.parentSessionPath).toBeUndefined();+ } finally {+ rmSync(root, { recursive: true, force: true });+ }+ });++ it("returns the surviving child alone when its parent file is gone", async () => {+ const root = mkdtempSync(join(tmpdir(), "prime-rlm-ledger-orphan-"));+ try {+ const { sessionsDir, parent, parentFile } = makeRoots(root);+ const artifactDir = parent.getSessionArtifactDir();+ if (!artifactDir) throw new Error("Missing artifact dir");+ const child = makeChildSession(root, join(artifactDir, "sub-11111111"), parentFile, 1, "survivor");+ const ledger = new RlmSpawnLedger(root, sessionsDir);+ await ledger.appendSpawn({+ childId: "sub-11111111",+ parent: parentFile,+ child: child.file,+ depth: 1,+ name: "survivor",+ });+ rmSync(parentFile);++ // The edge is reconciliation-dropped, but the child file exists: it+ // must come back as a lone root-shaped row, not vanish entirely.+ const siblings = await ledger.siblings(child.file);+ expect(siblings).toEqual([+ expect.objectContaining({ path: canonicalSessionPath(child.file), name: "survivor", rlmDepth: 0 }),+ ]);+ } finally {+ rmSync(root, { recursive: true, force: true });+ }+ });++ it("presents roots at their own depth without asserting depth-0 against nested-daemon edges", async () => {+ // A nested daemon's sessions dir has roots that legitimately carry+ // env-derived depths > 0: an edge at depth 3 whose parent is a root must+ // not be dropped against an assumed root depth of 0.+ const root = mkdtempSync(join(tmpdir(), "prime-rlm-ledger-nested-root-"));+ try {+ const { sessionsDir, parent, parentFile } = makeRoots(root);+ const artifactDir = parent.getSessionArtifactDir();+ if (!artifactDir) throw new Error("Missing artifact dir");+ const child = makeChildSession(root, join(artifactDir, "sub-11111111"), parentFile, 3, "deep-worker");+ const ledger = new RlmSpawnLedger(root, sessionsDir);+ await ledger.appendSpawn({+ childId: "sub-11111111",+ parent: parentFile,+ child: child.file,+ depth: 3,+ name: "deep-worker",+ });+ const family = await ledger.family();+ expect(family.map((row) => [row.name, row.rlmDepth])).toEqual([+ ["parent", 0],+ ["deep-worker", 3],+ ]);+ } finally {+ rmSync(root, { recursive: true, force: true });+ }+ });+});++function makeDaemonFixture(tempDir: string) {+ const sessionsDir = join(tempDir, "sessions");+ const createRuntime = vi.fn(async (options: Parameters<CreateAgentSessionRuntimeFactory>[0]) => ({+ session: makeRuntimeSession(options.sessionManager),+ extensionsResult: { extensions: [], errors: [], runtime: {} } as unknown as Awaited<+ ReturnType<CreateAgentSessionRuntimeFactory>+ >["extensionsResult"],+ services: { cwd: options.cwd, agentDir: options.agentDir } as Awaited<+ ReturnType<CreateAgentSessionRuntimeFactory>+ >["services"],+ diagnostics: [],+ }));+ const daemon = new AgentDaemon(join(tempDir, "daemon.sock"), {+ defaultSessionConfig: { agentDir: tempDir, cwd: tempDir, sessionDir: sessionsDir },+ createRuntime,+ });+ const internals = daemon as unknown as {+ sessions: Map<string, ActiveSessionState>;+ createRuntime(command: Extract<DaemonCommand, { type: "create" }>): Promise<ActiveSessionState>;+ createRlmSubagentRuntime(+ parentState: ActiveSessionState,+ options: CreateRlmSubagentRuntimeOptions,+ ): Promise<ActiveSessionState["runtime"]>;+ createSubagentRuntimeHost(parentState: ActiveSessionState): SubagentRuntimeHost;+ recordRlmSubagentDeletion(+ parentState: ActiveSessionState,+ childId: string,+ reason?: RlmLedgerDeleteReason,+ ): Promise<void>;+ setStateSessionName(state: ActiveSessionState, name: string): Promise<void>;+ rlmSpawnLedger(): RlmSpawnLedger;+ };+ return { daemon, internals, sessionsDir };+}++function makeRuntimeSession(+ sessionManager: Parameters<CreateAgentSessionRuntimeFactory>[0]["sessionManager"],+): Awaited<ReturnType<CreateAgentSessionRuntimeFactory>>["session"] {+ return {+ sessionManager,+ messages: [],+ extensionRunner: { hasHandlers: vi.fn(() => false), emit: vi.fn(async () => {}) },+ sessionFile: sessionManager.getSessionFile(),+ sessionId: sessionManager.getSessionId(),+ get sessionName() {+ return sessionManager.getSessionName();+ },+ rlmDepth: sessionManager.getHeader()?.rlmDepth ?? 0,+ setSubagentRuntimeHost: vi.fn(),+ getRlmChildRunStatus: vi.fn(() => "running"),+ registerRlmChildSession: vi.fn(() => true),+ releaseRlmChildSession: vi.fn(() => vi.fn()),+ subscribe: vi.fn(() => vi.fn()),+ bindExtensions: vi.fn(async () => {}),+ setExecEnvProvider: vi.fn(),+ getAvailableThinkingLevels: vi.fn(() => []),+ scopedModels: [],+ getActiveToolNames: vi.fn(() => []),+ getContextUsage: vi.fn(() => undefined),+ setSessionName: vi.fn((name: string) => sessionManager.appendSessionInfo(name)),+ dispose: vi.fn(),+ disposeAsync: vi.fn(async () => {}),+ abort: vi.fn(async () => {}),+ } as unknown as Awaited<ReturnType<CreateAgentSessionRuntimeFactory>>["session"];+}++function subagentRuntimeOptions(+ parentState: ActiveSessionState,+ overrides: Partial<CreateRlmSubagentRuntimeOptions> & Pick<CreateRlmSubagentRuntimeOptions, "id" | "sessionDir">,+): CreateRlmSubagentRuntimeOptions {+ return {+ parentSession: parentState.runtime.session,+ prompt: "do the work",+ sessionName: overrides.id,+ model: { provider: "test", id: "model" } as Model<Api>,+ thinkingLevel: "off",+ serviceTier: null,+ scopedModels: [],+ activeToolNames: [],+ customTools: [],+ includeGoals: false,+ includeCompactSkill: false,+ rlmDepth: 1,+ rlmMaxDepth: 4,+ rlmParentNodeId: overrides.id,+ ...overrides,+ };+}++describe("rlm spawn ledger daemon wiring", () => {+ it("appends spawn at admission, rename at the rename write point, and delete with a reason", async () => {+ const tempDir = mkdtempSync(join(tmpdir(), "prime-rlm-ledger-wiring-"));+ 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 childDir = join(parentManager.getSessionArtifactDir()!, "sub-1234abcd");+ const childRuntime = await internals.createRlmSubagentRuntime(+ parentState,+ subagentRuntimeOptions(parentState, {+ id: "sub-1234abcd",+ sessionName: "spawned-worker",+ sessionDir: childDir,+ }),+ );+ const childState = [...internals.sessions.values()].find(+ (state) => state.runtime.session === childRuntime.session,+ );+ if (!childState?.runtime.session.sessionFile) throw new Error("Missing child state");++ const ledger = internals.rlmSpawnLedger();+ await expect(ledger.edges()).resolves.toEqual([+ expect.objectContaining({+ childId: "sub-1234abcd",+ parent: canonicalSessionPath(parentFile),+ child: canonicalSessionPath(childState.runtime.session.sessionFile),+ depth: 1,+ name: "spawned-worker",+ }),+ ]);++ await internals.setStateSessionName(childState, "renamed-worker");+ await expect(ledger.edges()).resolves.toEqual([expect.objectContaining({ name: "renamed-worker" })]);++ await internals.recordRlmSubagentDeletion(parentState, "sub-1234abcd", "revoked");+ await expect(ledger.edges()).resolves.toEqual([]);+ const lines = readFileSync(ledger.ledgerPath, "utf8").trim().split("\n");+ expect(JSON.parse(lines.at(-1)!)).toMatchObject({ op: "delete", reason: "revoked" });+ expect(existsSync(rlmLedgerPath(tempDir, sessionsDir))).toBe(true);++ // Self-heal: with the registry already tombstoned, a live ledger edge+ // (a delete lost to a crash) is finished off by a retried deletion.+ await ledger.appendSpawn({+ childId: "sub-1234abcd",+ parent: parentFile,+ child: childState.runtime.session.sessionFile,+ depth: 1,+ name: "spawned-worker",+ });+ await expect(ledger.edges()).resolves.toHaveLength(1);+ await internals.recordRlmSubagentDeletion(parentState, "sub-1234abcd", "gc");+ await expect(ledger.edges()).resolves.toEqual([]);+ const healed = readFileSync(ledger.ledgerPath, "utf8").trim().split("\n");+ expect(JSON.parse(healed.at(-1)!)).toMatchObject({ op: "delete", reason: "gc" });+ // A second retry with no live edge appends nothing further.+ await internals.recordRlmSubagentDeletion(parentState, "sub-1234abcd", "gc");+ expect(readFileSync(ledger.ledgerPath, "utf8").trim().split("\n")).toHaveLength(healed.length);+ } 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 {+ const { internals, sessionsDir } = makeDaemonFixture(tempDir);+ const parentManager = SessionManager.create(tempDir, sessionsDir);+ parentManager.newSession();+ parentManager.appendSessionInfo("parent");+ parentManager.flushNow();+ const parentFile = parentManager.getSessionFile();+ if (!parentFile) throw new Error("Missing parent session file");+ const childDir = join(parentManager.getSessionArtifactDir()!, "sub-1234abcd");+ const child = makeChildSession(tempDir, childDir, parentFile, 1, "before-rename");+ const ledger = internals.rlmSpawnLedger();+ await ledger.appendSpawn({+ childId: "sub-1234abcd",+ parent: parentFile,+ child: child.file,+ depth: 1,+ name: "before-rename",+ });++ await ledger.appendRenameByChildPath(child.file, "after-rename");+ await expect(ledger.edges()).resolves.toEqual([expect.objectContaining({ name: "after-rename" })]);+ // An unknown path renames nothing and does not throw.+ await ledger.appendRenameByChildPath(join(tempDir, "unknown.jsonl"), "nobody");+ await expect(ledger.edges()).resolves.toEqual([expect.objectContaining({ name: "after-rename" })]);+ } finally {+ rmSync(tempDir, { recursive: true, force: true });+ }+ });++ it("seeds a missing ledger lazily from real-shaped registries, memoized", async () => {+ const tempDir = mkdtempSync(join(tmpdir(), "prime-rlm-ledger-seed-"));+ try {+ const sessionsDir = join(tempDir, "sessions");+ const parentManager = SessionManager.create(tempDir, sessionsDir);+ parentManager.newSession();+ parentManager.appendSessionInfo("parent");+ parentManager.flushNow();+ const parentFile = parentManager.getSessionFile();+ const parentArtifactDir = parentManager.getSessionArtifactDir();+ if (!parentFile || !parentArtifactDir) throw new Error("Missing parent session paths");+ // A fork root: header parentSession without rlmDepth. Ledger seeding+ // never consults headers, so it must appear as a plain root.+ const forkManager = SessionManager.create(tempDir, sessionsDir);+ forkManager.newSession({ parentSession: parentFile });+ forkManager.appendSessionInfo("forked-root");+ forkManager.flushNow();++ const childDir = join(parentArtifactDir, "sub-1234abcd");+ const child = makeChildSession(tempDir, childDir, parentFile, 1, "seed-worker");+ const grandchildDir = join(childDir, "sub-deadbeef");+ const grandchild = makeChildSession(tempDir, grandchildDir, child.file, 2, "nested-worker");++ const zeroDepthDir = join(parentArtifactDir, "sub-0depth00");+ const zeroDepth = makeChildSession(tempDir, zeroDepthDir, parentFile, 1, "zero-depth-worker");++ // Registry entries shaped exactly like recordRlmSubagentRegistryEntry+ // output. The seed-worker appears twice (running then completed) as+ // the real writer produces; the zero-depth entry carries a legacy+ // rlmDepth: 0; the grandchild entry omits depth fields entirely.+ mkdirSync(parentArtifactDir, { recursive: true });+ const registryEntry = (overrides: Record<string, unknown>) => ({+ type: "rlm_subagent",+ childId: "sub-1234abcd",+ sessionName: "seed-worker",+ sessionDir: childDir,+ sessionFile: child.file,+ parentSessionId: parentManager.getSessionId(),+ parentSessionFile: parentFile,+ rlmDepth: 1,+ rlmMaxDepth: 4,+ rlmParentNodeId: "sub-1234abcd",+ prompt: "seed the worker",+ model: { provider: "test", modelId: "model" },+ createdAt: 1,+ updatedAt: "2026-01-01T00:00:00.000Z",+ ...overrides,+ });+ writeFileSync(+ join(parentArtifactDir, "rlm-subagents.jsonl"),+ `${[+ JSON.stringify(registryEntry({ status: "running" })),+ JSON.stringify(registryEntry({ status: "completed", updatedAt: "2026-01-01T00:00:02.000Z" })),+ JSON.stringify(+ registryEntry({+ childId: "sub-0depth00",+ sessionName: "zero-depth-worker",+ sessionDir: zeroDepthDir,+ sessionFile: zeroDepth.file,+ rlmDepth: 0,+ status: "completed",+ }),+ ),+ ].join("\n")}\n`,+ );+ const childArtifactDir = child.manager.getSessionArtifactDir();+ if (!childArtifactDir) throw new Error("Missing child artifact dir");+ mkdirSync(childArtifactDir, { recursive: true });+ writeFileSync(+ join(childArtifactDir, "rlm-subagents.jsonl"),+ `${JSON.stringify({+ type: "rlm_subagent",+ childId: "sub-deadbeef",+ sessionName: "nested-worker",+ sessionDir: grandchildDir,+ sessionFile: grandchild.file,+ parentSessionId: child.manager.getSessionId(),+ parentSessionFile: child.file,+ status: "completed",+ createdAt: 2,+ updatedAt: "2026-01-01T00:00:01.000Z",+ })}\n`,+ );++ const { internals } = makeDaemonFixture(tempDir);+ expect(existsSync(rlmLedgerPath(tempDir, sessionsDir))).toBe(false);+ const family = await internals.rlmSpawnLedger().family();+ expect(family.map((row) => [row.name, row.rlmDepth])).toEqual(+ expect.arrayContaining([+ ["parent", 0],+ ["forked-root", 0],+ ["seed-worker", 1],+ // The legacy rlmDepth: 0 registry value is unwritable under the+ // spawn invariants; the seeder derives parent depth + 1 instead.+ ["zero-depth-worker", 1],+ ["nested-worker", 2],+ ]),+ );+ expect(family).toHaveLength(5);+ expect(existsSync(rlmLedgerPath(tempDir, sessionsDir))).toBe(true);++ // Memoized: the seeded ledger, not the registries, is the source now.+ rmSync(join(parentArtifactDir, "rlm-subagents.jsonl"));+ const again = await internals.rlmSpawnLedger().family();+ expect(again.map((row) => row.name)).toEqual(expect.arrayContaining(["seed-worker", "nested-worker"]));++ const siblings = await internals.rlmSpawnLedger().siblings(child.file);+ expect(siblings.map((row) => row.name).sort()).toEqual(["seed-worker", "zero-depth-worker"]);+ } finally {+ rmSync(tempDir, { recursive: true, force: true });+ }+ });++ it("leaves no ledger file behind an interrupted seed and re-seeds completely", async () => {+ const tempDir = mkdtempSync(join(tmpdir(), "prime-rlm-ledger-seed-crash-"));+ try {+ const sessionsDir = join(tempDir, "sessions");+ const parentManager = SessionManager.create(tempDir, sessionsDir);+ parentManager.newSession();+ parentManager.appendSessionInfo("parent");+ parentManager.flushNow();+ const parentFile = parentManager.getSessionFile();+ const parentArtifactDir = parentManager.getSessionArtifactDir();+ if (!parentFile || !parentArtifactDir) throw new Error("Missing parent session paths");+ const child = makeChildSession(tempDir, join(parentArtifactDir, "sub-11111111"), parentFile, 1, "worker");+ const seedEntry = {+ childId: "sub-11111111",+ sessionName: "worker",+ sessionFile: child.file,+ rlmDepth: 1,+ status: "completed" as const,+ };+ let calls = 0;+ const flaky = new RlmSpawnLedger(tempDir, sessionsDir, {+ readRegistryForSessionFile: async () => {+ if (++calls === 1) throw new Error("disk exploded mid-seed");+ return [];+ },+ });+ await expect(flaky.family()).resolves.toEqual([expect.objectContaining({ name: "parent" })]);+ // The interrupted seed published nothing: no ledger file, no partial state.+ expect(existsSync(rlmLedgerPath(tempDir, sessionsDir))).toBe(false);++ const healthy = new RlmSpawnLedger(tempDir, sessionsDir, {+ readRegistryForSessionFile: async (sessionFile) =>+ canonicalSessionPath(sessionFile) === canonicalSessionPath(parentFile) ? [seedEntry] : [],+ });+ await expect(healthy.family()).resolves.toEqual([+ expect.objectContaining({ name: "parent", rlmDepth: 0 }),+ expect.objectContaining({ name: "worker", rlmDepth: 1 }),+ ]);+ expect(existsSync(rlmLedgerPath(tempDir, sessionsDir))).toBe(true);+ } finally {+ rmSync(tempDir, { recursive: true, force: true });+ }+ });++ it("discards the seed when a live append creates the ledger during seeding", async () => {+ const tempDir = mkdtempSync(join(tmpdir(), "prime-rlm-ledger-seed-race-"));+ try {+ const sessionsDir = join(tempDir, "sessions");+ const parentManager = SessionManager.create(tempDir, sessionsDir);+ parentManager.newSession();+ parentManager.appendSessionInfo("parent");+ parentManager.flushNow();+ const parentFile = parentManager.getSessionFile();+ const parentArtifactDir = parentManager.getSessionArtifactDir();+ if (!parentFile || !parentArtifactDir) throw new Error("Missing parent session paths");+ const stale = makeChildSession(tempDir, join(parentArtifactDir, "sub-11111111"), parentFile, 1, "stale");+ const live = makeChildSession(tempDir, join(parentArtifactDir, "sub-22222222"), parentFile, 1, "live");+ // A second process's ledger over the same file: no seed source, so+ // its append lands directly.+ const other = new RlmSpawnLedger(tempDir, sessionsDir);+ const seeding = new RlmSpawnLedger(tempDir, sessionsDir, {+ readRegistryForSessionFile: async (sessionFile) => {+ if (canonicalSessionPath(sessionFile) !== canonicalSessionPath(parentFile)) return [];+ // Simulate the race: the live append creates the real file+ // between the seed's initial existence check and its publish.+ await other.appendSpawn({+ childId: "sub-22222222",+ parent: parentFile,+ child: live.file,+ depth: 1,+ name: "live",+ });+ return [+ {+ childId: "sub-11111111",+ sessionName: "stale",+ sessionFile: stale.file,+ rlmDepth: 1,+ status: "completed" as const,+ },+ ];+ },+ });++ const family = await seeding.family();+ // The live append won; the stale seed was discarded, not clobbered over it.+ expect(family.map((row) => row.name)).toEqual(["parent", "live"]);+ const contents = readFileSync(rlmLedgerPath(tempDir, sessionsDir), "utf8");+ expect(contents).toContain("sub-22222222");+ expect(contents).not.toContain("sub-11111111");+ } finally {+ rmSync(tempDir, { recursive: true, force: true });+ }+ });++ it("skips seeding entirely when the seed would exceed the read bounds", async () => {+ const tempDir = mkdtempSync(join(tmpdir(), "prime-rlm-ledger-seed-bounds-"));+ try {+ const sessionsDir = join(tempDir, "sessions");+ const parentManager = SessionManager.create(tempDir, sessionsDir);+ parentManager.newSession();+ parentManager.appendSessionInfo("parent");+ parentManager.flushNow();+ const parentFile = parentManager.getSessionFile();+ if (!parentFile) throw new Error("Missing parent session file");+ // Few-but-huge records: 40 x ~1MiB names serialize past the 32MiB+ // byte bound without a 100k-record loop.+ const hugeName = "n".repeat(1024 * 1024);+ const entries = Array.from({ length: 40 }, (_, index) => ({+ childId: `sub-${String(index).padStart(8, "0")}`,+ sessionName: hugeName,+ sessionFile: join(tempDir, `huge-${index}.jsonl`),+ rlmDepth: 1,+ status: "completed" as const,+ }));+ const logged: string[] = [];+ const ledger = new RlmSpawnLedger(+ tempDir,+ sessionsDir,+ {+ readRegistryForSessionFile: async (sessionFile) =>+ canonicalSessionPath(sessionFile) === canonicalSessionPath(parentFile) ? entries : [],+ },+ (message) => logged.push(message),+ );+ // No ledger file published; the family degrades to flat roots.+ await expect(ledger.family()).resolves.toEqual([expect.objectContaining({ name: "parent", rlmDepth: 0 })]);+ expect(existsSync(rlmLedgerPath(tempDir, sessionsDir))).toBe(false);+ expect(logged.some((message) => message.includes("seed exceeds read bounds"))).toBe(true);+ } finally {+ rmSync(tempDir, { recursive: true, force: true });+ }+ });++ it("publishes the seed via rename fallback on filesystems without hard links", async () => {+ const tempDir = mkdtempSync(join(tmpdir(), "prime-rlm-ledger-seed-nolink-"));+ try {+ const sessionsDir = join(tempDir, "sessions");+ const parentManager = SessionManager.create(tempDir, sessionsDir);+ parentManager.newSession();+ parentManager.appendSessionInfo("parent");+ parentManager.flushNow();+ const parentFile = parentManager.getSessionFile();+ const parentArtifactDir = parentManager.getSessionArtifactDir();+ if (!parentFile || !parentArtifactDir) throw new Error("Missing parent session paths");+ const child = makeChildSession(tempDir, join(parentArtifactDir, "sub-11111111"), parentFile, 1, "worker");+ const logged: string[] = [];+ const ledger = new RlmSpawnLedger(+ tempDir,+ sessionsDir,+ {+ readRegistryForSessionFile: async (sessionFile) =>+ canonicalSessionPath(sessionFile) === canonicalSessionPath(parentFile)+ ? [+ {+ childId: "sub-11111111",+ sessionName: "worker",+ sessionFile: child.file,+ rlmDepth: 1,+ status: "completed" as const,+ },+ ]+ : [],+ },+ (message) => logged.push(message),+ );+ linkFailure.code = "ENOTSUP";+ try {+ await expect(ledger.family()).resolves.toEqual([+ expect.objectContaining({ name: "parent", rlmDepth: 0 }),+ expect.objectContaining({ name: "worker", rlmDepth: 1 }),+ ]);+ } finally {+ linkFailure.code = undefined;+ }+ expect(existsSync(rlmLedgerPath(tempDir, sessionsDir))).toBe(true);+ expect(logged.some((message) => message.includes("falling back to rename"))).toBe(true);+ } finally {+ rmSync(tempDir, { recursive: true, force: true });+ }+ });++ it("degrades to a flat family when seeding fails instead of failing closed", async () => {+ const tempDir = mkdtempSync(join(tmpdir(), "prime-rlm-ledger-seedfail-"));+ try {+ const sessionsDir = join(tempDir, "sessions");+ const parentManager = SessionManager.create(tempDir, sessionsDir);+ parentManager.newSession();+ parentManager.appendSessionInfo("parent");+ parentManager.flushNow();+ const parentFile = parentManager.getSessionFile();+ if (!parentFile) throw new Error("Missing parent session file");+ const failures: string[] = [];+ const ledger = new RlmSpawnLedger(+ tempDir,+ sessionsDir,+ {+ readRegistryForSessionFile: async () => {+ throw new Error("registry exploded");+ },+ },+ (message) => failures.push(message),+ );+ const family = await ledger.family();+ expect(family.map((row) => [row.name, row.rlmDepth])).toEqual([["parent", 0]]);+ expect(failures.some((message) => message.includes("registry exploded"))).toBe(true);+ } finally {+ rmSync(tempDir, { recursive: true, force: true });+ }+ });+});++interface SupervisorLedgerInternals {+ rlmSpawnLedger(): RlmSpawnLedger;+ rlmLedgerSiblings(sessionPath: string): Promise<Array<{ name?: string; rlmDepth: number; path: string }>>;+ assertSupervisorSavedSessionNameAvailable(sessionPath: string, name: string): Promise<void>;+ handleCommand(client: object, command: Record<string, unknown>): Promise<unknown>;+ catalog: object;+}++describe("rlm spawn ledger supervisor wiring", () => {+ it("reserves saved-sibling names against ledger-backed siblings", async () => {+ const tempDir = mkdtempSync(join(tmpdir(), "prime-rlm-ledger-supervisor-"));+ try {+ const sessionsDir = join(tempDir, "sessions");+ const parentManager = SessionManager.create(tempDir, sessionsDir);+ parentManager.newSession();+ parentManager.appendSessionInfo("parent");+ parentManager.flushNow();+ const parentFile = parentManager.getSessionFile();+ const parentArtifactDir = parentManager.getSessionArtifactDir();+ if (!parentFile || !parentArtifactDir) throw new Error("Missing parent session paths");+ const first = makeChildSession(tempDir, join(parentArtifactDir, "sub-11111111"), parentFile, 1, "first");+ const second = makeChildSession(tempDir, join(parentArtifactDir, "sub-22222222"), parentFile, 1, "second");+ const supervisor = new DaemonSupervisor(join(tempDir, "daemon.sock"), {+ defaultSessionConfig: { agentDir: tempDir, cwd: tempDir, sessionDir: sessionsDir },+ descriptorDir: join(tempDir, "workers"),+ }) as unknown as SupervisorLedgerInternals;+ const ledger = supervisor.rlmSpawnLedger();+ await ledger.appendSpawn({+ childId: "sub-11111111",+ parent: parentFile,+ child: first.file,+ depth: 1,+ name: "first",+ });+ await ledger.appendSpawn({+ childId: "sub-22222222",+ parent: parentFile,+ child: second.file,+ depth: 1,+ name: "second",+ });++ await expect(supervisor.rlmLedgerSiblings(first.file)).resolves.toEqual([+ expect.objectContaining({ name: "first", rlmDepth: 1 }),+ expect.objectContaining({ name: "second", rlmDepth: 1 }),+ ]);+ await expect(supervisor.assertSupervisorSavedSessionNameAvailable(first.file, "second")).rejects.toThrow(+ "already exists at depth 1",+ );+ await expect(+ supervisor.assertSupervisorSavedSessionNameAvailable(first.file, "unclaimed"),+ ).resolves.toBeUndefined();+ } finally {+ rmSync(tempDir, { recursive: true, force: true });+ }+ });++ it("appends a ledger rename for an offline saved-session rename", async () => {+ const tempDir = mkdtempSync(join(tmpdir(), "prime-rlm-ledger-supervisor-rename-"));+ try {+ const sessionsDir = join(tempDir, "sessions");+ const parentManager = SessionManager.create(tempDir, sessionsDir);+ parentManager.newSession();+ parentManager.appendSessionInfo("parent");+ parentManager.flushNow();+ const parentFile = parentManager.getSessionFile();+ const parentArtifactDir = parentManager.getSessionArtifactDir();+ if (!parentFile || !parentArtifactDir) throw new Error("Missing parent session paths");+ const child = makeChildSession(tempDir, join(parentArtifactDir, "sub-11111111"), parentFile, 1, "old-name");+ const supervisor = new DaemonSupervisor(join(tempDir, "daemon.sock"), {+ defaultSessionConfig: { agentDir: tempDir, cwd: tempDir, sessionDir: sessionsDir },+ descriptorDir: join(tempDir, "workers"),+ }) as unknown as SupervisorLedgerInternals;+ const rename = vi.fn(async () => {});+ Object.assign(supervisor.catalog, { rename });+ const ledger = supervisor.rlmSpawnLedger();+ await ledger.appendSpawn({+ childId: "sub-11111111",+ parent: parentFile,+ child: child.file,+ depth: 1,+ name: "old-name",+ });++ await supervisor.handleCommand(+ {},+ { type: "rename_saved_session", sessionPath: child.file, name: "new-name" },+ );+ expect(rename).toHaveBeenCalledWith(child.file, "new-name");+ await expect(ledger.edges()).resolves.toEqual([expect.objectContaining({ name: "new-name" })]);+ } finally {+ rmSync(tempDir, { recursive: true, force: true });+ }+ });+});