@the-vibe-company/armada 0.1.0 → 0.1.2
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 +58 -6
- package/dist/armada.js +2019 -50
- package/package.json +5 -2
package/dist/armada.js
CHANGED
|
@@ -1,11 +1,29 @@
|
|
|
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
|
-
import { spawnSync } from "node:child_process";
|
|
5
|
-
import { readFile as
|
|
22
|
+
import { spawn, spawnSync } from "node:child_process";
|
|
23
|
+
import { readFile as readFile3 } from "node:fs/promises";
|
|
6
24
|
|
|
7
25
|
// src/cli.ts
|
|
8
|
-
import { dirname, join as
|
|
26
|
+
import { dirname as dirname2, join as join4, resolve } from "node:path";
|
|
9
27
|
|
|
10
28
|
// ../../node_modules/.bun/smol-toml@1.9.0/node_modules/smol-toml/dist/error.js
|
|
11
29
|
/*!
|
|
@@ -982,6 +1000,7 @@ var CONFIG_DEFAULTS = {
|
|
|
982
1000
|
readyLabel: "ready-for-agent",
|
|
983
1001
|
phaseGroup: "Agent phase",
|
|
984
1002
|
runtimeGroup: "Agent runtime",
|
|
1003
|
+
runtimes: ["Claude Code", "Codex", "Conductor"],
|
|
985
1004
|
silentAfterMinutes: 15
|
|
986
1005
|
};
|
|
987
1006
|
|
|
@@ -1052,24 +1071,48 @@ function parseConfig(text, source = CONFIG_FILE) {
|
|
|
1052
1071
|
problems.push(`"policy" must be a table`);
|
|
1053
1072
|
const labelsT = isTable(labels) ? labels : {};
|
|
1054
1073
|
const policyT = isTable(policy) ? policy : {};
|
|
1074
|
+
const gates = raw.gates === undefined ? {} : raw.gates;
|
|
1075
|
+
if (!isTable(gates))
|
|
1076
|
+
problems.push(`"gates" must be a table`);
|
|
1077
|
+
const gatesT = isTable(gates) ? gates : {};
|
|
1055
1078
|
const known = [
|
|
1056
1079
|
["project", project, ["name", "slug"]],
|
|
1057
1080
|
["tracker", tracker, ["program_root", "language", "ready_label", "labels"]],
|
|
1058
|
-
["tracker.labels", labelsT, ["phase_group", "runtime_group"]],
|
|
1081
|
+
["tracker.labels", labelsT, ["phase_group", "runtime_group", "runtimes"]],
|
|
1059
1082
|
["github", github, ["repository"]],
|
|
1060
|
-
["
|
|
1083
|
+
["gates", gatesT, ["required_checks"]],
|
|
1084
|
+
["policy", policyT, ["silence_minutes", "silent_after_minutes"]]
|
|
1061
1085
|
];
|
|
1062
1086
|
for (const [path, t, keys] of known)
|
|
1063
1087
|
for (const key of Object.keys(t))
|
|
1064
1088
|
if (!keys.includes(key))
|
|
1065
1089
|
problems.push(`unknown key "${path}.${key}"`);
|
|
1090
|
+
let runtimes = [...CONFIG_DEFAULTS.runtimes];
|
|
1091
|
+
if (labelsT.runtimes !== undefined) {
|
|
1092
|
+
const v = labelsT.runtimes;
|
|
1093
|
+
if (Array.isArray(v) && v.length && v.every((x) => typeof x === "string" && x.trim()))
|
|
1094
|
+
runtimes = [...new Set(v.map((x) => x.trim()))];
|
|
1095
|
+
else
|
|
1096
|
+
problems.push(`"tracker.labels.runtimes" must be a non-empty list of names`);
|
|
1097
|
+
}
|
|
1098
|
+
const silenceKey = policyT.silence_minutes !== undefined ? "silence_minutes" : "silent_after_minutes";
|
|
1099
|
+
if (policyT.silence_minutes !== undefined && policyT.silent_after_minutes !== undefined)
|
|
1100
|
+
problems.push(`"policy.silent_after_minutes" is the old name of "policy.silence_minutes"; keep only one`);
|
|
1066
1101
|
let silentAfterMinutes = CONFIG_DEFAULTS.silentAfterMinutes;
|
|
1067
|
-
if (policyT
|
|
1068
|
-
const v = policyT
|
|
1102
|
+
if (policyT[silenceKey] !== undefined) {
|
|
1103
|
+
const v = policyT[silenceKey];
|
|
1069
1104
|
if (typeof v === "number" && Number.isFinite(v) && v > 0)
|
|
1070
1105
|
silentAfterMinutes = v;
|
|
1071
1106
|
else
|
|
1072
|
-
problems.push(`"policy
|
|
1107
|
+
problems.push(`"policy.${silenceKey}" must be a positive number`);
|
|
1108
|
+
}
|
|
1109
|
+
let requiredChecks = [];
|
|
1110
|
+
if (gatesT.required_checks !== undefined) {
|
|
1111
|
+
const v = gatesT.required_checks;
|
|
1112
|
+
if (Array.isArray(v) && v.every((c) => typeof c === "string" && c.trim()))
|
|
1113
|
+
requiredChecks = [...new Set(v.map((c) => c.trim()))];
|
|
1114
|
+
else
|
|
1115
|
+
problems.push(`"gates.required_checks" must be a list of check names`);
|
|
1073
1116
|
}
|
|
1074
1117
|
const config = {
|
|
1075
1118
|
project: {
|
|
@@ -1085,12 +1128,14 @@ function parseConfig(text, source = CONFIG_FILE) {
|
|
|
1085
1128
|
readyLabel: str(tracker, "tracker", "ready_label", { default: CONFIG_DEFAULTS.readyLabel }),
|
|
1086
1129
|
labels: {
|
|
1087
1130
|
phaseGroup: str(labelsT, "tracker.labels", "phase_group", { default: CONFIG_DEFAULTS.phaseGroup }),
|
|
1088
|
-
runtimeGroup: str(labelsT, "tracker.labels", "runtime_group", { default: CONFIG_DEFAULTS.runtimeGroup })
|
|
1131
|
+
runtimeGroup: str(labelsT, "tracker.labels", "runtime_group", { default: CONFIG_DEFAULTS.runtimeGroup }),
|
|
1132
|
+
runtimes
|
|
1089
1133
|
}
|
|
1090
1134
|
},
|
|
1091
1135
|
github: {
|
|
1092
1136
|
repository: str(github, "github", "repository", { pattern: REPOSITORY, hint: "owner/name" })
|
|
1093
1137
|
},
|
|
1138
|
+
gates: { requiredChecks },
|
|
1094
1139
|
policy: { silentAfterMinutes }
|
|
1095
1140
|
};
|
|
1096
1141
|
if (problems.length)
|
|
@@ -1098,6 +1143,38 @@ function parseConfig(text, source = CONFIG_FILE) {
|
|
|
1098
1143
|
config.tracker.programRoot = config.tracker.programRoot.toUpperCase();
|
|
1099
1144
|
return config;
|
|
1100
1145
|
}
|
|
1146
|
+
function configTemplate(p) {
|
|
1147
|
+
const q = JSON.stringify;
|
|
1148
|
+
return `# Armada configuration: one project = one repository + one tracker program root.
|
|
1149
|
+
# No secrets here: keys come from the environment or \`armada auth login\`.
|
|
1150
|
+
|
|
1151
|
+
[project]
|
|
1152
|
+
name = ${q(p.name)}
|
|
1153
|
+
slug = ${q(p.slug)} # stable id: lowercase letters, digits and dashes
|
|
1154
|
+
|
|
1155
|
+
[tracker]
|
|
1156
|
+
program_root = ${q(p.programRoot)} # Linear issue at the root of the program
|
|
1157
|
+
language = "en" # language of owner-facing output
|
|
1158
|
+
ready_label = "ready-for-agent"
|
|
1159
|
+
|
|
1160
|
+
[tracker.labels]
|
|
1161
|
+
phase_group = "Agent phase"
|
|
1162
|
+
runtime_group = "Agent runtime"
|
|
1163
|
+
runtimes = ["Claude Code", "Codex", "Conductor"]
|
|
1164
|
+
|
|
1165
|
+
[github]
|
|
1166
|
+
repository = ${q(p.repository)}
|
|
1167
|
+
|
|
1168
|
+
[gates]
|
|
1169
|
+
# required_checks = ["test"] # CI checks that must be green before a hand-back (default: every check)
|
|
1170
|
+
|
|
1171
|
+
[policy]
|
|
1172
|
+
silence_minutes = 15 # a worker with no report for longer than this shows as silent
|
|
1173
|
+
`;
|
|
1174
|
+
}
|
|
1175
|
+
function slugify(name) {
|
|
1176
|
+
return name.normalize("NFKD").replace(/[\u0300-\u036f]/g, "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "") || "project";
|
|
1177
|
+
}
|
|
1101
1178
|
// ../core/src/credentials.ts
|
|
1102
1179
|
var LINEAR_KEY = {
|
|
1103
1180
|
name: "linearApiKey",
|
|
@@ -1467,11 +1544,13 @@ function buildLane(m, allComments, issue, opts) {
|
|
|
1467
1544
|
const announcing = comments.find((c) => c.status?.phase === phase);
|
|
1468
1545
|
const since = announcing?.createdAt ?? (phase === "shipping" || phase === "ready-to-merge" ? pr?.createdAt : undefined) ?? claims[0]?.at ?? issue.startedAt ?? issue.updatedAt;
|
|
1469
1546
|
const lastUpdate = latest(issue.updatedAt, comments[0]?.createdAt, pr?.updatedAt, issue.startedAt);
|
|
1547
|
+
const lastReport = latest(comments.find((c) => c.status || c.claim)?.createdAt, claims.at(-1)?.at, opts.lastEvents?.[issue.id]) || null;
|
|
1470
1548
|
const openBlockers = m.openBlockersOf(issue);
|
|
1471
1549
|
const agent = issue.delegate ?? issue.assignee;
|
|
1472
1550
|
const flags = [];
|
|
1473
1551
|
const waitingOnHuman = NEEDS_HUMAN.includes(phase) || phase === "merged";
|
|
1474
|
-
|
|
1552
|
+
const alive = lastReport ?? lastUpdate;
|
|
1553
|
+
if (!waitingOnHuman && opts.now - Date.parse(alive) > opts.silentAfterMinutes * MIN)
|
|
1475
1554
|
flags.push("silent");
|
|
1476
1555
|
if (pr?.state === "open" && pr.ci === "failure")
|
|
1477
1556
|
flags.push("ci-failing");
|
|
@@ -1498,6 +1577,7 @@ function buildLane(m, allComments, issue, opts) {
|
|
|
1498
1577
|
agent,
|
|
1499
1578
|
since,
|
|
1500
1579
|
lastUpdate,
|
|
1580
|
+
lastReport,
|
|
1501
1581
|
statusLine: withStatus?.status ? {
|
|
1502
1582
|
summary: withStatus.status.summary,
|
|
1503
1583
|
at: withStatus.createdAt,
|
|
@@ -1584,11 +1664,20 @@ function parseStatusLine(body) {
|
|
|
1584
1664
|
const phase = LEGACY[raw] ?? raw;
|
|
1585
1665
|
return PHASES.includes(phase) ? { phase, summary: (m[2] ?? "").trim() } : null;
|
|
1586
1666
|
}
|
|
1667
|
+
var unescapeMarkdown = (line) => line.replace(/\\([!-/:-@[-`{-~])/g, "$1");
|
|
1668
|
+
var trimMarks = (v) => {
|
|
1669
|
+
const t = v.trim();
|
|
1670
|
+
return t.match(/^([*_`]+)(.+)\1$/)?.[2]?.trim() ?? t;
|
|
1671
|
+
};
|
|
1587
1672
|
function parseClaim(body, at, author) {
|
|
1588
|
-
const line =
|
|
1589
|
-
|
|
1673
|
+
const line = body.split(`
|
|
1674
|
+
`).map(unescapeMarkdown).find((l) => /^[\s*_`>]*Agent claim\b/i.test(l));
|
|
1675
|
+
if (!line)
|
|
1590
1676
|
return null;
|
|
1591
|
-
const field = (k) =>
|
|
1677
|
+
const field = (k) => {
|
|
1678
|
+
const v = line.match(new RegExp(`(?:${k})[*_\`]*\\s*:\\s*([^·|]+)`, "i"))?.[1];
|
|
1679
|
+
return v && trimMarks(v) || null;
|
|
1680
|
+
};
|
|
1592
1681
|
return {
|
|
1593
1682
|
runtime: field("runtime"),
|
|
1594
1683
|
session: field("session"),
|
|
@@ -1607,10 +1696,15 @@ function parsePullRequestUrl(url, title = "") {
|
|
|
1607
1696
|
return m?.[1] && m[2] ? { url: `https://github.com/${m[1]}/pull/${m[2]}`, repo: m[1], number: Number(m[2]), title } : null;
|
|
1608
1697
|
}
|
|
1609
1698
|
function agentLabels(labels, groups) {
|
|
1610
|
-
|
|
1699
|
+
let agentPhase = null;
|
|
1700
|
+
for (const l of labels)
|
|
1701
|
+
if (l.group === groups.phaseGroup)
|
|
1702
|
+
agentPhase ??= phaseNamed(l.name);
|
|
1611
1703
|
const runtime = labels.find((l) => l.group === groups.runtimeGroup);
|
|
1612
|
-
return { agentPhase
|
|
1704
|
+
return { agentPhase, agentRuntime: runtime?.name ?? null };
|
|
1613
1705
|
}
|
|
1706
|
+
var sameName = (a, b) => a.toLowerCase().replace(/[^a-z0-9]/g, "") === b.toLowerCase().replace(/[^a-z0-9]/g, "");
|
|
1707
|
+
var phaseNamed = (name) => LABEL_PHASES.find((p) => sameName(p, name)) ?? null;
|
|
1614
1708
|
function truncationWarnings(raw) {
|
|
1615
1709
|
const cut = (c, what) => c.pageInfo?.hasNextPage ? [`${raw.identifier}: more ${what} than Armada reads; some are ignored`] : [];
|
|
1616
1710
|
return [
|
|
@@ -1836,7 +1930,7 @@ function normalizePull(raw, repo) {
|
|
|
1836
1930
|
mergedAt: raw.mergedAt
|
|
1837
1931
|
};
|
|
1838
1932
|
}
|
|
1839
|
-
var
|
|
1933
|
+
var PULL_FIELDS = `
|
|
1840
1934
|
fragment P on PullRequest {
|
|
1841
1935
|
number title url state isDraft mergeable headRefName headRefOid createdAt updatedAt mergedAt
|
|
1842
1936
|
commits(last: 1) { nodes { commit { statusCheckRollup { state contexts(first: 50) { nodes {
|
|
@@ -1844,7 +1938,8 @@ var PULLS_QUERY = `
|
|
|
1844
1938
|
... on CheckRun { name status conclusion }
|
|
1845
1939
|
... on StatusContext { context state }
|
|
1846
1940
|
} } } } } }
|
|
1847
|
-
}
|
|
1941
|
+
}`;
|
|
1942
|
+
var PULLS_QUERY = `${PULL_FIELDS}
|
|
1848
1943
|
query Pulls($owner: String!, $name: String!) {
|
|
1849
1944
|
repository(owner: $owner, name: $name) {
|
|
1850
1945
|
open: pullRequests(states: OPEN, first: 100, orderBy: { field: UPDATED_AT, direction: DESC }) {
|
|
@@ -1854,14 +1949,13 @@ var PULLS_QUERY = `
|
|
|
1854
1949
|
closed: pullRequests(states: [MERGED, CLOSED], first: 30, orderBy: { field: UPDATED_AT, direction: DESC }) { nodes { ...P } }
|
|
1855
1950
|
}
|
|
1856
1951
|
}`;
|
|
1857
|
-
async function
|
|
1858
|
-
const [owner, name] = opts.repository.split("/");
|
|
1952
|
+
async function githubQuery(opts, query, variables) {
|
|
1859
1953
|
const doFetch = opts.fetch ?? fetch;
|
|
1860
1954
|
const timeoutMs = opts.timeoutMs ?? REQUEST_TIMEOUT_MS;
|
|
1861
1955
|
const res = await doFetch(GITHUB_GRAPHQL, {
|
|
1862
1956
|
method: "POST",
|
|
1863
1957
|
headers: { "Content-Type": "application/json", Authorization: `Bearer ${opts.token}` },
|
|
1864
|
-
body: JSON.stringify({ query
|
|
1958
|
+
body: JSON.stringify({ query, variables }),
|
|
1865
1959
|
signal: AbortSignal.timeout(timeoutMs)
|
|
1866
1960
|
}).catch((err) => {
|
|
1867
1961
|
throw new GithubError(`GitHub API unreachable: ${networkReason(err, timeoutMs)}`);
|
|
@@ -1871,6 +1965,25 @@ async function fetchForge(opts) {
|
|
|
1871
1965
|
const json = await res.json();
|
|
1872
1966
|
if (json.errors?.length)
|
|
1873
1967
|
throw new GithubError(`GitHub API: ${json.errors.map((e) => e.message).join("; ")}`);
|
|
1968
|
+
return json;
|
|
1969
|
+
}
|
|
1970
|
+
var PULL_QUERY = `${PULL_FIELDS}
|
|
1971
|
+
query Pull($owner: String!, $name: String!, $number: Int!) {
|
|
1972
|
+
repository(owner: $owner, name: $name) { pullRequest(number: $number) { ...P } }
|
|
1973
|
+
}`;
|
|
1974
|
+
async function fetchPullRequest(opts) {
|
|
1975
|
+
const [owner, name] = opts.repository.split("/");
|
|
1976
|
+
const json = await githubQuery(opts, PULL_QUERY, {
|
|
1977
|
+
owner,
|
|
1978
|
+
name,
|
|
1979
|
+
number: opts.number
|
|
1980
|
+
});
|
|
1981
|
+
const raw = json.data?.repository?.pullRequest;
|
|
1982
|
+
return raw ? normalizePull(raw, opts.repository) : null;
|
|
1983
|
+
}
|
|
1984
|
+
async function fetchForge(opts) {
|
|
1985
|
+
const [owner, name] = opts.repository.split("/");
|
|
1986
|
+
const json = await githubQuery(opts, PULLS_QUERY, { owner, name });
|
|
1874
1987
|
const repo = json.data?.repository;
|
|
1875
1988
|
if (!repo)
|
|
1876
1989
|
throw new GithubError(`GitHub: repository ${opts.repository} not found`);
|
|
@@ -1903,6 +2016,241 @@ function attachPullRequests(program, forge) {
|
|
|
1903
2016
|
return { ...issue, prs: prs.sort((a, b) => a.number - b.number) };
|
|
1904
2017
|
});
|
|
1905
2018
|
}
|
|
2019
|
+
var FILE_QUERY = `
|
|
2020
|
+
query ArmadaConfig($owner: String!, $name: String!, $expression: String!) {
|
|
2021
|
+
repository(owner: $owner, name: $name) { object(expression: $expression) { ... on Blob { text } } }
|
|
2022
|
+
}`;
|
|
2023
|
+
async function fetchDefaultBranchFile(opts) {
|
|
2024
|
+
const [owner, name] = opts.repository.split("/");
|
|
2025
|
+
const doFetch = opts.fetch ?? fetch;
|
|
2026
|
+
const timeoutMs = opts.timeoutMs ?? REQUEST_TIMEOUT_MS;
|
|
2027
|
+
const res = await doFetch(GITHUB_GRAPHQL, {
|
|
2028
|
+
method: "POST",
|
|
2029
|
+
headers: { "Content-Type": "application/json", Authorization: `Bearer ${opts.token}` },
|
|
2030
|
+
body: JSON.stringify({ query: FILE_QUERY, variables: { owner, name, expression: `HEAD:${opts.path}` } }),
|
|
2031
|
+
signal: AbortSignal.timeout(timeoutMs)
|
|
2032
|
+
}).catch((err) => {
|
|
2033
|
+
throw new GithubError(`GitHub API unreachable: ${networkReason(err, timeoutMs)}`);
|
|
2034
|
+
});
|
|
2035
|
+
if (!res.ok)
|
|
2036
|
+
throw new GithubError(`GitHub API HTTP ${res.status}`);
|
|
2037
|
+
const json = await res.json();
|
|
2038
|
+
if (json.errors?.length)
|
|
2039
|
+
throw new GithubError(`GitHub API: ${json.errors.map((e) => e.message).join("; ")}`);
|
|
2040
|
+
if (!json.data?.repository)
|
|
2041
|
+
throw new GithubError(`GitHub: repository ${opts.repository} not found`);
|
|
2042
|
+
return json.data.repository.object?.text ?? null;
|
|
2043
|
+
}
|
|
2044
|
+
// ../core/src/labels.ts
|
|
2045
|
+
function requiredLabels(config) {
|
|
2046
|
+
return [
|
|
2047
|
+
{ name: config.tracker.labels.phaseGroup, values: [...LABEL_PHASES] },
|
|
2048
|
+
{ name: config.tracker.labels.runtimeGroup, values: config.tracker.labels.runtimes }
|
|
2049
|
+
];
|
|
2050
|
+
}
|
|
2051
|
+
var LABELS_QUERY = `
|
|
2052
|
+
query Labels($root: String!, $filter: IssueLabelFilter) {
|
|
2053
|
+
issue(id: $root) { team { id key } }
|
|
2054
|
+
issueLabels(first: 50, filter: $filter) {
|
|
2055
|
+
nodes { id name isGroup team { id } children(first: 100) { nodes { name } } }
|
|
2056
|
+
}
|
|
2057
|
+
}`;
|
|
2058
|
+
async function readLabels(config, opts) {
|
|
2059
|
+
const wanted = requiredLabels(config);
|
|
2060
|
+
const data = await gql(opts, LABELS_QUERY, {
|
|
2061
|
+
root: config.tracker.programRoot,
|
|
2062
|
+
filter: { or: wanted.map((g) => ({ name: { eqIgnoreCase: g.name } })) }
|
|
2063
|
+
});
|
|
2064
|
+
if (!data.issue)
|
|
2065
|
+
throw new LinearError(`Linear: program root ${config.tracker.programRoot} not found`);
|
|
2066
|
+
const team = data.issue.team;
|
|
2067
|
+
const groups = wanted.map((w) => {
|
|
2068
|
+
const candidates = data.issueLabels.nodes.filter((n) => n.isGroup && n.name.toLowerCase() === w.name.toLowerCase());
|
|
2069
|
+
const group = candidates.find((n) => n.team?.id === team.id) ?? candidates.find((n) => n.team === null);
|
|
2070
|
+
const have = new Set(group?.children.nodes.map((c) => c.name.toLowerCase()) ?? []);
|
|
2071
|
+
return {
|
|
2072
|
+
name: w.name,
|
|
2073
|
+
id: group?.id ?? null,
|
|
2074
|
+
scope: group ? group.team ? "team" : "workspace" : null,
|
|
2075
|
+
missing: w.values.filter((v) => !have.has(v.toLowerCase()))
|
|
2076
|
+
};
|
|
2077
|
+
});
|
|
2078
|
+
return { team, groups };
|
|
2079
|
+
}
|
|
2080
|
+
function checkLabels(state) {
|
|
2081
|
+
return state.groups.map((g) => {
|
|
2082
|
+
const id = `labels:${g.name}`;
|
|
2083
|
+
if (!g.id)
|
|
2084
|
+
return {
|
|
2085
|
+
id,
|
|
2086
|
+
level: "error",
|
|
2087
|
+
message: `label group "${g.name}" does not exist in Linear team ${state.team.key}`,
|
|
2088
|
+
fix: "run `armada init` to create it with every value"
|
|
2089
|
+
};
|
|
2090
|
+
if (g.missing.length)
|
|
2091
|
+
return {
|
|
2092
|
+
id,
|
|
2093
|
+
level: "error",
|
|
2094
|
+
message: `label group "${g.name}" lacks ${g.missing.map((v) => `"${v}"`).join(", ")}`,
|
|
2095
|
+
fix: "run `armada init` to add the missing values"
|
|
2096
|
+
};
|
|
2097
|
+
return { id, level: "ok", message: `label group "${g.name}" has every value`, fix: null };
|
|
2098
|
+
});
|
|
2099
|
+
}
|
|
2100
|
+
var CREATE_LABEL = `
|
|
2101
|
+
mutation CreateLabel($input: IssueLabelCreateInput!) {
|
|
2102
|
+
issueLabelCreate(input: $input) { success issueLabel { id } }
|
|
2103
|
+
}`;
|
|
2104
|
+
async function createLabel(opts, input) {
|
|
2105
|
+
const data = await gql(opts, CREATE_LABEL, { input });
|
|
2106
|
+
const created = data.issueLabelCreate.issueLabel;
|
|
2107
|
+
if (!data.issueLabelCreate.success || !created)
|
|
2108
|
+
throw new LinearError(`Linear refused to create label ${input.name}`);
|
|
2109
|
+
return created.id;
|
|
2110
|
+
}
|
|
2111
|
+
async function createMissingLabels(state, opts) {
|
|
2112
|
+
const created = [];
|
|
2113
|
+
for (const g of state.groups) {
|
|
2114
|
+
let groupId = g.id;
|
|
2115
|
+
let teamId = g.scope === "workspace" ? null : state.team.id;
|
|
2116
|
+
if (!groupId) {
|
|
2117
|
+
groupId = await createLabel(opts, {
|
|
2118
|
+
name: g.name,
|
|
2119
|
+
teamId: state.team.id,
|
|
2120
|
+
isGroup: true,
|
|
2121
|
+
groupType: "singleSelect"
|
|
2122
|
+
});
|
|
2123
|
+
teamId = state.team.id;
|
|
2124
|
+
created.push(g.name);
|
|
2125
|
+
}
|
|
2126
|
+
for (const value of g.missing) {
|
|
2127
|
+
await createLabel(opts, { name: value, parentId: groupId, ...teamId ? { teamId } : {} });
|
|
2128
|
+
created.push(`${g.name} / ${value}`);
|
|
2129
|
+
}
|
|
2130
|
+
}
|
|
2131
|
+
return created;
|
|
2132
|
+
}
|
|
2133
|
+
// ../core/src/linear-write.ts
|
|
2134
|
+
var MAX_COMMENTS2 = 100;
|
|
2135
|
+
var TICKET_QUERY = `
|
|
2136
|
+
query Ticket($id: String!) {
|
|
2137
|
+
issue(id: $id) {
|
|
2138
|
+
id identifier title url branchName description
|
|
2139
|
+
state { id type }
|
|
2140
|
+
team { id states(first: 50) { nodes { id name type position } } }
|
|
2141
|
+
assignee { id }
|
|
2142
|
+
labels(first: 50) { nodes { id name parent { name } } }
|
|
2143
|
+
attachments(first: 50) { nodes { title url } }
|
|
2144
|
+
comments(first: ${MAX_COMMENTS2}, orderBy: createdAt) { pageInfo { hasNextPage } nodes { id createdAt body user { name } } }
|
|
2145
|
+
}
|
|
2146
|
+
}`;
|
|
2147
|
+
var GROUP_LABELS_QUERY = `
|
|
2148
|
+
query GroupLabels($group: String!) {
|
|
2149
|
+
issueLabels(first: 100, filter: { parent: { name: { eq: $group } } }) { nodes { id name team { id } } }
|
|
2150
|
+
}`;
|
|
2151
|
+
var VIEWER_QUERY = "query Viewer { viewer { id name } }";
|
|
2152
|
+
var UPDATE_MUTATION = `
|
|
2153
|
+
mutation Update($id: String!, $input: IssueUpdateInput!) { issueUpdate(id: $id, input: $input) { success } }`;
|
|
2154
|
+
var COMMENT_MUTATION = `
|
|
2155
|
+
mutation Comment($input: CommentCreateInput!) { commentCreate(input: $input) { success comment { id } } }`;
|
|
2156
|
+
var DELETE_COMMENT_MUTATION = `
|
|
2157
|
+
mutation DeleteComment($id: String!) { commentDelete(id: $id) { success } }`;
|
|
2158
|
+
var LINK_MUTATION = `
|
|
2159
|
+
mutation Link($issueId: String!, $url: String!, $title: String) {
|
|
2160
|
+
attachmentLinkURL(issueId: $issueId, url: $url, title: $title) { success }
|
|
2161
|
+
}`;
|
|
2162
|
+
function normalizeTicket(raw, groups) {
|
|
2163
|
+
const labels = raw.labels.nodes.map((l) => ({ id: l.id, name: l.name, group: l.parent?.name ?? null }));
|
|
2164
|
+
const prs = new Map;
|
|
2165
|
+
for (const a of raw.attachments.nodes) {
|
|
2166
|
+
const pr = parsePullRequestUrl(a.url, a.title);
|
|
2167
|
+
if (pr)
|
|
2168
|
+
prs.set(pr.url, pr);
|
|
2169
|
+
}
|
|
2170
|
+
for (const m of raw.description?.matchAll(/https:\/\/github\.com\/[^/\s]+\/[^/\s]+\/pull\/\d+/g) ?? []) {
|
|
2171
|
+
const pr = parsePullRequestUrl(m[0]);
|
|
2172
|
+
if (pr && !prs.has(pr.url))
|
|
2173
|
+
prs.set(pr.url, pr);
|
|
2174
|
+
}
|
|
2175
|
+
return {
|
|
2176
|
+
id: raw.identifier,
|
|
2177
|
+
uuid: raw.id,
|
|
2178
|
+
title: raw.title,
|
|
2179
|
+
url: raw.url,
|
|
2180
|
+
branchName: raw.branchName || null,
|
|
2181
|
+
statusType: raw.state.type,
|
|
2182
|
+
stateId: raw.state.id,
|
|
2183
|
+
teamId: raw.team.id,
|
|
2184
|
+
assigneeId: raw.assignee?.id ?? null,
|
|
2185
|
+
labels,
|
|
2186
|
+
...agentLabels(labels, groups),
|
|
2187
|
+
states: raw.team.states.nodes.map((s) => ({ ...s, type: s.type })).sort((a, b) => a.position - b.position),
|
|
2188
|
+
comments: raw.comments.nodes.map((c) => normalizeComment(c, raw.identifier)).sort((a, b) => b.createdAt.localeCompare(a.createdAt)),
|
|
2189
|
+
prs: [...prs.values()].sort((a, b) => a.number - b.number),
|
|
2190
|
+
commentsTruncated: !!raw.comments.pageInfo?.hasNextPage,
|
|
2191
|
+
warnings: raw.comments.pageInfo?.hasNextPage ? [`${raw.identifier}: more than ${MAX_COMMENTS2} comments; older claims are not read`] : []
|
|
2192
|
+
};
|
|
2193
|
+
}
|
|
2194
|
+
function ensure(ok, what) {
|
|
2195
|
+
if (!ok)
|
|
2196
|
+
throw new LinearError(`Linear refused to ${what}`);
|
|
2197
|
+
}
|
|
2198
|
+
function createLinearWriter(opts) {
|
|
2199
|
+
return {
|
|
2200
|
+
async viewer() {
|
|
2201
|
+
return (await gql(opts, VIEWER_QUERY, {})).viewer;
|
|
2202
|
+
},
|
|
2203
|
+
async readTicket(id) {
|
|
2204
|
+
const data = await gql(opts, TICKET_QUERY, { id }).catch((err) => {
|
|
2205
|
+
if (err instanceof LinearError && /not found/i.test(err.message))
|
|
2206
|
+
return { issue: null };
|
|
2207
|
+
throw err;
|
|
2208
|
+
});
|
|
2209
|
+
return data.issue ? normalizeTicket(data.issue, opts.labels) : null;
|
|
2210
|
+
},
|
|
2211
|
+
async groupLabels(group, teamId) {
|
|
2212
|
+
const data = await gql(opts, GROUP_LABELS_QUERY, { group });
|
|
2213
|
+
const usable = data.issueLabels.nodes.filter((l) => !l.team || l.team.id === teamId);
|
|
2214
|
+
const byName = new Map;
|
|
2215
|
+
for (const l of [...usable].sort((a, b) => Number(!!b.team) - Number(!!a.team)))
|
|
2216
|
+
if (!byName.has(l.name))
|
|
2217
|
+
byName.set(l.name, { id: l.id, name: l.name, group });
|
|
2218
|
+
return [...byName.values()];
|
|
2219
|
+
},
|
|
2220
|
+
async updateTicket(uuid, change) {
|
|
2221
|
+
const input = {};
|
|
2222
|
+
if (change.stateId)
|
|
2223
|
+
input.stateId = change.stateId;
|
|
2224
|
+
if (change.assigneeId)
|
|
2225
|
+
input.assigneeId = change.assigneeId;
|
|
2226
|
+
if (change.addLabelIds?.length)
|
|
2227
|
+
input.addedLabelIds = change.addLabelIds;
|
|
2228
|
+
if (change.removeLabelIds?.length)
|
|
2229
|
+
input.removedLabelIds = change.removeLabelIds;
|
|
2230
|
+
if (!Object.keys(input).length)
|
|
2231
|
+
return;
|
|
2232
|
+
const data = await gql(opts, UPDATE_MUTATION, { id: uuid, input });
|
|
2233
|
+
ensure(data.issueUpdate?.success, "update the ticket");
|
|
2234
|
+
},
|
|
2235
|
+
async comment(uuid, body) {
|
|
2236
|
+
const data = await gql(opts, COMMENT_MUTATION, { input: { issueId: uuid, body } });
|
|
2237
|
+
ensure(data.commentCreate?.success && !!data.commentCreate.comment, "post the comment");
|
|
2238
|
+
return { id: data.commentCreate.comment?.id ?? "" };
|
|
2239
|
+
},
|
|
2240
|
+
async deleteComment(id) {
|
|
2241
|
+
const data = await gql(opts, DELETE_COMMENT_MUTATION, { id });
|
|
2242
|
+
ensure(data.commentDelete?.success, "delete the comment");
|
|
2243
|
+
},
|
|
2244
|
+
async linkUrl(uuid, url, title) {
|
|
2245
|
+
const data = await gql(opts, LINK_MUTATION, {
|
|
2246
|
+
issueId: uuid,
|
|
2247
|
+
url,
|
|
2248
|
+
title
|
|
2249
|
+
});
|
|
2250
|
+
ensure(data.attachmentLinkURL?.success, "link the pull request");
|
|
2251
|
+
}
|
|
2252
|
+
};
|
|
2253
|
+
}
|
|
1906
2254
|
// ../core/src/machine.ts
|
|
1907
2255
|
import { randomBytes } from "node:crypto";
|
|
1908
2256
|
import { chmod, mkdir, open, readFile, rename, rm, stat } from "node:fs/promises";
|
|
@@ -2041,14 +2389,408 @@ async function ensurePersonalConfig(paths) {
|
|
|
2041
2389
|
await writePrivate(paths, paths.config, PERSONAL_CONFIG_TEMPLATE, 420);
|
|
2042
2390
|
return true;
|
|
2043
2391
|
}
|
|
2392
|
+
// ../core/src/phases.ts
|
|
2393
|
+
var TRANSITIONS = {
|
|
2394
|
+
planning: ["awaiting-approval", "implementing"],
|
|
2395
|
+
"awaiting-approval": ["planning", "implementing"],
|
|
2396
|
+
implementing: ["shipping"],
|
|
2397
|
+
shipping: ["implementing", "ready-to-merge"],
|
|
2398
|
+
"ready-to-merge": ["shipping"],
|
|
2399
|
+
blocked: ["planning", "awaiting-approval", "implementing", "shipping", "ready-to-merge"]
|
|
2400
|
+
};
|
|
2401
|
+
var isLabelPhase = (v) => LABEL_PHASES.includes(v);
|
|
2402
|
+
function transitionProblem(from, to) {
|
|
2403
|
+
if (from === null)
|
|
2404
|
+
return "the ticket has no agent phase; claim it first with `armada claim`";
|
|
2405
|
+
if (from === to || to === "blocked" || TRANSITIONS[from].includes(to))
|
|
2406
|
+
return null;
|
|
2407
|
+
const allowed = [...TRANSITIONS[from], "blocked", `${from} (status update)`].join(", ");
|
|
2408
|
+
return `cannot go from ${from} to ${to}; from ${from} a worker may report: ${allowed}`;
|
|
2409
|
+
}
|
|
2410
|
+
var FULL_SHA = /^[0-9a-f]{40}$/;
|
|
2411
|
+
function handBackProblems({ pr, repository, sha, requiredChecks }) {
|
|
2412
|
+
const problems = [];
|
|
2413
|
+
if (!sha)
|
|
2414
|
+
problems.push("--sha is required: the full 40-character head SHA of the pull request");
|
|
2415
|
+
else if (!FULL_SHA.test(sha))
|
|
2416
|
+
problems.push(`--sha must be the full 40-character commit SHA, got "${sha}" (${sha.length} characters)`);
|
|
2417
|
+
if (!pr) {
|
|
2418
|
+
problems.push("no pull request is linked to the ticket; pass --pr <number or URL>");
|
|
2419
|
+
return problems;
|
|
2420
|
+
}
|
|
2421
|
+
if (pr.repo.toLowerCase() !== repository.toLowerCase())
|
|
2422
|
+
problems.push(`pull request #${pr.number} is in ${pr.repo}, not in the project repository ${repository}`);
|
|
2423
|
+
if (pr.state && pr.state !== "open")
|
|
2424
|
+
problems.push(`pull request #${pr.number} is ${pr.state}, not open`);
|
|
2425
|
+
if (pr.draft)
|
|
2426
|
+
problems.push(`pull request #${pr.number} is a draft; mark it ready for review`);
|
|
2427
|
+
if (pr.mergeable === "CONFLICTING")
|
|
2428
|
+
problems.push(`pull request #${pr.number} conflicts with its base; rebase it`);
|
|
2429
|
+
if (!pr.headSha)
|
|
2430
|
+
problems.push(`the head of pull request #${pr.number} could not be read from GitHub`);
|
|
2431
|
+
else if (sha && FULL_SHA.test(sha) && pr.headSha !== sha)
|
|
2432
|
+
problems.push(`${sha} is not the head of pull request #${pr.number} (head is ${pr.headSha}); push, then report`);
|
|
2433
|
+
const checks = pr.checks ?? [];
|
|
2434
|
+
if (requiredChecks.length) {
|
|
2435
|
+
for (const name of requiredChecks) {
|
|
2436
|
+
const runs = checks.filter((c) => c.name === name);
|
|
2437
|
+
const bad = runs.find((c) => c.state !== "success");
|
|
2438
|
+
if (!runs.length)
|
|
2439
|
+
problems.push(`required check "${name}" has not reported on the head yet`);
|
|
2440
|
+
else if (bad)
|
|
2441
|
+
problems.push(`required check "${name}" is ${bad.state}`);
|
|
2442
|
+
}
|
|
2443
|
+
} else if (!checks.length) {
|
|
2444
|
+
problems.push("no CI check has reported on the head yet (or set [gates] required_checks in armada.toml)");
|
|
2445
|
+
} else {
|
|
2446
|
+
for (const c of checks)
|
|
2447
|
+
if (c.state !== "success")
|
|
2448
|
+
problems.push(`check "${c.name}" is ${c.state}`);
|
|
2449
|
+
}
|
|
2450
|
+
return problems;
|
|
2451
|
+
}
|
|
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
|
+
|
|
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
|
+
{
|
|
2531
|
+
name: "armada-coordinator",
|
|
2532
|
+
files: [
|
|
2533
|
+
{ path: "MERGE.md", content: MERGE_default },
|
|
2534
|
+
{ path: "SKILL.md", content: SKILL_default }
|
|
2535
|
+
]
|
|
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
|
+
}
|
|
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) ?? "");
|
|
2569
|
+
|
|
2570
|
+
class SetupError extends Error {
|
|
2571
|
+
name = "SetupError";
|
|
2572
|
+
}
|
|
2573
|
+
function parseSkillsLock(text) {
|
|
2574
|
+
if (text === null)
|
|
2575
|
+
return null;
|
|
2576
|
+
let raw;
|
|
2577
|
+
try {
|
|
2578
|
+
raw = JSON.parse(text);
|
|
2579
|
+
} catch {
|
|
2580
|
+
throw new SetupError(`${SKILLS_LOCK_FILE} is not valid JSON`);
|
|
2581
|
+
}
|
|
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
|
+
try {
|
|
2590
|
+
raw = parse(text);
|
|
2591
|
+
} 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}`);
|
|
2594
|
+
}
|
|
2595
|
+
const scripts = raw.scripts;
|
|
2596
|
+
const setup = scripts?.setup;
|
|
2597
|
+
return typeof setup === "string" ? setup.trim() : "";
|
|
2598
|
+
}
|
|
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)
|
|
2648
|
+
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}`));
|
|
2657
|
+
}
|
|
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;
|
|
2671
|
+
}
|
|
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;
|
|
2683
|
+
}
|
|
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
|
+
`;
|
|
2692
|
+
}
|
|
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;
|
|
2718
|
+
}
|
|
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
|
+
`;
|
|
2732
|
+
}
|
|
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;
|
|
2775
|
+
}
|
|
2776
|
+
var planIsEmpty = (p) => !p.writes.length && !p.removes.length && !p.links.length;
|
|
2044
2777
|
// ../core/src/status.ts
|
|
2045
2778
|
var STATUS_SCHEMA_VERSION = 1;
|
|
2046
|
-
function buildStatus({
|
|
2779
|
+
function buildStatus({
|
|
2780
|
+
config,
|
|
2781
|
+
program,
|
|
2782
|
+
forge,
|
|
2783
|
+
forgeError = null,
|
|
2784
|
+
lastEvents,
|
|
2785
|
+
extraWarnings = [],
|
|
2786
|
+
now
|
|
2787
|
+
}) {
|
|
2047
2788
|
const issues = attachPullRequests(program, forge);
|
|
2048
2789
|
const m = buildModel(issues, program.rootId);
|
|
2049
2790
|
const lanes = inFlight(m, program.comments, {
|
|
2050
2791
|
now: now.getTime(),
|
|
2051
|
-
silentAfterMinutes: config.policy.silentAfterMinutes
|
|
2792
|
+
silentAfterMinutes: config.policy.silentAfterMinutes,
|
|
2793
|
+
...lastEvents ? { lastEvents } : {}
|
|
2052
2794
|
});
|
|
2053
2795
|
const phaseOf = new Map(lanes.map((l) => [l.issue.id, l.phase]));
|
|
2054
2796
|
const prRef = (p) => ({
|
|
@@ -2080,6 +2822,7 @@ function buildStatus({ config, program, forge, forgeError = null, now }) {
|
|
|
2080
2822
|
agent: l.agent,
|
|
2081
2823
|
since: l.since,
|
|
2082
2824
|
lastUpdate: l.lastUpdate,
|
|
2825
|
+
lastReport: l.lastReport,
|
|
2083
2826
|
silent: l.flags.includes("silent"),
|
|
2084
2827
|
statusLine: l.statusLine ? { summary: l.statusLine.summary, at: l.statusLine.at, url: l.statusLine.url } : null,
|
|
2085
2828
|
pr: l.pr ? prRef(l.pr) : null,
|
|
@@ -2102,7 +2845,7 @@ function buildStatus({ config, program, forge, forgeError = null, now }) {
|
|
|
2102
2845
|
failingChecks: (pr.checks ?? []).filter((c) => c.state === "failure").map((c) => c.name),
|
|
2103
2846
|
ticket: ticket ? { id: ticket.id, phase: phaseOf.get(ticket.id) ?? ticket.agentPhase } : null
|
|
2104
2847
|
})) : null,
|
|
2105
|
-
warnings: [...program.warnings, ...forge?.warnings ?? []]
|
|
2848
|
+
warnings: [...program.warnings, ...forge?.warnings ?? [], ...extraWarnings]
|
|
2106
2849
|
};
|
|
2107
2850
|
}
|
|
2108
2851
|
async function loadStatus(config, opts) {
|
|
@@ -2120,11 +2863,513 @@ async function loadStatus(config, opts) {
|
|
|
2120
2863
|
...opts.fetch ? { fetch: opts.fetch } : {},
|
|
2121
2864
|
now
|
|
2122
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)" });
|
|
2123
|
-
const
|
|
2124
|
-
|
|
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()
|
|
2878
|
+
});
|
|
2879
|
+
}
|
|
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
|
+
)`
|
|
2938
|
+
]
|
|
2939
|
+
}
|
|
2940
|
+
];
|
|
2941
|
+
var SCHEMA_VERSION = MIGRATIONS.at(-1)?.version ?? 0;
|
|
2942
|
+
|
|
2943
|
+
class TursoError extends Error {
|
|
2944
|
+
name = "TursoError";
|
|
2945
|
+
}
|
|
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***");
|
|
2951
|
+
}
|
|
2952
|
+
async function openTurso({ url, token }) {
|
|
2953
|
+
let db;
|
|
2954
|
+
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)}`);
|
|
2959
|
+
}
|
|
2960
|
+
try {
|
|
2961
|
+
await migrate(db);
|
|
2962
|
+
} catch (err) {
|
|
2963
|
+
db.close();
|
|
2964
|
+
throw new TursoError(`Turso database unavailable: ${redact(err, token)}`);
|
|
2965
|
+
}
|
|
2966
|
+
return db;
|
|
2967
|
+
}
|
|
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");
|
|
2982
|
+
}
|
|
2983
|
+
return Math.max(current, SCHEMA_VERSION);
|
|
2984
|
+
}
|
|
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]
|
|
2996
|
+
});
|
|
2997
|
+
}
|
|
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]
|
|
3004
|
+
});
|
|
3005
|
+
}
|
|
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
|
+
}));
|
|
3016
|
+
}
|
|
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()
|
|
3032
|
+
]
|
|
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
|
+
}));
|
|
3094
|
+
}
|
|
3095
|
+
// ../core/src/worker.ts
|
|
3096
|
+
class Refusal extends Error {
|
|
3097
|
+
name = "Refusal";
|
|
3098
|
+
}
|
|
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);
|
|
3105
|
+
return null;
|
|
3106
|
+
}
|
|
3107
|
+
let timer;
|
|
3108
|
+
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
|
+
]);
|
|
3115
|
+
} catch (err) {
|
|
3116
|
+
warnings.push(`Turso: could not ${what} (${redact(err)}); Linear is up to date`);
|
|
3117
|
+
return null;
|
|
3118
|
+
} finally {
|
|
3119
|
+
clearTimeout(timer);
|
|
3120
|
+
}
|
|
3121
|
+
}
|
|
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);
|
|
3144
|
+
}
|
|
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;
|
|
3160
|
+
}
|
|
3161
|
+
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
|
+
}
|
|
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})
|
|
3193
|
+
|
|
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 };
|
|
3241
|
+
}
|
|
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;
|
|
3256
|
+
}
|
|
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;
|
|
3279
|
+
}
|
|
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}`);
|
|
3304
|
+
}
|
|
3305
|
+
if (target) {
|
|
3306
|
+
await linear.updateTicket(ticket.uuid, {
|
|
3307
|
+
addLabelIds: [target.id],
|
|
3308
|
+
removeLabelIds: others(ticket, groups.phaseGroup, target.id)
|
|
3309
|
+
});
|
|
3310
|
+
}
|
|
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 });
|
|
3340
|
+
});
|
|
3341
|
+
return { ticket: ticket.id, url: ticket.url, lines, warnings, inbox };
|
|
3342
|
+
}
|
|
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)]
|
|
3354
|
+
});
|
|
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
|
+
});
|
|
3368
|
+
});
|
|
3369
|
+
return { ticket: ticket.id, url: ticket.url, lines, warnings, inbox: null };
|
|
2125
3370
|
}
|
|
2126
3371
|
// package.json
|
|
2127
|
-
var version = "0.1.
|
|
3372
|
+
var version = "0.1.2";
|
|
2128
3373
|
|
|
2129
3374
|
// src/io.ts
|
|
2130
3375
|
class UsageError extends Error {
|
|
@@ -2295,9 +3540,369 @@ async function authLogout(io) {
|
|
|
2295
3540
|
return 0;
|
|
2296
3541
|
}
|
|
2297
3542
|
|
|
3543
|
+
// src/repo.ts
|
|
3544
|
+
import { lstat, mkdir as mkdir2, readdir, readFile as readFile2, readlink, rm as rm2, symlink, writeFile } from "node:fs/promises";
|
|
3545
|
+
import { dirname, join as join2, relative, sep } from "node:path";
|
|
3546
|
+
var absent = (err) => {
|
|
3547
|
+
const code = err.code;
|
|
3548
|
+
return code === "ENOENT" || code === "ENOTDIR" || code === "EISDIR";
|
|
3549
|
+
};
|
|
3550
|
+
async function collect(base, dir, out) {
|
|
3551
|
+
for (const entry of await readdir(dir, { withFileTypes: true })) {
|
|
3552
|
+
const full = join2(dir, entry.name);
|
|
3553
|
+
if (entry.isDirectory()) {
|
|
3554
|
+
if (entry.name !== ".git" && entry.name !== "node_modules")
|
|
3555
|
+
await collect(base, full, out);
|
|
3556
|
+
} else if (entry.isFile())
|
|
3557
|
+
out.push({ path: relative(base, full).split(sep).join("/"), content: await readFile2(full) });
|
|
3558
|
+
}
|
|
3559
|
+
}
|
|
3560
|
+
function fsRepoView(root) {
|
|
3561
|
+
return {
|
|
3562
|
+
readFile: (path) => readFile2(join2(root, path), "utf8").catch((err) => {
|
|
3563
|
+
if (absent(err))
|
|
3564
|
+
return null;
|
|
3565
|
+
throw err;
|
|
3566
|
+
}),
|
|
3567
|
+
readLink: (path) => readlink(join2(root, path)).catch((err) => {
|
|
3568
|
+
if (absent(err) || err.code === "EINVAL")
|
|
3569
|
+
return null;
|
|
3570
|
+
throw err;
|
|
3571
|
+
}),
|
|
3572
|
+
readFolder: async (path) => {
|
|
3573
|
+
const out = [];
|
|
3574
|
+
try {
|
|
3575
|
+
await collect(join2(root, path), join2(root, path), out);
|
|
3576
|
+
} catch (err) {
|
|
3577
|
+
if (absent(err))
|
|
3578
|
+
return null;
|
|
3579
|
+
throw err;
|
|
3580
|
+
}
|
|
3581
|
+
return out;
|
|
3582
|
+
}
|
|
3583
|
+
};
|
|
3584
|
+
}
|
|
3585
|
+
async function assertNoLinkedParent(root, path) {
|
|
3586
|
+
const parts = path.split("/").slice(0, -1);
|
|
3587
|
+
for (let k = 1;k <= parts.length; k++) {
|
|
3588
|
+
const parent = parts.slice(0, k).join("/");
|
|
3589
|
+
if ((await lstat(join2(root, parent)).catch(() => null))?.isSymbolicLink())
|
|
3590
|
+
throw new CommandError(`${parent} is a link; Armada does not write through it. Replace it with a folder first.`);
|
|
3591
|
+
}
|
|
3592
|
+
}
|
|
3593
|
+
async function applyPlan(root, plan) {
|
|
3594
|
+
for (const path of [...plan.removes, ...plan.writes.map((w) => w.path), ...plan.links.map((l) => l.path)])
|
|
3595
|
+
await assertNoLinkedParent(root, path);
|
|
3596
|
+
for (const path of plan.removes)
|
|
3597
|
+
await rm2(join2(root, path), { force: true });
|
|
3598
|
+
for (const w of plan.writes) {
|
|
3599
|
+
const full = join2(root, w.path);
|
|
3600
|
+
await mkdir2(dirname(full), { recursive: true });
|
|
3601
|
+
await writeFile(full, w.content);
|
|
3602
|
+
}
|
|
3603
|
+
for (const l of plan.links) {
|
|
3604
|
+
const full = join2(root, l.path);
|
|
3605
|
+
await mkdir2(dirname(full), { recursive: true });
|
|
3606
|
+
if (await lstat(full).catch(() => null))
|
|
3607
|
+
await rm2(full, { recursive: true, force: true });
|
|
3608
|
+
await symlink(l.target, full);
|
|
3609
|
+
}
|
|
3610
|
+
}
|
|
3611
|
+
|
|
3612
|
+
class CommandError extends Error {
|
|
3613
|
+
name = "CommandError";
|
|
3614
|
+
}
|
|
3615
|
+
function requireExec(io) {
|
|
3616
|
+
if (!io.exec)
|
|
3617
|
+
throw new CommandError("this command needs git and gh, which this environment cannot run");
|
|
3618
|
+
return io.exec;
|
|
3619
|
+
}
|
|
3620
|
+
async function sh(exec, cwd, command, args) {
|
|
3621
|
+
const r = await exec(command, args, { cwd }).catch((err) => {
|
|
3622
|
+
throw new CommandError(`could not run ${command}: ${err instanceof Error ? err.message : String(err)}. Is ${command} installed?`);
|
|
3623
|
+
});
|
|
3624
|
+
if (r.code !== 0)
|
|
3625
|
+
throw new CommandError(`${command} ${args[0] ?? ""} failed: ${(r.stderr || r.stdout).trim() || `exit ${r.code}`}`);
|
|
3626
|
+
return r.stdout.trim();
|
|
3627
|
+
}
|
|
3628
|
+
async function gitRoot(exec, cwd) {
|
|
3629
|
+
const r = await exec("git", ["rev-parse", "--show-toplevel"], { cwd }).catch(() => null);
|
|
3630
|
+
return r && r.code === 0 ? r.stdout.trim() : null;
|
|
3631
|
+
}
|
|
3632
|
+
|
|
3633
|
+
// src/doctor.ts
|
|
3634
|
+
async function labelChecks(io, root) {
|
|
3635
|
+
const text = await fsRepoView(root).readFile(CONFIG_FILE);
|
|
3636
|
+
if (text === null)
|
|
3637
|
+
return [];
|
|
3638
|
+
let config2;
|
|
3639
|
+
try {
|
|
3640
|
+
config2 = parseConfig(text, CONFIG_FILE);
|
|
3641
|
+
} catch (err) {
|
|
3642
|
+
if (err instanceof ConfigError)
|
|
3643
|
+
return [];
|
|
3644
|
+
throw err;
|
|
3645
|
+
}
|
|
3646
|
+
const { linearApiKey } = (await loadCredentials(io)).credentials;
|
|
3647
|
+
if (!linearApiKey)
|
|
3648
|
+
return [
|
|
3649
|
+
{
|
|
3650
|
+
id: "labels",
|
|
3651
|
+
level: "warning",
|
|
3652
|
+
message: `Linear labels not checked: ${LINEAR_KEY.variable} is not set`,
|
|
3653
|
+
fix: `set ${LINEAR_KEY.variable} or run \`armada auth login\`, then run doctor again`
|
|
3654
|
+
}
|
|
3655
|
+
];
|
|
3656
|
+
try {
|
|
3657
|
+
const state = await readLabels(config2, { apiKey: linearApiKey, ...io.fetch ? { fetch: io.fetch } : {} });
|
|
3658
|
+
return checkLabels(state);
|
|
3659
|
+
} catch (err) {
|
|
3660
|
+
return [
|
|
3661
|
+
{
|
|
3662
|
+
id: "labels",
|
|
3663
|
+
level: "warning",
|
|
3664
|
+
message: `Linear labels not checked: ${err instanceof Error ? err.message : String(err)}`,
|
|
3665
|
+
fix: "run doctor again once Linear answers"
|
|
3666
|
+
}
|
|
3667
|
+
];
|
|
3668
|
+
}
|
|
3669
|
+
}
|
|
3670
|
+
async function buildDoctor(io, armadaVersion) {
|
|
3671
|
+
const root = (io.exec ? await gitRoot(io.exec, io.cwd) : null) ?? io.cwd;
|
|
3672
|
+
const checks = [...await checkRepository(fsRepoView(root), armadaVersion), ...await labelChecks(io, root)];
|
|
3673
|
+
return {
|
|
3674
|
+
schemaVersion: 1,
|
|
3675
|
+
root,
|
|
3676
|
+
armadaVersion,
|
|
3677
|
+
checks,
|
|
3678
|
+
errors: checks.filter((c) => c.level === "error").length,
|
|
3679
|
+
warnings: checks.filter((c) => c.level === "warning").length
|
|
3680
|
+
};
|
|
3681
|
+
}
|
|
3682
|
+
var plural = (n, word) => `${n} ${word}${n === 1 ? "" : "s"}`;
|
|
3683
|
+
function renderDoctor(r) {
|
|
3684
|
+
const lines = [`Armada ${r.armadaVersion} doctor · ${r.root}`, ""];
|
|
3685
|
+
for (const c of r.checks) {
|
|
3686
|
+
const [first, ...more] = c.message.split(`
|
|
3687
|
+
`);
|
|
3688
|
+
lines.push(` ${c.level.padEnd(8)} ${first}`);
|
|
3689
|
+
for (const m of more)
|
|
3690
|
+
lines.push(` ${m}`);
|
|
3691
|
+
if (c.fix)
|
|
3692
|
+
lines.push(` fix: ${c.fix}`);
|
|
3693
|
+
}
|
|
3694
|
+
lines.push("");
|
|
3695
|
+
if (!r.errors && !r.warnings)
|
|
3696
|
+
lines.push("Everything Armada needs is in place.");
|
|
3697
|
+
else
|
|
3698
|
+
lines.push(`${plural(r.errors, "error")}, ${plural(r.warnings, "warning")}.${r.errors ? " Workers cannot be launched until the errors are fixed." : ""}`);
|
|
3699
|
+
return `${lines.join(`
|
|
3700
|
+
`)}
|
|
3701
|
+
`;
|
|
3702
|
+
}
|
|
3703
|
+
async function doctor(io, json, armadaVersion) {
|
|
3704
|
+
const report = await buildDoctor(io, armadaVersion);
|
|
3705
|
+
io.stdout(json ? `${JSON.stringify(report, null, 2)}
|
|
3706
|
+
` : renderDoctor(report));
|
|
3707
|
+
return report.errors ? 1 : 0;
|
|
3708
|
+
}
|
|
3709
|
+
|
|
3710
|
+
// src/init.ts
|
|
3711
|
+
import { mkdtemp, realpath, rm as rm3 } from "node:fs/promises";
|
|
3712
|
+
import { tmpdir } from "node:os";
|
|
3713
|
+
import { join as join3 } from "node:path";
|
|
3714
|
+
var initBranch = (version2) => `armada/init-${version2}`;
|
|
3715
|
+
async function defaultBranch(exec, root) {
|
|
3716
|
+
const out = await sh(exec, root, "git", ["ls-remote", "--symref", "origin", "HEAD"]);
|
|
3717
|
+
const m = out.match(/^ref:\s+refs\/heads\/(\S+)\s+HEAD/m);
|
|
3718
|
+
if (!m?.[1])
|
|
3719
|
+
throw new CommandError("could not read the default branch of origin");
|
|
3720
|
+
return m[1];
|
|
3721
|
+
}
|
|
3722
|
+
async function resolveConfig(exec, root, checkout, opts) {
|
|
3723
|
+
const parse2 = (text2, where) => {
|
|
3724
|
+
try {
|
|
3725
|
+
return parseConfig(text2, where);
|
|
3726
|
+
} catch (err) {
|
|
3727
|
+
if (err instanceof ConfigError)
|
|
3728
|
+
throw new UsageError(`${err.message}
|
|
3729
|
+
Fix it, then run armada init again.`);
|
|
3730
|
+
throw err;
|
|
3731
|
+
}
|
|
3732
|
+
};
|
|
3733
|
+
const onDefault = await fsRepoView(checkout).readFile(CONFIG_FILE);
|
|
3734
|
+
if (onDefault !== null)
|
|
3735
|
+
return { config: parse2(onDefault, `${CONFIG_FILE} on the default branch`), text: null, source: "default branch" };
|
|
3736
|
+
const local = await fsRepoView(root).readFile(CONFIG_FILE);
|
|
3737
|
+
if (local !== null && !opts.programRoot)
|
|
3738
|
+
return { config: parse2(local, join3(root, CONFIG_FILE)), text: local, source: "working tree" };
|
|
3739
|
+
const branch = initBranch(opts.armadaVersion);
|
|
3740
|
+
if (!opts.programRoot && await sh(exec, root, "git", ["ls-remote", "origin", `refs/heads/${branch}`])) {
|
|
3741
|
+
await sh(exec, root, "git", ["fetch", "--quiet", "origin", branch]);
|
|
3742
|
+
const shown = await exec("git", ["show", `FETCH_HEAD:${CONFIG_FILE}`], { cwd: root });
|
|
3743
|
+
if (shown.code === 0)
|
|
3744
|
+
return { config: parse2(shown.stdout, `${CONFIG_FILE} on ${branch}`), text: shown.stdout, source: branch };
|
|
3745
|
+
}
|
|
3746
|
+
if (!opts.programRoot)
|
|
3747
|
+
throw new UsageError(`${CONFIG_FILE} is missing. Run armada init --program-root <ISSUE-ID> with the Linear issue at the root of the program, or add ${CONFIG_FILE} (see README).`);
|
|
3748
|
+
const repo = JSON.parse(await sh(exec, root, "gh", ["repo", "view", "--json", "name,nameWithOwner"]));
|
|
3749
|
+
const name = opts.name ?? repo.name;
|
|
3750
|
+
const text = configTemplate({
|
|
3751
|
+
name,
|
|
3752
|
+
slug: opts.slug ?? slugify(name),
|
|
3753
|
+
programRoot: opts.programRoot,
|
|
3754
|
+
repository: repo.nameWithOwner
|
|
3755
|
+
});
|
|
3756
|
+
return { config: parse2(text, `the new ${CONFIG_FILE}`), text, source: "new" };
|
|
3757
|
+
}
|
|
3758
|
+
async function branchIsCurrent(exec, checkout, branch, baseSha) {
|
|
3759
|
+
if (!await sh(exec, checkout, "git", ["ls-remote", "origin", `refs/heads/${branch}`]))
|
|
3760
|
+
return false;
|
|
3761
|
+
await sh(exec, checkout, "git", ["fetch", "--quiet", "origin", branch]);
|
|
3762
|
+
const [remoteTree, remoteParent, tree] = await Promise.all([
|
|
3763
|
+
sh(exec, checkout, "git", ["rev-parse", "FETCH_HEAD^{tree}"]),
|
|
3764
|
+
sh(exec, checkout, "git", ["rev-parse", "FETCH_HEAD^"]),
|
|
3765
|
+
sh(exec, checkout, "git", ["rev-parse", "HEAD^{tree}"])
|
|
3766
|
+
]);
|
|
3767
|
+
return remoteTree === tree && remoteParent === baseSha;
|
|
3768
|
+
}
|
|
3769
|
+
function prText(plan, version2) {
|
|
3770
|
+
const title = plan.installed.length ? `chore(armada): set up Armada ${version2}` : `chore(armada): update the Armada setup to ${version2}`;
|
|
3771
|
+
const lines = [
|
|
3772
|
+
`Adds what \`armada doctor\` checks, so Armada ${version2} can run agents on this repository.`,
|
|
3773
|
+
"",
|
|
3774
|
+
...plan.writes.map((w) => `- write \`${w.path}\``),
|
|
3775
|
+
...plan.links.map((l) => `- link \`${l.path}\` → \`${l.target}\``),
|
|
3776
|
+
...plan.removes.map((p) => `- remove \`${p}\``),
|
|
3777
|
+
"",
|
|
3778
|
+
"Once merged, `armada doctor` passes on the default branch.",
|
|
3779
|
+
"",
|
|
3780
|
+
"Opened by `armada init`. Running it again rebuilds this branch from the default branch and updates this pull request, so commits pushed here by hand are replaced."
|
|
3781
|
+
];
|
|
3782
|
+
return { title, body: lines.join(`
|
|
3783
|
+
`) };
|
|
3784
|
+
}
|
|
3785
|
+
async function init(io, opts) {
|
|
3786
|
+
const exec = requireExec(io);
|
|
3787
|
+
const tursoKey = STORED_KEYS.find((k) => k.name === "tursoUrl") ?? LINEAR_KEY;
|
|
3788
|
+
const required = (c) => [c.linearApiKey ? null : LINEAR_KEY, c.tursoUrl ? null : tursoKey];
|
|
3789
|
+
if (io.interactive || required((await loadCredentials(io)).credentials).some(Boolean)) {
|
|
3790
|
+
const login = await authLogin(io);
|
|
3791
|
+
if (login !== 0)
|
|
3792
|
+
return login;
|
|
3793
|
+
}
|
|
3794
|
+
const { credentials: credentials2 } = await loadCredentials(io);
|
|
3795
|
+
const missing2 = required(credentials2).find(Boolean);
|
|
3796
|
+
if (missing2)
|
|
3797
|
+
throw new UsageError(missingKeyMessage(missing2));
|
|
3798
|
+
const linearApiKey = credentials2.linearApiKey ?? "";
|
|
3799
|
+
const tursoUrl = credentials2.tursoUrl ?? "";
|
|
3800
|
+
const root = await gitRoot(exec, io.cwd);
|
|
3801
|
+
if (!root)
|
|
3802
|
+
throw new UsageError(`${io.cwd} is not inside a git repository`);
|
|
3803
|
+
const base = await defaultBranch(exec, root);
|
|
3804
|
+
await sh(exec, root, "git", ["fetch", "--quiet", "origin", base]);
|
|
3805
|
+
const baseSha = await sh(exec, root, "git", ["rev-parse", "FETCH_HEAD"]);
|
|
3806
|
+
const checkout = await realpath(await mkdtemp(join3(tmpdir(), "armada-init-")));
|
|
3807
|
+
try {
|
|
3808
|
+
await sh(exec, root, "git", ["worktree", "add", "--quiet", "--detach", checkout, baseSha]);
|
|
3809
|
+
const { config: config2, text, source } = await resolveConfig(exec, root, checkout, opts);
|
|
3810
|
+
const view = fsRepoView(checkout);
|
|
3811
|
+
const plan = await planSetup(view, { armadaVersion: opts.armadaVersion, configText: text });
|
|
3812
|
+
const log = (line) => io.stdout(`${line}
|
|
3813
|
+
`);
|
|
3814
|
+
log(`Armada ${opts.armadaVersion} · ${config2.github.repository} · ${config2.tracker.programRoot}`);
|
|
3815
|
+
if (source !== "default branch" && source !== "new")
|
|
3816
|
+
log(`Using ${CONFIG_FILE} from ${source === "working tree" ? "the working tree" : source}; the pull request adds it.`);
|
|
3817
|
+
const linear2 = { apiKey: linearApiKey, ...io.fetch ? { fetch: io.fetch } : {} };
|
|
3818
|
+
const created = await createMissingLabels(await readLabels(config2, linear2), linear2);
|
|
3819
|
+
log(created.length ? `Created Linear labels: ${created.join(", ")}` : "Linear labels: all present");
|
|
3820
|
+
if (planIsEmpty(plan))
|
|
3821
|
+
log(`${base} already has everything Armada needs; no pull request to open.`);
|
|
3822
|
+
else {
|
|
3823
|
+
const branch = initBranch(opts.armadaVersion);
|
|
3824
|
+
await applyPlan(checkout, plan);
|
|
3825
|
+
const paths = [...plan.writes.map((w) => w.path), ...plan.links.map((l) => l.path), ...plan.removes];
|
|
3826
|
+
await sh(exec, checkout, "git", ["add", "--all", "--force", "--", ...paths]);
|
|
3827
|
+
const { title, body } = prText(plan, opts.armadaVersion);
|
|
3828
|
+
await sh(exec, checkout, "git", ["commit", "--quiet", "--no-verify", "--message", title]);
|
|
3829
|
+
if (await branchIsCurrent(exec, checkout, branch, baseSha))
|
|
3830
|
+
log(`${branch} is already up to date.`);
|
|
3831
|
+
else
|
|
3832
|
+
await sh(exec, checkout, "git", ["push", "--quiet", "--force", "origin", `HEAD:refs/heads/${branch}`]);
|
|
3833
|
+
const repo = config2.github.repository;
|
|
3834
|
+
const open2 = JSON.parse(await sh(exec, root, "gh", [
|
|
3835
|
+
"pr",
|
|
3836
|
+
"list",
|
|
3837
|
+
"--repo",
|
|
3838
|
+
repo,
|
|
3839
|
+
"--head",
|
|
3840
|
+
branch,
|
|
3841
|
+
"--state",
|
|
3842
|
+
"open",
|
|
3843
|
+
"--json",
|
|
3844
|
+
"number,url"
|
|
3845
|
+
]) || "[]");
|
|
3846
|
+
const existing = open2[0];
|
|
3847
|
+
if (existing) {
|
|
3848
|
+
await sh(exec, root, "gh", [
|
|
3849
|
+
"pr",
|
|
3850
|
+
"edit",
|
|
3851
|
+
String(existing.number),
|
|
3852
|
+
"--repo",
|
|
3853
|
+
repo,
|
|
3854
|
+
"--title",
|
|
3855
|
+
title,
|
|
3856
|
+
"--body",
|
|
3857
|
+
body
|
|
3858
|
+
]);
|
|
3859
|
+
log(`Updated pull request ${existing.url}`);
|
|
3860
|
+
} else {
|
|
3861
|
+
const url = await sh(exec, root, "gh", [
|
|
3862
|
+
"pr",
|
|
3863
|
+
"create",
|
|
3864
|
+
"--repo",
|
|
3865
|
+
repo,
|
|
3866
|
+
"--base",
|
|
3867
|
+
base,
|
|
3868
|
+
"--head",
|
|
3869
|
+
branch,
|
|
3870
|
+
"--title",
|
|
3871
|
+
title,
|
|
3872
|
+
"--body",
|
|
3873
|
+
body
|
|
3874
|
+
]);
|
|
3875
|
+
log(`Opened pull request ${url.split(`
|
|
3876
|
+
`).pop()}`);
|
|
3877
|
+
}
|
|
3878
|
+
if (plan.installed.length)
|
|
3879
|
+
log(`Installs: ${plan.installed.join(", ")}`);
|
|
3880
|
+
if (plan.updated.length)
|
|
3881
|
+
log(`Updates: ${plan.updated.join(", ")}`);
|
|
3882
|
+
}
|
|
3883
|
+
const db = await openTurso({ url: tursoUrl, token: credentials2.tursoToken });
|
|
3884
|
+
try {
|
|
3885
|
+
const project2 = {
|
|
3886
|
+
slug: config2.project.slug,
|
|
3887
|
+
name: config2.project.name,
|
|
3888
|
+
repository: config2.github.repository,
|
|
3889
|
+
programRoot: config2.tracker.programRoot
|
|
3890
|
+
};
|
|
3891
|
+
await upsertProject(db, project2, io.now?.() ?? new Date);
|
|
3892
|
+
} finally {
|
|
3893
|
+
db.close();
|
|
3894
|
+
}
|
|
3895
|
+
log(`Registered project ${config2.project.slug}; armada status --all lists it.`);
|
|
3896
|
+
return 0;
|
|
3897
|
+
} finally {
|
|
3898
|
+
await exec("git", ["worktree", "remove", "--force", checkout], { cwd: root }).catch(() => null);
|
|
3899
|
+
await rm3(checkout, { recursive: true, force: true });
|
|
3900
|
+
}
|
|
3901
|
+
}
|
|
3902
|
+
|
|
2298
3903
|
// src/render.ts
|
|
2299
3904
|
var MIN2 = 60000;
|
|
2300
|
-
function
|
|
3905
|
+
function relative2(iso, now) {
|
|
2301
3906
|
const diff = now - Date.parse(iso);
|
|
2302
3907
|
const m = Math.round(Math.abs(diff) / MIN2);
|
|
2303
3908
|
const suffix = diff >= 0 ? "ago" : "from now";
|
|
@@ -2339,7 +3944,7 @@ function renderStatus(r) {
|
|
|
2339
3944
|
out.push(" nobody is working");
|
|
2340
3945
|
for (const t of r.inFlight) {
|
|
2341
3946
|
const who = [t.runtime, t.agent].filter(Boolean).join(" · ") || "unassigned";
|
|
2342
|
-
out.push(` ${pad(t.id, idWidth)} ${pad(phaseLabel(t), phaseWidth)} ${who} · updated ${
|
|
3947
|
+
out.push(` ${pad(t.id, idWidth)} ${pad(phaseLabel(t), phaseWidth)} ${who} · ${t.lastReport ? `reported ${relative2(t.lastReport, now)}` : `updated ${relative2(t.lastUpdate, now)}`}`);
|
|
2343
3948
|
out.push(`${indent}${truncate(t.title, 90)}${t.spec ? ` [${t.spec}]` : ""}`);
|
|
2344
3949
|
if (t.statusLine?.summary)
|
|
2345
3950
|
out.push(`${indent}“${truncate(t.statusLine.summary, 100)}”`);
|
|
@@ -2388,24 +3993,293 @@ function renderStatus(r) {
|
|
|
2388
3993
|
`;
|
|
2389
3994
|
}
|
|
2390
3995
|
|
|
3996
|
+
// src/projects.ts
|
|
3997
|
+
var message = (err) => err instanceof Error ? err.message : String(err);
|
|
3998
|
+
async function projectConfig(p, githubToken, io) {
|
|
3999
|
+
const fallback = (why) => ({
|
|
4000
|
+
config: parseConfig(configTemplate(p), `registry record ${p.slug}`),
|
|
4001
|
+
warning: `${CONFIG_FILE} not read (${why}); using the registry record with default labels and policy`
|
|
4002
|
+
});
|
|
4003
|
+
if (!githubToken)
|
|
4004
|
+
return fallback("no GitHub token");
|
|
4005
|
+
try {
|
|
4006
|
+
const text = await fetchDefaultBranchFile({
|
|
4007
|
+
token: githubToken,
|
|
4008
|
+
repository: p.repository,
|
|
4009
|
+
path: CONFIG_FILE,
|
|
4010
|
+
...io.fetch ? { fetch: io.fetch } : {}
|
|
4011
|
+
});
|
|
4012
|
+
if (text === null)
|
|
4013
|
+
return fallback(`not on the default branch of ${p.repository}`);
|
|
4014
|
+
return { config: parseConfig(text, `${p.repository}:${CONFIG_FILE}`), warning: null };
|
|
4015
|
+
} catch (err) {
|
|
4016
|
+
return fallback(message(err));
|
|
4017
|
+
}
|
|
4018
|
+
}
|
|
4019
|
+
async function statusAll(io, json) {
|
|
4020
|
+
const { credentials: credentials2 } = await loadCredentials(io);
|
|
4021
|
+
const linearApiKey = credentials2.linearApiKey;
|
|
4022
|
+
if (!linearApiKey)
|
|
4023
|
+
throw new UsageError(missingKeyMessage(LINEAR_KEY));
|
|
4024
|
+
const tursoKey = STORED_KEYS.find((k) => k.name === "tursoUrl");
|
|
4025
|
+
if (!credentials2.tursoUrl && tursoKey)
|
|
4026
|
+
throw new UsageError(missingKeyMessage(tursoKey));
|
|
4027
|
+
const db = await openTurso({ url: credentials2.tursoUrl ?? "", token: credentials2.tursoToken });
|
|
4028
|
+
let records;
|
|
4029
|
+
try {
|
|
4030
|
+
records = await listProjects(db);
|
|
4031
|
+
} finally {
|
|
4032
|
+
db.close();
|
|
4033
|
+
}
|
|
4034
|
+
const projects = await Promise.all(records.map(async (p) => {
|
|
4035
|
+
const base = { slug: p.slug, name: p.name, repository: p.repository };
|
|
4036
|
+
let warning = null;
|
|
4037
|
+
try {
|
|
4038
|
+
const read = await projectConfig(p, credentials2.githubToken, io);
|
|
4039
|
+
warning = read.warning;
|
|
4040
|
+
const config2 = read.config;
|
|
4041
|
+
const report = await loadStatus(config2, {
|
|
4042
|
+
linearApiKey,
|
|
4043
|
+
githubToken: credentials2.githubToken,
|
|
4044
|
+
...io.fetch ? { fetch: io.fetch } : {},
|
|
4045
|
+
...io.now ? { now: io.now } : {}
|
|
4046
|
+
});
|
|
4047
|
+
return { ...base, report, error: null, configWarning: warning };
|
|
4048
|
+
} catch (err) {
|
|
4049
|
+
return { ...base, report: null, error: message(err), configWarning: warning };
|
|
4050
|
+
}
|
|
4051
|
+
}));
|
|
4052
|
+
const all = { schemaVersion: 1, projects };
|
|
4053
|
+
if (json)
|
|
4054
|
+
io.stdout(`${JSON.stringify(all, null, 2)}
|
|
4055
|
+
`);
|
|
4056
|
+
else if (!projects.length)
|
|
4057
|
+
io.stdout("No project is registered yet. Run `armada init` in a repository to register it.\n");
|
|
4058
|
+
else
|
|
4059
|
+
io.stdout(projects.map((p) => {
|
|
4060
|
+
if (!p.report)
|
|
4061
|
+
return `${p.name} (${p.slug}) · ${p.repository}
|
|
4062
|
+
! not read: ${p.error}
|
|
4063
|
+
${p.configWarning ? ` ! ${p.configWarning}
|
|
4064
|
+
` : ""}`;
|
|
4065
|
+
return `${renderStatus(p.report)}${p.configWarning ? ` ! ${p.configWarning}
|
|
4066
|
+
` : ""}`;
|
|
4067
|
+
}).join(`
|
|
4068
|
+
${"─".repeat(60)}
|
|
4069
|
+
|
|
4070
|
+
`));
|
|
4071
|
+
return projects.some((p) => p.error) ? 1 : 0;
|
|
4072
|
+
}
|
|
4073
|
+
|
|
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
|
+
|
|
2391
4247
|
// src/cli.ts
|
|
2392
4248
|
var USAGE = `Usage: armada <command> [options]
|
|
2393
4249
|
|
|
2394
4250
|
Commands:
|
|
2395
4251
|
status Tickets in flight, tickets ready to start and pull requests waiting
|
|
4252
|
+
status --all The same for every project registered by \`armada init\`
|
|
4253
|
+
doctor What this repository lacks to be run by Armada, with the fix for each
|
|
4254
|
+
init [--program-root <ISSUE-ID>] [--name <name>] [--slug <slug>]
|
|
4255
|
+
Open one pull request that installs or updates it all, create the
|
|
4256
|
+
missing Linear labels and register the project. The options are for
|
|
4257
|
+
a repository without armada.toml (Linear issue at the program root)
|
|
4258
|
+
claim <ticket> --runtime <name> --handle <id> [--branch <name>]
|
|
4259
|
+
Claim a ticket for this worker: In Progress, phase planning, runtime
|
|
4260
|
+
label and an Agent claim comment; refused if another worker holds it
|
|
4261
|
+
report <phase> [--message <text> | --message-file <path|->] [--pr <n|url>] [--sha <sha>]
|
|
4262
|
+
Report a phase (planning, awaiting-approval, implementing, shipping,
|
|
4263
|
+
blocked, ready-to-merge); the same phase again is a status update.
|
|
4264
|
+
ready-to-merge needs --sha (full 40 characters, the PR head) and green CI.
|
|
4265
|
+
Prints what waits in this worker's inbox.
|
|
4266
|
+
release --reason <text>
|
|
4267
|
+
Give the ticket back: agent labels removed, ticket moved back
|
|
2396
4268
|
auth login Ask for the missing keys (hidden input) and store them on this machine
|
|
2397
4269
|
auth status Show which keys are set and where each comes from, never their values
|
|
2398
4270
|
auth logout Remove Armada's keys from this machine
|
|
2399
4271
|
|
|
2400
4272
|
Options:
|
|
2401
|
-
--json Print the
|
|
4273
|
+
--json Print the result as JSON
|
|
2402
4274
|
--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
|
|
2403
4276
|
-h, --help Show this help
|
|
2404
4277
|
-v, --version Print the version
|
|
2405
4278
|
|
|
2406
4279
|
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
|
|
4280
|
+
LINEAR_API_KEY Linear API key (required by status, init, claim, report, release)
|
|
4281
|
+
ARMADA_TURSO_URL Turso database URL (required by init and status --all; optional
|
|
4282
|
+
elsewhere; a file: URL works locally)
|
|
2409
4283
|
ARMADA_TURSO_TOKEN Turso database token
|
|
2410
4284
|
GITHUB_TOKEN GitHub token; falls back to GH_TOKEN, then \`gh auth token\`
|
|
2411
4285
|
|
|
@@ -2414,24 +4288,58 @@ Files:
|
|
|
2414
4288
|
credentials KEY=value lines, mode 0600, written by \`armada auth login\`
|
|
2415
4289
|
config.toml personal defaults: language, [turso] url, [dashboard] url
|
|
2416
4290
|
`;
|
|
4291
|
+
var VALUE_OPTIONS = [
|
|
4292
|
+
"runtime",
|
|
4293
|
+
"handle",
|
|
4294
|
+
"branch",
|
|
4295
|
+
"ticket",
|
|
4296
|
+
"message",
|
|
4297
|
+
"message-file",
|
|
4298
|
+
"pr",
|
|
4299
|
+
"sha",
|
|
4300
|
+
"reason",
|
|
4301
|
+
"program-root",
|
|
4302
|
+
"name",
|
|
4303
|
+
"slug"
|
|
4304
|
+
];
|
|
4305
|
+
var COMMAND_OPTIONS = {
|
|
4306
|
+
claim: ["runtime", "handle", "branch"],
|
|
4307
|
+
report: ["ticket", "message", "message-file", "pr", "sha"],
|
|
4308
|
+
release: ["ticket", "reason"],
|
|
4309
|
+
init: ["program-root", "name", "slug"]
|
|
4310
|
+
};
|
|
2417
4311
|
function parseArgs(argv) {
|
|
2418
|
-
const args = {
|
|
4312
|
+
const args = {
|
|
4313
|
+
command: null,
|
|
4314
|
+
rest: [],
|
|
4315
|
+
json: false,
|
|
4316
|
+
all: false,
|
|
4317
|
+
config: null,
|
|
4318
|
+
help: false,
|
|
4319
|
+
version: false,
|
|
4320
|
+
options: {}
|
|
4321
|
+
};
|
|
2419
4322
|
for (let k = 0;k < argv.length; k++) {
|
|
2420
4323
|
const a = argv[k];
|
|
4324
|
+
const named = a?.match(/^--([a-z-]+)(?:=([\s\S]*))?$/);
|
|
4325
|
+
const name = named?.[1];
|
|
2421
4326
|
if (a === "--json")
|
|
2422
4327
|
args.json = true;
|
|
4328
|
+
else if (a === "--all")
|
|
4329
|
+
args.all = true;
|
|
2423
4330
|
else if (a === "-h" || a === "--help")
|
|
2424
4331
|
args.help = true;
|
|
2425
4332
|
else if (a === "-v" || a === "--version")
|
|
2426
4333
|
args.version = true;
|
|
2427
|
-
else if (
|
|
2428
|
-
const v = argv[++k];
|
|
2429
|
-
if (
|
|
2430
|
-
throw new UsageError(
|
|
2431
|
-
|
|
2432
|
-
|
|
2433
|
-
|
|
2434
|
-
|
|
4334
|
+
else if (name && (name === "config" || VALUE_OPTIONS.includes(name))) {
|
|
4335
|
+
const v = named?.[2] ?? argv[++k];
|
|
4336
|
+
if (v === undefined)
|
|
4337
|
+
throw new UsageError(`--${name} needs a value`);
|
|
4338
|
+
if (name === "config")
|
|
4339
|
+
args.config = v;
|
|
4340
|
+
else
|
|
4341
|
+
args.options[name] = v;
|
|
4342
|
+
} else if (a?.startsWith("-"))
|
|
2435
4343
|
throw new UsageError(`unknown option ${a}`);
|
|
2436
4344
|
else if (!args.command && a)
|
|
2437
4345
|
args.command = a;
|
|
@@ -2448,12 +4356,12 @@ async function findConfig(io, explicit) {
|
|
|
2448
4356
|
throw new UsageError(`${path} does not exist`);
|
|
2449
4357
|
return { path, text };
|
|
2450
4358
|
}
|
|
2451
|
-
for (let dir = resolve(io.cwd);; dir =
|
|
2452
|
-
const path =
|
|
4359
|
+
for (let dir = resolve(io.cwd);; dir = dirname2(dir)) {
|
|
4360
|
+
const path = join4(dir, CONFIG_FILE);
|
|
2453
4361
|
const text = await io.readFile(path);
|
|
2454
4362
|
if (text !== null)
|
|
2455
4363
|
return { path, text };
|
|
2456
|
-
if (
|
|
4364
|
+
if (dirname2(dir) === dir)
|
|
2457
4365
|
break;
|
|
2458
4366
|
}
|
|
2459
4367
|
throw new UsageError(`no ${CONFIG_FILE} found in ${io.cwd} or any parent directory. Add one at the repository root (see README).`);
|
|
@@ -2461,17 +4369,20 @@ async function findConfig(io, explicit) {
|
|
|
2461
4369
|
async function status2(io, args) {
|
|
2462
4370
|
const { path, text } = await findConfig(io, args.config);
|
|
2463
4371
|
const config2 = parseConfig(text, path);
|
|
2464
|
-
const {
|
|
4372
|
+
const { credentials: credentials2 } = await loadCredentials(io);
|
|
4373
|
+
const { linearApiKey, githubToken } = credentials2;
|
|
2465
4374
|
if (!linearApiKey)
|
|
2466
4375
|
throw new UsageError(missingKeyMessage(LINEAR_KEY));
|
|
2467
|
-
const
|
|
4376
|
+
const events = statusEvents(config2, credentials2);
|
|
4377
|
+
const report2 = await loadStatus(config2, {
|
|
2468
4378
|
linearApiKey,
|
|
2469
4379
|
githubToken,
|
|
4380
|
+
...events ? { lastEvents: events } : {},
|
|
2470
4381
|
...io.fetch ? { fetch: io.fetch } : {},
|
|
2471
4382
|
...io.now ? { now: io.now } : {}
|
|
2472
4383
|
});
|
|
2473
|
-
io.stdout(args.json ? `${JSON.stringify(
|
|
2474
|
-
` : renderStatus(
|
|
4384
|
+
io.stdout(args.json ? `${JSON.stringify(report2, null, 2)}
|
|
4385
|
+
` : renderStatus(report2));
|
|
2475
4386
|
return 0;
|
|
2476
4387
|
}
|
|
2477
4388
|
function noExtra(rest) {
|
|
@@ -2490,9 +4401,35 @@ async function run(argv, io) {
|
|
|
2490
4401
|
(args.help ? io.stdout : io.stderr)(USAGE);
|
|
2491
4402
|
return args.help ? 0 : 2;
|
|
2492
4403
|
}
|
|
4404
|
+
const allowed = COMMAND_OPTIONS[args.command] ?? [];
|
|
4405
|
+
for (const name of Object.keys(args.options))
|
|
4406
|
+
if (!allowed.includes(name))
|
|
4407
|
+
throw new UsageError(`--${name} does not apply to ${args.command}`);
|
|
4408
|
+
if (args.all && args.command !== "status")
|
|
4409
|
+
throw new UsageError(`--all does not apply to ${args.command}`);
|
|
4410
|
+
const worker2 = { claim, report, release }[args.command];
|
|
4411
|
+
if (worker2) {
|
|
4412
|
+
const { path, text } = await findConfig(io, args.config);
|
|
4413
|
+
const config2 = parseConfig(text, path);
|
|
4414
|
+
const { credentials: credentials2 } = await loadCredentials(io);
|
|
4415
|
+
return await worker2(io, config2, credentials2, args);
|
|
4416
|
+
}
|
|
2493
4417
|
if (args.command === "status") {
|
|
2494
4418
|
noExtra(args.rest);
|
|
2495
|
-
return await status2(io, args);
|
|
4419
|
+
return await (args.all ? statusAll(io, args.json) : status2(io, args));
|
|
4420
|
+
}
|
|
4421
|
+
if (args.command === "doctor") {
|
|
4422
|
+
noExtra(args.rest);
|
|
4423
|
+
return await doctor(io, args.json, version);
|
|
4424
|
+
}
|
|
4425
|
+
if (args.command === "init") {
|
|
4426
|
+
noExtra(args.rest);
|
|
4427
|
+
return await init(io, {
|
|
4428
|
+
armadaVersion: version,
|
|
4429
|
+
programRoot: args.options["program-root"] ?? null,
|
|
4430
|
+
name: args.options.name ?? null,
|
|
4431
|
+
slug: args.options.slug ?? null
|
|
4432
|
+
});
|
|
2496
4433
|
}
|
|
2497
4434
|
if (args.command === "auth") {
|
|
2498
4435
|
const [sub, ...extra] = args.rest;
|
|
@@ -2550,6 +4487,22 @@ function echo(before, after) {
|
|
|
2550
4487
|
}
|
|
2551
4488
|
|
|
2552
4489
|
// src/main.ts
|
|
4490
|
+
function gitBranch() {
|
|
4491
|
+
try {
|
|
4492
|
+
const r = spawnSync("git", ["rev-parse", "--abbrev-ref", "HEAD"], { encoding: "utf8", timeout: 5000 });
|
|
4493
|
+
const branch = r.status === 0 ? r.stdout.trim() : "";
|
|
4494
|
+
return branch && branch !== "HEAD" ? branch : null;
|
|
4495
|
+
} catch {
|
|
4496
|
+
return null;
|
|
4497
|
+
}
|
|
4498
|
+
}
|
|
4499
|
+
async function readStdin() {
|
|
4500
|
+
let text = "";
|
|
4501
|
+
process.stdin.setEncoding("utf8");
|
|
4502
|
+
for await (const chunk of process.stdin)
|
|
4503
|
+
text += chunk;
|
|
4504
|
+
return text;
|
|
4505
|
+
}
|
|
2553
4506
|
function ghToken() {
|
|
2554
4507
|
try {
|
|
2555
4508
|
const r = spawnSync("gh", ["auth", "token"], { encoding: "utf8", timeout: 5000 });
|
|
@@ -2583,10 +4536,23 @@ function prompt(question, { hidden }) {
|
|
|
2583
4536
|
stdin.resume();
|
|
2584
4537
|
});
|
|
2585
4538
|
}
|
|
4539
|
+
var exec = (command, args, { cwd }) => new Promise((done, fail) => {
|
|
4540
|
+
const child = spawn(command, args, { cwd, stdio: ["ignore", "pipe", "pipe"] });
|
|
4541
|
+
let stdout = "";
|
|
4542
|
+
let stderr = "";
|
|
4543
|
+
child.stdout.setEncoding("utf8").on("data", (d) => {
|
|
4544
|
+
stdout += d;
|
|
4545
|
+
});
|
|
4546
|
+
child.stderr.setEncoding("utf8").on("data", (d) => {
|
|
4547
|
+
stderr += d;
|
|
4548
|
+
});
|
|
4549
|
+
child.on("error", fail);
|
|
4550
|
+
child.on("close", (code) => done({ code: code ?? 1, stdout, stderr }));
|
|
4551
|
+
});
|
|
2586
4552
|
var code = await run(process.argv.slice(2), {
|
|
2587
4553
|
cwd: process.cwd(),
|
|
2588
4554
|
env: process.env,
|
|
2589
|
-
readFile: (path) =>
|
|
4555
|
+
readFile: (path) => readFile3(path, "utf8").catch((err) => {
|
|
2590
4556
|
if (err.code === "ENOENT" || err.code === "ENOTDIR")
|
|
2591
4557
|
return null;
|
|
2592
4558
|
throw err;
|
|
@@ -2595,6 +4561,9 @@ var code = await run(process.argv.slice(2), {
|
|
|
2595
4561
|
stderr: (t) => process.stderr.write(t),
|
|
2596
4562
|
ghToken,
|
|
2597
4563
|
interactive: Boolean(process.stdin.isTTY && process.stderr.isTTY),
|
|
2598
|
-
prompt
|
|
4564
|
+
prompt,
|
|
4565
|
+
gitBranch,
|
|
4566
|
+
readStdin,
|
|
4567
|
+
exec
|
|
2599
4568
|
});
|
|
2600
4569
|
process.stdout.write("", () => process.exit(code));
|