hud-gateway 0.0.0-stage → 0.1.0
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/README.md +35 -2
- package/bin/hud-gateway.mjs +366 -0
- package/core.js +566 -0
- package/package.json +34 -4
- package/sample.js +123 -0
package/README.md
CHANGED
|
@@ -1,3 +1,36 @@
|
|
|
1
|
-
#
|
|
1
|
+
# hud-gateway
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
How much of your team's time goes to approving agent PRs that were already fine, and the approvals
|
|
4
|
+
policy that hands it back.
|
|
5
|
+
|
|
6
|
+
```
|
|
7
|
+
npx hud-gateway # the repo behind `origin` in this folder
|
|
8
|
+
npx hud-gateway owner/repo
|
|
9
|
+
npx hud-gateway --days 90 # 30 days by default; it widens to 90 and 180 on its own when 30 days hold fewer than 25 agent PRs
|
|
10
|
+
npx hud-gateway --sample # an invented repo, no token: for demos and recordings
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
Read-only and zero dependencies. It uses your `gh` login (its token, read once) or `GITHUB_TOKEN` with
|
|
14
|
+
read access to Contents, Pull requests and Metadata. It lists merged PRs 100 a request, then reads reviews and files
|
|
15
|
+
only for the PRs that need them (agent-written, and fix PRs), 25 a request with four in flight, so a
|
|
16
|
+
30-day window of a busy repo takes seconds; `--rest` reads over the REST API instead. The policy is written
|
|
17
|
+
to `hud-gateway.yml` next to you, and the result opens in the Hud editor at play.hudx.io/gateway, carried
|
|
18
|
+
inside the link itself: nothing is uploaded.
|
|
19
|
+
|
|
20
|
+
Flags: `--days 30`, `--max 2000`, `--out hud-gateway.yml`, `--json out.json`, `--payload out.json`, `--no-open`, `--quiet`, `--rest`.
|
|
21
|
+
|
|
22
|
+
The three beats before the policy:
|
|
23
|
+
|
|
24
|
+
- **Hours waited for approvals that changed nothing.** A rubber stamp is a human approval with no
|
|
25
|
+
review comment, no change request and no commit after it. The wait runs from the moment the PR was
|
|
26
|
+
final (last push or ready-for-review) to that approval.
|
|
27
|
+
- **Did they hold up?** Of the PRs that merged with a rubber stamp or no human review, old enough to
|
|
28
|
+
judge, how many were not reverted or rewritten within 14 days. Rewritten means a later PR that reads
|
|
29
|
+
like a fix and names the PR or touches at least half of its non-test files. Reverts are PRs with
|
|
30
|
+
"revert" in the title that point at it. No production signal is used.
|
|
31
|
+
- **Reviewer time.** 20 minutes of attention per rubber stamp.
|
|
32
|
+
|
|
33
|
+
Then the draft: rules from the repository tree, CODEOWNERS, branch rules and the AI reviewers already
|
|
34
|
+
on the PRs, replayed deterministically on the agent-written PRs. No model call anywhere.
|
|
35
|
+
|
|
36
|
+
Source: https://github.com/code-hud/play-hud/tree/main/packages/hud-gateway
|
|
@@ -0,0 +1,366 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// hud-gateway: how much of your team's time goes to approving agent PRs that were already fine,
|
|
3
|
+
// and the approvals policy that hands it back. Zero dependencies, read-only.
|
|
4
|
+
//
|
|
5
|
+
// npx hud-gateway # the repo behind `origin` in this folder
|
|
6
|
+
// npx hud-gateway owner/repo
|
|
7
|
+
// flags: --days 30 (widens to 90 and 180 on its own when 30 days hold too few agent PRs) --max 2000 --out hud-gateway.yml --json out.json --no-open --quiet --rest --sample (an invented repo, no token)
|
|
8
|
+
//
|
|
9
|
+
// Uses your `gh` login (its token, read once) or GITHUB_TOKEN. One GraphQL request per 50 PRs, read-only;
|
|
10
|
+
// --rest uses the REST API instead (3 to 4 requests per PR, slower).
|
|
11
|
+
// The policy and the backtest travel to the editor inside the URL fragment: no server sees them.
|
|
12
|
+
|
|
13
|
+
import { execFile, execFileSync, spawn } from 'node:child_process';
|
|
14
|
+
import { promisify } from 'node:util';
|
|
15
|
+
import { writeFileSync } from 'node:fs';
|
|
16
|
+
import { gzipSync } from 'node:zlib';
|
|
17
|
+
import { runBacktest, runBacktestGraphQL, draftPolicy, evaluatePolicy, ruleText, ruleVerdict, toPayload, toYaml, funTime, SAFE_DAYS, REVIEW_MIN } from '../core.js';
|
|
18
|
+
import { sampleApi, SAMPLE_SLUG } from '../sample.js';
|
|
19
|
+
|
|
20
|
+
const run = promisify(execFile);
|
|
21
|
+
const argv = process.argv.slice(2);
|
|
22
|
+
const flag = (name, dflt) => {
|
|
23
|
+
const i = argv.indexOf(`--${name}`);
|
|
24
|
+
if (i === -1) return dflt;
|
|
25
|
+
const v = argv[i + 1];
|
|
26
|
+
return v === undefined || v.startsWith('--') ? true : v;
|
|
27
|
+
};
|
|
28
|
+
const EDITOR = process.env.HUD_GATEWAY_URL || 'https://play.hudx.io/gateway';
|
|
29
|
+
const TTY = !!process.stdout.isTTY && !flag('quiet', false) && !process.env.CI;
|
|
30
|
+
const ANIM = TTY && !process.env.NO_ANIM;
|
|
31
|
+
|
|
32
|
+
// ---------- terminal ----------
|
|
33
|
+
const C = process.env.NO_COLOR ? Object.fromEntries(['teal', 'mint', 'amber', 'red', 'dim', 'white', 'bold', 'off'].map((k) => [k, ''])) : {
|
|
34
|
+
teal: '\x1b[38;2;15;232;211m', mint: '\x1b[38;2;95;255;188m', amber: '\x1b[38;2;255;180;107m', red: '\x1b[38;2;242;102;114m',
|
|
35
|
+
dim: '\x1b[38;2;138;156;166m', white: '\x1b[97m', bold: '\x1b[1m', off: '\x1b[0m',
|
|
36
|
+
};
|
|
37
|
+
const out = (s = '') => process.stdout.write(`${s}\n`);
|
|
38
|
+
const sleep = (ms) => (ANIM ? new Promise((r) => setTimeout(r, ms)) : Promise.resolve());
|
|
39
|
+
const fmt = (n) => Number(n).toLocaleString('en-US');
|
|
40
|
+
const hrs = (h) => (h >= 48 ? `${Math.round(h / 24)} d ${Math.round(h % 24)} h` : h >= 10 ? `${Math.round(h)} h` : `${Math.round(h * 10) / 10} h`);
|
|
41
|
+
const plural = (n, w) => `${fmt(n)} ${w}${n === 1 ? '' : 's'}`;
|
|
42
|
+
|
|
43
|
+
class Line {
|
|
44
|
+
constructor() { this.on = false; this.t = null; this.i = 0; this.text = ''; }
|
|
45
|
+
start(text) {
|
|
46
|
+
this.text = text; this.on = true;
|
|
47
|
+
if (!TTY) { out(` ${text}`); return; }
|
|
48
|
+
const frames = '⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏';
|
|
49
|
+
this.t = setInterval(() => { process.stdout.write(`\r ${C.teal}${frames[this.i++ % frames.length]}${C.off} ${this.text}\x1b[K`); }, 80);
|
|
50
|
+
}
|
|
51
|
+
set(text) { this.text = text; if (!TTY && text !== this.text) out(` ${text}`); }
|
|
52
|
+
done(text) { if (this.t) clearInterval(this.t); this.on = false; if (TTY) process.stdout.write(`\r ${C.mint}✓${C.off} ${text}\x1b[K\n`); else out(` ${text}`); }
|
|
53
|
+
}
|
|
54
|
+
const bar = (done, total, w = 22) => { const f = total ? Math.round((w * done) / total) : 0; return `${C.teal}${'█'.repeat(f)}${C.dim}${'░'.repeat(w - f)}${C.off}`; };
|
|
55
|
+
|
|
56
|
+
// a number that counts up to its value (the reveal), then stays
|
|
57
|
+
async function countUp(value, unit, tail) {
|
|
58
|
+
const steps = 28;
|
|
59
|
+
const big = (v) => ` ${C.bold}${C.white}${(`${fmt(v)} ${unit}`).padEnd(18)}${C.off}`;
|
|
60
|
+
if (!ANIM) { out(`${big(value)}${tail}`); return; }
|
|
61
|
+
for (let i = 1; i <= steps; i++) {
|
|
62
|
+
const e = 1 - Math.pow(1 - i / steps, 3);
|
|
63
|
+
process.stdout.write(`\r${big(Math.round(value * e))}\x1b[K`);
|
|
64
|
+
await sleep(32);
|
|
65
|
+
}
|
|
66
|
+
process.stdout.write(`\r${big(value)}${tail}\x1b[K\n`);
|
|
67
|
+
}
|
|
68
|
+
async function say(text, ms = 420) { out(text); await sleep(ms); }
|
|
69
|
+
|
|
70
|
+
// ---------- repo ----------
|
|
71
|
+
function originSlug() {
|
|
72
|
+
try {
|
|
73
|
+
const url = execFileSync('git', ['remote', 'get-url', 'origin'], { stdio: ['ignore', 'pipe', 'ignore'] }).toString().trim();
|
|
74
|
+
const m = url.match(/github\.com[:/]([\w.-]+)\/([\w.-]+?)(?:\.git)?\/?$/i);
|
|
75
|
+
return m ? `${m[1]}/${m[2]}` : null;
|
|
76
|
+
} catch { return null; }
|
|
77
|
+
}
|
|
78
|
+
const SAMPLE = !!flag('sample', false);
|
|
79
|
+
const slug = SAMPLE ? SAMPLE_SLUG : argv.find((a) => /^[\w.-]+\/[\w.-]+$/.test(a)) || originSlug();
|
|
80
|
+
if (!slug) {
|
|
81
|
+
console.error('Usage: npx hud-gateway [owner/repo] (run inside a clone, or name the repository)');
|
|
82
|
+
process.exit(1);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
// ---------- GitHub access ----------
|
|
86
|
+
let TOKEN = process.env.GITHUB_TOKEN || process.env.GH_TOKEN || null;
|
|
87
|
+
let REQS = 0;
|
|
88
|
+
async function token() {
|
|
89
|
+
if (TOKEN) return TOKEN;
|
|
90
|
+
try { TOKEN = (await run('gh', ['auth', 'token'])).stdout.trim(); } catch { /* no gh */ }
|
|
91
|
+
if (!TOKEN) throw new Error('No GitHub access. Run `gh auth login` or set GITHUB_TOKEN (read-only is enough).');
|
|
92
|
+
return TOKEN;
|
|
93
|
+
}
|
|
94
|
+
const sample = SAMPLE ? sampleApi() : null;
|
|
95
|
+
async function http(url, init) {
|
|
96
|
+
for (let attempt = 0; ; attempt++) {
|
|
97
|
+
REQS++;
|
|
98
|
+
const res = await fetch(url, { ...init, headers: { authorization: `Bearer ${await token()}`, accept: 'application/vnd.github+json', 'user-agent': 'hud-gateway', 'content-type': 'application/json', ...(init?.headers || {}) } });
|
|
99
|
+
if (res.status === 403 && res.headers.get('x-ratelimit-remaining') === '0') {
|
|
100
|
+
const wait = Math.max(5, Number(res.headers.get('x-ratelimit-reset')) * 1000 - Date.now());
|
|
101
|
+
throw new Error(`GitHub rate limit hit; it resets in ${Math.ceil(wait / 60000)} min.`);
|
|
102
|
+
}
|
|
103
|
+
if (res.ok) return res.json();
|
|
104
|
+
if (attempt >= 3 || [401, 403, 404].includes(res.status)) throw new Error(`GitHub ${res.status} on ${url.replace('https://api.github.com/', '')}`);
|
|
105
|
+
await new Promise((r) => setTimeout(r, 1500 * (attempt + 1)));
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
// REST, with a last resort: when the token is refused outright but `gh` works (proxied or enterprise setups),
|
|
109
|
+
// go through `gh api` for the rest of the run.
|
|
110
|
+
let viaGh = false;
|
|
111
|
+
async function api(path) {
|
|
112
|
+
if (sample) return sample(path);
|
|
113
|
+
if (viaGh) { REQS++; return JSON.parse((await run('gh', ['api', path], { maxBuffer: 1 << 28 })).stdout); }
|
|
114
|
+
try { return await http(`https://api.github.com/${path}`); }
|
|
115
|
+
catch (e) {
|
|
116
|
+
if (!/GitHub 401/.test(e.message)) throw e;
|
|
117
|
+
try { await run('gh', ['api', 'rate_limit']); viaGh = true; return api(path); } catch { throw e; }
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
async function gql(query, variables) {
|
|
121
|
+
if (sample) return sample.gql(query, variables);
|
|
122
|
+
const d = await http('https://api.github.com/graphql', { method: 'POST', body: JSON.stringify({ query, variables }) });
|
|
123
|
+
if (d.errors?.length) throw new Error(d.errors[0].message);
|
|
124
|
+
return d.data;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
function openBrowser(url) {
|
|
128
|
+
try {
|
|
129
|
+
const cmd = process.platform === 'darwin' ? ['open', [url]] : process.platform === 'win32' ? ['rundll32', ['url.dll,FileProtocolHandler', url]] : ['xdg-open', [url]];
|
|
130
|
+
const child = spawn(cmd[0], cmd[1], { stdio: 'ignore', detached: true });
|
|
131
|
+
child.on('error', () => {});
|
|
132
|
+
child.unref();
|
|
133
|
+
return true;
|
|
134
|
+
} catch { return false; }
|
|
135
|
+
}
|
|
136
|
+
const b64url = (buf) => buf.toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
|
|
137
|
+
|
|
138
|
+
// ---------- layout helpers ----------
|
|
139
|
+
const W = Math.min(Math.max((process.stdout.columns || 100) - 2, 60), 110);
|
|
140
|
+
const plain = (t) => t.replace(/\x1b\[[0-9;]*m/g, '');
|
|
141
|
+
const vlen = (t) => plain(t).length;
|
|
142
|
+
const padR = (t, n) => t + ' '.repeat(Math.max(0, n - vlen(t)));
|
|
143
|
+
const cut = (t, n) => (t.length > n ? `${t.slice(0, n - 1)}…` : t);
|
|
144
|
+
const wrap = (text, indent = 4, width = W) => {
|
|
145
|
+
const words = text.split(' '), lines = [];
|
|
146
|
+
let cur = '';
|
|
147
|
+
for (const w of words) {
|
|
148
|
+
if (vlen(cur) + vlen(w) + 1 > width - indent && cur) { lines.push(cur); cur = w; } else cur = cur ? `${cur} ${w}` : w;
|
|
149
|
+
}
|
|
150
|
+
if (cur) lines.push(cur);
|
|
151
|
+
return lines.map((l) => ' '.repeat(indent) + l).join('\n');
|
|
152
|
+
};
|
|
153
|
+
const rule = (title, right = '') => {
|
|
154
|
+
const left = ` ${C.bold}${C.white}${title}${C.off} `;
|
|
155
|
+
const n = Math.max(4, W - vlen(left) - vlen(right) - (right ? 2 : 0));
|
|
156
|
+
out(`${left}${C.dim}${'─'.repeat(n)}${C.off}${right ? ` ${right}` : ''}`);
|
|
157
|
+
};
|
|
158
|
+
// a two-column fact row: a big value on the left, its meaning on the right
|
|
159
|
+
const fact = (value, text, col = C.white) => out(` ${col}${C.bold}${padR(value, 18)}${C.off} ${C.dim}${text}${C.off}`);
|
|
160
|
+
const sub = (text) => out(wrap(`${C.dim}${text}${C.off}`, 23));
|
|
161
|
+
// rules in the CLI read shorter than on the page
|
|
162
|
+
const shortRule = (r) => {
|
|
163
|
+
switch (r.kind) {
|
|
164
|
+
case 'docs_tests': return 'Docs and tests only, on green CI';
|
|
165
|
+
case 'title': return `Title or label has ${r.words.join(', ')}`;
|
|
166
|
+
case 'paths': return `${r.label || 'Paths'}: ${r.globs.slice(0, 2).join(', ')}${r.globs.length > 2 ? ` +${r.globs.length - 2}` : ''}`;
|
|
167
|
+
case 'bot': return `${r.name && r.name !== 'Custom' ? r.name : r.login} must not request changes`;
|
|
168
|
+
case 'checks': return `${r.required ? 'Required checks' : 'CI checks'} pass: ${r.checks.slice(0, 3).join(', ')}${r.checks.length > 3 ? ` +${r.checks.length - 3}` : ''}`;
|
|
169
|
+
case 'size': return `More than ${r.maxFiles} files touched`;
|
|
170
|
+
case 'default': return r.value === 'fast' ? 'Everything else' : 'Everything else';
|
|
171
|
+
default: return ruleText(r);
|
|
172
|
+
}
|
|
173
|
+
};
|
|
174
|
+
|
|
175
|
+
// ---------- the run ----------
|
|
176
|
+
const askedDays = flag('days', null);
|
|
177
|
+
let days = Number(askedDays || 30);
|
|
178
|
+
try {
|
|
179
|
+
out();
|
|
180
|
+
out(` ${C.bold}${C.white}{Hud} Merge Gateway${C.off}`);
|
|
181
|
+
out(` ${C.dim}${slug} · ${SAMPLE ? 'an invented sample repo' : 'read-only, nothing is posted to GitHub'}${C.off}`);
|
|
182
|
+
out();
|
|
183
|
+
|
|
184
|
+
const line = new Line();
|
|
185
|
+
line.start('Listing merged PRs');
|
|
186
|
+
const t0 = Date.now();
|
|
187
|
+
const live = { stamps: 0, hours: 0, agent: 0 };
|
|
188
|
+
const onRow = (r) => {
|
|
189
|
+
if (r.kind !== 'agent') return;
|
|
190
|
+
live.agent++;
|
|
191
|
+
if (r.review === 'rubber_stamp') { live.stamps++; live.hours += r.waitHours || 0; }
|
|
192
|
+
};
|
|
193
|
+
const tally = () => (live.stamps ? ` ${C.dim}·${C.off} ${C.white}${fmt(Math.round(live.hours))} h${C.off} ${C.dim}waited so far, ${live.stamps} rubber stamps${C.off}` : live.agent ? ` ${C.dim}· ${live.agent} agent PRs so far${C.off}` : '');
|
|
194
|
+
const opts = {
|
|
195
|
+
days, maxPrs: Number(flag('max', 2000)), concurrency: 16, files: true, onRow,
|
|
196
|
+
onProgress: ({ phase, done, total }) => {
|
|
197
|
+
const el = `${C.dim}${Math.round((Date.now() - t0) / 1000)} s${C.off}`;
|
|
198
|
+
if (phase === 'list') line.set(`Listing merged PRs ${C.dim}· ${fmt(done)} found${C.off} ${el}${tally()}`);
|
|
199
|
+
if (phase === 'read') line.set(`Reading the ${fmt(total)} that need a closer look ${bar(done, total)} ${C.dim}${fmt(done)}/${fmt(total)}${C.off} ${el}${tally()}`);
|
|
200
|
+
},
|
|
201
|
+
};
|
|
202
|
+
// Read 30 days first so the first number shows fast; widen only when that window holds too few agent PRs.
|
|
203
|
+
const ENOUGH = 25;
|
|
204
|
+
let s, how = 'GraphQL';
|
|
205
|
+
const read = async (d) => {
|
|
206
|
+
live.stamps = 0; live.hours = 0; live.agent = 0;
|
|
207
|
+
const o = { ...opts, days: d };
|
|
208
|
+
if (flag('rest', false)) { how = 'REST'; return runBacktest(slug, api, o); }
|
|
209
|
+
try { return await runBacktestGraphQL(slug, gql, o); }
|
|
210
|
+
catch (e) {
|
|
211
|
+
if (/rate limit|No GitHub access/.test(e.message)) throw e;
|
|
212
|
+
how = `REST (GraphQL said: ${e.message.slice(0, 50)})`;
|
|
213
|
+
line.set(`GraphQL unavailable; reading over REST`);
|
|
214
|
+
return runBacktest(slug, api, o);
|
|
215
|
+
}
|
|
216
|
+
};
|
|
217
|
+
s = await read(days);
|
|
218
|
+
for (const wider of [90, 180]) {
|
|
219
|
+
if (askedDays || s.agent_prs >= ENOUGH || days >= wider) break;
|
|
220
|
+
line.set(`${plural(s.agent_prs, 'agent-written PR')} in ${days} days is thin; reading ${wider} days`);
|
|
221
|
+
days = wider;
|
|
222
|
+
s = await read(days);
|
|
223
|
+
}
|
|
224
|
+
line.done(`${fmt(s.merged_prs)} merged PRs · ${C.white}${fmt(s.agent_prs)} by agents${C.off} (${s.agent_share_pct}%) · last ${days} days ${C.dim}· ${Math.round((Date.now() - t0) / 1000)} s · ${how} · ${REQS} requests${C.off}`);
|
|
225
|
+
|
|
226
|
+
if (!s.agent_prs) {
|
|
227
|
+
out();
|
|
228
|
+
out(wrap(`No agent-written PRs found in the last ${days} days. Try ${C.white}--days 365${C.off}, or run this on a repo where coding agents open PRs.`, 2));
|
|
229
|
+
out();
|
|
230
|
+
process.exit(0);
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
// ---- beat 1: the wait (or, with no rubber stamps, the merges nobody looked at) ----
|
|
234
|
+
const stamps = s.outcomes.rubber_stamp;
|
|
235
|
+
const noHuman = s.outcomes.no_human;
|
|
236
|
+
await sleep(500);
|
|
237
|
+
out();
|
|
238
|
+
if (stamps) {
|
|
239
|
+
rule('Approvals that changed nothing');
|
|
240
|
+
out();
|
|
241
|
+
const fun = funTime(s.wait_hours_total);
|
|
242
|
+
await countUp(s.wait_hours_total, 'hours', ` ${C.white}(${plural(fun.days, 'working day')})${C.off} ${C.dim}waited for approvals that changed nothing${C.off}`);
|
|
243
|
+
await sleep(500);
|
|
244
|
+
if (fun.line) { out(` ${C.dim}${' '.repeat(18)} ${fun.line}${C.off}`); await sleep(500); }
|
|
245
|
+
fact(plural(stamps, 'PR'), 'approved by a person with no comment, no change request and no commit after it');
|
|
246
|
+
fact(`${hrs(s.wait_hours_median)} median`, `longest #${s.longest_wait.number}, ${hrs(s.longest_wait.hours)}${noHuman ? ` · another ${plural(noHuman, 'PR')} merged with no human review at all` : ''}`);
|
|
247
|
+
} else {
|
|
248
|
+
rule('Nobody waited. Nobody looked either.');
|
|
249
|
+
out();
|
|
250
|
+
await countUp(noHuman, 'PRs', ` ${C.dim}written by agents, merged with no human review at all${C.off}`);
|
|
251
|
+
await sleep(500);
|
|
252
|
+
fact(s.outcomes.human_changed_it ? plural(s.outcomes.human_changed_it, 'PR') : '0 PRs', 'got real review feedback. Not one agent PR waited for an approval that changed nothing.');
|
|
253
|
+
}
|
|
254
|
+
await sleep(900);
|
|
255
|
+
|
|
256
|
+
// ---- beat 2: were they safe ----
|
|
257
|
+
out();
|
|
258
|
+
rule(`Were they safe to merge ${stamps ? 'without that approval' : 'like that'}?`);
|
|
259
|
+
out();
|
|
260
|
+
if (s.quiet_judged) {
|
|
261
|
+
const bad = s.quiet_judged - s.quiet_held;
|
|
262
|
+
fact(`${Math.round(s.quiet_held_pct)}% held up`, `${fmt(s.quiet_held)} of ${fmt(s.quiet_judged)} were not reverted or rewritten in the ${SAFE_DAYS} days after`, bad ? C.amber : C.mint);
|
|
263
|
+
if (bad) fact(`${fmt(bad)} did not`, `${s.quiet_reverted} reverted · ${s.quiet_rewritten} rewritten by a fix PR`, C.amber);
|
|
264
|
+
} else {
|
|
265
|
+
fact('Too recent', `every quiet merge happened in the last ${SAFE_DAYS} days; run again in two weeks`);
|
|
266
|
+
}
|
|
267
|
+
await sleep(900);
|
|
268
|
+
|
|
269
|
+
// ---- beat 3: the estimate ----
|
|
270
|
+
if (stamps) {
|
|
271
|
+
out();
|
|
272
|
+
rule('Reviewer time');
|
|
273
|
+
out();
|
|
274
|
+
fact(`${plural(s.review_hours_est, 'hour')}`, `a quarter at ${REVIEW_MIN} min a review, spent approving what was already fine`);
|
|
275
|
+
await sleep(1000);
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
// ---- the policy ----
|
|
279
|
+
out();
|
|
280
|
+
const line2 = new Line();
|
|
281
|
+
line2.start('Drafting a policy from your tree, CODEOWNERS, branch rules and the reviewers you already run');
|
|
282
|
+
const policy = await draftPolicy(slug, api, s);
|
|
283
|
+
const sim = evaluatePolicy(policy, s);
|
|
284
|
+
const ymlPath = flag('out', 'hud-gateway.yml');
|
|
285
|
+
let wrote = true;
|
|
286
|
+
try { writeFileSync(ymlPath, toYaml(policy, 'dry-run')); } catch { wrote = false; }
|
|
287
|
+
line2.done(`Drafted ${plural(policy.rules.filter((r) => r.on !== false).length, 'rule')}${wrote ? ` ${C.dim}· written to ${ymlPath}${C.off}` : ''}`);
|
|
288
|
+
await sleep(300);
|
|
289
|
+
out();
|
|
290
|
+
rule('Draft policy', `${C.dim}first match wins${C.off}`);
|
|
291
|
+
out();
|
|
292
|
+
const col = { Approve: C.mint, Human: C.amber, Gate: C.teal };
|
|
293
|
+
const textW = W - 4 - 9 - 10;
|
|
294
|
+
for (const r of policy.rules) {
|
|
295
|
+
if (r.on === false) continue;
|
|
296
|
+
const v = ruleVerdict(r);
|
|
297
|
+
const cnt = sim.perRule[r.id] ? `${C.dim}${plural(sim.perRule[r.id], 'PR').padStart(8)}${C.off}` : '';
|
|
298
|
+
out(` ${col[v]}${v.toUpperCase().padEnd(8)}${C.off} ${padR(cut(shortRule(r), textW), textW)} ${cnt}`);
|
|
299
|
+
await sleep(120);
|
|
300
|
+
}
|
|
301
|
+
await sleep(400);
|
|
302
|
+
|
|
303
|
+
// ---- the replay ----
|
|
304
|
+
out();
|
|
305
|
+
rule(`Replayed on your ${plural(sim.total, 'agent PR')}`);
|
|
306
|
+
out();
|
|
307
|
+
fact(`${fmt(sim.fast)} fast track`, `${sim.fast_pct}% · no human in the loop · ${hrs(sim.hours_saved)} of waiting removed`, C.mint);
|
|
308
|
+
fact(`${fmt(sim.human)} to a human`, `${Math.round(100 - sim.fast_pct)}% · with Hud's verdict as context`, C.amber);
|
|
309
|
+
fact(`${sim.agreement_pct}% agree`, `same call as your reviewers made`);
|
|
310
|
+
fact(sim.fast_judged ? `${fmt(sim.fast_unsafe)} of ${fmt(sim.fast_judged)}` : 'too recent', `fast-tracked, then reverted or rewritten within ${SAFE_DAYS} days`, sim.fast_unsafe ? C.amber : C.mint);
|
|
311
|
+
await sleep(500);
|
|
312
|
+
|
|
313
|
+
// ---- three examples a side, the most reassuring first ----
|
|
314
|
+
const quiet = (p) => p.review === 'rubber_stamp' || p.review === 'no_human';
|
|
315
|
+
const scoreF = (p) => (p.safe === 1 ? 2 : p.safe === null && quiet(p) ? 1 : 0) * 1e4 + (p.waitHours || 0);
|
|
316
|
+
const scoreH = (p) => (p.outcome === 'reverted' ? 3 : p.review === 'human_changed_it' || p.safe === 0 ? 2 : 0) * 1e4 + (p.waitHours || 0);
|
|
317
|
+
const OUTW = { rubber_stamp: 'approved as-is', no_human: 'no human review', human_changed_it: 'a human changed it' };
|
|
318
|
+
const tag = (p) => (p.outcome === 'reverted' ? `${C.red}reverted${C.off}` : p.rewrittenBy ? `${C.amber}rewritten by #${p.rewrittenBy}${C.off}` : p.safe === 1 ? `${C.mint}held ${SAFE_DAYS} d${C.off}` : `${C.dim}too recent${C.off}`);
|
|
319
|
+
const show = (title, list, c) => {
|
|
320
|
+
out();
|
|
321
|
+
out(` ${c}${title}${C.off} ${C.dim}· ${list.length === 1 ? '1 PR' : `${fmt(list.length)} PRs`}${list.length > 3 ? ', the first 3' : ''}${C.off}`);
|
|
322
|
+
const tw = Math.max(24, W - 4 - 7 - 34);
|
|
323
|
+
for (const p of list.slice(0, 3)) {
|
|
324
|
+
const what = `${OUTW[p.review] || OUTW[p.outcome] || ''}${p.waitHours !== null ? `, ${hrs(p.waitHours)}` : ''}`;
|
|
325
|
+
out(` ${C.dim}#${String(p.number).padEnd(5)}${C.off} ${padR(cut(p.title, tw), tw)} ${C.dim}${what}${C.off} · ${tag(p)}`);
|
|
326
|
+
}
|
|
327
|
+
};
|
|
328
|
+
show('Would fast track', sim.prs.filter((p) => p.track === 'fast').sort((a, b) => scoreF(b) - scoreF(a)), C.mint);
|
|
329
|
+
show('Would send to a human', sim.prs.filter((p) => p.track === 'human').sort((a, b) => scoreH(b) - scoreH(a)), C.amber);
|
|
330
|
+
await sleep(900);
|
|
331
|
+
|
|
332
|
+
// ---- the production hook: real numbers from this repo, no projection ----
|
|
333
|
+
const secondLook = sim.second_look, unsafe = sim.fast_unsafe;
|
|
334
|
+
if (secondLook || unsafe) {
|
|
335
|
+
out();
|
|
336
|
+
rule('With production data');
|
|
337
|
+
out();
|
|
338
|
+
if (secondLook) { fact(`+${plural(secondLook, 'PR')}`, `this policy sends to a human were approved as-is anyway.`, C.mint); sub('The production reviewer clears those with evidence: hot paths, load, latency, reversibility.'); }
|
|
339
|
+
if (unsafe) { fact(plural(unsafe, 'PR'), `fast-tracked, then reverted or rewritten after merge.`, C.amber); sub('Production review holds PRs on hot paths and watches every deploy, with auto rollback.'); }
|
|
340
|
+
await sleep(900);
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
// ---- the handoff ----
|
|
344
|
+
const payload = toPayload(s, policy, sim);
|
|
345
|
+
const frag = b64url(gzipSync(Buffer.from(JSON.stringify(payload)), { level: 9 }));
|
|
346
|
+
const url = `${EDITOR}#d=${frag}`;
|
|
347
|
+
const opened = TTY && !flag('no-open', false) && openBrowser(url);
|
|
348
|
+
out();
|
|
349
|
+
rule('Next');
|
|
350
|
+
out();
|
|
351
|
+
out(` ${C.teal}➜${C.off} ${C.bold}${C.white}Edit the policy in the Hud editor, then activate it${C.off}${opened ? ` ${C.dim}· opening in your browser${C.off}` : ''}`);
|
|
352
|
+
out(` ${C.teal}${cut(url, W - 8)}${C.off}`);
|
|
353
|
+
out(` ${C.dim}${Math.round(url.length / 1024)} KB carried in the link itself; nothing was uploaded.${opened ? '' : ' Use --json to keep the full link.'}${C.off}`);
|
|
354
|
+
out();
|
|
355
|
+
out(` ${C.dim}No production signal was used. Production review joins the policy after you activate.${C.off}`);
|
|
356
|
+
out();
|
|
357
|
+
|
|
358
|
+
const pay = flag('payload', null);
|
|
359
|
+
if (pay) writeFileSync(pay, JSON.stringify(payload));
|
|
360
|
+
const file = flag('json', null);
|
|
361
|
+
if (file) { writeFileSync(file, JSON.stringify({ ...s, policy, simulation: sim, editor_url: url }, null, 2)); out(` wrote ${file}\n`); }
|
|
362
|
+
} catch (e) {
|
|
363
|
+
if (TTY) process.stdout.write('\x1b[K');
|
|
364
|
+
console.error(`\nhud-gateway: ${e.message}`);
|
|
365
|
+
process.exit(1);
|
|
366
|
+
}
|
package/core.js
ADDED
|
@@ -0,0 +1,566 @@
|
|
|
1
|
+
// hud-gateway core. Runs unchanged in Node (the CLI) and in the browser (/gateway).
|
|
2
|
+
// Everything goes through one injected `api(path)` that returns parsed GitHub REST JSON,
|
|
3
|
+
// so this file never sees a token. Read-only: GET requests only.
|
|
4
|
+
|
|
5
|
+
// ---------- detection rules: the whole "model", edit freely ----------
|
|
6
|
+
export const AGENT_BRANCH = /^(cursor|claude|codex|copilot|devin|jules|openhands|sweep|codegen|droid|factory|amp)[/\-_]/i;
|
|
7
|
+
export const AGENT_LOGIN = /^(copilot-swe-agent|devin-ai-integration|cursor|cursoragent|claude|claude-code|google-labs-jules|openhands-agent|openhands|codegen-sh|sweep-ai|chatgpt-codex-connector|factory-droid|amp-code)(\[bot\])?$/i;
|
|
8
|
+
export const AGENT_TEXT = /(generated with \[?claude code|co-authored-by:\s*claude|cursor\.com\/(agents|background-agent)|co-authored-by:\s*cursor ?agent|cursoragent@cursor\.com|chatgpt\.com\/codex|co-authored-by:\s*(codex|copilot|devin|openhands|jules)|devin\.ai\/sessions|app\.devin\.ai|noreply@anthropic\.com|copilot-swe-agent|openhands@all-hands\.dev)/i;
|
|
9
|
+
export const DEP_BOT = /^(dependabot|renovate|github-actions|snyk-bot|mergify|release-please|semantic-release-bot|allcontributors|imgbot|pre-commit-ci|depfu|greenkeeper)(\[bot\])?$/i;
|
|
10
|
+
export const DOCS_TESTS = /(^|\/)(docs?|documentation|__tests__|tests?|spec|e2e|fixtures|__snapshots__|\.changeset)(\/|$)|\.(md|mdx|rst|txt|snap)$|\.(test|spec)\.[cm]?[jt]sx?$|_test\.(go|py|rb)$|(^|\/)test_[^/]+\.py$|Tests?\.(java|kt|cs)$/i;
|
|
11
|
+
const isBot = (u) => !!u && (u.type === 'Bot' || /\[bot\]$/i.test(u.login || ''));
|
|
12
|
+
|
|
13
|
+
const REVIEWER_NAMES = [
|
|
14
|
+
[/^coderabbit/i, 'CodeRabbit'], [/^cursor(\[bot\])?$/i, 'Cursor Bugbot'], [/^copilot-pull-request-reviewer/i, 'Copilot'],
|
|
15
|
+
[/qodo|codium/i, 'Qodo'], [/^claude/i, 'Claude'], [/^greptile/i, 'Greptile'], [/^graphite/i, 'Graphite'],
|
|
16
|
+
[/^sourcery/i, 'Sourcery'], [/^ellipsis/i, 'Ellipsis'], [/^sonar/i, 'Sonar'],
|
|
17
|
+
];
|
|
18
|
+
export const reviewerName = (login) => (REVIEWER_NAMES.find(([rx]) => rx.test(login)) || [null, null])[1];
|
|
19
|
+
|
|
20
|
+
const CRITICAL = [
|
|
21
|
+
{ key: 'migrations', label: 'Database migrations', rx: /(^|\/)(migrations?|db\/migrate|alembic|flyway|liquibase)(\/|$)/i, ext: ['**/*.sql'] },
|
|
22
|
+
{ key: 'schema', label: 'Schemas and public contracts', rx: /(^|\/)(schema\.(prisma|graphql|sql)|openapi[^/]*|swagger[^/]*)$|\.proto$/i, ext: ['**/*.proto', '**/schema.prisma'] },
|
|
23
|
+
{ key: 'auth', label: 'Auth and permissions', rx: /(^|\/)(auth|authn|authz|oauth|sso|permissions?|rbac|iam)(\/|$)/i, ext: [] },
|
|
24
|
+
{ key: 'payments', label: 'Payments and billing', rx: /(^|\/)(payments?|billing|checkout|invoic\w*|stripe|ledger)(\/|$)/i, ext: [] },
|
|
25
|
+
{ key: 'iac', label: 'Infrastructure and CI', rx: /(^|\/)(terraform|helm|k8s|kubernetes|pulumi|cloudformation)(\/|$)|(^|\/)\.github\/workflows(\/|$)/i, ext: ['**/*.tf', '**/Dockerfile'] },
|
|
26
|
+
];
|
|
27
|
+
|
|
28
|
+
const FIX_TITLE = /\b(fix|fixes|fixed|hotfix|bugfix|repair|patch|regression|broke|broken|revert)\b/i;
|
|
29
|
+
|
|
30
|
+
// ---------- small helpers ----------
|
|
31
|
+
export const pct = (a, b) => (b ? Math.round((1000 * a) / b) / 10 : 0);
|
|
32
|
+
const median = (xs) => { if (!xs.length) return 0; const s = [...xs].sort((a, b) => a - b); const m = s.length >> 1; return s.length % 2 ? s[m] : (s[m - 1] + s[m]) / 2; };
|
|
33
|
+
const round1 = (x) => Math.round(x * 10) / 10;
|
|
34
|
+
const ms = (d) => new Date(d).getTime();
|
|
35
|
+
|
|
36
|
+
export function globToRegex(glob) {
|
|
37
|
+
const g = glob.trim().replace(/^\//, '');
|
|
38
|
+
let rx = '';
|
|
39
|
+
for (let i = 0; i < g.length; i++) {
|
|
40
|
+
const c = g[i];
|
|
41
|
+
if (c === '*') {
|
|
42
|
+
if (g[i + 1] === '*') { rx += '.*'; i++; if (g[i + 1] === '/') i++; } else rx += '[^/]*';
|
|
43
|
+
} else if (c === '?') rx += '[^/]';
|
|
44
|
+
else rx += c.replace(/[.+^${}()|[\]\\]/g, '\\$&');
|
|
45
|
+
}
|
|
46
|
+
if (g.endsWith('/')) rx += '.*';
|
|
47
|
+
return new RegExp(`^${rx}$`, 'i');
|
|
48
|
+
}
|
|
49
|
+
const matchAny = (globs, path) => globs.some((g) => { try { return globToRegex(g).test(path); } catch { return false; } });
|
|
50
|
+
|
|
51
|
+
// run `fn` over items with a concurrency cap and a requests-per-second cap shared through `gate`
|
|
52
|
+
async function pool(items, n, fn, onTick) {
|
|
53
|
+
const out = new Array(items.length);
|
|
54
|
+
let i = 0, done = 0;
|
|
55
|
+
await Promise.all(Array.from({ length: Math.max(1, Math.min(n, items.length)) }, async () => {
|
|
56
|
+
while (i < items.length) {
|
|
57
|
+
const k = i++;
|
|
58
|
+
out[k] = await fn(items[k], k);
|
|
59
|
+
done++;
|
|
60
|
+
if (onTick) onTick(done, items.length);
|
|
61
|
+
}
|
|
62
|
+
}));
|
|
63
|
+
return out;
|
|
64
|
+
}
|
|
65
|
+
function throttled(api, rps) {
|
|
66
|
+
if (!rps) return api;
|
|
67
|
+
let next = 0;
|
|
68
|
+
return async (path) => {
|
|
69
|
+
const now = Date.now();
|
|
70
|
+
const at = Math.max(now, next);
|
|
71
|
+
next = at + 1000 / rps;
|
|
72
|
+
if (at > now) await new Promise((r) => setTimeout(r, at - now));
|
|
73
|
+
return api(path);
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// ---------- the backtest ----------
|
|
78
|
+
// opts: { days=90, maxPrs=5000, concurrency=8, rps=0, files=true, onProgress({phase, done, total}) }
|
|
79
|
+
export async function runBacktest(slug, rawApi, opts = {}) {
|
|
80
|
+
const { days = 90, maxPrs = 5000, concurrency = 8, rps = 0, files = true, onProgress = () => {}, onRow = null } = opts;
|
|
81
|
+
const api = throttled(rawApi, rps);
|
|
82
|
+
const since = new Date(Date.now() - days * 864e5);
|
|
83
|
+
const repo = await api(`repos/${slug}`);
|
|
84
|
+
const base = repo.default_branch;
|
|
85
|
+
|
|
86
|
+
onProgress({ phase: 'list', done: 0, total: 0 });
|
|
87
|
+
const prs = [];
|
|
88
|
+
for (let page = 1; prs.length < maxPrs; page++) {
|
|
89
|
+
const batch = await api(`repos/${slug}/pulls?state=closed&base=${encodeURIComponent(base)}&sort=updated&direction=desc&per_page=100&page=${page}`);
|
|
90
|
+
if (!batch.length) break;
|
|
91
|
+
for (const p of batch) if (p.merged_at && new Date(p.merged_at) >= since && prs.length < maxPrs) prs.push(p);
|
|
92
|
+
onProgress({ phase: 'list', done: prs.length, total: 0 });
|
|
93
|
+
if (new Date(batch[batch.length - 1].updated_at) < since) break;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
const reverted = revertsIn(prs);
|
|
97
|
+
|
|
98
|
+
const rows = await pool(prs, concurrency, async (p) => {
|
|
99
|
+
const [reviews, commits] = await Promise.all([
|
|
100
|
+
api(`repos/${slug}/pulls/${p.number}/reviews?per_page=100`),
|
|
101
|
+
api(`repos/${slug}/pulls/${p.number}/commits?per_page=100`),
|
|
102
|
+
]);
|
|
103
|
+
const row = classify(p, reviews, commits, reverted);
|
|
104
|
+
if (row.kind === 'agent' && row.review === 'rubber_stamp') {
|
|
105
|
+
const events = await api(`repos/${slug}/issues/${p.number}/events?per_page=100`).catch(() => []);
|
|
106
|
+
row.waitHours = waitFor(p, commits, reviews, events.filter((e) => e.event === 'ready_for_review').map((e) => ms(e.created_at)));
|
|
107
|
+
}
|
|
108
|
+
if (files && (row.kind === 'agent' || FIX_TITLE.test(p.title))) {
|
|
109
|
+
const fl = await api(`repos/${slug}/pulls/${p.number}/files?per_page=100`).catch(() => []);
|
|
110
|
+
row.paths = fl.map((f) => f.filename);
|
|
111
|
+
}
|
|
112
|
+
if (onRow) onRow(row);
|
|
113
|
+
return row;
|
|
114
|
+
}, (done, total) => onProgress({ phase: 'read', done, total }));
|
|
115
|
+
|
|
116
|
+
markRewrites(rows);
|
|
117
|
+
return summarize(slug, base, days, since, rows);
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
// ---------- the fast path: GraphQL in two phases ----------
|
|
121
|
+
// Phase 1 lists merged PRs with the light fields (100 a page): enough to tell agent PRs from human ones
|
|
122
|
+
// and to find reverts. Phase 2 fetches reviews, files and ready-for-review events only for the PRs that
|
|
123
|
+
// need them (agent-written, and fix PRs for the rewrite check), 25 a request, a few requests in flight,
|
|
124
|
+
// newest first so the tally climbs while it reads. gql(query, variables) returns the parsed `data`.
|
|
125
|
+
export const LIST_QUERY = `query($owner:String!,$name:String!,$after:String){
|
|
126
|
+
repository(owner:$owner,name:$name){ defaultBranchRef{ name }
|
|
127
|
+
pullRequests(states:MERGED,first:100,orderBy:{field:UPDATED_AT,direction:DESC},after:$after){
|
|
128
|
+
pageInfo{ hasNextPage endCursor }
|
|
129
|
+
nodes{ number title body url mergedAt createdAt updatedAt headRefName baseRefName changedFiles
|
|
130
|
+
author{ login __typename } labels(first:10){ nodes{ name } }
|
|
131
|
+
commits(first:40){ nodes{ commit{ message committedDate author{ email user{ login } } parents{ totalCount } } } }
|
|
132
|
+
} } } }`;
|
|
133
|
+
const detailQuery = (numbers) => `query($owner:String!,$name:String!){ repository(owner:$owner,name:$name){ ${numbers.map((n) => `p${n}: pullRequest(number:${n}){ number
|
|
134
|
+
reviews(first:40){ nodes{ state submittedAt author{ login __typename } } }
|
|
135
|
+
files(first:80){ nodes{ path } }
|
|
136
|
+
timelineItems(itemTypes:[READY_FOR_REVIEW_EVENT],first:5){ nodes{ ... on ReadyForReviewEvent{ createdAt } } } }`).join('\n')} } }`;
|
|
137
|
+
export async function runBacktestGraphQL(slug, gql, opts = {}) {
|
|
138
|
+
const { days = 90, maxPrs = 5000, concurrency = 4, onProgress = () => {}, onRow = null } = opts;
|
|
139
|
+
const [owner, name] = slug.split('/');
|
|
140
|
+
const since = new Date(Date.now() - days * 864e5);
|
|
141
|
+
const prs = [];
|
|
142
|
+
let after = null, base = null;
|
|
143
|
+
for (;;) {
|
|
144
|
+
const d = await gql(LIST_QUERY, { owner, name, after });
|
|
145
|
+
const repo = d.repository;
|
|
146
|
+
if (!repo) throw new Error(`No access to ${slug}`);
|
|
147
|
+
base = base || repo.defaultBranchRef?.name || 'main';
|
|
148
|
+
const page = repo.pullRequests;
|
|
149
|
+
let stop = !page.pageInfo.hasNextPage;
|
|
150
|
+
for (const n of page.nodes) {
|
|
151
|
+
if (new Date(n.updatedAt) < since) stop = true;
|
|
152
|
+
if (!n.mergedAt || n.baseRefName !== base || new Date(n.mergedAt) < since || prs.length >= maxPrs) continue;
|
|
153
|
+
prs.push(n);
|
|
154
|
+
}
|
|
155
|
+
onProgress({ phase: 'list', done: prs.length, total: 0 });
|
|
156
|
+
if (stop || prs.length >= maxPrs) break;
|
|
157
|
+
after = page.pageInfo.endCursor;
|
|
158
|
+
}
|
|
159
|
+
// normalize to the REST shapes classify() reads
|
|
160
|
+
const norm = prs.map((n) => ({
|
|
161
|
+
p: { number: n.number, title: n.title, body: n.body, html_url: n.url, merged_at: n.mergedAt, created_at: n.createdAt,
|
|
162
|
+
user: { login: n.author?.login || 'ghost', type: n.author?.__typename === 'Bot' ? 'Bot' : 'User' }, head: { ref: n.headRefName },
|
|
163
|
+
labels: n.labels.nodes },
|
|
164
|
+
commits: n.commits.nodes.map((c) => ({ commit: { message: c.commit.message, author: { email: c.commit.author?.email || '' }, committer: { date: c.commit.committedDate } }, author: c.commit.author?.user ? { login: c.commit.author.user.login } : null, parents: Array.from({ length: c.commit.parents.totalCount }) })),
|
|
165
|
+
changedFiles: n.changedFiles, reviews: [], paths: null, ready: [],
|
|
166
|
+
}));
|
|
167
|
+
const reverted = revertsIn(norm.map((x) => x.p));
|
|
168
|
+
// a first pass with no reviews says which PRs are agent-written; those and fix PRs get the detail fetch
|
|
169
|
+
const need = norm.filter((x) => classify(x.p, [], x.commits, reverted).kind === 'agent' || FIX_TITLE.test(x.p.title));
|
|
170
|
+
need.sort((a, b) => ms(b.p.merged_at) - ms(a.p.merged_at));
|
|
171
|
+
const batches = [];
|
|
172
|
+
for (let i = 0; i < need.length; i += 25) batches.push(need.slice(i, i + 25));
|
|
173
|
+
const byNumber = new Map(norm.map((x) => [x.p.number, x]));
|
|
174
|
+
const rows = new Map();
|
|
175
|
+
let done = 0;
|
|
176
|
+
onProgress({ phase: 'read', done: 0, total: need.length });
|
|
177
|
+
const finish = (x) => {
|
|
178
|
+
const row = classify(x.p, x.reviews, x.commits, reverted);
|
|
179
|
+
if (row.kind === 'agent' && row.review === 'rubber_stamp') row.waitHours = waitFor(x.p, x.commits, x.reviews, x.ready);
|
|
180
|
+
row.paths = x.paths;
|
|
181
|
+
rows.set(x.p.number, row);
|
|
182
|
+
if (onRow) onRow(row);
|
|
183
|
+
};
|
|
184
|
+
await pool(batches, concurrency, async (batch) => {
|
|
185
|
+
const d = await gql(detailQuery(batch.map((x) => x.p.number)), { owner, name });
|
|
186
|
+
for (const x of batch) {
|
|
187
|
+
const n = d.repository[`p${x.p.number}`];
|
|
188
|
+
if (!n) continue;
|
|
189
|
+
x.reviews = n.reviews.nodes.map((r) => ({ state: r.state, submitted_at: r.submittedAt, user: r.author ? { login: r.author.login, type: r.author.__typename === 'Bot' ? 'Bot' : 'User' } : null }));
|
|
190
|
+
x.paths = n.files.nodes.map((f) => f.path);
|
|
191
|
+
x.ready = n.timelineItems.nodes.map((e) => ms(e.createdAt));
|
|
192
|
+
finish(x);
|
|
193
|
+
done++;
|
|
194
|
+
}
|
|
195
|
+
onProgress({ phase: 'read', done, total: need.length });
|
|
196
|
+
});
|
|
197
|
+
for (const x of norm) if (!rows.has(x.p.number)) { const row = classify(x.p, [], x.commits, reverted); rows.set(x.p.number, row); }
|
|
198
|
+
const all = norm.map((x) => rows.get(x.p.number));
|
|
199
|
+
markRewrites(all);
|
|
200
|
+
return summarize(slug, base, days, since, all);
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
// reverts: a merged PR with "revert" in its title that points at #N (body, title, or quoted title)
|
|
204
|
+
function revertsIn(prs) {
|
|
205
|
+
const reverted = new Set();
|
|
206
|
+
const byTitle = new Map(prs.map((p) => [p.title.trim(), p.number]));
|
|
207
|
+
for (const p of prs) {
|
|
208
|
+
if (!/\brevert\b/i.test(p.title)) continue;
|
|
209
|
+
const m = (p.body || '').match(/reverts?\s+(?:[\w.-]+\/[\w.-]+)?#(\d+)/i) || p.title.match(/\(#(\d+)\)/);
|
|
210
|
+
const q = p.title.match(/revert\s+"(.+)"\s*$/i);
|
|
211
|
+
const n = m ? Number(m[1]) : q && byTitle.get(q[1].trim());
|
|
212
|
+
if (n && n !== p.number) reverted.add(n);
|
|
213
|
+
}
|
|
214
|
+
return reverted;
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
// what people did on one PR, from its reviews and commits (REST or GraphQL shapes, normalized by the caller)
|
|
218
|
+
function classify(p, reviews, commits, reverted) {
|
|
219
|
+
const commitText = commits.map((c) => `${c.commit.message}\n${c.commit.author?.email || ''}\n${c.author?.login || ''}`).join('\n');
|
|
220
|
+
const why = AGENT_BRANCH.test(p.head.ref) ? 'branch'
|
|
221
|
+
: AGENT_LOGIN.test(p.user.login) ? 'author'
|
|
222
|
+
: AGENT_TEXT.test(p.body || '') ? 'pr-body'
|
|
223
|
+
: AGENT_TEXT.test(commitText) || commits.some((c) => AGENT_LOGIN.test(c.author?.login || '')) ? 'commits' : null;
|
|
224
|
+
const kind = why ? 'agent' : DEP_BOT.test(p.user.login) || isBot(p.user) ? 'automation' : 'human';
|
|
225
|
+
const human = reviews.filter((r) => r.user && !isBot(r.user) && r.user.login !== p.user.login && r.state !== 'PENDING' && r.submitted_at);
|
|
226
|
+
const bots = {};
|
|
227
|
+
for (const r of reviews) if (isBot(r.user)) (bots[r.user.login] ||= []).push(r.state);
|
|
228
|
+
const firstHuman = human[0];
|
|
229
|
+
const firstApproval = human.find((r) => r.state === 'APPROVED');
|
|
230
|
+
const feedback = human.some((r) => r.state === 'CHANGES_REQUESTED' || r.state === 'COMMENTED');
|
|
231
|
+
const real = commits.filter((c) => (c.parents || []).length < 2);
|
|
232
|
+
const changedAfterReview = firstHuman ? real.some((c) => ms(c.commit.committer.date) > ms(firstHuman.submitted_at)) : false;
|
|
233
|
+
// review: what people did before merge. outcome: the same, except a revert wins.
|
|
234
|
+
const review = !human.length ? 'no_human'
|
|
235
|
+
: feedback || changedAfterReview ? 'human_changed_it'
|
|
236
|
+
: firstApproval ? 'rubber_stamp' : 'human_changed_it';
|
|
237
|
+
const outcome = reverted.has(p.number) ? 'reverted' : review;
|
|
238
|
+
return {
|
|
239
|
+
number: p.number, title: p.title, url: p.html_url, author: p.user.login, branch: p.head.ref, merged_at: p.merged_at,
|
|
240
|
+
labels: (p.labels || []).map((l) => l.name), kind, why, review, outcome, waitHours: null, bots, paths: null,
|
|
241
|
+
refs: [...new Set(Array.from(`${p.title}\n${p.body || ''}`.matchAll(/#(\d+)\b/g), (m) => Number(m[1])))].filter((n) => n !== p.number),
|
|
242
|
+
};
|
|
243
|
+
}
|
|
244
|
+
// wait = first human approval minus the moment the PR was final and ready (last push or ready-for-review)
|
|
245
|
+
function waitFor(p, commits, reviews, readyTimes) {
|
|
246
|
+
const human = reviews.filter((r) => r.user && !isBot(r.user) && r.user.login !== p.user.login && r.state !== 'PENDING' && r.submitted_at);
|
|
247
|
+
const firstApproval = human.find((r) => r.state === 'APPROVED');
|
|
248
|
+
if (!firstApproval) return null;
|
|
249
|
+
const t = ms(firstApproval.submitted_at);
|
|
250
|
+
const real = commits.filter((c) => (c.parents || []).length < 2);
|
|
251
|
+
const start = Math.max(ms(p.created_at), ...[...readyTimes, ...real.map((c) => ms(c.commit.committer.date))].filter((x) => x <= t));
|
|
252
|
+
return Math.max(0, (t - start) / 36e5);
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
// A PR was "rewritten" when a later merged PR, within SAFE_DAYS, reads like a fix and either names it
|
|
256
|
+
// (#N in its title or body) or touches at least half of its non-test files. Together with reverts this is
|
|
257
|
+
// the defensive side of the backtest: did the approvals that changed nothing let anything bad through?
|
|
258
|
+
// Deliberately conservative: a one-line fix in a hot file does not count against every PR that touched it.
|
|
259
|
+
export const SAFE_DAYS = 14;
|
|
260
|
+
export const REVIEW_MIN = 20;
|
|
261
|
+
export function markRewrites(rows) {
|
|
262
|
+
const byTime = [...rows].filter((r) => r.merged_at).sort((a, b) => ms(a.merged_at) - ms(b.merged_at));
|
|
263
|
+
const fixes = byTime.filter((r) => FIX_TITLE.test(r.title) && r.paths && r.paths.length);
|
|
264
|
+
// files that most PRs touch (a lockfile, a changelog, a built bundle) say nothing about overlap
|
|
265
|
+
const seen = {};
|
|
266
|
+
for (const r of byTime) for (const p of new Set(r.paths || [])) seen[p] = (seen[p] || 0) + 1;
|
|
267
|
+
const hot = (p) => seen[p] >= Math.max(5, byTime.length * 0.3);
|
|
268
|
+
for (const r of byTime) {
|
|
269
|
+
r.rewrittenBy = null;
|
|
270
|
+
if (r.outcome === 'reverted' || !r.paths || !r.paths.length) continue;
|
|
271
|
+
const mine = new Set(r.paths.filter((p) => !DOCS_TESTS.test(p) && !hot(p)));
|
|
272
|
+
if (!mine.size) continue;
|
|
273
|
+
const t0 = ms(r.merged_at), t1 = t0 + SAFE_DAYS * 864e5;
|
|
274
|
+
const f = fixes.find((x) => x.number !== r.number && ms(x.merged_at) > t0 && ms(x.merged_at) <= t1
|
|
275
|
+
&& ((x.refs || []).includes(r.number) || x.paths.filter((p) => mine.has(p)).length * 2 >= mine.size));
|
|
276
|
+
if (f) r.rewrittenBy = f.number;
|
|
277
|
+
}
|
|
278
|
+
const now = Date.now();
|
|
279
|
+
for (const r of rows) {
|
|
280
|
+
const quiet = (r.review || r.outcome) === 'rubber_stamp' || (r.review || r.outcome) === 'no_human';
|
|
281
|
+
// 1 = held up for SAFE_DAYS, 0 = reverted or rewritten, null = merged too recently to know
|
|
282
|
+
r.safe = !quiet ? null : r.outcome === 'reverted' || r.rewrittenBy ? 0 : now - ms(r.merged_at) >= SAFE_DAYS * 864e5 ? 1 : null;
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
export function summarize(slug, base, days, since, rows) {
|
|
287
|
+
const agent = rows.filter((r) => r.kind === 'agent');
|
|
288
|
+
const by = (o) => agent.filter((r) => r.outcome === o);
|
|
289
|
+
const stamp = agent.filter((r) => (r.review || r.outcome) === 'rubber_stamp');
|
|
290
|
+
const waits = stamp.map((r) => r.waitHours).filter((x) => x !== null);
|
|
291
|
+
const botCount = {};
|
|
292
|
+
for (const r of agent) for (const b of Object.keys(r.bots || {})) botCount[b] = (botCount[b] || 0) + 1;
|
|
293
|
+
const reviewers = Object.entries(botCount)
|
|
294
|
+
.filter(([, n]) => n >= Math.max(3, agent.length * 0.1)).sort((a, b) => b[1] - a[1])
|
|
295
|
+
.map(([login, n]) => ({ login, name: reviewerName(login) || 'Custom', share_pct: pct(n, agent.length) }));
|
|
296
|
+
const quiet = agent.filter((r) => (r.review || r.outcome) === 'rubber_stamp' || (r.review || r.outcome) === 'no_human');
|
|
297
|
+
const judged = quiet.filter((r) => r.safe !== null);
|
|
298
|
+
const held = judged.filter((r) => r.safe === 1);
|
|
299
|
+
const longest = stamp.filter((r) => r.waitHours !== null).sort((a, b) => b.waitHours - a.waitHours)[0] || null;
|
|
300
|
+
const hoursSaved = (xs) => Math.round(xs.reduce((a, r) => a + (r.waitHours || 0), 0));
|
|
301
|
+
return {
|
|
302
|
+
repo: slug, base, mode: 'api', days, since: new Date(since).toISOString().slice(0, 10),
|
|
303
|
+
merged_prs: rows.length,
|
|
304
|
+
agent_prs: agent.length, agent_share_pct: pct(agent.length, rows.length),
|
|
305
|
+
detected_by: agent.reduce((a, r) => ((a[r.why] = (a[r.why] || 0) + 1), a), {}),
|
|
306
|
+
outcomes: { rubber_stamp: stamp.length, no_human: quiet.length - stamp.length, human_changed_it: agent.length - quiet.length, reverted: by('reverted').length },
|
|
307
|
+
safe_no_human_pct: pct(quiet.length, agent.length),
|
|
308
|
+
rubber_stamp_pct: pct(stamp.length, agent.length),
|
|
309
|
+
wait_hours_total: Math.round(waits.reduce((a, b) => a + b, 0)),
|
|
310
|
+
wait_hours_median: round1(median(waits)),
|
|
311
|
+
longest_wait: longest ? { number: longest.number, title: longest.title, url: longest.url, hours: round1(longest.waitHours) } : null,
|
|
312
|
+
// defensive: of the PRs that merged with a rubber stamp or no human review, old enough to judge,
|
|
313
|
+
// how many were not reverted or rewritten within SAFE_DAYS
|
|
314
|
+
safe_days: SAFE_DAYS,
|
|
315
|
+
quiet_prs: quiet.length,
|
|
316
|
+
quiet_judged: judged.length, quiet_held: held.length, quiet_held_pct: pct(held.length, judged.length),
|
|
317
|
+
quiet_rewritten: judged.filter((r) => r.rewrittenBy).length, quiet_reverted: judged.filter((r) => r.outcome === 'reverted').length,
|
|
318
|
+
// estimate: REVIEW_MIN of a reviewer's attention per rubber stamp
|
|
319
|
+
review_min: REVIEW_MIN, review_hours_est: Math.round((stamp.length * REVIEW_MIN) / 60),
|
|
320
|
+
wait_hours_judged_safe: hoursSaved(held),
|
|
321
|
+
ai_reviewers: reviewers,
|
|
322
|
+
rows,
|
|
323
|
+
};
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
// ---------- draft a policy from what the repo already does ----------
|
|
327
|
+
// A policy is a plain list of rules. Every rule reads as one English sentence (ruleText) and is
|
|
328
|
+
// evaluated deterministically (evaluatePolicy). No model call anywhere.
|
|
329
|
+
export async function draftPolicy(slug, api, result) {
|
|
330
|
+
const base = result.base;
|
|
331
|
+
const rules = [];
|
|
332
|
+
let id = 1;
|
|
333
|
+
const add = (r) => rules.push({ id: `r${id++}`, on: true, ...r });
|
|
334
|
+
|
|
335
|
+
add({ kind: 'docs_tests', source: 'Hud defaults' });
|
|
336
|
+
add({ kind: 'title', words: ['do-not-merge', 'wip'], source: 'Hud defaults' });
|
|
337
|
+
|
|
338
|
+
// critical paths, found in the repository's own tree
|
|
339
|
+
const tree = await api(`repos/${slug}/git/trees/${encodeURIComponent(base)}?recursive=1`).catch(() => ({ tree: [] }));
|
|
340
|
+
const paths = (tree.tree || []).filter((t) => t.type === 'blob').map((t) => t.path);
|
|
341
|
+
for (const c of CRITICAL) {
|
|
342
|
+
const dirs = {};
|
|
343
|
+
for (const p of paths) {
|
|
344
|
+
if (DOCS_TESTS.test(p) || /(^|\/)(node_modules|vendor|dist|build)\//.test(p)) continue;
|
|
345
|
+
const m = p.match(c.rx);
|
|
346
|
+
if (!m) continue;
|
|
347
|
+
const end = m.index + m[0].length;
|
|
348
|
+
const pre = p.slice(0, end).replace(/\/$/, '');
|
|
349
|
+
const dir = /\.[\w-]+$/.test(pre.split('/').pop()) ? pre : `${pre}/**`;
|
|
350
|
+
dirs[dir] = (dirs[dir] || 0) + 1;
|
|
351
|
+
}
|
|
352
|
+
const top = Object.entries(dirs).sort((a, b) => b[1] - a[1]).slice(0, 6).map(([d]) => d);
|
|
353
|
+
const ext = c.ext.filter((g) => paths.some((p) => globToRegex(g).test(p)));
|
|
354
|
+
const globs = [...new Set([...top, ...ext])];
|
|
355
|
+
if (globs.length) add({ kind: 'paths', label: c.label, globs, source: 'your repository tree' });
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
// CODEOWNERS
|
|
359
|
+
for (const f of ['.github/CODEOWNERS', 'CODEOWNERS', 'docs/CODEOWNERS']) {
|
|
360
|
+
const c = await api(`repos/${slug}/contents/${f}?ref=${encodeURIComponent(base)}`).catch(() => null);
|
|
361
|
+
if (!c || !c.content) continue;
|
|
362
|
+
const text = decodeB64(c.content);
|
|
363
|
+
const owners = text.split('\n').map((l) => l.replace(/#.*/, '').trim()).filter(Boolean).map((l) => l.split(/\s+/)).filter((p) => p.length > 1)
|
|
364
|
+
.map(([pattern, ...who]) => ({ pattern, owners: who }));
|
|
365
|
+
const specific = owners.filter((o) => o.pattern !== '*');
|
|
366
|
+
if (specific.length) add({ kind: 'paths', label: 'Paths with a code owner', globs: specific.slice(0, 40).map((o) => codeownersGlob(o.pattern)), on: false, source: f });
|
|
367
|
+
break;
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
// AI reviewers already running
|
|
371
|
+
for (const r of result.ai_reviewers) add({ kind: 'bot', login: r.login, name: r.name, share_pct: r.share_pct, source: 'reviews on your recent PRs' });
|
|
372
|
+
|
|
373
|
+
// required checks and approvals from branch rules (falls back to checks seen on the branch head)
|
|
374
|
+
const br = await api(`repos/${slug}/rules/branches/${encodeURIComponent(base)}`).catch(() => null);
|
|
375
|
+
let checks = [];
|
|
376
|
+
let required = true;
|
|
377
|
+
if (Array.isArray(br)) for (const r of br) if (r.type === 'required_status_checks') checks.push(...(r.parameters?.required_status_checks || []).map((c) => c.context));
|
|
378
|
+
if (!checks.length) {
|
|
379
|
+
required = false;
|
|
380
|
+
const cr = await api(`repos/${slug}/commits/${encodeURIComponent(base)}/check-runs?per_page=100`).catch(() => null);
|
|
381
|
+
checks = [...new Set((cr?.check_runs || []).map((c) => c.name))];
|
|
382
|
+
}
|
|
383
|
+
if (checks.length) add({ kind: 'checks', checks: [...new Set(checks)].slice(0, 12), required, source: required ? 'your branch rules' : 'checks on your default branch' });
|
|
384
|
+
|
|
385
|
+
add({ kind: 'size', maxFiles: 40, source: 'Hud defaults' });
|
|
386
|
+
add({ kind: 'default', value: 'fast', source: 'Hud defaults' });
|
|
387
|
+
return { version: 1, repo: slug, base, drafted_at: new Date().toISOString(), rules };
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
function decodeB64(b64) {
|
|
391
|
+
const clean = b64.replace(/\s+/g, '');
|
|
392
|
+
if (typeof atob === 'function') return new TextDecoder().decode(Uint8Array.from(atob(clean), (c) => c.charCodeAt(0)));
|
|
393
|
+
return Buffer.from(clean, 'base64').toString('utf8');
|
|
394
|
+
}
|
|
395
|
+
function codeownersGlob(p) {
|
|
396
|
+
let g = p.replace(/^\//, '');
|
|
397
|
+
if (!p.includes('/') || (p.indexOf('/') === p.length - 1 && !p.startsWith('/'))) g = `**/${g}`;
|
|
398
|
+
if (g.endsWith('/')) g += '**';
|
|
399
|
+
else if (!/[*.]/.test(g.split('/').pop())) g += '/**';
|
|
400
|
+
return g;
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
export function ruleText(r) {
|
|
404
|
+
switch (r.kind) {
|
|
405
|
+
case 'docs_tests': return 'Docs and tests only: approve on green CI.';
|
|
406
|
+
case 'title': return `A title or label with ${r.words.map((w) => `"${w}"`).join(' or ')} needs a human.`;
|
|
407
|
+
case 'paths': return `${r.label || 'These paths'}: anything touching ${r.globs.slice(0, 3).join(', ')}${r.globs.length > 3 ? ` and ${r.globs.length - 3} more` : ''} needs a human.`;
|
|
408
|
+
case 'bot': return `${r.name && r.name !== 'Custom' ? r.name : r.login} must not request changes before Hud approves.`;
|
|
409
|
+
case 'checks': return `${r.required ? 'Required checks' : 'CI checks'} must pass: ${r.checks.slice(0, 4).join(', ')}${r.checks.length > 4 ? ` and ${r.checks.length - 4} more` : ''}.`;
|
|
410
|
+
case 'size': return `A PR touching more than ${r.maxFiles} files needs a human.`;
|
|
411
|
+
case 'default': return r.value === 'fast' ? 'Everything else: fast track, approve without another human.' : 'Everything else needs a human.';
|
|
412
|
+
default: return '';
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
export const ruleVerdict = (r) => ({ docs_tests: 'Approve', title: 'Human', paths: 'Human', bot: 'Gate', checks: 'Gate', size: 'Human', default: r.value === 'fast' ? 'Approve' : 'Human' })[r.kind];
|
|
416
|
+
|
|
417
|
+
// ---------- replay a policy over the backtested PRs ----------
|
|
418
|
+
// Returns where each agent-written PR would have gone, and how that compares with what people did.
|
|
419
|
+
export function evaluatePolicy(policy, result) {
|
|
420
|
+
const rules = policy.rules.filter((r) => r.on !== false);
|
|
421
|
+
const dflt = rules.find((r) => r.kind === 'default') || { value: 'human' };
|
|
422
|
+
const prs = result.rows.filter((r) => r.kind === 'agent').map((pr) => {
|
|
423
|
+
const paths = pr.paths || [];
|
|
424
|
+
const hay = `${pr.title} ${(pr.labels || []).join(' ')}`.toLowerCase();
|
|
425
|
+
let track = null, rule = null;
|
|
426
|
+
const set = (t, r) => { if (!track) { track = t; rule = r; } };
|
|
427
|
+
for (const r of rules) {
|
|
428
|
+
if (r.kind === 'title' && r.words.some((w) => w && hay.includes(w.toLowerCase()))) set('human', r);
|
|
429
|
+
if (r.kind === 'paths' && paths.some((p) => matchAny(r.globs, p))) set('human', r);
|
|
430
|
+
if (r.kind === 'size' && paths.length > r.maxFiles) set('human', r);
|
|
431
|
+
if (r.kind === 'bot' && (pr.bots?.[r.login] || []).includes('CHANGES_REQUESTED')) set('human', r);
|
|
432
|
+
}
|
|
433
|
+
const docs = rules.find((r) => r.kind === 'docs_tests');
|
|
434
|
+
if (!track && docs && paths.length && paths.every((p) => DOCS_TESTS.test(p))) set('fast', docs);
|
|
435
|
+
if (!track) set(dflt.value === 'fast' ? 'fast' : 'human', dflt);
|
|
436
|
+
const rv = pr.review || pr.outcome;
|
|
437
|
+
const safe = rv === 'rubber_stamp' || rv === 'no_human';
|
|
438
|
+
const verdict = track === 'fast'
|
|
439
|
+
? (pr.outcome === 'reverted' ? 'fast_reverted' : safe ? 'fast_agree' : 'fast_human_changed')
|
|
440
|
+
: (safe ? 'second_look' : 'hold_agree');
|
|
441
|
+
return { number: pr.number, title: pr.title, url: pr.url, outcome: pr.outcome, review: rv, waitHours: pr.waitHours, safe: pr.safe, rewrittenBy: pr.rewrittenBy || null, track, rule: rule.id, verdict };
|
|
442
|
+
});
|
|
443
|
+
const n = (v) => prs.filter((p) => p.verdict === v).length;
|
|
444
|
+
const fast = prs.filter((p) => p.track === 'fast');
|
|
445
|
+
const perRule = {};
|
|
446
|
+
for (const p of prs) perRule[p.rule] = (perRule[p.rule] || 0) + 1;
|
|
447
|
+
return {
|
|
448
|
+
total: prs.length,
|
|
449
|
+
fast: fast.length, fast_pct: pct(fast.length, prs.length),
|
|
450
|
+
human: prs.length - fast.length,
|
|
451
|
+
agreement_pct: pct(n('fast_agree') + n('hold_agree'), prs.length),
|
|
452
|
+
fast_agree: n('fast_agree'), fast_human_changed: n('fast_human_changed'), fast_reverted: n('fast_reverted'),
|
|
453
|
+
second_look: n('second_look'), hold_agree: n('hold_agree'),
|
|
454
|
+
// fast-tracked PRs that were reverted or rewritten within SAFE_DAYS (the defensive number for this policy)
|
|
455
|
+
fast_unsafe: fast.filter((p) => p.safe === 0).length,
|
|
456
|
+
fast_judged: fast.filter((p) => p.safe !== null).length,
|
|
457
|
+
review_hours_est: Math.round((fast.length * REVIEW_MIN) / 60),
|
|
458
|
+
hours_saved: Math.round(fast.reduce((a, p) => a + (p.waitHours || 0), 0)),
|
|
459
|
+
perRule, prs,
|
|
460
|
+
};
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
|
|
464
|
+
// ---------- the handoff: CLI to the /gateway editor in a URL fragment ----------
|
|
465
|
+
// Only agent-written PRs travel, with the fields evaluatePolicy needs. Paths go through one dictionary.
|
|
466
|
+
// Nothing is sent anywhere: the fragment never reaches a server.
|
|
467
|
+
const OUT_CODE = { rubber_stamp: 's', no_human: 'n', human_changed_it: 'c', reverted: 'r' };
|
|
468
|
+
const REV_CODE = { rubber_stamp: 's', no_human: 'n', human_changed_it: 'c' };
|
|
469
|
+
const CODE_REV = Object.fromEntries(Object.entries(REV_CODE).map(([k, v]) => [v, k]));
|
|
470
|
+
const CODE_OUT = Object.fromEntries(Object.entries(OUT_CODE).map(([k, v]) => [v, k]));
|
|
471
|
+
export function toPayload(result, policy, sim) {
|
|
472
|
+
const dict = [], idx = new Map();
|
|
473
|
+
const ix = (p) => { if (!idx.has(p)) { idx.set(p, dict.length); dict.push(p); } return idx.get(p); };
|
|
474
|
+
const prs = result.rows.filter((r) => r.kind === 'agent').map((r) => [
|
|
475
|
+
r.number, r.title.slice(0, 80), OUT_CODE[r.outcome], r.waitHours === null ? null : round1(r.waitHours),
|
|
476
|
+
r.safe, REV_CODE[r.review || r.outcome] || 'c', r.rewrittenBy || 0, Object.entries(r.bots || {}).filter(([, st]) => st.includes('CHANGES_REQUESTED')).map(([b]) => b),
|
|
477
|
+
(r.paths || []).slice(0, 80).map(ix), (r.labels || []).slice(0, 6),
|
|
478
|
+
]);
|
|
479
|
+
const { rows, ...summary } = result;
|
|
480
|
+
return { v: 1, at: new Date().toISOString(), summary, policy, sim: sim ? { fast: sim.fast, total: sim.total } : null, dict, prs };
|
|
481
|
+
}
|
|
482
|
+
export function fromPayload(p) {
|
|
483
|
+
const rows = p.prs.map(([number, title, o, waitHours, safe, rv, rewrittenBy, changes, paths, labels]) => ({
|
|
484
|
+
number, title, url: `https://github.com/${p.summary.repo}/pull/${number}`, kind: 'agent', outcome: CODE_OUT[o], review: CODE_REV[rv], waitHours, safe, rewrittenBy: rewrittenBy || null,
|
|
485
|
+
bots: Object.fromEntries(changes.map((b) => [b, ['CHANGES_REQUESTED']])), paths: paths.map((i) => p.dict[i]), labels,
|
|
486
|
+
}));
|
|
487
|
+
return { result: { ...p.summary, rows }, policy: p.policy, at: p.at };
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
|
|
491
|
+
// ---------- the policy as YAML ----------
|
|
492
|
+
// The policy file is plain YAML and reads top to bottom: the first rule that matches decides. Each rule
|
|
493
|
+
// is one mapping with a `kind`. This is a small emitter and parser for exactly that shape; no library.
|
|
494
|
+
const yq = (v) => (typeof v === 'string' && /^[\w./*?@ -]*$/.test(v) && !/^(true|false|null|yes|no|on|off|~)$/i.test(v) && !/^[-\s*&!%@`|>?:]|\s$|^\d/.test(v) && v !== '' ? v : JSON.stringify(v));
|
|
495
|
+
export function toYaml(policy, autonomy = 'dry-run') {
|
|
496
|
+
const L = [];
|
|
497
|
+
L.push(`# Hud Merge Gateway policy for ${policy.repo}`, `# Rules run top to bottom; the first that matches decides where the PR goes.`, `# Edit here or at https://play.hudx.io/gateway`, '');
|
|
498
|
+
L.push(`version: ${policy.version || 1}`, `repo: ${yq(policy.repo)}`, `base: ${yq(policy.base)}`, `autonomy: ${autonomy}`, `drafted_at: ${yq(policy.drafted_at)}`, '', 'rules:');
|
|
499
|
+
for (const r of policy.rules) {
|
|
500
|
+
L.push(` # ${ruleText(r)}`);
|
|
501
|
+
L.push(` - kind: ${r.kind}`);
|
|
502
|
+
for (const [k, v] of Object.entries(r)) {
|
|
503
|
+
if (k === 'kind' || k === 'id' || k === 'source' || v === undefined || (k === 'on' && v !== false)) continue;
|
|
504
|
+
if (Array.isArray(v)) L.push(` ${k}: [${v.map(yq).join(', ')}]`);
|
|
505
|
+
else L.push(` ${k}: ${typeof v === 'string' ? yq(v) : v}`);
|
|
506
|
+
}
|
|
507
|
+
if (r.source) L.push(` source: ${yq(r.source)}`);
|
|
508
|
+
L.push('');
|
|
509
|
+
}
|
|
510
|
+
return L.join('\n');
|
|
511
|
+
}
|
|
512
|
+
const yv = (t) => {
|
|
513
|
+
t = t.trim();
|
|
514
|
+
if (t === '' || t === '~' || t === 'null') return null;
|
|
515
|
+
if (t === 'true') return true;
|
|
516
|
+
if (t === 'false') return false;
|
|
517
|
+
if (/^-?\d+(\.\d+)?$/.test(t)) return Number(t);
|
|
518
|
+
if (t.startsWith('[') && t.endsWith(']')) return t.slice(1, -1).split(/,(?=(?:[^"]*"[^"]*")*[^"]*$)/).map((x) => x.trim()).filter(Boolean).map(yv);
|
|
519
|
+
if (t.startsWith('"') && t.endsWith('"')) { try { return JSON.parse(t); } catch { return t.slice(1, -1); } }
|
|
520
|
+
if (t.startsWith("'") && t.endsWith("'")) return t.slice(1, -1);
|
|
521
|
+
return t;
|
|
522
|
+
};
|
|
523
|
+
export function fromYaml(text) {
|
|
524
|
+
const out = { rules: [] };
|
|
525
|
+
let cur = null, id = 1;
|
|
526
|
+
for (const raw of text.split('\n')) {
|
|
527
|
+
const line = raw.replace(/\s+#.*$|^\s*#.*$/, '').replace(/\s+$/, '');
|
|
528
|
+
if (!line.trim()) continue;
|
|
529
|
+
let m;
|
|
530
|
+
if ((m = line.match(/^(\w+):\s*(.*)$/))) { if (m[1] === 'rules') cur = null; else out[m[1]] = yv(m[2]); continue; }
|
|
531
|
+
if ((m = line.match(/^\s+-\s+(\w+):\s*(.*)$/))) { cur = { id: `r${id++}`, on: true }; cur[m[1]] = yv(m[2]); out.rules.push(cur); continue; }
|
|
532
|
+
if (cur && (m = line.match(/^\s+(\w+):\s*(.*)$/))) { cur[m[1]] = yv(m[2]); continue; }
|
|
533
|
+
throw new Error(`Cannot read line: ${raw.trim()}`);
|
|
534
|
+
}
|
|
535
|
+
for (const r of out.rules) {
|
|
536
|
+
if (!r.kind) throw new Error('A rule has no kind');
|
|
537
|
+
if (r.kind === 'paths' && !Array.isArray(r.globs)) throw new Error('A paths rule needs globs: [...]');
|
|
538
|
+
if (r.kind === 'title' && !Array.isArray(r.words)) throw new Error('A title rule needs words: [...]');
|
|
539
|
+
if (r.kind === 'checks' && !Array.isArray(r.checks)) throw new Error('A checks rule needs checks: [...]');
|
|
540
|
+
}
|
|
541
|
+
if (!out.rules.some((r) => r.kind === 'default')) out.rules.push({ id: `r${id++}`, on: true, kind: 'default', value: 'human', source: 'added: no default rule' });
|
|
542
|
+
return { version: out.version || 1, repo: out.repo, base: out.base, drafted_at: out.drafted_at, rules: out.rules, autonomy: out.autonomy };
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
|
|
546
|
+
// ---------- the hours, in human units ----------
|
|
547
|
+
// Working days at 8 h, and how many times the team could have watched a whole film series instead.
|
|
548
|
+
// Runtimes are the theatrical totals; the pick is stable for a given number so a rerun reads the same.
|
|
549
|
+
const SERIES = [
|
|
550
|
+
{ name: 'all eight Harry Potter films', hours: 19.7 },
|
|
551
|
+
{ name: 'the whole Star Wars saga, all nine', hours: 20.3 },
|
|
552
|
+
{ name: 'the Lord of the Rings extended trilogy', hours: 11.4 },
|
|
553
|
+
{ name: 'every Mission: Impossible film', hours: 17.8 },
|
|
554
|
+
{ name: 'the full Toy Story run', hours: 6.4 },
|
|
555
|
+
];
|
|
556
|
+
export function funTime(hours) {
|
|
557
|
+
const days = Math.round(hours / 8);
|
|
558
|
+
const fits = SERIES.filter((x) => hours / x.hours >= 2);
|
|
559
|
+
if (!fits.length) {
|
|
560
|
+
if (hours >= 2.3) return { days, line: `Enough to watch The Matrix ${Math.floor(hours / 2.3)} time${Math.floor(hours / 2.3) === 1 ? '' : 's'} and still wonder which pill.` };
|
|
561
|
+
return { days, line: null };
|
|
562
|
+
}
|
|
563
|
+
const pick = fits[Math.floor(hours) % fits.length];
|
|
564
|
+
const n = Math.floor(hours / pick.hours);
|
|
565
|
+
return { days, line: `Enough to watch ${pick.name} ${n.toLocaleString('en-US')} times.`, times: n, series: pick.name };
|
|
566
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,36 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "hud-gateway",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "How many hours your team spent approving agent-written PRs that were already fine, and the approvals policy that hands them back. Read-only, runs locally.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"bin": {
|
|
7
|
+
"hud-gateway": "bin/hud-gateway.mjs"
|
|
8
|
+
},
|
|
9
|
+
"files": [
|
|
10
|
+
"bin",
|
|
11
|
+
"core.js",
|
|
12
|
+
"sample.js",
|
|
13
|
+
"README.md"
|
|
14
|
+
],
|
|
15
|
+
"engines": {
|
|
16
|
+
"node": ">=18"
|
|
17
|
+
},
|
|
18
|
+
"license": "MIT",
|
|
19
|
+
"keywords": [
|
|
20
|
+
"github",
|
|
21
|
+
"pull-requests",
|
|
22
|
+
"code-review",
|
|
23
|
+
"ai-agents",
|
|
24
|
+
"approvals",
|
|
25
|
+
"merge",
|
|
26
|
+
"policy",
|
|
27
|
+
"hud"
|
|
28
|
+
],
|
|
29
|
+
"homepage": "https://play.hudx.io/gateway",
|
|
30
|
+
"repository": {
|
|
31
|
+
"type": "git",
|
|
32
|
+
"url": "git+https://github.com/code-hud/play-hud.git",
|
|
33
|
+
"directory": "packages/hud-gateway"
|
|
34
|
+
},
|
|
35
|
+
"author": "Hud <dev@hud.io>"
|
|
36
|
+
}
|
package/sample.js
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
// A seeded fake GitHub for `npx hud-gateway --sample`: a mid-size service repo where coding agents open
|
|
2
|
+
// most PRs, people rubber-stamp most of those, and a few get reverted. Deterministic, so demos repeat.
|
|
3
|
+
// Everything here is invented. It exists so the reveal can be shown or recorded without a token.
|
|
4
|
+
|
|
5
|
+
export const SAMPLE_SLUG = 'acme/checkout-platform';
|
|
6
|
+
|
|
7
|
+
function rng(seed) { let s = seed >>> 0; return () => { s = (s * 1664525 + 1013904223) >>> 0; return s / 4294967296; }; }
|
|
8
|
+
|
|
9
|
+
const AREAS = [
|
|
10
|
+
['services/checkout/src', 0.22], ['services/payments/src', 0.1], ['services/catalog/src', 0.16], ['services/auth/src', 0.06],
|
|
11
|
+
['apps/web/src', 0.2], ['packages/ui/src', 0.1], ['infra/terraform', 0.04], ['db/migrations', 0.04], ['docs', 0.08],
|
|
12
|
+
];
|
|
13
|
+
const TITLES = [
|
|
14
|
+
'Add idempotency key to order submit', 'Cache product variants per session', 'Retry webhook delivery with backoff', 'Fix rounding in cart totals',
|
|
15
|
+
'Extract address validation', 'Add rate limit to coupon lookup', 'Normalize phone numbers at signup', 'Remove dead feature flag checks',
|
|
16
|
+
'Batch inventory reads on the cart page', 'Tighten types in the pricing module', 'Handle empty line items in receipt email', 'Upgrade stripe client',
|
|
17
|
+
'Add tracing spans to fulfillment', 'Split checkout session reducer', 'Paginate order history', 'Migrate tax table to new schema',
|
|
18
|
+
'Dedupe analytics events on retry', 'Add missing index on orders.customer_id', 'Expose refund reason in API', 'Gate new address form behind flag',
|
|
19
|
+
'Log slow catalog queries', 'Fix timezone in delivery estimates', 'Harden JWT refresh path', 'Add Terraform for the new queue',
|
|
20
|
+
'Document the refund flow', 'Update README for local setup', 'Unit tests for coupon stacking', 'E2E test for guest checkout',
|
|
21
|
+
];
|
|
22
|
+
const HUMANS = ['dana', 'omri', 'lee', 'priya', 'sam'];
|
|
23
|
+
const BOTS = ['coderabbitai[bot]', 'cursor[bot]'];
|
|
24
|
+
|
|
25
|
+
export function sampleApi(opts = {}) {
|
|
26
|
+
const { prs: N = 182, days = 90, seed = 7 } = opts;
|
|
27
|
+
const R = rng(seed);
|
|
28
|
+
const pick = (xs) => xs[Math.floor(R() * xs.length)];
|
|
29
|
+
const now = Date.now();
|
|
30
|
+
const prs = [], detail = {};
|
|
31
|
+
let number = 2400;
|
|
32
|
+
const revertable = [];
|
|
33
|
+
for (let i = 0; i < N; i++) {
|
|
34
|
+
const n = number++;
|
|
35
|
+
const agent = R() < 0.68;
|
|
36
|
+
const mergedAt = now - R() * days * 864e5;
|
|
37
|
+
const area = (() => { let x = R(); for (const [a, w] of AREAS) { x -= w; if (x <= 0) return a; } return AREAS[0][0]; })();
|
|
38
|
+
const docs = area === 'docs' || R() < 0.08;
|
|
39
|
+
const nFiles = docs ? 1 + Math.floor(R() * 3) : 1 + Math.floor(R() * R() * 24);
|
|
40
|
+
const paths = Array.from({ length: nFiles }, (_, k) => docs ? `docs/${pick(['refunds', 'setup', 'api', 'runbook'])}-${k}.md` : `${area}/${pick(['order', 'cart', 'price', 'session', 'coupon', 'address', 'refund', 'inventory'])}${k ? k : ''}.${area.includes('terraform') ? 'tf' : area.includes('migrations') ? 'sql' : 'ts'}`);
|
|
41
|
+
if (R() < 0.15) paths.push(`${area.replace('/src', '')}/__tests__/${pick(['order', 'cart', 'price'])}.test.ts`);
|
|
42
|
+
const title = `${pick(TITLES)}${R() < 0.2 ? ` (${pick(['part 2', 'follow-up', 'v2'])})` : ''}`;
|
|
43
|
+
const created = mergedAt - (agent ? 2 + R() * 40 : 6 + R() * 90) * 36e5;
|
|
44
|
+
const author = agent ? 'cursoragent' : pick(HUMANS);
|
|
45
|
+
const headRef = agent ? `cursor/${title.toLowerCase().replace(/[^a-z0-9]+/g, '-').slice(0, 30)}` : `${author}/${n}`;
|
|
46
|
+
prs.push({ number: n, title, body: agent ? 'Made with Cursor Agent\n\ncursor.com/agents' : '', merged_at: new Date(mergedAt).toISOString(), created_at: new Date(created).toISOString(), updated_at: new Date(mergedAt).toISOString(), html_url: `https://github.com/${SAMPLE_SLUG}/pull/${n}`, user: { login: author, type: 'User' }, head: { ref: headRef }, labels: R() < 0.06 ? [{ name: 'wip' }] : [] });
|
|
47
|
+
// the review story
|
|
48
|
+
const reviews = [];
|
|
49
|
+
const bot = R() < 0.55 ? BOTS[0] : R() < 0.5 ? BOTS[1] : null;
|
|
50
|
+
if (bot) reviews.push({ user: { login: bot, type: 'Bot' }, state: R() < 0.12 ? 'CHANGES_REQUESTED' : 'COMMENTED', submitted_at: new Date(created + 0.3 * 36e5).toISOString() });
|
|
51
|
+
const path = R();
|
|
52
|
+
const reviewer = pick(HUMANS.filter((h) => h !== author));
|
|
53
|
+
let kind;
|
|
54
|
+
if (!agent) kind = path < 0.5 ? 'stamp' : 'changed';
|
|
55
|
+
else kind = path < 0.62 ? 'stamp' : path < 0.74 ? 'none' : 'changed';
|
|
56
|
+
const commits = [{ sha: `${n}a`, parents: [{}], commit: { message: title, author: { email: agent ? 'cursoragent@cursor.com' : `${author}@acme.dev` }, committer: { date: new Date(created - 36e5).toISOString() } }, author: { login: author } }];
|
|
57
|
+
if (kind === 'stamp') {
|
|
58
|
+
const wait = agent ? (R() < 0.7 ? 1 + R() * 9 : 10 + R() * 60) : 2 + R() * 30;
|
|
59
|
+
reviews.push({ user: { login: reviewer, type: 'User' }, state: 'APPROVED', submitted_at: new Date(created + wait * 36e5).toISOString() });
|
|
60
|
+
} else if (kind === 'changed') {
|
|
61
|
+
const t = created + (2 + R() * 20) * 36e5;
|
|
62
|
+
reviews.push({ user: { login: reviewer, type: 'User' }, state: R() < 0.5 ? 'CHANGES_REQUESTED' : 'COMMENTED', submitted_at: new Date(t).toISOString() });
|
|
63
|
+
commits.push({ sha: `${n}b`, parents: [{}], commit: { message: 'Address review', author: { email: `${author}@acme.dev` }, committer: { date: new Date(t + 3 * 36e5).toISOString() } }, author: { login: author } });
|
|
64
|
+
reviews.push({ user: { login: reviewer, type: 'User' }, state: 'APPROVED', submitted_at: new Date(t + 5 * 36e5).toISOString() });
|
|
65
|
+
}
|
|
66
|
+
detail[n] = { reviews, commits, files: paths.map((filename) => ({ filename })), events: [] };
|
|
67
|
+
if (agent && kind === 'stamp' && !docs && now - mergedAt > 20 * 864e5) revertable.push({ n, mergedAt, title, paths });
|
|
68
|
+
}
|
|
69
|
+
// four reverts and three rewrites of rubber-stamped agent PRs
|
|
70
|
+
const victims = revertable.sort(() => R() - 0.5).slice(0, 7);
|
|
71
|
+
victims.forEach((v, i) => {
|
|
72
|
+
const n = number++;
|
|
73
|
+
const at = v.mergedAt + (0.5 + R() * 9) * 864e5;
|
|
74
|
+
const revert = i < 4;
|
|
75
|
+
prs.push({ number: n, title: revert ? `Revert "${v.title}"` : `Fix ${v.title.toLowerCase()} regression`, body: revert ? `Reverts ${SAMPLE_SLUG}#${v.n}` : `Follow-up to #${v.n}`, merged_at: new Date(at).toISOString(), created_at: new Date(at - 36e5).toISOString(), updated_at: new Date(at).toISOString(), html_url: `https://github.com/${SAMPLE_SLUG}/pull/${n}`, user: { login: 'dana', type: 'User' }, head: { ref: `dana/${revert ? 'revert' : 'fix'}-${v.n}` }, labels: [] });
|
|
76
|
+
detail[n] = { reviews: [{ user: { login: 'lee', type: 'User' }, state: 'APPROVED', submitted_at: new Date(at - 0.5 * 36e5).toISOString() }], commits: [{ sha: `${n}a`, parents: [{}], commit: { message: 'fix', author: { email: 'dana@acme.dev' }, committer: { date: new Date(at - 36e5).toISOString() } }, author: { login: 'dana' } }], files: v.paths.map((filename) => ({ filename })), events: [] };
|
|
77
|
+
});
|
|
78
|
+
prs.sort((a, b) => new Date(b.updated_at) - new Date(a.updated_at));
|
|
79
|
+
|
|
80
|
+
const tree = { tree: [
|
|
81
|
+
...AREAS.filter(([a]) => a !== 'docs').flatMap(([a]) => ['order', 'cart', 'price', 'session', 'coupon', 'refund'].map((f) => ({ type: 'blob', path: `${a}/${f}.${a.includes('terraform') ? 'tf' : a.includes('migrations') ? 'sql' : 'ts'}` }))),
|
|
82
|
+
{ type: 'blob', path: 'services/payments/src/stripe/client.ts' }, { type: 'blob', path: 'services/auth/src/oauth/google.ts' },
|
|
83
|
+
{ type: 'blob', path: 'db/migrations/20260901_tax_table.sql' }, { type: 'blob', path: 'db/schema.prisma' }, { type: 'blob', path: '.github/workflows/ci.yml' },
|
|
84
|
+
{ type: 'blob', path: 'docs/refunds.md' }, { type: 'blob', path: 'README.md' },
|
|
85
|
+
] };
|
|
86
|
+
const codeowners = '# owners\n/services/payments/ @acme/payments\n/services/auth/ @acme/security\n/db/migrations/ @acme/data\n/infra/ @acme/platform\n';
|
|
87
|
+
// the same fake repo over GraphQL, for the CLI's fast path: answers LIST_QUERY pages and detail batches
|
|
88
|
+
const toNode = (p) => ({ number: p.number, title: p.title, body: p.body, url: p.html_url, mergedAt: p.merged_at, createdAt: p.created_at, updatedAt: p.updated_at,
|
|
89
|
+
headRefName: p.head.ref, baseRefName: 'main', changedFiles: detail[p.number].files.length, author: { login: p.user.login, __typename: p.user.type === 'Bot' ? 'Bot' : 'User' },
|
|
90
|
+
labels: { nodes: p.labels }, commits: { nodes: detail[p.number].commits.map((c) => ({ commit: { message: c.commit.message, committedDate: c.commit.committer.date, author: { email: c.commit.author.email, user: c.author ? { login: c.author.login } : null }, parents: { totalCount: c.parents.length } } })) } });
|
|
91
|
+
const gql = async (query, vars) => {
|
|
92
|
+
await new Promise((r) => setTimeout(r, 40));
|
|
93
|
+
if (query.includes('pullRequests(states:MERGED')) {
|
|
94
|
+
const start = vars.after ? Number(vars.after) : 0;
|
|
95
|
+
const nodes = prs.slice(start, start + 100).map(toNode);
|
|
96
|
+
return { repository: { defaultBranchRef: { name: 'main' }, pullRequests: { pageInfo: { hasNextPage: start + 100 < prs.length, endCursor: String(start + 100) }, nodes } } };
|
|
97
|
+
}
|
|
98
|
+
const out = {};
|
|
99
|
+
for (const m of query.matchAll(/p(\d+): pullRequest\(number:(\d+)\)/g)) {
|
|
100
|
+
const d = detail[m[2]];
|
|
101
|
+
out[`p${m[1]}`] = { number: Number(m[2]), reviews: { nodes: d.reviews.map((r) => ({ state: r.state, submittedAt: r.submitted_at, author: { login: r.user.login, __typename: r.user.type === 'Bot' ? 'Bot' : 'User' } })) },
|
|
102
|
+
files: { nodes: d.files.map((f) => ({ path: f.filename })) }, timelineItems: { nodes: [] } };
|
|
103
|
+
}
|
|
104
|
+
return { repository: out };
|
|
105
|
+
};
|
|
106
|
+
const api = async (path) => {
|
|
107
|
+
await new Promise((r) => setTimeout(r, 6));
|
|
108
|
+
if (path === `repos/${SAMPLE_SLUG}`) return { default_branch: 'main' };
|
|
109
|
+
let m;
|
|
110
|
+
if ((m = path.match(/\/pulls\?.*page=(\d+)/))) { const p = Number(m[1]); return prs.slice((p - 1) * 100, p * 100); }
|
|
111
|
+
if ((m = path.match(/\/pulls\/(\d+)\/reviews/))) return detail[m[1]].reviews;
|
|
112
|
+
if ((m = path.match(/\/pulls\/(\d+)\/commits/))) return detail[m[1]].commits;
|
|
113
|
+
if ((m = path.match(/\/pulls\/(\d+)\/files/))) return detail[m[1]].files;
|
|
114
|
+
if ((m = path.match(/\/issues\/(\d+)\/events/))) return detail[m[1]].events;
|
|
115
|
+
if (path.includes('/git/trees/')) return tree;
|
|
116
|
+
if (path.includes('CODEOWNERS')) return path.includes('.github/CODEOWNERS') ? { content: Buffer.from(codeowners).toString('base64') } : null;
|
|
117
|
+
if (path.includes('/rules/branches/')) return [{ type: 'required_status_checks', parameters: { required_status_checks: [{ context: 'ci / test' }, { context: 'ci / typecheck' }, { context: 'ci / lint' }] } }];
|
|
118
|
+
if (path.includes('/check-runs')) return { check_runs: [] };
|
|
119
|
+
throw new Error(`sample has no ${path}`);
|
|
120
|
+
};
|
|
121
|
+
api.gql = gql;
|
|
122
|
+
return api;
|
|
123
|
+
}
|