@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.
- package/CHANGELOG.md +111 -1
- package/README.md +10 -8
- package/bin/dibs.mjs +379 -74
- 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 +135 -11
- 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/docs/windows.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 +113 -28
- package/src/after.mjs +127 -0
- package/src/agents.mjs +2 -1
- package/src/alerts.mjs +109 -48
- 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 +254 -86
- package/src/config.mjs +85 -14
- package/src/connect.mjs +4 -2
- package/src/cool.mjs +28 -12
- 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 +121 -7
- package/src/guard.mjs +288 -105
- 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 +51 -11
- package/src/measure.mjs +60 -14
- 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 +29 -7
- package/src/preempt.mjs +123 -15
- package/src/primer.mjs +91 -20
- package/src/prints.mjs +99 -0
- package/src/proc.mjs +11 -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 +262 -26
- 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/service.mjs +5 -1
- 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 +1082 -134
- 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 +354 -60
- package/src/work.mjs +487 -0
- package/src/worker.mjs +7 -1
package/src/reviews.mjs
ADDED
|
@@ -0,0 +1,377 @@
|
|
|
1
|
+
// dibs review: one agent asks another to look over a change before it lands, so the person isn't
|
|
2
|
+
// the only check. The author names a branch or a commit range in a repo and what to look at; dibs
|
|
3
|
+
// picks a reviewer among the agents running now (never the author's own session): one that knows
|
|
4
|
+
// the area first (dibs who knows, src/route.mjs, when this dibs has it), then one working in the
|
|
5
|
+
// same repo, then one listening, so it hears the request within seconds. The request reaches it as
|
|
6
|
+
// any message from another agent does, signed by the author, never as the person's. The reviewer
|
|
7
|
+
// answers with approve or changes and notes; the author hears the answer the same way.
|
|
8
|
+
//
|
|
9
|
+
// An approval covers the commit it was asked about. A project whose .dibs.json says
|
|
10
|
+
// "reviewBeforeMerge" gets the guard hook's check (src/reviewgate.mjs): a merge into main, or a push to it, of a
|
|
11
|
+
// commit nobody approved is turned away with the command that asks for a review.
|
|
12
|
+
//
|
|
13
|
+
// Reviews keep their own file and lock (reviews.json), like handoffs: nothing here decides who
|
|
14
|
+
// runs next. The hook reads the file without the lock; writes are renames.
|
|
15
|
+
import path from 'node:path';
|
|
16
|
+
import fs from 'node:fs';
|
|
17
|
+
import { HOME } from './config.mjs';
|
|
18
|
+
import { logChange } from './owner.mjs';
|
|
19
|
+
import { makeAlive, sessionFiles } from './proc.mjs';
|
|
20
|
+
import { whoAmI, send, messageTo, othersNow, delivery, unreachable } from './talk.mjs';
|
|
21
|
+
import { cwdOf } from './about.mjs';
|
|
22
|
+
import { underLock, commit } from './lock.mjs';
|
|
23
|
+
import { REVIEWS as FILE, git, guarded, standing, DEFAULT_INTO } from './reviewgate.mjs';
|
|
24
|
+
import { expand } from './files.mjs';
|
|
25
|
+
import { minutes } from './plain.mjs';
|
|
26
|
+
import { bold, dim, columns } from './style.mjs';
|
|
27
|
+
import { die, now, say, fakeFull } from './util.mjs';
|
|
28
|
+
import { readJSON } from './durable.mjs';
|
|
29
|
+
|
|
30
|
+
const LOCK = path.join(HOME, 'reviews.lock');
|
|
31
|
+
// Writes take milliseconds: a live holder past this is stuck on something else, and the caller hears so.
|
|
32
|
+
const LOCK_WAIT = 15e3;
|
|
33
|
+
// An open request nobody answered in a week is stale.
|
|
34
|
+
const OPEN_FOR = 7 * 864e5;
|
|
35
|
+
// Two weeks of answers: an approval has to outlast the wait for a merge, and the list stays short.
|
|
36
|
+
const KEEP_FOR = 14 * 864e5;
|
|
37
|
+
const KEEP_DONE = 300;
|
|
38
|
+
// What to look at is a few sentences, as a message is.
|
|
39
|
+
const MAX_NOTE = 4000;
|
|
40
|
+
// The changed files kept with a request, for the list and for picking who knows them.
|
|
41
|
+
const FILES_KEPT = 100;
|
|
42
|
+
// The list shows this many of the most recently answered.
|
|
43
|
+
const RECENT = 5;
|
|
44
|
+
// The board and the page show answers this recent beside the open requests.
|
|
45
|
+
const SHOWN_FOR = 864e5;
|
|
46
|
+
// A commit as a request names it: long enough to stay unique in any repo an agent works in.
|
|
47
|
+
const SHA_SHOWN = 12;
|
|
48
|
+
|
|
49
|
+
const USAGE = `dibs review request [<branch>|<from>..<to>] [-m "what to look at"] [--to <agent>] [--repo <dir>] [--pr <n>]
|
|
50
|
+
ask another agent to review a change (no branch: the one checked out, against main);
|
|
51
|
+
dibs picks one that knows the area and is running, and you hear its answer
|
|
52
|
+
dibs review approve <id> ["notes"] it's good to merge; its author hears your notes
|
|
53
|
+
dibs review changes <id> "what to change" not yet; its author hears what to change
|
|
54
|
+
dibs review cancel <id> drop a request
|
|
55
|
+
dibs review list [--all] [--json] open requests and recent answers (--all: every answer kept)
|
|
56
|
+
dibs review check [<branch>] [--repo <dir>] exit 0 if that commit has an approving review, 1 if not`;
|
|
57
|
+
|
|
58
|
+
const OPEN = 'open', APPROVED = 'approved', CHANGES = 'changes';
|
|
59
|
+
|
|
60
|
+
function locked(fn) {
|
|
61
|
+
let lost = [];
|
|
62
|
+
const r = underLock(LOCK, h => {
|
|
63
|
+
const s = load();
|
|
64
|
+
const before = JSON.stringify(s);
|
|
65
|
+
lost = reap(s);
|
|
66
|
+
const out = fn(s);
|
|
67
|
+
if (JSON.stringify(s) !== before) commit(h, FILE, JSON.stringify(s, null, 1), { fake: () => fakeFull('state') });
|
|
68
|
+
return out;
|
|
69
|
+
}, { wait: LOCK_WAIT, files: [FILE] });
|
|
70
|
+
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);
|
|
71
|
+
// Told after the lock: a message takes the messages lock.
|
|
72
|
+
for (const x of lost) if (x.from) tryTell(x.from, `${x.gone} was reviewing ${x.id} (${what(x)}), and its session ended before it answered. `
|
|
73
|
+
+ `Ask again and dibs picks someone else: dibs review request ${x.ref}${x.pr != null ? ` --pr ${x.pr}` : ''}`);
|
|
74
|
+
return r.out;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function load() {
|
|
78
|
+
let s = {};
|
|
79
|
+
try { s = readJSON(FILE); } catch (e) {
|
|
80
|
+
if (e.code !== 'ENOENT') say(`${FILE} was unreadable (${e.message}); starting with no reviews.`);
|
|
81
|
+
}
|
|
82
|
+
s.seq ||= 0; s.reviews ||= [];
|
|
83
|
+
return s;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
// An open request whose reviewer's Claude Code session is gone has no reviewer any more, and its
|
|
87
|
+
// author is told. Open ones expire after OPEN_FOR; answered ones stay KEEP_FOR. Returns the ones it
|
|
88
|
+
// took a reviewer from.
|
|
89
|
+
function reap(s, t = now()) {
|
|
90
|
+
const waiting = s.reviews.filter(x => x.state === OPEN && x.reviewer?.session && x.reviewer.agentId === 'main');
|
|
91
|
+
const lost = [];
|
|
92
|
+
if (waiting.length) {
|
|
93
|
+
const files = sessionFiles();
|
|
94
|
+
const up = makeAlive(files.map(f => f.pid));
|
|
95
|
+
const live = new Set(files.filter(f => up(f.pid)).map(f => f.sessionId));
|
|
96
|
+
for (const x of waiting) {
|
|
97
|
+
if (live.has(x.reviewer.session)) continue;
|
|
98
|
+
lost.push({ ...x, gone: x.reviewer.name });
|
|
99
|
+
(x.history ||= []).push({ state: 'unassigned', by: x.reviewer.name, why: 'its session ended', at: t });
|
|
100
|
+
x.reviewer = null;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
for (const x of s.reviews) if (x.state === OPEN && t - x.at > OPEN_FOR) Object.assign(x, { state: 'expired', answeredAt: t });
|
|
104
|
+
const closed = s.reviews.filter(x => x.state !== OPEN && t - (x.answeredAt || x.at) < KEEP_FOR).slice(-KEEP_DONE);
|
|
105
|
+
s.reviews = s.reviews.filter(x => x.state === OPEN || closed.includes(x));
|
|
106
|
+
return lost;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
const short = sha => String(sha || '').slice(0, SHA_SHOWN);
|
|
110
|
+
const what = x => (x.branch ? `${x.branch} at ${short(x.head).slice(0, 7)}` : `${short(x.base).slice(0, 7)}..${short(x.head).slice(0, 7)}`);
|
|
111
|
+
const word = s => (/^[\w.,/@:=+~^-]+$/.test(s) ? s : `'${String(s).replace(/'/g, "'\\''")}'`);
|
|
112
|
+
const nameOf = me => me?.name || 'the person';
|
|
113
|
+
function tryTell(to, text) { try { messageTo(to, text); } catch {} }
|
|
114
|
+
const sameAgent = (a, b) => !!a?.session && a.session === b?.session;
|
|
115
|
+
|
|
116
|
+
const idOf = arg => {
|
|
117
|
+
const n = Number(String(arg ?? '').replace(/^r/i, ''));
|
|
118
|
+
return arg && Number.isInteger(n) && n > 0 ? n : die('which review? Its id is the r number: dibs review approve r3 "looks right". Open ones: dibs review list');
|
|
119
|
+
};
|
|
120
|
+
const rid = x => `r${x.id}`;
|
|
121
|
+
const refuse = (err, code = 1) => ({ err, code });
|
|
122
|
+
const said = r => (r.err ? die(r.err, r.code) : r);
|
|
123
|
+
|
|
124
|
+
export async function review(args) {
|
|
125
|
+
const sub = args[0];
|
|
126
|
+
if (sub === 'request' || sub === 'ask') return request(args.slice(1));
|
|
127
|
+
if (sub === 'approve') return answer(args, APPROVED);
|
|
128
|
+
if (sub === 'changes') return answer(args, CHANGES);
|
|
129
|
+
if (sub === 'cancel') return cancel(args);
|
|
130
|
+
if (sub === 'check') return check(args.slice(1));
|
|
131
|
+
if (sub === 'help' || sub === '-h' || sub === '--help') return console.log(USAGE);
|
|
132
|
+
if (!sub || sub === 'list' || sub.startsWith('--')) return list(args.filter(a => a !== 'list'));
|
|
133
|
+
die(`unknown dibs review ${sub}.\n${USAGE}`);
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
function flags(args, takes) {
|
|
137
|
+
const o = { words: [] };
|
|
138
|
+
for (let i = 0; i < args.length; i++) {
|
|
139
|
+
const a = args[i], next = () => args[++i] ?? die(`${a} needs a value.\n${USAGE}`);
|
|
140
|
+
if (a === '-m' || a === '--msg') { if (!takes.includes('m')) die(`unknown flag ${a}.\n${USAGE}`); o.note = next().trim(); }
|
|
141
|
+
else if (a === '--to' && takes.includes('to')) o.to = next();
|
|
142
|
+
else if (a === '--repo') o.repo = path.resolve(expand(next()));
|
|
143
|
+
else if (a === '--pr' && takes.includes('pr')) { const n = Number(String(next()).replace(/^#/, '')); o.pr = Number.isInteger(n) && n > 0 ? n : die('--pr takes the pull request\'s number: --pr 42'); }
|
|
144
|
+
else if (a === '--json') o.json = true;
|
|
145
|
+
else if (a === '--all' && takes.includes('all')) o.all = true;
|
|
146
|
+
else if (a.startsWith('-') && a.length > 1 && !a.includes('..')) die(`unknown flag ${a}.\n${USAGE}`);
|
|
147
|
+
else o.words.push(a);
|
|
148
|
+
}
|
|
149
|
+
return o;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
// What a request names, read from git in dir: { repo (the git common dir, the same for every
|
|
153
|
+
// worktree), root, branch, base, head, ref, files, stat }. Dies saying why when it can't.
|
|
154
|
+
function resolve(dir, ref) {
|
|
155
|
+
const top = git(dir, ['rev-parse', '--path-format=absolute', '--git-common-dir', '--show-toplevel']);
|
|
156
|
+
if (!top) die(`${dir} isn't in a git repo. Run this in the repo, or say which: --repo <dir>`);
|
|
157
|
+
const [repo, root] = top.split('\n');
|
|
158
|
+
const sha = r => (/^[\w./@{}~^-]{1,200}$/.test(r) ? git(dir, ['rev-parse', '--verify', '--quiet', `${r}^{commit}`]) : null)
|
|
159
|
+
|| die(`no commit ${r} in ${root}. Name a branch, a commit or a range: dibs review request fix-login, or main..fix-login`);
|
|
160
|
+
const isBranch = r => !!git(dir, ['rev-parse', '--verify', '--quiet', `refs/heads/${r}`]);
|
|
161
|
+
let base, head, branch, into = null;
|
|
162
|
+
if (ref && ref.includes('..')) {
|
|
163
|
+
const three = ref.includes('...');
|
|
164
|
+
const [a, b = ''] = ref.split(three ? '...' : '..');
|
|
165
|
+
head = sha(b || 'HEAD');
|
|
166
|
+
base = three ? git(dir, ['merge-base', sha(a || 'HEAD'), head]) : sha(a || 'HEAD');
|
|
167
|
+
branch = b && isBranch(b) ? b : null;
|
|
168
|
+
} else {
|
|
169
|
+
if (!ref) ref = git(dir, ['symbolic-ref', '--quiet', '--short', 'HEAD']) || 'HEAD';
|
|
170
|
+
head = sha(ref);
|
|
171
|
+
branch = isBranch(ref) ? ref : null;
|
|
172
|
+
into = (guarded(root) || DEFAULT_INTO).find(isBranch) || null;
|
|
173
|
+
if (!into) die(`there's no main or master here to compare ${ref} with. Name what to review as a range: dibs review request <from>..${word(ref)}`);
|
|
174
|
+
base = git(dir, ['merge-base', into, head]);
|
|
175
|
+
if (base === head) die(`${ref} has nothing ${into} doesn't, so there's nothing to review against it. Name a range instead: dibs review request ${into}~3..${into}`);
|
|
176
|
+
}
|
|
177
|
+
if (!base) die(`${ref} and its base share no history, so there's no change to review. Name a range: dibs review request <from>..<to>`);
|
|
178
|
+
const files = (git(dir, ['diff', '--name-only', base, head]) || '').split('\n').filter(Boolean);
|
|
179
|
+
if (!files.length) die(`${ref || 'that'} changes no files against ${short(base).slice(0, 7)}, so there's nothing to review.`);
|
|
180
|
+
const stat = (git(dir, ['diff', '--shortstat', base, head]) || '').trim();
|
|
181
|
+
return { repo, root, branch, base, head, ref: ref || (branch ?? `${short(base)}..${short(head)}`), files, stat, into };
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
// The folder the changed files share, as an absolute path: what "who knows" is asked about.
|
|
185
|
+
function area(info) {
|
|
186
|
+
const dirs = info.files.map(f => path.dirname(f).split('/'));
|
|
187
|
+
let common = dirs[0] || [];
|
|
188
|
+
for (const d of dirs) { let k = 0; while (k < common.length && d[k] === common[k]) k++; common = common.slice(0, k); }
|
|
189
|
+
return path.join(info.root, ...common.filter(x => x && x !== '.'));
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
// Who should review: an agent running now that isn't the author, best first. skip: names that
|
|
193
|
+
// already had it. Returns { name, why } or null when nobody can.
|
|
194
|
+
async function pick(info, args, skip = new Set()) {
|
|
195
|
+
const others = othersNow('review', args).filter(a => a.name && !skip.has(a.name) && (a.reach === 'listening' || a.reach === 'working'));
|
|
196
|
+
if (!others.length) return null;
|
|
197
|
+
// dibs who knows, when this dibs has it: the agents that edited, held, ran or posted about the area.
|
|
198
|
+
let routed = [];
|
|
199
|
+
try { routed = (await import('./route.mjs')).lookup(area(info), { cwd: info.root }).found || []; } catch {}
|
|
200
|
+
const routeAt = new Map(routed.map((m, i) => [m.name, i]));
|
|
201
|
+
const repos = new Map();
|
|
202
|
+
const sameRepo = a => {
|
|
203
|
+
const cwd = a.session && cwdOf(a.session);
|
|
204
|
+
if (!cwd) return false;
|
|
205
|
+
if (!repos.has(cwd)) repos.set(cwd, git(cwd, ['rev-parse', '--path-format=absolute', '--git-common-dir']));
|
|
206
|
+
return repos.get(cwd) === info.repo;
|
|
207
|
+
};
|
|
208
|
+
const key = a => [routeAt.get(a.name) ?? Infinity, sameRepo(a) ? 0 : 1, a.reach === 'listening' ? 0 : 1, a.agentId === 'main' ? 0 : 1];
|
|
209
|
+
const ranked = others.map(a => ({ a, k: key(a) })).sort((x, y) => { for (let i = 0; i < x.k.length; i++) if (x.k[i] !== y.k[i]) return x.k[i] - y.k[i]; return 0; });
|
|
210
|
+
const { a, k } = ranked[0];
|
|
211
|
+
const r = routed[k[0]];
|
|
212
|
+
const why = [Number.isFinite(k[0]) ? `knows ${path.relative(info.root, area(info)) || 'this repo'}${r?.why?.[0]?.text ? ` (${r.why[0].text})` : ''}` : '',
|
|
213
|
+
k[1] === 0 ? 'works in the same repo' : '', a.reach === 'listening' ? 'is listening' : 'is working now'].filter(Boolean).join(', ');
|
|
214
|
+
return { name: a.name, why };
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
async function request(args) {
|
|
218
|
+
const o = flags(args, ['m', 'to', 'pr']);
|
|
219
|
+
if (o.words.length > 1) die(`review one branch or range at a time: dibs review request fix-login -m "what to look at"\n${USAGE}`);
|
|
220
|
+
if ((o.note || '').length > MAX_NOTE) die(`what to look at is ${o.note.length} characters; keep it under ${MAX_NOTE}, or point to a file. Nothing was asked.`);
|
|
221
|
+
const info = resolve(o.repo || process.cwd(), o.words[0]);
|
|
222
|
+
const me = whoAmI('review', args);
|
|
223
|
+
if (o.to) {
|
|
224
|
+
const no = unreachable(o.to);
|
|
225
|
+
if (no) die(no, 1);
|
|
226
|
+
if (me && o.to === me.name) die("that's you. Another agent has to review it: leave out --to and dibs picks one.");
|
|
227
|
+
}
|
|
228
|
+
// Asked again for the same commit: the same request, to someone new when there's anyone (the last one never answered).
|
|
229
|
+
const was = locked(s => { const x = s.reviews.find(r => r.state === OPEN && r.repo === info.repo && r.head === info.head); return x ? { ...x } : null; });
|
|
230
|
+
const skip = new Set(was?.reviewer ? [was.reviewer.name] : []);
|
|
231
|
+
// With nobody else about, the one that had it hears it again, as a reminder.
|
|
232
|
+
const chosen = o.to ? { name: o.to, why: 'was named by the author' } : (await pick(info, args, skip)) || (skip.size ? await pick(info, args) : null);
|
|
233
|
+
const x = locked(s => {
|
|
234
|
+
let x = s.reviews.find(r => r.state === OPEN && r.repo === info.repo && r.head === info.head);
|
|
235
|
+
if (!x) {
|
|
236
|
+
x = { id: ++s.seq, repo: info.repo, root: info.root, branch: info.branch, base: info.base, head: info.head, ref: info.ref,
|
|
237
|
+
files: info.files.slice(0, FILES_KEPT), changed: info.files.length, stat: info.stat, from: me, state: OPEN, at: now(), history: [] };
|
|
238
|
+
s.reviews.push(x);
|
|
239
|
+
}
|
|
240
|
+
if (o.note) x.note = o.note;
|
|
241
|
+
if (o.pr != null) x.pr = o.pr;
|
|
242
|
+
x.reviewer = chosen ? { name: chosen.name } : null;
|
|
243
|
+
x.picked = chosen?.why || null;
|
|
244
|
+
x.history.push({ state: 'asked', by: nameOf(me), ...(chosen && { of: chosen.name }), at: now() });
|
|
245
|
+
return { ...x };
|
|
246
|
+
});
|
|
247
|
+
logChange('review request', { id: rid(x), ...(chosen && { to: chosen.name }) });
|
|
248
|
+
if (!chosen) {
|
|
249
|
+
if (o.json) return console.log(JSON.stringify({ review: shown(x), to: null }));
|
|
250
|
+
return console.log(`${rid(x)} is asked for ${what(x)}, but no other agent is working or listening here now, so nobody has it yet. `
|
|
251
|
+
+ `It waits on the board; any agent can answer it (dibs review approve ${rid(x)} "notes"), and asking again later picks one: dibs review request ${word(x.ref)}`);
|
|
252
|
+
}
|
|
253
|
+
const files = `${x.changed} file${x.changed === 1 ? '' : 's'}${x.stat ? `, ${x.stat.replace(/^\d+ files? changed,?\s*/, '')}` : ''}`;
|
|
254
|
+
const text = `Review request ${rid(x)}: ${nameOf(me)} asks you to review ${what(x)} in ${x.root} (${files}).`
|
|
255
|
+
+ `${x.note ? ` What to look at: ${x.note}` : ''}${x.pr != null ? ` It's pull request #${x.pr}.` : ''}`
|
|
256
|
+
+ `\nSee it: git -C ${word(x.root)} diff ${short(x.base)}..${short(x.head)}`
|
|
257
|
+
+ `\nAnswer: dibs review approve ${rid(x)} "what you checked", or dibs review changes ${rid(x)} "what to change". ${me ? `${me.name} hears` : 'The person sees'} your answer.`
|
|
258
|
+
+ ` dibs picked you for this (${chosen.why}). If you can't review it, say so: ${me ? `dibs say --to ${word(me.name)} "..."` : 'dibs say "..."'}`;
|
|
259
|
+
const r = send(chosen.name, text, 'review', args);
|
|
260
|
+
// The record keeps how to reach the reviewer, for its session's end and the cancel notice.
|
|
261
|
+
locked(s => { const y = s.reviews.find(z => z.id === x.id); if (y?.reviewer?.name === chosen.name) Object.assign(y.reviewer, { session: r.th.session, agentId: r.th.agentId, who: r.th.who }); });
|
|
262
|
+
if (o.json) return console.log(JSON.stringify({ review: shown(x), to: r.to }));
|
|
263
|
+
const d = delivery(r);
|
|
264
|
+
console.log(`${rid(x)} (${what(x)}) is with ${r.to}, who ${chosen.why}${d.startsWith('but ') ? ', ' : ': '}${d}`
|
|
265
|
+
+ ` Its answer reaches you like any message. Where it stands: dibs review list`);
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
// approve and changes: anyone but the author's own session may answer, the person included, and
|
|
269
|
+
// the author hears who did.
|
|
270
|
+
async function answer(args, verdict) {
|
|
271
|
+
const me = whoAmI('review', args);
|
|
272
|
+
const name = nameOf(me);
|
|
273
|
+
const n = idOf(args[1]);
|
|
274
|
+
const note = args.slice(2).join(' ').trim().slice(0, MAX_NOTE);
|
|
275
|
+
if (verdict === CHANGES && !note) die(`say what to change: dibs review changes r${n} "the retry loop never gives up". Nothing was answered.`);
|
|
276
|
+
const x = said(locked(s => {
|
|
277
|
+
const x = s.reviews.find(r => r.id === n);
|
|
278
|
+
if (!x) return refuse(`no review r${n}. Open ones: dibs review list`);
|
|
279
|
+
if (x.state === 'cancelled' || x.state === 'expired') return refuse(`${rid(x)} is ${x.state}. Its author can ask again: dibs review request ${word(x.ref)}`);
|
|
280
|
+
if (sameAgent(me, x.from)) return refuse(`you asked for ${rid(x)}, so another agent has to answer it. It's with ${x.reviewer?.name || 'nobody yet'}: dibs review list`);
|
|
281
|
+
Object.assign(x, { state: verdict, answeredAt: now(), verdictBy: name, verdictNote: note || null });
|
|
282
|
+
x.history.push({ state: verdict, by: name, ...(note && { note }), at: now() });
|
|
283
|
+
return { ...x };
|
|
284
|
+
}));
|
|
285
|
+
logChange(verdict === APPROVED ? 'review approve' : 'review changes', { id: rid(x) });
|
|
286
|
+
// The branch may have moved on since the request: the answer covers the commit that was asked about.
|
|
287
|
+
const tip = x.branch ? git(x.root, ['rev-parse', '--verify', '--quiet', `refs/heads/${x.branch}`]) : null;
|
|
288
|
+
const moved = tip && tip !== x.head ? ` ${x.branch} has moved to ${short(tip).slice(0, 7)} since, so this answer covers ${short(x.head).slice(0, 7)} only.` : '';
|
|
289
|
+
if (x.from && !sameAgent(me, x.from)) {
|
|
290
|
+
tryTell(x.from, verdict === APPROVED
|
|
291
|
+
? `${name} approved ${rid(x)} (${what(x)})${note ? `: ${note}${/[.!?]$/.test(note) ? '' : '.'}` : '.'}${moved} Merge when you're ready.`
|
|
292
|
+
: `${name} asked for changes in ${rid(x)} (${what(x)}): ${note}\nMake them, commit, and ask again: dibs review request ${word(x.ref)}${x.pr != null ? ` --pr ${x.pr}` : ''}`);
|
|
293
|
+
}
|
|
294
|
+
console.log(`${rid(x)} ${verdict === APPROVED ? 'approved' : 'needs changes'}.${x.from ? ` ${x.from.name} is told.` : ''}${moved}`);
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
function cancel(args) {
|
|
298
|
+
const me = whoAmI('review', args);
|
|
299
|
+
const n = idOf(args[1]);
|
|
300
|
+
const x = said(locked(s => {
|
|
301
|
+
const x = s.reviews.find(r => r.id === n);
|
|
302
|
+
if (!x) return refuse(`no review r${n}. Open ones: dibs review list`);
|
|
303
|
+
if (x.state !== OPEN) return refuse(`${rid(x)} is already ${x.state}.`);
|
|
304
|
+
Object.assign(x, { state: 'cancelled', answeredAt: now(), verdictBy: nameOf(me) });
|
|
305
|
+
x.history.push({ state: 'cancelled', by: nameOf(me), at: now() });
|
|
306
|
+
return { ...x };
|
|
307
|
+
}));
|
|
308
|
+
logChange('review cancel', { id: rid(x) });
|
|
309
|
+
if (x.reviewer?.session && !sameAgent(me, x.reviewer)) tryTell(x.reviewer, `${rid(x)} (${what(x)}) was cancelled by ${nameOf(me)}: no need to review it.`);
|
|
310
|
+
console.log(`${rid(x)} is cancelled.`);
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
// dibs review check [<branch>] [--repo dir]: what the guard hook would find, for scripts and agents.
|
|
314
|
+
function check(args) {
|
|
315
|
+
const o = flags(args, []);
|
|
316
|
+
const dir = o.repo || process.cwd();
|
|
317
|
+
const top = git(dir, ['rev-parse', '--path-format=absolute', '--git-common-dir']);
|
|
318
|
+
if (!top) die(`${dir} isn't in a git repo. Run this in the repo, or say which: --repo <dir>`);
|
|
319
|
+
const ref = o.words[0] || 'HEAD';
|
|
320
|
+
const sha = /^[\w./@{}~^-]{1,200}$/.test(ref) ? git(dir, ['rev-parse', '--verify', '--quiet', `${ref}^{commit}`]) : null;
|
|
321
|
+
if (!sha) die(`no commit ${ref} here.`);
|
|
322
|
+
const s = standing(load().reviews, { repo: top, sha, branch: ref === 'HEAD' ? null : ref });
|
|
323
|
+
const into = guarded(dir);
|
|
324
|
+
const rule = into ? `This repo asks for one before merging into ${into.join(' or ')}.` : 'This repo doesn\'t ask for one before merging.';
|
|
325
|
+
if (o.json) { console.log(JSON.stringify({ sha, approved: s.approved ? shown(s.approved) : null, open: s.open ? shown(s.open) : null, required: into })); process.exitCode = s.approved ? 0 : 1; return; }
|
|
326
|
+
if (s.approved) return console.log(`${short(sha).slice(0, 7)} is approved: ${rid(s.approved)} by ${s.approved.verdictBy}${s.approved.verdictNote ? ` ("${s.approved.verdictNote}")` : ''}. ${rule}`);
|
|
327
|
+
const why = s.open ? `${rid(s.open)} is waiting on ${s.open.reviewer?.name || 'any agent'}` : s.changes ? `${s.changes.verdictBy} asked for changes in ${rid(s.changes)}`
|
|
328
|
+
: s.older ? `${rid(s.older)} approved ${short(s.older.head).slice(0, 7)}, before it moved` : 'nobody has been asked';
|
|
329
|
+
die(`${short(sha).slice(0, 7)} has no approving review: ${why}. ${rule} Ask: dibs review request${ref === 'HEAD' ? '' : ` ${word(ref)}`}`, 1);
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
// What the board, the page, the phone and --json show of one: names and commits, never sessions or paths.
|
|
333
|
+
export const shown = x => ({ id: rid(x), state: x.state, project: path.basename(x.root || ''), branch: x.branch || null, base: short(x.base), head: short(x.head),
|
|
334
|
+
changed: x.changed ?? (x.files || []).length, stat: x.stat || null, note: x.note || null, pr: x.pr ?? null, from: x.from?.name || 'the person',
|
|
335
|
+
reviewer: x.reviewer?.name || null, picked: x.picked || null, at: x.at, answeredAt: x.answeredAt || null, by: x.verdictBy || null, verdict: x.verdictNote || null });
|
|
336
|
+
|
|
337
|
+
// Open requests and the answers of the last day, newest first, for the board and the page. Read
|
|
338
|
+
// without the lock; the reaping isn't saved.
|
|
339
|
+
export function reviewsNow(t = now()) {
|
|
340
|
+
if (!fs.existsSync(FILE)) return [];
|
|
341
|
+
const s = load();
|
|
342
|
+
reap(s, t);
|
|
343
|
+
return s.reviews.filter(x => x.state === OPEN || ((x.state === APPROVED || x.state === CHANGES) && t - x.answeredAt < SHOWN_FOR))
|
|
344
|
+
.sort((a, b) => (b.answeredAt || b.at) - (a.answeredAt || a.at)).map(shown);
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
// Answers given between since and t, for dibs recap.
|
|
348
|
+
export function answeredSince(since, t = now()) {
|
|
349
|
+
if (!fs.existsSync(FILE)) return [];
|
|
350
|
+
return load().reviews.filter(x => (x.state === APPROVED || x.state === CHANGES) && x.answeredAt > since && x.answeredAt <= t).map(shown);
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
// One line for the board.
|
|
354
|
+
export const reviewLine = (x, t = now()) => `${x.id} ${x.branch || `${x.base.slice(0, 7)}..${x.head.slice(0, 7)}`} in ${x.project} from ${x.from}, `
|
|
355
|
+
+ (x.state === OPEN ? (x.reviewer ? `with ${x.reviewer} ${t - x.at < 6e4 ? 'since just now' : `for ${minutes(t - x.at)}`}` : 'nobody has it yet')
|
|
356
|
+
: x.state === APPROVED ? `approved by ${x.by}` : x.state === CHANGES ? `changes asked by ${x.by}` : x.state);
|
|
357
|
+
|
|
358
|
+
function list(args) {
|
|
359
|
+
const o = flags(args, ['all']);
|
|
360
|
+
const all = !!o.all;
|
|
361
|
+
if (o.words.length) die(`unknown ${o.words[0]}.\n${USAGE}`);
|
|
362
|
+
const t = now();
|
|
363
|
+
const s = locked(x => x);
|
|
364
|
+
const open = s.reviews.filter(x => x.state === OPEN).sort((a, b) => a.at - b.at);
|
|
365
|
+
const done = s.reviews.filter(x => x.state !== OPEN).sort((a, b) => (b.answeredAt || 0) - (a.answeredAt || 0));
|
|
366
|
+
if (o.json) return console.log(JSON.stringify({ reviews: [...open, ...(all ? done : done.slice(0, RECENT))].map(shown) }, null, 1));
|
|
367
|
+
if (!open.length && !done.length) return console.log('No reviews. Ask another agent to look over a change: dibs review request <branch> -m "what to look at"');
|
|
368
|
+
const out = [bold(open.length ? `${open.length} waiting for an answer:` : 'Nothing waiting for an answer.')];
|
|
369
|
+
out.push(...columns(open.map(x => [rid(x), reviewLine(shown(x), t).replace(/^r\d+ /, '') + (x.note ? dim(` (${x.note.slice(0, 80)})`) : '')])));
|
|
370
|
+
const old = all ? done : done.slice(0, RECENT);
|
|
371
|
+
if (old.length) {
|
|
372
|
+
out.push('', dim(all ? 'Answered:' : 'Answered lately:'));
|
|
373
|
+
out.push(...columns(old.map(x => [rid(x), dim(`${reviewLine(shown(x), t).replace(/^r\d+ /, '')}${x.verdictNote ? `: ${x.verdictNote.slice(0, 120)}` : ''}`)])));
|
|
374
|
+
}
|
|
375
|
+
out.push('', dim('Answer one: dibs review approve <id> "notes", or dibs review changes <id> "what to change". Everything: dibs review help'));
|
|
376
|
+
console.log(out.join('\n'));
|
|
377
|
+
}
|
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
|
+
}
|