@dibssoftware/dibs 0.0.180 → 0.0.195

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 (107) hide show
  1. package/CHANGELOG.md +111 -1
  2. package/README.md +10 -8
  3. package/bin/dibs.mjs +379 -74
  4. package/docs/agents.md +303 -0
  5. package/docs/council.md +88 -0
  6. package/docs/files.md +3 -3
  7. package/docs/guard.md +86 -11
  8. package/docs/json.md +211 -0
  9. package/docs/later.md +5 -5
  10. package/docs/machines.md +6 -6
  11. package/docs/questions.md +104 -3
  12. package/docs/reference.md +124 -30
  13. package/docs/relay.md +135 -11
  14. package/docs/releasing.md +7 -1
  15. package/docs/scheduling.md +28 -6
  16. package/docs/secrets.md +53 -0
  17. package/docs/simulators.md +3 -3
  18. package/docs/windows.md +3 -3
  19. package/package.json +1 -1
  20. package/skills/dibs/SKILL.md +79 -149
  21. package/src/about.mjs +341 -0
  22. package/src/acquire.mjs +113 -28
  23. package/src/after.mjs +127 -0
  24. package/src/agents.mjs +2 -1
  25. package/src/alerts.mjs +109 -48
  26. package/src/answers.mjs +2 -2
  27. package/src/board.mjs +21 -16
  28. package/src/broker.mjs +23 -7
  29. package/src/carry.mjs +287 -0
  30. package/src/codex.mjs +132 -0
  31. package/src/commands.mjs +254 -86
  32. package/src/config.mjs +85 -14
  33. package/src/connect.mjs +4 -2
  34. package/src/cool.mjs +28 -12
  35. package/src/council.mjs +482 -0
  36. package/src/cwd.mjs +9 -0
  37. package/src/decisions.mjs +250 -0
  38. package/src/declare.mjs +96 -0
  39. package/src/diskreport.mjs +306 -0
  40. package/src/diskuse.mjs +420 -0
  41. package/src/diskwarn.mjs +68 -13
  42. package/src/doctor.mjs +149 -0
  43. package/src/doors.mjs +547 -0
  44. package/src/durable.mjs +143 -0
  45. package/src/envs.mjs +372 -0
  46. package/src/events.mjs +7 -2
  47. package/src/files.mjs +121 -7
  48. package/src/guard.mjs +288 -105
  49. package/src/guardd.mjs +8 -1
  50. package/src/halt.mjs +63 -0
  51. package/src/handoffs.mjs +362 -0
  52. package/src/history.mjs +34 -4
  53. package/src/hogs.mjs +36 -8
  54. package/src/jobprogress.mjs +283 -0
  55. package/src/later.mjs +21 -10
  56. package/src/lock.mjs +51 -11
  57. package/src/measure.mjs +60 -14
  58. package/src/media.mjs +240 -0
  59. package/src/news.mjs +31 -0
  60. package/src/notes.mjs +49 -8
  61. package/src/notices.mjs +126 -43
  62. package/src/ondemand.mjs +25 -2
  63. package/src/outcome.mjs +163 -0
  64. package/src/overlap.mjs +2 -2
  65. package/src/override.mjs +149 -79
  66. package/src/owner.mjs +15 -2
  67. package/src/people.mjs +236 -0
  68. package/src/pickup.mjs +72 -0
  69. package/src/picture.mjs +321 -0
  70. package/src/plain.mjs +84 -18
  71. package/src/platform.mjs +29 -7
  72. package/src/preempt.mjs +123 -15
  73. package/src/primer.mjs +91 -20
  74. package/src/prints.mjs +99 -0
  75. package/src/proc.mjs +11 -1
  76. package/src/progress.mjs +49 -3
  77. package/src/proof.mjs +102 -0
  78. package/src/push.mjs +271 -0
  79. package/src/questions.mjs +328 -57
  80. package/src/quota.mjs +1 -1
  81. package/src/recap.mjs +205 -0
  82. package/src/relay.mjs +262 -26
  83. package/src/remote.mjs +23 -10
  84. package/src/reviewgate.mjs +268 -0
  85. package/src/reviews.mjs +377 -0
  86. package/src/route.mjs +263 -0
  87. package/src/rules.mjs +216 -0
  88. package/src/schedule.mjs +238 -44
  89. package/src/schema.mjs +62 -0
  90. package/src/scratch.mjs +2 -2
  91. package/src/serve.mjs +3 -2
  92. package/src/service.mjs +5 -1
  93. package/src/signed.mjs +97 -0
  94. package/src/simpool.mjs +46 -1
  95. package/src/spend.mjs +375 -0
  96. package/src/state.mjs +43 -17
  97. package/src/talk.mjs +1082 -134
  98. package/src/thin.sh +2 -0
  99. package/src/trail.mjs +290 -0
  100. package/src/trailnote.mjs +209 -0
  101. package/src/util.mjs +7 -0
  102. package/src/vault.mjs +435 -0
  103. package/src/vendors.mjs +327 -0
  104. package/src/version.mjs +1 -1
  105. package/src/web.mjs +354 -60
  106. package/src/work.mjs +487 -0
  107. package/src/worker.mjs +7 -1
package/src/notices.mjs CHANGED
@@ -13,12 +13,16 @@ import path from 'node:path';
13
13
  import { paths, HOME } from './config.mjs';
14
14
  import { peek, history } from './state.mjs';
15
15
  import { notify } from './talk.mjs';
16
- import { minutes, stuckFor } from './plain.mjs';
16
+ import { minutes, stuckFor, slowText, andList } from './plain.mjs';
17
+ import { slowness, LONG_OVER } from './jobprogress.mjs';
17
18
  import { stuckLeases } from './acquire.mjs';
