@dibssoftware/dibs 0.0.180 → 0.0.195

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 (107) hide show
  1. package/CHANGELOG.md +111 -1
  2. package/README.md +10 -8
  3. package/bin/dibs.mjs +379 -74
  4. package/docs/agents.md +303 -0
  5. package/docs/council.md +88 -0
  6. package/docs/files.md +3 -3
  7. package/docs/guard.md +86 -11
  8. package/docs/json.md +211 -0
  9. package/docs/later.md +5 -5
  10. package/docs/machines.md +6 -6
  11. package/docs/questions.md +104 -3
  12. package/docs/reference.md +124 -30
  13. package/docs/relay.md +135 -11
  14. package/docs/releasing.md +7 -1
  15. package/docs/scheduling.md +28 -6
  16. package/docs/secrets.md +53 -0
  17. package/docs/simulators.md +3 -3
  18. package/docs/windows.md +3 -3
  19. package/package.json +1 -1
  20. package/skills/dibs/SKILL.md +79 -149
  21. package/src/about.mjs +341 -0
  22. package/src/acquire.mjs +113 -28
  23. package/src/after.mjs +127 -0
  24. package/src/agents.mjs +2 -1
  25. package/src/alerts.mjs +109 -48
  26. package/src/answers.mjs +2 -2
  27. package/src/board.mjs +21 -16
  28. package/src/broker.mjs +23 -7
  29. package/src/carry.mjs +287 -0
  30. package/src/codex.mjs +132 -0
  31. package/src/commands.mjs +254 -86
  32. package/src/config.mjs +85 -14
  33. package/src/connect.mjs +4 -2
  34. package/src/cool.mjs +28 -12
  35. package/src/council.mjs +482 -0
  36. package/src/cwd.mjs +9 -0
  37. package/src/decisions.mjs +250 -0
  38. package/src/declare.mjs +96 -0
  39. package/src/diskreport.mjs +306 -0
  40. package/src/diskuse.mjs +420 -0
  41. package/src/diskwarn.mjs +68 -13
  42. package/src/doctor.mjs +149 -0
  43. package/src/doors.mjs +547 -0
  44. package/src/durable.mjs +143 -0
  45. package/src/envs.mjs +372 -0
  46. package/src/events.mjs +7 -2
  47. package/src/files.mjs +121 -7
  48. package/src/guard.mjs +288 -105
  49. package/src/guardd.mjs +8 -1
  50. package/src/halt.mjs +63 -0
  51. package/src/handoffs.mjs +362 -0
  52. package/src/history.mjs +34 -4
  53. package/src/hogs.mjs +36 -8
  54. package/src/jobprogress.mjs +283 -0
  55. package/src/later.mjs +21 -10
  56. package/src/lock.mjs +51 -11
  57. package/src/measure.mjs +60 -14
  58. package/src/media.mjs +240 -0
  59. package/src/news.mjs +31 -0
  60. package/src/notes.mjs +49 -8
  61. package/src/notices.mjs +126 -43
  62. package/src/ondemand.mjs +25 -2
  63. package/src/outcome.mjs +163 -0
  64. package/src/overlap.mjs +2 -2
  65. package/src/override.mjs +149 -79
  66. package/src/owner.mjs +15 -2
  67. package/src/people.mjs +236 -0
  68. package/src/pickup.mjs +72 -0
  69. package/src/picture.mjs +321 -0
  70. package/src/plain.mjs +84 -18
  71. package/src/platform.mjs +29 -7
  72. package/src/preempt.mjs +123 -15
  73. package/src/primer.mjs +91 -20
  74. package/src/prints.mjs +99 -0
  75. package/src/proc.mjs +11 -1
  76. package/src/progress.mjs +49 -3
  77. package/src/proof.mjs +102 -0
  78. package/src/push.mjs +271 -0
  79. package/src/questions.mjs +328 -57
  80. package/src/quota.mjs +1 -1
  81. package/src/recap.mjs +205 -0
  82. package/src/relay.mjs +262 -26
  83. package/src/remote.mjs +23 -10
  84. package/src/reviewgate.mjs +268 -0
  85. package/src/reviews.mjs +377 -0
  86. package/src/route.mjs +263 -0
  87. package/src/rules.mjs +216 -0
  88. package/src/schedule.mjs +238 -44
  89. package/src/schema.mjs +62 -0
  90. package/src/scratch.mjs +2 -2
  91. package/src/serve.mjs +3 -2
  92. package/src/service.mjs +5 -1
  93. package/src/signed.mjs +97 -0
  94. package/src/simpool.mjs +46 -1
  95. package/src/spend.mjs +375 -0
  96. package/src/state.mjs +43 -17
  97. package/src/talk.mjs +1082 -134
  98. package/src/thin.sh +2 -0
  99. package/src/trail.mjs +290 -0
  100. package/src/trailnote.mjs +209 -0
  101. package/src/util.mjs +7 -0
  102. package/src/vault.mjs +435 -0
  103. package/src/vendors.mjs +327 -0
  104. package/src/version.mjs +1 -1
  105. package/src/web.mjs +354 -60
  106. package/src/work.mjs +487 -0
  107. package/src/worker.mjs +7 -1
package/src/measure.mjs CHANGED
@@ -5,7 +5,7 @@ const GB = b => gb(b).replace(/G$/, ' GB');
5
5
  // its peak goes into history with its run time, and the next run of the same
6
6
  // command is planned at what it really took.
