@nodii/dev 0.6.54 → 0.6.56

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/README.md CHANGED
@@ -118,7 +118,10 @@ nodii-dev inbox show drift|request|question ID
118
118
  nodii-dev drift file --service ID --severity local|consumer-visible|breaking
119
119
  --summary TEXT (--body TEXT|--body-file FILE)
120
120
  [--related-artifact-type TYPE --related-artifact-id ID]
121
- nodii-dev drift list|show|resolve|triage
121
+ nodii-dev drift accept ID --decision DEC-nnnn [--reason TEXT] # staff or steward only
122
+ nodii-dev drift resolve ID --reason TEXT # staff or steward only
123
+ nodii-dev drift supersede ID --by DRIFT_ID [--reason TEXT]
124
+ nodii-dev drift list|show|triage
122
125
  nodii-dev request file --from ID --to ID --kind KIND (--spec TEXT|--spec-file FILE)
123
126
  [--required-capability NAME]
124
127
  [--target-artifact-type TYPE --target-artifact-id ID]
@@ -142,7 +145,7 @@ nodii-dev rules show CLAUSE_ID
142
145
  nodii-dev gather tune cases|runs
143
146
  nodii-dev gather tune replay CASE_ID
144
147
  nodii-dev gather tune start --cases all|ID,ID --corpus-ref REF [--pickers P,Q] [--trigger T] [--settings JSON]
145
- nodii-dev gather tune exec RUN_ID [--pickers shortlist-only,gemma-e4b,gemma-12b,gemma-26b]
148
+ nodii-dev gather tune exec RUN_ID [--pickers shortlist-only,gemma-e4b,gemma-12b,gemma-26b] [--concurrency N] # resumable
146
149
  nodii-dev gather tune trial RUN_ID --case ID --picker P --iteration N [--documents A,B]
147
150
  nodii-dev gather tune finalize RUN_ID [--supersedes RUN_ID --reason TEXT]
148
151
  nodii-dev gather tune missed [--document CODE] [--since ISO]
@@ -955,7 +958,13 @@ first.
955
958
  coordinator run and shows its running lanes, orphaned runs and unclaimed
956
959
  results. A live second coordinator is refused; a coordinator whose heartbeat
957
960
  watchdog has recorded it orphaned is recorded as the predecessor of the
