@dibssoftware/dibs 0.0.0-stage → 0.0.179

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 (75) hide show
  1. package/CHANGELOG.md +594 -0
  2. package/LICENSE +670 -0
  3. package/README.md +85 -2
  4. package/bin/dibs-guard.mjs +7 -0
  5. package/bin/dibs.mjs +548 -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/reference.md +157 -0
  13. package/docs/relay.md +196 -0
  14. package/docs/releasing.md +27 -0
  15. package/docs/scheduling.md +163 -0
  16. package/docs/simulators.md +17 -0
  17. package/package.json +45 -4
  18. package/skills/dibs/SKILL.md +183 -0
  19. package/src/acquire.mjs +700 -0
  20. package/src/admin.mjs +145 -0
  21. package/src/agents.mjs +145 -0
  22. package/src/alerts.mjs +499 -0
  23. package/src/answers.mjs +65 -0
  24. package/src/board.mjs +202 -0
  25. package/src/broker.mjs +369 -0
  26. package/src/commands.mjs +810 -0
  27. package/src/config.mjs +324 -0
  28. package/src/connect.mjs +106 -0
  29. package/src/cool.mjs +160 -0
  30. package/src/diskwarn.mjs +154 -0
  31. package/src/events.mjs +96 -0
  32. package/src/files.mjs +1123 -0
  33. package/src/guard.mjs +613 -0
  34. package/src/history.mjs +247 -0
  35. package/src/hogs.mjs +227 -0
  36. package/src/later.mjs +487 -0
  37. package/src/measure.mjs +262 -0
  38. package/src/news.mjs +101 -0
  39. package/src/nodecheck.mjs +17 -0
  40. package/src/notes.mjs +171 -0
  41. package/src/notices.mjs +160 -0
  42. package/src/ondemand.mjs +572 -0
  43. package/src/overlap.mjs +151 -0
  44. package/src/override.mjs +360 -0
  45. package/src/owner.mjs +30 -0
  46. package/src/plain.mjs +470 -0
  47. package/src/platform.mjs +357 -0
  48. package/src/preempt.mjs +438 -0
  49. package/src/primer.mjs +89 -0
  50. package/src/proc.mjs +99 -0
  51. package/src/progress.mjs +187 -0
  52. package/src/qr.mjs +204 -0
  53. package/src/questions.mjs +389 -0
  54. package/src/quota.mjs +81 -0
  55. package/src/reads.mjs +54 -0
  56. package/src/relay.mjs +779 -0
  57. package/src/remote.mjs +584 -0
  58. package/src/reset.mjs +127 -0
  59. package/src/schedule.mjs +1020 -0
  60. package/src/scratch.mjs +61 -0
  61. package/src/serve.mjs +742 -0
  62. package/src/service.mjs +221 -0
  63. package/src/shard.mjs +59 -0
  64. package/src/simctl.mjs +42 -0
  65. package/src/simpool.mjs +258 -0
  66. package/src/state.mjs +201 -0
  67. package/src/stats.mjs +328 -0
  68. package/src/style.mjs +44 -0
  69. package/src/talk.mjs +702 -0
  70. package/src/thin.sh +130 -0
  71. package/src/trust.mjs +152 -0
  72. package/src/util.mjs +184 -0
  73. package/src/version.mjs +2 -0
  74. package/src/web.mjs +1119 -0
  75. package/src/worker.mjs +318 -0
