@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/serve.mjs CHANGED
@@ -182,7 +182,8 @@ export function bareBusy(busy) {
182
182
  }
183
183
  return out;
184
184
  }
185
- export const bare = x => ({ ...x, cmd: x.cmd == null ? x.cmd : Array.isArray(x.cmd) ? [] : '', purpose: '',
185
+ // A job's progress keeps its percent and loses its words ("13% done, 1200/9000 flops solved" reads "13% done").
186
+ export const bare = x => ({ ...x, cmd: x.cmd == null ? x.cmd : Array.isArray(x.cmd) ? [] : '', purpose: '', ...(typeof x.done === 'string' && { done: x.done.replace(/,.*$/, '') }),
186
187
  ...(Array.isArray(x.res) ? { res: x.res.map(hidePath) } : {}), ...(Array.isArray(x.holds) ? { holds: x.holds.map(hidePath) } : {}) });
187
188
 
188
189
  // What a client sees of an on-demand machine: its state and how long it takes to wake.
@@ -520,7 +521,7 @@ export function makeServer({ token, log = () => {}, self = null, joinUrl = () =>
520
521
  const give = ready ? w.pending.splice(0).map(id => jobs.get(id)).filter(j => j && j.state === 'queued') : [];
521
522
  for (const j of give) Object.assign(j, { state: 'running', started: now() });
522
523
  return { cancel, jobs: give.map(j => ({ ...pub(j), cwdRel: j.cwdRel, files: j.files, bring: j.bring, root: j.root, label: j.label,
523
- prio: j.prio, by: j.by, est: j.est, mem: j.mem, askedMem: j.askedMem, cpu: j.cpu, disk: j.disk, ports: j.ports, wait: j.wait, maxWait: j.maxWait, stayOn: j.stayOn, rule: j.rule, repo: j.repo })) };
524
+ prio: j.prio, by: j.by, est: j.est, timeLimit: j.timeLimit, mem: j.mem, askedMem: j.askedMem, cpu: j.cpu, disk: j.disk, ports: j.ports, wait: j.wait, maxWait: j.maxWait, stayOn: j.stayOn, rule: j.rule, repo: j.repo, ...(j.byAgent === true && { byAgent: true }) })) };
524
525
  };
525
526
  hooks.up?.(w);
526
527
  let a = answer();
package/src/service.mjs CHANGED
@@ -30,7 +30,11 @@ const label = k => `dev.dibs.${k}`;
30
30
  const plist = k => path.join(process.env.DIBS_LAUNCH_AGENTS || path.join(os.homedir(), 'Library', 'LaunchAgents'), `${label(k)}.plist`);
31
31
  const LAUNCHCTL = process.env.DIBS_LAUNCHCTL || 'launchctl';
32
32
  const unit = k => path.join(process.env.DIBS_LAUNCH_AGENTS || path.join(os.homedir(), '.config', 'systemd', 'user'), `dibs-${k}.service`);
33
- const logFile = k => path.join(HOME, `${k}.log`);
33
+ // The guard service's output can't go in guard.log: that's the hook's own error
34
+ // log, which the alerts read as hook failures (src/alerts.mjs readHook).
35
+ const LOGS = { guard: 'guard-service.log' };
36
+ export const logName = k => LOGS[k] || `${k}.log`;
37
+ const logFile = k => path.join(HOME, logName(k));
34
38
  const sh = (cmd, args) => { try { return execFileSync(cmd, args, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }); } catch (e) { return e.stdout || ''; } };
