Skip to content
527 linesCodeBlameRaw
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 | "pushed"
108 | "learned";
109
110/**
111 * The event types `eventItem` makes a line of. Ask the log for these only:
112 * a repository's newest events are mostly ones no line is made of (session
113 * steps, queue and merge-check changes), which would otherwise fill the
114 * page and leave nothing to show.
115 */
116export const FEED_EVENT_TYPES = [
117 "pull.merged",
118 "issue.opened",
119 "issue.closed",
120 "pull.opened",
121 "pull.ready",
122 "checks.completed",
123 "review.completed",
124 "comment.created",
125 "agent.asked",
126 "deployment_status.created",
127] as const satisfies readonly G1tEvent["type"][];
128
129/** With pushes to the default branch too, for one project's feed. */
130export const PROJECT_FEED_EVENT_TYPES = [...FEED_EVENT_TYPES, "git.push"] as const satisfies readonly G1tEvent["type"][];
131
132/** One thing that moved, as the feed shows it. */
133export type ActivityItem = {
134 id: string;
135 /** Epoch ms. */
136 at: number;
137 repo: RepoPath;
138 actor: string | null;
139 verb: Verb;
140 /** The issue or pull request it was about. */
141 number: number | null;
142 /** For a memory: what was learned. For a deploy: where. */
143 text?: string;
144 /** Where the line links, when it is not an issue or pull request. */
145 to?: string;
146};
147
148/** An event from the log as a feed item, or null for those not worth a line. */
149export function eventItem(event: G1tEvent, repo: RepoPath): ActivityItem | null {
150 const base = { id: event.id, at: Date.parse(event.time), repo, actor: event.actor };
151 switch (event.type) {
152 case "pull.merged":
153 return { ...base, verb: "landed", number: event.data.number };
154 case "issue.opened":
155 return { ...base, verb: "opened_issue", number: event.data.number };
156 case "issue.closed":
157 return event.data.resolvedBy != null ? null : { ...base, verb: "closed_issue", number: event.data.number };
158 case "pull.opened":
159 return { ...base, actor: event.data.agent || event.actor, verb: "started", number: event.data.number };
160 case "pull.ready":
161 return { ...base, verb: "ready", number: event.data.number };
162 case "checks.completed":
163 return { ...base, actor: null, verb: event.data.status === "passed" ? "checks_passed" : "checks_failed", number: event.data.number };
164 case "review.completed":
165 if (!event.data.verdict) return null;
166 return { ...base, actor: "g1t", verb: event.data.verdict === "approve" ? "approved" : "changes_requested", number: event.data.number };
167 case "comment.created":
168 if (event.data.verdict) {
169 return { ...base, verb: event.data.verdict === "approve" ? "approved" : "changes_requested", number: event.data.number };
170 }
171 return { ...base, verb: "commented", number: event.data.number };
172 case "agent.asked":
173 return { ...base, verb: "asked", number: event.data.number };
174 case "deployment_status.created": {
175 // Production, once it is up or has failed: g1t.page builds, g1t
176 // Actions jobs and deployments reported through the API alike.
177 const { deployment, deploymentStatus } = event.data;
178 if (!deployment.production_environment) return null;
179 const state = deploymentStatus.state;
180 if (state !== "success" && state !== "failure" && state !== "error") return null;
181 return {
182 ...base,
183 verb: state === "success" ? "deployed" : "deploy_failed",
184 number: null,
185 to: `/${repo.namespace}/${repo.name}/deployments/${deployment.id}`,
186 };
187 }
188 default:
189 return null;
190 }
191}
192
193/**
194 * A push to the default branch as a feed line, or null for any other push
195 * and for one that only landed a pull request (`merged`: the commits pull
196 * requests' merges made), which already has its own line.
197 */
198export function pushItem(event: G1tEvent, repo: RepoPath, merged: ReadonlySet<string>): ActivityItem | null {
199 if (event.type !== "git.push" || !event.data.defaultBranch || !event.data.ref.startsWith("refs/heads/")) return null;
200 const after = event.data.after;
201 if (!after || /^0+$/.test(after) || merged.has(after)) return null;
202 return {
203 id: event.id,
204 at: Date.parse(event.time),
205 repo,
206 actor: event.actor,
207 verb: "pushed",
208 number: null,
209 text: after.slice(0, 7),
210 to: `/${repo.namespace}/${repo.name}/commit/${after}`,
211 };
212}
213
214/** One project's events as its feed: every line `eventItem` makes, and its people's pushes. */
215export function projectFeed(events: G1tEvent[], repo: RepoPath): ActivityItem[] {
216 const merged = new Set(events.flatMap((event) => (event.type === "pull.merged" ? [event.data.commit] : [])));
217 return events.flatMap((event) => eventItem(event, repo) ?? pushItem(event, repo, merged) ?? []);
218}
219
220/** Accounts that act for g1t itself, named in the log by fixed ids. */
221const G1T_ACTORS: Record<string, string> = { usr_g1t_agent: "g1t", g1t_policy: "g1t" };
222/** Who an account the lookup no longer knows was. */
223export const DELETED_USER = "a deleted user";
224
225/** An account id rather than a name: usernames never hold an underscore. */
226const isAccountId = (actor: string) => actor.includes("_");
227
228/** The account ids among `actors` to look up by name, once each. */
229export function actorIds(actors: (string | null)[]): string[] {
230 return [...new Set(actors.filter((actor): actor is string => actor != null && isAccountId(actor) && !(actor in G1T_ACTORS)))];
231}
232
233/**
234 * An actor by name: an account id becomes its username, from `names` (the
235 * identity service's lookup). An id it does not know is an account since
236 * deleted; with no lookup at all, the actor is only "someone".
237 */
238export function nameActor(actor: string | null, names: Record<string, string> | null): string | null {
239 if (actor == null || !isAccountId(actor)) return actor;
240 return G1T_ACTORS[actor] ?? names?.[actor] ?? (names ? DELETED_USER : "someone");
241}
242
243/** Several things one actor did in one project in a short while, read as one line. */
244export type ActivityGroup = {
245 id: string;
246 actor: string | null;
247 repo: RepoPath;
248 /** Newest and oldest, epoch ms. */
249 at: number;
250 from: number;
251 /** Each kind of thing done, in the order first seen, with what it was done to. */
252 parts: { verb: Verb; numbers: number[]; texts: string[]; to?: string }[];
253 count: number;
254};
255
256const sameRepo = (a: RepoPath, b: RepoPath) =>
257 a.namespace.toLowerCase() === b.namespace.toLowerCase() && a.name.toLowerCase() === b.name.toLowerCase();
258
259/**
260 * Groups items, newest first, so that a run of things one actor did in one
261 * project within `window` of the run's newest reads as one line.
262 */
263export function groupActivity(items: ActivityItem[], window = 45 * MINUTE): ActivityGroup[] {
264 const sorted = [...items].sort((a, b) => b.at - a.at);
265 const groups: ActivityGroup[] = [];
266 for (const item of sorted) {
267 const last = groups[groups.length - 1];
268 if (last && last.actor === item.actor && sameRepo(last.repo, item.repo) && last.at - item.at <= window) {
269 let part = last.parts.find((p) => p.verb === item.verb);
270 if (!part) {
271 part = { verb: item.verb, numbers: [], texts: [], to: item.to };
272 last.parts.push(part);
273 }
274 if (item.number != null && !part.numbers.includes(item.number)) part.numbers.push(item.number);
275 if (item.text && !part.texts.includes(item.text)) part.texts.push(item.text);
276 last.from = item.at;
277 last.count += 1;
278 continue;
279 }
280 groups.push({
281 id: item.id,
282 actor: item.actor,
283 repo: item.repo,
284 at: item.at,
285 from: item.at,
286 parts: [{ verb: item.verb, numbers: item.number != null ? [item.number] : [], texts: item.text ? [item.text] : [], to: item.to }],
287 count: 1,
288 });
289 }
290 return groups;
291}
292
293// --- Needs you --------------------------------------------------------------
294
295export type NeedKind = "limit" | "deploy" | "invitation" | "stalled" | "conflict" | "review" | "stuck" | "runner" | "checks" | "ready";
296
297/** Something waiting on the viewer, with where to act on it. */
298export type Need = {
299 key: string;
300 kind: NeedKind;
301 title: string;
302 detail: string;
303 to: string;
304 action: string;
305 /** Epoch ms: when it started waiting. */
306 at: number;
307 where: string | null;
308};
309
310const NEED_RANK: Record<NeedKind, number> = {
311 limit: 0,
312 deploy: 1,
313 invitation: 1.5,
314 conflict: 2,
315 stalled: 3,
316 stuck: 4,
317 runner: 4,
318 review: 5,
319 checks: 6,
320 ready: 7,
321};
322
323/** Most urgent first: by kind, then what has waited longest. One of each key. */
324export function rankNeeds(needs: Need[]): Need[] {
325 const seen = new Set<string>();
326 return [...needs]
327 .sort((a, b) => NEED_RANK[a.kind] - NEED_RANK[b.kind] || a.at - b.at)
328 .filter((need) => (seen.has(need.key) ? false : (seen.add(need.key), true)));
329}
330
331/** How long something has waited, from minutes: "45 min", "17 h", "2 d". */
332export function waitedFor(minutes: number): string {
333 const whole = Math.max(0, Math.floor(minutes));
334 if (whole < 60) return `${whole} min`;
335 if (whole < 24 * 60) return `${Math.floor(whole / 60)} h`;
336 return `${Math.floor(whole / (24 * 60))} d`;
337}
338
339/** Whether a run has gone quiet: running with no new step for `quiet`. */
340export function stuckMinutes(run: Pick<AgentRun, "status" | "updatedAt">, now: number, quiet = 10 * MINUTE): number | null {
341 if (run.status !== "running") return null;
342 const idle = now - Date.parse(run.updatedAt);
343 return idle >= quiet ? Math.floor(idle / MINUTE) : null;
344}
345
346// --- Digest -----------------------------------------------------------------
347
348export type DigestCounts = {
349 landed: number;
350 reviews: number;
351 opened: number;
352 deploys: number;
353 failedDeploys: number;
354 /** The longest an agent has been quiet, in minutes; null when none is. */
355 stuck: number | null;
356};
357
358export type DigestPart = { text: string; tone: "fg" | "warn" | "danger" | "accent"; anchor: string };
359
360const count = (n: number, one: string, many: string) => `${n} ${n === 1 ? one : many}`;
361
362/** What moved since the viewer was last here, as the pieces of a sentence. */
363export function digestParts(c: DigestCounts): DigestPart[] {
364 const parts: DigestPart[] = [];
365 if (c.landed > 0) parts.push({ text: `${count(c.landed, "change", "changes")} landed`, tone: "accent", anchor: "activity" });
366 if (c.reviews > 0) parts.push({ text: `${count(c.reviews, "pull request needs", "pull requests need")} your review`, tone: "warn", anchor: "your-pulls" });
367 if (c.stuck != null) parts.push({ text: `an agent has been quiet for ${waitedFor(c.stuck)}`, tone: "warn", anchor: "live" });
368 if (c.failedDeploys > 0) parts.push({ text: `${count(c.failedDeploys, "deploy", "deploys")} failed`, tone: "danger", anchor: "needs-you" });
369 if (c.deploys > 0) parts.push({ text: `${count(c.deploys, "deploy", "deploys")} went out`, tone: "fg", anchor: "projects" });
370 if (c.opened > 0) parts.push({ text: `${count(c.opened, "issue was", "issues were")} opened`, tone: "fg", anchor: "activity" });
371 return parts;
372}
373
374// --- Pulse ------------------------------------------------------------------
375
376/** Counts per day for the `days` days ending today (UTC), oldest first. */
377export function dailyBuckets(points: { at: number; value?: number }[], days: number, now: number): number[] {
378 const end = Math.floor(now / DAY);
379 const buckets = new Array<number>(days).fill(0);
380 for (const point of points) {
381 const index = days - 1 - (end - Math.floor(point.at / DAY));
382 if (index >= 0 && index < days) buckets[index] += point.value ?? 1;
383 }
384 return buckets;
385}
386
387export function median(values: number[]): number | null {
388 if (values.length === 0) return null;
389 const sorted = [...values].sort((a, b) => a - b);
390 const middle = Math.floor(sorted.length / 2);
391 return sorted.length % 2 ? sorted[middle] : (sorted[middle - 1] + sorted[middle]) / 2;
392}
393
394/**
395 * The share of pull requests whose first run of checks passed, from the
396 * `checks.completed` events of one or more projects. Null with none.
397 */
398export function firstPassRate(events: { repo: string; number: number; at: number; passed: boolean }[]): { rate: number | null; of: number } {
399 const first = new Map<string, { at: number; passed: boolean }>();
400 for (const event of events) {
401 const key = `${event.repo}#${event.number}`;
402 const seen = first.get(key);
403 if (!seen || event.at < seen.at) first.set(key, { at: event.at, passed: event.passed });
404 }
405 if (first.size === 0) return { rate: null, of: 0 };
406 const passed = [...first.values()].filter((run) => run.passed).length;
407 return { rate: passed / first.size, of: first.size };
408}
409
410/** The share of check runs that passed. Null with none. */
411export function passRate(results: boolean[]): number | null {
412 if (results.length === 0) return null;
413 return results.filter(Boolean).length / results.length;
414}
415
416/** How long from an issue being opened to its change landing, for each that did, in ms. */
417export function issueToMerge(
418 opened: { repo: string; number: number; at: number }[],
419 merged: { repo: string; issue: number | null; at: number }[],
420): number[] {
421 const openedAt = new Map(opened.map((o) => [`${o.repo}#${o.number}`, o.at]));
422 const spans: number[] = [];
423 for (const m of merged) {
424 if (m.issue == null) continue;
425 const start = openedAt.get(`${m.repo}#${m.issue}`);
426 if (start != null && m.at >= start) spans.push(m.at - start);
427 }
428 return spans;
429}
430
431/** Hours agents spent at work since `since`, counting runs still going up to `now`. */
432export function agentHours(runs: Pick<AgentRun, "kind" | "startedAt" | "finishedAt">[], since: number, now: number): number {
433 let ms = 0;
434 for (const run of runs) {
435 if (!run.startedAt || run.kind === "checks" || run.kind === "queue" || run.kind === "mergecheck") continue;
436 const start = Math.max(Date.parse(run.startedAt), since);
437 const end = run.finishedAt ? Date.parse(run.finishedAt) : now;
438 if (end > start) ms += end - start;
439 }
440 return ms / HOUR;
441}
442
443/** "3h", "2d 4h", "40m": a span in the largest units that read well. */
444export function formatSpan(ms: number | null): string {
445 if (ms == null) return "—";
446 if (ms < HOUR) return `${Math.max(1, Math.round(ms / MINUTE))}m`;
447 if (ms < DAY) return `${Math.round(ms / HOUR)}h`;
448 const days = Math.floor(ms / DAY);
449 const hours = Math.round((ms % DAY) / HOUR);
450 return hours ? `${days}d ${hours}h` : `${days}d`;
451}
452
453/**
454 * Points for a sparkline `width` by `height`: the values spread across the
455 * width, scaled so the largest touches the top and zero sits on the
456 * bottom, with `pad` kept clear for the line's width.
457 */
458export function sparkPoints(values: number[], width: number, height: number, pad = 2): [number, number][] {
459 if (values.length === 0) return [];
460 const max = Math.max(...values, 0);
461 const step = values.length > 1 ? (width - pad * 2) / (values.length - 1) : 0;
462 return values.map((value, index) => {
463 const x = values.length > 1 ? pad + index * step : width / 2;
464 const y = max > 0 ? height - pad - (Math.max(0, value) / max) * (height - pad * 2) : height - pad;
465 return [Math.round(x * 100) / 100, Math.round(y * 100) / 100];
466 });
467}
468
469// --- A project's pipeline ---------------------------------------------------
470
471export type PipelineStage = "working" | "checking" | "reviewing" | "queue" | "landed";
472
473export const PIPELINE: { stage: PipelineStage; label: string }[] = [
474 { stage: "working", label: "Working" },
475 { stage: "checking", label: "Checking" },
476 { stage: "reviewing", label: "Reviewing" },
477 { stage: "queue", label: "Queue" },
478 { stage: "landed", label: "Landed" },
479];
480
481/**
482 * Where a pull request stands on its way to landing, from what a list of
483 * pull requests says about it, the run at work on it, the merge queue, and
484 * for one g1t sees through, its lifecycle (waiting on its checks).
485 */
486export function pipelineStage(
487 pull: Pick<Pull, "status" | "checkStatus" | "number">,
488 run: Pick<AgentRun, "kind"> | undefined,
489 queued: Set<number>,
490 lifecycle?: { stage: string } | null,
491): PipelineStage {
492 if (pull.status === "merged") return "landed";
493 if (queued.has(pull.number)) return "queue";
494 if (run) {
495 if (run.kind === "checks") return "checking";
496 if (run.kind === "review") return "reviewing";
497 if (run.kind === "queue") return "queue";
498 return "working";
499 }
500 if (pull.status === "draft") return "working";
501 if (lifecycle?.stage === "checking") return "checking";
502 if (pull.checkStatus === "queued" || pull.checkStatus === "running") return "checking";
503 return "reviewing";
504}
505
506/** The numbers of the pull requests waiting or being tested in a merge queue. */
507export function queuedNumbers(entries: Pick<QueueEntry, "number" | "state">[]): Set<number> {
508 return new Set(entries.filter((e) => e.state === "waiting" || e.state === "testing" || e.state === "passed").map((e) => e.number));
509}
510
511/** Open issues by how long they have been open. */
512export function ageBuckets(created: string[], now: number): { label: string; count: number }[] {
513 const buckets = [
514 { label: "Under a day", max: DAY, count: 0 },
515 { label: "Under a week", max: 7 * DAY, count: 0 },
516 { label: "Under a month", max: 30 * DAY, count: 0 },
517 { label: "Older", max: Number.POSITIVE_INFINITY, count: 0 },
518 ];
519 for (const at of created) {
520 const age = now - Date.parse(at);
521 const bucket = buckets.find((b) => age < b.max) ?? buckets[buckets.length - 1];
522 bucket.count += 1;
523 }
524 return buckets.map(({ label, count }) => ({ label, count }));
525}
526
527export const TIME = { MINUTE, HOUR, DAY };