18
19
  import { overAskLine } from './measure.mjs';
19
20
  import { now, callerPid, clock } from './util.mjs';
20
- import { read as readPosts, tasks, QUIET_AFTER, EXPIRE_AFTER } from './progress.mjs';
21
+ import { sessionFiles } from './proc.mjs';
22
+ import { read as readPosts, tasks, QUIET_AFTER, FILE as POSTS } from './progress.mjs';
21
23
  import { quoted } from './style.mjs';
24
+ import { described } from './declare.mjs';
25
+ import { writeWhole } from './durable.mjs';
22
26
 
23
27
  // Which runs look stuck and which used more memory than they asked for is
24
28
  // decided where the board decides it (stuckLeases, l.overAsk), so the notice
@@ -29,10 +33,12 @@ export const NOTICE_EVERY = 20e3;
29
33
  let last = 0;
30
34
  const sent = new Set();
31
35
 
32
- const what = l => `#${l.id} (${l.purpose ? `"${l.purpose}", ` : ''}${(l.cmd || l.res.join(',')).slice(0, 60)})`;
36
+ const what = l => `#${l.id} ("${described(l)}"${l.cmd ? `, ${l.cmd.slice(0, 60)}` : ''})`;
33
37
 
34
- // [lease, once, text] for each notice the state holds, for the lease's agent.
35
- export function noticesIn(s, t = now()) {
38
+ // [lease, once, text, quiet] for each notice the state holds, for the lease's agent. quiet: it
39
+ // asks nothing of the agent now, so it doesn't wake a dibs listen (src/talk.mjs notify).
40
+ // hist: run history, for a job running several times its usual time (src/jobprogress.mjs).
41
+ export function noticesIn(s, t = now(), hist = []) {
36
42
  const out = [];
37
43
  const waiting = (s.queue || []).filter(q => q.pid);
38
44
  const stuck = new Set(stuckLeases({ queue: [], leases: [], ...s }, t));
@@ -40,17 +46,26 @@ export function noticesIn(s, t = now()) {
40
46
  const others = waiting.filter(q => q.res.some(r => l.res.includes(r)));
41
47
  if (stuck.has(l) && others.length)
42
48
  out.push([l, `idle:#${l.id}`, `your job ${what(l)} has used no CPU for ${minutes(stuckFor(l, t))} while ${others.length} other `
43
- + `${others.length === 1 ? 'job waits' : 'jobs wait'} for ${l.res.join(', ')}. If it's stuck, end it: stop the tool call or background task `
44
- + `running it, or kill ${l.pid} (its dibs run, which takes the whole job down and frees the turn). If it's still working, leave it.`]);
49
+ + `${others.length === 1 ? 'job waits' : 'jobs wait'} for ${l.res.join(', ')}. A job waiting on the network or another machine uses no CPU either. `
50
+ + `Ending it frees the turn: stop the tool call or background task running it, or kill ${l.pid} (its dibs run, which takes the whole job down).`]);
45
51
  if (l.overAsk?.used && l.overAsk.asked && l.overAsk.suggest)
46
- out.push([l, `mem:#${l.id}`, `your job ${what(l)}: ${overAskLine(l.overAsk)}`]);
52
+ out.push([l, `mem:#${l.id}`, `your job ${what(l)}: ${overAskLine(l.overAsk)}`, true]);
47
53
  if (l.loadPast)
48
54
  out.push([l, `loadpast:#${l.id}`, `your job ${what(l)} waited ${minutes(l.loadWaited || 0)} for the machine's load to fall, so it started anyway at background priority on the efficiency cores. `
49
- + 'It runs slower there. If a person is waiting on it now, raise it: dibs boost ' + l.id + ' high -m "why".']);
55
+ + 'It runs slower there. If a person is waiting on it now, raise it: dibs boost ' + l.id + ' high -m "why".', true]);
56
+ // Far off its own pace: the agent hears once, with who waits behind it. dibs never stops it.
57
+ const sl = slowness(l, hist, t);
58
+ if (sl) {
59
+ const behind = others.slice(0, 3).map(q => `${q.who}${q.purpose ? `'s "${described(q)}"` : ''}`);
60
+ out.push([l, `slow:#${l.id}`, `your job ${what(l)} ${slowText(sl)}`
61
+ + `${others.length ? `, while ${andList(others.length > 3 ? [...behind, `${others.length - 3} more`] : behind)} ${others.length > 1 ? 'wait' : 'waits'} behind it for ${l.res.join(', ')}` : ''}. `
62
+ + `dibs won't stop it. If it's stuck or no longer worth it, end it: stop the tool call or background task running it, or kill ${l.pid} (its dibs run). If it's working, leave it`
63
+ + `${l.progress ? '' : '; reporting progress from it (dibs progress 40%) lets dibs tell slow from stuck next time'}.`, !others.length]);
64
+ }
50
65
  const watcher = (l.pauses || []).filter(p => p.watcher && !p.gone);
51
66
  if (l.pausedAt && watcher.length)
52
67
  out.push([l, `paused:#${l.id}:${l.pausedAt}`, `your job ${what(l)} was paused because free ${watcher.some(p => p.disk) ? 'disk' : 'memory'} is low. `
53
- + "It keeps its turn and resumes by itself when there's room: don't run it again or end it."]);
68
+ + "It keeps its turn and resumes by itself when there's room: don't run it again or end it.", true]);
54
69
  }
55
70
  return out;
56
71
  }
