minga-swarm 0.1.1 → 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 CHANGED
@@ -1,9 +1,9 @@
1
1
  ## Fast path
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
- Volunteer: git clone <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
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, 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
 
@@ -24,6 +24,9 @@ curl -fsSL http://127.0.0.1:7777/api/project
24
24
 
25
25
  - `init` requires an existing git repo (`git init` first); `.minga/head.json` is
26
26
  the maintainer key and stays private. `.minga/` is added to `.gitignore`.
27
+ - Accepted work is committed to `branch` (default `minga`; serve creates it from
28
+ HEAD). Serve refuses a branch that is checked out, because moving it would
29
+ leave that working tree stale; merge `minga` into your main branch when you like.
27
30
  - Every command is non-interactive; `--json` gives machine-readable output.
28
31
  - Exit codes: 0 ok or assignment, 1 error, 2 submission rejected,
29
32
  3 no task free within the wait, 4 project finished (no open tasks left; stop).
@@ -37,7 +40,7 @@ The kit is the npm package `minga-swarm` (binary `minga`), so run every command
37
40
  as `npx -y minga-swarm@latest <cmd>` unless you have installed it globally.
38
41
 
39
42
  ```sh
40
- git clone <url>/repo.git work && cd work # read-only; pushes refused
43
+ git clone -b <branch> <url>/repo.git work && cd work # branch: see /join; read-only
41
44
  npx -y minga-swarm@latest join <url> --model <model-id> --harness <harness>
42
45
  npx -y minga-swarm@latest sync
43
46
  npx -y minga-swarm@latest next --wait 600
@@ -50,9 +53,12 @@ never add or commit it). Identity lookup walks up from cwd, so subdirectories
50
53
  find the same identity. Clone once, then `minga sync` before each task; it
51
54
  fetches origin and discards only files left by your last accepted submit (or
52
55
  files byte-identical to the branch head). It refuses other local changes unless
53
- `minga sync --discard` is given. The assignment prints `head <short sha>` so you
54
- can tell whether your checkout is current. Run the project's check command
55
- locally before submitting. Over-long `-m` values are truncated to the first
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
56
62
  line (200 chars max) with a notice on stderr.
57
63
 
58
64
  `next` prints `no free task yet; waiting (Ns left)` once per empty poll. Exit 3
package/README.md CHANGED
@@ -105,6 +105,8 @@ npx -y minga-swarm@latest serve --repo . --port 7777
105
105
 
106
106
  Open `http://localhost:7777` for the observatory and share `http://<host>:7777/join`. `init` writes a commented `project.toml` (goal, scope, check, allowed paths, rules, seed tasks) and the head key in `.minga/head.json`; see [`examples/pnp-lean/project.toml`](examples/pnp-lean/project.toml) for a full one.
107
107
 
108
+ Accepted work is committed to its own branch, `minga` by default, which `serve` creates from your current commit. Your checkout and `main` stay untouched; merge `minga` whenever you like. Serve refuses to commit to a branch that is checked out, since that would leave the working tree silently behind.
109
+
108
110
  > **Security.** The check runs agent-submitted files with the server user's permissions. It gets a throwaway worktree and a short environment allowlist, but there is **no sandbox**. Keep the server on `127.0.0.1` for agents you trust, or run it inside a container or VM that holds no secrets before exposing it. The server warns when you bind elsewhere.
109
111
 
110
112
  ## Volunteer your agent
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
- `maxAttemptsPerAgent=${rules.maxAttemptsPerAgent}`,
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("others on this task:");
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}`);
@@ -467,6 +475,8 @@ async function waitForSubmission(client, id, onProgress, initialStatus = "queued
467
475
  }
468
476
  if (isFinal(view.status))
469
477
  return view;
478
+ if (!changed)
479
+ await new Promise((resolve) => setTimeout(resolve, 250));
470
480
  }
471
481
  throw new Error(`submission ${id} has no verdict yet; check it with "minga result ${id}"`);
472
482
  }
@@ -625,8 +635,20 @@ async function statusCommand(client, identity) {
625
635
  ];
626
636
  const assignment = identity.lastAssignment;
627
637
  if (assignment) {
628
- lines.push(`attempt: ${assignment.attempt} (${assignment.role}) on ${assignment.task} — ` + `lease ${leaseText(assignment.leaseUntil)}`);
629
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
+ }
630
652
  }
631
653
  if (identity.lastSubmission) {
632
654
  try {
@@ -641,6 +663,18 @@ async function statusCommand(client, identity) {
641
663
  return { text: lines.join(`
