A self-improving RLM agent for coding workflows and long-running autonomous tasks.
Rust
prevent stale heartbeats from reviving archived sessions (#372)
kted30145848c2
diff --git a/packages/coding-agent/CHANGELOG.md b/packages/coding-agent/CHANGELOG.mdindex 6f1d26bc2e..deef57a9bf 100644--- a/packages/coding-agent/CHANGELOG.md+++ b/packages/coding-agent/CHANGELOG.md@@ -4,6 +4,7 @@- Added `/btw` and `/side` for one-turn inline side questions that use the current context without changing the main session ([ENG-4509](https://linear.app/primeintellect/issue/ENG-4509/add-btw-and-side-side-question-flows)).- Changed the new-chat splash to show only version, model, and cwd metadata and rotate among five example prompts.+- Fixed stale heartbeat jobs reopening archived, deleted, or concurrently terminated sessions ([ENG-4519](https://linear.app/primeintellect/issue/ENG-4519/heartbeats-rebirth-sessions-that-were-previously-killed)).## [0.2.8] - 2026-07-09diff --git a/packages/coding-agent/src/core/session-manager.ts b/packages/coding-agent/src/core/session-manager.tsindex 0fb03d3f05..3b177bb7a0 100644--- a/packages/coding-agent/src/core/session-manager.ts+++ b/packages/coding-agent/src/core/session-manager.ts@@ -862,7 +862,7 @@ interface SessionInfoCacheEntry {// content: cache list metadata and rescan only files that changed.const sessionInfoCache = new Map<string, SessionInfoCacheEntry>();-async function buildSessionInfo(filePath: string): Promise<SessionInfo | null> {+export async function readSessionInfo(filePath: string): Promise<SessionInfo | null> {let stats: Awaited<ReturnType<typeof stat>>;try {stats = await stat(filePath);@@ -1021,7 +1021,7 @@ async function listSessionsFromDir(let loaded = 0;for (const file of files) {- const info = await buildSessionInfo(file);+ const info = await readSessionInfo(file);loaded++;callbacks?.onProgress?.(progressOffset + loaded, total);if (info) {diff --git a/packages/coding-agent/src/modes/daemon/daemon-mode.ts b/packages/coding-agent/src/modes/daemon/daemon-mode.tsindex aac19cbb04..5a10efbbc8 100644--- a/packages/coding-agent/src/modes/daemon/daemon-mode.ts+++ b/packages/coding-agent/src/modes/daemon/daemon-mode.ts@@ -77,7 +77,7 @@ import type {SubagentRuntimeHost,} from "../../core/rlm-runtime.js";import { deleteSessionFile } from "../../core/session-file-actions.js";-import { type SessionInfo, SessionManager } from "../../core/session-manager.js";+import { readSessionInfo, type SessionInfo, SessionManager } from "../../core/session-manager.js";import type { SessionStats } from "../../core/session-stats.js";import { type SideQuestionRun, startSideQuestion } from "../../core/side-question.js";import { killTrackedDetachedChildren } from "../../utils/shell.js";@@ -239,6 +239,10 @@ function delay(ms: number): Promise<void> {return new Promise((resolveDelay) => setTimeout(resolveDelay, ms));}+type RuntimeOpenGuard = () => boolean | Promise<boolean>;++class RuntimeOpenCancelledError extends Error {}+export async function runDaemonMode(options: DaemonModeOptions): Promise<never> {const socketPath = options.socketPath ?? defaultDaemonSocketPath();const daemon = new AgentDaemon(socketPath, options);@@ -404,6 +408,7 @@ export class AgentDaemon {name?: string,clientEnv?: Record<string, string>,onStateCreated?: (state: ActiveSessionState) => void,+ runtimeOpenGuard?: RuntimeOpenGuard,): Promise<ActiveSessionState> {const state: ActiveSessionState = {activeSessionId: createActiveSessionId(this.sessions),@@ -429,6 +434,9 @@ export class AgentDaemon {},subagentRuntimeHost: this.createSubagentRuntimeHost(state),});+ if (runtimeOpenGuard && !(await runtimeOpenGuard())) {+ throw new RuntimeOpenCancelledError();+ }} catch (error) {state.unsubscribe?.();this.sessions.delete(state.activeSessionId);@@ -468,7 +476,10 @@ export class AgentDaemon {this.rebindCronJobsToState(state);}- private async createRuntime(command: Extract<DaemonCommand, { type: "create" }>): Promise<ActiveSessionState> {+ private async createRuntime(+ command: Extract<DaemonCommand, { type: "create" }>,+ runtimeOpenGuard?: RuntimeOpenGuard,+ ): Promise<ActiveSessionState> {const config = mergeAgentSessionRuntimeConfig(this.options.defaultSessionConfig, command.config);if (!config.cwd) {throw new Error("Active session config is missing cwd");@@ -490,6 +501,9 @@ export class AgentDaemon {? SessionManager.continueRecent(cwd, config.sessionDir): SessionManager.create(cwd, config.sessionDir);const createState = async (): Promise<ActiveSessionState> => {+ if (runtimeOpenGuard && !(await runtimeOpenGuard())) {+ throw new RuntimeOpenCancelledError();+ }const existing = this.findSessionBySessionFile(sessionManager.getSessionFile());if (existing) {// A live runtime already owns this session file; reuse it instead of@@ -577,9 +591,19 @@ export class AgentDaemon {},}),);- return this.addRuntime(runtime, command.name, clientEnv, (state) => {- stateRef = state;- });+ if (runtimeOpenGuard && !(await runtimeOpenGuard())) {+ await runtime.dispose().catch(() => undefined);+ throw new RuntimeOpenCancelledError();+ }+ return this.addRuntime(+ runtime,+ command.name,+ clientEnv,+ (state) => {+ stateRef = state;+ },+ runtimeOpenGuard,+ );};const sessionFile = sessionManager.getSessionFile();@@ -591,7 +615,21 @@ export class AgentDaemon {if (pending) {// Same as the reuse path above: adopt-if-absent, never overwrite the// identity the racing creator's extensions already captured.- const state = await pending;+ let state: ActiveSessionState;+ try {+ state = await pending;+ } catch (error) {+ if (!runtimeOpenGuard && error instanceof RuntimeOpenCancelledError) {+ if (this.openingSessions.get(sessionKey) === pending) {+ this.openingSessions.delete(sessionKey);+ }+ return this.createRuntime(command);+ }+ throw error;+ }+ if (runtimeOpenGuard && !(await runtimeOpenGuard())) {+ throw new RuntimeOpenCancelledError();+ }if (command.name) {state.runtime.session.setSessionName(command.name);}@@ -614,18 +652,29 @@ export class AgentDaemon {if (this.updateRestartPreparing) {return "skipped";}- const state = await this.getOrCreateCronJobSession(job);- if (!state || this.updateRestartPreparing) {+ const requirePersistedJob = this.cronStore.list().some((candidate) => candidate.id === job.id);+ const dueJob = requirePersistedJob ? this.cronStore.getDueJob(job.id) : job;+ if (!dueJob) {+ return "skipped";+ }+ const state = await this.getOrCreateCronJobSession(dueJob, requirePersistedJob);+ const runnableJob = requirePersistedJob ? this.cronStore.getDueJob(job.id) : dueJob;+ if (+ !state ||+ !runnableJob ||+ this.updateRestartPreparing ||+ !this.isCronJobRunnableForState(runnableJob, state, requirePersistedJob)+ ) {return "skipped";}const session = state.runtime.session;const isAgentMessagePromptInProgress =this.agentMessageAcceptingTargets.has(state.activeSessionId) ||this.agentMessagePreparingTargets.has(state.activeSessionId);- if (isHeartbeatCronJob(job) && isAgentMessagePromptInProgress) {+ if (isHeartbeatCronJob(runnableJob) && isAgentMessagePromptInProgress) {return "skipped";}- if (shouldDeferHeartbeatCronJob(job, session)) {+ if (shouldDeferHeartbeatCronJob(runnableJob, session)) {return "skipped";}const shouldQueueCronPrompt =@@ -636,22 +685,41 @@ export class AgentDaemon {session.isBashRunning ||session.hasAcceptedPromptInFlight ||session.pendingMessageCount > 0;- if (!isHeartbeatCronJob(job) && shouldQueueCronPrompt) {- await session.followUp(job.prompt);+ if (!isHeartbeatCronJob(runnableJob) && shouldQueueCronPrompt) {+ if (!this.isCronJobRunnableForState(runnableJob, state, requirePersistedJob)) {+ return "skipped";+ }+ await session.followUp(runnableJob.prompt);return;}- if (isHeartbeatCronJob(job)) {- await this.promptHeartbeatWithAgentMessagePreparingGuard(state, job, {+ const getRunnableJob = (): AgentCronJob | undefined => {+ const current = requirePersistedJob ? this.cronStore.getDueJob(job.id) : runnableJob;+ return current && this.isCronJobRunnableForState(current, state, requirePersistedJob) ? current : undefined;+ };+ if (isHeartbeatCronJob(runnableJob)) {+ const didPrompt = await this.promptHeartbeatWithAgentMessagePreparingGuard(+ state,+ runnableJob,+ {+ streamingBehavior: "followUp",+ followUpQueueKey: `heartbeat:${runnableJob.id}`,+ source: "rpc",+ },+ getRunnableJob,+ );+ return didPrompt ? undefined : "skipped";+ }+ const canPrompt = () => getRunnableJob() !== undefined;+ const didPrompt = await this.promptWithAgentMessagePreparingGuard(+ state,+ runnableJob.prompt,+ {streamingBehavior: "followUp",- followUpQueueKey: `heartbeat:${job.id}`,source: "rpc",- });- return;- }- await this.promptWithAgentMessagePreparingGuard(state, job.prompt, {- streamingBehavior: "followUp",- source: "rpc",- });+ },+ canPrompt,+ );+ return didPrompt ? undefined : "skipped";}// Wraps session.prompt so the target counts as "preparing" until the turn@@ -662,42 +730,62 @@ export class AgentDaemon {state: ActiveSessionState,message: string,options?: PromptOptions,- ): Promise<void> {- await this.withAgentMessagePreparingGuard(state, (session) => {- const prompt =- options?.agentMessageId === undefined- ? session.prompt.bind(session)- : session.acceptAgentMessagePrompt.bind(session);- return prompt(message, {- ...options,- preflightResult: (didSucceed) => {- options?.preflightResult?.(didSucceed);- },- });- });+ canPrompt?: () => boolean,+ ): Promise<boolean> {+ return this.withAgentMessagePreparingGuard(+ state,+ (session) => {+ const prompt =+ options?.agentMessageId === undefined+ ? session.prompt.bind(session)+ : session.acceptAgentMessagePrompt.bind(session);+ return prompt(message, {+ ...options,+ preflightResult: (didSucceed) => {+ options?.preflightResult?.(didSucceed);+ },+ });+ },+ canPrompt,+ );}private async promptHeartbeatWithAgentMessagePreparingGuard(state: ActiveSessionState,job: AgentCronJob,options?: PromptOptions,- ): Promise<void> {- await this.withAgentMessagePreparingGuard(state, (session) =>- session.promptHeartbeat(job, {- ...options,- preflightResult: (didSucceed) => {- options?.preflightResult?.(didSucceed);- },- }),+ getPromptJob?: () => AgentCronJob | undefined,+ ): Promise<boolean> {+ let promptJob = job;+ return this.withAgentMessagePreparingGuard(+ state,+ (session) =>+ session.promptHeartbeat(promptJob, {+ ...options,+ preflightResult: (didSucceed) => {+ options?.preflightResult?.(didSucceed);+ },+ }),+ () => {+ if (!getPromptJob) {+ return true;+ }+ const current = getPromptJob();+ if (!current) {+ return false;+ }+ promptJob = current;+ return true;+ },);}private async withAgentMessagePreparingGuard(state: ActiveSessionState,run: (session: AgentSession) => Promise<void>,- ): Promise<void> {+ canRun?: () => boolean,+ ): Promise<boolean> {const activeSessionId = state.activeSessionId;- const session = state.runtime.session;this.agentMessagePreparingTargets.set(activeSessionId,(this.agentMessagePreparingTargets.get(activeSessionId) ?? 0) + 1,@@ -717,7 +805,12 @@ export class AgentDaemon {};try {await this.agentMessageTargetLocks.get(activeSessionId)?.catch(() => undefined);+ const session = state.runtime.session;+ if (canRun && !canRun()) {+ return false;+ }await run(session);+ return true;} finally {clearPreparing();}@@ -903,26 +996,102 @@ export class AgentDaemon {state.runtime.session.removeQueuedFollowUp(`heartbeat:${job.id}`);}- private async getOrCreateCronJobSession(job: AgentCronJob): Promise<ActiveSessionState | undefined> {+ private async getOrCreateCronJobSession(+ job: AgentCronJob,+ requirePersistedJob: boolean,+ ): Promise<ActiveSessionState | undefined> {if (this.updateRestartPreparing) {return undefined;}- const current = this.sessions.get(job.activeSessionId) ?? this.findSessionBySessionFile(job.sessionFile);+ const dueJob = requirePersistedJob ? this.cronStore.getDueJob(job.id) : job;+ if (!dueJob) {+ return undefined;+ }+ const activeIdMatch = this.sessions.get(dueJob.activeSessionId);+ const current =+ this.findSessionBySessionFile(dueJob.sessionFile) ??+ (!requirePersistedJob || activeIdMatch?.runtime.session.sessionId === dueJob.sessionId+ ? activeIdMatch+ : undefined);// A half-bound match falls through to createRuntime, which awaits the// pending create for the same session file instead of prompting mid-bind.if (current && !this.bindingSessions.has(current.activeSessionId)) {this.rebindCronJobsToState(current);- return current;+ const reboundJob = requirePersistedJob ? this.cronStore.getDueJob(job.id) : dueJob;+ return reboundJob && this.isCronJobRunnableForState(reboundJob, current, requirePersistedJob)+ ? current+ : undefined;+ }+ if (!requirePersistedJob) {+ return undefined;}- if (job.source === "rlm_heartbeat" && job.runtimeKind === "subagent") {+ if (dueJob.source === "rlm_heartbeat" && dueJob.runtimeKind === "subagent") {if (current && this.bindingSessions.has(current.activeSessionId)) {return undefined;}- this.cronStore.cancel(job.id);+ this.cronStore.cancel(dueJob.id);this.cronScheduler.wake();return undefined;}- return this.createRuntime({ type: "create", sessionPath: job.sessionFile });+ if (!(await this.isPersistedCronJobRunnable(dueJob.id))) {+ return undefined;+ }+ try {+ return await this.createRuntime({ type: "create", sessionPath: dueJob.sessionFile }, () =>+ this.isPersistedCronJobRunnable(dueJob.id),+ );+ } catch (error) {+ if (error instanceof RuntimeOpenCancelledError) {+ return undefined;+ }+ throw error;+ }+ }++ private async isPersistedCronJobRunnable(jobId: string): Promise<boolean> {+ for (let attempt = 0; attempt < 2; attempt++) {+ const job = this.cronStore.getDueJob(jobId);+ if (!job) {+ return false;+ }+ const sessionFile = resolve(job.sessionFile);+ const sessionInfo = await readSessionInfo(sessionFile);+ const current = this.cronStore.getDueJob(jobId);+ if (!current) {+ return false;+ }+ if (resolve(current.sessionFile) !== sessionFile || current.sessionId !== job.sessionId) {+ continue;+ }+ if (!sessionInfo || sessionInfo.id !== current.sessionId || sessionInfo.state?.status !== "active") {+ this.cancelScheduledJobsForSessionFile(current.sessionFile);+ return false;+ }+ return true;+ }+ return false;+ }++ private isCronJobRunnableForState(+ job: AgentCronJob,+ state: ActiveSessionState,+ requirePersistedJob: boolean,+ ): boolean {+ if (this.sessions.get(state.activeSessionId) !== state || this.closingSessions.has(state.activeSessionId)) {+ return false;+ }+ if (!requirePersistedJob) {+ return job.status === "active" && job.activeSessionId === state.activeSessionId;+ }+ const current = this.cronStore.getDueJob(job.id);+ const sessionFile = state.runtime.session.sessionFile;+ return (+ current !== undefined &&+ current.activeSessionId === state.activeSessionId &&+ current.sessionId === state.runtime.session.sessionId &&+ sessionFile !== undefined &&+ resolve(current.sessionFile) === resolve(sessionFile)+ );}private findSessionBySessionFile(sessionFile: string | undefined): ActiveSessionState | undefined {diff --git a/packages/coding-agent/test/suite/regressions/4519-heartbeat-rebirth.test.ts b/packages/coding-agent/test/suite/regressions/4519-heartbeat-rebirth.test.tsnew file mode 100644index 0000000000..6532cb3a26--- /dev/null+++ b/packages/coding-agent/test/suite/regressions/4519-heartbeat-rebirth.test.ts@@ -0,0 +1,318 @@+import { existsSync } from "node:fs";+import { join } from "node:path";+import { afterEach, describe, expect, it, vi } from "vitest";+import type { AgentSession } from "../../../src/core/agent-session.js";+import type { CreateAgentSessionRuntimeFactory } from "../../../src/core/agent-session-runtime.js";+import type { AgentCronJob, AgentCronJobStore, AgentCronScheduler } from "../../../src/core/cron-jobs.js";+import type { ActiveSessionState } from "../../../src/modes/daemon/active-session-state.js";+import { AgentDaemon } from "../../../src/modes/daemon/daemon-mode.js";+import { createHarness, type Harness } from "../harness.js";++type AgentDaemonCronInternals = {+ agentMessagePreparingTargets: Map<string, number>;+ agentMessageTargetLocks: Map<string, Promise<void>>;+ cronStore: AgentCronJobStore;+ cronScheduler: AgentCronScheduler;+ createRuntime(command: { type: "create"; sessionPath: string }): Promise<ActiveSessionState>;+ sessions: Map<string, ActiveSessionState>;+ runCronJob(job: AgentCronJob): Promise<"skipped" | undefined>;+ withAgentMessagePreparingGuard(+ state: ActiveSessionState,+ run: (session: AgentSession) => Promise<void>,+ canRun?: () => boolean,+ ): Promise<boolean>;+};++function createDaemon(harness: Harness, createRuntime: CreateAgentSessionRuntimeFactory): AgentDaemon {+ return new AgentDaemon(join(harness.tempDir, "daemon.sock"), {+ defaultSessionConfig: {+ agentDir: harness.tempDir,+ cwd: harness.tempDir,+ sessionDir: join(harness.tempDir, "sessions"),+ },+ createRuntime,+ });+}++function createDueHeartbeat(+ store: AgentCronJobStore,+ input: { activeSessionId: string; sessionId: string; sessionFile: string; cwd: string },+): AgentCronJob {+ return store.createHeartbeat({+ ...input,+ scheduleText: "every 10s",+ prompt: "continue scheduled work",+ now: new Date(Date.now() - 20_000),+ });+}++function runtimeResult(harness: Harness, cwd: string, agentDir: string) {+ return {+ session: harness.session,+ services: { cwd, agentDir } as never,+ diagnostics: [],+ extensionsResult: {} as never,+ };+}++async function waitForCondition(predicate: () => boolean): Promise<void> {+ for (let attempt = 0; attempt < 100; attempt++) {+ if (predicate()) {+ return;+ }+ await new Promise((resolve) => setTimeout(resolve, 0));+ }+ throw new Error("condition was not met");+}++describe("ENG-4519 heartbeat rebirth", () => {+ const harnesses: Harness[] = [];++ afterEach(() => {+ while (harnesses.length > 0) {+ harnesses.pop()?.cleanup();+ }+ });++ it("cancels legacy jobs instead of reopening an archived session", async () => {+ const harness = await createHarness({ persistSession: true });+ harnesses.push(harness);+ harness.sessionManager.appendSessionState({ status: "active" });+ harness.sessionManager.appendSessionState({ status: "archived" });+ const createRuntime = vi.fn<CreateAgentSessionRuntimeFactory>(async () => {+ throw new Error("archived sessions must not be reopened");+ });+ const daemon = createDaemon(harness, createRuntime);+ const internals = daemon as unknown as AgentDaemonCronInternals;+ const sessionFile = harness.session.sessionFile!;+ const heartbeat = createDueHeartbeat(internals.cronStore, {+ activeSessionId: "old-active",+ sessionId: harness.session.sessionId,+ sessionFile,+ cwd: harness.tempDir,+ });+ const pausedHeartbeat = internals.cronStore.createRlmHeartbeat({+ activeSessionId: "old-active",+ sessionId: harness.session.sessionId,+ sessionFile,+ cwd: harness.tempDir,+ scheduleText: "every 1m",+ prompt: "check internal work",+ now: new Date(),+ });+ internals.cronStore.updateRlmHeartbeat("old-active", pausedHeartbeat.id, { status: "pause" });++ await expect(internals.cronScheduler.runDue(new Date())).resolves.toBe(0);++ expect(createRuntime).not.toHaveBeenCalled();+ expect(internals.sessions.size).toBe(0);+ for (const id of [heartbeat.id, pausedHeartbeat.id]) {+ expect(internals.cronStore.list().find((job) => job.id === id)).toMatchObject({ status: "cancelled" });+ }+ });++ it("cancels a job without recreating its deleted session file", async () => {+ const harness = await createHarness({ persistSession: true });+ harnesses.push(harness);+ const createRuntime = vi.fn<CreateAgentSessionRuntimeFactory>(async () => {+ throw new Error("missing sessions must not be recreated");+ });+ const daemon = createDaemon(harness, createRuntime);+ const internals = daemon as unknown as AgentDaemonCronInternals;+ const sessionFile = join(harness.tempDir, "sessions", "deleted-session.jsonl");+ const heartbeat = createDueHeartbeat(internals.cronStore, {+ activeSessionId: "old-active",+ sessionId: "deleted-session",+ sessionFile,+ cwd: harness.tempDir,+ });++ await expect(internals.cronScheduler.runDue(new Date())).resolves.toBe(0);++ expect(createRuntime).not.toHaveBeenCalled();+ expect(existsSync(sessionFile)).toBe(false);+ expect(internals.sessions.size).toBe(0);+ expect(internals.cronStore.list().find((job) => job.id === heartbeat.id)).toMatchObject({+ status: "cancelled",+ });+ });++ it("stops opening a runtime when its heartbeat is cancelled in flight", async () => {+ const harness = await createHarness({ persistSession: true });+ harnesses.push(harness);+ harness.sessionManager.appendSessionState({ status: "active" });+ let releaseRuntime: () => void = () => {};+ const runtimeGate = new Promise<void>((resolve) => {+ releaseRuntime = resolve;+ });+ const createRuntime = vi.fn<CreateAgentSessionRuntimeFactory>(async ({ cwd, agentDir }) => {+ await runtimeGate;+ return runtimeResult(harness, cwd, agentDir);+ });+ const daemon = createDaemon(harness, createRuntime);+ const internals = daemon as unknown as AgentDaemonCronInternals;+ const heartbeat = createDueHeartbeat(internals.cronStore, {+ activeSessionId: "old-active",+ sessionId: harness.session.sessionId,+ sessionFile: harness.session.sessionFile!,+ cwd: harness.tempDir,+ });++ const run = internals.runCronJob(heartbeat);+ await waitForCondition(() => createRuntime.mock.calls.length > 0);+ expect(createRuntime).toHaveBeenCalledOnce();+ internals.cronStore.cancel(heartbeat.id);+ releaseRuntime();++ await expect(run).resolves.toBe("skipped");+ expect(internals.sessions.size).toBe(0);+ });++ it("records a heartbeat cancelled while waiting to prompt as skipped", async () => {+ const harness = await createHarness({ persistSession: true });+ harnesses.push(harness);+ harness.sessionManager.appendSessionState({ status: "active" });+ const promptHeartbeat = vi.spyOn(harness.session, "promptHeartbeat").mockResolvedValue();+ const createRuntime = vi.fn<CreateAgentSessionRuntimeFactory>(async ({ cwd, agentDir }) =>+ runtimeResult(harness, cwd, agentDir),+ );+ const daemon = createDaemon(harness, createRuntime);+ const internals = daemon as unknown as AgentDaemonCronInternals;+ const state = await internals.createRuntime({+ type: "create",+ sessionPath: harness.session.sessionFile!,+ });+ const heartbeat = createDueHeartbeat(internals.cronStore, {+ activeSessionId: state.activeSessionId,+ sessionId: harness.session.sessionId,+ sessionFile: harness.session.sessionFile!,+ cwd: harness.tempDir,+ });+ let releaseLock: () => void = () => {};+ const lock = new Promise<void>((resolve) => {+ releaseLock = resolve;+ });+ internals.agentMessageTargetLocks.set(state.activeSessionId, lock);++ const run = internals.cronScheduler.runDue(new Date());+ await waitForCondition(() => internals.agentMessagePreparingTargets.has(state.activeSessionId));+ internals.cronStore.cancel(heartbeat.id);+ releaseLock();++ await expect(run).resolves.toBe(0);+ expect(promptHeartbeat).not.toHaveBeenCalled();+ const storedHeartbeat = internals.cronStore.list().find((job) => job.id === heartbeat.id);+ expect(storedHeartbeat).toMatchObject({+ status: "cancelled",+ runCount: 0,+ });+ expect(storedHeartbeat?.lastRunAt).toBeUndefined();+ });++ it("uses an updated RLM heartbeat instruction after waiting to prompt", async () => {+ const harness = await createHarness({ persistSession: true });+ harnesses.push(harness);+ harness.sessionManager.appendSessionState({ status: "active" });+ const promptHeartbeat = vi.spyOn(harness.session, "promptHeartbeat").mockResolvedValue();+ const createRuntime = vi.fn<CreateAgentSessionRuntimeFactory>(async ({ cwd, agentDir }) =>+ runtimeResult(harness, cwd, agentDir),+ );+ const daemon = createDaemon(harness, createRuntime);+ const internals = daemon as unknown as AgentDaemonCronInternals;+ const state = await internals.createRuntime({+ type: "create",+ sessionPath: harness.session.sessionFile!,+ });+ const heartbeat = internals.cronStore.createRlmHeartbeat({+ activeSessionId: state.activeSessionId,+ sessionId: harness.session.sessionId,+ sessionFile: harness.session.sessionFile!,+ cwd: harness.tempDir,+ scheduleText: "every 10s",+ prompt: "old instruction",+ now: new Date(Date.now() - 20_000),+ });+ let releaseLock: () => void = () => {};+ const lock = new Promise<void>((resolve) => {+ releaseLock = resolve;+ });+ internals.agentMessageTargetLocks.set(state.activeSessionId, lock);++ const run = internals.cronScheduler.runDue(new Date());+ await waitForCondition(() => internals.agentMessagePreparingTargets.has(state.activeSessionId));+ internals.cronStore.updateRlmHeartbeat(state.activeSessionId, heartbeat.id, {+ prompt: "updated instruction",+ });+ releaseLock();++ await expect(run).resolves.toBe(1);+ expect(promptHeartbeat).toHaveBeenCalledWith(+ expect.objectContaining({ id: heartbeat.id, prompt: "updated instruction" }),+ expect.anything(),+ );+ });++ it("uses the current runtime session after waiting for a prompt lock", async () => {+ const original = await createHarness();+ const replacement = await createHarness();+ harnesses.push(original, replacement);+ const daemon = createDaemon(original, async () => {+ throw new Error("runtime creation is not expected");+ });+ const internals = daemon as unknown as AgentDaemonCronInternals;+ const activeSessionId = "active-session";+ const runtime = { session: original.session };+ const state = { activeSessionId, runtime } as unknown as ActiveSessionState;+ let releaseLock: () => void = () => {};+ const lock = new Promise<void>((resolve) => {+ releaseLock = resolve;+ });+ internals.agentMessageTargetLocks.set(activeSessionId, lock);+ let promptedSession: AgentSession | undefined;++ const guardedRun = internals.withAgentMessagePreparingGuard(+ state,+ async (session) => {+ promptedSession = session;+ },+ () => runtime.session === replacement.session,+ );+ await waitForCondition(() => internals.agentMessagePreparingTargets.has(activeSessionId));+ runtime.session = replacement.session;+ releaseLock();++ await expect(guardedRun).resolves.toBe(true);+ expect(promptedSession).toBe(replacement.session);+ });++ it("still restores and prompts a session explicitly persisted as active", async () => {+ const harness = await createHarness({ persistSession: true });+ harnesses.push(harness);+ harness.sessionManager.appendSessionState({ status: "active" });+ const promptHeartbeat = vi.spyOn(harness.session, "promptHeartbeat").mockResolvedValue();+ const createRuntime = vi.fn<CreateAgentSessionRuntimeFactory>(async ({ cwd, agentDir }) =>+ runtimeResult(harness, cwd, agentDir),+ );+ const daemon = createDaemon(harness, createRuntime);+ const internals = daemon as unknown as AgentDaemonCronInternals;+ const heartbeat = createDueHeartbeat(internals.cronStore, {+ activeSessionId: "old-active",+ sessionId: harness.session.sessionId,+ sessionFile: harness.session.sessionFile!,+ cwd: harness.tempDir,+ });++ await expect(internals.runCronJob(heartbeat)).resolves.toBeUndefined();++ expect(createRuntime).toHaveBeenCalledOnce();+ expect(internals.sessions.size).toBe(1);+ expect(promptHeartbeat).toHaveBeenCalledWith(+ expect.objectContaining({ id: heartbeat.id, prompt: "continue scheduled work" }),+ expect.objectContaining({+ streamingBehavior: "followUp",+ followUpQueueKey: `heartbeat:${heartbeat.id}`,+ source: "rpc",+ }),+ );+ });+});