@@ -62,78 +77,146 @@ export function noticeScan(t = now()) {
62
77
  last = t;
63
78
  try {
64
79
  const s = JSON.parse(fs.readFileSync(paths.state, 'utf8'));
65
- for (const [l, once, text] of noticesIn(s, t)) {
80
+ // History only matters to a job that has run long enough to be long (src/jobprogress.mjs LONG_OVER).
81
+ const hist = (s.leases || []).some(l => l.kind === 'run' && t - l.start > LONG_OVER) ? history() : [];
82
+ for (const [l, once, text, quiet] of noticesIn(s, t, hist)) {
66
83
  if (sent.has(once)) continue;
67
84
  sent.add(once);
68
- notify(l, once, text);
85
+ notify(l, once, text, { quiet: !!quiet });
69
86
  }
70
87
  } catch {}
71
88
  }
72
89
 
73
- // At most one nudge per task this often. On 2026-11-03, 5 of 35 notices were
74
- // these, and agents were posting progress only to stop them.
75
- export const NAG_EVERY = 2 * 36e5;
90
+ // One nudge per task, ever: on 2026-11-03, 5 of 35 notices were these, and agents
91
+ // were posting progress only to stop them; on 2026-11-28 an agent read one every 45
92
+ // minutes. Kept a day, as long as a task can stay open without a post.
93
+ export const NAG_KEEP = 864e5;
76
94
  // An agent with no job running or waiting, and none run in this long, isn't
77
95
  // working now: its open task waits quietly for it to come back.
78
96
  export const AWAY_AFTER = 30 * 6e4;
79
97
  const NAGS = path.join(HOME, 'nags.json');
80
98
 
81
- // [to, once, text, task] for each task still in progress that needs a word
99
+ // [to, once, text, task, quiet, close] for each task still in progress that needs a word
82
100
  // from whoever posted it: past its ETA, or with no post for QUIET_AFTER.
83
101
  // Expired tasks are let go. Only tasks posted from a Claude Code session: the
84
102
  // hook is how the notice arrives. A subagent's task is nudged to that subagent;
85
- // once it has ended (ended(k)), its lead hears once that it was left open.
86
- // nagged: when each task was last nudged; working(k): whether the agent the
87
- // notice would go to is at work now.
88
- export function progressNoticesIn(posts, t = now(), { nagged = {}, working = () => true, ended = () => false } = {}) {
103
+ // once it has ended (ended(k)), dibs closes the task (close: the task to close) and its
104
+ // lead hears once: it read "let go 5 hr 15 min from now" (2026-11-28), hours of an open
105
+ // task nobody would post to again.
106
+ // nagged: which tasks were nudged, and when; working(k): whether the agent the notice
107
+ // would go to has worked since its last post (a nudge on a timer alone came at 11 PM with
108
+ // nothing changed, 2026-11-28); running(k): whether a dibs job of its is running or waiting,
109
+ // which is progress the person already sees, so it isn't nudged then.
110
+ // Every nudge is quiet: it asks for a post, not for the agent to wake (src/talk.mjs notify).
111
+ export function progressNoticesIn(posts, t = now(), { nagged = {}, working = () => true, ended = () => false, running = () => false } = {}) {
89
112
  const out = [];
90
113
  for (const k of tasks(posts, t)) {
91
114
  if (k.state !== 'doing' || !k.session) continue;
92
115
  const task = `${k.who}:${k.agentId || 'main'}:${k.task || k.project}`;
93
116
  const name = k.task ? `"${k.task}"` : `in ${k.project || 'this folder'}`;
94
117
  if (k.agentId && ended(k)) {
95
- // Said once: nothing to do, it expires by itself; the lead only shouldn't be surprised.
96
118
  const lead = `${task}:lead`;
97
- if (nagged[lead] || !working({ ...k, agentId: null }) || !(k.overdue || t - k.last > QUIET_AFTER)) continue;
119
+ if (nagged[lead]) continue;
98
120
  out.push([{ sessionId: k.session, who: k.who }, `left:${task}`, `your subagent ${k.label || k.agentId.slice(0, 8)} ended with its progress task ${name} still open `
99
- + `(last post at ${clock(k.last)}). Nothing to do: it's let go ${minutes(Math.max(k.last, k.eta || 0) + EXPIRE_AFTER - t)} from now. `
100
- + `If the work goes on, post it under your own task.`, lead]);
121
+ + `(last post at ${clock(k.last)}), so dibs closed it. If the work goes on, post it under your own task.`, lead, true, k]);
101
122
  continue;
102
123
  }
103
- if (t - (nagged[task] || 0) < NAG_EVERY || !working(k)) continue;
124
+ // A post this recent is fresh, even past its ETA: the agent just said where it stands.
125
+ if (nagged[task] || t - k.last <= QUIET_AFTER || running(k) || !working(k)) continue;
104
126
  const to = { sessionId: k.session, who: k.who, ...(k.agentId && { agentId: k.agentId }) };
105
127
  const again = (...more) => quoted(['dibs', 'progress', 'where it stands', ...(k.task ? ['--task', k.task] : []), ...more]);
106
128
  if (k.overdue) out.push([to, `late:${task}:${k.eta}`, `your progress task ${name} was due at ${clock(k.eta)} and is still open. `
107
- + `If it's finished, say so: ${again('--done')}. If not, post where it stands with a new time: ${again('--eta', '30m')}.`, task]);
108
- else if (t - k.last > QUIET_AFTER) out.push([to, `quiet:${task}:${k.last}`, `your progress task ${name} has had no post for ${minutes(t - k.last)}. `
109
- + `Post where it stands (${again()}), or close it: --done if it's finished, --blocked if it's stuck.`, task]);
129
+ + `If it's finished, say so: ${again('--done')}. If not, post where it stands with a new time: ${again('--eta', '30m')}.`, task, true]);
130
+ else out.push([to, `quiet:${task}:${k.last}`, `your progress task ${name} has had no post for ${minutes(t - k.last)}. `
131
+ + `Post where it stands (${again()}), or close it: --done if it's finished, --blocked if it's stuck.`, task, true]);
110
132
  }