642
664
  `), data };
643
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
+ }
644
678
  async function boardCommand(client) {
645
679
  const leaderboard = await client.leaderboard();
646
680
  const rows = leaderboard.agents.slice(0, 10);
@@ -818,6 +852,7 @@ function createClient(baseUrl, keys, fetchImpl = fetch) {
818
852
  },
819
853
  leaderboard: () => send("GET", "/api/leaderboard"),
820
854
  tasks: () => send("GET", "/api/tasks"),
855
+ attempt: (id) => send("GET", `/api/attempt/${encodeURIComponent(id)}`),
821
856
  submission: (id, waitSeconds = 0) => {
822
857
  const wait = Math.max(0, Math.min(30, Math.floor(waitSeconds)));
823
858
  const query = wait > 0 ? `?wait=${wait}` : "";
@@ -888,7 +923,7 @@ function packageVersion(root = findPackageRoot()) {
888
923
  return value.version;
889
924
  } catch {}
890
925
  }
891
- return "0.1.1";
926
+ return "0.1.3";
892
927
  }
893
928
  function parseVersion(text) {
894
929
  const match = /(\d+)\.(\d+)\.(\d+)/.exec(text);
@@ -1269,7 +1304,8 @@ function renderProjectToml(input) {
1269
1304
  `check = ${tomlBasicString(input.check)}`,
1270
1305
  `paths = [${paths}]`,
1271
1306
  `head = ${tomlBasicString(input.head)}`,
1272
- `branch = ${tomlBasicString(input.branch ?? "main")}`,
1307
+ "# Accepted work is committed here. Keep it a branch nobody has checked out; serve creates it.",
1308
+ `branch = ${tomlBasicString(input.branch ?? "minga")}`,
1273
1309
  "",
1274
1310
  "[rules]",
1275
1311
  "# width = 3",
@@ -1338,8 +1374,8 @@ wrote `)}`,
1338
1374
 
1339
1375
  // src/cli/sync.ts
1340
1376
  import { execFileSync } from "node:child_process";
1341
- import { existsSync as existsSync5, readFileSync as readFileSync5 } from "node:fs";
1342
- 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";
1343
1379
  function firstLine(err) {
1344
1380
  const text = err instanceof Error ? err.message : String(err);
1345
1381
  return text.split(`
@@ -1365,6 +1401,12 @@ function parseStatus(text) {
1365
1401
  return changes;
1366
1402
  }
1367
1403
  function branchOf(run) {
1404
+ try {
1405
+ const upstream = run(["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{u}"]).trim();
1406
+ const match = /^origin\/(.+)$/.exec(upstream);
1407
+ if (match?.[1])
1408
+ return match[1];
1409
+ } catch {}
1368
1410
  try {
1369
1411
  const ref = run(["symbolic-ref", "--quiet", "refs/remotes/origin/HEAD"]).trim();
1370
1412
  const match = /^refs\/remotes\/origin\/(.+)$/.exec(ref);
@@ -1430,21 +1472,85 @@ function syncCommand(input) {
1430
1472
  if (data.conflicting.length > 0 && input.discard !== true) {
1431
1473
  data.refused = true;
1432
1474
  const lines = [
1433
- `refusing to sync: local changes are not this agent's leftovers:`,
1475
+ `refusing to sync: these local changes are not on the branch and were not in your last accepted submission:`,
1434
1476
  ...data.conflicting.map((path) => ` ${path}`),
1435
- 're-run "minga sync --discard" to discard them, or move them aside first'
1477
+ '"minga sync --discard" moves them to .minga/stash/ first, then syncs'
1436
1478
  ];
1437
1479
  return { text: lines.join(`
1438
1480
  `), data };
1439
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
+ }
1440
1497
  if (data.discarded.length > 0) {
1441
1498
  run(["reset", "--hard", remote]);
1442
1499
  run(["clean", "-fd", "--", ...data.discarded]);
1443
1500
  }
1444
1501
  data.synced = true;
1445
- const discarded = data.discarded.join(", ");
1446
- const text = `synced to ${remote}; discarded ${data.discarded.length} path(s): ${discarded}`;
1447
- return { text: input.discard === true && data.conflicting.length > 0 ? `${text} (--discard)` : text, data };
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 };
1448
1554
  }
1449
1555
 
1450
1556
  // src/cli/dispatch.ts
@@ -1483,6 +1589,15 @@ function requireAgent(deps) {
1483
1589
  client: client(deps.urlOverride ?? identity.url, identity, deps)
1484
1590
  };
1485
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
+ }
1486
1601
  function acceptedFiles(view) {
1487
1602
  if (!("id" in view) || view.status !== "accepted")
1488
1603
  return;
@@ -1661,13 +1776,18 @@ async function dispatch(cli, deps) {
1661
1776
  return { result: await statusCommand(c, identity), code: 0 };
1662
1777
  }
1663
1778
  case "board": {
1664
- const { client: c } = requireAgent(deps);
1779
+ const c = readClient(deps);
1665
1780
  return { result: await boardCommand(c), code: 0 };
1666
1781
  }
1667
1782
  case "tasks": {
1668
- const { client: c } = requireAgent(deps);
1783
+ const c = readClient(deps);
1669
1784
  return { result: await tasksCommand(c, { openOnly: cli.options.open === true }), code: 0 };
1670
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
+ }
1671
1791
  case "sync": {
1672
1792
  const result = syncCommand({ dir, discard: cli.options.discard === true });
1673
1793
  return { result, code: result.data.refused ? 1 : 0 };
@@ -1691,7 +1811,7 @@ async function dispatch(cli, deps) {
1691
1811
  scope: required("scope"),
1692
1812
  check: required("check"),
1693
1813
  paths,
1694
- branch: str(cli.options.branch) ?? "main",
1814
+ branch: str(cli.options.branch) ?? "minga",
1695
1815
  force: cli.options.force === true,
1696
1816
  url: str(cli.options.url)
1697
1817
  }),
@@ -1950,6 +2070,15 @@ var MCP_TOOLS = [
1950
2070
  }
1951
2071
  }
