@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/doors.mjs ADDED
@@ -0,0 +1,547 @@
1
+ // dibs doors: the guard recognizing commands that can't be undone, instead of trusting the agent to
2
+ // say so. An agent decides for itself whether a question is a one-way door, and one that wrongly
3
+ // calls a deploy reversible never asks. With doors on (`dibs doors on`; off by default, since Claude
4
+ // Code and Codex have permission systems of their own), the guard hook turns away a force push over
5
+ // main, a production deploy, a TestFlight upload, a publish, a recursive delete of a home-level
6
+ // folder, a DROP TABLE and the like, unless the person said yes to that door:
7
+ // - once: the agent asks `dibs question ... --about <kind>` (a door's kind makes it one-way and
8
+ // only the person's answer counts), and the person's yes lets one such command through, in that
9
+ // project, within ONCE_FOR
10
+ // - standing: `dibs doors allow <kind>` by the person, for routine doors that shouldn't nag
11
+ // Every door a command goes through under a yes is logged, with the yes it went through under.
12
+ //
13
+ // The hook loads this only when doors are on and the command looks like one (DOOR_HINT in
14
+ // src/guard.mjs), so with doors off it costs nothing. Anything it can't read (a $VARIABLE, a quote
15
+ // it can't close) is let through: words inside quotes and heredocs are data, and a false alarm
16
+ // costs the person's attention. Only agents' calls are checked (AGENT_ENV): the person's own
17
+ // terminal never is.
18
+ import fs from 'node:fs';
19
+ import os from 'node:os';
20
+ import path from 'node:path';
21
+ import { commands, expand, projectKey } from './files.mjs';
22
+ import { guarded, DEFAULT_INTO } from './reviewgate.mjs';
23
+ import { repoOf, noteDoor } from './trailnote.mjs';
24
+
25
+ // The same folder as config.mjs's HOME, worked out here because the hook loads no other module.
26
+ const DIBS_HOME = process.env.DIBS_HOME || path.join(os.homedir(), '.dibs');
27
+ export const DOORS = path.join(DIBS_HOME, 'doors.json');
28
+ // One file per once-only yes that has been used, made with O_EXCL: two commands racing for one yes
29
+ // can't both get it, and the hook takes no lock.
30
+ export const USED = path.join(DIBS_HOME, 'doors-used');
31
+ const EVENTS = path.join(DIBS_HOME, 'events.jsonl');
32
+ // A yes to a question covers the command the agent asked about, which it runs as soon as it hears.
33
+ // An hour leaves room for a build to finish first, and isn't a yes to whatever comes next week.
34
+ export const ONCE_FOR = 60 * 6e4;
35
+
36
+ // Set in an agent's environment: the same list as AGENT_ENV in src/owner.mjs (test/doors-guard
37
+ // checks they agree), copied because owner.mjs loads half of dibs and the hook loads only this.
38
+ export const AGENT_ENV = ['CLAUDECODE', 'CLAUDE_CODE_CHILD_SESSION', 'CLAUDE_CODE_SESSION_ID', 'CLAUDE_CODE_ENTRYPOINT', 'AI_AGENT',
39
+ 'CODEX_SANDBOX', 'CODEX_THREAD_ID', 'CURSOR_AGENT', 'GEMINI_CLI', 'OPENCODE'];
40
+
41
+ // Each kind: what it is, what can't be undone (for the question's --one-way), and the question.
42
+ export const KINDS = {
43
+ 'force-push': { is: 'force pushes over main, master or a protected branch', cant: "a force push replaces the branch on the remote, and commits only the remote had are gone", ask: 'Force-push over this branch on the remote now?' },
44
+ 'remote-delete': { is: 'deleting a branch, tag or repository on a remote', cant: 'a deleted remote branch, tag or repository is gone for everyone who had not fetched it', ask: 'Delete this from the remote now?' },
45
+ deploy: { is: 'production deploys', cant: 'a production deploy reaches real users the moment it lands', ask: 'Deploy to production now?' },
46
+ testflight: { is: 'uploads to TestFlight and App Store Connect', cant: 'an uploaded build number is used up for good and reaches testers', ask: 'Upload this build to TestFlight now?' },
47
+ appstore: { is: 'submissions to App Store review and releases to the App Store', cant: 'a submission goes to Apple, and a release reaches every user', ask: 'Submit this to the App Store now?' },
48
+ publish: { is: 'publishing a package or a GitHub release', cant: 'a published version number can never be reused, and people install it at once', ask: 'Publish this version now?' },
49
+ delete: { is: 'recursive deletes of /, a top-level folder, your home folder or a folder directly in it', cant: 'rm -r skips the Trash: what it deletes is gone', ask: 'Delete this folder for good now?' },
50
+ database: { is: 'dropping or truncating a database, schema or table, and destructive Neon, Supabase, Turso and Cloudflare data commands', cant: 'dropped or deleted data is gone unless a backup holds it', ask: 'Drop or delete this data now?' },
51
+ purchase: { is: 'purchases through known CLIs (domains, live Stripe charges)', cant: 'money spent stays spent', ask: 'Make this purchase now?' },
52
+ };
53
+
54
+ const base = s => String(s || '').slice(String(s || '').lastIndexOf('/') + 1);
55
+ const ASSIGN = /^[A-Za-z_][A-Za-z0-9_]*=/;
56
+ // Package runners whose first word is the tool: pnpm wrangler deploy, bunx vercel --prod.
57
+ const PM = new Set(['npm', 'pnpm', 'yarn', 'bun', 'npx', 'bunx']);
58
+ const TOOLS = new Set(['wrangler', 'vercel', 'fly', 'flyctl', 'firebase', 'netlify', 'ntl', 'supabase', 'neon', 'neonctl', 'twine', 'eas', 'stripe']);
59
+ // Words before the command that only run it, for the command a dibs run starts.
60
+ const LEAD = new Set(['env', 'sudo', 'nice', 'nohup', 'caffeinate', 'time', 'command', 'exec', 'npx', 'bunx']);
61
+ // Flags of these tools that take a value, so the value isn't read as a subcommand.
62
+ const VALUED = new Set(['-c', '--config', '-e', '--env', '--cwd', '-a', '--app', '--project', '-P', '--scope', '-t', '--token', '-C',
63
+ '--account', '--profile', '--output', '-o', '--org', '--project-ref', '--db-url', '--region', '-r', '--branch', '--target']);
64
+ const words = a => {
65
+ const out = [];
66
+ for (let i = 0; i < a.length; i++) {
67
+ const w = a[i];
68
+ if (w == null) { out.push(null); continue; }
69
+ if (VALUED.has(w)) { i++; continue; }
70
+ if (!w.startsWith('-')) out.push(w);
71
+ }
72
+ return out;
73
+ };
74
+ // --env production, --env=production, -e production: the value, or undefined.
75
+ const flag = (a, ...names) => {
76
+ for (let i = 0; i < a.length; i++) {
77
+ if (names.includes(a[i])) return a[i + 1] ?? null;
78
+ const n = names.find(x => x.startsWith('--') && a[i]?.startsWith(`${x}=`));
79
+ if (n) return a[i].slice(n.length + 1);
80
+ }
81
+ return undefined;
82
+ };
83
+ const PROD = /^prod(uction)?$/i;
84
+ const MAINLINE = new Set(['main', 'master', 'production']);
85
+ // A plist that sends the exported build to App Store Connect instead of leaving it on disk.
86
+ const UPLOADS = /<key>destination<\/key>\s*<string>upload<\/string>/;
87
+ // SQL that throws data away. Only read in a SQL client's own argument (psql -c), never in other quotes.
88
+ const DROPS = /\b(drop\s+(database|schema|table)|truncate\s+(table\s+)?["`\w])/i;
89
+ const LOCAL_HOST = /^(localhost|127\.0\.0\.1|::1|\[::1\]|\/.*)?$/;
90
+
91
+ // The doors one command (its words, the program first) goes through: [{ kind, what }].
92
+ // ctx: { dir, src, assigns } for the folder it runs in, the whole Bash line and the VAR=value words before it.
93
+ export function doorsOf(t, ctx) {
94
+ let prog = base(t[0]);
95
+ let a = t.slice(1);
96
+ if (prog === 'xcrun') { prog = base(a[0]); a = a.slice(1); }
97
+ if (PM.has(prog) && ['exec', 'dlx', 'x'].includes(a[0])) a = a.slice(1);
98
+ if (PM.has(prog) && TOOLS.has(a[0])) { prog = a[0]; a = a.slice(1); }
99
+ if (/^python(3(\.\d+)*)?$/.test(prog) && a[0] === '-m') { prog = a[1]; a = a.slice(2); }
100
+ const w = words(a);
101
+ const has = (...f) => f.some(x => a.includes(x));
102
+ const one = (kind, what) => [{ kind, what }];
103
+ if (!prog) return [];
104
+ if (prog === 'git') return gitDoors(a, ctx);
105
+ if (prog === 'dibs' || prog === 'dibs.mjs') return dibsDoors(a, ctx);
106
+ if (has('--help', '--dry-run')) return [];
107
+ if (prog === 'wrangler') {
108
+ const env = flag(a, '--env', '-e');
109
+ const prodEnv = env === undefined || PROD.test(env || '');
110
+ if (['deploy', 'publish'].includes(w[0]) && prodEnv) return one('deploy', `a production deploy (wrangler ${w[0]})`);
111
+ if (w[0] === 'versions' && w[1] === 'deploy' && prodEnv) return one('deploy', 'a production deploy (wrangler versions deploy)');
112
+ if (w[0] === 'pages' && ['deploy', 'publish'].includes(w[1])) {
113
+ const br = flag(a, '--branch');
114
+ return br === undefined || MAINLINE.has(br) ? one('deploy', 'a production deploy (wrangler pages deploy)') : [];
115
+ }
116
+ if (w[0] === 'd1' && w[1] === 'execute' && has('--remote') && DROPS.test(flag(a, '--command') || '')) return one('database', 'dropping data in a D1 database');
117
+ if ((w[0] === 'd1' && w[1] === 'delete') || (w[0] === 'r2' && w[1] === 'bucket' && w[2] === 'delete') || (w[0] === 'kv' && w[1] === 'namespace' && w[2] === 'delete'))
118
+ return one('database', `deleting a Cloudflare ${w[0] === 'd1' ? 'D1 database' : w[0] === 'r2' ? 'R2 bucket' : 'KV namespace'}`);
119
+ return [];
120
+ }
121
+ if (prog === 'vercel') {
122
+ if (w[0] === 'domains' && ['buy', 'purchase'].includes(w[1])) return one('purchase', 'buying a domain (vercel domains buy)');
123
+ if (w[0] === 'promote' || has('--prod', '--production') || flag(a, '--target') === 'production') return one('deploy', 'a production deploy (vercel --prod)');
124
+ return [];
125
+ }
126
+ if ((prog === 'fly' || prog === 'flyctl') && w[0] === 'deploy' && !has('--build-only')) return one('deploy', `a production deploy (${prog} deploy)`);
127
+ if (prog === 'firebase' && w[0] === 'deploy') return one('deploy', 'a production deploy (firebase deploy)');
128
+ if ((prog === 'netlify' || prog === 'ntl') && w[0] === 'deploy' && has('--prod', '--prod-if-unlocked', '--prodIfUnlocked')) return one('deploy', 'a production deploy (netlify deploy --prod)');
129
+ if (prog === 'altool' && a.some(x => /^--upload-(app|package)$/.test(x || ''))) return one('testflight', 'an upload to App Store Connect (altool)');
130
+ if (prog === 'xcodebuild' && a.includes('-exportArchive') && exportsUpload(a, ctx)) return one('testflight', 'an upload to App Store Connect (xcodebuild -exportArchive)');
131
+ if (prog === 'asc') {
132
+ if (w[0] === 'builds' && w[1] === 'upload') return one('testflight', 'an upload to App Store Connect (asc builds upload)');
133
+ if (w[0] === 'publish' && w[1] === 'testflight') return one('testflight', 'an upload to TestFlight (asc publish testflight)');
134
+ if (w[0] === 'publish' && w[1] === 'appstore') return has('--submit') ? one('appstore', 'a submission to App Store review (asc publish appstore --submit)') : one('testflight', 'an upload to App Store Connect (asc publish appstore)');
135
+ if (w[0] === 'review' && ['submit', 'submissions-submit'].includes(w[1])) return one('appstore', 'a submission to App Store review (asc review submit)');
136
+ if (w[0] === 'versions' && w[1] === 'release') return one('appstore', 'releasing a version on the App Store (asc versions release)');
137
+ return [];
138
+ }
139
+ if (prog === 'fastlane') {
140
+ if (w.some(x => ['pilot', 'upload_to_testflight', 'testflight'].includes(x))) return one('testflight', 'an upload to TestFlight (fastlane pilot)');
141
+ if (w.some(x => ['deliver', 'upload_to_app_store', 'appstore'].includes(x))) return one('appstore', 'a submission to the App Store (fastlane deliver)');
142
+ return [];
143
+ }
144
+ if (prog === 'eas' && w[0] === 'submit') return one('testflight', 'a submission to the app stores (eas submit)');
145
+ if (['npm', 'pnpm', 'bun', 'yarn'].includes(prog) && (w[0] === 'publish' || (prog === 'yarn' && w[0] === 'npm' && w[1] === 'publish'))) return one('publish', `publishing a package (${prog} publish)`);
146
+ if (prog === 'cargo' && w[0] === 'publish' && !has('-n')) return one('publish', 'publishing a crate (cargo publish)');
147
+ if (prog === 'twine' && w[0] === 'upload') return one('publish', 'publishing a package to PyPI (twine upload)');
148
+ if ((prog === 'poetry' || prog === 'uv') && w[0] === 'publish') return one('publish', `publishing a package (${prog} publish)`);
149
+ if (prog === 'gem' && w[0] === 'push') return one('publish', 'publishing a gem (gem push)');
150
+ if (prog === 'gh') {
151
+ if (w[0] === 'release' && w[1] === 'create' && !has('--draft', '-d')) return one('publish', 'publishing a GitHub release (gh release create)');
152
+ if (w[0] === 'repo' && w[1] === 'delete') return one('remote-delete', 'deleting a GitHub repository (gh repo delete)');
153
+ return [];
154
+ }
155
+ if (prog === 'rm') return rmDoors(a, ctx);
156
+ if (['psql', 'mysql', 'mariadb'].includes(prog)) return sqlDoors(prog, a);
157
+ if (prog === 'neon' || prog === 'neonctl') {
158
+ const res = w[0]?.replace(/s$/, '');
159
+ if (['project', 'branche', 'branch', 'database', 'role'].includes(res) && w[1] === 'delete') return one('database', `deleting a Neon ${res === 'branche' ? 'branch' : res} (${prog} ${w[0]} delete)`);
160
+ if (['branche', 'branch'].includes(res) && ['reset', 'restore'].includes(w[1])) return one('database', `overwriting a Neon branch (${prog} branches ${w[1]})`);
161
+ return [];
162
+ }
163
+ if (prog === 'supabase') {
164
+ if (['projects', 'branches'].includes(w[0]) && w[1] === 'delete') return one('database', `deleting a Supabase ${w[0].slice(0, -1)} (supabase ${w[0]} delete)`);
165
+ if (w[0] === 'db' && w[1] === 'reset' && (has('--linked') || flag(a, '--db-url') !== undefined)) return one('database', 'resetting a remote Supabase database (supabase db reset --linked)');
166
+ if (w[0] === 'storage' && w[1] === 'rm') return one('database', 'deleting Supabase storage objects (supabase storage rm)');
167
+ return [];
168
+ }
169
+ if (prog === 'turso' && w[0] === 'db' && w[1] === 'destroy') return one('database', 'deleting a Turso database (turso db destroy)');
170
+ if (prog === 'gcloud' && w[0] === 'domains' && w[1] === 'registrations' && w[2] === 'register') return one('purchase', 'buying a domain (gcloud domains registrations register)');
171
+ if (prog === 'aws' && w[0] === 'route53domains' && w[1] === 'register-domain') return one('purchase', 'buying a domain (aws route53domains register-domain)');
172
+ if (prog === 'stripe' && has('--live') && w.some(x => ['create', 'confirm', 'capture', 'pay'].includes(x))) return one('purchase', 'a live Stripe charge or payment');
173
+ return [];
174
+ }
175
+
176
+ // xcodebuild -exportArchive with an options plist whose destination is upload.
177
+ function exportsUpload(a, ctx) {
178
+ const plist = a[a.indexOf('-exportOptionsPlist') + 1];
179
+ if (!plist) return false;
180
+ if (plist.startsWith('/dev/')) return UPLOADS.test(ctx.src); // a heredoc fed on stdin
181
+ try { return UPLOADS.test(fs.readFileSync(path.resolve(ctx.dir || '/', expand(plist)), 'utf8')); } catch { return false; }
182
+ }
183
+
184
+ const GIT_VALUED = new Set(['-C', '-c', '--git-dir', '--work-tree', '--namespace', '--exec-path', '--config-env']);
185
+ const PUSH_VALUED = new Set(['-o', '--push-option', '--repo', '--receive-pack', '--exec']);
186
+ function gitDoors(a, ctx) {
187
+ let i = 0, dir = ctx.dir;
188
+ for (; i < a.length; i++) {
189
+ const x = a[i];
190
+ if (x == null) return [];
191
+ if (x === '-C') { const p = a[++i]; if (p == null) return []; dir = dir && path.resolve(dir, expand(p)); continue; }
192
+ if (GIT_VALUED.has(x)) { i++; continue; }
193
+ if (!x.startsWith('-')) break;
194
+ }
195
+ if (a[i] !== 'push') return [];
196
+ const rest = a.slice(i + 1);
197
+ let force = false, del = false, all = false;
198
+ const pos = [];
199
+ for (let k = 0; k < rest.length; k++) {
200
+ const x = rest[k];
201
+ if (x == null) return [];
202
+ if (x === '--') { pos.push(...rest.slice(k + 1)); break; }
203
+ if (x === '--dry-run' || x === '--help' || x === '-h') return [];
204
+ if (x === '--force' || x.startsWith('--force-with-lease') || x === '--force-if-includes') { force = true; continue; }
205
+ if (x === '--delete') { del = true; continue; }
206
+ if (x === '--mirror') { force = true; all = true; continue; }
207
+ if (x === '--all' || x === '--branches') { all = true; continue; }
208
+ if (PUSH_VALUED.has(x)) { k++; continue; }
209
+ if (/^-[a-zA-Z0-9]+$/.test(x)) { // short flags, maybe several in one: -fu
210
+ if (x.includes('n')) return [];
211
+ if (x.includes('f')) force = true;
212
+ if (x.includes('d')) del = true;
213
+ continue;
214
+ }
215
+ if (x.startsWith('-')) continue;
216
+ pos.push(x);
217
+ }
218
+ if (pos.some(x => x == null)) return [];
219
+ const specs = pos.slice(1);
220
+ if (del) return specs.length ? [{ kind: 'remote-delete', what: `deleting ${specs.join(', ')} on ${pos[0]} (git push --delete)` }] : [];
221
+ const gone = specs.filter(s => /^:[^:]/.test(s));
222
+ if (gone.length) return [{ kind: 'remote-delete', what: `deleting ${gone.map(s => s.slice(1)).join(', ')} on ${pos[0]} (git push ${gone[0]})` }];
223
+ const branch = dir ? repoOf(dir)?.branch || null : null;
224
+ const protectedOnes = new Set([...DEFAULT_INTO, ...((dir && guarded(dir)) || [])]);
225
+ if (all && force) return [{ kind: 'force-push', what: `a force push of every branch (git push ${rest.includes('--mirror') ? '--mirror' : '--all --force'})` }];
226
+ const targets = specs.length ? specs : [force ? 'HEAD' : null].filter(Boolean);
227
+ for (const s of targets) {
228
+ const forced = force || s.startsWith('+');
229
+ const x = s.replace(/^\+/, '');
230
+ let dst = x.includes(':') ? x.split(':')[1] : x;
231
+ if (dst === 'HEAD') dst = branch;
232
+ dst = (dst || '').replace(/^refs\/heads\//, '');
233
+ if (forced && protectedOnes.has(dst)) return [{ kind: 'force-push', what: `a force push over ${dst} (git push ${force ? '--force' : s})` }];
234
+ }
235
+ return [];
236
+ }
237
+
238
+ // dibs run <res> ... -- <command>: the command it runs, and a deploy run told it's for production.
239
+ function dibsDoors(a, ctx) {
240
+ const dd = a.indexOf('--');
241
+ if (dd < 0) return [];
242
+ let inner = a.slice(dd + 1);
243
+ while (inner[0] != null && (ASSIGN.test(inner[0]) || LEAD.has(base(inner[0])))) {
244
+ inner = inner.slice(1);
245
+ while (inner[0]?.startsWith('-')) inner = inner.slice(1);
246
+ }
247
+ if (inner[0] == null) return [];
248
+ const found = doorsOf(inner, ctx);
249
+ if (found.length) return found;
250
+ const own = a.slice(0, dd);
251
+ const res = own[0] === 'run' ? own.slice(1).filter(x => x && !x.startsWith('-')).flatMap(x => x.split(',')) : [];
252
+ if (!res.includes('deploy')) return [];
253
+ const told = [...inner, ...(ctx.assigns || [])].some(x => x != null && (PROD.test(x) || /^--?(env|environment|target|stage)=prod(uction)?$/i.test(x) || /^[A-Za-z_]\w*=prod(uction)?$/i.test(x)))
254
+ || ['--env', '--environment', '--target', '--stage', '-e'].some(f => PROD.test(flag(inner, f) || ''));
255
+ return told ? [{ kind: 'deploy', what: 'a production deploy (dibs run deploy for production)' }] : [];
256
+ }
257
+
258
+ // A home-level folder, the home folder itself, /, or a top-level folder: what one rm -r takes with it.
259
+ // System temp folders are where scratch lives, and are left alone.
260
+ const TEMP_TOP = new Set(['tmp', 'var', 'private']);
261
+ // A path with / between folders and no drive letter: on Windows a path with backslashes split on /
262
+ // was one part, so every recursive delete read as one of a top-level folder.
263
+ const posixy = p => p.replace(/\\/g, '/').replace(/^[A-Za-z]:(?=\/)/, '');
264
+ function sweeping(abs) {
265
+ abs = posixy(abs);
266
+ const home = posixy(os.homedir());
267
+ if (abs === home || path.posix.dirname(abs) === home) return true;
268
+ const parts = abs.split('/').filter(Boolean);
269
+ return parts.length <= 1 || (parts.length === 2 && !TEMP_TOP.has(parts[0]));
270
+ }
271
+ function rmDoors(a, ctx) {
272
+ let recursive = false;
273
+ const targets = [];
274
+ for (let k = 0; k < a.length; k++) {
275
+ const x = a[k];
276
+ if (x === '--') { targets.push(...a.slice(k + 1)); break; }
277
+ if (x == null) { targets.push(null); continue; }
278
+ if (x === '--recursive' || /^-[a-zA-Z]*[rR][a-zA-Z]*$/.test(x)) { recursive = true; continue; }
279
+ if (!x.startsWith('-')) targets.push(x);
280
+ }
281
+ if (!recursive) return [];
282
+ for (const p of targets) {
283
+ if (p == null) continue; // a $VARIABLE: src/files.mjs tmpGuard looks at those
284
+ const e = expand(p);
285
+ if (!path.isAbsolute(e) && !ctx.dir) continue;
286
+ const abs = posixy(path.resolve(ctx.dir || '/', e)).replace(/\/\*$/, '/x'); // dir/* takes everything in dir
287
+ if (sweeping(abs)) return [{ kind: 'delete', what: `a recursive delete of ${p}` }];
288
+ }
289
+ return [];
290
+ }
291
+
292
+ // psql -c "DROP TABLE ..." against a server that isn't this machine's.
293
+ function sqlDoors(prog, a) {
294
+ const sql = prog === 'psql' ? flag(a, '-c', '--command') : flag(a, '-e', '--execute');
295
+ if (!sql || !DROPS.test(sql)) return [];
296
+ const host = flag(a, '-h', '--host');
297
+ const url = a.find(x => x == null || /^(postgres(ql)?|mysql):\/\//.test(x));
298
+ const urlHost = url === undefined ? undefined : url === null ? null : url.replace(/^[a-z]+:\/\/([^@/]*@)?/, '').split(/[/:?]/)[0];
299
+ // No host and no URL: the local socket. A URL in a $VARIABLE is the usual way to reach a real one.
300
+ const remote = (host != null && !LOCAL_HOST.test(host)) || urlHost === null || (urlHost != null && !LOCAL_HOST.test(urlHost));
301
+ return remote ? [{ kind: 'database', what: `dropping data through ${prog} (${sql.match(DROPS)[0].replace(/\s+/g, ' ').toUpperCase()})` }] : [];
302
+ }
303
+
304
+ // Every door in a Bash command, with the folder each runs in. split: src/guard.mjs's shell reader.
305
+ export function doorsIn(cmd, split, cwd) {
306
+ const segs = typeof cmd === 'string' && split(cmd);
307
+ if (!segs) return [];
308
+ const out = [];
309
+ for (const { seg, name, args, dir } of commands(segs, cwd)) {
310
+ if (!name) continue;
311
+ const t = [name, ...args.map(w => (w.opaque ? null : w.text))];
312
+ const assigns = seg.filter(w => !w.redir && !w.opaque && ASSIGN.test(w.text)).map(w => w.text);
313
+ const line = seg.filter(w => !w.redir).map(w => w.text).join(' ');
314
+ for (const d of doorsOf(t, { dir: dir || cwd, src: cmd, assigns })) out.push({ ...d, dir: dir || cwd, line });
315
+ }
316
+ return out;
317
+ }
318
+
319
+ // The project a folder belongs to, as dibs question records it (from its real path: /tmp is /private/tmp).
320
+ const projectOf = dir => { try { return projectKey(fs.realpathSync.native(dir)); } catch { return projectKey(dir); } };
321
+ const readYeses = () => { try { return JSON.parse(fs.readFileSync(DOORS, 'utf8')).yeses || []; } catch { return []; } };
322
+ const usedFile = id => path.join(USED, String(id).replace(/[^\w-]/g, ''));
323
+ const used = y => y.once && fs.existsSync(usedFile(y.id));
324
+ const lower = s => String(s || '').toLowerCase();
325
+ // Whether a yes covers this door: its kind, its project (or every project), its words, its time.
326
+ export function covers(y, d, project, t = Date.now()) {
327
+ return y.kind === d.kind && (!y.project || y.project === project) && !(y.until && t > y.until)
328
+ && (y.match || []).every(m => lower(d.line).split(/\s+/).includes(lower(m)));
329
+ }
330
+ const kindOn = (cfg, kind) => !(cfg?.doors?.off || []).includes(kind);
331
+ export const doorsOn = cfg => cfg?.doors?.on === true;
332
+
333
+ // The hook's answer for a Bash call with doors on: a deny for a door nobody said yes to, or null.
334
+ // A command that goes through under a yes uses it up (a once-only one) and goes on the record.
335
+ // vendor: the agent tool whose format the call came in (src/guard.mjs vendorOf). Codex's, Gemini CLI's,
336
+ // Cursor's and OpenCode's formats are an agent's call by themselves; Claude Code's hooks carry its variables.
337
+ export function gate(input, split, cfg, { env = process.env, vendor = 'claude' } = {}) {
338
+ if (vendor === 'claude' && !AGENT_ENV.some(k => env[k])) return null;
339
+ const cwd = typeof input.cwd === 'string' ? input.cwd : null;
340
+ const found = doorsIn(input.tool_input?.command, split, cwd).filter(d => kindOn(cfg, d.kind));
341
+ if (!found.length) return null;
342
+ const yeses = readYeses();
343
+ const t = Date.now();
344
+ const picks = found.map(d => {
345
+ const project = projectOf(d.dir || cwd || '/');
346
+ return { d, project, y: yeses.filter(y => covers(y, d, project, t) && !used(y)).sort((a, b) => !!b.once - !!a.once)[0] || null };
347
+ });
348
+ const missing = picks.find(p => !p.y);
349
+ // A once-only yes is used when its command is let through; another door on the line without one keeps it.
350
+ if (!missing) for (const p of picks) {
351
+ if (!p.y.once) continue;
352
+ try { fs.mkdirSync(USED, { recursive: true }); fs.writeFileSync(usedFile(p.y.id), String(t), { flag: 'wx' }); }
353
+ catch { return refuse(input, { ...p, y: null }, t); }
354
+ }
355
+ if (missing) return refuse(input, missing, t);
356
+ for (const p of picks) {
357
+ record({ act: 'door', door: p.d.kind, what: p.d.what, yes: p.y.id, yesBy: p.y.by, once: !!p.y.once, project: p.project, session: input.session_id || null }, t);
358
+ try { noteDoor(input, { door: p.d.kind, what: p.d.what, yes: p.y.id, yesBy: p.y.by, dir: p.d.dir }); } catch {}
359
+ }
360
+ return null;
361
+ }
362
+
363
+ // One line in the event log, as src/events.mjs writes them: never the command's text.
364
+ function record(e, t) {
365
+ try { fs.appendFileSync(EVENTS, JSON.stringify({ at: t, kind: 'override', by: 'an agent', byAgent: true, ...e }) + '\n'); } catch {}
366
+ }
367
+
368
+ function refuse(input, { d, project }, t) {
369
+ record({ act: 'door refused', door: d.kind, what: d.what, project, session: input.session_id || null }, t);
370
+ const k = KINDS[d.kind];
371
+ const why = `dibs: this command is ${d.what}, and that can't be undone, so the person's yes comes first (dibs doors is on). `
372
+ + "Only the person's own answer counts: not yours, another agent's, a standing rule's or a past decision. Ask, and wait for the answer:\n"
373
+ + ` dibs question "${k.ask}" --options yes,no --recommend yes -m "<why now, in plain words>" --one-way "${k.cant}" --about ${d.kind} --wait\n`
374
+ + `Their yes lets one such command through in this project in the next ${ONCE_FOR / 6e4} minutes. If they say no, don't run it, and don't look for another way to do the same thing.`;
375
+ return { hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'deny', permissionDecisionReason: why } };
376
+ }
377
+
378
+ // ----- dibs doors: the person's switch, kinds and standing yeses (loaded by the CLI, never the hook) -----
379
+
380
+ // Exit code for what only the person may do (as dibs secret's refusals).
381
+ const REFUSED = 78;
382
+ // A yes as the person writes one: yes, ok, go ahead, ship it. Anything else is no.
383
+ const YES = /^\s*(yes|y|yep|yeah|ok|okay|sure|approved?|allow|go( ahead)?|do it|ship it)\b/i;
384
+ // Enough for every routine door a person keeps; a loop that makes more is a bug.
385
+ const MOST = 200;
386
+ const LOCK_WAIT = 15e3;
387
+
388
+ async function deps() {
389
+ const [{ actor, logChange }, { underLock, commit }, util, config] = await Promise.all([
390
+ import('./owner.mjs'), import('./lock.mjs'), import('./util.mjs'), import('./config.mjs')]);
391
+ return { actor, logChange, underLock, commit, ...util, paths: config.paths, loadConfig: config.loadConfig };
392
+ }
393
+
394
+ async function locked(fn) {
395
+ const { underLock, commit, die, fakeFull } = await deps();
396
+ const r = underLock(`${DOORS.slice(0, -5)}.lock`, h => {
397
+ let s = {};
398
+ try { s = JSON.parse(fs.readFileSync(DOORS, 'utf8')); } catch {}
399
+ s.seq ||= 0; s.yeses ||= [];
400
+ const before = JSON.stringify(s);
401
+ const t = Date.now();
402
+ // Spent and expired yeses go, with their used-files.
403
+ const done = s.yeses.filter(y => (y.until && t > y.until) || used(y));
404
+ for (const y of done) try { fs.rmSync(usedFile(y.id), { force: true }); } catch {}
405
+ s.yeses = s.yeses.filter(y => !done.includes(y));
406
+ const out = fn(s);
407
+ if (JSON.stringify(s) !== before) commit(h, DOORS, JSON.stringify(s, null, 1), { fake: () => fakeFull('state') });
408
+ return out;
409
+ }, { wait: LOCK_WAIT, files: [DOORS] });
410
+ if (!r) die(`doors.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);
411
+ return r.out;
412
+ }
413
+
414
+ // The door kind a question is about, when doors are on and that kind is checked: its answer must be
415
+ // the person's, and their yes lets one such command through.
416
+ export const doorOf = (cfg, about) => (doorsOn(cfg) && KINDS[about] && kindOn(cfg, about) ? about : null);
417
+
418
+ // The person answered a door's question: a yes becomes a once-only yes for that door in that project.
419
+ // Returns what it covers, for the answer's line, or null for anything but yes.
420
+ export async function yesFromAnswer(q) {
421
+ if (!q.door || !YES.test(String(q.answer || ''))) return null;
422
+ const { actor } = await deps();
423
+ const who = actor();
424
+ if (who.agent) return null;
425
+ const t = Date.now();
426
+ const y = await locked(s => {
427
+ const y = { id: `y${++s.seq}`, kind: q.door, project: q.project || null, once: true, until: t + ONCE_FOR, by: who.name, question: q.id, at: t };
428
+ s.yeses.push(y);
429
+ return y;
430
+ });
431
+ record({ act: 'door yes', door: y.kind, yes: y.id, project: y.project, question: q.id, by: who.name, byAgent: false }, t);
432
+ return `that yes lets one ${y.kind} command through, in ${place(y.project)}, in the next ${ONCE_FOR / 6e4} minutes (${y.id})`;
433
+ }
434
+
435
+ const USAGE = `dibs doors: the guard turns away commands that can't be undone until the person says yes. Off unless the person turns it on
436
+ dibs doors [--json] on or off, each kind of door, and the standing yeses
437
+ dibs doors on | off turn the check on or off (once the person turns it on, only they can turn it off)
438
+ dibs doors on | off <kind> check that kind, or stop checking it (off: the person only)
439
+ dibs doors allow <kind> [--repo <dir>] [--match words] [--for 30d] [--once] [-m why]
440
+ the person's standing yes: that kind goes through without asking, everywhere
441
+ unless --repo; --match: only commands with every one of those words
442
+ dibs doors block <kind|id> take a kind's standing yeses back (or one, by id): it asks the person again
443
+ dibs doors check "<command>" which door a command goes through, if any
444
+ Kinds: ${Object.keys(KINDS).join(', ')}`;
445
+
446
+ export async function doors(args) {
447
+ const d = await deps();
448
+ const { die, say, actor, logChange } = d;
449
+ const [verb, ...rest] = args;
450
+ const json = args.includes('--json');
451
+ const raw = () => { try { return JSON.parse(fs.readFileSync(d.paths.config, 'utf8')); } catch { return {}; } };
452
+ const cfg = raw();
453
+ const who = actor();
454
+ const notYours = what => die(`only the person can ${what}: it loosens the check, and you're an agent (${who.name}). Nothing changed (exit 78: refused). Ask them if it should change.`, REFUSED);
455
+ const kindArg = k => (KINDS[k] ? k : die(`${k ? `"${k}" isn't a kind of door` : 'which kind?'}. Kinds: ${Object.keys(KINDS).join(', ')}`));
456
+ const write = doors => {
457
+ const c = raw();
458
+ c.doors = doors;
459
+ fs.mkdirSync(path.dirname(d.paths.config), { recursive: true });
460
+ const tmp = `${d.paths.config}.${process.pid}`;
461
+ fs.writeFileSync(tmp, JSON.stringify(c, null, 2) + '\n');
462
+ fs.renameSync(tmp, d.paths.config);
463
+ };
464
+ const cur = { on: false, off: [], ...(cfg.doors || {}) };
465
+ if (!verb || verb === '--json' || verb === 'list') return show(cfg, json);
466
+ if (verb === 'help' || verb === '--help' || verb === '-h') return console.log(USAGE);
467
+ if (verb === 'check') {
468
+ const { split } = await import('./guard.mjs');
469
+ const found = doorsIn(rest.join(' '), split, process.cwd());
470
+ if (!found.length) { console.log('no door: it goes through as usual'); process.exitCode = 1; return; }
471
+ for (const f of found) console.log(`${f.kind}: ${f.what}${doorsOn(cfg) ? (kindOn(cfg, f.kind) ? '' : ' (not checked: that kind is off)') : ' (dibs doors is off, so nothing is checked)'}`);
472
+ return;
473
+ }
474
+ if (verb === 'on' || verb === 'off') {
475
+ const kind = rest[0] ? kindArg(rest[0]) : null;
476
+ const on = verb === 'on';
477
+ if (kind) {
478
+ if (!on && who.agent) notYours(`stop checking ${kind}`);
479
+ const off = on ? cur.off.filter(k => k !== kind) : [...new Set([...cur.off, kind])];
480
+ write({ ...cur, off });
481
+ logChange(`doors ${verb} ${kind}`, { door: kind });
482
+ return console.log(`${kind} (${KINDS[kind].is}): ${on ? 'checked' : 'not checked'}${cur.on ? '' : '. dibs doors itself is off: dibs doors on'}`);
483
+ }
484
+ if (!on && who.agent && cur.on && !cur.byAgent) notYours('turn dibs doors off');
485
+ write({ ...cur, on, by: who.name, ...(who.agent ? { byAgent: true } : { byAgent: false }), at: Date.now() });
486
+ logChange(`doors ${verb}`, {});
487
+ return console.log(on ? `dibs doors is on: agents' commands that can't be undone (${Object.keys(KINDS).filter(k => kindOn(cfg, k)).join(', ')}) wait for your yes. See them: dibs doors`
488
+ : 'dibs doors is off: the guard no longer checks for commands that can\'t be undone.');
489
+ }
490
+ if (verb === 'allow') {
491
+ const kind = kindArg(rest[0]);
492
+ if (who.agent) notYours(`say yes to ${kind}`);
493
+ const o = { once: false };
494
+ for (let i = 1; i < rest.length; i++) {
495
+ const a = rest[i], next = () => rest[++i] ?? die(`${a} needs a value`);
496
+ if (a === '--repo') o.project = projectOf(path.resolve(expand(next())));
497
+ else if (a === '--here') o.project = projectOf(process.cwd());
498
+ else if (a === '--match') o.match = next().split(/[\s,]+/).filter(Boolean);
499
+ else if (a === '--for') o.until = Date.now() + d.ms(next());
500
+ else if (a === '--once') o.once = true;
501
+ else if (a === '-m' || a === '--msg') o.why = next();
502
+ else die(`unknown ${a.startsWith('-') ? 'flag' : 'word'} ${a}.\n${USAGE}`);
503
+ }
504
+ const y = await locked(s => {
505
+ if (s.yeses.length >= MOST) die(`there are already ${MOST} yeses. Take some back first: dibs doors block <id>`);
506
+ const y = { id: `y${++s.seq}`, kind, project: o.project || null, ...(o.match && { match: o.match }), once: o.once, until: o.until || null, by: who.name, at: Date.now(), ...(o.why && { why: o.why }) };
507
+ s.yeses.push(y);
508
+ return y;
509
+ });
510
+ logChange('doors allow', { door: kind, yes: y.id, project: y.project, once: y.once, until: y.until });
511
+ return console.log(`${y.id}: ${describe(y)}.${cur.on ? '' : ' dibs doors is off, so nothing is checked yet: dibs doors on'}`);
512
+ }
513
+ if (verb === 'block') {
514
+ const w = rest[0] || die(`block what? dibs doors block <kind|id>\n${USAGE}`);
515
+ const isId = /^y\d+$/.test(w);
516
+ if (!isId) kindArg(w);
517
+ const gone = await locked(s => {
518
+ const g = s.yeses.filter(y => (isId ? y.id === w : y.kind === w));
519
+ s.yeses = s.yeses.filter(y => !g.includes(y));
520
+ return g;
521
+ });
522
+ // Blocking a kind also checks it again, if the person had stopped checking it.
523
+ if (!isId && cur.off.includes(w)) write({ ...cur, off: cur.off.filter(k => k !== w) });
524
+ logChange('doors block', { door: isId ? gone[0]?.kind ?? null : w, yeses: gone.map(y => y.id) });
525
+ if (isId && !gone.length) { say(`no yes ${w}. See them: dibs doors`); process.exitCode = 1; return; }
526
+ return console.log(`${gone.length ? `took back ${gone.map(y => y.id).join(', ')}` : 'no standing yes to take back'}${isId ? '' : `: ${w} asks the person every time`}.`);
527
+ }
528
+ die(USAGE);
529
+ }
530
+
531
+ const place = p => (p ? p.replace(os.homedir(), '~') : 'every project');
532
+ function describe(y) {
533
+ return `${y.once ? 'one' : 'every'} ${y.kind} command${y.match ? ` with ${y.match.join(' ')} in it` : ''} goes through without asking, in ${place(y.project)}`
534
+ + `${y.until ? `, until ${new Date(y.until).toLocaleString()}` : ''} (yes from ${y.by})`;
535
+ }
536
+
537
+ function show(cfg, json) {
538
+ const yeses = readYeses().filter(y => !(y.until && Date.now() > y.until) && !used(y));
539
+ const kinds = Object.entries(KINDS).map(([kind, k]) => ({ kind, is: k.is, checked: kindOn(cfg, kind) }));
540
+ if (json) return console.log(JSON.stringify({ on: doorsOn(cfg), by: cfg.doors?.by ?? null, kinds, yeses }, null, 1));
541
+ const out = [doorsOn(cfg) ? `dibs doors is on (turned on by ${cfg.doors.by || 'the person'}): an agent's command that can't be undone waits for the person's yes.`
542
+ : "dibs doors is off: the guard doesn't check for commands that can't be undone. Turn it on: dibs doors on"];
543
+ for (const k of kinds) out.push(` ${k.checked ? 'checked ' : 'not checked'} ${k.kind}: ${k.is}`);
544
+ out.push(yeses.length ? 'Standing and unused yeses:' : 'No yeses: every door asks the person. A routine one can go through without asking: dibs doors allow <kind>');
545
+ for (const y of yeses) out.push(` ${y.id} ${describe(y)}`);
546
+ console.log(out.join('\n'));
547
+ }