@nodii/dev 0.6.158 → 0.6.159
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 +28 -8
- package/dist/cli.js +5 -3
- package/dist/closeout.js +14 -11
- package/dist/coordinator-board.js +4 -5
- package/dist/coordinator-watch.js +98 -30
- package/dist/core.js +1 -1
- package/dist/doctor.js +26 -1
- package/dist/lane-env.js +41 -6
- package/dist/starting.js +3 -2
- package/dist/surface.js +23 -10
- package/dist/systemd.js +191 -0
- package/dist/watchdog.js +118 -9
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -140,7 +140,8 @@ The machine's coordinator runs these. The clauses that make them procedure are d
|
|
|
140
140
|
```sh
|
|
141
141
|
nodii-dev coordinator board # print "What needs you" and "What's running" from Dev
|
|
142
142
|
nodii-dev coordinator board --write --sheet 6b # running -> docs/open/6b-status.md, waiting on you -> 6b.md (MW4-31)
|
|
143
|
-
nodii-dev coordinator watch install # launchd com.nodii.coordinator-watch
|
|
143
|
+
nodii-dev coordinator watch install # macOS: launchd com.nodii.coordinator-watch; Linux: systemd nodii-coordinator-watch.service
|
|
144
|
+
# (harness install does this on the coordinator)
|
|
144
145
|
nodii-dev coordinator watch status # each job: health, last run, result
|
|
145
146
|
nodii-dev coordinator watch once publish-watch # one job now, in the foreground
|
|
146
147
|
nodii-dev coordinator watch alerts [--all]
|
|
@@ -150,8 +151,8 @@ nodii-dev figma publish FILE --sets CS-1,CS-2 [--dry-run]
|
|
|
150
151
|
```
|
|
151
152
|
|
|
152
153
|
- **Board.** "Waiting on" comes from Dev's real state: the lane's status, the change sets it holds (state, pending items, file order), Dev's wait records, the heavy-slot queue and `answered.md`. It never comes from the lane's note, which is shown as written in its own column. A question counts as the operator's only when it is an open item on the sheet. `--write` puts "What's running" on the status page `docs/open/<sheet>-status.md` and only the lanes that wait on the operator on the sheet, because MW4-31 keeps status off the sheet. It works in the worktree `nodii-infra/.claude/worktrees/<sheet>-board` and merges through a PR. First it copies every answer the operator typed in their checkout, verbatim, into `answered.md` and into the sheet. Then it fast-forwards the operator's checkout, and only when nothing else there differs from main. An empty board, or one that drops by more than half, is refused (`--force` once you have checked Dev). Priority domains are coordinator configuration in `~/.config/nodii-dev/coordinator/settings.json` (`domains`); a lane outside them is listed under "Other lanes".
|
|
153
|
-
- **Watch.** Jobs and intervals: board 15 min, apply-watch 3, publish-watch 10, real-stuck 30, complexity 30, orphan-slots 10, keepalive 10. Everything goes to one log, `~/Library/Logs/nodii-dev/
|
|
154
|
-
- **publish-watch** stays off until the coordinator sets `"publishWatch": true` in `settings.json`. MW8-7 still names the operator as publisher until hub-429 lands. It needs a Figma token to read the new version. It reads `FIGMA_PAT` from the keychain (`security add-generic-password -s nodii-dev-figma-pat -a "$USER" -w`), never from the plist or a file.
|
|
154
|
+
- **Watch.** Jobs and intervals: board 15 min, apply-watch 3, publish-watch 10, real-stuck 30, complexity 30, orphan-slots 10, keepalive 10. Everything goes to one log, `coordinator-watch.log`, under `~/Library/Logs/nodii-dev/` on macOS and `~/.local/state/nodii-dev/logs/` on Linux. On Linux the memory guard on a resume reads `MemAvailable` from `/proc/meminfo`. Alerts go to `~/.config/nodii-dev/coordinator/alerts.log` and open the coordinator's next session. A job is paused by `~/.config/nodii-dev/coordinator/hold-<job>`. A resume tries the lane's own account first. On an account refusal it tries the accounts listed in `settings.json` `keepaliveProfiles` (`[{ "profile": "/abs/path", "class": "short" }]`), because the account roster is the operator's call (MW1-38.3). The watch never stops a process it did not start (K02-15). It reports an orphaned slot instead.
|
|
155
|
+
- **publish-watch** stays off until the coordinator sets `"publishWatch": true` in `settings.json`. MW8-7 still names the operator as publisher until hub-429 lands. It needs a Figma token to read the new version. It reads `FIGMA_PAT` from the keychain (`security add-generic-password -s nodii-dev-figma-pat -a "$USER" -w`; on Linux the Secret Service, `secret-tool store --label "nodii-dev Figma token" service nodii-dev-figma-pat account "$USER"`), never from the plist, a unit or a file. On Linux the job answers "macOS only".
|
|
155
156
|
- **Chrome.** `chrome start` adopts the Chrome already serving the port, or starts one on the profile, and records the endpoint on Dev's machine record (`hostFacts.sharedChrome`; coordinator or staff only). Every command opens its own background tab and closes only that tab (K02-16, K02-17). `chrome signin` refuses anything but a `tech-*` tenant and a yopmail test identity. It signs in within its own tab and opens `--open PATH` if given. Then it signs out (the app's logout, then that origin's storage and cookies cleared), so no session or token outlives it (MW3-40.2). It never prints or stores a credential, tries each tenant at most once an hour, skips a tenant another tab has open, and rests a tenant after a failed sign-in until `--clear-rest`.
|
|
156
157
|
- **figma publish** refuses a set that is not `awaiting_publish`. It ticks exactly the approved components of the named sets in Figma's Publish library dialog and unticks every other row. It stops if a row won't settle or if it saw fewer rows than the dialog counts. It records a set in Dev only when all of the set's components were published.
|
|
157
158
|
|
|
@@ -652,8 +653,9 @@ nodii-dev harness check [--json] # 0 current, 1 differs from Dev,
|
|
|
652
653
|
nodii-dev repo policy [--json] # print this repository's nodii.repo.yaml facts (STD-11)
|
|
653
654
|
nodii-dev repo lint [--json] # 0 clean, 1 findings
|
|
654
655
|
nodii-dev harness update --check # the same check
|
|
655
|
-
nodii-dev watchdog install [--interval SECONDS] #
|
|
656
|
-
nodii-
|
|
656
|
+
nodii-dev watchdog install [--interval SECONDS] # macOS: com.nodii.watchdog in ~/Library/LaunchAgents
|
|
657
|
+
# Linux: nodii-watchdog.service and .timer in ~/.config/systemd/user
|
|
658
|
+
nodii-dev watchdog sweep # the job's entrypoint; normally not run by hand
|
|
657
659
|
```
|
|
658
660
|
|
|
659
661
|
### Structured dev checks
|
|
@@ -677,7 +679,8 @@ Every entry also has `kind`, `serviceId`, `deployedDigest` (`sha256:...` or a co
|
|
|
677
679
|
|
|
678
680
|
Dev refuses `on_dev` with `DEV_CHECK_FAILED` when the latest check of any kind failed. It refuses with `DEV_CHECK_REQUIRED` when a check is missing: `worker_ready` for a service with an implemented worker in Dev's registry, and `catalog_publish` for a service recorded as using `@nodii/role-catalog`. A rollout status or a passing `/readyz` does not prove a publish: a pod that published earlier keeps serving.
|
|
679
681
|
|
|
680
|
-
The per-
|
|
682
|
+
The per-machine watchdog runs outside agent sessions: under launchd on macOS,
|
|
683
|
+
and as a systemd user timer on Linux. Run `watchdog install` once
|
|
681
684
|
with the machine coordinator's config; it refuses a lane or unassigned agent.
|
|
682
685
|
Every sweep reports three host facts to Dev: watched run processes that exited
|
|
683
686
|
without ending their run, `/tmp/cc-socks/<pid>.sock` sockets whose process is
|
|
@@ -688,7 +691,7 @@ Every watched run whose PID is alive (or whose lane supervisor is, between
|
|
|
688
691
|
same-session continuations) is reported as `process_alive`. That is not a
|
|
689
692
|
heartbeat. With Dev's matching sweep change (NODII-DEV-CLI-42), a lane
|
|
690
693
|
run with no heartbeat goes Quiet at 15 minutes and Orphan at 45 minutes even
|
|
691
|
-
while its
|
|
694
|
+
while its machine still sees the process (MW1-36); a Dev without that change holds
|
|
692
695
|
the run short of Orphan while `process_alive` arrives. Only a coordinator run
|
|
693
696
|
takes `process_alive` as its heartbeat.
|
|
694
697
|
Each sweep also reads Dev's live runs for the machine. A dead process is reported
|
|
@@ -700,10 +703,26 @@ A sweep leaves a dead lane runtime alone while its lane supervisor still lives
|
|
|
700
703
|
(the supervisor reports the exit itself) and skips it once the supervisor has
|
|
701
704
|
reported.
|
|
702
705
|
Run launchers and wrappers persist one owner-only record per process under
|
|
703
|
-
`~/.config/nodii-dev/watchdog/runs/`; the plist itself contains only absolute
|
|
706
|
+
`~/.config/nodii-dev/watchdog/runs/`; the plist or unit itself contains only absolute
|
|
704
707
|
command/config paths, its schedule, and log paths, while OAuth credentials
|
|
705
708
|
remain in the machine keychain.
|
|
706
709
|
|
|
710
|
+
On Linux the job is two systemd user units, installed without root:
|
|
711
|
+
|
|
712
|
+
| Unit | What it does |
|
|
713
|
+
| --- | --- |
|
|
714
|
+
| `~/.config/systemd/user/nodii-watchdog.service` | One sweep (`Type=oneshot`), with `NODII_DEV_CONFIG_PATH` and the installing shell's `PATH`. Output goes to `~/.local/state/nodii-dev/logs/watchdog.log` and `watchdog.error.log`. |
|
|
715
|
+
| `~/.config/systemd/user/nodii-watchdog.timer` | Starts the service at install and at login, then every `--interval` seconds (`AccuracySec=1s`, since a timer's default slack is a minute). |
|
|
716
|
+
|
|
717
|
+
- **Install.** `watchdog install` runs `systemctl --user daemon-reload` and `enable --now nodii-watchdog.timer`. Identical units under a running timer change nothing; identical units under a stopped or disabled timer are started again, and the install says so. A new coordinator's config rewrites the service and restarts the timer. If systemd refuses, the previous units come back and the command fails with `WATCHDOG_INSTALL_FAILED`.
|
|
718
|
+
- **Where.** The unit and log directories are the ones the systemd user manager uses: `XDG_CONFIG_HOME` and `XDG_STATE_HOME` are read from `systemctl --user show-environment`, not from the installing shell, so the units are where systemd looks and the logs are where the daemon writes. Unset, they are `~/.config` and `~/.local/state`.
|
|
719
|
+
- **A hung sweep.** systemd turns the start timeout off for a oneshot service, so the service sets `TimeoutStartSec` to three intervals, ten minutes at the least. A sweep that runs longer is stopped and reads failed (`Result=timeout`), and the next firing sweeps again. A sweep that could not tell Dev about a run (a failed run report, Dev's live runs or a local run record unreadable) exits 1, so it reads failed too; errors in its other jobs are recorded in its output and do not fail it.
|
|
720
|
+
- **`KillMode=process`.** A sweep resumes resume-due lanes, and coordinator watch's keepalive does too. systemd's default stops every process left in a unit's control group when the unit stops, which would end each resumed lane as its sweep exits. Both units stop only their own process.
|
|
721
|
+
- **Lingering.** Without it the units run only while the user is logged in. `watchdog install` reports the state and never changes it; `loginctl enable-linger` is the operator's choice. The sign-in stays in the login keyring, which a login unlocks.
|
|
722
|
+
- **Look at it.** `systemctl --user list-timers nodii-watchdog.timer`, `systemctl --user status nodii-watchdog.service`, and `nodii-dev doctor`. Its `watchdog` check also reads how the last sweep ended, and reports a running timer whose sweep failed or timed out.
|
|
723
|
+
|
|
724
|
+
Coordinator watch is `nodii-coordinator-watch.service` on Linux (`Restart=always`, `RestartSec=60`), installed the same way. `harness install` and `harness update` on the coordinator start it, and their line says so, with the lingering notice when lingering is off. Its publish-watch job is macOS only: the shared Chrome is found and started there. Any other operating system is refused with `WATCHDOG_UNSUPPORTED` or `WATCH_UNSUPPORTED`.
|
|
725
|
+
|
|
707
726
|
`harness install` and `harness update` merge the safety hooks into both
|
|
708
727
|
`.claude/settings.json` and `.codex/hooks.json`; every installed hook invokes
|
|
709
728
|
only `nodii-dev`. The
|
|
@@ -1280,6 +1299,7 @@ exits 0 only when every check is `OK`. `--json` returns the same checks as
|
|
|
1280
1299
|
| `hooks_claude` | Whether Claude hooks are installed, trusted by that runtime, and have a private firing receipt. |
|
|
1281
1300
|
| `hooks_codex_personal`, `hooks_codex_work` | For `~/.codex` and `~/.codex-work`, whether Codex's own hook registry reports the hooks installed and trusted (including managed status), whether the managed absolute CLI is present and new enough, and whether that profile has fired one. |
|
|
1282
1301
|
| `host_restart` | For the machine's coordinator: whether Dev has recorded this machine's boot, then whether any lane is still `host_lost`. `MISSING` names the next command. Other agents read `OK`. |
|
|
1302
|
+
| `watchdog` | For the machine's coordinator: whether the watchdog job is installed, running, and runs under this coordinator's config (launchd on macOS, `nodii-watchdog.timer` on Linux). `MISSING` names `watchdog install`. Other agents read `OK`. |
|
|
1283
1303
|
| `lane_env` | Every `claude` and `codex` process whose working directory is in an active lane's worktree on this machine, and whether its environment carries `NODII_DEV_CONFIG_PATH` naming that lane's `lane-<key>.json`. The managed hooks exit without acting for a process without it (AGENT-HARNESS-61). Run inside a lane, it checks that lane only. `MISSING` names each process; `lane launch` and `lane resume` start the agent with the variable set. `lane check` prints the same report for its lane as `lane_env:` lines, without blocking the review. |
|
|
1284
1304
|
|
|
1285
1305
|
Doctor may refresh the access token, as any command does. The permission table
|
package/dist/cli.js
CHANGED
|
@@ -278,8 +278,9 @@ Usage: nodii-dev <command> [options] [--json]
|
|
|
278
278
|
repo policy # print this repository's nodii.repo.yaml facts (STD-11)
|
|
279
279
|
repo lint # 0 clean, 1 findings: policy file missing or invalid, stray root
|
|
280
280
|
# files, docs layout, scratch not gitignored, test scripts
|
|
281
|
-
watchdog install [--interval SECONDS] # install/update the per-
|
|
282
|
-
|
|
281
|
+
watchdog install [--interval SECONDS] # install/update the per-machine liveness sweep (default 60s): launchd on
|
|
282
|
+
# macOS, a systemd user timer (nodii-watchdog.timer) on Linux
|
|
283
|
+
watchdog sweep # the job's entrypoint: report dead runs, stale sockets, unpushed worktrees,
|
|
283
284
|
# and re-report account usage every 5 min
|
|
284
285
|
docs check|validate|upload <path...> --class ruling|conformance|editorial
|
|
285
286
|
[--base CODE=VERSION] [--decision FILE] [--conformance-ref REF]
|
|
@@ -321,7 +322,8 @@ Usage: nodii-dev <command> [options] [--json]
|
|
|
321
322
|
# docs/open/<sheet>-status.md and waiting-on-you into <sheet>.md (MW4-31),
|
|
322
323
|
# from a nodii-infra worktree, harvesting typed answers first
|
|
323
324
|
coordinator watch run|install|status|once JOB|alerts [--all]
|
|
324
|
-
# the coordinator's supervised daemon (launchd: com.nodii.coordinator-watch
|
|
325
|
+
# the coordinator's supervised daemon (launchd: com.nodii.coordinator-watch;
|
|
326
|
+
# systemd: nodii-coordinator-watch.service):
|
|
325
327
|
# board, apply-watch, publish-watch, real-stuck, complexity, orphan slots,
|
|
326
328
|
# keepalive; one log, and status shows each job's health
|
|
327
329
|
chrome start [--profile DIR] [--port N] | chrome status
|
package/dist/closeout.js
CHANGED
|
@@ -17,10 +17,12 @@
|
|
|
17
17
|
// steps that depend on it are skipped, never forced.
|
|
18
18
|
import { execFile } from "node:child_process";
|
|
19
19
|
import { existsSync } from "node:fs";
|
|
20
|
+
import { realpath } from "node:fs/promises";
|
|
20
21
|
import { dirname, resolve, sep } from "node:path";
|
|
21
22
|
import { promisify } from "node:util";
|
|
22
23
|
import { encode } from "./core.js";
|
|
23
24
|
import { heavySlotArgv } from "./heavy.js";
|
|
25
|
+
import { procCwds, processCwds } from "./lane-env.js";
|
|
24
26
|
|
|
25
27
|
const execFileAsync = promisify(execFile);
|
|
26
28
|
export const STOPPED_LABEL = "Stopped";
|
|
@@ -45,18 +47,19 @@ const inside = (path, root) => {
|
|
|
45
47
|
return a === b || a.startsWith(b + sep);
|
|
46
48
|
};
|
|
47
49
|
|
|
48
|
-
/**
|
|
49
|
-
|
|
50
|
+
/**
|
|
51
|
+
* PIDs whose current directory is inside the worktree (MW1-49). The kernel,
|
|
52
|
+
* and so lsof and /proc, report a directory with its symlinks resolved, so the
|
|
53
|
+
* worktree is compared both as recorded and resolved: a worktree reached
|
|
54
|
+
* through a symlinked parent is still seen as busy.
|
|
55
|
+
*/
|
|
56
|
+
export async function processesIn(worktree, exec, selfCwd, { platform = process.platform, cwds = procCwds, real = (path) => realpath(path).catch(() => resolve(path)) } = {}) {
|
|
57
|
+
const roots = [...new Set([resolve(worktree), await real(worktree)])];
|
|
58
|
+
const within = (path) => roots.some((root) => inside(path, root));
|
|
50
59
|
const found = [];
|
|
51
|
-
if (
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
catch (error) { out = error?.stdout ?? ""; }
|
|
55
|
-
let pid = null;
|
|
56
|
-
for (const line of out.split("\n")) {
|
|
57
|
-
if (line.startsWith("p")) pid = Number(line.slice(1));
|
|
58
|
-
else if (line.startsWith("n") && pid && pid !== process.pid && inside(line.slice(1), worktree)) found.push({ pid, cwd: line.slice(1) });
|
|
59
|
-
}
|
|
60
|
+
if (within(selfCwd)) found.push({ pid: process.pid, cwd: selfCwd });
|
|
61
|
+
for (const [pid, cwd] of await processCwds({ platform, lsof: (args) => exec("lsof", args), proc: cwds }))
|
|
62
|
+
if (pid !== process.pid && within(cwd)) found.push({ pid, cwd });
|
|
60
63
|
return found;
|
|
61
64
|
}
|
|
62
65
|
|
|
@@ -19,6 +19,7 @@ import { promisify } from "node:util";
|
|
|
19
19
|
import { fileURLToPath } from "node:url";
|
|
20
20
|
import { CliError, devRequest, encode, query, readConfig } from "./core.js";
|
|
21
21
|
import { governorMachineId } from "./governor.js";
|
|
22
|
+
import { procCwds, processCwds } from "./lane-env.js";
|
|
22
23
|
|
|
23
24
|
const execFile = promisify(execFileCallback);
|
|
24
25
|
export const coordinatorHome = (home = homedir()) => join(home, ".config", "nodii-dev", "coordinator");
|
|
@@ -110,14 +111,12 @@ export function parseHeavyStatus(text, cwdOf = () => null) {
|
|
|
110
111
|
return { holding, queued };
|
|
111
112
|
}
|
|
112
113
|
|
|
113
|
-
export async function heavyQueue({ execute = execFile } = {}) {
|
|
114
|
+
export async function heavyQueue({ execute = execFile, os = process.platform, procCwd = procCwds } = {}) {
|
|
114
115
|
const slot = join(dirname(fileURLToPath(import.meta.url)), "heavy-slot.sh");
|
|
115
116
|
let text = "";
|
|
116
117
|
try { text = (await execute("/bin/bash", [slot, "--status"], { timeout: 20_000 })).stdout; } catch { return { holding: new Map(), queued: new Map() }; }
|
|
117
|
-
const
|
|
118
|
-
|
|
119
|
-
try { cwds.set(pid, (await execute("lsof", ["-a", "-p", String(pid), "-d", "cwd", "-Fn"])).stdout.split("\n").find((l) => l.startsWith("n"))?.slice(1)); } catch {}
|
|
120
|
-
}
|
|
118
|
+
const pids = [...text.matchAll(/queued \d+: pid (\d+)/g)].map((m) => Number(m[1]));
|
|
119
|
+
const cwds = pids.length ? await processCwds({ pids, platform: os, lsof: async (args) => (await execute("lsof", args)).stdout, proc: procCwd }) : new Map();
|
|
121
120
|
return parseHeavyStatus(text, (pid) => cwds.get(pid));
|
|
122
121
|
}
|
|
123
122
|
|
|
@@ -1,14 +1,16 @@
|
|
|
1
1
|
// nodii-dev coordinator watch: the coordinator's supervised daemon.
|
|
2
2
|
//
|
|
3
|
-
// coordinator watch run the loop
|
|
4
|
-
// coordinator watch install writes and loads ~/Library/LaunchAgents/com.nodii.coordinator-watch.plist
|
|
3
|
+
// coordinator watch run the loop the service manager keeps alive; one instance per machine
|
|
4
|
+
// coordinator watch install macOS: writes and loads ~/Library/LaunchAgents/com.nodii.coordinator-watch.plist
|
|
5
|
+
// Linux: writes and starts ~/.config/systemd/user/nodii-coordinator-watch.service
|
|
5
6
|
// coordinator watch status each job's health: last run, result, next run, failures
|
|
6
7
|
// coordinator watch once JOB one job now, in the foreground (for a person or a test)
|
|
7
8
|
// coordinator watch alerts alerts not yet shown to the coordinator session (--all for every one)
|
|
8
9
|
//
|
|
9
10
|
// Jobs (hub-405): board, apply-watch, publish-watch, real-stuck,
|
|
10
11
|
// complexity, orphan-slots, keepalive. Everything goes to one log
|
|
11
|
-
// (~/Library/Logs/nodii-dev
|
|
12
|
+
// (coordinator-watch.log under ~/Library/Logs/nodii-dev on macOS and
|
|
13
|
+
// ~/.local/state/nodii-dev/logs on Linux); alerts also go to
|
|
12
14
|
// alerts.log, which the coordinator's SessionStart shows until read.
|
|
13
15
|
//
|
|
14
16
|
// The daemon reads Dev and this machine. It never stops a process it did not
|
|
@@ -25,15 +27,23 @@ import {
|
|
|
25
27
|
DEFAULT_DOMAINS, boardCommand, coordinatorHome, heavyQueue, laneDomain, laneProcesses, liveChangeSets, machineLanes, readCoordinatorSettings,
|
|
26
28
|
} from "./coordinator-board.js";
|
|
27
29
|
import { governorMachineId } from "./governor.js";
|
|
30
|
+
import { envAssignment, execLine, installNote, installSupervised, lingerLine, logsDir, supervisedDirs, unitPath, unitText } from "./systemd.js";
|
|
28
31
|
|
|
29
32
|
const execFile = promisify(execFileCallback);
|
|
30
33
|
const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
31
34
|
export const WATCH_LABEL = "com.nodii.coordinator-watch";
|
|
35
|
+
/** The same daemon on Linux, as a systemd user service. */
|
|
36
|
+
export const WATCH_SERVICE = "nodii-coordinator-watch.service";
|
|
32
37
|
const statePath = (home) => join(coordinatorHome(home), "watch-state.json");
|
|
33
38
|
const pidPath = (home) => join(coordinatorHome(home), "watch.pid");
|
|
34
39
|
export const alertsPath = (home = homedir()) => join(coordinatorHome(home), "alerts.log");
|
|
35
40
|
const alertsReadPath = (home) => join(coordinatorHome(home), "alerts.read");
|
|
36
|
-
|
|
41
|
+
/**
|
|
42
|
+
* The daemon's log. The daemon resolves it from its own environment, which on
|
|
43
|
+
* Linux is the systemd user manager's; anything else that names the log (the
|
|
44
|
+
* install, status) passes that same environment.
|
|
45
|
+
*/
|
|
46
|
+
export const watchLogPath = (home = homedir(), os = platform(), env = process.env) => join(logsDir({ home, os, env }), "coordinator-watch.log");
|
|
37
47
|
const workaroundsPath = (home) => join(coordinatorHome(home), "workarounds.log");
|
|
38
48
|
const holdPath = (home, job) => join(coordinatorHome(home), `hold-${job}`);
|
|
39
49
|
|
|
@@ -63,9 +73,18 @@ async function writeJson(path, value) {
|
|
|
63
73
|
// ---- Shared reads -------------------------------------------------------------
|
|
64
74
|
|
|
65
75
|
/** Machine guards for a resume (the prototype's numbers, measured on this Mac, 12 Nov). */
|
|
66
|
-
export async function machineGuards({ execute = execFile, load = loadavg } = {}) {
|
|
76
|
+
export async function machineGuards({ execute = execFile, load = loadavg, os = platform(), read = readFile } = {}) {
|
|
67
77
|
let freePercent = null;
|
|
68
|
-
|
|
78
|
+
if (os === "linux") {
|
|
79
|
+
// Linux has no memory_pressure: what a new process can have is MemAvailable.
|
|
80
|
+
try {
|
|
81
|
+
const meminfo = await read("/proc/meminfo", "utf8");
|
|
82
|
+
const kb = (name) => Number(meminfo.match(new RegExp(`^${name}:\\s+(\\d+) kB`, "m"))?.[1] ?? NaN);
|
|
83
|
+
freePercent = Math.round((kb("MemAvailable") / kb("MemTotal")) * 100);
|
|
84
|
+
} catch {}
|
|
85
|
+
} else {
|
|
86
|
+
try { freePercent = Number((await execute("memory_pressure", [], { timeout: 15_000 })).stdout.match(/free percentage:\s*(\d+)/i)?.[1] ?? NaN); } catch {}
|
|
87
|
+
}
|
|
69
88
|
let laneProcesses = null;
|
|
70
89
|
try { laneProcesses = (await execute("ps", ["-axo", "command="], { maxBuffer: 32 * 1024 * 1024 })).stdout.split("\n").filter((l) => /^claude --print\b/.test(l)).length; } catch {}
|
|
71
90
|
return { load15: Math.round(load()[2]), freePercent: Number.isFinite(freePercent) ? freePercent : null, laneProcesses };
|
|
@@ -139,6 +158,8 @@ async function publishWatchJob(ctx) {
|
|
|
139
158
|
// Off until the coordinator turns it on: the rulebook still names the operator
|
|
140
159
|
// as publisher (MW8-7) until hub-429 lands the operator's 13 Nov word.
|
|
141
160
|
if (!(await readCoordinatorSettings(ctx.home)).publishWatch) return { summary: "off (settings.json publishWatch is not true; hub-429)" };
|
|
161
|
+
// The publish drives the shared Chrome, which this CLI finds and starts on macOS only.
|
|
162
|
+
if (ctx.os && ctx.os !== "darwin") return { summary: `macOS only (the shared Chrome is not driven on ${ctx.os})` };
|
|
142
163
|
const state = ctx.jobState;
|
|
143
164
|
state.backoff ??= {};
|
|
144
165
|
const sets = (await liveChangeSets(ctx)).filter((set) => set.state === "awaiting_publish");
|
|
@@ -286,22 +307,31 @@ export const JOB_RUNNERS = {
|
|
|
286
307
|
|
|
287
308
|
// ---- The context the jobs run in ----------------------------------------------
|
|
288
309
|
|
|
289
|
-
|
|
290
|
-
|
|
310
|
+
const FIGMA_PAT_SERVICE = "nodii-dev-figma-pat";
|
|
311
|
+
const figmaPatStoreCommand = (os) => os === "linux"
|
|
312
|
+
? `secret-tool store --label "nodii-dev Figma token" service ${FIGMA_PAT_SERVICE} account "$USER"`
|
|
313
|
+
: `security add-generic-password -s ${FIGMA_PAT_SERVICE} -a "$USER" -w`;
|
|
314
|
+
|
|
315
|
+
/** The Figma token from the machine's secret store: the macOS keychain, or the Secret Service on Linux. */
|
|
316
|
+
export async function figmaPatFromKeychain(execute, os = platform()) {
|
|
317
|
+
const [command, args] = os === "linux"
|
|
318
|
+
? ["secret-tool", ["lookup", "service", FIGMA_PAT_SERVICE]]
|
|
319
|
+
: ["security", ["find-generic-password", "-s", FIGMA_PAT_SERVICE, "-w"]];
|
|
320
|
+
try { return (await execute(command, args, { timeout: 10_000 })).stdout.trim() || null; }
|
|
291
321
|
catch { return null; }
|
|
292
322
|
}
|
|
293
323
|
|
|
294
|
-
export function watchContext({ home = homedir(), request = devRequest, config = readConfig, execute = execFile, now = Date.now, sleep = delay, log, jobState = {} } = {}) {
|
|
324
|
+
export function watchContext({ home = homedir(), request = devRequest, config = readConfig, execute = execFile, now = Date.now, sleep = delay, log, jobState = {}, os = platform() } = {}) {
|
|
295
325
|
let machine = null;
|
|
296
326
|
let processesCache = null;
|
|
297
327
|
let guardsCache = null;
|
|
298
328
|
const ctx = {
|
|
299
|
-
home, request, now, sleep, jobState,
|
|
329
|
+
home, request, now, sleep, jobState, os,
|
|
300
330
|
stamp: () => new Date(now()).toISOString().slice(11, 16) + "Z",
|
|
301
331
|
machineId: async () => (machine ??= await governorMachineId({}, { request, config })),
|
|
302
332
|
processes: async () => (processesCache ??= await laneProcesses()),
|
|
303
|
-
heavy: () => heavyQueue({ execute }),
|
|
304
|
-
guards: async () => (guardsCache ??= await machineGuards({ execute })),
|
|
333
|
+
heavy: () => heavyQueue({ execute, os }),
|
|
334
|
+
guards: async () => (guardsCache ??= await machineGuards({ execute, os })),
|
|
305
335
|
amend: async (key, rules, reason) => {
|
|
306
336
|
const { amendLaneCommand } = await import("./starting.js");
|
|
307
337
|
await amendLaneCommand(key, { rules, reason });
|
|
@@ -335,8 +365,8 @@ export function watchContext({ home = homedir(), request = devRequest, config =
|
|
|
335
365
|
const { figmaPublish } = await import("./figma-publish.js");
|
|
336
366
|
const env = { ...process.env };
|
|
337
367
|
if (!env.FIGMA_PAT && !env.FIGMA_TOKEN) {
|
|
338
|
-
const pat = await figmaPatFromKeychain(execute);
|
|
339
|
-
if (!pat) throw new CliError("FIGMA_TOKEN_REQUIRED",
|
|
368
|
+
const pat = await figmaPatFromKeychain(execute, os);
|
|
369
|
+
if (!pat) throw new CliError("FIGMA_TOKEN_REQUIRED", `publish-watch needs a Figma token to read the new version: store it once with ${figmaPatStoreCommand(os)}`, 1);
|
|
340
370
|
env.FIGMA_PAT = pat;
|
|
341
371
|
}
|
|
342
372
|
return figmaPublish(file, { sets: ids.join(",") }, { request, home, env });
|
|
@@ -434,7 +464,9 @@ export async function watchRun({ home = homedir(), tickMs = 30_000, sleep = dela
|
|
|
434
464
|
}
|
|
435
465
|
|
|
436
466
|
/** 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 } = {}) {
|
|
467
|
+
export async function watchStatus({ home = homedir(), now = Date.now, os = platform(), execute = execFile } = {}) {
|
|
468
|
+
// On Linux the daemon's log is where the user manager's environment puts it, not this shell's.
|
|
469
|
+
const log = os === "linux" ? join((await supervisedDirs({ home, execute })).logs, "coordinator-watch.log") : watchLogPath(home, os);
|
|
438
470
|
const state = await readJson(statePath(home), { jobs: {} });
|
|
439
471
|
const pid = Number((await readFile(pidPath(home), "utf8").catch(() => "")).trim()) || null;
|
|
440
472
|
const running = pid ? await pidAlive(pid) : false;
|
|
@@ -446,7 +478,7 @@ export async function watchStatus({ home = homedir(), now = Date.now } = {}) {
|
|
|
446
478
|
return { job, health, interval: interval / MIN, lastStart: r.lastStart, lastOk: r.lastOk, nextAt: r.nextAt, failures: r.failures, summary: r.summary };
|
|
447
479
|
});
|
|
448
480
|
const unread = (await unreadAlerts({ home })).length;
|
|
449
|
-
return { running, pid, jobs, unreadAlerts: unread, log
|
|
481
|
+
return { running, pid, jobs, unreadAlerts: unread, log };
|
|
450
482
|
}
|
|
451
483
|
|
|
452
484
|
export async function unreadAlerts({ home = homedir(), all = false, markRead = false } = {}) {
|
|
@@ -464,7 +496,7 @@ export async function coordinatorAlertLines({ home = homedir() } = {}) {
|
|
|
464
496
|
return [`coordinator watch: ${lines.length} new alert(s) (nodii-dev coordinator watch alerts --all for every one):`, ...lines.slice(-10).map((l) => ` ${l}`)];
|
|
465
497
|
}
|
|
466
498
|
|
|
467
|
-
// ---- launchd
|
|
499
|
+
// ---- The service manager: launchd on macOS, systemd on Linux ------------------
|
|
468
500
|
|
|
469
501
|
const xml = (value) => String(value).replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">").replaceAll('"', """).replaceAll("'", "'");
|
|
470
502
|
|
|
@@ -474,21 +506,55 @@ export function watchPlist({ runtime, entry, config, log, path }) {
|
|
|
474
506
|
}
|
|
475
507
|
|
|
476
508
|
/**
|
|
477
|
-
*
|
|
478
|
-
*
|
|
509
|
+
* The Linux daemon: restarted whenever it exits, a minute apart (launchd's
|
|
510
|
+
* KeepAlive and ThrottleInterval). KillMode=process because keepalive resumes
|
|
511
|
+
* lanes, and those processes stay in this service's control group: systemd's
|
|
512
|
+
* default would stop every one of them when the daemon restarts, and the
|
|
513
|
+
* daemon never stops a process it did not start (K02-15).
|
|
514
|
+
*/
|
|
515
|
+
export function watchUnit({ runtime, entry, config, log, path }) {
|
|
516
|
+
return unitText([
|
|
517
|
+
["Unit", [["Description", "nodii-dev coordinator watch"]]],
|
|
518
|
+
["Service", [
|
|
519
|
+
["ExecStart", execLine([runtime, entry, "coordinator", "watch", "run"])],
|
|
520
|
+
["Environment", envAssignment("NODII_DEV_CONFIG_PATH", config)],
|
|
521
|
+
["Environment", envAssignment("PATH", path)],
|
|
522
|
+
["Restart", "always"],
|
|
523
|
+
["RestartSec", "60"],
|
|
524
|
+
["StandardOutput", `append:${unitPath(log)}`],
|
|
525
|
+
["StandardError", `append:${unitPath(log)}`],
|
|
526
|
+
["KillMode", "process"],
|
|
527
|
+
]],
|
|
528
|
+
["Install", [["WantedBy", "default.target"]]],
|
|
529
|
+
]);
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
/**
|
|
533
|
+
* Installs the daemon for this machine's coordinator. The plist or unit names
|
|
534
|
+
* the coordinator's own config; it carries no secret (the Figma token stays in
|
|
479
535
|
* the keychain).
|
|
480
536
|
*/
|
|
481
537
|
export async function installWatch({
|
|
482
|
-
home = homedir(), uid = process.getuid?.(), os = platform(), runtime = process.execPath, entry = resolve(process.argv[1]),
|
|
538
|
+
home = homedir(), uid = process.getuid?.(), os = platform(), env = process.env, runtime = process.execPath, entry = resolve(process.argv[1]),
|
|
483
539
|
configFile = configPath(), execute = execFile, config = readConfig, request = devRequest, requireCoordinator = true,
|
|
484
540
|
} = {}) {
|
|
485
|
-
if (os !== "darwin"
|
|
541
|
+
if (os !== "darwin" && os !== "linux")
|
|
542
|
+
throw new CliError("WATCH_UNSUPPORTED", `coordinator watch installs with launchd on macOS and with a systemd user service on Linux; ${os} is not supported.`, 2);
|
|
486
543
|
if (requireCoordinator) {
|
|
487
544
|
const { governorSessionKind } = await import("./governor.js");
|
|
488
545
|
const { kind } = await governorSessionKind({ request, config });
|
|
489
546
|
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
547
|
}
|
|
491
|
-
|
|
548
|
+
if (os === "linux") {
|
|
549
|
+
// The daemon resumes lanes, so it needs the installing shell's PATH to find the lane runtime (hub-251).
|
|
550
|
+
const { watchdogPath } = await import("./watchdog.js");
|
|
551
|
+
const { logs, ...installed } = await installSupervised({
|
|
552
|
+
home, execute, activate: WATCH_SERVICE, errorCode: "WATCH_INSTALL_FAILED",
|
|
553
|
+
build: ({ logs: dir }) => [{ name: WATCH_SERVICE, contents: watchUnit({ runtime, entry, config: resolve(configFile), log: join(dir, "coordinator-watch.log"), path: watchdogPath(env.PATH, runtime) }) }],
|
|
554
|
+
});
|
|
555
|
+
return { ...installed, log: join(logs, "coordinator-watch.log") };
|
|
556
|
+
}
|
|
557
|
+
const log = watchLogPath(home, os);
|
|
492
558
|
const plistPath = join(home, "Library", "LaunchAgents", `${WATCH_LABEL}.plist`);
|
|
493
559
|
// launchd's PATH is bare: give the daemon the tools it calls (git, gh, node, security).
|
|
494
560
|
const path = [dirname(runtime), "/opt/homebrew/bin", "/usr/local/bin", "/usr/bin", "/bin", "/usr/sbin", "/sbin"].join(":");
|
|
@@ -499,21 +565,21 @@ export async function installWatch({
|
|
|
499
565
|
const service = `gui/${uid}/${WATCH_LABEL}`;
|
|
500
566
|
let loaded = true;
|
|
501
567
|
try { await execute("launchctl", ["print", service]); } catch { loaded = false; }
|
|
502
|
-
if (previous === contents && loaded) return { changed: false, loaded: true, plistPath, label: WATCH_LABEL, log };
|
|
568
|
+
if (previous === contents && loaded) return { changed: false, loaded: true, manager: "launchd", plistPath, label: WATCH_LABEL, log };
|
|
503
569
|
if (loaded) await execute("launchctl", ["bootout", service]).catch(() => {});
|
|
504
570
|
await writeFile(plistPath, contents, { mode: 0o644 });
|
|
505
571
|
try { await execute("launchctl", ["bootstrap", `gui/${uid}`, plistPath]); }
|
|
506
572
|
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 };
|
|
573
|
+
return { changed: previous !== contents, loaded: true, manager: "launchd", plistPath, label: WATCH_LABEL, log };
|
|
508
574
|
}
|
|
509
575
|
|
|
510
576
|
/**
|
|
511
|
-
* For harness install/update: on macOS, when this agent is its
|
|
512
|
-
* coordinator, load the watch. Null for anyone else; a failure is
|
|
513
|
-
* never thrown, so the harness install itself still succeeds.
|
|
577
|
+
* For harness install/update: on macOS and Linux, when this agent is its
|
|
578
|
+
* machine's coordinator, load the watch. Null for anyone else; a failure is
|
|
579
|
+
* reported, never thrown, so the harness install itself still succeeds.
|
|
514
580
|
*/
|
|
515
581
|
export async function coordinatorWatchForHarness({ os = platform(), install = installWatch, kindOf } = {}) {
|
|
516
|
-
if (os !== "darwin") return null;
|
|
582
|
+
if (os !== "darwin" && os !== "linux") return null;
|
|
517
583
|
try {
|
|
518
584
|
const { governorSessionKind } = await import("./governor.js");
|
|
519
585
|
const { kind } = await (kindOf ?? governorSessionKind)();
|
|
@@ -523,7 +589,8 @@ export async function coordinatorWatchForHarness({ os = platform(), install = in
|
|
|
523
589
|
}
|
|
524
590
|
try {
|
|
525
591
|
const data = await install({ requireCoordinator: false });
|
|
526
|
-
|
|
592
|
+
// The daemon is the coordinator's standing job: it is started here, and the line says so, with lingering.
|
|
593
|
+
return { ...data, line: [`coordinator watch: ${data.label} loaded${installNote(data)}; log ${data.log}`, lingerLine(data.linger)].filter(Boolean).join(" ") };
|
|
527
594
|
} catch (error) {
|
|
528
595
|
return { error: error?.code ?? "WATCH_INSTALL_FAILED", line: `coordinator watch NOT installed: ${error?.message ?? error}` };
|
|
529
596
|
}
|
|
@@ -538,7 +605,8 @@ export async function coordinatorWatchCommand(action, rest, flags, deps = {}) {
|
|
|
538
605
|
}
|
|
539
606
|
if (sub === "install") {
|
|
540
607
|
const data = await installWatch(deps);
|
|
541
|
-
|
|
608
|
+
const from = data.plistPath ?? data.unitPaths.join(" and ");
|
|
609
|
+
return { payload: { data }, human: [`${data.label} is loaded from ${from}${installNote(data)}; log: ${data.log}`, lingerLine(data.linger)].filter(Boolean).join("\n") };
|
|
542
610
|
}
|
|
543
611
|
if (sub === "status") {
|
|
544
612
|
const data = await watchStatus(deps);
|
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.
|
|
7
|
+
export const VERSION = "0.6.159";
|
|
8
8
|
export const configPath = () =>
|
|
9
9
|
process.env.NODII_DEV_CONFIG_PATH ??
|
|
10
10
|
join(homedir(), ".config/nodii-dev/config.json");
|
package/dist/doctor.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { readFile } from "node:fs/promises";
|
|
2
2
|
import { homedir } from "node:os";
|
|
3
|
-
import { basename, join } from "node:path";
|
|
3
|
+
import { basename, join, resolve } from "node:path";
|
|
4
4
|
import { devRequest, encode, isOAuthConfig, query, setAuthProvider } from "./core.js";
|
|
5
5
|
import { OAuthAuthProvider, decodeClaims, loadRefreshToken } from "./oauth.js";
|
|
6
6
|
import { inferGitContext, repoName } from "./lanes.js";
|
|
@@ -11,6 +11,7 @@ import { managedStatus } from "./managed-version.js";
|
|
|
11
11
|
import { hostBootedAt } from "./host.js";
|
|
12
12
|
import { listAccounts } from "./accounts.js";
|
|
13
13
|
import { LANE_ENV_FIX, agentProcesses, laneConfigName, laneEnvProblem, laneEnvReport } from "./lane-env.js";
|
|
14
|
+
import { watchdogStatus } from "./watchdog.js";
|
|
14
15
|
|
|
15
16
|
/**
|
|
16
17
|
* What a lane's commands need, in Dev's route policy (staffRuleFor in Dev's
|
|
@@ -402,6 +403,30 @@ export async function doctorCommand(deps = {}) {
|
|
|
402
403
|
}
|
|
403
404
|
}
|
|
404
405
|
|
|
406
|
+
// The machine's watchdog job (launchd on macOS, a systemd timer on Linux):
|
|
407
|
+
// without it no sweep reports a dead lane process, and it must run under this
|
|
408
|
+
// coordinator's config or Dev refuses every sweep (NODII-DEV-CLI-42). It is
|
|
409
|
+
// the coordinator's to keep, so a lane reads ok here, as for a restart.
|
|
410
|
+
if (!agent?.machineId) checks.push(cannot("watchdog", "needs a machine"));
|
|
411
|
+
else if (agent.role !== "coordinator") checks.push(ok("watchdog", "the machine's coordinator keeps the watchdog running"));
|
|
412
|
+
else {
|
|
413
|
+
const installFix = `${prefix}nodii-dev watchdog install`;
|
|
414
|
+
try {
|
|
415
|
+
const job = await (deps.watchdogStatus ?? watchdogStatus)({ configFile: resolve(path) });
|
|
416
|
+
const extra = { manager: job.manager, label: job.label, path: job.path, installed: job.installed, active: job.active, ownConfig: job.ownConfig, ...(job.lastSweep ? { lastSweep: job.lastSweep } : {}) };
|
|
417
|
+
// systemd: the timer runs on while its sweeps fail or hang (a hung one is stopped at its timeout).
|
|
418
|
+
const sweepFailed = job.lastSweep && job.lastSweep !== "success";
|
|
419
|
+
if (!job.supported) checks.push(cannot("watchdog", "the watchdog installs on macOS (launchd) and Linux (systemd) only", extra));
|
|
420
|
+
else if (!job.installed) checks.push(missing("watchdog", `${job.label} is not installed (${job.manager}); no sweep reports a dead lane process`, installFix, extra));
|
|
421
|
+
else if (!job.active) checks.push(missing("watchdog", `${job.label} is installed but not running (${job.manager}); no sweep reports a dead lane process`, installFix, extra));
|
|
422
|
+
else if (!job.ownConfig) checks.push(missing("watchdog", `${job.label} runs under another agent's config, so Dev refuses every sweep`, installFix, extra));
|
|
423
|
+
else if (sweepFailed) checks.push(missing("watchdog", `${job.label} is running, but its last sweep ended with ${job.lastSweep}${job.lastSweep === "timeout" ? " (it hung and was stopped)" : ""}; no dead lane process is reported while sweeps fail`, `tail -n 50 ${job.errorLog}`, extra));
|
|
424
|
+
else checks.push(ok("watchdog", `${job.label} is running under this coordinator (${job.manager})`, extra));
|
|
425
|
+
} catch (error) {
|
|
426
|
+
checks.push(cannot("watchdog", error?.message ?? String(error)));
|
|
427
|
+
}
|
|
428
|
+
}
|
|
429
|
+
|
|
405
430
|
// No managed hooks means no managed copy: the hook checks above report that.
|
|
406
431
|
try {
|
|
407
432
|
// Someone asked now, so not the hour-old answer SessionStart can use: it would
|
package/dist/lane-env.js
CHANGED
|
@@ -34,12 +34,7 @@ async function darwinProcesses(exec) {
|
|
|
34
34
|
.map((match) => ({ pid: Number(match[1]), runtime: basename(match[2]) }));
|
|
35
35
|
if (!found.length) return [];
|
|
36
36
|
const pids = found.map((x) => x.pid).join(",");
|
|
37
|
-
const cwds =
|
|
38
|
-
let pid = null;
|
|
39
|
-
for (const line of (await exec("lsof", ["-a", "-d", "cwd", "-Fpn", "-p", pids])).split("\n")) {
|
|
40
|
-
if (line.startsWith("p")) pid = Number(line.slice(1));
|
|
41
|
-
else if (line.startsWith("n") && pid) cwds.set(pid, line.slice(1));
|
|
42
|
-
}
|
|
37
|
+
const cwds = await processCwds({ pids: found.map((x) => x.pid), platform: "darwin", lsof: (args) => exec("lsof", args) });
|
|
43
38
|
// `ps -E` appends the process's starting environment to its arguments, so
|
|
44
39
|
// the environment is what follows the arguments: a prompt that spells out
|
|
45
40
|
// NODII_DEV_CONFIG_PATH is not the variable. A process whose environment ps
|
|
@@ -73,6 +68,46 @@ async function linuxProcesses(fs) {
|
|
|
73
68
|
return found;
|
|
74
69
|
}
|
|
75
70
|
|
|
71
|
+
/**
|
|
72
|
+
* Each process's working directory, read from /proc: pid -> cwd. This is what
|
|
73
|
+
* `lsof -d cwd` answers on macOS; on Linux lsof is an optional package. Given
|
|
74
|
+
* `pids`, only those are read. A process this user may not read is left out.
|
|
75
|
+
*/
|
|
76
|
+
export async function procCwds({ pids, fs = { readdir, readlink } } = {}) {
|
|
77
|
+
const names = pids ? pids.map(String) : (await fs.readdir("/proc")).filter((entry) => /^\d+$/.test(entry));
|
|
78
|
+
const cwds = new Map();
|
|
79
|
+
for (const name of names) {
|
|
80
|
+
const cwd = await fs.readlink(`/proc/${name}/cwd`).catch(() => null);
|
|
81
|
+
if (cwd) cwds.set(Number(name), cwd);
|
|
82
|
+
}
|
|
83
|
+
return cwds;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* Each process's working directory, pid -> cwd, the one lookup every caller
|
|
88
|
+
* uses (lane closeout, the heavy queue, agent listing). `lsof -d cwd` answers
|
|
89
|
+
* where it runs, and macOS always has it; `lsof(args)` runs it and resolves to
|
|
90
|
+
* its stdout. lsof exits non-zero once a process has vanished and still prints
|
|
91
|
+
* the rest, so that output is used. On Linux lsof is an optional package: when
|
|
92
|
+
* it is missing, or fails having printed nothing, /proc answers instead, so a
|
|
93
|
+
* busy directory is never read as free. `pids` limits the read.
|
|
94
|
+
*/
|
|
95
|
+
export async function processCwds({ pids, platform = process.platform, lsof, proc = procCwds } = {}) {
|
|
96
|
+
let out;
|
|
97
|
+
try { out = await lsof(["-a", "-d", "cwd", "-Fpn", ...(pids ? ["-p", pids.join(",")] : [])]); }
|
|
98
|
+
catch (error) {
|
|
99
|
+
out = error?.stdout ?? "";
|
|
100
|
+
if (platform === "linux" && (error?.code === "ENOENT" || !out)) return proc(pids ? { pids } : {});
|
|
101
|
+
}
|
|
102
|
+
const cwds = new Map();
|
|
103
|
+
let pid = null;
|
|
104
|
+
for (const line of String(out).split("\n")) {
|
|
105
|
+
if (line.startsWith("p")) pid = Number(line.slice(1));
|
|
106
|
+
else if (line.startsWith("n") && pid) cwds.set(pid, line.slice(1));
|
|
107
|
+
}
|
|
108
|
+
return cwds;
|
|
109
|
+
}
|
|
110
|
+
|
|
76
111
|
/** Every claude and codex process on this machine, with its cwd and its NODII_DEV_CONFIG_PATH. */
|
|
77
112
|
export async function agentProcesses({ platform = process.platform, exec = run, fs = { readdir, readFile, readlink } } = {}) {
|
|
78
113
|
if (platform === "darwin") return darwinProcesses(exec);
|
package/dist/starting.js
CHANGED
|
@@ -309,7 +309,8 @@ export async function coordinatorHeartbeatLoop({ machine, runId, pid, processSta
|
|
|
309
309
|
|
|
310
310
|
/** Register each --account, then report every account's usage (MW1-38.1). */
|
|
311
311
|
/**
|
|
312
|
-
* The
|
|
312
|
+
* The watchdog job (launchd on macOS, a systemd timer on Linux) runs as one
|
|
313
|
+
* agent, so a new coordinator has to take it over
|
|
313
314
|
* or every sweep is refused (WATCHDOG_COORDINATOR_REQUIRED; NODII-DEV-CLI-42).
|
|
314
315
|
*/
|
|
315
316
|
async function takeOverWatchdog(installWatchdog) {
|
|
@@ -344,7 +345,7 @@ export async function coordinatorCommand(action, flags, {
|
|
|
344
345
|
isAlive = async (pid, startedAt) => (await import("./watchdog.js")).isProcessAlive(pid, startedAt),
|
|
345
346
|
sessionPid = coordinatorRuntimePid,
|
|
346
347
|
existingHeartbeater = runningHeartbeater,
|
|
347
|
-
// Only the CLI passes
|
|
348
|
+
// Only the CLI passes the watchdog's installer, so no caller touches launchd or systemd by default.
|
|
348
349
|
installWatchdog = null,
|
|
349
350
|
} = {}) {
|
|
350
351
|
if (action === "heartbeat") {
|
package/dist/surface.js
CHANGED
|
@@ -32,7 +32,7 @@ import { CliError, VERSION, devRequest, readConfig } from "./core.js";
|
|
|
32
32
|
import { createRenderer } from "./vendor/render-templates.mjs";
|
|
33
33
|
|
|
34
34
|
/** Bumped whenever the emitted code changes shape for the same inputs. */
|
|
35
|
-
export const GENERATOR_FORMAT =
|
|
35
|
+
export const GENERATOR_FORMAT = 25;
|
|
36
36
|
export const TREE_DIR = "docs/figma-ux-ds/figma/surface-trees";
|
|
37
37
|
export const GENERATED_SUFFIX = ".surface.generated.tsx";
|
|
38
38
|
/** Where every generated product page lives, as a git glob (NODII-DEV-CLI-77). */
|
|
@@ -1850,7 +1850,7 @@ function dataProps(views, propsType) {
|
|
|
1850
1850
|
const list = itemList(m.index, m[1]);
|
|
1851
1851
|
if (list) {
|
|
1852
1852
|
const field = member(entry(list), m[2]);
|
|
1853
|
-
const nullable = / == null \? \("(?:[^"\\]|\\.)*"\) : \(
|
|
1853
|
+
const nullable = / == null \? \("(?:[^"\\]|\\.)*"\) : \((?:<div\b[^>]*>\s*)*$/.test(body.slice(0, m.index)) || field.get("\u0000pii")?.raw.endsWith(" | null");
|
|
1854
1854
|
field.set("\u0000pii", { raw: PII_ROW_FIELD + (nullable ? " | null" : "") });
|
|
1855
1855
|
}
|
|
1856
1856
|
}
|
|
@@ -2519,7 +2519,7 @@ const PII_ROW_READ = /<PiiText value=\{([a-z][A-Za-z0-9]*)\.([A-Za-z][A-Za-z0-9]
|
|
|
2519
2519
|
*/
|
|
2520
2520
|
function settlePiiColumns(views, unmapped) {
|
|
2521
2521
|
const NODE_READ = /(^|>)\s*\{([a-z][A-Za-z0-9]*)\.([A-Za-z][A-Za-z0-9]*)\}/gm;
|
|
2522
|
-
const PII_CELL = />\n[ \t]*<PiiText value=\{([a-z][A-Za-z0-9]*)\.([A-Za-z][A-Za-z0-9]*)\.value\} kind="[^\n]*\/>\
|
|
2522
|
+
const PII_CELL = />\n[ \t]*(?:<div\b[^>]*>\s*)*<PiiText value=\{([a-z][A-Za-z0-9]*)\.([A-Za-z][A-Za-z0-9]*)\.value\} kind="[^\n]*\/>\s*(?:<\/div>\s*)*<\/TableCell>/g;
|
|
2523
2523
|
const reads = new Map();
|
|
2524
2524
|
const count = (view, openers, at, param, key, how) => {
|
|
2525
2525
|
const list = listAt(openers, at, param);
|
|
@@ -2533,7 +2533,7 @@ function settlePiiColumns(views, unmapped) {
|
|
|
2533
2533
|
const openers = listOpeners(view.body);
|
|
2534
2534
|
for (const m of view.body.matchAll(PII_ROW_READ)) {
|
|
2535
2535
|
const r = count(view, openers, m.index, m[1], m[2], "pii");
|
|
2536
|
-
const empty = / == null \? \(("(?:[^"\\]|\\.)*")\) : \(
|
|
2536
|
+
const empty = / == null \? \(("(?:[^"\\]|\\.)*")\) : \((?:<div\b[^>]*>\s*)*$/.exec(view.body.slice(0, m.index));
|
|
2537
2537
|
if (r && empty) r.empty = empty[1];
|
|
2538
2538
|
}
|
|
2539
2539
|
for (const m of view.body.matchAll(NODE_READ)) count(view, openers, m.index, m[2], m[3], "node");
|
|
@@ -2556,7 +2556,7 @@ function settlePiiColumns(views, unmapped) {
|
|
|
2556
2556
|
// Nullable cells also participate in the cross-view contract. A genuinely
|
|
2557
2557
|
// different cell kind must not leave an object read behind a ReactNode type.
|
|
2558
2558
|
const nullableOpeners = listOpeners(view.body);
|
|
2559
|
-
view.body = view.body.replace(/>\n[ \t]*\{([a-z][A-Za-z0-9]*)\.([A-Za-z][A-Za-z0-9]*) == null \? \("(?:[^"\\]|\\.)*"\) : \(
|
|
2559
|
+
view.body = view.body.replace(/>\n[ \t]*\{([a-z][A-Za-z0-9]*)\.([A-Za-z][A-Za-z0-9]*) == null \? \("(?:[^"\\]|\\.)*"\) : \((?:<div\b[^>]*>\s*)*<PiiText[^\n]*\/>\s*(?:<\/div>\s*)*\)\}\n[ \t]*<\/TableCell>/g, (all, param, key, at) => (mixed.has(`${listAt(nullableOpeners, at, param)}.${key}`) ? `>{${param}.${key}}</TableCell>` : all));
|
|
2560
2560
|
}
|
|
2561
2561
|
for (const r of mixed.values()) {
|
|
2562
2562
|
unmapped.push({ variant: r.variant, path: r.list, kind: LIFTED, detail: `column ${r.key} of ${r.list} is PiiText in ${r.pii} of the ${r.pii + r.node} tables that share its rows: it stays a ReactNode, and the page must draw its people through PiiText itself (U05; cli-140)` });
|
|
@@ -2564,11 +2564,24 @@ function settlePiiColumns(views, unmapped) {
|
|
|
2564
2564
|
}
|
|
2565
2565
|
|
|
2566
2566
|
/** The attributes of the PiiText a body cell's template draws as its whole content (Table cell, Content=PII); null for any other cell. */
|
|
2567
|
-
function
|
|
2567
|
+
function piiCellParts({ code, held }) {
|
|
2568
2568
|
const own = (code ?? "").trim();
|
|
2569
2569
|
if (held || !/^<TableCell\b/.test(own)) return null;
|
|
2570
|
-
|
|
2571
|
-
|
|
2570
|
+
let inner = own.slice(openTagEnd(own) + 1).replace(/<\/TableCell>$/, "").trim();
|
|
2571
|
+
let before = "", after = "";
|
|
2572
|
+
// Surface-owned layout frames may wrap the one person. Preserve their
|
|
2573
|
+
// emitted layout, and reject siblings or any other content in the cell.
|
|
2574
|
+
while (/^<div\b/.test(inner) && inner.endsWith("</div>")) {
|
|
2575
|
+
const end = openTagEnd(inner);
|
|
2576
|
+
before += inner.slice(0, end + 1) + "\n";
|
|
2577
|
+
after = "\n</div>" + after;
|
|
2578
|
+
inner = inner.slice(end + 1, -6).trim();
|
|
2579
|
+
}
|
|
2580
|
+
const attrs = /^<PiiText\b([^<>]*?)\s*\/>$/.exec(inner)?.[1];
|
|
2581
|
+
return attrs === undefined ? null : { attrs, before, after };
|
|
2582
|
+
}
|
|
2583
|
+
function piiCellAttrs(cell) {
|
|
2584
|
+
return piiCellParts(cell)?.attrs ?? null;
|
|
2572
2585
|
}
|
|
2573
2586
|
|
|
2574
2587
|
function piiTreeKind(cell) {
|
|
@@ -2596,10 +2609,10 @@ function piiTreeKind(cell) {
|
|
|
2596
2609
|
|
|
2597
2610
|
/** That cell's PiiText, reading the served pair at `ref` (`row.employee`), with the kind the tree states for it. */
|
|
2598
2611
|
function piiCellText({ cell, code }, ref) {
|
|
2599
|
-
const attrs =
|
|
2612
|
+
const { attrs = "", before = "", after = "" } = piiCellParts({ code }) ?? {};
|
|
2600
2613
|
const kind = piiTreeKind(cell);
|
|
2601
2614
|
const size = /\ssize="\w+"/.exec(attrs)?.[0] ?? "";
|
|
2602
|
-
return
|
|
2615
|
+
return `${before}<PiiText value={${ref}.value} kind="${kind}" model={${ref}.model} relation={${ref}.relation} maskHint={${ref}.maskHint}${size} />${after}`;
|
|
2603
2616
|
}
|
|
2604
2617
|
|
|
2605
2618
|
/** Only a plain literal empty cell is compatible with a nullable person. */
|
package/dist/systemd.js
ADDED
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
// systemd user units: how nodii-dev's supervised jobs (the watchdog sweep and
|
|
2
|
+
// coordinator watch) run on Linux. launchd does the same on macOS, from
|
|
3
|
+
// watchdog.js and coordinator-watch.js. Nothing here needs root: units live in
|
|
4
|
+
// the user's own unit directory and are driven with `systemctl --user`.
|
|
5
|
+
import { execFile as execFileCallback } from "node:child_process";
|
|
6
|
+
import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
|
|
7
|
+
import { homedir, userInfo } from "node:os";
|
|
8
|
+
import { dirname, isAbsolute, join } from "node:path";
|
|
9
|
+
import { promisify } from "node:util";
|
|
10
|
+
import { CliError } from "./core.js";
|
|
11
|
+
|
|
12
|
+
const execFile = promisify(execFileCallback);
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* An XDG base directory. The variable describes the real user's home, so it
|
|
16
|
+
* is honoured only for that home: a caller that names another home (a test,
|
|
17
|
+
* a dry run) gets that home's default and never the real user's directory.
|
|
18
|
+
*/
|
|
19
|
+
function xdgDir(home, env, variable, fallback) {
|
|
20
|
+
const set = env?.[variable];
|
|
21
|
+
return home === homedir() && typeof set === "string" && isAbsolute(set) ? set : join(home, ...fallback);
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** Where systemd reads a user's own units. */
|
|
25
|
+
export const userUnitDir = (home = homedir(), env = process.env) => join(xdgDir(home, env, "XDG_CONFIG_HOME", [".config"]), "systemd", "user");
|
|
26
|
+
|
|
27
|
+
/** The logs of nodii-dev's supervised jobs: ~/Library/Logs on macOS, the XDG state directory elsewhere. */
|
|
28
|
+
export function logsDir({ home = homedir(), os = process.platform, env = process.env } = {}) {
|
|
29
|
+
if (os === "darwin") return join(home, "Library", "Logs", "nodii-dev");
|
|
30
|
+
return join(xdgDir(home, env, "XDG_STATE_HOME", [".local", "state"]), "nodii-dev", "logs");
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function oneLine(value) {
|
|
34
|
+
const text = String(value);
|
|
35
|
+
if (/[\n\r]/.test(text)) throw new Error(`a systemd unit value cannot hold a line break: ${JSON.stringify(text)}`);
|
|
36
|
+
return text;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
// systemd expands %-specifiers in every one of these values, so a literal % is doubled.
|
|
40
|
+
const quoted = (value) => `"${oneLine(value).replaceAll("\\", "\\\\").replaceAll('"', '\\"').replaceAll("%", "%%")}"`;
|
|
41
|
+
|
|
42
|
+
/** An ExecStart= command line. `$` starts a variable there, so a literal one is doubled. */
|
|
43
|
+
export const execLine = (args) => args.map((arg) => quoted(arg).replaceAll("$", "$$$$")).join(" ");
|
|
44
|
+
|
|
45
|
+
/** An Environment= assignment. `$` has no meaning there. */
|
|
46
|
+
export const envAssignment = (name, value) => quoted(`${name}=${oneLine(value)}`);
|
|
47
|
+
|
|
48
|
+
/** A path inside a value that is not quoted (StandardOutput=append:PATH). */
|
|
49
|
+
export const unitPath = (path) => oneLine(path).replaceAll("%", "%%");
|
|
50
|
+
|
|
51
|
+
/** Renders `[[section, [[key, value], ...]], ...]` as a unit file. */
|
|
52
|
+
export const unitText = (sections) => `${sections.map(([name, entries]) => `[${name}]\n${entries.map(([key, value]) => `${key}=${value}`).join("\n")}\n`).join("\n")}`;
|
|
53
|
+
|
|
54
|
+
async function writeUnit(path, contents) {
|
|
55
|
+
await mkdir(dirname(path), { recursive: true });
|
|
56
|
+
const temporary = `${path}.tmp-${process.pid}`;
|
|
57
|
+
// A unit holds commands, paths and a schedule, never a secret.
|
|
58
|
+
await writeFile(temporary, contents, { mode: 0o644 });
|
|
59
|
+
await rename(temporary, path);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
const readOrNull = (path) => readFile(path, "utf8").catch((error) => error?.code === "ENOENT" ? null : Promise.reject(error));
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Writes the units and enables and starts `activate`.
|
|
66
|
+
*
|
|
67
|
+
* - Identical files and `activate` already enabled and active: nothing runs
|
|
68
|
+
* beyond the two state reads, and `changed` is false.
|
|
69
|
+
* - Changed files under an active unit: it is restarted, so a new
|
|
70
|
+
* coordinator's config takes effect now (`enable --now` leaves a running
|
|
71
|
+
* unit alone).
|
|
72
|
+
* - Any failure: the previous files come back (new ones are removed), the
|
|
73
|
+
* unit returns to its previous state, and the error is thrown.
|
|
74
|
+
*/
|
|
75
|
+
export async function installUserUnits({ dir, units, activate, execute = execFile }) {
|
|
76
|
+
const systemctl = (...args) => execute("systemctl", ["--user", ...args]);
|
|
77
|
+
const answers = async (verb) => { try { await systemctl(verb, activate); return true; } catch { return false; } };
|
|
78
|
+
const paths = units.map((unit) => join(dir, unit.name));
|
|
79
|
+
const previous = [];
|
|
80
|
+
for (const path of paths) previous.push(await readOrNull(path));
|
|
81
|
+
const same = units.every((unit, index) => previous[index] === unit.contents);
|
|
82
|
+
const active = await answers("is-active");
|
|
83
|
+
const enabled = await answers("is-enabled");
|
|
84
|
+
if (same && active && enabled) return { changed: false, unitPaths: paths };
|
|
85
|
+
try {
|
|
86
|
+
for (const [index, unit] of units.entries()) if (previous[index] !== unit.contents) await writeUnit(paths[index], unit.contents);
|
|
87
|
+
await systemctl("daemon-reload");
|
|
88
|
+
await systemctl("enable", "--now", activate);
|
|
89
|
+
if (active && !same) await systemctl("restart", activate);
|
|
90
|
+
} catch (error) {
|
|
91
|
+
if (!enabled) await systemctl("disable", "--now", activate).catch(() => {});
|
|
92
|
+
// Each restore step runs whatever an earlier one did; the install's own
|
|
93
|
+
// error is what is thrown, naming any file that could not be put back.
|
|
94
|
+
const unrestored = [];
|
|
95
|
+
for (const [index, path] of paths.entries()) {
|
|
96
|
+
try {
|
|
97
|
+
if (previous[index] === null) await rm(path, { force: true });
|
|
98
|
+
else if (previous[index] !== units[index].contents) await writeUnit(path, previous[index]);
|
|
99
|
+
} catch (restoreError) { unrestored.push(`${path} (${restoreError?.code ?? restoreError?.message ?? restoreError})`); }
|
|
100
|
+
}
|
|
101
|
+
await systemctl("daemon-reload").catch(() => {});
|
|
102
|
+
if (active) await systemctl("restart", activate).catch(() => {});
|
|
103
|
+
if (unrestored.length && error instanceof Error) error.message += `; could not restore ${unrestored.join(", ")}`;
|
|
104
|
+
throw error;
|
|
105
|
+
}
|
|
106
|
+
// `started`: the files were current but the job was stopped or disabled, and is running again now.
|
|
107
|
+
return { changed: !same, started: same, unitPaths: paths };
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* The systemd user manager's own environment (`systemctl --user show-environment`).
|
|
112
|
+
* It is where the manager looks for units and what its services inherit, so a
|
|
113
|
+
* unit directory or log path that a service also computes is resolved from it,
|
|
114
|
+
* not from the installing shell's (which may set XDG_* the manager never sees).
|
|
115
|
+
* Empty when the manager cannot be asked: the XDG defaults then apply.
|
|
116
|
+
*/
|
|
117
|
+
export async function managerEnv({ execute = execFile } = {}) {
|
|
118
|
+
try {
|
|
119
|
+
const env = {};
|
|
120
|
+
for (const line of (await execute("systemctl", ["--user", "show-environment"])).stdout.split("\n")) {
|
|
121
|
+
const at = line.indexOf("=");
|
|
122
|
+
if (at > 0) env[line.slice(0, at)] = line.slice(at + 1);
|
|
123
|
+
}
|
|
124
|
+
return env;
|
|
125
|
+
} catch { return {}; }
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* The supervised-job directories for `home`: units and logs as the user manager
|
|
130
|
+
* resolves them. The manager is asked only for the real user's home; any other
|
|
131
|
+
* home (a test, a dry run) reads its own defaults and asks nothing.
|
|
132
|
+
*/
|
|
133
|
+
export async function supervisedDirs({ home = homedir(), execute = execFile } = {}) {
|
|
134
|
+
const env = home === homedir() ? await managerEnv({ execute }) : {};
|
|
135
|
+
return { unitDir: userUnitDir(home, env), logs: logsDir({ home, os: "linux", env }) };
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* The one Linux install for a supervised job (the watchdog timer, coordinator
|
|
140
|
+
* watch): resolve the directories, make the log directory, write and start the
|
|
141
|
+
* units (installUserUnits), and report the same shape for every job.
|
|
142
|
+
* `build({ logs })` returns the units; a refusal is thrown as `errorCode`.
|
|
143
|
+
*/
|
|
144
|
+
export async function installSupervised({ home = homedir(), execute = execFile, build, activate, errorCode }) {
|
|
145
|
+
const { unitDir, logs } = await supervisedDirs({ home, execute });
|
|
146
|
+
const units = build({ logs });
|
|
147
|
+
await mkdir(logs, { recursive: true, mode: 0o700 });
|
|
148
|
+
let installed;
|
|
149
|
+
try { installed = await installUserUnits({ dir: unitDir, units, activate, execute }); }
|
|
150
|
+
catch (error) { throw new CliError(errorCode, `Could not start ${activate}: ${error?.message ?? error}`, 1); }
|
|
151
|
+
return { ...installed, loaded: true, manager: "systemd", label: activate, logs, linger: await lingerState({ execute }) };
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* A unit's state, read only: ActiveState (active, activating, inactive,
|
|
156
|
+
* failed, ...) and Result (success, or why the last run ended: exit-code,
|
|
157
|
+
* timeout, signal, ...). Nulls when systemd cannot be asked.
|
|
158
|
+
*/
|
|
159
|
+
export async function unitState(unit, { execute = execFile } = {}) {
|
|
160
|
+
try {
|
|
161
|
+
const out = (await execute("systemctl", ["--user", "show", unit, "--property=ActiveState,Result"])).stdout;
|
|
162
|
+
const value = (name) => out.match(new RegExp(`^${name}=(.*)$`, "m"))?.[1]?.trim() || null;
|
|
163
|
+
return { activeState: value("ActiveState"), result: value("Result") };
|
|
164
|
+
} catch { return { activeState: null, result: null }; }
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/** How an install's outcome reads: updated, brought back, or unchanged. */
|
|
168
|
+
export const installNote = (data) => data.changed ? "" : data.started ? " (units current; it was not running, and is started)" : " (already current)";
|
|
169
|
+
|
|
170
|
+
/** Whether `unit` is active now. False too when systemd cannot be asked. */
|
|
171
|
+
export async function unitActive(unit, { execute = execFile } = {}) {
|
|
172
|
+
try { await execute("systemctl", ["--user", "is-active", unit]); return true; }
|
|
173
|
+
catch { return false; }
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/**
|
|
177
|
+
* Whether this user's units keep running with no login session (lingering):
|
|
178
|
+
* true, false, or null when it cannot be read. Only read: turning it on is the
|
|
179
|
+
* operator's choice (`loginctl enable-linger`).
|
|
180
|
+
*/
|
|
181
|
+
export async function lingerState({ execute = execFile, user = userInfo().username } = {}) {
|
|
182
|
+
try {
|
|
183
|
+
const answer = (await execute("loginctl", ["show-user", user, "--property=Linger", "--value"])).stdout.trim();
|
|
184
|
+
return answer === "yes" ? true : answer === "no" ? false : null;
|
|
185
|
+
} catch { return null; }
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/** What an install prints about lingering, or null when there is nothing to choose. */
|
|
189
|
+
export const lingerLine = (linger) => linger === false
|
|
190
|
+
? "Lingering is off, so this runs only while you are logged in. `loginctl enable-linger` keeps it running after logout; that is your choice, and the sign-in stays in the login keyring, which a login unlocks."
|
|
191
|
+
: null;
|
package/dist/watchdog.js
CHANGED
|
@@ -6,9 +6,13 @@ import { promisify } from "node:util";
|
|
|
6
6
|
import { CliError, configPath, devRequest, encode, readConfig } from "./core.js";
|
|
7
7
|
import { USAGE_REFRESH_MS, listAccounts, reportUsage } from "./accounts.js";
|
|
8
8
|
import { laneCloseout, laneCommand } from "./lanes.js";
|
|
9
|
+
import { envAssignment, execLine, installNote, installSupervised, lingerLine, logsDir, supervisedDirs, unitActive, unitPath, unitState, unitText } from "./systemd.js";
|
|
9
10
|
|
|
10
11
|
const execFile = promisify(execFileCallback);
|
|
11
12
|
export const WATCHDOG_LABEL = "com.nodii.watchdog";
|
|
13
|
+
/** The same job on Linux: a oneshot service and the timer that starts it. */
|
|
14
|
+
export const WATCHDOG_SERVICE = "nodii-watchdog.service";
|
|
15
|
+
export const WATCHDOG_TIMER = "nodii-watchdog.timer";
|
|
12
16
|
const RUN_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
|
|
13
17
|
|
|
14
18
|
export const watchdogHome = (home = homedir()) => join(home, ".config", "nodii-dev", "watchdog");
|
|
@@ -222,7 +226,7 @@ export function laneCapReminderText(state, now = new Date()) {
|
|
|
222
226
|
return null;
|
|
223
227
|
}
|
|
224
228
|
|
|
225
|
-
/** Held in a file because the sweep runs under launchd, outside the coordinator's session. */
|
|
229
|
+
/** Held in a file because the sweep runs under launchd or systemd, outside the coordinator's session. */
|
|
226
230
|
export async function saveLaneCapReminder(text, { home = homedir() } = {}) {
|
|
227
231
|
const path = laneCapReminderPath(home);
|
|
228
232
|
if (!text) return rm(path, { force: true });
|
|
@@ -239,7 +243,7 @@ export async function laneCapReminder({ home = homedir() } = {}) {
|
|
|
239
243
|
/** hub-251: resume-due lanes one sweep resumes at most, so a cleared fan-in never launches a burst. */
|
|
240
244
|
export const RESUME_DUE_PER_SWEEP = 3;
|
|
241
245
|
|
|
242
|
-
/** One launchd
|
|
246
|
+
/** One sweep (launchd on macOS, a systemd timer on Linux). The machine coordinator reports every observation through Dev's run watchdog contract. */
|
|
243
247
|
export async function sweepWatchdog({
|
|
244
248
|
records,
|
|
245
249
|
loadRecords = readWatchedRuns,
|
|
@@ -417,10 +421,60 @@ export function launchdPlist({ runtime, entry, config, interval, stdoutPath, std
|
|
|
417
421
|
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>${WATCHDOG_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>StartInterval</key><integer>${interval}</integer><key>ProcessType</key><string>Background</string><key>StandardOutPath</key><string>${xml(stdoutPath)}</string><key>StandardErrorPath</key><string>${xml(stderrPath)}</string></dict></plist>\n`;
|
|
418
422
|
}
|
|
419
423
|
|
|
424
|
+
/**
|
|
425
|
+
* The Linux job, as systemd user units.
|
|
426
|
+
*
|
|
427
|
+
* - KillMode=process: a sweep resumes resume-due lanes, and those processes
|
|
428
|
+
* stay in the service's control group. systemd's default stops the whole
|
|
429
|
+
* group when the sweep exits, which would end every lane it just resumed;
|
|
430
|
+
* launchd stops only the job's own process group.
|
|
431
|
+
* - OnStartupSec is counted from the user manager's start, so by install time
|
|
432
|
+
* it has passed and the first sweep runs at once (launchd's RunAtLoad).
|
|
433
|
+
* - AccuracySec: a timer's default slack is a minute, as long as the interval.
|
|
434
|
+
* - TimeoutStartSec: systemd turns the start timeout off for a oneshot
|
|
435
|
+
* service, so a sweep hung on a stalled request would stay "activating" and
|
|
436
|
+
* every later timer firing would find it running and do nothing. A sweep is
|
|
437
|
+
* stopped after three intervals, ten minutes at the least; it then reads
|
|
438
|
+
* failed (Result=timeout), which `doctor` reports, and the next firing
|
|
439
|
+
* sweeps again. KillMode=process means only the sweep itself is stopped.
|
|
440
|
+
*/
|
|
441
|
+
export const sweepTimeout = (interval) => Math.max(600, 3 * interval);
|
|
442
|
+
|
|
443
|
+
export function watchdogUnits({ runtime, entry, config, interval, stdoutPath, stderrPath, path = watchdogPath(undefined, runtime) }) {
|
|
444
|
+
const service = unitText([
|
|
445
|
+
["Unit", [["Description", "nodii-dev watchdog sweep"]]],
|
|
446
|
+
["Service", [
|
|
447
|
+
["Type", "oneshot"],
|
|
448
|
+
["ExecStart", execLine([runtime, entry, "watchdog", "sweep", "--json"])],
|
|
449
|
+
["Environment", envAssignment("NODII_DEV_CONFIG_PATH", config)],
|
|
450
|
+
["Environment", envAssignment("PATH", path)],
|
|
451
|
+
["StandardOutput", `append:${unitPath(stdoutPath)}`],
|
|
452
|
+
["StandardError", `append:${unitPath(stderrPath)}`],
|
|
453
|
+
["KillMode", "process"],
|
|
454
|
+
["TimeoutStartSec", `${sweepTimeout(interval)}s`],
|
|
455
|
+
]],
|
|
456
|
+
]);
|
|
457
|
+
const timer = unitText([
|
|
458
|
+
["Unit", [["Description", `nodii-dev watchdog sweep, every ${interval}s`]]],
|
|
459
|
+
["Timer", [["OnStartupSec", "30s"], ["OnUnitActiveSec", `${interval}s`], ["AccuracySec", "1s"], ["Unit", WATCHDOG_SERVICE]]],
|
|
460
|
+
["Install", [["WantedBy", "timers.target"]]],
|
|
461
|
+
]);
|
|
462
|
+
return [{ name: WATCHDOG_SERVICE, contents: service }, { name: WATCHDOG_TIMER, contents: timer }];
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
function installSystemdWatchdog({ home, env, interval, runtime, entry, configFile, execute }) {
|
|
466
|
+
return installSupervised({
|
|
467
|
+
home, execute, activate: WATCHDOG_TIMER, errorCode: "WATCHDOG_INSTALL_FAILED",
|
|
468
|
+
// PATH is the installing shell's: the sweep resumes lanes and must find their runtime (hub-251).
|
|
469
|
+
build: ({ logs }) => watchdogUnits({ runtime, entry, config: resolve(configFile), interval, stdoutPath: join(logs, "watchdog.log"), stderrPath: join(logs, "watchdog.error.log"), path: watchdogPath(env.PATH, runtime) }),
|
|
470
|
+
}).then((installed) => ({ ...installed, interval }));
|
|
471
|
+
}
|
|
472
|
+
|
|
420
473
|
export async function installWatchdog({
|
|
421
474
|
home = homedir(),
|
|
422
475
|
uid = process.getuid?.(),
|
|
423
476
|
os = platform(),
|
|
477
|
+
env = process.env,
|
|
424
478
|
interval = 60,
|
|
425
479
|
runtime = process.execPath,
|
|
426
480
|
entry = resolve(process.argv[1]),
|
|
@@ -429,13 +483,15 @@ export async function installWatchdog({
|
|
|
429
483
|
request = devRequest,
|
|
430
484
|
execute = execFile,
|
|
431
485
|
} = {}) {
|
|
432
|
-
if (os !== "darwin"
|
|
486
|
+
if (os !== "darwin" && os !== "linux")
|
|
487
|
+
throw new CliError("WATCHDOG_UNSUPPORTED", `The per-machine watchdog installs with launchd on macOS and with systemd user units on Linux; ${os} is not supported.`, 2);
|
|
433
488
|
if (!Number.isInteger(interval) || interval < 10 || interval > 3600)
|
|
434
489
|
throw new CliError("USAGE", "watchdog install --interval must be 10..3600 seconds.", 2);
|
|
435
|
-
if (!Number.isInteger(uid) || uid < 0) throw new CliError("WATCHDOG_INSTALL_FAILED", "Cannot determine the macOS user id for launchd.", 1);
|
|
490
|
+
if (os === "darwin" && (!Number.isInteger(uid) || uid < 0)) throw new CliError("WATCHDOG_INSTALL_FAILED", "Cannot determine the macOS user id for launchd.", 1);
|
|
436
491
|
const current = typeof config === "function" ? await config() : config;
|
|
437
492
|
await assertCoordinator(current, request);
|
|
438
|
-
|
|
493
|
+
if (os === "linux") return installSystemdWatchdog({ home, env, interval, runtime, entry, configFile, execute });
|
|
494
|
+
const logs = logsDir({ home, os });
|
|
439
495
|
const plistPath = join(home, "Library", "LaunchAgents", `${WATCHDOG_LABEL}.plist`);
|
|
440
496
|
const contents = launchdPlist({ runtime, entry, config: resolve(configFile), interval, stdoutPath: join(logs, "watchdog.log"), stderrPath: join(logs, "watchdog.error.log") });
|
|
441
497
|
await mkdir(logs, { recursive: true, mode: 0o700 });
|
|
@@ -445,7 +501,7 @@ export async function installWatchdog({
|
|
|
445
501
|
let loaded = true;
|
|
446
502
|
try { await execute("launchctl", ["print", service]); }
|
|
447
503
|
catch { loaded = false; }
|
|
448
|
-
if (previous === contents && loaded) return { changed: false, loaded: true, plistPath, label: WATCHDOG_LABEL, interval };
|
|
504
|
+
if (previous === contents && loaded) return { changed: false, loaded: true, manager: "launchd", plistPath, label: WATCHDOG_LABEL, interval };
|
|
449
505
|
if (loaded) await execute("launchctl", ["bootout", service]);
|
|
450
506
|
try {
|
|
451
507
|
if (previous !== contents) await atomicWrite(plistPath, contents);
|
|
@@ -456,18 +512,71 @@ export async function installWatchdog({
|
|
|
456
512
|
if (loaded && previous !== null) await execute("launchctl", ["bootstrap", domain, plistPath]).catch(() => {});
|
|
457
513
|
throw new CliError("WATCHDOG_INSTALL_FAILED", `Could not load ${WATCHDOG_LABEL}: ${error?.message ?? error}`, 1);
|
|
458
514
|
}
|
|
459
|
-
return { changed: previous !== contents, loaded: true, plistPath, label: WATCHDOG_LABEL, interval };
|
|
515
|
+
return { changed: previous !== contents, loaded: true, manager: "launchd", plistPath, label: WATCHDOG_LABEL, interval };
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
/**
|
|
519
|
+
* Whether the watchdog job is installed and running, and whether it runs
|
|
520
|
+
* under `configFile`: the job runs as one agent, and a sweep by any other
|
|
521
|
+
* agent is refused (NODII-DEV-CLI-42). Reads only.
|
|
522
|
+
*/
|
|
523
|
+
export async function watchdogStatus({
|
|
524
|
+
home = homedir(), uid = process.getuid?.(), os = platform(), configFile = configPath(), execute = execFile,
|
|
525
|
+
} = {}) {
|
|
526
|
+
const config = resolve(configFile);
|
|
527
|
+
if (os === "linux") {
|
|
528
|
+
const { unitDir, logs } = await supervisedDirs({ home, execute });
|
|
529
|
+
const path = join(unitDir, WATCHDOG_SERVICE);
|
|
530
|
+
const contents = await readFile(path, "utf8").catch(() => null);
|
|
531
|
+
const active = contents !== null && await unitActive(WATCHDOG_TIMER, { execute });
|
|
532
|
+
// The timer can be running while its sweeps fail or time out: the service says how the last one ended.
|
|
533
|
+
const sweep = active ? await unitState(WATCHDOG_SERVICE, { execute }) : { activeState: null, result: null };
|
|
534
|
+
return {
|
|
535
|
+
supported: true, manager: "systemd", label: WATCHDOG_TIMER, path,
|
|
536
|
+
installed: contents !== null,
|
|
537
|
+
active,
|
|
538
|
+
ownConfig: contents !== null && contents.includes(`Environment=${envAssignment("NODII_DEV_CONFIG_PATH", config)}\n`),
|
|
539
|
+
lastSweep: sweep.result, sweepState: sweep.activeState, errorLog: join(logs, "watchdog.error.log"),
|
|
540
|
+
};
|
|
541
|
+
}
|
|
542
|
+
if (os === "darwin") {
|
|
543
|
+
const path = join(home, "Library", "LaunchAgents", `${WATCHDOG_LABEL}.plist`);
|
|
544
|
+
const contents = await readFile(path, "utf8").catch(() => null);
|
|
545
|
+
let active = contents !== null;
|
|
546
|
+
if (active) { try { await execute("launchctl", ["print", `gui/${uid}/${WATCHDOG_LABEL}`]); } catch { active = false; } }
|
|
547
|
+
return {
|
|
548
|
+
supported: true, manager: "launchd", label: WATCHDOG_LABEL, path, installed: contents !== null, active,
|
|
549
|
+
ownConfig: contents !== null && contents.includes(`<key>NODII_DEV_CONFIG_PATH</key><string>${xml(config)}</string>`),
|
|
550
|
+
};
|
|
551
|
+
}
|
|
552
|
+
return { supported: false, manager: null, label: null, path: null, installed: false, active: false, ownConfig: false };
|
|
460
553
|
}
|
|
461
554
|
|
|
555
|
+
/**
|
|
556
|
+
* The sweep errors that leave Dev without a run's state: a failed run report,
|
|
557
|
+
* Dev's live runs unread, or a local run record unreadable.
|
|
558
|
+
*/
|
|
559
|
+
export const SWEEP_FATAL_KINDS = new Set(["run", "live_runs", "registry"]);
|
|
560
|
+
|
|
462
561
|
export async function watchdogCommand(action, flags, dependencies = {}) {
|
|
463
562
|
if (action === "install") {
|
|
464
563
|
const interval = Number(flags.interval ?? 60);
|
|
465
564
|
const data = await installWatchdog({ interval, ...dependencies });
|
|
466
|
-
|
|
565
|
+
const from = data.plistPath ?? data.unitPaths.join(" and ");
|
|
566
|
+
const lines = [`${data.label} is loaded from ${from}; sweep every ${data.interval}s${installNote(data)}.`, ...(data.logs ? [`Logs: ${data.logs}`] : []), lingerLine(data.linger)];
|
|
567
|
+
return { payload: { data }, human: lines.filter(Boolean).join("\n") };
|
|
467
568
|
}
|
|
468
569
|
if (action === "sweep") {
|
|
469
570
|
const data = await sweepWatchdog(dependencies);
|
|
470
|
-
|
|
571
|
+
// A sweep exists to tell Dev about each run. When that failed, it exits 1, so
|
|
572
|
+
// the service manager records the failure (systemd's Result) and `doctor`
|
|
573
|
+
// reports it; errors in its other jobs are recorded and do not fail it.
|
|
574
|
+
const unreported = data.errors.filter((error) => SWEEP_FATAL_KINDS.has(error.kind)).length;
|
|
575
|
+
return {
|
|
576
|
+
payload: { data },
|
|
577
|
+
human: `Watchdog sweep: ${data.orphanedRuns.length} orphaned run(s), ${data.unwatchedRuns.length} unwatched run(s), ${data.staleSockets.length} stale socket(s), ${data.unpushedWorktrees.length} unpushed worktree(s), ${data.errors.length} error(s)${unreported ? `, ${unreported} of them leaving Dev without a run's state` : ""}.`,
|
|
578
|
+
...(unreported ? { exitCode: 1 } : {}),
|
|
579
|
+
};
|
|
471
580
|
}
|
|
472
581
|
throw new CliError("USAGE", "watchdog install [--interval SECONDS] | watchdog sweep", 2);
|
|
473
582
|
}
|