A self-improving RLM agent for coding workflows and long-running autonomous tasks.
Rust
fix: heartbeat sessions are normal sessions — idle display and normal residency with durable wake (#1967)
Sebastian Müllerd72beaf9e346
diff --git a/packages/coding-agent/.changes/eng-5847-heartbeat-idle-status.md b/packages/coding-agent/.changes/eng-5847-heartbeat-idle-status.mdnew file mode 100644index 0000000000..ec19f21051--- /dev/null+++ b/packages/coding-agent/.changes/eng-5847-heartbeat-idle-status.md@@ -0,0 +1,5 @@+- Fixed sessions with armed heartbeats showing as Running forever in the agents view; between firings they now list as Idle with the heartbeat badge and a `heartbeat · next <time>` label.+- Added a dimmed heartbeat badge for sessions whose only heartbeats are paused.+- Added an armed-heartbeat warning to the agents-view delete confirmation for sessions and subagents.+- Changed sessions with armed heartbeats to passivate like any idle session; the daemon now wakes them when the next heartbeat is due, including after a daemon restart.+- Fixed heartbeats of passivated sessions disappearing from the heartbeat list and agents-view badges.diff --git a/packages/coding-agent/src/core/session-action-store.ts b/packages/coding-agent/src/core/session-action-store.tsindex 312479986f..937eea09a1 100644--- a/packages/coding-agent/src/core/session-action-store.ts+++ b/packages/coding-agent/src/core/session-action-store.ts@@ -350,7 +350,6 @@ export type IdleEvictionMinutes = number | "off";export interface SessionEvictionSnapshot {isSessionActive: boolean;attachedClients: number;- hasRegisteredHeartbeat: boolean;hasRegisteredCronJob: boolean;lastActivityAt: number;}@@ -367,6 +366,7 @@ export interface WorkerEvictionSnapshot {isStopping: boolean;hasOwnerClient: boolean;isPreparingUpdateRestart: boolean;+ hasWakeBlindSchedule: boolean;sessions: readonly SessionEvictionSnapshot[];}@@ -381,7 +381,6 @@ function isIdleEvictionThresholdMet(return (!session.isSessionActive &&session.attachedClients === 0 &&- !session.hasRegisteredHeartbeat &&!session.hasRegisteredCronJob &&Number.isFinite(session.lastActivityAt) &&now - session.lastActivityAt >= idleEvictionMinutes * 60_000@@ -414,6 +413,7 @@ export function canEvictWorker(worker.isStopping ||worker.hasOwnerClient ||worker.isPreparingUpdateRestart ||+ worker.hasWakeBlindSchedule ||worker.sessions.length === 0) {return false;diff --git a/packages/coding-agent/src/modes/agents-view/agents-view-mode.ts b/packages/coding-agent/src/modes/agents-view/agents-view-mode.tsindex d674c86d7f..abfb726614 100644--- a/packages/coding-agent/src/modes/agents-view/agents-view-mode.ts+++ b/packages/coding-agent/src/modes/agents-view/agents-view-mode.ts@@ -2541,7 +2541,8 @@ export class AgentsViewMode implements Component, Focusable {const details = row.section === "inactive" ? `${row.summary.messageCount} · ${age}` : age;const detailsWidth = row.section === "inactive" ? Math.max(10, visibleWidth(details)) : 10;const heartbeatBadge = !pendingDelete && !pendingKill ? formatHeartbeatBadge(row.heartbeat) : "";- const heartbeatCell = heartbeatBadge ? theme.fg("error", heartbeatBadge) : "";+ const heartbeatPausedOnly = (row.heartbeat?.activeCount ?? 0) < 1;+ const heartbeatCell = heartbeatBadge ? theme.fg(heartbeatPausedOnly ? "dim" : "error", heartbeatBadge) : "";const heartbeatWidth = visibleWidth(heartbeatBadge);const titleWidth = Math.max(0,@@ -2552,10 +2553,12 @@ export class AgentsViewMode implements Component, Focusable {2 -(heartbeatWidth > 0 ? heartbeatWidth + 1 : 0),);+ const armedHeartbeat = row.summary.hasActiveHeartbeat === true || (row.heartbeat?.activeCount ?? 0) > 0;+ const heartbeatWarning = armedHeartbeat ? "has an armed heartbeat — " : "";const title = pendingDelete- ? this.getPendingDeleteTitle()+ ? `${heartbeatWarning}${this.getPendingDeleteTitle()}`: pendingKill- ? `${keyText("app.agents.delete")} again to ${row.section === "running" ? "stop" : "delete"}`+ ? `${heartbeatWarning}${keyText("app.agents.delete")} again to ${row.section === "running" ? "stop" : "delete"}`: styleRowTitle(row);// Keep stable model information ahead of the variable summary so narrow rows truncate the summary first.const summaryText = !pendingDelete && !pendingKill ? row.summary.summary : undefined;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.tsindex 701f313634..52388973db 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@@ -8,6 +8,7 @@ export type AgentsViewSection = "running" | "idle" | "inactive";export interface UnifiedSessionHeartbeat {activeCount: number;+ pausedCount?: number;nextRunAt?: string;}@@ -94,13 +95,10 @@ export function classifyAgentsViewSession(summary: SessionSummary): AgentsViewSereturn summary.rosterStatus ?? classifySessionRosterStatus(summary);}-export function classifyUnifiedSession(record: Pick<UnifiedSessionRecord, "daemon" | "heartbeat">): AgentsViewSection {+export function classifyUnifiedSession(record: Pick<UnifiedSessionRecord, "daemon">): AgentsViewSection {if (!record.daemon) {return "inactive";}- if ((record.heartbeat?.activeCount ?? 0) > 0) {- return "running";- }return classifyAgentsViewSession(record.daemon);}@@ -202,7 +200,10 @@ export function reconcileUnifiedSessions(heartbeatByActiveId.get(daemon.activeSessionId ?? daemon.id) ??(daemon.hasActiveHeartbeat ? { activeCount: 1 } : undefined);const record: UnifiedSessionRecord = {- daemon: heartbeat && !daemon.hasActiveHeartbeat ? { ...daemon, hasActiveHeartbeat: true } : daemon,+ daemon:+ heartbeat && heartbeat.activeCount > 0 && !daemon.hasActiveHeartbeat+ ? { ...daemon, hasActiveHeartbeat: true }+ : daemon,identity: aliases[0]!,identityAliases: aliases,section: "idle",@@ -483,41 +484,59 @@ export function aggregateSessionHeartbeats(for (const summary of summaries) {for (const key of getSummaryKeys(summary)) summaryByKey.set(key, summary);}- const jobIdsByOwner = new Map<string, Set<string>>();+ const activeJobIdsByOwner = new Map<string, Set<string>>();+ const pausedJobIdsByOwner = new Map<string, Set<string>>();const nextRunByJob = new Map<string, string>();- const add = (owner: string, jobId: string): void => {- const ids = jobIdsByOwner.get(owner) ?? new Set<string>();+ const add = (byOwner: Map<string, Set<string>>, owner: string, jobId: string): void => {+ const ids = byOwner.get(owner) ?? new Set<string>();ids.add(jobId);- jobIdsByOwner.set(owner, ids);+ byOwner.set(owner, ids);};for (const heartbeat of heartbeats) {const job = heartbeat.job;- if (job.status !== "active") continue;- if (job.nextRunAt && Number.isFinite(Date.parse(job.nextRunAt))) nextRunByJob.set(job.id, job.nextRunAt);- let summary = summaryByKey.get(`active:${job.activeSessionId}`);+ if (job.status !== "active" && job.status !== "paused") continue;+ const byOwner = job.status === "active" ? activeJobIdsByOwner : pausedJobIdsByOwner;+ if (job.status === "active" && job.nextRunAt && Number.isFinite(Date.parse(job.nextRunAt))) {+ nextRunByJob.set(job.id, job.nextRunAt);+ }+ // Passivation stales the job's active id; session id and file still find the owning row.+ let summary: SessionSummary | undefined;+ for (const key of [`active:${job.activeSessionId}`, `session:${job.sessionId}`, fileIdentity(job.sessionFile)]) {+ summary = summaryByKey.get(key);+ if (summary) break;+ }const visited = new Set<string>();- if (!summary) add(job.activeSessionId, job.id);+ if (!summary) add(byOwner, job.activeSessionId, job.id);while (summary) {const owner = summary.activeSessionId ?? summary.id;if (visited.has(owner)) break;visited.add(owner);- add(owner, job.id);+ add(byOwner, owner, job.id);summary = findParentSummary(summary, summaryByKey);}}const result = new Map<string, UnifiedSessionHeartbeat>();- for (const [owner, jobIds] of jobIdsByOwner) {+ for (const owner of new Set([...activeJobIdsByOwner.keys(), ...pausedJobIdsByOwner.keys()])) {+ const jobIds = activeJobIdsByOwner.get(owner) ?? new Set<string>();+ const pausedCount = pausedJobIdsByOwner.get(owner)?.size ?? 0;const nextRunAt = [...jobIds].map((jobId) => nextRunByJob.get(jobId)).filter((value): value is string => value !== undefined).sort((a, b) => Date.parse(a) - Date.parse(b))[0];- result.set(owner, { activeCount: jobIds.size, ...(nextRunAt ? { nextRunAt } : {}) });+ result.set(owner, {+ activeCount: jobIds.size,+ ...(pausedCount > 0 ? { pausedCount } : {}),+ ...(nextRunAt ? { nextRunAt } : {}),+ });}return result;}export function formatHeartbeatBadge(heartbeat: UnifiedSessionHeartbeat | undefined, now = Date.now()): string {- if (!heartbeat || heartbeat.activeCount < 1) return "";+ if (!heartbeat) return "";+ if (heartbeat.activeCount < 1) {+ return (heartbeat.pausedCount ?? 0) > 0 ? `♥ ${heartbeat.pausedCount}` : "";+ }const next = heartbeat.nextRunAt ? Date.parse(heartbeat.nextRunAt) : Number.NaN;const countdown = Number.isFinite(next) ? formatHeartbeatCountdown(next - now) : undefined;return `♥ ${heartbeat.activeCount}${countdown ? `·${countdown}` : ""}`;@@ -672,7 +691,7 @@ export function buildAgentsViewRows(summary,title: getAgentsViewSessionTitle(summary),subtitle: getSessionSubtitle(summary),- statusLabel: getSessionStatusLabel(summary),+ statusLabel: getSessionStatusLabel(summary, record?.heartbeat),depth: 0,selectable: true,runningSubagentCount: 0,@@ -682,7 +701,6 @@ export function buildAgentsViewRows();const rowsByKey = buildRowKeyMap(baseRows);const childrenByParent = new Map<MutableAgentsViewRow, MutableAgentsViewRow[]>();- const parentByChild = new Map<MutableAgentsViewRow, MutableAgentsViewRow>();const nestedRows = new Set<MutableAgentsViewRow>();for (const row of baseRows) {@@ -697,7 +715,6 @@ export function buildAgentsViewRows(continue;}nestedRows.add(row);- parentByChild.set(row, parent);if (row.section === "running") {parent.runningSubagentCount += 1;}@@ -705,7 +722,6 @@ export function buildAgentsViewRows(siblings.push(row);childrenByParent.set(parent, siblings);}- propagateHeartbeatStateToAncestors(baseRows, parentByChild);const roots = baseRows.filter((row) => !nestedRows.has(row));const flattened: AgentsViewRow[] = [];@@ -748,25 +764,6 @@ function isUnifiedSessionRecord(value: SessionSummary | UnifiedSessionRecord): vreturn "identityAliases" in value;}-function propagateHeartbeatStateToAncestors(- rows: readonly MutableAgentsViewRow[],- parentByChild: ReadonlyMap<MutableAgentsViewRow, MutableAgentsViewRow>,-): void {- for (const row of rows) {- if (!row.summary.hasActiveHeartbeat) {- continue;- }- const visited = new Set<MutableAgentsViewRow>([row]);- let ancestor = parentByChild.get(row);- while (ancestor && !visited.has(ancestor)) {- visited.add(ancestor);- ancestor.section = "running";- ancestor.statusLabel = getSessionStatusLabel(ancestor.summary, true);- ancestor = parentByChild.get(ancestor);- }- }-}-type MutableAgentsViewRow = AgentsViewRow;function createSubagentSummaryRow(@@ -875,6 +872,13 @@ function compareAgentsViewRows(a: AgentsViewRow, b: AgentsViewRow): number {if (sectionDiff !== 0) {return sectionDiff;}+ if (a.section === "inactive") {+ const heartbeatDiff =+ Number(b.summary.hasActiveHeartbeat ?? false) - Number(a.summary.hasActiveHeartbeat ?? false);+ if (heartbeatDiff !== 0) {+ return heartbeatDiff;+ }+ }if (a.section !== "running") {const activityDiff = getTimestamp(b.summary.lastActivityAt) - getTimestamp(a.summary.lastActivityAt);if (activityDiff !== 0) {@@ -979,7 +983,7 @@ function getSessionSubtitle(summary: SessionSummary): string {return parts.join(" ");}-function getSessionStatusLabel(summary: SessionSummary, hasActiveHeartbeat = summary.hasActiveHeartbeat): string {+function getSessionStatusLabel(summary: SessionSummary, heartbeat?: UnifiedSessionHeartbeat): string {if (summary.statusLabel !== undefined) {return summary.statusLabel;}@@ -1016,8 +1020,11 @@ function getSessionStatusLabel(summary: SessionSummary, hasActiveHeartbeat = sumif (summary.lifecycle === "archived") {return "archived";}- if (hasActiveHeartbeat) {- return "heartbeat active";+ if (summary.hasActiveHeartbeat) {+ const next = heartbeat?.nextRunAt ? Date.parse(heartbeat.nextRunAt) : Number.NaN;+ return Number.isFinite(next)+ ? `heartbeat · next ${formatHeartbeatCountdown(next - Date.now())}`+ : "heartbeat active";}if (summary.runtimeKind === "subagent" && summary.repliedSinceTask) {return "replied";diff --git a/packages/coding-agent/src/modes/daemon/agent-roster.ts b/packages/coding-agent/src/modes/daemon/agent-roster.tsindex fe0f674ea9..e2d73c029f 100644--- a/packages/coding-agent/src/modes/daemon/agent-roster.ts+++ b/packages/coding-agent/src/modes/daemon/agent-roster.ts@@ -11,13 +11,12 @@ export interface AgentStatusInput {queuedChild: boolean;/** Actively working: streaming, running tools/bash, or running children. */busy: boolean;- hasActiveHeartbeat: boolean;}export function classifyAgentStatus(input: AgentStatusInput): AgentRosterStatus {if (input.queuedChild) return "running";if (!input.resident) return "inactive";- return input.busy || input.hasActiveHeartbeat ? "running" : "idle";+ return input.busy ? "running" : "idle";}export function isSessionSummaryBusy(@@ -27,17 +26,13 @@ export function isSessionSummaryBusy(}export function classifySessionRosterStatus(- summary: Pick<- SessionSummary,- "activeSessionId" | "activity" | "isSessionActive" | "hasRunningRlmChildren" | "hasActiveHeartbeat"- >,+ summary: Pick<SessionSummary, "activeSessionId" | "activity" | "isSessionActive" | "hasRunningRlmChildren">,queuedChild = false,): AgentRosterStatus {return classifyAgentStatus({resident: !!summary.activeSessionId,queuedChild,busy: summary.activity === "working" || isSessionSummaryBusy(summary),- hasActiveHeartbeat: summary.hasActiveHeartbeat === true,});}diff --git a/packages/coding-agent/src/modes/daemon/daemon-mode.ts b/packages/coding-agent/src/modes/daemon/daemon-mode.tsindex 1cfe6f0117..aa66982c26 100644--- a/packages/coding-agent/src/modes/daemon/daemon-mode.ts+++ b/packages/coding-agent/src/modes/daemon/daemon-mode.ts@@ -1531,6 +1531,32 @@ export class AgentDaemon {this.cronStore.recoverSessionArtifact(session.sessionId);this.cronScheduler.wake();}+ // A fresh worker only knows resident sessions' jobs; passive descendants' schedules must fire without hydration.+ if (state.runtime.metadata.kind !== "subagent") {+ void this.registerPassiveDescendantCronArtifacts().catch((error) => {+ this.log(`Could not register passive descendant scheduled jobs: ${String(error)}`);+ });+ }+ }++ private async registerPassiveDescendantCronArtifacts(): Promise<void> {+ let registered = false;+ for (const passive of await this.listPassiveRlmSubagents()) {+ try {+ const artifactDir = getSessionArtifactPathForFile(resolve(passive.entry.sessionFile), passive.info.id);+ if (this.cronStore.registerSessionArtifact(passive.info.id, artifactDir)) {+ registered = true;+ this.cronStore.recoverSessionArtifact(passive.info.id);+ }+ } catch (error) {+ this.log(+ `Could not register scheduled jobs for passive subagent ${passive.entry.childId}: ${String(error)}`,+ );+ }+ }+ if (registered) {+ this.cronScheduler.wake();+ }}private async createRuntime(@@ -2641,7 +2667,6 @@ export class AgentDaemon {return {isSessionActive: summary.isSessionActive || summary.hasRunningRlmChildren === true || hasPendingAdmission,attachedClients: state.clients.size + state.pendingAttaches,- hasRegisteredHeartbeat: jobs.some((job) => isHeartbeatCronJob(job) && job.status === "active"),hasRegisteredCronJob: jobs.some((job) => !isHeartbeatCronJob(job)),lastActivityAt: Date.parse(summary.lastActivityAt ?? ""),hasParent: state.runtime.metadata.kind === "subagent" && !!state.runtime.metadata.parentActiveSessionId,@@ -5386,9 +5411,6 @@ export class AgentDaemon {activity: session.isSessionActive ? "working" : "idle",isSessionActive: session.isSessionActive,hasRunningRlmChildren: session.hasRunningRlmChildren?.() ?? false,- hasActiveHeartbeat:- this.cronStore.getHeartbeat(state.activeSessionId)?.status === "active" ||- this.cronStore.listRlmHeartbeats(state.activeSessionId).some((job) => job.status === "active"),isStreaming: session.isStreaming,} as SessionSummary),...(metadata.rlmChildId ? { rlmChildId: metadata.rlmChildId } : {}),diff --git a/packages/coding-agent/src/modes/daemon/daemon-session-list.ts b/packages/coding-agent/src/modes/daemon/daemon-session-list.tsindex 6155d703f6..07144dfc0a 100644--- a/packages/coding-agent/src/modes/daemon/daemon-session-list.ts+++ b/packages/coding-agent/src/modes/daemon/daemon-session-list.ts@@ -140,7 +140,6 @@ export function isEvictableEmptySessionSummary(summary: SessionSummary): booleansummary.messageCount === 0 &&!summary.sessionName &&!isSessionSummaryBusy(summary) &&- summary.hasRegisteredHeartbeat !== true &&summary.hasRegisteredCronJob !== true);}diff --git a/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts b/packages/coding-agent/src/modes/daemon/daemon-supervisor.tsindex b5afde5da3..90194ec478 100644--- a/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts+++ b/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts@@ -1,6 +1,15 @@import { type ChildProcess, spawn } from "node:child_process";import { createHash, randomBytes, randomUUID } from "node:crypto";-import { chmodSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";+import {+ chmodSync,+ existsSync,+ mkdirSync,+ readdirSync,+ readFileSync,+ renameSync,+ rmSync,+ writeFileSync,+} from "node:fs";import { createServer, type Server, type Socket } from "node:net";import { basename, dirname, join, resolve } from "node:path";import { Writable } from "node:stream";@@ -31,6 +40,7 @@ import {import {type AgentCronJob,AgentCronJobStore,+ isHeartbeatCronJob,migrateLegacyCronJobsToSessionArtifacts,SESSION_SCHEDULED_JOBS_FILENAME,} from "../../core/cron-jobs.js";@@ -199,6 +209,9 @@ const IDLE_EVICTION_MAX_SWEEP_INTERVAL_MS = 5 * 60_000;const IDLE_EVICTION_MIN_SWEEP_INTERVAL_MS = 60_000;const IDLE_EVICTION_DRAIN_TIMEOUT_MS = 5_000;const CHILD_PASSIVATION_PER_WORKER_CAP = 2;+const SCHEDULED_WAKE_RETRY_MS = 60_000;+const SCHEDULED_WAKE_MAX_TIMEOUT_MS = 2_147_483_647;+const SCHEDULED_WAKE_CLIENT_ID = "scheduled-wake";const SUPERVISOR_CONFIG_FILE_NAME = "supervisor-config";const WORKER_STARTUP_GATE_FD = 3;@@ -717,6 +730,10 @@ export class DaemonSupervisor {private idleEvictionTimer?: ReturnType<typeof setTimeout>;private idleEvictionSweep?: Promise<void>;private idleEvictionFence?: Promise<void>;+ private scheduledWakeTimer?: ReturnType<typeof setTimeout>;+ private scheduledWakeRecompute?: Promise<void>;+ private scheduledWakeRecomputeQueued = false;+ private readonly scheduledWakeFailures = new Map<string, number>();constructor(private readonly socketPath: string,@@ -819,6 +836,7 @@ export class DaemonSupervisor {this.scheduleOwnedWorkerCleanup(worker);}this.scheduleIdleEvictionSweep();+ this.scheduleScheduledSessionWakeRecompute();this.rosterWatchdogTimer = setInterval(() => this.sweepRosterStaleness(), ROSTER_WATCHDOG_INTERVAL_MS);this.rosterWatchdogTimer.unref();this.assertSocketLeaseHeld();@@ -870,6 +888,159 @@ export class DaemonSupervisor {this.rosterWatchdogTimer = undefined;}+ private clearScheduledWakeTimer(): void {+ if (!this.scheduledWakeTimer) return;+ clearTimeout(this.scheduledWakeTimer);+ this.scheduledWakeTimer = undefined;+ }++ // The supervisor only wakes non-resident trees; firing and delivery stay worker-owned.+ private scheduleScheduledSessionWakeRecompute(): void {+ if (this.shuttingDown) return;+ if (this.scheduledWakeRecompute) {+ this.scheduledWakeRecomputeQueued = true;+ return;+ }+ this.scheduledWakeRecompute = this.recomputeScheduledSessionWake()+ .catch((error) => this.log(`Scheduled-session wake recompute failed: ${String(error)}`))+ .finally(() => {+ this.scheduledWakeRecompute = undefined;+ if (this.scheduledWakeRecomputeQueued) {+ this.scheduledWakeRecomputeQueued = false;+ this.scheduleScheduledSessionWakeRecompute();+ }+ });+ }++ /** Durable truth: the ledger family (fork headers stripped) plus each session's scheduled-jobs artifact. */+ private async collectPassiveScheduledJobs(+ includeInactive = false,+ ): Promise<Array<{ rootSessionFile: string; job: AgentCronJob; info: SessionInfo }>> {+ const pendingCancelRoots = new Set<string>();+ for (const intent of this.collectEphemeralCancelIntents()) {+ const context = this.workerSessionArtifactContext(intent);+ if (!context || !intent.descriptor.rootSessionId) continue;+ try {+ await this.cancelScheduledJobsForSessionTree(intent.descriptor.rootSessionId, context.sessionFile);+ this.deleteWorkerDescriptor(intent);+ } catch {+ // Still owned until the cancel lands; the tree stays excluded below.+ pendingCancelRoots.add(canonicalSessionPath(context.sessionFile));+ }+ }+ const infos = await this.rlmSpawnLedger().family();+ const infoByPath = new Map(infos.map((info) => [canonicalSessionPath(info.path), info] as const));+ const storeBySessionId = new Map<string, AgentCronJobStore>();+ const infoBySessionId = new Map<string, SessionInfo>();+ for (const info of infos) {+ if (info.state !== undefined && info.state.status !== "active") continue;+ const artifactDir = getSessionArtifactPathForFile(resolve(info.path), info.id);+ if (!existsSync(join(artifactDir, SESSION_SCHEDULED_JOBS_FILENAME))) continue;+ const store = AgentCronJobStore.forSessionArtifacts();+ store.registerSessionArtifact(info.id, artifactDir);+ storeBySessionId.set(info.id, store);+ infoBySessionId.set(info.id, info);+ }+ if (infoBySessionId.size === 0) return [];+ const uncoveredRootFor = (info: SessionInfo): string | undefined => {+ let current = info;+ const visited = new Set([canonicalSessionPath(current.path)]);+ while (true) {+ try {+ if (this.findWorkerBySessionFile(current.path)) return undefined;+ } catch {+ return undefined;+ }+ if (!current.parentSessionPath) break;+ const parent = infoByPath.get(canonicalSessionPath(current.parentSessionPath));+ if (!parent || visited.has(canonicalSessionPath(parent.path))) break;+ visited.add(canonicalSessionPath(parent.path));+ current = parent;+ }+ return current.path;+ };+ const results: Array<{ rootSessionFile: string; job: AgentCronJob; info: SessionInfo }> = [];+ for (const [artifactSessionId, store] of storeBySessionId) {+ let jobs: AgentCronJob[];+ try {+ jobs = store.list();+ } catch (error) {+ this.log(`Skipping unreadable scheduled jobs for session ${artifactSessionId}: ${String(error)}`);+ continue;+ }+ for (const job of jobs) {+ if (!includeInactive && job.status !== "active" && job.status !== "paused") continue;+ const info = infoBySessionId.get(job.sessionId);+ if (!info) continue;+ const rootSessionFile = uncoveredRootFor(info);+ if (rootSessionFile === undefined) continue;+ if (pendingCancelRoots.has(canonicalSessionPath(rootSessionFile))) continue;+ results.push({ rootSessionFile, job, info });+ }+ }+ return results;+ }++ private async recomputeScheduledSessionWake(): Promise<void> {+ if (this.shuttingDown || this.updateRestartPhase !== undefined) return;+ const candidates = await this.collectPassiveScheduledJobs();+ this.clearScheduledWakeTimer();+ if (this.shuttingDown || this.updateRestartPhase !== undefined) return;+ const now = Date.now();+ const wakeTimes: number[] = [];+ const candidateRoots = new Set(candidates.map(({ rootSessionFile }) => canonicalSessionPath(rootSessionFile)));+ for (const root of [...this.scheduledWakeFailures.keys()]) {+ if (!candidateRoots.has(root)) this.scheduledWakeFailures.delete(root);+ }+ for (const { rootSessionFile, job } of candidates) {+ if (job.status !== "active" || job.nextRunAt === undefined) continue;+ const runAt = Date.parse(job.nextRunAt);+ if (!Number.isFinite(runAt)) continue;+ // The failure floor keeps an overdue job off a hot retry loop.+ const failedAt = this.scheduledWakeFailures.get(canonicalSessionPath(rootSessionFile));+ wakeTimes.push(failedAt !== undefined ? Math.max(runAt, failedAt + SCHEDULED_WAKE_RETRY_MS) : runAt);+ }+ if (wakeTimes.length === 0) return;+ const delay = Math.min(Math.max(0, Math.min(...wakeTimes) - now), SCHEDULED_WAKE_MAX_TIMEOUT_MS);+ this.scheduledWakeTimer = setTimeout(() => {+ this.scheduledWakeTimer = undefined;+ void this.wakeDueScheduledSessions().catch((error) =>+ this.log(`Scheduled-session wake failed: ${String(error)}`),+ );+ }, delay);+ this.scheduledWakeTimer.unref();+ }++ private async wakeDueScheduledSessions(now = Date.now()): Promise<void> {+ // Disarmed during update-restart preparation; the phase transition or next boot re-arms once.+ if (this.shuttingDown || this.updateRestartPhase !== undefined) {+ this.clearScheduledWakeTimer();+ return;+ }+ try {+ const due = new Map<string, string>();+ for (const { rootSessionFile, job } of await this.collectPassiveScheduledJobs()) {+ if (job.status !== "active" || job.nextRunAt === undefined) continue;+ const runAt = Date.parse(job.nextRunAt);+ if (!Number.isFinite(runAt) || runAt > now) continue;+ due.set(canonicalSessionPath(rootSessionFile), rootSessionFile);+ }+ for (const [rootKey, sessionPath] of due) {+ if (this.shuttingDown || this.updateRestartPhase !== undefined) return;+ try {+ await this.createOrReuseWorker(SCHEDULED_WAKE_CLIENT_ID, { type: "create", sessionPath });+ this.scheduledWakeFailures.delete(rootKey);+ this.log(`Woke session worker for a due scheduled job: ${sessionPath}`);+ } catch (error) {+ this.scheduledWakeFailures.set(rootKey, Date.now());+ this.log(`Scheduled wake failed for ${sessionPath}: ${String(error)}`);+ }+ }+ } finally {+ this.scheduleScheduledSessionWakeRecompute();+ }+ }+private scheduleIdleEvictionSweep(): void {if (this.shuttingDown || this.idleEvictionTimer || this.idleEvictionSweep) return;const delayMs = idleEvictionSweepIntervalMs(this.settingsManager.getIdleEvictionMinutes());@@ -894,6 +1065,7 @@ export class DaemonSupervisor {hasOwnerClient: worker.descriptor.ownerClientId !== undefined,isPreparingUpdateRestart:this.updateRestartPhase !== undefined || worker.updateRestartPrepareClient !== undefined,+ hasWakeBlindSchedule: this.isWakeBlindScheduledWorker(worker),sessions: this.workerRosterEntries(worker).filter((entry) => !entry.queuedChild).map(sessionSummaryFromRosterEntry)@@ -902,7 +1074,6 @@ export class DaemonSupervisor {return {isSessionActive: isSessionSummaryBusy(summary),attachedClients: this.attachedClientCount(summary, activeSessionId),- hasRegisteredHeartbeat: summary.hasRegisteredHeartbeat === true,hasRegisteredCronJob: summary.hasRegisteredCronJob === true,lastActivityAt: Date.parse(summary.lastActivityAt ?? ""),};@@ -910,6 +1081,18 @@ export class DaemonSupervisor {};}+ /** A schedule whose root file sits outside the enumerable sessions root is invisible to the wake scan; keep it resident. */+ private isWakeBlindScheduledWorker(worker: ResidentWorker): boolean {+ const sessionFile = worker.descriptor.sessionFile ?? worker.descriptor.createCommand.sessionPath;+ const agentDir = this.defaultSessionConfig.agentDir;+ if (!sessionFile || !agentDir) return false;+ const sessionsRoot = canonicalSessionPath(this.defaultSessionConfig.sessionDir ?? getSessionsDir(agentDir));+ if (dirname(canonicalSessionPath(sessionFile)) === sessionsRoot) return false;+ return this.workerRosterEntries(worker).some(+ (entry) => entry.summary.hasRegisteredHeartbeat === true || entry.summary.hasRegisteredCronJob === true,+ );+ }+private async runIdleEvictionSweep(now = Date.now()): Promise<void> {if (this.shuttingDown || this.updateRestartPhase !== undefined || this.idleEvictionFence) return;await this.settingsManager.reload();@@ -1063,7 +1246,8 @@ export class DaemonSupervisor {this.shuttingDown ||this.updateRestartPhase !== undefined ||this.workers.get(worker.descriptor.workerId) !== worker ||- this.isWorkerStopping(worker)+ this.isWorkerStopping(worker) ||+ this.isWakeBlindScheduledWorker(worker)) {return false;}@@ -1155,6 +1339,32 @@ export class DaemonSupervisor {}}+ /** Trees whose ephemeral-stop cancel failed stay owned until a retry lands: tombstoned client-owned descriptors with no resident worker. */+ private collectEphemeralCancelIntents(): Array<{ descriptor: DaemonWorkerDescriptor; descriptorPath: string }> {+ const intents: Array<{ descriptor: DaemonWorkerDescriptor; descriptorPath: string }> = [];+ let names: string[];+ try {+ names = readdirSync(this.descriptorDir);+ } catch {+ return intents;+ }+ for (const name of names) {+ if (name === SUPERVISOR_CONFIG_FILE_NAME || !name.endsWith(".json")) continue;+ const descriptorPath = join(this.descriptorDir, name);+ let descriptor: unknown;+ try {+ descriptor = JSON.parse(readFileSync(descriptorPath, "utf8"));+ } catch {+ continue;+ }+ if (!isDaemonWorkerDescriptor(descriptor, this.socketPath)) continue;+ if (descriptor.stopRequestedAt === undefined || descriptor.ownerClientId === undefined) continue;+ if (this.workers.has(descriptor.workerId)) continue;+ intents.push({ descriptor, descriptorPath });+ }+ return intents;+ }+private loadPersistedSupervisorConfig(): AgentSessionRuntimeConfig | undefined {try {const parsed = JSON.parse(@@ -1203,7 +1413,7 @@ export class DaemonSupervisor {renameSync(tempPath, worker.descriptorPath);}- private deleteWorkerDescriptor(worker: ResidentWorker): void {+ private deleteWorkerDescriptor(worker: { descriptorPath: string; descriptor: DaemonWorkerDescriptor }): void {try {rmSync(worker.descriptorPath, { force: true });rmSync(worker.descriptor.recoveryJournalPath, { force: true });@@ -2072,6 +2282,9 @@ export class DaemonSupervisor {jobs.set(job.id, job);}}+ for (const { job } of await this.collectPassiveScheduledJobs(command.includeInactive === true)) {+ if (!jobs.has(job.id)) jobs.set(job.id, job);+ }return success(command.id, "cron_list", { jobs: sortCronJobs([...jobs.values()]) });}case "heartbeats_list": {@@ -2119,6 +2332,15 @@ export class DaemonSupervisor {heartbeats.set(heartbeat.job.id, heartbeat);}}+ // Passivated sessions keep their armed heartbeats; no worker can list them.+ for (const { job, info } of await this.collectPassiveScheduledJobs()) {+ if (!isHeartbeatCronJob(job) || heartbeats.has(job.id)) continue;+ heartbeats.set(job.id, {+ job,+ ...(info.name !== undefined ? { sessionName: info.name } : {}),+ ...(info.firstMessage !== undefined ? { firstMessage: info.firstMessage } : {}),+ });+ }return success(command.id, "heartbeats_list", { heartbeats: [...heartbeats.values()] });}case "heartbeat_manage": {@@ -2128,6 +2350,24 @@ export class DaemonSupervisor {heartbeat.job.id === command.jobId && heartbeat.job.activeSessionId === command.activeSessionId,),);+ if (!cachedWorker) {+ // Passive jobs are managed against their durable store; no wake just to flip a status.+ const passive = (await this.collectPassiveScheduledJobs()).find(+ ({ job }) => job.id === command.jobId && job.activeSessionId === command.activeSessionId,+ );+ if (passive) {+ const store = AgentCronJobStore.forSessionArtifacts();+ store.registerSessionArtifact(+ passive.info.id,+ getSessionArtifactPathForFile(resolve(passive.info.path), passive.info.id),+ );+ const heartbeat = store.manageHeartbeat(command.activeSessionId, command.jobId, command.action);+ if (heartbeat) {+ this.broadcastHeartbeatsChanged();+ return success(command.id, "heartbeat_manage", { heartbeat });+ }+ }+ }const worker = cachedWorker ?? (await this.findWorkerForClient(client, command.activeSessionId)).worker;this.assertWorkerAccessibleToClient(client, worker, command.activeSessionId);const response = await this.forwardToWorker(worker, command);@@ -2184,6 +2424,19 @@ export class DaemonSupervisor {return this.forwardToWorker(candidate.worker, command);}}+ const passive = (await this.collectPassiveScheduledJobs()).find(({ job }) => job.id === command.jobId);+ if (passive) {+ const store = AgentCronJobStore.forSessionArtifacts();+ store.registerSessionArtifact(+ passive.info.id,+ getSessionArtifactPathForFile(resolve(passive.info.path), passive.info.id),+ );+ const job = store.cancel(command.jobId);+ if (job) {+ this.broadcastHeartbeatsChanged();+ return success(command.id, "cron_cancel", { job });+ }+ }throw new Error(`No cron job found: ${command.jobId}`);}case "heartbeat_get": {@@ -4245,7 +4498,13 @@ export class DaemonSupervisor {this.roster().delete(entry.agentId);continue;}- this.writeRosterEntry(passivatedWorkerRosterEntry(entry));+ // Registration marks survive eviction: passive rows still have schedules behind them.+ this.writeRosterEntry(+ passivatedWorkerRosterEntry(entry, {+ hasRegisteredHeartbeat: entry.summary.hasRegisteredHeartbeat === true,+ hasRegisteredCronJob: entry.summary.hasRegisteredCronJob === true,+ }),+ );}}@@ -4620,11 +4879,12 @@ export class DaemonSupervisor {});}- private findWorkerBySessionFile(sessionFile: string): ResidentWorker | undefined {+ private findWorkerBySessionFile(sessionFile: string, exclude?: ResidentWorker): ResidentWorker | undefined {const target = canonicalSessionPath(sessionFile);const targetEntry = this.roster().bySessionFile(target);const matches = new Set<ResidentWorker>();for (const worker of this.workers.values()) {+ if (worker === exclude) continue;// The roster is the one live ownership source; the stale pull cache must not resurrect a match.const summaryMatches = targetEntry?.workerId === worker.descriptor.workerId;const descriptorPath = worker.descriptor.sessionFile@@ -5760,6 +6020,7 @@ export class DaemonSupervisor {return manifest;} catch (error) {this.updateRestartPhase = undefined;+ this.scheduleScheduledSessionWakeRecompute();throw error;}}@@ -6143,9 +6404,16 @@ export class DaemonSupervisor {assertStopStillApplies();}this.invalidateWorkerSessionInputPauses(worker, "Session worker stopped while input was paused");+ // Client-owned schedules die with the registration, like their roster rows. Cancel+ // before the worker leaves the map, so no recompute sees the tree uncovered mid-stop.+ let ephemeralCancelSettled = true;+ if (removeDescriptor && worker.descriptor.ownerClientId !== undefined) {+ ephemeralCancelSettled = await this.cancelEphemeralWorkerScheduledJobs(worker);+ }this.workers.delete(worker.descriptor.workerId);this.flipWorkerRosterEntriesInactive(worker);- if (removeDescriptor) {+ // A failed cancel keeps the stop tombstone as the durable intent; the enumeration retry or the next boot finishes it.+ if (removeDescriptor && ephemeralCancelSettled) {this.deleteWorkerDescriptor(worker);}if (!this.shuttingDown) {@@ -6268,6 +6536,79 @@ export class DaemonSupervisor {}}+ private async cancelScheduledJobsForSessionTree(+ rootSessionId: string,+ rootSessionFile: string,+ stillWanted?: () => boolean,+ exclude?: ResidentWorker,+ ): Promise<void> {+ const store = AgentCronJobStore.forSessionArtifacts();+ const sessions = [{ sessionId: rootSessionId, sessionFile: rootSessionFile }];+ const childrenByParent = new Map<string, SessionInfo[]>();+ for (const info of await this.rlmSpawnLedger().family()) {+ if (!info.parentSessionPath) continue;+ const key = canonicalSessionPath(info.parentSessionPath);+ childrenByParent.set(key, [...(childrenByParent.get(key) ?? []), info]);+ }+ const queue = [canonicalSessionPath(rootSessionFile)];+ const visited = new Set(queue);+ while (queue.length > 0) {+ for (const info of childrenByParent.get(queue.shift()!) ?? []) {+ const child = canonicalSessionPath(info.path);+ if (visited.has(child)) continue;+ visited.add(child);+ sessions.push({ sessionId: info.id, sessionFile: info.path });+ queue.push(child);+ }+ }+ // A worker covering any tree member owns its stores again; a stale intent must not kill new schedules.+ for (const { sessionFile } of sessions) {+ try {+ if (this.findWorkerBySessionFile(sessionFile, exclude)) return;+ } catch {+ return;+ }+ }+ let registered = false;+ for (const { sessionId, sessionFile } of sessions) {+ const artifactDir = getSessionArtifactPathForFile(sessionFile, sessionId);+ if (!existsSync(join(artifactDir, SESSION_SCHEDULED_JOBS_FILENAME))) continue;+ store.registerSessionArtifact(sessionId, artifactDir);+ registered = true;+ }+ if (!registered) return;+ // Re-checked in the same synchronous turn as the walk: a promotion committed during the family read keeps its schedules.+ if (stillWanted && !stillWanted()) return;+ for (const { sessionFile } of sessions) {+ store.cancelJobsForSession({ sessionFile });+ }+ }++ private async cancelEphemeralWorkerScheduledJobs(worker: ResidentWorker): Promise<boolean> {+ const context = this.workerSessionArtifactContext(worker);+ if (!context || !worker.descriptor.rootSessionId) {+ return true;+ }+ try {+ await this.cancelScheduledJobsForSessionTree(+ worker.descriptor.rootSessionId,+ context.sessionFile,+ () => worker.descriptor.ownerClientId !== undefined,+ worker,+ );+ return true;+ } catch (error) {+ // A promotion that landed during the failed read means the cancel is no longer wanted.+ if (worker.descriptor.ownerClientId === undefined) {+ return true;+ }+ this.log(+ `Could not cancel scheduled jobs for client-owned worker ${worker.descriptor.workerId}: ${String(error)}`,+ );+ return false;+ }+ }+private reclaimStoppedWorkerCronLock(worker: ResidentWorker): void {const context = this.workerSessionArtifactContext(worker);if (!context) {@@ -6276,9 +6617,9 @@ export class DaemonSupervisor {rmSync(join(context.artifactDir, `${SESSION_SCHEDULED_JOBS_FILENAME}.lock`), { recursive: true, force: true });}- private workerSessionArtifactContext(- worker: ResidentWorker,- ): { sessionFile: string; artifactDir: string } | undefined {+ private workerSessionArtifactContext(worker: {+ descriptor: DaemonWorkerDescriptor;+ }): { sessionFile: string; artifactDir: string } | undefined {const sessionFile = worker.descriptor.sessionFile ?? worker.descriptor.createCommand.sessionPath;if (!sessionFile || !worker.descriptor.rootSessionId) {return undefined;@@ -6301,6 +6642,7 @@ export class DaemonSupervisor {}private broadcastHeartbeatsChanged(): void {+ this.scheduleScheduledSessionWakeRecompute();for (const client of this.clients) {this.write(client, { type: "heartbeats_changed" });}@@ -6396,6 +6738,7 @@ export class DaemonSupervisor {private async cleanupSupervisorResourcesOnce(): Promise<void> {this.shuttingDown = true;this.clearIdleEvictionTimer();+ this.clearScheduledWakeTimer();this.clearRosterWatchdogTimer();await this.idleEvictionSweep?.catch(() => undefined);for (const cleanup of this.signalCleanupHandlers.splice(0)) {@@ -6496,6 +6839,7 @@ export class DaemonSupervisor {}this.shuttingDown = true;this.clearIdleEvictionTimer();+ this.clearScheduledWakeTimer();this.clearRosterWatchdogTimer();await this.idleEvictionSweep?.catch(() => undefined);if (closingReason) {diff --git a/packages/coding-agent/src/modes/interactive/components/subagent-summary-line.ts b/packages/coding-agent/src/modes/interactive/components/subagent-summary-line.tsindex 0d8b7b44b0..1f228fa82f 100644--- a/packages/coding-agent/src/modes/interactive/components/subagent-summary-line.ts+++ b/packages/coding-agent/src/modes/interactive/components/subagent-summary-line.ts@@ -13,10 +13,7 @@ export interface SubagentSummaryCounts {inactive: number;}-export function classifySubagentSnapshotStatus(- child: AgentConnectionRlmChildAgentSnapshot,- activeHeartbeatSessionIds: ReadonlySet<string>,-): AgentRosterStatus {+export function classifySubagentSnapshotStatus(child: AgentConnectionRlmChildAgentSnapshot): AgentRosterStatus {// Activity implies a live session; the in-process connection never stamps activeSessionId.const resident = child.activeSessionId !== undefined || child.activity !== undefined;const busy = child.status === "running" || child.status === "queued" || child.activity !== undefined;@@ -24,20 +21,18 @@ export function classifySubagentSnapshotStatus(resident,queuedChild: !resident && busy,busy,- hasActiveHeartbeat: child.activeSessionId !== undefined && activeHeartbeatSessionIds.has(child.activeSessionId),});}export function countDirectSubagentStatuses(children: Iterable<AgentConnectionRlmChildAgentSnapshot>,parentId: string | undefined,- activeHeartbeatSessionIds: ReadonlySet<string>,): SubagentSummaryCounts {const counts: SubagentSummaryCounts = { total: 0, running: 0, idle: 0, inactive: 0 };for (const child of children) {if (child.parentId !== parentId || child.status === "cancelled") continue;counts.total += 1;- counts[classifySubagentSnapshotStatus(child, activeHeartbeatSessionIds)] += 1;+ counts[classifySubagentSnapshotStatus(child)] += 1;}return counts;}@@ -45,18 +40,13 @@ export function countDirectSubagentStatuses(export function countRosterSubagentStatuses(summaries: Iterable<SessionSummary>,parent: { activeSessionId?: string | undefined; sessionId?: string | undefined; sessionFile?: string | undefined },- activeHeartbeatSessionIds: ReadonlySet<string>,): SubagentSummaryCounts {const counts: SubagentSummaryCounts = { total: 0, running: 0, idle: 0, inactive: 0 };for (const child of summaries) {if (child.runtimeKind !== "subagent" || child.lifecycle !== "live") continue;if (!isDirectAgentChild(child, parent)) continue;counts.total += 1;- const status =- child.activeSessionId !== undefined && activeHeartbeatSessionIds.has(child.activeSessionId)- ? "running"- : (child.rosterStatus ?? classifySessionRosterStatus(child));- counts[status] += 1;+ counts[child.rosterStatus ?? classifySessionRosterStatus(child)] += 1;}return counts;}diff --git a/packages/coding-agent/src/modes/interactive/interactive-mode.ts b/packages/coding-agent/src/modes/interactive/interactive-mode.tsindex 358cbb17cb..84d0019b0f 100644--- a/packages/coding-agent/src/modes/interactive/interactive-mode.ts+++ b/packages/coding-agent/src/modes/interactive/interactive-mode.ts@@ -6017,11 +6017,6 @@ export class InteractiveMode {}private updateSubagentSummaryLine(): void {- const activeHeartbeatSessionIds = new Set(- this.heartbeatCatalog- .filter((heartbeat) => heartbeat.job.status === "active")- .map((heartbeat) => heartbeat.job.activeSessionId),- );const rosterSummaries = this.rosterBar?.summaries();// A client-owned session has no row on the public roster; only then do the// snapshots carry the bar. A public parent with zero roster children shows zero.@@ -6029,16 +6024,12 @@ export class InteractiveMode {rosterSummaries?.some((row) => row.sessionId === this.connectionState?.sessionId) === true;this.subagentSummaryLine.setSubagentCounts(rosterSummaries && sessionOnRoster- ? countRosterSubagentStatuses(- rosterSummaries,- {- activeSessionId: this.connectionState?.activeSessionId,- sessionId: this.connectionState?.sessionId,- sessionFile: this.connectionState?.sessionFile,- },- activeHeartbeatSessionIds,- )- : countDirectSubagentStatuses(this.subagentSnapshots.values(), this.rlmNodeId, activeHeartbeatSessionIds),+ ? countRosterSubagentStatuses(rosterSummaries, {+ activeSessionId: this.connectionState?.activeSessionId,+ sessionId: this.connectionState?.sessionId,+ sessionFile: this.connectionState?.sessionFile,+ })+ : countDirectSubagentStatuses(this.subagentSnapshots.values(), this.rlmNodeId),);if (!this.subagentSummaryLine.isSelectable() && this.subagentSummaryLine.focused) this.focusEditor();}diff --git a/packages/coding-agent/test/agent-roster.test.ts b/packages/coding-agent/test/agent-roster.test.tsindex 0ea00f88e3..f050abb2e4 100644--- a/packages/coding-agent/test/agent-roster.test.ts+++ b/packages/coding-agent/test/agent-roster.test.ts@@ -36,35 +36,20 @@ describe("classifyAgentStatus", () => {it("classifies once and both surface adapters agree with it", () => {// The formula's three defining rows: a queued child runs before any session// exists, nothing else resurrects a non-resident agent, residents split on work.- expect(classifyAgentStatus({ resident: false, queuedChild: true, busy: false, hasActiveHeartbeat: false })).toBe(- "running",- );- expect(classifyAgentStatus({ resident: false, queuedChild: false, busy: true, hasActiveHeartbeat: true })).toBe(- "inactive",- );- expect(classifySubagentSnapshotStatus({ ...childFor(false, false), status: "queued" }, new Set())).toBe(- "running",- );+ expect(classifyAgentStatus({ resident: false, queuedChild: true, busy: false })).toBe("running");+ expect(classifyAgentStatus({ resident: false, queuedChild: false, busy: true })).toBe("inactive");+ expect(classifySubagentSnapshotStatus({ ...childFor(false, false), status: "queued" })).toBe("running");for (const busy of [false, true]) {+ const expected = classifyAgentStatus({ resident: true, queuedChild: false, busy });+ expect(expected).toBe(busy ? "running" : "idle");for (const heartbeat of [false, true]) {- const expected = classifyAgentStatus({- resident: true,- queuedChild: false,- busy,- hasActiveHeartbeat: heartbeat,- });- expect(expected).toBe(busy || heartbeat ? "running" : "idle");- const heartbeatIds = new Set(heartbeat ? ["as-1"] : []);expect(classifySessionRosterStatus(summaryFor(true, busy, heartbeat)), `busy=${busy} hb=${heartbeat}`).toBe(expected,);- expect(- classifySubagentSnapshotStatus(childFor(true, busy), heartbeatIds),- `busy=${busy} hb=${heartbeat}`,- ).toBe(expected);}+ expect(classifySubagentSnapshotStatus(childFor(true, busy)), `busy=${busy}`).toBe(expected);}- expect(classifySessionRosterStatus(summaryFor(false, false, false))).toBe("inactive");- expect(classifySubagentSnapshotStatus(childFor(false, false), new Set())).toBe("inactive");+ expect(classifySessionRosterStatus(summaryFor(false, false, true))).toBe("inactive");+ expect(classifySubagentSnapshotStatus(childFor(false, false))).toBe("inactive");});});diff --git a/packages/coding-agent/test/agents-view-mode.test.ts b/packages/coding-agent/test/agents-view-mode.test.tsindex d471269723..b4a30cdac1 100644--- a/packages/coding-agent/test/agents-view-mode.test.ts+++ b/packages/coding-agent/test/agents-view-mode.test.ts@@ -1,4 +1,5 @@import { setKeybindings } from "@earendil-works/pi-tui";+import stripAnsi from "strip-ansi";import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";import { KeybindingsManager } from "../src/core/keybindings.js";import type { ModelRegistry } from "../src/core/model-registry.js";@@ -15,11 +16,12 @@ import {import {type AgentsViewRow,buildAgentsViewRows,+ reconcileUnifiedSessions,resolveAgentsViewLeftResult,} from "../src/modes/agents-view/agents-view-state.js";import type { SessionSummary } from "../src/modes/daemon/daemon-session-list.js";import type { InteractiveModeUiServices } from "../src/modes/interactive/interactive-mode-services.js";-import { stopThemeWatcher } from "../src/modes/interactive/theme/theme.js";+import { stopThemeWatcher, theme } from "../src/modes/interactive/theme/theme.js";const modeMocks = vi.hoisted(() => ({interactiveRun: vi.fn<() => Promise<never>>(),@@ -685,6 +687,60 @@ describe("AgentsViewMode", () => {stopThemeWatcher();}});++ it("dims a paused-only heartbeat badge and keeps active badges in the error color", () => {+ const job = (status: "active" | "paused") => ({+ job: {+ id: `${status}-job`,+ status,+ activeSessionId: "scope-active",+ sessionId: "scope-session",+ sessionFile: "/tmp/scope.jsonl",+ cwd: "/tmp",+ prompt: "tick",+ schedule: { kind: "interval" as const, expression: "5m" },+ createdAt: "2026-01-01T00:00:00Z",+ updatedAt: "2026-01-01T00:00:00Z",+ runCount: 0,+ },+ });+ const view = new AgentsViewMode({ config: {}, uiServices: createUiServices() }, {});++ try {+ const [pausedRow] = buildAgentsViewRows(reconcileUnifiedSessions([summary()], [], [job("paused")]));+ Reflect.set(view, "rows", [pausedRow]);+ const pausedLine = invoke("renderRow", view, pausedRow, 160) as string;+ expect(pausedLine).toContain(theme.fg("dim", "♥ 1"));+ expect(pausedRow).toMatchObject({ section: "idle" });++ const [activeRow] = buildAgentsViewRows(reconcileUnifiedSessions([summary()], [], [job("active")]));+ Reflect.set(view, "rows", [activeRow]);+ const activeLine = invoke("renderRow", view, activeRow, 160) as string;+ expect(activeLine).toContain(theme.fg("error", "♥ 1"));+ } finally {+ stopThemeWatcher();+ }+ });++ it("warns about the armed heartbeat in the delete confirmation", () => {+ const view = new AgentsViewMode({ config: {}, uiServices: createUiServices() }, {});+ Reflect.set(view, "deleteConfirmExpiresAt", Date.now() + 10_000);+ const confirmLine = (row: AgentsViewRow): string => {+ Reflect.set(view, "rows", [row]);+ Reflect.set(view, "pendingDeleteAgent", { identity: row.identity, summary: row.summary, stopped: false });+ return stripAnsi(invoke("renderRow", view, row, 160) as string);+ };++ try {+ const [armedRow] = buildAgentsViewRows([summary({ hasActiveHeartbeat: true })]);+ expect(confirmLine(armedRow!)).toContain("has an armed heartbeat — ");+ const [plainRow] = buildAgentsViewRows([summary()]);+ expect(confirmLine(plainRow!)).not.toContain("armed heartbeat");+ expect(confirmLine(plainRow!)).toContain("again to remove");+ } finally {+ stopThemeWatcher();+ }+ });});function createUiServices(): InteractiveModeUiServices {diff --git a/packages/coding-agent/test/agents-view-state.test.ts b/packages/coding-agent/test/agents-view-state.test.tsindex c0a0303b50..970f0cebfb 100644--- a/packages/coding-agent/test/agents-view-state.test.ts+++ b/packages/coding-agent/test/agents-view-state.test.ts@@ -49,11 +49,11 @@ import { formatAgentDepthLabel } from "../src/modes/interactive/interactive-modeimport type { InteractiveModeUiServices } from "../src/modes/interactive/interactive-mode-services.js";import type { Theme } from "../src/modes/interactive/theme/theme.js";-function heartbeat(id: string, nextRunAt?: string, activeSessionId = "child") {+function heartbeat(id: string, nextRunAt?: string, activeSessionId = "child", status: "active" | "paused" = "active") {return {job: {id,- status: "active" as const,+ status,activeSessionId,sessionId: `${activeSessionId}-session`,sessionFile: `/tmp/${activeSessionId}.jsonl`,@@ -109,19 +109,19 @@ describe("agents view state", () => {expect(classifyAgentsViewSession(makeSummary({ activity: "idle", taskState: undefined }))).toBe("idle");});- test("active heartbeats make sessions Running regardless of current activity", () => {+ test("armed heartbeats stay Idle between firings; only real work is Running", () => {expect(classifyAgentsViewSession(makeSummary({ activity: "working", hasActiveHeartbeat: true }))).toBe("running");expect(classifyAgentsViewSession(makeSummary({ activity: "idle", taskState: "completed", hasActiveHeartbeat: true })),- ).toBe("running");+ ).toBe("idle");const [row] = buildAgentsViewRows([makeSummary({ activity: "idle", hasActiveHeartbeat: true })]);- expect(row).toMatchObject({ section: "running", statusLabel: "heartbeat active" });+ expect(row).toMatchObject({ section: "idle", statusLabel: "heartbeat active" });const [busyRow] = buildAgentsViewRows([makeSummary({ activity: "working", hasActiveHeartbeat: true, isStreaming: true, isRunningTools: true }),]);expect(busyRow).toMatchObject({ section: "running", statusLabel: "running tools" });- expect(sectionTitle("running")).toBe("Running");+ expect(sectionTitle("idle")).toBe("Idle");});test("labels replied subagents with active heartbeats as heartbeat active", () => {@@ -143,7 +143,7 @@ describe("agents view state", () => {const expanded = buildAgentsViewRows(summaries, new Set([collapsed[0]?.identity ?? ""]));expect(expanded.find((row) => row.title === "Replied child")).toMatchObject({- section: "running",+ section: "idle",statusLabel: "heartbeat active",});});@@ -189,8 +189,8 @@ describe("agents view state", () => {}),]);- expect(rows.map((row) => row.title)).toEqual(["newer working", "older working", "heartbeat", "completed"]);- expect(rows.map((row) => row.section)).toEqual(["running", "running", "running", "idle"]);+ expect(rows.map((row) => row.title)).toEqual(["newer working", "older working", "completed", "heartbeat"]);+ expect(rows.map((row) => row.section)).toEqual(["running", "running", "idle", "idle"]);});test("keeps row order stable when activity and modification times and daemon input order change", () => {@@ -279,6 +279,29 @@ describe("agents view state", () => {expect(rows.map((row) => row.section)).toEqual(["running", "idle", "idle", "idle"]);});+ test("armed heartbeats rank first within the inactive section", () => {+ const rows = buildAgentsViewRows([+ makeSummary({+ id: "recent",+ activeSessionId: undefined,+ sessionId: "recent",+ sessionName: "recent",+ lastActivityAt: "2026-01-03T00:00:00Z",+ }),+ makeSummary({+ id: "beating",+ activeSessionId: undefined,+ sessionId: "beating",+ sessionName: "beating",+ hasActiveHeartbeat: true,+ lastActivityAt: "2026-01-01T00:00:00Z",+ }),+ ]);++ expect(rows.map((row) => row.section)).toEqual(["inactive", "inactive"]);+ expect(rows.map((row) => row.summary.sessionId)).toEqual(["beating", "recent"]);+ });+test("summarizes subagents on their parent and omits subagent rows", () => {const rows = buildAgentsViewRows([makeSummary({@@ -373,25 +396,25 @@ describe("agents view state", () => {const collapsed = buildAgentsViewRows(summaries);expect(collapsed[0]).toMatchObject({kind: "agent",- section: "running",- statusLabel: "heartbeat active",+ section: "idle",+ statusLabel: "completed",});expect(collapsed[1]).toMatchObject({kind: "subagent-summary",- section: "running",- title: "1 subagent running · 1 heartbeat active",- runningSubagentCount: 1,+ section: "idle",+ title: "1 subagent · 1 heartbeat active",+ runningSubagentCount: 0,});const expanded = buildAgentsViewRows(summaries, new Set([collapsed[0]?.identity ?? ""]));expect(expanded[1]).toMatchObject({ kind: "subagent-summary", expanded: true });expect(expanded[2]).toMatchObject({kind: "subagent",- section: "running",+ section: "idle",statusLabel: "heartbeat active",});});- test("counts every idle heartbeating subagent as running", () => {+ test("keeps idle heartbeating subagents out of the running count", () => {const heartbeatChildren = Array.from({ length: 10 }, (_, index) =>makeSummary({id: `heartbeat-child-${index}`,@@ -425,15 +448,15 @@ describe("agents view state", () => {}),]);- expect(rows[0]).toMatchObject({ section: "running", runningSubagentCount: 11 });+ expect(rows[0]).toMatchObject({ section: "idle", runningSubagentCount: 1 });expect(rows[1]).toMatchObject({kind: "subagent-summary",- title: "11 subagents running · 10 heartbeats active",- runningSubagentCount: 11,+ title: "1 subagent running · 10 heartbeats active",+ runningSubagentCount: 1,});});- test("propagates a descendant heartbeat through completed subagent ancestors", () => {+ test("leaves completed ancestors idle while a descendant heartbeat is armed", () => {const summaries = [makeSummary({id: "heartbeat-grandchild",@@ -469,8 +492,8 @@ describe("agents view state", () => {const rootIdentity = buildAgentsViewRows(summaries)[0]?.identity ?? "";const oneLevel = buildAgentsViewRows(summaries, new Set([rootIdentity]));const child = oneLevel.find((row) => row.title === "Child");- expect(oneLevel[0]).toMatchObject({ section: "running", statusLabel: "heartbeat active" });- expect(child).toMatchObject({ section: "running", statusLabel: "heartbeat active" });+ expect(oneLevel[0]).toMatchObject({ section: "idle", statusLabel: "completed" });+ expect(child).toMatchObject({ section: "idle", statusLabel: "completed" });const childIdentity = child?.identity ?? "";const expanded = buildAgentsViewRows(summaries, new Set([rootIdentity, childIdentity]));@@ -479,9 +502,9 @@ describe("agents view state", () => {.filter((row) => row.kind === "agent" || row.kind === "subagent").map((row) => [row.title, row.section, row.statusLabel]),).toEqual([- ["Root", "running", "heartbeat active"],- ["Child", "running", "heartbeat active"],- ["Heartbeat grandchild", "running", "heartbeat active"],+ ["Root", "idle", "completed"],+ ["Child", "idle", "completed"],+ ["Heartbeat grandchild", "idle", "heartbeat active"],]);});@@ -1075,7 +1098,7 @@ describe("agents view state", () => {test("shows a fallback heartbeat count while catalog details are unavailable", () => {const [record] = reconcileUnifiedSessions([makeSummary({ hasActiveHeartbeat: true })], []);- expect(record).toMatchObject({ section: "running", heartbeat: { activeCount: 1 } });+ expect(record).toMatchObject({ section: "idle", heartbeat: { activeCount: 1 } });expect(formatHeartbeatBadge(record?.heartbeat)).toBe("♥ 1");});@@ -1125,8 +1148,8 @@ describe("agents view state", () => {expect(aggregates.get("child")).toEqual({ activeCount: 2, nextRunAt: "2026-01-01T00:05:00Z" });expect(aggregates.get("parent")).toEqual({ activeCount: 2, nextRunAt: "2026-01-01T00:05:00Z" });const rows = buildAgentsViewRows(reconcileUnifiedSessions([parent, child], [], [heartbeat("one")]));- expect(rows[0]).toMatchObject({ section: "running", heartbeat: { activeCount: 1 } });- expect(rows[1]).toMatchObject({ title: "1 subagent running · 1 heartbeat active" });+ expect(rows[0]).toMatchObject({ section: "idle", heartbeat: { activeCount: 1 } });+ expect(rows[1]).toMatchObject({ title: "1 subagent · 1 heartbeat active" });expect(formatHeartbeatBadge(aggregates.get("parent"), Date.parse("2026-01-01T00:00:00Z"))).toBe("♥ 2·5m");expect(formatHeartbeatBadge(@@ -1154,6 +1177,26 @@ describe("agents view state", () => {Date.parse("2026-01-01T00:00:00Z"),),).toBe("♥ 1·1s");++ const soonRows = buildAgentsViewRows(+ reconcileUnifiedSessions(+ [parent],+ [],+ [heartbeat("one", new Date(Date.now() + 5 * 60_000).toISOString(), "parent")],+ ),+ );+ expect(soonRows[0]).toMatchObject({ section: "idle", statusLabel: "heartbeat · next 5m" });+ });++ test("counts paused heartbeats separately without affecting the section", () => {+ const parent = makeSummary({ id: "parent", activeSessionId: "parent", sessionId: "parent-session" });+ const paused = heartbeat("paused-job", undefined, "parent", "paused");+ const aggregates = aggregateSessionHeartbeats([parent], [paused]);+ expect(aggregates.get("parent")).toEqual({ activeCount: 0, pausedCount: 1 });+ expect(formatHeartbeatBadge(aggregates.get("parent"))).toBe("♥ 1");+ const [record] = reconcileUnifiedSessions([parent], [], [paused]);+ expect(record).toMatchObject({ section: "idle", heartbeat: { activeCount: 0, pausedCount: 1 } });+ expect(record?.daemon?.hasActiveHeartbeat).toBeUndefined();});describe("restores selection to the previously open session", () => {diff --git a/packages/coding-agent/test/daemon-mode.test.ts b/packages/coding-agent/test/daemon-mode.test.tsindex 5f0f7fabce..aef6e10385 100644--- a/packages/coding-agent/test/daemon-mode.test.ts+++ b/packages/coding-agent/test/daemon-mode.test.ts@@ -13,7 +13,7 @@ import {} from "node:fs";import { createServer, type Server, type Socket } from "node:net";import { tmpdir } from "node:os";-import { join, resolve } from "node:path";+import { basename, join, resolve } from "node:path";import type { Api, Model } from "@earendil-works/pi-ai";import { describe, expect, it, vi } from "vitest";import { ENV_AGENT_DIR } from "../src/config.js";@@ -28,7 +28,7 @@ import type { AgentObserveController } from "../src/core/agent-observe.js";import type { CreateAgentSessionRuntimeFactory } from "../src/core/agent-session-runtime.js";import { installAgentTraceUpload } from "../src/core/agent-traces.js";import { AuthStorage } from "../src/core/auth-storage.js";-import type { AgentCronJob, AgentCronJobStore } from "../src/core/cron-jobs.js";+import { type AgentCronJob, AgentCronJobStore } from "../src/core/cron-jobs.js";import { PRIME_AGENT_TRACES_PROVIDER_ID } from "../src/core/prime-inference-auth.js";import {type CreateRlmSubagentRuntimeOptions,@@ -36,7 +36,12 @@ import {type SubagentRuntimeHost,} from "../src/core/rlm-runtime.js";import { canonicalSessionPath } from "../src/core/session-lease.js";-import { readSessionInfo, type SessionInfo, SessionManager } from "../src/core/session-manager.js";+import {+ getSessionArtifactPathForFile,+ readSessionInfo,+ type SessionInfo,+ SessionManager,+} from "../src/core/session-manager.js";import { SettingsManager } from "../src/core/settings-manager.js";import type { ActiveSessionState, DaemonSocketClient } from "../src/modes/daemon/active-session-state.js";import {@@ -524,7 +529,7 @@ describe("daemon mode helpers", () => {});});- it("classifies local roster status with heartbeat and running-child activity", () => {+ it("classifies local roster status from running-child activity, not armed heartbeats", () => {const daemon = new AgentDaemon("/tmp/prime-agent-status-test.sock", {defaultSessionConfig: { agentDir: "/tmp", cwd: "/tmp" },createRuntime: vi.fn(),@@ -550,8 +555,8 @@ describe("daemon mode helpers", () => {};createAgentMessageAgentSummary(state: ActiveSessionState): { status?: string };};- const getHeartbeat = vi.spyOn(internals.cronStore, "getHeartbeat").mockReturnValue(undefined);- const listRlmHeartbeats = vi.spyOn(internals.cronStore, "listRlmHeartbeats").mockReturnValue([]);+ vi.spyOn(internals.cronStore, "getHeartbeat").mockReturnValue({ status: "active" } as AgentCronJob);+ vi.spyOn(internals.cronStore, "listRlmHeartbeats").mockReturnValue([{ status: "active" } as AgentCronJob]);expect(internals.createAgentMessageAgentSummary(state).status).toBe("running");hasRunningChildren = false;@@ -560,11 +565,6 @@ describe("daemon mode helpers", () => {metadata: { kind: "subagent", createdAt: 1 },} as ActiveSessionState["runtime"];expect(internals.createAgentMessageAgentSummary(state).status).toBe("idle");- getHeartbeat.mockReturnValue({ status: "active" } as AgentCronJob);- expect(internals.createAgentMessageAgentSummary(state).status).toBe("running");- getHeartbeat.mockReturnValue(undefined);- listRlmHeartbeats.mockReturnValue([{ status: "active" } as AgentCronJob]);- expect(internals.createAgentMessageAgentSummary(state).status).toBe("running");});it("reserves a session name across equivalent session-relative parent headers", async () => {@@ -4014,6 +4014,57 @@ describe("daemon mode helpers", () => {}});+ it("registers passive descendants' scheduled jobs when their root becomes resident", async () => {+ const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-daemon-passive-descendant-jobs-"));+ try {+ const fixture = makePersistedRlmDaemonFixture(tempDir);+ const childSessionId = basename(fixture.childArtifactDir);+ const grandchildSessionId = basename(fixture.grandchildSessionFile, ".jsonl");+ const seedStore = AgentCronJobStore.forSessionArtifacts();+ seedStore.registerSessionArtifact(childSessionId, fixture.childArtifactDir);+ seedStore.registerSessionArtifact(+ grandchildSessionId,+ getSessionArtifactPathForFile(fixture.grandchildSessionFile, grandchildSessionId),+ );+ const makeJob = (sessionId: string, sessionFile: string) =>+ seedStore.createRlmHeartbeat({+ activeSessionId: `stale-${sessionId}`,+ sessionId,+ sessionFile,+ cwd: tempDir,+ runtimeKind: "subagent",+ scheduleText: "every 30s",+ prompt: "report exactly: hi",+ });+ makeJob(childSessionId, fixture.childSessionFile);+ const grandchildHeartbeat = makeJob(grandchildSessionId, fixture.grandchildSessionFile);++ const workerDaemon = new AgentDaemon(join(tempDir, "worker-daemon.sock"), {+ defaultSessionConfig: { agentDir: tempDir, cwd: tempDir, sessionDir: join(tempDir, "sessions") },+ createRuntime: fixture.createRuntime,+ worker: { authenticationToken: "worker-token" },+ });+ const internals = workerDaemon as unknown as {+ cronStore: AgentCronJobStore;+ createRuntime(command: Extract<DaemonCommand, { type: "create" }>): Promise<ActiveSessionState>;+ };+ // A corrupt child artifact must not strand the remaining descendants.+ const recover = internals.cronStore.recoverSessionArtifact.bind(internals.cronStore);+ vi.spyOn(internals.cronStore, "recoverSessionArtifact").mockImplementation((sessionId) => {+ if (sessionId === childSessionId) throw new Error("corrupt scheduled-jobs.json");+ return recover(sessionId);+ });++ await internals.createRuntime({ type: "create", sessionPath: fixture.parentSessionFile });++ await vi.waitFor(() =>+ expect(internals.cronStore.list().some((job) => job.id === grandchildHeartbeat.id)).toBe(true),+ );+ } finally {+ rmSync(tempDir, { recursive: true, force: true });+ }+ });+it("replaces a resident top-level RLM child when restoring its heartbeat", async () => {const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-daemon-replace-child-heartbeat-"));try {@@ -6031,7 +6082,6 @@ describe("daemon mode helpers", () => {internals.sessionPassivationSnapshot = vi.fn(async (state: ActiveSessionState) => ({isSessionActive: false,attachedClients: 0,- hasRegisteredHeartbeat: false,hasRegisteredCronJob: false,lastActivityAt: order.get(state) ?? 99,hasParent: state !== root,diff --git a/packages/coding-agent/test/daemon-peer-transport.test.ts b/packages/coding-agent/test/daemon-peer-transport.test.tsindex da785ef18d..be24d52d22 100644--- a/packages/coding-agent/test/daemon-peer-transport.test.ts+++ b/packages/coding-agent/test/daemon-peer-transport.test.ts@@ -469,8 +469,12 @@ describe("supervisor direct transport issuance", () => {rosterStore: roster,updateRestartPhase: undefined,isWorkerStopping: vi.fn(() => false),+ defaultSessionConfig: {},}) as unknown as SupervisorInternals;- const worker = { descriptor: { workerId: "worker-1", lifecycle: "ready" }, client: {} };+ const worker = {+ descriptor: { workerId: "worker-1", lifecycle: "ready", sessionFile: "/tmp/peer-test/session.jsonl" },+ client: {},+ };expect(supervisor.workerEvictionSnapshot(worker).sessions[0]?.attachedClients).toBe(1);});diff --git a/packages/coding-agent/test/daemon-supervisor-eviction.test.ts b/packages/coding-agent/test/daemon-supervisor-eviction.test.tsindex b655d1d2aa..212d0b428b 100644--- a/packages/coding-agent/test/daemon-supervisor-eviction.test.ts+++ b/packages/coding-agent/test/daemon-supervisor-eviction.test.ts@@ -1,7 +1,10 @@-import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";import { afterEach, describe, expect, it, vi } from "vitest";+import { getSessionsDir } from "../src/config.js";+import { type AgentCronJob, AgentCronJobStore, SESSION_SCHEDULED_JOBS_FILENAME } from "../src/core/cron-jobs.js";+import { getSessionArtifactPathForFile, type SessionInfo } from "../src/core/session-manager.js";import { workerRosterEntryFromSummary } from "../src/modes/daemon/agent-roster.js";import { success } from "../src/modes/daemon/daemon-protocol.js";import type { SessionSummary } from "../src/modes/daemon/daemon-session-list.js";@@ -14,11 +17,24 @@ interface WorkerFixture {lifecycle: "starting" | "ready" | "recovering" | "failed";rootActiveSessionId: string;rootSessionId: string;+ sessionFile?: string;pid: number;ownerClientId?: string;stopRequestedAt?: string;createCommand: { type: "create"; config?: { sessionDir?: string } };+ version?: number;+ supervisorSocketPath?: string;+ socketPath?: string;+ authenticationToken?: string;+ recoveryJournalPath?: string;+ createdAt?: string;+ updatedAt?: string;+ consecutiveFailures?: number;};+ descriptorPath?: string;+ transcriptCaches?: Map<string, unknown>;+ snapshotCache?: Map<string, unknown>;+ stopRevision?: number;client?: {request: ReturnType<typeof vi.fn>;requestWorker: ReturnType<typeof vi.fn>;@@ -34,15 +50,32 @@ interface SupervisorInternals {clients: Set<{ id: string; attachedActiveSessionIds: Set<string> }>;idleEvictionFence?: Promise<void>;mutationDrain: { begin(): void; end(): void };- catalog: { resolve: ReturnType<typeof vi.fn>; stop: ReturnType<typeof vi.fn> };+ catalog: { resolve: ReturnType<typeof vi.fn>; stop: ReturnType<typeof vi.fn>; list?: ReturnType<typeof vi.fn> };+ rlmSpawnLedgerInstance?: { family: ReturnType<typeof vi.fn>; liveEdges: ReturnType<typeof vi.fn> };+ updateRestartPhase?: "draining" | "fencing" | "prepared";createOrReuseWorker: ReturnType<typeof vi.fn>;stopWorker: ReturnType<typeof vi.fn>;log: ReturnType<typeof vi.fn>;+ scheduledWakeTimer?: ReturnType<typeof setTimeout>;+ scheduledWakeRecompute?: Promise<void>;scheduleIdleEvictionSweep(): void;runIdleEvictionSweep(now?: number): Promise<void>;+ recomputeScheduledSessionWake(): Promise<void>;+ wakeDueScheduledSessions(now?: number): Promise<void>;shutdown(exitCode: number, stopWorkers: boolean): Promise<never>;handleCommand(client: object, command: object): Promise<unknown>;writeRosterEntry(entry: object, worker?: object): unknown;+ cancelEphemeralWorkerScheduledJobs(worker: WorkerFixture): Promise<boolean>;+ descriptorDir: string;+ socketPath: string;+ defaultSessionConfig: { agentDir?: string; sessionDir?: string };+ persistWorker(worker: WorkerFixture): void;+ stopWorkerUntracked(worker: WorkerFixture, removeDescriptor: boolean, force?: boolean): Promise<void>;+ promoteOwnedWorker(client: object, worker: WorkerFixture): Promise<void>;+ loadWorkerDescriptors(): void;+ adoptOrRecoverWorker(worker: WorkerFixture): Promise<void>;+ assertRecoveryAllowed: () => Promise<void>;+ cancelScheduledJobsForSessionTree: (id: string, file: string) => Promise<void>;}const tempDirs: string[] = [];@@ -123,20 +156,55 @@ describe("daemon supervisor whole-tree eviction", () => {const heartbeat = makeWorker("heartbeat", [makeSummary("heartbeat-root", now, { hasRegisteredHeartbeat: true })]);const cron = makeWorker("cron", [makeSummary("cron-root", now, { hasRegisteredCronJob: true })]);const attached = makeWorker("attached", [makeSummary("attached-root", now)]);- for (const worker of [idle, active, heartbeat, cron, attached]) {+ // A schedule outside the enumerable sessions root cannot be re-woken; it must stay resident.+ const sessionsRoot = getSessionsDir(supervisor.defaultSessionConfig.agentDir ?? "");+ mkdirSync(sessionsRoot, { recursive: true });+ heartbeat.descriptor.sessionFile = join(sessionsRoot, "heartbeat-root.jsonl");+ const blindDir = mkdtempSync(join(tmpdir(), "prime-custom-session-dir-"));+ tempDirs.push(blindDir);+ const blind = makeWorker("blind-heartbeat", [makeSummary("blind-root", now, { hasRegisteredHeartbeat: true })]);+ blind.descriptor.sessionFile = join(blindDir, "blind-root.jsonl");+ for (const worker of [idle, active, heartbeat, cron, attached, blind]) {supervisor.workers.set(worker.descriptor.workerId, worker);}- seedSupervisorRoster(supervisor, idle, active, heartbeat, cron, attached);+ seedSupervisorRoster(supervisor, idle, active, heartbeat, cron, attached, blind);supervisor.clients.add({ id: "viewer", attachedActiveSessionIds: new Set(["attached-root"]) });await supervisor.runIdleEvictionSweep(now);- expect(supervisor.stopWorker).toHaveBeenCalledTimes(1);+ expect(supervisor.stopWorker).toHaveBeenCalledTimes(2);expect(supervisor.stopWorker).toHaveBeenCalledWith(idle, true);+ expect(supervisor.stopWorker).toHaveBeenCalledWith(heartbeat, true);expect(supervisor.log).toHaveBeenCalledWith(expect.stringMatching(/Evicted idle worker idle .*idleMinutes=120 sessions=2/),);- expect([...supervisor.workers.keys()].sort()).toEqual(["active", "attached", "cron", "heartbeat"]);+ expect([...supervisor.workers.keys()].sort()).toEqual(["active", "attached", "blind-heartbeat", "cron"]);+ });++ it("keeps a custom-dir worker resident when a heartbeat lands during the eviction drain", async () => {+ const now = Date.parse("2026-08-01T12:00:00.000Z");+ const supervisor = makeSupervisor();+ const blindDir = mkdtempSync(join(tmpdir(), "prime-custom-session-dir-"));+ tempDirs.push(blindDir);+ const worker = makeWorker("blind", [makeSummary("blind-root", now)]);+ worker.descriptor.sessionFile = join(blindDir, "blind-root.jsonl");+ supervisor.workers.set("blind", worker);+ seedSupervisorRoster(supervisor, worker);+ const armed = makeSummary("blind-root", now, { hasRegisteredHeartbeat: true });+ worker+ .client!.request.mockImplementationOnce(async () =>+ success(undefined, "list", { sessions: [makeSummary("blind-root", now)] }),+ )+ .mockImplementation(async () => {+ // A heartbeat_set admitted mid-drain pushes its registration mark before the fenced recheck.+ supervisor.writeRosterEntry(workerRosterEntryFromSummary(armed), worker);+ return success(undefined, "list", { sessions: [armed] });+ });++ await supervisor.runIdleEvictionSweep(now);++ expect(supervisor.stopWorker).not.toHaveBeenCalled();+ expect(supervisor.workers.get("blind")).toBe(worker);});it("delegates capped child passivation only to live non-evictable workers", async () => {@@ -211,24 +279,6 @@ describe("daemon supervisor whole-tree eviction", () => {expect(supervisor.workers.has("parent")).toBe(true);});- it("evicts a paused-heartbeat session but pins an active-heartbeat session", async () => {- const now = Date.parse("2026-08-01T12:00:00.000Z");- const supervisor = makeSupervisor();- const paused = makeWorker("paused", [makeSummary("paused-root", now)]);- const active = makeWorker("active-heartbeat", [- makeSummary("active-heartbeat-root", now, { hasRegisteredHeartbeat: true }),- ]);- supervisor.workers.set("paused", paused);- supervisor.workers.set("active-heartbeat", active);- seedSupervisorRoster(supervisor, paused, active);-- await supervisor.runIdleEvictionSweep(now);-- expect(supervisor.stopWorker).toHaveBeenCalledTimes(1);- expect(supervisor.stopWorker).toHaveBeenCalledWith(paused, true);- expect(supervisor.workers.has("active-heartbeat")).toBe(true);- });-it("honors off after reloading settings at sweep time", async () => {const now = Date.parse("2026-08-01T12:00:00.000Z");const supervisor = makeSupervisor("off");@@ -472,21 +522,27 @@ describe("daemon supervisor empty-session eviction on detach", () => {const now = Date.parse("2026-08-01T12:00:00.000Z");const supervisor = makeSupervisor();const empty = makeWorker("empty", [makeSummary("empty-root", now, { messageCount: 0 })]);+ const heartbeat = makeWorker("heartbeat", [+ makeSummary("heartbeat-root", now, { messageCount: 0, hasRegisteredHeartbeat: true }),+ ]);const exempt = [makeWorker("named", [makeSummary("named-root", now, { messageCount: 0, sessionName: "keep me" })]),makeWorker("busy", [makeSummary("busy-root", now, { messageCount: 0, isSessionActive: true })]),makeWorker("one-message", [makeSummary("one-message-root", now)]),- makeWorker("heartbeat", [- makeSummary("heartbeat-root", now, { messageCount: 0, hasRegisteredHeartbeat: true }),- ]),makeWorker("cron", [makeSummary("cron-root", now, { messageCount: 0, hasRegisteredCronJob: true })]),makeWorker("owned", [makeSummary("owned-root", now, { messageCount: 0 })]),+ makeWorker("blind-heartbeat", [+ makeSummary("blind-root", now, { messageCount: 0, hasRegisteredHeartbeat: true }),+ ]),];- exempt[5]!.descriptor.ownerClientId = "owner";- for (const worker of [empty, ...exempt]) {+ exempt[4]!.descriptor.ownerClientId = "owner";+ const blindDir = mkdtempSync(join(tmpdir(), "prime-custom-session-dir-"));+ tempDirs.push(blindDir);+ exempt[5]!.descriptor.sessionFile = join(blindDir, "blind-root.jsonl");+ for (const worker of [empty, heartbeat, ...exempt]) {supervisor.workers.set(worker.descriptor.workerId, worker);}- seedSupervisorRoster(supervisor, empty, ...exempt);+ seedSupervisorRoster(supervisor, empty, heartbeat, ...exempt);const first = makeDetachClient("first", ["empty-root"]);const viewer = makeDetachClient("viewer", ["empty-root",@@ -496,6 +552,7 @@ describe("daemon supervisor empty-session eviction on detach", () => {"heartbeat-root","cron-root","owned-root",+ "blind-root",]);supervisor.clients.add(first);supervisor.clients.add(viewer);@@ -506,12 +563,13 @@ describe("daemon supervisor empty-session eviction on detach", () => {await supervisor.handleCommand(viewer, { id: "detach-all", type: "detach" });await vi.waitFor(() => expect(supervisor.stopWorker).toHaveBeenCalledWith(empty, true));+ await vi.waitFor(() => expect(supervisor.stopWorker).toHaveBeenCalledWith(heartbeat, true));await settle();- expect(supervisor.stopWorker).toHaveBeenCalledTimes(1);+ expect(supervisor.stopWorker).toHaveBeenCalledTimes(2);expect([...supervisor.workers.keys()].sort()).toEqual([+ "blind-heartbeat","busy","cron",- "heartbeat","named","one-message","owned",@@ -586,7 +644,7 @@ describe("daemon supervisor empty-session eviction on detach", () => {expect(supervisor.workers.get("swap")).toBe(successor);});- it("does not evict when a mutation admitted during the refresh registers a schedule", async () => {+ it("does not evict when a mutation admitted during the refresh registers a cron schedule", async () => {const now = Date.parse("2026-08-01T12:00:00.000Z");const supervisor = makeSupervisor();const worker = makeWorker("gap", [makeSummary("gap-root", now, { messageCount: 0 })]);@@ -607,11 +665,11 @@ describe("daemon supervisor empty-session eviction on detach", () => {await supervisor.handleCommand(client, { id: "detach", type: "detach", activeSessionId: "gap-root" });await vi.waitFor(() => expect(worker.client!.request).toHaveBeenCalled());- // A heartbeat_set admitted mid-refresh registers a schedule before the eviction decision.+ // A cron_add admitted mid-refresh registers a schedule before the eviction decision.supervisor.mutationDrain.begin();worker.client!.request.mockImplementation(async () =>success(undefined, "list", {- sessions: [makeSummary("gap-root", now, { messageCount: 0, hasRegisteredHeartbeat: true })],+ sessions: [makeSummary("gap-root", now, { messageCount: 0, hasRegisteredCronJob: true })],}),);releaseList();@@ -684,3 +742,517 @@ describe("daemon supervisor empty-session eviction on detach", () => {expect(supervisor.stopWorker).toHaveBeenCalledWith(worker, true);});});++describe("daemon supervisor scheduled-session wake", () => {+ const now = Date.parse("2026-08-01T12:00:00.000Z");++ function makeSavedInfo(path: string, id: string, overrides: Partial<SessionInfo> = {}): SessionInfo {+ return {+ path,+ id,+ cwd: "/tmp/project",+ rlmDepth: 0,+ created: new Date(now - 12 * 60 * 60_000),+ modified: new Date(now - 12 * 60 * 60_000),+ messageCount: 1,+ ...overrides,+ } as SessionInfo;+ }++ function makeScheduledSessionFile(+ fileBase: string,+ sessionId = fileBase,+ ): { sessionFile: string; store: AgentCronJobStore } {+ const directory = mkdtempSync(join(tmpdir(), "prime-supervisor-wake-"));+ tempDirs.push(directory);+ const sessionDir = join(directory, "sessions");+ mkdirSync(sessionDir, { recursive: true });+ const sessionFile = join(sessionDir, `${fileBase}.jsonl`);+ writeFileSync(sessionFile, "");+ const store = AgentCronJobStore.forSessionArtifacts();+ store.registerSessionArtifact(sessionId, getSessionArtifactPathForFile(sessionFile, sessionId));+ return { sessionFile, store };+ }++ function armHeartbeat(store: AgentCronJobStore, sessionId: string, sessionFile: string, at: number): AgentCronJob {+ return store.createHeartbeat({+ activeSessionId: "stale-active",+ sessionId,+ sessionFile,+ cwd: "/tmp/project",+ scheduleText: "every 5m",+ prompt: "tick",+ now: new Date(at),+ });+ }++ it("wakes the non-resident root through the existing create path when a descendant heartbeat is due", async () => {+ const supervisor = makeSupervisor();+ const root = makeScheduledSessionFile("wake-root");+ const child = makeScheduledSessionFile("wake-child");+ armHeartbeat(child.store, "wake-child", child.sessionFile, now - 10 * 60_000);+ supervisor.rlmSpawnLedgerInstance = {+ family: vi.fn(async () => [+ makeSavedInfo(root.sessionFile, "wake-root"),+ makeSavedInfo(child.sessionFile, "wake-child", { parentSessionPath: root.sessionFile, rlmDepth: 1 }),+ ]),+ liveEdges: vi.fn(async () => []),+ };+ const woken = makeWorker("woken", [+ makeSummary("woken-root", now, { sessionId: "wake-root", sessionFile: root.sessionFile }),+ ]);+ woken.descriptor.sessionFile = root.sessionFile;+ supervisor.createOrReuseWorker = vi.fn(async () => {+ supervisor.workers.set("woken", woken);+ return woken;+ });++ await supervisor.wakeDueScheduledSessions(now);++ expect(supervisor.createOrReuseWorker).toHaveBeenCalledTimes(1);+ expect(supervisor.createOrReuseWorker).toHaveBeenCalledWith("scheduled-wake", {+ type: "create",+ sessionPath: root.sessionFile,+ });+ });++ it("does not wake the passive root over a mid-tree session that has its own resident worker", async () => {+ const supervisor = makeSupervisor();+ supervisor.createOrReuseWorker = vi.fn();+ const root = makeScheduledSessionFile("covered-mid-root");+ const mid = makeScheduledSessionFile("covered-mid");+ armHeartbeat(mid.store, "covered-mid", mid.sessionFile, now - 10 * 60_000);+ supervisor.rlmSpawnLedgerInstance = {+ family: vi.fn(async () => [+ makeSavedInfo(root.sessionFile, "covered-mid-root"),+ makeSavedInfo(mid.sessionFile, "covered-mid", { parentSessionPath: root.sessionFile, rlmDepth: 1 }),+ ]),+ liveEdges: vi.fn(async () => []),+ };+ const resident = makeWorker("mid-worker", []);+ resident.descriptor.sessionFile = mid.sessionFile;+ supervisor.workers.set("mid-worker", resident);++ await supervisor.wakeDueScheduledSessions(now);+ expect(supervisor.createOrReuseWorker).not.toHaveBeenCalled();+ await supervisor.scheduledWakeRecompute;+ await supervisor.recomputeScheduledSessionWake();+ expect(supervisor.scheduledWakeTimer).toBeUndefined();+ });++ it("skips a corrupt scheduled-jobs artifact but still wakes the other passive sessions", async () => {+ const supervisor = makeSupervisor();+ const healthy = makeScheduledSessionFile("healthy-root");+ const corrupt = makeScheduledSessionFile("corrupt-root");+ armHeartbeat(healthy.store, "healthy-root", healthy.sessionFile, now - 10 * 60_000);+ armHeartbeat(corrupt.store, "corrupt-root", corrupt.sessionFile, now - 10 * 60_000);+ writeFileSync(+ join(getSessionArtifactPathForFile(corrupt.sessionFile, "corrupt-root"), SESSION_SCHEDULED_JOBS_FILENAME),+ "{ not json",+ );+ supervisor.rlmSpawnLedgerInstance = {+ family: vi.fn(async () => [+ makeSavedInfo(healthy.sessionFile, "healthy-root"),+ makeSavedInfo(corrupt.sessionFile, "corrupt-root"),+ ]),+ liveEdges: vi.fn(async () => []),+ };+ supervisor.createOrReuseWorker = vi.fn(async () => makeWorker("woken", []));++ await supervisor.wakeDueScheduledSessions(now);++ expect(supervisor.createOrReuseWorker).toHaveBeenCalledTimes(1);+ expect(supervisor.createOrReuseWorker).toHaveBeenCalledWith("scheduled-wake", {+ type: "create",+ sessionPath: healthy.sessionFile,+ });+ });++ it("re-arms the wake timer from the durable store and skips covered, paused, and cancelled jobs", async () => {+ const supervisor = makeSupervisor();+ supervisor.createOrReuseWorker = vi.fn();+ const { sessionFile, store } = makeScheduledSessionFile("armed-root");+ // Real-clock epochs keep nextRunAt in the future so the armed timer never fires mid-test.+ const armedAt = Date.now();+ const job = armHeartbeat(store, "armed-root", sessionFile, armedAt);+ supervisor.rlmSpawnLedgerInstance = {+ family: vi.fn(async () => [makeSavedInfo(sessionFile, "armed-root")]),+ liveEdges: vi.fn(async () => []),+ };++ await supervisor.recomputeScheduledSessionWake();+ expect(supervisor.scheduledWakeTimer).toBeDefined();++ const resident = makeWorker("resident", []);+ resident.descriptor.sessionFile = sessionFile;+ supervisor.workers.set("resident", resident);+ await supervisor.recomputeScheduledSessionWake();+ expect(supervisor.scheduledWakeTimer).toBeUndefined();+ supervisor.workers.delete("resident");++ store.pauseHeartbeat("stale-active");+ await supervisor.recomputeScheduledSessionWake();+ expect(supervisor.scheduledWakeTimer).toBeUndefined();+ await supervisor.wakeDueScheduledSessions(armedAt + 60 * 60_000);+ expect(supervisor.createOrReuseWorker).not.toHaveBeenCalled();+ // Settle the recompute the wake pass queued before mutating the store again.+ await supervisor.scheduledWakeRecompute;++ store.resumeHeartbeat("stale-active");+ await supervisor.recomputeScheduledSessionWake();+ expect(supervisor.scheduledWakeTimer).toBeDefined();++ store.cancel(job.id);+ await supervisor.recomputeScheduledSessionWake();+ expect(supervisor.scheduledWakeTimer).toBeUndefined();+ });++ it("does not arm the wake timer while an update restart is being prepared", async () => {+ const supervisor = makeSupervisor();+ supervisor.createOrReuseWorker = vi.fn();+ const { sessionFile, store } = makeScheduledSessionFile("restart-root");+ armHeartbeat(store, "restart-root", sessionFile, now - 10 * 60_000);+ supervisor.rlmSpawnLedgerInstance = {+ family: vi.fn(async () => [makeSavedInfo(sessionFile, "restart-root")]),+ liveEdges: vi.fn(async () => []),+ };+ supervisor.updateRestartPhase = "prepared";++ await supervisor.recomputeScheduledSessionWake();+ expect(supervisor.scheduledWakeTimer).toBeUndefined();+ await supervisor.wakeDueScheduledSessions(now);+ expect(supervisor.createOrReuseWorker).not.toHaveBeenCalled();+ expect(supervisor.scheduledWakeTimer).toBeUndefined();++ supervisor.updateRestartPhase = undefined;+ // A throwing launch keeps the re-armed overdue job on the 60s retry backoff.+ supervisor.createOrReuseWorker = vi.fn(async () => {+ throw new Error("no launch in this test");+ });+ await supervisor.recomputeScheduledSessionWake();+ expect(supervisor.scheduledWakeTimer).toBeDefined();+ });++ it("cancels a client-owned worker's scheduled jobs, descendants included, when its registration dies", async () => {+ const supervisor = makeSupervisor();+ const root = makeScheduledSessionFile("owned-root");+ // The child's persisted id differs from its filename; the artifact keys on the id.+ const child = makeScheduledSessionFile("owned-child", "owned-child-real");+ armHeartbeat(root.store, "owned-root", root.sessionFile, now);+ armHeartbeat(child.store, "owned-child-real", child.sessionFile, now);+ const owned = makeWorker("owned", []);+ owned.descriptor.ownerClientId = "owner";+ owned.descriptor.rootSessionId = "owned-root";+ owned.descriptor.sessionFile = root.sessionFile;+ supervisor.rlmSpawnLedgerInstance = {+ family: vi.fn(async () => [+ makeSavedInfo(root.sessionFile, "owned-root"),+ makeSavedInfo(child.sessionFile, "owned-child-real", {+ parentSessionPath: root.sessionFile,+ rlmDepth: 1,+ }),+ ]),+ liveEdges: vi.fn(async () => []),+ };++ // A different worker covering ANY tree member keeps its schedules; only a fully uncovered tree is cancelled.+ const covering = makeWorker("covering", []);+ covering.descriptor.sessionFile = child.sessionFile;+ supervisor.workers.set("covering", covering);+ expect(await supervisor.cancelEphemeralWorkerScheduledJobs(owned)).toBe(true);+ expect(root.store.list().map((job) => job.status)).toEqual(["active"]);+ covering.descriptor.sessionFile = root.sessionFile;+ expect(await supervisor.cancelEphemeralWorkerScheduledJobs(owned)).toBe(true);+ expect(root.store.list().map((job) => job.status)).toEqual(["active"]);+ supervisor.workers.delete("covering");++ expect(await supervisor.cancelEphemeralWorkerScheduledJobs(owned)).toBe(true);++ expect(root.store.list().map((job) => job.status)).toEqual(["cancelled"]);+ expect(child.store.list().map((job) => job.status)).toEqual(["cancelled"]);+ });++ it("keeps schedules that were promoted public while the ephemeral cancel was in flight", async () => {+ const supervisor = makeSupervisor();+ const { sessionFile, store } = makeScheduledSessionFile("promoted-root");+ armHeartbeat(store, "promoted-root", sessionFile, now);+ let releaseFamily = () => {};+ const familyGate = new Promise<void>((resolve) => {+ releaseFamily = resolve;+ });+ supervisor.rlmSpawnLedgerInstance = {+ family: vi.fn(async () => {+ await familyGate;+ return [makeSavedInfo(sessionFile, "promoted-root")];+ }),+ liveEdges: vi.fn(async () => []),+ };+ const directory = mkdtempSync(join(tmpdir(), "prime-supervisor-promote-"));+ tempDirs.push(directory);+ const owned = makeWorker("owned", []);+ owned.descriptor.ownerClientId = "owner";+ owned.descriptor.rootSessionId = "promoted-root";+ owned.descriptor.sessionFile = sessionFile;+ owned.descriptorPath = join(directory, "owned.json");++ const cancel = supervisor.cancelEphemeralWorkerScheduledJobs(owned);+ await supervisor.promoteOwnedWorker({ id: "owner", attachedActiveSessionIds: new Set<string>() }, owned);+ releaseFamily();++ expect(await cancel).toBe(true);+ expect(owned.descriptor.ownerClientId).toBeUndefined();+ expect(store.list().map((job) => job.status)).toEqual(["active"]);+ });++ it("never parks or retries the cancel once the tree was promoted during a failing family read", async () => {+ const supervisor = makeSupervisor();+ supervisor.createOrReuseWorker = vi.fn();+ const { sessionFile, store } = makeScheduledSessionFile("promoted-parked-root");+ armHeartbeat(store, "promoted-parked-root", sessionFile, now - 10 * 60_000);+ let failFamily: (error: Error) => void = () => {};+ const familyGate = new Promise<never>((_, reject) => {+ failFamily = reject;+ });+ let familyReads = 0;+ supervisor.rlmSpawnLedgerInstance = {+ family: vi.fn(async () => {+ familyReads += 1;+ if (familyReads === 1) await familyGate;+ return [makeSavedInfo(sessionFile, "promoted-parked-root")];+ }),+ liveEdges: vi.fn(async () => []),+ };+ mkdirSync(supervisor.descriptorDir, { recursive: true });+ const owned = makeWorker("owned", []);+ owned.descriptor.ownerClientId = "owner";+ owned.descriptor.rootSessionId = "promoted-parked-root";+ owned.descriptor.sessionFile = sessionFile;+ owned.descriptor.version = 2;+ owned.descriptor.supervisorSocketPath = supervisor.socketPath;+ owned.descriptor.socketPath = "owned.sock";+ owned.descriptor.authenticationToken = "token";+ owned.descriptor.recoveryJournalPath = join(supervisor.descriptorDir, "owned.recovery.jsonl");+ owned.descriptor.createdAt = new Date(now).toISOString();+ owned.descriptor.updatedAt = new Date(now).toISOString();+ owned.descriptor.consecutiveFailures = 0;+ owned.descriptor.stopRequestedAt = new Date(now).toISOString();+ owned.descriptorPath = join(supervisor.descriptorDir, "owned.json");++ const cancel = supervisor.cancelEphemeralWorkerScheduledJobs(owned);+ await supervisor.promoteOwnedWorker({ id: "owner", attachedActiveSessionIds: new Set<string>() }, owned);+ failFamily(new Error("ledger read failed"));++ const settled = await cancel;+ await supervisor.recomputeScheduledSessionWake();+ expect(store.list().map((job) => job.status)).toEqual(["active"]);+ expect(settled).toBe(true);+ });++ it("keeps a tree wake-ineligible after a failed ephemeral cancel until an enumeration retry lands", async () => {+ const supervisor = makeSupervisor();+ supervisor.createOrReuseWorker = vi.fn();+ const { sessionFile, store } = makeScheduledSessionFile("failed-cancel-root");+ armHeartbeat(store, "failed-cancel-root", sessionFile, now - 10 * 60_000);+ supervisor.rlmSpawnLedgerInstance = {+ family: vi.fn(async () => [makeSavedInfo(sessionFile, "failed-cancel-root")]),+ liveEdges: vi.fn(async () => []),+ };+ mkdirSync(supervisor.descriptorDir, { recursive: true });+ const owned = makeWorker("owned", []);+ owned.descriptor.ownerClientId = "owner";+ owned.descriptor.rootSessionId = "failed-cancel-root";+ owned.descriptor.sessionFile = sessionFile;+ owned.descriptor.version = 2;+ owned.descriptor.supervisorSocketPath = supervisor.socketPath;+ owned.descriptor.socketPath = "owned.sock";+ owned.descriptor.authenticationToken = "token";+ owned.descriptor.recoveryJournalPath = join(supervisor.descriptorDir, "owned.recovery.jsonl");+ owned.descriptor.createdAt = new Date(now).toISOString();+ owned.descriptor.updatedAt = new Date(now).toISOString();+ owned.descriptor.consecutiveFailures = 0;+ owned.descriptor.stopRequestedAt = new Date(now).toISOString();+ owned.descriptorPath = join(supervisor.descriptorDir, "owned.json");+ supervisor.persistWorker(owned);+ const treeCancel = vi+ .spyOn(+ supervisor as unknown as { cancelScheduledJobsForSessionTree: (id: string, file: string) => Promise<void> },+ "cancelScheduledJobsForSessionTree",+ )+ .mockRejectedValue(new Error("corrupt scheduled-jobs.json"));++ await supervisor.cancelEphemeralWorkerScheduledJobs(owned);+ expect(store.list().map((job) => job.status)).toEqual(["active"]);++ await supervisor.recomputeScheduledSessionWake();+ expect(supervisor.scheduledWakeTimer).toBeUndefined();+ await supervisor.wakeDueScheduledSessions(now);+ expect(supervisor.createOrReuseWorker).not.toHaveBeenCalled();+ expect(store.list().map((job) => job.status)).toEqual(["active"]);++ // The next enumeration retries the cancel; once it lands the jobs are gone for good.+ treeCancel.mockRestore();+ await supervisor.recomputeScheduledSessionWake();+ expect(store.list().map((job) => job.status)).toEqual(["cancelled"]);+ expect(existsSync(owned.descriptorPath)).toBe(false);+ expect(supervisor.scheduledWakeTimer).toBeUndefined();+ });++ it("keeps the tombstoned descriptor after a failed ephemeral cancel so the next boot finishes it", async () => {+ const directory = mkdtempSync(join(tmpdir(), "prime-supervisor-durable-cancel-"));+ tempDirs.push(directory);+ writeFileSync(join(directory, "settings.json"), JSON.stringify({ idleEvictionMinutes: 90 }));+ const workersDir = join(directory, "workers");+ mkdirSync(workersDir, { recursive: true });+ const socketPath = join(directory, "daemon.sock");+ const { sessionFile, store } = makeScheduledSessionFile("durable-cancel-root");+ armHeartbeat(store, "durable-cancel-root", sessionFile, now - 10 * 60_000);+ const bootSupervisor = (): SupervisorInternals => {+ const supervisor = new DaemonSupervisor(socketPath, {+ defaultSessionConfig: { agentDir: directory, cwd: directory },+ descriptorDir: workersDir,+ }) as unknown as SupervisorInternals;+ supervisor.log = vi.fn();+ supervisor.rlmSpawnLedgerInstance = {+ family: vi.fn(async () => [makeSavedInfo(sessionFile, "durable-cancel-root")]),+ liveEdges: vi.fn(async () => []),+ };+ return supervisor;+ };+ const descriptorPath = join(workersDir, "owned-worker.json");+ const owned: WorkerFixture = {+ descriptor: {+ workerId: "owned-worker",+ lifecycle: "ready",+ version: 2,+ supervisorSocketPath: socketPath,+ socketPath: join(directory, "worker.sock"),+ authenticationToken: "token",+ recoveryJournalPath: join(workersDir, "owned-worker.recovery.jsonl"),+ rootActiveSessionId: "owned-active",+ rootSessionId: "durable-cancel-root",+ sessionFile,+ pid: 2_000_000_000,+ ownerClientId: "owner",+ createdAt: new Date(now).toISOString(),+ updatedAt: new Date(now).toISOString(),+ consecutiveFailures: 0,+ createCommand: { type: "create" },+ },+ descriptorPath,+ summaries: new Map(),+ transcriptCaches: new Map(),+ snapshotCache: new Map(),+ intentionalStop: false,+ stopRevision: 0,+ };+ const stopping = bootSupervisor();+ stopping.workers.set("owned-worker", owned);+ vi.spyOn(stopping, "cancelScheduledJobsForSessionTree").mockRejectedValue(new Error("store busy"));++ await stopping.stopWorkerUntracked(owned, true, true);+ await stopping.scheduledWakeRecompute;++ // The stop tombstone survives the failed cancel as the durable intent.+ expect(existsSync(descriptorPath)).toBe(true);+ expect(store.list().map((job) => job.status)).toEqual(["active"]);++ const rebooted = bootSupervisor();+ rebooted.assertRecoveryAllowed = vi.fn(async () => {});+ rebooted.loadWorkerDescriptors();+ expect(rebooted.workers.size).toBe(1);+ await rebooted.adoptOrRecoverWorker([...rebooted.workers.values()][0]!);++ expect(store.list().map((job) => job.status)).toEqual(["cancelled"]);+ expect(existsSync(descriptorPath)).toBe(false);+ await rebooted.recomputeScheduledSessionWake();+ expect(rebooted.scheduledWakeTimer).toBeUndefined();+ });++ it("pauses a passivated heartbeat against its durable store without waking it", async () => {+ const supervisor = makeSupervisor();+ supervisor.createOrReuseWorker = vi.fn();+ const { sessionFile, store } = makeScheduledSessionFile("managed-root");+ const job = armHeartbeat(store, "managed-root", sessionFile, now - 10 * 60_000);+ supervisor.rlmSpawnLedgerInstance = {+ family: vi.fn(async () => [makeSavedInfo(sessionFile, "managed-root")]),+ liveEdges: vi.fn(async () => []),+ };++ const response = await supervisor.handleCommand(+ { id: "manager", attachedActiveSessionIds: new Set<string>() },+ { id: "manage-1", type: "heartbeat_manage", activeSessionId: "stale-active", jobId: job.id, action: "pause" },+ );++ expect(response).toMatchObject({ success: true, data: { heartbeat: { id: job.id, status: "paused" } } });+ expect(store.list().map((candidate) => candidate.status)).toEqual(["paused"]);+ await supervisor.scheduledWakeRecompute;+ expect(supervisor.scheduledWakeTimer).toBeUndefined();+ expect(supervisor.createOrReuseWorker).not.toHaveBeenCalled();+ });++ it("lists and cancels a passive scheduled job without a resident worker", async () => {+ const supervisor = makeSupervisor();+ const { sessionFile, store } = makeScheduledSessionFile("unscoped-root");+ const job = armHeartbeat(store, "unscoped-root", sessionFile, now);+ supervisor.rlmSpawnLedgerInstance = {+ family: vi.fn(async () => [makeSavedInfo(sessionFile, "unscoped-root")]),+ liveEdges: vi.fn(async () => []),+ };+ const client = { id: "manager", attachedActiveSessionIds: new Set<string>() };++ const listed = await supervisor.handleCommand(client, { id: "list-1", type: "cron_list" });+ expect(listed).toMatchObject({ success: true, data: { jobs: [{ id: job.id, status: "active" }] } });++ const cancelled = await supervisor.handleCommand(client, { id: "cancel-1", type: "cron_cancel", jobId: job.id });+ expect(cancelled).toMatchObject({ success: true, data: { job: { id: job.id, status: "cancelled" } } });+ expect(store.list().map((candidate) => candidate.status)).toEqual(["cancelled"]);++ // Terminal jobs stay reachable through an inclusive listing, exactly like resident sessions.+ const relisted = await supervisor.handleCommand(client, { id: "list-2", type: "cron_list" });+ expect(relisted).toMatchObject({ success: true, data: { jobs: [] } });+ const inclusive = await supervisor.handleCommand(client, {+ id: "list-3",+ type: "cron_list",+ includeInactive: true,+ });+ expect(inclusive).toMatchObject({ success: true, data: { jobs: [{ id: job.id, status: "cancelled" }] } });+ });++ it("drops a stale ephemeral-cancel intent once a worker covers the tree again", async () => {+ const supervisor = makeSupervisor();+ const { sessionFile, store } = makeScheduledSessionFile("reopened-root");+ armHeartbeat(store, "reopened-root", sessionFile, now);+ supervisor.rlmSpawnLedgerInstance = {+ family: vi.fn(async () => [makeSavedInfo(sessionFile, "reopened-root")]),+ liveEdges: vi.fn(async () => []),+ };+ mkdirSync(supervisor.descriptorDir, { recursive: true });+ const stopped = makeWorker("stopped", []);+ stopped.descriptor.ownerClientId = "owner";+ stopped.descriptor.rootSessionId = "reopened-root";+ stopped.descriptor.sessionFile = sessionFile;+ stopped.descriptor.version = 2;+ stopped.descriptor.supervisorSocketPath = supervisor.socketPath;+ stopped.descriptor.socketPath = "stopped.sock";+ stopped.descriptor.authenticationToken = "token";+ stopped.descriptor.recoveryJournalPath = join(supervisor.descriptorDir, "stopped.recovery.jsonl");+ stopped.descriptor.createdAt = new Date(now).toISOString();+ stopped.descriptor.updatedAt = new Date(now).toISOString();+ stopped.descriptor.consecutiveFailures = 0;+ stopped.descriptor.stopRequestedAt = new Date(now).toISOString();+ stopped.descriptorPath = join(supervisor.descriptorDir, "stopped.json");+ supervisor.persistWorker(stopped);+ const reopened = makeWorker("reopened", []);+ reopened.descriptor.sessionFile = sessionFile;+ supervisor.workers.set("reopened", reopened);++ const response = await supervisor.handleCommand(+ { id: "viewer", attachedActiveSessionIds: new Set<string>() },+ { id: "hb-list", type: "heartbeats_list" },+ );++ expect(response).toMatchObject({ success: true });+ expect(store.list().map((job) => job.status)).toEqual(["active"]);+ expect(existsSync(stopped.descriptorPath)).toBe(false);+ });+});diff --git a/packages/coding-agent/test/session-action-store.test.ts b/packages/coding-agent/test/session-action-store.test.tsindex e6a9ee752c..990f75f391 100644--- a/packages/coding-agent/test/session-action-store.test.ts+++ b/packages/coding-agent/test/session-action-store.test.ts@@ -238,7 +238,6 @@ describe("whole-tree eviction capability", () => {const idleSession = {isSessionActive: false,attachedClients: 0,- hasRegisteredHeartbeat: false,hasRegisteredCronJob: false,lastActivityAt: now - 90 * 60_000,};@@ -248,6 +247,7 @@ describe("whole-tree eviction capability", () => {isStopping: false,hasOwnerClient: false,isPreparingUpdateRestart: false,+ hasWakeBlindSchedule: false,sessions: [idleSession],};@@ -270,10 +270,10 @@ describe("whole-tree eviction capability", () => {{ sessions: [{ ...idleSession, isSessionActive: true }] },],["attached client", { sessions: [{ ...idleSession, attachedClients: 1 }] }],- ["heartbeat", { sessions: [{ ...idleSession, hasRegisteredHeartbeat: true }] }],["cron job", { sessions: [{ ...idleSession, hasRegisteredCronJob: true }] }],["missing activity timestamp", { sessions: [{ ...idleSession, lastActivityAt: Number.NaN }] }],["owner client", { hasOwnerClient: true }],+ ["wake-blind schedule", { hasWakeBlindSchedule: true }],["update preparation", { isPreparingUpdateRestart: true }],["disconnected worker", { isConnected: false }],["stopping worker", { isStopping: true }],@@ -296,7 +296,6 @@ describe("child passivation capability", () => {const idleChild = {isSessionActive: false,attachedClients: 0,- hasRegisteredHeartbeat: false,hasRegisteredCronJob: false,lastActivityAt: now - 90 * 60_000,hasParent: true,@@ -314,7 +313,6 @@ describe("child passivation capability", () => {["hydrating child", { isHydrating: true }],["busy child", { isSessionActive: true }],["attached child", { attachedClients: 1 }],- ["heartbeat child", { hasRegisteredHeartbeat: true }],["cron child", { hasRegisteredCronJob: true }],["recent child", { lastActivityAt: now - 89 * 60_000 }],["child without activity time", { lastActivityAt: Number.NaN }],diff --git a/packages/coding-agent/test/subagent-summary-line.test.ts b/packages/coding-agent/test/subagent-summary-line.test.tsindex f7808cd058..d08c515064 100644--- a/packages/coding-agent/test/subagent-summary-line.test.ts+++ b/packages/coding-agent/test/subagent-summary-line.test.ts@@ -93,10 +93,10 @@ describe("SubagentSummaryLine", () => {child("grandchild", "running", { parentId: "running" }),];- expect(countDirectSubagentStatuses(children, undefined, new Set(["heartbeat-session"]))).toEqual({+ expect(countDirectSubagentStatuses(children, undefined)).toEqual({total: 8,- running: 4,- idle: 2,+ running: 3,+ idle: 3,inactive: 2,});});@@ -280,7 +280,7 @@ describe("SubagentSummaryLine", () => {rosterStatus: "idle",} as SessionSummary;expect(isDirectAgentChild(rosterChild, { sessionId: "root-session" })).toBe(true);- expect(countRosterSubagentStatuses([rosterChild], { sessionId: "root-session" }, new Set())).toEqual({+ expect(countRosterSubagentStatuses([rosterChild], { sessionId: "root-session" })).toEqual({total: 1,running: 0,idle: 1,