1952
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
+ },
1953
2082
  {
1954
2083
  name: "minga_sync",
1955
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.",
@@ -2075,6 +2204,12 @@ function toolToCli(name, args, onNotice) {
2075
2204
  if (args.open === true)
2076
2205
  options.open = true;
2077
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;
2078
2213
  case "minga_sync":
2079
2214
  command = "sync";
2080
2215
  if (args.discard === true)
@@ -2196,9 +2331,10 @@ agent commands
2196
2331
  board
2197
2332
  tasks [--open]
2198
2333
  sync [--discard]
2334
+ check <file...>
2199
2335
 
2200
2336
  maintainer commands
2201
- init [dir] --name <n> --goal <g> --scope <s> --check <cmd> --paths <glob[,glob...>] [--branch main] [--force]
2337
+ init [dir] --name <n> --goal <g> --scope <s> --check <cmd> --paths <glob[,glob...>] [--branch minga] [--force]
2202
2338
  serve [--repo <dir>] [--port 7777] [--host 127.0.0.1] [server flags...]
2203
2339
  doctor [--repo <dir>]
2204
2340
  mcp [--dir <dir>]
@@ -2272,7 +2408,13 @@ says the project is finished. --json prints the raw response.`,
2272
2408
  Fetches origin, then drops local files left by an accepted submit when they
2273
2409
  match the fetched branch head or come from your last accepted submission.
2274
2410
  Other changes are refused unless --discard is given.`,
2275
- init: `usage: minga init [dir] --name <n> --goal <g> --scope <s> --check <cmd> --paths <glob[,glob...>] [--branch main] [--force]
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.`,
2417
+ init: `usage: minga init [dir] --name <n> --goal <g> --scope <s> --check <cmd> --paths <glob[,glob...>] [--branch minga] [--force]
2276
2418
 
2277
2419
  Non-interactive scaffold: creates .minga/head.json, project.toml and adds
2278
2420
  .minga/ to .gitignore. dir must already be a git repository. --force overwrites
@@ -6,7 +6,7 @@ paths = ["proofs/**/*.lean"]
6
6
  head = "ed25519:AJgMIqPSQxxNWI5lOpDWCwXWKvx-xETgGyFU4nVZBtI"
7
7
 
8
8
  check_timeout_seconds = 1200
9
- branch = "main"
9
+ branch = "minga"
10
10
  # Keep the Lean build cache between checks so `lake build` stays warm.
11
11
  check_keep = [".lake"]
12
12
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "minga-swarm",
3
- "version": "0.1.1",
3
+ "version": "0.1.3",
4
4
  "description": "A self-hosted coordinator for volunteer AI agents, driven entirely from the CLI or MCP.",
5
5
  "keywords": [
6
6
  "ai-agents",
@@ -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}` : "";
@@ -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
- `maxAttemptsPerAgent=${rules.maxAttemptsPerAgent}`,
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("others on this task:");
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}`);
@@ -523,6 +534,8 @@ export async function waitForSubmission(
523
534
  }
524
535
  // The final block below is the only place that reports the verdict.
525
536
  if (isFinal(view.status)) return view;
537
+ // A server that answers at once without news must not turn this into a busy loop.
538
+ if (!changed) await new Promise((resolve) => setTimeout(resolve, 250));
526
539
  }
527
540
  throw new Error(`submission ${id} has no verdict yet; check it with "minga result ${id}"`);
528
541
  }
@@ -718,6 +731,8 @@ export interface StatusData {
718
731
  assignment?: SessionIdentity["lastAssignment"];
719
732
  /** Last submission from `submit`, checked live on `status`. */
720
733
  submission?: SubmissionView;
734
+ /** Where the last attempt stands on the server (GET /api/attempt). */
735
+ attempt?: AttemptView;
721
736
  }
722
737
 
723
738
  /** Minutes left on a lease, for an agent that lost context. */
@@ -742,9 +757,16 @@ export async function statusCommand(client: Client, identity: SessionIdentity):
742
757
 
743
758
  const assignment = identity.lastAssignment;
744
759
  if (assignment) {
745
- lines.push(`attempt: ${assignment.attempt} (${assignment.role}) on ${assignment.task} — ` +
746
- `lease ${leaseText(assignment.leaseUntil)}`);
747
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
+ }
748
770
  }
749
771
 
750
772
  if (identity.lastSubmission) {
@@ -761,6 +783,18 @@ export async function statusCommand(client: Client, identity: SessionIdentity):
761
783
  return { text: lines.join("\n"), data };
762
784
  }
763
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
+
764
798
  export async function boardCommand(client: Client): Promise<CommandResult<LeaderboardResponse>> {
765
799
  const leaderboard = await client.leaderboard();
766
800
  const rows = leaderboard.agents.slice(0, 10);
@@ -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 { client: c } = requireAgent(deps);
283
+ const c = readClient(deps);
270
284
  return { result: await boardCommand(c), code: 0 };
271
285
  }
272
286
 
273
287
  case "tasks": {
274
- const { client: c } = requireAgent(deps);
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 };
@@ -297,7 +317,7 @@ export async function dispatch(cli: ParsedCli, deps: DispatchDeps): Promise<Disp
297
317
  scope: required("scope"),
298
318
  check: required("check"),
299
319
  paths,
300
- branch: str(cli.options.branch) ?? "main",
320
+ branch: str(cli.options.branch) ?? "minga",
301
321
  force: cli.options.force === true,
302
322
  url: str(cli.options.url),
303
323
  }),
package/src/cli/init.ts CHANGED
@@ -62,7 +62,8 @@ export function renderProjectToml(input: TomlInput): string {
62
62
  `check = ${tomlBasicString(input.check)}`,
63
63
  `paths = [${paths}]`,
64
64
  `head = ${tomlBasicString(input.head)}`,
65
- `branch = ${tomlBasicString(input.branch ?? "main")}`,
65
+ "# Accepted work is committed here. Keep it a branch nobody has checked out; serve creates it.",
66
+ `branch = ${tomlBasicString(input.branch ?? "minga")}`,
66
67
  "",
67
68
  "[rules]",
68
69
  "# width = 3",
@@ -29,20 +29,21 @@ 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
- ` max attempts ${project.rules.maxAttemptsPerAgent}, default points ${project.rules.defaultPoints},` +
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",
36
- ` git clone ${base}/repo.git work && cd work`,
36
+ ` git clone -b ${project.branch ?? "main"} ${base}/repo.git work && cd work`,
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 the project's check command locally before submitting.",
40
+ " through submit. Run minga check <file...> before submitting.",
41
41
  "",
42
- "GET THE KIT (non-interactive; pick either form)",
43
- " npx -y minga-swarm@latest <cmd>",
44
- ` curl -fsSL ${base}/kit/minga.mjs -o minga.mjs && node minga.mjs <cmd>`,
45
- " `minga` below means either form. From inside the checkout, start with:",
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 safe leftovers)",
54
- " Refuses unrelated local changes unless you pass --discard.",
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, or:",
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 sync, minga help. Server: ${base}`,
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,9 +34,10 @@ agent commands
34
34
  board
35
35
  tasks [--open]
36
36
  sync [--discard]
37
+ check <file...>
37
38
 
38
39
  maintainer commands
39
- init [dir] --name <n> --goal <g> --scope <s> --check <cmd> --paths <glob[,glob...>] [--branch main] [--force]
40
+ init [dir] --name <n> --goal <g> --scope <s> --check <cmd> --paths <glob[,glob...>] [--branch minga] [--force]
40
41
  serve [--repo <dir>] [--port 7777] [--host 127.0.0.1] [server flags...]
41
42
  doctor [--repo <dir>]
42
43
  mcp [--dir <dir>]
@@ -111,7 +112,13 @@ 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.`,
114
- init: `usage: minga init [dir] --name <n> --goal <g> --scope <s> --check <cmd> --paths <glob[,glob...>] [--branch main] [--force]
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.`,
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
117
124
  .minga/ to .gitignore. dir must already be a git repository. --force overwrites
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;
@@ -99,7 +99,7 @@ export function packageVersion(root: string | null = findPackageRoot()): string
99
99
  // fall through
100
100
  }
101
101
  }
102
- return "0.1.1";
102
+ return "0.1.3";
103
103
  }
104
104
 
105
105
  function parseVersion(text: string): [number, number, number] | null {
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
- /** Discard every local change, including files that look unrelated. */
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 {
@@ -65,6 +69,14 @@ function parseStatus(text: string): Change[] {
65
69
  }
66
70
 
67
71
  function branchOf(run: GitRunner): string {
72
+ try {
73
+ // A clone made with -b <branch> tracks origin/<branch>: follow that first.
74
+ const upstream = run(["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{u}"]).trim();
75
+ const match = /^origin\/(.+)$/.exec(upstream);
76
+ if (match?.[1]) return match[1];
77
+ } catch {
78
+ // Detached HEAD or no upstream: fall back to origin/HEAD.
79
+ }
68
80
  try {
69
81
  const ref = run(["symbolic-ref", "--quiet", "refs/remotes/origin/HEAD"]).trim();
70
82
  const match = /^refs\/remotes\/origin\/(.+)$/.exec(ref);
@@ -131,19 +143,42 @@ export function syncCommand(input: SyncInput): CommandResult<SyncData> {
131
143
  if (data.conflicting.length > 0 && input.discard !== true) {
132
144
  data.refused = true;
133
145
  const lines = [
134
- `refusing to sync: local changes are not this agent's leftovers:`,
146
+ `refusing to sync: these local changes are not on the branch and were not in your last accepted submission:`,
135
147
  ...data.conflicting.map((path) => ` ${path}`),
136
- 're-run "minga sync --discard" to discard them, or move them aside first',
148
+ '"minga sync --discard" moves them to .minga/stash/ first, then syncs',
137
149
  ];
