Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 16 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -227,7 +227,21 @@ Every `pollSeconds` (default 300) the daemon wakes and runs one iteration:
`<worktree>/.validation-artifacts/<pr>/` to `~/.foreman/<name>/artifacts/<pr>/`, because a
headless session cannot write outside its worktree and the worktree is removed at merge. A
session that ends without a valid outcome is retried up to `limits.attempts` (3) times; if all
fail, the issue is labelled `blocked` with a log excerpt and unassigned.
fail, the issue is labelled `blocked` with a log excerpt and unassigned. Two API refusals are
handled apart, because neither is the task's fault and resuming cannot get past either
(`src/session-end.ts` holds every match on the API's wording):
- **Usage limit** (`You've hit your … limit`, or a spent five-hour or seven-day window in the
stream's rate-limit event). Not retried and not blocked. The claim stays open, as after
`stop`, with one note on the issue. Dispatching pauses until the window's reset plus two
minutes, or for 30 minutes when the reset is unknown. The pause is kept in `state.json` as
`pausedUntil`, survives a restart, and shows in `status` and on the page as
`paused: usage limit until 22:52Z`. The first tick after it resumes the session. The resumed
session is a new dispatch, so it counts nothing against `limits.attempts`. `foreman go`
clears the pause at once.
- **Safeguard flag** (`… safeguards flagged this message`). The flagged session is never
resumed. The next attempt starts one new session in the same worktree, told that the
earlier work is already there. A second flag blocks the issue with
`safeguard flag on 2 sessions (req_…)`.
10. **Phase check.** If every task under a phase epic is closed, the phase-closer is dispatched.
Then the planner, which is gated three ways: the epic must carry **`agent-ready`** (the owner's
go-ahead — without it the foreman never plans anything), no approved phase may still be
Expand Down Expand Up @@ -726,7 +740,7 @@ All of these work from any terminal on the Mac. Inside a configured `repoDir` yo
<host>: aborted by operator`, unassigns itself and moves a round-1 builder issue back to Ready.
The worktree is left for reuse. If the daemon is already dead and `state.json` shows an
unfinished claim, `abort` posts the release itself.
- **Start again:** `foreman -p widgets go` removes `STOP` and wakes the daemon, or `launchctl
- **Start again:** `foreman -p widgets go` removes `STOP`, clears a usage-limit pause, and wakes the daemon, or `launchctl
kickstart`s it, or prints the start command. `foreman -p widgets restart` stops and starts,
clearing the `STOP` that `stop` left.
- **This Mac, next poll only:** `touch ~/.foreman/widgets/STOP`. Preflight fails on the next
Expand Down
14 changes: 12 additions & 2 deletions src/cli/daemon.ts
Original file line number Diff line number Diff line change
Expand Up @@ -158,12 +158,22 @@ export async function runDaemon(
model: previous?.model ?? null,
maxSessionsPerDay: previous?.maxSessionsPerDay ?? null,
theme: previous?.theme ?? pickTheme(instance.name, others),
// A restart during a usage-limit pause must not dispatch straight into the limit.
pausedUntil: previous?.pausedUntil ?? null,
pauseReason: previous?.pauseReason ?? null,
}),
);
// `go` is the owner overruling a usage-limit pause (the limit was raised, or it reset early):
// clear it before the wake, so the tick that follows dispatches.
const clearPause = () => {
if (!store.get().pausedUntil) return;
store.patch({ pausedUntil: null, pauseReason: null });
log("info", "usage-limit pause cleared by go");
};
const controller = new Controller((mode) => {
log("info", "operator requested", { mode });
store.patch({ stopping: { mode, at: new Date().toISOString() } });
});
}, clearPause);
controller.install();
const lock = new Mutex();
const ctx = realCtx(
Expand Down Expand Up @@ -211,7 +221,7 @@ export async function runDaemon(
act: async (cmd) => {
if (cmd === "go") {
if (existsSync(stopFile)) unlinkSync(stopFile);
controller.wake();
controller.go();
return "STOP removed; tick requested";
}
writeFileSync(stopFile, "");
Expand Down
13 changes: 13 additions & 0 deletions src/control.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,19 @@ describe("Controller", () => {
});
});

describe("go", () => {
it("SIGUSR2 is go: it runs the go handler, then wakes the sleeping loop", async () => {
const order: string[] = [];
const c = new Controller(undefined, () => order.push("go"));
const fake = new EventEmitter();
c.install(fake as unknown as NodeJS.Process);
const p = c.sleep(5_000).then(() => order.push("woke"));
fake.emit("SIGUSR2");
await p;
expect(order).toEqual(["go", "woke"]);
});
});

describe("Mutex", () => {
it("serialises overlapping runs", async () => {
const m = new Mutex();
Expand Down
15 changes: 13 additions & 2 deletions src/control.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,11 @@ export class Controller {
private mode: StopMode | null = null;
private wakers = new Set<() => void>();

constructor(private readonly onChange: (mode: StopMode) => void = () => {}) {}
constructor(
private readonly onChange: (mode: StopMode) => void = () => {},
/** The owner's `go`: runs before the wake, so the tick it triggers sees its effect. */
private readonly onGo: () => void = () => {},
) {}

get signal(): AbortSignal {
return this.ac.signal;
Expand All @@ -29,6 +33,12 @@ export class Controller {
return true;
}

/** The owner said go: clear what `onGo` clears, then run the next tick now. */
go(): void {
this.onGo();
this.wake();
}

wake(): void {
const ws = this.wakers;
this.wakers = new Set();
Expand All @@ -52,7 +62,8 @@ export class Controller {
p.on("SIGTERM", () => this.request("stop"));
p.on("SIGINT", () => this.request("stop"));
p.on("SIGUSR1", () => this.request("abort"));
p.on("SIGUSR2", () => this.wake());
// `ctl go` is the only sender of SIGUSR2.
p.on("SIGUSR2", () => this.go());
}
}

Expand Down
12 changes: 12 additions & 0 deletions src/ctl.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -294,6 +294,18 @@ describe("ctlGo", () => {
expect(log.stop).toBe(false);
expect(log.kills).toEqual(["SIGUSR2 100"]);
});
it("clears a usage-limit pause even with no daemon running, so the next start dispatches", async () => {
const { d, dir } = deps({ launchdInstalled: async () => true });
writeState(dir, {
...base(),
exitedAt: "2026-09-04T05:00:00.000Z",
pausedUntil: "2099-01-01T00:00:00.000Z",
pauseReason: "usage limit",
});
await ctlGo(d);
expect(readState(dir)?.pausedUntil).toBeNull();
expect(readState(dir)?.pauseReason).toBeNull();
});
it("kickstarts launchd when installed, else prints the start command", async () => {
const a = deps({ launchdInstalled: async () => true });
await ctlGo(a.d);
Expand Down
6 changes: 6 additions & 0 deletions src/ctl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -291,6 +291,12 @@ export async function ctlGo(d: CtlDeps): Promise<void> {
d.removeStop();
d.out("STOP file removed");
const s = readState(d.stateDir);
// A live daemon clears its own pause on SIGUSR2. A stopped one carries the pause over into the
// next start, so it is cleared here, in the file that start reads.
if (s && !d.pidAlive(s.pid) && s.pausedUntil) {
writeState(d.stateDir, { ...s, pausedUntil: null, pauseReason: null });
d.out("usage-limit pause cleared");
}
if (s && d.pidAlive(s.pid)) {
d.kill(s.pid, "SIGUSR2");
d.out("tick requested");
Expand Down
100 changes: 100 additions & 0 deletions src/dispatch.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import {
trustWorktree,
} from "./dispatch.ts";
import type { Exec } from "./exec.ts";
import { endReason } from "./session-end.ts";
import { emptyActivity } from "./stream.ts";

const cfg = parseConfig(
Expand Down Expand Up @@ -355,6 +356,105 @@ describe("dispatchWithRetry", () => {
});
});

const fixture = (name: string) =>
readFileSync(join(import.meta.dirname, `../test/fixtures/${name}.jsonl`), "utf8");

/** Plays one recorded session per spawn, through the stream callback as `realSpawn` does. */
function replay(names: string[]) {
const calls: { args: string[]; input: string }[] = [];
const spawn: Spawner = async (_cmd, args, opts) => {
const text = fixture(names[Math.min(calls.length, names.length - 1)] as string);
calls.push({ args, input: opts.input });
for (const l of text.split("\n").filter((x) => x.length > 0)) opts.onStdoutLine?.(l);
return { code: 0, stdout: text, stderr: "", timedOut: false, interrupted: false };
};
return { calls, spawn };
}
const FRESH_ID = "77777777-7777-7777-7777-777777777777";

describe("dispatchWithRetry on an API refusal", () => {
it("does not retry a usage limit", async () => {
const { calls, spawn } = replay(["refusal-usage-limit"]);
const r = await dispatchWithRetry(req, cfg, { spawn, onAttempt: async () => {} });
expect(calls).toHaveLength(1);
expect(r.outcome).toBeNull();
expect(r.end).toEqual({
cause: "usage_limit",
requestId: null,
resetsAt: "2026-11-09T22:50:00.000Z",
});
});

it("retries a flagged resumed session once, as a new session, then stops naming the cause", async () => {
const { calls, spawn } = replay(["refusal-safeguard"]);
const attempts: DispatchRequest[] = [];
const r = await dispatchWithRetry({ ...req, resume: true }, cfg, {
spawn,
onAttempt: async (a) => {
attempts.push(a);
},
newSessionId: () => FRESH_ID,
});
expect(calls).toHaveLength(2);
expect(calls[0]?.args.join(" ")).toContain(`--resume ${req.sessionId}`);
// Never the flagged id again: resuming resends the flagged context.
expect(calls[1]?.args.join(" ")).toContain(`--session-id ${FRESH_ID}`);
expect(calls[1]?.args).not.toContain("--resume");
expect(attempts.map((a) => [a.sessionId, a.resume])).toEqual([
[req.sessionId, true],
[FRESH_ID, false],
]);
// Same worktree, and the new session is told the earlier work is already in it.
expect(attempts[1]?.worktree).toBe(req.worktree);
expect(calls[1]?.input).toContain("already in this worktree");
expect(calls[1]?.input).not.toContain("You are resuming interrupted work");
expect(r.outcome).toBeNull();
expect(r.end?.cause).toBe("safeguard");
expect(endReason(r)).toBe(
"safeguard flag on 2 sessions (req_011Cgt4qVTW9B5dwTGegArfo, req_011Cgt4qVTW9B5dwTGegArfo)",
);
});

it("runs the one fresh session even when the flag lands on the last allowed attempt", async () => {
const { calls, spawn } = replay(["refusal-safeguard"]);
const r = await dispatchWithRetry(
req,
cfg,
{ spawn, onAttempt: async () => {}, newSessionId: () => FRESH_ID },
1,
);
expect(calls).toHaveLength(2);
expect(calls[1]?.args.join(" ")).toContain(`--session-id ${FRESH_ID}`);
expect(r.flagged).toHaveLength(2);
});

it("returns the fresh session's outcome when it gets past the flag", async () => {
let n = 0;
const flagged = replay(["refusal-safeguard"]).spawn;
const spawn: Spawner = async (cmd, args, opts) => {
n++;
if (n === 1) return flagged(cmd, args, opts);
return { code: 0, stdout: okJson(), stderr: "", timedOut: false, interrupted: false };
};
const r = await dispatchWithRetry(req, cfg, {
spawn,
onAttempt: async () => {},
newSessionId: () => FRESH_ID,
});
expect(n).toBe(2);
expect(r.outcome?.outcome).toBe("pr_opened");
});

it("keeps resuming, as today, a session that ends with no refusal", async () => {
const { calls, spawn } = replay(["refusal-none"]);
const r = await dispatchWithRetry(req, cfg, { spawn, onAttempt: async () => {} });
expect(calls.map((c) => c.args.includes("--resume"))).toEqual([false, true, true]);
expect(calls.every((c) => c.args.join(" ").includes(req.sessionId))).toBe(true);
expect(r.end?.cause).toBe("other");
expect(endReason(r)).toBe("error_max_turns after retries");
});
});

describe("interrupts", () => {
it("realSpawn kills the child on abort and reports interrupted", async () => {
const ac = new AbortController();
Expand Down
70 changes: 63 additions & 7 deletions src/dispatch.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { spawn } from "node:child_process";
import { randomUUID } from "node:crypto";
import { existsSync, readFileSync, writeFileSync } from "node:fs";
import { homedir } from "node:os";
import { join } from "node:path";
Expand All @@ -9,6 +10,7 @@ import type { FeedEntry } from "./feed.ts";
import { log } from "./log.ts";
import { FORBIDDEN_ENV } from "./preflight.ts";
import { defaultRepoConfig } from "./repo-config.ts";
import { classifyEnd, type SessionEnd } from "./session-end.ts";
import { EFFORT_DEFAULT_LEVEL, type EffortLevel } from "./state-file.ts";
import { type Activity, emptyActivity, foldEvent } from "./stream.ts";
import type { Role } from "./types.ts";
Expand Down Expand Up @@ -87,6 +89,10 @@ export interface SessionResult {
timedOut: boolean;
stderr: string;
interrupted: boolean;
/** Why a session with no outcome ended (`classifyEnd`); absent when it has an outcome. */
end?: SessionEnd;
/** The request id of each safeguard-flagged session this dispatch ran, in order. */
flagged?: (string | null)[];
}

export function slugify(title: string): string {
Expand Down Expand Up @@ -401,6 +407,8 @@ export interface DispatchDeps {
signal?: AbortSignal;
onSpawn?: (pid: number) => void;
onActivity?: (activity: Activity, entries: FeedEntry[]) => void;
/** The id a fresh session after a safeguard flag runs under; `randomUUID` when absent. */
newSessionId?: () => string;
}

export async function runSession(
Expand Down Expand Up @@ -439,6 +447,7 @@ export async function runSession(
parsed.interrupted = r.interrupted;
if (r.interrupted && !parsed.outcome) parsed.subtype = "interrupted";
if (!parsed.sessionId) parsed.sessionId = req.sessionId;
if (!parsed.outcome && !parsed.interrupted) parsed.end = classifyEnd(parsed, activity);
deps.onActivity?.(activity, [
{
t: new Date().toISOString(),
Expand All @@ -463,26 +472,72 @@ export async function runSession(
return parsed;
}

/** Attempt 1 as requested; later attempts resume the same session id. Stops on a valid outcome. */
/**
* What a session started after a safeguard flag is told. It cannot resume the flagged
* conversation, so it starts cold in a worktree that already holds the earlier work.
*/
export function freshAfterFlagNotes(defaultBranch = "main"): string {
return `An earlier session on this task was stopped by an API safeguard flag and cannot be resumed, so this is a new session. The earlier work is already in this worktree: commits on this branch and any uncommitted changes. Run \`git status\` and \`git log origin/${defaultBranch}..HEAD\`, read your last Progress comment on the issue, and continue from the worktree's current state. Do not redo finished steps and do not discard uncommitted changes.`;
}

/**
* Attempt 1 as requested; later attempts resume the same session id. Stops on a valid outcome.
*
* Two API refusals are not the task's doing, and resuming cannot get past either:
* - a usage limit returns at once. The caller pauses the daemon; it is neither retried nor
* counted against `attempts`.
* - a safeguard flag is never resumed, because resuming resends the flagged context. The next
* attempt is one new session in the same worktree; a second flag returns.
*/
export async function dispatchWithRetry(
req: DispatchRequest,
cfg: ForemanConfig,
deps: DispatchDeps,
attempts = 3,
): Promise<SessionResult> {
let last: SessionResult | null = null;
for (let attempt = req.attempt; attempt < req.attempt + attempts; attempt++) {
let sessionId = req.sessionId;
let resume = req.resume;
let notes = req.notes;
const flagged: (string | null)[] = [];
let end = req.attempt + attempts;
for (let attempt = req.attempt; attempt < end; attempt++) {
// An abort landing between attempts (the first attempt always runs) must not post another
// "session …" comment and spawn a child just to kill it.
if (attempt > req.attempt && deps.signal?.aborted) break;
const r = await runSession(
{ ...req, attempt, resume: req.resume || attempt > req.attempt },
cfg,
deps,
);
const r = await runSession({ ...req, attempt, sessionId, resume, notes }, cfg, deps);
last = r;
if (r.outcome) return r;
if (r.interrupted) return r; // operator stop/abort: never retry
if (r.end?.cause === "usage_limit") {
log("warn", "session stopped by the usage limit; not retrying", {
issue: req.issue,
attempt,
resetsAt: r.end.resetsAt,
});
return r;
}
if (r.end?.cause === "safeguard") {
flagged.push(r.end.requestId);
r.flagged = [...flagged];
if (flagged.length > 1) return r;
log("warn", "session flagged by API safeguards; retrying once as a new session", {
issue: req.issue,
attempt,
requestId: r.end.requestId,
});
// The one fresh session runs even when the flag used up the last attempt.
end = Math.max(end, attempt + 2);
sessionId = (deps.newSessionId ?? randomUUID)();
resume = false;
notes = [freshAfterFlagNotes(deps.defaultBranch ?? "main"), req.notes]
.filter(Boolean)
.join("\n");
continue;
}
// Every later attempt resumes the session that just ended: the requested one, or the new one
// a safeguard flag started.
resume = true;
log("warn", "session ended without outcome; retrying", {
issue: req.issue,
attempt,
Expand All @@ -491,5 +546,6 @@ export async function dispatchWithRetry(
});
}
if (!last) throw new Error("dispatchWithRetry: attempts must be at least 1");
if (flagged.length > 0) last.flagged = [...flagged];
return last;
}
Loading
Loading