@dibssoftware/dibs 0.0.179 → 0.0.181

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 (53) hide show
  1. package/CHANGELOG.md +31 -2
  2. package/README.md +4 -2
  3. package/bin/dibs-guard.mjs +10 -1
  4. package/bin/dibs.mjs +37 -10
  5. package/docs/benchmarks.md +1 -1
  6. package/docs/files.md +1 -1
  7. package/docs/guard.md +6 -0
  8. package/docs/questions.md +6 -2
  9. package/docs/reference.md +4 -4
  10. package/docs/relay.md +24 -9
  11. package/docs/releasing.md +4 -3
  12. package/docs/scheduling.md +4 -4
  13. package/docs/windows.md +14 -0
  14. package/package.json +1 -1
  15. package/skills/dibs/SKILL.md +6 -6
  16. package/src/acquire.mjs +93 -27
  17. package/src/agents.mjs +7 -22
  18. package/src/alerts.mjs +75 -29
  19. package/src/board.mjs +1 -2
  20. package/src/broker.mjs +26 -11
  21. package/src/commands.mjs +37 -14
  22. package/src/config.mjs +21 -4
  23. package/src/cool.mjs +105 -10
  24. package/src/diskwarn.mjs +4 -0
  25. package/src/events.mjs +10 -1
  26. package/src/files.mjs +52 -88
  27. package/src/guard.mjs +76 -30
  28. package/src/guardd.mjs +97 -0
  29. package/src/guardw.mjs +19 -0
  30. package/src/later.mjs +20 -25
  31. package/src/lock.mjs +308 -0
  32. package/src/measure.mjs +27 -7
  33. package/src/ondemand.mjs +5 -2
  34. package/src/override.mjs +39 -2
  35. package/src/plain.mjs +2 -2
  36. package/src/platform.mjs +175 -42
  37. package/src/preempt.mjs +51 -3
  38. package/src/primer.mjs +1 -1
  39. package/src/proc.mjs +45 -5
  40. package/src/questions.mjs +8 -22
  41. package/src/relay.mjs +137 -32
  42. package/src/remote.mjs +12 -8
  43. package/src/schedule.mjs +139 -26
  44. package/src/serve.mjs +16 -3
  45. package/src/service.mjs +9 -4
  46. package/src/state.mjs +139 -47
  47. package/src/stats.mjs +3 -2
  48. package/src/talk.mjs +169 -83
  49. package/src/trust.mjs +7 -1
  50. package/src/util.mjs +28 -2
  51. package/src/version.mjs +1 -1
  52. package/src/web.mjs +17 -26
  53. package/src/worker.mjs +2 -1
package/src/cool.mjs CHANGED
@@ -11,15 +11,16 @@ import path from 'node:path';
11
11
  import { HOME, machine, loadConfig } from './config.mjs';
12
12
  import { withState, history, peek } from './state.mjs';
13
13
  import { singleInstance } from './proc.mjs';
14
- import { processes, lower, memPressure, isDibs } from './platform.mjs';
14
+ import { processes, lower, memPressure, isDibs, runtimes } from './platform.mjs';
15
15
  import { hogsOnce, hogHint } from './hogs.mjs';
16
- import { pressureStep, pressurePause, pressureResume, diskStep, diskPause, diskPausesPerPass, diskLine, diskCritical, adoptPauses, diskRequeue, measured } from './preempt.mjs';
16
+ import { pressureStep, pressurePause, pressureRequeue, pressureResume, diskStep, diskPause, diskPausesPerPass, diskLine, diskCritical, adoptPauses, diskRequeue, measured, hardStop, hardResume, HARD_STOP, HARD_RESUME } from './preempt.mjs';
17
+ import { inversions, lift } from './override.mjs';
17
18
  import { swapGrowing } from './schedule.mjs';
18
19
  import { event } from './events.mjs';
19
20
  import { notify } from './talk.mjs';
20
21
  import { watchBroker } from './broker.mjs';
21
22
  import { progressScan } from './notices.mjs';
22
- import { scan as scanAlerts } from './alerts.mjs';
23
+ import { scan as scanAlerts, CPU_FILE } from './alerts.mjs';
23
24
  import { say, sleep, now, noSpace, gb } from './util.mjs';
24
25
 
25
26
  const PIDFILE = path.join(HOME, 'cool.pid');
@@ -33,11 +34,46 @@ const SAMPLE_EVERY = 60e3;
33
34
 
34
35
  const toolName = args => path.basename(args.split(/\s+/)[0]).replace(/\.exe$/i, '');
35
36
 
