@bom0792/herdgate 0.9.37 → 0.9.39

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,172 @@
1
+ // Listening-port attribution via process ancestry (see docs/research/
2
+ // 2026-11-21-marketplace/deep/portfwd.md — mechanism from herdr-portfwd
3
+ // src/discover.rs `ProcessTree::ancestry` + `attribute`, MIT). No lsof/ss/ps
4
+ // subprocesses: /proc/net/tcp + /proc/net/tcp6 supply LISTEN sockets with
5
+ // their inodes, /proc/<pid>/fd readlinks match inode → owning pid, and a ppid
6
+ // walk (cycle-guarded, depth-capped, pid 0 filtered — the kernel is never a
7
+ // shell) attributes the port to the session shell it descends from.
8
+ // A listener no shell owns lands in `unattributed` — an owner is never
9
+ // invented. Torn-safe: pids and fds that vanish or are unreadable mid-scan
10
+ // are skipped, never fail the batch.
11
+
12
+ import { readdirSync, readFileSync, readlinkSync } from 'node:fs';
13
+ import { join } from 'node:path';
14
+
15
+ const MAX_ANCESTRY_DEPTH = 32;
16
+ const SOCKET_INODE = /^socket:\[(\d+)\]$/;
17
+
18
+ /** {pid → key} from a mixed list of pids and {pid, key} entries; first wins. */
19
+ function shellIndex(shellPids) {
20
+ const shells = new Map();
21
+ for (const entry of Array.isArray(shellPids) ? shellPids : []) {
22
+ const pid = typeof entry === 'number' ? entry : entry?.pid;
23
+ const key = typeof entry === 'number' ? String(entry) : entry?.key ?? String(entry?.pid);
24
+ if (Number.isInteger(pid) && pid > 0 && !shells.has(pid)) shells.set(pid, key);
25
+ }
26
+ return shells;
27
+ }
28
+
29
+ /**
30
+ * /proc/net/tcp(6) LISTEN rows → [{port, proto, inode}]. st "0A" is
31
+ * TCP_LISTEN; the inode is field 10 (parts[9]); the port is the hex half of
32
+ * the local address. Unreadable tables are skipped, not fatal.
33
+ */
34
+ function listeningSockets(procDir, file, proto) {
35
+ const rows = [];
36
+ let text;
37
+ try {
38
+ text = readFileSync(join(procDir, file), 'utf8');
39
+ } catch {
40
+ return rows;
41
+ }
42
+ for (const line of text.split('\n').slice(1)) { // header row: " sl local_address …"
43
+ const parts = line.trim().split(/\s+/);
44
+ if (parts.length < 10 || parts[3] !== '0A') continue;
45
+ const port = Number.parseInt(parts[1].split(':')[1] ?? '', 16);
46
+ const inode = Number(parts[9]);
47
+ if (Number.isInteger(port) && port > 0 && Number.isInteger(inode) && inode > 0) {
48
+ rows.push({ port, proto, inode });
49
+ }
50
+ }
51
+ return rows;
52
+ }
53
+
54
+ /**
55
+ * One pass over numeric /proc entries: stat (ppid + comm) and fd readlinks.
56
+ * Returns {ppid: Map, comm: Map, byInode: Map inode → pid} — torn-safe.
57
+ */
58
+ function scanProcesses(procDir, wantedInodes) {
59
+ const ppid = new Map();
60
+ const comm = new Map();
61
+ const byInode = new Map();
62
+ let names;
63
+ try {
64
+ names = readdirSync(procDir);
65
+ } catch {
66
+ return { ppid, comm, byInode };
67
+ }
68
+ for (const name of names) {
69
+ if (!/^\d+$/.test(name)) continue;
70
+ const pid = Number(name);
71
+ let stat;
72
+ try {
73
+ stat = readFileSync(join(procDir, name, 'stat'), 'utf8');
74
+ } catch {
75
+ continue; // pid vanished mid-scan — skipped, batch keeps going
76
+ }
77
+ const close = stat.lastIndexOf(')');
78
+ const rest = stat.slice(close + 1).trim().split(/\s+/);
79
+ const parent = Number(rest[1]);
80
+ if (Number.isFinite(parent) && parent > 0) ppid.set(pid, parent); // pid 0 filtered
81
+ if (close > 0) comm.set(pid, stat.slice(stat.indexOf('(') + 1, close));
82
+ let fds;
83
+ try {
84
+ fds = readdirSync(join(procDir, name, 'fd'));
85
+ } catch {
86
+ continue; // no permission / raced away — ppid still counted
87
+ }
88
+ for (const fd of fds) {
89
+ let target;
90
+ try {
91
+ target = readlinkSync(join(procDir, name, 'fd', fd));
92
+ } catch {
93
+ continue;
94
+ }
95
+ const match = SOCKET_INODE.exec(target);
96
+ if (!match) continue;
97
+ const inode = Number(match[1]);
98
+ if (wantedInodes.has(inode) && !byInode.has(inode)) byInode.set(inode, pid);
99
+ }
100
+ }
101
+ return { ppid, comm, byInode };
102
+ }
103
+
104
+ function commandOf(procDir, pid, comm) {
105
+ try {
106
+ const cmdline = readFileSync(join(procDir, String(pid), 'cmdline'), 'utf8');
107
+ const text = cmdline.split('\0').filter(Boolean).join(' ');
108
+ if (text) return text;
109
+ } catch {
110
+ /* fall through to comm */
111
+ }
112
+ return comm.get(pid) ?? '';
113
+ }
114
+
115
+ /**
116
+ * Attribute listening ports to session shells. shellPids: pids or {pid, key}
117
+ * entries — the key of the matched shell comes back as ownerKey. Returns
118
+ * {attributed: [{port, proto, pid, cmd, ownerKey}], unattributed: [{port,
119
+ * proto, pid?, cmd?}]} — sorted by (port, proto), deduped. The owning pid is
120
+ * the process holding the socket; the owner is the shell it descends from.
121
+ * Never invents an owner: unattributed listeners stay unattributed. Missing
122
+ * /proc → empty lists; never throws.
123
+ */
124
+ export function attributePorts(shellPids, procDir = '/proc') {
125
+ const shells = shellIndex(shellPids);
126
+ const sockets = [
127
+ ...listeningSockets(procDir, 'net/tcp', 'tcp'),
128
+ ...listeningSockets(procDir, 'net/tcp6', 'tcp6'),
129
+ ];
130
+ const { ppid, comm, byInode } = scanProcesses(procDir, new Set(sockets.map(s => s.inode)));
131
+
132
+ const attributed = [];
133
+ const unattributed = [];
134
+ const seenAttributed = new Set();
135
+ const seenUnattributed = new Set();
136
+ for (const { port, proto, inode } of sockets.sort((a, b) => a.port - b.port || a.proto.localeCompare(b.proto))) {
137
+ const pid = byInode.get(inode);
138
+ if (!Number.isInteger(pid)) {
139
+ const id = `${port}/${proto}`;
140
+ if (!seenUnattributed.has(id)) {
141
+ seenUnattributed.add(id);
142
+ unattributed.push({ port, proto }); // socket owner not observable (no fd access)
143
+ }
144
+ continue;
145
+ }
146
+ // ppid walk back to a shell: cycle-guarded, depth-capped, pid 0 filtered.
147
+ let ownerKey;
148
+ let cur = pid;
149
+ const walked = new Set();
150
+ for (let depth = 0; depth < MAX_ANCESTRY_DEPTH; depth++) {
151
+ if (shells.has(cur)) { ownerKey = shells.get(cur); break; }
152
+ if (walked.has(cur)) break;
153
+ walked.add(cur);
154
+ cur = ppid.get(cur);
155
+ if (!Number.isInteger(cur) || cur <= 0) break;
156
+ }
157
+ if (ownerKey !== undefined) {
158
+ const id = `${port}/${proto}/${pid}`;
159
+ if (!seenAttributed.has(id)) {
160
+ seenAttributed.add(id);
161
+ attributed.push({ port, proto, pid, cmd: commandOf(procDir, pid, comm), ownerKey });
162
+ }
163
+ } else {
164
+ const id = `${port}/${proto}/${pid}`;
165
+ if (!seenUnattributed.has(id)) {
166
+ seenUnattributed.add(id);
167
+ unattributed.push({ port, proto, pid, cmd: commandOf(procDir, pid, comm) });
168
+ }
169
+ }
170
+ }
171
+ return { attributed, unattributed };
172
+ }
@@ -65,6 +65,13 @@ async function launch({ action, bin, hc, mobile, mobileScope, base, state }) {
65
65
  }
