@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
@@ -0,0 +1,143 @@
1
+ // Files that survive a crash, a full disk or a power cut, and a broken one put right.
2
+ //
3
+ // On 2026-10-14 the state file was found unreadable, set aside as state.json.corrupt-*, and
4
+ // dibs started fresh: every lease and waiter it tracked was forgotten. The copy set aside
5
+ // parses fine. Two writers then shared one state.json.tmp and a live holder's lock could be
6
+ // taken after 30 s at high load, so one writer's half-written temp file was renamed into place
7
+ // while the other was still writing it, a reader caught it half done, and by the time it
8
+ // copied the file the write had finished. Per-process temporary files (src/lock.mjs commit) and
9
+ // locks never taken from a live owner closed that hole; this is what's left:
10
+ //
11
+ // - writeWhole: a temporary copy, flushed to disk (fsync), then renamed over the file, so after
12
+ // a power cut the file is the old one or the new one, never empty or half there. (macOS's fsync
13
+ // leaves the drive's own cache unflushed; the copy below covers what that misses.)
14
+ // - keepLast: before a locked write replaces a file, the version it replaces stays as
15
+ // <file>.bak (a hard link: no copy, no space), so there's always a last good copy.
16
+ // - heal: under the file's lock, a file that doesn't parse is set aside as <file>.corrupt-<ms>
17
+ // and the last good copy put back, or, with none, the file is moved aside so its reader starts
18
+ // empty. Either way an event says what came back and what was lost (src/alerts.mjs shows it).
19
+ //
20
+ // Node built-ins and src/util.mjs only (as src/lock.mjs): the guard hook loads src/lock.mjs, which loads this.
21
+ import fs from 'node:fs';
22
+ import os from 'node:os';
23
+ import path from 'node:path';
24
+ import { isMainThread, threadId } from 'node:worker_threads';
25
+ import { fakeFull } from './util.mjs';
26
+
27
+ const HOME = process.env.DIBS_HOME || path.join(os.homedir(), '.dibs');
28
+ // Ids a file hands out (seq) skip this far past the restored copy's, so an id given out in the
29
+ // change that was lost (a job that may still be running) is never given to another.
30
+ export const SEQ_SKIP = 100;
31
+
32
+ export const bakOf = file => `${file}.bak`;
33
+ const tmpOf = file => `${file}.${process.pid}${isMainThread ? '' : `.t${threadId}`}.tmp`;
34
+
35
+ // Writes text to a new file and flushes it to disk before returning, so the rename that follows
36
+ // never puts an empty file in place. The folder isn't flushed after the rename: that only decides
37
+ // whether a power cut leaves the new file or the old one, and either is whole. Flushing both cost
38
+ // 11 ms a write on a loaded Mac (2026-11-29), held under the state lock; the file alone, about 7.
39
+ export function writeSynced(file, text, mode) {
40
+ fs.writeFileSync(file, text, mode ? { mode } : undefined);
41
+ const fd = fs.openSync(file, 'r+');
42
+ try { fs.fsyncSync(fd); } finally { fs.closeSync(fd); }
43
+ }
44
+
45
+ // A whole file, for a writer without a lock: written aside, flushed, renamed into place. A write
46
+ // cut short (a full disk) leaves the old file and no temporary one.
47
+ export function writeWhole(file, text, { mode } = {}) {
48
+ const tmp = tmpOf(file);
49
+ try { writeSynced(tmp, text, mode); fs.renameSync(tmp, file); }
50
+ catch (e) { try { fs.rmSync(tmp, { force: true }); } catch {} throw e; }
51
+ }
52
+
53
+ // The version about to be replaced stays as <file>.bak. Best effort: no file yet, or a file
54
+ // system without hard links, just means no copy this time.
55
+ export function keepLast(file) {
56
+ const tmp = `${bakOf(file)}.${process.pid}${isMainThread ? '' : `.t${threadId}`}.tmp`;
57
+ try { fs.linkSync(file, tmp); fs.renameSync(tmp, bakOf(file)); }
58
+ catch { try { fs.rmSync(tmp, { force: true }); } catch {} }
59
+ }
60
+
61
+ // The parsed object, or undefined when the text isn't a whole JSON object. An empty file is
62
+ // broken too: it's what a power cut leaves of a file renamed into place before it reached the disk.
63
+ export function parsed(text) {
64
+ try { const v = JSON.parse(text); return v && typeof v === 'object' ? v : undefined; } catch { return undefined; }
65
+ }
66
+
67
+ // <file>.bak when it parses: { v, raw, at } (at: when that copy was written), else null.
68
+ export function lastGood(file) {
69
+ try {
70
+ const raw = fs.readFileSync(bakOf(file), 'utf8');
71
+ const v = parsed(raw);
72
+ return v ? { v, raw, at: fs.statSync(bakOf(file)).mtimeMs } : null;
73
+ } catch { return null; }
74
+ }
75
+
76
+ // A JSON file read without its lock: one that doesn't parse reads as its last good copy until the
77
+ // next holder of its lock puts that copy back (heal), so a list never shows empty in between. A
78
+ // missing file throws ENOENT and a broken one with no copy a SyntaxError, as JSON.parse(readFileSync) did.
79
+ export function readJSON(file) {
80
+ const raw = fs.readFileSync(file, 'utf8');
81
+ const v = parsed(raw) || lastGood(file)?.v;
82
+ if (v) return v;
83
+ JSON.parse(raw);
84
+ throw new SyntaxError(`${file} isn't a JSON object`);
85
+ }
86
+
87
+ // What a restored copy holds, in words a person can check: "3 leases, 2 queue".
88
+ export function contents(v) {
89
+ return Object.entries(v || {}).filter(([, x]) => Array.isArray(x)).map(([k, x]) => `${x.length} ${k}`).join(', ');
90
+ }
91
+
92
+ // Puts a broken file right, under its lock. Returns what it did ({ file, saved, from, kept }), or
93
+ // null when the file is missing or whole. A full disk is thrown (the caller says exit 74 as for
94
+ // any write); anything else leaves the file as it was, for dibs doctor to report.
95
+ export function heal(file, { by } = {}) {
96
+ let raw;
97
+ try { raw = fs.readFileSync(file, 'utf8'); } catch { return null; }
98
+ if (parsed(raw)) return null;
99
+ const saved = `${file}.corrupt-${Date.now()}`;
100
+ const good = lastGood(file);
101
+ try {
102
+ if (good) {
103
+ fs.linkSync(file, saved); // the broken bytes, kept as they were for whoever looks
104
+ if (typeof good.v.seq === 'number') good.v.seq += SEQ_SKIP;
105
+ try { fakeFull('state'); writeWhole(file, JSON.stringify(good.v, null, 1)); }
106
+ catch (e) { fs.rmSync(saved, { force: true }); throw e; } // tried again by the next holder: one copy, not one a try
107
+ } else fs.renameSync(file, saved);
108
+ } catch (e) {
109
+ if (e.code === 'ENOSPC' || e.code === 'EDQUOT') throw e;
110
+ return null;
111
+ }
112
+ const done = { file, saved, size: Buffer.byteLength(raw), from: good?.at ?? null, kept: good ? contents(good.v) : '' };
113
+ note({ kind: 'recovered', ...done, ...(by && { by }) });
114
+ if (!by) process.stderr.write(`dibs: ${path.basename(file)} was unreadable (cut short or garbled). ${good
115
+ ? `Put back its copy from ${new Date(good.at).toLocaleString()}; changes after that are lost.` : 'With no earlier copy, it starts empty.'}`
116
+ + ` The broken file is kept at ${saved}; dibs alerts has the details.\n`);
117
+ return done;
118
+ }
119
+
120
+ // One line in the event log (src/events.mjs's file, written the same way), so the alerts and
121
+ // dibs history see it. No secrets here: paths, sizes, times and counts.
122
+ export function note(e) {
123
+ try { fs.appendFileSync(path.join(HOME, 'events.jsonl'), JSON.stringify({ at: Date.now(), ...e }) + '\n'); } catch {}
124
+ }
125
+
126
+ // The lines of a .jsonl file that parse. A line cut short (a crash or a full disk mid-append) is
127
+ // skipped, and when the next append ran onto the end of it, the whole line after it is kept: it
128
+ // starts with the same first key as the broken one (every line of a log does), which an object
129
+ // nested inside the broken one doesn't.
130
+ export function jsonLines(text) {
131
+ const out = [];
132
+ for (const l of text.split('\n')) {
133
+ if (!l.trim()) continue;
134
+ const v = parsed(l);
135
+ if (v) { out.push(v); continue; }
136
+ const head = l.match(/^\{"[^"]*":/)?.[0];
137
+ for (let i = head ? l.indexOf(head, 1) : -1; i > 0; i = l.indexOf(head, i + 1)) {
138
+ const w = parsed(l.slice(i));
139
+ if (w) { out.push(w); break; }
140
+ }
141
+ }
142
+ return out;
143
+ }
package/src/envs.mjs ADDED
@@ -0,0 +1,372 @@
1
+ // Environments and accounts: env:staging, env:prod, account:asc, a test database, a
2
+ // logged-in browser profile. Each exists once per project, so it's leased like any
3
+ // resource (one holder per project at a time, given back when the command ends:
4
+ // ENV_RES in src/config.mjs), and each remembers what's on it. Two agents both
5
+ // deploying to staging used to find out what the other put there only when
6
+ // something broke.
7
+ //
8
+ // Every lease end on one is written down: dibs run's command and exit code, a hold's
9
+ // length, or the holder's own words (dibs env staging left "deployed web@1a2b3c"),
10
+ // with who and when. The end is seen inside withState (src/state.mjs), however the
11
+ // lease ended, crash and expiry included, and written here once the state lock is
12
+ // free. The next agent to lease it is told what's there before its command starts.
13
+ //
14
+ // A project names its environments in .dibs.json, and the machine's config.json names
15
+ // ones every project has:
16
+ // "envs": { "staging": { "about": "https://staging.example.com" },
17
+ // "prod": { "oneWay": "deploys reach paying users" }, "account:asc": {} }
18
+ // A name without a colon is env:<name>. oneWay: leasing it needs the person's yes
19
+ // (dibs question --one-way), each time, unless a standing rule covers it (ruleAnswer).
20
+ //
21
+ // Its own file and lock, never state.json's: nothing here decides who runs next.
22
+ import fs from 'node:fs';
23
+ import path from 'node:path';
24
+ import { execFileSync } from 'node:child_process';
25
+ import { HOME, paths, isEnv } from './config.mjs';
26
+ import { underLock, commit } from './lock.mjs';
27
+ import { rulesAbove } from './trust.mjs';
28
+ import { projectKey } from './files.mjs';
29
+ import { identity, isMine, tag } from './proc.mjs';
30
+ import { bold, dim, amber, wrap } from './style.mjs';
31
+ import { clock, die, dur, now, say, fakeFull } from './util.mjs';
32
+ import { readJSON } from './durable.mjs';
33
+
34
+ const FILE = path.join(HOME, 'envs.json');
35
+ const LOCK = path.join(HOME, 'envs.lock');
36
+ // Writes take milliseconds: a live holder past this is stuck on something else.
37
+ const LOCK_WAIT = 15e3;
38
+ // What each environment keeps: enough to see the last few days of a busy staging.
39
+ const KEEP = 50;
40
+ const SHOWN = 10;
41
+ // A note left after the lease ended fills in that lease's entry, when it's the same
42
+ // agent's and this recent: "dibs run env:staging -- ./deploy.sh" then "dibs env staging left ...".
43
+ const AMEND_FOR = 30 * 6e4;
44
+ // A note left during a lease waits for the lease's end. One whose lease ended
45
+ // without this file hearing of it (a disk that was full then) is dropped after this.
46
+ const PENDING_FOR = 24 * 36e5;
47
+ const GIT_WAIT = 2000;
48
+ // The person said no: refused, nothing ran (DIBS_CODES in src/commands.mjs).
49
+ const REFUSED = 78;
50
+
51
+ export { isEnv };
52
+ // staging -> env:staging; env:staging and account:asc stay as they are.
53
+ export const envName = n => (String(n).includes(':') ? String(n) : `env:${n}`);
54
+ export const projectOf = (cwd = process.cwd()) => process.env.DIBS_REPO || projectKey(cwd);
55
+ // A project's key is its origin URL or its folder: the last part of either names it.
56
+ // An origin URL can carry a token (https://user:token@host/...): never shown.
57
+ const shownRepo = repo => String(repo || '').replace(/\/\/[^/@]*@/, '//');
58
+ export const projectName = repo => String(repo || '').replace(/\.git$/, '').split(/[/:\\]/).filter(Boolean).pop() || String(repo || '');
59
+
60
+ function load() {
61
+ let s = {};
62
+ try { s = readJSON(FILE); } catch (e) {
63
+ if (e.code !== 'ENOENT') say(`${FILE} was unreadable (${e.message}); starting with no environment history.`);
64
+ }
65
+ s.envs ||= [];
66
+ return s;
67
+ }
68
+
69
+ // null when the lock stayed held past LOCK_WAIT.
70
+ const tryLocked = fn => underLock(LOCK, h => {
71
+ const s = load();
72
+ const before = JSON.stringify(s);
73
+ const out = fn(s);
74
+ if (JSON.stringify(s) !== before) commit(h, FILE, JSON.stringify(s, null, 1), { fake: () => fakeFull('state') });
75
+ return out;
76
+ }, { wait: LOCK_WAIT, files: [FILE] });
77
+ function locked(fn) {
78
+ const r = tryLocked(fn);
79
+ if (!r) die(`${LOCK} is held by a dibs that's still running, and stayed held for ${LOCK_WAIT / 1000}s. Nothing was changed: run the same command again.`, 75);
80
+ return r.out;
81
+ }
82
+
83
+ const find = (s, res, repo) => s.envs.find(e => e.res === res && e.repo === repo);
84
+ const findOrMake = (s, res, repo) => find(s, res, repo) || (s.envs.push({ res, repo, log: [], pending: {} }), s.envs[s.envs.length - 1]);
85
+
86
+ // What config.json and the project's .dibs.json files say about its environments,
87
+ // nearest file last so it wins. Read raw: this also runs after the state lock, where
88
+ // dying on a bad file would help nobody. A file that can't be read says nothing.
89
+ export function declared(cwd = process.cwd()) {
90
+ const out = {};
91
+ const add = envs => {
92
+ if (!envs || typeof envs !== 'object' || Array.isArray(envs)) return;
93
+ for (const [k, v] of Object.entries(envs)) {
94
+ const res = envName(k);
95
+ if (!isEnv(res)) continue;
96
+ const c = v && typeof v === 'object' ? v : {};
97
+ out[res] = { ...out[res], ...(typeof c.about === 'string' && { about: c.about }),
98
+ ...(c.oneWay != null && { oneWay: c.oneWay === false ? null : typeof c.oneWay === 'string' && c.oneWay.trim() ? c.oneWay.trim() : true }) };
99
+ }
100
+ };
101
+ try { add(JSON.parse(fs.readFileSync(paths.config, 'utf8')).envs); } catch {}
102
+ for (const f of rulesAbove(cwd).reverse()) try { add(JSON.parse(fs.readFileSync(f, 'utf8')).envs); } catch {}
103
+ return out;
104
+ }
105
+
106
+ // The commit a lease starts from, when its folder is in git: "main@1a2b3c4".
107
+ export function gitHead(cwd) {
108
+ try {
109
+ // One git call: the short sha, then the refs at HEAD ("HEAD -> main, origin/main"; just "HEAD" when detached).
110
+ const [sha, refs = ''] = execFileSync('git', ['log', '-1', '--format=%h%n%D'], { cwd, encoding: 'utf8', timeout: GIT_WAIT, stdio: ['ignore', 'pipe', 'ignore'] }).trim().split('\n');
111
+ const branch = refs.match(/HEAD -> ([^,]+)/)?.[1];
112
+ return sha ? (branch ? `${branch}@${sha}` : sha) : null;
113
+ } catch { return null; }
114
+ }
115
+
116
+ // ---- Lease ends, seen in withState ----------------------------------------
117
+
118
+ let ended = [];
119
+
120
+ // Called by withState with the leases a change removed. Copies what the record needs;
121
+ // written by recordEnds once the state lock is let go.
122
+ export function noteEnds(gone) {
123
+ for (const l of gone) {
124
+ const res = l.res.filter(isEnv);
125
+ if (!res.length) continue;
126
+ ended.push({ res, repo: l.repo || l.cwd || null, at: now(), lease: l.id, kind: l.kind, start: l.start, who: l.who, agent: l.agent || null, label: l.label || '',
127
+ cmd: l.cmd || '', purpose: l.purpose || '', code: l.code ?? null, head: l.head || null, cwd: l.cwd || null,
128
+ how: l.requeue ? 'requeued' : l.kind === 'run' ? (l.code == null ? 'lost' : 'exit') : l.expires && l.expires <= now() ? 'expired' : 'released' });
129
+ }
130
+ }
131
+
132
+ // After the state lock: write down every end noteEnds saw. A change that wasn't written ended nothing.
133
+ export function recordEnds(written) {
134
+ const xs = ended.splice(0);
135
+ if (!written || !xs.length) return;
136
+ const settings = new Map(xs.map(x => [x.cwd, x.cwd ? declared(x.cwd) : {}]));
137
+ // Never dies: this runs as a job ends, whose exit code must come back whatever happens here.
138
+ try {
139
+ const r = tryLocked(s => {
140
+ for (const x of xs) for (const res of x.res) {
141
+ if (!x.repo) continue;
142
+ const e = findOrMake(s, res, x.repo);
143
+ const conf = settings.get(x.cwd)?.[res];
144
+ if (conf) Object.assign(e, { about: conf.about ?? null, oneWay: conf.oneWay ?? null });
145
+ const note = e.pending?.[x.lease];
146
+ if (note) delete e.pending[x.lease];
147
+ // A hold whose runs were each written down already says nothing new, unless its holder left a note.
148
+ if (x.kind === 'hold' && !note && e.log.some(y => y.kind === 'run' && y.at >= x.start && y.who === x.who)) continue;
149
+ const { res: _r, repo: _p, cwd: _c, ...entry } = x;
150
+ e.log.push({ ...entry, what: note?.what ?? null });
151
+ e.log = e.log.slice(-KEEP);
152
+ }
153
+ });
154
+ if (!r) throw new Error(`${LOCK} stayed held for ${LOCK_WAIT / 1000}s`);
155
+ } catch (e) {
156
+ say(`couldn't write down what was left on ${xs.flatMap(x => x.res).join(', ')} (${e.message}). Leave a note by hand: dibs env <name> left "..."`);
157
+ }
158
+ }
159
+
160
+ // ---- Reading --------------------------------------------------------------
161
+
162
+ // What an entry says was left there, in a few words.
163
+ export function whatLeft(x) {
164
+ if (x.what) return x.what;
165
+ if (x.kind === 'note') return '';
166
+ if (x.kind === 'hold') return `held it ${dur(x.at - x.start)}, no note`;
167
+ const cmd = x.cmd.length > 60 ? `${x.cmd.slice(0, 57)}...` : x.cmd;
168
+ if (x.how === 'lost') return `ran ${cmd}; dibs lost it before it exited, so it may have stopped half way`;
169
+ if (x.how === 'requeued') return `ran ${cmd}; stopped by dibs half way and put back in line`;
170
+ return `ran ${cmd}, exit ${x.code}`;
171
+ }
172
+ const byWhom = x => tag({ who: x.who, label: x.label });
173
+ // One line about an entry: what, who, how long ago, and the facts beside it.
174
+ export function entryLine(x, t = now()) {
175
+ const facts = [x.what && x.kind === 'run' ? `${x.cmd ? `ran ${x.cmd.slice(0, 40)}, ` : ''}exit ${x.code ?? '?'}` : '', x.head ? `from ${x.head}` : ''].filter(Boolean);
176
+ return `${whatLeft(x) ? `"${whatLeft(x)}"` : '(no note)'} by ${byWhom(x)}, ${dur(Math.max(0, t - x.at))} ago${facts.length ? ` (${facts.join(', ')})` : ''}`;
177
+ }
178
+
179
+ // Leases on res in this project now, from the state as it is (read without the lock).
180
+ function holders(st, res, repo) {
181
+ return (st.leases || []).filter(l => l.res.includes(res) && (l.repo || l.cwd) === repo && !(l.covered || []).includes(res));
182
+ }
183
+
184
+ // Every environment of a project (or of every project, with repo null): the declared
185
+ // ones, the ones with a history, and the ones leased now.
186
+ export function envsJson({ repo = null, cwd = process.cwd(), st = null, t = now() } = {}) {
187
+ const s = load();
188
+ const leases = (st?.leases || []).filter(l => l.res.some(isEnv));
189
+ const keys = new Map();
190
+ const add = (res, r) => { if (r) keys.set(`${res}\n${r}`, { res, repo: r }); };
191
+ for (const e of s.envs) if (!repo || e.repo === repo) add(e.res, e.repo);
192
+ for (const l of leases) for (const res of l.res.filter(isEnv)) if (!repo || (l.repo || l.cwd) === repo) add(res, l.repo || l.cwd);
193
+ const here = repo ? declared(cwd) : {};
194
+ for (const res of Object.keys(here)) add(res, repo);
195
+ return [...keys.values()].map(({ res, repo: r }) => {
196
+ const e = find(s, res, r) || { log: [] };
197
+ const conf = r === repo ? here[res] : null;
198
+ const using = st ? holders(st, res, r).map(l => ({ id: l.id, who: l.who, label: l.label || '', kind: l.kind, since: l.start, purpose: l.purpose || '', cmd: l.cmd || '' })) : [];
199
+ const last = e.log.at(-1) || null;
200
+ return { res, name: res.replace(/^env:/, ''), repo: shownRepo(r), project: projectName(r), about: conf?.about ?? e.about ?? null, oneWay: conf ? conf.oneWay ?? null : e.oneWay ?? null,
201
+ using, last: last && { ...last, left: whatLeft(last) }, log: e.log.slice(-SHOWN).reverse().map(x => ({ ...x, left: whatLeft(x) })), at: t };
202
+ }).sort((a, b) => a.project.localeCompare(b.project) || a.res.localeCompare(b.res));
203
+ }
204
+
205
+ // What the next holder hears before its command starts: one or two lines per environment.
206
+ export function briefing(lease, t = now()) {
207
+ const repo = lease.repo || lease.cwd;
208
+ const res = lease.res.filter(isEnv);
209
+ if (!res.length || !repo) return [];
210
+ const s = load();
211
+ return res.map(r => {
212
+ const last = find(s, r, repo)?.log.at(-1);
213
+ const n = r.replace(/^env:/, '');
214
+ return `${r}${last ? ` has ${entryLine(last, t)}.` : ': nothing written down about it yet.'} When you're done, say what you left there: dibs env ${n} left "..."`;
215
+ });
216
+ }
217
+
218
+ // ---- dibs env -------------------------------------------------------------
219
+
220
+ // dibs env [<name> [left "what"]] [--all] [--json]
221
+ export async function env(args) {
222
+ const json = args.includes('--json'), all = args.includes('--all');
223
+ const words = args.filter(a => a !== '--json' && a !== '--all');
224
+ const bad = words.find(a => a.startsWith('-'));
225
+ if (bad) die(`unknown flag ${bad}. dibs env [<name>] [--all] [--json], or dibs env <name> left "what's there now"`);
226
+ if (words[1] === 'left') return left(envName(words[0]), words.slice(2).join(' ').trim());
227
+ if (words.length > 1) die(`dibs env ${words[0]} shows it; to say what you left there: dibs env ${words[0]} left "deployed web@1a2b3c"`);
228
+ const { peek } = await import('./state.mjs');
229
+ const repo = all ? null : projectOf();
230
+ const list = envsJson({ repo, st: peek() });
231
+ if (words[0]) {
232
+ const res = envName(words[0]);
233
+ if (!isEnv(res)) die(`${words[0]} isn't an environment name: letters, digits, dots and dashes, like staging, env:prod or account:asc`);
234
+ const mine = list.filter(e => e.res === res);
235
+ if (json) return console.log(JSON.stringify({ envs: mine }, null, 1));
236
+ if (!mine.length) die(`${res} has no history ${all ? 'in any project' : `in ${projectName(repo)}`} and isn't in its .dibs.json. Lease it to start one: dibs run ${res} -- <command>`, 1);
237
+ return console.log(mine.map(e => detail(e)).join('\n\n'));
238
+ }
239
+ if (json) return console.log(JSON.stringify({ envs: list }, null, 1));
240
+ if (!list.length) return console.log(`No environments ${all ? 'anywhere yet' : `in ${projectName(repo)} yet`}. Name them in .dibs.json, {"envs": {"staging": {}, "prod": {"oneWay": "deploys reach users"}}}, and lease one: dibs run env:staging -- ./deploy.sh`);
241
+ const out = [];
242
+ let project = null;
243
+ for (const e of list) {
244
+ if (e.project !== project) { project = e.project; out.push(bold(all ? `${project} (${e.repo})` : project)); }
245
+ out.push(` ${e.res.padEnd(16)} ${summary(e)}`);
246
+ }
247
+ out.push('', dim('History of one: dibs env <name>. Say what you left there: dibs env <name> left "..."'));
248
+ console.log(out.join('\n'));
249
+ }
250
+
251
+ function usingLine(e, t) {
252
+ return e.using.map(l => `${l.kind === 'hold' ? 'held' : 'in use'} by ${tag(l)} for ${dur(t - l.since)}${l.purpose ? ` ("${l.purpose}")` : l.cmd ? `: ${l.cmd.slice(0, 50)}` : ''}`).join('; ');
253
+ }
254
+ function summary(e, t = now()) {
255
+ const parts = [e.using.length ? amber(usingLine(e, t)) : 'free', e.last ? `last: ${entryLine(e.last, t)}` : 'nothing written down yet'];
256
+ if (e.oneWay) parts.push(amber("needs the person's yes"));
257
+ return parts.join('. ');
258
+ }
259
+ function detail(e, t = now()) {
260
+ const out = [bold(`${e.res} in ${e.project}`) + (e.about ? ` ${e.about}` : '')];
261
+ if (e.oneWay) out.push(amber(wrap(` Needs the person's yes before each lease: ${e.oneWay === true ? 'it is marked one-way' : e.oneWay}.`, ' ')));
262
+ out.push(e.using.length ? amber(` Now: ${usingLine(e, t)}`) : ' Now: free');
263
+ if (!e.log.length) out.push(' Nothing written down yet.');
264
+ else {
265
+ out.push(' What was left there, newest first:');
266
+ for (const x of e.log) out.push(wrap(` ${clock(x.at)} ${entryLine(x, t)}`, ' '));
267
+ }
268
+ out.push('', dim(` Say what you left there: dibs env ${e.name} left "..."`));
269
+ return out.join('\n');
270
+ }
271
+
272
+ // dibs env <name> left "what": the caller's own words on what's there now. During the
273
+ // caller's lease they wait for its end; just after it, they fill in its entry; otherwise
274
+ // they're a note of their own (the person resetting staging by hand, say).
275
+ function left(res, what) {
276
+ if (!isEnv(res)) die(`${res} isn't an environment name: letters, digits, dots and dashes, like staging, env:prod or account:asc`);
277
+ if (!what) die(`left what? dibs env ${res.replace(/^env:/, '')} left "deployed web@1a2b3c"`);
278
+ const repo = projectOf();
279
+ const id = identity();
280
+ // Inside dibs run, DIBS_LEASE names the run's own lease; else the caller's own lease on it.
281
+ let st = {};
282
+ try { st = JSON.parse(fs.readFileSync(paths.state, 'utf8')); } catch {}
283
+ const leases = holders(st, res, repo).concat((st.leases || []).filter(l => l.res.includes(res) && (l.repo || l.cwd) === repo && (l.covered || []).includes(res)));
284
+ const lease = leases.find(l => String(l.id) === process.env.DIBS_LEASE) || leases.find(l => isMine(l, id));
285
+ const t = now();
286
+ const r = locked(s => {
287
+ const e = findOrMake(s, res, repo);
288
+ for (const [k, p] of Object.entries(e.pending || {})) if (t - p.at > PENDING_FOR) delete e.pending[k];
289
+ if (lease) { (e.pending ||= {})[lease.id] = { what, at: t }; return 'pending'; }
290
+ const last = e.log.at(-1);
291
+ if (last && last.kind !== 'note' && !last.what && last.who === id.who && t - last.at < AMEND_FOR) { last.what = what; return 'amended'; }
292
+ e.log.push({ kind: 'note', at: t, start: t, who: id.who, agent: id.agent, label: id.label || '', what });
293
+ e.log = e.log.slice(-KEEP);
294
+ return 'noted';
295
+ });
296
+ const n = res.replace(/^env:/, '');
297
+ if (r === 'pending') console.log(`Noted: ${res} will read "${what}" once your #${lease.id} ends. Leave another note before then to change it.`);
298
+ else if (r === 'amended') console.log(`Noted: your last turn on ${res} now reads "${what}". The next agent to lease it hears so first.`);
299
+ else console.log(`Noted on ${res}: "${what}". The next agent to lease it hears so first. Its history: dibs env ${n}`);
300
+ }
301
+
302
+ // ---- The door: leasing a one-way environment needs the person's yes -------
303
+
304
+ // Standing rules (the rules branch, src/rules.mjs) hook in here: a rule the person set
305
+ // for this kind of question ("env-prod") answers it, and nobody is asked. Returns the
306
+ // answer, or null to ask the person. Nothing answers until rules land.
307
+ export const ruleAnswer = (kind, ask) => null;
308
+
309
+ // Before a run or hold joins the line: every one-way environment it leases needs a yes.
310
+ // A lease covered by the caller's own hold on it already had one. Dies when the answer
311
+ // isn't yes (exit 78), or none came from the person (exit 75, as an unanswered question's wait does).
312
+ export async function door(o, cfg) {
313
+ const res = [...new Set(o.res)].filter(isEnv);
314
+ if (!res.length) return;
315
+ const conf = declared();
316
+ // A project that names its environments has only those: env:stagin would be a lease of its own, beside the real one.
317
+ const known = Object.keys(conf);
318
+ const stray = known.length && res.find(r => !conf[r]);
319
+ if (stray) die(`${stray} isn't one of this project's environments (${known.sort().join(', ')}, named in .dibs.json or config.json "envs"). Did you mean ${closest(stray, known)}? Nothing ran.`);
320
+ const doors = res.filter(r => conf[r]?.oneWay);
321
+ if (!doors.length) return;
322
+ const repo = projectOf();
323
+ const id = identity(o);
324
+ let st = {};
325
+ try { st = JSON.parse(fs.readFileSync(paths.state, 'utf8')); } catch {}
326
+ const held = r => (st.leases || []).some(l => l.kind === 'hold' && l.res.includes(r) && (l.repo || l.cwd) === repo && isMine(l, id));
327
+ for (const r of doors.filter(r => !held(r))) {
328
+ if (!o.purpose) die(`${r} needs the person's yes before anyone uses it, and they decide on your reason: add -m "why", like -m "ship the fixed checkout". Nothing ran.`);
329
+ const n = r.replace(/^env:/, '');
330
+ const what = o.cmd?.length ? `run ${o.cmd.join(' ').slice(0, 120)}` : `hold it${o.for ? ` for ${dur(o.for)}` : ''}`;
331
+ const text = `May ${id.agent || id.who} use ${r} of ${projectName(repo)} now, to ${what}?`;
332
+ const kind = r.replace(':', '-');
333
+ const ruled = ruleAnswer(kind, { res: r, repo, text, purpose: o.purpose, who: id.who });
334
+ const cantUndo = conf[r].oneWay === true ? `what's done on ${r} can't be taken back` : `${conf[r].oneWay} (${r} is marked one-way)`;
335
+ const { answer, by } = ruled != null ? { answer: ruled, by: 'a standing rule' } : await ask(text, o, cantUndo, cfg);
336
+ // Another agent's answer isn't the person's yes: on a one-way door it counts for nothing.
337
+ if (by && ruled == null) die(`question about ${r} was answered by ${by} not the person, and ${r} needs the person's own yes. Nothing ran and nothing joined the line (exit 75). Run the same command again to ask the person.`, 75);
338
+ const who = by || 'the person';
339
+ if (String(answer).trim().toLowerCase() !== 'yes')
340
+ die(`${who} answered "${answer}" to using ${r}, so nothing ran and nothing joined the line. Don't run it again unless they say otherwise (exit ${REFUSED}: refused, nothing ran); see what's there: dibs env ${n}`, REFUSED);
341
+ say(`${who} said yes to ${r}; joining the line for it.`);
342
+ }
343
+ }
344
+
345
+ // The declared name fewest edits away from r.
346
+ function closest(r, names) {
347
+ const edits = (a, b) => {
348
+ let row = Array.from({ length: b.length + 1 }, (_, j) => j);
349
+ for (let i = 1; i <= a.length; i++) {
350
+ const next = [i];
351
+ for (let j = 1; j <= b.length; j++) next[j] = Math.min(row[j] + 1, next[j - 1] + 1, row[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
352
+ row = next;
353
+ }
354
+ return row[b.length];
355
+ };
356
+ return names.reduce((best, n) => (edits(r, n) < edits(r, best) ? n : best));
357
+ }
358
+
359
+ // dibs question --one-way --wait, with its answer kept off stdout, which is the command's.
360
+ async function ask(text, o, cantUndo, cfg) {
361
+ const { question, asked } = await import('./questions.mjs');
362
+ const args = [text, '--options', 'yes,no', '--recommend', 'yes', '-m', o.purpose, '--one-way', cantUndo, '--wait',
363
+ ...(o.as ? ['--as', o.as] : []), ...(o.prio ? ['-p', o.prio] : []), ...(o.maxWait != null && o.maxWait !== Infinity ? ['--timeout', `${Math.max(1, Math.round(o.maxWait / 1000))}s`] : [])];
364
+ const log = console.log;
365
+ let answer = null;
366
+ console.log = x => { answer = String(x); };
367
+ // Only the person's own yes, asked each time: no past decision or standing rule stands in for it.
368
+ try { await question(args, cfg, { personOnly: true }); } finally { console.log = log; }
369
+ // An agent may answer for the person (on the record, as its name): say so, never "the person".
370
+ const q = asked().filter(x => x.text === text && x.answer === answer).at(-1);
371
+ return { answer, by: q?.answeredBy ? `${q.answeredBy}, an agent,` : null };
372
+ }
package/src/events.mjs CHANGED
@@ -9,6 +9,7 @@ import fs from 'node:fs';
9
9
  import path from 'node:path';
10
10
  import { HOME, paths } from './config.mjs';
11
11
  import { now } from './util.mjs';
12
+ import { redact } from './prints.mjs';
12
13
 
13
14
  export const EVENTS = path.join(HOME, 'events.jsonl');
14
15
  export const OLDER = path.join(HOME, 'events.1.jsonl');
@@ -28,7 +29,8 @@ function complain(e) {
28
29
  // Append one event: { kind, res, who, ... }. `at` is set when missing.
29
30
  // Overrides go through here too: event({ kind: 'override', res, who, ... }).
30
31
  export function event(e) {
31
- try { fs.appendFileSync(EVENTS, JSON.stringify({ at: now(), ...e }) + '\n'); } catch (err) { complain(err); }
32
+ // A stored secret's value never reaches the log, whatever field it turned up in (src/prints.mjs).
33
+ try { fs.appendFileSync(EVENTS, redact(JSON.stringify({ at: now(), ...e })) + '\n'); } catch (err) { complain(err); }
32
34
  }
33
35
 
34
36
  // Move the current file aside once it's past half of either limit. Called
@@ -93,7 +95,10 @@ export function logChanges(before, paused, s) {
93
95
  if (after.has(l.id)) continue;
94
96
  const pausedMs = (l.pausedMs || 0) + (paused.get(l.id) ? t - paused.get(l.id) : 0);
95
97
  // What it was, so a failure can be named and a later success of the same command can close it (src/alerts.mjs).
96
- out.push({ at: t, kind: 'end', ...fields(l), code: l.code ?? null, ms: t - l.start, paused: pausedMs,
98
+ // Whose session it ran in and how long it waited, so the person's screens can say what it meant (src/picture.mjs),
99
+ // and which files a session that ended held (src/carry.mjs).
100
+ out.push({ at: t, kind: 'end', ...fields(l), code: l.code ?? null, ms: t - l.start, paused: pausedMs, ...(l.waited != null && { waited: l.waited }),
101
+ ...(l.sessionId && { session: l.sessionId }), ...(l.agentId && l.agentId !== 'main' && { agentId: l.agentId }), ...(l.codex && { codex: l.codex }),
97
102
  ...(l.kind === 'run' && { key: l.key, cmd: String(l.cmd || '').slice(0, 120), ...(l.purpose && { purpose: String(l.purpose).slice(0, 120) }),
98
103
  // A deadline (--by) makes its failure the person's business; an override's by is a name, not that.
99
104
  ...(typeof l.by === 'number' && { due: l.by }) }) });