@nodii/dev 0.6.218 → 0.6.220

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.
@@ -0,0 +1,250 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { readFileSync, readdirSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { CliError, devRequest, encode, readConfig } from "./core.js";
5
+
6
+ /**
7
+ * DEV-PROCESS-1 (hub-653, hub-654): `lane pause` and `lane continue`.
8
+ *
9
+ * A pause is recorded in Dev first, so nothing restarts the lane (Dev refuses
10
+ * every resume LANE_PAUSED), and then every process the lane started on this
11
+ * machine is stopped with SIGSTOP. `lane continue` clears the record and
12
+ * wakes the same processes with SIGCONT: the lane goes on where it was, in
13
+ * the same session, with the same pids.
14
+ *
15
+ * A lane's processes are found by the lane key they carry. The supervisor
16
+ * starts the runtime with NODII_DEV_LANE_KEY in its environment, and every
17
+ * process the runtime starts inherits it: a plain child, a `nohup` job, a job
18
+ * in its own session (`setsid`), a heavy-slot job, and a background job whose
19
+ * shell has exited and which now belongs to init. Its parent chain and its
20
+ * working directory are not used: the first breaks when an in-between shell
21
+ * exits, and the second takes in any process that happens to sit in the
22
+ * worktree (an operator's shell, another lane's job). A descendant of a
23
+ * process found that way is the lane's too, whatever its environment says.
24
+ *
25
+ * Only the one variable is matched: the rest of a process's environment is
26
+ * read by the kernel's interface and dropped on the line it came in, never
27
+ * kept, printed or sent.
28
+ *
29
+ * SIGSTOP frees no memory (06 §10): a paused lane keeps what it holds,
30
+ * a heavy slot included, until it is continued or stopped.
31
+ */
32
+
33
+ const KEY_VARIABLE = "NODII_DEV_LANE_KEY";
34
+
35
+ /** `ps -E` (macOS): each line is `pid ppid stat command… VAR=value…`; only the pid and whether the key matches are kept. */
36
+ export function parsePsWithKey(text, laneKey) {
37
+ const needle = new RegExp(`(?:^|\\s)${KEY_VARIABLE}=(\\S+)(?=\\s|$)`, "g");
38
+ const rows = [];
39
+ for (const line of String(text ?? "").split("\n")) {
40
+ const match = /^\s*(\d+)\s+(\d+)\s+(\S+)\s+(.*)$/.exec(line);
41
+ if (!match) continue;
42
+ let carries = false;
43
+ for (const found of match[4].matchAll(needle)) if (found[1] === laneKey) carries = true;
44
+ rows.push({ pid: Number(match[1]), ppid: Number(match[2]), stat: match[3], carries });
45
+ }
46
+ return rows;
47
+ }
48
+
49
+ const readDarwinPs = () => execFileSync("ps", ["-A", "-E", "-ww", "-o", "pid=,ppid=,stat=,command="], {
50
+ encoding: "utf8", timeout: 10_000, maxBuffer: 64 * 1024 * 1024, stdio: ["ignore", "pipe", "ignore"],
51
+ });
52
+
53
+ /** Linux: /proc/<pid>/stat for the parent and state, /proc/<pid>/environ for the one variable. */
54
+ export function procRowsWithKey(laneKey, proc = "/proc") {
55
+ const wanted = `${KEY_VARIABLE}=${laneKey}`;
56
+ const rows = [];
57
+ let names;
58
+ try { names = readdirSync(proc).filter((name) => /^\d+$/.test(name)); } catch { return null; }
59
+ for (const name of names) {
60
+ try {
61
+ const stat = readFileSync(join(proc, name, "stat"), "utf8");
62
+ const fields = stat.slice(stat.lastIndexOf(")") + 2).split(" ");
63
+ let carries = false;
64
+ // Another user's process is unreadable: it is not this lane's.
65
+ try { carries = readFileSync(join(proc, name, "environ"), "utf8").split("\0").includes(wanted); } catch {}
66
+ rows.push({ pid: Number(name), ppid: Number(fields[1]), stat: fields[0], carries });
67
+ } catch {
68
+ // The process ended while the table was read.
69
+ }
70
+ }
71
+ return rows;
72
+ }
73
+
74
+ /** This machine's processes, each with whether it carries the lane's key. */
75
+ export function laneProcessRows(laneKey, { platform = process.platform, ps = readDarwinPs, proc = "/proc" } = {}) {
76
+ if (platform === "linux") {
77
+ const rows = procRowsWithKey(laneKey, proc);
78
+ if (rows) return rows;
79
+ }
80
+ return parsePsWithKey(ps(), laneKey);
81
+ }
82
+
83
+ /**
84
+ * The lane's processes: every process carrying its key, and every
85
+ * descendant of one. The caller and its ancestors are never in it.
86
+ */
87
+ export function laneProcesses(rows, { self = process.pid } = {}) {
88
+ const byPid = new Map(rows.map((row) => [row.pid, row]));
89
+ const excluded = new Set();
90
+ for (let pid = self, depth = 0; pid > 1 && byPid.has(pid) && depth < 64; pid = byPid.get(pid).ppid, depth += 1) excluded.add(pid);
91
+ excluded.add(self);
92
+ const children = new Map();
93
+ for (const row of rows) {
94
+ if (!children.has(row.ppid)) children.set(row.ppid, []);
95
+ children.get(row.ppid).push(row);
96
+ }
97
+ const found = new Map();
98
+ const walk = (row) => {
99
+ if (found.has(row.pid) || excluded.has(row.pid) || row.pid <= 1) return;
100
+ found.set(row.pid, row);
101
+ for (const child of children.get(row.pid) ?? []) walk(child);
102
+ };
103
+ for (const row of rows) if (row.carries) walk(row);
104
+ return [...found.values()].sort((a, b) => a.pid - b.pid);
105
+ }
106
+
107
+ /** A process stopped by a signal reads T in `ps` and /proc. */
108
+ export const isStopped = (row) => /^T/.test(row?.stat ?? "");
109
+ const isZombie = (row) => /^Z/.test(row?.stat ?? "");
110
+
111
+ /**
112
+ * Send one signal to each of the lane's processes, then read the table again.
113
+ * Answers what was signalled and what did not reach the wanted state.
114
+ */
115
+ export async function signalLane(laneKey, signal, {
116
+ rows = (key) => laneProcessRows(key),
117
+ kill = (pid, name) => process.kill(pid, name),
118
+ self = process.pid,
119
+ settle = () => new Promise((resolve) => setTimeout(resolve, 300)),
120
+ } = {}) {
121
+ const before = laneProcesses(rows(laneKey), { self }).filter((row) => !isZombie(row));
122
+ const signalled = [];
123
+ const failed = [];
124
+ // Parents first on a stop, so none starts a new child while its children stop; children first on a continue.
125
+ const order = signal === "SIGCONT" ? [...before].reverse() : before;
126
+ for (const row of order) {
127
+ try {
128
+ kill(row.pid, signal);
129
+ signalled.push(row.pid);
130
+ } catch (error) {
131
+ if (error?.code !== "ESRCH") failed.push({ pid: row.pid, code: error?.code ?? "SIGNAL_FAILED" });
132
+ }
133
+ }
134
+ await settle();
135
+ const after = new Map(laneProcesses(rows(laneKey), { self }).map((row) => [row.pid, row]));
136
+ const wrong = signalled.filter((pid) => {
137
+ const row = after.get(pid);
138
+ if (!row || isZombie(row)) return false;
139
+ return signal === "SIGSTOP" ? !isStopped(row) : isStopped(row);
140
+ });
141
+ // A process that appeared after the first read (started by one not yet stopped) is the lane's too.
142
+ const late = [...after.values()].filter((row) => !before.some((b) => b.pid === row.pid) && !isZombie(row) && (signal === "SIGSTOP" ? !isStopped(row) : isStopped(row)));
143
+ return { pids: signalled, failed, wrong, late: late.map((row) => row.pid) };
144
+ }
145
+
146
+ const pauseText = (key, verb, result) => {
147
+ const count = result.pids.length;
148
+ const lines = [count
149
+ ? `${key}: ${verb} ${count} process${count === 1 ? "" : "es"} on this machine (pid ${result.pids.join(", ")}).`
150
+ : `${key}: no process of this lane runs on this machine; nothing to ${verb === "stopped" ? "stop" : "wake"} here.`];
151
+ if (result.failed.length) lines.push(`Could not signal: ${result.failed.map((f) => `${f.pid} (${f.code})`).join(", ")}.`);
152
+ if (result.wrong.length) lines.push(`Not ${verb} after the signal: pid ${result.wrong.join(", ")}.`);
153
+ if (result.late.length) lines.push(`Started during the ${verb === "stopped" ? "pause" : "continue"}, not ${verb}: pid ${result.late.join(", ")}. Run the command again.`);
154
+ return lines.join("\n");
155
+ };
156
+
157
+ const incomplete = (result) => result.failed.length || result.wrong.length || result.late.length;
158
+
159
+ /**
160
+ * DEV-PROCESS-1 (steward-dev-process's ruling of 26 Nov, MW1-37.3): pause,
161
+ * continue and stop reach only processes on the machine where they run, so a
162
+ * lane Dev places on another machine is refused COORDINATOR_OTHER_MACHINE,
163
+ * naming that machine, before Dev records anything. A lane placed on no
164
+ * machine has nothing running elsewhere and goes ahead.
165
+ */
166
+ export async function assertLaneOnThisMachine(key, verb, { request = devRequest, config = readConfig } = {}) {
167
+ const lane = (await request("GET", `/api/v1/lanes/${encode(key)}`)).data;
168
+ if (!lane?.machineId) return;
169
+ const c = await config(false).catch(() => null);
170
+ const agent = c?.agentId ? (await request("GET", `/api/v1/agents/${encode(c.agentId)}`).catch(() => null))?.data ?? null : null;
171
+ if (agent?.machineId && agent.machineId === lane.machineId) return;
172
+ const machine = (await request("GET", `/api/v1/machines/${encode(lane.machineId)}`).catch(() => null))?.data ?? null;
173
+ const where = machine?.name ?? lane.machineId;
174
+ throw new CliError("COORDINATOR_OTHER_MACHINE", `Lane ${key} runs on ${where}, not on this machine${agent?.machineId ? "" : " (this session's agent is placed on no machine)"}. lane ${verb} reaches only the processes on the machine where it runs (MW1-37.3), so nothing was recorded. Run it on ${where}.`, 1);
175
+ }
176
+
177
+ /**
178
+ * `lane pause <key> --reason TEXT` and `lane continue <key>`.
179
+ * Dev first: a pause or continue it refuses changes nothing on this machine.
180
+ */
181
+ export async function lanePauseCommand(action, key, flags, {
182
+ request = devRequest,
183
+ signal = signalLane,
184
+ env = process.env,
185
+ config = readConfig,
186
+ } = {}) {
187
+ if (!key) throw new CliError("USAGE", `lane ${action} <key>${action === "pause" ? " --reason TEXT" : ""}`, 2);
188
+ // A lane never pauses itself: it would stop the very command that records it.
189
+ if (env.NODII_DEV_LANE_KEY === key)
190
+ throw new CliError("USAGE", `lane ${action} ${key} runs inside lane ${key}: a lane is paused and continued by its coordinator or the operator.`, 2);
191
+ const reason = flags.reason;
192
+ if (action === "pause" && (typeof reason !== "string" || !reason.trim()))
193
+ throw new CliError("USAGE", "lane pause needs --reason TEXT: why the lane is paused.", 2);
194
+ await assertLaneOnThisMachine(key, action, { request, config });
195
+ const body = { ...(action === "pause" ? { reason: reason.trim() } : {}), via: "nodii-dev" };
196
+ // Run again after an incomplete pause or continue, Dev already holds the record: the signals are still sent.
197
+ const already = action === "pause" ? "LANE_ALREADY_PAUSED" : "LANE_NOT_PAUSED";
198
+ let payload = null;
199
+ try {
200
+ payload = await request("POST", `/api/v1/lanes/${encode(key)}/${action}`, body);
201
+ } catch (error) {
202
+ if (error?.code !== already) throw error;
203
+ }
204
+ const result = await signal(key, action === "pause" ? "SIGSTOP" : "SIGCONT");
205
+ const verb = action === "pause" ? "stopped" : "woke";
206
+ const head = action === "pause"
207
+ ? `${key}: ${payload ? "paused" : "already paused"} in Dev; no resume, keepalive or sweep restarts it until \`nodii-dev lane continue ${key}\`.`
208
+ : `${key}: ${payload ? "continued" : "not paused"} in Dev.`;
209
+ const human = `${head}\n${pauseText(key, verb, result)}`;
210
+ const data = { ...(payload?.data ?? {}), processes: result };
211
+ if (incomplete(result))
212
+ throw new CliError("LANE_SIGNAL_INCOMPLETE", `${human}\nDev records the lane ${action === "pause" ? "paused" : "continued"}; run \`nodii-dev lane ${action} ${key}${action === "pause" ? " --reason TEXT" : ""}\` again for the processes left.`, 1, data);
213
+ return { payload: { ...payload, data }, human };
214
+ }
215
+
216
+ /**
217
+ * DEV-PROCESS-1 item 4: `lane stop` ends the lane's processes on this machine,
218
+ * found by its key as `lane pause` finds them. Each is continued first (a
219
+ * paused process holds a SIGTERM until it runs), told SIGTERM, and after the
220
+ * grace period any still running is killed. The caller and its ancestors, and
221
+ * every process of another lane, are never signalled.
222
+ */
223
+ export async function endLane(laneKey, {
224
+ rows = (key) => laneProcessRows(key),
225
+ kill = (pid, name) => process.kill(pid, name),
226
+ self = process.pid,
227
+ graceMs = 10_000,
228
+ sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
229
+ } = {}) {
230
+ const live = () => laneProcesses(rows(laneKey), { self }).filter((row) => !isZombie(row));
231
+ const first = live();
232
+ const send = (list, signal) => {
233
+ for (const row of list) {
234
+ try { kill(row.pid, signal); } catch {}
235
+ }
236
+ };
237
+ send(first, "SIGCONT");
238
+ send(first, "SIGTERM");
239
+ const end = Date.now() + graceMs;
240
+ let left = live();
241
+ while (left.length && Date.now() < end) {
242
+ await sleep(250);
243
+ left = live();
244
+ }
245
+ const killed = left.map((row) => row.pid);
246
+ send(left, "SIGKILL");
247
+ await sleep(250);
248
+ const remaining = live().map((row) => row.pid);
249
+ return { pids: first.map((row) => row.pid), killed, remaining };
250
+ }