A self-improving RLM agent for coding workflows and long-running autonomous tasks.
Rust
fix(coding-agent): scope the roster seed to registered workers' families without changing list --all (#1951)
Sebastian Müller0749e06671f0
diff --git a/packages/coding-agent/.changes/roster-seed-scope.md b/packages/coding-agent/.changes/roster-seed-scope.mdnew file mode 100644index 0000000000..60997476dd--- /dev/null+++ b/packages/coding-agent/.changes/roster-seed-scope.md@@ -0,0 +1 @@+- Scoped the roster's restart seed to registered workers' families: the saved-session corpus stays owned by the disk catalog, so a supervisor restart no longer publishes thousands of inactive rows (and one header read per row) to every roster subscriber. `prime list --all` output is unchanged: subagent rows of families without a registered worker are now served on demand from the spawn ledger.diff --git a/packages/coding-agent/src/modes/daemon/agent-roster.ts b/packages/coding-agent/src/modes/daemon/agent-roster.tsindex 6fd855cb4d..fe0f674ea9 100644--- a/packages/coding-agent/src/modes/daemon/agent-roster.ts+++ b/packages/coding-agent/src/modes/daemon/agent-roster.ts@@ -118,6 +118,7 @@ export function passivatedWorkerRosterEntry(export function sessionSummaryFromRosterEntry(entry: WorkerRosterEntry | AgentRosterEntry): SessionSummary {const ledger = "status" in entry ? entry : undefined;+ // statusLabel/lastHeardFromAt are set only for exceptional states; viewers key label display on their presence.return {...entry.summary,sessionActions: { queuedCount: 0, steering: [], followUps: [] },diff --git a/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts b/packages/coding-agent/src/modes/daemon/daemon-supervisor.tsindex 7ea78cd89e..b5afde5da3 100644--- a/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts+++ b/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts@@ -434,6 +434,28 @@ function isSupervisorRecoveryCancelled(error: unknown): boolean {return isSupervisorShutdownAdmissionCancelled(error) || isSupervisorGenerationStale(error);}+// Workers can be registered mid-tree (a resumed subagent transcript), so descent is membership at+// any step of the parent walk, never a comparison against the ultimate root alone.+function rosterFamilyDescendsFrom(+ edges: readonly RlmLedgerEdge[],+): (path: string, roots: ReadonlySet<string>) => boolean {+ const parentByChild = new Map(+ edges.map((edge) => [canonicalSessionPath(edge.child), canonicalSessionPath(edge.parent)]),+ );+ return (path, roots) => {+ const visited = new Set<string>();+ let current = path;+ while (!visited.has(current)) {+ if (roots.has(current)) return true;+ visited.add(current);+ const parent = parentByChild.get(current);+ if (parent === undefined) return false;+ current = parent;+ }+ return false;+ };+}+function isDaemonWorkerProbeTimeout(error: unknown): boolean {return error instanceof DaemonWorkerProbeTimeoutError;}@@ -2426,6 +2448,16 @@ export class DaemonSupervisor {// The on-disk scan is public: an unserved (client-owned) worker row hides its live metadata only.merged.push(summaryForInactiveSession(info));}+ // The boot seed covers registered workers' families only, so dead families (pure on-disk+ // history, no registered worker anywhere in the tree) are not roster-resident. Their+ // subagent rows are read from the spawn ledger on demand instead.+ let spawnEdges: RlmLedgerEdge[] = [];+ try {+ spawnEdges = await this.rlmSpawnLedger().liveEdges();+ } catch (error) {+ this.log(`Could not list spawn-ledger sessions: ${String(error)}`);+ }+ const spawnParents = new Map(spawnEdges.map((edge) => [canonicalSessionPath(edge.child), edge.parent]));const offlineRows: AgentRosterEntry[] = [];for (const entry of this.roster().values()) {if (entry.queuedChild || entry.summary.activeSessionId !== undefined) continue;@@ -2437,7 +2469,27 @@ export class DaemonSupervisor {for (const hydrated of await Promise.all(offlineRows.map((entry) => this.hydrateSeededEntry(entry)))) {const summary = sessionSummaryFromRosterEntry(hydrated);if (cwd !== undefined && resolve(summary.cwd) !== cwd) continue;- if (!this.matchesListSessionDir(summary, sessionDir)) continue;+ if (!this.matchesListSessionDir(summary, sessionDir, spawnParents)) continue;+ merged.push(summary);+ }+ const unseededFiles = new Set<string>();+ for (const edge of spawnEdges) {+ const childPath = canonicalSessionPath(edge.child);+ if (scannedFiles.has(childPath) || activeByFile.has(childPath) || unseededFiles.has(childPath)) continue;+ if (this.roster().hasSessionFile(childPath)) continue;+ const entry = this.rosterEntryForSpawnLedgerEdge(edge);+ if (this.roster().has(entry.agentId)) continue;+ unseededFiles.add(childPath);+ // Hydrated one at a time, like the boot seed: a large dead-family ledger must not fan+ // out into one concurrent transcript read per child.+ const hydrated = await this.hydratedSeedEntry(entry);+ // The same classification a roster write would have applied: these rows read "inactive".+ const summary = sessionSummaryFromRosterEntry({+ ...hydrated,+ status: classifySessionRosterStatus(hydrated.summary),+ });+ if (cwd !== undefined && resolve(summary.cwd) !== cwd) continue;+ if (!this.matchesListSessionDir(summary, sessionDir, spawnParents)) continue;merged.push(summary);}for (const summary of active) {@@ -2448,21 +2500,29 @@ export class DaemonSupervisor {return success(command.id, "list", { ...data, sessions: merged });}+ private async hydratedSeedEntry<T extends WorkerRosterEntry>(entry: T): Promise<T> {+ const info = entry.summary.sessionFile+ ? await readSessionInfo(entry.summary.sessionFile).catch(() => undefined)+ : undefined;+ if (!info) return { ...entry, seededCwd: true as const };+ const { seededCwd, ...rest } = entry;+ return { ...rest, summary: { ...entry.summary, cwd: info.cwd } } as T;+ }+private async hydrateSeededEntry(entry: AgentRosterEntry): Promise<AgentRosterEntry> {if (entry.seededCwd !== true || !entry.summary.sessionFile) return entry;- const info = await readSessionInfo(entry.summary.sessionFile).catch(() => undefined);- if (!info) return entry;+ const hydrated = await this.hydratedSeedEntry(entry);+ if (hydrated.seededCwd === true) return entry;const current = this.roster().get(entry.agentId);if (current !== entry) return current ?? entry;- const { seededCwd, ...rest } = entry;- return this.roster().write(- { ...rest, summary: { ...entry.summary, cwd: info.cwd } },- entry.workerId,- entry.statusLabel,- );+ return this.roster().write(hydrated, entry.workerId, entry.statusLabel);}- private matchesListSessionDir(summary: SessionSummary, sessionDir: string | undefined): boolean {+ private matchesListSessionDir(+ summary: SessionSummary,+ sessionDir: string | undefined,+ spawnParents?: ReadonlyMap<string, string>,+ ): boolean {if (sessionDir === undefined) return true;if (!summary.sessionFile) return false;let file = resolve(summary.sessionFile);@@ -2473,7 +2533,9 @@ export class DaemonSupervisor {if (visited.has(canonical)) break;visited.add(canonical);file = resolve(parentSessionPath);- parentSessionPath = this.roster().bySessionFile(canonical)?.summary.parentSessionPath;+ // Dead-family ancestors are not roster-resident; the spawn ledger continues the walk.+ parentSessionPath =+ this.roster().bySessionFile(canonical)?.summary.parentSessionPath ?? spawnParents?.get(canonical);}return dirname(file) === resolve(sessionDir);}@@ -3949,23 +4011,20 @@ export class DaemonSupervisor {private async seedRosterLedger(): Promise<void> {try {- for (const info of await this.catalog.list(undefined, this.defaultSessionConfig.sessionDir)) {- const entry = workerRosterEntryFromSummary(summaryForInactiveSession(info));- if (!this.roster().has(entry.agentId)) this.writeRosterEntry(entry);- }- } catch (error) {- this.log(`Could not seed the agent roster from the session catalog: ${String(error)}`);- }- try {- // Stat-reconciled: rows the disk cannot back (out-of-band transcript removal) never seed.- for (const edge of await this.rlmSpawnLedger().liveEdges()) {+ const roots = new Set<string>();+ for (const worker of this.workers.values()) {+ const root = worker.descriptor.sessionFile ?? worker.descriptor.createCommand.sessionPath;+ if (root !== undefined) roots.add(canonicalSessionPath(root));+ }+ if (roots.size === 0) return;+ const edges = await this.rlmSpawnLedger().liveEdges();+ const descendsFrom = rosterFamilyDescendsFrom(edges);+ for (const edge of edges) {+ if (!descendsFrom(canonicalSessionPath(edge.parent), roots)) continue;const entry = this.rosterEntryForSpawnLedgerEdge(edge);if (this.roster().has(entry.agentId)) continue;if (this.roster().hasSessionFile(canonicalSessionPath(edge.child))) continue;- const info = await readSessionInfo(edge.child).catch(() => undefined);- this.roster().write(- info ? { ...entry, summary: { ...entry.summary, cwd: info.cwd } } : { ...entry, seededCwd: true },- );+ this.roster().write(await this.hydratedSeedEntry(entry));}} catch (error) {this.log(`Could not seed the agent roster from the spawn ledger: ${String(error)}`);@@ -4077,7 +4136,6 @@ export class DaemonSupervisor {delta: Extract<DaemonWorkerRosterOutbound, { type: "roster_delta" }>,source?: DaemonWorkerClient,): Promise<void> {- // Live edges are read before any deletion, so a reseeded child never surfaces as a transient removal.let edgesFailed = false;const edges = await this.rlmSpawnLedger().liveEdges()@@ -4097,48 +4155,24 @@ export class DaemonSupervisor {unclaimed.set(entry.agentId, entry);}}- // A reseed keeps the previous claim and hydrated summary; a synthetic seed would drop- // lastActivityAt (pinning canEvictWorker on NaN) and flap the claim off on every snapshot.- // Only THIS worker's family reseeds: other families' rows are owned by their own workers or- // the startup seed, and a client-owned worker's dropped rows must not resurrect as public rows.+ // Only this worker's family reseeds: anything wider can resurrect a client-owned worker's dropped children.const workerRoot = worker.descriptor.sessionFile ?? worker.descriptor.createCommand.sessionPath;- const rootPath = workerRoot !== undefined ? canonicalSessionPath(workerRoot) : undefined;- const parentByChild = new Map(- edges.map((edge) => [canonicalSessionPath(edge.child), canonicalSessionPath(edge.parent)]),- );- const familyRoot = (path: string): string => {- const visited = new Set<string>();- let current = path;- while (!visited.has(current)) {- visited.add(current);- const parent = parentByChild.get(current);- if (parent === undefined) return current;- current = parent;- }- return current;+ const rootPaths = new Set(workerRoot !== undefined ? [canonicalSessionPath(workerRoot)] : []);+ const descendsFrom = rosterFamilyDescendsFrom(edges);+ const familyEdges = edges.filter((edge) => descendsFrom(canonicalSessionPath(edge.parent), rootPaths));+ // "Unclaimed" rows survive: the sweep deletes them but the restore branch rewrites them.+ const rowSurvivesWithoutReseed = (entry: WorkerRosterEntry, childPath: string): boolean => {+ if (unclaimed.has(entry.agentId)) return true;+ if (sent.has(entry.agentId) && !removed.has(entry.agentId)) return true;+ const survives = (row: AgentRosterEntry | undefined): boolean =>+ row !== undefined && !unclaimed.has(row.agentId) && !removed.has(row.agentId);+ return survives(this.roster().get(entry.agentId)) || survives(this.roster().bySessionFile(childPath));};- const familyEdges = edges.filter(- (edge) => rootPath !== undefined && familyRoot(canonicalSessionPath(edge.child)) === rootPath,- );- const seedInfo = new Map<string, SessionInfo | null | undefined>();+ const seededEntries = new Map<string, WorkerRosterEntry>();for (const edge of familyEdges) {const entry = this.rosterEntryForSpawnLedgerEdge(edge);- const childPath = canonicalSessionPath(edge.child);- const currentById = this.roster().get(entry.agentId);- const currentByFile = this.roster().bySessionFile(childPath);- const currentIdSurvives =- currentById !== undefined && !unclaimed.has(currentById.agentId) && !removed.has(currentById.agentId);- const currentFileSurvives =- currentByFile !== undefined && !unclaimed.has(currentByFile.agentId) && !removed.has(currentByFile.agentId);- if (- unclaimed.has(entry.agentId) ||- (sent.has(entry.agentId) && !removed.has(entry.agentId)) ||- currentIdSurvives ||- currentFileSurvives- ) {- continue;- }- seedInfo.set(entry.agentId, await readSessionInfo(edge.child).catch(() => undefined));+ if (rowSurvivesWithoutReseed(entry, canonicalSessionPath(edge.child))) continue;+ seededEntries.set(entry.agentId, await this.hydratedSeedEntry(entry));if (!this.isWorkerRosterApplyCurrent(worker, applySource)) return;}@@ -4163,10 +4197,7 @@ export class DaemonSupervisor {this.writeRosterEntry(rest, worker);continue;}- const info = seedInfo.get(entry.agentId);- this.roster().write(- info ? { ...entry, summary: { ...entry.summary, cwd: info.cwd } } : { ...entry, seededCwd: true },- );+ this.roster().write(seededEntries.get(entry.agentId) ?? { ...entry, seededCwd: true });}}diff --git a/packages/coding-agent/test/daemon-agent-roster.test.ts b/packages/coding-agent/test/daemon-agent-roster.test.tsindex bd1dcd47bb..2e60cd8f23 100644--- a/packages/coding-agent/test/daemon-agent-roster.test.ts+++ b/packages/coding-agent/test/daemon-agent-roster.test.ts@@ -1,4 +1,4 @@-import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { existsSync, mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { dirname, join } from "node:path";import type { AgentMessage } from "@earendil-works/pi-agent-core";@@ -551,6 +551,8 @@ function makeSupervisor(workers: WorkerFixture[], extra: Record<string, unknown>assertRecoveryAllowed: vi.fn(async () => {throw new Error("recovery halted for test");}),+ // handleList consults the spawn ledger; the unit fixture defaults to an empty one.+ rlmSpawnLedger: () => ({ liveEdges: async () => [] }),log: vi.fn(),...extra,}) as SupervisorFixture;@@ -827,17 +829,21 @@ describe("supervisor roster ledger", () => {}});- it("seeds catalog and ledger rows list-all-only, serves resident worker rows, and keeps evicted rows inactive", async () => {- const directory = mkdtempSync(join(tmpdir(), "prime-roster-seed-"));+ it("seeds only registered workers' families; list --all still serves dead-family ledger rows", async () => {+ // realpath: the sessionDir filter compares against ledger paths, which are canonicalized.+ const directory = realpathSync(mkdtempSync(join(tmpdir(), "prime-roster-seed-")));tempDirs.push(directory);const sessionsDir = join(directory, "sessions");const ledger = new RlmSpawnLedger(directory, sessionsDir);const liveChildPath = join(directory, "artifacts", "live-child.jsonl");const deletedChildPath = join(directory, "artifacts", "deleted-child.jsonl");+ const foreignChildPath = join(directory, "artifacts", "foreign-child.jsonl");mkdirSync(sessionsDir, { recursive: true });writeFileSync(join(sessionsDir, "root.jsonl"), "");+ writeFileSync(join(sessionsDir, "foreign-root.jsonl"), "");mkdirSync(dirname(liveChildPath), { recursive: true });writeFileSync(liveChildPath, "");+ writeFileSync(foreignChildPath, "");await ledger.appendSpawn({childId: "live-child",parent: join(sessionsDir, "root.jsonl"),@@ -861,8 +867,50 @@ describe("supervisor roster ledger", () => {depth: 1,name: "ghost-child",});+ // A dead family: its root has no registered worker, so its children never seed;+ // list --all still serves them straight from the spawn ledger.+ await ledger.appendSpawn({+ childId: "foreign-child",+ parent: join(sessionsDir, "foreign-root.jsonl"),+ child: foreignChildPath,+ depth: 1,+ name: "foreign-child",+ });+ // A worker registered mid-tree (resumed subagent) seeds its descendants, not its siblings.+ const foreignGrandPath = join(directory, "artifacts", "foreign-grand.jsonl");+ const foreignSiblingPath = join(directory, "artifacts", "foreign-sibling.jsonl");+ writeFileSync(foreignGrandPath, "");+ writeFileSync(foreignSiblingPath, "");+ await ledger.appendSpawn({+ childId: "foreign-grand",+ parent: foreignChildPath,+ child: foreignGrandPath,+ depth: 2,+ name: "foreign-grand",+ });+ await ledger.appendSpawn({+ childId: "foreign-sibling",+ parent: join(sessionsDir, "foreign-root.jsonl"),+ child: foreignSiblingPath,+ depth: 1,+ name: "foreign-sibling",+ });+ // A depth-2 dead-family child: the sessionDir walk must climb ledger edges, not roster rows.+ const deadGrandPath = join(directory, "artifacts", "dead-grand.jsonl");+ writeFileSync(deadGrandPath, "");+ await ledger.appendSpawn({+ childId: "dead-grand",+ parent: foreignSiblingPath,+ child: deadGrandPath,+ depth: 2,+ name: "dead-grand",+ });- const supervisor = makeSupervisor([], {+ const worker = makeWorker("worker-1");+ Object.assign(worker.descriptor, { sessionFile: join(sessionsDir, "root.jsonl") });+ const midWorker = makeWorker("worker-mid");+ Object.assign(midWorker.descriptor, { sessionFile: foreignChildPath });+ const supervisor = makeSupervisor([worker, midWorker], {rlmSpawnLedger: () => ledger,catalog: {list: vi.fn(async () => [@@ -876,22 +924,53 @@ describe("supervisor roster ledger", () => {firstMessage: "hello",allMessagesText: "",},+ {+ id: "foreign-root",+ path: join(sessionsDir, "foreign-root.jsonl"),+ cwd: "/tmp/project",+ created: new Date(0),+ modified: new Date(0),+ messageCount: 1,+ firstMessage: "",+ allMessagesText: "",+ },]),},});await supervisor.seedRosterLedger();- // A push-only view needs saved top-level rows in the ledger itself, not only in list-all rescans.- expect(supervisor.roster().has("saved-root")).toBe(true);- const listed = await supervisor.handleList({}, { type: "list", all: true });+ // Only registered workers' descendants seed; the saved corpus is served by the catalog scan alone.+ expect(supervisor.roster().has("saved-root")).toBe(false);+ const seededChildIds = new Set([...supervisor.roster().values()].map((entry) => entry.summary.rlmChildId));+ // The mid-tree worker seeds its descendant, never its own transcript's siblings or ancestors.+ expect(seededChildIds.has("foreign-grand")).toBe(true);+ expect(seededChildIds.has("foreign-child")).toBe(false);+ expect(seededChildIds.has("foreign-sibling")).toBe(false);+ // Dead-family rows stay visible in list --all, served on demand from the spawn ledger.+ const listed = await supervisor.handleList({}, { type: "list", all: true, sessionDir: sessionsDir });const ids = listed.data?.sessions.map((session) => session.sessionId).sort();- expect(ids).toEqual(["live-child", "saved-root"]);+ expect(ids).toEqual([+ "dead-grand",+ "foreign-child",+ "foreign-grand",+ "foreign-root",+ "foreign-sibling",+ "live-child",+ "saved-root",+ ]);expect(listed.data?.sessions.every((session) => session.activeSessionId === undefined)).toBe(true);+ expect(listed.data?.sessions.find((session) => session.sessionId === "foreign-sibling")).toMatchObject({+ rosterStatus: "inactive",+ runtimeKind: "subagent",+ rlmDepth: 1,+ rlmChildId: "foreign-sibling",+ sessionFile: foreignSiblingPath,+ parentSessionPath: join(sessionsDir, "foreign-root.jsonl"),+ cwd: dirname(foreignSiblingPath),+ });expect((await supervisor.handleList({}, { type: "list" })).data?.sessions).toEqual([]);// A live worker's rows: the active root and its passivated child are resident; seeded rows stay list-all-only.- const worker = makeWorker("worker-1");- supervisor.workers.set("worker-1", worker);supervisor.writeRosterEntry(workerRosterEntryFromSummary(summary({@@ -926,7 +1005,12 @@ describe("supervisor roster ledger", () => {const liveAll = await supervisor.handleList({}, { type: "list", all: true });expect(liveAll.data?.sessions.map((session) => session.sessionId).sort()).toEqual(["child-session",+ "dead-grand","evicted",+ "foreign-child",+ "foreign-grand",+ "foreign-root",+ "foreign-sibling","live-child","saved-root",]);diff --git a/packages/coding-agent/test/rlm-ledger.test.ts b/packages/coding-agent/test/rlm-ledger.test.tsindex 86f7b4a747..2ebb9286dc 100644--- a/packages/coding-agent/test/rlm-ledger.test.ts+++ b/packages/coding-agent/test/rlm-ledger.test.ts@@ -1089,6 +1089,10 @@ describe("rlm spawn ledger supervisor wiring", () => {depth: 1,name: "worker",});+ // The seed scopes to registered workers' families.+ supervisor.workers.set("worker-1", {+ descriptor: { workerId: "worker-1", sessionFile: parentFile, createCommand: { type: "create" } },+ } as never);await supervisor.seedRosterLedger();const response = await supervisor.handleCommand({}, { type: "roster_subscribe" });@@ -1134,6 +1138,10 @@ describe("rlm spawn ledger supervisor wiring", () => {name: "existing",});Object.assign(supervisor.catalog, { list: vi.fn(async () => []) });+ // The seed scopes to registered workers' families.+ supervisor.workers.set("worker-1", {+ descriptor: { workerId: "worker-1", sessionFile: parentFile, createCommand: { type: "create" } },+ } as never);await supervisor.seedRosterLedger();const seeded = await supervisor.handleCommand({}, { type: "roster_subscribe" });if (!seeded?.success) throw new Error("Roster subscription failed");