@the-vibe-company/armada 0.1.2 → 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +17 -1
  2. package/dist/armada.js +1885 -1056
  3. package/package.json +1 -1
package/dist/armada.js CHANGED
@@ -23,7 +23,7 @@ import { spawn, spawnSync } from "node:child_process";
23
23
  import { readFile as readFile3 } from "node:fs/promises";
24
24
 
25
25
  // src/cli.ts
26
- import { dirname as dirname2, join as join4, resolve } from "node:path";
26
+ import { dirname as dirname3, join as join5, resolve } from "node:path";
27
27
 
28
28
  // ../../node_modules/.bun/smol-toml@1.9.0/node_modules/smol-toml/dist/error.js
29
29
  /*!
@@ -1080,7 +1080,7 @@ function parseConfig(text, source = CONFIG_FILE) {
1080
1080
  ["tracker", tracker, ["program_root", "language", "ready_label", "labels"]],
1081
1081
  ["tracker.labels", labelsT, ["phase_group", "runtime_group", "runtimes"]],
1082
1082
  ["github", github, ["repository"]],
1083
- ["gates", gatesT, ["required_checks"]],
1083
+ ["gates", gatesT, ["required_checks", "local_commands"]],
1084
1084
  ["policy", policyT, ["silence_minutes", "silent_after_minutes"]]
1085
1085
  ];
1086
1086
  for (const [path, t, keys] of known)
@@ -1114,6 +1114,14 @@ function parseConfig(text, source = CONFIG_FILE) {
1114
1114
  else
1115
1115
  problems.push(`"gates.required_checks" must be a list of check names`);
1116
1116
  }
1117
+ let localCommands = [];
1118
+ if (gatesT.local_commands !== undefined) {
1119
+ const v = gatesT.local_commands;
1120
+ if (Array.isArray(v) && v.every((c) => typeof c === "string" && c.trim()))
1121
+ localCommands = v.map((c) => c.trim());
1122
+ else
1123
+ problems.push(`"gates.local_commands" must be a list of shell commands`);
1124
+ }
1117
1125
  const config = {
1118
1126
  project: {
1119
1127
  name: str(project, "project", "name"),
@@ -1135,7 +1143,7 @@ function parseConfig(text, source = CONFIG_FILE) {
1135
1143
  github: {
1136
1144
  repository: str(github, "github", "repository", { pattern: REPOSITORY, hint: "owner/name" })
1137
1145
  },
1138
- gates: { requiredChecks },
1146
+ gates: { requiredChecks, localCommands },
1139
1147
  policy: { silentAfterMinutes }
1140
1148
  };
1141
1149
  if (problems.length)
@@ -2041,6 +2049,71 @@ async function fetchDefaultBranchFile(opts) {
2041
2049
  throw new GithubError(`GitHub: repository ${opts.repository} not found`);
2042
2050
  return json.data.repository.object?.text ?? null;
2043
2051
  }
2052
+ var MERGE_PULL_QUERY = `${PULL_FIELDS}
2053
+ query MergePull($owner: String!, $name: String!, $number: Int!) {
2054
+ repository(owner: $owner, name: $name) {
2055
+ pullRequest(number: $number) {
2056
+ ...P
2057
+ mergeStateStatus baseRefName mergeCommit { oid }
2058
+ reviewThreads(first: 100) { totalCount nodes { isResolved } }
2059
+ }
2060
+ }
2061
+ }`;
2062
+ async function fetchMergePull(opts) {
2063
+ const [owner, name] = opts.repository.split("/");
2064
+ const json = await githubQuery(opts, MERGE_PULL_QUERY, {
2065
+ owner,
2066
+ name,
2067
+ number: opts.number
2068
+ });
2069
+ const raw = json.data?.repository?.pullRequest;
2070
+ if (!raw)
2071
+ return null;
2072
+ const pr = normalizePull(raw, opts.repository);
2073
+ const threads = raw.reviewThreads.nodes;
2074
+ return {
2075
+ ...pr,
2076
+ state: pr.state ?? "open",
2077
+ headSha: raw.headRefOid,
2078
+ checks: pr.checks ?? [],
2079
+ mergeStateStatus: raw.mergeStateStatus,
2080
+ baseRef: raw.baseRefName,
2081
+ mergeCommit: raw.mergeCommit?.oid ?? null,
2082
+ reviewThreads: {
2083
+ total: raw.reviewThreads.totalCount,
2084
+ read: threads.length,
2085
+ unresolved: threads.filter((t) => !t.isResolved).length
2086
+ }
2087
+ };
2088
+ }
2089
+ var COMPARE_QUERY = `
2090
+ query Compare($owner: String!, $name: String!, $base: String!, $head: String!) {
2091
+ repository(owner: $owner, name: $name) {
2092
+ ref(qualifiedName: $base) { target { oid } compare(headRef: $head) { status aheadBy behindBy } }
2093
+ }
2094
+ }`;
2095
+ async function fetchComparison(opts) {
2096
+ const [owner, name] = opts.repository.split("/");
2097
+ const json = await githubQuery(opts, COMPARE_QUERY, { owner, name, base: `refs/heads/${opts.base}`, head: opts.head });
2098
+ const ref = json.data?.repository?.ref;
2099
+ if (!ref?.compare)
2100
+ return null;
2101
+ return { baseSha: ref.target.oid, ...ref.compare };
2102
+ }
2103
+ async function fetchPullDiff(opts) {
2104
+ const doFetch = opts.fetch ?? fetch;
2105
+ const timeoutMs = opts.timeoutMs ?? REQUEST_TIMEOUT_MS;
2106
+ const res = await doFetch(`https://api.github.com/repos/${opts.repository}/pulls/${opts.number}`, {
2107
+ method: "GET",
2108
+ headers: { Accept: "application/vnd.github.diff", Authorization: `Bearer ${opts.token}` },
2109
+ signal: AbortSignal.timeout(timeoutMs)
2110
+ }).catch((err) => {
2111
+ throw new GithubError(`GitHub API unreachable: ${networkReason(err, timeoutMs)}`);
2112
+ });
2113
+ if (!res.ok)
2114
+ throw new GithubError(`GitHub API HTTP ${res.status} reading the diff of #${opts.number}`);
2115
+ return res.text();
2116
+ }
2044
2117
  // ../core/src/labels.ts
2045
2118
  function requiredLabels(config) {
2046
2119
  return [
@@ -2430,7 +2503,11 @@ function handBackProblems({ pr, repository, sha, requiredChecks }) {
2430
2503
  problems.push(`the head of pull request #${pr.number} could not be read from GitHub`);
2431
2504
  else if (sha && FULL_SHA.test(sha) && pr.headSha !== sha)
2432
2505
  problems.push(`${sha} is not the head of pull request #${pr.number} (head is ${pr.headSha}); push, then report`);
2433
- const checks = pr.checks ?? [];
2506
+ problems.push(...checkProblems(pr.checks ?? [], requiredChecks));
2507
+ return problems;
2508
+ }
2509
+ function checkProblems(checks, requiredChecks) {
2510
+ const problems = [];
2434
2511
  if (requiredChecks.length) {
2435
2512
  for (const name of requiredChecks) {
2436
2513
  const runs = checks.filter((c) => c.name === name);
@@ -2449,927 +2526,1465 @@ function handBackProblems({ pr, repository, sha, requiredChecks }) {
2449
2526
  }
2450
2527
  return problems;
2451
2528
  }
2452
- // ../core/src/skills.ts
2453
- import { createHash } from "node:crypto";
2454
-
2455
- // ../../skills/armada-coordinator/MERGE.md
2456
- var MERGE_default = "# Merging a pull request\n\n`armada merge <pr>` runs this checklist, merges and closes the ticket. When you merge by hand, follow the same steps.\n\n## Before\n\n1. The worker has handed back: `Agent phase` is `ready-to-merge` and you have the full 40-character head SHA it reported.\n2. `gh pr view <n> --json headRefOid,mergeStateStatus,isDraft,title` shows that SHA, `CLEAN`, not a draft, and a Commitizen title.\n3. `gh pr checks <n>` shows every required check passing.\n4. The head contains the current default branch: `git merge-base --is-ancestor origin/<default> <sha>`. If not, ask the worker to rebase.\n5. Semantic check: search the default branch for callers of anything the pull request deletes or renames.\n\n## Merge\n\n```sh\ngh pr merge <n> --squash --match-head-commit <full-sha>\n```\n\n- One merge at a time.\n- Leave out `--delete-branch`: it deletes local worktrees that have the branch checked out, including other agents'. Delete the branch once its worktree is gone.\n- If GitHub answers with a 5xx, check `gh pr view <n> --json state` before retrying.\n\n## After\n\n1. The ticket is Done, its `Agent phase` and `Agent runtime` labels removed, the pull request linked.\n2. Tell every in-flight worker what the merge changes for them: a shared file, a migration, a new check, code they must now reuse or delete.\n3. Launch the tickets this merge unblocked.\n";
2457
-
2458
- // ../../skills/armada-coordinator/SKILL.md
2459
- var SKILL_default = `---
2460
- name: armada-coordinator
2461
- description: Coordinating an Armada fleet of coding agents on one project. Use when designated coordinator, or asked to launch workers on ready tickets, answer their questions, merge their green pull requests, or resume a fleet in a new local or cloud session. Reads the fleet with armada status and armada inbox and drives workers through the runtime guide skill.
2462
- ---
2463
-
2464
- The coordinator turns the owner's intent into merged pull requests. Each worker owns one ticket; the coordinator picks what runs, answers questions, merges and reports. There is one coordinator per project. \`armada.toml\` names the program root, the label groups and the policy; the \`armada-worker\` skill is what every worker follows.
2465
-
2466
- **Standing authority.** Unless the owner said otherwise, they delegate reversible technical decisions, plan approval and merging to you: act, then report. Escalate only product decisions, irreversible or outward-facing actions, and anything that spends money.
2467
-
2468
- **Armada never drives a runtime.** Launching, messaging, checking and stopping a worker go through the runtime guide skill for the worker's runtime (for example \`armada-runtime-conductor\`). Armada records what happened.
2469
-
2470
- ## Loop
2471
-
2472
- 1. **Read the fleet** with \`armada status\` and \`armada inbox\`, never from memory. Done when you can name every ticket in flight and its phase, every ready ticket, every pull request waiting, every silent worker and every pending question or request.
2473
- 2. **Answer what waits for you first.** For each question: decide, deliver the answer in the worker's session with the runtime guide's *message* section, then \`armada answer <item> --message "<decision and reason>"\`. Decide reversible choices yourself and prefer the option that keeps behaviour observable. When two workers need the same shared resource (a migration slot, a generated file, a version number), set the rule once and tell both.
2474
- 3. **Check silent workers** with the runtime guide's *status* section. A worker that is still working gets a nudge to report; a worker that died is relaunched or its ticket released.
2475
- 4. **Launch ready tickets** that do not collide with work in flight: \`armada brief <ticket>\` gives the launch prompt and the environment the runtime must pass; launch with the runtime guide's *launch* section, then record the handle with \`armada claim\` if the worker did not. Add to the brief what only you know: merged blockers and their hand-back notes, decisions already made, and which parallel workers touch neighbouring code. Done when every launched ticket is In Progress with a claim.
2476
- 5. **Merge handed-back pull requests** one at a time with \`armada merge <pr>\`, following [MERGE.md](MERGE.md). Done when the pull request is merged, the ticket is Done with its agent labels removed, and every in-flight worker affected by what landed has been told.
2477
- 6. **Turn findings into tickets.** A gap a worker reports or a bug you see becomes a ticket under the right spec, with blocked-by relations, and is launched when ready. No finding lives only in a transcript.
2478
- 7. **Report to the owner** in their language (\`tracker.language\` in \`armada.toml\`, or the owner's personal setting): what merged, what runs, what you decided for them, and the one thing they must do, with its exact place (a URL, a setting). Outcomes and numbers, no process narration.
2479
-
2480
- Repeat from step 1; \`armada inbox --wait\` blocks until something needs you.
2481
2529
 
2482
- ## Rules of thumb
2483
-
2484
- - Merge only after the worker's hand-back; a green pull request can still get one more rebased push.
2485
- - Parallel workers in one area collide: stagger them, or give each a disjoint area and tell them the boundary.
2486
- - Everything that must survive your session goes to the tracker or the repository. The next coordinator may be a fresh cloud session with none of your context: it resumes from \`armada status\` and \`armada inbox\`.
2487
- - When a command named here is missing from your Armada version (\`armada --help\`), do the step by hand with the same protocol and say so in your report.
2488
- `;
2489
-
2490
- // ../../skills/armada-runtime-conductor/SKILL.md
2491
- var SKILL_default2 = "---\nname: armada-runtime-conductor\ndescription: Runtime guide for running Armada workers on Conductor. Use when an Armada coordinator must launch a worker, send it a message, check whether it is alive, or stop and archive it on Conductor. Four fixed sections, each with the conductor command and how to read its output.\n---\n\nArmada never calls a runtime itself. This guide tells the coordinator how to do the four runtime actions with the `conductor` command line tool, and what to record in Armada afterwards. Check the exact flags with `conductor --help` and `conductor <command> --help`: this first version gives the commands to use, and a later Armada release completes the options and sample outputs.\n\n## Launch\n\n```sh\nconductor workspace create --repo <owner/name> --branch <ticket branch>\n```\n\nPass the prompt from `armada brief <ticket>` as the first message, and the environment variables it lists. Read the workspace id and the session id from the output; they form the handle `<workspace>/<session>`. Record it with `armada claim <ticket> --runtime conductor --handle <workspace>/<session>` unless the worker claims it itself.\n\n## Message\n\n```sh\nconductor message create --workspace <workspace> --session <session> --message \"<text>\"\n```\n\nUse it to deliver an answer, an approval or a heads-up that the default branch moved. A zero exit code means Conductor accepted the message; it does not mean the worker read it. After delivering an answer, record it with `armada answer`.\n\n## Status\n\n```sh\nconductor session status --workspace <workspace> --session <session>\n```\n\nTells whether the session is running, idle or ended. A silent worker whose session is running is busy: nudge it to report. An idle or ended session with the ticket not handed back needs a message or a relaunch.\n\n## Stop and archive\n\n```sh\nconductor workspace archive --workspace <workspace>\n```\n\nArchive a worker's workspace after its pull request is merged, or when its ticket is released. Archiving stops the session and frees the workspace; the branch and the pull request stay on GitHub.\n";
2492
-
2493
- // ../../skills/armada-worker/SKILL.md
2494
- var SKILL_default3 = `---
2495
- name: armada-worker
2496
- description: Working one ticket as an Armada worker agent. Use when you were launched on a ticket by an Armada coordinator, or asked to claim, plan, implement and ship one ticket of a project that has an armada.toml. Covers the claim, the phase reports every 15 minutes, questions to the coordinator, the green pull request and the hand-back. A worker never merges.
2497
- ---
2498
-
2499
- You are a worker. You own exactly one ticket, named in your launch brief. You turn it into one green pull request and hand it back to the coordinator, who merges. \`armada.toml\` at the repository root names the tracker program, the label groups and the policy; \`AGENTS.md\` (or \`CLAUDE.md\`) holds the repository's own rules, and they win over this skill where they are stricter.
2500
-
2501
- ## Rules
2502
-
2503
- - **Never merge**, never enable auto-merge, never approve your own plan. The coordinator merges.
2504
- - **Report at least every 15 minutes** of work with \`armada report <phase> --message "<what you are doing>"\`. The same phase is allowed: it is your heartbeat. A worker silent for longer than \`policy.silence_minutes\` shows as silent, and the coordinator comes to check on you.
2505
- - **Ask instead of guessing** when a choice changes the ticket's outcome: \`armada ask "<question, the options, your recommendation>"\`. Your phase becomes \`blocked\` until the coordinator answers in your session. Decide reversible technical choices yourself and record each one, with its reason, on the ticket and in the pull request.
2506
- - **The ticket is the source of truth.** Read it, its parent spec and the hand-back comments of its merged blockers in full before planning.
2507
- - Work only in your own branch and worktree. Never touch another agent's checkout, and stop only the processes you started.
2508
- - Never print, commit or log a secret.
2509
-
2510
- ## Steps
2511
-
2512
- 1. **Claim.** \`armada claim <ticket> --runtime <runtime> --handle <workspace>/<session>\`. It assigns the ticket, moves it to In Progress, sets \`Agent phase = planning\` and your \`Agent runtime\`, and posts the \`Agent claim\` comment. If it refuses because another claim exists, stop: the older claim wins.
2513
- 2. **Branch.** Use the branch named after the ticket (the tracker suggests one, for example \`feature/abc-12-short-title\`), created from the latest default branch.
2514
- 3. **Plan.** Write the plan: what changes, how it is tested, and the checks a person could observe when it is done. If your brief says plans are pre-approved, post it with \`armada report implementing --message "<plan>"\` and go on. Otherwise post it with \`armada report awaiting-approval --message "<plan>"\`, push your branch, and wait for the coordinator's answer in your session.
2515
- 4. **Implement** test-first. A material change to the approved plan needs a new approval.
2516
- 5. **Ship.** \`armada report shipping --pr <number>\`. Use the \`ship-pr-dev\` skill when the repository has it; otherwise run the repository's local checks, open the pull request with a Commitizen title (\`feat(scope): …\`), link it on the ticket, and fix CI until every required check is green.
2517
- 6. **Rebase** on the latest default branch right before hand-back, and get CI green on that final head.
2518
- 7. **Hand back.** \`armada report ready-to-merge --pr <number> --sha <full 40-character head SHA>\`. Armada refuses a short SHA, a SHA that is not the pull request head, or a red check. Then report to the coordinator: pull request URL, full SHA, CI state, the decisions you made, and what the next tickets need to know.
2519
-
2520
- If you stop without finishing, run \`armada release --reason "<why>"\` so the ticket is free again.
2521
-
2522
- ## When a command is missing
2523
-
2524
- This skill is versioned with Armada; an older CLI may lack a command (\`armada --help\` lists them). Do the same step by hand in the tracker, keeping the protocol: exactly one label from the phase group (\`planning\`, \`awaiting-approval\`, \`implementing\`, \`shipping\`, \`blocked\`, \`ready-to-merge\`) and one from the runtime group; a first comment \`Agent claim — runtime: <runtime> · session: <id> · branch: <branch> · started: <ISO date>\`; and every comment starting with \`Agent status: <phase> — <one-line summary>\`.
2525
- `;
2526
-
2527
- // ../core/src/skills.ts
2528
- var SKILLS_SOURCE = "The-Vibe-Company/armada";
2529
- var BUNDLED_SKILLS = [
2530
+ // ../core/src/turso.ts
2531
+ var MIGRATIONS = [
2530
2532
  {
2531
- name: "armada-coordinator",
2532
- files: [
2533
- { path: "MERGE.md", content: MERGE_default },
2534
- { path: "SKILL.md", content: SKILL_default }
2533
+ version: 1,
2534
+ statements: [
2535
+ `CREATE TABLE IF NOT EXISTS projects (
2536
+ slug TEXT PRIMARY KEY,
2537
+ name TEXT NOT NULL,
2538
+ repository TEXT NOT NULL,
2539
+ program_root TEXT NOT NULL,
2540
+ created_at TEXT NOT NULL,
2541
+ updated_at TEXT NOT NULL
2542
+ )`,
2543
+ `CREATE TABLE IF NOT EXISTS events (
2544
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
2545
+ project TEXT NOT NULL,
2546
+ ticket TEXT NOT NULL,
2547
+ kind TEXT NOT NULL,
2548
+ phase TEXT,
2549
+ message TEXT,
2550
+ runtime TEXT,
2551
+ handle TEXT,
2552
+ pr_url TEXT,
2553
+ head_sha TEXT,
2554
+ created_at TEXT NOT NULL
2555
+ )`,
2556
+ "CREATE INDEX IF NOT EXISTS events_by_ticket ON events (project, ticket, created_at)",
2557
+ `CREATE TABLE IF NOT EXISTS runtime_handles (
2558
+ project TEXT NOT NULL,
2559
+ ticket TEXT NOT NULL,
2560
+ runtime TEXT NOT NULL,
2561
+ handle TEXT NOT NULL,
2562
+ branch TEXT,
2563
+ claimed_at TEXT NOT NULL,
2564
+ released_at TEXT,
2565
+ PRIMARY KEY (project, ticket)
2566
+ )`,
2567
+ `CREATE TABLE IF NOT EXISTS inbox_items (
2568
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
2569
+ project TEXT NOT NULL,
2570
+ ticket TEXT,
2571
+ kind TEXT NOT NULL,
2572
+ recipient TEXT NOT NULL,
2573
+ author TEXT,
2574
+ body TEXT NOT NULL,
2575
+ created_at TEXT NOT NULL,
2576
+ resolved_at TEXT,
2577
+ resolution TEXT
2578
+ )`,
2579
+ "CREATE INDEX IF NOT EXISTS inbox_open ON inbox_items (project, recipient, resolved_at)",
2580
+ `CREATE TABLE IF NOT EXISTS leases (
2581
+ project TEXT NOT NULL,
2582
+ name TEXT NOT NULL,
2583
+ holder TEXT NOT NULL,
2584
+ acquired_at TEXT NOT NULL,
2585
+ expires_at TEXT NOT NULL,
2586
+ PRIMARY KEY (project, name)
2587
+ )`
2535
2588
  ]
2536
- },
2537
- { name: "armada-runtime-conductor", files: [{ path: "SKILL.md", content: SKILL_default2 }] },
2538
- { name: "armada-worker", files: [{ path: "SKILL.md", content: SKILL_default3 }] }
2539
- ];
2540
- function skillFolderHash(files) {
2541
- const hash = createHash("sha256");
2542
- for (const f of [...files].sort((a, b) => a.path.localeCompare(b.path))) {
2543
- hash.update(f.path);
2544
- hash.update(f.content);
2545
2589
  }
2546
- return hash.digest("hex");
2547
- }
2548
-
2549
- // ../core/src/setup.ts
2550
- var AGENTS_SKILLS_DIR = ".agents/skills";
2551
- var CLAUDE_SKILLS_DIR = ".claude/skills";
2552
- var SKILLS_LOCK_FILE = "skills-lock.json";
2553
- var CONDUCTOR_SETTINGS = ".conductor/settings.toml";
2554
- var GITIGNORE = ".gitignore";
2555
- var SHIP_ARTIFACTS = "plans/ship-pr-dev/";
2556
- var ok = (id, message) => ({ id, level: "ok", message, fix: null });
2557
- var bad = (id, level, message, fix) => ({
2558
- id,
2559
- level,
2560
- message,
2561
- fix
2562
- });
2563
- var skillDir = (name) => `${AGENTS_SKILLS_DIR}/${name}`;
2564
- var linkPath = (name) => `${CLAUDE_SKILLS_DIR}/${name}`;
2565
- var skillLinkTarget = (name) => `../../${AGENTS_SKILLS_DIR}/${name}`;
2566
- var bundledHash = (s) => skillFolderHash(s.files);
2567
- var WHOLE_DIR_LINKS = new Set(["../.agents/skills", "../.agents/skills/"]);
2568
- var linksWholeDir = async (view) => WHOLE_DIR_LINKS.has(await view.readLink(CLAUDE_SKILLS_DIR) ?? "");
2590
+ ];
2591
+ var SCHEMA_VERSION = MIGRATIONS.at(-1)?.version ?? 0;
2569
2592
 
2570
- class SetupError extends Error {
2571
- name = "SetupError";
2593
+ class TursoError extends Error {
2594
+ name = "TursoError";
2572
2595
  }
2573
- function parseSkillsLock(text) {
2574
- if (text === null)
2575
- return null;
2576
- let raw;
2596
+ function redact(err, token) {
2597
+ let message = err instanceof Error ? err.message : String(err);
2598
+ if (token)
2599
+ message = message.split(token).join("***");
2600
+ return message.replace(/(authToken=)[^&\s"']+/gi, "$1***");
2601
+ }
2602
+ async function openTurso({ url, token }) {
2603
+ let db;
2577
2604
  try {
2578
- raw = JSON.parse(text);
2579
- } catch {
2580
- throw new SetupError(`${SKILLS_LOCK_FILE} is not valid JSON`);
2605
+ const { createClient } = await import("@libsql/client");
2606
+ db = createClient(token ? { url, authToken: token } : { url });
2607
+ } catch (err) {
2608
+ throw new TursoError(`cannot open the Turso database: ${redact(err, token)}`);
2581
2609
  }
2582
- const lock = raw;
2583
- if (typeof lock?.version !== "number" || typeof lock.skills !== "object" || lock.skills === null)
2584
- throw new SetupError(`${SKILLS_LOCK_FILE} has no "version" number and "skills" object`);
2585
- return lock;
2586
- }
2587
- function conductorSetup(text) {
2588
- let raw;
2589
2610
  try {
2590
- raw = parse(text);
2611
+ await migrate(db);
2591
2612
  } catch (err) {
2592
- const where = err instanceof TomlError ? ` (line ${err.line}, column ${err.column})` : "";
2593
- throw new SetupError(`${CONDUCTOR_SETTINGS} is not valid TOML${where}`);
2613
+ db.close();
2614
+ throw new TursoError(`Turso database unavailable: ${redact(err, token)}`);
2594
2615
  }
2595
- const scripts = raw.scripts;
2596
- const setup = scripts?.setup;
2597
- return typeof setup === "string" ? setup.trim() : "";
2616
+ return db;
2598
2617
  }
2599
- var IGNORES_SHIP = new Set(["plans/ship-pr-dev/", "plans/ship-pr-dev", "plans/", "plans", "plans/*"]);
2600
- var ignoresShipArtifacts = (gitignore) => (gitignore ?? "").split(/\r?\n/).some((l) => IGNORES_SHIP.has(l.trim().replace(/^\//, "")));
2601
- async function checkRepository(view, armadaVersion) {
2602
- const checks = [];
2603
- const configText = await view.readFile(CONFIG_FILE);
2604
- if (configText === null)
2605
- checks.push(bad("config", "error", `${CONFIG_FILE} is missing`, "run `armada init --program-root <ISSUE-ID>` to open a pull request that adds it"));
2606
- else
2607
- try {
2608
- const config = parseConfig(configText, CONFIG_FILE);
2609
- checks.push(ok("config", `${CONFIG_FILE} is valid (project ${config.project.slug})`));
2610
- } catch (err) {
2611
- if (!(err instanceof ConfigError))
2612
- throw err;
2613
- checks.push(bad("config", "error", err.message, `fix the keys listed above in ${CONFIG_FILE}`));
2614
- }
2615
- let lock = null;
2616
- let lockError = null;
2617
- try {
2618
- lock = parseSkillsLock(await view.readFile(SKILLS_LOCK_FILE));
2619
- } catch (err) {
2620
- if (!(err instanceof SetupError))
2621
- throw err;
2622
- lockError = err.message;
2623
- }
2624
- if (lockError)
2625
- checks.push(bad("skills-lock", "error", lockError, `repair or delete ${SKILLS_LOCK_FILE}`));
2626
- const wholeDir = await linksWholeDir(view);
2627
- for (const skill of BUNDLED_SKILLS) {
2628
- const folder = await view.readFolder(skillDir(skill.name));
2629
- const installed = folder?.some((f) => f.path === "SKILL.md") ? skillFolderHash(folder) : null;
2630
- const id = `skill:${skill.name}`;
2631
- if (installed === null) {
2632
- checks.push(bad(id, "error", `skill ${skill.name} is missing from ${AGENTS_SKILLS_DIR}`, "run `armada init`"));
2633
- continue;
2634
- }
2635
- if (installed !== bundledHash(skill))
2636
- checks.push(bad(id, "warning", `skill ${skill.name} differs from the version in Armada ${armadaVersion}`, "run `armada init` to open a pull request that updates it"));
2637
- else
2638
- checks.push(ok(id, `skill ${skill.name} is up to date`));
2639
- const target = await view.readLink(linkPath(skill.name));
2640
- const linkId = `skill-link:${skill.name}`;
2641
- if (wholeDir)
2642
- checks.push(ok(linkId, `${CLAUDE_SKILLS_DIR} links to ${AGENTS_SKILLS_DIR}`));
2643
- else if (target === skillLinkTarget(skill.name))
2644
- checks.push(ok(linkId, `${linkPath(skill.name)} links to ${skillDir(skill.name)}`));
2645
- else
2646
- checks.push(bad(linkId, "error", target === null ? `${linkPath(skill.name)} is not a link to ${skillDir(skill.name)}, so Claude Code does not see the skill` : `${linkPath(skill.name)} links to ${target} instead of ${skillLinkTarget(skill.name)}`, "run `armada init`"));
2647
- if (lockError)
2618
+ async function migrate(db) {
2619
+ await db.execute("CREATE TABLE IF NOT EXISTS schema_migrations (version INTEGER PRIMARY KEY, applied_at TEXT NOT NULL)");
2620
+ const current = Number((await db.execute("SELECT max(version) AS v FROM schema_migrations")).rows[0]?.v ?? 0);
2621
+ for (const m of MIGRATIONS) {
2622
+ if (m.version <= current)
2648
2623
  continue;
2649
- const entry = lock?.skills[skill.name];
2650
- const lockId = `skill-lock:${skill.name}`;
2651
- if (!entry)
2652
- checks.push(bad(lockId, "error", `${SKILLS_LOCK_FILE} does not record ${skill.name}`, "run `armada init`"));
2653
- else if (installed !== null && entry.computedHash !== installed)
2654
- checks.push(bad(lockId, "warning", `${SKILLS_LOCK_FILE} records a different content for ${skill.name} than ${skillDir(skill.name)}`, "run `armada init`"));
2655
- else
2656
- checks.push(ok(lockId, `${SKILLS_LOCK_FILE} records ${skill.name}`));
2624
+ const stmts = [
2625
+ ...m.statements,
2626
+ {
2627
+ sql: "INSERT OR IGNORE INTO schema_migrations (version, applied_at) VALUES (?, ?)",
2628
+ args: [m.version, new Date().toISOString()]
2629
+ }
2630
+ ];
2631
+ await db.batch(stmts, "write");
2657
2632
  }
2658
- const settings = await view.readFile(CONDUCTOR_SETTINGS);
2659
- if (settings === null)
2660
- checks.push(bad("conductor", "error", `${CONDUCTOR_SETTINGS} is missing`, "run `armada init` to add it with a setup script"));
2661
- else
2662
- try {
2663
- checks.push(conductorSetup(settings) ? ok("conductor", `${CONDUCTOR_SETTINGS} has a setup script`) : bad("conductor", "error", `${CONDUCTOR_SETTINGS} has no [scripts] setup`, "run `armada init`, or add a setup command under [scripts]"));
2664
- } catch (err) {
2665
- if (!(err instanceof SetupError))
2666
- throw err;
2667
- checks.push(bad("conductor", "error", err.message, `fix ${CONDUCTOR_SETTINGS}`));
2668
- }
2669
- checks.push(ignoresShipArtifacts(await view.readFile(GITIGNORE)) ? ok("gitignore", `${GITIGNORE} ignores ${SHIP_ARTIFACTS}`) : bad("gitignore", "warning", `${GITIGNORE} does not ignore ${SHIP_ARTIFACTS}, so the ship-pr-dev skill refuses to start`, "run `armada init`"));
2670
- return checks;
2633
+ return Math.max(current, SCHEMA_VERSION);
2671
2634
  }
2672
- async function guessSetupCommand(view) {
2673
- const has = async (p) => await view.readFile(p) !== null;
2674
- if (await has("bun.lock") || await has("bun.lockb"))
2675
- return "bun install --frozen-lockfile";
2676
- if (await has("pnpm-lock.yaml"))
2677
- return "pnpm install --frozen-lockfile";
2678
- if (await has("yarn.lock"))
2679
- return "yarn install --frozen-lockfile";
2680
- if (await has("package-lock.json"))
2681
- return "npm ci";
2682
- return null;
2635
+ async function upsertProject(db, p, now = new Date) {
2636
+ const at = now.toISOString();
2637
+ await db.execute({
2638
+ sql: `INSERT INTO projects (slug, name, repository, program_root, created_at, updated_at)
2639
+ VALUES (?, ?, ?, ?, ?, ?)
2640
+ ON CONFLICT (slug) DO UPDATE SET
2641
+ name = excluded.name, repository = excluded.repository,
2642
+ program_root = excluded.program_root, updated_at = excluded.updated_at
2643
+ WHERE name IS NOT excluded.name OR repository IS NOT excluded.repository
2644
+ OR program_root IS NOT excluded.program_root`,
2645
+ args: [p.slug, p.name, p.repository, p.programRoot, at, at]
2646
+ });
2683
2647
  }
2684
- var SETUP_COMMENT = "# Commands a fresh workspace runs once: install dependencies, copy env files.";
2685
- function conductorSettings(setup) {
2686
- return `"$schema" = "https://conductor.build/schemas/settings.repo.schema.json"
2687
-
2688
- [scripts]
2689
- ${SETUP_COMMENT}
2690
- setup = ${JSON.stringify(setup ?? "true")}
2691
- `;
2648
+ async function ensureProject(db, p, now = new Date) {
2649
+ const at = now.toISOString();
2650
+ await db.execute({
2651
+ sql: `INSERT OR IGNORE INTO projects (slug, name, repository, program_root, created_at, updated_at)
2652
+ VALUES (?, ?, ?, ?, ?, ?)`,
2653
+ args: [p.slug, p.name, p.repository, p.programRoot, at, at]
2654
+ });
2692
2655
  }
2693
- function withSetup(text, setup) {
2694
- const command = setup ?? "true";
2695
- const line = `${SETUP_COMMENT}
2696
- setup = ${JSON.stringify(command)}`;
2697
- const lines = text.split(`
2698
- `);
2699
- const at = lines.findIndex((l) => /^\s*\[scripts\]\s*(#.*)?$/.test(l));
2700
- let edited;
2701
- if (at >= 0) {
2702
- lines.splice(at + 1, 0, line);
2703
- edited = lines.join(`
2704
- `);
2705
- } else
2706
- edited = `${text.replace(/\n*$/, `
2707
- `)}
2708
- [scripts]
2709
- ${line}
2710
- `;
2711
- let result = "";
2712
- try {
2713
- result = conductorSetup(edited);
2714
- } catch {}
2715
- if (result !== command)
2716
- throw new SetupError(`${CONDUCTOR_SETTINGS} has a [scripts] table Armada cannot add a setup command to safely; set \`setup\` under [scripts] by hand`);
2717
- return edited;
2656
+ async function listProjects(db) {
2657
+ const rs = await db.execute("SELECT slug, name, repository, program_root, created_at, updated_at FROM projects ORDER BY slug");
2658
+ return rs.rows.map((r) => ({
2659
+ slug: String(r.slug),
2660
+ name: String(r.name),
2661
+ repository: String(r.repository),
2662
+ programRoot: String(r.program_root),
2663
+ createdAt: String(r.created_at),
2664
+ updatedAt: String(r.updated_at)
2665
+ }));
2718
2666
  }
2719
- function lockText(lock, armadaVersion) {
2720
- const skills = { ...lock?.skills ?? {} };
2721
- for (const s of BUNDLED_SKILLS)
2722
- skills[s.name] = {
2723
- source: SKILLS_SOURCE,
2724
- sourceType: "github",
2725
- skillPath: `skills/${s.name}/SKILL.md`,
2726
- ...armadaVersion === "0.0.0" ? {} : { ref: `v${armadaVersion}` },
2727
- computedHash: bundledHash(s)
2728
- };
2729
- const sorted = Object.fromEntries(Object.keys(skills).sort().map((k) => [k, skills[k]]));
2730
- return `${JSON.stringify({ version: lock?.version ?? 1, skills: sorted }, null, 2)}
2731
- `;
2667
+ async function recordEvent(db, e) {
2668
+ await db.execute({
2669
+ sql: `INSERT INTO events (project, ticket, kind, phase, message, runtime, handle, pr_url, head_sha, created_at)
2670
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
2671
+ args: [
2672
+ e.project,
2673
+ e.ticket,
2674
+ e.kind,
2675
+ e.phase ?? null,
2676
+ e.message ?? null,
2677
+ e.runtime ?? null,
2678
+ e.handle ?? null,
2679
+ e.prUrl ?? null,
2680
+ e.headSha ?? null,
2681
+ e.at.toISOString()
2682
+ ]
2683
+ });
2732
2684
  }
2733
- async function planSetup(view, opts) {
2734
- const plan = { writes: [], removes: [], links: [], installed: [], updated: [] };
2735
- if (opts.configText !== null && await view.readFile(CONFIG_FILE) === null)
2736
- plan.writes.push({ path: CONFIG_FILE, content: opts.configText });
2737
- const wholeDir = await linksWholeDir(view);
2738
- for (const skill of BUNDLED_SKILLS) {
2739
- const folder = await view.readFolder(skillDir(skill.name));
2740
- const current = folder?.length ? skillFolderHash(folder) === bundledHash(skill) : false;
2741
- if (!current) {
2742
- ((folder?.length) ? plan.updated : plan.installed).push(skill.name);
2743
- for (const f of skill.files)
2744
- plan.writes.push({ path: `${skillDir(skill.name)}/${f.path}`, content: f.content });
2745
- const keep = new Set(skill.files.map((f) => f.path));
2746
- for (const f of folder ?? [])
2747
- if (!keep.has(f.path))
2748
- plan.removes.push(`${skillDir(skill.name)}/${f.path}`);
2749
- }
2750
- if (!wholeDir && await view.readLink(linkPath(skill.name)) !== skillLinkTarget(skill.name))
2751
- plan.links.push({ path: linkPath(skill.name), target: skillLinkTarget(skill.name) });
2752
- }
2753
- const lockBefore = await view.readFile(SKILLS_LOCK_FILE);
2754
- const lockAfter = lockText(parseSkillsLock(lockBefore), opts.armadaVersion);
2755
- if (lockAfter !== lockBefore)
2756
- plan.writes.push({ path: SKILLS_LOCK_FILE, content: lockAfter });
2757
- const settings = await view.readFile(CONDUCTOR_SETTINGS);
2758
- if (settings === null)
2759
- plan.writes.push({ path: CONDUCTOR_SETTINGS, content: conductorSettings(await guessSetupCommand(view)) });
2760
- else if (!conductorSetup(settings))
2761
- plan.writes.push({ path: CONDUCTOR_SETTINGS, content: withSetup(settings, await guessSetupCommand(view)) });
2762
- const gitignore = await view.readFile(GITIGNORE);
2763
- if (!ignoresShipArtifacts(gitignore)) {
2764
- const base = gitignore === null || gitignore === "" ? "" : `${gitignore.replace(/\n*$/, `
2765
- `)}
2766
- `;
2767
- plan.writes.push({
2768
- path: GITIGNORE,
2769
- content: `${base}# Local agent run artifacts (ship-pr-dev)
2770
- ${SHIP_ARTIFACTS}
2771
- `
2772
- });
2773
- }
2774
- return plan;
2685
+ async function lastEventTimes(db, project) {
2686
+ const rs = await db.execute({
2687
+ sql: "SELECT ticket, max(created_at) AS at FROM events WHERE project = ? GROUP BY ticket",
2688
+ args: [project]
2689
+ });
2690
+ return Object.fromEntries(rs.rows.map((r) => [String(r.ticket), String(r.at)]));
2775
2691
  }
2776
- var planIsEmpty = (p) => !p.writes.length && !p.removes.length && !p.links.length;
2777
- // ../core/src/status.ts
2778
- var STATUS_SCHEMA_VERSION = 1;
2779
- function buildStatus({
2780
- config,
2781
- program,
2782
- forge,
2783
- forgeError = null,
2784
- lastEvents,
2785
- extraWarnings = [],
2786
- now
2787
- }) {
2788
- const issues = attachPullRequests(program, forge);
2789
- const m = buildModel(issues, program.rootId);
2790
- const lanes = inFlight(m, program.comments, {
2791
- now: now.getTime(),
2792
- silentAfterMinutes: config.policy.silentAfterMinutes,
2793
- ...lastEvents ? { lastEvents } : {}
2692
+ async function saveRuntimeHandle(db, h) {
2693
+ await db.execute({
2694
+ sql: `INSERT INTO runtime_handles (project, ticket, runtime, handle, branch, claimed_at, released_at)
2695
+ VALUES (?, ?, ?, ?, ?, ?, NULL)
2696
+ ON CONFLICT (project, ticket) DO UPDATE SET
2697
+ claimed_at = CASE WHEN handle = excluded.handle AND released_at IS NULL
2698
+ THEN claimed_at ELSE excluded.claimed_at END,
2699
+ runtime = excluded.runtime, handle = excluded.handle, branch = excluded.branch,
2700
+ released_at = NULL`,
2701
+ args: [h.project, h.ticket, h.runtime, h.handle, h.branch, h.at.toISOString()]
2794
2702
  });
2795
- const phaseOf = new Map(lanes.map((l) => [l.issue.id, l.phase]));
2796
- const prRef = (p) => ({
2797
- number: p.number,
2798
- url: p.url,
2799
- title: p.title,
2800
- draft: p.draft ?? null,
2801
- ci: p.ci ?? null,
2802
- mergeable: p.mergeable ?? null
2703
+ }
2704
+ async function releaseRuntimeHandle(db, project, ticket, at) {
2705
+ await db.execute({
2706
+ sql: "UPDATE runtime_handles SET released_at = ? WHERE project = ? AND ticket = ? AND released_at IS NULL",
2707
+ args: [at.toISOString(), project, ticket]
2803
2708
  });
2804
- return {
2805
- schemaVersion: STATUS_SCHEMA_VERSION,
2806
- generatedAt: now.toISOString(),
2807
- project: { name: config.project.name, slug: config.project.slug, repository: config.github.repository },
2808
- programRoot: { id: m.root.id, title: m.root.title, url: m.root.url },
2809
- sources: {
2810
- linear: { fetchedAt: program.fetchedAt },
2811
- github: { fetchedAt: forge?.fetchedAt ?? null, error: forge ? null : forgeError ?? "not read" }
2812
- },
2813
- silentAfterMinutes: config.policy.silentAfterMinutes,
2814
- inFlight: lanes.map((l) => ({
2815
- id: l.issue.id,
2816
- title: l.issue.title,
2817
- url: l.issue.url,
2818
- spec: l.spec,
2819
- phase: l.phase,
2820
- phaseSource: l.phaseSource,
2821
- runtime: l.runtime,
2822
- agent: l.agent,
2823
- since: l.since,
2824
- lastUpdate: l.lastUpdate,
2825
- lastReport: l.lastReport,
2826
- silent: l.flags.includes("silent"),
2827
- statusLine: l.statusLine ? { summary: l.statusLine.summary, at: l.statusLine.at, url: l.statusLine.url } : null,
2828
- pr: l.pr ? prRef(l.pr) : null,
2829
- openBlockers: l.openBlockers,
2830
- flags: l.flags
2831
- })),
2832
- frontier: frontier(m, config.tracker.readyLabel).map((c) => ({
2833
- id: c.issue.id,
2834
- title: c.issue.title,
2835
- url: c.issue.url,
2836
- spec: c.spec,
2837
- readyForAgent: c.readyForAgent,
2838
- onCriticalPath: c.onCriticalPath,
2839
- unlocks: c.unlocksAll
2840
- })),
2841
- pullRequests: forge ? waitingPullRequests(m, forge.prs).map(({ pr, ticket }) => ({
2842
- ...prRef(pr),
2843
- headSha: pr.headSha ?? null,
2844
- updatedAt: pr.updatedAt ?? null,
2845
- failingChecks: (pr.checks ?? []).filter((c) => c.state === "failure").map((c) => c.name),
2846
- ticket: ticket ? { id: ticket.id, phase: phaseOf.get(ticket.id) ?? ticket.agentPhase } : null
2847
- })) : null,
2848
- warnings: [...program.warnings, ...forge?.warnings ?? [], ...extraWarnings]
2849
- };
2850
2709
  }
2851
- async function loadStatus(config, opts) {
2852
- const now = opts.now ?? (() => new Date);
2853
- const programP = fetchProgram({
2854
- apiKey: opts.linearApiKey,
2855
- rootId: config.tracker.programRoot,
2856
- labels: config.tracker.labels,
2857
- ...opts.fetch ? { fetch: opts.fetch } : {},
2858
- now
2710
+ async function openRuntimeHandles(db, project) {
2711
+ const rs = await db.execute({
2712
+ sql: `SELECT project, ticket, runtime, handle, branch, claimed_at, released_at
2713
+ FROM runtime_handles WHERE project = ? AND released_at IS NULL ORDER BY ticket`,
2714
+ args: [project]
2859
2715
  });
2860
- const forgeP = opts.githubToken ? fetchForge({
2861
- token: opts.githubToken,
2862
- repository: config.github.repository,
2863
- ...opts.fetch ? { fetch: opts.fetch } : {},
2864
- now
2865
- }).then((forge2) => ({ forge: forge2, error: null }), (err) => ({ forge: null, error: err instanceof Error ? err.message : String(err) })) : Promise.resolve({ forge: null, error: "no GitHub token (set GITHUB_TOKEN or run gh auth login)" });
2866
- const eventsP = opts.lastEvents ? opts.lastEvents().then((events2) => ({ events: events2 }), (err) => ({
2867
- warning: `Turso could not be read (${err instanceof Error ? err.message : String(err)}); silence is measured from Linear only`
2868
- })) : Promise.resolve({});
2869
- const [program, { forge, error }, events] = await Promise.all([programP, forgeP, eventsP]);
2870
- return buildStatus({
2871
- config,
2872
- program,
2873
- forge,
2874
- forgeError: error,
2875
- ...events.events ? { lastEvents: events.events } : {},
2876
- extraWarnings: events.warning ? [events.warning] : [],
2877
- now: now()
2716
+ return rs.rows.map((r) => ({
2717
+ project: String(r.project),
2718
+ ticket: String(r.ticket),
2719
+ runtime: String(r.runtime),
2720
+ handle: String(r.handle),
2721
+ branch: r.branch === null ? null : String(r.branch),
2722
+ claimedAt: String(r.claimed_at),
2723
+ releasedAt: null
2724
+ }));
2725
+ }
2726
+ async function getRuntimeHandle(db, project, ticket) {
2727
+ const rs = await db.execute({
2728
+ sql: `SELECT project, ticket, runtime, handle, branch, claimed_at, released_at
2729
+ FROM runtime_handles WHERE project = ? AND ticket = ?`,
2730
+ args: [project, ticket]
2878
2731
  });
2732
+ const r = rs.rows[0];
2733
+ return r ? {
2734
+ project: String(r.project),
2735
+ ticket: String(r.ticket),
2736
+ runtime: String(r.runtime),
2737
+ handle: String(r.handle),
2738
+ branch: r.branch === null ? null : String(r.branch),
2739
+ claimedAt: String(r.claimed_at),
2740
+ releasedAt: r.released_at === null ? null : String(r.released_at)
2741
+ } : null;
2879
2742
  }
2880
- // ../core/src/turso.ts
2881
- var MIGRATIONS = [
2882
- {
2883
- version: 1,
2884
- statements: [
2885
- `CREATE TABLE IF NOT EXISTS projects (
2886
- slug TEXT PRIMARY KEY,
2887
- name TEXT NOT NULL,
2888
- repository TEXT NOT NULL,
2889
- program_root TEXT NOT NULL,
2890
- created_at TEXT NOT NULL,
2891
- updated_at TEXT NOT NULL
2892
- )`,
2893
- `CREATE TABLE IF NOT EXISTS events (
2894
- id INTEGER PRIMARY KEY AUTOINCREMENT,
2895
- project TEXT NOT NULL,
2896
- ticket TEXT NOT NULL,
2897
- kind TEXT NOT NULL,
2898
- phase TEXT,
2899
- message TEXT,
2900
- runtime TEXT,
2901
- handle TEXT,
2902
- pr_url TEXT,
2903
- head_sha TEXT,
2904
- created_at TEXT NOT NULL
2905
- )`,
2906
- "CREATE INDEX IF NOT EXISTS events_by_ticket ON events (project, ticket, created_at)",
2907
- `CREATE TABLE IF NOT EXISTS runtime_handles (
2908
- project TEXT NOT NULL,
2909
- ticket TEXT NOT NULL,
2910
- runtime TEXT NOT NULL,
2911
- handle TEXT NOT NULL,
2912
- branch TEXT,
2913
- claimed_at TEXT NOT NULL,
2914
- released_at TEXT,
2915
- PRIMARY KEY (project, ticket)
2916
- )`,
2917
- `CREATE TABLE IF NOT EXISTS inbox_items (
2918
- id INTEGER PRIMARY KEY AUTOINCREMENT,
2919
- project TEXT NOT NULL,
2920
- ticket TEXT,
2921
- kind TEXT NOT NULL,
2922
- recipient TEXT NOT NULL,
2923
- author TEXT,
2924
- body TEXT NOT NULL,
2925
- created_at TEXT NOT NULL,
2926
- resolved_at TEXT,
2927
- resolution TEXT
2928
- )`,
2929
- "CREATE INDEX IF NOT EXISTS inbox_open ON inbox_items (project, recipient, resolved_at)",
2930
- `CREATE TABLE IF NOT EXISTS leases (
2931
- project TEXT NOT NULL,
2932
- name TEXT NOT NULL,
2933
- holder TEXT NOT NULL,
2934
- acquired_at TEXT NOT NULL,
2935
- expires_at TEXT NOT NULL,
2936
- PRIMARY KEY (project, name)
2937
- )`
2743
+ async function addInboxItem(db, item) {
2744
+ const rs = await db.execute({
2745
+ sql: `INSERT INTO inbox_items (project, ticket, kind, recipient, author, body, created_at)
2746
+ VALUES (?, ?, ?, ?, ?, ?, ?)`,
2747
+ args: [item.project, item.ticket, item.kind, item.recipient, item.author, item.body, item.at.toISOString()]
2748
+ });
2749
+ return Number(rs.lastInsertRowid);
2750
+ }
2751
+ async function putHandBack(db, item) {
2752
+ const updated = await db.execute({
2753
+ sql: `UPDATE inbox_items SET body = ?, author = ?, created_at = ?
2754
+ WHERE project = ? AND ticket = ? AND kind = 'hand-back' AND resolved_at IS NULL`,
2755
+ args: [item.body, item.author, item.at.toISOString(), item.project, item.ticket]
2756
+ });
2757
+ if (!updated.rowsAffected)
2758
+ await addInboxItem(db, { ...item, kind: "hand-back", recipient: "coordinator" });
2759
+ }
2760
+ async function openInboxItems(db, q) {
2761
+ const rs = await db.execute({
2762
+ sql: `SELECT id, project, ticket, kind, recipient, author, body, created_at FROM inbox_items
2763
+ WHERE project = ? AND recipient = ? AND resolved_at IS NULL ${q.ticket ? "AND ticket = ?" : ""}
2764
+ ORDER BY created_at, id`,
2765
+ args: q.ticket ? [q.project, q.recipient, q.ticket] : [q.project, q.recipient]
2766
+ });
2767
+ return rs.rows.map((r) => ({
2768
+ id: Number(r.id),
2769
+ project: String(r.project),
2770
+ ticket: r.ticket === null ? null : String(r.ticket),
2771
+ kind: String(r.kind),
2772
+ recipient: String(r.recipient),
2773
+ author: r.author === null ? null : String(r.author),
2774
+ body: String(r.body),
2775
+ createdAt: String(r.created_at)
2776
+ }));
2777
+ }
2778
+ async function resolveInboxItems(db, q) {
2779
+ const rs = await db.execute({
2780
+ sql: `UPDATE inbox_items SET resolved_at = ?, resolution = ?
2781
+ WHERE project = ? AND ticket = ? AND kind = ? AND resolved_at IS NULL`,
2782
+ args: [q.at.toISOString(), q.resolution, q.project, q.ticket, q.kind]
2783
+ });
2784
+ return rs.rowsAffected;
2785
+ }
2786
+ async function acquireLease(db, l) {
2787
+ const at = l.at.toISOString();
2788
+ const expires = new Date(l.at.getTime() + l.ttlMs).toISOString();
2789
+ const rs = await db.execute({
2790
+ sql: `INSERT INTO leases (project, name, holder, acquired_at, expires_at) VALUES (?, ?, ?, ?, ?)
2791
+ ON CONFLICT (project, name) DO UPDATE SET
2792
+ acquired_at = CASE WHEN leases.holder = excluded.holder THEN leases.acquired_at ELSE excluded.acquired_at END,
2793
+ holder = excluded.holder, expires_at = excluded.expires_at
2794
+ WHERE leases.holder = excluded.holder OR leases.expires_at <= ?`,
2795
+ args: [l.project, l.name, l.holder, at, expires, at]
2796
+ });
2797
+ if (rs.rowsAffected)
2798
+ return { acquired: true };
2799
+ return { acquired: false, held: await getLease(db, l.project, l.name) };
2800
+ }
2801
+ async function getLease(db, project, name) {
2802
+ const rs = await db.execute({
2803
+ sql: "SELECT project, name, holder, acquired_at, expires_at FROM leases WHERE project = ? AND name = ?",
2804
+ args: [project, name]
2805
+ });
2806
+ const r = rs.rows[0];
2807
+ return r ? {
2808
+ project: String(r.project),
2809
+ name: String(r.name),
2810
+ holder: String(r.holder),
2811
+ acquiredAt: String(r.acquired_at),
2812
+ expiresAt: String(r.expires_at)
2813
+ } : null;
2814
+ }
2815
+ async function renewLease(db, l) {
2816
+ const rs = await db.execute({
2817
+ sql: "UPDATE leases SET expires_at = ? WHERE project = ? AND name = ? AND holder = ?",
2818
+ args: [new Date(l.at.getTime() + l.ttlMs).toISOString(), l.project, l.name, l.holder]
2819
+ });
2820
+ return rs.rowsAffected > 0;
2821
+ }
2822
+ async function releaseLease(db, l) {
2823
+ await db.execute({
2824
+ sql: "DELETE FROM leases WHERE project = ? AND name = ? AND holder = ?",
2825
+ args: [l.project, l.name, l.holder]
2826
+ });
2827
+ }
2828
+
2829
+ // ../core/src/worker.ts
2830
+ class Refusal extends Error {
2831
+ name = "Refusal";
2832
+ }
2833
+ var TURSO_TIMEOUT_MS = 1e4;
2834
+ async function live(ctx, warnings, what, step) {
2835
+ const { db, warning } = await ctx.turso();
2836
+ if (!db) {
2837
+ if (warning)
2838
+ warnings.push(warning);
2839
+ return null;
2840
+ }
2841
+ let timer;
2842
+ try {
2843
+ return await Promise.race([
2844
+ step(db),
2845
+ new Promise((_, reject) => {
2846
+ timer = setTimeout(() => reject(new Error(`no answer within ${TURSO_TIMEOUT_MS / 1000} s`)), TURSO_TIMEOUT_MS);
2847
+ })
2848
+ ]);
2849
+ } catch (err) {
2850
+ warnings.push(`Turso: could not ${what} (${redact(err)}); Linear is up to date`);
2851
+ return null;
2852
+ } finally {
2853
+ clearTimeout(timer);
2854
+ }
2855
+ }
2856
+ var projectOf = (config) => ({
2857
+ slug: config.project.slug,
2858
+ name: config.project.name,
2859
+ repository: config.github.repository,
2860
+ programRoot: config.tracker.programRoot
2861
+ });
2862
+ async function readOpenTicket(ctx, id) {
2863
+ const ticket = await ctx.linear.readTicket(id);
2864
+ if (!ticket)
2865
+ throw new Refusal(`ticket ${id} not found in Linear`);
2866
+ if (ticket.statusType === "completed" || ticket.statusType === "canceled")
2867
+ throw new Refusal(`${ticket.id} is ${ticket.statusType}; there is nothing to work on`);
2868
+ return ticket;
2869
+ }
2870
+ var ID = /(?:^|[^a-z0-9])([a-z][a-z0-9]*-\d+)(?=$|[^a-z0-9])/gi;
2871
+ function ticketFromBranch(branch, programRoot) {
2872
+ const ids = [...branch.matchAll(ID)].map((m) => (m[1] ?? "").toUpperCase());
2873
+ const team = programRoot.split("-")[0]?.toUpperCase();
2874
+ return ids.find((id) => id.split("-")[0] === team) ?? ids[0] ?? null;
2875
+ }
2876
+ function activeClaimComments(comments) {
2877
+ const asc = [...comments].sort((a, b) => a.createdAt.localeCompare(b.createdAt) || a.id.localeCompare(b.id));
2878
+ let active = [];
2879
+ for (const c of asc) {
2880
+ if (c.status?.phase === "released")
2881
+ active = [];
2882
+ if (c.claim)
2883
+ active.push(c);
2884
+ }
2885
+ return active;
2886
+ }
2887
+ function findLabel(labels, name, group) {
2888
+ const found = labels.find((l) => sameName(l.name, name));
2889
+ if (found)
2890
+ return found;
2891
+ const names = labels.map((l) => l.name).join(", ") || "none";
2892
+ throw new Refusal(`no "${name}" label in the "${group}" label group (available: ${names})`);
2893
+ }
2894
+ var others = (ticket, group, keep) => ticket.labels.filter((l) => l.group === group && l.id !== keep).map((l) => l.id);
2895
+ var firstState = (states, ...types) => {
2896
+ for (const type of types) {
2897
+ const s = states.find((x) => x.type === type);
2898
+ if (s)
2899
+ return s;
2900
+ }
2901
+ return null;
2902
+ };
2903
+ function claimLine(o) {
2904
+ return `Agent claim — runtime: ${o.runtime} · session: ${o.handle} · branch: ${o.branch ?? "unknown"} · started: ${o.started}`;
2905
+ }
2906
+ async function claimTicket(ctx, input) {
2907
+ const { config, linear } = ctx;
2908
+ const groups = config.tracker.labels;
2909
+ const ticket = await readOpenTicket(ctx, input.ticket);
2910
+ const [phaseLabels, runtimeLabels] = await Promise.all([
2911
+ linear.groupLabels(groups.phaseGroup, ticket.teamId),
2912
+ linear.groupLabels(groups.runtimeGroup, ticket.teamId)
2913
+ ]);
2914
+ const planning = findLabel(phaseLabels, "planning", groups.phaseGroup);
2915
+ const runtime = findLabel(runtimeLabels, input.runtime, groups.runtimeGroup);
2916
+ const branch = input.branch ?? ticket.branchName;
2917
+ const warnings = [...ticket.warnings];
2918
+ const lines = [];
2919
+ if (ticket.commentsTruncated)
2920
+ throw new Refusal(`${ticket.id} has more comments than Armada reads, so an older claim may be hidden; claim it by hand`);
2921
+ const viewer = await linear.viewer();
2922
+ const inProgress = ticket.statusType === "started" ? null : firstState(ticket.states, "started");
2923
+ const held = activeClaimComments(ticket.comments);
2924
+ const holder = held[0]?.claim;
2925
+ const resuming = !!holder && holder.session === input.handle;
2926
+ if (!resuming) {
2927
+ if (holder)
2928
+ throw new Refusal(`${ticket.id} is already claimed by ${holder.runtime ?? "an unknown runtime"} · ${holder.session ?? "unknown session"} since ${holder.at}; release it first with \`armada release\``);
2929
+ if (ticket.agentPhase)
2930
+ throw new Refusal(`${ticket.id} already carries the agent phase "${ticket.agentPhase}"; release it first with \`armada release\``);
2931
+ const started = ctx.now().toISOString();
2932
+ const body = `Agent status: planning — claimed by ${runtime.name} (${input.handle})
2933
+
2934
+ ${claimLine({ runtime: runtime.name, handle: input.handle, branch, started })}`;
2935
+ const mine = await linear.comment(ticket.uuid, body);
2936
+ const after = await linear.readTicket(ticket.id);
2937
+ const winner = after ? activeClaimComments(after.comments)[0] : undefined;
2938
+ if (winner && winner.id !== mine.id) {
2939
+ await linear.deleteComment(mine.id);
2940
+ throw new Refusal(`${ticket.id} was claimed first by ${winner.claim?.runtime ?? "another worker"} · ${winner.claim?.session ?? "unknown session"}; your claim was withdrawn`);
2941
+ }
2942
+ lines.push(`Claimed ${ticket.id} for ${runtime.name} (${input.handle}).`);
2943
+ } else {
2944
+ lines.push(`${ticket.id} is already claimed by this session (${input.handle}); labels and state repaired.`);
2945
+ }
2946
+ if (ticket.statusType !== "started" && !inProgress)
2947
+ warnings.push(`the team of ${ticket.id} has no started state; the ticket was not moved`);
2948
+ const phaseLabel = resuming && ticket.agentPhase ? null : planning;
2949
+ await linear.updateTicket(ticket.uuid, {
2950
+ ...inProgress ? { stateId: inProgress.id } : {},
2951
+ ...ticket.assigneeId !== viewer.id ? { assigneeId: viewer.id } : {},
2952
+ addLabelIds: [phaseLabel, runtime].filter((l) => !!l && !ticket.labels.some((x) => x.id === l.id)).map((l) => l.id),
2953
+ removeLabelIds: [
2954
+ ...phaseLabel ? others(ticket, groups.phaseGroup, phaseLabel.id) : [],
2955
+ ...others(ticket, groups.runtimeGroup, runtime.id)
2938
2956
  ]
2957
+ });
2958
+ lines.push(`${inProgress ? `Moved to ${inProgress.name}` : "State unchanged"}, assigned to ${viewer.name}, labels ${phaseLabel?.name ?? ticket.agentPhase} and ${runtime.name}.`);
2959
+ const at = ctx.now();
2960
+ await live(ctx, warnings, "record the claim", async (db) => {
2961
+ await ensureProject(db, projectOf(config), at);
2962
+ await saveRuntimeHandle(db, {
2963
+ project: config.project.slug,
2964
+ ticket: ticket.id,
2965
+ runtime: runtime.name,
2966
+ handle: input.handle,
2967
+ branch,
2968
+ at
2969
+ });
2970
+ await recordEvent(db, {
2971
+ project: config.project.slug,
2972
+ ticket: ticket.id,
2973
+ kind: "claim",
2974
+ phase: phaseLabel ? "planning" : ticket.agentPhase,
2975
+ runtime: runtime.name,
2976
+ handle: input.handle,
2977
+ at
2978
+ });
2979
+ });
2980
+ return { ticket: ticket.id, url: ticket.url, lines, warnings, inbox: null };
2981
+ }
2982
+ function resolvePr(ticket, repository, pr) {
2983
+ if (pr) {
2984
+ const trimmed = pr.trim().replace(/^#/, "");
2985
+ if (/^\d+$/.test(trimmed)) {
2986
+ const url = `https://github.com/${repository}/pull/${trimmed}`;
2987
+ return parsePullRequestUrl(url);
2988
+ }
2989
+ const parsed = parsePullRequestUrl(trimmed);
2990
+ if (!parsed)
2991
+ throw new Refusal(`--pr must be a pull request number or URL, got "${pr}"`);
2992
+ return parsed;
2939
2993
  }
2940
- ];
2941
- var SCHEMA_VERSION = MIGRATIONS.at(-1)?.version ?? 0;
2994
+ const inRepo = ticket.prs.filter((p) => p.repo.toLowerCase() === repository.toLowerCase());
2995
+ return [...inRepo].sort((a, b) => b.number - a.number)[0] ?? null;
2996
+ }
2997
+ async function reportPhase(ctx, input) {
2998
+ const { config, linear } = ctx;
2999
+ const groups = config.tracker.labels;
3000
+ const ticket = await readOpenTicket(ctx, input.ticket);
3001
+ const problem = transitionProblem(ticket.agentPhase, input.phase);
3002
+ if (problem)
3003
+ throw new Refusal(`${ticket.id}: ${problem}`);
3004
+ const warnings = [...ticket.warnings];
3005
+ const message = input.message?.trim() ?? "";
3006
+ let pr = resolvePr(ticket, config.github.repository, input.pr);
3007
+ const sha = input.sha?.trim().toLowerCase() || null;
3008
+ let summary;
3009
+ let body;
3010
+ if (input.phase === "ready-to-merge") {
3011
+ const inRepo = !!pr && pr.repo.toLowerCase() === config.github.repository.toLowerCase();
3012
+ if (inRepo && !ctx.readPull)
3013
+ throw new Refusal("a hand-back needs GitHub to check the pull request head and CI; set GITHUB_TOKEN or run `gh auth login`");
3014
+ if (pr && inRepo && ctx.readPull) {
3015
+ const fresh = await ctx.readPull(pr.number);
3016
+ if (!fresh)
3017
+ throw new Refusal(`pull request #${pr.number} was not found in ${config.github.repository}`);
3018
+ pr = fresh;
3019
+ }
3020
+ const problems = handBackProblems({
3021
+ pr,
3022
+ repository: config.github.repository,
3023
+ sha,
3024
+ requiredChecks: config.gates.requiredChecks
3025
+ });
3026
+ if (problems.length)
3027
+ throw new Refusal(`${ticket.id}: hand-back refused:
3028
+ ${problems.map((p) => ` - ${p}`).join(`
3029
+ `)}`);
3030
+ summary = `PR #${pr?.number}, head ${sha}, CI green`;
3031
+ body = message;
3032
+ } else {
3033
+ if (!message)
3034
+ throw new Refusal("--message is required: say what you did or what you are doing");
3035
+ const [first = "", ...rest] = message.split(`
3036
+ `);
3037
+ summary = first.trim();
3038
+ body = rest.join(`
3039
+ `).trim();
3040
+ }
3041
+ const target = ticket.agentPhase === input.phase ? null : findLabel(await linear.groupLabels(groups.phaseGroup, ticket.teamId), input.phase, groups.phaseGroup);
3042
+ if (pr && input.pr && !ticket.prs.some((p) => p.url === pr?.url)) {
3043
+ await linear.linkUrl(ticket.uuid, pr.url, pr.title || `Pull request #${pr.number}`);
3044
+ }
3045
+ if (target) {
3046
+ await linear.updateTicket(ticket.uuid, {
3047
+ addLabelIds: [target.id],
3048
+ removeLabelIds: others(ticket, groups.phaseGroup, target.id)
3049
+ });
3050
+ }
3051
+ const statusLine = `Agent status: ${input.phase} — ${summary}`;
3052
+ await linear.comment(ticket.uuid, body ? `${statusLine}
3053
+
3054
+ ${body}` : statusLine);
3055
+ const lines = [
3056
+ ticket.agentPhase === input.phase ? `Status update posted on ${ticket.id} (${input.phase}).` : `${ticket.id}: ${ticket.agentPhase} → ${input.phase}.`
3057
+ ];
3058
+ const at = ctx.now();
3059
+ const inbox = await live(ctx, warnings, "record the report", async (db) => {
3060
+ await ensureProject(db, projectOf(config), at);
3061
+ await recordEvent(db, {
3062
+ project: config.project.slug,
3063
+ ticket: ticket.id,
3064
+ kind: "report",
3065
+ phase: input.phase,
3066
+ message: summary,
3067
+ prUrl: pr?.url ?? null,
3068
+ headSha: sha,
3069
+ at
3070
+ });
3071
+ if (input.phase === "ready-to-merge")
3072
+ await putHandBack(db, {
3073
+ project: config.project.slug,
3074
+ ticket: ticket.id,
3075
+ author: null,
3076
+ body: statusLine,
3077
+ at
3078
+ });
3079
+ return openInboxItems(db, { project: config.project.slug, recipient: "worker", ticket: ticket.id });
3080
+ });
3081
+ return { ticket: ticket.id, url: ticket.url, lines, warnings, inbox };
3082
+ }
3083
+ async function releaseTicket(ctx, input) {
3084
+ const { config, linear } = ctx;
3085
+ const groups = config.tracker.labels;
3086
+ const ticket = await readOpenTicket(ctx, input.ticket);
3087
+ if (!ticket.agentPhase && !ticket.agentRuntime && !activeClaimComments(ticket.comments).length)
3088
+ throw new Refusal(`${ticket.id} is not claimed; there is nothing to release`);
3089
+ const warnings = [...ticket.warnings];
3090
+ const back = ticket.statusType === "started" ? firstState(ticket.states, "unstarted", "backlog") : null;
3091
+ await linear.updateTicket(ticket.uuid, {
3092
+ ...back ? { stateId: back.id } : {},
3093
+ removeLabelIds: [...others(ticket, groups.phaseGroup, null), ...others(ticket, groups.runtimeGroup, null)]
3094
+ });
3095
+ await linear.comment(ticket.uuid, `Agent status: released — ${input.reason.trim()}`);
3096
+ const lines = [`Released ${ticket.id}${back ? `, moved back to ${back.name}` : ""}.`];
3097
+ const at = ctx.now();
3098
+ await live(ctx, warnings, "record the release", async (db) => {
3099
+ await ensureProject(db, projectOf(config), at);
3100
+ await releaseRuntimeHandle(db, config.project.slug, ticket.id, at);
3101
+ await recordEvent(db, {
3102
+ project: config.project.slug,
3103
+ ticket: ticket.id,
3104
+ kind: "release",
3105
+ message: input.reason.trim(),
3106
+ at
3107
+ });
3108
+ });
3109
+ return { ticket: ticket.id, url: ticket.url, lines, warnings, inbox: null };
3110
+ }
2942
3111
 
2943
- class TursoError extends Error {
2944
- name = "TursoError";
3112
+ // ../core/src/merge.ts
3113
+ var MERGE_LEASE = "merge";
3114
+ var MERGE_LEASE_TTL_MS = 20 * 60000;
3115
+ var LEASE_POLL_MS = 5000;
3116
+ var MERGE_BACKOFF_MS = [2000, 4000, 8000];
3117
+ var CONFIRM_BACKOFF_MS = [1000, 2000, 4000, 8000];
3118
+ var UNKNOWN_BACKOFF_MS = [2000, 4000];
3119
+ var COMMITIZEN_TITLE = /^(feat|fix|docs|style|refactor|perf|test|build|ci|chore|revert)(\([\w./,-]+\))?!?: \S/;
3120
+ function findHandBack(ticket) {
3121
+ const c = ticket.comments.find((x) => x.status?.phase === "ready-to-merge");
3122
+ if (!c?.status)
3123
+ return null;
3124
+ const pr = c.status.summary.match(/\bPR #(\d+)/i)?.[1];
3125
+ const sha = c.status.summary.match(/\bhead ([0-9a-f]+)\b/i)?.[1];
3126
+ return { pr: pr ? Number(pr) : null, sha: sha?.toLowerCase() ?? null, at: c.createdAt };
3127
+ }
3128
+ var STATE_HELP = {
3129
+ BEHIND: "the base branch requires it to be up to date; ask the worker to rebase",
3130
+ BLOCKED: "a branch protection rule blocks it (a required review or check)",
3131
+ DIRTY: "it conflicts with its base; ask the worker to rebase",
3132
+ DRAFT: "it is a draft",
3133
+ HAS_HOOKS: "GitHub reports pre-receive hooks; merge it by hand",
3134
+ UNKNOWN: "GitHub is still computing mergeability; try again in a minute",
3135
+ UNSTABLE: "a check that is not required is failing"
3136
+ };
3137
+ function mergeProblems({ pull, ticket, handBack, requiredChecks }) {
3138
+ const n = `#${pull.number}`;
3139
+ const problems = [];
3140
+ if (ticket.agentPhase !== "ready-to-merge")
3141
+ problems.push(`${ticket.id} has not been handed back: its agent phase is ${ticket.agentPhase ?? "not set"}, not ready-to-merge`);
3142
+ if (!handBack)
3143
+ problems.push(`${ticket.id} has no "Agent status: ready-to-merge" comment carrying the head SHA`);
3144
+ else {
3145
+ if (handBack.pr !== null && handBack.pr !== pull.number)
3146
+ problems.push(`the hand-back on ${ticket.id} names PR #${handBack.pr}, not ${n}`);
3147
+ if (!handBack.sha)
3148
+ problems.push(`the hand-back on ${ticket.id} carries no head SHA`);
3149
+ else if (!FULL_SHA.test(handBack.sha))
3150
+ problems.push(`the handed-back SHA ${handBack.sha} is not a full 40-character SHA; ask the worker to report ready-to-merge again`);
3151
+ else if (handBack.sha !== pull.headSha)
3152
+ problems.push(`the head of ${n} is ${pull.headSha}, not the handed-back ${handBack.sha}: it moved after the hand-back; ask the worker to report again`);
3153
+ }
3154
+ if (pull.state !== "open")
3155
+ problems.push(`${n} is ${pull.state}, not open`);
3156
+ if (pull.draft)
3157
+ problems.push(`${n} is a draft`);
3158
+ if (!COMMITIZEN_TITLE.test(pull.title))
3159
+ problems.push(`the title "${pull.title}" is not in Commitizen format, e.g. "feat(cli): add a command"`);
3160
+ if (pull.mergeStateStatus !== "CLEAN")
3161
+ problems.push(`GitHub reports ${n} as ${pull.mergeStateStatus}, not CLEAN${STATE_HELP[pull.mergeStateStatus] ? `: ${STATE_HELP[pull.mergeStateStatus]}` : ""}`);
3162
+ for (const p of checkProblems(pull.checks, requiredChecks))
3163
+ problems.push(`on head ${pull.headSha.slice(0, 7)}: ${p}`);
3164
+ const { total, read, unresolved } = pull.reviewThreads;
3165
+ if (unresolved)
3166
+ problems.push(`${n} has ${unresolved} unresolved review thread${unresolved > 1 ? "s" : ""}`);
3167
+ else if (total > read)
3168
+ problems.push(`${n} has more than ${read} review threads; check they are resolved by hand`);
3169
+ return problems;
2945
3170
  }
2946
- function redact(err, token) {
2947
- let message = err instanceof Error ? err.message : String(err);
2948
- if (token)
2949
- message = message.split(token).join("***");
2950
- return message.replace(/(authToken=)[^&\s"']+/gi, "$1***");
3171
+ function baseProblem(pull, cmp, localCommands) {
3172
+ if (!cmp)
3173
+ return `GitHub could not compare the head of #${pull.number} with ${pull.baseRef}`;
3174
+ if (cmp.behindBy === 0)
3175
+ return null;
3176
+ if (!localCommands.length)
3177
+ return `the head lacks ${cmp.behindBy} commit${cmp.behindBy > 1 ? "s" : ""} of ${pull.baseRef}; ask the worker to rebase, or declare [gates] local_commands in armada.toml so armada merge can test the merge`;
3178
+ return null;
2951
3179
  }
2952
- async function openTurso({ url, token }) {
2953
- let db;
3180
+ var CODE_FILE = /\.(?:[cm]?[jt]sx?|py|go|rs)$/;
3181
+ var DECLARATIONS = [
3182
+ /^(?:export\s+)?(?:default\s+)?(?:declare\s+)?(?:abstract\s+)?(?:async\s+)?(?:function\*?|class|interface|type|enum|const|let|var)\s+([A-Za-z_$][\w$]*)/,
3183
+ /^(?:async\s+)?(?:def|class)\s+([A-Za-z_]\w*)/,
3184
+ /^(?:func\s+(?:\([^)]*\)\s*)?|type\s+)([A-Za-z_]\w*)/,
3185
+ /^(?:pub(?:\([^)]*\))?\s+)?(?:async\s+)?(?:fn|struct|enum|trait|mod|const|static)\s+([A-Za-z_]\w*)/
3186
+ ];
3187
+ function declared(line) {
3188
+ for (const re of DECLARATIONS) {
3189
+ const name = line.match(re)?.[1];
3190
+ if (name)
3191
+ return name;
3192
+ }
3193
+ return null;
3194
+ }
3195
+ function removedSymbols(diff) {
3196
+ const removed = new Map;
3197
+ const added = new Set;
3198
+ const files = new Set;
3199
+ let file = "";
3200
+ for (const line of diff.split(`
3201
+ `)) {
3202
+ const header = line.match(/^diff --git a\/(.+?) b\/(.+)$/);
3203
+ if (header?.[1] && header[2]) {
3204
+ files.add(header[1]).add(header[2]);
3205
+ file = header[1];
3206
+ continue;
3207
+ }
3208
+ if (!CODE_FILE.test(file) || line.startsWith("---") || line.startsWith("+++"))
3209
+ continue;
3210
+ const name = line[0] === "-" || line[0] === "+" ? declared(line.slice(1)) : null;
3211
+ if (!name || name.length < 3)
3212
+ continue;
3213
+ if (line[0] === "-")
3214
+ removed.set(name, file);
3215
+ else
3216
+ added.add(name);
3217
+ }
3218
+ for (const name of added)
3219
+ removed.delete(name);
3220
+ return { removed, files };
3221
+ }
3222
+ function semanticHints(symbols, uses, base) {
3223
+ const hints = [];
3224
+ for (const [name, from] of symbols.removed) {
3225
+ const elsewhere = (uses.get(name) ?? []).filter((f) => !symbols.files.has(f));
3226
+ if (!elsewhere.length)
3227
+ continue;
3228
+ const shown = elsewhere.slice(0, 5).join(", ");
3229
+ const more = elsewhere.length > 5 ? ` and ${elsewhere.length - 5} more` : "";
3230
+ hints.push(`\`${name}\`, removed from ${from}, still appears on ${base} in ${shown}${more}`);
3231
+ }
3232
+ return hints;
3233
+ }
3234
+ var LOCK_CALL_TIMEOUT_MS = 1e4;
3235
+ async function timed(p, ms, what) {
3236
+ let timer;
2954
3237
  try {
2955
- const { createClient } = await import("@libsql/client");
2956
- db = createClient(token ? { url, authToken: token } : { url });
2957
- } catch (err) {
2958
- throw new TursoError(`cannot open the Turso database: ${redact(err, token)}`);
3238
+ return await Promise.race([
3239
+ p,
3240
+ new Promise((_, reject) => {
3241
+ timer = setTimeout(() => reject(new Refusal(`Turso did not answer within ${ms / 1000} s to ${what}; nothing was merged`)), ms);
3242
+ })
3243
+ ]);
3244
+ } finally {
3245
+ clearTimeout(timer);
3246
+ }
3247
+ }
3248
+ async function withLease(db, o, body) {
3249
+ const key = { project: o.project, name: o.name, holder: o.holder, ttlMs: o.ttlMs };
3250
+ const poll = o.pollMs ?? LEASE_POLL_MS;
3251
+ const maxWait = o.maxWaitMs ?? o.ttlMs;
3252
+ const lockTimeout = o.timeoutMs ?? LOCK_CALL_TIMEOUT_MS;
3253
+ let waited = 0;
3254
+ let lastHolder;
3255
+ for (;; ) {
3256
+ const got = await timed(acquireLease(db, { ...key, at: o.now() }), lockTimeout, `take the ${o.name} lock`).catch(async (err) => {
3257
+ await timed(releaseLease(db, key), lockTimeout, `release the ${o.name} lock`).catch(() => {});
3258
+ throw err;
3259
+ });
3260
+ if (got.acquired)
3261
+ break;
3262
+ if (waited >= maxWait)
3263
+ throw new Refusal(`the ${o.name} lock of ${o.project} is still held by ${got.held?.holder ?? "another coordinator"} (until ${got.held?.expiresAt ?? "unknown"}); try again later`);
3264
+ if (got.held?.holder !== lastHolder) {
3265
+ lastHolder = got.held?.holder ?? null;
3266
+ o.onWait?.(got.held);
3267
+ }
3268
+ await o.sleep(poll);
3269
+ waited += poll;
2959
3270
  }
2960
3271
  try {
2961
- await migrate(db);
3272
+ return await body(() => timed(renewLease(db, { ...key, at: o.now() }), lockTimeout, `renew the ${o.name} lock`).catch(() => false));
3273
+ } finally {
3274
+ await timed(releaseLease(db, key), lockTimeout, `release the ${o.name} lock`).catch(() => {});
3275
+ }
3276
+ }
3277
+ var say = (ctx, line) => ctx.progress?.(line);
3278
+ async function readSettled(ctx, number) {
3279
+ let pull = await ctx.forge.readPull(number);
3280
+ for (const ms of UNKNOWN_BACKOFF_MS) {
3281
+ if (pull?.state !== "open" || pull.mergeStateStatus !== "UNKNOWN")
3282
+ break;
3283
+ await ctx.sleep(ms);
3284
+ pull = await ctx.forge.readPull(number);
3285
+ }
3286
+ if (!pull)
3287
+ throw new Refusal(`pull request #${number} was not found in ${ctx.config.github.repository}`);
3288
+ return pull;
3289
+ }
3290
+ async function readTicketFor(ctx, pull, explicit) {
3291
+ const id = explicit?.trim().toUpperCase() || (pull.headRef ? ticketFromBranch(pull.headRef, ctx.config.tracker.programRoot) : null);
3292
+ if (!id)
3293
+ throw new Refusal(`the branch of #${pull.number} (${pull.headRef ?? "unknown"}) names no ticket; pass --ticket <id>`);
3294
+ const ticket = await ctx.linear.readTicket(id);
3295
+ if (!ticket)
3296
+ throw new Refusal(`ticket ${id} not found in Linear`);
3297
+ return ticket;
3298
+ }
3299
+ async function checklist(ctx, input) {
3300
+ const { config } = ctx;
3301
+ const pull = await readSettled(ctx, input.pr);
3302
+ const ticket = await readTicketFor(ctx, pull, input.ticket);
3303
+ const handBack = findHandBack(ticket);
3304
+ const warnings = [...ticket.warnings];
3305
+ const lines = [];
3306
+ const problems = mergeProblems({ pull, ticket, handBack, requiredChecks: config.gates.requiredChecks });
3307
+ const cmp = await ctx.forge.compare(pull.baseRef, pull.headSha);
3308
+ const behind = baseProblem(pull, cmp, config.gates.localCommands);
3309
+ if (behind)
3310
+ problems.push(behind);
3311
+ else if (cmp && cmp.behindBy > 0) {
3312
+ if (!ctx.repo)
3313
+ problems.push(`the head lacks commits of ${pull.baseRef} and git is not available to test the merge`);
3314
+ else if (!problems.length) {
3315
+ say(ctx, `The head lacks ${cmp.behindBy} commit(s) of ${pull.baseRef}; testing the merge in a throwaway worktree…`);
3316
+ const test = await ctx.repo.testMerge({
3317
+ branch: pull.baseRef,
3318
+ base: cmp.baseSha,
3319
+ head: pull.headSha,
3320
+ number: pull.number,
3321
+ commands: config.gates.localCommands
3322
+ });
3323
+ if (test.ok)
3324
+ lines.push(`Head lacks ${cmp.behindBy} commit(s) of ${pull.baseRef}; the test merge passed every local command.`);
3325
+ else
3326
+ problems.push(`the test merge into ${pull.baseRef} failed at \`${test.step}\`:
3327
+ ${indent(test.output)}`);
3328
+ }
3329
+ }
3330
+ const hints = await hintsFor(ctx, pull, cmp, warnings);
3331
+ if (problems.length)
3332
+ throw new Refusal(`#${pull.number} (${ticket.id}) cannot be merged:
3333
+ ${problems.map((p) => ` - ${p}`).join(`
3334
+ `)}${hints.length ? `
3335
+ Hints (not blocking):
3336
+ ${hints.map((h) => ` - ${h}`).join(`
3337
+ `)}` : ""}`);
3338
+ lines.unshift(`Checklist passed for #${pull.number} (${ticket.id}): handed back at ${pull.headSha}, CLEAN, checks green, no open review thread.`);
3339
+ return { pull, ticket, sha: pull.headSha, baseSha: cmp?.baseSha ?? null, lines, hints, warnings };
3340
+ }
3341
+ var indent = (text) => text.trimEnd().split(`
3342
+ `).map((l) => ` ${l}`).join(`
3343
+ `);
3344
+ async function hintsFor(ctx, pull, cmp, warnings) {
3345
+ try {
3346
+ const symbols = removedSymbols(await ctx.forge.diff(pull.number));
3347
+ if (!symbols.removed.size)
3348
+ return [];
3349
+ if (!ctx.repo || !cmp) {
3350
+ warnings.push(`semantic hint skipped: ${ctx.repo ? `GitHub could not compare the head with ${pull.baseRef}` : "git is not available to search the base branch"}`);
3351
+ return [];
3352
+ }
3353
+ const uses = await ctx.repo.grepWords({
3354
+ branch: pull.baseRef,
3355
+ rev: cmp.baseSha,
3356
+ words: [...symbols.removed.keys()]
3357
+ });
3358
+ return semanticHints(symbols, uses, pull.baseRef);
2962
3359
  } catch (err) {
2963
- db.close();
2964
- throw new TursoError(`Turso database unavailable: ${redact(err, token)}`);
3360
+ warnings.push(`semantic hint skipped: ${err instanceof Error ? err.message : String(err)}`);
3361
+ return [];
2965
3362
  }
2966
- return db;
2967
3363
  }
2968
- async function migrate(db) {
2969
- await db.execute("CREATE TABLE IF NOT EXISTS schema_migrations (version INTEGER PRIMARY KEY, applied_at TEXT NOT NULL)");
2970
- const current = Number((await db.execute("SELECT max(version) AS v FROM schema_migrations")).rows[0]?.v ?? 0);
2971
- for (const m of MIGRATIONS) {
2972
- if (m.version <= current)
2973
- continue;
2974
- const stmts = [
2975
- ...m.statements,
2976
- {
2977
- sql: "INSERT OR IGNORE INTO schema_migrations (version, applied_at) VALUES (?, ?)",
2978
- args: [m.version, new Date().toISOString()]
2979
- }
2980
- ];
2981
- await db.batch(stmts, "write");
3364
+ async function recheck(ctx, c) {
3365
+ const pull = await readSettled(ctx, c.pull.number);
3366
+ const ticket = await ctx.linear.readTicket(c.ticket.id) ?? c.ticket;
3367
+ const problems = mergeProblems({
3368
+ pull,
3369
+ ticket,
3370
+ handBack: findHandBack(ticket),
3371
+ requiredChecks: ctx.config.gates.requiredChecks
3372
+ });
3373
+ if (pull.headSha === c.sha) {
3374
+ const cmp = await ctx.forge.compare(pull.baseRef, pull.headSha);
3375
+ if (cmp?.baseSha !== c.baseSha)
3376
+ problems.push(`${pull.baseRef} moved to ${cmp?.baseSha ?? "an unknown commit"} while #${pull.number} was checked`);
2982
3377
  }
2983
- return Math.max(current, SCHEMA_VERSION);
3378
+ if (problems.length)
3379
+ throw new Refusal(`#${pull.number} changed while it was checked; nothing was merged, run armada merge again:
3380
+ ${problems.map((p) => ` - ${p}`).join(`
3381
+ `)}`);
2984
3382
  }
2985
- async function upsertProject(db, p, now = new Date) {
2986
- const at = now.toISOString();
2987
- await db.execute({
2988
- sql: `INSERT INTO projects (slug, name, repository, program_root, created_at, updated_at)
2989
- VALUES (?, ?, ?, ?, ?, ?)
2990
- ON CONFLICT (slug) DO UPDATE SET
2991
- name = excluded.name, repository = excluded.repository,
2992
- program_root = excluded.program_root, updated_at = excluded.updated_at
2993
- WHERE name IS NOT excluded.name OR repository IS NOT excluded.repository
2994
- OR program_root IS NOT excluded.program_root`,
2995
- args: [p.slug, p.name, p.repository, p.programRoot, at, at]
3383
+ async function mergePinned(ctx, pull, sha, ticket) {
3384
+ const n = `#${pull.number}`;
3385
+ let readError = "";
3386
+ const read = () => {
3387
+ readError = "";
3388
+ return ctx.forge.readPull(pull.number).catch((err) => {
3389
+ readError = err instanceof Error ? err.message : String(err);
3390
+ return null;
3391
+ });
3392
+ };
3393
+ for (let attempt = 0;; attempt++) {
3394
+ const res = await ctx.forge.merge(pull.number, sha);
3395
+ if (res.ok)
3396
+ break;
3397
+ const fresh = await read();
3398
+ if (fresh?.state === "merged")
3399
+ break;
3400
+ if (!fresh)
3401
+ throw new Refusal(`GitHub failed (${res.message}) and ${n} could not be read back (${readError || "not found"}); check it on GitHub: if it merged, close ${ticket} by hand`);
3402
+ if (!res.transient)
3403
+ throw new Refusal(`GitHub refused to merge ${n}: ${res.message}`);
3404
+ if (fresh.state !== "open")
3405
+ throw new Refusal(`GitHub failed (${res.message}) and ${n} is now ${fresh.state}; not retrying`);
3406
+ if (fresh.headSha !== sha)
3407
+ throw new Refusal(`GitHub failed (${res.message}) and the head of ${n} moved to ${fresh.headSha}; not retrying`);
3408
+ const wait = MERGE_BACKOFF_MS[attempt];
3409
+ if (wait === undefined)
3410
+ throw new Refusal(`GitHub kept failing (${res.message}) after ${attempt + 1} attempts; ${n} is still open and nothing was merged`);
3411
+ say(ctx, `GitHub answered ${res.message}; ${n} is still open at ${sha.slice(0, 7)}, retrying in ${wait / 1000} s…`);
3412
+ await ctx.sleep(wait);
3413
+ }
3414
+ let seen = null;
3415
+ for (let i = 0;; i++) {
3416
+ seen = await read();
3417
+ if (seen?.state === "merged")
3418
+ break;
3419
+ const wait = CONFIRM_BACKOFF_MS[i];
3420
+ if (wait === undefined)
3421
+ throw new Refusal(seen ? `the merge of ${n} was accepted but GitHub shows it as ${seen.state}, not merged (auto-merge or a merge queue?); the ticket was left as is` : `the merge of ${n} was accepted but GitHub could not be read back (${readError || "not found"}); check it on GitHub: if it merged, close ${ticket} by hand`);
3422
+ await ctx.sleep(wait);
3423
+ }
3424
+ if (seen.headSha !== sha)
3425
+ throw new Refusal(`${n} was merged at ${seen.headSha}, not at the handed-back ${sha}; check main now`);
3426
+ return seen;
3427
+ }
3428
+ var runtimeGuide = (runtime) => runtime ? `armada-runtime-${runtime.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "")}` : null;
3429
+ async function closeTicket(ctx, ticket, merged, unlocked) {
3430
+ const groups = ctx.config.tracker.labels;
3431
+ const done = ticket.statusType === "completed" ? null : firstState(ticket.states, "completed");
3432
+ await ctx.linear.updateTicket(ticket.uuid, {
3433
+ ...done ? { stateId: done.id } : {},
3434
+ removeLabelIds: [...others(ticket, groups.phaseGroup, null), ...others(ticket, groups.runtimeGroup, null)]
2996
3435
  });
3436
+ if (!ticket.prs.some((p) => p.url === merged.url))
3437
+ await ctx.linear.linkUrl(ticket.uuid, merged.url, merged.title || `Pull request #${merged.number}`);
3438
+ await ctx.linear.comment(ticket.uuid, `Agent status: merged — PR #${merged.number} squash-merged into ${merged.baseRef} as ${merged.mergeCommit ?? "unknown"}, head ${merged.headSha}${unlocked ? ", merged without lock (--no-lock)" : ""}`);
3439
+ return [
3440
+ `${ticket.id}: ${done ? `moved to ${done.name}` : "state unchanged"}, agent labels removed, merged status posted.`
3441
+ ];
2997
3442
  }
2998
- async function ensureProject(db, p, now = new Date) {
2999
- const at = now.toISOString();
3000
- await db.execute({
3001
- sql: `INSERT OR IGNORE INTO projects (slug, name, repository, program_root, created_at, updated_at)
3002
- VALUES (?, ?, ?, ?, ?, ?)`,
3003
- args: [p.slug, p.name, p.repository, p.programRoot, at, at]
3443
+ async function mergePullRequest(ctx, input) {
3444
+ if (input.dryRun) {
3445
+ const c = await checklist(ctx, input);
3446
+ return outcome(c, false, null, c.lines.concat("Dry run: nothing was merged."), [], null);
3447
+ }
3448
+ const { config } = ctx;
3449
+ const slug = config.project.slug;
3450
+ const early = [];
3451
+ const run = async (renew) => {
3452
+ const c = await checklist(ctx, input);
3453
+ c.warnings.unshift(...early);
3454
+ await recheck(ctx, c);
3455
+ if (!await renew())
3456
+ throw new Refusal("the merge lock could not be renewed (it expired and another coordinator took it, or Turso did not answer); nothing was merged");
3457
+ say(ctx, `Merging #${c.pull.number} at ${c.sha}…`);
3458
+ const merged = await mergePinned(ctx, c.pull, c.sha, c.ticket.id);
3459
+ const lines = [
3460
+ ...c.lines,
3461
+ `Merged #${merged.number} into ${merged.baseRef} as ${merged.mergeCommit ?? "unknown"} (head ${merged.headSha}).`
3462
+ ];
3463
+ try {
3464
+ lines.push(...await closeTicket(ctx, c.ticket, merged, !!input.noLock));
3465
+ } catch (err) {
3466
+ throw new Error(`#${merged.number} is merged, but Linear could not be updated (${err instanceof Error ? err.message : String(err)}); close ${c.ticket.id} by hand: Done, agent labels removed, pull request linked`);
3467
+ }
3468
+ return after(ctx, c, merged, lines);
3469
+ };
3470
+ if (input.noLock) {
3471
+ early.push(`merged without the merge lock (--no-lock): make sure no other coordinator merges in ${slug} now`);
3472
+ return run(async () => true);
3473
+ }
3474
+ const { db, warning } = await ctx.turso();
3475
+ if (!db && ctx.tursoConfigured)
3476
+ throw new Refusal(`the merge lock needs Turso, which is unavailable (${warning ?? "no answer"}); nothing was merged. Fix Turso, or pass --no-lock if you are sure no other coordinator merges in ${slug} now`);
3477
+ if (!db) {
3478
+ early.push(`${warning ?? "Turso is not configured"}; the merge lock was not taken, so make sure no other coordinator merges in ${slug} now`);
3479
+ return run(async () => true);
3480
+ }
3481
+ return withLease(db, {
3482
+ project: slug,
3483
+ name: MERGE_LEASE,
3484
+ holder: ctx.holder,
3485
+ ttlMs: MERGE_LEASE_TTL_MS,
3486
+ now: ctx.now,
3487
+ sleep: ctx.sleep,
3488
+ onWait: (held) => say(ctx, `Waiting for the merge lock held by ${held?.holder ?? "another coordinator"} (until ${held?.expiresAt ?? "?"})…`)
3489
+ }, run);
3490
+ }
3491
+ async function after(ctx, c, merged, lines) {
3492
+ const { config } = ctx;
3493
+ const slug = config.project.slug;
3494
+ const at = ctx.now();
3495
+ const live$ = await live(ctx, c.warnings, "record the merge", async (db) => {
3496
+ await ensureProject(db, projectOf(config), at);
3497
+ const handle = await getRuntimeHandle(db, slug, c.ticket.id);
3498
+ await recordEvent(db, {
3499
+ project: slug,
3500
+ ticket: c.ticket.id,
3501
+ kind: "merge",
3502
+ phase: "merged",
3503
+ message: `PR #${merged.number} merged as ${merged.mergeCommit ?? "unknown"}`,
3504
+ prUrl: merged.url,
3505
+ headSha: merged.headSha,
3506
+ at
3507
+ });
3508
+ const resolved = await resolveInboxItems(db, {
3509
+ project: slug,
3510
+ ticket: c.ticket.id,
3511
+ kind: "hand-back",
3512
+ resolution: `merged as ${merged.mergeCommit ?? "unknown"}`,
3513
+ at
3514
+ });
3515
+ await releaseRuntimeHandle(db, slug, c.ticket.id, at);
3516
+ return { handle, resolved, open: await openRuntimeHandles(db, slug) };
3004
3517
  });
3518
+ if (live$?.resolved)
3519
+ lines.push(`Hand-back resolved in the coordinator's inbox.`);
3520
+ let workers = [];
3521
+ try {
3522
+ const handles = new Map((live$?.open ?? []).map((h) => [h.ticket, h]));
3523
+ workers = (await ctx.inFlight()).filter((t) => t.id !== c.ticket.id).map((t) => ({
3524
+ ticket: t.id,
3525
+ title: t.title,
3526
+ phase: t.phase,
3527
+ runtime: t.runtime ?? handles.get(t.id)?.runtime ?? null,
3528
+ handle: handles.get(t.id)?.handle ?? null
3529
+ }));
3530
+ } catch (err) {
3531
+ c.warnings.push(`could not list the workers in flight (${err instanceof Error ? err.message : String(err)}); run armada status`);
3532
+ }
3533
+ const claim = activeClaimComments(c.ticket.comments)[0]?.claim;
3534
+ const runtime = live$?.handle?.runtime ?? c.ticket.agentRuntime ?? claim?.runtime ?? null;
3535
+ const archive = { runtime, handle: live$?.handle?.handle ?? claim?.session ?? null, guide: runtimeGuide(runtime) };
3536
+ return outcome(c, true, merged, lines, workers, archive);
3005
3537
  }
3006
- async function listProjects(db) {
3007
- const rs = await db.execute("SELECT slug, name, repository, program_root, created_at, updated_at FROM projects ORDER BY slug");
3008
- return rs.rows.map((r) => ({
3009
- slug: String(r.slug),
3010
- name: String(r.name),
3011
- repository: String(r.repository),
3012
- programRoot: String(r.program_root),
3013
- createdAt: String(r.created_at),
3014
- updatedAt: String(r.updated_at)
3015
- }));
3538
+ function outcome(c, merged, pr, lines, workers, archive) {
3539
+ const p = pr ?? c.pull;
3540
+ return {
3541
+ merged,
3542
+ pr: {
3543
+ number: p.number,
3544
+ url: p.url,
3545
+ title: p.title,
3546
+ base: p.baseRef,
3547
+ headSha: p.headSha,
3548
+ mergeCommit: pr?.mergeCommit ?? null
3549
+ },
3550
+ ticket: { id: c.ticket.id, url: c.ticket.url },
3551
+ lines,
3552
+ hints: c.hints,
3553
+ workers,
3554
+ archive,
3555
+ warnings: c.warnings
3556
+ };
3016
3557
  }
3017
- async function recordEvent(db, e) {
3018
- await db.execute({
3019
- sql: `INSERT INTO events (project, ticket, kind, phase, message, runtime, handle, pr_url, head_sha, created_at)
3020
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
3021
- args: [
3022
- e.project,
3023
- e.ticket,
3024
- e.kind,
3025
- e.phase ?? null,
3026
- e.message ?? null,
3027
- e.runtime ?? null,
3028
- e.handle ?? null,
3029
- e.prUrl ?? null,
3030
- e.headSha ?? null,
3031
- e.at.toISOString()
3558
+ // ../core/src/skills.ts
3559
+ import { createHash } from "node:crypto";
3560
+
3561
+ // ../../skills/armada-coordinator/MERGE.md
3562
+ var MERGE_default = "# Merging a pull request\n\nRun `armada merge <pr>` (add `--dry-run` to see the checklist only). It checks everything below, takes the project's merge lock, merges pinned to the handed-back SHA, confirms the merge on GitHub and closes the ticket. Its output lists the workers in flight to tell and the worker session to archive. When a refusal names a rule, fix the cause (usually: ask the worker to rebase and report again) rather than merging by hand. When you must merge by hand, follow the same steps.\n\n## Before\n\n1. The worker has handed back: `Agent phase` is `ready-to-merge` and you have the full 40-character head SHA it reported.\n2. `gh pr view <n> --json headRefOid,mergeStateStatus,isDraft,title` shows that SHA, `CLEAN`, not a draft, and a Commitizen title.\n3. `gh pr checks <n>` shows every required check passing.\n4. The head contains the current default branch: `git merge-base --is-ancestor origin/<default> <sha>`. If not, ask the worker to rebase.\n5. Semantic check: search the default branch for callers of anything the pull request deletes or renames.\n\n## Merge\n\n```sh\ngh pr merge <n> --squash --match-head-commit <full-sha>\n```\n\n- One merge at a time: `armada merge` holds the project's merge lock. If it refuses because Turso is down, use `--no-lock` only when you are sure no other coordinator merges in the project.\n- Leave out `--delete-branch`: it deletes local worktrees that have the branch checked out, including other agents'. Delete the branch once its worktree is gone.\n- If GitHub answers with a 5xx, check `gh pr view <n> --json state` before retrying.\n\n## After\n\n1. The ticket is Done, its `Agent phase` and `Agent runtime` labels removed, the pull request linked.\n2. Tell every in-flight worker what the merge changes for them: a shared file, a migration, a new check, code they must now reuse or delete.\n3. Archive the merged worker's workspace with the \"Stop and archive\" section of its runtime guide.\n4. Launch the tickets this merge unblocked.\n";
3563
+
3564
+ // ../../skills/armada-coordinator/SKILL.md
3565
+ var SKILL_default = `---
3566
+ name: armada-coordinator
3567
+ description: Coordinating an Armada fleet of coding agents on one project. Use when designated coordinator, or asked to launch workers on ready tickets, answer their questions, merge their green pull requests, or resume a fleet in a new local or cloud session. Reads the fleet with armada status and armada inbox and drives workers through the runtime guide skill.
3568
+ ---
3569
+
3570
+ The coordinator turns the owner's intent into merged pull requests. Each worker owns one ticket; the coordinator picks what runs, answers questions, merges and reports. There is one coordinator per project. \`armada.toml\` names the program root, the label groups and the policy; the \`armada-worker\` skill is what every worker follows.
3571
+
3572
+ **Standing authority.** Unless the owner said otherwise, they delegate reversible technical decisions, plan approval and merging to you: act, then report. Escalate only product decisions, irreversible or outward-facing actions, and anything that spends money.
3573
+
3574
+ **Armada never drives a runtime.** Launching, messaging, checking and stopping a worker go through the runtime guide skill for the worker's runtime (for example \`armada-runtime-conductor\`). Armada records what happened.
3575
+
3576
+ ## Loop
3577
+
3578
+ 1. **Read the fleet** with \`armada status\` and \`armada inbox\`, never from memory. Done when you can name every ticket in flight and its phase, every ready ticket, every pull request waiting, every silent worker and every pending question or request.
3579
+ 2. **Answer what waits for you first.** For each question: decide, deliver the answer in the worker's session with the runtime guide's *message* section, then \`armada answer <item> --message "<decision and reason>"\`. Decide reversible choices yourself and prefer the option that keeps behaviour observable. When two workers need the same shared resource (a migration slot, a generated file, a version number), set the rule once and tell both.
3580
+ 3. **Check silent workers** with the runtime guide's *status* section. A worker that is still working gets a nudge to report; a worker that died is relaunched or its ticket released.
3581
+ 4. **Launch ready tickets** that do not collide with work in flight: \`armada brief <ticket>\` gives the launch prompt and the environment the runtime must pass; launch with the runtime guide's *launch* section, then record the handle with \`armada claim\` if the worker did not. Add to the brief what only you know: merged blockers and their hand-back notes, decisions already made, and which parallel workers touch neighbouring code. Done when every launched ticket is In Progress with a claim.
3582
+ 5. **Merge handed-back pull requests** one at a time with \`armada merge <pr>\`, following [MERGE.md](MERGE.md). Done when the pull request is merged, the ticket is Done with its agent labels removed, and every in-flight worker affected by what landed has been told.
3583
+ 6. **Turn findings into tickets.** A gap a worker reports or a bug you see becomes a ticket under the right spec, with blocked-by relations, and is launched when ready. No finding lives only in a transcript.
3584
+ 7. **Report to the owner** in their language (\`tracker.language\` in \`armada.toml\`, or the owner's personal setting): what merged, what runs, what you decided for them, and the one thing they must do, with its exact place (a URL, a setting). Outcomes and numbers, no process narration.
3585
+
3586
+ Repeat from step 1; \`armada inbox --wait\` blocks until something needs you.
3587
+
3588
+ ## Rules of thumb
3589
+
3590
+ - Merge only after the worker's hand-back; a green pull request can still get one more rebased push.
3591
+ - Parallel workers in one area collide: stagger them, or give each a disjoint area and tell them the boundary.
3592
+ - Everything that must survive your session goes to the tracker or the repository. The next coordinator may be a fresh cloud session with none of your context: it resumes from \`armada status\` and \`armada inbox\`.
3593
+ - When a command named here is missing from your Armada version (\`armada --help\`), do the step by hand with the same protocol and say so in your report.
3594
+ `;
3595
+
3596
+ // ../../skills/armada-runtime-conductor/SKILL.md
3597
+ var SKILL_default2 = "---\nname: armada-runtime-conductor\ndescription: Runtime guide for running Armada workers on Conductor. Use when an Armada coordinator must launch a worker, send it a message, check whether it is alive, or stop and archive it on Conductor. Four fixed sections, each with the conductor command and how to read its output.\n---\n\nArmada never calls a runtime itself. This guide tells the coordinator how to do the four runtime actions with the `conductor` command line tool, and what to record in Armada afterwards. Check the exact flags with `conductor --help` and `conductor <command> --help`: this first version gives the commands to use, and a later Armada release completes the options and sample outputs.\n\n## Launch\n\n```sh\nconductor workspace create --repo <owner/name> --branch <ticket branch>\n```\n\nPass the prompt from `armada brief <ticket>` as the first message, and the environment variables it lists. Read the workspace id and the session id from the output; they form the handle `<workspace>/<session>`. Record it with `armada claim <ticket> --runtime conductor --handle <workspace>/<session>` unless the worker claims it itself.\n\n## Message\n\n```sh\nconductor message create --workspace <workspace> --session <session> --message \"<text>\"\n```\n\nUse it to deliver an answer, an approval or a heads-up that the default branch moved. A zero exit code means Conductor accepted the message; it does not mean the worker read it. After delivering an answer, record it with `armada answer`.\n\n## Status\n\n```sh\nconductor session status --workspace <workspace> --session <session>\n```\n\nTells whether the session is running, idle or ended. A silent worker whose session is running is busy: nudge it to report. An idle or ended session with the ticket not handed back needs a message or a relaunch.\n\n## Stop and archive\n\n```sh\nconductor workspace archive --workspace <workspace>\n```\n\nArchive a worker's workspace after its pull request is merged, or when its ticket is released. Archiving stops the session and frees the workspace; the branch and the pull request stay on GitHub.\n";
3598
+
3599
+ // ../../skills/armada-worker/SKILL.md
3600
+ var SKILL_default3 = `---
3601
+ name: armada-worker
3602
+ description: Working one ticket as an Armada worker agent. Use when you were launched on a ticket by an Armada coordinator, or asked to claim, plan, implement and ship one ticket of a project that has an armada.toml. Covers the claim, the phase reports every 15 minutes, questions to the coordinator, the green pull request and the hand-back. A worker never merges.
3603
+ ---
3604
+
3605
+ You are a worker. You own exactly one ticket, named in your launch brief. You turn it into one green pull request and hand it back to the coordinator, who merges. \`armada.toml\` at the repository root names the tracker program, the label groups and the policy; \`AGENTS.md\` (or \`CLAUDE.md\`) holds the repository's own rules, and they win over this skill where they are stricter.
3606
+
3607
+ ## Rules
3608
+
3609
+ - **Never merge**, never enable auto-merge, never approve your own plan. The coordinator merges.
3610
+ - **Report at least every 15 minutes** of work with \`armada report <phase> --message "<what you are doing>"\`. The same phase is allowed: it is your heartbeat. A worker silent for longer than \`policy.silence_minutes\` shows as silent, and the coordinator comes to check on you.
3611
+ - **Ask instead of guessing** when a choice changes the ticket's outcome: \`armada ask "<question, the options, your recommendation>"\`. Your phase becomes \`blocked\` until the coordinator answers in your session. Decide reversible technical choices yourself and record each one, with its reason, on the ticket and in the pull request.
3612
+ - **The ticket is the source of truth.** Read it, its parent spec and the hand-back comments of its merged blockers in full before planning.
3613
+ - Work only in your own branch and worktree. Never touch another agent's checkout, and stop only the processes you started.
3614
+ - Never print, commit or log a secret.
3615
+
3616
+ ## Steps
3617
+
3618
+ 1. **Claim.** \`armada claim <ticket> --runtime <runtime> --handle <workspace>/<session>\`. It assigns the ticket, moves it to In Progress, sets \`Agent phase = planning\` and your \`Agent runtime\`, and posts the \`Agent claim\` comment. If it refuses because another claim exists, stop: the older claim wins.
3619
+ 2. **Branch.** Use the branch named after the ticket (the tracker suggests one, for example \`feature/abc-12-short-title\`), created from the latest default branch.
3620
+ 3. **Plan.** Write the plan: what changes, how it is tested, and the checks a person could observe when it is done. If your brief says plans are pre-approved, post it with \`armada report implementing --message "<plan>"\` and go on. Otherwise post it with \`armada report awaiting-approval --message "<plan>"\`, push your branch, and wait for the coordinator's answer in your session.
3621
+ 4. **Implement** test-first. A material change to the approved plan needs a new approval.
3622
+ 5. **Ship.** \`armada report shipping --pr <number>\`. Use the \`ship-pr-dev\` skill when the repository has it; otherwise run the repository's local checks, open the pull request with a Commitizen title (\`feat(scope): …\`), link it on the ticket, and fix CI until every required check is green.
3623
+ 6. **Rebase** on the latest default branch right before hand-back, and get CI green on that final head.
3624
+ 7. **Hand back.** \`armada report ready-to-merge --pr <number> --sha <full 40-character head SHA>\`. Armada refuses a short SHA, a SHA that is not the pull request head, or a red check. Then report to the coordinator: pull request URL, full SHA, CI state, the decisions you made, and what the next tickets need to know.
3625
+
3626
+ If you stop without finishing, run \`armada release --reason "<why>"\` so the ticket is free again.
3627
+
3628
+ ## When a command is missing
3629
+
3630
+ This skill is versioned with Armada; an older CLI may lack a command (\`armada --help\` lists them). Do the same step by hand in the tracker, keeping the protocol: exactly one label from the phase group (\`planning\`, \`awaiting-approval\`, \`implementing\`, \`shipping\`, \`blocked\`, \`ready-to-merge\`) and one from the runtime group; a first comment \`Agent claim — runtime: <runtime> · session: <id> · branch: <branch> · started: <ISO date>\`; and every comment starting with \`Agent status: <phase> — <one-line summary>\`.
3631
+ `;
3632
+
3633
+ // ../core/src/skills.ts
3634
+ var SKILLS_SOURCE = "The-Vibe-Company/armada";
3635
+ var BUNDLED_SKILLS = [
3636
+ {
3637
+ name: "armada-coordinator",
3638
+ files: [
3639
+ { path: "MERGE.md", content: MERGE_default },
3640
+ { path: "SKILL.md", content: SKILL_default }
3032
3641
  ]
3033
- });
3034
- }
3035
- async function lastEventTimes(db, project) {
3036
- const rs = await db.execute({
3037
- sql: "SELECT ticket, max(created_at) AS at FROM events WHERE project = ? GROUP BY ticket",
3038
- args: [project]
3039
- });
3040
- return Object.fromEntries(rs.rows.map((r) => [String(r.ticket), String(r.at)]));
3041
- }
3042
- async function saveRuntimeHandle(db, h) {
3043
- await db.execute({
3044
- sql: `INSERT INTO runtime_handles (project, ticket, runtime, handle, branch, claimed_at, released_at)
3045
- VALUES (?, ?, ?, ?, ?, ?, NULL)
3046
- ON CONFLICT (project, ticket) DO UPDATE SET
3047
- claimed_at = CASE WHEN handle = excluded.handle AND released_at IS NULL
3048
- THEN claimed_at ELSE excluded.claimed_at END,
3049
- runtime = excluded.runtime, handle = excluded.handle, branch = excluded.branch,
3050
- released_at = NULL`,
3051
- args: [h.project, h.ticket, h.runtime, h.handle, h.branch, h.at.toISOString()]
3052
- });
3053
- }
3054
- async function releaseRuntimeHandle(db, project, ticket, at) {
3055
- await db.execute({
3056
- sql: "UPDATE runtime_handles SET released_at = ? WHERE project = ? AND ticket = ? AND released_at IS NULL",
3057
- args: [at.toISOString(), project, ticket]
3058
- });
3059
- }
3060
- async function addInboxItem(db, item) {
3061
- const rs = await db.execute({
3062
- sql: `INSERT INTO inbox_items (project, ticket, kind, recipient, author, body, created_at)
3063
- VALUES (?, ?, ?, ?, ?, ?, ?)`,
3064
- args: [item.project, item.ticket, item.kind, item.recipient, item.author, item.body, item.at.toISOString()]
3065
- });
3066
- return Number(rs.lastInsertRowid);
3067
- }
3068
- async function putHandBack(db, item) {
3069
- const updated = await db.execute({
3070
- sql: `UPDATE inbox_items SET body = ?, author = ?, created_at = ?
3071
- WHERE project = ? AND ticket = ? AND kind = 'hand-back' AND resolved_at IS NULL`,
3072
- args: [item.body, item.author, item.at.toISOString(), item.project, item.ticket]
3073
- });
3074
- if (!updated.rowsAffected)
3075
- await addInboxItem(db, { ...item, kind: "hand-back", recipient: "coordinator" });
3076
- }
3077
- async function openInboxItems(db, q) {
3078
- const rs = await db.execute({
3079
- sql: `SELECT id, project, ticket, kind, recipient, author, body, created_at FROM inbox_items
3080
- WHERE project = ? AND recipient = ? AND resolved_at IS NULL ${q.ticket ? "AND ticket = ?" : ""}
3081
- ORDER BY created_at, id`,
3082
- args: q.ticket ? [q.project, q.recipient, q.ticket] : [q.project, q.recipient]
3083
- });
3084
- return rs.rows.map((r) => ({
3085
- id: Number(r.id),
3086
- project: String(r.project),
3087
- ticket: r.ticket === null ? null : String(r.ticket),
3088
- kind: String(r.kind),
3089
- recipient: String(r.recipient),
3090
- author: r.author === null ? null : String(r.author),
3091
- body: String(r.body),
3092
- createdAt: String(r.created_at)
3093
- }));
3642
+ },
3643
+ { name: "armada-runtime-conductor", files: [{ path: "SKILL.md", content: SKILL_default2 }] },
3644
+ { name: "armada-worker", files: [{ path: "SKILL.md", content: SKILL_default3 }] }
3645
+ ];
3646
+ function skillFolderHash(files) {
3647
+ const hash = createHash("sha256");
3648
+ for (const f of [...files].sort((a, b) => a.path.localeCompare(b.path))) {
3649
+ hash.update(f.path);
3650
+ hash.update(f.content);
3651
+ }
3652
+ return hash.digest("hex");
3094
3653
  }
3095
- // ../core/src/worker.ts
3096
- class Refusal extends Error {
3097
- name = "Refusal";
3654
+
3655
+ // ../core/src/setup.ts
3656
+ var AGENTS_SKILLS_DIR = ".agents/skills";
3657
+ var CLAUDE_SKILLS_DIR = ".claude/skills";
3658
+ var SKILLS_LOCK_FILE = "skills-lock.json";
3659
+ var CONDUCTOR_SETTINGS = ".conductor/settings.toml";
3660
+ var GITIGNORE = ".gitignore";
3661
+ var SHIP_ARTIFACTS = "plans/ship-pr-dev/";
3662
+ var ok = (id, message) => ({ id, level: "ok", message, fix: null });
3663
+ var bad = (id, level, message, fix) => ({
3664
+ id,
3665
+ level,
3666
+ message,
3667
+ fix
3668
+ });
3669
+ var skillDir = (name) => `${AGENTS_SKILLS_DIR}/${name}`;
3670
+ var linkPath = (name) => `${CLAUDE_SKILLS_DIR}/${name}`;
3671
+ var skillLinkTarget = (name) => `../../${AGENTS_SKILLS_DIR}/${name}`;
3672
+ var bundledHash = (s) => skillFolderHash(s.files);
3673
+ var WHOLE_DIR_LINKS = new Set(["../.agents/skills", "../.agents/skills/"]);
3674
+ var linksWholeDir = async (view) => WHOLE_DIR_LINKS.has(await view.readLink(CLAUDE_SKILLS_DIR) ?? "");
3675
+
3676
+ class SetupError extends Error {
3677
+ name = "SetupError";
3098
3678
  }
3099
- var TURSO_TIMEOUT_MS = 1e4;
3100
- async function live(ctx, warnings, what, step) {
3101
- const { db, warning } = await ctx.turso();
3102
- if (!db) {
3103
- if (warning)
3104
- warnings.push(warning);
3679
+ function parseSkillsLock(text) {
3680
+ if (text === null)
3105
3681
  return null;
3682
+ let raw;
3683
+ try {
3684
+ raw = JSON.parse(text);
3685
+ } catch {
3686
+ throw new SetupError(`${SKILLS_LOCK_FILE} is not valid JSON`);
3106
3687
  }
3107
- let timer;
3688
+ const lock = raw;
3689
+ if (typeof lock?.version !== "number" || typeof lock.skills !== "object" || lock.skills === null)
3690
+ throw new SetupError(`${SKILLS_LOCK_FILE} has no "version" number and "skills" object`);
3691
+ return lock;
3692
+ }
3693
+ function conductorSetup(text) {
3694
+ let raw;
3108
3695
  try {
3109
- return await Promise.race([
3110
- step(db),
3111
- new Promise((_, reject) => {
3112
- timer = setTimeout(() => reject(new Error(`no answer within ${TURSO_TIMEOUT_MS / 1000} s`)), TURSO_TIMEOUT_MS);
3113
- })
3114
- ]);
3696
+ raw = parse(text);
3115
3697
  } catch (err) {
3116
- warnings.push(`Turso: could not ${what} (${redact(err)}); Linear is up to date`);
3117
- return null;
3118
- } finally {
3119
- clearTimeout(timer);
3698
+ const where = err instanceof TomlError ? ` (line ${err.line}, column ${err.column})` : "";
3699
+ throw new SetupError(`${CONDUCTOR_SETTINGS} is not valid TOML${where}`);
3120
3700
  }
3701
+ const scripts = raw.scripts;
3702
+ const setup = scripts?.setup;
3703
+ return typeof setup === "string" ? setup.trim() : "";
3121
3704
  }
3122
- var project = (config) => ({
3123
- slug: config.project.slug,
3124
- name: config.project.name,
3125
- repository: config.github.repository,
3126
- programRoot: config.tracker.programRoot
3127
- });
3128
- async function readOpenTicket(ctx, id) {
3129
- const ticket = await ctx.linear.readTicket(id);
3130
- if (!ticket)
3131
- throw new Refusal(`ticket ${id} not found in Linear`);
3132
- if (ticket.statusType === "completed" || ticket.statusType === "canceled")
3133
- throw new Refusal(`${ticket.id} is ${ticket.statusType}; there is nothing to work on`);
3134
- return ticket;
3135
- }
3136
- function activeClaimComments(comments) {
3137
- const asc = [...comments].sort((a, b) => a.createdAt.localeCompare(b.createdAt) || a.id.localeCompare(b.id));
3138
- let active = [];
3139
- for (const c of asc) {
3140
- if (c.status?.phase === "released")
3141
- active = [];
3142
- if (c.claim)
3143
- active.push(c);
3705
+ var IGNORES_SHIP = new Set(["plans/ship-pr-dev/", "plans/ship-pr-dev", "plans/", "plans", "plans/*"]);
3706
+ var ignoresShipArtifacts = (gitignore) => (gitignore ?? "").split(/\r?\n/).some((l) => IGNORES_SHIP.has(l.trim().replace(/^\//, "")));
3707
+ async function checkRepository(view, armadaVersion) {
3708
+ const checks = [];
3709
+ const configText = await view.readFile(CONFIG_FILE);
3710
+ if (configText === null)
3711
+ checks.push(bad("config", "error", `${CONFIG_FILE} is missing`, "run `armada init --program-root <ISSUE-ID>` to open a pull request that adds it"));
3712
+ else
3713
+ try {
3714
+ const config = parseConfig(configText, CONFIG_FILE);
3715
+ checks.push(ok("config", `${CONFIG_FILE} is valid (project ${config.project.slug})`));
3716
+ } catch (err) {
3717
+ if (!(err instanceof ConfigError))
3718
+ throw err;
3719
+ checks.push(bad("config", "error", err.message, `fix the keys listed above in ${CONFIG_FILE}`));
3720
+ }
3721
+ let lock = null;
3722
+ let lockError = null;
3723
+ try {
3724
+ lock = parseSkillsLock(await view.readFile(SKILLS_LOCK_FILE));
3725
+ } catch (err) {
3726
+ if (!(err instanceof SetupError))
3727
+ throw err;
3728
+ lockError = err.message;
3144
3729
  }
3145
- return active;
3146
- }
3147
- function findLabel(labels, name, group) {
3148
- const found = labels.find((l) => sameName(l.name, name));
3149
- if (found)
3150
- return found;
3151
- const names = labels.map((l) => l.name).join(", ") || "none";
3152
- throw new Refusal(`no "${name}" label in the "${group}" label group (available: ${names})`);
3153
- }
3154
- var others = (ticket, group, keep) => ticket.labels.filter((l) => l.group === group && l.id !== keep).map((l) => l.id);
3155
- var firstState = (states, ...types) => {
3156
- for (const type of types) {
3157
- const s = states.find((x) => x.type === type);
3158
- if (s)
3159
- return s;
3730
+ if (lockError)
3731
+ checks.push(bad("skills-lock", "error", lockError, `repair or delete ${SKILLS_LOCK_FILE}`));
3732
+ const wholeDir = await linksWholeDir(view);
3733
+ for (const skill of BUNDLED_SKILLS) {
3734
+ const folder = await view.readFolder(skillDir(skill.name));
3735
+ const installed = folder?.some((f) => f.path === "SKILL.md") ? skillFolderHash(folder) : null;
3736
+ const id = `skill:${skill.name}`;
3737
+ if (installed === null) {
3738
+ checks.push(bad(id, "error", `skill ${skill.name} is missing from ${AGENTS_SKILLS_DIR}`, "run `armada init`"));
3739
+ continue;
3740
+ }
3741
+ if (installed !== bundledHash(skill))
3742
+ checks.push(bad(id, "warning", `skill ${skill.name} differs from the version in Armada ${armadaVersion}`, "run `armada init` to open a pull request that updates it"));
3743
+ else
3744
+ checks.push(ok(id, `skill ${skill.name} is up to date`));
3745
+ const target = await view.readLink(linkPath(skill.name));
3746
+ const linkId = `skill-link:${skill.name}`;
3747
+ if (wholeDir)
3748
+ checks.push(ok(linkId, `${CLAUDE_SKILLS_DIR} links to ${AGENTS_SKILLS_DIR}`));
3749
+ else if (target === skillLinkTarget(skill.name))
3750
+ checks.push(ok(linkId, `${linkPath(skill.name)} links to ${skillDir(skill.name)}`));
3751
+ else
3752
+ checks.push(bad(linkId, "error", target === null ? `${linkPath(skill.name)} is not a link to ${skillDir(skill.name)}, so Claude Code does not see the skill` : `${linkPath(skill.name)} links to ${target} instead of ${skillLinkTarget(skill.name)}`, "run `armada init`"));
3753
+ if (lockError)
3754
+ continue;
3755
+ const entry = lock?.skills[skill.name];
3756
+ const lockId = `skill-lock:${skill.name}`;
3757
+ if (!entry)
3758
+ checks.push(bad(lockId, "error", `${SKILLS_LOCK_FILE} does not record ${skill.name}`, "run `armada init`"));
3759
+ else if (installed !== null && entry.computedHash !== installed)
3760
+ checks.push(bad(lockId, "warning", `${SKILLS_LOCK_FILE} records a different content for ${skill.name} than ${skillDir(skill.name)}`, "run `armada init`"));
3761
+ else
3762
+ checks.push(ok(lockId, `${SKILLS_LOCK_FILE} records ${skill.name}`));
3160
3763
  }
3764
+ const settings = await view.readFile(CONDUCTOR_SETTINGS);
3765
+ if (settings === null)
3766
+ checks.push(bad("conductor", "error", `${CONDUCTOR_SETTINGS} is missing`, "run `armada init` to add it with a setup script"));
3767
+ else
3768
+ try {
3769
+ checks.push(conductorSetup(settings) ? ok("conductor", `${CONDUCTOR_SETTINGS} has a setup script`) : bad("conductor", "error", `${CONDUCTOR_SETTINGS} has no [scripts] setup`, "run `armada init`, or add a setup command under [scripts]"));
3770
+ } catch (err) {
3771
+ if (!(err instanceof SetupError))
3772
+ throw err;
3773
+ checks.push(bad("conductor", "error", err.message, `fix ${CONDUCTOR_SETTINGS}`));
3774
+ }
3775
+ checks.push(ignoresShipArtifacts(await view.readFile(GITIGNORE)) ? ok("gitignore", `${GITIGNORE} ignores ${SHIP_ARTIFACTS}`) : bad("gitignore", "warning", `${GITIGNORE} does not ignore ${SHIP_ARTIFACTS}, so the ship-pr-dev skill refuses to start`, "run `armada init`"));
3776
+ return checks;
3777
+ }
3778
+ async function guessSetupCommand(view) {
3779
+ const has = async (p) => await view.readFile(p) !== null;
3780
+ if (await has("bun.lock") || await has("bun.lockb"))
3781
+ return "bun install --frozen-lockfile";
3782
+ if (await has("pnpm-lock.yaml"))
3783
+ return "pnpm install --frozen-lockfile";
3784
+ if (await has("yarn.lock"))
3785
+ return "yarn install --frozen-lockfile";
3786
+ if (await has("package-lock.json"))
3787
+ return "npm ci";
3161
3788
  return null;
3162
- };
3163
- function claimLine(o) {
3164
- return `Agent claim — runtime: ${o.runtime} · session: ${o.handle} · branch: ${o.branch ?? "unknown"} · started: ${o.started}`;
3165
3789
  }
3166
- async function claimTicket(ctx, input) {
3167
- const { config, linear } = ctx;
3168
- const groups = config.tracker.labels;
3169
- const ticket = await readOpenTicket(ctx, input.ticket);
3170
- const [phaseLabels, runtimeLabels] = await Promise.all([
3171
- linear.groupLabels(groups.phaseGroup, ticket.teamId),
3172
- linear.groupLabels(groups.runtimeGroup, ticket.teamId)
3173
- ]);
3174
- const planning = findLabel(phaseLabels, "planning", groups.phaseGroup);
3175
- const runtime = findLabel(runtimeLabels, input.runtime, groups.runtimeGroup);
3176
- const branch = input.branch ?? ticket.branchName;
3177
- const warnings = [...ticket.warnings];
3178
- const lines = [];
3179
- if (ticket.commentsTruncated)
3180
- throw new Refusal(`${ticket.id} has more comments than Armada reads, so an older claim may be hidden; claim it by hand`);
3181
- const viewer = await linear.viewer();
3182
- const inProgress = ticket.statusType === "started" ? null : firstState(ticket.states, "started");
3183
- const held = activeClaimComments(ticket.comments);
3184
- const holder = held[0]?.claim;
3185
- const resuming = !!holder && holder.session === input.handle;
3186
- if (!resuming) {
3187
- if (holder)
3188
- throw new Refusal(`${ticket.id} is already claimed by ${holder.runtime ?? "an unknown runtime"} · ${holder.session ?? "unknown session"} since ${holder.at}; release it first with \`armada release\``);
3189
- if (ticket.agentPhase)
3190
- throw new Refusal(`${ticket.id} already carries the agent phase "${ticket.agentPhase}"; release it first with \`armada release\``);
3191
- const started = ctx.now().toISOString();
3192
- const body = `Agent status: planning — claimed by ${runtime.name} (${input.handle})
3790
+ var SETUP_COMMENT = "# Commands a fresh workspace runs once: install dependencies, copy env files.";
3791
+ function conductorSettings(setup) {
3792
+ return `"$schema" = "https://conductor.build/schemas/settings.repo.schema.json"
3193
3793
 
3194
- ${claimLine({ runtime: runtime.name, handle: input.handle, branch, started })}`;
3195
- const mine = await linear.comment(ticket.uuid, body);
3196
- const after = await linear.readTicket(ticket.id);
3197
- const winner = after ? activeClaimComments(after.comments)[0] : undefined;
3198
- if (winner && winner.id !== mine.id) {
3199
- await linear.deleteComment(mine.id);
3200
- throw new Refusal(`${ticket.id} was claimed first by ${winner.claim?.runtime ?? "another worker"} · ${winner.claim?.session ?? "unknown session"}; your claim was withdrawn`);
3201
- }
3202
- lines.push(`Claimed ${ticket.id} for ${runtime.name} (${input.handle}).`);
3203
- } else {
3204
- lines.push(`${ticket.id} is already claimed by this session (${input.handle}); labels and state repaired.`);
3205
- }
3206
- if (ticket.statusType !== "started" && !inProgress)
3207
- warnings.push(`the team of ${ticket.id} has no started state; the ticket was not moved`);
3208
- const phaseLabel = resuming && ticket.agentPhase ? null : planning;
3209
- await linear.updateTicket(ticket.uuid, {
3210
- ...inProgress ? { stateId: inProgress.id } : {},
3211
- ...ticket.assigneeId !== viewer.id ? { assigneeId: viewer.id } : {},
3212
- addLabelIds: [phaseLabel, runtime].filter((l) => !!l && !ticket.labels.some((x) => x.id === l.id)).map((l) => l.id),
3213
- removeLabelIds: [
3214
- ...phaseLabel ? others(ticket, groups.phaseGroup, phaseLabel.id) : [],
3215
- ...others(ticket, groups.runtimeGroup, runtime.id)
3216
- ]
3217
- });
3218
- lines.push(`${inProgress ? `Moved to ${inProgress.name}` : "State unchanged"}, assigned to ${viewer.name}, labels ${phaseLabel?.name ?? ticket.agentPhase} and ${runtime.name}.`);
3219
- const at = ctx.now();
3220
- await live(ctx, warnings, "record the claim", async (db) => {
3221
- await ensureProject(db, project(config), at);
3222
- await saveRuntimeHandle(db, {
3223
- project: config.project.slug,
3224
- ticket: ticket.id,
3225
- runtime: runtime.name,
3226
- handle: input.handle,
3227
- branch,
3228
- at
3229
- });
3230
- await recordEvent(db, {
3231
- project: config.project.slug,
3232
- ticket: ticket.id,
3233
- kind: "claim",
3234
- phase: phaseLabel ? "planning" : ticket.agentPhase,
3235
- runtime: runtime.name,
3236
- handle: input.handle,
3237
- at
3238
- });
3239
- });
3240
- return { ticket: ticket.id, url: ticket.url, lines, warnings, inbox: null };
3794
+ [scripts]
3795
+ ${SETUP_COMMENT}
3796
+ setup = ${JSON.stringify(setup ?? "true")}
3797
+ `;
3241
3798
  }
3242
- function resolvePr(ticket, repository, pr) {
3243
- if (pr) {
3244
- const trimmed = pr.trim().replace(/^#/, "");
3245
- if (/^\d+$/.test(trimmed)) {
3246
- const url = `https://github.com/${repository}/pull/${trimmed}`;
3247
- return parsePullRequestUrl(url);
3248
- }
3249
- const parsed = parsePullRequestUrl(trimmed);
3250
- if (!parsed)
3251
- throw new Refusal(`--pr must be a pull request number or URL, got "${pr}"`);
3252
- return parsed;
3253
- }
3254
- const inRepo = ticket.prs.filter((p) => p.repo.toLowerCase() === repository.toLowerCase());
3255
- return [...inRepo].sort((a, b) => b.number - a.number)[0] ?? null;
3799
+ function withSetup(text, setup) {
3800
+ const command = setup ?? "true";
3801
+ const line = `${SETUP_COMMENT}
3802
+ setup = ${JSON.stringify(command)}`;
3803
+ const lines = text.split(`
3804
+ `);
3805
+ const at = lines.findIndex((l) => /^\s*\[scripts\]\s*(#.*)?$/.test(l));
3806
+ let edited;
3807
+ if (at >= 0) {
3808
+ lines.splice(at + 1, 0, line);
3809
+ edited = lines.join(`
3810
+ `);
3811
+ } else
3812
+ edited = `${text.replace(/\n*$/, `
3813
+ `)}
3814
+ [scripts]
3815
+ ${line}
3816
+ `;
3817
+ let result = "";
3818
+ try {
3819
+ result = conductorSetup(edited);
3820
+ } catch {}
3821
+ if (result !== command)
3822
+ throw new SetupError(`${CONDUCTOR_SETTINGS} has a [scripts] table Armada cannot add a setup command to safely; set \`setup\` under [scripts] by hand`);
3823
+ return edited;
3256
3824
  }
3257
- async function reportPhase(ctx, input) {
3258
- const { config, linear } = ctx;
3259
- const groups = config.tracker.labels;
3260
- const ticket = await readOpenTicket(ctx, input.ticket);
3261
- const problem = transitionProblem(ticket.agentPhase, input.phase);
3262
- if (problem)
3263
- throw new Refusal(`${ticket.id}: ${problem}`);
3264
- const warnings = [...ticket.warnings];
3265
- const message = input.message?.trim() ?? "";
3266
- let pr = resolvePr(ticket, config.github.repository, input.pr);
3267
- const sha = input.sha?.trim().toLowerCase() || null;
3268
- let summary;
3269
- let body;
3270
- if (input.phase === "ready-to-merge") {
3271
- const inRepo = !!pr && pr.repo.toLowerCase() === config.github.repository.toLowerCase();
3272
- if (inRepo && !ctx.readPull)
3273
- throw new Refusal("a hand-back needs GitHub to check the pull request head and CI; set GITHUB_TOKEN or run `gh auth login`");
3274
- if (pr && inRepo && ctx.readPull) {
3275
- const fresh = await ctx.readPull(pr.number);
3276
- if (!fresh)
3277
- throw new Refusal(`pull request #${pr.number} was not found in ${config.github.repository}`);
3278
- pr = fresh;
3825
+ function lockText(lock, armadaVersion) {
3826
+ const skills = { ...lock?.skills ?? {} };
3827
+ for (const s of BUNDLED_SKILLS)
3828
+ skills[s.name] = {
3829
+ source: SKILLS_SOURCE,
3830
+ sourceType: "github",
3831
+ skillPath: `skills/${s.name}/SKILL.md`,
3832
+ ...armadaVersion === "0.0.0" ? {} : { ref: `v${armadaVersion}` },
3833
+ computedHash: bundledHash(s)
3834
+ };
3835
+ const sorted = Object.fromEntries(Object.keys(skills).sort().map((k) => [k, skills[k]]));
3836
+ return `${JSON.stringify({ version: lock?.version ?? 1, skills: sorted }, null, 2)}
3837
+ `;
3838
+ }
3839
+ async function planSetup(view, opts) {
3840
+ const plan = { writes: [], removes: [], links: [], installed: [], updated: [] };
3841
+ if (opts.configText !== null && await view.readFile(CONFIG_FILE) === null)
3842
+ plan.writes.push({ path: CONFIG_FILE, content: opts.configText });
3843
+ const wholeDir = await linksWholeDir(view);
3844
+ for (const skill of BUNDLED_SKILLS) {
3845
+ const folder = await view.readFolder(skillDir(skill.name));
3846
+ const current = folder?.length ? skillFolderHash(folder) === bundledHash(skill) : false;
3847
+ if (!current) {
3848
+ ((folder?.length) ? plan.updated : plan.installed).push(skill.name);
3849
+ for (const f of skill.files)
3850
+ plan.writes.push({ path: `${skillDir(skill.name)}/${f.path}`, content: f.content });
3851
+ const keep = new Set(skill.files.map((f) => f.path));
3852
+ for (const f of folder ?? [])
3853
+ if (!keep.has(f.path))
3854
+ plan.removes.push(`${skillDir(skill.name)}/${f.path}`);
3279
3855
  }
3280
- const problems = handBackProblems({
3281
- pr,
3282
- repository: config.github.repository,
3283
- sha,
3284
- requiredChecks: config.gates.requiredChecks
3285
- });
3286
- if (problems.length)
3287
- throw new Refusal(`${ticket.id}: hand-back refused:
3288
- ${problems.map((p) => ` - ${p}`).join(`
3289
- `)}`);
3290
- summary = `PR #${pr?.number}, head ${sha}, CI green`;
3291
- body = message;
3292
- } else {
3293
- if (!message)
3294
- throw new Refusal("--message is required: say what you did or what you are doing");
3295
- const [first = "", ...rest] = message.split(`
3296
- `);
3297
- summary = first.trim();
3298
- body = rest.join(`
3299
- `).trim();
3300
- }
3301
- const target = ticket.agentPhase === input.phase ? null : findLabel(await linear.groupLabels(groups.phaseGroup, ticket.teamId), input.phase, groups.phaseGroup);
3302
- if (pr && input.pr && !ticket.prs.some((p) => p.url === pr?.url)) {
3303
- await linear.linkUrl(ticket.uuid, pr.url, pr.title || `Pull request #${pr.number}`);
3856
+ if (!wholeDir && await view.readLink(linkPath(skill.name)) !== skillLinkTarget(skill.name))
3857
+ plan.links.push({ path: linkPath(skill.name), target: skillLinkTarget(skill.name) });
3304
3858
  }
3305
- if (target) {
3306
- await linear.updateTicket(ticket.uuid, {
3307
- addLabelIds: [target.id],
3308
- removeLabelIds: others(ticket, groups.phaseGroup, target.id)
3859
+ const lockBefore = await view.readFile(SKILLS_LOCK_FILE);
3860
+ const lockAfter = lockText(parseSkillsLock(lockBefore), opts.armadaVersion);
3861
+ if (lockAfter !== lockBefore)
3862
+ plan.writes.push({ path: SKILLS_LOCK_FILE, content: lockAfter });
3863
+ const settings = await view.readFile(CONDUCTOR_SETTINGS);
3864
+ if (settings === null)
3865
+ plan.writes.push({ path: CONDUCTOR_SETTINGS, content: conductorSettings(await guessSetupCommand(view)) });
3866
+ else if (!conductorSetup(settings))
3867
+ plan.writes.push({ path: CONDUCTOR_SETTINGS, content: withSetup(settings, await guessSetupCommand(view)) });
3868
+ const gitignore = await view.readFile(GITIGNORE);
3869
+ if (!ignoresShipArtifacts(gitignore)) {
3870
+ const base = gitignore === null || gitignore === "" ? "" : `${gitignore.replace(/\n*$/, `
3871
+ `)}
3872
+ `;
3873
+ plan.writes.push({
3874
+ path: GITIGNORE,
3875
+ content: `${base}# Local agent run artifacts (ship-pr-dev)
3876
+ ${SHIP_ARTIFACTS}
3877
+ `
3309
3878
  });
3310
3879
  }
3311
- const statusLine = `Agent status: ${input.phase} — ${summary}`;
3312
- await linear.comment(ticket.uuid, body ? `${statusLine}
3313
-
3314
- ${body}` : statusLine);
3315
- const lines = [
3316
- ticket.agentPhase === input.phase ? `Status update posted on ${ticket.id} (${input.phase}).` : `${ticket.id}: ${ticket.agentPhase} → ${input.phase}.`
3317
- ];
3318
- const at = ctx.now();
3319
- const inbox = await live(ctx, warnings, "record the report", async (db) => {
3320
- await ensureProject(db, project(config), at);
3321
- await recordEvent(db, {
3322
- project: config.project.slug,
3323
- ticket: ticket.id,
3324
- kind: "report",
3325
- phase: input.phase,
3326
- message: summary,
3327
- prUrl: pr?.url ?? null,
3328
- headSha: sha,
3329
- at
3330
- });
3331
- if (input.phase === "ready-to-merge")
3332
- await putHandBack(db, {
3333
- project: config.project.slug,
3334
- ticket: ticket.id,
3335
- author: null,
3336
- body: statusLine,
3337
- at
3338
- });
3339
- return openInboxItems(db, { project: config.project.slug, recipient: "worker", ticket: ticket.id });
3880
+ return plan;
3881
+ }
3882
+ var planIsEmpty = (p) => !p.writes.length && !p.removes.length && !p.links.length;
3883
+ // ../core/src/status.ts
3884
+ var STATUS_SCHEMA_VERSION = 1;
3885
+ function buildStatus({
3886
+ config,
3887
+ program,
3888
+ forge,
3889
+ forgeError = null,
3890
+ lastEvents,
3891
+ extraWarnings = [],
3892
+ now
3893
+ }) {
3894
+ const issues = attachPullRequests(program, forge);
3895
+ const m = buildModel(issues, program.rootId);
3896
+ const lanes = inFlight(m, program.comments, {
3897
+ now: now.getTime(),
3898
+ silentAfterMinutes: config.policy.silentAfterMinutes,
3899
+ ...lastEvents ? { lastEvents } : {}
3340
3900
  });
3341
- return { ticket: ticket.id, url: ticket.url, lines, warnings, inbox };
3901
+ const phaseOf = new Map(lanes.map((l) => [l.issue.id, l.phase]));
3902
+ const prRef = (p) => ({
3903
+ number: p.number,
3904
+ url: p.url,
3905
+ title: p.title,
3906
+ draft: p.draft ?? null,
3907
+ ci: p.ci ?? null,
3908
+ mergeable: p.mergeable ?? null
3909
+ });
3910
+ return {
3911
+ schemaVersion: STATUS_SCHEMA_VERSION,
3912
+ generatedAt: now.toISOString(),
3913
+ project: { name: config.project.name, slug: config.project.slug, repository: config.github.repository },
3914
+ programRoot: { id: m.root.id, title: m.root.title, url: m.root.url },
3915
+ sources: {
3916
+ linear: { fetchedAt: program.fetchedAt },
3917
+ github: { fetchedAt: forge?.fetchedAt ?? null, error: forge ? null : forgeError ?? "not read" }
3918
+ },
3919
+ silentAfterMinutes: config.policy.silentAfterMinutes,
3920
+ inFlight: lanes.map((l) => ({
3921
+ id: l.issue.id,
3922
+ title: l.issue.title,
3923
+ url: l.issue.url,
3924
+ spec: l.spec,
3925
+ phase: l.phase,
3926
+ phaseSource: l.phaseSource,
3927
+ runtime: l.runtime,
3928
+ agent: l.agent,
3929
+ since: l.since,
3930
+ lastUpdate: l.lastUpdate,
3931
+ lastReport: l.lastReport,
3932
+ silent: l.flags.includes("silent"),
3933
+ statusLine: l.statusLine ? { summary: l.statusLine.summary, at: l.statusLine.at, url: l.statusLine.url } : null,
3934
+ pr: l.pr ? prRef(l.pr) : null,
3935
+ openBlockers: l.openBlockers,
3936
+ flags: l.flags
3937
+ })),
3938
+ frontier: frontier(m, config.tracker.readyLabel).map((c) => ({
3939
+ id: c.issue.id,
3940
+ title: c.issue.title,
3941
+ url: c.issue.url,
3942
+ spec: c.spec,
3943
+ readyForAgent: c.readyForAgent,
3944
+ onCriticalPath: c.onCriticalPath,
3945
+ unlocks: c.unlocksAll
3946
+ })),
3947
+ pullRequests: forge ? waitingPullRequests(m, forge.prs).map(({ pr, ticket }) => ({
3948
+ ...prRef(pr),
3949
+ headSha: pr.headSha ?? null,
3950
+ updatedAt: pr.updatedAt ?? null,
3951
+ failingChecks: (pr.checks ?? []).filter((c) => c.state === "failure").map((c) => c.name),
3952
+ ticket: ticket ? { id: ticket.id, phase: phaseOf.get(ticket.id) ?? ticket.agentPhase } : null
3953
+ })) : null,
3954
+ warnings: [...program.warnings, ...forge?.warnings ?? [], ...extraWarnings]
3955
+ };
3342
3956
  }
3343
- async function releaseTicket(ctx, input) {
3344
- const { config, linear } = ctx;
3345
- const groups = config.tracker.labels;
3346
- const ticket = await readOpenTicket(ctx, input.ticket);
3347
- if (!ticket.agentPhase && !ticket.agentRuntime && !activeClaimComments(ticket.comments).length)
3348
- throw new Refusal(`${ticket.id} is not claimed; there is nothing to release`);
3349
- const warnings = [...ticket.warnings];
3350
- const back = ticket.statusType === "started" ? firstState(ticket.states, "unstarted", "backlog") : null;
3351
- await linear.updateTicket(ticket.uuid, {
3352
- ...back ? { stateId: back.id } : {},
3353
- removeLabelIds: [...others(ticket, groups.phaseGroup, null), ...others(ticket, groups.runtimeGroup, null)]
3957
+ async function loadStatus(config, opts) {
3958
+ const now = opts.now ?? (() => new Date);
3959
+ const programP = fetchProgram({
3960
+ apiKey: opts.linearApiKey,
3961
+ rootId: config.tracker.programRoot,
3962
+ labels: config.tracker.labels,
3963
+ ...opts.fetch ? { fetch: opts.fetch } : {},
3964
+ now
3354
3965
  });
3355
- await linear.comment(ticket.uuid, `Agent status: released — ${input.reason.trim()}`);
3356
- const lines = [`Released ${ticket.id}${back ? `, moved back to ${back.name}` : ""}.`];
3357
- const at = ctx.now();
3358
- await live(ctx, warnings, "record the release", async (db) => {
3359
- await ensureProject(db, project(config), at);
3360
- await releaseRuntimeHandle(db, config.project.slug, ticket.id, at);
3361
- await recordEvent(db, {
3362
- project: config.project.slug,
3363
- ticket: ticket.id,
3364
- kind: "release",
3365
- message: input.reason.trim(),
3366
- at
3367
- });
3966
+ const forgeP = opts.githubToken ? fetchForge({
3967
+ token: opts.githubToken,
3968
+ repository: config.github.repository,
3969
+ ...opts.fetch ? { fetch: opts.fetch } : {},
3970
+ now
3971
+ }).then((forge2) => ({ forge: forge2, error: null }), (err) => ({ forge: null, error: err instanceof Error ? err.message : String(err) })) : Promise.resolve({ forge: null, error: "no GitHub token (set GITHUB_TOKEN or run gh auth login)" });
3972
+ const eventsP = opts.lastEvents ? opts.lastEvents().then((events2) => ({ events: events2 }), (err) => ({
3973
+ warning: `Turso could not be read (${err instanceof Error ? err.message : String(err)}); silence is measured from Linear only`
3974
+ })) : Promise.resolve({});
3975
+ const [program, { forge, error }, events] = await Promise.all([programP, forgeP, eventsP]);
3976
+ return buildStatus({
3977
+ config,
3978
+ program,
3979
+ forge,
3980
+ forgeError: error,
3981
+ ...events.events ? { lastEvents: events.events } : {},
3982
+ extraWarnings: events.warning ? [events.warning] : [],
3983
+ now: now()
3368
3984
  });
3369
- return { ticket: ticket.id, url: ticket.url, lines, warnings, inbox: null };
3370
3985
  }
3371
3986
  // package.json
3372
- var version = "0.1.2";
3987
+ var version = "0.1.3";
3373
3988
 
3374
3989
  // src/io.ts
3375
3990
  class UsageError extends Error {
@@ -3882,21 +4497,390 @@ async function init(io, opts) {
3882
4497
  }
3883
4498
  const db = await openTurso({ url: tursoUrl, token: credentials2.tursoToken });
3884
4499
  try {
3885
- const project2 = {
3886
- slug: config2.project.slug,
3887
- name: config2.project.name,
3888
- repository: config2.github.repository,
3889
- programRoot: config2.tracker.programRoot
4500
+ const project = {
4501
+ slug: config2.project.slug,
4502
+ name: config2.project.name,
4503
+ repository: config2.github.repository,
4504
+ programRoot: config2.tracker.programRoot
4505
+ };
4506
+ await upsertProject(db, project, io.now?.() ?? new Date);
4507
+ } finally {
4508
+ db.close();
4509
+ }
4510
+ log(`Registered project ${config2.project.slug}; armada status --all lists it.`);
4511
+ return 0;
4512
+ } finally {
4513
+ await exec("git", ["worktree", "remove", "--force", checkout], { cwd: root }).catch(() => null);
4514
+ await rm3(checkout, { recursive: true, force: true });
4515
+ }
4516
+ }
4517
+
4518
+ // src/merge.ts
4519
+ import { randomUUID } from "node:crypto";
4520
+ import { rm as rm4 } from "node:fs/promises";
4521
+ import { hostname, tmpdir as tmpdir2 } from "node:os";
4522
+ import { dirname as dirname2, join as join4 } from "node:path";
4523
+
4524
+ // src/worker.ts
4525
+ var TURSO_OPEN_TIMEOUT_MS = 1e4;
4526
+ async function openLive(credentials2) {
4527
+ if (!credentials2.tursoUrl)
4528
+ return { db: null, warning: "Turso is not configured (ARMADA_TURSO_URL); live activity is not recorded" };
4529
+ let timer;
4530
+ const opening = openTurso({ url: credentials2.tursoUrl, token: credentials2.tursoToken });
4531
+ try {
4532
+ const db = await Promise.race([
4533
+ opening,
4534
+ new Promise((_, reject) => {
4535
+ timer = setTimeout(() => reject(new Error(`no answer within ${TURSO_OPEN_TIMEOUT_MS / 1000} s`)), TURSO_OPEN_TIMEOUT_MS);
4536
+ })
4537
+ ]);
4538
+ return { db, warning: null };
4539
+ } catch (err) {
4540
+ opening.then((db) => db.close(), () => {});
4541
+ const reason = err instanceof Error ? err.message : String(err);
4542
+ return { db: null, warning: `Turso unavailable (${reason}); live activity is not recorded, Linear is` };
4543
+ } finally {
4544
+ clearTimeout(timer);
4545
+ }
4546
+ }
4547
+ function statusEvents(config2, credentials2) {
4548
+ if (!credentials2.tursoUrl)
4549
+ return;
4550
+ return async () => {
4551
+ const { db, warning } = await openLive(credentials2);
4552
+ if (!db)
4553
+ throw new Error(warning ?? "Turso unavailable");
4554
+ try {
4555
+ return await lastEventTimes(db, config2.project.slug);
4556
+ } finally {
4557
+ db.close();
4558
+ }
4559
+ };
4560
+ }
4561
+ function currentTicket(io, config2, explicit) {
4562
+ const fromEnv2 = io.env.ARMADA_TICKET?.trim();
4563
+ const id = explicit?.trim() || fromEnv2 || (() => {
4564
+ const branch = io.gitBranch?.();
4565
+ return branch ? ticketFromBranch(branch, config2.tracker.programRoot) : null;
4566
+ })();
4567
+ if (!id)
4568
+ throw new UsageError("which ticket? pass --ticket <id>, set ARMADA_TICKET, or run on the ticket's branch");
4569
+ return id.toUpperCase();
4570
+ }
4571
+ async function context(io, config2, credentials2) {
4572
+ if (!credentials2.linearApiKey)
4573
+ throw new UsageError(missingKeyMessage(LINEAR_KEY));
4574
+ const linearOpts = {
4575
+ apiKey: credentials2.linearApiKey,
4576
+ labels: config2.tracker.labels,
4577
+ ...io.fetch ? { fetch: io.fetch } : {}
4578
+ };
4579
+ const linear2 = io.linearWriter ? io.linearWriter(linearOpts) : createLinearWriter(linearOpts);
4580
+ let live2 = null;
4581
+ const token = credentials2.githubToken;
4582
+ const ctx = {
4583
+ config: config2,
4584
+ linear: linear2,
4585
+ turso: () => {
4586
+ live2 ??= openLive(credentials2);
4587
+ return live2;
4588
+ },
4589
+ readPull: token ? (number) => fetchPullRequest({
4590
+ token,
4591
+ repository: config2.github.repository,
4592
+ number,
4593
+ ...io.fetch ? { fetch: io.fetch } : {}
4594
+ }) : null,
4595
+ now: io.now ?? (() => new Date)
4596
+ };
4597
+ const close = async () => {
4598
+ const opened = await live2;
4599
+ opened?.db?.close();
4600
+ };
4601
+ return { ctx, close };
4602
+ }
4603
+ function print(io, outcome2, json) {
4604
+ if (json) {
4605
+ io.stdout(`${JSON.stringify(outcome2, null, 2)}
4606
+ `);
4607
+ return;
4608
+ }
4609
+ const out = [...outcome2.lines, outcome2.url];
4610
+ if (outcome2.inbox) {
4611
+ if (!outcome2.inbox.length)
4612
+ out.push("Inbox: nothing waiting for you.");
4613
+ else {
4614
+ out.push(`Inbox (${outcome2.inbox.length}) — read and act on these:`);
4615
+ for (const item of outcome2.inbox)
4616
+ out.push(` #${item.id} ${item.kind}${item.author ? ` from ${item.author}` : ""} · ${item.createdAt}`, ...item.body.split(`
4617
+ `).map((l) => ` ${l}`));
4618
+ }
4619
+ }
4620
+ io.stdout(`${out.join(`
4621
+ `)}
4622
+ `);
4623
+ for (const w of outcome2.warnings)
4624
+ io.stderr(`armada: warning: ${w}
4625
+ `);
4626
+ }
4627
+ async function withContext(io, config2, credentials2, json, act) {
4628
+ const { ctx, close } = await context(io, config2, credentials2);
4629
+ try {
4630
+ print(io, await act(ctx), json);
4631
+ return 0;
4632
+ } finally {
4633
+ await close();
4634
+ }
4635
+ }
4636
+ async function claim(io, config2, credentials2, a) {
4637
+ const [ticket, ...extra] = a.rest;
4638
+ if (!ticket)
4639
+ throw new UsageError("claim needs a ticket: armada claim <ticket> --runtime <name> --handle <id>");
4640
+ if (extra.length)
4641
+ throw new UsageError(`unexpected argument ${extra[0]}`);
4642
+ const runtime = a.options.runtime?.trim();
4643
+ const handle = a.options.handle?.trim();
4644
+ if (!runtime)
4645
+ throw new UsageError("--runtime is required, e.g. --runtime conductor");
4646
+ if (!handle)
4647
+ throw new UsageError("--handle is required: the runtime's id for this session, e.g. <workspace>/<session>");
4648
+ return withContext(io, config2, credentials2, a.json, (ctx) => claimTicket(ctx, {
4649
+ ticket: ticket.toUpperCase(),
4650
+ runtime,
4651
+ handle,
4652
+ ...a.options.branch ? { branch: a.options.branch } : {}
4653
+ }));
4654
+ }
4655
+ async function report(io, config2, credentials2, a) {
4656
+ const [phase, ...extra] = a.rest;
4657
+ if (!phase || !isLabelPhase(phase))
4658
+ throw new UsageError(`report needs a phase: ${LABEL_PHASES.join(", ")}${phase ? ` (got "${phase}")` : ""}`);
4659
+ if (extra.length)
4660
+ throw new UsageError(`unexpected argument ${extra[0]}`);
4661
+ if (a.options.message !== undefined && a.options["message-file"] !== undefined)
4662
+ throw new UsageError("pass --message or --message-file, not both");
4663
+ let message = a.options.message ?? null;
4664
+ const file = a.options["message-file"];
4665
+ if (file !== undefined) {
4666
+ message = file === "-" ? await io.readStdin?.() ?? null : await io.readFile(file);
4667
+ if (message === null)
4668
+ throw new UsageError(`cannot read the message from ${file}`);
4669
+ }
4670
+ if (!message?.trim() && phase !== "ready-to-merge")
4671
+ throw new UsageError("--message is required: what you did or what you are doing (first line = summary)");
4672
+ const ticket = currentTicket(io, config2, a.options.ticket);
4673
+ return withContext(io, config2, credentials2, a.json, (ctx) => reportPhase(ctx, {
4674
+ ticket,
4675
+ phase,
4676
+ message,
4677
+ pr: a.options.pr ?? null,
4678
+ sha: a.options.sha ?? null
4679
+ }));
4680
+ }
4681
+ async function release(io, config2, credentials2, a) {
4682
+ if (a.rest.length)
4683
+ throw new UsageError(`unexpected argument ${a.rest[0]}`);
4684
+ const reason = a.options.reason?.trim();
4685
+ if (!reason)
4686
+ throw new UsageError("--reason is required: why the ticket is given back");
4687
+ const ticket = currentTicket(io, config2, a.options.ticket);
4688
+ return withContext(io, config2, credentials2, a.json, (ctx) => releaseTicket(ctx, { ticket, reason }));
4689
+ }
4690
+
4691
+ // src/merge.ts
4692
+ var TRANSIENT = /\bHTTP 5\d\d\b|\b5\d\d (?:Bad Gateway|Service Unavailable|Gateway Time-?out|Internal Server Error)\b|Bad Gateway|Service Unavailable|Gateway Time-?out|ECONNRESET|ETIMEDOUT|connection reset|i\/o timeout|TLS handshake timeout/i;
4693
+ var tail = (text, lines = 30) => text.trimEnd().split(`
4694
+ `).slice(-lines).join(`
4695
+ `);
4696
+ function ghMerge(exec, cwd, repository) {
4697
+ return async (number, sha) => {
4698
+ const args = ["pr", "merge", String(number), "--repo", repository, "--squash", "--match-head-commit", sha];
4699
+ try {
4700
+ const r = await exec("gh", args, { cwd });
4701
+ const message = tail(`${r.stderr}
4702
+ ${r.stdout}`.trim(), 5) || `gh exited with ${r.code}`;
4703
+ return { ok: r.code === 0, message, transient: r.code !== 0 && TRANSIENT.test(message) };
4704
+ } catch (err) {
4705
+ return {
4706
+ ok: false,
4707
+ message: `cannot run gh: ${err instanceof Error ? err.message : String(err)}`,
4708
+ transient: false
3890
4709
  };
3891
- await upsertProject(db, project2, io.now?.() ?? new Date);
3892
- } finally {
3893
- db.close();
3894
4710
  }
3895
- log(`Registered project ${config2.project.slug}; armada status --all lists it.`);
4711
+ };
4712
+ }
4713
+ var escapeRe = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
4714
+ function gitRepo(exec, cwd) {
4715
+ const git = async (args, dir = cwd) => {
4716
+ const r = await exec("git", args, { cwd: dir });
4717
+ return r;
4718
+ };
4719
+ const must = async (args, dir = cwd) => {
4720
+ const r = await git(args, dir);
4721
+ if (r.code !== 0)
4722
+ throw new Error(`git ${args[0]} failed: ${tail(r.stderr || r.stdout, 5)}`);
4723
+ return r;
4724
+ };
4725
+ return {
4726
+ async grepWords({ branch, rev, words }) {
4727
+ await must(["fetch", "--quiet", "origin", branch]);
4728
+ const r = await git(["grep", "-I", "-n", "-w", "-F", ...words.flatMap((w) => ["-e", w]), rev, "--"]);
4729
+ if (r.code > 1)
4730
+ throw new Error(`git grep failed: ${tail(r.stderr, 5)}`);
4731
+ const uses = new Map;
4732
+ const tests = words.map((w) => [w, new RegExp(`(?<![\\w$])${escapeRe(w)}(?![\\w$])`)]);
4733
+ for (const line of r.stdout.split(`
4734
+ `)) {
4735
+ const m = line.match(new RegExp(`^${escapeRe(rev)}:(.+?):\\d+:(.*)$`));
4736
+ if (!m?.[1])
4737
+ continue;
4738
+ const [file, text = ""] = [m[1], m[2]];
4739
+ for (const [w, re] of tests) {
4740
+ if (!re.test(text))
4741
+ continue;
4742
+ const files = uses.get(w) ?? [];
4743
+ if (!files.includes(file))
4744
+ uses.set(w, [...files, file]);
4745
+ }
4746
+ }
4747
+ return uses;
4748
+ },
4749
+ async testMerge({ branch, base, head, number, commands }) {
4750
+ await must(["fetch", "--quiet", "origin", branch, `refs/pull/${number}/head`]);
4751
+ const dir = join4(tmpdir2(), `armada-merge-${number}-${randomUUID().slice(0, 8)}`);
4752
+ const remove = async () => {
4753
+ await git(["worktree", "remove", "--force", dir]);
4754
+ await git(["worktree", "prune"]);
4755
+ await rm4(dir, { recursive: true, force: true });
4756
+ };
4757
+ const added = await git(["worktree", "add", "--detach", dir, base]);
4758
+ if (added.code !== 0) {
4759
+ await remove();
4760
+ return { ok: false, step: "git worktree add", output: tail(added.stderr) };
4761
+ }
4762
+ try {
4763
+ const merged = await git([
4764
+ ...["-c", "user.name=Armada", "-c", "user.email=armada@localhost", "-c", "commit.gpgsign=false"],
4765
+ ...["merge", "--no-ff", "--no-edit", "--no-verify", head]
4766
+ ], dir);
4767
+ if (merged.code !== 0)
4768
+ return {
4769
+ ok: false,
4770
+ step: `git merge ${head.slice(0, 7)}`,
4771
+ output: tail(`${merged.stdout}
4772
+ ${merged.stderr}`)
4773
+ };
4774
+ for (const command of commands) {
4775
+ const r = await exec("sh", ["-c", command], { cwd: dir });
4776
+ if (r.code !== 0)
4777
+ return { ok: false, step: command, output: tail(`${r.stdout}
4778
+ ${r.stderr}`) };
4779
+ }
4780
+ return { ok: true };
4781
+ } finally {
4782
+ await remove().catch(() => {});
4783
+ }
4784
+ }
4785
+ };
4786
+ }
4787
+ function prNumber(arg, repository) {
4788
+ if (!arg)
4789
+ throw new UsageError("merge needs a pull request: armada merge <number or URL>");
4790
+ const trimmed = arg.trim().replace(/^#/, "");
4791
+ if (/^\d+$/.test(trimmed))
4792
+ return Number(trimmed);
4793
+ const pr = parsePullRequestUrl(trimmed);
4794
+ if (!pr)
4795
+ throw new UsageError(`"${arg}" is not a pull request number or URL`);
4796
+ if (pr.repo.toLowerCase() !== repository.toLowerCase())
4797
+ throw new UsageError(`${pr.url} is not in the project repository ${repository}`);
4798
+ return pr.number;
4799
+ }
4800
+ function render(o) {
4801
+ const out = [...o.lines, o.pr.url, o.ticket.url];
4802
+ if (o.hints.length)
4803
+ out.push("Hints for you to judge (not blocking):", ...o.hints.map((h) => ` - ${h}`));
4804
+ if (!o.merged)
4805
+ return `${out.join(`
4806
+ `)}
4807
+ `;
4808
+ if (!o.workers.length)
4809
+ out.push("No other worker is in flight.");
4810
+ else {
4811
+ out.push(`Tell these workers in flight what landed on ${o.pr.base} (rebase, shared files, new checks):`);
4812
+ for (const w of o.workers)
4813
+ out.push(` ${w.ticket} ${w.phase} ${[w.runtime, w.handle].filter(Boolean).join(" · ") || "runtime unknown"} ${w.title}`);
4814
+ }
4815
+ const a = o.archive;
4816
+ if (a)
4817
+ out.push(`Archive the worker's workspace of ${o.ticket.id} (${[a.runtime, a.handle].filter(Boolean).join(" · ") || "session unknown"}) with the "Stop and archive" section of ${a.guide ? `the ${a.guide} skill` : "its runtime guide"}.`);
4818
+ return `${out.join(`
4819
+ `)}
4820
+ `;
4821
+ }
4822
+ async function merge2(io, config2, credentials2, a, configPath) {
4823
+ const [arg, ...extra] = a.rest;
4824
+ if (extra.length)
4825
+ throw new UsageError(`unexpected argument ${extra[0]}`);
4826
+ const number = prNumber(arg, config2.github.repository);
4827
+ if (!credentials2.linearApiKey)
4828
+ throw new UsageError(missingKeyMessage(LINEAR_KEY));
4829
+ const token = credentials2.githubToken;
4830
+ if (!token)
4831
+ throw new UsageError("armada merge reads GitHub: set GITHUB_TOKEN or run `gh auth login`");
4832
+ const exec = io.exec;
4833
+ if (!exec)
4834
+ throw new UsageError("armada merge needs to run git and gh");
4835
+ const linearApiKey = credentials2.linearApiKey;
4836
+ const repoDir = dirname2(configPath);
4837
+ const fetchOpt = io.fetch ? { fetch: io.fetch } : {};
4838
+ const gh = { token, repository: config2.github.repository, ...fetchOpt };
4839
+ const linearOpts = { apiKey: linearApiKey, labels: config2.tracker.labels, ...fetchOpt };
4840
+ const now = io.now ?? (() => new Date);
4841
+ const turso2 = { live: null };
4842
+ const ctx = {
4843
+ config: config2,
4844
+ linear: io.linearWriter ? io.linearWriter(linearOpts) : createLinearWriter(linearOpts),
4845
+ forge: {
4846
+ readPull: (n) => fetchMergePull({ ...gh, number: n }),
4847
+ compare: (base, head) => fetchComparison({ ...gh, base, head }),
4848
+ diff: (n) => fetchPullDiff({ ...gh, number: n }),
4849
+ merge: ghMerge(exec, repoDir, config2.github.repository)
4850
+ },
4851
+ repo: gitRepo(exec, repoDir),
4852
+ tursoConfigured: !!credentials2.tursoUrl,
4853
+ turso: () => {
4854
+ turso2.live ??= openLive(credentials2);
4855
+ return turso2.live;
4856
+ },
4857
+ inFlight: async () => (await loadStatus(config2, { linearApiKey, githubToken: null, ...fetchOpt, now })).inFlight.map((t) => ({
4858
+ id: t.id,
4859
+ title: t.title,
4860
+ phase: t.phase,
4861
+ runtime: t.runtime
4862
+ })),
4863
+ holder: `${io.env.USER || "coordinator"}@${hostname()} ${randomUUID().slice(0, 8)}`,
4864
+ now,
4865
+ sleep: io.sleep ?? ((ms) => new Promise((done) => setTimeout(done, ms))),
4866
+ progress: (line) => io.stderr(`armada: ${line}
4867
+ `)
4868
+ };
4869
+ try {
4870
+ const o = await mergePullRequest(ctx, {
4871
+ pr: number,
4872
+ ticket: a.options.ticket ?? null,
4873
+ dryRun: !!a.options["dry-run"],
4874
+ noLock: !!a.options["no-lock"]
4875
+ });
4876
+ io.stdout(a.json ? `${JSON.stringify(o, null, 2)}
4877
+ ` : render(o));
4878
+ for (const w of o.warnings)
4879
+ io.stderr(`armada: warning: ${w}
4880
+ `);
3896
4881
  return 0;
3897
4882
  } finally {
3898
- await exec("git", ["worktree", "remove", "--force", checkout], { cwd: root }).catch(() => null);
3899
- await rm3(checkout, { recursive: true, force: true });
4883
+ (await turso2.live)?.db?.close();
3900
4884
  }
3901
4885
  }
3902
4886
 
@@ -3934,7 +4918,7 @@ function renderStatus(r) {
3934
4918
  const now = Date.parse(r.generatedAt);
3935
4919
  const out = [];
3936
4920
  const idWidth = Math.max(6, ...r.inFlight.map((t) => t.id.length), ...r.frontier.map((t) => t.id.length), ...(r.pullRequests ?? []).map((p) => `#${p.number}`.length));
3937
- const indent = " ".repeat(idWidth + 4);
4921
+ const indent2 = " ".repeat(idWidth + 4);
3938
4922
  const phaseWidth = Math.max(0, ...r.inFlight.map((t) => phaseLabel(t).length));
3939
4923
  out.push(`${r.project.name} · ${r.programRoot.id} ${r.programRoot.title}`);
3940
4924
  const gh = r.sources.github.error ? `GitHub not read: ${r.sources.github.error}` : `GitHub ${r.project.repository}`;
@@ -3945,13 +4929,13 @@ function renderStatus(r) {
3945
4929
  for (const t of r.inFlight) {
3946
4930
  const who = [t.runtime, t.agent].filter(Boolean).join(" · ") || "unassigned";
3947
4931
  out.push(` ${pad(t.id, idWidth)} ${pad(phaseLabel(t), phaseWidth)} ${who} · ${t.lastReport ? `reported ${relative2(t.lastReport, now)}` : `updated ${relative2(t.lastUpdate, now)}`}`);
3948
- out.push(`${indent}${truncate(t.title, 90)}${t.spec ? ` [${t.spec}]` : ""}`);
4932
+ out.push(`${indent2}${truncate(t.title, 90)}${t.spec ? ` [${t.spec}]` : ""}`);
3949
4933
  if (t.statusLine?.summary)
3950
- out.push(`${indent}“${truncate(t.statusLine.summary, 100)}”`);
4934
+ out.push(`${indent2}“${truncate(t.statusLine.summary, 100)}”`);
3951
4935
  if (t.pr)
3952
- out.push(`${indent}${[`PR #${t.pr.number}`, prState(t.pr)].filter(Boolean).join(" · ")}`);
4936
+ out.push(`${indent2}${[`PR #${t.pr.number}`, prState(t.pr)].filter(Boolean).join(" · ")}`);
3953
4937
  if (t.flags.length)
3954
- out.push(`${indent}! ${t.flags.join(", ")}`);
4938
+ out.push(`${indent2}! ${t.flags.join(", ")}`);
3955
4939
  }
3956
4940
  const ready = r.frontier.filter((t) => t.readyForAgent);
3957
4941
  const untriaged = r.frontier.filter((t) => !t.readyForAgent);
@@ -3979,9 +4963,9 @@ function renderStatus(r) {
3979
4963
  for (const p of r.pullRequests ?? []) {
3980
4964
  const ticket = p.ticket ? `${p.ticket.id}${p.ticket.phase ? ` ${p.ticket.phase}` : ""}` : "no ticket";
3981
4965
  out.push(` ${pad(`#${p.number}`, idWidth)} ${[ticket, prState(p)].filter(Boolean).join(" · ")}`);
3982
- out.push(`${indent}${truncate(p.title, 90)}`);
4966
+ out.push(`${indent2}${truncate(p.title, 90)}`);
3983
4967
  if (p.failingChecks.length)
3984
- out.push(`${indent}! failing: ${p.failingChecks.join(", ")}`);
4968
+ out.push(`${indent2}! failing: ${p.failingChecks.join(", ")}`);
3985
4969
  }
3986
4970
  if (r.warnings.length) {
3987
4971
  out.push("", `Warnings (${r.warnings.length})`);
@@ -4038,13 +5022,13 @@ async function statusAll(io, json) {
4038
5022
  const read = await projectConfig(p, credentials2.githubToken, io);
4039
5023
  warning = read.warning;
4040
5024
  const config2 = read.config;
4041
- const report = await loadStatus(config2, {
5025
+ const report2 = await loadStatus(config2, {
4042
5026
  linearApiKey,
4043
5027
  githubToken: credentials2.githubToken,
4044
5028
  ...io.fetch ? { fetch: io.fetch } : {},
4045
5029
  ...io.now ? { now: io.now } : {}
4046
5030
  });
4047
- return { ...base, report, error: null, configWarning: warning };
5031
+ return { ...base, report: report2, error: null, configWarning: warning };
4048
5032
  } catch (err) {
4049
5033
  return { ...base, report: null, error: message(err), configWarning: warning };
4050
5034
  }
@@ -4071,179 +5055,6 @@ ${"─".repeat(60)}
4071
5055
  return projects.some((p) => p.error) ? 1 : 0;
4072
5056
  }
4073
5057
 
4074
- // src/worker.ts
4075
- var TURSO_OPEN_TIMEOUT_MS = 1e4;
4076
- async function openLive(credentials2) {
4077
- if (!credentials2.tursoUrl)
4078
- return { db: null, warning: "Turso is not configured (ARMADA_TURSO_URL); live activity is not recorded" };
4079
- let timer;
4080
- const opening = openTurso({ url: credentials2.tursoUrl, token: credentials2.tursoToken });
4081
- try {
4082
- const db = await Promise.race([
4083
- opening,
4084
- new Promise((_, reject) => {
4085
- timer = setTimeout(() => reject(new Error(`no answer within ${TURSO_OPEN_TIMEOUT_MS / 1000} s`)), TURSO_OPEN_TIMEOUT_MS);
4086
- })
4087
- ]);
4088
- return { db, warning: null };
4089
- } catch (err) {
4090
- opening.then((db) => db.close(), () => {});
4091
- const reason = err instanceof Error ? err.message : String(err);
4092
- return { db: null, warning: `Turso unavailable (${reason}); live activity is not recorded, Linear is` };
4093
- } finally {
4094
- clearTimeout(timer);
4095
- }
4096
- }
4097
- function statusEvents(config2, credentials2) {
4098
- if (!credentials2.tursoUrl)
4099
- return;
4100
- return async () => {
4101
- const { db, warning } = await openLive(credentials2);
4102
- if (!db)
4103
- throw new Error(warning ?? "Turso unavailable");
4104
- try {
4105
- return await lastEventTimes(db, config2.project.slug);
4106
- } finally {
4107
- db.close();
4108
- }
4109
- };
4110
- }
4111
- var ID = /(?:^|[^a-z0-9])([a-z][a-z0-9]*-\d+)(?=$|[^a-z0-9])/gi;
4112
- function ticketFromBranch(branch, programRoot) {
4113
- const ids = [...branch.matchAll(ID)].map((m) => (m[1] ?? "").toUpperCase());
4114
- const team = programRoot.split("-")[0]?.toUpperCase();
4115
- return ids.find((id) => id.split("-")[0] === team) ?? ids[0] ?? null;
4116
- }
4117
- function currentTicket(io, config2, explicit) {
4118
- const fromEnv2 = io.env.ARMADA_TICKET?.trim();
4119
- const id = explicit?.trim() || fromEnv2 || (() => {
4120
- const branch = io.gitBranch?.();
4121
- return branch ? ticketFromBranch(branch, config2.tracker.programRoot) : null;
4122
- })();
4123
- if (!id)
4124
- throw new UsageError("which ticket? pass --ticket <id>, set ARMADA_TICKET, or run on the ticket's branch");
4125
- return id.toUpperCase();
4126
- }
4127
- async function context(io, config2, credentials2) {
4128
- if (!credentials2.linearApiKey)
4129
- throw new UsageError(missingKeyMessage(LINEAR_KEY));
4130
- const linearOpts = {
4131
- apiKey: credentials2.linearApiKey,
4132
- labels: config2.tracker.labels,
4133
- ...io.fetch ? { fetch: io.fetch } : {}
4134
- };
4135
- const linear2 = io.linearWriter ? io.linearWriter(linearOpts) : createLinearWriter(linearOpts);
4136
- let live2 = null;
4137
- const token = credentials2.githubToken;
4138
- const ctx = {
4139
- config: config2,
4140
- linear: linear2,
4141
- turso: () => {
4142
- live2 ??= openLive(credentials2);
4143
- return live2;
4144
- },
4145
- readPull: token ? (number) => fetchPullRequest({
4146
- token,
4147
- repository: config2.github.repository,
4148
- number,
4149
- ...io.fetch ? { fetch: io.fetch } : {}
4150
- }) : null,
4151
- now: io.now ?? (() => new Date)
4152
- };
4153
- const close = async () => {
4154
- const opened = await live2;
4155
- opened?.db?.close();
4156
- };
4157
- return { ctx, close };
4158
- }
4159
- function print(io, outcome, json) {
4160
- if (json) {
4161
- io.stdout(`${JSON.stringify(outcome, null, 2)}
4162
- `);
4163
- return;
4164
- }
4165
- const out = [...outcome.lines, outcome.url];
4166
- if (outcome.inbox) {
4167
- if (!outcome.inbox.length)
4168
- out.push("Inbox: nothing waiting for you.");
4169
- else {
4170
- out.push(`Inbox (${outcome.inbox.length}) — read and act on these:`);
4171
- for (const item of outcome.inbox)
4172
- out.push(` #${item.id} ${item.kind}${item.author ? ` from ${item.author}` : ""} · ${item.createdAt}`, ...item.body.split(`
4173
- `).map((l) => ` ${l}`));
4174
- }
4175
- }
4176
- io.stdout(`${out.join(`
4177
- `)}
4178
- `);
4179
- for (const w of outcome.warnings)
4180
- io.stderr(`armada: warning: ${w}
4181
- `);
4182
- }
4183
- async function withContext(io, config2, credentials2, json, act) {
4184
- const { ctx, close } = await context(io, config2, credentials2);
4185
- try {
4186
- print(io, await act(ctx), json);
4187
- return 0;
4188
- } finally {
4189
- await close();
4190
- }
4191
- }
4192
- async function claim(io, config2, credentials2, a) {
4193
- const [ticket, ...extra] = a.rest;
4194
- if (!ticket)
4195
- throw new UsageError("claim needs a ticket: armada claim <ticket> --runtime <name> --handle <id>");
4196
- if (extra.length)
4197
- throw new UsageError(`unexpected argument ${extra[0]}`);
4198
- const runtime = a.options.runtime?.trim();
4199
- const handle = a.options.handle?.trim();
4200
- if (!runtime)
4201
- throw new UsageError("--runtime is required, e.g. --runtime conductor");
4202
- if (!handle)
4203
- throw new UsageError("--handle is required: the runtime's id for this session, e.g. <workspace>/<session>");
4204
- return withContext(io, config2, credentials2, a.json, (ctx) => claimTicket(ctx, {
4205
- ticket: ticket.toUpperCase(),
4206
- runtime,
4207
- handle,
4208
- ...a.options.branch ? { branch: a.options.branch } : {}
4209
- }));
4210
- }
4211
- async function report(io, config2, credentials2, a) {
4212
- const [phase, ...extra] = a.rest;
4213
- if (!phase || !isLabelPhase(phase))
4214
- throw new UsageError(`report needs a phase: ${LABEL_PHASES.join(", ")}${phase ? ` (got "${phase}")` : ""}`);
4215
- if (extra.length)
4216
- throw new UsageError(`unexpected argument ${extra[0]}`);
4217
- if (a.options.message !== undefined && a.options["message-file"] !== undefined)
4218
- throw new UsageError("pass --message or --message-file, not both");
4219
- let message2 = a.options.message ?? null;
4220
- const file = a.options["message-file"];
4221
- if (file !== undefined) {
4222
- message2 = file === "-" ? await io.readStdin?.() ?? null : await io.readFile(file);
4223
- if (message2 === null)
4224
- throw new UsageError(`cannot read the message from ${file}`);
4225
- }
4226
- if (!message2?.trim() && phase !== "ready-to-merge")
4227
- throw new UsageError("--message is required: what you did or what you are doing (first line = summary)");
4228
- const ticket = currentTicket(io, config2, a.options.ticket);
4229
- return withContext(io, config2, credentials2, a.json, (ctx) => reportPhase(ctx, {
4230
- ticket,
4231
- phase,
4232
- message: message2,
4233
- pr: a.options.pr ?? null,
4234
- sha: a.options.sha ?? null
4235
- }));
4236
- }
4237
- async function release(io, config2, credentials2, a) {
4238
- if (a.rest.length)
4239
- throw new UsageError(`unexpected argument ${a.rest[0]}`);
4240
- const reason = a.options.reason?.trim();
4241
- if (!reason)
4242
- throw new UsageError("--reason is required: why the ticket is given back");
4243
- const ticket = currentTicket(io, config2, a.options.ticket);
4244
- return withContext(io, config2, credentials2, a.json, (ctx) => releaseTicket(ctx, { ticket, reason }));
4245
- }
4246
-
4247
5058
  // src/cli.ts
4248
5059
  var USAGE = `Usage: armada <command> [options]
4249
5060
 
@@ -4265,6 +5076,13 @@ Commands:
4265
5076
  Prints what waits in this worker's inbox.
4266
5077
  release --reason <text>
4267
5078
  Give the ticket back: agent labels removed, ticket moved back
5079
+ merge <pr> [--ticket <id>] [--dry-run] [--no-lock]
5080
+ Coordinator: check a handed-back pull request (hand-back SHA = head,
5081
+ CLEAN, required checks green, no open review thread, base contained
5082
+ or test-merged), squash-merge it pinned to that SHA under the merge
5083
+ lock, close the ticket and list the workers to tell. Never deletes
5084
+ the branch. --dry-run only runs the checklist. Refused when Turso is
5085
+ configured but down; --no-lock then merges without the lock.
4268
5086
  auth login Ask for the missing keys (hidden input) and store them on this machine
4269
5087
  auth status Show which keys are set and where each comes from, never their values
4270
5088
  auth logout Remove Armada's keys from this machine
@@ -4272,7 +5090,8 @@ Commands:
4272
5090
  Options:
4273
5091
  --json Print the result as JSON
4274
5092
  --config <path> Use this armada.toml instead of searching from the current directory
4275
- --ticket <id> Ticket for report and release; default ARMADA_TICKET, then the git branch
5093
+ --ticket <id> Ticket for report and release (default ARMADA_TICKET, then the git
5094
+ branch) and for merge (default: the ticket the PR branch names)
4276
5095
  -h, --help Show this help
4277
5096
  -v, --version Print the version
4278
5097
 
@@ -4282,6 +5101,7 @@ Keys (the environment always wins over the file):
4282
5101
  elsewhere; a file: URL works locally)
4283
5102
  ARMADA_TURSO_TOKEN Turso database token
4284
5103
  GITHUB_TOKEN GitHub token; falls back to GH_TOKEN, then \`gh auth token\`
5104
+ (merge also runs gh and git, with gh's own login)
4285
5105
 
4286
5106
  Files:
4287
5107
  $XDG_CONFIG_HOME/armada (default ~/.config/armada)
@@ -4302,11 +5122,13 @@ var VALUE_OPTIONS = [
4302
5122
  "name",
4303
5123
  "slug"
4304
5124
  ];
5125
+ var FLAG_OPTIONS = ["dry-run", "no-lock"];
4305
5126
  var COMMAND_OPTIONS = {
4306
5127
  claim: ["runtime", "handle", "branch"],
4307
5128
  report: ["ticket", "message", "message-file", "pr", "sha"],
4308
5129
  release: ["ticket", "reason"],
4309
- init: ["program-root", "name", "slug"]
5130
+ init: ["program-root", "name", "slug"],
5131
+ merge: ["ticket", "dry-run", "no-lock"]
4310
5132
  };
4311
5133
  function parseArgs(argv) {
4312
5134
  const args = {
@@ -4331,6 +5153,8 @@ function parseArgs(argv) {
4331
5153
  args.help = true;
4332
5154
  else if (a === "-v" || a === "--version")
4333
5155
  args.version = true;
5156
+ else if (name && FLAG_OPTIONS.includes(name) && named?.[2] === undefined)
5157
+ args.options[name] = "true";
4334
5158
  else if (name && (name === "config" || VALUE_OPTIONS.includes(name))) {
4335
5159
  const v = named?.[2] ?? argv[++k];
4336
5160
  if (v === undefined)
@@ -4356,12 +5180,12 @@ async function findConfig(io, explicit) {
4356
5180
  throw new UsageError(`${path} does not exist`);
4357
5181
  return { path, text };
4358
5182
  }
4359
- for (let dir = resolve(io.cwd);; dir = dirname2(dir)) {
4360
- const path = join4(dir, CONFIG_FILE);
5183
+ for (let dir = resolve(io.cwd);; dir = dirname3(dir)) {
5184
+ const path = join5(dir, CONFIG_FILE);
4361
5185
  const text = await io.readFile(path);
4362
5186
  if (text !== null)
4363
5187
  return { path, text };
4364
- if (dirname2(dir) === dir)
5188
+ if (dirname3(dir) === dir)
4365
5189
  break;
4366
5190
  }
4367
5191
  throw new UsageError(`no ${CONFIG_FILE} found in ${io.cwd} or any parent directory. Add one at the repository root (see README).`);
@@ -4414,6 +5238,11 @@ async function run(argv, io) {
4414
5238
  const { credentials: credentials2 } = await loadCredentials(io);
4415
5239
  return await worker2(io, config2, credentials2, args);
4416
5240
  }
5241
+ if (args.command === "merge") {
5242
+ const { path, text } = await findConfig(io, args.config);
5243
+ const { credentials: credentials2 } = await loadCredentials(io);
5244
+ return await merge2(io, parseConfig(text, path), credentials2, args, path);
5245
+ }
4417
5246
  if (args.command === "status") {
4418
5247
  noExtra(args.rest);
4419
5248
  return await (args.all ? statusAll(io, args.json) : status2(io, args));
@@ -4479,11 +5308,11 @@ function feedLine(line, chunk) {
4479
5308
  }
4480
5309
  return { answer, sequence };
4481
5310
  }
4482
- function echo(before, after) {
5311
+ function echo(before, after2) {
4483
5312
  let common = 0;
4484
- while (common < before.length && common < after.length && before[common] === after[common])
5313
+ while (common < before.length && common < after2.length && before[common] === after2[common])
4485
5314
  common++;
4486
- return "\b \b".repeat(before.length - common) + after.slice(common);
5315
+ return "\b \b".repeat(before.length - common) + after2.slice(common);
4487
5316
  }
4488
5317
 
4489
5318
  // src/main.ts