@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/remote.mjs ADDED
@@ -0,0 +1,584 @@
1
+ // Several machines. One runs `dibs serve` (the coordinator); every machine that
2
+ // takes jobs runs `dibs worker`; any machine can send a job with
3
+ // `dibs run <res> --anywhere` or `--on <machine>`. The working copy goes along,
4
+ // the output streams back, and the exit code and any --bring files come home.
5
+ import fs from 'node:fs';
6
+ import os from 'node:os';
7
+ import path from 'node:path';
8
+ import crypto from 'node:crypto';
9
+ import dgram from 'node:dgram';
10
+ import { execFileSync } from 'node:child_process';
11
+ import { HOME, resCfg } from './config.mjs';
12
+ import { identity } from './proc.mjs';
13
+ import { OS } from './platform.mjs';
14
+ import { run } from './commands.mjs';
15
+ import { dur, gb, size, die, say, sleep, now, clock, when, SIGNALS } from './util.mjs';
16
+ import { VERSION } from './version.mjs';
17
+ import { bold, dim } from './style.mjs';
18
+ import { rulesAbove, readRules, ruleAllows, isRuleFile, isCode, normCode, codeKey, codeProof } from './trust.mjs';
19
+ import { projectKey } from './files.mjs';
20
+ import { jobSize } from './simpool.mjs';
21
+ import { defaultMaxWait } from './acquire.mjs';
22
+ import { logChange } from './owner.mjs';
23
+ import { ondemandOf } from './ondemand.mjs';
24
+
25
+ export const REMOTE = path.join(HOME, 'remote.json');
26
+ export const DEFAULT_PORT = 7420;
27
+ // What a joining machine broadcasts to find coordinators with an open pairing code (src/serve.mjs).
28
+ export const FIND = 'dibs-find-v1';
29
+ export const LOST = 76; // exit code: the coordinator or the machine running the job went away before it started
30
+ export const MAYBE_RAN = 77; // exit code: lost after the job started; it may have run, or still be running
31
+ export const MAX_BUNDLE = 300 * 1024 ** 2; // a compressed working copy, or the files a job brings back
32
+
33
+ // Files that never leave this machine, even when git tracks them: by name,
34
+ // and anything inside a folder that only ever holds keys.
35
+ const SECRET_FILES = [
36
+ '\\.env[^/]*', '[^/]+\\.env', '\\.dev\\.vars[^/]*', '\\.npmrc', '\\.yarnrc\\.yml', '\\.netrc', '\\.pypirc', '\\.git-credentials', '\\.pgpass', '\\.my\\.cnf',
37
+ '\\.htpasswd', '\\.vault-token', '\\.boto', '\\.s3cfg', 'auth\\.json', 'token\\.(json|pickle)',
38
+ 'id_(rsa|dsa|ecdsa|ed25519)(?![^/]*\\.pub$)[^/]*', 'deploy_key(?![^/]*\\.pub$)[^/]*',
39
+ '\\.?credentials(\\.(json|ya?ml|csv|txt|toml))?', '\\.?secrets?(\\.(json|ya?ml|toml|env|txt|ini))?',
40
+ '[^/]*service[-_]account[^/]*\\.json', '[^/]*-firebase-adminsdk-[^/]*\\.json', 'client_secret[^/]*\\.json',
41
+ '[^/]*\\.tfvars', '[^/]*\\.tfstate(\\.backup)?', 'kubeconfig[^/]*', '\\.kube/config', '\\.docker/config\\.json', '\\.config/gh/hosts\\.ya?ml',
42
+ '[^/]*\\.(p8|p12|pfx|pem|key|keystore|jks|mobileprovision|provisionprofile|asc|gpg|ppk|keychain|keychain-db)',
43
+ ];
44
+ const SECRET_DIRS = ['\\.ssh', '\\.aws', '\\.gnupg', '\\.dibs'];
45
+ export const SECRET = new RegExp(`(^|/)((${SECRET_FILES.join('|')})$|(${SECRET_DIRS.join('|')})/)`, 'i');
46
+ // Folders skipped when the working copy isn't a git repo (git uses .gitignore instead).
47
+ const SKIP_DIRS = new Set(['node_modules', 'DerivedData', 'build', 'dist', 'venv', '__pycache__', 'Pods', 'target']);
48
+ // Outside git, hidden folders stay home (they hold tools' settings and
49
+ // tokens), except these, which builds and tests read.
50
+ const KEEP_DOT_DIRS = new Set(['.github', '.husky', '.storybook', '.swiftpm', '.mvn', '.yarn', '.cargo', '.devcontainer', '.circleci', '.changeset', '.vscode']);
51
+
52
+ export const shortHost = () => os.hostname().replace(/\.(local|lan|home)$/i, '');
53
+
54
+ // { url, token, name } from `dibs join`, or null when this machine isn't in a
55
+ // group. A file that's there but can't be read goes to onBad, by default a
56
+ // stop with the reason: taken as "not in a group", a worker would wait for
57
+ // dibs join forever and the board would quietly drop the other machines.
58
+ export function remoteConf(onBad = die) {
59
+ let c;
60
+ try { c = JSON.parse(fs.readFileSync(REMOTE, 'utf8')); }
61
+ catch (e) {
62
+ if (e.code === 'ENOENT') return null;
63
+ return onBad(`${REMOTE} can't be read (${e.message}). Fix it, or connect again: dibs join <url> <token>`);
64
+ }
65
+ return c?.url && c?.token ? { name: shortHost(), ...c } : null;
66
+ }
67
+ // Written whole and swapped in, so a dibs reading it meanwhile never sees half a file.
68
+ export function saveRemote(c) {
69
+ fs.mkdirSync(HOME, { recursive: true });
70
+ const tmp = `${REMOTE}.${process.pid}`;
71
+ fs.writeFileSync(tmp, JSON.stringify(c, null, 2) + '\n', { mode: 0o600 });
72
+ fs.chmodSync(tmp, 0o600);
73
+ fs.renameSync(tmp, REMOTE);
74
+ }
75
+ // Never starting with '-', which would read as a flag in `dibs join <url> <token>`.
76
+ export function newToken() {
77
+ for (;;) { const t = crypto.randomBytes(24).toString('base64url'); if (t[0] !== '-') return t; }
78
+ }
79
+
80
+ // One HTTP call to the coordinator. JSON in and out unless raw is set.
81
+ export async function call(rc, method, route, body, { timeout = 20e3, raw = false } = {}) {
82
+ const headers = { authorization: `Bearer ${rc.token}`, 'x-dibs-version': VERSION };
83
+ let payload;
84
+ if (Buffer.isBuffer(body)) { payload = body; headers['content-type'] = 'application/octet-stream'; }
85
+ else if (body !== undefined) { payload = JSON.stringify(body); headers['content-type'] = 'application/json'; }
86
+ const r = await fetch(new URL(route, rc.url), { method, headers, body: payload, signal: AbortSignal.timeout(timeout) });
87
+ if (!r.ok) {
88
+ let msg = `${r.status} ${r.statusText}`;
89
+ try { msg = (await r.json()).error || msg; } catch {}
90
+ const e = new Error(msg); e.status = r.status; throw e;
91
+ }
92
+ return raw ? Buffer.from(await r.arrayBuffer()) : r.json();
93
+ }
94
+
95
+ // The operating system a set of resources needs (sim and xcode-build need macOS).
96
+ function needsOs(cfg, res) {
97
+ const want = [...new Set(res.map(r => resCfg(cfg, r).os).filter(Boolean))];
98
+ if (want.length > 1) die(`${res.join(', ')} need different systems (${want.join(', ')}); no machine has both`);
99
+ return want[0] || null;
100
+ }
101
+
102
+ const tarEnv = { ...process.env, COPYFILE_DISABLE: '1' }; // no ._ files from macOS
103
+ // Past MAX_BUNDLE, tar's output overflows the buffer (ENOBUFS): that's the size
104
+ // limit, said as one, with a 413 so retry() doesn't try again.
105
+ export function tarCreate(cwd, files, max = MAX_BUNDLE) {
106
+ try {
107
+ return execFileSync('tar', ['-czf', '-', '--no-xattrs', '--null', '-T', '-'],
108
+ { cwd, input: files.join('\0'), env: tarEnv, maxBuffer: max, stdio: ['pipe', 'pipe', 'pipe'] });
109
+ } catch (e) {
110
+ if (e.code === 'ENOBUFS') throw Object.assign(new Error(`over the ${size(max)} limit compressed`), { status: 413 });
111
+ throw e;
112
+ }
113
+ }
114
+ // only: extract just these paths (files, or folders with everything under
115
+ // them), whatever else the archive holds.
116
+ export function tarExtract(dir, buf, only = null) {
117
+ fs.mkdirSync(dir, { recursive: true });
118
+ let members = [];
119
+ if (only) {
120
+ const listed = execFileSync('tar', ['-tzf', '-'], { input: buf, env: tarEnv, encoding: 'utf8', maxBuffer: 64 * 1024 ** 2, stdio: ['pipe', 'pipe', 'pipe'] }).split('\n').filter(Boolean);
121
+ members = listed.filter(m => { const n = safeRel(m); return n && only.some(p => n === p || n.startsWith(`${p}/`)); });
122
+ if (!members.length) return [];
123
+ }
124
+ execFileSync('tar', ['-xzf', '-', ...(members.length ? ['--', ...members] : [])], { cwd: dir, input: buf, env: tarEnv, stdio: ['pipe', 'ignore', 'pipe'] });
125
+ return members;
126
+ }
127
+
128
+ // The folder a working copy comes from: the git repo around cwd, or cwd itself.
129
+ function projectRoot(cwd = process.cwd()) {
130
+ try { return fs.realpathSync(execFileSync('git', ['rev-parse', '--show-toplevel'], { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim()); }
131
+ catch { return cwd; }
132
+ }
133
+ // A load-held job may go to an on-demand machine on its own (acquire.mjs step)
134
+ // only when it can run there. Never one that needs macOS: a resource that
135
+ // says os macos, a command naming a macOS tool, or a local script that uses
136
+ // Apple frameworks. On 2026-10-18 the job that waited hours on load was OCR
137
+ // through Apple Vision, run as python3 tools/reocr_batch.py: nothing in the
138
+ // command says macOS, so the script itself is read. Only its first SCRIPT_PEEK
139
+ // bytes, where the imports are.
140
+ const MAC_TOOLS = /(^|[\s/;&|("'])(xcrun|xcodebuild|xcode-select|swift|swiftc|osascript|sw_vers|simctl|pbcopy|pbpaste|codesign|mdfind|sips|screencapture|launchctl|plutil)(?=\s|$)|\.swift\b/;
141
+ const MAC_FRAMEWORKS = /\b(import\s+(Vision|Quartz|AppKit|Foundation|CoreML|Cocoa)\b|from\s+(Vision|Quartz|AppKit|Foundation|CoreML|Cocoa)\s+import|objc\.|pyobjc|NSApplication|VNRecognizeTextRequest|osascript|xcrun)/;
142
+ const SCRIPT_PEEK = 64 * 1024;
143
+ export function macOnly(cmd, cwd) {
144
+ if (MAC_TOOLS.test(cmd)) return true;
145
+ for (const word of cmd.split(/\s+/)) {
146
+ if (!/\.(py|sh|js|mjs|rb|pl|swift)$/.test(word)) continue;
147
+ try {
148
+ const fd = fs.openSync(path.resolve(cwd, word), 'r');
149
+ const buf = Buffer.alloc(SCRIPT_PEEK);
150
+ const n = fs.readSync(fd, buf, 0, SCRIPT_PEEK, 0);
151
+ fs.closeSync(fd);
152
+ if (MAC_FRAMEWORKS.test(buf.toString('utf8', 0, n)) || MAC_TOOLS.test(buf.toString('utf8', 0, n))) return true;
153
+ } catch {}
154
+ }
155
+ return false;
156
+ }
157
+ // The checks that cost nothing: a run of a command, no file leases, nothing
158
+ // that needs macOS, a project that isn't the home folder, a coordinator, and
159
+ // an on-demand machine in this machine's config. That last one keeps a thin
160
+ // waiter from turning into Node to ask about a machine that isn't there; a
161
+ // machine that isn't the coordinator doesn't list them, so only the
162
+ // coordinator's own waiters ship on their own.
163
+ export function mayShip(me, cfg, cwd) {
164
+ if (me.kind !== 'run' || !me.cmd || me.res.some(r => r.startsWith('files:'))) return false;
165
+ try { if (!ondemandOf(cfg).length) return false; } catch { return false; }
166
+ try { if (needsOs(cfg, me.res) === 'macos') return false; } catch { return false; }
167
+ if (macOnly(me.cmd, cwd) || !remoteConf(() => null) || namesPaths(me.cmd)) return false;
168
+ const root = gitRoot(cwd);
169
+ if (!root) return false;
170
+ let home = os.homedir();
171
+ try { home = fs.realpathSync(home); } catch {}
172
+ return !(root === path.parse(root).root || home === root || home.startsWith(root.endsWith(path.sep) ? root : root + path.sep));
173
+ }
174
+ // Only a git working copy ships on its own: that's what the copy is, and a
175
+ // folder outside git may hold anything.
176
+ function gitRoot(cwd) {
177
+ try { return fs.realpathSync(execFileSync('git', ['rev-parse', '--show-toplevel'], { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim()); }
178
+ catch { return null; }
179
+ }
180
+ // A command that names a path of this machine (/Users/..., ~/...) means a file the
181
+ // copy on another machine won't have there, even one inside the project. On
182
+ // 2026-10-20 a browser run naming /Users/alex/... shipped to boat-1 and failed.
183
+ // The system's own folders are the same on Linux; a temp folder's files aren't.
184
+ const SYSTEM_PATHS = /^\/(bin|sbin|usr\/bin|usr\/sbin|dev|etc|proc)(\/|$)/;
185
+ export function namesPaths(cmd) {
186
+ for (const m of String(cmd).matchAll(/(?:^|[\s'"=:(])(~?\/[^\s'";|&)<>]*)/g))
187
+ if (!m[1].startsWith('//') && (m[1].startsWith('~') || !SYSTEM_PATHS.test(m[1]))) return true;
188
+ return false;
189
+ }
190
+ // The on-demand machine a load-held job should go to, or null. The machines
191
+ // list is read at most once a minute per waiter; the job's .dibs.json rules
192
+ // pick among them, and one /place call asks the coordinator to agree (its
193
+ // limits, memory, a problem since). A placement back here means stay.
194
+ const MACHINES_FOR = 60e3;
195
+ let known = { at: 0, rows: [], jobs: [] };
196
+ // temp: a VM made for the job may be used too, when the one it stands beside
197
+ // is full. A memory wait asks for that (acquire.mjs step): the job was held
198
+ // for memory, and a full boat-1 would only hold it again. A load wait doesn't:
199
+ // the temporary VM is made for jobs bigger than boat-1, and costs more.
200
+ // Jobs pack onto boat-1 while what's sent there fits its memory, then onto the
201
+ // one temporary VM beside it: every VM woken or made is a boat start, and the
202
+ // account has 200 a day.
203
+ const VM_RESERVE = 1024 ** 3; // the VM's own system and its dibs worker
204
+ export async function loadShipTarget(me, cfg, cwd, { temp = false } = {}) {
205
+ const rc = remoteConf(() => null);
206
+ if (!rc) return null;
207
+ if (now() - known.at > MACHINES_FOR) {
208
+ try { const r = await call(rc, 'GET', '/machines', undefined, { timeout: 8000 }); known = { at: now(), rows: r.machines || [], jobs: r.jobs || [] }; }
209
+ catch { known = { at: now(), rows: [], jobs: [] }; }
210
+ }
211
+ const rule = readRules(rulesAbove(cwd));
212
+ const root = projectRoot(cwd);
213
+ const booked = name => known.jobs.filter(j => j.machine === name && j.state !== 'done').reduce((a, j) => a + (j.mem || 0), 0);
214
+ const full = m => booked(m.name) + (me.mem || 0) > (m.ondemand.mem || m.memTotal || 0) - VM_RESERVE;
215
+ // Not one that can't wake now (boat's starts used up, a failed wake): the job would only come back.
216
+ const usable = known.rows.filter(m => m.ondemand && !m.ondemand.problem && !(m.ondemand.cantWake?.until > now()) && m.name !== rc.name && ruleAllows(rule, m.name, rc.name));
217
+ const vms = usable.filter(m => !m.ondemand.temp);
218
+ // The VM itself while the job fits beside what's there; then the VM made beside a full one; then the full one.
219
+ // Any other wait goes only to a VM with room: one already full would only hold it again.
220
+ const order = temp
221
+ ? [...vms.filter(m => !full(m)), ...usable.filter(m => m.ondemand.temp && vms.some(v => v.name === m.ondemand.temp.of && full(v))), ...vms.filter(full)]
222
+ : vms.filter(m => !full(m));
223
+ for (const vm of order) {
224
+ const need = { res: me.res, os: null, on: vm.name, from: rc.name, fromOs: OS, root: rootHash(rc.name, root), mem: me.mem, cpu: me.cpu, ...(rule.stayOn && { stayOn: rule.stayOn, rule: rule.text }) };
225
+ try { if ((await call(rc, 'POST', '/place', need, { timeout: 8000 })).machine === vm.name) return vm.name; } catch {}
226
+ }
227
+ return null;
228
+ }
229
+
230
+ // A project's id: the sending machine and the folder, hashed.
231
+ const rootHash = (from, root) => crypto.createHash('sha1').update(`${from}:${root}`).digest('hex').slice(0, 12);
232
+ // The name of a project's copy on a worker, in ~/.dibs/work.
233
+ export const copyKey = (from, root) => `${String(from).replace(/[^\w.-]/g, '_')}-${String(root).replace(/[^\w]/g, '')}`;
234
+
235
+ // The files of the working copy at root (from projectRoot): in git, tracked
236
+ // files plus new ones git doesn't ignore; outside it, the folder minus build
237
+ // output. Secret-looking files stay behind.
238
+ function workingCopy(root, cwd = process.cwd()) {
239
+ let files;
240
+ try {
241
+ files = execFileSync('git', ['ls-files', '-co', '--exclude-standard', '-z'], { cwd: root, encoding: 'utf8', maxBuffer: 256 * 1024 ** 2, stdio: ['ignore', 'pipe', 'ignore'] })
242
+ .split('\0').filter(Boolean);
243
+ } catch {
244
+ files = [];
245
+ const walk = rel => {
246
+ for (const e of fs.readdirSync(path.join(root, rel), { withFileTypes: true })) {
247
+ const p = rel ? `${rel}/${e.name}` : e.name;
248
+ if (e.isDirectory()) { if (!SKIP_DIRS.has(e.name) && (!e.name.startsWith('.') || KEEP_DOT_DIRS.has(e.name))) walk(p); }
249
+ else files.push(p);
250
+ }
251
+ };
252
+ walk('');
253
+ }
254
+ const kept = [], secret = [];
255
+ for (const f of new Set(files)) {
256
+ let st;
257
+ try { st = fs.lstatSync(path.join(root, f)); } catch { continue; } // deleted but still tracked
258
+ if (st.isDirectory()) continue; // a submodule
259
+ (SECRET.test(f) ? secret : kept).push(f);
260
+ }
261
+ const cwdRel = path.relative(root, fs.realpathSync(cwd)).split(path.sep).join('/');
262
+ return { files: kept.sort(), secret, cwdRel };
263
+ }
264
+
265
+ // Paths a job is allowed to touch: relative, inside its folder.
266
+ export function safeRel(p) {
267
+ const n = path.posix.normalize(String(p).split(path.sep).join('/'));
268
+ return n && n !== '.' && !n.startsWith('../') && n !== '..' && !path.posix.isAbsolute(n) && !/^[a-z]:/i.test(n) ? n : null;
269
+ }
270
+
271
+ // dibs run <res> --anywhere | --on <machine>
272
+ export async function remoteRun(o, cfg) {
273
+ const rc = remoteConf();
274
+ if (!rc) {
275
+ if (o.on && o.on !== shortHost()) die(`this machine isn't connected to a coordinator, so it can't reach ${o.on}. Set one up: dibs join <url> <token> (see dibs help)`);
276
+ say('not connected to a coordinator (dibs join), so running here');
277
+ return run(o, cfg);
278
+ }
279
+ if (!o.cmd || !o.cmd.length) die('nothing to run. Use: dibs run <resource> --anywhere -- <command>');
280
+ const res = [...new Set(o.res)];
281
+ if (!res.length) die('name a resource, e.g. dibs run test --anywhere -- npm test');
282
+ const id = identity(o);
283
+ // The project's .dibs.json decides before anything is sent: --on a machine it
284
+ // doesn't allow is refused, and --anywhere stays here rather than go there.
285
+ const rule = readRules(rulesAbove(process.cwd()));
286
+ const refuse = (machine, rule) => {
287
+ const msg = `${rule.text}, so it can't go to ${machine}`;
288
+ if (o.on) die(msg);
289
+ say(`${msg}; running here`);
290
+ return run(o, cfg);
291
+ };
292
+ if (o.on && !ruleAllows(rule, o.on, rc.name)) return refuse(o.on, rule);
293
+ const root = projectRoot();
294
+ // Your home folder, or a folder above it, holds far more than a project, keys included.
295
+ let home = os.homedir();
296
+ try { home = fs.realpathSync(home); } catch {}
297
+ if (root === path.parse(root).root || home === root || home.startsWith(root.endsWith(path.sep) ? root : root + path.sep)) {
298
+ const msg = `${root} is your home folder or above it, and dibs won't send all of that to another machine. Run from the project's folder`;
299
+ if (o.on && o.on !== rc.name) die(msg);
300
+ if (!o.on) say(`${msg}; running here`);
301
+ return run(o, cfg);
302
+ }
303
+ // Every .dibs.json that applies, including the ones inside the copy that
304
+ // would be sent, makes the rule the coordinator and the worker enforce too.
305
+ const wc = workingCopy(root);
306
+ const all = readRules([...rulesAbove(process.cwd()), ...wc.files.filter(isRuleFile).map(f => path.join(root, f))]);
307
+ if (o.on && !ruleAllows(all, o.on, rc.name)) return refuse(o.on, all);
308
+ const { mem, cpu } = jobSize(cfg, res, o);
309
+ const need = {
310
+ res, os: needsOs(cfg, res), on: o.on || null, from: rc.name, fromOs: OS, root: rootHash(rc.name, root), mem, cpu,
311
+ askedCpu: o.cpu ?? null, // what --cpu said; cpu is the resource's guess, which never makes a bigger VM
312
+ ...(all.stayOn && { stayOn: all.stayOn, rule: all.text }),
313
+ };
314
+ let place;
315
+ try { place = await call(rc, 'POST', '/place', need, { timeout: 8000 }); }
316
+ catch (e) {
317
+ if (e.status === 401 && !(o.on && o.on !== rc.name)) { say(`the coordinator refused this machine: ${e.message}. Running here`); return run(o, cfg); }
318
+ if (e.status) die(e.message);
319
+ if (o.on && o.on !== rc.name) die(`can't reach the coordinator at ${rc.url} (${e.message}), so the job didn't go to ${o.on}`, LOST);
320
+ say(`can't reach the coordinator at ${rc.url} (${e.message}); running here`);
321
+ return run(o, cfg);
322
+ }
323
+ if (place.machine === rc.name) {
324
+ // --on another machine that the coordinator sent back here says why (an on-demand VM it can't find).
325
+ if (o.on !== rc.name) say(`running here: ${place.why}`);
326
+ return run(o, cfg);
327
+ }
328
+
329
+ // The coordinator honors the rule too, but the code is ours to keep.
330
+ if (!ruleAllows(all, place.machine, rc.name)) return refuse(place.machine, all);
331
+ const bring = o.bring.map(p => safeRel(p) ?? die(`--bring takes a path inside this folder, not ${p}`));
332
+ let buf;
333
+ try { buf = tarCreate(root, wc.files); }
334
+ catch (e) { if (e.status === 413) die(`the working copy is ${e.message}. Ignore build output in .gitignore`); throw e; }
335
+ if (wc.secret.length) say(`kept ${wc.secret.length} secret-looking file${wc.secret.length > 1 ? 's' : ''} on this machine: ${wc.secret.slice(0, 4).join(', ')}${wc.secret.length > 4 ? ', ...' : ''}`);
336
+
337
+ const job = await call(rc, 'POST', '/jobs', {
338
+ ...need, machine: place.machine, cmd: o.cmd, cwdRel: wc.cwdRel, files: wc.files, bring,
339
+ who: id.who, agent: id.agent, label: id.label, purpose: o.purpose || '', prio: o.prio, by: o.by, est: o.est,
340
+ disk: o.disk, ports: o.ports, repo: projectKey(process.cwd()), // its project, which one-per-project resources go by there
341
+ // Decided here: the worker isn't in a Claude Code session, but this end, which waits for it, may be.
342
+ ...((o.maxWait ?? defaultMaxWait()) === Infinity ? { wait: true } : { maxWait: o.maxWait }),
343
+ askedMem: o.mem ?? null, // what --mem said; need.mem is the resource default when it said nothing
344
+ }).catch(e => die(`the coordinator refused the job: ${e.message}`, e.status ? 2 : LOST));
345
+ await call(rc, 'PUT', `/jobs/${job.id}/bundle`, buf, { timeout: 300e3 })
346
+ .catch(e => die(`couldn't send the working copy: ${e.message}`, LOST));
347
+ say(`job ${job.id} goes to ${job.machine}, ${place.why} (sent ${wc.files.length} files, ${size(buf.length)})`);
348
+ return follow(rc, job.id, bring);
349
+ }
350
+
351
+ // Exiting right after a write to a pipe drops whatever hasn't drained yet.
352
+ const drained = () => Promise.all([process.stdout, process.stderr].map(s => new Promise(r => s.write('', r))));
353
+
354
+ // How long a sender waits, after a coordinator restart, for the machine running
355
+ // its job to check in and hand it over again. A worker retries every 5s, and an
356
+ // on-demand VM's needs its forward started again.
357
+ const REATTACH = 2 * 6e4;
358
+ // Stream a job's output until it ends, then bring its files home and exit with its code.
359
+ async function follow(rc, jobId, bring) {
360
+ let next = 0, failingSince = 0, cancelling = 0, started = false, unknownSince = 0;
361
+ // Lost before the job started, it's safe to send again (76); after, it may have run (77).
362
+ const lost = () => (started ? MAYBE_RAN : LOST);
363
+ const cancel = async () => {
364
+ if (cancelling) process.exit(130); // a second Ctrl-C stops waiting
365
+ cancelling = now();
366
+ say(`stopping job ${jobId}...`);
367
+ await call(rc, 'POST', `/jobs/${jobId}/cancel`, {}).catch(() => {});
368
+ };
369
+ for (const sig of SIGNALS) process.on(sig, cancel);
370
+ for (;;) {
371
+ let r;
372
+ try {
373
+ r = await call(rc, 'GET', `/jobs/${jobId}/out?after=${next}`, undefined, { timeout: 30e3 });
374
+ failingSince = 0; unknownSince = 0;
375
+ } catch (e) {
376
+ // A coordinator that restarted forgets every job until the machine running
377
+ // it checks in again (src/serve.mjs adopt). Wait for that; a job never
378
+ // picked up again was lost with the old coordinator.
379
+ if (e.status === 404) {
380
+ if (!unknownSince) say(`the coordinator restarted and doesn't know job ${jobId} yet; waiting for the machine running it to check in again`);
381
+ unknownSince ||= now();
382
+ if (now() - unknownSince > REATTACH) die(`the coordinator restarted and no machine picked job ${jobId} up again in ${Math.round(REATTACH / 1000)}s. ${started ? 'It may have run: check before running it again' : "It hadn't started: it's safe to send again"}`, lost());
383
+ await sleep(2000);
384
+ continue;
385
+ }
386
+ if (e.status === 401 || e.status === 403) die(`the coordinator stopped accepting this machine (${e.message}). Job ${jobId} was stopped${started ? ' after it started' : ' before it started'}`, lost());
387
+ failingSince ||= now();
388
+ if (now() - failingSince > 60e3) die(`lost the coordinator at ${rc.url} for a minute (${e.message}). Job ${jobId} ${started ? 'may still be running; check before running it again' : "hadn't started"}. See dibs machines`, lost());
389
+ await sleep(2000);
390
+ continue;
391
+ }
392
+ if (r.gap) process.stderr.write(`\ndibs: (${size(r.gap)} of output dropped; the coordinator keeps the last 16M)\n`);
393
+ for (const [s, d] of r.chunks) (s === 2 ? process.stderr : process.stdout).write(Buffer.from(d, 'base64'));
394
+ next = r.next;
395
+ if (r.state === 'running' || r.chunks.length) started = true;
396
+ if (r.state === 'done') {
397
+ if (r.why) say(r.why);
398
+ if (r.artifacts && bring.length) {
399
+ try {
400
+ const got = tarExtract(process.cwd(), await call(rc, 'GET', `/jobs/${jobId}/artifacts`, undefined, { raw: true, timeout: 300e3 }), bring);
401
+ say(got.length ? `brought back: ${bring.join(', ')}` : `nothing came back at ${bring.join(', ')}`);
402
+ }
403
+ catch (e) { say(`couldn't bring back ${bring.join(', ')}: ${e.message}`); }
404
+ }
405
+ await drained();
406
+ process.exit(cancelling ? 130 : r.code);
407
+ }
408
+ if (cancelling && now() - cancelling > 15e3) die(`job ${jobId} didn't confirm it stopped; see dibs machines`, 130);
409
+ }
410
+ }
411
+
412
+ // Where the Tailscale CLI may be: on PATH, or inside the Mac app.
413
+ export const TS_CLI = ['tailscale', '/Applications/Tailscale.app/Contents/MacOS/Tailscale'];
414
+ // How long a joiner listens for coordinators answering its broadcast, and gives each a hello.
415
+ const LOOKUP_MS = 1500, HELLO_MS = 2500;
416
+ // Tailscale peers asked at most: a big tailnet is asked about the machines it has online, not every one.
417
+ const MAX_PEERS = 64;
418
+
419
+ // This machine's Tailscale peers that are online, as IPv4 addresses. DIBS_TAILSCALE
420
+ // names the CLI to ask instead (none: there's no Tailscale), so tests never reach a real tailnet.
421
+ function tailnetPeers() {
422
+ const env = process.env.DIBS_TAILSCALE;
423
+ if (env === 'none') return [];
424
+ for (const cli of env ? [env] : TS_CLI) {
425
+ try {
426
+ const st = JSON.parse(execFileSync(cli, ['status', '--json'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], timeout: 5000, maxBuffer: 16 * 1024 ** 2 }));
427
+ return Object.values(st.Peer || {}).filter(p => p.Online).map(p => (p.TailscaleIPs || []).find(ip => /^100\.\d+\.\d+\.\d+$/.test(ip))).filter(Boolean).slice(0, MAX_PEERS);
428
+ } catch {}
429
+ }
430
+ return [];
431
+ }
432
+
433
+ // Coordinators with an open pairing code on this network: a UDP broadcast on every
434
+ // interface (and loopback), answered with where to reach them. DIBS_PAIR_PORT moves it off 7420.
435
+ function lookup() {
436
+ const port = Number(process.env.DIBS_PAIR_PORT) || DEFAULT_PORT;
437
+ const targets = new Set(['255.255.255.255', '127.0.0.1']);
438
+ for (const list of Object.values(os.networkInterfaces())) for (const a of list || []) {
439
+ if ((a.family !== 'IPv4' && a.family !== 4) || a.internal || !a.netmask) continue;
440
+ const ip = a.address.split('.').map(Number), mask = a.netmask.split('.').map(Number);
441
+ targets.add(ip.map((x, i) => (x & mask[i]) | (~mask[i] & 255)).join('.'));
442
+ }
443
+ return new Promise(resolve => {
444
+ const found = new Set();
445
+ const sock = dgram.createSocket('udp4');
446
+ const done = () => { try { sock.close(); } catch {} resolve([...found]); };
447
+ sock.on('error', done);
448
+ sock.on('message', (msg, from) => {
449
+ try {
450
+ const r = JSON.parse(String(msg));
451
+ if (r.t !== 'dibs-coordinator-v1' || !Number.isInteger(r.port)) return;
452
+ for (const u of Array.isArray(r.urls) ? r.urls : []) if (typeof u === 'string' && /^http:\/\/[\w.:[\]-]+$/.test(u)) found.add(u);
453
+ found.add(`http://${from.address}:${r.port}`);
454
+ } catch {}
455
+ });
456
+ sock.bind(() => {
457
+ sock.setBroadcast(true);
458
+ for (const tgt of targets) sock.send(FIND, port, tgt, () => {});
459
+ setTimeout(done, LOOKUP_MS);
460
+ });
461
+ });
462
+ }
463
+
464
+ // Which of these coordinators holds the code: each is asked to prove it (src/serve.mjs
465
+ // /pair/hello) before the code goes anywhere, so a machine that only answers learns nothing.
466
+ async function holder(urls, code) {
467
+ const key = codeKey(code);
468
+ const tries = urls.map(async url => {
469
+ const nj = crypto.randomBytes(32).toString('base64url');
470
+ const r = await call({ url, token: '' }, 'POST', '/pair/hello', { n: nj }, { timeout: HELLO_MS });
471
+ if (typeof r?.nc !== 'string' || !Array.isArray(r.proofs) || !r.proofs.includes(codeProof(key, nj, r.nc))) throw new Error('not this one');
472
+ return { url, name: r.name };
473
+ });
474
+ try { return await Promise.any(tries); } catch { return null; }
475
+ }
476
+
477
+ // dibs join <code> [--at <address>]: the one step after dibs pair --machine on the coordinator.
478
+ async function joinWithCode(o, code) {
479
+ const name = o.name || shortHost();
480
+ let urls, where;
481
+ if (o.at) {
482
+ let u;
483
+ try { u = new URL(/^https?:\/\//.test(o.at) ? o.at : `http://${o.at}`); } catch { die(`can't read ${o.at} as an address`); }
484
+ if (!u.port && u.protocol === 'http:') u.port = String(DEFAULT_PORT);
485
+ urls = [u.origin];
486
+ where = u.origin;
487
+ } else {
488
+ const net = await lookup(), peers = tailnetPeers();
489
+ urls = [...new Set([...net, ...peers.map(ip => `http://${ip}:${DEFAULT_PORT}`)])];
490
+ where = `this network${net.length ? ` (${net.length} answered)` : ''}${peers.length ? ` and ${peers.length} Tailscale peer${peers.length === 1 ? '' : 's'}` : ''}`;
491
+ }
492
+ const found = urls.length ? await holder(urls, code) : null;
493
+ if (!found) die(`no coordinator holding that code answered on ${where}. Is the code still open (dibs pair --list on the coordinator)? If the coordinator is on another network, give its address: dibs join ${normCode(code).replace(/^(.{4})/, '$1-')} --at <address>`, 1);
494
+ let r;
495
+ try { r = await call({ url: found.url, token: '' }, 'POST', '/pair/join', { code: normCode(code), name }, { timeout: 8000 }); }
496
+ catch (e) { die(e.status ? `the coordinator at ${found.url} refused: ${e.message}` : `can't reach ${found.url}: ${e.message}`, e.status ? (e.status === 401 ? 1 : 2) : LOST); }
497
+ const rc = { url: found.url, token: r.token, name: r.name };
498
+ saveRemote(rc);
499
+ logChange('join', { url: found.url, code: true }); // never the code or the token
500
+ console.log(`joined ${found.name || 'the coordinator'} at ${found.url} as ${r.name} (coordinator dibs ${r.version})`);
501
+ console.log(` take jobs on this machine: dibs service install worker (or run dibs worker in a terminal)`);
502
+ console.log(` send a job: dibs run test --anywhere -- npm test`);
503
+ }
504
+
505
+ // dibs join <url> <token>, or dibs join <code>: connect this machine to a coordinator.
506
+ export async function join(o) {
507
+ if (o.res.length === 1 && isCode(o.res[0])) return joinWithCode(o, o.res[0]);
508
+ if (o.at) die('--at goes with a pairing code: dibs join <code> --at <address>');
509
+ const [url, token] = o.res; // the two words that aren't flags
510
+ if (!url || !token) die('dibs join <code> (from dibs pair --machine on the coordinator), or dibs join <url> <token> (from dibs invite)');
511
+ let u;
512
+ try { u = new URL(/^https?:\/\//.test(url) ? url : `http://${url}`); } catch { die(`can't read ${url} as an address`); }
513
+ if (!u.port && u.protocol === 'http:') u.port = String(DEFAULT_PORT);
514
+ logChange('join', { url: u.origin }); // never the token
515
+ const rc = { url: u.origin, token, name: o.name || remoteConf(() => null)?.name || shortHost() }; // joining again is the fix for a broken file
516
+ let hello;
517
+ try { hello = await call(rc, 'GET', '/hello', undefined, { timeout: 8000 }); }
518
+ catch (e) { die(e.status === 401 ? `the coordinator rejected that token: ${e.message}` : `can't reach ${rc.url}: ${e.message}`, e.status ? 2 : LOST); }
519
+ saveRemote(rc);
520
+ console.log(`joined ${rc.url} as ${rc.name} (coordinator dibs ${hello.version}, ${hello.machines.length} machine${hello.machines.length === 1 ? '' : 's'} online${hello.machines.length ? `: ${hello.machines.join(', ')}` : ''})`);
521
+ console.log(` take jobs on this machine: dibs service install worker (or run dibs worker in a terminal)`);
522
+ console.log(` send a job: dibs run test --anywhere -- npm test`);
523
+ }
524
+
525
+ const sendsNote = (r, name) => { const s = r.sends?.[name]; return !s ? '' : s.length ? `sends only ${s.join(',')}` : 'sends nothing'; };
526
+
527
+ // dibs machines: every machine in the group, and the jobs moving between them.
528
+ export async function machines(o) {
529
+ const rc = remoteConf();
530
+ // A read, not a mistake: outside a group there's nothing to list (exit 0, not 2 as before 2026-11-03).
531
+ if (!rc) {
532
+ if (o.json) return console.log(JSON.stringify({ group: false, machines: [], jobs: [] }, null, 1));
533
+ return console.log("this machine isn't in a group. dibs pair --machine on a coordinator adds one (then dibs join <code> here); dibs serve makes this one the coordinator.");
534
+ }
535
+ let r;
536
+ try { r = await call(rc, 'GET', '/machines', undefined, { timeout: 8000 }); }
537
+ catch (e) { die(`can't reach the coordinator at ${rc.url}: ${e.message}`, LOST); }
538
+ if (o.json) return console.log(JSON.stringify(r, null, 1));
539
+ const t = r.now;
540
+ const here = copyKey(rc.name, rootHash(rc.name, projectRoot()));
541
+ const live = r.machines.filter(m => !m.lost);
542
+ const moving = r.jobs.filter(j => j.state !== 'done');
543
+ console.log(bold(!r.machines.length ? 'No machines are taking jobs yet. On each one: dibs service install worker'
544
+ : `${live.length} machine${live.length === 1 ? '' : 's'} taking jobs${live.length < r.machines.length ? `, ${r.machines.length - live.length} not reporting` : ''}`
545
+ + `${moving.length ? `, ${moving.length} job${moving.length === 1 ? '' : 's'} moving between them` : ''}.`));
546
+ const rows = r.machines.map(m => {
547
+ const lines = Object.entries(m.busy || {}).filter(([, b]) => b.used || b.waiting)
548
+ .map(([k, b]) => `${k} ${b.used} of ${b.slots}${b.waiting ? `, ${b.waiting} waiting` : ''}`);
549
+ const perCore = m.load / (m.cores || 1);
550
+ const vm = m.ondemand;
551
+ // A sleeping VM has no readings of its own; its row says what it is instead.
552
+ if (vm && vm.state !== 'running')
553
+ return [m.name, m.os, m.cores, vm.problem ? 'unusable' : vm.cantWake ? "can't wake" : vm.state, '-', '-', vm.problem ? `on-demand ${vm.provider} VM, can't be used: ${vm.problem}`
554
+ : vm.cantWake ? `can't wake: ${vm.cantWake.why}, checks again ${when(vm.cantWake.until)}`
555
+ : vm.temp ? `${vm.provider} VM made for jobs too big for ${vm.temp.of} (up to ${vm.temp.max}), deleted after`
556
+ : `${vm.state === 'asleep' ? `on-demand ${vm.provider} VM: a job sent here wakes it (${vm.resumeMs ? `~${Math.round(vm.resumeMs / 1000)}s` : 'under a minute'})` : `on-demand ${vm.provider} VM`}`];
557
+ const notes = [vm ? `${vm.temp ? `temporary ${vm.provider} VM, deleted` : `on-demand ${vm.provider} VM, stops`} after ${dur(vm.idleStop)} idle` : '', m.lost ? `NOT REPORTING (last heard ${dur(t - m.seen)} ago)` : '', m.name !== rc.name && m.copies?.[here] ? `has this project${m.copies[here].free ? '' : ' (in use)'}` : '',
558
+ m.only ? `only takes ${m.only.join(',')}` : '', sendsNote(r, m.name), m.version !== r.version ? `runs dibs ${m.version}` : ''].filter(Boolean);
559
+ return [m.name + (m.name === rc.name ? ' (here)' : ''), m.os, m.cores, perCore < 0.5 ? 'quiet' : perCore < 1 ? 'busy' : 'very busy', `${m.memFree}%`,
560
+ m.diskFree == null ? 'disk unknown' : gb(m.diskFree).replace(/G$/, ' GB'), [lines.join('; ') || '-', ...notes].join(' ')];
561
+ });
562
+ if (rows.length) {
563
+ const head = ['', 'system', 'cores', 'busy', 'memory free', 'disk free', 'in use'];
564
+ const w = head.map((h, i) => Math.max(h.length, ...rows.map(x => String(x[i]).length)));
565
+ console.log();
566
+ for (const x of [head, ...rows]) console.log(` ${x.map((c, i) => (i === x.length - 1 ? String(c) : String(c).padEnd(w[i]))).join(' ')}`.trimEnd());
567
+ }
568
+ // A coordinator that just started hears from this machine's worker a few seconds later; until then it isn't in the list.
569
+ if (r.started && !r.machines.some(m => m.name === rc.name))
570
+ console.log(` ${rc.name} (here) worker hasn't checked in since the coordinator started at ${clock(r.started)}`);
571
+ for (const m of r.invited || [])
572
+ console.log(` ${m.name.padEnd(16)} ${m.joined ? 'no worker running since the coordinator started' : `invited ${dur(t - m.invited)} ago, hasn't joined yet`}`
573
+ + `${r.limits?.[m.name] ? ` only takes ${r.limits[m.name].join(',')}` : ''}${sendsNote(r, m.name) ? ` ${sendsNote(r, m.name)}` : ''}`);
574
+ const removed = (r.removed || []).filter(m => t - m.at < 24 * 3.6e6);
575
+ if (removed.length) console.log(` removed in the last day: ${removed.map(m => `${m.name} (${dur(t - m.at)} ago)`).join(', ')}`);
576
+ const jobs = r.jobs.filter(j => j.state !== 'done' || t - j.doneAt < 5 * 6e4);
577
+ if (jobs.length) {
578
+ console.log(`\n${bold('Jobs sent between machines')}`);
579
+ for (const j of jobs)
580
+ console.log(` #${String(j.id).padEnd(3)} ${(j.agent || j.who).padEnd(20)} ${`${j.from} -> ${j.machine}`.padEnd(22)} ${(j.state === 'done' ? `done, exit ${j.code}` : j.state).padEnd(12)}`
581
+ + ` ${dur(t - j.created).padStart(6)} ${j.res.join(',')}${j.purpose ? ` "${j.purpose}"` : ''} ${dim(j.cmd.join(' ').slice(0, 40))}`);
582
+ }
583
+ console.log(`\n${dim(`Coordinator: ${rc.url}, dibs ${r.version}. Send a job: dibs run <resource> --anywhere -- <command>`)}`);
584
+ }