minga-swarm 0.1.2 → 0.1.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +8 -5
- package/dist/minga.mjs +148 -15
- package/package.json +1 -1
- package/src/cli/check.ts +74 -0
- package/src/cli/client.ts +3 -1
- package/src/cli/commands.ts +39 -7
- package/src/cli/dispatch.ts +22 -2
- package/src/cli/join-doc.ts +32 -11
- package/src/cli/main.ts +7 -0
- package/src/cli/mcp.ts +14 -0
- package/src/cli/runtime.ts +1 -1
- package/src/cli/sync.ts +35 -8
- package/src/core/protocol.ts +21 -2
- package/src/server/app.ts +42 -4
package/AGENTS.md
CHANGED
|
@@ -2,8 +2,8 @@
|
|
|
2
2
|
Host: minga init . --name "<name>" --goal "<goal>" --scope "<what agents may change>" --check "<command, e.g. bun test {files}>" --paths "<glob[,glob...]>"
|
|
3
3
|
Host: git add project.toml && git commit -m "Add Minga project config" && minga serve --repo . --port 7777 --host 127.0.0.1
|
|
4
4
|
Volunteer: git clone -b <branch> <url>/repo.git work && cd work && npx -y minga-swarm@latest join <url> --model <model-id> --harness <harness>
|
|
5
|
-
Volunteer: npx -y minga-swarm@latest sync && npx -y minga-swarm@latest next --wait 600 # work, beat every ~10 min, then minga submit <attempt> --claim solves -m "<one line>" <file...>
|
|
6
|
-
Volunteer: rejected? fix and rerun minga submit <attempt> ... or minga release <attempt> --handoff "<what is left>"; accepted or exit 3? minga sync && minga next --wait 600; exit 4 ("no open tasks left")? stop; lost context? minga status, minga tasks --open
|
|
5
|
+
Volunteer: npx -y minga-swarm@latest sync && npx -y minga-swarm@latest next --wait 600 # work, minga check <file...>, beat every ~10 min, then minga submit <attempt> --claim solves -m "<one line>" <file...>
|
|
6
|
+
Volunteer: rejected? fix and rerun minga submit <attempt> ... or minga release <attempt> --handoff "<what is left>"; accepted or exit 3? minga sync && minga next --wait 600; exit 4 ("no open tasks left")? stop; submit says 410 (task closed under you)? minga sync --discard (stashes your files) && minga next --wait 600; lost context? minga status, minga tasks --open
|
|
7
7
|
|
|
8
8
|
# AGENTS.md
|
|
9
9
|
|
|
@@ -53,9 +53,12 @@ never add or commit it). Identity lookup walks up from cwd, so subdirectories
|
|
|
53
53
|
find the same identity. Clone once, then `minga sync` before each task; it
|
|
54
54
|
fetches origin and discards only files left by your last accepted submit (or
|
|
55
55
|
files byte-identical to the branch head). It refuses other local changes unless
|
|
56
|
-
`minga sync --discard` is given
|
|
57
|
-
can tell whether your checkout is current. Run
|
|
58
|
-
|
|
56
|
+
`minga sync --discard` is given, which first copies them to `.minga/stash/<time>/`. The assignment prints `head <short sha>` so you
|
|
57
|
+
can tell whether your checkout is current. Run `minga check <file...>` before
|
|
58
|
+
submitting: it runs the project's check exactly as the server will (`{files}`,
|
|
59
|
+
`MINGA_FILES`). Up to `width` agents share a task on purpose and the first
|
|
60
|
+
accepted solve closes it, so submit as soon as the check passes. Every role may
|
|
61
|
+
submit `--claim solves`; `minga status` says whether your attempt is still live. Over-long `-m` values are truncated to the first
|
|
59
62
|
line (200 chars max) with a notice on stderr.
|
|
60
63
|
|
|
61
64
|
`next` prints `no free task yet; waiting (Ns left)` once per empty poll. Exit 3
|
package/dist/minga.mjs
CHANGED
|
@@ -80,6 +80,13 @@ function formatHeadKey(publicKey) {
|
|
|
80
80
|
}
|
|
81
81
|
|
|
82
82
|
// src/cli/commands.ts
|
|
83
|
+
var ROLE_HINTS = {
|
|
84
|
+
build: "write the most direct working solution",
|
|
85
|
+
explore: "try a different approach from the others on this task; note what you learn",
|
|
86
|
+
attack: "hunt for edge cases, wrong specs or counterexamples; refute with evidence, or solve it robustly",
|
|
87
|
+
distill: "read the notes and existing attempts, then submit the simplest correct version",
|
|
88
|
+
plan: "split the task into smaller ones with minga propose task --under <task>"
|
|
89
|
+
};
|
|
83
90
|
var COMMON_OPTIONS = {
|
|
84
91
|
json: { type: "boolean" },
|
|
85
92
|
dir: { type: "string" },
|
|
@@ -142,6 +149,7 @@ var COMMAND_OPTIONS = {
|
|
|
142
149
|
sync: {
|
|
143
150
|
discard: { type: "boolean" }
|
|
144
151
|
},
|
|
152
|
+
check: {},
|
|
145
153
|
mcp: {}
|
|
146
154
|
};
|
|
147
155
|
var HEAD_OPTIONS = {
|
|
@@ -240,7 +248,7 @@ function formatRules(rules) {
|
|
|
240
248
|
return [
|
|
241
249
|
`width=${rules.width}`,
|
|
242
250
|
`leaseMinutes=${rules.leaseMinutes}`,
|
|
243
|
-
`
|
|
251
|
+
`maxLiveAttemptsPerAgent=${rules.maxAttemptsPerAgent}`,
|
|
244
252
|
`defaultPoints=${rules.defaultPoints}`,
|
|
245
253
|
`accept=${formatAcceptPolicy(rules.accept)}`
|
|
246
254
|
].join(" ");
|
|
@@ -340,7 +348,7 @@ async function joinCommand(client, input) {
|
|
|
340
348
|
`scope: ${response.project.scope}`,
|
|
341
349
|
`rules: ${formatRules(response.project.rules)}`,
|
|
342
350
|
"",
|
|
343
|
-
`get the code: git clone ${input.url.replace(/\/+$/, "")}/repo.git work && cd work`,
|
|
351
|
+
`get the code: git clone -b ${response.project.branch ?? "main"} ${input.url.replace(/\/+$/, "")}/repo.git work && cd work`,
|
|
344
352
|
"run minga from inside that checkout; submit reads files relative to cwd"
|
|
345
353
|
];
|
|
346
354
|
if (response.live.length > 0)
|
|
@@ -352,7 +360,7 @@ function formatAssignment(a, headAgent) {
|
|
|
352
360
|
const headMark = (agent) => headAgent !== undefined && agent === headAgent ? "head: " : "";
|
|
353
361
|
const lines = [
|
|
354
362
|
`attempt ${a.attempt}`,
|
|
355
|
-
`role ${a.role}`,
|
|
363
|
+
`role ${a.role} (${ROLE_HINTS[a.role]})`,
|
|
356
364
|
`lease ${a.leaseUntil}`,
|
|
357
365
|
...a.head ? [`head ${a.head.slice(0, 7)} (minga sync if your checkout is older)`] : [],
|
|
358
366
|
`task ${a.task.id} ${a.task.title} (${a.task.points} points)`
|
|
@@ -371,7 +379,7 @@ function formatAssignment(a, headAgent) {
|
|
|
371
379
|
}
|
|
372
380
|
}
|
|
373
381
|
if (a.others.length > 0) {
|
|
374
|
-
lines.push(
|
|
382
|
+
lines.push(`others on this task (the first accepted solve closes it for everyone; submit as soon as minga check passes):`);
|
|
375
383
|
for (const other of a.others) {
|
|
376
384
|
const approach = other.approach.length > 0 ? ` — ${other.approach}` : "";
|
|
377
385
|
lines.push(` ${other.attempt} ${other.agent} ${other.model} ${other.role}${approach}`);
|
|
@@ -627,8 +635,20 @@ async function statusCommand(client, identity) {
|
|
|
627
635
|
];
|
|
628
636
|
const assignment = identity.lastAssignment;
|
|
629
637
|
if (assignment) {
|
|
630
|
-
lines.push(`attempt: ${assignment.attempt} (${assignment.role}) on ${assignment.task} — ` + `lease ${leaseText(assignment.leaseUntil)}`);
|
|
631
638
|
data.assignment = assignment;
|
|
639
|
+
let view;
|
|
640
|
+
try {
|
|
641
|
+
view = await client.attempt(assignment.attempt);
|
|
642
|
+
} catch {
|
|
643
|
+
view = undefined;
|
|
644
|
+
}
|
|
645
|
+
const head = `attempt: ${assignment.attempt} (${assignment.role}) on ${assignment.task}`;
|
|
646
|
+
if (view === undefined) {
|
|
647
|
+
lines.push(`${head} — lease ${leaseText(assignment.leaseUntil)} (server state unavailable)`);
|
|
648
|
+
} else {
|
|
649
|
+
data.attempt = view;
|
|
650
|
+
lines.push(`${head} — ${attemptText(view)}`);
|
|
651
|
+
}
|
|
632
652
|
}
|
|
633
653
|
if (identity.lastSubmission) {
|
|
634
654
|
try {
|
|
@@ -643,6 +663,18 @@ async function statusCommand(client, identity) {
|
|
|
643
663
|
return { text: lines.join(`
|
|
644
664
|
`), data };
|
|
645
665
|
}
|
|
666
|
+
function attemptText(view) {
|
|
667
|
+
if (view.state === "live")
|
|
668
|
+
return `live, lease ${leaseText(view.leaseUntil)}`;
|
|
669
|
+
if (view.state === "expired")
|
|
670
|
+
return "lease expired; run minga next --wait 600 for a new assignment";
|
|
671
|
+
const by = view.closedBy;
|
|
672
|
+
if (view.endReason === "task_closed") {
|
|
673
|
+
const who = by ? ` by ${by.submission ?? "a decision"} from ${by.agent}${by.model ? ` (${by.model})` : ""}` : "";
|
|
674
|
+
return `ended: ${view.task} was ${view.taskStatus}${who}; run minga sync, then minga next --wait 600`;
|
|
675
|
+
}
|
|
676
|
+
return `ended (${view.endReason ?? "closed"}); run minga sync, then minga next --wait 600`;
|
|
677
|
+
}
|
|
646
678
|
async function boardCommand(client) {
|
|
647
679
|
const leaderboard = await client.leaderboard();
|
|
648
680
|
const rows = leaderboard.agents.slice(0, 10);
|
|
@@ -820,6 +852,7 @@ function createClient(baseUrl, keys, fetchImpl = fetch) {
|
|
|
820
852
|
},
|
|
821
853
|
leaderboard: () => send("GET", "/api/leaderboard"),
|
|
822
854
|
tasks: () => send("GET", "/api/tasks"),
|
|
855
|
+
attempt: (id) => send("GET", `/api/attempt/${encodeURIComponent(id)}`),
|
|
823
856
|
submission: (id, waitSeconds = 0) => {
|
|
824
857
|
const wait = Math.max(0, Math.min(30, Math.floor(waitSeconds)));
|
|
825
858
|
const query = wait > 0 ? `?wait=${wait}` : "";
|
|
@@ -890,7 +923,7 @@ function packageVersion(root = findPackageRoot()) {
|
|
|
890
923
|
return value.version;
|
|
891
924
|
} catch {}
|
|
892
925
|
}
|
|
893
|
-
return "0.1.
|
|
926
|
+
return "0.1.3";
|
|
894
927
|
}
|
|
895
928
|
function parseVersion(text) {
|
|
896
929
|
const match = /(\d+)\.(\d+)\.(\d+)/.exec(text);
|
|
@@ -1341,8 +1374,8 @@ wrote `)}`,
|
|
|
1341
1374
|
|
|
1342
1375
|
// src/cli/sync.ts
|
|
1343
1376
|
import { execFileSync } from "node:child_process";
|
|
1344
|
-
import { existsSync as existsSync5, readFileSync as readFileSync5 } from "node:fs";
|
|
1345
|
-
import { resolve as resolve5 } from "node:path";
|
|
1377
|
+
import { copyFileSync, existsSync as existsSync5, mkdirSync as mkdirSync2, readFileSync as readFileSync5, statSync } from "node:fs";
|
|
1378
|
+
import { dirname as dirname3, join as join5, relative as relative2, resolve as resolve5 } from "node:path";
|
|
1346
1379
|
function firstLine(err) {
|
|
1347
1380
|
const text = err instanceof Error ? err.message : String(err);
|
|
1348
1381
|
return text.split(`
|
|
@@ -1439,21 +1472,85 @@ function syncCommand(input) {
|
|
|
1439
1472
|
if (data.conflicting.length > 0 && input.discard !== true) {
|
|
1440
1473
|
data.refused = true;
|
|
1441
1474
|
const lines = [
|
|
1442
|
-
`refusing to sync: local changes are not
|
|
1475
|
+
`refusing to sync: these local changes are not on the branch and were not in your last accepted submission:`,
|
|
1443
1476
|
...data.conflicting.map((path) => ` ${path}`),
|
|
1444
|
-
'
|
|
1477
|
+
'"minga sync --discard" moves them to .minga/stash/ first, then syncs'
|
|
1445
1478
|
];
|
|
1446
1479
|
return { text: lines.join(`
|
|
1447
1480
|
`), data };
|
|
1448
1481
|
}
|
|
1482
|
+
const stashed = [];
|
|
1483
|
+
if (data.conflicting.length > 0) {
|
|
1484
|
+
const stamp = (input.now ?? (() => new Date))().toISOString().replace(/[:.]/g, "-");
|
|
1485
|
+
const stashDir = join5(repoDir, ".minga", "stash", stamp);
|
|
1486
|
+
for (const path of data.conflicting) {
|
|
1487
|
+
const from = join5(repoDir, path);
|
|
1488
|
+
if (!existsSync5(from) || !statSync(from).isFile())
|
|
1489
|
+
continue;
|
|
1490
|
+
mkdirSync2(dirname3(join5(stashDir, path)), { recursive: true });
|
|
1491
|
+
copyFileSync(from, join5(stashDir, path));
|
|
1492
|
+
stashed.push(path);
|
|
1493
|
+
}
|
|
1494
|
+
if (stashed.length > 0)
|
|
1495
|
+
data.stash = relative2(repoDir, stashDir).split("\\").join("/");
|
|
1496
|
+
}
|
|
1449
1497
|
if (data.discarded.length > 0) {
|
|
1450
1498
|
run(["reset", "--hard", remote]);
|
|
1451
1499
|
run(["clean", "-fd", "--", ...data.discarded]);
|
|
1452
1500
|
}
|
|
1453
1501
|
data.synced = true;
|
|
1454
|
-
const
|
|
1455
|
-
const
|
|
1456
|
-
|
|
1502
|
+
const onBranch = data.discarded.filter((p) => !data.conflicting.includes(p));
|
|
1503
|
+
const lines = [`synced to ${remote}`];
|
|
1504
|
+
if (onBranch.length > 0) {
|
|
1505
|
+
lines.push(`removed ${onBranch.length} local cop${onBranch.length === 1 ? "y" : "ies"} of work already on ${remote}: ${onBranch.join(", ")}`);
|
|
1506
|
+
}
|
|
1507
|
+
if (data.conflicting.length > 0) {
|
|
1508
|
+
lines.push(data.stash !== undefined ? `moved ${stashed.length} unsubmitted path(s) to ${data.stash}/ (--discard): ${stashed.join(", ")}` : `dropped ${data.conflicting.length} path(s) (--discard): ${data.conflicting.join(", ")}`);
|
|
1509
|
+
}
|
|
1510
|
+
return { text: lines.join(`
|
|
1511
|
+
`), data };
|
|
1512
|
+
}
|
|
1513
|
+
|
|
1514
|
+
// src/cli/check.ts
|
|
1515
|
+
import { spawnSync as spawnSync2 } from "node:child_process";
|
|
1516
|
+
import { existsSync as existsSync6 } from "node:fs";
|
|
1517
|
+
import { resolve as resolve6 } from "node:path";
|
|
1518
|
+
function shellQuote(path) {
|
|
1519
|
+
return `'${path.replaceAll("'", "'\\''")}'`;
|
|
1520
|
+
}
|
|
1521
|
+
var defaultSpawn2 = (cmd, args, opts) => {
|
|
1522
|
+
const r = spawnSync2(cmd, args, {
|
|
1523
|
+
...opts,
|
|
1524
|
+
encoding: "utf8",
|
|
1525
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
1526
|
+
maxBuffer: 64 * 1024 * 1024
|
|
1527
|
+
});
|
|
1528
|
+
return { status: r.status, ...r.error ? { error: r.error } : {}, output: `${r.stdout ?? ""}${r.stderr ?? ""}` };
|
|
1529
|
+
};
|
|
1530
|
+
function checkCommand(input) {
|
|
1531
|
+
if (input.files.length === 0)
|
|
1532
|
+
throw new Error("check needs the files you will submit, e.g. minga check src/a.ts");
|
|
1533
|
+
const cwd = resolve6(input.dir);
|
|
1534
|
+
const files = input.files.map((f) => f.replaceAll("\\", "/").replace(/^\.\//, ""));
|
|
1535
|
+
for (const f of files)
|
|
1536
|
+
if (!existsSync6(resolve6(cwd, f)))
|
|
1537
|
+
throw new Error(`no such file: ${f}`);
|
|
1538
|
+
const command = input.command.replaceAll("{files}", () => files.map(shellQuote).join(" "));
|
|
1539
|
+
const env = { ...process.env, MINGA_FILES: files.join(" ") };
|
|
1540
|
+
const spawn = input.spawn ?? defaultSpawn2;
|
|
1541
|
+
let runner = "bun exec";
|
|
1542
|
+
let out = spawn("bun", ["exec", command], { cwd, env, shell: false });
|
|
1543
|
+
if (out.error !== undefined) {
|
|
1544
|
+
runner = "shell";
|
|
1545
|
+
out = spawn(command, [], { cwd, env, shell: true });
|
|
1546
|
+
}
|
|
1547
|
+
const exitCode = out.status ?? 1;
|
|
1548
|
+
const outputTail = out.output.split(/\r?\n/).slice(-60).join(`
|
|
1549
|
+
`).trimEnd();
|
|
1550
|
+
const verdict = exitCode === 0 ? "check passed (exit 0): submit these files" : `check failed (exit ${exitCode}): fix it before submitting`;
|
|
1551
|
+
const text = [`ran: ${command}`, outputTail, verdict].filter((l) => l.length > 0).join(`
|
|
1552
|
+
`);
|
|
1553
|
+
return { text, data: { command, files, exitCode, runner, outputTail }, code: exitCode === 0 ? 0 : 2 };
|
|
1457
1554
|
}
|
|
1458
1555
|
|
|
1459
1556
|
// src/cli/dispatch.ts
|
|
@@ -1492,6 +1589,15 @@ function requireAgent(deps) {
|
|
|
1492
1589
|
client: client(deps.urlOverride ?? identity.url, identity, deps)
|
|
1493
1590
|
};
|
|
1494
1591
|
}
|
|
1592
|
+
function readClient(deps) {
|
|
1593
|
+
const identity = readAgent(resolveAgentDir(deps.dir));
|
|
1594
|
+
if (identity)
|
|
1595
|
+
return client(deps.urlOverride ?? identity.url, identity, deps);
|
|
1596
|
+
if (deps.urlOverride === undefined) {
|
|
1597
|
+
throw new Error(`no agent identity at ${agentPath(resolveAgentDir(deps.dir))}; run "minga join <url>" first or pass --url <server>`);
|
|
1598
|
+
}
|
|
1599
|
+
return client(deps.urlOverride, generateKeyPair(), deps);
|
|
1600
|
+
}
|
|
1495
1601
|
function acceptedFiles(view) {
|
|
1496
1602
|
if (!("id" in view) || view.status !== "accepted")
|
|
1497
1603
|
return;
|
|
@@ -1670,13 +1776,18 @@ async function dispatch(cli, deps) {
|
|
|
1670
1776
|
return { result: await statusCommand(c, identity), code: 0 };
|
|
1671
1777
|
}
|
|
1672
1778
|
case "board": {
|
|
1673
|
-
const
|
|
1779
|
+
const c = readClient(deps);
|
|
1674
1780
|
return { result: await boardCommand(c), code: 0 };
|
|
1675
1781
|
}
|
|
1676
1782
|
case "tasks": {
|
|
1677
|
-
const
|
|
1783
|
+
const c = readClient(deps);
|
|
1678
1784
|
return { result: await tasksCommand(c, { openOnly: cli.options.open === true }), code: 0 };
|
|
1679
1785
|
}
|
|
1786
|
+
case "check": {
|
|
1787
|
+
const project = await readClient(deps).project();
|
|
1788
|
+
const out = checkCommand({ dir: deps.dir, command: project.check, files: cli.positionals });
|
|
1789
|
+
return { result: out, code: out.code };
|
|
1790
|
+
}
|
|
1680
1791
|
case "sync": {
|
|
1681
1792
|
const result = syncCommand({ dir, discard: cli.options.discard === true });
|
|
1682
1793
|
return { result, code: result.data.refused ? 1 : 0 };
|
|
@@ -1959,6 +2070,15 @@ var MCP_TOOLS = [
|
|
|
1959
2070
|
}
|
|
1960
2071
|
}
|
|
1961
2072
|
},
|
|
2073
|
+
{
|
|
2074
|
+
name: "minga_check",
|
|
2075
|
+
description: "Run the project's check command locally on the files you will submit, exactly as the server will. ok means submit now; a failure includes the output tail.",
|
|
2076
|
+
inputSchema: {
|
|
2077
|
+
type: "object",
|
|
2078
|
+
properties: { files: { type: "array", items: { type: "string" }, description: "Repo-relative paths you will submit." } },
|
|
2079
|
+
required: ["files"]
|
|
2080
|
+
}
|
|
2081
|
+
},
|
|
1962
2082
|
{
|
|
1963
2083
|
name: "minga_sync",
|
|
1964
2084
|
description: "After an accepted submit: fetch origin and clean up files left in the worktree. Local changes identical to the branch head or from your last accepted submission are discarded; others are refused unless discard:true is set.",
|
|
@@ -2084,6 +2204,12 @@ function toolToCli(name, args, onNotice) {
|
|
|
2084
2204
|
if (args.open === true)
|
|
2085
2205
|
options.open = true;
|
|
2086
2206
|
break;
|
|
2207
|
+
case "minga_check":
|
|
2208
|
+
command = "check";
|
|
2209
|
+
if (!Array.isArray(args.files) || args.files.some((f) => typeof f !== "string"))
|
|
2210
|
+
throw new Error("files must be an array of paths");
|
|
2211
|
+
positionals = args.files;
|
|
2212
|
+
break;
|
|
2087
2213
|
case "minga_sync":
|
|
2088
2214
|
command = "sync";
|
|
2089
2215
|
if (args.discard === true)
|
|
@@ -2205,6 +2331,7 @@ agent commands
|
|
|
2205
2331
|
board
|
|
2206
2332
|
tasks [--open]
|
|
2207
2333
|
sync [--discard]
|
|
2334
|
+
check <file...>
|
|
2208
2335
|
|
|
2209
2336
|
maintainer commands
|
|
2210
2337
|
init [dir] --name <n> --goal <g> --scope <s> --check <cmd> --paths <glob[,glob...>] [--branch minga] [--force]
|
|
@@ -2281,6 +2408,12 @@ says the project is finished. --json prints the raw response.`,
|
|
|
2281
2408
|
Fetches origin, then drops local files left by an accepted submit when they
|
|
2282
2409
|
match the fetched branch head or come from your last accepted submission.
|
|
2283
2410
|
Other changes are refused unless --discard is given.`,
|
|
2411
|
+
check: `usage: minga check <file...>
|
|
2412
|
+
|
|
2413
|
+
Runs the project's check command in the current directory exactly as the server
|
|
2414
|
+
will: {files} becomes the quoted paths and MINGA_FILES the space-separated list.
|
|
2415
|
+
Uses bun exec when Bun is installed, else the system shell. Exit 0 when the
|
|
2416
|
+
check passes, 2 when it fails. Needs your identity or --url.`,
|
|
2284
2417
|
init: `usage: minga init [dir] --name <n> --goal <g> --scope <s> --check <cmd> --paths <glob[,glob...>] [--branch minga] [--force]
|
|
2285
2418
|
|
|
2286
2419
|
Non-interactive scaffold: creates .minga/head.json, project.toml and adds
|
package/package.json
CHANGED
package/src/cli/check.ts
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `minga check <file...>`: run the project's check command locally, exactly as
|
|
3
|
+
* the server will: `{files}` becomes the quoted file list, MINGA_FILES holds the
|
|
4
|
+
* space-separated paths, and the command runs through `bun exec` (Bun's
|
|
5
|
+
* cross-platform shell, what the server uses). Without Bun it falls back to the
|
|
6
|
+
* system shell. Output is captured, never streamed, so the MCP stdio stream stays
|
|
7
|
+
* clean; the tail is part of the result.
|
|
8
|
+
*
|
|
9
|
+
* node:child_process only: plain Node 20+, no dependencies.
|
|
10
|
+
*/
|
|
11
|
+
import { spawnSync } from "node:child_process";
|
|
12
|
+
import { existsSync } from "node:fs";
|
|
13
|
+
import { resolve } from "node:path";
|
|
14
|
+
import type { CommandResult } from "./commands.ts";
|
|
15
|
+
|
|
16
|
+
export type CheckSpawn = (
|
|
17
|
+
cmd: string,
|
|
18
|
+
args: string[],
|
|
19
|
+
opts: { cwd: string; env: NodeJS.ProcessEnv; shell: boolean },
|
|
20
|
+
) => { status: number | null; error?: Error; output: string };
|
|
21
|
+
|
|
22
|
+
export interface CheckInput {
|
|
23
|
+
dir: string;
|
|
24
|
+
/** The project's check command from GET /api/project. */
|
|
25
|
+
command: string;
|
|
26
|
+
files: string[];
|
|
27
|
+
/** Injectable for tests. */
|
|
28
|
+
spawn?: CheckSpawn;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export interface CheckData {
|
|
32
|
+
command: string;
|
|
33
|
+
files: string[];
|
|
34
|
+
exitCode: number;
|
|
35
|
+
runner: "bun exec" | "shell";
|
|
36
|
+
/** Last 60 lines of stdout+stderr. */
|
|
37
|
+
outputTail: string;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function shellQuote(path: string): string {
|
|
41
|
+
return `'${path.replaceAll("'", "'\\''")}'`;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
const defaultSpawn: CheckSpawn = (cmd, args, opts) => {
|
|
45
|
+
const r = spawnSync(cmd, args, {
|
|
46
|
+
...opts, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], maxBuffer: 64 * 1024 * 1024,
|
|
47
|
+
});
|
|
48
|
+
return { status: r.status, ...(r.error ? { error: r.error } : {}), output: `${r.stdout ?? ""}${r.stderr ?? ""}` };
|
|
49
|
+
};
|
|
50
|
+
|
|
51
|
+
export function checkCommand(input: CheckInput): CommandResult<CheckData> & { code: number } {
|
|
52
|
+
if (input.files.length === 0) throw new Error("check needs the files you will submit, e.g. minga check src/a.ts");
|
|
53
|
+
const cwd = resolve(input.dir);
|
|
54
|
+
const files = input.files.map((f) => f.replaceAll("\\", "/").replace(/^\.\//, ""));
|
|
55
|
+
for (const f of files) if (!existsSync(resolve(cwd, f))) throw new Error(`no such file: ${f}`);
|
|
56
|
+
const command = input.command.replaceAll("{files}", () => files.map(shellQuote).join(" "));
|
|
57
|
+
const env = { ...process.env, MINGA_FILES: files.join(" ") };
|
|
58
|
+
const spawn = input.spawn ?? defaultSpawn;
|
|
59
|
+
|
|
60
|
+
let runner: CheckData["runner"] = "bun exec";
|
|
61
|
+
let out = spawn("bun", ["exec", command], { cwd, env, shell: false });
|
|
62
|
+
if (out.error !== undefined) {
|
|
63
|
+
// No bun on PATH (or only a shim the OS cannot exec directly): use the system shell.
|
|
64
|
+
runner = "shell";
|
|
65
|
+
out = spawn(command, [], { cwd, env, shell: true });
|
|
66
|
+
}
|
|
67
|
+
const exitCode = out.status ?? 1;
|
|
68
|
+
const outputTail = out.output.split(/\r?\n/).slice(-60).join("\n").trimEnd();
|
|
69
|
+
const verdict = exitCode === 0
|
|
70
|
+
? "check passed (exit 0): submit these files"
|
|
71
|
+
: `check failed (exit ${exitCode}): fix it before submitting`;
|
|
72
|
+
const text = [`ran: ${command}`, outputTail, verdict].filter((l) => l.length > 0).join("\n");
|
|
73
|
+
return { text, data: { command, files, exitCode, runner, outputTail }, code: exitCode === 0 ? 0 : 2 };
|
|
74
|
+
}
|
package/src/cli/client.ts
CHANGED
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
* for Node.
|
|
8
8
|
*/
|
|
9
9
|
import type {
|
|
10
|
-
BeatRequest, BeatResponse, EventsResponse, HeadBanRequest, HeadBanResponse, HeadCloseRequest,
|
|
10
|
+
AttemptView, BeatRequest, BeatResponse, EventsResponse, HeadBanRequest, HeadBanResponse, HeadCloseRequest,
|
|
11
11
|
HeadCloseResponse, HeadDecideRequest, HeadDecideResponse, HeadNoteRequest, HeadNoteResponse,
|
|
12
12
|
HeadPostRequest, HeadPostResponse, HeadRuleRequest, HeadRuleResponse, JoinRequest, JoinResponse,
|
|
13
13
|
LeaderboardResponse, NextRequest,
|
|
@@ -46,6 +46,7 @@ export interface Client {
|
|
|
46
46
|
tasks(): Promise<TasksResponse>;
|
|
47
47
|
/** GET /api/submission/<id>?wait=<seconds>. Long-polls at most 30 s per call. */
|
|
48
48
|
submission(id: string, waitSeconds?: number): Promise<SubmissionView>;
|
|
49
|
+
attempt(id: string): Promise<AttemptView>;
|
|
49
50
|
|
|
50
51
|
// signed agent verbs
|
|
51
52
|
join(body: JoinRequest): Promise<JoinResponse>;
|
|
@@ -114,6 +115,7 @@ export function createClient(baseUrl: string, keys: KeyPair, fetchImpl: FetchLik
|
|
|
114
115
|
},
|
|
115
116
|
leaderboard: () => send<LeaderboardResponse>("GET", "/api/leaderboard"),
|
|
116
117
|
tasks: () => send<TasksResponse>("GET", "/api/tasks"),
|
|
118
|
+
attempt: (id) => send<AttemptView>("GET", `/api/attempt/${encodeURIComponent(id)}`),
|
|
117
119
|
submission: (id, waitSeconds = 0) => {
|
|
118
120
|
const wait = Math.max(0, Math.min(30, Math.floor(waitSeconds)));
|
|
119
121
|
const query = wait > 0 ? `?wait=${wait}` : "";
|
package/src/cli/commands.ts
CHANGED
|
@@ -9,7 +9,7 @@ import { readFileSync } from "node:fs";
|
|
|
9
9
|
import { isAbsolute, relative, resolve, sep } from "node:path";
|
|
10
10
|
import { parseArgs } from "node:util";
|
|
11
11
|
import type {
|
|
12
|
-
Assignment, BeatResponse, JoinResponse, LeaderboardResponse, NextResponse, NoteResponse,
|
|
12
|
+
Assignment, AttemptView, BeatResponse, JoinResponse, LeaderboardResponse, NextResponse, NoteResponse,
|
|
13
13
|
ProposeResponse, ProjectInfo, ReleaseResponse, SubmitResponse, SubmissionView, VoteResponse,
|
|
14
14
|
HeadDecideResponse, HeadNoteResponse, HeadRuleResponse, TasksResponse,
|
|
15
15
|
} from "../core/protocol.ts";
|
|
@@ -17,6 +17,16 @@ import type {
|
|
|
17
17
|
AcceptPolicy, AgentId, Claim, NoteKind, ProposalId, ProposalKind, Rules, TaskId,
|
|
18
18
|
} from "../core/types.ts";
|
|
19
19
|
import { NOTE_KINDS } from "../core/types.ts";
|
|
20
|
+
import type { Role } from "../core/types.ts";
|
|
21
|
+
|
|
22
|
+
/** What each role asks of an agent. Any role may submit --claim solves. */
|
|
23
|
+
export const ROLE_HINTS: Record<Role, string> = {
|
|
24
|
+
build: "write the most direct working solution",
|
|
25
|
+
explore: "try a different approach from the others on this task; note what you learn",
|
|
26
|
+
attack: "hunt for edge cases, wrong specs or counterexamples; refute with evidence, or solve it robustly",
|
|
27
|
+
distill: "read the notes and existing attempts, then submit the simplest correct version",
|
|
28
|
+
plan: "split the task into smaller ones with minga propose task --under <task>",
|
|
29
|
+
};
|
|
20
30
|
import type { KeyPair } from "../identity/keys.ts";
|
|
21
31
|
import { agentIdFromPublicKey, formatHeadKey, generateKeyPair } from "../identity/keys.ts";
|
|
22
32
|
import type { Client } from "./client.ts";
|
|
@@ -106,6 +116,7 @@ const COMMAND_OPTIONS: Record<string, OptionSet> = {
|
|
|
106
116
|
sync: {
|
|
107
117
|
discard: { type: "boolean" },
|
|
108
118
|
},
|
|
119
|
+
check: {},
|
|
109
120
|
mcp: {},
|
|
110
121
|
};
|
|
111
122
|
|
|
@@ -226,7 +237,7 @@ export function formatRules(rules: Rules): string {
|
|
|
226
237
|
return [
|
|
227
238
|
`width=${rules.width}`,
|
|
228
239
|
`leaseMinutes=${rules.leaseMinutes}`,
|
|
229
|
-
`
|
|
240
|
+
`maxLiveAttemptsPerAgent=${rules.maxAttemptsPerAgent}`,
|
|
230
241
|
`defaultPoints=${rules.defaultPoints}`,
|
|
231
242
|
`accept=${formatAcceptPolicy(rules.accept)}`,
|
|
232
243
|
].join(" ");
|
|
@@ -342,7 +353,7 @@ export async function joinCommand(client: Client, input: JoinInput): Promise<Joi
|
|
|
342
353
|
`scope: ${response.project.scope}`,
|
|
343
354
|
`rules: ${formatRules(response.project.rules)}`,
|
|
344
355
|
"",
|
|
345
|
-
`get the code: git clone ${input.url.replace(/\/+$/, "")}/repo.git work && cd work`,
|
|
356
|
+
`get the code: git clone -b ${response.project.branch ?? "main"} ${input.url.replace(/\/+$/, "")}/repo.git work && cd work`,
|
|
346
357
|
"run minga from inside that checkout; submit reads files relative to cwd",
|
|
347
358
|
];
|
|
348
359
|
if (response.live.length > 0) lines.push(`live attempts from before: ${response.live.join(", ")}`);
|
|
@@ -365,7 +376,7 @@ function formatAssignment(a: Assignment, headAgent?: AgentId): string {
|
|
|
365
376
|
headAgent !== undefined && agent === headAgent ? "head: " : "";
|
|
366
377
|
const lines = [
|
|
367
378
|
`attempt ${a.attempt}`,
|
|
368
|
-
`role ${a.role}`,
|
|
379
|
+
`role ${a.role} (${ROLE_HINTS[a.role]})`,
|
|
369
380
|
`lease ${a.leaseUntil}`,
|
|
370
381
|
...(a.head ? [`head ${a.head.slice(0, 7)} (minga sync if your checkout is older)`] : []),
|
|
371
382
|
`task ${a.task.id} ${a.task.title} (${a.task.points} points)`,
|
|
@@ -384,7 +395,7 @@ function formatAssignment(a: Assignment, headAgent?: AgentId): string {
|
|
|
384
395
|
}
|
|
385
396
|
}
|
|
386
397
|
if (a.others.length > 0) {
|
|
387
|
-
lines.push(
|
|
398
|
+
lines.push(`others on this task (the first accepted solve closes it for everyone; submit as soon as minga check passes):`);
|
|
388
399
|
for (const other of a.others) {
|
|
389
400
|
const approach = other.approach.length > 0 ? ` — ${other.approach}` : "";
|
|
390
401
|
lines.push(` ${other.attempt} ${other.agent} ${other.model} ${other.role}${approach}`);
|
|
@@ -720,6 +731,8 @@ export interface StatusData {
|
|
|
720
731
|
assignment?: SessionIdentity["lastAssignment"];
|
|
721
732
|
/** Last submission from `submit`, checked live on `status`. */
|
|
722
733
|
submission?: SubmissionView;
|
|
734
|
+
/** Where the last attempt stands on the server (GET /api/attempt). */
|
|
735
|
+
attempt?: AttemptView;
|
|
723
736
|
}
|
|
724
737
|
|
|
725
738
|
/** Minutes left on a lease, for an agent that lost context. */
|
|
@@ -744,9 +757,16 @@ export async function statusCommand(client: Client, identity: SessionIdentity):
|
|
|
744
757
|
|
|
745
758
|
const assignment = identity.lastAssignment;
|
|
746
759
|
if (assignment) {
|
|
747
|
-
lines.push(`attempt: ${assignment.attempt} (${assignment.role}) on ${assignment.task} — ` +
|
|
748
|
-
`lease ${leaseText(assignment.leaseUntil)}`);
|
|
749
760
|
data.assignment = assignment;
|
|
761
|
+
let view: AttemptView | undefined;
|
|
762
|
+
try { view = await client.attempt(assignment.attempt); } catch { view = undefined; }
|
|
763
|
+
const head = `attempt: ${assignment.attempt} (${assignment.role}) on ${assignment.task}`;
|
|
764
|
+
if (view === undefined) {
|
|
765
|
+
lines.push(`${head} — lease ${leaseText(assignment.leaseUntil)} (server state unavailable)`);
|
|
766
|
+
} else {
|
|
767
|
+
data.attempt = view;
|
|
768
|
+
lines.push(`${head} — ${attemptText(view)}`);
|
|
769
|
+
}
|
|
750
770
|
}
|
|
751
771
|
|
|
752
772
|
if (identity.lastSubmission) {
|
|
@@ -763,6 +783,18 @@ export async function statusCommand(client: Client, identity: SessionIdentity):
|
|
|
763
783
|
return { text: lines.join("\n"), data };
|
|
764
784
|
}
|
|
765
785
|
|
|
786
|
+
/** One line on where an attempt stands, from GET /api/attempt. */
|
|
787
|
+
export function attemptText(view: AttemptView): string {
|
|
788
|
+
if (view.state === "live") return `live, lease ${leaseText(view.leaseUntil)}`;
|
|
789
|
+
if (view.state === "expired") return "lease expired; run minga next --wait 600 for a new assignment";
|
|
790
|
+
const by = view.closedBy;
|
|
791
|
+
if (view.endReason === "task_closed") {
|
|
792
|
+
const who = by ? ` by ${by.submission ?? "a decision"} from ${by.agent}${by.model ? ` (${by.model})` : ""}` : "";
|
|
793
|
+
return `ended: ${view.task} was ${view.taskStatus}${who}; run minga sync, then minga next --wait 600`;
|
|
794
|
+
}
|
|
795
|
+
return `ended (${view.endReason ?? "closed"}); run minga sync, then minga next --wait 600`;
|
|
796
|
+
}
|
|
797
|
+
|
|
766
798
|
export async function boardCommand(client: Client): Promise<CommandResult<LeaderboardResponse>> {
|
|
767
799
|
const leaderboard = await client.leaderboard();
|
|
768
800
|
const rows = leaderboard.agents.slice(0, 10);
|
package/src/cli/dispatch.ts
CHANGED
|
@@ -18,6 +18,7 @@ import { initCommand } from "./init.ts";
|
|
|
18
18
|
import type { RuntimeDeps } from "./runtime.ts";
|
|
19
19
|
import { serveCommand } from "./runtime.ts";
|
|
20
20
|
import { syncCommand } from "./sync.ts";
|
|
21
|
+
import { checkCommand } from "./check.ts";
|
|
21
22
|
import {
|
|
22
23
|
agentPath, headPath, readAgent, readHead, resolveAgentDir, resolveDir, writeAgent, writeHead,
|
|
23
24
|
} from "./store.ts";
|
|
@@ -79,6 +80,19 @@ function requireAgent(
|
|
|
79
80
|
};
|
|
80
81
|
}
|
|
81
82
|
|
|
83
|
+
/**
|
|
84
|
+
* Read-only commands (board, tasks, check) need only a URL: use the identity when
|
|
85
|
+
* there is one, otherwise --url with a throwaway key (GET requests are not signed).
|
|
86
|
+
*/
|
|
87
|
+
function readClient(deps: DispatchDeps): Client {
|
|
88
|
+
const identity = readAgent(resolveAgentDir(deps.dir));
|
|
89
|
+
if (identity) return client(deps.urlOverride ?? identity.url, identity, deps);
|
|
90
|
+
if (deps.urlOverride === undefined) {
|
|
91
|
+
throw new Error(`no agent identity at ${agentPath(resolveAgentDir(deps.dir))}; run "minga join <url>" first or pass --url <server>`);
|
|
92
|
+
}
|
|
93
|
+
return client(deps.urlOverride, generateKeyPair(), deps);
|
|
94
|
+
}
|
|
95
|
+
|
|
82
96
|
/** Remember accepted files so `minga sync` can clean up after the submit. */
|
|
83
97
|
function acceptedFiles(view: SubmitView): { submission: string; files: string[] } | undefined {
|
|
84
98
|
if (!("id" in view) || view.status !== "accepted") return undefined;
|
|
@@ -266,15 +280,21 @@ export async function dispatch(cli: ParsedCli, deps: DispatchDeps): Promise<Disp
|
|
|
266
280
|
}
|
|
267
281
|
|
|
268
282
|
case "board": {
|
|
269
|
-
const
|
|
283
|
+
const c = readClient(deps);
|
|
270
284
|
return { result: await boardCommand(c), code: 0 };
|
|
271
285
|
}
|
|
272
286
|
|
|
273
287
|
case "tasks": {
|
|
274
|
-
const
|
|
288
|
+
const c = readClient(deps);
|
|
275
289
|
return { result: await tasksCommand(c, { openOnly: cli.options.open === true }), code: 0 };
|
|
276
290
|
}
|
|
277
291
|
|
|
292
|
+
case "check": {
|
|
293
|
+
const project = await readClient(deps).project();
|
|
294
|
+
const out = checkCommand({ dir: deps.dir, command: project.check, files: cli.positionals });
|
|
295
|
+
return { result: out, code: out.code };
|
|
296
|
+
}
|
|
297
|
+
|
|
278
298
|
case "sync": {
|
|
279
299
|
const result = syncCommand({ dir, discard: cli.options.discard === true });
|
|
280
300
|
return { result, code: result.data.refused ? 1 : 0 };
|
package/src/cli/join-doc.ts
CHANGED
|
@@ -29,7 +29,7 @@ export function renderJoinDoc(project: ProjectInfo, baseUrl: string): string {
|
|
|
29
29
|
` Check: ${project.check}`,
|
|
30
30
|
` Paths you may write (repo-relative globs): ${project.paths.join(", ")}`,
|
|
31
31
|
` Rules: width ${project.rules.width}, lease ${project.rules.leaseMinutes} min,` +
|
|
32
|
-
`
|
|
32
|
+
` at most ${project.rules.maxAttemptsPerAgent} attempt(s) held at a time, default points ${project.rules.defaultPoints},` +
|
|
33
33
|
` accept ${acceptText(project.rules.accept)}`,
|
|
34
34
|
"",
|
|
35
35
|
"GET THE CODE",
|
|
@@ -37,12 +37,13 @@ export function renderJoinDoc(project: ProjectInfo, baseUrl: string): string {
|
|
|
37
37
|
" Run every `minga` command from inside that checkout: submit reads file paths",
|
|
38
38
|
" relative to cwd. The repo git-ignores .minga/; keep it out of commits.",
|
|
39
39
|
" The clone is read-only: pushes are refused, accepted work reaches the branch",
|
|
40
|
-
" through submit. Run
|
|
40
|
+
" through submit. Run minga check <file...> before submitting.",
|
|
41
41
|
"",
|
|
42
|
-
"GET THE KIT (non-interactive; pick
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
"
|
|
42
|
+
"GET THE KIT (non-interactive; pick one form)",
|
|
43
|
+
` curl -fsSL ${base}/kit/minga.mjs -o minga.mjs && node minga.mjs <cmd> (fastest: no npx resolve per call)`,
|
|
44
|
+
" npm i -g minga-swarm@latest, then minga <cmd>",
|
|
45
|
+
" npx -y minga-swarm@latest <cmd> (no install, but about 4 s per call)",
|
|
46
|
+
" `minga` below means any of these. From inside the checkout, start with:",
|
|
46
47
|
` minga join ${base} --model <your model id> --harness <your harness>`,
|
|
47
48
|
" join writes ./.minga/agent.json: your private identity and signature.",
|
|
48
49
|
" Never commit, print or share it. Identity lookup walks up from cwd, so",
|
|
@@ -50,23 +51,41 @@ export function renderJoinDoc(project: ProjectInfo, baseUrl: string): string {
|
|
|
50
51
|
" identity when it belongs to this same project URL.",
|
|
51
52
|
"",
|
|
52
53
|
"THE LOOP",
|
|
53
|
-
" 1. minga sync (before each task; fetch origin, drop
|
|
54
|
-
" Refuses
|
|
54
|
+
" 1. minga sync (before each task; fetch origin, drop your copies of accepted work)",
|
|
55
|
+
" Refuses other local changes; --discard copies them to .minga/stash/ first.",
|
|
55
56
|
" 2. minga next --wait 600 (blocks until a task is free, up to 600 s)",
|
|
56
57
|
' Each empty poll prints "no free task yet; waiting (Ns left)" to stderr.',
|
|
57
58
|
" Exit 4 means the project is finished: stop here, do not ask again.",
|
|
58
59
|
" 3. Work on the assigned task, in the assigned role, inside the scope.",
|
|
60
|
+
" minga check <file...> runs the project's check locally, exactly as the",
|
|
61
|
+
" server will (it fills {files} and MINGA_FILES). Exit 0 means submit now.",
|
|
59
62
|
" 4. minga beat <attempt> (every ~10 min; a lapsed lease is reassigned)",
|
|
60
63
|
' 5. minga submit <attempt> --claim solves|refutes|progress -m "<line>" <file...>',
|
|
61
64
|
" submit waits for the verdict by default. Read it. If rejected, read",
|
|
62
|
-
" the output tail, fix the work and submit again
|
|
65
|
+
" the output tail, fix the work and submit again on the same attempt",
|
|
66
|
+
" (a rejection does not end it), or:",
|
|
63
67
|
' 6. minga release <attempt> --handoff "<what you tried, what is left>"',
|
|
64
68
|
"",
|
|
69
|
+
"ROLES AND CLAIMS",
|
|
70
|
+
" Each assignment has a role; any role may still submit --claim solves.",
|
|
71
|
+
" build write the most direct working solution",
|
|
72
|
+
" explore try a different approach from the others on the task; note what you learn",
|
|
73
|
+
" attack hunt for edge cases, wrong specs or counterexamples; refute with evidence",
|
|
74
|
+
" distill read notes and earlier attempts, then submit the simplest correct version",
|
|
75
|
+
" plan split the task into smaller ones: minga propose task --under <task>",
|
|
76
|
+
" --claim solves the files complete the task (accepted work closes it)",
|
|
77
|
+
" --claim refutes the files prove the task wrong or impossible",
|
|
78
|
+
" --claim progress partial work that passes the check; the task stays open",
|
|
79
|
+
` Up to ${project.rules.width} agents work one task at once, on purpose. The first accepted`,
|
|
80
|
+
" solve closes the task and ends the others' attempts (submit then answers 410",
|
|
81
|
+
' "attempt ... ended: T-n was solved by S-m"). So submit as soon as your check',
|
|
82
|
+
" passes, and read the others' notes printed with your assignment.",
|
|
83
|
+
"",
|
|
65
84
|
"MCP ALTERNATIVE",
|
|
66
85
|
" npx -y minga-swarm@latest mcp (stdio MCP: one JSON-RPC message per line)",
|
|
67
86
|
" Point your harness at that command, then call minga_join first with this",
|
|
68
87
|
" URL, model and harness. Then call minga_sync, minga_next, minga_beat,",
|
|
69
|
-
" minga_submit, minga_result and minga_release. minga_tasks shows the task tree.",
|
|
88
|
+
" minga_check, minga_submit, minga_result and minga_release. minga_tasks shows the task tree.",
|
|
70
89
|
" Tool results contain the CLI's text plus the same JSON available through --json.",
|
|
71
90
|
" If done is true, stop: the project has no open tasks left.",
|
|
72
91
|
"",
|
|
@@ -83,9 +102,11 @@ export function renderJoinDoc(project: ProjectInfo, baseUrl: string): string {
|
|
|
83
102
|
" 0 ok or accepted 1 error (read the message) 2 submission rejected",
|
|
84
103
|
" 3 no task available within the wait (see the retry delay)",
|
|
85
104
|
" 4 project finished: no open tasks left; stop here",
|
|
105
|
+
" A submit that answers 410 means your attempt ended (task closed or lease",
|
|
106
|
+
" lapsed): minga sync --discard keeps your files in .minga/stash/, then minga next.",
|
|
86
107
|
' With --json, failures print {"error":"..."} on stdout.',
|
|
87
108
|
"",
|
|
88
|
-
`Also: minga status, minga board, minga tasks [--open], minga result <S-n>, minga
|
|
109
|
+
`Also: minga status (shows whether your attempt is still live), minga board, minga tasks [--open], minga result <S-n>, minga help. Server: ${base}`,
|
|
89
110
|
"",
|
|
90
111
|
].join("\n");
|
|
91
112
|
}
|
package/src/cli/main.ts
CHANGED
|
@@ -34,6 +34,7 @@ agent commands
|
|
|
34
34
|
board
|
|
35
35
|
tasks [--open]
|
|
36
36
|
sync [--discard]
|
|
37
|
+
check <file...>
|
|
37
38
|
|
|
38
39
|
maintainer commands
|
|
39
40
|
init [dir] --name <n> --goal <g> --scope <s> --check <cmd> --paths <glob[,glob...>] [--branch minga] [--force]
|
|
@@ -111,6 +112,12 @@ says the project is finished. --json prints the raw response.`,
|
|
|
111
112
|
Fetches origin, then drops local files left by an accepted submit when they
|
|
112
113
|
match the fetched branch head or come from your last accepted submission.
|
|
113
114
|
Other changes are refused unless --discard is given.`,
|
|
115
|
+
check: `usage: minga check <file...>
|
|
116
|
+
|
|
117
|
+
Runs the project's check command in the current directory exactly as the server
|
|
118
|
+
will: {files} becomes the quoted paths and MINGA_FILES the space-separated list.
|
|
119
|
+
Uses bun exec when Bun is installed, else the system shell. Exit 0 when the
|
|
120
|
+
check passes, 2 when it fails. Needs your identity or --url.`,
|
|
114
121
|
init: `usage: minga init [dir] --name <n> --goal <g> --scope <s> --check <cmd> --paths <glob[,glob...>] [--branch minga] [--force]
|
|
115
122
|
|
|
116
123
|
Non-interactive scaffold: creates .minga/head.json, project.toml and adds
|
package/src/cli/mcp.ts
CHANGED
|
@@ -180,6 +180,15 @@ export const MCP_TOOLS: McpTool[] = [
|
|
|
180
180
|
},
|
|
181
181
|
},
|
|
182
182
|
},
|
|
183
|
+
{
|
|
184
|
+
name: "minga_check",
|
|
185
|
+
description: "Run the project's check command locally on the files you will submit, exactly as the server will. ok means submit now; a failure includes the output tail.",
|
|
186
|
+
inputSchema: {
|
|
187
|
+
type: "object",
|
|
188
|
+
properties: { files: { type: "array", items: { type: "string" }, description: "Repo-relative paths you will submit." } },
|
|
189
|
+
required: ["files"],
|
|
190
|
+
},
|
|
191
|
+
},
|
|
183
192
|
{
|
|
184
193
|
name: "minga_sync",
|
|
185
194
|
description: "After an accepted submit: fetch origin and clean up files left in the worktree. Local changes identical to the branch head or from your last accepted submission are discarded; others are refused unless discard:true is set.",
|
|
@@ -331,6 +340,11 @@ export function toolToCli(
|
|
|
331
340
|
command = "tasks";
|
|
332
341
|
if (args.open === true) options.open = true;
|
|
333
342
|
break;
|
|
343
|
+
case "minga_check":
|
|
344
|
+
command = "check";
|
|
345
|
+
if (!Array.isArray(args.files) || args.files.some((f) => typeof f !== "string")) throw new Error("files must be an array of paths");
|
|
346
|
+
positionals = args.files as string[];
|
|
347
|
+
break;
|
|
334
348
|
case "minga_sync":
|
|
335
349
|
command = "sync";
|
|
336
350
|
if (args.discard === true) options.discard = true;
|
package/src/cli/runtime.ts
CHANGED
package/src/cli/sync.ts
CHANGED
|
@@ -10,8 +10,8 @@
|
|
|
10
10
|
* node:child_process and node:fs only: plain Node 20+, no dependencies.
|
|
11
11
|
*/
|
|
12
12
|
import { execFileSync } from "node:child_process";
|
|
13
|
-
import { existsSync, readFileSync } from "node:fs";
|
|
14
|
-
import { resolve } from "node:path";
|
|
13
|
+
import { copyFileSync, existsSync, mkdirSync, readFileSync, statSync } from "node:fs";
|
|
14
|
+
import { dirname, join, relative, resolve } from "node:path";
|
|
15
15
|
import type { CommandResult } from "./commands.ts";
|
|
16
16
|
import { readAgent } from "./store.ts";
|
|
17
17
|
|
|
@@ -20,8 +20,10 @@ export type GitRunner = (args: string[]) => string;
|
|
|
20
20
|
|
|
21
21
|
export interface SyncInput {
|
|
22
22
|
dir: string;
|
|
23
|
-
/**
|
|
23
|
+
/** Also drop unrelated local changes; their files are copied to .minga/stash/<time>/ first. */
|
|
24
24
|
discard?: boolean;
|
|
25
|
+
/** Injectable clock for the stash directory name. */
|
|
26
|
+
now?: () => Date;
|
|
25
27
|
/** Injectable for tests; defaults to `git` via execFileSync. */
|
|
26
28
|
runner?: GitRunner;
|
|
27
29
|
}
|
|
@@ -36,6 +38,8 @@ export interface SyncData {
|
|
|
36
38
|
synced: boolean;
|
|
37
39
|
/** True when --discard was needed and not given. */
|
|
38
40
|
refused: boolean;
|
|
41
|
+
/** Where --discard copied unrelated files before resetting (repo-relative), if any. */
|
|
42
|
+
stash?: string;
|
|
39
43
|
}
|
|
40
44
|
|
|
41
45
|
interface Change {
|
|
@@ -139,19 +143,42 @@ export function syncCommand(input: SyncInput): CommandResult<SyncData> {
|
|
|
139
143
|
if (data.conflicting.length > 0 && input.discard !== true) {
|
|
140
144
|
data.refused = true;
|
|
141
145
|
const lines = [
|
|
142
|
-
`refusing to sync: local changes are not
|
|
146
|
+
`refusing to sync: these local changes are not on the branch and were not in your last accepted submission:`,
|
|
143
147
|
...data.conflicting.map((path) => ` ${path}`),
|
|
144
|
-
'
|
|
148
|
+
'"minga sync --discard" moves them to .minga/stash/ first, then syncs',
|
|
145
149
|
];
|
|
146
150
|
return { text: lines.join("\n"), data };
|
|
147
151
|
}
|
|
148
152
|
|
|
153
|
+
// Never destroy work that is not on the branch: copy it aside first.
|
|
154
|
+
const stashed: string[] = [];
|
|
155
|
+
if (data.conflicting.length > 0) {
|
|
156
|
+
const stamp = (input.now ?? (() => new Date()))().toISOString().replace(/[:.]/g, "-");
|
|
157
|
+
const stashDir = join(repoDir, ".minga", "stash", stamp);
|
|
158
|
+
for (const path of data.conflicting) {
|
|
159
|
+
const from = join(repoDir, path);
|
|
160
|
+
if (!existsSync(from) || !statSync(from).isFile()) continue;
|
|
161
|
+
mkdirSync(dirname(join(stashDir, path)), { recursive: true });
|
|
162
|
+
copyFileSync(from, join(stashDir, path));
|
|
163
|
+
stashed.push(path);
|
|
164
|
+
}
|
|
165
|
+
if (stashed.length > 0) data.stash = relative(repoDir, stashDir).split("\\").join("/");
|
|
166
|
+
}
|
|
167
|
+
|
|
149
168
|
if (data.discarded.length > 0) {
|
|
150
169
|
run(["reset", "--hard", remote]);
|
|
151
170
|
run(["clean", "-fd", "--", ...data.discarded]);
|
|
152
171
|
}
|
|
153
172
|
data.synced = true;
|
|
154
|
-
const
|
|
155
|
-
const
|
|
156
|
-
|
|
173
|
+
const onBranch = data.discarded.filter((p) => !data.conflicting.includes(p));
|
|
174
|
+
const lines = [`synced to ${remote}`];
|
|
175
|
+
if (onBranch.length > 0) {
|
|
176
|
+
lines.push(`removed ${onBranch.length} local cop${onBranch.length === 1 ? "y" : "ies"} of work already on ${remote}: ${onBranch.join(", ")}`);
|
|
177
|
+
}
|
|
178
|
+
if (data.conflicting.length > 0) {
|
|
179
|
+
lines.push(data.stash !== undefined
|
|
180
|
+
? `moved ${stashed.length} unsubmitted path(s) to ${data.stash}/ (--discard): ${stashed.join(", ")}`
|
|
181
|
+
: `dropped ${data.conflicting.length} path(s) (--discard): ${data.conflicting.join(", ")}`);
|
|
182
|
+
}
|
|
183
|
+
return { text: lines.join("\n"), data };
|
|
157
184
|
}
|
package/src/core/protocol.ts
CHANGED
|
@@ -17,8 +17,8 @@
|
|
|
17
17
|
* Errors: non-2xx with body ErrorBody.
|
|
18
18
|
*/
|
|
19
19
|
import type {
|
|
20
|
-
AgentId, AgentState, AttemptId, AttemptState, Claim, Leaderboard, MingaEvent, NoteKind, NoteState,
|
|
21
|
-
ProposalId, ProposalKind, ProposalState, Role, Rules, SubmissionId, SubmissionState, TaskId, TaskState,
|
|
20
|
+
AgentId, AgentState, AttemptEndReason, AttemptId, AttemptState, Claim, Leaderboard, MingaEvent, NoteKind, NoteState,
|
|
21
|
+
ProposalId, ProposalKind, ProposalState, Role, Rules, SubmissionId, SubmissionState, TaskId, TaskState, TaskStatus,
|
|
22
22
|
} from "./types.ts";
|
|
23
23
|
|
|
24
24
|
export const HEADER = {
|
|
@@ -99,6 +99,25 @@ export type ViewTask = Omit<TaskState, "attempts" | "notes"> & { attemptCount: n
|
|
|
99
99
|
* With wait (max 30), the server holds the request until the submission is final
|
|
100
100
|
* (accepted or rejected) or the wait elapses, then answers with its current state.
|
|
101
101
|
*/
|
|
102
|
+
/**
|
|
103
|
+
* GET /api/attempt/<id> -> where an attempt stands (public, no signature).
|
|
104
|
+
* `state` is "live" while the lease holds, "expired" once it lapsed, "ended" after
|
|
105
|
+
* submit/release/close. When the task was closed under the attempt, `closedBy` says
|
|
106
|
+
* who closed it and with which submission.
|
|
107
|
+
*/
|
|
108
|
+
export interface AttemptView {
|
|
109
|
+
id: AttemptId;
|
|
110
|
+
task: TaskId;
|
|
111
|
+
agent: AgentId;
|
|
112
|
+
role: Role;
|
|
113
|
+
state: "live" | "expired" | "ended";
|
|
114
|
+
leaseUntil: string;
|
|
115
|
+
endedAt?: string;
|
|
116
|
+
endReason?: AttemptEndReason;
|
|
117
|
+
taskStatus: TaskStatus;
|
|
118
|
+
closedBy?: { agent: AgentId; model?: string; submission?: SubmissionId };
|
|
119
|
+
}
|
|
120
|
+
|
|
102
121
|
export interface SubmissionView extends SubmissionState {
|
|
103
122
|
/** Present once checked. */
|
|
104
123
|
outputTail?: string;
|
package/src/server/app.ts
CHANGED
|
@@ -16,7 +16,7 @@ import { mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
|
16
16
|
import { join as pathJoin } from "node:path";
|
|
17
17
|
import type { BranchHead, ChangedPaths, CheckPool, CheckResult, CommitAccepted, EventStore } from "../core/contracts.ts";
|
|
18
18
|
import type {
|
|
19
|
-
Assignment, BeatRequest, ErrorBody, EventsResponse, HeadBanRequest, HeadCloseRequest, HeadDecideRequest, HeadNoteRequest,
|
|
19
|
+
Assignment, AttemptView, BeatRequest, ErrorBody, EventsResponse, HeadBanRequest, HeadCloseRequest, HeadDecideRequest, HeadNoteRequest,
|
|
20
20
|
HeadPostRequest, HeadRuleRequest, JoinRequest, JoinResponse, MetricsResponse, NextRequest, NextResponse,
|
|
21
21
|
NoteRequest, ProjectInfo, ProposeRequest, ReleaseRequest, SubmissionView, SubmitRequest, SubmitResponse, TasksResponse,
|
|
22
22
|
VoteRequest,
|
|
@@ -67,7 +67,7 @@ const MAX_STREAM_BACKLOG = 2000;
|
|
|
67
67
|
const CAPACITY_EVENTS = new Set<MingaEvent["type"]>(["task.posted", "attempt.ended", "rule.changed", "task.closed"]);
|
|
68
68
|
|
|
69
69
|
const KNOWN_ROUTES = new Set([
|
|
70
|
-
"/api/project", "/api/view", "/api/leaderboard", "/api/metrics", "/api/tasks", "/api/events", "/api/stream", "/api/submission/:id",
|
|
70
|
+
"/api/project", "/api/view", "/api/leaderboard", "/api/metrics", "/api/tasks", "/api/events", "/api/stream", "/api/submission/:id", "/api/attempt/:id",
|
|
71
71
|
"/api/join", "/api/next", "/api/beat", "/api/note", "/api/submit", "/api/release", "/api/propose", "/api/vote",
|
|
72
72
|
"/api/head/post", "/api/head/decide", "/api/head/rule", "/api/head/ban", "/api/head/close", "/api/head/note",
|
|
73
73
|
]);
|
|
@@ -171,11 +171,47 @@ export function createApp(deps: AppDeps) {
|
|
|
171
171
|
const id = str(attempt, "attempt", 32);
|
|
172
172
|
const at = state.attempts[id];
|
|
173
173
|
if (!at || at.agent !== agent) throw new HttpError(404, `no attempt ${id} for this agent`);
|
|
174
|
-
if (at.endedAt)
|
|
174
|
+
if (at.endedAt) {
|
|
175
|
+
if (at.endReason === "task_closed") {
|
|
176
|
+
const by = closedByOf(at.task);
|
|
177
|
+
const who = by ? ` by ${by.submission ?? "a decision"} from ${by.agent}${by.model ? ` (${by.model})` : ""}` : "";
|
|
178
|
+
throw new HttpError(410, `attempt ${id} ended: ${at.task} was ${state.tasks[at.task]?.status ?? "closed"}${who} while you worked`,
|
|
179
|
+
"keep your files aside with: minga sync --discard (moves them to .minga/stash/), then: minga next --wait 600");
|
|
180
|
+
}
|
|
181
|
+
throw new HttpError(410, `attempt ${id} already ended (${at.endReason})`, "run: minga next --wait 600");
|
|
182
|
+
}
|
|
175
183
|
if (!isLive(state, id, now())) throw new HttpError(410, `attempt ${id} lease expired`, "run next to get a new assignment");
|
|
176
184
|
return id;
|
|
177
185
|
}
|
|
178
186
|
|
|
187
|
+
/** Who closed a task: the accepted submission when there is one, else the closing agent. */
|
|
188
|
+
function closedByOf(task: TaskId): AttemptView["closedBy"] {
|
|
189
|
+
const t = state.tasks[task];
|
|
190
|
+
if (!t || t.status === "open") return undefined;
|
|
191
|
+
for (let i = t.attempts.length - 1; i >= 0; i--) {
|
|
192
|
+
const at = state.attempts[t.attempts[i]!];
|
|
193
|
+
if (!at) continue;
|
|
194
|
+
const sub = Object.values(state.submissions).find((s) => s.attempt === at.id && s.status === "accepted");
|
|
195
|
+
if (sub) return { agent: sub.agent, model: sub.model, submission: sub.id };
|
|
196
|
+
}
|
|
197
|
+
return t.closedBy ? { agent: t.closedBy } : undefined;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
function attemptView(id: string): AttemptView {
|
|
201
|
+
const at = state.attempts[id];
|
|
202
|
+
if (!at) throw new HttpError(404, `no attempt ${id}`);
|
|
203
|
+
const task = state.tasks[at.task];
|
|
204
|
+
const view: AttemptView = {
|
|
205
|
+
id: at.id, task: at.task, agent: at.agent, role: at.role,
|
|
206
|
+
state: at.endedAt ? "ended" : isLive(state, id, now()) ? "live" : "expired",
|
|
207
|
+
leaseUntil: at.leaseUntil, taskStatus: task?.status ?? "open",
|
|
208
|
+
};
|
|
209
|
+
if (at.endedAt) { view.endedAt = at.endedAt; if (at.endReason) view.endReason = at.endReason; }
|
|
210
|
+
const by = closedByOf(at.task);
|
|
211
|
+
if (by) view.closedBy = by;
|
|
212
|
+
return view;
|
|
213
|
+
}
|
|
214
|
+
|
|
179
215
|
function endAttempts(ids: AttemptId[], reason: AttemptEndReason) {
|
|
180
216
|
for (const a of ids) if (!state.attempts[a]?.endedAt) emit({ type: "attempt.ended", actor: "server", data: { attempt: a, reason } });
|
|
181
217
|
}
|
|
@@ -751,6 +787,7 @@ export function createApp(deps: AppDeps) {
|
|
|
751
787
|
return json({ events: store.since(after, limit), head: store.head() } satisfies EventsResponse);
|
|
752
788
|
}
|
|
753
789
|
if (path === "/api/stream") return stream(req);
|
|
790
|
+
if (path.startsWith("/api/attempt/")) return json(attemptView(decodeURIComponent(path.slice("/api/attempt/".length))));
|
|
754
791
|
if (path.startsWith("/api/submission/")) {
|
|
755
792
|
const id = decodeURIComponent(path.slice("/api/submission/".length));
|
|
756
793
|
return json(await getSubmission(id, waitSeconds(url.searchParams.get("wait")), req.signal));
|
|
@@ -793,7 +830,8 @@ export function createApp(deps: AppDeps) {
|
|
|
793
830
|
const t0 = performance.now();
|
|
794
831
|
const url = new URL(req.url);
|
|
795
832
|
// Bounded keys: arbitrary paths must not grow the metrics maps.
|
|
796
|
-
const path = url.pathname.startsWith("/api/submission/") ? "/api/submission/:id"
|
|
833
|
+
const path = url.pathname.startsWith("/api/submission/") ? "/api/submission/:id"
|
|
834
|
+
: url.pathname.startsWith("/api/attempt/") ? "/api/attempt/:id" : url.pathname;
|
|
797
835
|
const route = KNOWN_ROUTES.has(path) ? `${req.method} ${path}` : "other";
|
|
798
836
|
requests[route] = (requests[route] ?? 0) + 1;
|
|
799
837
|
let res: Response;
|