@nodii/dev 0.6.132 → 0.6.134

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,564 @@
1
+ // nodii-dev coordinator watch: the coordinator's supervised daemon.
2
+ //
3
+ // coordinator watch run the loop launchd runs (KeepAlive); one instance per machine
4
+ // coordinator watch install writes and loads ~/Library/LaunchAgents/com.nodii.coordinator-watch.plist
5
+ // coordinator watch status each job's health: last run, result, next run, failures
6
+ // coordinator watch once JOB one job now, in the foreground (for a person or a test)
7
+ // coordinator watch alerts alerts not yet shown to the coordinator session (--all for every one)
8
+ //
9
+ // Jobs (hub-405): board, apply-watch, publish-watch, real-stuck,
10
+ // complexity, orphan-slots, keepalive. Everything goes to one log
11
+ // (~/Library/Logs/nodii-dev/coordinator-watch.log); alerts also go to
12
+ // alerts.log, which the coordinator's SessionStart shows until read.
13
+ //
14
+ // The daemon reads Dev and this machine. It never stops a process it did not
15
+ // start (K02-15, MW2-49), never reorders change sets (MW8-4.1), sends only
16
+ // factual lane notes (operator, 13 Nov: "you only need me to approve directive
17
+ // changes"), and resumes lanes only inside the machine guards.
18
+ import { execFile as execFileCallback } from "node:child_process";
19
+ import { appendFile, mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
20
+ import { homedir, loadavg, platform } from "node:os";
21
+ import { dirname, join, resolve } from "node:path";
22
+ import { promisify } from "node:util";
23
+ import { CliError, configPath, devRequest, encode, readConfig } from "./core.js";
24
+ import {
25
+ DEFAULT_DOMAINS, boardCommand, coordinatorHome, heavyQueue, laneDomain, laneProcesses, liveChangeSets, machineLanes, readCoordinatorSettings,
26
+ } from "./coordinator-board.js";
27
+ import { governorMachineId } from "./governor.js";
28
+
29
+ const execFile = promisify(execFileCallback);
30
+ const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
31
+ export const WATCH_LABEL = "com.nodii.coordinator-watch";
32
+ const statePath = (home) => join(coordinatorHome(home), "watch-state.json");
33
+ const pidPath = (home) => join(coordinatorHome(home), "watch.pid");
34
+ export const alertsPath = (home = homedir()) => join(coordinatorHome(home), "alerts.log");
35
+ const alertsReadPath = (home) => join(coordinatorHome(home), "alerts.read");
36
+ export const watchLogPath = (home = homedir()) => join(home, "Library", "Logs", "nodii-dev", "coordinator-watch.log");
37
+ const workaroundsPath = (home) => join(coordinatorHome(home), "workarounds.log");
38
+ const holdPath = (home, job) => join(coordinatorHome(home), `hold-${job}`);
39
+
40
+ const MIN = 60_000;
41
+ /** Each job's interval. */
42
+ export const JOBS = {
43
+ board: 15 * MIN,
44
+ "apply-watch": 3 * MIN,
45
+ "publish-watch": 10 * MIN,
46
+ "real-stuck": 30 * MIN,
47
+ complexity: 30 * MIN,
48
+ "orphan-slots": 10 * MIN,
49
+ keepalive: 10 * MIN,
50
+ };
51
+
52
+ async function readJson(path, fallback) {
53
+ try { return JSON.parse(await readFile(path, "utf8")); }
54
+ catch (error) { if (error?.code === "ENOENT") return fallback; throw error; }
55
+ }
56
+ async function writeJson(path, value) {
57
+ await mkdir(dirname(path), { recursive: true, mode: 0o700 });
58
+ const tmp = `${path}.tmp-${process.pid}`;
59
+ await writeFile(tmp, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600 });
60
+ await rename(tmp, path);
61
+ }
62
+
63
+ // ---- Shared reads -------------------------------------------------------------
64
+
65
+ /** Machine guards for a resume (the prototype's numbers, measured on this Mac, 12 Nov). */
66
+ export async function machineGuards({ execute = execFile, load = loadavg } = {}) {
67
+ let freePercent = null;
68
+ try { freePercent = Number((await execute("memory_pressure", [], { timeout: 15_000 })).stdout.match(/free percentage:\s*(\d+)/i)?.[1] ?? NaN); } catch {}
69
+ let laneProcesses = null;
70
+ try { laneProcesses = (await execute("ps", ["-axo", "command="], { maxBuffer: 32 * 1024 * 1024 })).stdout.split("\n").filter((l) => /^claude --print\b/.test(l)).length; } catch {}
71
+ return { load15: Math.round(load()[2]), freePercent: Number.isFinite(freePercent) ? freePercent : null, laneProcesses };
72
+ }
73
+
74
+ /** Whether a resume may run now. Priority lanes get more room, as on 12 Nov. */
75
+ export function resumeAllowed(guards, { priority, hold = false }) {
76
+ if (guards.laneProcesses !== null && guards.laneProcesses >= 42) return { ok: false, reason: `${guards.laneProcesses} lane processes (cap 42)` };
77
+ if (guards.freePercent !== null && guards.freePercent < (priority ? 25 : 20)) return { ok: false, reason: `memory ${guards.freePercent}% free` };
78
+ if (guards.load15 >= (priority ? 100 : 60)) return { ok: false, reason: `load ${guards.load15}` };
79
+ if (hold && !priority) return { ok: false, reason: "keepalive hold" };
80
+ return { ok: true };
81
+ }
82
+
83
+ async function exists(path) {
84
+ try { await readFile(path); return true; } catch { return false; }
85
+ }
86
+
87
+ async function laneDetail(key, request) {
88
+ return (await request("GET", `/api/v1/lanes/${encode(key)}`)).data;
89
+ }
90
+
91
+ const nonFact = (amendment) => !/^fact/i.test(amendment?.reason ?? "");
92
+
93
+ // ---- Jobs ---------------------------------------------------------------------
94
+
95
+ /** board: the sheet's "What's running", merged when it changed. */
96
+ async function boardJob(ctx) {
97
+ const settings = await readCoordinatorSettings(ctx.home);
98
+ if (!settings.sheet) return { summary: "skipped: no sheet set (run coordinator board --write --sheet NAME once)" };
99
+ const result = await (ctx.board ?? boardCommand)({ write: true }, { home: ctx.home });
100
+ const data = result.payload.data;
101
+ const alerts = data.operator && !data.operator.forwarded ? [`board: operator's checkout not fast-forwarded: ${data.operator.reason}`] : [];
102
+ return { summary: `${data.rows} lanes, ${data.merged ? "merged" : "unchanged"}${data.harvested?.length ? `, harvested ${data.harvested.map((h) => h.id).join(",")}` : ""}`, alerts };
103
+ }
104
+
105
+ /**
106
+ * apply-watch: when the operator has decided every item of a set, Dev wakes no
107
+ * one (hub-389). Tell the holder as a fact, once, and resume it if it's down.
108
+ */
109
+ async function applyWatchJob(ctx) {
110
+ const state = ctx.jobState;
111
+ state.sets ??= {};
112
+ const sets = (await liveChangeSets(ctx)).filter((set) => set.state === "applying" && set.pending === 0 && set.holderLane);
113
+ const alive = await ctx.processes();
114
+ const alerts = [];
115
+ const done = [];
116
+ for (const set of sets) {
117
+ const seen = state.sets[set.id];
118
+ if (!seen) {
119
+ await ctx.amend(set.holderLane, `FACT (coordinator watch, ${ctx.stamp()}): the operator has decided every item of ${set.id} ("${set.title}"), and Dev now shows it applying. Later sets on this file wait behind it (MW8-4.1).`, `fact: ${set.id} decided`);
120
+ state.sets[set.id] = { notedAt: new Date(ctx.now()).toISOString(), lane: set.holderLane };
121
+ done.push(`${set.id}->${set.holderLane} noted`);
122
+ }
123
+ if (alive.get(set.holderLane) === false) {
124
+ const why = await ctx.tryResume(set.holderLane, { priority: true });
125
+ done.push(`${set.holderLane} ${why}`);
126
+ }
127
+ const noted = Date.parse(state.sets[set.id].notedAt);
128
+ if (ctx.now() - noted > 60 * MIN && !state.sets[set.id].alerted) {
129
+ alerts.push(`apply-watch: ${set.id} still applying an hour after ${set.holderLane} was told`);
130
+ state.sets[set.id].alerted = true;
131
+ }
132
+ }
133
+ for (const id of Object.keys(state.sets)) if (!sets.some((set) => set.id === id)) delete state.sets[id];
134
+ return { summary: `${sets.length} decided set(s) applying${done.length ? `: ${done.join("; ")}` : ""}`, alerts };
135
+ }
136
+
137
+ /** publish-watch: finished sets (awaiting_publish) are published, by file, through the shared Chrome. */
138
+ async function publishWatchJob(ctx) {
139
+ // Off until the coordinator turns it on: the rulebook still names the operator
140
+ // as publisher (MW8-7) until hub-429 lands the operator's 13 Nov word.
141
+ if (!(await readCoordinatorSettings(ctx.home)).publishWatch) return { summary: "off (settings.json publishWatch is not true; hub-429)" };
142
+ const state = ctx.jobState;
143
+ state.backoff ??= {};
144
+ const sets = (await liveChangeSets(ctx)).filter((set) => set.state === "awaiting_publish");
145
+ if (!sets.length) return { summary: "nothing awaiting publish" };
146
+ const byFile = new Map();
147
+ for (const set of sets) byFile.set(set.fileKey, [...(byFile.get(set.fileKey) ?? []), set.id]);
148
+ const alerts = [];
149
+ const lines = [];
150
+ for (const [file, ids] of byFile) {
151
+ if ((state.backoff[file] ?? 0) > ctx.now()) { lines.push(`${file}: backing off`); continue; }
152
+ try {
153
+ const data = await ctx.publish(file, ids);
154
+ lines.push(`${file}: published ${data.version ?? "?"}, recorded ${data.recorded.join(",") || "none"}`);
155
+ if (data.unmapped.length || data.notRecorded.length)
156
+ alerts.push(`publish-watch: ${file}: ${[...data.unmapped.map((u) => `${u.set} ${u.name} not in the dialog`), ...data.notRecorded.map((n) => `${n.id} not recorded (${n.reason})`)].join("; ")}`);
157
+ } catch (error) {
158
+ state.backoff[file] = ctx.now() + 60 * MIN;
159
+ alerts.push(`publish-watch: ${file} (${ids.join(",")}) failed: ${error?.code ?? ""} ${error?.message ?? error}`.trim());
160
+ lines.push(`${file}: failed`);
161
+ }
162
+ }
163
+ return { summary: lines.join("; "), alerts };
164
+ }
165
+
166
+ /**
167
+ * real-stuck: a lane is stuck only when it is building, its process is down and
168
+ * Dev has heard nothing from it for an hour. Merged, built and ended lanes never
169
+ * count, and Dev's own stuck flag is not used: it stays set after a lane merges.
170
+ */
171
+ export async function realStuck(ctx) {
172
+ const lanes = (await machineLanes(await ctx.machineId(), ctx)).filter((lane) => lane.status === "building" && !lane.key.startsWith("steward-"));
173
+ const alive = await ctx.processes();
174
+ const stuck = [];
175
+ for (const lane of lanes) {
176
+ // This machine's process record wins; Dev's liveness only for a lane with none.
177
+ const local = alive.get(lane.key);
178
+ if (local === true || (local === undefined && lane.liveness === "active")) continue;
179
+ const last = Date.parse(lane.lastHeartbeatAt ?? lane.updatedAt ?? 0);
180
+ const minutes = Math.round((ctx.now() - last) / MIN);
181
+ if (minutes > 60) stuck.push({ key: lane.key, minutes });
182
+ }
183
+ return stuck;
184
+ }
185
+
186
+ async function realStuckJob(ctx) {
187
+ const stuck = await realStuck(ctx);
188
+ ctx.jobState.last = stuck;
189
+ return { summary: `${stuck.length} stuck${stuck.length ? `: ${stuck.map((s) => `${s.key}(${s.minutes}m)`).join(" ")}` : ""}` };
190
+ }
191
+
192
+ /** complexity (rule 13): two or more signals of a process that has stopped working -> one alert. */
193
+ export function complexitySignals({ running, merged, churn, coordinatorAmends, workarounds, stuck }) {
194
+ const trips = [];
195
+ if (running >= 10 && merged <= 1) trips.push(`output (${merged} merged in 3h, ${running} priority lanes)`);
196
+ if (churn.length) trips.push(`churn (amended >=5x in 24h: ${churn.join(" ")})`);
197
+ if (coordinatorAmends >= 30) trips.push(`coordinator churn (${coordinatorAmends} amendments in 3h)`);
198
+ if (workarounds >= 2) trips.push(`workarounds (${workarounds} in 3h)`);
199
+ if (stuck >= 10) trips.push(`stuck (${stuck})`);
200
+ return trips;
201
+ }
202
+
203
+ async function complexityJob(ctx) {
204
+ const since3h = ctx.now() - 180 * MIN;
205
+ const since24h = ctx.now() - 24 * 60 * MIN;
206
+ const settings = await readCoordinatorSettings(ctx.home);
207
+ const domains = settings.domains ?? DEFAULT_DOMAINS;
208
+ const lanes = (await machineLanes(await ctx.machineId(), ctx)).filter((lane) => lane.status === "building" && laneDomain(lane.key, domains));
209
+ let coordinatorAmends = 0;
210
+ const churn = [];
211
+ const repos = new Set();
212
+ for (const lane of lanes) {
213
+ const detail = await laneDetail(lane.key, ctx.request).catch(() => null);
214
+ for (const repo of [...(lane.repos ?? []), ...(detail?.repos ?? [])]) {
215
+ const name = typeof repo === "string" ? repo : repo?.repo ?? repo?.name;
216
+ if (name) repos.add(name);
217
+ }
218
+ // Fact notes are not churn (rule 13).
219
+ const amends = (detail?.amendments ?? []).filter(nonFact);
220
+ const a24 = amends.filter((a) => Date.parse(a.createdAt) > since24h).length;
221
+ coordinatorAmends += amends.filter((a) => Date.parse(a.createdAt) > since3h).length;
222
+ if (a24 >= 5) churn.push(`${lane.key}:${a24}`);
223
+ }
224
+ const merged = await ctx.mergedSince([...repos], new Date(since3h).toISOString());
225
+ const workarounds = (await readFile(workaroundsPath(ctx.home), "utf8").catch(() => "")).split("\n")
226
+ .filter((line) => { const t = Date.parse(line.split(" ")[0]); return Number.isFinite(t) && t > since3h; }).length;
227
+ const stuck = (await realStuck(ctx)).length;
228
+ const trips = complexitySignals({ running: lanes.length, merged, churn, coordinatorAmends, workarounds, stuck });
229
+ return { summary: `${trips.length} signal(s)${trips.length ? `: ${trips.join("; ")}` : ""}`, alerts: trips.length >= 2 ? [`COMPLEXITY (${trips.length} signals): ${trips.join("; ")}`] : [] };
230
+ }
231
+
232
+ /**
233
+ * orphan-slots: heavy-slot status reclaims slots whose holder has exited. A slot
234
+ * held over 30 minutes by a live process whose lane is down is reported, never
235
+ * killed: only the session that started a process stops it (K02-15).
236
+ */
237
+ async function orphanSlotsJob(ctx) {
238
+ const heavy = await ctx.heavy();
239
+ const alive = await ctx.processes();
240
+ const alerts = [];
241
+ for (const [key, slot] of heavy.holding) {
242
+ if (slot.seconds > 30 * 60 && alive.get(key) === false)
243
+ alerts.push(`orphan-slots: pid ${slot.pid} holds a heavy slot for ${Math.round(slot.seconds / 60)} min and lane ${key} is down; that lane's next session stops it, or a person with the pid does`);
244
+ }
245
+ return { summary: `${heavy.holding.size} slot(s) held, ${heavy.queued.size} queued, ${alerts.length} orphan(s)`, alerts };
246
+ }
247
+
248
+ /** keepalive: resume building lanes whose process is down, priority first, inside the guards. */
249
+ async function keepaliveJob(ctx) {
250
+ const settings = await readCoordinatorSettings(ctx.home);
251
+ const domains = settings.domains ?? DEFAULT_DOMAINS;
252
+ const lanes = (await machineLanes(await ctx.machineId(), ctx)).filter((lane) => lane.status === "building" && !lane.key.startsWith("steward-"));
253
+ const alive = await ctx.processes();
254
+ const state = ctx.jobState;
255
+ state.blockedResumedAt ??= {};
256
+ const down = lanes.filter((lane) => alive.get(lane.key) === false || (!alive.has(lane.key) && ["orphan", "dead"].includes(lane.liveness)))
257
+ .sort((a, b) => Number(!laneDomain(a.key, domains)) - Number(!laneDomain(b.key, domains)) || a.key.localeCompare(b.key));
258
+ const resumed = [];
259
+ const skipped = [];
260
+ for (const lane of down) {
261
+ if (resumed.length >= (settings.keepaliveMaxPerRun ?? 3)) { skipped.push(`${lane.key} (next run)`); continue; }
262
+ // A blocked lane is resumed at most once an hour, so it rechecks its blocker.
263
+ if (lane.liveness === "blocked") {
264
+ const last = state.blockedResumedAt[lane.key] ?? 0;
265
+ if (ctx.now() - last < 60 * MIN) { skipped.push(`${lane.key} (blocked, resumed within the hour)`); continue; }
266
+ }
267
+ const why = await ctx.tryResume(lane.key, { priority: Boolean(laneDomain(lane.key, domains)) });
268
+ if (why === "resumed") {
269
+ resumed.push(lane.key);
270
+ if (lane.liveness === "blocked") state.blockedResumedAt[lane.key] = ctx.now();
271
+ await ctx.sleep(settings.keepaliveGapMs ?? 90_000);
272
+ } else skipped.push(`${lane.key} (${why})`);
273
+ }
274
+ return { summary: `${down.length} down; resumed ${resumed.join(", ") || "none"}${skipped.length ? `; skipped ${skipped.join(", ")}` : ""}` };
275
+ }
276
+
277
+ export const JOB_RUNNERS = {
278
+ board: boardJob,
279
+ "apply-watch": applyWatchJob,
280
+ "publish-watch": publishWatchJob,
281
+ "real-stuck": realStuckJob,
282
+ complexity: complexityJob,
283
+ "orphan-slots": orphanSlotsJob,
284
+ keepalive: keepaliveJob,
285
+ };
286
+
287
+ // ---- The context the jobs run in ----------------------------------------------
288
+
289
+ async function figmaPatFromKeychain(execute) {
290
+ try { return (await execute("security", ["find-generic-password", "-s", "nodii-dev-figma-pat", "-w"], { timeout: 10_000 })).stdout.trim() || null; }
291
+ catch { return null; }
292
+ }
293
+
294
+ export function watchContext({ home = homedir(), request = devRequest, config = readConfig, execute = execFile, now = Date.now, sleep = delay, log, jobState = {} } = {}) {
295
+ let machine = null;
296
+ let processesCache = null;
297
+ let guardsCache = null;
298
+ const ctx = {
299
+ home, request, now, sleep, jobState,
300
+ stamp: () => new Date(now()).toISOString().slice(11, 16) + "Z",
301
+ machineId: async () => (machine ??= await governorMachineId({}, { request, config })),
302
+ processes: async () => (processesCache ??= await laneProcesses()),
303
+ heavy: () => heavyQueue({ execute }),
304
+ guards: async () => (guardsCache ??= await machineGuards({ execute })),
305
+ amend: async (key, rules, reason) => {
306
+ const { amendLaneCommand } = await import("./starting.js");
307
+ await amendLaneCommand(key, { rules, reason });
308
+ await log?.(`amend ${key}: ${reason}`);
309
+ },
310
+ tryResume: async (key, { priority }) => {
311
+ const hold = await exists(holdPath(home, "keepalive"));
312
+ const verdict = resumeAllowed(await ctx.guards(), { priority, hold });
313
+ if (!verdict.ok) return `not resumed: ${verdict.reason}`;
314
+ const { laneCommand } = await import("./lanes.js");
315
+ // The lane's own account first; on an account refusal, the coordinator's
316
+ // allowed lane accounts in order (settings.keepaliveProfiles: the account
317
+ // roster is the operator's call, MW1-38.3, so it is configuration).
318
+ const settings = await readCoordinatorSettings(home);
319
+ const attempts = [{}, ...(settings.keepaliveProfiles ?? []).map((p) => ({ profile: p.profile, class: p.class ?? "short" }))];
320
+ let last = "LANE_RESUME_FAILED";
321
+ for (const flags of attempts) {
322
+ try {
323
+ await laneCommand("resume", [key], flags);
324
+ guardsCache = null;
325
+ await log?.(`resumed ${key}${flags.profile ? ` on ${flags.profile}` : ""}`);
326
+ return "resumed";
327
+ } catch (error) {
328
+ last = error?.code ?? "LANE_RESUME_FAILED";
329
+ if (!/^ACCOUNT_|LANE_ALREADY_ON_ACCOUNT/.test(last)) break;
330
+ }
331
+ }
332
+ return `resume refused: ${last}`;
333
+ },
334
+ publish: async (file, ids) => {
335
+ const { figmaPublish } = await import("./figma-publish.js");
336
+ const env = { ...process.env };
337
+ if (!env.FIGMA_PAT && !env.FIGMA_TOKEN) {
338
+ const pat = await figmaPatFromKeychain(execute);
339
+ if (!pat) throw new CliError("FIGMA_TOKEN_REQUIRED", "publish-watch needs a Figma token to read the new version: store it once with security add-generic-password -s nodii-dev-figma-pat -a \"$USER\" -w", 1);
340
+ env.FIGMA_PAT = pat;
341
+ }
342
+ return figmaPublish(file, { sets: ids.join(",") }, { request, home, env });
343
+ },
344
+ mergedSince: async (repos, sinceIso) => {
345
+ let merged = 0;
346
+ for (const repo of repos) {
347
+ try {
348
+ const out = (await execute("gh", ["pr", "list", "-R", repo.includes("/") ? repo : `cognion-nucleus/${repo}`, "--state", "merged", "--search", `merged:>=${sinceIso}`, "--json", "headRefName"], { timeout: 30_000 })).stdout;
349
+ merged += JSON.parse(out).filter((pr) => !/changeset-release|docs\/open|release\//.test(pr.headRefName)).length;
350
+ } catch {}
351
+ }
352
+ return merged;
353
+ },
354
+ };
355
+ return ctx;
356
+ }
357
+
358
+ // ---- Running, logging, status -------------------------------------------------
359
+
360
+ export async function watchLog(line, { home = homedir() } = {}) {
361
+ const path = watchLogPath(home);
362
+ await mkdir(dirname(path), { recursive: true, mode: 0o700 });
363
+ await appendFile(path, `${new Date().toISOString()} ${line}\n`);
364
+ }
365
+
366
+ export async function raiseAlert(text, { home = homedir() } = {}) {
367
+ await mkdir(coordinatorHome(home), { recursive: true, mode: 0o700 });
368
+ await appendFile(alertsPath(home), `${new Date().toISOString()} ${text.replace(/\s+/g, " ")}\n`);
369
+ await watchLog(`ALERT ${text}`, { home });
370
+ }
371
+
372
+ /** Runs one job and records its result in the state file. */
373
+ export async function runJob(job, { home = homedir(), ctxFor = (jobState) => watchContext({ home, jobState, log: (l) => watchLog(`${job}: ${l}`, { home }) }), now = Date.now } = {}) {
374
+ const runner = JOB_RUNNERS[job];
375
+ if (!runner) throw new CliError("USAGE", `Unknown job ${job}; jobs: ${Object.keys(JOBS).join(", ")}`, 2);
376
+ const state = await readJson(statePath(home), { jobs: {} });
377
+ state.jobs ??= {};
378
+ const record = state.jobs[job] ?? {};
379
+ const jobState = record.data ?? {};
380
+ const started = now();
381
+ let outcome;
382
+ try {
383
+ if (await exists(holdPath(home, job))) outcome = { ok: true, summary: "held (hold file present)", alerts: [] };
384
+ else {
385
+ const result = await runner(ctxFor(jobState));
386
+ outcome = { ok: true, summary: result.summary, alerts: result.alerts ?? [] };
387
+ }
388
+ } catch (error) {
389
+ outcome = { ok: false, summary: `${error?.code ?? "ERROR"}: ${String(error?.message ?? error).slice(0, 300)}`, alerts: [] };
390
+ }
391
+ const failures = outcome.ok ? 0 : (record.failures ?? 0) + 1;
392
+ if (!outcome.ok && failures === 3) outcome.alerts.push(`watch: ${job} failed 3 times running: ${outcome.summary}`);
393
+ const fresh = await readJson(statePath(home), { jobs: {} });
394
+ fresh.jobs ??= {};
395
+ fresh.jobs[job] = {
396
+ lastStart: new Date(started).toISOString(), lastEnd: new Date(now()).toISOString(), ok: outcome.ok, summary: outcome.summary, failures,
397
+ ...(outcome.ok ? { lastOk: new Date(now()).toISOString() } : { lastOk: record.lastOk ?? null }),
398
+ nextAt: new Date(started + JOBS[job]).toISOString(), data: jobState,
399
+ };
400
+ await writeJson(statePath(home), fresh);
401
+ await watchLog(`${job}: ${outcome.ok ? "ok" : "FAILED"} ${outcome.summary}`, { home });
402
+ for (const alert of outcome.alerts) await raiseAlert(alert, { home });
403
+ return { job, ...outcome };
404
+ }
405
+
406
+ async function pidAlive(pid) {
407
+ try { process.kill(pid, 0); return true; } catch (error) { return error?.code === "EPERM"; }
408
+ }
409
+
410
+ /** The daemon loop. One instance per machine; jobs run one at a time, each on its interval. */
411
+ export async function watchRun({ home = homedir(), tickMs = 30_000, sleep = delay, now = Date.now, run = runJob, forever = true } = {}) {
412
+ const prior = Number((await readFile(pidPath(home), "utf8").catch(() => "")).trim());
413
+ if (prior && prior !== process.pid && (await pidAlive(prior)))
414
+ throw new CliError("WATCH_ALREADY_RUNNING", `coordinator watch is already running (pid ${prior}).`, 1);
415
+ await mkdir(coordinatorHome(home), { recursive: true, mode: 0o700 });
416
+ await writeFile(pidPath(home), `${process.pid}\n`);
417
+ await watchLog(`watch: started (pid ${process.pid})`, { home });
418
+ const stop = () => { forever = false; };
419
+ process.once("SIGTERM", stop);
420
+ try {
421
+ do {
422
+ const state = await readJson(statePath(home), { jobs: {} });
423
+ for (const job of Object.keys(JOBS)) {
424
+ const next = Date.parse(state.jobs?.[job]?.nextAt ?? 0);
425
+ if (!(next > now())) await run(job, { home });
426
+ }
427
+ if (forever) await sleep(tickMs);
428
+ } while (forever);
429
+ } finally {
430
+ process.off("SIGTERM", stop);
431
+ if (Number((await readFile(pidPath(home), "utf8").catch(() => "")).trim()) === process.pid) await rm(pidPath(home), { force: true });
432
+ await watchLog("watch: stopped", { home });
433
+ }
434
+ }
435
+
436
+ /** Each job's health: ok, late (missed its interval twice over), failing, or never run. */
437
+ export async function watchStatus({ home = homedir(), now = Date.now } = {}) {
438
+ const state = await readJson(statePath(home), { jobs: {} });
439
+ const pid = Number((await readFile(pidPath(home), "utf8").catch(() => "")).trim()) || null;
440
+ const running = pid ? await pidAlive(pid) : false;
441
+ const jobs = Object.entries(JOBS).map(([job, interval]) => {
442
+ const r = state.jobs?.[job];
443
+ if (!r) return { job, health: "never run", interval: interval / MIN };
444
+ const late = now() - Date.parse(r.lastStart) > interval * 2 + 5 * MIN;
445
+ const health = !r.ok ? "failing" : late ? "late" : "ok";
446
+ return { job, health, interval: interval / MIN, lastStart: r.lastStart, lastOk: r.lastOk, nextAt: r.nextAt, failures: r.failures, summary: r.summary };
447
+ });
448
+ const unread = (await unreadAlerts({ home })).length;
449
+ return { running, pid, jobs, unreadAlerts: unread, log: watchLogPath(home) };
450
+ }
451
+
452
+ export async function unreadAlerts({ home = homedir(), all = false, markRead = false } = {}) {
453
+ const lines = (await readFile(alertsPath(home), "utf8").catch(() => "")).split("\n").filter(Boolean);
454
+ const read = Number((await readFile(alertsReadPath(home), "utf8").catch(() => "0")).trim()) || 0;
455
+ const out = all ? lines : lines.slice(read);
456
+ if (markRead) await writeFile(alertsReadPath(home), `${lines.length}\n`, { mode: 0o600 });
457
+ return out;
458
+ }
459
+
460
+ /** For the coordinator's SessionStart: unread alerts, shown once. */
461
+ export async function coordinatorAlertLines({ home = homedir() } = {}) {
462
+ const lines = await unreadAlerts({ home, markRead: true });
463
+ if (!lines.length) return [];
464
+ return [`coordinator watch: ${lines.length} new alert(s) (nodii-dev coordinator watch alerts --all for every one):`, ...lines.slice(-10).map((l) => ` ${l}`)];
465
+ }
466
+
467
+ // ---- launchd ------------------------------------------------------------------
468
+
469
+ const xml = (value) => String(value).replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;").replaceAll("'", "&apos;");
470
+
471
+ export function watchPlist({ runtime, entry, config, log, path }) {
472
+ const args = [runtime, entry, "coordinator", "watch", "run"].map((v) => `<string>${xml(v)}</string>`).join("");
473
+ return `<?xml version="1.0" encoding="UTF-8"?>\n<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">\n<plist version="1.0"><dict><key>Label</key><string>${WATCH_LABEL}</string><key>ProgramArguments</key><array>${args}</array><key>EnvironmentVariables</key><dict><key>NODII_DEV_CONFIG_PATH</key><string>${xml(config)}</string><key>PATH</key><string>${xml(path)}</string></dict><key>RunAtLoad</key><true/><key>KeepAlive</key><true/><key>ThrottleInterval</key><integer>60</integer><key>ProcessType</key><string>Background</string><key>StandardOutPath</key><string>${xml(log)}</string><key>StandardErrorPath</key><string>${xml(log)}</string></dict></plist>\n`;
474
+ }
475
+
476
+ /**
477
+ * Installs the daemon for this machine's coordinator. The plist names the
478
+ * coordinator's own config; it carries no secret (the Figma token stays in
479
+ * the keychain).
480
+ */
481
+ export async function installWatch({
482
+ home = homedir(), uid = process.getuid?.(), os = platform(), runtime = process.execPath, entry = resolve(process.argv[1]),
483
+ configFile = configPath(), execute = execFile, config = readConfig, request = devRequest, requireCoordinator = true,
484
+ } = {}) {
485
+ if (os !== "darwin") throw new CliError("WATCH_UNSUPPORTED", "coordinator watch installs with launchd and runs on macOS only.", 2);
486
+ if (requireCoordinator) {
487
+ const { governorSessionKind } = await import("./governor.js");
488
+ const { kind } = await governorSessionKind({ request, config });
489
+ if (kind !== "coordinator") throw new CliError("WATCH_COORDINATOR_ONLY", "Only the machine's coordinator installs coordinator watch: run it with the coordinator's NODII_DEV_CONFIG_PATH.", 1);
490
+ }
491
+ const log = watchLogPath(home);
492
+ const plistPath = join(home, "Library", "LaunchAgents", `${WATCH_LABEL}.plist`);
493
+ // launchd's PATH is bare: give the daemon the tools it calls (git, gh, node, security).
494
+ const path = [dirname(runtime), "/opt/homebrew/bin", "/usr/local/bin", "/usr/bin", "/bin", "/usr/sbin", "/sbin"].join(":");
495
+ const contents = watchPlist({ runtime, entry, config: resolve(configFile), log, path });
496
+ await mkdir(dirname(log), { recursive: true, mode: 0o700 });
497
+ await mkdir(dirname(plistPath), { recursive: true });
498
+ const previous = await readFile(plistPath, "utf8").catch(() => null);
499
+ const service = `gui/${uid}/${WATCH_LABEL}`;
500
+ let loaded = true;
501
+ try { await execute("launchctl", ["print", service]); } catch { loaded = false; }
502
+ if (previous === contents && loaded) return { changed: false, loaded: true, plistPath, label: WATCH_LABEL, log };
503
+ if (loaded) await execute("launchctl", ["bootout", service]).catch(() => {});
504
+ await writeFile(plistPath, contents, { mode: 0o644 });
505
+ try { await execute("launchctl", ["bootstrap", `gui/${uid}`, plistPath]); }
506
+ catch (error) { throw new CliError("WATCH_INSTALL_FAILED", `Could not load ${WATCH_LABEL}: ${error?.message ?? error}`, 1); }
507
+ return { changed: previous !== contents, loaded: true, plistPath, label: WATCH_LABEL, log };
508
+ }
509
+
510
+ /**
511
+ * For harness install/update: on macOS, when this agent is its machine's
512
+ * coordinator, load the watch. Null for anyone else; a failure is reported,
513
+ * never thrown, so the harness install itself still succeeds.
514
+ */
515
+ export async function coordinatorWatchForHarness({ os = platform(), install = installWatch, kindOf } = {}) {
516
+ if (os !== "darwin") return null;
517
+ try {
518
+ const { governorSessionKind } = await import("./governor.js");
519
+ const { kind } = await (kindOf ?? governorSessionKind)();
520
+ if (kind !== "coordinator") return null;
521
+ } catch {
522
+ return null;
523
+ }
524
+ try {
525
+ const data = await install({ requireCoordinator: false });
526
+ return { ...data, line: `coordinator watch: ${data.label} loaded${data.changed ? "" : " (already current)"}; log ${data.log}` };
527
+ } catch (error) {
528
+ return { error: error?.code ?? "WATCH_INSTALL_FAILED", line: `coordinator watch NOT installed: ${error?.message ?? error}` };
529
+ }
530
+ }
531
+
532
+ export async function coordinatorWatchCommand(action, rest, flags, deps = {}) {
533
+ if (action === "board") return boardCommand(flags, deps);
534
+ const sub = rest[0];
535
+ if (sub === "run") {
536
+ await watchRun(deps);
537
+ return { payload: { data: { stopped: true } }, human: "coordinator watch stopped." };
538
+ }
539
+ if (sub === "install") {
540
+ const data = await installWatch(deps);
541
+ return { payload: { data }, human: `${data.label} is loaded from ${data.plistPath}${data.changed ? "" : " (already current)"}; log: ${data.log}` };
542
+ }
543
+ if (sub === "status") {
544
+ const data = await watchStatus(deps);
545
+ return {
546
+ payload: { data },
547
+ human: [
548
+ data.running ? `running (pid ${data.pid}); log ${data.log}` : `NOT RUNNING; install with nodii-dev coordinator watch install. Log ${data.log}`,
549
+ ...data.jobs.map((j) => `${j.job.padEnd(14)} ${j.health.padEnd(9)} every ${j.interval} min${j.lastStart ? `, last ${j.lastStart.slice(11, 16)}Z` : ""}${j.failures ? `, ${j.failures} failure(s)` : ""}${j.summary ? `: ${j.summary}` : ""}`),
550
+ `${data.unreadAlerts} unread alert(s)`,
551
+ ].join("\n"),
552
+ };
553
+ }
554
+ if (sub === "once") {
555
+ const data = await runJob(rest[1], deps);
556
+ if (!data.ok) process.exitCode = 1;
557
+ return { payload: { data }, human: `${data.job}: ${data.ok ? "ok" : "FAILED"} ${data.summary}${data.alerts.length ? `\n${data.alerts.map((a) => `ALERT ${a}`).join("\n")}` : ""}` };
558
+ }
559
+ if (sub === "alerts") {
560
+ const lines = await unreadAlerts({ ...deps, all: Boolean(flags.all), markRead: true });
561
+ return { payload: { data: { alerts: lines } }, human: lines.length ? lines.join("\n") : "No new alerts." };
562
+ }
563
+ throw new CliError("USAGE", "coordinator watch run|install|status|once JOB|alerts [--all] · coordinator board [--write --sheet NAME]", 2);
564
+ }
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.132";
7
+ export const VERSION = "0.6.134";
8
8
  export const configPath = () =>
9
9
  process.env.NODII_DEV_CONFIG_PATH ??
10
10
  join(homedir(), ".config/nodii-dev/config.json");