35
39
  const esc = s => String(s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
36
40
  const uid = () => process.getuid?.() ?? 0;
package/src/signed.mjs ADDED
@@ -0,0 +1,97 @@
1
+ // The person's signature on what they send from a paired phone. Agents act on "Message from
2
+ // the person", and every file dibs keeps in ~/.dibs can be written by any process running as
3
+ // this user, so a line in messages.json proves nothing by itself. What does: a phone paired with
4
+ // --allow-talk signs each message, answer and vote with a key that never leaves it (a Secure
5
+ // Enclave key behind Face ID, or a passkey that requires user verification; docs/relay.md
6
+ // "Talking from a phone"). src/relay.mjs checks that signature before the call runs and keeps it
7
+ // with what the call queues; src/talk.mjs checks it again here when it hands the message to an
8
+ // agent, against the phone's public key kept at pairing. Writing a message into the file gets a
9
+ // forger nothing without the phone.
10
+ //
11
+ // What this can't stop: a process that rewrites dibs's own code, the hook, or the phone's public
12
+ // key in relay.json. Those change what dibs believes, not what the phone signed. docs/relay.md
13
+ // "What a signature proves" says the rest.
14
+ //
15
+ // Loaded by the hook only when a message waits (src/talk.mjs), so it reads one file and nothing else.
16
+ import fs from 'node:fs';
17
+ import path from 'node:path';
18
+ import crypto from 'node:crypto';
19
+ import { HOME } from './config.mjs';
20
+
21
+ export const PAGE = process.env.DIBS_RELAY_PAGE || 'https://app.dibs.cc/';
22
+ const DEVICES = path.join(HOME, 'relay.json');
23
+ // Messages are kept a week (src/talk.mjs KEEP_FOR), and a copy of a signed message is caught by
24
+ // finding the one already delivered. Past a week that record is gone, so an older signature isn't taken.
25
+ export const PROOF_LIFE = 7 * 24 * 36e5;
26
+
27
+ const b64u = b => Buffer.from(b).toString('base64url');
28
+ function unb64u(s, len) {
29
+ if (typeof s !== 'string' || !/^[A-Za-z0-9_-]*$/.test(s)) return null;
30
+ const b = Buffer.from(s, 'base64url');
31
+ return b64u(b) === s && (len == null || b.length === len) ? b : null;
32
+ }
33
+ const utf8 = s => Buffer.from(String(s), 'utf8');
34
+ const u32 = n => { const b = Buffer.alloc(4); b.writeUInt32BE(n); return b; };
35
+ const tx = (label, ...fields) => Buffer.concat([label, ...fields].flatMap(f => { const b = Buffer.isBuffer(f) ? f : utf8(f); return [u32(b.length), b]; }));
36
+ const sha = b => crypto.createHash('sha256').update(b).digest();
37
+ const sameBytes = (a, b) => a.length === b.length && crypto.timingSafeEqual(a, b);
38
+
39
+ export const p256 = raw => { try { return crypto.createPublicKey({ key: { kty: 'EC', crv: 'P-256', x: b64u(raw.subarray(1, 33)), y: b64u(raw.subarray(33)) }, format: 'jwk' }); } catch { return null; } };
40
+
41
+ // The body as signed: its fields sorted, no spaces, each a string or true/false, written as
42
+ // JSON.stringify writes them. Null when it has anything else, which no talk call needs.
43
+ export function bodyBytes(body) {
44
+ if (body == null) body = {};
45
+ if (typeof body !== 'object' || Array.isArray(body)) return null;
46
+ const keys = Object.keys(body).filter(k => k !== 'uv').sort();
47
+ if (keys.some(k => !/^[A-Za-z]{1,32}$/.test(k) || !['string', 'boolean'].includes(typeof body[k]))) return null;
48
+ return utf8(`{${keys.map(k => `${JSON.stringify(k)}:${JSON.stringify(body[k])}`).join(',')}}`);
49
+ }
50
+ // What the phone's key signs for one call.
51
+ export const talkDigest = (did, method, where, body, t) => sha(tx('dibs-talk-v1', did, method, where, sha(body), String(t)));
52
+ const verifyP256 = (pub, data, sig, dsaEncoding) => { try { return crypto.verify('sha256', data, { key: p256(unb64u(pub, 65)), dsaEncoding }, sig); } catch { return false; } };
53
+ // rpId and origin: the page's (app.dibs.cc), where the browser made the credential.
54
+ function webauthnOk(tk, digest, uv, page = new URL(PAGE)) {
55
+ const ad = unb64u(uv.authenticatorData), cd = unb64u(uv.clientDataJSON), sig = unb64u(uv.sig);
56
+ if (!ad || !cd || !sig || ad.length < 37 || sig.length > 80) return false;
57
+ let c;
58
+ try { c = JSON.parse(cd.toString('utf8')); } catch { return false; }
59
+ // User present (bit 0) and user verified (bit 2): Face ID or the passcode, not just a tap.
60
+ const flags = ad[32];
61
+ if (!sameBytes(ad.subarray(0, 32), sha(utf8(page.hostname))) || !(flags & 1) || !(flags & 4)) return false;
62
+ if (c?.type !== 'webauthn.get' || c.challenge !== b64u(digest) || c.origin !== page.origin || c.crossOrigin === true) return false;
63
+ return verifyP256(tk.pub, Buffer.concat([ad, sha(cd)]), sig, 'der');
64
+ }
65
+ // Whether uv is the talking key tk's signature over this call: device did, method, path, body bytes.
66
+ export function signatureOk(did, tk, method, where, bytes, uv) {
67
+ if (!uv || typeof uv !== 'object' || !Number.isSafeInteger(uv.t) || uv.kind !== tk?.kind) return false;
68
+ const digest = talkDigest(did, method, where, bytes, uv.t);
69
+ if (tk.kind === 'raw') { const sig = unb64u(uv.sig, 64); return !!sig && verifyP256(tk.pub, digest, sig, 'ieee-p1363'); }
70
+ return tk.kind === 'webauthn' && webauthnOk(tk, digest, uv);
71
+ }
72
+
73
+ // What a checked call leaves with what it queued: the device, the call and the exact bytes signed.
74
+ export const proofOf = (did, method, where, bytes, uv) => ({ d: did, m: method, p: where, b: bytes.toString('utf8'), uv });
75
+
76
+ // The paired devices, read without relay.json's lock: writes are renames.
77
+ export function devices() {
78
+ try { const d = JSON.parse(fs.readFileSync(DEVICES, 'utf8')).devices; return d && typeof d === 'object' ? d : {}; } catch { return {}; }
79
+ }
80
+
81
+ // Every name web/transport.js deviceName() can produce, and the dibs app's (src/web.mjs has the same).
82
+ const LABEL = /^(Edge|Firefox|Chrome|Safari|A browser|dibs app)( on (iPhone|iPad|Android|Mac|Windows|Linux))?$/;
83
+ const label = (dev, did) => `${LABEL.test(dev?.name || '') ? dev.name : 'a browser'} (remote ${String(did).replace(/[^A-Za-z0-9_-]/g, '').slice(0, 8)})`;
84
+
85
+ // A kept proof checked again: { ok, route, body, device } when a phone still paired with this Mac,
86
+ // allowed to talk, signed these bytes in the last week; else { why }, in words for the agent.
87
+ export function checkProof(x, t = Date.now(), list = devices()) {
88
+ if (!x || typeof x !== 'object' || typeof x.d !== 'string' || typeof x.m !== 'string' || typeof x.p !== 'string' || typeof x.b !== 'string')
89
+ return { why: 'its signature is malformed' };
90
+ const dev = Object.hasOwn(list, x.d) ? list[x.d] : null;
91
+ if (!dev || dev.talk !== true || !dev.tk) return { why: 'the phone that signed it is no longer paired with this Mac' };
92
+ if (!Number.isSafeInteger(x.uv?.t) || t - x.uv.t > PROOF_LIFE) return { why: 'it was signed more than a week ago' };
93
+ if (!signatureOk(x.d, dev.tk, x.m, x.p, utf8(x.b), x.uv)) return { why: "its signature doesn't check out" };
94
+ let body, route;
95
+ try { body = JSON.parse(x.b); route = new URL(x.p, 'http://dibs').pathname; } catch { return { why: 'its signature is malformed' }; }
96
+ return { ok: true, route, body, device: label(dev, x.d) };
97
+ }
package/src/simpool.mjs CHANGED
@@ -93,6 +93,51 @@ export function reapPool(s, ctl = null) {
93
93
  }
94
94
  }