package/src/thin.sh ADDED
@@ -0,0 +1,130 @@
1
+ # dibs run and dibs hold, waiting without Node. bin/dibs.mjs starts this as
2
+ # /bin/sh thin.sh <bin/dibs.mjs> run|hold <args>
3
+ # when config.json has "waits": "thin". Node gets in line as this process and
4
+ # runs a job that can start at once; a waiting one comes back here, gets in line
5
+ # again (_enqueue, picking up its place), and this shell blocks on a read from its own FIFO,
6
+ # which costs no CPU and about 1.5 MB, and the broker (src/broker.mjs) writes
7
+ # to it: "out <line>" to print, "go" when it's this waiter's turn, "exit N".
8
+ # On go it execs Node for the run itself, so the pid and start time the lease
9
+ # names stay this process's. Keep it small and POSIX: it runs under dash too.
10
+ B=$1
11
+ shift
12
+ D=${DIBS_HOME:-$HOME/.dibs}
13
+ # How bin/dibs.mjs starts Node (LEAN in src/util.mjs); keep them in step.
14
+ N="node --max-semi-space-size=1"
15
+ F=$D/w/$$
16
+ # First, Node gets in line as this same process (exec): a job that can start now
17
+ # runs in it, Node started once. One that must wait keeps its place and comes
18
+ # back here with DIBS_THIN_RESUME set, to wait as below. On 2026-10-21 starting
19
+ # Node twice (once to get in line, once to run) was 90 ms of every run.
20
+ if [ -z "${DIBS_THIN_RESUME:-}" ]; then
21
+ exec $N "$B" _enqueue $$ "$PPID" "$F" "$@"
22
+ fi
23
+ unset DIBS_THIN_RESUME
24
+ # No FIFO, no thin wait: wait the old way instead.
25
+ { mkdir -p "$D/w" && rm -f "$F" && mkfifo -m 600 "$F"; } 2>/dev/null || exec $N "$B" "$@"
26
+ # Opening the read end blocks until there's a writer, so open a writer of our own first.
27
+ exec 4<>"$F" 3<"$F"
28
+ gone() { exec 3<&- 4>&-; rm -f "$F"; }
29
+ # Anything that goes wrong with a thin wait leaves an event (kind thin) in the
30
+ # history, so it can be found later. why is always one of the words below.
31
+ note() { printf '{"at":%s000,"kind":"thin","why":"%s","id":%s,"shell":%s}\n' "$(date +%s)" "$1" "${id:-0}" $$ >>"$D/events.jsonl" 2>/dev/null; }
32
+
33
+ # Set before getting in line: a signal that comes while Node is at it is
34
+ # acted on once Node is done, and leaves whatever place it made. Its answer,
35
+ # if it gave one, is already in the FIFO: read without our own writer, an
36
+ # empty FIFO is end of file at once rather than a wait.
37
+ id=
38
+ leave() {
39
+ # A signal during `IFS= read` runs this with IFS still empty in bash, and $N
40
+ # would then be one word, "node --max...", which isn't a command.
41
+ unset IFS
42
+ [ -z "$id" ] && { exec 4>&-; IFS= read -r r <&3; case $r in go\ *|wait\ *) id=${r#* } ;; esac; }
43
+ $N "$B" _leave "${id:-0}" $$ "$1"
44
+ gone
45
+ exit "$2"
46
+ }
47
+ trap 'leave SIGINT 130' INT
48
+ trap 'leave SIGTERM 143' TERM
49
+ trap 'leave SIGHUP 129' HUP
50
+
51
+ $N "$B" _enqueue $$ "$PPID" "$F" "$@" || { code=$?; trap - INT TERM HUP; [ $code = 70 ] && note 'getting in line crashed'; gone; exit $code; }
52
+ IFS= read -r r <&3
53
+ # From here on only the broker writes, so end of file means it isn't here.
54
+ exec 4>&-
55
+ case $r in
56
+ go\ *|wait\ *) id=${r#* } ;;
57
+ exit\ *) trap - INT TERM HUP; gone; exit "${r#exit }" ;;
58
+ fat) trap - INT TERM HUP; gone; exec $N "$B" "$@" ;;
59
+ *) trap - INT TERM HUP; note 'no answer from getting in line'; gone; exit 70 ;;
60
+ esac
61
+
62
+ # End of file: no broker has this FIFO open. One that's alive hasn't reached
63
+ # us yet (it opens every waiter's FIFO on its next tick), so read again after
64
+ # a pause. One that's dead crashed or was replaced by a release. Only one
65
+ # waiter starts the next, whoever makes the broker.starting folder; the rest
66
+ # wait for it, so 50 waiters don't start 50 Nodes at once. A broker that
67
+ # couldn't be started (broker.broken, less than a minute old), found dead three
68
+ # times in a minute, or missing for GIVE_UP seconds is broken: give the place
69
+ # up for the in-process wait, which picks it up again.
70
+ GIVE_UP=${DIBS_THIN_GIVE_UP:-15}
71
+ broken() { [ -n "$(find "$D/broker.broken" -mmin -1 2>/dev/null)" ]; }
72
+ gap=1 dead= t1= t2=
73
+ nobroker() {
74
+ p=
75
+ read -r p <"$D/broker.pid" 2>/dev/null
76
+ # A liveness hint only: kill -0 sends nothing.
77
+ if [ -n "$p" ] && kill -0 "$p" 2>/dev/null; then
78
+ dead=
79
+ sleep $((gap / 10)).$((gap % 10))
80
+ [ $gap -lt 20 ] && gap=$((gap * 2))
81
+ return 0
82
+ fi
83
+ t=$(date +%s)
84
+ if [ -z "$dead" ]; then
85
+ dead=$t
86
+ [ -n "$t1" ] && [ $((t - t1)) -lt 60 ] && { gaveup='broker died three times in a minute'; return 1; }
87
+ t1=$t2 t2=$t
88
+ fi
89
+ [ $((t - dead)) -ge "$GIVE_UP" ] && { gaveup='no broker for too long'; return 1; }
90
+ broken && { gaveup='no broker could be started'; return 1; }
91
+ if mkdir "$D/broker.starting" 2>/dev/null; then
92
+ echo $$ >"$D/broker.starting/pid"
93
+ note 'broker gone, starting another'
94
+ $N "$B" _rewait
95
+ code=$?
96
+ rm -rf "$D/broker.starting"
97
+ return $code
98
+ fi
99
+ # A starter killed before it finished would hold the folder for good.
100
+ s=
101
+ read -r s <"$D/broker.starting/pid" 2>/dev/null
102
+ [ -n "$s" ] && ! kill -0 "$s" 2>/dev/null && rm -rf "$D/broker.starting"
103
+ sleep 0.$(($$ % 9 + 1))
104
+ }
105
+
106
+ [ "${r%% *}" = go ] || while :; do
107
+ if IFS= read -r line <&3; then
108
+ gap=1 dead=
109
+ case $line in
110
+ go) break ;;
111
+ out\ *) printf '%s\n' "${line#out }" >&2 ;;
112
+ exit\ *) gone; exit "${line#exit }" ;;
113
+ # No broker could be started: Node waits instead, and picks the kept place up.
114
+ fat) trap - INT TERM HUP; gone; exec $N "$B" "$@" ;;
115
+ esac
116
+ else
117
+ nobroker && continue
118
+ trap - INT TERM HUP
119
+ note "$gaveup: waiting in Node"
120
+ $N "$B" _leave "$id" $$ keep
121
+ gone
122
+ exec $N "$B" "$@"
123
+ fi
124
+ done
125
+
126
+ gone
127
+ trap - INT TERM HUP
128
+ v=$1
129
+ shift
130
+ exec $N "$B" "$v" --lease "$id" "$@"
package/src/trust.mjs ADDED
@@ -0,0 +1,152 @@
1
+ // Who may talk to the coordinator, and where a job may go.
2
+ //
3
+ // The coordinator keeps a token per machine in ~/.dibs/machines.json (only
4
+ // their hashes), so each machine can be removed on its own and can't speak as
5
+ // another. The token in its own remote.json is the admin token: it works only
6
+ // over loopback, so it never helps anyone on another machine.
7
+ //
8
+ // A project says where it may go with a .dibs.json file, {"stayOn": ["mini"]},
9
+ // in its folder or any folder above it. Every clone carries the rule.
10
+ import fs from 'node:fs';
11
+ import path from 'node:path';
12
+ import crypto from 'node:crypto';
13
+ import { HOME } from './config.mjs';
14
+ import { now } from './util.mjs';
15
+
16
+ export const MACHINES = path.join(HOME, 'machines.json');
17
+ export const NAME = /^[A-Za-z0-9][\w.-]{0,62}$/;
18
+ const RULE_FILE = '.dibs.json';
19
+
20
+ // dibs pair --machine: a one-time code a new machine joins with. The same codebook as
21
+ // dibs pair's: 8 Crockford base32 characters, 40 bits, 10 minutes, one use.
22
+ const CODE_CHARS = '0123456789ABCDEFGHJKMNPQRSTVWXYZ';
23
+ const CODE_LEN = 8;
24
+ export const CODE_LIFE = 10 * 6e4;
25
+ export const normCode = s => String(s || '').toUpperCase().replace(/[^0-9A-Z]/g, '').replace(/O/g, '0').replace(/[IL]/g, '1');
26
+ // What a word on `dibs join`'s line looks like when it's a code, not an address: ABCD-EFGH.
27
+ export const isCode = s => /^[0-9A-Za-z]{4}-?[0-9A-Za-z]{4}$/.test(String(s || ''));
28
+ export function newCode() {
29
+ let c = '';
30
+ for (let i = 0; i < CODE_LEN; i++) c += CODE_CHARS[crypto.randomInt(CODE_CHARS.length)];
31
+ return `${c.slice(0, 4)}-${c.slice(4)}`;
32
+ }
33
+ // The coordinator keeps this, not the code.
34
+ export const codeKey = code => crypto.createHash('sha256').update(`dibs-pair-machine-v1\0${normCode(code)}`).digest();
35
+ // A coordinator proves it holds the code before the joiner sends it: HMAC over both
36
+ // sides' random nonces. Anything else answering on the network learns only a nonce.
37
+ export const codeProof = (key, nj, nc) => crypto.createHmac('sha256', key).update(`dibs-pair-machine-proof-v1\0${nj}\0${nc}`).digest('base64url');
38
+
39
+ const hash = t => crypto.createHash('sha256').update(String(t)).digest();
40
+ const same = (a, b) => a.length === b.length && crypto.timingSafeEqual(a, b);
41
+ const loopback = addr => /^(127\.|::1$|::ffff:127\.)/.test(String(addr || ''));
42
+
43
+ export function loadRegistry(file = MACHINES) {
44
+ let r = {};
45
+ try { r = JSON.parse(fs.readFileSync(file, 'utf8')); }
46
+ catch (e) { if (e.code !== 'ENOENT') throw new Error(`${file} can't be read (${e.message}). Fix or delete it; deleting it removes every invited machine`); }
47
+ return { machines: r.machines || {}, removed: r.removed || {}, limits: r.limits || {}, sends: r.sends || {} };
48
+ }
49
+
50
+ export function makeTrust({ token, file = MACHINES }) {
51
+ const reg = loadRegistry(file);
52
+ const admin = hash(token);
53
+ const save = () => {
54
+ fs.mkdirSync(path.dirname(file), { recursive: true });
55
+ const tmp = `${file}.${process.pid}`;
56
+ fs.writeFileSync(tmp, JSON.stringify(reg, null, 2) + '\n', { mode: 0o600 });
57
+ fs.renameSync(tmp, file);
58
+ fs.chmodSync(file, 0o600);
59
+ };
60
+ const t = {
61
+ reg,
62
+ // { admin } or { name, hash } for a good token; { error } otherwise.
63
+ who(req) {
64
+ const got = String(req.headers.authorization || '').replace(/^Bearer /, '');
65
+ if (!got) return { error: 'no token' };
66
+ const h = hash(got);
67
+ if (same(h, admin)) return loopback(req.socket?.remoteAddress) ? { admin: true }
68
+ : { error: "that is the coordinator's own token, and it only works on the coordinator's machine. On the coordinator, run dibs invite <name> and use the join line it prints" };
69
+ for (const [name, m] of Object.entries(reg.machines)) if (same(h, Buffer.from(m.hash, 'hex'))) return { name, hash: m.hash };
70
+ for (const [name, r] of Object.entries(reg.removed))
71
+ if (r.hash && same(h, Buffer.from(r.hash, 'hex'))) return { error: r.why || `${name} was removed from the group` };
72
+ return { error: 'bad token' };
73
+ },
74
+ // Still the token this machine has now (not kicked or re-invited since).
75
+ current: who => who.admin || reg.machines[who.name]?.hash === who.hash,
76
+ has: name => !!reg.machines[name],
77
+ // extra: { paired } for a machine that joined with a code from dibs pair --machine.
78
+ invite(name, extra = {}) {
79
+ const token = `dibs_${crypto.randomBytes(24).toString('base64url')}`;
80
+ reg.machines[name] = { hash: hash(token).toString('hex'), invited: now(), joined: null, ...extra };
81
+ delete reg.removed[name];
82
+ save();
83
+ return token;
84
+ },
85
+ revoke(name, why) {
86
+ const m = reg.machines[name];
87
+ if (!m) return false;
88
+ reg.removed[name] = { at: now(), hash: m.hash, why };
89
+ delete reg.machines[name];
90
+ save();
91
+ return true;
92
+ },
93
+ // undefined leaves that half as it was; null lifts it.
94
+ limit(name, only, sends) {
95
+ if (only) reg.limits[name] = only; else if (only === null) delete reg.limits[name];
96
+ if (sends) reg.sends[name] = sends; else if (sends === null) delete reg.sends[name];
97
+ save();
98
+ },
99
+ only: name => reg.limits[name] || null,
100
+ // What a machine may send to other machines: a list of resources ([] for nothing), or null for anything.
101
+ sends: name => reg.sends[name] || null,
102
+ joined(name) {
103
+ const m = reg.machines[name];
104
+ if (m && !m.joined) { m.joined = now(); save(); }
105
+ },
106
+ };
107
+ return t;
108
+ }
109
+
110
+ // Why machine w may not run this job (its limit, or the project's rule), or null.
111
+ export function allowed(w, need) {
112
+ if (!need.res || w.name === need.from) return null; // the sender's own machine is always fine
113
+ if (need.stayOn && !need.stayOn.includes(w.name)) return `${need.rule || 'the project rule'}, so not ${w.name}`;
114
+ if (w.only && !need.res.every(r => w.only.includes(r))) return `${w.name} only takes ${w.only.join(', ')} jobs (dibs limit on the coordinator)`;
115
+ return null;
116
+ }
117
+
118
+ // The .dibs.json files that apply to a folder: its own and every one above it.
119
+ export function rulesAbove(dir) {
120
+ const found = [];
121
+ for (let d = path.resolve(dir); ; d = path.dirname(d)) {
122
+ const f = path.join(d, RULE_FILE);
123
+ if (fs.existsSync(f)) found.push(f);
124
+ if (path.dirname(d) === d) return found;
125
+ }
126
+ }
127
+ export const isRuleFile = f => path.basename(f) === RULE_FILE;
128
+
129
+ // The rule several .dibs.json files make together: a job may go only where all
130
+ // of them allow. A file that can't be read keeps the project home.
131
+ export function readRules(files) {
132
+ let stayOn = null;
133
+ const used = [], broken = [];
134
+ for (const f of new Set(files)) {
135
+ let list;
136
+ try {
137
+ const r = JSON.parse(fs.readFileSync(f, 'utf8'));
138
+ if (r.stayOn === undefined) continue;
139
+ if (!Array.isArray(r.stayOn) || !r.stayOn.every(x => typeof x === 'string')) throw new Error('stayOn must be a list of machine names');
140
+ list = r.stayOn;
141
+ } catch (e) { broken.push(`${f} (${e.message})`); list = []; }
142
+ used.push(f);
143
+ stayOn = stayOn ? stayOn.filter(x => list.includes(x)) : [...list];
144
+ }
145
+ if (!stayOn) return { stayOn: null };
146
+ const where = stayOn.length ? `keeps this project on ${stayOn.join(', ')}` : 'keeps this project on the machine it lives on';
147
+ const text = broken.length ? `${broken.join(' and ')} can't be read, so dibs ${where}`
148
+ : `${used.join(' and ')} ${used.length > 1 ? where.replace(/^keeps/, 'keep') : where}`;
149
+ return { stayOn, text };
150
+ }
151
+
152
+ export const ruleAllows = (rule, machine, from) => machine === from || !rule.stayOn || rule.stayOn.includes(machine);
package/src/util.mjs ADDED
@@ -0,0 +1,184 @@
1
+ // Parsing and formatting shared by every module. No state, no side effects
2
+ // beyond printing and exiting in die().
3
+ import fs from 'node:fs';
4
+ import os from 'node:os';
5
+
6
+ export const now = () => Date.now();
7
+ // The process that called dibs. A thin waiter's _enqueue (src/broker.mjs) runs
8
+ // under the waiting shell, so it's told the shell's parent instead. Node 22
9
+ // ignores a redefined process.ppid, so it's kept here.
10
+ let parentPid = null;
11
+ export const setCaller = pid => { parentPid = pid; };
12
+ export const callerPid = () => parentPid ?? process.ppid;
13
+ // Subagent types that name no one: Claude Code's built-in kinds. A named
14
+ // agent-team teammate's type is its name ("fix-guard").
15
+ const GENERIC_AGENTS = new Set(['general-purpose', 'Explore', 'Plan', 'claude']);
16
+ // What to call one subagent of a session, beside the session's name: its own
17
+ // name, else the -m reason its job gave, else the start of its id. Empty for
18
+ // a lease no subagent was seen taking.
19
+ export const agentLabel = x => (!x.agentId || x.agentId === 'main' ? ''
20
+ : x.label && x.label !== x.who && !GENERIC_AGENTS.has(x.label) ? x.label
21
+ : x.purpose ? `"${x.purpose}"` : x.agentId.replace(/^a(gent-?)?/, '').slice(0, 8));
22
+ // A lease or wait's holder: session/subagent when a subagent took it, else the
23
+ // usual "who (label)".
24
+ export const holder = (x, tag) => (agentLabel(x) ? `${x.who}/${agentLabel(x)}` : tag(x));
25
+
26
+ // Whether the caller runs inside Claude Code, the only place SendMessage means anything.
27
+ export const inClaudeCode = () => !!(process.env.CLAUDECODE || process.env.CLAUDE_CODE_SESSION_ID);
28
+ export const sleep = ms => new Promise(r => setTimeout(r, ms));
29
+ export const sleepSync = ms => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
30
+
31
+ export function say(msg) { process.stderr.write(`dibs: ${msg}\n`); }
32
+ // Exit 1 (nothing matched) and 75 (not your turn yet) aren't errors, so only the rest are red.
33
+ // Red as in src/style.mjs, kept here so the guard hook loads nothing more.
34
+ const CALM = new Set([0, 1, 75]);
35
+ // dibs web reads the CLI's own functions in its long-lived process, where a
36
+ // die() would take the page down: inside inProcess() it throws instead. Exit 75
37
+ // (a lock busy, try again) answers 503 with a time to retry; anything else is
38
+ // dibs's own trouble on this machine, 500. It used to be 502, which reads as a
39
+ // proxy failing and named nothing to do (2026-11-02).
40
+ const RETRY_AFTER = 2;
41
+ let throwing = 0;
42
+ export function inProcess(fn) {
43
+ throwing++;
44
+ try { return fn(); } finally { throwing--; }
45
+ }
46
+ // The same for a read that awaits: only where nothing else runs in the process
47
+ // meanwhile (src/reads.mjs answers one request at a time).
48
+ export async function inProcessAsync(fn) {
49
+ throwing++;
50
+ try { return await fn(); } finally { throwing--; }
51
+ }
52
+ // What die() last said and the code it exited with, for bin/dibs.mjs's record
53
+ // of a lost job or a crash: a command that exits 76 on its own is neither.
54
+ export let lastDie = '', lastDieCode = null;
55
+ export function die(msg, code = 2) {
56
+ lastDie = String(msg);
57
+ lastDieCode = code;
58
+ if (throwing) throw Object.assign(new Error(msg), { status: code === 75 ? 503 : 500, exitCode: code, ...(code === 75 && { retryAfter: RETRY_AFTER }) });
59
+ const red = !CALM.has(code) && !process.env.NO_COLOR && (!!process.env.FORCE_COLOR || (process.stderr.isTTY && process.env.TERM !== 'dumb'));
60
+ process.stderr.write(`${red ? '\x1b[31mdibs:\x1b[39m' : 'dibs:'} ${msg}\n`);
61
+ process.exit(code);
62
+ }
63
+ // One --notify line (src/commands.mjs notifyOnExit). Best effort: the wait or run it reports on has ended either way.
64
+ export function notifyLine(file, line) {
65
+ try { fs.appendFileSync(file, JSON.stringify(line) + '\n'); } catch {}
66
+ }
67
+ // Said wherever dibs tells an agent to free disk: the person's rule, which the guard enforces (tmpGuard in src/files.mjs).
68
+ export const OFF_LIMITS = "Never delete in another session's /private/tmp/claude-* folder to make room: they're off limits.";
69
+ // A full disk: out of space, or past this user's disk quota.
70
+ export const noSpace = e => e?.code === 'ENOSPC' || e?.code === 'EDQUOT';
71
+ export const fullDisk = e => `the disk is full (${e.code}${e.path ? ` writing ${e.path}` : ''}), so dibs couldn't save its change and nothing changed.`
72
+ + ` Free some disk space, then run the same command again (exit 74). ${OFF_LIMITS}`;
73
+
74
+ // Tests stand in for a full disk with DIBS_FAKE_ENOSPC, a file: while it
75
+ // exists, a write at a step it names (any step, if it names none) fails the
76
+ // way ENOSPC does. Steps: lock (a lock's pid file), state (any state file), notes (the guard's notes).
77
+ export function fakeFull(step) {
78
+ const f = process.env.DIBS_FAKE_ENOSPC;
79
+ if (!f) return;
80
+ let steps;
81
+ try { steps = fs.readFileSync(f, 'utf8').split(/\s+/).filter(Boolean); } catch { return; }
82
+ if (!steps.length || steps.includes(step)) throw Object.assign(new Error(`ENOSPC: no space left on device (DIBS_FAKE_ENOSPC, ${step})`), { code: 'ENOSPC' });
83
+ }
84
+
85
+ // A timestamped line for the logs of long-running services (serve, worker).
86
+ export const log = msg => console.log(`${new Date().toISOString()} ${msg}`);
87
+
88
+ // What ends a dibs process from outside: Ctrl-C, kill, a closed terminal.
89
+ // V8 settings for a dibs that waits or supervises: dozens of them sit idle for
90
+ // hours. A 1 MB young generation (default 16 MB, grown to 3 of them by a poll's
91
+ // garbage) took a waiter from 74 MB of memory to 41 MB on 2026-10-15. Not
92
+ // --lite-mode or --jitless: they turn off WebAssembly, and Node's fetch needs
93
+ // it, so nothing could reach the coordinator. bin/dibs.mjs's exec line and N in
94
+ // src/thin.sh pass the same; keep them in step.
95
+ export const LEAN = ['--max-semi-space-size=1'];
96
+ export const SIGNALS = ['SIGINT', 'SIGTERM', 'SIGHUP'];
97
+ // The exit code a shell gives a process ended by sig.
98
+ export const signalExit = sig => 128 + (os.constants.signals[sig] || 0);
99
+
100
+ export function bytes(s) {
101
+ if (typeof s === 'number') return s;
102
+ const m = String(s).trim().match(/^([\d.]+)\s*([KMGT]?)B?$/i);
103
+ if (!m) die(`can't read size "${s}" (try 4G or 500M)`);
104
+ return parseFloat(m[1]) * { '': 1, K: 1024, M: 1024 ** 2, G: 1024 ** 3, T: 1024 ** 4 }[m[2].toUpperCase()];
105
+ }
106
+
107
+ export function ms(s) {
108
+ if (typeof s === 'number') return s;
109
+ const m = String(s).trim().match(/^([\d.]+)\s*(ms|s|m|h)?$/);
110
+ if (!m) die(`can't read duration "${s}" (try 90s, 8m, 1h)`);
111
+ return parseFloat(m[1]) * { ms: 1, s: 1e3, m: 6e4, h: 3.6e6 }[m[2] || 'm'];
112
+ }
113
+
114
+ // A deadline is a clock time (23:30, 9pm, 9:15am) or a duration from now (20m).
115
+ // A clock time already past today means tomorrow. Without am/pm, 5:00 means
116
+ // whichever of 5:00 and 17:00 comes next, since the board shows 12-hour times.
117
+ export function deadline(s, from = now()) {
118
+ const t = String(s).trim().toLowerCase();
119
+ const m = t.match(/^(\d{1,2})(?::(\d{2}))?\s*(am|pm)?$/);
120
+ if (m && (m[2] || m[3])) {
121
+ let h = Number(m[1]);
122
+ const min = Number(m[2] || 0);
123
+ if (min > 59 || h > 23 || (m[3] && (h < 1 || h > 12))) die(`can't read time "${s}"`);
124
+ if (m[3]) h = h % 12 + (m[3] === 'pm' ? 12 : 0);
125
+ const next = hour => {
126
+ const d = new Date(from); d.setHours(hour, min, 0, 0);
127
+ if (d.getTime() < from - 6e4) d.setDate(d.getDate() + 1);
128
+ return d.getTime();
129
+ };
130
+ return !m[3] && h >= 1 && h <= 12 ? Math.min(next(h % 12), next(h % 12 + 12)) : next(h);
131
+ }
132
+ return from + ms(t);
133
+ }
134
+
135
+ export const gb = b => (b / 1024 ** 3).toFixed(b < 10 * 1024 ** 3 ? 1 : 0) + 'G';
136
+ // Any size, in the unit that reads best: 840K, 12M, 1.4G.
137
+ export const size = b => (b < 1024 ** 2 ? `${Math.max(1, Math.round(b / 1024))}K` : b < 1024 ** 3 ? `${Math.round(b / 1024 ** 2)}M` : gb(b));
138
+
139
+ export function dur(t) {
140
+ t = Math.max(0, Math.round(t / 1000));
141
+ if (t < 60) return `${t}s`;
142
+ if (t < 3600) return `${Math.floor(t / 60)}m${String(t % 60).padStart(2, '0')}s`;
143
+ return `${Math.floor(t / 3600)}h${String(Math.floor(t / 60) % 60).padStart(2, '0')}m`;
144
+ }
145
+
146
+ // A command's inline secrets (API_KEY=..., --token ...) stay on this machine: dibs web and its stats show commands masked.
147
+ const SECRETISH = /\b([A-Z0-9_]*(?:KEY|TOKEN|SECRET|PASSWORD|PASSWD|AUTH)[A-Z0-9_]*=)\S+|(--?(?:token|password|secret|api-key|key)[= ])\S+/gi;
148
+ export const masked = s => (typeof s === 'string' ? s.replace(SECRETISH, (m, a, b) => `${a || b}***`) : s);
149
+
150
+ export const clock = t => new Date(t).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
151
+ // A time later today reads as a clock; another day gets its date too, so a retry weeks off doesn't look like tonight.
152
+ export const when = (t, from = now()) => new Date(t).toDateString() === new Date(from).toDateString() ? `at ${clock(t)}` : `on ${new Date(t).toLocaleDateString('en-CA')} at ${clock(t)}`;
153
+
154
+ // A history key's command part is the program and its first word, then
155
+ // KEY_SPLIT and the words keys gained after 0.0.74 (src/acquire.mjs commandKey). Lines
156
+ // written before then are under the part before KEY_SPLIT: they count for a
157
+ // command until it has history under its full key.
158
+ export const KEY_SPLIT = ' / ';
159
+ export function runsOf(hist, key) {
160
+ const by = indexed(hist).byKey;
161
+ const mine = by.get(key) || [];
162
+ const cut = key ? key.indexOf(KEY_SPLIT) : -1;
163
+ if (mine.length || cut < 0) return mine;
164
+ return by.get(key.slice(0, cut)) || [];
165
+ }
166
+
167
+ // History grouped by key and by agent, built once per history array. A waiter
168
+ // ranks the whole line every poll, and scanning a thousand lines for each
169
+ // waiter in each comparison cost 100 ms of CPU per poll with 40 waiting, and
170
+ // enough garbage to grow every waiter's heap past 150 MB. Rebuilt if the array grows.
171
+ const INDEX = new WeakMap();
172
+ export function indexed(hist) {
173
+ let x = INDEX.get(hist);
174
+ if (x?.n === hist.length) return x;
175
+ x = { n: hist.length, byKey: new Map(), byWho: new Map() };
176
+ for (const h of hist) {
177
+ if (!x.byKey.has(h.key)) x.byKey.set(h.key, []);
178
+ x.byKey.get(h.key).push(h);
179
+ if (!x.byWho.has(h.who)) x.byWho.set(h.who, []);
180
+ x.byWho.get(h.who).push({ at: h.at, dur: h.dur, res: String(h.key).split('|')[0].split(',') });
181
+ }
182
+ INDEX.set(hist, x);
183
+ return x;
184
+ }
@@ -0,0 +1,2 @@
1
+ // Bump with every release and add a matching section at the top of CHANGELOG.md.
2
+ export const VERSION = '0.0.179';