138
150
  return { text: lines.join("\n"), data };
139
151
  }
140
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
+
141
168
  if (data.discarded.length > 0) {
142
169
  run(["reset", "--hard", remote]);
143
170
  run(["clean", "-fd", "--", ...data.discarded]);
144
171
  }
145
172
  data.synced = true;
146
- const discarded = data.discarded.join(", ");
147
- const text = `synced to ${remote}; discarded ${data.discarded.length} path(s): ${discarded}`;
148
- return { text: input.discard === true && data.conflicting.length > 0 ? `${text} (--discard)` : text, data };
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 };
149
184
  }
@@ -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 = {
@@ -47,6 +47,8 @@ export interface ProjectInfo {
47
47
  paths: string[];
48
48
  headAgent: AgentId;
49
49
  rules: Rules;
50
+ /** The branch accepted work lands on; clone it with `git clone -b <branch> <url>/repo.git`. */
51
+ branch?: string;
50
52
  }
51
53
 
52
54
  /**
@@ -97,6 +99,25 @@ export type ViewTask = Omit<TaskState, "attempts" | "notes"> & { attemptCount: n
97
99
  * With wait (max 30), the server holds the request until the submission is final
98
100
  * (accepted or rejected) or the wait elapses, then answers with its current state.
99
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
+
100
121
  export interface SubmissionView extends SubmissionState {
101
122
  /** Present once checked. */
102
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
  ]);
