Skip to content

A self-improving RLM agent for coding workflows and long-running autonomous tasks.

Rust

preserve completed subagent heartbeats (#451)

ktbe85ddbf8e5c
diff --git a/packages/coding-agent/CHANGELOG.md b/packages/coding-agent/CHANGELOG.md
index 4ddfcaaf87..a04c4c5517 100644
--- a/packages/coding-agent/CHANGELOG.md
+++ b/packages/coding-agent/CHANGELOG.md
@@ -2,6 +2,7 @@
## [Unreleased]
+- Fixed completed subagents cancelling their RLM heartbeats before the first run ([ENG-4652](https://linear.app/primeintellect/issue/ENG-4652/subagent-heartbeats-dont-work)).
- Changed the fullscreen follow shortcut from `Alt+Down` to `Ctrl+Shift+Down` for more reliable terminal input ([ENG-4684](https://linear.app/primeintellect/issue/ENG-4684/altdown-doesnt-work)).
- Fixed the Agents View reordering sessions whenever prompts or heartbeats updated their activity timestamps ([ENG-4650](https://linear.app/primeintellect/issue/ENG-4650/agents-view-shifts-session-list-constantly)).
- Added parent-scoped subagent lifecycle APIs: create children with readable default or orchestrator-chosen names, recover running or completed children through `rlm.list_subagents()`, continue them through agent messaging, and close/remove them with `rlm.delete_subagent()`.
diff --git a/packages/coding-agent/src/modes/agents-view/agents-view-state.ts b/packages/coding-agent/src/modes/agents-view/agents-view-state.ts
index 39339a6f30..0ebd01c5ce 100644
--- a/packages/coding-agent/src/modes/agents-view/agents-view-state.ts
+++ b/packages/coding-agent/src/modes/agents-view/agents-view-state.ts
@@ -179,7 +179,7 @@ export function buildAgentsViewRows(
}
}
} else {
- flattened.push(createSubagentSummaryRow(row, children.length, depth + 1, childHasSpawnCode));
+ flattened.push(createSubagentSummaryRow(row, children, depth + 1, childHasSpawnCode));
}
};
for (const root of roots.sort(compareAgentsViewRows)) {
@@ -192,17 +192,23 @@ type MutableAgentsViewRow = AgentsViewRow;
function createSubagentSummaryRow(
parent: AgentsViewRow,
- totalCount: number,
+ children: readonly AgentsViewRow[],
depth: number,
hasSpawnCode: boolean,
): AgentsViewRow {
+ const totalCount = children.length;
const running = parent.runningSubagentCount;
+ const heartbeatCount = children.filter((child) => child.summary.hasActiveHeartbeat).length;
// Finished subagents stay reachable through the summary row even when
// nothing is running anymore.
- const title =
+ const subagentTitle =
running > 0
? `${running} ${running === 1 ? "subagent" : "subagents"} running`
: `${totalCount} ${totalCount === 1 ? "subagent" : "subagents"}`;
+ const title =
+ heartbeatCount > 0
+ ? `${subagentTitle} · ${heartbeatCount} ${heartbeatCount === 1 ? "heartbeat" : "heartbeats"} active`
+ : subagentTitle;
return {
kind: "subagent-summary",
section: parent.section,
diff --git a/packages/coding-agent/src/modes/daemon/daemon-mode.ts b/packages/coding-agent/src/modes/daemon/daemon-mode.ts
index 1d21ac732e..21ac5ddd48 100644
--- a/packages/coding-agent/src/modes/daemon/daemon-mode.ts
+++ b/packages/coding-agent/src/modes/daemon/daemon-mode.ts
@@ -1603,9 +1603,7 @@ export class AgentDaemon {
if (current && this.bindingSessions.has(current.activeSessionId)) {
return undefined;
}
- this.cronStore.cancel(dueJob.id);
- this.cronScheduler.wake();
- return undefined;
+ return this.restoreRlmHeartbeatSession(dueJob);
}
if (!(await this.isPersistedCronJobRunnable(dueJob.id))) {
return undefined;
@@ -1622,6 +1620,49 @@ export class AgentDaemon {
}
}
+ private async restoreRlmHeartbeatSession(job: AgentCronJob): Promise<ActiveSessionState | undefined> {
+ const childInfo = await readSessionInfo(job.sessionFile);
+ const parentSessionPath = childInfo?.parentSessionPath;
+ const parentInfo = parentSessionPath ? await readSessionInfo(parentSessionPath) : undefined;
+ if (
+ !childInfo ||
+ childInfo.id !== job.sessionId ||
+ !parentSessionPath ||
+ !parentInfo ||
+ parentInfo.state?.status !== "active"
+ ) {
+ this.cancelRlmHeartbeat(job.id);
+ return undefined;
+ }
+
+ try {
+ const parentState = await this.createRuntime(
+ { type: "create", sessionPath: parentSessionPath },
+ () => this.getRunnableCronJob(job.id) !== undefined,
+ );
+ await this.rehydrateCompletedRlmSubagents(parentState);
+ const childState = this.findSessionBySessionFile(job.sessionFile);
+ if (!childState || childState.runtime.metadata.kind !== "subagent") {
+ this.cancelRlmHeartbeat(job.id);
+ return undefined;
+ }
+ this.rebindCronJobsToState(childState);
+ const reboundJob = this.getRunnableCronJob(job.id);
+ return reboundJob && this.isCronJobRunnableForState(reboundJob, childState, true) ? childState : undefined;
+ } catch (error) {
+ if (error instanceof RuntimeOpenCancelledError) {
+ return undefined;
+ }
+ throw error;
+ }
+ }
+
+ private cancelRlmHeartbeat(jobId: string): void {
+ if (this.cronStore.cancel(jobId)) {
+ this.cronScheduler.wake();
+ }
+ }
+
private async isPersistedCronJobRunnable(jobId: string): Promise<boolean> {
for (let attempt = 0; attempt < 2; attempt++) {
const job = this.getRunnableCronJob(jobId);
@@ -1750,8 +1791,6 @@ export class AgentDaemon {
// closeChildSessions tears it down with the parent. Errored or cancelled children
// would re-seed as "done", so close them immediately.
if (state && status === "done") {
- // Run shutdown side effects without disposing the still-readable session.
- this.cancelSubagentRlmHeartbeats(state);
await flushAgentTraceUpload(state.runtime.session.sessionManager).catch(() => undefined);
// Retention can decline if deletion or parent teardown won while the trace
// flush was in flight. Persist completion only after retention succeeds, so
@@ -4352,7 +4391,7 @@ export class AgentDaemon {
}
if (reason === "killed") {
this.cancelScheduledJobsForSession(state);
- } else {
+ } else if (reason !== "shutdown" && reason !== "update") {
this.cancelSubagentRlmHeartbeats(state);
}
// Abort in-flight status work before any await/dispose so it can't write
diff --git a/packages/coding-agent/test/agents-view-state.test.ts b/packages/coding-agent/test/agents-view-state.test.ts
index 7b77933e62..6da3176971 100644
--- a/packages/coding-agent/test/agents-view-state.test.ts
+++ b/packages/coding-agent/test/agents-view-state.test.ts
@@ -213,7 +213,7 @@ describe("agents view state", () => {
expect(rows.map((row) => [row.title, row.kind])).toEqual([
["Parent", "agent"],
- ["2 subagents running", "subagent-summary"],
+ ["2 subagents running · 1 heartbeat active", "subagent-summary"],
["Other", "agent"],
]);
expect(rows.map((row) => row.runningSubagentCount)).toEqual([2, 2, 0]);
@@ -223,6 +223,42 @@ describe("agents view state", () => {
expect(rows[1]?.identity).not.toBe(rows[0]?.identity);
});
+ test("surfaces an idle retained subagent heartbeat while its parent is collapsed", () => {
+ const summaries = [
+ makeSummary({
+ id: "heartbeat-child",
+ activeSessionId: "heartbeat-child",
+ sessionId: "heartbeat-child-session",
+ sessionName: "Heartbeat child",
+ runtimeKind: "subagent",
+ parentActiveSessionId: "parent-active",
+ hasActiveHeartbeat: true,
+ activity: "idle",
+ messageCount: 2,
+ }),
+ makeSummary({
+ id: "parent-active",
+ activeSessionId: "parent-active",
+ sessionId: "parent-session",
+ sessionName: "Parent",
+ activity: "idle",
+ messageCount: 2,
+ }),
+ ];
+
+ const collapsed = buildAgentsViewRows(summaries);
+ expect(collapsed[1]).toMatchObject({
+ kind: "subagent-summary",
+ title: "1 subagent · 1 heartbeat active",
+ });
+ const expanded = buildAgentsViewRows(summaries, new Set([collapsed[0]?.identity ?? ""]));
+ expect(expanded[1]).toMatchObject({
+ kind: "subagent",
+ section: "heartbeats",
+ statusLabel: "heartbeat active",
+ });
+ });
+
test("expands subagent rows for expanded parents and collapses otherwise", () => {
const summaries = [
makeSummary({
diff --git a/packages/coding-agent/test/daemon-mode.test.ts b/packages/coding-agent/test/daemon-mode.test.ts
index 2507e82fb5..249f504010 100644
--- a/packages/coding-agent/test/daemon-mode.test.ts
+++ b/packages/coding-agent/test/daemon-mode.test.ts
@@ -242,6 +242,263 @@ describe("daemon mode helpers", () => {
expect(acceptAgentMessagePrompt.mock.calls[0]?.[0]).toContain("report current progress");
});
+ it("keeps RLM heartbeats active when a successful subagent is retained", async () => {
+ const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-daemon-retained-heartbeat-"));
+ try {
+ const sessionDir = join(tempDir, "sessions");
+ const parentManager = SessionManager.create(tempDir, sessionDir);
+ parentManager.newSession();
+ const parentSessionFile = parentManager.getSessionFile();
+ const parentArtifactDir = parentManager.getSessionArtifactDir();
+ if (!parentSessionFile || !parentArtifactDir) {
+ throw new Error("Missing parent session paths");
+ }
+ const childSessionDir = join(parentArtifactDir, "child-1");
+ const childManager = SessionManager.create(tempDir, childSessionDir);
+ childManager.newSession({ parentSession: parentSessionFile });
+ const childSessionFile = childManager.getSessionFile();
+ if (!childSessionFile) {
+ throw new Error("Missing child session file");
+ }
+
+ const daemon = new AgentDaemon(join(tempDir, "daemon.sock"), {
+ defaultSessionConfig: { agentDir: tempDir, cwd: tempDir, sessionDir },
+ createRuntime: async () => {
+ throw new Error("unexpected runtime creation");
+ },
+ });
+ const parentState = makeState("parent");
+ const parentSession = makeRuntimeSession(parentManager);
+ parentState.runtime = {
+ ...parentState.runtime,
+ metadata: { kind: "top-level", createdAt: 1 },
+ session: parentSession,
+ } as unknown as ActiveSessionState["runtime"];
+ const childState = makeState("child", parentState.activeSessionId);
+ childState.extensionUiRequests = new Map();
+ const childSession = makeRuntimeSession(childManager);
+ const promptHeartbeat = vi.fn(
+ async (_job: AgentCronJob, options?: { preflightResult?: (didSucceed: boolean) => void }) => {
+ options?.preflightResult?.(true);
+ },
+ );
+ Object.assign(childSession, {
+ isStreaming: false,
+ isCompacting: false,
+ isRetrying: false,
+ isBashRunning: false,
+ hasAcceptedPromptInFlight: false,
+ pendingMessageCount: 0,
+ promptHeartbeat,
+ });
+ childState.runtime = {
+ ...childState.runtime,
+ metadata: {
+ kind: "subagent",
+ createdAt: 2,
+ parentActiveSessionId: parentState.activeSessionId,
+ parentSessionId: parentSession.sessionId,
+ parentSessionFile,
+ rlmChildId: "child-1",
+ rlmParentNodeId: "child-1",
+ sessionDir: childSessionDir,
+ },
+ cwd: tempDir,
+ session: childSession,
+ dispose: vi.fn(async () => {}),
+ } as unknown as ActiveSessionState["runtime"];
+ const internals = daemon as unknown as {
+ cronStore: AgentCronJobStore;
+ cronScheduler: { runDue(now: Date): Promise<number> };
+ sessions: Map<string, ActiveSessionState>;
+ findRuntimeState: ReturnType<typeof vi.fn>;
+ closeSession(state: ActiveSessionState, reason: "shutdown"): Promise<void>;
+ createSubagentRuntimeHost(parent: ActiveSessionState): {
+ releaseRlmSubagentRuntime(
+ runtime: ActiveSessionState["runtime"],
+ options: CreateRlmSubagentRuntimeOptions,
+ status: "done" | "error" | "cancelled",
+ ): Promise<void>;
+ };
+ };
+ internals.findRuntimeState = vi.fn(() => childState);
+ const heartbeat = internals.cronStore.createRlmHeartbeat({
+ activeSessionId: childState.activeSessionId,
+ sessionId: childSession.sessionId,
+ sessionFile: childSessionFile,
+ cwd: tempDir,
+ runtimeKind: "subagent",
+ scheduleText: "every 30s",
+ prompt: "report exactly: hi",
+ now: new Date("2026-01-01T00:00:00.000Z"),
+ });
+ const releaseOptions = {
+ parentSession,
+ id: "child-1",
+ prompt: "initialize a heartbeat",
+ sessionName: "heartbeat-child",
+ sessionDir: childSessionDir,
+ rlmDepth: 1,
+ rlmMaxDepth: 4,
+ rlmParentNodeId: "child-1",
+ } as unknown as CreateRlmSubagentRuntimeOptions;
+
+ internals.sessions.set(childState.activeSessionId, childState);
+ await internals
+ .createSubagentRuntimeHost(parentState)
+ .releaseRlmSubagentRuntime(childState.runtime, releaseOptions, "done");
+
+ expect(internals.cronStore.list().find((job) => job.id === heartbeat.id)).toMatchObject({
+ status: "active",
+ runCount: 0,
+ });
+ expect(parentSession.retainFinishedRlmChildSession).toHaveBeenCalledWith("child-1", childSession);
+ const dueRuns = await internals.cronScheduler.runDue(new Date("2026-07-16T00:00:00.000Z"));
+ expect(dueRuns).toBe(1);
+ expect(promptHeartbeat).toHaveBeenCalledOnce();
+ expect(internals.cronStore.list().find((job) => job.id === heartbeat.id)).toMatchObject({
+ status: "active",
+ runCount: 1,
+ });
+
+ await internals.closeSession(childState, "shutdown");
+ expect(internals.cronStore.list().find((job) => job.id === heartbeat.id)).toMatchObject({
+ status: "active",
+ });
+ } finally {
+ rmSync(tempDir, { recursive: true, force: true });
+ }
+ });
+
+ it("defers RLM heartbeats while a subagent is binding", async () => {
+ const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-daemon-binding-heartbeat-"));
+ let releaseChildBinding: (() => void) | undefined;
+ try {
+ const sessionDir = join(tempDir, "sessions");
+ const parentManager = SessionManager.create(tempDir, sessionDir);
+ parentManager.newSession();
+ const parentSessionFile = parentManager.getSessionFile();
+ if (!parentSessionFile) {
+ throw new Error("Missing parent session file");
+ }
+ const childSessionDir = join(parentManager.getSessionArtifactDir() ?? tempDir, "child-1");
+ let markChildBindingStarted: (() => void) | undefined;
+ const childBindingStarted = new Promise<void>((resolve) => {
+ markChildBindingStarted = resolve;
+ });
+ const childBindingGate = new Promise<void>((resolve) => {
+ releaseChildBinding = resolve;
+ });
+ const promptHeartbeat = vi.fn(
+ async (_job: AgentCronJob, options?: { preflightResult?: (didSucceed: boolean) => void }) => {
+ options?.preflightResult?.(true);
+ },
+ );
+ const createRuntime = vi.fn(async (options: Parameters<CreateAgentSessionRuntimeFactory>[0]) => {
+ const session = makeRuntimeSession(options.sessionManager);
+ Object.assign(session, {
+ isStreaming: false,
+ isCompacting: false,
+ isRetrying: false,
+ isBashRunning: false,
+ hasAcceptedPromptInFlight: false,
+ pendingMessageCount: 0,
+ promptHeartbeat,
+ });
+ if (options.sessionOptions?.rlmSessionDir === childSessionDir) {
+ session.bindExtensions = vi.fn(async () => {
+ markChildBindingStarted?.();
+ await childBindingGate;
+ });
+ }
+ return {
+ session,
+ 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 },
+ createRuntime,
+ });
+ const internals = daemon as unknown as {
+ cronStore: AgentCronJobStore;
+ cronScheduler: { runDue(now: Date): Promise<number> };
+ sessions: Map<string, ActiveSessionState>;
+ createRuntime(command: Extract<DaemonCommand, { type: "create" }>): Promise<ActiveSessionState>;
+ createRlmSubagentRuntime(
+ parentState: ActiveSessionState,
+ options: CreateRlmSubagentRuntimeOptions,
+ ): Promise<ActiveSessionState["runtime"]>;
+ };
+ const parentState = await internals.createRuntime({ type: "create", sessionPath: parentSessionFile });
+ const childRuntimePromise = internals.createRlmSubagentRuntime(parentState, {
+ parentSession: parentState.runtime.session,
+ id: "child-1",
+ prompt: "initialize a heartbeat",
+ sessionName: "heartbeat-child",
+ sessionDir: childSessionDir,
+ model: {} as Model<Api>,
+ thinkingLevel: "off",
+ serviceTier: null,
+ scopedModels: [],
+ activeToolNames: [],
+ customTools: [],
+ includeGoals: false,
+ includeCompactSkill: false,
+ rlmDepth: 1,
+ rlmMaxDepth: 4,
+ rlmParentNodeId: "child-1",
+ });
+ await childBindingStarted;
+ const childState = [...internals.sessions.values()].find(
+ (state) => state.runtime.metadata.rlmChildId === "child-1",
+ );
+ const childSessionFile = childState?.runtime.session.sessionFile;
+ if (!childState || !childSessionFile) {
+ throw new Error("Missing binding child session");
+ }
+ const heartbeat = internals.cronStore.createRlmHeartbeat({
+ activeSessionId: childState.activeSessionId,
+ sessionId: childState.runtime.session.sessionId,
+ sessionFile: childSessionFile,
+ cwd: tempDir,
+ runtimeKind: "subagent",
+ scheduleText: "every 30s",
+ prompt: "report exactly: hi",
+ now: new Date("2026-01-01T00:00:00.000Z"),
+ });
+
+ expect(await internals.cronScheduler.runDue(new Date("2026-07-16T00:00:00.000Z"))).toBe(0);
+ expect(promptHeartbeat).not.toHaveBeenCalled();
+ expect(internals.cronStore.list().find((job) => job.id === heartbeat.id)).toMatchObject({
+ status: "active",
+ runCount: 0,
+ });
+
+ if (!releaseChildBinding) {
+ throw new Error("Missing child binding release");
+ }
+ releaseChildBinding();
+ releaseChildBinding = undefined;
+ await childRuntimePromise;
+ expect(await internals.cronScheduler.runDue(new Date("2027-01-01T00:00:00.000Z"))).toBe(1);
+ expect(promptHeartbeat).toHaveBeenCalledOnce();
+ expect(internals.cronStore.list().find((job) => job.id === heartbeat.id)).toMatchObject({
+ status: "active",
+ runCount: 1,
+ });
+ } finally {
+ releaseChildBinding?.();
+ rmSync(tempDir, { recursive: true, force: true });
+ }
+ });
+
it("closes the exact parent-scoped daemon runtime when a retained subagent is deleted", async () => {
const daemon = new AgentDaemon("/tmp/prime-agent-test.sock", {
defaultSessionConfig: { agentDir: "/tmp/prime-agent-test-agent", cwd: "/tmp" },
@@ -2877,6 +3134,147 @@ describe("daemon mode helpers", () => {
}
});
+ it("restores a completed subagent through its parent when an RLM heartbeat becomes due", async () => {
+ const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-daemon-restore-subagent-heartbeat-"));
+ try {
+ const sessionDir = join(tempDir, "sessions");
+ const parentManager = SessionManager.create(tempDir, sessionDir);
+ parentManager.newSession();
+ parentManager.appendSessionState({ status: "active" });
+ const parentSessionFile = parentManager.getSessionFile();
+ const parentArtifactDir = parentManager.getSessionArtifactDir();
+ if (!parentSessionFile || !parentArtifactDir) {
+ throw new Error("Missing parent session paths");
+ }
+
+ const childId = "heartbeat-child";
+ const childSessionDir = join(parentArtifactDir, childId);
+ const childManager = SessionManager.create(tempDir, childSessionDir);
+ childManager.newSession({ parentSession: parentSessionFile });
+ childManager.appendSessionInfo("heartbeat-child");
+ const childSessionFile = childManager.getSessionFile();
+ if (!childSessionFile) {
+ throw new Error("Missing child session file");
+ }
+ writeFileSync(
+ join(parentArtifactDir, "rlm-subagents.jsonl"),
+ `${JSON.stringify({
+ type: "rlm_subagent",
+ childId,
+ sessionName: "heartbeat-child",
+ sessionDir: childSessionDir,
+ sessionFile: childSessionFile,
+ parentSessionId: parentManager.getSessionId(),
+ parentSessionFile,
+ rlmDepth: 1,
+ rlmMaxDepth: 4,
+ rlmParentNodeId: childId,
+ status: "completed",
+ createdAt: 1,
+ updatedAt: "2026-01-01T00:00:00.000Z",
+ })}\n`,
+ );
+
+ 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 },
+ createRuntime,
+ });
+ const internals = daemon as unknown as {
+ cronStore: AgentCronJobStore;
+ getOrCreateCronJobSession(job: AgentCronJob, requirePersistedJob: boolean): Promise<ActiveSessionState>;
+ };
+ const heartbeat = internals.cronStore.createRlmHeartbeat({
+ activeSessionId: "stale-child-active-id",
+ sessionId: childManager.getSessionId(),
+ sessionFile: childSessionFile,
+ cwd: tempDir,
+ runtimeKind: "subagent",
+ scheduleText: "every 30s",
+ prompt: "report exactly: hi",
+ now: new Date("2026-01-01T00:00:00.000Z"),
+ });
+
+ const childState = await internals.getOrCreateCronJobSession(heartbeat, true);
+
+ expect(childState.runtime.metadata).toMatchObject({
+ kind: "subagent",
+ rlmChildId: childId,
+ });
+ expect(createRuntime).toHaveBeenCalledTimes(2);
+ expect(internals.cronStore.list().find((job) => job.id === heartbeat.id)).toMatchObject({
+ status: "active",
+ activeSessionId: childState.activeSessionId,
+ sessionId: childManager.getSessionId(),
+ });
+ } finally {
+ rmSync(tempDir, { recursive: true, force: true });
+ }
+ });
+
+ it("cancels a detached subagent heartbeat when its parent is archived", async () => {
+ const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-daemon-archived-subagent-heartbeat-"));
+ try {
+ const sessionDir = join(tempDir, "sessions");
+ const parentManager = SessionManager.create(tempDir, sessionDir);
+ parentManager.newSession();
+ parentManager.appendSessionState({ status: "archived" });
+ const parentSessionFile = parentManager.getSessionFile();
+ const parentArtifactDir = parentManager.getSessionArtifactDir();
+ if (!parentSessionFile || !parentArtifactDir) {
+ throw new Error("Missing parent session paths");
+ }
+ const childManager = SessionManager.create(tempDir, join(parentArtifactDir, "child-1"));
+ childManager.newSession({ parentSession: parentSessionFile });
+ const childSessionFile = childManager.getSessionFile();
+ if (!childSessionFile) {
+ throw new Error("Missing child session file");
+ }
+
+ const createRuntime = vi.fn(async () => {
+ throw new Error("archived parent must not be restored");
+ });
+ const daemon = new AgentDaemon(join(tempDir, "daemon.sock"), {
+ defaultSessionConfig: { agentDir: tempDir, cwd: tempDir, sessionDir },
+ createRuntime,
+ });
+ const internals = daemon as unknown as {
+ cronStore: AgentCronJobStore;
+ getOrCreateCronJobSession(
+ job: AgentCronJob,
+ requirePersistedJob: boolean,
+ ): Promise<ActiveSessionState | undefined>;
+ };
+ const heartbeat = internals.cronStore.createRlmHeartbeat({
+ activeSessionId: "stale-child-active-id",
+ sessionId: childManager.getSessionId(),
+ sessionFile: childSessionFile,
+ cwd: tempDir,
+ runtimeKind: "subagent",
+ scheduleText: "every 30s",
+ prompt: "report exactly: hi",
+ now: new Date("2026-01-01T00:00:00.000Z"),
+ });
+
+ await expect(internals.getOrCreateCronJobSession(heartbeat, true)).resolves.toBeUndefined();
+ expect(createRuntime).not.toHaveBeenCalled();
+ expect(internals.cronStore.list().find((job) => job.id === heartbeat.id)).toMatchObject({
+ status: "cancelled",
+ });
+ } finally {
+ rmSync(tempDir, { recursive: true, force: true });
+ }
+ });
+
it("rehydrates completed RLM subagents into the parent registry and durably deletes them", async () => {
const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-daemon-rlm-rehydrate-"));
try {
diff --git a/packages/coding-agent/test/daemon-session-list.test.ts b/packages/coding-agent/test/daemon-session-list.test.ts
index 2f86d486e0..393bf95f38 100644
--- a/packages/coding-agent/test/daemon-session-list.test.ts
+++ b/packages/coding-agent/test/daemon-session-list.test.ts
@@ -137,6 +137,40 @@ describe("buildSessionList", () => {
expect(entries[0]?.activity).toBe("idle");
});
+ it("marks a retained completed subagent with an active RLM heartbeat", () => {
+ const messages = [{ role: "user", content: "initialize a heartbeat" }] as unknown as AgentMessage[];
+ const entries = buildSessionList(
+ [
+ makeState({
+ activeSessionId: "parent",
+ sessionId: "parent-session",
+ messages,
+ }),
+ makeState({
+ activeSessionId: "child",
+ sessionId: "child-session",
+ sessionFile: "/tmp/child.jsonl",
+ messages,
+ metadata: {
+ kind: "subagent",
+ createdAt: 1,
+ parentActiveSessionId: "parent",
+ parentSessionId: "parent-session",
+ rlmChildId: "child-1",
+ },
+ }),
+ ],
+ [],
+ [makeCronJob({ id: "rlm-job", activeSessionId: "child", source: "rlm_heartbeat" })],
+ );
+
+ expect(entries.find((entry) => entry.id === "child")).toMatchObject({
+ runtimeKind: "subagent",
+ activity: "idle",
+ hasActiveHeartbeat: true,
+ });
+ });
+
it("merges active records with saved sessions and marks inactive sessions", () => {
const activePath = resolve("/tmp/project/active.jsonl");
const sleepingPath = resolve("/tmp/project/sleeping.jsonl");