@dibssoftware/dibs 0.0.0-stage → 0.0.178

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.
Files changed (72) hide show
  1. package/CHANGELOG.md +577 -0
  2. package/LICENSE +670 -0
  3. package/README.md +234 -2
  4. package/bin/dibs-guard.mjs +7 -0
  5. package/bin/dibs.mjs +526 -0
  6. package/docs/benchmarks.md +193 -0
  7. package/docs/files.md +30 -0
  8. package/docs/guard.md +91 -0
  9. package/docs/later.md +43 -0
  10. package/docs/machines.md +147 -0
  11. package/docs/questions.md +78 -0
  12. package/docs/relay.md +196 -0
  13. package/docs/releasing.md +25 -0
  14. package/docs/scheduling.md +163 -0
  15. package/docs/simulators.md +17 -0
  16. package/package.json +44 -4
  17. package/skills/dibs/SKILL.md +162 -0
  18. package/src/acquire.mjs +697 -0
  19. package/src/admin.mjs +145 -0
  20. package/src/agents.mjs +145 -0
  21. package/src/alerts.mjs +437 -0
  22. package/src/answers.mjs +65 -0
  23. package/src/board.mjs +202 -0
  24. package/src/broker.mjs +369 -0
  25. package/src/commands.mjs +801 -0
  26. package/src/config.mjs +320 -0
  27. package/src/connect.mjs +106 -0
  28. package/src/cool.mjs +160 -0
  29. package/src/diskwarn.mjs +161 -0
  30. package/src/events.mjs +94 -0
  31. package/src/files.mjs +1100 -0
  32. package/src/guard.mjs +583 -0
  33. package/src/history.mjs +247 -0
  34. package/src/hogs.mjs +214 -0
  35. package/src/later.mjs +487 -0
  36. package/src/measure.mjs +262 -0
  37. package/src/nodecheck.mjs +17 -0
  38. package/src/notices.mjs +121 -0
  39. package/src/ondemand.mjs +572 -0
  40. package/src/overlap.mjs +151 -0
  41. package/src/override.mjs +351 -0
  42. package/src/owner.mjs +30 -0
  43. package/src/plain.mjs +467 -0
  44. package/src/platform.mjs +357 -0
  45. package/src/preempt.mjs +438 -0
  46. package/src/primer.mjs +61 -0
  47. package/src/proc.mjs +98 -0
  48. package/src/progress.mjs +158 -0
  49. package/src/qr.mjs +204 -0
  50. package/src/questions.mjs +389 -0
  51. package/src/quota.mjs +81 -0
  52. package/src/reads.mjs +54 -0
  53. package/src/relay.mjs +779 -0
  54. package/src/remote.mjs +584 -0
  55. package/src/reset.mjs +127 -0
  56. package/src/schedule.mjs +995 -0
  57. package/src/scratch.mjs +61 -0
  58. package/src/serve.mjs +736 -0
  59. package/src/service.mjs +221 -0
  60. package/src/shard.mjs +59 -0
  61. package/src/simctl.mjs +42 -0
  62. package/src/simpool.mjs +258 -0
  63. package/src/state.mjs +201 -0
  64. package/src/stats.mjs +328 -0
  65. package/src/style.mjs +44 -0
  66. package/src/talk.mjs +523 -0
  67. package/src/thin.sh +130 -0
  68. package/src/trust.mjs +152 -0
  69. package/src/util.mjs +184 -0
  70. package/src/version.mjs +2 -0
  71. package/src/web.mjs +1117 -0
  72. package/src/worker.mjs +318 -0
