minga-swarm 0.1.0 → 0.1.1

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "minga-swarm",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
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",
package/src/cli/client.ts CHANGED
@@ -8,11 +8,12 @@
8
8
  */
9
9
  import type {
10
10
  BeatRequest, BeatResponse, EventsResponse, HeadBanRequest, HeadBanResponse, HeadCloseRequest,
11
- HeadCloseResponse, HeadDecideRequest, HeadDecideResponse, HeadPostRequest, HeadPostResponse,
12
- HeadRuleRequest, HeadRuleResponse, JoinRequest, JoinResponse, LeaderboardResponse, NextRequest,
11
+ HeadCloseResponse, HeadDecideRequest, HeadDecideResponse, HeadNoteRequest, HeadNoteResponse,
12
+ HeadPostRequest, HeadPostResponse, HeadRuleRequest, HeadRuleResponse, JoinRequest, JoinResponse,
13
+ LeaderboardResponse, NextRequest,
13
14
  NextResponse, NoteRequest, NoteResponse, ProposeRequest, ProposeResponse, ProjectInfo,
14
15
  ReleaseRequest, ReleaseResponse, SubmitRequest, SubmitResponse, SubmissionView,
15
- VoteRequest, VoteResponse,
16
+ TasksResponse, VoteRequest, VoteResponse,
16
17
  } from "../core/protocol.ts";
17
18
  import type { AgentId } from "../core/types.ts";
18
19
  import { agentIdFromPublicKey, signRequest } from "../identity/keys.ts";