37
+ // Cores that stopped taking work. On 2026-11-10 this Mac's 4 performance cores did:
38
+ // load went from 127 to 400 while top read a flat 40% idle, and only a restart
39
+ // fixed it. Load that high counts work that's ready to run, so with that much of
40
+ // the CPU idle the work isn't being run, and moving hot processes to background
41
+ // priority (off the performance cores) only made it worse. Past STUCK_LOAD per
42
+ // core with STUCK_IDLE or more of the CPU idle, the watcher lowers nothing, and
43
+ // after STUCK_AFTER of it (src/alerts.mjs) the person is told to restart.
44
+ const STUCK_LOAD = 5;
45
+ const STUCK_IDLE = 0.25;
46
+ export function coresStuck(m) {
47
+ if (!(m?.cores > 0) || m.busy == null || !(m.load >= STUCK_LOAD * m.cores)) return false;
48
+ return 1 - m.busy / m.cores >= STUCK_IDLE;
49
+ }
50
+
51
+ // Processes left behind: build and test tools outside dibs that have run for
52
+ // ORPHAN_AGE and whose script is gone. On 2026-11-10 two node testfast.mjs from a
53
+ // deleted scratchpad had run 23 hours at 17 CPU-hours each, kept hot and moved to
54
+ // background priority over and over. They're named in an alert; nothing is killed.
55
+ const ORPHAN_AGE = 3 * 36e5;
56
+ const ORPHAN_EVERY = 6e4; // a ps over the hot ones, once a minute
57
+ const SCRIPT = /\.(c|m)?[jt]sx?$|\.py$|\.rb$/;
58
+ // The script a tool runs, when its command line names one by its full path.
59
+ export function scriptOf(args) {
60
+ return args.split(/\s+/).slice(1).find(a => a.startsWith('/') && SCRIPT.test(a)) || null;
61
+ }
62
+ export function orphans(procs, leased, ages, gone = f => !fs.existsSync(f)) {
63
+ const out = [];
64
+ for (const p of procs) {
65
+ if (leased.has(p.pgid) || !TOOLS.test(toolName(p.args)) || isDibs(p)) continue;
66
+ const script = scriptOf(p.args), r = ages.get(p.pid);
67
+ if (script && r && r.age >= ORPHAN_AGE && gone(script)) out.push({ pid: p.pid, name: toolName(p.args), script, age: r.age, cpu: r.cpu });
68
+ }
69
+ return out;
70
+ }
71
+
36
72
  // One pass. A process must be hot on two passes in a row, so short bursts are
37
73
  // left alone. Returns the processes it moved.
