@the-vibe-company/armada 0.0.0 → 0.1.1
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.
- package/README.md +29 -5
- package/dist/armada.js +1012 -39
- package/package.json +5 -2
package/README.md
CHANGED
|
@@ -4,7 +4,7 @@ Armada runs a fleet of coding agents on one project and keeps every piece of wor
|
|
|
4
4
|
|
|
5
5
|
It imposes one method: grill the decisions, write a spec, cut it into tickets, let one worker agent ship each ticket as a green pull request, and let a coordinator agent merge. The tracker is the source of truth for progress; Armada adds live telemetry, contention rules and a fleet dashboard on top.
|
|
6
6
|
|
|
7
|
-
**Status:** early. `armada status` and `armada
|
|
7
|
+
**Status:** early. `armada status`, `armada auth`, `armada claim`, `armada report` and `armada release` work; the other commands are being built.
|
|
8
8
|
|
|
9
9
|
## Install
|
|
10
10
|
|
|
@@ -26,12 +26,33 @@ armada status # or: armada status --json
|
|
|
26
26
|
|
|
27
27
|
`armada status` reads the `armada.toml` of the current repository (or the nearest parent directory) and prints:
|
|
28
28
|
|
|
29
|
-
- **In flight**: tickets an agent holds, with their phase, runtime, last
|
|
29
|
+
- **In flight**: tickets an agent holds, with their phase, runtime, last report and pull request. A worker with no report (an `armada report` event in Turso, an `Agent status:` comment or its claim) for longer than `policy.silence_minutes` is flagged `silent`, unless it is waiting on a human (`awaiting-approval`, `blocked`, `ready-to-merge`). A ticket that never had a report falls back to its last sign of life (ticket edit, comment or pull request update).
|
|
30
30
|
- **Ready to start**: tickets without sub-issues that are not started, not held by an agent, have no open pull request, and whose blocked-by tickets are all closed, ranked by what they unlock. Tickets without the ready label, or still in triage, are listed separately.
|
|
31
31
|
- **Pull requests waiting**: open pull requests with their CI state and mergeability.
|
|
32
32
|
|
|
33
33
|
GitHub is read with `GITHUB_TOKEN`, `GH_TOKEN` or the GitHub CLI login (`gh auth token`). Without any of them the tickets are still shown.
|
|
34
34
|
|
|
35
|
+
## Work on a ticket (workers)
|
|
36
|
+
|
|
37
|
+
A worker writes to the tracker only through three commands. They set the labels and write the comments in the protocol format, and record each event in Turso.
|
|
38
|
+
|
|
39
|
+
```sh
|
|
40
|
+
armada claim ABC-12 --runtime conductor --handle <workspace>/<session>
|
|
41
|
+
armada report awaiting-approval --message-file plan.md # first line = summary
|
|
42
|
+
armada report implementing --message "plan approved, writing the parser"
|
|
43
|
+
armada report implementing --message "parser done, wiring the CLI" # same phase = status update
|
|
44
|
+
armada report shipping --message "PR open" --pr 34
|
|
45
|
+
armada report ready-to-merge --pr 34 --sha <full 40-character head SHA>
|
|
46
|
+
armada release --reason "wrong ticket"
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
- `claim` re-reads the ticket and refuses it when another worker holds it; if two claims race, the older comment wins and the other withdraws. It assigns the ticket to the Linear key's user, moves it to the team's first started state, sets the `planning` phase label and the runtime label (matched by name, so `conductor` finds `Conductor`), and posts an `Agent claim — runtime · session · branch · started` line. The handle is kept in that comment and in Turso, so a coordinator finds the session either way. Claiming again with the same handle repairs labels and state.
|
|
50
|
+
- `report <phase>` accepts: planning → awaiting-approval or implementing; awaiting-approval → planning or implementing; implementing → shipping; shipping → implementing or ready-to-merge; ready-to-merge → shipping; blocked from anywhere and back to any phase; the current phase again as a status update. Anything else exits 1 with the reason. The output lists what waits in the worker's inbox.
|
|
51
|
+
- `ready-to-merge` is refused unless the pull request is open in the project repository, `--sha` is the full 40-character SHA of its head, and every check in `[gates] required_checks` is green on that head (with none declared: at least one check, all green). It needs a GitHub token.
|
|
52
|
+
- `release` removes the phase and runtime labels, moves the ticket back to the team's first unstarted state and posts `Agent status: released — <reason>`.
|
|
53
|
+
- `report` and `release` find the ticket from `--ticket`, then `ARMADA_TICKET`, then the current git branch (`feature/abc-12-…`).
|
|
54
|
+
- Turso is optional. When it is not configured or not reachable, the commands still write Linear and print a warning.
|
|
55
|
+
|
|
35
56
|
## Keys
|
|
36
57
|
|
|
37
58
|
Armada needs a few keys. Set them up once per machine with `armada auth login`, or pass them as environment variables, which always win over the stored ones (the way to go in CI and cloud sandboxes).
|
|
@@ -39,8 +60,8 @@ Armada needs a few keys. Set them up once per machine with `armada auth login`,
|
|
|
39
60
|
| Variable | What | Needed by |
|
|
40
61
|
| --- | --- | --- |
|
|
41
62
|
| `LINEAR_API_KEY` | Linear personal API key (Linear > Settings > Security & access > Personal API keys) | `armada status` |
|
|
42
|
-
| `ARMADA_TURSO_URL` | Turso database URL, `libsql://...` | live activity (
|
|
43
|
-
| `ARMADA_TURSO_TOKEN` | Turso database token | live activity (
|
|
63
|
+
| `ARMADA_TURSO_URL` | Turso database URL, `libsql://...` (`file:/path/armada.db` for a local database) | live activity: events, runtime handles, inbox (optional) |
|
|
64
|
+
| `ARMADA_TURSO_TOKEN` | Turso database token | live activity (optional) |
|
|
44
65
|
| `GITHUB_TOKEN` or `GH_TOKEN` | GitHub token; otherwise `gh auth token` is used | pull requests and CI |
|
|
45
66
|
|
|
46
67
|
- `armada auth login` asks only for the keys that are missing, with hidden input for tokens, and stores them in `~/.config/armada/credentials` (or `$XDG_CONFIG_HOME/armada/credentials`), mode 0600 in a 0700 directory. Without a terminal it asks nothing and lists the variables to set instead.
|
|
@@ -82,8 +103,11 @@ runtime_group = "Agent runtime" # single-select label group for the agent runti
|
|
|
82
103
|
[github]
|
|
83
104
|
repository = "acme/widgets" # owner/name (required)
|
|
84
105
|
|
|
106
|
+
[gates]
|
|
107
|
+
required_checks = ["test"] # CI checks that must be green before a hand-back (default: every check)
|
|
108
|
+
|
|
85
109
|
[policy]
|
|
86
|
-
|
|
110
|
+
silence_minutes = 15 # a worker with no report for longer is flagged silent (default 15)
|
|
87
111
|
```
|
|
88
112
|
|
|
89
113
|
A missing or invalid key stops the command with a message naming it, for example `missing required key "tracker.program_root"`. This repository's own configuration is in [`armada.toml`](https://github.com/The-Vibe-Company/armada/blob/main/armada.toml).
|
package/dist/armada.js
CHANGED
|
@@ -1,4 +1,22 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
+
import { createRequire } from "node:module";
|
|
3
|
+
var __create = Object.create;
|
|
4
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
5
|
+
var __defProp = Object.defineProperty;
|
|
6
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
7
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __toESM = (mod, isNodeMode, target) => {
|
|
9
|
+
target = mod != null ? __create(__getProtoOf(mod)) : {};
|
|
10
|
+
const to = isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target;
|
|
11
|
+
for (let key of __getOwnPropNames(mod))
|
|
12
|
+
if (!__hasOwnProp.call(to, key))
|
|
13
|
+
__defProp(to, key, {
|
|
14
|
+
get: () => mod[key],
|
|
15
|
+
enumerable: true
|
|
16
|
+
});
|
|
17
|
+
return to;
|
|
18
|
+
};
|
|
19
|
+
var __require = /* @__PURE__ */ createRequire(import.meta.url);
|
|
2
20
|
|
|
3
21
|
// src/main.ts
|
|
4
22
|
import { spawnSync } from "node:child_process";
|
|
@@ -1052,24 +1070,40 @@ function parseConfig(text, source = CONFIG_FILE) {
|
|
|
1052
1070
|
problems.push(`"policy" must be a table`);
|
|
1053
1071
|
const labelsT = isTable(labels) ? labels : {};
|
|
1054
1072
|
const policyT = isTable(policy) ? policy : {};
|
|
1073
|
+
const gates = raw.gates === undefined ? {} : raw.gates;
|
|
1074
|
+
if (!isTable(gates))
|
|
1075
|
+
problems.push(`"gates" must be a table`);
|
|
1076
|
+
const gatesT = isTable(gates) ? gates : {};
|
|
1055
1077
|
const known = [
|
|
1056
1078
|
["project", project, ["name", "slug"]],
|
|
1057
1079
|
["tracker", tracker, ["program_root", "language", "ready_label", "labels"]],
|
|
1058
1080
|
["tracker.labels", labelsT, ["phase_group", "runtime_group"]],
|
|
1059
1081
|
["github", github, ["repository"]],
|
|
1060
|
-
["
|
|
1082
|
+
["gates", gatesT, ["required_checks"]],
|
|
1083
|
+
["policy", policyT, ["silence_minutes", "silent_after_minutes"]]
|
|
1061
1084
|
];
|
|
1062
1085
|
for (const [path, t, keys] of known)
|
|
1063
1086
|
for (const key of Object.keys(t))
|
|
1064
1087
|
if (!keys.includes(key))
|
|
1065
1088
|
problems.push(`unknown key "${path}.${key}"`);
|
|
1089
|
+
const silenceKey = policyT.silence_minutes !== undefined ? "silence_minutes" : "silent_after_minutes";
|
|
1090
|
+
if (policyT.silence_minutes !== undefined && policyT.silent_after_minutes !== undefined)
|
|
1091
|
+
problems.push(`"policy.silent_after_minutes" is the old name of "policy.silence_minutes"; keep only one`);
|
|
1066
1092
|
let silentAfterMinutes = CONFIG_DEFAULTS.silentAfterMinutes;
|
|
1067
|
-
if (policyT
|
|
1068
|
-
const v = policyT
|
|
1093
|
+
if (policyT[silenceKey] !== undefined) {
|
|
1094
|
+
const v = policyT[silenceKey];
|
|
1069
1095
|
if (typeof v === "number" && Number.isFinite(v) && v > 0)
|
|
1070
1096
|
silentAfterMinutes = v;
|
|
1071
1097
|
else
|
|
1072
|
-
problems.push(`"policy
|
|
1098
|
+
problems.push(`"policy.${silenceKey}" must be a positive number`);
|
|
1099
|
+
}
|
|
1100
|
+
let requiredChecks = [];
|
|
1101
|
+
if (gatesT.required_checks !== undefined) {
|
|
1102
|
+
const v = gatesT.required_checks;
|
|
1103
|
+
if (Array.isArray(v) && v.every((c) => typeof c === "string" && c.trim()))
|
|
1104
|
+
requiredChecks = [...new Set(v.map((c) => c.trim()))];
|
|
1105
|
+
else
|
|
1106
|
+
problems.push(`"gates.required_checks" must be a list of check names`);
|
|
1073
1107
|
}
|
|
1074
1108
|
const config = {
|
|
1075
1109
|
project: {
|
|
@@ -1091,6 +1125,7 @@ function parseConfig(text, source = CONFIG_FILE) {
|
|
|
1091
1125
|
github: {
|
|
1092
1126
|
repository: str(github, "github", "repository", { pattern: REPOSITORY, hint: "owner/name" })
|
|
1093
1127
|
},
|
|
1128
|
+
gates: { requiredChecks },
|
|
1094
1129
|
policy: { silentAfterMinutes }
|
|
1095
1130
|
};
|
|
1096
1131
|
if (problems.length)
|
|
@@ -1467,11 +1502,13 @@ function buildLane(m, allComments, issue, opts) {
|
|
|
1467
1502
|
const announcing = comments.find((c) => c.status?.phase === phase);
|
|
1468
1503
|
const since = announcing?.createdAt ?? (phase === "shipping" || phase === "ready-to-merge" ? pr?.createdAt : undefined) ?? claims[0]?.at ?? issue.startedAt ?? issue.updatedAt;
|
|
1469
1504
|
const lastUpdate = latest(issue.updatedAt, comments[0]?.createdAt, pr?.updatedAt, issue.startedAt);
|
|
1505
|
+
const lastReport = latest(comments.find((c) => c.status || c.claim)?.createdAt, claims.at(-1)?.at, opts.lastEvents?.[issue.id]) || null;
|
|
1470
1506
|
const openBlockers = m.openBlockersOf(issue);
|
|
1471
1507
|
const agent = issue.delegate ?? issue.assignee;
|
|
1472
1508
|
const flags = [];
|
|
1473
1509
|
const waitingOnHuman = NEEDS_HUMAN.includes(phase) || phase === "merged";
|
|
1474
|
-
|
|
1510
|
+
const alive = lastReport ?? lastUpdate;
|
|
1511
|
+
if (!waitingOnHuman && opts.now - Date.parse(alive) > opts.silentAfterMinutes * MIN)
|
|
1475
1512
|
flags.push("silent");
|
|
1476
1513
|
if (pr?.state === "open" && pr.ci === "failure")
|
|
1477
1514
|
flags.push("ci-failing");
|
|
@@ -1498,6 +1535,7 @@ function buildLane(m, allComments, issue, opts) {
|
|
|
1498
1535
|
agent,
|
|
1499
1536
|
since,
|
|
1500
1537
|
lastUpdate,
|
|
1538
|
+
lastReport,
|
|
1501
1539
|
statusLine: withStatus?.status ? {
|
|
1502
1540
|
summary: withStatus.status.summary,
|
|
1503
1541
|
at: withStatus.createdAt,
|
|
@@ -1584,11 +1622,20 @@ function parseStatusLine(body) {
|
|
|
1584
1622
|
const phase = LEGACY[raw] ?? raw;
|
|
1585
1623
|
return PHASES.includes(phase) ? { phase, summary: (m[2] ?? "").trim() } : null;
|
|
1586
1624
|
}
|
|
1625
|
+
var unescapeMarkdown = (line) => line.replace(/\\([!-/:-@[-`{-~])/g, "$1");
|
|
1626
|
+
var trimMarks = (v) => {
|
|
1627
|
+
const t = v.trim();
|
|
1628
|
+
return t.match(/^([*_`]+)(.+)\1$/)?.[2]?.trim() ?? t;
|
|
1629
|
+
};
|
|
1587
1630
|
function parseClaim(body, at, author) {
|
|
1588
|
-
const line =
|
|
1589
|
-
|
|
1631
|
+
const line = body.split(`
|
|
1632
|
+
`).map(unescapeMarkdown).find((l) => /^[\s*_`>]*Agent claim\b/i.test(l));
|
|
1633
|
+
if (!line)
|
|
1590
1634
|
return null;
|
|
1591
|
-
const field = (k) =>
|
|
1635
|
+
const field = (k) => {
|
|
1636
|
+
const v = line.match(new RegExp(`(?:${k})[*_\`]*\\s*:\\s*([^·|]+)`, "i"))?.[1];
|
|
1637
|
+
return v && trimMarks(v) || null;
|
|
1638
|
+
};
|
|
1592
1639
|
return {
|
|
1593
1640
|
runtime: field("runtime"),
|
|
1594
1641
|
session: field("session"),
|
|
@@ -1607,10 +1654,15 @@ function parsePullRequestUrl(url, title = "") {
|
|
|
1607
1654
|
return m?.[1] && m[2] ? { url: `https://github.com/${m[1]}/pull/${m[2]}`, repo: m[1], number: Number(m[2]), title } : null;
|
|
1608
1655
|
}
|
|
1609
1656
|
function agentLabels(labels, groups) {
|
|
1610
|
-
|
|
1657
|
+
let agentPhase = null;
|
|
1658
|
+
for (const l of labels)
|
|
1659
|
+
if (l.group === groups.phaseGroup)
|
|
1660
|
+
agentPhase ??= phaseNamed(l.name);
|
|
1611
1661
|
const runtime = labels.find((l) => l.group === groups.runtimeGroup);
|
|
1612
|
-
return { agentPhase
|
|
1662
|
+
return { agentPhase, agentRuntime: runtime?.name ?? null };
|
|
1613
1663
|
}
|
|
1664
|
+
var sameName = (a, b) => a.toLowerCase().replace(/[^a-z0-9]/g, "") === b.toLowerCase().replace(/[^a-z0-9]/g, "");
|
|
1665
|
+
var phaseNamed = (name) => LABEL_PHASES.find((p) => sameName(p, name)) ?? null;
|
|
1614
1666
|
function truncationWarnings(raw) {
|
|
1615
1667
|
const cut = (c, what) => c.pageInfo?.hasNextPage ? [`${raw.identifier}: more ${what} than Armada reads; some are ignored`] : [];
|
|
1616
1668
|
return [
|
|
@@ -1836,7 +1888,7 @@ function normalizePull(raw, repo) {
|
|
|
1836
1888
|
mergedAt: raw.mergedAt
|
|
1837
1889
|
};
|
|
1838
1890
|
}
|
|
1839
|
-
var
|
|
1891
|
+
var PULL_FIELDS = `
|
|
1840
1892
|
fragment P on PullRequest {
|
|
1841
1893
|
number title url state isDraft mergeable headRefName headRefOid createdAt updatedAt mergedAt
|
|
1842
1894
|
commits(last: 1) { nodes { commit { statusCheckRollup { state contexts(first: 50) { nodes {
|
|
@@ -1844,7 +1896,8 @@ var PULLS_QUERY = `
|
|
|
1844
1896
|
... on CheckRun { name status conclusion }
|
|
1845
1897
|
... on StatusContext { context state }
|
|
1846
1898
|
} } } } } }
|
|
1847
|
-
}
|
|
1899
|
+
}`;
|
|
1900
|
+
var PULLS_QUERY = `${PULL_FIELDS}
|
|
1848
1901
|
query Pulls($owner: String!, $name: String!) {
|
|
1849
1902
|
repository(owner: $owner, name: $name) {
|
|
1850
1903
|
open: pullRequests(states: OPEN, first: 100, orderBy: { field: UPDATED_AT, direction: DESC }) {
|
|
@@ -1854,14 +1907,13 @@ var PULLS_QUERY = `
|
|
|
1854
1907
|
closed: pullRequests(states: [MERGED, CLOSED], first: 30, orderBy: { field: UPDATED_AT, direction: DESC }) { nodes { ...P } }
|
|
1855
1908
|
}
|
|
1856
1909
|
}`;
|
|
1857
|
-
async function
|
|
1858
|
-
const [owner, name] = opts.repository.split("/");
|
|
1910
|
+
async function githubQuery(opts, query, variables) {
|
|
1859
1911
|
const doFetch = opts.fetch ?? fetch;
|
|
1860
1912
|
const timeoutMs = opts.timeoutMs ?? REQUEST_TIMEOUT_MS;
|
|
1861
1913
|
const res = await doFetch(GITHUB_GRAPHQL, {
|
|
1862
1914
|
method: "POST",
|
|
1863
1915
|
headers: { "Content-Type": "application/json", Authorization: `Bearer ${opts.token}` },
|
|
1864
|
-
body: JSON.stringify({ query
|
|
1916
|
+
body: JSON.stringify({ query, variables }),
|
|
1865
1917
|
signal: AbortSignal.timeout(timeoutMs)
|
|
1866
1918
|
}).catch((err) => {
|
|
1867
1919
|
throw new GithubError(`GitHub API unreachable: ${networkReason(err, timeoutMs)}`);
|
|
@@ -1871,6 +1923,25 @@ async function fetchForge(opts) {
|
|
|
1871
1923
|
const json = await res.json();
|
|
1872
1924
|
if (json.errors?.length)
|
|
1873
1925
|
throw new GithubError(`GitHub API: ${json.errors.map((e) => e.message).join("; ")}`);
|
|
1926
|
+
return json;
|
|
1927
|
+
}
|
|
1928
|
+
var PULL_QUERY = `${PULL_FIELDS}
|
|
1929
|
+
query Pull($owner: String!, $name: String!, $number: Int!) {
|
|
1930
|
+
repository(owner: $owner, name: $name) { pullRequest(number: $number) { ...P } }
|
|
1931
|
+
}`;
|
|
1932
|
+
async function fetchPullRequest(opts) {
|
|
1933
|
+
const [owner, name] = opts.repository.split("/");
|
|
1934
|
+
const json = await githubQuery(opts, PULL_QUERY, {
|
|
1935
|
+
owner,
|
|
1936
|
+
name,
|
|
1937
|
+
number: opts.number
|
|
1938
|
+
});
|
|
1939
|
+
const raw = json.data?.repository?.pullRequest;
|
|
1940
|
+
return raw ? normalizePull(raw, opts.repository) : null;
|
|
1941
|
+
}
|
|
1942
|
+
async function fetchForge(opts) {
|
|
1943
|
+
const [owner, name] = opts.repository.split("/");
|
|
1944
|
+
const json = await githubQuery(opts, PULLS_QUERY, { owner, name });
|
|
1874
1945
|
const repo = json.data?.repository;
|
|
1875
1946
|
if (!repo)
|
|
1876
1947
|
throw new GithubError(`GitHub: repository ${opts.repository} not found`);
|
|
@@ -1903,6 +1974,127 @@ function attachPullRequests(program, forge) {
|
|
|
1903
1974
|
return { ...issue, prs: prs.sort((a, b) => a.number - b.number) };
|
|
1904
1975
|
});
|
|
1905
1976
|
}
|
|
1977
|
+
// ../core/src/linear-write.ts
|
|
1978
|
+
var MAX_COMMENTS2 = 100;
|
|
1979
|
+
var TICKET_QUERY = `
|
|
1980
|
+
query Ticket($id: String!) {
|
|
1981
|
+
issue(id: $id) {
|
|
1982
|
+
id identifier title url branchName description
|
|
1983
|
+
state { id type }
|
|
1984
|
+
team { id states(first: 50) { nodes { id name type position } } }
|
|
1985
|
+
assignee { id }
|
|
1986
|
+
labels(first: 50) { nodes { id name parent { name } } }
|
|
1987
|
+
attachments(first: 50) { nodes { title url } }
|
|
1988
|
+
comments(first: ${MAX_COMMENTS2}, orderBy: createdAt) { pageInfo { hasNextPage } nodes { id createdAt body user { name } } }
|
|
1989
|
+
}
|
|
1990
|
+
}`;
|
|
1991
|
+
var GROUP_LABELS_QUERY = `
|
|
1992
|
+
query GroupLabels($group: String!) {
|
|
1993
|
+
issueLabels(first: 100, filter: { parent: { name: { eq: $group } } }) { nodes { id name team { id } } }
|
|
1994
|
+
}`;
|
|
1995
|
+
var VIEWER_QUERY = "query Viewer { viewer { id name } }";
|
|
1996
|
+
var UPDATE_MUTATION = `
|
|
1997
|
+
mutation Update($id: String!, $input: IssueUpdateInput!) { issueUpdate(id: $id, input: $input) { success } }`;
|
|
1998
|
+
var COMMENT_MUTATION = `
|
|
1999
|
+
mutation Comment($input: CommentCreateInput!) { commentCreate(input: $input) { success comment { id } } }`;
|
|
2000
|
+
var DELETE_COMMENT_MUTATION = `
|
|
2001
|
+
mutation DeleteComment($id: String!) { commentDelete(id: $id) { success } }`;
|
|
2002
|
+
var LINK_MUTATION = `
|
|
2003
|
+
mutation Link($issueId: String!, $url: String!, $title: String) {
|
|
2004
|
+
attachmentLinkURL(issueId: $issueId, url: $url, title: $title) { success }
|
|
2005
|
+
}`;
|
|
2006
|
+
function normalizeTicket(raw, groups) {
|
|
2007
|
+
const labels = raw.labels.nodes.map((l) => ({ id: l.id, name: l.name, group: l.parent?.name ?? null }));
|
|
2008
|
+
const prs = new Map;
|
|
2009
|
+
for (const a of raw.attachments.nodes) {
|
|
2010
|
+
const pr = parsePullRequestUrl(a.url, a.title);
|
|
2011
|
+
if (pr)
|
|
2012
|
+
prs.set(pr.url, pr);
|
|
2013
|
+
}
|
|
2014
|
+
for (const m of raw.description?.matchAll(/https:\/\/github\.com\/[^/\s]+\/[^/\s]+\/pull\/\d+/g) ?? []) {
|
|
2015
|
+
const pr = parsePullRequestUrl(m[0]);
|
|
2016
|
+
if (pr && !prs.has(pr.url))
|
|
2017
|
+
prs.set(pr.url, pr);
|
|
2018
|
+
}
|
|
2019
|
+
return {
|
|
2020
|
+
id: raw.identifier,
|
|
2021
|
+
uuid: raw.id,
|
|
2022
|
+
title: raw.title,
|
|
2023
|
+
url: raw.url,
|
|
2024
|
+
branchName: raw.branchName || null,
|
|
2025
|
+
statusType: raw.state.type,
|
|
2026
|
+
stateId: raw.state.id,
|
|
2027
|
+
teamId: raw.team.id,
|
|
2028
|
+
assigneeId: raw.assignee?.id ?? null,
|
|
2029
|
+
labels,
|
|
2030
|
+
...agentLabels(labels, groups),
|
|
2031
|
+
states: raw.team.states.nodes.map((s) => ({ ...s, type: s.type })).sort((a, b) => a.position - b.position),
|
|
2032
|
+
comments: raw.comments.nodes.map((c) => normalizeComment(c, raw.identifier)).sort((a, b) => b.createdAt.localeCompare(a.createdAt)),
|
|
2033
|
+
prs: [...prs.values()].sort((a, b) => a.number - b.number),
|
|
2034
|
+
commentsTruncated: !!raw.comments.pageInfo?.hasNextPage,
|
|
2035
|
+
warnings: raw.comments.pageInfo?.hasNextPage ? [`${raw.identifier}: more than ${MAX_COMMENTS2} comments; older claims are not read`] : []
|
|
2036
|
+
};
|
|
2037
|
+
}
|
|
2038
|
+
function ensure(ok, what) {
|
|
2039
|
+
if (!ok)
|
|
2040
|
+
throw new LinearError(`Linear refused to ${what}`);
|
|
2041
|
+
}
|
|
2042
|
+
function createLinearWriter(opts) {
|
|
2043
|
+
return {
|
|
2044
|
+
async viewer() {
|
|
2045
|
+
return (await gql(opts, VIEWER_QUERY, {})).viewer;
|
|
2046
|
+
},
|
|
2047
|
+
async readTicket(id) {
|
|
2048
|
+
const data = await gql(opts, TICKET_QUERY, { id }).catch((err) => {
|
|
2049
|
+
if (err instanceof LinearError && /not found/i.test(err.message))
|
|
2050
|
+
return { issue: null };
|
|
2051
|
+
throw err;
|
|
2052
|
+
});
|
|
2053
|
+
return data.issue ? normalizeTicket(data.issue, opts.labels) : null;
|
|
2054
|
+
},
|
|
2055
|
+
async groupLabels(group, teamId) {
|
|
2056
|
+
const data = await gql(opts, GROUP_LABELS_QUERY, { group });
|
|
2057
|
+
const usable = data.issueLabels.nodes.filter((l) => !l.team || l.team.id === teamId);
|
|
2058
|
+
const byName = new Map;
|
|
2059
|
+
for (const l of [...usable].sort((a, b) => Number(!!b.team) - Number(!!a.team)))
|
|
2060
|
+
if (!byName.has(l.name))
|
|
2061
|
+
byName.set(l.name, { id: l.id, name: l.name, group });
|
|
2062
|
+
return [...byName.values()];
|
|
2063
|
+
},
|
|
2064
|
+
async updateTicket(uuid, change) {
|
|
2065
|
+
const input = {};
|
|
2066
|
+
if (change.stateId)
|
|
2067
|
+
input.stateId = change.stateId;
|
|
2068
|
+
if (change.assigneeId)
|
|
2069
|
+
input.assigneeId = change.assigneeId;
|
|
2070
|
+
if (change.addLabelIds?.length)
|
|
2071
|
+
input.addedLabelIds = change.addLabelIds;
|
|
2072
|
+
if (change.removeLabelIds?.length)
|
|
2073
|
+
input.removedLabelIds = change.removeLabelIds;
|
|
2074
|
+
if (!Object.keys(input).length)
|
|
2075
|
+
return;
|
|
2076
|
+
const data = await gql(opts, UPDATE_MUTATION, { id: uuid, input });
|
|
2077
|
+
ensure(data.issueUpdate?.success, "update the ticket");
|
|
2078
|
+
},
|
|
2079
|
+
async comment(uuid, body) {
|
|
2080
|
+
const data = await gql(opts, COMMENT_MUTATION, { input: { issueId: uuid, body } });
|
|
2081
|
+
ensure(data.commentCreate?.success && !!data.commentCreate.comment, "post the comment");
|
|
2082
|
+
return { id: data.commentCreate.comment?.id ?? "" };
|
|
2083
|
+
},
|
|
2084
|
+
async deleteComment(id) {
|
|
2085
|
+
const data = await gql(opts, DELETE_COMMENT_MUTATION, { id });
|
|
2086
|
+
ensure(data.commentDelete?.success, "delete the comment");
|
|
2087
|
+
},
|
|
2088
|
+
async linkUrl(uuid, url, title) {
|
|
2089
|
+
const data = await gql(opts, LINK_MUTATION, {
|
|
2090
|
+
issueId: uuid,
|
|
2091
|
+
url,
|
|
2092
|
+
title
|
|
2093
|
+
});
|
|
2094
|
+
ensure(data.attachmentLinkURL?.success, "link the pull request");
|
|
2095
|
+
}
|
|
2096
|
+
};
|
|
2097
|
+
}
|
|
1906
2098
|
// ../core/src/machine.ts
|
|
1907
2099
|
import { randomBytes } from "node:crypto";
|
|
1908
2100
|
import { chmod, mkdir, open, readFile, rename, rm, stat } from "node:fs/promises";
|
|
@@ -2041,14 +2233,83 @@ async function ensurePersonalConfig(paths) {
|
|
|
2041
2233
|
await writePrivate(paths, paths.config, PERSONAL_CONFIG_TEMPLATE, 420);
|
|
2042
2234
|
return true;
|
|
2043
2235
|
}
|
|
2236
|
+
// ../core/src/phases.ts
|
|
2237
|
+
var TRANSITIONS = {
|
|
2238
|
+
planning: ["awaiting-approval", "implementing"],
|
|
2239
|
+
"awaiting-approval": ["planning", "implementing"],
|
|
2240
|
+
implementing: ["shipping"],
|
|
2241
|
+
shipping: ["implementing", "ready-to-merge"],
|
|
2242
|
+
"ready-to-merge": ["shipping"],
|
|
2243
|
+
blocked: ["planning", "awaiting-approval", "implementing", "shipping", "ready-to-merge"]
|
|
2244
|
+
};
|
|
2245
|
+
var isLabelPhase = (v) => LABEL_PHASES.includes(v);
|
|
2246
|
+
function transitionProblem(from, to) {
|
|
2247
|
+
if (from === null)
|
|
2248
|
+
return "the ticket has no agent phase; claim it first with `armada claim`";
|
|
2249
|
+
if (from === to || to === "blocked" || TRANSITIONS[from].includes(to))
|
|
2250
|
+
return null;
|
|
2251
|
+
const allowed = [...TRANSITIONS[from], "blocked", `${from} (status update)`].join(", ");
|
|
2252
|
+
return `cannot go from ${from} to ${to}; from ${from} a worker may report: ${allowed}`;
|
|
2253
|
+
}
|
|
2254
|
+
var FULL_SHA = /^[0-9a-f]{40}$/;
|
|
2255
|
+
function handBackProblems({ pr, repository, sha, requiredChecks }) {
|
|
2256
|
+
const problems = [];
|
|
2257
|
+
if (!sha)
|
|
2258
|
+
problems.push("--sha is required: the full 40-character head SHA of the pull request");
|
|
2259
|
+
else if (!FULL_SHA.test(sha))
|
|
2260
|
+
problems.push(`--sha must be the full 40-character commit SHA, got "${sha}" (${sha.length} characters)`);
|
|
2261
|
+
if (!pr) {
|
|
2262
|
+
problems.push("no pull request is linked to the ticket; pass --pr <number or URL>");
|
|
2263
|
+
return problems;
|
|
2264
|
+
}
|
|
2265
|
+
if (pr.repo.toLowerCase() !== repository.toLowerCase())
|
|
2266
|
+
problems.push(`pull request #${pr.number} is in ${pr.repo}, not in the project repository ${repository}`);
|
|
2267
|
+
if (pr.state && pr.state !== "open")
|
|
2268
|
+
problems.push(`pull request #${pr.number} is ${pr.state}, not open`);
|
|
2269
|
+
if (pr.draft)
|
|
2270
|
+
problems.push(`pull request #${pr.number} is a draft; mark it ready for review`);
|
|
2271
|
+
if (pr.mergeable === "CONFLICTING")
|
|
2272
|
+
problems.push(`pull request #${pr.number} conflicts with its base; rebase it`);
|
|
2273
|
+
if (!pr.headSha)
|
|
2274
|
+
problems.push(`the head of pull request #${pr.number} could not be read from GitHub`);
|
|
2275
|
+
else if (sha && FULL_SHA.test(sha) && pr.headSha !== sha)
|
|
2276
|
+
problems.push(`${sha} is not the head of pull request #${pr.number} (head is ${pr.headSha}); push, then report`);
|
|
2277
|
+
const checks = pr.checks ?? [];
|
|
2278
|
+
if (requiredChecks.length) {
|
|
2279
|
+
for (const name of requiredChecks) {
|
|
2280
|
+
const runs = checks.filter((c) => c.name === name);
|
|
2281
|
+
const bad = runs.find((c) => c.state !== "success");
|
|
2282
|
+
if (!runs.length)
|
|
2283
|
+
problems.push(`required check "${name}" has not reported on the head yet`);
|
|
2284
|
+
else if (bad)
|
|
2285
|
+
problems.push(`required check "${name}" is ${bad.state}`);
|
|
2286
|
+
}
|
|
2287
|
+
} else if (!checks.length) {
|
|
2288
|
+
problems.push("no CI check has reported on the head yet (or set [gates] required_checks in armada.toml)");
|
|
2289
|
+
} else {
|
|
2290
|
+
for (const c of checks)
|
|
2291
|
+
if (c.state !== "success")
|
|
2292
|
+
problems.push(`check "${c.name}" is ${c.state}`);
|
|
2293
|
+
}
|
|
2294
|
+
return problems;
|
|
2295
|
+
}
|
|
2044
2296
|
// ../core/src/status.ts
|
|
2045
2297
|
var STATUS_SCHEMA_VERSION = 1;
|
|
2046
|
-
function buildStatus({
|
|
2298
|
+
function buildStatus({
|
|
2299
|
+
config,
|
|
2300
|
+
program,
|
|
2301
|
+
forge,
|
|
2302
|
+
forgeError = null,
|
|
2303
|
+
lastEvents,
|
|
2304
|
+
extraWarnings = [],
|
|
2305
|
+
now
|
|
2306
|
+
}) {
|
|
2047
2307
|
const issues = attachPullRequests(program, forge);
|
|
2048
2308
|
const m = buildModel(issues, program.rootId);
|
|
2049
2309
|
const lanes = inFlight(m, program.comments, {
|
|
2050
2310
|
now: now.getTime(),
|
|
2051
|
-
silentAfterMinutes: config.policy.silentAfterMinutes
|
|
2311
|
+
silentAfterMinutes: config.policy.silentAfterMinutes,
|
|
2312
|
+
...lastEvents ? { lastEvents } : {}
|
|
2052
2313
|
});
|
|
2053
2314
|
const phaseOf = new Map(lanes.map((l) => [l.issue.id, l.phase]));
|
|
2054
2315
|
const prRef = (p) => ({
|
|
@@ -2080,6 +2341,7 @@ function buildStatus({ config, program, forge, forgeError = null, now }) {
|
|
|
2080
2341
|
agent: l.agent,
|
|
2081
2342
|
since: l.since,
|
|
2082
2343
|
lastUpdate: l.lastUpdate,
|
|
2344
|
+
lastReport: l.lastReport,
|
|
2083
2345
|
silent: l.flags.includes("silent"),
|
|
2084
2346
|
statusLine: l.statusLine ? { summary: l.statusLine.summary, at: l.statusLine.at, url: l.statusLine.url } : null,
|
|
2085
2347
|
pr: l.pr ? prRef(l.pr) : null,
|
|
@@ -2102,7 +2364,7 @@ function buildStatus({ config, program, forge, forgeError = null, now }) {
|
|
|
2102
2364
|
failingChecks: (pr.checks ?? []).filter((c) => c.state === "failure").map((c) => c.name),
|
|
2103
2365
|
ticket: ticket ? { id: ticket.id, phase: phaseOf.get(ticket.id) ?? ticket.agentPhase } : null
|
|
2104
2366
|
})) : null,
|
|
2105
|
-
warnings: [...program.warnings, ...forge?.warnings ?? []]
|
|
2367
|
+
warnings: [...program.warnings, ...forge?.warnings ?? [], ...extraWarnings]
|
|
2106
2368
|
};
|
|
2107
2369
|
}
|
|
2108
2370
|
async function loadStatus(config, opts) {
|
|
@@ -2120,11 +2382,489 @@ async function loadStatus(config, opts) {
|
|
|
2120
2382
|
...opts.fetch ? { fetch: opts.fetch } : {},
|
|
2121
2383
|
now
|
|
2122
2384
|
}).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)" });
|
|
2123
|
-
const
|
|
2124
|
-
|
|
2385
|
+
const eventsP = opts.lastEvents ? opts.lastEvents().then((events2) => ({ events: events2 }), (err) => ({
|
|
2386
|
+
warning: `Turso could not be read (${err instanceof Error ? err.message : String(err)}); silence is measured from Linear only`
|
|
2387
|
+
})) : Promise.resolve({});
|
|
2388
|
+
const [program, { forge, error }, events] = await Promise.all([programP, forgeP, eventsP]);
|
|
2389
|
+
return buildStatus({
|
|
2390
|
+
config,
|
|
2391
|
+
program,
|
|
2392
|
+
forge,
|
|
2393
|
+
forgeError: error,
|
|
2394
|
+
...events.events ? { lastEvents: events.events } : {},
|
|
2395
|
+
extraWarnings: events.warning ? [events.warning] : [],
|
|
2396
|
+
now: now()
|
|
2397
|
+
});
|
|
2398
|
+
}
|
|
2399
|
+
// ../core/src/turso.ts
|
|
2400
|
+
var MIGRATIONS = [
|
|
2401
|
+
{
|
|
2402
|
+
version: 1,
|
|
2403
|
+
statements: [
|
|
2404
|
+
`CREATE TABLE IF NOT EXISTS projects (
|
|
2405
|
+
slug TEXT PRIMARY KEY,
|
|
2406
|
+
name TEXT NOT NULL,
|
|
2407
|
+
repository TEXT NOT NULL,
|
|
2408
|
+
program_root TEXT NOT NULL,
|
|
2409
|
+
created_at TEXT NOT NULL,
|
|
2410
|
+
updated_at TEXT NOT NULL
|
|
2411
|
+
)`,
|
|
2412
|
+
`CREATE TABLE IF NOT EXISTS events (
|
|
2413
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
2414
|
+
project TEXT NOT NULL,
|
|
2415
|
+
ticket TEXT NOT NULL,
|
|
2416
|
+
kind TEXT NOT NULL,
|
|
2417
|
+
phase TEXT,
|
|
2418
|
+
message TEXT,
|
|
2419
|
+
runtime TEXT,
|
|
2420
|
+
handle TEXT,
|
|
2421
|
+
pr_url TEXT,
|
|
2422
|
+
head_sha TEXT,
|
|
2423
|
+
created_at TEXT NOT NULL
|
|
2424
|
+
)`,
|
|
2425
|
+
"CREATE INDEX IF NOT EXISTS events_by_ticket ON events (project, ticket, created_at)",
|
|
2426
|
+
`CREATE TABLE IF NOT EXISTS runtime_handles (
|
|
2427
|
+
project TEXT NOT NULL,
|
|
2428
|
+
ticket TEXT NOT NULL,
|
|
2429
|
+
runtime TEXT NOT NULL,
|
|
2430
|
+
handle TEXT NOT NULL,
|
|
2431
|
+
branch TEXT,
|
|
2432
|
+
claimed_at TEXT NOT NULL,
|
|
2433
|
+
released_at TEXT,
|
|
2434
|
+
PRIMARY KEY (project, ticket)
|
|
2435
|
+
)`,
|
|
2436
|
+
`CREATE TABLE IF NOT EXISTS inbox_items (
|
|
2437
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
2438
|
+
project TEXT NOT NULL,
|
|
2439
|
+
ticket TEXT,
|
|
2440
|
+
kind TEXT NOT NULL,
|
|
2441
|
+
recipient TEXT NOT NULL,
|
|
2442
|
+
author TEXT,
|
|
2443
|
+
body TEXT NOT NULL,
|
|
2444
|
+
created_at TEXT NOT NULL,
|
|
2445
|
+
resolved_at TEXT,
|
|
2446
|
+
resolution TEXT
|
|
2447
|
+
)`,
|
|
2448
|
+
"CREATE INDEX IF NOT EXISTS inbox_open ON inbox_items (project, recipient, resolved_at)",
|
|
2449
|
+
`CREATE TABLE IF NOT EXISTS leases (
|
|
2450
|
+
project TEXT NOT NULL,
|
|
2451
|
+
name TEXT NOT NULL,
|
|
2452
|
+
holder TEXT NOT NULL,
|
|
2453
|
+
acquired_at TEXT NOT NULL,
|
|
2454
|
+
expires_at TEXT NOT NULL,
|
|
2455
|
+
PRIMARY KEY (project, name)
|
|
2456
|
+
)`
|
|
2457
|
+
]
|
|
2458
|
+
}
|
|
2459
|
+
];
|
|
2460
|
+
var SCHEMA_VERSION = MIGRATIONS.at(-1)?.version ?? 0;
|
|
2461
|
+
|
|
2462
|
+
class TursoError extends Error {
|
|
2463
|
+
name = "TursoError";
|
|
2464
|
+
}
|
|
2465
|
+
function redact(err, token) {
|
|
2466
|
+
let message = err instanceof Error ? err.message : String(err);
|
|
2467
|
+
if (token)
|
|
2468
|
+
message = message.split(token).join("***");
|
|
2469
|
+
return message.replace(/(authToken=)[^&\s"']+/gi, "$1***");
|
|
2470
|
+
}
|
|
2471
|
+
async function openTurso({ url, token }) {
|
|
2472
|
+
let db;
|
|
2473
|
+
try {
|
|
2474
|
+
const { createClient } = await import("@libsql/client");
|
|
2475
|
+
db = createClient(token ? { url, authToken: token } : { url });
|
|
2476
|
+
} catch (err) {
|
|
2477
|
+
throw new TursoError(`cannot open the Turso database: ${redact(err, token)}`);
|
|
2478
|
+
}
|
|
2479
|
+
try {
|
|
2480
|
+
await migrate(db);
|
|
2481
|
+
} catch (err) {
|
|
2482
|
+
db.close();
|
|
2483
|
+
throw new TursoError(`Turso database unavailable: ${redact(err, token)}`);
|
|
2484
|
+
}
|
|
2485
|
+
return db;
|
|
2486
|
+
}
|
|
2487
|
+
async function migrate(db) {
|
|
2488
|
+
await db.execute("CREATE TABLE IF NOT EXISTS schema_migrations (version INTEGER PRIMARY KEY, applied_at TEXT NOT NULL)");
|
|
2489
|
+
const current = Number((await db.execute("SELECT max(version) AS v FROM schema_migrations")).rows[0]?.v ?? 0);
|
|
2490
|
+
for (const m of MIGRATIONS) {
|
|
2491
|
+
if (m.version <= current)
|
|
2492
|
+
continue;
|
|
2493
|
+
const stmts = [
|
|
2494
|
+
...m.statements,
|
|
2495
|
+
{
|
|
2496
|
+
sql: "INSERT OR IGNORE INTO schema_migrations (version, applied_at) VALUES (?, ?)",
|
|
2497
|
+
args: [m.version, new Date().toISOString()]
|
|
2498
|
+
}
|
|
2499
|
+
];
|
|
2500
|
+
await db.batch(stmts, "write");
|
|
2501
|
+
}
|
|
2502
|
+
return Math.max(current, SCHEMA_VERSION);
|
|
2503
|
+
}
|
|
2504
|
+
async function ensureProject(db, p, now = new Date) {
|
|
2505
|
+
const at = now.toISOString();
|
|
2506
|
+
await db.execute({
|
|
2507
|
+
sql: `INSERT OR IGNORE INTO projects (slug, name, repository, program_root, created_at, updated_at)
|
|
2508
|
+
VALUES (?, ?, ?, ?, ?, ?)`,
|
|
2509
|
+
args: [p.slug, p.name, p.repository, p.programRoot, at, at]
|
|
2510
|
+
});
|
|
2511
|
+
}
|
|
2512
|
+
async function recordEvent(db, e) {
|
|
2513
|
+
await db.execute({
|
|
2514
|
+
sql: `INSERT INTO events (project, ticket, kind, phase, message, runtime, handle, pr_url, head_sha, created_at)
|
|
2515
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
|
2516
|
+
args: [
|
|
2517
|
+
e.project,
|
|
2518
|
+
e.ticket,
|
|
2519
|
+
e.kind,
|
|
2520
|
+
e.phase ?? null,
|
|
2521
|
+
e.message ?? null,
|
|
2522
|
+
e.runtime ?? null,
|
|
2523
|
+
e.handle ?? null,
|
|
2524
|
+
e.prUrl ?? null,
|
|
2525
|
+
e.headSha ?? null,
|
|
2526
|
+
e.at.toISOString()
|
|
2527
|
+
]
|
|
2528
|
+
});
|
|
2529
|
+
}
|
|
2530
|
+
async function lastEventTimes(db, project) {
|
|
2531
|
+
const rs = await db.execute({
|
|
2532
|
+
sql: "SELECT ticket, max(created_at) AS at FROM events WHERE project = ? GROUP BY ticket",
|
|
2533
|
+
args: [project]
|
|
2534
|
+
});
|
|
2535
|
+
return Object.fromEntries(rs.rows.map((r) => [String(r.ticket), String(r.at)]));
|
|
2536
|
+
}
|
|
2537
|
+
async function saveRuntimeHandle(db, h) {
|
|
2538
|
+
await db.execute({
|
|
2539
|
+
sql: `INSERT INTO runtime_handles (project, ticket, runtime, handle, branch, claimed_at, released_at)
|
|
2540
|
+
VALUES (?, ?, ?, ?, ?, ?, NULL)
|
|
2541
|
+
ON CONFLICT (project, ticket) DO UPDATE SET
|
|
2542
|
+
claimed_at = CASE WHEN handle = excluded.handle AND released_at IS NULL
|
|
2543
|
+
THEN claimed_at ELSE excluded.claimed_at END,
|
|
2544
|
+
runtime = excluded.runtime, handle = excluded.handle, branch = excluded.branch,
|
|
2545
|
+
released_at = NULL`,
|
|
2546
|
+
args: [h.project, h.ticket, h.runtime, h.handle, h.branch, h.at.toISOString()]
|
|
2547
|
+
});
|
|
2548
|
+
}
|
|
2549
|
+
async function releaseRuntimeHandle(db, project, ticket, at) {
|
|
2550
|
+
await db.execute({
|
|
2551
|
+
sql: "UPDATE runtime_handles SET released_at = ? WHERE project = ? AND ticket = ? AND released_at IS NULL",
|
|
2552
|
+
args: [at.toISOString(), project, ticket]
|
|
2553
|
+
});
|
|
2554
|
+
}
|
|
2555
|
+
async function addInboxItem(db, item) {
|
|
2556
|
+
const rs = await db.execute({
|
|
2557
|
+
sql: `INSERT INTO inbox_items (project, ticket, kind, recipient, author, body, created_at)
|
|
2558
|
+
VALUES (?, ?, ?, ?, ?, ?, ?)`,
|
|
2559
|
+
args: [item.project, item.ticket, item.kind, item.recipient, item.author, item.body, item.at.toISOString()]
|
|
2560
|
+
});
|
|
2561
|
+
return Number(rs.lastInsertRowid);
|
|
2562
|
+
}
|
|
2563
|
+
async function putHandBack(db, item) {
|
|
2564
|
+
const updated = await db.execute({
|
|
2565
|
+
sql: `UPDATE inbox_items SET body = ?, author = ?, created_at = ?
|
|
2566
|
+
WHERE project = ? AND ticket = ? AND kind = 'hand-back' AND resolved_at IS NULL`,
|
|
2567
|
+
args: [item.body, item.author, item.at.toISOString(), item.project, item.ticket]
|
|
2568
|
+
});
|
|
2569
|
+
if (!updated.rowsAffected)
|
|
2570
|
+
await addInboxItem(db, { ...item, kind: "hand-back", recipient: "coordinator" });
|
|
2571
|
+
}
|
|
2572
|
+
async function openInboxItems(db, q) {
|
|
2573
|
+
const rs = await db.execute({
|
|
2574
|
+
sql: `SELECT id, project, ticket, kind, recipient, author, body, created_at FROM inbox_items
|
|
2575
|
+
WHERE project = ? AND recipient = ? AND resolved_at IS NULL ${q.ticket ? "AND ticket = ?" : ""}
|
|
2576
|
+
ORDER BY created_at, id`,
|
|
2577
|
+
args: q.ticket ? [q.project, q.recipient, q.ticket] : [q.project, q.recipient]
|
|
2578
|
+
});
|
|
2579
|
+
return rs.rows.map((r) => ({
|
|
2580
|
+
id: Number(r.id),
|
|
2581
|
+
project: String(r.project),
|
|
2582
|
+
ticket: r.ticket === null ? null : String(r.ticket),
|
|
2583
|
+
kind: String(r.kind),
|
|
2584
|
+
recipient: String(r.recipient),
|
|
2585
|
+
author: r.author === null ? null : String(r.author),
|
|
2586
|
+
body: String(r.body),
|
|
2587
|
+
createdAt: String(r.created_at)
|
|
2588
|
+
}));
|
|
2589
|
+
}
|
|
2590
|
+
// ../core/src/worker.ts
|
|
2591
|
+
class Refusal extends Error {
|
|
2592
|
+
name = "Refusal";
|
|
2593
|
+
}
|
|
2594
|
+
var TURSO_TIMEOUT_MS = 1e4;
|
|
2595
|
+
async function live(ctx, warnings, what, step) {
|
|
2596
|
+
const { db, warning } = await ctx.turso();
|
|
2597
|
+
if (!db) {
|
|
2598
|
+
if (warning)
|
|
2599
|
+
warnings.push(warning);
|
|
2600
|
+
return null;
|
|
2601
|
+
}
|
|
2602
|
+
let timer;
|
|
2603
|
+
try {
|
|
2604
|
+
return await Promise.race([
|
|
2605
|
+
step(db),
|
|
2606
|
+
new Promise((_, reject) => {
|
|
2607
|
+
timer = setTimeout(() => reject(new Error(`no answer within ${TURSO_TIMEOUT_MS / 1000} s`)), TURSO_TIMEOUT_MS);
|
|
2608
|
+
})
|
|
2609
|
+
]);
|
|
2610
|
+
} catch (err) {
|
|
2611
|
+
warnings.push(`Turso: could not ${what} (${redact(err)}); Linear is up to date`);
|
|
2612
|
+
return null;
|
|
2613
|
+
} finally {
|
|
2614
|
+
clearTimeout(timer);
|
|
2615
|
+
}
|
|
2616
|
+
}
|
|
2617
|
+
var project = (config) => ({
|
|
2618
|
+
slug: config.project.slug,
|
|
2619
|
+
name: config.project.name,
|
|
2620
|
+
repository: config.github.repository,
|
|
2621
|
+
programRoot: config.tracker.programRoot
|
|
2622
|
+
});
|
|
2623
|
+
async function readOpenTicket(ctx, id) {
|
|
2624
|
+
const ticket = await ctx.linear.readTicket(id);
|
|
2625
|
+
if (!ticket)
|
|
2626
|
+
throw new Refusal(`ticket ${id} not found in Linear`);
|
|
2627
|
+
if (ticket.statusType === "completed" || ticket.statusType === "canceled")
|
|
2628
|
+
throw new Refusal(`${ticket.id} is ${ticket.statusType}; there is nothing to work on`);
|
|
2629
|
+
return ticket;
|
|
2630
|
+
}
|
|
2631
|
+
function activeClaimComments(comments) {
|
|
2632
|
+
const asc = [...comments].sort((a, b) => a.createdAt.localeCompare(b.createdAt) || a.id.localeCompare(b.id));
|
|
2633
|
+
let active = [];
|
|
2634
|
+
for (const c of asc) {
|
|
2635
|
+
if (c.status?.phase === "released")
|
|
2636
|
+
active = [];
|
|
2637
|
+
if (c.claim)
|
|
2638
|
+
active.push(c);
|
|
2639
|
+
}
|
|
2640
|
+
return active;
|
|
2641
|
+
}
|
|
2642
|
+
function findLabel(labels, name, group) {
|
|
2643
|
+
const found = labels.find((l) => sameName(l.name, name));
|
|
2644
|
+
if (found)
|
|
2645
|
+
return found;
|
|
2646
|
+
const names = labels.map((l) => l.name).join(", ") || "none";
|
|
2647
|
+
throw new Refusal(`no "${name}" label in the "${group}" label group (available: ${names})`);
|
|
2648
|
+
}
|
|
2649
|
+
var others = (ticket, group, keep) => ticket.labels.filter((l) => l.group === group && l.id !== keep).map((l) => l.id);
|
|
2650
|
+
var firstState = (states, ...types) => {
|
|
2651
|
+
for (const type of types) {
|
|
2652
|
+
const s = states.find((x) => x.type === type);
|
|
2653
|
+
if (s)
|
|
2654
|
+
return s;
|
|
2655
|
+
}
|
|
2656
|
+
return null;
|
|
2657
|
+
};
|
|
2658
|
+
function claimLine(o) {
|
|
2659
|
+
return `Agent claim — runtime: ${o.runtime} · session: ${o.handle} · branch: ${o.branch ?? "unknown"} · started: ${o.started}`;
|
|
2660
|
+
}
|
|
2661
|
+
async function claimTicket(ctx, input) {
|
|
2662
|
+
const { config, linear } = ctx;
|
|
2663
|
+
const groups = config.tracker.labels;
|
|
2664
|
+
const ticket = await readOpenTicket(ctx, input.ticket);
|
|
2665
|
+
const [phaseLabels, runtimeLabels] = await Promise.all([
|
|
2666
|
+
linear.groupLabels(groups.phaseGroup, ticket.teamId),
|
|
2667
|
+
linear.groupLabels(groups.runtimeGroup, ticket.teamId)
|
|
2668
|
+
]);
|
|
2669
|
+
const planning = findLabel(phaseLabels, "planning", groups.phaseGroup);
|
|
2670
|
+
const runtime = findLabel(runtimeLabels, input.runtime, groups.runtimeGroup);
|
|
2671
|
+
const branch = input.branch ?? ticket.branchName;
|
|
2672
|
+
const warnings = [...ticket.warnings];
|
|
2673
|
+
const lines = [];
|
|
2674
|
+
if (ticket.commentsTruncated)
|
|
2675
|
+
throw new Refusal(`${ticket.id} has more comments than Armada reads, so an older claim may be hidden; claim it by hand`);
|
|
2676
|
+
const viewer = await linear.viewer();
|
|
2677
|
+
const inProgress = ticket.statusType === "started" ? null : firstState(ticket.states, "started");
|
|
2678
|
+
const held = activeClaimComments(ticket.comments);
|
|
2679
|
+
const holder = held[0]?.claim;
|
|
2680
|
+
const resuming = !!holder && holder.session === input.handle;
|
|
2681
|
+
if (!resuming) {
|
|
2682
|
+
if (holder)
|
|
2683
|
+
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\``);
|
|
2684
|
+
if (ticket.agentPhase)
|
|
2685
|
+
throw new Refusal(`${ticket.id} already carries the agent phase "${ticket.agentPhase}"; release it first with \`armada release\``);
|
|
2686
|
+
const started = ctx.now().toISOString();
|
|
2687
|
+
const body = `Agent status: planning — claimed by ${runtime.name} (${input.handle})
|
|
2688
|
+
|
|
2689
|
+
${claimLine({ runtime: runtime.name, handle: input.handle, branch, started })}`;
|
|
2690
|
+
const mine = await linear.comment(ticket.uuid, body);
|
|
2691
|
+
const after = await linear.readTicket(ticket.id);
|
|
2692
|
+
const winner = after ? activeClaimComments(after.comments)[0] : undefined;
|
|
2693
|
+
if (winner && winner.id !== mine.id) {
|
|
2694
|
+
await linear.deleteComment(mine.id);
|
|
2695
|
+
throw new Refusal(`${ticket.id} was claimed first by ${winner.claim?.runtime ?? "another worker"} · ${winner.claim?.session ?? "unknown session"}; your claim was withdrawn`);
|
|
2696
|
+
}
|
|
2697
|
+
lines.push(`Claimed ${ticket.id} for ${runtime.name} (${input.handle}).`);
|
|
2698
|
+
} else {
|
|
2699
|
+
lines.push(`${ticket.id} is already claimed by this session (${input.handle}); labels and state repaired.`);
|
|
2700
|
+
}
|
|
2701
|
+
if (ticket.statusType !== "started" && !inProgress)
|
|
2702
|
+
warnings.push(`the team of ${ticket.id} has no started state; the ticket was not moved`);
|
|
2703
|
+
const phaseLabel = resuming && ticket.agentPhase ? null : planning;
|
|
2704
|
+
await linear.updateTicket(ticket.uuid, {
|
|
2705
|
+
...inProgress ? { stateId: inProgress.id } : {},
|
|
2706
|
+
...ticket.assigneeId !== viewer.id ? { assigneeId: viewer.id } : {},
|
|
2707
|
+
addLabelIds: [phaseLabel, runtime].filter((l) => !!l && !ticket.labels.some((x) => x.id === l.id)).map((l) => l.id),
|
|
2708
|
+
removeLabelIds: [
|
|
2709
|
+
...phaseLabel ? others(ticket, groups.phaseGroup, phaseLabel.id) : [],
|
|
2710
|
+
...others(ticket, groups.runtimeGroup, runtime.id)
|
|
2711
|
+
]
|
|
2712
|
+
});
|
|
2713
|
+
lines.push(`${inProgress ? `Moved to ${inProgress.name}` : "State unchanged"}, assigned to ${viewer.name}, labels ${phaseLabel?.name ?? ticket.agentPhase} and ${runtime.name}.`);
|
|
2714
|
+
const at = ctx.now();
|
|
2715
|
+
await live(ctx, warnings, "record the claim", async (db) => {
|
|
2716
|
+
await ensureProject(db, project(config), at);
|
|
2717
|
+
await saveRuntimeHandle(db, {
|
|
2718
|
+
project: config.project.slug,
|
|
2719
|
+
ticket: ticket.id,
|
|
2720
|
+
runtime: runtime.name,
|
|
2721
|
+
handle: input.handle,
|
|
2722
|
+
branch,
|
|
2723
|
+
at
|
|
2724
|
+
});
|
|
2725
|
+
await recordEvent(db, {
|
|
2726
|
+
project: config.project.slug,
|
|
2727
|
+
ticket: ticket.id,
|
|
2728
|
+
kind: "claim",
|
|
2729
|
+
phase: phaseLabel ? "planning" : ticket.agentPhase,
|
|
2730
|
+
runtime: runtime.name,
|
|
2731
|
+
handle: input.handle,
|
|
2732
|
+
at
|
|
2733
|
+
});
|
|
2734
|
+
});
|
|
2735
|
+
return { ticket: ticket.id, url: ticket.url, lines, warnings, inbox: null };
|
|
2736
|
+
}
|
|
2737
|
+
function resolvePr(ticket, repository, pr) {
|
|
2738
|
+
if (pr) {
|
|
2739
|
+
const trimmed = pr.trim().replace(/^#/, "");
|
|
2740
|
+
if (/^\d+$/.test(trimmed)) {
|
|
2741
|
+
const url = `https://github.com/${repository}/pull/${trimmed}`;
|
|
2742
|
+
return parsePullRequestUrl(url);
|
|
2743
|
+
}
|
|
2744
|
+
const parsed = parsePullRequestUrl(trimmed);
|
|
2745
|
+
if (!parsed)
|
|
2746
|
+
throw new Refusal(`--pr must be a pull request number or URL, got "${pr}"`);
|
|
2747
|
+
return parsed;
|
|
2748
|
+
}
|
|
2749
|
+
const inRepo = ticket.prs.filter((p) => p.repo.toLowerCase() === repository.toLowerCase());
|
|
2750
|
+
return [...inRepo].sort((a, b) => b.number - a.number)[0] ?? null;
|
|
2751
|
+
}
|
|
2752
|
+
async function reportPhase(ctx, input) {
|
|
2753
|
+
const { config, linear } = ctx;
|
|
2754
|
+
const groups = config.tracker.labels;
|
|
2755
|
+
const ticket = await readOpenTicket(ctx, input.ticket);
|
|
2756
|
+
const problem = transitionProblem(ticket.agentPhase, input.phase);
|
|
2757
|
+
if (problem)
|
|
2758
|
+
throw new Refusal(`${ticket.id}: ${problem}`);
|
|
2759
|
+
const warnings = [...ticket.warnings];
|
|
2760
|
+
const message = input.message?.trim() ?? "";
|
|
2761
|
+
let pr = resolvePr(ticket, config.github.repository, input.pr);
|
|
2762
|
+
const sha = input.sha?.trim().toLowerCase() || null;
|
|
2763
|
+
let summary;
|
|
2764
|
+
let body;
|
|
2765
|
+
if (input.phase === "ready-to-merge") {
|
|
2766
|
+
const inRepo = !!pr && pr.repo.toLowerCase() === config.github.repository.toLowerCase();
|
|
2767
|
+
if (inRepo && !ctx.readPull)
|
|
2768
|
+
throw new Refusal("a hand-back needs GitHub to check the pull request head and CI; set GITHUB_TOKEN or run `gh auth login`");
|
|
2769
|
+
if (pr && inRepo && ctx.readPull) {
|
|
2770
|
+
const fresh = await ctx.readPull(pr.number);
|
|
2771
|
+
if (!fresh)
|
|
2772
|
+
throw new Refusal(`pull request #${pr.number} was not found in ${config.github.repository}`);
|
|
2773
|
+
pr = fresh;
|
|
2774
|
+
}
|
|
2775
|
+
const problems = handBackProblems({
|
|
2776
|
+
pr,
|
|
2777
|
+
repository: config.github.repository,
|
|
2778
|
+
sha,
|
|
2779
|
+
requiredChecks: config.gates.requiredChecks
|
|
2780
|
+
});
|
|
2781
|
+
if (problems.length)
|
|
2782
|
+
throw new Refusal(`${ticket.id}: hand-back refused:
|
|
2783
|
+
${problems.map((p) => ` - ${p}`).join(`
|
|
2784
|
+
`)}`);
|
|
2785
|
+
summary = `PR #${pr?.number}, head ${sha}, CI green`;
|
|
2786
|
+
body = message;
|
|
2787
|
+
} else {
|
|
2788
|
+
if (!message)
|
|
2789
|
+
throw new Refusal("--message is required: say what you did or what you are doing");
|
|
2790
|
+
const [first = "", ...rest] = message.split(`
|
|
2791
|
+
`);
|
|
2792
|
+
summary = first.trim();
|
|
2793
|
+
body = rest.join(`
|
|
2794
|
+
`).trim();
|
|
2795
|
+
}
|
|
2796
|
+
const target = ticket.agentPhase === input.phase ? null : findLabel(await linear.groupLabels(groups.phaseGroup, ticket.teamId), input.phase, groups.phaseGroup);
|
|
2797
|
+
if (pr && input.pr && !ticket.prs.some((p) => p.url === pr?.url)) {
|
|
2798
|
+
await linear.linkUrl(ticket.uuid, pr.url, pr.title || `Pull request #${pr.number}`);
|
|
2799
|
+
}
|
|
2800
|
+
if (target) {
|
|
2801
|
+
await linear.updateTicket(ticket.uuid, {
|
|
2802
|
+
addLabelIds: [target.id],
|
|
2803
|
+
removeLabelIds: others(ticket, groups.phaseGroup, target.id)
|
|
2804
|
+
});
|
|
2805
|
+
}
|
|
2806
|
+
const statusLine = `Agent status: ${input.phase} — ${summary}`;
|
|
2807
|
+
await linear.comment(ticket.uuid, body ? `${statusLine}
|
|
2808
|
+
|
|
2809
|
+
${body}` : statusLine);
|
|
2810
|
+
const lines = [
|
|
2811
|
+
ticket.agentPhase === input.phase ? `Status update posted on ${ticket.id} (${input.phase}).` : `${ticket.id}: ${ticket.agentPhase} → ${input.phase}.`
|
|
2812
|
+
];
|
|
2813
|
+
const at = ctx.now();
|
|
2814
|
+
const inbox = await live(ctx, warnings, "record the report", async (db) => {
|
|
2815
|
+
await ensureProject(db, project(config), at);
|
|
2816
|
+
await recordEvent(db, {
|
|
2817
|
+
project: config.project.slug,
|
|
2818
|
+
ticket: ticket.id,
|
|
2819
|
+
kind: "report",
|
|
2820
|
+
phase: input.phase,
|
|
2821
|
+
message: summary,
|
|
2822
|
+
prUrl: pr?.url ?? null,
|
|
2823
|
+
headSha: sha,
|
|
2824
|
+
at
|
|
2825
|
+
});
|
|
2826
|
+
if (input.phase === "ready-to-merge")
|
|
2827
|
+
await putHandBack(db, {
|
|
2828
|
+
project: config.project.slug,
|
|
2829
|
+
ticket: ticket.id,
|
|
2830
|
+
author: null,
|
|
2831
|
+
body: statusLine,
|
|
2832
|
+
at
|
|
2833
|
+
});
|
|
2834
|
+
return openInboxItems(db, { project: config.project.slug, recipient: "worker", ticket: ticket.id });
|
|
2835
|
+
});
|
|
2836
|
+
return { ticket: ticket.id, url: ticket.url, lines, warnings, inbox };
|
|
2837
|
+
}
|
|
2838
|
+
async function releaseTicket(ctx, input) {
|
|
2839
|
+
const { config, linear } = ctx;
|
|
2840
|
+
const groups = config.tracker.labels;
|
|
2841
|
+
const ticket = await readOpenTicket(ctx, input.ticket);
|
|
2842
|
+
if (!ticket.agentPhase && !ticket.agentRuntime && !activeClaimComments(ticket.comments).length)
|
|
2843
|
+
throw new Refusal(`${ticket.id} is not claimed; there is nothing to release`);
|
|
2844
|
+
const warnings = [...ticket.warnings];
|
|
2845
|
+
const back = ticket.statusType === "started" ? firstState(ticket.states, "unstarted", "backlog") : null;
|
|
2846
|
+
await linear.updateTicket(ticket.uuid, {
|
|
2847
|
+
...back ? { stateId: back.id } : {},
|
|
2848
|
+
removeLabelIds: [...others(ticket, groups.phaseGroup, null), ...others(ticket, groups.runtimeGroup, null)]
|
|
2849
|
+
});
|
|
2850
|
+
await linear.comment(ticket.uuid, `Agent status: released — ${input.reason.trim()}`);
|
|
2851
|
+
const lines = [`Released ${ticket.id}${back ? `, moved back to ${back.name}` : ""}.`];
|
|
2852
|
+
const at = ctx.now();
|
|
2853
|
+
await live(ctx, warnings, "record the release", async (db) => {
|
|
2854
|
+
await ensureProject(db, project(config), at);
|
|
2855
|
+
await releaseRuntimeHandle(db, config.project.slug, ticket.id, at);
|
|
2856
|
+
await recordEvent(db, {
|
|
2857
|
+
project: config.project.slug,
|
|
2858
|
+
ticket: ticket.id,
|
|
2859
|
+
kind: "release",
|
|
2860
|
+
message: input.reason.trim(),
|
|
2861
|
+
at
|
|
2862
|
+
});
|
|
2863
|
+
});
|
|
2864
|
+
return { ticket: ticket.id, url: ticket.url, lines, warnings, inbox: null };
|
|
2125
2865
|
}
|
|
2126
2866
|
// package.json
|
|
2127
|
-
var version = "0.
|
|
2867
|
+
var version = "0.1.1";
|
|
2128
2868
|
|
|
2129
2869
|
// src/io.ts
|
|
2130
2870
|
class UsageError extends Error {
|
|
@@ -2339,7 +3079,7 @@ function renderStatus(r) {
|
|
|
2339
3079
|
out.push(" nobody is working");
|
|
2340
3080
|
for (const t of r.inFlight) {
|
|
2341
3081
|
const who = [t.runtime, t.agent].filter(Boolean).join(" · ") || "unassigned";
|
|
2342
|
-
out.push(` ${pad(t.id, idWidth)} ${pad(phaseLabel(t), phaseWidth)} ${who} · updated ${relative(t.lastUpdate, now)}`);
|
|
3082
|
+
out.push(` ${pad(t.id, idWidth)} ${pad(phaseLabel(t), phaseWidth)} ${who} · ${t.lastReport ? `reported ${relative(t.lastReport, now)}` : `updated ${relative(t.lastUpdate, now)}`}`);
|
|
2343
3083
|
out.push(`${indent}${truncate(t.title, 90)}${t.spec ? ` [${t.spec}]` : ""}`);
|
|
2344
3084
|
if (t.statusLine?.summary)
|
|
2345
3085
|
out.push(`${indent}“${truncate(t.statusLine.summary, 100)}”`);
|
|
@@ -2388,24 +3128,208 @@ function renderStatus(r) {
|
|
|
2388
3128
|
`;
|
|
2389
3129
|
}
|
|
2390
3130
|
|
|
3131
|
+
// src/worker.ts
|
|
3132
|
+
var TURSO_OPEN_TIMEOUT_MS = 1e4;
|
|
3133
|
+
async function openLive(credentials2) {
|
|
3134
|
+
if (!credentials2.tursoUrl)
|
|
3135
|
+
return { db: null, warning: "Turso is not configured (ARMADA_TURSO_URL); live activity is not recorded" };
|
|
3136
|
+
let timer;
|
|
3137
|
+
const opening = openTurso({ url: credentials2.tursoUrl, token: credentials2.tursoToken });
|
|
3138
|
+
try {
|
|
3139
|
+
const db = await Promise.race([
|
|
3140
|
+
opening,
|
|
3141
|
+
new Promise((_, reject) => {
|
|
3142
|
+
timer = setTimeout(() => reject(new Error(`no answer within ${TURSO_OPEN_TIMEOUT_MS / 1000} s`)), TURSO_OPEN_TIMEOUT_MS);
|
|
3143
|
+
})
|
|
3144
|
+
]);
|
|
3145
|
+
return { db, warning: null };
|
|
3146
|
+
} catch (err) {
|
|
3147
|
+
opening.then((db) => db.close(), () => {});
|
|
3148
|
+
const reason = err instanceof Error ? err.message : String(err);
|
|
3149
|
+
return { db: null, warning: `Turso unavailable (${reason}); live activity is not recorded, Linear is` };
|
|
3150
|
+
} finally {
|
|
3151
|
+
clearTimeout(timer);
|
|
3152
|
+
}
|
|
3153
|
+
}
|
|
3154
|
+
function statusEvents(config2, credentials2) {
|
|
3155
|
+
if (!credentials2.tursoUrl)
|
|
3156
|
+
return;
|
|
3157
|
+
return async () => {
|
|
3158
|
+
const { db, warning } = await openLive(credentials2);
|
|
3159
|
+
if (!db)
|
|
3160
|
+
throw new Error(warning ?? "Turso unavailable");
|
|
3161
|
+
try {
|
|
3162
|
+
return await lastEventTimes(db, config2.project.slug);
|
|
3163
|
+
} finally {
|
|
3164
|
+
db.close();
|
|
3165
|
+
}
|
|
3166
|
+
};
|
|
3167
|
+
}
|
|
3168
|
+
var ID = /(?:^|[^a-z0-9])([a-z][a-z0-9]*-\d+)(?=$|[^a-z0-9])/gi;
|
|
3169
|
+
function ticketFromBranch(branch, programRoot) {
|
|
3170
|
+
const ids = [...branch.matchAll(ID)].map((m) => (m[1] ?? "").toUpperCase());
|
|
3171
|
+
const team = programRoot.split("-")[0]?.toUpperCase();
|
|
3172
|
+
return ids.find((id) => id.split("-")[0] === team) ?? ids[0] ?? null;
|
|
3173
|
+
}
|
|
3174
|
+
function currentTicket(io, config2, explicit) {
|
|
3175
|
+
const fromEnv2 = io.env.ARMADA_TICKET?.trim();
|
|
3176
|
+
const id = explicit?.trim() || fromEnv2 || (() => {
|
|
3177
|
+
const branch = io.gitBranch?.();
|
|
3178
|
+
return branch ? ticketFromBranch(branch, config2.tracker.programRoot) : null;
|
|
3179
|
+
})();
|
|
3180
|
+
if (!id)
|
|
3181
|
+
throw new UsageError("which ticket? pass --ticket <id>, set ARMADA_TICKET, or run on the ticket's branch");
|
|
3182
|
+
return id.toUpperCase();
|
|
3183
|
+
}
|
|
3184
|
+
async function context(io, config2, credentials2) {
|
|
3185
|
+
if (!credentials2.linearApiKey)
|
|
3186
|
+
throw new UsageError(missingKeyMessage(LINEAR_KEY));
|
|
3187
|
+
const linearOpts = {
|
|
3188
|
+
apiKey: credentials2.linearApiKey,
|
|
3189
|
+
labels: config2.tracker.labels,
|
|
3190
|
+
...io.fetch ? { fetch: io.fetch } : {}
|
|
3191
|
+
};
|
|
3192
|
+
const linear2 = io.linearWriter ? io.linearWriter(linearOpts) : createLinearWriter(linearOpts);
|
|
3193
|
+
let live2 = null;
|
|
3194
|
+
const token = credentials2.githubToken;
|
|
3195
|
+
const ctx = {
|
|
3196
|
+
config: config2,
|
|
3197
|
+
linear: linear2,
|
|
3198
|
+
turso: () => {
|
|
3199
|
+
live2 ??= openLive(credentials2);
|
|
3200
|
+
return live2;
|
|
3201
|
+
},
|
|
3202
|
+
readPull: token ? (number) => fetchPullRequest({
|
|
3203
|
+
token,
|
|
3204
|
+
repository: config2.github.repository,
|
|
3205
|
+
number,
|
|
3206
|
+
...io.fetch ? { fetch: io.fetch } : {}
|
|
3207
|
+
}) : null,
|
|
3208
|
+
now: io.now ?? (() => new Date)
|
|
3209
|
+
};
|
|
3210
|
+
const close = async () => {
|
|
3211
|
+
const opened = await live2;
|
|
3212
|
+
opened?.db?.close();
|
|
3213
|
+
};
|
|
3214
|
+
return { ctx, close };
|
|
3215
|
+
}
|
|
3216
|
+
function print(io, outcome, json) {
|
|
3217
|
+
if (json) {
|
|
3218
|
+
io.stdout(`${JSON.stringify(outcome, null, 2)}
|
|
3219
|
+
`);
|
|
3220
|
+
return;
|
|
3221
|
+
}
|
|
3222
|
+
const out = [...outcome.lines, outcome.url];
|
|
3223
|
+
if (outcome.inbox) {
|
|
3224
|
+
if (!outcome.inbox.length)
|
|
3225
|
+
out.push("Inbox: nothing waiting for you.");
|
|
3226
|
+
else {
|
|
3227
|
+
out.push(`Inbox (${outcome.inbox.length}) — read and act on these:`);
|
|
3228
|
+
for (const item of outcome.inbox)
|
|
3229
|
+
out.push(` #${item.id} ${item.kind}${item.author ? ` from ${item.author}` : ""} · ${item.createdAt}`, ...item.body.split(`
|
|
3230
|
+
`).map((l) => ` ${l}`));
|
|
3231
|
+
}
|
|
3232
|
+
}
|
|
3233
|
+
io.stdout(`${out.join(`
|
|
3234
|
+
`)}
|
|
3235
|
+
`);
|
|
3236
|
+
for (const w of outcome.warnings)
|
|
3237
|
+
io.stderr(`armada: warning: ${w}
|
|
3238
|
+
`);
|
|
3239
|
+
}
|
|
3240
|
+
async function withContext(io, config2, credentials2, json, act) {
|
|
3241
|
+
const { ctx, close } = await context(io, config2, credentials2);
|
|
3242
|
+
try {
|
|
3243
|
+
print(io, await act(ctx), json);
|
|
3244
|
+
return 0;
|
|
3245
|
+
} finally {
|
|
3246
|
+
await close();
|
|
3247
|
+
}
|
|
3248
|
+
}
|
|
3249
|
+
async function claim(io, config2, credentials2, a) {
|
|
3250
|
+
const [ticket, ...extra] = a.rest;
|
|
3251
|
+
if (!ticket)
|
|
3252
|
+
throw new UsageError("claim needs a ticket: armada claim <ticket> --runtime <name> --handle <id>");
|
|
3253
|
+
if (extra.length)
|
|
3254
|
+
throw new UsageError(`unexpected argument ${extra[0]}`);
|
|
3255
|
+
const runtime = a.options.runtime?.trim();
|
|
3256
|
+
const handle = a.options.handle?.trim();
|
|
3257
|
+
if (!runtime)
|
|
3258
|
+
throw new UsageError("--runtime is required, e.g. --runtime conductor");
|
|
3259
|
+
if (!handle)
|
|
3260
|
+
throw new UsageError("--handle is required: the runtime's id for this session, e.g. <workspace>/<session>");
|
|
3261
|
+
return withContext(io, config2, credentials2, a.json, (ctx) => claimTicket(ctx, {
|
|
3262
|
+
ticket: ticket.toUpperCase(),
|
|
3263
|
+
runtime,
|
|
3264
|
+
handle,
|
|
3265
|
+
...a.options.branch ? { branch: a.options.branch } : {}
|
|
3266
|
+
}));
|
|
3267
|
+
}
|
|
3268
|
+
async function report(io, config2, credentials2, a) {
|
|
3269
|
+
const [phase, ...extra] = a.rest;
|
|
3270
|
+
if (!phase || !isLabelPhase(phase))
|
|
3271
|
+
throw new UsageError(`report needs a phase: ${LABEL_PHASES.join(", ")}${phase ? ` (got "${phase}")` : ""}`);
|
|
3272
|
+
if (extra.length)
|
|
3273
|
+
throw new UsageError(`unexpected argument ${extra[0]}`);
|
|
3274
|
+
if (a.options.message !== undefined && a.options["message-file"] !== undefined)
|
|
3275
|
+
throw new UsageError("pass --message or --message-file, not both");
|
|
3276
|
+
let message = a.options.message ?? null;
|
|
3277
|
+
const file = a.options["message-file"];
|
|
3278
|
+
if (file !== undefined) {
|
|
3279
|
+
message = file === "-" ? await io.readStdin?.() ?? null : await io.readFile(file);
|
|
3280
|
+
if (message === null)
|
|
3281
|
+
throw new UsageError(`cannot read the message from ${file}`);
|
|
3282
|
+
}
|
|
3283
|
+
if (!message?.trim() && phase !== "ready-to-merge")
|
|
3284
|
+
throw new UsageError("--message is required: what you did or what you are doing (first line = summary)");
|
|
3285
|
+
const ticket = currentTicket(io, config2, a.options.ticket);
|
|
3286
|
+
return withContext(io, config2, credentials2, a.json, (ctx) => reportPhase(ctx, {
|
|
3287
|
+
ticket,
|
|
3288
|
+
phase,
|
|
3289
|
+
message,
|
|
3290
|
+
pr: a.options.pr ?? null,
|
|
3291
|
+
sha: a.options.sha ?? null
|
|
3292
|
+
}));
|
|
3293
|
+
}
|
|
3294
|
+
async function release(io, config2, credentials2, a) {
|
|
3295
|
+
if (a.rest.length)
|
|
3296
|
+
throw new UsageError(`unexpected argument ${a.rest[0]}`);
|
|
3297
|
+
const reason = a.options.reason?.trim();
|
|
3298
|
+
if (!reason)
|
|
3299
|
+
throw new UsageError("--reason is required: why the ticket is given back");
|
|
3300
|
+
const ticket = currentTicket(io, config2, a.options.ticket);
|
|
3301
|
+
return withContext(io, config2, credentials2, a.json, (ctx) => releaseTicket(ctx, { ticket, reason }));
|
|
3302
|
+
}
|
|
3303
|
+
|
|
2391
3304
|
// src/cli.ts
|
|
2392
3305
|
var USAGE = `Usage: armada <command> [options]
|
|
2393
3306
|
|
|
2394
3307
|
Commands:
|
|
2395
3308
|
status Tickets in flight, tickets ready to start and pull requests waiting
|
|
3309
|
+
claim <ticket> --runtime <name> --handle <id> [--branch <name>]
|
|
3310
|
+
Claim a ticket for this worker: In Progress, phase planning, runtime
|
|
3311
|
+
label and an Agent claim comment; refused if another worker holds it
|
|
3312
|
+
report <phase> [--message <text> | --message-file <path|->] [--pr <n|url>] [--sha <sha>]
|
|
3313
|
+
Report a phase (planning, awaiting-approval, implementing, shipping,
|
|
3314
|
+
blocked, ready-to-merge); the same phase again is a status update.
|
|
3315
|
+
ready-to-merge needs --sha (full 40 characters, the PR head) and green CI.
|
|
3316
|
+
Prints what waits in this worker's inbox.
|
|
3317
|
+
release --reason <text>
|
|
3318
|
+
Give the ticket back: agent labels removed, ticket moved back
|
|
2396
3319
|
auth login Ask for the missing keys (hidden input) and store them on this machine
|
|
2397
3320
|
auth status Show which keys are set and where each comes from, never their values
|
|
2398
3321
|
auth logout Remove Armada's keys from this machine
|
|
2399
3322
|
|
|
2400
3323
|
Options:
|
|
2401
|
-
--json Print the
|
|
3324
|
+
--json Print the result as JSON
|
|
2402
3325
|
--config <path> Use this armada.toml instead of searching from the current directory
|
|
3326
|
+
--ticket <id> Ticket for report and release; default ARMADA_TICKET, then the git branch
|
|
2403
3327
|
-h, --help Show this help
|
|
2404
3328
|
-v, --version Print the version
|
|
2405
3329
|
|
|
2406
3330
|
Keys (the environment always wins over the file):
|
|
2407
|
-
LINEAR_API_KEY Linear API key (required by status)
|
|
2408
|
-
ARMADA_TURSO_URL Turso database URL
|
|
3331
|
+
LINEAR_API_KEY Linear API key (required by status, claim, report, release)
|
|
3332
|
+
ARMADA_TURSO_URL Turso database URL (live activity; optional, a file: URL works locally)
|
|
2409
3333
|
ARMADA_TURSO_TOKEN Turso database token
|
|
2410
3334
|
GITHUB_TOKEN GitHub token; falls back to GH_TOKEN, then \`gh auth token\`
|
|
2411
3335
|
|
|
@@ -2414,24 +3338,41 @@ Files:
|
|
|
2414
3338
|
credentials KEY=value lines, mode 0600, written by \`armada auth login\`
|
|
2415
3339
|
config.toml personal defaults: language, [turso] url, [dashboard] url
|
|
2416
3340
|
`;
|
|
3341
|
+
var VALUE_OPTIONS = ["runtime", "handle", "branch", "ticket", "message", "message-file", "pr", "sha", "reason"];
|
|
3342
|
+
var COMMAND_OPTIONS = {
|
|
3343
|
+
claim: ["runtime", "handle", "branch"],
|
|
3344
|
+
report: ["ticket", "message", "message-file", "pr", "sha"],
|
|
3345
|
+
release: ["ticket", "reason"]
|
|
3346
|
+
};
|
|
2417
3347
|
function parseArgs(argv) {
|
|
2418
|
-
const args = {
|
|
3348
|
+
const args = {
|
|
3349
|
+
command: null,
|
|
3350
|
+
rest: [],
|
|
3351
|
+
json: false,
|
|
3352
|
+
config: null,
|
|
3353
|
+
help: false,
|
|
3354
|
+
version: false,
|
|
3355
|
+
options: {}
|
|
3356
|
+
};
|
|
2419
3357
|
for (let k = 0;k < argv.length; k++) {
|
|
2420
3358
|
const a = argv[k];
|
|
3359
|
+
const named = a?.match(/^--([a-z-]+)(?:=([\s\S]*))?$/);
|
|
3360
|
+
const name = named?.[1];
|
|
2421
3361
|
if (a === "--json")
|
|
2422
3362
|
args.json = true;
|
|
2423
3363
|
else if (a === "-h" || a === "--help")
|
|
2424
3364
|
args.help = true;
|
|
2425
3365
|
else if (a === "-v" || a === "--version")
|
|
2426
3366
|
args.version = true;
|
|
2427
|
-
else if (
|
|
2428
|
-
const v = argv[++k];
|
|
2429
|
-
if (
|
|
2430
|
-
throw new UsageError(
|
|
2431
|
-
|
|
2432
|
-
|
|
2433
|
-
|
|
2434
|
-
|
|
3367
|
+
else if (name && (name === "config" || VALUE_OPTIONS.includes(name))) {
|
|
3368
|
+
const v = named?.[2] ?? argv[++k];
|
|
3369
|
+
if (v === undefined)
|
|
3370
|
+
throw new UsageError(`--${name} needs a value`);
|
|
3371
|
+
if (name === "config")
|
|
3372
|
+
args.config = v;
|
|
3373
|
+
else
|
|
3374
|
+
args.options[name] = v;
|
|
3375
|
+
} else if (a?.startsWith("-"))
|
|
2435
3376
|
throw new UsageError(`unknown option ${a}`);
|
|
2436
3377
|
else if (!args.command && a)
|
|
2437
3378
|
args.command = a;
|
|
@@ -2461,17 +3402,20 @@ async function findConfig(io, explicit) {
|
|
|
2461
3402
|
async function status2(io, args) {
|
|
2462
3403
|
const { path, text } = await findConfig(io, args.config);
|
|
2463
3404
|
const config2 = parseConfig(text, path);
|
|
2464
|
-
const {
|
|
3405
|
+
const { credentials: credentials2 } = await loadCredentials(io);
|
|
3406
|
+
const { linearApiKey, githubToken } = credentials2;
|
|
2465
3407
|
if (!linearApiKey)
|
|
2466
3408
|
throw new UsageError(missingKeyMessage(LINEAR_KEY));
|
|
2467
|
-
const
|
|
3409
|
+
const events = statusEvents(config2, credentials2);
|
|
3410
|
+
const report2 = await loadStatus(config2, {
|
|
2468
3411
|
linearApiKey,
|
|
2469
3412
|
githubToken,
|
|
3413
|
+
...events ? { lastEvents: events } : {},
|
|
2470
3414
|
...io.fetch ? { fetch: io.fetch } : {},
|
|
2471
3415
|
...io.now ? { now: io.now } : {}
|
|
2472
3416
|
});
|
|
2473
|
-
io.stdout(args.json ? `${JSON.stringify(
|
|
2474
|
-
` : renderStatus(
|
|
3417
|
+
io.stdout(args.json ? `${JSON.stringify(report2, null, 2)}
|
|
3418
|
+
` : renderStatus(report2));
|
|
2475
3419
|
return 0;
|
|
2476
3420
|
}
|
|
2477
3421
|
function noExtra(rest) {
|
|
@@ -2490,6 +3434,17 @@ async function run(argv, io) {
|
|
|
2490
3434
|
(args.help ? io.stdout : io.stderr)(USAGE);
|
|
2491
3435
|
return args.help ? 0 : 2;
|
|
2492
3436
|
}
|
|
3437
|
+
const allowed = COMMAND_OPTIONS[args.command] ?? [];
|
|
3438
|
+
for (const name of Object.keys(args.options))
|
|
3439
|
+
if (!allowed.includes(name))
|
|
3440
|
+
throw new UsageError(`--${name} does not apply to ${args.command}`);
|
|
3441
|
+
const worker2 = { claim, report, release }[args.command];
|
|
3442
|
+
if (worker2) {
|
|
3443
|
+
const { path, text } = await findConfig(io, args.config);
|
|
3444
|
+
const config2 = parseConfig(text, path);
|
|
3445
|
+
const { credentials: credentials2 } = await loadCredentials(io);
|
|
3446
|
+
return await worker2(io, config2, credentials2, args);
|
|
3447
|
+
}
|
|
2493
3448
|
if (args.command === "status") {
|
|
2494
3449
|
noExtra(args.rest);
|
|
2495
3450
|
return await status2(io, args);
|
|
@@ -2550,6 +3505,22 @@ function echo(before, after) {
|
|
|
2550
3505
|
}
|
|
2551
3506
|
|
|
2552
3507
|
// src/main.ts
|
|
3508
|
+
function gitBranch() {
|
|
3509
|
+
try {
|
|
3510
|
+
const r = spawnSync("git", ["rev-parse", "--abbrev-ref", "HEAD"], { encoding: "utf8", timeout: 5000 });
|
|
3511
|
+
const branch = r.status === 0 ? r.stdout.trim() : "";
|
|
3512
|
+
return branch && branch !== "HEAD" ? branch : null;
|
|
3513
|
+
} catch {
|
|
3514
|
+
return null;
|
|
3515
|
+
}
|
|
3516
|
+
}
|
|
3517
|
+
async function readStdin() {
|
|
3518
|
+
let text = "";
|
|
3519
|
+
process.stdin.setEncoding("utf8");
|
|
3520
|
+
for await (const chunk of process.stdin)
|
|
3521
|
+
text += chunk;
|
|
3522
|
+
return text;
|
|
3523
|
+
}
|
|
2553
3524
|
function ghToken() {
|
|
2554
3525
|
try {
|
|
2555
3526
|
const r = spawnSync("gh", ["auth", "token"], { encoding: "utf8", timeout: 5000 });
|
|
@@ -2595,6 +3566,8 @@ var code = await run(process.argv.slice(2), {
|
|
|
2595
3566
|
stderr: (t) => process.stderr.write(t),
|
|
2596
3567
|
ghToken,
|
|
2597
3568
|
interactive: Boolean(process.stdin.isTTY && process.stderr.isTTY),
|
|
2598
|
-
prompt
|
|
3569
|
+
prompt,
|
|
3570
|
+
gitBranch,
|
|
3571
|
+
readStdin
|
|
2599
3572
|
});
|
|
2600
3573
|
process.stdout.write("", () => process.exit(code));
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@the-vibe-company/armada",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.1.1",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Run a fleet of coding agents on one project: the armada command line.",
|
|
6
6
|
"license": "MIT",
|
|
@@ -31,9 +31,12 @@
|
|
|
31
31
|
"access": "public"
|
|
32
32
|
},
|
|
33
33
|
"scripts": {
|
|
34
|
-
"build": "bun build src/bin.ts --target node --outfile dist/armada.js",
|
|
34
|
+
"build": "bun build src/bin.ts --target node --external @libsql/client --outfile dist/armada.js",
|
|
35
35
|
"prepack": "bun run build && cp ../../README.md ../../LICENSE ."
|
|
36
36
|
},
|
|
37
|
+
"dependencies": {
|
|
38
|
+
"@libsql/client": "0.18.0"
|
|
39
|
+
},
|
|
37
40
|
"devDependencies": {
|
|
38
41
|
"@armada/core": "workspace:*"
|
|
39
42
|
}
|