@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/bin/dibs.mjs ADDED
@@ -0,0 +1,526 @@
1
+ #!/bin/sh
2
+ ":" //; case "$1" in run|hold) [ "${DIBS_THIN:-}" != 0 ] && ! grep -qsE '"waits"[[:space:]]*:[[:space:]]*"(fat|node)"' "${DIBS_HOME:-$HOME/.dibs}/config.json" && ! { grep -qs '"leases": \[\]' "${DIBS_HOME:-$HOME/.dibs}/state.json" && grep -qs '"queue": \[\]' "${DIBS_HOME:-$HOME/.dibs}/state.json"; } && { f=$0; while [ -L "$f" ]; do l=$(readlink "$f"); case $l in /*) f=$l;; *) f=${f%/*}/$l;; esac; done; exec /bin/sh "${f%/*}/../src/thin.sh" "$f" "$@"; };; esac; exec node --max-semi-space-size=1 "$0" "$@"
3
+ // Line 2 is read by sh and ignored by Node (a string, then a comment). sh
4
+ // sends run and hold to src/thin.sh unless config.json says "waits": "fat"
5
+ // (or "node") or DIBS_THIN=0 is set, and everything else to Node, as before.
6
+ // With nothing held and nobody in line it goes straight to Node too: a thin
7
+ // wait starts Node twice (to get in line, then to run), 75 ms more, for a wait
8
+ // that won't happen.
9
+ // dibs: take turns on shared machine resources so parallel agents stop colliding.
10
+ import fs from 'node:fs';
11
+ import path from 'node:path';
12
+ import { fileURLToPath } from 'node:url';
13
+ import { loadConfig, paths, profiled } from '../src/config.mjs';
14
+ import { identity } from '../src/proc.mjs';
15
+ import { PRIORITY_SHIFT, PRIORITIES, priority } from '../src/schedule.mjs';
16
+ import { VERSION } from '../src/version.mjs';
17
+ import { run, notifyOnExit, hold, release, when, why, mine, who, yieldTo, ask, requests, status, freePort, pace, checkNames, nearest } from '../src/commands.mjs';
18
+ import { remoteRun, join, machines } from '../src/remote.mjs';
19
+ import { sims } from '../src/simpool.mjs';
20
+ import { question, questions, answer, hoursCmd } from '../src/questions.mjs';
21
+ import { say, tell, threads, noticesFor } from '../src/talk.mjs';
22
+ import { bytes, ms, deadline, die, noSpace, fullDisk, setCaller, lastDie, lastDieCode } from '../src/util.mjs';
23
+ import { event } from '../src/events.mjs';
24
+ import { fileRes, isFiles, resList } from '../src/files.mjs';
25
+ import { boost, pause, resume, stop, cap } from '../src/override.mjs';
26
+ import { later } from '../src/later.mjs';
27
+ import { isQuota } from '../src/quota.mjs';
28
+
29
+ // Commands no waiting or running dibs needs load when called: a waiter is a
30
+ // long-lived process, and each module it never uses costs it memory.
31
+ const lazy = name => import(`../src/${name}.mjs`);
32
+
33
+ const ROOT = path.join(path.dirname(fileURLToPath(import.meta.url)), '..');
34
+
35
+ const HELP = `dibs ${VERSION}: agents take turns on this machine's simulator, builds, test runs and deploys.
36
+
37
+ Wait your turn
38
+ dibs run test -m "why" -- npm test wait for a turn, run, give it back when it exits
39
+ dibs run sim,xcode-build -- <command> need two things? ask for both at once
40
+ dibs hold sim --for 20m -m "why" keep it across several commands, each still in dibs run sim -- <cmd>
41
+ (no wait under your hold); give it back: dibs release sim
42
+ dibs hold 'files:src/auth/**' -m "why" keep other agents' edits off these files
43
+ dibs run test --anywhere -- <command> on whichever machine in the group starts it soonest (--on <machine>: that one)
44
+
45
+ Tell the person
46
+ dibs progress "what you did or found" --task <name> --eta 30m as often as you commit; then --blocked or --done
47
+ dibs question "Ship 123 now?" --options yes,no --recommend yes -m why --one-way "testers get it at once"
48
+ only one-way doors reach the person; the same command plus --wait reads the answer
49
+ dibs say "done: tests pass" an FYI in your thread, no question
50
+
51
+ Look around
52
+ dibs what each resource is doing and who's next
53
+ dibs why where you are in the queue and what you're waiting for
54
+ dibs when sim when you'd get it, without joining the queue
55
+ dibs who sim | dibs mine | dibs history who has it, what you have (exit 1: nothing), what happened this week
56
+ dibs yield web-app let another agent go first
57
+
58
+ Set up
59
+ dibs pace quiet|normal|max how hard dibs drives this machine
60
+ dibs guard install make Claude Code agents use dibs when they forget
61
+ dibs machines other machines in the group
62
+
63
+ Priority: -p urgent|high|normal|low|idle (urgent and high need -m "why"). Due by a time: --by 23:30.
64
+ Exit 75: your command never ran (you gave up waiting) and didn't fail. Run the same command again within 2 minutes.
65
+ Everything else: dibs help all`;
66
+
67
+ const LATER_HELP = `run it later
68
+ dibs later <res> --at 02:00 -- <cmd> schedule a run for a time (at most 7 days out); returns at once with its id
69
+ dibs later <res> --in 3h -- <cmd> ...or a while from now
70
+ dibs later <res> --after <what> -- <cmd> ...or when something ends: #42 on the board, an agent (web-app, or web-app:deploy
71
+ for its deploy), or an earlier later job (l3). --after-ok: only if it succeeded
72
+ When due, it runs as dibs run --wait with your flags, in this folder, with PATH,
73
+ HOME and LANG (more with --env NAME). Output: ~/.dibs/later/<id>.log
74
+ dibs later list [--json] scheduled, waiting, running, and how the finished ones ended
75
+ dibs later cancel <id> drop it, or stop it if it's running`;
76
+
77
+ const HELP_ALL = `dibs ${VERSION}: take turns on shared machine resources.
78
+
79
+ get a turn
80
+ dibs run <res>[,<res>] [flags] -- <cmd> wait for the resources, run cmd, release when it exits
81
+ dibs run <res> --after #42 -- <cmd> ...but join the line only once job #42 has ended
82
+ dibs hold <res> [--for 20m] keep a resource across several tool calls (max 1h); again to extend
83
+ dibs release [<res>] give back your holds
84
+ dibs hold 'files:src/auth/**' -m "why" keep other agents' edits off these paths (from the git root; * ** ?; quote it)
85
+
86
+ ask without joining the queue
87
+ dibs [--detail] the board: what each resource is doing and who's next (--detail: ids and numbers)
88
+ dibs who <res> who holds it, until when, who's next
89
+ dibs when <res>[,<res>] when you'd get it if you asked now
90
+ dibs why [--detail] why you're waiting, in sentences (--detail: how your place was worked out)
91
+ dibs mine [<res>] what you hold and wait for (exit 1 if nothing: "do I hold sim?")
92
+ dibs alerts [--json] [--all] what's wrong, each with its fix: long waits, memory holding work back, stuck or failed
93
+ jobs, dibs's services and hook, a full disk. dibs alerts dismiss <id|all> closes one for a day
94
+ dibs history [--since 7d] [--json] what happened: busy time, waits and who waited, by resource, agent and hour
95
+ dibs stats [--json] waits against run times, today and the last 7 days: median and 90% by resource
96
+ dibs stats --me | --agent <name> [--since 30d] [--json]
97
+ per agent and resource: run and wait time, failures by exit code, what held
98
+ jobs back, top commands, ETAs met, the machine's load and memory over time
99
+
100
+ ${LATER_HELP}
101
+
102
+ work with other agents
103
+ dibs yield <agent> [<res>] let another agent go first (and release your hold on what they need)
104
+ dibs ask "..." send a request or bug report to whoever maintains dibs
105
+
106
+ ask the person (one-way doors only)
107
+ dibs question "..." --recommend <option> -m why [--options a,b] [--one-way "what can't be undone"] [--wait]
108
+ without --one-way: decided at once with your recommendation (printed on
109
+ stdout, logged, shown to the person as done). With it: queued for the person;
110
+ --wait prints only the answer; --timeout 1m caps the wait (exit 75: no answer
111
+ by then, or dismissed; a question asked first without --wait stays open for the person)
112
+ dibs questions [--json] open questions first, by priority then age
113
+ dibs answer <id> <text> answer one with an option or any words (words reach the asker as a message too)
114
+ dibs questions dismiss <id> dismiss one; its waiting agent gets exit 75
115
+ dibs hours [09:00-23:00|off] [--json] the person's hours: outside them, questions below urgent wait for morning
116
+ dibs say "..." [--as label] [--to person] an FYI to the person in your thread: progress, done, blocked on X.
117
+ --to person: a reply to what they said (the desk's answers)
118
+
119
+ progress (post as often as you commit)
120
+ dibs progress "..." [--task <name>] [--eta 30m|17:30] [--done|--blocked]
121
+ what you just did, found or decided, in a sentence or a paragraph. The person
122
+ reads every post live; other agents read them too. Post at each step, not at the end
123
+ dibs progress [--agent <name>] [-n 50] [--json] recent posts
124
+
125
+ the person's page and MCP server
126
+ dibs web [--port 7421] [--bind <address>] every agent's jobs, tasks and posts at http://127.0.0.1:7421, and the same as
127
+ MCP tools at /mcp (read-only unless signed in with --allow-actions). dibs service install web keeps it up
128
+ dibs connect connect a browser, a phone, your dibs account, another Claude's MCP or another
129
+ machine: it explains each, and on a terminal asks which
130
+ dibs connect --list | --remove <id> everything connected to this Mac; disconnect one
131
+ dibs connect --approve <code> let a new browser of your dibs account in: the 6 digits it shows
132
+ dibs connect --accounts [--json] the dibs accounts this Mac is on, and the browsers waiting for its approval
133
+ dibs connect --refuse <id> turn down a waiting browser (its id from dibs connect --accounts)
134
+ dibs pair a one-time code to sign the page or an MCP client in (10 minutes, one use)
135
+ dibs pair --allow-actions a code that also lets an MCP client act: post progress, answer, message agents, hold,
136
+ boost, pause, resume and stop jobs, as an agent named after it (mcp-<name>)
137
+ dibs pair --allow-commands all that, and queue_run: commands to run on this Mac, as dibs later. Only on this
138
+ Mac's own MCP (127.0.0.1:7421/mcp), never through mcp.dibs.cc
139
+ dibs pair --list | --revoke <id|all> what's signed in (MCP clients: can act or look only; on the coordinator, its machines)
140
+ dibs pair --machine [--name x] on the coordinator: a one-time code another machine joins with (10 minutes, one use);
141
+ dibs pair --revoke <machine> removes one that joined
142
+ dibs pair --remote [--allow-actions] a one-time link and QR code to pair a phone or any browser with https://app.dibs.cc,
143
+ end-to-end encrypted through the relay (dibs service install relay keeps it connected).
144
+ It can only look unless --allow-actions; the hook and hours never change remotely
145
+ dibs relay [--url wss://app.dibs.cc] the relay connection itself, in the foreground
146
+ dibs relay mcp on|off let MCP clients (another Claude account's connectors) reach this Mac's read-only MCP at
147
+ https://mcp.dibs.cc/mcp through the relay, signing in with a dibs pair code. Off by default
148
+
149
+ talk with your agents
150
+ dibs threads [--json] one thread per agent: its notes, questions, and your messages
151
+ dibs threads read <agent> the conversation; marks its notes read
152
+ dibs tell <agent> "..." a message for that agent: it gets it with its next tool call, or as it
153
+ finishes its turn (needs dibs guard install). From an agent, it says which agent sent it
154
+ dibs tell desk "..." to the agent config.json names as "desk": it answers with dibs say --to person
155
+
156
+ several machines
157
+ dibs run <res> --anywhere -- <cmd> run it on whichever machine would start it soonest (maybe this one)
158
+ dibs run <res> --on <machine> -- <cmd> run it on that machine
159
+ dibs machines every machine, its load and line, and the jobs moving between them
160
+ dibs serve be the coordinator (one machine does this); then dibs pair --machine or dibs invite <machine>
161
+ dibs join <code> [--at <address>] join with a code from dibs pair --machine: finds the coordinator on this network
162
+ or through Tailscale (--at when it's elsewhere), then dibs service install worker
163
+ dibs join <url> <token> [--name x] connect this machine to a coordinator with a line from dibs invite
164
+ dibs worker take jobs here (dibs service install worker keeps it running)
165
+ dibs leave this machine out of its group: it stops taking jobs and forgets the coordinator.
166
+ On the coordinator, only once no other machine is joined (dibs kick each first)
167
+ dibs invite <machine> on the coordinator: a token for that machine, and the join line to run there
168
+ dibs kick <machine> on the coordinator: remove it now; its jobs stop and its token stops working
169
+ dibs limit <machine> --only test,heavy on the coordinator: the only jobs it takes from others (--any lifts it)
170
+ dibs limit <machine> --sends test|none on the coordinator: the only jobs it may send to other machines
171
+ .dibs.json {"stayOn": ["mini"]} at a project's root: the machines its code may go to (besides its own)
172
+ dibs service install|remove|status [serve] [worker] [throttle] [web] [relay] start them at login and keep them up
173
+ join, leave, invite, kick, limit, service, guard install/remove, pace, hours and cap go in the history with who ran them
174
+
175
+ priorities and pauses (ids are the #numbers on dibs --detail; anyone, person or agent, on any job; the board names who.
176
+ An agent acting on a job that isn't its own adds --owner <session>, or session/agent, as the board names it)
177
+ dibs boost <id|agent> <prio> [-m why] change a waiter's or running job's priority: re-ranks it, and moves a run
178
+ onto or off the efficiency cores (an agent name changes all its work).
179
+ An agent raising a job to high or urgent passes -m, which everyone sees
180
+ dibs pause <id> [--force] [-m why] freeze a running job where it stands; it keeps its lease (sim, xcode-build
181
+ and deploy need --force: frozen midway they can fail)
182
+ dibs resume <id> [-m why] continue a paused job
183
+ dibs stop <id> [-m why] end a job and kill its processes, as a crash would; its agent is told
184
+ dibs cap <agent> <prio|off> that agent's work never waits or runs above prio until off
185
+
186
+ other
187
+ dibs port print a free port
188
+ dibs sims [prune] the simulators behind sim-own; prune deletes the idle ones
189
+ dibs pace [quiet|normal|max|off] how hard dibs drives this machine: quiet keeps the fan calm, max finishes fast
190
+ dibs throttle [--watch] move CPU hogs running outside dibs to background priority when the machine is hot
191
+ dibs setup scratch [--size 40G] print the one-time commands for a capped volume for build output (--check: how full)
192
+ dibs changes what changed in recent versions
193
+ dibs guard install|remove|status|check a Claude Code hook that runs heavy commands through dibs when an agent forgets
194
+
195
+ flags
196
+ -m "why" shown to everyone (required with urgent and high)
197
+ -p <level> priority, how far it moves you in the queue:
198
+ urgent (1) 2 hr ahead something is broken or a person is waiting now
199
+ high (2) 1 hr ahead on the critical path
200
+ normal (3) arrival order
201
+ low (4) 10 min back nobody is waiting on it; runs at background priority
202
+ idle (5) 60 min back only when nobody else waits; runs at background priority
203
+ low and idle runs may be paused (not killed) for urgent or high work, or under memory pressure
204
+ --by 23:30|20m deadline: as it nears you move up the queue (up to an hour), and you're warned if it's at risk
205
+ --est 5m how long the job takes, when dibs has no history for it. Short jobs move up a little
206
+ --cost 3 tokens a quota:<name> job takes from its bucket (default 1)
207
+ --mem 4G memory the job needs (default from the resource). dibs measures what it really uses
208
+ and plans the next run at that when it's more
209
+ --cpu 2 cores the job keeps busy (default from the resource)
210
+ --disk 10G free disk the job needs
211
+ --port NAME put a free port in env NAME for the command (repeatable)
212
+ --wait wait in the queue as long as it takes. The default inside Claude Code, which moves a
213
+ tool call that reaches its timeout to the background instead of killing it
214
+ --max-wait 8m stop waiting after this with exit 75. The default (8m) everywhere else
215
+ --no-wait don't wait at all
216
+ --notify <file> when dibs exits, append one JSON line to file: {"code", "started", "res", "cmd", ...}
217
+ --as label a label shown next to your agent name (for subagents)
218
+ --json machine-readable output (board, when, mine, requests, machines, history, questions, threads, hours, pace, guard status)
219
+ --anywhere send it to the least busy machine (see "several machines")
220
+ --shards N split a playwright test, vitest or node --test run into N pieces across machines, output and exit codes merged.
221
+ vitest and node --test suites that usually take over 5 minutes split in two on their own; --no-shard keeps one
222
+ --on <machine> send it to that machine
223
+ --bring <path> with --anywhere/--on: copy this file or folder back when the job ends (repeatable)
224
+
225
+ Your place in the queue is your arrival time, moved by priority, a near deadline, a short known run time
226
+ (up to 5 min), heavy use of the same resource in the last hour (up to 10 min back), and already holding a
227
+ lease (like high). dibs why says which moved you; dibs why --detail shows the math.
228
+
229
+ Agents are listed by session name, the same name SendMessage uses.
230
+ Resources: sim, sim-own, xcode-build, playwright, test, deploy, heavy, or any name you make up (use the same one as others).
231
+ quota:<name> is a rate limit shared by every script here (config.json "quotas": {"asc": {"per": "1h", "limit": 300}}):
232
+ a job waits until its bucket has --cost tokens, so scripts calling one API wait instead of getting 429s.
233
+ Subagents: with dibs guard installed, at most agents.slots (default 8) run at once across every Claude Code
234
+ session here. A spawn past that is denied, unless the session has none running; wait for one of yours to finish.
235
+ A profile is a name for a resource with its ports and sizes, set once in config.json "profiles":
236
+ {"playwright:web": {"res": "playwright", "ports": ["WEB", "API"], "mem": "3G", "cpu": 2}}, then dibs run playwright:web -- <command>.
237
+ files:<path or glob> is a file lease: while you hold it, dibs guard turns away other sessions' edits and writes there.
238
+ sim is the one shared booted simulator. sim-own boots a private one for your command: its udid is in $SIM, its name in $SIM_NAME.
239
+ Exit codes: the command's own, or 75 gave up waiting (NOT a failure: your command never started; run the
240
+ same command again within 2 minutes to keep your place), 74 not enough disk,
241
+ 76 lost the coordinator or the other machine before the job started (safe to send again),
242
+ 77 lost it after the job started on another machine (it may have run: check before running it again),
243
+ 127 command didn't start, 2 bad usage (also: you already have this exact command waiting or running),
244
+ 1 nothing matched (mine, release), 70 dibs itself crashed (a bug in dibs; report it: dibs ask "...").
245
+ A job sent to another machine takes the git working copy (tracked files plus new ones git doesn't ignore;
246
+ outside git, the folder minus build output). .env files, keys and certificates never leave this machine.
247
+ Config: ${paths.config}`;
248
+
249
+ function parse(argv) {
250
+ const o = { res: [], cmd: null, ports: [], bring: [] };
251
+ const dd = argv.indexOf('--');
252
+ if (dd >= 0) { o.cmd = argv.slice(dd + 1); argv = argv.slice(0, dd); }
253
+ for (let i = 0; i < argv.length; i++) {
254
+ const a = argv[i], next = () => argv[++i] ?? die(`${a} needs a value`);
255
+ if (a === '-m' || a === '--msg') o.purpose = next();
256
+ else if (a === '-p' || a === '--priority') { o.prio = priority(next()); if (!(o.prio in PRIORITY_SHIFT)) die(`priority is one of ${PRIORITIES.join(', ')} (or 1-5)`); }
257
+ else if (a === '--by') o.by = deadline(next());
258
+ else if (a === '--est') o.est = ms(next());
259
+ else if (a === '--cost') { o.cost = Number(next()); if (!(o.cost > 0)) die('--cost takes a number of tokens above 0'); }
260
+ else if (a === '--mem') o.mem = bytes(next());
261
+ else if (a === '--cpu') { o.cpu = Number(next()); if (!(o.cpu >= 0)) die('--cpu takes a number of cores'); }
262
+ else if (a === '--disk') o.disk = bytes(next());
263
+ else if (a === '--max-wait') o.maxWait = ms(next());
264
+ else if (a === '--no-wait') o.maxWait = 0;
265
+ else if (a === '--wait') o.maxWait = Infinity;
266
+ else if (a === '--notify') o.notify = next();
267
+ else if (a === '--for') o.for = ms(next());
268
+ else if (a === '--lease') o.lease = Number(next()); // src/thin.sh's, on its turn
269
+ else if (a === '--after') o.after = next();
270
+ else if (a === '--since') o.since = next();
271
+ else if (a === '--as') o.as = next();
272
+ else if (a === '--port') o.ports.push(next());
273
+ else if (a === '--json') o.json = true;
274
+ else if (a === '--detail') o.detail = true;
275
+ else if (a === '--watch') o.watch = true;
276
+ else if (a === '--anywhere') o.anywhere = true;
277
+ else if (a === '--shards') { o.shards = Number(next()); if (!(Number.isInteger(o.shards) && o.shards >= 1 && o.shards <= 8)) die('--shards takes how many pieces to split a suite into, 1 to 8 (1: none)'); }
278
+ else if (a === '--no-shard') o.shards = 1;
279
+ else if (a === '--on') o.on = next();
280
+ else if (a === '--bring') o.bring.push(next());
281
+ else if (a === '--name') o.name = next();
282
+ else if (a === '--at') o.at = next();
283
+ else if (a === '--ephemeral') o.ephemeral = true; // a worker on an on-demand VM (src/ondemand.mjs)
284
+ else if (a === '--listen') { o.listen = Number(next()); if (!(o.listen > 0 && o.listen < 65536)) die('--listen takes a port number'); }
285
+ else if (a === '--bind') o.bind = next();
286
+ else if (a === '--only') { o.only = next().split(',').filter(Boolean); if (!o.only.length) die('--only takes resource names, e.g. --only test,heavy'); }
287
+ else if (a === '--any') o.any = true;
288
+ else if (a === '--sends') { const v = next(); o.sends = v === 'none' ? [] : v.split(',').filter(Boolean); if (v !== 'none' && !o.sends.length) die('--sends takes resource names, e.g. --sends test,heavy, or none'); }
289
+ else if (a === '--force') o.force = true;
290
+ else if (a === '--size') o.size = next();
291
+ else if (a === '--check') o.check = true;
292
+ else if (a.startsWith('-')) die(`unknown flag ${a}. Every flag: dibs help all`);
293
+ else o.res.push(...resList(a).map(r => fileRes(r) ?? die("files: needs a path or glob, e.g. 'files:src/auth/**'")));
294
+ }
295
+ return o;
296
+ }
297
+
298
+ // The changelog's sections, newest first: [{ version, body }].
299
+ function changelog() {
300
+ try {
301
+ return fs.readFileSync(path.join(ROOT, 'CHANGELOG.md'), 'utf8').split(/^## /m).slice(1)
302
+ .map(sec => ({ version: sec.split(/\s/)[0], body: sec.slice(sec.indexOf('\n') + 1).trim() }));
303
+ } catch { return []; }
304
+ }
305
+
306
+ // The first time each agent session runs a new version, one line pointing at
307
+ // what changed. Only for an agent that ran an older one here: a brand-new
308
+ // install, or a session that never ran dibs before, has nothing to compare.
309
+ // Written to stderr, so it never lands in output a script reads.
310
+ function announce() {
311
+ const id = identity();
312
+ const key = String(id.spid || id.who);
313
+ let seen = {};
314
+ try { seen = JSON.parse(fs.readFileSync(paths.seen, 'utf8')); } catch {}
315
+ if (seen[key] === VERSION) return;
316
+ const before = seen[key];
317
+ seen[key] = VERSION;
318
+ try {
319
+ const tmp = `${paths.seen}.${process.pid}`;
320
+ fs.writeFileSync(tmp, JSON.stringify(seen));
321
+ fs.renameSync(tmp, paths.seen);
322
+ } catch {}
323
+ if (before) process.stderr.write(`dibs was updated to ${VERSION}: see \`dibs changes\`\n`);
324
+ }
325
+
326
+ // A caller with no hook to hand it notices (outside Claude Code) gets them here.
327
+ function notices() {
328
+ if (process.env.CLAUDE_CODE_SESSION_ID) return;
329
+ const n = noticesFor(identity().who);
330
+ if (n) process.stderr.write(`${n}\n`);
331
+ }
332
+
333
+ // Old names keep working, so nothing that already calls dibs breaks.
334
+ const ALIASES = { done: 'release', renew: 'hold', news: 'changes', cool: 'throttle', ls: 'status', board: 'status' };
335
+ const VERBS = new Set(['run', 'hold', 'release', 'when', 'why', 'mine', 'who', 'yield', 'ask', 'requests', 'port', 'throttle', 'changes', 'status', 'help',
336
+ 'machines', 'serve', 'join', 'leave', 'worker', 'service', 'invite', 'kick', 'limit', 'guard', 'sims', 'pace', 'setup', 'history', 'stats',
337
+ 'question', 'questions', 'answer', 'hours', 'say', 'tell', 'threads', 'boost', 'pause', 'resume', 'stop', 'cap', 'later',
338
+ 'progress', 'web', 'pair', 'relay', 'connect', 'alerts']);
339
+
340
+ // A job sent from another machine ends when the worker that started it does,
341
+ // even if the worker was killed outright and couldn't say so.
342
+ function followParent() {
343
+ const parent = process.ppid;
344
+ setInterval(() => { if (process.ppid !== parent) process.kill(process.pid, 'SIGTERM'); }, 2000).unref();
345
+ }
346
+
347
+ // A suite split across machines (src/shard.mjs), or null: --shards N, or on its own
348
+ // for a vitest or node --test suite that usually takes over 5 minutes, with an
349
+ // on-demand machine to send the other half to.
350
+ async function shardsFor(o, cfg) {
351
+ if (!o.cmd?.length || o.shards === 1 || o.anywhere || o.on || o.lease || o.after || process.env.DIBS_SHARD) return null;
352
+ const { sharder, runShards, AUTO_OVER, AUTO_SHARDS } = await lazy('shard');
353
+ const split = sharder(o.cmd);
354
+ if (!split) { if (o.shards > 1) die(`--shards splits a playwright test, vitest or node --test run, which this isn't: ${o.cmd.join(' ')}`); return null; }
355
+ const { ondemandOf } = await lazy('ondemand');
356
+ let vm = null;
357
+ try { vm = ondemandOf(cfg).find(m => !m.temp)?.name || null; } catch {}
358
+ let n = o.shards;
359
+ if (!n && vm && split.which !== 'playwright') {
360
+ const { typical } = await import('../src/schedule.mjs');
361
+ const { history } = await import('../src/state.mjs');
362
+ const { commandKey } = await lazy('acquire');
363
+ if (typical(history(), `${o.res.join(',')}|${commandKey(o.cmd)}`) > AUTO_OVER) n = AUTO_SHARDS;
364
+ }
365
+ return n > 1 ? () => runShards(o, n, split, vm) : null;
366
+ }
367
+
368
+ async function main() {
369
+ let argv = process.argv.slice(2);
370
+ // Not for thin waits' own calls (_enqueue, _broker, _rewait, _leave): the broker follows
371
+ // a remote job's worker for its waiter, and the broker outlives whoever started it.
372
+ if (process.env.DIBS_REMOTE_JOB && !String(argv[0]).startsWith('_')) followParent();
373
+ let verb = argv[0];
374
+ if (verb === '--version' || verb === '-v' || verb === 'version') return console.log(VERSION);
375
+ if (verb === '-h' || verb === '--help') verb = 'help';
376
+ verb = ALIASES[verb] || verb;
377
+ if (verb === 'help') return console.log(argv[1] === 'all' ? HELP_ALL : HELP);
378
+ if (verb === 'changes') return console.log(changelog().slice(0, 3).map(c => `${c.version}\n${c.body}`).join('\n\n'));
379
+ // The hook runs on every Bash call: no config file writes, no what's-new notice.
380
+ if (verb === 'guard') {
381
+ if (argv[1] === 'install' || argv[1] === 'remove') (await import('../src/owner.mjs')).logChange(`guard ${argv[1]}`);
382
+ return (await lazy('guard')).guard(argv.slice(1));
383
+ }
384
+ // src/thin.sh's own calls, not commands anyone types (src/broker.mjs).
385
+ if (verb === '_broker') return (await import('../src/broker.mjs')).broker();
386
+ // The Mac app's reader: its polls, answered by one process that stays up (src/reads.mjs).
387
+ if (verb === '_reads') return (await import('../src/reads.mjs')).reads(readOne);
388
+ if (verb === '_rewait') { if (!(await import('../src/broker.mjs')).ensureBroker()) process.exitCode = 1; return; }
389
+ if (verb === '_leave') return (await import('../src/broker.mjs')).leaveLine(Number(argv[1]), Number(argv[2]), argv[3]);
390
+ let thin = null;
391
+ if (verb === '_enqueue') {
392
+ thin = (await import('../src/broker.mjs')).thinCall(Number(argv[1]), argv[3]);
393
+ // Node's parent is the waiting shell; the caller, for twins and nesting, is the shell's parent.
394
+ setCaller(Number(argv[2]));
395
+ process.argv.splice(2, 4); // the command as typed, for the line that says how to run it again
396
+ argv = process.argv.slice(2);
397
+ verb = argv[0];
398
+ }
399
+ calledVerb = verb;
400
+ const cfg = loadConfig();
401
+ // Services, jobs sent from another machine and scheduled ones have nobody to read the notes.
402
+ // A thin waiter's turn has had them already, when it got in line.
403
+ const lease = argv.slice(0, argv.indexOf('--') >>> 0).includes('--lease');
404
+ if (!process.env.DIBS_REMOTE_JOB && !process.env.DIBS_LATER_JOB && !lease && !['serve', 'worker', 'service', 'relay'].includes(verb)) { announce(); notices(); }
405
+ // `dibs sim -- cmd` (no verb) means run; a bare `dibs` or `dibs --json` is the board.
406
+ // `dibs -m why sim -- cmd` is a run too: anything with a command after -- is.
407
+ if (!verb || (verb.startsWith('-') && verb !== '--' && !argv.includes('--'))) return status(parse(argv), cfg);
408
+ if (!VERBS.has(verb) && !argv.includes('--') && !cfg.resources[verb] && !isFiles(verb) && !isQuota(verb)) {
409
+ // `dibs list`, `dibs stauts`: a command that doesn't exist, not a run missing its --.
410
+ const near = nearest(verb, [...VERBS, ...Object.keys(ALIASES)]);
411
+ die(`unknown command ${verb}.${near ? ` Did you mean dibs ${near}?` : ''} Commands: dibs help. To run something: dibs run <resource> -- <command>`);
412
+ }
413
+ const rest = VERBS.has(verb) ? argv.slice(1) : argv;
414
+ if (!VERBS.has(verb)) verb = 'run';
415
+ switch (verb) {
416
+ case 'run': {
417
+ const o = profiled(parse(rest), cfg);
418
+ if (o.bring.length && !o.anywhere && !o.on) die('--bring only means something with --anywhere or --on');
419
+ if ((o.anywhere || o.on) && o.res.some(isFiles)) die("file leases cover this machine's files. Take them here (dibs hold files:...), then send the job without them");
420
+ if (o.after && (o.anywhere || o.on)) die('--after works for a run on this machine; for another, use dibs later --after');
421
+ checkNames(o.res, cfg);
422
+ const shards = await shardsFor(o, cfg);
423
+ // Paths thin waits don't cover: a shell's Node hands back to it to wait in Node; one already
424
+ // the shell's own Node (src/broker.mjs inlineCall) just goes on here.
425
+ if (thin?.inline && (shards || o.anywhere || o.on || o.after)) thin = null;
426
+ if (shards) { if (thin) return thin.fat(); notifyOnExit(o); return shards(); }
427
+ // Waiting thin covers a plain run here: the rest wait in-process.
428
+ // A run sent to another machine waits there (thin, through its worker); --after waits outside the line.
429
+ if (thin && (o.anywhere || o.on || o.after)) return thin.fat();
430
+ o.thin = thin;
431
+ notifyOnExit(o);
432
+ return o.anywhere || o.on ? remoteRun(o, cfg) : run(o, cfg);
433
+ }
434
+ case 'machines': return machines(parse(rest));
435
+ case 'serve': return (await lazy('serve')).serve(parse(rest));
436
+ case 'join': return join(parse(rest));
437
+ case 'worker': return (await lazy('worker')).worker(parse(rest), cfg);
438
+ case 'invite': return (await lazy('admin')).invite(parse(rest));
439
+ case 'kick': return (await lazy('admin')).kick(parse(rest));
440
+ case 'leave': return (await lazy('admin')).leave();
441
+ case 'limit': return (await lazy('admin')).limit(parse(rest));
442
+ case 'service': return (await lazy('service')).service(rest);
443
+ case 'hold': { const o = profiled(parse(rest), cfg); if (o.notify || o.after) die(`${o.notify ? '--notify' : '--after'} works with dibs run`); checkNames(o.res, cfg); o.thin = thin; return hold(o, cfg); }
444
+ case 'release': return release(parse(rest));
445
+ case 'when': { const o = profiled(parse(rest), cfg); checkNames(o.res, cfg); return when(o, cfg); }
446
+ case 'why': return why(parse(rest), cfg);
447
+ case 'mine': return mine(parse(rest), cfg);
448
+ case 'who': return who(parse(rest), cfg);
449
+ case 'yield': return yieldTo(parse(rest));
450
+ case 'ask': return ask(rest, cfg);
451
+ case 'requests': return requests(parse(rest));
452
+ case 'port': return console.log(await freePort());
453
+ case 'throttle': return (await lazy('cool')).throttle(parse(rest), cfg);
454
+ case 'status': return status(parse(rest), cfg);
455
+ case 'sims': { const o = parse(rest); return sims(o, o.res, cfg); }
456
+ case 'pace': return pace(rest);
457
+ case 'setup': { const o = parse(rest); return (await lazy('scratch')).setup(o.res, o); }
458
+ case 'history': return (await lazy('history')).history(parse(rest), cfg);
459
+ case 'stats': return (await lazy('stats')).stats(rest, cfg);
460
+ case 'alerts': return (await lazy('alerts')).alerts(rest, cfg);
461
+ case 'question': return question(rest, cfg);
462
+ case 'questions': return questions(rest, cfg);
463
+ case 'answer': return answer(rest);
464
+ case 'hours': return hoursCmd(rest, cfg);
465
+ case 'say': return say(rest);
466
+ case 'progress': return (await lazy('progress')).post(rest);
467
+ case 'web': return (await lazy('web')).web(rest);
468
+ case 'pair': return (await lazy('web')).pair(rest);
469
+ case 'connect': return (await lazy('connect')).connect(rest);
470
+ case 'relay': return (await lazy('relay')).relay(rest);
471
+ case 'tell': return tell(rest);
472
+ case 'threads': return threads(rest);
473
+ case 'boost': return boost(rest, cfg);
474
+ case 'pause': return pause(rest, cfg);
475
+ case 'resume': return resume(rest);
476
+ case 'stop': return stop(rest);
477
+ case 'cap': return cap(rest);
478
+ case 'later': return /^(help|-h|--help)$/.test(rest[0] || '') ? console.log(LATER_HELP) : later(rest, cfg, parse);
479
+ }
480
+ }
481
+
482
+ // One of the CLI's read-only verbs, exactly as main() runs it, for the Mac app's
483
+ // reader. Anything else is refused: the reader never changes anything.
484
+ const COUNT = /^\d{1,5}$/;
485
+ async function readOne(argv) {
486
+ const cfg = loadConfig();
487
+ const [verb, ...rest] = argv;
488
+ const only = (...want) => rest.length === want.length && want.every((w, i) => (w instanceof RegExp ? w.test(rest[i]) : w === rest[i]));
489
+ if (verb === '--version' && !rest.length) return console.log(VERSION);
490
+ if (verb === '--json' && !rest.length) return status(parse(argv), cfg);
491
+ if (verb === 'questions' && only('--json')) return questions(rest, cfg);
492
+ if (verb === 'threads' && only('--json')) return threads(rest);
493
+ if (verb === 'progress' && (only('--json') || only('--json', '-n', COUNT))) return (await lazy('progress')).post(rest);
494
+ if (verb === 'later' && only('list', '--json')) return later(rest, cfg, parse);
495
+ if (verb === 'history' && only('--json', '--since', /^\d+[mhd]$/)) return (await lazy('history')).history(parse(rest), cfg);
496
+ if (verb === 'stats' && rest[0] === '--json' && (only('--json', '--since', /^\d+[mhd]$/) || only('--json', '--since', /^\d+[mhd]$/, '--agent', /^[^-]/)))
497
+ return (await lazy('stats')).stats(rest, cfg);
498
+ if (verb === 'guard' && only('status', '--json')) return (await lazy('guard')).guard(rest);
499
+ if (verb === 'pace' && only('--json')) return pace(rest);
500
+ if (verb === 'pair' && only('--list')) return (await lazy('web')).pair(rest);
501
+ if (verb === 'connect' && only('--accounts', '--json')) return (await lazy('connect')).connect(rest);
502
+ if (verb === 'service' && rest[0] === 'status' && rest.slice(1).every(k => /^[a-z]+$/.test(k))) return (await lazy('service')).service(rest);
503
+ if (verb === 'sims' && only('--json')) { const o = parse(rest); return sims(o, o.res, cfg); }
504
+ die(`the app's reader answers only the read-only verbs, not dibs ${argv.join(' ')}`, 2);
505
+ }
506
+
507
+ // A crash gets a code of its own (70, EX_SOFTWARE), never one an agent reads as
508
+ // "nothing matched" (1) or as its command's own failure.
509
+ const CRASHED = 70;
510
+ const crash = e => die(`dibs itself crashed (a bug in dibs, not in your command; exit ${CRASHED}). Report it: dibs ask "..."\n${e?.stack || String(e)}`, CRASHED);
511
+ // A full disk is no bug: say what to do, with the exit code agents know (74), not a stack.
512
+ const fail = e => (noSpace(e) ? die(fullDisk(e), 74) : crash(e));
513
+ process.on('uncaughtException', fail);
514
+
515
+ // A job lost on its way to or on another machine (76, 77) and dibs's own crash
516
+ // (70) go in the event log, so the person hears of them (src/alerts.mjs), not
517
+ // only the agent whose tool call ended.
518
+ let calledVerb = '';
519
+ process.on('exit', code => {
520
+ if (code !== lastDieCode || !(code === CRASHED || ((code === 76 || code === 77) && calledVerb === 'run'))) return;
521
+ try {
522
+ event({ kind: code === CRASHED ? 'crash' : 'lost', code, verb: calledVerb, who: identity().who,
523
+ cmd: process.argv.slice(2).join(' ').slice(0, 160), why: lastDie.split('\n')[0].slice(0, 300) });
524
+ } catch {}
525
+ });
526
+ main().catch(fail);