@dibssoftware/dibs 0.0.181 → 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.
- package/CHANGELOG.md +103 -1
- package/README.md +10 -8
- package/bin/dibs.mjs +370 -73
- package/docs/agents.md +303 -0
- package/docs/council.md +88 -0
- package/docs/files.md +3 -3
- package/docs/guard.md +86 -11
- package/docs/json.md +211 -0
- package/docs/later.md +5 -5
- package/docs/machines.md +6 -6
- package/docs/questions.md +104 -3
- package/docs/reference.md +124 -30
- package/docs/relay.md +120 -9
- package/docs/releasing.md +7 -1
- package/docs/scheduling.md +28 -6
- package/docs/secrets.md +53 -0
- package/docs/simulators.md +3 -3
- package/package.json +1 -1
- package/skills/dibs/SKILL.md +79 -149
- package/src/about.mjs +341 -0
- package/src/acquire.mjs +111 -27
- package/src/after.mjs +127 -0
- package/src/agents.mjs +2 -1
- package/src/alerts.mjs +95 -42
- package/src/answers.mjs +2 -2
- package/src/board.mjs +21 -16
- package/src/broker.mjs +23 -7
- package/src/carry.mjs +287 -0
- package/src/codex.mjs +132 -0
- package/src/commands.mjs +243 -82
- package/src/config.mjs +85 -14
- package/src/connect.mjs +4 -2
- package/src/cool.mjs +27 -11
- package/src/council.mjs +482 -0
- package/src/cwd.mjs +9 -0
- package/src/decisions.mjs +250 -0
- package/src/declare.mjs +96 -0
- package/src/diskreport.mjs +306 -0
- package/src/diskuse.mjs +420 -0
- package/src/diskwarn.mjs +68 -13
- package/src/doctor.mjs +149 -0
- package/src/doors.mjs +547 -0
- package/src/durable.mjs +143 -0
- package/src/envs.mjs +372 -0
- package/src/events.mjs +7 -2
- package/src/files.mjs +118 -6
- package/src/guard.mjs +239 -86
- package/src/guardd.mjs +8 -1
- package/src/halt.mjs +63 -0
- package/src/handoffs.mjs +362 -0
- package/src/history.mjs +34 -4
- package/src/hogs.mjs +36 -8
- package/src/jobprogress.mjs +283 -0
- package/src/later.mjs +21 -10
- package/src/lock.mjs +33 -9
- package/src/measure.mjs +42 -11
- package/src/media.mjs +240 -0
- package/src/news.mjs +31 -0
- package/src/notes.mjs +49 -8
- package/src/notices.mjs +126 -43
- package/src/ondemand.mjs +25 -2
- package/src/outcome.mjs +163 -0
- package/src/overlap.mjs +2 -2
- package/src/override.mjs +149 -79
- package/src/owner.mjs +15 -2
- package/src/people.mjs +236 -0
- package/src/pickup.mjs +72 -0
- package/src/picture.mjs +321 -0
- package/src/plain.mjs +84 -18
- package/src/platform.mjs +19 -0
- package/src/preempt.mjs +123 -15
- package/src/primer.mjs +91 -20
- package/src/prints.mjs +99 -0
- package/src/proc.mjs +1 -1
- package/src/progress.mjs +49 -3
- package/src/proof.mjs +102 -0
- package/src/push.mjs +271 -0
- package/src/questions.mjs +328 -57
- package/src/quota.mjs +1 -1
- package/src/recap.mjs +205 -0
- package/src/relay.mjs +139 -20
- package/src/remote.mjs +23 -10
- package/src/reviewgate.mjs +268 -0
- package/src/reviews.mjs +377 -0
- package/src/route.mjs +263 -0
- package/src/rules.mjs +216 -0
- package/src/schedule.mjs +238 -44
- package/src/schema.mjs +62 -0
- package/src/scratch.mjs +2 -2
- package/src/serve.mjs +3 -2
- package/src/signed.mjs +97 -0
- package/src/simpool.mjs +46 -1
- package/src/spend.mjs +375 -0
- package/src/state.mjs +43 -17
- package/src/talk.mjs +1078 -133
- package/src/thin.sh +2 -0
- package/src/trail.mjs +290 -0
- package/src/trailnote.mjs +209 -0
- package/src/util.mjs +7 -0
- package/src/vault.mjs +435 -0
- package/src/vendors.mjs +327 -0
- package/src/version.mjs +1 -1
- package/src/web.mjs +353 -60
- package/src/work.mjs +487 -0
- package/src/worker.mjs +7 -1
package/src/route.mjs
ADDED
|
@@ -0,0 +1,263 @@
|
|
|
1
|
+
// dibs who knows <path or words>: which other agent to ask, from what dibs already knows. No
|
|
2
|
+
// model reads anything: the answer is the agents' own tool calls (src/about.mjs reads which files
|
|
3
|
+
// each edited and read from Claude Code's transcripts), their file leases now and lately, their
|
|
4
|
+
// dibs runs, their progress tasks, and their session's title, first prompt and branch. Each
|
|
5
|
+
// match is weighed by kind and by how long ago it happened, and an agent that can hear a message
|
|
6
|
+
// soon (listening, or working) ranks above one that's idle; one whose session ended last.
|
|
7
|
+
//
|
|
8
|
+
// dibs tell --who-knows <path or words> "..." sends to the best one that's still running, so
|
|
9
|
+
// agents ask each other first and bring the person only what can't be undone.
|
|
10
|
+
//
|
|
11
|
+
// Read without any lock: every source is appended to, or replaced by rename.
|
|
12
|
+
import fs from 'node:fs';
|
|
13
|
+
import path from 'node:path';
|
|
14
|
+
import { loadConfig } from './config.mjs';
|
|
15
|
+
import { readEvents } from './events.mjs';
|
|
16
|
+
import { read as readPosts, tasks as progressTasks } from './progress.mjs';
|
|
17
|
+
import { threadsJson, listening } from './talk.mjs';
|
|
18
|
+
import { about, touched } from './about.mjs';
|
|
19
|
+
import { sessionFiles, makeAlive, identity } from './proc.mjs';
|
|
20
|
+
import { peek } from './state.mjs';
|
|
21
|
+
import { FILES, isFiles, fileRes, overlap, short, gitRoot, projectKey } from './files.mjs';
|
|
22
|
+
import { named, minutes } from './plain.mjs';
|
|
23
|
+
import { die, now, masked } from './util.mjs';
|
|
24
|
+
import { bold, dim } from './style.mjs';
|
|
25
|
+
|
|
26
|
+
const MAIN = 'main';
|
|
27
|
+
// Edits, reads and posts this old still count. Runs and leases a week back, since "who ran the
|
|
28
|
+
// iOS build last" may mean days ago; their weight has halved many times by then.
|
|
29
|
+
const RECENT = 24 * 36e5;
|
|
30
|
+
const RUNS_BACK = 7 * 864e5;
|
|
31
|
+
// Something that happened this long ago counts half as much as something happening now.
|
|
32
|
+
const HALF_LIFE = 3 * 36e5;
|
|
33
|
+
// How much one match says about knowing it. Holding a lease or running a job now says most;
|
|
34
|
+
// having read a file, or having been asked about it in the session's first prompt, says least.
|
|
35
|
+
const WEIGHT = { lease: 6, running: 4, edited: 4, held: 3, task: 3, title: 3, ran: 2.5, branch: 2, read: 1.5, asked: 1.5, project: 1 };
|
|
36
|
+
// How soon a message would reach it (src/talk.mjs reacher): a match that can't answer soon ranks lower.
|
|
37
|
+
const REACH = { listening: 1.25, working: 1, command: 0.9, idle: 0.7, ended: 0.2, unknown: 0.2 };
|
|
38
|
+
const REACH_WORDS = { listening: 'listening', working: 'working', command: 'outside Claude Code (hears with its next dibs command)',
|
|
39
|
+
idle: "idle and not listening (hears when it next works)", ended: 'its session has ended', unknown: "dibs can't reach it by name" };
|
|
40
|
+
// The plain list shows this many; --all shows every match.
|
|
41
|
+
const SHOWN = 5;
|
|
42
|
+
// Words that say what kind of question it is, not what it's about.
|
|
43
|
+
const STOP = new Set(['who', 'whos', 'what', 'which', 'is', 'are', 'was', 'were', 'the', 'an', 'on', 'in', 'of', 'for', 'to', 'at', 'by', 'it',
|
|
44
|
+
'knows', 'know', 'about', 'working', 'works', 'work', 'worked', 'ran', 'run', 'runs', 'running', 'last', 'did', 'does', 'do', 'has', 'have',
|
|
45
|
+
'had', 'with', 'me', 'my', 'and', 'or', 'recently', 'lately', 'latest', 'touched', 'edited', 'changed', 'owns', 'any', 'anyone', 'someone', 'stuff', 'thing', 'things', 'code', 'part']);
|
|
46
|
+
// What the built-in resources are for, in the words agents ask with ("who ran the iOS build").
|
|
47
|
+
const RES_WORDS = { 'xcode-build': 'xcode build ios macos iphone swift app', sim: 'simulator ios iphone app', 'sim-own': 'simulator ios iphone app',
|
|
48
|
+
playwright: 'playwright browser web e2e', test: 'tests suite', deploy: 'deploy ship release', heavy: 'heavy' };
|
|
49
|
+
|
|
50
|
+
const FOLD = ['darwin', 'win32'].includes(process.platform);
|
|
51
|
+
const fold = s => (FOLD ? s.toLowerCase() : s);
|
|
52
|
+
const tokens = s => String(s || '').toLowerCase().split(/[^a-z0-9]+/).filter(Boolean);
|
|
53
|
+
|
|
54
|
+
// The question, read once: a path or glob when it looks like one, else the words that matter.
|
|
55
|
+
export function question(text, cwd = process.cwd()) {
|
|
56
|
+
const q = text.trim();
|
|
57
|
+
const root = gitRoot(cwd) || cwd;
|
|
58
|
+
const pathy = !/\s/.test(q) && (/[/*?]/.test(q) || /\.\w+$/.test(q) || q.startsWith('~') || fs.existsSync(path.resolve(root, q)));
|
|
59
|
+
if (pathy) {
|
|
60
|
+
const rel = q.replace(/^\.\//, '').replace(/\/+$/, '');
|
|
61
|
+
// A relative path also matches the same place in any other project: an agent asking about
|
|
62
|
+
// src/payments from another repo, or about a file name alone, still finds who edited it.
|
|
63
|
+
const tail = /^[~/.]|[*?]/.test(rel) ? null : fold(rel);
|
|
64
|
+
return { kind: 'path', text: q, res: fileRes(FILES + q, cwd), tail };
|
|
65
|
+
}
|
|
66
|
+
const words = [...new Set(tokens(q).filter(w => w.length > 1 && !STOP.has(w)))];
|
|
67
|
+
return { kind: 'words', text: q, words };
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
// Does the absolute path p fall under the question's path?
|
|
71
|
+
function onPath(q, p) {
|
|
72
|
+
if (!p) return false;
|
|
73
|
+
const bare = p.replace(/\/\*\*?$/, '');
|
|
74
|
+
if (q.res && overlap(q.res, FILES + p)) return true;
|
|
75
|
+
return !!q.tail && `${fold(bare)}/`.includes(`/${q.tail}/`);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// Does text hold the question's words? One or two words: all of them; more: two in three.
|
|
79
|
+
// A word matches the start of one in the text (payment, payments), or anywhere in a long one (build, xcodebuild).
|
|
80
|
+
function hasWords(q, text) {
|
|
81
|
+
if (!q.words.length) return false;
|
|
82
|
+
const have = tokens(text);
|
|
83
|
+
const got = q.words.filter(w => have.some(h => h.startsWith(w) || (w.length >= 4 && h.includes(w)))).length;
|
|
84
|
+
return got >= (q.words.length <= 2 ? q.words.length : Math.ceil(q.words.length * 2 / 3));
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
const matches = (q, p) => (q.kind === 'path' ? onPath(q, p) : hasWords(q, p));
|
|
88
|
+
|
|
89
|
+
// Every agent dibs knows of: each thread (what dibs tell reaches), and each Claude Code session
|
|
90
|
+
// running here that has no thread yet. { name, session, agentId, reach, about }.
|
|
91
|
+
function agents(t) {
|
|
92
|
+
const list = threadsJson(t, null, { described: true }).threads
|
|
93
|
+
.map(th => ({ name: th.to, session: th.session || null, agentId: th.agentId || MAIN, reach: th.reach || 'unknown', about: th.about || {} }));
|
|
94
|
+
const files = sessionFiles();
|
|
95
|
+
const up = makeAlive(files.map(f => f.pid));
|
|
96
|
+
const on = listening();
|
|
97
|
+
for (const f of files.sort((a, b) => b.updated - a.updated)) {
|
|
98
|
+
// A session without a name can't be told anything by name; one already listed is its thread.
|
|
99
|
+
if (!f.name || list.some(a => a.session === f.sessionId && a.agentId === MAIN)) continue;
|
|
100
|
+
const reach = !up(f.pid) ? 'ended' : on.has(`${f.sessionId}|${MAIN}`) ? 'listening' : f.status === 'idle' ? 'idle' : 'working';
|
|
101
|
+
list.push({ name: f.name, session: f.sessionId, agentId: MAIN, reach, about: about(f.sessionId, MAIN) || {} });
|
|
102
|
+
}
|
|
103
|
+
return list;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
const ago = (t, at) => (t - at < 6e4 ? 'just now' : `${minutes(t - at)} ago`);
|
|
107
|
+
const cut = (s, n) => { s = String(s).replace(/\s+/g, ' ').trim(); return s.length > n ? `${s.slice(0, n - 3).trimEnd()}...` : s; };
|
|
108
|
+
const shown = (p, cwd) => short(FILES + p, cwd).slice(FILES.length);
|
|
109
|
+
const what = x => (x.purpose ? `"${cut(x.purpose, 60)}"` : x.cmd ? `"${cut(masked(String(x.cmd)), 60)}"` : '');
|
|
110
|
+
|
|
111
|
+
// The ranked matches for question q, best first: [{ name, reach, score, why: [{ kind, text, at }],
|
|
112
|
+
// branch, project, title }]. me: the caller's name and session, left out. Pure over its inputs
|
|
113
|
+
// but for the files it reads to compare paths, so tests can hand in what they need.
|
|
114
|
+
export function rank(q, { agents: list, leases = [], events = [], posts = [], touches = new Map(), me = {}, cwd = process.cwd(), cfg = {}, t = now() }) {
|
|
115
|
+
const found = new Map();
|
|
116
|
+
const bySession = new Map(list.map(a => [`${a.session}|${a.agentId}`, a]));
|
|
117
|
+
const byName = new Map();
|
|
118
|
+
for (const a of list) if (!byName.has(a.name) || a.agentId === MAIN) byName.set(a.name, a);
|
|
119
|
+
// Who did it: the agent by session (and subagent, while it runs), else by the name it ran under.
|
|
120
|
+
const whose = ({ session, agentId, who }) => {
|
|
121
|
+
const sub = session && agentId && agentId !== MAIN && bySession.get(`${session}|${agentId}`);
|
|
122
|
+
if (sub && sub.reach !== 'ended') return { a: sub };
|
|
123
|
+
const lead = session && bySession.get(`${session}|${MAIN}`);
|
|
124
|
+
if (lead) return { a: lead, viaSub: !!sub || (!!agentId && agentId !== MAIN) };
|
|
125
|
+
if (!who) return null;
|
|
126
|
+
if (!byName.has(who)) byName.set(who, { name: who, session: null, agentId: MAIN, reach: 'unknown', about: {} });
|
|
127
|
+
return { a: byName.get(who) };
|
|
128
|
+
};
|
|
129
|
+
const add = (owner, kind, text, at = null) => {
|
|
130
|
+
if (!owner) return;
|
|
131
|
+
const { a, viaSub } = owner;
|
|
132
|
+
if (a.name === me.name || (me.session && a.session === me.session)) return;
|
|
133
|
+
let f = found.get(a);
|
|
134
|
+
if (!f) found.set(a, f = { a, ev: [] });
|
|
135
|
+
f.ev.push({ kind, text: viaSub ? `${text} (through a subagent)` : text, at, w: WEIGHT[kind] * (at ? 0.5 ** (Math.max(0, t - at) / HALF_LIFE) : 1) });
|
|
136
|
+
};
|
|
137
|
+
const resText = r => `${r} ${isFiles(r) ? '' : `${named(cfg, r).label} ${RES_WORDS[r] || ''}`}`;
|
|
138
|
+
|
|
139
|
+
for (const l of leases) {
|
|
140
|
+
const owner = whose({ session: l.sessionId, agentId: l.agentId, who: l.who });
|
|
141
|
+
const files = l.res.filter(isFiles);
|
|
142
|
+
const onFiles = q.kind === 'path' ? files.some(r => onPath(q, r.slice(FILES.length))) : files.length && hasWords(q, `${files.join(' ')} ${l.purpose || ''}`);
|
|
143
|
+
if (onFiles) add(owner, 'lease', `holds ${files.map(r => shown(r.slice(FILES.length), cwd)).join(', ')} now`);
|
|
144
|
+
else if (l.kind === 'run' && q.kind === 'words' && hasWords(q, `${l.res.map(resText).join(' ')} ${l.cmd || ''} ${l.purpose || ''}`))
|
|
145
|
+
add(owner, 'running', `is running ${l.res.join(',')} ${what(l)} now`.trim());
|
|
146
|
+
}
|
|
147
|
+
const live = new Set(leases.map(l => l.id));
|
|
148
|
+
for (const e of events) {
|
|
149
|
+
if (t - e.at > RUNS_BACK || live.has(e.id) || !Array.isArray(e.res)) continue;
|
|
150
|
+
const owner = () => whose({ who: e.who });
|
|
151
|
+
const files = e.res.filter(isFiles);
|
|
152
|
+
if (e.kind === 'start' && files.length && files.some(r => matches(q, r.slice(FILES.length))))
|
|
153
|
+
add(owner(), 'held', `held ${files.map(r => shown(r.slice(FILES.length), cwd)).join(', ')} ${ago(t, e.at)}`, e.at);
|
|
154
|
+
else if (e.kind === 'end' && e.type === 'run' && q.kind === 'words' && hasWords(q, `${e.res.map(resText).join(' ')} ${e.cmd || ''} ${e.purpose || ''}`))
|
|
155
|
+
add(owner(), 'ran', `ran ${e.res.join(',')} ${what(e)} ${ago(t, e.at)}${e.code ? ` (exit ${e.code})` : ''}`.replace(/ +/g, ' '), e.at);
|
|
156
|
+
}
|
|
157
|
+
for (const k of progressTasks(posts, t)) {
|
|
158
|
+
if (k.state === 'expired') continue;
|
|
159
|
+
const said = `${k.task || ''} ${k.text}`;
|
|
160
|
+
const hit = q.kind === 'words' ? hasWords(q, said) : (q.tail && fold(said).includes(q.tail)) || (q.res && said.includes(q.res.slice(FILES.length)));
|
|
161
|
+
if (hit) add(whose({ session: k.session, agentId: k.agentId, who: k.who }), 'task', `${k.state === 'done' ? 'finished' : 'is on'} task ${k.task || '(untitled)'}: "${cut(k.text, 80)}"`, k.last);
|
|
162
|
+
}
|
|
163
|
+
// A path inside a git project: an agent working in that project knows a little about it.
|
|
164
|
+
const dir = q.kind === 'path' && q.res && !/[*?]/.test(q.res) ? path.dirname(q.res.slice(FILES.length)) : null;
|
|
165
|
+
const project = dir && gitRoot(dir) ? projectKey(dir) : null;
|
|
166
|
+
for (const [a, x] of touches) {
|
|
167
|
+
for (const f of x.files) {
|
|
168
|
+
if (!matches(q, f.path)) continue;
|
|
169
|
+
add(whose({ session: a.session, agentId: f.agentId, who: a.name }), f.how, `${f.how} ${shown(f.path, cwd)} ${ago(t, f.at)}`, f.at);
|
|
170
|
+
}
|
|
171
|
+
if (project && x.cwd && projectKey(x.cwd) === project) add({ a }, 'project', `works in ${path.basename(x.cwd)}`);
|
|
172
|
+
}
|
|
173
|
+
if (q.kind === 'words') {
|
|
174
|
+
for (const a of list) {
|
|
175
|
+
const ab = a.about || {};
|
|
176
|
+
if (ab.title && hasWords(q, ab.title)) add({ a }, 'title', `has a session titled "${cut(ab.title, 70)}"`);
|
|
177
|
+
else if (ab.brief && hasWords(q, ab.brief)) add({ a }, 'title', `was given "${cut(ab.brief, 70)}"`);
|
|
178
|
+
if (ab.branch && hasWords(q, ab.branch)) add({ a }, 'branch', `is on branch ${ab.branch}`);
|
|
179
|
+
if (ab.asked && hasWords(q, ab.asked)) add({ a }, 'asked', `was asked "${cut(ab.asked, 70)}"`);
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
const out = [];
|
|
184
|
+
for (const { a, ev } of found.values()) {
|
|
185
|
+
// The best match of each kind counts in full; more of the same (fifty edits) adds a little.
|
|
186
|
+
const best = new Map();
|
|
187
|
+
for (const e of ev) if (!best.has(e.kind) || e.w > best.get(e.kind).w) best.set(e.kind, e);
|
|
188
|
+
const known = [...best.values()].reduce((n, e) => n + e.w, 0) + Math.min(ev.length - best.size, 20) * 0.05;
|
|
189
|
+
const why = [...best.values()].sort((x, y) => y.w - x.w).map(({ kind, text, at }) => ({ kind, text, ...(at && { at }) }));
|
|
190
|
+
out.push({ name: a.name, reach: a.reach, score: Math.round(known * (REACH[a.reach] ?? 0.2) * 100) / 100, why,
|
|
191
|
+
...(a.about?.project && { project: a.about.project }), ...(a.about?.branch && { branch: a.about.branch }), ...(a.about?.title && { title: a.about.title }) });
|
|
192
|
+
}
|
|
193
|
+
return out.sort((x, y) => y.score - x.score);
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
// Everything rank needs, read from this machine. cwd: where relative paths start.
|
|
197
|
+
export function lookup(text, { cwd = process.cwd(), t = now() } = {}) {
|
|
198
|
+
const q = question(text, cwd);
|
|
199
|
+
if (q.kind === 'words' && !q.words.length) return { q, found: [] };
|
|
200
|
+
const list = agents(t);
|
|
201
|
+
const touches = new Map();
|
|
202
|
+
for (const a of list) {
|
|
203
|
+
if (!a.session || a.agentId !== MAIN) continue;
|
|
204
|
+
const x = touched(a.session, t - RECENT);
|
|
205
|
+
if (x) touches.set(a, x);
|
|
206
|
+
}
|
|
207
|
+
const id = identity();
|
|
208
|
+
const me = { name: id.agent || id.who, session: process.env.CLAUDE_CODE_SESSION_ID || sessionFiles().find(f => f.pid === id.spid)?.sessionId || null };
|
|
209
|
+
const st = peek();
|
|
210
|
+
const up = makeAlive(st.leases.map(l => l.pid).filter(Boolean));
|
|
211
|
+
const leases = st.leases.filter(l => Array.isArray(l.res) && (l.kind !== 'hold' || !l.expires || t < l.expires) && (!l.pid || up(l.pid)));
|
|
212
|
+
const found = rank(q, { agents: list, leases, events: readEvents(t).filter(e => t - e.at <= RUNS_BACK), posts: readPosts({ since: t - RECENT }),
|
|
213
|
+
touches, me, cwd, cfg: loadConfig(), t });
|
|
214
|
+
return { q, found };
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
// One match as a line: "web-app: edited src/payments/charge.ts 12 min ago, on branch fix-refunds, listening".
|
|
218
|
+
export function line(m, n = 3) {
|
|
219
|
+
const said = m.why.slice(0, n).map(w => w.text);
|
|
220
|
+
if (m.branch && !m.why.some(w => w.kind === 'branch')) said.push(`on branch ${m.branch}`);
|
|
221
|
+
said.push(REACH_WORDS[m.reach] || m.reach);
|
|
222
|
+
return `${m.name}: ${said.join(', ')}`;
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
// The match a message should go to: the best one dibs tell can reach and that's still running.
|
|
226
|
+
export const reachable = m => m.reach !== 'ended' && m.reach !== 'unknown';
|
|
227
|
+
|
|
228
|
+
const nothing = q => `nobody here has edited, held, run or posted about ${q.kind === 'path' ? q.text : `"${q.text}"`} lately (exit 1: nothing matched).`
|
|
229
|
+
+ ' Look for yourself, or ask the person if the next step can\'t be undone: dibs question "..." --one-way "..."';
|
|
230
|
+
|
|
231
|
+
// dibs who knows <path or words> [--all] [--json]
|
|
232
|
+
export function whoKnows(args) {
|
|
233
|
+
const json = args.includes('--json'), all = args.includes('--all');
|
|
234
|
+
const bad = args.find(a => a.startsWith('-') && a !== '--json' && a !== '--all');
|
|
235
|
+
if (bad) die(`unknown flag ${bad}. Try: dibs who knows src/payments, or dibs who knows "the login page"`);
|
|
236
|
+
const text = args.filter(a => a !== '--json' && a !== '--all').join(' ').trim();
|
|
237
|
+
if (!text) die('who knows what? dibs who knows src/payments, dibs who knows "the login page", dibs who knows "iOS build"');
|
|
238
|
+
const { q, found } = lookup(text);
|
|
239
|
+
if (json) {
|
|
240
|
+
console.log(JSON.stringify({ query: text, kind: q.kind, agents: found }, null, 1));
|
|
241
|
+
if (!found.length) process.exitCode = 1;
|
|
242
|
+
return;
|
|
243
|
+
}
|
|
244
|
+
if (!found.length) die(nothing(q), 1);
|
|
245
|
+
const list = all ? found : found.slice(0, SHOWN);
|
|
246
|
+
console.log(bold(`Who knows ${q.kind === 'path' ? q.text : `"${q.text}"`}, best first:`));
|
|
247
|
+
for (const m of list) console.log(` ${line(m)}`);
|
|
248
|
+
if (found.length > list.length) console.log(dim(` ${found.length - list.length} more: dibs who knows ${args.join(' ')} --all`));
|
|
249
|
+
const best = found.find(reachable);
|
|
250
|
+
console.log(dim(best ? `Ask the best one still running: dibs tell --who-knows ${shellWord(text)} "..." --wait 5m (it goes to ${best.name})`
|
|
251
|
+
: 'None of them is running now, so nobody can answer. Look for yourself, or ask the person if it can\'t be undone.'));
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
const shellWord = s => (/^[\w.,/@:=+-]+$/.test(s) ? s : `'${s.replace(/'/g, "'\\''")}'`);
|
|
255
|
+
|
|
256
|
+
// For dibs tell --who-knows: { to, line } for the agent to send to, or exits 1 naming who else matched.
|
|
257
|
+
export function pick(text) {
|
|
258
|
+
const { q, found } = lookup(text);
|
|
259
|
+
const best = found.find(reachable);
|
|
260
|
+
if (best) return { to: best.name, line: line(best), why: best.why[0]?.text || '' };
|
|
261
|
+
if (!found.length) die(`${nothing(q)} Nothing was sent.`, 1);
|
|
262
|
+
die(`only agents that aren't running now match ${q.kind === 'path' ? q.text : `"${q.text}"`} (exit 1: nothing matched): ${found.slice(0, 3).map(m => line(m, 1)).join('; ')}. Nothing was sent.`, 1);
|
|
263
|
+
}
|
package/src/rules.mjs
ADDED
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
// Standing rules: the person answers a kind of question once, and dibs answers it the same way
|
|
2
|
+
// every time after. "Always yes to TestFlight uploads", "never deploy to production after 18:00",
|
|
3
|
+
// "no to deleting simulators other than dibs-pool".
|
|
4
|
+
//
|
|
5
|
+
// Matching is plain and can be explained in a line: no model reads the question. A rule covers
|
|
6
|
+
// questions asked with its --about (a kind the asker names, like testflight or deploy), and then
|
|
7
|
+
// only if every --if word is in the question itself, no --unless word is anywhere in it, and the
|
|
8
|
+
// clock is inside its --between. Two rules that both cover a question and disagree answer neither:
|
|
9
|
+
// the question goes on as if there were no rules. A --needs-you question (a login, a code on the
|
|
10
|
+
// person's phone) never gets a rule's answer: no answer does what only the person can.
|
|
11
|
+
//
|
|
12
|
+
// Rules keep their own file and lock, as questions do. dibs question reads the file without the
|
|
13
|
+
// lock (writes are renames) and takes the lock only to count a rule's use.
|
|
14
|
+
import fs from 'node:fs';
|
|
15
|
+
import path from 'node:path';
|
|
16
|
+
import { HOME } from './config.mjs';
|
|
17
|
+
import { actor, logChange } from './owner.mjs';
|
|
18
|
+
import { underLock, commit } from './lock.mjs';
|
|
19
|
+
import { clock, die, dur, now, say, fakeFull } from './util.mjs';
|
|
20
|
+
import { bold, dim, amber, wrap } from './style.mjs';
|
|
21
|
+
import { readJSON } from './durable.mjs';
|
|
22
|
+
|
|
23
|
+
const FILE = path.join(HOME, 'rules.json');
|
|
24
|
+
const LOCK = path.join(HOME, 'rules.lock');
|
|
25
|
+
// Writes take milliseconds: a live holder past this is stuck on something else, and the caller hears so.
|
|
26
|
+
const LOCK_WAIT = 15e3;
|
|
27
|
+
// A kind of question: short enough to type, plain enough to match exactly.
|
|
28
|
+
export const ABOUT = /^[a-z0-9][a-z0-9._-]{0,39}$/;
|
|
29
|
+
// Enough to stop a typo'd loop from making thousands; far more than a person keeps in their head.
|
|
30
|
+
const MOST = 200;
|
|
31
|
+
|
|
32
|
+
function locked(fn) {
|
|
33
|
+
const r = underLock(LOCK, h => {
|
|
34
|
+
const s = load();
|
|
35
|
+
const before = JSON.stringify(s);
|
|
36
|
+
const out = fn(s);
|
|
37
|
+
if (JSON.stringify(s) !== before) commit(h, FILE, JSON.stringify(s, null, 1), { fake: () => fakeFull('state') });
|
|
38
|
+
return out;
|
|
39
|
+
}, { wait: LOCK_WAIT, files: [FILE] });
|
|
40
|
+
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);
|
|
41
|
+
return r.out;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function load() {
|
|
45
|
+
let s = {};
|
|
46
|
+
try { s = readJSON(FILE); } catch (e) {
|
|
47
|
+
if (e.code !== 'ENOENT') say(`${FILE} was unreadable (${e.message}); no rule answers anything until it's fixed or removed.`);
|
|
48
|
+
}
|
|
49
|
+
s.seq ||= 0; s.rules ||= [];
|
|
50
|
+
return s;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// Every rule, read without the lock.
|
|
54
|
+
export const readRules = () => load().rules;
|
|
55
|
+
|
|
56
|
+
// "18:00" -> minutes since midnight, or null.
|
|
57
|
+
function readTime(hhmm) {
|
|
58
|
+
const m = String(hhmm).match(/^(\d{1,2}):(\d{2})$/);
|
|
59
|
+
return m && Number(m[1]) <= 23 && Number(m[2]) <= 59 ? Number(m[1]) * 60 + Number(m[2]) : null;
|
|
60
|
+
}
|
|
61
|
+
// Inside start-end on the clock; an end before the start runs past midnight, as dibs hours does.
|
|
62
|
+
function inside(w, t) {
|
|
63
|
+
const d = new Date(t), at = d.getHours() * 60 + d.getMinutes();
|
|
64
|
+
const a = readTime(w.start), b = readTime(w.end);
|
|
65
|
+
return a <= b ? at >= a && at < b : at >= a || at < b;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
const lower = s => String(s ?? '').toLowerCase();
|
|
69
|
+
const escape = s => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
70
|
+
// A whole word or phrase: "upload" is in "upload build 12", not in "uploads" or "reupload".
|
|
71
|
+
const hasWord = (text, w) => new RegExp(`(^|[^\\p{L}\\p{N}])${escape(lower(w))}($|[^\\p{L}\\p{N}])`, 'u').test(lower(text));
|
|
72
|
+
|
|
73
|
+
// Why this rule doesn't answer this question, or null when it does. q: { about, text, purpose,
|
|
74
|
+
// cantUndo, needsYou, options }.
|
|
75
|
+
export function misses(rule, q, t = now()) {
|
|
76
|
+
if (rule.about !== q.about) return `it's about ${rule.about}, the question is about ${q.about || 'nothing (no --about)'}`;
|
|
77
|
+
// An agent may set a rule, but only the person's own rules answer what can't be undone.
|
|
78
|
+
if (rule.byAgent && q.cantUndo != null) return `${rule.by}, an agent, set it, and an agent's rule answers only what can be undone: this is a one-way door, so it goes to the person`;
|
|
79
|
+
// --if words must be in what's asked: the question and what can't be undone.
|
|
80
|
+
const asked = `${q.text} ${q.cantUndo || ''}`;
|
|
81
|
+
const absent = (rule.if || []).filter(w => !hasWord(asked, w));
|
|
82
|
+
if (absent.length) return `the question doesn't say ${absent.map(w => `"${w}"`).join(' or ')}`;
|
|
83
|
+
// --unless words count anywhere, the asker's reasons too: when in doubt, the rule steps aside.
|
|
84
|
+
const all = lower([q.text, q.purpose, q.cantUndo, q.needsYou, ...(q.options || [])].filter(Boolean).join(' '));
|
|
85
|
+
const present = (rule.unless || []).filter(w => all.includes(lower(w)));
|
|
86
|
+
if (present.length) return `the question mentions ${present.map(w => `"${w}"`).join(' and ')}`;
|
|
87
|
+
if (rule.between && !inside(rule.between, t)) return `it's ${clock(t)}, outside ${rule.between.start}-${rule.between.end}`;
|
|
88
|
+
if (q.options && !q.options.some(o => lower(o) === lower(rule.answer))) return `its answer, ${rule.answer}, isn't one of the options (${q.options.join(', ')})`;
|
|
89
|
+
return null;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
// What the rules say about a question: { rule, answer } when exactly one answer comes from them,
|
|
93
|
+
// { clash: [rules] } when rules that cover it disagree, else { none, near } with the rules about
|
|
94
|
+
// the same kind and why each stepped aside.
|
|
95
|
+
export function ruleFor(q, list = readRules(), t = now()) {
|
|
96
|
+
if (!q.about) return { none: 'it has no --about, so no rule covers it', near: [] };
|
|
97
|
+
const same = list.filter(r => r.about === q.about);
|
|
98
|
+
const hits = same.filter(r => !misses(r, q, t));
|
|
99
|
+
const near = same.filter(r => misses(r, q, t)).map(r => ({ rule: r, why: misses(r, q, t) }));
|
|
100
|
+
if (q.needsYou != null) return { none: 'it needs the person to do something, and no rule can', near };
|
|
101
|
+
if (!hits.length) return { none: same.length ? `no rule about ${q.about} covers it` : `there are no rules about ${q.about}`, near };
|
|
102
|
+
const answers = new Set(hits.map(r => lower(r.answer)));
|
|
103
|
+
if (answers.size > 1) return { clash: hits, near };
|
|
104
|
+
// The most particular rule explains it best: the one with the most conditions.
|
|
105
|
+
const conds = r => (r.if || []).length + (r.unless || []).length + (r.between ? 1 : 0);
|
|
106
|
+
const rule = [...hits].sort((a, b) => conds(b) - conds(a))[0];
|
|
107
|
+
return { rule, answer: q.options?.find(o => lower(o) === lower(rule.answer)) ?? rule.answer, near };
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
// What a rule says, in a line: "about testflight, if it says upload: yes".
|
|
111
|
+
export function describeRule(r) {
|
|
112
|
+
const when = [
|
|
113
|
+
r.if?.length && `if it says ${r.if.map(w => `"${w}"`).join(' and ')}`,
|
|
114
|
+
r.unless?.length && `unless it mentions ${r.unless.map(w => `"${w}"`).join(' or ')}`,
|
|
115
|
+
r.between && (r.between.end === '00:00' ? `after ${r.between.start}` : r.between.start === '00:00' ? `before ${r.between.end}` : `between ${r.between.start} and ${r.between.end}`),
|
|
116
|
+
].filter(Boolean).join(', ');
|
|
117
|
+
return `about ${r.about}${when ? `, ${when}` : ''}: ${r.answer}`;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
// A rule answered question qid: counted on the rule, for the list. Best effort: the answer
|
|
121
|
+
// already stands, and a lost count is no reason to fail the asker.
|
|
122
|
+
export function noteHit(id, qid, t = now()) {
|
|
123
|
+
try { locked(s => { const r = s.rules.find(x => x.id === id); if (r) Object.assign(r, { hits: (r.hits || 0) + 1, lastAt: t, lastQuestion: qid }); }); } catch {}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
const shown = r => ({ id: r.id, about: r.about, answer: r.answer, if: r.if || [], unless: r.unless || [], between: r.between || null, why: r.why || null,
|
|
127
|
+
by: r.by, byAgent: !!r.byAgent, at: r.at, hits: r.hits || 0, lastAt: r.lastAt || null, lastQuestion: r.lastQuestion ?? null, says: describeRule(r) });
|
|
128
|
+
export const rulesJson = () => ({ rules: readRules().map(shown) });
|
|
129
|
+
|
|
130
|
+
// Which questions a rule covers, whatever it answers: two rules with the same conditions only ever clash.
|
|
131
|
+
const conditions = r => JSON.stringify([r.about, (r.if || []).map(lower).sort(), (r.unless || []).map(lower).sort(), r.between || null]);
|
|
132
|
+
const words = v => v.split(',').map(x => x.trim()).filter(Boolean);
|
|
133
|
+
const USE = 'dibs rules add --about testflight --answer yes [--if upload] [--unless production] [--between 18:00-08:00] -m "why"';
|
|
134
|
+
|
|
135
|
+
function parseAdd(args) {
|
|
136
|
+
const o = { if: [], unless: [] };
|
|
137
|
+
for (let i = 0; i < args.length; i++) {
|
|
138
|
+
const a = args[i], next = () => args[++i] ?? die(`${a} needs a value. ${USE}`);
|
|
139
|
+
if (a === '--about') o.about = lower(next().trim());
|
|
140
|
+
else if (a === '--answer') o.answer = next().trim();
|
|
141
|
+
else if (a === '--if') o.if.push(...words(next()));
|
|
142
|
+
else if (a === '--unless') o.unless.push(...words(next()));
|
|
143
|
+
else if (a === '--between') o.between = next();
|
|
144
|
+
else if (a === '--after') o.between = `${next()}-00:00`;
|
|
145
|
+
else if (a === '--before') o.between = `00:00-${next()}`;
|
|
146
|
+
else if (a === '-m' || a === '--msg') o.why = next().trim();
|
|
147
|
+
else die(`unknown ${a.startsWith('-') ? 'flag' : 'word'} ${a}. ${USE}`);
|
|
148
|
+
}
|
|
149
|
+
if (!o.about || !ABOUT.test(o.about)) die(`a rule needs --about: the kind of question it answers, in lowercase letters, digits and dashes (testflight, deploy, simulators). Nothing was added. ${USE}`);
|
|
150
|
+
if (!o.answer) die(`a rule needs --answer: what it says every time (yes, no, or an option). Nothing was added. ${USE}`);
|
|
151
|
+
if (o.between != null) {
|
|
152
|
+
const [start, end, extra] = String(o.between).split('-');
|
|
153
|
+
if (extra != null || readTime(start) == null || readTime(end) == null || readTime(start) === readTime(end))
|
|
154
|
+
die(`can't read --between ${o.between}. Use 18:00-08:00 (an end before the start runs past midnight), --after 18:00 or --before 09:00. Nothing was added.`);
|
|
155
|
+
o.between = { start: start.padStart(5, '0'), end: end.padStart(5, '0') };
|
|
156
|
+
}
|
|
157
|
+
return o;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
// dibs rules [--json] | add ... | test "question" --about x [...] | remove <id>
|
|
161
|
+
export async function rulesCmd(args) {
|
|
162
|
+
const [verb, ...rest] = args;
|
|
163
|
+
if (verb === 'add') return add(rest);
|
|
164
|
+
if (verb === 'remove' || verb === 'rm') return remove(rest);
|
|
165
|
+
if (verb === 'test') return (await import('./questions.mjs')).testRule(rest);
|
|
166
|
+
if (verb && verb !== '--json') die(`dibs rules takes add, test, remove or --json, not ${verb}. ${USE}`);
|
|
167
|
+
if (rest.length) die(`unknown ${rest[0]}. Try: dibs rules [--json]`);
|
|
168
|
+
if (verb === '--json') return console.log(JSON.stringify(rulesJson(), null, 1));
|
|
169
|
+
const list = readRules(), t = now();
|
|
170
|
+
if (!list.length) return console.log(`No standing rules: every question goes the usual way. Add one: ${USE}`);
|
|
171
|
+
const out = [bold(`${list.length} standing rule${list.length > 1 ? 's' : ''}. A question asked with the same --about gets its answer at once.`)];
|
|
172
|
+
for (const r of list) {
|
|
173
|
+
out.push('', ` ${r.id} ${describeRule(r)}`);
|
|
174
|
+
if (r.why) out.push(dim(wrap(` ${r.why}`, ' ')));
|
|
175
|
+
const used = r.hits ? `answered ${r.hits} question${r.hits > 1 ? 's' : ''}, last #${r.lastQuestion} ${dur(t - r.lastAt)} ago` : 'not used yet';
|
|
176
|
+
out.push(dim(` set by ${r.by} ${dur(t - r.at)} ago; ${used}`));
|
|
177
|
+
if (r.byAgent) out.push(amber(' set by an agent, not the person'));
|
|
178
|
+
}
|
|
179
|
+
out.push('', `Remove one: dibs rules remove ${list[0].id} Try one: dibs rules test "Upload build 12 to TestFlight?" --about ${list[0].about}`);
|
|
180
|
+
console.log(out.join('\n'));
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
function add(args) {
|
|
184
|
+
const o = parseAdd(args);
|
|
185
|
+
const who = actor();
|
|
186
|
+
const r = locked(s => {
|
|
187
|
+
if (s.rules.length >= MOST) return { full: true };
|
|
188
|
+
const same = s.rules.find(x => conditions(x) === conditions(o));
|
|
189
|
+
if (same && lower(same.answer) === lower(o.answer)) return { rule: { ...same }, again: true };
|
|
190
|
+
const rule = { id: `r${++s.seq}`, about: o.about, answer: o.answer, ...(o.if.length && { if: o.if }), ...(o.unless.length && { unless: o.unless }),
|
|
191
|
+
...(o.between && { between: o.between }), ...(o.why && { why: o.why }), by: who.name, ...(who.agent && { byAgent: true }), ...(who.via && { via: who.via }), at: now(), hits: 0 };
|
|
192
|
+
s.rules.push(rule);
|
|
193
|
+
// The same conditions with another answer: the new one replaces it.
|
|
194
|
+
const replaced = same ? s.rules.splice(s.rules.indexOf(same), 1)[0] : null;
|
|
195
|
+
return { rule: { ...rule }, replaced };
|
|
196
|
+
});
|
|
197
|
+
if (r.full) die(`there are already ${MOST} rules. Remove some first: dibs rules`, 1);
|
|
198
|
+
if (r.again) return console.log(`${r.rule.id} already says that: ${describeRule(r.rule)}. Nothing changed.`);
|
|
199
|
+
logChange('rule', { rule: r.rule.id, says: describeRule(r.rule), ...(r.replaced && { replaced: r.replaced.id }) });
|
|
200
|
+
console.log(`${r.rule.id}: ${describeRule(r.rule)}.${r.replaced ? ` It replaces ${r.replaced.id}, which answered ${r.replaced.answer} to the same questions.` : ''}`);
|
|
201
|
+
// An agent's rule answers two-way doors only (src/questions.mjs ruleFor): a one-way door of its kind still goes to the person.
|
|
202
|
+
say(`questions asked with --about ${r.rule.about} that it covers get ${r.rule.answer} at once, ${r.rule.byAgent ? "two-way doors only: one-way doors still go to the person, since an agent set it" : 'one-way doors too'}, and the person sees which rule answered.`
|
|
203
|
+
+ ` Check one: dibs rules test "..." --about ${r.rule.about}. Remove it: dibs rules remove ${r.rule.id}`);
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
function remove(args) {
|
|
207
|
+
const id = args[0];
|
|
208
|
+
if (!id || args.length > 1) die('which rule? dibs rules remove <id> (the ids: dibs rules)');
|
|
209
|
+
const r = locked(s => {
|
|
210
|
+
const i = s.rules.findIndex(x => x.id === id);
|
|
211
|
+
return i < 0 ? null : s.rules.splice(i, 1)[0];
|
|
212
|
+
});
|
|
213
|
+
if (!r) die(`no rule ${id}. See them: dibs rules`, 1);
|
|
214
|
+
logChange('rule removed', { rule: r.id, says: describeRule(r) });
|
|
215
|
+
console.log(`removed ${r.id} (${describeRule(r)}). Questions about ${r.about} go the usual way again.`);
|
|
216
|
+
}
|