95
95
 
96
+ // Free pool devices a lease's command names outright (xcodebuild -destination
97
+ // name=dibs-pool-1, simctl boot <udid>) that no other live lease's command names.
98
+ // A pool device used that way, under sim instead of its pool's own resource,
99
+ // is booted by the command and never by a pool lease, so nothing knew to shut
100
+ // it down: on 2026-11-27 dibs-pool-1 sat booted and idle after an agent's
101
+ // xcodebuild test, holding 3 GB while the disk was under the floor.
102
+ const cmdText = l => (Array.isArray(l?.cmd) ? l.cmd.join(' ') : String(l?.cmd || ''));
103
+ const names = (text, d) => (d.udid && text.includes(d.udid)) || new RegExp(`${d.name}(?!\\d)`).test(text);
104
+ export function namedFree(s, lease) {
105
+ const text = cmdText(lease);
106
+ if (!text.includes(PREFIX) && !(s.pool || []).some(d => d.udid && text.includes(d.udid))) return [];
107
+ const others = (s.leases || []).filter(l => l.id !== lease.id).map(cmdText);
108
+ return (s.pool || []).filter(d => !d.lease && d.udid && names(text, d) && !others.some(o => names(o, d)));
109
+ }
110
+ // When such a run ends: shut down the pool devices it named. Called inside withState, so it only starts the shutdowns.
111
+ export function shutNamed(s, lease, ctl = null) {
112
+ for (const d of namedFree(s, lease)) { (ctl ||= simctl()).shutdownLater(d.udid); d.booted = false; }
113
+ }
114
+
115
+ // Under twice the disk floor (src/diskwarn.mjs clean): shut down and erase the
116
+ // pool's free devices no live lease names, idle at least ERASE_IDLE. The next lease
117
+ // erases one anyway when it goes to another agent, and boots it either way. Not
118
+ // while anyone holds sim: a hold has no command to say which simulator it uses.
119
+ // Returns the bytes freed.
120
+ const ERASE_IDLE = 10 * 6e4; // an agent between two runs on its device gets it back as it was
121
+ export function eraseIdle(ctl = simctl(), t = now()) {
122
+ const idle = withState(s => {
123
+ if ((s.leases || []).some(l => l.kind === 'hold' && l.res.includes('sim'))) return [];
124
+ const live = (s.leases || []).map(cmdText);
125
+ return (s.pool || []).filter(d => !d.lease && d.udid && ours(d.name) && t - (d.lastUsed || 0) >= ERASE_IDLE && !live.some(o => names(o, d))).map(d => ({ ...d }));
126
+ });
127
+ if (!idle.length) return 0;
128
+ const sizeOf = () => new Map(ctl.devices().map(d => [d.udid, d.size || 0]));
129
+ const before = sizeOf();
130
+ const done = [];
131
+ for (const d of idle) {
132
+ if (!before.has(d.udid)) continue;
133
+ try { ctl.shutdown(d.udid); ctl.erase(d.udid); done.push(d.name); } catch {}
134
+ }
135
+ // Erased, a device has nobody's data: the next lease takes it without erasing it again.
136
+ withState(s => { for (const d of s.pool || []) if (done.includes(d.name) && !d.lease) Object.assign(d, { booted: false, lastWho: null }); });
137
+ const after = sizeOf();
138
+ return idle.reduce((a, d) => a + Math.max(0, (before.get(d.udid) || 0) - (after.get(d.udid) || 0)), 0);
139
+ }
140
+
96
141
  // Memory one more simulator needs, and how many fit now. Devices still
97
142
  // booting haven't taken their memory yet, so they're counted here.
98
143
  export function poolRoom(s, cfg, r, m = machine()) {
@@ -230,7 +275,7 @@ export function sims(o, args, cfg, ctl = simctl()) {
230
275
  + `(${gb(Math.max(room.free, 0))} free, ${gb(room.keep)} kept free, ${gb(room.per)} each)`);
231
276
  }
232
277
  for (const d of others) console.log(` ${d.name.padEnd(13)} ${d.udid.padEnd(36)} ${d.state.padEnd(9)} not made by this dibs (${HOME}); another dibs on this Mac may be using it, so prune leaves it alone`);
