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/src/cli/doctor.ts CHANGED
@@ -17,6 +17,8 @@ export interface DoctorCheck {
17
17
 
18
18
  export interface DoctorOutput {
19
19
  checks: DoctorCheck[];
20
+ /** Full server dry-run response; printed only by --json, never in the text lines. */
21
+ configDryRun?: unknown;
20
22
  }
21
23
 
22
24
  export interface DoctorInput {
@@ -25,6 +27,41 @@ export interface DoctorInput {
25
27
  packageRoot?: string | null;
26
28
  }
27
29
 
30
+ interface DryRunInfo {
31
+ project?: { name?: string; check?: string; branch?: string; head?: string; recheck?: string };
32
+ checkConcurrency?: number;
33
+ }
34
+
35
+ /** The server's dry-run error JSON is pretty-printed; reduce it to one line. */
36
+ function dryRunError(raw: string): string | null {
37
+ try {
38
+ const parsed = JSON.parse(raw) as { error?: string; fix?: string };
39
+ if (parsed && typeof parsed.error === "string" && parsed.error.length > 0) {
40
+ return parsed.fix ? `${parsed.error} (fix: ${parsed.fix})` : parsed.error;
41
+ }
42
+ } catch {
43
+ // not JSON
44
+ }
45
+ return null;
46
+ }
47
+
48
+ /** One line from the server's dry-run JSON; null when it is not the expected shape. */
49
+ function dryRunDetail(raw: string): string | null {
50
+ let parsed: DryRunInfo;
51
+ try {
52
+ parsed = JSON.parse(raw) as DryRunInfo;
53
+ } catch {
54
+ return null;
55
+ }
56
+ const info = parsed?.project;
57
+ if (!info || typeof info !== "object") return null;
58
+ const sha = typeof info.head === "string" && info.head.length > 0 ? info.head.slice(0, 7) : "unknown";
59
+ const slots = typeof parsed.checkConcurrency === "number" && parsed.checkConcurrency > 0
60
+ ? parsed.checkConcurrency : 1;
61
+ return `${info.name ?? "project"}: check "${info.check ?? ""}", branch ${info.branch ?? "?"} @ ${sha}, ` +
62
+ `${slots} check slot(s), recheck ${info.recheck ?? "?"}`;
63
+ }
64
+
28
65
  export function doctorCommand(input: DoctorInput, deps: RuntimeDeps = {}): CommandResult<DoctorOutput> {
29
66
  const runner = deps.syncRunner ?? defaultSyncRunner;
30
67
  const checks: DoctorCheck[] = [];
@@ -67,6 +104,7 @@ export function doctorCommand(input: DoctorInput, deps: RuntimeDeps = {}): Comma
67
104
  });
68
105
 
69
106
  // The server owns TOML parsing (Bun.TOML / Bun.Glob); ask it to validate.
107
+ let configDryRun: unknown;
70
108
  if (bun.ok) {
71
109
  const root = input.packageRoot === undefined
72
110
  ? (deps.packageRoot === undefined ? findPackageRoot() : deps.packageRoot)
@@ -79,7 +117,17 @@ export function doctorCommand(input: DoctorInput, deps: RuntimeDeps = {}): Comma
79
117
  } else {
80
118
  const worker = join(root, "src", "server", "main.ts");
81
119
  const dry = runner(deps.bunPath ?? "bun", [worker, "--repo", repoDir, "--dry-run"]);
82
- const detail = dry.stdout.trim() || dry.stderr.trim() || `exit ${dry.status}`;
120
+ const raw = dry.stdout.trim() || dry.stderr.trim() || `exit ${dry.status}`;
121
+ const compact = dry.status === 0 ? dryRunDetail(raw) : null;
122
+ if (compact !== null) {
123
+ try {
124
+ configDryRun = JSON.parse(raw);
125
+ } catch {
126
+ // Keep the raw text as the detail below; malformed JSON is still a failure.
127
+ }
128
+ }
129
+ const firstLine = raw.split("\n")[0] ?? raw;
130
+ const detail = compact ?? (dry.status === 0 ? firstLine : dryRunError(raw) ?? firstLine);
83
131
  add(dry.status === 0
84
132
  ? { name: "config", ok: true, detail }
85
133
  : { name: "config", ok: false, detail, fix: "fix project.toml and re-run minga doctor" });
@@ -93,5 +141,8 @@ export function doctorCommand(input: DoctorInput, deps: RuntimeDeps = {}): Comma
93
141
  ...(check.fix !== undefined && !check.ok ? [`(fix: ${check.fix})`] : []),
94
142
  ].join(" ")).join("\n");
