@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
@@ -0,0 +1,151 @@
1
+ // Running a job next to others on a full resource, when the machine can take it.
2
+ //
3
+ // For most resources the slot count is a stand-in for "the machine can take
4
+ // this many": three test runs, two builds. When a full resource's running
5
+ // jobs leave real room, one more may start on top of them:
6
+ // fit its size fits what's really free: memory above minFreeMem, and
7
+ // cores under the load ceiling (maxLoad, else one per core). The
8
+ // size is what its command really used (src/measure.mjs), else the
9
+ // --mem it asked for. A job with neither has an unknown cost and
10
+ // doesn't overlap.
11
+ // squeeze also: a job that usually takes under squeezeUnder (from history,
12
+ // never --est) starts if its memory fits, even when its cores would
13
+ // take the load past the ceiling. The person accepted that load hit
14
+ // by choosing it. Not once the load is already past it.
15
+ // Either way the machine's own gates still apply after this (src/schedule.mjs
16
+ // verdict): free disk, swap, the memory budget with no roomy exception, and
17
+ // the load ceiling.
18
+ // Never on a resource that's one at a time: exclusive in its config (sim and
19
+ // deploy by default, and names dibs doesn't know, which are often someone's
20
+ // lock), a pool, one with an onRelease reset, file leases and quotas.
21
+ //
22
+ // A job on top never takes a slot, so when a slot frees the next waiter in
23
+ // line gets it as usual and nobody is passed for good. It never pauses anyone.
24
+ // Under memory pressure it's the first to pause, newest first (src/preempt.mjs).
25
+ //
26
+ // config.overlap: off, fit or squeeze. loadConfig sets it from the pace when
27
+ // the file doesn't (quiet off, normal fit, max squeeze; no pace, off).
28
+ import { resCfg, machine, hardware } from './config.mjs';
29
+ import { tag } from './proc.mjs';
30
+ import { isFiles } from './files.mjs';
31
+ import { isQuota } from './quota.mjs';
32
+ import { learned } from './measure.mjs';
33
+ import { loadAhead, typical, cpuLoad } from './schedule.mjs';
34
+ import { OS } from './platform.mjs';
35
+ // plain.mjs imports the scheduler, which imports this; only functions cross, so the cycle is safe.
36
+ import { andList, about, named } from './plain.mjs';
37
+ import { gb, ms, now } from './util.mjs';
38
+
39
+ // A job reaches most of its memory over its first seconds, and the sampler
40
+ // sees a lease only every 10s, so for this long after a start the free reading
41
+ // doesn't show all of it yet. The rest is taken off what's free.
42
+ const SETTLE = 30e3;
43
+
44
+ // Everything the person reads about overlap, in one place, in the plain
45
+ // words the rest of dibs uses (src/plain.mjs): GB with a space, queue, no slots.
46
+ const GB = b => gb(b).replace(/G$/, ' GB');
47
+ const say = {
48
+ oneAtATime: (r, cfg) => `Can't run alongside: ${named(cfg, r).queue} runs one job at a time.`,
49
+ hold: () => "Can't run alongside: a hold keeps what it holds to itself.",
50
+ unknown: () => "Can't run alongside: dibs hasn't measured this command yet and it gave no --mem, so it can't tell whether it fits. Pass --mem the first time.",
51
+ mem: (need, free, from) => `Can't run alongside: it ${from === 'asked' ? 'asked for' : 'usually needs'} ${GB(need)} of memory and ${GB(free)} is free.`,
52
+ load: (cpu, load, ceiling) => `Can't run alongside: it usually keeps ${cpu} cores busy, and that would take the machine from ${load.toFixed(1)} past its busy limit of ${ceiling}.`,
53
+ ahead: q => `Can't run alongside yet: ${tag(q)} is ahead of you in the queue and fits alongside too, so it goes first.`,
54
+ started: (a, queues) => a.kind === 'squeeze'
55
+ ? `${queues} full, so this squeezes in next to ${andList(a.with)} (it usually takes ${about(a.usually)}).`
56
+ : `${queues} full, so this runs alongside ${andList(a.with)}: it needs about ${GB(a.mem)} of memory, and there's room.`,
57
+ pressured: () => 'paused your job: the machine is short on memory, and a job running alongside others is the first to pause.'
58
+ + ' It keeps its place and picks up again when memory frees up.',
59
+ row: a => (a.kind === 'squeeze' ? `squeezed in (usually takes ${about(a.usually)})` : `running alongside ${andList(a.with)}`),
60
+ };
61
+ export const startLine = (a, cfg) => say.started(a, `${andList(a.res.map(r => named(cfg, r).queue))} ${a.res.length > 1 ? 'are' : 'is'}`);
62
+ export const pausedLine = () => say.pressured();
63
+ export const alongsideLabel = l => (l.alongside ? say.row(l.alongside) : '');
64
+
65
+ // For dibs pace: what the machine does with a full queue, in a sentence.
66
+ export function sideBySide(cfg) {
67
+ const mode = overlapMode(cfg);
68
+ if (mode === 'off') return 'no. A job waits for its turn when its queue is full.';
69
+ const fit = "when they fit. A job may start next to the ones filling its queue if the machine has the memory and cores for it";
70
+ return mode === 'fit' ? `${fit}.` : `${fit}, and one that usually takes under ${about(ms(cfg.squeezeUnder))} squeezes in even if it takes the machine past its busy limit.`;
71
+ }
72
+
73
+ export const overlapMode = cfg => cfg.overlap || 'off';
74
+
75
+ // One at a time, whatever the machine has free. A name dibs doesn't know is
76
+ // one unless the config's unknown says exclusive: false.
77
+ export function exclusive(cfg, r) {
78
+ if (isFiles(r) || isQuota(r)) return true;
79
+ const c = resCfg(cfg, r);
80
+ if (c.pool || c.onRelease) return true;
81
+ // resCfg fills a configured resource's gaps from unknown, so read its own config here.
82
+ return cfg.resources[r] ? cfg.resources[r].exclusive === true : cfg.unknown?.exclusive !== false;
83
+ }
84
+
85
+ // A lease running on top of r's slots, which it doesn't count against.
86
+ export const onTop = (l, r) => !!l.alongside?.res?.includes(r);
87
+
88
+ // Memory free now, less what jobs started in the last SETTLE haven't taken yet.
89
+ // A job planned at the budget (src/measure.mjs sized) will take what it usually uses.
90
+ function memFree(s, m, t) {
91
+ const settling = s.leases.filter(l => l.kind === 'run' && !l.pausedAt && t - l.start < SETTLE)
92
+ .reduce((a, l) => a + Math.max(0, (l.alongside?.mem ?? Math.max(l.mem, l.usual || 0)) - (l.use?.mem || 0)), 0);
93
+ return m.memFree / 100 * hardware().mem - settling;
94
+ }
95
+
96
+ // What a job costs as far as overlap goes: what it really used, else what it
97
+ // asked for, else null.
98
+ function sizeOf(me, hist) {
99
+ const got = learned(hist, me.key);
100
+ if (got) return { mem: got.mem, cpu: got.cpu, from: 'learned' };
101
+ return me.declared ? { mem: me.mem, cpu: me.cpu, from: 'asked' } : null;
102
+ }
103
+
104
+ // Whether a waiter could start on top of r now. Never mind who's ahead.
105
+ function fits(s, me, r, cfg, hist, m, t) {
106
+ if (exclusive(cfg, r)) return { ok: false, why: say.oneAtATime(r, cfg) };
107
+ if (me.kind === 'hold' || me.key?.endsWith('|hold')) return { ok: false, why: say.hold() };
108
+ const size = sizeOf(me, hist);
109
+ const usually = typical(hist, me.key);
110
+ const quick = overlapMode(cfg) === 'squeeze' && usually != null && usually < ms(cfg.squeezeUnder);
111
+ if (!size && !quick) return { ok: false, why: say.unknown() };
112
+ const mem = size?.mem ?? me.mem;
113
+ const room = memFree(s, m, t) - cfg.minFreeMem / 100 * hardware().mem;
114
+ if (mem > room) return { ok: false, why: say.mem(mem, Math.max(0, room), size?.from) };
115
+ const ceiling = cfg.maxLoad ?? (m.cores || hardware().cores);
116
+ // Cores in use, as the load ceiling reads them (src/schedule.mjs overLoad): a
117
+ // load average swollen by swapping isn't work. Plus recent starts it doesn't show yet.
118
+ const load = cpuLoad(m) + loadAhead(s, m);
119
+ const fitsLoad = !!size && load + size.cpu <= ceiling;
120
+ if (!fitsLoad && !quick) return { ok: false, why: say.load(size.cpu, load, ceiling) };
121
+ const next = new Set(s.leases.filter(l => l.res.includes(r) && !onTop(l, r)).map(l => tag(l)));
122
+ return { ok: true, kind: fitsLoad ? 'fit' : 'squeeze', res: [r], with: [...next], mem, ...(usually != null ? { usually } : {}) };
123
+ }
124
+
125
+ // verdict's hook for a full resource: null when overlap is off, else { ok,
126
+ // why } or { ok, kind, res, with, mem, usually }. A waiter ahead that wants
127
+ // r and fits on top too goes first.
128
+ export function alongside(s, me, r, cfg, hist, t, ahead) {
129
+ if (overlapMode(cfg) === 'off') return null;
130
+ const m = machine();
131
+ const a = fits(s, me, r, cfg, hist, m, t);
132
+ if (!a.ok) return a;
133
+ const first = ahead.find(q => q.res.includes(r) && fits(s, q, r, cfg, hist, m, t).ok);
134
+ return first ? { ok: false, why: say.ahead(first), ahead: first } : a;
135
+ }
136
+
137
+ // Several resources' admissions as one, for the lease.
138
+ export function merge(as) {
139
+ if (!as.length) return null;
140
+ return { kind: as.some(a => a.kind === 'squeeze') ? 'squeeze' : 'fit', res: as.flatMap(a => a.res),
141
+ with: [...new Set(as.flatMap(a => a.with))], mem: as[0].mem, ...(as[0].usually != null ? { usually: as[0].usually } : {}) };
142
+ }
143
+
144
+ // Under memory pressure, jobs on top, and a first run let in on probation
145
+ // (src/schedule.mjs probation), pause before anyone else's, newest first.
146
+ // Only on resources that allow pausing at all.
147
+ export function pressureVictim(s, cfg) {
148
+ if (OS === 'windows') return null;
149
+ return s.leases.filter(l => (l.alongside || l.trial) && l.kind === 'run' && l.pgid && !l.pauses?.some(p => p.watcher)
150
+ && l.res.every(r => resCfg(cfg, r).pausable === true)).sort((a, b) => b.start - a.start)[0] || null;
151
+ }
@@ -0,0 +1,351 @@
1
+ // Overrides: "this one matters more" (boost), "not now" (pause, resume),
2
+ // "stop that" (stop) and "this agent never gets above low" (cap). The person
3
+ // runs them, and so may any agent, on any job. Each one names who did it
4
+ // (src/owner.mjs actor), on the job for the board and in the event log, so
5
+ // the person can see which agent did what.
6
+ //
7
+ // What was changed is kept on the waiter or lease itself, so the board
8
+ // can say so and cap off can undo it:
9
+ // owner { act: 'boost' | 'cap', prio, at, by?, reason? }: by is the
10
+ // agent that did it (none: the person)
11
+ // askedPrio the priority the agent asked for, before the owner changed it
12
+ // ownerStop when it was stopped; its dibs process says so and exits
13
+ // stopBy the agent that stopped it (none: the person)
14
+ // s.caps { <agent>: { prio, at, by? } }
15
+ // An owner pause is an { owner, by? } entry in lease.pauses (src/preempt.mjs),
16
+ // so it ends with the lease like any other pause.
17
+ import { spawnSync } from 'node:child_process';
18
+ import { resCfg } from './config.mjs';
19
+ import { tag, makeAlive, identity, isMine } from './proc.mjs';
20
+ import { descendants, processes, pidsIn, stopTree, lower, raise, OS } from './platform.mjs';
21
+ import { withState, history } from './state.mjs';
22
+ import { ownerPause, pauseLabel } from './preempt.mjs';
23
+ import { PRIORITIES, BACKGROUND, NEEDS_REASON, priority, byRank } from './schedule.mjs';
24
+ import { actor } from './owner.mjs';
25
+ import { event } from './events.mjs';
26
+ import { die, now } from './util.mjs';
27
+ import { takeAgent, callKey } from './files.mjs';
28
+ import { quoted } from './style.mjs';
29
+
30
+ const rankOf = p => PRIORITIES.indexOf(p || 'normal');
31
+ const USAGE = {
32
+ boost: 'dibs boost <id or agent> <urgent|high|normal|low|idle> [-m "why"] [--owner <session>]',
33
+ pause: 'dibs pause <id> [--force] [-m "why"] [--owner <session>]',
34
+ resume: 'dibs resume <id> [-m "why"] [--owner <session>]',
35
+ stop: 'dibs stop <id> [-m "why"] [--owner <session>]',
36
+ cap: 'dibs cap <agent> <urgent|high|normal|low|idle|off>',
37
+ };
38
+ const IDS = 'Ids are the #numbers on the board (dibs), or "id" in dibs --json.';
39
+
40
+ // History's event log gets one "override" event per change, naming who made
41
+ // it: by is the agent's session name, or 'the person'.
42
+ const recordAll = (act, changes, who, reason = '') => {
43
+ for (const c of changes) event({ kind: 'override', act, ...c, by: who.name, byAgent: who.agent, ...(who.via && { via: who.via }), ...(reason && { reason }) });
44
+ };
45
+ // What goes on the job: the agent's name, the person's paired browser, or nothing for the person here.
46
+ const byOf = who => (who.agent || who.via ? { by: who.name } : {});
47
+
48
+ function argsOf(verb, args, flags = []) {
49
+ const o = args.indexOf('--owner');
50
+ let owner = null;
51
+ if (o >= 0) {
52
+ if (!args[o + 1] || args[o + 1].startsWith('-')) die(`--owner needs the job's owner: its session, or session/agent, as the board shows it. Use: ${USAGE[verb] || verb}`);
53
+ owner = args[o + 1];
54
+ args = [...args.slice(0, o), ...args.slice(o + 2)];
55
+ }
56
+ const parsed = argsOf1(verb, args, flags);
57
+ return { ...parsed, owner };
58
+ }
59
+ function argsOf1(verb, args, flags = []) {
60
+ const m = args.findIndex(a => a === '-m' || a === '--msg');
61
+ let reason = '';
62
+ if (m >= 0) {
63
+ if (args[m + 1] == null) die(`-m needs a reason everyone can see: -m "why". Use: ${USAGE[verb]}`);
64
+ reason = args[m + 1].trim();
65
+ args = [...args.slice(0, m), ...args.slice(m + 2)];
66
+ }
67
+ const bad = args.find(a => a.startsWith('-') && !flags.includes(a));
68
+ if (bad) die(`unknown flag ${bad}. Use: ${USAGE[verb]}`);
69
+ return { words: args.filter(a => !a.startsWith('-')), flags: new Set(args.filter(a => flags.includes(a))), reason };
70
+ }
71
+
72
+ function prioArg(verb, p) {
73
+ const prio = priority(p);
74
+ if (!PRIORITIES.includes(prio)) die(`priority is one of ${PRIORITIES.join(', ')} (or 1-5). Use: ${USAGE[verb]}`);
75
+ return prio;
76
+ }
77
+
78
+ const byName = name => x => x.agent === name || x.who === name;
79
+
80
+ // Whose a job is, as --owner names it: its session, then /agent for a subagent's.
81
+ export const ownerOf = x => `${x.agent || x.who}${x.label ? `/${x.label}` : ''}`;
82
+ // The calling agent: its session, and the subagent the guard hook saw make this
83
+ // call (src/files.mjs takeAgent), so siblings in one session aren't each other.
84
+ function caller(verb) {
85
+ const a = takeAgent(verb, [], callKey(verb));
86
+ return { ...identity({ as: a?.agentType || undefined }), agentId: a?.agentId || null };
87
+ }
88
+ // Its own: the same session, and the same subagent when either side was stamped
89
+ // (else the same label). An unstamped job of an older dibs needs --owner from
90
+ // a stamped caller: refusing too often is the safe side of this.
91
+ const own = (x, me) => isMine(x, me) && (x.agentId || me.agentId ? x.agentId === me.agentId : (x.label || '') === (me.label || ''));
92
+ // A job that isn't the calling agent's own takes --owner naming it, or nothing
93
+ // changes (exit 2). An id typed from memory or a board can be someone else's:
94
+ // on 2026-10-19 an agent boosted #10167 and only learned from the output whose
95
+ // it was, and crews sharing a session stopped each other's jobs. The person is
96
+ // never asked.
97
+ function notYours(verb, x, who, me, want) {
98
+ if (!who.agent || own(x, me)) return null;
99
+ if (want && (want === ownerOf(x) || want === (x.agent || x.who))) return null;
100
+ return `#${x.id} is ${ownerOf(x)}'s ${x.res.join(',')} job${x.purpose ? ` ("${x.purpose}")` : ''}${want ? `, not ${want}'s` : ', not yours'}. Nothing changed.`
101
+ + ` If you meant it: dibs ${quoted([verb, ...process.argv.slice(3).filter((a, i, all) => a !== '--owner' && all[i - 1] !== '--owner')])} --owner ${ownerOf(x)}`;
102
+ }
103
+ // The first line names whose job it is, before anything else is said about it.
104
+ const naming = (verbing, x) => `${verbing} #${x.id}: ${ownerOf(x)} ${x.res.join(',')}${x.purpose ? ` '${x.purpose}'` : ''}`;
105
+ const what = (s, x) => (s.queue.includes(x) ? 'wait' : x.kind === 'hold' ? 'hold' : 'run');
106
+ const brief = (s, x) => ({ id: x.id, res: x.res, who: tag(x), kind: what(s, x) });
107
+ const out = line => console.log(line);
108
+
109
+ // The run's own process group is still the one dibs started, not a reused number.
110
+ const ours = l => !!l.pgid && (!l.pgstart || makeAlive([l.pgid])(l.pgid, l.pgstart));
111
+ // Every group a run's tree is spread over, when it's still ours.
112
+ const groupsOf = l => (ours(l) ? new Set([l.pgid, ...(l.groups || []), ...(l.stopped || []), ...descendants(l.pgid)]) : new Set());
113
+
114
+ // Set a waiter's or lease's priority on the owner's say. Back at what the agent
115
+ // asked for, nothing is left marked.
116
+ function setPrio(x, prio, act, who, reason = '') {
117
+ delete x.agentBoost; // 0.0.91-0.0.109's own-job boost, replaced by this
118
+ x.askedPrio ??= x.prio || 'normal';
119
+ x.prio = prio;
120
+ if (prio === x.askedPrio && act === 'boost') { delete x.owner; delete x.askedPrio; }
121
+ else x.owner = { act, prio, at: now(), ...byOf(who), ...(reason && { reason }) };
122
+ }
123
+
124
+ // A run's background QoS follows its priority: low and idle on the efficiency
125
+ // cores, the rest off them. `from` is its priority before the change (runs
126
+ // started by an older dibs don't record their QoS). Returns the pids to move,
127
+ // found under the lock; they're moved after it, since a big tree takes a while.
128
+ // Reads of the process table after a boost moves a job, for children forked meanwhile.
129
+ const CATCH_UP = 3;
130
+ function requeue(l, from) {
131
+ if (l.kind !== 'run' || !l.pgid || OS === 'windows') return null;
132
+ const bg = BACKGROUND.has(l.prio);
133
+ if ((l.background ?? BACKGROUND.has(from)) === bg) return null;
134
+ l.background = bg;
135
+ const groups = groupsOf(l);
136
+ return { bg, groups: [...groups], pids: processes().filter(p => groups.has(p.pgid)).map(p => p.pid) };
137
+ }
138
+
139
+ // dibs boost <id or agent> <prio>: change a waiter's or running lease's
140
+ // priority. A waiter is re-ranked; a run's preemption (src/preempt.mjs pauses
141
+ // only low and idle runs) and background QoS follow the new priority.
142
+ export function boost(args) {
143
+ const who = actor();
144
+ const me = caller('boost');
145
+ const { words: [target, p], reason, owner } = argsOf('boost', args);
146
+ if (!target || !p) die(`Use: ${USAGE.boost}. ${IDS}`);
147
+ const prio = prioArg('boost', p);
148
+ // Everyone sees an agent's high or urgent, and why, as they do on dibs run -p.
149
+ if (who.agent && NEEDS_REASON.has(prio) && !reason) die(`${prio} needs a reason everyone can see: dibs boost ${target} ${prio} -m "why". Nothing changed.`);
150
+ const hist = history();
151
+ const r = withState(s => {
152
+ const items = /^\d+$/.test(target) ? [...s.leases, ...s.queue].filter(x => String(x.id) === target) : [...s.leases, ...s.queue].filter(byName(target));
153
+ for (const x of items) { const no = notYours('boost', x, who, me, owner); if (no) return { refused: no }; }
154
+ const changes = [];
155
+ for (const x of items) {
156
+ const from = x.prio || 'normal';
157
+ if (from === prio) { changes.push({ ...brief(s, x), x: { ...x }, from, same: true }); continue; }
158
+ setPrio(x, prio, 'boost', who, reason);
159
+ changes.push({ ...brief(s, x), x: { ...x }, from, prio, qos: s.leases.includes(x) ? requeue(x, from) : null });
160
+ }
161
+ const order = s.queue.filter(q => q.pid).sort(byRank(hist));
162
+ for (const c of changes) if (c.kind === 'wait') c.place = order.findIndex(q => q.id === c.id) + 1;
163
+ return changes;
164
+ });
165
+ if (r.refused) die(r.refused, 2);
166
+ if (!r.length) die(`nothing matched ${target}: no lease or waiter with that id or agent name. ${IDS}`, 1);
167
+ for (const c of r) {
168
+ out(naming('boosting', c.x));
169
+ const head = `#${c.id} ${c.who}'s ${c.res.join(',')} ${c.kind}`;
170
+ if (c.same) { out(`${head}: already ${c.prio || c.from}`); continue; }
171
+ let line = `${head}: ${c.from} -> ${c.prio}`;
172
+ if (c.place) line += `, now #${c.place} in the queue`;
173
+ if (c.qos) {
174
+ // One that exited meanwhile has nothing left to move, a zombie its parent hasn't reaped included.
175
+ const gone = pid => !/^[^Z]/.test(spawnSync('ps', ['-o', 'stat=', '-p', String(pid)], { encoding: 'utf8' }).stdout.trim());
176
+ const move = pid => (c.qos.bg ? lower(pid) : raise(pid)) || gone(pid);
177
+ const tried = new Set(c.qos.pids);
178
+ let moved = c.qos.pids.filter(move).length;
179
+ // A child forked between reading the process table and moving its parent kept the old
180
+ // priority, and at background priority on a busy machine even a sleep 0.05 can last
181
+ // seconds. The parents are moved now, so what they start next follows: a few reads catch the rest.
182
+ for (let i = 0; i < CATCH_UP; i++) {
183
+ const late = pidsIn(c.qos.groups).filter(pid => !tried.has(pid));
184
+ if (!late.length) break;
185
+ for (const pid of late) tried.add(pid);
186
+ moved += late.filter(move).length;
187
+ }
188
+ line += c.qos.bg ? ', moved to background priority (efficiency cores)' : ', moved off background priority';
189
+ if (moved < tried.size) line += ` (${tried.size - moved} of its ${tried.size} processes couldn't be moved${OS === 'linux' && !c.qos.bg ? ': Linux lets only root raise a priority' : ''})`;
190
+ }
191
+ if (c.kind === 'run' && BACKGROUND.has(c.prio)) line += '; urgent and high work may now pause it';
192
+ out(line);
193
+ }
194
+ recordAll('boost', r.filter(c => !c.same).map(({ id, res, who, prio, from }) => ({ id, res, who, prio, from })), who, reason);
195
+ }
196
+
197
+ // Why the owner can't pause this lease, or null. Resources marked pausable:
198
+ // false (sim, xcode-build and deploy by default) stay unpaused unless --force:
199
+ // a frozen deploy, simulator or build can time out against the services it
200
+ // talks to and fail in ways a clean stop wouldn't.
201
+ function unpausable(l, cfg, force) {
202
+ if (OS === 'windows') return `Windows can't pause a process tree (it has no SIGSTOP). dibs stop ${l.id} ends it instead.`;
203
+ if (l.kind === 'hold') return `#${l.id} is a hold: its process is the agent's own session, and pausing that would freeze the agent. dibs stop ${l.id} releases the hold instead.`;
204
+ if (!l.pgid) return `#${l.id} hasn't started its command yet. Try again in a moment.`;
205
+ const fixed = l.res.filter(r => resCfg(cfg, r).pausable !== true);
206
+ if (fixed.length && !force)
207
+ return `${fixed.join(', ')} is marked pausable: false: a deploy, simulator or build frozen midway can time out against the services it talks to`
208
+ + ` and fail in ways a clean stop wouldn't. Nothing changed. dibs pause ${l.id} --force freezes it anyway; dibs stop ${l.id} ends it.`;
209
+ return null;
210
+ }
211
+
212
+ function leaseArg(verb, args, flags) {
213
+ const a = argsOf(verb, args, flags);
214
+ if (a.words.length !== 1 || !/^\d+$/.test(a.words[0])) die(`Use: ${USAGE[verb]}. ${IDS}`);
215
+ return { id: a.words[0], flags: a.flags, reason: a.reason, owner: a.owner };
216
+ }
217
+ const missing = (s, id) => `no lease #${id}${s.queue.some(q => String(q.id) === id) ? ' (it\'s waiting, not running)' : ''}. ${IDS}`;
218
+
219
+ // dibs pause <id> [--force]: stop a run's tree where it stands. It keeps its
220
+ // lease and its slot until dibs resume, or until it ends.
221
+ export function pause(args, cfg) {
222
+ const who = actor();
223
+ const me = caller('pause');
224
+ const { id, flags, reason, owner } = leaseArg('pause', args, ['--force']);
225
+ const r = withState(s => {
226
+ const l = s.leases.find(x => String(x.id) === id);
227
+ if (!l) return { err: s.queue.some(q => String(q.id) === id) ? `#${id} is waiting, not running: there's nothing to pause yet. To hold it back, lower it: dibs boost ${id} idle` : missing(s, id), code: 1 };
228
+ const no = notYours('pause', l, who, me, owner);
229
+ if (no) return { err: no, code: 2 };
230
+ out(naming('pausing', l));
231
+ const why = unpausable(l, cfg, flags.has('--force'));
232
+ if (why) return { err: why, code: 2 };
233
+ if (l.pauses?.some(p => p.owner)) return { same: brief(s, l) };
234
+ ownerPause(l, true, now(), who.agent || who.via ? who.name : null, reason);
235
+ return { done: brief(s, l) };
236
+ });
237
+ if (r.err) die(r.err, r.code);
238
+ const c = r.done || r.same;
239
+ if (r.same) return out(`#${id} ${c.who}'s ${c.res.join(',')} run is already paused by you. dibs resume ${id} continues it.`);
240
+ out(`paused #${id} ${c.who}'s ${c.res.join(',')} run. It keeps its lease and its slot; dibs resume ${id} continues it.`);
241
+ recordAll('pause', [{ id: c.id, res: c.res, who: c.who }], who, reason);
242
+ }
243
+
244
+ // dibs resume <id>: undo the owner's pause. Pauses dibs made itself (for an
245
+ // urgent job, for memory) stay until their reason ends.
246
+ export function resume(args) {
247
+ const who = actor();
248
+ const me = caller('resume');
249
+ const { id, reason, owner } = leaseArg('resume', args);
250
+ const r = withState(s => {
251
+ const l = s.leases.find(x => String(x.id) === id);
252
+ if (!l) return { err: missing(s, id) };
253
+ const no = notYours('resume', l, who, me, owner);
254
+ if (no) return { err: no, code: 2 };
255
+ out(naming('resuming', l));
256
+ if (!l.pauses?.some(p => p.owner))
257
+ return { err: `#${id} isn't paused by you${l.pausedAt ? ` (it's ${pauseLabel(l)}, which dibs undoes by itself)` : ''}. Nothing changed.` };
258
+ ownerPause(l, false);
259
+ if (reason) l.resumeReason = reason; else delete l.resumeReason;
260
+ return { done: brief(s, l), still: l.pausedAt ? pauseLabel(l) : null };
261
+ });
262
+ if (r.err) die(r.err, r.code || 1);
263
+ const c = r.done;
264
+ out(r.still ? `took your pause off #${id} ${c.who}'s ${c.res.join(',')} run, but it stays ${r.still} until that ends.`
265
+ : `resumed #${id} ${c.who}'s ${c.res.join(',')} run.`);
266
+ recordAll('resume', [{ id: c.id, res: c.res, who: c.who }], who, reason);
267
+ }
268
+
269
+ // dibs stop <id>: the owner's kill switch. A run's tree is killed as a crash
270
+ // would kill it, and its dibs process says "stopped by the owner" and gives
271
+ // the lease back. A waiter's dibs process leaves the line and exits. A hold is
272
+ // released.
273
+ export function stop(args) {
274
+ const who = actor();
275
+ const me = caller('stop');
276
+ const { id, reason, owner } = leaseArg('stop', args);
277
+ const r = withState(s => {
278
+ const x = [...s.leases, ...s.queue].find(y => String(y.id) === id);
279
+ if (!x) return null;
280
+ const no = notYours('stop', x, who, me, owner);
281
+ if (no) return { refused: no };
282
+ out(naming('stopping', x));
283
+ const c = brief(s, x);
284
+ if (c.kind === 'hold') s.leases = s.leases.filter(l => l !== x);
285
+ else if (c.kind === 'wait' && !x.pid) s.queue = s.queue.filter(q => q !== x); // a kept place: nobody is waiting on it
286
+ else {
287
+ x.ownerStop = now();
288
+ if (who.agent || who.via) x.stopBy = who.name;
289
+ if (reason) x.stopReason = reason;
290
+ // SIGKILL ends stopped processes too, so a paused run needs no SIGCONT first.
291
+ // The lock is still held, so the run's own dibs can't remove the lease
292
+ // (and its group number can't be handed out again) in between.
293
+ if (c.kind === 'run') for (const g of groupsOf(x)) stopTree(g, 'SIGKILL');
294
+ }
295
+ return c;
296
+ });
297
+ if (!r) die(`no lease or waiter #${id}. ${IDS}`, 1);
298
+ if (r.refused) die(r.refused, 2);
299
+ out(r.kind === 'hold' ? `released #${id} ${r.who}'s hold on ${r.res.join(',')}. A hold has no process to kill; the agent finds out when it next asks.`
300
+ : r.kind === 'wait' ? `took #${id} ${r.who} out of line for ${r.res.join(',')}. Its command never started.`
301
+ : `stopped #${id} ${r.who}'s ${r.res.join(',')} run and killed its processes. Its dibs tells the agent it was stopped by ${who.agent || who.via ? who.name : 'the owner'}.`);
302
+ recordAll('stop', [{ id: r.id, res: r.res, who: r.who }], who, reason);
303
+ }
304
+
305
+ // Lower a waiter to its agent's cap, or back up toward what it asked for when
306
+ // the cap rises. Returns [from, to] when it changed.
307
+ function capOne(q, prio, who) {
308
+ const base = q.owner?.act === 'cap' ? q.askedPrio : q.prio || 'normal';
309
+ const to = prio && rankOf(base) < rankOf(prio) ? prio : base;
310
+ const from = q.prio || 'normal';
311
+ if (to === from) return null;
312
+ if (to === base) { q.prio = base; delete q.owner; delete q.askedPrio; } else setPrio(q, to, 'cap', who);
313
+ return [from, to];
314
+ }
315
+
316
+ // At enqueue (src/acquire.mjs): a capped agent's new request waits at its cap.
317
+ export function capWaiter(s, q) {
318
+ const c = s.caps?.[q.agent] || s.caps?.[q.who];
319
+ if (c && rankOf(q.prio) < rankOf(c.prio)) setPrio(q, c.prio, 'cap', { agent: !!c.by, name: c.by });
320
+ }
321
+
322
+ // dibs cap <agent> <prio|off>: that agent's work never waits or runs above
323
+ // prio: its waiters now and every request it makes until off. Running jobs
324
+ // are left alone (dibs boost or dibs pause them).
325
+ export function cap(args) {
326
+ const who = actor();
327
+ const { words: [name, p] } = argsOf('cap', args);
328
+ if (!name || !p) die(`Use: ${USAGE.cap}`);
329
+ const prio = p === 'off' ? null : prioArg('cap', p);
330
+ const r = withState(s => {
331
+ const had = s.caps?.[name]?.prio || null;
332
+ if (prio) (s.caps ||= {})[name] = { prio, at: now(), ...byOf(who) };
333
+ else if (s.caps) { delete s.caps[name]; if (!Object.keys(s.caps).length) delete s.caps; }
334
+ const changed = s.queue.filter(byName(name)).map(q => [q, capOne(q, prio, who)]).filter(([, d]) => d)
335
+ .map(([q, [from, to]]) => ({ ...brief(s, q), from, prio: to }));
336
+ return { had, changed };
337
+ });
338
+ out(prio ? `${name}'s work now waits and runs at ${prio} or below${r.had ? ` (was capped at ${r.had})` : ''}, until dibs cap ${name} off.`
339
+ : r.had ? `took the ${r.had} cap off ${name}.` : `${name} had no cap. Nothing changed.`);
340
+ for (const c of r.changed) out(` #${c.id} ${c.who}'s ${c.res.join(',')} wait: ${c.from} -> ${c.prio}`);
341
+ if (prio || r.had) recordAll('cap', [{ who: name, prio: prio || 'off', from: r.had }], who);
342
+ }
343
+
344
+ // What a board row says about the owner's hand in it: by owner (the person)
345
+ // or by the agent that did it, with its reason.
346
+ export function ownerLabel(x) {
347
+ if (!x.owner) return '';
348
+ const by = x.owner.by || 'owner';
349
+ if (x.owner.act === 'cap') return `capped ${x.owner.prio} by ${by}`;
350
+ return `${rankOf(x.owner.prio) < rankOf(x.askedPrio) ? 'boosted' : 'lowered'} by ${by}${x.owner.reason ? `: ${x.owner.reason}` : ''}`;
351
+ }
package/src/owner.mjs ADDED
@@ -0,0 +1,30 @@
1
+ // Who is calling, for the record. Agents may do everything the person can
2
+ // (answer questions, set hours, change the group of machines, override any
3
+ // job), so nothing here refuses anyone. What it does is name the caller in the
4
+ // event log and on the board, so the person can see which agent did what.
5
+ import { identity } from './proc.mjs';
6
+ import { event } from './events.mjs';
7
+
8
+ // Set in the environment of an agent's tool calls: Claude Code, Codex, Cursor,
9
+ // Gemini CLI, opencode, and the AI_AGENT convention several of them share.
10
+ export const AGENT_ENV = ['CLAUDECODE', 'CLAUDE_CODE_CHILD_SESSION', 'CLAUDE_CODE_SESSION_ID', 'CLAUDE_CODE_ENTRYPOINT', 'AI_AGENT',
11
+ 'CODEX_SANDBOX', 'CODEX_THREAD_ID', 'CURSOR_AGENT', 'GEMINI_CLI', 'OPENCODE'];
12
+
13
+ // The caller: { name, agent, via }. An agent goes by its session name (the one the
14
+ // board and SendMessage use); anyone else is the person. DIBS_VIA names the paired
15
+ // browser a page action came through (src/web.mjs sets it for relay calls), so the
16
+ // record says "the person via Safari on iPhone (remote ...)". An agent can't borrow it.
17
+ export function actor(env = process.env) {
18
+ const id = identity();
19
+ const agent = AGENT_ENV.some(k => env[k]) || !!id.spid;
20
+ const via = !agent && typeof env.DIBS_VIA === 'string' && env.DIBS_VIA ? env.DIBS_VIA : null;
21
+ return { agent, name: agent ? id.agent || id.who : via ? `the person via ${via}` : 'the person', ...(via && { via }) };
22
+ }
23
+
24
+ // One line in the event log for a change to the person's settings or the
25
+ // group of machines, naming who made it. Overrides of jobs log their own
26
+ // (src/override.mjs), with the job.
27
+ export function logChange(act, extra = {}) {
28
+ const who = actor();
29
+ event({ kind: 'override', act, ...extra, by: who.name, byAgent: who.agent, ...(who.via && { via: who.via }) });
30
+ }