7
7
  //
8
- // Memory is physical footprint (src/platform.mjs footprints), CPU is the
8
+ // Memory is physical footprint (src/platform.mjs footprints; the working set on Windows), CPU is the
9
9
  // process table's % of a core, both summed over every process group the lease
10
10
  // spans plus, for a pool simulator, the simulator's own launchd_sim tree,
11
11
  // which runs outside the job's. Reading footprints costs a top call, so
@@ -18,11 +18,16 @@ import { processes, footprints, OS } from './platform.mjs';
18
18
  import { withStateIfRoom } from './state.mjs';
19
19
  import { gb, now, bytes, runsOf, say, KEY_SPLIT } from './util.mjs';
20
20
  import { event } from './events.mjs';
21
+ import { noteCpu } from './jobprogress.mjs';
22
+ import { marginOf } from './schedule.mjs';
21
23
 
22
24
  // top costs about 0.3s of CPU per call, so 10s keeps it near 3% of one core
23
25
  // while anything runs, and nothing while nothing does. A build's peak lasts
24
26
  // longer than that; a spike shorter than it can be missed.
25
27
  export const SAMPLE_EVERY = Number(process.env.DIBS_SAMPLE_MS) || 10e3;
28
+ // A measurement counts the CPU a job had since the one before for at most this long: three
29
+ // slots, or three of a run's 3-second ticks when the slots are shorter than those.
30
+ const CPU_GAP_MAX = Math.max(3 * SAMPLE_EVERY, 9e3);
26
31
  // The learned size is the most any of the last few measured runs used: one
27
32
  // light run doesn't undo a heavy one, and a command that got lighter is
28
33
  // believed after this many runs.
