@nodii/dev 0.6.55 → 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]
@@ -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)
@@ -623,6 +633,7 @@ export async function main(argv = process.argv.slice(2)) {
623
633
  const json = Boolean(f.json);
624
634
  const [command, action, ...rest] = args;
625
635
  if (!command || f.help || command === "help") return console.log(HELP);
636
+ assertKnownFlags(args, f);
626
637
  if (command === "api") {
627
638
  const catalog = await loadCatalog({ refresh: action === "catalog" && f.refresh === true });
628
639
  const operations = operationsFrom(catalog.spec);
@@ -887,6 +898,30 @@ export async function main(argv = process.argv.slice(2)) {
887
898
  json,
888
899
  );
889
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
+ }
890
925
  if (command === "request" && action === "file") {
891
926
  const specMd = f["spec-file"]
892
927
  ? await readFile(f["spec-file"], "utf8")
@@ -987,6 +1022,30 @@ export async function main(argv = process.argv.slice(2)) {
987
1022
  // change set id keeps the per-set route.
988
1023
  if (action === "published" && rest[0] && !isChangeSetId(rest[0]))
989
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
+ }
990
1049
  if (action === "submit") {
991
1050
  const payload = f.file ? JSON.parse(await readFile(f.file, "utf8")) : { figmaVersion: requireFlag(f, "figma-version") };
992
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.55";
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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nodii/dev",
3
- "version": "0.6.55",
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": {