66
66
  const env = {
67
67
  ...process.env,
68
+ // The TUI publisher is an interactive-machine default (a laptop you are
69
+ // looking at), not a battery-sipping box: push views every 5s unless the
70
+ // operator set an explicit cadence. The plugin/systemd default stays 30s.
71
+ HERDGATE_PUBLISH_MS: process.env.HERDGATE_PUBLISH_MS ?? "5000",
72
+ // Match the freshness window to the cadence so a view op almost always
73
+ // replays the last snapshot instead of forcing a fresh spawn.
74
+ HERDGATE_SNAPSHOT_FRESH_MS: process.env.HERDGATE_SNAPSHOT_FRESH_MS ?? process.env.HERDGATE_PUBLISH_MS ?? "5000",
68
75
  HERDGATE_MOBILE_HC_BIN: mobileHcBin,
69
76
  HERDGATE_MOBILE_TUI_DEVICE: mobile,
70
77
  HERDGATE_MOBILE_TUI_SCOPE: mobileScope,
@@ -0,0 +1,212 @@
1
+ // Per-machine /proc sampler: CPU/RAM attribution for process trees (Pi session
2
+ // shells and their descendants), no cgroups and no dependencies — plain fs.
3
+ // Mechanism ported from herdr-pc-ram-and-cpu-usage-overlay (MIT, EZCorp; see
4
+ // docs/research/2026-11-21-marketplace/deep/ram.md): one scan_proc() pass over
5
+ // /proc/<pid>/stat per call, parse_stat() cutting after the LAST ')' (comm may
6
+ // contain spaces and parens), subtree() DFS with a visited set, and
7
+ // delta_jiffies() with the cutime/cstime 3-case so short-lived children — cargo
8
+ // test, spawned build tools — still count:
9
+ // alive in both scans → after - before
10
+ // born inside window → whole jiffies (all of it happened in the window)
11
+ // died inside window → its before-jiffies are subtracted, because the
12
+ // kernel folded its whole lifetime into the cutime of
13
+ // a still-living ancestor (ppid walk through pids that
14
+ // vanished too, cycle-guarded and depth-capped).
15
+ // CPU is a share of the whole machine: ΣΔjiffies / CLK_TCK / elapsed_s / nproc
16
+ // × 100, clamped to [0, 100]. RAM is the Σ statm resident field × page size.
17
+ // Torn-safe: a pid that disappears mid-scan is skipped, never fails the batch;
18
+ // a missing /proc yields [] rather than a throw.
19
+
20
+ import { readdirSync, readFileSync } from 'node:fs';
21
+ import { cpus } from 'node:os';
22
+ import { join } from 'node:path';
23
+
24
+ const MAX_WALK_DEPTH = 32; // ppid-ancestry walks: cycle guard + depth cap
25
+ const DEFAULT_CLK_TCK = 100; // USER_HZ on mainstream Linux
26
+ const DEFAULT_PAGE_SIZE = 4096; // statm counts pages, not bytes
27
+
28
+ /**
29
+ * Parse /proc/<pid>/stat. The comm field is parenthesized and may itself
30
+ * contain spaces and parentheses, so fields are read after the LAST ')'.
31
+ * Returns {pid, ppid, utime, stime, cutime, cstime, jiffies, comm} or null.
32
+ */
33
+ export function parseStat(text) {
34
+ const close = text.lastIndexOf(')');
35
+ if (close < 0) return null;
36
+ const open = text.indexOf('(');
37
+ const pid = Number(text.slice(0, open).trim());
38
+ const comm = open >= 0 && close > open ? text.slice(open + 1, close) : '';
39
+ // rest[0]=state rest[1]=ppid … rest[11]=utime rest[12]=stime
40
+ // rest[13]=cutime rest[14]=cstime (fields 3..17 of the stat line)
41
+ const rest = text.slice(close + 1).trim().split(/\s+/);
42
+ const ppid = Number(rest[1]);
43
+ const utime = Number(rest[11]);
44
+ const stime = Number(rest[12]);
45
+ const cutime = Number(rest[13]);
46
+ const cstime = Number(rest[14]);
47
+ if (!Number.isInteger(pid) || !Number.isFinite(ppid) || !Number.isFinite(utime)
48
+ || !Number.isFinite(stime) || !Number.isFinite(cutime) || !Number.isFinite(cstime)) return null;
49
+ return { pid, ppid, comm, utime, stime, cutime, cstime, jiffies: utime + stime + cutime + cstime };
50
+ }
51
+
52
+ /**
53
+ * One pass over procDir: every numeric /proc entry's stat, torn-safe (a pid
54
+ * that vanishes between readdir and read is skipped). Returns Map pid → stat.
55
+ */
56
+ export function scanProc(procDir) {
57
+ const scan = new Map();
58
+ let names;
59
+ try {
60
+ names = readdirSync(procDir);
61
+ } catch {
62
+ return scan;
63
+ }
64
+ for (const name of names) {
65
+ if (!/^\d+$/.test(name)) continue;
66
+ const pid = Number(name);
67
+ let text;
68
+ try {
69
+ text = readFileSync(join(procDir, name, 'stat'), 'utf8');
70
+ } catch {
71
+ continue; // pid vanished mid-scan — drop it, do not fail the batch
72
+ }
73
+ const stat = parseStat(text);
74
+ if (stat && stat.pid === pid) scan.set(pid, stat);
75
+ }
76
+ return scan;
77
+ }
78
+
79
+ /** ppid → [child pids] graph from one scan. */
80
+ export function childrenMap(scan) {
81
+ const map = new Map();
82
+ for (const stat of scan.values()) {
83
+ if (!map.has(stat.ppid)) map.set(stat.ppid, []);
84
+ map.get(stat.ppid).push(stat.pid);
85
+ }
86
+ return map;
87
+ }
88
+
89
+ /** DFS from a root over the children graph, visited-set guarded against cycles. */
90
+ export function subtreeOf(rootPid, children) {
91
+ const seen = new Set();
92
+ const stack = [rootPid];
93
+ while (stack.length) {
94
+ const pid = stack.pop();
95
+ if (typeof pid !== 'number' || !Number.isInteger(pid) || pid <= 0 || seen.has(pid)) continue;
96
+ seen.add(pid);
97
+ for (const child of children.get(pid) ?? []) stack.push(child);
98
+ }
99
+ return seen;
100
+ }
101
+
102
+ /**
103
+ * The nearest ancestor of a dead pid that is still alive in the after-scan —
104
+ * the process whose cutime absorbed the dead pid's folded lifetime CPU. Walks
105
+ * the ppid chain through pids that vanished too; pid 0 (kernel) ends the walk;
106
+ * cycle-guarded, depth-capped. Returns the pid or undefined.
107
+ */
108
+ function livingAncestor(deadPid, before, after) {
109
+ let cur = before.get(deadPid)?.ppid ?? 0;
110
+ const seen = new Set([deadPid]);
111
+ for (let depth = 0; cur > 0 && depth < MAX_WALK_DEPTH; depth++) {
112
+ if (seen.has(cur)) return undefined; // cycle in garbage data — give up, not up
113
+ if (after.has(cur)) return cur;
114
+ seen.add(cur);
115
+ cur = before.get(cur)?.ppid ?? 0;
116
+ }
117
+ return undefined;
118
+ }
119
+
120
+ /**
121
+ * delta_jiffies between two scans for one root's subtrees (3-case; see module
122
+ * header). The subtraction for the dead case only applies when the absorbing
123
+ * living ancestor is itself inside the after-subtree — if the fold landed on a
124
+ * process outside the measured tree, the CPU left the tree with the child.
125
+ */
126
+ export function deltaJiffies(before, after, subBefore, subAfter) {
127
+ let total = 0;
128
+ for (const pid of subAfter) {
129
+ const now = after.get(pid);
130
+ const was = before.get(pid);
131
+ total += was ? now.jiffies - was.jiffies : now.jiffies; // alive / born-in-window
132
+ }
133
+ for (const pid of subBefore) {
134
+ if (after.has(pid)) continue; // still alive — already covered above
135
+ const ancestor = livingAncestor(pid, before, after);
136
+ if (ancestor !== undefined && subAfter.has(ancestor)) total -= before.get(pid).jiffies;
137
+ }
138
+ return total;
139
+ }
140
+
141
+ /** Σ statm resident field (field 2, pages) × page size; unreadable pids count 0. */
142
+ function sumRss(procDir, pids, pageSize) {
143
+ let bytes = 0;
144
+ for (const pid of pids) {
145
+ try {
146
+ const fields = readFileSync(join(procDir, String(pid), 'statm'), 'utf8').trim().split(/\s+/);
147
+ const resident = Number(fields[1]);
148
+ if (Number.isFinite(resident)) bytes += resident * pageSize;
149
+ } catch {
150
+ continue;
151
+ }
152
+ }
153
+ return bytes;
154
+ }
155
+
156
+ // Per-procDir sampling state: the previous scan and its clock reading. The
157
+ // caller sets the cadence (daemon-style refresh); the first call is a baseline
158
+ // with cpuPct 0, every later call is the delta against the stored scan.
159
+ const state = new Map();
160
+
161
+ function readdirable(dir) {
162
+ try {
163
+ readdirSync(dir);
164
+ return true;
165
+ } catch {
166
+ return false;
167
+ }
168
+ }
169
+
170
+ /**
171
+ * Sample CPU/RAM for every root's process tree. roots: [{pid, key}] — pid is
172
+ * the tree root (a session shell), key travels back on the result row:
173
+ * [{key, cpuPct, ramBytes, procs}]
174
+ * cpuPct is a share of the whole machine (0..100, clamped); ramBytes sums
175
+ * statm RSS over the live subtree; procs counts live subtree members. A root
176
+ * that vanished returns zeros; a missing procDir returns []. Never throws.
177
+ * opts: {clkTck, nproc, pageSize, clock} — all injectable for deterministic
178
+ * tests (defaults: 100, os.cpus().length, 4096, Date.now).
179
+ */
180
+ export function sysSnapshot(roots, procDir = '/proc', opts = {}) {
181
+ const list = Array.isArray(roots) ? roots : [];
182
+ const scan = scanProc(procDir);
183
+ if (scan.size === 0 && !readdirable(procDir)) return []; // no /proc → [], never a throw
184
+ const previous = state.get(procDir);
185
+ const clock = typeof opts.clock === 'function' ? opts.clock : Date.now;
186
+ const now = clock();
187
+ const clkTck = Number.isFinite(opts.clkTck) && opts.clkTck > 0 ? opts.clkTck : DEFAULT_CLK_TCK;
188
+ const nproc = Number.isFinite(opts.nproc) && opts.nproc > 0 ? opts.nproc : cpus().length;
189
+ const pageSize = Number.isFinite(opts.pageSize) && opts.pageSize > 0 ? opts.pageSize : DEFAULT_PAGE_SIZE;
190
+
191
+ const children = childrenMap(scan);
192
+ const results = [];
193
+ for (const root of list) {
194
+ const pid = Number(typeof root === 'object' ? root?.pid : root);
195
+ const key = typeof root === 'object' ? root?.key : String(pid);
196
+ // A root missing from the scan has no subtree at all (subtreeOf would
197
+ // otherwise count the root itself while the delta loop has no stat for it).
198
+ const sub = Number.isInteger(pid) && scan.has(pid) ? subtreeOf(pid, children) : new Set();
199
+ let cpuPct = 0;
200
+ if (previous && sub.size) {
201
+ const elapsedS = (now - previous.at) / 1000;
202
+ if (elapsedS > 0 && previous.scan.has(pid)) {
203
+ const subBefore = subtreeOf(pid, childrenMap(previous.scan));
204
+ const delta = deltaJiffies(previous.scan, scan, subBefore, sub);
205
+ cpuPct = Math.min(100, Math.max(0, (delta / clkTck / elapsedS / nproc) * 100));
206
+ }
207
+ }
208
+ results.push({ key, cpuPct, ramBytes: sumRss(procDir, sub, pageSize), procs: sub.size });
209
+ }
210
+ state.set(procDir, { scan, at: now });
211
+ return results;
212
+ }
@@ -0,0 +1,255 @@
1
+ #!/usr/bin/env node
2
+ // Wake-by-herdr-event: the [[events]] hooks in herdr-plugin.toml run this file
3
+ // once per event — a short-lived process, never a daemon. Herdr is the observer
4
+ // now: pane.agent_status_changed says the child's turn closed (idle|done),
5
+ // pane.exited/pane.closed say the pane is gone. Wake no longer depends on the
6
+ // child cooperating (arm + marker + journal watcher — three live bugs made it
7
+ // silently miss); the spawn registry supplies the parent edge, delivery reuses
8
+ // pi-wake's quiet-wait protocol, and a per-child sidecar dedupes episodes by
9
+ // the child's agent revision. Any failure logs to stderr and exits 0 — an
10
+ // event hook must never raise a noisy toast, and a user pane is never touched.
11
+ import { mkdirSync, readdirSync, readFileSync, rmSync, statSync, unlinkSync } from 'node:fs';
12
+ import { join } from 'node:path';
13
+ import { pathToFileURL } from 'node:url';
14
+ import { findReceipt, journalBase } from './pi-receipts.mjs';
15
+ import { SETTLED, SETTLE_DIRECTIVE, deathFrame, deliverToParent, herdrRunner, paneForSession, patchSpawn, readAllSpawns, writeFileVerified } from './pi-wake.mjs';
16
+
17
+ const HOOKED = new Set(['pane.agent_status_changed', 'pane.exited', 'pane.closed']);
18
+ /** herdr-pings semantics: 'done' = settled-UNSEEN, not process exit — both
19
+ * idle and done mean "the child finished its turn"; working/blocked wake no
20
+ * one, and the `agent` label (process alive) is irrelevant to a settle. */
21
+ const WAKE_STATUSES = new Set(['idle', 'done']);
22
+ const log = (line) => console.error(`herdgate wake-event: ${line}`);
23
+
24
+ const delayMs = (env, name, fallback) => {
25
+ const n = Number(env[name]);
26
+ return Number.isFinite(n) && n >= 0 ? n : fallback;
27
+ };
28
+
29
+ /** HERDR_PLUGIN_EVENT_JSON carries {event, data}; tolerate a bare data object. */
30
+ function eventData(payload) {
31
+ if (!payload || typeof payload !== 'object') return null;
32
+ return payload.data && typeof payload.data === 'object' ? payload.data : payload;
33
+ }
34
+
35
+ const sidecarPath = (base, id) => join(base, `${id}.wake.json`);
36
+
37
+ function readSidecar(base, id) {
38
+ try {
39
+ const parsed = JSON.parse(readFileSync(sidecarPath(base, id), 'utf8'));
40
+ return parsed && typeof parsed === 'object' ? parsed : {};
41
+ } catch { return {}; }
42
+ }
43
+
44
+ /** tmp+rename + stamp+byte-verify (pi-wake.writeFileVerified): a crash
45
+ * mid-write leaves the OLD sidecar (or none) — never a half file — and a
46
+ * write that lies about landing is caught and retried once. Updates happen
47
+ * only AFTER a frame actually landed, so a crash before delivery never
48
+ * suppresses the next wake either. */
49
+ function writeSidecar(base, id, value) {
50
+ writeFileVerified(sidecarPath(base, id), `${JSON.stringify(value)}\n`, { log });
51
+ }
52
+
53
+ /** flock-style try-lock for event bursts — herdr-sidebar LaunchLock
54
+ * (ensure.rs acquire(false)): one settle fans out to status+exit+closed
55
+ * hooks at once, and herdr runs them concurrently with no sequence number,
56
+ * so without serialization two peers can both read "no sidecar yet" and
57
+ * double-deliver. try semantics (the sidebar's focus-mode): busy -> exit 0
58
+ * at once, a peer is already handling this child. Node has no flock(2), so
59
+ * the lock is the report's sanctioned atomic mkdir — same acquire-or-skip;
60
+ * a crashed holder self-heals via the staleness steal (age > stale window). */
61
+ const wakeLockPath = (base) => join(base, 'wake.lock');
62
+
63
+ function acquireWakeLock(base, env) {
64
+ const file = wakeLockPath(base);
65
+ const staleMs = delayMs(env, 'HERDGATE_WAKE_LOCK_STALE_MS', 60_000);
66
+ const tryLock = () => {
67
+ try { mkdirSync(file, { mode: 0o700 }); return true; }
68
+ catch { return false; }
69
+ };
70
+ if (tryLock()) return true;
71
+ try {
72
+ if (Date.now() - statSync(file).mtimeMs > staleMs) { // crashed holder: steal once
73
+ rmSync(file, { recursive: true, force: true });
74
+ return tryLock();
75
+ }
76
+ } catch { /* a peer raced the steal: treat as busy */ }
77
+ return false;
78
+ }
79
+
80
+ const releaseWakeLock = (base) => rmSync(wakeLockPath(base), { recursive: true, force: true });
81
+
82
+ /** Drop sidecars whose child left the registry (compacted away after 200
83
+ * spawns) — runs only on our own children's events, never throws. */
84
+ function sweepSidecars(base, liveIds) {
85
+ try {
86
+ for (const name of readdirSync(base)) {
87
+ if (!name.endsWith('.wake.json')) continue;
88
+ const id = name.slice(0, -'.wake.json'.length);
89
+ if (!liveIds.has(id)) unlinkSync(join(base, name));
90
+ }
91
+ } catch { /* nothing to sweep */ }
92
+ }
93
+
94
+ /** The event-driven settle frame: the wake-skill banner line, then the
95
+ * self-describing tag line (directive rides IN the frame — it must survive
96
+ * the parent's context compaction). Receipt enrichment (title/tokens) is
97
+ * best effort: with no receipt the frame still goes — exactly the strength
98
+ * of the event architecture over arm/marker cooperation. */
99
+ export function eventWakeFrame({ spawn, agentStatus, receipt, generation, at = Date.now() }) {
100
+ const name = spawn?.name ?? 'child';
101
+ const bits = [`[herdgate-wake child=${name}`, `id=${spawn?.id ?? '?'}`, `status=${agentStatus}`];
102
+ if (receipt?.reason) bits.push(`reason=${receipt.reason}`);
103
+ if (receipt?.title) bits.push(`title="${String(receipt.title).replace(/\s+/g, ' ').slice(0, 60)}"`);
104
+ if (receipt?.usage && Number.isFinite(receipt.usage.totalTokens)) bits.push(`tokens=${receipt.usage.totalTokens}`);
105
+ bits.push('via=herdr-event', `ts=${new Date(at).toISOString()}`);
106
+ // Generation token (herdr-sesh requestID): the parent's revision at fire
107
+ // time rides IN the frame, so a frame landing after the parent turned is
108
+ // self-describing about when it was minted.
109
+ if (Number.isFinite(generation)) bits.push(`gen=${generation}]`);
110
+ else bits.push(']');
111
+ const line = `${bits.join(' ')}${SETTLE_DIRECTIVE}`;
112
+ const body = line.length <= 480 ? line : `${bits.join(' ').slice(0, 300)}…]${SETTLE_DIRECTIVE}`;
113
+ const headline = receipt?.title ? String(receipt.title).replace(/\s+/g, ' ').slice(0, 60) : 'việc con đã settle — herdr báo';
114
+ return `🔔 WAKE — agent ${name} ${agentStatus}: ${headline}\n${body}`;
115
+ }
116
+
117
+ /** DIED: the exact dwake banner (the parent's handling protocol recognizes the
118
+ * format) plus the via=herdr-event tag line. */
119
+ export function eventDeathFrame(spawn, at = Date.now()) {
120
+ const name = spawn?.name ?? 'child';
121
+ return `${deathFrame(spawn)}\n[herdgate-wake child=${name} id=${spawn?.id ?? '?'} status=died via=herdr-event ts=${new Date(at).toISOString()}]`;
122
+ }
123
+
124
+ /** idle/done: the child's turn closed. Dedupe per episode via the child's own
125
+ * agent revision (herdr agent get), then deliver through the parent's
126
+ * quiet-wait and record the episode only AFTER the frame landed. A revision
127
+ * probe that fails wakes anyway unless the heartbeat says corpse (fail
128
+ * open — a duplicate is recoverable, a missed wake is not). */
129
+ function onStatusChanged(env, { data, paneId, spawn, base, run, listPanes, agentProbe }) {
130
+ const status = data?.agent_status;
131
+ if (!WAKE_STATUSES.has(status)) return; // working/blocked transitions wake nobody
132
+ const panes = listPanes();
133
+ if (!panes.some(p => p?.pane_id === paneId)) {
134
+ return log(`child ${spawn.name} pane ${paneId} is gone — the exit event owns the wake`);
135
+ }
136
+ let revision = null;
137
+ try { revision = run('agent', 'get', paneId)?.result?.agent?.revision ?? null; } catch { revision = null; }
138
+ const sidecar = readSidecar(base, spawn.id);
139
+ // Heartbeat liveness (herdr-sidebar ipc.rs: HEARTBEAT_STALE_SECS = 20 —
140
+ // "a corpse keeps both label and token", and a herdr resume replays
141
+ // idle/done for panes whose TUI died long ago). The sidecar stamps
142
+ // lastHeartbeatAt on every delivered frame; a settle whose revision never
143
+ // moved (or cannot be probed) backed by a heartbeat staler than 20s is a
144
+ // corpse settle — drop the fake frame, log it, wake nobody.
145
+ const heartbeatStaleMs = delayMs(env, 'HERDGATE_WAKE_HEARTBEAT_STALE_MS', 20_000);
146
+ const lastHeartbeatAt = typeof sidecar.lastHeartbeatAt === 'number' ? sidecar.lastHeartbeatAt : null;
147
+ const now = Date.now();
148
+ const revisionHeld = revision !== null && sidecar.lastRevision === revision;
149
+ if ((revisionHeld || revision === null) && lastHeartbeatAt !== null && now - lastHeartbeatAt > heartbeatStaleMs) {
150
+ return log(`child ${spawn.name} ${status} but revision ${revision ?? '?'} never moved and the heartbeat is ${((now - lastHeartbeatAt) / 1000) | 0}s stale — corpse settle, frame dropped`);
151
+ }
152
+ if (revision !== null && sidecar.lastRevision === revision) {
153
+ return log(`child ${spawn.name} episode rev ${revision} already woke the parent — deduped`);
154
+ }
155
+ // One-id chain: the receipt request id IS the spawn id; the sessionId
156
+ // fallback only covers odd record shapes. Enrichment may still come back
157
+ // null (no arm, journal elsewhere) — the frame goes regardless.
158
+ const receipt = findReceipt(base, spawn.id) ?? findReceipt(base, spawn.sessionId);
159
+ // Generation token (herdr-sesh requestID): capture the PARENT's revision at
160
+ // fire time and mint it into the frame. If the parent turns while we wait
161
+ // for a quiet moment, delivery proceeds anyway — the drift is logged by
162
+ // deliverToParent, never used to drop a wake.
163
+ const parentPane = spawn.parentPaneId && panes.some(p => p?.pane_id === spawn.parentPaneId)
164
+ ? spawn.parentPaneId
165
+ : paneForSession(panes, spawn.parentSessionId);
166
+ let generation = null;
167
+ if (parentPane) {
168
+ try { generation = run('agent', 'get', parentPane)?.result?.agent?.revision ?? null; } catch { generation = null; }
169
+ }
170
+ log(`child ${spawn.name} ${status} (rev ${revision ?? '?'}) — waking the parent`);
171
+ deliverToParent({
172
+ spawn, line: eventWakeFrame({ spawn, agentStatus: status, receipt, generation }), label: `settled ${status}`,
173
+ run, listPanes, agentProbe, log, generation,
174
+ retryDelayMs: () => new Promise(r => setTimeout(r, delayMs(env, 'HERDGATE_WAKE_RETRY_MS', 3000))),
175
+ settleDelayMs: () => new Promise(r => setTimeout(r, delayMs(env, 'HERDGATE_WAKE_SETTLE_MS', 2000))),
176
+ maxWaitMs: delayMs(env, 'HERDGATE_WAKE_MAX_WAIT_MS', 15 * 60 * 1000),
177
+ onDelivered: () => writeSidecar(base, spawn.id, { ...sidecar, lastRevision: revision, lastWakeAt: Date.now(), lastHeartbeatAt: Date.now() }),
178
+ });
179
+ }
180
+
181
+ /** pane.exited/pane.closed: the pane is gone. One DIED per child — a parent's
182
+ * intentional close or a settle that landed in time is not a death. The
183
+ * registry is marked BEFORE waking, exactly like the old death watch. */
184
+ function onPaneGone(env, { spawn, base, run, listPanes, agentProbe }) {
185
+ if (spawn.died === true) return; // already reported once
186
+ if (spawn.closedBy === 'parent') return; // closed on purpose
187
+ if (!spawn.parentPaneId) return; // no parent-pane edge: not ours to report
188
+ const receipt = findReceipt(base, spawn.id);
189
+ if (receipt && SETTLED.has(receipt.status)) {
190
+ return log(`child ${spawn.name} settled ${receipt.status} before the pane closed — not a death`);
191
+ }
192
+ const marked = patchSpawn(base, spawn.id, { died: true, diedAt: Date.now() });
193
+ if (!marked) return; // record vanished mid-flight: nothing to wake about
194
+ const sidecar = readSidecar(base, spawn.id);
195
+ writeSidecar(base, spawn.id, { ...sidecar, died: true, diedAt: Date.now() });
196
+ log(`child ${marked.name} pane ${marked.paneId} vanished before settling — waking the parent`);
197
+ deliverToParent({
198
+ spawn: marked, line: eventDeathFrame(marked), label: 'DIED',
199
+ run, listPanes, agentProbe, log,
200
+ retryDelayMs: () => new Promise(r => setTimeout(r, delayMs(env, 'HERDGATE_WAKE_RETRY_MS', 3000))),
201
+ settleDelayMs: () => new Promise(r => setTimeout(r, delayMs(env, 'HERDGATE_WAKE_SETTLE_MS', 2000))),
202
+ maxWaitMs: delayMs(env, 'HERDGATE_WAKE_MAX_WAIT_MS', 15 * 60 * 1000),
203
+ // A delivered DIED frame is a heartbeat too: it proves the pipeline is
204
+ // live, so later corpse verdicts for this child measure from here.
205
+ onDelivered: () => writeSidecar(base, spawn.id, { ...readSidecar(base, spawn.id), lastHeartbeatAt: Date.now() }),
206
+ });
207
+ }
208
+
209
+ /** Handle one herdr plugin event. Splits cleanly: not our event or not our
210
+ * pane → silent exit before a single herdr call; ours → dedupe/deliver. */
211
+ export function runWakeEvent(env = process.env) {
212
+ const eventName = env.HERDR_PLUGIN_EVENT ?? '';
213
+ if (!HOOKED.has(eventName)) return;
214
+ let payload = null;
215
+ try { payload = JSON.parse(env.HERDR_PLUGIN_EVENT_JSON || '{}'); }
216
+ catch (error) {
217
+ return log(`unreadable HERDR_PLUGIN_EVENT_JSON: ${error instanceof Error ? error.message : String(error)}`);
218
+ }
219
+ const data = eventData(payload);
220
+ const paneId = typeof data?.pane_id === 'string' ? data.pane_id.trim() : '';
221
+ if (!paneId) return log(`${eventName} carries no pane_id — nothing to do`);
222
+ const base = journalBase(env);
223
+ const run = herdrRunner();
224
+ const listPanes = () => { try { return run('pane', 'list')?.result?.panes ?? []; } catch { return []; } };
225
+ const agentProbe = (pane) => {
226
+ const agent = run('agent', 'get', pane)?.result?.agent;
227
+ return { status: agent?.agent_status, revision: agent?.revision ?? null };
228
+ };
229
+ const spawns = readAllSpawns(base);
230
+ const spawn = spawns.find(s => s.paneId === paneId);
231
+ if (!spawn) return; // a user pane: silently never touched
232
+ // Burst guard BEFORE a single herdr call: a busy lock means a peer hook is
233
+ // already deciding for this child — exit 0 and let it finish.
234
+ if (!acquireWakeLock(base, env)) {
235
+ return log(`wake lock busy — a burst-peer hook is already handling child ${spawn.name}, exiting`);
236
+ }
237
+ try {
238
+ sweepSidecars(base, new Set(spawns.map(s => s.id)));
239
+ if (eventName === 'pane.agent_status_changed') return onStatusChanged(env, { data, paneId, spawn, base, run, listPanes, agentProbe });
240
+ return onPaneGone(env, { spawn, base, run, listPanes, agentProbe });
241
+ } finally {
242
+ releaseWakeLock(base); // async delivery continues lock-free (single-flight per process)
243
+ }
244
+ }
245
+
246
+ /** CLI entry — never throws: an event hook failing loudly would spam toasts. */
247
+ export function main() {
248
+ try {
249
+ runWakeEvent(process.env);
250
+ } catch (error) {
251
+ log(`failed: ${error instanceof Error ? error.message : String(error)}`);
252
+ }
253
+ }
254
+
255
+ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) main();
@@ -156,7 +156,7 @@ export class HerdGateAgent {
156
156
  export async function provision(o: {
157
157
  baseUrl: string; // http(s)://host[:port]
158
158
  name: string;
159
- onCode?: (url: string | { code: string }) => void;
159
+ onCode?: (info: { url: string; code: string }) => void;
160
160
  pollMs?: number;
161
161
  timeoutMs?: number;
162
162
  }): Promise<{ roomToken: string; roomId: string }> {
@@ -167,7 +167,9 @@ export async function provision(o: {
167
167
  });
168
168
  if (!res.ok) throw new Error(`agent/code: ${res.status}`);
169
169
  const minted = (await res.json()) as { code: string; url: string };
170
- (o.onCode ?? ((u) => console.log(`pair this host: ${u}`)))(minted.url);
170
+ // Both fields go to the caller: the url to click, the code for the pairing QR
171
+ // (see ../agent/qr.ts — the PWA opens with `#pair=<code>` prefilled).
172
+ (o.onCode ?? ((i) => console.log(`pair this host: ${i.url}`)))({ url: minted.url, code: minted.code });
171
173
  const deadline = Date.now() + (o.timeoutMs ?? 11 * 60_000);
172
174
  while (Date.now() < deadline) {
173
175
  await new Promise((r) => setTimeout(r, o.pollMs ?? 3_000));