111
133
  return out;
112
134
  }
113
135
 
114
136
  const DAY = 864e5;
137
+ // A session's or subagent's dibs job running or waiting now. A subagent counts only its own
138
+ // jobs (they carry its id); a main agent counts any of its session's, or any under its name.
139
+ function runningIn(s) {
140
+ const mine = k => x => x.sessionId === k.session && (k.agentId ? x.agentId === k.agentId : true);
141
+ return k => (s.leases || []).some(mine(k)) || (s.queue || []).some(q => q.pid && mine(k)(q)) || (!k.agentId && (s.leases || []).some(l => l.who === k.who));
142
+ }
143
+ const readNags = () => { try { return JSON.parse(fs.readFileSync(NAGS, 'utf8')); } catch { return {}; } };
144
+ // Each nudge is remembered a day, so a watcher restart can't repeat it.
145
+ function writeNags(nagged, before, t) {
146
+ for (const [k, at] of Object.entries(nagged)) if (t - at >= NAG_KEEP) delete nagged[k];
147
+ if (JSON.stringify(nagged) !== before) writeWhole(NAGS, JSON.stringify(nagged));
148
+ }
149
+ // A subagent's open task closed under dibs's name, so the page and phones stop showing it in progress.
150
+ function closeTask(k, t) {
151
+ const p = { at: t, who: k.who, ...(k.label && { label: k.label }), session: k.session, agentId: k.agentId, ...(k.project && { project: k.project }),
152
+ ...(k.task && { task: k.task }), state: 'done', by: 'dibs', text: `closed by dibs: its subagent ended with it open (last post at ${clock(k.last)}).` };
153
+ fs.appendFileSync(POSTS, `${JSON.stringify(p)}\n`);
154
+ }
155
+
115
156
  // From the throttle watcher (src/cool.mjs), which is always running: no waiter needed.
