Skip to content

Where people and agents ship software together. The open-source git platform for the whole job: issues, agents, checks and deploys to the edge.

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