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