Skip to content

g1t/apps/web/app/lib/mission.ts

463 lines18,776 bytesCodeBlame
1/**
2 * The arithmetic behind mission control and a project's overview: when the
3 * viewer was last here, what moved since, how a burst of one agent's work
4 * reads as one line, the week's pulse, and where each pull request stands
5 * in its way to landing. Pure, so it is tested on its own; it imports only
6 * types.
7 */
8import type { AgentRun, G1tEvent, Pull, QueueEntry, RepoPath } from "@g1t/contracts";
9
10const MINUTE = 60_000;
11const HOUR = 60 * MINUTE;
12const DAY = 24 * HOUR;
13
14// --- Last seen ----------------------------------------------------------------
15
16/** The cookie that remembers when the viewer was last on mission control. */
17export const SEEN_COOKIE = "g1t_seen";
18/** A gap this long between page views starts a new visit. */
19export const VISIT_GAP_MS = 30 * MINUTE;
20
21/**
22 * Reads the last-seen cookie (`<previous visit>.<last view>`, in epoch ms)
23 * and works out what to count from and what to write back. Views within
24 * `VISIT_GAP_MS` of each other are one visit, so the page refreshing
25 * itself does not reset what is new. `since` is null on a first visit.
26 */
27export function nextSeen(raw: string | null | undefined, now: number, gap = VISIT_GAP_MS): { since: number | null; value: string } {
28 const [prevText, atText] = (raw ?? "").split(".");
29 const prev = Number(prevText);
30 const at = Number(atText);
31 if (!Number.isFinite(at) || at <= 0 || at > now) return { since: null, value: `0.${now}` };
32 if (now - at > gap) return { since: at, value: `${at}.${now}` };
33 const since = Number.isFinite(prev) && prev > 0 && prev <= at ? prev : null;
34 return { since, value: `${since ?? 0}.${now}` };
35}
36
37/** Reads one cookie from a `Cookie` header. */
38export function readCookie(header: string | null, name: string): string | null {
39 if (!header) return null;
40 for (const part of header.split(";")) {
41 const [key, ...rest] = part.trim().split("=");
42 if (key === name) {
43 try {
44 return decodeURIComponent(rest.join("="));
45 } catch {
46 return null;
47 }
48 }
49 }
50 return null;
51}
52
53/** "Good morning", "Good afternoon" or "Good evening", for an hour of the day. */
54export function greetingFor(hour: number): string {
55 if (hour >= 5 && hour < 12) return "Good morning";
56 if (hour >= 12 && hour < 17) return "Good afternoon";
57 return "Good evening";
58}
59
60/** The hour of the day in a time zone, or in UTC when it is unknown or invalid. */
61export function hourIn(now: number, timeZone: string | null): number {
62 try {
63 const text = new Intl.DateTimeFormat("en-US", { hour: "numeric", hourCycle: "h23", timeZone: timeZone || "UTC" }).format(now);
64 const hour = Number.parseInt(text, 10);
65 return Number.isFinite(hour) ? hour % 24 : new Date(now).getUTCHours();
66 } catch {
67 return new Date(now).getUTCHours();
68 }
69}
70
71/** What the composer's text makes: its first line the title, all of it the body when there is more. */
72export function splitRequest(text: string, max = 200): { title: string; body: string } {
73 const trimmed = text.trim();
74 const [first = "", ...rest] = trimmed.split(/\r?\n/);
75 let title = first.trim();
76 if (title.length > max) {
77 const cut = title.slice(0, max - 1);
78 const space = cut.lastIndexOf(" ");
79 title = `${(space > max / 2 ? cut.slice(0, space) : cut).trimEnd()}…`;
80 }
81 const more = rest.join("\n").trim();
82 // A shortened title loses words, so the body keeps all of it.
83 return { title, body: title !== first.trim() ? trimmed : more };
84}
85
86// --- Activity ---------------------------------------------------------------
87
88/** Accounts that are g1t's own agents and machinery. */
89export function isAgent(name: string | null | undefined): boolean {
90 return name === "g1t" || (name ?? "").endsWith("-agent");
91}
92
93export type Verb =
94 | "landed"
95 | "opened_issue"
96 | "closed_issue"
97 | "started"
98 | "ready"
99 | "checks_passed"
100 | "checks_failed"
101 | "approved"
102 | "changes_requested"
103 | "commented"
104 | "asked"
105 | "deployed"
106 | "deploy_failed"
107 | "learned";
108
109/** One thing that moved, as the feed shows it. */
110export type ActivityItem = {
111 id: string;
112 /** Epoch ms. */
113 at: number;
114 repo: RepoPath;
115 actor: string | null;
116 verb: Verb;
117 /** The issue or pull request it was about. */
118 number: number | null;
119 /** For a memory: what was learned. For a deploy: where. */
120 text?: string;
121 /** Where the line links, when it is not an issue or pull request. */
122 to?: string;
123};
124
125/** An event from the log as a feed item, or null for those not worth a line. */
126export function eventItem(event: G1tEvent, repo: RepoPath): ActivityItem | null {
127 const base = { id: event.id, at: Date.parse(event.time), repo, actor: event.actor };
128 switch (event.type) {
129 case "pull.merged":
130 return { ...base, verb: "landed", number: event.data.number };
131 case "issue.opened":
132 return { ...base, verb: "opened_issue", number: event.data.number };
133 case "issue.closed":
134 return event.data.resolvedBy != null ? null : { ...base, verb: "closed_issue", number: event.data.number };
135 case "pull.opened":
136 return { ...base, actor: event.data.agent || event.actor, verb: "started", number: event.data.number };
137 case "pull.ready":
138 return { ...base, verb: "ready", number: event.data.number };
139 case "checks.completed":
140 return { ...base, actor: null, verb: event.data.status === "passed" ? "checks_passed" : "checks_failed", number: event.data.number };
141 case "review.completed":
142 if (!event.data.verdict) return null;
143 return { ...base, actor: "g1t", verb: event.data.verdict === "approve" ? "approved" : "changes_requested", number: event.data.number };
144 case "comment.created":
145 if (event.data.verdict) {
146 return { ...base, verb: event.data.verdict === "approve" ? "approved" : "changes_requested", number: event.data.number };
147 }
148 return { ...base, verb: "commented", number: event.data.number };
149 case "agent.asked":
150 return { ...base, verb: "asked", number: event.data.number };
151 default:
152 return null;
153 }
154}
155
156/** Accounts that act for g1t itself, named in the log by fixed ids. */
157const G1T_ACTORS: Record<string, string> = { usr_g1t_agent: "g1t", g1t_policy: "g1t" };
158/** Who an account the lookup no longer knows was. */
159export const DELETED_USER = "a deleted user";
160
161/** An account id rather than a name: usernames never hold an underscore. */
162const isAccountId = (actor: string) => actor.includes("_");
163
164/** The account ids among `actors` to look up by name, once each. */
165export function actorIds(actors: (string | null)[]): string[] {
166 return [...new Set(actors.filter((actor): actor is string => actor != null && isAccountId(actor) && !(actor in G1T_ACTORS)))];
167}
168
169/**
170 * An actor by name: an account id becomes its username, from `names` (the
171 * identity service's lookup). An id it does not know is an account since
172 * deleted; with no lookup at all, the actor is only "someone".
173 */
174export function nameActor(actor: string | null, names: Record<string, string> | null): string | null {
175 if (actor == null || !isAccountId(actor)) return actor;
176 return G1T_ACTORS[actor] ?? names?.[actor] ?? (names ? DELETED_USER : "someone");
177}
178
179/** Several things one actor did in one project in a short while, read as one line. */
180export type ActivityGroup = {
181 id: string;
182 actor: string | null;
183 repo: RepoPath;
184 /** Newest and oldest, epoch ms. */
185 at: number;
186 from: number;
187 /** Each kind of thing done, in the order first seen, with what it was done to. */
188 parts: { verb: Verb; numbers: number[]; texts: string[]; to?: string }[];
189 count: number;
190};
191
192const sameRepo = (a: RepoPath, b: RepoPath) =>
193 a.namespace.toLowerCase() === b.namespace.toLowerCase() && a.name.toLowerCase() === b.name.toLowerCase();
194
195/**
196 * Groups items, newest first, so that a run of things one actor did in one
197 * project within `window` of the run's newest reads as one line.
198 */
199export function groupActivity(items: ActivityItem[], window = 45 * MINUTE): ActivityGroup[] {
200 const sorted = [...items].sort((a, b) => b.at - a.at);
201 const groups: ActivityGroup[] = [];
202 for (const item of sorted) {
203 const last = groups[groups.length - 1];
204 if (last && last.actor === item.actor && sameRepo(last.repo, item.repo) && last.at - item.at <= window) {
205 let part = last.parts.find((p) => p.verb === item.verb);
206 if (!part) {
207 part = { verb: item.verb, numbers: [], texts: [], to: item.to };
208 last.parts.push(part);
209 }
210 if (item.number != null && !part.numbers.includes(item.number)) part.numbers.push(item.number);
211 if (item.text && !part.texts.includes(item.text)) part.texts.push(item.text);
212 last.from = item.at;
213 last.count += 1;
214 continue;
215 }
216 groups.push({
217 id: item.id,
218 actor: item.actor,
219 repo: item.repo,
220 at: item.at,
221 from: item.at,
222 parts: [{ verb: item.verb, numbers: item.number != null ? [item.number] : [], texts: item.text ? [item.text] : [], to: item.to }],
223 count: 1,
224 });
225 }
226 return groups;
227}
228
229// --- Needs you --------------------------------------------------------------
230
231export type NeedKind = "limit" | "deploy" | "invitation" | "stalled" | "conflict" | "review" | "stuck" | "runner" | "checks" | "ready";
232
233/** Something waiting on the viewer, with where to act on it. */
234export type Need = {
235 key: string;
236 kind: NeedKind;
237 title: string;
238 detail: string;
239 to: string;
240 action: string;
241 /** Epoch ms: when it started waiting. */
242 at: number;
243 where: string | null;
244};
245
246const NEED_RANK: Record<NeedKind, number> = {
247 limit: 0,
248 deploy: 1,
249 invitation: 1.5,
250 conflict: 2,
251 stalled: 3,
252 stuck: 4,
253 runner: 4,
254 review: 5,
255 checks: 6,
256 ready: 7,
257};
258
259/** Most urgent first: by kind, then what has waited longest. One of each key. */
260export function rankNeeds(needs: Need[]): Need[] {
261 const seen = new Set<string>();
262 return [...needs]
263 .sort((a, b) => NEED_RANK[a.kind] - NEED_RANK[b.kind] || a.at - b.at)
264 .filter((need) => (seen.has(need.key) ? false : (seen.add(need.key), true)));
265}
266
267/** How long something has waited, from minutes: "45 min", "17 h", "2 d". */
268export function waitedFor(minutes: number): string {
269 const whole = Math.max(0, Math.floor(minutes));
270 if (whole < 60) return `${whole} min`;
271 if (whole < 24 * 60) return `${Math.floor(whole / 60)} h`;
272 return `${Math.floor(whole / (24 * 60))} d`;
273}
274
275/** Whether a run has gone quiet: running with no new step for `quiet`. */
276export function stuckMinutes(run: Pick<AgentRun, "status" | "updatedAt">, now: number, quiet = 10 * MINUTE): number | null {
277 if (run.status !== "running") return null;
278 const idle = now - Date.parse(run.updatedAt);
279 return idle >= quiet ? Math.floor(idle / MINUTE) : null;
280}
281
282// --- Digest -----------------------------------------------------------------
283
284export type DigestCounts = {
285 landed: number;
286 reviews: number;
287 opened: number;
288 deploys: number;
289 failedDeploys: number;
290 /** The longest an agent has been quiet, in minutes; null when none is. */
291 stuck: number | null;
292};
293
294export type DigestPart = { text: string; tone: "fg" | "warn" | "danger" | "accent"; anchor: string };
295
296const count = (n: number, one: string, many: string) => `${n} ${n === 1 ? one : many}`;
297
298/** What moved since the viewer was last here, as the pieces of a sentence. */
299export function digestParts(c: DigestCounts): DigestPart[] {
300 const parts: DigestPart[] = [];
301 if (c.landed > 0) parts.push({ text: `${count(c.landed, "change", "changes")} landed`, tone: "accent", anchor: "activity" });
302 if (c.reviews > 0) parts.push({ text: `${count(c.reviews, "pull request needs", "pull requests need")} your review`, tone: "warn", anchor: "your-pulls" });
303 if (c.stuck != null) parts.push({ text: `an agent has been quiet for ${waitedFor(c.stuck)}`, tone: "warn", anchor: "live" });
304 if (c.failedDeploys > 0) parts.push({ text: `${count(c.failedDeploys, "deploy", "deploys")} failed`, tone: "danger", anchor: "needs-you" });
305 if (c.deploys > 0) parts.push({ text: `${count(c.deploys, "deploy", "deploys")} went out`, tone: "fg", anchor: "projects" });
306 if (c.opened > 0) parts.push({ text: `${count(c.opened, "issue was", "issues were")} opened`, tone: "fg", anchor: "activity" });
307 return parts;
308}
309
310// --- Pulse ------------------------------------------------------------------
311
312/** Counts per day for the `days` days ending today (UTC), oldest first. */
313export function dailyBuckets(points: { at: number; value?: number }[], days: number, now: number): number[] {
314 const end = Math.floor(now / DAY);
315 const buckets = new Array<number>(days).fill(0);
316 for (const point of points) {
317 const index = days - 1 - (end - Math.floor(point.at / DAY));
318 if (index >= 0 && index < days) buckets[index] += point.value ?? 1;
319 }
320 return buckets;
321}
322
323export function median(values: number[]): number | null {
324 if (values.length === 0) return null;
325 const sorted = [...values].sort((a, b) => a - b);
326 const middle = Math.floor(sorted.length / 2);
327 return sorted.length % 2 ? sorted[middle] : (sorted[middle - 1] + sorted[middle]) / 2;
328}
329
330/**
331 * The share of pull requests whose first run of checks passed, from the
332 * `checks.completed` events of one or more projects. Null with none.
333 */
334export function firstPassRate(events: { repo: string; number: number; at: number; passed: boolean }[]): { rate: number | null; of: number } {
335 const first = new Map<string, { at: number; passed: boolean }>();
336 for (const event of events) {
337 const key = `${event.repo}#${event.number}`;
338 const seen = first.get(key);
339 if (!seen || event.at < seen.at) first.set(key, { at: event.at, passed: event.passed });
340 }
341 if (first.size === 0) return { rate: null, of: 0 };
342 const passed = [...first.values()].filter((run) => run.passed).length;
343 return { rate: passed / first.size, of: first.size };
344}
345
346/** The share of check runs that passed. Null with none. */
347export function passRate(results: boolean[]): number | null {
348 if (results.length === 0) return null;
349 return results.filter(Boolean).length / results.length;
350}
351
352/** How long from an issue being opened to its change landing, for each that did, in ms. */
353export function issueToMerge(
354 opened: { repo: string; number: number; at: number }[],
355 merged: { repo: string; issue: number | null; at: number }[],
356): number[] {
357 const openedAt = new Map(opened.map((o) => [`${o.repo}#${o.number}`, o.at]));
358 const spans: number[] = [];
359 for (const m of merged) {
360 if (m.issue == null) continue;
361 const start = openedAt.get(`${m.repo}#${m.issue}`);
362 if (start != null && m.at >= start) spans.push(m.at - start);
363 }
364 return spans;
365}
366
367/** Hours agents spent at work since `since`, counting runs still going up to `now`. */
368export function agentHours(runs: Pick<AgentRun, "kind" | "startedAt" | "finishedAt">[], since: number, now: number): number {
369 let ms = 0;
370 for (const run of runs) {
371 if (!run.startedAt || run.kind === "checks" || run.kind === "queue" || run.kind === "mergecheck") continue;
372 const start = Math.max(Date.parse(run.startedAt), since);
373 const end = run.finishedAt ? Date.parse(run.finishedAt) : now;
374 if (end > start) ms += end - start;
375 }
376 return ms / HOUR;
377}
378
379/** "3h", "2d 4h", "40m": a span in the largest units that read well. */
380export function formatSpan(ms: number | null): string {
381 if (ms == null) return "—";
382 if (ms < HOUR) return `${Math.max(1, Math.round(ms / MINUTE))}m`;
383 if (ms < DAY) return `${Math.round(ms / HOUR)}h`;
384 const days = Math.floor(ms / DAY);
385 const hours = Math.round((ms % DAY) / HOUR);
386 return hours ? `${days}d ${hours}h` : `${days}d`;
387}
388
389/**
390 * Points for a sparkline `width` by `height`: the values spread across the
391 * width, scaled so the largest touches the top and zero sits on the
392 * bottom, with `pad` kept clear for the line's width.
393 */
394export function sparkPoints(values: number[], width: number, height: number, pad = 2): [number, number][] {
395 if (values.length === 0) return [];
396 const max = Math.max(...values, 0);
397 const step = values.length > 1 ? (width - pad * 2) / (values.length - 1) : 0;
398 return values.map((value, index) => {
399 const x = values.length > 1 ? pad + index * step : width / 2;
400 const y = max > 0 ? height - pad - (Math.max(0, value) / max) * (height - pad * 2) : height - pad;
401 return [Math.round(x * 100) / 100, Math.round(y * 100) / 100];
402 });
403}
404
405// --- A project's pipeline ---------------------------------------------------
406
407export type PipelineStage = "working" | "checking" | "reviewing" | "queue" | "landed";
408
409export const PIPELINE: { stage: PipelineStage; label: string }[] = [
410 { stage: "working", label: "Working" },
411 { stage: "checking", label: "Checking" },
412 { stage: "reviewing", label: "Reviewing" },
413 { stage: "queue", label: "Queue" },
414 { stage: "landed", label: "Landed" },
415];
416
417/**
418 * Where a pull request stands on its way to landing, from what a list of
419 * pull requests says about it, the run at work on it, the merge queue, and
420 * for one g1t sees through, its lifecycle (waiting on its checks).
421 */
422export function pipelineStage(
423 pull: Pick<Pull, "status" | "checkStatus" | "number">,
424 run: Pick<AgentRun, "kind"> | undefined,
425 queued: Set<number>,
426 lifecycle?: { stage: string } | null,
427): PipelineStage {
428 if (pull.status === "merged") return "landed";
429 if (queued.has(pull.number)) return "queue";
430 if (run) {
431 if (run.kind === "checks") return "checking";
432 if (run.kind === "review") return "reviewing";
433 if (run.kind === "queue") return "queue";
434 return "working";
435 }
436 if (pull.status === "draft") return "working";
437 if (lifecycle?.stage === "checking") return "checking";
438 if (pull.checkStatus === "queued" || pull.checkStatus === "running") return "checking";
439 return "reviewing";
440}
441
442/** The numbers of the pull requests waiting or being tested in a merge queue. */
443export function queuedNumbers(entries: Pick<QueueEntry, "number" | "state">[]): Set<number> {
444 return new Set(entries.filter((e) => e.state === "waiting" || e.state === "testing" || e.state === "passed").map((e) => e.number));
445}
446
447/** Open issues by how long they have been open. */
448export function ageBuckets(created: string[], now: number): { label: string; count: number }[] {
449 const buckets = [
450 { label: "Under a day", max: DAY, count: 0 },
451 { label: "Under a week", max: 7 * DAY, count: 0 },
452 { label: "Under a month", max: 30 * DAY, count: 0 },
453 { label: "Older", max: Number.POSITIVE_INFINITY, count: 0 },
454 ];
455 for (const at of created) {
456 const age = now - Date.parse(at);
457 const bucket = buckets.find((b) => age < b.max) ?? buckets[buckets.length - 1];
458 bucket.count += 1;
459 }
460 return buckets.map(({ label, count }) => ({ label, count }));
461}
462
463export const TIME = { MINUTE, HOUR, DAY };