116
- export function progressScan(t = now()) {
157
+ export async function progressScan(t = now()) {
117
158
  try {
118
- let nagged = {};
119
- try { nagged = JSON.parse(fs.readFileSync(NAGS, 'utf8')); } catch {}
159
+ const nagged = readNags();
120
160
  const s = peek(), hist = history();
121
- // At work: a job running or waiting, or one run in the last AWAY_AFTER. A
122
- // subagent counts only its own jobs (they carry its id) and its own posts.
123
- const mine = k => x => x.sessionId === k.session && (k.agentId ? x.agentId === k.agentId : true);
124
- const busy = k => (s.leases || []).some(mine(k)) || (s.queue || []).some(q => q.pid && mine(k)(q));
125
- const working = k => (k.agentId ? busy(k) || t - k.last < AWAY_AFTER
126
- : busy(k) || (s.leases || []).some(l => l.who === k.who) || hist.some(r => r.who === k.who && t - r.at < AWAY_AFTER));
127
- const ended = k => !busy(k) && t - k.last >= AWAY_AFTER;
161
+ const running = runningIn(s);
162
+ // At work since its last post: a tool call since then in the last AT_WORK (its transcript), or for
163
+ // a main agent a dibs job run since then in the last AWAY_AFTER (history doesn't say which subagent).
164
+ const { about, workFor } = await import('./about.mjs');
165
+ const toolAt = k => workFor(k.session, k.agentId || 'main')?.tool?.at || 0;
166
+ const working = k => (!k.agentId && hist.some(r => r.who === k.who && r.at > k.last && t - r.at < AWAY_AFTER))
167
+ || (toolAt(k) > k.last && t - toolAt(k) < AT_WORK);
168
+ // Ended: Claude Code marked the subagent finished, or it has no job and no post in AWAY_AFTER.
169
+ const ended = k => !running(k) && (t - k.last >= AWAY_AFTER || about(k.session, k.agentId)?.finished === true);
128
170
  const before = JSON.stringify(nagged);
129
- for (const [to, once, text, task] of progressNoticesIn(readPosts({ since: t - DAY }), t, { nagged, working, ended })) {
171
+ for (const [to, once, text, task, quiet, close] of progressNoticesIn(readPosts({ since: t - DAY }), t, { nagged, working, ended, running })) {
130
172
  if (sent.has(once)) continue;
131
173
  sent.add(once);
132
- if (notify(to, once, text)) nagged[task] = t;
174
+ if (close) closeTask(close, t);
175
+ // The closing is what matters: it's remembered even when the lead's notice couldn't be left.
176
+ if (notify(to, once, text, { quiet: !!quiet }) || close) nagged[task] = t;
133
177
  }
134
- // A lead's one word about a subagent's task is kept as long as the task can be: never twice.
135
- for (const [k, at] of Object.entries(nagged)) if (t - at >= (k.endsWith(':lead') ? DAY : NAG_EVERY)) delete nagged[k];
136
- if (JSON.stringify(nagged) !== before) fs.writeFileSync(NAGS, JSON.stringify(nagged));
178
+ writeNags(nagged, before, t);
179
+ } catch {}
180
+ }
181
+
182
+ // An agent at work this long on the person's newest prompt, with no progress post and no plan
183
+ // since, hears once how to say what it's doing: the person's screens show its plan and posts,
184
+ // and without them only "No update for 20 min" (src/picture.mjs). Once per session: told how,
185
+ // it knows, and telling it again at every prompt is the nag agents learn to skip.
186
+ export const UNSAID_AFTER = 20 * 6e4;
187
+ // At work: a tool call this recent.
188
+ const AT_WORK = 5 * 6e4;
189
+ // [to, once, text, key] for each Claude Code session that should hear it. sessions: sessionFiles()
190
+ // still running; workOf(sessionId): its transcript's work (src/about.mjs workFor); posts: the day's;
191
+ // running(sessionId): a dibs job of the session's running or waiting, which the person already sees.
192
+ export function unsaidNoticesIn(sessions, workOf, posts, t = now(), nagged = {}, running = () => false) {
193
+ const out = [];
194
+ for (const f of sessions) {
195
+ const key = `unsaid:${f.sessionId}`;
196
+ if (nagged[key] || running(f.sessionId)) continue;
197
+ const w = workOf(f.sessionId);
198
+ const from = w?.prompt;
199
+ if (!from || !w.tool?.at || t - w.tool.at > AT_WORK || w.tool.at < from || t - from < UNSAID_AFTER) continue;
200
+ if (w.plan && (w.plan.at || 0) >= from) continue;
201
+ // A post since the prompt, or one still fresh from before it.
202
+ if (posts.some(p => p.session === f.sessionId && !p.agentId && (p.at >= from || t - p.at <= QUIET_AFTER))) continue;
203
+ out.push([{ sessionId: f.sessionId, who: f.name }, `${key}:${from}`, `you've been at work for ${minutes(t - from)} and the person can't see on what: `
204
+ + 'no progress post and no plan since their last message. Post what you\'re doing: dibs progress "..." --task <name> (now, then as it moves).', key]);
205
+ }
206
+ return out;
207
+ }
208
+
209
+ // From the throttle watcher, beside progressScan. Reads transcripts, so it's loaded only here.
210
+ export async function unsaidScan(t = now()) {
211
+ try {
212
+ const { workFor } = await import('./about.mjs');
213
+ const nagged = readNags(), before = JSON.stringify(nagged);
214
+ const s = peek();
215
+ const busy = id => (s.leases || []).some(l => l.sessionId === id) || (s.queue || []).some(q => q.pid && q.sessionId === id);
216
+ const alive = pid => { try { process.kill(pid, 0); return true; } catch (e) { return e.code === 'EPERM'; } };
217
+ const found = unsaidNoticesIn(sessionFiles().filter(f => alive(f.pid)), id => workFor(id, 'main'), readPosts({ since: t - DAY }), t, nagged, busy);
218
+ for (const [to, once, text, key] of found) if (!sent.has(once) && notify(to, once, text, { quiet: true })) { sent.add(once); nagged[key] = t; }
219
+ writeNags(nagged, before, t);
137
220
  } catch {}
138
221
  }
139
222
 
package/src/ondemand.mjs CHANGED
@@ -31,6 +31,7 @@ import { fileURLToPath } from 'node:url';
31
31
  import { HOME } from './config.mjs';
32
32
  import { event } from './events.mjs';
33
33
  import { ms, now, log } from './util.mjs';
34
+ import { recordFor } from './spend.mjs';
34
35
  import { VERSION } from './version.mjs';
35
36
 
36
37
  const ROOT = path.join(path.dirname(fileURLToPath(import.meta.url)), '..');
@@ -73,11 +74,25 @@ export function ondemandOf(cfg) {
73
74
  if (typeof m.registry !== 'string' || !m.registry) throw new Error(`${at}: registry is the file that says who owns which VM, like "~/boat/VMS.md"`);
74
75
  if (typeof m.match !== 'string' || !m.match.trim()) throw new Error(`${at}: match is a word in the Use column of this VM's row, like "dibs"`);
75
76
  if (m.create != null && !SIZES[m.create?.max]) throw new Error(`${at}: create is { "max": "small" }, "default" or "large": the biggest VM dibs may make for a job bigger than this one`);
77
+ if (m.perHour != null && !perHourOk(m.perHour)) throw new Error(`${at}: perHour is what an hour of it costs, like 0.12, or one price per size: { "small": 0.06, "default": 0.12, "large": 0.24 }`);
76
78
  return { name: m.name, provider: m.provider, registry: m.registry.replace(/^~(?=\/)/, os.homedir()), match: m.match.trim(), owner: m.owner || null,
77
- idleStop: idleStopOf(m.idleStop, at), cores: m.cores ?? 4, memTotal: m.mem ? Number(m.mem) : 8 * 1024 ** 3, create: m.create ? { max: m.create.max } : null };
79
+ idleStop: idleStopOf(m.idleStop, at), cores: m.cores ?? 4, memTotal: m.mem ? Number(m.mem) : 8 * 1024 ** 3, create: m.create ? { max: m.create.max } : null,
80
+ ...(m.perHour != null && { perHour: m.perHour }) };
78
81
  });
79
82
  }
80
83
 
84
+ // What an hour costs, from config: one price, or one per boat size. Prices are dollars.
85
+ const perHourOk = p => (typeof p === 'number' ? p >= 0 : p && typeof p === 'object' && Object.entries(p).every(([k, v]) => SIZES[k] && typeof v === 'number' && v >= 0));
86
+ // The price of an hour of this VM, or null when config doesn't say. A temporary VM is the size it
87
+ // was made in; the dedicated one, the size its cores say.
88
+ export function hourly(vm) {
89
+ const p = vm.perHour;
90
+ if (typeof p === 'number') return p;
91
+ if (!p) return null;
92
+ const size = vm.type || Object.keys(SIZES).find(k => SIZES[k].cores === vm.cores);
93
+ return p[size] ?? null;
94
+ }
95
+
81
96
  // How long it may sit idle before it's stopped. Every idle second is billed:
