diff --git a/README.md b/README.md index e24ecdd..c24d348 100644 --- a/README.md +++ b/README.md @@ -227,7 +227,21 @@ Every `pollSeconds` (default 300) the daemon wakes and runs one iteration: `/.validation-artifacts//` to `~/.foreman//artifacts//`, 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 @@ -726,7 +740,7 @@ All of these work from any terminal on the Mac. Inside a configured `repoDir` yo : 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 diff --git a/src/cli/daemon.ts b/src/cli/daemon.ts index c7de766..faba745 100644 --- a/src/cli/daemon.ts +++ b/src/cli/daemon.ts @@ -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( @@ -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, ""); diff --git a/src/control.test.ts b/src/control.test.ts index 7acbcce..3850992 100644 --- a/src/control.test.ts +++ b/src/control.test.ts @@ -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(); diff --git a/src/control.ts b/src/control.ts index 5e449b1..931236b 100644 --- a/src/control.ts +++ b/src/control.ts @@ -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; @@ -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(); @@ -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()); } } diff --git a/src/ctl.test.ts b/src/ctl.test.ts index b69e6a1..f9e7e84 100644 --- a/src/ctl.test.ts +++ b/src/ctl.test.ts @@ -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); diff --git a/src/ctl.ts b/src/ctl.ts index 51fffae..f85be5e 100644 --- a/src/ctl.ts +++ b/src/ctl.ts @@ -291,6 +291,12 @@ export async function ctlGo(d: CtlDeps): Promise { 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"); diff --git a/src/dispatch.test.ts b/src/dispatch.test.ts index c5d40b3..66982d4 100644 --- a/src/dispatch.test.ts +++ b/src/dispatch.test.ts @@ -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( @@ -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(); diff --git a/src/dispatch.ts b/src/dispatch.ts index a7f35cf..618ddf3 100644 --- a/src/dispatch.ts +++ b/src/dispatch.ts @@ -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"; @@ -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"; @@ -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 { @@ -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( @@ -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(), @@ -463,7 +472,23 @@ 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, @@ -471,18 +496,48 @@ export async function dispatchWithRetry( attempts = 3, ): Promise { 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, @@ -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; } diff --git a/src/ledger.ts b/src/ledger.ts index 2342b36..384f6e4 100644 --- a/src/ledger.ts +++ b/src/ledger.ts @@ -30,6 +30,12 @@ export const fmt = { `session ${id} interrupted on ${host}: stopped by operator after ${minutes}m`, aborted: (host: string) => `released by ${host}: aborted by operator`, unblocked: (host: string) => `unblocked by owner via foreman@${host}`, + /** + * Deliberately none of CLAIM, SESSION or TERMINAL, and not `blocked by`: the claim stays open + * so the first tick after the reset resumes this session. + */ + usageLimit: (id: string, host: string, until: string) => + `usage limit reached on foreman@${host}: session ${id} paused until ${until}; the claim stays open and the session resumes then`, planPrStuck: (host: string, pr: number, sha: string, reason: string) => `plan PR #${pr} cannot merge at ${sha}: ${reason}. Fix it or merge it by hand (foreman@${host})`, }; diff --git a/src/loop.test.ts b/src/loop.test.ts index 54599d0..77f0ab6 100644 --- a/src/loop.test.ts +++ b/src/loop.test.ts @@ -8,7 +8,7 @@ import { parseConfig } from "./config.ts"; import type { Spawner } from "./dispatch.ts"; import { type Exec, realExec } from "./exec.ts"; import type { GitHubApi } from "./github.ts"; -import { fmt } from "./ledger.ts"; +import { fmt, openClaim } from "./ledger.ts"; import { ACTIVITY_FLUSH_MS, type Ctx, @@ -26,6 +26,7 @@ import { } from "./loop.ts"; import type { LabelledIssue, NotifyEvent, NotifyPort } from "./notify.ts"; import { defaultRepoConfig } from "./repo-config.ts"; +import { plan } from "./state.ts"; import type { Issue } from "./types.ts"; const cfg = parseConfig( @@ -1930,3 +1931,169 @@ describe("modelFor", () => { expect(modelFor(ctx({ state: st.store }), ["model:--flag"])).toBe("sonnet"); }); }); + +describe("API refusals", () => { + const fixture = (name: string) => + readFileSync(join(import.meta.dirname, `../test/fixtures/${name}.jsonl`), "utf8"); + /** Plays a recorded session through the stream callback, as `realSpawn` does. */ + const replaySpawn = + (name: string, counter: { n: number } = { n: 0 }): Spawner => + async (_cmd, _args, opts) => { + counter.n++; + const text = fixture(name); + 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 }; + }; + /** The bodies posted on one issue, in order, as the ledger would read them back. */ + const posted = (calls: string[], n: number) => + calls + .filter((c) => c.startsWith(`comment issue ${n} `)) + .map((c, k) => comment(c.slice(`comment issue ${n} `.length), `2026-09-03T12:00:0${k}Z`)); + + it("a usage limit pauses the daemon, keeps the claim open for a resume, and blocks nothing", async () => { + const i = issue({ number: 794, title: "feat: tokyo bounds", status: "In Progress" }); + const { gh, calls } = fakeGh([i]); + const n = recordNotify(); + const st = memState(); + const dir = mkdtempSync(join(tmpdir(), "tt-loop-")); + const spawns = { n: 0 }; + await execute( + { type: "claim", issue: 794, role: "builder", pr: null, round: 1 }, + ctx({ + gh, + notify: n.port, + state: st.store, + stateDir: dir, + spawn: replaySpawn("refusal-usage-limit", spawns), + }), + ); + expect(spawns.n).toBe(1); + expect(calls.some((c) => c.includes("blocked"))).toBe(false); + expect(calls.some((c) => c.startsWith("unassign"))).toBe(false); + expect(n.kinds()).toEqual([]); + expect(st.get().pausedUntil).toBe("2026-11-09T22:52:00.000Z"); + expect(st.get().pauseReason).toBe("usage limit"); + expect(st.get().current).toBeNull(); + // One short note, and the claim still open with this session: the next tick after the reset + // resumes it rather than starting over, and nothing counts against `limits.attempts`. + const bodies = posted(calls, 794); + const notes = bodies.filter((c) => c.body.includes("usage limit")); + expect(notes).toHaveLength(1); + expect(notes[0]?.body).toContain("2026-11-09 22:52Z"); + const issueAfter = { ...i, comments: bodies }; + expect(openClaim(bodies)?.sessionId).toMatch(/^[0-9a-f-]{36}$/); + expect(plan(snapshot({ issues: [issueAfter] }))[0]?.type).toBe("resume"); + const line = JSON.parse(readFileSync(join(dir, "sessions.log"), "utf8").trim()); + expect(line.outcome).toBe("usage_limit"); + }); + + it("a safeguard flag on the fresh retry blocks with the cause, never 'success after retries'", async () => { + const i = issue({ number: 795, title: "feat: report" }); + const { gh, calls } = fakeGh([i]); + const n = recordNotify(); + const spawns = { n: 0 }; + await execute( + { type: "claim", issue: 795, role: "builder", pr: null, round: 1 }, + ctx({ + gh, + notify: n.port, + stateDir: mkdtempSync(join(tmpdir(), "tt-loop-")), + spawn: replaySpawn("refusal-safeguard", spawns), + }), + ); + expect(spawns.n).toBe(2); + const reason = + "safeguard flag on 2 sessions (req_011Cgt4qVTW9B5dwTGegArfo, req_011Cgt4qVTW9B5dwTGegArfo)"; + expect(calls).toContain("addLabels issue 795 blocked"); + expect( + calls.some((c) => c.startsWith(`comment issue 795 blocked by foreman@mac-a: ${reason}`)), + ).toBe(true); + expect(calls.some((c) => c.includes("success after retries"))).toBe(false); + expect(n.events).toEqual([{ kind: "blocked", issue: 795, title: "feat: report", reason }]); + }); + + it("a session that finished as its window ran out still pauses the next one", async () => { + const i = issue({ number: 796 }); + const { gh } = fakeGh([i]); + const st = memState(); + const spent = fixture("refusal-usage-limit") + .split("\n") + .find((l) => l.includes("rate_limit_event")) as string; + const done = okSpawn({ outcome: "pr_opened", pr: 5, notes: "" }); + await execute( + { type: "claim", issue: 796, role: "builder", pr: null, round: 1 }, + ctx({ + gh, + state: st.store, + stateDir: mkdtempSync(join(tmpdir(), "tt-loop-")), + spawn: async (cmd, args, opts) => { + opts.onStdoutLine?.(spent); + return done(cmd, args, opts); + }, + }), + ); + expect(st.get().pausedUntil).toBe("2026-11-09T22:52:00.000Z"); + }); + + it("runForever sleeps until pausedUntil instead of the poll interval", async () => { + const st = memState(); + st.store.patch({ pausedUntil: "2026-09-03T13:00:00.000Z", pauseReason: "usage limit" }); + const seconds: number[] = []; + const stop = new Error("stop"); + await expect( + runForever(ctx({ state: st.store }), { + // The tick that hit the limit did work, which would otherwise mean "tick again at once". + iterate: async () => ({ didWork: true, action: "claim" }), + sleep: async (ms) => { + seconds.push(ms / 1000); + throw stop; + }, + }), + ).rejects.toThrow("stop"); + expect(seconds).toEqual([3600]); + expect(st.get().nextTickAt).toBe("2026-09-03T13:00:00.000Z"); + }); + + it("runForever ignores a pause that has already ended", async () => { + const st = memState(); + st.store.patch({ pausedUntil: "2026-09-03T11:00:00.000Z", pauseReason: "usage limit" }); + const seconds: number[] = []; + const stop = new Error("stop"); + await expect( + runForever(ctx({ state: st.store }), { + iterate: async () => ({ didWork: false, action: null }), + sleep: async (ms) => { + seconds.push(ms / 1000); + throw stop; + }, + }), + ).rejects.toThrow("stop"); + expect(seconds).toEqual([300]); + }); + + it("runOnce refuses to dispatch while paused, naming the reset", async () => { + const st = memState(); + // Preflight runs on the real clock, like the daily cap it sits beside. + const until = new Date(Date.now() + 3600_000).toISOString(); + st.store.patch({ pausedUntil: until, pauseReason: "usage limit" }); + const n = recordNotify(); + let spawned = false; + const r = await runOnce( + ctx({ + state: st.store, + notify: n.port, + spawn: async () => { + spawned = true; + throw new Error("no session while paused"); + }, + }), + ); + expect(r.didWork).toBe(false); + expect(spawned).toBe(false); + expect(st.get().lastPreflight).toEqual({ + ok: false, + reason: `paused: usage limit until ${until.slice(11, 16)}Z`, + }); + expect(n.parked).toEqual([`paused: usage limit until ${until.slice(11, 16)}Z`]); + }); +}); diff --git a/src/loop.ts b/src/loop.ts index 859a828..365d0d6 100644 --- a/src/loop.ts +++ b/src/loop.ts @@ -42,6 +42,13 @@ import { graphqlBudget, preflight } from "./preflight.ts"; import { writeSessionFiles } from "./prompts.ts"; import { ledgerInterrupt } from "./release.ts"; import { defaultRepoConfig, type RepoConfig } from "./repo-config.ts"; +import { + endReason, + exhaustedResetAt, + formatResetAt, + pauseUntil, + USAGE_LIMIT_REASON, +} from "./session-end.ts"; import { appendMerge, appendSession, @@ -568,6 +575,14 @@ async function runRole(ctx: Ctx, r: RunRole): Promise { } return; } + if (!result.outcome && result.end?.cause === "usage_limit") { + await pauseForUsageLimit(ctx, r, result, current, model); + return; + } + // A session can return its outcome on the very turn its window runs out; the next one would + // be refused on its first turn, so the pause starts now all the same. + const spentReset = current.activity ? exhaustedResetAt(current.activity) : null; + if (result.outcome && spentReset) setPause(ctx, pauseUntil(spentReset, ctx.now())); if (result.interrupted && result.outcome) { const mode = ctx.stopMode() ?? "stop"; log("info", "session finished despite interrupt; applying its outcome", { @@ -603,6 +618,49 @@ async function runRole(ctx: Ctx, r: RunRole): Promise { await applyOutcome(ctx, r, result, worktree); } +function setPause(ctx: Ctx, until: string): void { + ctx.state?.patch({ pausedUntil: until, pauseReason: USAGE_LIMIT_REASON }); + log("warn", "Claude usage limit spent; dispatching paused", { until }); +} + +/** + * The API stopped the session, not the task: nothing is wrong with the issue, so it is neither + * blocked nor released. Like an operator `stop`, the claim stays open — assignee, worktree and + * session id all kept — and the first tick after the reset resumes it with its context intact, + * as a new dispatch that counts nothing against `limits.attempts`. Releasing it instead would + * lose the fix-round labels `prepareSession` already removed. No `finished` comment, which + * would close the claim; one short note says what happened and when work resumes. + */ +async function pauseForUsageLimit( + ctx: Ctx, + r: RunRole, + result: SessionResult, + current: CurrentSession, + model: string, +): Promise { + const { cfg, gh } = ctx; + const until = pauseUntil(result.end?.resetsAt ?? null, ctx.now()); + setPause(ctx, until); + appendSession(ctx.stateDir, { + t: ctx.now(), + host: cfg.host, + role: r.role, + issue: r.issue.number, + sessionId: result.sessionId, + attempt: current.attempt, + costUsd: result.costUsd, + outcome: "usage_limit", + title: r.issue.title, + ...sessionMetrics(result, current, model), + }); + await gh.comment( + "issue", + r.issue.number, + fmt.usageLimit(result.sessionId, cfg.host, formatResetAt(until, ctx.now())), + ); + ctx.state?.patch({ current: null }); +} + // Role sessions cannot write outside their worktree (`--permission-mode dontAsk` denies it even // for allowlisted mkdir/mv), so the validator leaves screenshots in // `/.validation-artifacts//` and the foreman archives them here before the worktree @@ -627,7 +685,8 @@ async function applyOutcome( const pr = res.outcome?.pr ?? r.pr; if (!res.outcome) { const excerpt = [res.resultText ?? "", res.stderr].join("\n").trim().slice(-1500); - const reason = `${res.timedOut ? "timed out" : res.subtype} after retries`; + // Names what `classifyEnd` found; a session with no refusal keeps today's wording. + const reason = endReason(res); await gh.addLabels("issue", n, ["blocked"]); await gh.comment( "issue", @@ -1102,6 +1161,12 @@ export async function runOnce(ctx: Ctx): Promise { repoDir: ctx.cfg.repoDir, instance: ctx.instance, hookLog: ctx.hookLog, + pause: ctx.state + ? { + until: ctx.state.get().pausedUntil ?? null, + reason: ctx.state.get().pauseReason ?? null, + } + : null, }, ); ctx.state?.patch({ lastPreflight: { ok: pre.ok, reason: pre.ok ? null : pre.reason } }); @@ -1250,15 +1315,25 @@ export async function runForever(ctx: Ctx, deps: LoopDeps = {}): Promise { // A tick that did work has changed the board — a merge unblocks dependents, a session has // already spent its minutes — so waiting out another `pollSeconds` is dead time. // A tick that found something new still sleeps the plain interval, and a failure backs off. - const delaySeconds = + const tickDelay = outcome.didWork && consecutiveFailures === 0 ? 0 : consecutiveFailures > 0 ? backoffSeconds(ctx.cfg.pollSeconds, consecutiveFailures) : idleSeconds(ctx.cfg.pollSeconds, consecutiveQuiet); - if (delaySeconds === 0) log("info", "ticking again immediately", { action: outcome.action }); - if (consecutiveQuiet > 0) log("info", "idle backoff", { consecutiveQuiet, delaySeconds }); const at = ctx.now(); + // A usage-limit pause outranks every other delay, the zero after a tick that did work + // included: each tick before the reset would only be refused. The sleep is the controller's, + // so `go` (which clears the pause) still wakes it at once. + const pausedUntil = ctx.state?.get().pausedUntil ?? null; + const pausedFor = pausedUntil + ? Math.ceil((Date.parse(pausedUntil) - Date.parse(at)) / 1000) + : 0; + const delaySeconds = Math.max(tickDelay, pausedFor); + if (pausedFor > tickDelay) log("info", "paused until the usage limit resets", { pausedUntil }); + else if (delaySeconds === 0) + log("info", "ticking again immediately", { action: outcome.action }); + if (consecutiveQuiet > 0) log("info", "idle backoff", { consecutiveQuiet, delaySeconds }); ctx.state?.patch({ lastTickAt: at, nextTickAt: new Date(Date.parse(at) + delaySeconds * 1000).toISOString(), diff --git a/src/preflight.test.ts b/src/preflight.test.ts index 52e908c..dabc12b 100644 --- a/src/preflight.test.ts +++ b/src/preflight.test.ts @@ -54,6 +54,17 @@ describe("preflight", () => { it("passes with a subscription login", async () => { expect((await preflight(cfg, deps())).ok).toBe(true); }); + it("refuses while the Claude usage limit is spent and its reset is still ahead", async () => { + const now = new Date("2026-11-09T21:34:00.000Z"); + const pause = { until: "2026-11-09T22:52:00.000Z", reason: "usage limit" }; + expect(await preflight(cfg, deps({ now, pause }))).toEqual({ + ok: false, + reason: "paused: usage limit until 22:52Z", + }); + const after = new Date("2026-11-09T22:53:00.000Z"); + expect((await preflight(cfg, deps({ now: after, pause }))).ok).toBe(true); + expect((await preflight(cfg, deps({ now, pause: null }))).ok).toBe(true); + }); it("fails on API-key auth", async () => { const exec: Exec = async () => ({ code: 0, diff --git a/src/preflight.ts b/src/preflight.ts index 4ec66ac..d956599 100644 --- a/src/preflight.ts +++ b/src/preflight.ts @@ -4,6 +4,7 @@ import type { BudgetSample } from "./budget.ts"; import type { ForemanConfig } from "./config.ts"; import type { Exec } from "./exec.ts"; import { parsePreflight, runHook } from "./hooks.ts"; +import { formatResetAt } from "./session-end.ts"; export const FORBIDDEN_ENV = [ "ANTHROPIC_API_KEY", @@ -22,6 +23,11 @@ export interface PreflightDeps { repoDir: string; instance: string; hookLog?: (line: string) => void; + /** + * The daemon's dispatch pause (state.json `pausedUntil`/`pauseReason`), set when a session + * found the Claude usage limit spent. Absent or null means no pause. + */ + pause?: { until: string | null; reason: string | null } | null; } export type PreflightResult = { ok: true; warnings: string[] } | { ok: false; reason: string }; @@ -99,6 +105,15 @@ export async function preflight(cfg: ForemanConfig, deps: PreflightDeps): Promis const bad = checkEnv(deps.env); if (bad) return { ok: false, reason: `${bad} is set; refusing to run with API-key billing` }; if (existsSync(join(deps.stateDir, "STOP"))) return { ok: false, reason: "STOP file present" }; + // Before `claude auth status`: a session started now would be refused by the API on its first + // turn. The reason names a fixed time rather than a countdown, so it reads the same every tick + // and the parked notification goes out once. + const until = deps.pause?.until ?? null; + if (until && Date.parse(until) > deps.now.getTime()) + return { + ok: false, + reason: `paused: ${deps.pause?.reason ?? "usage limit"} until ${formatResetAt(until, deps.now.toISOString())}`, + }; const auth = await deps.exec("claude", ["auth", "status"]); let status: { loggedIn?: boolean; authMethod?: string } = {}; diff --git a/src/session-end.test.ts b/src/session-end.test.ts new file mode 100644 index 0000000..3957de6 --- /dev/null +++ b/src/session-end.test.ts @@ -0,0 +1,148 @@ +import { readFileSync } from "node:fs"; +import { join } from "node:path"; +import { describe, expect, it } from "vitest"; +import { parseResult } from "./dispatch.ts"; +import { + classifyEnd, + endReason, + exhaustedResetAt, + formatResetAt, + pauseUntil, +} from "./session-end.ts"; +import { type Activity, emptyActivity, foldEvent } from "./stream.ts"; + +const now = "2026-11-09T21:34:00.000Z"; + +/** A recorded session: the activity foreman folds from its stream, and the parsed result line. */ +function session(name: string) { + const text = readFileSync(join(import.meta.dirname, `../test/fixtures/${name}.jsonl`), "utf8"); + const lines = text.split("\n").filter((l) => l.length > 0); + let activity: Activity = emptyActivity(); + for (const l of lines) activity = foldEvent(activity, l, now, "/work/794").activity; + return { activity, result: parseResult(text, false) }; +} + +describe("classifyEnd", () => { + it("names a usage limit and takes the reset time from the rate-limit event", () => { + const { activity, result } = session("refusal-usage-limit"); + expect(result.subtype).toBe("success"); + expect(classifyEnd(result, activity)).toEqual({ + cause: "usage_limit", + requestId: null, + resetsAt: "2026-11-09T22:50:00.000Z", + }); + }); + + it("names a usage limit from the text alone, with no rate-limit event", () => { + const end = classifyEnd( + { resultText: "You've hit your session limit · resets 6:40pm", stderr: "" }, + emptyActivity(), + ); + expect(end.cause).toBe("usage_limit"); + expect(end.resetsAt).toBeNull(); + }); + + it("names a usage limit from a spent window alone, whatever the text says", () => { + const activity: Activity = { + ...emptyActivity(), + rateLimit: { + fiveHour: 0.5, + sevenDay: 1, + resetsAt: "2026-11-09T22:50:00.000Z", + sevenDayResetsAt: "2026-11-13T00:00:00.000Z", + }, + }; + expect(classifyEnd({ resultText: null, stderr: "" }, activity)).toEqual({ + cause: "usage_limit", + requestId: null, + resetsAt: "2026-11-13T00:00:00.000Z", + }); + }); + + it("names a safeguard flag and pulls out its request id", () => { + const { activity, result } = session("refusal-safeguard"); + expect(result.subtype).toBe("success"); + expect(classifyEnd(result, activity)).toEqual({ + cause: "safeguard", + requestId: "req_011Cgt4qVTW9B5dwTGegArfo", + resetsAt: null, + }); + }); + + it("finds a safeguard flag in the streamed text when the result carries none", () => { + const { activity } = session("refusal-safeguard"); + expect(classifyEnd({ resultText: null, stderr: "" }, activity).cause).toBe("safeguard"); + }); + + it("calls a session that ends with neither text, and no spent window, other", () => { + const { activity, result } = session("refusal-none"); + expect(classifyEnd(result, activity)).toEqual({ + cause: "other", + requestId: null, + resetsAt: null, + }); + expect(classifyEnd({ resultText: null, stderr: "" }, emptyActivity()).cause).toBe("other"); + }); +}); + +describe("exhaustedResetAt", () => { + it("is the reset of the spent window, and null while every window has room", () => { + expect(exhaustedResetAt(session("refusal-usage-limit").activity)).toBe( + "2026-11-09T22:50:00.000Z", + ); + expect(exhaustedResetAt(session("refusal-none").activity)).toBeNull(); + expect(exhaustedResetAt(emptyActivity())).toBeNull(); + }); +}); + +describe("pauseUntil", () => { + it("adds a small margin to a reset time still ahead", () => { + expect(pauseUntil("2026-11-09T22:50:00.000Z", now)).toBe("2026-11-09T22:52:00.000Z"); + }); + it("falls back to a fixed pause when the reset time is unknown or already past", () => { + expect(pauseUntil(null, now)).toBe("2026-11-09T22:04:00.000Z"); + expect(pauseUntil("2026-11-09T20:00:00.000Z", now)).toBe("2026-11-09T22:04:00.000Z"); + }); +}); + +describe("formatResetAt", () => { + it("is a clock time within a day and a dated time beyond", () => { + expect(formatResetAt("2026-11-09T22:52:00.000Z", now)).toBe("22:52Z"); + expect(formatResetAt("2026-11-13T00:02:00.000Z", now)).toBe("2026-11-13 00:02Z"); + }); +}); + +describe("endReason", () => { + const base = { timedOut: false, subtype: "success" }; + it("keeps today's wording when the cause is other", () => { + expect(endReason({ ...base, end: undefined })).toBe("success after retries"); + expect(endReason({ ...base, timedOut: true, end: undefined })).toBe("timed out after retries"); + expect(endReason({ ...base, end: { cause: "other", requestId: null, resetsAt: null } })).toBe( + "success after retries", + ); + }); + it("names a safeguard flag, how many sessions it stopped, and the request ids", () => { + expect( + endReason({ + ...base, + end: { cause: "safeguard", requestId: "req_b", resetsAt: null }, + flagged: ["req_a", "req_b"], + }), + ).toBe("safeguard flag on 2 sessions (req_a, req_b)"); + expect( + endReason({ + ...base, + end: { cause: "safeguard", requestId: null, resetsAt: null }, + flagged: [null], + }), + ).toBe("safeguard flag on 1 session"); + }); + it("names a usage limit", () => { + expect( + endReason({ + ...base, + end: { cause: "usage_limit", requestId: null, resetsAt: "2026-11-09T22:50:00.000Z" }, + }), + ).toBe("usage limit"); + }); +}); diff --git a/src/session-end.ts b/src/session-end.ts new file mode 100644 index 0000000..1da0f79 --- /dev/null +++ b/src/session-end.ts @@ -0,0 +1,123 @@ +import type { Activity } from "./stream.ts"; + +/** + * Why a `claude -p` session ended without an outcome, when the API rather than the task stopped + * it. Both refusals arrive as `subtype: "success"`, so the subtype says nothing here. + */ +export type EndCause = "usage_limit" | "safeguard" | "other"; + +export interface SessionEnd { + cause: EndCause; + /** The API request id a refusal names (`req_…`), for the block comment; null when absent. */ + requestId: string | null; + /** When the spent usage window resets, from the rate-limit event; null when unknown. */ + resetsAt: string | null; +} + +/* + * Every match on the API's wording lives in this block, and nowhere else in the package: that + * wording changes, and when it does this is the one place to follow it. + */ +const USAGE_LIMIT_TEXT = /hit your .*limit/i; +const SAFEGUARD_TEXT = /safeguards flagged/i; +const REQUEST_ID = /\breq_[A-Za-z0-9]+/; +/** The `error` field Claude Code puts on the synthetic message that announces a usage limit. */ +const USAGE_LIMIT_API_ERROR = "rate_limit"; + +/** A window is spent at utilization 1; the rate-limit event reports 0–1. */ +const SPENT = 1; + +/** + * When the spent window resets: the later reset when both are spent. Null while every window + * still has room, or when the event named no reset for the spent one. + */ +export function exhaustedResetAt(activity: Activity): string | null { + const r = activity.rateLimit; + if (!r) return null; + const spent = [ + r.fiveHour >= SPENT ? r.resetsAt : undefined, + r.sevenDay >= SPENT ? r.sevenDayResetsAt : undefined, + ]; + if (spent.every((x) => x === undefined)) return null; + const known = spent.filter((x): x is string => typeof x === "string"); + return known.sort().at(-1) ?? null; +} + +function spentWindow(activity: Activity): boolean { + const r = activity.rateLimit; + return r !== null && (r.fiveHour >= SPENT || r.sevenDay >= SPENT); +} + +/** + * Pure. The texts are the result line's `result`, the last streamed assistant text, and stderr, + * in that order; the first is the only one that carries a refusal's full `Request ID:` line. + */ +export function classifyEnd( + result: { resultText: string | null; stderr: string }, + activity: Activity, +): SessionEnd { + const texts = [result.resultText ?? "", activity.lastText?.text ?? "", result.stderr]; + const requestId = + texts.map((t) => REQUEST_ID.exec(t)?.[0]).find((x): x is string => x !== undefined) ?? null; + if (texts.some((t) => SAFEGUARD_TEXT.test(t))) + return { cause: "safeguard", requestId, resetsAt: null }; + if ( + texts.some((t) => USAGE_LIMIT_TEXT.test(t)) || + activity.lastApiError === USAGE_LIMIT_API_ERROR || + spentWindow(activity) + ) { + // The text names a local clock time ("resets 3:50pm (America/Los_Angeles)"); the event's + // epoch is the reliable one. With no spent window on record, the five-hour reset is the + // limit the text is about, as long as it is still ahead of the session's last event. + const resetsAt = exhaustedResetAt(activity) ?? activity.rateLimit?.resetsAt ?? null; + return { cause: "usage_limit", requestId, resetsAt }; + } + return { cause: "other", requestId: null, resetsAt: null }; +} + +/** Past the reset by this much, so the first session after it does not race the API's clock. */ +export const PAUSE_MARGIN_MS = 2 * 60_000; +/** + * How long to pause when the reset time is unknown or already behind us. Without a floor a + * stale reset would let the next tick dispatch straight into the same refusal. + */ +export const PAUSE_FALLBACK_MS = 30 * 60_000; + +export function pauseUntil(resetsAt: string | null, now: string): string { + const at = resetsAt ? Date.parse(resetsAt) : Number.NaN; + const t = + Number.isFinite(at) && at > Date.parse(now) + ? at + PAUSE_MARGIN_MS + : Date.parse(now) + PAUSE_FALLBACK_MS; + return new Date(t).toISOString(); +} + +/** `22:52Z` within a day of `now`; `2026-11-13 00:02Z` for a weekly reset further out. */ +export function formatResetAt(iso: string, now: string): string { + const clock = `${iso.slice(11, 16)}Z`; + return Date.parse(iso) - Date.parse(now) < 24 * 3600_000 ? clock : `${iso.slice(0, 10)} ${clock}`; +} + +/** The pause reason the daemon stores, and preflight, `status` and the page show. */ +export const USAGE_LIMIT_REASON = "usage limit"; + +/** + * The one-line reason for a block or a notification when a dispatch ended without an outcome. + * `other` keeps the exact wording foreman has always used. + */ +export function endReason(r: { + timedOut: boolean; + subtype: string; + end?: SessionEnd; + /** The request id of each flagged session, in order; null where the error named none. */ + flagged?: (string | null)[]; +}): string { + if (r.end?.cause === "safeguard") { + const flagged = r.flagged ?? [r.end.requestId]; + const ids = flagged.filter((x): x is string => x !== null); + const n = flagged.length; + return `safeguard flag on ${n} session${n === 1 ? "" : "s"}${ids.length ? ` (${ids.join(", ")})` : ""}`; + } + if (r.end?.cause === "usage_limit") return USAGE_LIMIT_REASON; + return `${r.timedOut ? "timed out" : r.subtype} after retries`; +} diff --git a/src/state-file.ts b/src/state-file.ts index 6315baa..103436d 100644 --- a/src/state-file.ts +++ b/src/state-file.ts @@ -343,6 +343,14 @@ export const ForemanStateSchema = z.object({ * Older state.json files predate this field; the default keeps them readable. */ theme: ThemeSchema.nullable().default(null), + /** + * No session is dispatched before this time: a session found the Claude usage limit spent, and + * this is its reset plus a margin. Survives a restart; `go` clears it. Older state.json files + * predate both fields; the defaults keep them readable. + */ + pausedUntil: z.string().nullable().default(null), + /** Why dispatching is paused (`usage limit`); null when it is not. */ + pauseReason: z.string().nullable().default(null), }); export type ForemanState = z.infer; @@ -362,6 +370,9 @@ export function initialState(o: { maxSessionsPerDay?: number | null; /** Carried over from the previous state.json, or picked at first start; never reset. */ theme?: ThemeName | null; + /** Carried over, so a restart during a usage-limit pause does not dispatch into the limit. */ + pausedUntil?: string | null; + pauseReason?: string | null; }): ForemanState { return { version: 1, @@ -370,6 +381,8 @@ export function initialState(o: { model: o.model ?? null, maxSessionsPerDay: o.maxSessionsPerDay ?? null, theme: o.theme ?? null, + pausedUntil: o.pausedUntil ?? null, + pauseReason: o.pauseReason ?? null, exitedAt: null, lastTickAt: null, nextTickAt: null, diff --git a/src/status.test.ts b/src/status.test.ts index 0346514..5d8f96c 100644 --- a/src/status.test.ts +++ b/src/status.test.ts @@ -145,6 +145,30 @@ describe("describeStatus", () => { // A running session still outranks it: the tick that started it had a healthy preflight. expect(describeStatus(input({ state: { ...capped, current } })).nowPhase).toBe("session"); }); + it("names a usage-limit pause and when it ends, in the report and the text", () => { + const paused = { + ...state(), + lastTickAt: "2026-09-04T05:09:00.000Z", + nextTickAt: "2026-09-04T07:52:00.000Z", + lastPlan: ["claim#143"], + lastPreflight: { ok: false, reason: "paused: usage limit until 07:52Z" }, + pausedUntil: "2026-09-04T07:52:00.000Z", + pauseReason: "usage limit", + }; + const r = describeStatus(input({ state: paused })); + expect(r.pause).toEqual({ + until: "2026-09-04T07:52:00.000Z", + reason: "usage limit", + label: "paused: usage limit until 07:52Z", + }); + const text = formatStatus(r); + expect(text).toContain("paused: usage limit until 07:52Z"); + expect(text).toContain("now paused · usage limit until 07:52Z (ctl go resumes now)"); + expect(text).not.toContain("retrying every tick"); + // Once the pause has ended it is not reported, whatever state.json still holds. + const over = describeStatus(input({ state: paused, now: "2026-09-04T08:00:00.000Z" })); + expect(over.pause).toBeNull(); + }); it("reports the config cap, and the live override when one is set", () => { const fromConfig = describeStatus(input()); expect(fromConfig.cap).toEqual({ diff --git a/src/status.ts b/src/status.ts index 8646c4d..79f6539 100644 --- a/src/status.ts +++ b/src/status.ts @@ -1,6 +1,7 @@ import { type Attention, describeAttention } from "./attention.ts"; import { overlayCurrent } from "./board.ts"; import { formatBudget } from "./budget.ts"; +import { formatResetAt, USAGE_LIMIT_REASON } from "./session-end.ts"; import { type SessionLogEntry, todayStats } from "./sessions.ts"; import { type Board, @@ -69,6 +70,11 @@ export interface StatusReport { }; /** The effort every session runs at, and the levels a task's `effort:` label may pick. */ effort: { default: EffortLevel; levels: readonly EffortLevel[] }; + /** + * A usage-limit pause still ahead of `now`: no session is dispatched before `until`. `label` is + * the line `status` and the page show. + */ + pause: { until: string; reason: string; label: string } | null; tick: { lastAt: string | null; nextAt: string | null; @@ -206,6 +212,7 @@ export function describeStatus(i: StatusInput): StatusReport { choices: i.modelChoices, }, effort: { default: EFFORT_DEFAULT_LEVEL, levels: EFFORT_LEVELS }, + pause: pauseOf(s?.pausedUntil ?? null, s?.pauseReason ?? null, i.now), tick: s ? { lastAt: s.lastTickAt, @@ -240,6 +247,12 @@ export function describeStatus(i: StatusInput): StatusReport { }; } +function pauseOf(until: string | null, reason: string | null, now: string): StatusReport["pause"] { + if (!until || Date.parse(until) <= Date.parse(now)) return null; + const why = reason ?? USAGE_LIMIT_REASON; + return { until, reason: why, label: `paused: ${why} until ${formatResetAt(until, now)}` }; +} + const hhmm = (iso: string | null) => (iso ? `${iso.slice(11, 19)}Z` : "–"); const mins = (m: number) => m >= 60 ? `${Math.floor(m / 60)}h${String(m % 60).padStart(2, "0")}m` : `${m}m`; @@ -264,7 +277,7 @@ export function formatStatus(r: StatusReport): string { : `preflight failed: ${r.tick.preflight.reason}` : "no tick yet"; lines.push( - `tick last ${hhmm(r.tick.lastAt)} ${pre} next ${hhmm(r.tick.nextAt)} backoff ${r.tick.consecutiveFailures}`, + `tick last ${hhmm(r.tick.lastAt)} ${pre} next ${hhmm(r.tick.nextAt)} backoff ${r.tick.consecutiveFailures}${r.pause ? ` ${r.pause.label}` : ""}`, ); } if (r.stopping) lines.push(`STOPPING (${r.stopping.mode}) since ${hhmm(r.stopping.at)}`); @@ -284,7 +297,9 @@ export function formatStatus(r: StatusReport): string { lines.push( `STALLED no output for ${mins(c.silentMinutes)} (limit ${c.limitMinutes}m; ctl stop to interrupt)`, ); - } else if (r.nowPhase === "parked") + } else if (r.pause) + lines.push(`now ${r.pause.label.replace(/^paused: /, "paused · ")} (ctl go resumes now)`); + else if (r.nowPhase === "parked") lines.push( `now parked · ${r.tick?.preflight?.reason ?? "preflight failed"} (retrying every tick)`, ); diff --git a/src/stream.test.ts b/src/stream.test.ts index c2f179f..a2f5f51 100644 --- a/src/stream.test.ts +++ b/src/stream.test.ts @@ -1,7 +1,7 @@ import { readFileSync } from "node:fs"; import { join } from "node:path"; import { describe, expect, it } from "vitest"; -import { emptyActivity, foldEvent, summarizeToolUse } from "./stream.ts"; +import { ActivitySchema, emptyActivity, foldEvent, summarizeToolUse } from "./stream.ts"; const lines = readFileSync(join(import.meta.dirname, "../test/fixtures/stream.jsonl"), "utf8") .split("\n") @@ -103,8 +103,42 @@ describe("foldEvent", () => { fiveHour: 0.06, sevenDay: 0.33, resetsAt: "2026-09-04T18:10:00.000Z", + sevenDayResetsAt: "2026-09-06T22:00:00.000Z", }); }); + it("keeps a seven-day window that arrives without a five-hour one, and no 1970 reset", () => { + const line = JSON.stringify({ + type: "rate_limit_event", + rate_limit_info: { unifiedWindows: { seven_day: { utilization: 1 } } }, + }); + const a = foldEvent(emptyActivity(), line, now, wt).activity; + expect(a.rateLimit).toEqual({ + fiveHour: 0, + sevenDay: 1, + resetsAt: null, + sevenDayResetsAt: null, + }); + }); + it("keeps the error Claude Code puts on a synthetic API-error message", () => { + const line = JSON.stringify({ + type: "assistant", + error: "rate_limit", + message: { id: "m9", content: [{ type: "text", text: "You've hit your limit" }] }, + }); + const errored = foldEvent(emptyActivity(), line, now, wt).activity; + expect(errored.lastApiError).toBe("rate_limit"); + expect(emptyActivity().lastApiError).toBeNull(); + // A session that recovers from the error is no longer stopped by it. + const next = JSON.stringify({ + type: "assistant", + message: { id: "m10", content: [{ type: "text", text: "carrying on" }] }, + }); + expect(foldEvent(errored, next, now, wt).activity.lastApiError).toBeNull(); + }); + it("reads an old state.json activity that predates the seven-day reset", () => { + const old = { ...emptyActivity(), rateLimit: { fiveHour: 1, sevenDay: 0, resetsAt: "x" } }; + expect(ActivitySchema.parse(old).rateLimit?.sevenDayResetsAt).toBeNull(); + }); it("emits feed entries without thinking, raw inputs or MCP tool arguments", () => { const { entries } = foldAll(lines); const kinds = entries.map((e) => e.kind); diff --git a/src/stream.ts b/src/stream.ts index dc8f8d5..5b8514a 100644 --- a/src/stream.ts +++ b/src/stream.ts @@ -14,14 +14,29 @@ export const ActivitySchema = z.object({ .nullable(), lastText: z.object({ text: z.string(), at: z.string() }).nullable(), lastError: z.object({ tool: z.string(), at: z.string() }).nullable(), + /** + * The `error` Claude Code sets on a synthetic assistant message that reports an API refusal + * (`rate_limit` for a usage limit). Added later; the default keeps older state.json readable. + */ + lastApiError: z.string().nullable().default(null), tokens: z.object({ input: z.number(), output: z.number(), cacheRead: z.number(), cacheWrite: z.number(), }), + /** + * The last `rate_limit_event`: utilization of each window (1 = spent) and when each resets. + * A reset the event leaves out is null, never 1970. `sevenDayResetsAt` arrived later; the + * default keeps an older state.json's `current.activity` readable. + */ rateLimit: z - .object({ fiveHour: z.number(), sevenDay: z.number(), resetsAt: z.string() }) + .object({ + fiveHour: z.number(), + sevenDay: z.number(), + resetsAt: z.string().nullable(), + sevenDayResetsAt: z.string().nullable().default(null), + }) .nullable(), }); export type Activity = z.infer; @@ -37,6 +52,7 @@ export function emptyActivity(): Activity { lastTool: null, lastText: null, lastError: null, + lastApiError: null, tokens: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }, rateLimit: null, }; @@ -115,6 +131,9 @@ interface Msg { } const num = (v: unknown): number => (typeof v === "number" && Number.isFinite(v) ? v : 0); +/** Epoch seconds as ISO; null when absent, so a missing reset never reads as 1970. */ +const epochIso = (v: unknown): string | null => + typeof v === "number" && Number.isFinite(v) && v > 0 ? new Date(v * 1000).toISOString() : null; /** Pure and total: any line the folder does not understand only bumps `events`. */ export function foldEvent(a: Activity, line: string, nowIso: string, worktree: string): FoldResult { @@ -141,16 +160,18 @@ export function foldEvent(a: Activity, line: string, nowIso: string, worktree: s const w = (info.unifiedWindows ?? {}) as Record>; const five = w.five_hour ?? {}; const seven = w.seven_day ?? {}; - if (typeof five.utilization === "number") { + // Either window can be the one that ran out, so an event naming only one is still kept. + if (typeof five.utilization === "number" || typeof seven.utilization === "number") { next.rateLimit = { - fiveHour: five.utilization, + fiveHour: num(five.utilization), sevenDay: num(seven.utilization), - resetsAt: new Date(num(five.resetsAt) * 1000).toISOString(), + resetsAt: epochIso(five.resetsAt), + sevenDayResetsAt: epochIso(seven.resetsAt), }; entries.push({ t: at, kind: "rate_limit", - fiveHour: five.utilization, + fiveHour: num(five.utilization), sevenDay: num(seven.utilization), }); } @@ -160,6 +181,8 @@ export function foldEvent(a: Activity, line: string, nowIso: string, worktree: s if (j.type === "assistant") { const m = (j.message ?? {}) as Msg; next.lastEventAt = at; + // Per message, not sticky: only the latest message says whether the API is refusing now. + next.lastApiError = typeof j.error === "string" && j.error ? j.error : null; if (m.id && m.id !== a.lastMessageId) { next.turns = a.turns + 1; next.lastMessageId = m.id; diff --git a/src/web.html b/src/web.html index ab4ba9d..22080a4 100644 --- a/src/web.html +++ b/src/web.html @@ -445,7 +445,9 @@

Dashboard

paused: { cls: "warn", fix: "Resume on the Board tab" }, }; function bannerRows(r) { - const rows = (r.attention?.banners ?? []).map((w) => ({ cls: BANNER[w.kind]?.cls ?? "warn", text: esc(w.detail), fix: BANNER[w.kind]?.fix ?? "" })); + // A usage-limit pause fails preflight too, but there is nothing to fix: it ends on its own. + const bannerOf = (w) => (w.kind === "preflight" && r.pause ? { cls: "warn", fix: "waits for the reset; Go resumes now" } : BANNER[w.kind]); + const rows = (r.attention?.banners ?? []).map((w) => ({ cls: bannerOf(w)?.cls ?? "warn", text: esc(w.detail), fix: bannerOf(w)?.fix ?? "" })); if (r.daemon === "UNKNOWN") rows.push({ cls: "warn", text: "no state.json: restart the daemon", fix: "" }); if (r.daemon === "STOPPED") rows.push({ cls: "warn", text: "the daemon is stopped", fix: "foreman start" }); if (r.daemon === "CRASHED") rows.push({ cls: "bad", text: "the daemon crashed", fix: "check foreman.err.log, then start it" }); @@ -463,7 +465,8 @@

Dashboard

if (!c) { // "idle" is reserved for a tick that found nothing eligible; between a finished session and // the next tick the daemon is asleep on a schedule, and says so. - const phase = r.nowPhase === "parked" + const phase = r.pause ? { label: "paused", sub: esc(r.pause.label.replace(/^paused: /, "")) } + : r.nowPhase === "parked" ? { label: "parked", sub: esc(r.tick?.preflight?.reason ?? "preflight failed") } : r.nowPhase === "between_ticks" ? { label: "between ticks", sub: `next tick ${t(r.tick?.nextAt)}` } @@ -471,7 +474,7 @@

Dashboard

? { label: "ticking", sub: `since ${t(r.tick?.lastAt)}` } : { label: "idle", sub: `last tick ${t(r.tick?.lastAt)} · next ${t(r.tick?.nextAt)}` }; el.className = "card now idle"; - el.innerHTML = `
${phase.label}${phase.sub}
`; + el.innerHTML = `
${phase.label}${phase.sub}
`; return; } const a = c.activity; @@ -899,7 +902,7 @@

${link("issues", c.issue)} · ${esc(c.title)}

Model for new sessions
${esc(m?.current ?? "–")}
${m?.source === "override" ? `
override · foreman.json says ${esc(m.configured)}
` : ""}
${modelOpts.map((o) => ``).join("")}
Daily session cap
${esc(r.today?.count ?? 0)} of ${esc(c?.current ?? r.today?.cap ?? 0)} today · ${usd(r.today?.spendUsd)}
${c?.source === "override" ? `
override · foreman.json says ${esc(c.configured)}
` : ""}
${capOpts.map((o) => ``).join("")}
GitHub budget
${b ? `${b.remaining.toLocaleString("en-US")} of ${b.limit.toLocaleString("en-US")} points` : "–"}
${b ? `
resets ${hm(b.resetAt)} · last tick ${esc(b.tickReads)} reads, ${esc(b.actionSpend)} by sessions, ${esc(b.betweenTicks)} elsewhere
` : ""}
-
Last tick ${t(r.tick?.lastAt)} · ${r.tick?.preflight ? (r.tick.preflight.ok ? "preflight ok" : `preflight failed: ${esc(r.tick.preflight.reason)}`) : "no tick yet"}Next tick ${r.tick?.blockedBySession ? "after the session" : t(r.tick?.nextAt)}Backoff ${esc(r.tick?.consecutiveFailures ?? 0)}launchd ${r.launchdInstalled ? "installed" : "not installed"}${r.lastPlan ? `Plan ${esc(r.lastPlan.join(", "))}` : ""}
`; +
Last tick ${t(r.tick?.lastAt)} · ${r.tick?.preflight ? (r.tick.preflight.ok ? "preflight ok" : `preflight failed: ${esc(r.tick.preflight.reason)}`) : "no tick yet"}Next tick ${r.tick?.blockedBySession ? "after the session" : t(r.tick?.nextAt)}Backoff ${esc(r.tick?.consecutiveFailures ?? 0)}${r.pause ? `Paused ${esc(r.pause.label.replace(/^paused: /, ""))}` : ""}launchd ${r.launchdInstalled ? "installed" : "not installed"}${r.lastPlan ? `Plan ${esc(r.lastPlan.join(", "))}` : ""}
`; for (const x of $("daemonCard").querySelectorAll("button[data-model]")) x.onclick = () => { if (x.dataset.model !== m.current) setModel(x.dataset.model); }; for (const x of $("daemonCard").querySelectorAll("button[data-cap]")) x.onclick = () => { if (x.dataset.cap !== String(c.current)) setCap(x.dataset.cap === "default" ? null : Number(x.dataset.cap)); }; } diff --git a/src/web.test.ts b/src/web.test.ts index 1390090..128cd8d 100644 --- a/src/web.test.ts +++ b/src/web.test.ts @@ -30,6 +30,7 @@ const report: StatusReport = { model: { current: "opus", configured: "opus", source: "config", choices: MODEL_CHOICES }, cap: { current: 20, configured: 20, source: "config", choices: CAP_CHOICES }, effort: { default: "high", levels: EFFORT_LEVELS }, + pause: null, tick: null, current: null, orphan: null, @@ -658,6 +659,13 @@ describe("web.html", () => { expect(html).toContain(`Confirm $${"{cmd}"}?`); expect(html).toContain("Back to live"); }); + it("shows a usage-limit pause on the Now card and its banner, with Go as the way out", () => { + expect(html).toContain( + 'r.pause ? { label: "paused", sub: esc(r.pause.label.replace(/^paused: /, "")) }', + ); + expect(html).toContain("waits for the reset; Go resumes now"); + expect(html).toContain("Paused "); + }); it("puts every reason the foreman is idle in a banner", () => { expect(html).toContain("no state.json: restart the daemon"); expect(html).toContain("run ctl abort"); diff --git a/test/fixtures/refusal-none.jsonl b/test/fixtures/refusal-none.jsonl new file mode 100644 index 0000000..1a0beb2 --- /dev/null +++ b/test/fixtures/refusal-none.jsonl @@ -0,0 +1,4 @@ +{"type":"system","subtype":"init","model":"claude-opus-5-5","session_id":"66666666-6666-6666-6666-666666666666"} +{"type":"rate_limit_event","rate_limit_info":{"status":"allowed","unifiedWindows":{"five_hour":{"utilization":0.42,"resetsAt":1794264600},"seven_day":{"utilization":0.3,"resetsAt":1794528000}}},"session_id":"66666666-6666-6666-6666-666666666666"} +{"type":"assistant","message":{"id":"msg_c1","model":"claude-opus-5-5","content":[{"type":"tool_use","name":"Bash","input":{"description":"Run the tests"}}],"usage":{"input_tokens":10,"output_tokens":5}},"session_id":"66666666-6666-6666-6666-666666666666"} +{"type":"result","subtype":"error_max_turns","is_error":true,"num_turns":50,"total_cost_usd":3,"duration_ms":1000,"session_id":"66666666-6666-6666-6666-666666666666","result":null,"permission_denials":[]} diff --git a/test/fixtures/refusal-safeguard.jsonl b/test/fixtures/refusal-safeguard.jsonl new file mode 100644 index 0000000..50d8a44 --- /dev/null +++ b/test/fixtures/refusal-safeguard.jsonl @@ -0,0 +1,4 @@ +{"type":"system","subtype":"init","model":"claude-opus-5-5","session_id":"55555555-5555-5555-5555-555555555555"} +{"type":"assistant","message":{"id":"msg_b1","model":"claude-opus-5-5","content":[{"type":"tool_use","name":"Bash","input":{"description":"Run the tests"}}],"usage":{"input_tokens":10,"output_tokens":5}},"session_id":"55555555-5555-5555-5555-555555555555"} +{"type":"assistant","message":{"id":"msg_b2","model":"","content":[{"type":"text","text":"API Error: Opus 5.5's safeguards flagged this message (https://www.anthropic.com/legal/aup). This sometimes happens with safe, normal conversations. Claude Code can't respond to this message with Opus 5.5. Try rephrasing the request in a new session or change your model. Learn more: https://support.claude.com\n\nDetails: `[reasoning_extraction]`\nRequest ID: req_011Cgt4qVTW9B5dwTGegArfo\nMessage ID: msg_011Cgt4qVtHdXRLWMtdv3jSR"}]},"session_id":"55555555-5555-5555-5555-555555555555"} +{"type":"result","subtype":"success","is_error":false,"num_turns":187,"total_cost_usd":10.8,"duration_ms":1000,"session_id":"55555555-5555-5555-5555-555555555555","result":"API Error: Opus 5.5's safeguards flagged this message (https://www.anthropic.com/legal/aup). This sometimes happens with safe, normal conversations. Claude Code can't respond to this message with Opus 5.5. Try rephrasing the request in a new session or change your model. Learn more: https://support.claude.com\n\nDetails: `[reasoning_extraction]`\nRequest ID: req_011Cgt4qVTW9B5dwTGegArfo\nMessage ID: msg_011Cgt4qVtHdXRLWMtdv3jSR","permission_denials":[]} diff --git a/test/fixtures/refusal-usage-limit.jsonl b/test/fixtures/refusal-usage-limit.jsonl new file mode 100644 index 0000000..fa7bc49 --- /dev/null +++ b/test/fixtures/refusal-usage-limit.jsonl @@ -0,0 +1,5 @@ +{"type":"system","subtype":"init","model":"claude-opus-5-5","session_id":"44444444-4444-4444-4444-444444444444"} +{"type":"assistant","message":{"id":"msg_a1","model":"claude-opus-5-5","content":[{"type":"tool_use","name":"Write","input":{"file_path":"/work/794/app/test_tz/tokyo/profit_report_bounds_test.dart"}}],"usage":{"input_tokens":10,"output_tokens":5}},"session_id":"44444444-4444-4444-4444-444444444444"} +{"type":"rate_limit_event","rate_limit_info":{"status":"rejected","unifiedWindows":{"five_hour":{"utilization":1,"resetsAt":1794264600},"seven_day":{"utilization":0.1,"resetsAt":1794528000}}},"session_id":"44444444-4444-4444-4444-444444444444"} +{"type":"assistant","message":{"id":"msg_a2","model":"","content":[{"type":"text","text":"You've hit your 5-hour limit · resets 3:50pm (America/Los_Angeles)"}]},"error":"rate_limit","session_id":"44444444-4444-4444-4444-444444444444"} +{"type":"result","subtype":"success","is_error":false,"num_turns":44,"total_cost_usd":1.968,"duration_ms":1000,"session_id":"44444444-4444-4444-4444-444444444444","result":"You've hit your 5-hour limit · resets 3:50pm (America/Los_Angeles)","permission_denials":[]}