@the-vibe-company/armada 0.1.2 → 0.1.4
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 +46 -2
- package/dist/armada.js +2253 -1032
- package/package.json +1 -1
package/dist/armada.js
CHANGED
|
@@ -23,7 +23,7 @@ import { spawn, spawnSync } from "node:child_process";
|
|
|
23
23
|
import { readFile as readFile3 } from "node:fs/promises";
|
|
24
24
|
|
|
25
25
|
// src/cli.ts
|
|
26
|
-
import { dirname as
|
|
26
|
+
import { dirname as dirname3, join as join5, resolve } from "node:path";
|
|
27
27
|
|
|
28
28
|
// ../../node_modules/.bun/smol-toml@1.9.0/node_modules/smol-toml/dist/error.js
|
|
29
29
|
/*!
|
|
@@ -1075,14 +1075,50 @@ function parseConfig(text, source = CONFIG_FILE) {
|
|
|
1075
1075
|
if (!isTable(gates))
|
|
1076
1076
|
problems.push(`"gates" must be a table`);
|
|
1077
1077
|
const gatesT = isTable(gates) ? gates : {};
|
|
1078
|
+
const conductor = raw.conductor === undefined ? {} : raw.conductor;
|
|
1079
|
+
if (!isTable(conductor))
|
|
1080
|
+
problems.push(`"conductor" must be a table`);
|
|
1081
|
+
const conductorT = isTable(conductor) ? conductor : {};
|
|
1082
|
+
const profilesRaw = conductorT.profiles === undefined ? {} : conductorT.profiles;
|
|
1083
|
+
if (!isTable(profilesRaw))
|
|
1084
|
+
problems.push(`"conductor.profiles" must be a table of profiles`);
|
|
1085
|
+
const profilesT = isTable(profilesRaw) ? profilesRaw : {};
|
|
1078
1086
|
const known = [
|
|
1079
1087
|
["project", project, ["name", "slug"]],
|
|
1080
1088
|
["tracker", tracker, ["program_root", "language", "ready_label", "labels"]],
|
|
1081
1089
|
["tracker.labels", labelsT, ["phase_group", "runtime_group", "runtimes"]],
|
|
1082
1090
|
["github", github, ["repository"]],
|
|
1083
|
-
["gates", gatesT, ["required_checks"]],
|
|
1084
|
-
["policy", policyT, ["silence_minutes", "silent_after_minutes"]]
|
|
1091
|
+
["gates", gatesT, ["required_checks", "local_commands"]],
|
|
1092
|
+
["policy", policyT, ["silence_minutes", "silent_after_minutes"]],
|
|
1093
|
+
["conductor", conductorT, ["default_profile", "profiles"]]
|
|
1085
1094
|
];
|
|
1095
|
+
const profiles = {};
|
|
1096
|
+
for (const [name, p] of Object.entries(profilesT)) {
|
|
1097
|
+
const path = `conductor.profiles.${name}`;
|
|
1098
|
+
if (!isTable(p)) {
|
|
1099
|
+
problems.push(`"${path}" must be a table`);
|
|
1100
|
+
continue;
|
|
1101
|
+
}
|
|
1102
|
+
if (name === "__proto__") {
|
|
1103
|
+
problems.push(`"${path}" is not a usable profile name`);
|
|
1104
|
+
continue;
|
|
1105
|
+
}
|
|
1106
|
+
known.push([path, p, ["agent", "model", "effort", "fast_mode"]]);
|
|
1107
|
+
if (p.fast_mode !== undefined && typeof p.fast_mode !== "boolean")
|
|
1108
|
+
problems.push(`"${path}.fast_mode" must be true or false`);
|
|
1109
|
+
profiles[name] = {
|
|
1110
|
+
agent: str(p, path, "agent"),
|
|
1111
|
+
model: str(p, path, "model"),
|
|
1112
|
+
effort: str(p, path, "effort"),
|
|
1113
|
+
fastMode: p.fast_mode === true
|
|
1114
|
+
};
|
|
1115
|
+
}
|
|
1116
|
+
let defaultProfile = null;
|
|
1117
|
+
if (conductorT.default_profile !== undefined) {
|
|
1118
|
+
defaultProfile = str(conductorT, "conductor", "default_profile") || null;
|
|
1119
|
+
if (defaultProfile && !Object.hasOwn(profiles, defaultProfile))
|
|
1120
|
+
problems.push(`"conductor.default_profile" is "${defaultProfile}", but there is no [conductor.profiles.${defaultProfile}]`);
|
|
1121
|
+
}
|
|
1086
1122
|
for (const [path, t, keys] of known)
|
|
1087
1123
|
for (const key of Object.keys(t))
|
|
1088
1124
|
if (!keys.includes(key))
|
|
@@ -1114,6 +1150,14 @@ function parseConfig(text, source = CONFIG_FILE) {
|
|
|
1114
1150
|
else
|
|
1115
1151
|
problems.push(`"gates.required_checks" must be a list of check names`);
|
|
1116
1152
|
}
|
|
1153
|
+
let localCommands = [];
|
|
1154
|
+
if (gatesT.local_commands !== undefined) {
|
|
1155
|
+
const v = gatesT.local_commands;
|
|
1156
|
+
if (Array.isArray(v) && v.every((c) => typeof c === "string" && c.trim()))
|
|
1157
|
+
localCommands = v.map((c) => c.trim());
|
|
1158
|
+
else
|
|
1159
|
+
problems.push(`"gates.local_commands" must be a list of shell commands`);
|
|
1160
|
+
}
|
|
1117
1161
|
const config = {
|
|
1118
1162
|
project: {
|
|
1119
1163
|
name: str(project, "project", "name"),
|
|
@@ -1135,8 +1179,9 @@ function parseConfig(text, source = CONFIG_FILE) {
|
|
|
1135
1179
|
github: {
|
|
1136
1180
|
repository: str(github, "github", "repository", { pattern: REPOSITORY, hint: "owner/name" })
|
|
1137
1181
|
},
|
|
1138
|
-
gates: { requiredChecks },
|
|
1139
|
-
policy: { silentAfterMinutes }
|
|
1182
|
+
gates: { requiredChecks, localCommands },
|
|
1183
|
+
policy: { silentAfterMinutes },
|
|
1184
|
+
conductor: { defaultProfile, profiles }
|
|
1140
1185
|
};
|
|
1141
1186
|
if (problems.length)
|
|
1142
1187
|
throw new ConfigError(source, problems);
|
|
@@ -1170,187 +1215,45 @@ repository = ${q(p.repository)}
|
|
|
1170
1215
|
|
|
1171
1216
|
[policy]
|
|
1172
1217
|
silence_minutes = 15 # a worker with no report for longer than this shows as silent
|
|
1218
|
+
|
|
1219
|
+
# How \`armada brief\` launches workers on Conductor. Every value is passed explicitly;
|
|
1220
|
+
# \`conductor model\` lists each agent's model ids and effort levels.
|
|
1221
|
+
[conductor]
|
|
1222
|
+
default_profile = "opus"
|
|
1223
|
+
|
|
1224
|
+
[conductor.profiles.opus]
|
|
1225
|
+
agent = "claude"
|
|
1226
|
+
model = "opus-5-5-1m"
|
|
1227
|
+
effort = "high"
|
|
1228
|
+
|
|
1229
|
+
[conductor.profiles.codex]
|
|
1230
|
+
agent = "codex"
|
|
1231
|
+
model = "gpt-6.1-sol"
|
|
1232
|
+
effort = "high"
|
|
1173
1233
|
`;
|
|
1174
1234
|
}
|
|
1175
1235
|
function slugify(name) {
|
|
1176
1236
|
return name.normalize("NFKD").replace(/[\u0300-\u036f]/g, "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "") || "project";
|
|
1177
1237
|
}
|
|
1178
|
-
|
|
1179
|
-
|
|
1180
|
-
|
|
1181
|
-
|
|
1182
|
-
|
|
1183
|
-
|
|
1184
|
-
|
|
1185
|
-
|
|
1186
|
-
|
|
1187
|
-
|
|
1188
|
-
|
|
1189
|
-
|
|
1190
|
-
|
|
1191
|
-
|
|
1192
|
-
|
|
1193
|
-
|
|
1194
|
-
}
|
|
1195
|
-
{
|
|
1196
|
-
name: "tursoToken",
|
|
1197
|
-
variable: "ARMADA_TURSO_TOKEN",
|
|
1198
|
-
secret: true,
|
|
1199
|
-
label: "Turso database token",
|
|
1200
|
-
hint: "`turso db tokens create <database>`"
|
|
1201
|
-
}
|
|
1202
|
-
];
|
|
1203
|
-
var clean = (v) => v?.trim() || null;
|
|
1204
|
-
var fromEnv = (env, variable) => {
|
|
1205
|
-
const value = clean(env[variable]);
|
|
1206
|
-
return value ? { value, source: { kind: "env", variable } } : null;
|
|
1207
|
-
};
|
|
1208
|
-
function resolveCredentials({ env, store = {}, personal, ghToken }) {
|
|
1209
|
-
const fromStore = (variable) => {
|
|
1210
|
-
const value = clean(store[variable]);
|
|
1211
|
-
return value ? { value, source: { kind: "store" } } : null;
|
|
1212
|
-
};
|
|
1213
|
-
const stored = (variable) => fromEnv(env, variable) ?? fromStore(variable);
|
|
1214
|
-
const fromGh = () => {
|
|
1215
|
-
const value = clean(ghToken?.());
|
|
1216
|
-
return value ? { value, source: { kind: "gh" } } : null;
|
|
1217
|
-
};
|
|
1218
|
-
const tursoUrlConfig = clean(personal?.turso.url);
|
|
1219
|
-
const found = {
|
|
1220
|
-
linearApiKey: stored("LINEAR_API_KEY"),
|
|
1221
|
-
tursoUrl: stored("ARMADA_TURSO_URL") ?? (tursoUrlConfig ? { value: tursoUrlConfig, source: { kind: "config", key: "turso.url" } } : null),
|
|
1222
|
-
tursoToken: stored("ARMADA_TURSO_TOKEN"),
|
|
1223
|
-
githubToken: fromEnv(env, "GITHUB_TOKEN") ?? fromEnv(env, "GH_TOKEN") ?? fromGh()
|
|
1224
|
-
};
|
|
1225
|
-
return {
|
|
1226
|
-
linearApiKey: found.linearApiKey?.value ?? null,
|
|
1227
|
-
tursoUrl: found.tursoUrl?.value ?? null,
|
|
1228
|
-
tursoToken: found.tursoToken?.value ?? null,
|
|
1229
|
-
githubToken: found.githubToken?.value ?? null,
|
|
1230
|
-
sources: {
|
|
1231
|
-
linearApiKey: found.linearApiKey?.source ?? null,
|
|
1232
|
-
tursoUrl: found.tursoUrl?.source ?? null,
|
|
1233
|
-
tursoToken: found.tursoToken?.source ?? null,
|
|
1234
|
-
githubToken: found.githubToken?.source ?? null
|
|
1235
|
-
}
|
|
1236
|
-
};
|
|
1237
|
-
}
|
|
1238
|
-
var missingKeys = (credentials) => STORED_KEYS.filter((k) => credentials[k.name] === null);
|
|
1239
|
-
function missingKeyMessage(key) {
|
|
1240
|
-
return `${key.variable} is not set. Set it in the environment, or run \`armada auth login\` to store it on this machine (${key.hint}).`;
|
|
1241
|
-
}
|
|
1242
|
-
// ../core/src/dotenv.ts
|
|
1243
|
-
var ASSIGNMENT = /^\s*(export\s+)?([A-Za-z_][A-Za-z0-9_]*)=(.*)$/;
|
|
1244
|
-
function shellWord(raw) {
|
|
1245
|
-
let out = "";
|
|
1246
|
-
let k = 0;
|
|
1247
|
-
while (k < raw.length) {
|
|
1248
|
-
const c = raw.charAt(k);
|
|
1249
|
-
if (c === " " || c === "\t")
|
|
1250
|
-
break;
|
|
1251
|
-
if (c === "'") {
|
|
1252
|
-
const end = raw.indexOf("'", k + 1);
|
|
1253
|
-
if (end < 0)
|
|
1254
|
-
return null;
|
|
1255
|
-
out += raw.slice(k + 1, end);
|
|
1256
|
-
k = end + 1;
|
|
1257
|
-
} else if (c === '"') {
|
|
1258
|
-
k++;
|
|
1259
|
-
for (;; ) {
|
|
1260
|
-
if (k >= raw.length)
|
|
1261
|
-
return null;
|
|
1262
|
-
const d = raw.charAt(k);
|
|
1263
|
-
if (d === '"')
|
|
1264
|
-
break;
|
|
1265
|
-
const next = raw.charAt(k + 1);
|
|
1266
|
-
if (d === "\\" && (next === '"' || next === "\\" || next === "$" || next === "`")) {
|
|
1267
|
-
out += next;
|
|
1268
|
-
k += 2;
|
|
1269
|
-
} else {
|
|
1270
|
-
out += d;
|
|
1271
|
-
k++;
|
|
1272
|
-
}
|
|
1273
|
-
}
|
|
1274
|
-
k++;
|
|
1275
|
-
} else if (c === "\\") {
|
|
1276
|
-
if (k + 1 >= raw.length)
|
|
1277
|
-
return null;
|
|
1278
|
-
out += raw.charAt(k + 1);
|
|
1279
|
-
k += 2;
|
|
1280
|
-
} else {
|
|
1281
|
-
out += c;
|
|
1282
|
-
k++;
|
|
1283
|
-
}
|
|
1284
|
-
}
|
|
1285
|
-
const rest = raw.slice(k).trim();
|
|
1286
|
-
return rest === "" || rest.startsWith("#") ? { value: out, comment: rest } : null;
|
|
1287
|
-
}
|
|
1288
|
-
function parseLine(line) {
|
|
1289
|
-
const trimmed = line.trim();
|
|
1290
|
-
if (!trimmed || trimmed.startsWith("#"))
|
|
1291
|
-
return "blank";
|
|
1292
|
-
const m = ASSIGNMENT.exec(line);
|
|
1293
|
-
if (!m)
|
|
1294
|
-
return null;
|
|
1295
|
-
const word = shellWord(m[3] ?? "");
|
|
1296
|
-
return word === null ? null : { key: m[2] ?? "", value: word.value };
|
|
1297
|
-
}
|
|
1298
|
-
var splitLines = (text) => text.split(/\r?\n/);
|
|
1299
|
-
function parseDotenv(text) {
|
|
1300
|
-
const values = new Map;
|
|
1301
|
-
const invalidLines = [];
|
|
1302
|
-
const assigned = new Set;
|
|
1303
|
-
splitLines(text).forEach((line, index) => {
|
|
1304
|
-
const key = ASSIGNMENT.exec(line)?.[2];
|
|
1305
|
-
if (key !== undefined)
|
|
1306
|
-
assigned.add(key);
|
|
1307
|
-
const parsed = parseLine(line);
|
|
1308
|
-
if (parsed === null)
|
|
1309
|
-
invalidLines.push(index + 1);
|
|
1310
|
-
else if (parsed !== "blank")
|
|
1311
|
-
values.set(parsed.key, parsed.value);
|
|
1312
|
-
});
|
|
1313
|
-
return { values: Object.fromEntries(values), invalidLines, assigned: [...assigned] };
|
|
1314
|
-
}
|
|
1315
|
-
var SHELL_SAFE = /^[A-Za-z0-9_\-.:/@+=,%]+$/;
|
|
1316
|
-
function formatDotenvValue(key, value) {
|
|
1317
|
-
if (/[\r\n\0]/.test(value))
|
|
1318
|
-
throw new Error(`the value for ${key} contains a line break and cannot be stored`);
|
|
1319
|
-
if (value === "")
|
|
1320
|
-
return "''";
|
|
1321
|
-
return SHELL_SAFE.test(value) ? value : `'${value.replaceAll("'", `'\\''`)}'`;
|
|
1322
|
-
}
|
|
1323
|
-
function updateDotenv(text, updates) {
|
|
1324
|
-
const lines = text === "" ? [] : splitLines(text);
|
|
1325
|
-
if (lines.length && lines[lines.length - 1] === "")
|
|
1326
|
-
lines.pop();
|
|
1327
|
-
const seen = new Set;
|
|
1328
|
-
const out = [];
|
|
1329
|
-
for (const line of lines) {
|
|
1330
|
-
const m = ASSIGNMENT.exec(line);
|
|
1331
|
-
const key = m?.[2];
|
|
1332
|
-
if (!m || key === undefined || !Object.hasOwn(updates, key)) {
|
|
1333
|
-
out.push(line);
|
|
1334
|
-
continue;
|
|
1335
|
-
}
|
|
1336
|
-
if (seen.has(key))
|
|
1337
|
-
continue;
|
|
1338
|
-
seen.add(key);
|
|
1339
|
-
const value = updates[key];
|
|
1340
|
-
if (value === null || value === undefined)
|
|
1341
|
-
continue;
|
|
1342
|
-
const comment = shellWord(m[3] ?? "")?.comment;
|
|
1343
|
-
out.push(`${m[1] ?? ""}${key}=${formatDotenvValue(key, value)}${comment ? ` ${comment}` : ""}`);
|
|
1344
|
-
}
|
|
1345
|
-
for (const [key, value] of Object.entries(updates)) {
|
|
1346
|
-
if (seen.has(key) || value === null)
|
|
1347
|
-
continue;
|
|
1348
|
-
out.push(`${key}=${formatDotenvValue(key, value)}`);
|
|
1349
|
-
}
|
|
1350
|
-
return out.length ? `${out.join(`
|
|
1351
|
-
`)}
|
|
1352
|
-
` : "";
|
|
1238
|
+
function resolveProfile(config, requested) {
|
|
1239
|
+
const { profiles, defaultProfile } = config.conductor;
|
|
1240
|
+
const names = Object.keys(profiles);
|
|
1241
|
+
const name = requested ?? defaultProfile ?? (names.length === 1 ? names[0] ?? null : null);
|
|
1242
|
+
const profile = name && Object.hasOwn(profiles, name) ? profiles[name] : undefined;
|
|
1243
|
+
if (name && profile)
|
|
1244
|
+
return { name, profile };
|
|
1245
|
+
const available = names.length ? names.join(", ") : "none";
|
|
1246
|
+
if (name)
|
|
1247
|
+
return { name: null, profile: null, problem: `no Conductor profile "${name}" (available: ${available})` };
|
|
1248
|
+
if (names.length)
|
|
1249
|
+
return {
|
|
1250
|
+
name: null,
|
|
1251
|
+
profile: null,
|
|
1252
|
+
problem: `several Conductor profiles and no conductor.default_profile; pass --profile (${available})`
|
|
1253
|
+
};
|
|
1254
|
+
return { name: null, profile: null, problem: null };
|
|
1353
1255
|
}
|
|
1256
|
+
|
|
1354
1257
|
// ../core/src/model.ts
|
|
1355
1258
|
var CLOSED = ["completed", "canceled"];
|
|
1356
1259
|
var NOT_STARTED = ["triage", "backlog", "unstarted"];
|
|
@@ -1631,6 +1534,7 @@ function waitingPullRequests(m, prs) {
|
|
|
1631
1534
|
ticketOf.set(p.url, i);
|
|
1632
1535
|
return prs.filter((p) => p.state === "open").map((pr) => ({ pr, ticket: ticketOf.get(pr.url) ?? null })).sort((a, b) => a.pr.number - b.pr.number);
|
|
1633
1536
|
}
|
|
1537
|
+
|
|
1634
1538
|
// ../core/src/types.ts
|
|
1635
1539
|
var LABEL_PHASES = [
|
|
1636
1540
|
"planning",
|
|
@@ -1876,41 +1780,449 @@ async function fetchTree(opts, delegate) {
|
|
|
1876
1780
|
};
|
|
1877
1781
|
}
|
|
1878
1782
|
|
|
1879
|
-
// ../core/src/
|
|
1880
|
-
var
|
|
1881
|
-
|
|
1882
|
-
|
|
1883
|
-
|
|
1783
|
+
// ../core/src/brief.ts
|
|
1784
|
+
var ARMADA_PACKAGE = "@the-vibe-company/armada";
|
|
1785
|
+
var WORKER_SKILL_PATH = ".agents/skills/armada-worker/SKILL.md";
|
|
1786
|
+
var CONDUCTOR_HANDLE = '"$CONDUCTOR_WORKSPACE_ID/$CONDUCTOR_SESSION_ID"';
|
|
1787
|
+
var MAX_NOTES = 10;
|
|
1788
|
+
var NOTES = "pageInfo { hasNextPage } nodes { id createdAt body user { name } }";
|
|
1789
|
+
var BRIEF_QUERY = `
|
|
1790
|
+
query Brief($id: String!) {
|
|
1791
|
+
issue(id: $id) {
|
|
1792
|
+
identifier title url branchName description
|
|
1793
|
+
state { name type }
|
|
1794
|
+
parent { identifier title url }
|
|
1795
|
+
comments(first: 50) { ${NOTES} }
|
|
1796
|
+
inverseRelations(first: 25) {
|
|
1797
|
+
pageInfo { hasNextPage }
|
|
1798
|
+
nodes { type issue { identifier title url state { name type } comments(first: 50) { ${NOTES} } } }
|
|
1799
|
+
}
|
|
1800
|
+
}
|
|
1801
|
+
}`;
|
|
1802
|
+
var noteUrl = (issueUrl, id) => `${issueUrl}#comment-${id.slice(0, 8)}`;
|
|
1803
|
+
var toNotes = (issueUrl, raw) => raw.nodes.map((c) => ({ url: noteUrl(issueUrl, c.id), author: c.user?.name ?? null, createdAt: c.createdAt, body: c.body })).sort((a, b) => b.createdAt.localeCompare(a.createdAt));
|
|
1804
|
+
function normalizeBriefTicket(raw) {
|
|
1805
|
+
const warnings = [];
|
|
1806
|
+
const cut = (c, what) => {
|
|
1807
|
+
if (c.pageInfo?.hasNextPage)
|
|
1808
|
+
warnings.push(`${what}; the brief may miss the newest ones`);
|
|
1809
|
+
};
|
|
1810
|
+
cut(raw.comments, `${raw.identifier} has more comments than Armada reads`);
|
|
1811
|
+
cut(raw.inverseRelations, `${raw.identifier} has more relations than Armada reads`);
|
|
1812
|
+
const blockers = raw.inverseRelations.nodes.filter((r) => r.type === "blocks").map(({ issue: b }) => {
|
|
1813
|
+
cut(b.comments, `blocker ${b.identifier} has more comments than Armada reads`);
|
|
1814
|
+
return {
|
|
1815
|
+
id: b.identifier,
|
|
1816
|
+
title: b.title,
|
|
1817
|
+
url: b.url,
|
|
1818
|
+
status: b.state.name,
|
|
1819
|
+
statusType: b.state.type,
|
|
1820
|
+
notes: toNotes(b.url, b.comments)
|
|
1821
|
+
};
|
|
1822
|
+
}).sort((a, b) => a.id.localeCompare(b.id, "en", { numeric: true }));
|
|
1823
|
+
return {
|
|
1824
|
+
id: raw.identifier,
|
|
1825
|
+
title: raw.title,
|
|
1826
|
+
url: raw.url,
|
|
1827
|
+
branchName: raw.branchName || null,
|
|
1828
|
+
description: raw.description?.trim() ?? "",
|
|
1829
|
+
status: raw.state.name,
|
|
1830
|
+
statusType: raw.state.type,
|
|
1831
|
+
parent: raw.parent ? { id: raw.parent.identifier, title: raw.parent.title, url: raw.parent.url } : null,
|
|
1832
|
+
notes: toNotes(raw.url, raw.comments),
|
|
1833
|
+
blockers,
|
|
1834
|
+
warnings
|
|
1835
|
+
};
|
|
1884
1836
|
}
|
|
1885
|
-
function
|
|
1886
|
-
const
|
|
1887
|
-
|
|
1888
|
-
|
|
1889
|
-
|
|
1890
|
-
|
|
1891
|
-
|
|
1892
|
-
if (["FAILURE", "TIMED_OUT", "CANCELLED", "ACTION_REQUIRED", "STARTUP_FAILURE", "ERROR", "STALE"].includes(c))
|
|
1893
|
-
return "failure";
|
|
1894
|
-
return "pending";
|
|
1837
|
+
async function fetchBriefTicket(opts, id) {
|
|
1838
|
+
const data = await gql(opts, BRIEF_QUERY, { id }).catch((err) => {
|
|
1839
|
+
if (err instanceof LinearError && /not found/i.test(err.message))
|
|
1840
|
+
return { issue: null };
|
|
1841
|
+
throw err;
|
|
1842
|
+
});
|
|
1843
|
+
return data.issue ? normalizeBriefTicket(data.issue) : null;
|
|
1895
1844
|
}
|
|
1896
|
-
function
|
|
1897
|
-
|
|
1898
|
-
|
|
1899
|
-
if (states.includes("failure"))
|
|
1900
|
-
return "failure";
|
|
1901
|
-
if (states.includes("pending"))
|
|
1902
|
-
return "pending";
|
|
1903
|
-
return "success";
|
|
1845
|
+
function handBackNote(notes) {
|
|
1846
|
+
const withStatus = notes.filter((n) => parseStatusLine(n.body));
|
|
1847
|
+
return withStatus.find((n) => parseStatusLine(n.body)?.phase === "ready-to-merge") ?? withStatus[0] ?? null;
|
|
1904
1848
|
}
|
|
1905
|
-
|
|
1906
|
-
|
|
1907
|
-
|
|
1908
|
-
|
|
1909
|
-
|
|
1910
|
-
|
|
1911
|
-
|
|
1849
|
+
var VARIABLES = [
|
|
1850
|
+
{ name: "LINEAR_API_KEY", required: true, purpose: "Linear key the worker claims and reports with" },
|
|
1851
|
+
{ name: "ARMADA_TURSO_URL", required: false, purpose: "Turso database for live activity" },
|
|
1852
|
+
{ name: "ARMADA_TURSO_TOKEN", required: false, purpose: "Turso database token" }
|
|
1853
|
+
];
|
|
1854
|
+
|
|
1855
|
+
class BriefError extends Error {
|
|
1856
|
+
name = "BriefError";
|
|
1857
|
+
}
|
|
1858
|
+
function buildBrief(input) {
|
|
1859
|
+
const { config, ticket, program } = input;
|
|
1860
|
+
const warnings = [...ticket.warnings, ...program.warnings];
|
|
1861
|
+
const choice = resolveProfile(config, input.profile);
|
|
1862
|
+
if (!choice.profile && choice.problem)
|
|
1863
|
+
throw new BriefError(choice.problem);
|
|
1864
|
+
if (!choice.profile)
|
|
1865
|
+
warnings.push("armada.toml declares no [conductor.profiles.<name>]; add one so the launch passes an explicit agent, model and effort");
|
|
1866
|
+
if (ticket.statusType === "completed" || ticket.statusType === "canceled")
|
|
1867
|
+
warnings.push(`${ticket.id} is ${ticket.status}; there is nothing to launch`);
|
|
1868
|
+
const open = ticket.blockers.filter((b) => b.statusType !== "completed" && b.statusType !== "canceled");
|
|
1869
|
+
if (open.length)
|
|
1870
|
+
warnings.push(`${ticket.id} is blocked by ${open.map((b) => `${b.id} (${b.status})`).join(", ")}`);
|
|
1871
|
+
const m = buildModel(program.issues, program.rootId);
|
|
1872
|
+
const lanes = inFlight(m, program.comments, {
|
|
1873
|
+
now: input.now.getTime(),
|
|
1874
|
+
silentAfterMinutes: config.policy.silentAfterMinutes
|
|
1875
|
+
});
|
|
1876
|
+
const self = lanes.find((l) => l.issue.id === ticket.id);
|
|
1877
|
+
if (self)
|
|
1878
|
+
warnings.push(`${ticket.id} is already in flight (${self.phase}); launching again makes a second worker`);
|
|
1879
|
+
if (!program.issues.some((i) => i.id === ticket.id))
|
|
1880
|
+
warnings.push(`${ticket.id} is not under the program root ${config.tracker.programRoot}`);
|
|
1881
|
+
const parallel = lanes.filter((l) => l.issue.id !== ticket.id).map((l) => ({
|
|
1882
|
+
id: l.issue.id,
|
|
1883
|
+
title: l.issue.title,
|
|
1884
|
+
url: l.issue.url,
|
|
1885
|
+
phase: l.phase,
|
|
1886
|
+
branch: l.claim?.branch ?? null,
|
|
1887
|
+
pr: l.pr?.url ?? null
|
|
1888
|
+
}));
|
|
1889
|
+
const pkg = `${ARMADA_PACKAGE}@${input.version}`;
|
|
1890
|
+
const branch = ticket.branchName;
|
|
1891
|
+
const claimCommand = `armada claim ${ticket.id} --runtime conductor --handle ${CONDUCTOR_HANDLE}${branch ? ` --branch ${branch}` : ""}`;
|
|
1892
|
+
const has = (name) => !!input.env[name]?.trim();
|
|
1893
|
+
const environment = [
|
|
1894
|
+
...VARIABLES.map((v) => ({
|
|
1895
|
+
...v,
|
|
1896
|
+
value: null,
|
|
1897
|
+
inShell: has(v.name),
|
|
1898
|
+
inStore: !has(v.name) && !!input.stored?.includes(v.name)
|
|
1899
|
+
})),
|
|
1900
|
+
{
|
|
1901
|
+
name: "ARMADA_TICKET",
|
|
1902
|
+
required: true,
|
|
1903
|
+
value: ticket.id,
|
|
1904
|
+
inShell: false,
|
|
1905
|
+
inStore: false,
|
|
1906
|
+
purpose: "the ticket this worker owns"
|
|
1907
|
+
}
|
|
1908
|
+
];
|
|
1909
|
+
const brief = {
|
|
1910
|
+
ticket: {
|
|
1911
|
+
id: ticket.id,
|
|
1912
|
+
title: ticket.title,
|
|
1913
|
+
url: ticket.url,
|
|
1914
|
+
branch,
|
|
1915
|
+
status: ticket.status,
|
|
1916
|
+
description: ticket.description
|
|
1917
|
+
},
|
|
1918
|
+
parent: ticket.parent,
|
|
1919
|
+
runtime: "conductor",
|
|
1920
|
+
profile: choice.profile ? { name: choice.name, ...choice.profile } : null,
|
|
1921
|
+
repository: { name: config.github.repository, url: `https://github.com/${config.github.repository}` },
|
|
1922
|
+
install: `npm install -g ${pkg}`,
|
|
1923
|
+
fallback: `npm exec --yes --package=${pkg} -- armada`,
|
|
1924
|
+
claimCommand,
|
|
1925
|
+
environment,
|
|
1926
|
+
blockers: ticket.blockers.map(({ notes, ...b }) => ({ ...b, handBack: handBackNote(notes) })),
|
|
1927
|
+
notes: ticket.notes.slice(0, MAX_NOTES),
|
|
1928
|
+
parallel,
|
|
1929
|
+
warnings
|
|
1930
|
+
};
|
|
1931
|
+
if (ticket.notes.length > MAX_NOTES)
|
|
1932
|
+
warnings.push(`${ticket.id} has ${ticket.notes.length} comments; the brief carries the newest ${MAX_NOTES}`);
|
|
1933
|
+
return { ...brief, prompt: renderPrompt(brief) };
|
|
1912
1934
|
}
|
|
1913
|
-
|
|
1935
|
+
var quote = (body) => body.trim().split(`
|
|
1936
|
+
`).map((l) => l ? `> ${l}` : ">").join(`
|
|
1937
|
+
`);
|
|
1938
|
+
var byLine = (n) => `${n.author ?? "unknown"}, ${n.createdAt.slice(0, 16).replace("T", " ")}Z — ${n.url}`;
|
|
1939
|
+
function renderPrompt(b) {
|
|
1940
|
+
const t = b.ticket;
|
|
1941
|
+
const out = [
|
|
1942
|
+
`# ${t.id} — ${t.title}`,
|
|
1943
|
+
"",
|
|
1944
|
+
`You are an Armada worker. You own exactly one ticket, ${t.id} (${t.url}), and turn it into one green pull request on ${b.repository.name}. Follow the \`armada-worker\` skill (\`${WORKER_SKILL_PATH}\`) and the repository's \`AGENTS.md\`. Never merge.`,
|
|
1945
|
+
"",
|
|
1946
|
+
"## First: install Armada and claim the ticket",
|
|
1947
|
+
"",
|
|
1948
|
+
"```sh",
|
|
1949
|
+
b.install,
|
|
1950
|
+
b.claimCommand,
|
|
1951
|
+
"```",
|
|
1952
|
+
"",
|
|
1953
|
+
`This installs the coordinator's Armada version. If the global install is refused, use \`${b.fallback}\` wherever this brief or the skill says \`armada\`.`,
|
|
1954
|
+
"",
|
|
1955
|
+
"If the claim is refused, stop and say why in your reply: another worker holds the ticket.",
|
|
1956
|
+
"",
|
|
1957
|
+
"## Branch",
|
|
1958
|
+
"",
|
|
1959
|
+
t.branch ? `Work on \`${t.branch}\`. Your workspace starts on a branch Conductor named; rename it before your first commit: \`git branch -m ${t.branch}\`.` : "Linear suggests no branch name for this ticket; name yours after the ticket id.",
|
|
1960
|
+
""
|
|
1961
|
+
];
|
|
1962
|
+
if (t.description)
|
|
1963
|
+
out.push("## Ticket", "", quote(t.description), "");
|
|
1964
|
+
if (b.parent)
|
|
1965
|
+
out.push("## Parent", "", `${b.parent.id} — ${b.parent.title} (${b.parent.url}). Read it before planning.`, "");
|
|
1966
|
+
if (b.blockers.length) {
|
|
1967
|
+
out.push("## Blockers and their hand-back notes", "");
|
|
1968
|
+
for (const x of b.blockers) {
|
|
1969
|
+
out.push(`### ${x.id} — ${x.title} (${x.status})`, "", x.url, "");
|
|
1970
|
+
out.push(x.handBack ? `${byLine(x.handBack)}
|
|
1971
|
+
|
|
1972
|
+
${quote(x.handBack.body)}` : "No hand-back note.", "");
|
|
1973
|
+
}
|
|
1974
|
+
}
|
|
1975
|
+
if (b.notes.length) {
|
|
1976
|
+
out.push("## Already recorded on this ticket", "", "Newest first. Decisions here stand unless the coordinator changes them.", "");
|
|
1977
|
+
for (const n of b.notes)
|
|
1978
|
+
out.push(`### ${byLine(n)}`, "", quote(n.body), "");
|
|
1979
|
+
}
|
|
1980
|
+
out.push("## Workers in flight", "");
|
|
1981
|
+
if (b.parallel.length) {
|
|
1982
|
+
out.push("Stay out of their areas. If you must change the same files, say so in a report before you do.", "");
|
|
1983
|
+
for (const w of b.parallel)
|
|
1984
|
+
out.push(`- ${w.id} — ${w.title} (${w.phase})${w.branch ? `, branch \`${w.branch}\`` : ""}${w.pr ? `, ${w.pr}` : ""}`);
|
|
1985
|
+
} else
|
|
1986
|
+
out.push("None.");
|
|
1987
|
+
out.push("", "## Environment", "", `The coordinator set ${b.environment.map((v) => `\`${v.name}\``).join(", ")} in this workspace. Never print, commit or log their values.`);
|
|
1988
|
+
return `${out.join(`
|
|
1989
|
+
`)}
|
|
1990
|
+
`;
|
|
1991
|
+
}
|
|
1992
|
+
async function loadBrief(config, opts) {
|
|
1993
|
+
const now = opts.now ?? (() => new Date);
|
|
1994
|
+
const linear = { apiKey: opts.linearApiKey, ...opts.fetch ? { fetch: opts.fetch } : {} };
|
|
1995
|
+
const choice = resolveProfile(config, opts.profile);
|
|
1996
|
+
if (!choice.profile && choice.problem)
|
|
1997
|
+
throw new BriefError(choice.problem);
|
|
1998
|
+
const [ticket, program] = await Promise.all([
|
|
1999
|
+
fetchBriefTicket(linear, opts.ticket),
|
|
2000
|
+
fetchProgram({ ...linear, rootId: config.tracker.programRoot, labels: config.tracker.labels, now })
|
|
2001
|
+
]);
|
|
2002
|
+
if (!ticket)
|
|
2003
|
+
throw new Error(`ticket ${opts.ticket} not found in Linear`);
|
|
2004
|
+
return buildBrief({
|
|
2005
|
+
config,
|
|
2006
|
+
ticket,
|
|
2007
|
+
program,
|
|
2008
|
+
profile: opts.profile,
|
|
2009
|
+
version: opts.version,
|
|
2010
|
+
env: opts.env,
|
|
2011
|
+
...opts.stored ? { stored: opts.stored } : {},
|
|
2012
|
+
now: now()
|
|
2013
|
+
});
|
|
2014
|
+
}
|
|
2015
|
+
// ../core/src/credentials.ts
|
|
2016
|
+
var LINEAR_KEY = {
|
|
2017
|
+
name: "linearApiKey",
|
|
2018
|
+
variable: "LINEAR_API_KEY",
|
|
2019
|
+
secret: true,
|
|
2020
|
+
label: "Linear API key",
|
|
2021
|
+
hint: "Linear > Settings > Security & access > Personal API keys"
|
|
2022
|
+
};
|
|
2023
|
+
var STORED_KEYS = [
|
|
2024
|
+
LINEAR_KEY,
|
|
2025
|
+
{
|
|
2026
|
+
name: "tursoUrl",
|
|
2027
|
+
variable: "ARMADA_TURSO_URL",
|
|
2028
|
+
secret: false,
|
|
2029
|
+
label: "Turso database URL",
|
|
2030
|
+
hint: "libsql://<database>-<organization>.turso.io, from `turso db show <database> --url`"
|
|
2031
|
+
},
|
|
2032
|
+
{
|
|
2033
|
+
name: "tursoToken",
|
|
2034
|
+
variable: "ARMADA_TURSO_TOKEN",
|
|
2035
|
+
secret: true,
|
|
2036
|
+
label: "Turso database token",
|
|
2037
|
+
hint: "`turso db tokens create <database>`"
|
|
2038
|
+
}
|
|
2039
|
+
];
|
|
2040
|
+
var clean = (v) => v?.trim() || null;
|
|
2041
|
+
var fromEnv = (env, variable) => {
|
|
2042
|
+
const value = clean(env[variable]);
|
|
2043
|
+
return value ? { value, source: { kind: "env", variable } } : null;
|
|
2044
|
+
};
|
|
2045
|
+
function resolveCredentials({ env, store = {}, personal, ghToken }) {
|
|
2046
|
+
const fromStore = (variable) => {
|
|
2047
|
+
const value = clean(store[variable]);
|
|
2048
|
+
return value ? { value, source: { kind: "store" } } : null;
|
|
2049
|
+
};
|
|
2050
|
+
const stored = (variable) => fromEnv(env, variable) ?? fromStore(variable);
|
|
2051
|
+
const fromGh = () => {
|
|
2052
|
+
const value = clean(ghToken?.());
|
|
2053
|
+
return value ? { value, source: { kind: "gh" } } : null;
|
|
2054
|
+
};
|
|
2055
|
+
const tursoUrlConfig = clean(personal?.turso.url);
|
|
2056
|
+
const found = {
|
|
2057
|
+
linearApiKey: stored("LINEAR_API_KEY"),
|
|
2058
|
+
tursoUrl: stored("ARMADA_TURSO_URL") ?? (tursoUrlConfig ? { value: tursoUrlConfig, source: { kind: "config", key: "turso.url" } } : null),
|
|
2059
|
+
tursoToken: stored("ARMADA_TURSO_TOKEN"),
|
|
2060
|
+
githubToken: fromEnv(env, "GITHUB_TOKEN") ?? fromEnv(env, "GH_TOKEN") ?? fromGh()
|
|
2061
|
+
};
|
|
2062
|
+
return {
|
|
2063
|
+
linearApiKey: found.linearApiKey?.value ?? null,
|
|
2064
|
+
tursoUrl: found.tursoUrl?.value ?? null,
|
|
2065
|
+
tursoToken: found.tursoToken?.value ?? null,
|
|
2066
|
+
githubToken: found.githubToken?.value ?? null,
|
|
2067
|
+
sources: {
|
|
2068
|
+
linearApiKey: found.linearApiKey?.source ?? null,
|
|
2069
|
+
tursoUrl: found.tursoUrl?.source ?? null,
|
|
2070
|
+
tursoToken: found.tursoToken?.source ?? null,
|
|
2071
|
+
githubToken: found.githubToken?.source ?? null
|
|
2072
|
+
}
|
|
2073
|
+
};
|
|
2074
|
+
}
|
|
2075
|
+
var missingKeys = (credentials) => STORED_KEYS.filter((k) => credentials[k.name] === null);
|
|
2076
|
+
function missingKeyMessage(key) {
|
|
2077
|
+
return `${key.variable} is not set. Set it in the environment, or run \`armada auth login\` to store it on this machine (${key.hint}).`;
|
|
2078
|
+
}
|
|
2079
|
+
// ../core/src/dotenv.ts
|
|
2080
|
+
var ASSIGNMENT = /^\s*(export\s+)?([A-Za-z_][A-Za-z0-9_]*)=(.*)$/;
|
|
2081
|
+
function shellWord(raw) {
|
|
2082
|
+
let out = "";
|
|
2083
|
+
let k = 0;
|
|
2084
|
+
while (k < raw.length) {
|
|
2085
|
+
const c = raw.charAt(k);
|
|
2086
|
+
if (c === " " || c === "\t")
|
|
2087
|
+
break;
|
|
2088
|
+
if (c === "'") {
|
|
2089
|
+
const end = raw.indexOf("'", k + 1);
|
|
2090
|
+
if (end < 0)
|
|
2091
|
+
return null;
|
|
2092
|
+
out += raw.slice(k + 1, end);
|
|
2093
|
+
k = end + 1;
|
|
2094
|
+
} else if (c === '"') {
|
|
2095
|
+
k++;
|
|
2096
|
+
for (;; ) {
|
|
2097
|
+
if (k >= raw.length)
|
|
2098
|
+
return null;
|
|
2099
|
+
const d = raw.charAt(k);
|
|
2100
|
+
if (d === '"')
|
|
2101
|
+
break;
|
|
2102
|
+
const next = raw.charAt(k + 1);
|
|
2103
|
+
if (d === "\\" && (next === '"' || next === "\\" || next === "$" || next === "`")) {
|
|
2104
|
+
out += next;
|
|
2105
|
+
k += 2;
|
|
2106
|
+
} else {
|
|
2107
|
+
out += d;
|
|
2108
|
+
k++;
|
|
2109
|
+
}
|
|
2110
|
+
}
|
|
2111
|
+
k++;
|
|
2112
|
+
} else if (c === "\\") {
|
|
2113
|
+
if (k + 1 >= raw.length)
|
|
2114
|
+
return null;
|
|
2115
|
+
out += raw.charAt(k + 1);
|
|
2116
|
+
k += 2;
|
|
2117
|
+
} else {
|
|
2118
|
+
out += c;
|
|
2119
|
+
k++;
|
|
2120
|
+
}
|
|
2121
|
+
}
|
|
2122
|
+
const rest = raw.slice(k).trim();
|
|
2123
|
+
return rest === "" || rest.startsWith("#") ? { value: out, comment: rest } : null;
|
|
2124
|
+
}
|
|
2125
|
+
function parseLine(line) {
|
|
2126
|
+
const trimmed = line.trim();
|
|
2127
|
+
if (!trimmed || trimmed.startsWith("#"))
|
|
2128
|
+
return "blank";
|
|
2129
|
+
const m = ASSIGNMENT.exec(line);
|
|
2130
|
+
if (!m)
|
|
2131
|
+
return null;
|
|
2132
|
+
const word = shellWord(m[3] ?? "");
|
|
2133
|
+
return word === null ? null : { key: m[2] ?? "", value: word.value };
|
|
2134
|
+
}
|
|
2135
|
+
var splitLines = (text) => text.split(/\r?\n/);
|
|
2136
|
+
function parseDotenv(text) {
|
|
2137
|
+
const values = new Map;
|
|
2138
|
+
const invalidLines = [];
|
|
2139
|
+
const assigned = new Set;
|
|
2140
|
+
splitLines(text).forEach((line, index) => {
|
|
2141
|
+
const key = ASSIGNMENT.exec(line)?.[2];
|
|
2142
|
+
if (key !== undefined)
|
|
2143
|
+
assigned.add(key);
|
|
2144
|
+
const parsed = parseLine(line);
|
|
2145
|
+
if (parsed === null)
|
|
2146
|
+
invalidLines.push(index + 1);
|
|
2147
|
+
else if (parsed !== "blank")
|
|
2148
|
+
values.set(parsed.key, parsed.value);
|
|
2149
|
+
});
|
|
2150
|
+
return { values: Object.fromEntries(values), invalidLines, assigned: [...assigned] };
|
|
2151
|
+
}
|
|
2152
|
+
var SHELL_SAFE = /^[A-Za-z0-9_\-.:/@+=,%]+$/;
|
|
2153
|
+
function formatDotenvValue(key, value) {
|
|
2154
|
+
if (/[\r\n\0]/.test(value))
|
|
2155
|
+
throw new Error(`the value for ${key} contains a line break and cannot be stored`);
|
|
2156
|
+
if (value === "")
|
|
2157
|
+
return "''";
|
|
2158
|
+
return SHELL_SAFE.test(value) ? value : `'${value.replaceAll("'", `'\\''`)}'`;
|
|
2159
|
+
}
|
|
2160
|
+
function updateDotenv(text, updates) {
|
|
2161
|
+
const lines = text === "" ? [] : splitLines(text);
|
|
2162
|
+
if (lines.length && lines[lines.length - 1] === "")
|
|
2163
|
+
lines.pop();
|
|
2164
|
+
const seen = new Set;
|
|
2165
|
+
const out = [];
|
|
2166
|
+
for (const line of lines) {
|
|
2167
|
+
const m = ASSIGNMENT.exec(line);
|
|
2168
|
+
const key = m?.[2];
|
|
2169
|
+
if (!m || key === undefined || !Object.hasOwn(updates, key)) {
|
|
2170
|
+
out.push(line);
|
|
2171
|
+
continue;
|
|
2172
|
+
}
|
|
2173
|
+
if (seen.has(key))
|
|
2174
|
+
continue;
|
|
2175
|
+
seen.add(key);
|
|
2176
|
+
const value = updates[key];
|
|
2177
|
+
if (value === null || value === undefined)
|
|
2178
|
+
continue;
|
|
2179
|
+
const comment = shellWord(m[3] ?? "")?.comment;
|
|
2180
|
+
out.push(`${m[1] ?? ""}${key}=${formatDotenvValue(key, value)}${comment ? ` ${comment}` : ""}`);
|
|
2181
|
+
}
|
|
2182
|
+
for (const [key, value] of Object.entries(updates)) {
|
|
2183
|
+
if (seen.has(key) || value === null)
|
|
2184
|
+
continue;
|
|
2185
|
+
out.push(`${key}=${formatDotenvValue(key, value)}`);
|
|
2186
|
+
}
|
|
2187
|
+
return out.length ? `${out.join(`
|
|
2188
|
+
`)}
|
|
2189
|
+
` : "";
|
|
2190
|
+
}
|
|
2191
|
+
// ../core/src/github.ts
|
|
2192
|
+
var GITHUB_GRAPHQL = "https://api.github.com/graphql";
|
|
2193
|
+
|
|
2194
|
+
class GithubError extends Error {
|
|
2195
|
+
name = "GithubError";
|
|
2196
|
+
}
|
|
2197
|
+
function checkState(status, conclusion) {
|
|
2198
|
+
const s = (status ?? "").toUpperCase();
|
|
2199
|
+
const c = (conclusion ?? "").toUpperCase();
|
|
2200
|
+
if (s && s !== "COMPLETED")
|
|
2201
|
+
return "pending";
|
|
2202
|
+
if (["SUCCESS", "NEUTRAL", "SKIPPED"].includes(c))
|
|
2203
|
+
return "success";
|
|
2204
|
+
if (["FAILURE", "TIMED_OUT", "CANCELLED", "ACTION_REQUIRED", "STARTUP_FAILURE", "ERROR", "STALE"].includes(c))
|
|
2205
|
+
return "failure";
|
|
2206
|
+
return "pending";
|
|
2207
|
+
}
|
|
2208
|
+
function rollup(states) {
|
|
2209
|
+
if (!states.length)
|
|
2210
|
+
return "none";
|
|
2211
|
+
if (states.includes("failure"))
|
|
2212
|
+
return "failure";
|
|
2213
|
+
if (states.includes("pending"))
|
|
2214
|
+
return "pending";
|
|
2215
|
+
return "success";
|
|
2216
|
+
}
|
|
2217
|
+
function ticketIdFromBranch(branch, known) {
|
|
2218
|
+
for (const m of branch.matchAll(/(?:^|[/_-])([a-z][a-z0-9]*-\d+)(?=[-_/]|$)/gi)) {
|
|
2219
|
+
const id = m[1]?.toUpperCase();
|
|
2220
|
+
if (id && known.has(id))
|
|
2221
|
+
return id;
|
|
2222
|
+
}
|
|
2223
|
+
return null;
|
|
2224
|
+
}
|
|
2225
|
+
function normalizePull(raw, repo) {
|
|
1914
2226
|
const status = raw.commits.nodes[0]?.commit.statusCheckRollup ?? null;
|
|
1915
2227
|
const checks = status?.contexts.nodes.map((c) => c.__typename === "CheckRun" ? { name: c.name, state: checkState(c.status, c.conclusion) } : { name: c.context, state: checkState("", c.state) });
|
|
1916
2228
|
return {
|
|
@@ -2041,24 +2353,89 @@ async function fetchDefaultBranchFile(opts) {
|
|
|
2041
2353
|
throw new GithubError(`GitHub: repository ${opts.repository} not found`);
|
|
2042
2354
|
return json.data.repository.object?.text ?? null;
|
|
2043
2355
|
}
|
|
2044
|
-
|
|
2045
|
-
|
|
2046
|
-
|
|
2047
|
-
|
|
2048
|
-
|
|
2049
|
-
|
|
2050
|
-
}
|
|
2051
|
-
|
|
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 } } }
|
|
2356
|
+
var MERGE_PULL_QUERY = `${PULL_FIELDS}
|
|
2357
|
+
query MergePull($owner: String!, $name: String!, $number: Int!) {
|
|
2358
|
+
repository(owner: $owner, name: $name) {
|
|
2359
|
+
pullRequest(number: $number) {
|
|
2360
|
+
...P
|
|
2361
|
+
mergeStateStatus baseRefName mergeCommit { oid }
|
|
2362
|
+
reviewThreads(first: 100) { totalCount nodes { isResolved } }
|
|
2363
|
+
}
|
|
2056
2364
|
}
|
|
2057
2365
|
}`;
|
|
2058
|
-
async function
|
|
2059
|
-
const
|
|
2060
|
-
const
|
|
2061
|
-
|
|
2366
|
+
async function fetchMergePull(opts) {
|
|
2367
|
+
const [owner, name] = opts.repository.split("/");
|
|
2368
|
+
const json = await githubQuery(opts, MERGE_PULL_QUERY, {
|
|
2369
|
+
owner,
|
|
2370
|
+
name,
|
|
2371
|
+
number: opts.number
|
|
2372
|
+
});
|
|
2373
|
+
const raw = json.data?.repository?.pullRequest;
|
|
2374
|
+
if (!raw)
|
|
2375
|
+
return null;
|
|
2376
|
+
const pr = normalizePull(raw, opts.repository);
|
|
2377
|
+
const threads = raw.reviewThreads.nodes;
|
|
2378
|
+
return {
|
|
2379
|
+
...pr,
|
|
2380
|
+
state: pr.state ?? "open",
|
|
2381
|
+
headSha: raw.headRefOid,
|
|
2382
|
+
checks: pr.checks ?? [],
|
|
2383
|
+
mergeStateStatus: raw.mergeStateStatus,
|
|
2384
|
+
baseRef: raw.baseRefName,
|
|
2385
|
+
mergeCommit: raw.mergeCommit?.oid ?? null,
|
|
2386
|
+
reviewThreads: {
|
|
2387
|
+
total: raw.reviewThreads.totalCount,
|
|
2388
|
+
read: threads.length,
|
|
2389
|
+
unresolved: threads.filter((t) => !t.isResolved).length
|
|
2390
|
+
}
|
|
2391
|
+
};
|
|
2392
|
+
}
|
|
2393
|
+
var COMPARE_QUERY = `
|
|
2394
|
+
query Compare($owner: String!, $name: String!, $base: String!, $head: String!) {
|
|
2395
|
+
repository(owner: $owner, name: $name) {
|
|
2396
|
+
ref(qualifiedName: $base) { target { oid } compare(headRef: $head) { status aheadBy behindBy } }
|
|
2397
|
+
}
|
|
2398
|
+
}`;
|
|
2399
|
+
async function fetchComparison(opts) {
|
|
2400
|
+
const [owner, name] = opts.repository.split("/");
|
|
2401
|
+
const json = await githubQuery(opts, COMPARE_QUERY, { owner, name, base: `refs/heads/${opts.base}`, head: opts.head });
|
|
2402
|
+
const ref = json.data?.repository?.ref;
|
|
2403
|
+
if (!ref?.compare)
|
|
2404
|
+
return null;
|
|
2405
|
+
return { baseSha: ref.target.oid, ...ref.compare };
|
|
2406
|
+
}
|
|
2407
|
+
async function fetchPullDiff(opts) {
|
|
2408
|
+
const doFetch = opts.fetch ?? fetch;
|
|
2409
|
+
const timeoutMs = opts.timeoutMs ?? REQUEST_TIMEOUT_MS;
|
|
2410
|
+
const res = await doFetch(`https://api.github.com/repos/${opts.repository}/pulls/${opts.number}`, {
|
|
2411
|
+
method: "GET",
|
|
2412
|
+
headers: { Accept: "application/vnd.github.diff", Authorization: `Bearer ${opts.token}` },
|
|
2413
|
+
signal: AbortSignal.timeout(timeoutMs)
|
|
2414
|
+
}).catch((err) => {
|
|
2415
|
+
throw new GithubError(`GitHub API unreachable: ${networkReason(err, timeoutMs)}`);
|
|
2416
|
+
});
|
|
2417
|
+
if (!res.ok)
|
|
2418
|
+
throw new GithubError(`GitHub API HTTP ${res.status} reading the diff of #${opts.number}`);
|
|
2419
|
+
return res.text();
|
|
2420
|
+
}
|
|
2421
|
+
// ../core/src/labels.ts
|
|
2422
|
+
function requiredLabels(config) {
|
|
2423
|
+
return [
|
|
2424
|
+
{ name: config.tracker.labels.phaseGroup, values: [...LABEL_PHASES] },
|
|
2425
|
+
{ name: config.tracker.labels.runtimeGroup, values: config.tracker.labels.runtimes }
|
|
2426
|
+
];
|
|
2427
|
+
}
|
|
2428
|
+
var LABELS_QUERY = `
|
|
2429
|
+
query Labels($root: String!, $filter: IssueLabelFilter) {
|
|
2430
|
+
issue(id: $root) { team { id key } }
|
|
2431
|
+
issueLabels(first: 50, filter: $filter) {
|
|
2432
|
+
nodes { id name isGroup team { id } children(first: 100) { nodes { name } } }
|
|
2433
|
+
}
|
|
2434
|
+
}`;
|
|
2435
|
+
async function readLabels(config, opts) {
|
|
2436
|
+
const wanted = requiredLabels(config);
|
|
2437
|
+
const data = await gql(opts, LABELS_QUERY, {
|
|
2438
|
+
root: config.tracker.programRoot,
|
|
2062
2439
|
filter: { or: wanted.map((g) => ({ name: { eqIgnoreCase: g.name } })) }
|
|
2063
2440
|
});
|
|
2064
2441
|
if (!data.issue)
|
|
@@ -2430,7 +2807,11 @@ function handBackProblems({ pr, repository, sha, requiredChecks }) {
|
|
|
2430
2807
|
problems.push(`the head of pull request #${pr.number} could not be read from GitHub`);
|
|
2431
2808
|
else if (sha && FULL_SHA.test(sha) && pr.headSha !== sha)
|
|
2432
2809
|
problems.push(`${sha} is not the head of pull request #${pr.number} (head is ${pr.headSha}); push, then report`);
|
|
2433
|
-
|
|
2810
|
+
problems.push(...checkProblems(pr.checks ?? [], requiredChecks));
|
|
2811
|
+
return problems;
|
|
2812
|
+
}
|
|
2813
|
+
function checkProblems(checks, requiredChecks) {
|
|
2814
|
+
const problems = [];
|
|
2434
2815
|
if (requiredChecks.length) {
|
|
2435
2816
|
for (const name of requiredChecks) {
|
|
2436
2817
|
const runs = checks.filter((c) => c.name === name);
|
|
@@ -2449,593 +2830,166 @@ function handBackProblems({ pr, repository, sha, requiredChecks }) {
|
|
|
2449
2830
|
}
|
|
2450
2831
|
return problems;
|
|
2451
2832
|
}
|
|
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
2833
|
|
|
2522
|
-
|
|
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 = [
|
|
2834
|
+
// ../core/src/turso.ts
|
|
2835
|
+
var MIGRATIONS = [
|
|
2530
2836
|
{
|
|
2531
|
-
|
|
2532
|
-
|
|
2533
|
-
|
|
2534
|
-
|
|
2837
|
+
version: 1,
|
|
2838
|
+
statements: [
|
|
2839
|
+
`CREATE TABLE IF NOT EXISTS projects (
|
|
2840
|
+
slug TEXT PRIMARY KEY,
|
|
2841
|
+
name TEXT NOT NULL,
|
|
2842
|
+
repository TEXT NOT NULL,
|
|
2843
|
+
program_root TEXT NOT NULL,
|
|
2844
|
+
created_at TEXT NOT NULL,
|
|
2845
|
+
updated_at TEXT NOT NULL
|
|
2846
|
+
)`,
|
|
2847
|
+
`CREATE TABLE IF NOT EXISTS events (
|
|
2848
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
2849
|
+
project TEXT NOT NULL,
|
|
2850
|
+
ticket TEXT NOT NULL,
|
|
2851
|
+
kind TEXT NOT NULL,
|
|
2852
|
+
phase TEXT,
|
|
2853
|
+
message TEXT,
|
|
2854
|
+
runtime TEXT,
|
|
2855
|
+
handle TEXT,
|
|
2856
|
+
pr_url TEXT,
|
|
2857
|
+
head_sha TEXT,
|
|
2858
|
+
created_at TEXT NOT NULL
|
|
2859
|
+
)`,
|
|
2860
|
+
"CREATE INDEX IF NOT EXISTS events_by_ticket ON events (project, ticket, created_at)",
|
|
2861
|
+
`CREATE TABLE IF NOT EXISTS runtime_handles (
|
|
2862
|
+
project TEXT NOT NULL,
|
|
2863
|
+
ticket TEXT NOT NULL,
|
|
2864
|
+
runtime TEXT NOT NULL,
|
|
2865
|
+
handle TEXT NOT NULL,
|
|
2866
|
+
branch TEXT,
|
|
2867
|
+
claimed_at TEXT NOT NULL,
|
|
2868
|
+
released_at TEXT,
|
|
2869
|
+
PRIMARY KEY (project, ticket)
|
|
2870
|
+
)`,
|
|
2871
|
+
`CREATE TABLE IF NOT EXISTS inbox_items (
|
|
2872
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
2873
|
+
project TEXT NOT NULL,
|
|
2874
|
+
ticket TEXT,
|
|
2875
|
+
kind TEXT NOT NULL,
|
|
2876
|
+
recipient TEXT NOT NULL,
|
|
2877
|
+
author TEXT,
|
|
2878
|
+
body TEXT NOT NULL,
|
|
2879
|
+
created_at TEXT NOT NULL,
|
|
2880
|
+
resolved_at TEXT,
|
|
2881
|
+
resolution TEXT
|
|
2882
|
+
)`,
|
|
2883
|
+
"CREATE INDEX IF NOT EXISTS inbox_open ON inbox_items (project, recipient, resolved_at)",
|
|
2884
|
+
`CREATE TABLE IF NOT EXISTS leases (
|
|
2885
|
+
project TEXT NOT NULL,
|
|
2886
|
+
name TEXT NOT NULL,
|
|
2887
|
+
holder TEXT NOT NULL,
|
|
2888
|
+
acquired_at TEXT NOT NULL,
|
|
2889
|
+
expires_at TEXT NOT NULL,
|
|
2890
|
+
PRIMARY KEY (project, name)
|
|
2891
|
+
)`
|
|
2535
2892
|
]
|
|
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
2893
|
}
|
|
2546
|
-
|
|
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) ?? "");
|
|
2894
|
+
];
|
|
2895
|
+
var SCHEMA_VERSION = MIGRATIONS.at(-1)?.version ?? 0;
|
|
2569
2896
|
|
|
2570
|
-
class
|
|
2571
|
-
name = "
|
|
2897
|
+
class TursoError extends Error {
|
|
2898
|
+
name = "TursoError";
|
|
2572
2899
|
}
|
|
2573
|
-
function
|
|
2574
|
-
|
|
2575
|
-
|
|
2576
|
-
|
|
2900
|
+
function redact(err, token) {
|
|
2901
|
+
let message = err instanceof Error ? err.message : String(err);
|
|
2902
|
+
if (token)
|
|
2903
|
+
message = message.split(token).join("***");
|
|
2904
|
+
return message.replace(/(authToken=)[^&\s"']+/gi, "$1***");
|
|
2905
|
+
}
|
|
2906
|
+
async function openTurso({ url, token }) {
|
|
2907
|
+
let db;
|
|
2577
2908
|
try {
|
|
2578
|
-
|
|
2579
|
-
|
|
2580
|
-
|
|
2909
|
+
const { createClient } = await import("@libsql/client");
|
|
2910
|
+
db = createClient(token ? { url, authToken: token } : { url });
|
|
2911
|
+
} catch (err) {
|
|
2912
|
+
throw new TursoError(`cannot open the Turso database: ${redact(err, token)}`);
|
|
2581
2913
|
}
|
|
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
2914
|
try {
|
|
2590
|
-
|
|
2915
|
+
await migrate(db);
|
|
2591
2916
|
} catch (err) {
|
|
2592
|
-
|
|
2593
|
-
throw new
|
|
2917
|
+
db.close();
|
|
2918
|
+
throw new TursoError(`Turso database unavailable: ${redact(err, token)}`);
|
|
2594
2919
|
}
|
|
2595
|
-
|
|
2596
|
-
const setup = scripts?.setup;
|
|
2597
|
-
return typeof setup === "string" ? setup.trim() : "";
|
|
2920
|
+
return db;
|
|
2598
2921
|
}
|
|
2599
|
-
|
|
2600
|
-
|
|
2601
|
-
|
|
2602
|
-
const
|
|
2603
|
-
|
|
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)
|
|
2922
|
+
async function migrate(db) {
|
|
2923
|
+
await db.execute("CREATE TABLE IF NOT EXISTS schema_migrations (version INTEGER PRIMARY KEY, applied_at TEXT NOT NULL)");
|
|
2924
|
+
const current = Number((await db.execute("SELECT max(version) AS v FROM schema_migrations")).rows[0]?.v ?? 0);
|
|
2925
|
+
for (const m of MIGRATIONS) {
|
|
2926
|
+
if (m.version <= current)
|
|
2648
2927
|
continue;
|
|
2649
|
-
const
|
|
2650
|
-
|
|
2651
|
-
|
|
2652
|
-
|
|
2653
|
-
|
|
2654
|
-
|
|
2655
|
-
|
|
2656
|
-
|
|
2928
|
+
const stmts = [
|
|
2929
|
+
...m.statements,
|
|
2930
|
+
{
|
|
2931
|
+
sql: "INSERT OR IGNORE INTO schema_migrations (version, applied_at) VALUES (?, ?)",
|
|
2932
|
+
args: [m.version, new Date().toISOString()]
|
|
2933
|
+
}
|
|
2934
|
+
];
|
|
2935
|
+
await db.batch(stmts, "write");
|
|
2657
2936
|
}
|
|
2658
|
-
|
|
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;
|
|
2937
|
+
return Math.max(current, SCHEMA_VERSION);
|
|
2683
2938
|
}
|
|
2684
|
-
|
|
2685
|
-
|
|
2686
|
-
|
|
2687
|
-
|
|
2688
|
-
|
|
2689
|
-
|
|
2690
|
-
|
|
2691
|
-
|
|
2939
|
+
async function upsertProject(db, p, now = new Date) {
|
|
2940
|
+
const at = now.toISOString();
|
|
2941
|
+
await db.execute({
|
|
2942
|
+
sql: `INSERT INTO projects (slug, name, repository, program_root, created_at, updated_at)
|
|
2943
|
+
VALUES (?, ?, ?, ?, ?, ?)
|
|
2944
|
+
ON CONFLICT (slug) DO UPDATE SET
|
|
2945
|
+
name = excluded.name, repository = excluded.repository,
|
|
2946
|
+
program_root = excluded.program_root, updated_at = excluded.updated_at
|
|
2947
|
+
WHERE name IS NOT excluded.name OR repository IS NOT excluded.repository
|
|
2948
|
+
OR program_root IS NOT excluded.program_root`,
|
|
2949
|
+
args: [p.slug, p.name, p.repository, p.programRoot, at, at]
|
|
2950
|
+
});
|
|
2692
2951
|
}
|
|
2693
|
-
function
|
|
2694
|
-
const
|
|
2695
|
-
|
|
2696
|
-
|
|
2697
|
-
|
|
2698
|
-
|
|
2699
|
-
|
|
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;
|
|
2952
|
+
async function ensureProject(db, p, now = new Date) {
|
|
2953
|
+
const at = now.toISOString();
|
|
2954
|
+
await db.execute({
|
|
2955
|
+
sql: `INSERT OR IGNORE INTO projects (slug, name, repository, program_root, created_at, updated_at)
|
|
2956
|
+
VALUES (?, ?, ?, ?, ?, ?)`,
|
|
2957
|
+
args: [p.slug, p.name, p.repository, p.programRoot, at, at]
|
|
2958
|
+
});
|
|
2718
2959
|
}
|
|
2719
|
-
function
|
|
2720
|
-
const
|
|
2721
|
-
|
|
2722
|
-
|
|
2723
|
-
|
|
2724
|
-
|
|
2725
|
-
|
|
2726
|
-
|
|
2727
|
-
|
|
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
|
-
`;
|
|
2960
|
+
async function listProjects(db) {
|
|
2961
|
+
const rs = await db.execute("SELECT slug, name, repository, program_root, created_at, updated_at FROM projects ORDER BY slug");
|
|
2962
|
+
return rs.rows.map((r) => ({
|
|
2963
|
+
slug: String(r.slug),
|
|
2964
|
+
name: String(r.name),
|
|
2965
|
+
repository: String(r.repository),
|
|
2966
|
+
programRoot: String(r.program_root),
|
|
2967
|
+
createdAt: String(r.created_at),
|
|
2968
|
+
updatedAt: String(r.updated_at)
|
|
2969
|
+
}));
|
|
2732
2970
|
}
|
|
2733
|
-
async function
|
|
2734
|
-
|
|
2735
|
-
|
|
2736
|
-
|
|
2737
|
-
|
|
2738
|
-
|
|
2739
|
-
|
|
2740
|
-
|
|
2741
|
-
|
|
2742
|
-
|
|
2743
|
-
|
|
2744
|
-
|
|
2745
|
-
|
|
2746
|
-
|
|
2747
|
-
|
|
2748
|
-
|
|
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;
|
|
2971
|
+
async function recordEvent(db, e) {
|
|
2972
|
+
await db.execute({
|
|
2973
|
+
sql: `INSERT INTO events (project, ticket, kind, phase, message, runtime, handle, pr_url, head_sha, created_at)
|
|
2974
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
|
2975
|
+
args: [
|
|
2976
|
+
e.project,
|
|
2977
|
+
e.ticket,
|
|
2978
|
+
e.kind,
|
|
2979
|
+
e.phase ?? null,
|
|
2980
|
+
e.message ?? null,
|
|
2981
|
+
e.runtime ?? null,
|
|
2982
|
+
e.handle ?? null,
|
|
2983
|
+
e.prUrl ?? null,
|
|
2984
|
+
e.headSha ?? null,
|
|
2985
|
+
e.at.toISOString()
|
|
2986
|
+
]
|
|
2987
|
+
});
|
|
2775
2988
|
}
|
|
2776
|
-
|
|
2777
|
-
|
|
2778
|
-
|
|
2779
|
-
|
|
2780
|
-
config,
|
|
2781
|
-
program,
|
|
2782
|
-
forge,
|
|
2783
|
-
forgeError = null,
|
|
2784
|
-
lastEvents,
|
|
2785
|
-
extraWarnings = [],
|
|
2786
|
-
now
|
|
2787
|
-
}) {
|
|
2788
|
-
const issues = attachPullRequests(program, forge);
|
|
2789
|
-
const m = buildModel(issues, program.rootId);
|
|
2790
|
-
const lanes = inFlight(m, program.comments, {
|
|
2791
|
-
now: now.getTime(),
|
|
2792
|
-
silentAfterMinutes: config.policy.silentAfterMinutes,
|
|
2793
|
-
...lastEvents ? { lastEvents } : {}
|
|
2794
|
-
});
|
|
2795
|
-
const phaseOf = new Map(lanes.map((l) => [l.issue.id, l.phase]));
|
|
2796
|
-
const prRef = (p) => ({
|
|
2797
|
-
number: p.number,
|
|
2798
|
-
url: p.url,
|
|
2799
|
-
title: p.title,
|
|
2800
|
-
draft: p.draft ?? null,
|
|
2801
|
-
ci: p.ci ?? null,
|
|
2802
|
-
mergeable: p.mergeable ?? null
|
|
2803
|
-
});
|
|
2804
|
-
return {
|
|
2805
|
-
schemaVersion: STATUS_SCHEMA_VERSION,
|
|
2806
|
-
generatedAt: now.toISOString(),
|
|
2807
|
-
project: { name: config.project.name, slug: config.project.slug, repository: config.github.repository },
|
|
2808
|
-
programRoot: { id: m.root.id, title: m.root.title, url: m.root.url },
|
|
2809
|
-
sources: {
|
|
2810
|
-
linear: { fetchedAt: program.fetchedAt },
|
|
2811
|
-
github: { fetchedAt: forge?.fetchedAt ?? null, error: forge ? null : forgeError ?? "not read" }
|
|
2812
|
-
},
|
|
2813
|
-
silentAfterMinutes: config.policy.silentAfterMinutes,
|
|
2814
|
-
inFlight: lanes.map((l) => ({
|
|
2815
|
-
id: l.issue.id,
|
|
2816
|
-
title: l.issue.title,
|
|
2817
|
-
url: l.issue.url,
|
|
2818
|
-
spec: l.spec,
|
|
2819
|
-
phase: l.phase,
|
|
2820
|
-
phaseSource: l.phaseSource,
|
|
2821
|
-
runtime: l.runtime,
|
|
2822
|
-
agent: l.agent,
|
|
2823
|
-
since: l.since,
|
|
2824
|
-
lastUpdate: l.lastUpdate,
|
|
2825
|
-
lastReport: l.lastReport,
|
|
2826
|
-
silent: l.flags.includes("silent"),
|
|
2827
|
-
statusLine: l.statusLine ? { summary: l.statusLine.summary, at: l.statusLine.at, url: l.statusLine.url } : null,
|
|
2828
|
-
pr: l.pr ? prRef(l.pr) : null,
|
|
2829
|
-
openBlockers: l.openBlockers,
|
|
2830
|
-
flags: l.flags
|
|
2831
|
-
})),
|
|
2832
|
-
frontier: frontier(m, config.tracker.readyLabel).map((c) => ({
|
|
2833
|
-
id: c.issue.id,
|
|
2834
|
-
title: c.issue.title,
|
|
2835
|
-
url: c.issue.url,
|
|
2836
|
-
spec: c.spec,
|
|
2837
|
-
readyForAgent: c.readyForAgent,
|
|
2838
|
-
onCriticalPath: c.onCriticalPath,
|
|
2839
|
-
unlocks: c.unlocksAll
|
|
2840
|
-
})),
|
|
2841
|
-
pullRequests: forge ? waitingPullRequests(m, forge.prs).map(({ pr, ticket }) => ({
|
|
2842
|
-
...prRef(pr),
|
|
2843
|
-
headSha: pr.headSha ?? null,
|
|
2844
|
-
updatedAt: pr.updatedAt ?? null,
|
|
2845
|
-
failingChecks: (pr.checks ?? []).filter((c) => c.state === "failure").map((c) => c.name),
|
|
2846
|
-
ticket: ticket ? { id: ticket.id, phase: phaseOf.get(ticket.id) ?? ticket.agentPhase } : null
|
|
2847
|
-
})) : null,
|
|
2848
|
-
warnings: [...program.warnings, ...forge?.warnings ?? [], ...extraWarnings]
|
|
2849
|
-
};
|
|
2850
|
-
}
|
|
2851
|
-
async function loadStatus(config, opts) {
|
|
2852
|
-
const now = opts.now ?? (() => new Date);
|
|
2853
|
-
const programP = fetchProgram({
|
|
2854
|
-
apiKey: opts.linearApiKey,
|
|
2855
|
-
rootId: config.tracker.programRoot,
|
|
2856
|
-
labels: config.tracker.labels,
|
|
2857
|
-
...opts.fetch ? { fetch: opts.fetch } : {},
|
|
2858
|
-
now
|
|
2859
|
-
});
|
|
2860
|
-
const forgeP = opts.githubToken ? fetchForge({
|
|
2861
|
-
token: opts.githubToken,
|
|
2862
|
-
repository: config.github.repository,
|
|
2863
|
-
...opts.fetch ? { fetch: opts.fetch } : {},
|
|
2864
|
-
now
|
|
2865
|
-
}).then((forge2) => ({ forge: forge2, error: null }), (err) => ({ forge: null, error: err instanceof Error ? err.message : String(err) })) : Promise.resolve({ forge: null, error: "no GitHub token (set GITHUB_TOKEN or run gh auth login)" });
|
|
2866
|
-
const eventsP = opts.lastEvents ? opts.lastEvents().then((events2) => ({ events: events2 }), (err) => ({
|
|
2867
|
-
warning: `Turso could not be read (${err instanceof Error ? err.message : String(err)}); silence is measured from Linear only`
|
|
2868
|
-
})) : Promise.resolve({});
|
|
2869
|
-
const [program, { forge, error }, events] = await Promise.all([programP, forgeP, eventsP]);
|
|
2870
|
-
return buildStatus({
|
|
2871
|
-
config,
|
|
2872
|
-
program,
|
|
2873
|
-
forge,
|
|
2874
|
-
forgeError: error,
|
|
2875
|
-
...events.events ? { lastEvents: events.events } : {},
|
|
2876
|
-
extraWarnings: events.warning ? [events.warning] : [],
|
|
2877
|
-
now: now()
|
|
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]
|
|
2989
|
+
async function lastEventTimes(db, project) {
|
|
2990
|
+
const rs = await db.execute({
|
|
2991
|
+
sql: "SELECT ticket, max(created_at) AS at FROM events WHERE project = ? GROUP BY ticket",
|
|
2992
|
+
args: [project]
|
|
3039
2993
|
});
|
|
3040
2994
|
return Object.fromEntries(rs.rows.map((r) => [String(r.ticket), String(r.at)]));
|
|
3041
2995
|
}
|
|
@@ -3057,6 +3011,39 @@ async function releaseRuntimeHandle(db, project, ticket, at) {
|
|
|
3057
3011
|
args: [at.toISOString(), project, ticket]
|
|
3058
3012
|
});
|
|
3059
3013
|
}
|
|
3014
|
+
async function openRuntimeHandles(db, project) {
|
|
3015
|
+
const rs = await db.execute({
|
|
3016
|
+
sql: `SELECT project, ticket, runtime, handle, branch, claimed_at, released_at
|
|
3017
|
+
FROM runtime_handles WHERE project = ? AND released_at IS NULL ORDER BY ticket`,
|
|
3018
|
+
args: [project]
|
|
3019
|
+
});
|
|
3020
|
+
return rs.rows.map((r) => ({
|
|
3021
|
+
project: String(r.project),
|
|
3022
|
+
ticket: String(r.ticket),
|
|
3023
|
+
runtime: String(r.runtime),
|
|
3024
|
+
handle: String(r.handle),
|
|
3025
|
+
branch: r.branch === null ? null : String(r.branch),
|
|
3026
|
+
claimedAt: String(r.claimed_at),
|
|
3027
|
+
releasedAt: null
|
|
3028
|
+
}));
|
|
3029
|
+
}
|
|
3030
|
+
async function getRuntimeHandle(db, project, ticket) {
|
|
3031
|
+
const rs = await db.execute({
|
|
3032
|
+
sql: `SELECT project, ticket, runtime, handle, branch, claimed_at, released_at
|
|
3033
|
+
FROM runtime_handles WHERE project = ? AND ticket = ?`,
|
|
3034
|
+
args: [project, ticket]
|
|
3035
|
+
});
|
|
3036
|
+
const r = rs.rows[0];
|
|
3037
|
+
return r ? {
|
|
3038
|
+
project: String(r.project),
|
|
3039
|
+
ticket: String(r.ticket),
|
|
3040
|
+
runtime: String(r.runtime),
|
|
3041
|
+
handle: String(r.handle),
|
|
3042
|
+
branch: r.branch === null ? null : String(r.branch),
|
|
3043
|
+
claimedAt: String(r.claimed_at),
|
|
3044
|
+
releasedAt: r.released_at === null ? null : String(r.released_at)
|
|
3045
|
+
} : null;
|
|
3046
|
+
}
|
|
3060
3047
|
async function addInboxItem(db, item) {
|
|
3061
3048
|
const rs = await db.execute({
|
|
3062
3049
|
sql: `INSERT INTO inbox_items (project, ticket, kind, recipient, author, body, created_at)
|
|
@@ -3092,9 +3079,60 @@ async function openInboxItems(db, q) {
|
|
|
3092
3079
|
createdAt: String(r.created_at)
|
|
3093
3080
|
}));
|
|
3094
3081
|
}
|
|
3095
|
-
|
|
3096
|
-
|
|
3097
|
-
|
|
3082
|
+
async function resolveInboxItems(db, q) {
|
|
3083
|
+
const rs = await db.execute({
|
|
3084
|
+
sql: `UPDATE inbox_items SET resolved_at = ?, resolution = ?
|
|
3085
|
+
WHERE project = ? AND ticket = ? AND kind = ? AND resolved_at IS NULL`,
|
|
3086
|
+
args: [q.at.toISOString(), q.resolution, q.project, q.ticket, q.kind]
|
|
3087
|
+
});
|
|
3088
|
+
return rs.rowsAffected;
|
|
3089
|
+
}
|
|
3090
|
+
async function acquireLease(db, l) {
|
|
3091
|
+
const at = l.at.toISOString();
|
|
3092
|
+
const expires = new Date(l.at.getTime() + l.ttlMs).toISOString();
|
|
3093
|
+
const rs = await db.execute({
|
|
3094
|
+
sql: `INSERT INTO leases (project, name, holder, acquired_at, expires_at) VALUES (?, ?, ?, ?, ?)
|
|
3095
|
+
ON CONFLICT (project, name) DO UPDATE SET
|
|
3096
|
+
acquired_at = CASE WHEN leases.holder = excluded.holder THEN leases.acquired_at ELSE excluded.acquired_at END,
|
|
3097
|
+
holder = excluded.holder, expires_at = excluded.expires_at
|
|
3098
|
+
WHERE leases.holder = excluded.holder OR leases.expires_at <= ?`,
|
|
3099
|
+
args: [l.project, l.name, l.holder, at, expires, at]
|
|
3100
|
+
});
|
|
3101
|
+
if (rs.rowsAffected)
|
|
3102
|
+
return { acquired: true };
|
|
3103
|
+
return { acquired: false, held: await getLease(db, l.project, l.name) };
|
|
3104
|
+
}
|
|
3105
|
+
async function getLease(db, project, name) {
|
|
3106
|
+
const rs = await db.execute({
|
|
3107
|
+
sql: "SELECT project, name, holder, acquired_at, expires_at FROM leases WHERE project = ? AND name = ?",
|
|
3108
|
+
args: [project, name]
|
|
3109
|
+
});
|
|
3110
|
+
const r = rs.rows[0];
|
|
3111
|
+
return r ? {
|
|
3112
|
+
project: String(r.project),
|
|
3113
|
+
name: String(r.name),
|
|
3114
|
+
holder: String(r.holder),
|
|
3115
|
+
acquiredAt: String(r.acquired_at),
|
|
3116
|
+
expiresAt: String(r.expires_at)
|
|
3117
|
+
} : null;
|
|
3118
|
+
}
|
|
3119
|
+
async function renewLease(db, l) {
|
|
3120
|
+
const rs = await db.execute({
|
|
3121
|
+
sql: "UPDATE leases SET expires_at = ? WHERE project = ? AND name = ? AND holder = ?",
|
|
3122
|
+
args: [new Date(l.at.getTime() + l.ttlMs).toISOString(), l.project, l.name, l.holder]
|
|
3123
|
+
});
|
|
3124
|
+
return rs.rowsAffected > 0;
|
|
3125
|
+
}
|
|
3126
|
+
async function releaseLease(db, l) {
|
|
3127
|
+
await db.execute({
|
|
3128
|
+
sql: "DELETE FROM leases WHERE project = ? AND name = ? AND holder = ?",
|
|
3129
|
+
args: [l.project, l.name, l.holder]
|
|
3130
|
+
});
|
|
3131
|
+
}
|
|
3132
|
+
|
|
3133
|
+
// ../core/src/worker.ts
|
|
3134
|
+
class Refusal extends Error {
|
|
3135
|
+
name = "Refusal";
|
|
3098
3136
|
}
|
|
3099
3137
|
var TURSO_TIMEOUT_MS = 1e4;
|
|
3100
3138
|
async function live(ctx, warnings, what, step) {
|
|
@@ -3119,7 +3157,7 @@ async function live(ctx, warnings, what, step) {
|
|
|
3119
3157
|
clearTimeout(timer);
|
|
3120
3158
|
}
|
|
3121
3159
|
}
|
|
3122
|
-
var
|
|
3160
|
+
var projectOf = (config) => ({
|
|
3123
3161
|
slug: config.project.slug,
|
|
3124
3162
|
name: config.project.name,
|
|
3125
3163
|
repository: config.github.repository,
|
|
@@ -3133,6 +3171,12 @@ async function readOpenTicket(ctx, id) {
|
|
|
3133
3171
|
throw new Refusal(`${ticket.id} is ${ticket.statusType}; there is nothing to work on`);
|
|
3134
3172
|
return ticket;
|
|
3135
3173
|
}
|
|
3174
|
+
var ID = /(?:^|[^a-z0-9])([a-z][a-z0-9]*-\d+)(?=$|[^a-z0-9])/gi;
|
|
3175
|
+
function ticketFromBranch(branch, programRoot) {
|
|
3176
|
+
const ids = [...branch.matchAll(ID)].map((m) => (m[1] ?? "").toUpperCase());
|
|
3177
|
+
const team = programRoot.split("-")[0]?.toUpperCase();
|
|
3178
|
+
return ids.find((id) => id.split("-")[0] === team) ?? ids[0] ?? null;
|
|
3179
|
+
}
|
|
3136
3180
|
function activeClaimComments(comments) {
|
|
3137
3181
|
const asc = [...comments].sort((a, b) => a.createdAt.localeCompare(b.createdAt) || a.id.localeCompare(b.id));
|
|
3138
3182
|
let active = [];
|
|
@@ -3218,7 +3262,7 @@ ${claimLine({ runtime: runtime.name, handle: input.handle, branch, started })}`;
|
|
|
3218
3262
|
lines.push(`${inProgress ? `Moved to ${inProgress.name}` : "State unchanged"}, assigned to ${viewer.name}, labels ${phaseLabel?.name ?? ticket.agentPhase} and ${runtime.name}.`);
|
|
3219
3263
|
const at = ctx.now();
|
|
3220
3264
|
await live(ctx, warnings, "record the claim", async (db) => {
|
|
3221
|
-
await ensureProject(db,
|
|
3265
|
+
await ensureProject(db, projectOf(config), at);
|
|
3222
3266
|
await saveRuntimeHandle(db, {
|
|
3223
3267
|
project: config.project.slug,
|
|
3224
3268
|
ticket: ticket.id,
|
|
@@ -3317,7 +3361,7 @@ ${body}` : statusLine);
|
|
|
3317
3361
|
];
|
|
3318
3362
|
const at = ctx.now();
|
|
3319
3363
|
const inbox = await live(ctx, warnings, "record the report", async (db) => {
|
|
3320
|
-
await ensureProject(db,
|
|
3364
|
+
await ensureProject(db, projectOf(config), at);
|
|
3321
3365
|
await recordEvent(db, {
|
|
3322
3366
|
project: config.project.slug,
|
|
3323
3367
|
ticket: ticket.id,
|
|
@@ -3338,38 +3382,918 @@ ${body}` : statusLine);
|
|
|
3338
3382
|
});
|
|
3339
3383
|
return openInboxItems(db, { project: config.project.slug, recipient: "worker", ticket: ticket.id });
|
|
3340
3384
|
});
|
|
3341
|
-
return { ticket: ticket.id, url: ticket.url, lines, warnings, inbox };
|
|
3385
|
+
return { ticket: ticket.id, url: ticket.url, lines, warnings, inbox };
|
|
3386
|
+
}
|
|
3387
|
+
async function releaseTicket(ctx, input) {
|
|
3388
|
+
const { config, linear } = ctx;
|
|
3389
|
+
const groups = config.tracker.labels;
|
|
3390
|
+
const ticket = await readOpenTicket(ctx, input.ticket);
|
|
3391
|
+
if (!ticket.agentPhase && !ticket.agentRuntime && !activeClaimComments(ticket.comments).length)
|
|
3392
|
+
throw new Refusal(`${ticket.id} is not claimed; there is nothing to release`);
|
|
3393
|
+
const warnings = [...ticket.warnings];
|
|
3394
|
+
const back = ticket.statusType === "started" ? firstState(ticket.states, "unstarted", "backlog") : null;
|
|
3395
|
+
await linear.updateTicket(ticket.uuid, {
|
|
3396
|
+
...back ? { stateId: back.id } : {},
|
|
3397
|
+
removeLabelIds: [...others(ticket, groups.phaseGroup, null), ...others(ticket, groups.runtimeGroup, null)]
|
|
3398
|
+
});
|
|
3399
|
+
await linear.comment(ticket.uuid, `Agent status: released — ${input.reason.trim()}`);
|
|
3400
|
+
const lines = [`Released ${ticket.id}${back ? `, moved back to ${back.name}` : ""}.`];
|
|
3401
|
+
const at = ctx.now();
|
|
3402
|
+
await live(ctx, warnings, "record the release", async (db) => {
|
|
3403
|
+
await ensureProject(db, projectOf(config), at);
|
|
3404
|
+
await releaseRuntimeHandle(db, config.project.slug, ticket.id, at);
|
|
3405
|
+
await recordEvent(db, {
|
|
3406
|
+
project: config.project.slug,
|
|
3407
|
+
ticket: ticket.id,
|
|
3408
|
+
kind: "release",
|
|
3409
|
+
message: input.reason.trim(),
|
|
3410
|
+
at
|
|
3411
|
+
});
|
|
3412
|
+
});
|
|
3413
|
+
return { ticket: ticket.id, url: ticket.url, lines, warnings, inbox: null };
|
|
3414
|
+
}
|
|
3415
|
+
|
|
3416
|
+
// ../core/src/merge.ts
|
|
3417
|
+
var MERGE_LEASE = "merge";
|
|
3418
|
+
var MERGE_LEASE_TTL_MS = 20 * 60000;
|
|
3419
|
+
var LEASE_POLL_MS = 5000;
|
|
3420
|
+
var MERGE_BACKOFF_MS = [2000, 4000, 8000];
|
|
3421
|
+
var CONFIRM_BACKOFF_MS = [1000, 2000, 4000, 8000];
|
|
3422
|
+
var UNKNOWN_BACKOFF_MS = [2000, 4000];
|
|
3423
|
+
var COMMITIZEN_TITLE = /^(feat|fix|docs|style|refactor|perf|test|build|ci|chore|revert)(\([\w./,-]+\))?!?: \S/;
|
|
3424
|
+
function findHandBack(ticket) {
|
|
3425
|
+
const c = ticket.comments.find((x) => x.status?.phase === "ready-to-merge");
|
|
3426
|
+
if (!c?.status)
|
|
3427
|
+
return null;
|
|
3428
|
+
const pr = c.status.summary.match(/\bPR #(\d+)/i)?.[1];
|
|
3429
|
+
const sha = c.status.summary.match(/\bhead ([0-9a-f]+)\b/i)?.[1];
|
|
3430
|
+
return { pr: pr ? Number(pr) : null, sha: sha?.toLowerCase() ?? null, at: c.createdAt };
|
|
3431
|
+
}
|
|
3432
|
+
var STATE_HELP = {
|
|
3433
|
+
BEHIND: "the base branch requires it to be up to date; ask the worker to rebase",
|
|
3434
|
+
BLOCKED: "a branch protection rule blocks it (a required review or check)",
|
|
3435
|
+
DIRTY: "it conflicts with its base; ask the worker to rebase",
|
|
3436
|
+
DRAFT: "it is a draft",
|
|
3437
|
+
HAS_HOOKS: "GitHub reports pre-receive hooks; merge it by hand",
|
|
3438
|
+
UNKNOWN: "GitHub is still computing mergeability; try again in a minute",
|
|
3439
|
+
UNSTABLE: "a check that is not required is failing"
|
|
3440
|
+
};
|
|
3441
|
+
function mergeProblems({ pull, ticket, handBack, requiredChecks }) {
|
|
3442
|
+
const n = `#${pull.number}`;
|
|
3443
|
+
const problems = [];
|
|
3444
|
+
if (ticket.agentPhase !== "ready-to-merge")
|
|
3445
|
+
problems.push(`${ticket.id} has not been handed back: its agent phase is ${ticket.agentPhase ?? "not set"}, not ready-to-merge`);
|
|
3446
|
+
if (!handBack)
|
|
3447
|
+
problems.push(`${ticket.id} has no "Agent status: ready-to-merge" comment carrying the head SHA`);
|
|
3448
|
+
else {
|
|
3449
|
+
if (handBack.pr !== null && handBack.pr !== pull.number)
|
|
3450
|
+
problems.push(`the hand-back on ${ticket.id} names PR #${handBack.pr}, not ${n}`);
|
|
3451
|
+
if (!handBack.sha)
|
|
3452
|
+
problems.push(`the hand-back on ${ticket.id} carries no head SHA`);
|
|
3453
|
+
else if (!FULL_SHA.test(handBack.sha))
|
|
3454
|
+
problems.push(`the handed-back SHA ${handBack.sha} is not a full 40-character SHA; ask the worker to report ready-to-merge again`);
|
|
3455
|
+
else if (handBack.sha !== pull.headSha)
|
|
3456
|
+
problems.push(`the head of ${n} is ${pull.headSha}, not the handed-back ${handBack.sha}: it moved after the hand-back; ask the worker to report again`);
|
|
3457
|
+
}
|
|
3458
|
+
if (pull.state !== "open")
|
|
3459
|
+
problems.push(`${n} is ${pull.state}, not open`);
|
|
3460
|
+
if (pull.draft)
|
|
3461
|
+
problems.push(`${n} is a draft`);
|
|
3462
|
+
if (!COMMITIZEN_TITLE.test(pull.title))
|
|
3463
|
+
problems.push(`the title "${pull.title}" is not in Commitizen format, e.g. "feat(cli): add a command"`);
|
|
3464
|
+
if (pull.mergeStateStatus !== "CLEAN")
|
|
3465
|
+
problems.push(`GitHub reports ${n} as ${pull.mergeStateStatus}, not CLEAN${STATE_HELP[pull.mergeStateStatus] ? `: ${STATE_HELP[pull.mergeStateStatus]}` : ""}`);
|
|
3466
|
+
for (const p of checkProblems(pull.checks, requiredChecks))
|
|
3467
|
+
problems.push(`on head ${pull.headSha.slice(0, 7)}: ${p}`);
|
|
3468
|
+
const { total, read, unresolved } = pull.reviewThreads;
|
|
3469
|
+
if (unresolved)
|
|
3470
|
+
problems.push(`${n} has ${unresolved} unresolved review thread${unresolved > 1 ? "s" : ""}`);
|
|
3471
|
+
else if (total > read)
|
|
3472
|
+
problems.push(`${n} has more than ${read} review threads; check they are resolved by hand`);
|
|
3473
|
+
return problems;
|
|
3474
|
+
}
|
|
3475
|
+
function baseProblem(pull, cmp, localCommands) {
|
|
3476
|
+
if (!cmp)
|
|
3477
|
+
return `GitHub could not compare the head of #${pull.number} with ${pull.baseRef}`;
|
|
3478
|
+
if (cmp.behindBy === 0)
|
|
3479
|
+
return null;
|
|
3480
|
+
if (!localCommands.length)
|
|
3481
|
+
return `the head lacks ${cmp.behindBy} commit${cmp.behindBy > 1 ? "s" : ""} of ${pull.baseRef}; ask the worker to rebase, or declare [gates] local_commands in armada.toml so armada merge can test the merge`;
|
|
3482
|
+
return null;
|
|
3483
|
+
}
|
|
3484
|
+
var CODE_FILE = /\.(?:[cm]?[jt]sx?|py|go|rs)$/;
|
|
3485
|
+
var DECLARATIONS = [
|
|
3486
|
+
/^(?:export\s+)?(?:default\s+)?(?:declare\s+)?(?:abstract\s+)?(?:async\s+)?(?:function\*?|class|interface|type|enum|const|let|var)\s+([A-Za-z_$][\w$]*)/,
|
|
3487
|
+
/^(?:async\s+)?(?:def|class)\s+([A-Za-z_]\w*)/,
|
|
3488
|
+
/^(?:func\s+(?:\([^)]*\)\s*)?|type\s+)([A-Za-z_]\w*)/,
|
|
3489
|
+
/^(?:pub(?:\([^)]*\))?\s+)?(?:async\s+)?(?:fn|struct|enum|trait|mod|const|static)\s+([A-Za-z_]\w*)/
|
|
3490
|
+
];
|
|
3491
|
+
function declared(line) {
|
|
3492
|
+
for (const re of DECLARATIONS) {
|
|
3493
|
+
const name = line.match(re)?.[1];
|
|
3494
|
+
if (name)
|
|
3495
|
+
return name;
|
|
3496
|
+
}
|
|
3497
|
+
return null;
|
|
3498
|
+
}
|
|
3499
|
+
function removedSymbols(diff) {
|
|
3500
|
+
const removed = new Map;
|
|
3501
|
+
const added = new Set;
|
|
3502
|
+
const files = new Set;
|
|
3503
|
+
let file = "";
|
|
3504
|
+
for (const line of diff.split(`
|
|
3505
|
+
`)) {
|
|
3506
|
+
const header = line.match(/^diff --git a\/(.+?) b\/(.+)$/);
|
|
3507
|
+
if (header?.[1] && header[2]) {
|
|
3508
|
+
files.add(header[1]).add(header[2]);
|
|
3509
|
+
file = header[1];
|
|
3510
|
+
continue;
|
|
3511
|
+
}
|
|
3512
|
+
if (!CODE_FILE.test(file) || line.startsWith("---") || line.startsWith("+++"))
|
|
3513
|
+
continue;
|
|
3514
|
+
const name = line[0] === "-" || line[0] === "+" ? declared(line.slice(1)) : null;
|
|
3515
|
+
if (!name || name.length < 3)
|
|
3516
|
+
continue;
|
|
3517
|
+
if (line[0] === "-")
|
|
3518
|
+
removed.set(name, file);
|
|
3519
|
+
else
|
|
3520
|
+
added.add(name);
|
|
3521
|
+
}
|
|
3522
|
+
for (const name of added)
|
|
3523
|
+
removed.delete(name);
|
|
3524
|
+
return { removed, files };
|
|
3525
|
+
}
|
|
3526
|
+
function semanticHints(symbols, uses, base) {
|
|
3527
|
+
const hints = [];
|
|
3528
|
+
for (const [name, from] of symbols.removed) {
|
|
3529
|
+
const elsewhere = (uses.get(name) ?? []).filter((f) => !symbols.files.has(f));
|
|
3530
|
+
if (!elsewhere.length)
|
|
3531
|
+
continue;
|
|
3532
|
+
const shown = elsewhere.slice(0, 5).join(", ");
|
|
3533
|
+
const more = elsewhere.length > 5 ? ` and ${elsewhere.length - 5} more` : "";
|
|
3534
|
+
hints.push(`\`${name}\`, removed from ${from}, still appears on ${base} in ${shown}${more}`);
|
|
3535
|
+
}
|
|
3536
|
+
return hints;
|
|
3537
|
+
}
|
|
3538
|
+
var LOCK_CALL_TIMEOUT_MS = 1e4;
|
|
3539
|
+
async function timed(p, ms, what) {
|
|
3540
|
+
let timer;
|
|
3541
|
+
try {
|
|
3542
|
+
return await Promise.race([
|
|
3543
|
+
p,
|
|
3544
|
+
new Promise((_, reject) => {
|
|
3545
|
+
timer = setTimeout(() => reject(new Refusal(`Turso did not answer within ${ms / 1000} s to ${what}; nothing was merged`)), ms);
|
|
3546
|
+
})
|
|
3547
|
+
]);
|
|
3548
|
+
} finally {
|
|
3549
|
+
clearTimeout(timer);
|
|
3550
|
+
}
|
|
3551
|
+
}
|
|
3552
|
+
async function withLease(db, o, body) {
|
|
3553
|
+
const key = { project: o.project, name: o.name, holder: o.holder, ttlMs: o.ttlMs };
|
|
3554
|
+
const poll = o.pollMs ?? LEASE_POLL_MS;
|
|
3555
|
+
const maxWait = o.maxWaitMs ?? o.ttlMs;
|
|
3556
|
+
const lockTimeout = o.timeoutMs ?? LOCK_CALL_TIMEOUT_MS;
|
|
3557
|
+
let waited = 0;
|
|
3558
|
+
let lastHolder;
|
|
3559
|
+
for (;; ) {
|
|
3560
|
+
const got = await timed(acquireLease(db, { ...key, at: o.now() }), lockTimeout, `take the ${o.name} lock`).catch(async (err) => {
|
|
3561
|
+
await timed(releaseLease(db, key), lockTimeout, `release the ${o.name} lock`).catch(() => {});
|
|
3562
|
+
throw err;
|
|
3563
|
+
});
|
|
3564
|
+
if (got.acquired)
|
|
3565
|
+
break;
|
|
3566
|
+
if (waited >= maxWait)
|
|
3567
|
+
throw new Refusal(`the ${o.name} lock of ${o.project} is still held by ${got.held?.holder ?? "another coordinator"} (until ${got.held?.expiresAt ?? "unknown"}); try again later`);
|
|
3568
|
+
if (got.held?.holder !== lastHolder) {
|
|
3569
|
+
lastHolder = got.held?.holder ?? null;
|
|
3570
|
+
o.onWait?.(got.held);
|
|
3571
|
+
}
|
|
3572
|
+
await o.sleep(poll);
|
|
3573
|
+
waited += poll;
|
|
3574
|
+
}
|
|
3575
|
+
try {
|
|
3576
|
+
return await body(() => timed(renewLease(db, { ...key, at: o.now() }), lockTimeout, `renew the ${o.name} lock`).catch(() => false));
|
|
3577
|
+
} finally {
|
|
3578
|
+
await timed(releaseLease(db, key), lockTimeout, `release the ${o.name} lock`).catch(() => {});
|
|
3579
|
+
}
|
|
3580
|
+
}
|
|
3581
|
+
var say = (ctx, line) => ctx.progress?.(line);
|
|
3582
|
+
async function readSettled(ctx, number) {
|
|
3583
|
+
let pull = await ctx.forge.readPull(number);
|
|
3584
|
+
for (const ms of UNKNOWN_BACKOFF_MS) {
|
|
3585
|
+
if (pull?.state !== "open" || pull.mergeStateStatus !== "UNKNOWN")
|
|
3586
|
+
break;
|
|
3587
|
+
await ctx.sleep(ms);
|
|
3588
|
+
pull = await ctx.forge.readPull(number);
|
|
3589
|
+
}
|
|
3590
|
+
if (!pull)
|
|
3591
|
+
throw new Refusal(`pull request #${number} was not found in ${ctx.config.github.repository}`);
|
|
3592
|
+
return pull;
|
|
3593
|
+
}
|
|
3594
|
+
async function readTicketFor(ctx, pull, explicit) {
|
|
3595
|
+
const id = explicit?.trim().toUpperCase() || (pull.headRef ? ticketFromBranch(pull.headRef, ctx.config.tracker.programRoot) : null);
|
|
3596
|
+
if (!id)
|
|
3597
|
+
throw new Refusal(`the branch of #${pull.number} (${pull.headRef ?? "unknown"}) names no ticket; pass --ticket <id>`);
|
|
3598
|
+
const ticket = await ctx.linear.readTicket(id);
|
|
3599
|
+
if (!ticket)
|
|
3600
|
+
throw new Refusal(`ticket ${id} not found in Linear`);
|
|
3601
|
+
return ticket;
|
|
3602
|
+
}
|
|
3603
|
+
async function checklist(ctx, input) {
|
|
3604
|
+
const { config } = ctx;
|
|
3605
|
+
const pull = await readSettled(ctx, input.pr);
|
|
3606
|
+
const ticket = await readTicketFor(ctx, pull, input.ticket);
|
|
3607
|
+
const handBack = findHandBack(ticket);
|
|
3608
|
+
const warnings = [...ticket.warnings];
|
|
3609
|
+
const lines = [];
|
|
3610
|
+
const problems = mergeProblems({ pull, ticket, handBack, requiredChecks: config.gates.requiredChecks });
|
|
3611
|
+
const cmp = await ctx.forge.compare(pull.baseRef, pull.headSha);
|
|
3612
|
+
const behind = baseProblem(pull, cmp, config.gates.localCommands);
|
|
3613
|
+
if (behind)
|
|
3614
|
+
problems.push(behind);
|
|
3615
|
+
else if (cmp && cmp.behindBy > 0) {
|
|
3616
|
+
if (!ctx.repo)
|
|
3617
|
+
problems.push(`the head lacks commits of ${pull.baseRef} and git is not available to test the merge`);
|
|
3618
|
+
else if (!problems.length) {
|
|
3619
|
+
say(ctx, `The head lacks ${cmp.behindBy} commit(s) of ${pull.baseRef}; testing the merge in a throwaway worktree…`);
|
|
3620
|
+
const test = await ctx.repo.testMerge({
|
|
3621
|
+
branch: pull.baseRef,
|
|
3622
|
+
base: cmp.baseSha,
|
|
3623
|
+
head: pull.headSha,
|
|
3624
|
+
number: pull.number,
|
|
3625
|
+
commands: config.gates.localCommands
|
|
3626
|
+
});
|
|
3627
|
+
if (test.ok)
|
|
3628
|
+
lines.push(`Head lacks ${cmp.behindBy} commit(s) of ${pull.baseRef}; the test merge passed every local command.`);
|
|
3629
|
+
else
|
|
3630
|
+
problems.push(`the test merge into ${pull.baseRef} failed at \`${test.step}\`:
|
|
3631
|
+
${indent(test.output)}`);
|
|
3632
|
+
}
|
|
3633
|
+
}
|
|
3634
|
+
const hints = await hintsFor(ctx, pull, cmp, warnings);
|
|
3635
|
+
if (problems.length)
|
|
3636
|
+
throw new Refusal(`#${pull.number} (${ticket.id}) cannot be merged:
|
|
3637
|
+
${problems.map((p) => ` - ${p}`).join(`
|
|
3638
|
+
`)}${hints.length ? `
|
|
3639
|
+
Hints (not blocking):
|
|
3640
|
+
${hints.map((h) => ` - ${h}`).join(`
|
|
3641
|
+
`)}` : ""}`);
|
|
3642
|
+
lines.unshift(`Checklist passed for #${pull.number} (${ticket.id}): handed back at ${pull.headSha}, CLEAN, checks green, no open review thread.`);
|
|
3643
|
+
return { pull, ticket, sha: pull.headSha, baseSha: cmp?.baseSha ?? null, lines, hints, warnings };
|
|
3644
|
+
}
|
|
3645
|
+
var indent = (text) => text.trimEnd().split(`
|
|
3646
|
+
`).map((l) => ` ${l}`).join(`
|
|
3647
|
+
`);
|
|
3648
|
+
async function hintsFor(ctx, pull, cmp, warnings) {
|
|
3649
|
+
try {
|
|
3650
|
+
const symbols = removedSymbols(await ctx.forge.diff(pull.number));
|
|
3651
|
+
if (!symbols.removed.size)
|
|
3652
|
+
return [];
|
|
3653
|
+
if (!ctx.repo || !cmp) {
|
|
3654
|
+
warnings.push(`semantic hint skipped: ${ctx.repo ? `GitHub could not compare the head with ${pull.baseRef}` : "git is not available to search the base branch"}`);
|
|
3655
|
+
return [];
|
|
3656
|
+
}
|
|
3657
|
+
const uses = await ctx.repo.grepWords({
|
|
3658
|
+
branch: pull.baseRef,
|
|
3659
|
+
rev: cmp.baseSha,
|
|
3660
|
+
words: [...symbols.removed.keys()]
|
|
3661
|
+
});
|
|
3662
|
+
return semanticHints(symbols, uses, pull.baseRef);
|
|
3663
|
+
} catch (err) {
|
|
3664
|
+
warnings.push(`semantic hint skipped: ${err instanceof Error ? err.message : String(err)}`);
|
|
3665
|
+
return [];
|
|
3666
|
+
}
|
|
3667
|
+
}
|
|
3668
|
+
async function recheck(ctx, c) {
|
|
3669
|
+
const pull = await readSettled(ctx, c.pull.number);
|
|
3670
|
+
const ticket = await ctx.linear.readTicket(c.ticket.id) ?? c.ticket;
|
|
3671
|
+
const problems = mergeProblems({
|
|
3672
|
+
pull,
|
|
3673
|
+
ticket,
|
|
3674
|
+
handBack: findHandBack(ticket),
|
|
3675
|
+
requiredChecks: ctx.config.gates.requiredChecks
|
|
3676
|
+
});
|
|
3677
|
+
if (pull.headSha === c.sha) {
|
|
3678
|
+
const cmp = await ctx.forge.compare(pull.baseRef, pull.headSha);
|
|
3679
|
+
if (cmp?.baseSha !== c.baseSha)
|
|
3680
|
+
problems.push(`${pull.baseRef} moved to ${cmp?.baseSha ?? "an unknown commit"} while #${pull.number} was checked`);
|
|
3681
|
+
}
|
|
3682
|
+
if (problems.length)
|
|
3683
|
+
throw new Refusal(`#${pull.number} changed while it was checked; nothing was merged, run armada merge again:
|
|
3684
|
+
${problems.map((p) => ` - ${p}`).join(`
|
|
3685
|
+
`)}`);
|
|
3686
|
+
}
|
|
3687
|
+
async function mergePinned(ctx, pull, sha, ticket) {
|
|
3688
|
+
const n = `#${pull.number}`;
|
|
3689
|
+
let readError = "";
|
|
3690
|
+
const read = () => {
|
|
3691
|
+
readError = "";
|
|
3692
|
+
return ctx.forge.readPull(pull.number).catch((err) => {
|
|
3693
|
+
readError = err instanceof Error ? err.message : String(err);
|
|
3694
|
+
return null;
|
|
3695
|
+
});
|
|
3696
|
+
};
|
|
3697
|
+
for (let attempt = 0;; attempt++) {
|
|
3698
|
+
const res = await ctx.forge.merge(pull.number, sha);
|
|
3699
|
+
if (res.ok)
|
|
3700
|
+
break;
|
|
3701
|
+
const fresh = await read();
|
|
3702
|
+
if (fresh?.state === "merged")
|
|
3703
|
+
break;
|
|
3704
|
+
if (!fresh)
|
|
3705
|
+
throw new Refusal(`GitHub failed (${res.message}) and ${n} could not be read back (${readError || "not found"}); check it on GitHub: if it merged, close ${ticket} by hand`);
|
|
3706
|
+
if (!res.transient)
|
|
3707
|
+
throw new Refusal(`GitHub refused to merge ${n}: ${res.message}`);
|
|
3708
|
+
if (fresh.state !== "open")
|
|
3709
|
+
throw new Refusal(`GitHub failed (${res.message}) and ${n} is now ${fresh.state}; not retrying`);
|
|
3710
|
+
if (fresh.headSha !== sha)
|
|
3711
|
+
throw new Refusal(`GitHub failed (${res.message}) and the head of ${n} moved to ${fresh.headSha}; not retrying`);
|
|
3712
|
+
const wait = MERGE_BACKOFF_MS[attempt];
|
|
3713
|
+
if (wait === undefined)
|
|
3714
|
+
throw new Refusal(`GitHub kept failing (${res.message}) after ${attempt + 1} attempts; ${n} is still open and nothing was merged`);
|
|
3715
|
+
say(ctx, `GitHub answered ${res.message}; ${n} is still open at ${sha.slice(0, 7)}, retrying in ${wait / 1000} s…`);
|
|
3716
|
+
await ctx.sleep(wait);
|
|
3717
|
+
}
|
|
3718
|
+
let seen = null;
|
|
3719
|
+
for (let i = 0;; i++) {
|
|
3720
|
+
seen = await read();
|
|
3721
|
+
if (seen?.state === "merged")
|
|
3722
|
+
break;
|
|
3723
|
+
const wait = CONFIRM_BACKOFF_MS[i];
|
|
3724
|
+
if (wait === undefined)
|
|
3725
|
+
throw new Refusal(seen ? `the merge of ${n} was accepted but GitHub shows it as ${seen.state}, not merged (auto-merge or a merge queue?); the ticket was left as is` : `the merge of ${n} was accepted but GitHub could not be read back (${readError || "not found"}); check it on GitHub: if it merged, close ${ticket} by hand`);
|
|
3726
|
+
await ctx.sleep(wait);
|
|
3727
|
+
}
|
|
3728
|
+
if (seen.headSha !== sha)
|
|
3729
|
+
throw new Refusal(`${n} was merged at ${seen.headSha}, not at the handed-back ${sha}; check main now`);
|
|
3730
|
+
return seen;
|
|
3731
|
+
}
|
|
3732
|
+
var runtimeGuide = (runtime) => runtime ? `armada-runtime-${runtime.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "")}` : null;
|
|
3733
|
+
async function closeTicket(ctx, ticket, merged, unlocked) {
|
|
3734
|
+
const groups = ctx.config.tracker.labels;
|
|
3735
|
+
const done = ticket.statusType === "completed" ? null : firstState(ticket.states, "completed");
|
|
3736
|
+
await ctx.linear.updateTicket(ticket.uuid, {
|
|
3737
|
+
...done ? { stateId: done.id } : {},
|
|
3738
|
+
removeLabelIds: [...others(ticket, groups.phaseGroup, null), ...others(ticket, groups.runtimeGroup, null)]
|
|
3739
|
+
});
|
|
3740
|
+
if (!ticket.prs.some((p) => p.url === merged.url))
|
|
3741
|
+
await ctx.linear.linkUrl(ticket.uuid, merged.url, merged.title || `Pull request #${merged.number}`);
|
|
3742
|
+
await ctx.linear.comment(ticket.uuid, `Agent status: merged — PR #${merged.number} squash-merged into ${merged.baseRef} as ${merged.mergeCommit ?? "unknown"}, head ${merged.headSha}${unlocked ? ", merged without lock (--no-lock)" : ""}`);
|
|
3743
|
+
return [
|
|
3744
|
+
`${ticket.id}: ${done ? `moved to ${done.name}` : "state unchanged"}, agent labels removed, merged status posted.`
|
|
3745
|
+
];
|
|
3746
|
+
}
|
|
3747
|
+
async function mergePullRequest(ctx, input) {
|
|
3748
|
+
if (input.dryRun) {
|
|
3749
|
+
const c = await checklist(ctx, input);
|
|
3750
|
+
return outcome(c, false, null, c.lines.concat("Dry run: nothing was merged."), [], null);
|
|
3751
|
+
}
|
|
3752
|
+
const { config } = ctx;
|
|
3753
|
+
const slug = config.project.slug;
|
|
3754
|
+
const early = [];
|
|
3755
|
+
const run = async (renew) => {
|
|
3756
|
+
const c = await checklist(ctx, input);
|
|
3757
|
+
c.warnings.unshift(...early);
|
|
3758
|
+
await recheck(ctx, c);
|
|
3759
|
+
if (!await renew())
|
|
3760
|
+
throw new Refusal("the merge lock could not be renewed (it expired and another coordinator took it, or Turso did not answer); nothing was merged");
|
|
3761
|
+
say(ctx, `Merging #${c.pull.number} at ${c.sha}…`);
|
|
3762
|
+
const merged = await mergePinned(ctx, c.pull, c.sha, c.ticket.id);
|
|
3763
|
+
const lines = [
|
|
3764
|
+
...c.lines,
|
|
3765
|
+
`Merged #${merged.number} into ${merged.baseRef} as ${merged.mergeCommit ?? "unknown"} (head ${merged.headSha}).`
|
|
3766
|
+
];
|
|
3767
|
+
try {
|
|
3768
|
+
lines.push(...await closeTicket(ctx, c.ticket, merged, !!input.noLock));
|
|
3769
|
+
} catch (err) {
|
|
3770
|
+
throw new Error(`#${merged.number} is merged, but Linear could not be updated (${err instanceof Error ? err.message : String(err)}); close ${c.ticket.id} by hand: Done, agent labels removed, pull request linked`);
|
|
3771
|
+
}
|
|
3772
|
+
return after(ctx, c, merged, lines);
|
|
3773
|
+
};
|
|
3774
|
+
if (input.noLock) {
|
|
3775
|
+
early.push(`merged without the merge lock (--no-lock): make sure no other coordinator merges in ${slug} now`);
|
|
3776
|
+
return run(async () => true);
|
|
3777
|
+
}
|
|
3778
|
+
const { db, warning } = await ctx.turso();
|
|
3779
|
+
if (!db && ctx.tursoConfigured)
|
|
3780
|
+
throw new Refusal(`the merge lock needs Turso, which is unavailable (${warning ?? "no answer"}); nothing was merged. Fix Turso, or pass --no-lock if you are sure no other coordinator merges in ${slug} now`);
|
|
3781
|
+
if (!db) {
|
|
3782
|
+
early.push(`${warning ?? "Turso is not configured"}; the merge lock was not taken, so make sure no other coordinator merges in ${slug} now`);
|
|
3783
|
+
return run(async () => true);
|
|
3784
|
+
}
|
|
3785
|
+
return withLease(db, {
|
|
3786
|
+
project: slug,
|
|
3787
|
+
name: MERGE_LEASE,
|
|
3788
|
+
holder: ctx.holder,
|
|
3789
|
+
ttlMs: MERGE_LEASE_TTL_MS,
|
|
3790
|
+
now: ctx.now,
|
|
3791
|
+
sleep: ctx.sleep,
|
|
3792
|
+
onWait: (held) => say(ctx, `Waiting for the merge lock held by ${held?.holder ?? "another coordinator"} (until ${held?.expiresAt ?? "?"})…`)
|
|
3793
|
+
}, run);
|
|
3794
|
+
}
|
|
3795
|
+
async function after(ctx, c, merged, lines) {
|
|
3796
|
+
const { config } = ctx;
|
|
3797
|
+
const slug = config.project.slug;
|
|
3798
|
+
const at = ctx.now();
|
|
3799
|
+
const live$ = await live(ctx, c.warnings, "record the merge", async (db) => {
|
|
3800
|
+
await ensureProject(db, projectOf(config), at);
|
|
3801
|
+
const handle = await getRuntimeHandle(db, slug, c.ticket.id);
|
|
3802
|
+
await recordEvent(db, {
|
|
3803
|
+
project: slug,
|
|
3804
|
+
ticket: c.ticket.id,
|
|
3805
|
+
kind: "merge",
|
|
3806
|
+
phase: "merged",
|
|
3807
|
+
message: `PR #${merged.number} merged as ${merged.mergeCommit ?? "unknown"}`,
|
|
3808
|
+
prUrl: merged.url,
|
|
3809
|
+
headSha: merged.headSha,
|
|
3810
|
+
at
|
|
3811
|
+
});
|
|
3812
|
+
const resolved = await resolveInboxItems(db, {
|
|
3813
|
+
project: slug,
|
|
3814
|
+
ticket: c.ticket.id,
|
|
3815
|
+
kind: "hand-back",
|
|
3816
|
+
resolution: `merged as ${merged.mergeCommit ?? "unknown"}`,
|
|
3817
|
+
at
|
|
3818
|
+
});
|
|
3819
|
+
await releaseRuntimeHandle(db, slug, c.ticket.id, at);
|
|
3820
|
+
return { handle, resolved, open: await openRuntimeHandles(db, slug) };
|
|
3821
|
+
});
|
|
3822
|
+
if (live$?.resolved)
|
|
3823
|
+
lines.push(`Hand-back resolved in the coordinator's inbox.`);
|
|
3824
|
+
let workers = [];
|
|
3825
|
+
try {
|
|
3826
|
+
const handles = new Map((live$?.open ?? []).map((h) => [h.ticket, h]));
|
|
3827
|
+
workers = (await ctx.inFlight()).filter((t) => t.id !== c.ticket.id).map((t) => ({
|
|
3828
|
+
ticket: t.id,
|
|
3829
|
+
title: t.title,
|
|
3830
|
+
phase: t.phase,
|
|
3831
|
+
runtime: t.runtime ?? handles.get(t.id)?.runtime ?? null,
|
|
3832
|
+
handle: handles.get(t.id)?.handle ?? null
|
|
3833
|
+
}));
|
|
3834
|
+
} catch (err) {
|
|
3835
|
+
c.warnings.push(`could not list the workers in flight (${err instanceof Error ? err.message : String(err)}); run armada status`);
|
|
3836
|
+
}
|
|
3837
|
+
const claim = activeClaimComments(c.ticket.comments)[0]?.claim;
|
|
3838
|
+
const runtime = live$?.handle?.runtime ?? c.ticket.agentRuntime ?? claim?.runtime ?? null;
|
|
3839
|
+
const archive = { runtime, handle: live$?.handle?.handle ?? claim?.session ?? null, guide: runtimeGuide(runtime) };
|
|
3840
|
+
return outcome(c, true, merged, lines, workers, archive);
|
|
3841
|
+
}
|
|
3842
|
+
function outcome(c, merged, pr, lines, workers, archive) {
|
|
3843
|
+
const p = pr ?? c.pull;
|
|
3844
|
+
return {
|
|
3845
|
+
merged,
|
|
3846
|
+
pr: {
|
|
3847
|
+
number: p.number,
|
|
3848
|
+
url: p.url,
|
|
3849
|
+
title: p.title,
|
|
3850
|
+
base: p.baseRef,
|
|
3851
|
+
headSha: p.headSha,
|
|
3852
|
+
mergeCommit: pr?.mergeCommit ?? null
|
|
3853
|
+
},
|
|
3854
|
+
ticket: { id: c.ticket.id, url: c.ticket.url },
|
|
3855
|
+
lines,
|
|
3856
|
+
hints: c.hints,
|
|
3857
|
+
workers,
|
|
3858
|
+
archive,
|
|
3859
|
+
warnings: c.warnings
|
|
3860
|
+
};
|
|
3861
|
+
}
|
|
3862
|
+
// ../core/src/skills.ts
|
|
3863
|
+
import { createHash } from "node:crypto";
|
|
3864
|
+
|
|
3865
|
+
// ../../skills/armada-coordinator/MERGE.md
|
|
3866
|
+
var MERGE_default = "# Merging a pull request\n\nRun `armada merge <pr>` (add `--dry-run` to see the checklist only). It checks everything below, takes the project's merge lock, merges pinned to the handed-back SHA, confirms the merge on GitHub and closes the ticket. Its output lists the workers in flight to tell and the worker session to archive. When a refusal names a rule, fix the cause (usually: ask the worker to rebase and report again) rather than merging by hand. When you must merge by hand, follow the same steps.\n\n## Before\n\n1. The worker has handed back: `Agent phase` is `ready-to-merge` and you have the full 40-character head SHA it reported.\n2. `gh pr view <n> --json headRefOid,mergeStateStatus,isDraft,title` shows that SHA, `CLEAN`, not a draft, and a Commitizen title.\n3. `gh pr checks <n>` shows every required check passing.\n4. The head contains the current default branch: `git merge-base --is-ancestor origin/<default> <sha>`. If not, ask the worker to rebase.\n5. Semantic check: search the default branch for callers of anything the pull request deletes or renames.\n\n## Merge\n\n```sh\ngh pr merge <n> --squash --match-head-commit <full-sha>\n```\n\n- One merge at a time: `armada merge` holds the project's merge lock. If it refuses because Turso is down, use `--no-lock` only when you are sure no other coordinator merges in the project.\n- Leave out `--delete-branch`: it deletes local worktrees that have the branch checked out, including other agents'. Delete the branch once its worktree is gone.\n- If GitHub answers with a 5xx, check `gh pr view <n> --json state` before retrying.\n\n## After\n\n1. The ticket is Done, its `Agent phase` and `Agent runtime` labels removed, the pull request linked.\n2. Tell every in-flight worker what the merge changes for them: a shared file, a migration, a new check, code they must now reuse or delete.\n3. Archive the merged worker's workspace with the \"Stop and archive\" section of its runtime guide.\n4. Launch the tickets this merge unblocked.\n";
|
|
3867
|
+
|
|
3868
|
+
// ../../skills/armada-coordinator/SKILL.md
|
|
3869
|
+
var SKILL_default = `---
|
|
3870
|
+
name: armada-coordinator
|
|
3871
|
+
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.
|
|
3872
|
+
---
|
|
3873
|
+
|
|
3874
|
+
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.
|
|
3875
|
+
|
|
3876
|
+
**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.
|
|
3877
|
+
|
|
3878
|
+
**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.
|
|
3879
|
+
|
|
3880
|
+
## Loop
|
|
3881
|
+
|
|
3882
|
+
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.
|
|
3883
|
+
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.
|
|
3884
|
+
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.
|
|
3885
|
+
4. **Launch ready tickets** that do not collide with work in flight, one at a time:
|
|
3886
|
+
- pick the ticket from the frontier in \`armada status\`;
|
|
3887
|
+
- run \`armada brief <ticket>\` and resolve its warnings; the profile (agent, model, effort) comes from \`[conductor]\` in \`armada.toml\`, \`--profile <name>\` picks another one;
|
|
3888
|
+
- write the prompt with \`armada brief <ticket> --prompt > <file>\` and add what only you know: which parallel workers touch neighbouring code and where the boundary is, and decisions not yet on the ticket;
|
|
3889
|
+
- launch it with the runtime guide's *launch* section, passing the profile's values and the environment variables the brief names;
|
|
3890
|
+
- check the claim: \`armada status\` shows the ticket in flight, phase \`planning\`, with the handle the runtime returned. Done when every launched ticket is In Progress with a claim.
|
|
3891
|
+
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.
|
|
3892
|
+
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.
|
|
3893
|
+
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.
|
|
3894
|
+
|
|
3895
|
+
Repeat from step 1; \`armada inbox --wait\` blocks until something needs you.
|
|
3896
|
+
|
|
3897
|
+
## Rules of thumb
|
|
3898
|
+
|
|
3899
|
+
- Merge only after the worker's hand-back; a green pull request can still get one more rebased push.
|
|
3900
|
+
- Parallel workers in one area collide: stagger them, or give each a disjoint area and tell them the boundary.
|
|
3901
|
+
- 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\`.
|
|
3902
|
+
- 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.
|
|
3903
|
+
`;
|
|
3904
|
+
|
|
3905
|
+
// ../../skills/armada-runtime-conductor/SKILL.md
|
|
3906
|
+
var SKILL_default2 = "---\nname: armada-runtime-conductor\ndescription: Runtime guide for running Armada workers on Conductor Cloud. Use when an Armada coordinator must launch a worker on a ticket, send it a message, check whether a silent worker is still alive, or stop and archive it. Four fixed sections, each with the exact conductor command and how to read its output.\n---\n\nArmada never calls a runtime. This guide tells the coordinator how to launch, message, check and stop a worker with the `conductor` command line tool, and what to record in Armada afterwards. It was checked against `conductor` 0.89.2; if a flag is refused, compare with `conductor <command> --help`.\n\n- Always pass `--json` and read fields with `jq`. Exit codes: 0 ok, 1 runtime error, 2 usage error, 3 authentication (`conductor auth status`), 4 server error.\n- A worker is one workspace with one session. Its Armada handle is `<workspaceId>/<sessionId>`; the worker's claim comment carries it, so `armada status` and the ticket always lead back to the session.\n- Never type a secret value into a command, a file or a message: name the variable and let your shell expand it. The expanded value is still in the `conductor` process's arguments while it runs, so launch from a machine only you use.\n\n## Launch\n\n1. Pick a ready ticket from `armada status` that does not collide with work in flight.\n2. Run `armada brief ABC-12`. Read the profile (agent, model, effort, fast mode), the environment table and the warnings. Resolve every warning first: an open blocker, a ticket already in flight. Export each required variable the table marks `NOT set in this shell`. One marked `in credentials file` is in Armada's machine store: keep the `set -a` line of the launch command below, which loads that file without printing it.\n3. Write the prompt to a file, and add what only you know (the boundary with a parallel worker, a decision not yet on the ticket):\n\n```sh\narmada brief ABC-12 --prompt > /tmp/abc-12-brief.md\n```\n\n4. Create the workspace with every value from the profile. Never leave the agent, model or effort to Conductor's defaults. Add `--fast-mode` when the profile says fast mode; drop an optional `--env` line whose variable you do not have. Run the whole block as one command: shell state does not carry over between separate calls, and the subshell keeps the keys out of the rest of your session. Drop the `set -a` line when every variable is set in your shell.\n\n```sh\n(\n set -a; . \"${XDG_CONFIG_HOME:-$HOME/.config}/armada/credentials\"; set +a\n [ -n \"$LINEAR_API_KEY\" ] || { echo \"LINEAR_API_KEY is missing\" >&2; exit 1; }\n conductor --json workspace create \\\n --repo-url https://github.com/<owner>/<name> \\\n --branch main \\\n --name \"ABC-12 <short title>\" \\\n --agent claude --model opus-5-5-1m --effort high \\\n --message-file - \\\n --env ARMADA_TICKET=ABC-12 \\\n --env LINEAR_API_KEY=\"$LINEAR_API_KEY\" \\\n --env ARMADA_TURSO_URL=\"$ARMADA_TURSO_URL\" \\\n --env ARMADA_TURSO_TOKEN=\"$ARMADA_TURSO_TOKEN\" \\\n < /tmp/abc-12-brief.md > /tmp/abc-12-launch.json\n)\njq -r '\"\\(.workspaceId)/\\(.sessionId)\"' /tmp/abc-12-launch.json\n```\n\n- `--branch` is the base branch (the default branch). Conductor creates a branch named `conductor/<slug of --name>`; the brief tells the worker to rename it to the ticket's branch.\n- The output has `workspaceId`, `sessionId`, `deepLink` and `initialMessage` (`messageId`, `state: \"queued\"`). Keep the handle the `jq` line prints, and give the owner the `deepLink` when they want to watch.\n- Conductor sets `CONDUCTOR_WORKSPACE_ID` and `CONDUCTOR_SESSION_ID` inside the workspace. The brief's first commands install your Armada version (`npm install -g`) and claim the ticket with them. `--env` values are not shown back by `workspace get`.\n- An unknown agent, model or effort fails the command. Check the ids with `conductor model` (each agent's models, efforts and defaults) and fix the profile in `armada.toml`.\n\n5. **Check the claim.** Within a few minutes, `armada status` lists the ticket in flight, phase `planning`, runtime `Conductor`, and the ticket's claim comment reads `session: <workspaceId>/<sessionId>`. No claim after ten minutes: read the transcript (Status section). If the worker cannot claim (for example a missing key), fix the cause and message it; as a last resort record the handle yourself with `armada claim ABC-12 --runtime conductor --handle <workspaceId>/<sessionId>`.\n\n## Message\n\n```sh\nprintf '%s\\n' \"Plan approved. Go on.\" | conductor --json message create --session <sessionId> --message-file -\nconductor --json message create --session <sessionId> --message-file - < /tmp/abc-12-answer.md\n```\n\nThe output is `{\"messageId\": …, \"state\": \"sent\"}`. Exit code 0 means Conductor accepted the message, not that the worker read it: check that the session turns `working`, then read its reply in the transcript. Use it to deliver an answer, a plan approval, or a heads-up that the default branch moved. After delivering an answer, record it with `armada answer` when your Armada version has it.\n\n## Status\n\n```sh\nconductor --json session status <sessionId>\n```\n\nThe output is `{\"workspaceId\", \"sessionId\", \"status\", \"updatedAt\"}`. For a worker:\n\n- `working`: a turn is running. A silent worker that is `working` is busy (a long build or test run): leave it, and read the transcript if it stays silent past twice `policy.silence_minutes`.\n- `idle`: no turn is running. The worker finished its turn: it handed back, it waits for an answer, or it stopped without finishing. If `armada status` does not show it `ready-to-merge`, `awaiting-approval` or `blocked`, it has stopped: read its last reply, then message it to go on, or release and relaunch the ticket.\n- `error`: the last turn failed (agent or provider failure). Read the transcript and message it to resume; if it fails again, cancel, archive, release and relaunch.\n- Right after launch the session is `idle` for a few seconds while the workspace is initializing and the first message is queued; it turns `working` when the agent starts.\n\nThe workspace itself: `conductor --json workspace status <workspaceId>` gives `status` `initializing`, `ready` or `archived`.\n\n**Read the transcript** to see what a worker did or said. Events come oldest first, 100 per page; `hasMore` tells when to fetch the next page with `--after` the last event id. Keep the last id you read and poll from it.\n\n```sh\nconductor --json session message <sessionId> --limit 100 > /tmp/abc-12-events.json\njq -r '.hasMore, .data[-1].id' /tmp/abc-12-events.json\njq -r '.data[] | select(.content.rawPayload.type == \"result\") | .content.rawPayload | \"error=\\(.is_error)\\n\\(.result)\"' /tmp/abc-12-events.json\njq -r '.data[] | select(.content.rawPayload.type == \"assistant\") | .content.rawPayload.message.content[] | select(.type == \"tool_use\") | .input.command // .name' /tmp/abc-12-events.json\nconductor --json session message <sessionId> --after <lastEventId> --limit 100\n```\n\nThe second line prints whether more pages exist and the id to continue from; the third, each turn's final reply; the fourth, the commands and tools the worker ran. `.content.rawPayload` is the agent's own event format: these filters read the `claude` agent; for another agent, look at one event and adapt the filter.\n\n## Stop and archive\n\n```sh\nconductor --json session cancel <sessionId>\nconductor --json workspace archive <workspaceId>\n```\n\n- `session cancel` stops the running turn: `{\"status\", \"canceledQueuedMessages\"}`, and the session is `idle` within seconds. The workspace stays; a message starts a new turn. Use it on a worker that runs the wrong thing.\n- `workspace archive` answers `{\"status\": \"archived\"}`. Archive a worker's workspace after its pull request is merged, or after `armada release --ticket ABC-12 --reason \"<why>\"` for a worker that stops without handing back. The branch and the pull request stay on GitHub.\n- After an archive, `session status` still answers `idle`; `workspace status` says `archived`.\n";
|
|
3907
|
+
|
|
3908
|
+
// ../../skills/armada-worker/SKILL.md
|
|
3909
|
+
var SKILL_default3 = `---
|
|
3910
|
+
name: armada-worker
|
|
3911
|
+
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.
|
|
3912
|
+
---
|
|
3913
|
+
|
|
3914
|
+
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.
|
|
3915
|
+
|
|
3916
|
+
## Rules
|
|
3917
|
+
|
|
3918
|
+
- **Never merge**, never enable auto-merge, never approve your own plan. The coordinator merges.
|
|
3919
|
+
- **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.
|
|
3920
|
+
- **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.
|
|
3921
|
+
- **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.
|
|
3922
|
+
- Work only in your own branch and worktree. Never touch another agent's checkout, and stop only the processes you started.
|
|
3923
|
+
- Never print, commit or log a secret.
|
|
3924
|
+
|
|
3925
|
+
## Steps
|
|
3926
|
+
|
|
3927
|
+
1. **Claim** with the exact command your brief starts with, for example \`armada claim <ticket> --runtime conductor --handle "$CONDUCTOR_WORKSPACE_ID/$CONDUCTOR_SESSION_ID"\`. Install the Armada version the brief names first; if it gives a fallback command, use it wherever this skill says \`armada\`. 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.
|
|
3928
|
+
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.
|
|
3929
|
+
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.
|
|
3930
|
+
4. **Implement** test-first. A material change to the approved plan needs a new approval.
|
|
3931
|
+
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.
|
|
3932
|
+
6. **Rebase** on the latest default branch right before hand-back, and get CI green on that final head.
|
|
3933
|
+
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.
|
|
3934
|
+
|
|
3935
|
+
If you stop without finishing, run \`armada release --reason "<why>"\` so the ticket is free again.
|
|
3936
|
+
|
|
3937
|
+
## When a command is missing
|
|
3938
|
+
|
|
3939
|
+
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>\`.
|
|
3940
|
+
`;
|
|
3941
|
+
|
|
3942
|
+
// ../core/src/skills.ts
|
|
3943
|
+
var SKILLS_SOURCE = "The-Vibe-Company/armada";
|
|
3944
|
+
var BUNDLED_SKILLS = [
|
|
3945
|
+
{
|
|
3946
|
+
name: "armada-coordinator",
|
|
3947
|
+
files: [
|
|
3948
|
+
{ path: "MERGE.md", content: MERGE_default },
|
|
3949
|
+
{ path: "SKILL.md", content: SKILL_default }
|
|
3950
|
+
]
|
|
3951
|
+
},
|
|
3952
|
+
{ name: "armada-runtime-conductor", files: [{ path: "SKILL.md", content: SKILL_default2 }] },
|
|
3953
|
+
{ name: "armada-worker", files: [{ path: "SKILL.md", content: SKILL_default3 }] }
|
|
3954
|
+
];
|
|
3955
|
+
function skillFolderHash(files) {
|
|
3956
|
+
const hash = createHash("sha256");
|
|
3957
|
+
for (const f of [...files].sort((a, b) => a.path.localeCompare(b.path))) {
|
|
3958
|
+
hash.update(f.path);
|
|
3959
|
+
hash.update(f.content);
|
|
3960
|
+
}
|
|
3961
|
+
return hash.digest("hex");
|
|
3962
|
+
}
|
|
3963
|
+
|
|
3964
|
+
// ../core/src/setup.ts
|
|
3965
|
+
var AGENTS_SKILLS_DIR = ".agents/skills";
|
|
3966
|
+
var CLAUDE_SKILLS_DIR = ".claude/skills";
|
|
3967
|
+
var SKILLS_LOCK_FILE = "skills-lock.json";
|
|
3968
|
+
var CONDUCTOR_SETTINGS = ".conductor/settings.toml";
|
|
3969
|
+
var GITIGNORE = ".gitignore";
|
|
3970
|
+
var SHIP_ARTIFACTS = "plans/ship-pr-dev/";
|
|
3971
|
+
var ok = (id, message) => ({ id, level: "ok", message, fix: null });
|
|
3972
|
+
var bad = (id, level, message, fix) => ({
|
|
3973
|
+
id,
|
|
3974
|
+
level,
|
|
3975
|
+
message,
|
|
3976
|
+
fix
|
|
3977
|
+
});
|
|
3978
|
+
var skillDir = (name) => `${AGENTS_SKILLS_DIR}/${name}`;
|
|
3979
|
+
var linkPath = (name) => `${CLAUDE_SKILLS_DIR}/${name}`;
|
|
3980
|
+
var skillLinkTarget = (name) => `../../${AGENTS_SKILLS_DIR}/${name}`;
|
|
3981
|
+
var bundledHash = (s) => skillFolderHash(s.files);
|
|
3982
|
+
var WHOLE_DIR_LINKS = new Set(["../.agents/skills", "../.agents/skills/"]);
|
|
3983
|
+
var linksWholeDir = async (view) => WHOLE_DIR_LINKS.has(await view.readLink(CLAUDE_SKILLS_DIR) ?? "");
|
|
3984
|
+
|
|
3985
|
+
class SetupError extends Error {
|
|
3986
|
+
name = "SetupError";
|
|
3987
|
+
}
|
|
3988
|
+
function parseSkillsLock(text) {
|
|
3989
|
+
if (text === null)
|
|
3990
|
+
return null;
|
|
3991
|
+
let raw;
|
|
3992
|
+
try {
|
|
3993
|
+
raw = JSON.parse(text);
|
|
3994
|
+
} catch {
|
|
3995
|
+
throw new SetupError(`${SKILLS_LOCK_FILE} is not valid JSON`);
|
|
3996
|
+
}
|
|
3997
|
+
const lock = raw;
|
|
3998
|
+
if (typeof lock?.version !== "number" || typeof lock.skills !== "object" || lock.skills === null)
|
|
3999
|
+
throw new SetupError(`${SKILLS_LOCK_FILE} has no "version" number and "skills" object`);
|
|
4000
|
+
return lock;
|
|
4001
|
+
}
|
|
4002
|
+
function conductorSetup(text) {
|
|
4003
|
+
let raw;
|
|
4004
|
+
try {
|
|
4005
|
+
raw = parse(text);
|
|
4006
|
+
} catch (err) {
|
|
4007
|
+
const where = err instanceof TomlError ? ` (line ${err.line}, column ${err.column})` : "";
|
|
4008
|
+
throw new SetupError(`${CONDUCTOR_SETTINGS} is not valid TOML${where}`);
|
|
4009
|
+
}
|
|
4010
|
+
const scripts = raw.scripts;
|
|
4011
|
+
const setup = scripts?.setup;
|
|
4012
|
+
return typeof setup === "string" ? setup.trim() : "";
|
|
4013
|
+
}
|
|
4014
|
+
var IGNORES_SHIP = new Set(["plans/ship-pr-dev/", "plans/ship-pr-dev", "plans/", "plans", "plans/*"]);
|
|
4015
|
+
var ignoresShipArtifacts = (gitignore) => (gitignore ?? "").split(/\r?\n/).some((l) => IGNORES_SHIP.has(l.trim().replace(/^\//, "")));
|
|
4016
|
+
async function checkRepository(view, armadaVersion) {
|
|
4017
|
+
const checks = [];
|
|
4018
|
+
const configText = await view.readFile(CONFIG_FILE);
|
|
4019
|
+
if (configText === null)
|
|
4020
|
+
checks.push(bad("config", "error", `${CONFIG_FILE} is missing`, "run `armada init --program-root <ISSUE-ID>` to open a pull request that adds it"));
|
|
4021
|
+
else
|
|
4022
|
+
try {
|
|
4023
|
+
const config = parseConfig(configText, CONFIG_FILE);
|
|
4024
|
+
checks.push(ok("config", `${CONFIG_FILE} is valid (project ${config.project.slug})`));
|
|
4025
|
+
} catch (err) {
|
|
4026
|
+
if (!(err instanceof ConfigError))
|
|
4027
|
+
throw err;
|
|
4028
|
+
checks.push(bad("config", "error", err.message, `fix the keys listed above in ${CONFIG_FILE}`));
|
|
4029
|
+
}
|
|
4030
|
+
let lock = null;
|
|
4031
|
+
let lockError = null;
|
|
4032
|
+
try {
|
|
4033
|
+
lock = parseSkillsLock(await view.readFile(SKILLS_LOCK_FILE));
|
|
4034
|
+
} catch (err) {
|
|
4035
|
+
if (!(err instanceof SetupError))
|
|
4036
|
+
throw err;
|
|
4037
|
+
lockError = err.message;
|
|
4038
|
+
}
|
|
4039
|
+
if (lockError)
|
|
4040
|
+
checks.push(bad("skills-lock", "error", lockError, `repair or delete ${SKILLS_LOCK_FILE}`));
|
|
4041
|
+
const wholeDir = await linksWholeDir(view);
|
|
4042
|
+
for (const skill of BUNDLED_SKILLS) {
|
|
4043
|
+
const folder = await view.readFolder(skillDir(skill.name));
|
|
4044
|
+
const installed = folder?.some((f) => f.path === "SKILL.md") ? skillFolderHash(folder) : null;
|
|
4045
|
+
const id = `skill:${skill.name}`;
|
|
4046
|
+
if (installed === null) {
|
|
4047
|
+
checks.push(bad(id, "error", `skill ${skill.name} is missing from ${AGENTS_SKILLS_DIR}`, "run `armada init`"));
|
|
4048
|
+
continue;
|
|
4049
|
+
}
|
|
4050
|
+
if (installed !== bundledHash(skill))
|
|
4051
|
+
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"));
|
|
4052
|
+
else
|
|
4053
|
+
checks.push(ok(id, `skill ${skill.name} is up to date`));
|
|
4054
|
+
const target = await view.readLink(linkPath(skill.name));
|
|
4055
|
+
const linkId = `skill-link:${skill.name}`;
|
|
4056
|
+
if (wholeDir)
|
|
4057
|
+
checks.push(ok(linkId, `${CLAUDE_SKILLS_DIR} links to ${AGENTS_SKILLS_DIR}`));
|
|
4058
|
+
else if (target === skillLinkTarget(skill.name))
|
|
4059
|
+
checks.push(ok(linkId, `${linkPath(skill.name)} links to ${skillDir(skill.name)}`));
|
|
4060
|
+
else
|
|
4061
|
+
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`"));
|
|
4062
|
+
if (lockError)
|
|
4063
|
+
continue;
|
|
4064
|
+
const entry = lock?.skills[skill.name];
|
|
4065
|
+
const lockId = `skill-lock:${skill.name}`;
|
|
4066
|
+
if (!entry)
|
|
4067
|
+
checks.push(bad(lockId, "error", `${SKILLS_LOCK_FILE} does not record ${skill.name}`, "run `armada init`"));
|
|
4068
|
+
else if (installed !== null && entry.computedHash !== installed)
|
|
4069
|
+
checks.push(bad(lockId, "warning", `${SKILLS_LOCK_FILE} records a different content for ${skill.name} than ${skillDir(skill.name)}`, "run `armada init`"));
|
|
4070
|
+
else
|
|
4071
|
+
checks.push(ok(lockId, `${SKILLS_LOCK_FILE} records ${skill.name}`));
|
|
4072
|
+
}
|
|
4073
|
+
const settings = await view.readFile(CONDUCTOR_SETTINGS);
|
|
4074
|
+
if (settings === null)
|
|
4075
|
+
checks.push(bad("conductor", "error", `${CONDUCTOR_SETTINGS} is missing`, "run `armada init` to add it with a setup script"));
|
|
4076
|
+
else
|
|
4077
|
+
try {
|
|
4078
|
+
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]"));
|
|
4079
|
+
} catch (err) {
|
|
4080
|
+
if (!(err instanceof SetupError))
|
|
4081
|
+
throw err;
|
|
4082
|
+
checks.push(bad("conductor", "error", err.message, `fix ${CONDUCTOR_SETTINGS}`));
|
|
4083
|
+
}
|
|
4084
|
+
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`"));
|
|
4085
|
+
return checks;
|
|
4086
|
+
}
|
|
4087
|
+
async function guessSetupCommand(view) {
|
|
4088
|
+
const has = async (p) => await view.readFile(p) !== null;
|
|
4089
|
+
if (await has("bun.lock") || await has("bun.lockb"))
|
|
4090
|
+
return "bun install --frozen-lockfile";
|
|
4091
|
+
if (await has("pnpm-lock.yaml"))
|
|
4092
|
+
return "pnpm install --frozen-lockfile";
|
|
4093
|
+
if (await has("yarn.lock"))
|
|
4094
|
+
return "yarn install --frozen-lockfile";
|
|
4095
|
+
if (await has("package-lock.json"))
|
|
4096
|
+
return "npm ci";
|
|
4097
|
+
return null;
|
|
4098
|
+
}
|
|
4099
|
+
var SETUP_COMMENT = "# Commands a fresh workspace runs once: install dependencies, copy env files.";
|
|
4100
|
+
function conductorSettings(setup) {
|
|
4101
|
+
return `"$schema" = "https://conductor.build/schemas/settings.repo.schema.json"
|
|
4102
|
+
|
|
4103
|
+
[scripts]
|
|
4104
|
+
${SETUP_COMMENT}
|
|
4105
|
+
setup = ${JSON.stringify(setup ?? "true")}
|
|
4106
|
+
`;
|
|
4107
|
+
}
|
|
4108
|
+
function withSetup(text, setup) {
|
|
4109
|
+
const command = setup ?? "true";
|
|
4110
|
+
const line = `${SETUP_COMMENT}
|
|
4111
|
+
setup = ${JSON.stringify(command)}`;
|
|
4112
|
+
const lines = text.split(`
|
|
4113
|
+
`);
|
|
4114
|
+
const at = lines.findIndex((l) => /^\s*\[scripts\]\s*(#.*)?$/.test(l));
|
|
4115
|
+
let edited;
|
|
4116
|
+
if (at >= 0) {
|
|
4117
|
+
lines.splice(at + 1, 0, line);
|
|
4118
|
+
edited = lines.join(`
|
|
4119
|
+
`);
|
|
4120
|
+
} else
|
|
4121
|
+
edited = `${text.replace(/\n*$/, `
|
|
4122
|
+
`)}
|
|
4123
|
+
[scripts]
|
|
4124
|
+
${line}
|
|
4125
|
+
`;
|
|
4126
|
+
let result = "";
|
|
4127
|
+
try {
|
|
4128
|
+
result = conductorSetup(edited);
|
|
4129
|
+
} catch {}
|
|
4130
|
+
if (result !== command)
|
|
4131
|
+
throw new SetupError(`${CONDUCTOR_SETTINGS} has a [scripts] table Armada cannot add a setup command to safely; set \`setup\` under [scripts] by hand`);
|
|
4132
|
+
return edited;
|
|
4133
|
+
}
|
|
4134
|
+
function lockText(lock, armadaVersion) {
|
|
4135
|
+
const skills = { ...lock?.skills ?? {} };
|
|
4136
|
+
for (const s of BUNDLED_SKILLS)
|
|
4137
|
+
skills[s.name] = {
|
|
4138
|
+
source: SKILLS_SOURCE,
|
|
4139
|
+
sourceType: "github",
|
|
4140
|
+
skillPath: `skills/${s.name}/SKILL.md`,
|
|
4141
|
+
...armadaVersion === "0.0.0" ? {} : { ref: `v${armadaVersion}` },
|
|
4142
|
+
computedHash: bundledHash(s)
|
|
4143
|
+
};
|
|
4144
|
+
const sorted = Object.fromEntries(Object.keys(skills).sort().map((k) => [k, skills[k]]));
|
|
4145
|
+
return `${JSON.stringify({ version: lock?.version ?? 1, skills: sorted }, null, 2)}
|
|
4146
|
+
`;
|
|
4147
|
+
}
|
|
4148
|
+
async function planSetup(view, opts) {
|
|
4149
|
+
const plan = { writes: [], removes: [], links: [], installed: [], updated: [] };
|
|
4150
|
+
if (opts.configText !== null && await view.readFile(CONFIG_FILE) === null)
|
|
4151
|
+
plan.writes.push({ path: CONFIG_FILE, content: opts.configText });
|
|
4152
|
+
const wholeDir = await linksWholeDir(view);
|
|
4153
|
+
for (const skill of BUNDLED_SKILLS) {
|
|
4154
|
+
const folder = await view.readFolder(skillDir(skill.name));
|
|
4155
|
+
const current = folder?.length ? skillFolderHash(folder) === bundledHash(skill) : false;
|
|
4156
|
+
if (!current) {
|
|
4157
|
+
((folder?.length) ? plan.updated : plan.installed).push(skill.name);
|
|
4158
|
+
for (const f of skill.files)
|
|
4159
|
+
plan.writes.push({ path: `${skillDir(skill.name)}/${f.path}`, content: f.content });
|
|
4160
|
+
const keep = new Set(skill.files.map((f) => f.path));
|
|
4161
|
+
for (const f of folder ?? [])
|
|
4162
|
+
if (!keep.has(f.path))
|
|
4163
|
+
plan.removes.push(`${skillDir(skill.name)}/${f.path}`);
|
|
4164
|
+
}
|
|
4165
|
+
if (!wholeDir && await view.readLink(linkPath(skill.name)) !== skillLinkTarget(skill.name))
|
|
4166
|
+
plan.links.push({ path: linkPath(skill.name), target: skillLinkTarget(skill.name) });
|
|
4167
|
+
}
|
|
4168
|
+
const lockBefore = await view.readFile(SKILLS_LOCK_FILE);
|
|
4169
|
+
const lockAfter = lockText(parseSkillsLock(lockBefore), opts.armadaVersion);
|
|
4170
|
+
if (lockAfter !== lockBefore)
|
|
4171
|
+
plan.writes.push({ path: SKILLS_LOCK_FILE, content: lockAfter });
|
|
4172
|
+
const settings = await view.readFile(CONDUCTOR_SETTINGS);
|
|
4173
|
+
if (settings === null)
|
|
4174
|
+
plan.writes.push({ path: CONDUCTOR_SETTINGS, content: conductorSettings(await guessSetupCommand(view)) });
|
|
4175
|
+
else if (!conductorSetup(settings))
|
|
4176
|
+
plan.writes.push({ path: CONDUCTOR_SETTINGS, content: withSetup(settings, await guessSetupCommand(view)) });
|
|
4177
|
+
const gitignore = await view.readFile(GITIGNORE);
|
|
4178
|
+
if (!ignoresShipArtifacts(gitignore)) {
|
|
4179
|
+
const base = gitignore === null || gitignore === "" ? "" : `${gitignore.replace(/\n*$/, `
|
|
4180
|
+
`)}
|
|
4181
|
+
`;
|
|
4182
|
+
plan.writes.push({
|
|
4183
|
+
path: GITIGNORE,
|
|
4184
|
+
content: `${base}# Local agent run artifacts (ship-pr-dev)
|
|
4185
|
+
${SHIP_ARTIFACTS}
|
|
4186
|
+
`
|
|
4187
|
+
});
|
|
4188
|
+
}
|
|
4189
|
+
return plan;
|
|
4190
|
+
}
|
|
4191
|
+
var planIsEmpty = (p) => !p.writes.length && !p.removes.length && !p.links.length;
|
|
4192
|
+
// ../core/src/status.ts
|
|
4193
|
+
var STATUS_SCHEMA_VERSION = 1;
|
|
4194
|
+
function buildStatus({
|
|
4195
|
+
config,
|
|
4196
|
+
program,
|
|
4197
|
+
forge,
|
|
4198
|
+
forgeError = null,
|
|
4199
|
+
lastEvents,
|
|
4200
|
+
extraWarnings = [],
|
|
4201
|
+
now
|
|
4202
|
+
}) {
|
|
4203
|
+
const issues = attachPullRequests(program, forge);
|
|
4204
|
+
const m = buildModel(issues, program.rootId);
|
|
4205
|
+
const lanes = inFlight(m, program.comments, {
|
|
4206
|
+
now: now.getTime(),
|
|
4207
|
+
silentAfterMinutes: config.policy.silentAfterMinutes,
|
|
4208
|
+
...lastEvents ? { lastEvents } : {}
|
|
4209
|
+
});
|
|
4210
|
+
const phaseOf = new Map(lanes.map((l) => [l.issue.id, l.phase]));
|
|
4211
|
+
const prRef = (p) => ({
|
|
4212
|
+
number: p.number,
|
|
4213
|
+
url: p.url,
|
|
4214
|
+
title: p.title,
|
|
4215
|
+
draft: p.draft ?? null,
|
|
4216
|
+
ci: p.ci ?? null,
|
|
4217
|
+
mergeable: p.mergeable ?? null
|
|
4218
|
+
});
|
|
4219
|
+
return {
|
|
4220
|
+
schemaVersion: STATUS_SCHEMA_VERSION,
|
|
4221
|
+
generatedAt: now.toISOString(),
|
|
4222
|
+
project: { name: config.project.name, slug: config.project.slug, repository: config.github.repository },
|
|
4223
|
+
programRoot: { id: m.root.id, title: m.root.title, url: m.root.url },
|
|
4224
|
+
sources: {
|
|
4225
|
+
linear: { fetchedAt: program.fetchedAt },
|
|
4226
|
+
github: { fetchedAt: forge?.fetchedAt ?? null, error: forge ? null : forgeError ?? "not read" }
|
|
4227
|
+
},
|
|
4228
|
+
silentAfterMinutes: config.policy.silentAfterMinutes,
|
|
4229
|
+
inFlight: lanes.map((l) => ({
|
|
4230
|
+
id: l.issue.id,
|
|
4231
|
+
title: l.issue.title,
|
|
4232
|
+
url: l.issue.url,
|
|
4233
|
+
spec: l.spec,
|
|
4234
|
+
phase: l.phase,
|
|
4235
|
+
phaseSource: l.phaseSource,
|
|
4236
|
+
runtime: l.runtime,
|
|
4237
|
+
agent: l.agent,
|
|
4238
|
+
since: l.since,
|
|
4239
|
+
lastUpdate: l.lastUpdate,
|
|
4240
|
+
lastReport: l.lastReport,
|
|
4241
|
+
silent: l.flags.includes("silent"),
|
|
4242
|
+
statusLine: l.statusLine ? { summary: l.statusLine.summary, at: l.statusLine.at, url: l.statusLine.url } : null,
|
|
4243
|
+
pr: l.pr ? prRef(l.pr) : null,
|
|
4244
|
+
openBlockers: l.openBlockers,
|
|
4245
|
+
flags: l.flags
|
|
4246
|
+
})),
|
|
4247
|
+
frontier: frontier(m, config.tracker.readyLabel).map((c) => ({
|
|
4248
|
+
id: c.issue.id,
|
|
4249
|
+
title: c.issue.title,
|
|
4250
|
+
url: c.issue.url,
|
|
4251
|
+
spec: c.spec,
|
|
4252
|
+
readyForAgent: c.readyForAgent,
|
|
4253
|
+
onCriticalPath: c.onCriticalPath,
|
|
4254
|
+
unlocks: c.unlocksAll
|
|
4255
|
+
})),
|
|
4256
|
+
pullRequests: forge ? waitingPullRequests(m, forge.prs).map(({ pr, ticket }) => ({
|
|
4257
|
+
...prRef(pr),
|
|
4258
|
+
headSha: pr.headSha ?? null,
|
|
4259
|
+
updatedAt: pr.updatedAt ?? null,
|
|
4260
|
+
failingChecks: (pr.checks ?? []).filter((c) => c.state === "failure").map((c) => c.name),
|
|
4261
|
+
ticket: ticket ? { id: ticket.id, phase: phaseOf.get(ticket.id) ?? ticket.agentPhase } : null
|
|
4262
|
+
})) : null,
|
|
4263
|
+
warnings: [...program.warnings, ...forge?.warnings ?? [], ...extraWarnings]
|
|
4264
|
+
};
|
|
3342
4265
|
}
|
|
3343
|
-
async function
|
|
3344
|
-
const
|
|
3345
|
-
const
|
|
3346
|
-
|
|
3347
|
-
|
|
3348
|
-
|
|
3349
|
-
|
|
3350
|
-
|
|
3351
|
-
await linear.updateTicket(ticket.uuid, {
|
|
3352
|
-
...back ? { stateId: back.id } : {},
|
|
3353
|
-
removeLabelIds: [...others(ticket, groups.phaseGroup, null), ...others(ticket, groups.runtimeGroup, null)]
|
|
4266
|
+
async function loadStatus(config, opts) {
|
|
4267
|
+
const now = opts.now ?? (() => new Date);
|
|
4268
|
+
const programP = fetchProgram({
|
|
4269
|
+
apiKey: opts.linearApiKey,
|
|
4270
|
+
rootId: config.tracker.programRoot,
|
|
4271
|
+
labels: config.tracker.labels,
|
|
4272
|
+
...opts.fetch ? { fetch: opts.fetch } : {},
|
|
4273
|
+
now
|
|
3354
4274
|
});
|
|
3355
|
-
|
|
3356
|
-
|
|
3357
|
-
|
|
3358
|
-
|
|
3359
|
-
|
|
3360
|
-
|
|
3361
|
-
|
|
3362
|
-
|
|
3363
|
-
|
|
3364
|
-
|
|
3365
|
-
|
|
3366
|
-
|
|
3367
|
-
|
|
4275
|
+
const forgeP = opts.githubToken ? fetchForge({
|
|
4276
|
+
token: opts.githubToken,
|
|
4277
|
+
repository: config.github.repository,
|
|
4278
|
+
...opts.fetch ? { fetch: opts.fetch } : {},
|
|
4279
|
+
now
|
|
4280
|
+
}).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)" });
|
|
4281
|
+
const eventsP = opts.lastEvents ? opts.lastEvents().then((events2) => ({ events: events2 }), (err) => ({
|
|
4282
|
+
warning: `Turso could not be read (${err instanceof Error ? err.message : String(err)}); silence is measured from Linear only`
|
|
4283
|
+
})) : Promise.resolve({});
|
|
4284
|
+
const [program, { forge, error }, events] = await Promise.all([programP, forgeP, eventsP]);
|
|
4285
|
+
return buildStatus({
|
|
4286
|
+
config,
|
|
4287
|
+
program,
|
|
4288
|
+
forge,
|
|
4289
|
+
forgeError: error,
|
|
4290
|
+
...events.events ? { lastEvents: events.events } : {},
|
|
4291
|
+
extraWarnings: events.warning ? [events.warning] : [],
|
|
4292
|
+
now: now()
|
|
3368
4293
|
});
|
|
3369
|
-
return { ticket: ticket.id, url: ticket.url, lines, warnings, inbox: null };
|
|
3370
4294
|
}
|
|
3371
4295
|
// package.json
|
|
3372
|
-
var version = "0.1.
|
|
4296
|
+
var version = "0.1.4";
|
|
3373
4297
|
|
|
3374
4298
|
// src/io.ts
|
|
3375
4299
|
class UsageError extends Error {
|
|
@@ -3540,6 +4464,77 @@ async function authLogout(io) {
|
|
|
3540
4464
|
return 0;
|
|
3541
4465
|
}
|
|
3542
4466
|
|
|
4467
|
+
// src/brief.ts
|
|
4468
|
+
function renderBrief(b) {
|
|
4469
|
+
const p = b.profile;
|
|
4470
|
+
const width = Math.max(...b.environment.map((v) => v.name.length + (v.value ? v.value.length + 1 : 0)));
|
|
4471
|
+
const out = [
|
|
4472
|
+
`Brief for ${b.ticket.id} — ${b.ticket.title} (${b.ticket.status})`,
|
|
4473
|
+
b.ticket.url,
|
|
4474
|
+
"",
|
|
4475
|
+
`Runtime: conductor (follow the armada-runtime-conductor skill to launch)`,
|
|
4476
|
+
`Profile: ${p ? `${p.name}: agent ${p.agent}, model ${p.model}, effort ${p.effort}${p.fastMode ? ", fast mode" : ""}` : "none declared in armada.toml"}`,
|
|
4477
|
+
`Repository: ${b.repository.url}`,
|
|
4478
|
+
`Branch: ${b.ticket.branch ?? "none suggested by Linear"} (the worker renames its workspace branch to it)`,
|
|
4479
|
+
"",
|
|
4480
|
+
"Environment to pass (values are never printed):",
|
|
4481
|
+
...b.environment.map((v) => {
|
|
4482
|
+
const label = v.value ? `${v.name}=${v.value}` : v.name;
|
|
4483
|
+
const state = v.value ? "value above" : v.inShell ? "set in this shell" : v.inStore ? "in credentials file" : "NOT set in this shell";
|
|
4484
|
+
return ` ${label.padEnd(width)} ${v.required ? "required" : "optional"} ${state.padEnd(21)} ${v.purpose}`;
|
|
4485
|
+
})
|
|
4486
|
+
];
|
|
4487
|
+
if (b.warnings.length)
|
|
4488
|
+
out.push("", "Warnings:", ...b.warnings.map((w) => ` - ${w}`));
|
|
4489
|
+
out.push("", `----- prompt (\`armada brief ${b.ticket.id} --prompt\` prints only this) -----`, "", b.prompt);
|
|
4490
|
+
return out.join(`
|
|
4491
|
+
`);
|
|
4492
|
+
}
|
|
4493
|
+
async function brief2(io, config2, credentials2, a, version2) {
|
|
4494
|
+
const [ticket, ...extra] = a.rest;
|
|
4495
|
+
if (!ticket)
|
|
4496
|
+
throw new UsageError("brief needs a ticket: armada brief <ticket> [--profile <name>]");
|
|
4497
|
+
if (extra.length)
|
|
4498
|
+
throw new UsageError(`unexpected argument ${extra[0]}`);
|
|
4499
|
+
const promptOnly = a.options.prompt === "true";
|
|
4500
|
+
if (a.json && promptOnly)
|
|
4501
|
+
throw new UsageError("pass --json or --prompt, not both");
|
|
4502
|
+
const profile = a.options.profile?.trim() || null;
|
|
4503
|
+
const choice = resolveProfile(config2, profile);
|
|
4504
|
+
if (!choice.profile && choice.problem)
|
|
4505
|
+
throw new UsageError(choice.problem);
|
|
4506
|
+
if (!credentials2.linearApiKey)
|
|
4507
|
+
throw new UsageError(missingKeyMessage(LINEAR_KEY));
|
|
4508
|
+
let b;
|
|
4509
|
+
try {
|
|
4510
|
+
b = await loadBrief(config2, {
|
|
4511
|
+
linearApiKey: credentials2.linearApiKey,
|
|
4512
|
+
ticket: ticket.toUpperCase(),
|
|
4513
|
+
profile,
|
|
4514
|
+
version: version2,
|
|
4515
|
+
env: io.env,
|
|
4516
|
+
stored: STORED_KEYS.filter((k) => credentials2.sources[k.name]?.kind === "store").map((k) => k.variable),
|
|
4517
|
+
...io.fetch ? { fetch: io.fetch } : {},
|
|
4518
|
+
...io.now ? { now: io.now } : {}
|
|
4519
|
+
});
|
|
4520
|
+
} catch (err) {
|
|
4521
|
+
if (err instanceof BriefError)
|
|
4522
|
+
throw new UsageError(err.message);
|
|
4523
|
+
throw err;
|
|
4524
|
+
}
|
|
4525
|
+
if (a.json)
|
|
4526
|
+
io.stdout(`${JSON.stringify(b, null, 2)}
|
|
4527
|
+
`);
|
|
4528
|
+
else if (promptOnly) {
|
|
4529
|
+
io.stdout(b.prompt);
|
|
4530
|
+
for (const w of b.warnings)
|
|
4531
|
+
io.stderr(`armada: warning: ${w}
|
|
4532
|
+
`);
|
|
4533
|
+
} else
|
|
4534
|
+
io.stdout(renderBrief(b));
|
|
4535
|
+
return 0;
|
|
4536
|
+
}
|
|
4537
|
+
|
|
3543
4538
|
// src/repo.ts
|
|
3544
4539
|
import { lstat, mkdir as mkdir2, readdir, readFile as readFile2, readlink, rm as rm2, symlink, writeFile } from "node:fs/promises";
|
|
3545
4540
|
import { dirname, join as join2, relative, sep } from "node:path";
|
|
@@ -3882,21 +4877,390 @@ async function init(io, opts) {
|
|
|
3882
4877
|
}
|
|
3883
4878
|
const db = await openTurso({ url: tursoUrl, token: credentials2.tursoToken });
|
|
3884
4879
|
try {
|
|
3885
|
-
const
|
|
3886
|
-
slug: config2.project.slug,
|
|
3887
|
-
name: config2.project.name,
|
|
3888
|
-
repository: config2.github.repository,
|
|
3889
|
-
programRoot: config2.tracker.programRoot
|
|
4880
|
+
const project = {
|
|
4881
|
+
slug: config2.project.slug,
|
|
4882
|
+
name: config2.project.name,
|
|
4883
|
+
repository: config2.github.repository,
|
|
4884
|
+
programRoot: config2.tracker.programRoot
|
|
4885
|
+
};
|
|
4886
|
+
await upsertProject(db, project, io.now?.() ?? new Date);
|
|
4887
|
+
} finally {
|
|
4888
|
+
db.close();
|
|
4889
|
+
}
|
|
4890
|
+
log(`Registered project ${config2.project.slug}; armada status --all lists it.`);
|
|
4891
|
+
return 0;
|
|
4892
|
+
} finally {
|
|
4893
|
+
await exec("git", ["worktree", "remove", "--force", checkout], { cwd: root }).catch(() => null);
|
|
4894
|
+
await rm3(checkout, { recursive: true, force: true });
|
|
4895
|
+
}
|
|
4896
|
+
}
|
|
4897
|
+
|
|
4898
|
+
// src/merge.ts
|
|
4899
|
+
import { randomUUID } from "node:crypto";
|
|
4900
|
+
import { rm as rm4 } from "node:fs/promises";
|
|
4901
|
+
import { hostname, tmpdir as tmpdir2 } from "node:os";
|
|
4902
|
+
import { dirname as dirname2, join as join4 } from "node:path";
|
|
4903
|
+
|
|
4904
|
+
// src/worker.ts
|
|
4905
|
+
var TURSO_OPEN_TIMEOUT_MS = 1e4;
|
|
4906
|
+
async function openLive(credentials2) {
|
|
4907
|
+
if (!credentials2.tursoUrl)
|
|
4908
|
+
return { db: null, warning: "Turso is not configured (ARMADA_TURSO_URL); live activity is not recorded" };
|
|
4909
|
+
let timer;
|
|
4910
|
+
const opening = openTurso({ url: credentials2.tursoUrl, token: credentials2.tursoToken });
|
|
4911
|
+
try {
|
|
4912
|
+
const db = await Promise.race([
|
|
4913
|
+
opening,
|
|
4914
|
+
new Promise((_, reject) => {
|
|
4915
|
+
timer = setTimeout(() => reject(new Error(`no answer within ${TURSO_OPEN_TIMEOUT_MS / 1000} s`)), TURSO_OPEN_TIMEOUT_MS);
|
|
4916
|
+
})
|
|
4917
|
+
]);
|
|
4918
|
+
return { db, warning: null };
|
|
4919
|
+
} catch (err) {
|
|
4920
|
+
opening.then((db) => db.close(), () => {});
|
|
4921
|
+
const reason = err instanceof Error ? err.message : String(err);
|
|
4922
|
+
return { db: null, warning: `Turso unavailable (${reason}); live activity is not recorded, Linear is` };
|
|
4923
|
+
} finally {
|
|
4924
|
+
clearTimeout(timer);
|
|
4925
|
+
}
|
|
4926
|
+
}
|
|
4927
|
+
function statusEvents(config2, credentials2) {
|
|
4928
|
+
if (!credentials2.tursoUrl)
|
|
4929
|
+
return;
|
|
4930
|
+
return async () => {
|
|
4931
|
+
const { db, warning } = await openLive(credentials2);
|
|
4932
|
+
if (!db)
|
|
4933
|
+
throw new Error(warning ?? "Turso unavailable");
|
|
4934
|
+
try {
|
|
4935
|
+
return await lastEventTimes(db, config2.project.slug);
|
|
4936
|
+
} finally {
|
|
4937
|
+
db.close();
|
|
4938
|
+
}
|
|
4939
|
+
};
|
|
4940
|
+
}
|
|
4941
|
+
function currentTicket(io, config2, explicit) {
|
|
4942
|
+
const fromEnv2 = io.env.ARMADA_TICKET?.trim();
|
|
4943
|
+
const id = explicit?.trim() || fromEnv2 || (() => {
|
|
4944
|
+
const branch = io.gitBranch?.();
|
|
4945
|
+
return branch ? ticketFromBranch(branch, config2.tracker.programRoot) : null;
|
|
4946
|
+
})();
|
|
4947
|
+
if (!id)
|
|
4948
|
+
throw new UsageError("which ticket? pass --ticket <id>, set ARMADA_TICKET, or run on the ticket's branch");
|
|
4949
|
+
return id.toUpperCase();
|
|
4950
|
+
}
|
|
4951
|
+
async function context(io, config2, credentials2) {
|
|
4952
|
+
if (!credentials2.linearApiKey)
|
|
4953
|
+
throw new UsageError(missingKeyMessage(LINEAR_KEY));
|
|
4954
|
+
const linearOpts = {
|
|
4955
|
+
apiKey: credentials2.linearApiKey,
|
|
4956
|
+
labels: config2.tracker.labels,
|
|
4957
|
+
...io.fetch ? { fetch: io.fetch } : {}
|
|
4958
|
+
};
|
|
4959
|
+
const linear2 = io.linearWriter ? io.linearWriter(linearOpts) : createLinearWriter(linearOpts);
|
|
4960
|
+
let live2 = null;
|
|
4961
|
+
const token = credentials2.githubToken;
|
|
4962
|
+
const ctx = {
|
|
4963
|
+
config: config2,
|
|
4964
|
+
linear: linear2,
|
|
4965
|
+
turso: () => {
|
|
4966
|
+
live2 ??= openLive(credentials2);
|
|
4967
|
+
return live2;
|
|
4968
|
+
},
|
|
4969
|
+
readPull: token ? (number) => fetchPullRequest({
|
|
4970
|
+
token,
|
|
4971
|
+
repository: config2.github.repository,
|
|
4972
|
+
number,
|
|
4973
|
+
...io.fetch ? { fetch: io.fetch } : {}
|
|
4974
|
+
}) : null,
|
|
4975
|
+
now: io.now ?? (() => new Date)
|
|
4976
|
+
};
|
|
4977
|
+
const close = async () => {
|
|
4978
|
+
const opened = await live2;
|
|
4979
|
+
opened?.db?.close();
|
|
4980
|
+
};
|
|
4981
|
+
return { ctx, close };
|
|
4982
|
+
}
|
|
4983
|
+
function print(io, outcome2, json) {
|
|
4984
|
+
if (json) {
|
|
4985
|
+
io.stdout(`${JSON.stringify(outcome2, null, 2)}
|
|
4986
|
+
`);
|
|
4987
|
+
return;
|
|
4988
|
+
}
|
|
4989
|
+
const out = [...outcome2.lines, outcome2.url];
|
|
4990
|
+
if (outcome2.inbox) {
|
|
4991
|
+
if (!outcome2.inbox.length)
|
|
4992
|
+
out.push("Inbox: nothing waiting for you.");
|
|
4993
|
+
else {
|
|
4994
|
+
out.push(`Inbox (${outcome2.inbox.length}) — read and act on these:`);
|
|
4995
|
+
for (const item of outcome2.inbox)
|
|
4996
|
+
out.push(` #${item.id} ${item.kind}${item.author ? ` from ${item.author}` : ""} · ${item.createdAt}`, ...item.body.split(`
|
|
4997
|
+
`).map((l) => ` ${l}`));
|
|
4998
|
+
}
|
|
4999
|
+
}
|
|
5000
|
+
io.stdout(`${out.join(`
|
|
5001
|
+
`)}
|
|
5002
|
+
`);
|
|
5003
|
+
for (const w of outcome2.warnings)
|
|
5004
|
+
io.stderr(`armada: warning: ${w}
|
|
5005
|
+
`);
|
|
5006
|
+
}
|
|
5007
|
+
async function withContext(io, config2, credentials2, json, act) {
|
|
5008
|
+
const { ctx, close } = await context(io, config2, credentials2);
|
|
5009
|
+
try {
|
|
5010
|
+
print(io, await act(ctx), json);
|
|
5011
|
+
return 0;
|
|
5012
|
+
} finally {
|
|
5013
|
+
await close();
|
|
5014
|
+
}
|
|
5015
|
+
}
|
|
5016
|
+
async function claim(io, config2, credentials2, a) {
|
|
5017
|
+
const [ticket, ...extra] = a.rest;
|
|
5018
|
+
if (!ticket)
|
|
5019
|
+
throw new UsageError("claim needs a ticket: armada claim <ticket> --runtime <name> --handle <id>");
|
|
5020
|
+
if (extra.length)
|
|
5021
|
+
throw new UsageError(`unexpected argument ${extra[0]}`);
|
|
5022
|
+
const runtime = a.options.runtime?.trim();
|
|
5023
|
+
const handle = a.options.handle?.trim();
|
|
5024
|
+
if (!runtime)
|
|
5025
|
+
throw new UsageError("--runtime is required, e.g. --runtime conductor");
|
|
5026
|
+
if (!handle)
|
|
5027
|
+
throw new UsageError("--handle is required: the runtime's id for this session, e.g. <workspace>/<session>");
|
|
5028
|
+
return withContext(io, config2, credentials2, a.json, (ctx) => claimTicket(ctx, {
|
|
5029
|
+
ticket: ticket.toUpperCase(),
|
|
5030
|
+
runtime,
|
|
5031
|
+
handle,
|
|
5032
|
+
...a.options.branch ? { branch: a.options.branch } : {}
|
|
5033
|
+
}));
|
|
5034
|
+
}
|
|
5035
|
+
async function report(io, config2, credentials2, a) {
|
|
5036
|
+
const [phase, ...extra] = a.rest;
|
|
5037
|
+
if (!phase || !isLabelPhase(phase))
|
|
5038
|
+
throw new UsageError(`report needs a phase: ${LABEL_PHASES.join(", ")}${phase ? ` (got "${phase}")` : ""}`);
|
|
5039
|
+
if (extra.length)
|
|
5040
|
+
throw new UsageError(`unexpected argument ${extra[0]}`);
|
|
5041
|
+
if (a.options.message !== undefined && a.options["message-file"] !== undefined)
|
|
5042
|
+
throw new UsageError("pass --message or --message-file, not both");
|
|
5043
|
+
let message = a.options.message ?? null;
|
|
5044
|
+
const file = a.options["message-file"];
|
|
5045
|
+
if (file !== undefined) {
|
|
5046
|
+
message = file === "-" ? await io.readStdin?.() ?? null : await io.readFile(file);
|
|
5047
|
+
if (message === null)
|
|
5048
|
+
throw new UsageError(`cannot read the message from ${file}`);
|
|
5049
|
+
}
|
|
5050
|
+
if (!message?.trim() && phase !== "ready-to-merge")
|
|
5051
|
+
throw new UsageError("--message is required: what you did or what you are doing (first line = summary)");
|
|
5052
|
+
const ticket = currentTicket(io, config2, a.options.ticket);
|
|
5053
|
+
return withContext(io, config2, credentials2, a.json, (ctx) => reportPhase(ctx, {
|
|
5054
|
+
ticket,
|
|
5055
|
+
phase,
|
|
5056
|
+
message,
|
|
5057
|
+
pr: a.options.pr ?? null,
|
|
5058
|
+
sha: a.options.sha ?? null
|
|
5059
|
+
}));
|
|
5060
|
+
}
|
|
5061
|
+
async function release(io, config2, credentials2, a) {
|
|
5062
|
+
if (a.rest.length)
|
|
5063
|
+
throw new UsageError(`unexpected argument ${a.rest[0]}`);
|
|
5064
|
+
const reason = a.options.reason?.trim();
|
|
5065
|
+
if (!reason)
|
|
5066
|
+
throw new UsageError("--reason is required: why the ticket is given back");
|
|
5067
|
+
const ticket = currentTicket(io, config2, a.options.ticket);
|
|
5068
|
+
return withContext(io, config2, credentials2, a.json, (ctx) => releaseTicket(ctx, { ticket, reason }));
|
|
5069
|
+
}
|
|
5070
|
+
|
|
5071
|
+
// src/merge.ts
|
|
5072
|
+
var TRANSIENT = /\bHTTP 5\d\d\b|\b5\d\d (?:Bad Gateway|Service Unavailable|Gateway Time-?out|Internal Server Error)\b|Bad Gateway|Service Unavailable|Gateway Time-?out|ECONNRESET|ETIMEDOUT|connection reset|i\/o timeout|TLS handshake timeout/i;
|
|
5073
|
+
var tail = (text, lines = 30) => text.trimEnd().split(`
|
|
5074
|
+
`).slice(-lines).join(`
|
|
5075
|
+
`);
|
|
5076
|
+
function ghMerge(exec, cwd, repository) {
|
|
5077
|
+
return async (number, sha) => {
|
|
5078
|
+
const args = ["pr", "merge", String(number), "--repo", repository, "--squash", "--match-head-commit", sha];
|
|
5079
|
+
try {
|
|
5080
|
+
const r = await exec("gh", args, { cwd });
|
|
5081
|
+
const message = tail(`${r.stderr}
|
|
5082
|
+
${r.stdout}`.trim(), 5) || `gh exited with ${r.code}`;
|
|
5083
|
+
return { ok: r.code === 0, message, transient: r.code !== 0 && TRANSIENT.test(message) };
|
|
5084
|
+
} catch (err) {
|
|
5085
|
+
return {
|
|
5086
|
+
ok: false,
|
|
5087
|
+
message: `cannot run gh: ${err instanceof Error ? err.message : String(err)}`,
|
|
5088
|
+
transient: false
|
|
3890
5089
|
};
|
|
3891
|
-
await upsertProject(db, project2, io.now?.() ?? new Date);
|
|
3892
|
-
} finally {
|
|
3893
|
-
db.close();
|
|
3894
5090
|
}
|
|
3895
|
-
|
|
5091
|
+
};
|
|
5092
|
+
}
|
|
5093
|
+
var escapeRe = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
5094
|
+
function gitRepo(exec, cwd) {
|
|
5095
|
+
const git = async (args, dir = cwd) => {
|
|
5096
|
+
const r = await exec("git", args, { cwd: dir });
|
|
5097
|
+
return r;
|
|
5098
|
+
};
|
|
5099
|
+
const must = async (args, dir = cwd) => {
|
|
5100
|
+
const r = await git(args, dir);
|
|
5101
|
+
if (r.code !== 0)
|
|
5102
|
+
throw new Error(`git ${args[0]} failed: ${tail(r.stderr || r.stdout, 5)}`);
|
|
5103
|
+
return r;
|
|
5104
|
+
};
|
|
5105
|
+
return {
|
|
5106
|
+
async grepWords({ branch, rev, words }) {
|
|
5107
|
+
await must(["fetch", "--quiet", "origin", branch]);
|
|
5108
|
+
const r = await git(["grep", "-I", "-n", "-w", "-F", ...words.flatMap((w) => ["-e", w]), rev, "--"]);
|
|
5109
|
+
if (r.code > 1)
|
|
5110
|
+
throw new Error(`git grep failed: ${tail(r.stderr, 5)}`);
|
|
5111
|
+
const uses = new Map;
|
|
5112
|
+
const tests = words.map((w) => [w, new RegExp(`(?<![\\w$])${escapeRe(w)}(?![\\w$])`)]);
|
|
5113
|
+
for (const line of r.stdout.split(`
|
|
5114
|
+
`)) {
|
|
5115
|
+
const m = line.match(new RegExp(`^${escapeRe(rev)}:(.+?):\\d+:(.*)$`));
|
|
5116
|
+
if (!m?.[1])
|
|
5117
|
+
continue;
|
|
5118
|
+
const [file, text = ""] = [m[1], m[2]];
|
|
5119
|
+
for (const [w, re] of tests) {
|
|
5120
|
+
if (!re.test(text))
|
|
5121
|
+
continue;
|
|
5122
|
+
const files = uses.get(w) ?? [];
|
|
5123
|
+
if (!files.includes(file))
|
|
5124
|
+
uses.set(w, [...files, file]);
|
|
5125
|
+
}
|
|
5126
|
+
}
|
|
5127
|
+
return uses;
|
|
5128
|
+
},
|
|
5129
|
+
async testMerge({ branch, base, head, number, commands }) {
|
|
5130
|
+
await must(["fetch", "--quiet", "origin", branch, `refs/pull/${number}/head`]);
|
|
5131
|
+
const dir = join4(tmpdir2(), `armada-merge-${number}-${randomUUID().slice(0, 8)}`);
|
|
5132
|
+
const remove = async () => {
|
|
5133
|
+
await git(["worktree", "remove", "--force", dir]);
|
|
5134
|
+
await git(["worktree", "prune"]);
|
|
5135
|
+
await rm4(dir, { recursive: true, force: true });
|
|
5136
|
+
};
|
|
5137
|
+
const added = await git(["worktree", "add", "--detach", dir, base]);
|
|
5138
|
+
if (added.code !== 0) {
|
|
5139
|
+
await remove();
|
|
5140
|
+
return { ok: false, step: "git worktree add", output: tail(added.stderr) };
|
|
5141
|
+
}
|
|
5142
|
+
try {
|
|
5143
|
+
const merged = await git([
|
|
5144
|
+
...["-c", "user.name=Armada", "-c", "user.email=armada@localhost", "-c", "commit.gpgsign=false"],
|
|
5145
|
+
...["merge", "--no-ff", "--no-edit", "--no-verify", head]
|
|
5146
|
+
], dir);
|
|
5147
|
+
if (merged.code !== 0)
|
|
5148
|
+
return {
|
|
5149
|
+
ok: false,
|
|
5150
|
+
step: `git merge ${head.slice(0, 7)}`,
|
|
5151
|
+
output: tail(`${merged.stdout}
|
|
5152
|
+
${merged.stderr}`)
|
|
5153
|
+
};
|
|
5154
|
+
for (const command of commands) {
|
|
5155
|
+
const r = await exec("sh", ["-c", command], { cwd: dir });
|
|
5156
|
+
if (r.code !== 0)
|
|
5157
|
+
return { ok: false, step: command, output: tail(`${r.stdout}
|
|
5158
|
+
${r.stderr}`) };
|
|
5159
|
+
}
|
|
5160
|
+
return { ok: true };
|
|
5161
|
+
} finally {
|
|
5162
|
+
await remove().catch(() => {});
|
|
5163
|
+
}
|
|
5164
|
+
}
|
|
5165
|
+
};
|
|
5166
|
+
}
|
|
5167
|
+
function prNumber(arg, repository) {
|
|
5168
|
+
if (!arg)
|
|
5169
|
+
throw new UsageError("merge needs a pull request: armada merge <number or URL>");
|
|
5170
|
+
const trimmed = arg.trim().replace(/^#/, "");
|
|
5171
|
+
if (/^\d+$/.test(trimmed))
|
|
5172
|
+
return Number(trimmed);
|
|
5173
|
+
const pr = parsePullRequestUrl(trimmed);
|
|
5174
|
+
if (!pr)
|
|
5175
|
+
throw new UsageError(`"${arg}" is not a pull request number or URL`);
|
|
5176
|
+
if (pr.repo.toLowerCase() !== repository.toLowerCase())
|
|
5177
|
+
throw new UsageError(`${pr.url} is not in the project repository ${repository}`);
|
|
5178
|
+
return pr.number;
|
|
5179
|
+
}
|
|
5180
|
+
function render(o) {
|
|
5181
|
+
const out = [...o.lines, o.pr.url, o.ticket.url];
|
|
5182
|
+
if (o.hints.length)
|
|
5183
|
+
out.push("Hints for you to judge (not blocking):", ...o.hints.map((h) => ` - ${h}`));
|
|
5184
|
+
if (!o.merged)
|
|
5185
|
+
return `${out.join(`
|
|
5186
|
+
`)}
|
|
5187
|
+
`;
|
|
5188
|
+
if (!o.workers.length)
|
|
5189
|
+
out.push("No other worker is in flight.");
|
|
5190
|
+
else {
|
|
5191
|
+
out.push(`Tell these workers in flight what landed on ${o.pr.base} (rebase, shared files, new checks):`);
|
|
5192
|
+
for (const w of o.workers)
|
|
5193
|
+
out.push(` ${w.ticket} ${w.phase} ${[w.runtime, w.handle].filter(Boolean).join(" · ") || "runtime unknown"} ${w.title}`);
|
|
5194
|
+
}
|
|
5195
|
+
const a = o.archive;
|
|
5196
|
+
if (a)
|
|
5197
|
+
out.push(`Archive the worker's workspace of ${o.ticket.id} (${[a.runtime, a.handle].filter(Boolean).join(" · ") || "session unknown"}) with the "Stop and archive" section of ${a.guide ? `the ${a.guide} skill` : "its runtime guide"}.`);
|
|
5198
|
+
return `${out.join(`
|
|
5199
|
+
`)}
|
|
5200
|
+
`;
|
|
5201
|
+
}
|
|
5202
|
+
async function merge2(io, config2, credentials2, a, configPath) {
|
|
5203
|
+
const [arg, ...extra] = a.rest;
|
|
5204
|
+
if (extra.length)
|
|
5205
|
+
throw new UsageError(`unexpected argument ${extra[0]}`);
|
|
5206
|
+
const number = prNumber(arg, config2.github.repository);
|
|
5207
|
+
if (!credentials2.linearApiKey)
|
|
5208
|
+
throw new UsageError(missingKeyMessage(LINEAR_KEY));
|
|
5209
|
+
const token = credentials2.githubToken;
|
|
5210
|
+
if (!token)
|
|
5211
|
+
throw new UsageError("armada merge reads GitHub: set GITHUB_TOKEN or run `gh auth login`");
|
|
5212
|
+
const exec = io.exec;
|
|
5213
|
+
if (!exec)
|
|
5214
|
+
throw new UsageError("armada merge needs to run git and gh");
|
|
5215
|
+
const linearApiKey = credentials2.linearApiKey;
|
|
5216
|
+
const repoDir = dirname2(configPath);
|
|
5217
|
+
const fetchOpt = io.fetch ? { fetch: io.fetch } : {};
|
|
5218
|
+
const gh = { token, repository: config2.github.repository, ...fetchOpt };
|
|
5219
|
+
const linearOpts = { apiKey: linearApiKey, labels: config2.tracker.labels, ...fetchOpt };
|
|
5220
|
+
const now = io.now ?? (() => new Date);
|
|
5221
|
+
const turso2 = { live: null };
|
|
5222
|
+
const ctx = {
|
|
5223
|
+
config: config2,
|
|
5224
|
+
linear: io.linearWriter ? io.linearWriter(linearOpts) : createLinearWriter(linearOpts),
|
|
5225
|
+
forge: {
|
|
5226
|
+
readPull: (n) => fetchMergePull({ ...gh, number: n }),
|
|
5227
|
+
compare: (base, head) => fetchComparison({ ...gh, base, head }),
|
|
5228
|
+
diff: (n) => fetchPullDiff({ ...gh, number: n }),
|
|
5229
|
+
merge: ghMerge(exec, repoDir, config2.github.repository)
|
|
5230
|
+
},
|
|
5231
|
+
repo: gitRepo(exec, repoDir),
|
|
5232
|
+
tursoConfigured: !!credentials2.tursoUrl,
|
|
5233
|
+
turso: () => {
|
|
5234
|
+
turso2.live ??= openLive(credentials2);
|
|
5235
|
+
return turso2.live;
|
|
5236
|
+
},
|
|
5237
|
+
inFlight: async () => (await loadStatus(config2, { linearApiKey, githubToken: null, ...fetchOpt, now })).inFlight.map((t) => ({
|
|
5238
|
+
id: t.id,
|
|
5239
|
+
title: t.title,
|
|
5240
|
+
phase: t.phase,
|
|
5241
|
+
runtime: t.runtime
|
|
5242
|
+
})),
|
|
5243
|
+
holder: `${io.env.USER || "coordinator"}@${hostname()} ${randomUUID().slice(0, 8)}`,
|
|
5244
|
+
now,
|
|
5245
|
+
sleep: io.sleep ?? ((ms) => new Promise((done) => setTimeout(done, ms))),
|
|
5246
|
+
progress: (line) => io.stderr(`armada: ${line}
|
|
5247
|
+
`)
|
|
5248
|
+
};
|
|
5249
|
+
try {
|
|
5250
|
+
const o = await mergePullRequest(ctx, {
|
|
5251
|
+
pr: number,
|
|
5252
|
+
ticket: a.options.ticket ?? null,
|
|
5253
|
+
dryRun: !!a.options["dry-run"],
|
|
5254
|
+
noLock: !!a.options["no-lock"]
|
|
5255
|
+
});
|
|
5256
|
+
io.stdout(a.json ? `${JSON.stringify(o, null, 2)}
|
|
5257
|
+
` : render(o));
|
|
5258
|
+
for (const w of o.warnings)
|
|
5259
|
+
io.stderr(`armada: warning: ${w}
|
|
5260
|
+
`);
|
|
3896
5261
|
return 0;
|
|
3897
5262
|
} finally {
|
|
3898
|
-
await
|
|
3899
|
-
await rm3(checkout, { recursive: true, force: true });
|
|
5263
|
+
(await turso2.live)?.db?.close();
|
|
3900
5264
|
}
|
|
3901
5265
|
}
|
|
3902
5266
|
|
|
@@ -3934,7 +5298,7 @@ function renderStatus(r) {
|
|
|
3934
5298
|
const now = Date.parse(r.generatedAt);
|
|
3935
5299
|
const out = [];
|
|
3936
5300
|
const idWidth = Math.max(6, ...r.inFlight.map((t) => t.id.length), ...r.frontier.map((t) => t.id.length), ...(r.pullRequests ?? []).map((p) => `#${p.number}`.length));
|
|
3937
|
-
const
|
|
5301
|
+
const indent2 = " ".repeat(idWidth + 4);
|
|
3938
5302
|
const phaseWidth = Math.max(0, ...r.inFlight.map((t) => phaseLabel(t).length));
|
|
3939
5303
|
out.push(`${r.project.name} · ${r.programRoot.id} ${r.programRoot.title}`);
|
|
3940
5304
|
const gh = r.sources.github.error ? `GitHub not read: ${r.sources.github.error}` : `GitHub ${r.project.repository}`;
|
|
@@ -3945,13 +5309,13 @@ function renderStatus(r) {
|
|
|
3945
5309
|
for (const t of r.inFlight) {
|
|
3946
5310
|
const who = [t.runtime, t.agent].filter(Boolean).join(" · ") || "unassigned";
|
|
3947
5311
|
out.push(` ${pad(t.id, idWidth)} ${pad(phaseLabel(t), phaseWidth)} ${who} · ${t.lastReport ? `reported ${relative2(t.lastReport, now)}` : `updated ${relative2(t.lastUpdate, now)}`}`);
|
|
3948
|
-
out.push(`${
|
|
5312
|
+
out.push(`${indent2}${truncate(t.title, 90)}${t.spec ? ` [${t.spec}]` : ""}`);
|
|
3949
5313
|
if (t.statusLine?.summary)
|
|
3950
|
-
out.push(`${
|
|
5314
|
+
out.push(`${indent2}“${truncate(t.statusLine.summary, 100)}”`);
|
|
3951
5315
|
if (t.pr)
|
|
3952
|
-
out.push(`${
|
|
5316
|
+
out.push(`${indent2}${[`PR #${t.pr.number}`, prState(t.pr)].filter(Boolean).join(" · ")}`);
|
|
3953
5317
|
if (t.flags.length)
|
|
3954
|
-
out.push(`${
|
|
5318
|
+
out.push(`${indent2}! ${t.flags.join(", ")}`);
|
|
3955
5319
|
}
|
|
3956
5320
|
const ready = r.frontier.filter((t) => t.readyForAgent);
|
|
3957
5321
|
const untriaged = r.frontier.filter((t) => !t.readyForAgent);
|
|
@@ -3979,9 +5343,9 @@ function renderStatus(r) {
|
|
|
3979
5343
|
for (const p of r.pullRequests ?? []) {
|
|
3980
5344
|
const ticket = p.ticket ? `${p.ticket.id}${p.ticket.phase ? ` ${p.ticket.phase}` : ""}` : "no ticket";
|
|
3981
5345
|
out.push(` ${pad(`#${p.number}`, idWidth)} ${[ticket, prState(p)].filter(Boolean).join(" · ")}`);
|
|
3982
|
-
out.push(`${
|
|
5346
|
+
out.push(`${indent2}${truncate(p.title, 90)}`);
|
|
3983
5347
|
if (p.failingChecks.length)
|
|
3984
|
-
out.push(`${
|
|
5348
|
+
out.push(`${indent2}! failing: ${p.failingChecks.join(", ")}`);
|
|
3985
5349
|
}
|
|
3986
5350
|
if (r.warnings.length) {
|
|
3987
5351
|
out.push("", `Warnings (${r.warnings.length})`);
|
|
@@ -4038,13 +5402,13 @@ async function statusAll(io, json) {
|
|
|
4038
5402
|
const read = await projectConfig(p, credentials2.githubToken, io);
|
|
4039
5403
|
warning = read.warning;
|
|
4040
5404
|
const config2 = read.config;
|
|
4041
|
-
const
|
|
5405
|
+
const report2 = await loadStatus(config2, {
|
|
4042
5406
|
linearApiKey,
|
|
4043
5407
|
githubToken: credentials2.githubToken,
|
|
4044
5408
|
...io.fetch ? { fetch: io.fetch } : {},
|
|
4045
5409
|
...io.now ? { now: io.now } : {}
|
|
4046
5410
|
});
|
|
4047
|
-
return { ...base, report, error: null, configWarning: warning };
|
|
5411
|
+
return { ...base, report: report2, error: null, configWarning: warning };
|
|
4048
5412
|
} catch (err) {
|
|
4049
5413
|
return { ...base, report: null, error: message(err), configWarning: warning };
|
|
4050
5414
|
}
|
|
@@ -4071,179 +5435,6 @@ ${"─".repeat(60)}
|
|
|
4071
5435
|
return projects.some((p) => p.error) ? 1 : 0;
|
|
4072
5436
|
}
|
|
4073
5437
|
|
|
4074
|
-
// src/worker.ts
|
|
4075
|
-
var TURSO_OPEN_TIMEOUT_MS = 1e4;
|
|
4076
|
-
async function openLive(credentials2) {
|
|
4077
|
-
if (!credentials2.tursoUrl)
|
|
4078
|
-
return { db: null, warning: "Turso is not configured (ARMADA_TURSO_URL); live activity is not recorded" };
|
|
4079
|
-
let timer;
|
|
4080
|
-
const opening = openTurso({ url: credentials2.tursoUrl, token: credentials2.tursoToken });
|
|
4081
|
-
try {
|
|
4082
|
-
const db = await Promise.race([
|
|
4083
|
-
opening,
|
|
4084
|
-
new Promise((_, reject) => {
|
|
4085
|
-
timer = setTimeout(() => reject(new Error(`no answer within ${TURSO_OPEN_TIMEOUT_MS / 1000} s`)), TURSO_OPEN_TIMEOUT_MS);
|
|
4086
|
-
})
|
|
4087
|
-
]);
|
|
4088
|
-
return { db, warning: null };
|
|
4089
|
-
} catch (err) {
|
|
4090
|
-
opening.then((db) => db.close(), () => {});
|
|
4091
|
-
const reason = err instanceof Error ? err.message : String(err);
|
|
4092
|
-
return { db: null, warning: `Turso unavailable (${reason}); live activity is not recorded, Linear is` };
|
|
4093
|
-
} finally {
|
|
4094
|
-
clearTimeout(timer);
|
|
4095
|
-
}
|
|
4096
|
-
}
|
|
4097
|
-
function statusEvents(config2, credentials2) {
|
|
4098
|
-
if (!credentials2.tursoUrl)
|
|
4099
|
-
return;
|
|
4100
|
-
return async () => {
|
|
4101
|
-
const { db, warning } = await openLive(credentials2);
|
|
4102
|
-
if (!db)
|
|
4103
|
-
throw new Error(warning ?? "Turso unavailable");
|
|
4104
|
-
try {
|
|
4105
|
-
return await lastEventTimes(db, config2.project.slug);
|
|
4106
|
-
} finally {
|
|
4107
|
-
db.close();
|
|
4108
|
-
}
|
|
4109
|
-
};
|
|
4110
|
-
}
|
|
4111
|
-
var ID = /(?:^|[^a-z0-9])([a-z][a-z0-9]*-\d+)(?=$|[^a-z0-9])/gi;
|
|
4112
|
-
function ticketFromBranch(branch, programRoot) {
|
|
4113
|
-
const ids = [...branch.matchAll(ID)].map((m) => (m[1] ?? "").toUpperCase());
|
|
4114
|
-
const team = programRoot.split("-")[0]?.toUpperCase();
|
|
4115
|
-
return ids.find((id) => id.split("-")[0] === team) ?? ids[0] ?? null;
|
|
4116
|
-
}
|
|
4117
|
-
function currentTicket(io, config2, explicit) {
|
|
4118
|
-
const fromEnv2 = io.env.ARMADA_TICKET?.trim();
|
|
4119
|
-
const id = explicit?.trim() || fromEnv2 || (() => {
|
|
4120
|
-
const branch = io.gitBranch?.();
|
|
4121
|
-
return branch ? ticketFromBranch(branch, config2.tracker.programRoot) : null;
|
|
4122
|
-
})();
|
|
4123
|
-
if (!id)
|
|
4124
|
-
throw new UsageError("which ticket? pass --ticket <id>, set ARMADA_TICKET, or run on the ticket's branch");
|
|
4125
|
-
return id.toUpperCase();
|
|
4126
|
-
}
|
|
4127
|
-
async function context(io, config2, credentials2) {
|
|
4128
|
-
if (!credentials2.linearApiKey)
|
|
4129
|
-
throw new UsageError(missingKeyMessage(LINEAR_KEY));
|
|
4130
|
-
const linearOpts = {
|
|
4131
|
-
apiKey: credentials2.linearApiKey,
|
|
4132
|
-
labels: config2.tracker.labels,
|
|
4133
|
-
...io.fetch ? { fetch: io.fetch } : {}
|
|
4134
|
-
};
|
|
4135
|
-
const linear2 = io.linearWriter ? io.linearWriter(linearOpts) : createLinearWriter(linearOpts);
|
|
4136
|
-
let live2 = null;
|
|
4137
|
-
const token = credentials2.githubToken;
|
|
4138
|
-
const ctx = {
|
|
4139
|
-
config: config2,
|
|
4140
|
-
linear: linear2,
|
|
4141
|
-
turso: () => {
|
|
4142
|
-
live2 ??= openLive(credentials2);
|
|
4143
|
-
return live2;
|
|
4144
|
-
},
|
|
4145
|
-
readPull: token ? (number) => fetchPullRequest({
|
|
4146
|
-
token,
|
|
4147
|
-
repository: config2.github.repository,
|
|
4148
|
-
number,
|
|
4149
|
-
...io.fetch ? { fetch: io.fetch } : {}
|
|
4150
|
-
}) : null,
|
|
4151
|
-
now: io.now ?? (() => new Date)
|
|
4152
|
-
};
|
|
4153
|
-
const close = async () => {
|
|
4154
|
-
const opened = await live2;
|
|
4155
|
-
opened?.db?.close();
|
|
4156
|
-
};
|
|
4157
|
-
return { ctx, close };
|
|
4158
|
-
}
|
|
4159
|
-
function print(io, outcome, json) {
|
|
4160
|
-
if (json) {
|
|
4161
|
-
io.stdout(`${JSON.stringify(outcome, null, 2)}
|
|
4162
|
-
`);
|
|
4163
|
-
return;
|
|
4164
|
-
}
|
|
4165
|
-
const out = [...outcome.lines, outcome.url];
|
|
4166
|
-
if (outcome.inbox) {
|
|
4167
|
-
if (!outcome.inbox.length)
|
|
4168
|
-
out.push("Inbox: nothing waiting for you.");
|
|
4169
|
-
else {
|
|
4170
|
-
out.push(`Inbox (${outcome.inbox.length}) — read and act on these:`);
|
|
4171
|
-
for (const item of outcome.inbox)
|
|
4172
|
-
out.push(` #${item.id} ${item.kind}${item.author ? ` from ${item.author}` : ""} · ${item.createdAt}`, ...item.body.split(`
|
|
4173
|
-
`).map((l) => ` ${l}`));
|
|
4174
|
-
}
|
|
4175
|
-
}
|
|
4176
|
-
io.stdout(`${out.join(`
|
|
4177
|
-
`)}
|
|
4178
|
-
`);
|
|
4179
|
-
for (const w of outcome.warnings)
|
|
4180
|
-
io.stderr(`armada: warning: ${w}
|
|
4181
|
-
`);
|
|
4182
|
-
}
|
|
4183
|
-
async function withContext(io, config2, credentials2, json, act) {
|
|
4184
|
-
const { ctx, close } = await context(io, config2, credentials2);
|
|
4185
|
-
try {
|
|
4186
|
-
print(io, await act(ctx), json);
|
|
4187
|
-
return 0;
|
|
4188
|
-
} finally {
|
|
4189
|
-
await close();
|
|
4190
|
-
}
|
|
4191
|
-
}
|
|
4192
|
-
async function claim(io, config2, credentials2, a) {
|
|
4193
|
-
const [ticket, ...extra] = a.rest;
|
|
4194
|
-
if (!ticket)
|
|
4195
|
-
throw new UsageError("claim needs a ticket: armada claim <ticket> --runtime <name> --handle <id>");
|
|
4196
|
-
if (extra.length)
|
|
4197
|
-
throw new UsageError(`unexpected argument ${extra[0]}`);
|
|
4198
|
-
const runtime = a.options.runtime?.trim();
|
|
4199
|
-
const handle = a.options.handle?.trim();
|
|
4200
|
-
if (!runtime)
|
|
4201
|
-
throw new UsageError("--runtime is required, e.g. --runtime conductor");
|
|
4202
|
-
if (!handle)
|
|
4203
|
-
throw new UsageError("--handle is required: the runtime's id for this session, e.g. <workspace>/<session>");
|
|
4204
|
-
return withContext(io, config2, credentials2, a.json, (ctx) => claimTicket(ctx, {
|
|
4205
|
-
ticket: ticket.toUpperCase(),
|
|
4206
|
-
runtime,
|
|
4207
|
-
handle,
|
|
4208
|
-
...a.options.branch ? { branch: a.options.branch } : {}
|
|
4209
|
-
}));
|
|
4210
|
-
}
|
|
4211
|
-
async function report(io, config2, credentials2, a) {
|
|
4212
|
-
const [phase, ...extra] = a.rest;
|
|
4213
|
-
if (!phase || !isLabelPhase(phase))
|
|
4214
|
-
throw new UsageError(`report needs a phase: ${LABEL_PHASES.join(", ")}${phase ? ` (got "${phase}")` : ""}`);
|
|
4215
|
-
if (extra.length)
|
|
4216
|
-
throw new UsageError(`unexpected argument ${extra[0]}`);
|
|
4217
|
-
if (a.options.message !== undefined && a.options["message-file"] !== undefined)
|
|
4218
|
-
throw new UsageError("pass --message or --message-file, not both");
|
|
4219
|
-
let message2 = a.options.message ?? null;
|
|
4220
|
-
const file = a.options["message-file"];
|
|
4221
|
-
if (file !== undefined) {
|
|
4222
|
-
message2 = file === "-" ? await io.readStdin?.() ?? null : await io.readFile(file);
|
|
4223
|
-
if (message2 === null)
|
|
4224
|
-
throw new UsageError(`cannot read the message from ${file}`);
|
|
4225
|
-
}
|
|
4226
|
-
if (!message2?.trim() && phase !== "ready-to-merge")
|
|
4227
|
-
throw new UsageError("--message is required: what you did or what you are doing (first line = summary)");
|
|
4228
|
-
const ticket = currentTicket(io, config2, a.options.ticket);
|
|
4229
|
-
return withContext(io, config2, credentials2, a.json, (ctx) => reportPhase(ctx, {
|
|
4230
|
-
ticket,
|
|
4231
|
-
phase,
|
|
4232
|
-
message: message2,
|
|
4233
|
-
pr: a.options.pr ?? null,
|
|
4234
|
-
sha: a.options.sha ?? null
|
|
4235
|
-
}));
|
|
4236
|
-
}
|
|
4237
|
-
async function release(io, config2, credentials2, a) {
|
|
4238
|
-
if (a.rest.length)
|
|
4239
|
-
throw new UsageError(`unexpected argument ${a.rest[0]}`);
|
|
4240
|
-
const reason = a.options.reason?.trim();
|
|
4241
|
-
if (!reason)
|
|
4242
|
-
throw new UsageError("--reason is required: why the ticket is given back");
|
|
4243
|
-
const ticket = currentTicket(io, config2, a.options.ticket);
|
|
4244
|
-
return withContext(io, config2, credentials2, a.json, (ctx) => releaseTicket(ctx, { ticket, reason }));
|
|
4245
|
-
}
|
|
4246
|
-
|
|
4247
5438
|
// src/cli.ts
|
|
4248
5439
|
var USAGE = `Usage: armada <command> [options]
|
|
4249
5440
|
|
|
@@ -4265,6 +5456,17 @@ Commands:
|
|
|
4265
5456
|
Prints what waits in this worker's inbox.
|
|
4266
5457
|
release --reason <text>
|
|
4267
5458
|
Give the ticket back: agent labels removed, ticket moved back
|
|
5459
|
+
merge <pr> [--ticket <id>] [--dry-run] [--no-lock]
|
|
5460
|
+
Coordinator: check a handed-back pull request (hand-back SHA = head,
|
|
5461
|
+
CLEAN, required checks green, no open review thread, base contained
|
|
5462
|
+
or test-merged), squash-merge it pinned to that SHA under the merge
|
|
5463
|
+
lock, close the ticket and list the workers to tell. Never deletes
|
|
5464
|
+
the branch. --dry-run only runs the checklist. Refused when Turso is
|
|
5465
|
+
configured but down; --no-lock then merges without the lock.
|
|
5466
|
+
brief <ticket> [--profile <name>] [--prompt]
|
|
5467
|
+
A new worker's launch prompt, the Conductor profile (agent, model,
|
|
5468
|
+
effort) and the environment variables to pass, named, never shown.
|
|
5469
|
+
--prompt prints only the prompt, for \`--message-file -\`
|
|
4268
5470
|
auth login Ask for the missing keys (hidden input) and store them on this machine
|
|
4269
5471
|
auth status Show which keys are set and where each comes from, never their values
|
|
4270
5472
|
auth logout Remove Armada's keys from this machine
|
|
@@ -4272,16 +5474,19 @@ Commands:
|
|
|
4272
5474
|
Options:
|
|
4273
5475
|
--json Print the result as JSON
|
|
4274
5476
|
--config <path> Use this armada.toml instead of searching from the current directory
|
|
4275
|
-
--ticket <id> Ticket for report and release
|
|
5477
|
+
--ticket <id> Ticket for report and release (default ARMADA_TICKET, then the git
|
|
5478
|
+
branch) and for merge (default: the ticket the PR branch names)
|
|
4276
5479
|
-h, --help Show this help
|
|
4277
5480
|
-v, --version Print the version
|
|
4278
5481
|
|
|
4279
5482
|
Keys (the environment always wins over the file):
|
|
4280
|
-
LINEAR_API_KEY Linear API key (required by status, init, claim, report,
|
|
5483
|
+
LINEAR_API_KEY Linear API key (required by status, init, brief, claim, report,
|
|
5484
|
+
release)
|
|
4281
5485
|
ARMADA_TURSO_URL Turso database URL (required by init and status --all; optional
|
|
4282
5486
|
elsewhere; a file: URL works locally)
|
|
4283
5487
|
ARMADA_TURSO_TOKEN Turso database token
|
|
4284
5488
|
GITHUB_TOKEN GitHub token; falls back to GH_TOKEN, then \`gh auth token\`
|
|
5489
|
+
(merge also runs gh and git, with gh's own login)
|
|
4285
5490
|
|
|
4286
5491
|
Files:
|
|
4287
5492
|
$XDG_CONFIG_HOME/armada (default ~/.config/armada)
|
|
@@ -4300,13 +5505,17 @@ var VALUE_OPTIONS = [
|
|
|
4300
5505
|
"reason",
|
|
4301
5506
|
"program-root",
|
|
4302
5507
|
"name",
|
|
4303
|
-
"slug"
|
|
5508
|
+
"slug",
|
|
5509
|
+
"profile"
|
|
4304
5510
|
];
|
|
5511
|
+
var FLAG_OPTIONS = ["dry-run", "no-lock", "prompt"];
|
|
4305
5512
|
var COMMAND_OPTIONS = {
|
|
4306
5513
|
claim: ["runtime", "handle", "branch"],
|
|
4307
5514
|
report: ["ticket", "message", "message-file", "pr", "sha"],
|
|
4308
5515
|
release: ["ticket", "reason"],
|
|
4309
|
-
init: ["program-root", "name", "slug"]
|
|
5516
|
+
init: ["program-root", "name", "slug"],
|
|
5517
|
+
merge: ["ticket", "dry-run", "no-lock"],
|
|
5518
|
+
brief: ["profile", "prompt"]
|
|
4310
5519
|
};
|
|
4311
5520
|
function parseArgs(argv) {
|
|
4312
5521
|
const args = {
|
|
@@ -4331,6 +5540,8 @@ function parseArgs(argv) {
|
|
|
4331
5540
|
args.help = true;
|
|
4332
5541
|
else if (a === "-v" || a === "--version")
|
|
4333
5542
|
args.version = true;
|
|
5543
|
+
else if (name && FLAG_OPTIONS.includes(name) && named?.[2] === undefined)
|
|
5544
|
+
args.options[name] = "true";
|
|
4334
5545
|
else if (name && (name === "config" || VALUE_OPTIONS.includes(name))) {
|
|
4335
5546
|
const v = named?.[2] ?? argv[++k];
|
|
4336
5547
|
if (v === undefined)
|
|
@@ -4356,12 +5567,12 @@ async function findConfig(io, explicit) {
|
|
|
4356
5567
|
throw new UsageError(`${path} does not exist`);
|
|
4357
5568
|
return { path, text };
|
|
4358
5569
|
}
|
|
4359
|
-
for (let dir = resolve(io.cwd);; dir =
|
|
4360
|
-
const path =
|
|
5570
|
+
for (let dir = resolve(io.cwd);; dir = dirname3(dir)) {
|
|
5571
|
+
const path = join5(dir, CONFIG_FILE);
|
|
4361
5572
|
const text = await io.readFile(path);
|
|
4362
5573
|
if (text !== null)
|
|
4363
5574
|
return { path, text };
|
|
4364
|
-
if (
|
|
5575
|
+
if (dirname3(dir) === dir)
|
|
4365
5576
|
break;
|
|
4366
5577
|
}
|
|
4367
5578
|
throw new UsageError(`no ${CONFIG_FILE} found in ${io.cwd} or any parent directory. Add one at the repository root (see README).`);
|
|
@@ -4414,6 +5625,16 @@ async function run(argv, io) {
|
|
|
4414
5625
|
const { credentials: credentials2 } = await loadCredentials(io);
|
|
4415
5626
|
return await worker2(io, config2, credentials2, args);
|
|
4416
5627
|
}
|
|
5628
|
+
if (args.command === "merge") {
|
|
5629
|
+
const { path, text } = await findConfig(io, args.config);
|
|
5630
|
+
const { credentials: credentials2 } = await loadCredentials(io);
|
|
5631
|
+
return await merge2(io, parseConfig(text, path), credentials2, args, path);
|
|
5632
|
+
}
|
|
5633
|
+
if (args.command === "brief") {
|
|
5634
|
+
const { path, text } = await findConfig(io, args.config);
|
|
5635
|
+
const { credentials: credentials2 } = await loadCredentials(io);
|
|
5636
|
+
return await brief2(io, parseConfig(text, path), credentials2, args, version);
|
|
5637
|
+
}
|
|
4417
5638
|
if (args.command === "status") {
|
|
4418
5639
|
noExtra(args.rest);
|
|
4419
5640
|
return await (args.all ? statusAll(io, args.json) : status2(io, args));
|
|
@@ -4479,11 +5700,11 @@ function feedLine(line, chunk) {
|
|
|
4479
5700
|
}
|
|
4480
5701
|
return { answer, sequence };
|
|
4481
5702
|
}
|
|
4482
|
-
function echo(before,
|
|
5703
|
+
function echo(before, after2) {
|
|
4483
5704
|
let common = 0;
|
|
4484
|
-
while (common < before.length && common <
|
|
5705
|
+
while (common < before.length && common < after2.length && before[common] === after2[common])
|
|
4485
5706
|
common++;
|
|
4486
|
-
return "\b \b".repeat(before.length - common) +
|
|
5707
|
+
return "\b \b".repeat(before.length - common) + after2.slice(common);
|
|
4487
5708
|
}
|
|
4488
5709
|
|
|
4489
5710
|
// src/main.ts
|