Skip to content

The fastest browser for AI agents to run browser automation, built for sharing your logged-in browser state with your AI agents, like Codex or Claude Code, without disturbing you. Zero cost, zero config.

feat(tools): wait for the Claude usage reset instead of failing tickets

Zhuowei Wang49651f6536b9
diff --git a/tools/linear-autofix/README.md b/tools/linear-autofix/README.md
index 52867b8..dd33914 100644
--- a/tools/linear-autofix/README.md
+++ b/tools/linear-autofix/README.md
@@ -141,7 +141,7 @@ Operations:
```sh
node src/cli.mjs status
node src/cli.mjs stop # STOP file: running tick finishes its step, later ticks exit
-node src/cli.mjs resume
+node src/cli.mjs resume # also clears a Claude usage pause
node src/cli.mjs publish CITRO-2908 # push failed or E2E did not finish? fix the host, then redo only E2E + push + PR
node src/cli.mjs retry CITRO-2908 # start over: re-triage and re-implement (keeps worktree and branch)
node src/cli.mjs reset CITRO-2908 --remote # forget the ticket entirely: record, worktree, branches, bot labels
@@ -225,6 +225,23 @@ escalates instead of pushing again. A round whose outcome is `disputed`
produces a PR comment and no commit; the next tick sees the same findings and
escalates, which is intended: a dispute needs a human.
+## When Claude usage runs out
+
+A `claude -p` run that stops on the account's usage limit does not count as a
+ticket error. The bot records a pause in `usage-pause.json` in the state dir,
+until the reset time Claude reports plus one minute, or for 30 minutes when it
+reports none. During the pause:
+
+- Triage and implementation are skipped, and no review fix round starts.
+- Review checks keep running, since they do not need Claude: merged PRs,
+ finished reviews and waiting PRs are still handled.
+- A ticket cut off mid-run loses that run's commits and uncommitted changes.
+ The first tick after the reset starts it again from where the run started.
+
+`node src/cli.mjs status` shows the pause, and `node src/cli.mjs resume` clears
+it early (for example after adding usage). The run's own `AUTOFIX_*_BUDGET_USD`
+limit is different: it still escalates.
+
## E2E failures
Whenever the branch changes `package/ego-browser/` or `skills/ego-browser/`, the
diff --git a/tools/linear-autofix/src/claude.mjs b/tools/linear-autofix/src/claude.mjs
index a849f54..7f47555 100644
--- a/tools/linear-autofix/src/claude.mjs
+++ b/tools/linear-autofix/src/claude.mjs
@@ -2,11 +2,100 @@ import fs from "node:fs";
import path from "node:path";
import { config } from "./config.mjs";
import { run, tail } from "./proc.mjs";
+import { setUsagePause, usagePausedUntil } from "./state.mjs";
+
+// How long to wait when a usage limit did not come with a reset time.
+const USAGE_RETRY_MS = 30 * 60_000;
+// Resume just after the reset, not at the instant the server may still refuse.
+const USAGE_RESET_MARGIN_MS = 60_000;
+const USAGE_LIMIT_TEXT =
+ /you've hit your .*(limit|budget)|usage limit reached|out of usage credits/i;
+
+/** The account is out of Claude usage; retrying before `until` (ms) is pointless. */
+export class UsageLimitError extends Error {
+ constructor(until, { reason, duringRun = false } = {}) {
+ super(
+ `Claude usage limit: paused until ${new Date(until).toISOString()}${reason ? ` (${reason})` : ""}`,
+ );
+ this.name = "UsageLimitError";
+ this.until = until;
+ // False when the run was refused before starting, so it changed nothing.
+ this.duringRun = duringRun;
+ }
+}
+
+/**
+ * Pick the final result and the last rejected rate-limit event out of
+ * `--output-format stream-json` output. Pure.
+ */
+export function parseClaudeStream(stdout) {
+ let result = null;
+ let rejected = null;
+ for (const line of String(stdout ?? "").split("\n")) {
+ if (!line.trim()) continue;
+ let message;
+ try {
+ message = JSON.parse(line);
+ } catch {
+ continue;
+ }
+ if (message.type === "result") result = message;
+ if (
+ message.type === "rate_limit_event" &&
+ message.rate_limit_info?.status === "rejected"
+ ) {
+ rejected = message.rate_limit_info;
+ }
+ }
+ return { result, rejected };
+}
+
+/**
+ * Whether a run stopped because the account ran out of usage, and when to try
+ * again (ms). A rejected event alone is not enough: a run can finish normally
+ * after one, and the run's own `--max-budget-usd` is a different limit. `stderr`
+ * is only consulted without a result; assistant text never is, since a ticket
+ * can talk about limits. Pure. Returns { until, reason } or null.
+ */
+export function detectUsageLimit({ result, rejected, stderr = "", now }) {
+ if (result && result.is_error !== true) return null;
+ if (/budget/i.test(result?.subtype ?? "")) return null;
+ const text = result ? String(result.result ?? "") : String(stderr);
+ if (
+ !rejected &&
+ result?.api_error_status !== 429 &&
+ !USAGE_LIMIT_TEXT.test(text)
+ ) {
+ return null;
+ }
+ const resetsAt = Number(rejected?.resetsAt) * 1000;
+ return {
+ until:
+ resetsAt > now ? resetsAt + USAGE_RESET_MARGIN_MS : now + USAGE_RETRY_MS,
+ reason: text.trim().slice(0, 200),
+ };
+}
+
+function pauseIfUsageLimit(stdout, stderr) {
+ const limit = detectUsageLimit({
+ ...parseClaudeStream(stdout),
+ stderr,
+ now: Date.now(),
+ });
+ if (!limit) return;
+ setUsagePause(limit.until, limit.reason);
+ throw new UsageLimitError(limit.until, {
+ reason: limit.reason,
+ duringRun: true,
+ });
+}
/**
* Run `claude -p` headless. The prompt goes in on stdin. Returns
* { text, structured, costUsd, turns, raw }. Throws on timeout or a non-zero
- * exit; a Claude-side `is_error` result is returned with `isError: true`.
+ * exit, and throws UsageLimitError (after recording the pause) when the account
+ * is out of usage; any other Claude-side `is_error` result is returned with
+ * `isError: true`. stream-json is used because only it carries the reset time.
*
* Permission model: `dontAsk` denies every tool call outside `allowedTools`,
* which is how the orchestrator keeps `git push` and `gh` in its own hands.
@@ -29,10 +118,14 @@ export async function runClaude({
schema,
addDirs = [],
}) {
+ const pausedUntil = usagePausedUntil();
+ if (pausedUntil) throw new UsageLimitError(pausedUntil);
+
const args = [
"-p",
"--output-format",
- "json",
+ "stream-json",
+ "--verbose",
"--no-session-persistence",
"--strict-mcp-config",
];
@@ -65,17 +158,17 @@ export async function runClaude({
err.stderr ?? "",
);
}
+ pauseIfUsageLimit(err.stdout, err.stderr);
throw err;
}
if (runDir)
- fs.writeFileSync(path.join(runDir, `${label}.stdout.json`), result.stdout);
+ fs.writeFileSync(path.join(runDir, `${label}.stdout.jsonl`), result.stdout);
- let parsed;
- try {
- parsed = JSON.parse(result.stdout);
- } catch {
+ pauseIfUsageLimit(result.stdout, result.stderr);
+ const { result: parsed } = parseClaudeStream(result.stdout);
+ if (!parsed) {
throw new Error(
- `claude returned non-JSON output:\n${tail(result.stdout)}\n${tail(result.stderr)}`,
+ `claude returned no result message:\n${tail(result.stdout)}\n${tail(result.stderr)}`,
);
}
const text =
diff --git a/tools/linear-autofix/src/claude.test.mjs b/tools/linear-autofix/src/claude.test.mjs
new file mode 100644
index 0000000..cd86252
--- /dev/null
+++ b/tools/linear-autofix/src/claude.test.mjs
@@ -0,0 +1,218 @@
+import assert from "node:assert/strict";
+import fs from "node:fs";
+import { execFileSync } from "node:child_process";
+import os from "node:os";
+import path from "node:path";
+import { test } from "node:test";
+
+// config.mjs reads these once, and node --test gives each file its own process.
+const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "autofix-claude-test-"));
+const fake = path.join(tmp, "fake-claude.mjs");
+process.env.AUTOFIX_STATE_DIR = path.join(tmp, "state");
+process.env.AUTOFIX_CLAUDE_BIN = fake;
+
+const { detectUsageLimit, parseClaudeStream, runClaude, UsageLimitError } =
+ await import("./claude.mjs");
+const { clearUsagePause, setUsagePause, usagePausedUntil } =
+ await import("./state.mjs");
+const { runCodeClaude } = await import("./implement.mjs");
+
+const now = Date.parse("2026-11-02T04:00:00Z");
+const resetsAt = now / 1000 + 3600;
+const rejected = { status: "rejected", resetsAt };
+const errorResult = (over = {}) => ({
+ type: "result",
+ subtype: "success",
+ is_error: true,
+ result: "You've hit your limit",
+ ...over,
+});
+
+function fakeClaude(lines, exitCode = 0) {
+ fs.writeFileSync(
+ fake,
+ `#!/usr/bin/env node\nprocess.stdin.resume();\nprocess.stdin.on("end", () => {\n console.log(${JSON.stringify(lines.map((l) => JSON.stringify(l)).join("\n"))});\n process.exitCode = ${exitCode};\n});\n`,
+ { mode: 0o755 },
+ );
+}
+
+test("parseClaudeStream finds the result and the last rejected event", () => {
+ const stdout = [
+ "not json",
+ JSON.stringify({
+ type: "rate_limit_event",
+ rate_limit_info: { status: "allowed", resetsAt: 1 },
+ }),
+ JSON.stringify({ type: "rate_limit_event", rate_limit_info: rejected }),
+ JSON.stringify({ type: "result", result: "ok" }),
+ "",
+ ].join("\n");
+ const parsed = parseClaudeStream(stdout);
+ assert.equal(parsed.result.result, "ok");
+ assert.deepEqual(parsed.rejected, rejected);
+ assert.deepEqual(parseClaudeStream(undefined), {
+ result: null,
+ rejected: null,
+ });
+});
+
+test("detectUsageLimit waits for the reset, plus a margin", () => {
+ const limit = detectUsageLimit({ result: errorResult(), rejected, now });
+ assert.equal(limit.until, resetsAt * 1000 + 60_000);
+ assert.match(limit.reason, /hit your limit/);
+});
+
+test("detectUsageLimit falls back to a short wait without a usable reset", () => {
+ const fallback = now + 30 * 60_000;
+ for (const input of [
+ { result: errorResult(), now },
+ { result: errorResult(), rejected: { status: "rejected" }, now },
+ { result: errorResult(), rejected: { resetsAt: now / 1000 - 5 }, now },
+ {
+ result: errorResult({ result: "API Error", api_error_status: 429 }),
+ now,
+ },
+ { result: null, stderr: "Claude usage limit reached", now },
+ ]) {
+ assert.equal(detectUsageLimit(input).until, fallback);
+ }
+});
+
+test("detectUsageLimit ignores what is not a usage limit", () => {
+ // Finished normally, even though a window was rejected along the way.
+ assert.equal(
+ detectUsageLimit({
+ result: {
+ type: "result",
+ is_error: false,
+ result: "you've hit your limit",
+ },
+ rejected,
+ now,
+ }),
+ null,
+ );
+ // The run's own --max-budget-usd.
+ assert.equal(
+ detectUsageLimit({
+ result: errorResult({ subtype: "error_max_budget_usd", result: "" }),
+ rejected,
+ now,
+ }),
+ null,
+ );
+ assert.equal(
+ detectUsageLimit({
+ result: errorResult({ result: "something else broke" }),
+ now,
+ }),
+ null,
+ );
+ assert.equal(detectUsageLimit({ result: null, stderr: "crash", now }), null);
+});
+
+test("runClaude pauses on a usage limit, then refuses to start", async () => {
+ clearUsagePause();
+ const future = Math.floor(Date.now() / 1000) + 3600;
+ fakeClaude(
+ [
+ {
+ type: "rate_limit_event",
+ rate_limit_info: { status: "rejected", resetsAt: future },
+ },
+ errorResult(),
+ ],
+ 1,
+ );
+ await assert.rejects(
+ runClaude({ prompt: "x", cwd: tmp, label: "t" }),
+ UsageLimitError,
+ );
+ assert.equal(usagePausedUntil(), future * 1000 + 60_000);
+
+ fs.rmSync(fake); // Starting it now would be a different error.
+ await assert.rejects(
+ runClaude({ prompt: "x", cwd: tmp, label: "t" }),
+ UsageLimitError,
+ );
+ clearUsagePause();
+});
+
+test("runClaude returns a normal result and other errors as before", async () => {
+ clearUsagePause();
+ fakeClaude([
+ { type: "system", subtype: "init" },
+ {
+ type: "result",
+ is_error: false,
+ result: "done",
+ structured_output: { a: 1 },
+ total_cost_usd: 0.5,
+ num_turns: 2,
+ },
+ ]);
+ const ok = await runClaude({ prompt: "x", cwd: tmp, label: "t" });
+ assert.equal(ok.text, "done");
+ assert.deepEqual(ok.structured, { a: 1 });
+ assert.equal(ok.isError, false);
+ assert.equal(ok.costUsd, 0.5);
+
+ fakeClaude([errorResult({ result: "something else broke" })]);
+ const failed = await runClaude({ prompt: "x", cwd: tmp, label: "t" });
+ assert.equal(failed.isError, true);
+ assert.equal(usagePausedUntil(), null);
+});
+
+test("a run cut off by the limit leaves the worktree as it started", async () => {
+ clearUsagePause();
+ const repo = path.join(tmp, "repo");
+ fs.mkdirSync(repo);
+ const git = (...args) =>
+ execFileSync("git", args, { cwd: repo, encoding: "utf8" }).trim();
+ git("init", "-q");
+ git("config", "user.email", "[email protected]");
+ git("config", "user.name", "t");
+ fs.writeFileSync(path.join(repo, "a.txt"), "start\n");
+ fs.writeFileSync(path.join(repo, ".gitignore"), "ignored.txt\n");
+ fs.writeFileSync(path.join(repo, "ignored.txt"), "keep\n");
+ git("add", ".");
+ git("commit", "-qm", "start");
+ const start = git("rev-parse", "HEAD");
+
+ const run = { prompt: "x", runDir: tmp, label: "t" };
+ fs.writeFileSync(
+ fake,
+ `#!/usr/bin/env node
+import { execFileSync } from "node:child_process";
+import fs from "node:fs";
+process.stdin.resume();
+process.stdin.on("end", () => {
+ fs.writeFileSync("a.txt", "partial commit\\n");
+ execFileSync("git", ["commit", "-qam", "partial"]);
+ fs.writeFileSync("a.txt", "uncommitted\\n");
+ fs.writeFileSync("new.txt", "untracked\\n");
+ console.log(${JSON.stringify(JSON.stringify(errorResult()))});
+ process.exitCode = 1;
+});
+`,
+ { mode: 0o755 },
+ );
+ // A .mjs fake, so its imports work; cwd is the repo.
+ await assert.rejects(runCodeClaude(repo, run), UsageLimitError);
+ assert.equal(git("rev-parse", "HEAD"), start);
+ assert.equal(git("status", "--porcelain"), "");
+ assert.equal(fs.readFileSync(path.join(repo, "a.txt"), "utf8"), "start\n");
+ assert.ok(fs.existsSync(path.join(repo, "ignored.txt")));
+
+ // Refused before starting: nothing ran, so hand edits are left alone.
+ fs.writeFileSync(path.join(repo, "a.txt"), "by hand\n");
+ await assert.rejects(runCodeClaude(repo, run), UsageLimitError);
+ assert.equal(fs.readFileSync(path.join(repo, "a.txt"), "utf8"), "by hand\n");
+ clearUsagePause();
+});
+
+test("an expired pause no longer counts", () => {
+ setUsagePause(Date.now() - 1000, "old");
+ assert.equal(usagePausedUntil(), null);
+ clearUsagePause();
+});
diff --git a/tools/linear-autofix/src/cli.mjs b/tools/linear-autofix/src/cli.mjs
index 62baa80..de93cf8 100755
--- a/tools/linear-autofix/src/cli.mjs
+++ b/tools/linear-autofix/src/cli.mjs
@@ -6,8 +6,10 @@ import {
load,
loadAll,
remove,
+ clearUsagePause,
setStop,
stopRequested,
+ usagePausedUntil,
transition,
upsertFromIssue,
worktreePath,
@@ -135,6 +137,11 @@ function status() {
);
if (stopRequested())
console.log("STOP file present: ticks exit immediately\n");
+ const pausedUntil = usagePausedUntil();
+ if (pausedUntil)
+ console.log(
+ `Claude usage limit: no Claude runs until ${new Date(pausedUntil).toISOString()} (resume clears this)\n`,
+ );
const width = Math.max(10, ...records.map((r) => r.identifier.length));
for (const r of records) {
const extra = r.pr?.url ?? r.triage?.verdict ?? "";
@@ -206,7 +213,8 @@ async function main([command, arg]) {
);
case "resume":
setStop(false);
- return console.log("STOP file removed");
+ clearUsagePause();
+ return console.log("STOP file and usage pause removed");
default:
process.stdout.write(USAGE);
process.exitCode = command ? 1 : 0;
diff --git a/tools/linear-autofix/src/git.mjs b/tools/linear-autofix/src/git.mjs
index 19cd93d..d86e45f 100644
--- a/tools/linear-autofix/src/git.mjs
+++ b/tools/linear-autofix/src/git.mjs
@@ -186,6 +186,12 @@ export async function push(dir, branch, { skipHookE2e = false } = {}) {
});
}
+/** Drop whatever a run left in the worktree: commits after `sha` and untracked files (ignored ones stay). */
+export async function discardTo(dir, sha) {
+ await gitIn(dir, ["reset", "--hard", sha]);
+ await gitIn(dir, ["clean", "-fd"]);
+}
+
export async function remoteSha(dir, branch) {
const { stdout, code } = await gitIn(
dir,
diff --git a/tools/linear-autofix/src/implement.mjs b/tools/linear-autofix/src/implement.mjs
index 32c31d1..cfa3c02 100644
--- a/tools/linear-autofix/src/implement.mjs
+++ b/tools/linear-autofix/src/implement.mjs
@@ -1,7 +1,12 @@
import fs from "node:fs";
import path from "node:path";
import { config } from "./config.mjs";
-import { loadPrompt, renderPrompt, runClaude } from "./claude.mjs";
+import {
+ loadPrompt,
+ renderPrompt,
+ runClaude,
+ UsageLimitError,
+} from "./claude.mjs";
import * as git from "./git.mjs";
import * as github from "./github.mjs";
import * as linear from "./linear.mjs";
@@ -45,6 +50,28 @@ export const CODE_TOOLS = [
"Bash(git mv *)",
];
+/**
+ * Run Claude with the code tools in a worktree. A run cut off by the usage limit
+ * leaves half-finished work, so it is dropped: the retry after the reset starts
+ * from the same commit as this run, and never mistakes it for a finished fix.
+ */
+export async function runCodeClaude(dir, options) {
+ const before = await git.headSha(dir);
+ try {
+ return await runClaude({
+ ...options,
+ cwd: dir,
+ allowedTools: CODE_TOOLS,
+ addDirs: [options.runDir],
+ });
+ } catch (err) {
+ if (err instanceof UsageLimitError && err.duringRun) {
+ await git.discardTo(dir, before);
+ }
+ throw err;
+ }
+}
+
export const PR_FOOTER =
"🤖 Generated with [Claude Code](https://claude.com/claude-code)";
@@ -91,13 +118,10 @@ export async function implement(issue, record) {
outDir: out,
identifier: record.identifier,
});
- const res = await runClaude({
+ const res = await runCodeClaude(dir, {
prompt,
- cwd: dir,
runDir: out,
label: "implement",
- allowedTools: CODE_TOOLS,
- addDirs: [out],
budgetUsd: config.implementBudgetUsd,
timeoutMs: config.implementTimeoutMs,
});
diff --git a/tools/linear-autofix/src/review.mjs b/tools/linear-autofix/src/review.mjs
index c8c421e..d8527e0 100644
--- a/tools/linear-autofix/src/review.mjs
+++ b/tools/linear-autofix/src/review.mjs
@@ -1,6 +1,6 @@
import path from "node:path";
import { config } from "./config.mjs";
-import { loadPrompt, renderPrompt, runClaude } from "./claude.mjs";
+import { loadPrompt, renderPrompt } from "./claude.mjs";
import {
classifyReview,
extractFindings,
@@ -11,7 +11,13 @@ import {
import * as git from "./git.mjs";
import * as github from "./github.mjs";
import * as linear from "./linear.mjs";
-import { note, runDir, transition, worktreePath } from "./state.mjs";
+import {
+ note,
+ runDir,
+ transition,
+ usagePausedUntil,
+ worktreePath,
+} from "./state.mjs";
import {
freshPrComments,
renderPrComments,
@@ -19,7 +25,7 @@ import {
splitThreads,
} from "./threads.mjs";
import { escalate, FOOTER } from "./actions.mjs";
-import { CODE_TOOLS, readJson } from "./implement.mjs";
+import { readJson, runCodeClaude } from "./implement.mjs";
import { e2eWarning, flushE2eComment, gatedPush, recordE2e } from "./e2e.mjs";
// After a push, Codex's review takes up to 30 minutes. Wait this long for a
@@ -127,7 +133,7 @@ export async function review(issue, record) {
// (publish) or adopted (tick); a record without one sees every comment.
record.review.commentsSeenAt ??= "";
const prComments = freshPrComments(pr.comments, record.review.commentsSeenAt);
- const verdict = assessHead({
+ const assessed = assessHead({
pr,
codex,
ci,
@@ -136,6 +142,12 @@ export async function review(issue, record) {
prComments,
headSeenAt: record.review.headSeenAt,
});
+ // Fixing needs Claude. Everything else (merged, done, draft ready) does not,
+ // so the check itself keeps running through a usage pause.
+ const verdict =
+ assessed.action === "fix" && usagePausedUntil()
+ ? { ...assessed, action: "wait" }
+ : assessed;
note(
record,
`review check ${sha.slice(0, 8)}`,
@@ -223,13 +235,10 @@ export async function review(issue, record) {
prComments: prComments.length ? renderPrComments(prComments) : "(none)",
ciText: ci === "failure" ? await github.checksText(pr.number) : `(${ci})`,
});
- const res = await runClaude({
+ const res = await runCodeClaude(dir, {
prompt,
- cwd: dir,
runDir: out,
label: "review-fix",
- allowedTools: CODE_TOOLS,
- addDirs: [out],
budgetUsd: config.reviewBudgetUsd,
timeoutMs: config.reviewTimeoutMs,
});
diff --git a/tools/linear-autofix/src/state.mjs b/tools/linear-autofix/src/state.mjs
index f425f3f..b64e93e 100644
--- a/tools/linear-autofix/src/state.mjs
+++ b/tools/linear-autofix/src/state.mjs
@@ -15,6 +15,7 @@ export const STAGES = Object.freeze([
const issuesDir = () => path.join(config.stateDir, "issues");
const lockPath = () => path.join(config.stateDir, "tick.lock");
const stopPath = () => path.join(config.stateDir, "STOP");
+const usagePausePath = () => path.join(config.stateDir, "usage-pause.json");
export function ensureStateDir() {
fs.mkdirSync(issuesDir(), { recursive: true });
@@ -57,6 +58,32 @@ export function loadAll() {
.map((f) => JSON.parse(fs.readFileSync(path.join(issuesDir(), f), "utf8")));
}
+/** When the Claude usage pause ends (ms), or null when there is none. */
+export function usagePausedUntil(now = Date.now()) {
+ try {
+ const until = new Date(
+ JSON.parse(fs.readFileSync(usagePausePath(), "utf8")).until,
+ ).getTime();
+ return until > now ? until : null;
+ } catch (err) {
+ if (err.code === "ENOENT") return null;
+ throw err;
+ }
+}
+
+/** Stop calling Claude until `until` (ms). Shared by every ticket and process. */
+export function setUsagePause(until, reason) {
+ ensureStateDir();
+ fs.writeFileSync(
+ usagePausePath(),
+ JSON.stringify({ until: new Date(until).toISOString(), reason }, null, 2),
+ );
+}
+
+export function clearUsagePause() {
+ fs.rmSync(usagePausePath(), { force: true });
+}
+
export function save(record) {
ensureStateDir();
record.updatedAt = new Date().toISOString();
diff --git a/tools/linear-autofix/src/tick.mjs b/tools/linear-autofix/src/tick.mjs
index 9eecabf..d87558f 100644
--- a/tools/linear-autofix/src/tick.mjs
+++ b/tools/linear-autofix/src/tick.mjs
@@ -1,3 +1,4 @@
+import { UsageLimitError } from "./claude.mjs";
import { config } from "./config.mjs";
import * as github from "./github.mjs";
import * as linear from "./linear.mjs";
@@ -9,6 +10,7 @@ import {
stopRequested,
transition,
upsertFromIssue,
+ usagePausedUntil,
} from "./state.mjs";
import { triage } from "./triage.mjs";
import { implement } from "./implement.mjs";
@@ -59,6 +61,12 @@ async function guarded(record, fn) {
await fn();
clearErrors(record);
} catch (err) {
+ // Not the ticket's fault: it does not count toward escalation, and it
+ // resumes from its current stage once the pause ends.
+ if (err instanceof UsageLimitError) {
+ note(record, "usage limit", err.message);
+ return;
+ }
await recordError(record, err);
}
}
@@ -101,11 +109,19 @@ export async function tick() {
await guarded(record, () => review(issue, record));
}
+ const pausedUntil = usagePausedUntil();
+ if (pausedUntil) {
+ console.log(
+ `Claude usage paused until ${new Date(pausedUntil).toISOString()}; skipping triage and implementation`,
+ );
+ return;
+ }
+
// 2. Triage new tickets; adopt tickets whose branch already has an open PR.
for (const { issue, record } of work.filter(
(w) => w.record.stage === "new",
)) {
- if (stopRequested()) return;
+ if (stopRequested() || usagePausedUntil()) return;
await guarded(record, async () => {
const existing = await github.findPr(record.branch);
if (existing?.state === "OPEN") {
@@ -132,7 +148,7 @@ export async function tick() {
for (const { issue, record } of work.filter(
(w) => w.record.stage === "triaged",
)) {
- if (stopRequested()) return;
+ if (stopRequested() || usagePausedUntil()) return;
if (open() >= config.maxImplementing) {
note(
record,