package/src/state.mjs ADDED
@@ -0,0 +1,201 @@
1
+ // The shared state file: who holds what and who's waiting. Every change goes
2
+ // through withState, which holds a mkdir lock for a few milliseconds.
3
+ import fs from 'node:fs';
4
+ import path from 'node:path';
5
+ import { paths, HOME } from './config.mjs';
6
+ import { makeAlive } from './proc.mjs';
7
+ import { stopTree, starts, liveGroups, OS } from './platform.mjs';
8
+ import { settle, flush } from './preempt.mjs';
9
+ import { reapPool } from './simpool.mjs';
10
+ import { queueResets, startResets, reapResets } from './reset.mjs';
11
+ import { logChanges, event } from './events.mjs';
12
+ import { die, now, say, sleepSync, noSpace, fakeFull } from './util.mjs';
13
+
14
+ export const KEEP_PLACE = 120e3; // a waiter that gave up keeps its place this long
15
+
16
+ export function withState(fn) {
17
+ fs.mkdirSync(HOME, { recursive: true });
18
+ const t0 = now();
19
+ const owner = path.join(paths.lock, 'pid');
20
+ for (;;) {
21
+ try { fs.mkdirSync(paths.lock); } catch (e) {
22
+ if (e.code !== 'EEXIST') throw e;
23
+ // Take the lock over only from a writer that died holding it, or one stuck
24
+ // for 30s. The age check matters: the pid we read may belong to a writer
25
+ // that just finished, while the directory is already someone's fresh lock.
26
+ let pid = 0, age = 0;
27
+ try { pid = Number(fs.readFileSync(owner, 'utf8')); } catch {}
28
+ try { age = now() - fs.statSync(paths.lock).mtimeMs; } catch { continue; }
29
+ if (age > 30000 || (age > 3000 && (!pid || !makeAlive([pid])(pid)))) takeOver(pid);
30
+ if (now() - t0 > 45000) die(`state lock stuck; remove ${paths.lock} if no dibs is running. Your command did not run.`, 75);
31
+ sleepSync(10 + Math.random() * 20);
32
+ continue;
33
+ }
34
+ // A lock with no pid in it (a full disk) would hold everyone up until it looked stale: give it back now.
35
+ try { fakeFull('lock'); fs.writeFileSync(owner, String(process.pid)); break; }
36
+ catch (e) { fs.rmSync(paths.lock, { recursive: true, force: true }); throw e; }
37
+ }
38
+ let written = false, moved = false;
39
+ vanished = [];
40
+ try {
41
+ const { s, raw } = read();
42
+ const before = [...s.leases];
43
+ const line = ids(s);
44
+ const paused = new Map(before.map(l => [l.id, l.pausedAt]));
45
+ reap(s);
46
+ const out = fn(s);
47
+ settle(s, now(), history); // resume work paused for a lease that has ended, and never leave every job paused
48
+ queueResets(s, before.filter(l => !s.leases.some(x => x.id === l.id))); // onRelease for every lease this change ended
49
+ // Nothing changed, nothing written: most waiters' polls change nothing, and
50
+ // an unchanged file tells a waiter it can poll less often (src/acquire.mjs nextPoll).
51
+ const text = JSON.stringify(s, null, 1);
52
+ if (text !== raw) {
53
+ // A write cut short by a full disk leaves the old state in place, and no half file taking up space.
54
+ try { fakeFull('state'); fs.writeFileSync(paths.state + '.tmp', text); }
55
+ catch (e) { fs.rmSync(paths.state + '.tmp', { force: true }); throw e; }
56
+ fs.renameSync(paths.state + '.tmp', paths.state);
57
+ written = true;
58
+ moved = ids(s) !== line;
59
+ }
60
+ logChanges(before, paused, s);
61
+ for (const e of vanished) event(e);
62
+ flush(); // pause and resume signals, now that the state says why
63
+ return out;
64
+ } finally {
65
+ flush(false); // a change that failed sends nothing
66
+ fs.rmSync(paths.lock, { recursive: true, force: true });
67
+ if (moved && kicks) try { kick(); } catch {} // after the lock, which the broker takes next
68
+ startResets(written);
69
+ }
70
+ }
71
+
72
+ // The broker (src/broker.mjs) ticks when kicked: one byte down its control
73
+ // FIFO whenever a change starts or ends a lease or changes the line, so the
74
+ // next waiter's turn comes at once rather than at the next tick. Never
75
+ // blocks; false when no broker is reading. The broker turns it off for itself.
76
+ const ids = s => `${s.leases.map(l => l.id)}|${s.queue.map(q => `${q.id}:${q.pid}`)}`;
77
+ let kicks = true;
78
+ export const quiet = () => { kicks = false; };
79
+ export function kick() {
80
+ let fd;
81
+ // ENXIO: nobody reading. Anything else (no FIFO there) is no broker either.
82
+ try { fd = fs.openSync(paths.ctl, fs.constants.O_WRONLY | fs.constants.O_NONBLOCK); } catch { return false; }
83
+ try { fs.writeSync(fd, 'k'); } catch (e) { if (e.code !== 'EAGAIN') throw e; } finally { fs.closeSync(fd); }
84
+ return true;
85
+ }
86
+
87
+ // For a change that can wait for the next one (a measurement, a note of
88
+ // split-off groups): on a full disk it's skipped, and this returns undefined.
89
+ export function withStateIfRoom(fn) {
90
+ try { return withState(fn); } catch (e) { if (noSpace(e)) return undefined; throw e; }
91
+ }
92
+
93
+ // Move the stale lock aside atomically, then check it was the one we judged.
94
+ // If another waiter replaced it in between, put theirs back.
95
+ function takeOver(pid) {
96
+ const aside = `${paths.lock}.stale-${process.pid}-${now()}`;
97
+ try { fs.renameSync(paths.lock, aside); } catch { return; }
98
+ let got = 0;
99
+ try { got = Number(fs.readFileSync(path.join(aside, 'pid'), 'utf8')); } catch {}
100
+ if (got === pid) fs.rmSync(aside, { recursive: true, force: true });
101
+ else try { fs.renameSync(aside, paths.lock); } catch { fs.rmSync(aside, { recursive: true, force: true }); }
102
+ }
103
+
104
+ // The state as last written, without the lock and without reaping: what dibs
105
+ // web shows. Writes are a rename, so this never sees half a file; a holder that
106
+ // died shows until the next dibs call reaps it.
107
+ export function peek() { return read().s; }
108
+
109
+ function read() {
110
+ let s = { seq: 0, leases: [], queue: [] }, raw = null;
111
+ if (fs.existsSync(paths.state)) {
112
+ try { raw = fs.readFileSync(paths.state, 'utf8'); s = JSON.parse(raw); }
113
+ catch {
114
+ const bad = `${paths.state}.corrupt-${now()}`;
115
+ fs.copyFileSync(paths.state, bad);
116
+ say(`state file was unreadable; saved it to ${bad} and started fresh. Running jobs keep running but aren't tracked.`);
117
+ }
118
+ }
119
+ s.seq ||= 0; s.leases ||= []; s.queue ||= [];
120
+ return { s, raw };
121
+ }
122
+
123
+ // Drop leases whose process is gone (killing anything they left running) and
124
+ // waiters who left or died.
125
+ // Waiters found dead by this change, for the history once it's written.
126
+ let vanished = [];
127
+ function reap(s) {
128
+ const t = now();
129
+ const alive = makeAlive([...s.leases.map(l => l.pid), ...s.queue.map(q => q.pid || q.keptFor), ...(s.resets || []).flatMap(x => [x.pid, x.cpid])]);
130
+ s.leases = s.leases.filter(l => {
131
+ if (l.kind === 'hold') return t < l.expires && (!l.pid || alive(l.pid, l.pstart));
132
+ if (alive(l.pid, l.pstart)) return true;
133
+ killLease(l);
134
+ // Its dibs was killed, so nobody recorded what it measured. A job big enough
135
+ // to get its dibs killed is the one the next run most needs to plan for.
136
+ if (l.peak?.mem) record(l.key, t - l.start - (l.pausedMs || 0), l.who, l.peak, true);
137
+ return false;
138
+ });
139
+ // A waiter whose process is gone leaves the line, however it went: a place
140
+ // left behind by a kill, or by a path that didn't clean up, would sit ahead of
141
+ // live waiters. That includes a place kept for a thin waiter's own retry in
142
+ // Node (src/broker.mjs keptFor), which only that process can pick up. A place
143
+ // kept with no process on it (a wait that timed out, exit 75) stays KEEP_PLACE
144
+ // for the same command to pick up.
145
+ s.queue = s.queue.filter(q => {
146
+ const owner = q.pid || (q.keptFor && !q.pid ? q.keptFor : null);
147
+ if (owner && !alive(owner, q.pstart)) {
148
+ vanished.push({ at: t, kind: 'left', id: q.id, res: q.res, who: q.who, prio: q.prio || 'normal', type: q.kind, ms: t - q.enq, why: 'gone' });
149
+ return false;
150
+ }
151
+ return q.pid || (q.keepUntil && t < q.keepUntil);
152
+ });
153
+ reapPool(s);
154
+ reapResets(s, alive);
155
+ }
156
+
157
+ // Everything a run lease started: its process group and any groups its
158
+ // children split off into. Windows has no groups and recycles pids, so there
159
+ // the tree is killed only if its root is still the process we started.
160
+ export function killLease(l) {
161
+ if (OS === 'windows') {
162
+ if (l.pgid && makeAlive([l.pgid])(l.pgid, l.pgstart)) stopTree(l.pgid, 'SIGKILL');
163
+ return;
164
+ }
165
+ // A paused run's stopped groups too: stopped, they'd wait forever.
166
+ const all = [...new Set([l.pgid, ...(l.groups || []), ...(l.stopped || [])])].filter(Boolean);
167
+ if (!all.length) return;
168
+ const leaders = starts(all);
169
+ if (!leaders) return; // the process table can't be read: signal nothing rather than guess
170
+ const live = liveGroups();
171
+ const known = { ...l.groupStarts, [l.pgid]: l.pgstart };
172
+ for (const g of all) if (stillOurs(l, g, leaders.get(g), known[g], live)) stopTree(g, 'SIGKILL');
173
+ }
174
+
175
+ // A group number is reused once its group empties, so a group is the run's
176
+ // only if its leader is the process recorded (same start time), or its leader
177
+ // has exited and the group still has members (a number can't be reused while
178
+ // its group has any). A group the run had stopped can't have emptied while
179
+ // stopped, so a leader that started before the pause is the run's too.
180
+ function stillOurs(l, g, leader, recorded, live) {
181
+ if (!leader) return live.has(g);
182
+ if (recorded) return leader === recorded;
183
+ return !!l.pausedAt && (l.stopped || []).includes(g) && Date.parse(leader) <= l.pausedAt;
184
+ }
185
+
186
+ // Past run times, newest last. A line cut short (a crash mid-append) is
187
+ // skipped, not allowed to throw away every other line.
188
+ export function history() {
189
+ let text;
190
+ try { text = fs.readFileSync(paths.history, 'utf8'); } catch (e) { if (e.code === 'ENOENT') return []; throw e; }
191
+ return text.trim().split('\n').slice(-1000).flatMap(l => { try { return [JSON.parse(l)]; } catch { return []; } });
192
+ }
193
+
194
+ // peak is the most the run was measured using (src/measure.mjs), when it ran long enough to be.
195
+ // A failed run (nonzero exit, or its dibs killed) is recorded for its size
196
+ // only: its time says nothing about a run's (schedule.mjs typical skips it).
197
+ // Run times are worth less than the run: on a full disk this one goes unrecorded.
198
+ export function record(key, duration, who, peak, failed = false) {
199
+ try { fs.appendFileSync(paths.history, JSON.stringify({ key, dur: duration, who, at: now(), ...(peak ? { mem: peak.mem, cpu: peak.cpu, ...(peak.fit && { fit: true }), ...(peak.ate != null && { ate: Math.round(peak.ate) }) } : {}), ...(failed && { failed: true }) }) + '\n'); }
200
+ catch (e) { if (!noSpace(e)) throw e; }
201
+ }
package/src/stats.mjs ADDED
@@ -0,0 +1,328 @@
1
+ // dibs stats --agent/--me/--since/--json, the web page's Stats view and the
2
+ // MCP stats tool: what each agent and each resource did, from what dibs
3
+ // already writes down. Nothing here is recorded for stats' sake:
4
+ // events.jsonl starts (with the wait and what held them), ends (run time,
5
+ // exit code), waits, give-ups, pauses, owner overrides, and
6
+ // the throttle watcher's machine samples
7
+ // history.jsonl each run's command and its measured memory
8
+ // progress.jsonl agents' posts: tasks, ETAs, done and blocked
9
+ // collect() is a pure function of those, so a test can feed it a made-up week.
10
+ import fs from 'node:fs';
11
+ import { paths } from './config.mjs';
12
+ import { readEvents } from './events.mjs';
13
+ import { read as readPosts } from './progress.mjs';
14
+ import { identity } from './proc.mjs';
15
+ import { span, stats as plainStats, statsOf } from './history.mjs';
16
+ import { die, now, dur, clock, masked } from './util.mjs';
17
+ import { bold, dim } from './style.mjs';
18
+
19
+ const HOUR = 36e5, DAY = 24 * HOUR;
20
+ // The machine chart: more points than this and a phone draws a smear.
21
+ const MACHINE_POINTS = 240;
22
+ const TOP = 6;
23
+ // Ends by signal: SIGTERM (143) and SIGKILL (137) are a stop, not the command failing.
24
+ const STOPPED = new Set([137, 143, 130]);
25
+ // What held a job back, as the start event's `held` and the wait event's `rule` name it (src/acquire.mjs).
26
+ export const RULES = {
27
+ memory: 'free memory', pressure: 'memory pressure', swap: 'swapping', swaproom: 'disk for swap', disk: 'free disk',
28
+ drain: 'disk filling', cpu: 'CPU cores', load: 'machine load', slot: 'a busy slot', ahead: 'someone ahead',
29
+ together: 'a job it would slow', reset: 'a reset', files: 'a file lease',
30
+ };
31
+
32
+ const pct = (xs, p) => (xs.length ? [...xs].sort((a, b) => a - b)[Math.ceil(p * xs.length) - 1] : null);
33
+ const sum = xs => xs.reduce((a, b) => a + b, 0);
34
+ const midnight = t => new Date(t).setHours(0, 0, 0, 0);
35
+ const nextDay = t => { const d = new Date(t); d.setDate(d.getDate() + 1); return d.setHours(0, 0, 0, 0); };
36
+ const top = (m, n = TOP) => [...m.entries()].sort((a, b) => b[1].n - a[1].n || b[1].ms - a[1].ms).slice(0, n).map(([k, v]) => ({ name: k, ...v }));
37
+ const bump = (m, k, ms = 0) => { const x = m.get(k) || { n: 0, ms: 0 }; x.n++; x.ms += ms; m.set(k, x); };
38
+ // A history key is "res,res|program words / more words" (src/acquire.mjs commandKey): the command part.
39
+ // File leases name one path each; together they're one line, as on the Mac app's schedule.
40
+ const resOf = rs => [...new Set((rs || []).map(r => (r.startsWith('files:') ? 'files' : r)))];
41
+ const cmdOf = key => masked(String(key || '').split('|').slice(1).join('|').split(' / ')[0].replace(/[\u0000-\u001f\u007f\u2028\u2029]+/g, ' ').trim()) || null;
42
+
43
+ // Every history.jsonl line since `since`. history() in state.mjs keeps only the newest 1000.
44
+ export function readRuns(since) {
45
+ let text = '';
46
+ try { text = fs.readFileSync(paths.history, 'utf8'); } catch {}
47
+ const out = [];
48
+ for (const l of text.split('\n')) {
49
+ if (!l) continue;
50
+ try { const r = JSON.parse(l); if (r.at >= since) out.push(r); } catch {}
51
+ }
52
+ return out;
53
+ }
54
+
55
+ // One job per start that has an end: who, what, how long it waited and ran,
56
+ // and how it ended. A job still running counts its wait, not yet its run.
57
+ function jobsOf(events, since, until) {
58
+ const starts = new Map(), out = [];
59
+ for (const e of events) {
60
+ if (e.kind === 'start') starts.set(e.id, e);
61
+ else if (e.kind === 'end' && starts.has(e.id)) {
62
+ const s = starts.get(e.id);
63
+ starts.delete(e.id);
64
+ if (s.at >= since && s.at <= until) out.push({ id: e.id, who: s.who, res: resOf(s.res), type: s.type || 'run', at: s.at, end: e.at, wait: s.ms || 0, run: e.ms || 0, code: e.code ?? null, held: s.held || null });
65
+ }
66
+ }
67
+ for (const s of starts.values()) if (s.at >= since && s.at <= until) out.push({ id: s.id, who: s.who, res: resOf(s.res), type: s.type || 'run', at: s.at, end: null, wait: s.ms || 0, run: until - s.at, code: null, held: s.held || null, open: true });
68
+ return out.sort((a, b) => a.at - b.at);
69
+ }
70
+
71
+ // How a task's ETA held up: for each task an agent finished, its last ETA
72
+ // before the done post against when it was done. late > 0 ms means past it.
73
+ function etas(posts) {
74
+ const by = new Map(), out = [];
75
+ for (const p of posts) {
76
+ const key = `${p.who}\0${p.task || ''}\0${p.task ? '' : p.project || ''}`;
77
+ const t = by.get(key) || { who: p.who, task: p.task || null, eta: null, blockedAt: null, blockedMs: 0 };
78
+ by.set(key, t);
79
+ // Blocked lasts from the blocked post to the task's next post.
80
+ if (t.blockedAt != null) { t.blockedMs += p.at - t.blockedAt; t.blockedAt = null; }
81
+ if (p.state === 'blocked') t.blockedAt = p.at;
82
+ if (p.eta) t.eta = p.eta;
83
+ if (p.state === 'done' && t.eta) { out.push({ who: p.who, task: t.task, eta: t.eta, done: p.at, late: p.at - t.eta }); t.eta = null; }
84
+ }
85
+ return { finished: out, tasks: [...by.values()] };
86
+ }
87
+
88
+ function heldOf(jobs) {
89
+ const m = new Map();
90
+ for (const j of jobs) for (const [rule, ms] of Object.entries(j.held || {})) bump(m, rule, ms);
91
+ return [...m.entries()].sort((a, b) => b[1].ms - a[1].ms).map(([rule, v]) => ({ rule, label: RULES[rule] || rule, jobs: v.n, ms: v.ms }));
92
+ }
93
+
94
+ function exits(jobs) {
95
+ const runs = jobs.filter(j => j.type === 'run' && !j.open);
96
+ const codes = {};
97
+ for (const j of runs) codes[j.code ?? 'none'] = (codes[j.code ?? 'none'] || 0) + 1;
98
+ const failed = runs.filter(j => j.code != null && j.code !== 0 && !STOPPED.has(j.code)).length;
99
+ const stopped = runs.filter(j => STOPPED.has(j.code)).length;
100
+ return { runs: runs.length, failed, stopped, failRate: runs.length ? failed / runs.length : null, codes };
101
+ }
102
+
103
+ // A start a second or less after asking is dibs's own bookkeeping, not a wait anyone felt.
104
+ const FELT = 1000;
105
+ function waitsOf(jobs) {
106
+ const w = jobs.filter(j => j.wait > FELT).map(j => j.wait);
107
+ const done = jobs.filter(j => !j.open);
108
+ return {
109
+ waitMs: sum(jobs.map(j => j.wait)), waited: w.length, feltMedian: pct(w, 0.5), medianWait: pct(jobs.map(j => j.wait), 0.5), p90Wait: pct(jobs.map(j => j.wait), 0.9),
110
+ waitedLonger: done.filter(j => j.wait > j.run).length, waitedLongerShare: done.length ? done.filter(j => j.wait > j.run).length / done.length : null,
111
+ };
112
+ }
113
+
114
+ // Busy time per local hour of the day, as a share of that hour's time in the window.
115
+ function byHourOfDay(ivs, since, until) {
116
+ const busy = new Array(24).fill(0), there = new Array(24).fill(0);
117
+ for (let t = since; t < until;) {
118
+ const d = new Date(t); d.setMinutes(60, 0, 0);
119
+ const next = Math.min(d.getTime(), until);
120
+ there[new Date(t).getHours()] += next - t;
121
+ t = next;
122
+ }
123
+ for (const { a, b } of ivs) {
124
+ for (let t = Math.max(a, since), end = Math.min(b, until); t < end;) {
125
+ const d = new Date(t); d.setMinutes(60, 0, 0);
126
+ const next = Math.min(d.getTime(), end);
127
+ busy[new Date(t).getHours()] += next - t;
128
+ t = next;
129
+ }
130
+ }
131
+ return busy.map((ms, h) => (there[h] ? Math.min(1, ms / there[h]) : 0));
132
+ }
133
+
134
+ // Time covered by at least one interval.
135
+ function union(ivs, lo, hi) {
136
+ const cl = ivs.map(({ a, b }) => [Math.max(a, lo), Math.min(b, hi)]).filter(([x, y]) => y > x).sort((p, q) => p[0] - q[0]);
137
+ let total = 0, end = -Infinity;
138
+ for (const [x, y] of cl) {
139
+ if (y <= end) continue;
140
+ total += y - Math.max(x, end);
141
+ end = y;
142
+ }
143
+ return total;
144
+ }
145
+
146
+ // Run and wait time falling in each (day, hour) cell: days down, hours across.
147
+ function grid(jobs, since, until) {
148
+ const days = [];
149
+ for (let d = midnight(since); d < until; d = nextDay(d)) days.push({ day: d, run: new Array(24).fill(0), wait: new Array(24).fill(0), jobs: new Array(24).fill(0) });
150
+ const spread = (a, b, key) => {
151
+ for (let t = Math.max(a, since), end = Math.min(b, until); t < end;) {
152
+ const d = new Date(t); d.setMinutes(60, 0, 0);
153
+ const next = Math.min(d.getTime(), end);
154
+ const row = days.find(x => x.day === midnight(t));
155
+ if (row) row[key][new Date(t).getHours()] += next - t;
156
+ t = next;
157
+ }
158
+ };
159
+ for (const j of jobs) {
160
+ spread(j.at - j.wait, j.at, 'wait');
161
+ spread(j.at, j.at + j.run, 'run');
162
+ const row = days.find(x => x.day === midnight(j.at));
163
+ if (row) row.jobs[new Date(j.at).getHours()]++;
164
+ }
165
+ return days;
166
+ }
167
+
168
+ function machineOf(events, since, until, agent) {
169
+ const samples = events.filter(e => e.kind === 'sample' && e.at >= since && e.at <= until);
170
+ const step = Math.max(6e4, (until - since) / MACHINE_POINTS);
171
+ const buckets = new Map();
172
+ for (const s of samples) {
173
+ const k = Math.floor((s.at - since) / step);
174
+ const b = buckets.get(k) || { at: since + k * step, load: [], memFree: [], diskFree: [] };
175
+ for (const f of ['load', 'memFree', 'diskFree']) if (typeof s[f] === 'number') b[f].push(s[f]);
176
+ buckets.set(k, b);
177
+ }
178
+ const avg = xs => (xs.length ? sum(xs) / xs.length : null);
179
+ const series = [...buckets.values()].sort((a, b) => a.at - b.at).map(b => ({ at: Math.round(b.at), load: avg(b.load), memFree: avg(b.memFree), diskFree: avg(b.diskFree) }));
180
+ const inWin = e => e.at >= since && e.at <= until && (!agent || e.who === agent);
181
+ const pauses = events.filter(e => e.kind === 'pause' && inWin(e));
182
+ const overrides = events.filter(e => e.kind === 'override' && e.at >= since && e.at <= until && (!agent || e.who === agent || e.by === agent));
183
+ // An owner's pause leaves an override event too; the rest are dibs's own (memory pressure, urgent work).
184
+ const ownerPauses = overrides.filter(e => e.act === 'pause').length;
185
+ const memLow = series.filter(x => x.memFree != null).sort((a, b) => a.memFree - b.memFree)[0] || null;
186
+ const diskLow = series.filter(x => x.diskFree != null).sort((a, b) => a.diskFree - b.diskFree)[0] || null;
187
+ const loadHigh = series.filter(x => x.load != null).sort((a, b) => b.load - a.load)[0] || null;
188
+ return {
189
+ series, samples: samples.length, memLow, diskLow, loadHigh,
190
+ pauses: pauses.length, ownerPauses, dibsPauses: Math.max(0, pauses.length - ownerPauses),
191
+ overrides: overrides.slice(-40).map(e => ({ at: e.at, act: e.act, by: e.by || null, byAgent: !!e.byAgent, id: e.id ?? null, who: e.who ?? null, to: e.to ?? null, prio: e.prio ?? null, reason: e.reason ?? null })),
192
+ cleaned: sum(events.filter(e => e.kind === 'clean' && e.at >= since && e.at <= until).map(e => e.freed || 0)),
193
+ };
194
+ }
195
+
196
+ // The whole picture between since and until, for everyone or one agent.
197
+ export function collect({ events, runs = [], posts = [], since, until, agent = null }) {
198
+ const all = jobsOf(events, since, until);
199
+ const jobs = agent ? all.filter(j => j.who === agent) : all;
200
+ const gaveUp = events.filter(e => e.kind === 'timeout' && e.at >= since && e.at <= until && (!agent || e.who === agent));
201
+ const left = events.filter(e => e.kind === 'left' && e.at >= since && e.at <= until && (!agent || e.who === agent));
202
+ const myPosts = posts.filter(p => p.at >= since && p.at <= until && (!agent || p.who === agent));
203
+ const eta = etas(posts.filter(p => p.at <= until && (!agent || p.who === agent)));
204
+ const etaIn = eta.finished.filter(x => x.done >= since);
205
+ const myRuns = runs.filter(r => r.at >= since && r.at <= until && (!agent || r.who === agent));
206
+
207
+ const agentsOf = new Map();
208
+ for (const j of jobs) (agentsOf.get(j.who) || agentsOf.set(j.who, []).get(j.who)).push(j);
209
+ for (const p of myPosts) if (!agentsOf.has(p.who)) agentsOf.set(p.who, []);
210
+ const agents = [...agentsOf.entries()].map(([who, js]) => {
211
+ const res = new Map(), cmds = new Map();
212
+ for (const j of js) for (const r of j.res) bump(res, r, j.open ? 0 : j.run);
213
+ const rs = myRuns.filter(r => r.who === who);
214
+ for (const r of rs) { const c = cmdOf(r.key); if (c) bump(cmds, c, r.dur || 0); }
215
+ const ps = myPosts.filter(p => p.who === who);
216
+ const mine = etaIn.filter(x => x.who === who);
217
+ const tasks = eta.tasks.filter(x => x.who === who);
218
+ return {
219
+ who, jobs: js.length, runMs: sum(js.map(j => j.run)), ...waitsOf(js), ...exits(js),
220
+ gaveUp: gaveUp.filter(e => e.who === who).length,
221
+ resources: top(res), commands: top(cmds), heldBy: heldOf(js),
222
+ peakMem: Math.max(0, ...rs.map(r => r.mem || 0)) || null,
223
+ posts: ps.length, tasksDone: new Set(ps.filter(p => p.state === 'done').map(p => p.task || p.project)).size,
224
+ blockedMs: sum(tasks.map(x => x.blockedMs)), blockedNow: tasks.filter(x => x.blockedAt != null).length,
225
+ eta: { finished: mine.length, onTime: mine.filter(x => x.late <= 0).length, medianLate: pct(mine.map(x => x.late), 0.5) },
226
+ };
227
+ }).sort((a, b) => b.jobs - a.jobs || b.posts - a.posts);
228
+
229
+ const resNames = [...new Set(jobs.flatMap(j => j.res))];
230
+ const resources = resNames.map(r => {
231
+ const js = jobs.filter(j => j.res.includes(r));
232
+ const ivs = js.map(j => ({ a: j.at, b: j.at + j.run }));
233
+ const busy = union(ivs, since, until);
234
+ const holders = new Map();
235
+ for (const j of js) bump(holders, j.who, j.run);
236
+ return {
237
+ res: r, jobs: js.length, busyMs: busy, utilization: busy / Math.max(1, until - since), ...waitsOf(js),
238
+ hours: byHourOfDay(ivs, since, until), heldBy: heldOf(js), agents: top(holders, 4),
239
+ gaveUp: gaveUp.filter(e => resOf(e.res).includes(r)).length,
240
+ waitRules: Object.entries(events.filter(e => e.kind === 'wait' && e.at >= since && e.at <= until && resOf(e.res).includes(r) && (!agent || e.who === agent))
241
+ .reduce((m, e) => ({ ...m, [e.rule || 'slot']: (m[e.rule || 'slot'] || 0) + 1 }), {})).sort((a, b) => b[1] - a[1]).map(([rule, n]) => ({ rule, label: RULES[rule] || rule, n })),
242
+ };
243
+ }).sort((a, b) => b.busyMs - a.busyMs);
244
+
245
+ const days = [];
246
+ for (let d = midnight(since); d < until; d = nextDay(d)) {
247
+ const js = jobs.filter(j => j.at >= d && j.at < nextDay(d));
248
+ days.push({ day: d, jobs: js.length, runMs: sum(js.map(j => j.run)), waitMs: sum(js.map(j => j.wait)), ...exits(js) });
249
+ }
250
+
251
+ return {
252
+ since, until, agent,
253
+ totals: {
254
+ jobs: jobs.length, agents: agents.filter(a => a.jobs).length, runMs: sum(jobs.map(j => j.run)), ...waitsOf(jobs), ...exits(jobs),
255
+ gaveUp: gaveUp.length, leftLine: left.length, posts: myPosts.length,
256
+ eta: { finished: etaIn.length, onTime: etaIn.filter(x => x.late <= 0).length, medianLate: pct(etaIn.map(x => x.late), 0.5) },
257
+ heldBy: heldOf(jobs),
258
+ },
259
+ agents, resources, days, grid: grid(jobs, since, until), machine: machineOf(events, since, until, agent),
260
+ };
261
+ }
262
+
263
+ // The same from the files on disk.
264
+ export function gather({ since, until = now(), agent = null } = {}) {
265
+ return collect({ events: readEvents(until), runs: readRuns(since), posts: readPosts({ since: since - 7 * DAY }), since, until, agent });
266
+ }
267
+
268
+ // Plain sentences first, then the numbers: what an agent reads to see how it's doing.
269
+ const share = x => (x == null ? '-' : `${Math.round(100 * x)}%`);
270
+ export function text(s) {
271
+ const t = s.totals, who = s.agent || 'Everyone';
272
+ const out = [bold(`${who}, ${new Date(s.since).toLocaleDateString([], { month: 'short', day: 'numeric' })} ${clock(s.since)} to now`)];
273
+ if (!t.jobs && !t.posts) return [...out, 'Nothing went through dibs in this period.'];
274
+ out.push(`${t.jobs} job${t.jobs === 1 ? '' : 's'}: ran ${dur(t.runMs)}, waited ${dur(t.waitMs)}. ${t.waitedLongerShare != null ? `${share(t.waitedLongerShare)} waited longer than they ran.` : ''}`.trim());
275
+ if (t.runs) out.push(`${t.runs} finished run${t.runs === 1 ? '' : 's'}: ${t.failed} failed (${share(t.failRate)}), ${t.stopped} stopped by a signal.${t.gaveUp ? ` ${t.gaveUp} gave up waiting (exit 75).` : ''}`);
276
+ if (t.heldBy.length) out.push(`Held back most by ${t.heldBy.slice(0, 3).map(h => `${h.label} (${dur(h.ms)})`).join(', ')}.`);
277
+ if (t.eta.finished) out.push(`ETAs: ${t.eta.onTime} of ${t.eta.finished} tasks done on time${t.eta.medianLate > 0 ? `, typically ${dur(t.eta.medianLate)} late` : ''}.`);
278
+ if (t.posts) out.push(`${t.posts} progress post${t.posts === 1 ? '' : 's'}.`);
279
+ const cols = (head, rows) => {
280
+ const w = head.map((c, i) => Math.max(c.length, ...rows.map(r => String(r[i]).length)));
281
+ return [head, ...rows].map(r => ` ${r.map((c, i) => (i ? String(c).padStart(w[i]) : String(c).padEnd(w[i]))).join(' ')}`.trimEnd());
282
+ };
283
+ if (s.resources.length) {
284
+ out.push('', bold('By resource'), ...cols(['', 'jobs', 'busy', 'in use', 'had to wait', 'usually', '1 in 10 over', 'gave up'],
285
+ s.resources.slice(0, 12).map(r => [r.res, r.jobs, dur(r.busyMs), share(r.utilization), r.waited, r.waited ? dur(r.feltMedian) : '-', dur(r.p90Wait || 0), r.gaveUp])));
286
+ }
287
+ if (!s.agent && s.agents.length) {
288
+ out.push('', bold('By agent'), ...cols(['', 'jobs', 'ran', 'waited', 'waited > ran', 'failed', 'posts', 'ETAs met'],
289
+ s.agents.slice(0, 20).map(a => [a.who, a.jobs, dur(a.runMs), dur(a.waitMs), share(a.waitedLongerShare), share(a.failRate), a.posts, a.eta.finished ? `${a.eta.onTime}/${a.eta.finished}` : '-'])));
290
+ }
291
+ if (s.agent && s.agents[0]) {
292
+ const a = s.agents[0];
293
+ if (a.commands.length) out.push('', bold('Top commands'), ...a.commands.map(c => ` ${String(c.n).padStart(4)}x ${dur(c.ms).padStart(7)} ${c.name}`));
294
+ const codes = Object.entries(a.codes).sort((x, y) => y[1] - x[1]);
295
+ if (codes.length) out.push('', bold('Exit codes'), ` ${codes.map(([c, n]) => `${c}: ${n}`).join(', ')}`);
296
+ if (a.peakMem) out.push('', `Most memory one run used: ${(a.peakMem / 1024 ** 3).toFixed(1)} GB.`);
297
+ if (a.blockedMs) out.push(`Blocked for ${dur(a.blockedMs)} in all (from a --blocked post to the next).`);
298
+ }
299
+ const m = s.machine;
300
+ if (m.samples) out.push('', `Machine: load peaked at ${m.loadHigh?.load?.toFixed(1) ?? '?'} around ${m.loadHigh ? clock(m.loadHigh.at) : '?'}; memory got down to ${m.memLow?.memFree != null ? Math.round(m.memLow.memFree) : '?'}% free. ${m.pauses} pause${m.pauses === 1 ? '' : 's'} (${m.ownerPauses} by hand).`);
301
+ out.push('', dim('More: dibs stats --since 30d, --agent <name>, --me, --json'));
302
+ return out;
303
+ }
304
+
305
+ // dibs stats [--since 7d] [--agent <name> | --me] [--json]. With no flags it
306
+ // prints what it always has: waits against run times, today and this week.
307
+ export function stats(args, cfg) {
308
+ const o = {};
309
+ for (let i = 0; i < args.length; i++) {
310
+ const a = args[i], next = () => args[++i] ?? die(`${a} needs a value`);
311
+ if (a === '--since') o.since = next();
312
+ else if (a === '--agent') o.agent = next();
313
+ else if (a === '--me') o.me = true;
314
+ else if (a === '--json') o.json = true;
315
+ else die(`unknown ${a.startsWith('-') ? 'flag' : 'word'} ${a}. Use: dibs stats [--since 7d] [--agent <name> | --me] [--json]`);
316
+ }
317
+ if (o.me && o.agent) die('--me or --agent, not both');
318
+ if (!o.since && !o.agent && !o.me && !o.json) return plainStats(o, cfg);
319
+ const until = now(), since = until - span(o.since || '7d');
320
+ const agent = o.me ? identity().who : o.agent || null;
321
+ const s = gather({ since, until, agent });
322
+ if (o.json) {
323
+ // The old --json shape stays for whoever reads it, with everything else beside it.
324
+ const events = readEvents(until);
325
+ return console.log(JSON.stringify({ today: statsOf(events, midnight(until)), week: statsOf(events, until - 7 * DAY), ...s }, null, 1));
326
+ }
327
+ console.log(text(s).join('\n'));
328
+ }
package/src/style.mjs ADDED
@@ -0,0 +1,44 @@
1
+ // How output looks to a person at a terminal: color, and lines that fit.
2
+ // Color only when the stream is a terminal and NO_COLOR isn't set, so agents'
3
+ // logs and anything piped stay plain text. FORCE_COLOR turns it on anyway.
4
+ const colored = stream => !process.env.NO_COLOR && (!!process.env.FORCE_COLOR || (!!stream?.isTTY && process.env.TERM !== 'dumb'));
5
+ const paint = (open, close) => (s, stream = process.stdout) => (colored(stream) ? `\x1b[${open}m${s}\x1b[${close}m` : s);
6
+ export const bold = paint(1, 22);
7
+ export const dim = paint(2, 22);
8
+ // Amber is for what needs you or comes next; red only for real errors.
9
+ export const amber = paint(33, 39);
10
+ export const red = paint(31, 39);
11
+
12
+ // Nothing wider than this, even on a wide terminal: long lines are hard to read.
13
+ const MAX_WIDTH = 100;
14
+ export const width = (stream = process.stdout) => Math.min(MAX_WIDTH, stream?.columns || MAX_WIDTH);
15
+ const shown = s => s.replace(/\x1b\[\d+m/g, '').length;
16
+
17
+ // Word-wrap text to the width, keeping its own leading spaces, with `indent`
18
+ // before every line after the first.
19
+ export function wrap(text, indent = '', w = width()) {
20
+ const lead = String(text).match(/^ */)[0];
21
+ const out = [];
22
+ let line = lead;
23
+ for (const word of String(text).slice(lead.length).split(' ')) {
24
+ if (line.trim() && shown(line) + 1 + shown(word) > w) { out.push(line); line = indent + word; }
25
+ else line = line.trim() ? `${line} ${word}` : line + word;
26
+ }
27
+ out.push(line);
28
+ return out.join('\n');
29
+ }
30
+
31
+ // Two columns: a label, then lines of text that wrap under themselves. A label
32
+ // too long for the column gets a line of its own.
33
+ export function columns(rows, w = width(), most = 18) {
34
+ const col = Math.min(most, Math.max(0, ...rows.map(([k]) => shown(k)))) + 3;
35
+ const pad = ' '.repeat(col);
36
+ return rows.flatMap(([k, ...lines]) => {
37
+ const body = lines.filter(Boolean).flatMap(l => wrap(l, '', w - col).split('\n'));
38
+ if (shown(k) + 3 > col) return [k, ...body.map(b => pad + b)];
39
+ return body.map((b, i) => (i ? pad : k + ' '.repeat(col - shown(k))) + b);
40
+ });
41
+ }
42
+
43
+ // A command as someone could paste it back into a shell.
44
+ export const quoted = args => args.map(a => (/^[\w@%+=:,./-]+$/.test(a) ? a : `'${a.replace(/'/g, `'\\''`)}'`)).join(' ');