@@ -41,6 +42,8 @@ export interface Client {
41
42
  state(): Promise<StateResponse>;
42
43
  events(after?: number, limit?: number): Promise<EventsResponse>;
43
44
  leaderboard(): Promise<LeaderboardResponse>;
45
+ /** GET /api/tasks: every task, compact, for a tree overview. */
46
+ tasks(): Promise<TasksResponse>;
44
47
  /** GET /api/submission/<id>?wait=<seconds>. Long-polls at most 30 s per call. */
45
48
  submission(id: string, waitSeconds?: number): Promise<SubmissionView>;
46
49
 
@@ -59,6 +62,7 @@ export interface Client {
59
62
  headDecide(body: HeadDecideRequest): Promise<HeadDecideResponse>;
60
63
  headRule(body: HeadRuleRequest): Promise<HeadRuleResponse>;
61
64
  headBan(body: HeadBanRequest): Promise<HeadBanResponse>;
65
+ headNote(body: HeadNoteRequest): Promise<HeadNoteResponse>;
62
66
  headClose(body: HeadCloseRequest): Promise<HeadCloseResponse>;
63
67
  }
64
68
 
@@ -109,6 +113,7 @@ export function createClient(baseUrl: string, keys: KeyPair, fetchImpl: FetchLik
109
113
  return send<EventsResponse>("GET", `/api/events?${query}`);
110
114
  },
111
115
  leaderboard: () => send<LeaderboardResponse>("GET", "/api/leaderboard"),
116
+ tasks: () => send<TasksResponse>("GET", "/api/tasks"),
112
117
  submission: (id, waitSeconds = 0) => {
113
118
  const wait = Math.max(0, Math.min(30, Math.floor(waitSeconds)));
114
119
  const query = wait > 0 ? `?wait=${wait}` : "";
@@ -128,6 +133,7 @@ export function createClient(baseUrl: string, keys: KeyPair, fetchImpl: FetchLik
128
133
  headDecide: (body) => send<HeadDecideResponse>("POST", "/api/head/decide", body),
129
134
  headRule: (body) => send<HeadRuleResponse>("POST", "/api/head/rule", body),
130
135
  headBan: (body) => send<HeadBanResponse>("POST", "/api/head/ban", body),
136
+ headNote: (body) => send<HeadNoteResponse>("POST", "/api/head/note", body),
131
137
  headClose: (body) => send<HeadCloseResponse>("POST", "/api/head/close", body),
132
138
  };
133
139
  }
@@ -11,7 +11,7 @@ import { parseArgs } from "node:util";
11
11
  import type {
12
12
  Assignment, BeatResponse, JoinResponse, LeaderboardResponse, NextResponse, NoteResponse,
13
13
  ProposeResponse, ProjectInfo, ReleaseResponse, SubmitResponse, SubmissionView, VoteResponse,
14
- HeadDecideResponse, HeadRuleResponse,
14
+ HeadDecideResponse, HeadNoteResponse, HeadRuleResponse, TasksResponse,
15
15
  } from "../core/protocol.ts";
16
16
  import type {
17
17
  AcceptPolicy, AgentId, Claim, NoteKind, ProposalId, ProposalKind, Rules, TaskId,
@@ -88,6 +88,9 @@ const COMMAND_OPTIONS: Record<string, OptionSet> = {
88
88
  vote: {},
89
89
  status: {},
90
90
  board: {},
91
+ tasks: {
92
+ open: { type: "boolean" },
93
+ },
91
94
  init: {
92
95
  name: { type: "string" },
93
96
  goal: { type: "string" },
@@ -100,6 +103,9 @@ const COMMAND_OPTIONS: Record<string, OptionSet> = {
100
103
  doctor: {
101
104
  repo: { type: "string" },
102
105
  },
106
+ sync: {
107
+ discard: { type: "boolean" },
108
+ },
103
109
  mcp: {},
104
110
  };
105
111
 
@@ -118,6 +124,9 @@ const HEAD_OPTIONS: Record<string, OptionSet> = {
118
124
  ban: {
119
125
  reason: { type: "string" },
120
126
  },
127
+ note: {
128
+ kind: { type: "string" },
129
+ },
121
130
  close: {
122
131
  reason: { type: "string" },
123
132
  },
@@ -332,6 +341,9 @@ export async function joinCommand(client: Client, input: JoinInput): Promise<Joi
332
341
  `goal: ${response.project.goal}`,
333
342
  `scope: ${response.project.scope}`,
334
343
  `rules: ${formatRules(response.project.rules)}`,
344
+ "",
345
+ `get the code: git clone ${input.url.replace(/\/+$/, "")}/repo.git work && cd work`,
346
+ "run minga from inside that checkout; submit reads files relative to cwd",
335
347
  ];
336
348
  if (response.live.length > 0) lines.push(`live attempts from before: ${response.live.join(", ")}`);
337
349
  return { identity, result: { text: lines.join("\n"), data: response } };
@@ -347,11 +359,15 @@ export interface NextInput {
347
359
  onProgress?: (line: string) => void;
348
360
  }
349
361
 
350
- function formatAssignment(a: Assignment): string {
362
+ /** `headAgent` marks maintainer notes so agents can tell them from peer notes. */
363
+ function formatAssignment(a: Assignment, headAgent?: AgentId): string {
364
+ const headMark = (agent: AgentId): string =>
365
+ headAgent !== undefined && agent === headAgent ? "head: " : "";
351
366
  const lines = [
352
367
  `attempt ${a.attempt}`,
353
368
  `role ${a.role}`,
354
369
  `lease ${a.leaseUntil}`,
370
+ ...(a.head ? [`head ${a.head.slice(0, 7)} (minga sync if your checkout is older)`] : []),
355
371
  `task ${a.task.id} ${a.task.title} (${a.task.points} points)`,
356
372
  ];
357
373
  if (a.path.length > 0) {
@@ -359,11 +375,13 @@ function formatAssignment(a: Assignment): string {
359
375
  }
360
376
  lines.push("body:", indent(a.task.body.length > 0 ? a.task.body : "(empty)"));
361
377
  if (a.handoff) {
362
- lines.push(`handoff ${a.handoff.id} (${a.handoff.kind}) ${a.handoff.text}`);
378
+ lines.push(`handoff ${a.handoff.id} ${headMark(a.handoff.agent)}(${a.handoff.kind}) ${a.handoff.text}`);
363
379
  }
364
380
  if (a.notes.length > 0) {
365
381
  lines.push("notes:");
366
- for (const note of a.notes) lines.push(` ${note.id} ${note.agent} ${note.kind}: ${note.text}`);
382
+ for (const note of a.notes) {
383
+ lines.push(` ${note.id} ${headMark(note.agent)}${note.agent} ${note.kind}: ${note.text}`);
384
+ }
367
385
  }
368
386
  if (a.others.length > 0) {
369
387
  lines.push("others on this task:");
@@ -395,9 +413,26 @@ export async function nextCommand(client: Client, input: NextInput = {}): Promis
395
413
  ...(input.approach !== undefined ? { approach: input.approach } : {}),
396
414
  ...(chunk > 0 ? { wait: chunk } : {}),
397
415
  });
398
- if (response.assignment) return { text: formatAssignment(response.assignment), data: response };
416
+ // done is a terminal answer: no open leaf task remains, so stop asking.
417
+ if (response.done === true) {
418
+ return { text: "the project has no open tasks left. Stop here.", data: response };
419
+ }
420
+ if (response.assignment) {
421
+ let headAgent: AgentId | undefined;
422
+ if (response.assignment.notes.length > 0 || response.assignment.handoff) {
423
+ try {
424
+ headAgent = (await client.project()).headAgent;
425
+ } catch {
426
+ // An unavailable project endpoint must not hide the assignment.
427
+ }
428
+ }
429
+ return { text: formatAssignment(response.assignment, headAgent), data: response };
430
+ }
399
431
  last = response;
400
- input.onProgress?.(`waiting for a task (retry in ${response.retryAfterSeconds ?? 60}s)`);
432
+ if (chunk > 0) {
433
+ const left = Math.max(0, Math.ceil(total - (Date.now() - started) / 1000));
434
+ input.onProgress?.(`no free task yet; waiting (${left}s left)`);
435
+ }
401
436
 
402
437
  if (total === 0 || chunk <= 0) break;
403
438
  // A server that ignores `wait` must not spin the CPU in a tight loop.
@@ -410,13 +445,28 @@ export async function nextCommand(client: Client, input: NextInput = {}): Promis
410
445
 
411
446
  const wait = last?.retryAfterSeconds ?? 60;
412
447
  return {
413
- text: `nothing to do, retry in ${wait}s`,
448
+ // Without --wait an agent should be told the one command that will block.
449
+ text: total === 0
450
+ ? 'nothing to do right now; run "minga next --wait 600" to wait for a task'
451
+ : `nothing to do, retry in ${wait}s`,
414
452
  data: last ?? { assignment: null, retryAfterSeconds: wait },
415
453
  };
416
454
  }
417
455
 
418
456
  // ---------------------------------------------------------------- submit / result
419
457
 
458
+ /** The server keeps only the first line, max 200 chars; fit it before sending. */
459
+ export const SUBMIT_MESSAGE_MAX = 200;
460
+
461
+ export function fitSubmitMessage(message: string): { message: string; notice?: string } {
462
+ if (message.length <= SUBMIT_MESSAGE_MAX) return { message };
463
+ const first = message.split("\n")[0] ?? "";
464
+ const fitted = first.length > SUBMIT_MESSAGE_MAX
465
+ ? `${first.slice(0, SUBMIT_MESSAGE_MAX - 3)}...`
466
+ : first;
467
+ return { message: fitted, notice: `submit message over ${SUBMIT_MESSAGE_MAX} chars; using "${fitted}"` };
468
+ }
469
+
420
470
  export interface SubmitInput {
421
471
  attempt: string;
422
472
  claim: Claim;
@@ -461,21 +511,31 @@ export async function waitForSubmission(
461
511
  initialStatus = "queued",
462
512
  ): Promise<SubmissionView> {
463
513
  let lastStatus = initialStatus;
514
+ let lastRuns = 0;
464
515
  // Each poll holds the connection for up to 30 s; 1000 polls is > 8 hours.
465
516
  for (let i = 0; i < 1000; i++) {
466
517
  const view = await client.submission(id, 30);
467
- if (view.status !== lastStatus) {
468
- lastStatus = view.status;
469
- if (view.status === "checking") onProgress?.(`checking ${id}`);
470
- }
471
- if (isFinal(view.status)) {
472
- onProgress?.(`verdict ${view.status} ${id}`);
473
- return view;
518
+ const changed = view.status !== lastStatus || view.runs !== lastRuns;
519
+ lastStatus = view.status;
520
+ lastRuns = view.runs;
521
+ if (view.status === "checking" && changed) {
522
+ onProgress?.(`checking ${id} (run ${view.runs})`);
474
523
  }
524
+ // The final block below is the only place that reports the verdict.
525
+ if (isFinal(view.status)) return view;
475
526
  }
476
527
  throw new Error(`submission ${id} has no verdict yet; check it with "minga result ${id}"`);
477
528
  }
478
529
 
530
+ /** Why a check was discarded without a verdict, read from the server's outputTail. */
531
+ function staleReason(view: SubmitView): string | undefined {
532
+ if (!("stale" in view) || view.stale !== true) return undefined;
533
+ const tail = view.outputTail ?? "";
534
+ if (/branch kept moving/i.test(tail)) return "the branch kept moving";
535
+ if (/\bclosed\b/i.test(tail)) return "the task closed first";
536
+ return "unknown reason";
537
+ }
538
+
479
539
  /** The exact text printed for a submission, shared by submit and result. */
480
540
  export function renderSubmission(view: SubmitView): string {
481
541
  // The ack uses `submission`; the view returned by GET uses `id`.
@@ -485,14 +545,31 @@ export function renderSubmission(view: SubmitView): string {
485
545
  return `submission ${id}: queued${position}`;
486
546
  }
487
547
  const lines: string[] = [];
488
- if (view.status === "checking") lines.push(`submission ${id}: checking`);
489
- else lines.push(`verdict: ${view.status}`, `submission ${id}`);
490
- lines.push(`exit code: ${view.exitCode ?? 0}${view.timedOut ? " (timed out)" : ""}`);
548
+ if (view.status === "checking") {
549
+ lines.push(`submission ${id}: checking`);
550
+ return lines.join("\n");
551
+ }
552
+ const attempt = "attempt" in view ? view.attempt : id;
553
+ const exitCode = view.exitCode ?? 0;
554
+ lines.push(`verdict: ${view.status}`, `submission ${id}`);
555
+ lines.push(`exit code: ${exitCode}${view.timedOut ? " (timed out)" : ""}`);
556
+ if (view.status === "rejected") {
557
+ const reason = staleReason(view);
558
+ if (reason !== undefined) lines.push(`stale: ${reason}`);
559
+ }
491
560
  if (view.outputTail && view.outputTail.length > 0) {
492
561
  lines.push("output tail:", indent(view.outputTail));
562
+ } else if (view.status === "rejected") {
563
+ lines.push(`output: (the check printed nothing; exit code ${exitCode})`);
493
564
  }
494
565
  if (view.commit !== undefined) lines.push(`commit: ${view.commit}`);
495
566
  lines.push(`points: ${view.points}`);
567
+ if (view.status === "accepted") {
568
+ lines.push("next: minga sync && minga next --wait 600");
569
+ } else if (view.status === "rejected") {
570
+ lines.push(`next: fix and run "minga submit ${attempt} ..." again, or ` +
571
+ `"minga release ${attempt} --handoff \\"...\\""`);
572
+ }
496
573
  return lines.join("\n");
497
574
  }
498
575
 
@@ -512,9 +589,9 @@ export async function submitCommand(client: Client, input: SubmitInput): Promise
512
589
  ...(input.model !== undefined ? { model: input.model } : {}),
513
590
  });
514
591
 
515
- const progress = `queued ${queued.submission} #${queued.position}`;
592
+ const progress = `queued ${queued.submission} (#${queued.position} in line)`;
516
593
  input.onProgress?.(progress);
517
- if (input.wait === false) return { text: progress, data: queued };
594
+ if (input.wait === false) return { text: renderSubmission(queued), data: queued };
518
595
 
519
596
  const final = await waitForSubmission(client, queued.submission, input.onProgress);
520
597
  return { text: renderSubmission(final), data: final };
@@ -637,20 +714,51 @@ export async function voteCommand(client: Client, input: VoteInput): Promise<Com
637
714
  export interface StatusData {
638
715
  agent: AgentId;
639
716
  project: ProjectInfo;
717
+ /** Last assignment from `next`, persisted in .minga/agent.json. */
718
+ assignment?: SessionIdentity["lastAssignment"];
719
+ /** Last submission from `submit`, checked live on `status`. */
720
+ submission?: SubmissionView;
721
+ }
722
+
723
+ /** Minutes left on a lease, for an agent that lost context. */
724
+ function leaseText(leaseUntil: string): string {
725
+ const ms = Date.parse(leaseUntil) - Date.now();
726
+ if (!Number.isFinite(ms)) return leaseUntil;
727
+ return ms > 0 ? `${Math.ceil(ms / 60_000)}m left` : "expired";
640
728
  }
641
729
 
642
- export async function statusCommand(client: Client, agent: AgentId): Promise<CommandResult<StatusData>> {
730
+ export async function statusCommand(client: Client, identity: SessionIdentity): Promise<CommandResult<StatusData>> {
643
731
  const project = await client.project();
644
- const text = [
732
+ const data: StatusData = { agent: identity.agent, project };
733
+ const lines = [
645
734
  `project: ${project.name}`,
646
735
  `goal: ${project.goal}`,
647
736
  `scope: ${project.scope}`,
648
737
  `check: ${project.check}`,
649
738
  `paths: ${project.paths.join(", ")}`,
650
739
  `rules: ${formatRules(project.rules)}`,
651
- `your agent: ${agent}`,
652
- ].join("\n");
653
- return { text, data: { agent, project } };
740
+ `your agent: ${identity.agent}`,
741
+ ];
742
+
743
+ const assignment = identity.lastAssignment;
744
+ if (assignment) {
745
+ lines.push(`attempt: ${assignment.attempt} (${assignment.role}) on ${assignment.task} — ` +
746
+ `lease ${leaseText(assignment.leaseUntil)}`);
747
+ data.assignment = assignment;
748
+ }
749
+
750
+ if (identity.lastSubmission) {
751
+ try {
752
+ const view = await client.submission(identity.lastSubmission, 0);
753
+ const position = view.status === "queued" && view.position !== undefined ? ` #${view.position}` : "";
754
+ lines.push(`submission: ${view.id} ${view.status}${position}`);
755
+ data.submission = view;
756
+ } catch {
757
+ lines.push(`submission: ${identity.lastSubmission} (unavailable)`);
758
+ }
759
+ }
760
+
761
+ return { text: lines.join("\n"), data };
654
762
  }
655
763
 
656
764
  export async function boardCommand(client: Client): Promise<CommandResult<LeaderboardResponse>> {
@@ -676,6 +784,68 @@ export async function boardCommand(client: Client): Promise<CommandResult<Leader
676
784
  return { text, data: leaderboard };
677
785
  }
678
786
 
787
+ // ---------------------------------------------------------------- tasks overview
788
+
789
+ export interface TasksInput {
790
+ /** Show only open tasks (areas included); the footer always reports open leaves. */
791
+ openOnly?: boolean;
792
+ }
793
+
794
+ /** Render a compact tree: status, live attempts, points and title, indented by parent. */
795
+ export function tasksCommand(client: Client, input: TasksInput = {}): Promise<CommandResult<TasksResponse>> {
796
+ return client.tasks().then((overview) => ({ text: renderTasks(overview, input), data: overview }));
797
+ }
798
+
799
+ /** One task line: status first, `N live` only when the task is actually open. */
800
+ export function renderTaskLine(
801
+ task: TasksResponse["tasks"][number],
802
+ depth = 0,
803
+ area = false,
804
+ ): string {
805
+ const status = task.status === "open" && task.live > 0
806
+ ? `open · ${task.live} live`
807
+ : task.status;
808
+ const line = `${task.id} ${status.padEnd(10)} ${task.points} pts ${task.title}${area ? " [area]" : ""}`;
809
+ return `${" ".repeat(depth)}${line}`;
810
+ }
811
+
812
+ export function renderTasks(overview: TasksResponse, input: TasksInput = {}): string {
813
+ const byId = new Map(overview.tasks.map((t) => [t.id, t]));
814
+ const children = new Map<string | null, typeof overview.tasks>();
815
+ for (const t of overview.tasks) {
816
+ const parent = t.parent && byId.has(t.parent) ? t.parent : null;
817
+ const list = children.get(parent) ?? [];
818
+ list.push(t);
819
+ children.set(parent, list);
820
+ }
821
+
822
+ const lines: string[] = [];
823
+ const seen = new Set<string>();
824
+ const visit = (parent: string | null, depth: number): void => {
825
+ for (const t of children.get(parent) ?? []) {
826
+ if (seen.has(t.id)) continue;
827
+ seen.add(t.id);
828
+ if (!input.openOnly || t.status === "open") {
829
+ lines.push(renderTaskLine(t, depth, byId.get(t.id)?.leaf === false));
830
+ }
831
+ visit(t.id, depth + 1);
832
+ }
833
+ };
834
+ visit(null, 0);
835
+ // Orphans of a cycle still deserve a line.
836
+ for (const t of overview.tasks) {
837
+ if (!seen.has(t.id)) {
838
+ seen.add(t.id);
839
+ if (!input.openOnly || t.status === "open") {
840
+ lines.push(renderTaskLine(t, 0, !t.leaf));
841
+ }
842
+ }
843
+ }
844
+
845
+ const footer = overview.done ? "project finished" : `open leaf tasks: ${overview.open}`;
846
+ return lines.length > 0 ? [...lines, "", footer].join("\n") : footer;
847
+ }
848
+
679
849
  // ---------------------------------------------------------------- head
680
850
 
681
851
  export interface HeadKeygenOutput {
@@ -768,6 +938,28 @@ export async function headBanCommand(
768
938
  return { text: `banned ${input.agent}`, data: response };
769
939
  }
770
940
 
941
+ export interface HeadNoteInput {
942
+ task: TaskId;
943
+ text: string;
944
+ kind?: NoteKind;
945
+ }
946
+
947
+ /** Leaves a note as the head; defaults to the server's `result` kind. */
948
+ export async function headNoteCommand(
949
+ client: Client,
950
+ input: HeadNoteInput,
951
+ ): Promise<CommandResult<HeadNoteResponse>> {
952
+ const response = await client.headNote({
953
+ task: input.task,
954
+ text: input.text,
955
+ ...(input.kind !== undefined ? { kind: input.kind } : {}),
956
+ });
957
+ return {
958
+ text: `note ${response.note.id} on ${input.task} (${response.note.kind})`,
959
+ data: response,
960
+ };
961
+ }
962
+
771
963
  export interface HeadCloseInput {
772
964
  task: TaskId;
773
965
  status: "withdrawn" | "impossible" | "solved";
@@ -7,23 +7,26 @@ import type { FetchLike } from "./client.ts";
7
7
  import { createClient } from "./client.ts";
8
8
  import type { Client } from "./client.ts";
9
9
  import {
10
- beatCommand, boardCommand, headBanCommand, headCloseCommand, headDecideCommand, headKeygenCommand,
11
- headPostCommand, headRuleCommand, joinCommand, nextCommand, noteCommand, parseClaim,
10
+ beatCommand, boardCommand, fitSubmitMessage, headBanCommand, headCloseCommand, headDecideCommand,
11
+ headKeygenCommand, headNoteCommand, headPostCommand, headRuleCommand, joinCommand, nextCommand, noteCommand, parseClaim,
12
12
  parseNoteKind, parseRuleArgs, proposeCommand, releaseCommand, resultCommand, statusCommand,
13
- submitCommand, submissionExitCode, voteCommand,
13
+ submitCommand, submissionExitCode, tasksCommand, voteCommand,
14
14
  } from "./commands.ts";
15
- import type { CommandResult, ParsedCli, ParsedValue } from "./commands.ts";
15
+ import type { CommandResult, ParsedCli, ParsedValue, SubmitView } from "./commands.ts";
16
16
  import { doctorCommand } from "./doctor.ts";
17
17
  import { initCommand } from "./init.ts";
18
18
  import type { RuntimeDeps } from "./runtime.ts";
19
19
  import { serveCommand } from "./runtime.ts";
20
- import { agentPath, headPath, readAgent, readHead, resolveDir, writeAgent, writeHead } from "./store.ts";
20
+ import { syncCommand } from "./sync.ts";
21
+ import {
22
+ agentPath, headPath, readAgent, readHead, resolveAgentDir, resolveDir, writeAgent, writeHead,
23
+ } from "./store.ts";
21
24
  import type { SessionIdentity } from "./store.ts";
22
25
 
23
26
  export interface DispatchDeps {
24
27
  dir: string;
25
28
  urlOverride?: string;
26
- /** Progress lines (queued / checking / verdict), never part of --json output. */
29
+ /** Progress lines (queued / checking), written to stderr, never part of --json output. */
27
30
  onProgress?: (line: string) => void;
28
31
  fetchImpl?: FetchLike;
29
32
  runtime?: RuntimeDeps;
@@ -31,7 +34,8 @@ export interface DispatchDeps {
31
34
 
32
35
  export interface DispatchOutcome<T = unknown> {
33
36
  result: CommandResult<T>;
34
- /** 0 ok, 1 error (thrown), 2 rejected submission, 3 no task available. */
37
+ /** 0 ok or assignment, 1 error (thrown), 2 rejected submission,
38
+ * 3 no task free within the wait, 4 project finished (no open tasks left). */
35
39
  code: number;
36
40
  }
37
41
 
@@ -62,17 +66,25 @@ function client(url: string, keys: { publicKey: string; privateKey: string }, de
62
66
 
63
67
  function requireAgent(
64
68
  deps: DispatchDeps,
65
- ): { identity: SessionIdentity; client: Client } {
66
- const identity = readAgent(deps.dir);
69
+ ): { identity: SessionIdentity; identityDir: string; client: Client } {
70
+ const identityDir = resolveAgentDir(deps.dir);
71
+ const identity = readAgent(identityDir);
67
72
  if (!identity) {
68
- throw new Error(`no agent identity at ${agentPath(deps.dir)}; run "minga join <url>" first`);
73
+ throw new Error(`no agent identity at ${agentPath(identityDir)}; run "minga join <url>" first`);
69
74
  }
70
75
  return {
71
76
  identity,
77
+ identityDir,
72
78
  client: client(deps.urlOverride ?? identity.url, identity, deps),
73
79
  };
74
80
  }
75
81
 
82
+ /** Remember accepted files so `minga sync` can clean up after the submit. */
83
+ function acceptedFiles(view: SubmitView): { submission: string; files: string[] } | undefined {
84
+ if (!("id" in view) || view.status !== "accepted") return undefined;
85
+ return { submission: view.id, files: view.files };
86
+ }
87
+
76
88
  function requireHeadClient(deps: DispatchDeps): Client {
77
89
  const identity = readHead(deps.dir);
78
90
  if (!identity) {
@@ -98,7 +110,12 @@ export async function dispatch(cli: ParsedCli, deps: DispatchDeps): Promise<Disp
98
110
  const harness = str(cli.options.harness);
99
111
  if (!model || !harness) throw new Error("join needs --model and --harness");
100
112
  const existing = readAgent(dir);
101
- const keys = existing ? { publicKey: existing.publicKey, privateKey: existing.privateKey } : generateKeyPair();
113
+ // An ancestor identity is reused only for the same project; otherwise
114
+ // join still writes to cwd (or --dir), as documented.
115
+ const reuse = existing !== null && existing.url === url;
116
+ const keys = existing && reuse
117
+ ? { publicKey: existing.publicKey, privateKey: existing.privateKey }
118
+ : generateKeyPair();
102
119
  const { identity, result } = await joinCommand(client(url, keys, deps), {
103
120
  url,
104
121
  keys,
@@ -106,19 +123,31 @@ export async function dispatch(cli: ParsedCli, deps: DispatchDeps): Promise<Disp
106
123
  harness,
107
124
  owner: str(cli.options.owner),
108
125
  });
109
- writeAgent(dir, identity);
126
+ writeAgent(reuse ? resolveAgentDir(dir) : resolveDir(dir), identity);
110
127
  return { result, code: 0 };
111
128
  }
112
129
 
113
130
  case "next": {
114
- const { identity, client: c } = requireAgent(deps);
131
+ const { identity, identityDir, client: c } = requireAgent(deps);
115
132
  const result = await nextCommand(c, {
116
133
  model: modelOf(cli, identity),
117
134
  approach: str(cli.options.approach),
118
135
  wait: intOption(cli.options.wait, "wait") ?? 0,
119
136
  onProgress: deps.onProgress,
120
137
  });
121
- return { result, code: result.data.assignment ? 0 : 3 };
138
+ const a = result.data.assignment;
139
+ if (a) {
140
+ writeAgent(identityDir, {
141
+ ...identity,
142
+ lastAssignment: {
143
+ attempt: a.attempt,
144
+ role: a.role,
145
+ leaseUntil: a.leaseUntil,
146
+ task: a.task.id,
147
+ },
148
+ });
149
+ }
150
+ return { result, code: result.data.done === true ? 4 : result.data.assignment ? 0 : 3 };
122
151
  }
123
152
 
124
153
  case "beat": {
@@ -147,30 +176,41 @@ export async function dispatch(cli: ParsedCli, deps: DispatchDeps): Promise<Disp
147
176
  const attempt = requirePositional(cli, 0, "submit needs an attempt id");
148
177
  const claimText = str(cli.options.claim);
149
178
  if (!claimText) throw new Error("submit needs --claim solves|refutes|progress");
150
- const message = str(cli.options.message);
151
- if (!message) throw new Error('submit needs -m "<message>"');
152
- const { identity, client: c } = requireAgent(deps);
179
+ const rawMessage = str(cli.options.message);
180
+ if (!rawMessage) throw new Error('submit needs -m "<message>"');
181
+ const fitted = fitSubmitMessage(rawMessage);
182
+ if (fitted.notice !== undefined) deps.onProgress?.(fitted.notice);
183
+ const { identity, identityDir, client: c } = requireAgent(deps);
153
184
  const result = await submitCommand(c, {
154
185
  attempt,
155
186
  claim: parseClaim(claimText),
156
- message,
187
+ message: fitted.message,
157
188
  files: cli.positionals.slice(1),
158
189
  root: str(cli.options.root),
159
190
  model: modelOf(cli, identity),
160
191
  wait: cli.options.wait !== false,
161
192
  onProgress: deps.onProgress,
162
193
  });
194
+ const submission = "submission" in result.data ? result.data.submission : result.data.id;
195
+ const accepted = acceptedFiles(result.data);
196
+ writeAgent(identityDir, {
197
+ ...identity,
198
+ lastSubmission: submission,
199
+ ...(accepted !== undefined ? { lastAccepted: accepted } : {}),
200
+ });
163
201
  return { result, code: submissionExitCode(result.data) };
164
202
  }
165
203
 
166
204
  case "result": {
167
205
  const submission = requirePositional(cli, 0, "result needs a submission id (S-n)");
168
- const { client: c } = requireAgent(deps);
206
+ const { identity, identityDir, client: c } = requireAgent(deps);
169
207
  const result = await resultCommand(c, {
170
208
  submission,
171
209
  wait: cli.options.wait === true,
172
210
  onProgress: deps.onProgress,
173
211
  });
212
+ const accepted = acceptedFiles(result.data);
213
+ if (accepted !== undefined) writeAgent(identityDir, { ...identity, lastAccepted: accepted });
174
214
  return { result, code: submissionExitCode(result.data) };
175
215
  }
176
216
 
@@ -222,7 +262,7 @@ export async function dispatch(cli: ParsedCli, deps: DispatchDeps): Promise<Disp
222
262
 
223
263
  case "status": {
224
264
  const { identity, client: c } = requireAgent(deps);
225
- return { result: await statusCommand(c, identity.agent), code: 0 };
265
+ return { result: await statusCommand(c, identity), code: 0 };
226
266
  }
227
267
 
228
268
  case "board": {
@@ -230,6 +270,16 @@ export async function dispatch(cli: ParsedCli, deps: DispatchDeps): Promise<Disp
230
270
  return { result: await boardCommand(c), code: 0 };
231
271
  }
232
272
 
273
+ case "tasks": {
274
+ const { client: c } = requireAgent(deps);
275
+ return { result: await tasksCommand(c, { openOnly: cli.options.open === true }), code: 0 };
276
+ }
277
+
278
+ case "sync": {
279
+ const result = syncCommand({ dir, discard: cli.options.discard === true });
280
+ return { result, code: result.data.refused ? 1 : 0 };
281
+ }
282
+
233
283
  case "init": {
234
284
  const required = (name: string): string => {
235
285
  const value = str(cli.options[name]);
@@ -325,6 +375,21 @@ export async function dispatch(cli: ParsedCli, deps: DispatchDeps): Promise<Disp
325
375
  return { result: await headBanCommand(c, { agent, reason }), code: 0 };
326
376
  }
327
377
 
378
+ if (action === "note") {
379
+ const task = requirePositional(cli, 0, "head note needs a task id");
380
+ const text = cli.positionals.slice(1).join(" ");
381
+ if (text.length === 0) throw new Error("head note needs some text");
382
+ const kindText = str(cli.options.kind);
383
+ return {
384
+ result: await headNoteCommand(c, {
385
+ task,
386
+ text,
387
+ ...(kindText !== undefined ? { kind: parseNoteKind(kindText) } : {}),
388
+ }),
389
+ code: 0,
390
+ };
391
+ }
392
+
328
393
  if (action === "close") {
329
394
  const task = requirePositional(cli, 0, "head close needs a task id");
330
395
  const status = requirePositional(cli, 1, "head close needs withdrawn, impossible or solved");