82
97
  // 30s by default (enough for a script's next job to follow its last), 3m at most.
83
98
  const IDLE_DEFAULT = 30e3, IDLE_MAX = 3 * 6e4;
@@ -346,6 +361,7 @@ export function ondemand(list, srv, { port, tick = TICK, log: say = log, clock =
346
361
  notes: `Created ${hhmm()} by dibs (${type}); dibs deletes it, and this row, when its jobs end` });
347
362
  Object.assign(w, { cores: SIZES[type].cores, memTotal: SIZES[type].mem });
348
363
  vm.cantWake = null;
364
+ vm.type = type;
349
365
  event({ kind: 'ondemand', act: 'create', name: vm.name, id, type, ms: vm.resumeMs });
350
366
  return { id };
351
367
  };
@@ -434,7 +450,14 @@ export function ondemand(list, srv, { port, tick = TICK, log: say = log, clock =
434
450
  if (r.code) say(`${vm.name}: boat stop failed (${r.err}). Its own auto-stop still ends it within the hour.`);
435
451
  else noteVm(vm, vm.id, `Stopped ${hhmm()} by dibs (${why})`);
436
452
  }
437
- event({ kind: 'ondemand', act: vm.temp ? 'delete' : 'stop', name: vm.name, id: vm.id, why, billed: vm.upSince ? Math.round((now() - vm.upSince) / 1000) : null, ok: !r.code });
453
+ const billed = vm.upSince ? Math.round((now() - vm.upSince) / 1000) : null;
454
+ event({ kind: 'ondemand', act: vm.temp ? 'delete' : 'stop', name: vm.name, id: vm.id, why, billed, ok: !r.code });
455
+ // Every second it ran was billed: into the spend ledger, when config says what an hour costs.
456
+ const rate = hourly(vm);
457
+ if (billed && rate != null) {
458
+ const amount = Math.round(billed / 3600 * rate * 100);
459
+ if (amount > 0) recordFor('dibs', { amount, on: 'boat', note: `${vm.name}${vm.type ? ` (${vm.type})` : ''} up ${Math.round(billed / 60)}m${vm.id ? `, ${vm.id}` : ''}` });
460
+ }
438
461
  const w = workers.get(vm.name);
439
462
  if (w) Object.assign(w, { running: [], busy: {}, seen: 0, lost: false }, vm.temp ? { cores: vm.cores, memTotal: vm.memTotal } : {});
440
463
  Object.assign(vm, { upSince: null, idleSince: null, waitingSince: null, extended: 0 }, vm.temp ? { id: null } : {});
@@ -0,0 +1,163 @@
1
+ // What a finished run meant, in one sentence the person reads instead of a command line:
2
+ // "Tests pass, 212 of 212", "Build failed in Login.swift: cannot find 'Session' in scope".
3
+ // Plain parsers over the end of a run's output, as its agent's transcript kept it (dibs run
4
+ // leaves stdout and stderr to the agent, so dibs never stores output itself). Nothing here
5
+ // guesses: an output no parser knows gives null, and the caller falls back to the agent's own
6
+ // words or the run's -m.
7
+ import path from 'node:path';
8
+ import { masked } from './util.mjs';
9
+
10
+ // The end of the output holds every summary line these tools print; a 2 MB log's start never matters.
11
+ export const OUTPUT_READ = 64 * 1024;
12
+ // An error message as it reaches a phone: the compiler's line, cut.
13
+ const ERROR_SHOWN = 120;
14
+ // A failing test's name, cut.
15
+ const NAME_SHOWN = 60;
16
+
17
+ const cut = (s, n) => { const x = String(s).replace(/\s+/g, ' ').trim(); return x.length > n ? `${x.slice(0, n - 3).trimEnd()}...` : x; };
18
+ // Token-shaped words never leave the Mac, in a sentence any more than in a command.
19
+ const clean = (s, n) => cut(masked(String(s)).replace(/\b[A-Za-z0-9_-]{32,}\b/g, '***'), n);
20
+ const ESC = /\u001b\[[0-9;?]*[A-Za-z]/g;
21
+ const last = (text, re) => { let m = null; for (const x of text.matchAll(re)) m = x; return m; };
22
+ const num = x => Number(String(x).replace(/,/g, ''));
23
+
24
+ // "3 of 212 tests fail: expired token login, and 2 more"
25
+ function failing(failed, total, names, noun = 'tests') {
26
+ const first = names.find(Boolean);
27
+ const verb = failed === 1 ? `${noun.replace(/s$/, '')} fails` : `${noun} fail`;
28
+ const more = failed > 1 ? `, and ${failed - 1} more` : '';
29
+ return `${failed} of ${total} ${verb}${first ? `: ${clean(first, NAME_SHOWN)}${more}` : ''}`;
30
+ }
31
+ const passing = (n, noun = 'Tests') => `${noun} pass, ${n} of ${n}`;
32
+
33
+ // The first compiler error: "path:12:5: error: message".
34
+ function compileError(text) {
35
+ const m = /^(\S[^\n:]*?\.[A-Za-z]+):\d+(?::\d+)?:\s*(?:fatal )?error:\s*(.+)$/m.exec(text);
36
+ return m && { file: path.basename(m[1]), msg: m[2] };
37
+ }
38
+
39
+ // Each parser takes the output (colours stripped) and the exit code; returns { text, ok } or null.
40
+ const PARSERS = [
41
+ // node:test, TAP ("# pass 212") or the spec reporter ("ℹ pass 212").
42
+ t => {
43
+ const pass = last(t, /^(?:#|ℹ) pass (\d+)\s*$/gm), fail = last(t, /^(?:#|ℹ) fail (\d+)\s*$/gm);
44
+ if (!pass || !fail) return null;
45
+ const p = num(pass[1]), f = num(fail[1]);
46
+ if (!f) return { text: passing(p), ok: true };
47
+ const names = [...t.matchAll(/^\s*not ok \d+ - (.+?)\s*(?:#.*)?$/gm)].map(m => m[1])
48
+ .concat([...t.matchAll(/^\s*✖ (.+?)(?: \([\d.]+m?s\))?\s*$/gm)].map(m => m[1]).filter(n => !/^failing tests:?$/.test(n)));
49
+ return { text: failing(f, p + f, names), ok: false };
50
+ },
51
+ // Jest: "Tests: 2 failed, 210 passed, 212 total"
52
+ t => {
53
+ const m = last(t, /^Tests:\s+(.*?)(\d+) total\s*$/gm);
54
+ if (!m) return null;
55
+ const f = num(/(\d+) failed/.exec(m[1])?.[1] || 0), total = num(m[2]);
56
+ if (!f) return { text: passing(num(/(\d+) passed/.exec(m[1])?.[1] || total)), ok: true };
57
+ const names = [...t.matchAll(/^\s*● (.+?)\s*$/gm)].map(x => x[1].split(' › ').at(-1));
58
+ return { text: failing(f, total, names), ok: false };
59
+ },
60
+ // Vitest: " Tests 2 failed | 210 passed (212)"
61
+ t => {
62
+ const m = last(t, /^\s*Tests\s+(.*?)\((\d+)\)\s*$/gm);
63
+ if (!m || !/passed|failed/.test(m[1])) return null;
64
+ const f = num(/(\d+) failed/.exec(m[1])?.[1] || 0), total = num(m[2]);
65
+ if (!f) return { text: passing(total), ok: true };
66
+ const names = [...t.matchAll(/^\s*(?:FAIL|×|✗)\s+\S+\s+>\s+(.+?)\s*$/gm)].map(x => x[1].split(' > ').at(-1));
67
+ return { text: failing(f, total, names), ok: false };
68
+ },
69
+ // pytest: "==== 2 failed, 210 passed, 1 skipped in 3.20s ===="
70
+ t => {
71
+ const m = last(t, /^=+ (.*?\b(?:passed|failed)\b.*?) in [\d.]+s(?: \([^)]*\))? =+\s*$/gm);
72
+ if (!m) return null;
73
+ const p = num(/(\d+) passed/.exec(m[1])?.[1] || 0), f = num(/(\d+) failed/.exec(m[1])?.[1] || 0) + num(/(\d+) errors?/.exec(m[1])?.[1] || 0);
74
+ if (!f) return { text: passing(p), ok: true };
75
+ const names = [...t.matchAll(/^(?:FAILED|ERROR) \S+?::(\S+)/gm)].map(x => x[1]);
76
+ return { text: failing(f, p + f, names), ok: false };
77
+ },
78
+ // Playwright: " 12 passed (41s)" and " 2 failed"
79
+ t => {
80
+ const p = last(t, /^\s+(\d+) passed \([\d.]+m?s\)\s*$/gm);
81
+ const f = last(t, /^\s+(\d+) failed\s*$/gm);
82
+ if (!p && !f) return null;
83
+ const pn = p ? num(p[1]) : 0, fn = f ? num(f[1]) : 0;
84
+ if (!fn) return { text: passing(pn, 'Browser tests'), ok: true };
85
+ const names = [...t.matchAll(/^\s+\d+\) \[[^\]]+\] › .*? › (.+?)\s*(?:─|$)/gm)].map(x => x[1]);
86
+ return { text: `Browser tests: ${failing(fn, pn + fn, names)}`, ok: false };
87
+ },
88
+ // cargo: "test result: ok. 31 passed; 0 failed; ..." (one per test binary)
89
+ t => {
90
+ const rs = [...t.matchAll(/^test result: (ok|FAILED)\. (\d+) passed; (\d+) failed;/gm)];
91
+ if (!rs.length) return null;
92
+ const p = rs.reduce((n, m) => n + num(m[2]), 0), f = rs.reduce((n, m) => n + num(m[3]), 0);
93
+ if (!f) return { text: passing(p), ok: true };
94
+ const names = [...t.matchAll(/^test (\S+) \.\.\. FAILED$/gm)].map(x => x[1]);
95
+ return { text: failing(f, p + f, names), ok: false };
96
+ },
97
+ // go test: "--- FAIL: TestLogin", "ok example.com/pkg 0.3s", "FAIL example.com/pkg"
98
+ t => {
99
+ const fails = [...t.matchAll(/^\s*--- FAIL: (\S+)/gm)].map(x => x[1]);
100
+ const oks = [...t.matchAll(/^ok\s+\S+\s+(?:[\d.]+s|\(cached\))/gm)].length;
101
+ const failedPkgs = [...t.matchAll(/^FAIL\s+\S+\s+[\d.]+s/gm)].length;
102
+ if (!fails.length && !oks && !failedPkgs) return null;
103
+ if (!fails.length && !failedPkgs) return { text: `Tests pass in ${oks} package${oks === 1 ? '' : 's'}`, ok: true };
104
+ const n = fails.length || failedPkgs;
105
+ return { text: `${n} ${fails.length ? `test${n === 1 ? '' : 's'}` : `package${n === 1 ? '' : 's'}`} fail${n === 1 ? 's' : ''}${fails[0] ? `: ${clean(fails[0], NAME_SHOWN)}${n > 1 ? `, and ${n - 1} more` : ''}` : ''}`, ok: false };
106
+ },
107
+ // XCTest: "Executed 48 tests, with 0 failures (0 unexpected) in 2.1 (2.2) seconds"
108
+ t => {
109
+ const m = last(t, /Executed (\d+) tests?, with (\d+) failures?/g);
110
+ if (!m) return null;
111
+ const total = num(m[1]), f = num(m[2]);
112
+ if (!f) return { text: passing(total), ok: true };
113
+ const names = [...t.matchAll(/Test Case '-\[\S+ (\w+)\]' failed/g)].map(x => x[1]);
114
+ return { text: failing(f, total, names), ok: false };
115
+ },
116
+ // Swift Testing: "Test run with 12 tests passed after 0.5 seconds." / "... failed after ... with 2 issues."
117
+ t => {
118
+ const m = last(t, /Test run with (\d+) tests?(?: in \d+ suites?)? (passed|failed) after [\d.]+ seconds(?: with (\d+) issues?)?/g);
119
+ if (!m) return null;
120
+ if (m[2] === 'passed') return { text: passing(num(m[1])), ok: true };
121
+ const names = [...t.matchAll(/Test (\w+)\(\) (?:recorded an issue|failed)/g)].map(x => x[1]);
122
+ return { text: `Tests fail${m[3] ? ` with ${m[3]} issue${m[3] === '1' ? '' : 's'}` : ''}${names[0] ? `: ${clean(names[0], NAME_SHOWN)}` : ''}`, ok: false };
123
+ },
124
+ // tsc: "Found 3 errors in 2 files." and the first "api.ts(12,5): error TS2304: ..." or "api.ts:12:5 - error TS2304: ..."
125
+ t => {
126
+ const found = last(t, /^Found (\d+) errors?\b/gm);
127
+ const first = /^(\S+?)(?:\(\d+,\d+\)|:\d+:\d+)\s*[-:]\s*error TS\d+:\s*(.+)$/m.exec(t);
128
+ if (!found && !first) return null;
129
+ const n = found ? num(found[1]) : 1;
130
+ return { text: `Type check failed${first ? ` in ${path.basename(first[1])}` : ''}: ${n} error${n === 1 ? '' : 's'}${first ? `, first: ${clean(first[2], ERROR_SHOWN)}` : ''}`, ok: false };
131
+ },
132
+ // xcodebuild's own verdict, and the first compiler error behind a failed one.
133
+ (t, code) => {
134
+ const won = last(t, /\*\* (BUILD|ARCHIVE|TEST) (SUCCEEDED|FAILED) \*\*/g);
135
+ const err = code !== 0 ? compileError(t) : null;
136
+ if (!won && !err) return null;
137
+ const what = won?.[1] === 'ARCHIVE' ? 'Archive' : won?.[1] === 'TEST' ? 'Tests' : 'Build';
138
+ if (won && won[2] === 'SUCCEEDED' && code === 0) return { text: what === 'Tests' ? 'Tests pass' : `${what} worked`, ok: true };
139
+ return { text: `${what === 'Tests' ? 'Tests failed' : `${what} failed`}${err ? ` in ${err.file}: ${clean(err.msg, ERROR_SHOWN)}` : ''}`, ok: false };
140
+ },
141
+ ];
142
+
143
+ // The sentence for one run's output, or null when no parser knows it. code: the run's exit code.
144
+ export function outcomeOf(output, code = null) {
145
+ if (typeof output !== 'string' || !output) return null;
146
+ const t = output.slice(-OUTPUT_READ).replace(ESC, '').replace(/\r/g, '');
147
+ for (const p of PARSERS) {
148
+ const r = p(t, code);
149
+ if (r) return r;
150
+ }
151
+ return null;
152
+ }
153
+
154
+ // The first sentence of something an agent wrote, if it's one line a person can read at a
155
+ // glance: under max characters, ending in a period (or ! or ?). Markdown marks go.
156
+ export function firstSentence(text, max = 140) {
157
+ // Its first line: a list or a second paragraph after it is more than a glance.
158
+ const first = String(text || '').replace(/```[\s\S]*?```/g, '\n').split('\n').map(x => x.trim()).find(Boolean) || '';
159
+ const plain = first.replace(/[*_`#>]+/g, '').replace(/\s+/g, ' ').trim();
160
+ const m = /^(.+?[.!?])(?:\s|$)/.exec(plain);
161
+ if (!m || m[1].length >= max || m[1].length < 3) return null;
162
+ return m[1];
163
+ }
package/src/overlap.mjs CHANGED
@@ -25,7 +25,7 @@
25
25
  //
26
26
  // config.overlap: off, fit or squeeze. loadConfig sets it from the pace when
27
27
  // the file doesn't (quiet off, normal fit, max squeeze; no pace, off).
28
- import { resCfg, machine, hardware } from './config.mjs';
28
+ import { resCfg, machine, hardware, isEnv } from './config.mjs';
29
29
  import { tag } from './proc.mjs';
30
30
  import { isFiles } from './files.mjs';
31
31
  import { isQuota } from './quota.mjs';
@@ -75,7 +75,7 @@ export const overlapMode = cfg => cfg.overlap || 'off';
75
75
  // One at a time, whatever the machine has free. A name dibs doesn't know is
76
76
  // one unless the config's unknown says exclusive: false.
77
77
  export function exclusive(cfg, r) {
78
- if (isFiles(r) || isQuota(r)) return true;
78
+ if (isFiles(r) || isQuota(r) || isEnv(r)) return true;
79
79
  const c = resCfg(cfg, r);
80
80
  if (c.pool || c.onRelease) return true;
81
81
  // resCfg fills a configured resource's gaps from unknown, so read its own config here.