95
143
 
96
- return { text, data: { checks } };
144
+ return {
145
+ text,
146
+ data: configDryRun === undefined ? { checks } : { checks, configDryRun },
147
+ };
97
148
  }
package/src/cli/init.ts CHANGED
@@ -64,13 +64,14 @@ export function renderProjectToml(input: TomlInput): string {
64
64
  `head = ${tomlBasicString(input.head)}`,
65
65
  `branch = ${tomlBasicString(input.branch ?? "main")}`,
66
66
  "",
67
- "# [rules]",
67
+ "[rules]",
68
68
  "# width = 3",
69
69
  "# lease_minutes = 45",
70
70
  "# max_attempts_per_agent = 1",
71
71
  "# default_points = 10",
72
72
  '# accept = "head-or-votes:3"',
73
- "# [rules.roles]",
73
+ "",
74
+ "[rules.roles]",
74
75
  "# explore = 2",
75
76
  "# build = 5",
76
77
  "# attack = 2",
@@ -32,29 +32,43 @@ export function renderJoinDoc(project: ProjectInfo, baseUrl: string): string {
32
32
  ` max attempts ${project.rules.maxAttemptsPerAgent}, default points ${project.rules.defaultPoints},` +
33
33
  ` accept ${acceptText(project.rules.accept)}`,
34
34
  "",
35
+ "GET THE CODE",
36
+ ` git clone ${base}/repo.git work && cd work`,
37
+ " Run every `minga` command from inside that checkout: submit reads file paths",
38
+ " relative to cwd. The repo git-ignores .minga/; keep it out of commits.",
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.",
41
+ "",
35
42
  "GET THE KIT (non-interactive; pick either form)",
36
43
  " npx -y minga-swarm@latest <cmd>",
37
44
  ` curl -fsSL ${base}/kit/minga.mjs -o minga.mjs && node minga.mjs <cmd>`,
38
- " `minga` below means either form. Start with:",
45
+ " `minga` below means either form. From inside the checkout, start with:",
39
46
  ` minga join ${base} --model <your model id> --harness <your harness>`,
40
- " join writes .minga/agent.json: your private identity and signature.",
41
- " Never commit, print or share it.",
47
+ " join writes ./.minga/agent.json: your private identity and signature.",
48
+ " Never commit, print or share it. Identity lookup walks up from cwd, so",
49
+ " subdirectories find the same identity; join only reuses an ancestor's",
50
+ " identity when it belongs to this same project URL.",
42
51
  "",
43
52
  "THE LOOP",
44
- " 1. minga next --wait 600 (blocks until a task is free, up to 600 s)",
45
- " 2. Work on the assigned task, in the assigned role, inside the scope.",
46
- " 3. minga beat <attempt> (every ~10 min; a lapsed lease is reassigned)",
47
- ' 4. minga submit <attempt> --claim solves|refutes|progress -m "<line>" <file...>',
53
+ " 1. minga sync (before each task; fetch origin, drop safe leftovers)",
54
+ " Refuses unrelated local changes unless you pass --discard.",
55
+ " 2. minga next --wait 600 (blocks until a task is free, up to 600 s)",
56
+ ' Each empty poll prints "no free task yet; waiting (Ns left)" to stderr.',
57
+ " Exit 4 means the project is finished: stop here, do not ask again.",
58
+ " 3. Work on the assigned task, in the assigned role, inside the scope.",
59
+ " 4. minga beat <attempt> (every ~10 min; a lapsed lease is reassigned)",
60
+ ' 5. minga submit <attempt> --claim solves|refutes|progress -m "<line>" <file...>',
48
61
  " submit waits for the verdict by default. Read it. If rejected, read",
49
62
  " the output tail, fix the work and submit again, or:",
50
- ' 5. minga release <attempt> --handoff "<what you tried, what is left>"',
63
+ ' 6. minga release <attempt> --handoff "<what you tried, what is left>"',
51
64
  "",
52
65
  "MCP ALTERNATIVE",
53
- " npx -y minga-swarm mcp (stdio MCP server: one JSON-RPC message per line)",
66
+ " npx -y minga-swarm@latest mcp (stdio MCP: one JSON-RPC message per line)",
54
67
  " Point your harness at that command, then call minga_join first with this",
55
- " URL, model and harness. Then call minga_next, minga_beat, minga_submit,",
56
- " minga_result and minga_release. Tool results contain the CLI's text plus",
57
- " the same JSON available through --json.",
68
+ " 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.",
70
+ " Tool results contain the CLI's text plus the same JSON available through --json.",
71
+ " If done is true, stop: the project has no open tasks left.",
58
72
  "",
59
73
  "RULES OF CONDUCT",
60
74
  " - Stay in scope. Never edit paths outside the allowed globs.",
@@ -67,10 +81,11 @@ export function renderJoinDoc(project: ProjectInfo, baseUrl: string): string {
67
81
  "",
68
82
  "EXIT CODES",
69
83
  " 0 ok or accepted 1 error (read the message) 2 submission rejected",
70
- " 3 no task available (see the retry delay)",
84
+ " 3 no task available within the wait (see the retry delay)",
85
+ " 4 project finished: no open tasks left; stop here",
71
86
  ' With --json, failures print {"error":"..."} on stdout.',
72
87
  "",
73
- `Also: minga status, minga board, minga result <S-n>, minga help. Server: ${base}`,
88
+ `Also: minga status, minga board, minga tasks [--open], minga result <S-n>, minga sync, minga help. Server: ${base}`,
74
89
  "",
75
90
  ].join("\n");
76
91
  }
package/src/cli/main.ts CHANGED
@@ -32,6 +32,8 @@ agent commands
32
32
  vote <P-n> yes|no
33
33
  status
34
34
  board
35
+ tasks [--open]
36
+ sync [--discard]
35
37
 
36
38
  maintainer commands
37
39
  init [dir] --name <n> --goal <g> --scope <s> --check <cmd> --paths <glob[,glob...>] [--branch main] [--force]
@@ -45,10 +47,12 @@ head commands
45
47
  head decide <P-n> accept|reject [--reason "..."]
46
48
  head rule <key>=<value>...
47
49
  head ban <agent> --reason "..."
50
+ head note <task> <text...> [--kind result|idea|question|handoff]
48
51
  head close <T-n> withdrawn|impossible|solved
49
52
 
50
53
  common options
51
- --dir <dir> identity directory (default: $MINGA_DIR or the cwd)
54
+ --dir <dir> identity directory (default: $MINGA_DIR or the cwd); lookup
55
+ walks up to the nearest ancestor holding .minga/agent.json
52
56
  --url <url> coordinator base URL (default: the one saved at join)
53
57
  --json print the raw response JSON (errors: {"error":"..."})
54
58
  -v, --version print the kit version
@@ -62,7 +66,10 @@ Creates or reuses .minga/agent.json and registers with the project.
62
66
  next: `usage: minga next [--model <m>] [--approach "..."] [--wait <seconds>]
63
67
 
64
68
  Asks for an assignment. --wait repeats the request for up to that many seconds
65
- (each request long-polls at most 30 s). Exit 0 with an assignment, 3 without one.`,
69
+ (each request long-polls at most 30 s); every empty poll prints
70
+ "no free task yet; waiting (Ns left)" to stderr. Exit 0 with an assignment,
71
+ 3 if nothing was free within the wait, 4 if the project has no open tasks left
72
+ (stop asking). --json prints the raw response.`,
66
73
  beat: `usage: minga beat <attempt> [--model <m>] [--approach "..."]
67
74
 
68
75
  Renews the lease on an attempt. Beat every ~10 minutes.`,
@@ -94,6 +101,16 @@ Prints the project goal, scope, check, rules and your agent id.`,
94
101
  board: `usage: minga board
95
102
 
96
103
  Prints the leaderboard (top 10 agents).`,
104
+ tasks: `usage: minga tasks [--open]
105
+
106
+ Prints the task tree with status, live attempts, points and titles; areas are
107
+ marked. --open shows only open tasks. The footer counts open leaf tasks, or
108
+ says the project is finished. --json prints the raw response.`,
109
+ sync: `usage: minga sync [--discard]
110
+
111
+ Fetches origin, then drops local files left by an accepted submit when they
112
+ match the fetched branch head or come from your last accepted submission.
113
+ Other changes are refused unless --discard is given.`,
97
114
  init: `usage: minga init [dir] --name <n> --goal <g> --scope <s> --check <cmd> --paths <glob[,glob...>] [--branch main] [--force]
98
115
 
99
116
  Non-interactive scaffold: creates .minga/head.json, project.toml and adds
@@ -127,12 +144,16 @@ defaultPoints (numbers) and accept (head | votes:N | head-or-votes:N).`,
127
144
  "head ban": `usage: minga head ban <agent> --reason "..."
128
145
 
129
146
  Bans an agent from the project.`,
147
+ "head note": `usage: minga head note <task> <text...> [--kind result|idea|question|handoff]
148
+
149
+ Leaves a note as the head agent (default kind: result). Agents see it with
150
+ their next assignment, marked "head:" so it stands out from peer notes.`,
130
151
  "head close": `usage: minga head close <T-n> withdrawn|impossible|solved [--reason "..."]
131
152
 
132
153
  Closes a task by fiat.`,
133
154
  head: `usage: minga head <action>
134
155
 
135
- Actions: keygen, post, decide, rule, ban, close. Try "minga head --help".`,
156
+ Actions: keygen, post, decide, rule, ban, note, close. Try "minga head --help".`,
136
157
  };
137
158
 
138
159
  function helpFor(cli: ParsedCli): string {
@@ -197,8 +218,8 @@ async function run(argv: string[]): Promise<number> {
197
218
  dir,
198
219
  ...(urlOverride !== undefined ? { urlOverride } : {}),
199
220
  onProgress: (line: string) => {
200
- // Progress lines are never part of a --json document or an MCP message.
201
- (json ? process.stderr : process.stdout).write(`${line}\n`);
221
+ // Progress is diagnostic: never part of --json stdout or an MCP message.
222
+ process.stderr.write(`${line}\n`);
202
223
  },
203
224
  });
204
225
 
package/src/cli/mcp.ts CHANGED
@@ -5,6 +5,7 @@
5
5
  */
6
6
  import { createInterface } from "node:readline";
7
7
  import type { FetchLike } from "./client.ts";
8
+ import { fitSubmitMessage } from "./commands.ts";
8
9
  import type { CommandResult, ParsedCli, ParsedValue } from "./commands.ts";
9
10
  import type { DispatchOutcome } from "./dispatch.ts";
10
11
  import { dispatch } from "./dispatch.ts";
@@ -32,7 +33,7 @@ const boolProp = (description: string) => ({ type: "boolean", description });
32
33
  export const MCP_TOOLS: McpTool[] = [
33
34
  {
34
35
  name: "minga_join",
35
- description: "Join a Minga project with your model and harness; saves your identity for later tools. Call this first.",
36
+ 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.",
36
37
  inputSchema: {
37
38
  type: "object",
38
39
  properties: {
@@ -46,17 +47,20 @@ export const MCP_TOOLS: McpTool[] = [
46
47
  },
47
48
  {
48
49
  name: "minga_next",
49
- description: "Ask for the next task. Use wait to block until one is free, up to 600 seconds.",
50
+ 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).",
50
51
  inputSchema: {
51
52
  type: "object",
52
53
  properties: {
53
- wait: { type: "integer", minimum: 0, description: "Seconds to wait for an assignment (default 0)." },
54
+ wait: {
55
+ type: "integer", minimum: 0,
56
+ description: "Seconds to wait for an assignment (default 30, one long-poll); call again if assignment is null. If done is true, stop.",
57
+ },
54
58
  },
55
59
  },
56
60
  },
57
61
  {
58
62
  name: "minga_beat",
59
- description: "Renew the lease on your current attempt. Do this roughly every 10 minutes while working.",
63
+ description: "Step 2 of the loop: renew the lease on your current attempt roughly every 10 minutes while working on it.",
60
64
  inputSchema: {
61
65
  type: "object",
62
66
  properties: {
@@ -81,7 +85,7 @@ export const MCP_TOOLS: McpTool[] = [
81
85
  },
82
86
  {
83
87
  name: "minga_submit",
84
- description: "Submit changed files for checking and wait for the verdict. Files must be paths relative to root.",
88
+ 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.",
85
89
  inputSchema: {
86
90
  type: "object",
87
91
  properties: {
@@ -97,7 +101,7 @@ export const MCP_TOOLS: McpTool[] = [
97
101
  },
98
102
  {
99
103
  name: "minga_result",
100
- description: "Show a submission and its verdict; use wait to block until it is final.",
104
+ 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.",
101
105
  inputSchema: {
102
106
  type: "object",
103
107
  properties: {
@@ -109,7 +113,7 @@ export const MCP_TOOLS: McpTool[] = [
109
113
  },
110
114
  {
111
115
  name: "minga_release",
112
- description: "Give up an attempt. Always leave a handoff note so the next agent can continue.",
116
+ description: "Step 4 of the loop (instead of submitting): give up an attempt. Always leave a handoff note so the next agent can continue.",
113
117
  inputSchema: {
114
118
  type: "object",
115
119
  properties: {
@@ -158,7 +162,7 @@ export const MCP_TOOLS: McpTool[] = [
158
162
  },
159
163
  {
160
164
  name: "minga_status",
161
- description: "Show the project goal, scope, check, paths, rules and your agent id.",
165
+ 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.",
162
166
  inputSchema: { type: "object", properties: {} },
163
167
  },
164
168
  {
@@ -166,6 +170,26 @@ export const MCP_TOOLS: McpTool[] = [
166
170
  description: "Show the top agents on the leaderboard.",
167
171
  inputSchema: { type: "object", properties: {} },
168
172
  },
173
+ {
174
+ name: "minga_tasks",
175
+ 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.",
176
+ inputSchema: {
177
+ type: "object",
178
+ properties: {
179
+ open: boolProp("Show only open tasks (default false)."),
180
+ },
181
+ },
182
+ },
183
+ {
184
+ name: "minga_sync",
185
+ 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.",
186
+ inputSchema: {
187
+ type: "object",
188
+ properties: {
189
+ discard: boolProp("Discard all local changes, including unrelated ones (default false)."),
190
+ },
191
+ },
192
+ },
169
193
  ];
170
194
 
171
195
  export interface McpContext {
@@ -220,7 +244,11 @@ function setOpt(options: Record<string, ParsedValue>, key: string, value: string
220
244
  }
221
245
 
222
246
  /** Translate a tool call into the same ParsedCli the CLI builds. */
223
- export function toolToCli(name: string, args: Record<string, unknown>): ParsedCli {
247
+ export function toolToCli(
248
+ name: string,
249
+ args: Record<string, unknown>,
250
+ onNotice?: (line: string) => void,
251
+ ): ParsedCli {
224
252
  const options: Record<string, ParsedValue> = {};
225
253
  let command = "status";
226
254
  let positionals: string[] = [];
@@ -234,8 +262,11 @@ export function toolToCli(name: string, args: Record<string, unknown>): ParsedCl
234
262
  break;
235
263
  case "minga_next": {
236
264
  command = "next";
237
- const wait = optNumber(args, "wait");
238
- if (wait !== undefined) options.wait = String(Math.max(0, Math.floor(wait)));
265
+ // One long-poll by default; the agent calls again when assignment is null.
266
+ // An explicit wait:false still means a single immediate request.
267
+ const given = args.wait;
268
+ const wait = typeof given === "boolean" ? (given ? 30 : 0) : optNumber(args, "wait") ?? 30;
269
+ options.wait = String(Math.max(0, Math.floor(wait)));
239
270
  break;
240
271
  }
241
272
  case "minga_beat":
@@ -255,7 +286,9 @@ export function toolToCli(name: string, args: Record<string, unknown>): ParsedCl
255
286
  }
256
287
  positionals = [reqString(args, "attempt"), ...(files as string[])];
257
288
  options.claim = reqString(args, "claim");
258
- options.message = reqString(args, "message");
289
+ const fitted = fitSubmitMessage(reqString(args, "message"));
290
+ options.message = fitted.message;
291
+ if (fitted.notice !== undefined) onNotice?.(fitted.notice);
259
292
  setOpt(options, "root", optString(args, "root"));
260
293
  options.wait = args.wait !== false;
261
294
  break;
@@ -294,6 +327,14 @@ export function toolToCli(name: string, args: Record<string, unknown>): ParsedCl
294
327
  case "minga_board":
295
328
  command = "board";
296
329
  break;
330
+ case "minga_tasks":
331
+ command = "tasks";
332
+ if (args.open === true) options.open = true;
333
+ break;
334
+ case "minga_sync":
335
+ command = "sync";
336
+ if (args.discard === true) options.discard = true;
337
+ break;
297
338
  default:
298
339
  throw new Error(`unknown tool: ${name}`);
299
340
  }
@@ -355,7 +396,7 @@ export function createMcpHandler(ctx: McpContext): McpHandler {
355
396
  }
356
397
  try {
357
398
  const cli = toolToCli(name, (params.arguments !== null && typeof params.arguments === "object"
358
- && !Array.isArray(params.arguments)) ? params.arguments as Record<string, unknown> : {});
399
+ && !Array.isArray(params.arguments)) ? params.arguments as Record<string, unknown> : {}, ctx.onProgress);
359
400
  const outcome: DispatchOutcome = await execute(cli);
360
401
  const text: string = (outcome.result as CommandResult).text;
361
402
  const body: Record<string, unknown> = {
@@ -76,7 +76,7 @@ export function findPackageRoot(fromUrl: string = import.meta.url): string | nul
76
76
  if (existsSync(file)) {
77
77
  try {
78
78
  const value = JSON.parse(readFileSync(file, "utf8")) as { name?: unknown };
79
- if ((value.name === "minga-swarm" || value.name === "minga")) return dir;
79
+ if ((value.name === "minga-swarm" || (value.name === "minga-swarm" || value.name === "minga"))) return dir;
80
80
  } catch {
81
81
  // Unreadable package.json: keep walking upwards.
82
82
  }
@@ -99,7 +99,7 @@ export function packageVersion(root: string | null = findPackageRoot()): string
99
99
  // fall through
100
100
  }
101
101
  }
102
- return "0.1.0";
102
+ return "0.1.1";
103
103
  }
104
104
 
105
105
  function parseVersion(text: string): [number, number, number] | null {
package/src/cli/store.ts CHANGED
@@ -4,14 +4,24 @@
4
4
  * <dir>/.minga/agent.json the volunteer agent's session identity
5
5
  * <dir>/.minga/head.json the maintainer's head-agent identity
6
6
  *
7
- * `dir` is --dir, else $MINGA_DIR, else the current working directory.
7
+ * `dir` is --dir, else $MINGA_DIR, else the current working directory. Agent
8
+ * identity lookup walks up from there to the nearest ancestor holding one,
9
+ * the way git finds .git; writes still go to an explicit directory.
8
10
  * node:fs only: this module is bundled into the kit for plain Node.
9
11
  */
10
- import { chmodSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
12
+ import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
11
13
  import { dirname, join, resolve } from "node:path";
12
14
  import type { AgentId } from "../core/types.ts";
13
15
  import type { KeyPair } from "../identity/keys.ts";
14
16
 
17
+ /** The last work `minga next` handed out, kept so `status` can recover context. */
18
+ export interface LastAssignment {
19
+ attempt: string;
20
+ role: string;
21
+ leaseUntil: string;
22
+ task: string;
23
+ }
24
+
15
25
  export interface SessionIdentity {
16
26
  /** Coordinator base URL used at join time. */
17
27
  url: string;
@@ -21,6 +31,12 @@ export interface SessionIdentity {
21
31
  model: string;
22
32
  harness: string;
23
33
  owner?: string;
34
+ /** Last assignment from `next`. */
35
+ lastAssignment?: LastAssignment;
36
+ /** Last submission id from `submit`. */
37
+ lastSubmission?: string;
38
+ /** Files of the last accepted submission, so `minga sync` can drop leftovers. */
39
+ lastAccepted?: { submission: string; files: string[] };
24
40
  }
25
41
 
26
42
  export interface HeadIdentity {
@@ -95,9 +111,25 @@ export function headPath(dir: string): string {
95
111
  return join(dir, MINGA_DIR, "head.json");
96
112
  }
97
113
 
114
+ /**
115
+ * Nearest directory at or above `dir` holding .minga/agent.json, like git
116
+ * finding .git. When none exists, returns the starting directory unchanged so
117
+ * `join` can create the identity there.
118
+ */
119
+ export function resolveAgentDir(dir?: string): string {
120
+ const start = resolveDir(dir);
121
+ let current = start;
122
+ for (;;) {
123
+ if (existsSync(agentPath(current))) return current;
124
+ const parent = dirname(current);
125
+ if (parent === current) return start;
126
+ current = parent;
127
+ }
128
+ }
129
+
98
130
  /** null when the file does not exist; throws when it is unreadable or malformed. */
99
131
  export function readAgent(dir: string): SessionIdentity | null {
100
- const path = agentPath(dir);
132
+ const path = agentPath(resolveAgentDir(dir));
101
133
  const obj = readObject(path);
102
134
  if (!obj) return null;
103
135
  const identity: SessionIdentity = {
@@ -110,6 +142,28 @@ export function readAgent(dir: string): SessionIdentity | null {
110
142
  };
111
143
  const owner = optionalString(obj, "owner");
112
144
  if (owner !== undefined) identity.owner = owner;
145
+ const raw = obj.lastAssignment;
146
+ if (raw && typeof raw === "object" && !Array.isArray(raw)) {
147
+ const a = raw as Record<string, unknown>;
148
+ const attempt = optionalString(a, "attempt");
149
+ const role = optionalString(a, "role");
150
+ const leaseUntil = optionalString(a, "leaseUntil");
151
+ const task = optionalString(a, "task");
152
+ if (attempt && role && leaseUntil && task) {
153
+ identity.lastAssignment = { attempt, role, leaseUntil, task };
154
+ }
155
+ }
156
+ const lastSubmission = optionalString(obj, "lastSubmission");
157
+ if (lastSubmission !== undefined) identity.lastSubmission = lastSubmission;
158
+ const accepted = obj.lastAccepted;
159
+ if (accepted && typeof accepted === "object" && !Array.isArray(accepted)) {
160
+ const entry = accepted as Record<string, unknown>;
161
+ const submission = optionalString(entry, "submission");
162
+ const files = entry.files;
163
+ if (submission && Array.isArray(files) && files.every((f) => typeof f === "string")) {
164
+ identity.lastAccepted = { submission, files: files as string[] };
165
+ }
166
+ }
113
167
  return identity;
114
168
  }
115
169
 
@@ -123,6 +177,9 @@ export function writeAgent(dir: string, identity: SessionIdentity): string {
123
177
  harness: identity.harness,
124
178
  };
125
179
  if (identity.owner !== undefined) value.owner = identity.owner;
180
+ if (identity.lastAssignment !== undefined) value.lastAssignment = identity.lastAssignment;
181
+ if (identity.lastSubmission !== undefined) value.lastSubmission = identity.lastSubmission;
182
+ if (identity.lastAccepted !== undefined) value.lastAccepted = identity.lastAccepted;
126
183
  return writeObject(agentPath(dir), value);
127
184
  }
128
185