Skip to content
501 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/**
216 * A workspace acting as itself: a build or deployment run under the
217 * workspace's own identity. That is g1t working for the workspace, not a
218 * person, so it is never named after the workspace, as home.server.ts
219 * names it too.
220 */
221const isWorkspaceId = (actor: string) => actor.startsWith("wsp_");
222
223/** The account ids among `actors` to look up by name, once each. */
224export function actorIds(actors: (string | null)[]): string[] {
225 return [
226 ...new Set(
227 actors.filter((actor): actor is string => actor != null && isAccountId(actor) && !(actor in G1T_ACTORS) && !isWorkspaceId(actor)),
228 ),
229 ];
230}
231
232/**
233 * An actor by name: an account id becomes its username, from `names` (the
234 * identity service's lookup); a workspace is g1t. An id it does not know is
235 * an account since deleted; with no lookup at all, the actor is only
236 * "someone".
237 */
238export function nameActor(actor: string | null, names: Record<string, string> | null): string | null {
239 if (actor == null || !isAccountId(actor)) return actor;
240 if (isWorkspaceId(actor)) return "g1t";
241 return G1T_ACTORS[actor] ?? names?.[actor] ?? (names ? DELETED_USER : "someone");
242}
243
244/** Several things one actor did in one project in a short while, read as one line. */
245export type ActivityGroup = {
246 id: string;
247 actor: string | null;
248 repo: RepoPath;
249 /** Newest and oldest, epoch ms. */
250 at: number;
251 from: number;
252 /** Each kind of thing done, in the order first seen, with what it was done to. */
253 parts: { verb: Verb; numbers: number[]; texts: string[]; to?: string }[];
254 count: number;
255};
256
257const sameRepo = (a: RepoPath, b: RepoPath) =>
258 a.namespace.toLowerCase() === b.namespace.toLowerCase() && a.name.toLowerCase() === b.name.toLowerCase();
259
260/**
261 * Groups items, newest first, so that a run of things one actor did in one
262 * project within `window` of the run's newest reads as one line.
263 */
264export function groupActivity(items: ActivityItem[], window = 45 * MINUTE): ActivityGroup[] {
265 const sorted = [...items].sort((a, b) => b.at - a.at);
266 const groups: ActivityGroup[] = [];
267 for (const item of sorted) {
268 const last = groups[groups.length - 1];
269 if (last && last.actor === item.actor && sameRepo(last.repo, item.repo) && last.at - item.at <= window) {
270 let part = last.parts.find((p) => p.verb === item.verb);
271 if (!part) {
272 part = { verb: item.verb, numbers: [], texts: [], to: item.to };
273 last.parts.push(part);
274 }
275 if (item.number != null && !part.numbers.includes(item.number)) part.numbers.push(item.number);
276 if (item.text && !part.texts.includes(item.text)) part.texts.push(item.text);
277 last.from = item.at;
278 last.count += 1;
279 continue;
280 }
281 groups.push({
282 id: item.id,
283 actor: item.actor,
284 repo: item.repo,
285 at: item.at,
286 from: item.at,
287 parts: [{ verb: item.verb, numbers: item.number != null ? [item.number] : [], texts: item.text ? [item.text] : [], to: item.to }],
288 count: 1,
289 });
290 }
291 return groups;
292}
293
294// --- Needs you --------------------------------------------------------------
295
296export type NeedKind = "deploy" | "invitation" | "stalled" | "conflict" | "review" | "stuck" | "runner" | "checks" | "ready";
297
298/** Something waiting on the viewer, with where to act on it. */
299export type Need = {
300 key: string;
301 kind: NeedKind;
302 title: string;
303 detail: string;
304 to: string;
305 action: string;
306 /** Epoch ms: when it started waiting. */
307 at: number;
308 where: string | null;
309};
310
311const NEED_RANK: Record<NeedKind, number> = {
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<RunLike, "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// --- Pulse ------------------------------------------------------------------
347
348/** Counts per day for the `days` days ending today (UTC), oldest first. */
349export function dailyBuckets(points: { at: number; value?: number }[], days: number, now: number): number[] {
350 const end = Math.floor(now / DAY);
351 const buckets = new Array<number>(days).fill(0);
352 for (const point of points) {
353 const index = days - 1 - (end - Math.floor(point.at / DAY));
354 if (index >= 0 && index < days) buckets[index] += point.value ?? 1;
355 }
356 return buckets;
357}
358
359export function median(values: number[]): number | null {
360 if (values.length === 0) return null;
361 const sorted = [...values].sort((a, b) => a - b);
362 const middle = Math.floor(sorted.length / 2);
363 return sorted.length % 2 ? sorted[middle] : (sorted[middle - 1] + sorted[middle]) / 2;
364}
365
366/**
367 * The share of pull requests whose first run of checks passed, from the
368 * `checks.completed` events of one or more projects. Null with none.
369 */
370export function firstPassRate(events: { repo: string; number: number; at: number; passed: boolean }[]): { rate: number | null; of: number } {
371 const first = new Map<string, { at: number; passed: boolean }>();
372 for (const event of events) {
373 const key = `${event.repo}#${event.number}`;
374 const seen = first.get(key);
375 if (!seen || event.at < seen.at) first.set(key, { at: event.at, passed: event.passed });
376 }
377 if (first.size === 0) return { rate: null, of: 0 };
378 const passed = [...first.values()].filter((run) => run.passed).length;
379 return { rate: passed / first.size, of: first.size };
380}
381
382/** The share of check runs that passed. Null with none. */
383export function passRate(results: boolean[]): number | null {
384 if (results.length === 0) return null;
385 return results.filter(Boolean).length / results.length;
386}
387
388/**
389 * A project's health from its recent workflow runs, for one that ships
390 * without pull requests (whose checks are what `checks.completed` counts).
391 * Only runs that finished and passed or failed count: cancelled and skipped
392 * say nothing about the code. A run passed on the first try when its first
393 * attempt is the one that passed.
394 */
395export function runHealth(runs: { attempt: number; status: string; conclusion: string | null }[]): { passRate: number | null; firstPass: { rate: number | null; of: number }; checkRuns: number } {
396 const decided = runs.filter((run) => run.status === "completed" && (run.conclusion === "success" || run.conclusion === "failure"));
397 const passed = decided.map((run) => run.conclusion === "success");
398 const first = decided.filter((run) => run.conclusion === "success" && run.attempt <= 1).length;
399 return { passRate: passRate(passed), firstPass: { rate: decided.length ? first / decided.length : null, of: decided.length }, checkRuns: decided.length };
400}
401
402/** How long from an issue being opened to its change landing, for each that did, in ms. */
403export function issueToMerge(
404 opened: { repo: string; number: number; at: number }[],
405 merged: { repo: string; issue: number | null; at: number }[],
406): number[] {
407 const openedAt = new Map(opened.map((o) => [`${o.repo}#${o.number}`, o.at]));
408 const spans: number[] = [];
409 for (const m of merged) {
410 if (m.issue == null) continue;
411 const start = openedAt.get(`${m.repo}#${m.issue}`);
412 if (start != null && m.at >= start) spans.push(m.at - start);
413 }
414 return spans;
415}
416
417/** "3h", "2d 4h", "40m": a span in the largest units that read well. */
418export function formatSpan(ms: number | null): string {
419 if (ms == null) return "—";
420 if (ms < HOUR) return `${Math.max(1, Math.round(ms / MINUTE))}m`;
421 if (ms < DAY) return `${Math.round(ms / HOUR)}h`;
422 const days = Math.floor(ms / DAY);
423 const hours = Math.round((ms % DAY) / HOUR);
424 return hours ? `${days}d ${hours}h` : `${days}d`;
425}
426
427/**
428 * Points for a sparkline `width` by `height`: the values spread across the
429 * width, scaled so the largest touches the top and zero sits on the
430 * bottom, with `pad` kept clear for the line's width.
431 */
432export function sparkPoints(values: number[], width: number, height: number, pad = 2): [number, number][] {
433 if (values.length === 0) return [];
434 const max = Math.max(...values, 0);
435 const step = values.length > 1 ? (width - pad * 2) / (values.length - 1) : 0;
436 return values.map((value, index) => {
437 const x = values.length > 1 ? pad + index * step : width / 2;
438 const y = max > 0 ? height - pad - (Math.max(0, value) / max) * (height - pad * 2) : height - pad;
439 return [Math.round(x * 100) / 100, Math.round(y * 100) / 100];
440 });
441}
442
443// --- A project's pipeline ---------------------------------------------------
444
445export type PipelineStage = "working" | "checking" | "reviewing" | "queue" | "landed";
446
447export const PIPELINE: { stage: PipelineStage; label: string }[] = [
448 { stage: "working", label: "Working" },
449 { stage: "checking", label: "Checking" },
450 { stage: "reviewing", label: "Reviewing" },
451 { stage: "queue", label: "Queue" },
452 { stage: "landed", label: "Landed" },
453];
454
455/**
456 * Where a pull request stands on its way to landing, from what a list of
457 * pull requests says about it, the run at work on it, the merge queue, and
458 * for one g1t sees through, its lifecycle (waiting on its checks).
459 */
460export function pipelineStage(
461 pull: Pick<Pull, "status" | "checkStatus" | "number">,
462 run: Pick<RunLike, "kind"> | undefined,
463 queued: Set<number>,
464 lifecycle?: { stage: string } | null,
465): PipelineStage {
466 if (pull.status === "merged") return "landed";
467 if (queued.has(pull.number)) return "queue";
468 if (run) {
469 if (run.kind === "checks") return "checking";
470 if (run.kind === "review") return "reviewing";
471 if (run.kind === "queue") return "queue";
472 return "working";
473 }
474 if (pull.status === "draft") return "working";
475 if (lifecycle?.stage === "checking") return "checking";
476 if (pull.checkStatus === "queued" || pull.checkStatus === "running") return "checking";
477 return "reviewing";
478}
479
480/** The numbers of the pull requests waiting or being tested in a merge queue. */
481export function queuedNumbers(entries: Pick<QueueEntry, "number" | "state">[]): Set<number> {
482 return new Set(entries.filter((e) => e.state === "waiting" || e.state === "testing" || e.state === "passed").map((e) => e.number));
483}
484
485/** Open issues by how long they have been open. */
486export function ageBuckets(created: string[], now: number): { label: string; count: number }[] {
487 const buckets = [
488 { label: "Under a day", max: DAY, count: 0 },
489 { label: "Under a week", max: 7 * DAY, count: 0 },
490 { label: "Under a month", max: 30 * DAY, count: 0 },
491 { label: "Older", max: Number.POSITIVE_INFINITY, count: 0 },
492 ];
493 for (const at of created) {
494 const age = now - Date.parse(at);
495 const bucket = buckets.find((b) => age < b.max) ?? buckets[buckets.length - 1];
496 bucket.count += 1;
497 }
498 return buckets.map(({ label, count }) => ({ label, count }));
499}
500
501export const TIME = { MINUTE, HOUR, DAY };