/** * The process-task store: the one place that knows which tasks a session has, * how they are identified, and how a running process becomes a finished record. * * Every session owns one `TaskStore` under its state directory, and every change * to a record is followed by a save. Loading the first time a session is touched * is what makes history survive a restart: records come back from disk, and a * record that still says `running` is marked `interrupted` because whatever ran * it is gone. Nothing is adopted and nothing is killed on load — the store reads * files and leaves every process alone. * * @author mystery4f <40482524+mystery4f@users.noreply.github.com> */ import { stat } from "node:fs/promises"; import { resolve } from "node:path"; import { setTimeout as sleep } from "node:timers/promises"; import { elapsedOf } from "../base/format.js"; import { type OutputTail, readOutputFrom, readOutputTail } from "../base/output.js"; import { processOutputPath, sessionTaskDirectory, type TaskScope } from "../base/runtime-state.js"; import { DEFAULT_MAX_RUNNING_TASKS, DEFAULT_OUTPUT_CAP_BYTES, MAX_RUNNING_TASKS_ENV, } from "../base/settings.js"; import type { KillReason, ProcessTask, Task, TaskStatus } from "../base/task.js"; import type { OwnedTaskSession, TaskSessions } from "../base/task-sessions.js"; import { resolveShellPolicy, type ShellChoice, type ShellPolicy } from "./shell.js"; import { type RunningProcess, type StartProcessOptions, type StopOutcome, startProcess, } from "./supervisor.js"; export type { TaskScope }; export interface StartProcessTaskInput extends TaskScope { command: string; name?: string; /** * Runtime cap in whole milliseconds, measured from the start. The tool parses * seconds; the record and the timer speak milliseconds. */ timeoutMs?: number; /** Shell for this command; the configured one unless the call picks another. */ shell?: ShellChoice; /** * Directory for this call, relative to the session's cwd unless it is absolute. * Resolved once, before a record exists; the record keeps the absolute path. */ workingDirectory?: string; /** * Variables for the child only, merged over the extension's environment. Not * recorded: a task file is not a safe place for a token, and the child already * has what it needs. */ env?: Record; /** * The cmd loop whose fire starts this process (ADR-0014). The child keeps an * ordinary process id and carries the link in its record, never in the id. */ parentId?: string; /** One-based fire number of the owning loop; always given with `parentId`. */ fire?: number; } /** An id and an output file held for a command that runs in the foreground (ADR-0020). */ export interface ForegroundReservation { readonly id: string; /** Directory the command runs in, resolved before the spawn. */ readonly cwd: string; /** File the supervisor writes the command's output to. */ readonly outputPath: string; } /** What a foreground command needs before it can be spawned. */ export interface ReserveForegroundInput extends TaskScope { /** * Directory for this call, relative to the session's cwd unless it is absolute. * Same rule as a background task: resolved once, before anything is spawned. */ readonly workingDirectory?: string; } /** A reserved foreground command, handed to the supervisor. */ export interface SpawnForegroundInput { readonly command: string; readonly cwd: string; readonly outputPath: string; readonly env?: Record; readonly shell?: ShellChoice; /** Called once when a chunk is dropped for crossing the output cap. */ readonly onOutputCap?: () => void; } /** What a reservation becomes once a process stands behind it. */ export interface AdoptForegroundInput extends TaskScope { readonly command: string; readonly reservation: ForegroundReservation; /** The process already running: the one thing a detach hands over. */ readonly running: RunningProcess; /** * When the process itself started, before it was a task. The record's age and * its `createdAt` come from here, so a caller reporting a detached command does * not under-report how long it has been running. */ readonly startedAt?: number; readonly name?: string; } /** A task as it looks right now: the record plus the values that keep moving. */ export interface ProcessTaskView { task: ProcessTask; /** Milliseconds from creation to end, or to now while it runs. */ elapsedMs: number; /** Bytes in the output file, live for a running task. */ outputBytes: number; } /** What a stop is asked for. The reason defaults to the user's own kill. */ export interface StopTaskOptions { reason?: KillReason; /** Overrides the store's grace period, mostly for tests. */ graceMs?: number; /** Overrides the store's forced-kill confirmation window. */ confirmMs?: number; } /** How `stop` answered. */ export type StopTaskOutcome = "killed" | "already-finished" | "tree-survived"; export interface StopTaskResult { /** The record after the stop: finished whenever the outcome is `killed`. */ view: ProcessTaskView; outcome: StopTaskOutcome; /** Milliseconds the stop took. */ tookMs: number; /** * How long the polite signal was allowed to wait. Absent when nothing was * signalled, because a command that had already ended never reached a grace. */ graceMs?: number; /** What the system said, when the tree could not be confirmed gone. */ detail?: string; } /** How a wait answered: the record, and whether the wait caught the end. */ export interface WaitTaskResult { /** The record as it stood when the wait returned. */ view: ProcessTaskView; /** * True when the task ended before the deadline, false when the deadline * passed first and the view is still running. A deadline is not an error. */ waited: boolean; /** * True when the caller aborted the wait before the task ended. The task is * untouched: a cancelled wait is the user stopping the watch, not the work. */ cancelled: boolean; } /** What a follow read answered: the new bytes, and where the cursor now sits. */ export interface FollowTaskResult { /** The record as it stood when the read returned. */ view: ProcessTaskView; /** Output appended since this task's previous follow read, decoded as text. */ delta: string; /** Offset the read started at. */ from: number; /** Offset just past the bytes read; the next follow read starts here. */ offset: number; /** Bytes in `delta`. */ deltaBytes: number; /** True when the task has ended and the file has been read to its end. */ finished: boolean; /** True when the window passed with no new bytes; the task may still be running. */ timedOut: boolean; } export interface ProcessTasksOptions { platform?: NodeJS.Platform; env?: NodeJS.ProcessEnv; /** Clock seam for tests; defaults to `Date.now`. */ now?: () => number; /** Grace a polite kill gets before it is forced; defaults to the supervisor's. */ killGraceMs?: number; /** How long a forced kill gets to clear the tree; defaults to the supervisor's. */ killConfirmMs?: number; /** Bytes a task's output may hold; defaults to the documented 20 MiB. */ outputCapBytes?: number; /** * How many process tasks one session may run at once, children included: * defaults to the documented 20. A fire and a chain step are records of this * store too, so they meet the same ceiling (ADR-0014). */ maxRunningTasks?: number; /** * How a spawned command is supervised. Absent, the supervisor spawns a real * process and signals a real tree. A test supplies a fake so it can answer a * stop with `tree-survived` — a real `taskkill /T /F` nearly always wins, so * the surviving tree has no other deterministic seam. */ supervise?: (options: StartProcessOptions) => RunningProcess; /** * How long a stop that lost to a surviving tree waits before it is tried again; * defaults to a second. A kill that could not clear the tree has not ended the * task, so the wait between attempts is what keeps the record honest. */ survivedRetryMs?: number; /** * How often a follow call looks at the output file while it waits for new * bytes; defaults to 50ms. A test lowers it so the answer comes as soon as the * bytes land instead of on the next tick of a timer, without changing a single * thing the follow answers. */ followPollMs?: number; /** * Called once for every task that ends, with the record as it stands after * the final status was written. Announcing the task — a session message, a * panel refresh — is the caller's business, so this store stays silent. */ onFinish?: (view: ProcessTaskView) => void; /** Shared session loader; one instance is passed to every kind of store. */ sessions: TaskSessions; /** * Shell resolved at load time. Absent, the store resolves one from `env`: a task * started by a test still runs in the platform's default shell. */ shellPolicy?: ShellPolicy; } /** * The process store's view of a shared session: the loaded records plus the * processes this store is supervising. */ interface SessionTasks extends OwnedTaskSession { readonly running: Map; /** Why each running task is being stopped, kept until its exit is booked. */ readonly killReasons: Map; /** * The limits that have already ended tasks. Separate from `killReasons` * because a limit ends the task whether or not a signal reached it: a capped * command can exit on the same tick as the dropped byte. */ readonly limitReasons: Map; /** Pending runtime caps, kept so a natural end can cancel its timer. */ readonly runtimeCaps: Map>; /** * Pending waits on a task's end, keyed by task id. `finish` resolves them, so * a wait is woken by the end event instead of polling the record. */ readonly waiters: Map void>>; /** * Where each task's follow read has reached, in output bytes. Follow is the * only reader that moves a cursor, so a plain `pretty_task_bg_logs` tail neither seeds nor * consumes one; nothing here is persisted because a cursor belongs to the * session that asked, not to the task. */ readonly followOffsets: Map; /** * How a queued step will start, keyed by task id. A record holds what is * durable; a per-call shell, variables and runtime cap are not, so they wait * here between the queue and the launch. Nothing is persisted, and that is * enough: a restart settles every waiting step, so no step is ever launched * from a plan older than the process that holds it (ADR-0013). */ readonly queued: Map; } /** The launch-time half of a step: what a record has no field for. */ interface QueuedLaunch { env?: Record; shell?: ShellChoice; timeoutMs?: number; } const NAME_LIMIT = 48; /** * How long a stop waits for the exit bookkeeping once the tree is confirmed * gone. Past that, the stop settles the record itself. */ const EXIT_WAIT_MS = 2000; /** * How long a stop that could not clear its tree waits before trying the kill * again. A survivor is not an ending, so the reason and the deadline stay with the * record, and the retry is what eventually honours them. */ const SURVIVED_RETRY_MS = 1000; /** * How often a follow read looks at the output file while it waits for new * bytes. Small enough that a line shows up promptly, large enough that a * minute-long follow is a few thousand stats, not a busy loop. */ const FOLLOW_POLL_MS = 50; /** Map the supervisor's answer onto the store's, which speaks of tasks. */ const STOP_OUTCOMES = { stopped: "killed", "already-exited": "already-finished", "tree-survived": "tree-survived", } satisfies Record; function errorMessage(error: unknown): string { return error instanceof Error ? error.message : String(error); } /** * Wait at most `timeoutMs` for a promise to settle. True when it did: a promise * that never settles must not hold the kill's answer hostage. */ async function settledWithin(promise: Promise, timeoutMs: number): Promise { let timer: ReturnType | undefined; const timeout = new Promise((resolve) => { timer = setTimeout(() => { resolve(false); }, timeoutMs); }); try { return await Promise.race([ promise.then( () => true, () => true, ), timeout, ]); } finally { if (timer !== undefined) clearTimeout(timer); } } /** A readable default name from the command, for when the caller gives none. */ export function deriveTaskName(command: string): string { const line = command.split("\n", 1)[0] ?? ""; const collapsed = line.trim().replace(/\s+/g, " "); if (collapsed.length === 0) return "command"; if (collapsed.length <= NAME_LIMIT) return collapsed; return `${collapsed.slice(0, NAME_LIMIT - 1)}…`; } export class ProcessTasks { private readonly platform: NodeJS.Platform; private readonly env: NodeJS.ProcessEnv | undefined; private readonly now: () => number; /** * Keyed by state directory, not session id: the directory already encodes cwd * and session, and the promise keeps two turns from loading the same history * twice. */ private readonly sessions = new Map>(); private readonly killGraceMs: number | undefined; private readonly killConfirmMs: number | undefined; private readonly outputCapBytes: number; /** The ceiling `docs/scope-v1.md` promises, and the key that moves it. */ private readonly maxRunningTasks: number; private readonly supervise: (options: StartProcessOptions) => RunningProcess; /** How long a stop that lost to a surviving tree waits before trying again. */ private readonly survivedRetryMs: number; /** How often a follow read looks at the output file while it waits. */ private readonly followPollMs: number; private readonly onFinish: ((view: ProcessTaskView) => void) | undefined; /** The shell every task starts in, resolved once so a bad config fails at load. */ private readonly shellPolicy: ShellPolicy; /** Loads and saves the shared record set; both kinds write through it. */ private readonly hub: TaskSessions; constructor(options: ProcessTasksOptions) { this.platform = options.platform ?? process.platform; this.env = options.env; this.now = options.now ?? Date.now; // Required, not defaulted: a second hub would load the same directory into a // second map, and whichever saved last would erase the other's records. this.hub = options.sessions; this.killGraceMs = options.killGraceMs; this.killConfirmMs = options.killConfirmMs; this.outputCapBytes = options.outputCapBytes ?? DEFAULT_OUTPUT_CAP_BYTES; this.maxRunningTasks = options.maxRunningTasks ?? DEFAULT_MAX_RUNNING_TASKS; this.supervise = options.supervise ?? startProcess; this.survivedRetryMs = options.survivedRetryMs ?? SURVIVED_RETRY_MS; this.followPollMs = options.followPollMs ?? FOLLOW_POLL_MS; this.onFinish = options.onFinish; this.shellPolicy = options.shellPolicy ?? resolveShellPolicy({ platform: this.platform, env: this.env }); } /** Start a command in the background and return its record immediately. */ async start(input: StartProcessTaskInput): Promise { const session = await this.session(input); // The ceiling is checked before a record exists: a refused start leaves // nothing behind to explain, and the caller that asked — a `pretty_task_bg_run`, a fire — // reports the reason itself. const refusal = this.capRefusal(session); if (refusal !== undefined) throw new Error(refusal); const task = await this.record(session, input, "running"); session.tasks.set(task.id, task); await this.ignite(session, task, input, (reason) => { session.tasks.delete(task.id); throw new Error(reason); }); return task; } /** * Queue a step without starting it (ADR-0013): a chain owns the queue and says * when a step's turn comes. The record exists right away so the caller can quote * its id and a reader can see what is ahead, but nothing is spawned until * `launch`. A queued step is `waiting` and carries its chain in `parentId`, which * is also what keeps it out of the processes list (ADR-0014). */ async queueStep(input: StartProcessTaskInput): Promise { const session = await this.session(input); const task = await this.record(session, input, "waiting"); session.tasks.set(task.id, task); session.queued.set(task.id, { env: input.env, shell: input.shell, timeoutMs: input.timeoutMs, }); await this.persist(session); return task; } /** * Start a queued step now. Undefined means there was nothing to launch: the * session has no such task, or the step is no longer `waiting` because it has * already run or a stop settled it. A step that cannot be spawned ends `failed` * here instead of staying `waiting`, because the chain behind it is waiting for * an end, not for a process. */ async launch(session: OwnedTaskSession, id: string): Promise { const runtime = await this.attached(session); const task = runtime.tasks.get(id); if (task === undefined || task.kind !== "process" || task.status !== "waiting") return undefined; const plan = runtime.queued.get(id) ?? {}; runtime.queued.delete(id); const refusal = this.capRefusal(runtime); if (refusal !== undefined) { // A launch has no caller to throw at: the chain reads the step's record, so // the refusal is written there as the step's own failure. The record keeps // its place in the queue and ends `failed`, which ends the chain with this // reason rather than leaving a step `waiting` forever. this.finish(runtime, task, undefined, null, refusal); return task; } const at = this.now(); task.status = "running"; task.updatedAt = at; await this.ignite(runtime, task, plan, (reason) => this.finish(runtime, task, undefined, null, reason), ); return task; } /** * Reserve the id and the output file a foreground command will use, before it * is spawned (ADR-0020). * * Both have to exist before the process does: the supervisor opens the output * file at spawn, so the directory must be there first, and the id has to be * settled while the command is still in the foreground — a detach then changes * who is waiting, not what the task is called. */ async reserveForeground(input: ReserveForegroundInput): Promise { const session = await this.session(input); await session.store.ensureDirectory(); const cwd = await this.resolveWorkingDirectory(input.cwd, input.workingDirectory); const id = this.createId(session); return { id, cwd, outputPath: processOutputPath(session.directory, id) }; } /** * Spawn a reserved command into the foreground. Same supervisor, same shell * policy, same output cap as a background task; the difference is who holds the * handle. The caller keeps it, and that handle is what makes a detach possible: * nothing has to be signalled, respawned or renamed. */ spawnForeground(input: SpawnForegroundInput): RunningProcess { return this.supervise({ command: input.command, cwd: input.cwd, outputPath: input.outputPath, maxOutputBytes: this.outputCapBytes, ...(input.onOutputCap !== undefined ? { onOutputCap: input.onOutputCap } : {}), platform: this.platform, env: this.env, ...(input.env !== undefined ? { envOverrides: input.env } : {}), shellPolicy: this.shellPolicy, ...(input.shell !== undefined ? { shell: input.shell } : {}), }); } /** * Turn a running foreground command into an ordinary task (ADR-0020): the * record appears under the id the run already used, the process that is already * running is booked under it, and its exit ends the task like any other end. * Nothing is spawned and the pid does not change, so the command never notices. * * The ceiling is checked before the record exists, for the reason a start checks * it: a refused detach leaves nothing behind, and the caller keeps waiting — a * command that cannot become a task stays a foreground command rather than * disappearing. */ async adoptForeground(input: AdoptForegroundInput): Promise { const session = await this.session(input); const refusal = this.capRefusal(session); if (refusal !== undefined) throw new Error(refusal); const task = await this.record( session, { cwd: input.cwd, sessionId: input.sessionId, command: input.command, ...(input.name !== undefined ? { name: input.name } : {}), workingDirectory: input.reservation.cwd, }, "running", { ...input.reservation, origin: "foreground", ...(input.startedAt !== undefined ? { startedAt: input.startedAt } : {}), }, ); session.tasks.set(task.id, task); // The record is on disk before the caller stops waiting, so a detach that // returns an id always has a task behind that id. this.book(session, task, input.running); task.outputBytes = input.running.bytesWritten(); await this.persist(session); return task; } /** * Build a process record. The directory is settled before the record exists: a * cwd that cannot be used rejects the call instead of leaving a task that never * started. */ private async record( session: SessionTasks, input: StartProcessTaskInput, status: TaskStatus, /** * The id and file a foreground run reserved, and when its process started; * absent for a fresh start. A detached command has been running for a while * before it becomes a task, and the record's age is the process's age: a clock * that restarted at the detach would report a 23-second process as 7 seconds. */ reservation?: ForegroundReservation & { readonly origin?: ProcessTask["origin"]; readonly startedAt?: number; }, ): Promise { const cwd = await this.resolveWorkingDirectory(input.cwd, input.workingDirectory); const id = reservation?.id ?? this.createId(session); const name = input.name?.trim(); const createdAt = reservation?.startedAt ?? this.now(); return { id, kind: "process", name: name !== undefined && name.length > 0 ? name : deriveTaskName(input.command), status, createdAt, updatedAt: createdAt, command: input.command, cwd, outputPath: reservation?.outputPath ?? processOutputPath(session.directory, id), outputBytes: 0, ...(input.parentId !== undefined ? { parentId: input.parentId } : {}), ...(input.fire !== undefined ? { fire: input.fire } : {}), ...(reservation?.origin !== undefined ? { origin: reservation.origin } : {}), }; } /** * Hand one command to the supervisor. The shell, the variables and the cap are * not part of a record (a task file is no place for a token), so they arrive here * as the plan the caller kept: `start` builds one from its input, a queued step * keeps one until its turn comes. */ /** * The one ladder a spawn walks: spawn, book, persist, cap. `fail` decides what a * refusal means to the caller, which is the only thing a start and a launch * ever disagreed about — a start has a call to throw at, a launch has a record * to write the reason into. */ private async ignite( session: SessionTasks, task: ProcessTask, plan: QueuedLaunch, fail: (reason: string) => void, ): Promise { let running: RunningProcess; try { // The spawn opens the output file, so the session directory has to exist // before it: this is the one write that does not go through the store. await session.store.ensureDirectory(); running = this.spawn(session, task, plan); } catch (error) { fail(errorMessage(error)); return; } this.book(session, task, running); // The id is about to reach the model, so the record reaches the disk first: // an extension that crashes right after this turn still knows the task. await this.persist(session); this.scheduleRuntimeCap(session, task.id, plan.timeoutMs); } private spawn(session: SessionTasks, task: ProcessTask, plan: QueuedLaunch): RunningProcess { return this.supervise({ command: task.command, cwd: task.cwd, outputPath: task.outputPath, maxOutputBytes: this.outputCapBytes, onOutputCap: () => { // The reason is recorded here, before the stop is asked for: a command // can exit on the same tick as the dropped byte, and that exit must // not turn a capped task back into a completed one. session.limitReasons.set(task.id, "output_cap"); // The session is in hand, so the stop needs no scope to find it again. void this.stopRecord(session, task, { reason: "output_cap" }); }, platform: this.platform, env: this.env, envOverrides: plan.env, shellPolicy: this.shellPolicy, shell: plan.shell, }); } /** * The refusal a start gets when the session already runs as many process tasks * as it may, or `undefined` when there is room. * * Counting records rather than calling the supervisor keeps fires and chain * steps inside the ceiling: a fire is a process record with a loop for a parent, * a step one with a chain for a parent, and a child of `pretty_task_bg_run` is a record too * (ADR-0014). One pass over the loaded records is the count, so nothing has to be * kept in step with the running map. */ private capRefusal(session: SessionTasks): string | undefined { let running = 0; for (const task of session.tasks.values()) { if (task.kind === "process" && task.status === "running") running += 1; } if (running < this.maxRunningTasks) return undefined; // The message is the report: a fire and a chain step fail out of sight, and // the recorded error is the only place their reason is read. It names the // ceiling and the key that moves it, because "too many tasks" without either // leaves the reader unable to act. return ( `This session already has ${String(running)} running process tasks; the limit is ` + `${String(this.maxRunningTasks)} (${MAX_RUNNING_TASKS_ENV}). ` + "Stop one with pretty_task_bg_kill before starting another." ); } /** * Attach the supervisor to a record: the pid, the running entry, and the exit * that ends the task. `start` and `launch` both end here, so a step's end is * booked exactly like the end of a task the user started. */ private book(session: SessionTasks, task: ProcessTask, running: RunningProcess): void { task.pid = running.pid; session.running.set(task.id, running); void running.exit.then( (exit) => { this.finish(session, task, running, exit.exitCode); }, (error: unknown) => { this.finish(session, task, running, null, errorMessage(error)); }, ); } /** * Start one task's command again as a new record. The old row stays: rerunning * adds history rather than rewriting it, so the reader keeps both outcomes. */ async rerun(scope: TaskScope, id: string): Promise { const previous = await this.get(scope, id); if (previous === undefined || previous.task.kind !== "process") return undefined; const task = await this.start({ cwd: scope.cwd, sessionId: scope.sessionId, command: previous.task.command, name: previous.task.name, workingDirectory: previous.task.cwd, }); return this.view(await this.session(scope), task); } /** * Every process record of the session, children included, oldest first. The panel * counts them (ADR-0014) and resolves a chain's steps through it; a row still * stands for a root only. */ async listAll(scope: TaskScope): Promise { const session = await this.session(scope); return [...session.tasks.values()] .filter((task): task is ProcessTask => task.kind === "process") .map((task) => this.view(session, task)); } /** Every root process task of the session, oldest first, including loaded history. */ async list(scope: TaskScope): Promise { // A child is a record, not a row: a loop's fire and a chain's step read through // their own tools, and only the parent they belong to is listed (ADR-0014). const all = await this.listAll(scope); return all.filter((view) => view.task.parentId === undefined); } async get(scope: TaskScope, id: string): Promise { const session = await this.session(scope); const task = session.tasks.get(id); return task === undefined || task.kind !== "process" ? undefined : this.view(session, task); } /** The tail of a task's output. Undefined when the session has no such task. */ async logs( scope: TaskScope, id: string, options: { lines: number; maxBytes?: number }, ): Promise<{ view: ProcessTaskView; tail: OutputTail } | undefined> { const session = await this.session(scope); const task = session.tasks.get(id); if (task === undefined || task.kind !== "process") return undefined; // Every reader of a task's output comes through here, so one decoder serves // `pretty_task_bg_logs`, the panel and a completion notice alike (ADR-0008). const tail = await readOutputTail(task.outputPath, { ...options, platform: this.platform }); return { view: this.view(session, task), tail }; } /** * The output appended to a task's file since this task's previous follow read. * Undefined when the session has no such task. The cursor is in memory and * belongs to the session: it starts at the beginning of the file, moves only * past bytes an answer actually carried, and a plain tail read leaves it * alone. `finished` says the record has ended, so no later read will grow. * A read waits up to `timeoutMs` for new bytes and returns as soon as some * arrive; an empty delta with `timedOut` is an answer, not an error. */ async follow( scope: TaskScope, id: string, timeoutMs: number, ): Promise { const session = await this.session(scope); const task = session.tasks.get(id); if (task === undefined || task.kind !== "process") return undefined; const deadline = this.now() + timeoutMs; for (;;) { const from = session.followOffsets.get(id) ?? 0; const read = await readOutputFrom(task.outputPath, from, { platform: this.platform }); session.followOffsets.set(id, read.to); const finished = task.endedAt !== undefined; if (read.text.length > 0 || finished) { return { view: this.view(session, task), delta: read.text, from: read.from, offset: read.to, deltaBytes: read.to - read.from, finished, timedOut: false, }; } // Nothing yet: give the process a moment, then look again. A finished // task never reaches this wait, so an ended task answers at once. const remaining = deadline - this.now(); if (remaining <= 0) { return { view: this.view(session, task), delta: "", from: read.from, offset: read.to, deltaBytes: 0, finished: false, timedOut: true, }; } await sleep(Math.min(this.followPollMs, remaining)); } } /** * Wait for one task to end, for `timeoutMs` to pass, or for `signal` to abort. * Undefined means the session has no such task. The deadline is an answer, not * an error: the view is whatever the record says then, and `waited` says which * happened. An aborted wait answers at once and leaves the task running. */ async wait( scope: TaskScope, id: string, timeoutMs: number, signal?: AbortSignal, ): Promise { const session = await this.session(scope); const task = session.tasks.get(id); if (task === undefined || task.kind !== "process") return undefined; // A task nobody supervises has no later end to wait for: history loaded from // disk, and a record another end already settled, answer right away. `waited` // still tells the truth: a record left `running` without a supervisor caught // no end, so it answers false even though the wait returns at once. if (!session.running.has(id)) { return { view: this.view(session, task), waited: task.endedAt !== undefined, cancelled: false, }; } // Waiting is a listener on the end event, not a poll: `finish` resolves it on // the same tick the record gets its final status, so the wake-up sees the end. // An abort is a third way out and must release the turn too (issue: Esc could // not interrupt a wait); it resolves the same listener without touching the // process, so a cancelled wait still reports the running record. // An already-aborted signal is not waited on at all: the caller asked to stop // before the wait began, and the record is still the answer. let cancelled = signal?.aborted === true; if (signal?.aborted !== true) { await new Promise((resolve) => { const waiters = session.waiters.get(id) ?? new Set<() => void>(); session.waiters.set(id, waiters); const listener = (): void => { cancelled = signal?.aborted === true; clearTimeout(timer); signal?.removeEventListener("abort", listener); waiters.delete(listener); if (waiters.size === 0) session.waiters.delete(id); resolve(); }; const timer = setTimeout(listener, timeoutMs); waiters.add(listener); signal?.addEventListener("abort", listener, { once: true }); // An abort that landed between the check above and this registration // never fires the listener, so the wait is settled here instead. if (signal?.aborted === true) listener(); }); } return { view: this.view(session, task), waited: task.endedAt !== undefined, cancelled }; } /** * Stop one task and everything its command started. Undefined means the * session has no such task; every other case is an answer, including a task * that had already finished on its own. */ async stop( scope: TaskScope, id: string, options: StopTaskOptions = {}, ): Promise { const session = await this.session(scope); const loaded = session.tasks.get(id); if (loaded === undefined) return undefined; // A record of the loop kind is not this store's to stop. if (loaded.kind !== "process") return undefined; return this.stopRecord(session, loaded, options); } /** * Stop every running child of one loop, across loaded sessions. The loop's * own stop path goes through here so a paused or deleted command loop never * leaves a process running that no root row points at (ADR-0014). */ async stopChildren(parentId: string, options: StopTaskOptions = {}): Promise { // pi-lens-ignore: no-single-promise-in-promise-methods -- a Map's values spread to one promise per session, not a single promise const sessions = await Promise.all([...this.sessions.values()]); const results: StopTaskResult[] = []; for (const session of sessions) { for (const task of [...session.tasks.values()]) { if (task.kind !== "process" || task.parentId !== parentId) continue; if (task.status !== "running" || !session.running.has(task.id)) continue; results.push(await this.stopRecord(session, task, options)); } } return results; } private async stopRecord( session: SessionTasks, task: ProcessTask, options: StopTaskOptions, ): Promise { const running = session.running.get(task.id); if (running === undefined) { return { view: this.view(session, task), outcome: "already-finished", tookMs: 0 }; } // The reason rides with the task, not with the signal: the supervisor only // reports whether anything was signalled, the store knows who asked. The // first ask wins — a second stop joins the one already in flight instead of // relabelling its end. if (!session.killReasons.has(task.id)) session.killReasons.set(task.id, options.reason ?? "user"); const stopped = await running.stop({ graceMs: options.graceMs ?? this.killGraceMs, confirmMs: options.confirmMs ?? this.killConfirmMs, }); // A tree that survived the kill has not ended anything: the record keeps // running, the reason stays with it so its eventual exit is still the kill // that was asked for, and the deadline stays armed now that it was not met. // The answer says so on the record, because a kill that lost must be loud. if (stopped.outcome === "tree-survived") { this.noteSurvival(session, task, stopped.detail); this.scheduleStop(session, task.id, this.survivedRetryMs, options); return { view: this.view(session, task), outcome: STOP_OUTCOMES[stopped.outcome], tookMs: stopped.tookMs, graceMs: stopped.graceMs, detail: stopped.detail, }; } this.clearRuntimeCap(session, task.id); // A stop that got an answer must leave a finished record, never `running`: // the exit bookkeeping usually arrives on its own, and when it does not the // stop settles the record here. `finish` ignores a record already settled, // so a late exit cannot contradict this answer. if (stopped.outcome === "stopped" && !(await settledWithin(running.exit, EXIT_WAIT_MS))) { this.finish(session, task, running, null); } session.killReasons.delete(task.id); return { view: this.view(session, task), outcome: STOP_OUTCOMES[stopped.outcome], tookMs: stopped.tookMs, graceMs: stopped.graceMs, detail: stopped.detail, }; } private view(session: SessionTasks, task: ProcessTask): ProcessTaskView { const running = session.running.get(task.id); return { task, elapsedMs: elapsedOf(task, this.now()), outputBytes: running === undefined ? task.outputBytes : running.bytesWritten(), }; } private finish( session: SessionTasks, task: ProcessTask, /** * The supervisor of the process that ended, or undefined when there never was * one: a step that could not be spawned still needs an end in its record. */ running: RunningProcess | undefined, exitCode: number | null, failure?: string, ): void { session.running.delete(task.id); this.clearRuntimeCap(session, task.id); // A limit ends the task whether or not a signal reached it: the dropped byte // is the end of the story even when the command exits on the same tick. const limitReason = session.limitReasons.get(task.id); // A stop of our own only counts when a signal actually went out: a task that // ended on its own during a stop keeps its natural end instead of becoming // a kill. const stopReason = running?.signalled() === true ? session.killReasons.get(task.id) : undefined; const killReason = limitReason ?? stopReason; session.killReasons.delete(task.id); session.limitReasons.delete(task.id); if (running !== undefined) task.outputBytes = running.bytesWritten(); // A stop that was already answered settled this record; a late exit may only // improve its byte count, never overwrite what the kill said. if (task.endedAt !== undefined) return; const at = this.now(); task.exitCode = exitCode; task.endedAt = at; // Ending is a transition a reader cares about, so the row moves up in the // panel even though its output stopped growing this instant (ADR-0010). task.updatedAt = at; if (killReason !== undefined) { // We asked for this end, so it is a kill even when the exit code looks // ordinary — and the reason says who asked. task.status = "killed"; task.killReason = killReason; // A note from a kill that once lost is history now that the kill landed: // the record ends killed, and a stale "could not be stopped" would lie. task.error = undefined; } else if (failure !== undefined) { task.status = "failed"; task.error = failure; } else if (exitCode === 0) { task.status = "completed"; } else { task.status = "failed"; task.error = exitCode === null ? "the command was terminated by a signal" : `exited with code ${exitCode}`; } // A wait is released only after the final status is in the record: the // caller's view has to be the end it was waiting for, exit code and all. this.settleWaiters(session, task.id); // The record reaches the disk before the notice leaves: a reader who restarts // the session right after the notice has to find the same ending on disk. void this.persist(session).then(() => { this.onFinish?.(this.view(session, task)); }); } /** Release every pending wait on a task whose record just got its end. */ private settleWaiters(session: SessionTasks, id: string): void { const waiters = session.waiters.get(id); if (waiters === undefined) return; session.waiters.delete(id); for (const waiter of waiters) waiter(); } /** * Stop the task when its runtime cap passes. The stop is the same one the user * would ask for, with the reason recorded, so a task that outlived its cap ends * `killed` / `timeout` rather than `failed`. */ private scheduleRuntimeCap( session: SessionTasks, id: string, timeoutMs: number | undefined, ): void { if (timeoutMs === undefined) return; this.scheduleStop(session, id, timeoutMs, { reason: "timeout" }); } /** * Arm the stop at `delayMs` from now, replacing the timer already armed for the * task: one task waits on one stop at a time, whether that stop comes from a * deadline, a cap, or a kill that has to be tried again. */ private scheduleStop( session: SessionTasks, id: string, delayMs: number, options: StopTaskOptions, ): void { this.clearRuntimeCap(session, id); const timer = setTimeout(() => { const task = session.tasks.get(id); // The session is already in hand, so the stop reaches the record it named and // needs no scope of its own — which is also what lets a launched step, whose // turn came long after the call that queued it, keep its cap. if (task === undefined || task.kind !== "process") return; void this.stopRecord(session, task, options); }, delayMs); // A waiting stop must not be the reason the host process stays alive. timer.unref(); session.runtimeCaps.set(id, timer); } /** * Say on the record that a kill could not clear its tree. The record is still * running, so this is the only place a reader — the panel, `pretty_task_bg_status`, the next * `pretty_task_bg_kill` — can learn that the task outlived a stop that was already paid for. */ private noteSurvival(session: SessionTasks, task: ProcessTask, detail: string | undefined): void { const note = `the process tree could not be stopped: ${ detail ?? "it was still there after the forced kill" }. The task is still running; the kill will be tried again.`; // Every retry that loses says the same sentence: one note, not one a second. if (task.error === note) return; task.error = note; task.updatedAt = this.now(); void this.persist(session); } /** Cancel a task's runtime cap; a task that ends on its own leaves no timer. */ private clearRuntimeCap(session: SessionTasks, id: string): void { const timer = session.runtimeCaps.get(id); if (timer !== undefined) clearTimeout(timer); session.runtimeCaps.delete(id); } /** * Hand the current records to the store. The store queues its own writes and * treats persistence as best effort, so a save never fails a turn and a full * disk never fails a task. Callers that need the record durable (a fresh task * whose id is about to be handed out) await it; the process exit does not. */ private persist(session: SessionTasks): Promise { return this.hub.persist(session); } private session(scope: TaskScope): Promise { const directory = sessionTaskDirectory(scope.cwd, scope.sessionId); const existing = this.sessions.get(directory); if (existing !== undefined) return existing; const opened = this.hub.session(scope).then((shared) => this.attach(shared)); this.sessions.set(directory, opened); return opened; } /** * The runtime half of a session another store already holds: the processes this * store supervises, keyed by the records both stores share. A chain hands its * session in when it launches a step, so the queue and the process it starts * work on one map of records instead of two copies of the same history. */ private async attached(shared: OwnedTaskSession): Promise { const existing = this.sessions.get(shared.directory); if (existing !== undefined) return existing; const opened = this.attach(shared); this.sessions.set(shared.directory, opened); return opened; } private async attach(shared: OwnedTaskSession): Promise { // A loaded record carries the output size it was last saved with; the file // itself is the truth. Refresh once per process store, even when the loop // tools loaded the session first. for (const record of [...shared.tasks.values()]) { shared.tasks.set(record.id, await this.withCurrentOutput(record)); } return { ...shared, running: new Map(), killReasons: new Map(), limitReasons: new Map(), runtimeCaps: new Map(), waiters: new Map(), followOffsets: new Map(), queued: new Map(), }; } /** * Resolve the directory this call runs in and make sure it is usable. A * relative request is resolved against the session's cwd, the same base the * task record uses; without a request the session's cwd is used as it is. */ private async resolveWorkingDirectory( sessionCwd: string, requested: string | undefined, ): Promise { const cwd = resolve(sessionCwd, requested ?? "."); let isDirectory: boolean; try { const directory = await stat(cwd); isDirectory = directory.isDirectory(); } catch (error) { const code = error instanceof Error && "code" in error ? String(error.code) : ""; if (code === "ENOENT" || code === "ENOTDIR") { throw new Error(`Working directory ${cwd} does not exist.`); } throw new Error(`Working directory ${cwd} cannot be used: ${errorMessage(error)}`); } if (!isDirectory) { throw new Error(`Working directory ${cwd} is not a directory.`); } return cwd; } /** * A record read from disk carries the output size it was last written with. The * file itself is the truth: a crash can lose the last save, not the bytes. */ private async withCurrentOutput(record: Task): Promise { if (record.kind !== "process") return record; try { const info = await stat(record.outputPath); return { ...record, outputBytes: info.size }; } catch { return record; } } private createId(session: SessionTasks): string { return this.hub.createId(session, "process"); } }