38
- function throttleOnce(cfg, seen = new Map()) {
39
- const load = machine().load;
40
- const leased = new Set(withState(s => s.leases.flatMap(l => [l.pgid, ...(l.groups || [])]).filter(Boolean)));
74
+ function throttleOnce(cfg, seen = new Map(), leased = leasedGroups()) {
75
+ const m = machine(), load = m.load;
76
+ const stuck = coresStuck(m);
41
77
  const moved = [];
42
78
  const next = new Map();
43
79
  for (const p of processes()) {
@@ -45,7 +81,7 @@ function throttleOnce(cfg, seen = new Map()) {
45
81
  if (p.cpu < HOT || p.pid === process.pid || leased.has(p.pgid) || !TOOLS.test(toolName(p.args)) || isDibs(p)) continue;
46
82
  const prev = seen.get(p.pid);
47
83
  if (prev === 'done') { next.set(p.pid, 'done'); continue; }
48
- if (prev && load > cfg.coolLoad && lower(p.pid)) {
84
+ if (prev && load > cfg.coolLoad && !stuck && lower(p.pid)) {
49
85
  moved.push({ ...p, name: toolName(p.args) });
50
86
  next.set(p.pid, 'done');
51
87
  fs.appendFileSync(LOG, `${new Date().toISOString()} load ${load.toFixed(1)}: background ${toolName(p.args)} ${p.pid} (${p.cpu}% cpu)\n`);
@@ -56,12 +92,33 @@ function throttleOnce(cfg, seen = new Map()) {
56
92
  return moved;
57
93
  }
58
94
 
95
+ const leasedGroups = () => new Set(withState(s => s.leases.flatMap(l => [l.pgid, ...(l.groups || [])]).filter(Boolean)));
96
+
97
+ // What the watcher saw that only a person can fix, for src/alerts.mjs: since when
98
+ // the cores have looked stuck, and the orphans. Every pass, with when, so a
99
+ // watcher that stopped leaves no alert standing.
100
+ function noteCpu(note) {
101
+ try { fs.writeFileSync(`${CPU_FILE}.${process.pid}`, JSON.stringify({ at: now(), ...note })); fs.renameSync(`${CPU_FILE}.${process.pid}`, CPU_FILE); } catch {}
102
+ }
103
+
59
104
  // One memory pressure reading. Under sustained critical pressure, pause the
60
105
  // next idle or low lease; once it's been normal for a while, resume one.
61
106
  // Returns { act, leases } when it did something.
62
107
  export function pressureOnce(cfg, track, read = memPressure) {
63
108
  const act = pressureStep(track, read());
64
109
  if (!act) return null;
110
+ if (act === 'pause') {
111
+ const l = withState(s => pressureRequeue(s, cfg, now(), history()));
112
+ if (l) {
113
+ const used = measured(l) || l.mem;
114
+ fs.appendFileSync(LOG, `${new Date().toISOString()} memory pressure still critical with jobs paused: stopped ${l.who} ${l.res.join(',')} (${l.prio || 'normal'}), using ${gb(used)}, to run again at the front of its line: ${l.cmd.slice(0, 60)}\n`);
115
+ event({ kind: 'requeue', id: l.id, res: l.res, who: l.who, agent: l.agent, prio: l.prio || 'normal', why: 'memory', mem: used, booked: l.mem });
116
+ notify(l, `requeue:#${l.id}`, `your job #${l.id} (${l.purpose ? `"${l.purpose}", ` : ''}${l.cmd.slice(0, 60)}) was paused for memory pressure, and pausing frees no memory`
117
+ + ` (a stopped job's memory goes to swap), so with the pressure still critical dibs stopped it. Its dibs run put it back at the front of its line and runs it again`
118
+ + ` from the start once there's room. Don't run it again yourself, and don't end it: the same tool call carries on.`);
119
+ return { act: 'requeue', leases: [l] };
120
+ }
121
+ }
65
122
  const ls = withState(s => (act === 'pause' ? [pressurePause(s, cfg, now(), history())].filter(Boolean) : pressureResume(s)));
66
123
  for (const l of ls)
67
124
  fs.appendFileSync(LOG, `${new Date().toISOString()} memory pressure ${act === 'pause' ? 'critical: paused' : 'eased: resumed'} ${l.who} ${l.res.join(',')} (${l.prio || 'normal'}${l.alongside ? ', on top' : ''}): ${l.cmd.slice(0, 60)}\n`);
@@ -73,6 +130,7 @@ export function pressureOnce(cfg, track, read = memPressure) {
73
130
  // again, resume one a minute.
74
131
  // Returns { act, leases } when it did something.
75
132
  export function diskOnce(cfg, track, m = machine()) {
133
+ const hard = hardOnce(m);
76
134
  const act = diskStep(track, m, cfg);
77
135
  if (!act) return null;
78
136
  // Swap still growing with jobs already paused: their memory is what's going to swap.
@@ -108,6 +166,27 @@ export function diskOnce(cfg, track, m = machine()) {
108
166
  return ls.length ? { act, leases: ls } : null;
109
167
  }
110
168
 
169
+ // The hard stop (src/preempt.mjs hardStop), said loudly: the board's alert for the person
170
+ // (src/alerts.mjs), a line in the log, and a notice to the job's own session.
171
+ function hardOnce(m) {
172
+ const r = withState(s => ({ resumed: hardResume(s, m), paused: hardStop(s, now(), m) }));
173
+ const free = gb(m.diskFree ?? 0).replace(/G$/, ' GB');
174
+ for (const l of r.resumed) {
175
+ fs.appendFileSync(LOG, `${new Date().toISOString()} disk back to ${free}: resumed ${l.who} ${l.res.join(',')} (${l.prio || 'normal'}): ${l.cmd.slice(0, 60)}\n`);
176
+ event({ kind: 'resume', id: l.id, res: l.res, who: l.who, why: 'hard stop over', diskFree: m.diskFree });
177
+ notify(l, `hardresume:#${l.id}:${now()}`, `your job #${l.id} (${l.cmd.slice(0, 60)}) is running again: free disk is back to ${free}.`);
178
+ }
179
+ const l = r.paused;
180
+ if (l) {
181
+ fs.appendFileSync(LOG, `${new Date().toISOString()} disk at ${free}, under ${gb(HARD_STOP)}: hard stop, paused ${l.who} ${l.res.join(',')} (${l.prio || 'normal'}), writing fastest: ${l.cmd.slice(0, 60)}\n`);
182
+ event({ kind: 'pause', id: l.id, res: l.res, who: l.who, prio: l.prio || 'normal', why: 'hard stop', diskFree: m.diskFree });
183
+ notify(l, `hardstop:#${l.id}:${l.pausedAt}`, `your job #${l.id} (${l.purpose ? `"${l.purpose}", ` : ''}${l.cmd.slice(0, 60)}) is paused: free disk is down to ${free}, `
184
+ + `under the ${gb(HARD_STOP).replace(/G$/, ' GB')} where every job on the machine is about to fail, and it was writing the most. It resumes once there's ${gb(HARD_RESUME).replace(/G$/, ' GB')}. `
185
+ + "Free what you can of your own now: build output, scratch folders and merged worktrees your session made. Don't end the job or run it again.");
186
+ }
187
+ return r;
188
+ }
189
+
111
190
  export async function throttle(o, cfg) {
112
191
  if (!o.watch) {
113
192
  const seen = new Map();
@@ -122,7 +201,7 @@ export async function throttle(o, cfg) {
122
201
  say(`throttling: when load is over ${cfg.coolLoad}, build and test processes outside dibs go to background priority.`
123
202
  + ` Under heavy memory pressure, idle and low dibs jobs pause until it eases; when swap fills the disk, jobs below high pause until there's room. Log: ${LOG}`);
124
203
  const seen = new Map(), track = { high: 0, low: 0, diskOk: 0, diskStill: 0 };
125
- let sampled = 0, nudged = 0;
204
+ let sampled = 0, nudged = 0, stuckSince = null, found = [], looked = 0;
126
205
  // Disk pauses stay while the disk is still critical: the next watcher adopts them (src/preempt.mjs settle).
127
206
  const stop = () => {
128
207
  try { withState(s => pressureResume(s, diskCritical(machine(), cfg) ? 'memory' : true)); } catch {}
@@ -143,11 +222,27 @@ export async function throttle(o, cfg) {
143
222
  // First, without the lock: a broker stuck while holding it would hold up this pass too.
144
223
  const fixed = watchBroker();
145
224
  if (fixed) fs.appendFileSync(LOG, `${new Date().toISOString()} ${fixed}\n`);
146
- try { throttleOnce(cfg, seen); pressureOnce(cfg, track); diskOnce(cfg, track); } catch (e) { if (!noSpace(e)) throw e; }
225
+ try {
226
+ const leased = leasedGroups();
227
+ throttleOnce(cfg, seen, leased);
228
+ const m = machine(), stuck = coresStuck(m);
229
+ if (stuck !== (stuckSince != null)) fs.appendFileSync(LOG, `${new Date().toISOString()} load ${m.load.toFixed(0)} with ${Math.round(100 * (1 - m.busy / m.cores))}% of the CPU idle: `
230
+ + `${stuck ? 'cores look stuck, lowering nothing until it passes' : 'the cores are taking work again'}\n`);
231
+ stuckSince = stuck ? stuckSince ?? now() : null;
232
+ if (now() - looked >= ORPHAN_EVERY) {
233
+ looked = now();
234
+ const hot = processes().filter(p => p.cpu >= HOT && p.pid !== process.pid);
235
+ found = orphans(hot, leased, runtimes(hot.map(p => p.pid)));
236
+ }
237
+ noteCpu({ stuckSince, ...(stuck && { load: Math.round(m.load), idle: Math.round(100 * (1 - m.busy / m.cores)), cores: m.cores, swapping: m.vmPressure >= 1 || swapGrowing(m) }), orphans: found });
238
+ pressureOnce(cfg, track); diskOnce(cfg, track);
239
+ } catch (e) { if (!noSpace(e)) throw e; }
240
+ // A lift whose waiter went away without leaving (kill -9) drops back here (src/override.mjs inversions).
241
+ try { lift(withState(s => inversions(s, cfg))); } catch (e) { if (!noSpace(e)) throw e; }
147
242
  // Not awaited: measuring a full temp folder can take a minute, and this loop keeps the machine's pace meanwhile.
148
243
  hogsOnce(cfg, machine());
149
244
  // Alerts open and close even while nobody looks at the board (src/alerts.mjs); the scan itself keeps its pace.
150
- scanAlerts({ s: peek(), cfg, hist: history() });
245
+ scanAlerts({ s: peek(), cfg, hist: history(), watcher: true });
151
246
  // Open progress tasks gone quiet or past their ETA: their agents hear about it (src/notices.mjs).
152
247
  if (now() - nudged >= SAMPLE_EVERY) { nudged = now(); progressScan(); }
153
248
  if (now() - sampled >= SAMPLE_EVERY) {
package/src/diskwarn.mjs CHANGED
@@ -16,6 +16,7 @@ import { freeDisk, OS } from './platform.mjs';
16
16
  import { event } from './events.mjs';
17
17
  import { gb, bytes, now } from './util.mjs';
18
18
  import { makeAlive } from './proc.mjs';
19
+ import { withState } from './state.mjs';
19
20
 
20
21
  const GB = b => gb(b).replace(/G$/, ' GB');
21
22
  const SAY_FREED = 0.1 * 1024 ** 3; // less than shows as 0.0 GB: not worth a line
@@ -84,6 +85,9 @@ export async function clean(t = now(), where = HOME) {
84
85
  done.push({ label: st.label, freed: Math.max(0, by) });
85
86
  }
86
87
  const freed = done.reduce((a, d) => a + d.freed, 0);
88
+ // The room this freed hides what running jobs wrote meanwhile, so their runs don't count
89
+ // toward being small (src/schedule.mjs tinyDisk).
90
+ try { withState(s => { for (const l of s.leases) if (l.kind === 'run') l.cleaned = true; }); } catch {}
87
91
  try {
88
92
  fs.appendFileSync(LOG, `${new Date(t).toISOString()} disk low: dibs cleared ${done.map(d => d.label).join(', ')}, freeing ${GB(freed)}\n`);
89
93
  event({ kind: 'clean', freed, steps: done });
package/src/events.mjs CHANGED
@@ -7,7 +7,7 @@
7
7
  // run: an error is written once per process to dibs.log and dropped.
8
8
  import fs from 'node:fs';
9
9
  import path from 'node:path';
10
- import { HOME } from './config.mjs';
10
+ import { HOME, paths } from './config.mjs';
11
11
  import { now } from './util.mjs';
12
12
 
13
13
  export const EVENTS = path.join(HOME, 'events.jsonl');
@@ -33,7 +33,16 @@ export function event(e) {
33
33
 
34
34
  // Move the current file aside once it's past half of either limit. Called
35
35
  // under the state lock, so two processes never rotate at once.
36
+ // Run times (src/state.mjs record) rotate the same way, at RUNS_ROTATE: about 15,000
37
+ // runs, a month here. Learned sizes need only the newest 1000, read across both files.
38
+ const RUNS_ROTATE = 2 * 1024 ** 2;
39
+ function rotateRuns() {
40
+ try { if (fs.statSync(paths.history).size >= RUNS_ROTATE) fs.renameSync(paths.history, paths.historyOlder); }
41
+ catch (e) { if (e.code !== 'ENOENT') complain(e); }
42
+ }
43
+
36
44
  export function rotate(t = now()) {
45
+ rotateRuns();
37
46
  try {
38
47
  const st = fs.statSync(EVENTS);
39
48
  if (st.size < KEEP_BYTES / 2 && t - firstAt() < KEEP_MS / 2) return;
package/src/files.mjs CHANGED
@@ -6,9 +6,22 @@
6
6
  // but util.mjs, reads state.json without the lock (it's written by rename) and
7
7
  // spawns nothing unless another session's lease covers the path.
8
8
  import fs from 'node:fs';
9
- import os from 'node:os';
10
- import path from 'node:path';
9
+ import nodeOs from 'node:os';
10
+ import nodePath from 'node:path';
11
11
  import { execFileSync } from 'node:child_process';
12
+
13
+ // Every path in this file is written with /, Windows too (C:/Users/x/src/a.ts, as
14
+ // git writes them): lease keys, globs and the hook's comparisons all split on /.
15
+ // path and os here hand back paths that way; macOS and Linux are unchanged.
16
+ const WIN = process.platform === 'win32';
17
+ const slash = p => (WIN && typeof p === 'string' ? p.replace(/\\/g, '/') : p);
18
+ const path = !WIN ? nodePath : {
19
+ ...nodePath, sep: '/',
20
+ resolve: (...a) => slash(nodePath.resolve(...a)), join: (...a) => slash(nodePath.join(...a)), dirname: p => slash(nodePath.dirname(p)),
21
+ relative: (a, b) => slash(nodePath.relative(a, b)), normalize: p => slash(nodePath.normalize(p)),
22
+ };
23
+ const os = !WIN ? nodeOs : { ...nodeOs, homedir: () => slash(nodeOs.homedir()), tmpdir: () => slash(nodeOs.tmpdir()) };
24
+ const cwdNow = () => slash(process.cwd());
12
25
  import { dur, clock, fakeFull, callerPid } from './util.mjs';
13
26
 
14
27
  export const FILES = 'files:';
@@ -50,7 +63,9 @@ function sibling(l, w) {
50
63
  let tmpRoots = null;
51
64
  export function claudeTmp() {
52
65
  if (tmpRoots) return tmpRoots;
53
- const uid = process.getuid?.();
66
+ // Claude Code names it claude-<getuid() ?? 0>: claude-0 on Windows, which has no uid, under
67
+ // CLAUDE_CODE_TMPDIR or /tmp, which there is \tmp on the current drive (Claude Code 2.1.323).
68
+ const uid = process.getuid?.() ?? (WIN ? 0 : null);
54
69
  if (uid == null) return (tmpRoots = []);
55
70
  // DIBS_CLAUDE_TMP: tests put the temp folder somewhere of their own.
56
71
  const bases = process.env.DIBS_CLAUDE_TMP ? [process.env.DIBS_CLAUDE_TMP]
@@ -87,12 +102,11 @@ function guessedOthers(prefix, session) {
87
102
  return null;
88
103
  }
89
104
 
90
- // Inside a session's own folder its subagents share the scratchpad, so a
91
- // recursive delete there could still take a sibling's work. dibs remembers
92
- // which agent first wrote into each folder at the top of the scratchpad
93
- // (scratch/<session>/<folder> in DIBS_HOME, made with wx so the first one
94
- // wins without a lock), and a recursive delete of one is that agent's alone.
95
- const UNTRACKED_MAX = 20; // files: an older folder this small is cheap to lose, one bigger may be someone's work
105
+ // dibs remembers which agent first wrote into each folder at the top of a
106
+ // session's scratchpad (scratch/<session>/<folder> in DIBS_HOME, made with wx so
107
+ // the first one wins without a lock), so the disk watcher can tell whose it is
108
+ // (src/hogs.mjs). It never decides who may delete: every agent of a session may
109
+ // delete anything in its own scratchpad short of all of it.
96
110
  const makersDir = session => path.join(dibsHome(), 'scratch', session);
97
111
  const agentOf = input => input.agent_id || 'main';
98
112
 
@@ -106,73 +120,25 @@ function inSession(p) {
106
120
  return null;
107
121
  }
108
122
 
109
- // Subagents of a session that have stopped (SubagentStop), so the main thread may clear
110
- // what they left in the scratchpad. A teammate that takes another message starts again
111
- // and loses the mark. The name can't be a folder's: encodeURIComponent never makes a bare %.
112
- const stopMark = (session, agent) => path.join(makersDir(session), '%stopped', encodeURIComponent(agent));
113
- export function subagentState(input) {
114
- if (typeof input?.session_id !== 'string' || typeof input.agent_id !== 'string' || !input.agent_id) return;
115
- const f = stopMark(input.session_id, input.agent_id);
116
- try {
117
- if (input.hook_event_name === 'SubagentStop') { fs.mkdirSync(path.dirname(f), { recursive: true }); fs.writeFileSync(f, String(Date.now())); }
118
- else if (input.hook_event_name === 'SubagentStart') fs.rmSync(f, { force: true });
119
- } catch {}
120
- }
121
- const stopped = (session, agent) => fs.existsSync(stopMark(session, agent));
122
-
123
- // Folders that rebuild themselves: a browser profile's caches, Xcode's and Swift's build
124
- // output, a bundler's. Any agent of the session may clear them in its own scratchpad
125
- // (on 2026-11-03 an agent had to ask a teammate to delete Chrome caches in its own session).
126
- const CACHES = new Set(['Cache', 'Caches', 'Code Cache', 'GPUCache', 'DerivedData', '.build', 'build', 'dist', '.next', '.turbo', '.cache']);
127
-
128
123
  export function maker(session, name) {
129
124
  try { return JSON.parse(fs.readFileSync(path.join(makersDir(session), encodeURIComponent(name)), 'utf8')); } catch { return null; }
130
125
  }
131
126
 
132
- // Whether the folder at dir holds more than max files, stopping as soon as it does.
133
- function bigger(dir, max) {
134
- const stack = [dir];
135
- let n = 0;
136
- while (stack.length) {
137
- let list;
138
- try { list = fs.readdirSync(stack.pop(), { withFileTypes: true }); } catch { continue; }
139
- for (const e of list) {
140
- if (e.isDirectory()) stack.push(path.join(e.parentPath ?? e.path, e.name));
141
- else if (++n > max) return true;
142
- }
143
- }
144
- return false;
145
- }
146
-
147
- const agentName = m => (m.agent === 'main' ? 'the main thread' : m.type ? `${m.type} (${m.agent})` : m.agent);
148
-
149
127
  // Why a recursive delete of p, in the caller's own session folder, would take
150
- // what isn't the caller's to take, or null when it's fine.
128
+ // the whole of what every agent of the session shares, or null when it's fine.
151
129
  function ownDelete(p, t, input) {
152
130
  const at = inSession(p);
153
131
  if (!at) return null;
154
132
  const [folder, rest] = at, pad = path.join(folder, 'scratchpad');
155
133
  const whole = what => `${p} is ${what}, which every agent of your session keeps its scratch files in, so ${t.why} can't delete all of it.\n`
156
- + 'Delete the folders in it that you made instead. If it really must all go, have the person delete it.';
134
+ + 'Delete the folders in it you are done with instead. If it really must all go, have the person delete it.';
157
135
  if (!rest.length) return whole("your session's temp folder");
158
136
  if (!overlap(path.join(folder, rest[0]), pad)) return null;
159
137
  if (rest.length === 1) return whole("your session's scratchpad");
160
- if (!GLOB.test(rest.slice(1).join('/')) && rest.slice(1).some(n => CACHES.has(n))) return null;
161
- let names = [rest[1]];
162
- if (GLOB.test(rest[1])) {
163
- try { names = fs.readdirSync(pad).filter(n => overlap(path.join(pad, rest[1]), path.join(pad, n))); } catch { names = []; }
164
- }
165
- for (const n of names) {
166
- const m = maker(input.session_id, n), dir = path.join(pad, n);
167
- // The main thread may clear what a subagent of its own left, once that subagent has stopped.
168
- if (m && m.agent !== agentOf(input) && !(agentOf(input) === 'main' && m.agent !== 'main' && stopped(input.session_id, m.agent)))
169
- return `${dir} in your session's scratchpad was made by ${agentName(m)}, another agent of your session, so ${t.why} can't delete it.\n`
170
- + `Ask ${m.agent === 'main' ? 'the main thread' : m.type || m.agent} whether it's done with it, or have the person delete it. Deleting single files in it is fine, `
171
- + `and so is a cache or build folder in it (${[...CACHES].join(', ')})${agentOf(input) === 'main' ? '. Once that subagent has finished, you may delete the folder' : ''}.`;
172
- if (!m && !namedBy(input.session_id, n, agentOf(input)) && bigger(names.length > 1 || rest.length === 2 ? dir : p, UNTRACKED_MAX))
173
- return `${dir} in your session's scratchpad holds more than ${UNTRACKED_MAX} files, and dibs can't tell which agent of your session made it (it's older than dibs's record), so ${t.why} can't delete it all.\n`
174
- + 'Ask the agents of your session whose it is, or have the person delete it. Deleting single files in it is fine.';
175
- }
138
+ // A glob of only wildcards at the top (scratchpad/*, scratchpad/.*) is the whole scratchpad by another name.
139
+ if (rest.length === 2 && /^[*?.]+$/.test(rest[1])) return whole("your session's scratchpad");
140
+ // Anything under it is the session's own, whoever of the session made it and however
141
+ // old: 2e had to ask a teammate to delete 850 MB of browser profiles at 4.9 GB free (2026-11-04).
176
142
  return null;
177
143
  }
178
144
 
@@ -180,10 +146,9 @@ function ownDelete(p, t, input) {
180
146
  // A program can make a scratchpad folder dibs doesn't see it write
181
147
  // (xcodebuild -derivedDataPath scratchpad/dd made fix-app's 0.5 GB of derived
182
148
  // data on 2026-10-18), so a folder that doesn't exist yet and is named
183
- // anywhere in a command counts as made by whoever ran it. And an agent whose
184
- // command named a folder dibs has no record of may delete it, whatever its size.
149
+ // anywhere in a command counts as made by whoever ran it.
185
150
  function noteMakers(input, split, written) {
186
- const made = new Set(), named = new Set(), gone = new Set();
151
+ const made = new Set(), gone = new Set();
187
152
  const top = p => {
188
153
  const at = inSession(real(p));
189
154
  return at && at[1][0] === 'scratchpad' && at[1].length >= 2 && !GLOB.test(at[1][1]) && path.basename(at[0]) === input.session_id
@@ -198,12 +163,10 @@ function noteMakers(input, split, written) {
198
163
  }
199
164
  for (const p of namedPaths(input, split)) {
200
165
  const f = top(p);
201
- if (!f) continue;
202
- named.add(f[0]);
203
- if (!fs.existsSync(f[1])) made.add(f[0]);
166
+ if (f && !fs.existsSync(f[1])) made.add(f[0]);
204
167
  }
205
- for (const n of gone) { made.delete(n); named.delete(n); }
206
- if (!made.size && !named.size && !gone.size) return;
168
+ for (const n of gone) made.delete(n);
169
+ if (!made.size && !gone.size) return;
207
170
  // Best effort: a full disk or a race costs only a record, never the call.
208
171
  try {
209
172
  const dir = makersDir(input.session_id);
@@ -217,19 +180,16 @@ function noteMakers(input, split, written) {
217
180
  try { fs.writeFileSync(path.join(dir, encodeURIComponent(n)), JSON.stringify({ agent: agentOf(input), type: input.agent_type || null, at: Date.now() }), { flag: 'wx' }); fresh = true; }
218
181
  catch {}
219
182
  }
220
- // name@agent: encodeURIComponent turns any @ into %40, so these never meet a folder's own record.
221
- for (const n of named) fs.writeFileSync(path.join(dir, `${encodeURIComponent(n)}@${encodeURIComponent(agentOf(input))}`), '');
222
183
  if (fresh) pruneMakers();
223
184
  } catch {}
224
185
  }
225
- const namedBy = (session, name, agent) => fs.existsSync(path.join(makersDir(session), `${encodeURIComponent(name)}@${encodeURIComponent(agent)}`));
226
186
 
227
187
  // Every word of a Bash command that could be a path in this session's folder,
228
188
  // absolute: arguments anywhere (after dibs run's --, too), and --out=<path> values.
229
189
  function namedPaths(input, split) {
230
190
  const cmd = input.tool_name === 'Bash' && input.tool_input?.command;
231
191
  if (typeof cmd !== 'string' || !(cmd.includes(input.session_id) || String(input.cwd).includes(input.session_id))) return [];
232
- return namedIn(cmd, typeof input.cwd === 'string' ? input.cwd : process.cwd(), input.session_id, split, 0);
192
+ return namedIn(cmd, typeof input.cwd === 'string' ? slash(input.cwd) : cwdNow(), input.session_id, split, 0);
233
193
  }
234
194
  // A script handed to a shell with -c is read the same way, from the folder the shell starts in:
235
195
  // dibs run xcode-build -- sh -c '... -derivedDataPath <scratchpad>/dd-test' made 177 MB on
@@ -274,7 +234,7 @@ function mkdirs(input, split) {
274
234
  const segs = input.tool_name === 'Bash' && typeof input.tool_input?.command === 'string' && /\bmkdir\b/.test(input.tool_input.command) && split(input.tool_input.command);
275
235
  if (!segs) return [];
276
236
  const out = [];
277
- for (const { name, args, dir } of commands(segs, typeof input.cwd === 'string' ? input.cwd : process.cwd()))
237
+ for (const { name, args, dir } of commands(segs, typeof input.cwd === 'string' ? slash(input.cwd) : cwdNow()))
278
238
  if (name === 'mkdir') for (const w of operands(args, new Set(['-m', '--mode']))) { const f = from(dir, w); if (f) out.push({ path: f.text, why: 'mkdir' }); }
279
239
  return out;
280
240
  }
@@ -321,7 +281,7 @@ function real(abs) {
321
281
  let k = segs.findIndex(s => GLOB.test(s));
322
282
  if (k < 0) k = segs.length;
323
283
  for (let i = k; i > 1; i--) {
324
- try { return [fs.realpathSync.native(segs.slice(0, i).join('/')), ...segs.slice(i)].join('/'); } catch {}
284
+ try { return [slash(fs.realpathSync.native(segs.slice(0, i).join('/'))), ...segs.slice(i)].join('/'); } catch {}
325
285
  }
326
286
  return abs;
327
287
  }
@@ -377,12 +337,12 @@ function mainOf(dir) {
377
337
  if (path.basename(path.dirname(gitdir)) !== 'worktrees') return null;
378
338
  common = path.dirname(path.dirname(gitdir));
379
339
  }
380
- if (path.basename(common) === '.git') return fs.realpathSync(path.dirname(common));
340
+ if (path.basename(common) === '.git') return slash(fs.realpathSync(path.dirname(common)));
381
341
  // A submodule's own worktrees: its checkout is core.worktree. A bare repo has none, so the repo itself stands in.
382
342
  let config = '';
383
343
  try { config = fs.readFileSync(path.join(common, 'config'), 'utf8'); } catch {}
384
344
  const w = /^\s*worktree\s*=\s*(.+?)\s*$/m.exec(config);
385
- return fs.realpathSync(w ? path.resolve(common, w[1]) : common);
345
+ return slash(fs.realpathSync(w ? path.resolve(common, w[1]) : common));
386
346
  } catch { return null; }
387
347
  }
388
348
 
@@ -405,10 +365,10 @@ export const fileKey = r => (isFiles(r) ? FILES + canon(r.slice(FILES.length)) :
405
365
 
406
366
  // ' in another copy of this repo (wt-trust)' when lease l was taken from a
407
367
  // different worktree of the repo cwd is in, else ''.
408
- export function elsewhere(l, cwd = process.cwd()) {
368
+ export function elsewhere(l, cwd = cwdNow()) {
409
369
  try {
410
370
  if (typeof l?.cwd !== 'string') return '';
411
- const mine = worktreeOf(real(path.resolve(cwd))), theirs = worktreeOf(real(l.cwd));
371
+ const mine = worktreeOf(real(path.resolve(cwd))), theirs = worktreeOf(real(path.resolve(l.cwd)));
412
372
  if (!mine || !theirs || mine[1] !== theirs[1] || mine[0] === theirs[0]) return '';
413
373
  return ` in another copy of this repo (${path.basename(theirs[0])})`;
414
374
  } catch { return ''; }
@@ -457,7 +417,7 @@ function braces(r) {
457
417
  return parts.flatMap(p => braces(r.slice(0, open) + p + r.slice(close + 1))).slice(0, BRACES);
458
418
  }
459
419
 
460
- export function fileRes(r, cwd = process.cwd()) {
420
+ export function fileRes(r, cwd = cwdNow()) {
461
421
  if (!isFiles(r)) return r;
462
422
  const p = r.slice(FILES.length).trim();
463
423
  if (!p) return null;
@@ -465,7 +425,7 @@ export function fileRes(r, cwd = process.cwd()) {
465
425
  }
466
426
 
467
427
  // How a lease reads to a person: relative to the git root you're in, else from ~.
468
- export function short(r, cwd = process.cwd()) {
428
+ export function short(r, cwd = cwdNow()) {
469
429
  if (!isFiles(r)) return r;
470
430
  const p = r.slice(FILES.length);
471
431
  const root = gitRoot(cwd) && real(gitRoot(cwd));
@@ -504,7 +464,7 @@ function walk(a, i, b, j) {
504
464
  // Unsure counts as yes. Both are keyed by the main worktree first (canon), so
505
465
  // a lease an older dibs stored under a worktree's own path still counts.
506
466
  export function overlap(a, b) {
507
- const segs = p => folded(canon(p.replace(FILES, ''))).split('/').filter(Boolean);
467
+ const segs = p => folded(canon(slash(p.replace(FILES, '')))).split('/').filter(Boolean);
508
468
  return walk(segs(a), 0, segs(b), 0);
509
469
  }
510
470
 
@@ -536,7 +496,11 @@ let above = null;
536
496
  function ancestors() {
537
497
  if (above) return above;
538
498
  const up = new Map();
539
- for (const line of execFileSync('ps', ['-A', '-o', 'pid=,ppid='], { encoding: 'utf8', timeout: 2000 }).trim().split('\n')) {
499
+ // Windows has no ps: one CIM read of the table, about a second, once per hook.
500
+ const table = WIN
501
+ ? execFileSync('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', 'Get-CimInstance Win32_Process -Property ProcessId,ParentProcessId | ForEach-Object { "$($_.ProcessId) $($_.ParentProcessId)" }'], { encoding: 'utf8', timeout: 10000, windowsHide: true })
502
+ : execFileSync('ps', ['-A', '-o', 'pid=,ppid='], { encoding: 'utf8', timeout: 2000 });
503
+ for (const line of table.trim().split(/\r?\n/)) {
540
504
  const [pid, ppid] = line.trim().split(/\s+/).map(Number);
541
505
  up.set(pid, ppid);
542
506
  }
@@ -1019,7 +983,7 @@ export function dibsCalls(cmd, split, cwd) {
1019
983
 
1020
984
  function noteAgent(input, split) {
1021
985
  if (input.tool_name !== 'Bash' || typeof input.session_id !== 'string') return;
1022
- const calls = dibsCalls(input.tool_input?.command, split, typeof input.cwd === 'string' ? input.cwd : process.cwd());
986
+ const calls = dibsCalls(input.tool_input?.command, split, typeof input.cwd === 'string' ? slash(input.cwd) : cwdNow());
1023
987
  if (!calls.length) return;
1024
988
  // Only a nicety (naming the subagent): a full disk must not cost the lease check after it.
1025
989
  try {
@@ -1080,7 +1044,7 @@ export const shellRes = rs => {
1080
1044
  // The paths a tool call would write, absolute.
1081
1045
  function targets(input, split, guesses = false) {
1082
1046
  const ti = input.tool_input || {};
1083
- const cwd = typeof input.cwd === 'string' ? input.cwd : process.cwd();
1047
+ const cwd = typeof input.cwd === 'string' ? slash(input.cwd) : cwdNow();
1084
1048
  if (input.tool_name === 'Bash') return bashWrites(ti.command, split, cwd, guesses);
1085
1049
  const p = ti.file_path ?? ti.notebook_path;
1086
1050
  return typeof p === 'string' && p ? [{ path: path.resolve(cwd, expand(p)), why: input.tool_name }] : [];
@@ -1094,7 +1058,7 @@ export function fileGuard(input, split) {
1094
1058
  noteAgent(input, split);
1095
1059
  const live = leases();
1096
1060
  if (!live.length) return null;
1097
- const cwd = typeof input.cwd === 'string' ? input.cwd : process.cwd();
1061
+ const cwd = typeof input.cwd === 'string' ? slash(input.cwd) : cwdNow();
1098
1062
  const t = Date.now();
1099
1063
  for (const target of targets(input, split)) {
1100
1064
  if (target.guess != null) continue;