233
- if (!rows.length && !strays.length) return console.log('no pool devices yet. The first `dibs run sim-own -- <cmd>` creates one.');
278
+ if (!rows.length && !strays.length) return console.log('no pool devices yet. The first `dibs run sim-own -m "..." -- <cmd>` creates one.');
234
279
  for (const d of rows.sort((a, b) => a.name.localeCompare(b.name, undefined, { numeric: true }))) {
235
280
  const use = d.lease ? `in use by ${d.who} for ${dur(t - d.since)}` : d.lastUsed ? `idle ${dur(t - d.lastUsed)}, last used by ${d.lastWho}` : 'never used';
236
281
  console.log(` ${d.name.padEnd(13)} ${String(d.udid || '').padEnd(36)} ${d.state.padEnd(9)} ${use}${d.disk != null ? `, ${size(d.disk)} on disk` : ''}`);
package/src/spend.mjs ADDED
@@ -0,0 +1,375 @@
1
+ // Money as a shared resource. Agents spend real money (ad budgets, cloud bills, paid APIs,
2
+ // on-demand VMs, domains), and like the simulator it exists once: two agents each keeping under
3
+ // "the $210 ads budget" spend $420. dibs keeps one ledger of what agents say they spent or are
4
+ // about to spend, caps on it per day or month (overall, per category, per project) set by the
5
+ // person or an agent on the record, and a check before spending that brings the person a one-way
6
+ // door when a cap would be passed.
7
+ //
8
+ // dibs spend 3.00 --on apple-ads -m "keyword bids" spent (the project is the repo's, or --project)
9
+ // dibs spend hold 210 --on apple-ads -m "monthly budget" about to commit it: counts against caps until
10
+ // closed; payments --against it draw it down
11
+ // dibs spend check 50 --on apple-ads -m "why" exit 0 within every cap; over one, the person
12
+ // decides (exit OVER when they say no)
13
+ // dibs spend cap 210 --on apple-ads --per month a cap (off to lift it)
14
+ //
15
+ // The ledger is only what agents and dibs record: dibs reads no bills and calls no billing API.
16
+ // Amounts are whole cents. Its own file and lock, as questions keep theirs: nothing here decides
17
+ // who runs next, and the page and the phone's notifier read it without the lock.
18
+ import fs from 'node:fs';
19
+ import path from 'node:path';
20
+ import { HOME } from './config.mjs';
21
+ import { identity } from './proc.mjs';
22
+ import { actor, logChange } from './owner.mjs';
23
+ import { event } from './events.mjs';
24
+ import { projectKey } from './files.mjs';
25
+ import { underLock, commit } from './lock.mjs';
26
+ import { clock, die, now, say, fakeFull } from './util.mjs';
27
+ import { bold, dim, amber, red } from './style.mjs';
28
+ import { readJSON } from './durable.mjs';
29
+
30
+ const FILE = path.join(HOME, 'spend.json');
31
+ const LOCK = path.join(HOME, 'spend.lock');
32
+ // Writes take milliseconds: a live holder past this is stuck on something else, and the caller hears so.
33
+ const LOCK_WAIT = 15e3;
34
+ // Entries are kept this long: a cap needs only this month, but the person asks what ads cost in March.
35
+ const KEEP = 400 * 864e5;
36
+ // A cap this full is the person's business before it's passed: the phone hears (src/push.mjs),
37
+ // and the page, the recap and dibs spend flag it.
38
+ export const NEAR = 0.8;
39
+ // The person said no (or anything but yes) to spending past a cap. Its own code, so an agent
40
+ // never reads it as "nothing matched" (1) or as a wait that gave up (75).
41
+ export const OVER = 78;
42
+ // The newest entries dibs spend and the page list.
43
+ const RECENT = 12;
44
+ const PERS = { day: 'today', month: 'this month' };
45
+ const USE = 'dibs spend 3.00 --on apple-ads -m "keyword bids"';
46
+
47
+ function locked(fn) {
48
+ const r = underLock(LOCK, h => {
49
+ const s = load();
50
+ const before = JSON.stringify(s);
51
+ const t = now();
52
+ s.entries = s.entries.filter(e => t - e.at < KEEP);
53
+ const out = fn(s);
54
+ if (JSON.stringify(s) !== before) commit(h, FILE, JSON.stringify(s, null, 1), { fake: () => fakeFull('state') });
55
+ return out;
56
+ }, { wait: LOCK_WAIT, files: [FILE] });
57
+ if (!r) die(`${LOCK} is held by a dibs that's still running, and stayed held for ${LOCK_WAIT / 1000}s. Nothing was recorded: run the same command again.`, 75);
58
+ return r.out;
59
+ }
60
+
61
+ // Writes are renames, so reading without the lock always sees a whole file.
62
+ function load() {
63
+ let s = {};
64
+ try { s = readJSON(FILE); } catch (e) {
65
+ if (e.code !== 'ENOENT') say(`${FILE} was unreadable (${e.message}); reading it as an empty ledger.`);
66
+ }
67
+ s.seq ||= 0; s.entries ||= []; s.caps ||= [];
68
+ return s;
69
+ }
70
+
71
+ // "3", "3.5", "$1,200.00" -> cents, or null.
72
+ export function cents(x) {
73
+ const m = String(x ?? '').replace(/,/g, '').trim().match(/^\$?(\d{1,9})(?:\.(\d{1,2}))?$/);
74
+ return m ? Number(m[1]) * 100 + Number((m[2] || '').padEnd(2, '0')) : null;
75
+ }
76
+ export const money = c => `$${(c / 100).toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
77
+
78
+ // Where this period began, in local time: caps reset at midnight and on the 1st.
79
+ export function periodStart(per, t = now()) {
80
+ const d = new Date(t);
81
+ return per === 'day' ? new Date(d.getFullYear(), d.getMonth(), d.getDate()).getTime() : new Date(d.getFullYear(), d.getMonth(), 1).getTime();
82
+ }
83
+
84
+ const applies = (c, on, project) => (!c.on || c.on === on) && (!c.project || c.project === project);
85
+ export const capName = c => (c.on && c.project ? `${c.on} for ${c.project}` : c.on || (c.project ? `everything for ${c.project}` : 'all spend'));
86
+ const sameCap = (a, b) => a.per === b.per && (a.on || null) === (b.on || null) && (a.project || null) === (b.project || null);
87
+
88
+ // What an entry counts against caps now: a payment its amount; an open hold what's left of it
89
+ // after the payments made against it (those count themselves).
90
+ function counted(s, e, t) {
91
+ if (!e.hold) return e.amount;
92
+ if (e.closed || (e.until && t >= e.until)) return 0;
93
+ const drawn = s.entries.filter(x => x.against === e.id).reduce((k, x) => k + x.amount, 0);
94
+ return Math.max(0, e.amount - drawn);
95
+ }
96
+
97
+ // A cap as everyone sees it: spent and held in its period so far.
98
+ function capView(s, c, t) {
99
+ const from = periodStart(c.per, t);
100
+ const used = s.entries.filter(e => e.at >= from && e.at <= t && applies(c, e.on, e.project)).reduce((k, e) => k + counted(s, e, t), 0);
101
+ return { on: c.on || null, project: c.project || null, per: c.per, limit: c.limit, by: c.by, at: c.at, name: capName(c), since: from, used, pct: c.limit ? used / c.limit : 1 };
102
+ }
103
+
104
+ // Payments since a time, by project, agent and category; and what open holds still count.
105
+ function totals(s, since, t) {
106
+ const paid = s.entries.filter(e => !e.hold && e.at >= since && e.at <= t);
107
+ const by = key => {
108
+ const m = new Map();
109
+ for (const e of paid) m.set(e[key] || null, (m.get(e[key] || null) || 0) + e.amount);
110
+ return [...m].sort((a, b) => b[1] - a[1]).map(([name, amount]) => ({ name, amount }));
111
+ };
112
+ const held = s.entries.filter(e => e.hold && e.at >= since && e.at <= t).reduce((k, e) => k + counted(s, e, t), 0);
113
+ return { since, total: paid.reduce((k, e) => k + e.amount, 0), held, byProject: by('project'), byAgent: by('who'), byOn: by('on') };
114
+ }
115
+
116
+ const shownEntry = (s, e, t) => ({ id: e.id, at: e.at, amount: e.amount, on: e.on, project: e.project, who: e.who, note: e.note,
117
+ ...(e.hold && { hold: true, left: counted(s, e, t), until: e.until || null, closed: e.closed || null }), ...(e.against && { against: e.against }) });
118
+
119
+ // What the page, the phone and dibs spend --json read. Without the lock.
120
+ export function spendJson(t = now(), s = load()) {
121
+ return {
122
+ // Amounts are whole cents.
123
+ now: t, unit: 'cents', today: totals(s, periodStart('day', t), t), month: totals(s, periodStart('month', t), t),
124
+ caps: s.caps.map(c => capView(s, c, t)),
125
+ holds: s.entries.filter(e => e.hold && counted(s, e, t) > 0).map(e => shownEntry(s, e, t)),
126
+ recent: s.entries.slice(-RECENT).reverse().map(e => shownEntry(s, e, t)),
127
+ };
128
+ }
129
+
130
+ // Caps at NEAR or past, for the notifier and the recap.
131
+ export function capsNear(t = now()) {
132
+ return spendJson(t).caps.filter(c => c.pct >= NEAR);
133
+ }
134
+
135
+ // Payments between two times, for the recap: the total, by project and by agent.
136
+ export function spentBetween(since, t = now()) {
137
+ const s = load();
138
+ const r = totals(s, since, t);
139
+ return { total: r.total, byProject: r.byProject, byAgent: r.byAgent, near: s.caps.map(c => capView(s, c, t)).filter(c => c.pct >= NEAR) };
140
+ }
141
+
142
+ // The project a spend is for when --project doesn't say: the repo it's made from (the sender's,
143
+ // for a job from another machine), or none outside a repo.
144
+ function projectHere() {
145
+ const base = k => k.replace(/\/+$/, '').split(/[/:]/).pop().replace(/\.git$/, '').toLowerCase() || null;
146
+ if (process.env.DIBS_REPO) return base(process.env.DIBS_REPO);
147
+ try {
148
+ const k = projectKey(process.cwd());
149
+ if (/^[\w+.-]+:\/\/|@/.test(k) || fs.existsSync(path.join(k, '.git'))) return base(k);
150
+ } catch {}
151
+ return null;
152
+ }
153
+
154
+ const NAME = /^[a-z0-9][\w.:-]{0,39}$/;
155
+ const nameOf = (v, flag) => {
156
+ const x = String(v).trim().toLowerCase();
157
+ return NAME.test(x) ? x : die(`${flag} takes a short name (letters, digits, - _ . :), like ${flag === '--on' ? 'apple-ads' : 'poker'}; not "${v}"`);
158
+ };
159
+ const idOf = v => {
160
+ const m = String(v ?? '').match(/^s?(\d+)$/);
161
+ return m ? Number(m[1]) : die(`an entry is its id from dibs spend, like s4; not "${v}"`);
162
+ };
163
+ // 30d, 12h, 90m.
164
+ const span = (v, flag) => {
165
+ const m = String(v).match(/^(\d+(?:\.\d+)?)([mhd])$/);
166
+ return m ? parseFloat(m[1]) * { m: 6e4, h: 36e5, d: 864e5 }[m[2]] : die(`${flag} takes how long, like 30d, 12h or 90m; not "${v}"`);
167
+ };
168
+
169
+ function parse(args) {
170
+ const o = { words: [] };
171
+ for (let i = 0; i < args.length; i++) {
172
+ const a = args[i], next = () => args[++i] ?? die(`${a} needs a value`);
173
+ if (a === '--on') o.on = nameOf(next(), '--on');
174
+ else if (a === '--project') o.project = nameOf(next(), '--project');
175
+ else if (a === '-m' || a === '--msg') o.note = next().trim();
176
+ else if (a === '--per') { o.per = next(); if (!PERS[o.per]) die('--per is day or month'); }
177
+ else if (a === '--for') o.for = span(next(), '--for');
178
+ else if (a === '--since') o.since = span(next(), '--since');
179
+ else if (a === '--against') o.against = idOf(next());
180
+ else if (a === '--recommend') o.recommend = next().trim();
181
+ else if (a === '-p' || a === '--priority') o.prio = next();
182
+ else if (a === '--timeout') o.timeout = next();
183
+ else if (a === '--no-wait') o.noWait = true;
184
+ else if (a === '--as') o.as = next();
185
+ else if (a === '--json') o.json = true;
186
+ else if (a.startsWith('-') && a.length > 1 && cents(a) == null) die(`unknown flag ${a}. Every flag: dibs help all`);
187
+ else o.words.push(a);
188
+ }
189
+ return o;
190
+ }
191
+
192
+ function amountOf(o, what) {
193
+ if (o.words.length !== 1) die(`${what}: one amount, then flags. ${USE}`);
194
+ const c = cents(o.words[0]);
195
+ if (!c) die(`"${o.words[0]}" isn't an amount above 0. Amounts look like 3, 3.50 or 1,200.00. ${USE}`);
196
+ return c;
197
+ }
198
+
199
+ // dibs spend <amount> | hold <amount> | check <amount> | cap <limit|off> | close <id> | [list] [--json]
200
+ export async function spend(args) {
201
+ const [verb, ...rest] = args;
202
+ if (verb === 'check') return check(rest);
203
+ if (verb === 'cap') return capCmd(rest);
204
+ if (verb === 'hold') return add(rest, true);
205
+ if (verb === 'close') return closeHold(rest);
206
+ if (verb === 'list') return list(rest);
207
+ if (verb == null || (verb.startsWith('-') && cents(verb) == null)) return list(args);
208
+ return add(args, false);
209
+ }
210
+
211
+ const where = e => `${e.on}${e.project ? ` for ${e.project}` : ''}`;
212
+ const capLine = c => `${c.name} ${PERS[c.per]}: ${money(c.used)} of ${money(c.limit)} (${Math.round(c.pct * 100)}%)`;
213
+
214
+ function add(args, hold) {
215
+ const o = parse(args);
216
+ const amount = amountOf(o, hold ? 'dibs spend hold' : 'dibs spend');
217
+ if (!hold && o.for != null) die('--for is how long a hold lasts: dibs spend hold 210 --on apple-ads --for 30d');
218
+ if (hold && o.against != null) die('--against draws a payment from a hold: dibs spend 42 --against s3');
219
+ const id = identity(o);
220
+ const here = o.project || projectHere();
221
+ const t = now();
222
+ const r = locked(s => {
223
+ let from = null;
224
+ if (o.against != null) {
225
+ from = s.entries.find(e => e.id === o.against && e.hold);
226
+ if (!from) return { no: `no hold s${o.against}. The holds: dibs spend` };
227
+ }
228
+ const on = o.on || from?.on;
229
+ if (!on) return { no: `spent on what? --on <category>, like --on apple-ads. Nothing was recorded. ${USE}`, code: 2 };
230
+ const e = { id: ++s.seq, at: t, amount, on, project: from && !o.project ? from.project : here, who: id.who, ...(id.label && { label: id.label }),
231
+ note: o.note || '', ...(hold && { hold: true, ...(o.for != null && { until: t + o.for }) }), ...(from && { against: from.id }) };
232
+ s.entries.push(e);
233
+ return { e, caps: s.caps.filter(c => applies(c, e.on, e.project)).map(c => capView(s, c, t)) };
234
+ });
235
+ if (r.no) die(r.no, r.code || 1);
236
+ const { e, caps } = r;
237
+ event({ kind: 'spend', act: hold ? 'hold' : 'spent', entry: e.id, amount: e.amount, on: e.on, project: e.project, who: e.who, ...(e.against && { against: e.against }) });
238
+ console.log(`s${e.id}`);
239
+ say(`${hold ? 'holding' : 'recorded'} ${money(e.amount)} on ${where(e)}${hold ? `: it counts against caps until you close it (dibs spend close s${e.id})${e.until ? ` or ${clock(e.until)} on ${new Date(e.until).toLocaleDateString('en-CA')}` : ''}; record payments against it with --against s${e.id}` : ''}.`);
240
+ for (const c of caps) {
241
+ if (c.used > c.limit) say(red(`over the cap: ${capLine(c)}. Recorded anyway; before the next spend, dibs spend check <amount> --on ${e.on} asks the person.`));
242
+ else if (c.pct >= NEAR) say(amber(`near the cap: ${capLine(c)}.`));
243
+ }
244
+ }
245
+
246
+ function closeHold(args) {
247
+ const o = parse(args);
248
+ if (o.words.length !== 1) die('close which hold? dibs spend close s3 (the ids: dibs spend)');
249
+ const n = idOf(o.words[0]);
250
+ const by = actor().name;
251
+ const r = locked(s => {
252
+ const e = s.entries.find(x => x.id === n);
253
+ if (!e?.hold) return { no: `no hold s${n}. The holds: dibs spend` };
254
+ if (e.closed) return { no: `hold s${n} is already closed` };
255
+ const left = counted(s, e, now());
256
+ Object.assign(e, { closed: now(), closedBy: by });
257
+ return { e: { ...e }, left };
258
+ });
259
+ if (r.no) die(r.no, 1);
260
+ event({ kind: 'spend', act: 'close', entry: n, by });
261
+ console.log(`closed hold s${n} (${money(r.e.amount)} on ${where(r.e)}): the ${money(r.left)} left of it stops counting against caps.`);
262
+ }
263
+
264
+ // dibs spend cap <limit|off> --per day|month [--on <category>] [--project <name>]
265
+ function capCmd(args) {
266
+ const o = parse(args);
267
+ if (!o.words.length) return list(args);
268
+ if (o.words.length !== 1) die('dibs spend cap 210 --on apple-ads --per month (or off in place of the amount)');
269
+ if (!o.per) die('a cap is per day or per month: --per day, --per month');
270
+ const off = o.words[0] === 'off';
271
+ const limit = off ? null : cents(o.words[0]);
272
+ if (!off && !limit) die(`"${o.words[0]}" isn't an amount above 0. dibs spend cap 210 --on apple-ads --per month, or off`);
273
+ const want = { on: o.on || null, project: o.project || null, per: o.per };
274
+ const who = actor();
275
+ const r = locked(s => {
276
+ const old = s.caps.find(c => sameCap(c, want));
277
+ if (off && !old) return { no: `there's no ${o.per === 'day' ? 'daily' : 'monthly'} cap on ${capName(want)}. The caps: dibs spend` };
278
+ s.caps = s.caps.filter(c => !sameCap(c, want));
279
+ if (!off) s.caps.push({ ...want, limit, by: who.name, at: now() });
280
+ return { old: old ? old.limit : null, view: off ? null : capView(s, s.caps.at(-1), now()) };
281
+ });
282
+ if (r.no) die(r.no, 1);
283
+ logChange('spend cap', { cap: want, limit, from: r.old });
284
+ if (off) return console.log(`lifted the ${o.per === 'day' ? 'daily' : 'monthly'} cap on ${capName(want)} (it was ${money(r.old)}).`);
285
+ console.log(`cap set: ${capLine(r.view)}. Past it, dibs spend check asks the person; past ${Math.round(NEAR * 100)}%, their phone hears.`);
286
+ }
287
+
288
+ // dibs spend check <amount> --on <category> -m "why": exit 0 within every cap that covers it.
289
+ // Over one, a one-way door only the person may answer (an agent's dibs answer is turned away),
290
+ // waited for like dibs question --wait: yes is exit 0,
291
+ // anything else is printed and exits OVER; no answer in time is 75, as for any question.
292
+ async function check(args) {
293
+ const o = parse(args);
294
+ const amount = amountOf(o, 'dibs spend check');
295
+ const t = now();
296
+ const s = load();
297
+ // A payment out of a hold adds only what the hold doesn't already cover.
298
+ const from = o.against != null ? s.entries.find(e => e.id === o.against && e.hold) : null;
299
+ if (o.against != null && !from) die(`no hold s${o.against}. The holds: dibs spend`, 1);
300
+ o.on ||= from?.on;
301
+ if (!o.on) die(`spending on what? --on <category>, like --on apple-ads: dibs spend check ${o.words[0]} --on apple-ads -m "why"`);
302
+ const project = o.project || from?.project || projectHere();
303
+ const extra = from ? Math.max(0, amount - counted(s, from, t)) : amount;
304
+ const caps = s.caps.filter(c => applies(c, o.on, project)).map(c => capView(s, c, t));
305
+ const over = caps.filter(c => c.used + extra > c.limit);
306
+ const record = `dibs spend ${(amount / 100).toFixed(2)} --on ${o.on}${o.project ? ` --project ${o.project}` : ''}${from ? ` --against s${from.id}` : ''} -m "what"`;
307
+ if (!over.length) {
308
+ console.log('ok');
309
+ say(caps.length ? `within ${caps.length === 1 ? 'the cap' : `all ${caps.length} caps`}: ${caps.map(c => capLine({ ...c, used: c.used + extra, pct: (c.used + extra) / c.limit })).join('; ')}, with this. Go ahead, and record it as you commit it: ${record}`
310
+ : `no cap covers ${where({ on: o.on, project })}. Go ahead, and record it as you commit it: ${record}`);
311
+ return;
312
+ }
313
+ if (!o.note) die(`${money(amount)} on ${where({ on: o.on, project })} goes over ${over.map(capLine).join('; ')}, so the person decides. Say what it's for: -m "why". Nothing was asked.`);
314
+ const detail = over.map(c => `${c.name} ${PERS[c.per]} would be ${money(c.used + extra)}, cap ${money(c.limit)} (${money(c.used)} spent or held)`).join('; ');
315
+ const text = `Spend ${money(amount)} on ${where({ on: o.on, project })}? It goes over a spend cap.`;
316
+ const q = [text, '--options', 'yes,no', '--recommend', o.recommend || 'yes', '-m', `${o.note} (over: ${detail})`,
317
+ '--one-way', `money spent on ${o.on} can't be taken back`, ...(o.prio ? ['-p', o.prio] : []), ...(o.timeout ? ['--timeout', o.timeout] : []), ...(o.noWait ? [] : ['--wait'])];
318
+ const { question } = await import('./questions.mjs');
319
+ const { loadConfig } = await import('./config.mjs');
320
+ const answer = await question(q, loadConfig(), { print: false, personOnly: true });
321
+ if (o.noWait) die(`over the cap, so the person decides: asked them (dibs questions). Nothing is approved yet: run the same check again to wait for their answer.`, 75);
322
+ const yes = String(answer).trim().toLowerCase() === 'yes';
323
+ event({ kind: 'spend', act: yes ? 'approved' : 'refused', amount, on: o.on, project, who: identity(o).who, answer: String(answer).slice(0, 200) });
324
+ console.log(answer);
325
+ if (!yes) die(`not approved: don't spend it (exit ${OVER}). The answer is above; reply in your thread if it asks something.`, OVER);
326
+ say(`approved. Go ahead, and record it as you commit it: ${record}`);
327
+ }
328
+
329
+ // dibs spend [list] [--since 30d] [--json]
330
+ function list(args) {
331
+ const o = parse(args);
332
+ if (o.words.length) die(`dibs spend takes an amount first (${USE}), or check, hold, close, cap or list`);
333
+ const t = now();
334
+ const s = load();
335
+ const j = spendJson(t, s);
336
+ if (o.json) return console.log(JSON.stringify(o.since ? { ...j, since: totals(s, t - o.since, t) } : j, null, 1));
337
+ const sum = o.since ? totals(s, t - o.since, t) : j.month;
338
+ const out = [bold(`Spent ${o.since ? `since ${new Date(t - o.since).toLocaleDateString('en-CA')}` : 'this month'}: ${money(sum.total)}${o.since ? '' : `, ${money(j.today.total)} of it today`}${sum.held ? `; ${money(sum.held)} more held` : ''}.`)];
339
+ if (j.caps.length) {
340
+ out.push('', ' Caps');
341
+ for (const c of j.caps) out.push(` ${(c.pct >= 1 ? red : c.pct >= NEAR ? amber : x => x)(capLine(c))}${dim(` set by ${c.by}`)}`);
342
+ } else out.push('', dim(' No caps. Set one: dibs spend cap 210 --on apple-ads --per month'));
343
+ const row = (title, xs, none) => { if (xs.length) out.push('', ` ${title}`, ...xs.map(x => ` ${x.name ?? none} ${money(x.amount)}`)); };
344
+ row('By project', sum.byProject, '(no project)');
345
+ row('By agent', sum.byAgent, '?');
346
+ row('By category', sum.byOn, '?');
347
+ if (j.holds.length) {
348
+ out.push('', ' Open holds');
349
+ for (const e of j.holds) out.push(` s${e.id} ${e.who}: ${money(e.left)} left of ${money(e.amount)} on ${where(e)}${e.note ? `, ${e.note}` : ''}`);
350
+ }
351
+ if (j.recent.length) {
352
+ out.push('', ' Latest');
353
+ for (const e of j.recent) out.push(dim(` s${e.id} ${new Date(e.at).toLocaleDateString('en-CA')} ${clock(e.at)} ${e.who} ${e.hold ? 'held ' : ''}${money(e.amount)} on ${where(e)}${e.note ? `: ${e.note}` : ''}`));
354
+ }
355
+ out.push('', `Record: ${USE} Before spending: dibs spend check 50 --on apple-ads -m "why"`);
356
+ console.log(out.join('\n'));
357
+ }
358
+
359
+ // Spend dibs itself knows of, with no agent to record it: an on-demand VM's time (src/ondemand.mjs).
360
+ // Never throws or exits: a ledger that can't be written mustn't stop a VM from stopping.
361
+ export function recordFor(by, { amount, on, project = null, note = '' }) {
362
+ try {
363
+ const t = now();
364
+ const r = underLock(LOCK, h => {
365
+ const s = load();
366
+ const e = { id: ++s.seq, at: t, amount, on, project, who: by, note };
367
+ s.entries = s.entries.filter(x => t - x.at < KEEP).concat(e);
368
+ commit(h, FILE, JSON.stringify(s, null, 1), { fake: () => fakeFull('state') });
369
+ return e;
370
+ }, { wait: LOCK_WAIT, files: [FILE] });
371
+ if (!r) throw new Error(`${LOCK} stayed held for ${LOCK_WAIT / 1000}s`);
372
+ event({ kind: 'spend', act: 'spent', entry: r.out.id, amount, on, project, who: by });
373
+ return r.out;
374
+ } catch (err) { say(`couldn't record ${money(amount)} on ${on} in the spend ledger: ${err.message}`); return null; }
375
+ }