Skip to content
Merged
17 changes: 9 additions & 8 deletions doc/fleet-schedule-registry.md
Original file line number Diff line number Diff line change
Expand Up @@ -390,18 +390,19 @@ registered. The primary user's repos are maintained by git's own
per-user launchd agents, which `git maintenance start` installs outside
Nix; they are not recorded here until a review reads them on the Mac.

## Surface 6 — PM-stack process intervals (4 entries)
## Surface 6 — PM-stack process intervals (5 entries)

Recurring loops owned by PM-stack processes (aggregator, console). These are not
Recurring loops owned by PM-stack processes (aggregator, console, dispatch). These are not
external scheduler surfaces; this inventory records timers that run only
while the service is alive.

| name/id | repo/scope | cadence | state | owner / scope | prompt/brief pointer | budget | kill criteria | created | last review |
| --------------------------- | --------------------- | ---------------- | ---------------------------- | ------------- | -------------------------------------------------------------- | ------------ | ------------------------------------------------------------------------------------------------------------------------------------ | ---------- | ----------- |
| SLO journal sampler (#9988) | developing-today/code | every 60 seconds | live aggregator process only | issue #9988 | `pm-stack/aggregator/src/server.ts` (`SLO_SAMPLE_INTERVAL_MS`) | not recorded | Remove/disable if the health view or append-only journal becomes unavailable; sampler is unref'd and does not keep the process alive | 2026-11-18 | 2026-11-18 |
| Console state refresh | developing-today/code | every 5 seconds | live console process only | PR #12452 | `pm-stack/console/src/docs.ts` (`Docs.start`) | not recorded | Reads only while the app was opened in the last 10 minutes; remove if state is no longer served from memory | 2026-11-22 | 2026-11-22 |
| Console notifier | developing-today/code | every 60 seconds | live console process only | PR #12452 | `pm-stack/console/src/notify.ts` (`Notifier.start`) | not recorded | Reads only while a device is subscribed; remove if notifications move to another sender | 2026-11-22 | 2026-11-22 |
| Console report to the edge | developing-today/code | 5 to 30 seconds | live console process only | PR #12505 | `pm-stack/console/src/sync.ts` (`EdgeLink.start`) | not recorded | Runs only when PM_CONSOLE_EDGE_URL is set; remove if the app is no longer served from the edge | 2026-11-22 | 2026-11-22 |
| name/id | repo/scope | cadence | state | owner / scope | prompt/brief pointer | budget | kill criteria | created | last review |
| -------------------------------- | --------------------- | --------------------------------------------------- | ----------------------------- | ------------- | ---------------------------------------------------------------------------- | ------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------- | ----------- |
| SLO journal sampler (#9988) | developing-today/code | every 60 seconds | live aggregator process only | issue #9988 | `pm-stack/aggregator/src/server.ts` (`SLO_SAMPLE_INTERVAL_MS`) | not recorded | Remove/disable if the health view or append-only journal becomes unavailable; sampler is unref'd and does not keep the process alive | 2026-11-18 | 2026-11-18 |
| dispatch worktree sweep (#12217) | developing-today/code | `PM_DISPATCH_WORKTREE_SWEEP_SECONDS` (default 900s) | live dispatch process only | issue #12217 | `pm-stack/dispatch/src/server.ts` (`startWorktreeSweep()`; config in `src/config.ts`) | not recorded | Set to `off` or remove/disable the sweep if registry/session safety checks become unavailable; timer is unref'd and does not keep the process alive | 2026-11-21 | 2026-11-21 |
| Console state refresh | developing-today/code | every 5 seconds | live console process only | PR #12452 | `pm-stack/console/src/docs.ts` (`Docs.start`) | not recorded | Reads only while the app was opened in the last 10 minutes; remove if state is no longer served from memory | 2026-11-22 | 2026-11-22 |
| Console notifier | developing-today/code | every 60 seconds | live console process only | PR #12452 | `pm-stack/console/src/notify.ts` (`Notifier.start`) | not recorded | Reads only while a device is subscribed; remove if notifications move to another sender | 2026-11-22 | 2026-11-22 |
| Console report to the edge | developing-today/code | 5 to 30 seconds | live console process only | PR #12505 | `pm-stack/console/src/sync.ts` (`EdgeLink.start`) | not recorded | Runs only when PM_CONSOLE_EDGE_URL is set; remove if the app is no longer served from the edge | 2026-11-22 | 2026-11-22 |

## Surface 7 — Cloudflare Worker cron triggers (2 entries)

Expand Down
22 changes: 22 additions & 0 deletions pm-stack/dispatch/src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,14 @@ export interface Config {
* (PM_DISPATCH_WORKTREE_ROOT, default ~/git/fleet; "off" runs in the
* requested directory as before). code#12213. */
worktreeRoot: string | null;
/** Registry file holding the worktree <-> task/session association
* the cleanup lifecycle retires trees from (code#12217). Only
* meaningful when worktreeRoot is set. */
worktreeRegistryFile: string;
/** Seconds between worktree cleanup sweeps (PM_DISPATCH_WORKTREE_
* SWEEP_SECONDS, default 900; "off" disables the timer — the
* failure-path cleanup still runs). code#12217. */
worktreeSweepSeconds: number | null;
}

export function loadConfig(env: Record<string, string | undefined> = process.env): Config {
Expand Down Expand Up @@ -123,5 +131,19 @@ export function loadConfig(env: Record<string, string | undefined> = process.env
env.PM_DISPATCH_WORKTREE_ROOT?.trim().toLowerCase() === "off"
? null
: s(env.PM_DISPATCH_WORKTREE_ROOT, join(homedir(), "git", "fleet")),
worktreeRegistryFile: s(
env.PM_DISPATCH_WORKTREE_REGISTRY,
join(homedir(), ".local", "state", "pm-dispatch", "worktree-registry.json"),
),
worktreeSweepSeconds: (() => {
const v = s(env.PM_DISPATCH_WORKTREE_SWEEP_SECONDS, "900");
if (v.toLowerCase() === "off") return null;
if (!/^\d+$/.test(v) || Number(v) < 1 || Number(v) > 2_147_483) {
throw new Error(
`Invalid PM_DISPATCH_WORKTREE_SWEEP_SECONDS "${v}": expected a positive integer from 1 to 2147483, or "off"`,
);
}
return Number(v);
})(),
};
}
94 changes: 83 additions & 11 deletions pm-stack/dispatch/src/launch_failure.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,8 +73,20 @@ export async function compensateOrphanedIssue(
/** Mutable context shared by launchSession and its failure handler. */
export interface LaunchFailureContext {
sessionId: string | null;
/** The dispatch worktree created for this launch, if any (#12217).
* Set the moment the tree exists — before the session — so a failure
* at session creation can still clean the tree up. */
worktree: string | null;
}

/** Run once the launch's session is CONFIRMED gone (dispatch itself
* deleted it), or — when no session was ever recorded — after the
* failure was established. Returns the cleanup outcome for the note,
* or null when there is nothing to retire. Never throws: a worktree
* outcome must not mask the launch failure being reported. */
export type RetireWorktree = (sessionId?: string | null) => Promise<{ worktree: string; removed: boolean; reason: string } | null>;
export type ReportRetirement = (outcome: { worktree: string; removed: boolean; reason: string }) => void;

/**
* Run the part of a launch that follows successful session creation.
* Retain the new session ID so the failure handler can record it before
Expand All @@ -98,17 +110,48 @@ export async function handleLaunchFailure(
e: unknown,
sessionId: string | null = null,
deleteSession?: (sessionId: string) => Promise<void>,
retireWorktree?: RetireWorktree,
reportRetirement: ReportRetirement = (outcome) => {
if (!outcome.removed) {
console.warn(`[pm-dispatch] task worktree ${outcome.worktree} retained: ${outcome.reason}`);
}
},
): Promise<string> {
const msg = e instanceof Error ? e.message : String(e);
// #12217: best-effort worktree retirement, reported, never thrown —
// and never attempted while the session may still be live.
const retireSafely = async (retiredSessionId: string | null = sessionId): Promise<{ worktree: string; removed: boolean; reason: string } | null> => {
if (!retireWorktree) return null;
try {
const outcome = await retireWorktree(retiredSessionId);
if (outcome && !outcome.removed) safelyReportRetirement(outcome);
return outcome;
} catch (re) {
const reason = re instanceof Error ? re.message : String(re);
const outcome = { worktree: "unknown", removed: false, reason };
safelyReportRetirement(outcome);
return outcome;
}
};
const safelyReportRetirement = (outcome: { worktree: string; removed: boolean; reason: string }) => {
try {
reportRetirement(outcome);
} catch {
/* reporting must not mask the original launch failure */
}
};
if (e instanceof ClaimLostError) {
// Lost the claim race (#10737): the task and its issue now belong
// to the worker that claimed it, so neither is cancelled, noted or
// closed. Only this launch's own session is cleaned up.
if (sessionId != null && deleteSession) {
try {
await deleteSession(sessionId);
await retireSafely(sessionId);
} catch {
/* best-effort: the session never received the task's claim */
// Deletion may have failed while the session is still live. Run
// the fail-closed evidence check so the retained worktree is visible.
await retireSafely(sessionId);
}
}
return msg;
Expand All @@ -122,14 +165,43 @@ export async function handleLaunchFailure(
cancelError = ce instanceof Error ? ce.message : String(ce);
}
let cleanupError: string | null = null;
if (sessionId != null) {
if (!deleteSession) {
cleanupError = "session deletion callback unavailable";
} else {
try {
await deleteSession(sessionId);
} catch (de) {
cleanupError = de instanceof Error ? de.message : String(de);
let worktreeNote = "";
if (sessionId == null) {
// createSession can time out or lose its response after the server
// accepted the request. The session may still come up later, so the
// tree cannot be retired on an empty session-list snapshot.
const outcome = retireWorktree
? await retireSafely(null) ?? {
worktree: "unknown",
removed: false,
reason: "session creation outcome is unknown; a session may still be live",
}
: null;
if (outcome) {
worktreeNote = outcome.removed
? `\n\nTask worktree ${outcome.worktree} was removed after the failed launch.`
: `\n\nTask worktree ${outcome.worktree} was retained: ${outcome.reason}.`;
}
} else if (!deleteSession) {
cleanupError = "session deletion callback unavailable";
} else {
try {
await deleteSession(sessionId);
// The session is confirmed gone: only now may the worktree be
// considered for retirement (#12217).
const outcome = await retireSafely();
if (outcome) {
worktreeNote = outcome.removed
? `\n\nTask worktree ${outcome.worktree} was removed after the failed launch.`
: `\n\nTask worktree ${outcome.worktree} was retained: ${outcome.reason}.`;
}
} catch (de) {
cleanupError = de instanceof Error ? de.message : String(de);
const outcome = await retireSafely(sessionId);
if (outcome) {
worktreeNote = outcome.removed
? `\n\nTask worktree ${outcome.worktree} was removed after the failed launch.`
: `\n\nTask worktree ${outcome.worktree} was retained: ${outcome.reason}.`;
}
}
}
Expand All @@ -142,8 +214,8 @@ export async function handleLaunchFailure(
: `\n\nOpenCode session ${sessionId} may still be live; session cleanup failed: ${cleanupError}`;
const note =
cancelError == null
? `Dispatch launch FAILED and queue task #${taskId} was cancelled.${sessionNote}\n\nError: ${msg}`
: `Dispatch launch FAILED and cancelling queue task #${taskId} FAILED — the task may still be queued or claimed and needs cleanup.${sessionNote}\n\nError: ${msg}\nCancellation error: ${cancelError}`;
? `Dispatch launch FAILED and queue task #${taskId} was cancelled.${sessionNote}${worktreeNote}\n\nError: ${msg}`
: `Dispatch launch FAILED and cancelling queue task #${taskId} FAILED — the task may still be queued or claimed and needs cleanup.${sessionNote}${worktreeNote}\n\nError: ${msg}\nCancellation error: ${cancelError}`;
try {
await github.comment(repo, issueNumber, note);
} catch {
Expand Down
15 changes: 14 additions & 1 deletion pm-stack/dispatch/src/opencode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ import { readFile } from "node:fs/promises";
import type { ModelRef } from "./validate.ts";
import { outboundTimeout } from "./fetchTimeout.ts";

const SESSION_LIST_LIMITS = [1_000, 10_000, 100_000] as const;

export class OpenCodeError extends Error {
status = 502;
constructor(
Expand Down Expand Up @@ -111,7 +113,18 @@ export class OpenCodeClient {
}

async listSessions(): Promise<unknown> {
return this.api("GET", "/api/session");
for (const limit of SESSION_LIST_LIMITS) {
const data = await this.api("GET", `/api/session?limit=${limit}`);
// OpenCode silently truncates the default session list at 50. A
// response below its requested limit is the only completeness proof
// this endpoint offers; if the largest supported probe is still full,
// do not let cleanup infer that an omitted session is absent.
if (!Array.isArray(data)) return data;
if (data.length < limit) return data;
}
throw new OpenCodeError(
`opencode session list reached the maximum completeness limit (${SESSION_LIST_LIMITS.at(-1)})`,
);
}

/** Read one session's current state (issue #5555): the raw session
Expand Down
Loading