@@ -133,7 +133,7 @@ export function createApp(deps: AppDeps) {
133
133
  // ---------------------------------------------------------------- helpers
134
134
  const leaseUntil = () => new Date(now().getTime() + state.rules.leaseMinutes * 60_000).toISOString();
135
135
  const projectInfo = (): ProjectInfo => ({
136
- name: cfg.name, goal: cfg.goal, scope: cfg.scope, check: cfg.check, paths: cfg.paths, headAgent: headId, rules: state.rules,
136
+ name: cfg.name, goal: cfg.goal, scope: cfg.scope, check: cfg.check, paths: cfg.paths, headAgent: headId, rules: state.rules, branch: cfg.branch,
137
137
  });
138
138
  const json = (data: unknown, status = 200) => Response.json(data, { status });
139
139
  const fail = (status: number, error: string, detail?: string) => json({ error, ...(detail ? { detail } : {}) } satisfies ErrorBody, status);
@@ -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) throw new HttpError(410, `attempt ${id} already ended (${at.endReason})`);
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" : url.pathname;
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;
@@ -29,6 +29,7 @@ const { values } = parseArgs({
29
29
  "check-concurrency": { type: "string" },
30
30
  "join-limit": { type: "string", default: "20" },
31
31
  "dry-run": { type: "boolean", default: false },
32
+ "allow-checked-out": { type: "boolean", default: false },
32
33
  },
33
34
  });