958
- takeover. Each `--account RUNTIME:PROFILE` (for example
961
+ takeover. `coordinator start` finds a running run from the local watchdog
962
+ record (CLI-16). Run from that run's own session, it adopts the run again:
963
+ it rewrites the state file and restarts the heartbeater. A run whose session
964
+ has exited and whose last heartbeat is older than 3x its expected interval is
965
+ taken over: its process exit is recorded and the start runs again, so Dev
966
+ records the takeover. A stale run whose session is still alive is refused,
967
+ since its process did not exit. Each `--account RUNTIME:PROFILE` (for example
959
968
  `--account claude:/Users/me/.claude-work`) registers that model account on
960
969
  the machine, and the command then reports every registered account's usage.
961
970
 
@@ -991,7 +1000,11 @@ watchdog sweep re-reports every account every 5 minutes (install it with
991
1000
  `coordinator-NAME.heartbeat.pid` next to the config) tied to the coordinator
992
1001
  session's process. It heartbeats the run at half its expected interval while
993
1002
  the session lives, ends the run (`done`) when the session exits, and stops
994
- without touching a run that a later `coordinator start` replaced.
1003
+ without touching a run that a later `coordinator start` replaced. Only a
1004
+ state file that names another run counts as replaced: a missing
1005
+ `coordinator-NAME.json` is written again from Dev's run, and the heartbeater
1006
+ keeps beating. `lane launch` with no state file likewise uses Dev's running
1007
+ coordinator run for the machine when it belongs to the caller (CLI-16).
995
1008
 
996
1009
  `lane launch KEY` replaces the manual worktree/start/process sequence. It
997
1010
  requires the issue (whose title supplies both lane title and objective), done
package/dist/cli.js CHANGED
@@ -46,6 +46,9 @@ import {
46
46
  figmaScopeSet,
47
47
  figmaScopeSetText,
48
48
  figmaSubmit,
49
+ checkSubmitPayload,
50
+ assertContext,
51
+ resubmitPayload,
49
52
  submitMode,
50
53
  isChangeSetId,
51
54
  scopeText,
@@ -57,7 +60,8 @@ import { tuneCommand } from "./tune.js";
57
60
  import { PICKER_MODEL, TUNING_MODELS, measurePickerLatency, pickTimingStats, pickTimingText, pickTimingsPath, readPickTimings } from "./gather.js";
58
61
  import { docsCommand, rulebookCommand, rulesCommand } from "./upload.js";
59
62
  import { changeSetCommand, guidelineCommand } from "./guidelines.js";
60
- import { designCheck, designCheckText, designRoles, designRolesText } from "./design.js";
63
+ import { designCheck, designCheckChangeSet, designCheckText, designRoles, designRolesText } from "./design.js";
64
+ import { assertKnownFlags } from "./flags.js";
61
65
  import { watchdogCommand } from "./watchdog.js";
62
66
  import { machineCapacityCommand } from "./accounts.js";
63
67
  import {
@@ -114,6 +118,10 @@ Usage: nodii-dev <command> [options] [--json]
114
118
  # blocked and wont_do need --reason; done needs --dev-check
115
119
  inbox list|show
116
120
  drift file | request file
121
+ drift accept <id> --decision DEC-nnnn [--reason TEXT] # staff or steward only (Dev refuses a lane)
122
+ drift resolve <id> --reason TEXT # the operator resolution; staff or steward only
123
+ drift supersede <id> --by DRIFT_ID [--reason TEXT]
124
+ # write commands refuse a flag they do not take (USAGE, exit 2)
117
125
  decisions list|get|search # get DEC-n reads the AD decision with its amends
118
126
  design entries|entry|guide
119
127
  design guideline list [--drafted] [--all] | show ENTRY
@@ -134,7 +142,9 @@ Usage: nodii-dev <command> [options] [--json]
134
142
  figma publish-plan FILE_KEY # what to publish, and what to leave unchecked in Figma's dialog
135
143
  figma published FILE_KEY|CHANGE_SET --figma-version V # a file key marks every awaiting set published
136
144
  figma check|log-write|submit|apply|abandon|release
137
- figma submit CHANGE_SET --file SUBMIT.json [--sync]
145
+ figma submit CHANGE_SET --file SUBMIT.json [--sync] [--dry-run]
146
+ # --dry-run (submit and resubmit) runs Dev's dry run of the
147
+ # submit gate on the same body, as design check --change-set; never writes
138
148
  # SUBMIT.json: { figmaVersion, writeUp, items: [{ figmaNodeId, change, context,
139
149
  # variants: [{ nodeId, name, context, afterPngBase64 }] }] } (DEC-0204);
140
150
  # a missing writeUp, context or variant name, or an item with no variants,
@@ -145,7 +155,7 @@ Usage: nodii-dev <command> [options] [--json]
145
155
  # and poll it (a large set outlasts the edge's timeout); --sync waits
146
156
  # on one request instead. A 502/504 is checked against the set, never resent
147
157
  figma withdraw CHANGE_SET # holder takes back a submit: in_review -> editing (or a re-submit -> applying)
148
- figma resubmit CHANGE_SET PAYLOAD.json [--sync]
158
+ figma resubmit CHANGE_SET PAYLOAD.json [--sync] [--dry-run]
149
159
  # holder re-submits every rejected item: applying -> in_review, round + 1;
150
160
  # each item needs context, each variant name and context; writeUp optional
151
161
  figma changeset show CHANGE_SET # write-up, items, context, variants, round, decision and comment (with the previous round's)
@@ -177,9 +187,11 @@ Usage: nodii-dev <command> [options] [--json]
177
187
  gather tune replay <case-id> # blind replay + trigger shortlist, for the lane-agent picker
178
188
  gather tune start --cases all|ID,ID --corpus-ref REF [--pickers P,Q] [--trigger manual] [--settings JSON]
179
189
  # --pickers: the subset this run scores (default all five)
180
- gather tune exec <run-id> [--pickers shortlist-only,gemma-e4b,gemma-12b,gemma-26b]
190
+ gather tune exec <run-id> [--pickers shortlist-only,gemma-e4b,gemma-12b,gemma-26b] [--concurrency N]
181
191
  # runs each automatic picker the run scores 5x per case; a Gemma
182
- # model this Mac lacks is reported unavailable (exit 1), never filled in
192
+ # model this Mac lacks is reported unavailable (exit 1), never filled in;
193
+ # resumable: a rerun skips the trials an earlier exec recorded;
194
+ # --concurrency 1-8 (default 4) for shortlist-only, Gemma runs 1 at a time
183
195
  gather tune trial <run-id> --case ID --picker P --iteration N [--documents A,B]
184
196
  # one trial; lane-agent passes its own --documents pick
185
197
  gather tune finalize <run-id> [--supersedes <run-id> --reason TEXT]
@@ -621,6 +633,7 @@ export async function main(argv = process.argv.slice(2)) {
621
633
  const json = Boolean(f.json);
622
634
  const [command, action, ...rest] = args;
623
635
  if (!command || f.help || command === "help") return console.log(HELP);
636
+ assertKnownFlags(args, f);
624
637
  if (command === "api") {
625
638
  const catalog = await loadCatalog({ refresh: action === "catalog" && f.refresh === true });
626
639
  const operations = operationsFrom(catalog.spec);
@@ -885,6 +898,30 @@ export async function main(argv = process.argv.slice(2)) {
885
898
  json,
886
899
  );
887
900
  }
901
+ // CLI-19: Dev decides who may accept, resolve or supersede (staff or
902
+ // steward); a lane identity may only file, and Dev refuses it here.
903
+ if (command === "drift" && ["accept", "resolve", "supersede"].includes(action)) {
904
+ const id = rest[0];
905
+ if (!id || rest.length > 1) throw new CliError("USAGE", "drift accept|resolve|supersede <id> --reason TEXT [--decision DEC-nnnn] [--by DRIFT_ID]", 2);
906
+ // The OpenAPI flag names the generic path took still work.
907
+ const text = (value) => (typeof value === "string" && value.trim() ? value.trim() : undefined);
908
+ const reason = text(f.reason) ?? text(f["resolution-md"]);
909
+ const decision = text(f.decision) ?? text(f["related-decision-id"]);
910
+ if (action === "resolve" && f.status !== undefined && f.status !== "accepted-as-canonical")
911
+ throw new CliError("USAGE", `drift resolve takes --status accepted-as-canonical only (that is drift accept); got --status ${f.status}.`, 2);
912
+ const verb = action === "resolve" && f.status === "accepted-as-canonical" ? "accept" : action;
913
+ if (verb === "resolve" && decision) throw new CliError("USAGE", "drift resolve takes no --decision: citing a decision accepts the drift; use drift accept <id> --decision DEC-nnnn.", 2);
914
+ if (verb === "accept" && !decision) throw new CliError("USAGE", "drift accept <id> needs --decision DEC-nnnn: the decision that makes the drift canonical.", 2);
915
+ if (verb === "resolve" && !reason) throw new CliError("USAGE", "drift resolve <id> needs --reason TEXT.", 2);
916
+ const by = text(f.by) ?? text(f["superseding-drift-id"]);
917
+ if (verb === "supersede" && !by) throw new CliError("USAGE", "drift supersede <id> needs --by DRIFT_ID.", 2);
918
+ const [route, body] =
919
+ verb === "accept" ? ["accept", { relatedDecisionId: decision, resolutionMd: reason ?? null }]
920
+ : verb === "resolve" ? ["operator-resolve", { resolutionMd: reason }]
921
+ : ["supersede", { supersedingDriftId: by, resolutionMd: reason ?? null }];
922
+ return emit(await devRequest("POST", `/api/v1/drift/${encode(id)}/${route}`, body), json,
923
+ (p) => `${p.data?.id ?? id}: ${p.data?.status ?? action}.`);
924
+ }
888
925
  if (command === "request" && action === "file") {
889
926
  const specMd = f["spec-file"]
890
927
  ? await readFile(f["spec-file"], "utf8")
@@ -985,6 +1022,30 @@ export async function main(argv = process.argv.slice(2)) {
985
1022
  // change set id keeps the per-set route.
986
1023
  if (action === "published" && rest[0] && !isChangeSetId(rest[0]))
987
1024
  return emit(await figmaFilePublished(rest[0], f.file ? JSON.parse(await readFile(f.file, "utf8")) : { figmaVersion: requireFlag(f, "figma-version") }), json, (p) => figmaFilePublishedText(p.data));
1025
+ // --dry-run runs Dev's dry run of the submit gate (design check --change-set)
1026
+ // on the same body, and never writes (CLI-18).
1027
+ const dryRun = async (id, text, file) => {
1028
+ const result = await designCheckChangeSet(undefined, { "change-set": id, ...(text ? { file } : {}), ...(f["figma-version"] ? { "figma-version": f["figma-version"] } : {}), ...(f.sync ? { sync: true } : {}), ...(f.async ? { async: true } : {}) },
1029
+ { read: async () => text });
1030
+ emit(result.payload, json, result.human);
1031
+ if (result.exitCode) {
1032
+ if (!json) console.error(`DS_CONFORMANCE_FAILED: ${result.payload.data.findings.length} finding(s)`);
1033
+ process.exitCode = result.exitCode;
1034
+ }
1035
+ };
1036
+ if (action === "submit" && f["dry-run"]) {
1037
+ if (!rest[0]) throw new CliError("USAGE", "figma submit CHANGE_SET --file SUBMIT.json --dry-run", 2);
1038
+ // The same body checks as the real submit, which needs --file.
1039
+ const text = f.file ? await readFile(f.file, "utf8") : null;
1040
+ checkSubmitPayload(text ? JSON.parse(text) : { figmaVersion: f["figma-version"] }, f.file || "the submit (no --file)");
1041
+ return dryRun(rest[0], text, f.file);
1042
+ }
1043
+ if (action === "resubmit" && f["dry-run"]) {
1044
+ if (!rest[0] || !rest[1]) throw new CliError("USAGE", "figma resubmit CHANGE_SET PAYLOAD.json --dry-run", 2);
1045
+ const text = await readFile(rest[1], "utf8");
1046
+ assertContext(resubmitPayload(text, rest[1]), { resubmit: true, file: rest[1] });
1047
+ return dryRun(rest[0], text, rest[1]);
1048
+ }
988
1049
  if (action === "submit") {
989
1050
  const payload = f.file ? JSON.parse(await readFile(f.file, "utf8")) : { figmaVersion: requireFlag(f, "figma-version") };
990
1051
  // A 200 carries top-level warnings (STALE_FIGMA_VERSION): print them.
package/dist/core.js CHANGED
@@ -4,7 +4,7 @@ import { chmod, mkdir, readFile, rm, writeFile } from "node:fs/promises";
4
4
  import { homedir, platform } from "node:os";
5
5
  import { dirname, join } from "node:path";
6
6
 
7
- export const VERSION = "0.6.54";
7
+ export const VERSION = "0.6.56";
8
8
  export const configPath = () =>
9
9
  process.env.NODII_DEV_CONFIG_PATH ??
10
10
  join(homedir(), ".config/nodii-dev/config.json");
package/dist/figma.js CHANGED
@@ -605,11 +605,16 @@ export const figmaScopeSetText = (id, data) =>
605
605
  * A body without its context (writeUp, item context, variant name and context)
606
606
  * is refused here, before any call to Dev (DEV-DSN-25).
607
607
  */
608
- export async function figmaSubmit(id, payload, { request = devRequest, file = "the submit body", ...options } = {}) {
608
+ /** The submit body's local checks, before Dev is called (DEV-DSN-25); `figma submit --dry-run` runs them too. */
609
+ export function checkSubmitPayload(payload, file = "the submit body") {
609
610
  if (!payload || typeof payload !== "object" || Array.isArray(payload)) throw new CliError("USAGE", `${file}: expected a JSON object`, 2);
610
611
  if (!Array.isArray(payload.items) || payload.items.length === 0)
611
612
  throw new CliError("USAGE", `${file}: items must list the set's items, each with its context and variants (figma submit CHANGE_SET --file SUBMIT.json)`, 2);
612
- assertContext(payload, { file });
613
+ return assertContext(payload, { file });
614
+ }
615
+
616
+ export async function figmaSubmit(id, payload, { request = devRequest, file = "the submit body", ...options } = {}) {
617
+ checkSubmitPayload(payload, file);
613
618
  return changeSetCall(id, (method, path, body) => submitCall(id, "submit", body, { request, ...options }))(
614
619
  "POST", `/api/v1/design/change-sets/${encode(id)}/submit`, payload);
615
620
  }
package/dist/flags.js ADDED
@@ -0,0 +1,65 @@
1
+ // Declared flags per command (NODII-DEV-CLI-18). parseArgs accepts any
2
+ // `--flag`, and a command reads only the keys it knows, so a mistyped or
3
+ // imagined flag was silently dropped: `figma submit --dry-run` ran a real
4
+ // submit. Every write command is listed here; an unknown flag is refused with
5
+ // USAGE before the command runs. A command not listed is not checked yet.
6
+ import { CliError } from "./core.js";
7
+
8
+ // Every command takes these.
9
+ const GLOBAL = ["json", "help"];
10
+ const BODY = ["body", "body-file"];
11
+ const ISSUE_FIELDS = ["title", "kind", "priority", "project", ...BODY, "comment", "comment-file"];
12
+ const SUBMIT_MODE = ["sync", "async"];
13
+ const WAIT = ["wait", "wait-minutes"];
14
+
15
+ export const COMMAND_FLAGS = {
16
+ "coordinator start": ["machine", "account", "heartbeat-seconds"],
17
+ "coordinator heartbeat": ["machine", "run", "pid", "pid-started-at", "interval"],
18
+ "issues create": ["service", ...ISSUE_FIELDS],
19
+ "issues update": ISSUE_FIELDS,
20
+ "issues transition": ["to", "reason", "dev-check"],
21
+ "issues comment": BODY,
22
+ "issues claim": ["ttl"],
23
+ "issues release": ["note"],
24
+ "lane launch": [
25
+ "machine", "coordinator-run", "machine-id", "repo", "branch", "base", "worktree", "owned-path",
26
+ "figma", "route", "runtime", "issue", "done-check", "kind", "side", "profile", "class", "model",
27
+ "subagents", "notes", "narrowing-note", "narrowing-remainder", "heartbeat-seconds",
28
+ ],
29
+ "lane amend": ["objective", "scope", "rules", "reason"],
30
+ "lane start": ["key", "issue", "title", "kind", "side", "repo", "branch", "worktree", "step-limit"],
31
+ "lane step": ["side", "start", "done", "block", "not-applicable", "reason", "reason-code", "note", "review", "delta"],
32
+ "lane evidence": ["pr", "commit", "figma", "deploy", "dev-check"],
33
+ "lane done-check": ["evidence"],
34
+ "lane heartbeat": ["note"],
35
+ "lane resume": ["override", "reason"],
36
+ "lane stop": ["reason"],
37
+ "lane land": [],
38
+ "lane review": ["file", "not-required", "decision", "question", "quote", "at"],
39
+ "lane non-issue": ["reason", "reroute", "evidence", "commits", "branch"],
40
+ "drift file": ["service", "severity", "summary", ...BODY, "related-artifact-type", "related-artifact-id"],
41
+ "drift accept": ["reason", "decision", "resolution-md", "related-decision-id"],
42
+ "drift resolve": ["reason", "resolution-md", "status", "decision", "related-decision-id"],
43
+ "drift supersede": ["reason", "by", "resolution-md", "superseding-drift-id"],
44
+ "request file": ["from", "to", "kind", "summary", "spec", "spec-file", "required-capability", "target-artifact-type", "target-artifact-id"],
45
+ "docs upload": ["class", "change-class", "pending", "decision", "meaning-unchanged", "conformance-ref", "base", ...WAIT],
46
+ "docs ratify": ["domain", "decision", ...WAIT],
47
+ "figma submit": ["file", "figma-version", ...SUBMIT_MODE, "dry-run"],
48
+ "figma resubmit": [...SUBMIT_MODE, "dry-run"],
49
+ "figma withdraw": [],
50
+ "figma abandon": ["file"],
51
+ "figma apply": ["file", "figma-version"],
52
+ "figma lock": ["title", "scope"],
53
+ };
54
+
55
+ /** Refuse a flag the command does not declare (USAGE, exit 2), naming the valid ones. */
56
+ export function assertKnownFlags(args, flags) {
57
+ const [command, action] = args;
58
+ const declared = COMMAND_FLAGS[`${command} ${action}`];
59
+ if (!declared) return;
60
+ const known = new Set([...GLOBAL, ...declared]);
61
+ const unknown = Object.keys(flags).filter((flag) => !known.has(flag));
62
+ if (!unknown.length) return;
63
+ const valid = declared.length ? declared.map((flag) => `--${flag}`).join(", ") : "none";
64
+ throw new CliError("USAGE", `${command} ${action} does not take ${unknown.map((flag) => `--${flag}`).join(", ")}; its flags: ${valid} (and --json).`, 2, { unknown, valid: declared });
65
+ }
package/dist/starting.js CHANGED
@@ -114,9 +114,9 @@ export function laneConfigPath(key, current = configPath()) {
114
114
  const lane = String(key).toLowerCase().replaceAll(/[^a-z0-9_-]/g, "-");
115
115
  return join(agentsDir, `lane-${lane}.json`);
116
116
  }
117
- async function saveJson(file, value) {
117
+ async function saveJson(file, value, { flag = "w" } = {}) {
118
118
  await mkdir(dirname(file), { recursive: true, mode: 0o700 });
119
- await writeFile(file, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600 });
119
+ await writeFile(file, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600, flag });
120
120
  }
121
121
  async function loadJson(file) {
122
122
  try { return JSON.parse(await readFile(file, "utf8")); }
@@ -148,6 +148,91 @@ async function watchCoordinator(runId) {
148
148
  });
149
149
  }
150
150
 
151
+ /**
152
+ * This machine's running coordinator run, as Dev holds it, found from the
153
+ * watchdog's local records (CLI-16). The state file is a cache: when it is
154
+ * gone, Dev's run for this machine and this identity is still the authority.
155
+ */
156
+ export async function findCoordinatorRun(machine, {
157
+ request = devRequest,
158
+ watched = async () => (await import("./watchdog.js")).readWatchedRuns(),
159
+ agentId,
160
+ identity = configPath(),
161
+ } = {}) {
162
+ // Without the caller's own agent id no run can be shown to be its own.
163
+ if (!agentId) return null;
164
+ const { records } = await watched();
165
+ const found = [];
166
+ let unreadable = null;
167
+ // Only this identity's own records: another identity's run is never adopted.
168
+ for (const record of records.filter((r) => r.configPath === identity)) {
169
+ let run;
170
+ try { run = (await request("GET", `/api/v1/runs/${encode(record.runId)}`)).data; }
171
+ catch (error) {
172
+ // A run Dev no longer has is not this machine's; any other error means
173
+ // the answer is unknown, never "no run".
174
+ if (error?.code !== "RUN_NOT_FOUND") unreadable = error;
175
+ continue;
176
+ }
177
+ if (run?.kind !== "coordinator" || run.status !== "running") continue;
178
+ if (run.metadata?.machineName !== machine && run.metadata?.machineId !== machine) continue;
179
+ if (run.ownerAgentId !== agentId) continue;
180
+ found.push({ ...run, watched: { pid: record.pid, processStartedAt: record.processStartedAt ?? null } });
181
+ }
182
+ const newest = found.sort((a, b) => String(b.startedAt).localeCompare(String(a.startedAt)))[0] ?? null;
183
+ if (!newest && unreadable)
184
+ throw new CliError(unreadable.code ?? "DEV_UNREACHABLE", `Could not read this machine's coordinator runs from Dev (${unreadable.code ?? "error"}: ${unreadable.message ?? unreadable}); try again.`, 1);
185
+ return newest;
186
+ }
187
+
188
+ const coordinatorState = (machine, run, agentId) => ({
189
+ machine,
190
+ machineId: run.metadata.machineId,
191
+ runId: run.id,
192
+ agentId: agentId ?? run.ownerAgentId,
193
+ startedAt: run.startedAt,
194
+ });
195
+
196
+ /**
197
+ * Adopt this session's own running coordinator run again (CLI-16): rewrite the
198
+ * state file and restart the heartbeater. Dev's run is unchanged.
199
+ */
200
+ async function adoptCoordinatorRun(machine, run, c, { save, heartbeater, existingHeartbeater }) {
201
+ await save(stateFile(machine), coordinatorState(machine, run, c.agentId));
202
+ const expected = run.expectedHeartbeatSeconds ?? 60;
203
+ // A heartbeater still beating this run keeps it; a second is never started.
204
+ let heartbeaterPid = await existingHeartbeater(machine, run.id).catch(() => null);
205
+ let heartbeaterError = null;
206
+ if (!heartbeaterPid) {
207
+ try { heartbeaterPid = await heartbeater({ runId: run.id, machine, pid: run.watched.pid, processStartedAt: run.watched.processStartedAt ?? null, intervalSeconds: Math.max(5, Math.floor(expected / 2)) }); }
208
+ catch (error) { heartbeaterError = error?.message ?? String(error); }
209
+ }
210
+ return {
211
+ payload: { data: { adopted: true, run, machine: { id: run.metadata.machineId, name: machine } }, heartbeaterPid },
212
+ human: [
213
+ `Coordinator ${run.id} is this session's run on ${machine}; adopted it again (last heartbeat ${run.lastHeartbeatAt ?? "never"}).`,
214
+ heartbeaterPid
215
+ ? `heartbeater ${heartbeaterPid} keeps the run alive while session ${run.watched.pid} lives`
216
+ : `heartbeater not started${heartbeaterError ? ` (${heartbeaterError})` : ""}: the run goes quiet without heartbeats`,
217
+ ].join("\n"),
218
+ };
219
+ }
220
+
221
+ /** A run whose last heartbeat is older than 3x its expected interval is stale (CLI-16). */
222
+ export function coordinatorRunStale(run, now = Date.now()) {
223
+ const expected = Number(run.expectedHeartbeatSeconds ?? 60);
224
+ const last = Date.parse(run.lastHeartbeatAt ?? run.startedAt ?? "");
225
+ return !Number.isFinite(last) || now - last > expected * 3 * 1000;
226
+ }
227
+
228
+ /** The saved heartbeater's PID while it is alive and beating `runId`, else null. */
229
+ async function runningHeartbeater(machine, runId, run = execFile) {
230
+ const pid = Number((await readFile(heartbeatPidFile(machine), "utf8")).trim());
231
+ if (!Number.isInteger(pid) || pid <= 1) return null;
232
+ const { stdout } = await run("ps", ["-p", String(pid), "-o", "command="], { encoding: "utf8" });
233
+ return / coordinator heartbeat /.test(stdout) && stdout.includes(`--run ${runId}`) ? pid : null;
234
+ }
235
+
151
236
  const heartbeatPidFile = (machine) => join(dirname(configPath()), `coordinator-${encodeURIComponent(machine)}.heartbeat.pid`);
152
237
 
153
238
  /**
@@ -177,10 +262,25 @@ export async function coordinatorHeartbeatLoop({ machine, runId, pid, processSta
177
262
  request = devRequest,
178
263
  isAlive = async (target, startedAt) => (await import("./watchdog.js")).isProcessAlive(target, startedAt),
179
264
  currentRunId = async () => (await loadJson(stateFile(machine)))?.runId,
265
+ restoreState = async () => {
266
+ const run = (await request("GET", `/api/v1/runs/${encode(runId)}`)).data;
267
+ if (run?.status !== "running") return;
268
+ // Exclusive create: a `coordinator start` that wrote the file meanwhile wins.
269
+ try { await saveJson(stateFile(machine), coordinatorState(machine, run), { flag: "wx" }); }
270
+ catch (error) { if (error?.code !== "EEXIST") throw error; }
271
+ },
180
272
  sleep = (ms) => delay(ms),
181
273
  } = {}) {
182
274
  for (;;) {
183
- if ((await currentRunId()) !== runId) return { stopped: "replaced" };
275
+ const current = await currentRunId();
276
+ // Only a state file that names another run means `coordinator start`
277
+ // replaced this one. A missing file is restored from Dev, never read as
278
+ // replaced (CLI-16).
279
+ if (current && current !== runId) return { stopped: "replaced" };
280
+ if (!current) {
281
+ try { await restoreState(); }
282
+ catch (error) { process.stderr.write(`coordinator state restore failed (${error?.code ?? error?.message ?? "error"}); retrying.\n`); }
283
+ }
184
284
  if (!(await isAlive(pid, processStartedAt))) {
185
285
  try {
186
286
  await request("POST", `/api/v1/runs/${encode(runId)}/end`, {
@@ -218,7 +318,13 @@ async function coordinatorCapacity(machineId, flags, { request, readers }) {
218
318
  }
219
319
  }
220
320
 
221
- export async function coordinatorCommand(action, flags, { request = devRequest, config = readConfig, save = saveJson, watch = watchCoordinator, readers, heartbeater = spawnHeartbeater, heartbeatLoop = coordinatorHeartbeatLoop } = {}) {
321
+ export async function coordinatorCommand(action, flags, {
322
+ request = devRequest, config = readConfig, save = saveJson, watch = watchCoordinator, readers, heartbeater = spawnHeartbeater,
323
+ heartbeatLoop = coordinatorHeartbeatLoop, findRun = findCoordinatorRun, now = Date.now,
324
+ isAlive = async (pid, startedAt) => (await import("./watchdog.js")).isProcessAlive(pid, startedAt),
325
+ sessionPid = coordinatorRuntimePid,
326
+ existingHeartbeater = runningHeartbeater,
327
+ } = {}) {
222
328
  if (action === "heartbeat") {
223
329
  const result = await heartbeatLoop({
224
330
  machine: requireFlag(flags, "machine"),
@@ -232,12 +338,52 @@ export async function coordinatorCommand(action, flags, { request = devRequest,
232
338
  if (action !== "start") throw new CliError("USAGE", `Unknown coordinator action: ${action}`, 2);
233
339
  const machine = requireFlag(flags, "machine");
234
340
  accountFlags(flags.account);
235
- const payload = await request("POST", "/api/v1/coordinator-runs/start", {
341
+ const startBody = {
236
342
  machine,
237
343
  expectedHeartbeatSeconds: flags["heartbeat-seconds"] ? Number(flags["heartbeat-seconds"]) : 60,
238
344
  ...via,
239
- });
345
+ };
240
346
  const c = await config();
347
+ let payload;
348
+ try {
349
+ payload = await request("POST", "/api/v1/coordinator-runs/start", startBody);
350
+ } catch (error) {
351
+ if (error?.code !== "COORDINATOR_ALREADY_RUNNING") throw error;
352
+ const live = await findRun(machine, { request, agentId: c.agentId });
353
+ if (!live)
354
+ throw new CliError("COORDINATOR_ALREADY_RUNNING", `Dev holds a running coordinator run for ${machine}, and no local watchdog record shows it is this identity's, so it cannot be checked for takeover.`, 1);
355
+ const pid = live.watched?.pid;
356
+ const sessionAlive = Number.isInteger(pid) && (await isAlive(pid, live.watched.processStartedAt));
357
+ // CLI-16: the run's session is this session (its heartbeater or state file
358
+ // was lost): adopt the run again and restart its heartbeater.
359
+ if (sessionAlive && pid === (await sessionPid().catch(() => null)))
360
+ return adoptCoordinatorRun(machine, live, c, { save, heartbeater, existingHeartbeater });
361
+ const interval = live.expectedHeartbeatSeconds ?? 60;
362
+ if (!coordinatorRunStale(live, now()))
363
+ throw new CliError("COORDINATOR_ALREADY_RUNNING", `Coordinator run ${live.id} for ${machine} is live (last heartbeat ${live.lastHeartbeatAt ?? "never"}); it is taken over only after 3x its ${interval}s heartbeat interval with its session gone. Run coordinator start from that run's own session to adopt it again.`, 1);
364
+ // A run whose session pid is unknown cannot be shown to have exited.
365
+ if (!Number.isInteger(pid))
366
+ throw new CliError("COORDINATOR_ALREADY_RUNNING", `Coordinator run ${live.id} for ${machine} has had no heartbeat since ${live.lastHeartbeatAt ?? live.startedAt}, but its watchdog record names no session pid, so its exit cannot be checked; it was not taken over.`, 1);
367
+ // A stale run whose session still lives is not taken over: its process
368
+ // did not exit, and Dev would record that it did (P-4).
369
+ if (sessionAlive)
370
+ throw new CliError("COORDINATOR_ALREADY_RUNNING", `Coordinator run ${live.id} for ${machine} has had no heartbeat since ${live.lastHeartbeatAt ?? live.startedAt}, but its session (pid ${pid}) is still alive. Run nodii-dev coordinator start from that session to adopt the run again, or end that session first.`, 1);
371
+ // CLI-16: the session is gone and the run went quiet. Re-read it just
372
+ // before the takeover, then record the process exit (the run becomes an
373
+ // orphan), so Dev records takeover_of_run_id.
374
+ const current = (await request("GET", `/api/v1/runs/${encode(live.id)}`)).data;
375
+ if (current?.status === "running" && !coordinatorRunStale(current, now()))
376
+ throw new CliError("COORDINATOR_ALREADY_RUNNING", `Coordinator run ${live.id} for ${machine} heartbeated at ${current.lastHeartbeatAt}; it is live again and was not taken over.`, 1);
377
+ try {
378
+ await request("POST", `/api/v1/runs/${encode(live.id)}/process-exit`, {
379
+ reason: `coordinator start took over: session pid ${pid} has exited and no heartbeat since ${live.lastHeartbeatAt ?? live.startedAt} (over 3x ${interval}s)`,
380
+ deathFingerprint: "coordinator-heartbeat-stale",
381
+ });
382
+ } catch (exitError) {
383
+ if (exitError?.code !== "RUN_ALREADY_TERMINAL") throw exitError;
384
+ }
385
+ payload = await request("POST", "/api/v1/coordinator-runs/start", startBody);
386
+ }
241
387
  let watched;
242
388
  try {
243
389
  watched = await watch(payload.data.run.id);
@@ -396,12 +542,30 @@ export async function launchLaneCommand(key, flags, {
396
542
  catalog = loadDsCatalog,
397
543
  laneConfig = loadJson,
398
544
  identityPath = laneConfigPath,
545
+ findRun = findCoordinatorRun,
546
+ save = saveJson,
547
+ isAlive = async (pid, startedAt) => (await import("./watchdog.js")).isProcessAlive(pid, startedAt),
399
548
  } = {}) {
400
549
  if (!key) throw new CliError("USAGE", "lane launch needs <key>.", 2);
401
550
  const machine = requireFlag(flags, "machine");
402
- const coordinator = flags["coordinator-run"]
551
+ let coordinator = flags["coordinator-run"]
403
552
  ? { runId: flags["coordinator-run"], machineId: requireFlag(flags, "machine-id") }
404
553
  : await state(stateFile(machine));
554
+ if (!coordinator) {
555
+ // CLI-16: the state file is a cache of Dev's run. When it is gone, use
556
+ // the machine's running coordinator run if it is this identity's and its
557
+ // session still lives.
558
+ const live = await findRun(machine, { request, agentId: (await config()).agentId });
559
+ if (live && Number.isInteger(live.watched?.pid) && (await isAlive(live.watched.pid, live.watched.processStartedAt))) {
560
+ coordinator = coordinatorState(machine, live);
561
+ // Exclusive create: a `coordinator start` that wrote the file meanwhile wins.
562
+ try { await save(stateFile(machine), coordinator, { flag: "wx" }); }
563
+ catch (error) {
564
+ if (error?.code !== "EEXIST") throw error;
565
+ coordinator = await state(stateFile(machine));
566
+ }
567
+ }
568
+ }
405
569
  if (!coordinator) throw new CliError("COORDINATOR_NOT_STARTED", `Run nodii-dev coordinator start --machine ${machine} first.`, 1);
406
570
  const repositories = launchRepositories(key, flags);
407
571
  const runtime = requireFlag(flags, "runtime");
@@ -506,11 +670,43 @@ export async function launchLaneCommand(key, flags, {
506
670
  };
507
671
  }
508
672
 
509
- export async function amendLaneCommand(key, flags, { request = devRequest } = {}) {
673
+ // What each amendment refusal means: Dev's message only repeats the code.
674
+ const AMEND_REFUSALS = {
675
+ LANE_NOT_FOUND: (key) => `Dev has no lane ${key}.`,
676
+ COORDINATOR_REQUIRED: (key) => `Only the machine coordinator that launched ${key} may amend it; run lane amend under that coordinator's identity.`,
677
+ LANE_LAUNCH_NOT_FOUND: (key) => `${key} was not started with nodii-dev lane launch, so it has no launch contract to amend.`,
678
+ };
679
+ const ERROR_CODE = /^[A-Z][A-Z0-9_]*$/;
680
+
681
+ export async function amendLaneCommand(key, flags, { request = devRequest, now = Date.now, config = readConfig } = {}) {
510
682
  if (!key) throw new CliError("USAGE", "lane amend needs <key>.", 2);
511
683
  const change = Object.fromEntries([["objective", flags.objective], ["scope", flags.scope], ["rules", flags.rules]].filter(([, value]) => value));
512
684
  if (!Object.keys(change).length) throw new CliError("USAGE", "lane amend needs --objective, --scope, or --rules.", 2);
513
- const payload = await request("POST", `/api/v1/lanes/${encode(key)}/amendments`, { change, reason: requireFlag(flags, "reason"), ...via });
685
+ const reason = requireFlag(flags, "reason");
686
+ let payload;
687
+ try {
688
+ payload = await request("POST", `/api/v1/lanes/${encode(key)}/amendments`, { change, reason, ...via });
689
+ } catch (error) {
690
+ const say = AMEND_REFUSALS[error?.code];
691
+ if (say) throw new CliError(error.code, say(key), error.exitCode ?? 1, error.details);
692
+ // A Dev before NODII-DEV-CLI-17 answered a recorded amendment with a 409
693
+ // whose code is the reason itself. Read the lane back for the row.
694
+ if (error?.code && !ERROR_CODE.test(error.code) && error.code === reason.trim()) {
695
+ // Only the lane's newest amendment, written in the last two minutes,
696
+ // can be this call's: an older identical one is not confirmation.
697
+ const lane = (await request("GET", `/api/v1/lanes/${encode(key)}`)).data;
698
+ const newest = [...(lane?.amendments ?? [])].sort((a, b) => b.version - a.version)[0];
699
+ // Either side of now, so a local clock behind Dev's never widens it.
700
+ const fresh = newest && Math.abs(now() - Date.parse(newest.createdAt ?? "")) < 120_000;
701
+ const mine = newest && newest.actorAgentId === (await config()).agentId;
702
+ // Dev stores the change as jsonb, which reorders keys: compare by key.
703
+ const sameChange = (a, b) => JSON.stringify(Object.entries(a ?? {}).sort()) === JSON.stringify(Object.entries(b).sort());
704
+ if (fresh && mine && newest.reason === reason.trim() && sameChange(newest.change, change))
705
+ return { payload: { data: newest }, human: `Recorded amendment ${newest.version} for ${key}.` };
706
+ throw new CliError("AMENDMENT_UNCONFIRMED", `Dev answered the amendment with a 409 named after its reason, and lane ${key} shows no amendment with that reason and change. Check nodii-dev lane show ${key} before amending again.`, 1);
707
+ }
708
+ throw error;
709
+ }
514
710
  return { payload, human: `Recorded amendment ${payload.data.version} for ${key}.` };
515
711
  }
516
712
 
package/dist/tune.js CHANGED
@@ -1,3 +1,6 @@
1
+ import { appendFile, mkdir, readFile } from "node:fs/promises";
2
+ import { homedir } from "node:os";
3
+ import { join } from "node:path";
1
4
  import { CliError, devRequest, encode, query } from "./core.js";
2
5
  import { GATHER_TIMEOUT_MS, TUNING_MODELS, gatherText, pickDocuments, warmPicker } from "./gather.js";
3
6
 
@@ -10,6 +13,12 @@ export const TUNING_PICKERS = ["shortlist-only", "lane-agent", "gemma-e4b", "gem
10
13
  export const TUNING_REPEATS = 5;
11
14
  const TRIGGERS = ["setup", "trigger_change", "document_change", "missed_trigger", "manual"];
12
15
  const SECTION_LIMIT = 3;
16
+ // exec runs a server-bound picker's trials this many at a time by default
17
+ // (AH-20: one at a time, 150 shortlist-only trials outlast a 10-minute
18
+ // session limit). A local Gemma picker always runs one at a time: one model
19
+ // in Ollama's memory, and its pick latency is part of what tuning measures.
20
+ const EXEC_CONCURRENCY = 4;
21
+ const MAX_EXEC_CONCURRENCY = 8;
13
22
  const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
14
23
 
15
24
  const list = (value) => String(value ?? "").split(",").map((x) => x.trim()).filter(Boolean);
@@ -41,6 +50,13 @@ function pickersFlag(value) {
41
50
  return pickers;
42
51
  }
43
52
 
53
+ function concurrencyFlag(value) {
54
+ if (value === undefined) return EXEC_CONCURRENCY;
55
+ const n = Number(value);
56
+ if (!Number.isInteger(n) || n < 1 || n > MAX_EXEC_CONCURRENCY) throw new CliError("USAGE", `--concurrency must be a whole number from 1 to ${MAX_EXEC_CONCURRENCY}`, 2);
57
+ return n;
58
+ }
59
+
44
60
  function iterationFlag(value) {
45
61
  const n = Number(value);
46
62
  if (!Number.isInteger(n) || n < 1 || n > TUNING_REPEATS) throw new CliError("USAGE", `--iteration needs a whole number from 1 to ${TUNING_REPEATS}`, 2);
@@ -226,6 +242,41 @@ export async function runTrial(replay, picker, { request = devRequest, corpus =
226
242
  }
227
243
  }
228
244
 
245
+ export const tuningProgressDir = (env = process.env) => env.NODII_DEV_TUNING_DIR || join(homedir(), ".cache", "nodii-dev", "tuning");
246
+
247
+ /**
248
+ * The trials exec has had Dev accept for one run, one JSON line each, so a
249
+ * rerun after a kill resumes instead of starting over. Dev's trial PUT is
250
+ * idempotent: a lost or unreadable line only means that trial is run again,
251
+ * never that a trial is skipped without Dev holding it.
252
+ */
253
+ export function tuningProgress(runId, dir = tuningProgressDir()) {
254
+ const path = join(dir, `${runId}.jsonl`);
255
+ const key = (picker, caseId, iteration) => `${picker}\u0000${caseId}\u0000${iteration}`;
256
+ const done = new Set();
257
+ return {
258
+ path,
259
+ async load() {
260
+ let text = "";
261
+ try { text = await readFile(path, "utf8"); }
262
+ catch (error) { if (error.code !== "ENOENT") throw error; }
263
+ for (const line of text.split("\n")) {
264
+ if (!line.trim()) continue;
265
+ try {
266
+ const x = JSON.parse(line);
267
+ done.add(key(x.picker, x.caseId, x.iteration));
268
+ } catch { /* a torn last line: that trial runs again */ }
269
+ }
270
+ },
271
+ has: (picker, caseId, iteration) => done.has(key(picker, caseId, iteration)),
272
+ async add(picker, caseId, iteration) {
273
+ await mkdir(dir, { recursive: true });
274
+ await appendFile(path, `${JSON.stringify({ picker, caseId, iteration, at: new Date().toISOString() })}\n`);
275
+ done.add(key(picker, caseId, iteration));
276
+ },
277
+ };
278
+ }
279
+
229
280
  async function runCases(request, id) {
230
281
  const runs = (await request("GET", "/api/v1/gather/tuning/runs")).data ?? [];
231
282
  const run = runs.find((x) => x.id === id);
@@ -250,9 +301,11 @@ function execText(payload) {
250
301
  const d = payload.data;
251
302
  const lines = [`Tuning run ${d.runId}: ${d.cases} case${d.cases === 1 ? "" : "s"} × ${TUNING_REPEATS} repeats`];
252
303
  for (const p of d.pickers) {
253
- if (p.status === "recorded") lines.push(` ${p.picker.padEnd(15)}recorded ${p.recorded}/${p.expected}`);
254
- else lines.push(` ${p.picker.padEnd(15)}${p.status.toUpperCase()}${p.recorded ? ` after ${p.recorded}/${p.expected}` : ""}: ${p.reason}`);
304
+ const resumed = p.resumed ? ` (${p.resumed} from an earlier exec)` : "";
305
+ if (p.status === "recorded") lines.push(` ${p.picker.padEnd(15)}recorded ${p.recorded}/${p.expected}${resumed}`);
306
+ else lines.push(` ${p.picker.padEnd(15)}${p.status.toUpperCase()}${p.recorded ? ` after ${p.recorded}/${p.expected}${resumed}` : ""}: ${p.reason}`);
255
307
  }
308
+ if (!d.complete && d.pickers.some((p) => p.recorded)) lines.push(`Rerun the same exec to resume: trials already recorded are skipped (${d.progress}).`);
256
309
  lines.push(d.complete
257
310
  ? `All requested pickers recorded. Finalize once every picker is in: nodii-dev gather tune finalize ${d.runId}`
258
311
  : "The matrix is not complete; Dev's finalize refuses a partial run. Nothing was faked for the pickers above.");
@@ -284,7 +337,7 @@ function missedText({ data }) {
284
337
  * client for Dev's Gather tuning API (AH-11). Scoring is Dev's; the CLI only
285
338
  * runs the pickers and assembles each trial's Clause map read-only.
286
339
  */
287
- export async function tuneCommand(action, args, flags, { request = devRequest, pick = pickDocuments, warm = warmPicker, corpus } = {}) {
340
+ export async function tuneCommand(action, args, flags, { request = devRequest, pick = pickDocuments, warm = warmPicker, corpus, progressDir } = {}) {
288
341
  // DEV-REV-18: clauses a review cited that Gather never served the lane.
289
342
  if (action === "missed") {
290
343
  for (const flag of ["document", "since"])
@@ -369,30 +422,51 @@ export async function tuneCommand(action, args, flags, { request = devRequest, p
369
422
  if (action === "exec") {
370
423
  const runId = uuid(args[0], "<run-id>");
371
424
  const requested = flags.pickers === undefined ? null : pickersFlag(flags.pickers);
425
+ const concurrency = concurrencyFlag(flags.concurrency);
372
426
  if (requested?.includes("lane-agent")) throw new CliError("USAGE", "the lane-agent picker is the agent itself: record each pick with `gather tune trial --picker lane-agent`", 2);
373
427
  const { cases, pickers: runPickers } = await runCases(request, runId);
374
428
  const outside = (requested ?? []).filter((picker) => !runPickers.includes(picker));
375
429
  if (outside.length) throw new CliError("TUNING_TRIAL_OUTSIDE_MATRIX", `run ${runId} scores ${runPickers.join(", ")}, not ${outside.join(", ")}`, 1);
376
430
  // By default, every automatic picker the run scores.
377
431
  const pickers = requested ?? runPickers.filter((picker) => picker !== "lane-agent");
432
+ const progress = tuningProgress(runId, progressDir);
433
+ await progress.load();
378
434
  const shared = corpus ?? tuningCorpus(request);
379
435
  const replays = new Map();
380
- const replayOf = async (caseId) => {
381
- if (!replays.has(caseId)) replays.set(caseId, (await request("GET", `/api/v1/gather/tuning/cases/${encode(caseId)}/replay`)).data);
436
+ const replayOf = (caseId) => {
437
+ if (!replays.has(caseId)) replays.set(caseId, request("GET", `/api/v1/gather/tuning/cases/${encode(caseId)}/replay`).then((x) => x.data));
382
438
  return replays.get(caseId);
383
439
  };
384
440
  const results = [];
385
441
  for (const picker of pickers) {
386
- const result = { picker, status: "recorded", recorded: 0, expected: cases.length * TUNING_REPEATS };
442
+ const result = { picker, status: "recorded", recorded: 0, resumed: 0, expected: cases.length * TUNING_REPEATS };
387
443
  results.push(result);
444
+ const pending = [];
445
+ for (const caseId of cases)
446
+ for (let iteration = 1; iteration <= TUNING_REPEATS; iteration++)
447
+ if (progress.has(picker, caseId, iteration)) result.resumed++;
448
+ else pending.push({ caseId, iteration });
449
+ result.recorded = result.resumed;
450
+ if (!pending.length) continue;
388
451
  try {
389
452
  if (TUNING_MODELS[picker]) await warm({ model: TUNING_MODELS[picker] });
390
- for (const caseId of cases)
391
- for (let iteration = 1; iteration <= TUNING_REPEATS; iteration++) {
392
- const trial = await runTrial(await replayOf(caseId), picker, { request, pick, corpus: shared });
393
- await putTrial(request, runId, trial, iteration);
394
- result.recorded++;
453
+ // Workers take trials in order; the first failure stops new trials and
454
+ // is raised once the ones in flight settle, so each recorded trial is noted.
455
+ let failure;
456
+ const worker = async () => {
457
+ while (!failure && pending.length) {
458
+ const { caseId, iteration } = pending.shift();
459
+ try {
460
+ const trial = await runTrial(await replayOf(caseId), picker, { request, pick, corpus: shared });
461
+ await putTrial(request, runId, trial, iteration);
462
+ await progress.add(picker, caseId, iteration);
463
+ result.recorded++;
464
+ } catch (error) { failure ??= error; }
395
465
  }
466
+ };
467
+ const width = TUNING_MODELS[picker] ? 1 : concurrency;
468
+ await Promise.all(Array.from({ length: Math.min(width, pending.length) }, worker));
469
+ if (failure) throw failure;
396
470
  } catch (error) {
397
471
  // A Gemma picker this Mac cannot run is reported, not filled in; any
398
472
  // other failure is a real error and stops the run.
@@ -401,7 +475,7 @@ export async function tuneCommand(action, args, flags, { request = devRequest, p
401
475
  }
402
476
  }
403
477
  const complete = results.every((r) => r.status === "recorded");
404
- return { payload: { data: { runId, cases: cases.length, complete, pickers: results } }, human: execText, exitCode: complete ? 0 : 1 };
478
+ return { payload: { data: { runId, cases: cases.length, complete, progress: progress.path, pickers: results } }, human: execText, exitCode: complete ? 0 : 1 };
405
479
  }
406
480
  if (action === "finalize") {
407
481
  const runId = uuid(args[0], "<run-id>");
@@ -415,5 +489,5 @@ export async function tuneCommand(action, args, flags, { request = devRequest, p
415
489
  const payload = await request("POST", `/api/v1/gather/tuning/runs/${encode(runId)}/finalize`, body);
416
490
  return { payload, human: (p) => summaryText(p.data) };
417
491
  }
418
- throw new CliError("USAGE", "gather tune missed [--document CODE] [--since ISO]|cases|replay <case-id>|start --cases all|ID,ID --corpus-ref REF [--pickers P,Q]|trial <run-id> --case ID --picker P --iteration N [--documents A,B]|exec <run-id> [--pickers P,Q]|finalize <run-id> [--supersedes <run-id> --reason TEXT]|runs", 2);
492
+ throw new CliError("USAGE", "gather tune missed [--document CODE] [--since ISO]|cases|replay <case-id>|start --cases all|ID,ID --corpus-ref REF [--pickers P,Q]|trial <run-id> --case ID --picker P --iteration N [--documents A,B]|exec <run-id> [--pickers P,Q] [--concurrency N]|finalize <run-id> [--supersedes <run-id> --reason TEXT]|runs", 2);
419
493
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nodii/dev",
3
- "version": "0.6.54",
3
+ "version": "0.6.56",
4
4
  "description": "Agent CLI for Nodii Dev, reached through the platform edge",
5
5
  "type": "module",
6
6
  "bin": {