@@ -48,7 +53,7 @@ export function treeOf(l, s, procs) {
48
53
  for (const x of s.leases || [])
49
54
  if (x.id !== l.id && x.kind === 'run' && x.pgid && x.pgid !== l.pgid && groups.has(x.pgid))
50
55
  for (const g of [x.pgid, ...(x.groups || [])]) groups.delete(g);
51
- const pids = new Set(procs.filter(p => groups.has(p.pgid)).map(p => p.pid));
56
+ const pids = OS === 'windows' ? windowsTree(l, groups, s, procs) : new Set(procs.filter(p => groups.has(p.pgid)).map(p => p.pid));
52
57
  const holds = new Set(s.leases.filter(h => h.kind === 'hold' && h.pid && h.pid === l.spid).map(h => h.id));
53
58
  // A hold's simulator counts in one of the runs under it, the first: two test
54
59
  // runs on one held simulator each counting it charged it twice.
@@ -74,6 +79,21 @@ export function treeOf(l, s, procs) {
74
79
  return pids;
75
80
  }
76
81
 
82
+ // Windows has no process groups (each process's group is its pid): a lease is its groups' processes
83
+ // and everything under them by parent, less the trees of runs nested in it, measured as their own.
84
+ function windowsTree(l, groups, s, procs) {
85
+ const kids = new Map();
86
+ for (const p of procs) if (p.ppid !== p.pid) { if (!kids.has(p.ppid)) kids.set(p.ppid, []); kids.get(p.ppid).push(p.pid); }
87
+ const nested = new Set((s.leases || []).filter(x => x.id !== l.id && x.kind === 'run' && x.pgid && x.pgid !== l.pgid).map(x => x.pgid));
88
+ const pids = new Set(), stack = procs.filter(p => groups.has(p.pgid)).map(p => p.pid);
89
+ while (stack.length) {
90
+ const pid = stack.pop();
91
+ if (pids.has(pid) || nested.has(pid)) continue;
92
+ pids.add(pid);
93
+ stack.push(...(kids.get(pid) || []));
94
+ }
95
+ return pids;
96
+ }
77
97
  // Memory in bytes and CPU in cores for a set of pids. A process top didn't
78
98
  // list (it started since) counts at its RSS.
79
99
  export function usage(pids, procs, foot) {
@@ -126,7 +146,7 @@ function shareDisk(s, got, m, t) {
126
146
  // Measure every run lease on the machine, if this process won the slot.
127
147
  // Called from each `dibs run` on its group-tracking tick. True if it measured.
128
148
  export function sample(t = now()) {
129
- if (OS === 'windows' || !claim(t)) return false;
149
+ if (!claim(t)) return false;
130
150
  // A plain read: the state file is replaced whole, never written in place.
131
151
  let s;
132
152
  try { s = JSON.parse(fs.readFileSync(paths.state, 'utf8')); } catch { return false; }
@@ -146,6 +166,11 @@ export function sample(t = now()) {
146
166
  for (const l of s.leases) {
147
167
  const u = got.get(l.id);
148
168
  if (!u) continue;
169
+ // What it has had of the CPU, added up: the work it got done, where its clock time is only time
170
+ // (src/jobprogress.mjs). A long gap (the machine asleep) or a pause adds nothing it can't vouch for.
171
+ if (l.cpuAt && !l.pausedAt) l.cpuMs = (l.cpuMs || 0) + u.cpu * Math.min(t - l.cpuAt, CPU_GAP_MAX);
172
+ l.cpuAt = t;
173
+ noteCpu(l, t);
149
174
  l.use = { ...u, at: t };
150
175
  // When its memory last rose past what it had reached: a job let in by the
151
176
  // stall breaker counts as settled once this is a while ago (schedule.mjs).
@@ -212,9 +237,14 @@ function family(key) {
212
237
  }
213
238
  // Only runs measured with fit() count: earlier ones counted shared memory in
214
239
  // every process, and planned browser runs at three times what they used.
215
- export function learned(hist, key, cores = hardware().cores) {
216
- let runs = runsOf(hist, key).filter(h => h.mem > 0 && h.fit);
217
- if (!runs.length) runs = hist.filter(h => h.mem > 0 && h.fit && family(h.key) === family(key));
240
+ // repo: only runs from that project (or recorded before runs said which), since
241
+ // npm test in one repo says nothing about npm test in another. own: the runs were
242
+ // of this very command, not borrowed from its family.
243
+ export function learned(hist, key, cores = hardware().cores, repo = null) {
244
+ const here = h => !repo || !h.repo || h.repo === repo;
245
+ let runs = runsOf(hist, key).filter(h => h.mem > 0 && h.fit && here(h));
246
+ const own = runs.length > 0;
247
+ if (!own) runs = hist.filter(h => h.mem > 0 && h.fit && here(h) && family(h.key) === family(key));
218
248
  runs = runs.slice(-LEARN_RUNS);
219
249
  if (!runs.length) return null;
220
250
  // The middle run, not the biggest: one run that read 15 GB (a browser's shared
@@ -223,20 +253,35 @@ export function learned(hist, key, cores = hardware().cores) {
223
253
  // A run that outgrows its plan books what it uses anyway (memOf).
224
254
  const mems = runs.map(h => h.mem).sort((a, b) => a - b);
225
255
  const mem = mems[Math.floor(mems.length / 2)];
226
- return { mem: Math.min(mem, hardware().mem), cpu: Math.min(Math.max(...runs.map(h => h.cpu || 0)), cores) };
256
+ // Cores the same way. A run's cpu is its busiest 10-second sample, and the biggest of
257
+ // those planned an incremental Xcode rebuild at 9 of 10 cores on 2026-11-27: its runs
258
+ // peaked at 0.9 to 9.4, it needed nearly every core free, and waited 42 minutes on
259
+ // 2.6 cores in use. A running job books the cores it uses (coresOf), not its peak.
260
+ const cpus = runs.map(h => h.cpu || 0).sort((a, b) => a - b);
261
+ return { mem: Math.min(mem, hardware().mem), cpu: Math.min(cpus[Math.floor(cpus.length / 2)], cores), own };
227
262
  }
228
263
 
229
- // A job's size as dibs plans it: what it asked for, raised to what its
230
- // command has really used. asked and askedCpu keep the declared numbers. A
231
- // command that has used more than the whole memory budget is planned at the
264
+ // A job's size as dibs plans it. Once this command has run here (in this
265
+ // project), its memory is what its runs peaked at plus a margin (marginOf),
266
+ // whatever it asked for: --mem is the first guess for a job dibs has never
267
+ // seen. Agents that asked honestly, high, waited behind ones that asked low
268
+ // (the person, 2026-11-28). A size borrowed from the command's family only
269
+ // raises an ask, never lowers one. asked and askedCpu keep the declared numbers.
270
+ // learnedMem: the plan is what runs showed, so the ask can't make it never fit (explicitAsk).
271
+ // A command that has used more than the whole memory budget is planned at the
232
272
  // budget, with usual saying what it used: it waits for the budget to empty,
233
273
  // not for a machine with no leases at all.
234
- export function sized(size, hist, key, cfg) {
235
- const got = learned(hist, key, cfg.cores);
274
+ export function sized(size, hist, key, cfg, repo = null) {
275
+ const got = learned(hist, key, cfg.cores, repo);
236
276
  if (!got) return size;
237
277
  const out = { ...size };
238
278
  const budget = bytes(cfg.budget);
239
- if (got.mem > size.mem) Object.assign(out, got.mem > budget && size.mem <= budget ? { mem: budget, asked: size.mem, usual: got.mem } : { mem: got.mem, asked: size.mem });
279
+ const plan = Math.min(got.mem + marginOf(got.mem), hardware().mem);
280
+ if (got.own || plan > size.mem) {
281
+ Object.assign(out, got.mem > budget ? { mem: budget, asked: size.mem, usual: got.mem } : { mem: Math.min(plan, budget), asked: size.mem });
282
+ if (got.own) out.learnedMem = true;
283
+ out.used = got.mem; // what its runs peaked at, for the line that says why (grewPlain)
284
+ }
240
285
  // Like memory: a learned number past the CPU budget is planned at the budget, so the job can still start alone.
241
286
  if (Math.ceil(got.cpu) > size.cpu) Object.assign(out, { cpu: size.cpu <= cfg.cores ? Math.min(Math.ceil(got.cpu), cfg.cores) : Math.ceil(got.cpu), askedCpu: size.cpu });
242
287
  return out;
@@ -255,6 +300,7 @@ export function grewPlain(x, key) {
255
300
  if (x.usual != null)
256
301
  return `${what} usually uses up to ${GB(x.usual)} of memory${cores ? ` and ${cores}` : ''}, more than the ${GB(x.mem)} dibs shares out at once,`
257
302
  + ` so dibs plans it at all ${GB(x.mem)}: it starts when no other job is using that memory.`;
303
+ if (x.asked != null && x.used != null) return `${what} used up to ${GB(x.used)} of memory${cores ? ` and ${cores}` : ''} in recent runs (it asks for ${GB(x.asked)}), so dibs plans for ${GB(x.mem)}.`;
258
304
  const parts = [x.asked != null ? `${GB(x.mem)} of memory (it asks for ${GB(x.asked)})` : '', cores].filter(Boolean);
259
305
  return parts.length ? `${what} used up to ${parts.join(' and ')} in recent runs, so dibs plans for that.` : '';
260
306
  }
@@ -263,5 +309,5 @@ export function grewLine(x) {
263
309
  const cores = x.askedCpu != null ? `${x.cpu} cores (asked ${x.askedCpu})` : '';
264
310
  if (x.usual != null) return `usually uses ~${gb(x.usual)}${cores ? ` and ${cores}` : ''}; planned at the ${gb(x.mem)} budget`;
265
311
  const parts = [x.asked != null ? `~${gb(x.mem)} (asked ${gb(x.asked)})` : '', cores].filter(Boolean);
266
- return parts.length ? `uses ${parts.join(' and ')}` : '';
312
+ return parts.length ? `planned at ${parts.join(' and ')}` : '';
267
313
  }
package/src/media.mjs ADDED
@@ -0,0 +1,240 @@
1
+ // Files and links that travel with a message (dibs say --file, dibs tell --link, ...).
2
+ //
3
+ // A file is copied at send into ~/.dibs/media, named by a hash of its bytes, so what the
4
+ // person or another agent opens is what was sent, even after the original changes or goes:
5
+ // media/<id>/<name> the bytes, under the name it was sent with (a second name is a hard link)
6
+ // media/<id>.json { id, kind, mime, size, at }, touched at every send
7
+ // A link is a grant for one path on this Mac, read live: media/links/<id>.json { id, path,
8
+ // isDir, name, at }. Reads under it resolve every link and must land inside the granted path.
9
+ //
10
+ // No lock: every write is a whole file renamed into place, and one id names the same bytes
11
+ // whoever writes them. Secret-looking files (SECRET, as src/remote.mjs keeps them home) are
12
+ // refused at send, never listed under a link and never served from one.
13
+ import fs from 'node:fs';
14
+ import os from 'node:os';
15
+ import path from 'node:path';
16
+ import crypto from 'node:crypto';
17
+ import { HOME } from './config.mjs';
18
+ import { SECRET } from './remote.mjs';
19
+ import { die, now, size as sized } from './util.mjs';
20
+
21
+ export const MEDIA = path.join(HOME, 'media');
22
+ const LINKS = path.join(MEDIA, 'links');
23
+ // A PDF report, a CSV export or a set of screenshots fits well under this. Past it a file is a
24
+ // build product, not something to read on a phone, and through the relay it would take a dozen
25
+ // round trips of RELAY_CHUNK each: share it live with --link instead.
26
+ export const MAX_FILE = 25 * 1024 ** 2;
27
+ // Every attachment kept, together. This Mac runs near its 5 GB disk floor, and a week of
28
+ // attachments must never be what pushes it under.
29
+ export const MAX_STORE = 500 * 1024 ** 2;
30
+ // As long as the messages that carry them (KEEP_FOR in src/talk.mjs).
31
+ const KEEP_FOR = 7 * 24 * 36e5;
32
+ // More than this in one message is a folder: send it with --link.
33
+ export const MAX_ATTACH = 10;
34
+ // A folder listing past this many entries is cut short and says so.
35
+ const MAX_LIST = 2000;
36
+ // Through the relay a file comes in pieces of at most this many bytes. Base64 grows it by a
37
+ // third, and the answer must fit the relay's largest frame (4 MiB, src/relay.mjs BUCKETS).
38
+ export const RELAY_CHUNK = 2 * 1024 ** 2;
39
+
40
+ const EXT = {
41
+ png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg', gif: 'image/gif', webp: 'image/webp', heic: 'image/heic', heif: 'image/heif', bmp: 'image/bmp', svg: 'image/svg+xml',
42
+ pdf: 'application/pdf', csv: 'text/csv', tsv: 'text/tab-separated-values', md: 'text/markdown', markdown: 'text/markdown',
43
+ txt: 'text/plain', log: 'text/plain', json: 'application/json', html: 'text/html', htm: 'text/html', zip: 'application/zip',
44
+ mov: 'video/quicktime', mp4: 'video/mp4', m4a: 'audio/mp4', mp3: 'audio/mpeg', wav: 'audio/wav',
45
+ };
46
+ // Types a browser may show in place. Anything else (HTML above all, which would run in the
47
+ // page's own origin) is served as a download.
48
+ const INLINE = /^(image\/(png|jpeg|gif|webp|heic|heif|bmp|svg\+xml)|application\/pdf|application\/json|text\/(plain|csv|tab-separated-values|markdown)|video\/(mp4|quicktime)|audio\/(mp4|mpeg|wav))$/;
49
+ export const mimeOf = name => EXT[path.extname(name).slice(1).toLowerCase()] || 'application/octet-stream';
50
+ export const inline = mime => INLINE.test(mime);
51
+ export function kindOf(name, mime = mimeOf(name)) {
52
+ if (mime.startsWith('image/')) return 'image';
53
+ if (mime === 'application/pdf') return 'pdf';
54
+ if (mime === 'text/csv' || mime === 'text/tab-separated-values') return 'csv';
55
+ if (mime === 'text/markdown') return 'report';
56
+ return 'file';
57
+ }
58
+
59
+ // The name a file is kept and shown under: its own, without anything a path or a terminal reads.
60
+ const cleanName = n => path.basename(String(n)).replace(/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}/\\]+/gu, ' ').trim().slice(0, 120) || 'file';
61
+ const FILE_ID = /^[0-9a-f]{32}$/;
62
+ const LINK_ID = /^[A-Za-z0-9_-]{22}$/;
63
+
64
+ // Why this path may not leave the Mac, or null.
65
+ // SECRET reads / between folders: a Windows path's backslashes become / first, or C:/Users/x/id_ed25519 written with backslashes went out.
66
+ const fwd = x => String(x).replace(/\\/g, '/');
67
+ function refusal(p, real) {
68
+ if (SECRET.test(fwd(p)) || SECRET.test(fwd(real)) || SECRET.test(`${fwd(real)}/`)) return `${p} looks like it holds keys or passwords, so dibs won't send it. Send what the reader needs instead (a redacted copy, or the line that matters in the message).`;
69
+ const home = fs.realpathSync(HOME);
70
+ if (real === home || real.startsWith(home + path.sep)) return `${p} is inside dibs's own folder, which holds its tokens, so dibs won't send it.`;
71
+ return null;
72
+ }
73
+
74
+ function realOrDie(p) {
75
+ try { return fs.realpathSync(p); } catch { return die(`${p} doesn't exist (or can't be read). Nothing was sent.`); }
76
+ }
77
+
78
+ // One file into the store: { id, kind, name, size, mime }. as: 'report' marks markdown as a report.
79
+ function keep(p, as) {
80
+ const real = realOrDie(p);
81
+ const why = refusal(p, real);
82
+ if (why) die(`${why} Nothing was sent.`);
83
+ const st = fs.statSync(real);
84
+ if (st.isDirectory()) die(`${p} is a folder. Share a folder live with --link ${p}. Nothing was sent.`);
85
+ if (!st.isFile()) die(`${p} isn't a regular file. Nothing was sent.`);
86
+ if (st.size > MAX_FILE) die(`${p} is ${sized(st.size)}; a message carries files up to ${sized(MAX_FILE)}. Share it live instead: --link ${p}. Nothing was sent.`);
87
+ const data = fs.readFileSync(real);
88
+ const id = crypto.createHash('sha256').update(data).digest('hex').slice(0, 32);
89
+ const name = cleanName(p);
90
+ const mime = as === 'report' ? 'text/markdown' : mimeOf(name);
91
+ const kind = as === 'report' ? 'report' : kindOf(name, mime);
92
+ const dir = path.join(MEDIA, id), file = path.join(dir, name), meta = path.join(MEDIA, `${id}.json`);
93
+ const had = fs.existsSync(meta);
94
+ if (!had && stored() + data.length > MAX_STORE) die(`dibs keeps at most ${sized(MAX_STORE)} of attachments, and this would pass it. Older ones go after a week; share this one live with --link ${p}. Nothing was sent.`);
95
+ fs.mkdirSync(dir, { recursive: true });
96
+ if (!fs.existsSync(file)) {
97
+ const other = fs.readdirSync(dir)[0];
98
+ if (other) fs.linkSync(path.join(dir, other), file);
99
+ else { const tmp = `${file}.${process.pid}.tmp`; fs.writeFileSync(tmp, data); fs.renameSync(tmp, file); }
100
+ }
101
+ writeJson(meta, { id, kind, mime, size: data.length, at: now() });
102
+ return { id, kind, name, size: data.length, mime };
103
+ }
104
+
105
+ // A live share of one file or folder: { id, kind: 'link', name, size, mime, isDir, path }.
106
+ function grant(p) {
107
+ const real = realOrDie(p);
108
+ const why = refusal(p, real);
109
+ if (why) die(`${why} Nothing was sent.`);
110
+ if (real === '/' || real === fs.realpathSync(os.homedir())) die(`${p} would share everything in it. Link the folder that holds what you mean. Nothing was sent.`);
111
+ const st = fs.statSync(real);
112
+ const id = crypto.randomBytes(16).toString('base64url');
113
+ const name = cleanName(real) || real;
114
+ const isDir = st.isDirectory();
115
+ fs.mkdirSync(LINKS, { recursive: true });
116
+ writeJson(path.join(LINKS, `${id}.json`), { id, path: real, isDir, name, at: now() });
117
+ return { id, kind: 'link', name, size: isDir ? 0 : st.size, mime: isDir ? 'inode/directory' : mimeOf(name), isDir, path: real };
118
+ }
119
+
120
+ function writeJson(file, v) {
121
+ const tmp = `${file}.${process.pid}.tmp`;
122
+ fs.writeFileSync(tmp, JSON.stringify(v));
123
+ fs.renameSync(tmp, file);
124
+ }
125
+
126
+ // What the store holds now, after letting go of what's older than a week.
127
+ function stored(t = now()) {
128
+ let total = 0;
129
+ let names = [];
130
+ try { names = fs.readdirSync(MEDIA); } catch { return 0; }
131
+ for (const n of names) {
132
+ if (!n.endsWith('.json')) continue;
133
+ const f = path.join(MEDIA, n);
134
+ try {
135
+ const m = JSON.parse(fs.readFileSync(f, 'utf8'));
136
+ if (t - m.at > KEEP_FOR) { fs.rmSync(path.join(MEDIA, m.id), { recursive: true, force: true }); fs.rmSync(f, { force: true }); continue; }
137
+ total += m.size || 0;
138
+ } catch {}
139
+ }
140
+ try {
141
+ for (const n of fs.readdirSync(LINKS)) {
142
+ const f = path.join(LINKS, n);
143
+ try { if (t - JSON.parse(fs.readFileSync(f, 'utf8')).at > KEEP_FOR) fs.rmSync(f, { force: true }); } catch {}
144
+ }
145
+ } catch {}
146
+ return total;
147
+ }
148
+
149
+ // The flags dibs say, tell and poll share: --file, --report, --link. Returns the args left over
150
+ // and the list asked for, [{ path, as }].
151
+ export function takeFlags(args) {
152
+ const rest = [], want = [];
153
+ for (let i = 0; i < args.length; i++) {
154
+ const a = args[i];
155
+ const as = a === '--file' ? 'file' : a === '--report' ? 'report' : a === '--link' ? 'link' : null;
156
+ if (!as) { rest.push(a); continue; }
157
+ const p = args[++i];
158
+ if (!p) die(`${a} needs a path: dibs say "..." ${a} ./out/${as === 'report' ? 'report.md' : as === 'link' ? 'screenshots' : 'chart.png'}`);
159
+ want.push({ path: p, as });
160
+ }
161
+ if (want.length > MAX_ATTACH) die(`that's ${want.length} attachments; one message carries up to ${MAX_ATTACH}. Put them in a folder and share it with --link. Nothing was sent.`);
162
+ return { rest, want };
163
+ }
164
+
165
+ // Every one checked before any is kept, so one refusal sends nothing.
166
+ export function attach(want) {
167
+ for (const w of want) { const real = realOrDie(w.path); const why = refusal(w.path, real); if (why) die(`${why} Nothing was sent.`); }
168
+ return want.map(w => (w.as === 'link' ? grant(w.path) : keep(w.path, w.as)));
169
+ }
170
+
171
+ // Where an agent on this Mac reads an attachment.
172
+ export const localPath = a => (a.kind === 'link' ? a.path : path.join(MEDIA, a.id, a.name));
173
+
174
+ // A stored file by id: { file, meta } or null.
175
+ export function fileOf(id) {
176
+ if (!FILE_ID.test(String(id))) return null;
177
+ try {
178
+ const meta = JSON.parse(fs.readFileSync(path.join(MEDIA, `${id}.json`), 'utf8'));
179
+ const dir = path.join(MEDIA, id);
180
+ const name = fs.readdirSync(dir).find(n => !n.endsWith('.tmp'));
181
+ return name ? { file: path.join(dir, name), meta: { ...meta, name } } : null;
182
+ } catch { return null; }
183
+ }
184
+
185
+ // What a link reads at rel (a path under it, '' for itself): { dir: listing } or { file, meta },
186
+ // { refused } for a path that leaves the grant or looks secret, null for an unknown link or a missing path.
187
+ export function linkOf(id, rel = '') {
188
+ if (!LINK_ID.test(String(id))) return null;
189
+ let g;
190
+ try { g = JSON.parse(fs.readFileSync(path.join(LINKS, `${id}.json`), 'utf8')); } catch { return null; }
191
+ if (now() - g.at > KEEP_FOR) return null;
192
+ if (typeof rel !== 'string' || rel.includes('\0') || path.isAbsolute(rel)) return { refused: 'path is relative to the shared folder' };
193
+ let real;
194
+ try { real = fs.realpathSync(path.resolve(g.path, rel)); } catch { return null; }
195
+ // Inside the grant after every link is resolved: no .., no symlink out.
196
+ if (real !== g.path && !(g.isDir && real.startsWith(g.path + path.sep))) return { refused: 'that path is outside what was shared' };
197
+ if (refusal(real, real)) return { refused: 'that file looks like it holds keys or passwords, so dibs won\'t serve it' };
198
+ const st = fs.statSync(real);
199
+ const name = path.basename(real);
200
+ if (st.isDirectory()) return { dir: listing(g, real) };
201
+ if (!st.isFile()) return { refused: 'that isn\'t a regular file' };
202
+ const mime = mimeOf(name);
203
+ return { file: real, meta: { id, name, mime, kind: kindOf(name, mime), size: st.size, at: st.mtimeMs } };
204
+ }
205
+
206
+ function listing(g, real) {
207
+ const rel = path.relative(g.path, real);
208
+ let ents = fs.readdirSync(real, { withFileTypes: true }).filter(e => !SECRET.test(path.join(real, e.name)) && !SECRET.test(`${path.join(real, e.name)}/`));
209
+ const more = ents.length > MAX_LIST;
210
+ ents = ents.sort((a, b) => a.name.localeCompare(b.name)).slice(0, MAX_LIST);
211
+ const entries = [];
212
+ for (const e of ents) {
213
+ let st;
214
+ // A symlink that points out of the share isn't listed: it couldn't be opened anyway.
215
+ try { const r = fs.realpathSync(path.join(real, e.name)); if (r !== g.path && !r.startsWith(g.path + path.sep)) continue; st = fs.statSync(r); } catch { continue; }
216
+ const isDir = st.isDirectory();
217
+ const mime = isDir ? 'inode/directory' : mimeOf(e.name);
218
+ entries.push({ name: e.name, path: rel ? `${rel}/${e.name}` : e.name, isDir, size: isDir ? 0 : st.size, mtime: Math.round(st.mtimeMs), kind: isDir ? 'folder' : kindOf(e.name, mime), mime });
219
+ }
220
+ return { id: g.id, name: g.name, root: g.path, path: rel, isDir: true, entries, ...(more && { more: true }) };
221
+ }
222
+
223
+ // A byte range as HTTP's Range header or the relay's ?range= says it ("bytes=0-99", "0-99", "100-",
224
+ // "-500"), within size: { start, end } inclusive, null for the whole file, false for one that can't be met.
225
+ export function rangeOf(v, size) {
226
+ if (v == null || v === '') return null;
227
+ const m = /^(?:bytes=)?(\d*)-(\d*)$/.exec(String(v).trim());
228
+ if (!m || (m[1] === '' && m[2] === '')) return false;
229
+ let start, end;
230
+ if (m[1] === '') { start = Math.max(0, size - Number(m[2])); end = size - 1; }
231
+ else { start = Number(m[1]); end = m[2] === '' ? size - 1 : Math.min(Number(m[2]), size - 1); }
232
+ return start <= end && start < size ? { start, end } : false;
233
+ }
234
+
235
+ export function readRange(file, start, end) {
236
+ const buf = Buffer.alloc(end - start + 1);
237
+ const fd = fs.openSync(file, 'r');
238
+ try { fs.readSync(fd, buf, 0, buf.length, start); } finally { fs.closeSync(fd); }
239
+ return buf;
240
+ }
package/src/news.mjs CHANGED
@@ -37,6 +37,37 @@ export function changelog() {
37
37
  // The sections after from, up to and including to, oldest first.
38
38
  export const since = (from, to) => changelog().filter(c => /^\d/.test(c.version) && newer(c.version, from) && !newer(c.version, to)).reverse();
39
39
 
40
+ // The what's-new notice every agent session reads once per version is at most this many
41
+ // changes: each version's notes run to a dozen lines, and every session paid for all of them.
42
+ export const NEWS_LINES = 3;
43
+ // A change is cut to its first sentence, and a long first sentence to this.
44
+ const NEWS_WIDTH = 160;
45
+
46
+ // The first sentence of a change: up to the first full stop outside backticks.
47
+ function headline(line) {
48
+ const text = line.replace(/^-\s*/, '').trim();
49
+ let tick = false, end = text.length;
50
+ for (let i = 0; i < text.length; i++) {
51
+ if (text[i] === '`') tick = !tick;
52
+ else if (!tick && text[i] === '.' && (i + 1 === text.length || text[i + 1] === ' ')) { end = i + 1; break; }
53
+ }
54
+ const first = text.slice(0, end);
55
+ if (first.length <= NEWS_WIDTH) return first;
56
+ let cut = first.slice(0, NEWS_WIDTH).replace(/\s+\S*$/, '');
57
+ // Never leave a code span open.
58
+ if ((cut.match(/`/g) || []).length % 2) cut = cut.slice(0, cut.lastIndexOf('`')).trimEnd();
59
+ return `${cut} ...`;
60
+ }
61
+
62
+ // What an agent that last ran from hears on its first command under to: the first change of
63
+ // each version since, newest first, which the changelog puts first because it's what changes
64
+ // what an agent does. At most NEWS_LINES of them; dibs news has the rest.
65
+ export function whatsNew(from, to) {
66
+ const firsts = since(from, to).reverse().map(c => c.body.split('\n').find(l => /^-\s/.test(l))).filter(Boolean);
67
+ const shown = firsts.slice(0, NEWS_LINES).map(l => `- ${headline(l)}`);
68
+ return [`dibs was updated to ${to}. What to do differently (all of it: dibs news):`, ...shown];
69
+ }
70
+
40
71
  const readSeen = () => { try { return JSON.parse(fs.readFileSync(paths.seen, 'utf8')); } catch { return {}; } };
41
72
  export const seenBy = key => readSeen()[key] || null;
42
73
  export function markSeen(key, version) {
package/src/notes.mjs CHANGED
@@ -2,14 +2,20 @@
2
2
  //
3
3
  // dibs.md the agent instructions, made from skills/dibs/SKILL.md (one source,
4
4
  // no second copy to drift), in the folder dibs is installed in.
5
- // Rewritten on every install and upgrade, so it matches the version.
5
+ // Rewritten on every install and upgrade, and by any dibs command
6
+ // that finds it missing or older than the code (keep()): a git
7
+ // checkout updates by merges, which run no installer.
6
8
  // the block a few marked lines in the agents' own instruction files saying to
7
9
  // read dibs.md before builds, tests, simulators or deploys:
8
10
  // ~/.claude/CLAUDE.md when ~/.claude exists (made if missing)
9
11
  // ~/.codex/AGENTS.md when ~/.codex exists (made if missing)
12
+ // ~/.gemini/GEMINI.md when ~/.gemini exists (made if missing)
13
+ // ~/.config/opencode/AGENTS.md when that folder exists (made if missing)
14
+ // Cursor keeps its user rules in its settings, not a file: it reads the
15
+ // repo's AGENTS.md below.
10
16
  // CLAUDE.md and AGENTS.md at the root of the git repo dibs runs in,
11
- // when that isn't the home folder: only files already there, unless
12
- // asked with dibs init --repo
17
+ // when that isn't the home folder or dibs's own source: only files
18
+ // already there, unless asked with dibs init --repo
13
19
  //
14
20
  // Only what's between the markers is ever written; the rest of a file stays byte for
15
21
  // byte. Each write goes to a temp file beside the real one, with its mode, then is
@@ -41,10 +47,10 @@ export function dibsMd(root = ROOT) {
41
47
  return [
42
48
  '# dibs: instructions for coding agents',
43
49
  '',
44
- `Written by dibs ${VERSION} when it was installed here, and rewritten on every install and upgrade, so edits don't last.`,
45
- `Docs: https://dibs.cc, and ${path.join(root, 'README.md')}. Every command: \`dibs help all\`.`,
50
+ `Written by dibs ${VERSION}, and rewritten whenever dibs changes, so edits don't last.`,
51
+ `The full agent reference: ${path.join(root, 'docs', 'agents.md')}. Every command: \`dibs help all\`. Docs: https://dibs.cc`,
46
52
  '',
47
- body || 'Run builds, tests, simulators and deploys through dibs: `dibs run <resource> -m "why" -- <command>`. `dibs help` lists everything.',
53
+ body || 'Run builds, tests, simulators and deploys through dibs: `dibs run <resource> -m "<what this does and why, in plain words>" -- <command>`. `dibs help` lists everything.',
48
54
  '',
49
55
  ].join('\n');
50
56
  }
@@ -86,11 +92,17 @@ export function withoutBlock(text) {
86
92
  return before + after;
87
93
  }
88
94
 
89
- // The git repo the command runs in, unless it's the home folder itself.
95
+ // dibs's own source (this checkout, a worktree of it, a clone): its AGENTS.md and CLAUDE.md
96
+ // are tracked instructions for working on dibs, and a note in them would be committed.
97
+ function dibsSource(top) {
98
+ try { return JSON.parse(fs.readFileSync(path.join(top, 'package.json'), 'utf8')).name === '@dibssoftware/dibs'; } catch { return false; }
99
+ }
100
+
101
+ // The git repo the command runs in, unless it's the home folder itself or dibs's own source.
90
102
  function repoRoot(cwd) {
91
103
  try {
92
104
  const top = execFileSync('git', ['rev-parse', '--show-toplevel'], { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], timeout: 3000 }).trim();
93
- return top && path.resolve(top) !== path.resolve(os.homedir()) ? top : null;
105
+ return top && path.resolve(top) !== path.resolve(os.homedir()) && !dibsSource(top) ? top : null;
94
106
  } catch { return null; }
95
107
  }
96
108
 
@@ -99,6 +111,9 @@ function targets(cwd, repo) {
99
111
  const home = os.homedir(), out = [];
100
112
  if (fs.existsSync(path.join(home, '.claude'))) out.push({ file: path.join(home, '.claude', 'CLAUDE.md'), made: true });
101
113
  if (fs.existsSync(path.join(home, '.codex'))) out.push({ file: path.join(home, '.codex', 'AGENTS.md'), made: true });
114
+ if (fs.existsSync(path.join(home, '.gemini'))) out.push({ file: path.join(home, '.gemini', 'GEMINI.md'), made: true });
115
+ const opencode = path.join(process.env.XDG_CONFIG_HOME || path.join(home, '.config'), 'opencode');
116
+ if (fs.existsSync(opencode)) out.push({ file: path.join(opencode, 'AGENTS.md'), made: true });
102
117
  const top = repoRoot(cwd);
103
118
  if (top) {
104
119
  const there = ['CLAUDE.md', 'AGENTS.md'].map(n => path.join(top, n)).filter(f => fs.existsSync(f));
@@ -115,6 +130,32 @@ function mdPlace(root) {
115
130
  try { fs.accessSync(root, fs.constants.W_OK); return f; } catch { return path.join(HOME, 'dibs.md'); }
116
131
  }
117
132
 
133
+ const mtime = f => { try { return fs.statSync(f).mtimeMs; } catch { return 0; } };
134
+
135
+ // dibs.md present and current, from any dibs command: three stats when it is, which is
136
+ // nearly always. It's behind when the skill or the version changed after it was written (a
137
+ // git merge in the checkout dibs runs from, an upgrade), or gone (a fresh clone: it's
138
+ // gitignored). Only dibs.md: the notes in the agents' files name its place, which this
139
+ // doesn't move, and they're dibs init's to write. Never throws: the command comes first.
140
+ // DIBS_KEEP_MD=0 turns it off (test/helpers.mjs, so tests don't race on the checkout's copy).
141
+ export function keep(root = ROOT) {
142
+ if (off() || process.env.DIBS_KEEP_MD === '0') return null;
143
+ try {
144
+ const md = mdPlace(root);
145
+ const at = mtime(md);
146
+ const versionFile = path.join(root, 'src', 'version.mjs');
147
+ if (at && at > mtime(path.join(root, 'skills', 'dibs', 'SKILL.md')) && at > mtime(versionFile)) return null;
148
+ // A process started before an update would write the old version's number: the next one writes it.
149
+ if (/VERSION = '([^']+)'/.exec(fs.readFileSync(versionFile, 'utf8'))?.[1] !== VERSION) return null;
150
+ const text = dibsMd(root);
151
+ let old = null;
152
+ try { old = fs.readFileSync(md, 'utf8'); } catch {}
153
+ if (old === text) { const t = new Date(); fs.utimesSync(md, t, t); return null; }
154
+ writeAtomic(md, text);
155
+ return md;
156
+ } catch { return null; }
157
+ }
158
+
118
159
  // Write dibs.md and the blocks. Returns the files that changed.
119
160
  export function write({ root = ROOT, cwd = process.cwd(), repo = false } = {}) {
120
161
  const changed = [];