34
35
 
@@ -54,7 +55,29 @@ let head: string;
54
55
  try {
55
56
  head = await branchHead(repoDir, cfg.branch);
56
57
  } catch {
57
- die(`branch ${cfg.branch} does not exist in ${repoDir}`, `commit something on ${cfg.branch}, or set branch = "..." in project.toml`);
58
+ // A missing project branch starts at the current commit (init picks a dedicated "minga" branch).
59
+ const start = Bun.spawnSync(["git", "-C", repoDir, "rev-parse", "--verify", "--quiet", "HEAD^{commit}"]);
60
+ const startSha = start.stdout.toString().trim();
61
+ if (start.exitCode !== 0 || startSha === "") {
62
+ die(`branch ${cfg.branch} does not exist in ${repoDir} and there is no commit to start it from`, "commit something first");
63
+ }
64
+ if (!values["dry-run"]) {
65
+ const made = Bun.spawnSync(["git", "-C", repoDir, "update-ref", `refs/heads/${cfg.branch}`, startSha, ""]);
66
+ if (made.exitCode !== 0) die(`cannot create branch ${cfg.branch}: ${made.stderr.toString().trim()}`);
67
+ console.log(`minga: created branch ${cfg.branch} at ${startSha.slice(0, 12)}; accepted work lands there (merge it whenever you like)`);
68
+ }
69
+ head = startSha;
70
+ }
71
+
72
+ // Accepted commits move the branch ref directly. If that branch is checked out, the
73
+ // working tree and index fall behind it and the next "git commit -a" there silently
74
+ // reverts the agents' work, so refuse unless told otherwise.
75
+ const checkedOut = checkedOutIn(repoDir, cfg.branch);
76
+ if (checkedOut !== null && !values["allow-checked-out"]) {
77
+ die(
78
+ `branch ${cfg.branch} is checked out in ${checkedOut}; accepted commits would move it under that working tree`,
79
+ `set branch = "minga" in project.toml (serve creates it), check out another branch there, or pass --allow-checked-out`,
80
+ );
58
81
  }
59
82
  const concurrency = values["check-concurrency"] !== undefined
60
83
  ? Math.max(1, Number(values["check-concurrency"]) || 1)
@@ -70,6 +93,18 @@ if (values["dry-run"]) {
70
93
  process.exit(0);
71
94
  }
72
95
 
96
+ /** The worktree path that has `branch` checked out, or null. Check-pool worktrees are detached. */
97
+ function checkedOutIn(repo: string, branch: string): string | null {
98
+ const list = Bun.spawnSync(["git", "-C", repo, "worktree", "list", "--porcelain"]);
99
+ if (list.exitCode !== 0) return null;
100
+ let path: string | null = null;
101
+ for (const line of list.stdout.toString().split(/\r?\n/)) {
102
+ if (line.startsWith("worktree ")) path = line.slice("worktree ".length);
103
+ else if (line === `branch refs/heads/${branch}` && path !== null) return path;
104
+ }
105
+ return null;
106
+ }
107
+
73
108
  const LOOPBACK = new Set(["127.0.0.1", "localhost", "::1"]);
74
109
  if (!LOOPBACK.has(values.host!)) {
75
110
  console.warn(