minga-swarm 0.1.0 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/minga.mjs CHANGED
@@ -124,6 +124,9 @@ var COMMAND_OPTIONS = {
124
124
  vote: {},
125
125
  status: {},
126
126
  board: {},
127
+ tasks: {
128
+ open: { type: "boolean" }
129
+ },
127
130
  init: {
128
131
  name: { type: "string" },
129
132
  goal: { type: "string" },
@@ -136,6 +139,9 @@ var COMMAND_OPTIONS = {
136
139
  doctor: {
137
140
  repo: { type: "string" }
138
141
  },
142
+ sync: {
143
+ discard: { type: "boolean" }
144
+ },
139
145
  mcp: {}
140
146
  };
141
147
  var HEAD_OPTIONS = {
@@ -153,6 +159,9 @@ var HEAD_OPTIONS = {
153
159
  ban: {
154
160
  reason: { type: "string" }
155
161
  },
162
+ note: {
163
+ kind: { type: "string" }
164
+ },
156
165
  close: {
157
166
  reason: { type: "string" }
158
167
  }
@@ -329,18 +338,23 @@ async function joinCommand(client, input) {
329
338
  `${response.rejoin ? "rejoined" : "joined"} ${response.project.name} as agent ${response.agent}`,
330
339
  `goal: ${response.project.goal}`,
331
340
  `scope: ${response.project.scope}`,
332
- `rules: ${formatRules(response.project.rules)}`
341
+ `rules: ${formatRules(response.project.rules)}`,
342
+ "",
343
+ `get the code: git clone ${input.url.replace(/\/+$/, "")}/repo.git work && cd work`,
344
+ "run minga from inside that checkout; submit reads files relative to cwd"
333
345
  ];
334
346
  if (response.live.length > 0)
335
347
  lines.push(`live attempts from before: ${response.live.join(", ")}`);
336
348
  return { identity, result: { text: lines.join(`
337
349
  `), data: response } };
338
350
  }
339
- function formatAssignment(a) {
351
+ function formatAssignment(a, headAgent) {
352
+ const headMark = (agent) => headAgent !== undefined && agent === headAgent ? "head: " : "";
340
353
  const lines = [
341
354
  `attempt ${a.attempt}`,
342
355
  `role ${a.role}`,
343
356
  `lease ${a.leaseUntil}`,
357
+ ...a.head ? [`head ${a.head.slice(0, 7)} (minga sync if your checkout is older)`] : [],
344
358
  `task ${a.task.id} ${a.task.title} (${a.task.points} points)`
345
359
  ];
346
360
  if (a.path.length > 0) {
@@ -348,12 +362,13 @@ function formatAssignment(a) {
348
362
  }
349
363
  lines.push("body:", indent(a.task.body.length > 0 ? a.task.body : "(empty)"));
350
364
  if (a.handoff) {
351
- lines.push(`handoff ${a.handoff.id} (${a.handoff.kind}) ${a.handoff.text}`);
365
+ lines.push(`handoff ${a.handoff.id} ${headMark(a.handoff.agent)}(${a.handoff.kind}) ${a.handoff.text}`);
352
366
  }
353
367
  if (a.notes.length > 0) {
354
368
  lines.push("notes:");
355
- for (const note of a.notes)
356
- lines.push(` ${note.id} ${note.agent} ${note.kind}: ${note.text}`);
369
+ for (const note of a.notes) {
370
+ lines.push(` ${note.id} ${headMark(note.agent)}${note.agent} ${note.kind}: ${note.text}`);
371
+ }
357
372
  }
358
373
  if (a.others.length > 0) {
359
374
  lines.push("others on this task:");
@@ -380,10 +395,23 @@ async function nextCommand(client, input = {}) {
380
395
  ...input.approach !== undefined ? { approach: input.approach } : {},
381
396
  ...chunk > 0 ? { wait: chunk } : {}
382
397
  });
383
- if (response.assignment)
384
- return { text: formatAssignment(response.assignment), data: response };
398
+ if (response.done === true) {
399
+ return { text: "the project has no open tasks left. Stop here.", data: response };
400
+ }
401
+ if (response.assignment) {
402
+ let headAgent;
403
+ if (response.assignment.notes.length > 0 || response.assignment.handoff) {
404
+ try {
405
+ headAgent = (await client.project()).headAgent;
406
+ } catch {}
407
+ }
408
+ return { text: formatAssignment(response.assignment, headAgent), data: response };
409
+ }
385
410
  last = response;
386
- input.onProgress?.(`waiting for a task (retry in ${response.retryAfterSeconds ?? 60}s)`);
411
+ if (chunk > 0) {
412
+ const left = Math.max(0, Math.ceil(total - (Date.now() - started) / 1000));
413
+ input.onProgress?.(`no free task yet; waiting (${left}s left)`);
414
+ }
387
415
  if (total === 0 || chunk <= 0)
388
416
  break;
389
417
  if (Date.now() - t0 < 50) {
@@ -395,10 +423,19 @@ async function nextCommand(client, input = {}) {
395
423
  }
396
424
  const wait = last?.retryAfterSeconds ?? 60;
397
425
  return {
398
- text: `nothing to do, retry in ${wait}s`,
426
+ text: total === 0 ? 'nothing to do right now; run "minga next --wait 600" to wait for a task' : `nothing to do, retry in ${wait}s`,
399
427
  data: last ?? { assignment: null, retryAfterSeconds: wait }
400
428
  };
401
429
  }
430
+ var SUBMIT_MESSAGE_MAX = 200;
431
+ function fitSubmitMessage(message) {
432
+ if (message.length <= SUBMIT_MESSAGE_MAX)
433
+ return { message };
434
+ const first = message.split(`
435
+ `)[0] ?? "";
436
+ const fitted = first.length > SUBMIT_MESSAGE_MAX ? `${first.slice(0, SUBMIT_MESSAGE_MAX - 3)}...` : first;
437
+ return { message: fitted, notice: `submit message over ${SUBMIT_MESSAGE_MAX} chars; using "${fitted}"` };
438
+ }
402
439
  function readSubmissionFiles(root, files) {
403
440
  const resolvedRoot = resolve(root);
404
441
  const out = {};
@@ -419,20 +456,32 @@ function isFinal(status) {
419
456
  }
420
457
  async function waitForSubmission(client, id, onProgress, initialStatus = "queued") {
421
458
  let lastStatus = initialStatus;
459
+ let lastRuns = 0;
422
460
  for (let i = 0;i < 1000; i++) {
423
461
  const view = await client.submission(id, 30);
424
- if (view.status !== lastStatus) {
425
- lastStatus = view.status;
426
- if (view.status === "checking")
427
- onProgress?.(`checking ${id}`);
462
+ const changed = view.status !== lastStatus || view.runs !== lastRuns;
463
+ lastStatus = view.status;
464
+ lastRuns = view.runs;
465
+ if (view.status === "checking" && changed) {
466
+ onProgress?.(`checking ${id} (run ${view.runs})`);
428
467
  }
429
- if (isFinal(view.status)) {
430
- onProgress?.(`verdict ${view.status} ${id}`);
468
+ if (isFinal(view.status))
431
469
  return view;
432
- }
470
+ if (!changed)
471
+ await new Promise((resolve) => setTimeout(resolve, 250));
433
472
  }
434
473
  throw new Error(`submission ${id} has no verdict yet; check it with "minga result ${id}"`);
435
474
  }
475
+ function staleReason(view) {
476
+ if (!("stale" in view) || view.stale !== true)
477
+ return;
478
+ const tail = view.outputTail ?? "";
479
+ if (/branch kept moving/i.test(tail))
480
+ return "the branch kept moving";
481
+ if (/\bclosed\b/i.test(tail))
482
+ return "the task closed first";
483
+ return "unknown reason";
484
+ }
436
485
  function renderSubmission(view) {
437
486
  const id = "submission" in view ? view.submission : view.id;
438
487
  if (view.status === "queued") {
@@ -440,17 +489,33 @@ function renderSubmission(view) {
440
489
  return `submission ${id}: queued${position}`;
441
490
  }
442
491
  const lines = [];
443
- if (view.status === "checking")
492
+ if (view.status === "checking") {
444
493
  lines.push(`submission ${id}: checking`);
445
- else
446
- lines.push(`verdict: ${view.status}`, `submission ${id}`);
447
- lines.push(`exit code: ${view.exitCode ?? 0}${view.timedOut ? " (timed out)" : ""}`);
494
+ return lines.join(`
495
+ `);
496
+ }
497
+ const attempt = "attempt" in view ? view.attempt : id;
498
+ const exitCode = view.exitCode ?? 0;
499
+ lines.push(`verdict: ${view.status}`, `submission ${id}`);
500
+ lines.push(`exit code: ${exitCode}${view.timedOut ? " (timed out)" : ""}`);
501
+ if (view.status === "rejected") {
502
+ const reason = staleReason(view);
503
+ if (reason !== undefined)
504
+ lines.push(`stale: ${reason}`);
505
+ }
448
506
  if (view.outputTail && view.outputTail.length > 0) {
449
507
  lines.push("output tail:", indent(view.outputTail));
508
+ } else if (view.status === "rejected") {
509
+ lines.push(`output: (the check printed nothing; exit code ${exitCode})`);
450
510
  }
451
511
  if (view.commit !== undefined)
452
512
  lines.push(`commit: ${view.commit}`);
453
513
  lines.push(`points: ${view.points}`);
514
+ if (view.status === "accepted") {
515
+ lines.push("next: minga sync && minga next --wait 600");
516
+ } else if (view.status === "rejected") {
517
+ lines.push(`next: fix and run "minga submit ${attempt} ..." again, or ` + `"minga release ${attempt} --handoff \\"...\\""`);
518
+ }
454
519
  return lines.join(`
455
520
  `);
456
521
  }
@@ -468,10 +533,10 @@ async function submitCommand(client, input) {
468
533
  files,
469
534
  ...input.model !== undefined ? { model: input.model } : {}
470
535
  });
471
- const progress = `queued ${queued.submission} #${queued.position}`;
536
+ const progress = `queued ${queued.submission} (#${queued.position} in line)`;
472
537
  input.onProgress?.(progress);
473
538
  if (input.wait === false)
474
- return { text: progress, data: queued };
539
+ return { text: renderSubmission(queued), data: queued };
475
540
  const final = await waitForSubmission(client, queued.submission, input.onProgress);
476
541
  return { text: renderSubmission(final), data: final };
477
542
  }
@@ -542,19 +607,41 @@ async function voteCommand(client, input) {
542
607
  return { text: lines.join(`
543
608
  `), data: response };
544
609
  }
545
- async function statusCommand(client, agent) {
610
+ function leaseText(leaseUntil) {
611
+ const ms = Date.parse(leaseUntil) - Date.now();
612
+ if (!Number.isFinite(ms))
613
+ return leaseUntil;
614
+ return ms > 0 ? `${Math.ceil(ms / 60000)}m left` : "expired";
615
+ }
616
+ async function statusCommand(client, identity) {
546
617
  const project = await client.project();
547
- const text = [
618
+ const data = { agent: identity.agent, project };
619
+ const lines = [
548
620
  `project: ${project.name}`,
549
621
  `goal: ${project.goal}`,
550
622
  `scope: ${project.scope}`,
551
623
  `check: ${project.check}`,
552
624
  `paths: ${project.paths.join(", ")}`,
553
625
  `rules: ${formatRules(project.rules)}`,
554
- `your agent: ${agent}`
555
- ].join(`
556
- `);
557
- return { text, data: { agent, project } };
626
+ `your agent: ${identity.agent}`
627
+ ];
628
+ const assignment = identity.lastAssignment;
629
+ if (assignment) {
630
+ lines.push(`attempt: ${assignment.attempt} (${assignment.role}) on ${assignment.task} — ` + `lease ${leaseText(assignment.leaseUntil)}`);
631
+ data.assignment = assignment;
632
+ }
633
+ if (identity.lastSubmission) {
634
+ try {
635
+ const view = await client.submission(identity.lastSubmission, 0);
636
+ const position = view.status === "queued" && view.position !== undefined ? ` #${view.position}` : "";
637
+ lines.push(`submission: ${view.id} ${view.status}${position}`);
638
+ data.submission = view;
639
+ } catch {
640
+ lines.push(`submission: ${identity.lastSubmission} (unavailable)`);
641
+ }
642
+ }
643
+ return { text: lines.join(`
644
+ `), data };
558
645
  }
559
646
  async function boardCommand(client) {
560
647
  const leaderboard = await client.leaderboard();
@@ -574,6 +661,49 @@ async function boardCommand(client) {
574
661
  `);
575
662
  return { text, data: leaderboard };
576
663
  }
664
+ function tasksCommand(client, input = {}) {
665
+ return client.tasks().then((overview) => ({ text: renderTasks(overview, input), data: overview }));
666
+ }
667
+ function renderTaskLine(task, depth = 0, area = false) {
668
+ const status = task.status === "open" && task.live > 0 ? `open · ${task.live} live` : task.status;
669
+ const line = `${task.id} ${status.padEnd(10)} ${task.points} pts ${task.title}${area ? " [area]" : ""}`;
670
+ return `${" ".repeat(depth)}${line}`;
671
+ }
672
+ function renderTasks(overview, input = {}) {
673
+ const byId = new Map(overview.tasks.map((t) => [t.id, t]));
674
+ const children = new Map;
675
+ for (const t of overview.tasks) {
676
+ const parent = t.parent && byId.has(t.parent) ? t.parent : null;
677
+ const list = children.get(parent) ?? [];
678
+ list.push(t);
679
+ children.set(parent, list);
680
+ }
681
+ const lines = [];
682
+ const seen = new Set;
683
+ const visit = (parent, depth) => {
684
+ for (const t of children.get(parent) ?? []) {
685
+ if (seen.has(t.id))
686
+ continue;
687
+ seen.add(t.id);
688
+ if (!input.openOnly || t.status === "open") {
689
+ lines.push(renderTaskLine(t, depth, byId.get(t.id)?.leaf === false));
690
+ }
691
+ visit(t.id, depth + 1);
692
+ }
693
+ };
694
+ visit(null, 0);
695
+ for (const t of overview.tasks) {
696
+ if (!seen.has(t.id)) {
697
+ seen.add(t.id);
698
+ if (!input.openOnly || t.status === "open") {
699
+ lines.push(renderTaskLine(t, 0, !t.leaf));
700
+ }
701
+ }
702
+ }
703
+ const footer = overview.done ? "project finished" : `open leaf tasks: ${overview.open}`;
704
+ return lines.length > 0 ? [...lines, "", footer].join(`
705
+ `) : footer;
706
+ }
577
707
  function headKeygenCommand(existing, url) {
578
708
  const keys = existing ? { publicKey: existing.publicKey, privateKey: existing.privateKey } : generateKeyPair();
579
709
  const identity = {
@@ -625,6 +755,17 @@ async function headBanCommand(client, input) {
625
755
  const response = await client.headBan({ agent: input.agent, reason: input.reason });
626
756
  return { text: `banned ${input.agent}`, data: response };
627
757
  }
758
+ async function headNoteCommand(client, input) {
759
+ const response = await client.headNote({
760
+ task: input.task,
761
+ text: input.text,
762
+ ...input.kind !== undefined ? { kind: input.kind } : {}
763
+ });
764
+ return {
765
+ text: `note ${response.note.id} on ${input.task} (${response.note.kind})`,
766
+ data: response
767
+ };
768
+ }
628
769
  async function headCloseCommand(client, input) {
629
770
  const response = await client.headClose({
630
771
  task: input.task,
@@ -678,6 +819,7 @@ function createClient(baseUrl, keys, fetchImpl = fetch) {
678
819
  return send("GET", `/api/events?${query}`);
679
820
  },
680
821
  leaderboard: () => send("GET", "/api/leaderboard"),
822
+ tasks: () => send("GET", "/api/tasks"),
681
823
  submission: (id, waitSeconds = 0) => {
682
824
  const wait = Math.max(0, Math.min(30, Math.floor(waitSeconds)));
683
825
  const query = wait > 0 ? `?wait=${wait}` : "";
@@ -695,6 +837,7 @@ function createClient(baseUrl, keys, fetchImpl = fetch) {
695
837
  headDecide: (body) => send("POST", "/api/head/decide", body),
696
838
  headRule: (body) => send("POST", "/api/head/rule", body),
697
839
  headBan: (body) => send("POST", "/api/head/ban", body),
840
+ headNote: (body) => send("POST", "/api/head/note", body),
698
841
  headClose: (body) => send("POST", "/api/head/close", body)
699
842
  };
700
843
  }
@@ -729,7 +872,7 @@ function findPackageRoot(fromUrl = import.meta.url) {
729
872
  if (existsSync(file)) {
730
873
  try {
731
874
  const value = JSON.parse(readFileSync2(file, "utf8"));
732
- if (value.name === "minga-swarm" || value.name === "minga")
875
+ if (value.name === "minga-swarm" || (value.name === "minga-swarm" || value.name === "minga"))
733
876
  return dir;
734
877
  } catch {}
735
878
  }
@@ -747,7 +890,7 @@ function packageVersion(root = findPackageRoot()) {
747
890
  return value.version;
748
891
  } catch {}
749
892
  }
750
- return "0.1.0";
893
+ return "0.1.2";
751
894
  }
752
895
  function parseVersion(text) {
753
896
  const match = /(\d+)\.(\d+)\.(\d+)/.exec(text);
@@ -859,6 +1002,29 @@ async function serveCommand(raw, deps = {}) {
859
1002
  // src/cli/doctor.ts
860
1003
  import { existsSync as existsSync2 } from "node:fs";
861
1004
  import { join as join2, resolve as resolve2 } from "node:path";
1005
+ function dryRunError(raw) {
1006
+ try {
1007
+ const parsed = JSON.parse(raw);
1008
+ if (parsed && typeof parsed.error === "string" && parsed.error.length > 0) {
1009
+ return parsed.fix ? `${parsed.error} (fix: ${parsed.fix})` : parsed.error;
1010
+ }
1011
+ } catch {}
1012
+ return null;
1013
+ }
1014
+ function dryRunDetail(raw) {
1015
+ let parsed;
1016
+ try {
1017
+ parsed = JSON.parse(raw);
1018
+ } catch {
1019
+ return null;
1020
+ }
1021
+ const info = parsed?.project;
1022
+ if (!info || typeof info !== "object")
1023
+ return null;
1024
+ const sha = typeof info.head === "string" && info.head.length > 0 ? info.head.slice(0, 7) : "unknown";
1025
+ const slots = typeof parsed.checkConcurrency === "number" && parsed.checkConcurrency > 0 ? parsed.checkConcurrency : 1;
1026
+ return `${info.name ?? "project"}: check "${info.check ?? ""}", branch ${info.branch ?? "?"} @ ${sha}, ` + `${slots} check slot(s), recheck ${info.recheck ?? "?"}`;
1027
+ }
862
1028
  function doctorCommand(input, deps = {}) {
863
1029
  const runner = deps.syncRunner ?? defaultSyncRunner;
864
1030
  const checks = [];
@@ -892,6 +1058,7 @@ function doctorCommand(input, deps = {}) {
892
1058
  detail: `${tomlPath} is missing`,
893
1059
  fix: `minga init ${repoDir} --name "<name>" --goal "<goal>" --scope "<scope>" --check "<check>" --paths "<glob>"`
894
1060
  });
1061
+ let configDryRun;
895
1062
  if (bun.ok) {
896
1063
  const root = input.packageRoot === undefined ? deps.packageRoot === undefined ? findPackageRoot() : deps.packageRoot : input.packageRoot;
897
1064
  if (root === null) {
@@ -904,7 +1071,16 @@ function doctorCommand(input, deps = {}) {
904
1071
  } else {
905
1072
  const worker = join2(root, "src", "server", "main.ts");
906
1073
  const dry = runner(deps.bunPath ?? "bun", [worker, "--repo", repoDir, "--dry-run"]);
907
- const detail = dry.stdout.trim() || dry.stderr.trim() || `exit ${dry.status}`;
1074
+ const raw = dry.stdout.trim() || dry.stderr.trim() || `exit ${dry.status}`;
1075
+ const compact = dry.status === 0 ? dryRunDetail(raw) : null;
1076
+ if (compact !== null) {
1077
+ try {
1078
+ configDryRun = JSON.parse(raw);
1079
+ } catch {}
1080
+ }
1081
+ const firstLine = raw.split(`
1082
+ `)[0] ?? raw;
1083
+ const detail = compact ?? (dry.status === 0 ? firstLine : dryRunError(raw) ?? firstLine);
908
1084
  add(dry.status === 0 ? { name: "config", ok: true, detail } : { name: "config", ok: false, detail, fix: "fix project.toml and re-run minga doctor" });
909
1085
  }
910
1086
  }
@@ -915,15 +1091,18 @@ function doctorCommand(input, deps = {}) {
915
1091
  ...check.fix !== undefined && !check.ok ? [`(fix: ${check.fix})`] : []
916
1092
  ].join(" ")).join(`
917
1093
  `);
918
- return { text, data: { checks } };
1094
+ return {
1095
+ text,
1096
+ data: configDryRun === undefined ? { checks } : { checks, configDryRun }
1097
+ };
919
1098
  }
920
1099
 
921
1100
  // src/cli/init.ts
922
- import { existsSync as existsSync3, readFileSync as readFileSync4, writeFileSync as writeFileSync2 } from "node:fs";
1101
+ import { existsSync as existsSync4, readFileSync as readFileSync4, writeFileSync as writeFileSync2 } from "node:fs";
923
1102
  import { join as join4, resolve as resolve4 } from "node:path";
924
1103
 
925
1104
  // src/cli/store.ts
926
- import { chmodSync, mkdirSync, readFileSync as readFileSync3, writeFileSync } from "node:fs";
1105
+ import { chmodSync, existsSync as existsSync3, mkdirSync, readFileSync as readFileSync3, writeFileSync } from "node:fs";
927
1106
  import { dirname as dirname2, join as join3, resolve as resolve3 } from "node:path";
928
1107
  var MINGA_DIR = ".minga";
929
1108
  function readText(path) {
@@ -979,8 +1158,20 @@ function agentPath(dir) {
979
1158
  function headPath(dir) {
980
1159
  return join3(dir, MINGA_DIR, "head.json");
981
1160
  }
1161
+ function resolveAgentDir(dir) {
1162
+ const start = resolveDir(dir);
1163
+ let current = start;
1164
+ for (;; ) {
1165
+ if (existsSync3(agentPath(current)))
1166
+ return current;
1167
+ const parent = dirname2(current);
1168
+ if (parent === current)
1169
+ return start;
1170
+ current = parent;
1171
+ }
1172
+ }
982
1173
  function readAgent(dir) {
983
- const path = agentPath(dir);
1174
+ const path = agentPath(resolveAgentDir(dir));
984
1175
  const obj = readObject(path);
985
1176
  if (!obj)
986
1177
  return null;
@@ -995,6 +1186,29 @@ function readAgent(dir) {
995
1186
  const owner = optionalString(obj, "owner");
996
1187
  if (owner !== undefined)
997
1188
  identity.owner = owner;
1189
+ const raw = obj.lastAssignment;
1190
+ if (raw && typeof raw === "object" && !Array.isArray(raw)) {
1191
+ const a = raw;
1192
+ const attempt = optionalString(a, "attempt");
1193
+ const role = optionalString(a, "role");
1194
+ const leaseUntil = optionalString(a, "leaseUntil");
1195
+ const task = optionalString(a, "task");
1196
+ if (attempt && role && leaseUntil && task) {
1197
+ identity.lastAssignment = { attempt, role, leaseUntil, task };
1198
+ }
1199
+ }
1200
+ const lastSubmission = optionalString(obj, "lastSubmission");
1201
+ if (lastSubmission !== undefined)
1202
+ identity.lastSubmission = lastSubmission;
1203
+ const accepted = obj.lastAccepted;
1204
+ if (accepted && typeof accepted === "object" && !Array.isArray(accepted)) {
1205
+ const entry = accepted;
1206
+ const submission = optionalString(entry, "submission");
1207
+ const files = entry.files;
1208
+ if (submission && Array.isArray(files) && files.every((f) => typeof f === "string")) {
1209
+ identity.lastAccepted = { submission, files };
1210
+ }
1211
+ }
998
1212
  return identity;
999
1213
  }
1000
1214
  function writeAgent(dir, identity) {
@@ -1008,6 +1222,12 @@ function writeAgent(dir, identity) {
1008
1222
  };
1009
1223
  if (identity.owner !== undefined)
1010
1224
  value.owner = identity.owner;
1225
+ if (identity.lastAssignment !== undefined)
1226
+ value.lastAssignment = identity.lastAssignment;
1227
+ if (identity.lastSubmission !== undefined)
1228
+ value.lastSubmission = identity.lastSubmission;
1229
+ if (identity.lastAccepted !== undefined)
1230
+ value.lastAccepted = identity.lastAccepted;
1011
1231
  return writeObject(agentPath(dir), value);
1012
1232
  }
1013
1233
  function readHead(dir) {
@@ -1051,15 +1271,17 @@ function renderProjectToml(input) {
1051
1271
  `check = ${tomlBasicString(input.check)}`,
1052
1272
  `paths = [${paths}]`,
1053
1273
  `head = ${tomlBasicString(input.head)}`,
1054
- `branch = ${tomlBasicString(input.branch ?? "main")}`,
1274
+ "# Accepted work is committed here. Keep it a branch nobody has checked out; serve creates it.",
1275
+ `branch = ${tomlBasicString(input.branch ?? "minga")}`,
1055
1276
  "",
1056
- "# [rules]",
1277
+ "[rules]",
1057
1278
  "# width = 3",
1058
1279
  "# lease_minutes = 45",
1059
1280
  "# max_attempts_per_agent = 1",
1060
1281
  "# default_points = 10",
1061
1282
  '# accept = "head-or-votes:3"',
1062
- "# [rules.roles]",
1283
+ "",
1284
+ "[rules.roles]",
1063
1285
  "# explore = 2",
1064
1286
  "# build = 5",
1065
1287
  "# attack = 2",
@@ -1076,11 +1298,11 @@ function renderProjectToml(input) {
1076
1298
  }
1077
1299
  function initCommand(input) {
1078
1300
  const dir = resolve4(input.dir);
1079
- if (!existsSync3(join4(dir, ".git"))) {
1301
+ if (!existsSync4(join4(dir, ".git"))) {
1080
1302
  throw new Error(`${dir} is not a git repository; run "git init ${dir}" first`);
1081
1303
  }
1082
1304
  const tomlPath = join4(dir, "project.toml");
1083
- if (existsSync3(tomlPath) && input.force !== true) {
1305
+ if (existsSync4(tomlPath) && input.force !== true) {
1084
1306
  throw new Error(`${tomlPath} already exists; pass --force to overwrite it`);
1085
1307
  }
1086
1308
  const { identity, result } = headKeygenCommand(readHead(dir), input.url);
@@ -1088,7 +1310,7 @@ function initCommand(input) {
1088
1310
  const projectToml = renderProjectToml({ ...input, head: result.data.head });
1089
1311
  writeFileSync2(tomlPath, projectToml, "utf8");
1090
1312
  const gitignore = join4(dir, ".gitignore");
1091
- const current = existsSync3(gitignore) ? readFileSync4(gitignore, "utf8") : "";
1313
+ const current = existsSync4(gitignore) ? readFileSync4(gitignore, "utf8") : "";
1092
1314
  const hasIgnore = current.split(/\r?\n/).some((line) => {
1093
1315
  const trimmed = line.trim();
1094
1316
  return trimmed === ".minga" || trimmed === ".minga/";
@@ -1117,6 +1339,123 @@ wrote `)}`,
1117
1339
  };
1118
1340
  }
1119
1341
 
1342
+ // src/cli/sync.ts
1343
+ 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";
1346
+ function firstLine(err) {
1347
+ const text = err instanceof Error ? err.message : String(err);
1348
+ return text.split(`
1349
+ `)[0] ?? text;
1350
+ }
1351
+ function parseStatus(text) {
1352
+ const changes = [];
1353
+ for (const line of text.split(/\r?\n/)) {
1354
+ if (line.length < 4)
1355
+ continue;
1356
+ const code = line.slice(0, 2);
1357
+ if (code === "!!")
1358
+ continue;
1359
+ let path = line.slice(3);
1360
+ if ((code.includes("R") || code.includes("C")) && path.includes(" -> ")) {
1361
+ path = path.slice(path.indexOf(" -> ") + 4);
1362
+ }
1363
+ if (path.startsWith('"') && path.endsWith('"'))
1364
+ path = path.slice(1, -1);
1365
+ if (path.length > 0)
1366
+ changes.push({ code, path });
1367
+ }
1368
+ return changes;
1369
+ }
1370
+ function branchOf(run) {
1371
+ try {
1372
+ const upstream = run(["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{u}"]).trim();
1373
+ const match = /^origin\/(.+)$/.exec(upstream);
1374
+ if (match?.[1])
1375
+ return match[1];
1376
+ } catch {}
1377
+ try {
1378
+ const ref = run(["symbolic-ref", "--quiet", "refs/remotes/origin/HEAD"]).trim();
1379
+ const match = /^refs\/remotes\/origin\/(.+)$/.exec(ref);
1380
+ if (match?.[1])
1381
+ return match[1];
1382
+ } catch {}
1383
+ return "main";
1384
+ }
1385
+ function headContent(run, branch, path) {
1386
+ try {
1387
+ return run(["show", `origin/${branch}:${path}`]);
1388
+ } catch {
1389
+ return null;
1390
+ }
1391
+ }
1392
+ function localContent(repoDir, path) {
1393
+ const absolute = resolve5(repoDir, path);
1394
+ if (!existsSync5(absolute))
1395
+ return null;
1396
+ try {
1397
+ return readFileSync5(absolute, "utf8");
1398
+ } catch {
1399
+ return null;
1400
+ }
1401
+ }
1402
+ function syncCommand(input) {
1403
+ const repoDir = resolve5(input.dir);
1404
+ const run = input.runner ?? ((args) => execFileSync("git", args, {
1405
+ cwd: repoDir,
1406
+ encoding: "utf8",
1407
+ stdio: ["ignore", "pipe", "pipe"]
1408
+ }));
1409
+ try {
1410
+ run(["fetch", "origin"]);
1411
+ } catch (err) {
1412
+ throw new Error(`git fetch origin failed: ${firstLine(err)}`);
1413
+ }
1414
+ const branch = branchOf(run);
1415
+ const remote = `origin/${branch}`;
1416
+ const changes = parseStatus(run(["status", "--porcelain"]));
1417
+ const accepted = readAgent(repoDir)?.lastAccepted?.files ?? [];
1418
+ const data = {
1419
+ branch,
1420
+ changed: changes.map((c) => c.path),
1421
+ discarded: [],
1422
+ conflicting: [],
1423
+ synced: false,
1424
+ refused: false
1425
+ };
1426
+ if (changes.length === 0) {
1427
+ return { text: `already on ${remote}; no local changes to sync`, data };
1428
+ }
1429
+ for (const change of changes) {
1430
+ const inHead = headContent(run, branch, change.path);
1431
+ const local = localContent(repoDir, change.path);
1432
+ const identical = inHead !== null && local !== null && inHead === local;
1433
+ const safe = identical || accepted.includes(change.path);
1434
+ if (!safe)
1435
+ data.conflicting.push(change.path);
1436
+ if (safe || input.discard === true)
1437
+ data.discarded.push(change.path);
1438
+ }
1439
+ if (data.conflicting.length > 0 && input.discard !== true) {
1440
+ data.refused = true;
1441
+ const lines = [
1442
+ `refusing to sync: local changes are not this agent's leftovers:`,
1443
+ ...data.conflicting.map((path) => ` ${path}`),
1444
+ 're-run "minga sync --discard" to discard them, or move them aside first'
1445
+ ];
1446
+ return { text: lines.join(`
1447
+ `), data };
1448
+ }
1449
+ if (data.discarded.length > 0) {
1450
+ run(["reset", "--hard", remote]);
1451
+ run(["clean", "-fd", "--", ...data.discarded]);
1452
+ }
1453
+ data.synced = true;
1454
+ const discarded = data.discarded.join(", ");
1455
+ const text = `synced to ${remote}; discarded ${data.discarded.length} path(s): ${discarded}`;
1456
+ return { text: input.discard === true && data.conflicting.length > 0 ? `${text} (--discard)` : text, data };
1457
+ }
1458
+
1120
1459
  // src/cli/dispatch.ts
1121
1460
  function str(value) {
1122
1461
  return typeof value === "string" && value.length > 0 ? value : undefined;
@@ -1142,15 +1481,22 @@ function client(url, keys, deps) {
1142
1481
  return createClient(url, keys, deps.fetchImpl ?? fetch);
1143
1482
  }
1144
1483
  function requireAgent(deps) {
1145
- const identity = readAgent(deps.dir);
1484
+ const identityDir = resolveAgentDir(deps.dir);
1485
+ const identity = readAgent(identityDir);
1146
1486
  if (!identity) {
1147
- throw new Error(`no agent identity at ${agentPath(deps.dir)}; run "minga join <url>" first`);
1487
+ throw new Error(`no agent identity at ${agentPath(identityDir)}; run "minga join <url>" first`);
1148
1488
  }
1149
1489
  return {
1150
1490
  identity,
1491
+ identityDir,
1151
1492
  client: client(deps.urlOverride ?? identity.url, identity, deps)
1152
1493
  };
1153
1494
  }
1495
+ function acceptedFiles(view) {
1496
+ if (!("id" in view) || view.status !== "accepted")
1497
+ return;
1498
+ return { submission: view.id, files: view.files };
1499
+ }
1154
1500
  function requireHeadClient(deps) {
1155
1501
  const identity = readHead(deps.dir);
1156
1502
  if (!identity) {
@@ -1176,7 +1522,8 @@ async function dispatch(cli, deps) {
1176
1522
  if (!model || !harness)
1177
1523
  throw new Error("join needs --model and --harness");
1178
1524
  const existing = readAgent(dir);
1179
- const keys = existing ? { publicKey: existing.publicKey, privateKey: existing.privateKey } : generateKeyPair();
1525
+ const reuse = existing !== null && existing.url === url;
1526
+ const keys = existing && reuse ? { publicKey: existing.publicKey, privateKey: existing.privateKey } : generateKeyPair();
1180
1527
  const { identity, result } = await joinCommand(client(url, keys, deps), {
1181
1528
  url,
1182
1529
  keys,
@@ -1184,18 +1531,30 @@ async function dispatch(cli, deps) {
1184
1531
  harness,
1185
1532
  owner: str(cli.options.owner)
1186
1533
  });
1187
- writeAgent(dir, identity);
1534
+ writeAgent(reuse ? resolveAgentDir(dir) : resolveDir(dir), identity);
1188
1535
  return { result, code: 0 };
1189
1536
  }
1190
1537
  case "next": {
1191
- const { identity, client: c } = requireAgent(deps);
1538
+ const { identity, identityDir, client: c } = requireAgent(deps);
1192
1539
  const result = await nextCommand(c, {
1193
1540
  model: modelOf(cli, identity),
1194
1541
  approach: str(cli.options.approach),
1195
1542
  wait: intOption(cli.options.wait, "wait") ?? 0,
1196
1543
  onProgress: deps.onProgress
1197
1544
  });
1198
- return { result, code: result.data.assignment ? 0 : 3 };
1545
+ const a = result.data.assignment;
1546
+ if (a) {
1547
+ writeAgent(identityDir, {
1548
+ ...identity,
1549
+ lastAssignment: {
1550
+ attempt: a.attempt,
1551
+ role: a.role,
1552
+ leaseUntil: a.leaseUntil,
1553
+ task: a.task.id
1554
+ }
1555
+ });
1556
+ }
1557
+ return { result, code: result.data.done === true ? 4 : result.data.assignment ? 0 : 3 };
1199
1558
  }
1200
1559
  case "beat": {
1201
1560
  const attempt = requirePositional(cli, 0, "beat needs an attempt id");
@@ -1223,30 +1582,43 @@ async function dispatch(cli, deps) {
1223
1582
  const claimText = str(cli.options.claim);
1224
1583
  if (!claimText)
1225
1584
  throw new Error("submit needs --claim solves|refutes|progress");
1226
- const message = str(cli.options.message);
1227
- if (!message)
1585
+ const rawMessage = str(cli.options.message);
1586
+ if (!rawMessage)
1228
1587
  throw new Error('submit needs -m "<message>"');
1229
- const { identity, client: c } = requireAgent(deps);
1588
+ const fitted = fitSubmitMessage(rawMessage);
1589
+ if (fitted.notice !== undefined)
1590
+ deps.onProgress?.(fitted.notice);
1591
+ const { identity, identityDir, client: c } = requireAgent(deps);
1230
1592
  const result = await submitCommand(c, {
1231
1593
  attempt,
1232
1594
  claim: parseClaim(claimText),
1233
- message,
1595
+ message: fitted.message,
1234
1596
  files: cli.positionals.slice(1),
1235
1597
  root: str(cli.options.root),
1236
1598
  model: modelOf(cli, identity),
1237
1599
  wait: cli.options.wait !== false,
1238
1600
  onProgress: deps.onProgress
1239
1601
  });
1602
+ const submission = "submission" in result.data ? result.data.submission : result.data.id;
1603
+ const accepted = acceptedFiles(result.data);
1604
+ writeAgent(identityDir, {
1605
+ ...identity,
1606
+ lastSubmission: submission,
1607
+ ...accepted !== undefined ? { lastAccepted: accepted } : {}
1608
+ });
1240
1609
  return { result, code: submissionExitCode(result.data) };
1241
1610
  }
1242
1611
  case "result": {
1243
1612
  const submission = requirePositional(cli, 0, "result needs a submission id (S-n)");
1244
- const { client: c } = requireAgent(deps);
1613
+ const { identity, identityDir, client: c } = requireAgent(deps);
1245
1614
  const result = await resultCommand(c, {
1246
1615
  submission,
1247
1616
  wait: cli.options.wait === true,
1248
1617
  onProgress: deps.onProgress
1249
1618
  });
1619
+ const accepted = acceptedFiles(result.data);
1620
+ if (accepted !== undefined)
1621
+ writeAgent(identityDir, { ...identity, lastAccepted: accepted });
1250
1622
  return { result, code: submissionExitCode(result.data) };
1251
1623
  }
1252
1624
  case "release": {
@@ -1295,12 +1667,20 @@ async function dispatch(cli, deps) {
1295
1667
  }
1296
1668
  case "status": {
1297
1669
  const { identity, client: c } = requireAgent(deps);
1298
- return { result: await statusCommand(c, identity.agent), code: 0 };
1670
+ return { result: await statusCommand(c, identity), code: 0 };
1299
1671
  }
1300
1672
  case "board": {
1301
1673
  const { client: c } = requireAgent(deps);
1302
1674
  return { result: await boardCommand(c), code: 0 };
1303
1675
  }
1676
+ case "tasks": {
1677
+ const { client: c } = requireAgent(deps);
1678
+ return { result: await tasksCommand(c, { openOnly: cli.options.open === true }), code: 0 };
1679
+ }
1680
+ case "sync": {
1681
+ const result = syncCommand({ dir, discard: cli.options.discard === true });
1682
+ return { result, code: result.data.refused ? 1 : 0 };
1683
+ }
1304
1684
  case "init": {
1305
1685
  const required = (name) => {
1306
1686
  const value = str(cli.options[name]);
@@ -1320,7 +1700,7 @@ async function dispatch(cli, deps) {
1320
1700
  scope: required("scope"),
1321
1701
  check: required("check"),
1322
1702
  paths,
1323
- branch: str(cli.options.branch) ?? "main",
1703
+ branch: str(cli.options.branch) ?? "minga",
1324
1704
  force: cli.options.force === true,
1325
1705
  url: str(cli.options.url)
1326
1706
  }),
@@ -1386,6 +1766,21 @@ async function dispatch(cli, deps) {
1386
1766
  throw new Error("head ban needs --reason");
1387
1767
  return { result: await headBanCommand(c, { agent, reason }), code: 0 };
1388
1768
  }
1769
+ if (action === "note") {
1770
+ const task = requirePositional(cli, 0, "head note needs a task id");
1771
+ const text = cli.positionals.slice(1).join(" ");
1772
+ if (text.length === 0)
1773
+ throw new Error("head note needs some text");
1774
+ const kindText = str(cli.options.kind);
1775
+ return {
1776
+ result: await headNoteCommand(c, {
1777
+ task,
1778
+ text,
1779
+ ...kindText !== undefined ? { kind: parseNoteKind(kindText) } : {}
1780
+ }),
1781
+ code: 0
1782
+ };
1783
+ }
1389
1784
  if (action === "close") {
1390
1785
  const task = requirePositional(cli, 0, "head close needs a task id");
1391
1786
  const status = requirePositional(cli, 1, "head close needs withdrawn, impossible or solved");
@@ -1416,7 +1811,7 @@ var boolProp = (description) => ({ type: "boolean", description });
1416
1811
  var MCP_TOOLS = [
1417
1812
  {
1418
1813
  name: "minga_join",
1419
- description: "Join a Minga project with your model and harness; saves your identity for later tools. Call this first.",
1814
+ description: "Step 0: join a Minga project with your model and harness; saves your identity for later tools. Call this first. Loop after it: minga_next -> work -> minga_beat -> minga_submit -> read the verdict with minga_submit or minga_result, or give up with minga_release; if done is true, stop: the project has no open tasks left.",
1420
1815
  inputSchema: {
1421
1816
  type: "object",
1422
1817
  properties: {
@@ -1430,17 +1825,21 @@ var MCP_TOOLS = [
1430
1825
  },
1431
1826
  {
1432
1827
  name: "minga_next",
1433
- description: "Ask for the next task. Use wait to block until one is free, up to 600 seconds.",
1828
+ description: "Step 1 of the loop: ask for a task. wait defaults to 30 seconds (one long-poll); call again if assignment is null. if done is true, stop: the project has no open tasks left. The result includes the assigned branch head: run minga sync until you have it, then work, minga_beat every ~10 min, minga_submit, and read the verdict (or minga_release).",
1434
1829
  inputSchema: {
1435
1830
  type: "object",
1436
1831
  properties: {
1437
- wait: { type: "integer", minimum: 0, description: "Seconds to wait for an assignment (default 0)." }
1832
+ wait: {
1833
+ type: "integer",
1834
+ minimum: 0,
1835
+ description: "Seconds to wait for an assignment (default 30, one long-poll); call again if assignment is null. If done is true, stop."
1836
+ }
1438
1837
  }
1439
1838
  }
1440
1839
  },
1441
1840
  {
1442
1841
  name: "minga_beat",
1443
- description: "Renew the lease on your current attempt. Do this roughly every 10 minutes while working.",
1842
+ description: "Step 2 of the loop: renew the lease on your current attempt roughly every 10 minutes while working on it.",
1444
1843
  inputSchema: {
1445
1844
  type: "object",
1446
1845
  properties: {
@@ -1465,7 +1864,7 @@ var MCP_TOOLS = [
1465
1864
  },
1466
1865
  {
1467
1866
  name: "minga_submit",
1468
- description: "Submit changed files for checking and wait for the verdict. Files must be paths relative to root.",
1867
+ description: "Step 3 of the loop: submit changed files (paths relative to root) for checking; waits for the verdict by default, up to ~10 minutes. Pass wait:false to return immediately and then call minga_result. On rejection, fix and submit again or call minga_release.",
1469
1868
  inputSchema: {
1470
1869
  type: "object",
1471
1870
  properties: {
@@ -1481,7 +1880,7 @@ var MCP_TOOLS = [
1481
1880
  },
1482
1881
  {
1483
1882
  name: "minga_result",
1484
- description: "Show a submission and its verdict; use wait to block until it is final.",
1883
+ description: "Show a submission and its verdict. Use this after minga_submit with wait:false; set wait:true to block until the verdict is final.",
1485
1884
  inputSchema: {
1486
1885
  type: "object",
1487
1886
  properties: {
@@ -1493,7 +1892,7 @@ var MCP_TOOLS = [
1493
1892
  },
1494
1893
  {
1495
1894
  name: "minga_release",
1496
- description: "Give up an attempt. Always leave a handoff note so the next agent can continue.",
1895
+ description: "Step 4 of the loop (instead of submitting): give up an attempt. Always leave a handoff note so the next agent can continue.",
1497
1896
  inputSchema: {
1498
1897
  type: "object",
1499
1898
  properties: {
@@ -1542,13 +1941,33 @@ var MCP_TOOLS = [
1542
1941
  },
1543
1942
  {
1544
1943
  name: "minga_status",
1545
- description: "Show the project goal, scope, check, paths, rules and your agent id.",
1944
+ description: "Show the project goal, scope, check, paths, rules, your agent id, your last attempt with lease remaining and your last submission's queue position.",
1546
1945
  inputSchema: { type: "object", properties: {} }
1547
1946
  },
1548
1947
  {
1549
1948
  name: "minga_board",
1550
1949
  description: "Show the top agents on the leaderboard.",
1551
1950
  inputSchema: { type: "object", properties: {} }
1951
+ },
1952
+ {
1953
+ name: "minga_tasks",
1954
+ description: "Show the task tree with status, live attempts (open tasks only), points and titles; areas are marked. Set open:true to show only open tasks. The footer counts open leaf tasks or says the project is finished. structuredContent is the same raw response as --json.",
1955
+ inputSchema: {
1956
+ type: "object",
1957
+ properties: {
1958
+ open: boolProp("Show only open tasks (default false).")
1959
+ }
1960
+ }
1961
+ },
1962
+ {
1963
+ name: "minga_sync",
1964
+ 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.",
1965
+ inputSchema: {
1966
+ type: "object",
1967
+ properties: {
1968
+ discard: boolProp("Discard all local changes, including unrelated ones (default false).")
1969
+ }
1970
+ }
1552
1971
  }
1553
1972
  ];
1554
1973
  function rpcResult(id, result) {
@@ -1557,7 +1976,7 @@ function rpcResult(id, result) {
1557
1976
  function rpcError(id, code, message) {
1558
1977
  return JSON.stringify({ jsonrpc: "2.0", id, error: { code, message } });
1559
1978
  }
1560
- function firstLine(err) {
1979
+ function firstLine2(err) {
1561
1980
  const text = err instanceof Error ? err.message : String(err);
1562
1981
  return text.split(`
1563
1982
  `)[0] ?? text;
@@ -1581,7 +2000,7 @@ function setOpt(options, key, value) {
1581
2000
  if (value !== undefined)
1582
2001
  options[key] = value;
1583
2002
  }
1584
- function toolToCli(name, args) {
2003
+ function toolToCli(name, args, onNotice) {
1585
2004
  const options = {};
1586
2005
  let command = "status";
1587
2006
  let positionals = [];
@@ -1595,9 +2014,9 @@ function toolToCli(name, args) {
1595
2014
  break;
1596
2015
  case "minga_next": {
1597
2016
  command = "next";
1598
- const wait = optNumber(args, "wait");
1599
- if (wait !== undefined)
1600
- options.wait = String(Math.max(0, Math.floor(wait)));
2017
+ const given = args.wait;
2018
+ const wait = typeof given === "boolean" ? given ? 30 : 0 : optNumber(args, "wait") ?? 30;
2019
+ options.wait = String(Math.max(0, Math.floor(wait)));
1601
2020
  break;
1602
2021
  }
1603
2022
  case "minga_beat":
@@ -1617,7 +2036,10 @@ function toolToCli(name, args) {
1617
2036
  }
1618
2037
  positionals = [reqString(args, "attempt"), ...files];
1619
2038
  options.claim = reqString(args, "claim");
1620
- options.message = reqString(args, "message");
2039
+ const fitted = fitSubmitMessage(reqString(args, "message"));
2040
+ options.message = fitted.message;
2041
+ if (fitted.notice !== undefined)
2042
+ onNotice?.(fitted.notice);
1621
2043
  setOpt(options, "root", optString(args, "root"));
1622
2044
  options.wait = args.wait !== false;
1623
2045
  break;
@@ -1657,6 +2079,16 @@ function toolToCli(name, args) {
1657
2079
  case "minga_board":
1658
2080
  command = "board";
1659
2081
  break;
2082
+ case "minga_tasks":
2083
+ command = "tasks";
2084
+ if (args.open === true)
2085
+ options.open = true;
2086
+ break;
2087
+ case "minga_sync":
2088
+ command = "sync";
2089
+ if (args.discard === true)
2090
+ options.discard = true;
2091
+ break;
1660
2092
  default:
1661
2093
  throw new Error(`unknown tool: ${name}`);
1662
2094
  }
@@ -1711,7 +2143,7 @@ function createMcpHandler(ctx) {
1711
2143
  });
1712
2144
  }
1713
2145
  try {
1714
- const cli = toolToCli(name, params.arguments !== null && typeof params.arguments === "object" && !Array.isArray(params.arguments) ? params.arguments : {});
2146
+ const cli = toolToCli(name, params.arguments !== null && typeof params.arguments === "object" && !Array.isArray(params.arguments) ? params.arguments : {}, ctx.onProgress);
1715
2147
  const outcome = await execute(cli);
1716
2148
  const text = outcome.result.text;
1717
2149
  const body = {
@@ -1723,7 +2155,7 @@ function createMcpHandler(ctx) {
1723
2155
  return rpcResult(id, body);
1724
2156
  } catch (err) {
1725
2157
  return rpcResult(id, {
1726
- content: [{ type: "text", text: firstLine(err) }],
2158
+ content: [{ type: "text", text: firstLine2(err) }],
1727
2159
  isError: true
1728
2160
  });
1729
2161
  }
@@ -1771,9 +2203,11 @@ agent commands
1771
2203
  vote <P-n> yes|no
1772
2204
  status
1773
2205
  board
2206
+ tasks [--open]
2207
+ sync [--discard]
1774
2208
 
1775
2209
  maintainer commands
1776
- init [dir] --name <n> --goal <g> --scope <s> --check <cmd> --paths <glob[,glob...>] [--branch main] [--force]
2210
+ init [dir] --name <n> --goal <g> --scope <s> --check <cmd> --paths <glob[,glob...>] [--branch minga] [--force]
1777
2211
  serve [--repo <dir>] [--port 7777] [--host 127.0.0.1] [server flags...]
1778
2212
  doctor [--repo <dir>]
1779
2213
  mcp [--dir <dir>]
@@ -1784,10 +2218,12 @@ head commands
1784
2218
  head decide <P-n> accept|reject [--reason "..."]
1785
2219
  head rule <key>=<value>...
1786
2220
  head ban <agent> --reason "..."
2221
+ head note <task> <text...> [--kind result|idea|question|handoff]
1787
2222
  head close <T-n> withdrawn|impossible|solved
1788
2223
 
1789
2224
  common options
1790
- --dir <dir> identity directory (default: $MINGA_DIR or the cwd)
2225
+ --dir <dir> identity directory (default: $MINGA_DIR or the cwd); lookup
2226
+ walks up to the nearest ancestor holding .minga/agent.json
1791
2227
  --url <url> coordinator base URL (default: the one saved at join)
1792
2228
  --json print the raw response JSON (errors: {"error":"..."})
1793
2229
  -v, --version print the kit version
@@ -1800,7 +2236,10 @@ Creates or reuses .minga/agent.json and registers with the project.
1800
2236
  next: `usage: minga next [--model <m>] [--approach "..."] [--wait <seconds>]
1801
2237
 
1802
2238
  Asks for an assignment. --wait repeats the request for up to that many seconds
1803
- (each request long-polls at most 30 s). Exit 0 with an assignment, 3 without one.`,
2239
+ (each request long-polls at most 30 s); every empty poll prints
2240
+ "no free task yet; waiting (Ns left)" to stderr. Exit 0 with an assignment,
2241
+ 3 if nothing was free within the wait, 4 if the project has no open tasks left
2242
+ (stop asking). --json prints the raw response.`,
1804
2243
  beat: `usage: minga beat <attempt> [--model <m>] [--approach "..."]
1805
2244
 
1806
2245
  Renews the lease on an attempt. Beat every ~10 minutes.`,
@@ -1832,7 +2271,17 @@ Prints the project goal, scope, check, rules and your agent id.`,
1832
2271
  board: `usage: minga board
1833
2272
 
1834
2273
  Prints the leaderboard (top 10 agents).`,
1835
- init: `usage: minga init [dir] --name <n> --goal <g> --scope <s> --check <cmd> --paths <glob[,glob...>] [--branch main] [--force]
2274
+ tasks: `usage: minga tasks [--open]
2275
+
2276
+ Prints the task tree with status, live attempts, points and titles; areas are
2277
+ marked. --open shows only open tasks. The footer counts open leaf tasks, or
2278
+ says the project is finished. --json prints the raw response.`,
2279
+ sync: `usage: minga sync [--discard]
2280
+
2281
+ Fetches origin, then drops local files left by an accepted submit when they
2282
+ match the fetched branch head or come from your last accepted submission.
2283
+ Other changes are refused unless --discard is given.`,
2284
+ init: `usage: minga init [dir] --name <n> --goal <g> --scope <s> --check <cmd> --paths <glob[,glob...>] [--branch minga] [--force]
1836
2285
 
1837
2286
  Non-interactive scaffold: creates .minga/head.json, project.toml and adds
1838
2287
  .minga/ to .gitignore. dir must already be a git repository. --force overwrites
@@ -1865,12 +2314,16 @@ defaultPoints (numbers) and accept (head | votes:N | head-or-votes:N).`,
1865
2314
  "head ban": `usage: minga head ban <agent> --reason "..."
1866
2315
 
1867
2316
  Bans an agent from the project.`,
2317
+ "head note": `usage: minga head note <task> <text...> [--kind result|idea|question|handoff]
2318
+
2319
+ Leaves a note as the head agent (default kind: result). Agents see it with
2320
+ their next assignment, marked "head:" so it stands out from peer notes.`,
1868
2321
  "head close": `usage: minga head close <T-n> withdrawn|impossible|solved [--reason "..."]
1869
2322
 
1870
2323
  Closes a task by fiat.`,
1871
2324
  head: `usage: minga head <action>
1872
2325
 
1873
- Actions: keygen, post, decide, rule, ban, close. Try "minga head --help".`
2326
+ Actions: keygen, post, decide, rule, ban, note, close. Try "minga head --help".`
1874
2327
  };
1875
2328
  function helpFor(cli) {
1876
2329
  if (cli.command === "head") {
@@ -1879,7 +2332,7 @@ function helpFor(cli) {
1879
2332
  }
1880
2333
  return HELP[cli.command] ?? USAGE;
1881
2334
  }
1882
- function firstLine2(err) {
2335
+ function firstLine3(err) {
1883
2336
  const text = err instanceof Error ? err.message : String(err);
1884
2337
  return text.split(`
1885
2338
  `)[0] ?? text;
@@ -1930,7 +2383,7 @@ async function run(argv) {
1930
2383
  dir,
1931
2384
  ...urlOverride !== undefined ? { urlOverride } : {},
1932
2385
  onProgress: (line) => {
1933
- (json ? process.stderr : process.stdout).write(`${line}
2386
+ process.stderr.write(`${line}
1934
2387
  `);
1935
2388
  }
1936
2389
  });
@@ -1940,9 +2393,9 @@ async function run(argv) {
1940
2393
  run(process.argv.slice(2)).then((code) => {
1941
2394
  process.exitCode = code;
1942
2395
  }, (err) => {
1943
- const message = `minga: ${firstLine2(err)}`;
2396
+ const message = `minga: ${firstLine3(err)}`;
1944
2397
  if (process.argv.slice(2).includes("--json")) {
1945
- process.stdout.write(`${JSON.stringify({ error: firstLine2(err) })}
2398
+ process.stdout.write(`${JSON.stringify({ error: firstLine3(err) })}
1946
2399
  `);
1947
2400
  } else {
1948
2401
  process.stderr.write(`${message}