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.

6.8 KB
Raw Blame
import fs from "node:fs";
import path from "node:path";
import { config } from "./config.mjs";

export const STAGES = Object.freeze([
  "new", // seen, not yet triaged
  "triaged", // verdict fix, waiting for an implementation slot
  "implementing", // worktree + Claude run in progress (crash marker)
  "in_review", // PR open, review loop active
  "done", // review loop finished; a human merges
  "escalated", // bot gave up, human attention needed
  "skipped", // verdict was not fix
]);

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 });
  fs.mkdirSync(path.join(config.stateDir, "worktrees"), { recursive: true });
  fs.mkdirSync(path.join(config.stateDir, "runs"), { recursive: true });
}

const IDENTIFIER = /^[A-Z][A-Z0-9]{0,15}-\d{1,8}$/;

/** A Linear identifier such as CITRO-2908; anything else is refused before it reaches a path. */
export function assertIdentifier(identifier) {
  if (typeof identifier !== "string" || !IDENTIFIER.test(identifier)) {
    throw new Error(`invalid issue identifier: ${JSON.stringify(identifier)}`);
  }
  return identifier;
}

export function recordPath(identifier) {
  return path.join(issuesDir(), `${assertIdentifier(identifier)}.json`);
}

export function load(identifier) {
  try {
    return JSON.parse(fs.readFileSync(recordPath(identifier), "utf8"));
  } catch (err) {
    if (err.code === "ENOENT") return null;
    throw err;
  }
}

export function remove(identifier) {
  fs.rmSync(recordPath(identifier), { force: true });
}

export function loadAll() {
  ensureStateDir();
  return fs
    .readdirSync(issuesDir())
    .filter((f) => f.endsWith(".json"))
    .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();
  const file = recordPath(record.identifier);
  fs.writeFileSync(`${file}.tmp`, JSON.stringify(record, null, 2));
  fs.renameSync(`${file}.tmp`, file);
  return record;
}

/** Events of the current process, drained into the Linear execution log. */
const journal = [];

export function journalEvents() {
  return journal.slice();
}

export function clearJournal() {
  journal.length = 0;
}

/** Append a history event and persist. */
export function note(record, event, detail) {
  record.history ??= [];
  record.history.push({
    at: new Date().toISOString(),
    event,
    ...(detail ? { detail } : {}),
  });
  if (record.history.length > 200)
    record.history.splice(0, record.history.length - 200);
  journal.push({
    identifier: record.identifier,
    event,
    detail: detail ? String(detail) : "",
  });
  console.log(
    `[${record.identifier}] ${event}${detail ? `: ${truncate(detail)}` : ""}`,
  );
  return save(record);
}

export function transition(record, stage, detail) {
  if (!STAGES.includes(stage)) throw new Error(`unknown stage ${stage}`);
  const from = record.stage;
  record.stage = stage;
  return note(record, `stage ${from} -> ${stage}`, detail);
}

/** Create or refresh the record for a Linear issue. Pure apart from I/O. */
export function upsertFromIssue(issue) {
  const existing = load(issue.identifier);
  const base = existing ?? {
    id: issue.id,
    identifier: issue.identifier,
    stage: "new",
    history: [],
    createdAt: new Date().toISOString(),
  };
  base.title = issue.title;
  base.url = issue.url;
  base.branch = issue.branchName;
  base.teamId = issue.team?.id;
  base.teamKey = issue.team?.key;
  base.linearState = issue.state?.name;
  base.linearUpdatedAt = issue.updatedAt;
  base.labels = (issue.labels?.nodes ?? []).map((l) => l.name);
  base.latestCommentAt = latestCommentAt(issue);
  base.lastSeenCommentAt ??= base.latestCommentAt;
  return save(base);
}

/** Newest comment timestamp on the issue, or null. Pure. */
export function latestCommentAt(issue) {
  const stamps = (issue.comments?.nodes ?? [])
    .map((c) => c.createdAt)
    .filter(Boolean);
  return stamps.length ? stamps.sort().at(-1) : null;
}

/**
 * Take the tick lock. The lock file is created exclusively; a file left by a
 * dead process is removed and creation retried, so two starters racing over
 * the same stale file cannot both win (only one unlink+create succeeds).
 */
export function acquireLock() {
  ensureStateDir();
  for (let attempt = 0; attempt < 2; attempt++) {
    try {
      fs.writeFileSync(lockPath(), String(process.pid), { flag: "wx" });
      return true;
    } catch (err) {
      if (err.code !== "EEXIST") throw err;
    }
    let pid = NaN;
    try {
      pid = Number(fs.readFileSync(lockPath(), "utf8"));
    } catch (err) {
      if (err.code !== "ENOENT") throw err;
      continue; // the other starter removed it; retry the exclusive create
    }
    if (pid && isAlive(pid)) return false;
    try {
      fs.unlinkSync(lockPath());
    } catch (err) {
      if (err.code !== "ENOENT") throw err;
    }
  }
  return false;
}

export function releaseLock() {
  try {
    fs.unlinkSync(lockPath());
  } catch {}
}

function isAlive(pid) {
  try {
    process.kill(pid, 0);
    return true;
  } catch {
    return false;
  }
}

export function stopRequested() {
  return fs.existsSync(stopPath());
}

export function setStop(on) {
  ensureStateDir();
  if (on) fs.writeFileSync(stopPath(), new Date().toISOString());
  else fs.rmSync(stopPath(), { force: true });
}

export function runDir(identifier, stage) {
  const dir = path.join(
    config.stateDir,
    "runs",
    assertIdentifier(identifier),
    `${new Date().toISOString().replace(/[:.]/g, "-")}-${stage}`,
  );
  fs.mkdirSync(dir, { recursive: true });
  return dir;
}

export function worktreePath(identifier) {
  return path.join(config.stateDir, "worktrees", assertIdentifier(identifier));
}

export function truncate(text, max = 160) {
  const s = String(text).replace(/\s+/g, " ");
  return s.length > max ? `${s.slice(0, max - 1)}…` : s;
}