paseo-follow-up 2.3.0 → 2.4.0-beta.1
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/client/brief.tsx +7 -5
- package/client/header.tsx +18 -9
- package/client/home-list.tsx +3 -3
- package/client/home.tsx +3 -2
- package/client/merge-button.tsx +1 -1
- package/client/stacks.tsx +24 -2
- package/index.client.tsx +1 -1
- package/index.server.ts +42 -7
- package/package.json +2 -1
- package/server/agent-actions.ts +4 -3
- package/server/agent-hook.mjs +35 -6
- package/server/browser-bridge.ts +20 -2
- package/server/check-watches.ts +145 -0
- package/server/engine.ts +13 -2
- package/server/github.ts +15 -2
- package/server/hook-source.ts +35 -6
- package/server/mcp-source.ts +8 -5
- package/server/mcp.mjs +8 -5
- package/server/obligations.ts +18 -2
- package/server/pr-actions.ts +17 -11
- package/server/pr-owner.ts +30 -13
- package/server/pr-stats-gate.ts +102 -0
- package/server/pr-stats-store.ts +196 -0
- package/server/pr-stats-sync.ts +228 -0
- package/server/questions.ts +35 -8
- package/server/ranker.ts +3 -2
- package/server/wait-for-checks.ts +108 -0
- package/shared/activity.ts +2 -2
- package/shared/attention.ts +88 -15
- package/shared/brief.ts +16 -0
- package/shared/chat.ts +1 -1
- package/shared/check-watch.ts +129 -0
- package/shared/contracts.ts +10 -3
- package/shared/errors.ts +34 -0
- package/shared/home.ts +51 -13
- package/shared/model.ts +17 -2
- package/shared/poll.ts +9 -2
- package/shared/pr-actions.ts +61 -3
- package/shared/pr-stats-records.ts +169 -0
- package/shared/questions.ts +75 -0
- package/shared/queue.ts +1 -1
- package/shared/ranker.ts +3 -2
- package/shared/scale.ts +24 -0
- package/shared/status-invariants.ts +39 -1
- package/shared/task-status.ts +9 -2
package/server/pr-actions.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { STOP_WAIT_MS, settleWithin, type Deadline } from "./teardown";
|
|
2
2
|
import { randomUUID } from "node:crypto";
|
|
3
|
-
import { downstack, isGithubFlow, mergeBlockers, prActionBlocks, type ActionPlan, type BrowserPr, type MergeStage, type PrActionKind } from "../shared/pr-actions";
|
|
3
|
+
import { downstack, isGithubFlow, prRefs, mergeBlockers, prActionBlocks, type ActionPlan, type BrowserPr, type MergeStage, type PrActionKind } from "../shared/pr-actions";
|
|
4
4
|
import type { MergeMethod } from "../shared/pr-workflow";
|
|
5
5
|
import type { Workspace, Pr } from "../shared/model";
|
|
6
6
|
import { findWorkspace } from "./engine";
|
|
@@ -10,6 +10,7 @@ import { GraphiteWriteError, type Graphite } from "./graphite";
|
|
|
10
10
|
import { BrowserBridge } from "./browser-bridge";
|
|
11
11
|
import { allAssigned, configuredReviewers, noReviewers, reviewerLabel, sameLogin, withoutAuthor, type ReviewerEntry } from "../shared/reviewers";
|
|
12
12
|
import { chooseMethod, GithubWriteError, ReviewRequestError } from "./github";
|
|
13
|
+
import { errorText, plainError } from "../shared/errors";
|
|
13
14
|
|
|
14
15
|
function active(w: Workspace) {
|
|
15
16
|
if (!w.enable_tracking || w.archived) throw new Error("This workspace is not actively tracked.");
|
|
@@ -72,7 +73,7 @@ export class PrActions {
|
|
|
72
73
|
const readKey = `${w.id}:${identity(rows)}`;
|
|
73
74
|
if (!this.reads.has(readKey)) this.reads.set(readKey, this.read(rows).finally(() => this.reads.delete(readKey)));
|
|
74
75
|
try { return { browser, pr: (await this.reads.get(readKey)!).find(row => row.number === p.number) ?? null, error: null }; }
|
|
75
|
-
catch (error) { return { browser: this.browser.status(), pr: null, error: error instanceof Error ? error
|
|
76
|
+
catch (error) { return { browser: this.browser.status(), pr: null, error: error instanceof Error ? errorText(plainError(error)) : "Could not read Graphite state." }; }
|
|
76
77
|
}
|
|
77
78
|
async prepare(workspaceId: string, key: string, kind: PrActionKind): Promise<ActionPlan> {
|
|
78
79
|
const w = await this.fresh(workspaceId);
|
|
@@ -201,13 +202,15 @@ export class PrActions {
|
|
|
201
202
|
} else {
|
|
202
203
|
const reply = await this.browser.request(plan.kind, prs[0].repo, wire(prs));
|
|
203
204
|
state = reply.outcome === "completed" ? "submitted" : reply.outcome;
|
|
204
|
-
const changed = reply.applied
|
|
205
|
+
const changed = prRefs(reply.applied);
|
|
205
206
|
result = reply.outcome === "completed" ? `Merge when ready ${plan.kind === "enable_mwr" ? "enabled" : "disabled"} for ${changed}.` : `${changed ? `Changed ${changed}. ` : ""}${reply.error || "Graphite could not confirm every selected PR."}`;
|
|
206
207
|
}
|
|
207
208
|
} catch (error) {
|
|
208
209
|
state = (error instanceof GraphiteWriteError || error instanceof GithubWriteError) && error.uncertain ? "uncertain" : "failed";
|
|
209
|
-
result = error instanceof Error ? error
|
|
210
|
+
result = error instanceof Error ? errorText(plainError(error)) : `${via(prs)} action failed.`;
|
|
210
211
|
}
|
|
212
|
+
// The result crosses an RPC as textSchema (2000 chars): a long one ends in an ellipsis, it never fails the reply.
|
|
213
|
+
if (result.length > 2000) result = `${result.slice(0, 1999)}…`;
|
|
211
214
|
await this.store.mutate(s => {
|
|
212
215
|
const current = findWorkspace(s, w.id);
|
|
213
216
|
const action = current.prActions.find(a => a.id === id)!; action.state = state; action.result = result; if (state === "submitted" && merge) action.merge = merge;
|
|
@@ -233,15 +236,18 @@ export class PrActions {
|
|
|
233
236
|
private async githubExecute(kind: PrActionKind, prs: Pr[]): Promise<{ state: "submitted" | "failed" | "uncertain"; result: string; merge?: MergeStage }> {
|
|
234
237
|
const gh = this.github;
|
|
235
238
|
if (!gh.merge || !gh.autoMerge || !gh.retarget) throw new Error("GitHub merging isn't available here.");
|
|
236
|
-
|
|
237
|
-
const
|
|
239
|
+
// What happened so far, as numbers: said with prRefs, so a long stack's result stays one short paragraph.
|
|
240
|
+
const retargeted: number[] = [], merged: number[] = [], toggled: number[] = []; let queued: number | null = null;
|
|
241
|
+
const progress = () => [retargeted.length ? `Retargeted ${prRefs(retargeted)} to ${prs[0].snapshot!.trunk}.` : "", merged.length ? `Merged ${prRefs(merged)}.` : "",
|
|
242
|
+
queued !== null ? `Added #${queued} to the merge queue.` : "", toggled.length ? `Auto-merge ${kind === "enable_mwr" ? "on" : "off"} for ${prRefs(toggled)}.` : ""].filter(Boolean).join(" ");
|
|
243
|
+
const partial = (error: unknown) => { const message = error instanceof Error ? error.message : "GitHub action failed."; const done = progress(); return done ? `${done} Then: ${message}` : message; };
|
|
238
244
|
const method = (p: Pr) => chooseMethod(p.snapshot!.repoMerge, this.savedMethod(p.repo));
|
|
239
245
|
try {
|
|
240
246
|
if (kind === "merge") {
|
|
241
247
|
const queue = !!prs[0].snapshot!.repoMerge?.mergeQueue;
|
|
242
248
|
for (const [i, p] of prs.entries()) {
|
|
243
249
|
const s = p.snapshot!;
|
|
244
|
-
if (i > 0 && s.base !== s.trunk) { await gh.retarget(p, s.trunk);
|
|
250
|
+
if (i > 0 && s.base !== s.trunk) { await gh.retarget(p, s.trunk); retargeted.push(p.number); }
|
|
245
251
|
for (let attempt = 0; ; attempt++) {
|
|
246
252
|
try { await gh.merge(p, { method: method(p), head: s.head, mergeQueue: queue }); break; }
|
|
247
253
|
catch (error) {
|
|
@@ -250,16 +256,16 @@ export class PrActions {
|
|
|
250
256
|
await this.settle(3_000);
|
|
251
257
|
}
|
|
252
258
|
}
|
|
253
|
-
|
|
259
|
+
if (queue) queued = p.number; else merged.push(p.number);
|
|
254
260
|
if (queue) break; // The queue merges the rest in order once the first lands; GitHub retargets nothing yet.
|
|
255
261
|
}
|
|
256
|
-
return { state: "submitted", result:
|
|
262
|
+
return { state: "submitted", result: progress(), merge: queue ? "queued" : "merged" };
|
|
257
263
|
}
|
|
258
264
|
for (const p of prs) {
|
|
259
265
|
await gh.autoMerge(p, kind === "enable_mwr" ? { enable: true, method: method(p), head: p.snapshot!.head, mergeQueue: !!p.snapshot!.repoMerge?.mergeQueue } : { enable: false });
|
|
260
|
-
|
|
266
|
+
toggled.push(p.number);
|
|
261
267
|
}
|
|
262
|
-
return { state: "submitted", result:
|
|
268
|
+
return { state: "submitted", result: progress() };
|
|
263
269
|
} catch (error) {
|
|
264
270
|
return { state: error instanceof GithubWriteError && !error.uncertain ? "failed" : "uncertain", result: partial(error) };
|
|
265
271
|
}
|
package/server/pr-owner.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { State, Workspace } from "../shared/model";
|
|
2
|
-
import { buildHome, GROUP_TITLE, HOME_GROUPS, type HomeGroupId } from "../shared/home";
|
|
2
|
+
import { buildHome, GROUP_TITLE, HOME_GROUPS, type BadgeTone, type HomeGroupId, type Workstream } from "../shared/home";
|
|
3
3
|
import { isLive } from "../shared/agent-load";
|
|
4
4
|
|
|
5
5
|
/** Duplicate claims are ambiguous. Never route by recency or by PR title. */
|
|
@@ -20,7 +20,16 @@ export function browserRepositories(state: State): string[] {
|
|
|
20
20
|
|
|
21
21
|
/** The live Paseo facts about a workspace's main agent that the browser view needs. */
|
|
22
22
|
export type BrowserAgent = { status: string; pendingPermissions?: unknown[]; requiresAttention?: boolean; attentionReason?: string | null; backgroundWork?: { count?: unknown } | null };
|
|
23
|
-
|
|
23
|
+
/**
|
|
24
|
+
* The color of a row's state, so the browser never parses Follow-up's English. It comes from the same tone Home paints
|
|
25
|
+
* the row's first badge (or headline) with: attention (amber), danger (red), success (green), accent (blue: running,
|
|
26
|
+
* sending, finished), muted.
|
|
27
|
+
*/
|
|
28
|
+
export const BROWSER_TONES = ["attention", "danger", "success", "accent", "muted"] as const;
|
|
29
|
+
export type BrowserTone = typeof BROWSER_TONES[number];
|
|
30
|
+
const TONE: Record<BadgeTone | Workstream["tone"], BrowserTone> = { warning: "attention", danger: "danger", success: "success", merged: "success", accent: "accent", running: "accent", muted: "muted" };
|
|
31
|
+
export type BrowserWorkspaceView = { group: HomeGroupId; state: string; tone: BrowserTone };
|
|
32
|
+
export type BrowserWorkspace = { workspaceId: string; agentId: string; title: string; agentStatus: string } & BrowserWorkspaceView;
|
|
24
33
|
export const BROWSER_WORKSPACE_LIMIT = 3;
|
|
25
34
|
|
|
26
35
|
/** Every active tracked workspace that registered this PR. Unlike `prOwner`, several are expected: a stack or a review workspace. */
|
|
@@ -44,25 +53,33 @@ function fixDetail(w: Workspace, fallback: string): string {
|
|
|
44
53
|
* Follow-up's one line for a workspace ("Needs you · Merge ready"), from the same model Home uses, plus the
|
|
45
54
|
* main agent's live Paseo attention, which Home reads from the inbox and the server does not have otherwise.
|
|
46
55
|
*/
|
|
47
|
-
export function browserWorkspaceState(w: Workspace, agent: BrowserAgent, now = Date.now()):
|
|
56
|
+
export function browserWorkspaceState(w: Workspace, agent: BrowserAgent | null, now = Date.now()): BrowserWorkspaceView {
|
|
48
57
|
const row = buildHome({ rows: [], tracked: [w], paseo: [], now }).byKey.get(`ws:${w.id}`);
|
|
49
58
|
const group = row?.group ?? "quiet";
|
|
50
|
-
if (group === "needs") return { group, state: `${GROUP_TITLE.needs} · ${row!.badges[0]?.text ?? row!.word ?? "Action"}
|
|
51
|
-
if (agent
|
|
59
|
+
if (group === "needs") return { group, state: `${GROUP_TITLE.needs} · ${row!.badges[0]?.text ?? row!.word ?? "Action"}`, tone: TONE[row!.badges[0]?.tone ?? row!.tone] };
|
|
60
|
+
if (!agent) {
|
|
61
|
+
// The main agent is closed. Done work has nothing left to do; anything else needs the developer to pick an agent.
|
|
62
|
+
return row?.readyToArchive ? { group, state: "Done · ready to archive", tone: "success" } : { group: "needs", state: `${GROUP_TITLE.needs} · Agent closed`, tone: "attention" };
|
|
63
|
+
}
|
|
64
|
+
if (agent.pendingPermissions?.length || agent.attentionReason === "permission") return { group: "needs", state: `${GROUP_TITLE.needs} · Permission`, tone: TONE.warning };
|
|
52
65
|
// Paseo's attention reason outlives the turn it describes: a running agent's "error" is the last turn's, not now's.
|
|
53
66
|
// 0.16: live background work counts as running too (no "Finished" while a job it started still runs).
|
|
54
67
|
const running = isLive(agent);
|
|
55
|
-
if (agent.status === "error" || agent.attentionReason === "error" && !running) return { group: "needs", state: `${GROUP_TITLE.needs} · Error
|
|
56
|
-
if (group === "sending") return { group, state: `${GROUP_TITLE.sending} · ${fixDetail(w, row!.line)}
|
|
57
|
-
if (group === "running" || running) return { group: "running", state: GROUP_TITLE.running };
|
|
58
|
-
if (agent.requiresAttention) return { group: "needs", state: `${GROUP_TITLE.needs} · Finished
|
|
59
|
-
if (group === "waiting") return { group, state: row!.line ? `${GROUP_TITLE.waiting} · ${row!.line}` : GROUP_TITLE.waiting };
|
|
60
|
-
return { group, state:
|
|
68
|
+
if (agent.status === "error" || agent.attentionReason === "error" && !running) return { group: "needs", state: `${GROUP_TITLE.needs} · Error`, tone: TONE.danger };
|
|
69
|
+
if (group === "sending") return { group, state: `${GROUP_TITLE.sending} · ${fixDetail(w, row!.line)}`, tone: TONE.running };
|
|
70
|
+
if (group === "running" || running) return { group: "running", state: GROUP_TITLE.running, tone: TONE.running };
|
|
71
|
+
if (agent.requiresAttention) return { group: "needs", state: `${GROUP_TITLE.needs} · Finished`, tone: TONE.accent };
|
|
72
|
+
if (group === "waiting") return { group, state: row!.line ? `${GROUP_TITLE.waiting} · ${row!.line}` : GROUP_TITLE.waiting, tone: TONE.muted };
|
|
73
|
+
return row?.readyToArchive ? { group, state: "Done · ready to archive", tone: TONE.success } : { group, state: GROUP_TITLE.quiet, tone: TONE.muted };
|
|
61
74
|
}
|
|
62
75
|
|
|
63
|
-
/**
|
|
76
|
+
/**
|
|
77
|
+
* Most urgent first, then most recently updated. At most three; `more` counts the rest. A claim whose main agent is
|
|
78
|
+
* closed (`agent: null`) stays, as "Needs you · Agent closed" with `agentStatus: "closed"`; the caller leaves out a claim
|
|
79
|
+
* whose agent it couldn't read at all, since an unknown agent is not a closed one.
|
|
80
|
+
*/
|
|
64
81
|
export function browserWorkspaces(entries: { workspace: Workspace; agent: BrowserAgent | null }[], now = Date.now()): { workspaces: BrowserWorkspace[]; more: number } {
|
|
65
|
-
const rows = entries.
|
|
82
|
+
const rows = entries.map(({ workspace: w, agent }) => ({ w, view: { workspaceId: w.id, agentId: w.mainAgentId, title: w.title, agentStatus: !agent ? "closed" : agent.pendingPermissions?.length ? "permission" : agent.status, ...browserWorkspaceState(w, agent, now) } }));
|
|
66
83
|
rows.sort((a, b) => HOME_GROUPS.indexOf(a.view.group) - HOME_GROUPS.indexOf(b.view.group) || b.w.updatedAt.localeCompare(a.w.updatedAt) || a.w.id.localeCompare(b.w.id));
|
|
67
84
|
return { workspaces: rows.slice(0, BROWSER_WORKSPACE_LIMIT).map(r => r.view), more: Math.max(0, rows.length - BROWSER_WORKSPACE_LIMIT) };
|
|
68
85
|
}
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import { budgetTier, DEFAULT_LIMIT, type Budget } from "../shared/poll";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* The one gate every PR-statistics request passes (invariant `stats-never-spend-below-low`, docs/pr-stats.md).
|
|
5
|
+
* Stats are the least important thing Follow-up reads from GitHub, so they yield to everything:
|
|
6
|
+
*
|
|
7
|
+
* 1. the governor allows background work (nothing while the VM is constrained or critical);
|
|
8
|
+
* 2. the account's budget tier is `normal` (≥ 40 % of the limit left): stats stop at `low`, far above the 20 %
|
|
9
|
+
* reserve the PR poller and agents' own `gh` calls live on;
|
|
10
|
+
* 3. the stats slice isn't spent: the `rateLimit.cost` of stats responses in the last rolling hour, plus the next
|
|
11
|
+
* page's expected cost (the last page's), stays within `slice × limit` (5 % = 250 of 5000 points by default);
|
|
12
|
+
* 4. no other stats request is in flight.
|
|
13
|
+
*
|
|
14
|
+
* The ledger and the one-in-flight rule are worker-wide, not per account: stricter than the design's per-account
|
|
15
|
+
* rule (two opted-in repositories on different accounts share one slice), and it never needs the account map.
|
|
16
|
+
* Every response's `rateLimit` goes to `noteRateLimit`, the same per-owner `Budget` the PR poller reads
|
|
17
|
+
* (`Github.noteRateLimit`), so a burst seen by either one throttles both (`stats-feed-the-shared-budget`).
|
|
18
|
+
*/
|
|
19
|
+
export const STATS_SLICE_DEFAULT = 0.05;
|
|
20
|
+
export const STATS_SLICE_MIN = 0.01;
|
|
21
|
+
export const STATS_SLICE_MAX = 0.1;
|
|
22
|
+
export const SLICE_WINDOW_MS = 60 * 60_000;
|
|
23
|
+
/** A page's cost before any was measured: 1 point per page of 25 (design §2.2). */
|
|
24
|
+
export const EXPECTED_PAGE_COST = 1;
|
|
25
|
+
|
|
26
|
+
export type GateReason = "governor" | "budget" | "slice" | "busy";
|
|
27
|
+
export type GateAnswer = { ok: true } | { ok: false; reason: GateReason; until: number | null };
|
|
28
|
+
export type RateLimit = { cost?: number; remaining?: number; resetAt?: string; limit?: number };
|
|
29
|
+
export interface GateDeps {
|
|
30
|
+
/** The account's budget as the PR poller last saw it (`Github.budget`). */
|
|
31
|
+
budget(owner: string): Budget | undefined;
|
|
32
|
+
/** Feeds a stats response's rateLimit into that same budget. */
|
|
33
|
+
noteRateLimit(owner: string, rate: RateLimit): void;
|
|
34
|
+
/** Records that GitHub refused for the limit, until `resetAt`. */
|
|
35
|
+
noteLimited(owner: string, resetAt: number): void;
|
|
36
|
+
allowsBackground(): boolean;
|
|
37
|
+
/** The slice as a fraction of the hourly limit (settings); clamped to [STATS_SLICE_MIN, STATS_SLICE_MAX]. */
|
|
38
|
+
slice?(): number;
|
|
39
|
+
now?: () => number;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export class StatsGate {
|
|
43
|
+
private ledger: { at: number; cost: number }[] = [];
|
|
44
|
+
private inFlight = false;
|
|
45
|
+
private expected = EXPECTED_PAGE_COST;
|
|
46
|
+
private now: () => number;
|
|
47
|
+
constructor(private deps: GateDeps) { this.now = deps.now ?? Date.now; }
|
|
48
|
+
|
|
49
|
+
private limitOf(owner: string): number { const b = this.deps.budget(owner); return b?.limit && b.limit > 0 ? b.limit : DEFAULT_LIMIT; }
|
|
50
|
+
private sliceShare(): number { const s = this.deps.slice?.() ?? STATS_SLICE_DEFAULT; return Number.isFinite(s) ? Math.min(STATS_SLICE_MAX, Math.max(STATS_SLICE_MIN, s)) : STATS_SLICE_DEFAULT; }
|
|
51
|
+
private prune(now: number): void { while (this.ledger.length && this.ledger[0]!.at <= now - SLICE_WINDOW_MS) this.ledger.shift(); }
|
|
52
|
+
/** Points stats spent in the rolling hour. */
|
|
53
|
+
spent(): number { this.prune(this.now()); return this.ledger.reduce((sum, e) => sum + e.cost, 0); }
|
|
54
|
+
/** The slice in points for this owner's account. */
|
|
55
|
+
slicePoints(owner: string): number { return Math.floor(this.sliceShare() * this.limitOf(owner)); }
|
|
56
|
+
|
|
57
|
+
/** Whether a stats request for `owner`'s repository may go out now, `cost` being what it is expected to cost. */
|
|
58
|
+
mayRead(owner: string, cost = this.expected): GateAnswer {
|
|
59
|
+
const now = this.now();
|
|
60
|
+
if (!this.deps.allowsBackground()) return { ok: false, reason: "governor", until: null };
|
|
61
|
+
const budget = this.deps.budget(owner);
|
|
62
|
+
if (budgetTier(budget, now) !== "normal") return { ok: false, reason: "budget", until: budget?.resetAt ?? null };
|
|
63
|
+
this.prune(now);
|
|
64
|
+
const cap = this.slicePoints(owner);
|
|
65
|
+
let spent = this.ledger.reduce((sum, e) => sum + e.cost, 0);
|
|
66
|
+
if (spent + cost > cap) {
|
|
67
|
+
// The slice reopens when enough of the hour's oldest spending rolls out of the window.
|
|
68
|
+
let until = now + SLICE_WINDOW_MS;
|
|
69
|
+
for (const e of this.ledger) { spent -= e.cost; if (spent + cost <= cap) { until = e.at + SLICE_WINDOW_MS; break; } }
|
|
70
|
+
return { ok: false, reason: "slice", until };
|
|
71
|
+
}
|
|
72
|
+
if (this.inFlight) return { ok: false, reason: "busy", until: null };
|
|
73
|
+
return { ok: true };
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Runs one stats request through the gate: refused (with the answer) when the gate is closed, else `request` runs
|
|
78
|
+
* as the only stats request in flight, and its `rateLimit` is charged to the slice and fed to the shared budget.
|
|
79
|
+
*/
|
|
80
|
+
async run<T>(owner: string, request: () => Promise<{ value: T; rate: RateLimit | undefined }>, cost = this.expected): Promise<{ ok: true; value: T } | Extract<GateAnswer, { ok: false }>> {
|
|
81
|
+
const answer = this.mayRead(owner, cost);
|
|
82
|
+
if (!answer.ok) return answer;
|
|
83
|
+
this.inFlight = true;
|
|
84
|
+
try {
|
|
85
|
+
const { value, rate } = await request();
|
|
86
|
+
this.charge(owner, rate, cost);
|
|
87
|
+
return { ok: true, value };
|
|
88
|
+
} catch (error) {
|
|
89
|
+
const e = error as { rateLimited?: boolean; resetAt?: number };
|
|
90
|
+
if (e?.rateLimited) this.deps.noteLimited(owner, e.resetAt ?? this.now() + 10 * 60_000);
|
|
91
|
+
// A request that failed may still have cost something; charge the expectation so failures can't loop free.
|
|
92
|
+
this.ledger.push({ at: this.now(), cost });
|
|
93
|
+
throw error;
|
|
94
|
+
} finally { this.inFlight = false; }
|
|
95
|
+
}
|
|
96
|
+
private charge(owner: string, rate: RateLimit | undefined, fallback: number): void {
|
|
97
|
+
const cost = typeof rate?.cost === "number" && rate.cost >= 0 ? rate.cost : fallback;
|
|
98
|
+
this.ledger.push({ at: this.now(), cost });
|
|
99
|
+
if (cost > 0) this.expected = cost;
|
|
100
|
+
if (rate && typeof rate.remaining === "number") this.deps.noteRateLimit(owner, rate);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
import { readFile, unlink } from "node:fs/promises";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { z } from "zod";
|
|
4
|
+
import { statsRecordSchema, STATS_PAGE_SIZE, type StatsRecord } from "../shared/pr-stats-records";
|
|
5
|
+
import { WriteBehind, type WriteHealth } from "./write-behind";
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* PR statistics' records, one file per opted-in repository: `plugin-data/follow-up/stats/<owner>/<repo>.json`
|
|
9
|
+
* (docs/pr-stats.md, docs/data-files.md). The sync merges pages into it; the metrics read it.
|
|
10
|
+
*
|
|
11
|
+
* Resources (invariant `stats-are-computed-on-read`): a repository's records are in memory only while something reads
|
|
12
|
+
* or syncs it. `open` loads the file and keeps it in an LRU of `STATS_LOADED_MAX` repositories, each dropped
|
|
13
|
+
* `STATS_KEEP_MS` after its last use, so nothing stays loaded between reads. Writes go through `WriteBehind` (an ack
|
|
14
|
+
* never waits on the disk) as parts: each record's bytes are encoded once per record object and reused until that PR
|
|
15
|
+
* changes, so a page of 25 PRs re-encodes 25 records, never the whole file (`a-mutation-costs-what-it-changes`).
|
|
16
|
+
*/
|
|
17
|
+
export const STATS_LOADED_MAX = 2;
|
|
18
|
+
export const STATS_KEEP_MS = 5 * 60_000;
|
|
19
|
+
/** Past this many records a repository's window shortens (oldest first) and the page says to which date. */
|
|
20
|
+
export const STATS_RECORDS_MAX = 25_000;
|
|
21
|
+
/** Allowed history windows in days (D7: 90 by default). */
|
|
22
|
+
export const STATS_WINDOWS = [30, 90, 180] as const;
|
|
23
|
+
export const STATS_WINDOW_DEFAULT = 90;
|
|
24
|
+
const REPO = /^[\w.-]+\/[\w.-]+$/;
|
|
25
|
+
|
|
26
|
+
const at = z.number().int().nonnegative();
|
|
27
|
+
export const statsMetaSchema = z.object({
|
|
28
|
+
repo: z.string().regex(REPO),
|
|
29
|
+
/** The repository's default branch, from the last page read (stack detection: a PR based elsewhere may be stacked). */
|
|
30
|
+
defaultBranch: z.string().nullable(),
|
|
31
|
+
/** The newest updatedAt an incremental walk has fully covered (epoch s); null before the first page. */
|
|
32
|
+
highWater: at.nullable(),
|
|
33
|
+
/** An incremental walk cut short by the gate, resumed from here: its cursor and the newest updatedAt it saw. */
|
|
34
|
+
incremental: z.object({ after: z.string(), high: at }).nullable(),
|
|
35
|
+
/** The 90-day backfill: the cursor to continue from, whether it reached the window's start, how far back it reached. */
|
|
36
|
+
backfill: z.object({ after: z.string().nullable(), done: z.boolean(), coveredTo: at.nullable() }),
|
|
37
|
+
/** The page size: STATS_PAGE_SIZE, halved after a 502 or RESOURCE_LIMITS answer until a page succeeds. */
|
|
38
|
+
page: z.number().int().positive(),
|
|
39
|
+
windowDays: z.number().int().positive(),
|
|
40
|
+
/** PRs whose reviews ran past the page; a follow-up query reads the rest. */
|
|
41
|
+
pendingReviews: z.array(z.number().int().positive()),
|
|
42
|
+
lastSyncAt: at.nullable(),
|
|
43
|
+
/** Points the last run spent, and pages it read. */
|
|
44
|
+
lastCost: z.number().nonnegative(),
|
|
45
|
+
lastPages: z.number().int().nonnegative(),
|
|
46
|
+
/** Why the last run stopped short of done: the gate's reason and when it reopens, or a read error. */
|
|
47
|
+
waiting: z.object({ reason: z.enum(["governor", "budget", "slice", "busy"]), until: at.nullable() }).nullable(),
|
|
48
|
+
error: z.object({ message: z.string(), status: z.number().int().nullable(), at }).nullable(),
|
|
49
|
+
/** Set when the record cap shortened the window: the date records reach back to. */
|
|
50
|
+
cappedTo: at.nullable(),
|
|
51
|
+
}).strict();
|
|
52
|
+
export type StatsMeta = z.infer<typeof statsMetaSchema>;
|
|
53
|
+
export type RepoStats = { meta: StatsMeta; records: Map<number, StatsRecord> };
|
|
54
|
+
|
|
55
|
+
export function freshMeta(repo: string, windowDays = STATS_WINDOW_DEFAULT): StatsMeta {
|
|
56
|
+
return { repo, defaultBranch: null, highWater: null, incremental: null, backfill: { after: null, done: false, coveredTo: null }, page: STATS_PAGE_SIZE, windowDays, pendingReviews: [], lastSyncAt: null, lastCost: 0, lastPages: 0, waiting: null, error: null, cappedTo: null };
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** The file for a repository, or null for a name that isn't `owner/repo` (never a path outside `stats/`). */
|
|
60
|
+
export function statsPath(directory: string, repo: string): string | null {
|
|
61
|
+
if (!REPO.test(repo) || repo.split("/").some(part => part === "." || part === "..")) return null;
|
|
62
|
+
const [owner, name] = repo.split("/");
|
|
63
|
+
return join(directory, "stats", owner!, `${name}.json`);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
const recordBytes = new WeakMap<StatsRecord, Buffer>();
|
|
67
|
+
const bytesOf = (record: StatsRecord): Buffer => { let b = recordBytes.get(record); if (!b) { b = Buffer.from(JSON.stringify(record)); recordBytes.set(record, b); } return b; };
|
|
68
|
+
const COMMA = Buffer.from(","), END = Buffer.from("]}");
|
|
69
|
+
/** The file as parts: the meta, then each record's cached bytes. Byte for byte `JSON.stringify({ v, meta, records })`. */
|
|
70
|
+
export function encodeStats(stats: RepoStats): Buffer[] {
|
|
71
|
+
const parts: Buffer[] = [Buffer.from(`{"v":1,"meta":${JSON.stringify(stats.meta)},"records":[`)];
|
|
72
|
+
let first = true;
|
|
73
|
+
for (const record of stats.records.values()) { if (!first) parts.push(COMMA); parts.push(bytesOf(record)); first = false; }
|
|
74
|
+
parts.push(END);
|
|
75
|
+
return parts;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
type Entry = { stats: RepoStats; usedAt: number; timer: ReturnType<typeof setTimeout> | null };
|
|
79
|
+
export class StatsStore {
|
|
80
|
+
private loaded = new Map<string, Entry>();
|
|
81
|
+
private loading = new Map<string, Promise<RepoStats>>();
|
|
82
|
+
private writers = new Map<string, WriteBehind<RepoStats>>();
|
|
83
|
+
/** Files read from disk (tests: a record read loads once, and again only after it was dropped). */
|
|
84
|
+
loads = 0;
|
|
85
|
+
constructor(readonly directory: string, private o: { now?: () => number; keepMs?: number; max?: number; health?: WriteHealth; log?: (line: string) => void } = {}) {}
|
|
86
|
+
private get now() { return this.o.now ?? Date.now; }
|
|
87
|
+
|
|
88
|
+
/** Repositories in memory now. */
|
|
89
|
+
inMemory(): string[] { return [...this.loaded.keys()]; }
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* A repository's records, loaded for this use. The object stays the same while it is loaded; callers read it and
|
|
93
|
+
* hand changes to `save`. A missing or unreadable file is an empty store (unknown is not off: nothing is lost by
|
|
94
|
+
* reading again).
|
|
95
|
+
*/
|
|
96
|
+
async open(repo: string): Promise<RepoStats> {
|
|
97
|
+
const path = statsPath(this.directory, repo);
|
|
98
|
+
if (!path) throw new Error(`Not a repository: ${repo}`);
|
|
99
|
+
const hit = this.loaded.get(repo);
|
|
100
|
+
if (hit) { this.touch(repo, hit); return hit.stats; }
|
|
101
|
+
let pending = this.loading.get(repo);
|
|
102
|
+
if (!pending) {
|
|
103
|
+
pending = (async () => {
|
|
104
|
+
// A write still landing for a store dropped from memory is the newest copy: let it land before reading.
|
|
105
|
+
await this.writers.get(repo)?.flush().catch(() => undefined);
|
|
106
|
+
const stats = await this.read(repo, path);
|
|
107
|
+
const entry: Entry = { stats, usedAt: this.now(), timer: null };
|
|
108
|
+
this.loaded.set(repo, entry); this.touch(repo, entry); this.evict();
|
|
109
|
+
return stats;
|
|
110
|
+
})().finally(() => this.loading.delete(repo));
|
|
111
|
+
this.loading.set(repo, pending);
|
|
112
|
+
}
|
|
113
|
+
return pending;
|
|
114
|
+
}
|
|
115
|
+
private async read(repo: string, path: string): Promise<RepoStats> {
|
|
116
|
+
this.loads++;
|
|
117
|
+
const text = await readFile(path, "utf8").catch(() => null);
|
|
118
|
+
if (text === null) return { meta: freshMeta(repo), records: new Map() };
|
|
119
|
+
try {
|
|
120
|
+
const raw = JSON.parse(text) as { meta?: unknown; records?: unknown };
|
|
121
|
+
const meta = statsMetaSchema.parse(raw.meta);
|
|
122
|
+
const records = new Map<number, StatsRecord>();
|
|
123
|
+
let dropped = 0;
|
|
124
|
+
for (const item of Array.isArray(raw.records) ? raw.records : []) {
|
|
125
|
+
const parsed = statsRecordSchema.safeParse(item);
|
|
126
|
+
if (parsed.success) records.set(parsed.data.n, Object.freeze(parsed.data)); else dropped++;
|
|
127
|
+
}
|
|
128
|
+
if (dropped) (this.o.log ?? console.warn)(`[follow-up] PR stats: dropped ${dropped} unreadable record${dropped === 1 ? "" : "s"} of ${repo}`);
|
|
129
|
+
return { meta: { ...meta, repo }, records };
|
|
130
|
+
} catch (error) {
|
|
131
|
+
(this.o.log ?? console.warn)(`[follow-up] PR stats: ${repo}'s file is unreadable (${error instanceof Error ? error.message : String(error)}); starting it again`);
|
|
132
|
+
return { meta: freshMeta(repo), records: new Map() };
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
private touch(repo: string, entry: Entry): void {
|
|
136
|
+
entry.usedAt = this.now();
|
|
137
|
+
if (entry.timer) clearTimeout(entry.timer);
|
|
138
|
+
entry.timer = setTimeout(() => this.drop(repo), this.o.keepMs ?? STATS_KEEP_MS);
|
|
139
|
+
(entry.timer as { unref?: () => void }).unref?.();
|
|
140
|
+
}
|
|
141
|
+
private evict(): void {
|
|
142
|
+
const max = this.o.max ?? STATS_LOADED_MAX;
|
|
143
|
+
while (this.loaded.size > max) {
|
|
144
|
+
const oldest = [...this.loaded].sort((a, b) => a[1].usedAt - b[1].usedAt)[0]!;
|
|
145
|
+
this.drop(oldest[0]);
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
/** Drops a repository from memory; its pending write still lands (the writer keeps the value). */
|
|
149
|
+
drop(repo: string): void {
|
|
150
|
+
const entry = this.loaded.get(repo);
|
|
151
|
+
if (!entry) return;
|
|
152
|
+
if (entry.timer) clearTimeout(entry.timer);
|
|
153
|
+
this.loaded.delete(repo);
|
|
154
|
+
const writer = this.writers.get(repo);
|
|
155
|
+
if (writer && !writer.dirty) this.writers.delete(repo);
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* Merges records into a loaded repository and saves it behind the caller. A record equal to the stored one keeps
|
|
160
|
+
* the stored object (and its encoded bytes): a write that changes nothing isn't a write.
|
|
161
|
+
*/
|
|
162
|
+
merge(stats: RepoStats, records: StatsRecord[]): number {
|
|
163
|
+
let changed = 0;
|
|
164
|
+
for (const record of records) {
|
|
165
|
+
const old = stats.records.get(record.n);
|
|
166
|
+
if (old && bytesOf(old).equals(Buffer.from(JSON.stringify(record)))) continue;
|
|
167
|
+
stats.records.set(record.n, Object.freeze(record)); changed++;
|
|
168
|
+
}
|
|
169
|
+
return changed;
|
|
170
|
+
}
|
|
171
|
+
/** Saves a repository behind the caller (WriteBehind: coalesced, temp + fsync + rename). */
|
|
172
|
+
save(stats: RepoStats): void {
|
|
173
|
+
const repo = stats.meta.repo;
|
|
174
|
+
const path = statsPath(this.directory, repo);
|
|
175
|
+
if (!path) return;
|
|
176
|
+
let writer = this.writers.get(repo);
|
|
177
|
+
if (!writer) {
|
|
178
|
+
writer = new WriteBehind<RepoStats>({ path, encode: encodeStats, health: this.o.health, log: this.o.log, onWritten: () => { if (!this.loaded.has(repo) && !this.writers.get(repo)?.dirty) this.writers.delete(repo); } });
|
|
179
|
+
this.writers.set(repo, writer);
|
|
180
|
+
}
|
|
181
|
+
writer.set({ meta: stats.meta, records: new Map(stats.records) });
|
|
182
|
+
}
|
|
183
|
+
/** Removes a repository's file and anything in memory (turning stats off with "Also delete"). */
|
|
184
|
+
async delete(repo: string): Promise<void> {
|
|
185
|
+
const path = statsPath(this.directory, repo);
|
|
186
|
+
if (!path) return;
|
|
187
|
+
this.drop(repo);
|
|
188
|
+
const writer = this.writers.get(repo);
|
|
189
|
+
if (writer) { await writer.flush().catch(() => undefined); this.writers.delete(repo); }
|
|
190
|
+
await unlink(path).catch(() => undefined);
|
|
191
|
+
}
|
|
192
|
+
/** Writes everything pending (the worker's stop, test cleanup). */
|
|
193
|
+
async flush(): Promise<void> { for (const writer of [...this.writers.values()]) await writer.flush(); }
|
|
194
|
+
/** Drops everything from memory and clears the timers (the worker's stop, after flush). */
|
|
195
|
+
close(): void { for (const repo of [...this.loaded.keys()]) this.drop(repo); }
|
|
196
|
+
}
|